diff --git a/.agents/skills/launch/SKILL.md b/.agents/skills/launch/SKILL.md index 864f20f7649a..126c35bdf234 100644 --- a/.agents/skills/launch/SKILL.md +++ b/.agents/skills/launch/SKILL.md @@ -483,6 +483,7 @@ Code OSS is a full Electron app and easily eats 1-4 GB. Always clean up. ## Troubleshooting +- **pnpm bootstrap fails on Windows** - check the actual Node/pnpm paths (`Get-Command node, pnpm -All`): stale shims can bypass fnm, and Corepack's bootstrap registry can differ from npm's configured registry. Select the Node version from `.nvmrc`; if Corepack remains blocked, install the pinned pnpm through the existing registry as described in [Contributing Fixes](../../../CONTRIBUTING.md#contributing-fixes). - **`Daemon pid=...: listen EINVAL` from `@playwright/cli`** - the daemon's socket path (`TMPDIR` + a fixed ~33-char prefix + the `-s=` session name) exceeded the ~103-byte unix socket limit. macOS's default `TMPDIR` leaves only ~16 characters for the session name, so shorten `-s=` first. If you need a longer name, scope the override to the single command (`TMPDIR=/tmp npx @playwright/cli ...`) rather than `export`ing it, so the launcher keeps using your private per-user temp dir. - **"Sent env to running instance. Terminating..."** - The dynamic `--user-data-dir` should prevent this. If you see it, another Code OSS is using the same profile path; pass `--source-user-data-dir` to a different source or check that the temp copy actually happened (`ls "$(node -p 'JSON.parse(process.argv[1]).userDataDir' "$INFO")"`). - **Renderer ESM errors / `import { Menu } from 'electron'`** - `ELECTRON_RUN_AS_NODE` is set in your env. The launcher unsets it for the child, but if you spawn `code.sh` yourself, do the same. diff --git a/.eslint-plugin-local/AGENTS.md b/.eslint-plugin-local/AGENTS.md new file mode 100644 index 000000000000..01d4c51fd066 --- /dev/null +++ b/.eslint-plugin-local/AGENTS.md @@ -0,0 +1,34 @@ +# Writing lint rules + +See [README.md](README.md) for how to add a rule. The rules here run in ESLint (editor, pre-commit hook, `pnpm run eslint`) and in oxlint (CI, `pnpm run oxlint`), which loads them as ESLint-compatible JS plugins. A rule must report the same problems in both. + +## Keep rules fast + +oxlint runs all JS plugin rules of a process on one thread, and the rules run on every file, so a few microseconds per node add up to seconds per run. Profiles of a full run showed most of the JS time going to the patterns below, not to what the rules check. + +- **Listen to rare node types, not selectors on common ones.** A complex selector (one with a descendant `A B`, child `A > B`, attribute `[...]` or pseudo-class part) is matched against every node of its last type, and a descendant selector walks all ancestors of each one. `'ImportDeclaration Literal'` runs on every literal in every file. Listen to `ImportDeclaration` and check `node.source`, or track enter/exit of the outer node with a counter. Plain node types (`CallExpression`, `Literal`) and `:exit` are cheap. +- **Ask for scope information last.** The first `context.sourceCode.getScope()` or `getDeclaredVariables()` in a file makes oxlint run the full scope analysis of that file. Check cheap syntactic conditions first (does the file import the module, does the callee have the right name), and resolve candidates in `Program:exit` only when they hold. The check must be a necessary condition for a report, never a heuristic. +- **Walk `node.parent` instead of calling `sourceCode.getAncestors()`**, which builds an array. +- **Read `node.loc` only to report.** oxlint computes locations on first access. +- **Do per-options work once.** Rule options are the same object for every file: compile regular expressions and minimatch patterns once, at module level or in a `WeakMap` keyed by the options, and cache results that depend only on the options and a string. +- **Do per-file work once, in `create()`.** Compute the file's relative path or layer there, not per import, and return `{}` when no check can apply to the file. +- **Don't read files per file or per node.** Cache at module level. If the content can change while a long-lived ESLint server runs in the editor, read it again before reporting. + +## Measure and verify + +- Profile one oxlint process (JS plugin rules run on its main thread), then look at the self time of the rule's functions and of oxlint's `esquery` and scope functions: + `node --cpu-prof --cpu-prof-dir=/tmp/oxlint-profile node_modules/oxlint/bin/oxlint --format=json src` +- Compare timings with `node build/oxlint.ts --processes=1 `, before and after. +- Run the rule's tests: `node --test .eslint-plugin-local/tests/.test.ts`. +- For a change that must not change behavior, compare the full output of both linters before and after with every disable directive switched off. In a clean checkout of the base commit, and again in one of the change (for example two `git worktree`s), run: + + ```sh + NAME=before # or after + git grep -lzE 'eslint-(disable|enable)' -- '*.ts' '*.tsx' '*.mts' '*.cts' '*.js' '*.mjs' '*.cjs' | xargs -0 perl -pi -e 's/eslint-(disable|enable)/eslint-x$1/g' + rm -f .eslintcache # ESLint's cache doesn't notice changed rules + node --max-old-space-size=8192 build/eslint.ts | grep -E ': line [0-9]+, col' | sort > /tmp/eslint-$NAME.txt + node build/oxlint.ts | grep -E ': line [0-9]+, col' | sort > /tmp/oxlint-$NAME.txt + git checkout -- . # restores the directives, and discards all other uncommitted changes + ``` + + Then diff the `before` and `after` files of each linter. Both should report about ten thousand problems, and nothing should differ. diff --git a/.eslint-plugin-local/README.md b/.eslint-plugin-local/README.md index e93a14d18b26..a207b9af1905 100644 --- a/.eslint-plugin-local/README.md +++ b/.eslint-plugin-local/README.md @@ -46,7 +46,7 @@ For example, here's a configuration that enables the no `test.only` rule in all ``` # Creating a new custom rule -This walks through the steps to create a new eslint rule: +This walks through the steps to create a new eslint rule (see [AGENTS.md](AGENTS.md) for how to keep it fast): 1. Create a new rule file under `.eslint-plugin-local`. Generally you should call it `code-YOUR-RULE-NAME.ts`, for example, `.eslint-plugin-local/code-no-not-null-assertions-on-undefined-values.ts` @@ -110,6 +110,20 @@ rules: { In these cases make sure to update the `meta.schema` property on your rule with the JSON schema for the arguments. You can access these arguments using `context.options` in the rule `create` function +# Running the rules with oxlint + +Pull request and product build CI run the rules with [oxlint](https://oxc.rs/docs/guide/usage/linter.html), which is faster than ESLint. ESLint still runs them in the editor and the pre-commit hook, and with `pnpm run eslint`. `pnpm run oxlint` takes the same arguments as `pnpm run eslint` (files, or `--changed-since `) and reports in the same format, with ESLint's rule names. + +There is one configuration: [oxlint.config.ts](../oxlint.config.ts) converts `eslint.config.js` when oxlint loads it (see `build/lib/oxlintConfig.ts`). oxlint implements ESLint's core rules and the `@typescript-eslint` rules natively, and loads the other plugins as JS plugins, which run on one thread per process; `build/oxlint.ts` therefore splits a full run into several processes by folder, and lints the extensions that use type information in a separate process with `--type-aware`. + +So that configuration and disable directives work in both linters, `eslint.config.js` uses the names oxlint reports: + +- `eslint-js/*` and `ts-eslint-js/*` are the ESLint and typescript-eslint rules that oxlint does not implement, such as `eslint-js/no-restricted-syntax` and `ts-eslint-js/naming-convention`. The adapters in `adapters/` load the original implementations for both linters. Add a rule there before using it. +- `jsdoc-js/*` is `eslint-plugin-jsdoc`, because oxlint reserves `jsdoc` for its own implementation. +- `@stylistic/*` replaces ESLint's deprecated formatting rules (`semi`, `no-extra-semi`, `comma-dangle`). + +A rule of a plugin that oxlint cannot load fails the conversion, and a rule that oxlint does not know fails oxlint, so a rule never silently stops running. Plugins must be modules: oxlint cannot load plugins defined inline in `eslint.config.js`. oxlint does not support configuring rules in comments (`/* eslint rule: "warn" */`). + ## Agent host metadata boundary `local/code-no-private-agent-host-meta-import` keeps `src/vs/platform/agentHost/common/meta/copilotd/` and `meta/vscode/` private. Feature code must import domain helpers and portable types from top-level `meta/*.ts` modules, even for type-only imports. Top-level modules can adapt either private implementation; each private implementation can import only its own private folder. Files under `test/` directories may import raw metadata for parsing/vector tests, and `build/agentHost/generateCopilotMetadata.ts` may access the generated schema. @@ -122,6 +136,18 @@ The rule checks static imports, re-exports, import types, literal dynamic import It keeps `src/vs/workbench/contrib/chat/` from importing `src/vs/workbench/contrib/sessions/`, because Sessions depends on chat and never the reverse. Existing violations are listed in that configuration block's `ignores` and should be removed from the list once they are fixed ([#346756](https://github.com/microsoft/vscode/issues/346756)). Run its tests with `node --test .eslint-plugin-local/tests/code-no-restricted-path-imports.test.ts`. +## Restricted import zones + +`local/code-no-restricted-zone-imports` replaces `import/no-restricted-paths` and takes the same options: `{ zones: [{ target, from, except?, message? }], basePath? }`. In a file that matches a zone's `target`, it reports each import whose resolved path matches one of the zone's `from` paths and none of its `except` paths, with `Unexpected path "" imported in restricted zone.` followed by the zone's `message`. A path that contains glob characters is a minimatch glob, and extglobs such as `extensions/copilot/src/!(lib)/**` work; any other path matches itself and everything below it. As in `import/no-restricted-paths`, the exceptions of a glob are globs, and the exceptions of a directory are relative to that directory. Paths are relative to `basePath`, which defaults to the repository root rather than the current working directory, and are matched as `/`-separated repository-relative paths, so the rule behaves the same on Windows. + +`import/no-restricted-paths` resolved imports through the filesystem, which can't resolve extensionless TypeScript imports, so it silently skipped most of them. This rule resolves relative specifiers by path arithmetic instead, without filesystem access. Bare specifiers, such as packages and tsconfig path aliases like Copilot's `vscode`, are not checked. The rule checks static imports and re-exports (including `import type`), `import x = require()`, and dynamic `import()` and `require()` calls whose argument is a string literal. + +It enforces the rules between folders of `extensions/copilot/src` and `extensions/copilot/test`, such as `platform` not importing `extension`. Copilot's layers (`common`, `vscode`, `node`, `vscode-node`, `worker` and `vscode-worker`) are enforced by `local/code-layering`, the same rule that enforces VS Code's layers, configured with Copilot's extra layer names. `local/code-layering` looks for layer folders below the repository root only, so the name of the checkout doesn't matter, and it checks static imports, re-exports, `import x = require()`, and dynamic `import()` and `require()` calls whose argument is a string literal; run its tests with `node --test .eslint-plugin-local/tests/code-layering.test.ts`. The layering violations that already existed when it replaced `import/no-restricted-paths` are suppressed on their lines and should be fixed over time. Run its tests with `node --test .eslint-plugin-local/tests/code-no-restricted-zone-imports.test.ts`. + +## PascalCase class names + +`local/code-class-name-pascal-case` requires class names to be PascalCase as typescript-eslint defines it: the first character is not lowercase, and the name has no underscores. It replaces `@typescript-eslint/naming-convention` configured with `{ selector: 'class', format: ['PascalCase'] }`, with the same message, because that rule's general selector matching is expensive to run on every TypeScript file. Anonymous class expressions are not checked. The terminal contributions turn it off, because their full naming convention configuration (`ts-eslint-js/naming-convention`) already checks class names. Run its tests with `node --test .eslint-plugin-local/tests/code-class-name-pascal-case.test.ts`. + ## Asynchronous production filesystem operations diff --git a/.eslint-plugin-local/adapters/eslintCore.ts b/.eslint-plugin-local/adapters/eslintCore.ts new file mode 100644 index 000000000000..68b92c03f0b7 --- /dev/null +++ b/.eslint-plugin-local/adapters/eslintCore.ts @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { ESLint, Rule } from 'eslint'; +import { builtinRules } from 'eslint/use-at-your-own-risk'; + +/** + * The ESLint core rules that oxlint does not implement, as the `eslint-js` plugin. Both linters run ESLint's own + * implementation under the same name, so configuration and disable directives work in both. + */ +const ruleNames = [ + 'no-buffer-constructor', + 'no-restricted-syntax', +]; + +const rules: Record = {}; +for (const name of ruleNames) { + const rule = builtinRules.get(name); + if (!rule) { + throw new Error(`ESLint has no core rule '${name}'`); + } + rules[name] = rule; +} + +export default { meta: { name: 'eslint-js' }, rules } satisfies ESLint.Plugin; diff --git a/.eslint-plugin-local/adapters/header.ts b/.eslint-plugin-local/adapters/header.ts new file mode 100644 index 000000000000..7919ce097f09 --- /dev/null +++ b/.eslint-plugin-local/adapters/header.ts @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { fixupPluginRules } from '@eslint/compat'; +import type { ESLint } from 'eslint'; +import { createRequire } from 'module'; + +const require = createRequire(import.meta.url); + +/** + * `eslint-plugin-header`, as the `header` plugin that both linters load. It predates the rule APIs of current + * linters, so its rules go through `fixupPluginRules`, and its options are not validated against a schema. + */ +const pluginHeader = require('eslint-plugin-header'); +pluginHeader.rules.header.meta.schema = false; + +export default { meta: { name: 'header' }, rules: fixupPluginRules(pluginHeader).rules } satisfies ESLint.Plugin; diff --git a/.eslint-plugin-local/adapters/typescriptEslint.ts b/.eslint-plugin-local/adapters/typescriptEslint.ts new file mode 100644 index 000000000000..d5181499dfd5 --- /dev/null +++ b/.eslint-plugin-local/adapters/typescriptEslint.ts @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { ESLint, Rule } from 'eslint'; +import tseslint from 'typescript-eslint'; + +/** + * The typescript-eslint rules that oxlint does not implement, as the `ts-eslint-js` plugin. Both linters run + * typescript-eslint's implementation under the same name, so configuration and disable directives work in both. + */ +const ruleNames = [ + 'naming-convention', + 'no-restricted-imports', +]; + +// Parser services without a TypeScript program, for linters that provide none (oxlint). The rules above only need a +// program for options that select by type, which this repository does not use. +const servicesWithoutProgram = { + program: null, + esTreeNodeToTSNodeMap: new WeakMap(), + tsNodeToESTreeNodeMap: new WeakMap(), + emitDecoratorMetadata: undefined, + experimentalDecorators: undefined, + isolatedDeclarations: undefined, +}; + +function forwardTo(target: T, overrides: Record): T { + // The proxy target is empty, because the linter's objects can have read-only properties that a proxy must not change. + return new Proxy(Object.create(null), { + get(_, property) { + if (typeof property === 'string' && Object.hasOwn(overrides, property)) { + return overrides[property]; + } + const value = Reflect.get(target, property, target); + return typeof value === 'function' ? value.bind(target) : value; + } + }); +} + +function withParserServices(rule: Rule.RuleModule): Rule.RuleModule { + return { + ...rule, + create(context) { + if (context.sourceCode.parserServices?.esTreeNodeToTSNodeMap) { + return rule.create(context); + } + const sourceCode = forwardTo(context.sourceCode, { parserServices: servicesWithoutProgram }); + return rule.create(forwardTo(context, { sourceCode, getSourceCode: () => sourceCode })); + } + }; +} + +const typescriptEslintRules = (tseslint.plugin as ESLint.Plugin).rules ?? {}; +const rules: Record = {}; +for (const name of ruleNames) { + const rule = typescriptEslintRules[name]; + if (!rule) { + throw new Error(`typescript-eslint has no rule '${name}'`); + } + rules[name] = withParserServices(rule); +} + +export default { meta: { name: 'ts-eslint-js' }, rules } satisfies ESLint.Plugin; diff --git a/.eslint-plugin-local/code-class-name-pascal-case.ts b/.eslint-plugin-local/code-class-name-pascal-case.ts new file mode 100644 index 000000000000..cd3491424988 --- /dev/null +++ b/.eslint-plugin-local/code-class-name-pascal-case.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 type * as eslint from 'eslint'; +import type * as ESTree from 'estree'; + +/** + * Equivalent to `@typescript-eslint/naming-convention` configured with `{ selector: 'class', format: ['PascalCase'] }`, + * without the cost of running that rule's general selector matching on every file. + */ +export default new class ClassNamePascalCase implements eslint.Rule.RuleModule { + + readonly meta: eslint.Rule.RuleMetaData = { + type: 'suggestion', + messages: { + notPascalCase: 'Class name `{{name}}` must match one of the following formats: PascalCase', + }, + docs: { + description: 'Require class names to be PascalCase.', + }, + schema: [], + }; + + create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener { + const checkClass = (node: ESTree.ClassDeclaration | ESTree.ClassExpression): void => { + if (node.id && !isPascalCase(node.id.name)) { + context.report({ + node: node.id, + messageId: 'notPascalCase', + data: { name: node.id.name }, + }); + } + }; + + return { + ClassDeclaration: checkClass, + ClassExpression: checkClass, + }; + } +}; + +/** + * typescript-eslint's definition of PascalCase: the first character is not lowercase and there are no underscores. + */ +function isPascalCase(name: string): boolean { + return name.length === 0 || (name[0] === name[0].toUpperCase() && !name.includes('_')); +} diff --git a/.eslint-plugin-local/code-import-patterns.ts b/.eslint-plugin-local/code-import-patterns.ts index 7629b6ac94ed..037e566fa7e3 100644 --- a/.eslint-plugin-local/code-import-patterns.ts +++ b/.eslint-plugin-local/code-import-patterns.ts @@ -11,6 +11,20 @@ import { createImportRuleListener } from './utils.ts'; const REPO_ROOT = path.normalize(path.join(import.meta.dirname, '../')); +const matchers = new Map(); + +/** + * Same as `minimatch(path, pattern)`, but compiles each pattern only once. + */ +function match(path: string, pattern: string): boolean { + let matcher = matchers.get(pattern); + if (!matcher) { + matcher = new minimatch.Minimatch(pattern); + matchers.set(pattern, matcher); + } + return matcher.match(path); +} + interface ConditionalPattern { when?: 'hasBrowser' | 'hasNode' | 'hasElectron' | 'test'; pattern: string; @@ -60,7 +74,7 @@ export default new class implements eslint.Rule.RuleModule { const relativeFilename = getRelativeFilename(context); for (const config of configs) { - if (minimatch(relativeFilename, config.target)) { + if (match(relativeFilename, config.target)) { return createImportRuleListener((node, value) => this._checkImport(context, config, node, value)); } } @@ -73,11 +87,14 @@ export default new class implements eslint.Rule.RuleModule { return {}; } - private _optionsCache = new WeakMap(); + // ESLint passes a new `context.options` array for every file, but the option objects in it are reused. + private _optionsCache = new WeakMap(); private _processOptions(options: RawOption[]): ImportPatternsConfig[] { - if (this._optionsCache.has(options)) { - return this._optionsCache.get(options)!; + const cacheKey = options[0]; + const cached = cacheKey && this._optionsCache.get(cacheKey); + if (cached) { + return cached; } type Layer = 'common' | 'worker' | 'browser' | 'electron-browser' | 'node' | 'electron-utility' | 'electron-main'; @@ -220,7 +237,9 @@ export default new class implements eslint.Rule.RuleModule { configs.push({ target, restrictions: restrictions.filter(r => typeof r === 'string') as string[] }); } } - this._optionsCache.set(options, configs); + if (cacheKey) { + this._optionsCache.set(cacheKey, configs); + } return configs; } @@ -259,7 +278,7 @@ export default new class implements eslint.Rule.RuleModule { let matched = false; for (const pattern of restrictions) { - if (minimatch(importPath, pattern)) { + if (match(importPath, pattern)) { matched = true; break; } diff --git a/.eslint-plugin-local/code-layering.ts b/.eslint-plugin-local/code-layering.ts index cca94c4b6ea2..d987cec51e53 100644 --- a/.eslint-plugin-local/code-layering.ts +++ b/.eslint-plugin-local/code-layering.ts @@ -4,13 +4,51 @@ *--------------------------------------------------------------------------------------------*/ import * as eslint from 'eslint'; -import { join, dirname } from 'path'; +import type * as ESTree from 'estree'; +import { posix, relative, resolve } from 'path'; import { createImportRuleListener } from './utils.ts'; -type Config = { - allowed: Set; - disallowed: Set; -}; +type Layers = Record; + +interface LayeringViolation { + readonly from: string; + readonly allowed: readonly string[]; +} + +const repositoryRoot = resolve(import.meta.dirname, '..'); + +/** + * Returns a function that checks an import specifier of `filename` against the layers, or `undefined` when the file + * is in no layer. Layers are found in the folders below `root` only, so the name of the checkout doesn't matter. + */ +export function createLayeringChecker(root: string, filename: string, layers: Layers): ((specifier: string) => LayeringViolation | undefined) | undefined { + const directory = posix.dirname(relative(root, filename).replace(/\\/g, '/')); + const fileLayer = findLayer(directory.split('/'), layer => !!layers[layer]); + if (!fileLayer) { + return undefined; + } + + const allowed = new Set(layers[fileLayer]).add(fileLayer); + const disallowed = new Set(Object.keys(layers).filter(layer => !allowed.has(layer))); + + return specifier => { + const path = specifier[0] === '.' ? posix.join(directory, specifier.replace(/\\/g, '/')) : specifier; + const importLayer = findLayer(posix.dirname(path).split(/\\|\//), layer => allowed.has(layer) || disallowed.has(layer)); + return importLayer && disallowed.has(importLayer) ? { from: importLayer, allowed: [...allowed] } : undefined; + }; +} + +/** + * Returns the innermost folder name that is a layer. + */ +function findLayer(folders: readonly string[], isLayer: (folder: string) => boolean): string | undefined { + for (let i = folders.length - 1; i >= 0; i--) { + if (isLayer(folders[i])) { + return folders[i]; + } + } + return undefined; +} export default new class implements eslint.Rule.RuleModule { @@ -35,58 +73,36 @@ export default new class implements eslint.Rule.RuleModule { }; create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener { - - const fileDirname = dirname(context.filename); - const parts = fileDirname.split(/\\|\//); - const ruleArgs = context.options[0] as Record; - let config: Config | undefined; - for (let i = parts.length - 1; i >= 0; i--) { - if (ruleArgs[parts[i]]) { - config = { - allowed: new Set(ruleArgs[parts[i]]).add(parts[i]), - disallowed: new Set() - }; - Object.keys(ruleArgs).forEach(key => { - if (!config!.allowed.has(key)) { - config!.disallowed.add(key); - } - }); - break; - } - } - - if (!config) { - // nothing + const check = createLayeringChecker(repositoryRoot, context.filename, context.options[0] as Layers); + if (!check) { return {}; } - return createImportRuleListener((node, path) => { - if (path[0] === '.') { - path = join(dirname(context.filename), path); + const checkImport = (node: ESTree.Node | null | undefined): void => { + if (node?.type !== 'Literal' || typeof node.value !== 'string' || !node.loc) { + return; } + const violation = check(node.value); + if (violation) { + context.report({ + loc: node.loc, + messageId: 'layerbreaker', + data: { + from: violation.from, + allowed: violation.allowed.join(', ') + } + }); + } + }; - const parts = dirname(path).split(/\\|\//); - for (let i = parts.length - 1; i >= 0; i--) { - const part = parts[i]; - - if (config!.allowed.has(part)) { - // GOOD - same layer - break; - } - - if (config!.disallowed.has(part)) { - // BAD - wrong layer - context.report({ - loc: node.loc, - messageId: 'layerbreaker', - data: { - from: part, - allowed: [...config!.allowed.keys()].join(', ') - } - }); - break; + return { + ...createImportRuleListener(node => checkImport(node as ESTree.Node)), + ImportExpression: (node: ESTree.ImportExpression) => checkImport(node.source), + CallExpression: (node: ESTree.CallExpression) => { + if (node.callee.type === 'Identifier' && node.callee.name === 'require' && node.arguments.length === 1) { + checkImport(node.arguments[0]); } - } - }); + }, + }; } }; diff --git a/.eslint-plugin-local/code-no-parameter-property-before-init.ts b/.eslint-plugin-local/code-no-parameter-property-before-init.ts new file mode 100644 index 000000000000..b9fe4c87ce64 --- /dev/null +++ b/.eslint-plugin-local/code-no-parameter-property-before-init.ts @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { Context, CreateRule, ESTree, RuleMeta, Visitor } from '@oxlint/plugins'; + +type VisitorKeys = Context['sourceCode']['visitorKeys']; + +/** A method, getter or function-valued field that a field initializer can run. */ +interface Member { + readonly runsOn: 'call' | 'access'; + /** What runs: the parameters, whose default values run when the arguments are left out, and the body. */ + readonly roots: readonly ESTree.Node[]; +} + +/** How running a member reads a parameter property: its name, and the path to it, such as `['this.update()', 'this.service']`. */ +interface Read { + readonly name: string; + readonly path: readonly string[]; +} + +/** + * With JavaScript class field semantics (`useDefineForClassFields`), class fields are initialized before the + * constructor assigns the parameter properties, so a field initializer must not read a parameter property, directly or + * through the methods and getters that it runs. + * + * This only follows code that runs during initialization: function bodies are skipped unless the initializer calls them + * as a method or a function-valued field of the same class, or reads them as a getter. + */ +export default new class NoParameterPropertyBeforeInit implements CreateRule { + meta: RuleMeta = { + type: 'problem', + messages: { + direct: 'Parameter property \'{{name}}\' is read before it is initialized: class fields are initialized before the constructor assigns parameter properties.', + indirect: 'Parameter property \'{{name}}\' is read before it is initialized, through {{path}}: class fields are initialized before the constructor assigns parameter properties.', + }, + schema: false, + }; + + create(context: Context): Visitor { + const visitorKeys = context.sourceCode.visitorKeys; + return { + ClassBody: (body: ESTree.ClassBody) => { + const parameterProperties = getParameterProperties(body); + if (!parameterProperties.size) { + return; + } + + const members = getMembers(body); + + /** Calls `onRead` for each parameter property that `root` reads, and `onRun` for each member that it runs, until either returns `true`. */ + const forEachUse = (root: ESTree.Node, onRead: (node: ESTree.MemberExpression, name: string) => boolean, onRun: (node: ESTree.MemberExpression, name: string) => boolean) => { + walk(root, visitorKeys, node => { + const name = getThisMemberName(node); + if (name === undefined || isAssignmentTarget(node as ESTree.MemberExpression)) { + return false; + } + const memberExpression = node as ESTree.MemberExpression; + if (parameterProperties.has(name)) { + return onRead(memberExpression, name); + } + const member = members.get(name); + return member && (member.runsOn === 'access' || isInvoked(memberExpression)) ? onRun(memberExpression, name) : false; + }); + }; + + /** What running each member reads directly, and the members that it runs, in order. */ + const summaries = new Map(); + const summarize = (memberName: string) => { + let summary = summaries.get(memberName); + if (!summary) { + let read: Read | null = null; + const runs: { name: string; label: string }[] = []; + for (const root of members.get(memberName)!.roots) { + forEachUse(root, (node, name) => { + read = { name, path: [formatThisMember(node, name)] }; + return true; + }, (node, name) => { + runs.push({ name, label: formatThisMember(node, name) }); + return false; + }); + if (read) { + break; + } + } + summary = { read, runs }; + summaries.set(memberName, summary); + } + return summary; + }; + + /** How running each member reads a parameter property, directly or through the members that it runs. */ + const reads = new Map(); + const getRead = (memberName: string): Read | null => { + if (!reads.has(memberName)) { + // Summarize the members that the member can run, then propagate their reads until nothing changes, + // which handles members that run each other. + const reachable = [memberName]; + for (let i = 0; i < reachable.length; i++) { + for (const { name } of summarize(reachable[i]).runs) { + if (!reads.has(name) && !reachable.includes(name)) { + reachable.push(name); + } + } + } + const found = new Map(reachable.map(name => [name, summarize(name).read])); + for (let changed = true; changed;) { + changed = false; + for (const name of reachable) { + if (!found.get(name)) { + for (const run of summarize(name).runs) { + const read = reads.get(run.name) ?? found.get(run.name); + if (read) { + found.set(name, { name: read.name, path: [run.label, ...read.path] }); + changed = true; + break; + } + } + } + } + } + for (const [name, read] of found) { + reads.set(name, read); + } + } + return reads.get(memberName)!; + }; + + for (const element of body.body) { + if ((element.type === 'PropertyDefinition' || element.type === 'AccessorProperty') && !element.static && element.value) { + forEachUse(element.value, (node, name) => { + context.report({ node, messageId: 'direct', data: { name } }); + return false; + }, (node, memberName) => { + const read = getRead(memberName); + if (read) { + context.report({ node, messageId: 'indirect', data: { name: read.name, path: [formatThisMember(node, memberName), ...read.path].join(' -> ') } }); + } + return false; + }); + } + } + } + }; + } +}; + +function getParameterProperties(body: ESTree.ClassBody): Set { + const names = new Set(); + for (const element of body.body) { + if (element.type === 'MethodDefinition' && element.kind === 'constructor') { + for (const param of element.value.params) { + if (param.type === 'TSParameterProperty') { + const binding = param.parameter.type === 'AssignmentPattern' ? param.parameter.left : param.parameter; + if (binding.type === 'Identifier') { + names.add(binding.name); + } + } + } + } + } + return names; +} + +function getMembers(body: ESTree.ClassBody): Map { + const members = new Map(); + for (const element of body.body) { + // Calling a generator only creates an iterator, which doesn't run its body. + if (element.type === 'MethodDefinition' && !element.static && (element.kind === 'method' || element.kind === 'get') && element.value.body && !element.value.generator) { + const name = getKeyName(element.key, element.computed); + if (name !== undefined) { + members.set(name, { runsOn: element.kind === 'get' ? 'access' : 'call', roots: [...element.value.params, element.value.body] }); + } + } else if (element.type === 'PropertyDefinition' && !element.static && (element.value?.type === 'ArrowFunctionExpression' || element.value?.type === 'FunctionExpression') && element.value.body && !element.value.generator) { + const name = getKeyName(element.key, element.computed); + if (name !== undefined) { + members.set(name, { runsOn: 'call', roots: [...element.value.params, element.value.body] }); + } + } + } + return members; +} + +function getKeyName(key: ESTree.Node, computed: boolean): string | undefined { + if (key.type === 'Identifier' && !computed) { + return key.name; + } + if (key.type === 'PrivateIdentifier') { + return `#${key.name}`; + } + if (key.type === 'Literal' && typeof key.value === 'string') { + return key.value; + } + return undefined; +} + +/** The name of the member that `node` reads from `this`, as in `this.name`, `this['name']` or `this.#name`. */ +function getThisMemberName(node: ESTree.Node): string | undefined { + if (node.type !== 'MemberExpression' || node.object.type !== 'ThisExpression') { + return undefined; + } + return getKeyName(node.property, node.computed); +} + +/** Whether `node` is called, as in `this.m()`, or used as the tag of a template, as in ``this.m`text` ``. */ +function isInvoked(node: ESTree.MemberExpression): boolean { + return node.parent.type === 'CallExpression' && node.parent.callee === node + || node.parent.type === 'TaggedTemplateExpression' && node.parent.tag === node; +} + +/** Whether `node` is only written, as in `this.s = value`. */ +function isAssignmentTarget(node: ESTree.MemberExpression): boolean { + return node.parent.type === 'AssignmentExpression' && node.parent.operator === '=' && node.parent.left === node; +} + +function formatThisMember(node: ESTree.MemberExpression, name: string): string { + if (node.parent.type === 'TaggedTemplateExpression' && node.parent.tag === node) { + return `this.${name}\`\``; + } + return `this.${name}${isInvoked(node) ? '()' : ''}`; +} + +/** Functions and classes don't run when they are created, and have their own `this`. */ +const skippedTypes = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration', 'ClassExpression', 'ClassDeclaration']); + +/** + * Visits `node` and its descendants, except for functions and classes, until `visit` returns `true`. + */ +function walk(node: ESTree.Node, visitorKeys: VisitorKeys, visit: (node: ESTree.Node) => boolean): boolean { + if (skippedTypes.has(node.type)) { + return false; + } + if (visit(node)) { + return true; + } + for (const key of visitorKeys[node.type] ?? []) { + const child = (node as unknown as Record)[key]; + if (Array.isArray(child)) { + for (const item of child) { + if (isNode(item) && walk(item, visitorKeys, visit)) { + return true; + } + } + } else if (isNode(child) && walk(child, visitorKeys, visit)) { + return true; + } + } + return false; +} + +function isNode(value: unknown): value is ESTree.Node { + return !!value && typeof value === 'object' && typeof (value as { type?: unknown }).type === 'string'; +} diff --git a/.eslint-plugin-local/code-no-restricted-zone-imports.ts b/.eslint-plugin-local/code-no-restricted-zone-imports.ts new file mode 100644 index 000000000000..b0c66f77c5cd --- /dev/null +++ b/.eslint-plugin-local/code-no-restricted-zone-imports.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 type * as eslint from 'eslint'; +import type * as ESTree from 'estree'; +import type { TSESTree } from '@typescript-eslint/utils'; +import minimatch from 'minimatch'; +import { posix, relative, resolve } from 'path'; +import { createImportRuleListener } from './utils.ts'; + +interface Zone { + readonly target: string | readonly string[]; + readonly from: string | readonly string[]; + readonly except?: readonly string[]; + readonly message?: string; +} + +interface Options { + readonly zones: readonly Zone[]; + readonly basePath?: string; +} + +/** + * Tests a `/`-separated path that is relative to the repository root. + */ +type PathMatcher = (path: string) => boolean; + +interface Restriction { + readonly isRestricted: PathMatcher; + readonly isException: PathMatcher; +} + +interface CompiledZone { + readonly isTarget: PathMatcher; + readonly restrictions: readonly Restriction[]; + readonly message: string | undefined; +} + +const repositoryRoot = resolve(import.meta.dirname, '..'); + +// ESLint passes a new `context.options` array for every file, but the option objects in it are reused. +const compiledZonesCache = new WeakMap(); + +const stringOrStrings = { + anyOf: [ + { type: 'string' }, + { type: 'array', items: { type: 'string' }, minItems: 1 }, + ], +}; + +/** + * Replaces `import/no-restricted-paths`, with the same options: in files that match a zone's `target`, imports that + * resolve to a path matching one of the zone's `from` paths, and none of its `except` paths, are reported. + * + * Unlike `import/no-restricted-paths`, imports are not resolved through the filesystem, which could not resolve + * extensionless TypeScript imports. Relative specifiers are resolved by path arithmetic instead, and bare specifiers, + * such as packages and tsconfig path aliases, are not checked. + */ +export default new class NoRestrictedZoneImports implements eslint.Rule.RuleModule { + + readonly meta: eslint.Rule.RuleMetaData = { + type: 'problem', + messages: { + restricted: 'Unexpected path "{{specifier}}" imported in restricted zone.{{suffix}}', + }, + docs: { + description: 'Disallow imports from restricted paths into the files of a zone.', + }, + schema: [{ + type: 'object', + properties: { + zones: { + type: 'array', + minItems: 1, + items: { + type: 'object', + properties: { + target: stringOrStrings, + from: stringOrStrings, + except: { type: 'array', items: { type: 'string' } }, + message: { type: 'string' }, + }, + required: ['target', 'from'], + additionalProperties: false, + }, + }, + basePath: { type: 'string' }, + }, + required: ['zones'], + additionalProperties: false, + }], + }; + + create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener { + const options = context.options[0] as Options | undefined; + if (!options) { + return {}; + } + + const filename = toRepositoryPath(context.physicalFilename); + const zones = compileZones(options).filter(zone => zone.isTarget(filename)); + if (zones.length === 0) { + return {}; + } + + const directory = posix.dirname(filename); + const checkImport = (node: TSESTree.Node | ESTree.Node | null | undefined): void => { + if (node?.type !== 'Literal' || typeof node.value !== 'string' || !node.loc || !isRelative(node.value)) { + return; + } + const path = posix.join(directory, node.value); + for (const zone of zones) { + if (zone.restrictions.some(restriction => restriction.isRestricted(path) && !restriction.isException(path))) { + context.report({ + loc: node.loc, + messageId: 'restricted', + data: { specifier: node.value, suffix: zone.message ? ` ${zone.message}` : '' }, + }); + } + } + }; + + return { + ...createImportRuleListener(node => checkImport(node)), + ImportExpression: (node: ESTree.ImportExpression) => checkImport(node.source), + CallExpression: (node: ESTree.CallExpression) => { + if (node.callee.type === 'Identifier' && node.callee.name === 'require' && node.arguments.length === 1) { + checkImport(node.arguments[0]); + } + }, + }; + } +}; + +function compileZones(options: Options): readonly CompiledZone[] { + let zones = compiledZonesCache.get(options); + if (!zones) { + const basePath = resolve(repositoryRoot, options.basePath ?? ''); + zones = options.zones.map(zone => ({ + isTarget: matchesAny(asArray(zone.target).map(target => createMatcher(target, toRepositoryPath(basePath, target)))), + restrictions: asArray(zone.from).map(from => ({ + isRestricted: createMatcher(from, toRepositoryPath(basePath, from)), + // As in `import/no-restricted-paths`, the exceptions to a directory are relative to that directory. + isException: matchesAny((zone.except ?? []).map(except => createMatcher(except, isGlob(from) ? toRepositoryPath(basePath, except) : toRepositoryPath(basePath, from, except)))), + })), + message: zone.message, + })); + compiledZonesCache.set(options, zones); + } + return zones; +} + +/** + * Returns a matcher for a glob pattern or, when `pattern` contains no glob characters, for the path itself and + * everything below it. + */ +function createMatcher(pattern: string, path: string): PathMatcher { + if (isGlob(pattern)) { + const glob = new minimatch.Minimatch(path); + return candidate => glob.match(candidate); + } + if (path === '') { + return candidate => candidate !== '..' && !candidate.startsWith('../'); + } + return candidate => candidate === path || candidate.startsWith(`${path}/`); +} + +function matchesAny(matchers: readonly PathMatcher[]): PathMatcher { + return path => matchers.some(matcher => matcher(path)); +} + +function isGlob(pattern: string): boolean { + return /[*?[\]{}()!]/.test(pattern); +} + +function isRelative(specifier: string): boolean { + return /^\.\.?(?:\/|$)/.test(specifier); +} + +/** + * Resolves the given paths, relative to the repository root, and returns the result relative to the repository root + * with `/` separators. + */ +function toRepositoryPath(...paths: string[]): string { + return relative(repositoryRoot, resolve(repositoryRoot, ...paths)).replace(/\\/g, '/'); +} + +function asArray(value: T | readonly T[]): readonly T[] { + return Array.isArray(value) ? value : [value as T]; +} diff --git a/.eslint-plugin-local/code-translation-remind.ts b/.eslint-plugin-local/code-translation-remind.ts index b0029234d8f5..ae5bda1834d4 100644 --- a/.eslint-plugin-local/code-translation-remind.ts +++ b/.eslint-plugin-local/code-translation-remind.ts @@ -30,7 +30,7 @@ export default new class TranslationRemind implements eslint.Rule.RuleModule { return; } - const currentFile = context.filename; + const currentFile = context.filename.replace(/\\/g, '/'); const matchService = currentFile.match(/vs\/workbench\/services\/\w+/); const matchPart = currentFile.match(/vs\/workbench\/contrib\/\w+/); const matchSessionsPart = currentFile.match(/vs\/sessions\/contrib\/\w+/); @@ -43,7 +43,7 @@ export default new class TranslationRemind implements eslint.Rule.RuleModule { let json; try { - json = readFileSync('./build/lib/i18n.resources.json', 'utf8'); + json = readFileSync(new URL('../build/lib/i18n.resources.json', import.meta.url), 'utf8'); } catch (e) { console.error('[translation-remind rule]: File with resources to pull from Transifex was not found. Aborting translation resource check for newly defined workbench part/service.'); return; diff --git a/.eslint-plugin-local/index.ts b/.eslint-plugin-local/index.ts index 3751c1f1e386..eda64445e559 100644 --- a/.eslint-plugin-local/index.ts +++ b/.eslint-plugin-local/index.ts @@ -18,4 +18,4 @@ readdirSync(import.meta.dirname) rules[path.basename(file, '.ts')] = require(path.join(import.meta.dirname, file)).default; }); -export { rules }; +export default { meta: { name: 'local' }, rules } satisfies ESLint.Plugin; diff --git a/.eslint-plugin-local/package.json b/.eslint-plugin-local/package.json index 358891f62cd1..fee157a02d01 100644 --- a/.eslint-plugin-local/package.json +++ b/.eslint-plugin-local/package.json @@ -6,11 +6,13 @@ "typecheck": "tsc -p tsconfig.json --noEmit" }, "devDependencies": { + "@eslint/compat": "^2.1.0", "@types/estree": "^1.0.9", "@types/minimatch": "^3.0.3", "@types/node": "24.x", "@typescript-eslint/utils": "8.66.0", "eslint": "10.8.0", + "eslint-plugin-header": "3.1.1", "eslint-visitor-keys": "^5.0.1", "minimatch": "^3.1.5", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/.eslint-plugin-local/tests/code-class-name-pascal-case.test.ts b/.eslint-plugin-local/tests/code-class-name-pascal-case.test.ts new file mode 100644 index 000000000000..efe9b05d6f1d --- /dev/null +++ b/.eslint-plugin-local/tests/code-class-name-pascal-case.test.ts @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RuleTester } from 'eslint'; +import { suite, test } from 'node:test'; +import tseslint from 'typescript-eslint'; +import rule from '../code-class-name-pascal-case.ts'; + +RuleTester.describe = suite; +RuleTester.it = test; + +const error = (name: string) => ({ message: `Class name \`${name}\` must match one of the following formats: PascalCase` }); + +new RuleTester({ languageOptions: { parser: tseslint.parser } }).run('code-class-name-pascal-case', rule, { + valid: [ + { name: 'PascalCase', code: `class SignService {}` }, + { name: 'anonymous class expression', code: `const service = class {};` }, + ], + invalid: [ + { name: 'lowercase declared class', code: `declare namespace vsda { export class signer {} }`, errors: [error('signer')] }, + { name: 'underscore', code: `const service = class Sign_Service {};`, errors: [error('Sign_Service')] }, + ], +}); diff --git a/.eslint-plugin-local/tests/code-layering.test.ts b/.eslint-plugin-local/tests/code-layering.test.ts new file mode 100644 index 000000000000..c75e8d8ac300 --- /dev/null +++ b/.eslint-plugin-local/tests/code-layering.test.ts @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { RuleTester } from 'eslint'; +import { suite, test } from 'node:test'; +import { resolve } from 'path'; +import tseslint from 'typescript-eslint'; +import rule, { createLayeringChecker } from '../code-layering.ts'; + +RuleTester.describe = suite; +RuleTester.it = test; + +const layers = { 'common': [], 'node': ['common'], 'vscode': ['common'], 'vscode-node': ['common', 'vscode', 'node'] }; +const options = [layers]; +const commonFile = resolve(import.meta.dirname, '../../extensions/copilot/src/util/common/types.ts'); +const error = (from: string) => ({ messageId: 'layerbreaker', data: { from, allowed: 'common' } }); + +suite('createLayeringChecker', () => { + test('ignores the folders of the checkout', () => { + const results = ['/work/vscode/vscode', '/work/other/checkout'].map(root => { + const check = createLayeringChecker(root, `${root}/extensions/copilot/src/util/common/types.ts`, layers); + return ['../../vscodeTypes', '../node/a', '../vscode/b'].map(specifier => check?.(specifier)?.from); + }); + assert.deepStrictEqual(results, [[undefined, 'node', 'vscode'], [undefined, 'node', 'vscode']]); + }); + + test('a file in no layer below the root is not checked', () => { + assert.strictEqual(createLayeringChecker('/work/vscode/vscode', '/work/vscode/vscode/extensions/copilot/src/vscodeTypes.ts', layers), undefined); + }); +}); + +new RuleTester({ languageOptions: { parser: tseslint.parser } }).run('code-layering', rule, { + valid: [ + { filename: commonFile, options, code: `import { x } from '../../vscodeTypes';` }, + { filename: commonFile, options, code: `const x = import('../common/x');` }, + ], + invalid: [ + { filename: commonFile, options, code: `import { x } from '../node/x';`, errors: [error('node')] }, + { filename: commonFile, options, code: `const x = import('../node/x');`, errors: [error('node')] }, + { filename: commonFile, options, code: `const x = require('../vscode/x');`, errors: [error('vscode')] }, + ], +}); diff --git a/.eslint-plugin-local/tests/code-no-parameter-property-before-init.test.ts b/.eslint-plugin-local/tests/code-no-parameter-property-before-init.test.ts new file mode 100644 index 000000000000..252ad21ea361 --- /dev/null +++ b/.eslint-plugin-local/tests/code-no-parameter-property-before-init.test.ts @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { suite, test } from 'node:test'; +import { RuleTester } from 'oxlint/plugins-dev'; +import rule from '../code-no-parameter-property-before-init.ts'; + +RuleTester.describe = suite; +RuleTester.it = test; + +const direct = (name: string) => ({ messageId: 'direct', data: { name } }); +const indirect = (name: string, path: string) => ({ messageId: 'indirect', data: { name, path } }); + +new RuleTester({ languageOptions: { sourceType: 'module', parserOptions: { lang: 'ts' } } }).run('code-no-parameter-property-before-init', rule, { + valid: [ + // The constructor runs after the parameter properties are assigned. + `class C { constructor(private readonly s: S) { this.s.run(); } }`, + // Functions that the initializer creates, but doesn't run. + `class C { x = () => this.s.run(); y = function () { return this; }; constructor(private readonly s: S) { } }`, + `class C { x = this.e.event(() => this.s.run()); constructor(private readonly s: S) { } }`, + // A method or a function-valued field that the initializer reads, but doesn't call. + `class C { x = this.m; y = this.f; f = () => this.s; constructor(private readonly s: S) { } m() { return this.s; } }`, + // A method that reads no parameter property, and recursion. + `class C { x = this.m(); constructor(private readonly s: S) { } m(): number { return this.m() + this.n; } }`, + // Static members, and other objects. + `class C { static x = this.s; y = other.s; constructor(private readonly s: S) { } }`, + // The \`this\` of a nested class or object method. + `class C { x = new class { s = 1; y = this.s; }; y = { s: 1, m() { return this.s; } }.m(); constructor(private readonly s: S) { } }`, + // Parameters that aren't properties, and members that the class doesn't declare. + `class C extends B { x = this.s; y = this.inherited(); constructor(s: S) { super(); } }`, + // Assignments that only write the parameter property. + `class C { x = (this.s = 1); constructor(public s: number) { } }`, + // Calling a generator only creates an iterator. + `class C { x = this.values(); y = this.g(); g = function* (this: C) { yield this.s; }; constructor(private readonly s: S) { } *values() { yield this.s; } }`, + ], + invalid: [ + { code: `class C { x = this.s.value; constructor(private readonly s: S) { } }`, errors: [direct('s')] }, + { code: `class C { x = this['s']; constructor(public s = 1) { } }`, errors: [direct('s')] }, + { code: `class C { accessor x = this.s; constructor(private readonly s: S) { } }`, errors: [direct('s')] }, + { code: `class C { x = this.m(); constructor(private readonly s: S) { } m() { return this.n(); } n() { return this.s; } }`, errors: [indirect('s', 'this.m() -> this.n() -> this.s')] }, + { code: `class C { x = this.g; constructor(private readonly s: S) { } get g() { return this.s; } }`, errors: [indirect('s', 'this.g -> this.s')] }, + { code: `class C { x = this.#m(); f = () => this.s; constructor(private readonly s: S) { } #m() { return this.f(); } }`, errors: [indirect('s', 'this.#m() -> this.f() -> this.s')] }, + { code: `class C { x = [this.a, this.m()]; constructor(private a: A, private b: B) { } m() { return this.b!; } }`, errors: [direct('a'), indirect('b', 'this.m() -> this.b')] }, + { code: `class C { x = (this.s += 1); constructor(public s: number) { } }`, errors: [direct('s')] }, + // Default values of parameters run when the call leaves out the arguments. + { code: `class C { x = this.m(); y = this.f(); f = (value = this.s) => value; constructor(private readonly s: S) { } m(value = this.s.value) { return value; } }`, errors: [indirect('s', 'this.m() -> this.s'), indirect('s', 'this.f() -> this.s')] }, + { code: 'class C { x = this.tag`text`; constructor(private readonly s: S) { } tag(parts: TemplateStringsArray) { return this.s; } }', errors: [indirect('s', 'this.tag`` -> this.s')] }, + // Members that run each other. + { code: `class C { x = this.a(false); y = this.b(); constructor(private readonly s: S) { } a(recur: boolean) { if (recur) { this.b(); } return this.s; } b() { return this.a(false); } }`, errors: [indirect('s', 'this.a() -> this.s'), indirect('s', 'this.b() -> this.a() -> this.s')] }, + { code: `class C { x = this.b(); constructor(private readonly s: S) { } a(): S { return this.b() ?? this.s; } b(): S { return this.a(); } }`, errors: [indirect('s', 'this.b() -> this.a() -> this.s')] }, + ], +}); diff --git a/.eslint-plugin-local/tests/code-no-restricted-zone-imports.test.ts b/.eslint-plugin-local/tests/code-no-restricted-zone-imports.test.ts new file mode 100644 index 000000000000..93d21769d4ed --- /dev/null +++ b/.eslint-plugin-local/tests/code-no-restricted-zone-imports.test.ts @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RuleTester } from 'eslint'; +import { suite, test } from 'node:test'; +import { resolve } from 'path'; +import tseslint from 'typescript-eslint'; +import rule from '../code-no-restricted-zone-imports.ts'; + +RuleTester.describe = suite; +RuleTester.it = test; + +const file = (path: string) => resolve(import.meta.dirname, '../..', path); +const commonFile = file('extensions/copilot/src/platform/git/common/gitService.ts'); +const platformFile = file('extensions/copilot/src/platform/git/vscode/gitService.ts'); +const message = 'Platform code must not depend on extension code.'; +const options = [{ + zones: [ + { target: '**/common/**', from: ['**/vscode/**', '**/node/**'] }, + { target: './extensions/copilot/src/platform', from: './extensions/copilot/src/extension', except: ['./allowed'], message }, + { target: 'extensions/copilot/src/!(lib)/**', from: './extensions/copilot/src/lib' }, + ], +}]; +const error = (specifier: string, suffix = '') => ({ message: `Unexpected path "${specifier}" imported in restricted zone.${suffix}` }); + +new RuleTester({ languageOptions: { parser: tseslint.parser } }).run('code-no-restricted-zone-imports', rule, { + valid: [ + { name: 'allowed relative import', filename: commonFile, options, code: `import { IGitService } from './git';` }, + { name: 'bare specifier', filename: commonFile, options, code: `import { Worker } from 'some-package/node/worker';` }, + { name: 'except', filename: platformFile, options, code: `import { x } from '../../../extension/allowed/x';` }, + { name: 'file excluded by an extglob', filename: file('extensions/copilot/src/lib/node/chatLibMain.ts'), options, code: `import { x } from '../common/x';` }, + ], + invalid: [ + { name: 'glob zone, extensionless', filename: commonFile, options, code: `import { Repository } from '../vscode/git';`, errors: [error('../vscode/git')] }, + { name: 'glob zone, .js', filename: commonFile, options, code: `import { exec } from '../node/exec.js';`, errors: [error('../node/exec.js')] }, + { name: 'type-only import', filename: commonFile, options, code: `import type { Repository } from '../vscode/git';`, errors: [error('../vscode/git')] }, + { + name: 're-export, dynamic import, import equals, and require', + filename: commonFile, + options, + code: [ + `export * from '../node/a';`, + `const b = import('../node/b');`, + `import c = require('../node/c');`, + `const d = require('../node/d');`, + ].join('\n'), + errors: [error('../node/a'), error('../node/b'), error('../node/c'), error('../node/d')], + }, + { name: 'directory zone with message', filename: platformFile, options, code: `import { x } from '../../../extension/x/common/x';`, errors: [error('../../../extension/x/common/x', ` ${message}`)] }, + { name: 'extglob target', filename: file('extensions/copilot/src/util/vscode/x.ts'), options, code: `import { x } from '../../lib/node/chatLibMain';`, errors: [error('../../lib/node/chatLibMain')] }, + ], +}); diff --git a/.eslint-plugin-local/tests/code-translation-remind.test.ts b/.eslint-plugin-local/tests/code-translation-remind.test.ts new file mode 100644 index 000000000000..f768d2e010db --- /dev/null +++ b/.eslint-plugin-local/tests/code-translation-remind.test.ts @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RuleTester } from 'eslint'; +import { suite, test } from 'node:test'; +import tseslint from 'typescript-eslint'; +import rule from '../code-translation-remind.ts'; + +RuleTester.describe = suite; +RuleTester.it = test; + +const code = `import { localize } from '../../../../nls.js';`; + +new RuleTester({ languageOptions: { parser: tseslint.parser } }).run('code-translation-remind', rule, { + valid: [ + { filename: '/repo/src/vs/workbench/contrib/chat/browser/example.ts', code }, + { filename: String.raw`C:\repo\src\vs\workbench\contrib\chat\browser\example.ts`, code }, + ], + invalid: [ + { filename: '/repo/src/vs/sessions/contrib/unregistered/browser/example.ts', code, errors: [{ messageId: 'missing' }] }, + { filename: String.raw`C:\repo\src\vs\sessions\contrib\unregistered\browser\example.ts`, code, errors: [{ messageId: 'missing' }] }, + ], +}); diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 9de3f6bb4da8..81aa099e42e2 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -13,6 +13,8 @@ # this is only about the final API, not about proposed API changes src/vscode-dts/vscode.d.ts @TylerLeonhardt @alexr00 src/vs/workbench/services/extensions/common/extensionPoints.json @TylerLeonhardt @alexr00 +# Extensions that may use any proposed API in every build +src/vs/workbench/services/extensions/common/extensionsProposedApiExceptions.ts @alexr00 @TylerLeonhardt # Quick Input API src/vs/platform/quickinput/common/quickInput.ts @TylerLeonhardt diff --git a/.github/instructions/agent-host-interoperability.instructions.md b/.github/instructions/agent-host-interoperability.instructions.md index 8c42b6da0c21..bcd1dfcc479d 100644 --- a/.github/instructions/agent-host-interoperability.instructions.md +++ b/.github/instructions/agent-host-interoperability.instructions.md @@ -5,9 +5,17 @@ applyTo: "src/vs/platform/agentHost/**,src/vs/workbench/contrib/chat/browser/age # AHP interoperability +This document contains durable, cross-cutting interoperability rules for VS Code's AHP clients and hosts. Keep it focused on stable protocol boundaries and reusable implementation guidance; do not add task-specific details, historical facts, or individual bug-fix behavior that belongs in code, tests, issues, or pull requests. + AHP clients communicate with any conforming Agent Host, not only the local VS Code Agent Host. Treat host-advertised session and chat URIs, identifiers, state, and capabilities as authoritative. Do not derive or reinterpret them using the local host's URI format, provider names, or implementation conventions. Helpers that construct IDs for the local host are not a substitute for reading IDs supplied by a remote host. -Use standard AHP fields and negotiated capabilities for shared behavior. If VS Code needs an optional extension, use a namespaced `_meta` value with a typed reader that validates its shape before use. Do not make the extension a requirement for other hosts, and do not use `_meta` to replace a standard protocol field or to justify assuming a particular host implementation. +## Protocol constructs before `_meta` + +- Agents **MUST NOT** use `_meta` to express information or behavior that existing protocol constructs can express. Check the standard fields, state, actions, commands, and negotiated capabilities before adding or extending metadata. +- If a requirement cannot be satisfied without `_meta`, agents **SHOULD** open an issue in [microsoft/agent-host-protocol](https://github.com/microsoft/agent-host-protocol/issues) describing the requirement and the protocol gap, rather than silently treating a private extension as the protocol. +- Alternate Agent Host and UI implementations may neither provide nor understand `_meta`. Any use of `_meta` **MUST** fall back gracefully in both directions: clients must remain functional when a host omits the metadata, and hosts must remain functional when a client omits or ignores it. Preserve standard protocol behavior without the extension; do not make metadata a requirement for interoperability or use it to assume a particular host or UI implementation. + +For optional extensions that still need `_meta`, use namespaced keys and typed readers that validate each value's shape before use. When changing an AHP client, cover a conforming host that advertises valid but different URIs and identifiers, as well as absent optional extensions. Test the behavior at the client boundary, not only against the local VS Code host. diff --git a/.github/instructions/agentHostTesting.instructions.md b/.github/instructions/agentHostTesting.instructions.md index 5a647b21a28d..95574f7130fc 100644 --- a/.github/instructions/agentHostTesting.instructions.md +++ b/.github/instructions/agentHostTesting.instructions.md @@ -26,6 +26,8 @@ Read `src/vs/platform/agentHost/node/serviceBootstrapping.md` before adding or m ## Protocol Metadata +Before adding or extending `_meta`, follow [AHP interoperability](./agent-host-interoperability.instructions.md#protocol-constructs-before-_meta): existing protocol constructs take precedence, unmet requirements should be raised in microsoft/agent-host-protocol, and optional metadata must fall back gracefully with alternate hosts and UIs. + Put new readers for namespaced protocol `_meta` slots under `common/meta`. Readers must validate every value they return and expose typed data; callers should pass the parent protocol object rather than inspecting `_meta` fields directly. Existing unnamespaced and legacy readers live elsewhere and should be migrated separately when touched. Use type guards for dynamic properties; do not bypass type narrowing or lint rules with `Reflect.get`. Host-specific parsers and writers live under `common/meta/vscode` and `common/meta/copilotd`. Feature code imports only top-level `common/meta` helpers, which own source selection and domain conversion; ESLint enforces this boundary for value and type imports. diff --git a/.github/instructions/editor-minimap.instructions.md b/.github/instructions/editor-minimap.instructions.md new file mode 100644 index 000000000000..163196683f82 --- /dev/null +++ b/.github/instructions/editor-minimap.instructions.md @@ -0,0 +1,36 @@ +--- +description: Use when changing the editor minimap, its layout, slider, decorations or section headers, or the editor overview ruler. Covers deliberate behaviors that are easy to break and how to verify minimap changes. +applyTo: "src/vs/editor/browser/viewParts/minimap/**,src/vs/editor/browser/viewParts/overviewRuler/**,src/vs/editor/common/services/findSectionHeaders.ts,src/vs/editor/test/browser/view/minimap*.test.ts,src/vs/editor/test/common/services/findSectionHeaders.test.ts" +--- + +# Editor Minimap + +The minimap is a canvas view part, `src/vs/editor/browser/viewParts/minimap/minimap.ts`, drawn on top of the editor contents beside the vertical scrollbar. Its layout (`minimapLeft`, `minimapWidth`, the canvas sizes and the scale) is computed in `EditorLayoutInfoComputer._computeMinimapLayout` and `_computeMinimapScale` in `src/vs/editor/common/config/editorOptions.ts`. Section headers come from `findSectionHeaders.ts`, which runs in the editor worker. + +## Deliberate behaviors: don't break them + +- **A translucent `minimap.background` shows the code underneath.** This is a feature (#32581, #58324, #132681). `_applyLayout` paints the background behind the canvas only when it is opaque. A change that always paints the background passes CI and breaks this. +- **The slider follows lines, not view zones.** View zones (inline chat, diff hunks, peek) are absent from the minimap. When the viewport starts inside a zone or the top padding, the fraction of the first visible line is clamped to `[0, 1]`, so the slider never jumps back while zones scroll by (#290138). Keep scrolling-down monotonic. `minimapLayout.test.ts` covers this. +- **The scale steps with the pixel ratio and tolerates a pixel ratio just below a step.** `floor(scale * pixelRatio + 0.125)` keeps a pixel ratio such as 1.9999998 (a slightly negative zoom on a Retina screen) at the higher step instead of halving the minimap (#236999). `editorLayoutProvider.test.ts` lists the pixel ratios to keep. +- **The decorations layer repaints only the rows that changed.** Any 2D draw on a visible canvas makes Chromium repaint the whole layer. So the decorations are recorded as a `RecordedFrame`, `RowSignatures.diff` compares them with the previous frame, and only the dirty band is replayed under a clip (#193422, `minimapDirtyRows.ts`). Don't read pixels back (`getImageData`) per frame: it costs more than the full repaint it saves. Anything drawn on that layer must go through the frame, or it won't be repainted. +- **Every themed color must be in `MinimapOptions.equals`.** Otherwise a theme change keeps the old color. Section header text once kept its old color this way. +- **Section header labels don't overlap.** Adjacent headers are stacked rather than drawn over each other (#213027). In `minimap.size: fill` the header must not be squeezed by the canvas scale (#244902). + +## Section headers (`findSectionHeaders.ts`) + +- Keep it language-agnostic. Don't hard-code keywords like `region` or comment syntax for one language. Language-specific data belongs in the language configuration: `folding.markers.start` may declare a named group `label` for the region name; otherwise the name is the text after the match. The comment tokens come from `blockCommentStartToken` and `blockCommentEndToken`. +- A `MARK:` label inside a block comment drops the comment end token (`` shows `Label`, #210371). The token is stripped only when a block comment is open on that line just before the first `separator` or `label` capture, not before the match. A custom regex may consume the opening token itself (`^ +_Generated from `src/index-schema.ts` — index schema 2. Do not edit by hand; run `npm run sync-skills`._ + +**Source.** State repo `egamma/vscodesweeper-state`, branch `main`: `targets.json` (the roster — one entry per enrolled repo, `name` picks the file) and `index-.json` per repo (`index-vscode.json` for microsoft/vscode). + +**Envelope.** `{ schema, target, generatedAt, site: { stateRepo, stateBranch }, rows }` — `schema` is the shape version (refuse a major you don't know), `target` the `owner/repo`, `generatedAt` when the index was built, `rows` the records below. + +**Rows are sparse.** A key is omitted when it would hold its default: an open issue has no `currentState`, an unassigned one no `owner`, a non-agent-ready one no `agentReadiness`. Always write `(.x // default)` or `.x == null` checks. `labels` and `areaLabels` are comma-joined strings, not arrays. + +| Field | Type | Present | Meaning | +|---|---|---|---| +| `number` | number | always | The issue number. Link: `https://github.com//issues/`. | +| `title` | string | always | The issue title at review time. | +| `url` | string | only when the issue URL is not the canonical `https://github.com//issues/` | Safety valve; derive the link from `number` otherwise. | +| `reviewUrl` | string | only when the record lives off the canonical path | The review record's URL. Canonical: `https://github.com//blob/state/records//items/.md`. | +| `owner` | string | when the issue had an assignee at review time | The assignee's GitHub login (a review-time snapshot, not the live assignee). Say "assignee" to users. | +| `createdAt` | string | always (ISO 8601) | When the issue was opened — the issue's age. | +| `reviewedAt` | string | always (ISO 8601) | When the sweeper last reviewed the issue. | +| `labels` | string | when the issue had labels at review time | The issue's labels, COMMA-JOINED into one string (`"bug, terminal, help wanted"`). Split before matching: `(.labels // "") \| split(", ") \| index("terminal")`. | +| `areaLabels` | string | when the review suggested area labels | Area labels the review proposed (or found), comma-joined like `labels`. Informational — nothing applies them. | +| `itemType` | string | always | What kind of item the review judged this to be. Values: `bug`, `feature-request`, `debt`, `polish`, `upstream`, `question`, `under-discussion`. | +| `triageAction` | string | when NOT `keep-open` (the absent default; route-to-area is folded into keep-open) | What the sweeper proposes. A proposal is never applied by the sweeper itself. Values: `propose-close`, `needs-info`. | +| `proposedLabel` | string | when the verdict proposes a label (absent = `none`) | A real label of the repo the verdict proposes (`*duplicate`, `info-needed`, `bug`, …). | +| `closeReason` | string | on close proposals | Why the close is proposed. Values: `duplicate`, `implemented-on-main`, `as-designed`, `not-reproducible`, `out-of-scope`, `question`, `invalid`. | +| `canonical` | string | on duplicate close proposals | The issue this one duplicates: `"12345"` (same repo) or `"owner/repo#12345"` (cross-repo). | +| `confidence` | number | always (0–1) | The review's confidence in its verdict. | +| `proposedComment` | string | when the verdict drafted a comment | The full proposed comment (long). Print it for ONE issue when asked, never in bulk. | +| `verification` | string | on bugs the review assessed | Reproduction strength tier, best → worst. Values: `Confirmed`, `Source-confirmed`, `Traced`, `Plausible`, `Unverified`, `Inconclusive`, `not applicable`. | +| `agentReadiness` | string | when not `none` (the absent default) | `implement`: diagnosis done, bounded change, named validation — an agent can go straight to code. `plan`: goal clear, but a design/diagnosis decision is open first. A review-time snapshot: the issue may have gained a PR or a `security` label since. Values: `implement`, `plan`. | +| `autoFixable` | string | always, as the STRING `"true"`/`"false"` | Legacy boolean = `agentReadiness == "implement"`. Prefer `agentReadiness`. | +| `linkedPr` | string | on agent-ready rows an OPEN contributor PR already references | That PR's URL. Treat the issue as taken. | +| `skillPr` | string | when a sweeper-implement skill PR exists for the issue | That PR's URL. | +| `skillPrState` | string | beside `skillPr` | Its state when last seen. Values: `open`, `merged`, `closed`. | +| `fixPr` | string | historical rows only (retired fork lane) | URL of a draft fix PR from the retired fork lane. | +| `implementPr` | string | historical rows only (retired implement lane) | URL of a draft PR from the retired implement lane. | +| `lane` | string | on open keep-open rows of the two ranked types | Which ranking the row belongs to. Rows without a lane are not ranked (closed, close proposals, needs-info, other item types). Values: `bugs`, `features`. | +| `valueRaw` | number | beside `lane` | The UN-normalized value score (demand × severity/breadth, age-damped). Comparable across assignees WITHIN one lane, never across lanes (features outrank bugs by construction); sort with `sort_by(-(.valueRaw // 0))`. | +| `upvotes` | number | beside `lane` | 👍 reactions at review time. | +| `comments` | number | beside `lane` | Comment count at review time. | +| `severity` | string | bugs lane | The bug's severity class. Values: `crash`, `data-loss`, `freeze`, `perf`, `correctness`, `visual`, `papercut`, `none`. | +| `signal` | string | features lane | Demand signal: `backlog-candidate` (milestoned Backlog), `active` (recent demand), `dormant`. Values: `backlog-candidate`, `active`, `dormant`. | +| `infoRequestedAt` | string | on a needs-info row whose request still stands (ISO, or `unknown`) | When the repo's needs-info label was applied. | +| `infoAnsweredAt` | string | beside `infoRequestedAt`, when the reporter answered but the label is still on | The reporter's first reply after the ask — the issue now waits on the maintainer. | +| `infoAnsweredBy` | string | beside `infoAnsweredAt` | Who answered. Values: `reporter`. | +| `infoRequestedBy` | string | on needs-info rows with a post-review request | Login that applied the label. | +| `infoCommentUsed` | string | on needs-info rows with a post-review request | Whether the proposed question was posted. Values: `verbatim`, `embedded`, `edited`, `none`, `not-proposed`. | +| `infoActedBy` | string | beside `infoCommentUsed` | Login that posted the question. | +| `currentState` | string | when CLOSED (absent = open) | Open issues carry no `currentState`. Filter open rows with `select(.currentState == null)`. Values: `closed`. | +| `closedAt` | string | closed rows (ISO) | When the issue was closed. | +| `stateReason` | string | closed rows | GitHub's close reason. Values: `completed`, `not_planned`, `duplicate`, `not_found`. | +| `closedBy` | string | closed rows | Login that closed the issue. | +| `proposedCommentUsed` | string | closed close-proposal rows | Whether the sweeper's proposed closing comment was posted. Values: `verbatim`, `embedded`, `edited`, `none`, `not-proposed`. | +| `actedBy` | string | beside `proposedCommentUsed` | Login that posted it. | +| `autoClosedAt` | string | rows the sweeper-close action closed (ISO) | An automatic close — never a maintainer action. | +| `autoLane` | string | beside `autoClosedAt` | Which auto-close lane closed it. Values: `duplicate`, `implemented`. | +| `autoObjectedAt` | string | auto-closed rows someone replied to afterwards (ISO) | A possible objection the assignee should look at. | +| `lastCommentAt` | string | open rows with a non-bot comment (ISO) | The newest human comment. | +| `lastCommentBy` | string | beside `lastCommentAt` | `reporter` for the issue author, else the login. | +| `assigneeActedAt` | string | open rows where a live assignee acted (ISO) | The assignee's latest action. | +| `previousTriageAction` | string | open rows re-reviewed after a comment | The verdict this review replaced (e.g. `needs-info` → now keep-open). | +| `previousCloseReason` | string | beside `previousTriageAction` | The replaced verdict's close reason. | +| `previousCanonical` | string | beside `previousTriageAction` | The replaced verdict's duplicate canonical. | +| `verifyVerdict` | string | close/needs-info proposals a blinded second review checked | The second review's verdict on the proposal. Values: `confirmed`, `refuted`, `unverifiable`. | +| `verifyEvidence` | string | beside `verifyVerdict` | Its one-line rationale. | +| `verifyKind` | string | beside `verifyVerdict`, where the lane classifies | Duplicate lane: canonical kind; implemented lane: `bug-fix` \| `feature`. | +| `verifyCanonical` | string | duplicate lane | The canonical the verifier found. | +| `verifyCanonicalRepo` | string | when the verifier's canonical is in another repo | That repo (`owner/name`). | +| `verifyStale` | boolean | when the row was re-reviewed after its verification | The verification no longer matches the current review. | +| `verifyUnreleased` | boolean | implemented lane | Fixed on main but in no stable release yet. | +| `disputedAgain` | boolean | refuted twice | A refuted proposal whose automatic re-review is spent — for a person. | +| `verifiedUpdatedAt` | string | when set | Issue `updatedAt` as the verifier saw it. | +| `dismissed` | boolean | when a maintainer removed the proposal | Hide by default: `select(.dismissed != true)`. | +| `dismissedIssue` | string | beside `dismissed` | The state-repo issue that recorded the dismissal. | +| `dismissedAt` | string | beside `dismissed` (ISO) | When. | +| `dismissedBy` | string | beside `dismissed` | Who. | +| `dismissedReason` | string | when a reason was given | The maintainer's one-line reason. | +| `dismissedKind` | string | when classified | Why it was dismissed. Values: `disagree`, `other-direction`, `already-handled`, `keep-open-anyway`, `other`. | +| `contentStale` | boolean | when the issue changed since its review | The verdict may be out of date. | + diff --git a/.github/skills/ux-css-layout/SKILL.md b/.github/skills/ux-css-layout/SKILL.md index 7e04156434b3..d4841410303a 100644 --- a/.github/skills/ux-css-layout/SKILL.md +++ b/.github/skills/ux-css-layout/SKILL.md @@ -1,6 +1,6 @@ --- name: ux-css-layout -description: VS Code CSS conventions, file organization, class naming, standard sizes, SplitView/Grid layout, scrollable content, responsive layout, and text overflow/ellipsis patterns. Use when writing CSS, building layouts, or fixing text truncation issues. +description: VS Code CSS conventions, SplitView/Grid layout, semantic sizes, rounded-surface geometry, clipping, scrollable content, and text overflow. Use when writing CSS, building layouts, or fixing corners, panel gaps, or text truncation. --- This skill covers CSS file organization, naming, standard sizes, programmatic layout (SplitView, Grid, scrollable), responsive patterns, and text overflow handling. @@ -69,6 +69,8 @@ Do not introduce `!important` in new or modified CSS. When a declaration loses t The narrow exception is shared focus/active-outline suppression, where `outline: 0 !important` is intentionally used to override native or global focus indicators and prevent flashing outlines during pointer activation. Keep this exception scoped to focus-indicator behavior; feature styling must still resolve cascade conflicts through selector specificity. +Represent semantic state explicitly rather than inferring it from incidental DOM order. For example, a content node ceasing to be `:last-child` does not prove a footer exists: completion widgets can append siblings and leave them mounted while hidden. Let the component that creates/removes the footer own its state class, and test unrelated trailing siblings. + ## 5. SplitView Layout **File**: `src/vs/base/browser/ui/splitview/splitview.ts` @@ -126,6 +128,12 @@ container.appendChild(scrollable.getDomNode()); scrollable.scanDomNode(); // call after content changes ``` +Keep scroll handlers lightweight: batch layout reads before writes, coalesce duplicate measurements, and skip unchanged CSSOM writes. Cache numeric values rather than comparing rounded style strings. Validate both unchanged scrolling and resizing that changes appearance without changing the item count. + +For content-sized lists and trees, distinguish logical item height from the complete scroll extent. Horizontal-scrollbar reservation can make `scrollHeight` larger than `contentHeight`; size a floating host from the extent it must actually display, with its own chrome accounted for separately. Test horizontal scrolling enabled and disabled. + +Verify actual scrollbar dragging and pointer acquisition after changing margins or clipping. In maximized/fullscreen layouts, check screen-edge hit regions as well as visual placement; an inset control must not become unnecessarily difficult to acquire. + ## 8. Responsive Layout VS Code does **not** use CSS media queries. Instead, it uses a **programmatic constraint-based layout system**: @@ -141,6 +149,22 @@ When building a responsive component: 3. Use `snap: true` for panels that should snap closed when too small. 4. Fire `onDidChange` when your constraints change dynamically. +Validate layout at the boundaries where dimensions are consumed: + +- Keep grid allocation, CSS margins/borders, and child-content dimensions consistent. Exercise the real `layout()` path and inspect both root bounds and dimensions passed to children; helper values and outer screenshots alone cannot prove content fits. +- Read current viewport and density state during layout rather than relying solely on constructor-selected behavior. Test transitions in both directions on the same instance, including collapse/expand and narrow/wide layouts, without shifting unrelated siblings. +- Use existing screen-aware sizing helpers and the target window's effective pixel ratio for fractional scaling. Zoom alone is not device pixel ratio. Check margins, borders, and gap symmetry in CSS coordinates and physical pixels instead of adding compensating pixels or arbitrary tolerances. +- Keep startup/restored geometry aligned with runtime layout, including missing-state fallbacks. Check affected visibility, density, and window variants, and preserve intentional exclusions such as modal or auxiliary surfaces. +- Keep inter-panel spacing separate from pane-internal padding, exterior gutters, and the frame's reserved stroke. Before changing a shared margin helper, inspect all consumers. Test zero, one-pixel, odd, and maximum supported gaps; small gaps cannot fund an unconditional inset on both sides. +- Resolve configurable geometry consistently for CSS, numeric grid layout, startup paint, and auxiliary/native content. Clearing a customization must restore inheritance. Preserve resolved appearance when stale saved bounds are discarded; invalid geometry does not necessarily invalidate the user's size preferences. +- Refresh derived sash endpoints and gripper placement after grid topology changes such as moving or aligning a panel, not only after a window resize. Check odd-gap centers, newly created sashes, and removal of stale state when returning to compact or gapless layouts. + +### Floating and docked surfaces + +- Capture the visible shared grid node's dimensions before hiding it, even when one of its logical children is already hidden. Verify resize, close/reopen, reload, and orientation changes, preserving separate width preferences where horizontal and stacked layouts intentionally differ. +- Derive detached-window frames from that window's own insets and visible layout, not mirrored main-window classes. Include main/detached combinations that disagree about visible editors or tab counts. +- Exercise hover-preview, pin/unpin, focus transfer into nested popups, deferred blur, and pointer exit through the production controller. A queued blur must not consume a newly started exit grace period. Use controlled timers to verify ordering instead of increasing delays, and restore docked sizing/padding when floating mode ends. + ## 9. Text Overflow & Ellipsis All text labels that can be truncated by a resizable container **must** use the ellipsis pattern. Clipped text without an ellipsis is a visual bug. @@ -239,12 +263,28 @@ For `IconLabel` and list/tree renderers, this is handled automatically. For cust ### Anti-Patterns (NEVER DO) -- **Never** let text clip without an ellipsis — if `overflow: hidden` is set, `text-overflow: ellipsis` must also be set. +- **Never** let single-line text labels clip without an ellipsis. This rule applies to labels, not structural clipping containers or overflow masks. - **Never** rely on a fixed pixel width for text that could be localized — localized strings vary in length. - **Never** use `text-overflow: ellipsis` without `overflow: hidden` and `white-space: nowrap` — all three are required. - **Never** forget `min-width: 0` on flex children that need to truncate. - **Never** truncate text without providing a hover/tooltip for the full string. +### Clipping and Alignment + +- Measure content items separately from adjacent actions and toolbars. Recalculate clipping when labels, status indicators, or actions change width, even if the viewport is unchanged. +- Check first/last and partially visible items with long labels and combined hover/focus/selection states. Masks must not cover actions or scroll hit targets. Recreated overflow edges must preserve the source edge's shape and border state, and clear stale state when clipping ends. +- Keep hover/focus geometry stable so controls do not jump under the pointer. Test state transitions on existing elements as well as fresh renders. +- Define which semantic value should align in compound badges or labels. Centering a variable-width string does not preserve the alignment of its trailing status; compare short and long compound values alongside single-value rows. + +### Rounded-surface geometry + +- Trace the painted perimeter through the production ancestors before changing a radius or overflow rule. Identify the owner of the frame stroke, content paint, material layer, connected cap, and overlays. A child can report the correct radius while an ancestor clips its outline or content paints over it. +- Match the reference boxes as well as the radius. A pseudo-element positioned inside a host border does not share the host's outer curve merely because it inherits `border-radius`. Use the appropriate border/padding-box geometry; for unequal or elliptical corners, prefer browser-resolved curves over a uniform subtraction. +- Do not repair an obscured corner by clipping the entire content subtree. Progress indicators and fixed completion widgets may intentionally escape it, and transforms or filters can change fixed-position containing blocks. Isolate decorative paint from interactive content and preserve overlay stacking and hit targets. +- Repainting an edge must not create a second, inset frame or double-paint a translucent stroke. Align the replacement paint to the original frame and verify the composited result at all exposed corners, including square corners. A computed radius or an overlay hit test alone cannot prove the perimeter is correct. +- Derive connected caps, clipping fallbacks, and nested frames from the owning surface's semantic radius and effective inset, not a generic default. Honor square/custom radii, asymmetric Activity Bar seams, footer presence, and native window overrides. Check both header and footer ancestors when the Activity Bar can move. +- Verify painted outlines and overlay interactions in the affected browser engines. Include short/narrow panes, retained hidden overlay siblings, footer add/remove, fractional scaling, and the relevant maximized/fullscreen/native-window states. Keep native-platform evidence distinct from a web-only reproduction. + --- ## 10. Design-System Size Tokens (spacing, radius, font, codicon, stroke) @@ -275,6 +315,10 @@ Scale (px): `0, 2, 4, 6, 8, 10, 12, 16, 20, 24, 28, 32, 36, 40` → `--vscode-sp - **Pills** (radius ≈ half the element height — e.g. `28h`/`14r`, `36h`/`18r`, `22×22`/`11r`) → `--vscode-cornerRadius-circle`, **not** xLarge. The literal-nearest token would square them and lose the fully-rounded intent. - **Leave untouched:** `50%`, `0`, `0px`, `inherit`, any `calc()`/`var()`. Preserve `!important`. +The ramp describes generic design defaults, not a replacement for component-specific geometry. When a panel exposes a semantic size customization, its frame and dependent paint must consume that resolved value, including `0`, rather than snapping it back to a generic radius. Keep native-window radii and control/overlay tiers separate from panel preferences. + +At supported standalone or fixture boundaries where size tokens may be absent, provide valid length fallbacks for required padding, insets, radii, and outlines. A `var()` fallback handles an unavailable custom property, not a defined value of the wrong type or a unitless length. Follow the existing host contract rather than adding speculative fallbacks to every token. + ### Font size & weight Generic UI ramp — pair a **size** token with a **weight** token ("Strong" = matching size token + `semiBold`, never a separate size): diff --git a/.github/skills/ux-theming/SKILL.md b/.github/skills/ux-theming/SKILL.md index 8a6227dee1e2..c502e1ae0055 100644 --- a/.github/skills/ux-theming/SKILL.md +++ b/.github/skills/ux-theming/SKILL.md @@ -1,6 +1,6 @@ --- name: ux-theming -description: VS Code theming, color tokens, widget styles, focus indicators, and high-contrast theme support. Use when registering colors, styling widgets with theme tokens, or ensuring HC/focus compliance. +description: VS Code theming, color tokens, composited surfaces, interaction-state precedence, and high-contrast support. Use when styling widgets, changing hover/focus/selection, or validating rendered theme states. --- This skill covers color registration, CSS variable usage, widget style patterns, focus indicators, and high-contrast theme requirements. @@ -57,6 +57,22 @@ Conversion functions in `colorUtils.ts`: } ``` +Trace the rendered control before choosing a token or selector; custom editor overlays may not use native input pseudo-elements. Inspect inherited and nested styles as well as the component's own declarations. + +### Contrast and Interaction States + +- Treat foreground and background as a semantic pair. A background change requires checking text, placeholders, links, operable inactive icons, hover, selection, and focus against the final composited surface. +- Resolve defaults, opacity, and user overrides before measuring contrast. For example, an opaque icon color may meet contrast requirements while its translucent inactive variant does not. +- Normal-size text and placeholders need at least 4.5:1 contrast; visual information needed to identify controls and focus needs at least 3:1 against adjacent colors. Apply the relevant accessibility criteria rather than extending these thresholds to decorative or disabled content. Unselected but operable controls are not disabled. +- Check nested labels and descriptions in combined states; an explicit child foreground can defeat a correctly paired selection background. +- Choose tokens by semantic role, not their current hue. A chart accent is not automatically a warning-button background, and pairing it with a default button foreground does not establish contrast. Reuse an appropriate control palette or register a themeable foreground/background pair when the component has its own semantics. + +### Composited Surfaces + +A theme variable is not necessarily opaque. For a floating panel that must conceal underlying content, inspect the resolved alpha and all material layers rather than assuming a panel token or `var()` fallback guarantees occlusion. Use the owning theme/color helpers to derive an opaque semantic background where needed, preserve the intended glass treatment elsewhere, and verify switching content and floating/docked modes on the same instance. + +Keep material paint separate from interactive descendants. Border-box and padding-box alignment, clipping, and duplicated translucent strokes are covered by [rounded-surface geometry](../ux-css-layout/SKILL.md#rounded-surface-geometry). + ## 4. Widget Styles Pattern **File**: `src/vs/platform/theme/browser/defaultStyles.ts` @@ -75,12 +91,18 @@ const button = new Button(container, getButtonStyles({ Available defaults: `defaultButtonStyles`, `defaultInputBoxStyles`, `defaultCheckboxStyles`, `defaultToggleStyles`, `defaultDialogStyles`, `defaultListStyles`, `defaultSelectBoxStyles`, `defaultMenuStyles`, `defaultProgressBarStyles`, `defaultCountBadgeStyles`, `defaultBreadcrumbsWidgetStyles`, `defaultKeybindingLabelStyles`, `defaultFindWidgetStyles`. +### Transient Theme Overrides + +Use the owning theme service for temporary palettes so CSS variables and programmatic color consumers remain consistent. Keep overrides scoped to the intended window and preserve the base theme and user customizations. + +Verify enabling, disabling, replacement, disposal, and theme changes, including stale asynchronous results. Clearing an override must restore the original colors without persisting generated values or changing another window's theme or startup colors. + ## 5. Focus Indicators Defined in `src/vs/workbench/browser/media/style.css`: ```css -.my-widget:focus { +.my-widget:focus-visible { outline-width: 1px; outline-style: solid; outline-offset: -1px; @@ -91,9 +113,10 @@ Defined in `src/vs/workbench/browser/media/style.css`: **Rules**: - Use `var(--vscode-focusBorder)` — never hardcode a focus color. - Default `outline-offset: -1px` (inset). Exception: checkboxes use `2px`. -- Active elements suppress focus ring: `.my-widget:active { outline: 0 !important; }` -- Use `.synthetic-focus` class for programmatic focus indication. -- Toggle buttons use `border: 1px dashed var(--vscode-focusBorder)` instead of outline. +- Preserve the owning widget's keyboard-focus mechanism, including supported `.focus-visible` or `.synthetic-focus` classes. Pointer activation should not leave an unnecessary keyboard ring, but broad `:active` suppression must not erase the boundary during keyboard activation. +- Toggle selection, pointer hover, and keyboard focus are different states; do not use a dashed focus border as a universal toggle rule. Follow the [interaction-state contract](#high-contrast-interaction-state-contract). +- Check keyboard focus independently from selection and hover, including ordinary links without explicit `tabindex` and icon-only controls. Inspect computed outlines and pseudo-elements under production styles; token registration alone does not establish visibility. +- Preserve a clear focus boundary through clipping and modal wrappers. Resolve competing border/outline ownership rather than adding duplicate rings or removing focus visibility. ### Focus Trapping @@ -102,9 +125,9 @@ Modal dialogs must trap focus within the dialog until dismissed. Use `dom.trackF ## 6. High Contrast Theme Rules - **Always** provide `hcDark` and `hcLight` defaults when registering colors. -- HC backgrounds: `Color.black` (hcDark), `Color.white` (hcLight). +- HC surface backgrounds: use the registered HC defaults, commonly `Color.black` (hcDark) and `Color.white` (hcLight). Preserve component-specific selection and control palettes. - HC borders: reference `contrastBorder` — it is `null` in normal themes, visible in HC. -- HC focus: use `activeContrastBorder` (derived from `focusBorder`). +- HC keyboard focus: use `focusBorder` or the owning list's focus token; reserve `contrastActiveBorder` for the interaction states below. - In CSS, use `.hc-black` / `.hc-light` class selectors for HC-specific overrides: ```css .hc-black .my-widget { border: 1px solid var(--vscode-contrastBorder); } @@ -115,12 +138,64 @@ Modal dialogs must trap focus within the dialog until dismissed. Use `dom.trackF .my-widget { box-shadow: 0 1px 3px var(--vscode-widget-shadow); } - .vscode-high-contrast .my-widget { + .monaco-workbench:is(.hc-black, .hc-light) .my-widget { box-shadow: none; border: 1px solid var(--vscode-contrastBorder); } ``` +### High-Contrast Interaction-State Contract + +Interaction boundaries communicate different semantics. Do not collapse hover, keyboard focus, selection, and persistent state into one generic rule. + +| State | Boundary | Required behavior | +|---|---|---| +| Pointer hover | Dashed `contrastActiveBorder` | Apply only to the actionable element actually under the pointer. A `mouse-navigation` class plus a stale focused row is not sufficient. | +| Keyboard focus | Solid `focusBorder` or the owning list focus token | Must win over simultaneous hover and open/expanded/pressed state. Preserve the focus ring when the pointer remains over the control. | +| Open, expanded, or pressed | Solid `contrastActiveBorder` | Persistent state, not transient hover. Keep normal-theme hover fill separate so an expanded control can respond to the pointer without becoming dashed. | +| Selected or checked | The component's selection palette and semantic foreground | Hover must not replace the selected background while leaving the selected foreground behind. | +| Disabled | No hover or active boundary | Disabled styling remains owned by the component. A disabled control that intentionally remains keyboard-focusable still needs a focus indicator. | + +Assign one boundary owner per interaction. A pseudo-element may paint an inset hover fill, but it must not also draw an outline when the component root owns the boundary. When a card contains independent actions, suppress the card boundary while a nested action is hovered, focused, or open. For virtualized trees, inspect both the `.monaco-list-row` and its painted child such as `.monaco-tl-row`; never clear the child focus ring when the outer row's outline is intentionally suppressed. + +Native disclosure state is not exposed as `aria-expanded` on ``. Use `details[open] > summary` for visual state, or synchronize a component state class/ARIA attribute for a non-native disclosure. Exclude keyboard focus from persistent-state rules as well as hover rules; greater selector specificity can otherwise erase focus even when the focus rule comes later. + +For a custom control whose expanded/pressed state uses ARIA, keep background and boundary selectors independent. This example preserves keyboard precedence in combined states: + +```css +.control:not(.disabled, :disabled, [aria-disabled='true']):is(:hover, .hovered) { + background-color: var(--vscode-list-hoverBackground); +} + +.monaco-workbench:is(.hc-black, .hc-light) .control:not(.disabled, :disabled, [aria-disabled='true'], :focus-visible, .focus-visible, [aria-expanded='true'], [aria-pressed='true']):is(:hover, .hovered) { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); +} + +.monaco-workbench:is(.hc-black, .hc-light) .control:not(:disabled):is(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); +} + +.monaco-workbench:is(.hc-black, .hc-light) .control:not(.disabled, :disabled, [aria-disabled='true'], :focus-visible, .focus-visible):is([aria-expanded='true'], [aria-pressed='true']) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); +} +``` + +For controls with a selected/checked palette, exclude that state from the generic hover fill or provide its correctly paired selected-hover colors. Keep independent status markers distinct as well: attention-required, pinned, selected, and focused states can coexist. Test their combined placement and semantic foregrounds rather than letting a new marker cover an existing one. + +Validate a state matrix rather than isolated screenshots: rest, hover, keyboard focus, focus plus hover, open/expanded/pressed plus focus and hover, selected/checked plus hover, disabled plus hover, and nested-action focus/hover. Load all production styles that compete for the boundary and verify both HC Dark and HC Light, plus normal Dark/Light when selector exclusions can affect hover fills. + +Test runtime theme changes and custom color overrides, including transitions where a previously defined token becomes absent. Clear stale inline colors or classes rather than leaving the previous theme's state behind. Render through production state-owning services so intentionally omitted decoration remains absent. + +### Testing Rendered Interaction States + +- A dispatched `mousemove` can update a widget's modality or logical focus without activating CSS `:hover`. Use real pointer input for interaction tests. A fixture may use the production-supported `.hovered` class, but it must assert the intended computed boundary before capturing a screenshot. +- Establish keyboard modality through the actual input path, then dispatch navigation from the focused item. An ancestor bubbling listener may never see keys consumed by an inner ActionBar; use capture only where the owner must observe the event before that handler. Test pointer-to-keyboard transitions with a stationary pointer. +- Do not assume `.focus()` or a synthetic key event makes `:focus-visible` true in every browser or Electron host. Control the fixture's supported focus state or drive actual keyboard input, isolate previous focus, and verify the state before asserting styles. Do not skip a failed focus assertion or weaken it to mere `activeElement` equality. +- When exact theme colors are the contract, load and assert those tokens. When preserving platform styling is the contract, assert a visible nonzero focus boundary instead of an unrelated hardcoded color. Include the relevant production stylesheet cascade in either case. +- Exercise both forced-focus and natural-focus fixture modes. Wait for a focus-triggered hover only when focus was actually requested. Check readiness, idle, and remount so an async tooltip is not captured accidentally or awaited forever. +- In missing-token tests, distinguish local removal from inherited values. If an ancestor supplies the property, use a scoped guaranteed-invalid value such as a self-reference to exercise `var()` fallback without changing global theme state. A fallback does not repair a defined value with the wrong CSS type. +- Hit-test the intended action region, allowing the hit element to be the control or one of its descendants, then activate it and assert the behavior or ARIA change. Exact root equality is brittle; CSS styling alone does not prove that labels, chevrons, or edge padding remain clickable. + ## 7. No Hardcoded Visual Values Reviewers will always flag hardcoded colors, shadows, sizes that should use theme tokens or CSS variables. @@ -142,7 +217,6 @@ Reviewers will always flag hardcoded colors, shadows, sizes that should use them **Size, spacing, radius, font and stroke** values have their own design-system **size** tokens (and decision logic — snap maps, the pill→`circle` rule, and the compact-glyph convention). Those live in the **ux-css-layout** skill (§10 Design-System Size Tokens) and the auto-injected `.github/instructions/design-tokens.instructions.md`. Reach for those when a flag is about *how big / how round / how bold* something is rather than *what color*. - --- ## Key Files diff --git a/.github/workflows/pr-linux-test.yml b/.github/workflows/pr-linux-test.yml index bb37cbd70be7..3251a9c1fcd4 100644 --- a/.github/workflows/pr-linux-test.yml +++ b/.github/workflows/pr-linux-test.yml @@ -411,8 +411,9 @@ jobs: env: DEBUG: "*browser*" + # The node.js integration tests never launch an extension host, so they don't use these extensions - name: Compile extensions for integration tests & smoke tests - if: ${{ env.INTEGRATION_TESTS == 'true' || env.SMOKE_TESTS == 'true' }} + if: ${{ (env.INTEGRATION_TESTS == 'true' && env.INTEGRATION_TEST_SUITE != 'node') || env.SMOKE_TESTS == 'true' }} run: | set -e pnpm run gulp \ diff --git a/.github/workflows/pr-win32-test.yml b/.github/workflows/pr-win32-test.yml index 74bc4542ebca..f30ef401cd79 100644 --- a/.github/workflows/pr-win32-test.yml +++ b/.github/workflows/pr-win32-test.yml @@ -275,8 +275,9 @@ jobs: env: DEBUG: "*browser*" + # The node.js integration tests never launch an extension host, so they don't use these extensions - name: Compile extensions for integration tests & smoke tests - if: ${{ env.INTEGRATION_TESTS == 'true' || env.SMOKE_TESTS == 'true' }} + if: ${{ (env.INTEGRATION_TESTS == 'true' && env.INTEGRATION_TEST_SUITE != 'node') || env.SMOKE_TESTS == 'true' }} shell: pwsh run: | . build/azure-pipelines/win32/exec.ps1 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index e6cecd98ddca..cd76c6be3671 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -63,7 +63,7 @@ jobs: outputs: checks-failed: ${{ steps.failed-checks.outputs.failed }} env: - # Hygiene and ESLint check only the files that changed since this commit, unless + # Hygiene and oxlint check only the files that changed since this commit, unless # a change can affect other files (see build/lib/changedFiles.ts). The full checks # run in the scheduled and manual product builds. PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -73,9 +73,9 @@ jobs: with: submodules: recursive - # Without the base commit, hygiene and ESLint check every file. + # Without the base commit, hygiene and oxlint check every file. - name: Fetch pull request base - run: git fetch --no-tags --depth=1 origin "$PR_BASE_SHA" || echo "::warning::Could not fetch $PR_BASE_SHA; hygiene and ESLint will check every file." + run: git fetch --no-tags --depth=1 origin "$PR_BASE_SHA" || echo "::warning::Could not fetch $PR_BASE_SHA; hygiene and oxlint will check every file." - name: Setup Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 @@ -151,12 +151,13 @@ jobs: pnpm -C extensions/markdown-language-features run test-markdown-editor-package-json pnpm -C extensions/markdown-language-features run test-markdown-editor-clipboard - # Hygiene and ESLint check only the changed files, so they take seconds and fail the job + # Hygiene and oxlint check only the changed files, so they take seconds and fail the job # before the compilation checks start. --continue-on-error reports both when both fail. - # ESLint stays out of the compilation checks so that its worker memory doesn't overlap theirs. - - name: Hygiene & ESLint + # oxlint runs the rules of eslint.config.js (see oxlint.config.ts). It stays out of the + # compilation checks so that the memory of its processes doesn't overlap theirs. + - name: Hygiene & oxlint id: hygiene - run: pnpm exec npm-run-all2 -lp --continue-on-error "hygiene --changed-since $PR_BASE_SHA" "eslint --changed-since $PR_BASE_SHA" + run: pnpm exec npm-run-all2 -lp --continue-on-error "hygiene --changed-since $PR_BASE_SHA" "oxlint --changed-since $PR_BASE_SHA" # core-ci-pr skips the minified bundles that only the product build uses. - name: Compile diff --git a/.vscode/notebooks/endgame.github-issues b/.vscode/notebooks/endgame.github-issues index c8df3f7675ea..f7167ce35101 100644 --- a/.vscode/notebooks/endgame.github-issues +++ b/.vscode/notebooks/endgame.github-issues @@ -7,7 +7,7 @@ { "kind": 2, "language": "github-issues", - "value": "$MILESTONE=milestone:\"1.145.0\"\n\n$TPI_CREATION=2026-03-23 // Used to find fixes that need to be verified" + "value": "$MILESTONE=milestone:\"1.146.0\"\n\n$TPI_CREATION=2026-03-23 // Used to find fixes that need to be verified" }, { "kind": 1, diff --git a/.vscode/notebooks/my-endgame.github-issues b/.vscode/notebooks/my-endgame.github-issues index 57180bfe8ca2..ead4ce74f855 100644 --- a/.vscode/notebooks/my-endgame.github-issues +++ b/.vscode/notebooks/my-endgame.github-issues @@ -7,7 +7,7 @@ { "kind": 2, "language": "github-issues", - "value": "$MILESTONE=milestone:\"1.145.0\"\n\n$MINE=assignee:@me" + "value": "$MILESTONE=milestone:\"1.146.0\"\n\n$MINE=assignee:@me" }, { "kind": 2, diff --git a/.vscode/settings.json b/.vscode/settings.json index 71c252d696f0..bf0b3e5dccc7 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,7 +9,8 @@ }, "chat.editing.explainChanges.enabled": true, "chat.artifactIntegrations.githubPullRequests.autoMarkReadyIgnoredChecks": [ - "VS Code PR Check" + "VS Code PR Check", + "Proof of Presence" ], // --- Editor --- "editor.insertSpaces": false, @@ -208,7 +209,6 @@ "sash" ], // --- Workbench --- - "editor.aiStats.enabled": true, // Team selfhosting on ai stats "multiDiffEditor.experimental.fileList": true, "azureMcp.enabledServices": [ "kusto" // Needed for kusto tool in data.prompt.md diff --git a/.vscode/tasks.json b/.vscode/tasks.json index fe4251108e25..212d111b3b74 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -508,7 +508,7 @@ ], "group": "build", "label": "tsec-compile-check", - "detail": "node_modules/tsec/bin/tsec -p src/tsconfig.json --noEmit" + "detail": "Runs the tsec security rules over src/tsconfig.tsec.json" }, { "label": "Launch Monaco Editor Vite", diff --git a/build/agent-sdk/package.ts b/build/agent-sdk/package.ts index 30c8b0c0cc0e..43134c1216d5 100644 --- a/build/agent-sdk/package.ts +++ b/build/agent-sdk/package.ts @@ -72,6 +72,7 @@ export async function buildOne(args: IBuildArgs): Promise { const agentDir = getAgentDir(args.sdk); const stagingDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-sdk-pkg-')); + const cleanUp = [stagingDir]; try { // Copy the pinned package.json + package-lock.json into the scratch // dir. `npm ci` errors out if a node_modules is already present, so @@ -86,9 +87,10 @@ export async function buildOne(args: IBuildArgs): Promise { if (libc) { npmEnv.npm_config_libc = libc; } - npmCi(stagingDir, npmEnv); - const nodeModulesDir = path.join(stagingDir, 'node_modules'); + // npm's debug logs go next to the staging dir, not into it, so they never end up in the tarball. + const npmLogsDir = `${stagingDir}-npm-logs`; + cleanUp.push(npmLogsDir); // The SDK ships its native binary in a per-platform package declared as // an *optional* dependency (e.g. `@openai/codex-linux-x64`). npm does not @@ -96,12 +98,22 @@ export async function buildOne(args: IBuildArgs): Promise { // registry hiccup can leave the base package present but the native // package missing — which would silently produce a binary-less tarball // and upload it to the (immutable, content-addressed) CDN path, failing - // only at runtime for end users. Fail loud here instead. + // only at runtime for end users. Fail loud here instead, but only after + // retrying the install, since the skipped download is usually transient. // See https://github.com/microsoft/vscode/pull/323881. - const missingNativeDep = findMissingNativeOptionalDep(nodeModulesDir, packageName, args.sdkTarget); - if (missingNativeDep) { - throw new Error(`[${SCRIPT}] npm ci left ${packageName}@${sdkVersion} without its native package '${missingNativeDep}' for target ${args.sdkTarget} — the optional dependency was silently skipped. Refusing to build a binary-less tarball; re-run to re-fetch it.`); - } + await installWithRetry({ + install: () => npmCi(stagingDir, npmEnv, npmLogsDir), + isRetryableError: error => error instanceof NpmCiExitError, + findProblem: () => { + const missingNativeDep = findMissingNativeOptionalDep(nodeModulesDir, packageName, args.sdkTarget); + if (!missingNativeDep) { + return undefined; + } + printNpmLogLines(npmLogsDir, missingNativeDep); + return `[${SCRIPT}] npm ci left ${packageName}@${sdkVersion} without its native package '${missingNativeDep}' for target ${args.sdkTarget} — the optional dependency was silently skipped. Refusing to build a binary-less tarball; re-run to re-fetch it.`; + }, + reset: () => fs.rmSync(nodeModulesDir, { recursive: true, force: true }), + }); chmodPlatformBinaries(nodeModulesDir, args.sdk, args.sdkTarget); @@ -119,7 +131,9 @@ export async function buildOne(args: IBuildArgs): Promise { console.log(`[${SCRIPT}] Wrote ${tgzPath} (${sizeBytes} bytes, sha256=${sha256})`); return { tgzPath, sha256, sdkVersion, sizeBytes }; } finally { - fs.rmSync(stagingDir, { recursive: true, force: true }); + for (const dir of cleanUp) { + fs.rmSync(dir, { recursive: true, force: true }); + } } } @@ -276,7 +290,74 @@ function verifySdkLoads(stagingDir: string, entry: string, context: string): voi } } -function npmCi(workDir: string, env: NodeJS.ProcessEnv): void { +/** Delays before the second and third install attempts. */ +export const INSTALL_RETRY_DELAYS_MS: readonly number[] = [10_000, 30_000]; + +export interface IInstallWithRetryOptions { + /** Runs the install; throws when it fails. */ + readonly install: () => void; + /** Whether an error thrown by `install` is worth retrying. Other errors fail on the first attempt. */ + readonly isRetryableError: (error: unknown) => boolean; + /** Describes what the install left broken, or returns `undefined` when the result is complete. */ + readonly findProblem: () => string | undefined; + /** Clears a failed install before the next attempt. */ + readonly reset: () => void; + readonly delaysMs?: readonly number[]; + readonly sleep?: (ms: number) => Promise; +} + +/** + * Runs `install` until it succeeds and `findProblem` finds nothing, retrying a + * failed or incomplete install after each delay. Throws the last problem when + * every attempt fails. + */ +export async function installWithRetry(options: IInstallWithRetryOptions): Promise { + const delaysMs = options.delaysMs ?? INSTALL_RETRY_DELAYS_MS; + const sleep = options.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))); + for (let attempt = 1; ; attempt++) { + let problem: string | undefined; + try { + options.install(); + problem = options.findProblem(); + } catch (error) { + if (!options.isRetryableError(error)) { + throw error; + } + problem = error instanceof Error ? error.message : String(error); + } + if (problem === undefined) { + return; + } + const delay = delaysMs[attempt - 1]; + if (delay === undefined) { + throw new Error(problem); + } + console.warn(`[${SCRIPT}] Install attempt ${attempt} of ${delaysMs.length + 1} failed: ${problem} Retrying in ${delay / 1000}s.`); + options.reset(); + await sleep(delay); + } +} + +/** Prints the lines of npm's latest debug log that mention `packageName`, which say why npm skipped it. */ +function printNpmLogLines(logsDir: string, packageName: string): void { + let files: string[]; + try { + files = fs.readdirSync(logsDir).filter(file => file.endsWith('.log')).sort(); + } catch { + return; + } + const latest = files.at(-1); + if (!latest) { + return; + } + const lines = fs.readFileSync(path.join(logsDir, latest), 'utf8').split(/\r?\n/).filter(line => line.includes(packageName)); + console.warn(`[${SCRIPT}] npm debug log lines for '${packageName}' (${latest}):`); + for (const line of lines.slice(-40)) { + console.warn(` ${line}`); + } +} + +function npmCi(workDir: string, env: NodeJS.ProcessEnv, logsDir: string): void { // `npm ci` rather than `npm install`: installs the exact graph from the // committed package-lock.json without resolving versions, which is what // makes the tarball bytes reproducible across runs. @@ -295,7 +376,7 @@ function npmCi(workDir: string, env: NodeJS.ProcessEnv): void { // refuses to spawn .cmd/.bat without it. const isWindows = process.platform === 'win32'; const npm = isWindows ? 'npm.cmd' : 'npm'; - const result = spawnSync(npm, ['ci', '--ignore-scripts', '--omit=peer'], { + const result = spawnSync(npm, ['ci', '--ignore-scripts', '--omit=peer', isWindows ? `--logs-dir="${logsDir}"` : `--logs-dir=${logsDir}`], { cwd: workDir, env: { ...process.env, ...env }, stdio: 'inherit', @@ -305,10 +386,13 @@ function npmCi(workDir: string, env: NodeJS.ProcessEnv): void { throw new Error(`[${SCRIPT}] npm ci failed to spawn: ${result.error.message}`); } if (result.status !== 0) { - throw new Error(`[${SCRIPT}] npm ci exited ${result.status}`); + throw new NpmCiExitError(`[${SCRIPT}] npm ci exited ${result.status}`); } } +/** `npm ci` ran but exited non-zero, for example after a network timeout. */ +class NpmCiExitError extends Error { } + /** * Builds the gzipped tar via node-tar. Same library on every host, so the * output is consistent regardless of whether GNU/BSD/Windows tar is what diff --git a/build/agent-sdk/test/installRetry.test.ts b/build/agent-sdk/test/installRetry.test.ts new file mode 100644 index 000000000000..3be8ab05f7a3 --- /dev/null +++ b/build/agent-sdk/test/installRetry.test.ts @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { suite, test } from 'node:test'; +import { installWithRetry } from '../package.ts'; + +suite('Agent SDK install retry', () => { + class RetryableError extends Error { } + + function run(outcomes: ('ok' | 'missing' | 'throws' | 'fatal')[]) { + const events: string[] = []; + let attempt = 0; + const promise = installWithRetry({ + install: () => { + events.push('install'); + if (outcomes[attempt] === 'throws') { + attempt++; + throw new RetryableError('npm ci exited 1'); + } + if (outcomes[attempt] === 'fatal') { + attempt++; + throw new Error('npm ci failed to spawn'); + } + }, + isRetryableError: error => error instanceof RetryableError, + findProblem: () => outcomes[attempt++] === 'missing' ? 'native package missing.' : undefined, + reset: () => events.push('reset'), + delaysMs: [10, 30], + sleep: async ms => { events.push(`sleep ${ms}`); }, + }); + return { promise, events }; + } + + test('does not retry a complete install', async () => { + const { promise, events } = run(['ok']); + await promise; + assert.deepStrictEqual(events, ['install']); + }); + + test('retries when the native package was skipped, then succeeds', async () => { + const { promise, events } = run(['missing', 'ok']); + await promise; + assert.deepStrictEqual(events, ['install', 'reset', 'sleep 10', 'install']); + }); + + test('retries when npm ci fails, then succeeds', async () => { + const { promise, events } = run(['throws', 'missing', 'ok']); + await promise; + assert.deepStrictEqual(events, ['install', 'reset', 'sleep 10', 'install', 'reset', 'sleep 30', 'install']); + }); + + test('throws the last problem when every attempt fails', async () => { + const { promise, events } = run(['missing', 'throws', 'missing']); + await assert.rejects(promise, /native package missing/); + assert.deepStrictEqual(events, ['install', 'reset', 'sleep 10', 'install', 'reset', 'sleep 30', 'install']); + }); + test('does not retry other install errors', async () => { + const { promise, events } = run(['fatal', 'ok']); + await assert.rejects(promise, /failed to spawn/); + assert.deepStrictEqual(events, ['install']); + }); +}); diff --git a/build/azure-pipelines/alpine/product-build-alpine-cli.yml b/build/azure-pipelines/alpine/product-build-alpine-cli.yml index ac07322377de..84fcfa94594b 100644 --- a/build/azure-pipelines/alpine/product-build-alpine-cli.yml +++ b/build/azure-pipelines/alpine/product-build-alpine-cli.yml @@ -20,14 +20,9 @@ jobs: variables: VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} templateContext: - # Defender for Linux can fold the 1ES PT antimalware scan of the outputs into a scan of system - # folders (/opt, /usr/lib) that started before the job, which blocks it for 45-55 min, so the - # job times out before publishing the outputs. A scan that times out completes the step with - # issues and the outputs are published. Until that's fixed the cap is 2 min, which also stops - # some scans that aren't blocked (up to 6 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputs: - ${{ if not(parameters.VSCODE_CHECK_ONLY) }}: - output: pipelineArtifact @@ -109,10 +104,10 @@ jobs: # inspired by: https://github.com/emk/rust-musl-builder/blob/main/Dockerfile - bash: | set -e - sudo apt-get update - sudo apt-get install -yq build-essential musl-dev musl-tools linux-libc-dev pkgconf xutils-dev lld + ./build/azure-pipelines/linux/apt-install-with-retry.sh build-essential musl-dev musl-tools linux-libc-dev pkgconf xutils-dev lld sudo ln -s "/usr/bin/g++" "/usr/bin/musl-g++" || echo "link exists" displayName: Install musl build dependencies + timeoutInMinutes: 25 - template: ../cli/install-rust-posix.yml@self parameters: diff --git a/build/azure-pipelines/alpine/product-build-alpine-node-modules.yml b/build/azure-pipelines/alpine/product-build-alpine-node-modules.yml deleted file mode 100644 index 958031ac91b2..000000000000 --- a/build/azure-pipelines/alpine/product-build-alpine-node-modules.yml +++ /dev/null @@ -1,161 +0,0 @@ -parameters: - - name: VSCODE_ARCH - type: string - -jobs: - - job: LinuxAlpine_${{ parameters.VSCODE_ARCH }} - displayName: Linux Alpine (${{ upper(parameters.VSCODE_ARCH) }}) - pool: - name: 1es-ubuntu-22.04-x64 - os: linux - timeoutInMinutes: 60 - variables: - NPM_ARCH: ${{ parameters.VSCODE_ARCH }} - VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} - steps: - - template: ../common/checkout.yml@self - - - template: ../common/setup-node.yml@self - parameters: - os: linux - - - template: ../distro/download-distro.yml@self - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get Secrets" - inputs: - azureSubscription: vscode-oss-build-secrets - KeyVaultName: vscode-oss-build-secrets - SecretsFilter: "github-token-code-oss" - - - script: node build/setup-npm-registry.ts $NPM_REGISTRY - condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Registry - - - template: ../common/apply-sdk-canary.yml@self - - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts alpine $VSCODE_ARCH $(node -p process.arch) alpine-3.22 > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: | - set -e - # Set the private NPM registry to the global npmrc file - # so that authentication works for subfolders like build/, remote/, extensions/ etc - # which does not have their own .npmrc file - npm config set registry "$NPM_REGISTRY" - echo "##vso[task.setvariable variable=NPMRC_PATH]$(npm config get userconfig)" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM - - - task: npmAuthenticate@0 - inputs: - workingFile: $(NPMRC_PATH) - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Authentication - - - template: ../common/install-pnpm.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - task: NuGetAuthenticate@1 - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Setup NuGet Authentication - - - template: ../common/setup-qemu.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['NPM_ARCH'], 'arm64')) - - - task: Docker@1 - inputs: - azureSubscriptionEndpoint: vscode - azureContainerRegistry: vscodehub.azurecr.io - command: "Run an image" - imageName: "vscode-linux-build-agent:alpine-$(VSCODE_ARCH)" - arguments: --pull=always - containerCommand: uname - displayName: "Pull image" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: sudo apt-get update && sudo apt-get install -y libkrb5-dev - displayName: Install build dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - mkdir -p .build/nodejs-musl - NODE_VERSION=$(node -p "require('./remote/package.json').nativeBuild.target") - BUILD_ID=$(node -p "require('./remote/package.json').nativeBuild.msBuildId") - az artifacts universal download \ - --organization "https://dev.azure.com/monacotools" \ - --project "Monaco" \ - --scope project \ - --feed "vscode-node" \ - --name "node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar" \ - --version "${NODE_VERSION}-${BUILD_ID}" \ - --path .build/nodejs-musl \ - --only-show-errors - tar -xzf ".build/nodejs-musl/node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar.gz" -C ".build/nodejs-musl" --strip-components=1 - rm ".build/nodejs-musl/node-v${NODE_VERSION}-linux-${VSCODE_ARCH}-musl.tar.gz" - env: - AZURE_DEVOPS_EXT_PAT: "$(System.AccessToken)" - displayName: Download NodeJS MUSL - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: pnpm run preinstall - displayName: Install Electron headers - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - - for i in {1..5}; do # try 5 times - pnpm install --frozen-lockfile && break - if [ $i -eq 5 ]; then - echo "pnpm install failed too many times" >&2 - exit 1 - fi - echo "pnpm install failed $i, trying again..." - done - env: - npm_config_arch: $(NPM_ARCH) - ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - GITHUB_TOKEN: "$(github-token-code-oss)" - FOUNDRY_LOCAL_NUGET_MODE: dotnet - FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" - VSCODE_REMOTE_DEPENDENCIES_CONTAINER_NAME: vscodehub.azurecr.io/vscode-linux-build-agent:alpine-$(VSCODE_ARCH) - VSCODE_HOST_MOUNT: "/mnt/vss/_work/1/s" - VSCODE_NPMRC_PATH: $(NPMRC_PATH) - displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - # NuGetAuthenticate@1 exposes its access token to all later steps as the - # VSS_NUGET_ACCESSTOKEN environment variable, from where they can write it - # to logs. Only installing dependencies needs it, so clear it now. - - script: echo "##vso[task.setvariable variable=VSS_NUGET_ACCESSTOKEN]" - displayName: Clear package feed credentials - condition: always() - - - script: node build/azure-pipelines/common/checkNativeOptionalDeps.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Verify native optional dependency binaries - - - script: node build/azure-pipelines/distro/mixin-npm.ts - displayName: Mixin distro node modules - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive diff --git a/build/azure-pipelines/alpine/product-build-alpine.yml b/build/azure-pipelines/alpine/product-build-alpine.yml index 491759868e68..74c4b4f0476d 100644 --- a/build/azure-pipelines/alpine/product-build-alpine.yml +++ b/build/azure-pipelines/alpine/product-build-alpine.yml @@ -82,20 +82,10 @@ jobs: condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts alpine $VSCODE_ARCH $(node -p process.arch) alpine-3.22 > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ../common/restore-pnpm-store.yml@self + parameters: + keyArgs: alpine $(VSCODE_ARCH) alpine-3.22 + os: linux - script: | set -e @@ -120,7 +110,7 @@ jobs: - template: ../common/setup-qemu.yml@self parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['NPM_ARCH'], 'arm64')) + condition: and(succeeded(), eq(variables['NPM_ARCH'], 'arm64')) - task: Docker@1 inputs: @@ -131,11 +121,10 @@ jobs: arguments: --pull=always containerCommand: uname displayName: "Pull image" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - script: sudo apt-get update && sudo apt-get install -y libkrb5-dev + - script: ./build/azure-pipelines/linux/apt-install-with-retry.sh libkrb5-dev displayName: Install build dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) + timeoutInMinutes: 25 - script: | set -e @@ -156,11 +145,9 @@ jobs: env: AZURE_DEVOPS_EXT_PAT: "$(System.AccessToken)" displayName: Download NodeJS MUSL - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: pnpm run preinstall displayName: Install Electron headers - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: | set -e @@ -184,7 +171,6 @@ jobs: VSCODE_HOST_MOUNT: "/mnt/vss/_work/1/s" VSCODE_NPMRC_PATH: $(NPMRC_PATH) displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where they can write it @@ -198,15 +184,10 @@ jobs: - script: node build/azure-pipelines/distro/mixin-npm.ts displayName: Mixin distro node modules - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../common/prune-pnpm-store.yml@self + parameters: + os: linux - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality diff --git a/build/azure-pipelines/common/apply-sdk-canary.yml b/build/azure-pipelines/common/apply-sdk-canary.yml index 08a8394f9044..415ded067e5f 100644 --- a/build/azure-pipelines/common/apply-sdk-canary.yml +++ b/build/azure-pipelines/common/apply-sdk-canary.yml @@ -1,7 +1,7 @@ # Copilot product dependency integration (no-op unless an override is set). # Overrides @github/copilot-sdk with a version published to the private feed, -# records its bundled runtime version, and refreshes the lockfile so the -# node_modules cache key below misses and `pnpm install` installs the canary. +# records its bundled runtime version, and refreshes the lockfile so that +# `pnpm install` installs the canary. # Authenticates before the standard npmAuthenticate step. # See microsoft/vscode-engineering specs/sdk-vscode-integration.spec.md. diff --git a/build/azure-pipelines/common/cacheKeys.ts b/build/azure-pipelines/common/cacheKeys.ts index 0714ce004a84..b66ccac5ef6e 100644 --- a/build/azure-pipelines/common/cacheKeys.ts +++ b/build/azure-pipelines/common/cacheKeys.ts @@ -104,6 +104,39 @@ export function computeNodeModulesBaseCacheKey(args: readonly string[], readFile return shasum.digest('hex'); } +/** + * Computes the key of the pnpm stores that a job can start from: the cache salt, the pnpm version, + * which decides the layout of the store, and the given arguments (the platform of the job). A store + * holds the files of every package that it ever installed, so a job can start from the store of + * other dependencies and download only the packages that it is missing. + */ +export function computePnpmStoreBaseCacheKey(args: readonly string[], readFile: ReadRepositoryFile = readRepositoryFile): string { + const shasum = crypto.createHash('sha256'); + + shasum.update(readFile('build/.cachesalt')); + shasum.update(JSON.stringify(JSON.parse(readFile('package.json').toString()).packageManager)); + + for (const arg of args) { + shasum.update(arg); + } + + return shasum.digest('hex'); +} + +/** + * Computes the pnpm store cache key from the `pnpm-lock.yaml` of every install root: the packages + * that the store holds after installing them. Use it after {@link computePnpmStoreBaseCacheKey}. + */ +export function computePnpmStoreCacheKey(readFile: ReadRepositoryFile = readRepositoryFile): string { + const shasum = crypto.createHash('sha256'); + + for (const dir of ['', ...separateRoots, ...distroRoots]) { + shasum.update(readFile(path.posix.join(dir, 'pnpm-lock.yaml'))); + } + + return shasum.digest('hex'); +} + /** * Computes the built-in extensions cache key from the built-in extensions in `product.json`. * diff --git a/build/azure-pipelines/common/computeChangedSince.ts b/build/azure-pipelines/common/computeChangedSince.ts index b30f7fa92abe..d3ec4f620fcf 100644 --- a/build/azure-pipelines/common/computeChangedSince.ts +++ b/build/azure-pipelines/common/computeChangedSince.ts @@ -66,7 +66,7 @@ function git(args: readonly string[]): string { } /** - * Sets VSCODE_CHANGED_SINCE to the commit that the commits of the build start from, so that hygiene and ESLint check + * Sets VSCODE_CHANGED_SINCE to the commit that the commits of the build start from, so that hygiene and oxlint check * only the files those commits change. Leaves it unset, so that they check every file, when that commit cannot be * determined. */ @@ -89,12 +89,12 @@ async function main(): Promise { const firstParentHistory = git(['rev-list', '--first-parent', `--max-count=${depth}`, head]).split('\n').filter(commit => !!commit); const base = findBaseCommit(head, commits, firstParentHistory); - console.log(`Hygiene and ESLint will check the files that the ${commits.length} commit${commits.length === 1 ? '' : 's'} of the build change since ${base}.`); + console.log(`Hygiene and oxlint will check the files that the ${commits.length} commit${commits.length === 1 ? '' : 's'} of the build change since ${base}.`); console.log(`##vso[task.setvariable variable=VSCODE_CHANGED_SINCE]${base}`); } if (import.meta.main) { main().catch(error => { - console.log(`##vso[task.logissue type=warning]Hygiene and ESLint will check every file: ${error instanceof Error ? error.message : String(error)}`); + console.log(`##vso[task.logissue type=warning]Hygiene and oxlint will check every file: ${error instanceof Error ? error.message : String(error)}`); }); } diff --git a/build/azure-pipelines/common/computePnpmStoreCacheKey.ts b/build/azure-pipelines/common/computePnpmStoreCacheKey.ts new file mode 100644 index 000000000000..eab258d97b09 --- /dev/null +++ b/build/azure-pipelines/common/computePnpmStoreCacheKey.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import fs from 'fs'; +import path from 'path'; +import { computePnpmStoreBaseCacheKey, computePnpmStoreCacheKey } from './cacheKeys.ts'; + +// Writes the files of the pnpm store cache key (see restore-pnpm-store.yml): `.build/pnpmstorebase`, for +// the platform of the job (the arguments, and the platform and architecture that pnpm installs the +// optional dependencies of), and `.build/pnpmstorelockfiles`, for the lockfiles. +// +// In Azure Pipelines it also points pnpm at the cached store for the later steps of the job: +// PNPM_CONFIG_STORE_DIR, outside of the sources but on their volume, so that pnpm can hard link from +// it, and PNPM_CONFIG_CACHE_DIR inside it. Steps templates set them here, as they can't declare job +// variables. + +const root = path.join(import.meta.dirname, '../../../'); +fs.mkdirSync(path.join(root, '.build'), { recursive: true }); +fs.writeFileSync(path.join(root, '.build', 'pnpmstorebase'), computePnpmStoreBaseCacheKey([...process.argv.slice(2), process.platform, process.arch])); +fs.writeFileSync(path.join(root, '.build', 'pnpmstorelockfiles'), computePnpmStoreCacheKey()); + +if (process.env['TF_BUILD'] && process.env['PIPELINE_WORKSPACE']) { + const storeDir = path.join(process.env['PIPELINE_WORKSPACE'], 'pnpm-store'); + console.log(`##vso[task.setvariable variable=PNPM_CONFIG_STORE_DIR]${storeDir}`); + console.log(`##vso[task.setvariable variable=PNPM_CONFIG_CACHE_DIR]${path.join(storeDir, 'cache')}`); +} diff --git a/build/azure-pipelines/common/install-pnpm.yml b/build/azure-pipelines/common/install-pnpm.yml index 481e573e26c6..335e0825a3cf 100644 --- a/build/azure-pipelines/common/install-pnpm.yml +++ b/build/azure-pipelines/common/install-pnpm.yml @@ -1,5 +1,5 @@ parameters: - # Condition of the steps, for example to install pnpm only when the node_modules cache missed. + # Condition of the steps, for example to install pnpm only when the job validates the dependencies. - name: condition type: string default: succeeded() diff --git a/build/azure-pipelines/common/mixin-vscode-capi.yml b/build/azure-pipelines/common/mixin-vscode-capi.yml index b03c54d68ccd..edf7b978a2e3 100644 --- a/build/azure-pipelines/common/mixin-vscode-capi.yml +++ b/build/azure-pipelines/common/mixin-vscode-capi.yml @@ -8,6 +8,28 @@ steps: retryCountOnTaskFailure: 3 displayName: Checkout microsoft/vscode-capi + # microsoft/vscode-capi has no .gitattributes, so Git checks out its files with CRLF line endings on Windows. The + # Copilot mixin (see ../copilot/builtin-steps.yml) compares its LICENSE with a string that has LF line endings, and + # copies its Copilot license into the extension, so check them out with LF line endings, as on Linux and macOS. + - pwsh: | + $ErrorActionPreference = 'Stop' + + function Invoke-CheckedCommand([scriptblock] $Command) { + & $Command + if ($LASTEXITCODE -ne 0) { + $commandText = $Command.ToString().Trim() + throw "Command failed with exit code ${LASTEXITCODE}: ${commandText}" + } + } + + $CapiPath = Join-Path '$(Build.SourcesDirectory)' '.build/vscode-capi' + Invoke-CheckedCommand { git -C $CapiPath config core.autocrlf false } + # Remove the files from the index, so that the reset writes all of them again. + Invoke-CheckedCommand { git -C $CapiPath rm --cached -r --quiet . } + Invoke-CheckedCommand { git -C $CapiPath reset --hard --quiet } + condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT')) + displayName: Check out vscode-capi with LF line endings + # npm ci starts from a clean node_modules, so it is safe to retry; transient registry errors # here (ENOTFOUND, ECONNRESET, E503, ETIMEDOUT) failed 8 main CI builds in 90 days. - pwsh: | diff --git a/build/azure-pipelines/common/prune-pnpm-store.yml b/build/azure-pipelines/common/prune-pnpm-store.yml new file mode 100644 index 000000000000..1ee9362de956 --- /dev/null +++ b/build/azure-pipelines/common/prune-pnpm-store.yml @@ -0,0 +1,33 @@ +parameters: + # Operating system of the job (linux, macOS or windows), for templates that know it: only the step + # for that OS is added. Empty adds both, and the one for the other OS is skipped at run time. + - name: os + type: string + default: '' + +# Removes the packages that the installed projects don't use from the pnpm store that +# restore-pnpm-store.yml restored, when the cache saves it at the end of the job (its key missed). +# Also removes the store's links to those projects (in `projects`): the cache follows links when it +# archives the store on Windows, and the next installation adds its own. Include it after the last +# installation of the job. A failure doesn't fail the job (continueOnError), and the cache then +# doesn't save the store. +steps: + - ${{ if ne(parameters.os, 'windows') }}: + - script: | + set -e + pnpm store prune + rm -rf "$(pnpm store path)/projects" + condition: and(succeeded(), ne(variables.PNPM_STORE_RESTORED, 'true'), ne(variables['Agent.OS'], 'Windows_NT')) + displayName: Prune pnpm store + continueOnError: true + + - ${{ if or(eq(parameters.os, ''), eq(parameters.os, 'windows')) }}: + - powershell: | + . $env:BUILD_SOURCESDIRECTORY/build/azure-pipelines/win32/exec.ps1 + $ErrorActionPreference = "Stop" + exec { pnpm store prune } + $StorePath = (pnpm store path) + Remove-Item -Recurse -Force -ErrorAction SilentlyContinue (Join-Path $StorePath "projects") + condition: and(succeeded(), ne(variables.PNPM_STORE_RESTORED, 'true'), eq(variables['Agent.OS'], 'Windows_NT')) + displayName: Prune pnpm store + continueOnError: true diff --git a/build/azure-pipelines/common/publish.ts b/build/azure-pipelines/common/publish.ts index aa6ca5973526..be1c46939626 100644 --- a/build/azure-pipelines/common/publish.ts +++ b/build/azure-pipelines/common/publish.ts @@ -11,6 +11,7 @@ import { pipeline } from 'node:stream/promises'; import yauzl from 'yauzl'; import crypto from 'crypto'; import { retry } from './retry.ts'; +import { getGatingJob, type IGatingJob, type Timeline, type TimelineRecord } from './publishGate.ts'; import { getCertificatesFromPFX, getKeyFromPFX } from '../../lib/pfx.ts'; import { CosmosClient } from '@azure/cosmos'; import { Worker, isMainThread, workerData } from 'node:worker_threads'; @@ -601,18 +602,6 @@ async function getPipelineArtifacts(): Promise { return result.value.filter(a => /^vscode_/.test(a.name) && !/sbom$/.test(a.name)); } -interface TimelineRecord { - readonly name: string; - readonly identifier?: string; - readonly type: string; - readonly state: string; - readonly result: string; -} - -interface Timeline { - readonly records: TimelineRecord[]; -} - /** * Whether the timeline record is the given stage. Stages are matched by their * YAML identifier, since the record name is the stage's display name when one @@ -626,93 +615,6 @@ async function getPipelineTimeline(): Promise { return await requestAZDOAPI('timeline'); } -/** - * Artifacts that can only be published once a job succeeded, by job name. The - * platform test jobs run in parallel with the jobs that produce these artifacts - * (see the platform-specific product-build job templates). The tests of a - * platform can be sharded across several jobs named `_`, in - * which case every shard must succeed. - */ -const artifactsByGatingJob: Readonly> = { - 'Windows_x64_Test': [ - 'vscode_client_win32_x64_setup', - 'vscode_client_win32_x64_user-setup', - 'vscode_client_win32_x64_archive', - 'vscode_server_win32_x64_archive', - 'vscode_web_win32_x64_archive', - 'vscode_cli_win32_x64_cli', - ], - 'Linux_x64_Test': [ - 'vscode_client_linux_x64_archive-unsigned', - 'vscode_client_linux_x64_deb-package', - 'vscode_client_linux_x64_rpm-package', - 'vscode_client_linux_x64_snap', - 'vscode_server_linux_x64_archive-unsigned', - 'vscode_web_linux_x64_archive-unsigned', - 'vscode_cli_linux_x64_cli', - ], - 'macOS_arm64_Test': [ - 'vscode_client_darwin_arm64_archive', - 'vscode_client_darwin_arm64_dmg', - 'vscode_server_darwin_arm64_archive', - 'vscode_web_darwin_arm64_archive', - 'vscode_cli_darwin_arm64_cli', - 'vscode_client_darwin_universal_archive', - 'vscode_client_darwin_universal_dmg', - ], -}; - -interface IGatingJob { - /** The job that blocks the publishing, or all gating jobs when none does. */ - readonly name: string; - /** `missing` when the job is not part of the pipeline run, e.g. when tests are skipped. */ - readonly state: 'succeeded' | 'pending' | 'failed' | 'missing'; -} - -/** - * Returns the job that gates the publishing of the artifact, if any, see - * `artifactsByGatingJob`. When the tests are sharded, returns a failed shard, - * else a pending one, else all shards once they all succeeded. - */ -function getGatingJob(timeline: Timeline, artifactName: string): IGatingJob | undefined { - const name = Object.keys(artifactsByGatingJob).find(job => artifactsByGatingJob[job].includes(artifactName)); - - if (!name) { - return undefined; - } - - // Job identifiers have the form `..__default`, and a retried job has a record for each attempt - const attemptsByJob = new Map(); - - for (const record of timeline.records) { - if (record.type !== 'Job') { - continue; - } - - const job = record.identifier?.split('.').find(part => part === name || part.startsWith(`${name}_`)) ?? (record.name === name ? name : undefined); - - if (job) { - attemptsByJob.set(job, [...attemptsByJob.get(job) ?? [], record]); - } - } - - if (attemptsByJob.size === 0) { - return { name, state: 'missing' }; - } - - const jobs: IGatingJob[] = [...attemptsByJob].map(([job, attempts]) => { - if (attempts.some(r => r.state === 'completed' && (r.result === 'succeeded' || r.result === 'succeededWithIssues'))) { - return { name: job, state: 'succeeded' }; - } else { - return { name: job, state: attempts.some(r => r.state !== 'completed') ? 'pending' : 'failed' }; - } - }); - - return jobs.find(job => job.state === 'failed') - ?? jobs.find(job => job.state === 'pending') - ?? { name: jobs.map(job => job.name).join(', '), state: 'succeeded' }; -} - async function downloadArtifact(artifact: Artifact, downloadPath: string): Promise { const abortController = new AbortController(); const timeout = setTimeout(() => abortController.abort(), 4 * 60 * 1000); @@ -780,7 +682,7 @@ interface Asset { } // Contains all of the logic for mapping details to our actual product names in CosmosDB -function getPlatform(product: string, os: string, arch: string, type: string): string { +export function getPlatform(product: string, os: string, arch: string, type: string): string { switch (os) { case 'win32': switch (product) { @@ -830,6 +732,9 @@ function getPlatform(product: string, os: string, arch: string, type: string): s if (arch === 'standalone') { return 'web-standalone'; } + if (arch === 'mobile') { + return 'web-mobile'; + } return `server-linux-${arch}-web`; default: throw new Error(`Unrecognized: ${product} ${os} ${arch} ${type}`); diff --git a/build/azure-pipelines/common/publishGate.ts b/build/azure-pipelines/common/publishGate.ts new file mode 100644 index 000000000000..1b216eda5df6 --- /dev/null +++ b/build/azure-pipelines/common/publishGate.ts @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export interface TimelineRecord { + readonly name: string; + readonly identifier?: string; + readonly type: string; + readonly state: string; + readonly result: string | null; +} + +export interface Timeline { + readonly records: TimelineRecord[]; +} + +/** + * Artifacts that can only be published once a job succeeded, by job name. The + * platform test jobs run in parallel with the jobs that produce these artifacts + * (see the platform-specific product-build job templates). The tests of a + * platform can be sharded across several jobs named `_`, in + * which case every shard must succeed. + */ +export const artifactsByGatingJob: Readonly> = { + 'Windows_x64_Test': [ + 'vscode_client_win32_x64_setup', + 'vscode_client_win32_x64_user-setup', + 'vscode_client_win32_x64_archive', + 'vscode_server_win32_x64_archive', + 'vscode_web_win32_x64_archive', + 'vscode_cli_win32_x64_cli', + ], + 'Linux_x64_Test': [ + 'vscode_client_linux_x64_archive-unsigned', + 'vscode_client_linux_x64_deb-package', + 'vscode_client_linux_x64_rpm-package', + 'vscode_client_linux_x64_snap', + 'vscode_server_linux_x64_archive-unsigned', + 'vscode_web_linux_x64_archive-unsigned', + 'vscode_cli_linux_x64_cli', + ], + 'macOS_arm64_Test': [ + 'vscode_client_darwin_arm64_archive', + 'vscode_client_darwin_arm64_dmg', + 'vscode_server_darwin_arm64_archive', + 'vscode_web_darwin_arm64_archive', + 'vscode_cli_darwin_arm64_cli', + 'vscode_client_darwin_universal_archive', + 'vscode_client_darwin_universal_dmg', + ], +}; + +export interface IGatingJob { + /** The job that blocks the publishing, or all gating jobs when none does. */ + readonly name: string; + /** `missing` when the job is not part of the pipeline run, e.g. when tests are skipped. */ + readonly state: 'succeeded' | 'pending' | 'failed' | 'missing'; +} + +/** + * Returns the job that gates the publishing of the artifact, if any, see + * `artifactsByGatingJob`. When the tests are sharded, returns a failed shard, + * else a pending one, else all shards once they all succeeded. + * + * Jobs are read from their `Phase` records, which exist for every job of the + * run from the moment it is queued and reflect the job's latest attempt. A job + * only gets a `Job` record once it is scheduled, so a test job that still waits + * for its compile job, or that a stage retry reset, has none yet and must not + * be mistaken for a job that isn't part of the run. + */ +export function getGatingJob(timeline: Timeline, artifactName: string): IGatingJob | undefined { + const name = Object.keys(artifactsByGatingJob).find(job => artifactsByGatingJob[job].includes(artifactName)); + + if (!name) { + return undefined; + } + + // Phase identifiers have the form `.` + const jobs: IGatingJob[] = timeline.records + .filter(record => record.type === 'Phase') + .flatMap((record): IGatingJob[] => { + const job = record.identifier?.split('.').pop(); + + if (!job || (job !== name && !job.startsWith(`${name}_`))) { + return []; + } + + if (record.state !== 'completed') { + return [{ name: job, state: 'pending' }]; + } + + // Anything else, including `skipped` when the compile job failed, blocks the publishing + return [{ name: job, state: record.result === 'succeeded' || record.result === 'succeededWithIssues' ? 'succeeded' : 'failed' }]; + }); + + if (jobs.length === 0) { + return { name, state: 'missing' }; + } + + return jobs.find(job => job.state === 'failed') + ?? jobs.find(job => job.state === 'pending') + ?? { name: jobs.map(job => job.name).join(', '), state: 'succeeded' }; +} diff --git a/build/azure-pipelines/common/releaseBuild.ts b/build/azure-pipelines/common/releaseBuild.ts index 9f1dc3cfd798..e52a9cc29808 100644 --- a/build/azure-pipelines/common/releaseBuild.ts +++ b/build/azure-pipelines/common/releaseBuild.ts @@ -40,7 +40,7 @@ async function getConfig(client: CosmosClient, quality: string): Promise return res.resources[0] as Config; } -async function main(force: boolean): Promise { +async function main(force: boolean): Promise<'released' | 'skipped'> { const commit = getEnv('BUILD_SOURCEVERSION'); const quality = getEnv('VSCODE_QUALITY'); @@ -53,8 +53,7 @@ async function main(force: boolean): Promise { console.log('Quality config:', config); if (config.frozen) { - console.log(`Skipping release because quality ${quality} is frozen.`); - return; + return 'skipped'; } } @@ -62,14 +61,23 @@ async function main(force: boolean): Promise { const scripts = client.database('builds').container(quality).scripts; await retry(() => scripts.storedProcedure('releaseBuild').execute('', [commit])); + return 'released'; } const [, , force] = process.argv; console.log(process.argv); -main(/^true$/i.test(force)).then(() => { - console.log('Build successfully released'); +main(/^true$/i.test(force)).then(result => { + if (result === 'skipped') { + // The step still succeeds, but the build must not read as released + const quality = getEnv('VSCODE_QUALITY'); + console.log(`##vso[task.logissue type=warning]Build not released, since quality ${quality} is frozen. Release it manually once the quality is unfrozen.`); + console.log('##vso[build.addbuildtag]release-skipped-frozen'); + console.log(`Build NOT released: quality ${quality} is frozen`); + } else { + console.log('Build successfully released'); + } process.exit(0); }, err => { console.error(err); diff --git a/build/azure-pipelines/common/removePnpmStoreProjects.ts b/build/azure-pipelines/common/removePnpmStoreProjects.ts new file mode 100644 index 000000000000..879b940fe0ba --- /dev/null +++ b/build/azure-pipelines/common/removePnpmStoreProjects.ts @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import fs from 'fs'; +import path from 'path'; + +// Removes the links to projects (`//projects`) from the pnpm store that +// restore-pnpm-store.yml restored (see there). `rmSync` removes links without following them. + +const storeDir = process.env['PNPM_CONFIG_STORE_DIR']; + +if (storeDir && fs.existsSync(storeDir)) { + for (const entry of fs.readdirSync(storeDir, { withFileTypes: true })) { + const projectsDir = path.join(storeDir, entry.name, 'projects'); + if (!entry.isDirectory() || !fs.existsSync(projectsDir)) { + continue; + } + + const links = fs.readdirSync(projectsDir); + fs.rmSync(projectsDir, { recursive: true, force: true }); + console.log(`Removed ${links.length} project links from ${projectsDir}${links.length ? `: ${links.join(', ')}` : ''}`); + } +} diff --git a/build/azure-pipelines/common/restore-pnpm-store.yml b/build/azure-pipelines/common/restore-pnpm-store.yml new file mode 100644 index 000000000000..69c60536b032 --- /dev/null +++ b/build/azure-pipelines/common/restore-pnpm-store.yml @@ -0,0 +1,56 @@ +parameters: + # Arguments of `computePnpmStoreCacheKey.ts`, for the platform of the job. Jobs that install the + # same dependencies on the same platform use the same arguments, so that they share a cache entry. + - name: keyArgs + type: string + # Operating system of the job (linux, macOS or windows), for templates that know it. Empty when the + # job can run on any of them. + - name: os + type: string + default: '' + +# Restores the pnpm store of the job's platform from the pipeline cache before the dependencies are +# installed. The first step points pnpm at the cached folder for the later steps of the job +# (PNPM_CONFIG_STORE_DIR), with pnpm's metadata cache inside it (PNPM_CONFIG_CACHE_DIR): the +# metadata cache also keeps the log of the lockfiles that passed the supply-chain policies, which +# pnpm then doesn't check again (https://pnpm.io/continuous-integration). +# +# The key is the platform and the lockfiles of every install root. When no store has it, for +# example after a lockfile change, the latest store of the platform is restored, so pnpm downloads +# only the packages that it doesn't have, and the cache saves the store at the end of the job. +# Include prune-pnpm-store.yml after the installation, so that the saved store drops the packages +# that the lockfiles no longer use. +# +# A failing cache step doesn't fail the job (continueOnError): pnpm then installs without the cached +# store, and the cache doesn't save it, because it only saves after jobs that fully succeeded. +steps: + - script: node build/azure-pipelines/common/computePnpmStoreCacheKey.ts ${{ parameters.keyArgs }} + displayName: Prepare pnpm store cache key + continueOnError: true + + - task: Cache@2 + inputs: + key: '"pnpm_store" | .build/pnpmstorebase | .build/pnpmstorelockfiles' + restoreKeys: '"pnpm_store" | .build/pnpmstorebase' + path: $(PNPM_CONFIG_STORE_DIR) + cacheHitVar: PNPM_STORE_RESTORED + # AcesShared agents download the default 64 KB dedup chunks of large entries at ~7 MB/s, with + # request timeouts, against ~40 MB/s for the 1 MB chunks of pipeline artifacts. These agent + # knobs make the post-job step save new entries with 1 MB chunks, and restores follow the + # chunking of the saved entry. + ${{ if eq(parameters.os, 'macOS') }}: + env: + AGENT_ENABLE_PIPELINEARTIFACT_LARGE_CHUNK_SIZE: "true" + OVERRIDE_PIPELINE_ARTIFACT_CHUNKSIZE: Dedup1024K + displayName: Restore pnpm store cache + retryCountOnTaskFailure: 2 + continueOnError: true + + # The store is saved without its links to projects (see prune-pnpm-store.yml), unless a pnpm + # command after the prune adds one, like the `pnpm deploy` into a temporary folder that packages + # Copilot (extensions/copilot/script/build/packageVsix.ts). Its folder is gone by the save, and on + # Windows the cache restores that link as a file link, which `pnpm store prune` fails to remove + # (os error 267). The job's installations add their own links, so remove the restored ones. + - script: node build/azure-pipelines/common/removePnpmStoreProjects.ts + displayName: Remove project links of the restored pnpm store + continueOnError: true diff --git a/build/azure-pipelines/common/sanity-tests.yml b/build/azure-pipelines/common/sanity-tests.yml index eed4a6d7fb13..4fafb8ba48b9 100644 --- a/build/azure-pipelines/common/sanity-tests.yml +++ b/build/azure-pipelines/common/sanity-tests.yml @@ -59,8 +59,8 @@ jobs: continueOnError: true sbomEnabled: false variables: - - name: SANITY_NODE_VERSION - value: 22.22.0 + - name: SANITY_NODE_VERSION_SPEC + value: 24.x - name: TEST_DIR value: $(Build.SourcesDirectory)/test/sanity - name: LOG_FILE @@ -79,6 +79,11 @@ jobs: value: --artifacts-dir /root/artifacts ${{ else }}: value: --artifacts-dir $(ARTIFACTS_DIR) + # The pnpm store that the cache below restores (restore-pnpm-store.yml needs more of the + # repository than this job checks out). The job installs only test/sanity, so pnpm's metadata + # cache, which saves little here, isn't cached with it. + - name: PNPM_CONFIG_STORE_DIR + value: $(Pipeline.Workspace)/pnpm-store - name: SETUID_SANDBOX_GREP ${{ if or(eq(length(parameters.artifacts), 0), and(contains(join(',', parameters.artifacts), '_deb-package'), contains(join(',', parameters.artifacts), '_rpm-package'))) }}: value: desktop-linux-(deb|rpm)- @@ -165,6 +170,29 @@ jobs: displayName: Clear NuGet access token condition: always() + # Resolve the latest release before restoring caches so a new Node.js release gets fresh caches. + - ${{ if eq(parameters.os, 'windows') }}: + - powershell: | + $ErrorActionPreference = 'Stop' + $sums = & curl.exe -fsSL --connect-timeout 20 --max-time 60 --retry 3 "https://nodejs.org/dist/latest-v$(SANITY_NODE_VERSION_SPEC)/SHASUMS256.txt" + if ($LASTEXITCODE -ne 0) { throw 'Could not resolve the latest Node.js release' } + $match = [regex]::Match(($sums -join "`n"), 'node-v(24\.\d+\.\d+)-') + if (-not $match.Success) { throw 'No Node.js 24 release found' } + Write-Host "##vso[task.setvariable variable=SANITY_NODE_VERSION]$($match.Groups[1].Value)" + displayName: Resolve latest Node.js 24 release + + - ${{ else }}: + - bash: | + set -euo pipefail + sums=$(curl -fsSL --connect-timeout 20 --max-time 60 --retry 3 "https://nodejs.org/dist/latest-v$(SANITY_NODE_VERSION_SPEC)/SHASUMS256.txt") + version=$(printf '%s\n' "$sums" | sed -n 's/.* node-v\(24\.[0-9]*\.[0-9]*\)-.*/\1/p' | sort -u) + if [[ ! "$version" =~ ^24\.[0-9]+\.[0-9]+$ ]]; then + echo 'Could not resolve the latest Node.js 24 release' >&2 + exit 1 + fi + echo "##vso[task.setvariable variable=SANITY_NODE_VERSION]$version" + displayName: Resolve latest Node.js 24 release + # Node.js comes from the pipeline cache when possible. nodejs.org stalls from the shared # agent pools at times, so the bounded download below is only the fallback. - task: Cache@2 @@ -190,11 +218,13 @@ jobs: - task: Cache@2 inputs: - key: '"sanity-node_modules" | "$(Agent.OS)" | "${{ parameters.arch }}" | $(TEST_DIR)/pnpm-lock.yaml' - path: $(TEST_DIR)/node_modules - cacheHitVar: SANITY_NODE_MODULES_RESTORED - displayName: Restore node_modules cache + key: '"pnpm_store" | "sanity" | "$(Agent.OS)" | "${{ parameters.arch }}" | $(TEST_DIR)/pnpm-lock.yaml' + restoreKeys: '"pnpm_store" | "sanity" | "$(Agent.OS)" | "${{ parameters.arch }}"' + path: $(PNPM_CONFIG_STORE_DIR) + cacheHitVar: PNPM_STORE_RESTORED + displayName: Restore pnpm store cache retryCountOnTaskFailure: 2 + continueOnError: true # Sets the registry and its authentication in the user npm configuration, as the product build # jobs do: `npm install -g pnpm` (also on a cache hit) doesn't read a project .npmrc, and these @@ -208,7 +238,10 @@ jobs: - script: pnpm install --frozen-lockfile workingDirectory: $(TEST_DIR) displayName: Install Dependencies - condition: and(succeeded(), ne(variables.SANITY_NODE_MODULES_RESTORED, 'true')) + + - template: ./prune-pnpm-store.yml@self + parameters: + os: ${{ parameters.os }} - script: pnpm run compile workingDirectory: $(TEST_DIR) diff --git a/build/azure-pipelines/common/sign.ts b/build/azure-pipelines/common/sign.ts index 5e149d1ea636..261245d11fba 100644 --- a/build/azure-pipelines/common/sign.ts +++ b/build/azure-pipelines/common/sign.ts @@ -214,34 +214,97 @@ function killProcessTree(child: cp.ChildProcess): void { } } +/** Matches the stdin authentication handshake used by EsrpCodeSigning 6.1.3 and ESRP CLI 6.0.26. */ +function startEsrpProcess(command: string, args: string[], systemAccessToken?: string) { + const env = { ...process.env }; + if (systemAccessToken !== undefined) { + for (const name of Object.keys(env)) { + if (['SYSTEM_ACCESSTOKEN', 'ENDPOINT_AUTH_SYSTEMVSSCONNECTION', 'ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN'].includes(name.toUpperCase())) { + delete env[name]; + } + } + } + + const child = cp.spawn(command, args, { env, stdio: [systemAccessToken === undefined ? 'inherit' : 'pipe', 'pipe', 'inherit'] }); + let inputReady = systemAccessToken === undefined; + let startupOutput = '\n'; + let inputFailure: Error | undefined; + let startupDeadline: ReturnType | undefined; + let resolveExit!: (exitCode: number | null) => void; + const terminate = () => { + killProcessTree(child); + // Don't wait on a process that survived the kill. + setTimeout(() => resolveExit(null), 30_000).unref(); + }; + const exited = new Promise((resolve, reject) => { + resolveExit = resolve; + child.once('error', (error: NodeJS.ErrnoException) => { + clearTimeout(startupDeadline); + const code = ['ENOENT', 'EACCES', 'EPERM', 'ENOEXEC'].includes(error.code ?? '') ? error.code : 'UNKNOWN'; + reject(new Error(`Failed to start the ESRP CLI (${code}). Check the CLI and .NET installation and permissions.`)); + }); + child.once('close', code => { + clearTimeout(startupDeadline); + if (inputFailure) { + reject(inputFailure); + } else if (code === 0 && !inputReady) { + reject(new Error('ESRP CLI exited without confirming authentication input. Update the task and CLI together.')); + } else { + resolve(code); + } + }); + }); + + child.stdout!.on('data', (data: Buffer) => { + process.stdout.write(data); + if (!inputReady) { + const output = startupOutput + data.toString('utf8'); + const marker = '\nESRP_AUTH_INPUT_READY'; + if (output.includes(`${marker}\n`) || output.includes(`${marker}\r\n`)) { + inputReady = true; + startupOutput = ''; + clearTimeout(startupDeadline); + } else { + startupOutput = output.slice(-(marker.length + 1)); + } + } + }); + + if (systemAccessToken !== undefined) { + startupDeadline = setTimeout(() => { + inputFailure = new Error('Timed out after 60 seconds waiting for the ESRP CLI to read authentication input.'); + terminate(); + }, 60_000); + child.stdin!.on('error', () => { + clearTimeout(startupDeadline); + inputFailure ??= new Error('Failed to deliver authentication input to the ESRP CLI.'); + terminate(); + }); + child.stdin!.end(`${systemAccessToken}\n`, 'utf8'); + } + + return { child, exited, terminate }; +} + /** * Runs an ESRP session and stops it once it stops making progress, so a stuck * operation fails the sign step in minutes instead of holding the job until its * time limit. The signed files are replaced in place as they complete, so the * session isn't resubmitted here. A stage retry signs fresh, unsigned artifacts. */ -export async function runWithEsrpStallGuard(command: string, args: string[], stallTimeoutMs: number, pollIntervalMs = 15_000): Promise<{ exitCode: number | null; stalled?: EsrpProgress }> { +export async function runWithEsrpStallGuard(command: string, args: string[], stallTimeoutMs: number, pollIntervalMs = 15_000, systemAccessToken?: string): Promise<{ exitCode: number | null; stalled?: EsrpProgress }> { const progress = new EsrpProgress(); - const child = cp.spawn(command, args, { stdio: ['inherit', 'pipe', 'inherit'] }); + const { child, exited, terminate } = startEsrpProcess(command, args, systemAccessToken); child.stdout!.on('data', (data: Buffer) => { - process.stdout.write(data); progress.write(data.toString()); }); let stalled: EsrpProgress | undefined; - let resolveExit!: (exitCode: number | null) => void; - const exited = new Promise((resolve, reject) => { - resolveExit = resolve; - child.once('error', reject); - child.once('close', resolve); - }); const timer = setInterval(() => { if (progress.stalledForMs() >= stallTimeoutMs) { clearInterval(timer); stalled = progress; - killProcessTree(child); - // Don't wait on a process that survived the kill. - setTimeout(() => resolveExit(null), 30_000).unref(); + terminate(); } }, pollIntervalMs); @@ -362,24 +425,16 @@ export function getEsrpDownloadTempFiles(folder: string, pattern: string): Map ReadonlyMap, options: EsrpDownloadStallOptions, pollIntervalMs = 15_000): Promise<{ exitCode: number | null; stalled?: EsrpDownloadStall }> { +export async function runWithEsrpDownloadStallGuard(command: string, args: string[], getTempFiles: () => ReadonlyMap, options: EsrpDownloadStallOptions, pollIntervalMs = 15_000, systemAccessToken?: string): Promise<{ exitCode: number | null; stalled?: EsrpDownloadStall }> { const monitor = new EsrpDownloadMonitor(options); - const child = cp.spawn(command, args, { stdio: 'inherit' }); + const { exited, terminate } = startEsrpProcess(command, args, systemAccessToken); let stalled: EsrpDownloadStall | undefined; - let resolveExit!: (exitCode: number | null) => void; - const exited = new Promise((resolve, reject) => { - resolveExit = resolve; - child.once('error', reject); - child.once('close', resolve); - }); const timer = setInterval(() => { stalled = monitor.sample(getTempFiles()); if (stalled) { clearInterval(timer); - killProcessTree(child); - // Don't wait on a process that survived the kill. - setTimeout(() => resolveExit(null), 30_000).unref(); + terminate(); } }, pollIntervalMs); @@ -403,12 +458,12 @@ function removeEsrpDownloadTempFiles(folder: string, pattern: string): void { * MAX_ESRP_DOWNLOAD_STALL_RESUBMISSIONS times. Returns the exit code of the * last session. */ -export async function runWithEsrpDownloadResubmission(command: string, createArgs: () => string[], folderPath: string, pattern: string, options: EsrpDownloadStallOptions, onStall: (stall: EsrpDownloadStall, attempt: number) => void, pollIntervalMs = 15_000): Promise { +export async function runWithEsrpDownloadResubmission(command: string, createArgs: () => string[], folderPath: string, pattern: string, options: EsrpDownloadStallOptions, onStall: (stall: EsrpDownloadStall, attempt: number) => void, pollIntervalMs = 15_000, systemAccessToken?: string): Promise { for (let attempt = 1; ; attempt++) { removeEsrpDownloadTempFiles(folderPath, pattern); // The last session isn't stopped, so the files get signed even if every download stalls. const guard = attempt <= MAX_ESRP_DOWNLOAD_STALL_RESUBMISSIONS; - const { exitCode, stalled } = await runWithEsrpDownloadStallGuard(command, createArgs(), () => guard ? getEsrpDownloadTempFiles(folderPath, pattern) : new Map(), options, pollIntervalMs); + const { exitCode, stalled } = await runWithEsrpDownloadStallGuard(command, createArgs(), () => guard ? getEsrpDownloadTempFiles(folderPath, pattern) : new Map(), options, pollIntervalMs, systemAccessToken); if (!stalled) { return exitCode; } @@ -416,14 +471,14 @@ export async function runWithEsrpDownloadResubmission(command: string, createArg } } -async function runDarwinSession(type: string, folderPath: string, pattern: string, createArgs: () => string[]): Promise { +async function runDarwinSession(type: string, folderPath: string, pattern: string, createArgs: () => string[], systemAccessToken: string): Promise { const options = getEsrpDownloadStallOptions(); const exitCode = await runWithEsrpDownloadResubmission('dotnet', createArgs, folderPath, pattern, options, (stalled, attempt) => { const rate = (stalled.bytesPerSecond / 1024 / 1024).toFixed(2); const file = path.basename(stalled.file, '.tmp'); console.log(`[esrp-stall] type=${type} file=${file} rate=${rate}MB/s window=${options.windowMs / 1000}s attempt=${attempt} action=resubmit`); console.log(`##vso[task.logissue type=warning]ESRP download of ${file} stalled at ${rate} MB/s; submitting it again (attempt ${attempt + 1}).`); - }); + }, undefined, systemAccessToken); if (exitCode !== 0) { console.error('ESRP failed'); console.error(`dotnet exited with code ${exitCode}`); @@ -432,6 +487,11 @@ async function runDarwinSession(type: string, folderPath: string, pattern: strin } export function main([esrpCliPath, type, folderPath, pattern]: string[]): void | Promise { + const token = process.env['SYSTEM_ACCESSTOKEN']; + if (!token?.trim() || /[\r\n]/.test(token) || token.trim().length > 32767) { + throw new Error('Missing or invalid SYSTEM_ACCESSTOKEN for ESRP signing.'); + } + const systemAccessToken = token.trim(); const tmp = new Temp(); process.on('exit', () => tmp.dispose()); @@ -444,20 +504,7 @@ export function main([esrpCliPath, type, folderPath, pattern]: string[]): void | const dotnetVersion = cp.execSync('dotnet --version', { encoding: 'utf8' }).trim(); const adoTaskVersion = path.basename(path.dirname(path.dirname(esrpCliPath))); - // esrpcli deletes the encryption key file once it has read it, so every session - // needs a newly encrypted token. const createArgs = (): string[] => { - const key = crypto.randomBytes(32); - const iv = crypto.randomBytes(16); - const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); - const encryptedToken = cipher.update(process.env['SYSTEM_ACCESSTOKEN']!.trim(), 'utf8', 'hex') + cipher.final('hex'); - - const encryptionDetailsPath = tmp.tmpNameSync(); - fs.writeFileSync(encryptionDetailsPath, JSON.stringify({ key: key.toString('hex'), iv: iv.toString('hex') })); - - const encryptedTokenPath = tmp.tmpNameSync(); - fs.writeFileSync(encryptedTokenPath, encryptedToken); - const federatedTokenData = { jobId: process.env['SYSTEM_JOBID'], planId: process.env['SYSTEM_PLANID'], @@ -467,9 +514,7 @@ export function main([esrpCliPath, type, folderPath, pattern]: string[]): void | managedIdentityId: process.env['VSCODE_ESRP_CLIENT_ID'], managedIdentityTenantId: process.env['VSCODE_ESRP_TENANT_ID'], serviceConnectionId: process.env['VSCODE_ESRP_SERVICE_CONNECTION_ID'], - tempDirectory: os.tmpdir(), - systemAccessToken: encryptedTokenPath, - encryptionKey: encryptionDetailsPath + systemAccessTokenSource: 'stdin' }; return [ @@ -510,7 +555,7 @@ export function main([esrpCliPath, type, folderPath, pattern]: string[]): void | if (isWindowsSignType(type)) { const stallTimeoutMs = getEsrpStallTimeoutMs(); - return runWithEsrpStallGuard('dotnet', createArgs(), stallTimeoutMs).then(({ exitCode, stalled }) => { + return runWithEsrpStallGuard('dotnet', createArgs(), stallTimeoutMs, undefined, systemAccessToken).then(({ exitCode, stalled }) => { if (stalled) { console.log(`##vso[task.logissue type=error]ESRP signing stalled: ${stalled.remaining} file(s) still pending after ${stallTimeoutMs / 60_000} minutes without progress (FileIds: ${stalled.fileIds}). Retry the stage, not this step: files signed so far were replaced in place.`); process.exit(1); @@ -528,20 +573,24 @@ export function main([esrpCliPath, type, folderPath, pattern]: string[]): void | } if (isDarwinSignType(type)) { - return runDarwinSession(type, folderPath, pattern, createArgs).catch(err => { + return runDarwinSession(type, folderPath, pattern, createArgs, systemAccessToken).catch(err => { console.error('ESRP failed'); console.error(err); process.exit(1); }); } - try { - cp.execFileSync('dotnet', createArgs(), { stdio: 'inherit' }); - } catch (err) { + return startEsrpProcess('dotnet', createArgs(), systemAccessToken).exited.then(exitCode => { + if (exitCode !== 0) { + console.error('ESRP failed'); + console.error(`dotnet exited with code ${exitCode}`); + process.exit(1); + } + }, err => { console.error('ESRP failed'); console.error(err); process.exit(1); - } + }); } if (import.meta.main) { diff --git a/build/azure-pipelines/common/workspaceLinks.ts b/build/azure-pipelines/common/workspaceLinks.ts new file mode 100644 index 000000000000..fb853793711f --- /dev/null +++ b/build/azure-pipelines/common/workspaceLinks.ts @@ -0,0 +1,97 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import fs from 'fs'; +import path from 'path'; + +// Hands the folder links of a workspace, such as the ones of pnpm's isolated `node_modules` (junctions +// on Windows), from a build job to test jobs through an archive format that can't store them. 7-Zip +// archives a junction as a copy of its target, so `node_modules/` loses the links to its +// dependencies, and resolving them from the copy fails. +// +// save records the folder links under in and removes them +// restore creates the links of again +// +// Links to files, and links to targets outside of , are left alone: an archive keeps them as +// copies, which still work. + +export interface WorkspaceLink { + /** Path of the link, relative to the root, with `/` separators. */ + readonly path: string; + /** Path of the target, relative to the root, with `/` separators. */ + readonly target: string; +} + +const toPosix = (p: string) => p.split(path.sep).join('/'); + +function isInside(root: string, file: string): boolean { + const relative = path.relative(root, file); + return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative); +} + +function isDirectory(file: string): boolean { + try { + return fs.statSync(file).isDirectory(); + } catch { + // A link whose target doesn't exist + return false; + } +} + +/** Returns the links to folders inside `root`, without following any link. */ +export function findWorkspaceLinks(root: string): WorkspaceLink[] { + root = path.resolve(root); + const links: WorkspaceLink[] = []; + const folders = [root]; + for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) { + for (const entry of fs.readdirSync(folder, { withFileTypes: true })) { + const file = path.join(folder, entry.name); + if (entry.isSymbolicLink()) { + const target = path.resolve(folder, fs.readlinkSync(file)); + if (isInside(root, target) && isDirectory(file)) { + links.push({ path: toPosix(path.relative(root, file)), target: toPosix(path.relative(root, target)) }); + } + } else if (entry.isDirectory() && entry.name !== '.git') { + folders.push(file); + } + } + } + return links.sort((a, b) => a.path.localeCompare(b.path)); +} + +export function saveWorkspaceLinks(root: string, manifest: string): WorkspaceLink[] { + const links = findWorkspaceLinks(root); + fs.mkdirSync(path.dirname(manifest), { recursive: true }); + fs.writeFileSync(manifest, JSON.stringify(links)); + for (const link of links) { + // Removes the link, not its target + fs.rmSync(path.join(root, link.path)); + } + return links; +} + +export function restoreWorkspaceLinks(root: string, manifest: string): WorkspaceLink[] { + root = path.resolve(root); + const links: WorkspaceLink[] = JSON.parse(fs.readFileSync(manifest, 'utf8')); + for (const link of links) { + const file = path.join(root, link.path); + fs.mkdirSync(path.dirname(file), { recursive: true }); + // Junctions need no privilege on Windows, and take absolute targets + fs.symlinkSync(path.join(root, link.target), file, process.platform === 'win32' ? 'junction' : 'dir'); + } + return links; +} + +if (import.meta.main) { + const [command, root, manifest] = process.argv.slice(2); + if (command === 'save' && root && manifest) { + console.log(`Removed ${saveWorkspaceLinks(root, manifest).length} folder links under ${root}, recorded in ${manifest}`); + } else if (command === 'restore' && root && manifest) { + console.log(`Created ${restoreWorkspaceLinks(root, manifest).length} folder links under ${root} from ${manifest}`); + } else { + console.error('Usage: workspaceLinks.ts save|restore '); + process.exit(1); + } +} diff --git a/build/azure-pipelines/copilot/setup-steps.yml b/build/azure-pipelines/copilot/setup-steps.yml index 4d32a71a7cc8..91c9bc701dec 100644 --- a/build/azure-pipelines/copilot/setup-steps.yml +++ b/build/azure-pipelines/copilot/setup-steps.yml @@ -1,7 +1,8 @@ steps: - task: NodeTool@0 inputs: - versionSpec: "22.21.x" + versionSpec: 24.x + checkLatest: true # Check out the private microsoft/vscode-capi repository using the agent's # GitHub App (Monaco) credentials instead of cloning it with a PAT. The @@ -22,20 +23,10 @@ steps: condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none'), not(contains(variables['Agent.OS'], 'windows'))) displayName: Setup NPM Registry (non-Windows) - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts $(node -p process.platform) $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"copilot_build_cache" | .build/packagelockhash | .build/vscode-capi/package-lock.json' - path: .build/node_modules_cache - cacheHitVar: BUILD_CACHE_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.BUILD_CACHE_RESTORED, 'true')) - displayName: Extract node_modules cache + # Copilot installs only some of the install roots, so its store has its own key. + - template: ../common/restore-pnpm-store.yml@self + parameters: + keyArgs: copilot - pwsh: | $ErrorActionPreference = 'Stop' @@ -71,7 +62,6 @@ steps: - script: pnpm install --frozen-lockfile workingDirectory: build displayName: Install build dependencies - condition: and(succeeded(), ne(variables.BUILD_CACHE_RESTORED, 'true')) retryCountOnTaskFailure: 3 # Only the dependencies of the root project, without the root install scripts that install every @@ -79,32 +69,21 @@ steps: - script: pnpm install --frozen-lockfile --ignore-scripts --filter . workingDirectory: $(Build.SourcesDirectory) displayName: Install vscode dependencies - condition: and(succeeded(), ne(variables.BUILD_CACHE_RESTORED, 'true')) retryCountOnTaskFailure: 3 - script: pnpm install --frozen-lockfile workingDirectory: $(Build.SourcesDirectory)/extensions/copilot displayName: Install copilot dependencies - condition: and(succeeded(), ne(variables.BUILD_CACHE_RESTORED, 'true')) retryCountOnTaskFailure: 3 # microsoft/vscode-capi is a separate repository that installs with npm. - script: npm ci workingDirectory: $(Build.SourcesDirectory)/.build/vscode-capi displayName: Install vscode-capi dependencies - condition: and(succeeded(), ne(variables.BUILD_CACHE_RESTORED, 'true')) retryCountOnTaskFailure: 3 - script: node build/azure-pipelines/common/checkNativeOptionalDeps.ts workingDirectory: $(Build.SourcesDirectory) displayName: Verify native optional dependency binaries - - script: | - set -e - mkdir -p .build - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - echo .build/vscode-capi/node_modules >> .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.BUILD_CACHE_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../common/prune-pnpm-store.yml@self diff --git a/build/azure-pipelines/darwin/product-build-darwin-ci.yml b/build/azure-pipelines/darwin/product-build-darwin-ci.yml index b98dac9ca87f..614c2cb2f953 100644 --- a/build/azure-pipelines/darwin/product-build-darwin-ci.yml +++ b/build/azure-pipelines/darwin/product-build-darwin-ci.yml @@ -43,7 +43,8 @@ jobs: displayName: Publish Log Files sbomEnabled: false isProduction: false - condition: succeededOrFailed() + # 1ES PT runs its binary analysis for every published output, so only publish when the logs are needed + condition: failed() steps: - template: ./steps/product-build-darwin-compile.yml@self parameters: diff --git a/build/azure-pipelines/darwin/product-build-darwin-node-modules.yml b/build/azure-pipelines/darwin/product-build-darwin-node-modules.yml deleted file mode 100644 index 35735520936b..000000000000 --- a/build/azure-pipelines/darwin/product-build-darwin-node-modules.yml +++ /dev/null @@ -1,139 +0,0 @@ -parameters: - - name: VSCODE_ARCH - type: string - -jobs: - - job: macOSNodeModules_${{ parameters.VSCODE_ARCH }} - displayName: macOS (${{ upper(parameters.VSCODE_ARCH) }}) - pool: - name: AcesShared - os: macOS - demands: - - ImageOverride -equals ACES_VM_SharedPool_Sequoia - timeoutInMinutes: 60 - variables: - VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} - steps: - - template: ../common/checkout.yml@self - - - template: ../common/setup-node.yml@self - parameters: - os: macOS - - - template: ../distro/download-distro.yml@self - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get Secrets" - inputs: - azureSubscription: vscode - KeyVaultName: vscode-build-secrets - SecretsFilter: "macos-developer-certificate,macos-developer-certificate-key" - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get GitHub token" - inputs: - azureSubscription: vscode-oss-build-secrets - KeyVaultName: vscode-oss-build-secrets - SecretsFilter: "github-token-code-oss" - - - script: node build/setup-npm-registry.ts $NPM_REGISTRY - condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Registry - - - template: ../common/apply-sdk-canary.yml@self - - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts darwin $VSCODE_ARCH $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - # AcesShared agents download the default 64 KB dedup chunks of this ~1.5 GB - # archive at ~7 MB/s, with request timeouts, against ~40 MB/s for the 1 MB - # chunks of pipeline artifacts. These agent knobs make the post-job step save - # new entries with 1 MB chunks, and restores follow the chunking of the saved - # entry. The "dedup1024k" key segment starts new entries in that format. - - task: Cache@2 - inputs: - key: '"node_modules" | "dedup1024k" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - env: - AGENT_ENABLE_PIPELINEARTIFACT_LARGE_CHUNK_SIZE: "true" - OVERRIDE_PIPELINE_ARTIFACT_CHUNKSIZE: Dedup1024K - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: | - set -e - # Set the private NPM registry to the global npmrc file - # so that authentication works for subfolders like build/, remote/, extensions/ etc - # which does not have their own .npmrc file - npm config set registry "$NPM_REGISTRY" - echo "##vso[task.setvariable variable=NPMRC_PATH]$(npm config get userconfig)" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM - - - task: npmAuthenticate@0 - inputs: - workingFile: $(NPMRC_PATH) - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Authentication - - - template: ../common/install-pnpm.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - task: PipAuthenticate@1 - inputs: - artifactFeeds: Monaco/vscode - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Setup PyPI Authentication - - - script: | - set -e - c++ --version - xcode-select -print-path - python3 -m pip install setuptools - - for i in {1..5}; do # try 5 times - pnpm install --frozen-lockfile && break - if [ $i -eq 5 ]; then - echo "pnpm install failed too many times" >&2 - exit 1 - fi - echo "pnpm install failed $i, trying again..." - done - env: - npm_config_arch: $(VSCODE_ARCH) - ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - GITHUB_TOKEN: "$(github-token-code-oss)" - FOUNDRY_LOCAL_SKIP_INSTALL: "1" - # Avoid using dlopen to load Kerberos on macOS which can cause missing libraries - # https://github.com/mongodb-js/kerberos/commit/04044d2814ad1d01e77f1ce87f26b03d86692cf2 - # flipped the default to support legacy linux distros which shouldn't happen - # on macOS. - GYP_DEFINES: "kerberos_use_rtld=false" - displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - # PipAuthenticate@1 exposes its access token to all later steps inside the - # PIP_INDEX_URL environment variable, from where they can write it to logs. - # Only installing dependencies needs it, so clear it now. - - script: echo "##vso[task.setvariable variable=PIP_INDEX_URL]" - displayName: Clear package feed credentials - condition: always() - - - script: node build/azure-pipelines/common/checkNativeOptionalDeps.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Verify native optional dependency binaries - - - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Mixin distro node modules - - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive diff --git a/build/azure-pipelines/darwin/product-build-darwin-test.yml b/build/azure-pipelines/darwin/product-build-darwin-test.yml index b6ab2eac0c99..eff7e291e134 100644 --- a/build/azure-pipelines/darwin/product-build-darwin-test.yml +++ b/build/azure-pipelines/darwin/product-build-darwin-test.yml @@ -13,8 +13,10 @@ parameters: # Each product test job tests the builds of the compilation artifact published # by the compile job (see product-build-darwin.yml, which must set # VSCODE_RUN_TESTS) with the selected test IDs, after applying the local -# entitlement signature required to run the product on macOS. Retrying a test -# job skips the test tasks that already passed in an earlier attempt. +# entitlement signature required to run the product on macOS. Failed unit, +# Agent Host E2E and node.js integration tests are rerun, as in the pull +# request workflows. Retrying a test job skips the test tasks that already +# passed in an earlier attempt. jobs: - job: macOS_${{ parameters.VSCODE_ARCH }}_Test_${{ parameters.VSCODE_JOB_NAME }} displayName: macOS (${{ upper(parameters.VSCODE_ARCH) }}) - ${{ parameters.VSCODE_JOB_DISPLAY_NAME }} @@ -63,3 +65,4 @@ jobs: parameters: VSCODE_TEST_IDS: ${{ parameters.VSCODE_TEST_IDS }} VSCODE_COMPILE_TEST_SUITES: true + VSCODE_RERUN_FAILED_TESTS: true diff --git a/build/azure-pipelines/darwin/steps/product-build-darwin-setup.yml b/build/azure-pipelines/darwin/steps/product-build-darwin-setup.yml index 2b8358127fdc..e8ccfc46e42f 100644 --- a/build/azure-pipelines/darwin/steps/product-build-darwin-setup.yml +++ b/build/azure-pipelines/darwin/steps/product-build-darwin-setup.yml @@ -38,28 +38,10 @@ steps: - template: ../../common/apply-sdk-canary.yml@self - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts darwin $VSCODE_ARCH $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - # AcesShared agents download the default 64 KB dedup chunks of this ~1.5 GB - # archive at ~7 MB/s, with request timeouts, against ~40 MB/s for the 1 MB - # chunks of pipeline artifacts. These agent knobs make the post-job step save - # new entries with 1 MB chunks, and restores follow the chunking of the saved - # entry. The "dedup1024k" key segment starts new entries in that format. - - task: Cache@2 - inputs: - key: '"node_modules" | "dedup1024k" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - env: - AGENT_ENABLE_PIPELINEARTIFACT_LARGE_CHUNK_SIZE: "true" - OVERRIDE_PIPELINE_ARTIFACT_CHUNKSIZE: Dedup1024K - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ../../common/restore-pnpm-store.yml@self + parameters: + keyArgs: darwin $(VSCODE_ARCH) + os: macOS - script: | set -e @@ -118,7 +100,6 @@ steps: # on macOS. GYP_DEFINES: "kerberos_use_rtld=false" displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 and PipAuthenticate@1 expose their access token to all # later steps, as VSS_NUGET_ACCESSTOKEN and inside PIP_INDEX_URL, from where @@ -135,16 +116,11 @@ steps: displayName: Verify native optional dependency binaries - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../../common/prune-pnpm-store.yml@self + parameters: + os: macOS - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality diff --git a/build/azure-pipelines/darwin/steps/product-build-darwin-test.yml b/build/azure-pipelines/darwin/steps/product-build-darwin-test.yml index fb2fd8f9354f..1925faac1939 100644 --- a/build/azure-pipelines/darwin/steps/product-build-darwin-test.yml +++ b/build/azure-pipelines/darwin/steps/product-build-darwin-test.yml @@ -5,6 +5,12 @@ parameters: - name: VSCODE_COMPILE_TEST_SUITES type: boolean default: false + # Reruns failed unit, Agent Host E2E and node.js integration tests, like the + # pull request workflows do (the extension host suites are not rerun). Only + # the product build test jobs set it. + - name: VSCODE_RERUN_FAILED_TESTS + type: boolean + default: false # Each test task records a checkpoint once it passes, and retries of the job # skip the test tasks that already passed in an earlier attempt of the same run. @@ -40,7 +46,7 @@ steps: parameters: testId: unit-electron testStep: - script: ./scripts/test.sh --build --tfs "Unit Tests" + script: ./scripts/test.sh --build --tfs "Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_SKIP_PRELAUNCH: '1' displayName: 🧪 Run unit tests (Electron) @@ -54,7 +60,7 @@ steps: script: | set -e mkdir -p .build/crashes - pnpm run test-node --build + pnpm run test-node --build${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: NODE_OPTIONS: "--report-on-fatalerror --report-uncaught-exception --report-directory=.build/crashes" displayName: 🧪 Run unit tests (node.js) @@ -65,7 +71,7 @@ steps: parameters: testId: unit-browser-webkit testStep: - script: pnpm run test-browser-no-install --build --browser webkit --tfs "Browser Unit Tests" + script: pnpm run test-browser-no-install --build --browser webkit --tfs "Browser Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: DEBUG: "*browser*" displayName: 🧪 Run unit tests (Browser, Webkit) @@ -110,7 +116,7 @@ steps: ProductJsonPath=$(find "$APP_ROOT" -name "product.json" -type f | head -n 1) BINARY_NAME=$(jq -r '.nameShort' "$ProductJsonPath") INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME/Contents/MacOS/$BINARY_NAME" \ - ./scripts/test-agent-host-e2e.sh --build --tfs "Integration Tests" + ./scripts/test-agent-host-e2e.sh --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_REMOTE_SERVER_PATH: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH) VSCODE_SKIP_PRELAUNCH: '1' @@ -132,7 +138,7 @@ steps: ProductJsonPath=$(find "$APP_ROOT" -name "product.json" -type f | head -n 1) BINARY_NAME=$(jq -r '.nameShort' "$ProductJsonPath") INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME/Contents/MacOS/$BINARY_NAME" \ - ./scripts/test-integration.sh --build --tfs "Integration Tests" + ./scripts/test-integration.sh --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_REMOTE_SERVER_PATH: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH) VSCODE_SKIP_PRELAUNCH: '1' diff --git a/build/azure-pipelines/linux/apt-install-with-retry.sh b/build/azure-pipelines/linux/apt-install-with-retry.sh new file mode 100755 index 000000000000..11d57dfa6769 --- /dev/null +++ b/build/azure-pipelines/linux/apt-install-with-retry.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. + +# Installs the given apt packages. Retries the update and install as a whole when +# the Ubuntu archive is unreachable for a while (seen behind the network +# isolation proxy), and fails the step if the last attempt fails too. +# +# Usage: apt-install-with-retry.sh ... + +set -euo pipefail + +# Abandon a stalled connection after 15s instead of apt's default 120s, and +# retry failed downloads (see build-snap.sh). +sudo sh -c 'printf "%s\n" "Acquire::Retries \"5\";" "Acquire::http::Timeout \"15\";" > /etc/apt/apt.conf.d/80-vscode-retry' + +attempts=3 +for ((attempt = 1; attempt <= attempts; attempt++)); do + if sudo apt-get update && sudo apt-get install -y "$@"; then + exit 0 + fi + if ((attempt < attempts)); then + echo "apt failed (attempt $attempt of $attempts); retrying in 60s." >&2 + sleep 60 + fi +done + +echo "apt failed after $attempts attempts." >&2 +exit 1 diff --git a/build/azure-pipelines/linux/build-snap.sh b/build/azure-pipelines/linux/build-snap.sh index 8dd07af0688b..e8f2c5ef60be 100755 --- a/build/azure-pipelines/linux/build-snap.sh +++ b/build/azure-pipelines/linux/build-snap.sh @@ -11,6 +11,13 @@ snapcraft --version # This applies to both the apt commands below and snapcraft's internal apt operations for stage-packages sudo sh -c 'echo "Acquire::Retries \"5\";" > /etc/apt/apt.conf.d/80-retries' +# Abandon a stalled connection after 15s instead of apt's default 120s. snapcraft +# fetches stage-packages one at a time, and when the mirror stalls a connection the +# retry on a new one usually succeeds at once; with the default, 35 such stalls took +# 70 minutes and the job hit its time limit. The timeout applies to inactivity, so +# slow but progressing downloads are unaffected. +sudo sh -c 'echo "Acquire::http::Timeout \"15\";" > /etc/apt/apt.conf.d/80-timeout' + # Point apt at the Azure Ubuntu mirror. The build agents cannot reach # archive.ubuntu.com/ports.ubuntu.com (DNS resolves them to a non-routable # TEST-NET address, so connections time out), whereas the Azure mirror is @@ -27,11 +34,28 @@ done # Make sure we get latest packages sudo apt-get update sudo apt-get upgrade -y -sudo apt-get install -y curl apt-transport-https ca-certificates +sudo apt-get install -y curl apt-transport-https ca-certificates gcc # Define variables SNAP_ROOT="$(pwd)/.build/linux/snap/$VSCODE_ARCH" +# Build OpenSSL 3 shared libraries against core20 glibc from the prebuilt static +# archives so the Copilot SDK runtime resolves libcrypto.so.3 / libssl.so.3 from +# the snap rather than loading an incompatible host OpenSSL. +OPENSSL_PREBUILT_DIR="$(pwd)/.build/linux/snap/openssl" +if [ -f "$OPENSSL_PREBUILT_DIR/libcrypto.a" ] && [ -f "$OPENSSL_PREBUILT_DIR/libssl.a" ]; then + for prebuild_dir in "$SNAP_ROOT"/code-*/usr/share/*/resources/app/node_modules.asar.unpacked/@github/copilot-sdk-linux-*/prebuilds/linux-*; do + [ -d "$prebuild_dir" ] || continue + gcc -shared -Wl,-soname,libcrypto.so.3 \ + -Wl,--whole-archive "$OPENSSL_PREBUILT_DIR/libcrypto.a" -Wl,--no-whole-archive \ + -ldl -pthread -o "$prebuild_dir/libcrypto.so.3" + gcc -shared -Wl,-soname,libssl.so.3 \ + -Wl,-rpath,'$ORIGIN' \ + -Wl,--whole-archive "$OPENSSL_PREBUILT_DIR/libssl.a" -Wl,--no-whole-archive \ + -L"$prebuild_dir" -l:libcrypto.so.3 -ldl -pthread -o "$prebuild_dir/libssl.so.3" + done +fi + # Create snap package BUILD_VERSION="$(date +%s)" SNAP_FILENAME="code-$VSCODE_QUALITY-$VSCODE_ARCH-$BUILD_VERSION.snap" diff --git a/build/azure-pipelines/linux/product-build-linux-ci.yml b/build/azure-pipelines/linux/product-build-linux-ci.yml index 829e14de7c21..2dd5d060c40d 100644 --- a/build/azure-pipelines/linux/product-build-linux-ci.yml +++ b/build/azure-pipelines/linux/product-build-linux-ci.yml @@ -23,12 +23,9 @@ jobs: VSCODE_ARCH: x64 BUILDS_API_URL: $(System.CollectionUri)$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)/ templateContext: - # Defender for Linux can block the 1ES PT antimalware scan of the outputs for 45-55 min (see - # product-build-linux-cli.yml), so cap it. Until that's fixed the cap is 2 min, which also - # stops some scans that aren't blocked (up to 7 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputs: - output: pipelineArtifact targetPath: $(Build.SourcesDirectory)/.build/crashes @@ -50,7 +47,8 @@ jobs: displayName: Publish Log Files sbomEnabled: false isProduction: false - condition: succeededOrFailed() + # 1ES PT runs its binary analysis for every published output, so only publish when the logs are needed + condition: failed() steps: - template: ./steps/product-build-linux-compile.yml@self parameters: diff --git a/build/azure-pipelines/linux/product-build-linux-cli.yml b/build/azure-pipelines/linux/product-build-linux-cli.yml index 2386273fb191..6105f5351f30 100644 --- a/build/azure-pipelines/linux/product-build-linux-cli.yml +++ b/build/azure-pipelines/linux/product-build-linux-cli.yml @@ -20,14 +20,9 @@ jobs: variables: VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} templateContext: - # Defender for Linux can fold the 1ES PT antimalware scan of the outputs into a scan of system - # folders (/opt, /usr/lib) that started before the job, which blocks it for 45-55 min, so the - # job times out before publishing the outputs. A scan that times out completes the step with - # issues and the outputs are published. Until that's fixed the cap is 2 min, which also stops - # some scans that aren't blocked (up to 6 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputs: - ${{ if not(parameters.VSCODE_CHECK_ONLY) }}: - output: pipelineArtifact diff --git a/build/azure-pipelines/linux/product-build-linux-node-modules.yml b/build/azure-pipelines/linux/product-build-linux-node-modules.yml deleted file mode 100644 index dbb31371b05f..000000000000 --- a/build/azure-pipelines/linux/product-build-linux-node-modules.yml +++ /dev/null @@ -1,164 +0,0 @@ -parameters: - - name: NPM_ARCH - type: string - - name: VSCODE_ARCH - type: string - -jobs: - - job: LinuxNodeModules_${{ parameters.VSCODE_ARCH }} - displayName: Linux (${{ upper(parameters.VSCODE_ARCH) }}) - pool: - name: 1es-ubuntu-22.04-x64 - os: linux - timeoutInMinutes: 60 - variables: - NPM_ARCH: ${{ parameters.NPM_ARCH }} - VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} - steps: - - template: ../common/checkout.yml@self - - - template: ../common/setup-node.yml@self - parameters: - os: linux - - - template: ../distro/download-distro.yml@self - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get Secrets" - inputs: - azureSubscription: vscode-oss-build-secrets - KeyVaultName: vscode-oss-build-secrets - SecretsFilter: "github-token-code-oss" - - - script: | - set -e - # Start X server - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y pkg-config \ - xvfb \ - libgtk-3-0 \ - libxkbfile-dev \ - libkrb5-dev \ - libgbm1 \ - rpm \ - bubblewrap \ - socat - sudo cp build/azure-pipelines/linux/xvfb.init /etc/init.d/xvfb - sudo chmod +x /etc/init.d/xvfb - sudo update-rc.d xvfb defaults - sudo service xvfb start - displayName: Setup system services - - - script: node build/setup-npm-registry.ts $NPM_REGISTRY - condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Registry - - - template: ../common/apply-sdk-canary.yml@self - - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts linux $VSCODE_ARCH $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: | - set -e - # Set the private NPM registry to the global npmrc file - # so that authentication works for subfolders like build/, remote/, extensions/ etc - # which does not have their own .npmrc file - npm config set registry "$NPM_REGISTRY" - echo "##vso[task.setvariable variable=NPMRC_PATH]$(npm config get userconfig)" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM - - - task: npmAuthenticate@0 - inputs: - workingFile: $(NPMRC_PATH) - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Authentication - - - template: ../common/install-pnpm.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - - for i in {1..5}; do # try 5 times - pnpm install --frozen-lockfile && break - if [ $i -eq 5 ]; then - echo "pnpm install failed too many times" >&2 - exit 1 - fi - echo "pnpm install failed $i, trying again..." - done - workingDirectory: build - env: - GITHUB_TOKEN: "$(github-token-code-oss)" - displayName: Install build dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - # Step will be used by both verify glibcxx version for remote server and building rpm package, - # hence avoid adding it behind NODE_MODULES_RESTORED condition. - - script: | - set -e - SYSROOT_ARCH=$VSCODE_ARCH - if [ "$SYSROOT_ARCH" == "x64" ]; then - SYSROOT_ARCH="amd64" - fi - export VSCODE_SYSROOT_DIR=$(Build.SourcesDirectory)/.build/sysroots/glibc-2.28-gcc-8.5.0 - SYSROOT_ARCH="$SYSROOT_ARCH" VSCODE_SYSROOT_PREFIX="-glibc-2.28-gcc-8.5.0" node -e 'import { getVSCodeSysroot } from "./build/linux/debian/install-sysroot.ts"; (async () => { await getVSCodeSysroot(process.env["SYSROOT_ARCH"]); })()' - env: - VSCODE_ARCH: $(VSCODE_ARCH) - GITHUB_TOKEN: "$(github-token-code-oss)" - displayName: Download vscode sysroots - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - - source ./build/azure-pipelines/linux/setup-env.sh - - # Run preinstall script before root dependencies are installed - # so that v8 headers are patched correctly for native modules. - pnpm run preinstall - - for i in {1..5}; do # try 5 times - pnpm install --frozen-lockfile && break - if [ $i -eq 5 ]; then - echo "pnpm install failed too many times" >&2 - exit 1 - fi - echo "pnpm install failed $i, trying again..." - done - env: - npm_config_arch: $(NPM_ARCH) - VSCODE_ARCH: $(VSCODE_ARCH) - ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - ONNXRUNTIME_NODE_INSTALL: skip - GITHUB_TOKEN: "$(github-token-code-oss)" - FOUNDRY_LOCAL_SKIP_INSTALL: "1" - displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: node build/azure-pipelines/common/checkNativeOptionalDeps.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Verify native optional dependency binaries - - - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Mixin distro node modules - - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive diff --git a/build/azure-pipelines/linux/product-build-linux-test.yml b/build/azure-pipelines/linux/product-build-linux-test.yml index 69fa40beba57..8196e082451f 100644 --- a/build/azure-pipelines/linux/product-build-linux-test.yml +++ b/build/azure-pipelines/linux/product-build-linux-test.yml @@ -12,8 +12,10 @@ parameters: # Each product test job tests the builds of the compilation artifact published # by the compile job (see product-build-linux.yml, which must set -# VSCODE_RUN_TESTS) with the selected test IDs. Retrying a test job skips the -# test tasks that already passed in an earlier attempt. +# VSCODE_RUN_TESTS) with the selected test IDs. Failed unit, Agent Host E2E and +# node.js integration tests are rerun, as in the pull request workflows. +# Retrying a test job skips the test tasks that already passed in an earlier +# attempt. jobs: - job: Linux_${{ parameters.VSCODE_ARCH }}_Test_${{ parameters.VSCODE_JOB_NAME }} displayName: Linux (${{ upper(parameters.VSCODE_ARCH) }}) - ${{ parameters.VSCODE_JOB_DISPLAY_NAME }} @@ -26,12 +28,9 @@ jobs: NPM_ARCH: ${{ parameters.NPM_ARCH }} VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} templateContext: - # Defender for Linux can block the 1ES PT antimalware scan of the outputs for 45-55 min (see - # product-build-linux-cli.yml), so cap it. Until that's fixed the cap is 2 min, which also - # stops some scans that aren't blocked (up to 7 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputs: - output: pipelineArtifact targetPath: $(Build.SourcesDirectory)/.build/crashes @@ -68,3 +67,4 @@ jobs: parameters: VSCODE_TEST_IDS: ${{ parameters.VSCODE_TEST_IDS }} VSCODE_COMPILE_TEST_SUITES: true + VSCODE_RERUN_FAILED_TESTS: true diff --git a/build/azure-pipelines/linux/product-build-linux.yml b/build/azure-pipelines/linux/product-build-linux.yml index 83ca17a97f5d..23ae412ebf2a 100644 --- a/build/azure-pipelines/linux/product-build-linux.yml +++ b/build/azure-pipelines/linux/product-build-linux.yml @@ -41,11 +41,8 @@ jobs: ${{ else }}: analyzeTargetGlob: '$(Agent.BuildDirectory)/VSCode-linux-$(VSCODE_ARCH)/**/*.node;$(Agent.BuildDirectory)/vscode-server-linux-$(VSCODE_ARCH)/**/*.node;$(Agent.BuildDirectory)/vscode-server-linux-$(VSCODE_ARCH)-web/**/*.node' preReleaseVersion: '4.3.1' - # Defender for Linux can block the 1ES PT antimalware scan of the outputs for 45-55 min (see - # product-build-linux-cli.yml), so cap it. Until that's fixed the cap is 2 min, which also - # stops some scans that aren't blocked (up to 7 min). antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputs: - output: pipelineArtifact targetPath: $(Build.ArtifactStagingDirectory)/compilation @@ -125,12 +122,9 @@ jobs: NPM_ARCH: ${{ parameters.NPM_ARCH }} VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} templateContext: - # Defender for Linux can block the 1ES PT antimalware scan of the outputs for 45-55 min (see - # product-build-linux-cli.yml), so cap it. Until that's fixed the cap is 2 min, which also - # stops some scans that aren't blocked (up to 7 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' outputParentDirectory: $(Build.ArtifactStagingDirectory)/out outputs: - output: pipelineArtifact diff --git a/build/azure-pipelines/linux/product-smoke-flaky-linux.yml b/build/azure-pipelines/linux/product-smoke-flaky-linux.yml index 59866bdcf4c3..6ffb0ae813ed 100644 --- a/build/azure-pipelines/linux/product-smoke-flaky-linux.yml +++ b/build/azure-pipelines/linux/product-smoke-flaky-linux.yml @@ -9,6 +9,12 @@ parameters: type: boolean - name: iterations type: object + # 20 Electron and 20 node.js unit iterations don't fit in one job within its + # timeout, so they are split across parallel jobs by odd and even iteration + # number, like the Windows ones (see ../win32/product-smoke-flaky-win32.yml). + - name: iterationShards + type: object + default: [odd, even] jobs: - template: ../common/product-smoke-flaky-build.yml@self @@ -47,65 +53,74 @@ jobs: displayName: Archive packaged server for reuse by test jobs - ${{ if eq(parameters.VSCODE_TEST_UNIT, true) }}: - - template: ../common/product-smoke-flaky-test.yml@self - parameters: - jobName: LinuxSmokeFlakyUnit - buildJobName: LinuxSmokeFlakyBuild - displayName: Linux Unit Tests - platform: linux - arch: x64 - testName: unit - artifactPrefix: smoke-flaky-linux-x64 - artifacts: - - name: repo - displayName: Download built workspace - display: ":10" - extractArtifactSteps: - - script: | - set -e - mkdir -p $(Build.SourcesDirectory) - tar -xzf $(Pipeline.Workspace)/smoke-flaky-linux-x64-repo/repo.tar.gz -C $(Build.SourcesDirectory) - displayName: Extract built workspace - setupSteps: - - script: | - set -e - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y pkg-config \ - xvfb \ - libgtk-3-0 \ - libxkbfile-dev \ - libkrb5-dev \ - libgbm1 \ - rpm \ - bubblewrap \ - socat - sudo cp build/azure-pipelines/linux/xvfb.init /etc/init.d/xvfb - sudo chmod +x /etc/init.d/xvfb - sudo update-rc.d xvfb defaults - sudo service xvfb start - displayName: Setup system services - postSetupSteps: - - script: | - set -e - ELECTRON_ROOT=.build/electron - sudo chown root $ELECTRON_ROOT/chrome-sandbox - sudo chmod 4755 $ELECTRON_ROOT/chrome-sandbox - displayName: Change setuid helper binary permission - testSteps: - - ${{ each i in parameters.iterations }}: - - script: ./scripts/test.sh --build --tfs "Unit Tests" - env: - VSCODE_SKIP_PRELAUNCH: '1' - displayName: "🧪 Unit test iteration ${{ i }}/${{ length(parameters.iterations) }} (Electron)" - continueOnError: true - timeoutInMinutes: 15 - - ${{ each i in parameters.iterations }}: + - ${{ each shard in parameters.iterationShards }}: + - template: ../common/product-smoke-flaky-test.yml@self + parameters: + jobName: LinuxSmokeFlakyUnit_${{ shard }} + buildJobName: LinuxSmokeFlakyBuild + displayName: Linux Unit Tests (${{ shard }} iterations) + platform: linux + arch: x64 + testName: unit-${{ shard }} + # Fits 10 Electron and 10 node.js iterations at their 20 and 15 minute + # step timeouts, plus job setup. + timeoutInMinutes: 370 + artifactPrefix: smoke-flaky-linux-x64 + artifacts: + - name: repo + displayName: Download built workspace + display: ":10" + extractArtifactSteps: - script: | set -e - pnpm run test-node --build - displayName: "🧪 Unit test iteration ${{ i }}/${{ length(parameters.iterations) }} (node.js)" - continueOnError: true - timeoutInMinutes: 15 + mkdir -p $(Build.SourcesDirectory) + tar -xzf $(Pipeline.Workspace)/smoke-flaky-linux-x64-repo/repo.tar.gz -C $(Build.SourcesDirectory) + displayName: Extract built workspace + setupSteps: + - script: | + set -e + ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update + ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y pkg-config \ + xvfb \ + libgtk-3-0 \ + libxkbfile-dev \ + libkrb5-dev \ + libgbm1 \ + rpm \ + bubblewrap \ + socat + sudo cp build/azure-pipelines/linux/xvfb.init /etc/init.d/xvfb + sudo chmod +x /etc/init.d/xvfb + sudo update-rc.d xvfb defaults + sudo service xvfb start + displayName: Setup system services + postSetupSteps: + - script: | + set -e + ELECTRON_ROOT=.build/electron + sudo chown root $ELECTRON_ROOT/chrome-sandbox + sudo chmod 4755 $ELECTRON_ROOT/chrome-sandbox + displayName: Change setuid helper binary permission + testSteps: + # Template expressions have no arithmetic, so an iteration's parity is + # read from its last digit. The odd shard keeps odd iterations and the + # even shard keeps the rest. + - ${{ each i in parameters.iterations }}: + - ${{ if xor(eq(shard, 'even'), or(endsWith(format('{0}', i), '1'), endsWith(format('{0}', i), '3'), endsWith(format('{0}', i), '5'), endsWith(format('{0}', i), '7'), endsWith(format('{0}', i), '9'))) }}: + - script: ./scripts/test.sh --build --tfs "Unit Tests" + env: + VSCODE_SKIP_PRELAUNCH: '1' + displayName: "🧪 Unit test iteration ${{ i }}/${{ length(parameters.iterations) }} (Electron)" + continueOnError: true + timeoutInMinutes: 20 + - ${{ each i in parameters.iterations }}: + - ${{ if xor(eq(shard, 'even'), or(endsWith(format('{0}', i), '1'), endsWith(format('{0}', i), '3'), endsWith(format('{0}', i), '5'), endsWith(format('{0}', i), '7'), endsWith(format('{0}', i), '9'))) }}: + - script: | + set -e + pnpm run test-node --build + displayName: "🧪 Unit test iteration ${{ i }}/${{ length(parameters.iterations) }} (node.js)" + continueOnError: true + timeoutInMinutes: 15 - ${{ if eq(parameters.VSCODE_TEST_INTEGRATION, true) }}: - template: ../common/product-smoke-flaky-test.yml@self diff --git a/build/azure-pipelines/linux/steps/product-build-linux-package.yml b/build/azure-pipelines/linux/steps/product-build-linux-package.yml index 43786369c98a..dcc79e6f9b9c 100644 --- a/build/azure-pipelines/linux/steps/product-build-linux-package.yml +++ b/build/azure-pipelines/linux/steps/product-build-linux-package.yml @@ -138,8 +138,19 @@ steps: displayName: Login to Container Registry - ${{ if eq(parameters.VSCODE_BUILD_LINUX_SNAP, true) }}: + - task: Npm@1 + displayName: Download openssl prebuilt for snap + inputs: + command: custom + customCommand: pack @vscode-internal/openssl-prebuilt@0.0.11 + customRegistry: useFeed + customFeed: "Monaco/openssl-prebuilt" + workingDir: $(Build.ArtifactStagingDirectory) + - script: | set -e + mkdir -p .build/linux/snap/openssl + tar -xzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=3 --directory=.build/linux/snap/openssl package/x64-linux/lib/libcrypto.a package/x64-linux/lib/libssl.a pnpm run gulp "vscode-linux-$(VSCODE_ARCH)-prepare-snap" sudo -E docker run -e VSCODE_ARCH -e VSCODE_QUALITY -v $(pwd):/work -w /work vscodehub.azurecr.io/vscode-linux-build-agent:snapcraft-x64@sha256:ab4a88c4d85e0d7a85acabba59543f7143f575bab2c0b2b07f5b77d4a7e491ff /bin/bash -c "./build/azure-pipelines/linux/build-snap.sh" diff --git a/build/azure-pipelines/linux/steps/product-build-linux-setup.yml b/build/azure-pipelines/linux/steps/product-build-linux-setup.yml index 2c38e8755679..c960479ab52a 100644 --- a/build/azure-pipelines/linux/steps/product-build-linux-setup.yml +++ b/build/azure-pipelines/linux/steps/product-build-linux-setup.yml @@ -57,20 +57,13 @@ steps: - template: ../../common/apply-sdk-canary.yml@self - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts linux $VSCODE_ARCH $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ../../common/restore-pnpm-store.yml@self + parameters: + # The store holds the packages for the agent's platform and architecture (which the key adds), + # whatever architecture the job builds for (npm_config_arch only affects native builds), so all + # Linux builds on the same agents share one store. + keyArgs: linux + os: linux - script: | set -e @@ -109,10 +102,7 @@ steps: env: GITHUB_TOKEN: "$(github-token-code-oss)" displayName: Install build dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - # Step will be used by both verify glibcxx version for remote server and building rpm package, - # hence avoid adding it behind NODE_MODULES_RESTORED condition. - script: | set -e SYSROOT_ARCH=$VSCODE_ARCH @@ -156,7 +146,6 @@ steps: FOUNDRY_LOCAL_NUGET_MODE: dotnet FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where tests can write it to @@ -171,16 +160,11 @@ steps: displayName: Verify native optional dependency binaries - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../../common/prune-pnpm-store.yml@self + parameters: + os: linux - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality diff --git a/build/azure-pipelines/linux/steps/product-build-linux-test.yml b/build/azure-pipelines/linux/steps/product-build-linux-test.yml index 44367796bee1..b0ddecf3a5c1 100644 --- a/build/azure-pipelines/linux/steps/product-build-linux-test.yml +++ b/build/azure-pipelines/linux/steps/product-build-linux-test.yml @@ -5,6 +5,12 @@ parameters: - name: VSCODE_COMPILE_TEST_SUITES type: boolean default: false + # Reruns failed unit, Agent Host E2E and node.js integration tests, like the + # pull request workflows do (the extension host suites are not rerun). Only + # the product build test jobs set it. + - name: VSCODE_RERUN_FAILED_TESTS + type: boolean + default: false # Each test task records a checkpoint once it passes, and retries of the job # skip the test tasks that already passed in an earlier attempt of the same run. @@ -61,7 +67,7 @@ steps: parameters: testId: unit-electron testStep: - script: ./scripts/test.sh --build --tfs "Unit Tests" + script: ./scripts/test.sh --build --tfs "Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_SKIP_PRELAUNCH: '1' displayName: 🧪 Run unit tests (Electron) @@ -75,7 +81,7 @@ steps: script: | set -e mkdir -p .build/crashes - pnpm run test-node --build + pnpm run test-node --build${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: NODE_OPTIONS: "--report-on-fatalerror --report-uncaught-exception --report-directory=.build/crashes" displayName: 🧪 Run unit tests (node.js) @@ -86,7 +92,7 @@ steps: parameters: testId: unit-browser-chromium testStep: - script: pnpm run test-browser-no-install --build --browser chromium --tfs "Browser Unit Tests" + script: pnpm run test-browser-no-install --build --browser chromium --tfs "Browser Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: DEBUG: "*browser*" displayName: 🧪 Run unit tests (Browser, Chromium) @@ -130,7 +136,7 @@ steps: APP_NAME=$(node -p "require(\"$APP_ROOT/resources/app/product.json\").applicationName") INTEGRATION_TEST_APP_NAME="$APP_NAME" \ INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME" \ - ./scripts/test-agent-host-e2e.sh --build --tfs "Integration Tests" + ./scripts/test-agent-host-e2e.sh --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_REMOTE_SERVER_PATH: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH) VSCODE_SKIP_PRELAUNCH: '1' @@ -151,7 +157,7 @@ steps: APP_NAME=$(node -p "require(\"$APP_ROOT/resources/app/product.json\").applicationName") INTEGRATION_TEST_APP_NAME="$APP_NAME" \ INTEGRATION_TEST_ELECTRON_PATH="$APP_ROOT/$APP_NAME" \ - ./scripts/test-integration.sh --build --tfs "Integration Tests" + ./scripts/test-integration.sh --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_REMOTE_SERVER_PATH: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH) VSCODE_SKIP_PRELAUNCH: '1' diff --git a/build/azure-pipelines/oss/installed-packages.test.ts b/build/azure-pipelines/oss/installed-packages.test.ts new file mode 100644 index 000000000000..b7ef450b058e --- /dev/null +++ b/build/azure-pipelines/oss/installed-packages.test.ts @@ -0,0 +1,93 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/*--------------------------------------------------------------------------------------------- + * Focused unit checks for collectInstalledPackages() in scan-licenses.ts, which lists the + * packages of a node_modules folder for Sections 1, 2 and 5. + * + * Run: npx tsx installed-packages.test.ts + * + * Covers (no network required): + * 1. pnpm's hoisted layout: the top-level packages (`.pnpm` holds only lock.yaml). + * 2. pnpm's isolated layout: the top-level links, then the store's hoisting folder, then the + * package folders of the store, without the links to their dependencies. + *--------------------------------------------------------------------------------------------*/ + +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { collectInstalledPackages } from './scan-licenses.js'; + +let passed = 0; +let failed = 0; + +function check(name: string, cond: boolean): void { + if (cond) { + passed++; + console.log(` ok ${name}`); + } else { + failed++; + console.error(` FAIL ${name}`); + } +} + +function writePackage(dir: string, name: string, version: string): void { + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version })); +} + +function link(target: string, linkPath: string): void { + fs.mkdirSync(path.dirname(linkPath), { recursive: true }); + fs.symlinkSync(target, linkPath, 'junction'); +} + +/** The packages of `nmDir`, as ` `. */ +function listed(nmDir: string): string[] { + return collectInstalledPackages(nmDir).map(({ name, dir }) => `${name} ${path.relative(nmDir, dir).split(path.sep).join('/')}`); +} + +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'installed-packages-')); +try { + // -- 1. hoisted layout -------------------------------------------------------- + console.log('hoisted layout:'); + const hoisted = path.join(tmp, 'hoisted', 'node_modules'); + writePackage(path.join(hoisted, 'a'), 'a', '1.0.0'); + writePackage(path.join(hoisted, '@s', 'c'), '@s/c', '3.0.0'); + writePackage(path.join(hoisted, 'a', 'node_modules', 'b'), 'b', '1.0.0'); + fs.mkdirSync(path.join(hoisted, '.pnpm')); + fs.writeFileSync(path.join(hoisted, '.pnpm', 'lock.yaml'), ''); + check('lists the top-level packages only', JSON.stringify(listed(hoisted).sort()) === JSON.stringify(['@s/c @s/c', 'a a'])); + + // -- 2. isolated layout ------------------------------------------------------- + console.log('isolated layout:'); + const isolated = path.join(tmp, 'isolated', 'node_modules'); + const store = path.join(isolated, '.pnpm'); + writePackage(path.join(store, 'a@1.0.0', 'node_modules', 'a'), 'a', '1.0.0'); + writePackage(path.join(store, 'b@1.0.0', 'node_modules', 'b'), 'b', '1.0.0'); + writePackage(path.join(store, 'b@2.0.0', 'node_modules', 'b'), 'b', '2.0.0'); + writePackage(path.join(store, '@s+c@3.0.0', 'node_modules', '@s', 'c'), '@s/c', '3.0.0'); + fs.writeFileSync(path.join(store, 'lock.yaml'), ''); + // A direct dependency of the install root, a dependency of `a`, and the store's hoisting folder. + link(path.join(store, 'a@1.0.0', 'node_modules', 'a'), path.join(isolated, 'a')); + link(path.join(store, 'b@2.0.0', 'node_modules', 'b'), path.join(store, 'a@1.0.0', 'node_modules', 'b')); + link(path.join(store, 'b@2.0.0', 'node_modules', 'b'), path.join(store, 'node_modules', 'b')); + check('lists the top level, the hoisting folder, then the store packages', JSON.stringify(listed(isolated)) === JSON.stringify([ + 'a a', + 'b .pnpm/node_modules/b', + '@s/c .pnpm/@s+c@3.0.0/node_modules/@s/c', + 'a .pnpm/a@1.0.0/node_modules/a', + 'b .pnpm/b@1.0.0/node_modules/b', + 'b .pnpm/b@2.0.0/node_modules/b', + ])); +} finally { + fs.rmSync(tmp, { recursive: true, force: true }); +} + +// -- summary ------------------------------------------------------------------ +console.log(''); +console.log(`installed-packages unit checks: ${passed} passed, ${failed} failed`); +if (failed > 0) { + process.exit(1); +} diff --git a/build/azure-pipelines/oss/scan-licenses.ts b/build/azure-pipelines/oss/scan-licenses.ts index 8c63949f481c..baf04a99bd21 100644 --- a/build/azure-pipelines/oss/scan-licenses.ts +++ b/build/azure-pipelines/oss/scan-licenses.ts @@ -547,6 +547,36 @@ function collectPackagesInNodeModules(nmDir: string): string[] { return packages; } +/** + * Returns the packages installed in the node_modules folder `nmDir`, each as its name in a + * node_modules folder (scoped names included) and its folder: the top-level packages of `nmDir`, + * then, when pnpm installed `nmDir` with the isolated linker, the packages of its virtual store + * (`.pnpm`). + * + * With pnpm's hoisted linker, every package of an install root has a folder in its node_modules + * folders, and `.pnpm` holds no packages. With the isolated linker, the top level holds only the + * install root's direct dependencies (links into the store), and the packages are in + * `.pnpm//node_modules/`, next to links to their dependencies. Callers keep the first + * folder that they find for a name, so the store's hoisting folder (`.pnpm/node_modules`, which + * links one version of each package) comes before the package folders of the store. + */ +export function collectInstalledPackages(nmDir: string): Array<{ name: string; dir: string }> { + const inFolder = (folder: string) => collectPackagesInNodeModules(folder).map(name => ({ name, dir: path.join(folder, ...name.split('/')) })); + const result = inFolder(nmDir); + const store = path.join(nmDir, '.pnpm'); + if (!fs.existsSync(store)) { + return result; + } + result.push(...inFolder(path.join(store, 'node_modules'))); + for (const id of fs.readdirSync(store).sort()) { + if (id === 'node_modules') { + continue; + } + result.push(...inFolder(path.join(store, id, 'node_modules')).filter(({ dir }) => !fs.lstatSync(dir).isSymbolicLink())); + } + return result; +} + /** * Returns the node_modules folders nested in the packages of `nmDir`, at any depth. */ @@ -1172,7 +1202,9 @@ async function main(): Promise { // `extensions` is a pnpm install root: with the hoisted layout most extension // dependencies are in extensions/node_modules, after the extensions' own folders. // Its nested node_modules folders come last, for packages that pnpm didn't - // hoist (e.g. `emmet`, whose name a workspace project has). + // hoist (e.g. `emmet`, whose name a workspace project has). With the isolated + // layout they are in the store of extensions/node_modules (see + // collectInstalledPackages). for (const ext of [...extensions, '(extensions)']) { const nmDirs = ext === '(extensions)' ? [path.join(extensionsDir, 'node_modules'), ...collectNestedNodeModules(path.join(extensionsDir, 'node_modules'))] : [ path.join(extensionsDir, ext, 'node_modules'), @@ -1181,10 +1213,7 @@ async function main(): Promise { ]; for (const nmDir of nmDirs) { - const packages = collectPackagesInNodeModules(nmDir); - - for (const pkgName of packages) { - const pkgDir = path.join(nmDir, ...pkgName.split('/')); + for (const { name: pkgName, dir: pkgDir } of collectInstalledPackages(nmDir)) { const pkgInfo = readPkgJson(pkgDir); const resolvedName = pkgInfo?.name || pkgName; const key = resolvedName.toLowerCase(); @@ -1249,10 +1278,7 @@ async function main(): Promise { const rootNmDir = path.join(repoRoot, 'node_modules'); if (fs.existsSync(rootNmDir)) { - const rootPackages = collectPackagesInNodeModules(rootNmDir); - - for (const pkgName of rootPackages) { - const pkgDir = path.join(rootNmDir, ...pkgName.split('/')); + for (const { name: pkgName, dir: pkgDir } of collectInstalledPackages(rootNmDir)) { const pkgInfo = readPkgJson(pkgDir); const resolvedName = pkgInfo?.name || pkgName; const key = resolvedName.toLowerCase(); @@ -1689,8 +1715,7 @@ async function main(): Promise { const pbSeedKeys = new Set(); const pbSeedParents: Array<{ key: string; dir: string; optDeps: Record }> = []; for (const root of pbRoots) { - for (const pkgName of collectPackagesInNodeModules(root)) { - const dir = path.join(root, ...pkgName.split('/')); + for (const { name: pkgName, dir } of collectInstalledPackages(root)) { const ck = pkgName.toLowerCase(); if (!pbOnDisk.has(ck)) { pbOnDisk.set(ck, dir); diff --git a/build/azure-pipelines/product-build-ado-ci.yml b/build/azure-pipelines/product-build-ado-ci.yml index 2b110bbb76f3..3a1eb4bd63d6 100644 --- a/build/azure-pipelines/product-build-ado-ci.yml +++ b/build/azure-pipelines/product-build-ado-ci.yml @@ -546,28 +546,3 @@ extends: - smoke-agents-kerberos-pac-proxy - - stage: node_modules - dependsOn: [] - jobs: - - template: build/azure-pipelines/win32/product-build-win32-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - VSCODE_POOL_NAME: 1es-windows-2022-x64-wus3 - - template: build/azure-pipelines/linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm64 - VSCODE_ARCH: arm64 - - template: build/azure-pipelines/linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm - VSCODE_ARCH: armhf - - template: build/azure-pipelines/alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: build/azure-pipelines/alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - - template: build/azure-pipelines/darwin/product-build-darwin-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: build/azure-pipelines/web/product-build-web-node-modules.yml@self diff --git a/build/azure-pipelines/product-build-template.yml b/build/azure-pipelines/product-build-template.yml index 9a775048cbfd..d249b67d54c3 100644 --- a/build/azure-pipelines/product-build-template.yml +++ b/build/azure-pipelines/product-build-template.yml @@ -70,6 +70,9 @@ parameters: displayName: "🎯 Web" type: boolean default: true + - name: VSCODE_BUILD_WEB_MOBILE + type: boolean + default: false - name: VSCODE_PUBLISH displayName: "Publish to builds.code.visualstudio.com" type: boolean @@ -92,6 +95,9 @@ parameters: stages: + - ${{ if and(eq(parameters.VSCODE_BUILD_WEB_MOBILE, true), or(eq(variables.VSCODE_CIBUILD, true), ne(parameters.VSCODE_BUILD_WEB, true))) }}: + - 'Mobile web requires a Product build with VSCODE_BUILD_WEB=true': error + - stage: Quality dependsOn: [] pool: @@ -664,6 +670,8 @@ stages: dependsOn: [] jobs: - template: web/product-build-web.yml@self + parameters: + VSCODE_BUILD_WEB_MOBILE: ${{ parameters.VSCODE_BUILD_WEB_MOBILE }} - ${{ if eq(variables['VSCODE_PUBLISH'], true) }}: - stage: Publish @@ -976,32 +984,6 @@ stages: parameters: VSCODE_RELEASE: ${{ parameters.VSCODE_RELEASE }} - - ${{ if eq(variables['VSCODE_CIBUILD'], true) }}: - - stage: node_modules - dependsOn: [] - jobs: - - template: win32/product-build-win32-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - - template: linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm64 - VSCODE_ARCH: arm64 - - template: linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm - VSCODE_ARCH: armhf - - template: alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - - template: darwin/product-build-darwin-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: web/product-build-web-node-modules.yml@self - - ${{ if and(eq(variables['VSCODE_CIBUILD'], false), eq(parameters.VSCODE_RUN_APISCAN, true)) }}: - stage: APIScan dependsOn: [] diff --git a/build/azure-pipelines/product-build.yml b/build/azure-pipelines/product-build.yml index e213bd0f5f10..14d156e727fc 100644 --- a/build/azure-pipelines/product-build.yml +++ b/build/azure-pipelines/product-build.yml @@ -103,6 +103,10 @@ parameters: displayName: "🎯 Web" type: boolean default: true + - name: VSCODE_BUILD_WEB_MOBILE + displayName: "Build the optional mobile web archive" + type: boolean + default: false - name: VSCODE_PUBLISH displayName: "Publish to builds.code.visualstudio.com" type: boolean @@ -327,13 +331,8 @@ extends: enabled: true enableExclusions: true exclusionsFilePath: $(Build.SourcesDirectory)/.eslint-ignore - # Defender for Linux can block the scan of a job's outputs for the length - # of a background scan of the agent, and without a timeout the scan runs - # until the job limit. On a timeout, 1ES logs an error and the publish - # still runs. This is the default for the jobs that don't set their own - # cap; 2 min matches those jobs until the Defender issue is fixed. antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' sourceAnalysisPool: ${{ variables.VSCODE_WINDOWS_POOL }} createAdoIssuesForJustificationsForDisablement: false containers: @@ -343,6 +342,9 @@ extends: networkIsolationPolicy: Permissive,CFSClean,CFSClean2,CFSClean3 stages: + - ${{ if and(eq(parameters.VSCODE_BUILD_WEB_MOBILE, true), or(eq(variables.VSCODE_CIBUILD, true), ne(parameters.VSCODE_BUILD_WEB, true))) }}: + - 'Mobile web requires a Product build with VSCODE_BUILD_WEB=true': error + # Reject at template expansion, before allocating agents. Web uploads the matching # commit's webview bootstrap assets even when VSCODE_PUBLISH is false. - ${{ if and(eq(variables.VSCODE_ARTIFACT_SANITY_REQUIRES_WEB, true), or(eq(variables.VSCODE_CIBUILD, true), ne(parameters.VSCODE_BUILD_WEB, true))) }}: @@ -936,6 +938,7 @@ extends: - template: build/azure-pipelines/web/product-build-web.yml@self parameters: VSCODE_POOL_NAME: ${{ variables.VSCODE_UBUNTU_POOL }} + VSCODE_BUILD_WEB_MOBILE: ${{ parameters.VSCODE_BUILD_WEB_MOBILE }} - ${{ if eq(variables['VSCODE_PUBLISH'], true) }}: - stage: Publish @@ -1521,32 +1524,6 @@ extends: - vscode_client_linux_armhf_archive-unsigned - vscode_client_linux_armhf_deb-package - - ${{ if eq(variables['VSCODE_CIBUILD'], true) }}: - - stage: node_modules - dependsOn: [] - jobs: - - template: build/azure-pipelines/win32/product-build-win32-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - - template: build/azure-pipelines/linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm64 - VSCODE_ARCH: arm64 - - template: build/azure-pipelines/linux/product-build-linux-node-modules.yml@self - parameters: - NPM_ARCH: arm - VSCODE_ARCH: armhf - - template: build/azure-pipelines/alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: build/azure-pipelines/alpine/product-build-alpine-node-modules.yml@self - parameters: - VSCODE_ARCH: arm64 - - template: build/azure-pipelines/darwin/product-build-darwin-node-modules.yml@self - parameters: - VSCODE_ARCH: x64 - - template: build/azure-pipelines/web/product-build-web-node-modules.yml@self - - ${{ if eq(variables['VSCODE_CIBUILD'], false) }}: - stage: APIScan dependsOn: [] diff --git a/build/azure-pipelines/product-copilot-recovery.yml b/build/azure-pipelines/product-copilot-recovery.yml index 17150e6fd231..d65697c3cdf8 100644 --- a/build/azure-pipelines/product-copilot-recovery.yml +++ b/build/azure-pipelines/product-copilot-recovery.yml @@ -46,7 +46,7 @@ extends: parameters: workingDirectory: ./extensions/copilot l10nSourcePaths: ./extensions/copilot/src - nodeVersion: 22.21.x + nodeVersion: 24.x # The copilot extension is bundled with esbuild and vendors prebuilt native # modules (e.g. @os-theme, @picovoice/pvrecorder-node) that depend on a # newer GLIBC than the template's sysroot check allows. The main product diff --git a/build/azure-pipelines/product-copilot.yml b/build/azure-pipelines/product-copilot.yml index 1f9b2c93214a..c42b60282826 100644 --- a/build/azure-pipelines/product-copilot.yml +++ b/build/azure-pipelines/product-copilot.yml @@ -25,14 +25,9 @@ jobs: - name: Codeql.SkipTaskAutoInjection value: true templateContext: - # Defender for Linux can fold the 1ES PT antimalware scan before "Publish Copilot VSIX" into a - # scan of system folders (/opt, /usr/lib) that started before the job, which blocks it for - # 45-55 min, so the job times out before publishing the VSIX. A scan that times out completes - # the step with issues and the VSIX is published. Until that's fixed the cap is 2 min, which - # also stops some scans that aren't blocked (up to 6 min). sdl: antimalwareScan: - scanTimeoutInMinutes: '2' + scanTimeoutInMinutes: '10' steps: - checkout: self path: s diff --git a/build/azure-pipelines/product-quality-checks.yml b/build/azure-pipelines/product-quality-checks.yml index 8a7421b6827d..4a005cd4d1a4 100644 --- a/build/azure-pipelines/product-quality-checks.yml +++ b/build/azure-pipelines/product-quality-checks.yml @@ -1,5 +1,5 @@ parameters: - # Hygiene and ESLint check only the files that the commits of the build change, unless a change can affect other + # Hygiene and oxlint check only the files that the commits of the build change, unless a change can affect other # files (see build/lib/changedFiles.ts). Other builds check every file. - name: VSCODE_CHECK_CHANGED_FILES type: boolean @@ -35,20 +35,10 @@ jobs: condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts quality $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ./common/restore-pnpm-store.yml@self + parameters: + keyArgs: quality + os: linux - script: | set -e @@ -83,7 +73,6 @@ jobs: env: GITHUB_TOKEN: "$(github-token-code-oss)" displayName: Install build dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: | set -e @@ -117,7 +106,6 @@ jobs: FOUNDRY_LOCAL_NUGET_MODE: dotnet FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where tests can write it @@ -131,16 +119,11 @@ jobs: displayName: Verify native optional dependency binaries - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ./common/prune-pnpm-store.yml@self + parameters: + os: linux - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality @@ -407,7 +390,7 @@ jobs: continueOnError: true # The NOTICE outputs are already in the artifact staging directory. Remove the - # intermediates from the repository so ESLint and hygiene below don't check them. + # intermediates from the repository so oxlint and hygiene below don't check them. - script: rm -rf .oss-build-out ThirdPartyNotices.generated.txt displayName: Remove NOTICE intermediates @@ -415,17 +398,18 @@ jobs: - script: node build/azure-pipelines/common/computeChangedSince.ts env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - displayName: Determine hygiene and ESLint scope + displayName: Determine hygiene and oxlint scope - # With VSCODE_CHANGED_SINCE, hygiene and ESLint check only the files that changed since that commit, so they + # With VSCODE_CHANGED_SINCE, hygiene and oxlint check only the files that changed since that commit, so they # take seconds and fail the job before the compilation checks start. --continue-on-error reports both when both - # fail. ESLint stays out of the compilation checks so that its worker memory doesn't overlap theirs. No `--` - # before the arguments: pnpm passes it on to the script, where it ends option parsing. + # fail. oxlint runs the rules of eslint.config.js (see oxlint.config.ts) and stays out of the compilation checks + # so that the memory of its processes doesn't overlap theirs. No `--` before the arguments: pnpm passes it on to + # the script, where it ends option parsing. - script: | set -e changed_since="${VSCODE_CHANGED_SINCE:+ --changed-since $VSCODE_CHANGED_SINCE}" - pnpm exec npm-run-all2 -lp --continue-on-error "hygiene$changed_since" "eslint$changed_since" - displayName: Hygiene & ESLint + pnpm exec npm-run-all2 -lp --continue-on-error "hygiene$changed_since" "oxlint$changed_since" + displayName: Hygiene & oxlint - script: pnpm exec npm-run-all2 -lp core-ci valid-layers-check define-class-fields-check vscode-dts-compile-check tsec-compile-check test-build-scripts env: @@ -433,7 +417,7 @@ jobs: displayName: Compile - ${{ else }}: - - script: pnpm exec npm-run-all2 -lp core-ci hygiene eslint valid-layers-check define-class-fields-check vscode-dts-compile-check tsec-compile-check test-build-scripts + - script: pnpm exec npm-run-all2 -lp core-ci hygiene oxlint valid-layers-check define-class-fields-check vscode-dts-compile-check tsec-compile-check test-build-scripts env: GITHUB_TOKEN: "$(github-token-code-oss)" displayName: Compile & Hygiene diff --git a/build/azure-pipelines/product-smoke-flaky.yml b/build/azure-pipelines/product-smoke-flaky.yml index f39970b7b8d7..3d6bbbb37e13 100644 --- a/build/azure-pipelines/product-smoke-flaky.yml +++ b/build/azure-pipelines/product-smoke-flaky.yml @@ -4,9 +4,10 @@ # fans out to parallel Unit/Integration/Smoke jobs that download and reuse that # build instead of recompiling. Each job repeats its suite 20 times, with each # repetition as its own step (continueOnError) so a single flaky failure does not -# abort the run and every iteration produces its own timeline record. Windows -# unit and integration iterations are too slow to fit in one job, so each is -# split into an odd-iteration and an even-iteration job. The +# abort the run and every iteration produces its own timeline record. Unit +# iterations on Windows and Linux, and integration iterations on Windows, are too +# slow to fit in one job, so each is split into an odd-iteration and an +# even-iteration job. The # pass/fail tally is read back from the build timeline by the vscode-probot # `SmokeFlaky` Azure Function (wired up via an ADO service hook on build # completion), which posts a summary to the Slack #build channel. @@ -19,18 +20,18 @@ pr: none trigger: none schedules: - # Run the insider flavor twice per day. `always: true` forces the runs even when - # there are no new commits, since flaky behavior is environmental and worth - # sampling regardless of source changes. - - cron: "0 3,16 * * *" - displayName: Twice daily at 03:00 and 16:00 UTC (insider smoke flaky detection) + # Run the insider flavor once per day, after the 05:00 UTC insider has its macOS agents and well before the + # 11:00 UTC one, since both use the shared macOS pool. `always: true` forces the runs even when there are + # no new commits, since flaky behavior is environmental and worth sampling regardless of source changes. + - cron: "0 6 * * *" + displayName: Daily at 06:00 UTC (insider smoke flaky detection) branches: include: - main always: true # Also sample the stable flavor on Monday mornings. - - cron: "0 3 * * 1" - displayName: Monday at 03:00 UTC (stable smoke flaky detection) + - cron: "0 6 * * 1" + displayName: Monday at 06:00 UTC (stable smoke flaky detection) branches: include: - main @@ -86,7 +87,7 @@ parameters: variables: - name: VSCODE_QUALITY - value: $[iif(eq(variables['Build.CronSchedule.DisplayName'], 'Monday at 03:00 UTC (stable smoke flaky detection)'), 'stable', '${{ parameters.VSCODE_QUALITY }}')] + value: $[iif(eq(variables['Build.CronSchedule.DisplayName'], 'Monday at 06:00 UTC (stable smoke flaky detection)'), 'stable', '${{ parameters.VSCODE_QUALITY }}')] - name: NPM_REGISTRY value: ${{ parameters.NPM_REGISTRY }} # Compile templates skip publish/codesign/artifact-staging when VSCODE_CIBUILD diff --git a/build/azure-pipelines/upload-cdn.ts b/build/azure-pipelines/upload-cdn.ts index a6fdec302e2f..2460765b7cec 100644 --- a/build/azure-pipelines/upload-cdn.ts +++ b/build/azure-pipelines/upload-cdn.ts @@ -10,6 +10,7 @@ import { filter, gzip, azureStorage } from '../lib/gulp/facade.ts'; import mime from 'mime'; import { ClientAssertionCredential } from '@azure/identity'; import { VinylStat } from '../lib/util.ts'; +import { getWebCdnConfiguration, validateMobileWebCdnIdentity } from './web/cdnConfiguration.ts'; const commit = process.env['BUILD_SOURCEVERSION']; const credential = new ClientAssertionCredential(process.env['AZURE_TENANT_ID']!, process.env['AZURE_CLIENT_ID']!, () => Promise.resolve(process.env['AZURE_ID_TOKEN']!)); @@ -74,19 +75,23 @@ function wait(stream: es.ThroughStream): Promise { } async function main(): Promise { + const configuration = getWebCdnConfiguration(process.argv.slice(2), process.env.VSCODE_QUALITY, commit); + if (configuration.mobile) { + await validateMobileWebCdnIdentity(configuration.source, process.env.VSCODE_QUALITY!, commit!); + } const files: string[] = []; const options = (compressed: boolean) => ({ account: process.env.AZURE_STORAGE_ACCOUNT, credential, container: '$web', - prefix: `${process.env.VSCODE_QUALITY}/${commit}/`, + prefix: configuration.prefix, contentSettings: { contentEncoding: compressed ? 'gzip' : undefined, cacheControl: 'max-age=31536000, public' } }); - const all = vfs.src('**', { cwd: '../vscode-web', base: '../vscode-web', dot: true }) + const all = vfs.src(configuration.patterns, { cwd: configuration.source, base: configuration.source, dot: true }) .pipe(filter(f => !f.isDirectory())); const compressed = all diff --git a/build/azure-pipelines/upload-sourcemaps.ts b/build/azure-pipelines/upload-sourcemaps.ts index b036736d5fc8..cb3b0529cdd1 100644 --- a/build/azure-pipelines/upload-sourcemaps.ts +++ b/build/azure-pipelines/upload-sourcemaps.ts @@ -8,7 +8,7 @@ import es from 'event-stream'; import Vinyl from 'vinyl'; import vfs from 'vinyl-fs'; import * as util from '../lib/util.ts'; -import { getProductionDependencies } from '../lib/dependencies.ts'; +import { getProductionDependencies, toPackagedLayout } from '../lib/dependencies.ts'; import { ClientAssertionCredential } from '@azure/identity'; import Stream from 'stream'; import { azureStorage } from '../lib/gulp/facade.ts'; @@ -37,8 +37,9 @@ function main(): Promise { sources.push(vs); const productionDependencies = getProductionDependencies(root); - const productionDependenciesSrc = productionDependencies.map((d: string) => path.relative(root, d)).map((d: string) => `./${d}/**/*.map`); + const productionDependenciesSrc = productionDependencies.map(d => path.relative(root, d.source)).map(d => `./${d}/**/*.map`); const nodeModules = vfs.src(productionDependenciesSrc, { base: '.' }) + .pipe(toPackagedLayout(productionDependencies)) .pipe(util.cleanNodeModules(path.join(root, 'build', '.moduleignore'))) .pipe(util.cleanNodeModules(path.join(root, 'build', `.moduleignore.${process.platform}`))); sources.push(nodeModules); diff --git a/build/azure-pipelines/web/cdnConfiguration.ts b/build/azure-pipelines/web/cdnConfiguration.ts new file mode 100644 index 000000000000..ff3d3872b55f --- /dev/null +++ b/build/azure-pipelines/web/cdnConfiguration.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 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { MobileManifest } from '../../next/mobile.ts'; + +/** Mobile has a separate root and inventory; the normal web preloader must never discover it. */ +export function getWebCdnConfiguration(args: readonly string[], quality: string | undefined, commit: string | undefined) { + assert.ok(args.length === 0 || (args.length === 1 && args[0] === '--mobile'), 'Usage: upload-cdn.ts [--mobile]'); + if (args.length === 0) { + return { source: '../vscode-web', prefix: `${quality}/${commit}/`, patterns: ['**'], mobile: false }; + } + assert.match(quality ?? '', /^(stable|insider|exploration)$/, 'Mobile publication requires an official build quality'); + assert.match(commit ?? '', /^[0-9a-f]{40}$/, 'Mobile publication requires BUILD_SOURCEVERSION'); + return { + source: 'out-mobile', + prefix: `agents/mobile/${quality}/${commit}/`, + patterns: ['out/**', 'node_modules/**', 'extensions/**', 'mobile.json'], + mobile: true, + }; +} + +/** The build registry, CDN assets and archive must all describe the same source revision. */ +export async function validateMobileWebCdnIdentity(directory: string, quality: string, commit: string): Promise { + const manifest: MobileManifest = JSON.parse(await readFile(join(directory, 'mobile.json'), 'utf8')); + assert.equal(manifest.schemaVersion, 2, 'Unsupported mobile build inventory'); + assert.equal(manifest.kind, 'sessions-mobile', 'Expected a mobile web build'); + assert.equal(manifest.build?.commit, commit, 'Mobile build does not match BUILD_SOURCEVERSION'); + assert.equal(manifest.build?.quality, quality, 'Mobile build does not match VSCODE_QUALITY'); +} diff --git a/build/azure-pipelines/web/product-build-web-node-modules.yml b/build/azure-pipelines/web/product-build-web-node-modules.yml deleted file mode 100644 index 38559ea19184..000000000000 --- a/build/azure-pipelines/web/product-build-web-node-modules.yml +++ /dev/null @@ -1,117 +0,0 @@ -jobs: - - job: WebNodeModules - displayName: Web - pool: - name: 1es-ubuntu-22.04-x64 - os: linux - timeoutInMinutes: 60 - steps: - - template: ../common/checkout.yml@self - - - template: ../common/setup-node.yml@self - parameters: - os: linux - - - template: ../distro/download-distro.yml@self - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get Secrets" - inputs: - azureSubscription: vscode-oss-build-secrets - KeyVaultName: vscode-oss-build-secrets - SecretsFilter: "github-token-code-oss" - - - script: node build/setup-npm-registry.ts $NPM_REGISTRY - condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Registry - - - template: ../common/apply-sdk-canary.yml@self - - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts web $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: | - set -e - # Set the private NPM registry to the global npmrc file - # so that authentication works for subfolders like build/, remote/, extensions/ etc - # which does not have their own .npmrc file - npm config set registry "$NPM_REGISTRY" - echo "##vso[task.setvariable variable=NPMRC_PATH]$(npm config get userconfig)" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM - - - task: npmAuthenticate@0 - inputs: - workingFile: $(NPMRC_PATH) - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Authentication - - - template: ../common/install-pnpm.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - task: NuGetAuthenticate@1 - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Setup NuGet Authentication - - - script: | - set -e - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update - ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y libkrb5-dev - displayName: Setup system services - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: pnpm run preinstall - displayName: Install Electron headers - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - script: | - set -e - - for i in {1..5}; do # try 5 times - pnpm install --frozen-lockfile && break - if [ $i -eq 5 ]; then - echo "pnpm install failed too many times" >&2 - exit 1 - fi - echo "pnpm install failed $i, trying again..." - done - env: - ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - GITHUB_TOKEN: "$(github-token-code-oss)" - FOUNDRY_LOCAL_NUGET_MODE: dotnet - FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" - displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - # NuGetAuthenticate@1 exposes its access token to all later steps as the - # VSS_NUGET_ACCESSTOKEN environment variable, from where they can write it - # to logs. Only installing dependencies needs it, so clear it now. - - script: echo "##vso[task.setvariable variable=VSS_NUGET_ACCESSTOKEN]" - displayName: Clear package feed credentials - condition: always() - - - script: node build/azure-pipelines/common/checkNativeOptionalDeps.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Verify native optional dependency binaries - - - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Mixin distro node modules - - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive diff --git a/build/azure-pipelines/web/product-build-web.yml b/build/azure-pipelines/web/product-build-web.yml index e65ef367584a..ec8c7c1453ab 100644 --- a/build/azure-pipelines/web/product-build-web.yml +++ b/build/azure-pipelines/web/product-build-web.yml @@ -2,6 +2,9 @@ parameters: - name: VSCODE_POOL_NAME type: string default: 1es-ubuntu-22.04-x64 + - name: VSCODE_BUILD_WEB_MOBILE + type: boolean + default: false jobs: - job: Web @@ -23,6 +26,15 @@ jobs: sbomBuildDropPath: $(Agent.BuildDirectory)/vscode-web sbomPackageName: "VS Code Linux x64 Web (Standalone)" sbomPackageVersion: $(Build.SourceVersion) + - ${{ if eq(parameters.VSCODE_BUILD_WEB_MOBILE, true) }}: + - output: pipelineArtifact + targetPath: $(Build.ArtifactStagingDirectory)/out/web/vscode-web-mobile.tar.gz + artifactName: vscode_web_linux_mobile_archive-unsigned + displayName: Publish mobile web archive + condition: and(succeeded(), ne(variables['WEB_MOBILE_ARCHIVE_PUBLISHED'], 'true')) + sbomBuildDropPath: $(Build.SourcesDirectory)/out-mobile + sbomPackageName: "VS Code Mobile Web" + sbomPackageVersion: $(Build.SourceVersion) steps: - template: ../common/checkout.yml@self @@ -43,20 +55,10 @@ jobs: condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.ts web $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - script: tar -xzf .build/node_modules_cache/cache.tgz - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ../common/restore-pnpm-store.yml@self + parameters: + keyArgs: web + os: linux - script: | set -e @@ -84,11 +86,9 @@ jobs: ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get update ./build/azure-pipelines/linux/apt-retry.sh sudo apt-get install -y libkrb5-dev displayName: Setup system services - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: pnpm run preinstall displayName: Install Electron headers - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - script: | set -e @@ -108,7 +108,6 @@ jobs: FOUNDRY_LOCAL_NUGET_MODE: dotnet FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where they can write it @@ -121,16 +120,11 @@ jobs: displayName: Verify native optional dependency binaries - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - script: | - set -e - node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt - mkdir -p .build/node_modules_cache - tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../common/prune-pnpm-store.yml@self + parameters: + os: linux - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality @@ -207,6 +201,37 @@ jobs: node build/azure-pipelines/upload-nlsmetadata.ts displayName: Upload NLS Metadata + - ${{ if eq(parameters.VSCODE_BUILD_WEB_MOBILE, true) }}: + - script: | + set -e + pnpm run test-mobile + node --test build/lib/test/mobileWebPublication.test.ts + pnpm run bundle-mobile + mkdir -p "$(Build.ArtifactStagingDirectory)/out/web" + tar --owner=0 --group=0 --transform='s,^out-mobile,vscode-web-mobile,' \ + -czf "$(Build.ArtifactStagingDirectory)/out/web/vscode-web-mobile.tar.gz" \ + out-mobile/out out-mobile/node_modules \ + out-mobile/extensions out-mobile/mobile.json + displayName: Build and validate mobile web archive + + - script: | + set -e + AZURE_STORAGE_ACCOUNT="vscodeweb" \ + AZURE_TENANT_ID="$(AZURE_TENANT_ID)" \ + AZURE_CLIENT_ID="$(AZURE_CLIENT_ID)" \ + AZURE_ID_TOKEN="$(AZURE_ID_TOKEN)" \ + node build/azure-pipelines/upload-cdn.ts --mobile + condition: and(succeeded(), eq(variables['VSCODE_PUBLISH'], 'True')) + displayName: Upload mobile web assets to the separate commit directory + + - script: >- + node build/azure-pipelines/common/checkForArtifact.ts + WEB_MOBILE_ARCHIVE_PUBLISHED vscode_web_linux_mobile_archive-unsigned + env: + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + continueOnError: true + displayName: Check for a mobile archive published by an earlier attempt + # Pipeline artifacts can't be overwritten, so a retry of this job must skip # the artifacts that an earlier attempt already published, for example # before an injected SDL step hung (see ../common/checkForArtifact.ts) diff --git a/build/azure-pipelines/win32/product-build-win32-ci.yml b/build/azure-pipelines/win32/product-build-win32-ci.yml index a5400ac19d84..3e8a96c16e5f 100644 --- a/build/azure-pipelines/win32/product-build-win32-ci.yml +++ b/build/azure-pipelines/win32/product-build-win32-ci.yml @@ -43,7 +43,8 @@ jobs: displayName: Publish Log Files sbomEnabled: false isProduction: false - condition: always() + # 1ES PT runs its binary analysis for every published output, so only publish when the logs are needed + condition: not(succeeded()) steps: - template: ./steps/product-build-win32-compile.yml@self parameters: diff --git a/build/azure-pipelines/win32/product-build-win32-node-modules.yml b/build/azure-pipelines/win32/product-build-win32-node-modules.yml deleted file mode 100644 index c3f2d3c92b87..000000000000 --- a/build/azure-pipelines/win32/product-build-win32-node-modules.yml +++ /dev/null @@ -1,110 +0,0 @@ -parameters: - - name: VSCODE_ARCH - type: string - - name: VSCODE_POOL_NAME - type: string - default: 1es-windows-2022-x64 - -jobs: - - job: WindowsNodeModules_${{ parameters.VSCODE_ARCH }} - displayName: Windows (${{ upper(parameters.VSCODE_ARCH) }}) - pool: - name: ${{ parameters.VSCODE_POOL_NAME }} - os: windows - timeoutInMinutes: 60 - variables: - VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} - steps: - - template: ../common/checkout.yml@self - - - template: ../common/setup-node.yml@self - parameters: - os: windows - - - task: UsePythonVersion@0 - inputs: - versionSpec: "3.x" - addToPath: true - - - template: ../distro/download-distro.yml@self - - - task: AzureKeyVault@2 - displayName: "Azure Key Vault: Get Secrets" - inputs: - azureSubscription: vscode-oss-build-secrets - KeyVaultName: vscode-oss-build-secrets - SecretsFilter: "github-token-code-oss" - - - powershell: node build/setup-npm-registry.ts $env:NPM_REGISTRY - condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Registry - - - template: ../common/apply-sdk-canary.yml@self - parameters: - windows: true - - - pwsh: | - mkdir .build -ea 0 - node build/azure-pipelines/common/computeNodeModulesCacheKey.ts win32 $(VSCODE_ARCH) $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - powershell: | - . build/azure-pipelines/win32/exec.ps1 - $ErrorActionPreference = "Stop" - # Set the private NPM registry to the global npmrc file - # so that authentication works for subfolders like build/, remote/, extensions/ etc - # which does not have their own .npmrc file - exec { npm config set registry "$env:NPM_REGISTRY" } - $NpmrcPath = (npm config get userconfig) - echo "##vso[task.setvariable variable=NPMRC_PATH]$NpmrcPath" - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM - - - task: npmAuthenticate@0 - inputs: - workingFile: $(NPMRC_PATH) - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) - displayName: Setup NPM Authentication - - - template: ../common/install-pnpm.yml@self - parameters: - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - powershell: | - . build/azure-pipelines/win32/exec.ps1 - $ErrorActionPreference = "Stop" - exec { pnpm install --frozen-lockfile } - env: - npm_config_arch: $(VSCODE_ARCH) - ELECTRON_SKIP_BINARY_DOWNLOAD: 1 - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - GITHUB_TOKEN: "$(github-token-code-oss)" - FOUNDRY_LOCAL_SKIP_INSTALL: "1" - retryCountOnTaskFailure: 5 - displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - - - powershell: node build/azure-pipelines/common/checkNativeOptionalDeps.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Verify native optional dependency binaries - - - powershell: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Mixin distro node modules - - - powershell: | - . build/azure-pipelines/win32/exec.ps1 - $ErrorActionPreference = "Stop" - exec { node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt } - exec { mkdir -Force .build/node_modules_cache } - exec { 7z.exe a .build/node_modules_cache/cache.7z -mx3 `@.build/node_modules_list.txt } - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive diff --git a/build/azure-pipelines/win32/product-build-win32-test.yml b/build/azure-pipelines/win32/product-build-win32-test.yml index 9c636dd25044..f8b833494fa4 100644 --- a/build/azure-pipelines/win32/product-build-win32-test.yml +++ b/build/azure-pipelines/win32/product-build-win32-test.yml @@ -16,9 +16,10 @@ parameters: # Each product test job tests the builds of the compilation artifact published # by the compile job (see product-build-win32.yml, which must set -# VSCODE_RUN_TESTS) with the selected test IDs. Retrying a test job skips the -# test tasks that already passed in an earlier attempt (see -# ../common/test-checkpoints.md). +# VSCODE_RUN_TESTS) with the selected test IDs. Failed unit, Agent Host E2E and +# node.js integration tests are rerun, as in the pull request workflows. +# Retrying a test job skips the test tasks that already passed in an earlier +# attempt (see ../common/test-checkpoints.md). jobs: - job: Windows_${{ parameters.VSCODE_ARCH }}_Test_${{ parameters.VSCODE_JOB_NAME }} displayName: Windows (${{ upper(parameters.VSCODE_ARCH) }}) - ${{ parameters.VSCODE_JOB_DISPLAY_NAME }} @@ -70,3 +71,4 @@ jobs: VSCODE_ARCH: ${{ parameters.VSCODE_ARCH }} VSCODE_TEST_IDS: ${{ parameters.VSCODE_TEST_IDS }} VSCODE_LINUX_X64_COMPILATION_ARTIFACT: ${{ parameters.VSCODE_LINUX_X64_COMPILATION_ARTIFACT }} + VSCODE_RERUN_FAILED_TESTS: true diff --git a/build/azure-pipelines/win32/product-build-win32.yml b/build/azure-pipelines/win32/product-build-win32.yml index d50479645321..00083ddff3a9 100644 --- a/build/azure-pipelines/win32/product-build-win32.yml +++ b/build/azure-pipelines/win32/product-build-win32.yml @@ -31,7 +31,7 @@ parameters: # CLI job must be part of the same stage. The sign and test jobs run in # parallel, but the Publish stage only publishes the x64 product artifacts once # all Windows__Test_ jobs have succeeded (see artifactsByGatingJob -# in ../common/publish.ts). +# in ../common/publishGate.ts). jobs: - job: Windows_${{ parameters.VSCODE_ARCH }}_Compile displayName: Windows (${{ upper(parameters.VSCODE_ARCH) }}) - Compile diff --git a/build/azure-pipelines/win32/product-smoke-flaky-win32.yml b/build/azure-pipelines/win32/product-smoke-flaky-win32.yml index 9687c89ba08e..77af8761f374 100644 --- a/build/azure-pipelines/win32/product-smoke-flaky-win32.yml +++ b/build/azure-pipelines/win32/product-smoke-flaky-win32.yml @@ -11,7 +11,8 @@ parameters: type: object # Windows unit and integration iterations are too slow to run all of them # sequentially in one job within its timeout. Each test type is split across - # parallel jobs by odd and even iteration number instead. + # parallel jobs by odd and even iteration number instead. Linux splits its unit + # iterations the same way (see ../linux/product-smoke-flaky-linux.yml). - name: iterationShards type: object default: [odd, even] @@ -43,7 +44,15 @@ jobs: # ever runs, turning it into one argument per file under the sources # directory and blowing past the command-line length limit, which # truncates and corrupts the trailing -xr!.git switch. - exec { 7z.exe a -tzip "$(Build.ArtifactStagingDirectory)\repo.zip" "$(Build.SourcesDirectory)\*" "-xr!.git" } + # 7-Zip stores the junctions of pnpm's node_modules as copies of their targets, which + # breaks module resolution, so they are recorded, removed and created again in the + # test jobs (see ../common/workspaceLinks.ts). + exec { node build/azure-pipelines/common/workspaceLinks.ts save "$(Build.SourcesDirectory)" "$(Build.SourcesDirectory)\.build\workspace-links.json" } + try { + exec { 7z.exe a -tzip "$(Build.ArtifactStagingDirectory)\repo.zip" "$(Build.SourcesDirectory)\*" "-xr!.git" } + } finally { + exec { node build/azure-pipelines/common/workspaceLinks.ts restore "$(Build.SourcesDirectory)" "$(Build.SourcesDirectory)\.build\workspace-links.json" } + } displayName: Archive built workspace for reuse by test jobs archiveAppSteps: - powershell: | @@ -76,9 +85,9 @@ jobs: platform: windows arch: x64 testName: unit-${{ shard }} - # Fits 10 Electron and 10 node.js iterations at their 15 minute step - # timeout, plus job setup. - timeoutInMinutes: 330 + # Fits 10 Electron and 10 node.js iterations at their 20 and 15 minute + # step timeouts, plus job setup. + timeoutInMinutes: 370 artifactPrefix: smoke-flaky-windows-x64 artifacts: - name: repo @@ -91,6 +100,9 @@ jobs: 7z.exe x $(Pipeline.Workspace)\smoke-flaky-windows-x64-repo\repo.zip -o"$(Build.SourcesDirectory)" -y if ($LASTEXITCODE -ne 0) { throw "7z extract of repo.zip failed with exit code $LASTEXITCODE" } displayName: Extract built workspace + setupSteps: + - powershell: node build/azure-pipelines/common/workspaceLinks.ts restore "$(Build.SourcesDirectory)" "$(Build.SourcesDirectory)\.build\workspace-links.json" + displayName: Restore the folder links of the built workspace testSteps: # Template expressions have no arithmetic, so an iteration's parity is # read from its last digit. The odd shard keeps odd iterations and the @@ -102,7 +114,7 @@ jobs: VSCODE_SKIP_PRELAUNCH: '1' displayName: "🧪 Unit test iteration ${{ i }}/${{ length(parameters.iterations) }} (Electron)" continueOnError: true - timeoutInMinutes: 15 + timeoutInMinutes: 20 - ${{ each i in parameters.iterations }}: - ${{ if xor(eq(shard, 'even'), or(endsWith(format('{0}', i), '1'), endsWith(format('{0}', i), '3'), endsWith(format('{0}', i), '5'), endsWith(format('{0}', i), '7'), endsWith(format('{0}', i), '9'))) }}: - powershell: | @@ -144,6 +156,9 @@ jobs: 7z.exe x $(Pipeline.Workspace)\smoke-flaky-windows-x64-server\server.zip -o"$(Agent.BuildDirectory)" -y if ($LASTEXITCODE -ne 0) { throw "7z extract of server.zip failed with exit code $LASTEXITCODE" } displayName: Extract built workspace, app and server + setupSteps: + - powershell: node build/azure-pipelines/common/workspaceLinks.ts restore "$(Build.SourcesDirectory)" "$(Build.SourcesDirectory)\.build\workspace-links.json" + displayName: Restore the folder links of the built workspace testSteps: - ${{ each i in parameters.iterations }}: # Template expressions have no arithmetic, so an iteration's parity @@ -225,6 +240,9 @@ jobs: 7z.exe x $(Pipeline.Workspace)\smoke-flaky-windows-x64-app\app.zip -o"$(Agent.BuildDirectory)" -y if ($LASTEXITCODE -ne 0) { throw "7z extract of app.zip failed with exit code $LASTEXITCODE" } displayName: Extract built workspace and app + setupSteps: + - powershell: node build/azure-pipelines/common/workspaceLinks.ts restore "$(Build.SourcesDirectory)" "$(Build.SourcesDirectory)\.build\workspace-links.json" + displayName: Restore the folder links of the built workspace testSteps: - ${{ each i in parameters.iterations }}: - powershell: | diff --git a/build/azure-pipelines/win32/sdl-scan-win32.yml b/build/azure-pipelines/win32/sdl-scan-win32.yml index b0ee145bf402..3017a578b08b 100644 --- a/build/azure-pipelines/win32/sdl-scan-win32.yml +++ b/build/azure-pipelines/win32/sdl-scan-win32.yml @@ -83,23 +83,12 @@ steps: echo $includes > "~/.gyp/include.gypi" displayName: Create include.gypi - - pwsh: | - mkdir .build -ea 0 - $gypConfigHash = (Get-FileHash "~/.gyp/include.gypi" -Algorithm SHA256).Hash - node build/azure-pipelines/common/computeNodeModulesCacheKey.ts win32 ${{ parameters.VSCODE_ARCH }} $(node -p process.arch) apiscan $gypConfigHash "$env:NPM_REGISTRY" > .build/apiscan-packagelockhash - displayName: Prepare API Scan node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules-apiscan" | .build/apiscan-packagelockhash' - path: .build/apiscan_node_modules_cache - cacheHitVar: APISCAN_NODE_MODULES_RESTORED - displayName: Restore API Scan node_modules cache - retryCountOnTaskFailure: 2 - - - powershell: 7z.exe x .build/apiscan_node_modules_cache/cache.7z -aoa - condition: and(succeeded(), eq(variables.APISCAN_NODE_MODULES_RESTORED, 'true')) - displayName: Extract API Scan node_modules cache + # The store doesn't depend on include.gypi, which only changes how the native modules build, so the + # job shares the store of the other Windows jobs. + - template: ../common/restore-pnpm-store.yml@self + parameters: + keyArgs: win32 ${{ parameters.VSCODE_ARCH }} + os: windows - powershell: node build/setup-npm-registry.ts $env:NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) @@ -137,7 +126,6 @@ steps: FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" retryCountOnTaskFailure: 5 displayName: Install dependencies - condition: and(succeeded(), ne(variables.APISCAN_NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where they can write it to @@ -150,17 +138,11 @@ steps: displayName: Verify native optional dependency binaries - script: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.APISCAN_NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - powershell: | - . build/azure-pipelines/win32/exec.ps1 - $ErrorActionPreference = "Stop" - exec { node build/azure-pipelines/common/listNodeModules.ts .build/apiscan_node_modules_list.txt } - mkdir -Force .build/apiscan_node_modules_cache - exec { 7z.exe a .build/apiscan_node_modules_cache/cache.7z -mx3 `@.build/apiscan_node_modules_list.txt } - condition: and(succeeded(), ne(variables.APISCAN_NODE_MODULES_RESTORED, 'true')) - displayName: Create API Scan node_modules archive + - template: ../common/prune-pnpm-store.yml@self + parameters: + os: windows - script: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality diff --git a/build/azure-pipelines/win32/steps/product-build-win32-setup.yml b/build/azure-pipelines/win32/steps/product-build-win32-setup.yml index 55566ed478ff..1ba3d3f47170 100644 --- a/build/azure-pipelines/win32/steps/product-build-win32-setup.yml +++ b/build/azure-pipelines/win32/steps/product-build-win32-setup.yml @@ -47,22 +47,10 @@ steps: parameters: windows: true - - pwsh: | - mkdir .build -ea 0 - node build/azure-pipelines/common/computeNodeModulesCacheKey.ts win32 $(VSCODE_ARCH) $(node -p process.arch) > .build/packagelockhash - displayName: Prepare node_modules cache key - - - task: Cache@2 - inputs: - key: '"node_modules" | .build/packagelockhash' - path: .build/node_modules_cache - cacheHitVar: NODE_MODULES_RESTORED - displayName: Restore node_modules cache - retryCountOnTaskFailure: 2 - - - powershell: 7z.exe x .build/node_modules_cache/cache.7z -aoa - condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Extract node_modules cache + - template: ../../common/restore-pnpm-store.yml@self + parameters: + keyArgs: win32 $(VSCODE_ARCH) + os: windows - powershell: | . build/azure-pipelines/win32/exec.ps1 @@ -104,7 +92,6 @@ steps: FOUNDRY_LOCAL_NUGET_FEEDS: "https://pkgs.dev.azure.com/monacotools/Monaco/_packaging/vscode/nuget/v3/index.json" retryCountOnTaskFailure: 5 displayName: Install dependencies - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) # NuGetAuthenticate@1 exposes its access token to all later steps as the # VSS_NUGET_ACCESSTOKEN environment variable, from where tests can write it to @@ -119,17 +106,11 @@ steps: displayName: Verify native optional dependency binaries - powershell: node build/azure-pipelines/distro/mixin-npm.ts - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - - powershell: | - . build/azure-pipelines/win32/exec.ps1 - $ErrorActionPreference = "Stop" - exec { node build/azure-pipelines/common/listNodeModules.ts .build/node_modules_list.txt } - exec { mkdir -Force .build/node_modules_cache } - exec { 7z.exe a .build/node_modules_cache/cache.7z -mx3 `@.build/node_modules_list.txt } - condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - displayName: Create node_modules archive + - template: ../../common/prune-pnpm-store.yml@self + parameters: + os: windows - powershell: node build/azure-pipelines/distro/mixin-quality.ts displayName: Mixin distro quality diff --git a/build/azure-pipelines/win32/steps/product-build-win32-test.yml b/build/azure-pipelines/win32/steps/product-build-win32-test.yml index f0635c923464..2990262a89ec 100644 --- a/build/azure-pipelines/win32/steps/product-build-win32-test.yml +++ b/build/azure-pipelines/win32/steps/product-build-win32-test.yml @@ -9,6 +9,12 @@ parameters: - name: VSCODE_LINUX_X64_COMPILATION_ARTIFACT type: boolean default: false + # Reruns failed unit, Agent Host E2E and node.js integration tests, like the + # pull request workflows do (the extension host suites are not rerun). Only + # the product build test jobs set it. + - name: VSCODE_RERUN_FAILED_TESTS + type: boolean + default: false # Each test task records a checkpoint once it passes, and retries of the job # skip the test tasks that already passed in an earlier attempt of the same @@ -38,7 +44,7 @@ steps: parameters: testId: unit-electron testStep: - powershell: .\scripts\test.bat --build --tfs "Unit Tests" + powershell: .\scripts\test.bat --build --tfs "Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: VSCODE_SKIP_PRELAUNCH: '1' displayName: 🧪 Run unit tests (Electron) @@ -51,7 +57,7 @@ steps: testStep: powershell: | New-Item -ItemType Directory -Force -Path .build\crashes | Out-Null - pnpm run test-node --build + pnpm run test-node --build${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} env: NODE_OPTIONS: "--report-on-fatalerror --report-uncaught-exception --report-directory=.build/crashes" displayName: 🧪 Run unit tests (node.js) @@ -62,7 +68,7 @@ steps: parameters: testId: unit-browser-chromium testStep: - powershell: pnpm run test-browser-no-install --build --browser chromium --tfs "Browser Unit Tests" + powershell: pnpm run test-browser-no-install --build --browser chromium --tfs "Browser Unit Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} displayName: 🧪 Run unit tests (Browser, Chromium) timeoutInMinutes: 30 @@ -125,7 +131,7 @@ steps: $AppNameShort = $AppProductJson.nameShort $env:INTEGRATION_TEST_ELECTRON_PATH = "$AppRoot\$AppNameShort.exe" $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\test\vscode-server-win32-$(VSCODE_ARCH)" - exec { .\scripts\test-agent-host-e2e.bat --build --tfs "Integration Tests" } + exec { .\scripts\test-agent-host-e2e.bat --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} } env: VSCODE_SKIP_PRELAUNCH: '1' displayName: 🧪 Run Agent Host E2E tests (Electron) @@ -148,7 +154,7 @@ steps: $AppNameShort = $AppProductJson.nameShort $env:INTEGRATION_TEST_ELECTRON_PATH = "$AppRoot\$AppNameShort.exe" $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\test\vscode-server-win32-$(VSCODE_ARCH)" - exec { .\scripts\test-integration.bat --build --tfs "Integration Tests" } + exec { .\scripts\test-integration.bat --build --tfs "Integration Tests"${{ iif(eq(parameters.VSCODE_RERUN_FAILED_TESTS, true), ' --rerun-failed-files 2', '') }} } env: VSCODE_SKIP_PRELAUNCH: '1' displayName: 🧪 Run integration tests (Electron) diff --git a/build/checker/layersChecker.ts b/build/checker/layersChecker.ts index 268b9977c5a2..76ab3d8afe5a 100644 --- a/build/checker/layersChecker.ts +++ b/build/checker/layersChecker.ts @@ -3,8 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { API, SymbolFlags, type Checker, type Program, type Project, type Symbol } from '@typescript/native/unstable/async'; -import { isExportSpecifier, isIdentifier, isImportSpecifier, isPropertyAccessExpression, type Identifier, type Node, type SourceFile } from '@typescript/native/unstable/ast'; +import { API, SymbolFlags, type Checker, type Program, type Project, type Symbol } from '@typescript/native/async'; +import { isExportSpecifier, isIdentifier, isImportSpecifier, isPropertyAccessExpression, type Identifier, type Node, type SourceFile } from '@typescript/native/ast'; import { dirname, join, relative, resolve } from 'path'; import minimatch from 'minimatch'; @@ -378,9 +378,9 @@ export async function checkLayers(tsconfigPath: string, rules: readonly IRule[]) try { const { fileNames } = await api.parseConfigFile(tsconfigPath); - const snapshot = await api.updateSnapshot({ openProjects: [tsconfigPath] }); + const snapshot = await api.createSnapshot({ openProjects: [tsconfigPath] }); - const project = snapshot.getProject(tsconfigPath); + const project = snapshot.getConfiguredProject(tsconfigPath); if (!project) { throw new Error(`Unable to load a project from '${tsconfigPath}'.`); } diff --git a/build/checksums/electron.txt b/build/checksums/electron.txt index 9c04eead1e85..5e5cb2578fb9 100644 --- a/build/checksums/electron.txt +++ b/build/checksums/electron.txt @@ -1,75 +1,75 @@ -1a2e7f6fd4b7c2c975b4e0d59f48788841ff60be832d6257ccadeb50dfa0ebd3 *chromedriver-v43.8.6-darwin-arm64.zip -234031ffba8a943a60b21ff17cb9535a0ad76d0df47754162bc4ed02b26ba00e *chromedriver-v43.8.6-darwin-x64.zip -7f06d1ab63ad547b7daf2f1a98713f9e1ad272d5096a64e5b5935e67a1998391 *chromedriver-v43.8.6-linux-arm64.zip -06279f83086814e23cc2711401d59b6756196eff6667f500a903ff913b4c6230 *chromedriver-v43.8.6-linux-armv7l.zip -bd70933be73d3eeb8e7e3b51e92796e68c10c66788a214211270174c78f6368e *chromedriver-v43.8.6-linux-x64.zip -6f17e421b37ee555efe58652f8d009528deda0d8587ae4b328a6d312ffddcaa4 *chromedriver-v43.8.6-mas-arm64.zip -e819a8b9646e5658b5d389b9a9e262d3b512569da291ffe3ab18d5e94d61676f *chromedriver-v43.8.6-mas-x64.zip -5d7fe3a0e373e01727a933ec715cb41ceff8f0634e09b249781c086f3ef407d4 *chromedriver-v43.8.6-win32-arm64.zip -db4533fc995a58a5e1f45a6629f9cbeb2cc59a347af7f671960c2fea2837adeb *chromedriver-v43.8.6-win32-ia32.zip -3f5aaf265ee1b5ca73fe300a85d4be8c5e35e3a0b287a33fa8ff355e20419ea6 *chromedriver-v43.8.6-win32-x64.zip -9da187d7576923dba6132aff6be1a1b7830d48487ce63a2412f61d4ce64b1d49 *electron-api.json -08cd4ed65f1ec2623404e5aaf1b03fa3dc2a7c9ae7433c0b8c58b9aa0ae9fc9f *electron-v43.8.6-darwin-arm64-dsym-snapshot.zip -98a6dbd7e117b859d7d28abf4ce34a22c2db92a69573b936fe04c8b6ff0aca7a *electron-v43.8.6-darwin-arm64-dsym.tar.xz -29048cce33b8d61927665cffdc7e5edeebadcdcd642a898f85e051c383ceec1f *electron-v43.8.6-darwin-arm64-symbols.zip -dd3ef1cf749e11f4426a1b5fb203bff1dbbc8cd589f43c46423ee40a87371390 *electron-v43.8.6-darwin-arm64.zip -08cd4ed65f1ec2623404e5aaf1b03fa3dc2a7c9ae7433c0b8c58b9aa0ae9fc9f *electron-v43.8.6-darwin-x64-dsym-snapshot.zip -fa1b0df2c613f1c6c220ffc47386c660cc79f21f7926a0e0ec919fa8a7a5dd50 *electron-v43.8.6-darwin-x64-dsym.tar.xz -366b8e618d0328f49317d4b8a135d1c75c79f1b706f774953f0e8647fc63165c *electron-v43.8.6-darwin-x64-symbols.zip -c12e82216da91117623165c8f9f6c8175cb7f9940d01da2cbbd5c6696dcf0b45 *electron-v43.8.6-darwin-x64.zip -981f8244659e811385cde694adaae1c8964c4ec431b7ec7dbc0fb049c8a6402b *electron-v43.8.6-linux-arm64-debug.zip -05f6fd4fa2efc2b92d9b032f15a8fbdaf6e7578e5dfd63e2a897d348cc5eded9 *electron-v43.8.6-linux-arm64-symbols.zip -4db7899786a668f6c85a480e8c2b96b53bf83b373c2e02b2c4ae9e506e55e05a *electron-v43.8.6-linux-arm64.zip -28b06e6b9a867cc1476e3113224a8f542efecc59b3df7e4fae55a060186f6dad *electron-v43.8.6-linux-armv7l-debug.zip -42e3651b69ac436d7ecfc51fdb6b0bc529d1625c081dd4738136ecdc796d8ce8 *electron-v43.8.6-linux-armv7l-symbols.zip -bd43178771ed730ddd89341df3cd26baa5f58064ba5795b4f37e86d7ea7bfc10 *electron-v43.8.6-linux-armv7l.zip -5c63bbec8f1a287fd448d9ac49dcec89ce47e6193de341022f4b861a9c39a3f9 *electron-v43.8.6-linux-x64-debug.zip -5167e4a849165d319b6a8d06741b5c76d13d40a3e4ef70245fb14f34f118486e *electron-v43.8.6-linux-x64-symbols.zip -1c657678e0701c5d55b18a3fe18cd9e8a0a375c976292fbfb8406ab13a763402 *electron-v43.8.6-linux-x64.zip -08cd4ed65f1ec2623404e5aaf1b03fa3dc2a7c9ae7433c0b8c58b9aa0ae9fc9f *electron-v43.8.6-mas-arm64-dsym-snapshot.zip -1df28214d4f4c8bee4c8516ebb7384273e078e736cf4b3447bee34aba2822041 *electron-v43.8.6-mas-arm64-dsym.tar.xz -98ff03c44349a5abfa9d53f19c67b1370f42aed57d7da37a3a8c2e056d1a06b2 *electron-v43.8.6-mas-arm64-symbols.zip -a359237b4c7b0d37b557f18eb3abc46c1e46093848a76d1800aca8f67f83a914 *electron-v43.8.6-mas-arm64.zip -08cd4ed65f1ec2623404e5aaf1b03fa3dc2a7c9ae7433c0b8c58b9aa0ae9fc9f *electron-v43.8.6-mas-x64-dsym-snapshot.zip -511bdff79efe6a2132ed2a42e4fb415f44ba4e99070cf850dac2f5508d3e37d8 *electron-v43.8.6-mas-x64-dsym.tar.xz -88d5e86ee504d0e967008d025ea0cdbb6ab5094abf1e25fd5a88e741dacf67be *electron-v43.8.6-mas-x64-symbols.zip -4d9091c144c1969e2bf583de7587987721913efd138e036631f05cf9e1043a26 *electron-v43.8.6-mas-x64.zip -0847432b3c220b0cf85fe781c7eb24d6f61df1a28d16529dddd74fd268cb6a48 *electron-v43.8.6-win32-arm64-pdb.zip -955fdda2ad5fd3a91dd7fb68896b895ebe9ee6aff9b378478a74a67465603bd0 *electron-v43.8.6-win32-arm64-symbols.zip -1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.6-win32-arm64-toolchain-profile.zip -819305e106769acb05dddec761f5dfac25d013ad04f6d713ae4339ef2b127060 *electron-v43.8.6-win32-arm64.zip -6df4ec2a8b8e077a7d532468916b08913fb75c878c7fe09acd069781c84a9c63 *electron-v43.8.6-win32-ia32-pdb.zip -a23bd05f8a927299e0be4e258d05601a2c18ef54af53e2a2c25c3b2d6940b338 *electron-v43.8.6-win32-ia32-symbols.zip -1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.6-win32-ia32-toolchain-profile.zip -e3d630c0a16c7c701ef151f8d4136fb238652a162fd9761cae4bb2b26612f48a *electron-v43.8.6-win32-ia32.zip -824dbea03959ca495b61929f522d97a9252514ec10e8fb2b913f459a2b3611fd *electron-v43.8.6-win32-x64-pdb.zip -50f8b80f67e865f81064d5c962b72d2ed32f966f0d9c96eb0ea6604424fab4a4 *electron-v43.8.6-win32-x64-symbols.zip -1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.6-win32-x64-toolchain-profile.zip -e4b7f67b4205e13780088e07b29d5c7d2decc10f2331fd62927f8ea7750e9ba8 *electron-v43.8.6-win32-x64.zip -fd8aeabab4a2273d2cac658e6d8a7fa5934cc618370e4db23eb4d3fd247e488a *electron.d.ts -75310bb7393ceca1ca8a96f76176ea6ead31d2ab78a09580b56fd482afc20c2b *ffmpeg-v43.8.6-darwin-arm64.zip -fc72ff93232be1a9a19836c580cad85737095b38197df417df107c624205231b *ffmpeg-v43.8.6-darwin-x64.zip -4f12ed99ced48fe01d4cb238c5475dc80e047041daa8af121ba8b80fe788ae6f *ffmpeg-v43.8.6-linux-arm64.zip -d507b8f9b777405c950987f69624d8ae0c6da3dba6a2e5e7a7a8bc582f2a22ef *ffmpeg-v43.8.6-linux-armv7l.zip -282e2e0dedaea4b7277c7c7d9111f53045f9f53ba9e5681de29bd972c5049879 *ffmpeg-v43.8.6-linux-x64.zip -29f1ee935a4a4142000ac0384729c85a8a69bcce93b2121e17bf2a764ce8ae57 *ffmpeg-v43.8.6-mas-arm64.zip -9861ab7ed800c9504b51dc1432bf77753d6ce9bec88163e7b68cc3753338854c *ffmpeg-v43.8.6-mas-x64.zip -09bdb6f7a038a68c9dfadfbc2ccc31bcc97e340f35001606bb28006780c0cbbf *ffmpeg-v43.8.6-win32-arm64.zip -e5f90c5f89ebafd967d48834802666b8be56b4efce15a67bcd569bda5ee1be37 *ffmpeg-v43.8.6-win32-ia32.zip -0ffa49e6fcfa52b4b588ba019613a6c1d1ab59e697fc8a0a0fa514d9f2151e0e *ffmpeg-v43.8.6-win32-x64.zip -83581f58eecc1c40abd9e2f06315213ff0e42978553d4eb0132fcdf5870fd3a2 *hunspell_dictionaries.zip -3b92472e056d566350e9754d16c22bd9e6d82d3cdadeac57250b80f73c858ada *libcxx-objects-v43.8.6-linux-arm64.zip -1ea79fdd3e06b72a1cfbc8c9195bd0db3c6f948801a5013ac00b6b176ccd1d37 *libcxx-objects-v43.8.6-linux-armv7l.zip -65b46cf476beb5ebc8e450659701054f99d97bb7bdc2866b593a86d07e19d13e *libcxx-objects-v43.8.6-linux-x64.zip -0b0ecee02cd72efa686b4e977cdd16ac7c4de393ffae216a6072709b4bcf6975 *libcxx_headers.zip -44ead66e0b119cac843fc863d990a03da030f6a59192ec6fa6b77747cb2a3ed2 *libcxxabi_headers.zip -57a8eb785299234d1c7cd09b1ba84d6fb2ffd4066d691a702ee4f3fe5636cda5 *mksnapshot-v43.8.6-darwin-arm64.zip -76192ad696043e1ea8a14c935a6220678984a18b80e098ff8a5e1b9feac8cd3a *mksnapshot-v43.8.6-darwin-x64.zip -c72af391dab1c28189b2bddf12b2cd36b7dd9939fbdb51cac9a24048d01a55eb *mksnapshot-v43.8.6-linux-arm64-x64.zip -4ef78b4b96fea9f1579ec4c2e63e874e7df35ff196c5626777613b4bf9e937b2 *mksnapshot-v43.8.6-linux-armv7l-x64.zip -594806b685e20ac185e4d4b3ac18aa4b0500f33773b3a18460a14e597549481b *mksnapshot-v43.8.6-linux-x64.zip -bdc18316b2aad0491ac21b64585536486aa7ba9c457d209eaf355266062670e2 *mksnapshot-v43.8.6-mas-arm64.zip -82664fb80cd013680d5b55b79016b0618b1d6b37c17392ca38b4d02d1647fc75 *mksnapshot-v43.8.6-mas-x64.zip -1261a3f6e4f4bafe033a435ca389acad8df00d26d76c692a7251af7fdc71ccb6 *mksnapshot-v43.8.6-win32-arm64-x64.zip -48dca7cc889ce17a29eea55160f27bd83b0c1ef3f59b2ae5fb3b256185763488 *mksnapshot-v43.8.6-win32-ia32.zip -9a745d102c6ca77876dbae125e94e55748045f3b9f743b7bfaa73bb2fa8827fc *mksnapshot-v43.8.6-win32-x64.zip +eda574fc543584c6d50a547516b11c749ddcfb795baf75838ec1a8ad402b2bdf *chromedriver-v43.8.9-darwin-arm64.zip +99195c52febece728c2c5cf5b1f0b2c19daaa8cb66313b1c7a42e882877cf200 *chromedriver-v43.8.9-darwin-x64.zip +d95b1c7638f975816bcfbfa6b5c1e03404f27cfe57b55d1eb29123d4a5b27c8d *chromedriver-v43.8.9-linux-arm64.zip +c5cffbe51a1b80f1c34a4b690a7fec7539dc749bd19886bf397ffdf37e61f5c3 *chromedriver-v43.8.9-linux-armv7l.zip +b8896a16f324f0c373e6c6ae6a3abe17bba52ad3ca81b95824c5fd09c9f19478 *chromedriver-v43.8.9-linux-x64.zip +b8eff2f59bca0fb2d3d01924bef181d4ca959f1b87dd8aa4f882c4d4a91d9c41 *chromedriver-v43.8.9-mas-arm64.zip +ebd01886d7b479fa6687351f0b218cb690c2a905adfb6f0f5be92c754be50b2f *chromedriver-v43.8.9-mas-x64.zip +bdac70ebc2470f5c0744ea7634cee449ede3cc5bcb5a5a45caeb2b2226048a48 *chromedriver-v43.8.9-win32-arm64.zip +31b66c8fba366c7cd83300771b560c4d7af347cf9cce644150e9021c17412fb3 *chromedriver-v43.8.9-win32-ia32.zip +1d2f35c07b12a46cd3fcf6459d0a11d47de376bf07193967798edb077e6f8783 *chromedriver-v43.8.9-win32-x64.zip +7365b8591158ce39592dd6ec3947242cecc876ab8de38cbbf353ecfcf9d2a28e *electron-api.json +bf1d86b055ec66a7e22002c7730cadfa769a9eb0b49881ed3497be71df9b0bed *electron-v43.8.9-darwin-arm64-dsym-snapshot.zip +c8945328cd34d3a7b6d3bb3028e11879793499f11b03cf4c539c0a378fff64c4 *electron-v43.8.9-darwin-arm64-dsym.tar.xz +6526a9501032aac3a071ed148fd658afa8814bcd5433a09b151f9dfc6102e9bb *electron-v43.8.9-darwin-arm64-symbols.zip +4009ceb8ede9ca15da8039d1c626496ec4795dca5fa6f2fe64611f6501b881b6 *electron-v43.8.9-darwin-arm64.zip +bf1d86b055ec66a7e22002c7730cadfa769a9eb0b49881ed3497be71df9b0bed *electron-v43.8.9-darwin-x64-dsym-snapshot.zip +068c473063ee154fb4dea728ce0b9efa018038ad783c0747113e8ca0feb929b4 *electron-v43.8.9-darwin-x64-dsym.tar.xz +2ac877f1f467f734ab7cad348b778c3b05b1231c872ef8980dfb23eeb765d75d *electron-v43.8.9-darwin-x64-symbols.zip +fed0b90a6075ba44ba06b64768b4786823404c4868f099cd4644cc974969cbfd *electron-v43.8.9-darwin-x64.zip +ba059fc27e62bd42591f689a64c9b84f8bab471ef3bb35876eaff97659ec6a1b *electron-v43.8.9-linux-arm64-debug.zip +320b0b88977b980bb2c234646994151b11858d31a9d24b064d1dcb28af78257c *electron-v43.8.9-linux-arm64-symbols.zip +cb2f091bc51c738388033526d80291bdb49aa1d9dad8dd1cafcf6421f8f6051d *electron-v43.8.9-linux-arm64.zip +1c5231af4e28cdf990266b8cc3c6595fe361bce8c6505f0393662f7dd4152af1 *electron-v43.8.9-linux-armv7l-debug.zip +ecb41bd4a4d8ac3d451ea6cbe1daba11e22f8d9cd4963073389335ff6a6519a4 *electron-v43.8.9-linux-armv7l-symbols.zip +9ec8b7bb15fa6f148b1e08e874fae9f1de9a25ba610964d73779ff7ce4dd6945 *electron-v43.8.9-linux-armv7l.zip +ad2e98e4b57f09bc128ac988c9ff8253150376aa2ec129f814fb7b80c053c676 *electron-v43.8.9-linux-x64-debug.zip +8eed41a4a6ceda0e83df238c6f2e87c0d00e70dfa839b6ae2289537302bde1b3 *electron-v43.8.9-linux-x64-symbols.zip +c3ded54175b5e6dee523858a43ff765b679bbbd119d6fc830e827c62b8ddcbe8 *electron-v43.8.9-linux-x64.zip +bf1d86b055ec66a7e22002c7730cadfa769a9eb0b49881ed3497be71df9b0bed *electron-v43.8.9-mas-arm64-dsym-snapshot.zip +5d52f38cd1e76a8887d1507c5d54317405464fac9d67e1171f0a0d54319dd448 *electron-v43.8.9-mas-arm64-dsym.tar.xz +8464747fc5a7f6e2813582dcad6a97730224d2de05b7646742d7341f69337e5a *electron-v43.8.9-mas-arm64-symbols.zip +14369d9a70f46df1918d29a5a3fa1fc24e02dbcf371d329ac8139f8d25f72195 *electron-v43.8.9-mas-arm64.zip +bf1d86b055ec66a7e22002c7730cadfa769a9eb0b49881ed3497be71df9b0bed *electron-v43.8.9-mas-x64-dsym-snapshot.zip +ea67cb1413f713ed15c12354c1e6cad153e2b1d36a3dce2c3d6dbf42a420462d *electron-v43.8.9-mas-x64-dsym.tar.xz +4f3220a610bc4b79d0c9df8d279192b89a350e3c8ed53b3e59d403c443d3b486 *electron-v43.8.9-mas-x64-symbols.zip +1f1090e3a9975324440289f2f19e8e537391437f9d9e2571161c4edf786a948a *electron-v43.8.9-mas-x64.zip +2b36ba0ac266cb8c0e00466fc3e6265c12a1012c56b45e19bf3fa4d6154f38e6 *electron-v43.8.9-win32-arm64-pdb.zip +627e01b13dd60e810ac00659f4b6d47eb84844ae2c18b4f065019199a4a53274 *electron-v43.8.9-win32-arm64-symbols.zip +1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.9-win32-arm64-toolchain-profile.zip +20524ceb204e836f792e0679ec4a6d4c686fdd0e93a430ac580d8acebae9f9c4 *electron-v43.8.9-win32-arm64.zip +716a8d7eb61fa7446ba0db0d0323f4faf2a7c9e206b50a75a1d5ee255edb22be *electron-v43.8.9-win32-ia32-pdb.zip +921ffc693f4d52d1cc0e048eb441562327a6bde640355ed4da2aa0205c1aa52b *electron-v43.8.9-win32-ia32-symbols.zip +1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.9-win32-ia32-toolchain-profile.zip +22588030344a1d2cd7eee2ebc886b8be85f536b67e93ecdec05c343f19fd39c4 *electron-v43.8.9-win32-ia32.zip +88cbb60b00c0b62b13e55a6f598f647316322d2a82d71d02d22498a53e5c2151 *electron-v43.8.9-win32-x64-pdb.zip +8a9b2cdd7aa172a1cb7292f1fdc9f3316e3d7fe0097f49f6cdadb5e25861be53 *electron-v43.8.9-win32-x64-symbols.zip +1b5679d4b831a18cc3297300f86c66ac1caf2bd07630a8dcc01798418b0bb1a7 *electron-v43.8.9-win32-x64-toolchain-profile.zip +cbbf40da8afa3990ce5ff84fa7bef78c531fd46e8202f3d4527a21437a7eeb9c *electron-v43.8.9-win32-x64.zip +74fefcfed8b81258343126d50cc7705725a0b4facc9bafc3ec142f97d742f53a *electron.d.ts +794a5deee6ca25f674f32435658429ae216c91d7928f0240cbd200c399da0e4b *ffmpeg-v43.8.9-darwin-arm64.zip +099cae50846f5dc05faeeb7c527f1849493da3fbb082e236fe40762325484969 *ffmpeg-v43.8.9-darwin-x64.zip +ae70c9267c6a0207a0d246e6f7633f72e182fe2707f995c5c75270c101137b8e *ffmpeg-v43.8.9-linux-arm64.zip +6f700936f3677b211d80fa80c4b579f9dc10c3670eb6015eb6fc0a0d83ea66da *ffmpeg-v43.8.9-linux-armv7l.zip +060568826db5610ff194ea6ab6418f180871cafa516af170bcd33d3b17629b83 *ffmpeg-v43.8.9-linux-x64.zip +4d97e1523ce6006dd3904a51a1e9a98f50a0600a656aa42dbb62dc01fe10948d *ffmpeg-v43.8.9-mas-arm64.zip +f39bcbd51f9f56ca72598561e60dee40f363adfadb4967c79e56097a33a29ea8 *ffmpeg-v43.8.9-mas-x64.zip +04e7600bd88d7761d7fd88e277cf81367995b00cc5abd81c0097256da375a082 *ffmpeg-v43.8.9-win32-arm64.zip +0e9f6b616ebd0077de8523ea5c844261ef1a86456ec9f55fd28e0a68c19db541 *ffmpeg-v43.8.9-win32-ia32.zip +d2db0a88f7c66c855aaa330d3769ca9c20148a0eaa03855b6cb0ee12db1e2cfa *ffmpeg-v43.8.9-win32-x64.zip +60c87d9242bdb7e1a5672a44cb22c86b66ec8593d8e9b33c279bd96fb256df7b *hunspell_dictionaries.zip +d47a87b609eb3760392faf235d0ba5efc3bad28e7d96daf51cfb72768fd2b60b *libcxx-objects-v43.8.9-linux-arm64.zip +c3874c1201ac8eb09bd4d7437fbb634e38934eb20ca35bea71ed71cb7544c0ba *libcxx-objects-v43.8.9-linux-armv7l.zip +a0dcc4c1b45596ea12924a78b8244e3b8c9c240cf958bb9ec1ba1b55cce940b3 *libcxx-objects-v43.8.9-linux-x64.zip +e5103c86dafb12ef2e098f7e2dcb5ea18aea1ddcc5ead6c84eb2daa5d21fb46f *libcxx_headers.zip +0cd1ca2c3de86f979a1379fc3e9f66f11165a433ef88ecd32cd3ae865ef39c12 *libcxxabi_headers.zip +89ff19b8d5584c7a9419522c94f529858f1049ab889c6ff18dcb1db46fd4319c *mksnapshot-v43.8.9-darwin-arm64.zip +f567980bd7b870cbe4c190056a753b206160fa09b821a23d40a95c7441b4965b *mksnapshot-v43.8.9-darwin-x64.zip +951077d03cb7e34eb03234d23fca095fdd2cd2839220f8e4c1d5878f420a4402 *mksnapshot-v43.8.9-linux-arm64-x64.zip +03e4cf7b376b7990d31e7968028aef02b52a7394cfde60b98586e857f381ab9f *mksnapshot-v43.8.9-linux-armv7l-x64.zip +eb308d845bdf124ca2a8bf9c0cfcba4c8d547802d2b6e09dcd9da22487706461 *mksnapshot-v43.8.9-linux-x64.zip +4728d23af1f84ef835478bfaa1a3966bb3bdf1ba3d495586b1ab9a7cd66b1717 *mksnapshot-v43.8.9-mas-arm64.zip +86ae6beb00047e4f82c9d646285d68e1f79a6fcec8edc88d125e1a6266318bfc *mksnapshot-v43.8.9-mas-x64.zip +47921c034163f5f64f1802df03158b3fc97feafdc9c94fdf164efbf9a0a1168b *mksnapshot-v43.8.9-win32-arm64-x64.zip +cd790b3962b366587213b89e5d8c05c1067a4ad732c7e77b5ed359dbc7009556 *mksnapshot-v43.8.9-win32-ia32.zip +117fbd311f81ad381fa7e348bf73825b50d3b18bff83b92971313c9916103ab0 *mksnapshot-v43.8.9-win32-x64.zip diff --git a/build/darwin/create-universal-app.ts b/build/darwin/create-universal-app.ts index 9a312a273edf..011b1fad07bb 100644 --- a/build/darwin/create-universal-app.ts +++ b/build/darwin/create-universal-app.ts @@ -15,6 +15,61 @@ const nodeModulesBases = [ path.join('Contents', 'Resources', 'app', 'node_modules.asar.unpacked') ]; +/** + * ASAR-internal paths allowed to exist in only one architecture's archive. + * The merger's globs do not match dotfiles implicitly, so SDK plugin metadata + * and their hidden directory need explicit patterns. + */ +export const singleArchFiles = `{${[ + '**/@github/copilot-darwin-*', + '**/@github/copilot-darwin-*/**', + '**/@github/copilot-sdk-darwin-*', + '**/@github/copilot-sdk-darwin-*/**', + '**/@github/copilot-sdk-darwin-*/plugins/*/.*', + '**/@github/copilot-sdk-darwin-*/plugins/*/.plugin/**', + '**/@github/copilot/prebuilds/darwin-*', + '**/@github/copilot/prebuilds/darwin-*/**', + '**/@github/copilot/tgrep/bin/darwin-*', + '**/@github/copilot/tgrep/bin/darwin-*/**', + '**/@github/copilot/sdk/tgrep/bin/darwin-*', + '**/@github/copilot/sdk/tgrep/bin/darwin-*/**', + '**/@github/copilot/sdk/prebuilds/darwin-*', + '**/@github/copilot/sdk/prebuilds/darwin-*/**', + '**/@github/copilot/sdk/ripgrep/bin/darwin-*', + '**/@github/copilot/sdk/ripgrep/bin/darwin-*/**', + '**/@vscode/ripgrep-universal/bin/darwin-*', + '**/@vscode/ripgrep-universal/bin/darwin-*/**', + '**/@vscode/os-proxy-resolver-darwin-*', + '**/@vscode/os-proxy-resolver-darwin-*/**', + '**/foundry-local-sdk/prebuilds', + '**/foundry-local-sdk/prebuilds/darwin-arm64', + '**/foundry-local-sdk/prebuilds/darwin-arm64/**', +].join(',')}}`; + +const x64ArchFiles = `{${[ + '*/kerberos.node', + '**/extensions/microsoft-authentication/dist/libmsalruntime.dylib', + '**/extensions/microsoft-authentication/dist/msal-node-runtime.node', + '**/node_modules/@github/copilot-darwin-*/**', + '**/node_modules/@github/copilot-sdk-darwin-*/**', + '**/node_modules/@github/copilot/prebuilds/darwin-*/*', + '**/node_modules/@github/copilot/tgrep/bin/darwin-*/*', + '**/node_modules/@github/copilot/sdk/tgrep/bin/darwin-*/*', + '**/node_modules.asar.unpacked/@github/copilot-darwin-*/**', + '**/node_modules.asar.unpacked/@github/copilot-sdk-darwin-*/**', + '**/node_modules.asar.unpacked/@github/copilot/prebuilds/darwin-*/*', + '**/node_modules.asar.unpacked/@github/copilot/tgrep/bin/darwin-*/*', + '**/node_modules.asar.unpacked/@github/copilot/sdk/tgrep/bin/darwin-*/*', + '**/extensions/copilot/node_modules/@github/copilot/sdk/prebuilds/darwin-*/*', + '**/extensions/copilot/node_modules/@github/copilot/sdk/ripgrep/bin/darwin-*/*', + '**/extensions/copilot/node_modules/@github/copilot/sdk/tgrep/bin/darwin-*/*', + '**/extensions/copilot/node_modules/@github/copilot/tgrep/bin/darwin-*/*', + '**/node_modules/@vscode/ripgrep-universal/bin/darwin-*/*', + '**/node_modules.asar.unpacked/@vscode/ripgrep-universal/bin/darwin-*/*', + '**/node_modules/@vscode/os-proxy-resolver-darwin-*/**', + '**/node_modules.asar.unpacked/@vscode/os-proxy-resolver-darwin-*/**', +].join(',')}}`; + /** * Ensures a directory exists in both the x64 and arm64 app bundles by copying * it from whichever build has it to the one that does not. This is needed for @@ -136,8 +191,8 @@ async function main(buildDir?: string) { // them as arch-unique. Paths here are ASAR-internal (top level, no `node_modules` // prefix). Over-covering is harmless: the allowlist is only consulted for files // that are actually unique to one arch. - singleArchFiles: '{**/@github/copilot-darwin-*,**/@github/copilot-darwin-*/**,**/@github/copilot-sdk-darwin-*,**/@github/copilot-sdk-darwin-*/**,**/@github/copilot/prebuilds/darwin-*,**/@github/copilot/prebuilds/darwin-*/**,**/@github/copilot/tgrep/bin/darwin-*,**/@github/copilot/tgrep/bin/darwin-*/**,**/@github/copilot/sdk/tgrep/bin/darwin-*,**/@github/copilot/sdk/tgrep/bin/darwin-*/**,**/@github/copilot/sdk/prebuilds/darwin-*,**/@github/copilot/sdk/prebuilds/darwin-*/**,**/@github/copilot/sdk/ripgrep/bin/darwin-*,**/@github/copilot/sdk/ripgrep/bin/darwin-*/**,**/@vscode/ripgrep-universal/bin/darwin-*,**/@vscode/ripgrep-universal/bin/darwin-*/**,**/@vscode/os-proxy-resolver-darwin-*,**/@vscode/os-proxy-resolver-darwin-*/**,**/foundry-local-sdk/prebuilds,**/foundry-local-sdk/prebuilds/darwin-arm64,**/foundry-local-sdk/prebuilds/darwin-arm64/**}', - x64ArchFiles: '{*/kerberos.node,**/extensions/microsoft-authentication/dist/libmsalruntime.dylib,**/extensions/microsoft-authentication/dist/msal-node-runtime.node,**/node_modules/@github/copilot-darwin-*/**,**/node_modules/@github/copilot-sdk-darwin-*/**,**/node_modules/@github/copilot/prebuilds/darwin-*/*,**/node_modules/@github/copilot/tgrep/bin/darwin-*/*,**/node_modules/@github/copilot/sdk/tgrep/bin/darwin-*/*,**/node_modules.asar.unpacked/@github/copilot-darwin-*/**,**/node_modules.asar.unpacked/@github/copilot-sdk-darwin-*/**,**/node_modules.asar.unpacked/@github/copilot/prebuilds/darwin-*/*,**/node_modules.asar.unpacked/@github/copilot/tgrep/bin/darwin-*/*,**/node_modules.asar.unpacked/@github/copilot/sdk/tgrep/bin/darwin-*/*,**/extensions/copilot/node_modules/@github/copilot/sdk/prebuilds/darwin-*/*,**/extensions/copilot/node_modules/@github/copilot/sdk/ripgrep/bin/darwin-*/*,**/extensions/copilot/node_modules/@github/copilot/sdk/tgrep/bin/darwin-*/*,**/extensions/copilot/node_modules/@github/copilot/tgrep/bin/darwin-*/*,**/node_modules/@vscode/ripgrep-universal/bin/darwin-*/*,**/node_modules.asar.unpacked/@vscode/ripgrep-universal/bin/darwin-*/*,**/node_modules/@vscode/os-proxy-resolver-darwin-*/**,**/node_modules.asar.unpacked/@vscode/os-proxy-resolver-darwin-*/**}', + singleArchFiles, + x64ArchFiles, filesToSkipComparison: (file: string) => { for (const expected of filesToSkip) { if (minimatch(file, expected)) { diff --git a/build/eslint.ts b/build/eslint.ts index 91f7970ce2ba..cd6714cdbc27 100644 --- a/build/eslint.ts +++ b/build/eslint.ts @@ -110,6 +110,7 @@ if (import.meta.main) { eslint(process.argv.slice(2)).catch((err) => { console.error(); console.error(err); - process.exit(1); + // Not process.exit(), which would truncate output that is still being written to a pipe. + process.exitCode = 1; }); } diff --git a/build/gulpfile.reh.ts b/build/gulpfile.reh.ts index c41a6045fb91..72a3b4c17b5d 100644 --- a/build/gulpfile.reh.ts +++ b/build/gulpfile.reh.ts @@ -12,7 +12,7 @@ import * as task from './lib/gulp/task.ts'; import { inlineMeta } from './lib/inlineMeta.ts'; import { computeNLSMetadataHash } from './lib/nlsMetadata.ts'; import product from '../product.json' with { type: 'json' }; -import { getProductionDependencies } from './lib/dependencies.ts'; +import { getProductionDependencies, toPackagedLayout } from './lib/dependencies.ts'; import { readISODate, writeISODate } from './lib/date.ts'; import vfs from 'vinyl-fs'; import packageJson from '../package.json' with { type: 'json' }; @@ -347,8 +347,9 @@ function packageTask(type: string, platform: string, arch: string, sourceFolderN const jsFilter = util.filter(data => !data.isDirectory() && /\.js$/.test(data.path)); const productionDependencies = getProductionDependencies(REMOTE_FOLDER); - const dependenciesSrc = productionDependencies.map(d => path.relative(REPO_ROOT, d)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`, `!${d}/.bin/**`]).flat(); + const dependenciesSrc = productionDependencies.map(d => path.relative(REPO_ROOT, d.source)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`, `!${d}/.bin/**`]).flat(); const cleanedDeps = gulp.src(dependenciesSrc, { base: 'remote', dot: true }) + .pipe(toPackagedLayout(productionDependencies)) // filter out unnecessary files, no source maps in server build .pipe(filter(['**', '!**/package-lock.json', '!**/*.{js,css}.map'])) .pipe(util.cleanNodeModules(path.join(import.meta.dirname, '.moduleignore'))) diff --git a/build/gulpfile.scan.ts b/build/gulpfile.scan.ts index 972b335a4d28..06aca72f2d30 100644 --- a/build/gulpfile.scan.ts +++ b/build/gulpfile.scan.ts @@ -72,15 +72,20 @@ BUILD_TARGETS.forEach(buildTarget => { task.task(setupSymbolsTask); }); -function getProductionDependencySources() { +/** + * Returns the files of the production dependencies, at their packaged paths. + */ +function getProductionDependencyFiles(): NodeJS.ReadWriteStream { const productionDependencies = deps.getProductionDependencies(root); - return productionDependencies.map(d => path.relative(root, d)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat(); + const sources = productionDependencies.map(d => path.relative(root, d.source)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat(); + return gulp.src(sources, { base: '.', dot: true }) + .pipe(deps.toPackagedLayout(productionDependencies)); } function nodeModules(destinationExe: string, destinationPdb: string, platform: string): task.CallbackTask { const exe = () => { - return gulp.src(getProductionDependencySources(), { base: '.', dot: true }) + return getProductionDependencyFiles() .pipe(filter([ '**/*.node', // Exclude these paths. @@ -92,7 +97,7 @@ function nodeModules(destinationExe: string, destinationPdb: string, platform: s if (platform === 'win32') { const pdb = () => { - return gulp.src(getProductionDependencySources(), { base: '.', dot: true }) + return getProductionDependencyFiles() .pipe(filter(['**/*.pdb'])) .pipe(gulp.dest(destinationPdb)); }; @@ -102,7 +107,7 @@ function nodeModules(destinationExe: string, destinationPdb: string, platform: s if (platform === 'linux') { const pdb = () => { - return gulp.src(getProductionDependencySources(), { base: '.', dot: true }) + return getProductionDependencyFiles() .pipe(filter(['**/*.sym'])) .pipe(gulp.dest(destinationPdb)); }; diff --git a/build/gulpfile.vscode.ts b/build/gulpfile.vscode.ts index 94f8395e63ea..ace10e4fd003 100644 --- a/build/gulpfile.vscode.ts +++ b/build/gulpfile.vscode.ts @@ -20,7 +20,7 @@ import product from '../product.json' with { type: 'json' }; import * as crypto from 'crypto'; import * as cp from 'child_process'; import * as i18n from './lib/i18n.ts'; -import { getProductionDependencies } from './lib/dependencies.ts'; +import { getProductionDependencies, toPackagedLayout } from './lib/dependencies.ts'; import { config } from './lib/electron.ts'; import { createAsar } from './lib/asar.ts'; import minimist from 'minimist'; @@ -239,7 +239,7 @@ function packageTask(platform: string, arch: string, sourceFolderName: string, d const jsFilter = util.filter(data => !data.isDirectory() && /\.js$/.test(data.path)); const root = path.resolve(path.join(import.meta.dirname, '..')); const productionDependencies = getProductionDependencies(root); - const dependenciesSrc = productionDependencies.map(d => path.relative(root, d)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat().concat('!**/*.mk'); + const dependenciesSrc = productionDependencies.map(d => path.relative(root, d.source)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat().concat('!**/*.mk'); const depFilterPattern = ['**', `!**/${config.version}/**`, '!**/bin/darwin-arm64-87/**', '!**/package-lock.json', '!**/yarn.lock']; if (stripSourceMapsInPackagingTasks) { @@ -247,6 +247,7 @@ function packageTask(platform: string, arch: string, sourceFolderName: string, d } const cleanedDeps = gulp.src(dependenciesSrc, { base: '.', dot: true }) + .pipe(toPackagedLayout(productionDependencies)) .pipe(filter(depFilterPattern)) .pipe(util.cleanNodeModules(path.join(import.meta.dirname, '.moduleignore'))) .pipe(util.cleanNodeModules(path.join(import.meta.dirname, `.moduleignore.${process.platform}`))); @@ -254,12 +255,13 @@ function packageTask(platform: string, arch: string, sourceFolderName: string, d const copilotRuntimePrebuilds = gulp.src(getCopilotRuntimePrebuildFiles(platform, arch), { base: '.', dot: true, allowEmpty: true }); ensureOSProxyResolverPlatformPackage(platform, arch); const osProxyResolverPlatformPackage = gulp.src(getOSProxyResolverPlatformFiles(platform, arch), { base: '.', dot: true, allowEmpty: true }); + // `cleanedDeps` has already dropped dot files; keep those of the platform packages, such as SDK plugin manifests. const deps = es.merge(cleanedDeps, copilotRuntimePrebuilds, osProxyResolverPlatformPackage) - .pipe(filter(getCopilotExcludeFilter(platform, arch))) - .pipe(filter(getCopilotTgrepExcludeFilter(platform, arch))) - .pipe(filter(getRipgrepExcludeFilter(platform, arch))) - .pipe(filter(getFoundryLocalExcludeFilter())) - .pipe(filter(getOSProxyResolverExcludeFilter(platform, arch))) + .pipe(filter(getCopilotExcludeFilter(platform, arch), { dot: true })) + .pipe(filter(getCopilotTgrepExcludeFilter(platform, arch), { dot: true })) + .pipe(filter(getRipgrepExcludeFilter(platform, arch), { dot: true })) + .pipe(filter(getFoundryLocalExcludeFilter(), { dot: true })) + .pipe(filter(getOSProxyResolverExcludeFilter(platform, arch), { dot: true })) .pipe(jsFilter) .pipe(util.rewriteSourceMappingURL(sourceMappingURLBase)) .pipe(jsFilter.restore) diff --git a/build/gulpfile.vscode.web.ts b/build/gulpfile.vscode.web.ts index 3915d35bf90f..97d56e008310 100644 --- a/build/gulpfile.vscode.web.ts +++ b/build/gulpfile.vscode.web.ts @@ -11,7 +11,7 @@ import { getVersion } from './lib/getVersion.ts'; import * as task from './lib/gulp/task.ts'; import { writeISODate } from './lib/date.ts'; import product from '../product.json' with { type: 'json' }; -import { getFlatProductionDependencies } from './lib/dependencies.ts'; +import { getFlatProductionDependencies, toPackagedLayout } from './lib/dependencies.ts'; import vfs from 'vinyl-fs'; import packageJson from '../package.json' with { type: 'json' }; import { compileApiProposalNamesTask, copyCodiconsTask } from './lib/compilation.ts'; @@ -50,9 +50,10 @@ function packageTask(sourceFolderName: string, destinationFolderName: string) { // `remote/web` is a member of the `remote` workspace, which installs most of its dependencies in // `remote/node_modules`. The web build packages them flat, in its own `node_modules`. - const deps = es.merge(...getFlatProductionDependencies(WEB_FOLDER).map(({ folder, base }) => { - const d = path.relative(REPO_ROOT, folder); - return gulp.src([`${d}/**`, `!${d}/node_modules/**`, `!${d}/**/{test,tests}/**`, `!${d}/.bin/**`], { base: path.relative(REPO_ROOT, base), dot: true }); + const deps = es.merge(...getFlatProductionDependencies(WEB_FOLDER).map(dependency => { + const d = path.relative(REPO_ROOT, dependency.source); + return gulp.src([`${d}/**`, `!${d}/node_modules/**`, `!${d}/**/{test,tests}/**`, `!${d}/.bin/**`], { base: path.relative(REPO_ROOT, dependency.base), dot: true }) + .pipe(toPackagedLayout([dependency])); })) .pipe(filter(['**', '!**/package-lock.json'])) .pipe(util.cleanNodeModules(path.join(import.meta.dirname, '.webignore'))); diff --git a/build/hygiene.ts b/build/hygiene.ts index 573514ae5c63..15042935a195 100644 --- a/build/hygiene.ts +++ b/build/hygiene.ts @@ -13,7 +13,7 @@ import VinylFile from 'vinyl'; import vfs from 'vinyl-fs'; import { all, copyrightFilter, eslintFilter, indentationFilter, stylelintFilter, tsFormattingFilter, unicodeFilter } from './filters.ts'; import eslint from './gulp-eslint.ts'; -import * as formatter from './lib/formatter.ts'; +import { Formatter } from './lib/formatter.ts'; import gulpstylelint from './stylelint.ts'; const copyrightHeaderLines = [ @@ -168,20 +168,22 @@ export function hygiene(some: NodeJS.ReadWriteStream | string[] | undefined, run this.emit('data', file); }); - const formatting = es.map(function (file: any, cb) { - try { - const rawInput = file.contents!.toString('utf8'); - if (!formatter.verifyFormatting(file.path, rawInput)) { - console.error( - `File not formatted. Run the 'Format Document' command to fix it:`, - file.relative - ); - errorCount++; - } - cb(undefined, file); - } catch (err) { - cb(err); - } + // Started for the first file that the formatting check covers. + let formatter: Promise | undefined; + const formatting = es.map(function (file: VinylFile, cb) { + formatter ??= Formatter.start(); + formatter + .then(f => f.verifyFormatting(file.path, file.contents!.toString('utf8'))) + .then(formatted => { + if (!formatted) { + console.error( + `File not formatted. Run the 'Format Document' command to fix it:`, + file.relative + ); + errorCount++; + } + cb(undefined, file); + }, err => cb(err)); }); let input: NodeJS.ReadWriteStream; @@ -263,7 +265,8 @@ export function hygiene(some: NodeJS.ReadWriteStream | string[] | undefined, run } this.emit('data', data); }, - function () { + async function () { + await formatter?.then(f => f.dispose(), () => undefined); process.stdout.write('\n'); console.log(`Hygiene checked ${checkedFiles.size} file${checkedFiles.size === 1 ? '' : 's'} in ${Date.now() - started}ms.`); if (requestedPaths && checkedFiles.size === 0) { diff --git a/build/lib/asar.ts b/build/lib/asar.ts index 873b3f946fd9..f4f7851b9102 100644 --- a/build/lib/asar.ts +++ b/build/lib/asar.ts @@ -14,7 +14,7 @@ export function createAsar(folderPath: string, unpackGlobs: string[], skipGlobs: const shouldUnpackFile = (file: VinylFile): boolean => { for (let i = 0; i < unpackGlobs.length; i++) { - if (minimatch(file.relative, unpackGlobs[i])) { + if (minimatch(file.relative, unpackGlobs[i], { dot: true })) { return true; } } diff --git a/build/lib/changedFiles.ts b/build/lib/changedFiles.ts index e55a2a4df178..3933d16be85c 100644 --- a/build/lib/changedFiles.ts +++ b/build/lib/changedFiles.ts @@ -26,8 +26,8 @@ export type CheckScope = | { readonly kind: 'files'; readonly files: readonly string[]; readonly reason: string }; /** - * Files that configure or implement ESLint for every file, so changing one lints the full repository. - * Entries ending in `/` match a folder; other entries match a file. + * Files that configure or implement ESLint, or oxlint with the same rules, for every file, so changing one lints the + * full repository. Entries ending in `/` match a folder; other entries match a file. */ const eslintFullCheckPaths = [ // Read by eslint.config.js. @@ -47,6 +47,10 @@ const eslintFullCheckPaths = [ 'build/filters.ts', 'build/eslint.ts', 'build/lib/changedFiles.ts', + // Convert eslint.config.js for oxlint, and run it. + 'oxlint.config.ts', + 'build/lib/oxlintConfig.ts', + 'build/oxlint.ts', ]; /** ESLint uses the closest configuration file to each linted file. */ diff --git a/build/lib/copilot.ts b/build/lib/copilot.ts index 6387d4f94b35..bec5758c0e98 100644 --- a/build/lib/copilot.ts +++ b/build/lib/copilot.ts @@ -7,13 +7,13 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { ensureNpmPackage, materializeNpmPackageVersion, type EnsureNpmPackageOptions } from './npmPackage.ts'; -import { parsePackageKey, readPnpmLockfile, type PnpmLockfile } from './pnpmLock.ts'; +import { getLockfileFolder, parsePackageKey, readPnpmLockfile, type PnpmLockfile } from './pnpmLock.ts'; /** * Options for {@link prepareBuiltInCopilotRipgrepShim}. Extends the npm packing * options with an override for the extension lockfile used to verify natives - * fetched for the pinned version (defaults to the repo's copy; overridable in - * tests). + * fetched for the pinned version (defaults to the repo's lockfile that records + * `extensions/copilot`; overridable in tests). */ export interface PrepareBuiltInCopilotOptions extends EnsureNpmPackageOptions { extensionLockfilePath?: string; @@ -402,7 +402,7 @@ function resolveVersionMatchedCopilotPlatformPackage(copilotPackagePlatformArch: * so the build must stop rather than ship an unverified binary. */ function resolvePinnedPlatformPackageIntegrity(packageName: string, extVersion: string, options: PrepareBuiltInCopilotOptions): string { - const lockfilePath = options.extensionLockfilePath ?? path.join(import.meta.dirname, '..', '..', 'extensions', 'copilot', 'pnpm-lock.yaml'); + const lockfilePath = options.extensionLockfilePath ?? getCopilotLockfilePath(); let lockfile: PnpmLockfile; try { @@ -425,6 +425,18 @@ function resolvePinnedPlatformPackageIntegrity(packageName: string, extVersion: return integrity; } +/** + * Returns the `pnpm-lock.yaml` that records the dependencies of `extensions/copilot`: the lockfile + * of its pnpm install root. + */ +function getCopilotLockfilePath(): string { + const lockfileFolder = getLockfileFolder('extensions/copilot'); + if (lockfileFolder === undefined) { + throw new Error('[prepareBuiltInCopilotRipgrepShim] extensions/copilot is not a pnpm project.'); + } + return path.join(import.meta.dirname, '..', '..', lockfileFolder, 'pnpm-lock.yaml'); +} + function readCopilotPackageVersion(copilotBase: string): string { const version = readOptionalPackageVersion(copilotBase); if (!version) { diff --git a/build/lib/dependencies.ts b/build/lib/dependencies.ts index 0aadccd02112..c3b04662a784 100644 --- a/build/lib/dependencies.ts +++ b/build/lib/dependencies.ts @@ -3,9 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import es from 'event-stream'; import fs from 'fs'; import path from 'path'; -import { getImporterId, getLockfileFolder, getSnapshotKey, readPnpmLockfile } from './pnpmLock.ts'; +import VinylFile from 'vinyl'; +import { getHoistedLocations } from './pnpmHoist.ts'; +import { getImporterId, getLockfileFolder, getSnapshotKey, readPnpmLockfile, type PnpmLockfile } from './pnpmLock.ts'; const root = fs.realpathSync(path.dirname(path.dirname(import.meta.dirname))); /** @@ -19,35 +22,104 @@ function getInstallRoot(folder: string): string { } /** - * Returns the folders of the installed production dependencies of the project in `folder`. + * A production dependency: the folder where the product ships it, and the folder that holds its + * files. + */ +export interface IProductionDependency { + /** + * The folder of the package in the layout of pnpm's hoisted linker (`nodeLinker: hoisted`), + * where the product ships it. + */ + readonly folder: string; + /** + * The folder that holds the files of the package: `folder` when pnpm installed it with the + * hoisted linker, its folder in pnpm's virtual store (`node_modules/.pnpm`) with the isolated + * linker. + */ + readonly source: string; +} + +interface IInstallRootLayout { + readonly lockfile: PnpmLockfile; + /** Whether pnpm installed the root with the hoisted linker, so that each package is in its `folder`. */ + readonly isHoisted: boolean; + /** The folders of each package in the hoisted layout, by snapshot key. */ + readonly locations: ReadonlyMap>; + /** The folders where pnpm's hoisted linker installed each package, by snapshot key (only when `isHoisted`). */ + readonly installedLocations: ReadonlyMap>; +} + +const installRootLayouts = new Map(); + +/** + * Returns the hoisted layout of the packages of an install root, computed from its lockfile, so that + * it is the same with either linker (see `build/lib/pnpmHoist.ts`). + */ +function getInstallRootLayout(installRoot: string): IInstallRootLayout { + let layout = installRootLayouts.get(installRoot); + if (!layout) { + const modulesFile = path.join(installRoot, 'node_modules', '.modules.yaml'); + if (!fs.existsSync(modulesFile)) { + throw new Error(`${modulesFile} is missing. Run pnpm install in ${installRoot}.`); + } + const modules = JSON.parse(fs.readFileSync(modulesFile, 'utf8')) as { nodeLinker?: string; hoistedLocations?: Record; skipped?: string[] }; + const toFolders = (locations: Iterable<[string, string[]]>) => new Map([...locations].map(([key, folders]) => [key, new Set(folders.map(f => path.join(installRoot, f)))])); + const lockfile = readPnpmLockfile(path.join(installRoot, 'pnpm-lock.yaml')); + const isHoisted = modules.nodeLinker === 'hoisted'; + if (isHoisted && !modules.hoistedLocations) { + throw new Error(`${modulesFile} has no hoistedLocations. Run pnpm install in ${installRoot}.`); + } + layout = { + lockfile, + isHoisted, + locations: toFolders(getHoistedLocations(lockfile, new Set(modules.skipped ?? []))), + installedLocations: toFolders(Object.entries(modules.hoistedLocations ?? {})), + }; + installRootLayouts.set(installRoot, layout); + } + return layout; +} + +/** + * Returns the folder of the dependency `name` of the package or project whose files are in + * `dependentSource`, in pnpm's isolated layout: a link next to the package in the virtual store + * (`.pnpm//node_modules/`), or in the project's `node_modules`. + */ +function getIsolatedSource(dependentSource: string, name: string, isProject: boolean): string | undefined { + let nodeModules = path.join(dependentSource, 'node_modules'); + if (!isProject) { + nodeModules = dependentSource; + while (path.basename(nodeModules) !== 'node_modules') { + nodeModules = path.dirname(nodeModules); + } + } + const folder = path.join(nodeModules, name); + return fs.existsSync(path.join(folder, 'package.json')) ? fs.realpathSync(folder) : undefined; +} + +/** + * Returns the installed production dependencies of the project in `folder`. * * `pnpm list --json` prints the dependencies of a package only at its first occurrence, which can * be outside the production tree, and `--parseable` also lists the packages that workspace members * hoisted into the same `node_modules`. So this walks the production dependencies in the lockfile - * from the project, and finds each one the way Node.js resolves it: in the nearest `node_modules` - * folder that has the locked version, according to the locations that pnpm's hoisted linker - * recorded in `node_modules/.modules.yaml`. Optional packages for other platforms are not - * installed and are skipped. + * from the project, and places each one the way Node.js resolves it in the hoisted layout: in the + * nearest `node_modules` folder that has the locked version. Optional packages for other platforms + * are not installed and are skipped. + * + * With the hoisted linker, this checks that pnpm installed each package where the computed layout + * puts it, so that the product ships the same layout after a switch to the isolated linker. */ -function getPnpmProductionDependencies(folder: string): string[] { +function getPnpmProductionDependencies(folder: string): IProductionDependency[] { const installRoot = getInstallRoot(folder); - const lockfile = readPnpmLockfile(path.join(installRoot, 'pnpm-lock.yaml')); - const importer = lockfile.importers[getImporterId(installRoot, folder)]; + const layout = getInstallRootLayout(installRoot); + const importer = layout.lockfile.importers[getImporterId(installRoot, folder)]; if (!importer) { throw new Error(`${folder} is not a project of ${path.join(installRoot, 'pnpm-lock.yaml')}.`); } - const modulesFile = path.join(installRoot, 'node_modules', '.modules.yaml'); - if (!fs.existsSync(modulesFile)) { - throw new Error(`${modulesFile} is missing. Run pnpm install in ${installRoot}.`); - } - const modules = JSON.parse(fs.readFileSync(modulesFile, 'utf8')) as { nodeLinker?: string; hoistedLocations?: Record }; - if (modules.nodeLinker !== 'hoisted' || !modules.hoistedLocations) { - throw new Error(`${installRoot} must be installed with nodeLinker: hoisted.`); - } - const locations = new Map(Object.entries(modules.hoistedLocations).map(([key, folders]) => [key, new Set(folders.map(f => path.join(installRoot, f)))])); const resolve = (fromFolder: string, name: string, key: string): string | undefined => { - const candidates = locations.get(key); + const candidates = layout.locations.get(key); if (!candidates) { return undefined; } @@ -62,31 +134,51 @@ function getPnpmProductionDependencies(folder: string): string[] { } }; - const result = new Set(); - const queue: { from: string; name: string; key: string }[] = []; - const enqueue = (from: string, dependencies: Record | undefined) => { + const result = new Map(); + const checkedKeys = new Set(); + const queue: { from: string; fromSource: string; fromProject: boolean; name: string; key: string }[] = []; + const enqueue = (from: string, fromSource: string, fromProject: boolean, dependencies: Record | undefined) => { for (const [name, version] of Object.entries(dependencies ?? {})) { const key = getSnapshotKey(name, version); if (key) { - queue.push({ from, name, key }); + queue.push({ from, fromSource, fromProject, name, key }); } } }; for (const kind of ['dependencies', 'optionalDependencies'] as const) { - enqueue(folder, Object.fromEntries(Object.entries(importer[kind] ?? {}).map(([name, { version }]) => [name, version]))); + enqueue(folder, folder, true, Object.fromEntries(Object.entries(importer[kind] ?? {}).map(([name, { version }]) => [name, version]))); } while (queue.length > 0) { - const { from, name, key } = queue.shift()!; + const { from, fromSource, fromProject, name, key } = queue.shift()!; + // Check every production package before resolving it, so that a package that the computed + // layout misses or misplaces fails the build instead of being left out of the product. + if (layout.isHoisted && !checkedKeys.has(key)) { + checkedKeys.add(key); + const computed = [...layout.locations.get(key) ?? []].sort(); + const installed = [...layout.installedLocations.get(key) ?? []].sort(); + if (JSON.stringify(computed) !== JSON.stringify(installed)) { + throw new Error(`pnpm installed ${key} at ${installed.map(f => path.relative(root, f)).join(', ') || 'no location'}, but the layout computed from ${path.relative(root, path.join(installRoot, 'pnpm-lock.yaml'))} has it at ${computed.map(f => path.relative(root, f)).join(', ') || 'no location'}. Update build/lib/pnpmHoist.ts to match pnpm's hoisting.`); + } + } const location = resolve(from, name, key); - if (!location || result.has(location) || !fs.existsSync(location)) { + if (!location || result.has(location)) { continue; } - result.add(location); - const snapshot = lockfile.snapshots?.[key]; - enqueue(location, snapshot?.dependencies); - enqueue(location, snapshot?.optionalDependencies); + let source: string | undefined; + if (layout.isHoisted) { + source = fs.existsSync(location) ? location : undefined; + } else { + source = getIsolatedSource(fromSource, name, fromProject); + } + if (!source) { + continue; + } + result.set(location, { folder: location, source }); + const snapshot = layout.lockfile.snapshots?.[key]; + enqueue(location, source, false, snapshot?.dependencies); + enqueue(location, source, false, snapshot?.optionalDependencies); } - return [...result].sort(); + return [...result.values()].sort((a, b) => a.folder < b.folder ? -1 : a.folder > b.folder ? 1 : 0); } /** @@ -107,48 +199,107 @@ export function getMixedInDistroDependencies(folder: string, distroFolder: strin .filter(dependency => fs.existsSync(dependency)); } -export function getProductionDependencies(folderPath: string): string[] { +/** + * Returns the production dependencies of the project in `folderPath`: each package with the folder + * where the product ships it and the folder that holds its files (see {@link IProductionDependency}). + * Read the files from `source` and move them to `folder` with {@link toPackagedLayout}. + */ +export function getProductionDependencies(folderPath: string): IProductionDependency[] { const realFolderPath = fs.realpathSync(folderPath); const result = getPnpmProductionDependencies(realFolderPath); // Account for distro npm dependencies. The lockfile doesn't know them, so they are taken from // where the mixin put them (npm listed them there as extraneous packages). const relativeFolderPath = path.relative(root, realFolderPath); const distroFolderPath = `${root}/.build/distro/npm/${relativeFolderPath}`; - result.push(...getMixedInDistroDependencies(realFolderPath, distroFolderPath)); + for (const folder of getMixedInDistroDependencies(realFolderPath, distroFolderPath)) { + if (!result.some(dependency => dependency.folder === folder)) { + result.push({ folder, source: folder }); + } + } + return result; +} - return [...new Set(result)]; +/** + * Returns a stream that moves the files of production dependencies, read from their `source` + * folders, to their `folder` (see {@link getProductionDependencies}). Files outside of these + * folders pass unchanged. With pnpm's hoisted linker the folders are the same, and the stream + * changes nothing. + * + * With the isolated linker, it drops the commands that pnpm links for the dependencies of each + * package in the store (`node_modules/.bin`), which point into the store. The product doesn't ship + * the commands of nested packages with either linker: the packaging filters drop dot folders. + */ +export function toPackagedLayout(dependencies: readonly IProductionDependency[]): NodeJS.ReadWriteStream { + // The hoisted layout can have a package in several folders, which share its folder in the store. + const moved = new Map(); + for (const dependency of dependencies) { + if (dependency.source !== dependency.folder) { + moved.set(dependency.source, [...moved.get(dependency.source) ?? [], dependency]); + } + } + if (moved.size === 0) { + return es.through(); + } + return es.through(function (file: VinylFile) { + for (let current = file.path; path.dirname(current) !== current; current = path.dirname(current)) { + const destinations = moved.get(current); + if (destinations) { + const relative = path.relative(current, file.path); + const [first, second] = relative.split(path.sep); + if (first === 'node_modules' && second === '.bin') { + return; + } + // Create every copy before emitting any: the streams downstream can change a file + // synchronously when it is emitted (for example its source map URL). + const copies = destinations.map((dependency, index) => { + const copy = index === 0 ? file : new VinylFile({ + cwd: file.cwd, + base: file.base, + path: file.path, + stat: file.stat ? Object.assign(Object.create(Object.getPrototypeOf(file.stat)), file.stat) : undefined, + contents: Buffer.isBuffer(file.contents) ? Buffer.from(file.contents) : file.contents, + }); + copy.path = path.join(dependency.folder, relative); + return copy; + }); + for (const copy of copies) { + this.emit('data', copy); + } + return; + } + } + this.emit('data', file); + }); } /** * A production dependency to package at `node_modules/`, where `` is the name that it is - * installed under: its path relative to `base`. + * installed under: its `folder` relative to `base`. */ -export interface IFlatProductionDependency { - /** The folder of the installed package, `/node_modules/`. */ - readonly folder: string; - /** The folder whose `node_modules` holds the installed package. */ +export interface IFlatProductionDependency extends IProductionDependency { + /** The folder whose `node_modules` holds the package in the hoisted layout. */ readonly base: string; } /** - * Maps the folders of installed packages to a flat layout: each one at `node_modules/`, - * wherever the install put it (in the project's `node_modules`, a parent's, or nested in another - * package). Throws when two packages have the same name, which a flat layout can't hold. + * Maps production dependencies to a flat layout: each one at `node_modules/`, wherever the + * install put it (in the project's `node_modules`, a parent's, or nested in another package). Throws + * when two packages have the same name, which a flat layout can't hold. */ -export function toFlatProductionDependencies(folders: readonly string[]): IFlatProductionDependency[] { +export function toFlatProductionDependencies(dependencies: readonly IProductionDependency[]): IFlatProductionDependency[] { const nodeModules = `${path.sep}node_modules${path.sep}`; const result = new Map(); - for (const folder of folders) { - const index = folder.lastIndexOf(nodeModules); + for (const dependency of dependencies) { + const index = dependency.folder.lastIndexOf(nodeModules); if (index === -1) { - throw new Error(`${folder} is not in a node_modules folder.`); + throw new Error(`${dependency.folder} is not in a node_modules folder.`); } - const name = folder.slice(index + nodeModules.length).split(path.sep).join('/'); + const name = dependency.folder.slice(index + nodeModules.length).split(path.sep).join('/'); const existing = result.get(name); if (existing) { - throw new Error(`Production dependencies ${existing.folder} and ${folder} are both named ${name}, so they can't both be packaged at node_modules/${name}.`); + throw new Error(`Production dependencies ${existing.folder} and ${dependency.folder} are both named ${name}, so they can't both be packaged at node_modules/${name}.`); } - result.set(name, { folder, base: folder.slice(0, index) }); + result.set(name, { ...dependency, base: dependency.folder.slice(0, index) }); } return [...result.values()]; } @@ -163,5 +314,5 @@ export function getFlatProductionDependencies(folderPath: string): IFlatProducti } if (import.meta.main) { - console.log(JSON.stringify(getProductionDependencies(root), null, ' ')); + console.log(JSON.stringify(getProductionDependencies(root).map(dependency => dependency.folder), null, ' ')); } diff --git a/build/lib/esbuild.ts b/build/lib/esbuild.ts index ab0a70212388..80729a7a4773 100644 --- a/build/lib/esbuild.ts +++ b/build/lib/esbuild.ts @@ -8,7 +8,7 @@ import * as path from 'path'; const root = path.resolve(import.meta.dirname, '../..'); -export type BuildTarget = 'desktop' | 'server' | 'server-web' | 'web'; +export type BuildTarget = 'desktop' | 'server' | 'server-web' | 'web' | 'mobile'; export function getBootstrapEntryPointsForTarget(target: BuildTarget): string[] { switch (target) { @@ -18,6 +18,7 @@ export function getBootstrapEntryPointsForTarget(target: BuildTarget): string[] case 'server-web': return ['server-main', 'server-cli', 'bootstrap-fork']; case 'web': + case 'mobile': return []; default: throw new Error(`Unknown target: ${target}`); diff --git a/build/lib/extensions.ts b/build/lib/extensions.ts index d440640f34d3..8b51b579d283 100644 --- a/build/lib/extensions.ts +++ b/build/lib/extensions.ts @@ -17,7 +17,7 @@ import * as util2 from './util.ts'; import fancyLog from 'fancy-log'; import ansiColors from 'ansi-colors'; import * as jsoncParser from 'jsonc-parser'; -import { getProductionDependencies } from './dependencies.ts'; +import { getProductionDependencies, toPackagedLayout } from './dependencies.ts'; import { type IExtensionDefinition, getExtensionStream } from './builtInExtensions.ts'; import { fetchUrls, fetchGithub } from './fetch.ts'; import { createTsgoStream, spawnTsgo } from './tsgo.ts'; @@ -461,11 +461,7 @@ function doPackageLocalExtensionsStream(forWeb: boolean, native: boolean): Strea result = localExtensionsStream; } else { // also include shared production node modules - const dependenciesStreams = getSharedExtensionDependencyFolders().map(({ folder, destination }) => - gulp.src([`${folder}/**`, `!${folder}/**/{test,tests}/**`], { base: folder }) - .pipe(filter(file => destination !== sharedTypeScriptDestination || isPackagedTypeScriptFile(file.relative.split(path.sep).join('/')))) - .pipe(rename(p => p.dirname = path.posix.join(destination, p.dirname!.split(path.sep).join('/')))) - ); + const dependenciesStreams = getSharedExtensionDependencyFolders().map(({ folder, destination }) => getSharedExtensionDependencyStream(folder, destination)); if (dependenciesStreams.length) { result = es.merge( @@ -522,27 +518,44 @@ export function isPackagedTypeScriptFile(relativePath: string): boolean { * Returns the production dependencies of `extensions/package.json` (shared by the built-in * extensions) with their destination in the build: `extensions/node_modules/...`. They are a * member of the pnpm workspace, so a dependency can be hoisted to the root `node_modules`; such a - * folder keeps its path relative to that `node_modules`. + * folder keeps its path relative to that `node_modules`. `folder` holds the files of the package + * (in pnpm's virtual store with the isolated linker). */ function getSharedExtensionDependencyFolders(): { folder: string; destination: string }[] { const extensionsNodeModules = path.join(root, 'extensions', 'node_modules'); const rootNodeModules = path.join(root, 'node_modules'); const result = new Map(); - for (const folder of getProductionDependencies('extensions/')) { + for (const { folder, source } of getProductionDependencies('extensions/')) { const relative = folder.startsWith(extensionsNodeModules + path.sep) ? path.relative(extensionsNodeModules, folder) : path.relative(rootNodeModules, folder); if (relative.startsWith('..')) { throw new Error(`Unexpected location of a shared extension dependency: ${folder}`); } const destination = path.posix.join('extensions', 'node_modules', relative.split(path.sep).join('/')); const existing = result.get(destination); - if (existing && existing !== folder) { - throw new Error(`Shared extension dependencies ${existing} and ${folder} would both be packaged at ${destination}`); + if (existing && existing !== source) { + throw new Error(`Shared extension dependencies ${existing} and ${source} would both be packaged at ${destination}`); } - result.set(destination, folder); + result.set(destination, source); } return [...result].map(([destination, folder]) => ({ folder: path.relative(root, folder).split(path.sep).join('/'), destination })); } +/** + * Returns the files of a shared extension dependency, read from `folder` and placed at + * `destination`. The files are moved rather than renamed, so that the filters that follow match + * their packaged path, and not the folder of the package in pnpm's virtual store (`.pnpm`). + */ +export function getSharedExtensionDependencyStream(folder: string, destination: string): Stream { + return gulp.src([`${folder}/**`, `!${folder}/**/{test,tests}/**`], { base: folder }) + .pipe(filter(file => destination !== sharedTypeScriptDestination || isPackagedTypeScriptFile(file.relative.split(path.sep).join('/')))) + .pipe(es.mapSync((file: File) => { + const relative = file.relative; + file.base = file.cwd; + file.path = path.join(file.cwd, destination, relative); + return file; + })); +} + /** * Package the built-in copilot extension specifically. * This is used by non-CI local builds where copilot is not downloaded as a VSIX @@ -560,11 +573,12 @@ export function packageCopilotExtensionStream(): Stream { ); const productionDependencies = getProductionDependencies('extensions/copilot'); - const dependenciesSrc = productionDependencies.map(d => path.relative(root, d)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat(); + const dependenciesSrc = productionDependencies.map(d => path.relative(root, d.source)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]).flat(); return es.merge( localExtensionsStream, gulp.src(dependenciesSrc, { base: '.' }) + .pipe(toPackagedLayout(productionDependencies)) .pipe(util2.cleanNodeModules(path.join(root, 'build', '.moduleignore'))) .pipe(util2.cleanNodeModules(path.join(root, 'build', `.moduleignore.${process.platform}`))) ).pipe(util2.setExecutableBit(['**/*.sh'])); diff --git a/build/lib/formatter.ts b/build/lib/formatter.ts index 112ab1a3f00a..a43c5aba3e0e 100644 --- a/build/lib/formatter.ts +++ b/build/lib/formatter.ts @@ -2,41 +2,24 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import cp from 'child_process'; import fs from 'fs'; +import module from 'module'; import path from 'path'; -import ts from 'typescript'; +import type { Readable, Writable } from 'stream'; +import url from 'url'; +const root = path.join(import.meta.dirname, '..', '..'); -class LanguageServiceHost implements ts.LanguageServiceHost { - files: ts.MapLike = {}; - addFile(fileName: string, text: string) { - this.files[fileName] = ts.ScriptSnapshot.fromString(text); - } - - fileExists(path: string): boolean { - return !!this.files[path]; - } - - readFile(path: string): string | undefined { - return this.files[path]?.getText(0, this.files[path]!.getLength()); - } - - // for ts.LanguageServiceHost - - getCompilationSettings = () => ts.getDefaultCompilerOptions(); - getScriptFileNames = () => Object.keys(this.files); - getScriptVersion = (_fileName: string) => '0'; - getScriptSnapshot = (fileName: string) => this.files[fileName]; - getCurrentDirectory = () => process.cwd(); - getDefaultLibFileName = (options: ts.CompilerOptions) => ts.getDefaultLibFilePath(options); -} - -const defaults: ts.FormatCodeSettings = { +/** + * The formatting settings: these defaults, overridden by the root tsfmt.json. + */ +const defaults = { baseIndentSize: 0, indentSize: 4, tabSize: 4, - indentStyle: ts.IndentStyle.Smart, - newLineCharacter: '\r\n', + indentStyle: 'smart', + newLineCharacter: '\n', convertTabsToSpaces: false, insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, @@ -56,78 +39,312 @@ const defaults: ts.FormatCodeSettings = { insertSpaceBeforeTypeAnnotation: false, }; -const getOverrides = (() => { - const cache = new Map(); - return (fileName: string) => { - let dir = path.dirname(fileName); - while (dir !== path.dirname(dir)) { - const tsfmtPath = path.join(dir, 'tsfmt.json'); - if (cache.has(tsfmtPath)) { - return cache.get(tsfmtPath)!; +/** More concurrent requests don't format faster. */ +const maxConcurrentRequests = 8; + +interface Position { + readonly line: number; + readonly character: number; +} + +interface TextEdit { + readonly range: { readonly start: Position; readonly end: Position }; + readonly newText: string; +} + +interface ResponseMessage { + readonly id: number; + readonly result?: unknown; + readonly error?: { readonly message: string }; +} + +interface RequestMessage { + readonly id: number; + readonly method: string; + readonly params?: { readonly items?: readonly { readonly section?: string }[] }; +} + +type GetExePath = (modules: { fs: typeof fs; module: typeof module; path: typeof path; url: typeof url }) => string; + +async function getTsgoPath(): Promise { + // @typescript/native's own bin uses getExePath to find the native executable, which is in a platform package. + const getExePathUrl = new URL('lib/getExePath.js', import.meta.resolve('@typescript/native/package.json')); + const getExePath: GetExePath = (await import(getExePathUrl.href)).default; + return getExePath({ fs, module, path, url }); +} + +function getLanguageId(fileName: string): string { + switch (path.extname(fileName)) { + case '.tsx': return 'typescriptreact'; + case '.js': case '.cjs': case '.mjs': return 'javascript'; + case '.jsx': return 'javascriptreact'; + default: return 'typescript'; + } +} + +/** + * Applies LSP text edits, which are ordered by position and don't overlap, to a text. + */ +function applyEdits(text: string, edits: readonly TextEdit[]): string { + const lineStarts = [0]; + for (const match of text.matchAll(/\r\n|\r|\n/g)) { + lineStarts.push(match.index + match[0].length); + } + const offsetAt = ({ line, character }: Position) => { + if (line >= lineStarts.length) { + return text.length; + } + const lineEnd = line + 1 < lineStarts.length ? lineStarts[line + 1] : text.length; + return Math.min(lineStarts[line] + character, lineEnd); + }; + const sorted = edits + .map((edit, index) => ({ start: offsetAt(edit.range.start), end: offsetAt(edit.range.end), newText: edit.newText, index })) + .sort((a, b) => a.start - b.start || a.index - b.index); + let result = ''; + let offset = 0; + for (const edit of sorted) { + result += text.slice(offset, edit.start) + edit.newText; + offset = edit.end; + } + return result + text.slice(offset); +} + +/** + * Formats TypeScript with the formatter of the native TypeScript language server (tsgo), like the Format Document + * command does in this workspace. + */ +export class Formatter { + + /** + * Starts the language server. Dispose the formatter to stop it. + */ + static async start(): Promise { + const settings = { ...defaults, ...JSON.parse(fs.readFileSync(path.join(root, 'tsfmt.json'), 'utf8')) }; + const child = cp.spawn(await getTsgoPath(), ['--lsp', '--stdio'], { cwd: root, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }); + const formatter = new Formatter(child, settings); + try { + await formatter.initialize(); + } catch (error) { + child.kill(); + throw error; + } + return formatter; + } + + /** The server caches the files that it reads from disk, so it would miss later changes to them. */ + private readonly filesReadFromDisk = new Set(); + private readonly pendingRequests = new Map void; reject: (error: Error) => void }>(); + private readonly waitingForRequestSlot: (() => void)[] = []; + private readonly exited: Promise; + private exitError: Error | undefined; + private disposing = false; + private stderr = ''; + private lastRequestId = 0; + private lastUntitledId = 0; + private activeRequests = 0; + private received: Buffer = Buffer.alloc(0); + private onDidSendConfiguration: (() => void) | undefined; + + private readonly child: cp.ChildProcessByStdio; + private readonly settings: Record; + + private constructor(child: cp.ChildProcessByStdio, settings: Record) { + this.child = child; + this.settings = settings; + child.stdout.on('data', (data: Buffer) => this.onData(data)); + // Writing to a server that exited fails, which the exit handler below reports. + child.stdin.on('error', () => { }); + // The server logs to stderr, including when it shuts down normally, so the log is only shown when it fails. + child.stderr.on('data', (data: Buffer) => this.stderr = (this.stderr + data.toString('utf8')).slice(-10_000)); + this.exited = new Promise(resolve => { + const onExit = (error: Error) => { + this.exitError ??= error; + for (const request of this.pendingRequests.values()) { + request.reject(this.exitError); + } + this.pendingRequests.clear(); + resolve(); + }; + child.on('error', error => onExit(new Error(`Could not start the TypeScript language server: ${error.message}`))); + child.on('exit', code => onExit(new Error(`The TypeScript language server exited with code ${code}.${!this.disposing && this.stderr ? `\n${this.stderr}` : ''}`))); + }); + } + + private async initialize(): Promise { + const configured = new Promise(resolve => this.onDidSendConfiguration = resolve); + await this.request('initialize', { processId: process.pid, rootUri: null, workspaceFolders: null, capabilities: { workspace: { configuration: true } } }); + this.notify('initialized', {}); + // The server applies the formatting settings when it gets them, which it asks for after initialization. + let timeout: NodeJS.Timeout | undefined; + await Promise.race([ + configured, + this.exited.then(() => { throw this.exitError; }), + new Promise((_, reject) => timeout = setTimeout(() => reject(new Error('The TypeScript language server did not request its configuration.')), 60_000)), + ]).finally(() => clearTimeout(timeout)); + } + + /** + * Formats `text`, the contents of the file `fileName`. + */ + async format(fileName: string, text: string): Promise { + return this.withRequestSlot(async () => { + const options = { tabSize: this.settings.tabSize, insertSpaces: this.settings.convertTabsToSpaces }; + let edits: unknown; + if (!this.filesReadFromDisk.has(fileName) && await fs.promises.readFile(fileName, 'utf8').catch(() => undefined) === text) { + // The server reads files that aren't open from disk, which is much faster than opening them. + this.filesReadFromDisk.add(fileName); + edits = await this.request('textDocument/formatting', { textDocument: { uri: url.pathToFileURL(fileName).href }, options }); + } else { + const uri = `untitled:/formatter/${++this.lastUntitledId}${path.extname(fileName)}`; + this.notify('textDocument/didOpen', { textDocument: { uri, languageId: getLanguageId(fileName), version: 1, text } }); + try { + edits = await this.request('textDocument/formatting', { textDocument: { uri }, options }); + } finally { + this.notify('textDocument/didClose', { textDocument: { uri } }); + } } - if (fs.existsSync(tsfmtPath)) { - const value = JSON.parse(fs.readFileSync(tsfmtPath, 'utf8')); - cache.set(tsfmtPath, value); - return value; + return applyEdits(text, Array.isArray(edits) ? edits : []); + }); + } + + /** + * Returns whether `text`, the contents of the file `fileName`, is formatted. + */ + async verifyFormatting(fileName: string, text: string): Promise { + const formatted = await this.format(fileName, text); + return text.replace(/\r\n/gm, '\n') === formatted.replace(/\r\n/gm, '\n'); + } + + async dispose(): Promise { + this.disposing = true; + // Stops a server that doesn't respond. When it exits, its pending requests, including shutdown, fail. + const timeout = setTimeout(() => this.child.kill('SIGKILL'), 5_000); + try { + if (!this.exitError) { + await this.request('shutdown').catch(() => undefined); + this.notify('exit'); } - dir = path.dirname(dir); + await this.exited; + } finally { + clearTimeout(timeout); } - // Fallback to the root tsfmt.json - const rootTsfmtPath = path.join(import.meta.dirname, '..', '..', 'tsfmt.json'); - if (!cache.has(rootTsfmtPath)) { - cache.set(rootTsfmtPath, JSON.parse(fs.readFileSync(rootTsfmtPath, 'utf8'))); + } + + private async withRequestSlot(fn: () => Promise): Promise { + while (this.activeRequests >= maxConcurrentRequests) { + await new Promise(resolve => this.waitingForRequestSlot.push(resolve)); } - return cache.get(rootTsfmtPath)!; - }; -})(); - -export function format(fileName: string, text: string) { - - const host = new LanguageServiceHost(); - host.addFile(fileName, text); - - const languageService = ts.createLanguageService(host); - const edits = languageService.getFormattingEditsForDocument(fileName, { ...defaults, ...getOverrides(fileName) }); - edits - .sort((a, b) => a.span.start - b.span.start) - .reverse() - .forEach(edit => { - const head = text.slice(0, edit.span.start); - const tail = text.slice(edit.span.start + edit.span.length); - text = `${head}${edit.newText}${tail}`; + this.activeRequests++; + try { + return await fn(); + } finally { + this.activeRequests--; + this.waitingForRequestSlot.shift()?.(); + } + } + + private request(method: string, params?: unknown): Promise { + if (this.exitError) { + return Promise.reject(this.exitError); + } + const id = ++this.lastRequestId; + return new Promise((resolve, reject) => { + this.pendingRequests.set(id, { resolve, reject }); + this.send({ id, method, params }); }); + } - return text; -} + private notify(method: string, params?: unknown): void { + if (!this.exitError) { + this.send({ method, params }); + } + } -export function verifyFormatting(fileName: string, text: string): boolean { - const formatted = format(fileName, text); - return text.replace(/\r\n/gm, '\n') === formatted.replace(/\r\n/gm, '\n'); + private send(message: object): void { + const content = JSON.stringify({ jsonrpc: '2.0', ...message }); + this.child.stdin.write(`Content-Length: ${Buffer.byteLength(content)}\r\n\r\n${content}`); + } + + private onData(data: Buffer): void { + this.received = this.received.length ? Buffer.concat([this.received, data]) : data; + for (; ;) { + const headerEnd = this.received.indexOf('\r\n\r\n'); + if (headerEnd === -1) { + return; + } + const contentLength = Number(/Content-Length: (?\d+)/i.exec(this.received.subarray(0, headerEnd).toString('latin1'))?.groups?.length); + const contentStart = headerEnd + 4; + if (this.received.length < contentStart + contentLength) { + return; + } + const message = JSON.parse(this.received.subarray(contentStart, contentStart + contentLength).toString('utf8')); + this.received = this.received.subarray(contentStart + contentLength); + if (typeof message.method === 'string' && message.id !== undefined) { + this.onRequest(message); + } else if (message.id !== undefined) { + this.onResponse(message); + } + } + } + + private onRequest(request: RequestMessage): void { + if (request.method === 'workspace/configuration') { + const editor = { tabSize: this.settings.tabSize, insertSpaces: this.settings.convertTabsToSpaces }; + this.send({ id: request.id, result: (request.params?.items ?? []).map(item => item.section === 'editor' ? editor : { format: this.settings }) }); + this.onDidSendConfiguration?.(); + } else { + this.send({ id: request.id, result: null }); + } + } + + private onResponse(response: ResponseMessage): void { + const request = this.pendingRequests.get(response.id); + if (!request) { + return; + } + this.pendingRequests.delete(response.id); + if (response.error) { + request.reject(new Error(response.error.message)); + } else { + request.resolve(response.result); + } + } } -if (import.meta.main) { - const args = process.argv.slice(2); +async function main(args: readonly string[]): Promise { const verify = args.includes('--verify'); const replace = args.includes('--replace'); - const files = args.filter(arg => !arg.startsWith('--')); - - let errorCount = 0; - for (const file of files) { - const absolutePath = path.resolve(file); - const text = fs.readFileSync(absolutePath, 'utf8'); - if (replace) { - const formatted = format(absolutePath, text); - if (text !== formatted) { - fs.writeFileSync(absolutePath, formatted, 'utf8'); - console.log(`Formatted ${file}`); + const files = args.filter(arg => !arg.startsWith('--')).map(file => path.resolve(file)); + + const formatter = await Formatter.start(); + try { + let errorCount = 0; + await Promise.all(files.map(async file => { + const relativePath = path.relative(process.cwd(), file); + const text = fs.readFileSync(file, 'utf8'); + if (replace) { + const formatted = await formatter.format(file, text); + if (text !== formatted) { + fs.writeFileSync(file, formatted, 'utf8'); + console.log(`Formatted ${relativePath}`); + } } + if (verify && !await formatter.verifyFormatting(file, fs.readFileSync(file, 'utf8'))) { + console.error(`File not formatted. Run the 'Format Document' command to fix it: ${relativePath}`); + errorCount++; + } + })); + if (errorCount > 0) { + process.exitCode = 1; } - if (verify && !verifyFormatting(absolutePath, replace ? fs.readFileSync(absolutePath, 'utf8') : text)) { - console.error(`File not formatted. Run the 'Format Document' command to fix it: ${file}`); - errorCount++; - } + } finally { + await formatter.dispose(); } - if (errorCount > 0) { +} + +if (import.meta.main) { + main(process.argv.slice(2)).catch(error => { + console.error(error); process.exit(1); - } + }); } diff --git a/build/lib/gulp/facade.ts b/build/lib/gulp/facade.ts index 82878435a38b..fe4c24d69ca1 100644 --- a/build/lib/gulp/facade.ts +++ b/build/lib/gulp/facade.ts @@ -12,6 +12,9 @@ /* eslint-disable local/code-no-direct-gulp-import */ import filter_ from 'gulp-filter'; +import minimatch from 'minimatch'; +import path from 'path'; +import type File from 'vinyl'; import rename_ from 'gulp-rename'; import replace_ from 'gulp-replace'; import plumber_ from 'gulp-plumber'; @@ -28,7 +31,34 @@ import vinylZip_ from '@vscode/gulp-vinyl-zip'; import sort_ from 'gulp-sort'; import g from 'gulp'; -export const filter = filter_; +/** + * gulp-filter, with glob patterns compiled once rather than for every file. Matches like gulp-filter does, which + * applies the patterns in order: a pattern adds a matching file and a negated pattern removes it. + */ +export function filter(pattern: string | string[] | filter_.FileFunction, options?: filter_.Options): filter_.Filter { + return filter_(typeof pattern === 'function' ? pattern : compileFilterPattern(pattern, options), options); +} + +function compileFilterPattern(pattern: string | readonly string[], options: minimatch.IOptions = {}): filter_.FileFunction { + const matchers = (typeof pattern === 'string' ? [pattern] : pattern).map(glob => { + const negated = glob[0] === '!'; + return { negated, matcher: new minimatch.Minimatch(negated ? glob.slice(1) : glob, options) }; + }); + return (file: File) => { + let relativePath = path.relative(file.cwd, file.path); + if (/^\.\.[\\/]/.test(relativePath)) { + relativePath = path.resolve(relativePath); + } + let matched = false; + for (const { negated, matcher } of matchers) { + if (matched === negated && matcher.match(relativePath)) { + matched = !negated; + } + } + return matched; + }; +} + export type { FileFunction } from 'gulp-filter'; export const rename = rename_; export const replace = replace_; diff --git a/build/lib/i18n.resources.json b/build/lib/i18n.resources.json index 36ef310964cb..edc30432ff1e 100644 --- a/build/lib/i18n.resources.json +++ b/build/lib/i18n.resources.json @@ -226,6 +226,10 @@ "name": "vs/workbench/contrib/scm", "project": "vscode-workbench" }, + { + "name": "vs/workbench/contrib/screenshotTool", + "project": "vscode-workbench" + }, { "name": "vs/workbench/contrib/search", "project": "vscode-workbench" @@ -704,6 +708,10 @@ "name": "vs/sessions/contrib/openAgentsWindow", "project": "vscode-sessions" }, + { + "name": "vs/sessions/contrib/agentsLauncher", + "project": "vscode-sessions" + }, { "name": "vs/sessions/contrib/accountMenu", "project": "vscode-sessions" diff --git a/build/lib/nodeCompileCache.ts b/build/lib/nodeCompileCache.ts index 66dfaf4c1b50..eb2c208c6a08 100644 --- a/build/lib/nodeCompileCache.ts +++ b/build/lib/nodeCompileCache.ts @@ -11,6 +11,9 @@ import * as path from 'path'; const nodeCompileCacheKinds = ['main', 'extension-host', 'shared-process', 'pty-host', 'agent-host'] as const; const nodeCompileCacheTagPattern = /^v\d+\.\d+\.\d+-(arm64|x64)-[0-9a-f]{8}$/; const nodeCompileCacheEntryPattern = /^[0-9a-f]{8}$/; +// Node writes each entry to `.XXXXXX` (uv_fs_mkstemp) and renames it into place, so a process that is +// stopped while it flushes on exit can leave one behind. The last completed write of that entry is intact. +const nodeCompileCacheTemporaryEntryPattern = /^[0-9a-f]{8}\.[A-Za-z0-9]{6}$/; export interface INodeCompileCacheProduct { readonly applicationName: string; @@ -103,7 +106,15 @@ export async function validateNodeCompileCache(rootDirectory: string, architectu } const cacheDirectory = path.join(kindDirectory, tagDirectories[0].name); - const cacheEntries = await fs.promises.readdir(cacheDirectory, { withFileTypes: true }); + const allCacheEntries = await fs.promises.readdir(cacheDirectory, { withFileTypes: true }); + const temporaryEntries = allCacheEntries.filter(entry => entry.isFile() && nodeCompileCacheTemporaryEntryPattern.test(entry.name)); + for (const entry of temporaryEntries) { + await fs.promises.rm(path.join(cacheDirectory, entry.name)); + } + if (temporaryEntries.length > 0) { + console.log(`Removed ${temporaryEntries.length} interrupted ${kind} Node.js compile cache write(s) in ${cacheDirectory}: ${temporaryEntries.map(entry => entry.name).join(', ')}.`); + } + const cacheEntries = allCacheEntries.filter(entry => !temporaryEntries.includes(entry)); const validCacheEntries = cacheEntries.filter(entry => entry.isFile() && nodeCompileCacheEntryPattern.test(entry.name)); const cacheEntryCount = validCacheEntries.length; if (cacheEntryCount === 0) { diff --git a/build/lib/npmPackage.ts b/build/lib/npmPackage.ts index f32936f4a151..44b8942281ad 100644 --- a/build/lib/npmPackage.ts +++ b/build/lib/npmPackage.ts @@ -24,7 +24,9 @@ export interface EnsureNpmPackageOptions { * Materializes an npm package from the version recorded in the adjacent * pnpm-lock.yaml (the lockfile of the install root that owns `nodeModulesRoot`) * when it is missing from node_modules, for example the package of another - * platform. + * platform. With pnpm's isolated linker, a package that pnpm installed but + * didn't link there (one that isn't a direct dependency) is linked from the + * virtual store instead. */ export function ensureNpmPackage(packageName: string, nodeModulesRoot = 'node_modules', options: EnsureNpmPackageOptions = {}): void { const packageDir = path.join(nodeModulesRoot, ...packageName.split('/')); @@ -35,6 +37,16 @@ export function ensureNpmPackage(packageName: string, nodeModulesRoot = 'node_mo const lockFilePath = path.join(path.dirname(nodeModulesRoot), 'pnpm-lock.yaml'); const lockPackage = readLockedPackage(lockFilePath, packageName); + // With pnpm's isolated linker, a package that isn't a direct dependency of the install root is + // only in the virtual store, which links one version of each package in `.pnpm/node_modules`. + const storeDir = path.join(nodeModulesRoot, '.pnpm', 'node_modules', ...packageName.split('/')); + if (fs.existsSync(path.join(storeDir, 'package.json')) && JSON.parse(fs.readFileSync(path.join(storeDir, 'package.json'), 'utf8')).version === lockPackage.version) { + fs.mkdirSync(path.dirname(packageDir), { recursive: true }); + fs.symlinkSync(fs.realpathSync(storeDir), packageDir, 'junction'); + console.log(`[ensureNpmPackage] Linked ${packageName}@${lockPackage.version} from pnpm's virtual store in ${packageDir}`); + return; + } + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-npm-package-')); try { const tarballPath = packNpmPackage(packageName, lockPackage.version, tempDir, options); diff --git a/build/lib/oxlintConfig.ts b/build/lib/oxlintConfig.ts new file mode 100644 index 000000000000..ee0347b10193 --- /dev/null +++ b/build/lib/oxlintConfig.ts @@ -0,0 +1,101 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { Linter } from 'eslint'; +import type { DummyRuleMap, OxlintConfig, OxlintOverride } from 'oxlint'; + +/** + * The plugins that oxlint loads as JS plugins, by the name that both linters know them by, and the module that oxlint + * loads, relative to the repository root. + */ +export const oxlintJsPlugins: Readonly> = { + 'local': './.eslint-plugin-local/index.ts', + 'copilot-local': './extensions/copilot/.eslintplugin/index.ts', + 'header': './.eslint-plugin-local/adapters/header.ts', + 'eslint-js': './.eslint-plugin-local/adapters/eslintCore.ts', + 'ts-eslint-js': './.eslint-plugin-local/adapters/typescriptEslint.ts', + 'jsdoc-js': 'eslint-plugin-jsdoc', + '@stylistic': '@stylistic/eslint-plugin', +}; + +/** + * Plugins whose rules oxlint implements natively under the same names. Rules without a plugin are ESLint's core rules, + * which oxlint implements natively too. + */ +const nativePlugins = new Set(['@typescript-eslint']); + +function pluginOf(rule: string): string { + const slash = rule.lastIndexOf('/'); + return slash === -1 ? '' : rule.slice(0, slash); +} + +function isGlobalIgnores(block: Linter.Config): boolean { + return Object.keys(block).every(key => key === 'ignores' || key === 'name') && !!block.ignores; +} + +function toPatterns(files: Linter.Config['files']): string[] { + return (files ?? ['**/*']).map(pattern => { + if (typeof pattern !== 'string') { + throw new Error('oxlint supports only string patterns in `files`'); + } + return pattern; + }); +} + +/** + * Converts the ESLint flat configuration of this repository into an oxlint configuration that runs the same rules on + * the same files. Rule names stay the same, so disable directives work in both linters: core rules and the + * `@typescript-eslint` rules are those that oxlint implements, and the other plugins load as JS plugins. Rules that + * oxlint does not know make it fail, rather than silently skip them. + */ +export function toOxlintConfig(eslintConfig: readonly Linter.Config[]): OxlintConfig { + const ignorePatterns: string[] = []; + const overrides: OxlintOverride[] = []; + const usedJsPlugins = new Set(); + + for (const block of eslintConfig) { + if (isGlobalIgnores(block)) { + ignorePatterns.push(...block.ignores!); + continue; + } + for (const unsupported of ['processor', 'settings', 'linterOptions'] as const) { + if (block[unsupported] !== undefined) { + throw new Error(`oxlint does not support \`${unsupported}\` in the ESLint configuration`); + } + } + if (!block.rules) { + continue; + } + + const rules: DummyRuleMap = {}; + for (const [rule, entry] of Object.entries(block.rules)) { + const plugin = pluginOf(rule); + if (plugin && !nativePlugins.has(plugin)) { + if (!Object.hasOwn(oxlintJsPlugins, plugin)) { + throw new Error(`oxlint cannot load the plugin of '${rule}': add the plugin to oxlintJsPlugins`); + } + usedJsPlugins.add(plugin); + } + if (entry !== undefined) { + rules[rule] = entry; + } + } + overrides.push({ + files: toPatterns(block.files), + ...(block.ignores ? { excludeFiles: [...block.ignores] } : {}), + rules, + }); + } + + return { + plugins: ['eslint', 'typescript'], + // Run only the rules that the ESLint configuration enables. + categories: { correctness: 'off' }, + options: { reportUnusedDisableDirectives: 'warn' }, + ignorePatterns, + jsPlugins: [...usedJsPlugins].sort().map(name => ({ name, specifier: oxlintJsPlugins[name] })), + overrides, + }; +} diff --git a/build/lib/pnpmHoist.ts b/build/lib/pnpmHoist.ts new file mode 100644 index 000000000000..f189ada9f019 --- /dev/null +++ b/build/lib/pnpmHoist.ts @@ -0,0 +1,597 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import path from 'path'; +import { getSnapshotKey, importerDependencyKinds, parsePackageKey, snapshotDependencyKinds, type PnpmLockfile } from './pnpmLock.ts'; + +/** + * Computes the `node_modules` layout that pnpm's hoisted linker (`nodeLinker: hoisted`) installs + * for a lockfile, without installing it: the folders of each package, relative to the install root. + * + * The product ships its dependencies in that layout. Computing it from the lockfile lets the build + * package the same layout whichever linker installed the dependencies: with the isolated linker, + * the packages are in pnpm's virtual store instead. + * + * pnpm (`real-hoist`) hoists with a port of the hoister of Yarn's node-modules linker + * (`@yarnpkg/nm`). This is a port of that hoister, reduced to what pnpm uses, plus the rules that + * reproduce pnpm's results on this repository's lockfiles: the dependencies of an importer are taken + * in name order, the provider of a peer is the nearest ancestor that depends on it, a dependency + * whose peer is the package that it is nested in stays nested, and dependencies whose peers can only + * be hoisted together with each other (a peer cycle, such as `webpack` and `webpack-cli`) stay where + * they are. `build/lib/dependencies.ts` compares the result with the + * locations that pnpm recorded when the hoisted linker installed the dependencies. + */ + +/** A dependency in the input tree: one per (dependency name, snapshot) pair. */ +interface IInputNode { + readonly name: string; + /** The real package name (different from `name` for npm aliases). */ + readonly identName: string; + /** The snapshot key, or the `link:`/`workspace:` reference of a project. */ + readonly reference: string; + readonly isWorkspace: boolean; + readonly peerNames: ReadonlySet; + dependencies: IInputNode[]; +} + +/** A node of the tree that the hoister rearranges. */ +interface IWorkNode { + readonly name: string; + readonly identName: string; + readonly reference: string; + readonly ident: string; + readonly isWorkspace: boolean; + readonly peerNames: ReadonlySet; + dependencies: Map; + originalDependencies: Map; + hoistedDependencies: Map; + decoupled: boolean; +} + +/** Whether a dependency can be hoisted: `depends` when only together with the peers in `dependsOn`. */ +type HoistInfo = { readonly state: 'yes' | 'no' } | { readonly state: 'depends'; readonly dependsOn: ReadonlySet }; + +function buildInputTree(lockfile: PnpmLockfile): IInputNode { + const nodes = new Map(); + const toNodes = (dependencies: readonly (readonly [string, string])[]): IInputNode[] => dependencies.map(([name, version]) => { + const key = getSnapshotKey(name, version); + if (!key) { + // A `link:` dependency on another project of the workspace. + const linkKey = `${name}:${version}`; + let node = nodes.get(linkKey); + if (!node) { + node = { name, identName: name, reference: version, isWorkspace: true, peerNames: new Set(), dependencies: [] }; + nodes.set(linkKey, node); + } + return node; + } + const nodeKey = `${name}:${key}`; + let node = nodes.get(nodeKey); + if (!node) { + const { name: identName, version: packageVersion } = parsePackageKey(key); + const snapshot = lockfile.snapshots?.[key]; + const peerDependencies = lockfile.packages?.[`${identName}@${packageVersion}`]?.peerDependencies; + node = { + name, + identName, + reference: key, + isWorkspace: false, + peerNames: new Set([...Object.keys(peerDependencies ?? {}), ...(snapshot?.transitivePeerDependencies ?? [])]), + dependencies: [], + }; + nodes.set(nodeKey, node); + const snapshotDependencies = new Map(); + for (const kind of snapshotDependencyKinds) { + for (const [dependencyName, dependencyVersion] of Object.entries(snapshot?.[kind] ?? {})) { + snapshotDependencies.set(dependencyName, dependencyVersion); + } + } + node.dependencies = toNodes([...snapshotDependencies]); + } + return node; + }); + const importerDependencies = (importerId: string): (readonly [string, string])[] => { + const importer = lockfile.importers[importerId]; + const dependencies = new Map(); + for (const kind of importerDependencyKinds) { + for (const [name, { version }] of Object.entries(importer?.[kind] ?? {})) { + dependencies.set(name, version); + } + } + return [...dependencies].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); + }; + + const root: IInputNode = { name: '.', identName: '.', reference: '', isWorkspace: true, peerNames: new Set(), dependencies: toNodes(importerDependencies('.')) }; + for (const importerId of Object.keys(lockfile.importers)) { + if (importerId !== '.') { + const name = encodeURIComponent(importerId); + root.dependencies.push({ name, identName: name, reference: `workspace:${importerId}`, isWorkspace: true, peerNames: new Set(), dependencies: toNodes(importerDependencies(importerId)) }); + } + } + return root; +} + +function createWorkNode(node: IInputNode): IWorkNode { + return { + name: node.name, + identName: node.identName, + reference: node.reference, + ident: `${node.identName}@${node.reference}`, + isWorkspace: node.isWorkspace, + peerNames: node.peerNames, + dependencies: new Map(), + originalDependencies: new Map(), + hoistedDependencies: new Map(), + decoupled: true, + }; +} + +/** + * Copies the input tree. A package that several packages depend on is one node, shared until the + * hoister changes it for one of them (see {@link decouple}). + */ +function cloneTree(tree: IInputNode): IWorkNode { + const root = createWorkNode(tree); + const seen = new Map([[tree, root]]); + const markCoupled = (node: IWorkNode, marked: Set) => { + if (marked.has(node)) { + return; + } + marked.add(node); + node.decoupled = false; + for (const dependency of node.dependencies.values()) { + if (!node.peerNames.has(dependency.name)) { + markCoupled(dependency, marked); + } + } + }; + const add = (node: IInputNode, parent: IWorkNode) => { + let workNode = seen.get(node); + const isSeen = !!workNode; + if (!workNode) { + workNode = createWorkNode(node); + seen.set(node, workNode); + } + parent.dependencies.set(node.name, workNode); + parent.originalDependencies.set(node.name, workNode); + if (!isSeen) { + for (const dependency of node.dependencies) { + add(dependency, workNode); + } + } else { + markCoupled(workNode, new Set()); + } + }; + for (const dependency of tree.dependencies) { + add(dependency, root); + } + return root; +} + +function aliasedIdent(node: IWorkNode): string { + return node.name === node.identName ? node.ident : `${node.name}@${node.ident}`; +} + +/** + * Gives `parent` its own copy of `node`, so that hoisting the dependencies of `node` for `parent` + * doesn't change it for the other packages that depend on it. + */ +function decouple(parent: IWorkNode, node: IWorkNode): IWorkNode { + if (node.decoupled) { + return node; + } + const clone: IWorkNode = { + ...node, + dependencies: new Map(node.dependencies), + originalDependencies: new Map(node.originalDependencies), + hoistedDependencies: new Map(node.hoistedDependencies), + decoupled: true, + }; + const self = clone.dependencies.get(clone.name); + if (self && self.ident === clone.ident) { + clone.dependencies.set(clone.name, clone); + } + parent.dependencies.set(clone.name, clone); + return clone; +} + +/** + * Returns the dependencies of `node` that aren't its peers, each after the peers that it shares + * with `node`'s dependencies. + */ +function getSortedRegularDependencies(node: IWorkNode): Set { + const result = new Set(); + const add = (dependency: IWorkNode, seen: Set) => { + if (seen.has(dependency)) { + return; + } + seen.add(dependency); + for (const peerName of dependency.peerNames) { + if (!node.peerNames.has(peerName)) { + const peer = node.dependencies.get(peerName); + if (peer && !result.has(peer)) { + add(peer, seen); + } + } + } + result.add(dependency); + }; + for (const dependency of node.dependencies.values()) { + if (!node.peerNames.has(dependency.name)) { + add(dependency, new Set()); + } + } + return result; +} + +/** + * Returns, for each name, the idents that may take that name in the `node_modules` of `root`, the + * most used first. + */ +function getHoistIdentMap(root: IWorkNode): Map { + const preferences = new Map; peerDependents: Set }>(); + const seen = new Set([root]); + const entry = (node: IWorkNode) => { + const key = `${node.name}@${node.ident}`; + let result = preferences.get(key); + if (!result) { + result = { dependents: new Set(), peerDependents: new Set() }; + preferences.set(key, result); + } + return result; + }; + const addDependent = (dependent: IWorkNode, node: IWorkNode) => { + const isSeen = seen.has(node); + entry(node).dependents.add(dependent.ident); + if (!isSeen) { + seen.add(node); + for (const dependency of node.dependencies.values()) { + const dependencyEntry = entry(dependency); + if (node.peerNames.has(dependency.name)) { + dependencyEntry.peerDependents.add(node.ident); + } else { + addDependent(node, dependency); + } + } + } + }; + for (const dependency of root.dependencies.values()) { + if (!root.peerNames.has(dependency.name)) { + addDependent(root, dependency); + } + } + + const result = new Map([[root.name, [root.ident]]]); + for (const dependency of root.dependencies.values()) { + if (!root.peerNames.has(dependency.name)) { + result.set(dependency.name, [dependency.ident]); + } + } + const usages = (key: string) => preferences.get(key)!.dependents.size + preferences.get(key)!.peerDependents.size; + const keys = [...preferences.keys()].sort((a, b) => usages(b) - usages(a)); + for (const key of keys) { + const name = key.substring(0, key.indexOf('@', 1)); + const ident = key.substring(name.length + 1); + if (!root.peerNames.has(name)) { + let idents = result.get(name); + if (!idents) { + idents = []; + result.set(name, idents); + } + if (!idents.includes(ident)) { + idents.push(ident); + } + } + } + return result; +} + +/** Returns the packages that the packages below `rootPath`'s last node expect from it, before any round. */ +function getZeroRoundUsedDependencies(rootPath: readonly IWorkNode[]): Map { + const result = new Map(); + const seen = new Set(); + const add = (node: IWorkNode) => { + if (seen.has(node)) { + return; + } + seen.add(node); + for (const dependency of node.hoistedDependencies.values()) { + result.set(dependency.name, dependency); + } + for (const dependency of node.dependencies.values()) { + if (!node.peerNames.has(dependency.name)) { + add(dependency); + } + } + }; + add(rootPath[rootPath.length - 1]); + return result; +} + +/** Returns the packages that the packages below `rootPath`'s last node resolve through the nodes of `rootPath`. */ +function getUsedDependencies(rootPath: readonly IWorkNode[]): Map { + const result = new Map(); + const seen = new Set(); + const add = (node: IWorkNode, hiddenNames: ReadonlySet) => { + if (seen.has(node)) { + return; + } + seen.add(node); + for (const dependency of node.hoistedDependencies.values()) { + if (!hiddenNames.has(dependency.name)) { + for (const pathNode of rootPath) { + const reachable = pathNode.dependencies.get(dependency.name); + if (reachable) { + result.set(reachable.name, reachable); + } + } + } + } + const childHiddenNames = new Set(node.dependencies.keys()); + for (const dependency of node.dependencies.values()) { + if (!node.peerNames.has(dependency.name)) { + add(dependency, childHiddenNames); + } + } + }; + add(rootPath[rootPath.length - 1], new Set()); + return result; +} + +function getHoistInfo(root: IWorkNode, nodePath: readonly IWorkNode[], node: IWorkNode, usedDependencies: ReadonlyMap, hoistIdents: ReadonlyMap, shadowedNodes: Map>, fastLookup: boolean): HoistInfo { + const parent = nodePath[nodePath.length - 1]; + let isHoistable = node.ident !== parent.ident && !node.isWorkspace && !root.peerNames.has(node.name); + + if (isHoistable) { + const used = usedDependencies.get(node.name); + let isNameAvailable = !used || used.ident === node.ident; + if (isNameAvailable) { + for (let index = nodePath.length - 1; index >= 1; index--) { + const dependency = nodePath[index].dependencies.get(node.name); + if (dependency && dependency.ident !== node.ident) { + isNameAvailable = false; + let shadowed = shadowedNodes.get(parent); + if (!shadowed) { + shadowed = new Set(); + shadowedNodes.set(parent, shadowed); + } + shadowed.add(node.name); + break; + } + } + } + isHoistable = isNameAvailable; + } + + if (isHoistable) { + isHoistable = hoistIdents.get(node.name) === node.ident; + } + + let dependsOn: Set | undefined = new Set(); + if (isHoistable) { + const unresolvedPeers = new Set(node.peerNames); + for (let index = nodePath.length - 1; index >= 1 && isHoistable; index--) { + const pathNode = nodePath[index]; + for (const peerName of unresolvedPeers) { + if (pathNode.peerNames.has(peerName) && pathNode.originalDependencies.has(peerName)) { + continue; + } + // A package whose peer is the package that it is nested in can't leave it. + if (pathNode.name === peerName && !pathNode.isWorkspace && root.dependencies.get(peerName) !== pathNode) { + dependsOn = undefined; + isHoistable = false; + break; + } + // Like pnpm's hoister, look for the provider of the peer up the ancestors: the nearest + // one that has it as a dependency (`@yarnpkg/nm` looks only at the parent). + const provider = pathNode.dependencies.get(peerName); + if (!provider) { + continue; + } + if (root.dependencies.get(peerName) !== provider) { + if (index === nodePath.length - 1) { + dependsOn!.add(provider); + } else { + dependsOn = undefined; + isHoistable = false; + break; + } + } + unresolvedPeers.delete(peerName); + } + } + } + + if (isHoistable && !fastLookup) { + for (const dependency of node.hoistedDependencies.values()) { + const used = usedDependencies.get(dependency.name) || root.dependencies.get(dependency.name); + if (!used || dependency.ident !== used.ident) { + isHoistable = false; + break; + } + } + } + + if (dependsOn && dependsOn.size > 0) { + return { state: 'depends', dependsOn }; + } + return { state: isHoistable ? 'yes' : 'no' }; +} + +function hoistGraph(rootPath: readonly IWorkNode[], usedDependencies: ReadonlyMap, hoistIdents: ReadonlyMap, parentShadowedNodes: ReadonlyMap>, shadowedNodes: Map>, fastLookup: boolean): { anotherRoundNeeded: boolean; isGraphChanged: boolean } { + const root = rootPath[rootPath.length - 1]; + const seen = new Set(); + let anotherRoundNeeded = false; + let isGraphChanged = false; + let nextNewNodes = new Set(); + + const hoistNodeDependencies = (nodePath: readonly IWorkNode[], aliasedPath: readonly string[], parent: IWorkNode) => { + if (seen.has(parent)) { + return; + } + const nextAliasedPath = [...aliasedPath, aliasedIdent(parent)]; + const dependants = new Map>(); + const infos = new Map(); + for (const dependency of getSortedRegularDependencies(parent)) { + const info = getHoistInfo(root, [root, ...nodePath, parent], dependency, usedDependencies, hoistIdents, shadowedNodes, fastLookup); + infos.set(dependency, info); + if (info.state === 'depends') { + for (const peer of info.dependsOn) { + let names = dependants.get(peer.name); + if (!names) { + names = new Set(); + dependants.set(peer.name, names); + } + names.add(dependency.name); + } + } + } + + // A dependency that depends on others being hoisted with it is hoisted only when they all + // are: a cycle of such dependencies stays. + const hoisted = new Set([...infos].filter(([, info]) => info.state === 'yes').map(([node]) => node)); + for (let changed = true; changed;) { + changed = false; + for (const [node, info] of infos) { + if (info.state === 'depends' && !hoisted.has(node) && [...info.dependsOn].every(peer => hoisted.has(peer))) { + hoisted.add(node); + changed = true; + } + } + } + const unhoistable = new Set(); + const addUnhoistable = (node: IWorkNode) => { + if (!unhoistable.has(node)) { + unhoistable.add(node); + for (const name of dependants.get(node.name) ?? []) { + addUnhoistable(parent.dependencies.get(name)!); + } + } + }; + for (const node of infos.keys()) { + if (!hoisted.has(node)) { + addUnhoistable(node); + } + } + + for (const node of infos.keys()) { + if (!unhoistable.has(node)) { + isGraphChanged = true; + if (parentShadowedNodes.get(parent)?.has(node.name)) { + anotherRoundNeeded = true; + } + parent.dependencies.delete(node.name); + parent.hoistedDependencies.set(node.name, node); + if (!root.dependencies.has(node.name) && root.ident !== node.ident) { + root.dependencies.set(node.name, node); + nextNewNodes.add(node); + } + } + } + + for (const node of getSortedRegularDependencies(parent)) { + if (unhoistable.has(node) && !nextAliasedPath.includes(aliasedIdent(node))) { + seen.add(parent); + hoistNodeDependencies([...nodePath, parent], nextAliasedPath, decouple(parent, node)); + seen.delete(parent); + } + } + }; + + nextNewNodes = new Set(getSortedRegularDependencies(root)); + const aliasedRootPath = rootPath.map(aliasedIdent); + while (nextNewNodes.size > 0) { + const newNodes = nextNewNodes; + nextNewNodes = new Set(); + for (const dependency of newNodes) { + if (dependency.ident !== root.ident) { + hoistNodeDependencies([], aliasedRootPath, decouple(root, dependency)); + } + } + } + return { anotherRoundNeeded, isGraphChanged }; +} + +function hoistTo(tree: IWorkNode, rootPath: readonly IWorkNode[], rootPathIdents: Set, parentShadowedNodes: ReadonlyMap>, fastLookup: boolean): { anotherRoundNeeded: boolean; isGraphChanged: boolean } { + const root = rootPath[rootPath.length - 1]; + const hoistIdentMap = getHoistIdentMap(root); + const usedDependencies = tree === root ? new Map() : fastLookup ? getZeroRoundUsedDependencies(rootPath) : getUsedDependencies(rootPath); + const hoistIdents = new Map([...hoistIdentMap].map(([name, idents]) => [name, idents[0]])); + const shadowedNodes = new Map>(); + let anotherRoundNeeded = false; + let isGraphChanged = false; + for (let stateChanged = true; stateChanged;) { + const result = hoistGraph(rootPath, usedDependencies, hoistIdents, parentShadowedNodes, shadowedNodes, fastLookup); + anotherRoundNeeded ||= result.anotherRoundNeeded; + isGraphChanged ||= result.isGraphChanged; + stateChanged = false; + for (const [name, idents] of hoistIdentMap) { + if (idents.length > 1 && !root.dependencies.has(name)) { + idents.shift(); + hoistIdents.set(name, idents[0]); + stateChanged = true; + } + } + } + for (const dependency of root.dependencies.values()) { + if (!root.peerNames.has(dependency.name) && !rootPathIdents.has(dependency.ident)) { + rootPathIdents.add(dependency.ident); + const result = hoistTo(tree, [...rootPath, dependency], rootPathIdents, shadowedNodes, fastLookup); + anotherRoundNeeded ||= result.anotherRoundNeeded; + isGraphChanged ||= result.isGraphChanged; + rootPathIdents.delete(dependency.ident); + } + } + return { anotherRoundNeeded, isGraphChanged }; +} + +/** + * Returns the folders where pnpm's hoisted linker installs each package of `lockfile`, by snapshot + * key, as POSIX paths relative to the install root (for example `node_modules/a/node_modules/b`). + * `skipped` are the snapshot keys of the optional packages that pnpm didn't install (`skipped` in + * `node_modules/.modules.yaml`). + */ +export function getHoistedLocations(lockfile: PnpmLockfile, skipped: ReadonlySet): Map { + const tree = cloneTree(buildInputTree(lockfile)); + for (let fastLookup = true; ; fastLookup = false) { + const result = hoistTo(tree, [tree], new Set([tree.ident]), new Map(), fastLookup); + if (!result.anotherRoundNeeded && !result.isGraphChanged) { + break; + } + } + + const result = new Map(); + const place = (node: IWorkNode, nodeModules: string, onPath: Set) => { + if (onPath.has(node)) { + return; + } + onPath.add(node); + for (const dependency of node.dependencies.values()) { + if (node.peerNames.has(dependency.name)) { + continue; + } + if (dependency.reference.startsWith('workspace:')) { + place(dependency, path.posix.join(dependency.reference.substring('workspace:'.length), 'node_modules'), onPath); + continue; + } + if (dependency.isWorkspace || !lockfile.snapshots?.[dependency.reference] || skipped.has(dependency.reference)) { + continue; + } + const location = path.posix.join(nodeModules, dependency.name); + let locations = result.get(dependency.reference); + if (!locations) { + locations = []; + result.set(dependency.reference, locations); + } + if (!locations.includes(location)) { + locations.push(location); + } + place(dependency, path.posix.join(location, 'node_modules'), onPath); + } + onPath.delete(node); + }; + place(tree, 'node_modules', new Set()); + return result; +} diff --git a/build/lib/policies/policyData.jsonc b/build/lib/policies/policyData.jsonc index 00fcda722c4e..8c44386b1fe9 100644 --- a/build/lib/policies/policyData.jsonc +++ b/build/lib/policies/policyData.jsonc @@ -535,7 +535,7 @@ } }, "type": "boolean", - "default": false, + "default": true, "included": true, "agentHost": { "status": "enforced" @@ -678,7 +678,7 @@ "localization": { "description": { "key": "chat.extensionToolsEnabled", - "value": "Enable using tools contributed by third-party extensions." + "value": "Enable using tools contributed by third-party extensions. These tools are also disabled when your organization disables MCP." } }, "type": "boolean", diff --git a/build/lib/propertyInitOrderChecker.ts b/build/lib/propertyInitOrderChecker.ts deleted file mode 100644 index 2c07f9c87575..000000000000 --- a/build/lib/propertyInitOrderChecker.ts +++ /dev/null @@ -1,320 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - - -import * as ts from 'typescript'; -import * as path from 'path'; -import * as fs from 'fs'; - -const TS_CONFIG_PATH = path.join(import.meta.dirname, '../../', 'src', 'tsconfig.json'); - -// -// ############################################################################################# -// -// A custom typescript checker that ensure constructor properties are NOT used to initialize -// defined properties. This is needed for the times when `useDefineForClassFields` is gone. -// -// see https://github.com/microsoft/vscode/issues/243049, https://github.com/microsoft/vscode/issues/186726, -// https://github.com/microsoft/vscode/pull/241544 -// -// ############################################################################################# -// - -const EntryKind = Object.freeze({ - Span: 'Span', - Node: 'Node', - StringLiteral: 'StringLiteral', - SearchedLocalFoundProperty: 'SearchedLocalFoundProperty', - SearchedPropertyFoundLocal: 'SearchedPropertyFoundLocal' -}); - -type EntryKind = typeof EntryKind[keyof typeof EntryKind]; - -const cancellationToken: ts.CancellationToken = { - isCancellationRequested: () => false, - throwIfCancellationRequested: () => { }, -}; - -const seenFiles = new Set(); -let errorCount = 0; - - - -function createProgram(tsconfigPath: string): ts.Program { - const tsConfig = ts.readConfigFile(tsconfigPath, ts.sys.readFile); - - const configHostParser: ts.ParseConfigHost = { fileExists: fs.existsSync, readDirectory: ts.sys.readDirectory, readFile: file => fs.readFileSync(file, 'utf8'), useCaseSensitiveFileNames: process.platform === 'linux' }; - const tsConfigParsed = ts.parseJsonConfigFileContent(tsConfig.config, configHostParser, path.resolve(path.dirname(tsconfigPath)), { noEmit: true }); - - const compilerHost = ts.createCompilerHost(tsConfigParsed.options, true); - - return ts.createProgram(tsConfigParsed.fileNames, tsConfigParsed.options, compilerHost); -} - -const program = createProgram(TS_CONFIG_PATH); - -program.getTypeChecker(); - -for (const file of program.getSourceFiles()) { - if (!file || file.isDeclarationFile) { - continue; - } - visit(file); -} - -if (seenFiles.size) { - console.log(); - console.log(`Found ${errorCount} error${errorCount === 1 ? '' : 's'} in ${seenFiles.size} file${seenFiles.size === 1 ? '' : 's'}.`); - process.exit(errorCount); -} - -function visit(node: ts.Node) { - if (ts.isParameter(node) && ts.isParameterPropertyDeclaration(node, node.parent)) { - checkParameterPropertyDeclaration(node); - } - - ts.forEachChild(node, visit); -} - -function checkParameterPropertyDeclaration(param: ts.ParameterPropertyDeclaration) { - const uses = [...collectReferences(param.name, [])]; - if (!uses.length) { - return; - } - - const sourceFile = param.getSourceFile(); - if (!seenFiles.has(sourceFile)) { - if (seenFiles.size) { - console.log(``); - } - console.log(`${formatFileName(param)}:`); - seenFiles.add(sourceFile); - } else { - console.log(``); - } - console.log(` Parameter property '${param.name.getText()}' is used before its declaration.`); - for (const { stack, container } of uses) { - const use = stack[stack.length - 1]; - console.log(` at ${formatLocation(use)}: ${formatMember(container)} -> ${formatStack(stack)}`); - errorCount++; - } -} - -interface InvalidUse { - stack: ts.Node[]; - container: ReferenceContainer; -} - -function* collectReferences(node: ts.Node, stack: ts.Node[], requiresInvocationDepth: number = 0, seen = new Set()): Generator { - for (const use of findAllReferencesInClass(node)) { - const container = findContainer(use); - if (!container || seen.has(container) || ts.isConstructorDeclaration(container)) { - continue; - } - seen.add(container); - - const nextStack = [...stack, use]; - - let nextRequiresInvocationDepth = requiresInvocationDepth; - if (isInvocation(use) && nextRequiresInvocationDepth > 0) { - nextRequiresInvocationDepth--; - } - - if (ts.isPropertyDeclaration(container) && nextRequiresInvocationDepth === 0) { - yield { stack: nextStack, container }; - } - else if (requiresInvocation(container)) { - nextRequiresInvocationDepth++; - } - - yield* collectReferences(container.name ?? container, nextStack, nextRequiresInvocationDepth, seen); - } -} - -function requiresInvocation(definition: ReferenceContainer): boolean { - return ts.isMethodDeclaration(definition) || ts.isFunctionDeclaration(definition) || ts.isFunctionExpression(definition) || ts.isArrowFunction(definition); -} - -function isInvocation(use: ts.Node): boolean { - let location = use; - if (ts.isPropertyAccessExpression(location.parent) && location.parent.name === location) { - location = location.parent; - } - else if (ts.isElementAccessExpression(location.parent) && location.parent.argumentExpression === location) { - location = location.parent; - } - return ts.isCallExpression(location.parent) && location.parent.expression === location - || ts.isTaggedTemplateExpression(location.parent) && location.parent.tag === location; -} - -function formatFileName(node: ts.Node): string { - const sourceFile = node.getSourceFile(); - return path.resolve(sourceFile.fileName); -} - -function formatLocation(node: ts.Node): string { - const sourceFile = node.getSourceFile(); - const { line, character } = ts.getLineAndCharacterOfPosition(sourceFile, node.pos); - return `${formatFileName(sourceFile)}(${line + 1},${character + 1})`; -} - -function formatStack(stack: ts.Node[]): string { - return stack.slice().reverse().map((use) => formatUse(use)).join(' -> '); -} - -function formatMember(container: ReferenceContainer): string { - const name = container.name?.getText(); - if (name) { - const className = findClass(container)?.name?.getText(); - if (className) { - return `${className}.${name}`; - } - return name; - } - return ''; -} - -function formatUse(use: ts.Node): string { - let text = use.getText(); - if (use.parent && ts.isPropertyAccessExpression(use.parent) && use.parent.name === use) { - if (use.parent.expression.kind === ts.SyntaxKind.ThisKeyword) { - text = `this.${text}`; - } - use = use.parent; - } - else if (use.parent && ts.isElementAccessExpression(use.parent) && use.parent.argumentExpression === use) { - if (use.parent.expression.kind === ts.SyntaxKind.ThisKeyword) { - text = `this['${text}']`; - } - use = use.parent; - } - if (ts.isCallExpression(use.parent)) { - text = `${text}(...)`; - } - return text; -} - -type ReferenceContainer = - | ts.PropertyDeclaration - | ts.MethodDeclaration - | ts.GetAccessorDeclaration - | ts.SetAccessorDeclaration - | ts.ConstructorDeclaration - | ts.ClassStaticBlockDeclaration - | ts.ArrowFunction - | ts.FunctionExpression - | ts.FunctionDeclaration - | ts.ParameterDeclaration; - -function findContainer(node: ts.Node): ReferenceContainer | undefined { - return ts.findAncestor(node, ancestor => { - switch (ancestor.kind) { - case ts.SyntaxKind.PropertyDeclaration: - case ts.SyntaxKind.MethodDeclaration: - case ts.SyntaxKind.GetAccessor: - case ts.SyntaxKind.SetAccessor: - case ts.SyntaxKind.Constructor: - case ts.SyntaxKind.ClassStaticBlockDeclaration: - case ts.SyntaxKind.ArrowFunction: - case ts.SyntaxKind.FunctionExpression: - case ts.SyntaxKind.FunctionDeclaration: - case ts.SyntaxKind.Parameter: - return true; - } - return false; - }) as ReferenceContainer | undefined; -} - -function findClass(node: ts.Node): ts.ClassLikeDeclaration | undefined { - return ts.findAncestor(node, ts.isClassLike); -} - -function* findAllReferencesInClass(node: ts.Node): Generator { - const classDecl = findClass(node); - if (!classDecl) { - return []; - } - for (const ref of findAllReferences(node)) { - for (const entry of ref.references) { - if (entry.kind !== EntryKind.Node || entry.node === node) { - continue; - } - if (findClass(entry.node) === classDecl) { - yield entry.node; - } - } - } -} - -// NOTE: The following uses TypeScript internals and are subject to change from version to version. - -interface TypeScriptInternals { - getTouchingPropertyName(sourceFile: ts.SourceFile, position: number): ts.Node; - FindAllReferences: { - FindReferencesUse: { - References: number; - }; - Core: { - getReferencedSymbolsForNode( - position: number, - node: ts.Node, - program: ts.Program, - sourceFiles: readonly ts.SourceFile[], - cancellationToken: ts.CancellationToken, - options: { use: number } - ): readonly SymbolAndEntries[] | undefined; - }; - }; -} - -function findAllReferences(node: ts.Node): readonly SymbolAndEntries[] { - const sourceFile = node.getSourceFile(); - const position = node.getStart(); - const tsInternal = ts as unknown as TypeScriptInternals; - const name: ts.Node = tsInternal.getTouchingPropertyName(sourceFile, position); - const options = { use: tsInternal.FindAllReferences.FindReferencesUse.References }; - return tsInternal.FindAllReferences.Core.getReferencedSymbolsForNode(position, name, program, [sourceFile], cancellationToken, options) ?? []; -} - -interface SymbolAndEntries { - readonly definition: Definition | undefined; - readonly references: readonly Entry[]; -} - -const DefinitionKind = Object.freeze({ - Symbol: 0, - Label: 1, - Keyword: 2, - This: 3, - String: 4, - TripleSlashReference: 5, -}); -type DefinitionKind = typeof DefinitionKind[keyof typeof DefinitionKind]; - -type Definition = - | { readonly type: DefinitionKind; readonly symbol: ts.Symbol } - | { readonly type: DefinitionKind; readonly node: ts.Identifier } - | { readonly type: DefinitionKind; readonly node: ts.Node } - | { readonly type: DefinitionKind; readonly node: ts.Node } - | { readonly type: DefinitionKind; readonly node: ts.StringLiteralLike } - | { readonly type: DefinitionKind; readonly reference: ts.FileReference; readonly file: ts.SourceFile }; - -type NodeEntryKind = typeof EntryKind.Node | typeof EntryKind.StringLiteral | typeof EntryKind.SearchedLocalFoundProperty | typeof EntryKind.SearchedPropertyFoundLocal; -type Entry = NodeEntry | SpanEntry; -interface ContextWithStartAndEndNode { - start: ts.Node; - end: ts.Node; -} -type ContextNode = ts.Node | ContextWithStartAndEndNode; -interface NodeEntry { - readonly kind: NodeEntryKind; - readonly node: ts.Node; - readonly context?: ContextNode; -} -interface SpanEntry { - readonly kind: typeof EntryKind.Span; - readonly fileName: string; - readonly textSpan: ts.TextSpan; -} diff --git a/build/lib/stylelint/vscode-known-variables.json b/build/lib/stylelint/vscode-known-variables.json index ad2527e23872..d7faa55ca34a 100644 --- a/build/lib/stylelint/vscode-known-variables.json +++ b/build/lib/stylelint/vscode-known-variables.json @@ -24,6 +24,7 @@ "--vscode-agentFeedbackEditorWidget-background", "--vscode-agentFeedbackEditorWidget-border", "--vscode-agentFeedbackInputWidget-border", + "--vscode-agentSessionNeedsInput-foreground", "--vscode-agentSessionReadIndicator-foreground", "--vscode-agentSessionSelectedBadge-border", "--vscode-agentSessionSelectedUnfocusedBadge-border", @@ -260,6 +261,7 @@ "--vscode-editorCodeLens-foreground", "--vscode-editorCommentsWidget-rangeActiveBackground", "--vscode-editorCommentsWidget-rangeBackground", + "--vscode-editorCommentsWidget-rangeBorder", "--vscode-editorCommentsWidget-replyInputBackground", "--vscode-editorCommentsWidget-resolvedBorder", "--vscode-editorCommentsWidget-unresolvedBorder", @@ -715,6 +717,8 @@ "--vscode-agentsPanel-foreground", "--vscode-agentsCard-border", "--vscode-agentsBottomPanel-border", + "--vscode-agentsActivityBar-background", + "--vscode-agentsActivityBar-border", "--vscode-agentsBadge-background", "--vscode-agentsBadge-foreground", "--vscode-agentsGradient-tintColor", @@ -1010,6 +1014,9 @@ "--activity-bar-width", "--agent-sessions-editor-tab-padding", "--agents-floating-panel-gap", + "--agents-grid-gap-offset", + "--agents-component-corner-radius", + "--agents-outer-panel-gap", "--agents-part-corner-radius", "--agents-part-frame-border-width", "--agents-session-frame-inset", @@ -1018,15 +1025,38 @@ "--chat-window-controls-width", "--session-chat-base-height", "--session-group-depth", + "--session-group-focus-foreground", + "--session-group-foreground", + "--session-group-hover-foreground", + "--session-group-inactive-focus-foreground", + "--session-group-inactive-selection-foreground", "--session-group-indent", "--session-group-insertion-depth", + "--session-group-interaction-foreground", + "--session-group-selection-foreground", "--editor-font-size", "--background-dark", "--background-light", + "--mobile-list-text-inset", "--mobile-diff-tok-comment", "--mobile-diff-tok-string", "--mobile-diff-tok-keyword", "--mobile-diff-tok-number", + "--mobile-surface-page", + "--mobile-surface-card", + "--mobile-surface-raised", + "--mobile-surface-pressed", + "--mobile-separator", + "--mobile-target", + "--mobile-row", + "--mobile-control", + "--mobile-control-fill", + "--mobile-control-glyph", + "--mobile-line-height-body", + "--mobile-line-height-label", + "--mobile-motion-push", + "--mobile-motion-fade", + "--mobile-ease-out", "--session-view-background", "--tools-connected-depth", "--session-view-foreground", @@ -1054,6 +1084,7 @@ "--chat-input-notice-radius", "--chat-input-own-radius", "--chat-input-notification-line-height", + "--chat-inline-attachment-max-width", "--chat-editing-last-edit-shift", "--chat-voice-icon-glow-color", "--sessions-chat-background-image", @@ -1066,6 +1097,11 @@ "--chat-chain-icon-start", "--chat-chain-icon-top", "--chat-chain-rail-top", + "--chat-conversation-chevron-bearing", + "--chat-conversation-chevron-length", + "--chat-conversation-chevron-open-shift", + "--chat-conversation-label-left", + "--chat-conversation-rail-left", "--chat-current-response-min-height", "--chat-persistent-hook-width", "--chat-persistent-icon-left", @@ -1130,6 +1166,11 @@ "--pane-header-size", "--model-hover-surface-background", "--modern-ui-activitybar-lane", + "--modern-ui-connected-pane-bottom-left-radius", + "--modern-ui-connected-pane-bottom-right-radius", + "--modern-ui-connected-pane-frame-radius", + "--modern-ui-connected-pane-radius", + "--modern-ui-connected-pane-right-radius", "--modern-ui-connected-tab-action-background", "--modern-ui-connected-tab-action-inset", "--modern-ui-connected-tab-active-background", @@ -1295,6 +1336,17 @@ "--window-border-width", "--window-corner-radius", "--window-device-pixel-ratio", + "--workbench-sash-end", + "--workbench-custom-buttons-corner-radius", + "--workbench-custom-controls-corner-radius", + "--workbench-custom-dialogs-corner-radius", + "--workbench-custom-hovers-corner-radius", + "--workbench-custom-inputs-corner-radius", + "--workbench-custom-menus-corner-radius", + "--workbench-custom-popups-corner-radius", + "--workbench-sash-highlight-end", + "--workbench-sash-highlight-start", + "--workbench-sash-start", "--window-zoom-factor", "--vscode-parameterHintsWidget-editorFontFamily", "--vscode-parameterHintsWidget-editorFontFamilyDefault", @@ -1417,6 +1469,7 @@ "--segmented-icon-toggle-radius", "--segmented-icon-toggle-single-width", "--segmented-icon-toggle-width", + "--vscode-activityBar-cornerRadius", "--vscode-agents-fontSize-body1", "--vscode-agents-fontSize-body2", "--vscode-agents-fontSize-heading1", @@ -1428,17 +1481,28 @@ "--vscode-agents-fontWeight-regular", "--vscode-agents-fontWeight-semiBold", "--vscode-agents-layout-floatingPanelGap", + "--vscode-agentsWindow-chatPanels-cornerRadius", + "--vscode-agentsWindow-editorArea-cornerRadius", + "--vscode-agentsWindow-panels-cornerRadius", + "--vscode-agentsWindow-panels-spacing", + "--vscode-agentsWindow-secondarySideBar-cornerRadius", + "--vscode-agentsWindow-toolsPanel-cornerRadius", "--vscode-bodyFontSize", "--vscode-bodyFontSize-small", "--vscode-bodyFontSize-xSmall", + "--vscode-buttons-cornerRadius", "--vscode-codiconFontSize", "--vscode-codiconFontSize-compact", + "--vscode-controls-cornerRadius", "--vscode-cornerRadius-circle", "--vscode-cornerRadius-large", "--vscode-cornerRadius-medium", "--vscode-cornerRadius-small", "--vscode-cornerRadius-xLarge", "--vscode-cornerRadius-xSmall", + "--vscode-default-cornerRadius", + "--vscode-dialogs-cornerRadius", + "--vscode-editorArea-cornerRadius", "--vscode-fontSize-body1", "--vscode-fontSize-body2", "--vscode-fontSize-heading1", @@ -1449,7 +1513,16 @@ "--vscode-fontSize-label3", "--vscode-fontWeight-regular", "--vscode-fontWeight-semiBold", + "--vscode-hovers-cornerRadius", + "--vscode-inputs-cornerRadius", "--vscode-keyboard-height", + "--vscode-menus-cornerRadius", + "--vscode-pages-cornerRadius", + "--vscode-panels-cornerRadius", + "--vscode-panels-spacing", + "--vscode-popups-cornerRadius", + "--vscode-primarySideBar-cornerRadius", + "--vscode-secondarySideBar-cornerRadius", "--vscode-spacing-sizeNone", "--vscode-spacing-size20", "--vscode-spacing-size40", @@ -1464,6 +1537,7 @@ "--vscode-spacing-size320", "--vscode-spacing-size360", "--vscode-spacing-size400", - "--vscode-strokeThickness" + "--vscode-strokeThickness", + "--vscode-toolsPanel-cornerRadius" ] } diff --git a/build/lib/test/copilot.test.ts b/build/lib/test/copilot.test.ts index 896483e62ae1..9990446136a0 100644 --- a/build/lib/test/copilot.test.ts +++ b/build/lib/test/copilot.test.ts @@ -12,6 +12,7 @@ import * as path from 'path'; import { suite, test } from 'node:test'; import { create } from 'tar'; import { copilotPlatforms, ensureCopilotPlatformPackage, getCopilotExcludeFilter, getCopilotRuntimePrebuildFiles, getCopilotRuntimeVersion, prepareBuiltInCopilotRipgrepShim, renderCopilotShimLauncher } from '../copilot.ts'; +import { getLockedVersion } from '../pnpmLock.ts'; import { writePnpmLockfile } from './pnpmLockfileFixture.ts'; /** @@ -361,6 +362,31 @@ suite('copilot', () => { } }); + test('verifies fetched natives against the repository lockfile that records extensions/copilot', () => { + const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-copilot-sdk-repo-lockfile-test-')); + try { + const builtInCopilotExtensionDir = path.join(repoRoot, 'extensions', 'copilot'); + const extensionCopilotDir = path.join(builtInCopilotExtensionDir, 'node_modules', '@github', 'copilot'); + const appNodeModulesDir = path.join(repoRoot, 'node_modules'); + const version = getLockedVersion('extensions/copilot', '@github/copilot'); + + fs.mkdirSync(path.join(extensionCopilotDir, 'sdk'), { recursive: true }); + fs.writeFileSync(path.join(extensionCopilotDir, 'package.json'), JSON.stringify({ version })); + + // Without a lockfile override, the pinned integrity must be found before the native is fetched. + const packCalls: string[] = []; + assert.throws(() => prepareBuiltInCopilotRipgrepShim('win32', 'x64', builtInCopilotExtensionDir, appNodeModulesDir, { + packPackage: (packageName, packageVersion) => { + packCalls.push(`${packageName}@${packageVersion}`); + throw new Error('not fetched in tests'); + } + }), /not fetched in tests/); + assert.deepStrictEqual(packCalls, [`@github/copilot-win32-x64@${version}`]); + } finally { + fs.rmSync(repoRoot, { recursive: true, force: true }); + } + }); + test('strips all copilot platform packages for unsupported armhf builds', () => { assert.deepStrictEqual( getCopilotExcludeFilter('linux', 'armhf'), diff --git a/build/lib/test/dependencies.test.ts b/build/lib/test/dependencies.test.ts index 33452e83b3b5..ee7d4e8f1906 100644 --- a/build/lib/test/dependencies.test.ts +++ b/build/lib/test/dependencies.test.ts @@ -8,7 +8,9 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { suite, test } from 'node:test'; -import { getMixedInDistroDependencies, toFlatProductionDependencies } from '../dependencies.ts'; +import es from 'event-stream'; +import VinylFile from 'vinyl'; +import { getMixedInDistroDependencies, toFlatProductionDependencies, toPackagedLayout } from '../dependencies.ts'; suite('dependencies', () => { @@ -32,19 +34,64 @@ suite('dependencies', () => { }); }); - test('packages dependencies flat, wherever the workspace installed them', () => { + test('packages dependencies flat, wherever the workspace or pnpm\'s virtual store installed them', () => { const remote = path.join(os.tmpdir(), 'remote'); - const folders = [ - path.join(remote, 'web', 'node_modules', 'jschardet'), - path.join(remote, 'node_modules', '@xterm', 'xterm'), - path.join(remote, 'node_modules', 'katex', 'node_modules', 'commander'), + const store = path.join(remote, 'node_modules', '.pnpm'); + const dependencies = [ + { folder: path.join(remote, 'web', 'node_modules', 'jschardet'), source: path.join(remote, 'web', 'node_modules', 'jschardet') }, + { folder: path.join(remote, 'node_modules', '@xterm', 'xterm'), source: path.join(store, '@xterm+xterm@6.0.0', 'node_modules', '@xterm', 'xterm') }, + { folder: path.join(remote, 'node_modules', 'katex', 'node_modules', 'commander'), source: path.join(remote, 'node_modules', 'katex', 'node_modules', 'commander') }, ]; - assert.deepStrictEqual(toFlatProductionDependencies(folders).map(({ folder, base }) => [path.relative(remote, base), path.relative(base, folder)]), [ - ['web', path.join('node_modules', 'jschardet')], - ['', path.join('node_modules', '@xterm', 'xterm')], - [path.join('node_modules', 'katex'), path.join('node_modules', 'commander')], + assert.deepStrictEqual({ + flat: toFlatProductionDependencies(dependencies).map(({ folder, base, source }) => [path.relative(remote, base), path.relative(base, folder), path.relative(remote, source)]), + sameName: assert.throws(() => toFlatProductionDependencies([...dependencies, { folder: path.join(remote, 'web', 'node_modules', 'commander'), source: path.join(remote, 'web', 'node_modules', 'commander') }]), /both named commander/), + }, { + flat: [ + ['web', path.join('node_modules', 'jschardet'), path.join('web', 'node_modules', 'jschardet')], + ['', path.join('node_modules', '@xterm', 'xterm'), path.join('node_modules', '.pnpm', '@xterm+xterm@6.0.0', 'node_modules', '@xterm', 'xterm')], + [path.join('node_modules', 'katex'), path.join('node_modules', 'commander'), path.join('node_modules', 'katex', 'node_modules', 'commander')], + ], + sameName: undefined, + }); + }); + + test('moves files from pnpm\'s virtual store to the hoisted layout, as independent copies', async t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-dependencies-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const store = path.join(root, 'node_modules', '.pnpm'); + const write = (file: string, contents: string) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, contents); + }; + // `a` and `b` depend on `uuid`, nested in each of them in the hoisted layout because another + // version is at the root. + const a = { folder: path.join(root, 'node_modules', 'a'), source: path.join(store, 'a@1.0.0', 'node_modules', 'a') }; + const uuid = { folder: path.join(root, 'node_modules', 'a', 'node_modules', 'uuid'), source: path.join(store, 'uuid@8.0.0', 'node_modules', 'uuid') }; + const b = { folder: path.join(root, 'node_modules', 'b'), source: path.join(store, 'b@1.0.0', 'node_modules', 'b') }; + const bUuid = { folder: path.join(root, 'node_modules', 'b', 'node_modules', 'uuid'), source: uuid.source }; + const distro = { folder: path.join(root, 'node_modules', 'vsda'), source: path.join(root, 'node_modules', 'vsda') }; + write(path.join(a.source, 'index.js'), 'a'); + write(path.join(a.source, 'node_modules', '.bin', 'uuid'), 'pnpm command shim'); + write(path.join(uuid.source, 'index.js'), '//# sourceMappingURL=index.js.map'); + write(path.join(distro.source, 'index.js'), 'vsda'); + const files = [path.join(a.source, 'index.js'), path.join(a.source, 'node_modules', '.bin', 'uuid'), path.join(uuid.source, 'index.js'), path.join(distro.source, 'index.js')] + .map(file => new VinylFile({ base: root, path: file, contents: fs.readFileSync(file) })); + + // Like `rewriteSourceMappingURL`, change each file synchronously, from its packaged path. + const packaged = await new Promise((resolve, reject) => es.readArray(files) + .pipe(toPackagedLayout([a, uuid, b, bUuid, distro])) + .pipe(es.mapSync((file: VinylFile) => { + file.contents = Buffer.from(file.contents!.toString().replace(/sourceMappingURL=(.*)$/, `sourceMappingURL=https://cdn/${path.dirname(file.relative).split(path.sep).join('/')}/$1`)); + return file; + })) + .pipe(es.writeArray((err: Error | undefined, result: VinylFile[]) => err ? reject(err) : resolve(result)))); + + assert.deepStrictEqual(packaged.map(file => [file.relative.split(path.sep).join('/'), file.contents!.toString()]), [ + ['node_modules/a/index.js', 'a'], + ['node_modules/a/node_modules/uuid/index.js', '//# sourceMappingURL=https://cdn/node_modules/a/node_modules/uuid/index.js.map'], + ['node_modules/b/node_modules/uuid/index.js', '//# sourceMappingURL=https://cdn/node_modules/b/node_modules/uuid/index.js.map'], + ['node_modules/vsda/index.js', 'vsda'], ]); - assert.throws(() => toFlatProductionDependencies([...folders, path.join(remote, 'web', 'node_modules', 'commander')]), /both named commander/); }); }); diff --git a/build/lib/test/esrpDownloadStall.test.ts b/build/lib/test/esrpDownloadStall.test.ts index 041634adfe51..967e41277913 100644 --- a/build/lib/test/esrpDownloadStall.test.ts +++ b/build/lib/test/esrpDownloadStall.test.ts @@ -87,13 +87,13 @@ suite('ESRP macOS download stall guard', () => { assert.ok(Date.now() - started < 10_000, 'the stalled session was not stopped promptly'); }); - // Like esrpcli: reads and deletes its key file, downloads to .tmp and + // Like esrpcli: reads authentication from stdin, downloads to .tmp and // moves it into place. Sessions listed in `stallingSessions` never finish their download. const fakeEsrpcli = ` const fs = require('fs'), path = require('path'); - const [keyFile, folder, counterFile, stallingSessions] = process.argv.slice(1); - if (!fs.existsSync(keyFile)) { console.log('Missing the encryption key data...'); process.exit(1); } - fs.rmSync(keyFile); + const [folder, counterFile, stallingSessions] = process.argv.slice(1); + require('node:assert/strict').equal(fs.readFileSync(0, 'utf8'), 'synthetic-esrp-token\\n'); + console.log('ESRP_AUTH_INPUT_READY'); const session = fs.existsSync(counterFile) ? Number(fs.readFileSync(counterFile, 'utf8')) + 1 : 1; fs.writeFileSync(counterFile, String(session)); const tmp = path.join(folder, 'VSCode-darwin-arm64.zip.tmp'); @@ -114,19 +114,15 @@ suite('ESRP macOS download stall guard', () => { fs.writeFileSync(path.join(folder, 'VSCode-darwin-arm64.zip'), 'unsigned'); // A leftover .tmp from an earlier, killed run fs.writeFileSync(path.join(folder, 'VSCode-darwin-arm64.zip.tmp'), 'leftover'); - const createArgs = () => { - const keyFile = path.join(folder, `key-${Math.random()}`); - fs.writeFileSync(keyFile, 'key'); - return ['-e', fakeEsrpcli, keyFile, folder, counterFile, stallingSessions]; - }; - const exitCode = await runWithEsrpDownloadResubmission(process.execPath, createArgs, folder, 'VSCode-darwin-arm64.zip', { windowMs: 150, minBytesPerSecond: MB }, (_stall, attempt) => stalls.push(attempt), 50); + const createArgs = () => ['-e', fakeEsrpcli, folder, counterFile, stallingSessions]; + const exitCode = await runWithEsrpDownloadResubmission(process.execPath, createArgs, folder, 'VSCode-darwin-arm64.zip', { windowMs: 150, minBytesPerSecond: MB }, (_stall, attempt) => stalls.push(attempt), 50, 'synthetic-esrp-token'); return { exitCode, stalls, sessions: Number(fs.readFileSync(counterFile, 'utf8')), signed: fs.readFileSync(path.join(folder, 'VSCode-darwin-arm64.zip'), 'utf8'), leftover: fs.existsSync(path.join(folder, 'VSCode-darwin-arm64.zip.tmp')) }; } finally { fs.rmSync(folder, { recursive: true, force: true }); } } - test('submits the file again with a new key after a killed session stalls', async () => { + test('sends authentication again after a killed session stalls', async () => { const result = await runFakeSessions('1'); assert.deepEqual(result.stalls, [1]); assert.equal(result.sessions, 2); diff --git a/build/lib/test/esrpStallGuard.test.ts b/build/lib/test/esrpStallGuard.test.ts index c482e1c6950b..4caffcdbd3d1 100644 --- a/build/lib/test/esrpStallGuard.test.ts +++ b/build/lib/test/esrpStallGuard.test.ts @@ -4,14 +4,89 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'node:assert/strict'; +import cp from 'node:child_process'; import { suite, test } from 'node:test'; -import { EsrpProgress, getEsrpStallTimeoutMs, runWithEsrpStallGuard } from '../../azure-pipelines/common/sign.ts'; +import { EsrpProgress, getEsrpStallTimeoutMs, main, runWithEsrpStallGuard } from '../../azure-pipelines/common/sign.ts'; function fakeEsrp(script: string): string[] { return ['-e', script]; } suite('ESRP stall guard', () => { + test('signing entrypoints send authentication on stdin without token files or environment credentials', async t => { + const credentials = ['SYSTEM_ACCESSTOKEN', 'ENDPOINT_AUTH_SYSTEMVSSCONNECTION', 'ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN']; + for (const name of credentials) { + const original = process.env[name]; + process.env[name] = 'synthetic-esrp-token'; + t.after(() => { + if (original === undefined) { + delete process.env[name]; + } else { + process.env[name] = original; + } + }); + } + + t.mock.method(cp, 'execSync', () => '6.0.428'); + const spawn = cp.spawn; + t.mock.method(cp, 'spawn', (command: string, args: readonly string[], options: cp.SpawnOptions) => { + assert.equal(command, 'dotnet'); + assert.ok(!JSON.stringify(args).includes('synthetic-esrp-token')); + const metadata = JSON.parse(args[args.indexOf('-federatedTokenData') + 1]); + assert.deepEqual({ + source: metadata.systemAccessTokenSource, + tokenFile: metadata.systemAccessToken, + keyFile: metadata.encryptionKey + }, { source: 'stdin', tokenFile: undefined, keyFile: undefined }); + return spawn(process.execPath, ['-e', ` + const assert = require('node:assert/strict'); + assert.equal(require('node:fs').readFileSync(0, 'utf8'), 'synthetic-esrp-token\\n'); + for (const name of ${JSON.stringify(credentials)}) { + assert.equal(process.env[name], undefined); + } + process.stdout.write('ESRP_AUTH_INPUT_'); + setTimeout(() => process.stdout.write('READY\\r\\n'), 10); + `], options); + }); + + for (const type of ['sign-windows', 'sign-darwin', 'sign-pgp']) { + await main(['/task/6.1.3/net6.0/esrpcli.dll', type, '.', '*.unsigned-test-file']); + } + }); + + test('rejects missing or invalid authentication before starting a process', t => { + const original = process.env['SYSTEM_ACCESSTOKEN']; + t.after(() => { + if (original === undefined) { + delete process.env['SYSTEM_ACCESSTOKEN']; + } else { + process.env['SYSTEM_ACCESSTOKEN'] = original; + } + }); + for (const token of ['', ' ', 'synthetic\ncredential', 'x'.repeat(32768)]) { + process.env['SYSTEM_ACCESSTOKEN'] = token; + assert.throws(() => main([]), /^Error: Missing or invalid SYSTEM_ACCESSTOKEN for ESRP signing\.$/); + } + delete process.env['SYSTEM_ACCESSTOKEN']; + assert.throws(() => main([]), /^Error: Missing or invalid SYSTEM_ACCESSTOKEN for ESRP signing\.$/); + }); + + test('rejects a CLI that does not acknowledge the stdin contract', async () => { + await assert.rejects( + runWithEsrpStallGuard(process.execPath, fakeEsrp(`require('node:fs').readFileSync(0, 'utf8');`), 500, 50, 'synthetic-esrp-token'), + /ESRP CLI exited without confirming authentication input/ + ); + }); + + test('preserves a failed authenticated session exit code', async () => { + const result = await runWithEsrpStallGuard(process.execPath, fakeEsrp(` + require('node:fs').readFileSync(0, 'utf8'); + console.log('ESRP_AUTH_INPUT_READY'); + process.exit(3); + `), 500, 50, 'synthetic-esrp-token'); + assert.deepEqual(result, { exitCode: 3, stalled: undefined }); + }); + test('measures a stall only once ESRP reports pending operations', () => { const progress = new EsrpProgress(0); progress.write('Waiting for signed files...\n', 1_000); diff --git a/build/lib/test/extensions.test.ts b/build/lib/test/extensions.test.ts index db2c30035359..c5667236ea8a 100644 --- a/build/lib/test/extensions.test.ts +++ b/build/lib/test/extensions.test.ts @@ -4,8 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import es from 'event-stream'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; import { suite, test } from 'node:test'; -import { isPackagedTypeScriptFile } from '../extensions.ts'; +import type VinylFile from 'vinyl'; +import { getSharedExtensionDependencyStream, isPackagedTypeScriptFile } from '../extensions.ts'; +import { cleanNodeModules } from '../util.ts'; suite('isPackagedTypeScriptFile', () => { test('keeps package.json and lib, without the compiler, typescriptServices and most declarations', () => { @@ -49,3 +55,23 @@ suite('isPackagedTypeScriptFile', () => { ]); }); }); + +suite('getSharedExtensionDependencyStream', () => { + test('places the files of a package in pnpm\'s virtual store at their destination, for the module filters', async t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-extensions-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const folder = path.join(root, 'node_modules', '.pnpm', 'x@1.0.0', 'node_modules', 'x'); + for (const file of ['index.js', 'README.md', 'test/index.js']) { + fs.mkdirSync(path.dirname(path.join(folder, file)), { recursive: true }); + fs.writeFileSync(path.join(folder, file), file); + } + const moduleIgnore = path.join(root, '.moduleignore'); + fs.writeFileSync(moduleIgnore, 'x/README.md\n'); + + const packaged = await new Promise((resolve, reject) => getSharedExtensionDependencyStream(folder, 'extensions/node_modules/x') + .pipe(cleanNodeModules(moduleIgnore)) + .pipe(es.writeArray((err: Error | undefined, result: VinylFile[]) => err ? reject(err) : resolve(result)))); + + assert.deepStrictEqual(packaged.filter(file => !file.isDirectory()).map(file => file.relative.split(path.sep).join('/')), ['extensions/node_modules/x/index.js']); + }); +}); diff --git a/build/lib/test/formatter.test.ts b/build/lib/test/formatter.test.ts new file mode 100644 index 000000000000..5e9e9d28fbf9 --- /dev/null +++ b/build/lib/test/formatter.test.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * 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 fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { suite, test } from 'node:test'; +import { Formatter } from '../formatter.ts'; + +suite('formatter', () => { + + test('formats files on disk and in memory with the tsfmt.json settings, and sees changes to files on disk', async () => { + const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-formatter-')); + const file = path.join(folder, 'test.ts'); + const formatter = await Formatter.start(); + try { + fs.writeFileSync(file, 'const f = function() {\n return [1,2];\n};\n'); + const fromDisk = await formatter.format(file, fs.readFileSync(file, 'utf8')); + fs.writeFileSync(file, 'if(x){y();}\n'); + const changedOnDisk = await formatter.format(file, fs.readFileSync(file, 'utf8')); + const inMemory = await formatter.format(file, 'let x = - (y);\n'); + + assert.deepStrictEqual({ fromDisk, changedOnDisk, inMemory }, { + fromDisk: 'const f = function () {\n\treturn [1, 2];\n};\n', + changedOnDisk: 'if (x) { y(); }\n', + inMemory: 'let x = -(y);\n', + }); + } finally { + await formatter.dispose(); + fs.rmSync(folder, { recursive: true, force: true }); + } + }); +}); diff --git a/build/lib/test/gulpFacade.test.ts b/build/lib/test/gulpFacade.test.ts new file mode 100644 index 000000000000..524dc46db007 --- /dev/null +++ b/build/lib/test/gulpFacade.test.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import es from 'event-stream'; +import path from 'path'; +import VinylFile from 'vinyl'; +import { suite, test } from 'node:test'; +import { filter } from '../gulp/facade.ts'; + +function filterPaths(paths: readonly string[], pattern: string[], options?: { dot?: boolean }): Promise { + const cwd = process.cwd(); + return new Promise((resolve, reject) => { + const matched: string[] = []; + es.readArray(paths.map(p => new VinylFile({ cwd, base: cwd, path: path.join(cwd, p) }))) + .pipe(filter(pattern, options)) + .on('data', (file: VinylFile) => matched.push(file.relative.replace(/\\/g, '/'))) + .on('end', () => resolve(matched)) + .on('error', reject); + }); +} + +suite('gulp facade filter', () => { + + test('applies the patterns in order, like gulp-filter', async () => { + const paths = ['a.ts', 'a.md', 'docs/keep.md', 'docs/drop.md', '.github/x.yml']; + assert.deepStrictEqual({ + ordered: await filterPaths(paths, ['**', '!**/*.md', 'docs/keep.md']), + negatedFirst: await filterPaths(paths, ['!**/*.md', '**/*.ts']), + dot: await filterPaths(paths, ['**', '!**/*.md'], { dot: true }), + }, { + ordered: ['a.ts', 'docs/keep.md'], + negatedFirst: ['a.ts'], + dot: ['a.ts', '.github/x.yml'], + }); + }); +}); diff --git a/build/lib/test/mobileWebPublication.test.ts b/build/lib/test/mobileWebPublication.test.ts new file mode 100644 index 000000000000..29a1e356d328 --- /dev/null +++ b/build/lib/test/mobileWebPublication.test.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { execFileSync } from 'node:child_process'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { load } from 'js-yaml'; +import { getWebCdnConfiguration, validateMobileWebCdnIdentity } from '../../azure-pipelines/web/cdnConfiguration.ts'; +import { mobileDirectory, mobileManifestName } from '../../next/mobile.ts'; + +const commit = '0123456789abcdef0123456789abcdef01234567'; + +test('normal publication keeps its existing source, commit directory and file inventory', () => { + assert.deepStrictEqual(getWebCdnConfiguration([], 'insider', commit), { + source: '../vscode-web', prefix: `insider/${commit}/`, patterns: ['**'], mobile: false, + }); +}); + +test('mobile publication cannot enter the normal web preload directory', () => { + assert.deepStrictEqual(getWebCdnConfiguration(['--mobile'], 'insider', commit), { + source: mobileDirectory, + prefix: `agents/mobile/insider/${commit}/`, + patterns: ['out/**', 'node_modules/**', 'extensions/**', mobileManifestName], + mobile: true, + }); + for (const [quality, revision] of [['dev', commit], ['stable', undefined], ['stable', '../other']]) { + assert.throws(() => getWebCdnConfiguration(['--mobile'], quality, revision)); + } + assert.throws(() => getWebCdnConfiguration(['--mobile', '--other'], 'stable', commit), /Usage/); +}); + +test('mobile CDN publication verifies the pipeline commit and quality without a second release ID', async t => { + const directory = await mkdtemp(join(tmpdir(), 'mobile-cdn-')); + t.after(() => rm(directory, { recursive: true, force: true })); + await writeFile(join(directory, mobileManifestName), JSON.stringify({ + schemaVersion: 2, kind: 'sessions-mobile', build: { commit, quality: 'insider' }, + })); + await validateMobileWebCdnIdentity(directory, 'insider', commit); + await assert.rejects(validateMobileWebCdnIdentity(directory, 'stable', commit), /VSCODE_QUALITY/); + await assert.rejects(validateMobileWebCdnIdentity(directory, 'insider', 'f'.repeat(40)), /BUILD_SOURCEVERSION/); +}); + +test('the standard publisher registers mobile separately while preserving web and server-web platform names', () => { + const moduleUrl = new URL('../../azure-pipelines/common/publish.ts', import.meta.url).href; + const output = execFileSync(process.execPath, ['--input-type=module', '-e', ` + const { getPlatform } = await import(${JSON.stringify(moduleUrl)}); + console.log(JSON.stringify(['mobile', 'standalone', 'x64'].map(arch => getPlatform('web', 'linux', arch, 'archive-unsigned')))); + `], { encoding: 'utf8', env: { ...process.env, SYSTEM_ACCESSTOKEN: 'unit-test' } }); + assert.deepStrictEqual(JSON.parse(output.trim()), ['web-mobile', 'web-standalone', 'server-linux-x64-web']); +}); + +test('both product pipeline entry points keep mobile opt-in and require the existing Web stage', async () => { + for (const file of ['../../azure-pipelines/product-build.yml', '../../azure-pipelines/product-build-template.yml']) { + const source = await readFile(new URL(file, import.meta.url), 'utf8'); + const pipeline = load(source) as { parameters: { name: string; default: boolean }[] }; + assert.equal(pipeline.parameters.find(parameter => parameter.name === 'VSCODE_BUILD_WEB_MOBILE')?.default, false); + assert.ok(source.includes('VSCODE_BUILD_WEB_MOBILE: ${{ parameters.VSCODE_BUILD_WEB_MOBILE }}')); + assert.ok(source.includes('Mobile web requires a Product build with VSCODE_BUILD_WEB=true')); + } +}); + +test('the existing Web job builds a normal archive before publication and guards mobile CDN writes', async () => { + const source = await readFile(new URL('../../azure-pipelines/web/product-build-web.yml', import.meta.url), 'utf8'); + const pipeline = load(source) as { parameters: { name: string; default: boolean }[]; jobs: { templateContext: { outputs: object[] } }[] }; + assert.equal(pipeline.parameters.find(parameter => parameter.name === 'VSCODE_BUILD_WEB_MOBILE')?.default, false); + assert.ok(JSON.stringify(pipeline.jobs[0].templateContext.outputs).includes('vscode_web_linux_mobile_archive-unsigned')); + assert.match(source, /^\s*pnpm run test-mobile\s*$/m); + assert.ok(source.includes('node --test build/lib/test/mobileWebPublication.test.ts')); + assert.match(source, /^\s*pnpm run bundle-mobile\s*$/m); + assert.ok(source.includes('--transform=\'s,^out-mobile,vscode-web-mobile,\'')); + assert.ok(source.includes('out-mobile/mobile.json')); + assert.ok(source.includes('condition: and(succeeded(), eq(variables[\'VSCODE_PUBLISH\'], \'True\'))')); + assert.ok(source.indexOf('Build and validate mobile web archive') < source.indexOf('node build/azure-pipelines/upload-cdn.ts --mobile')); + assert.ok(!source.includes('publish-mobile')); +}); + +test('mobile archive retries reuse the standard artifact check without changing the ordinary archive guard', async () => { + const mobileCondition = '${{ if eq(parameters.VSCODE_BUILD_WEB_MOBILE, true) }}'; + type Step = { script?: string; env?: { SYSTEM_ACCESSTOKEN?: string }; [mobileCondition]?: Step[] }; + const source = await readFile(new URL('../../azure-pipelines/web/product-build-web.yml', import.meta.url), 'utf8'); + const pipeline = load(source) as { + jobs: { + templateContext: { + outputs: { artifactName?: string; condition?: string; [mobileCondition]?: { artifactName: string; condition: string }[] }[]; + }; + steps: Step[]; + }[]; + }; + const job = pipeline.jobs[0]; + const mobileSteps = job.steps.flatMap(step => step[mobileCondition] ?? []); + const mobileCheck = mobileSteps.find(step => step.script?.includes('common/checkForArtifact.ts')); + const ordinaryCheck = job.steps.find(step => step.script?.includes('common/checkForArtifact.ts')); + assert.deepStrictEqual({ + outputs: job.templateContext.outputs.flatMap(output => output[mobileCondition] ?? []) + .map(({ artifactName, condition }) => ({ artifactName, condition })), + mobileCheck: mobileCheck?.script?.trim().split(/\s+/), + token: mobileCheck?.env?.SYSTEM_ACCESSTOKEN, + ordinaryCheck: ordinaryCheck?.script?.trim().split(/\s+/), + ordinaryCondition: job.templateContext.outputs.find(output => output.artifactName === 'vscode_web_linux_standalone_archive-unsigned')?.condition, + }, { + outputs: [{ + artifactName: 'vscode_web_linux_mobile_archive-unsigned', + condition: 'and(succeeded(), ne(variables[\'WEB_MOBILE_ARCHIVE_PUBLISHED\'], \'true\'))', + }], + mobileCheck: ['node', 'build/azure-pipelines/common/checkForArtifact.ts', 'WEB_MOBILE_ARCHIVE_PUBLISHED', 'vscode_web_linux_mobile_archive-unsigned'], + token: '$(System.AccessToken)', + ordinaryCheck: ['node', 'build/azure-pipelines/common/checkForArtifact.ts', 'WEB_ARCHIVE_PUBLISHED', 'vscode_web_linux_standalone_archive-unsigned'], + ordinaryCondition: 'and(succeeded(), ne(variables[\'WEB_ARCHIVE_PUBLISHED\'], \'true\'))', + }); +}); diff --git a/build/lib/test/nodeCompileCache.test.ts b/build/lib/test/nodeCompileCache.test.ts new file mode 100644 index 000000000000..31ee8c74eeae --- /dev/null +++ b/build/lib/test/nodeCompileCache.test.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { afterEach, beforeEach, suite, test } from 'node:test'; +import { validateNodeCompileCache } from '../nodeCompileCache.ts'; + +const kinds = ['main', 'extension-host', 'shared-process', 'pty-host', 'agent-host']; +const tag = `v24.22.1-${process.arch}-7034790f`; + +suite('validateNodeCompileCache', () => { + let root: string; + + beforeEach(async () => { + root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'node-compile-cache-test-')); + for (const kind of kinds) { + const cacheDirectory = path.join(root, kind, tag); + await fs.promises.mkdir(cacheDirectory, { recursive: true }); + await fs.promises.writeFile(path.join(root, kind, '.ready'), ''); + await fs.promises.writeFile(path.join(cacheDirectory, '6664eb6b'), 'entry'); + } + }); + + afterEach(async () => { + await fs.promises.rm(root, { recursive: true, force: true }); + }); + + test('removes temporary files a process left mid-write when it was stopped', async () => { + // Node writes each entry to `.XXXXXX` (uv_fs_mkstemp) and renames it into place. + const leftover = path.join(root, 'shared-process', tag, '6664eb6b.cqknyl'); + await fs.promises.writeFile(leftover, 'partial'); + + const count = await validateNodeCompileCache(root, process.arch); + + assert.deepStrictEqual({ count, leftoverExists: fs.existsSync(leftover), entry: fs.existsSync(path.join(root, 'shared-process', tag, '6664eb6b')) }, { count: kinds.length, leftoverExists: false, entry: true }); + }); + + test('still rejects other unexpected cache entries', async () => { + await fs.promises.writeFile(path.join(root, 'shared-process', tag, 'unexpected.txt'), ''); + + await assert.rejects(validateNodeCompileCache(root, process.arch), /unexpected shared-process cache entries in .*: unexpected\.txt\./); + }); +}); diff --git a/build/lib/test/nodeModulesCacheKeys.test.ts b/build/lib/test/nodeModulesCacheKeys.test.ts index 55970d6926c2..2b3cd5aca580 100644 --- a/build/lib/test/nodeModulesCacheKeys.test.ts +++ b/build/lib/test/nodeModulesCacheKeys.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import { suite, test } from 'node:test'; -import { computeNodeModulesBaseCacheKey, computeNodeModulesCacheKey, type ReadRepositoryFile } from '../../azure-pipelines/common/cacheKeys.ts'; +import { computeNodeModulesBaseCacheKey, computeNodeModulesCacheKey, computePnpmStoreBaseCacheKey, computePnpmStoreCacheKey, type ReadRepositoryFile } from '../../azure-pipelines/common/cacheKeys.ts'; /** Reads the given repository files, every other `package.json` as one that only pins pnpm, and other files as empty. */ function reader(files: Record = {}): ReadRepositoryFile { @@ -43,4 +43,27 @@ suite('node_modules cache keys', () => { platform: { base: true, key: true }, }); }); + + test('a pnpm store can start from the store of other lockfiles, but not of another pnpm version or platform', () => { + const args = ['linux', 'x64']; + const base = computePnpmStoreBaseCacheKey(args, reader()); + const key = computePnpmStoreCacheKey(reader()); + const changes = (files: Record, changedArgs = args) => ({ + base: computePnpmStoreBaseCacheKey(changedArgs, reader(files)) !== base, + key: computePnpmStoreCacheKey(reader(files)) !== key, + }); + assert.deepStrictEqual({ + lockfile: changes({ 'extensions/pnpm-lock.yaml': 'lockfileVersion: \'9.0\'' }), + nativeBuildHooks: changes({ '.pnpmfile.mjs': 'export const hooks = {};' }), + salt: changes({ 'build/.cachesalt': 'salt' }), + pnpmVersion: changes({ 'package.json': '{"packageManager":"pnpm@13.0.0"}' }), + platform: changes({}, ['win32', 'x64']), + }, { + lockfile: { base: false, key: true }, + nativeBuildHooks: { base: false, key: false }, + salt: { base: true, key: false }, + pnpmVersion: { base: true, key: false }, + platform: { base: true, key: false }, + }); + }); }); diff --git a/build/lib/test/npmPackage.test.ts b/build/lib/test/npmPackage.test.ts index 0d6dc308fd2c..a9774c9c99ba 100644 --- a/build/lib/test/npmPackage.test.ts +++ b/build/lib/test/npmPackage.test.ts @@ -280,4 +280,22 @@ suite('npmPackage', () => { }); }); } + + test('ensureNpmPackage links the installed version from pnpm\'s virtual store', t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'vscode-npm-package-test-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const nodeModulesRoot = path.join(root, 'node_modules'); + writePnpmLockfile(path.join(root, 'pnpm-lock.yaml'), { [packageName]: { version, integrity: 'sha512-unused' } }); + // With the isolated linker, a package that isn't a direct dependency is only in the store, and + // linked from its hoisting folder. + const installed = path.join(nodeModulesRoot, '.pnpm', `@github+copilot-darwin-arm64@${version}`, 'node_modules', ...packageName.split('/')); + fs.mkdirSync(installed, { recursive: true }); + fs.writeFileSync(path.join(installed, 'package.json'), JSON.stringify({ version })); + fs.mkdirSync(path.join(nodeModulesRoot, '.pnpm', 'node_modules', '@github'), { recursive: true }); + fs.symlinkSync(installed, path.join(nodeModulesRoot, '.pnpm', 'node_modules', ...packageName.split('/')), 'junction'); + + ensureNpmPackage(packageName, nodeModulesRoot, { packPackage: () => { throw new Error('The installed version must not be downloaded.'); } }); + + assert.strictEqual(fs.realpathSync(path.join(nodeModulesRoot, ...packageName.split('/'))), fs.realpathSync(installed)); + }); }); diff --git a/build/lib/test/oxlint.test.ts b/build/lib/test/oxlint.test.ts new file mode 100644 index 000000000000..2c9223ff83a6 --- /dev/null +++ b/build/lib/test/oxlint.test.ts @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { suite, test } from 'node:test'; +import { splitByFolder, splitFiles, toEslintRuleId } from '../../oxlint.ts'; + +suite('oxlint', () => { + + test('reports rules by their ESLint names', () => { + assert.deepStrictEqual( + ['eslint(no-var)', 'typescript(no-explicit-any)', 'local(code-layering)', '@stylistic(semi)', undefined].map(toEslintRuleId), + ['no-var', '@typescript-eslint/no-explicit-any', 'local/code-layering', '@stylistic/semi', undefined] + ); + }); + + test('passes folders whole unless they contain excluded files, and balances the groups', () => { + const files = [ + { path: 'src/a/1.ts', weight: 1 }, + { path: 'src/a/2.ts', weight: 1 }, + { path: 'src/b/1.ts', weight: 1 }, + { path: 'extensions/x/1.ts', weight: 1 }, + { path: 'root.ts', weight: 4 }, + ]; + + assert.deepStrictEqual([ + splitByFolder(files, 1, []), + splitByFolder(files, 1, ['extensions/z/']), + splitByFolder(files, 2, []), + ], [ + [['extensions', 'root.ts', 'src/a', 'src/b']], + [['extensions/x', 'root.ts', 'src/a', 'src/b']], + [['root.ts'], ['extensions', 'src/a/1.ts', 'src/a/2.ts', 'src/b']], + ]); + }); + + test('splits file lists to keep command lines short', () => { + assert.deepStrictEqual(splitFiles(['a.ts', 'b.ts', 'c.ts', 'd.ts'], 1, 10), [['a.ts', 'c.ts'], ['b.ts', 'd.ts']]); + }); + + test('keeps every group within the limit for alternating long and short paths', () => { + const files = Array.from({ length: 8 }, (_, index) => `${index}`.padEnd(index % 2 === 0 ? 18 : 5, 'x')); + const maxLength = 30; + const groups = splitFiles(files, 4, maxLength); + + assert.deepStrictEqual({ + withinLimit: groups.every(group => group.join(' ').length + 1 <= maxLength), + files: groups.flat().sort(), + }, { + withinLimit: true, + files: files.slice().sort(), + }); + }); +}); diff --git a/build/lib/test/oxlintConfig.test.ts b/build/lib/test/oxlintConfig.test.ts new file mode 100644 index 000000000000..335e22dc65af --- /dev/null +++ b/build/lib/test/oxlintConfig.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 'assert'; +import type { Linter } from 'eslint'; +import { suite, test } from 'node:test'; +import path from 'path'; +import { pathToFileURL } from 'url'; +import { oxlintJsPlugins, toOxlintConfig } from '../oxlintConfig.ts'; + +suite('oxlintConfig', () => { + + test('converts ignores, file patterns and rules, and loads the plugins that the rules use', () => { + const config = toOxlintConfig([ + { ignores: ['**/out/**'] }, + { languageOptions: { sourceType: 'module' } }, + { rules: { 'curly': 'warn', 'header/header': [2, 'block'] } }, + { files: ['src/**/*.ts'], ignores: ['**/*.test.ts'], rules: { '@typescript-eslint/no-explicit-any': 'warn', 'local/code-layering': 'off' } }, + ]); + + assert.deepStrictEqual(config, { + plugins: ['eslint', 'typescript'], + categories: { correctness: 'off' }, + options: { reportUnusedDisableDirectives: 'warn' }, + ignorePatterns: ['**/out/**'], + jsPlugins: [ + { name: 'header', specifier: oxlintJsPlugins.header }, + { name: 'local', specifier: oxlintJsPlugins.local }, + ], + overrides: [ + { files: ['**/*'], rules: { 'curly': 'warn', 'header/header': [2, 'block'] } }, + { files: ['src/**/*.ts'], excludeFiles: ['**/*.test.ts'], rules: { '@typescript-eslint/no-explicit-any': 'warn', 'local/code-layering': 'off' } }, + ], + }); + }); + + test('fails for rules of a plugin that oxlint cannot load', () => { + assert.throws(() => toOxlintConfig([{ rules: { 'import/no-cycle': 'warn' } }]), /import\/no-cycle/); + }); + + test('converts the configuration of the repository', async () => { + const root = path.join(import.meta.dirname, '..', '..', '..'); + const { default: eslintConfig } = await import(pathToFileURL(path.join(root, 'eslint.config.js')).href) as { default: Linter.Config[] }; + + assert.doesNotThrow(() => toOxlintConfig(eslintConfig)); + }); +}); diff --git a/build/lib/test/pnpmHoist.test.ts b/build/lib/test/pnpmHoist.test.ts new file mode 100644 index 000000000000..86f4a5f18a49 --- /dev/null +++ b/build/lib/test/pnpmHoist.test.ts @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { suite, test } from 'node:test'; +import { getHoistedLocations } from '../pnpmHoist.ts'; +import { parsePnpmLockfile } from '../pnpmLock.ts'; + +suite('pnpmHoist', () => { + + test('places packages the way pnpm\'s hoisted linker does', () => { + // - `a` and `b` need different versions of `c`: the version that more packages use is hoisted. + // - `loader` has a peer on `webpack`, which depends on it: it moves next to `webpack`, not to the root. + // - `webpack` and `webpack-cli` are each other's peers: they stay in the project that declares them. + // - `optional` was skipped (`skipped` in node_modules/.modules.yaml). + const lockfile = parsePnpmLockfile(`lockfileVersion: '9.0' +importers: + .: + dependencies: + a: + specifier: 1.0.0 + version: 1.0.0 + b: + specifier: 1.0.0 + version: 1.0.0 + d: + specifier: 1.0.0 + version: 1.0.0 + tools: + devDependencies: + webpack: + specifier: 5.0.0 + version: 5.0.0(webpack-cli@5.0.0) + webpack-cli: + specifier: 5.0.0 + version: 5.0.0(webpack@5.0.0) +packages: + a@1.0.0: + resolution: {integrity: sha512-a} + b@1.0.0: + resolution: {integrity: sha512-b} + c@1.0.0: + resolution: {integrity: sha512-c1} + c@2.0.0: + resolution: {integrity: sha512-c2} + d@1.0.0: + resolution: {integrity: sha512-d} + loader@1.0.0: + resolution: {integrity: sha512-loader} + peerDependencies: + webpack: ^5.0.0 + optional@1.0.0: + resolution: {integrity: sha512-optional} + webpack@5.0.0: + resolution: {integrity: sha512-webpack} + peerDependencies: + webpack-cli: '*' + webpack-cli@5.0.0: + resolution: {integrity: sha512-webpack-cli} + peerDependencies: + webpack: '*' +snapshots: + a@1.0.0: + dependencies: + c: 1.0.0 + b@1.0.0: + dependencies: + c: 2.0.0 + c@1.0.0: {} + c@2.0.0: {} + d@1.0.0: + dependencies: + c: 2.0.0 + optionalDependencies: + optional: 1.0.0 + loader@1.0.0(webpack@5.0.0(webpack-cli@5.0.0)): + dependencies: + webpack: 5.0.0(webpack-cli@5.0.0) + optional@1.0.0: {} + webpack@5.0.0(webpack-cli@5.0.0): + dependencies: + loader: 1.0.0(webpack@5.0.0(webpack-cli@5.0.0)) + webpack-cli: 5.0.0(webpack@5.0.0) + webpack-cli@5.0.0(webpack@5.0.0): + dependencies: + webpack: 5.0.0(webpack-cli@5.0.0) +`); + + assert.deepStrictEqual(Object.fromEntries(getHoistedLocations(lockfile, new Set(['optional@1.0.0']))), { + 'a@1.0.0': ['node_modules/a'], + 'b@1.0.0': ['node_modules/b'], + 'c@1.0.0': ['node_modules/a/node_modules/c'], + 'c@2.0.0': ['node_modules/c'], + 'd@1.0.0': ['node_modules/d'], + 'webpack@5.0.0(webpack-cli@5.0.0)': ['tools/node_modules/webpack'], + 'loader@1.0.0(webpack@5.0.0(webpack-cli@5.0.0))': ['tools/node_modules/loader'], + 'webpack-cli@5.0.0(webpack@5.0.0)': ['tools/node_modules/webpack-cli'], + }); + }); + + test('keeps a package next to the nearest ancestor that provides its peer', () => { + // `plugin` has a peer on `peer`, provided by `host` (2.0.0) through `mid`, which doesn't + // depend on it. The root has `peer` 1.0.0, so `plugin` can't move to the root. + const lockfile = parsePnpmLockfile(`lockfileVersion: '9.0' +importers: + .: + dependencies: + host: + specifier: 1.0.0 + version: 1.0.0 + mid: + specifier: 0.1.0 + version: 0.1.0 + peer: + specifier: 1.0.0 + version: 1.0.0 +packages: + host@1.0.0: + resolution: {integrity: sha512-host} + mid@0.1.0: + resolution: {integrity: sha512-mid0} + mid@1.0.0: + resolution: {integrity: sha512-mid1} + peer@1.0.0: + resolution: {integrity: sha512-peer1} + peer@2.0.0: + resolution: {integrity: sha512-peer2} + plugin@1.0.0: + resolution: {integrity: sha512-plugin} + peerDependencies: + peer: '*' +snapshots: + host@1.0.0: + dependencies: + mid: 1.0.0 + peer: 2.0.0 + mid@0.1.0: {} + mid@1.0.0: + dependencies: + plugin: 1.0.0(peer@2.0.0) + peer@1.0.0: {} + peer@2.0.0: {} + plugin@1.0.0(peer@2.0.0): + dependencies: + peer: 2.0.0 +`); + + assert.deepStrictEqual(Object.fromEntries(getHoistedLocations(lockfile, new Set())), { + 'host@1.0.0': ['node_modules/host'], + 'mid@1.0.0': ['node_modules/host/node_modules/mid'], + 'plugin@1.0.0(peer@2.0.0)': ['node_modules/host/node_modules/plugin'], + 'peer@2.0.0': ['node_modules/host/node_modules/peer'], + 'mid@0.1.0': ['node_modules/mid'], + 'peer@1.0.0': ['node_modules/peer'], + }); + }); +}); diff --git a/build/lib/test/publishGate.test.ts b/build/lib/test/publishGate.test.ts new file mode 100644 index 000000000000..2f9e06f6bd41 --- /dev/null +++ b/build/lib/test/publishGate.test.ts @@ -0,0 +1,86 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { suite, test } from 'node:test'; +import { artifactsByGatingJob, getGatingJob, type TimelineRecord } from '../../azure-pipelines/common/publishGate.ts'; + +function phase(identifier: string, state: string, result: string | null = null): TimelineRecord { + return { type: 'Phase', identifier, name: identifier.split('.').pop()!, state, result }; +} + +function job(identifier: string, state: string, result: string | null = null): TimelineRecord { + return { type: 'Job', identifier: `${identifier}.__default`, name: identifier.split('.').pop()!, state, result }; +} + +const linuxTests = ['Unit', 'UnitElectron', 'Integration', 'BrowserRemote', 'Smoke', 'AgentHostE2E'].map(name => `LinuxX64.Linux_x64_Test_${name}`); + +function gate(records: TimelineRecord[], artifact = 'vscode_cli_linux_x64_cli') { + return getGatingJob({ records }, artifact); +} + +suite('Publish gate', () => { + test('artifacts without a gating job are not gated', () => { + assert.strictEqual(gate([phase('LinuxX64.Linux_x64_Test_Unit', 'pending')], 'vscode_cli_alpine_x64_cli'), undefined); + }); + + test('an artifact is not gated when its tests are not part of the run', () => { + assert.deepStrictEqual(gate([ + phase('LinuxX64.LinuxCLI_x64', 'completed', 'succeeded'), + job('LinuxX64.LinuxCLI_x64', 'completed', 'succeeded'), + phase('LinuxX64.Linux_x64_Compile', 'inProgress'), + ]), { name: 'Linux_x64_Test', state: 'missing' }); + }); + + test('waits for tests that are not scheduled yet', () => { + // The CLI job finishes long before the tests, which wait for the compile job and have no job records yet + assert.deepStrictEqual(gate([ + phase('LinuxX64.LinuxCLI_x64', 'completed', 'succeeded'), + job('LinuxX64.LinuxCLI_x64', 'completed', 'succeeded'), + phase('LinuxX64.Linux_x64_Compile', 'inProgress'), + job('LinuxX64.Linux_x64_Compile', 'inProgress'), + ...linuxTests.map(id => phase(id, 'pending')), + ]), { name: 'Linux_x64_Test_Unit', state: 'pending' }); + }); + + test('waits for tests that a stage retry reset, even though an earlier attempt has job records', () => { + // Build 494123: the Linux stage was retried, and the compile job published the artifacts again before the tests ran + assert.deepStrictEqual(gate([ + phase('LinuxX64.Linux_x64_Compile', 'completed', 'succeeded'), + ...linuxTests.map(id => phase(id, 'pending')), + ...linuxTests.map(id => job(id, 'completed', id.endsWith('_Unit') ? 'failed' : 'succeeded')), + ], 'vscode_client_linux_x64_archive-unsigned'), { name: 'Linux_x64_Test_Unit', state: 'pending' }); + }); + + test('blocks when any shard failed, was canceled or was skipped', () => { + for (const result of ['failed', 'canceled', 'skipped', 'abandoned']) { + assert.deepStrictEqual(gate([ + ...linuxTests.map(id => phase(id, 'completed', id.endsWith('_Smoke') ? result : 'succeeded')), + phase('LinuxX64.Linux_x64_Test_Unit', 'inProgress'), + ]), { name: 'Linux_x64_Test_Smoke', state: 'failed' }, result); + } + }); + + test('passes once every shard succeeded', () => { + assert.deepStrictEqual(gate(linuxTests.map(id => phase(id, 'completed', id.endsWith('_Smoke') ? 'succeededWithIssues' : 'succeeded'))), { + name: linuxTests.map(id => id.split('.').pop()).join(', '), + state: 'succeeded', + }); + }); + + test('only matches the gating job of the artifact\'s platform', () => { + assert.deepStrictEqual(gate([ + phase('LinuxARM64.Linux_arm64_Test_Unit', 'completed', 'failed'), + phase('Windows.Windows_x64_Test_Unit', 'completed', 'failed'), + phase('LinuxX64.Linux_x64_Tests', 'completed', 'failed'), + phase('LinuxX64.Linux_x64_Test_Unit', 'completed', 'succeeded'), + ]), { name: 'Linux_x64_Test_Unit', state: 'succeeded' }); + }); + + test('every gated artifact belongs to exactly one gating job', () => { + const artifacts = Object.values(artifactsByGatingJob).flat(); + assert.strictEqual(new Set(artifacts).size, artifacts.length); + }); +}); diff --git a/build/lib/test/sessionsPresentationDependencies.test.ts b/build/lib/test/sessionsPresentationDependencies.test.ts new file mode 100644 index 000000000000..4074728553de --- /dev/null +++ b/build/lib/test/sessionsPresentationDependencies.test.ts @@ -0,0 +1,349 @@ +/*--------------------------------------------------------------------------------------------- + * 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 fs from 'fs'; +import path from 'path'; +import { suite, test } from 'node:test'; +import ts from 'typescript'; +import { getResourcePaths } from '../../next/resources.ts'; + +const repositoryRoot = path.resolve(import.meta.dirname, '../../..'); +const hostPickerRoot = 'src/vs/sessions/contrib/providers/remoteAgentHost/browser/'; +const sharedHostPickerRoot = 'src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/'; +const originalPicker = [ + 'hostFilterActionViewItem.ts', + 'mobileHostFilterActionViewItem.ts', + 'media/hostFilter.css', + 'media/hostPickerSheet.css', +].map(file => sharedHostPickerRoot + file).concat(hostPickerRoot + 'hostFilter.contribution.ts'); +const experimentalPicker = [ + 'mobileHostFilter.contribution.ts', + 'mobileHostDrawerHeaderViewItem.ts', + 'mobileHostPlaceChipViewItem.ts', + 'mobileHostPickerSheet.ts', + 'media/hostDrawerHeader.css', + 'media/hostPlaceChip.css', + 'media/mobileHostPickerSheet.css', +].map(file => hostPickerRoot + file); +const dependenciesByFile = new Map(); +const composerRoot = 'src/vs/sessions/contrib/providers/agentHost/browser/mobile/'; +const originalConfigurationPresenter = 'src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts'; +const mobileConfigurationPresenter = composerRoot + 'mobileChatPhoneInputPresenter.ts'; +const mobileInputButton = composerRoot + 'mobileChatInputActionViewItem.ts'; +const defaultRepositoryPicker = 'src/vs/workbench/contrib/sessions/browser/defaultSessionRepositoryPicker.ts'; +const mobileRepositoryPicker = 'src/vs/sessions/contrib/mobile/browser/mobileRepositoryPicker.ts'; +const defaultChatPresentation = 'src/vs/workbench/contrib/chat/browser/chatDefaultPresentation.contribution.ts'; +const defaultEditPresentation = 'src/vs/workbench/contrib/chat/browser/widget/chatContentParts/defaultChatEditPresentation.ts'; +const defaultListPresentation = 'src/vs/workbench/contrib/sessions/browser/defaultSessionsListPresentation.ts'; +const mobilePresentationRoot = 'src/vs/sessions/contrib/mobile/browser/'; +const defaultSessionsRegistrations = 'src/vs/sessions/services/sessions/browser/sessionsServices.registration.ts'; +const coreSessionsRegistrations = 'src/vs/sessions/services/sessions/browser/sessionsCoreServices.registration.ts'; +const chatBackgroundPresentation = [ + 'src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts', + 'src/vs/sessions/contrib/chat/browser/chatBackgroundTint.ts', + 'src/vs/sessions/contrib/chat/browser/getThemeColorsTool.ts', + 'src/vs/workbench/contrib/sessions/browser/chat/defaultChatViewFactory.ts', + 'src/vs/workbench/contrib/sessions/browser/chatBackgroundService.ts', + 'src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts', + 'src/vs/workbench/contrib/sessions/browser/sessionsChatSurface.ts', + 'src/vs/workbench/contrib/sessions/browser/media/chatBackground.css', +]; + +suite('Sessions presentation entry isolation', () => { + for (const { entry, expected, configurationPresenter } of [ + { entry: 'src/vs/sessions/sessions.web.main.ts', expected: originalPicker, configurationPresenter: originalConfigurationPresenter }, + { entry: 'src/vs/sessions/agents.web.mobile.main.ts', expected: experimentalPicker, configurationPresenter: mobileConfigurationPresenter }, + ]) { + test(`${entry} reaches only its own host picker implementation and styles`, () => { + const dependencies = collectSourceDependencies(entry); + assert.deepStrictEqual([...originalPicker, ...experimentalPicker] + .filter(file => dependencies.has(file)).sort(), [...expected].sort()); + }); + + test(`${entry} reaches only its own Configure Session presenter`, () => { + const dependencies = collectSourceDependencies(entry); + assert.deepStrictEqual([originalConfigurationPresenter, mobileConfigurationPresenter] + .filter(file => dependencies.has(file)), [configurationPresenter]); + }); + + test(`${entry} registers only its own session repository picker implementation`, () => { + const mobile = entry.includes('.mobile.'); + const dependencies = collectSourceDependencies(entry); + const registrations = getSingletonRegistrations(mobile ? 'src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts' : defaultSessionsRegistrations); + assert.deepStrictEqual({ + implementations: [defaultRepositoryPicker, mobileRepositoryPicker].filter(file => dependencies.has(file)), + registration: registrations.find(([service]) => service === 'ISessionRepositoryPicker'), + }, { + implementations: [mobile ? mobileRepositoryPicker : defaultRepositoryPicker], + registration: ['ISessionRepositoryPicker', mobile ? 'MobileRepositoryPicker' : 'DefaultSessionRepositoryPicker'], + }); + }); + + test(`${entry} registers the shared GitHub and comparison services required by its views`, () => { + const dependencies = collectSourceDependencies(entry); + const services = [ + 'src/vs/workbench/services/github/browser/githubService.ts', + 'src/vs/workbench/contrib/sessions/browser/sessionComparisonService.ts', + ]; + assert.deepStrictEqual(services.filter(file => dependencies.has(file)), services); + }); + + test(`${entry} registers shared session and host services without relying on implementation side effects`, () => { + const dependencies = collectSourceDependencies(entry); + const registrations = dependencies.has(coreSessionsRegistrations) ? getSingletonRegistrations(coreSessionsRegistrations) : []; + const required = [ + ['ISessionsProvidersService', 'SessionsProvidersService'], + ['ISessionsService', 'SessionsService'], + ['ISessionsManagementService', 'SessionsManagementService'], + ['ISessionHostService', 'SessionHostService'], + ['IFocusedSessionHostService', 'FocusedSessionHostService'], + ]; + assert.deepStrictEqual(required.map(([id]) => registrations.find(([service]) => service === id)), required); + }); + + test(`${entry} shares skills while selecting chat backgrounds only for the regular workbench`, () => { + const mobile = entry.includes('.mobile.'); + const dependencies = collectSourceDependencies(entry); + const registrations = [ + 'src/vs/sessions/contrib/chat/browser/chat.contribution.ts', + 'src/vs/sessions/contrib/chat/browser/chat.desktop.contribution.ts', + 'src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts', + mobilePresentationRoot + 'mobile.contribution.ts', + ].filter(file => dependencies.has(file)).flatMap(getSingletonRegistrations); + assert.deepStrictEqual({ + backgroundModules: chatBackgroundPresentation.filter(file => dependencies.has(file)), + factory: registrations.filter(([id]) => id === 'IChatViewFactory'), + backgroundService: registrations.filter(([id]) => id === 'ISessionsChatBackgroundService'), + promptsService: registrations.filter(([id]) => id === 'IPromptsService'), + }, { + backgroundModules: mobile ? [] : chatBackgroundPresentation, + factory: [['IChatViewFactory', mobile ? 'MobileChatViewFactory' : 'DefaultChatViewFactory']], + backgroundService: mobile ? [] : [['ISessionsChatBackgroundService', 'SessionsChatBackgroundService']], + promptsService: [['IPromptsService', 'AgenticPromptsService']], + }); + }); + + test(`${entry} supplies required window services without loading desktop presentation on mobile`, () => { + const mobile = entry.includes('.mobile.'); + const dependencies = collectSourceDependencies(entry); + const modules = mobile ? [mobilePresentationRoot + 'mobile.contribution.ts'] : [ + 'src/vs/sessions/contrib/canvases/browser/windowCanvases.contribution.ts', + 'src/vs/sessions/contrib/canvases/browser/pinnedCanvases.contribution.ts', + 'src/vs/workbench/contrib/chatWindow/browser/chatWindow.contribution.ts', + ]; + const registrations = modules.filter(file => dependencies.has(file)).flatMap(getSingletonRegistrations); + const desktopPresentation = [ + 'src/vs/sessions/contrib/canvases/browser/windowCanvasEditor.ts', + 'src/vs/sessions/contrib/canvases/browser/pinnedCanvasService.ts', + 'src/vs/workbench/contrib/chatWindow/browser/chatWindowService.ts', + 'src/vs/workbench/contrib/chatWindow/browser/media/chatWindow.css', + ]; + assert.deepStrictEqual({ + canvas: registrations.find(([id]) => id === 'IWindowCanvasService'), + pinnedCanvas: registrations.find(([id]) => id === 'IPinnedCanvasService'), + chatWindow: registrations.find(([id]) => id === 'IChatWindowService'), + presentation: desktopPresentation.filter(file => dependencies.has(file)), + }, { + canvas: ['IWindowCanvasService', 'WindowCanvasService'], + pinnedCanvas: ['IPinnedCanvasService', mobile ? 'MobileNullPinnedCanvasService' : 'PinnedCanvasService'], + chatWindow: ['IChatWindowService', mobile ? 'MobileNullChatWindowService' : 'ChatWindowService'], + presentation: mobile ? [] : desktopPresentation, + }); + }); + + test(`${entry} supplies layout and chat-input services without desktop features on mobile`, () => { + const mobile = entry.includes('.mobile.'); + const dependencies = collectSourceDependencies(entry); + const registrations = [ + 'src/vs/sessions/contrib/layout/browser/sessions.layout.contribution.ts', + 'src/vs/sessions/contrib/layout/browser/sessions.mobile.layout.contribution.ts', + 'src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.contribution.ts', + 'src/vs/sessions/contrib/worktreeSuggestion/browser/worktreeSuggestion.contribution.ts', + mobilePresentationRoot + 'mobile.contribution.ts', + ].filter(file => dependencies.has(file)).flatMap(getSingletonRegistrations); + assert.deepStrictEqual({ + workingSet: registrations.filter(([id]) => id === 'ISessionEditorWorkingSetService'), + screenshot: registrations.filter(([id]) => id === 'IScreenshotToolService'), + worktreeSuggestion: registrations.filter(([id]) => id === 'IWorktreeSuggestionService'), + desktopLayout: dependencies.has('src/vs/sessions/contrib/layout/browser/desktopLayoutController.ts'), + desktopScreenshot: dependencies.has('src/vs/workbench/contrib/screenshotTool/browser/screenshotToolService.ts'), + worktreeContribution: dependencies.has('src/vs/sessions/contrib/worktreeSuggestion/browser/worktreeSuggestion.contribution.ts'), + }, { + workingSet: [['ISessionEditorWorkingSetService', 'SessionEditorWorkingSetService']], + screenshot: [['IScreenshotToolService', mobile ? 'MobileNullScreenshotToolService' : 'ScreenshotToolService']], + worktreeSuggestion: [['IWorktreeSuggestionService', mobile ? 'MobileNullWorktreeSuggestionService' : 'WorktreeSuggestionService']], + desktopLayout: !mobile, + desktopScreenshot: !mobile, + worktreeContribution: !mobile, + }); + }); + + test(`${entry} selects edit, list, clipboard and chat-view presentation without importing the other entry`, () => { + const mobile = entry.includes('.mobile.'); + const dependencies = collectSourceDependencies(entry); + const normal = [defaultChatPresentation, defaultEditPresentation, defaultListPresentation]; + const experimental = ['mobileChatEditPresenter.ts', 'mobileSessionsListPresentation.ts', 'mobileClipboardImageContext.ts', 'mobileChatViewFactory.ts'].map(file => mobilePresentationRoot + file); + const registrations = [ + ...getSingletonRegistrations(mobile ? mobilePresentationRoot + 'mobile.contribution.ts' : defaultChatPresentation), + ...getSingletonRegistrations(mobile ? mobilePresentationRoot + 'mobile.contribution.ts' : defaultSessionsRegistrations), + ]; + assert.deepStrictEqual({ + files: [...normal, ...experimental].filter(file => dependencies.has(file)), + edit: registrations.find(([id]) => id === 'IChatEditPresentationService'), + list: registrations.find(([id]) => id === 'ISessionsListPresentation'), + }, { + files: mobile ? experimental : normal, + edit: ['IChatEditPresentationService', mobile ? 'MobileChatEditPresenter' : 'DefaultChatEditPresentationService'], + list: ['ISessionsListPresentation', mobile ? 'MobileSessionsListPresentation' : 'DefaultSessionsListPresentation'], + }); + }); + + test(`${entry} loads policy-continuation and shared composer contributions`, () => { + const dependencies = collectSourceDependencies(entry); + const contributions = [ + 'src/vs/sessions/contrib/providers/agentHost/browser/agentHostPolicyContinuationPresenter.contribution.ts', + 'src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts', + 'src/vs/sessions/browser/parts/sessionsPartContent.registration.ts', + 'src/vs/sessions/contrib/providers/agentHost/browser/agentHostSessionConfigPicker.contribution.ts', + 'src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.contribution.ts', + ]; + assert.deepStrictEqual(contributions.filter(file => dependencies.has(file)), contributions); + }); + + test(`${entry} keeps clipboard registration outside the restore-blocking phase`, () => { + const file = entry.includes('.mobile.') + ? mobilePresentationRoot + 'mobileClipboardImageContext.ts' + : defaultChatPresentation; + assert.match(fs.readFileSync(path.join(repositoryRoot, file), 'utf8'), + /registerWorkbenchContribution2\('chat\.(?:mobileClipboardImageContext|clipboardImageContext)', \w+, WorkbenchPhase\.AfterRestored\);/); + }); + + test(`${entry} includes redesigned input and edit rendering only for the mobile entry`, () => { + const dependencies = collectSourceDependencies(entry); + const mobile = entry.includes('.mobile.'); + const implementations = [ + mobileInputButton, + 'src/vs/sessions/contrib/mobile/browser/mobileChatEditRow.ts', + 'src/vs/sessions/contrib/mobile/browser/mobileSessionsListPresentation.ts', + hostPickerRoot + 'mobileAgentHostFilterService.ts', + ]; + assert.deepStrictEqual(implementations.map(file => dependencies.has(file)), implementations.map(() => mobile)); + }); + } + + test('mobile embedder and mock bootstrap share the Agents mobile entry', () => { + const entries = [ + 'src/vs/sessions/agents.web.mobile.main.internal.ts', + 'src/vs/sessions/test/agents.web.mobile.test.internal.ts', + ]; + assert.deepStrictEqual(entries.filter(entry => collectSourceDependencies(entry) + .has('src/vs/sessions/agents.web.mobile.main.ts')), entries); + }); + + test('mobile core registers the artifact and MCP OAuth services required by shared customers', () => { + const registrations = getSingletonRegistrations('src/vs/sessions/sessions.core.main.ts'); + const required = [ + ['IArtifactIntegrationRegistry', 'ArtifactIntegrationRegistry'], + ['IAgentHostMcpOAuthMetadataService', 'AgentHostMcpOAuthMetadataService'], + ]; + assert.deepStrictEqual(required.map(([id]) => registrations.find(([service]) => service === id)), required); + }); + + for (const entry of [ + 'src/vs/sessions/sessions.web.main.internal.ts', + 'src/vs/sessions/sessions.desktop.main.ts', + 'src/vs/workbench/workbench.web.main.internal.ts', + 'src/vs/workbench/workbench.desktop.main.ts', + ]) { + test(`${entry} excludes dedicated mobile UI, CSS and defaults`, () => { + const dependencies = collectSourceDependencies(entry); + const unexpected = [...dependencies].filter(isMobileEntryFile); + assert.deepStrictEqual(unexpected, []); + }); + } + + for (const target of ['web', 'desktop', 'server-web'] as const) { + test(`${target} production resource copying excludes dedicated mobile assets`, async () => { + const resources = await getResourcePaths(path.join(repositoryRoot, 'src'), target); + assert.deepStrictEqual(resources.map(file => `src/${file}`).filter(isMobileEntryFile), []); + }); + } + + test('background assets stay in regular workbenches and out of the mobile package', async () => { + const backgrounds = ['koi-dark-static.webp', 'koi-dark.webp', 'koi-light-static.webp', 'koi-light.webp'] + .map(file => `vs/sessions/services/chatBackground/browser/media/${file}`); + const resources = await Promise.all((['web', 'desktop', 'server-web', 'mobile'] as const).map(target => + getResourcePaths(path.join(repositoryRoot, 'src'), target))); + assert.deepStrictEqual(resources.map(files => files.filter(file => backgrounds.includes(file))), [ + backgrounds, backgrounds, backgrounds, [], + ]); + }); + + test('full chat imports retain the original script-widget CSS precedence', () => { + const source = fs.readFileSync(path.join(repositoryRoot, 'src/vs/sessions/sessions.common.main.ts'), 'utf8'); + const imports = ts.preProcessFile(source, true).importedFiles.map(reference => reference.fileName); + const desktop = imports.indexOf('./contrib/chat/browser/chat.desktop.contribution.js'); + const shared = imports.indexOf('./contrib/chat/browser/chat.contribution.js'); + assert.ok(desktop >= 0 && shared > desktop); + }); +}); + +function getSingletonRegistrations(file: string): string[][] { + const source = ts.createSourceFile(file, fs.readFileSync(path.join(repositoryRoot, file), 'utf8'), ts.ScriptTarget.Latest, true); + return source.statements.flatMap(statement => { + if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression) + || !ts.isIdentifier(statement.expression.expression) || statement.expression.expression.text !== 'registerSingleton') { + return []; + } + return [statement.expression.arguments.slice(0, 2).map(argument => argument.getText(source))]; + }); +} + +function isMobileEntryFile(file: string): boolean { + return file.startsWith('src/vs/sessions/contrib/mobile/') || + file.startsWith('src/vs/sessions/browser/mobile/') || + /^src\/vs\/sessions\/sessions\.core(?:\.web)?\.main\.ts$/.test(file) || + [ + ...experimentalPicker, + mobileConfigurationPresenter, + mobileInputButton, + hostPickerRoot + 'mobileAgentHostFilterService.ts', + hostPickerRoot + 'mobileTunnelConnection.ts', + ].includes(file); +} + +/** Includes type imports conservatively: neither source graph may depend on the other presentation. */ +function collectSourceDependencies(entry: string): Set { + const visited = new Set(); + const pending = [entry]; + while (pending.length > 0) { + const file = pending.pop()!; + if (visited.has(file)) { + continue; + } + visited.add(file); + if (!file.endsWith('.ts') && !file.endsWith('.js')) { + continue; + } + let dependencies = dependenciesByFile.get(file); + if (!dependencies) { + const source = fs.readFileSync(path.join(repositoryRoot, file), 'utf8'); + dependencies = ts.preProcessFile(source, true).importedFiles + .map(reference => reference.fileName) + .filter(specifier => specifier.startsWith('.')) + .map(specifier => { + const resolved = path.resolve(repositoryRoot, path.dirname(file), specifier); + const candidates = [resolved.replace(/\.js$/, '.ts'), resolved.replace(/\.js$/, '.tsx'), resolved.replace(/\.js$/, '.d.ts'), resolved]; + const dependency = candidates.find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile()); + assert.ok(dependency, `Cannot resolve ${specifier} from ${file}`); + return path.relative(repositoryRoot, dependency).replaceAll('\\', '/'); + }); + dependenciesByFile.set(file, dependencies); + } + pending.push(...dependencies); + } + return visited; +} diff --git a/build/lib/test/universalApp.test.ts b/build/lib/test/universalApp.test.ts new file mode 100644 index 000000000000..d7a0f0fd9635 --- /dev/null +++ b/build/lib/test/universalApp.test.ts @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { suite, test } from 'node:test'; +import { createPackageWithOptions, extractFile } from 'asar'; +import { mergeASARs } from 'vscode-universal-bundler/dist/cjs/asar-utils.js'; +import { singleArchFiles } from '../../darwin/create-universal-app.ts'; + +async function createArchive(root: string, arch: string, files: Record): Promise { + const source = path.join(root, arch); + for (const [file, contents] of Object.entries(files)) { + const target = path.join(source, file); + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, contents); + } + const archive = path.join(root, `${arch}.asar`); + await createPackageWithOptions(source, archive, { dot: true, unpackDir: '@github' }); + return archive; +} + +suite('universal app ASAR merge', () => { + test('preserves hidden SDK plugin metadata for both architectures', async t => { + const root = await mkdtemp(path.join(os.tmpdir(), 'vscode-universal-test-')); + t.after(() => rm(root, { recursive: true, force: true })); + + const filesForArch = (arch: string) => ({ + [`@github/copilot-sdk-darwin-${arch}/plugins/browser-use/.mcp.json`]: `{"arch":"${arch}"}`, + [`@github/copilot-sdk-darwin-${arch}/plugins/browser-use/.plugin/plugin.json`]: `{"name":"browser-use-${arch}"}`, + [`@github/copilot-sdk-darwin-${arch}/plugins/browser-use/.release-target`]: `darwin-${arch}`, + [`@github/copilot-sdk-darwin-${arch}/copilot-sdk/index.js`]: `export const arch = '${arch}';`, + }); + const x64Files = filesForArch('x64'); + const arm64Files = filesForArch('arm64'); + const x64AsarPath = await createArchive(root, 'x64', x64Files); + const arm64AsarPath = await createArchive(root, 'arm64', arm64Files); + const outputAsarPath = path.join(root, 'universal.asar'); + + await mergeASARs({ x64AsarPath, arm64AsarPath, outputAsarPath, singleArchFiles }); + + const expected = { ...x64Files, ...arm64Files }; + assert.deepStrictEqual( + Object.fromEntries(Object.keys(expected).map(file => [file, extractFile(outputAsarPath, file).toString()])), + expected, + ); + }); + + test('still rejects architecture-only files outside the allowlist', async t => { + const root = await mkdtemp(path.join(os.tmpdir(), 'vscode-universal-test-')); + t.after(() => rm(root, { recursive: true, force: true })); + + const x64AsarPath = await createArchive(root, 'x64', { + 'shared.json': '{}', + 'other-package/plugins/browser-use/.mcp.json': '{}', + }); + const arm64AsarPath = await createArchive(root, 'arm64', { 'shared.json': '{}' }); + + await assert.rejects( + mergeASARs({ x64AsarPath, arm64AsarPath, outputAsarPath: path.join(root, 'universal.asar'), singleArchFiles }), + /not covered by allowList rule/, + ); + }); +}); diff --git a/build/lib/test/workspaceLinks.test.ts b/build/lib/test/workspaceLinks.test.ts new file mode 100644 index 000000000000..ebca7ce307aa --- /dev/null +++ b/build/lib/test/workspaceLinks.test.ts @@ -0,0 +1,95 @@ +/*--------------------------------------------------------------------------------------------- + * 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 fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { suite, test } from 'node:test'; +import { findWorkspaceLinks, restoreWorkspaceLinks, saveWorkspaceLinks } from '../../azure-pipelines/common/workspaceLinks.ts'; + +const linkType = process.platform === 'win32' ? 'junction' : 'dir'; + +function write(file: string, content: string): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); +} + +/** A workspace laid out like pnpm's isolated `node_modules`, plus links that must be left alone. */ +function createWorkspace(): { root: string; outside: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-links-')); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-links-outside-')); + write(path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/a/index.js'), 'a'); + write(path.join(root, 'node_modules/.pnpm/b@1.0.0/node_modules/b/index.js'), 'b'); + write(path.join(root, '.git/HEAD'), 'ref'); + write(path.join(outside, 'c/index.js'), 'c'); + // `a` at the top level, and `b` beside `a` in the virtual store, so that `a` resolves it + fs.symlinkSync(path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/a'), path.join(root, 'node_modules/a'), linkType); + fs.symlinkSync(path.join(root, 'node_modules/.pnpm/b@1.0.0/node_modules/b'), path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/b'), linkType); + fs.symlinkSync(path.join(outside, 'c'), path.join(root, 'node_modules/c'), linkType); + fs.symlinkSync(path.join(root, 'missing'), path.join(root, 'node_modules/dangling'), linkType); + return { root, outside }; +} + +function isLink(file: string): boolean { + return fs.lstatSync(file).isSymbolicLink(); +} + +suite('workspaceLinks', () => { + + test('finds the folder links inside the workspace without following them', () => { + const { root, outside } = createWorkspace(); + try { + assert.deepStrictEqual(findWorkspaceLinks(root), [ + { path: 'node_modules/.pnpm/a@1.0.0/node_modules/b', target: 'node_modules/.pnpm/b@1.0.0/node_modules/b' }, + { path: 'node_modules/a', target: 'node_modules/.pnpm/a@1.0.0/node_modules/a' }, + ]); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('removes the links without their targets, and creates them again', () => { + const { root, outside } = createWorkspace(); + const manifest = path.join(root, '.build/workspace-links.json'); + try { + assert.strictEqual(saveWorkspaceLinks(root, manifest).length, 2); + assert.ok(!fs.existsSync(path.join(root, 'node_modules/a'))); + assert.ok(!fs.existsSync(path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/b'))); + assert.strictEqual(fs.readFileSync(path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/a/index.js'), 'utf8'), 'a'); + assert.strictEqual(fs.readFileSync(path.join(root, 'node_modules/.pnpm/b@1.0.0/node_modules/b/index.js'), 'utf8'), 'b'); + // Left for the archive to copy + assert.ok(isLink(path.join(root, 'node_modules/c'))); + assert.ok(isLink(path.join(root, 'node_modules/dangling'))); + + assert.strictEqual(restoreWorkspaceLinks(root, manifest).length, 2); + assert.ok(isLink(path.join(root, 'node_modules/a'))); + assert.strictEqual(fs.realpathSync(path.join(root, 'node_modules/a')), fs.realpathSync(path.join(root, 'node_modules/.pnpm/a@1.0.0/node_modules/a'))); + assert.strictEqual(fs.readFileSync(path.join(root, 'node_modules/a/index.js'), 'utf8'), 'a'); + assert.strictEqual(fs.readFileSync(path.join(fs.realpathSync(path.join(root, 'node_modules/a')), '../b/index.js'), 'utf8'), 'b'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('restores the links in a copy of the workspace at another path', () => { + const { root, outside } = createWorkspace(); + const copy = fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-links-copy-')); + const manifest = path.join(root, '.build/workspace-links.json'); + try { + saveWorkspaceLinks(root, manifest); + fs.cpSync(path.join(root, 'node_modules/.pnpm'), path.join(copy, 'node_modules/.pnpm'), { recursive: true }); + restoreWorkspaceLinks(copy, manifest); + assert.strictEqual(fs.realpathSync(path.join(copy, 'node_modules/a')), fs.realpathSync(path.join(copy, 'node_modules/.pnpm/a@1.0.0/node_modules/a'))); + assert.strictEqual(fs.readFileSync(path.join(copy, 'node_modules/.pnpm/a@1.0.0/node_modules/b/index.js'), 'utf8'), 'b'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(outside, { recursive: true, force: true }); + fs.rmSync(copy, { recursive: true, force: true }); + } + }); +}); diff --git a/build/lib/tsec.ts b/build/lib/tsec.ts new file mode 100644 index 000000000000..af5c6dec784d --- /dev/null +++ b/build/lib/tsec.ts @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createRequire } from 'module'; +import path from 'path'; +import type * as ts from 'typescript'; + +// +// Runs the security rules of tsec over src/tsconfig.tsec.json. The tsec command line also type +// checks the whole program first, which takes most of its time and repeats the type check of +// the compilation, so this script runs only the rules. +// + +/** The tsec modules, and the TypeScript that tsec resolves. */ +const tsecRequire = createRequire(path.join(import.meta.dirname, '..', '..', 'node_modules', 'tsec', 'package.json')); +const typescript: typeof ts = tsecRequire('typescript'); +const { performCheck }: { performCheck(program: ts.Program, host: ts.CompilerHost): ts.Diagnostic[] } = tsecRequire('./lib/packages/tsec/build.js'); +const { createCompilerHost }: { createCompilerHost(config: ts.ParsedCommandLine): ts.CompilerHost } = tsecRequire('./lib/packages/tsec/compiler_host.js'); +const { createDiagnosticsReporter }: { createDiagnosticsReporter(options: ts.CompilerOptions): (diagnostics: readonly ts.Diagnostic[], withSummary: boolean) => number } = tsecRequire('./lib/packages/tsec/report.js'); + +const configPath = path.join(import.meta.dirname, '..', '..', 'src', 'tsconfig.tsec.json'); +const config = typescript.getParsedCommandLineOfConfigFile(configPath, {}, { + ...typescript.sys, + onUnRecoverableConfigFileDiagnostic: diagnostic => { + throw new Error(typescript.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); + }, +}); +if (!config) { + throw new Error(`Could not read ${configPath}.`); +} + +const host = createCompilerHost(config); +const program = typescript.createProgram(config.fileNames, config.options, host); +const diagnostics = [...config.errors, ...performCheck(program, host)]; +const errorCount = createDiagnosticsReporter(config.options)(typescript.sortAndDeduplicateDiagnostics(diagnostics), /*withSummary*/ true); +process.exitCode = errorCount === 0 ? 0 : 1; diff --git a/build/next/MOBILE.md b/build/next/MOBILE.md new file mode 100644 index 000000000000..dcd88dd0264c --- /dev/null +++ b/build/next/MOBILE.md @@ -0,0 +1,127 @@ +# Isolated mobile web package + +The opt-in mobile target packages the dedicated Agents entry without adding +it to the ordinary editor, Agents, desktop or server outputs. + +```sh +pnpm run bundle-mobile +``` + +The output is `out-mobile/`, containing: + +- `out/`: the mobile entry, its own localization tables, workers and resources; +- `node_modules/`: explicitly selected browser runtime dependencies; +- `extensions/`: GitHub authentication and selected language/theme extensions; +- `mobile.json`: source commit, quality, asset hashes, entry points and + measured sizes. + +The build requires a source commit. In Git worktrees, supply it through the same +environment variable used by CI: + +```sh +BUILD_SOURCEVERSION="$(git rev-parse HEAD)" pnpm run bundle-mobile +``` + +Local packages use quality `dev`. Product builds require the normal quality +mixin to agree with `VSCODE_QUALITY`. Asset hashes describe package integrity and +local cache invalidation; they are not a separate production release identifier. +This build target alone does not publish or release anything. +The target name `mobile` identifies the package, independently of its release +quality or rollout status. + +## Boundaries and size checks + +[mobilePolicy.json](mobilePolicy.json) defines the reviewed +contribution list, forbidden dependencies, extensions, runtime libraries and +compressed-size limits. The build examines transitive bundle inputs, not only +the entry's direct imports. An unknown contribution or unpackaged dependency +fails the build independently of the size checks. + +The ordinary entry's repository, list, Configure Session and edit presentation +implementations and clipboard registration are also rejected. The mobile entry +selects its own implementations; their shared contracts and behavior remain +available. + +Mobile does not include chat-background controls, settings, rendering, tinting +or built-in background-generation tools. Its resource list is +independent of the common workbench list, so background images, including both +animated and still koi assets, are not copied into the package. + +The same built-in `SKILL.md` definitions as desktop are packaged under +`out/vs/sessions/skills/`, including the background-generation skill. Mobile +uses the shared prompts service and its existing enablement rules. The +background skill already instructs the agent to explain when required tools +are unavailable rather than generating an image it cannot apply; packaging +the skill does not include the background implementation or enable its tools. + +The size limits are experimental regression guards introduced with this target, +not existing VS Code product requirements or hosting restrictions. Review actual +dependency growth before changing a baseline; do not widen the contribution +list or remove a size check merely to make a build pass. + +The temporary ceilings are 6,400,000 gzip bytes for the main JavaScript, +275,000 for the stylesheet, 7,000,000 for the initial bundle and 16,500,000 +for the runtime. They leave headroom for normal shared-code growth above +the reviewed current-main baseline; the extension ceiling remains 800,000 +gzip bytes. These are growth guards, not mobile performance targets. +Reducing the actual downloads needed for a usable session list and composer +requires separate startup measurements and loading changes. + +- Initial size counts the main JavaScript, stylesheet and language bundle. +- Runtime size includes workers and runtime libraries but excludes extensions. +- Extensions have their own limit. +- Source maps, build/localization metadata and license notices are inventoried + but excluded from these runtime totals. + +These are sums of independently gzipped files, not a measured phone startup +download or memory budget. + +## Output safety and validation + +Only the target's owned output directory can be rebuilt. A lock prevents +concurrent builds from mixing files, and a rebuild removes the previous success +manifest before writing anything. A failed build never leaves a success manifest +for partial output. + +```sh +node --test build/next/test/mobile.test.ts build/next/test/resources.test.ts build/next/test/bundle.test.ts +pnpm -C build run typecheck +``` + +On macOS, use `TMPDIR=/private/tmp` for the tests so temporary file URLs have the +same canonical path. The tests cover exact size limits and one-byte overflows, +dependency boundaries, package contents, extension resources and output safety. +Producing a package is not evidence of live authentication or real-device +behavior; those require separate end-to-end validation. + +## Standard publication + +The existing product pipeline can include this target with +`VSCODE_BUILD_WEB_MOBILE=true`. The option is false by default and requires a +Product build with the ordinary Web stage enabled. When explicitly selected, a +failed mobile build, guard test or upload fails that selected build; errors are +not ignored. Ordinary builds do not run the optional mobile steps. + +The Web job creates `vscode-web-mobile.tar.gz`, with a `vscode-web-mobile/` +top-level directory, and registers its archive as platform `web-mobile` through +the normal publisher. Source commit and quality remain the release identity. +Normal release controls and platform-based update lookup select this asset; +there is no mobile-specific release registry. + +Both Web archives use the standard existing-artifact check so retrying the job +does not republish an immutable pipeline artifact. + +When the usual `VSCODE_PUBLISH` flag is enabled, the existing CDN uploader places +the expanded mobile files and their own `files.txt` under +`agents/mobile///`. This is outside the normal editor's asset +directory, so its preload inventory does not include mobile files. + +Publication contract checks run with the normal build-script tests and in the +opted-in Web job: + +```sh +node --test build/lib/test/mobileWebPublication.test.ts +``` + +Local checks do not replace an unpublished Azure product build or verification +of real archive/CDN registration before enabling release automation. diff --git a/build/next/index.ts b/build/next/index.ts index 1983fd1461c2..dd534bff120c 100644 --- a/build/next/index.ts +++ b/build/next/index.ts @@ -27,6 +27,7 @@ import { copyResources } from './resources.ts'; import { optimizeSvgFiles } from './svg.ts'; import { getBundleOptions } from './bundle.ts'; import { compileStandaloneFiles } from './standalone.ts'; +import { copyMobileLibraries, mobileDirectory, mobileEntryPoint, mobilePlugin, mobileQuality, packageMobileExtensions, prepareMobile, writeMobileManifest } from './mobile.ts'; const globAsync = promisify(glob); @@ -171,6 +172,12 @@ function getEntryPointsForTarget(target: BuildTarget): string[] { 'vs/workbench/workbench.web.main.internal', // web workbench only (no browser shell) ...keyboardMapEntryPoints, ]; + case 'mobile': + return [ + ...workerEntryPoints, + mobileEntryPoint, + ...keyboardMapEntryPoints, + ]; default: throw new Error(`Unknown target: ${target}`); } @@ -199,6 +206,8 @@ function getCssBundleEntryPointsForTarget(target: BuildTarget): Set { 'vs/workbench/workbench.web.main.internal', 'vs/sessions/sessions.web.main.internal', ]); + case 'mobile': + return new Set([mobileEntryPoint]); default: throw new Error(`Unknown target: ${target}`); } @@ -219,11 +228,14 @@ async function cleanDir(dir: string): Promise { * Scan for built-in extensions in the given directory. * Returns an array of extension entries for the builtinExtensionsScannerService. */ -function scanBuiltinExtensions(extensionsRoot: string): Array { +function scanBuiltinExtensions(extensionsRoot: string, required = false): Array { const scannedExtensions: Array = []; const extensionsPath = path.join(REPO_ROOT, extensionsRoot); if (!fs.existsSync(extensionsPath)) { + if (required) { + throw new Error(`Missing local extension sources: ${extensionsPath}`); + } return scannedExtensions; } @@ -251,6 +263,9 @@ function scanBuiltinExtensions(extensionsRoot: string): ArrayINSERT_BUILTIN_EXTENSIONS*/')) { if (builtinExtensionsReplacement === undefined) { - if (target === 'web' || target === 'server-web') { - // Web target uses .build/web/extensions (from compileWebExtensionsBuildTask) - // while server-web uses .build/extensions. - const extensionsRoot = target === 'web' ? '.build/web/extensions' : '.build/extensions'; - const builtinExtensions = JSON.stringify(scanBuiltinExtensions(extensionsRoot)); + if (target === 'web' || target === 'server-web' || target === 'mobile') { + const extensionsRoot = target === 'mobile' ? `${mobileDirectory}/extensions` + : target === 'server-web' ? '.build/extensions' : '.build/web/extensions'; + const builtinExtensions = JSON.stringify(scanBuiltinExtensions(extensionsRoot, target === 'mobile')); // Remove the outer brackets since the placeholder is inside an array literal builtinExtensionsReplacement = builtinExtensions.substring(1, builtinExtensions.length - 1); } else { @@ -460,6 +474,24 @@ async function transpile(outDir: string, excludeTests: boolean): Promise { // ============================================================================ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doManglePrivates: boolean, target: BuildTarget, sourceMapBaseUrl?: string): Promise { + if (target !== 'mobile') { + return bundleToOutput(outDir, doMinify, doNls, doManglePrivates, target, sourceMapBaseUrl); + } + if (!doMinify || !doNls || sourceMapBaseUrl) { + throw new Error('Mobile requires minification and isolated NLS, with local source maps. Use pnpm run bundle-mobile.'); + } + const release = await prepareMobile(REPO_ROOT, outDir); + try { + mobileQuality(quality, process.env['VSCODE_QUALITY']); + await packageMobileExtensions(REPO_ROOT); + await bundleToOutput(outDir, doMinify, doNls, doManglePrivates, target); + } finally { + await release(); + } +} + +async function bundleToOutput(outDir: string, doMinify: boolean, doNls: boolean, doManglePrivates: boolean, target: BuildTarget, sourceMapBaseUrl?: string): Promise { + const mobile = target === 'mobile'; await cleanDir(outDir); // Write build date file (used by packaging to embed in product.json). @@ -495,12 +527,15 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl const contentMapperPlugin = fileContentMapperPlugin(outDir, target); // Bundle each entry point directly from TypeScript source - await Promise.all(allEntryPoints.map(async (entryPoint) => { + const bundleEntryPoint = async (entryPoint: string) => { const entryPath = path.join(REPO_ROOT, SRC_DIR, `${entryPoint}.ts`); const outPath = path.join(REPO_ROOT, outDir, `${entryPoint}.js`); // Use CSS external plugin for entry points that don't need bundled CSS const plugins: esbuild.Plugin[] = bundleCssEntryPoints.has(entryPoint) ? [] : [cssExternalPlugin()]; + if (mobile) { + plugins.push(mobilePlugin(REPO_ROOT)); + } // Add content mapper plugin to inject product config and builtin extensions plugins.push(contentMapperPlugin); if (doNls) { @@ -516,6 +551,7 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl const buildOptions: esbuild.BuildOptions = { ...getBundleOptions(doMinify, 'neutral'), + ...(mobile ? { absWorkingDir: REPO_ROOT, metafile: true } : {}), entryPoints: needsCssBundling ? [{ in: entryPath, out: entryPoint }] : [entryPath], @@ -535,7 +571,14 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl const result = await esbuild.build(buildOptions); buildResults.push({ outPath, result }); - })); + }; + if (mobile) { + for (const entryPoint of allEntryPoints) { + await bundleEntryPoint(entryPoint); + } + } else { + await Promise.all(allEntryPoints.map(bundleEntryPoint)); + } // Bundle bootstrap files (with minimist inlined) directly from TypeScript source for (const entry of bootstrapEntryPoints) { @@ -570,7 +613,7 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl const nlsResult = await finalizeNLS( nlsCollector, path.join(REPO_ROOT, outDir), - [path.join(REPO_ROOT, 'out-build')] + mobile ? undefined : [path.join(REPO_ROOT, 'out-build')] ); indexMap = nlsResult.indexMap; } @@ -709,7 +752,7 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl }); } - if (allEntryPoints.includes(sessionsWebEntryPoint)) { + if (allEntryPoints.includes(sessionsWebEntryPoint) || mobile) { await bundleDevTunnelsWeb({ minify: doMinify, outDir: path.join(outDir, devTunnelsWebOutDir), @@ -720,6 +763,15 @@ async function bundle(outDir: string, doMinify: boolean, doNls: boolean, doMangl // Finish emitted assets and copied resources before packaging computes integrity data. await optimizeSvgFiles(outDirPath, doMinify); + if (mobile) { + await copyMobileLibraries(REPO_ROOT); + const inputs = new Set(buildResults.flatMap(({ result }) => Object.keys(result.metafile?.inputs ?? {}))); + if (!commit) { + throw new Error('Mobile requires a Git revision to identify the build.'); + } + await writeMobileManifest(REPO_ROOT, { commit, version, date: buildDate, quality: mobileQuality(quality, process.env['VSCODE_QUALITY']) }, inputs); + } + console.log(`[bundle] Done in ${Date.now() - t1}ms (${bundled} bundles)`); } @@ -839,6 +891,7 @@ Commands: build-fast Incrementally build changed development outputs transpile Transpile TypeScript to JavaScript (single-file, fast) bundle Bundle entry points into optimized bundles + bundle-mobile Build the isolated, minified mobile package in out-mobile/ Options for 'build-fast': --force Ignore incremental state and rebuild selected lanes @@ -878,6 +931,12 @@ async function main(): Promise { try { switch (command) { + case 'bundle-mobile': + if (process.argv.length > 3) { + throw new Error('bundle-mobile uses fixed build settings and output; command-line options are not supported.'); + } + await bundle(`${mobileDirectory}/out`, true, true, true, 'mobile'); + break; case 'build-fast': await runBuildFast(REPO_ROOT, options.force, options.clientOnly); break; diff --git a/build/next/mobile.ts b/build/next/mobile.ts new file mode 100644 index 000000000000..d330810939ba --- /dev/null +++ b/build/next/mobile.ts @@ -0,0 +1,532 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { createHash } from 'node:crypto'; +import * as fs from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import * as path from 'node:path'; +import { gzipSync } from 'node:zlib'; +import type * as esbuild from 'esbuild'; +import { parse as parseJsonc, type ParseError } from 'jsonc-parser'; +import policy from './mobilePolicy.json' with { type: 'json' }; + +export const mobileDirectory = 'out-mobile'; +export const mobileEntryPoint = 'vs/sessions/agents.web.mobile.main.internal'; +export const mobileManifestName = 'mobile.json'; +const manifestKind = 'sessions-mobile'; +export const mobileEntrypoints = { + workbench: `out/${mobileEntryPoint}.js`, + stylesheet: `out/${mobileEntryPoint}.css`, + nls: 'out/nls.messages.js', +}; +const entrypoints = mobileEntrypoints; + +export interface MobileExtension { + readonly id: string; + readonly path: string; +} + +export interface MobileAsset { + readonly path: string; + readonly bytes: number; + readonly gzipBytes: number; + readonly sha256: string; +} + +export interface MobileManifest { + readonly schemaVersion: 2; + readonly kind: typeof manifestKind; + readonly build: { readonly commit: string; readonly version: string; readonly date: string; readonly quality: 'dev' | 'insider' | 'stable' | 'exploration' }; + readonly entrypoints: typeof entrypoints; + readonly extensions: readonly MobileExtension[]; + readonly assets: readonly MobileAsset[]; + readonly preload: readonly string[]; + readonly sizes: { readonly initialGzipBytes: number; readonly runtimeGzipBytes: number; readonly extensionsGzipBytes: number }; + readonly budgets: typeof policy.budgets; + readonly contributions: readonly string[]; + readonly localization: { readonly keys: string; readonly metadata: string; readonly messages: string }; +} + +/** Refuse to clean any path except this target's owned output. */ +export async function prepareMobile(root: string, outDir: string): Promise<() => Promise> { + const output = path.resolve(root, outDir); + const mobileRoot = path.join(root, mobileDirectory); + if (output !== path.join(mobileRoot, 'out')) { + throw new Error(`Mobile output must be ${mobileDirectory}/out, not ${outDir}`); + } + for (const directory of [mobileRoot, output, path.join(mobileRoot, 'node_modules'), path.join(mobileRoot, 'extensions')]) { + try { + const stat = await fs.lstat(directory); + if (!stat.isDirectory() || stat.isSymbolicLink()) { + throw new Error(`Mobile output is not a regular directory: ${directory}`); + } + } catch (error) { + if (!isMissing(error)) { + throw error; + } + } + } + const files = await fs.readdir(mobileRoot).catch(error => { + if (isMissing(error)) { + return []; + } + throw error; + }); + if (files.length > 0) { + let marker: { schemaVersion?: number; kind?: string } | null; + try { + const markerPath = path.join(mobileRoot, '.mobile-build.json'); + const stat = await fs.lstat(markerPath); + if (!stat.isFile() || stat.isSymbolicLink()) { + throw new Error('Mobile ownership marker is not a regular file'); + } + marker = JSON.parse(await fs.readFile(markerPath, 'utf8')); + } catch (error) { + throw new Error(`Refusing to overwrite an unowned ${mobileDirectory} directory`, { cause: error }); + } + if (marker?.schemaVersion !== 1 || marker?.kind !== manifestKind) { + throw new Error(`Refusing to overwrite an unowned ${mobileDirectory} directory`); + } + } + await fs.mkdir(mobileRoot, { recursive: true }); + const lock = path.join(mobileRoot, '.mobile-build.lock'); + try { + await fs.writeFile(lock, `${process.pid}\n`, { flag: 'wx' }); + } catch (error) { + throw new Error(`Unable to acquire the mobile build lock: ${lock}. Check for another build before removing a stale lock.`, { cause: error }); + } + let released = false; + const release = async () => { + if (!released) { + released = true; + await fs.rm(lock, { force: true }); + } + }; + try { + await fs.writeFile(path.join(mobileRoot, '.mobile-build.json'), JSON.stringify({ schemaVersion: 1, kind: manifestKind })); + // A failed rebuild must never leave a success manifest pointing to partial files. + await fs.rm(path.join(mobileRoot, mobileManifestName), { force: true }); + await fs.rm(path.join(mobileRoot, 'node_modules'), { recursive: true, force: true }); + await fs.rm(path.join(mobileRoot, 'extensions'), { recursive: true, force: true }); + } catch (error) { + await release(); + throw error; + } + return release; +} + +export function checkMobileDependencies(inputs: Iterable): string[] { + const paths = [...inputs].map(file => file.replaceAll('\\', '/')).sort(); + const blocked = paths.filter(file => + /^src\/vs\/(?:sessions|workbench)\/(?:sessions|workbench)\.(?:common|desktop|web)\.main(?:\.internal)?\.ts$/.test(file) || + /^src\/vs\/.*\/(?:electron-[^/]+|node|test)\//.test(file) || + policy.forbiddenModules.includes(file)); + const contributions = paths.filter(file => /(?:\.contributions?|\.all)\.ts$/.test(file)); + const unexpected = contributions.filter(file => !policy.contributions.includes(file)); + if (blocked.length || unexpected.length) { + throw new Error(`Mobile dependency boundary failed:\n${[ + ...blocked.map(file => `Forbidden module: ${file}`), + ...unexpected.map(file => `Unreviewed contribution: ${file}`), + ].join('\n')}`); + } + return [...new Set(contributions)]; +} + +/** Uses emitted inputs, not type-only source imports, to enforce the component boundary. */ +export function mobilePlugin(root: string): esbuild.Plugin { + return { + name: 'mobile-boundaries', + setup(build) { + build.onResolve({ filter: /codicon\.ttf$/ }, args => { + if (path.basename(args.importer) === 'codicon.css') { + return { path: path.join(root, 'node_modules/@vscode/codicons/dist/codicon.ttf') }; + } + return undefined; + }); + build.onEnd(result => { + if (result.metafile) { + checkMobileDependencies(Object.keys(result.metafile.inputs)); + for (const output of Object.values(result.metafile.outputs)) { + for (const dependency of output.imports) { + if (dependency.external && !dependency.path.startsWith('data:') && + (dependency.kind !== 'dynamic-import' || !policy.externalModules.includes(dependency.path))) { + throw new Error(`Unpackaged mobile dependency: ${dependency.path}`); + } + } + } + } + }); + }, + }; +} + +export function checkMobileBudgets(assets: readonly MobileAsset[], budgets = policy.budgets): MobileManifest['sizes'] { + const byPath = new Map(assets.map(asset => [asset.path, asset])); + const required = Object.values(entrypoints).map(file => { + const asset = byPath.get(file); + if (!asset) { + throw new Error(`Mobile package is missing ${file}`); + } + return asset; + }); + const initialGzipBytes = required.reduce((total, asset) => total + asset.gzipBytes, 0); + const runtimeGzipBytes = assets.filter(asset => !asset.path.startsWith('extensions/') && !isBuildMetadata(asset.path)).reduce((total, asset) => total + asset.gzipBytes, 0); + const extensionsGzipBytes = assets.filter(asset => asset.path.startsWith('extensions/') && !isBuildMetadata(asset.path)).reduce((total, asset) => total + asset.gzipBytes, 0); + const measured: Record = { + workbenchJavaScriptGzipBytes: required[0].gzipBytes, + workbenchCssGzipBytes: required[1].gzipBytes, + initialGzipBytes, + runtimeGzipBytes, + extensionsGzipBytes, + }; + const exceeded = (Object.keys(budgets) as (keyof typeof budgets)[]).filter(key => measured[key] > budgets[key]); + if (exceeded.length) { + throw new Error(`Mobile size budget exceeded:\n${exceeded.map(key => `${key}: ${measured[key]} > ${budgets[key]} bytes`).join('\n')}`); + } + return { initialGzipBytes, runtimeGzipBytes, extensionsGzipBytes }; +} + +function isBuildMetadata(file: string): boolean { + return file.endsWith('.map') || /^out\/(?:date|nls\.(?:keys|metadata|messages)\.json)$/.test(file) || /(?:LICENSE|NOTICE)/i.test(file); +} + +export function mobileQuality(quality: string | undefined, expectedQuality?: string): MobileManifest['build']['quality'] { + const result = quality ?? 'dev'; + assert.ok(['dev', 'insider', 'stable', 'exploration'].includes(result), `Invalid mobile product quality: ${result}`); + if (expectedQuality) { + assert.equal(result, expectedQuality, 'Mobile quality must come from the matching product.json mixin, not only VSCODE_QUALITY'); + } + return result as MobileManifest['build']['quality']; +} + +export function checkMobilePath(file: string): void { + assert.ok(/^(?:[a-zA-Z0-9@_+., ()-]+\/)*[a-zA-Z0-9@_+., ()-]+$/.test(file) && file.split('/').every(part => part !== '.' && part !== '..' && !/[. ]$/.test(part)), + `Invalid mobile relative path: ${file}`); +} + +/** Also check parent directories: a regular file inside a symlink is not an artifact input. */ +export async function readMobileFile(root: string, file: string): Promise { + checkMobilePath(file); + let current = root; + for (const part of ['', ...file.split('/')]) { + current = path.join(current, part); + const stat = await fs.lstat(current); + assert.ok(!stat.isSymbolicLink(), `Symlinks are not allowed in mobile assets: ${file}`); + assert.ok(current === path.join(root, file) ? stat.isFile() : stat.isDirectory(), `Not a regular mobile input: ${file}`); + } + return fs.readFile(current); +} + +interface ExtensionManifest { + name: string; + publisher: string; + version: string; + license?: string; + main?: string; + browser?: string; + icon?: string; + scripts?: object; + dependencies?: object; + devDependencies?: object; + extensionDependencies?: string[]; + contributes?: { + themes?: { path: string }[]; + iconThemes?: { path: string }[]; + grammars?: { path: string }[]; + snippets?: { path: string }[]; + languages?: { configuration?: string; icon?: { light: string; dark: string } }[]; + }; +} + +function extensionId(manifest: ExtensionManifest): string { + assert.ok(typeof manifest.publisher === 'string' && typeof manifest.name === 'string' && + /^[a-z0-9-]+\.[a-z0-9-]+$/i.test(`${manifest.publisher}.${manifest.name}`), 'Invalid mobile extension identity'); + assert.ok(typeof manifest.version === 'string' && manifest.version.length > 0, 'Missing mobile extension version'); + return `${manifest.publisher}.${manifest.name}`.toLowerCase(); +} + +function checkExtensionDependencies(manifests: readonly ExtensionManifest[]): void { + const ids = new Set(manifests.map(extensionId)); + assert.equal(ids.size, manifests.length, 'Duplicate mobile extension identity'); + for (const manifest of manifests) { + assert.ok(!manifest.extensionDependencies || Array.isArray(manifest.extensionDependencies), `Invalid dependencies for ${extensionId(manifest)}`); + for (const dependency of manifest.extensionDependencies ?? []) { + assert.ok(typeof dependency === 'string' && ids.has(dependency.toLowerCase()), + `Required extension ${dependency} for ${extensionId(manifest)} must be explicitly included in the mobile package`); + } + } +} + +async function packageExtensionNotices(root: string, source: string, output: string): Promise { + const { getProductionDependencies } = await import('../lib/dependencies.ts'); + const dependencies = new Set(getProductionDependencies(source).map(dependency => dependency.source)); + // Source maps also reveal bundled aliases resolved outside the extension's dependency tree. + for (const file of await fs.readdir(path.join(output, 'dist'), { recursive: true })) { + if (!file.endsWith('.map')) { + continue; + } + const mapFile = path.join(output, 'dist', file); + const map: { sources: string[] } = JSON.parse(await fs.readFile(mapFile, 'utf8')); + for (const entry of map.sources) { + if (/^[a-zA-Z][a-zA-Z\d+.-]*:|^= 0 && parts[index + 1]) { + if (parts[index + 1] === '.pnpm') { + // Published maps can point above a package root within its pnpm store entry. + const storePackages = parts.slice(0, index + 3).join(path.sep) + path.sep + 'node_modules' + path.sep; + assert.ok(parts[index + 2] && [...dependencies].some(dependency => dependency.startsWith(storePackages)), + `Unidentified pnpm source-map dependency: ${entry}`); + continue; + } + dependencies.add(parts.slice(0, index + (parts[index + 1].startsWith('@') ? 3 : 2)).join(path.sep)); + } + } + } + const notices: string[] = []; + try { + notices.push((await readMobileFile(output, 'ThirdPartyNotices.txt')).toString()); + } catch (error) { + if (!isMissing(error)) { + throw error; + } + } + for (const directory of [...dependencies].sort()) { + const relative = path.relative(root, directory).replaceAll('\\', '/'); + const manifest: { name: string; version: string; license?: string | { type: string } } = + JSON.parse((await readMobileFile(root, `${relative}/package.json`)).toString()); + const files = (await fs.readdir(directory)).filter(file => /^(?:licen[sc]e|notice|thirdpartynotices)(?:[.-]|$)/i.test(file)).sort(); + assert.ok(files.length > 0 || manifest.license, `Missing license information for bundled dependency ${manifest.name}`); + const license = typeof manifest.license === 'string' ? manifest.license : manifest.license?.type; + notices.push(`${manifest.name}@${manifest.version}\nLicense: ${license ?? 'See the notices below'}`); + for (const file of files) { + notices.push((await readMobileFile(root, `${relative}/${file}`)).toString()); + } + } + if (notices.length) { + await fs.writeFile(path.join(output, 'ThirdPartyNotices.txt'), notices.join('\n\n') + '\n'); + } +} + +/** Build browser code into the artifact, then copy only VSCE-selected source resources, never checkout build output. */ +export async function packageMobileExtensions(root: string, names: readonly string[] = policy.extensions): Promise { + assert.ok(names.length > 0 && new Set(names).size === names.length, 'Mobile extensions must be an explicit, nonempty set'); + const manifests = await Promise.all(names.map(async name => { + assert.match(name, /^[a-z0-9-]+$/, 'Invalid mobile extension folder'); + const manifest: ExtensionManifest = JSON.parse((await readMobileFile(root, `extensions/${name}/package.json`)).toString()); + extensionId(manifest); + assert.ok(!manifest.main || manifest.browser, `Mobile extension ${name} has no browser entry`); + if (manifest.browser) { + assert.match(manifest.browser, /^\.\/dist\/browser\/[a-zA-Z0-9_-]+\.js$/, `Unsupported browser build layout for ${name}`); + await readMobileFile(root, `extensions/${name}/esbuild.browser.mts`); + } + return manifest; + })); + checkExtensionDependencies(manifests); + + const { esbuildExtensions } = await import('../lib/extensions.ts'); + const mobileRoot = path.join(root, mobileDirectory); + await fs.mkdir(path.join(mobileRoot, 'extensions'), { recursive: true }); + await esbuildExtensions('mobile extensions', false, names.flatMap((name, index) => manifests[index].browser ? [{ + script: path.join(root, 'extensions', name, 'esbuild.browser.mts'), + outputRoot: path.join(mobileRoot, 'extensions', name, 'dist'), + }] : [])); + + const vsce = createRequire(import.meta.url)('@vscode/vsce') as typeof import('@vscode/vsce'); + const license = await readMobileFile(root, 'LICENSE.txt'); + for (const [index, name] of names.entries()) { + const source = path.join(root, 'extensions', name); + const output = path.join(mobileRoot, 'extensions', name); + const files = await vsce.listFiles({ cwd: source, packageManager: vsce.PackageManager.None }); + for (const file of files) { + if (/^(?:dist|out|node_modules)\//.test(file)) { + continue; + } + const contents = await readMobileFile(source, file); + const destination = path.join(output, file); + await fs.mkdir(path.dirname(destination), { recursive: true }); + await fs.writeFile(destination, contents); + } + const manifest = { ...manifests[index] }; + delete manifest.main; + delete manifest.scripts; + delete manifest.dependencies; + delete manifest.devDependencies; + await fs.writeFile(path.join(output, 'package.json'), JSON.stringify(manifest)); + if (!files.some(file => /^(?:licen[sc]e)(?:[.-]|$)/i.test(file))) { + assert.equal(manifest.license, 'MIT', `Missing license for mobile extension ${name}`); + await fs.writeFile(path.join(output, 'LICENSE.txt'), license); + } + if (manifest.browser) { + await readMobileFile(output, manifest.browser.slice(2)); + await packageExtensionNotices(root, source, output); + } + } +} + +/** Validate the packaged manifests and their browser, grammar, theme and font resources. */ +export async function readMobileExtensions( + mobileRoot: string, + assets: ReadonlySet, + readContents: (file: string) => Promise = file => readMobileFile(mobileRoot, file), +): Promise { + const names = await fs.readdir(path.join(mobileRoot, 'extensions')); + const extensions: MobileExtension[] = []; + const manifests: ExtensionManifest[] = []; + assert.ok(names.length > 0, 'Mobile package has no packaged extensions'); + for (const name of names.sort()) { + const extensionPath = `extensions/${name}`; + const manifestPath = `${extensionPath}/package.json`; + assert.ok(assets.has(manifestPath), `Missing packaged extension manifest: ${manifestPath}`); + const manifest: ExtensionManifest = JSON.parse((await readContents(manifestPath)).toString()); + assert.ok(!manifest.main, `Mobile extension ${name} must not reference a desktop entry`); + const id = extensionId(manifest); + extensions.push({ id, path: extensionPath }); + manifests.push(manifest); + const resource = (base: string, reference: string) => { + assert.ok(typeof reference === 'string' && !/^[\\/]|[\\%?#]/.test(reference), `Invalid extension resource in ${base}`); + const file = path.posix.join(path.posix.dirname(base), reference); + checkMobilePath(file); + assert.ok(file.startsWith(`${extensionPath}/`) && assets.has(file), `Missing packaged extension resource: ${file}`); + return file; + }; + if (manifest.browser) { + resource(manifestPath, manifest.browser); + } + if (manifest.icon) { + resource(manifestPath, manifest.icon); + } + for (const entry of [...manifest.contributes?.grammars ?? [], ...manifest.contributes?.snippets ?? []]) { + resource(manifestPath, entry.path); + } + for (const language of manifest.contributes?.languages ?? []) { + if (language.configuration) { + resource(manifestPath, language.configuration); + } + if (language.icon) { + resource(manifestPath, language.icon.light); + resource(manifestPath, language.icon.dark); + } + } + const visitedThemes = new Set(); + const checkTheme = async (file: string): Promise => { + if (visitedThemes.has(file)) { + return; + } + visitedThemes.add(file); + const errors: ParseError[] = []; + const theme: { include?: string; fonts?: { src: { path: string }[] }[]; iconDefinitions?: Record } = + parseJsonc((await readContents(file)).toString(), errors, { allowTrailingComma: true }); + assert.equal(errors.length, 0, `Invalid packaged theme: ${file}`); + if (theme.include) { + await checkTheme(resource(file, theme.include)); + } + for (const font of theme.fonts ?? []) { + for (const source of font.src) { + resource(file, source.path); + } + } + for (const icon of Object.values(theme.iconDefinitions ?? {})) { + if (icon.iconPath) { + resource(file, icon.iconPath); + } + } + }; + for (const theme of [...manifest.contributes?.themes ?? [], ...manifest.contributes?.iconThemes ?? []]) { + await checkTheme(resource(manifestPath, theme.path)); + } + } + checkExtensionDependencies(manifests); + return extensions; +} + +/** Runtime libraries loaded by FileAccess/AMD live beside out/, not in a shared web package. */ +export async function copyMobileLibraries(root: string): Promise { + const mobileRoot = path.join(root, mobileDirectory); + for (const notice of ['LICENSE.txt', 'ThirdPartyNotices.txt']) { + await fs.writeFile(path.join(mobileRoot, 'out', notice), await readMobileFile(root, notice)); + } + for (const [packageName, patterns] of Object.entries(policy.libraries)) { + const source = path.join(root, 'node_modules', packageName); + const notices = (await fs.readdir(source)).filter(file => /^(?:licen[sc]e|notice|thirdpartynotices)(?:[.-]|$)/i.test(file)); + for (const pattern of [...patterns, ...notices]) { + const matches: string[] = []; + for await (const match of fs.glob(pattern, { cwd: source })) { + matches.push(match); + } + if (!matches.length) { + throw new Error(`Missing mobile library ${packageName}/${pattern}; restore repository dependencies`); + } + for (const file of matches) { + const input = path.join(source, file); + if (!(await fs.stat(input)).isFile()) { + continue; + } + const dest = path.join(mobileRoot, 'node_modules', packageName, file); + await fs.mkdir(path.dirname(dest), { recursive: true }); + await fs.copyFile(input, dest); + } + } + } +} + +export async function writeMobileManifest( + root: string, + build: MobileManifest['build'], + inputs: Iterable, +): Promise { + const mobileRoot = path.join(root, mobileDirectory); + const contributions = checkMobileDependencies(inputs); + const assets: MobileAsset[] = []; + for (const prefix of ['out', 'node_modules', 'extensions']) { + const directory = path.join(mobileRoot, prefix); + for (const file of await fs.readdir(directory, { recursive: true, withFileTypes: true })) { + if (file.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed in mobile assets: ${file.name}`); + } + if (!file.isFile()) { + continue; + } + const absolute = path.join(file.parentPath, file.name); + const relative = path.relative(mobileRoot, absolute).replaceAll('\\', '/'); + const contents = await readMobileFile(mobileRoot, relative); + if (relative.endsWith('.js') && contents.includes(Buffer.from('%%NLS'))) { + throw new Error(`Unresolved localization placeholders in ${relative}`); + } + assets.push({ + path: relative, bytes: contents.byteLength, gzipBytes: gzipSync(contents).byteLength, + sha256: createHash('sha256').update(contents).digest('hex'), + }); + } + } + assets.sort((a, b) => a.path.localeCompare(b.path)); + const keys: [string, string[]][] = JSON.parse(await fs.readFile(path.join(mobileRoot, 'out/nls.keys.json'), 'utf8')); + const messages: string[] = JSON.parse(await fs.readFile(path.join(mobileRoot, 'out/nls.messages.json'), 'utf8')); + assert.equal(keys.reduce((sum, [, keys]) => sum + keys.length, 0), messages.length, 'Mobile NLS keys and messages must match'); + assert.ok(keys.some(([module]) => module.startsWith('vs/sessions/contrib/mobile/')), 'Mobile NLS must include experimental messages'); + const manifest: MobileManifest = { + schemaVersion: 2, + kind: manifestKind, + build, + entrypoints, + extensions: await readMobileExtensions(mobileRoot, new Set(assets.map(asset => asset.path))), + assets, + preload: Object.values(entrypoints), + sizes: checkMobileBudgets(assets), + budgets: policy.budgets, + contributions, + localization: { keys: 'out/nls.keys.json', messages: 'out/nls.messages.json', metadata: 'out/nls.metadata.json' }, + }; + await fs.writeFile(path.join(mobileRoot, mobileManifestName), JSON.stringify(manifest, null, '\t') + '\n'); + console.log(`[mobile] ${assets.length} assets; ${manifest.extensions.length} extensions; ${manifest.sizes.initialGzipBytes} initial gzip bytes; ${manifest.sizes.runtimeGzipBytes} core runtime gzip bytes; ${manifest.sizes.extensionsGzipBytes} extension gzip bytes`); + return manifest; +} + +function isMissing(error: unknown): boolean { + return error instanceof Error && (error as NodeJS.ErrnoException).code === 'ENOENT'; +} diff --git a/build/next/mobilePolicy.json b/build/next/mobilePolicy.json new file mode 100644 index 000000000000..a6b10e8c88d3 --- /dev/null +++ b/build/next/mobilePolicy.json @@ -0,0 +1,198 @@ +{ + "_comment": "TODO: Lower these temporary size limits further to improve the mobile experience.", + "budgets": { + "workbenchJavaScriptGzipBytes": 6400000, + "workbenchCssGzipBytes": 275000, + "initialGzipBytes": 7000000, + "runtimeGzipBytes": 16500000, + "extensionsGzipBytes": 800000 + }, + "extensions": [ + "github-authentication", + "theme-defaults", + "theme-seti", + "cpp", + "css", + "diff", + "go", + "html", + "javascript", + "json", + "markdown-basics", + "python", + "rust", + "shellscript", + "typescript-basics", + "xml", + "yaml" + ], + "externalModules": [ + "@microsoft/1ds-core-js", + "@microsoft/1ds-post-js", + "module" + ], + "forbiddenModules": [ + "src/vs/sessions/contrib/chat/browser/chat.desktop.contribution.ts", + "src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts", + "src/vs/sessions/contrib/chat/browser/chatBackgroundTint.ts", + "src/vs/sessions/contrib/chat/browser/getThemeColorsTool.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/hostFilter.contribution.ts", + "src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts", + "src/vs/workbench/contrib/sessions/browser/defaultSessionRepositoryPicker.ts", + "src/vs/workbench/contrib/sessions/browser/defaultSessionsListPresentation.ts", + "src/vs/workbench/contrib/sessions/browser/chat/defaultChatViewFactory.ts", + "src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts", + "src/vs/workbench/contrib/sessions/browser/chatBackgroundService.ts", + "src/vs/workbench/contrib/sessions/browser/sessionsChatSurface.ts", + "src/vs/workbench/contrib/chat/browser/chatDefaultPresentation.contribution.ts", + "src/vs/workbench/contrib/chat/browser/widget/chatContentParts/defaultChatEditPresentation.ts", + "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts", + "src/vs/workbench/contrib/debug/browser/debug.contribution.ts", + "src/vs/workbench/contrib/terminal/terminal.all.ts", + "src/vs/workbench/contrib/search/browser/search.contribution.ts" + ], + "contributions": [ + "src/vs/editor/browser/widget/diffEditor/diffEditor.contribution.ts", + "src/vs/editor/browser/widget/diffEditor/registrations.contribution.ts", + "src/vs/editor/contrib/floatingMenu/browser/floatingMenu.contribution.ts", + "src/vs/editor/contrib/inlineCompletions/browser/inlineCompletions.contribution.ts", + "src/vs/editor/contrib/middleScroll/browser/middleScroll.contribution.ts", + "src/vs/editor/contrib/placeholderText/browser/placeholderText.contribution.ts", + "src/vs/editor/contrib/structuralDiff/common/structuralDiff.contribution.ts", + "src/vs/editor/editor.all.ts", + "src/vs/platform/actions/common/actions.contribution.ts", + "src/vs/platform/agentHost/common/agentHostStarter.config.contribution.ts", + "src/vs/sessions/browser/parts/dialogs/mobileDialog.web.contribution.ts", + "src/vs/sessions/contrib/accountMenu/browser/account.contribution.ts", + "src/vs/sessions/contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.ts", + "src/vs/sessions/contrib/aquarium/browser/aquarium.contribution.ts", + "src/vs/sessions/contrib/automations/browser/automations.contribution.ts", + "src/vs/sessions/contrib/changes/browser/changes.contribution.ts", + "src/vs/sessions/contrib/changes/browser/changesView.contribution.ts", + "src/vs/sessions/contrib/changes/browser/sessionActionContextKeys.contribution.ts", + "src/vs/sessions/contrib/chat/browser/chat.contribution.ts", + "src/vs/sessions/contrib/chat/browser/openSessionLinkOpener.contribution.ts", + "src/vs/sessions/contrib/chat/browser/requestOriginProvider.contribution.ts", + "src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts", + "src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts", + "src/vs/sessions/contrib/codeReview/browser/codeReview.contributions.ts", + "src/vs/sessions/contrib/configuration/browser/configuration.contribution.ts", + "src/vs/sessions/contrib/editor/browser/emptyFileEditor.contribution.ts", + "src/vs/sessions/contrib/fileTreeView/browser/fileTreeView.contribution.ts", + "src/vs/sessions/contrib/github/browser/github.contribution.ts", + "src/vs/sessions/contrib/layout/browser/sessions.mobile.layout.contribution.ts", + "src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts", + "src/vs/sessions/contrib/policyBlocked/browser/policyBlocked.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/agentHostAgentPicker.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/agentHostPolicyContinuationPresenter.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/agentHostSessionConfigPicker.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/agentHostSettings.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/agentSessionSettings.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.contribution.ts", + "src/vs/sessions/contrib/providers/agentHost/browser/openSubagentChat.contribution.ts", + "src/vs/sessions/contrib/providers/copilotChatSessions/browser/copilotChatSessions.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHost.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/connectionDiagnostics.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/missionControlAgentHost.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostFilter.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHost.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/tunnelAgentHost.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/webSocketAgentHost.contribution.ts", + "src/vs/sessions/contrib/providers/remoteAgentHost/browser/webTunnelAgentHostService.contribution.ts", + "src/vs/sessions/contrib/sessions/browser/customizationsToolbar.contribution.ts", + "src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts", + "src/vs/sessions/contrib/sessions/browser/sessionsTelemetry.contribution.ts", + "src/vs/sessions/contrib/workspace/browser/workspace.contribution.ts", + "src/vs/workbench/api/browser/extensionHost.contribution.ts", + "src/vs/workbench/browser/parts/editor/editor.contribution.ts", + "src/vs/workbench/browser/workbench.contribution.ts", + "src/vs/workbench/contrib/accessibility/browser/accessibility.contribution.ts", + "src/vs/workbench/contrib/accessibility/browser/extensionAccesibilityHelp.contribution.ts", + "src/vs/workbench/contrib/accessibilitySignals/browser/accessibilitySignal.contribution.ts", + "src/vs/workbench/contrib/agentsVoice/browser/agentsVoice.contribution.ts", + "src/vs/workbench/contrib/agentsVoice/browser/transcriptsView/voiceTranscripts.contribution.ts", + "src/vs/workbench/contrib/authentication/browser/authentication.contribution.ts", + "src/vs/workbench/contrib/browserView/browser/browserView.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatInputPicker.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/codexContinuation.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/localModel.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts", + "src/vs/workbench/contrib/chat/browser/agentSessions/experiments/agentSessionsExperiments.contribution.ts", + "src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.contribution.ts", + "src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizations.contribution.ts", + "src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplace.contribution.ts", + "src/vs/workbench/contrib/chat/browser/attachments/chatReferenceAttachmentWidget.contribution.ts", + "src/vs/workbench/contrib/chat/browser/attachments/transcriptContextAttachmentWidget.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chatDailyUsage.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chatManagement/chatManagement.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chatParticipant.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chatPetAchievements.contribution.ts", + "src/vs/workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.ts", + "src/vs/workbench/contrib/chat/browser/contextContrib/chatContext.contribution.ts", + "src/vs/workbench/contrib/chat/browser/customAgentUsage.contribution.ts", + "src/vs/workbench/contrib/chat/browser/editorChatUsage.contribution.ts", + "src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimeline.contribution.ts", + "src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHost.contribution.ts", + "src/vs/workbench/contrib/codeEditor/browser/codeEditor.contribution.ts", + "src/vs/workbench/contrib/dropOrPasteInto/browser/dropOrPasteInto.contribution.ts", + "src/vs/workbench/contrib/editTelemetry/browser/editTelemetry.contribution.ts", + "src/vs/workbench/contrib/externalUriOpener/common/externalUriOpener.contribution.ts", + "src/vs/workbench/contrib/files/browser/fileActions.contribution.ts", + "src/vs/workbench/contrib/files/browser/files.contribution.ts", + "src/vs/workbench/contrib/git/browser/git.contributions.ts", + "src/vs/workbench/contrib/list/browser/list.contribution.ts", + "src/vs/workbench/contrib/markdown/browser/markdown.contribution.ts", + "src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts", + "src/vs/workbench/contrib/multiDiffEditor/browser/icons.contribution.ts", + "src/vs/workbench/contrib/onboarding/browser/onboarding.contribution.ts", + "src/vs/workbench/contrib/onboarding/browser/onboardingTryout.contribution.ts", + "src/vs/workbench/contrib/opener/browser/opener.contribution.ts", + "src/vs/workbench/contrib/scm/browser/quickDiff.contribution.ts", + "src/vs/workbench/contrib/scm/browser/scm.service.contribution.ts", + "src/vs/workbench/contrib/search/browser/searchQuickAccess.contribution.ts", + "src/vs/workbench/contrib/share/browser/share.contribution.ts", + "src/vs/workbench/contrib/snippets/browser/snippets.service.contribution.ts", + "src/vs/workbench/contrib/speech/browser/speech.contribution.ts", + "src/vs/workbench/contrib/telemetry/browser/telemetry.contribution.ts", + "src/vs/workbench/contrib/terminal/browser/terminal.contribution.ts", + "src/vs/workbench/contrib/terminal/browser/terminal.web.contribution.ts", + "src/vs/workbench/contrib/terminal/common/environmentVariable.contribution.ts", + "src/vs/workbench/contrib/terminal/common/terminalExtensionPoints.contribution.ts", + "src/vs/workbench/contrib/terminalContrib/clipboard/browser/terminal.clipboard.contribution.ts", + "src/vs/workbench/contrib/terminalContrib/links/browser/terminal.links.contribution.ts", + "src/vs/workbench/contrib/terminalContrib/quickFix/browser/terminal.quickFix.contribution.ts", + "src/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.ts", + "src/vs/workbench/contrib/timeline/browser/timeline.service.contribution.ts", + "src/vs/workbench/contrib/url/browser/url.contribution.ts", + "src/vs/workbench/contrib/webview/browser/webview.contribution.ts", + "src/vs/workbench/contrib/webview/browser/webview.web.contribution.ts", + "src/vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution.ts", + "src/vs/workbench/services/policies/browser/managedSettingsUpdate.contribution.ts", + "src/vs/workbench/services/textMate/browser/textMateTokenizationFeature.contribution.ts", + "src/vs/workbench/services/treeSitter/browser/treeSitter.contribution.ts" + ], + "libraries": { + "@microsoft/1ds-core-js": ["bundle/ms.core.min.js"], + "@microsoft/1ds-post-js": ["bundle/ms.post.min.js"], + "@vscode/diff": ["dist/index.js"], + "@vscode/iconv-lite-umd": ["lib/iconv-lite-umd.js"], + "@vscode/tree-sitter-wasm": ["wasm/*.wasm", "wasm/tree-sitter.js"], + "@vscode/vscode-languagedetection": ["dist/lib/index.js", "model/*"], + "@xterm/addon-clipboard": ["lib/addon-clipboard.js"], + "@xterm/addon-image": ["lib/addon-image.js"], + "@xterm/addon-ligatures": ["lib/addon-ligatures.js"], + "@xterm/addon-progress": ["lib/addon-progress.js"], + "@xterm/addon-search": ["lib/addon-search.js"], + "@xterm/addon-serialize": ["lib/addon-serialize.js"], + "@xterm/addon-unicode11": ["lib/addon-unicode11.js"], + "@xterm/addon-webgl": ["lib/addon-webgl.js"], + "@xterm/xterm": ["lib/xterm.js", "css/xterm.css"], + "jschardet": ["dist/jschardet.min.js"], + "katex": ["dist/katex.min.js", "dist/katex.min.css", "dist/fonts/*"], + "tas-client": ["dist/tas-client.min.js"], + "vscode-oniguruma": ["release/main.js", "release/onig.wasm"], + "vscode-textmate": ["release/main.js"] + } +} diff --git a/build/next/resources.ts b/build/next/resources.ts index bbd34e011b3c..e76a1e3557ef 100644 --- a/build/next/resources.ts +++ b/build/next/resources.ts @@ -164,6 +164,24 @@ const webResourcePatterns = [ 'vs/workbench/services/extensionManagement/common/media/*.png', ]; +const mobileResourcePatterns = [ + 'vs/editor/common/languages/highlights/*.scm', + 'vs/editor/common/languages/injections/*.scm', + 'vs/workbench/browser/media/code-icon.svg', + 'vs/workbench/browser/parts/editor/media/letterpress*.svg', + 'vs/workbench/contrib/chat/browser/widget/media/chatPet/**/*.{gif,png}', + 'vs/sessions/contrib/chat/browser/media/*.svg', + 'vs/sessions/contrib/welcome/browser/media/themePreviews/*.svg', + 'vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html', + 'vs/workbench/contrib/webview/browser/pre/*.html', + 'vs/workbench/contrib/webview/browser/pre/*.js', + 'vs/platform/accessibilitySignal/browser/media/*.mp3', + 'vs/workbench/contrib/agentsVoice/browser/media/*.mp3', + 'vs/workbench/services/extensionManagement/common/media/*.{svg,png}', + 'vs/workbench/contrib/extensions/browser/media/*.{svg,png}', + 'vs/sessions/skills/**/SKILL.md', +]; + function getResourcePatternsForTarget(target: BuildTarget): string[] { switch (target) { case 'desktop': @@ -174,6 +192,8 @@ function getResourcePatternsForTarget(target: BuildTarget): string[] { return serverWebResourcePatterns; case 'web': return webResourcePatterns; + case 'mobile': + return mobileResourcePatterns; default: throw new Error(`Unknown target: ${target}`); } diff --git a/build/next/test/mobile.test.ts b/build/next/test/mobile.test.ts new file mode 100644 index 000000000000..934f7b4166ca --- /dev/null +++ b/build/next/test/mobile.test.ts @@ -0,0 +1,443 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { createHash } from 'node:crypto'; +import * as fs from 'node:fs/promises'; +import * as path from 'node:path'; +import { suite, test, type TestContext } from 'node:test'; +import { gzipSync } from 'node:zlib'; +import * as esbuild from 'esbuild'; +import ts from 'typescript'; +import { + checkMobileBudgets, checkMobileDependencies, checkMobilePath, mobileDirectory, + mobileEntryPoint, mobileManifestName, mobilePlugin, mobileQuality, + packageMobileExtensions, prepareMobile, readMobileExtensions, + writeMobileManifest, type MobileAsset, +} from '../mobile.ts'; +import { getBundleOptions } from '../bundle.ts'; +import { getBootstrapEntryPointsForTarget } from '../../lib/esbuild.ts'; +import { writePnpmLockfile } from '../../lib/test/pnpmLockfileFixture.ts'; +import { getResourcePaths } from '../resources.ts'; +import policy from '../mobilePolicy.json' with { type: 'json' }; +import packageJson from '../../../package.json' with { type: 'json' }; + +const entrypoints = { + workbench: `out/${mobileEntryPoint}.js`, + stylesheet: `out/${mobileEntryPoint}.css`, + nls: 'out/nls.messages.js', +}; +const build = { commit: '0123456789abcdef0123456789abcdef01234567', version: '1.0.0', date: '2026-10-05T00:00:00Z', quality: 'dev' as const }; + +async function createFixture(t: TestContext) { + const directory = path.resolve(import.meta.dirname, '../../../.build/mobile-tests'); + await fs.mkdir(directory, { recursive: true }); + const root = await fs.mkdtemp(path.join(directory, 'fixture-')); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const write = async (file: string, contents: string) => { + await fs.mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await fs.writeFile(path.join(root, file), contents); + }; + const mobileRoot = path.join(root, mobileDirectory); + const out = `${mobileDirectory}/out`; + return { root, mobileRoot, out, write }; +} + +function asset(file: string, gzipBytes = 1): MobileAsset { + return { path: file, bytes: gzipBytes, gzipBytes, sha256: '0'.repeat(64) }; +} + +suite('isolated mobile package', () => { + test('mobile bootstrap excludes native entries without changing standard targets', () => { + assert.deepStrictEqual(['desktop', 'server', 'server-web', 'web', 'mobile'].map(target => + getBootstrapEntryPointsForTarget(target as Parameters[0])), [ + ['main', 'mainImpl', 'cli', 'bootstrap-fork'], + ['server-main', 'server-cli', 'bootstrap-fork'], + ['server-main', 'server-cli', 'bootstrap-fork'], + [], + [], + ]); + }); + + test('refuses alternate output paths before changing any files', async t => { + const { root, write } = await createFixture(t); + await write('out/keep', 'normal output'); + await write('out-mobile-preview/keep', 'previous output'); + for (const out of ['out', 'out-build', 'out-vscode-web', 'out-mobile-preview/out', '.', '../out', `${mobileDirectory}/out/../other`]) { + await assert.rejects(prepareMobile(root, out), /output must be/); + } + assert.deepStrictEqual({ + normal: await fs.readFile(path.join(root, 'out/keep'), 'utf8'), + previous: await fs.readFile(path.join(root, 'out-mobile-preview/keep'), 'utf8'), + }, { normal: 'normal output', previous: 'previous output' }); + }); + + test('refuses an existing directory without its ownership marker', async t => { + const { root, out, write } = await createFixture(t); + await write(`${mobileDirectory}/unrelated.txt`, 'keep'); + await assert.rejects(prepareMobile(root, out), /unowned/); + assert.equal(await fs.readFile(path.join(root, mobileDirectory, 'unrelated.txt'), 'utf8'), 'keep'); + }); + + test('does not follow a symlinked ownership marker', { skip: process.platform === 'win32' ? 'File symlinks require elevated privileges' : false }, async t => { + const { root, out, mobileRoot, write } = await createFixture(t); + await write('marker.json', '{"schemaVersion":1,"kind":"sessions-mobile"}'); + await fs.mkdir(mobileRoot); + await fs.symlink(path.join(root, 'marker.json'), path.join(mobileRoot, '.mobile-build.json')); + await assert.rejects(prepareMobile(root, out), /unowned/); + assert.equal(await fs.readFile(path.join(root, 'marker.json'), 'utf8'), '{"schemaVersion":1,"kind":"sessions-mobile"}'); + }); + + for (const location of ['', 'out', 'node_modules', 'extensions']) { + test(`refuses a symlink at the ${location || 'package root'} boundary`, async t => { + const { root, out, mobileRoot } = await createFixture(t); + const other = path.join(root, 'elsewhere'); + await fs.mkdir(other); + if (location) { + await prepareMobile(root, out); + } + await fs.symlink(other, path.join(mobileRoot, location), 'junction'); + await assert.rejects(prepareMobile(root, out), /regular directory/); + }); + } + + test('invalidates completed output before a rebuild and clears only owned libraries', async t => { + const { root, out, write, mobileRoot } = await createFixture(t); + const release = await prepareMobile(root, out); + await write(`${mobileDirectory}/${mobileManifestName}`, '{}'); + await write(`${mobileDirectory}/node_modules/old.js`, 'old'); + await write(`${mobileDirectory}/extensions/old/package.json`, '{}'); + await write('out-build/nls.messages.json', 'original'); + await release(); + const releaseRebuild = await prepareMobile(root, out); + await releaseRebuild(); + assert.deepStrictEqual({ + contents: (await fs.readdir(mobileRoot)).sort(), + normalNls: await fs.readFile(path.join(root, 'out-build/nls.messages.json'), 'utf8'), + }, { contents: ['.mobile-build.json'], normalNls: 'original' }); + }); + + test('concurrent builds cannot invalidate each other or publish mixed artifacts', async t => { + const { root, out, write, mobileRoot } = await createFixture(t); + const release = await prepareMobile(root, out); + await write(`${mobileDirectory}/${mobileManifestName}`, 'first build'); + await assert.rejects(prepareMobile(root, out), /build lock/); + assert.equal(await fs.readFile(path.join(mobileRoot, mobileManifestName), 'utf8'), 'first build'); + await release(); + const releaseNext = await prepareMobile(root, out); + await release(); + await assert.rejects(prepareMobile(root, out), /build lock/); + await releaseNext(); + await assert.rejects(fs.access(path.join(mobileRoot, mobileManifestName)), { code: 'ENOENT' }); + }); + + test('blocks full entries, native code, test fixtures and unreviewed transitive contributions', () => { + for (const file of [ + 'src/vs/sessions/sessions.common.main.ts', + 'src/vs/workbench/workbench.web.main.internal.ts', + 'src/vs/base/node/terminal.ts', + 'src/vs/sessions/electron-browser/sessions.ts', + 'src/vs/sessions/test/web.test.ts', + 'src/vs/workbench/contrib/newFeature/browser/newFeature.contribution.ts', + 'src\\vs\\sessions\\contrib\\chat\\browser\\chat.desktop.contribution.ts', + 'src/vs/workbench/contrib/sessions/browser/defaultSessionRepositoryPicker.ts', + 'src/vs/workbench/contrib/sessions/browser/defaultSessionsListPresentation.ts', + 'src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts', + 'src/vs/workbench/contrib/chat/browser/chatDefaultPresentation.contribution.ts', + 'src/vs/workbench/contrib/chat/browser/widget/chatContentParts/defaultChatEditPresentation.ts', + ]) { + assert.throws(() => checkMobileDependencies([file]), /boundary failed/); + } + assert.deepStrictEqual(checkMobileDependencies([ + 'src/vs/workbench/contrib/chat/common/model/chatModel.ts', + 'src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts', + 'src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts', + ]), ['src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts']); + }); + + test('dependency checks inspect transitive esbuild inputs, not just entry imports', async t => { + const { root, write } = await createFixture(t); + await write('src/entry.ts', 'import \'./bridge.js\';'); + await write('src/bridge.ts', 'import \'./vs/sessions/contrib/accidental/browser/accidental.contribution.js\';'); + await write('src/vs/sessions/contrib/accidental/browser/accidental.contribution.ts', 'console.log("unexpected registration");'); + await assert.rejects(esbuild.build({ + ...getBundleOptions(true, 'neutral'), + absWorkingDir: root, entryPoints: ['src/entry.ts'], outfile: path.join(root, 'out/entry.js'), + metafile: true, plugins: [mobilePlugin(root)], logLevel: 'silent', + }), /Unreviewed contribution/); + }); + + test('the measured contribution baseline has no duplicates or forbidden modules', () => { + assert.equal(new Set(policy.contributions).size, policy.contributions.length); + assert.deepStrictEqual(checkMobileDependencies(policy.contributions), [...policy.contributions].sort()); + }); + + test('copied runtime libraries are repository dependencies, not implicit installs', () => { + assert.deepStrictEqual(Object.keys(policy.libraries).filter(name => !Object.hasOwn(packageJson.dependencies, name)), []); + }); + + test('quality defaults to dev locally but requires the matching product mixin in CI', () => { + assert.deepStrictEqual([ + mobileQuality(undefined), + mobileQuality('insider', 'insider'), + mobileQuality('stable', 'stable'), + mobileQuality('exploration', 'exploration'), + ], ['dev', 'insider', 'stable', 'exploration']); + assert.throws(() => mobileQuality('preview'), /Invalid.*quality/); + assert.throws(() => mobileQuality(undefined, 'insider'), /matching product.json mixin/); + }); + + test('artifact paths support source grammar filenames without URL escapes or traversal', () => { + checkMobilePath('extensions/javascript/syntaxes/Regular Expressions (JavaScript).tmLanguage'); + for (const file of ['../outside', 'out/../outside', 'out//file', 'out/file.', 'out/file ', 'out/%20file', 'out/file?query']) { + assert.throws(() => checkMobilePath(file), /Invalid mobile relative path/); + } + }); + + test('curated extensions contain only GitHub authentication and static language/theme contributions', async () => { + const root = path.resolve(import.meta.dirname, '../../..'); + const manifests = await Promise.all(policy.extensions.map(async name => JSON.parse(await fs.readFile(path.join(root, 'extensions', name, 'package.json'), 'utf8')))); + assert.deepStrictEqual({ + code: manifests.filter(manifest => manifest.main || manifest.browser).map(manifest => manifest.name), + required: manifests.filter(manifest => ['github-authentication', 'theme-defaults', 'vscode-theme-seti'].includes(manifest.name)).map(manifest => `${manifest.publisher}.${manifest.name}`).sort(), + }, { code: ['github-authentication'], required: ['vscode.github-authentication', 'vscode.theme-defaults', 'vscode.vscode-theme-seti'] }); + }); + + for (const nodeLinker of ['hoisted', 'isolated']) { + test(`extension packaging builds fresh browser output and preserves explicit dependencies and licenses (${nodeLinker})`, async t => { + const { root, mobileRoot, write } = await createFixture(t); + const dependency = nodeLinker === 'hoisted' + ? 'extensions/auth/node_modules/unused' + : 'extensions/auth/node_modules/.pnpm/unused@1.0.0/node_modules/unused'; + const mappedSource = nodeLinker === 'hoisted' + ? `${dependency}/src/original.ts` + : 'extensions/auth/node_modules/.pnpm/unused@1.0.0/src/original.ts'; + const sourceMapEntry = path.relative(path.join(mobileRoot, 'extensions/auth/dist/browser'), path.join(root, mappedSource)).replaceAll('\\', '/'); + await write('LICENSE.txt', 'MIT license'); + await write('extensions/auth/package.json', JSON.stringify({ + name: 'auth', publisher: 'vscode', version: '1.0.0', license: 'MIT', engines: { vscode: '^1.0.0' }, + main: './out/extension.js', browser: './dist/browser/extension.js', + activationEvents: [], extensionDependencies: ['vscode.grammar'], scripts: { build: 'unused' }, dependencies: { unused: '*' }, + })); + await write('extensions/auth/.vscodeignore', 'esbuild.browser.mts\nout/**\n'); + await write('extensions/auth/esbuild.browser.mts', ` + import { mkdir, writeFile } from 'node:fs/promises'; + import path from 'node:path'; + const output = path.join(process.argv[process.argv.indexOf('--outputRoot') + 1], 'browser'); + await mkdir(output, { recursive: true }); + await writeFile(path.join(output, 'extension.js'), 'fresh browser build'); + await writeFile(path.join(output, 'extension.js.map'), JSON.stringify({ sources: [${JSON.stringify(sourceMapEntry)}] })); + `); + await write('extensions/auth/dist/browser/extension.js', 'stale watcher output'); + await write('extensions/auth/dist/node/extension.js', 'desktop output'); + await write('extensions/auth/out/unrelated.js', 'old output'); + await write('extensions/auth/ThirdPartyNotices.txt', 'Extension notices'); + await write(`${dependency}/package.json`, '{"name":"unused","version":"1.0.0","license":"MIT"}'); + await write(`${dependency}/LICENSE`, 'Dependency license text'); + if (nodeLinker === 'isolated') { + await fs.symlink(path.join(root, dependency), path.join(root, 'extensions/auth/node_modules/unused'), 'junction'); + } + writePnpmLockfile(path.join(root, 'extensions/auth/pnpm-lock.yaml'), { unused: { version: '1.0.0' } }); + await write('extensions/auth/node_modules/.modules.yaml', JSON.stringify({ + nodeLinker, + hoistedLocations: nodeLinker === 'hoisted' ? { 'unused@1.0.0': ['node_modules/unused'] } : undefined, + })); + await write('extensions/grammar/package.json', '{"name":"grammar","publisher":"vscode","version":"1.0.0","license":"MIT","engines":{"vscode":"^1.0.0"}}'); + await packageMobileExtensions(root, ['auth', 'grammar']); + const manifest = JSON.parse(await fs.readFile(path.join(mobileRoot, 'extensions/auth/package.json'), 'utf8')); + assert.deepStrictEqual({ + manifest, + browser: await fs.readFile(path.join(mobileRoot, 'extensions/auth/dist/browser/extension.js'), 'utf8'), + license: await fs.readFile(path.join(mobileRoot, 'extensions/auth/LICENSE.txt'), 'utf8'), + directories: (await fs.readdir(path.join(mobileRoot, 'extensions/auth/dist'))).sort(), + checkout: await fs.readFile(path.join(root, 'extensions/auth/dist/browser/extension.js'), 'utf8'), + notices: await fs.readFile(path.join(mobileRoot, 'extensions/auth/ThirdPartyNotices.txt'), 'utf8'), + }, { + manifest: { name: 'auth', publisher: 'vscode', version: '1.0.0', license: 'MIT', engines: { vscode: '^1.0.0' }, browser: './dist/browser/extension.js', activationEvents: [], extensionDependencies: ['vscode.grammar'] }, + browser: 'fresh browser build', license: 'MIT license', directories: ['browser'], checkout: 'stale watcher output', + notices: 'Extension notices\n\nunused@1.0.0\nLicense: MIT\n\nDependency license text\n', + }); + }); + } + + test('unidentified pnpm source-map dependencies fail instead of omitting their licenses', async t => { + const { root, mobileRoot, write } = await createFixture(t); + const sourceMapEntry = path.relative(path.join(mobileRoot, 'extensions/auth/dist/browser'), path.join(root, 'node_modules/.pnpm/missing@1.0.0/src/original.ts')).replaceAll('\\', '/'); + await write('LICENSE.txt', 'MIT license'); + await write('extensions/auth/package.json', '{"name":"auth","publisher":"vscode","version":"1.0.0","license":"MIT","browser":"./dist/browser/extension.js","activationEvents":["*"],"engines":{"vscode":"^1.0.0"}}'); + await write('extensions/auth/.vscodeignore', 'esbuild.browser.mts\n'); + await write('extensions/auth/esbuild.browser.mts', ` + import { mkdir, writeFile } from 'node:fs/promises'; + import path from 'node:path'; + const output = path.join(process.argv[process.argv.indexOf('--outputRoot') + 1], 'browser'); + await mkdir(output, { recursive: true }); + await writeFile(path.join(output, 'extension.js'), 'browser build'); + await writeFile(path.join(output, 'extension.js.map'), JSON.stringify({ sources: [${JSON.stringify(sourceMapEntry)}] })); + `); + writePnpmLockfile(path.join(root, 'extensions/auth/pnpm-lock.yaml'), {}); + await write('extensions/auth/node_modules/.modules.yaml', '{"nodeLinker":"isolated"}'); + await assert.rejects(packageMobileExtensions(root, ['auth']), /Unidentified pnpm source-map dependency/); + }); + + test('missing extension sources, browser build inputs and required dependencies fail explicitly', async t => { + const { root, write } = await createFixture(t); + await assert.rejects(packageMobileExtensions(root, ['missing']), /ENOENT/); + await write('extensions/auth/package.json', '{"name":"auth","publisher":"vscode","version":"1.0.0","browser":"./dist/browser/extension.js"}'); + await assert.rejects(packageMobileExtensions(root, ['auth']), /esbuild.browser.mts/); + await write('extensions/auth/package.json', '{"name":"auth","publisher":"vscode","version":"1.0.0","extensionDependencies":["vscode.missing"]}'); + await assert.rejects(packageMobileExtensions(root, ['auth']), /Required extension vscode.missing/); + }); + + test('packaged theme fonts and browser entries cannot point outside their extension', async t => { + const { mobileRoot, write } = await createFixture(t); + const manifest = { name: 'theme', publisher: 'vscode', version: '1.0.0', contributes: { iconThemes: [{ path: './icons/theme.json' }] } }; + await write(`${mobileDirectory}/extensions/theme/package.json`, JSON.stringify(manifest)); + await write(`${mobileDirectory}/extensions/theme/icons/theme.json`, '{"fonts":[{"src":[{"path":"font.woff"}]}]}'); + const assets = new Set(['extensions/theme/package.json', 'extensions/theme/icons/theme.json']); + await assert.rejects(readMobileExtensions(mobileRoot, assets), /Missing packaged extension resource: .*font.woff/); + await write(`${mobileDirectory}/extensions/theme/package.json`, JSON.stringify({ ...manifest, browser: '../../../checkout.js' })); + await assert.rejects(readMobileExtensions(mobileRoot, assets), /Invalid mobile relative path|Missing packaged extension resource/); + }); + + test('retained terminal-output rendering has every string-loaded xterm runtime dependency', async () => { + const repositoryRoot = path.resolve(import.meta.dirname, '../../..'); + const libraries: Record = policy.libraries; + const missing: string[] = []; + let found = 0; + for (const file of [ + 'src/vs/workbench/contrib/terminal/browser/terminalInstance.ts', + 'src/vs/workbench/contrib/terminal/browser/xterm/xtermAddonImporter.ts', + ]) { + const source = ts.createSourceFile(file, await fs.readFile(path.join(repositoryRoot, file), 'utf8'), ts.ScriptTarget.Latest, true); + const visit = (node: ts.Node) => { + if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'importAMDNodeModule') { + const [module, resource] = node.arguments; + if (module && resource && ts.isStringLiteral(module) && ts.isStringLiteral(resource) && module.text.startsWith('@xterm/')) { + found++; + if (!libraries[module.text]?.includes(resource.text)) { + missing.push(`${module.text}/${resource.text}`); + } + } + } + ts.forEachChild(node, visit); + }; + visit(source); + } + assert.ok(found > 0, 'Inspect the retained output renderer if its runtime loading pattern changes'); + assert.deepStrictEqual(missing, []); + }); + + test('new bare runtime imports cannot rely on the normal workbench import map', async t => { + const { root, write } = await createFixture(t); + await write('src/entry.ts', 'import { show } from \'desktop-widget\'; show();'); + await assert.rejects(esbuild.build({ + ...getBundleOptions(true, 'neutral'), + absWorkingDir: root, entryPoints: ['src/entry.ts'], outfile: path.join(root, 'out/entry.js'), + metafile: true, plugins: [mobilePlugin(root)], logLevel: 'silent', + }), /Unpackaged mobile dependency: desktop-widget/); + }); + + test('budgets accept the exact limit and fail one byte over it', () => { + const assets = [asset(entrypoints.workbench, 10), asset(entrypoints.stylesheet, 4), asset(entrypoints.nls, 3), asset('node_modules/runtime.js', 5), asset('extensions/example/runtime.js', 7)]; + const budgets = { workbenchJavaScriptGzipBytes: 10, workbenchCssGzipBytes: 4, initialGzipBytes: 17, runtimeGzipBytes: 22, extensionsGzipBytes: 7 }; + assert.deepStrictEqual(checkMobileBudgets(assets, budgets), { initialGzipBytes: 17, runtimeGzipBytes: 22, extensionsGzipBytes: 7 }); + for (const key of Object.keys(budgets) as (keyof typeof budgets)[]) { + assert.throws(() => checkMobileBudgets(assets, { ...budgets, [key]: budgets[key] - 1 }), new RegExp(key)); + } + }); + + test('debug maps and localization metadata are inventoried but not counted as runtime downloads', () => { + assert.deepStrictEqual(checkMobileBudgets([ + ...Object.values(entrypoints).map(file => asset(file)), + asset('out/nls.metadata.json', 100000000), asset(`${entrypoints.workbench}.map`, 100000000), + ]), { initialGzipBytes: 3, runtimeGzipBytes: 3, extensionsGzipBytes: 0 }); + assert.throws(() => checkMobileBudgets([asset(entrypoints.workbench)]), /missing .*\.css/); + }); + + test('publishes only a completed package with its own asset and localization inventory', async t => { + const { root, out, mobileRoot, write } = await createFixture(t); + await prepareMobile(root, out); + const files: Record = { + [entrypoints.workbench]: 'export const example = 1;', + [entrypoints.stylesheet]: '.mobile-workbench { display: block; }', + [entrypoints.nls]: 'globalThis._VSCODE_NLS_MESSAGES=["Mobile"];', + 'out/nls.messages.json': '["Mobile"]', + 'out/nls.keys.json': '[["vs/sessions/contrib/mobile/browser/example",["title"]]]', + 'out/nls.metadata.json': '{"keys":{},"messages":{}}', + 'node_modules/example/runtime.js': 'example();', + 'extensions/example/package.json': '{"name":"example","publisher":"vscode","version":"1.0.0"}', + }; + for (const [file, contents] of Object.entries(files)) { + await write(`${mobileDirectory}/${file}`, contents); + } + await write('out-build/nls.messages.json', '["Normal"]'); + const manifest = await writeMobileManifest(root, build, []); + assert.deepStrictEqual({ + schemaVersion: manifest.schemaVersion, kind: manifest.kind, entrypoints: manifest.entrypoints, + preload: manifest.preload, extensions: manifest.extensions, normalNls: await fs.readFile(path.join(root, 'out-build/nls.messages.json'), 'utf8'), + assets: manifest.assets, stored: JSON.parse(await fs.readFile(path.join(mobileRoot, mobileManifestName), 'utf8')), + }, { + schemaVersion: 2, kind: 'sessions-mobile', entrypoints, preload: Object.values(entrypoints), + extensions: [{ id: 'vscode.example', path: 'extensions/example' }], normalNls: '["Normal"]', + assets: Object.entries(files).sort(([a], [b]) => a.localeCompare(b)).map(([file, contents]) => ({ + path: file, bytes: Buffer.byteLength(contents), gzipBytes: gzipSync(contents).byteLength, + sha256: createHash('sha256').update(contents).digest('hex'), + })), + stored: manifest, + }); + }); + + test('an unresolved localization placeholder prevents publication', async t => { + const { root, out, mobileRoot, write } = await createFixture(t); + await prepareMobile(root, out); + await write(`${out}/broken.js`, 'localize("%%NLS:example:title%%", "Title");'); + await fs.mkdir(path.join(mobileRoot, 'node_modules')); + await assert.rejects(writeMobileManifest(root, build, []), /Unresolved localization/); + await assert.rejects(fs.access(path.join(mobileRoot, mobileManifestName)), { code: 'ENOENT' }); + }); + + test('does not publish a package containing an asset symlink', { skip: process.platform === 'win32' ? 'File symlinks require elevated privileges' : false }, async t => { + const { root, out, mobileRoot, write } = await createFixture(t); + await prepareMobile(root, out); + await write('external.js', 'outside();'); + await fs.mkdir(path.join(mobileRoot, 'out')); + await fs.symlink(path.join(root, 'external.js'), path.join(mobileRoot, 'out', 'linked.js')); + await assert.rejects(writeMobileManifest(root, build, []), /Symlinks are not allowed/); + await assert.rejects(fs.access(path.join(mobileRoot, mobileManifestName)), { code: 'ENOENT' }); + }); + + test('mobile resources package the same built-in skill definitions as desktop', async t => { + const { root, write } = await createFixture(t); + const skillFiles = ['code-review', 'commit', 'create-pr', 'generate-chat-background'] + .map(skill => `vs/sessions/skills/${skill}/SKILL.md`); + for (const file of skillFiles) { + await write(file, '# Test skill'); + } + await write('vs/sessions/skills/commit/README.md', 'Not a skill definition'); + assert.deepStrictEqual(await Promise.all((['desktop', 'mobile'] as const) + .map(target => getResourcePaths(root, target))), [skillFiles, skillFiles]); + }); + + test('mobile resources keep worker frames and accessibility audio without shipping a full workbench shell', async t => { + const { root, write } = await createFixture(t); + for (const file of [ + 'vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html', + 'vs/platform/accessibilitySignal/browser/media/error.mp3', + 'vs/code/browser/workbench/workbench.html', + 'vs/sessions/browser/mobile/media/mobileWorkbench.css', + 'vs/sessions/services/chatBackground/browser/media/koi-dark.webp', + 'vs/sessions/services/chatBackground/browser/media/koi-dark-static.webp', + 'vs/sessions/services/chatBackground/browser/media/koi-light.webp', + 'vs/sessions/services/chatBackground/browser/media/koi-light-static.webp', + 'vs/sessions/test/fixture.html', + ]) { + await write(file, ''); + } + assert.deepStrictEqual(await getResourcePaths(root, 'mobile'), [ + 'vs/platform/accessibilitySignal/browser/media/error.mp3', + 'vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html', + ]); + }); +}); diff --git a/build/oxlint.ts b/build/oxlint.ts new file mode 100644 index 000000000000..ea738f7c7a4f --- /dev/null +++ b/build/oxlint.ts @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { spawn } from 'child_process'; +import { statSync } from 'fs'; +import { createRequire } from 'module'; +import { availableParallelism } from 'os'; +import path from 'path'; +import { parseArgs } from 'util'; +import { getChangedFilesScope, getEslintScope, typeAwareLintFolders } from './lib/changedFiles.ts'; + +// Runs oxlint with the rules of eslint.config.js (see oxlint.config.ts) and reports like `npm run eslint`, with +// ESLint's rule names, which the editor and disable directives use. oxlint runs JS plugin rules on one thread per +// process, so a large run is split into processes by folder. The extensions that use rules with type information run +// in a separate process with `--type-aware`, so that only that process builds TypeScript programs. + +const root = path.dirname(import.meta.dirname); +const oxlintBin = path.join(path.dirname(createRequire(import.meta.url).resolve('oxlint/package.json')), 'bin', 'oxlint'); + +/** Below this length a command line fits on every platform (Windows allows 32,767 characters). */ +const maxArgumentsLength = 24_000; + +/** Files per process below which starting another process costs more than it saves. */ +const minFilesPerProcess = 500; + +interface IOxlintDiagnostic { + readonly message: string; + readonly code?: string; + readonly severity: 'warning' | 'error' | string; + readonly filename: string; + readonly labels?: readonly { readonly span: { readonly line: number; readonly column: number } }[]; +} + +interface IOxlintOutput { + readonly diagnostics: readonly IOxlintDiagnostic[]; + readonly number_of_files: number; +} + +interface IWeightedFile { + readonly path: string; + readonly weight: number; +} + +/** + * Returns the ESLint name of the rule that an oxlint diagnostic code such as `eslint(no-var)`, `typescript(no-explicit-any)` + * or `local(code-layering)` names. + */ +export function toEslintRuleId(code: string | undefined): string | undefined { + const match = code ? /^(?.+)\((?.+)\)$/.exec(code) : null; + if (!match?.groups) { + return code || undefined; + } + const { plugin, rule } = match.groups; + switch (plugin) { + case 'eslint': return rule; + case 'typescript': return `@typescript-eslint/${rule}`; + default: return `${plugin}/${rule}`; + } +} + +function isInFolder(file: string, folder: string): boolean { + return file.startsWith(folder.endsWith('/') ? folder : `${folder}/`); +} + +/** + * Splits complete folders of files into `count` groups of paths of about the same size. A path is a folder when all of + * its files are in the group, so that command lines stay short; folders that contain one of `excludedFolders` are + * never passed whole, because their excluded files are linted elsewhere. + */ +export function splitByFolder(files: readonly IWeightedFile[], count: number, excludedFolders: readonly string[]): string[][] { + interface IFolder { readonly path: string; weight: number; readonly folders: Map; readonly files: IWeightedFile[] } + const top: IFolder = { path: '', weight: 0, folders: new Map(), files: [] }; + for (const file of files) { + const segments = file.path.split('/'); + let folder = top; + folder.weight += file.weight; + for (const segment of segments.slice(0, -1)) { + let child = folder.folders.get(segment); + if (!child) { + child = { path: folder.path ? `${folder.path}/${segment}` : segment, weight: 0, folders: new Map(), files: [] }; + folder.folders.set(segment, child); + } + child.weight += file.weight; + folder = child; + } + folder.files.push(file); + } + + // Chunks of at most a quarter of a group's share let the groups balance. + const maxChunk = top.weight / (count * 4); + const chunks: IWeightedFile[] = []; + const visit = (folder: IFolder) => { + const containsExcluded = excludedFolders.some(excluded => isInFolder(excluded, folder.path) || excluded.replace(/\/$/, '') === folder.path); + if (folder !== top && folder.weight <= maxChunk && !containsExcluded) { + chunks.push({ path: folder.path, weight: folder.weight }); + return; + } + folder.folders.forEach(visit); + chunks.push(...folder.files); + }; + visit(top); + + const groups = Array.from({ length: count }, () => ({ paths: [] as string[], weight: 0 })); + for (const chunk of chunks.sort((a, b) => b.weight - a.weight || a.path.localeCompare(b.path))) { + const lightest = groups.reduce((min, group) => group.weight < min.weight ? group : min); + lightest.paths.push(chunk.path); + lightest.weight += chunk.weight; + } + return groups.map(group => group.paths.sort()).filter(paths => paths.length > 0); +} + +/** + * Splits a list of files into at least `count` groups (fewer if there are fewer files) of about the same length, + * whose command lines stay below `maxLength` characters unless a single path is longer. + */ +export function splitFiles(files: readonly string[], count: number, maxLength = maxArgumentsLength): string[][] { + const length = files.reduce((sum, file) => sum + file.length + 1, 0); + const groupCount = Math.min(files.length, Math.max(count, Math.ceil(length / maxLength))); + const groups = Array.from({ length: groupCount }, () => ({ paths: [] as string[], length: 0 })); + for (const file of files) { + let lightest = groups.reduce((min, group) => group.length < min.length ? group : min); + if (lightest.paths.length > 0 && lightest.length + file.length + 1 > maxLength) { + lightest = { paths: [], length: 0 }; + groups.push(lightest); + } + lightest.paths.push(file); + lightest.length += file.length + 1; + } + return groups.map(group => group.paths); +} + +function runOxlint(args: readonly string[]): Promise { + const started = Date.now(); + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [oxlintBin, '--format', 'json', '--no-error-on-unmatched-pattern', ...args], { cwd: root }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', data => stdout += data); + child.stderr.on('data', data => stderr += data); + child.on('error', reject); + child.on('close', code => { + try { + resolve({ ...JSON.parse(stdout), duration: Date.now() - started }); + } catch { + reject(new Error(`oxlint exited with ${code}: ${stderr || stdout}`)); + } + }); + }); +} + +async function listFiles(paths: readonly string[]): Promise { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [oxlintBin, '--debug=files', '--no-error-on-unmatched-pattern', ...paths], { cwd: root }); + let stdout = ''; + child.stdout.on('data', data => stdout += data); + child.on('error', reject); + child.on('close', code => code === 0 ? resolve(stdout.split(/\r?\n/).filter(Boolean).map(file => file.replace(/\\/g, '/'))) : reject(new Error(`oxlint --debug=files exited with ${code}`))); + }); +} + +async function runAll(tasks: readonly (() => Promise)[], concurrency: number): Promise { + const results: T[] = new Array(tasks.length); + let next = 0; + await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, async () => { + while (next < tasks.length) { + const index = next++; + results[index] = await tasks[index](); + } + })); + return results; +} + +/** + * Formats diagnostics like ESLint's compact formatter, with ESLint's rule names, so that the output of both linters + * reads the same and can be diffed. + */ +export function formatCompact(diagnostics: readonly IOxlintDiagnostic[], cwd: string): string { + const lines = diagnostics.map(diagnostic => { + const { line, column } = diagnostic.labels?.[0]?.span ?? { line: 0, column: 0 }; + const rule = toEslintRuleId(diagnostic.code); + const severity = diagnostic.severity === 'error' ? 'Error' : 'Warning'; + return { file: path.resolve(cwd, diagnostic.filename), line, column, text: `line ${line}, col ${column}, ${severity} - ${diagnostic.message}${rule ? ` (${rule})` : ''}` }; + }); + lines.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column); + return lines.map(line => `${line.file}: ${line.text}`).join('\n'); +} + +function plural(count: number, noun: string, nouns = `${noun}s`): string { + return `${count} ${count === 1 ? noun : nouns}`; +} + +async function oxlint(args: readonly string[]): Promise { + const started = Date.now(); + const { values, positionals } = parseArgs({ + args: Array.from(args), + options: { 'changed-since': { type: 'string' }, 'processes': { type: 'string' } }, + allowPositionals: true, + }); + const changedSince = values['changed-since']; + if (changedSince !== undefined && positionals.length > 0) { + throw new Error('Pass either files to lint or --changed-since, not both.'); + } + const maxProcesses = values.processes ? Number(values.processes) : Math.min(8, availableParallelism()); + if (!Number.isInteger(maxProcesses) || maxProcesses < 1) { + throw new Error('--processes requires a positive number.'); + } + + // The paths of each process: oxlint applies the ignore patterns of the configuration to all of them. + const runs: { readonly args: string[] }[] = []; + let description: string; + const scope = changedSince !== undefined ? getChangedFilesScope(changedSince, getEslintScope) : undefined; + if (positionals.length === 0 && (!scope || scope.kind === 'full')) { + description = scope ? `the full repository because ${scope.reason}` : 'the full repository'; + const files = await listFiles(['.']); + const typeAware = typeAwareLintFolders.filter(folder => files.some(file => isInFolder(file, folder))); + const weighted = files.filter(file => !typeAware.some(folder => isInFolder(file, folder))).map(file => ({ path: file, weight: statSync(path.join(root, file)).size })); + runs.push(...splitByFolder(weighted, maxProcesses, typeAware).map(paths => ({ args: paths }))); + if (typeAware.length) { + runs.push({ args: ['--type-aware', ...typeAware] }); + } + } else { + const files = scope?.kind === 'files' ? Array.from(scope.files) : await listFiles(positionals); + description = scope?.kind === 'files' ? `${plural(files.length, 'file')} (${scope.reason})` : plural(positionals.length, 'requested target'); + const typeAwareFiles = new Set(files.filter(file => typeAwareLintFolders.some(folder => isInFolder(file, folder)))); + const otherFiles = files.filter(file => !typeAwareFiles.has(file)); + const processes = Math.min(maxProcesses, Math.ceil(otherFiles.length / minFilesPerProcess)); + if (otherFiles.length) { + runs.push(...splitFiles(otherFiles, processes).map(paths => ({ args: paths }))); + } + if (typeAwareFiles.size) { + runs.push(...splitFiles(Array.from(typeAwareFiles), 1).map(paths => ({ args: ['--type-aware', ...paths] }))); + } + } + + console.log(`oxlint: checking ${description}.`); + if (runs.length === 0) { + return; + } + const outputs = await runAll(runs.map(run => () => runOxlint(run.args)), maxProcesses + 1); + const diagnostics = outputs.flatMap(output => output.diagnostics); + if (diagnostics.length) { + console.log(formatCompact(diagnostics, root)); + console.log(`\n${plural(diagnostics.length, 'problem')}`); + } + const fileCount = outputs.reduce((sum, output) => sum + output.number_of_files, 0); + const slowest = Math.max(...outputs.map(output => output.duration)); + console.log(`oxlint: checked ${plural(fileCount, 'file')} in ${Date.now() - started}ms with ${plural(runs.length, 'process', 'processes')} (the slowest took ${slowest}ms).`); + if (diagnostics.length) { + throw new Error(`oxlint failed with ${diagnostics.length} warnings and/or errors`); + } +} + +if (import.meta.main) { + oxlint(process.argv.slice(2)).catch(err => { + console.error(); + console.error(err); + // Not process.exit(), which would truncate output that is still being written to a pipe. + process.exitCode = 1; + }); +} diff --git a/build/package.json b/build/package.json index d950c85f0b01..6ca0007ce1ee 100644 --- a/build/package.json +++ b/build/package.json @@ -59,6 +59,7 @@ "jsonc-parser": "^2.3.0", "jws": "^4.0.1", "mime": "^1.4.1", + "minimatch": "^3.1.5", "source-map": "0.6.1", "svgo": "2.8.4", "ternary-stream": "^3.0.0", diff --git a/build/pnpm-lock.yaml b/build/pnpm-lock.yaml index a84294b19d9c..a39bcbd9d197 100644 --- a/build/pnpm-lock.yaml +++ b/build/pnpm-lock.yaml @@ -161,6 +161,9 @@ importers: mime: specifier: ^1.4.1 version: 1.6.0 + minimatch: + specifier: ^3.1.5 + version: 3.1.5 source-map: specifier: 0.6.1 version: 0.6.1 diff --git a/build/rspack/package.json b/build/rspack/package.json index af90c8da1b8c..4c60fd419941 100644 --- a/build/rspack/package.json +++ b/build/rspack/package.json @@ -1,7 +1,6 @@ { "name": "code-oss-dev-rspack", "version": "1.0.0", - "packageManager": "pnpm@12.16.0", "private": true, "license": "MIT", "scripts": { diff --git a/build/vite/package.json b/build/vite/package.json index ea5cb6b90430..b7baa4c4076f 100644 --- a/build/vite/package.json +++ b/build/vite/package.json @@ -2,7 +2,6 @@ "name": "@vscode/sample-source", "private": true, "version": "0.0.0", - "packageManager": "pnpm@12.16.0", "type": "module", "scripts": { "dev": "vite", diff --git a/cglicenses.json b/cglicenses.json index 0c730e23c569..d33b5ac53f70 100644 --- a/cglicenses.json +++ b/cglicenses.json @@ -1276,5 +1276,26 @@ "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE" ] + }, + { + // Reason: The OSS license check cannot find local license text for @eslint/compat, + // and ClearlyDefined has no coverage. Use the upstream Apache-2.0 license. + // Source: https://github.com/eslint/rewrite/blob/compat-v2.1.0/packages/compat/LICENSE + "name": "@eslint/compat", + "fullLicenseTextUri": "https://raw.githubusercontent.com/eslint/rewrite/compat-v2.1.0/packages/compat/LICENSE" + }, + { + // Reason: ClearlyDefined is unreachable in the OSS license check for oxlint. + // Use the upstream MIT license from the matching release. + // Source: https://github.com/oxc-project/oxc/blob/oxlint_v1.90.0/LICENSE + "name": "oxlint", + "fullLicenseTextUri": "https://raw.githubusercontent.com/oxc-project/oxc/oxlint_v1.90.0/LICENSE" + }, + { + // Reason: The OSS license check cannot find local license text for oxlint-tsgolint, + // and ClearlyDefined has no coverage. Use the upstream MIT license. + // Source: https://github.com/oxc-project/tsgolint/blob/v7.0.2005/LICENSE + "name": "oxlint-tsgolint", + "fullLicenseTextUri": "https://raw.githubusercontent.com/oxc-project/tsgolint/v7.0.2005/LICENSE" } ] diff --git a/cgmanifest.json b/cgmanifest.json index e8a01cf8b315..8bf5bedc3f4a 100644 --- a/cgmanifest.json +++ b/cgmanifest.json @@ -529,13 +529,13 @@ "git": { "name": "electron", "repositoryUrl": "https://github.com/electron/electron", - "commitHash": "294458de94162d6f71ab2d740cdd5d5643d32aad", - "tag": "43.8.6" + "commitHash": "1afd314211c923547f1dd139b718e159575f2067", + "tag": "43.8.9" } }, "isOnlyProductionDependency": true, "license": "MIT", - "version": "43.8.6" + "version": "43.8.9" }, { "component": { diff --git a/cli/CONTRIBUTING.md b/cli/CONTRIBUTING.md index a2754b523ddd..db740d6690fc 100644 --- a/cli/CONTRIBUTING.md +++ b/cli/CONTRIBUTING.md @@ -32,6 +32,18 @@ an interactive prompt. Without `--tunnel`, `code agent` and `code agent host` still start or reuse a local agent host supervisor. +## GitHub environments + +Use `code agent host --github-environment --name ` to register an agent host as a GitHub environment. Like `code agent host`, it starts in the background by default; `--foreground` keeps it attached to the terminal. By default, it grants access to all accessible local drive roots on Windows and `/` on macOS and Linux, while keeping the launch directory as the shared project and default working directory. Network-backed Windows drives are not added automatically; inaccessible local drives are skipped with a warning. Automatically discovered grants are checked again when the agent host restarts, so a disconnected drive does not prevent registration. + +Background startup requires the GitHub credentials to be saved and readable by the detached supervisor. If credential persistence fails, use `--foreground` to keep the acquired credentials in memory without requiring them to be saved. + +Only one GitHub environment supervisor may run per server data directory. Repeated starts, including concurrent starts and `--foreground`, report an error instead of starting another host with the same environment identity. Stop the existing host with `code agent kill` before restarting it with different options, or use a separate `--server-data-dir` for an independent environment. Changing `--cli-data-dir` or `--user-data-dir` alone does not create an independent environment identity. + +On Windows, `code agent kill` forcefully terminates the selected supervisor and its process tree. A failed termination command reports an error instead of removing the host's discovery entry and reporting success. + +To restrict access, pass `--github-environment-root `. Repeat the option to grant multiple directories; explicit roots replace the default filesystem-wide grants and shared projects, with the first root as the default working directory. + ## Headless sandbox certificate management Run these commands on the computer hosting the agent, as the same operating-system account and with the same `COPILOT_HOME` as that agent host. If unset, the home defaults to the account's `.copilot` directory. Desktop VS Code and a separate Copilot CLI installation are not required. diff --git a/cli/Cargo.toml b/cli/Cargo.toml index f1b3e46118b9..83c7fa1c0d88 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -67,7 +67,7 @@ winresource = "0.1" [target.'cfg(windows)'.dependencies] winreg = "0.56" winapi = "0.3.9" -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Console", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Input_KeyboardAndMouse"] } [target.'cfg(target_os = "macos")'.dependencies] core-foundation = "0.9.3" diff --git a/cli/src/commands/agent_host.rs b/cli/src/commands/agent_host.rs index 4bc72f5d3dde..4280f5c39df0 100644 --- a/cli/src/commands/agent_host.rs +++ b/cli/src/commands/agent_host.rs @@ -30,6 +30,7 @@ use crate::tunnels::user_data_path::resolve_user_data_path; use crate::update_service::Platform; use crate::util::command::{kill_tree, DetachFromParent}; use crate::util::errors::{wrap, AnyError, CodeError}; +use crate::util::file_lock::{FileLock, Lock}; use crate::util::http::ReqwestSimpleHttp; use crate::util::prereqs::PreReqChecker; @@ -60,20 +61,28 @@ const SUPERVISOR_READY_TIMEOUT: Duration = Duration::from_secs(5 * 60); /// endpoint registry and either prints info about the live supervisor /// (`Reuse`), or starts a new supervisor (`SpawnFresh`) — daemonized by /// default, or run inline in this process when `--foreground` is set. +/// GitHub environments start a dedicated supervisor, with one owner per +/// server data directory. /// /// * **Supervisor** (when [`SUPERVISOR_ENV`] is set): binds the public TCP /// listener, publishes a registry entry recording this process's PID + /// port, runs the proxy accept loop, and manages the underlying VS Code /// server as a regular child process so the supervisor can kill+respawn /// it on update. -pub async fn agent_host(ctx: CommandContext, mut args: AgentHostArgs) -> Result { - if args.github_environment { - args.foreground = true; - return run_supervisor(ctx, args).await; - } +pub async fn agent_host(ctx: CommandContext, args: AgentHostArgs) -> Result { if std::env::var_os(SUPERVISOR_ENV).is_some() { return run_supervisor(ctx, args).await; } + if args.github_environment { + // Avoid prompting on duplicates; the supervisor rechecks and holds the lock. + drop(acquire_github_environment_lock(&args)?); + legal::require_consent(&ctx.paths, args.accept_server_license_terms)?; + if !args.foreground { + let credential = github_environment_credential(&ctx).await?; + require_persisted_github_environment_credential(&ctx.paths, &ctx.log, &credential)?; + } + return start_supervisor(ctx, args).await; + } run_foreground(ctx, args).await } @@ -224,6 +233,11 @@ async fn start_supervisor(ctx: CommandContext, args: AgentHostArgs) -> Result Result { + let _github_environment_lock = if args.github_environment { + Some(acquire_github_environment_lock(&args)?) + } else { + None + }; let started = Instant::now(); let user_data_path = resolve_user_data_path(args.user_data_dir.as_deref()); let instance_id = uuid::Uuid::new_v4().to_string(); @@ -259,7 +273,6 @@ async fn run_supervisor(mut ctx: CommandContext, mut args: AgentHostArgs) -> Res let platform: Platform = PreReqChecker::new().verify().await?; let github_environment = if args.github_environment { - legal::require_consent(&ctx.paths, args.accept_server_license_terms)?; Some(github_environment_config(&ctx, &args).await?) } else { None @@ -442,42 +455,89 @@ async fn run_supervisor(mut ctx: CommandContext, mut args: AgentHostArgs) -> Res Ok(0) } -async fn github_environment_config( - ctx: &CommandContext, - args: &AgentHostArgs, -) -> Result { - if args - .name +fn acquire_github_environment_lock(args: &AgentHostArgs) -> Result { + // Match server.main.ts: the backend's data directory owns the MC identity, + // independently of the CLI credential cache and endpoint registry. + let server_data_dir = args + .server_data_dir .as_deref() - .is_some_and(|name| name.trim().is_empty()) + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + .or_else(|| { + std::env::var_os("VSCODE_AGENT_FOLDER") + .filter(|path| !path.is_empty()) + .map(PathBuf::from) + }) + .or_else(|| dirs::home_dir().map(|home| home.join(constants::SERVER_DATA_PARENT_DIR))) + .ok_or_else(|| { + wrap( + "", + "Could not resolve the GitHub environment server data directory", + ) + })?; + let user_data_dir = server_data_dir.join("data"); + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] { - return Err(wrap("", "GitHub environment name must not be empty").into()); + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); } - let roots = if args.github_environment_root.is_empty() { - vec![std::env::current_dir().map_err(|e| wrap(e, "could not resolve current directory"))?] - } else { - args.github_environment_root.clone() - }; - let roots = roots - .iter() - .map(|root| { - let path = fs::canonicalize(root) - .map_err(|e| wrap(e, format!("could not resolve project {}", root.display())))?; - if !path.is_dir() { - return Err(wrap( - "", - format!("project {} is not a directory", root.display()), - )); - } - Ok(path.to_string_lossy().into_owned()) - }) - .collect::, _>>()?; - let mut auth = Auth::with_namespace( - &ctx.paths, - ctx.log.clone(), - Some("github-environments".into()), - ); + builder.create(&user_data_dir).map_err(|error| { + wrap( + error, + "Could not create the GitHub environment data directory", + ) + })?; + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(user_data_dir.join("agent-host-github-environment.lock")) + .map_err(|error| wrap(error, "Could not open the GitHub environment lock"))?; + match FileLock::acquire(file)? { + Lock::Acquired(lock) => Ok(lock), + Lock::AlreadyLocked(_) => Err(wrap( + "", + format!( + "A GitHub environment is already starting or running for {}. \ + Stop the existing host with `{application_name} agent kill`, \ + or use a different --server-data-dir.", + server_data_dir.display(), + application_name = constants::APPLICATION_NAME, + ), + ) + .into()), + } +} + +fn github_environment_auth(paths: &LauncherPaths, log: &log::Logger) -> Auth { + let mut auth = Auth::with_namespace(paths, log.clone(), Some("github-environments".into())); auth.set_provider(AuthProvider::Github); + auth +} + +fn require_persisted_github_environment_credential( + paths: &LauncherPaths, + log: &log::Logger, + credential: &str, +) -> Result<(), AnyError> { + let message = "GitHub environment credentials could not be saved for background startup; retry with --foreground"; + // A fresh Auth reads storage rather than the login instance's in-memory cache. + let persisted = github_environment_auth(paths, log) + .get_current_credential() + .map_err(|e| wrap(e, message))?; + if !persisted.is_some_and(|saved| { + matches!(saved.provider, AuthProvider::Github) && saved.access_token() == credential + }) { + return Err(wrap("", message).into()); + } + Ok(()) +} + +async fn github_environment_credential(ctx: &CommandContext) -> Result { + let auth = github_environment_auth(&ctx.paths, &ctx.log); let credential = if auth.get_current_credential()?.is_some() { auth.get_credential().await? } else { @@ -491,6 +551,22 @@ async fn github_environment_config( if credential.is_empty() { return Err(wrap("", "GitHub environment access token must not be empty").into()); } + Ok(credential) +} + +async fn github_environment_config( + ctx: &CommandContext, + args: &AgentHostArgs, +) -> Result { + if args + .name + .as_deref() + .is_some_and(|name| name.trim().is_empty()) + { + return Err(wrap("", "GitHub environment name must not be empty").into()); + } + let paths = github_environment_paths(&ctx.log, &args.github_environment_root)?; + let credential = github_environment_credential(ctx).await?; #[derive(serde::Deserialize)] struct GithubUser { id: u64, @@ -512,12 +588,117 @@ async fn github_environment_config( base_url: "https://api.github.com".into(), account_id: user.id.to_string(), credential, - roots, + optional_roots: paths + .roots + .iter() + .filter(|root| !paths.projects.contains(root)) + .cloned() + .collect(), + roots: paths.roots, + default_directory: paths.projects[0].clone(), + projects: paths.projects, name: args.name.clone(), live: true, }) } +struct GithubEnvironmentPaths { + roots: Vec, + projects: Vec, +} + +fn github_environment_paths( + log: &log::Logger, + requested_roots: &[PathBuf], +) -> Result { + let projects = if requested_roots.is_empty() { + vec![std::env::current_dir().map_err(|e| wrap(e, "could not resolve current directory"))?] + } else { + requested_roots.to_vec() + }; + let projects = projects + .iter() + .map(|root| { + let path = fs::canonicalize(root) + .map_err(|e| wrap(e, format!("could not resolve project {}", root.display())))?; + if !path.is_dir() { + return Err(wrap( + "", + format!("project {} is not a directory", root.display()), + )); + } + Ok(path.to_string_lossy().into_owned()) + }) + .collect::, _>>()?; + let mut roots = projects.clone(); + if requested_roots.is_empty() { + #[cfg(windows)] + roots.extend(github_environment_drive_roots( + log, + |letter| { + let drive = [letter as u16, b':' as u16, b'\\' as u16, 0]; + // SAFETY: drive is a valid, null-terminated UTF-16 root path. + unsafe { windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(drive.as_ptr()) } + }, + |path| fs::canonicalize(path), + )); + #[cfg(not(windows))] + { + let _ = log; + roots.push("/".into()); + } + } + Ok(GithubEnvironmentPaths { roots, projects }) +} + +#[cfg(windows)] +fn github_environment_drive_roots( + log: &log::Logger, + drive_type: impl Fn(u8) -> u32, + canonicalize: impl Fn(&Path) -> std::io::Result, +) -> Vec { + use windows_sys::Win32::System::WindowsProgramming::{ + DRIVE_CDROM, DRIVE_FIXED, DRIVE_RAMDISK, DRIVE_REMOVABLE, + }; + + let mut roots = Vec::new(); + for letter in b'A'..=b'Z' { + if !matches!( + drive_type(letter), + DRIVE_FIXED | DRIVE_REMOVABLE | DRIVE_CDROM | DRIVE_RAMDISK + ) { + continue; + } + let drive = PathBuf::from(format!("{}:\\", letter as char)); + match canonicalize(&drive) { + Ok(path) => { + if matches!( + path.components().next(), + Some(std::path::Component::Prefix(prefix)) + if matches!(prefix.kind(), std::path::Prefix::Disk(_) | std::path::Prefix::VerbatimDisk(_)) + ) { + roots.push(path.to_string_lossy().into_owned()); + } else { + info!( + log, + "Excluding network-backed drive {} from GitHub environment sharing", + drive.display() + ); + } + } + Err(error) => { + warning!( + log, + "Skipping inaccessible GitHub environment drive {}: {}", + drive.display(), + error + ); + } + } + } + roots +} + /// Resolve the user's `--host`/`--port` choice into a single /// [`SocketAddr`]. Defaults to loopback when `--host` is unset. fn resolve_listen_addr(args: &AgentHostArgs) -> Result { @@ -924,12 +1105,18 @@ impl ActiveAgentHost { } /// Populate the `--agent-host-bridge-*` fields on a [`CodeServerArgs`] - /// so the spawned VS Code server's `agentHostProxy` channel dials this - /// supervisor. Uses [`dial_host`] for the host so a supervisor bound + /// so a spawned VS Code server that predates registry discovery dials + /// this supervisor. Uses [`dial_host`] for the host so a supervisor bound /// to a wildcard (`0.0.0.0` / `::`) is reached via loopback rather - /// than the wildcard itself. + /// than the wildcard itself. Those servers put the host into a `ws://` + /// URL, so IPv6 literals are bracketed. pub fn apply_to_bridge(&self, csa: &mut CodeServerArgs) { - csa.agent_host_bridge_host = Some(self.dial_host().to_string()); + let host = self.dial_host(); + csa.agent_host_bridge_host = Some(if host.contains(':') && !host.starts_with('[') { + format!("[{host}]") + } else { + host.to_string() + }); csa.agent_host_bridge_port = Some(self.port); csa.agent_host_bridge_connection_token = self.token.clone(); } @@ -1024,6 +1211,259 @@ mod tests { use std::fs; use tokio::net::TcpListener; + #[tokio::test] + async fn github_environment_rejects_duplicate_start_before_authentication() { + let dir = tempfile::tempdir().unwrap(); + let mut args = AgentHostArgs { + github_environment: true, + server_data_dir: Some(dir.path().join("server").to_string_lossy().into_owned()), + user_data_dir: Some(dir.path().join("registry").to_string_lossy().into_owned()), + ..Default::default() + }; + let _owner = acquire_github_environment_lock(&args).unwrap(); + for foreground in [false, true] { + args.foreground = foreground; + for supervisor in [false, true] { + let ctx = CommandContext { + log: log::Logger::test(), + paths: LauncherPaths::new_without_replacements(dir.path().join("cli")), + args: Default::default(), + http: reqwest::Client::new(), + }; + let error = if supervisor { + run_supervisor(ctx, args.clone()).await + } else { + agent_host(ctx, args.clone()).await + } + .unwrap_err(); + assert!( + error.to_string().contains("already starting or running"), + "{error}" + ); + } + } + } + + #[test] + #[cfg(unix)] + fn github_environment_lock_keeps_new_server_data_private() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let server_data_dir = dir.path().join("server"); + let args = AgentHostArgs { + server_data_dir: Some(server_data_dir.to_string_lossy().into_owned()), + ..Default::default() + }; + let _owner = acquire_github_environment_lock(&args).unwrap(); + assert_eq!( + [server_data_dir.clone(), server_data_dir.join("data")] + .map(|path| fs::metadata(path).unwrap().permissions().mode() & 0o777), + [0o700, 0o700] + ); + } + + #[test] + fn github_environment_lock_releases_and_is_scoped_to_server_data() { + let dir = tempfile::tempdir().unwrap(); + let args = AgentHostArgs { + server_data_dir: Some(dir.path().join("server").to_string_lossy().into_owned()), + ..Default::default() + }; + let owner = acquire_github_environment_lock(&args).unwrap(); + let other = AgentHostArgs { + server_data_dir: Some( + dir.path() + .join("other-server") + .to_string_lossy() + .into_owned(), + ), + ..Default::default() + }; + let _other_owner = acquire_github_environment_lock(&other).unwrap(); + drop(owner); + assert!(acquire_github_environment_lock(&args).is_ok()); + } + + #[tokio::test] + async fn github_environment_background_rejects_missing_persisted_credential() { + let dir = tempfile::tempdir_in(".").unwrap(); + let paths = LauncherPaths::new_without_replacements(dir.path().to_path_buf()); + let log = log::Logger::test(); + fs::create_dir(paths.root().join("token-github-environments.json")).unwrap(); + let auth = github_environment_auth(&paths, &log); + let credential = auth + .login(Some(AuthProvider::Github), Some("fresh-token".into()), None) + .await + .unwrap(); + + assert_eq!( + auth.get_current_credential() + .unwrap() + .unwrap() + .access_token(), + credential.access_token() + ); + let error = require_persisted_github_environment_credential( + &paths, + &log, + credential.access_token(), + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "GitHub environment credentials could not be saved for background startup; retry with --foreground: " + ); + } + + #[tokio::test] + async fn github_environment_background_rejects_mismatched_persisted_credential() { + let dir = tempfile::tempdir_in(".").unwrap(); + let paths = LauncherPaths::new_without_replacements(dir.path().to_path_buf()); + let log = log::Logger::test(); + fs::write(paths.root().join("token-github-environments.json"), "null").unwrap(); + for (provider, token) in [ + (AuthProvider::Github, "stale-token"), + (AuthProvider::Microsoft, "fresh-token"), + ] { + github_environment_auth(&paths, &log) + .login(Some(provider), Some(token.into()), None) + .await + .unwrap(); + + let error = + require_persisted_github_environment_credential(&paths, &log, "fresh-token") + .unwrap_err(); + assert_eq!( + error.to_string(), + "GitHub environment credentials could not be saved for background startup; retry with --foreground: " + ); + } + } + + #[tokio::test] + async fn github_environment_background_accepts_persisted_credential() { + let dir = tempfile::tempdir_in(".").unwrap(); + let paths = LauncherPaths::new_without_replacements(dir.path().to_path_buf()); + let log = log::Logger::test(); + fs::write(paths.root().join("token-github-environments.json"), "null").unwrap(); + let credential = github_environment_auth(&paths, &log) + .login(Some(AuthProvider::Github), Some("fresh-token".into()), None) + .await + .unwrap(); + + require_persisted_github_environment_credential(&paths, &log, credential.access_token()) + .unwrap(); + } + + #[test] + fn github_environment_roots_default_to_local_filesystems() { + let cwd = std::env::current_dir().unwrap(); + let root = cwd.ancestors().last().unwrap(); + let paths = github_environment_paths(&log::Logger::test(), &[]).unwrap(); + assert_eq!( + ( + paths.projects, + paths.roots.contains( + &fs::canonicalize(root) + .unwrap() + .to_string_lossy() + .into_owned() + ) + ), + ( + vec![fs::canonicalize(&cwd) + .unwrap() + .to_string_lossy() + .into_owned()], + true + ) + ); + } + + #[cfg(windows)] + #[test] + fn github_environment_roots_include_other_local_drives() { + let cwd = std::env::current_dir().unwrap(); + let roots = github_environment_paths(&log::Logger::test(), &[]) + .unwrap() + .roots; + for letter in b'A'..=b'Z' { + let drive = PathBuf::from(format!("{}:\\", letter as char)); + if drive.exists() && cwd.ancestors().last() != Some(drive.as_path()) { + let canonical = fs::canonicalize(drive).unwrap(); + if matches!( + canonical.components().next(), + Some(std::path::Component::Prefix(prefix)) + if matches!(prefix.kind(), std::path::Prefix::VerbatimDisk(_) | std::path::Prefix::Disk(_)) + ) { + assert!( + roots.contains(&canonical.to_string_lossy().into_owned()), + "missing {canonical:?}" + ); + } + } + } + } + + #[cfg(windows)] + #[test] + fn github_environment_roots_skip_unusable_and_network_drives() { + use windows_sys::Win32::System::WindowsProgramming::{ + DRIVE_CDROM, DRIVE_FIXED, DRIVE_NO_ROOT_DIR, DRIVE_REMOTE, + }; + + let roots = github_environment_drive_roots( + &log::Logger::test(), + |letter| match letter { + b'C' | b'D' | b'E' | b'Q' => DRIVE_FIXED, + b'F' => DRIVE_CDROM, + b'Z' => DRIVE_REMOTE, + _ => DRIVE_NO_ROOT_DIR, + }, + |path| match path.to_str().unwrap() { + "C:\\" | "Q:\\" => Ok(path.to_path_buf()), + "D:\\" => Ok(PathBuf::from("\\\\server\\share\\")), + "E:\\" => Err(std::io::Error::from_raw_os_error(5)), + "F:\\" => Err(std::io::Error::from_raw_os_error(21)), + _ => panic!("must not probe absent or network drives: {path:?}"), + }, + ); + assert_eq!(roots, vec!["C:\\", "Q:\\"]); + } + + #[test] + fn github_environment_roots_preserve_explicit_scope() { + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("project"); + fs::create_dir(&project).unwrap(); + assert_eq!( + { + let paths = + github_environment_paths(&log::Logger::test(), &[project.clone()]).unwrap(); + (paths.roots, paths.projects) + }, + { + let project = fs::canonicalize(project) + .unwrap() + .to_string_lossy() + .into_owned(); + (vec![project.clone()], vec![project]) + } + ); + } + + #[test] + fn github_environment_roots_reject_invalid_explicit_roots() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("file"); + fs::write(&file, "").unwrap(); + assert!(github_environment_paths(&log::Logger::test(), &[file]).is_err()); + assert!( + github_environment_paths(&log::Logger::test(), &[dir.path().join("missing")]).is_err() + ); + } + #[test] fn mint_connection_token_generates_and_persists() { let dir = tempfile::tempdir().unwrap(); @@ -1073,6 +1513,32 @@ mod tests { } } + #[test] + fn apply_to_bridge_brackets_ipv6_hosts_for_legacy_server_urls() { + let bridge_host = |host: Option<&str>| { + let mut csa = CodeServerArgs::default(); + ActiveAgentHost { + pid: 1, + host: host.map(str::to_string), + port: 9000, + token: None, + } + .apply_to_bridge(&mut csa); + csa.agent_host_bridge_host.unwrap() + }; + assert_eq!( + [ + Some("::1"), + Some("[::1]"), + Some("::"), + Some("127.0.0.1"), + None + ] + .map(bridge_host), + ["[::1]", "[::1]", "127.0.0.1", "127.0.0.1", "127.0.0.1"] + ); + } + #[test] fn decide_foreground_action_spawn_fresh_when_nothing_registered() { let args = AgentHostArgs::default(); diff --git a/cli/src/commands/args.rs b/cli/src/commands/args.rs index ba49bb9f49a5..995a04025ed0 100644 --- a/cli/src/commands/args.rs +++ b/cli/src/commands/args.rs @@ -305,18 +305,19 @@ pub struct AgentHostArgs { ] )] pub tunnel: bool, - /// Register this agent host as a GitHub environment. Runs in the foreground. + /// Register this agent host as a GitHub environment. + /// Runs in the background unless `--foreground` is passed. #[clap( long, group = "remote_host", conflicts_with_all = [ "host", "port", "connection_token", "connection_token_file", - "without_connection_token", "replace", "new_instance", "foreground", "idle_timeout", + "without_connection_token", "replace", "new_instance", "idle_timeout", "random_name", "tunnel_id", "host_token", "cluster", "tunnel_name" ] )] pub github_environment: bool, - /// Grant access to a project directory. Repeat for multiple projects. Defaults to the current directory. + /// Restrict access to a project directory. Repeat for multiple projects. Defaults to all local filesystems. #[clap(long, requires = "github_environment", conflicts_with = "tunnel")] pub github_environment_root: Vec, /// Sets the machine name for the tunnel or GitHub environment. @@ -1272,6 +1273,7 @@ mod tests { let mut argv = command; argv.extend([ "--github-environment", + "--foreground", "--name", "build-machine", "--github-environment-root", @@ -1288,11 +1290,13 @@ mod tests { assert_eq!( ( args.github_environment, + args.foreground, args.name.as_deref(), args.github_environment_root, args.accept_server_license_terms ), ( + true, true, Some("build-machine"), vec!["project-a".into(), "project-b".into()], @@ -1314,7 +1318,6 @@ mod tests { vec!["--without-connection-token"], vec!["--replace"], vec!["--new-instance"], - vec!["--foreground"], vec!["--idle-timeout", "300"], vec!["--random-name"], vec!["--tunnel-id", "id"], diff --git a/cli/src/commands/tunnels.rs b/cli/src/commands/tunnels.rs index 8c92839e7e49..9fba46c12a1b 100644 --- a/cli/src/commands/tunnels.rs +++ b/cli/src/commands/tunnels.rs @@ -4,13 +4,12 @@ *--------------------------------------------------------------------------------------------*/ use base64::{engine::general_purpose as b64, Engine as _}; -use futures::{stream::FuturesUnordered, FutureExt, StreamExt}; +use futures::{stream::FuturesUnordered, StreamExt}; use serde::Serialize; use sha2::{Digest, Sha256}; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, str::FromStr, - sync::Arc, time::Duration, }; use sysinfo::Pid; @@ -20,7 +19,6 @@ use tokio::{ }; use super::{ - agent_host::ensure_supervisor_running, args::{ AuthProvider, CliCore, CommandShellArgs, ExistingTunnelArgs, TunnelArgs, TunnelForwardArgs, TunnelRenameArgs, TunnelServeArgs, TunnelServiceSubCommands, TunnelUserSubCommands, @@ -50,7 +48,6 @@ use crate::{ make_singleton_server, start_singleton_server, BroadcastLogSink, SingletonServerArgs, }, AuthRequired, Next, ServeStreamParams, ServiceContainer, ServiceManager, - SharedActiveAgentHost, }, util::{ app_lock::AppMutex, @@ -150,28 +147,10 @@ pub async fn command_shell(ctx: CommandContext, args: CommandShellArgs) -> Resul shutdown_reqs.push(ShutdownRequest::ParentProcessKilled(p)); } - // The supervisor is what lets the renderer reach the agent host via - // the `agentHostProxy` IPC channel on the spawned VS Code server. This - // future is genuinely lazy, exactly like the one built in - // `control_server::serve()`: nothing drives it here — a - // `command-shell` that nobody connects to must not spawn a standalone - // supervisor by itself. It's only driven once `handle_serve` awaits a - // clone of it on demand and mixes the bridge endpoint into the - // per-request `code_server_args`. On failure the renderer just won't - // see `agentHostProxy`; editing and the extension host still work. - let active_agent_host: SharedActiveAgentHost = { - let paths = ctx.paths.clone(); - let log = ctx.log.clone(); - async move { - ensure_supervisor_running(&paths, &log) - .await - .map(Arc::new) - .map_err(Arc::new) - } - .boxed() - .shared() - }; - + // No agent host supervisor here: the spawned VS Code server is the client's + // own commit, so it uses a live shared agent host from the endpoint registry + // or starts and publishes its own, and stays alive while that agent host + // has sessions or clients. let mut params = ServeStreamParams { log: ctx.log, launcher_paths: ctx.paths, @@ -182,7 +161,7 @@ pub async fn command_shell(ctx: CommandContext, args: CommandShellArgs) -> Resul .unwrap_or(AuthRequired::VSDA), exit_barrier: ShutdownRequest::create_rx(shutdown_reqs), code_server_args: (&ctx.args).into(), - active_agent_host: Some(active_agent_host), + active_agent_host: None, }; args.server_args.apply_to(&mut params.code_server_args); diff --git a/cli/src/tunnels/agent_host.rs b/cli/src/tunnels/agent_host.rs index 046e5ff9cf62..e01a8c86b5ac 100644 --- a/cli/src/tunnels/agent_host.rs +++ b/cli/src/tunnels/agent_host.rs @@ -72,6 +72,10 @@ pub struct GithubEnvironmentConfig { pub account_id: String, pub credential: String, pub roots: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub optional_roots: Vec, + pub projects: Vec, + pub default_directory: String, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, pub live: bool, @@ -2426,6 +2430,9 @@ mod tests { account_id: "123".into(), credential: "test-credential".into(), roots: vec![dir.path().to_string_lossy().into_owned()], + optional_roots: vec![], + projects: vec![dir.path().to_string_lossy().into_owned()], + default_directory: dir.path().to_string_lossy().into_owned(), name: Some("build-machine".into()), live: true, }; @@ -2484,6 +2491,9 @@ mod tests { account_id: "123".into(), credential: "test-credential".into(), roots: vec![dir.path().to_string_lossy().into_owned()], + optional_roots: vec![], + projects: vec![dir.path().to_string_lossy().into_owned()], + default_directory: dir.path().to_string_lossy().into_owned(), name: None, live: true, }); @@ -2521,6 +2531,9 @@ mod tests { account_id: "123".into(), credential: "test-credential".into(), roots: vec![dir.to_string_lossy().into_owned()], + optional_roots: vec![], + projects: vec![dir.to_string_lossy().into_owned()], + default_directory: dir.to_string_lossy().into_owned(), name: None, live: true, }); diff --git a/cli/src/tunnels/code_server.rs b/cli/src/tunnels/code_server.rs index b8a012306459..d5a32c46996c 100644 --- a/cli/src/tunnels/code_server.rs +++ b/cli/src/tunnels/code_server.rs @@ -75,11 +75,11 @@ pub struct CodeServerArgs { pub without_connection_token: bool, // reconnection pub reconnection_grace_time: Option, - // agent-host bridge: tells the spawned VS Code server where the - // canonical agent host is listening so it can register the - // `agentHostProxy` IPC channel and let renderers reach the agent - // host over the remote-agent connection. The server does NOT spawn - // an agent host of its own when these are set. + // agent-host bridge: tells a spawned VS Code server that predates + // registry discovery where the canonical agent host is listening, so + // it registers the `agentHostProxy` IPC channel against it instead of + // spawning an agent host of its own. Newer servers ignore these and + // discover the same agent host via the shared endpoint registry. pub agent_host_bridge_host: Option, pub agent_host_bridge_port: Option, pub agent_host_bridge_connection_token: Option, diff --git a/cli/src/tunnels/control_server.rs b/cli/src/tunnels/control_server.rs index 16ff8eb51192..879e908929af 100644 --- a/cli/src/tunnels/control_server.rs +++ b/cli/src/tunnels/control_server.rs @@ -105,10 +105,10 @@ struct HandlerContext { http: Arc, /// requests being served by the client http_requests: HttpRequestsMap, - /// Shared handle to the background `ensure_supervisor_running` task, - /// awaited in `handle_serve` to mix the bridge info into the spawned - /// server's args. `None` for callers (e.g. `command-shell`) that - /// already applied the bridge eagerly. + /// Shared `ensure_supervisor_running` future, awaited in `handle_serve` + /// so the spawned server can discover the supervisor via the shared + /// local agent-host endpoint registry. `None` for `command-shell`, whose + /// server starts its own agent host when no shared one is running. active_agent_host: Option, } @@ -220,13 +220,13 @@ pub async fn serve( // The supervisor is the only process that binds the user-facing TCP // listener and publishes the canonical registry entry; we never spawn // an in-process sidecar here. This future is genuinely lazy: nothing - // drives it until a consumer that actually needs the legacy (v5) - // single-supervisor endpoint awaits a clone of it — currently - // `handle_serve`'s `agentHostProxy` bridge, and the root/default route - // of the `agent-host` port forwarder below. A tunnel that nobody - // connects to must not spawn a standalone supervisor by itself; the - // protocol-v6 selection route (also below) consults the registry - // directly instead and never touches this future. + // drives it until a consumer needs the supervisor — currently + // `handle_serve`, so the spawned server discovers it via the registry, + // and the legacy (v5) root/default route of the `agent-host` port + // forwarder below. A tunnel that nobody connects to must not spawn a + // standalone supervisor by itself; the protocol-v6 selection route + // (also below) consults the registry directly and never touches this + // future. let active_agent_host: SharedActiveAgentHost = { let launcher_paths = launcher_paths.clone(); let log = log.clone(); @@ -811,17 +811,19 @@ async fn handle_serve( csa.connection_token = params.connection_token.or(csa.connection_token); csa.install_extensions.extend(params.extensions); - // Mix in the agent-host bridge info now that we actually need to spawn - // the VS Code server. `active_agent_host` is genuinely lazy (see the - // comment in `serve()`), so awaiting it here is what first drives the - // supervisor to start. If it failed we still serve — the renderer - // just won't see `agentHostProxy`. + // Ensure the supervisor is running before spawning the VS Code server + // so the server can discover it via the shared local agent-host endpoint + // registry. `active_agent_host` is genuinely lazy (see `serve()`), so + // awaiting it here first drives the supervisor to start. The bridge + // arguments are only for servers that predate registry discovery, since + // the client may request an older server commit; newer servers ignore + // them. On failure, the server will start its own agent host. if let Some(ah_fut) = c.active_agent_host.clone() { match ah_fut.await { Ok(a) => a.apply_to_bridge(&mut csa), Err(e) => warning!( c.log, - "Agent host supervisor unavailable; renderer will not see agentHostProxy: {}", + "Agent host supervisor unavailable; server will start its own agent host: {}", e ), } diff --git a/cli/src/util/command.rs b/cli/src/util/command.rs index 88c20b172d07..f535348340f3 100644 --- a/cli/src/util/command.rs +++ b/cli/src/util/command.rs @@ -214,7 +214,8 @@ fn apply_detach_flags_tokio(cmd: &mut tokio::process::Command) { /// Kills and processes and all of its children. #[cfg(windows)] pub async fn kill_tree(process_id: u32) -> Result<(), CodeError> { - capture_command("taskkill", &["/t", "/pid", &process_id.to_string()]).await?; + capture_command_and_check_status("taskkill", &["/f", "/t", "/pid", &process_id.to_string()]) + .await?; Ok(()) } @@ -305,6 +306,50 @@ pub async fn kill_tree(process_id: u32) -> Result<(), CodeError> { Ok(()) } +#[cfg(all(test, windows))] +mod windows_tests { + use super::*; + use std::time::Duration; + use tokio::io::AsyncBufReadExt; + + #[tokio::test] + async fn kill_tree_terminates_process_without_console_window() { + let mut child = new_tokio_command("powershell") + .args([ + "-NoProfile", + "-NonInteractive", + "-Command", + "Write-Output 'ready'; Start-Sleep -Seconds 30", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let pid = child.id().unwrap(); + let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap()).lines(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(10), stdout.next_line()) + .await + .unwrap() + .unwrap() + .as_deref(), + Some("ready") + ); + kill_tree(pid).await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), child.wait()) + .await + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn kill_tree_reports_taskkill_failure() { + // Windows process IDs are multiples of four, so this cannot target a live process. + assert!(kill_tree(u32::MAX).await.is_err()); + } +} + #[cfg(all(test, not(windows)))] mod tests { use super::*; diff --git a/eslint.config.js b/eslint.config.js index f5d47d3ac382..d5938251f8cb 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -3,7 +3,6 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check -import { fixupPluginRules } from '@eslint/compat'; import { defineConfig } from 'eslint/config'; import fs from 'fs'; import { builtinModules } from 'module'; @@ -11,13 +10,14 @@ import path from 'path'; import tseslint from 'typescript-eslint'; import stylistic from '@stylistic/eslint-plugin'; -import * as pluginLocal from './.eslint-plugin-local/index.ts'; -import * as pluginCopilotLocal from './extensions/copilot/.eslintplugin/index.ts'; -import pluginImport from 'eslint-plugin-import'; +import pluginLocal from './.eslint-plugin-local/index.ts'; +import pluginCopilotLocal from './extensions/copilot/.eslintplugin/index.ts'; import pluginJsdoc from 'eslint-plugin-jsdoc'; -import pluginHeader from 'eslint-plugin-header'; -pluginHeader.rules.header.meta.schema = false; +// Adapters that load third-party rules under the names oxlint also uses for them (see .eslint-plugin-local/README.md) +import pluginEslintJs from './.eslint-plugin-local/adapters/eslintCore.ts'; +import pluginHeader from './.eslint-plugin-local/adapters/header.ts'; +import pluginTypeScriptEslintJs from './.eslint-plugin-local/adapters/typescriptEslint.ts'; const ignores = fs.readFileSync(path.join(import.meta.dirname, '.eslint-ignore'), 'utf8') .toString() @@ -36,6 +36,16 @@ const allowedBracketNotationFiles = fs.readFileSync(path.join(import.meta.dirnam .map(line => line.trim()) .filter(line => line && !line.startsWith('#')); +// The layers of `local/code-layering`: each folder name maps to the layers it may import, besides its own. +const codeLayers = { + 'common': [], + 'node': ['common'], + 'browser': ['common'], + 'electron-browser': ['common', 'browser'], + 'electron-utility': ['common', 'node'], + 'electron-main': ['common', 'node', 'electron-utility'], +}; + export default defineConfig( // Global ignores { @@ -51,7 +61,11 @@ export default defineConfig( }, plugins: { 'local': pluginLocal, - 'header': fixupPluginRules(/** @type {any} */ (pluginHeader)), + 'header': pluginHeader, + '@stylistic': stylistic, + 'eslint-js': pluginEslintJs, + 'ts-eslint-js': pluginTypeScriptEslintJs, + 'jsdoc-js': pluginJsdoc, }, rules: { 'constructor-super': 'warn', @@ -63,7 +77,7 @@ export default defineConfig( 'destructuring': 'all' } ], - 'no-buffer-constructor': 'warn', + 'eslint-js/no-buffer-constructor': 'warn', 'no-caller': 'warn', 'no-case-declarations': 'warn', 'no-debugger': 'warn', @@ -71,7 +85,7 @@ export default defineConfig( 'no-duplicate-imports': 'warn', 'no-eval': 'warn', 'no-async-promise-executor': 'warn', - 'no-extra-semi': 'warn', + '@stylistic/no-extra-semi': 'warn', 'no-new-wrappers': 'warn', 'no-redeclare': 'off', 'no-sparse-arrays': 'warn', @@ -92,7 +106,7 @@ export default defineConfig( 'context' ], // non-complete list of globals that are easy to access unintentionally 'no-var': 'warn', - 'semi': 'warn', + '@stylistic/semi': 'warn', 'local/code-translation-remind': 'warn', 'local/code-no-declare-const-enum': 'warn', 'local/code-parameter-properties-must-have-explicit-accessibility': 'warn', @@ -114,31 +128,7 @@ export default defineConfig( 'local/code-no-http-import': ['warn', { target: 'src/vs/**' }], 'local/code-no-deep-import-of-internal': ['error', { '.*Internal': true, 'searchExtTypesInternal': false }], 'local/code-no-private-agent-host-meta-import': 'error', - 'local/code-layering': [ - 'warn', - { - 'common': [], - 'node': [ - 'common' - ], - 'browser': [ - 'common' - ], - 'electron-browser': [ - 'common', - 'browser' - ], - 'electron-utility': [ - 'common', - 'node' - ], - 'electron-main': [ - 'common', - 'node', - 'electron-utility' - ] - } - ], + 'local/code-layering': ['warn', codeLayers], 'header/header': [ 2, 'block', @@ -231,15 +221,10 @@ export default defineConfig( parser: tseslint.parser, }, plugins: { - '@stylistic': stylistic, '@typescript-eslint': tseslint.plugin, 'local': pluginLocal, - 'jsdoc': pluginJsdoc, }, rules: { - // Disable built-in semi rules in favor of stylistic - 'semi': 'off', - '@stylistic/semi': 'warn', '@stylistic/member-delimiter-style': 'warn', 'local/code-no-unused-expressions': [ 'warn', @@ -247,63 +232,31 @@ export default defineConfig( 'allowTernary': true } ], - 'jsdoc/no-types': 'warn', + 'jsdoc-js/no-types': 'warn', 'local/code-no-static-self-ref': 'warn', - '@typescript-eslint/naming-convention': [ - 'warn', - { - 'selector': 'class', - 'format': [ - 'PascalCase' - ] - } - ] + 'local/code-class-name-pascal-case': 'warn' } }, + // Disallow common telemetry properties in event data { files: [ - 'src/vs/platform/agentHost/test/**/missionControl*.test.ts', - 'src/vs/platform/agentHost/test/**/protocolServerHandler.test.ts', - 'src/vs/platform/agentHost/test/**/agentHostProtocolClient.test.ts', - 'src/vs/platform/agentHost/test/**/webPubSubRelayTransport.test.ts', - 'src/vs/platform/agentHost/test/common/webPubSub/*.test.ts', - 'src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandbox*.test.ts', - 'src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHost.contribution.test.ts', + 'src/**/*.ts', ], plugins: { - 'agent-host-test': { - rules: { - 'no-nested-tests': { - meta: { - type: 'problem', - schema: [], - messages: { nested: 'Declare tests in the suite, not inside another test; Mocha does not execute nested declarations.' }, - }, - create(context) { - return { - 'CallExpression[callee.name="test"] CallExpression[callee.name="test"]'(node) { - context.report({ node, messageId: 'nested' }); - }, - }; - }, - }, - }, - }, + 'local': pluginLocal, }, rules: { - 'agent-host-test/no-nested-tests': 'error', - }, + 'local/code-no-telemetry-common-property': 'warn', + } }, - // Disallow common telemetry properties in event data + // src compiles with useDefineForClassFields: false, but must keep working with JavaScript class field semantics, + // which src/tsconfig.defineClassFields.json checks (see define-class-fields-check in package.json) { files: [ 'src/**/*.ts', ], - plugins: { - 'local': pluginLocal, - }, rules: { - 'local/code-no-telemetry-common-property': 'warn', + 'local/code-no-parameter-property-before-init': 'warn', } }, // Force all gulp imports under build/ to go through the gulp facade @@ -1028,7 +981,7 @@ export default defineConfig( }, rules: { 'no-restricted-imports': 'off', - '@typescript-eslint/no-restricted-imports': [ + 'ts-eslint-js/no-restricted-imports': [ 'warn', { 'patterns': [ @@ -1055,7 +1008,7 @@ export default defineConfig( 'local': pluginLocal, }, rules: { - 'no-restricted-syntax': [ + 'eslint-js/no-restricted-syntax': [ 'warn', { 'selector': `TSArrayType > TSUnionType`, @@ -1145,15 +1098,15 @@ export default defineConfig( parser: tseslint.parser, }, rules: { - 'jsdoc/tag-lines': 'off', - 'jsdoc/valid-types': 'off', - 'jsdoc/no-multi-asterisks': [ + 'jsdoc-js/tag-lines': 'off', + 'jsdoc-js/valid-types': 'off', + 'jsdoc-js/no-multi-asterisks': [ 'warn', { 'allowWhitespace': true } ], - 'jsdoc/require-jsdoc': [ + 'jsdoc-js/require-jsdoc': [ 'warn', { 'enableFixer': false, @@ -1171,14 +1124,14 @@ export default defineConfig( ] } ], - 'jsdoc/check-param-names': [ + 'jsdoc-js/check-param-names': [ 'warn', { 'enableFixer': false, 'checkDestructured': false } ], - 'jsdoc/require-returns': 'warn' + 'jsdoc-js/require-returns': 'warn' } }, // common/browser layer @@ -1267,7 +1220,7 @@ export default defineConfig( }, rules: { 'local/code-no-global-document-listener': 'warn', - 'no-restricted-syntax': [ + 'eslint-js/no-restricted-syntax': [ 'warn', { 'selector': `NewExpression[callee.object.name='Intl']`, @@ -1951,6 +1904,7 @@ export default defineConfig( 'target': 'src/vs/workbench/api/~', 'restrictions': [ 'vscode', + '@vscode/internal-github', 'vs/base/~', 'vs/base/parts/*/~', 'vs/platform/*/~', @@ -2170,6 +2124,7 @@ export default defineConfig( 'vs/workbench/services/*/~', 'vs/workbench/contrib/*/~', 'vs/workbench/contrib/terminal/terminal.all.js', + 'vs/sessions/sessions.core.main.js', ] }, { @@ -2254,7 +2209,7 @@ export default defineConfig( ] }, { - 'target': 'src/vs/sessions/sessions.common.main.ts', + 'target': 'src/vs/sessions/{sessions.core.main.ts,sessions.common.main.ts}', 'layer': 'browser', 'restrictions': [ 'vs/base/~', @@ -2298,7 +2253,7 @@ export default defineConfig( ] }, { - 'target': 'src/vs/sessions/sessions.web.main.ts', + 'target': 'src/vs/sessions/{sessions.core.web.main.ts,sessions.web.main.ts}', 'layer': 'browser', 'restrictions': [ 'vs/base/~', @@ -2316,9 +2271,36 @@ export default defineConfig( 'vs/workbench/api/~', 'vs/workbench/services/*/~', 'vs/workbench/contrib/*/~', + 'vs/sessions/sessions.core.main.js', + 'vs/sessions/sessions.core.web.main.js', 'vs/sessions/sessions.common.main.js' ] }, + { + // The phone entry is an allow-list: it composes the shared core and + // individual contributions, never the desktop entry points. + 'target': 'src/vs/sessions/agents.web.mobile.main.ts', + 'layer': 'browser', + 'restrictions': [ + 'vs/base/~', + 'vs/base/parts/*/~', + 'vs/platform/*/~', + 'vs/editor/~', + 'vs/editor/contrib/*/~', + 'vs/editor/editor.all.js', + 'vs/sessions/~', + 'vs/sessions/services/*/~', + 'vs/sessions/contrib/*/~', + 'vs/sessions/contrib/providers/*/~', + 'vs/workbench/~', + 'vs/workbench/api/~', + 'vs/workbench/services/*/~', + 'vs/workbench/contrib/*/~', + 'vs/workbench/contrib/terminalContrib/*/~', + 'vs/sessions/sessions.core.main.js', + 'vs/sessions/sessions.core.web.main.js' + ] + }, { 'target': 'src/vs/sessions/sessions.web.main.internal.ts', 'layer': 'browser', @@ -2337,6 +2319,23 @@ export default defineConfig( 'vs/sessions/sessions.web.main.js' ] }, + { + 'target': 'src/vs/sessions/agents.web.mobile.main.internal.ts', + 'layer': 'browser', + 'restrictions': [ + 'vs/base/~', + 'vs/base/parts/*/~', + 'vs/platform/*/~', + 'vs/sessions/~', + 'vs/sessions/contrib/*/~', + 'vs/sessions/contrib/providers/*/~', + 'vs/workbench/~', + 'vs/workbench/browser/**', + 'vs/workbench/services/*/~', + 'vs/workbench/contrib/*/~', + 'vs/sessions/agents.web.mobile.main.js' + ] + }, { 'target': 'src/vs/sessions/test/sessions.web.test.internal.ts', 'layer': 'browser', @@ -2356,7 +2355,7 @@ export default defineConfig( ] }, { - 'target': 'src/vs/sessions/test/{web.test.ts,web.test.factory.ts}', + 'target': 'src/vs/sessions/test/agents.web.mobile.test.internal.ts', 'layer': 'browser', 'restrictions': [ 'vs/base/~', @@ -2365,6 +2364,25 @@ export default defineConfig( 'vs/sessions/~', 'vs/sessions/test/**', 'vs/sessions/contrib/*/~', + 'vs/sessions/contrib/providers/*/~', + 'vs/workbench/~', + 'vs/workbench/browser/**', + 'vs/workbench/services/*/~', + 'vs/workbench/contrib/*/~', + 'vs/sessions/agents.web.mobile.main.js' + ] + }, + { + 'target': 'src/vs/sessions/test/{web.test.ts,web.test.factory.ts,web.test.terminal.ts}', + 'layer': 'browser', + 'restrictions': [ + 'vs/base/~', + 'vs/base/parts/*/~', + 'vs/platform/*/~', + 'vs/sessions/~', + 'vs/sessions/services/*/~', + 'vs/sessions/test/**', + 'vs/sessions/contrib/*/~', 'vs/workbench/~', 'vs/workbench/browser/**', 'vs/workbench/services/*/~', @@ -2667,7 +2685,7 @@ export default defineConfig( parser: tseslint.parser, }, rules: { - '@typescript-eslint/naming-convention': [ + 'ts-eslint-js/naming-convention': [ 'warn', // variableLike { 'selector': 'variable', 'format': ['camelCase', 'UPPER_CASE', 'PascalCase'] }, @@ -2682,7 +2700,9 @@ export default defineConfig( { 'selector': 'typeLike', 'format': ['PascalCase'] }, { 'selector': 'interface', 'format': ['PascalCase'] } ], - 'comma-dangle': ['warn', 'only-multiline'] + // Covered by the `typeLike` naming convention above + 'local/code-class-name-pascal-case': 'off', + '@stylistic/comma-dangle': ['warn', 'only-multiline'] } }, // Ban dynamic require() and import() calls in extensions to ensure tree-shaking works @@ -2695,7 +2715,7 @@ export default defineConfig( 'extensions/copilot/**/*', ], rules: { - 'no-restricted-syntax': [ + 'eslint-js/no-restricted-syntax': [ 'warn', { 'selector': `CallExpression[callee.name='require'][arguments.0.type!='Literal']`, @@ -2720,7 +2740,7 @@ export default defineConfig( '@typescript-eslint': tseslint.plugin, }, rules: { - 'no-restricted-syntax': [ + 'eslint-js/no-restricted-syntax': [ 'warn', { selector: ':matches(PropertyDefinition, TSParameterProperty, MethodDefinition[key.name!="constructor"])[accessibility="private"]', @@ -2786,7 +2806,6 @@ export default defineConfig( parser: tseslint.parser, }, plugins: { - 'import': fixupPluginRules(pluginImport), 'copilot-local': pluginCopilotLocal, }, rules: { @@ -2808,61 +2827,22 @@ export default defineConfig( 'vscode-tas-client', 'web-tree-sitter' ], - 'import/no-restricted-paths': [ + // Copilot's own layers, in addition to VS Code's + 'local/code-layering': [ + 'warn', + { + ...codeLayers, + 'vscode': ['common'], + 'vscode-node': ['common', 'vscode', 'node'], + 'worker': ['common'], + 'vscode-worker': ['common', 'vscode', 'worker'], + } + ], + // Rules between folders, which the layers can't express + 'local/code-no-restricted-zone-imports': [ 'warn', { zones: [ - { - target: '**/common/**', - from: [ - '**/vscode/**', - '**/node/**', - '**/vscode-node/**', - '**/worker/**', - '**/vscode-worker/**' - ] - }, - { - target: '**/vscode/**', - from: [ - '**/node/**', - '**/vscode-node/**', - '**/worker/**', - '**/vscode-worker/**' - ] - }, - { - target: '**/node/**', - from: [ - '**/vscode/**', - '**/vscode-node/**', - '**/worker/**', - '**/vscode-worker/**' - ] - }, - { - target: '**/vscode-node/**', - from: [ - '**/worker/**', - '**/vscode-worker/**' - ] - }, - { - target: '**/worker/**', - from: [ - '**/vscode/**', - '**/node/**', - '**/vscode-node/**', - '**/vscode-worker/**' - ] - }, - { - target: '**/vscode-worker/**', - from: [ - '**/node/**', - '**/vscode-node/**' - ] - }, { target: './extensions/copilot/src/', from: './extensions/copilot/test/' @@ -3100,7 +3080,6 @@ export default defineConfig( 'extensions/copilot/src/platform/parser/node/parserWorker.ts', 'extensions/copilot/src/platform/parser/node/treeSitterQueries.ts', 'extensions/copilot/src/platform/remoteCodeSearch/common/githubCodeSearchService.ts', - 'extensions/copilot/src/platform/remoteSearch/node/codeOrDocsSearchClientImpl.ts', 'extensions/copilot/src/platform/review/vscode/reviewServiceImpl.ts', 'extensions/copilot/src/platform/scopeSelection/vscode-node/scopeSelectionImpl.ts', 'extensions/copilot/src/platform/snippy/common/snippyTypes.ts', @@ -3167,7 +3146,8 @@ export default defineConfig( 'extensions/copilot/src/lib/node/chatLibMain.ts', ], rules: { - 'import/no-restricted-paths': 'off' + 'local/code-layering': 'off', + 'local/code-no-restricted-zone-imports': 'off' } }, // Allow querySelector/querySelectorAll in test files - it's acceptable for test assertions @@ -3177,7 +3157,7 @@ export default defineConfig( 'extensions/**/test/**/*.ts', ], rules: { - 'no-restricted-syntax': [ + 'eslint-js/no-restricted-syntax': [ 'warn', // Keep the Intl helper restriction even in tests { diff --git a/extensions/configuration-editing/package.json b/extensions/configuration-editing/package.json index 9b5a083bbec5..1b1326f4f4c7 100644 --- a/extensions/configuration-editing/package.json +++ b/extensions/configuration-editing/package.json @@ -16,8 +16,7 @@ "onLanguage:jsonc" ], "enabledApiProposals": [ - "profileContentHandlers", - "github" + "profileContentHandlers" ], "main": "./out/configurationEditingMain", "browser": "./dist/browser/configurationEditingMain", diff --git a/extensions/configuration-editing/src/importExportProfiles.ts b/extensions/configuration-editing/src/importExportProfiles.ts index 05468b349ba9..72e00f972325 100644 --- a/extensions/configuration-editing/src/importExportProfiles.ts +++ b/extensions/configuration-editing/src/importExportProfiles.ts @@ -5,8 +5,9 @@ import * as vscode from 'vscode'; import { basename } from 'path'; +import * as internalGitHub from '@vscode/internal-github'; -type GitHubApi = Pick; +type GitHubApi = Pick; type AuthenticationApi = Pick; export class GitHubGistProfileContentHandler implements vscode.ProfileContentHandler { @@ -15,7 +16,7 @@ export class GitHubGistProfileContentHandler implements vscode.ProfileContentHan readonly description = vscode.l10n.t('gist'); constructor( - private readonly github: GitHubApi = vscode.github, + private readonly github: GitHubApi = internalGitHub, private readonly authentication: AuthenticationApi = vscode.authentication, ) { } @@ -42,7 +43,7 @@ export class GitHubGistProfileContentHandler implements vscode.ProfileContentHan async readProfile(idOrUri: string | vscode.Uri, token?: vscode.CancellationToken): Promise { this.throwIfCancelled(token); const gistId = typeof idOrUri === 'string' ? idOrUri : basename(idOrUri.path); - let client: vscode.GitHubAnonymousClient | undefined; + let client: internalGitHub.GitHubAnonymousClient | undefined; try { client = await this.github.getAnonymousClient(token); this.throwIfCancelled(token); diff --git a/extensions/configuration-editing/src/test/importExportProfiles.test.ts b/extensions/configuration-editing/src/test/importExportProfiles.test.ts index dd2e1461c15e..4403c2da8661 100644 --- a/extensions/configuration-editing/src/test/importExportProfiles.test.ts +++ b/extensions/configuration-editing/src/test/importExportProfiles.test.ts @@ -6,22 +6,23 @@ import * as vscode from 'vscode'; import * as assert from 'assert'; import 'mocha'; +import { GitHubError, type GitHubGist, type GitHubGistFile } from '@vscode/internal-github'; import { GitHubGistProfileContentHandler } from '../importExportProfiles'; type GitHubApi = NonNullable[0]>; type AuthenticationApi = NonNullable[1]>; -function gist(files: vscode.GitHubGistFile[]): vscode.GitHubGist { +function gist(files: GitHubGistFile[]): GitHubGist { return { id: 'gist-id', htmlUrl: vscode.Uri.parse('https://gist.github.com/gist-id'), files }; } -function file(content: string, overrides: Partial = {}): vscode.GitHubGistFile { +function file(content: string, overrides: Partial = {}): GitHubGistFile { return { content, isBinary: false, truncated: false, ...overrides }; } suite('GitHub gist profile content handler', () => { - function setup(options: { readonly read?: () => Promise; readonly create?: () => Promise; readonly acquire?: () => Promise } = {}) { + function setup(options: { readonly read?: () => Promise; readonly create?: () => Promise; readonly acquire?: () => Promise } = {}) { const calls: unknown[][] = []; const cancellation = new vscode.CancellationTokenSource(); const github: GitHubApi = { @@ -70,7 +71,7 @@ suite('GitHub gist profile content handler', () => { }); test('reports save failures and still releases the client', async () => { - const failure = new vscode.GitHubError('The selected GitHub session is not available to this extension.', 'authentication'); + const failure = new GitHubError('The selected GitHub session is not available to this extension.', 'authentication'); const { handler, calls, token, cancellation } = setup({ create: () => Promise.reject(failure) }); await assert.rejects(handler.saveProfile('profile', '{}', token), error => error === failure); cancellation.dispose(); @@ -98,13 +99,13 @@ suite('GitHub gist profile content handler', () => { async () => gist([]), async () => gist([file('{"partial', { truncated: true })]), async () => gist([file('e30=', { isBinary: true })]), - async () => { throw new vscode.GitHubError('Not Found', 'notFound', 404); }, + async () => { throw new GitHubError('Not Found', 'notFound', 404); }, ]) { const { handler, cancellation } = setup({ read }); results.push(await handler.readProfile('gist-id')); cancellation.dispose(); } - const { handler, calls, cancellation } = setup({ acquire: () => Promise.reject(new vscode.GitHubError('Busy', 'rateLimit')) }); + const { handler, calls, cancellation } = setup({ acquire: () => Promise.reject(new GitHubError('Busy', 'rateLimit')) }); results.push(await handler.readProfile('gist-id')); cancellation.dispose(); assert.deepStrictEqual({ results, calls }, { results: [null, null, null, null, null], calls: [['getAnonymousClient', false]] }); diff --git a/extensions/configuration-editing/tsconfig.json b/extensions/configuration-editing/tsconfig.json index 7699c9a50afa..dcfc214b5eb5 100644 --- a/extensions/configuration-editing/tsconfig.json +++ b/extensions/configuration-editing/tsconfig.json @@ -11,6 +11,6 @@ "src/**/*", "../../src/vscode-dts/vscode.d.ts", "../../src/vscode-dts/vscode.proposed.profileContentHandlers.d.ts", - "../../src/vscode-dts/vscode.proposed.github.d.ts", + "../../src/typings/internal-github.d.ts", ] } diff --git a/extensions/copilot/.eslintplugin/index.ts b/extensions/copilot/.eslintplugin/index.ts index 05098654d5d1..25ab59e5f0a2 100644 --- a/extensions/copilot/.eslintplugin/index.ts +++ b/extensions/copilot/.eslintplugin/index.ts @@ -16,4 +16,4 @@ await Promise.all( }) ); -export { rules }; +export default { meta: { name: 'copilot-local' }, rules } satisfies ESLint.Plugin; diff --git a/extensions/copilot/build/npm-package-next.yml b/extensions/copilot/build/npm-package-next.yml index 3156622d25ff..9d499bacbc0c 100644 --- a/extensions/copilot/build/npm-package-next.yml +++ b/extensions/copilot/build/npm-package-next.yml @@ -36,8 +36,9 @@ extends: buildSteps: - task: NodeTool@0 inputs: - versionSpec: 22.x - displayName: 🛠 Install Node.js (22.x) + versionSpec: 24.x + checkLatest: true + displayName: 🛠 Install Node.js - template: extensions/copilot/build/steps/setup-npm.yml@self parameters: @@ -103,11 +104,13 @@ extends: workingDirectory: extensions/copilot/chat-lib testPlatforms: - name: Linux - nodeVersions: [22.x] + nodeVersions: [24.x] + # chat-lib is consumed by other products, which don't share our GLIBC requirements. + useSysroot: false - name: MacOS - nodeVersions: [22.x] + nodeVersions: [24.x] - name: Windows - nodeVersions: [22.x] + nodeVersions: [24.x] workingDirectory: extensions/copilot/chat-lib testSteps: - template: extensions/copilot/build/steps/test-chat-lib.yml@self diff --git a/extensions/copilot/build/npm-package.yml b/extensions/copilot/build/npm-package.yml index 34c51d48f4b6..fb8a51d8bcad 100644 --- a/extensions/copilot/build/npm-package.yml +++ b/extensions/copilot/build/npm-package.yml @@ -44,11 +44,13 @@ extends: NPM_REGISTRY: ${{ parameters.NPM_REGISTRY }} testPlatforms: - name: Linux - nodeVersions: [22.x] + nodeVersions: [24.x] + # chat-lib is consumed by other products, which don't share our GLIBC requirements. + useSysroot: false - name: MacOS - nodeVersions: [22.x] + nodeVersions: [24.x] - name: Windows - nodeVersions: [22.x] + nodeVersions: [24.x] workingDirectory: extensions/copilot/chat-lib testSteps: - template: extensions/copilot/build/steps/test-chat-lib.yml@self diff --git a/extensions/copilot/build/steps/build-chat-lib.yml b/extensions/copilot/build/steps/build-chat-lib.yml index 096e90c982ad..5250aa4baa7a 100644 --- a/extensions/copilot/build/steps/build-chat-lib.yml +++ b/extensions/copilot/build/steps/build-chat-lib.yml @@ -5,8 +5,9 @@ parameters: steps: - task: NodeTool@0 inputs: - versionSpec: 22.x - displayName: 🛠 Install Node.js (22.x) + versionSpec: 24.x + checkLatest: true + displayName: 🛠 Install Node.js - template: setup-npm.yml parameters: diff --git a/extensions/copilot/chat-lib/package.json b/extensions/copilot/chat-lib/package.json index 16aa3ab76139..52e56131e200 100644 --- a/extensions/copilot/chat-lib/package.json +++ b/extensions/copilot/chat-lib/package.json @@ -1,7 +1,6 @@ { "name": "@vscode/chat-lib", "version": "0.0.0", - "packageManager": "pnpm@12.16.0", "description": "Chat and inline editing SDK extracted from VS Code Copilot Chat", "main": "dist/src/main.js", "types": "dist/src/main.d.ts", @@ -29,6 +28,7 @@ "undici": "^7.24.1", "vscode-languageserver-protocol": "^3.17.5", "vscode-languageserver-textdocument": "^1.0.12", + "vscode-languageserver-types": "^3.17.5", "web-tree-sitter": "^0.23.0", "yaml": "^2.8.0" }, @@ -67,7 +67,6 @@ "compile": "tsc6", "copy": "copyfiles src/package.json \"src/**/*.tiktoken\" dist", "package": "pnpm pack", - "postinstall": "tsx script/postinstall.js", "test": "vitest run", "test:watch": "vitest" } diff --git a/extensions/copilot/chat-lib/script/postinstall.ts b/extensions/copilot/chat-lib/script/postinstall.ts index f6d58e1354df..109b54916187 100644 --- a/extensions/copilot/chat-lib/script/postinstall.ts +++ b/extensions/copilot/chat-lib/script/postinstall.ts @@ -60,9 +60,9 @@ function treeSitterWasmDir(): string { async function main() { const platform = await platformDir(); if (!platform) { - // chat-lib is a member of Copilot's pnpm workspace, so every install of Copilot runs this - // script, also before `extract-chat-lib` created the sources. There is nothing to copy yet. - console.log('chat-lib: no sources yet (run `pnpm run extract-chat-lib` in extensions/copilot), skipping postinstall.'); + // `extract-chat-lib` declares this script when it creates the sources, which can be deleted + // afterwards, for example by `git clean`. There is nothing to copy then. + console.log('chat-lib: no extracted sources (run `pnpm run extract-chat-lib` in extensions/copilot), skipping postinstall.'); return; } const vendoredTiktokenFiles = [`${platform}/tokenizer/node/cl100k_base.tiktoken`, `${platform}/tokenizer/node/o200k_base.tiktoken`]; diff --git a/extensions/copilot/chat-lib/tsconfig.base.json b/extensions/copilot/chat-lib/tsconfig.base.json index de752aa3fb52..17fd578840a2 100644 --- a/extensions/copilot/chat-lib/tsconfig.base.json +++ b/extensions/copilot/chat-lib/tsconfig.base.json @@ -1,6 +1,11 @@ { "compilerOptions": { "module": "commonjs", + // TypeScript 6 resolves with the bundler rules here, which add the `import` condition. Add + // `require`, the condition with which Node loads this CommonJS output, so that declarations + // can name the types of packages with `exports` (such as @sinclair/typebox) through pnpm's + // symlinked node_modules instead of failing with TS2883 ("likely not portable"). + "customConditions": ["require"], "target": "es2022", "lib": ["ES2022"], "sourceMap": true, diff --git a/extensions/copilot/package.json b/extensions/copilot/package.json index 749356d30d95..9b439906cd1d 100644 --- a/extensions/copilot/package.json +++ b/extensions/copilot/package.json @@ -93,6 +93,7 @@ "enabledApiProposals": [ "agentSessionsWorkspace", "speech", + "structuralDiff", "agentsWindowConfiguration", "chatDebug", "chatHooks", @@ -6817,6 +6818,7 @@ "@fluentui/react-icons": "^2.0.305", "@hediet/node-reload": "^0.8.0", "@octokit/types": "^14.1.0", + "@parcel/watcher": "^2.5.6", "@types/eslint": "^9.0.0", "@types/express": "^5.0.6", "@types/markdown-it": "^14.0.0", diff --git a/extensions/copilot/pnpm-lock.yaml b/extensions/copilot/pnpm-lock.yaml index df41f71733d2..8055362964f2 100644 --- a/extensions/copilot/pnpm-lock.yaml +++ b/extensions/copilot/pnpm-lock.yaml @@ -167,6 +167,9 @@ importers: '@octokit/types': specifier: ^14.1.0 version: 14.1.0 + '@parcel/watcher': + specifier: ^2.5.6 + version: 2.5.6 '@types/eslint': specifier: ^9.0.0 version: 9.6.1 @@ -398,6 +401,9 @@ importers: vscode-languageserver-textdocument: specifier: ^1.0.12 version: 1.0.12 + vscode-languageserver-types: + specifier: ^3.17.5 + version: 3.17.5 web-tree-sitter: specifier: ^0.23.0 version: 0.23.2 @@ -1702,6 +1708,94 @@ packages: '@oxc-project/types@0.133.0': resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} + '@parcel/watcher-android-arm64@2.5.6': + resolution: {integrity: sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [android] + + '@parcel/watcher-darwin-arm64@2.5.6': + resolution: {integrity: sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [darwin] + + '@parcel/watcher-darwin-x64@2.5.6': + resolution: {integrity: sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [darwin] + + '@parcel/watcher-freebsd-x64@2.5.6': + resolution: {integrity: sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [freebsd] + + '@parcel/watcher-linux-arm-glibc@2.5.6': + resolution: {integrity: sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-arm-musl@2.5.6': + resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==} + engines: {node: '>= 10.0.0'} + cpu: [arm] + os: [linux] + libc: [musl] + + '@parcel/watcher-linux-arm64-glibc@2.5.6': + resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-arm64-musl@2.5.6': + resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@parcel/watcher-linux-x64-glibc@2.5.6': + resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@parcel/watcher-linux-x64-musl@2.5.6': + resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@parcel/watcher-win32-arm64@2.5.6': + resolution: {integrity: sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==} + engines: {node: '>= 10.0.0'} + cpu: [arm64] + os: [win32] + + '@parcel/watcher-win32-ia32@2.5.6': + resolution: {integrity: sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==} + engines: {node: '>= 10.0.0'} + cpu: [ia32] + os: [win32] + + '@parcel/watcher-win32-x64@2.5.6': + resolution: {integrity: sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==} + engines: {node: '>= 10.0.0'} + cpu: [x64] + os: [win32] + + '@parcel/watcher@2.5.6': + resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} + engines: {node: '>= 10.0.0'} + '@pkgjs/parseargs@0.11.0': resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} @@ -3934,6 +4028,9 @@ packages: node-addon-api@4.3.0: resolution: {integrity: sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==} + node-addon-api@7.1.1: + resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} + node-domexception@1.0.0: resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} engines: {node: '>=10.5.0'} @@ -7148,6 +7245,66 @@ snapshots: '@oxc-project/types@0.133.0': {} + '@parcel/watcher-android-arm64@2.5.6': + optional: true + + '@parcel/watcher-darwin-arm64@2.5.6': + optional: true + + '@parcel/watcher-darwin-x64@2.5.6': + optional: true + + '@parcel/watcher-freebsd-x64@2.5.6': + optional: true + + '@parcel/watcher-linux-arm-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-arm-musl@2.5.6': + optional: true + + '@parcel/watcher-linux-arm64-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-arm64-musl@2.5.6': + optional: true + + '@parcel/watcher-linux-x64-glibc@2.5.6': + optional: true + + '@parcel/watcher-linux-x64-musl@2.5.6': + optional: true + + '@parcel/watcher-win32-arm64@2.5.6': + optional: true + + '@parcel/watcher-win32-ia32@2.5.6': + optional: true + + '@parcel/watcher-win32-x64@2.5.6': + optional: true + + '@parcel/watcher@2.5.6': + dependencies: + detect-libc: 2.1.2 + is-glob: 4.0.3 + node-addon-api: 7.1.1 + picomatch: 4.0.4 + optionalDependencies: + '@parcel/watcher-android-arm64': 2.5.6 + '@parcel/watcher-darwin-arm64': 2.5.6 + '@parcel/watcher-darwin-x64': 2.5.6 + '@parcel/watcher-freebsd-x64': 2.5.6 + '@parcel/watcher-linux-arm-glibc': 2.5.6 + '@parcel/watcher-linux-arm-musl': 2.5.6 + '@parcel/watcher-linux-arm64-glibc': 2.5.6 + '@parcel/watcher-linux-arm64-musl': 2.5.6 + '@parcel/watcher-linux-x64-glibc': 2.5.6 + '@parcel/watcher-linux-x64-musl': 2.5.6 + '@parcel/watcher-win32-arm64': 2.5.6 + '@parcel/watcher-win32-ia32': 2.5.6 + '@parcel/watcher-win32-x64': 2.5.6 + '@pkgjs/parseargs@0.11.0': optional: true @@ -9591,6 +9748,8 @@ snapshots: node-addon-api@4.3.0: optional: true + node-addon-api@7.1.1: {} + node-domexception@1.0.0: {} node-fetch@3.3.2: diff --git a/extensions/copilot/pnpm-workspace.yaml b/extensions/copilot/pnpm-workspace.yaml index 69fdff39cfe8..9ee1d3b067b7 100644 --- a/extensions/copilot/pnpm-workspace.yaml +++ b/extensions/copilot/pnpm-workspace.yaml @@ -27,6 +27,8 @@ pmOnFail: ignore skills: dirs: [] allowBuilds: + # Only `.esbuild.mts --watch` uses it: the prebuilt binary is enough, without a build from source. + '@parcel/watcher@2.5.6': false '@playwright/browser-chromium@1.61.1': true '@vscode/vsce-sign@2.1.0': true esbuild@0.28.1: true diff --git a/extensions/copilot/script/build/extractChatLib.ts b/extensions/copilot/script/build/extractChatLib.ts index 236c8251e764..b4160dceb3e8 100644 --- a/extensions/copilot/script/build/extractChatLib.ts +++ b/extensions/copilot/script/build/extractChatLib.ts @@ -789,6 +789,11 @@ class ChatLibExtractor { } } + // The postinstall copies static files next to the extracted sources. chat-lib is a member of the + // pnpm workspace, whose installs run the install scripts of every member, so its checked-in + // package.json leaves the script out until there are sources. The published package declares it. + chatLibPackageJson.scripts = { ...chatLibPackageJson.scripts, postinstall: 'tsx script/postinstall.js' }; + // Write the updated chat-lib package.json await fs.promises.writeFile( chatLibPackageJsonPath, diff --git a/extensions/copilot/src/extension/byok/node/openAIEndpoint.ts b/extensions/copilot/src/extension/byok/node/openAIEndpoint.ts index 77e91eba4df4..a4d0831cfd90 100644 --- a/extensions/copilot/src/extension/byok/node/openAIEndpoint.ts +++ b/extensions/copilot/src/extension/byok/node/openAIEndpoint.ts @@ -304,6 +304,11 @@ export class OpenAIEndpoint extends ChatEndpoint { body.store = !zdr; body.n = undefined; body.stream_options = undefined; + if (body.truncation === 'disabled') { + // `disabled` is the Responses API default. Omit it so OpenAI-compatible servers + // that do not implement `truncation` (e.g. Kimi Code) accept the request. + delete body.truncation; + } if (!this.modelMetadata.capabilities.supports.thinking) { body.reasoning = undefined; body.include = undefined; diff --git a/extensions/copilot/src/extension/byok/node/test/openAIEndpoint.spec.ts b/extensions/copilot/src/extension/byok/node/test/openAIEndpoint.spec.ts index 74d46aaedd1c..c344b1987c1e 100644 --- a/extensions/copilot/src/extension/byok/node/test/openAIEndpoint.spec.ts +++ b/extensions/copilot/src/extension/byok/node/test/openAIEndpoint.spec.ts @@ -358,6 +358,26 @@ describe('OpenAIEndpoint - Reasoning Properties', () => { ]); }); + it('issue #348418: omits truncation unless the truncation setting is enabled', async () => { + const endpoint = instaService.createInstance(OpenAIEndpoint, + modelMetadata, + 'test-api-key', + 'https://api.example.com/v1/responses'); + const resolveTruncation = () => { + const body = endpoint.createRequestBody(createTestOptions([{ + role: Raw.ChatRole.User, + content: [{ type: Raw.ChatCompletionContentPartKind.Text, text: 'hello' }], + }])); + return 'truncation' in body ? body.truncation : 'omitted'; + }; + + const settingOff = resolveTruncation(); + await accessor.get(IConfigurationService).setConfig(ConfigKey.Advanced.UseResponsesApiTruncation, true); + const settingOn = resolveTruncation(); + + expect({ settingOff, settingOn }).toEqual({ settingOff: 'omitted', settingOn: 'auto' }); + }); + it('adds an empty object schema to a parameterless tool', () => { const endpoint = instaService.createInstance(OpenAIEndpoint, { diff --git a/extensions/copilot/src/extension/chatSessions/vscode-node/copilotCLITerminalIntegration.ts b/extensions/copilot/src/extension/chatSessions/vscode-node/copilotCLITerminalIntegration.ts index 22a7bf7e7ceb..6069f490e8af 100644 --- a/extensions/copilot/src/extension/chatSessions/vscode-node/copilotCLITerminalIntegration.ts +++ b/extensions/copilot/src/extension/chatSessions/vscode-node/copilotCLITerminalIntegration.ts @@ -19,6 +19,7 @@ import { createServiceIdentifier } from '../../../util/common/services'; import { disposableTimeout } from '../../../util/vs/base/common/async'; import { Disposable, DisposableStore } from '../../../util/vs/base/common/lifecycle'; import * as path from '../../../util/vs/base/common/path'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when Copilot started using VS Code's layers: a vscode-node file imports a browser file. import { windowsToGitBashPath } from '../../../util/vs/workbench/contrib/terminalContrib/suggest/browser/terminalGitBashHelpers'; import { PythonTerminalService } from './copilotCLIPythonTerminalService'; import { prepareCopilotCLINativeShim } from './copilotCLINativeShim'; diff --git a/extensions/copilot/src/extension/extension/vscode-node/contributions.ts b/extensions/copilot/src/extension/extension/vscode-node/contributions.ts index d948be618168..c8962f4883f3 100644 --- a/extensions/copilot/src/extension/extension/vscode-node/contributions.ts +++ b/extensions/copilot/src/extension/extension/vscode-node/contributions.ts @@ -53,6 +53,7 @@ import { ToolsContribution } from '../../tools/vscode-node/tools'; import { OTelChatDebugLogProviderContribution } from '../../trajectory/vscode-node/otelChatDebugLogProvider'; import { InlineCompletionContribution } from '../../typescriptContext/vscode-node/languageContextService'; import { NesRenameContribution } from '../../typescriptContext/vscode-node/nesRenameService'; +import { StructuralDiffContribution } from '../../typescriptContext/vscode-node/structuralDiffContribution'; import * as workspaceIndexingContribution from '../../workspaceChunkSearch/vscode-node/workspaceChunkSearch.contribution'; import { WorkspaceRecorderFeature } from '../../workspaceRecorder/vscode-node/workspaceRecorderFeature'; import vscodeContributions from '../vscode/contributions'; @@ -89,6 +90,7 @@ export const vscodeNodeContributions: IExtensionContributionFactory[] = [ asContributionFactory(FeedbackCommandContribution), asContributionFactory(InlineCompletionContribution), asContributionFactory(NesRenameContribution), + asContributionFactory(StructuralDiffContribution), asContributionFactory(SearchPanelCommands), asContributionFactory(ChatQuotaContribution), asContributionFactory(NotebookFollowCommands), diff --git a/extensions/copilot/src/extension/extension/vscode-node/services.ts b/extensions/copilot/src/extension/extension/vscode-node/services.ts index 59e0c81d96a5..ec41745c2acc 100644 --- a/extensions/copilot/src/extension/extension/vscode-node/services.ts +++ b/extensions/copilot/src/extension/extension/vscode-node/services.ts @@ -69,8 +69,6 @@ import { AdoCodeSearchService, IAdoCodeSearchService } from '../../../platform/r import { GithubCodeSearchService, IGithubCodeSearchService } from '../../../platform/remoteCodeSearch/common/githubCodeSearchService'; import { ICodeSearchAuthenticationService } from '../../../platform/remoteCodeSearch/node/codeSearchRepoAuth'; import { VsCodeCodeSearchAuthenticationService } from '../../../platform/remoteCodeSearch/vscode-node/codeSearchRepoAuth'; -import { IDocsSearchClient } from '../../../platform/remoteSearch/common/codeOrDocsSearchClient'; -import { DocsSearchClient } from '../../../platform/remoteSearch/node/codeOrDocsSearchClientImpl'; import { IRequestLogger } from '../../../platform/requestLogger/common/requestLogger'; import { IScopeSelector } from '../../../platform/scopeSelection/common/scopeSelection'; import { ScopeSelectorImpl } from '../../../platform/scopeSelection/vscode-node/scopeSelectionImpl'; @@ -225,7 +223,6 @@ export function registerServices(builder: IInstantiationServiceBuilder, extensio builder.define(IWorkspaceFileIndex, new SyncDescriptor(WorkspaceFileIndex)); builder.define(IChunkingEndpointClient, new SyncDescriptor(ChunkingEndpointClientImpl)); builder.define(ICommandService, new SyncDescriptor(CommandServiceImpl)); - builder.define(IDocsSearchClient, new SyncDescriptor(DocsSearchClient)); builder.define(ISearchService, new SyncDescriptor(SearchServiceImpl)); builder.define(ITestDepsResolver, new SyncDescriptor(TestDepsResolver)); builder.define(ISetupTestsDetector, new SyncDescriptor(SetupTestsDetector)); diff --git a/extensions/copilot/src/extension/inlineEdits/node/nextEditProvider.ts b/extensions/copilot/src/extension/inlineEdits/node/nextEditProvider.ts index a164f94b3d8a..72ce09f91141 100644 --- a/extensions/copilot/src/extension/inlineEdits/node/nextEditProvider.ts +++ b/extensions/copilot/src/extension/inlineEdits/node/nextEditProvider.ts @@ -14,10 +14,11 @@ import { InlineEditRequestLogContext, type MarkdownLoggable } from '../../../pla import { IInlineEditsModelService } from '../../../platform/inlineEdits/common/inlineEditsModelService'; import { resolveModelConfigValue } from '../../../platform/inlineEdits/common/modelConfigurationResolution'; import { IObservableDocument, ObservableWorkspace } from '../../../platform/inlineEdits/common/observableWorkspace'; +import { withoutOtherSensitiveFiles } from '../../../platform/inlineEdits/common/sensitiveFiles'; import { IStatelessNextEditModelTelemetry, IStatelessNextEditProvider, IStatelessNextEditTelemetry, NoNextEditReason, StatelessNextEditDocument, StatelessNextEditRequest, StatelessNextEditResult, StatelessNextEditTelemetryBuilder, StreamedEdit } from '../../../platform/inlineEdits/common/statelessNextEditProvider'; import { autorunWithChanges } from '../../../platform/inlineEdits/common/utils/observable'; import { DocumentHistory, HistoryContext, IHistoryContextProvider } from '../../../platform/inlineEdits/common/workspaceEditTracker/historyContextProvider'; -import { IXtabHistoryEditEntry, IXtabHistoryEntry, NesXtabHistoryTracker } from '../../../platform/inlineEdits/common/workspaceEditTracker/nesXtabHistoryTracker'; +import { IXtabHistoryEditEntry, IXtabHistoryEntry, IXtabHistoryRejectedEditEntry, NesXtabHistoryTracker } from '../../../platform/inlineEdits/common/workspaceEditTracker/nesXtabHistoryTracker'; import { ILogger, ILogService, LogTarget } from '../../../platform/log/common/logService'; import { CapturingToken } from '../../../platform/requestLogger/common/capturingToken'; import { IRequestLogger, LoggedRequestKind } from '../../../platform/requestLogger/common/requestLogger'; @@ -608,6 +609,30 @@ export class NextEditProvider extends Disposable implements INextEditProvider> { const curDocId = doc.id; const logger = parentLogger.createSubLogger('fetchNextEdit'); - const historyContext = this._historyContextProvider.getHistoryContext(curDocId); + const historyContext = this._getHistoryContext(curDocId); if (!historyContext) { return Result.error(new NoNextEditReason.Unexpected(new Error('DocumentMissingInHistoryContext'))); @@ -868,8 +893,7 @@ export class NextEditProvider extends Disposable implements INextEditProvider this._processDoc(doc)); - const xtabEditHistory = this._xtabHistoryTracker.getHistory(); - const rejectedEditHistory = this._xtabHistoryTracker.getRejectedEditHistory(); + const { xtabEditHistory, rejectedEditHistory } = this._getXtabHistory(curDocId); const firstEdit = new DeferredPromise>(); @@ -1276,7 +1300,7 @@ export class NextEditProvider extends Disposable implements INextEditProvider { + + let disposables: DisposableStore; + let configService: IConfigurationService; + + beforeEach(async () => { + disposables = new DisposableStore(); + configService = new InMemoryConfigurationService(new DefaultsOnlyConfigurationService()); + await configService.setConfig(ConfigKey.TeamInternal.InlineEditsCacheDelay, 0); + }); + + afterEach(() => { + disposables.dispose(); + }); + + it('sends files that commonly hold secrets only in requests for themselves', async () => { + const gitExtensionService = new NullGitExtensionService(); + const expService = new NullExperimentationService(); + const workspace = new MutableObservableWorkspace(); + const provider = new RequestCapturingProvider(); + const nextEditProvider = disposables.add(new NextEditProvider( + workspace, + provider, + new NesHistoryContextProvider(workspace, disposables.add(new ObservableGit(gitExtensionService))), + new NesXtabHistoryTracker(workspace, undefined, configService, expService), + undefined, + new NullInlineEditsModelService(), + configService, + new NullSnippyService(), + new LogServiceImpl([]), + expService, + new NullRequestLogger(), + )); + + const editDocument = (uri: string) => { + const doc = workspace.addDocument({ id: DocumentId.create(uri), initialValue: 'a\nb\n' }); + doc.setSelection([new OffsetRange(1, 1)], undefined); + doc.applyEdit(StringEdit.insert(1, 'x')); + return doc.id; + }; + const envId = editDocument(URI.file('/w/.env').toString()); + editDocument('vscode-userdata:/User/settings.json'); + const tsId = editDocument(URI.file('/w/a.ts').toString()); + + const requestContext = async (docId: DocumentId) => { + const context = { triggerKind: 1, selectedCompletionInfo: undefined, requestUuid: generateUuid(), requestIssuedDateTime: Date.now(), earliestShownDateTime: Date.now() }; + const telemetryBuilder = new NextEditProviderTelemetryBuilder(gitExtensionService, mockNotebookService, disposables.add(new TestWorkspaceService()), nextEditProvider.ID, undefined); + try { + await nextEditProvider.getNextEdit(docId, context, new InlineEditRequestLogContext(docId.toString(), 1, context), CancellationToken.None, telemetryBuilder.nesBuilder); + } finally { + telemetryBuilder.dispose(); + } + const request = provider.requests.at(-1)!; + const names = (ids: readonly DocumentId[]) => ids.map(id => posix.basename(id.path)); + return { + documents: names(request.documents.map(d => d.id)), + editHistory: names(request.xtabEditHistory.map(e => e.docId)), + }; + }; + + expect({ + 'a.ts': await requestContext(tsId), + '.env': await requestContext(envId), + }).toEqual({ + 'a.ts': { + documents: ['settings.json', 'a.ts'], + editHistory: ['settings.json', 'a.ts'], + }, + '.env': { + documents: ['.env', 'settings.json', 'a.ts'], + editHistory: ['.env', 'settings.json', 'a.ts'], + }, + }); + }); +}); diff --git a/extensions/copilot/src/extension/inlineEdits/test/vscode-node/documentFilter.spec.ts b/extensions/copilot/src/extension/inlineEdits/test/vscode-node/documentFilter.spec.ts index e3755a3c8994..3dd7f20aa0d2 100644 --- a/extensions/copilot/src/extension/inlineEdits/test/vscode-node/documentFilter.spec.ts +++ b/extensions/copilot/src/extension/inlineEdits/test/vscode-node/documentFilter.spec.ts @@ -16,9 +16,9 @@ describe('DocumentFilter', () => { const js = 'javascript'; - function createDoc(languageId: string): vscode.TextDocument { + function createDoc(languageId: string, uri = 'file:///foo/bar'): vscode.TextDocument { return { - uri: URI.parse('file:///foo/bar'), + uri: URI.parse(uri), languageId, } as vscode.TextDocument; } @@ -37,6 +37,41 @@ describe('DocumentFilter', () => { expect(isEnabled).toBe(true); }); + it('tracks documents of every scheme except ignored ones (issue #337933)', async () => { + const documentFilter = new DocumentFilter(ignoreService, new DefaultsOnlyConfigurationService()); + const uris = [ + 'file:///a.ts', + 'untitled:Untitled-1', + 'vscode-notebook-cell:/a.ipynb#W0sZmlsZQ%3D%3D', + 'memfs:/a.ts', + 'zowe-ds:/profile/USER.COBOL(MEMBER)', + 'vscode-remote://ssh-remote%2Bhost/a.ts', + 'vscode-userdata:/Users/u/Library/Application%20Support/Code/User/settings.json', + 'output:extension-output-1', + 'git:/a.ts?%7B%7D', + 'vscode-chat-code-block:/1', + 'chatSessionInput:/1', + 'vscode-chat-terminal-output:/terminal/1/out.txt', + ]; + + const tracked = Object.fromEntries(await Promise.all(uris.map(async uri => [uri, await documentFilter.isTrackingEnabled(createDoc(js, uri))]))); + + expect(tracked).toEqual({ + 'file:///a.ts': true, + 'untitled:Untitled-1': true, + 'vscode-notebook-cell:/a.ipynb#W0sZmlsZQ%3D%3D': true, + 'memfs:/a.ts': true, + 'zowe-ds:/profile/USER.COBOL(MEMBER)': true, + 'vscode-remote://ssh-remote%2Bhost/a.ts': true, + 'vscode-userdata:/Users/u/Library/Application%20Support/Code/User/settings.json': true, + 'output:extension-output-1': false, + 'git:/a.ts?%7B%7D': false, + 'vscode-chat-code-block:/1': false, + 'chatSessionInput:/1': false, + 'vscode-chat-terminal-output:/terminal/1/out.txt': false, + }); + }); + it('can react to copilot.enable config changes for off-by-default language id', async () => { const defaultsConfigService = new DefaultsOnlyConfigurationService(); const defaultConfig = defaultsConfigService.getConfig(ConfigKey.Enable); diff --git a/extensions/copilot/src/extension/inlineEdits/vscode-node/parts/documentFilter.ts b/extensions/copilot/src/extension/inlineEdits/vscode-node/parts/documentFilter.ts index 27c03cc2e2b8..19f39ca49c8d 100644 --- a/extensions/copilot/src/extension/inlineEdits/vscode-node/parts/documentFilter.ts +++ b/extensions/copilot/src/extension/inlineEdits/vscode-node/parts/documentFilter.ts @@ -6,9 +6,30 @@ import { NotebookDocument, TextDocument } from 'vscode'; import { ConfigKey, IConfigurationService } from '../../../../platform/configuration/common/configurationService'; import { IIgnoreService } from '../../../../platform/ignore/common/ignoreService'; -import { isNotebookCellOrNotebookChatInput } from '../../../../util/common/notebooks'; +import { Schemas } from '../../../../util/vs/base/common/network'; import { derived } from '../../../../util/vs/base/common/observableInternal'; +/** + * Schemes of documents that next edit suggestions never track. Users don't type in them, and their + * content changes would show up as misleading recent edits in other documents' prompts. + * + * Every other scheme is tracked: under unification, next edit suggestions replace ghost text, which + * served any document whose scheme its own ignore list doesn't cover. + */ +const ignoredSchemes = new Set([ + 'output', // output pane (tracking it would log about itself in a loop) + 'search-editor', + 'comment', + 'git', + Schemas.chatEditingSnapshotScheme, + Schemas.chatEditingModel, + 'chat-editing-notebook-snapshot-model', + Schemas.vscodeChatCodeBlock, + Schemas.vscodeChatCodeCompareBlock, + Schemas.vscodeChatInput, + 'vscode-chat-terminal-output', +]); + export class DocumentFilter { private readonly _enabledLanguagesObs; private readonly _ignoreCompletionsDisablement; @@ -22,8 +43,7 @@ export class DocumentFilter { } public async isTrackingEnabled(document: TextDocument | NotebookDocument): Promise { - // this should filter out documents coming from output pane, git fs, etc. - if (!['file', 'untitled'].includes(document.uri.scheme) && !isNotebookCellOrNotebookChatInput(document.uri)) { + if (ignoredSchemes.has(document.uri.scheme)) { return false; } if (isTextDocument(document) && !this.isLanguageEnabled(document.languageId)) { diff --git a/extensions/copilot/src/extension/prompt/node/repoInfoTelemetry.ts b/extensions/copilot/src/extension/prompt/node/repoInfoTelemetry.ts index c34f9950a0c4..77677485aefa 100644 --- a/extensions/copilot/src/extension/prompt/node/repoInfoTelemetry.ts +++ b/extensions/copilot/src/extension/prompt/node/repoInfoTelemetry.ts @@ -10,6 +10,7 @@ import { RelativePattern } from '../../../platform/filesystem/common/fileTypes'; import { IGitDiffService } from '../../../platform/git/common/gitDiffService'; import { IGitExtensionService } from '../../../platform/git/common/gitExtensionService'; import { getOrderedRepoInfosFromContext, IGitService, normalizeFetchUrl, RepoContext, ResolvedRepoRemoteInfo } from '../../../platform/git/common/gitService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change, Repository } from '../../../platform/git/vscode/git'; import { ILogService } from '../../../platform/log/common/logService'; import { ITelemetryService, multiplexProperties } from '../../../platform/telemetry/common/telemetry'; diff --git a/extensions/copilot/src/extension/prompts/node/agent/backgroundTodoAgent/backgroundTodoAgentProcessor.ts b/extensions/copilot/src/extension/prompts/node/agent/backgroundTodoAgent/backgroundTodoAgentProcessor.ts index ff99ceb6b0de..0e8249b08104 100644 --- a/extensions/copilot/src/extension/prompts/node/agent/backgroundTodoAgent/backgroundTodoAgentProcessor.ts +++ b/extensions/copilot/src/extension/prompts/node/agent/backgroundTodoAgent/backgroundTodoAgentProcessor.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import type { CancellationToken, ChatParticipantToolToken, Uri } from 'vscode'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { IEndpointProvider } from '../../../../../lib/node/chatLibMain'; import { ILogger, ILogService } from '../../../../../platform/log/common/logService'; import { IChatEndpoint } from '../../../../../platform/networking/common/networking'; diff --git a/extensions/copilot/src/extension/prompts/node/agent/test/systemInitiatedHistory.spec.tsx b/extensions/copilot/src/extension/prompts/node/agent/test/systemInitiatedHistory.spec.tsx index d6c5b9648b82..491d7c641196 100644 --- a/extensions/copilot/src/extension/prompts/node/agent/test/systemInitiatedHistory.spec.tsx +++ b/extensions/copilot/src/extension/prompts/node/agent/test/systemInitiatedHistory.spec.tsx @@ -12,6 +12,7 @@ import { ChatLocation } from '../../../../../platform/chat/common/commonTypes'; import { MockChatMLFetcher } from '../../../../../platform/chat/test/common/mockChatMLFetcher'; import { rawPartAsThinkingData } from '../../../../../platform/endpoint/common/thinkingDataContainer'; import { MockEndpoint } from '../../../../../platform/endpoint/test/node/mockEndpoint'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { ExtensionContributedChatEndpoint } from '../../../../../platform/endpoint/vscode-node/extChatEndpoint'; import { IChatEndpoint } from '../../../../../platform/networking/common/networking'; import { ITestingServicesAccessor } from '../../../../../platform/test/node/services'; @@ -23,7 +24,9 @@ import { Event } from '../../../../../util/vs/base/common/event'; import { SyncDescriptor } from '../../../../../util/vs/platform/instantiation/common/descriptors'; import { IInstantiationService } from '../../../../../util/vs/platform/instantiation/common/instantiation'; import { LanguageModelChatToolMode, LanguageModelTextPart, LanguageModelToolResult } from '../../../../../vscodeTypes'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { IBYOKStorageService } from '../../../../byok/vscode-node/byokStorageService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { CustomEndpointBYOKModelProvider } from '../../../../byok/vscode-node/customEndpointProvider'; import { ConversationStore, IConversationStore } from '../../../../conversationStore/node/conversationStore'; import { IIntentService, IntentService } from '../../../../intents/node/intentService'; diff --git a/extensions/copilot/src/extension/prompts/node/agent/test/thinkingHistory.spec.tsx b/extensions/copilot/src/extension/prompts/node/agent/test/thinkingHistory.spec.tsx index 0c134bdd806a..4418f73dcdab 100644 --- a/extensions/copilot/src/extension/prompts/node/agent/test/thinkingHistory.spec.tsx +++ b/extensions/copilot/src/extension/prompts/node/agent/test/thinkingHistory.spec.tsx @@ -12,6 +12,7 @@ import { MockChatMLFetcher } from '../../../../../platform/chat/test/common/mock import { ConfigKey, IConfigurationService } from '../../../../../platform/configuration/common/configurationService'; import { ModelSupportedEndpoint } from '../../../../../platform/endpoint/common/endpointProvider'; import { CopilotChatEndpoint } from '../../../../../platform/endpoint/node/copilotChatEndpoint'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { ExtensionContributedChatEndpoint } from '../../../../../platform/endpoint/vscode-node/extChatEndpoint'; import { FinishedCallback, IResponseDelta } from '../../../../../platform/networking/common/fetch'; import { IChatEndpoint, IEndpointBody } from '../../../../../platform/networking/common/networking'; @@ -26,6 +27,7 @@ import { SyncDescriptor } from '../../../../../util/vs/platform/instantiation/co import { IInstantiationService } from '../../../../../util/vs/platform/instantiation/common/instantiation'; import { LanguageModelChatToolMode, LanguageModelTextPart, LanguageModelToolResult } from '../../../../../vscodeTypes'; import { resolveModelInfo } from '../../../../byok/common/byokProvider'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { CustomEndpointBYOKModelProvider, CustomEndpointModelConfig } from '../../../../byok/vscode-node/customEndpointProvider'; import { ChatVariablesCollection } from '../../../../prompt/common/chatVariablesCollection'; import { Conversation, Turn, TurnStatus } from '../../../../prompt/common/conversation'; diff --git a/extensions/copilot/src/extension/prompts/node/feedback/currentChange.tsx b/extensions/copilot/src/extension/prompts/node/feedback/currentChange.tsx index 917d98f5071c..b32228506e9b 100644 --- a/extensions/copilot/src/extension/prompts/node/feedback/currentChange.tsx +++ b/extensions/copilot/src/extension/prompts/node/feedback/currentChange.tsx @@ -6,6 +6,7 @@ import { BasePromptElementProps, PromptElement, PromptPiece, PromptReference, Pr import type { Position, Selection, TextDocument } from 'vscode'; import { TextDocumentSnapshot } from '../../../../platform/editing/common/textDocumentSnapshot'; import { IGitExtensionService } from '../../../../platform/git/common/gitExtensionService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Repository } from '../../../../platform/git/vscode/git'; import { IIgnoreService } from '../../../../platform/ignore/common/ignoreService'; import { ILogService } from '../../../../platform/log/common/logService'; diff --git a/extensions/copilot/src/extension/prompts/node/panel/startDebugging.tsx b/extensions/copilot/src/extension/prompts/node/panel/startDebugging.tsx index aca32c44b3e4..00e3a95d87cf 100644 --- a/extensions/copilot/src/extension/prompts/node/panel/startDebugging.tsx +++ b/extensions/copilot/src/extension/prompts/node/panel/startDebugging.tsx @@ -11,7 +11,6 @@ import { IEnvService } from '../../../../platform/env/common/envService'; import { IExtensionsService } from '../../../../platform/extensions/common/extensionsService'; import { IFileSystemService } from '../../../../platform/filesystem/common/fileSystemService'; import { IIgnoreService } from '../../../../platform/ignore/common/ignoreService'; -import { ICodeOrDocsSearchItem } from '../../../../platform/remoteSearch/common/codeOrDocsSearchClient'; import { IWorkspaceService } from '../../../../platform/workspace/common/workspaceService'; import { CancellationToken } from '../../../../util/vs/base/common/cancellation'; import { ResourceSet } from '../../../../util/vs/base/common/map'; @@ -64,7 +63,6 @@ export interface StartDebuggingPromptProps extends BasePromptElementProps { } export interface StartDebuggingPromptState { - docSearchResults?: ICodeOrDocsSearchItem[]; resources?: URI[]; schema?: string[]; } @@ -378,18 +376,6 @@ export class StartDebuggingPrompt extends PromptElement - - {state.docSearchResults && state.docSearchResults.length > 0 && <>Below is a list of information from the Visual Studio Code documentation which might be relevant to the question.
} - {state.docSearchResults && state.docSearchResults.map((result) => { - if (result?.title && result.contents) { - // eslint-disable-next-line local/code-no-unused-expressions - - ##{result?.title?.trim()} - {result.path}
- {result.contents} -
; - } - })} -
{state.schema && <>Below is a list of properties that the launch config might include.
{state.schema.map((property) => { diff --git a/extensions/copilot/src/extension/review/node/githubReviewAgent.ts b/extensions/copilot/src/extension/review/node/githubReviewAgent.ts index 8e4fa084422f..08cdada13631 100644 --- a/extensions/copilot/src/extension/review/node/githubReviewAgent.ts +++ b/extensions/copilot/src/extension/review/node/githubReviewAgent.ts @@ -16,6 +16,7 @@ import { ICAPIClientService } from '../../../platform/endpoint/common/capiClient import { IDomainService } from '../../../platform/endpoint/common/domainService'; import { IEnvService } from '../../../platform/env/common/envService'; import { IGitExtensionService } from '../../../platform/git/common/gitExtensionService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { API, Repository } from '../../../platform/git/vscode/git'; import { IIgnoreService } from '../../../platform/ignore/common/ignoreService'; import { ILogService } from '../../../platform/log/common/logService'; diff --git a/extensions/copilot/src/extension/test/vscode-node/configurations.test.ts b/extensions/copilot/src/extension/test/vscode-node/configurations.test.ts index d7a9f9b09017..794d1bd3a9c7 100644 --- a/extensions/copilot/src/extension/test/vscode-node/configurations.test.ts +++ b/extensions/copilot/src/extension/test/vscode-node/configurations.test.ts @@ -24,8 +24,11 @@ suite('Configuration Defaults', () => { _serviceBrand: undefined, copilotToken: undefined, onDidStoreUpdate: Event.None, + onDidChangeTokenData: Event.None, githubEnterpriseUri: undefined, - onDidChangeGitHubEnterpriseUri: Event.None + onDidChangeGitHubEnterpriseUri: Event.None, + authenticationState: 'unknown', + onDidChangeAuthenticationState: Event.None }); }); diff --git a/extensions/copilot/src/extension/tools/node/findTextInFilesTool.tsx b/extensions/copilot/src/extension/tools/node/findTextInFilesTool.tsx index 1eb6050e1e04..35721c999fa9 100644 --- a/extensions/copilot/src/extension/tools/node/findTextInFilesTool.tsx +++ b/extensions/copilot/src/extension/tools/node/findTextInFilesTool.tsx @@ -30,6 +30,7 @@ import { Tag } from '../../prompts/node/base/tag'; import { ToolName } from '../common/toolNames'; import { CopilotToolMode, ICopilotTool, ToolRegistry } from '../common/toolsRegistry'; import { checkCancellation, InputGlobResult, inputGlobToPattern, patternContainsWorkspaceFolderPath } from './toolUtils'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { IExperimentationService } from '../../../lib/node/chatLibMain'; import { IGrepResultService } from './grepResultService'; diff --git a/extensions/copilot/src/extension/tools/node/scmChangesTool.ts b/extensions/copilot/src/extension/tools/node/scmChangesTool.ts index e1a428cde03b..c5189c56c678 100644 --- a/extensions/copilot/src/extension/tools/node/scmChangesTool.ts +++ b/extensions/copilot/src/extension/tools/node/scmChangesTool.ts @@ -7,6 +7,7 @@ import * as l10n from '@vscode/l10n'; import type * as vscode from 'vscode'; import { Diff, IGitDiffService } from '../../../platform/git/common/gitDiffService'; import { IGitService } from '../../../platform/git/common/gitService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change } from '../../../platform/git/vscode/git'; import { ILogService } from '../../../platform/log/common/logService'; import { IPromptPathRepresentationService } from '../../../platform/prompts/common/promptPathRepresentationService'; diff --git a/extensions/copilot/src/extension/tools/test/node/applyPatch/parser.spec.ts b/extensions/copilot/src/extension/tools/test/node/applyPatch/parser.spec.ts index 4df47f12863c..1e5c7dc57f18 100644 --- a/extensions/copilot/src/extension/tools/test/node/applyPatch/parser.spec.ts +++ b/extensions/copilot/src/extension/tools/test/node/applyPatch/parser.spec.ts @@ -563,7 +563,7 @@ suite('applyPatch parser', () => { ]; const linesToModify: number[] = []; - for (let i = random(1, maxEditsPerFile); linesToModify.length < i;) { + for (const i = random(1, maxEditsPerFile); linesToModify.length < i;) { const r = random(0, lines.length - 1); if (!linesToModify.includes(r)) { linesToModify.push(r); diff --git a/extensions/copilot/src/extension/typescriptContext/common/serverProtocol.ts b/extensions/copilot/src/extension/typescriptContext/common/serverProtocol.ts index a01dbf4571e3..a051d60db764 100644 --- a/extensions/copilot/src/extension/typescriptContext/common/serverProtocol.ts +++ b/extensions/copilot/src/extension/typescriptContext/common/serverProtocol.ts @@ -659,3 +659,118 @@ export namespace NesRenameResponse { export type NesRenameResponse = (tt.server.protocol.Response & { body: NesRenameResponse.OK | NesRenameResponse.Failed; }) | { type: 'cancelled' }; + +/** + * A text range given as zero-based UTF-16 offsets, with an exclusive end. + */ +export type OffsetRange = { + start: number; + end: number; +}; + +/** + * A textual change between the original and the modified text of a structural diff request. + */ +export type DiffTextChange = { + original: OffsetRange; + modified: OffsetRange; +}; + +export interface StructuralDiffRequestArgs { + /** + * The file whose versions are compared. Its name decides how both texts are parsed, names the + * root entity and identifies test files. The file itself is not read. + */ + fileName: FilePath; + originalText: string; + modifiedText: string; + changes: readonly DiffTextChange[]; +} + +export interface StructuralDiffRequest extends tt.server.protocol.Request { + arguments?: StructuralDiffRequestArgs; +} + +export enum StructuralDiffSymbolKind { + File = 'file', + Module = 'module', + Class = 'class', + Method = 'method', + Property = 'property', + Constructor = 'constructor', + Enum = 'enum', + Interface = 'interface', + Function = 'function', + Variable = 'variable', + Object = 'object', + Array = 'array', + EnumMember = 'enumMember' +} + +export enum StructuralDiffClassification { + Declaration = 'declaration', + Header = 'header', + Implementation = 'implementation', + Dependency = 'dependency', + Other = 'other' +} + +export enum StructuralDiffTag { + Test = 'test' +} + +/** + * A structural item as it appears in one text. Groups of import and export statements use the + * language kinds `imports` and `exports`. Their names are not localized. + */ +export type StructuralDiffItem = { + name: string; + kind: StructuralDiffSymbolKind; + languageKind?: string; + range: OffsetRange; + selectionRange?: OffsetRange; +}; + +export type StructuralDiffCoverage = { + textChangeIndex: number; + range: OffsetRange; + classification: StructuralDiffClassification; + tags: StructuralDiffTag[]; +}; + +export type StructuralDiffNode = { + id: string; + original?: StructuralDiffItem; + modified?: StructuralDiffItem; + originalChanges: StructuralDiffCoverage[]; + modifiedChanges: StructuralDiffCoverage[]; + children: StructuralDiffNode[]; +}; + +export type StructuralDiffResult = { + root: StructuralDiffNode; + isIncomplete: boolean; +}; + +export namespace StructuralDiffResponse { + + export type OK = StructuralDiffResult; + + export type Failed = CustomResponse.Failed; + + export function isCancelled(response: StructuralDiffResponse | undefined): boolean { + return response?.type === 'cancelled'; + } + + export function isOk(response: StructuralDiffResponse | undefined): response is Omit & { body: OK } { + return response?.type === 'response' && (response.body as OK | undefined)?.root !== undefined; + } + + export function isError(response: StructuralDiffResponse | undefined): response is Omit & { body: Failed } { + return response?.type === 'response' && (response.body as Failed | undefined)?.error !== undefined; + } +} + +export type StructuralDiffResponse = (tt.server.protocol.Response & { + body: StructuralDiffResponse.OK | StructuralDiffResponse.Failed; +}) | { type: 'cancelled' }; diff --git a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/protocol.ts b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/protocol.ts index a01dbf4571e3..a051d60db764 100644 --- a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/protocol.ts +++ b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/protocol.ts @@ -659,3 +659,118 @@ export namespace NesRenameResponse { export type NesRenameResponse = (tt.server.protocol.Response & { body: NesRenameResponse.OK | NesRenameResponse.Failed; }) | { type: 'cancelled' }; + +/** + * A text range given as zero-based UTF-16 offsets, with an exclusive end. + */ +export type OffsetRange = { + start: number; + end: number; +}; + +/** + * A textual change between the original and the modified text of a structural diff request. + */ +export type DiffTextChange = { + original: OffsetRange; + modified: OffsetRange; +}; + +export interface StructuralDiffRequestArgs { + /** + * The file whose versions are compared. Its name decides how both texts are parsed, names the + * root entity and identifies test files. The file itself is not read. + */ + fileName: FilePath; + originalText: string; + modifiedText: string; + changes: readonly DiffTextChange[]; +} + +export interface StructuralDiffRequest extends tt.server.protocol.Request { + arguments?: StructuralDiffRequestArgs; +} + +export enum StructuralDiffSymbolKind { + File = 'file', + Module = 'module', + Class = 'class', + Method = 'method', + Property = 'property', + Constructor = 'constructor', + Enum = 'enum', + Interface = 'interface', + Function = 'function', + Variable = 'variable', + Object = 'object', + Array = 'array', + EnumMember = 'enumMember' +} + +export enum StructuralDiffClassification { + Declaration = 'declaration', + Header = 'header', + Implementation = 'implementation', + Dependency = 'dependency', + Other = 'other' +} + +export enum StructuralDiffTag { + Test = 'test' +} + +/** + * A structural item as it appears in one text. Groups of import and export statements use the + * language kinds `imports` and `exports`. Their names are not localized. + */ +export type StructuralDiffItem = { + name: string; + kind: StructuralDiffSymbolKind; + languageKind?: string; + range: OffsetRange; + selectionRange?: OffsetRange; +}; + +export type StructuralDiffCoverage = { + textChangeIndex: number; + range: OffsetRange; + classification: StructuralDiffClassification; + tags: StructuralDiffTag[]; +}; + +export type StructuralDiffNode = { + id: string; + original?: StructuralDiffItem; + modified?: StructuralDiffItem; + originalChanges: StructuralDiffCoverage[]; + modifiedChanges: StructuralDiffCoverage[]; + children: StructuralDiffNode[]; +}; + +export type StructuralDiffResult = { + root: StructuralDiffNode; + isIncomplete: boolean; +}; + +export namespace StructuralDiffResponse { + + export type OK = StructuralDiffResult; + + export type Failed = CustomResponse.Failed; + + export function isCancelled(response: StructuralDiffResponse | undefined): boolean { + return response?.type === 'cancelled'; + } + + export function isOk(response: StructuralDiffResponse | undefined): response is Omit & { body: OK } { + return response?.type === 'response' && (response.body as OK | undefined)?.root !== undefined; + } + + export function isError(response: StructuralDiffResponse | undefined): response is Omit & { body: Failed } { + return response?.type === 'response' && (response.body as Failed | undefined)?.error !== undefined; + } +} + +export type StructuralDiffResponse = (tt.server.protocol.Response & { + body: StructuralDiffResponse.OK | StructuralDiffResponse.Failed; +}) | { type: 'cancelled' }; diff --git a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/structuralDiff.ts b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/structuralDiff.ts new file mode 100644 index 000000000000..b3016ce141f9 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/structuralDiff.ts @@ -0,0 +1,609 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import type tt from 'typescript/lib/tsserverlibrary'; +import TS from './typescript'; +const ts = TS(); + +import { StructuralDiffClassification, StructuralDiffSymbolKind, StructuralDiffTag, type DiffTextChange, type StructuralDiffItem, type StructuralDiffNode, type StructuralDiffRequestArgs, type StructuralDiffResult } from './protocol'; +import tss from './typescripts'; + +interface Span { + readonly start: number; + readonly end: number; +} + +/** + * Spans in document order that do not overlap, so that their ends are in order as well. + */ +type SortedSpans = readonly Span[]; + +interface EntityInfo { + readonly name: string; + readonly kind: StructuralDiffSymbolKind; + readonly languageKind: string; + readonly node: tt.Node; + readonly rangeNode: tt.Node; + readonly nameNode?: tt.Node; + readonly body?: tt.Node; +} + +interface Entity { + readonly value: StructuralDiffItem; + readonly node: tt.Node; + readonly span: Span; + readonly groupedSpans?: readonly Span[]; + readonly headerEnd: number; + readonly implementation: SortedSpans; + readonly isTest: boolean; + readonly children: Entity[]; + readonly rename?: { readonly name: Span; readonly declaration: tt.Node }; +} + +interface Source { + readonly file: tt.SourceFile; + readonly root: Entity; + readonly dependencies: SortedSpans; + readonly tests: SortedSpans; +} + +interface DiffTree { + readonly original?: Entity; + readonly modified?: Entity; + readonly result: StructuralDiffNode; + readonly children: DiffTree[]; + /** The spans of the children on each side, sorted by their start. */ + readonly childSpans: Readonly>; +} + +interface ChildSpan { + readonly child: DiffTree; + readonly span: Span; + /** The largest end of this and all preceding spans, which, unlike the ends, cannot decrease if siblings overlap. */ + readonly reach: number; +} + +type Side = 'original' | 'modified'; + +/** + * Parses both texts without a project and matches named siblings and conservative name-only renames + * in a sparse structural tree. This is the TS6 counterpart of the TS7 implementation. + */ +export function computeStructuralDiff(args: StructuralDiffRequestArgs, token: tt.CancellationToken): StructuralDiffResult { + const checkCancellation = () => token.throwIfCancellationRequested(); + const originalFile = ts.createSourceFile(args.fileName, args.originalText, ts.ScriptTarget.Latest, true); + checkCancellation(); + const modifiedFile = ts.createSourceFile(args.fileName, args.modifiedText, ts.ScriptTarget.Latest, true); + const original = collectSource(originalFile, checkCancellation); + const modified = collectSource(modifiedFile, checkCancellation); + const changes = args.changes; + let nextId = 0; + const merge = (left: Entity | undefined, right: Entity | undefined): DiffTree => { + checkCancellation(); + const result: StructuralDiffNode = { + id: String(nextId++), + original: left?.value, + modified: right?.value, + originalChanges: [], + modifiedChanges: [], + children: [], + }; + const leftChildren = left?.children ?? []; + const rightChildren = right?.children ?? []; + const counterparts = matchSiblings(leftChildren, rightChildren, originalFile, modifiedFile, changes, checkCancellation); + const matched = new Set(); + const children = rightChildren.map(child => { + const counterpart = counterparts.get(child); + if (counterpart !== undefined) { + matched.add(counterpart); + } + return merge(counterpart, child); + }); + for (const child of leftChildren) { + if (!matched.has(child)) { + children.push(merge(child, undefined)); + } + } + return { original: left, modified: right, result, children, childSpans: { original: getChildSpans(children, 'original'), modified: getChildSpans(children, 'modified') } }; + }; + const tree = merge(original.root, modified.root); + for (const [textChangeIndex, change] of changes.entries()) { + checkCancellation(); + classify(tree, 'original', original, textChangeIndex, change.original, checkCancellation); + classify(tree, 'modified', modified, textChangeIndex, change.modified, checkCancellation); + } + const prune = (node: DiffTree): StructuralDiffNode => { + for (const child of node.children) { + const result = prune(child); + if (result.originalChanges.length > 0 || result.modifiedChanges.length > 0 || result.children.length > 0) { + node.result.children.push(result); + } + } + return node.result; + }; + checkCancellation(); + return { root: prune(tree), isIncomplete: false }; +} + +function collectSource(file: tt.SourceFile, checkCancellation: () => void): Source { + const root: Entity = { + value: { name: getBaseFileName(file.fileName), kind: StructuralDiffSymbolKind.File, range: { start: 0, end: file.text.length } }, + node: file, + span: { start: 0, end: file.text.length }, + headerEnd: 0, + implementation: file.statements.map(statement => nodeSpan(statement, file)), + isTest: isTestFile(file.fileName), + children: [], + }; + const dependencies: Span[] = []; + const tests: Span[] = []; + const statementGroups = new Map>(); + const visit = (node: tt.Node, parent: Entity): void => { + checkCancellation(); + if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) || (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined)) { + dependencies.push(nodeSpan(node, file)); + } + const groupKind = ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) ? 'imports' + : ts.isExportDeclaration(node) || ts.isExportAssignment(node) || ts.isNamespaceExportDeclaration(node) ? 'exports' : undefined; + if (groupKind !== undefined) { + let groups = statementGroups.get(parent); + if (groups === undefined) { + groups = new Map(); + statementGroups.set(parent, groups); + } + const span = nodeSpan(node, file); + const spans = groups.get(groupKind); + if (spans === undefined) { + groups.set(groupKind, [span]); + } else { + spans.push(span); + } + } + if (ts.isCallExpression(node) && isTestCallee(node.expression)) { + for (const argument of node.arguments) { + if (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)) { + tests.push(nodeSpan(argument, file)); + } + } + } + let container = parent; + const info = node === parent.node ? undefined : getEntityInfo(node, file); + if (info !== undefined) { + const span = nodeSpan(info.rangeNode, file); + if (span.start < span.end && contains(parent.span, span)) { + const children = structuralChildren(info.node); + const headerEnd = info.body?.getStart(file) ?? children[0]?.getStart(file) ?? span.end; + container = { + value: { + name: info.name, + kind: info.kind, + languageKind: info.languageKind, + range: span, + selectionRange: info.nameNode === undefined ? undefined : nodeSpan(info.nameNode, file), + }, + node: info.node, + span, + headerEnd, + implementation: bodySpans(info.body, file), + isTest: parent.isTest || /^(?:it|test|spec)(?:$|[\s_.:-]|[A-Z])/.test(info.name), + children: [], + rename: info.nameNode && (ts.isIdentifier(info.nameNode) || ts.isPrivateIdentifier(info.nameNode)) + ? { name: nodeSpan(info.nameNode, file), declaration: info.rangeNode } + : undefined, + }; + parent.children.push(container); + } + } + ts.forEachChild(node, child => visit(child, container)); + }; + ts.forEachChild(file, child => visit(child, root)); + for (const [parent, groups] of statementGroups) { + for (const [kind, spans] of groups) { + checkCancellation(); + const span = { start: spans[0].start, end: spans[spans.length - 1].end }; + const isInStatement = createContainmentLookup(spans); + const children = parent.children.filter(child => isInStatement(child.span)); + const childSet = new Set(children); + parent.children.splice(0, parent.children.length, ...parent.children.filter(child => !childSet.has(child))); + parent.children.push({ + value: { + name: kind === 'imports' ? 'Imports' : 'Exports', + kind: StructuralDiffSymbolKind.Module, + languageKind: kind, + range: span, + selectionRange: spans[0], + }, + node: parent.node, + span, + groupedSpans: spans, + headerEnd: span.start, + implementation: spans, + isTest: parent.isTest, + children, + }); + } + parent.children.sort((left, right) => left.span.start - right.span.start); + } + // Test callbacks can be nested, but the classification only asks whether text lies in any of them. + return { file, root, dependencies: toSortedSpans(dependencies), tests: toSortedSpans(tests) }; +} + +function getEntityInfo(node: tt.Node, file: tt.SourceFile): EntityInfo | undefined { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) { + let rangeNode: tt.Node = node; + if (ts.isVariableDeclaration(node) && ts.isVariableDeclarationList(node.parent) + && node.parent.declarations.length === 1 && ts.isVariableStatement(node.parent.parent)) { + rangeNode = node.parent.parent; + } + const initializer = node.initializer && tss.Nodes.skipOuterExpressions(node.initializer); + const base = { name: node.name.getText(file), nameNode: node.name, rangeNode }; + if (initializer !== undefined) { + if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) { + return { ...base, node: initializer, kind: StructuralDiffSymbolKind.Function, languageKind: ts.isArrowFunction(initializer) ? 'arrow-function' : 'function', body: initializer.body }; + } + if (ts.isClassExpression(initializer)) { + return { ...base, node: initializer, kind: StructuralDiffSymbolKind.Class, languageKind: 'class' }; + } + if (ts.isObjectLiteralExpression(initializer) || ts.isArrayLiteralExpression(initializer)) { + return { ...base, node: initializer, kind: ts.isObjectLiteralExpression(initializer) ? StructuralDiffSymbolKind.Object : StructuralDiffSymbolKind.Array, languageKind: ts.isObjectLiteralExpression(initializer) ? 'object' : 'array', body: initializer }; + } + } + return { ...base, node, kind: ts.isVariableDeclaration(node) ? StructuralDiffSymbolKind.Variable : StructuralDiffSymbolKind.Property, languageKind: ts.isVariableDeclaration(node) ? 'variable' : 'property', body: node.initializer }; + } + const base = { node, rangeNode: node }; + if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) { + const name = node.name?.getText(file) ?? (node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined); + return name === undefined ? undefined : { ...base, name, nameNode: node.name, kind: StructuralDiffSymbolKind.Class, languageKind: 'class' }; + } + if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node) || ts.isModuleDeclaration(node)) { + const kind = ts.isInterfaceDeclaration(node) ? StructuralDiffSymbolKind.Interface + : ts.isTypeAliasDeclaration(node) ? StructuralDiffSymbolKind.Variable + : ts.isEnumDeclaration(node) ? StructuralDiffSymbolKind.Enum : StructuralDiffSymbolKind.Module; + const languageKind = ts.isInterfaceDeclaration(node) ? 'interface' : ts.isTypeAliasDeclaration(node) ? 'type-alias' : ts.isEnumDeclaration(node) ? 'enum' : 'module'; + return { ...base, name: node.name.getText(file), nameNode: node.name, kind, languageKind, body: ts.isModuleDeclaration(node) ? node.body : undefined }; + } + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) { + const name = node.name?.getText(file) ?? (ts.isFunctionDeclaration(node) && node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined); + return name === undefined ? undefined : { ...base, name, nameNode: node.name, kind: StructuralDiffSymbolKind.Function, languageKind: 'function', body: node.body }; + } + if (ts.isConstructorDeclaration(node)) { + return { ...base, name: 'constructor', kind: StructuralDiffSymbolKind.Constructor, languageKind: 'constructor', body: node.body }; + } + if (ts.isMethodDeclaration(node) || ts.isMethodSignature(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: StructuralDiffSymbolKind.Method, languageKind: 'method', body: ts.isMethodDeclaration(node) ? node.body : undefined }; + } + if (ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: StructuralDiffSymbolKind.Property, languageKind: ts.isGetAccessorDeclaration(node) ? 'getter' : 'setter', body: node.body }; + } + if (ts.isPropertySignature(node) || ts.isEnumMember(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: ts.isEnumMember(node) ? StructuralDiffSymbolKind.EnumMember : StructuralDiffSymbolKind.Property, languageKind: ts.isEnumMember(node) ? 'enum-member' : 'property', body: ts.isEnumMember(node) ? node.initializer : undefined }; + } + if (ts.isClassStaticBlockDeclaration(node)) { + return { ...base, name: 'static', kind: StructuralDiffSymbolKind.Method, languageKind: 'static-block', body: node.body }; + } + if (ts.isCallSignatureDeclaration(node) || ts.isConstructSignatureDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + const name = ts.isCallSignatureDeclaration(node) ? '(call)' : ts.isConstructSignatureDeclaration(node) ? '(new)' : '[index]'; + return { ...base, name, kind: ts.isConstructSignatureDeclaration(node) ? StructuralDiffSymbolKind.Constructor : StructuralDiffSymbolKind.Method, languageKind: ts.isCallSignatureDeclaration(node) ? 'call-signature' : ts.isConstructSignatureDeclaration(node) ? 'construct-signature' : 'index-signature' }; + } + return undefined; +} + +function structuralChildren(node: tt.Node): readonly tt.Node[] { + if (ts.isClassDeclaration(node) || ts.isClassExpression(node) || ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)) { + return node.members; + } + return []; +} + +function bodySpans(body: tt.Node | undefined, file: tt.SourceFile): readonly Span[] { + if (body === undefined) { + return []; + } + if (ts.isBlock(body) || ts.isModuleBlock(body)) { + return [{ start: body.getStart(file) + 1, end: Math.max(body.getStart(file) + 1, body.getEnd() - 1) }]; + } + return [nodeSpan(body, file)]; +} + +function entityKey(entity: Entity): string { + return JSON.stringify([entity.value.kind, entity.value.languageKind, entity.value.name]); +} + +function groupEntities(entities: readonly Entity[], keyOf: (entity: Entity) => string | undefined = entityKey): Map { + const groups = new Map(); + for (const entity of entities) { + const key = keyOf(entity); + if (key === undefined) { + continue; + } + const group = groups.get(key); + if (group === undefined) { + groups.set(key, [entity]); + } else { + group.push(entity); + } + } + return groups; +} + +function matchSiblings(original: readonly Entity[], modified: readonly Entity[], originalFile: tt.SourceFile, modifiedFile: tt.SourceFile, changes: readonly DiffTextChange[], checkCancellation: () => void): Map { + const originalByKey = groupEntities(original); + const modifiedByKey = groupEntities(modified); + const matches = new Map(); + const matchedOriginal = new Set(); + for (const entity of modified) { + checkCancellation(); + const key = entityKey(entity); + const candidates = originalByKey.get(key); + if (candidates?.length === 1 && modifiedByKey.get(key)?.length === 1) { + matches.set(entity, candidates[0]); + matchedOriginal.add(candidates[0]); + } + } + + const unmatchedOriginal = original.filter(entity => !matchedOriginal.has(entity) && originalByKey.get(entityKey(entity))?.length === 1); + const unmatchedModified = modified.filter(entity => !matches.has(entity) && modifiedByKey.get(entityKey(entity))?.length === 1); + if (unmatchedOriginal.length === 0 || unmatchedModified.length === 0) { + return matches; + } + const originalBySyntax = groupEntities(unmatchedOriginal, entity => renameFingerprint(entity, originalFile, checkCancellation)); + const modifiedBySyntax = groupEntities(unmatchedModified, entity => renameFingerprint(entity, modifiedFile, checkCancellation)); + for (const [fingerprint, candidates] of modifiedBySyntax) { + checkCancellation(); + const originalCandidates = originalBySyntax.get(fingerprint); + if (candidates.length !== 1 || originalCandidates?.length !== 1) { + continue; + } + const before = originalCandidates[0]; + const after = candidates[0]; + if (before.value.name !== after.value.name && isNameChanged(changes, before.rename!.name, after.rename!.name)) { + matches.set(after, before); + } + } + return matches; +} + +function renameFingerprint(entity: Entity, file: tt.SourceFile, checkCancellation: () => void): string | undefined { + if (entity.rename === undefined) { + return undefined; + } + const { name, declaration } = entity.rename; + const parts: [tt.SyntaxKind, string | null][] = []; + let nameTokens = 0; + let missingToken = false; + const visit = (node: tt.Node): void => { + checkCancellation(); + if (isJSDocNodeKind(node.kind) || isTriviaKind(node.kind)) { + return; + } + if (ts.isToken(node)) { + const span = nodeSpan(node, file); + if (span.start === span.end) { + missingToken = true; + } else if (span.start === name.start && span.end === name.end) { + nameTokens++; + parts.push([node.kind, null]); + } else { + parts.push([node.kind, node.getText(file)]); + } + } else { + parts.push([node.kind, null]); + node.getChildren(file).forEach(visit); + } + }; + visit(declaration); + return nameTokens === 1 && !missingToken + ? JSON.stringify([entity.value.kind, entity.value.languageKind, parts]) + : undefined; +} + +function touchesName(change: Span, name: Span): boolean { + return change.start === change.end + ? name.start <= change.start && change.start <= name.end + : change.start < name.end && name.start < change.end; +} + +/** + * Returns whether one change touches both the original and the modified name. The changes are ordered and do not + * overlap, so a binary search finds the ones around the original name, and renaming many declarations does not check + * every change for each of them. + */ +function isNameChanged(changes: readonly DiffTextChange[], originalName: Span, modifiedName: Span): boolean { + for (let index = findFirstIndex(changes, change => change.original.end >= originalName.start); index < changes.length && changes[index].original.start <= originalName.end; index++) { + if (touchesName(changes[index].original, originalName) && touchesName(changes[index].modified, modifiedName)) { + return true; + } + } + return false; +} + +function classify(tree: DiffTree, side: Side, source: Source, textChangeIndex: number, span: Span, checkCancellation: () => void): void { + checkCancellation(); + const entity = tree[side]; + if (entity === undefined || span.start >= span.end) { + return; + } + const counterpart = side === 'original' ? tree.modified : tree.original; + if (entity !== source.root && entity.groupedSpans === undefined && counterpart === undefined && contains(span, entity.span)) { + addCoverage(tree, side, source, textChangeIndex, span, StructuralDiffClassification.Declaration); + return; + } + let cursor = span.start; + const children = tree.childSpans[side]; + // A binary search skips the children before the span and the loop stops at the first child after it, so that + // bulk edits do not visit every sibling for every change. + for (let index = findFirstIndex(children, child => child.reach > span.start); index < children.length && children[index].span.start < span.end; index++) { + const { child, span: childSpan } = children[index]; + const start = Math.max(cursor, childSpan.start); + const end = Math.min(span.end, childSpan.end); + if (start >= end) { + continue; + } + addCoverage(tree, side, source, textChangeIndex, { start: cursor, end: start }); + classify(child, side, source, textChangeIndex, { start, end }, checkCancellation); + cursor = end; + } + addCoverage(tree, side, source, textChangeIndex, { start: cursor, end: span.end }); +} + +function getChildSpans(children: readonly DiffTree[], side: Side): ChildSpan[] { + const spans = children.flatMap(child => { + const entity = child[side]; + return entity === undefined ? [] : (entity.groupedSpans ?? [entity.span]).map(span => ({ child, span })); + }).sort((left, right) => left.span.start - right.span.start); + let reach = 0; + return spans.map(({ child, span }) => { + reach = Math.max(reach, span.end); + return { child, span, reach }; + }); +} + +function addCoverage(tree: DiffTree, side: Side, source: Source, textChangeIndex: number, span: Span, classification?: StructuralDiffClassification): void { + if (span.start >= span.end) { + return; + } + const entity = tree[side]!; + const header = { start: entity.span.start, end: entity.headerEnd }; + // Only regions that overlap the span can split it, so the many gaps between the declarations of a new file stay cheap. + const dependencies = getOverlappingSpans(source.dependencies, span); + const implementation = getOverlappingSpans(entity.implementation, span); + const tests = getOverlappingSpans(source.tests, span); + const boundaries = new Set([span.start, span.end]); + for (const region of [...dependencies, header, ...implementation, ...tests]) { + if (region.start > span.start && region.start < span.end) { + boundaries.add(region.start); + } + if (region.end > span.start && region.end < span.end) { + boundaries.add(region.end); + } + } + const offsets = [...boundaries].sort((left, right) => left - right); + const inDependency = createContainmentCheck(dependencies); + const inImplementation = createContainmentCheck(implementation); + const inTest = createContainmentCheck(tests); + const changes = side === 'original' ? tree.result.originalChanges : tree.result.modifiedChanges; + for (let index = 0; index < offsets.length - 1; index++) { + const part = { start: offsets[index], end: offsets[index + 1] }; + const kind = classification + ?? (inDependency(part) ? StructuralDiffClassification.Dependency + : contains(header, part) ? StructuralDiffClassification.Header + : inImplementation(part) ? StructuralDiffClassification.Implementation + : StructuralDiffClassification.Other); + const isTest = entity.isTest || inTest(part); + const previous = changes[changes.length - 1]; + if (previous?.textChangeIndex === textChangeIndex && previous.classification === kind + && previous.tags.includes(StructuralDiffTag.Test) === isTest && previous.range.end === part.start) { + changes[changes.length - 1] = { ...previous, range: { start: previous.range.start, end: part.end } }; + } else { + changes.push({ textChangeIndex, range: part, classification: kind, tags: isTest ? [StructuralDiffTag.Test] : [] }); + } + } +} + +function nodeSpan(node: tt.Node, file: tt.SourceFile): Span { + return { start: node.getStart(file), end: node.getEnd() }; +} + +function contains(container: Span, contained: Span): boolean { + return container.start <= contained.start && container.end >= contained.end; +} + +/** + * Returns sorted spans that cover the same offsets as the given spans, merging the ones that overlap. + */ +function toSortedSpans(spans: readonly Span[]): SortedSpans { + const result: Span[] = []; + for (const span of [...spans].sort((left, right) => left.start - right.start)) { + const last = result[result.length - 1]; + if (last !== undefined && span.start <= last.end) { + result[result.length - 1] = { start: last.start, end: Math.max(last.end, span.end) }; + } else { + result.push(span); + } + } + return result; +} + +function getOverlappingSpans(spans: SortedSpans, span: Span): SortedSpans { + const start = findFirstIndex(spans, candidate => candidate.end > span.start); + return spans.slice(start, findFirstIndex(spans, candidate => candidate.start >= span.end, start)); +} + +/** + * Returns a check whether a part lies within one of the spans. Parts must be checked in document order, which lets + * each check continue where the previous one stopped. + */ +function createContainmentCheck(spans: SortedSpans): (part: Span) => boolean { + let index = 0; + return part => { + while (index < spans.length && spans[index].end <= part.start) { + index++; + } + return index < spans.length && contains(spans[index], part); + }; +} + +/** + * Returns a lookup whether a span lies within one of the given spans, which must be sorted by their start. Unlike + * {@link createContainmentCheck}, the spans can overlap and can be looked up in any order: the spans that start at or + * before a span contain it if the largest of their ends reaches its end, which a binary search finds. + */ +function createContainmentLookup(spans: readonly Span[]): (span: Span) => boolean { + const reaches: number[] = []; + for (const span of spans) { + reaches.push(Math.max(reaches[reaches.length - 1] ?? span.end, span.end)); + } + return span => { + const count = findFirstIndex(spans, candidate => candidate.start > span.start); + return count > 0 && reaches[count - 1] >= span.end; + }; +} + +/** + * Returns the index of the first element that satisfies the predicate, or the array length if none does. The predicate + * must hold for all elements after that one. This is the plugin's copy of `findFirstIdxMonotonousOrArrLen`, which the + * TS7 implementation imports from `util/vs`. + */ +function findFirstIndex(array: readonly T[], predicate: (element: T) => boolean, low = 0): number { + let high = array.length; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (predicate(array[middle])) { + high = middle; + } else { + low = middle + 1; + } + } + return low; +} + +function isJSDocNodeKind(kind: tt.SyntaxKind): boolean { + return kind >= ts.SyntaxKind.FirstJSDocNode && kind <= ts.SyntaxKind.LastJSDocNode; +} + +function isTriviaKind(kind: tt.SyntaxKind): boolean { + return kind >= ts.SyntaxKind.FirstTriviaToken && kind <= ts.SyntaxKind.LastTriviaToken; +} + +function isTestCallee(node: tt.Node): boolean { + if (ts.isIdentifier(node)) { + return node.text === 'test' || node.text === 'it' || node.text === 'describe' || node.text === 'suite'; + } + if (ts.isPropertyAccessExpression(node) || ts.isCallExpression(node)) { + return isTestCallee(node.expression); + } + return false; +} + +function isTestFile(fileName: string): boolean { + const normalized = fileName.replace(/\\/g, '/'); + const name = normalized.slice(normalized.lastIndexOf('/') + 1); + return /(?:^|\/)(?:test|tests|__tests__)(?:\/|$)/i.test(normalized) + || /(?:^|[._-])(?:test|spec)(?=\.[^.]+$)/i.test(name) + || /^(?:test|spec)[._-]/i.test(name); +} + +function getBaseFileName(fileName: string): string { + return fileName.substring(Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\')) + 1); +} diff --git a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/typescripts.ts b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/typescripts.ts index 7506695256c9..d7e77392036d 100644 --- a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/typescripts.ts +++ b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/common/typescripts.ts @@ -218,6 +218,15 @@ namespace tss { } return undefined; } + + export function skipOuterExpressions(expression: tt.Expression): tt.Expression { + let current = expression; + while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isTypeAssertionExpression(current) + || ts.isNonNullExpression(current) || ts.isExpressionWithTypeArguments(current) || ts.isPartiallyEmittedExpression(current)) { + current = current.expression; + } + return current; + } } export namespace Declarations { diff --git a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/node/create.ts b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/node/create.ts index 63b0c1bb9f65..63f299aedfd3 100644 --- a/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/node/create.ts +++ b/extensions/copilot/src/extension/typescriptContext/serverPlugin/src/node/create.ts @@ -5,8 +5,9 @@ import type tt from 'typescript/lib/tsserverlibrary'; import { computeContext, nesRename, prepareNesRename } from '../common/api'; import { CharacterBudget, ComputeContextSession, ContextResult, NullLogger, RequestContext, TokenBudgetExhaustedError, type Logger } from '../common/contextProvider'; -import { ErrorCode, RenameKind, type CachedContextRunnableResult, type ComputeContextRequest, type ComputeContextResponse, type ContextRunnableResultId, type CustomResponse, type NesRenameRequest, type NesRenameResponse, type PingResponse, type PrepareNesRenameRequest, type PrepareNesRenameResponse, type Range, type RegionContextRequest, type RegionContextResponse, type RenameGroup } from '../common/protocol'; +import { ErrorCode, RenameKind, type CachedContextRunnableResult, type ComputeContextRequest, type ComputeContextResponse, type ContextRunnableResultId, type CustomResponse, type NesRenameRequest, type NesRenameResponse, type PingResponse, type PrepareNesRenameRequest, type PrepareNesRenameResponse, type Range, type RegionContextRequest, type RegionContextResponse, type RenameGroup, type StructuralDiffRequest, type StructuralDiffResponse } from '../common/protocol'; import { RegionContextProvider } from '../common/regionContextProvider'; +import { computeStructuralDiff } from '../common/structuralDiff'; import { CancellationTokenWithTimer, Sessions } from '../common/typescripts'; const ts = TS(); @@ -106,6 +107,10 @@ interface RegionContextHandlerResponse extends tt.server.HandlerResponse { response: RegionContextResponse.OK | RegionContextResponse.Failed; } +interface StructuralDiffHandlerResponse extends tt.server.HandlerResponse { + response: StructuralDiffResponse.OK | StructuralDiffResponse.Failed; +} + let installAttempted: boolean = false; let languageServerSession: LanguageServerSession | undefined = undefined; let languageServiceHost: tt.LanguageServiceHost | undefined = undefined; @@ -225,6 +230,31 @@ const regionContextHandler = (request: RegionContextRequest): RegionContextHandl } }; +const structuralDiffHandler = (request: StructuralDiffRequest): StructuralDiffHandlerResponse => { + const args = request.arguments; + if (args === undefined) { + return { response: { error: ErrorCode.noArguments, message: 'No arguments provided' }, responseRequired: true }; + } + if (typeof args.fileName !== 'string' || typeof args.originalText !== 'string' || typeof args.modifiedText !== 'string' || !Array.isArray(args.changes)) { + return { response: { error: ErrorCode.invalidArguments, message: 'Invalid structural diff arguments' }, responseRequired: true }; + } + + // The client cancels the request, so there is no time budget. + const cancellationToken = new CancellationTokenWithTimer(languageServiceHost?.getCancellationToken ? languageServiceHost.getCancellationToken() : undefined, Date.now(), Number.POSITIVE_INFINITY, languageServerSession?.host.isDebugging() ?? false); + try { + return { response: computeStructuralDiff(args, cancellationToken), responseRequired: true }; + } catch (error) { + if (error instanceof ts.OperationCanceledException) { + // The session reports the request as cancelled. + throw error; + } + if (error instanceof Error) { + return { response: { error: ErrorCode.exception, message: error.message, stack: error.stack }, responseRequired: true }; + } + return { response: { error: ErrorCode.exception, message: 'Unknown error' }, responseRequired: true }; + } +}; + const prepareNesRenameHandler = (request: PrepareNesRenameRequest): PrepareNesRenameHandlerResponse => { const input = resolveInput(request.arguments, 50); if (FailedHandlerResponse.is(input)) { @@ -295,6 +325,7 @@ export function create(info: tt.server.PluginCreateInfo): tt.LanguageService { languageServiceHost = info.languageServiceHost; info.session.addProtocolHandler('_.copilot.context', computeContextHandler); info.session.addProtocolHandler('_.copilot.regionContext', regionContextHandler); + info.session.addProtocolHandler('_.copilot.structuralDiff', structuralDiffHandler); info.session.addProtocolHandler('_.copilot.prepareNesRename', prepareNesRenameHandler); info.session.addProtocolHandler('_.copilot.postNesRename', nesRenameHandler); } diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffContribution.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffContribution.ts new file mode 100644 index 000000000000..8e9b1b84819a --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffContribution.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { ILogService } from '../../../platform/log/common/logService'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../util/vs/base/common/lifecycle'; +import { TS6StructuralDiffProvider } from './ts6/structuralDiffProvider'; +import { TS7StructuralDiffProvider } from './ts7/structuralDiffProvider'; +import { TypeScript } from './tsService'; + +export class StructuralDiffContribution extends Disposable { + constructor(@ILogService logService: ILogService) { + super(); + if (typeof vscode.languages.registerStructuralDiffProvider !== 'function') { + return; + } + // Like the TypeScript extension, run TS7 only while a native TypeScript extension is installed and fall back to TS6 otherwise. + const runsVersion7 = () => TypeScript.runsVersion7() && TypeScript.getVersion7Extension() !== undefined; + const registration = this._register(new MutableDisposable()); + let registeredVersion7: boolean | undefined; + const update = () => { + const version7 = runsVersion7(); + if (version7 === registeredVersion7) { + return; + } + registeredVersion7 = version7; + registration.clear(); + const resources = new DisposableStore(); + registration.value = resources; + const provider = resources.add(version7 ? new TS7StructuralDiffProvider(logService) : new TS6StructuralDiffProvider()); + resources.add(vscode.languages.registerStructuralDiffProvider([ + { language: 'typescript', scheme: 'file' }, + { language: 'typescriptreact', scheme: 'file' }, + { language: 'typescript', scheme: 'git' }, + { language: 'typescriptreact', scheme: 'git' }, + ], { + provideStructuralDiff: (original, modified, context, token) => runsVersion7() === version7 + ? provider.provideStructuralDiff(original, modified, context, token) + : undefined, + })); + }; + this._register(vscode.workspace.onDidChangeConfiguration(event => { + if (TypeScript.affectsVersion(event)) { + update(); + } + })); + this._register(vscode.extensions.onDidChange(update)); + update(); + } +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffDocuments.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffDocuments.ts new file mode 100644 index 000000000000..1e091ed512da --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/structuralDiffDocuments.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { isAbsolute } from 'node:path'; +import type * as vscode from 'vscode'; +import { CancellationError } from '../../../util/vs/base/common/errors'; +import { URI } from '../../../util/vs/base/common/uri'; + +/** + * Document handling shared by the TS6 and TS7 structural diff providers. + */ +export namespace StructuralDiffDocuments { + + /** + * Returns the file whose version the modified document shows, or `undefined` if the document is not + * a TypeScript working file or Git snapshot. A Git snapshot is resolved from its metadata rather than + * its possibly decorated path. + */ + export function getBackingFile(document: vscode.TextDocument): vscode.Uri | undefined { + if ((document.uri.scheme !== 'file' && document.uri.scheme !== 'git') + || (document.languageId !== 'typescript' && document.languageId !== 'typescriptreact')) { + return undefined; + } + if (document.uri.scheme === 'file') { + return document.uri; + } + const params: unknown = JSON.parse(document.uri.query); + if (typeof params !== 'object' || params === null + || !('path' in params) || typeof params.path !== 'string' || !isAbsolute(params.path) + || !('ref' in params) || typeof params.ref !== 'string') { + throw new Error('TypeScript structural diff requires a Git URI with an absolute file path and a string ref'); + } + return URI.file(params.path); + } + + /** + * Returns a check that throws a {@link CancellationError} once the request is cancelled or either + * document is closed or edited, because a result would no longer match the documents. + */ + export function createCancellationCheck(originalDocument: vscode.TextDocument, modifiedDocument: vscode.TextDocument, token: vscode.CancellationToken): () => void { + const originalVersion = originalDocument.version; + const modifiedVersion = modifiedDocument.version; + return () => { + if (token.isCancellationRequested || originalDocument.isClosed || modifiedDocument.isClosed + || originalDocument.version !== originalVersion || modifiedDocument.version !== modifiedVersion) { + throw new CancellationError(); + } + }; + } +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffCases.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffCases.ts new file mode 100644 index 000000000000..c864304bca70 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffCases.ts @@ -0,0 +1,723 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; +import path from 'node:path'; +import { test } from 'vitest'; +import * as vscode from 'vscode'; +import { createTextDocumentData } from '../../../../util/common/test/shims/textDocument'; +import { CancellationToken } from '../../../../util/vs/base/common/cancellation'; + +/** + * The TS7 provider opens these files to look up their project. The TS6 provider only uses their names. + */ +export const fixtureDirectory = path.join(__dirname, '../ts7/fixtures/structuralDiff/source'); + +/** A node that lists its children even when it has none, so that tests can read them directly. */ +interface NodeWithChildren extends vscode.StructuralDiffNode { + readonly children: readonly NodeWithChildren[]; +} + +interface StructuralDiffWithChildren extends vscode.StructuralDiff { + readonly root: NodeWithChildren; +} + +export type ComputeStructuralDiff = (originalText: string, modifiedText: string, changes?: readonly vscode.DiffTextChange[], fileUri?: vscode.Uri, languageId?: string, originalUri?: vscode.Uri) => Promise; + +/** + * Returns a function that diffs two texts with the provider and checks the result against the provider + * contract. Without explicit changes, the whole texts form one change. Nodes without children get an + * empty list. + */ +export function createCompute(getProvider: () => vscode.StructuralDiffProvider, defaultUri: vscode.Uri): ComputeStructuralDiff { + return async (originalText, modifiedText, changes, fileUri = defaultUri, languageId = 'typescript', originalUri = fileUri.with({ scheme: 'git' })) => { + const original = createTextDocumentData(originalUri, originalText, languageId).document; + const modified = createTextDocumentData(fileUri, modifiedText, languageId).document; + const context = { changes: changes ?? [{ originalRange: fullRange(original), modifiedRange: fullRange(modified) }] }; + const result = await getProvider().provideStructuralDiff(original, modified, context, CancellationToken.None); + assert.ok(result); + assertContract(result, original, modified, context); + return { ...result, root: withChildren(result.root) }; + }; +} + +/** + * Defines the tests that every TypeScript structural diff provider must pass in the current suite. + */ +export function defineStructuralDiffCases(compute: ComputeStructuralDiff): void { + test('groups a changed method under its unchanged class', async () => { + const original = 'class Calculator {\n\tcalculate(value: number) {\n\t\treturn value + 1;\n\t}\n}'; + const modified = original.replace('value + 1', 'value * 2'); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'value + 1'), + modifiedRange: rangeOf(modified, 'value * 2'), + }]); + assert.deepStrictEqual(summarize(result, original, modified), [{ + path: ['Calculator'], original: 'Calculator', modified: 'Calculator', kind: vscode.SymbolKind.Class, originalChanges: [], modifiedChanges: [], + }, { + path: ['Calculator', 'calculate'], original: 'calculate', modified: 'calculate', kind: vscode.SymbolKind.Method, + originalChanges: [[0, vscode.StructuralDiffClassification.Implementation, 'value + 1', []]], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Implementation, 'value * 2', []]], + }]); + }); + + test('splits a same-line header and body change into non-overlapping character ranges', async () => { + const original = 'function compute(value: number) { return value + 1; }'; + const modified = original.replace('value: number', 'value: string').replace('value + 1', 'value.length'); + const result = await compute(original, modified); + const node = result.root.children[0]; + assert.deepStrictEqual({ + original: node.originalChanges.map(change => change.classification), + modified: node.modifiedChanges.map(change => change.classification), + header: node.modifiedChanges.filter(change => change.classification === vscode.StructuralDiffClassification.Header).map(change => modifiedText(change.range, modified)), + }, { + original: [vscode.StructuralDiffClassification.Header, vscode.StructuralDiffClassification.Other, vscode.StructuralDiffClassification.Implementation, vscode.StructuralDiffClassification.Other], + modified: [vscode.StructuralDiffClassification.Header, vscode.StructuralDiffClassification.Other, vscode.StructuralDiffClassification.Implementation, vscode.StructuralDiffClassification.Other], + header: ['function compute(value: string) '], + }); + }); + + test('reports a whole added class as one declaration instead of duplicating its members', async () => { + const modified = 'export class Added {\n\tvalue = 1;\n\tmethod() { return this.value; }\n}'; + const result = await compute('', modified); + assert.deepStrictEqual(summarize(result, '', modified), [{ + path: ['Added'], original: undefined, modified: 'Added', kind: vscode.SymbolKind.Class, originalChanges: [], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Declaration, modified, []]], + }]); + }); + + test('reports whole deleted declarations against the original snapshot', async () => { + const original = 'function removed() {\n\treturn 1;\n}'; + const result = await compute(original, ''); + assert.deepStrictEqual(summarize(result, original, ''), [{ + path: ['removed'], original: 'removed', modified: undefined, kind: vscode.SymbolKind.Function, + originalChanges: [[0, vscode.StructuralDiffClassification.Declaration, original, []]], modifiedChanges: [], + }]); + }); + + test('matches a name-only rename with its original entity', async () => { + const original = 'function before() { return 1; }'; + const modified = 'function after() { return 1; }'; + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'before'), modifiedRange: rangeOf(modified, 'after'), + }]); + assert.deepStrictEqual(summarize(result, original, modified).map(node => ({ + path: node.path, original: node.original, modified: node.modified, + })), [ + { path: ['after'], original: 'before', modified: 'after' }, + ]); + }); + + for (const [source, before, after] of [ + ['class Example { private before: number = 1; }', 'before', 'after'], + ['class Example { private runNext(): void { schedule(); } }', 'runNext', 'runNext2'], + ['class Example { private runNext2(): void { schedule(); } }', 'runNext2', 'runNext'], + ['class Example { _value = 1; }', '_value', 'value'], + ['class Example { value = 1; }', 'value', '_value'], + ['class Example { calculate() { return 1; } }', 'calculate', 'calcFastulate'], + ['class Example { #before = 1; }', '#before', '#after'], + ['interface Example { before: number; }', 'before', 'after'], + ['const options = { before: 1 };', 'before', 'after'], + ['const before = () => 1;', 'before', 'after'], + ['class Example { before = () => 1; }', 'before', 'after'], + ['const before = 1;', 'before', 'after'], + ] as const) { + test(`matches a declaration-name edit including empty ranges: ${before} -> ${after} in ${source}`, async () => { + const modified = source.replace(before, after); + let prefix = 0; + while (prefix < Math.min(before.length, after.length) && before[prefix] === after[prefix]) { + prefix++; + } + let suffix = 0; + while (suffix < Math.min(before.length, after.length) - prefix + && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) { + suffix++; + } + const originalDocument = createTextDocumentData(vscode.Uri.parse('test:/file.ts'), source, 'typescript').document; + const modifiedDocument = createTextDocumentData(vscode.Uri.parse('test:/file.ts'), modified, 'typescript').document; + const originalName = rangeOf(source, before); + const modifiedName = rangeOf(modified, after); + const originalStart = originalDocument.offsetAt(originalName.start); + const modifiedStart = modifiedDocument.offsetAt(modifiedName.start); + const result = await compute(source, modified, [{ + originalRange: new vscode.Range(originalDocument.positionAt(originalStart + prefix), originalDocument.positionAt(originalStart + before.length - suffix)), + modifiedRange: new vscode.Range(modifiedDocument.positionAt(modifiedStart + prefix), modifiedDocument.positionAt(modifiedStart + after.length - suffix)), + }]); + const allNodes = flatten(result.root); + const renamed = allNodes.filter(node => node.modifiedItem?.name === after); + assert.deepStrictEqual({ + renamed: renamed.map(node => ({ + original: node.originalItem?.name, + modified: node.modifiedItem?.name, + originalSelection: node.originalItem?.selectionRange, + modifiedSelection: node.modifiedItem?.selectionRange, + })), + unmatched: allNodes.filter(node => !node.originalItem || !node.modifiedItem).map(node => (node.modifiedItem ?? node.originalItem)?.name), + }, { + renamed: [{ original: before, modified: after, originalSelection: originalName, modifiedSelection: modifiedName }], + unmatched: [], + }); + }); + } + + test('matches renamed getters and setters independently', async () => { + const original = 'class Example { get before() { return 1; } set before(value: number) { consume(value); } }'; + const modified = original.replaceAll('before', 'after'); + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, 'before'), modifiedRange: rangeOf(modified, 'after') }, + { originalRange: rangeOf(original, 'before', original.indexOf('set')), modifiedRange: rangeOf(modified, 'after', modified.indexOf('set')) }, + ]); + assert.deepStrictEqual(result.root.children[0].children.map(node => [ + node.originalItem?.name, node.modifiedItem?.name, declarationKeyword(node.originalItem, original), declarationKeyword(node.modifiedItem, modified), + ]), [ + ['before', 'after', 'get', 'get'], ['before', 'after', 'set', 'set'], + ]); + }); + + test('reserves exact-name matches before searching for renames', async () => { + const original = 'class Example { before() { return 1; } unchangedName() { return 1; } }'; + const modified = 'class Example { after() { return 1; } unchangedName() { return 2; } }'; + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.children[0].children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [ + ['before', 'after'], ['unchangedName', 'unchangedName'], + ]); + }); + + test('matches rename locations after earlier edits and allows reference changes outside the declaration', async () => { + const original = 'const value = 0;\nclass Example { before() { return 1; } }\nnew Example().before();'; + const modified = `// An earlier insertion\n${original.replaceAll('before', 'after')}`; + const result = await compute(original, modified, [ + { originalRange: new vscode.Range(0, 0, 0, 0), modifiedRange: new vscode.Range(0, 0, 1, 0) }, + { originalRange: rangeOf(original, 'before'), modifiedRange: rangeOf(modified, 'after') }, + { originalRange: rangeOf(original, 'before', original.indexOf('new Example')), modifiedRange: rangeOf(modified, 'after', modified.indexOf('new Example')) }, + ]); + assert.deepStrictEqual(result.root.children[0].children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [['before', 'after']]); + }); + + test('ignores formatting trivia without changing the syntax fingerprint', async () => { + const original = 'class Example { before(value: number) { return value + 1; } }'; + const modified = 'class Example { after ( value : number ) {\n // Comment\n return value + 1;\n} }'; + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'before'), modifiedRange: rangeOf(modified, 'after'), + }]); + assert.deepStrictEqual(result.root.children[0].children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [['before', 'after']]); + }); + + for (const [original, modified] of [ + ['class Example { before() { return 1; } }', 'class Example { after() { return 2; } }'], + ['class Example { before = 1; }', 'class Example { after = 2; }'], + ['class Example { before: number; }', 'class Example { after: string; }'], + ['class Example { before(value: number) {} }', 'class Example { after(value: string) {} }'], + ['class Example { private before() {} }', 'class Example { public after() {} }'], + ['function before() { return before(); }', 'function after() { return after(); }'], + ['function before() { return "before"; }', 'function after() { return "after"; }'], + ['function before() { return\nvalue; }', 'function after() { return value; }'], + ] as const) { + test(`does not infer a rename when syntax outside the name changes: ${original}`, async () => { + const result = await compute(original, modified); + assert.deepStrictEqual(flatten(result.root).filter(node => node.originalItem?.name === 'before' || node.modifiedItem?.name === 'after').map(node => [ + node.originalItem?.name, node.modifiedItem?.name, + ]), [[undefined, 'after'], ['before', undefined]]); + }); + } + + for (const [beforeMembers, afterMembers] of [ + ['before() {} other() {}', 'after() {} another() {}'], + ['before() {}', 'after() {} another() {}'], + ['before() {} other() {}', 'after() {}'], + ] as const) { + test(`does not infer ambiguous one-to-one rename candidates: ${beforeMembers} -> ${afterMembers}`, async () => { + const result = await compute(`class Example { ${beforeMembers} }`, `class Example { ${afterMembers} }`); + assert.strictEqual(result.root.children[0].children.every(node => !node.originalItem || !node.modifiedItem), true); + }); + } + + test('does not infer rename pairs for overloads', async () => { + const original = 'function before(value: string): void;\nfunction before(value: number): void;\nfunction before(value: string | number) {}'; + const modified = original.replaceAll('before', 'after'); + const result = await compute(original, modified); + assert.strictEqual(result.root.children.every(node => !node.originalItem || !node.modifiedItem), true); + }); + + test('requires paired name-location evidence instead of equating independent additions and deletions', async () => { + const original = 'class Example {\n\tbefore() { return 1; }\n\tkeep() { return 2; }\n}'; + const modified = 'class Example {\n\tkeep() { return 2; }\n\tafter() { return 1; }\n}'; + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, '\tbefore() { return 1; }\n'), modifiedRange: new vscode.Range(1, 0, 1, 0) }, + { originalRange: new vscode.Range(3, 0, 3, 0), modifiedRange: rangeOf(modified, '\tafter() { return 1; }\n') }, + ]); + assert.deepStrictEqual(result.root.children[0].children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [ + [undefined, 'after'], ['before', undefined], + ]); + }); + + test('does not search across different matched parent entities', async () => { + const original = 'class First { before() {} }\nclass Second {}'; + const modified = 'class First {}\nclass Second { after() {} }'; + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.children.map(node => ({ + parent: node.modifiedItem?.name, + children: node.children.map(child => [child.originalItem?.name, child.modifiedItem?.name]), + })), [ + { parent: 'First', children: [['before', undefined]] }, + { parent: 'Second', children: [[undefined, 'after']] }, + ]); + }); + + test('does not infer computed-name changes as simple identifier renames', async () => { + const original = 'class Example { [before]() {} }'; + const modified = 'class Example { [after]() {} }'; + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.children[0].children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [ + [undefined, '[after]'], ['[before]', undefined], + ]); + }); + + test('keeps getters and setters with the same name distinct', async () => { + const original = 'class Accessors {\n\tget value() { return 1; }\n\tset value(value: number) { consume(value); }\n}'; + const modified = original.replace('return 1', 'return 2').replace('consume(value)', 'consume(value + 1)'); + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, 'return 1'), modifiedRange: rangeOf(modified, 'return 2') }, + { originalRange: rangeOf(original, 'consume(value)'), modifiedRange: rangeOf(modified, 'consume(value + 1)') }, + ]); + assert.deepStrictEqual(result.root.children[0].children.map(node => [declarationKeyword(node.originalItem, original), declarationKeyword(node.modifiedItem, modified)]), [ + ['get', 'get'], ['set', 'set'], + ]); + }); + + test('does not merge duplicate declarations and overloads by name', async () => { + const original = 'function overloaded(value: string): void;\nfunction overloaded(value: number): void;\nfunction overloaded(value: string | number) {}'; + const modified = original.replace('value: number', 'value: boolean'); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'value: number'), modifiedRange: rangeOf(modified, 'value: boolean'), + }]); + assert.deepStrictEqual(result.root.children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [ + [undefined, 'overloaded'], ['overloaded', undefined], + ]); + }); + + test('retains namespaces and assigned object containers without duplicate callable nodes', async () => { + const original = 'namespace Example {\n\texport const options = {\n\t\tcalculate: (() => { return 1; }) satisfies Function,\n\t};\n}'; + const modified = original.replace('return 1', 'return 2'); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'return 1'), modifiedRange: rangeOf(modified, 'return 2'), + }]); + assert.deepStrictEqual(summarize(result, original, modified).map(node => [node.path, node.kind]), [ + [['Example'], vscode.SymbolKind.Module], + [['Example', 'options'], vscode.SymbolKind.Object], + [['Example', 'options', 'calculate'], vscode.SymbolKind.Function], + ]); + }); + + test('groups imports and re-exports separately without duplicating root coverage', async () => { + const original = 'import { oldName } from "dependency";\nexport { oldName } from "dependency";'; + const modified = original.replaceAll('oldName', 'newName'); + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, 'oldName'), modifiedRange: rangeOf(modified, 'newName') }, + { originalRange: rangeOf(original, 'oldName', original.indexOf('export')), modifiedRange: rangeOf(modified, 'newName', modified.indexOf('export')) }, + ]); + assert.deepStrictEqual({ + nodes: summarize(result, original, modified), + original: result.root.originalChanges, + modified: result.root.modifiedChanges, + }, { + nodes: [{ + path: ['Imports'], original: 'Imports', modified: 'Imports', kind: vscode.SymbolKind.Module, + originalChanges: [[0, vscode.StructuralDiffClassification.Dependency, 'oldName', []]], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Dependency, 'newName', []]], + }, { + path: ['Exports'], original: 'Exports', modified: 'Exports', kind: vscode.SymbolKind.Module, + originalChanges: [[1, vscode.StructuralDiffClassification.Dependency, 'oldName', []]], + modifiedChanges: [[1, vscode.StructuralDiffClassification.Dependency, 'newName', []]], + }], + original: [], modified: [], + }); + }); + + test('keeps added imports and deleted re-exports classified as dependencies', async () => { + const imports = 'import type { Value } from "dependency";'; + const exports = 'export { Value } from "dependency";'; + const added = await compute('', imports); + const deleted = await compute(exports, ''); + assert.deepStrictEqual({ + added: summarize(added, '', imports), + deleted: summarize(deleted, exports, ''), + }, { + added: [{ + path: ['Imports'], original: undefined, modified: 'Imports', kind: vscode.SymbolKind.Module, originalChanges: [], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Dependency, imports, []]], + }], + deleted: [{ + path: ['Exports'], original: 'Exports', modified: undefined, kind: vscode.SymbolKind.Module, modifiedChanges: [], + originalChanges: [[0, vscode.StructuralDiffClassification.Dependency, exports, []]], + }], + }); + }); + + test('groups side-effect and import-equals statements with ordinary imports', async () => { + const original = [ + 'import "old-side-effect";', + 'import Alias = require("old-module");', + 'import type { Value } from "old-types";', + ].join('\n'); + const modified = original.replaceAll('old-', 'new-'); + const changes = ['old-side-effect', 'old-module', 'old-types'].map(value => ({ + originalRange: rangeOf(original, value), modifiedRange: rangeOf(modified, value.replace('old-', 'new-')), + })); + const result = await compute(original, modified, changes); + const group = result.root.children[0]; + assert.deepStrictEqual({ + groups: result.root.children.map(node => node.modifiedItem?.name), + original: group.originalChanges.map(change => [change.textChangeIndex, change.classification, modifiedText(change.range, original)]), + modified: group.modifiedChanges.map(change => [change.textChangeIndex, change.classification, modifiedText(change.range, modified)]), + root: [result.root.originalChanges, result.root.modifiedChanges], + selection: group.modifiedItem?.selectionRange, + }, { + groups: ['Imports'], + original: [ + [0, vscode.StructuralDiffClassification.Dependency, 'old-side-effect'], + [1, vscode.StructuralDiffClassification.Dependency, 'old-module'], + [2, vscode.StructuralDiffClassification.Dependency, 'old-types'], + ], + modified: [ + [0, vscode.StructuralDiffClassification.Dependency, 'new-side-effect'], + [1, vscode.StructuralDiffClassification.Dependency, 'new-module'], + [2, vscode.StructuralDiffClassification.Dependency, 'new-types'], + ], + root: [[], []], + selection: rangeOf(modified, 'import "new-side-effect";'), + }); + }); + + for (const [original, modified, classification] of [ + ['export { oldName };', 'export { newName };', vscode.StructuralDiffClassification.Implementation], + ['export default oldName;', 'export default newName;', vscode.StructuralDiffClassification.Implementation], + ['export = oldName;', 'export = newName;', vscode.StructuralDiffClassification.Implementation], + ['export as namespace OldName;', 'export as namespace NewName;', vscode.StructuralDiffClassification.Implementation], + ['export type { Value } from "old-module";', 'export type { Value } from "new-module";', vscode.StructuralDiffClassification.Dependency], + ['export * from "old-module";', 'export * from "new-module";', vscode.StructuralDiffClassification.Dependency], + ] as const) { + test(`groups standalone export syntax: ${original}`, async () => { + const result = await compute(original, modified); + assert.deepStrictEqual({ + groups: result.root.children.map(node => node.modifiedItem?.name), + classifications: result.root.children[0].modifiedChanges.map(change => change.classification), + root: [result.root.originalChanges, result.root.modifiedChanges], + }, { groups: ['Exports'], classifications: [classification], root: [[], []] }); + }); + } + + test('does not put exported declarations or their export modifier changes in Exports', async () => { + const original = 'class Calculator {}\nfunction calculate() { return 1; }\nconst value = 1;'; + const modified = original.split('\n').map(line => `export ${line}`).join('\n'); + const changes = original.split('\n').map((_, line) => ({ + originalRange: new vscode.Range(line, 0, line, 0), + modifiedRange: new vscode.Range(line, 0, line, 'export '.length), + })); + const result = await compute(original, modified, changes); + assert.deepStrictEqual(result.root.children.map(node => ({ + name: node.modifiedItem?.name, + kind: node.modifiedItem?.kind, + classifications: node.modifiedChanges.map(change => [change.classification, modifiedText(change.range, modified)]), + })), [ + { name: 'Calculator', kind: vscode.SymbolKind.Class, classifications: [[vscode.StructuralDiffClassification.Header, 'export ']] }, + { name: 'calculate', kind: vscode.SymbolKind.Function, classifications: [[vscode.StructuralDiffClassification.Header, 'export ']] }, + { name: 'value', kind: vscode.SymbolKind.Variable, classifications: [[vscode.StructuralDiffClassification.Header, 'export ']] }, + ]); + }); + + for (const original of [ + 'export default class Calculator { value = 1; }', + 'export default function calculate() { return 1; }', + ]) { + test(`keeps default exported declarations in their normal structural location: ${original}`, async () => { + const modified = original.replace('1', '2'); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, '1'), modifiedRange: rangeOf(modified, '2'), + }]); + const name = original.includes('class') ? 'Calculator' : 'calculate'; + assert.deepStrictEqual(result.root.children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [[name, name]]); + }); + } + + test('does not let discontiguous import/export groups swallow intervening declarations', async () => { + const original = [ + 'import { first } from "one";', + 'export function between() { return 1; }', + 'import { second } from "two";', + 'export { first };', + 'export class Between { value = 1; }', + 'export { second } from "two";', + ].join('\n'); + const modified = original.replaceAll('first', 'firstChanged').replaceAll('second', 'secondChanged').replaceAll('1', '2'); + const result = await compute(original, modified); + assert.deepStrictEqual({ + names: result.root.children.map(node => node.modifiedItem?.name), + imports: result.root.children[0].modifiedChanges.map(change => modifiedText(change.range, modified)), + exports: result.root.children[2].modifiedChanges.map(change => modifiedText(change.range, modified)), + functionCoverage: result.root.children[1].modifiedChanges.map(change => modifiedText(change.range, modified)).join(''), + rootCoverage: result.root.modifiedChanges.map(change => modifiedText(change.range, modified)).join(''), + }, { + names: ['Imports', 'between', 'Exports', 'Between'], + imports: ['import { firstChanged } from "one";', 'import { secondChanged } from "two";'], + exports: ['export { firstChanged };', 'export { secondChanged } from "two";'], + functionCoverage: 'export function between() { return 2; }', + rootCoverage: '\n\n\n\n\n', + }); + }); + + test('groups declarations within an export statement under Exports', async () => { + const original = [ + 'export { value };', + 'function between() { return 1; }', + 'export default { calculate() { return 1; } };', + ].join('\n'); + const modified = original.replaceAll('return 1', 'return 2'); + const result = await compute(original, modified); + assert.deepStrictEqual(summarize(result, original, modified).map(node => node.path), [ + ['Exports'], ['Exports', 'calculate'], ['between'], + ]); + }); + + test('omits unchanged import/export groups when only a declaration body changes', async () => { + const original = 'import { Value } from "dependency";\nexport function calculate() { return 1; }\nexport { Value };'; + const modified = original.replace('return 1', 'return 2'); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'return 1'), modifiedRange: rangeOf(modified, 'return 2'), + }]); + assert.deepStrictEqual(result.root.children.map(node => [node.originalItem?.name, node.modifiedItem?.name]), [['calculate', 'calculate']]); + }); + + test('keeps import/export groups within their enclosing namespace', async () => { + const original = 'namespace Container {\n\timport Alias = Library.Old;\n\texport { Alias };\n}'; + const modified = original.replace('Library.Old', 'Library.New').replace('export { Alias }', 'export { Alias as Public }'); + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, 'Library.Old'), modifiedRange: rangeOf(modified, 'Library.New') }, + { originalRange: rangeOf(original, 'export { Alias }'), modifiedRange: rangeOf(modified, 'export { Alias as Public }') }, + ]); + assert.deepStrictEqual(summarize(result, original, modified).map(node => [node.path, node.kind]), [ + [['Container'], vscode.SymbolKind.Module], + [['Container', 'Imports'], vscode.SymbolKind.Module], + [['Container', 'Exports'], vscode.SymbolKind.Module], + ]); + }); + + test('does not match import/export groups with declarations having the same display names', async () => { + const original = 'namespace Imports { export const value = 1; }\nimport { oldName } from "dependency";\nnamespace Exports { export const value = 1; }\nexport { oldName };'; + const modified = original.replaceAll('1', '2').replaceAll('oldName', 'newName'); + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.children.map(node => [ + node.originalItem?.name, node.modifiedItem?.name, declarationKeyword(node.originalItem, original), declarationKeyword(node.modifiedItem, modified), + ]), [ + ['Imports', 'Imports', 'namespace', 'namespace'], + ['Imports', 'Imports', 'import', 'import'], + ['Exports', 'Exports', 'namespace', 'namespace'], + ['Exports', 'Exports', 'export', 'export'], + ]); + }); + + test('tags test callbacks without tagging unrelated code in the same change', async () => { + const original = 'const setup = 1;\ntest("works", () => { expect(setup).toBe(1); });'; + const modified = original.replaceAll('1', '2'); + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.modifiedChanges.map(change => [modifiedText(change.range, modified), change.tags]), [ + ['\n', []], + ['test("works", ', []], + ['() => { expect(setup).toBe(2); }', [vscode.StructuralDiffTag.Test]], + [');', []], + ]); + }); + + test('tags named test functions and test files', async () => { + const original = 'function testValue() { return 1; }'; + const modified = original.replace('1', '2'); + const result = await compute(original, modified, [{ originalRange: rangeOf(original, '1'), modifiedRange: rangeOf(modified, '2') }]); + assert.deepStrictEqual(result.root.children[0].modifiedChanges.map(change => change.tags), [[vscode.StructuralDiffTag.Test]]); + const testUri = vscode.Uri.file(path.join(fixtureDirectory, 'example.spec.ts')); + const fileResult = await compute('const value = 1;', 'const value = 2;', undefined, testUri); + assert.deepStrictEqual(fileResult.root.children[0].modifiedChanges.map(change => [change.classification, change.tags]), [ + [vscode.StructuralDiffClassification.Header, [vscode.StructuralDiffTag.Test]], + [vscode.StructuralDiffClassification.Implementation, [vscode.StructuralDiffTag.Test]], + [vscode.StructuralDiffClassification.Other, [vscode.StructuralDiffTag.Test]], + ]); + }); + + test('supports TypeScript React snapshots and JSX expression bodies', async () => { + const original = 'export const Component = () =>
old text
;'; + const modified = original.replace('old text', 'new text'); + const tsxUri = vscode.Uri.file(path.join(fixtureDirectory, 'component.tsx')); + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, 'old text'), modifiedRange: rangeOf(modified, 'new text'), + }], tsxUri, 'typescriptreact'); + assert.deepStrictEqual(summarize(result, original, modified), [{ + path: ['Component'], original: 'Component', modified: 'Component', kind: vscode.SymbolKind.Function, + originalChanges: [[0, vscode.StructuralDiffClassification.Implementation, 'old text', []]], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Implementation, 'new text', []]], + }]); + }); + + test('handles interface signatures, type aliases, enums, class fields and static blocks', async () => { + const original = [ + 'interface Callable { (value: number): number; new (): Callable; [key: string]: number; }', + 'type Alias = number;', + 'enum Choice { Value = 1 }', + 'class Fields { field = ((value: number) => value + 1) satisfies Function; static { const initial = 1; } }', + ].join('\n'); + const modified = original.replaceAll('number', 'string').replaceAll('1', '2'); + const result = await compute(original, modified); + assert.deepStrictEqual(summarize(result, original, modified).map(node => [node.path, node.kind]), [ + [['Callable'], vscode.SymbolKind.Interface], + [['Callable', '(call)'], vscode.SymbolKind.Method], + [['Callable', '(new)'], vscode.SymbolKind.Constructor], + [['Callable', '[index]'], vscode.SymbolKind.Method], + [['Alias'], vscode.SymbolKind.Variable], + [['Choice'], vscode.SymbolKind.Enum], + [['Choice', 'Value'], vscode.SymbolKind.EnumMember], + [['Fields'], vscode.SymbolKind.Class], + [['Fields', 'field'], vscode.SymbolKind.Function], + [['Fields', 'static'], vscode.SymbolKind.Method], + [['Fields', 'static', 'initial'], vscode.SymbolKind.Variable], + ]); + }); + + test('keeps unchanged entities out of the result', async () => { + const text = 'class Unchanged { method() { return 1; } }'; + const result = await compute(text, text, []); + assert.deepStrictEqual({ children: result.root.children, original: result.root.originalChanges, modified: result.root.modifiedChanges }, { children: [], original: [], modified: [] }); + }); + + test('handles UTF-16 offsets, CRLF and changes spanning multiple entities', async () => { + const original = 'const emoji = "😀";\r\nfunction first() { return 1; }\r\nfunction second() { return 2; }\r\n'; + const modified = original.replace('😀', '🙂').replace('return 1', 'return 3').replace('return 2', 'return 4'); + const result = await compute(original, modified, [ + { originalRange: rangeOf(original, '😀'), modifiedRange: rangeOf(modified, '🙂') }, + { originalRange: rangeOf(original, 'return 1; }\r\nfunction second() { return 2'), modifiedRange: rangeOf(modified, 'return 3; }\r\nfunction second() { return 4') }, + ]); + assert.deepStrictEqual(result.root.children.map(node => node.modifiedItem?.name), ['emoji', 'first', 'second']); + }); + + test('classifies file-level comments as other syntax', async () => { + const original = '// old comment\n'; + const modified = '// new comment\n'; + const result = await compute(original, modified); + assert.deepStrictEqual(result.root.modifiedChanges.map(change => [change.classification, modifiedText(change.range, modified)]), [[vscode.StructuralDiffClassification.Other, modified]]); + }); +} + +function fullRange(document: vscode.TextDocument): vscode.Range { + return new vscode.Range(new vscode.Position(0, 0), document.positionAt(document.getText().length)); +} + +function flatten(node: NodeWithChildren): NodeWithChildren[] { + return [node, ...node.children.flatMap(flatten)]; +} + +function withChildren(node: vscode.StructuralDiffNode): NodeWithChildren { + return { ...node, children: (node.children ?? []).map(withChildren) }; +} + +export function rangeOf(text: string, part: string, from = 0): vscode.Range { + const offset = text.indexOf(part, from); + assert.ok(offset >= 0, `Cannot find ${JSON.stringify(part)}`); + const document = createTextDocumentData(vscode.Uri.parse('test:/file.ts'), text, 'typescript').document; + return new vscode.Range(document.positionAt(offset), document.positionAt(offset + part.length)); +} + +function modifiedText(range: vscode.Range, text: string): string { + return createTextDocumentData(vscode.Uri.parse('test:/file.ts'), text, 'typescript').document.getText(range); +} + +/** + * The first word of the text of an entity, such as `get` or `namespace`, which tells what declares the entity. + */ +function declarationKeyword(entity: vscode.StructuralDiffItem | undefined, text: string): string | undefined { + return entity && modifiedText(entity.range, text).split(' ')[0]; +} + +export function summarize(diff: StructuralDiffWithChildren, original: string, modified: string) { + const result: { + path: string[]; + original: string | undefined; + modified: string | undefined; + kind: vscode.SymbolKind | undefined; + originalChanges: [number, vscode.StructuralDiffClassification, string, readonly vscode.StructuralDiffTag[] | undefined][]; + modifiedChanges: [number, vscode.StructuralDiffClassification, string, readonly vscode.StructuralDiffTag[] | undefined][]; + }[] = []; + const visit = (node: NodeWithChildren, parent: string[]) => { + const path = [...parent, (node.modifiedItem ?? node.originalItem)!.name]; + result.push({ + path, + original: node.originalItem?.name, + modified: node.modifiedItem?.name, + kind: (node.modifiedItem ?? node.originalItem)?.kind, + originalChanges: node.originalChanges.map(change => [change.textChangeIndex, change.classification, modifiedText(change.range, original), change.tags]), + modifiedChanges: node.modifiedChanges.map(change => [change.textChangeIndex, change.classification, modifiedText(change.range, modified), change.tags]), + }); + node.children.forEach(child => visit(child, path)); + }; + diff.root.children.forEach(node => visit(node, [])); + return result; +} + +function assertContract(diff: vscode.StructuralDiff, original: vscode.TextDocument, modified: vscode.TextDocument, context: vscode.StructuralDiffContext): void { + const ids = new Set(); + const errors: string[] = []; + const coverage: Record<'original' | 'modified', vscode.StructuralDiffCoverage[]> = { original: [], modified: [] }; + const getItem = (node: vscode.StructuralDiffNode, side: 'original' | 'modified') => side === 'original' ? node.originalItem : node.modifiedItem; + const visit = (node: vscode.StructuralDiffNode, parent?: vscode.StructuralDiffNode) => { + if (ids.has(node.id) || (!node.originalItem && !node.modifiedItem)) { + errors.push(`Invalid entity ${node.id}`); + } + ids.add(node.id); + for (const side of ['original', 'modified'] as const) { + const entity = getItem(node, side); + const changes = side === 'original' ? node.originalChanges : node.modifiedChanges; + if (entity === undefined && changes.length > 0) { + errors.push(`Missing ${side} entity ${node.id}`); + } + if (entity !== undefined && parent !== undefined && !getItem(parent, side)?.range.contains(entity.range)) { + errors.push(`Invalid ${side} parent ${node.id}`); + } + if (entity?.selectionRange !== undefined && !entity.range.contains(entity.selectionRange)) { + errors.push(`Invalid ${side} selection ${node.id}`); + } + for (const change of changes) { + const range = context.changes[change.textChangeIndex]?.[side === 'original' ? 'originalRange' : 'modifiedRange']; + if (range === undefined || !range.contains(change.range) || change.range.isEmpty || !entity?.range.contains(change.range)) { + errors.push(`Invalid ${side} coverage ${node.id}`); + } + } + coverage[side].push(...changes); + } + node.children?.forEach(child => visit(child, node)); + }; + visit(diff.root); + for (const [index, change] of context.changes.entries()) { + for (const side of ['original', 'modified'] as const) { + const document = side === 'original' ? original : modified; + const range = side === 'original' ? change.originalRange : change.modifiedRange; + let cursor = document.offsetAt(range.start); + const pieces = coverage[side].filter(value => value.textChangeIndex === index) + .sort((left, right) => left.range.start.compareTo(right.range.start)); + for (const piece of pieces) { + if (document.offsetAt(piece.range.start) !== cursor) { + errors.push(`Gap or overlap in ${side} change ${index}`); + } + cursor = document.offsetAt(piece.range.end); + } + if (cursor !== document.offsetAt(range.end)) { + errors.push(`Incomplete ${side} change ${index}`); + } + } + } + assert.deepStrictEqual({ + errors, isIncomplete: diff.isIncomplete, + rootOriginal: diff.root.originalItem?.range, rootModified: diff.root.modifiedItem?.range, + kinds: [diff.root.originalItem?.kind, diff.root.modifiedItem?.kind], + }, { + errors: [], isIncomplete: false, rootOriginal: fullRange(original), rootModified: fullRange(modified), + kinds: [vscode.SymbolKind.File, vscode.SymbolKind.File], + }); +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffContribution.spec.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffContribution.spec.ts new file mode 100644 index 000000000000..51501a3ddfc4 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/structuralDiffContribution.spec.ts @@ -0,0 +1,184 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; +import { afterAll, afterEach, beforeEach, suite, test, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { TestLogService } from '../../../../platform/testing/common/testLogService'; +import { createTextDocumentData } from '../../../../util/common/test/shims/textDocument'; +import { CancellationToken } from '../../../../util/vs/base/common/cancellation'; +import { DisposableStore } from '../../../../util/vs/base/common/lifecycle'; +import { StructuralDiffContribution } from '../structuralDiffContribution'; + +const mocks = vi.hoisted(() => { + const listeners: ((event: vscode.ConfigurationChangeEvent) => void)[] = []; + return { + available: true, + useTs7: true, + hasNativeExtension: true, + listeners, + extensionListeners: [] as (() => void)[], + events: [] as string[], + onConfigurationChange: vi.fn<(listener: (event: vscode.ConfigurationChangeEvent) => void) => vscode.Disposable>(), + onExtensionsChange: vi.fn<(listener: () => void) => vscode.Disposable>(), + register: vi.fn<(selector: vscode.DocumentSelector, provider: vscode.StructuralDiffProvider) => vscode.Disposable>(), + provide: { + TS6: vi.fn(), + TS7: vi.fn(), + }, + }; +}); + +vi.mock('vscode', async importOriginal => { + const original = await importOriginal(); + return { + ...original, + languages: { + get registerStructuralDiffProvider() { return mocks.available ? mocks.register : undefined; }, + }, + workspace: { + onDidChangeConfiguration: mocks.onConfigurationChange, + getConfiguration: () => ({ + inspect: () => ({ key: 'experimental.useTsgo', globalValue: mocks.useTs7 }), + get: () => mocks.useTs7, + }), + }, + extensions: { + getExtension: (extensionId: string) => mocks.hasNativeExtension && extensionId === 'typescriptteam.vscode-typescript' ? { id: extensionId } : undefined, + onDidChange: mocks.onExtensionsChange, + }, + }; +}); + +vi.mock('../ts6/structuralDiffProvider', () => ({ + TS6StructuralDiffProvider: class { + readonly provideStructuralDiff = mocks.provide.TS6; + constructor() { mocks.events.push('create TS6'); } + dispose() { mocks.events.push('dispose TS6'); } + }, +})); + +vi.mock('../ts7/structuralDiffProvider', () => ({ + TS7StructuralDiffProvider: class { + readonly provideStructuralDiff = mocks.provide.TS7; + constructor() { mocks.events.push('create TS7'); } + dispose() { mocks.events.push('dispose TS7'); } + }, +})); + +suite('TypeScript structural diff contribution', () => { + const store = new DisposableStore(); + + beforeEach(() => { + vi.resetAllMocks(); + mocks.available = true; + mocks.useTs7 = true; + mocks.hasNativeExtension = true; + mocks.listeners.length = 0; + mocks.extensionListeners.length = 0; + mocks.events.length = 0; + mocks.onConfigurationChange.mockImplementation(listener => { + mocks.listeners.push(listener); + return { dispose: () => { mocks.listeners.splice(mocks.listeners.indexOf(listener), 1); } }; + }); + mocks.onExtensionsChange.mockImplementation(listener => { + mocks.extensionListeners.push(listener); + return { dispose: () => { mocks.extensionListeners.splice(mocks.extensionListeners.indexOf(listener), 1); } }; + }); + mocks.register.mockImplementation(() => { + mocks.events.push('register'); + return { dispose: () => mocks.events.push('unregister') }; + }); + }); + + afterEach(() => store.clear()); + afterAll(() => store.dispose()); + + test('registers TypeScript and TSX providers for working files and Git snapshots and disposes their resources', () => { + const contribution = store.add(new StructuralDiffContribution(new TestLogService())); + const selectors = mocks.register.mock.calls.map(([selector]) => selector); + contribution.dispose(); + assert.deepStrictEqual({ selectors, events: mocks.events }, { + selectors: [[ + { language: 'typescript', scheme: 'file' }, + { language: 'typescriptreact', scheme: 'file' }, + { language: 'typescript', scheme: 'git' }, + { language: 'typescriptreact', scheme: 'git' }, + ]], + events: ['create TS7', 'register', 'dispose TS7', 'unregister'], + }); + }); + + for (const version of ['TS6', 'TS7'] as const) { + test(`delegates requests to the ${version} provider only while ${version} is active`, async () => { + mocks.useTs7 = version === 'TS7'; + store.add(new StructuralDiffContribution(new TestLogService())); + const provider = mocks.register.mock.calls[0][1]; + const original = createTextDocumentData(vscode.Uri.parse('git:/file.ts'), '', 'typescript').document; + const modified = createTextDocumentData(vscode.Uri.file('file.ts'), '', 'typescript').document; + const context = { changes: [] }; + const range = new vscode.Range(0, 0, 0, 0); + const entity = { name: 'file.ts', kind: vscode.SymbolKind.File, range }; + const expected: vscode.StructuralDiff = { + root: { id: 'file', originalItem: entity, modifiedItem: entity, originalChanges: [], modifiedChanges: [], children: [] }, + isIncomplete: false, + }; + mocks.provide[version].mockReturnValue(expected); + const active = await provider.provideStructuralDiff(original, modified, context, CancellationToken.None); + // The version changed, but the configuration listener has not yet replaced the registration. + mocks.useTs7 = !mocks.useTs7; + const inactive = await provider.provideStructuralDiff(original, modified, context, CancellationToken.None); + assert.deepStrictEqual({ + active, inactive, TS6: mocks.provide.TS6.mock.calls, TS7: mocks.provide.TS7.mock.calls, + }, { + active: expected, inactive: undefined, + TS6: version === 'TS6' ? [[original, modified, context, CancellationToken.None]] : [], + TS7: version === 'TS7' ? [[original, modified, context, CancellationToken.None]] : [], + }); + }); + } + + test('does not construct a provider when the host does not support the proposal', () => { + mocks.available = false; + store.add(new StructuralDiffContribution(new TestLogService())); + assert.deepStrictEqual(mocks.events, []); + }); + + test('replaces the provider when the active TypeScript version changes', () => { + mocks.useTs7 = false; + store.add(new StructuralDiffContribution(new TestLogService())); + mocks.useTs7 = true; + mocks.listeners[0]({ affectsConfiguration: () => true }); + mocks.useTs7 = false; + mocks.listeners[0]({ affectsConfiguration: () => true }); + assert.deepStrictEqual(mocks.events, [ + 'create TS6', 'register', + 'dispose TS6', 'unregister', 'create TS7', 'register', + 'dispose TS7', 'unregister', 'create TS6', 'register', + ]); + }); + + test('registers the TS6 provider while TS7 is enabled but no native TypeScript extension is installed', () => { + mocks.hasNativeExtension = false; + store.add(new StructuralDiffContribution(new TestLogService())); + assert.deepStrictEqual(mocks.events, ['create TS6', 'register']); + }); + + test('replaces the provider when a native TypeScript extension is installed or removed', () => { + mocks.hasNativeExtension = false; + store.add(new StructuralDiffContribution(new TestLogService())); + mocks.hasNativeExtension = true; + mocks.extensionListeners[0](); + // Changes of other extensions keep the provider. + mocks.extensionListeners[0](); + mocks.hasNativeExtension = false; + mocks.extensionListeners[0](); + assert.deepStrictEqual(mocks.events, [ + 'create TS6', 'register', + 'dispose TS6', 'unregister', 'create TS7', 'register', + 'dispose TS7', 'unregister', 'create TS6', 'register', + ]); + }); +}); diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/test/tsService.spec.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/tsService.spec.ts index d9f92d58a32f..0a8f5ec1a812 100644 --- a/extensions/copilot/src/extension/typescriptContext/vscode-node/test/tsService.spec.ts +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/test/tsService.spec.ts @@ -13,11 +13,13 @@ vi.mock('vscode', () => ({})); import { TypeScript } from '../tsService'; suite('TypeScript service', () => { - test('prefers the current TS7 extension and falls back to the legacy extension', () => { + test('prefers the current TS7 extension and falls back to the nightly and the legacy extension', () => { const currentExtensionId = 'typescriptteam.vscode-typescript'; + const nightlyExtensionId = 'typescriptteam.vscode-typescript-nightly'; const legacyExtensionId = 'typescriptteam.native-preview'; const scenarios = [ [currentExtensionId, legacyExtensionId], + [nightlyExtensionId, legacyExtensionId], [legacyExtensionId], [], ]; @@ -37,8 +39,9 @@ suite('TypeScript service', () => { assert.deepStrictEqual(actual, [ { selected: currentExtensionId, lookups: [currentExtensionId] }, - { selected: legacyExtensionId, lookups: [currentExtensionId, legacyExtensionId] }, - { selected: undefined, lookups: [currentExtensionId, legacyExtensionId] }, + { selected: nightlyExtensionId, lookups: [currentExtensionId, nightlyExtensionId] }, + { selected: legacyExtensionId, lookups: [currentExtensionId, nightlyExtensionId, legacyExtensionId] }, + { selected: undefined, lookups: [currentExtensionId, nightlyExtensionId, legacyExtensionId] }, ]); }); }); diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/structuralDiffProvider.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/structuralDiffProvider.ts new file mode 100644 index 000000000000..5b0d35dc4040 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/structuralDiffProvider.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 * as vscode from 'vscode'; +import { CancellationError } from '../../../../util/vs/base/common/errors'; +import * as protocol from '../../common/serverProtocol'; +import { StructuralDiffDocuments } from '../structuralDiffDocuments'; + +enum ExecutionTarget { + Semantic, + Syntax +} + +type ExecConfig = { + readonly lowPriority?: boolean; + readonly executionTarget?: ExecutionTarget; +}; + +type StructuralDiffRequest = (args: protocol.StructuralDiffRequestArgs, token: vscode.CancellationToken) => Thenable; + +/** + * Computes structural diffs in the TypeScript server plugin, which parses the supplied document contents + * in isolation, so neither the project nor the backing file changes. + */ +export class TS6StructuralDiffProvider implements vscode.StructuralDiffProvider, vscode.Disposable { + // Structural diffs are computed in the background, so interactive requests such as completions go first. + private static readonly ExecConfig: ExecConfig = { executionTarget: ExecutionTarget.Semantic, lowPriority: true }; + + constructor( + private readonly sendRequest: StructuralDiffRequest = (args, token) => vscode.commands.executeCommand('typescript.tsserverRequest', '_.copilot.structuralDiff', args, TS6StructuralDiffProvider.ExecConfig, token), + private readonly openDocument: (uri: vscode.Uri) => Thenable = uri => vscode.workspace.openTextDocument(uri), + ) { } + + async provideStructuralDiff(originalDocument: vscode.TextDocument, modifiedDocument: vscode.TextDocument, context: vscode.StructuralDiffContext, token: vscode.CancellationToken): Promise { + const fileUri = StructuralDiffDocuments.getBackingFile(modifiedDocument); + if (fileUri === undefined) { + return undefined; + } + const checkCancellation = StructuralDiffDocuments.createCancellationCheck(originalDocument, modifiedDocument, token); + checkCancellation(); + const toOffsets = (document: vscode.TextDocument, range: vscode.Range): protocol.OffsetRange => ({ start: document.offsetAt(range.start), end: document.offsetAt(range.end) }); + const response = await this.request({ + fileName: fileUri.fsPath, + originalText: originalDocument.getText(), + modifiedText: modifiedDocument.getText(), + changes: context.changes.map(change => ({ + original: toOffsets(originalDocument, change.originalRange), + modified: toOffsets(modifiedDocument, change.modifiedRange), + })), + }, fileUri, checkCancellation, token); + checkCancellation(); + if (protocol.StructuralDiffResponse.isCancelled(response)) { + throw new CancellationError(); + } + if (protocol.StructuralDiffResponse.isError(response)) { + throw new Error(`TypeScript structural diff failed: ${response.body.message}`); + } + return protocol.StructuralDiffResponse.isOk(response) ? toStructuralDiff(response.body, originalDocument, modifiedDocument) : undefined; + } + + /** + * tsserver loads the plugin, and with it the request handler, only when it creates a project for an open file, and + * it does not open Git snapshots. So a staged diff can be requested before the handler exists. When a request fails, + * the backing file is opened to create its project and the request is sent once more. It still analyzes only the + * supplied texts. + */ + private async request(args: protocol.StructuralDiffRequestArgs, fileUri: vscode.Uri, checkCancellation: () => void, token: vscode.CancellationToken): Promise { + try { + return await this.sendRequest(args, token); + } catch (error) { + checkCancellation(); + try { + await this.openDocument(fileUri); + } catch { + throw error; + } + checkCancellation(); + return this.sendRequest(args, token); + } + } + + dispose(): void { + // No resources to dispose for the TS6 implementation + } +} + +function toStructuralDiff(result: protocol.StructuralDiffResult, originalDocument: vscode.TextDocument, modifiedDocument: vscode.TextDocument): vscode.StructuralDiff { + const toRange = (document: vscode.TextDocument, range: protocol.OffsetRange) => new vscode.Range(document.positionAt(range.start), document.positionAt(range.end)); + const toEntity = (document: vscode.TextDocument, entity: protocol.StructuralDiffItem | undefined): vscode.StructuralDiffItem | undefined => entity && { + name: getName(entity), + kind: toSymbolKind(entity.kind), + range: toRange(document, entity.range), + selectionRange: entity.selectionRange && toRange(document, entity.selectionRange), + }; + const toCoverage = (document: vscode.TextDocument, coverage: protocol.StructuralDiffCoverage): vscode.StructuralDiffCoverage => ({ + textChangeIndex: coverage.textChangeIndex, + range: toRange(document, coverage.range), + classification: toClassification(coverage.classification), + tags: coverage.tags.map(toTag), + }); + const toNode = (node: protocol.StructuralDiffNode): vscode.StructuralDiffNode => ({ + id: node.id, + originalItem: toEntity(originalDocument, node.original), + modifiedItem: toEntity(modifiedDocument, node.modified), + originalChanges: node.originalChanges.map(coverage => toCoverage(originalDocument, coverage)), + modifiedChanges: node.modifiedChanges.map(coverage => toCoverage(modifiedDocument, coverage)), + children: node.children.map(toNode), + }); + return { root: toNode(result.root), isIncomplete: result.isIncomplete }; +} + +function getName(entity: protocol.StructuralDiffItem): string { + switch (entity.languageKind) { + case 'imports': + return vscode.l10n.t('Imports'); + case 'exports': + return vscode.l10n.t('Exports'); + default: + return entity.name; + } +} + +function toSymbolKind(kind: protocol.StructuralDiffSymbolKind): vscode.SymbolKind { + switch (kind) { + case protocol.StructuralDiffSymbolKind.File: + return vscode.SymbolKind.File; + case protocol.StructuralDiffSymbolKind.Module: + return vscode.SymbolKind.Module; + case protocol.StructuralDiffSymbolKind.Class: + return vscode.SymbolKind.Class; + case protocol.StructuralDiffSymbolKind.Method: + return vscode.SymbolKind.Method; + case protocol.StructuralDiffSymbolKind.Property: + return vscode.SymbolKind.Property; + case protocol.StructuralDiffSymbolKind.Constructor: + return vscode.SymbolKind.Constructor; + case protocol.StructuralDiffSymbolKind.Enum: + return vscode.SymbolKind.Enum; + case protocol.StructuralDiffSymbolKind.Interface: + return vscode.SymbolKind.Interface; + case protocol.StructuralDiffSymbolKind.Function: + return vscode.SymbolKind.Function; + case protocol.StructuralDiffSymbolKind.Variable: + return vscode.SymbolKind.Variable; + case protocol.StructuralDiffSymbolKind.Object: + return vscode.SymbolKind.Object; + case protocol.StructuralDiffSymbolKind.Array: + return vscode.SymbolKind.Array; + case protocol.StructuralDiffSymbolKind.EnumMember: + return vscode.SymbolKind.EnumMember; + } +} + +function toClassification(classification: protocol.StructuralDiffClassification): vscode.StructuralDiffClassification { + switch (classification) { + case protocol.StructuralDiffClassification.Declaration: + return vscode.StructuralDiffClassification.Declaration; + case protocol.StructuralDiffClassification.Header: + return vscode.StructuralDiffClassification.Header; + case protocol.StructuralDiffClassification.Implementation: + return vscode.StructuralDiffClassification.Implementation; + case protocol.StructuralDiffClassification.Dependency: + return vscode.StructuralDiffClassification.Dependency; + case protocol.StructuralDiffClassification.Other: + return vscode.StructuralDiffClassification.Other; + } +} + +function toTag(tag: protocol.StructuralDiffTag): vscode.StructuralDiffTag { + switch (tag) { + case protocol.StructuralDiffTag.Test: + return vscode.StructuralDiffTag.Test; + } +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/test/structuralDiff.spec.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/test/structuralDiff.spec.ts new file mode 100644 index 000000000000..b1a9d53e8ced --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts6/test/structuralDiff.spec.ts @@ -0,0 +1,134 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; +import path from 'node:path'; +import ts from 'typescript'; +import { beforeAll, suite, test } from 'vitest'; +import * as vscode from 'vscode'; +import { toGitUri } from '../../../../../platform/git/common/utils'; +import { createTextDocumentData, setDocText } from '../../../../../util/common/test/shims/textDocument'; +import { CancellationToken } from '../../../../../util/vs/base/common/cancellation'; +import { isCancellationError } from '../../../../../util/vs/base/common/errors'; +import * as protocol from '../../../common/serverProtocol'; +import type * as structuralDiff from '../../../serverPlugin/src/common/structuralDiff'; +import { createCompute, defineStructuralDiffCases, fixtureDirectory, rangeOf } from '../../test/structuralDiffCases'; +import { TS6StructuralDiffProvider } from '../structuralDiffProvider'; + +suite('TypeScript 6 structural diff', () => { + const uri = vscode.Uri.file(path.join(fixtureDirectory, 'example.ts')); + let computeStructuralDiff: typeof structuralDiff.computeStructuralDiff; + + beforeAll(async () => { + (await import('../../../serverPlugin/src/common/typescript')).default.install(ts); + computeStructuralDiff = (await import('../../../serverPlugin/src/common/structuralDiff')).computeStructuralDiff; + }); + + /** + * Runs the request in the server plugin, including the JSON serialization between the client and the TypeScript server. + */ + async function serve(args: protocol.StructuralDiffRequestArgs): Promise { + const body = computeStructuralDiff(JSON.parse(JSON.stringify(args)), { isCancellationRequested: () => false, throwIfCancellationRequested: () => { } }); + return JSON.parse(JSON.stringify({ seq: 0, type: 'response', command: '_.copilot.structuralDiff', request_seq: 0, success: true, body })); + } + + const provider = new TS6StructuralDiffProvider(serve); + defineStructuralDiffCases(createCompute(() => provider, uri)); + + test('sends the backing file of a Git snapshot, both texts and the change offsets', async () => { + const requests: protocol.StructuralDiffRequestArgs[] = []; + const provider = new TS6StructuralDiffProvider(async args => { + requests.push(args); + return undefined; + }); + const original = 'const before = 1;\n'; + const modified = 'const after = 1;\n'; + const result = await provider.provideStructuralDiff( + createTextDocumentData(toGitUri(uri, 'HEAD'), original, 'typescript').document, + createTextDocumentData(toGitUri(uri, '', { replaceFileExtension: true }), modified, 'typescript').document, + { changes: [{ originalRange: rangeOf(original, 'before'), modifiedRange: rangeOf(modified, 'after') }] }, + CancellationToken.None); + assert.deepStrictEqual({ result, requests }, { + result: undefined, + requests: [{ + fileName: uri.fsPath, + originalText: original, + modifiedText: modified, + changes: [{ original: { start: 6, end: 12 }, modified: { start: 6, end: 11 } }], + }], + }); + }); + + for (const [name, response, error] of [ + ['a plugin failure', { seq: 0, type: 'response', command: '_.copilot.structuralDiff', request_seq: 0, success: true, body: { error: protocol.ErrorCode.exception, message: 'Plugin failed' } }, /Plugin failed/], + ['a cancelled request', { type: 'cancelled' }, isCancellationError], + ] as const) { + test(`rejects ${name}`, async () => { + const provider = new TS6StructuralDiffProvider(async () => response); + const document = createTextDocumentData(uri, 'const value = 1;', 'typescript').document; + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, CancellationToken.None), error); + }); + } + + test('opens the backing file and repeats a staged request that tsserver rejects before it has a project', async () => { + const texts: [string, string][] = []; + let opened: vscode.Uri | undefined; + const provider = new TS6StructuralDiffProvider(async args => { + texts.push([args.originalText, args.modifiedText]); + if (opened === undefined) { + throw new Error('Unrecognized JSON command: _.copilot.structuralDiff'); + } + return serve(args); + }, async fileUri => { opened = fileUri; }); + const original = 'function staged() { return 1; }'; + const modified = 'function staged() { return 2; }'; + const result = await provider.provideStructuralDiff( + createTextDocumentData(toGitUri(uri, 'HEAD'), original, 'typescript').document, + createTextDocumentData(toGitUri(uri, ''), modified, 'typescript').document, + { changes: [{ originalRange: rangeOf(original, '1'), modifiedRange: rangeOf(modified, '2') }] }, + CancellationToken.None); + assert.deepStrictEqual({ opened: opened?.toString(), texts, names: result?.root.children?.map(node => node.modifiedItem?.name) }, { + opened: uri.toString(), + texts: [[original, modified], [original, modified]], + names: ['staged'], + }); + }); + + test('rejects with the request failure when the backing file cannot be opened', async () => { + const failure = new Error('Unrecognized JSON command: _.copilot.structuralDiff'); + const provider = new TS6StructuralDiffProvider(async () => { throw failure; }, async () => { throw new Error('File not found'); }); + const document = createTextDocumentData(toGitUri(uri, ''), 'const value = 1;', 'typescript').document; + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, CancellationToken.None), error => error === failure); + }); + + test('does not send a request for an already cancelled request', async () => { + const requests: protocol.StructuralDiffRequestArgs[] = []; + const provider = new TS6StructuralDiffProvider(async args => { + requests.push(args); + return serve(args); + }); + const document = createTextDocumentData(uri, '', 'typescript').document; + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, CancellationToken.Cancelled), isCancellationError); + assert.deepStrictEqual(requests, []); + }); + + for (const side of ['original', 'modified'] as const) { + test(`does not publish a result for a ${side} document edited during the request`, async () => { + const original = createTextDocumentData(toGitUri(uri, ''), 'const x = 1;', 'typescript'); + const modified = createTextDocumentData(uri, 'const x = 2;', 'typescript'); + const provider = new TS6StructuralDiffProvider(args => { + setDocText(side === 'original' ? original : modified, 'const x = 3;'); + return serve(args); + }); + await assert.rejects(provider.provideStructuralDiff(original.document, modified.document, { changes: [] }, CancellationToken.None), isCancellationError); + }); + } + + test('stops the analysis in the server plugin once the request is cancelled', () => { + const args = { fileName: uri.fsPath, originalText: 'const x = 1;', modifiedText: 'const x = 2;', changes: [] }; + const token = { isCancellationRequested: () => true, throwIfCancellationRequested: () => { throw new ts.OperationCanceledException(); } }; + assert.throws(() => computeStructuralDiff(args, token), ts.OperationCanceledException); + }); +}); diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/component.tsx b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/component.tsx new file mode 100644 index 000000000000..d36f9a5d8362 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/component.tsx @@ -0,0 +1 @@ +export const Component = () =>
old text
; \ No newline at end of file diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.spec.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.spec.ts new file mode 100644 index 000000000000..d432a7302e48 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.spec.ts @@ -0,0 +1 @@ +export const value = 1; \ No newline at end of file diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.ts new file mode 100644 index 000000000000..d432a7302e48 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/source/example.ts @@ -0,0 +1 @@ +export const value = 1; \ No newline at end of file diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/tsconfig.json b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/tsconfig.json new file mode 100644 index 000000000000..24c9e12111b2 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/fixtures/structuralDiff/tsconfig.json @@ -0,0 +1 @@ +{ "compilerOptions": { "rootDir": "./source", "jsx": "preserve" } } \ No newline at end of file diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiff.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiff.ts new file mode 100644 index 000000000000..b322a1dacaaf --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiff.ts @@ -0,0 +1,610 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as ts from '@typescript/native/ast'; +import * as vscode from 'vscode'; +import { findFirstIdxMonotonousOrArrLen } from '../../../../util/vs/base/common/arraysFind'; +import { CancellationError } from '../../../../util/vs/base/common/errors'; +import { basename } from '../../../../util/vs/base/common/path'; +import tss from './typescripts'; + +interface Span { + readonly start: number; + readonly end: number; +} + +/** + * Spans in document order that do not overlap, so that their ends are in order as well. + */ +type SortedSpans = readonly Span[]; + +interface EntityInfo { + readonly name: string; + readonly kind: vscode.SymbolKind; + readonly languageKind: string; + readonly node: ts.Node; + readonly rangeNode: ts.Node; + readonly nameNode?: ts.Node; + readonly body?: ts.Node; +} + +interface Entity { + readonly value: vscode.StructuralDiffItem; + /** A language-specific category, such as `getter` or `imports`, that tells apart entities of the same kind and name. */ + readonly languageKind?: string; + readonly node: ts.Node; + readonly span: Span; + readonly groupedSpans?: readonly Span[]; + readonly headerEnd: number; + readonly implementation: SortedSpans; + readonly isTest: boolean; + readonly children: Entity[]; + readonly rename?: { readonly name: Span; readonly declaration: ts.Node }; +} + +interface Source { + readonly file: ts.SourceFile; + readonly root: Entity; + readonly dependencies: SortedSpans; + readonly tests: SortedSpans; +} + +interface MutableDiffNode extends vscode.StructuralDiffNode { + readonly originalChanges: vscode.StructuralDiffCoverage[]; + readonly modifiedChanges: vscode.StructuralDiffCoverage[]; + readonly children: vscode.StructuralDiffNode[]; +} + +interface DiffTree { + readonly original?: Entity; + readonly modified?: Entity; + readonly result: MutableDiffNode; + readonly children: DiffTree[]; + /** The spans of the children on each side, sorted by their start. */ + readonly childSpans: Readonly>; +} + +interface ChildSpan { + readonly child: DiffTree; + readonly span: Span; + /** The largest end of this and all preceding spans, which, unlike the ends, cannot decrease if siblings overlap. */ + readonly reach: number; +} + +type Side = 'original' | 'modified'; + +interface TextChange { + readonly original: Span; + readonly modified: Span; +} + +/** + * Matches named siblings and conservative name-only renames in a sparse structural tree. + */ +export function computeStructuralDiff(originalFile: ts.SourceFile, modifiedFile: ts.SourceFile, context: vscode.StructuralDiffContext, token: vscode.CancellationToken): vscode.StructuralDiff { + const checkCancellation = () => { + if (token.isCancellationRequested) { + throw new CancellationError(); + } + }; + const original = collectSource(originalFile, checkCancellation); + const modified = collectSource(modifiedFile, checkCancellation); + const changes = context.changes.map(change => ({ + original: fromRange(originalFile, change.originalRange), + modified: fromRange(modifiedFile, change.modifiedRange), + })); + let nextId = 0; + const merge = (left: Entity | undefined, right: Entity | undefined): DiffTree => { + checkCancellation(); + const result: MutableDiffNode = { + id: String(nextId++), + originalItem: left?.value, + modifiedItem: right?.value, + originalChanges: [], + modifiedChanges: [], + children: [], + }; + const leftChildren = left?.children ?? []; + const rightChildren = right?.children ?? []; + const counterparts = matchSiblings(leftChildren, rightChildren, originalFile, modifiedFile, changes, checkCancellation); + const matched = new Set(); + const children = rightChildren.map(child => { + const counterpart = counterparts.get(child); + if (counterpart !== undefined) { + matched.add(counterpart); + } + return merge(counterpart, child); + }); + for (const child of leftChildren) { + if (!matched.has(child)) { + children.push(merge(child, undefined)); + } + } + return { original: left, modified: right, result, children, childSpans: { original: getChildSpans(children, 'original'), modified: getChildSpans(children, 'modified') } }; + }; + const tree = merge(original.root, modified.root); + for (const [textChangeIndex, change] of changes.entries()) { + checkCancellation(); + classify(tree, 'original', original, textChangeIndex, change.original, checkCancellation); + classify(tree, 'modified', modified, textChangeIndex, change.modified, checkCancellation); + } + const prune = (node: DiffTree): MutableDiffNode => { + for (const child of node.children) { + const result = prune(child); + if (result.originalChanges.length > 0 || result.modifiedChanges.length > 0 || result.children.length > 0) { + node.result.children.push(result); + } + } + return node.result; + }; + checkCancellation(); + return { root: prune(tree), isIncomplete: false }; +} + +function collectSource(file: ts.SourceFile, checkCancellation: () => void): Source { + const root: Entity = { + value: { name: basename(file.fileName), kind: vscode.SymbolKind.File, range: toRange(file, { start: 0, end: file.text.length }) }, + node: file, + span: { start: 0, end: file.text.length }, + headerEnd: 0, + implementation: file.statements.map(statement => nodeSpan(statement, file)), + isTest: isTestFile(file.fileName), + children: [], + }; + const dependencies: Span[] = []; + const tests: Span[] = []; + const statementGroups = new Map>(); + const visit = (node: ts.Node, parent: Entity): void => { + checkCancellation(); + if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) || (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined)) { + dependencies.push(nodeSpan(node, file)); + } + const groupKind = ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node) ? 'imports' + : ts.isExportDeclaration(node) || ts.isExportAssignment(node) || ts.isNamespaceExportDeclaration(node) ? 'exports' : undefined; + if (groupKind !== undefined) { + let groups = statementGroups.get(parent); + if (groups === undefined) { + groups = new Map(); + statementGroups.set(parent, groups); + } + const span = nodeSpan(node, file); + const spans = groups.get(groupKind); + if (spans === undefined) { + groups.set(groupKind, [span]); + } else { + spans.push(span); + } + } + if (ts.isCallExpression(node) && isTestCallee(node.expression)) { + for (const argument of node.arguments) { + if (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)) { + tests.push(nodeSpan(argument, file)); + } + } + } + let container = parent; + const info = node === parent.node ? undefined : getEntityInfo(node, file); + if (info !== undefined) { + const span = nodeSpan(info.rangeNode, file); + if (span.start < span.end && contains(parent.span, span)) { + const children = structuralChildren(info.node); + const headerEnd = info.body?.getStart(file) ?? children[0]?.getStart(file) ?? span.end; + container = { + value: { + name: info.name, + kind: info.kind, + range: toRange(file, span), + selectionRange: info.nameNode === undefined ? undefined : toRange(file, nodeSpan(info.nameNode, file)), + }, + languageKind: info.languageKind, + node: info.node, + span, + headerEnd, + implementation: bodySpans(info.body, file), + isTest: parent.isTest || /^(?:it|test|spec)(?:$|[\s_.:-]|[A-Z])/.test(info.name), + children: [], + rename: info.nameNode && (ts.isIdentifier(info.nameNode) || ts.isPrivateIdentifier(info.nameNode)) + ? { name: nodeSpan(info.nameNode, file), declaration: info.rangeNode } + : undefined, + }; + parent.children.push(container); + } + } + node.forEachChild(child => visit(child, container)); + }; + file.forEachChild(child => visit(child, root)); + for (const [parent, groups] of statementGroups) { + for (const [kind, spans] of groups) { + checkCancellation(); + const span = { start: spans[0].start, end: spans[spans.length - 1].end }; + const isInStatement = createContainmentLookup(spans); + const children = parent.children.filter(child => isInStatement(child.span)); + const childSet = new Set(children); + parent.children.splice(0, parent.children.length, ...parent.children.filter(child => !childSet.has(child))); + parent.children.push({ + value: { + name: kind === 'imports' ? vscode.l10n.t('Imports') : vscode.l10n.t('Exports'), + kind: vscode.SymbolKind.Module, + range: toRange(file, span), + selectionRange: toRange(file, spans[0]), + }, + languageKind: kind, + node: parent.node, + span, + groupedSpans: spans, + headerEnd: span.start, + implementation: spans, + isTest: parent.isTest, + children, + }); + } + parent.children.sort((left, right) => left.span.start - right.span.start); + } + // Test callbacks can be nested, but the classification only asks whether text lies in any of them. + return { file, root, dependencies: toSortedSpans(dependencies), tests: toSortedSpans(tests) }; +} + +function getEntityInfo(node: ts.Node, file: ts.SourceFile): EntityInfo | undefined { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) { + let rangeNode: ts.Node = node; + if (ts.isVariableDeclaration(node) && ts.isVariableDeclarationList(node.parent) + && node.parent.declarations.length === 1 && ts.isVariableStatement(node.parent.parent)) { + rangeNode = node.parent.parent; + } + const initializer = node.initializer && tss.Nodes.skipOuterExpressions(node.initializer); + const base = { name: node.name.getText(file), nameNode: node.name, rangeNode }; + if (initializer !== undefined) { + if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) { + return { ...base, node: initializer, kind: vscode.SymbolKind.Function, languageKind: ts.isArrowFunction(initializer) ? 'arrow-function' : 'function', body: initializer.body }; + } + if (ts.isClassExpression(initializer)) { + return { ...base, node: initializer, kind: vscode.SymbolKind.Class, languageKind: 'class' }; + } + if (ts.isObjectLiteralExpression(initializer) || ts.isArrayLiteralExpression(initializer)) { + return { ...base, node: initializer, kind: ts.isObjectLiteralExpression(initializer) ? vscode.SymbolKind.Object : vscode.SymbolKind.Array, languageKind: ts.isObjectLiteralExpression(initializer) ? 'object' : 'array', body: initializer }; + } + } + return { ...base, node, kind: ts.isVariableDeclaration(node) ? vscode.SymbolKind.Variable : vscode.SymbolKind.Property, languageKind: ts.isVariableDeclaration(node) ? 'variable' : 'property', body: node.initializer }; + } + const base = { node, rangeNode: node }; + if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) { + const name = node.name?.getText(file) ?? (node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined); + return name === undefined ? undefined : { ...base, name, nameNode: node.name, kind: vscode.SymbolKind.Class, languageKind: 'class' }; + } + if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node) || ts.isModuleDeclaration(node)) { + const kind = ts.isInterfaceDeclaration(node) ? vscode.SymbolKind.Interface + : ts.isTypeAliasDeclaration(node) ? vscode.SymbolKind.Variable + : ts.isEnumDeclaration(node) ? vscode.SymbolKind.Enum : vscode.SymbolKind.Module; + const languageKind = ts.isInterfaceDeclaration(node) ? 'interface' : ts.isTypeAliasDeclaration(node) ? 'type-alias' : ts.isEnumDeclaration(node) ? 'enum' : 'module'; + return { ...base, name: node.name.getText(file), nameNode: node.name, kind, languageKind, body: ts.isModuleDeclaration(node) ? node.body : undefined }; + } + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) { + const name = node.name?.getText(file) ?? (ts.isFunctionDeclaration(node) && node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined); + return name === undefined ? undefined : { ...base, name, nameNode: node.name, kind: vscode.SymbolKind.Function, languageKind: 'function', body: node.body }; + } + if (ts.isConstructorDeclaration(node)) { + return { ...base, name: 'constructor', kind: vscode.SymbolKind.Constructor, languageKind: 'constructor', body: node.body }; + } + if (ts.isMethodDeclaration(node) || ts.isMethodSignatureDeclaration(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: vscode.SymbolKind.Method, languageKind: 'method', body: ts.isMethodDeclaration(node) ? node.body : undefined }; + } + if (ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: vscode.SymbolKind.Property, languageKind: ts.isGetAccessorDeclaration(node) ? 'getter' : 'setter', body: node.body }; + } + if (ts.isPropertySignatureDeclaration(node) || ts.isEnumMember(node)) { + return { ...base, name: node.name.getText(file), nameNode: node.name, kind: ts.isEnumMember(node) ? vscode.SymbolKind.EnumMember : vscode.SymbolKind.Property, languageKind: ts.isEnumMember(node) ? 'enum-member' : 'property', body: ts.isEnumMember(node) ? node.initializer : undefined }; + } + if (ts.isClassStaticBlockDeclaration(node)) { + return { ...base, name: 'static', kind: vscode.SymbolKind.Method, languageKind: 'static-block', body: node.body }; + } + if (ts.isCallSignatureDeclaration(node) || ts.isConstructSignatureDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + const name = ts.isCallSignatureDeclaration(node) ? '(call)' : ts.isConstructSignatureDeclaration(node) ? '(new)' : '[index]'; + return { ...base, name, kind: ts.isConstructSignatureDeclaration(node) ? vscode.SymbolKind.Constructor : vscode.SymbolKind.Method, languageKind: ts.isCallSignatureDeclaration(node) ? 'call-signature' : ts.isConstructSignatureDeclaration(node) ? 'construct-signature' : 'index-signature' }; + } + return undefined; +} + +function structuralChildren(node: ts.Node): readonly ts.Node[] { + if (ts.isClassDeclaration(node) || ts.isClassExpression(node) || ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)) { + return node.members; + } + return []; +} + +function bodySpans(body: ts.Node | undefined, file: ts.SourceFile): readonly Span[] { + if (body === undefined) { + return []; + } + if (ts.isBlock(body) || ts.isModuleBlock(body)) { + return [{ start: body.getStart(file) + 1, end: Math.max(body.getStart(file) + 1, body.getEnd() - 1) }]; + } + return [nodeSpan(body, file)]; +} + +function entityKey(entity: Entity): string { + return JSON.stringify([entity.value.kind, entity.languageKind, entity.value.name]); +} + +function groupEntities(entities: readonly Entity[], keyOf: (entity: Entity) => string | undefined = entityKey): Map { + const groups = new Map(); + for (const entity of entities) { + const key = keyOf(entity); + if (key === undefined) { + continue; + } + const group = groups.get(key); + if (group === undefined) { + groups.set(key, [entity]); + } else { + group.push(entity); + } + } + return groups; +} + +function matchSiblings(original: readonly Entity[], modified: readonly Entity[], originalFile: ts.SourceFile, modifiedFile: ts.SourceFile, changes: readonly TextChange[], checkCancellation: () => void): Map { + const originalByKey = groupEntities(original); + const modifiedByKey = groupEntities(modified); + const matches = new Map(); + const matchedOriginal = new Set(); + for (const entity of modified) { + checkCancellation(); + const key = entityKey(entity); + const candidates = originalByKey.get(key); + if (candidates?.length === 1 && modifiedByKey.get(key)?.length === 1) { + matches.set(entity, candidates[0]); + matchedOriginal.add(candidates[0]); + } + } + + const unmatchedOriginal = original.filter(entity => !matchedOriginal.has(entity) && originalByKey.get(entityKey(entity))?.length === 1); + const unmatchedModified = modified.filter(entity => !matches.has(entity) && modifiedByKey.get(entityKey(entity))?.length === 1); + if (unmatchedOriginal.length === 0 || unmatchedModified.length === 0) { + return matches; + } + const originalBySyntax = groupEntities(unmatchedOriginal, entity => renameFingerprint(entity, originalFile, checkCancellation)); + const modifiedBySyntax = groupEntities(unmatchedModified, entity => renameFingerprint(entity, modifiedFile, checkCancellation)); + for (const [fingerprint, candidates] of modifiedBySyntax) { + checkCancellation(); + const originalCandidates = originalBySyntax.get(fingerprint); + if (candidates.length !== 1 || originalCandidates?.length !== 1) { + continue; + } + const before = originalCandidates[0]; + const after = candidates[0]; + if (before.value.name !== after.value.name && isNameChanged(changes, before.rename!.name, after.rename!.name)) { + matches.set(after, before); + } + } + return matches; +} + +function renameFingerprint(entity: Entity, file: ts.SourceFile, checkCancellation: () => void): string | undefined { + if (entity.rename === undefined) { + return undefined; + } + const { name, declaration } = entity.rename; + const parts: [ts.SyntaxKind, string | null][] = []; + let nameTokens = 0; + let missingToken = false; + const visit = (node: ts.Node): void => { + checkCancellation(); + if (ts.isJSDocNodeKind(node.kind) || ts.isTriviaKind(node.kind)) { + return; + } + if (ts.isToken(node)) { + const span = nodeSpan(node, file); + if (span.start === span.end) { + missingToken = true; + } else if (span.start === name.start && span.end === name.end) { + nameTokens++; + parts.push([node.kind, null]); + } else { + parts.push([node.kind, node.getText(file)]); + } + } else { + parts.push([node.kind, null]); + node.getChildren(file).forEach(visit); + } + }; + visit(declaration); + return nameTokens === 1 && !missingToken + ? JSON.stringify([entity.value.kind, entity.languageKind, parts]) + : undefined; +} + +function touchesName(change: Span, name: Span): boolean { + return change.start === change.end + ? name.start <= change.start && change.start <= name.end + : change.start < name.end && name.start < change.end; +} + +/** + * Returns whether one change touches both the original and the modified name. The changes are ordered and do not + * overlap, so a binary search finds the ones around the original name, and renaming many declarations does not check + * every change for each of them. + */ +function isNameChanged(changes: readonly TextChange[], originalName: Span, modifiedName: Span): boolean { + for (let index = findFirstIdxMonotonousOrArrLen(changes, change => change.original.end >= originalName.start); index < changes.length && changes[index].original.start <= originalName.end; index++) { + if (touchesName(changes[index].original, originalName) && touchesName(changes[index].modified, modifiedName)) { + return true; + } + } + return false; +} + +function classify(tree: DiffTree, side: Side, source: Source, textChangeIndex: number, span: Span, checkCancellation: () => void): void { + checkCancellation(); + const entity = tree[side]; + if (entity === undefined || span.start >= span.end) { + return; + } + const counterpart = side === 'original' ? tree.modified : tree.original; + if (entity !== source.root && entity.groupedSpans === undefined && counterpart === undefined && contains(span, entity.span)) { + addCoverage(tree, side, source, textChangeIndex, span, vscode.StructuralDiffClassification.Declaration); + return; + } + let cursor = span.start; + const children = tree.childSpans[side]; + // A binary search skips the children before the span and the loop stops at the first child after it, so that + // bulk edits do not visit every sibling for every change. + for (let index = findFirstIdxMonotonousOrArrLen(children, child => child.reach > span.start); index < children.length && children[index].span.start < span.end; index++) { + const { child, span: childSpan } = children[index]; + const start = Math.max(cursor, childSpan.start); + const end = Math.min(span.end, childSpan.end); + if (start >= end) { + continue; + } + addCoverage(tree, side, source, textChangeIndex, { start: cursor, end: start }); + classify(child, side, source, textChangeIndex, { start, end }, checkCancellation); + cursor = end; + } + addCoverage(tree, side, source, textChangeIndex, { start: cursor, end: span.end }); +} + +function getChildSpans(children: readonly DiffTree[], side: Side): ChildSpan[] { + const spans = children.flatMap(child => { + const entity = child[side]; + return entity === undefined ? [] : (entity.groupedSpans ?? [entity.span]).map(span => ({ child, span })); + }).sort((left, right) => left.span.start - right.span.start); + let reach = 0; + return spans.map(({ child, span }) => { + reach = Math.max(reach, span.end); + return { child, span, reach }; + }); +} + +function addCoverage(tree: DiffTree, side: Side, source: Source, textChangeIndex: number, span: Span, classification?: vscode.StructuralDiffClassification): void { + if (span.start >= span.end) { + return; + } + const entity = tree[side]!; + const header = { start: entity.span.start, end: entity.headerEnd }; + // Only regions that overlap the span can split it, so the many gaps between the declarations of a new file stay cheap. + const dependencies = getOverlappingSpans(source.dependencies, span); + const implementation = getOverlappingSpans(entity.implementation, span); + const tests = getOverlappingSpans(source.tests, span); + const boundaries = new Set([span.start, span.end]); + for (const region of [...dependencies, header, ...implementation, ...tests]) { + if (region.start > span.start && region.start < span.end) { + boundaries.add(region.start); + } + if (region.end > span.start && region.end < span.end) { + boundaries.add(region.end); + } + } + const offsets = [...boundaries].sort((left, right) => left - right); + const inDependency = createContainmentCheck(dependencies); + const inImplementation = createContainmentCheck(implementation); + const inTest = createContainmentCheck(tests); + const changes = side === 'original' ? tree.result.originalChanges : tree.result.modifiedChanges; + for (let index = 0; index < offsets.length - 1; index++) { + const part = { start: offsets[index], end: offsets[index + 1] }; + const kind = classification + ?? (inDependency(part) ? vscode.StructuralDiffClassification.Dependency + : contains(header, part) ? vscode.StructuralDiffClassification.Header + : inImplementation(part) ? vscode.StructuralDiffClassification.Implementation + : vscode.StructuralDiffClassification.Other); + const isTest = entity.isTest || inTest(part); + const range = toRange(source.file, part); + const previous = changes[changes.length - 1]; + if (previous?.textChangeIndex === textChangeIndex && previous.classification === kind + && (previous.tags?.includes(vscode.StructuralDiffTag.Test) ?? false) === isTest && previous.range.end.isEqual(range.start)) { + changes[changes.length - 1] = { ...previous, range: new vscode.Range(previous.range.start, range.end) }; + } else { + changes.push({ textChangeIndex, range, classification: kind, tags: isTest ? [vscode.StructuralDiffTag.Test] : [] }); + } + } +} + +function nodeSpan(node: ts.Node, file: ts.SourceFile): Span { + return { start: node.getStart(file), end: node.getEnd() }; +} + +function fromRange(file: ts.SourceFile, range: vscode.Range): Span { + return { + start: file.getPositionOfLineAndCharacter(range.start.line, range.start.character), + end: file.getPositionOfLineAndCharacter(range.end.line, range.end.character), + }; +} + +function toRange(file: ts.SourceFile, span: Span): vscode.Range { + const start = file.getLineAndCharacterOfPosition(span.start); + const end = file.getLineAndCharacterOfPosition(span.end); + return new vscode.Range(start.line, start.character, end.line, end.character); +} + +function contains(container: Span, contained: Span): boolean { + return container.start <= contained.start && container.end >= contained.end; +} + +/** + * Returns sorted spans that cover the same offsets as the given spans, merging the ones that overlap. + */ +function toSortedSpans(spans: readonly Span[]): SortedSpans { + const result: Span[] = []; + for (const span of [...spans].sort((left, right) => left.start - right.start)) { + const last = result[result.length - 1]; + if (last !== undefined && span.start <= last.end) { + result[result.length - 1] = { start: last.start, end: Math.max(last.end, span.end) }; + } else { + result.push(span); + } + } + return result; +} + +function getOverlappingSpans(spans: SortedSpans, span: Span): SortedSpans { + const start = findFirstIdxMonotonousOrArrLen(spans, candidate => candidate.end > span.start); + return spans.slice(start, findFirstIdxMonotonousOrArrLen(spans, candidate => candidate.start >= span.end, start)); +} + +/** + * Returns a check whether a part lies within one of the spans. Parts must be checked in document order, which lets + * each check continue where the previous one stopped. + */ +function createContainmentCheck(spans: SortedSpans): (part: Span) => boolean { + let index = 0; + return part => { + while (index < spans.length && spans[index].end <= part.start) { + index++; + } + return index < spans.length && contains(spans[index], part); + }; +} + +/** + * Returns a lookup whether a span lies within one of the given spans, which must be sorted by their start. Unlike + * {@link createContainmentCheck}, the spans can overlap and can be looked up in any order: the spans that start at or + * before a span contain it if the largest of their ends reaches its end, which a binary search finds. + */ +function createContainmentLookup(spans: readonly Span[]): (span: Span) => boolean { + const reaches: number[] = []; + for (const span of spans) { + reaches.push(Math.max(reaches[reaches.length - 1] ?? span.end, span.end)); + } + return span => { + const count = findFirstIdxMonotonousOrArrLen(spans, candidate => candidate.start > span.start); + return count > 0 && reaches[count - 1] >= span.end; + }; +} + +function isTestCallee(node: ts.Node): boolean { + if (ts.isIdentifier(node)) { + return node.text === 'test' || node.text === 'it' || node.text === 'describe' || node.text === 'suite'; + } + if (ts.isPropertyAccessExpression(node) || ts.isCallExpression(node)) { + return isTestCallee(node.expression); + } + return false; +} + +function isTestFile(fileName: string): boolean { + const normalized = fileName.replace(/\\/g, '/'); + const name = normalized.slice(normalized.lastIndexOf('/') + 1); + return /(?:^|\/)(?:test|tests|__tests__)(?:\/|$)/i.test(normalized) + || /(?:^|[._-])(?:test|spec)(?=\.[^.]+$)/i.test(name) + || /^(?:test|spec)[._-]/i.test(name); +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiffProvider.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiffProvider.ts new file mode 100644 index 000000000000..a8b53b8045a5 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/structuralDiffProvider.ts @@ -0,0 +1,87 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { API } from '@typescript/native/async'; +import type { SourceFile } from '@typescript/native/ast'; +import type * as vscode from 'vscode'; +import type { ILogService } from '../../../../platform/log/common/logService'; +import { DisposableStore } from '../../../../util/vs/base/common/lifecycle'; +import { StructuralDiffDocuments } from '../structuralDiffDocuments'; +import { computeStructuralDiff } from './structuralDiff'; +import { TypeScript7Api } from './ts7Api'; + +type StructuralDiffApi = Pick, 'clearSourceFileCache' | 'createSnapshot' | 'runWithTemporaryFileUpdate'>; + +interface StructuralDiffApiProvider extends vscode.Disposable { + getApi(): Promise; +} + +/** + * Uses the backing file for TS7 project lookup and analyzes only the supplied document contents in isolated snapshots. + */ +export class TS7StructuralDiffProvider implements vscode.StructuralDiffProvider, vscode.Disposable { + private readonly disposables = new DisposableStore(); + private readonly nativeApi: StructuralDiffApiProvider; + + constructor(logService: ILogService, nativeApi: StructuralDiffApiProvider = new TypeScript7Api(logService)) { + this.nativeApi = this.disposables.add(nativeApi); + } + + async provideStructuralDiff(originalDocument: vscode.TextDocument, modifiedDocument: vscode.TextDocument, context: vscode.StructuralDiffContext, token: vscode.CancellationToken): Promise { + const fileUri = StructuralDiffDocuments.getBackingFile(modifiedDocument); + if (fileUri === undefined) { + return undefined; + } + const checkCancellation = StructuralDiffDocuments.createCancellationCheck(originalDocument, modifiedDocument, token); + checkCancellation(); + const originalText = originalDocument.getText(); + const modifiedText = modifiedDocument.getText(); + const api = await this.nativeApi.getApi(); + checkCancellation(); + if (api === undefined) { + return undefined; + } + const file = { uri: fileUri.toString() }; + api.clearSourceFileCache(); + const snapshot = await api.createSnapshot({ openFiles: [file] }); + let result: vscode.StructuralDiff | undefined; + try { + checkCancellation(); + const readSource = async (text: string): Promise => { + let sourceFile: SourceFile | undefined; + await api.runWithTemporaryFileUpdate(snapshot, file, text, async temporarySnapshot => { + checkCancellation(); + const project = await temporarySnapshot.getDefaultProjectForFile(file); + sourceFile = await project?.program.getSourceFile(file); + checkCancellation(); + if (sourceFile !== undefined && sourceFile.text !== text) { + throw new Error('TypeScript structural diff snapshot does not match the requested document'); + } + }); + checkCancellation(); + return sourceFile; + }; + const original = await readSource(originalText); + const modified = await readSource(modifiedText); + if (original !== undefined && modified !== undefined) { + checkCancellation(); + result = computeStructuralDiff(original, modified, context, token); + } + } finally { + try { + await snapshot.dispose(); + } finally { + const closedSnapshot = await api.createSnapshot({ closeFiles: [file] }); + await closedSnapshot.dispose(); + } + } + checkCancellation(); + return result; + } + + dispose(): void { + this.disposables.dispose(); + } +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/test/structuralDiff.spec.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/test/structuralDiff.spec.ts new file mode 100644 index 000000000000..ac93e140b518 --- /dev/null +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/test/structuralDiff.spec.ts @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * 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'; +import fs from 'node:fs'; +import path from 'node:path'; +import { API, type DocumentIdentifier, type Snapshot } from '@typescript/native/async'; +import { afterAll, afterEach, beforeAll, beforeEach, suite, test } from 'vitest'; +import * as vscode from 'vscode'; +import { toGitUri } from '../../../../../platform/git/common/utils'; +import { TestLogService } from '../../../../../platform/testing/common/testLogService'; +import { createTextDocumentData, setDocText } from '../../../../../util/common/test/shims/textDocument'; +import { CancellationToken } from '../../../../../util/vs/base/common/cancellation'; +import { isCancellationError } from '../../../../../util/vs/base/common/errors'; +import { DisposableStore } from '../../../../../util/vs/base/common/lifecycle'; +import { createCompute, defineStructuralDiffCases, fixtureDirectory, rangeOf, summarize } from '../../test/structuralDiffCases'; +import { TS7StructuralDiffProvider } from '../structuralDiffProvider'; + +suite('TypeScript 7 structural diff', () => { + const store = new DisposableStore(); + const fileName = path.join(fixtureDirectory, 'example.ts'); + const uri = vscode.Uri.file(fileName); + let api: API; + let native: TestTypeScript7Api; + let provider: TS7StructuralDiffProvider; + const compute = createCompute(() => provider, uri); + + beforeAll(() => { + api = new API({ cwd: process.cwd() }); + }); + + beforeEach(() => { + native = new TestTypeScript7Api(api); + provider = store.add(new TS7StructuralDiffProvider(new TestLogService(), native)); + }); + + afterEach(() => store.clear()); + afterAll(async () => { + store.dispose(); + await api.close(); + }); + + for (const [file, languageId] of [['example.ts', 'typescript'], ['component.tsx', 'typescriptreact']]) { + test(`analyzes staged ${languageId} contents using the backing file only for project lookup`, async () => { + const fileUri = vscode.Uri.file(path.join(fixtureDirectory, file)); + const diskContents = fs.readFileSync(fileUri.fsPath, 'utf8'); + const original = 'function stagedOnly() { return 1; }'; + const modified = 'function stagedOnly() { return 2; }'; + const result = await compute(original, modified, [{ + originalRange: rangeOf(original, '1'), modifiedRange: rangeOf(modified, '2'), + }], toGitUri(fileUri, ''), languageId, toGitUri(fileUri, 'HEAD')); + assert.deepStrictEqual({ + nodes: summarize(result, original, modified).map(node => ({ + name: node.modified, originalChanges: node.originalChanges, modifiedChanges: node.modifiedChanges, + })), + requests: native.requests, + disposed: native.snapshots.every(snapshot => snapshot.isDisposed()), + diskContents: fs.readFileSync(fileUri.fsPath, 'utf8'), + }, { + nodes: [{ + name: 'stagedOnly', + originalChanges: [[0, vscode.StructuralDiffClassification.Implementation, '1', []]], + modifiedChanges: [[0, vscode.StructuralDiffClassification.Implementation, '2', []]], + }], + requests: [{ openFiles: [{ uri: fileUri.toString() }] }, { closeFiles: [{ uri: fileUri.toString() }] }], + disposed: true, diskContents, + }); + }); + } + + test('resolves the backing path from Git metadata rather than a decorated document path', async () => { + const original = 'function stagedOnly() { return 1; }'; + const modified = 'function stagedOnly() { return 2; }'; + const result = await compute(original, modified, undefined, toGitUri(uri, '', { replaceFileExtension: true }), 'typescript', toGitUri(uri, 'HEAD')); + assert.deepStrictEqual({ + names: result.root.children.map(node => node.modifiedItem?.name), + requests: native.requests, + }, { + names: ['stagedOnly'], + requests: [{ openFiles: [{ uri: uri.toString() }] }, { closeFiles: [{ uri: uri.toString() }] }], + }); + }); + + test('keeps simultaneous staged and unstaged requests for the same backing file isolated', async () => { + const head = 'function before() { return 1; }'; + const index = 'function renamed() { return 1; }'; + const working = 'function renamed() { return 2; }'; + const [staged, unstaged] = await Promise.all([ + compute(head, index, [{ originalRange: rangeOf(head, 'before'), modifiedRange: rangeOf(index, 'renamed') }], toGitUri(uri, ''), 'typescript', toGitUri(uri, 'HEAD')), + compute(index, working, [{ originalRange: rangeOf(index, '1'), modifiedRange: rangeOf(working, '2') }], uri, 'typescript', toGitUri(uri, '')), + ]); + assert.deepStrictEqual({ + staged: summarize(staged, head, index).map(node => ({ + original: node.original, modified: node.modified, modifiedChanges: node.modifiedChanges, + })), + unstaged: summarize(unstaged, index, working).map(node => ({ + original: node.original, modified: node.modified, modifiedChanges: node.modifiedChanges, + })), + disposed: native.snapshots.every(snapshot => snapshot.isDisposed()), + }, { + staged: [{ original: 'before', modified: 'renamed', modifiedChanges: [[0, vscode.StructuralDiffClassification.Header, 'renamed', []]] }], + unstaged: [{ original: 'renamed', modified: 'renamed', modifiedChanges: [[0, vscode.StructuralDiffClassification.Implementation, '2', []]] }], + disposed: true, + }); + }); + + for (const [name, query, error] of [ + ['malformed JSON', '{', SyntaxError], + ['null metadata', 'null', /absolute file path and a string ref/], + ['missing path', JSON.stringify({ ref: '' }), /absolute file path and a string ref/], + ['relative path', JSON.stringify({ path: 'example.ts', ref: '' }), /absolute file path and a string ref/], + ['missing ref', JSON.stringify({ path: fileName }), /absolute file path and a string ref/], + ] as const) { + test(`rejects a Git snapshot with ${name} before starting native analysis`, async () => { + const original = createTextDocumentData(toGitUri(uri, 'HEAD'), '', 'typescript').document; + const modified = createTextDocumentData(uri.with({ scheme: 'git', query }), '', 'typescript').document; + await assert.rejects(provider.provideStructuralDiff(original, modified, { changes: [] }, CancellationToken.None), error); + assert.deepStrictEqual(native.requests, []); + }); + } + + defineStructuralDiffCases(compute); + + test('balances opened files and disposes all native snapshots without modifying the project file', async () => { + await compute('function oldName() {}', 'function newName() {}'); + const snapshot = await api.createSnapshot({ openFiles: [fileName] }); + try { + const project = await snapshot.getDefaultProjectForFile(fileName); + const source = await project?.program.getSourceFile(fileName); + assert.deepStrictEqual({ + requests: native.requests, + disposed: native.snapshots.map(value => value.isDisposed()), + contents: source?.text, + }, { + requests: [{ openFiles: [{ uri: uri.toString() }] }, { closeFiles: [{ uri: uri.toString() }] }], + disposed: [true, true, true, true], + contents: fs.readFileSync(fileName, 'utf8'), + }); + } finally { + await snapshot.dispose(); + await (await api.createSnapshot({ closeFiles: [fileName] })).dispose(); + } + }); + + test('keeps concurrent requests for different versions of the same file isolated', async () => { + const results = await Promise.all([ + compute('function first() { return 1; }', 'function first() { return 2; }'), + compute('function second() { return "before"; }', 'function second() { return "after"; }'), + ]); + assert.deepStrictEqual({ + names: results.map(result => result.root.children[0].modifiedItem?.name), + open: native.requests.filter(request => request?.openFiles !== undefined).length, + close: native.requests.filter(request => request?.closeFiles !== undefined).length, + disposed: native.snapshots.every(snapshot => snapshot.isDisposed()), + }, { names: ['first', 'second'], open: 2, close: 2, disposed: true }); + }); + + test('declines when TS7 is unavailable', async () => { + native.available = false; + const document = createTextDocumentData(uri, 'const value = 1;', 'typescript').document; + assert.deepStrictEqual({ + result: await provider.provideStructuralDiff(document, document, { changes: [] }, CancellationToken.None), + requests: native.requests, + }, { result: undefined, requests: [] }); + }); + + test('does not start analysis for an already cancelled request', async () => { + const document = createTextDocumentData(uri, '', 'typescript').document; + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, CancellationToken.Cancelled), isCancellationError); + assert.deepStrictEqual(native.requests, []); + }); + + test('cancels during analysis and disposes all snapshots', async () => { + const source = store.add(new vscode.CancellationTokenSource()); + const document = createTextDocumentData(uri, 'const value = 1;', 'typescript').document; + native.beforeTemporaryUpdate = () => source.cancel(); + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, source.token), isCancellationError); + assert.deepStrictEqual(native.snapshots.map(snapshot => snapshot.isDisposed()), [true, true, true]); + }); + + test('does not publish a result when cancelled during asynchronous cleanup', async () => { + const source = store.add(new vscode.CancellationTokenSource()); + const document = createTextDocumentData(uri, 'const value = 1;', 'typescript').document; + native.afterCloseSnapshot = () => source.cancel(); + await assert.rejects(provider.provideStructuralDiff(document, document, { changes: [] }, source.token), isCancellationError); + assert.deepStrictEqual(native.snapshots.map(snapshot => snapshot.isDisposed()), [true, true, true, true]); + }); + + test('disposes snapshots on native analysis errors', async () => { + native.failure = new Error('Native analysis failed'); + await assert.rejects(compute('const x = 1;', 'const x = 2;'), /Native analysis failed/); + assert.deepStrictEqual(native.snapshots.map(snapshot => snapshot.isDisposed()), [true, true]); + }); + + test('rejects native snapshots with different contents', async () => { + native.mapText = text => `${text}\n`; + await assert.rejects(compute('const x = 1;', 'const x = 2;'), /snapshot does not match/); + assert.deepStrictEqual(native.snapshots.map(snapshot => snapshot.isDisposed()), [true, true, true]); + }); + + for (const side of ['original', 'modified'] as const) { + test(`rejects stale ${side} documents and releases the snapshots`, async () => { + const original = createTextDocumentData(uri.with({ scheme: 'git' }), 'const x = 1;', 'typescript'); + const modified = createTextDocumentData(uri, 'const x = 2;', 'typescript'); + native.beforeTemporaryUpdate = () => setDocText(side === 'original' ? original : modified, 'const x = 3;'); + await assert.rejects(provider.provideStructuralDiff(original.document, modified.document, { changes: [] }, CancellationToken.None), isCancellationError); + assert.deepStrictEqual(native.snapshots.map(snapshot => snapshot.isDisposed()), [true, true, true]); + }); + } +}); + +type FirstOfTwoOverloads = T extends { + (...args: infer A): infer R; + (...args: never[]): unknown; +} ? (...args: A) => R : never; + +type CreateSnapshotParams = Parameters< + FirstOfTwoOverloads['createSnapshot']> +>[0]; + +class TestTypeScript7Api { + available = true; + failure?: Error; + mapText?: (text: string) => string; + beforeTemporaryUpdate?: () => void; + afterCloseSnapshot?: () => void; + readonly snapshots: Snapshot[] = []; + readonly requests: CreateSnapshotParams[] = []; + + constructor(private readonly api: API) { } + + async getApi() { + if (!this.available) { + return undefined; + } + return { + clearSourceFileCache: () => this.api.clearSourceFileCache(), + createSnapshot: async (params?: CreateSnapshotParams) => { + this.requests.push(params ?? {}); + const snapshot = params === undefined ? await this.api.createSnapshot() : await this.api.createSnapshot(params); + this.snapshots.push(snapshot); + if (params?.closeFiles !== undefined) { + this.afterCloseSnapshot?.(); + } + return snapshot; + }, + runWithTemporaryFileUpdate: async (snapshot: Snapshot, file: DocumentIdentifier, text: string, callback: (snapshot: Snapshot) => void | Promise) => { + if (this.failure !== undefined) { + throw this.failure; + } + await this.api.runWithTemporaryFileUpdate(snapshot, file, this.mapText?.(text) ?? text, async temporarySnapshot => { + this.snapshots.push(temporarySnapshot); + this.beforeTemporaryUpdate?.(); + await callback(temporarySnapshot); + }); + }, + }; + } + + dispose(): void { } +} diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/typescripts.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/typescripts.ts index 151513f3fe53..2e5acc00673e 100644 --- a/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/typescripts.ts +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/ts7/typescripts.ts @@ -10,15 +10,22 @@ import { Symbol as NativeSymbol, SymbolFlags, type NodeHandle, type Program, typ import { findPrecedingToken, getTokenAtPosition, + isAsExpression, isBlock, isClassDeclaration, isInterfaceDeclaration, isModuleBlock, + isNonNullExpression, + isParenthesizedExpression, + isPartiallyEmittedExpression, + isSatisfiesExpression, isSourceFile, isTypeAliasDeclaration, + isTypeAssertion, isTypeReferenceNode, isExpressionWithTypeArguments, SyntaxKind, + type Expression, type Node, type SourceFile, type TypeNode, @@ -465,6 +472,15 @@ namespace tss { } return undefined; } + + export function skipOuterExpressions(expression: Expression): Expression { + let current = expression; + while (isParenthesizedExpression(current) || isAsExpression(current) || isSatisfiesExpression(current) || isTypeAssertion(current) + || isNonNullExpression(current) || isExpressionWithTypeArguments(current) || isPartiallyEmittedExpression(current)) { + current = current.expression; + } + return current; + } } export namespace StableSyntaxKinds { diff --git a/extensions/copilot/src/extension/typescriptContext/vscode-node/tsService.ts b/extensions/copilot/src/extension/typescriptContext/vscode-node/tsService.ts index 00d2d23cef07..7a8ec8cc9b44 100644 --- a/extensions/copilot/src/extension/typescriptContext/vscode-node/tsService.ts +++ b/extensions/copilot/src/extension/typescriptContext/vscode-node/tsService.ts @@ -11,7 +11,7 @@ export namespace TypeScript { const unifiedSection = 'js/ts'; const legacySection = 'typescript'; const useTsgoKey = 'experimental.useTsgo'; - const version7ExtensionIds = ['typescriptteam.vscode-typescript', 'typescriptteam.native-preview'] as const; + const version7ExtensionIds = ['typescriptteam.vscode-typescript', 'typescriptteam.vscode-typescript-nightly', 'typescriptteam.native-preview'] as const; export const versionKey = `${unifiedSection}.${useTsgoKey}`; export const legacyVersionKey = `${legacySection}.${useTsgoKey}`; diff --git a/extensions/copilot/src/extension/vscode-api.d.ts b/extensions/copilot/src/extension/vscode-api.d.ts index 1a4cb52fe0fc..ce325f6b5859 100644 --- a/extensions/copilot/src/extension/vscode-api.d.ts +++ b/extensions/copilot/src/extension/vscode-api.d.ts @@ -59,6 +59,7 @@ /// /// /// +/// /// /// /// diff --git a/extensions/copilot/src/extension/xtab/common/recentFilesForPrompt.ts b/extensions/copilot/src/extension/xtab/common/recentFilesForPrompt.ts index fd30cbea5b66..7e9e10edc31f 100644 --- a/extensions/copilot/src/extension/xtab/common/recentFilesForPrompt.ts +++ b/extensions/copilot/src/extension/xtab/common/recentFilesForPrompt.ts @@ -6,6 +6,7 @@ import { DocumentId } from '../../../platform/inlineEdits/common/dataTypes/docum import { LanguageContextResponse } from '../../../platform/inlineEdits/common/dataTypes/languageContext'; import * as xtabPromptOptions from '../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions'; import { PromptOptions, RecentFileClippingStrategy } from '../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions'; +import { isSensitiveFile } from '../../../platform/inlineEdits/common/sensitiveFiles'; import { StatelessNextEditDocument } from '../../../platform/inlineEdits/common/statelessNextEditProvider'; import { IXtabHistoryEditEntry, IXtabHistoryEntry } from '../../../platform/inlineEdits/common/workspaceEditTracker/nesXtabHistoryTracker'; import { ContextKind } from '../../../platform/languageServer/common/languageContextService'; @@ -429,7 +430,7 @@ export function appendNeighborFileSnippets( for (let i = neighborSnippets.length - 1; i >= 0; i--) { const neighborSnippet = neighborSnippets[i]; const documentId = DocumentId.create(neighborSnippet.uri); - if (docsInPrompt.has(documentId)) { + if (docsInPrompt.has(documentId) || isSensitiveFile(documentId)) { continue; } const potentialBudget = tokenBudget - computeTokens(neighborSnippet.snippet); diff --git a/extensions/copilot/src/extension/xtab/node/xtabProvider.ts b/extensions/copilot/src/extension/xtab/node/xtabProvider.ts index 6c9dba4947d4..11db5482c109 100644 --- a/extensions/copilot/src/extension/xtab/node/xtabProvider.ts +++ b/extensions/copilot/src/extension/xtab/node/xtabProvider.ts @@ -24,6 +24,7 @@ import { AggressivenessSetting, EarlyDivergenceCancellationMode, isEagernessProm import { InlineEditRequestLogContext } from '../../../platform/inlineEdits/common/inlineEditLogContext'; import { IInlineEditsModelService } from '../../../platform/inlineEdits/common/inlineEditsModelService'; import { ResponseProcessor } from '../../../platform/inlineEdits/common/responseProcessor'; +import { withoutOtherSensitiveFiles } from '../../../platform/inlineEdits/common/sensitiveFiles'; import { EditStreaming, EditStreamingWithTelemetry, IStatelessNextEditProvider, NoNextEditReason, RequestEditWindow, RequestEditWindowWithCursorJump, StatelessNextEditDocument, StatelessNextEditRequest, StatelessNextEditTelemetryBuilder, WithStatelessProviderTelemetry } from '../../../platform/inlineEdits/common/statelessNextEditProvider'; import { editWouldDeleteWhatWasJustInserted, editWouldDeleteWhatWasJustInserted2, IgnoreEmptyLineAndLeadingTrailingWhitespaceChanges, IgnoreWhitespaceOnlyChanges } from '../../../platform/inlineEdits/common/statelessNextEditProviders'; import { ILanguageContextProviderService, ProviderTarget } from '../../../platform/languageContextProvider/common/languageContextProviderService'; @@ -1444,13 +1445,14 @@ export class XtabProvider implements IStatelessNextEditProvider { new Edits(StringEdit, []), ); + // The follow-up request is for a different document, so filter the history for it again. const syntheticRequest = new StatelessNextEditRequest( request.headerRequestId, request.opportunityId, targetContent, [syntheticDoc], 0, - request.xtabEditHistory, + withoutOtherSensitiveFiles(request.xtabEditHistory, targetDocumentId), new DeferredPromise>(), request.expandedEditWindowNLines, request.isSpeculative, @@ -1458,7 +1460,7 @@ export class XtabProvider implements IStatelessNextEditProvider { request.recordingBookmark, request.recording, request.providerRequestStartDateTime, - request.xtabRejectedEditHistory, + withoutOtherSensitiveFiles(request.xtabRejectedEditHistory, targetDocumentId), ); return yield* this.doGetNextEditWithSelection( diff --git a/extensions/copilot/src/extension/xtab/test/node/xtabProvider.spec.ts b/extensions/copilot/src/extension/xtab/test/node/xtabProvider.spec.ts index e63e9ec99c71..27db5d73a8c3 100644 --- a/extensions/copilot/src/extension/xtab/test/node/xtabProvider.spec.ts +++ b/extensions/copilot/src/extension/xtab/test/node/xtabProvider.spec.ts @@ -13,13 +13,14 @@ import { InMemoryConfigurationService } from '../../../../platform/configuration import { IEndpointProvider } from '../../../../platform/endpoint/common/endpointProvider'; import { MockEndpoint } from '../../../../platform/endpoint/test/node/mockEndpoint'; import { DocumentId } from '../../../../platform/inlineEdits/common/dataTypes/documentId'; -import { Edits } from '../../../../platform/inlineEdits/common/dataTypes/edit'; +import { Edits, RootedEdit } from '../../../../platform/inlineEdits/common/dataTypes/edit'; import { ImportChanges } from '../../../../platform/inlineEdits/common/dataTypes/importFilteringOptions'; import { LanguageId } from '../../../../platform/inlineEdits/common/dataTypes/languageId'; -import { AggressivenessLevel, AggressivenessSetting, applyStrategyConfig, DEFAULT_OPTIONS, EarlyDivergenceCancellationMode, LanguageContextLanguages, LintOptionShowCode, LintOptionWarning, ModelConfiguration, PatchModelPrediction, PromptingStrategy, ResponseFormat } from '../../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions'; +import { AggressivenessLevel, AggressivenessSetting, applyStrategyConfig, DEFAULT_OPTIONS, EarlyDivergenceCancellationMode, LanguageContextLanguages, LintOptionShowCode, LintOptionWarning, ModelConfiguration, PatchModelPrediction, PromptingStrategy, RejectedEditsMemoryMode, ResponseFormat } from '../../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions'; import { InlineEditRequestLogContext } from '../../../../platform/inlineEdits/common/inlineEditLogContext'; import { IInlineEditsModelService } from '../../../../platform/inlineEdits/common/inlineEditsModelService'; import { NoNextEditReason, StatelessNextEditDocument, StatelessNextEditRequest, StreamedEdit, WithStatelessProviderTelemetry } from '../../../../platform/inlineEdits/common/statelessNextEditProvider'; +import { IXtabHistoryEditEntry } from '../../../../platform/inlineEdits/common/workspaceEditTracker/nesXtabHistoryTracker'; import { ILogger } from '../../../../platform/log/common/logService'; import { FilterReason } from '../../../../platform/networking/common/openai'; import { ISimulationTestContext } from '../../../../platform/simulationTestContext/common/simulationTestContext'; @@ -808,6 +809,7 @@ describe('XtabProvider integration', () => { insertedText?: string; languageId?: string; workspaceRoot?: URI; + docId?: DocumentId; }): StatelessNextEditDocument { const afterText = lines.join('\n'); const insertionOffset = opts?.insertionOffset ?? 0; @@ -824,7 +826,7 @@ describe('XtabProvider integration', () => { const recentEdits = new Edits(StringEdit, [recentStringEdit]); return new StatelessNextEditDocument( - DocumentId.create('file:///test/file.ts'), + opts?.docId ?? DocumentId.create('file:///test/file.ts'), opts?.workspaceRoot, LanguageId.create(opts?.languageId ?? 'typescript'), beforeLines, @@ -2060,6 +2062,86 @@ describe('XtabProvider integration', () => { openSpy.mockRestore(); }); + it('cross-file cursor jump retry leaves out the history of files that commonly hold secrets', async () => { + const provider = createProvider(); + await configService.setConfig(ConfigKey.InlineEditsNextCursorPredictionEnabled, true); + await configService.setConfig(ConfigKey.TeamInternal.InlineEditsNextCursorPredictionModelName, 'test-model'); + mockModelService.setSelectedConfig({ memory: { rejectedEdits: RejectedEditsMemoryMode.DiffWithTags } }); + + // The request starts in `.env`, so its own history is context for it, but not for the jump target. + const envId = DocumentId.create(URI.file('/test/.env').toString()); + const utilId = DocumentId.create(URI.file('/test/util.ts').toString()); + const lines = ['API_TOKEN=secret42', ...Array.from({ length: 29 }, (_, i) => `KEY_${i}=value`)]; + const cursorOffset = lines.slice(0, 5).join('\n').length; + const envDoc = makeDocumentWithEdit(lines, { insertionOffset: cursorOffset, docId: envId, languageId: 'dotenv' }); + const historyEdit = (docId: DocumentId, ordinal: number, before: string, inserted: string): IXtabHistoryEditEntry => ({ + kind: 'edit', + docId, + ordinal, + edit: new RootedEdit(new StringText(before), StringEdit.single(new StringReplacement(OffsetRange.emptyAt(before.length), inserted))), + }); + const request = new StatelessNextEditRequest( + 'req-1', + 'opp-1', + new StringText(envDoc.documentBeforeEdits.value), + [envDoc], + 0, + [historyEdit(utilId, 0, 'export function helper', 'Call() { }'), historyEdit(envId, 1, 'API_TOKEN=', 'secret42')], + new DeferredPromise>(), + undefined, + false, + createLogContext(), + undefined, + undefined, + Date.now(), + [{ kind: 'rejectedEdit', docId: envId, ordinal: 2, hunks: [{ startLineNumber: 2, oldLines: [], newLines: ['DB_PASSWORD=rejected43'] }] }], + ); + + // 1st call (main LLM): edit-window lines unchanged → no edits → cursor jump path + streamingFetcher.enqueueResponse({ + type: ChatFetchResponseType.Success, + requestId: 'req-main', + serverRequestId: 'srv-main', + usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, prompt_tokens_details: { cached_tokens: 0 } }, + value: lines.slice(3, 11).join('\n'), + resolvedModel: 'test-model', + }); + // 2nd call (cursor prediction): jump into another file + streamingFetcher.enqueueResponse({ + type: ChatFetchResponseType.Success, + requestId: 'req-cursor', + serverRequestId: 'srv-cursor', + usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, prompt_tokens_details: { cached_tokens: 0 } }, + value: '/test/other.ts:2', + resolvedModel: 'test-model', + }); + // 3rd call (retry in the jump target): unchanged lines → no edits + const targetLines = Array.from({ length: 5 }, (_, i) => `other ${i}`); + streamingFetcher.setStreamingLines(targetLines); + const targetDoc = createTextDocumentData(URI.file('/test/other.ts'), targetLines.join('\n'), 'typescript').document; + const workspaceService = instaService.invokeFunction(accessor => accessor.get(IWorkspaceService)); + const openSpy = vi.spyOn(workspaceService, 'openTextDocument').mockResolvedValue(targetDoc); + + await collectEdits(provider.provideNextEdit(request, createMockLogger(), createLogContext(), CancellationToken.None)); + openSpy.mockRestore(); + + const promptOfCall = (index: number) => streamingFetcher.capturedOptions[index].messages.map(getMessageText).join('\n'); + const contextIn = (prompt: string) => ({ + otherFileEdit: prompt.includes('helperCall'), + secretEdit: prompt.includes('secret42'), + rejectedSecretEdit: prompt.includes('rejected43'), + }); + expect({ + callCount: streamingFetcher.callCount, + envRequest: contextIn(promptOfCall(0)), + jumpTargetRequest: contextIn(promptOfCall(2)), + }).toEqual({ + callCount: 3, + envRequest: { otherFileEdit: true, secretEdit: true, rejectedSecretEdit: true }, + jumpTargetRequest: { otherFileEdit: true, secretEdit: false, rejectedSecretEdit: false }, + }); + }); + it('model fallback retry on NotFound then yields edits on second attempt', async () => { const provider = createProvider(); diff --git a/extensions/copilot/src/platform/authentication/common/copilotTokenStore.ts b/extensions/copilot/src/platform/authentication/common/copilotTokenStore.ts index d1bd0f756323..123664b77c7c 100644 --- a/extensions/copilot/src/platform/authentication/common/copilotTokenStore.ts +++ b/extensions/copilot/src/platform/authentication/common/copilotTokenStore.ts @@ -21,8 +21,13 @@ export interface ICopilotTokenStore { readonly _serviceBrand: undefined; copilotToken: CopilotToken | undefined; onDidStoreUpdate: Event; + /** Token envelope replacement, including metadata updates with an unchanged bearer token. */ + readonly onDidChangeTokenData: Event; githubEnterpriseUri: URI | undefined; readonly onDidChangeGitHubEnterpriseUri: Event; + /** Unknown until session discovery completes; token absence alone does not establish sign-out. */ + authenticationState: 'unknown' | 'signedIn' | 'signedOut'; + readonly onDidChangeAuthenticationState: Event; } export class CopilotTokenStore extends Disposable implements ICopilotTokenStore { @@ -30,9 +35,24 @@ export class CopilotTokenStore extends Disposable implements ICopilotTokenStore private _copilotToken: CopilotToken | undefined; private readonly _onDidStoreUpdate = this._register(new Emitter()); onDidStoreUpdate: Event = this._onDidStoreUpdate.event; + private readonly _onDidChangeTokenData = this._register(new Emitter()); + readonly onDidChangeTokenData = this._onDidChangeTokenData.event; private _githubEnterpriseUri: URI | undefined; private readonly _onDidChangeGitHubEnterpriseUri = this._register(new Emitter()); readonly onDidChangeGitHubEnterpriseUri = this._onDidChangeGitHubEnterpriseUri.event; + private _authenticationState: ICopilotTokenStore['authenticationState'] = 'unknown'; + private readonly _onDidChangeAuthenticationState = this._register(new Emitter()); + readonly onDidChangeAuthenticationState = this._onDidChangeAuthenticationState.event; + + get authenticationState(): ICopilotTokenStore['authenticationState'] { + return this._authenticationState; + } + set authenticationState(state: ICopilotTokenStore['authenticationState']) { + if (state !== this._authenticationState) { + this._authenticationState = state; + this._onDidChangeAuthenticationState.fire(); + } + } get githubEnterpriseUri(): URI | undefined { return this._githubEnterpriseUri; @@ -48,9 +68,12 @@ export class CopilotTokenStore extends Disposable implements ICopilotTokenStore return this._copilotToken; } set copilotToken(token: CopilotToken | undefined) { - const oldToken = this._copilotToken?.token; + const oldToken = this._copilotToken; this._copilotToken = token; - if (oldToken !== token?.token) { + if (oldToken !== token) { + this._onDidChangeTokenData.fire(); + } + if (oldToken?.token !== token?.token) { this._onDidStoreUpdate.fire(); } } diff --git a/extensions/copilot/src/platform/authentication/common/staticGitHubAuthenticationService.ts b/extensions/copilot/src/platform/authentication/common/staticGitHubAuthenticationService.ts index 62e2d1e7beaf..a8ae8818cc42 100644 --- a/extensions/copilot/src/platform/authentication/common/staticGitHubAuthenticationService.ts +++ b/extensions/copilot/src/platform/authentication/common/staticGitHubAuthenticationService.ts @@ -20,6 +20,7 @@ export class StaticGitHubAuthenticationService extends BaseAuthenticationService @IConfigurationService configurationService: IConfigurationService ) { super(logService, tokenStore, tokenManager, configurationService); + tokenStore.authenticationState = 'signedIn'; const that = this; this._anyGitHubSession = tokenProvider ? { diff --git a/extensions/copilot/src/platform/authentication/test/node/copilotTokenStore.spec.ts b/extensions/copilot/src/platform/authentication/test/node/copilotTokenStore.spec.ts index 1be3af540ae0..6023e6ebd38b 100644 --- a/extensions/copilot/src/platform/authentication/test/node/copilotTokenStore.spec.ts +++ b/extensions/copilot/src/platform/authentication/test/node/copilotTokenStore.spec.ts @@ -34,4 +34,23 @@ describe('CopilotTokenStore', () => { token: 'copilot-test', }); }); + + test('publishes metadata replacements separately from bearer token changes', () => { + const store = disposables.add(new CopilotTokenStore()); + const endpoints: (string | undefined)[] = []; + const bearerTokens: (string | undefined)[] = []; + disposables.add(store.onDidChangeTokenData(() => endpoints.push(store.copilotToken?.endpoints?.exp))); + disposables.add(store.onDidStoreUpdate(() => bearerTokens.push(store.copilotToken?.token))); + const info = createTestExtendedTokenInfo({ token: 'unchanged-token', endpoints: undefined }); + store.copilotToken = new CopilotToken(info); + store.copilotToken = new CopilotToken({ ...info, endpoints: { exp: 'https://exp.enterprise.githubcopilot.com' } }); + store.copilotToken = store.copilotToken; + store.copilotToken = new CopilotToken({ ...info, token: 'rotated-token' }); + store.copilotToken = undefined; + store.copilotToken = undefined; + expect({ endpoints, bearerTokens }).toEqual({ + endpoints: [undefined, 'https://exp.enterprise.githubcopilot.com', undefined, undefined], + bearerTokens: ['unchanged-token', 'rotated-token', undefined], + }); + }); }); diff --git a/extensions/copilot/src/platform/authentication/test/node/session.spec.ts b/extensions/copilot/src/platform/authentication/test/node/session.spec.ts index 9d76fbde0369..76d87ece8997 100644 --- a/extensions/copilot/src/platform/authentication/test/node/session.spec.ts +++ b/extensions/copilot/src/platform/authentication/test/node/session.spec.ts @@ -24,8 +24,11 @@ import { GITHUB_SCOPE_ALIGNED, GITHUB_SCOPE_READ_USER, GITHUB_SCOPE_USER_EMAIL } import { CopilotToken, createTestExtendedTokenInfo } from '../../common/copilotToken'; import { ICopilotTokenManager } from '../../common/copilotTokenManager'; import { CopilotTokenStore } from '../../common/copilotTokenStore'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { AuthenticationService } from '../../vscode-node/authenticationService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { VSCodeCopilotTokenManager } from '../../vscode-node/copilotTokenManager'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { getAlignedSession, getAnyAuthSession } from '../../vscode-node/session'; const vscodeAuthentication = vi.hoisted(() => ({ @@ -144,6 +147,25 @@ describe('Copilot session provenance', () => { return disposables.add(new VSCodeCopilotTokenManager(log, new NullTelemetryService(), domains, capi, fetcher, new NullEnvService(), configuration, tokenStore)); } + test('keeps auth unresolved until session discovery completes and publishes confirmed sign-out', async () => { + const discovered = new DeferredPromise(); + vscodeAuthentication.getAccounts.mockImplementation(async () => { + await discovered.p; + return api.sessions.map(session => session.account); + }); + const states: typeof tokenStore.authenticationState[] = [tokenStore.authenticationState]; + disposables.add(tokenStore.onDidChangeAuthenticationState(() => states.push(tokenStore.authenticationState))); + const service = createService(); + const ready = service.refreshAuthentication(); + expect(tokenStore.authenticationState).toBe('unknown'); + await discovered.complete(); + await ready; + api.selected = undefined; + api.sessions.length = 0; + await service.refreshAuthentication(); + expect(states).toEqual(['unknown', 'signedIn', 'unknown', 'signedOut']); + }); + test('ordinary sign-in carries the returned issuer without guessing a host', async () => { api.selected = undefined; const selected = await getAnyAuthSession(configuration, { createIfNone: { detail: 'test sign in' } }); diff --git a/extensions/copilot/src/platform/authentication/vscode-node/authenticationService.ts b/extensions/copilot/src/platform/authentication/vscode-node/authenticationService.ts index a8db8d32d913..672cc76eac96 100644 --- a/extensions/copilot/src/platform/authentication/vscode-node/authenticationService.ts +++ b/extensions/copilot/src/platform/authentication/vscode-node/authenticationService.ts @@ -32,6 +32,7 @@ export class AuthenticationService extends BaseAuthenticationService { } })); this._register(runOnChange(configurationService.getConfigObservable(ConfigKey.Shared.AuthProvider), () => { + this._tokenStore.authenticationState = 'unknown'; this._anyGitHubSession = undefined; this._permissiveGitHubSession = undefined; this.resetCopilotToken(); @@ -61,11 +62,13 @@ export class AuthenticationService extends BaseAuthenticationService { const previous = this._anyGitHubSession; this._anyGitHubSession = session; if (!authenticationSessionIdentityEquals(previous, session)) { + this._tokenStore.authenticationState = 'unknown'; this.resetCopilotToken(); } this._tokenStore.githubEnterpriseUri = session && providerId === AuthProviderId.GitHubEnterprise ? resolveGitHubSessionUri(session, providerId) : undefined; + this._tokenStore.authenticationState = session ? 'signedIn' : 'signedOut'; } return session; }; diff --git a/extensions/copilot/src/platform/endpoint/node/chatEndpoint.ts b/extensions/copilot/src/platform/endpoint/node/chatEndpoint.ts index f92e8a8d17e8..bba25e15e26d 100644 --- a/extensions/copilot/src/platform/endpoint/node/chatEndpoint.ts +++ b/extensions/copilot/src/platform/endpoint/node/chatEndpoint.ts @@ -33,6 +33,7 @@ import { ICAPIClientService } from '../common/capiClient'; import { getModelCapabilityOverride, isAnthropicFamily, isGeminiFamily, isKimiFamily, isKimiK3PlusFamily, modelSupportsContextEditing, modelSupportsThinkingContentInHistory, modelSupportsToolSearch } from '../common/chatModelCapabilities'; import { IDomainService } from '../common/domainService'; import { CustomModel, IChatModelInformation, ModelSupportedEndpoint } from '../common/endpointProvider'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { normalizeTokenPrices } from '../../../extension/conversation/common/languageModelAccess'; import { createMessagesRequestBody, processResponseFromMessagesEndpoint } from './messagesApi'; import { createResponsesRequestBody, getResponsesApiCompactionThreshold, processResponseFromChatEndpoint } from './responsesApi'; diff --git a/extensions/copilot/src/platform/endpoint/test/node/testEndpointProvider.ts b/extensions/copilot/src/platform/endpoint/test/node/testEndpointProvider.ts index e5dd2bf24392..e9680f9197ef 100644 --- a/extensions/copilot/src/platform/endpoint/test/node/testEndpointProvider.ts +++ b/extensions/copilot/src/platform/endpoint/test/node/testEndpointProvider.ts @@ -4,8 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import type { ChatRequest, LanguageModelChat } from 'vscode'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { CacheableRequest, SQLiteCache } from '../../../../../test/base/cache'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { TestingCacheSalts } from '../../../../../test/base/salts'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { CurrentTestRunInfo } from '../../../../../test/base/simulationContext'; import { TokenizerType } from '../../../../util/common/tokenizer'; import { SequencerByKey } from '../../../../util/vs/base/common/async'; diff --git a/extensions/copilot/src/platform/git/common/gitCommitMessageService.ts b/extensions/copilot/src/platform/git/common/gitCommitMessageService.ts index 155402a67647..32710d7db727 100644 --- a/extensions/copilot/src/platform/git/common/gitCommitMessageService.ts +++ b/extensions/copilot/src/platform/git/common/gitCommitMessageService.ts @@ -5,6 +5,7 @@ import type { CancellationToken, Uri } from 'vscode'; import { createServiceIdentifier } from '../../../util/common/services'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Repository } from '../vscode/git'; export const IGitCommitMessageService = createServiceIdentifier('IGitCommitMessageService'); diff --git a/extensions/copilot/src/platform/git/common/gitDiffService.ts b/extensions/copilot/src/platform/git/common/gitDiffService.ts index b162e7c837e6..ef2b96390ced 100644 --- a/extensions/copilot/src/platform/git/common/gitDiffService.ts +++ b/extensions/copilot/src/platform/git/common/gitDiffService.ts @@ -5,6 +5,7 @@ import type { CancellationToken, Uri } from 'vscode'; import { createServiceIdentifier } from '../../../util/common/services'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change, Repository } from '../vscode/git'; export const IGitDiffService = createServiceIdentifier('IGitDiffService'); diff --git a/extensions/copilot/src/platform/git/common/gitExtensionService.ts b/extensions/copilot/src/platform/git/common/gitExtensionService.ts index 5a1d658a8095..cd2edf80e714 100644 --- a/extensions/copilot/src/platform/git/common/gitExtensionService.ts +++ b/extensions/copilot/src/platform/git/common/gitExtensionService.ts @@ -5,6 +5,7 @@ import type * as vscode from 'vscode'; import { createServiceIdentifier } from '../../../util/common/services'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { API } from '../vscode/git'; export const IGitExtensionService = createServiceIdentifier('IGitExtensionService'); diff --git a/extensions/copilot/src/platform/git/common/gitService.ts b/extensions/copilot/src/platform/git/common/gitService.ts index bcdb99d2d24c..f3a067fe70ea 100644 --- a/extensions/copilot/src/platform/git/common/gitService.ts +++ b/extensions/copilot/src/platform/git/common/gitService.ts @@ -10,6 +10,7 @@ import { Event } from '../../../util/vs/base/common/event'; import { IObservable } from '../../../util/vs/base/common/observableInternal'; import { equalsIgnoreCase } from '../../../util/vs/base/common/strings'; import { URI } from '../../../util/vs/base/common/uri'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Branch, Change, CommitOptions, CommitShortStat, DiffChange, Ref, RefQuery, Repository, RepositoryAccessDetails, RepositoryKind, Worktree } from '../vscode/git'; export interface RepoContext { diff --git a/extensions/copilot/src/platform/git/common/nullGitDiffService.ts b/extensions/copilot/src/platform/git/common/nullGitDiffService.ts index 22ceb8654e94..0cd034359f06 100644 --- a/extensions/copilot/src/platform/git/common/nullGitDiffService.ts +++ b/extensions/copilot/src/platform/git/common/nullGitDiffService.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import type { CancellationToken, Uri } from 'vscode'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change, Repository } from '../vscode/git'; import { Diff, IGitDiffService } from './gitDiffService'; diff --git a/extensions/copilot/src/platform/git/common/utils.ts b/extensions/copilot/src/platform/git/common/utils.ts index 809ae9b4e7f2..cf5ce4322206 100644 --- a/extensions/copilot/src/platform/git/common/utils.ts +++ b/extensions/copilot/src/platform/git/common/utils.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import type * as vscode from 'vscode'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Remote, Repository } from '../vscode/git'; interface GitConfigSection { diff --git a/extensions/copilot/src/platform/ignore/node/test/mockGitService.ts b/extensions/copilot/src/platform/ignore/node/test/mockGitService.ts index c076166b6a28..2ca77fd738f8 100644 --- a/extensions/copilot/src/platform/ignore/node/test/mockGitService.ts +++ b/extensions/copilot/src/platform/ignore/node/test/mockGitService.ts @@ -10,6 +10,7 @@ import { IObservable } from '../../../../util/vs/base/common/observableInternal' import { observableValue } from '../../../../util/vs/base/common/observableInternal/observables/observableValue'; import { URI } from '../../../../util/vs/base/common/uri'; import { IGitService, RepoContext } from '../../../git/common/gitService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Branch, Change, Commit, CommitOptions, CommitShortStat, DiffChange, LogOptions, Ref, RefQuery, Repository, RepositoryAccessDetails } from '../../../git/vscode/git'; /** diff --git a/extensions/copilot/src/platform/inlineEdits/common/observableGit.ts b/extensions/copilot/src/platform/inlineEdits/common/observableGit.ts index a4fc2406ab18..f5d2c1dcc883 100644 --- a/extensions/copilot/src/platform/inlineEdits/common/observableGit.ts +++ b/extensions/copilot/src/platform/inlineEdits/common/observableGit.ts @@ -6,6 +6,7 @@ import { Disposable } from '../../../util/vs/base/common/lifecycle'; import { autorunWithStore, IObservable, ISettableObservable, mapObservableArrayCached, observableFromEvent, observableValue, waitForState } from '../../../util/vs/base/common/observable'; import { IGitExtensionService } from '../../git/common/gitExtensionService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { API } from '../../git/vscode/git'; export class ObservableGit extends Disposable { diff --git a/extensions/copilot/src/platform/inlineEdits/common/sensitiveFiles.ts b/extensions/copilot/src/platform/inlineEdits/common/sensitiveFiles.ts new file mode 100644 index 000000000000..276371355ef2 --- /dev/null +++ b/extensions/copilot/src/platform/inlineEdits/common/sensitiveFiles.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { posix } from '../../../util/vs/base/common/path'; +import { DocumentId } from './dataTypes/documentId'; + +const sensitiveFileNames = new Set([ + '.env', + 'mcp.json', + '.npmrc', + '.pypirc', + '.netrc', + '_netrc', + '.git-credentials', + '.pgpass', + 'id_rsa', + 'id_dsa', + 'id_ecdsa', + 'id_ed25519', +]); + +const sensitiveFileExtensions = new Set(['.pem', '.key', '.p12', '.pfx']); + +/** + * Whether the document is a file that commonly holds secrets, such as tokens, passwords or private keys. + */ +export function isSensitiveFile(docId: DocumentId): boolean { + const name = posix.basename(docId.path).toLowerCase(); + return sensitiveFileNames.has(name) || name.startsWith('.env.') || sensitiveFileExtensions.has(posix.extname(name)); +} + +/** + * Whether the content of `docId` may be sent in a request made for `activeDocId`. Files that commonly + * hold secrets are still served, but their content is only ever sent in requests for themselves. + */ +export function canUseAsContext(docId: DocumentId, activeDocId: DocumentId): boolean { + return docId === activeDocId || !isSensitiveFile(docId); +} + +/** + * Leaves out entries of documents other than `activeDocId` that commonly hold secrets, see {@link canUseAsContext}. + * Apply it whenever a request is built for an active document, including follow-up requests for another document. + */ +export function withoutOtherSensitiveFiles(entries: readonly T[], activeDocId: DocumentId): T[] { + return entries.filter(e => canUseAsContext(e.docId, activeDocId)); +} diff --git a/extensions/copilot/src/platform/networking/vscode-node/test/nodeFetchFetcherCache.test.ts b/extensions/copilot/src/platform/networking/vscode-node/test/nodeFetchFetcherCache.test.ts index 140a60f52bbb..b6ad6b6acb9d 100644 --- a/extensions/copilot/src/platform/networking/vscode-node/test/nodeFetchFetcherCache.test.ts +++ b/extensions/copilot/src/platform/networking/vscode-node/test/nodeFetchFetcherCache.test.ts @@ -6,6 +6,7 @@ import * as assert from 'assert'; import * as http from 'http'; import { IFetcherService } from '../../common/fetcherService'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { createExtensionTestingServices } from '../../../../extension/test/vscode-node/services'; import { ITestingServicesAccessor } from '../../../test/node/services'; diff --git a/extensions/copilot/src/platform/promptFiles/node/automaticInstructionsCollector.ts b/extensions/copilot/src/platform/promptFiles/node/automaticInstructionsCollector.ts index 768ab811be89..a04960c3a5ae 100644 --- a/extensions/copilot/src/platform/promptFiles/node/automaticInstructionsCollector.ts +++ b/extensions/copilot/src/platform/promptFiles/node/automaticInstructionsCollector.ts @@ -26,13 +26,17 @@ import { escape as escapeXml } from '../../../util/vs/base/common/strings'; import { URI } from '../../../util/vs/base/common/uri'; import { ParsedPromptFile } from '../../../util/vs/workbench/contrib/chat/common/promptSyntax/promptFileParser'; import { isLocation } from '../../../util/common/types'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { getToolName, ToolName } from '../../../extension/tools/common/toolNames'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { isCustomizationsIndex, isInstructionFile, toCustomizationsIndexReference, toInstructionFileReference } from '../../../extension/prompt/common/chatVariablesCollection'; +// eslint-disable-next-line local/code-layering, local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { getToolReferencePromptContent } from '../../../extension/prompt/vscode-node/promptVariablesService'; import { IExperimentationService } from '../../telemetry/common/nullExperimentationService'; import { getChatSessionType, matchesSessionType } from '../../chat/common/sessionUtils'; import { CopilotChatAttr, GenAiAttr, GenAiOperationName, IOTelService } from '../../otel/common'; import { ICustomInstructionsService } from '../../customInstructions/common/customInstructionsService'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { IPromptVariablesService } from '../../../extension/prompt/node/promptVariablesService'; import { arrayEqual } from 'diff/lib/util/array.js'; import { structuralEquals } from '../../../util/vs/base/common/equals'; diff --git a/extensions/copilot/src/platform/promptFiles/test/node/agentInstructionsLocator.spec.ts b/extensions/copilot/src/platform/promptFiles/test/node/agentInstructionsLocator.spec.ts index 9d75be170c86..5ac58296b0f2 100644 --- a/extensions/copilot/src/platform/promptFiles/test/node/agentInstructionsLocator.spec.ts +++ b/extensions/copilot/src/platform/promptFiles/test/node/agentInstructionsLocator.spec.ts @@ -20,6 +20,7 @@ import { SnapshotSearchService } from '../../../test/node/simulationWorkspaceSer import { TestWorkspaceService } from '../../../test/node/testWorkspaceService'; import { IWorkspaceService } from '../../../workspace/common/workspaceService'; import { INativeEnvService } from '../../../env/common/envService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { AgentInstructionsLocator } from '../../vscode-node/agentInstructionsLocator'; import { mockFiles } from './mockFiles'; import { AgentInstructionFileType, PromptConfig } from '../../common/promptsService'; diff --git a/extensions/copilot/src/platform/promptFiles/test/node/automaticInstructionsCollector.spec.ts b/extensions/copilot/src/platform/promptFiles/test/node/automaticInstructionsCollector.spec.ts index d020a0455129..f1eec8df981a 100644 --- a/extensions/copilot/src/platform/promptFiles/test/node/automaticInstructionsCollector.spec.ts +++ b/extensions/copilot/src/platform/promptFiles/test/node/automaticInstructionsCollector.spec.ts @@ -21,7 +21,9 @@ import { CancellationToken } from '../../../../util/vs/base/common/cancellation' import { Event } from '../../../../util/vs/base/common/event'; import { URI } from '../../../../util/vs/base/common/uri'; import { AutomaticInstructionsCollector, InstructionsCollectionEvent } from '../../node/automaticInstructionsCollector'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { InstructionFileIdPrefix, isCustomizationsIndex, isInstructionFile } from '../../../../extension/prompt/common/chatVariablesCollection'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { ToolName } from '../../../../extension/tools/common/toolNames'; import { NullExperimentationService } from '../../../telemetry/common/nullExperimentationService'; import { NullNativeEnvService } from '../../../env/common/nullEnvService'; diff --git a/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchClient.ts b/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchClient.ts deleted file mode 100644 index aef04b993241..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchClient.ts +++ /dev/null @@ -1,131 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import type { CancellationToken } from 'vscode'; -import { createServiceIdentifier } from '../../../util/common/services'; -import { CodeOrDocsSearchRepoError } from './codeOrDocsSearchErrors'; - -/** - * Represents the base scoping query for code or docs search. A scoping query is used to provide what exactly you want to search through. - */ -export interface ICodeOrDocsSearchBaseScopingQuery { - /** - * The repo(s) to search in. When only one is specified, any errors are thrown. If multiple repos are specified, - * then they are returned in the response. - */ - repo: string | string[]; - - /** - * The language to search for. If not provided, all languages will be searched. - */ - lang?: string[]; - - /** - * The language to exclude from the search. If not provided, no languages will be excluded. - */ - notLang?: string[]; - - /** - * The path to search for. If not provided, all paths will be searched. - */ - path?: string[]; - - /** - * The path to exclude from the search. If not provided, no paths will be excluded. - */ - notPath?: string[]; -} - -/** - * Represents a scoping query for code or docs search with only 1 repo. A scoping query is used to provide what exactly you want to search through. - */ -export interface ICodeOrDocsSearchSingleRepoScopingQuery extends ICodeOrDocsSearchBaseScopingQuery { - repo: string; -} - -/** - * Represents a scoping query for code or docs search with multiple repos. A scoping query is used to provide what exactly you want to search through. - */ -export interface ICodeOrDocsSearchMultiRepoScopingQuery extends ICodeOrDocsSearchBaseScopingQuery { - repo: string[]; -} - -/** - * What one of the results looks like that is returned by codesearch or docssearch. - */ -export interface ICodeOrDocsSearchItem { - path: string; - contents: string; - title?: string; - score: number; - repoName: string; - repoOwner: string; - range: { start: number; end: number }; - languageId: string; - languageName: string; - type: 'snippet' | string; - url: string; - ref: string; - commitOID?: string; - algorithm?: 'semantic' | 'bm25'; -} - -/** - * The result of a code or docs search. - */ -export interface ICodeOrDocsSearchResult { - results: ICodeOrDocsSearchItem[]; - errors: CodeOrDocsSearchRepoError[]; -} - -export interface ICodeOrDocsSearchOptions { - /** - * The number of results to return. Default is 6. - */ - limit?: number; - - /** - * How similar you want results to be. - */ - similarity?: number; -} - -/** - * The interface for the docs search client. - */ -export interface IDocsSearchClient { - readonly _serviceBrand: undefined; - - /** - * Search for related chunks using GitHub's search APIs - * @note When only a single repo is specified, we return the results as an array and also throw errors. - * @param query The search query - * @param scopingQuery A scoping query with a single repo specified. - * @param options The search options - */ - search( - query: string, - scopingQuery: ICodeOrDocsSearchSingleRepoScopingQuery, - options?: ICodeOrDocsSearchOptions, - cancellationToken?: CancellationToken - ): Promise; - - /** - * Search for related chunks using GitHub's search APIs - * @note When multiple repos are specified, we return the results and errors together. You are responsible for handling errors how you would like. - * @param query The search query - * @param scopingQuery A scoping query with multiple repos specified. - * @param options The search options - */ - search( - query: string, - scopingQuery: ICodeOrDocsSearchMultiRepoScopingQuery, - options?: ICodeOrDocsSearchOptions, - cancellationToken?: CancellationToken - ): Promise; -} - - -export const IDocsSearchClient = createServiceIdentifier('docsSearchClient'); diff --git a/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchErrors.ts b/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchErrors.ts deleted file mode 100644 index 60570dc1b2d7..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/common/codeOrDocsSearchErrors.ts +++ /dev/null @@ -1,84 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -export const enum SearchRepoErrorType { - missingInaccessibleRepoOrg = 'ERROR_TYPE_MISSING_INACCESSIBLE_REPO_ORG', - docsEmbeddingsUnavailable = 'ERROR_TYPE_DOCS_EMBEDDINGS_UNAVAILABLE', - notIndexed = 'ERROR_TYPE_NOT_INDEXED', -} - -export const enum SearchErrorType { - maxRetriesExceeded = 'ERROR_TYPE_MAX_RETRIES_EXCEEDED', - noAccessToEndpoint = 'ERROR_TYPE_NO_ACCESS_TO_ENDPOINT', -} - -export class CodeOrDocsSearchRepoError extends Error { - constructor(readonly repo: string, message?: string) { - super(message); - } -} - -/** - * This error is thrown when the repository is not accessible to the user. This might be because the user - * does not have access to the repository or the token does not have the OAuth scope (repo) to access the repository. - */ -export class InaccessibleRepoOrgError extends CodeOrDocsSearchRepoError { - override name = SearchRepoErrorType.missingInaccessibleRepoOrg; -} - -/** - * This error is thrown when the docs embeddings are not available for the given repository. - * NOTE: For our usecases, this is basically the same thing as NotIndexedError. - */ -export class EmbeddingsUnavailableError extends CodeOrDocsSearchRepoError { - override name = SearchRepoErrorType.docsEmbeddingsUnavailable; -} - -/** - * This error is thrown when the repository is not indexed entirely including when the embeddings are not available. - * NOTE: For our usecases, this is basically the same thing as EmbeddingsUnavailableError. - */ -export class NotIndexedError extends CodeOrDocsSearchRepoError { - override name = SearchRepoErrorType.notIndexed; -} - -/** - * This error is not thrown by the endpoint but is thrown by the client when the max retries are exceeded. - */ -export class MaxRetriesExceededError extends Error { - override name = SearchErrorType.maxRetriesExceeded; -} - -/** - * This error is not thrown by the endpoint but is thrown by the client when the code or docs search endpoint is not accessible. - * This is usually because of a feature flag that is not enabled for this user. - */ -export class NoAccessToEndpointError extends Error { - override name = SearchErrorType.noAccessToEndpoint; -} - -export function constructSearchRepoError({ error, message, repo }: { error: string; message: string; repo: string }): CodeOrDocsSearchRepoError { - switch (error) { - case SearchRepoErrorType.missingInaccessibleRepoOrg: - return new InaccessibleRepoOrgError(repo, message); - case SearchRepoErrorType.docsEmbeddingsUnavailable: - return new EmbeddingsUnavailableError(repo, message); - case SearchRepoErrorType.notIndexed: - return new NotIndexedError(repo, message); - default: - return new CodeOrDocsSearchRepoError(repo, message); - } -} - -export function constructSearchError({ error, message }: { error: string; message: string }): Error { - switch (error) { - case SearchErrorType.maxRetriesExceeded: - return new MaxRetriesExceededError(message); - case SearchErrorType.noAccessToEndpoint: - return new NoAccessToEndpointError(message); - default: - return new Error(message); - } -} diff --git a/extensions/copilot/src/platform/remoteSearch/common/utils.ts b/extensions/copilot/src/platform/remoteSearch/common/utils.ts deleted file mode 100644 index 93d3c2e8ab1c..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/common/utils.ts +++ /dev/null @@ -1,26 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { ICodeOrDocsSearchBaseScopingQuery } from './codeOrDocsSearchClient'; - -export function formatScopingQuery(query: ICodeOrDocsSearchBaseScopingQuery) { - const repo: string[] = Array.isArray(query.repo) ? query.repo : [query.repo]; - const parts: string[] = [ - `(repo:${repo.join(' OR repo:')})` - ]; - if (query.lang) { - parts.push(`(lang:${query.lang.join(' OR lang:')})`); - } - if (query.notLang) { - parts.push(`NOT (lang:${query.notLang.join(' OR lang:')})`); - } - if (query.path) { - parts.push(`(path:${query.path.join(' OR path:')})`); - } - if (query.notPath) { - parts.push(`NOT (path:${query.notPath.join(' OR path:')})`); - } - return parts.join(' '); -} diff --git a/extensions/copilot/src/platform/remoteSearch/node/codeOrDocsSearchClientImpl.ts b/extensions/copilot/src/platform/remoteSearch/node/codeOrDocsSearchClientImpl.ts deleted file mode 100644 index 4321bdc1ef6c..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/node/codeOrDocsSearchClientImpl.ts +++ /dev/null @@ -1,228 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import { RequestMetadata, RequestType } from '@vscode/copilot-api'; -import { TokenizerType } from '../../../util/common/tokenizer'; -import { CancellationToken } from '../../../util/vs/base/common/cancellation'; -import { CancellationError, isCancellationError } from '../../../util/vs/base/common/errors'; -import { generateUuid } from '../../../util/vs/base/common/uuid'; -import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation'; -import { IAuthenticationService } from '../../authentication/common/authentication'; -import { LogExecTime } from '../../log/common/logExecTime'; -import { ILogService } from '../../log/common/logService'; -import { IEndpoint, postRequest } from '../../networking/common/networking'; -import { ITelemetryService } from '../../telemetry/common/telemetry'; -import { ICodeOrDocsSearchBaseScopingQuery, ICodeOrDocsSearchItem, ICodeOrDocsSearchMultiRepoScopingQuery, ICodeOrDocsSearchOptions, ICodeOrDocsSearchResult, ICodeOrDocsSearchSingleRepoScopingQuery, IDocsSearchClient } from '../common/codeOrDocsSearchClient'; -import { SearchErrorType, constructSearchError, constructSearchRepoError } from '../common/codeOrDocsSearchErrors'; -import { formatScopingQuery } from '../common/utils'; - -/** - * What an error looks like that is returned by docssearch. - */ -interface IDocsSearchError { - message: string; - error: string; - repo: string; -} - -/** - * What the response looks like that is returned by docssearch. - */ -interface IDocsSearchResponse { - results: ICodeOrDocsSearchItem[]; - errors?: IDocsSearchError[]; -} - -class UnknownHttpError extends Error { - constructor( - readonly status: number, - message: string - ) { - super(message); - } -} - -const DEFAULT_LIMIT = 6; -const MAX_LIMIT = 100; -const DEFAULT_SIMILARITY = 0.766; - -export class DocsSearchClient implements IDocsSearchClient { - declare readonly _serviceBrand: undefined; - - private readonly slug = 'docs'; - - constructor( - @ITelemetryService private readonly _telemetryService: ITelemetryService, - @IAuthenticationService private readonly _authenticationService: IAuthenticationService, - @ILogService private readonly _logService: ILogService, - @IInstantiationService private readonly _instantiationService: IInstantiationService, - ) { } - - search(query: string, scopingQuery: ICodeOrDocsSearchSingleRepoScopingQuery, options?: ICodeOrDocsSearchOptions, token?: CancellationToken): Promise; - search(query: string, scopingQuery: ICodeOrDocsSearchMultiRepoScopingQuery, options?: ICodeOrDocsSearchOptions, token?: CancellationToken): Promise; - @LogExecTime(self => self._logService, 'CodeOrDocsSearchClientImpl::search') - async search( - query: string, - scopingQuery: ICodeOrDocsSearchSingleRepoScopingQuery | ICodeOrDocsSearchMultiRepoScopingQuery, - options: ICodeOrDocsSearchOptions = {}, - token?: CancellationToken, - ): Promise { - // Code search requires at least one repo specified - if (Array.isArray(scopingQuery.repo) && !scopingQuery.repo.length) { - throw new Error('No repos specified'); - } - - let result: IDocsSearchResponse; - try { - result = await this.postRequestWithRetry(query, scopingQuery, options, token ?? CancellationToken.None); - } catch (error) { - if (!isCancellationError(error)) { - this._telemetryService.sendGHTelemetryException(error, `${this.slug} search failed`); - } - throw error; - } - const errors = result.errors?.map(constructSearchRepoError) ?? []; - // If we're in single repo mode, we will throw errors. If not, we're return a similar shape - if (!Array.isArray(scopingQuery.repo)) { - if (errors.length) { - // TODO: Can this happen? - if (errors.length > 1) { - throw new AggregateError(errors); - } else { - throw errors[0]; - } - } - return result.results; - } - - // Multi-repo - return { - results: result.results, - errors - }; - } - - private async postRequestWithRetry( - query: string, - scopingQuery: ICodeOrDocsSearchBaseScopingQuery, - options: ICodeOrDocsSearchOptions, - token: CancellationToken - ): Promise { - const authToken = (await this._authenticationService.getGitHubSession('permissive', { silent: true }))?.accessToken ?? (await this._authenticationService.getGitHubSession('any', { silent: true }))?.accessToken; - if (token.isCancellationRequested) { - throw new CancellationError(); - } - - const MAX_RETRIES = 3; - let retryCount = 0; - - const errorMessages = new Set; - let error: Error | undefined; - while (retryCount < MAX_RETRIES) { - if (token.isCancellationRequested) { - throw new CancellationError(); - } - - try { - try { - const result = await this.postCodeOrDocsSearchRequest({ type: RequestType.SearchSkill, slug: this.slug }, authToken!, query, scopingQuery, options, token); - return result; - } catch (e) { - if (e instanceof UnknownHttpError) { - throw e; - } - error = e; - break; - } - } catch (error: any) { - retryCount++; - const waitTime = 100; - errorMessages.add(`Error fetching ${this.slug} search. ${error.message ?? error}`); - this._logService.warn(`[repo:${scopingQuery.repo}] Error fetching ${this.slug} search. Error: ${error.message ?? error}. Retrying in ${retryCount}ms. Query: ${query}`); - await new Promise(resolve => setTimeout(resolve, waitTime)); - } - } - - if (token.isCancellationRequested) { - throw new CancellationError(); - } - - if (retryCount >= MAX_RETRIES) { - this._logService.warn(`[repo:${scopingQuery.repo}] Max Retry Error thrown while querying '${query}'`); - error = constructSearchError({ - error: SearchErrorType.maxRetriesExceeded, - message: `${this.slug} search timed out after ${MAX_RETRIES} retries. ${Array.from(errorMessages).join('\n')}` - }); - } - - throw error; - } - - private async postCodeOrDocsSearchRequest( - requestMetadata: RequestMetadata, - authToken: string, - query: string, - scopingQuery: ICodeOrDocsSearchBaseScopingQuery, - options: ICodeOrDocsSearchOptions, - cancellationToken?: CancellationToken - ) { - const limit = Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT); - const similarity = options.similarity ?? DEFAULT_SIMILARITY; - const endpointInfo: IEndpoint = { - urlOrRequestMetadata: requestMetadata, - tokenizer: TokenizerType.O200K, - acquireTokenizer() { - throw new Error('Method not implemented.'); - }, - family: 'Code Or Doc Search', - name: 'Code Or Doc Search', - version: '2023-12-12-preview', - modelMaxPromptTokens: 0, - getExtraHeaders() { - const headers: Record = { - // needed for errors to be in the right format - // TODO: should this be the default of postRequest? - Accept: 'application/json', - 'X-GitHub-Api-Version': '2023-12-12-preview', - }; - return headers; - }, - }; - const response = await this._instantiationService.invokeFunction(postRequest, { - endpointOrUrl: endpointInfo, - secretKey: authToken ?? '', - intent: 'codesearch', - requestId: generateUuid(), - body: { - query, - scopingQuery: formatScopingQuery(scopingQuery), - similarity, - limit - }, - cancelToken: cancellationToken, - }); - - const text = await response.text(); - if (response.status === 404 || (response.status === 400 && text.includes('unknown integration'))) { - // If the endpoint is not available for this user it will return 404. - this._logService.debug(`${this.slug} search endpoint not available for this user.`); - const error = constructSearchError({ - error: SearchErrorType.noAccessToEndpoint, - message: `${this.slug}: ${text}` - }); - throw error; - } - - let result: IDocsSearchResponse; - try { - // handle 500s specifically (like blackbird queries) - result = JSON.parse(text); - } catch (e) { - // try again in the 500 case - throw new UnknownHttpError(response.status, text); - } - - return result; - } -} diff --git a/extensions/copilot/src/platform/remoteSearch/test/node/codeOrDocsSearchErrors.spec.ts b/extensions/copilot/src/platform/remoteSearch/test/node/codeOrDocsSearchErrors.spec.ts deleted file mode 100644 index d79e340e4988..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/test/node/codeOrDocsSearchErrors.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -import * as assert from 'assert'; -import { suite, test } from 'vitest'; -import { - CodeOrDocsSearchRepoError, - EmbeddingsUnavailableError, - InaccessibleRepoOrgError, - MaxRetriesExceededError, - NoAccessToEndpointError, - NotIndexedError, - SearchErrorType, - SearchRepoErrorType, - constructSearchError, - constructSearchRepoError -} from '../../common/codeOrDocsSearchErrors'; - -suite('Search Client Errors', () => { - test('should return an instance of InaccessibleRepoOrgError when error is missingInaccessibleRepoOrg', () => { - const error = constructSearchRepoError({ - error: SearchRepoErrorType.missingInaccessibleRepoOrg, - message: 'Error message', - repo: 'microsoft/vscode' - }); - assert.ok(error instanceof InaccessibleRepoOrgError); - }); - - test('should return an instance of EmbeddingsUnavailableError when error is docsEmbeddingsUnavailable', () => { - const error = constructSearchRepoError({ - error: SearchRepoErrorType.docsEmbeddingsUnavailable, - message: 'Error message', - repo: 'microsoft/vscode' - }); - assert.ok(error instanceof EmbeddingsUnavailableError); - }); - - test('should return an instance of NotIndexedError when error is notIndexed', () => { - const error = constructSearchRepoError({ - error: SearchRepoErrorType.notIndexed, - message: 'Error message', - repo: 'microsoft/vscode' - }); - assert.ok(error instanceof NotIndexedError); - }); - - test('should return an instance of CodeOrDocsSearchRepoError when error is unknown', () => { - const error = constructSearchRepoError({ - error: 'unknownERror', - message: 'Error message', - repo: 'microsoft/vscode' - }); - assert.ok(error instanceof CodeOrDocsSearchRepoError); - }); - - test('should return an instance of MaxRetriesExceededError when error is maxRetriesExceeded', () => { - const error = constructSearchError({ - error: SearchErrorType.maxRetriesExceeded, - message: 'Error message', - }); - assert.ok(error instanceof MaxRetriesExceededError); - }); - - test('should return an instance of NoAccessToEndpointError when error is noAccessToEndpoint', () => { - const error = constructSearchError({ - error: SearchErrorType.noAccessToEndpoint, - message: 'Error message', - }); - assert.ok(error instanceof NoAccessToEndpointError); - }); - - test('should return an instance of Error when error is not any of the known error types', () => { - const error = constructSearchError({ - error: 'unknownError', - message: 'Error message', - }); - assert.ok(error instanceof Error); - }); -}); diff --git a/extensions/copilot/src/platform/remoteSearch/test/node/utils.spec.ts b/extensions/copilot/src/platform/remoteSearch/test/node/utils.spec.ts deleted file mode 100644 index 0318a206625b..000000000000 --- a/extensions/copilot/src/platform/remoteSearch/test/node/utils.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { suite, test } from 'vitest'; -import { formatScopingQuery } from '../../common/utils'; - -suite('formatScopingQuery', () => { - test('should format a scoping query with only a repo', () => { - const query = { repo: 'owner/repo' }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo)'); - }); - - test('should format a scoping query with multiple repos', () => { - const query = { repo: ['owner/repo', 'owner/repo2'] }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo OR repo:owner/repo2)'); - }); - - test('should format a scoping query with a repo and a language', () => { - const query = { repo: 'owner/repo', lang: ['typescript', 'javascript'] }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo) (lang:typescript OR lang:javascript)'); - }); - - test('should format a scoping query with a repo and a notLang', () => { - const query = { repo: 'owner/repo', notLang: ['python', 'ruby'] }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo) NOT (lang:python OR lang:ruby)'); - }); - - test('should format a scoping query with a repo and a path', () => { - const query = { repo: 'owner/repo', path: ['src', 'test'] }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo) (path:src OR path:test)'); - }); - - test('should format a scoping query with a repo and a notPath', () => { - const query = { repo: 'owner/repo', notPath: ['node_modules', 'dist'] }; - const result = formatScopingQuery(query); - assert.strictEqual(result, '(repo:owner/repo) NOT (path:node_modules OR path:dist)'); - }); - - test('should format a scoping query with all options', () => { - const query = { - repo: 'owner/repo', - lang: ['typescript', 'javascript'], - notLang: ['python', 'ruby'], - path: ['src', 'test'], - notPath: ['node_modules', 'dist'] - }; - const result = formatScopingQuery(query); - assert.strictEqual( - result, - '(repo:owner/repo) (lang:typescript OR lang:javascript) NOT (lang:python OR lang:ruby) (path:src OR path:test) NOT (path:node_modules OR path:dist)' - ); - }); -}); diff --git a/extensions/copilot/src/platform/telemetry/common/telemetry.ts b/extensions/copilot/src/platform/telemetry/common/telemetry.ts index b62b3ddeccdd..3e8d3a36a7c4 100644 --- a/extensions/copilot/src/platform/telemetry/common/telemetry.ts +++ b/extensions/copilot/src/platform/telemetry/common/telemetry.ts @@ -219,7 +219,7 @@ const COMPRESSED_CHUNK_SUFFIX = 'Chunk'; // regardless of their length. These are known to frequently exceed the per-property limit, so // always producing the `Chunk` family gives the backend a single, uniform place to read the // value from instead of having to branch on whether the value happened to be chunked. -const ALWAYS_COMPRESSED_CHUNK_KEYS = new Set(['messagesJson', 'messageText', 'diffsJSON', 'prompt']); +const ALWAYS_COMPRESSED_CHUNK_KEYS = new Set(['messagesJson', 'messageText', 'diffsJSON', 'prompt', 'request.option.tools', 'request_option_tools']); // Overrides for the base name of the compressed chunk family. By default the chunk family is named // `Chunk`, but some backend mappings expect a different casing. For `messagesJson` the backend diff --git a/extensions/copilot/src/platform/telemetry/node/baseExperimentationService.ts b/extensions/copilot/src/platform/telemetry/node/baseExperimentationService.ts index 9805d3c07617..b5e38cd69ddb 100644 --- a/extensions/copilot/src/platform/telemetry/node/baseExperimentationService.ts +++ b/extensions/copilot/src/platform/telemetry/node/baseExperimentationService.ts @@ -30,6 +30,7 @@ export class UserInfoStore extends Disposable { private _isSn: boolean | undefined; private _isVscodeTeamMember: boolean | undefined; private _organizationList: string[] | undefined; + private _isProxima = false; private _onDidChangeUserInfo = this._register(new Emitter()); readonly onDidChangeUserInfo = this._onDidChangeUserInfo.event; @@ -40,7 +41,11 @@ export class UserInfoStore extends Disposable { static IS_SN_STORAGE_KEY = 'exp.github.copilot.isSn'; static IS_VSCODE_TEAM_MEMBER_STORAGE_KEY = 'exp.github.copilot.isVscodeTeamMember'; static ORGANIZATION_LIST_STORAGE_KEY = 'exp.github.copilot.organizationList'; - constructor(private readonly context: IVSCodeExtensionContext, copilotTokenStore: ICopilotTokenStore) { + static IS_PROXIMA_STORAGE_KEY = 'exp.github.copilot.isProxima'; + constructor( + private readonly context: IVSCodeExtensionContext, + copilotTokenStore: ICopilotTokenStore + ) { super(); if (copilotTokenStore) { @@ -54,13 +59,17 @@ export class UserInfoStore extends Disposable { } return undefined; }; + const getIsProxima = (): boolean => { + const stamp = copilotTokenStore.copilotToken?.getTokenValue('st'); + return !!stamp && stamp !== 'dotcom'; + }; - copilotTokenStore.onDidStoreUpdate(() => { - this.updateUserInfo(getInternalOrg(), copilotTokenStore.copilotToken?.sku, copilotTokenStore.copilotToken?.isFcv1(), copilotTokenStore.copilotToken?.isSn(), copilotTokenStore.copilotToken?.isVscodeTeamMember, copilotTokenStore.copilotToken?.organizationList); - }); + this._register(copilotTokenStore.onDidChangeTokenData(() => { + this.updateUserInfo(getInternalOrg(), copilotTokenStore.copilotToken?.sku, copilotTokenStore.copilotToken?.isFcv1(), copilotTokenStore.copilotToken?.isSn(), copilotTokenStore.copilotToken?.isVscodeTeamMember, copilotTokenStore.copilotToken?.organizationList, getIsProxima()); + })); if (copilotTokenStore.copilotToken) { - this.updateUserInfo(getInternalOrg(), copilotTokenStore.copilotToken.sku, copilotTokenStore.copilotToken.isFcv1(), copilotTokenStore.copilotToken.isSn(), copilotTokenStore.copilotToken.isVscodeTeamMember, copilotTokenStore.copilotToken.organizationList); + this.updateUserInfo(getInternalOrg(), copilotTokenStore.copilotToken.sku, copilotTokenStore.copilotToken.isFcv1(), copilotTokenStore.copilotToken.isSn(), copilotTokenStore.copilotToken.isVscodeTeamMember, copilotTokenStore.copilotToken.organizationList, getIsProxima()); } else { const cachedInternalValue = this.context.globalState.get(UserInfoStore.INTERNAL_ORG_STORAGE_KEY); const cachedSkuValue = this.context.globalState.get(UserInfoStore.SKU_STORAGE_KEY); @@ -68,8 +77,10 @@ export class UserInfoStore extends Disposable { const cachedIsSnValue = this.context.globalState.get(UserInfoStore.IS_SN_STORAGE_KEY); const cachedIsVscodeTeamMemberValue = this.context.globalState.get(UserInfoStore.IS_VSCODE_TEAM_MEMBER_STORAGE_KEY); const cachedOrganizationListValue = this.context.globalState.get(UserInfoStore.ORGANIZATION_LIST_STORAGE_KEY); - this.updateUserInfo(cachedInternalValue, cachedSkuValue, cachedIsFcv1Value, cachedIsSnValue, cachedIsVscodeTeamMemberValue, cachedOrganizationListValue); + const cachedIsProximaValue = this.context.globalState.get(UserInfoStore.IS_PROXIMA_STORAGE_KEY) ?? false; + this.updateUserInfo(cachedInternalValue, cachedSkuValue, cachedIsFcv1Value, cachedIsSnValue, cachedIsVscodeTeamMemberValue, cachedOrganizationListValue, cachedIsProximaValue); } + } } @@ -93,6 +104,10 @@ export class UserInfoStore extends Disposable { return this._isVscodeTeamMember; } + get isProxima(): boolean { + return this._isProxima; + } + /** * The list of organization IDs the user belongs to. * This can be used in ExP to target specific organizations via the X-GitHub-Copilot-OrganizationList filter. @@ -101,8 +116,8 @@ export class UserInfoStore extends Disposable { return this._organizationList; } - private updateUserInfo(internalOrg?: string, sku?: string, isFcv1?: boolean, isSn?: boolean, isVscodeTeamMember?: boolean, organizationList?: string[]): void { - if (this._internalOrg === internalOrg && this._sku === sku && this._isFcv1 === isFcv1 && this._isSn === isSn && this._isVscodeTeamMember === isVscodeTeamMember && equals(this._organizationList, organizationList)) { + private updateUserInfo(internalOrg: string | undefined, sku: string | undefined, isFcv1: boolean | undefined, isSn: boolean | undefined, isVscodeTeamMember: boolean | undefined, organizationList: string[] | undefined, isProxima: boolean): void { + if (this._internalOrg === internalOrg && this._sku === sku && this._isFcv1 === isFcv1 && this._isSn === isSn && this._isVscodeTeamMember === isVscodeTeamMember && equals(this._organizationList, organizationList) && this._isProxima === isProxima) { // no change return; } @@ -113,15 +128,18 @@ export class UserInfoStore extends Disposable { this._isSn = isSn; this._isVscodeTeamMember = isVscodeTeamMember; this._organizationList = organizationList; + this._isProxima = isProxima; void this.context.globalState.update(UserInfoStore.INTERNAL_ORG_STORAGE_KEY, this._internalOrg); void this.context.globalState.update(UserInfoStore.SKU_STORAGE_KEY, this._sku); void this.context.globalState.update(UserInfoStore.IS_FCV1_STORAGE_KEY, this._isFcv1); void this.context.globalState.update(UserInfoStore.IS_SN_STORAGE_KEY, this._isSn); void this.context.globalState.update(UserInfoStore.IS_VSCODE_TEAM_MEMBER_STORAGE_KEY, this._isVscodeTeamMember); void this.context.globalState.update(UserInfoStore.ORGANIZATION_LIST_STORAGE_KEY, this._organizationList); + void this.context.globalState.update(UserInfoStore.IS_PROXIMA_STORAGE_KEY, this._isProxima); this._onDidChangeUserInfo.fire(); } + } /** @@ -176,6 +194,7 @@ export class BaseExperimentationService extends Disposable implements IExperimen protected _delegate: ITASExperimentationService; protected readonly _userInfoStore: UserInfoStore; + protected readonly refreshOnUserInfoChange: boolean = true; /** Disposes the current delegate (stopping its polling); auto-disposes the previous one on replacement. */ private readonly _delegateDisposable = this._register(new MutableDisposable()); @@ -196,10 +215,13 @@ export class BaseExperimentationService extends Disposable implements IExperimen ) { super(); - this._userInfoStore = new UserInfoStore(context, copilotTokenStore); + this._userInfoStore = this._register(new UserInfoStore(context, copilotTokenStore)); // Refresh treatments when user info changes this._register(this._userInfoStore.onDidChangeUserInfo(async () => { + if (!this.refreshOnUserInfoChange) { + return; + } await this._delegate.getTreatmentVariableAsync('vscode', 'refresh'); this._logService.trace(`[BaseExperimentationService] User info changed, refreshed treatments`); this._signalTreatmentsChangeEvent(); diff --git a/extensions/copilot/src/platform/telemetry/test/node/assignmentFilters.spec.ts b/extensions/copilot/src/platform/telemetry/test/node/assignmentFilters.spec.ts index 02e01c91d08a..20dc627b1e7a 100644 --- a/extensions/copilot/src/platform/telemetry/test/node/assignmentFilters.spec.ts +++ b/extensions/copilot/src/platform/telemetry/test/node/assignmentFilters.spec.ts @@ -4,15 +4,19 @@ *--------------------------------------------------------------------------------------------*/ import { afterEach, describe, expect, it, vi } from 'vitest'; +// eslint-disable-next-line local/code-layering, local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { getUserKind } from '../../../../extension/completions-core/vscode-node/lib/src/auth/orgs'; import { mock } from '../../../../util/common/test/simpleMock'; import { DisposableStore } from '../../../../util/vs/base/common/lifecycle'; import { platform, PlatformToString } from '../../../../util/vs/base/common/platform'; import { CopilotToken, createTestExtendedTokenInfo } from '../../../authentication/common/copilotToken'; import { CopilotTokenStore } from '../../../authentication/common/copilotTokenStore'; +import { INTEGRATION_ID } from '../../../endpoint/common/licenseAgreement'; import { packageJson } from '../../../env/common/packagejson'; import { ILogService } from '../../../log/common/logService'; -import { CopilotAssignmentsFilterProvider } from '../../vscode-node/microsoftExperimentationService'; +import { UserInfoStore } from '../../node/baseExperimentationService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. +import { CopilotAssignmentsFilterProvider, GitHubAccountFilterProvider } from '../../vscode-node/microsoftExperimentationService'; vi.mock('vscode', async importOriginal => ({ ...await importOriginal(), @@ -30,6 +34,7 @@ describe('CopilotAssignmentsFilterProvider', () => { function createProvider() { const tokenStore = disposables.add(new CopilotTokenStore()); + tokenStore.authenticationState = 'signedIn'; const logService = new class extends mock() { override trace(): void { } override warn(): void { } @@ -47,6 +52,7 @@ describe('CopilotAssignmentsFilterProvider', () => { })); expect(Object.fromEntries(provider.getFilters())).toEqual({ + integratorid: INTEGRATION_ID, vscode_core_platform: PlatformToString(platform), vscode_core_windowkind: 'editor', devdeviceid: 'test-device', @@ -61,6 +67,7 @@ describe('CopilotAssignmentsFilterProvider', () => { github_core_isfcv1: '1', vscode_core_copilotchatextensionversion: packageJson.version.split('-')[0], }); + }); it('uses current token values after refresh and clears account values on sign-out', () => { @@ -155,3 +162,30 @@ describe('CopilotAssignmentsFilterProvider', () => { ]); }); }); + +describe('GitHubAccountFilterProvider', () => { + it('emits Proxima only as a legacy TAS header', () => { + let isProxima = false; + const userInfoStore = new class extends mock() { + override get isProxima(): boolean { + return isProxima; + } + }(); + const logService = new class extends mock() { + override trace(): void { } + }(); + const provider = new GitHubAccountFilterProvider(userInfoStore, logService); + + expect([false, true].map(value => { + isProxima = value; + const filters = provider.getFilters(); + return { + legacy: filters.get('X-GitHub-Copilot-IsProxima'), + edge: filters.get('github_core_isproxima'), + }; + })).toEqual([ + { legacy: '0', edge: undefined }, + { legacy: '1', edge: undefined }, + ]); + }); +}); diff --git a/extensions/copilot/src/platform/telemetry/test/node/experimentation.spec.ts b/extensions/copilot/src/platform/telemetry/test/node/experimentation.spec.ts index 987d4d0c6949..829ff6d96881 100644 --- a/extensions/copilot/src/platform/telemetry/test/node/experimentation.spec.ts +++ b/extensions/copilot/src/platform/telemetry/test/node/experimentation.spec.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import type * as vscode from 'vscode'; import { IExperimentationService as ITASExperimentationService } from 'vscode-tas-client'; import { mock } from '../../../../util/common/test/simpleMock'; @@ -17,6 +17,7 @@ import { ILogService } from '../../../log/common/logService'; import { FetchOptions, HeadersImpl, IFetcherService, Response } from '../../../networking/common/fetcherService'; import { createPlatformServices, ITestingServicesAccessor } from '../../../test/node/services'; import { TreatmentsChangeEvent } from '../../common/nullExperimentationService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { createTasFetch } from '../../vscode-node/tasFetch'; import { BaseExperimentationService, RevocationGate, TASClientDelegateFn, UserInfoStore } from '../../node/baseExperimentationService'; @@ -173,6 +174,7 @@ describe('ExP Service Tests', () => { let expService: TestExperimentationService; let copilotTokenService: ICopilotTokenStore; let extensionContext: IVSCodeExtensionContext; + const userInfoStores = new Set(); const GitHubProToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'token-gh-pro', username: 'fake', sku: 'pro', copilot_plan: 'unknown', organization_list: ['4535c7beffc844b46bb1ed4aa04d759a'] })); const GitHubAndMicrosoftEnterpriseToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'token-gh-msft-enterprise', username: 'fake', sku: 'enterprise', copilot_plan: 'unknown', organization_list: ['4535c7beffc844b46bb1ed4aa04d759a', 'a5db0bcaae94032fe715fb34a5e4bce2'] })); @@ -191,6 +193,19 @@ describe('ExP Service Tests', () => { expService = accessor.get(IInstantiationService).createInstance(TestExperimentationService); }); + function createUserInfoStore(): UserInfoStore { + const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + userInfoStores.add(userInfoStore); + return userInfoStore; + } + + afterEach(() => { + for (const userInfoStore of userInfoStores) { + userInfoStore.dispose(); + } + userInfoStores.clear(); + }); + beforeEach(() => { // Reset the mock service before each test expService.mockTasService.reset(); @@ -299,6 +314,38 @@ describe('ExP Service Tests', () => { expect(expService.mockTasService.refreshCallCount).toBe(1); }); + it('should classify Proxima from the token stamp and fail closed while it is unresolved', () => { + copilotTokenService.copilotToken = undefined; + const userInfoStore = createUserInfoStore(); + let changes = 0; + userInfoStore.onDidChangeUserInfo(() => changes++); + + const values = [userInfoStore.isProxima]; + copilotTokenService.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'st=proxima' })); + values.push(userInfoStore.isProxima); + copilotTokenService.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'st=dotcom' })); + values.push(userInfoStore.isProxima); + copilotTokenService.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'tid=no-stamp' })); + values.push(userInfoStore.isProxima); + copilotTokenService.copilotToken = undefined; + values.push(userInfoStore.isProxima); + + expect({ values, changes }).toEqual({ + values: [false, true, false, false, false], + changes: 3, + }); + }); + + it('should use cached Proxima status on initialization', async () => { + await extensionContext.globalState.update(UserInfoStore.IS_PROXIMA_STORAGE_KEY, true); + copilotTokenService.copilotToken = undefined; + + const userInfoStore = createUserInfoStore(); + + expect(userInfoStore.isProxima).toBe(true); + await extensionContext.globalState.update(UserInfoStore.IS_PROXIMA_STORAGE_KEY, undefined); + }); + it('should handle cached user info on initialization', async () => { // Simulate cached values in global state await extensionContext.globalState.update(UserInfoStore.INTERNAL_ORG_STORAGE_KEY, 'github'); @@ -507,7 +554,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify isVscodeTeamMember is set in UserInfoStore - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.isVscodeTeamMember).toBe(true); }); @@ -520,7 +567,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify isVscodeTeamMember is set correctly in UserInfoStore - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.isVscodeTeamMember).toBe(false); }); @@ -545,7 +592,7 @@ describe('ExP Service Tests', () => { await extensionContext.globalState.update(UserInfoStore.IS_VSCODE_TEAM_MEMBER_STORAGE_KEY, true); // Create new UserInfoStore instance to test initialization - const newUserInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const newUserInfoStore = createUserInfoStore(); // Should use cached value initially (when no token is present) expect(newUserInfoStore.isVscodeTeamMember).toBe(true); @@ -563,7 +610,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify organization list is correctly tracked - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.organizationList).toBeDefined(); expect(userInfoStore.organizationList).toContain('4535c7beffc844b46bb1ed4aa04d759a'); // GitHub org expect(userInfoStore.organizationList).toContain('a5db0bcaae94032fe715fb34a5e4bce2'); // Microsoft org @@ -593,7 +640,7 @@ describe('ExP Service Tests', () => { await extensionContext.globalState.update(UserInfoStore.ORGANIZATION_LIST_STORAGE_KEY, testOrgList); // Create new UserInfoStore instance to test initialization - const newUserInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const newUserInfoStore = createUserInfoStore(); // Should use cached value initially (when no token is present) expect(newUserInfoStore.organizationList).toEqual(testOrgList); @@ -611,7 +658,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify organization list is empty - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.organizationList).toBeDefined(); expect(userInfoStore.organizationList?.length).toBe(0); }); @@ -637,7 +684,7 @@ describe('ExP Service Tests', () => { expect(expService.mockTasService.refreshCallCount).toBe(1); // Verify the UserInfoStore has the correct value - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.isVscodeTeamMember).toBe(true); }); @@ -650,7 +697,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify isSn is set in UserInfoStore - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.isSn).toBe(true); }); @@ -663,7 +710,7 @@ describe('ExP Service Tests', () => { await treatmentsChangePromise; // Verify isSn is false in UserInfoStore - const userInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const userInfoStore = createUserInfoStore(); expect(userInfoStore.isSn).toBe(false); }); @@ -688,7 +735,7 @@ describe('ExP Service Tests', () => { await extensionContext.globalState.update(UserInfoStore.IS_SN_STORAGE_KEY, true); // Create new UserInfoStore instance to test initialization - const newUserInfoStore = new UserInfoStore(extensionContext, copilotTokenService); + const newUserInfoStore = createUserInfoStore(); // Should use cached value initially (when no token is present) expect(newUserInfoStore.isSn).toBe(true); diff --git a/extensions/copilot/src/platform/telemetry/test/node/telemetry.spec.ts b/extensions/copilot/src/platform/telemetry/test/node/telemetry.spec.ts index 6edfdda8918a..027c9abf2ef9 100644 --- a/extensions/copilot/src/platform/telemetry/test/node/telemetry.spec.ts +++ b/extensions/copilot/src/platform/telemetry/test/node/telemetry.spec.ts @@ -511,6 +511,19 @@ suite('multiplexProperties compression', function () { }); }); + test.each([ + ...[0, 100, 8192, 8193, 20000].map(length => ['request.option.tools', length] as const), + ...[0, 100, 8192, 8193, 20000].map(length => ['request_option_tools', length] as const), + ])('always compresses %s of length %i while preserving its raw prefix', async (key, length) => { + const tools = 'x'.repeat(length); + const result = await multiplexProperties({ [key]: tools }, gzipBase64); + + expect(result).toEqual({ + [key]: tools.slice(0, 8192), + [`${key}Chunk`]: await gzipBase64(tools), + }); + }); + test('always emits a compressed chunk family for known-large fields even when they fit', async () => { const result = await multiplexProperties({ diffsJSON: 'small', messagesJson: 'tiny', other: 'x' }, gzipBase64) as { [key: string]: string }; diff --git a/extensions/copilot/src/platform/telemetry/vscode-node/microsoftExperimentationService.ts b/extensions/copilot/src/platform/telemetry/vscode-node/microsoftExperimentationService.ts index 9459fb059ca3..d8b8f8ccecf6 100644 --- a/extensions/copilot/src/platform/telemetry/vscode-node/microsoftExperimentationService.ts +++ b/extensions/copilot/src/platform/telemetry/vscode-node/microsoftExperimentationService.ts @@ -8,8 +8,12 @@ import * as vscode from 'vscode'; import { getExperimentationServiceFromConfig, IExperimentationFilterProvider, TargetPopulation } from 'vscode-tas-client'; import { platform, PlatformToString } from '../../../util/vs/base/common/platform'; import { isObject } from '../../../util/vs/base/common/types'; +import { CancellationError } from '../../../util/vs/base/common/errors'; +import { mapsStrictEqualIgnoreOrder } from '../../../util/vs/base/common/map'; +import { runOnChange } from '../../../util/vs/base/common/observable'; import { ICopilotTokenStore } from '../../authentication/common/copilotTokenStore'; -import { IConfigurationService } from '../../configuration/common/configurationService'; +import { AuthProviderId, ConfigKey, IConfigurationService } from '../../configuration/common/configurationService'; +import { INTEGRATION_ID } from '../../endpoint/common/licenseAgreement'; import { IEnvService } from '../../env/common/envService'; import { packageJson } from '../../env/common/packagejson'; import { IVSCodeExtensionContext } from '../../extContext/common/extensionContext'; @@ -18,7 +22,7 @@ import { IFetcherService } from '../../networking/common/fetcherService'; import { FetcherService } from '../../networking/vscode-node/fetcherServiceImpl'; import { IExperimentationTelemetry, ITelemetryService } from '../common/telemetry'; import { BaseExperimentationService, RevocationGate, UserInfoStore } from '../node/baseExperimentationService'; -import { createTasFetch } from './tasFetch'; +import { createSignedOutAssignmentsFetch, createTasFetch, SIGNED_OUT_ASSIGNMENTS_ENDPOINTS } from './tasFetch'; function getTargetPopulation(isPreRelease: boolean): TargetPopulation { if (isPreRelease) { @@ -154,18 +158,19 @@ class CopilotCompletionsFilterProvider implements IExperimentationFilterProvider } } -class GithubAccountFilterProvider implements IExperimentationFilterProvider { +export class GitHubAccountFilterProvider implements IExperimentationFilterProvider { constructor(private _userInfoStore: UserInfoStore, private _logService: ILogService) { } getFilters(): Map { const orgListString = this._userInfoStore.organizationList?.join(','); - this._logService.trace(`[GithubAccountFilterProvider]::getFilters SKU: ${this._userInfoStore.sku}, Internal Org: ${this._userInfoStore.internalOrg}, IsFcv1: ${this._userInfoStore.isFcv1}, IsSn: ${this._userInfoStore.isSn}, IsVscodeTeamMember: ${this._userInfoStore.isVscodeTeamMember}, OrganizationList: ${orgListString}`); + this._logService.trace(`[GitHubAccountFilterProvider]::getFilters SKU: ${this._userInfoStore.sku}, Internal Org: ${this._userInfoStore.internalOrg}, IsFcv1: ${this._userInfoStore.isFcv1}, IsSn: ${this._userInfoStore.isSn}, IsVscodeTeamMember: ${this._userInfoStore.isVscodeTeamMember}, IsProxima: ${this._userInfoStore.isProxima}, OrganizationList: ${orgListString}`); const filters = new Map(); filters.set('X-GitHub-Copilot-SKU', this._userInfoStore.sku); filters.set('X-Microsoft-Internal-Org', this._userInfoStore.internalOrg); filters.set('X-GitHub-Copilot-IsFcv1', this._userInfoStore.isFcv1 ? '1' : '0'); filters.set('X-GitHub-Copilot-IsSn', this._userInfoStore.isSn ? '1' : '0'); filters.set('X-GitHub-Copilot-IsVscodeTeamMember', this._userInfoStore.isVscodeTeamMember ? '1' : '0'); + filters.set('X-GitHub-Copilot-IsProxima', this._userInfoStore.isProxima ? '1' : '0'); filters.set('X-GitHub-Copilot-OrganizationList', orgListString); return filters; } @@ -224,7 +229,7 @@ class WindowKindFilterProvider implements IExperimentationFilterProvider { } /** - * Emits Copilot account, Chat extension version, and environment userParams for the new TAS assignments API. + * Emits integrator, Copilot account, Chat extension version, and environment userParams for the new TAS assignments API. * Reads the token fresh on each call; generic app/build/extension-identity/target filters come from `vscode-tas-client`. */ export class CopilotAssignmentsFilterProvider implements IExperimentationFilterProvider { @@ -238,12 +243,13 @@ export class CopilotAssignmentsFilterProvider implements IExperimentationFilterP } getFilters(): Map { - const token = this._copilotTokenStore.copilotToken; + const token = this._copilotTokenStore.authenticationState === 'signedIn' ? this._copilotTokenStore.copilotToken : undefined; const internalOrg = token ? (token.isVscodeTeamMember ? 'vscode' : token.isGitHubInternal ? 'github' : token.isMicrosoftInternal ? 'microsoft' : undefined) : undefined; const filters = new Map(); + filters.set('integratorid', INTEGRATION_ID); filters.set('vscode_core_platform', PlatformToString(platform)); if (this._releaseDate) { filters.set('vscode_core_releasedate', this._releaseDate); @@ -267,6 +273,9 @@ export class CopilotAssignmentsFilterProvider implements IExperimentationFilterP } export class MicrosoftExperimentationService extends BaseExperimentationService { + // Token updates replace the delegate atomically, rather than refreshing the old endpoint with a new identity. + protected override readonly refreshOnUserInfoChange = false; + constructor( @ITelemetryService telemetryService: ITelemetryService, @IVSCodeExtensionContext context: IVSCodeExtensionContext, @@ -280,11 +289,31 @@ export class MicrosoftExperimentationService extends BaseExperimentationService const id = context.extension.id; const version = context.extension.packageJSON['version']; const targetPopulation = getTargetPopulation(envService.isPreRelease()); + const assignmentsFilterProvider = new CopilotAssignmentsFilterProvider(copilotTokenStore, logService); + const signedOutFetch = createSignedOutAssignmentsFetch(fetcherService, logService); + const getAssignments = () => { + const token = copilotTokenStore.copilotToken; + const state = copilotTokenStore.authenticationState; + let exp = state === 'signedIn' ? token?.endpoints?.exp : undefined; + const publicGitHub = configurationService.getConfig(ConfigKey.Shared.AuthProvider) !== AuthProviderId.GitHubEnterprise && !copilotTokenStore.githubEnterpriseUri; + const plan = token?.rawCopilotPlan; + const individual = token?.isIndividual && (plan === 'free' || plan === 'individual' || plan?.startsWith('individual_')); + if (!exp && publicGitHub && state === 'signedIn' && individual) { + exp = 'https://exp.individual.githubcopilot.com'; + } + const signedOut = state === 'signedOut'; + const endpoint = signedOut ? SIGNED_OUT_ASSIGNMENTS_ENDPOINTS[0] : exp ? `${exp.replace(/\/+$/, '')}/api/v1/assignments` : undefined; + return { + endpoint, + signedOut, + filters: endpoint ? assignmentsFilterProvider.getFilters() : new Map(), + }; + }; + let assignments = getAssignments(); let self: MicrosoftExperimentationService | undefined = undefined; const delegateFn = (memento: vscode.Memento, userInfoStore: UserInfoStore, gate: RevocationGate) => { const wrappedMemento = new ExpMementoWrapper(memento, envService); - const exp = copilotTokenStore.copilotToken?.endpoints?.exp; - const assignmentsEndpoint = exp ? `${exp.replace(/\/+$/, '')}/api/v1/assignments` : undefined; + const snapshot = assignments; // Route both the legacy (GET) and assignments (POST) requests through the extension's // fetcher service so they get proxy handling, retries/fallback, and the standard user-agent. const tasFetch = createTasFetch(fetcherService); @@ -297,7 +326,7 @@ export class MicrosoftExperimentationService extends BaseExperimentationService telemetry: new RevocableExpTelemetry(telemetryService, gate), memento: wrappedMemento, filterProviders: [ - new GithubAccountFilterProvider(userInfoStore, logService), + new GitHubAccountFilterProvider(userInfoStore, logService), new RelatedExtensionsFilterProvider(logService), new CopilotExtensionsFilterProvider(logService), // The callback is called in super ctor. At that time, self/this is not initialized yet (but also, no filter could have been possibly set). @@ -306,9 +335,15 @@ export class MicrosoftExperimentationService extends BaseExperimentationService new PlatformAndReleaseDateFilterProvider(logService), new WindowKindFilterProvider(logService), ], - fetch: tasFetch, - assignmentsEndpoint, - assignmentsFilterProviders: assignmentsEndpoint ? [new CopilotAssignmentsFilterProvider(copilotTokenStore, logService)] : undefined, + fetch: (url, init) => { + if (gate.isRevoked) { + throw new CancellationError(); + } + return tasFetch(url, init); + }, + assignmentsEndpoint: snapshot.endpoint, + assignmentsFetch: snapshot.signedOut ? (_url, init) => signedOutFetch(init, () => gate.isRevoked) : undefined, + assignmentsFilterProviders: snapshot.endpoint ? [{ getFilters: () => snapshot.filters }] : undefined, }); }; @@ -316,17 +351,22 @@ export class MicrosoftExperimentationService extends BaseExperimentationService self = this; // This is now fully initialized. - // The assignments endpoint is sourced from the Copilot token, which may arrive after - // this service is created. Recreate the delegate when its `exp` endpoint changes. - let currentExp = copilotTokenStore.copilotToken?.endpoints?.exp; - this._register(copilotTokenStore.onDidStoreUpdate(() => { - const token = copilotTokenStore.copilotToken; - const newExp = token?.endpoints?.exp; - if (newExp !== currentExp) { - currentExp = newExp; + const legacyAccountFilterProvider = new GitHubAccountFilterProvider(this._userInfoStore, logService); + let legacyAccountFilters = legacyAccountFilterProvider.getFilters(); + const updateAssignments = () => { + const next = getAssignments(); + const nextLegacyAccountFilters = legacyAccountFilterProvider.getFilters(); + if (next.endpoint !== assignments.endpoint || next.signedOut !== assignments.signedOut || !mapsStrictEqualIgnoreOrder(next.filters, assignments.filters) + || !mapsStrictEqualIgnoreOrder(nextLegacyAccountFilters, legacyAccountFilters)) { + assignments = next; + legacyAccountFilters = nextLegacyAccountFilters; this.recreateDelegate(); } - })); + }; + this._register(copilotTokenStore.onDidChangeTokenData(updateAssignments)); + this._register(copilotTokenStore.onDidChangeAuthenticationState(updateAssignments)); + this._register(copilotTokenStore.onDidChangeGitHubEnterpriseUri(updateAssignments)); + this._register(runOnChange(configurationService.getConfigObservable(ConfigKey.Shared.AuthProvider), updateAssignments)); if (fetcherService instanceof FetcherService) { fetcherService.setExperimentationService(this); diff --git a/extensions/copilot/src/platform/telemetry/vscode-node/tasFetch.ts b/extensions/copilot/src/platform/telemetry/vscode-node/tasFetch.ts index 334b73fcbe25..28d743c4e042 100644 --- a/extensions/copilot/src/platform/telemetry/vscode-node/tasFetch.ts +++ b/extensions/copilot/src/platform/telemetry/vscode-node/tasFetch.ts @@ -4,6 +4,108 @@ *--------------------------------------------------------------------------------------------*/ import { IFetcherService } from '../../networking/common/fetcherService'; +import { DeferredPromise, disposableTimeout, RunOnceScheduler } from '../../../util/vs/base/common/async'; +import { CancellationError } from '../../../util/vs/base/common/errors'; +import { DisposableStore, toDisposable } from '../../../util/vs/base/common/lifecycle'; +import { isObject } from '../../../util/vs/base/common/types'; +import { ILogService } from '../../log/common/logService'; + +export const SIGNED_OUT_ASSIGNMENTS_ENDPOINTS = [ + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + 'https://exp.business.githubcopilot.com/api/v1/assignments', + 'https://exp.individual.githubcopilot.com/api/v1/assignments', +]; +const SIGNED_OUT_ASSIGNMENTS_TIMEOUT = 5_000; +const SIGNED_OUT_ASSIGNMENTS_STAGGER = 1_000; + +/** Remembers a reachable anonymous TAS endpoint without changing signed-in or legacy transport. */ +export function createSignedOutAssignmentsFetch(fetcherService: IFetcherService, logService: ILogService) { + let preferredEndpoint: string | undefined; + return async (init: { method: 'POST'; headers: Record; body: string }, isRevoked: () => boolean) => { + const preferred = preferredEndpoint; + const endpoints = preferred + ? [preferred, ...SIGNED_OUT_ASSIGNMENTS_ENDPOINTS.filter(endpoint => endpoint !== preferred)] + : SIGNED_OUT_ASSIGNMENTS_ENDPOINTS; + // A remembered host only fails over on errors; time-based hedging is limited to discovery. + const hedge = !preferred; + const disposables = new DisposableStore(); + const controller = fetcherService.makeAbortController(); + disposables.add(toDisposable(() => controller.abort())); + const result = new DeferredPromise<{ status: number; json(): Promise }>(); + let next = 0; + let pending = 0; + const launchNext = async () => { + if (result.isSettled) { + return; + } + if (isRevoked()) { + result.error(new CancellationError()); + return; + } + const endpoint = endpoints[next++]; + pending++; + if (hedge && next < endpoints.length) { + scheduler.schedule(); + } + try { + const response = await fetcherService.fetch(endpoint, { + ...init, + callSite: 'exp.assignments', + signal: controller.signal, + retryFallbacks: false, + }); + if (response.status < 200 || response.status >= 300) { + throw new Error(`TAS returned HTTP ${response.status}`); + } + const data: unknown = await response.json(); + const fields = isObject(data) ? data as Record : undefined; + if (!fields || !isObject(fields.featureVariables) || typeof fields.assignmentContext !== 'string' + || !Object.values(fields.featureVariables).every(value => typeof value === 'string')) { + throw new Error('Invalid TAS assignments response'); + } + if (result.isSettled) { + return; + } + if (isRevoked()) { + throw new CancellationError(); + } + preferredEndpoint = endpoint; + result.complete({ status: response.status, json: async () => data }); + } catch (error) { + if (result.isSettled) { + return; + } + if (isRevoked()) { + result.error(new CancellationError()); + return; + } + logService.warn(`Signed-out TAS request failed at ${endpoint}: ${error}`); + pending--; + if (next < endpoints.length) { + scheduler.cancel(); + void launchNext(); + } else if (pending === 0) { + result.error(new Error('All signed-out TAS endpoints failed')); + } + } + }; + const scheduler = disposables.add(new RunOnceScheduler(() => { void launchNext(); }, SIGNED_OUT_ASSIGNMENTS_STAGGER)); + disposableTimeout(() => { + logService.warn('Signed-out TAS discovery timed out'); + // An unresponsive remembered host never fails over, so rediscover with hedging next time. + if (preferred && preferredEndpoint === preferred) { + preferredEndpoint = undefined; + } + result.error(new Error('Signed-out TAS discovery timed out')); + }, SIGNED_OUT_ASSIGNMENTS_TIMEOUT, disposables); + try { + void launchNext(); + return await result.p; + } finally { + disposables.dispose(); + } + }; +} /** * Builds the transport that TAS uses for both the legacy (GET) and the assignments (POST) diff --git a/extensions/copilot/src/platform/telemetry/vscode-node/test/microsoftExperimentationService.spec.ts b/extensions/copilot/src/platform/telemetry/vscode-node/test/microsoftExperimentationService.spec.ts new file mode 100644 index 000000000000..9e18283cf68a --- /dev/null +++ b/extensions/copilot/src/platform/telemetry/vscode-node/test/microsoftExperimentationService.spec.ts @@ -0,0 +1,436 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Extension } from 'vscode'; +import { getExperimentationServiceFromConfig, IExperimentationService } from 'vscode-tas-client'; +import { mock } from '../../../../util/common/test/simpleMock'; +import { DisposableStore } from '../../../../util/vs/base/common/lifecycle'; +import { CopilotToken, createTestExtendedTokenInfo } from '../../../authentication/common/copilotToken'; +import { CopilotTokenStore, ICopilotTokenStore } from '../../../authentication/common/copilotTokenStore'; +import { AuthProviderId, ConfigKey } from '../../../configuration/common/configurationService'; +import { DefaultsOnlyConfigurationService } from '../../../configuration/common/defaultsOnlyConfigurationService'; +import { InMemoryConfigurationService } from '../../../configuration/test/common/inMemoryConfigurationService'; +import { INTEGRATION_ID } from '../../../endpoint/common/licenseAgreement'; +import { IEnvService } from '../../../env/common/envService'; +import { IVSCodeExtensionContext } from '../../../extContext/common/extensionContext'; +import { ILogService } from '../../../log/common/logService'; +import { IFetcherService, Response } from '../../../networking/common/fetcherService'; +import { MockExtensionContext } from '../../../test/node/extensionContext'; +import { ITelemetryService } from '../../common/telemetry'; +import { UserInfoStore } from '../../node/baseExperimentationService'; +import { MicrosoftExperimentationService } from '../microsoftExperimentationService'; + +vi.mock('vscode', async importOriginal => ({ + ...await importOriginal(), + env: { appRoot: '', devDeviceId: 'test-device' }, + workspace: { isAgentSessionsWorkspace: false }, + extensions: { getExtension: () => undefined }, +})); + +vi.mock('vscode-tas-client', () => ({ + TargetPopulation: { Public: 'public', Insiders: 'insider' }, + getExperimentationServiceFromConfig: vi.fn(), +})); + +class MockTASClient extends mock() { + override readonly initializePromise = Promise.resolve(); + override readonly initialFetch = Promise.resolve(); + override readonly getTreatmentVariableAsync = vi.fn(async () => undefined); + override readonly dispose = vi.fn(); +} + +class ExperimentationExtensionContext extends mock() { + override extension = new class extends mock>() { + override id = 'GitHub.copilot-chat'; + override packageJSON = { version: '1.0.0' }; + }(); + override globalState = Object.assign(new MockExtensionContext().globalState, { setKeysForSync: () => { } }); +} + +describe('MicrosoftExperimentationService endpoint routing', () => { + const store = new DisposableStore(); + const clients: MockTASClient[] = []; + const endpoints = [ + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + 'https://exp.business.githubcopilot.com/api/v1/assignments', + 'https://exp.individual.githubcopilot.com/api/v1/assignments', + ]; + const emptyAssignments = '{"featureVariables":{},"assignmentContext":""}'; + + function response(status = 200, body = emptyAssignments) { + return Response.fromText(status, '', new Headers(), body, 'test-stub'); + } + + function fetchAssignments() { + const config = vi.mocked(getExperimentationServiceFromConfig).mock.calls.at(-1)![0]; + const userParams = Object.fromEntries(config.assignmentsFilterProviders!.flatMap(provider => [...provider.getFilters()])); + const init = { method: 'POST' as const, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userParams }) }; + return (config.assignmentsFetch ?? config.fetch)!(config.assignmentsEndpoint!, init); + } + + beforeEach(() => { + clients.length = 0; + vi.mocked(getExperimentationServiceFromConfig).mockClear(); + vi.mocked(getExperimentationServiceFromConfig).mockImplementation(() => { + const client = new MockTASClient(); + clients.push(client); + return client; + }); + }); + + afterEach(() => { + store.clear(); + vi.useRealTimers(); + }); + + function createService(token?: CopilotToken, state: ICopilotTokenStore['authenticationState'] = token ? 'signedIn' : 'signedOut', provider = AuthProviderId.GitHub, context = new ExperimentationExtensionContext()) { + const tokens = store.add(new CopilotTokenStore()); + tokens.authenticationState = state; + tokens.copilotToken = token; + const configuration = store.add(new InMemoryConfigurationService( + store.add(new DefaultsOnlyConfigurationService()), + new Map([[ConfigKey.Shared.AuthProvider, provider]]), + )); + const env = new class extends mock() { + override isPreRelease() { return false; } + }(); + const log = new class extends mock() { + override trace(): void { } + override warn(): void { } + }(); + const fetcher = new class extends mock() { + override fetch = vi.fn(async () => response()); + override makeAbortController() { return new AbortController(); } + }(); + const service = store.add(new MicrosoftExperimentationService( + new class extends mock() { }(), + context, + env, + tokens, + configuration, + fetcher, + log, + )); + return { service, tokens, configuration, fetcher }; + } + + for (const token of [undefined, new CopilotToken(createTestExtendedTokenInfo({ endpoints: undefined }))]) { + it(`sends the integrator only in assignment userParams when ${token ? 'signed in' : 'signed out'}`, async () => { + const { service, fetcher } = createService(token); + await service.hasTreatments(); + await fetchAssignments(); + const config = vi.mocked(getExperimentationServiceFromConfig).mock.calls.at(-1)![0]; + const legacyFilters = Object.fromEntries(config.filterProviders!.flatMap(provider => [...provider.getFilters()])); + expect({ + requests: fetcher.fetch.mock.calls.map(([, options]) => ({ + integratorId: JSON.parse(options.body!).userParams.integratorid, + headers: options.headers, + })), + legacyIntegratorId: legacyFilters.integratorid, + }).toEqual({ + requests: [{ integratorId: INTEGRATION_ID, headers: { 'Content-Type': 'application/json' } }], + legacyIntegratorId: undefined, + }); + }); + + it(`configures ${token ? 'individual routing without a token endpoint' : 'discovery when signed out'}`, async () => { + const { service } = createService(token); + await service.hasTreatments(); + const configs = vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => ({ + endpoint: config.assignmentsEndpoint, + hasLegacyFilters: !!config.filterProviders?.length, + hasAssignmentsFilters: !!config.assignmentsFilterProviders?.length, + hasTransport: typeof config.fetch === 'function', + })); + expect(configs).toEqual([{ + endpoint: token ? endpoints[2] : endpoints[0], + hasLegacyFilters: true, + hasAssignmentsFilters: true, + hasTransport: true, + }]); + }); + } + + it('switches between discovered and account routing even on the same host', async () => { + const { service, tokens } = createService(); + await service.hasTreatments(); + tokens.authenticationState = 'signedIn'; + tokens.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ endpoints: { exp: 'https://exp.enterprise.githubcopilot.com///' } })); + await service.hasTreatments(); + tokens.authenticationState = 'unknown'; + tokens.copilotToken = undefined; + tokens.authenticationState = 'signedOut'; + await service.hasTreatments(); + expect(vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => config.assignmentsEndpoint).filter(Boolean)).toEqual([ + endpoints[0], + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + endpoints[0], + ]); + }); + + it('waits for discovered auth and does not recreate for token refreshes with unchanged targeting', async () => { + const { service, tokens } = createService(undefined, 'unknown'); + await service.hasTreatments(); + tokens.authenticationState = 'signedIn'; + const info = createTestExtendedTokenInfo({ token: 'tid=user;refresh=1', endpoints: { exp: 'https://exp.individual.githubcopilot.com' } }); + tokens.copilotToken = new CopilotToken(info); + await service.hasTreatments(); + tokens.copilotToken = new CopilotToken({ ...info, token: 'tid=user;refresh=2' }); + await service.hasTreatments(); + expect(vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => config.assignmentsEndpoint)).toEqual([ + undefined, + 'https://exp.individual.githubcopilot.com/api/v1/assignments', + ]); + }); + + it('replaces signed-out assignments when a late token has no endpoint and cached user info matches', async () => { + const context = new ExperimentationExtensionContext(); + await context.globalState.update(UserInfoStore.SKU_STORAGE_KEY, 'free_limited_copilot'); + await context.globalState.update(UserInfoStore.IS_FCV1_STORAGE_KEY, false); + await context.globalState.update(UserInfoStore.IS_SN_STORAGE_KEY, false); + await context.globalState.update(UserInfoStore.IS_VSCODE_TEAM_MEMBER_STORAGE_KEY, false); + await context.globalState.update(UserInfoStore.ORGANIZATION_LIST_STORAGE_KEY, []); + const { service, tokens } = createService(undefined, 'signedOut', AuthProviderId.GitHub, context); + await service.hasTreatments(); + tokens.authenticationState = 'signedIn'; + tokens.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'tid=late-user', endpoints: undefined })); + await service.hasTreatments(); + expect(vi.mocked(getExperimentationServiceFromConfig).mock.calls.filter(([config]) => config.assignmentsEndpoint).map(([config]) => ({ + endpoint: config.assignmentsEndpoint, + tid: config.assignmentsFilterProviders?.[0].getFilters().get('copilottrackingid'), + }))).toEqual([ + { endpoint: endpoints[0], tid: undefined }, + { endpoint: 'https://exp.individual.githubcopilot.com/api/v1/assignments', tid: 'late-user' }, + ]); + }); + + it('refreshes changed targeting on the same endpoint without fetching through a superseded delegate', async () => { + const info = createTestExtendedTokenInfo({ token: 'tid=first', endpoints: { exp: 'https://exp.individual.githubcopilot.com' } }); + const { service, tokens } = createService(new CopilotToken(info)); + await service.hasTreatments(); + const originalConfig = vi.mocked(getExperimentationServiceFromConfig).mock.calls[0][0]; + tokens.copilotToken = new CopilotToken({ ...info, token: 'tid=second', enterprise_list: [42] }); + await service.hasTreatments(); + const configs = vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => config); + expect(configs.map(config => { + const filters = config.assignmentsFilterProviders?.[0].getFilters(); + return [filters?.get('copilottrackingid'), filters?.get('github_core_businessid')]; + })).toEqual([['first', ''], ['second', '42']]); + expect(() => originalConfig.fetch!('https://exp.individual.githubcopilot.com/api/v1/assignments', { method: 'POST', headers: {}, body: '{}' })).toThrow('Canceled'); + expect(clients.map(client => client.getTreatmentVariableAsync.mock.calls.length)).toEqual([0, 0]); + }); + + for (const { plan, individual, provider, state } of [ + { plan: 'business', individual: false, provider: AuthProviderId.GitHub, state: 'signedIn' }, + { plan: 'enterprise', individual: false, provider: AuthProviderId.GitHub, state: 'signedIn' }, + { plan: 'unknown', individual: true, provider: AuthProviderId.GitHub, state: 'signedIn' }, + { plan: 'individual', individual: true, provider: AuthProviderId.GitHubEnterprise, state: 'signedIn' }, + ] as const) { + it(`requires an explicit endpoint for ${plan}, ${provider}, ${state}`, async () => { + const token = state === 'signedIn' ? new CopilotToken(createTestExtendedTokenInfo({ sku: 'test-paid-sku', copilot_plan: plan, individual, endpoints: undefined })) : undefined; + const { service } = createService(token, state, provider); + await service.hasTreatments(); + expect(vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => config.assignmentsEndpoint)).toEqual([undefined]); + }); + } + + it('starts managed assignments when a refreshed token supplies the explicit endpoint', async () => { + const info = createTestExtendedTokenInfo({ token: 'tid=user;refresh=1', copilot_plan: 'enterprise', individual: false, endpoints: undefined }); + const { service, tokens } = createService(new CopilotToken(info), 'signedIn', AuthProviderId.GitHubEnterprise); + await service.hasTreatments(); + tokens.copilotToken = new CopilotToken({ ...info, endpoints: { exp: 'https://exp.example.ghe.com' } }); + await service.hasTreatments(); + expect(vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => config.assignmentsEndpoint)).toEqual([ + undefined, + 'https://exp.example.ghe.com/api/v1/assignments', + ]); + }); + + for (const state of ['unknown', 'signedIn'] as const) { + it(`refreshes legacy targeting without a new endpoint when auth is ${state}`, async () => { + const info = createTestExtendedTokenInfo({ token: 'tid=user', sku: 'business', copilot_plan: 'business', individual: false, endpoints: undefined }); + const { service, tokens } = createService(new CopilotToken(info), state, AuthProviderId.GitHubEnterprise); + await service.hasTreatments(); + const snapshots = () => vi.mocked(getExperimentationServiceFromConfig).mock.calls.map(([config]) => ({ + endpoint: config.assignmentsEndpoint, + legacy: Object.fromEntries(config.filterProviders![0].getFilters()), + })); + const before = snapshots()[0]; + tokens.copilotToken = new CopilotToken({ ...info, sku: 'enterprise', organization_list: ['vscode'] }); + await service.hasTreatments(); + const after = snapshots().at(-1)!; + tokens.copilotToken = new CopilotToken({ ...info, sku: 'enterprise', organization_list: ['vscode'] }); + await service.hasTreatments(); + expect({ + endpoints: [before.endpoint, after.endpoint], + skus: [before.legacy['X-GitHub-Copilot-SKU'], after.legacy['X-GitHub-Copilot-SKU']], + orgs: [before.legacy['X-GitHub-Copilot-OrganizationList'], after.legacy['X-GitHub-Copilot-OrganizationList']], + delegates: clients.length, + refreshes: clients.map(client => client.getTreatmentVariableAsync.mock.calls.length), + }).toEqual({ + endpoints: [undefined, undefined], + skus: ['business', 'enterprise'], + orgs: ['', 'vscode'], + delegates: 2, + refreshes: [0, 0], + }); + }); + } + + for (const failure of ['network', 'http', 'json', 'schema', 'timeout'] as const) { + it(`discovers and reuses an empty assignment after ${failure} failure even with enterprise auth configured`, async () => { + const staleToken = new CopilotToken(createTestExtendedTokenInfo({ token: 'tid=previous-user' })); + const { service, fetcher } = createService(staleToken, 'signedOut', AuthProviderId.GitHubEnterprise); + await service.hasTreatments(); + vi.useFakeTimers(); + fetcher.fetch.mockImplementationOnce(async (_url, options) => { + switch (failure) { + case 'network': throw new Error('Blocked'); + case 'http': return response(403, 'Forbidden'); + case 'json': return response(200, 'Blocked'); + case 'schema': return response(200, '{"featureVariables":[],"assignmentContext":""}'); + case 'timeout': return new Promise((_resolve, reject) => { + options.signal!.addEventListener('abort', () => reject(new Error('Aborted'))); + }); + } + }); + const pending = fetchAssignments(); + if (failure === 'timeout') { + await vi.advanceTimersByTimeAsync(1000); + } + const result = await pending; + await fetchAssignments(); + expect({ + urls: fetcher.fetch.mock.calls.map(([url]) => url), + identities: fetcher.fetch.mock.calls.map(([, options]) => JSON.parse(options.body!).userParams.copilottrackingid), + body: await result.json(), + firstAborted: fetcher.fetch.mock.calls[0][1].signal?.aborted, + }).toEqual({ + urls: [endpoints[0], endpoints[1], endpoints[1]], + identities: [undefined, undefined, undefined], + body: { featureVariables: {}, assignmentContext: '' }, + firstAborted: true, + }); + }); + } + + for (const winner of [0, 1, 2, undefined] as const) { + it(`staggers discovery and cancels outstanding work with ${winner === undefined ? 'a shared deadline' : `winner ${winner}`}`, async () => { + const { service, fetcher } = createService(); + await service.hasTreatments(); + vi.useFakeTimers(); + const start = Date.now(); + const starts: number[] = []; + const cancelled: string[] = []; + fetcher.fetch.mockImplementation(async (url, options) => { + starts.push(Date.now() - start); + if (winner !== undefined && url === endpoints[winner]) { + return response(); + } + return new Promise((_resolve, reject) => { + options.signal!.addEventListener('abort', () => { + cancelled.push(url); + reject(new Error('Aborted')); + }); + }); + }); + let settledAt: number | undefined; + const pending = fetchAssignments().finally(() => { settledAt = Date.now() - start; }); + const checked = winner === undefined + ? expect(pending).rejects.toThrow('Signed-out TAS discovery timed out') + : expect(pending).resolves.toMatchObject({ status: 200 }); + await vi.advanceTimersByTimeAsync(4999); + const beforeDeadline = settledAt; + await vi.advanceTimersByTimeAsync(1); + await checked; + await vi.advanceTimersByTimeAsync(1000); + const count = winner === undefined ? 3 : winner + 1; + expect({ + urls: fetcher.fetch.mock.calls.map(([url]) => url), + starts, + beforeDeadline, + settledAt, + cancelled, + timers: vi.getTimerCount(), + }).toEqual({ + urls: endpoints.slice(0, count), + starts: [0, 1000, 2000].slice(0, count), + beforeDeadline: winner === undefined ? undefined : winner * 1000, + settledAt: winner === undefined ? 5000 : winner * 1000, + cancelled: endpoints.slice(0, winner ?? 3), + timers: 0, + }); + }); + } + + it('a late successful loser cannot replace the remembered winner', async () => { + const { service, fetcher } = createService(); + await service.hasTreatments(); + vi.useFakeTimers(); + let complete: ((response: Response) => void) | undefined; + fetcher.fetch.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; })); + const pending = fetchAssignments(); + await vi.advanceTimersByTimeAsync(1000); + await pending; + complete!(response()); + await vi.advanceTimersByTimeAsync(0); + await fetchAssignments(); + expect(fetcher.fetch.mock.calls.map(([url]) => url)).toEqual([endpoints[0], endpoints[1], endpoints[1]]); + }); + + it('does not hedge a remembered host and rediscovers after it stops responding', async () => { + const { service, fetcher } = createService(); + await service.hasTreatments(); + vi.useFakeTimers(); + await fetchAssignments(); + fetcher.fetch.mockImplementationOnce(() => new Promise(() => { })); + const timedOut = expect(fetchAssignments()).rejects.toThrow('Signed-out TAS discovery timed out'); + await vi.advanceTimersByTimeAsync(5000); + await timedOut; + fetcher.fetch.mockImplementationOnce(() => new Promise(() => { })); + const rediscovered = fetchAssignments(); + await vi.advanceTimersByTimeAsync(1000); + await rediscovered; + expect(fetcher.fetch.mock.calls.map(([url]) => url)).toEqual([endpoints[0], endpoints[0], endpoints[0], endpoints[1]]); + }); + + it('rejects after one attempt per host, retries on the next fetch, and replaces a failed preferred host', async () => { + const { service, fetcher, tokens } = createService(); + await service.hasTreatments(); + let workingEndpoint: string | undefined; + fetcher.fetch.mockImplementation(async url => response(url === workingEndpoint ? 200 : 503)); + await expect(fetchAssignments()).rejects.toThrow('All signed-out TAS endpoints failed'); + workingEndpoint = endpoints[2]; + await fetchAssignments(); + workingEndpoint = endpoints[1]; + await fetchAssignments(); + await fetchAssignments(); + const discovered = fetcher.fetch.mock.calls.map(([url]) => url); + tokens.authenticationState = 'signedIn'; + tokens.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ endpoints: { exp: 'https://exp.individual.githubcopilot.com' } })); + await service.hasTreatments(); + await fetchAssignments(); + expect({ discovered, signedIn: fetcher.fetch.mock.calls.slice(discovered.length).map(([url]) => url) }).toEqual({ + discovered: [...endpoints, ...endpoints, endpoints[2], endpoints[0], endpoints[1], endpoints[1]], + signedIn: [endpoints[2]], + }); + }); + + it('does not continue discovery after sign-in revokes a pending anonymous fetch', async () => { + const { service, fetcher, tokens } = createService(); + await service.hasTreatments(); + let complete: ((response: Response) => void) | undefined; + fetcher.fetch.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; })); + const pending = fetchAssignments(); + tokens.authenticationState = 'signedIn'; + tokens.copilotToken = new CopilotToken(createTestExtendedTokenInfo({ endpoints: { exp: 'https://exp.individual.githubcopilot.com' } })); + await service.hasTreatments(); + complete!(response(503)); + await expect(pending).rejects.toThrow('Canceled'); + await fetchAssignments(); + expect(fetcher.fetch.mock.calls.map(([url]) => url)).toEqual([endpoints[0], endpoints[2]]); + }); +}); diff --git a/extensions/copilot/src/platform/test/node/services.ts b/extensions/copilot/src/platform/test/node/services.ts index ca834c8597b5..06dbcd1cc8db 100644 --- a/extensions/copilot/src/platform/test/node/services.ts +++ b/extensions/copilot/src/platform/test/node/services.ts @@ -102,6 +102,7 @@ import { SnapshotSearchService, TestingTabsAndEditorsService } from './simulatio import { TestChatAgentService } from './testChatAgentService'; import { TestWorkbenchService } from './testWorkbenchService'; import { TestWorkspaceService } from './testWorkspaceService'; +// eslint-disable-next-line local/code-no-restricted-zone-imports -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { IGrepResultService, NullGrepResultService } from '../../../extension/tools/node/grepResultService'; import { IRegionContextProviderService, NullRegionContextProviderService } from '../../languageContextProvider/common/regionContextProvider'; diff --git a/extensions/copilot/src/platform/test/node/simulationWorkspaceServices.ts b/extensions/copilot/src/platform/test/node/simulationWorkspaceServices.ts index 685e0b1faafe..b5533508e3b3 100644 --- a/extensions/copilot/src/platform/test/node/simulationWorkspaceServices.ts +++ b/extensions/copilot/src/platform/test/node/simulationWorkspaceServices.ts @@ -28,6 +28,7 @@ import { IFileSystemService } from '../../filesystem/common/fileSystemService'; import { FileType, RelativePattern } from '../../filesystem/common/fileTypes'; import { NodeFileSystemService } from '../../filesystem/node/fileSystemServiceImpl'; import { IGitService, RepoContext } from '../../git/common/gitService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Branch, Change, CommitOptions, CommitShortStat, DiffChange, Ref, RefQuery, Repository, RepositoryAccessDetails } from '../../git/vscode/git'; import { AbstractLanguageDiagnosticsService } from '../../languages/common/languageDiagnosticsService'; import { ILanguageFeaturesService } from '../../languages/common/languageFeaturesService'; diff --git a/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchChunkSearch.ts b/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchChunkSearch.ts index 01e689cd0d7c..034510b705cf 100644 --- a/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchChunkSearch.ts +++ b/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchChunkSearch.ts @@ -29,6 +29,7 @@ import { ConfigKey, ConfigTarget, IConfigurationService } from '../../../configu import { EmbeddingType } from '../../../embeddings/common/embeddingsComputer'; import { RelativePattern } from '../../../filesystem/common/fileTypes'; import { IGitService, ResolvedRepoRemoteInfo } from '../../../git/common/gitService'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change } from '../../../git/vscode/git'; import { logExecTime, LogExecTime } from '../../../log/common/logExecTime'; import { ILogService } from '../../../log/common/logService'; diff --git a/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/workspaceDiff.ts b/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/workspaceDiff.ts index 193ce9e176fe..2e831d0c2629 100644 --- a/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/workspaceDiff.ts +++ b/extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/workspaceDiff.ts @@ -10,6 +10,7 @@ import { Disposable } from '../../../../util/vs/base/common/lifecycle'; import { ResourceMap, ResourceSet } from '../../../../util/vs/base/common/map'; import { isEqualOrParent } from '../../../../util/vs/base/common/resources'; import { URI } from '../../../../util/vs/base/common/uri'; +// eslint-disable-next-line local/code-layering -- Pre-existing layering violation found when the zone check started resolving extensionless imports. import { Change } from '../../../git/vscode/git'; import { LogExecTime } from '../../../log/common/logExecTime'; import { ILogService } from '../../../log/common/logService'; diff --git a/extensions/copilot/src/util/common/test/shims/enums.ts b/extensions/copilot/src/util/common/test/shims/enums.ts index d7313e239117..9956ded1d218 100644 --- a/extensions/copilot/src/util/common/test/shims/enums.ts +++ b/extensions/copilot/src/util/common/test/shims/enums.ts @@ -71,4 +71,16 @@ export enum FileType { File = 1, Directory = 2, SymbolicLink = 64 +} + +export enum StructuralDiffClassification { + Declaration = 1, + Header = 2, + Implementation = 3, + Dependency = 4, + Other = 5, +} + +export enum StructuralDiffTag { + Test = 1, } \ No newline at end of file diff --git a/extensions/copilot/src/util/common/test/shims/vscodeTypesShim.ts b/extensions/copilot/src/util/common/test/shims/vscodeTypesShim.ts index 32398fd61846..bf8549bff8fa 100644 --- a/extensions/copilot/src/util/common/test/shims/vscodeTypesShim.ts +++ b/extensions/copilot/src/util/common/test/shims/vscodeTypesShim.ts @@ -20,7 +20,7 @@ import { SymbolInformation, SymbolKind } from '../../../vs/workbench/api/common/ import { EndOfLine, TextEdit } from '../../../vs/workbench/api/common/extHostTypes/textEdit'; import { AISearchKeyword, ChatErrorLevel, ChatInputNotificationSeverity, ChatQuestion, ChatQuestionType, ChatReferenceBinaryData, ChatReferenceDiagnostic, ChatRequestEditedFileEventKind, ChatRequestEditorData, ChatRequestNotebookData, ChatRequestTurn, ChatRequestTurn2, ChatResponseAnchorPart, ChatResponseAutoModeResolutionPart, ChatResponseClearToPreviousToolInvocationReason, ChatResponseCodeblockUriPart, ChatResponseCodeCitationPart, ChatResponseCommandButtonPart, ChatResponseConfirmationPart, ChatResponseExtensionsPart, ChatResponseExternalEditPart, ChatResponseFileTreePart, ChatResponseHookPart, ChatResponseInfoPart, ChatResponseMarkdownPart, ChatResponseMarkdownWithVulnerabilitiesPart, ChatResponseMovePart, ChatResponseNotebookEditPart, ChatResponseProgressPart, ChatResponseProgressPart2, ChatResponsePullRequestPart, ChatResponseQuestionCarouselPart, ChatResponseReferencePart, ChatResponseReferencePart2, ChatResponseTextEditPart, ChatResponseThinkingProgressPart, ChatResponseTurn, ChatResponseTurn2, ChatResponseVoiceProgressPart, ChatResponseWarningPart, ChatResponseWorkspaceEditPart, ChatSessionStatus, ChatSubagentToolInvocationData, ChatToolInvocationPart, ExcludeSettingOptions, LanguageModelChatApiType, LanguageModelChatMessage, LanguageModelChatMessageRole, LanguageModelChatToolMode, LanguageModelDataPart, LanguageModelDataPart2, LanguageModelError, LanguageModelPartAudience, LanguageModelPromptTsxPart, LanguageModelTextPart, LanguageModelTextPart2, LanguageModelThinkingPart, LanguageModelToolCallPart, LanguageModelToolExtensionSource, LanguageModelToolMCPSource, LanguageModelToolResult, LanguageModelToolResult2, LanguageModelToolResultPart, LanguageModelToolResultPart2, McpHttpServerDefinition, McpStdioServerDefinition, McpToolInvocationContentData, TextSearchMatch2 } from './chatTypes'; import { TextDocumentChangeReason, TextEditorSelectionChangeKind, WorkspaceEdit } from './editing'; -import { ChatLocation, ChatVariableLevel, DiagnosticSeverity, ExtensionMode, FileType, TextEditorCursorStyle, TextEditorLineNumbersStyle, TextEditorRevealType } from './enums'; +import { ChatLocation, ChatVariableLevel, DiagnosticSeverity, ExtensionMode, FileType, StructuralDiffClassification, StructuralDiffTag, TextEditorCursorStyle, TextEditorLineNumbersStyle, TextEditorRevealType } from './enums'; import { t } from './l10n'; import { NewSymbolName, NewSymbolNameTag, NewSymbolNameTriggerKind } from './newSymbolName'; import { TerminalShellExecutionCommandLineConfidence } from './terminal'; @@ -129,6 +129,8 @@ const shim: typeof vscodeTypes = { ChatRequestTurn2, LanguageModelError: LanguageModelError as any, // Some difference in the definition of Error is breaking this SymbolKind, + StructuralDiffClassification, + StructuralDiffTag, SnippetString, SnippetTextEdit, FileType, diff --git a/extensions/copilot/src/vscodeTypes.ts b/extensions/copilot/src/vscodeTypes.ts index be04f5eac831..93b46c3889b9 100644 --- a/extensions/copilot/src/vscodeTypes.ts +++ b/extensions/copilot/src/vscodeTypes.ts @@ -108,6 +108,8 @@ export import ChatResponseTurn2 = vscode.ChatResponseTurn2; export import ChatRequestTurn2 = vscode.ChatRequestTurn2; export import LanguageModelError = vscode.LanguageModelError; export import SymbolKind = vscode.SymbolKind; +export import StructuralDiffClassification = vscode.StructuralDiffClassification; +export import StructuralDiffTag = vscode.StructuralDiffTag; export import SnippetString = vscode.SnippetString; export import SnippetTextEdit = vscode.SnippetTextEdit; export import FileType = vscode.FileType; diff --git a/extensions/copilot/test/base/simulationContext.ts b/extensions/copilot/test/base/simulationContext.ts index 6dfa2d26de31..36be9d121e20 100644 --- a/extensions/copilot/test/base/simulationContext.ts +++ b/extensions/copilot/test/base/simulationContext.ts @@ -29,8 +29,6 @@ import { ICompletionsFetchService } from '../../src/platform/nesFetch/common/com import { CompletionsFetchService } from '../../src/platform/nesFetch/node/completionsFetchServiceImpl'; import { IReleaseNotesService } from '../../src/platform/releaseNotes/common/releaseNotesService'; import { ReleaseNotesService } from '../../src/platform/releaseNotes/vscode/releaseNotesServiceImpl'; -import { IDocsSearchClient } from '../../src/platform/remoteSearch/common/codeOrDocsSearchClient'; -import { DocsSearchClient } from '../../src/platform/remoteSearch/node/codeOrDocsSearchClientImpl'; import { IReviewService } from '../../src/platform/review/common/reviewService'; import { constructGlobalStateMemento, MockExtensionContext } from '../../src/platform/test/node/extensionContext'; import { TestingServiceCollection } from '../../src/platform/test/node/services'; @@ -228,7 +226,6 @@ export async function createSimulationAccessor( } testingServiceCollection.define(IEmbeddingsComputer, new SyncDescriptor(RemoteEmbeddingsComputer)); - testingServiceCollection.define(IDocsSearchClient, new SyncDescriptor(DocsSearchClient)); testingServiceCollection.define(IChunkingEndpointClient, new SyncDescriptor(ChunkingEndpointClientImpl)); const useRemoteEmbeddingsIndexCache = opts.languageModelCacheMode === CacheMode.Disable; diff --git a/extensions/copilot/tsconfig.json b/extensions/copilot/tsconfig.json index 0692c3a7a99f..0deb022f4477 100644 --- a/extensions/copilot/tsconfig.json +++ b/extensions/copilot/tsconfig.json @@ -33,6 +33,7 @@ "src/extension/test/node/fixtures/**/*", "src/extension/prompts/node/test/fixtures/**/*", "src/extension/typescriptContext/serverPlugin/fixtures/**", + "src/extension/typescriptContext/vscode-node/ts7/fixtures/**", "src/extension/completions-core/vscode-node/extension/src/copilotPanel/webView/suggestionsPanelWebview.ts" ] } diff --git a/extensions/emmet/src/abbreviationActions.ts b/extensions/emmet/src/abbreviationActions.ts index aa9ea7bb7cfd..7a5454a2aabc 100644 --- a/extensions/emmet/src/abbreviationActions.ts +++ b/extensions/emmet/src/abbreviationActions.ts @@ -220,7 +220,7 @@ export async function wrapWithAbbreviation(args: any): Promise { if (previewChanges) { const expandAbbrList: ExpandAbbreviationInput[] = rangesToReplace.map(rangesAndContent => - ({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent, baseIndent: rangesAndContent.baseIndent }) + ({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent, baseIndent: rangesAndContent.baseIndent }) ); inPreviewMode = true; @@ -228,7 +228,7 @@ export async function wrapWithAbbreviation(args: any): Promise { } const expandAbbrList: ExpandAbbreviationInput[] = rangesToReplace.map(rangesAndContent => - ({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent }) + ({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent }) ); if (inPreviewMode) { diff --git a/extensions/esbuild-extension-common.mts b/extensions/esbuild-extension-common.mts index 5b967a9140e7..85252f6b1b2f 100644 --- a/extensions/esbuild-extension-common.mts +++ b/extensions/esbuild-extension-common.mts @@ -21,7 +21,7 @@ function resolveBaseOptions(config: ExtensionRunConfig): esbuild.BuildOptions { treeShaking: true, sourcemap: true, target: ['es2024'], - external: ['vscode'], + external: ['vscode', '@vscode/internal-github'], format: config.format ?? 'cjs', logOverride: { 'import-is-undefined': 'error', diff --git a/extensions/git/src/commands.ts b/extensions/git/src/commands.ts index 5d5571980b69..60e019baa04c 100644 --- a/extensions/git/src/commands.ts +++ b/extensions/git/src/commands.ts @@ -3553,7 +3553,15 @@ export class CommandCenter { } try { - await repository.createWorktree({ path: worktreePath, branch, commitish: commitish }); + const createdWorktreePath = await repository.createWorktree({ path: worktreePath, branch, commitish: commitish }); + + // Remember the location picked by the user so that it is used as the default next time + const worktreeRootStorageKey = `${Repository.WORKTREE_ROOT_STORAGE_KEY}:${repository.root}`; + const worktreeRoot = path.dirname(createdWorktreePath); + const lastWorktreeRoot = this.globalState.get(worktreeRootStorageKey); + if (!lastWorktreeRoot || !pathEquals(worktreeRoot, lastWorktreeRoot)) { + await this.globalState.update(worktreeRootStorageKey, worktreeRoot); + } } catch (err) { if (err instanceof GitError && err.gitErrorCode === GitErrorCodes.WorktreeAlreadyExists) { await this.handleWorktreeAlreadyExists(err); @@ -4734,16 +4742,9 @@ export class CommandCenter { return undefined; } - // Stash - const regex = /^stash@{(\d+)}$/; - const match = regex.exec(stashUri.ref); - if (!match) { - return undefined; - } - - const [, index] = match; + // Stash (the uri references the stash commit hash since the stash index changes) const stashes = await repository.getStashes(); - const stash = stashes.find(stash => stash.index === parseInt(index)); + const stash = stashes.find(stash => stash.hash === stashUri.ref); if (!stash) { return undefined; } @@ -4771,7 +4772,7 @@ export class CommandCenter { } const title = `Git Stash #${stash.index}: ${stash.description}`; - const multiDiffSourceUri = toGitUri(Uri.file(repository.root), `stash@{${stash.index}}`, { scheme: 'git-stash' }); + const multiDiffSourceUri = toGitUri(Uri.file(repository.root), stash.hash, { scheme: 'git-stash' }); const resources: { originalUri: Uri | undefined; modifiedUri: Uri | undefined }[] = []; for (const change of stashChanges) { diff --git a/extensions/git/src/fileSystemProvider.ts b/extensions/git/src/fileSystemProvider.ts index 4d96a66e05e2..31055d4a3fa8 100644 --- a/extensions/git/src/fileSystemProvider.ts +++ b/extensions/git/src/fileSystemProvider.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import * as path from 'path'; import { workspace, Uri, Disposable, Event, EventEmitter, window, FileSystemProvider, FileChangeEvent, FileStat, FileType, FileChangeType, FileSystemError, LogOutputChannel } from 'vscode'; import { debounce, throttle } from './decorators'; import { fromGitUri, toGitUri } from './uri'; @@ -115,10 +116,13 @@ export class GitFileSystemProvider implements FileSystemProvider { private cleanup(): void { const now = new Date().getTime(); const cache = new Map(); + // A loaded Git document needs change events even when its file is not open, for example when the Source Control + // view compares the index with HEAD. + const loadedDocuments = new Set(workspace.textDocuments.map(d => d.uri.toString())); for (const row of this.cache.values()) { const { path } = fromGitUri(row.uri); - const isOpen = workspace.textDocuments + const isOpen = loadedDocuments.has(row.uri.toString()) || workspace.textDocuments .filter(d => d.uri.scheme === 'file') .some(d => pathEquals(d.uri.fsPath, path)); @@ -146,6 +150,20 @@ export class GitFileSystemProvider implements FileSystemProvider { this.logger.info(`[GitFileSystemProvider][getOrOpenRepository] Opening repository for ${fsPath}`); await this.model.openRepository(fsPath, true, true); + return this.model.getRepository(uri); + } + + // The repository might not be discovered by the initial repository scan (ex: it is + // nested deeper than `git.repositoryScanMaxDepth`) and is only opened when a file from + // it is visible in a text editor. Editors that only reference git resources (ex: the + // merge editor restored after a window reload) would not open it, so we open it using + // the same rules that are used for visible text editors. + const autoRepositoryDetection = workspace.getConfiguration('git').get('autoRepositoryDetection'); + if (workspace.isTrusted && (autoRepositoryDetection === true || autoRepositoryDetection === 'openEditors')) { + const fsPath = typeof uri === 'string' ? uri : path.dirname(fromGitUri(uri).path); + this.logger.trace(`[GitFileSystemProvider][getOrOpenRepository] Opening repository for ${fsPath}`); + + await this.model.openRepository(fsPath); repository = this.model.getRepository(uri); } diff --git a/extensions/git/src/git.ts b/extensions/git/src/git.ts index 2c0e5c4882f6..86aa525def19 100644 --- a/extensions/git/src/git.ts +++ b/extensions/git/src/git.ts @@ -1074,6 +1074,17 @@ export function parseLsFiles(raw: string): LsFilesElement[] { .map(([, mode, object, stage, file]) => ({ mode, object, stage, file })); } +/** + * Returns the path of a linked worktree given the content of its `gitdir` file + * (`/worktrees//gitdir`). The content is relative to the folder + * containing the `gitdir` file when the worktree uses relative paths (git >= 2.48). + */ +export function getWorktreePathFromGitdir(worktreeGitDirPath: string, gitdirContent: string): string { + // Remove '/.git' suffix + const worktreePath = gitdirContent.replace(/\/.git.*$/, ''); + return path.isAbsolute(worktreePath) ? worktreePath : path.resolve(worktreeGitDirPath, worktreePath); +} + const stashRegex = /([0-9a-f]{40})\n(.*)\nstash@{(\d+)}\n(WIP\s)?on\s([^:]+):\s(.*)\n(\d+)\n(\d+)(?:\x00)/gmi; function parseGitStashes(raw: string): Stash[] { @@ -2506,17 +2517,16 @@ export class Repository { env: { 'GIT_HTTP_USER_AGENT': this.git.userAgent } }; - args.push(options.remote); - - for (const tag of options.tags) { - args.push(`refs/tags/${tag}:refs/tags/${tag}`); - } - if (options.force) { args.push('--force'); } - await this.exec(args, spawnOptions); + args.push(options.remote); + + const refspecs = options.tags.map(tag => `refs/tags/${tag}:refs/tags/${tag}`); + for (const chunk of splitInChunks(refspecs, MAX_CLI_LENGTH)) { + await this.exec([...args, ...chunk], spawnOptions); + } } async pull(rebase?: boolean, remote?: string, branch?: string, options: PullOptions = {}): Promise { @@ -3154,8 +3164,7 @@ export class Repository { result.push({ name: dirent.name, - // Remove '/.git' suffix - path: gitdirContent.replace(/\/.git.*$/, ''), + path: getWorktreePathFromGitdir(path.dirname(gitdirPath), gitdirContent), // Remove 'ref: ' prefix ref: headContent.replace(/^ref: /, ''), // Detached if HEAD does not start with 'ref: ' diff --git a/extensions/git/src/historyProvider.ts b/extensions/git/src/historyProvider.ts index 8b36afcacaab..8eabc3e7d41d 100644 --- a/extensions/git/src/historyProvider.ts +++ b/extensions/git/src/historyProvider.ts @@ -119,8 +119,9 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec historyItemRefId = `refs/heads/${this.repository.HEAD.name}`; historyItemRefName = this.repository.HEAD.name; - // Remote - if (this.repository.HEAD.upstream) { + // Remote (skip the upstream if it could not be resolved, ex: `remote = .` + // with `merge` pointing to a ref that is not a local branch) + if (this.repository.HEAD.upstream?.commit) { if (this.repository.HEAD.upstream.remote === '.') { // Local branch this._currentHistoryItemRemoteRef = { diff --git a/extensions/git/src/repository.ts b/extensions/git/src/repository.ts index ccb262ad0e64..e16d5b727641 100644 --- a/extensions/git/src/repository.ts +++ b/extensions/git/src/repository.ts @@ -1982,12 +1982,6 @@ export class Repository implements Disposable { // Create the worktree await this.repository.addWorktree({ path: worktreePath!, commitish: commitish ?? 'HEAD', branch, noTrack }); - // Update worktree root in global state - const newWorktreeRoot = path.dirname(worktreePath!); - if (defaultWorktreeRoot && !pathEquals(newWorktreeRoot, defaultWorktreeRoot)) { - this.globalState.update(`${Repository.WORKTREE_ROOT_STORAGE_KEY}:${this.root}`, newWorktreeRoot); - } - // Worktree setup is best effort and must not delay or fail creation. this._setupWorktree(worktreePath!).then(undefined, err => { this.logger.warn(`[Repository][createWorktree] Failed to set up worktree '${worktreePath}': ${err}`); @@ -3510,7 +3504,10 @@ export class Repository implements Disposable { // Notification const replaceLocalTags = l10n.t('Replace Local Tag(s)'); const replaceLocalTagsAlways = l10n.t('Always Replace Local Tag(s)'); - const message = l10n.t('Unable to pull from remote repository due to conflicting tag(s): {0}. Would you like to resolve the conflict by replacing the local tag(s)?', tags.join(', ')); + const maxTags = 5; + const message = tags.length <= maxTags + ? l10n.t('Unable to pull from remote repository due to conflicting tag(s): {0}. Would you like to resolve the conflict by replacing the local tag(s)?', tags.join(', ')) + : l10n.t('Unable to pull from remote repository due to conflicting tag(s): {0} and {1} more. Would you like to resolve the conflict by replacing the local tag(s)?', tags.slice(0, maxTags).join(', '), tags.length - maxTags); const choice = await window.showErrorMessage(message, { modal: true }, replaceLocalTags, replaceLocalTagsAlways); if (choice !== replaceLocalTags && choice !== replaceLocalTagsAlways) { diff --git a/extensions/git/src/repositoryCache.ts b/extensions/git/src/repositoryCache.ts index 8f03d8998c77..aa49eb29687d 100644 --- a/extensions/git/src/repositoryCache.ts +++ b/extensions/git/src/repositoryCache.ts @@ -65,7 +65,7 @@ export class RepositoryCache { } return Array.from(this._recentRepositories.entries()).map(([rootPath, lastAccessTime]) => - ({ rootUri: Uri.file(rootPath), lastAccessTime } satisfies RepositoryAccessDetails)); + ({ rootUri: Uri.file(rootPath), lastAccessTime } satisfies RepositoryAccessDetails)); } constructor(public readonly _globalState: Memento, private readonly _logger: LogOutputChannel) { diff --git a/extensions/git/src/test/git.test.ts b/extensions/git/src/test/git.test.ts index 1fe840a364a7..3f95d80e128d 100644 --- a/extensions/git/src/test/git.test.ts +++ b/extensions/git/src/test/git.test.ts @@ -4,8 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import 'mocha'; -import { findGit, Git, GitStatusParser, parseGitCommits, parseGitFileLog, parseGitmodules, parseLsTree, parseLsFiles, parseGitRemotes, parseCoAuthors } from '../git'; +import { findGit, Git, GitStatusParser, parseGitCommits, parseGitFileLog, parseGitmodules, parseLsTree, parseLsFiles, parseGitRemotes, parseCoAuthors, getWorktreePathFromGitdir } from '../git'; import * as assert from 'assert'; +import * as path from 'path'; import { LogOutputChannel, window } from 'vscode'; import { splitInChunks } from '../util'; @@ -654,6 +655,20 @@ suite('git', () => { }); }); + suite('getWorktreePathFromGitdir', () => { + test('absolute and relative gitdir', function () { + const worktreeGitDirPath = path.resolve('/repo/.git/worktrees/feature'); + + assert.deepStrictEqual([ + getWorktreePathFromGitdir(worktreeGitDirPath, '/worktrees/feature/.git'), + getWorktreePathFromGitdir(worktreeGitDirPath, '../../../../worktrees/feature/.git') + ], [ + '/worktrees/feature', + path.resolve('/worktrees/feature') + ]); + }); + }); + suite('parseCoAuthors', () => { test('no co-authors', function () { assert.deepStrictEqual(parseCoAuthors('This is a commit message.'), []); diff --git a/extensions/markdown-language-features/markdown-editor-src/editor.ts b/extensions/markdown-language-features/markdown-editor-src/editor.ts index 7fabde69f3bb..c18d6305a2a1 100644 --- a/extensions/markdown-language-features/markdown-editor-src/editor.ts +++ b/extensions/markdown-language-features/markdown-editor-src/editor.ts @@ -459,7 +459,20 @@ class Editor extends Disposable { window.removeEventListener('blur', postEditorFocus); }, }); + // When the webview gets focus, for example right after the editor opens, and nothing in it + // has focus yet, put the caret into the document so typing works right away. + const focusEditorOnWindowFocus = (): void => { + const active = document.activeElement; + if (!this.model.readonlyMode.get() && (!active || active === document.body || active === document.documentElement)) { + view.focus(); + } + }; + window.addEventListener('focus', focusEditorOnWindowFocus); + this._register({ dispose: () => window.removeEventListener('focus', focusEditorOnWindowFocus) }); host.appendChild(view.element); + if (document.hasFocus()) { + focusEditorOnWindowFocus(); + } postEditorFocus(); // Render comments as the VS Code V2 markdown cards. The card colours come diff --git a/extensions/markdown-language-features/src/preview/markdownEditorProvider.ts b/extensions/markdown-language-features/src/preview/markdownEditorProvider.ts index 8ad660bd47e2..cd22ee914710 100644 --- a/extensions/markdown-language-features/src/preview/markdownEditorProvider.ts +++ b/extensions/markdown-language-features/src/preview/markdownEditorProvider.ts @@ -362,7 +362,18 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT this.#wireSingle(document, webviewPanel, originalDocument, codeBlockEditorProviders, webview); } - #configureWebview(document: vscode.TextDocument, editorWebview: AuthenticatedWebview, editEpoch: number): void { + /** + * New untitled and empty documents open in edit mode: there is nothing to read yet, so the + * user wants to write. Other documents open in the last chosen mode. + */ + #getInitialReadonly(document: vscode.TextDocument): boolean { + if (document.uri.scheme === 'untitled' || document.getText().length === 0) { + return false; + } + return this.#globalState.get(MarkdownEditorProvider.#readonlyStateKey, true); + } + + #configureWebview(document: vscode.TextDocument, editorWebview: AuthenticatedWebview, editEpoch: number, readonly: boolean): void { const webview = editorWebview.webview; const codeBlockEditorResourceRoots = vscode.workspace.isTrusted ? this.#contributions.contributions.codeBlockEditorProviders.map(provider => provider.extension.extensionUri) @@ -373,7 +384,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT includeWorkspaceResources: vscode.workspace.isTrusted, }), }; - webview.html = this.#getHtml(document, webview, editorWebview.messageSecret, editEpoch); + webview.html = this.#getHtml(document, webview, editorWebview.messageSecret, editEpoch, readonly); } #wireSingle( @@ -386,7 +397,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT let expectedWebviewContent: { readonly content: string; readonly epoch: number } | undefined; let webviewText = document.getText(); let webviewReady = false; - let readonly = this.#globalState.get(MarkdownEditorProvider.#readonlyStateKey, true); + let readonly = this.#getInitialReadonly(document); let codeBlockEditorProviders: readonly CodeBlockEditorProviderDefinition[] | undefined; let contributionUpdate = 0; const resolveCancellation = new vscode.CancellationTokenSource(); @@ -683,7 +694,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT expectedWebviewContent = undefined; webviewText = document.getText(); editorWebview.reset(); - this.#configureWebview(document, editorWebview, epoch); + this.#configureWebview(document, editorWebview, epoch, readonly); await refreshCodeBlockEditorProviders(true, true); }); }; @@ -742,7 +753,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT reloadWebview(); }); - this.#configureWebview(document, editorWebview, editQueue.epoch); + this.#configureWebview(document, editorWebview, editQueue.epoch, readonly); webviewPanel.onDidDispose(() => { navigation.dispose(); @@ -1149,7 +1160,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT }); } - #getHtml(document: vscode.TextDocument, webview: vscode.Webview, messageSecret: string, editEpoch: number): string { + #getHtml(document: vscode.TextDocument, webview: vscode.Webview, messageSecret: string, editEpoch: number, readonly: boolean): string { const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this.#mediaRoot, 'editor.js')); const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this.#mediaRoot, 'editor.css')); const baseUri = webview.asWebviewUri(document.uri); @@ -1164,7 +1175,7 @@ export class MarkdownEditorProvider extends Disposable implements vscode.CustomT content: document.getText(), documentVersion: document.version, editEpoch, - readonly: this.#globalState.get(MarkdownEditorProvider.#readonlyStateKey, true), + readonly, richLinksEnabled: vscode.workspace.getConfiguration('markdown').get('experimental.richLinks.enabled', true), linkPresentationRules: vscode.window.linkPresentationRules.map(rule => ({ id: rule.id, diff --git a/extensions/markdown-language-features/src/test/documentLink.test.ts b/extensions/markdown-language-features/src/test/documentLink.test.ts index 0000069a6600..2c754aa3b687 100644 --- a/extensions/markdown-language-features/src/test/documentLink.test.ts +++ b/extensions/markdown-language-features/src/test/documentLink.test.ts @@ -58,6 +58,52 @@ async function getLinksForFile(file: vscode.Uri): Promise assertActiveDocumentUri(workspaceFile('b.md')); }); + // Re-enable when the server dependency includes microsoft/vscode-markdown-languageserver#28. + test.skip('Should update custom agent links after an unsaved edit', async () => { + const file = workspaceFile('linkProbe.agent.md'); + await vscode.workspace.fs.writeFile(file, Buffer.from(`${new Array(53).fill('').join('\n')}\n[README](b.md)`)); + + try { + const document = await vscode.workspace.openTextDocument(file); + const editor = await vscode.window.showTextDocument(document); + assert.strictEqual(document.languageId, 'chatagent'); + + const [oldLink] = await getLinksForFile(file); + assert.deepStrictEqual({ + startLine: oldLink.range.start.line, + text: document.getText(oldLink.range), + }, { + startLine: 53, + text: 'b.md', + }); + + const updatedContent = [ + '---', + 'name: LinkProbe', + 'description: Test live links', + 'target: github-copilot', + '---', + '', + '[README](b.md)', + ].join('\n'); + await editor.edit(edit => edit.replace(new vscode.Range(0, 0, document.lineCount, 0), updatedContent)); + + const [link] = await getLinksForFile(file); + assert.deepStrictEqual({ + startLine: link.range.start.line, + text: document.getText(link.range), + }, { + startLine: 6, + text: 'b.md', + }); + await executeLink(link); + assertActiveDocumentUri(workspaceFile('b.md')); + } finally { + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await vscode.workspace.fs.delete(file); + } + }); + test('Should navigate to markdown file with leading /', async () => { await withFileContents(testFileA, '[b](./b.md)'); diff --git a/extensions/markdown-language-features/test-workspace/checkbox-count-extension/package.json b/extensions/markdown-language-features/test-workspace/checkbox-count-extension/package.json index 0c17d7b033c5..3e93cead5d2a 100644 --- a/extensions/markdown-language-features/test-workspace/checkbox-count-extension/package.json +++ b/extensions/markdown-language-features/test-workspace/checkbox-count-extension/package.json @@ -3,7 +3,6 @@ "displayName": "Markdown Checkbox Count Demo", "description": "Demonstrates a Markdown code block editor communicating with its extension host.", "version": "0.0.1", - "packageManager": "pnpm@12.16.0", "publisher": "vscode-samples", "private": true, "engines": { diff --git a/extensions/markdown-math/esbuild.notebook.mts b/extensions/markdown-math/esbuild.notebook.mts index 190924f79388..7c9b66189bd7 100644 --- a/extensions/markdown-math/esbuild.notebook.mts +++ b/extensions/markdown-math/esbuild.notebook.mts @@ -11,7 +11,9 @@ const srcDir = path.join(import.meta.dirname, 'notebook'); const outDir = path.join(import.meta.dirname, 'notebook-out'); function postBuild(outDir: string) { - const katexDir = resolvePackageDirectory(import.meta.dirname, 'katex'); + // The katex of @vscode/markdown-it-katex, whose JavaScript the notebook bundles + const markdownItKatexDir = fs.realpathSync(resolvePackageDirectory(import.meta.dirname, '@vscode/markdown-it-katex')); + const katexDir = resolvePackageDirectory(markdownItKatexDir, 'katex'); fs.copyFileSync( path.join(katexDir, 'dist', 'katex.min.css'), path.join(outDir, 'katex.min.css')); diff --git a/extensions/mermaid-markdown-features/package.json b/extensions/mermaid-markdown-features/package.json index 03f16f8780ca..80723d39bdde 100644 --- a/extensions/mermaid-markdown-features/package.json +++ b/extensions/mermaid-markdown-features/package.json @@ -267,6 +267,7 @@ "@types/node": "24.x", "@types/vscode-notebook-renderer": "^1.72.0", "@vscode/codicons": "^0.0.36", + "@vscode/hubrpc": "0.0.2-54", "playwright": "^1.61.1", "zod": "4.4.3" }, diff --git a/extensions/mermaid-markdown-features/preview-src/shared/index.ts b/extensions/mermaid-markdown-features/preview-src/shared/index.ts index 50b047a87f39..e7be880f7c73 100644 --- a/extensions/mermaid-markdown-features/preview-src/shared/index.ts +++ b/extensions/mermaid-markdown-features/preview-src/shared/index.ts @@ -187,7 +187,18 @@ export function buildMermaidConfig( return { startOnLoad: false, look: 'classic', - flowchart: { subGraphTitleMargin: { ...subgraphTitleMargin } }, + // Mermaid 12 lays out these diagram types with ELK unless a diagram sets a layout. ELK lays out diagrams with many + // edges in a single task that can block the webview for many seconds, so keep them on dagre, the layout before + // Mermaid 12 (use case and agentflow diagrams are new in Mermaid 12). The layout is set per diagram type rather + // than globally, so diagram types with their own default layout, such as mindmaps and swimlanes, keep it. + // Diagrams can still opt into `layout: elk`. + flowchart: { layout: 'dagre', subGraphTitleMargin: { ...subgraphTitleMargin } }, + class: { layout: 'dagre' }, + state: { layout: 'dagre' }, + er: { layout: 'dagre' }, + requirement: { layout: 'dagre' }, + usecase: { layout: 'dagre' }, + agentflow: { layout: 'dagre' }, ...vsCodeThemeTracker.resolveMermaidTheme(extensionConfig), }; } diff --git a/extensions/mermaid-markdown-features/scripts/markdownEditor.browser.test.mts b/extensions/mermaid-markdown-features/scripts/markdownEditor.browser.test.mts index 6acebed14748..55aa44f846a7 100644 --- a/extensions/mermaid-markdown-features/scripts/markdownEditor.browser.test.mts +++ b/extensions/mermaid-markdown-features/scripts/markdownEditor.browser.test.mts @@ -100,6 +100,20 @@ it('renders diagrams at their natural size in the VS Code theme, and follows edi await page.evaluate(() => window.mermaidTest.setText('zenuml\n Controller.Get(id) {\n Service.Get(id)\n }')); await frame.locator('svg').filter({ hasText: 'Controller' }).waitFor(); + // Diagram types with their own default layout keep it rather than dagre: a mindmap spreads its children around + // its root (cose-bilkent) instead of in a row below it, and a swimlane diagram draws its subgraphs as lanes. + await page.evaluate(() => window.mermaidTest.setText('mindmap\n root((Project))\n Source\n Preview\n Tests\n Docs')); + await frame.locator('svg').filter({ hasText: 'Docs' }).waitFor(); + const mindmap = await frame.evaluate(() => { + const nodes = [...document.querySelectorAll('g.node')]; + const root = nodes.find(node => node.textContent!.trim() === 'Project')!.getBoundingClientRect(); + const children = nodes.filter(node => node.textContent!.trim() !== 'Project').map(node => node.getBoundingClientRect()); + return { childAboveRoot: children.some(child => child.bottom <= root.top), childBelowRoot: children.some(child => child.top >= root.bottom) }; + }); + await page.evaluate(() => window.mermaidTest.setText('swimlane-beta\n subgraph Dev[Developer]\n A[Write code]\n end\n subgraph CI[Build]\n B[Run tests]\n end\n A --> B')); + await frame.locator('svg').filter({ hasText: 'Run tests' }).waitFor(); + assert.deepEqual({ ...mindmap, lanes: await frame.locator('g.cluster.swimlane').count() }, { childAboveRoot: true, childBelowRoot: true, lanes: 2 }); + // Subgraph titles stay centered unless an edge crosses them there, so the title of a subgraph whose // edge enters at its top center moves to the top left. A subgraph narrower than its title is widened // to keep the title off its sides. @@ -139,7 +153,7 @@ it('renders diagrams at their natural size in the VS Code theme, and follows edi // An edge that cannot avoid a title passes behind it: no pixel of the (red) edge shows over the title's // text where the edge crosses it, while the edge's arrowhead below the title stays whole. - await page.evaluate(() => window.mermaidTest.setText('---\nconfig:\n layout: dagre\n---\nflowchart TD\n A[Source] --> B\n subgraph Long[A subgraph title that is much wider than its content]\n B[Step]\n end')); + await page.evaluate(() => window.mermaidTest.setText('flowchart TD\n A[Source] --> B\n subgraph Long[A subgraph title that is much wider than its content]\n B[Step]\n end')); await frame.locator('svg').filter({ hasText: 'much wider' }).waitFor(); const crossing = await frame.evaluate(() => { const title = document.querySelector('.cluster-label foreignObject')!.getBoundingClientRect(); @@ -180,7 +194,7 @@ it('renders diagrams at their natural size in the VS Code theme, and follows edi // Class diagram namespaces get the same treatment as subgraphs. The edge entering this one runs just // inside the left-aligned position, so the title moves a little closer to the border instead. - await page.evaluate(() => window.mermaidTest.setText('---\nconfig:\n layout: dagre\n---\nclassDiagram\n namespace Rendering {\n class Renderer\n }\n Client --> Renderer')); + await page.evaluate(() => window.mermaidTest.setText('classDiagram\n namespace Rendering {\n class Renderer\n }\n Client --> Renderer')); await frame.locator('svg').filter({ hasText: 'Rendering' }).waitFor(); const namespaceTitle = await frame.evaluate(() => { const cluster = document.querySelector('g.cluster')!; @@ -202,7 +216,7 @@ it('renders diagrams at their natural size in the VS Code theme, and follows edi // A subgraph that edges attach to keeps its sides, so the edges still end at its border rather than // inside it, even though its title is wider than its content. - await page.evaluate(() => window.mermaidTest.setText('---\nconfig:\n layout: dagre\n---\nflowchart LR\n A[Source] --> S\n subgraph S[A subgraph title wider than its content]\n B[Step]\n end\n S --> C[Next]')); + await page.evaluate(() => window.mermaidTest.setText('flowchart LR\n A[Source] --> S\n subgraph S[A subgraph title wider than its content]\n B[Step]\n end\n S --> C[Next]')); await frame.locator('svg').filter({ hasText: 'wider than its content' }).waitFor(); const attachedEdges = await frame.evaluate(() => { const box = document.querySelector('g.cluster rect')!.getBoundingClientRect(); diff --git a/extensions/pnpm-lock.yaml b/extensions/pnpm-lock.yaml index 8227fe225bdd..86e18e5a7ea6 100644 --- a/extensions/pnpm-lock.yaml +++ b/extensions/pnpm-lock.yaml @@ -568,6 +568,9 @@ importers: '@vscode/codicons': specifier: ^0.0.36 version: 0.0.36 + '@vscode/hubrpc': + specifier: 0.0.2-54 + version: 0.0.2-54(zod@4.4.3) playwright: specifier: ^1.61.1 version: 1.61.1 diff --git a/extensions/terminal-suggest/src/completions/npm.ts b/extensions/terminal-suggest/src/completions/npm.ts index f031d467affc..0c06d9723d0b 100644 --- a/extensions/terminal-suggest/src/completions/npm.ts +++ b/extensions/terminal-suggest/src/completions/npm.ts @@ -211,7 +211,7 @@ export const npmScriptsGenerator: Fig.Generator = { script: [ 'bash', '-c', - 'until [[ -f package.json ]] || [[ $PWD = \' / \' ]]; do cd ..; done; cat package.json', + 'until [[ -f package.json ]] || [[ $PWD = \'/\' ]]; do cd ..; done; cat package.json', ], postProcess: function (out, [npmClient]) { if (out.trim() === '') { diff --git a/extensions/terminal-suggest/src/completions/yarn.ts b/extensions/terminal-suggest/src/completions/yarn.ts index 7b0750ba2b1e..bb4bcde07e3b 100644 --- a/extensions/terminal-suggest/src/completions/yarn.ts +++ b/extensions/terminal-suggest/src/completions/yarn.ts @@ -141,7 +141,7 @@ export const dependenciesGenerator: Fig.Generator = { script: [ 'bash', '-c', - 'until [[ -f package.json ]] || [[ $PWD = \' / \' ]]; do cd ..; done; cat package.json', + 'until [[ -f package.json ]] || [[ $PWD = \'/\' ]]; do cd ..; done; cat package.json', ], postProcess: function (out, context = []) { if (out.trim() === '') { diff --git a/extensions/typescript-language-features/src/test/smoke/documentSymbol.test.ts b/extensions/typescript-language-features/src/test/smoke/documentSymbol.test.ts new file mode 100644 index 000000000000..56b3f19dccb2 --- /dev/null +++ b/extensions/typescript-language-features/src/test/smoke/documentSymbol.test.ts @@ -0,0 +1,61 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import 'mocha'; +import * as vscode from 'vscode'; +import { disposeAll } from '../../utils/dispose'; +import { createRandomFile, deleteFile, wait } from '../testUtils'; + +suite('TypeScript Document Symbols', () => { + setup(async () => { + await vscode.extensions.getExtension('vscode.typescript-language-features')!.activate(); + }); + + test('should refresh symbols when a document is reopened after an external edit', async () => { + const file = await createRandomFile('export const original = 1;', 'ts'); + const disposables: vscode.Disposable[] = []; + try { + // Avoid openTextDocument's temporary model reference when testing close. + await vscode.commands.executeCommand('vscode.open', file); + const document = vscode.window.activeTextEditor?.document; + assert.ok(document); + + // TypeScript providers are registered lazily after activation. + let originalSymbols: vscode.DocumentSymbol[] | undefined; + for (let attempt = 0; attempt < 100; ++attempt) { + originalSymbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', file); + if (originalSymbols?.length) { + break; + } + await wait(100); + } + assert.deepStrictEqual(originalSymbols?.map(symbol => symbol.name), ['original']); + + const closed = new Promise(resolve => { + vscode.workspace.onDidCloseTextDocument(closedDocument => { + if (closedDocument === document) { + resolve(); + } + }, undefined, disposables); + }); + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await closed; + + await vscode.workspace.fs.writeFile(file, Buffer.from('export const updated = 2;')); + const reopened = await vscode.workspace.openTextDocument(file); + await vscode.window.showTextDocument(reopened); + assert.deepStrictEqual( + { version: reopened.version, text: reopened.getText() }, + { version: document.version, text: 'export const updated = 2;' }); + const symbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', file); + assert.deepStrictEqual(symbols?.map(symbol => symbol.name), ['updated']); + } finally { + disposeAll(disposables); + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await deleteFile(file); + } + }); +}); diff --git a/extensions/typescript-language-features/src/test/unit/cachedResponse.test.ts b/extensions/typescript-language-features/src/test/unit/cachedResponse.test.ts index 5b024e59a4fe..c886bbb669db 100644 --- a/extensions/typescript-language-features/src/test/unit/cachedResponse.test.ts +++ b/extensions/typescript-language-features/src/test/unit/cachedResponse.test.ts @@ -9,6 +9,8 @@ import * as vscode from 'vscode'; import { CachedResponse } from '../../tsServer/cachedResponse'; import type * as Proto from '../../tsServer/protocol/protocol'; import { ServerResponse } from '../../typescriptService'; +import { disposeAll } from '../../utils/dispose'; +import { createRandomFile, deleteFile } from '../testUtils'; suite('CachedResponse', () => { test('should cache simple response for same document', async () => { @@ -32,6 +34,38 @@ suite('CachedResponse', () => { assertResult(await response.execute(doc1, respondWith('test-5')), 'test-4'); }); + test('should invalidate cache when a document is reopened', async () => { + const file = await createRandomFile('const original = 1;', 'ts'); + const disposables: vscode.Disposable[] = []; + try { + // Avoid openTextDocument's temporary model reference when testing close. + await vscode.commands.executeCommand('vscode.open', file); + const document = vscode.window.activeTextEditor?.document; + assert.ok(document); + const response = new CachedResponse(); + assertResult(await response.execute(document, respondWith('original')), 'original'); + + const closed = new Promise(resolve => { + vscode.workspace.onDidCloseTextDocument(closedDocument => { + if (closedDocument === document) { + resolve(); + } + }, undefined, disposables); + }); + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await closed; + + await vscode.workspace.fs.writeFile(file, Buffer.from('const updated = 2;')); + const reopened = await vscode.workspace.openTextDocument(file); + assert.strictEqual(reopened.version, document.version); + assertResult(await response.execute(reopened, respondWith('updated')), 'updated'); + } finally { + disposeAll(disposables); + await vscode.commands.executeCommand('workbench.action.closeAllEditors'); + await deleteFile(file); + } + }); + test('should not cache cancelled responses', async () => { const doc = await createTextDocument(); const response = new CachedResponse(); diff --git a/extensions/typescript-language-features/src/test/unit/suggestNativePreview.test.ts b/extensions/typescript-language-features/src/test/unit/suggestNativePreview.test.ts new file mode 100644 index 000000000000..3cdffdfa8c97 --- /dev/null +++ b/extensions/typescript-language-features/src/test/unit/suggestNativePreview.test.ts @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import 'mocha'; +import * as sinon from 'sinon'; +import * as vscode from 'vscode'; +import { suggestNativePreview } from '../../ui/suggestNativePreview'; + +suite('Suggest TypeScript 7 preview', () => { + teardown(() => sinon.restore()); + + test('does not show when there is no active editor', async () => { + const showInformationMessage = sinon.stub(vscode.window, 'showInformationMessage'); + sinon.stub(vscode.window, 'activeTextEditor').get(() => undefined); + + await suggestNativePreview(undefined!, undefined!, undefined!); + assert.strictEqual(showInformationMessage.callCount, 0); + }); + + test('does not show for a JSON active editor', async () => { + const showInformationMessage = sinon.stub(vscode.window, 'showInformationMessage'); + const document = await vscode.workspace.openTextDocument({ language: 'json', content: '{}' }); + sinon.stub(vscode.window, 'activeTextEditor').get(() => ({ document } as vscode.TextEditor)); + + await suggestNativePreview(undefined!, undefined!, undefined!); + assert.strictEqual(showInformationMessage.callCount, 0); + }); + + test('does not show for a JavaScript active editor', async () => { + const showInformationMessage = sinon.stub(vscode.window, 'showInformationMessage'); + const document = await vscode.workspace.openTextDocument({ language: 'javascript', content: '' }); + sinon.stub(vscode.window, 'activeTextEditor').get(() => ({ document } as vscode.TextEditor)); + + await suggestNativePreview(undefined!, undefined!, undefined!); + assert.strictEqual(showInformationMessage.callCount, 0); + }); + +}); diff --git a/extensions/typescript-language-features/src/tsServer/cachedResponse.ts b/extensions/typescript-language-features/src/tsServer/cachedResponse.ts index cedc580761f1..edc6ca512a22 100644 --- a/extensions/typescript-language-features/src/tsServer/cachedResponse.ts +++ b/extensions/typescript-language-features/src/tsServer/cachedResponse.ts @@ -15,7 +15,7 @@ type Resolve = () => Promise { private response?: Promise>; private version: number = -1; - private document: string = ''; + private document?: WeakRef; /** * Execute a request. May return cached value or resolve the new value @@ -34,7 +34,7 @@ export class CachedResponse { } private matches(document: vscode.TextDocument): boolean { - return this.version === document.version && this.document === document.uri.toString(); + return this.version === document.version && this.document?.deref() === document; } private async reset( @@ -42,7 +42,7 @@ export class CachedResponse { resolve: Resolve ): Promise> { this.version = document.version; - this.document = document.uri.toString(); + this.document = new WeakRef(document); return this.response = resolve(); } } diff --git a/extensions/typescript-language-features/src/ui/suggestNativePreview.ts b/extensions/typescript-language-features/src/ui/suggestNativePreview.ts index 006580d6570e..5482c4d7e6d7 100644 --- a/extensions/typescript-language-features/src/ui/suggestNativePreview.ts +++ b/extensions/typescript-language-features/src/ui/suggestNativePreview.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; +import { isTypeScriptDocument } from '../configuration/languageIds'; import { getTsNativeExtension, tsNativeExtensionOldId } from '../commands/useTsgo'; import { ExperimentationService } from '../experimentationService'; import type { PluginManager } from '../tsServer/plugins.js'; @@ -17,6 +18,11 @@ export async function suggestNativePreview( experimentationService: ExperimentationService, pluginManager: PluginManager ): Promise { + const activeEditor = vscode.window.activeTextEditor; + if (!activeEditor || !isTypeScriptDocument(activeEditor.document)) { + return; + } + if (context.globalState.get(suggestTS7NoPluginsStorageKey)) { return; } diff --git a/extensions/typescript-language-features/web/src/serverHost.ts b/extensions/typescript-language-features/web/src/serverHost.ts index 975672a50be4..6bbbe34cba8f 100644 --- a/extensions/typescript-language-features/web/src/serverHost.ts +++ b/extensions/typescript-language-features/web/src/serverHost.ts @@ -105,7 +105,7 @@ function createServerHost( const scriptPath = combinePaths(packageRoot, browser); try { // This file isn't bundled so we really do want a dynamic import here - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const { default: module } = await import(/* webpackIgnore: true */ scriptPath); return { module, error: undefined }; } catch (e) { diff --git a/extensions/vscode-api-tests/src/singlefolder-tests/notebook.kernel.test.ts b/extensions/vscode-api-tests/src/singlefolder-tests/notebook.kernel.test.ts index 805c94460861..c5b2c69181e5 100644 --- a/extensions/vscode-api-tests/src/singlefolder-tests/notebook.kernel.test.ts +++ b/extensions/vscode-api-tests/src/singlefolder-tests/notebook.kernel.test.ts @@ -332,6 +332,43 @@ const apiTestSerializer: vscode.NotebookSerializer = { verifyOutputSyncKernel.controller.dispose(); }); + test('copying a running cell preserves copied output when saved', async function () { + const notebookType = 'notebook.nbdserializer'; + testDisposables.push(vscode.workspace.registerNotebookSerializer(notebookType, { + deserializeNotebook() { + return new vscode.NotebookData([new vscode.NotebookCellData(vscode.NotebookCellKind.Code, 'test', 'javascript')]); + }, + serializeNotebook(data) { + return new TextEncoder().encode(JSON.stringify(data.cells.map(cell => + cell.outputs?.map(output => output.items.map(item => new TextDecoder().decode(item.data))) + ))); + } + })); + const kernel = new Kernel('copyOutputsKernel', 'Copy Outputs Kernel', notebookType); + testDisposables.push(kernel.controller); + const uri = await createRandomFile('', undefined, '.nbdserializer'); + const notebook = await vscode.workspace.openNotebookDocument(uri); + await vscode.window.showNotebookDocument(notebook); + await assertKernel(kernel, notebook); + + const cell = notebook.cellAt(0); + const execution = kernel.controller.createNotebookCellExecution(cell); + execution.start(); + try { + await execution.replaceOutput([new vscode.NotebookCellOutput([vscode.NotebookCellOutputItem.stdout('before\n')])]); + await vscode.commands.executeCommand('notebook.cell.copyDown'); + await execution.appendOutputItems(vscode.NotebookCellOutputItem.stdout('after\n'), cell.outputs[0]); + } finally { + execution.end(true); + } + + await notebook.save(); + assert.deepStrictEqual( + JSON.parse(new TextDecoder().decode(await vscode.workspace.fs.readFile(uri))), + [[['before\nafter\n']], [['before\n']]] + ); + }); + test('executionSummary', async () => { const notebook = await openRandomNotebookDocument(); const editor = await vscode.window.showNotebookDocument(notebook); @@ -357,6 +394,32 @@ const apiTestSerializer: vscode.NotebookSerializer = { }); + for (const supportedLanguages of [undefined, []]) { + test(`executes after resetting supported languages with ${supportedLanguages === undefined ? 'undefined' : 'an empty array'}`, async () => { + const document = await openRandomNotebookDocument(); + await vscode.window.showNotebookDocument(document); + const cell = document.cellAt(0); + const execution = { document: document.uri, ranges: [{ start: 0, end: 1 }] }; + + defaultKernel.controller.supportedLanguages = ['javascript']; + await assertKernel(defaultKernel, document); + await vscode.commands.executeCommand('notebook.cell.execute', execution); + assert.strictEqual(cell.outputs.length, 0); + + defaultKernel.controller.supportedLanguages = supportedLanguages; + await assertKernel(defaultKernel, document); + await vscode.commands.executeCommand('notebook.cell.execute', execution); + + assert.deepStrictEqual({ + outputs: cell.outputs.map(output => output.items.map(item => new TextDecoder().decode(item.data))), + success: cell.executionSummary?.success + }, { + outputs: [['test']], + success: true + }); + }); + } + test('execution cancelled when delete while executing', async () => { const document = await openRandomNotebookDocument(); const cell = document.cellAt(0); diff --git a/extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts b/extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts index 57a88495814c..50a7e02b04fe 100644 --- a/extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts +++ b/extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts @@ -8,7 +8,7 @@ import * as fs from 'fs'; import { basename, join, posix } from 'path'; import * as vscode from 'vscode'; import { TestFS } from '../memfs'; -import { assertNoRpc, closeAllEditors, createRandomFile, delay, deleteFile, disposeAll, Mutable, pathEquals, revertAllDirty, rndName, testFs, withLogDisabled } from '../utils'; +import { assertNoRpc, closeAllEditors, createRandomFile, DeferredPromise, delay, deleteFile, disposeAll, Mutable, pathEquals, poll, revertAllDirty, rndName, testFs, withLogDisabled } from '../utils'; suite('vscode API - workspace', () => { @@ -558,6 +558,55 @@ suite('vscode API - workspace', () => { }); }); + test('registerTextDocumentContentProvider, refreshes independent documents concurrently', async function () { + const emitter = new vscode.EventEmitter(); + const firstContent = new DeferredPromise(); + const slowContent = new DeferredPromise(); + const slowStarted = new DeferredPromise(); + let refreshing = false; + const registration = vscode.workspace.registerTextDocumentContentProvider('independent-content', { + onDidChange: emitter.event, + provideTextDocumentContent(uri) { + if (!refreshing) { + return 'initial'; + } + if (uri.path === '/first') { + return firstContent.p; + } + if (uri.path === '/slow') { + slowStarted.complete(); + return slowContent.p; + } + return 'updated'; + } + }); + + try { + const [first, slow, fast] = await Promise.all([ + vscode.workspace.openTextDocument(vscode.Uri.parse('independent-content:/first')), + vscode.workspace.openTextDocument(vscode.Uri.parse('independent-content:/slow')), + vscode.workspace.openTextDocument(vscode.Uri.parse('independent-content:/fast')) + ]); + refreshing = true; + emitter.fire(first.uri); + emitter.fire(slow.uri); + emitter.fire(fast.uri); + try { + await firstContent.complete('updated'); + await poll(async () => slowStarted.isResolved, started => started, 'Slow refresh did not start', 50, 100); + await poll(async () => fast.getText(), text => text === 'updated', 'Independent document is blocked by the slow refresh', 50, 100); + assert.deepStrictEqual([slow.getText(), fast.getText(), slowContent.isSettled], ['initial', 'updated', false]); + } finally { + await firstContent.complete('updated'); + await slowContent.complete('updated'); + await poll(async () => [first.getText(), slow.getText(), fast.getText()], texts => texts.every(text => text === 'updated'), 'Pending refreshes did not finish', 50, 100); + } + } finally { + registration.dispose(); + emitter.dispose(); + } + }); + test('findFiles', () => { return vscode.workspace.findFiles('**/image.png').then((res) => { assert.strictEqual(res.length, 2); diff --git a/oxlint.config.ts b/oxlint.config.ts new file mode 100644 index 000000000000..433f794c7bee --- /dev/null +++ b/oxlint.config.ts @@ -0,0 +1,11 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { defineConfig } from 'oxlint'; +import { toOxlintConfig } from './build/lib/oxlintConfig.ts'; +import eslintConfig from './eslint.config.js'; + +// oxlint runs the rules of eslint.config.js, converted when oxlint loads this file. See build/lib/oxlintConfig.ts. +export default defineConfig(toOxlintConfig(eslintConfig)); diff --git a/package.json b/package.json index 42168f66821b..55bf8da08f3f 100644 --- a/package.json +++ b/package.json @@ -2,12 +2,12 @@ "name": "BlockIDE", "version": "1.0.4", "packageManager": "pnpm@12.16.0", - "distro": "d915b90d880d6ec3c76cd109247ccded03003672", + "distro": "dad962551a98032220a9b53a1cfb02bbcc7c42ed", "nativeBuild": { "runtime": "electron", - "target": "43.8.6", + "target": "43.8.9", "disturl": "https://electronjs.org/headers", - "msBuildId": "15893748", + "msBuildId": "16012121", "buildFromSource": true }, "author": { @@ -54,6 +54,8 @@ "kill-watch-clientd": "deemon --kill pnpm run watch-client", "transpile-client": "node build/next/index.ts transpile", "bundle-dev-tunnels-web": "node build/next/devTunnelsWeb.ts", + "bundle-mobile": "node build/next/index.ts bundle-mobile", + "test-mobile": "node --test build/next/test/mobile.test.ts", "watch-client-transpile": "node build/next/index.ts transpile --watch", "watch-client-transpiled": "deemon pnpm run watch-client-transpile", "kill-watch-client-transpiled": "deemon --kill pnpm run watch-client-transpile", @@ -75,10 +77,10 @@ "download-builtin-extensions": "node build/lib/builtInExtensions.ts", "download-builtin-extensions-cg": "node build/lib/builtInExtensionsCG.ts", "monaco-compile-check": "tsc --project src/tsconfig.monaco.json --noEmit", - "tsec-compile-check": "node --max-old-space-size=8192 node_modules/tsec/bin/tsec -p src/tsconfig.tsec.json", + "tsec-compile-check": "node --max-old-space-size=8192 build/lib/tsec.ts", "vscode-dts-compile-check": "tsc --project src/tsconfig.vscode-dts.json && tsc --project src/tsconfig.vscode-proposed-dts.json", "valid-layers-check": "node build/checker/layersChecker.ts && node build/checker/layersTypeCheck.ts", - "define-class-fields-check": "node --max-old-space-size=8192 build/lib/propertyInitOrderChecker.ts && tsc --project src/tsconfig.defineClassFields.json", + "define-class-fields-check": "tsc --project src/tsconfig.defineClassFields.json", "update-distro": "node build/npm/update-distro.ts", "export-policy-data": "node build/lib/policies/exportPolicyData.ts", "web": "echo 'pnpm run web' is replaced by './scripts/code-server' or './scripts/code-web'", @@ -89,6 +91,7 @@ "watch-cli": "pnpm run gulp watch-cli", "mock-policy-server": "node --experimental-strip-types scripts/mock-policy-server/server.ts", "eslint": "node --max-old-space-size=8192 build/eslint.ts", + "oxlint": "node build/oxlint.ts", "stylelint": "node build/stylelint.ts", "playwright-install": "pnpm exec playwright install", "compile-extensions-build": "pnpm run gulp compile-extensions-build", @@ -142,16 +145,16 @@ "@vscode/windows-mutex": "^0.5.0", "@vscode/windows-process-tree": "^0.8.0", "@vscode/windows-registry": "^1.3.0", - "@xterm/addon-clipboard": "^0.3.0-beta.303", - "@xterm/addon-image": "^0.10.0-beta.301", - "@xterm/addon-ligatures": "^0.11.0-beta.301", - "@xterm/addon-progress": "^0.3.0-beta.301", - "@xterm/addon-search": "^0.17.0-beta.301", - "@xterm/addon-serialize": "^0.15.0-beta.301", - "@xterm/addon-unicode11": "^0.10.0-beta.301", - "@xterm/addon-webgl": "^0.20.0-beta.300", - "@xterm/headless": "^6.1.0-beta.303", - "@xterm/xterm": "^6.1.0-beta.304", + "@xterm/addon-clipboard": "^0.3.0-beta.335", + "@xterm/addon-image": "^0.10.0-beta.332", + "@xterm/addon-ligatures": "^0.11.0-beta.331", + "@xterm/addon-progress": "^0.3.0-beta.331", + "@xterm/addon-search": "^0.17.0-beta.331", + "@xterm/addon-serialize": "^0.15.0-beta.331", + "@xterm/addon-unicode11": "^0.10.0-beta.331", + "@xterm/addon-webgl": "^0.20.0-beta.330", + "@xterm/headless": "^6.1.0-beta.335", + "@xterm/xterm": "^6.1.0-beta.337", "chrome-remote-interface": "^0.33.0", "detect-libc": "^2.1.2", "foundry-local-sdk": "2.2.1", @@ -229,7 +232,6 @@ "eslint": "10.8.0", "eslint-formatter-compact": "^8.40.0", "eslint-plugin-header": "3.1.1", - "eslint-plugin-import": "^2.32.0", "eslint-plugin-jsdoc": "^63.3.3", "event-stream": "3.3.4", "events": "^3.3.0", @@ -258,6 +260,8 @@ "mocha-junit-reporter": "^2.2.1", "mocha-multi-reporters": "^1.5.1", "npm-run-all2": "^8.0.4", + "oxlint": "1.90.0", + "oxlint-tsgolint": "7.0.2005", "p-all": "^1.0.0", "path-browserify": "^1.0.1", "playwright": "1.61.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 307f26ea1ce4..bb5047acce0b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -121,35 +121,35 @@ importers: specifier: ^1.3.0 version: 1.3.0 '@xterm/addon-clipboard': - specifier: ^0.3.0-beta.303 - version: 0.3.0-beta.303(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.335 + version: 0.3.0-beta.335(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-image': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.332 + version: 0.10.0-beta.332(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-ligatures': - specifier: ^0.11.0-beta.301 - version: 0.11.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.11.0-beta.331 + version: 0.11.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-progress': - specifier: ^0.3.0-beta.301 - version: 0.3.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.331 + version: 0.3.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-search': - specifier: ^0.17.0-beta.301 - version: 0.17.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.17.0-beta.331 + version: 0.17.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-serialize': - specifier: ^0.15.0-beta.301 - version: 0.15.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.15.0-beta.331 + version: 0.15.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-unicode11': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.331 + version: 0.10.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-webgl': - specifier: ^0.20.0-beta.300 - version: 0.20.0-beta.300(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.20.0-beta.330 + version: 0.20.0-beta.330(@xterm/xterm@6.1.0-beta.337) '@xterm/headless': - specifier: ^6.1.0-beta.303 - version: 6.1.0-beta.303 + specifier: ^6.1.0-beta.335 + version: 6.1.0-beta.335 '@xterm/xterm': - specifier: ^6.1.0-beta.304 - version: 6.1.0-beta.304 + specifier: ^6.1.0-beta.337 + version: 6.1.0-beta.337 chrome-remote-interface: specifier: ^0.33.0 version: 0.33.0 @@ -376,9 +376,6 @@ importers: eslint-plugin-header: specifier: 3.1.1 version: 3.1.1(eslint@10.8.0) - eslint-plugin-import: - specifier: ^2.32.0 - version: 2.32.0(eslint@10.8.0) eslint-plugin-jsdoc: specifier: ^63.3.3 version: 63.3.3(eslint@10.8.0) @@ -463,6 +460,12 @@ importers: npm-run-all2: specifier: ^8.0.4 version: 8.0.4 + oxlint: + specifier: 1.90.0 + version: 1.90.0(oxlint-tsgolint@7.0.2005) + oxlint-tsgolint: + specifier: 7.0.2005 + version: 7.0.2005 p-all: specifier: ^1.0.0 version: 1.0.0 @@ -521,6 +524,9 @@ importers: .eslint-plugin-local: devDependencies: + '@eslint/compat': + specifier: ^2.1.0 + version: 2.1.0(eslint@10.8.0) '@types/estree': specifier: ^1.0.9 version: 1.0.9 @@ -536,6 +542,9 @@ importers: eslint: specifier: 10.8.0 version: 10.8.0 + eslint-plugin-header: + specifier: 3.1.1 + version: 3.1.1(eslint@10.8.0) eslint-visitor-keys: specifier: ^5.0.1 version: 5.0.1 @@ -1606,6 +1615,158 @@ packages: resolution: {integrity: sha512-puWxACExDe9nxbBB3lOymQFrLYml2dVOrd7USiVRnSbgXE+KwBu+HxFvxrzfqsiSda9IWsXJG1ef7C1O2/GmKQ==} engines: {node: '>=8.0.0'} + '@oxlint-tsgolint/darwin-arm64@7.0.2005': + resolution: {integrity: sha512-VqDZxcZVjlonNLuuvraVNgDQt+1ndwa4yJo8OqsK4HYh/61ba9IlMStCVfi/aaIqRoDhNbAKC8gdcTrXqnb+Ug==} + cpu: [arm64] + os: [darwin] + + '@oxlint-tsgolint/darwin-x64@7.0.2005': + resolution: {integrity: sha512-4kUfLRNYoVpv0Tm3jPYrvxyfOc/LmdvFC3pKZ4tL6K7lA7K/VS81SAtmxRzbYXYSyb3SBWhwsuX+df4neqzxxA==} + cpu: [x64] + os: [darwin] + + '@oxlint-tsgolint/linux-arm64@7.0.2005': + resolution: {integrity: sha512-rhUNcPsBlKvhXtrbhbBUidtRBRdJ8fbEHN9H5Q5N59gby18ruGuDA7KUxl7oRnUzp797uykYQhkBDm+0KpfK/Q==} + cpu: [arm64] + os: [linux] + + '@oxlint-tsgolint/linux-x64@7.0.2005': + resolution: {integrity: sha512-tKs9yinDQZOHygM0e8EJnjTU3mzJtdfkOZP6Udu82iLMePUSHOhTJ9zzU/mSd1hQxURI4LTRRiFhfzC+PzwdNA==} + cpu: [x64] + os: [linux] + + '@oxlint-tsgolint/win32-arm64@7.0.2005': + resolution: {integrity: sha512-VYPnu1gjfbSv+ROhuyNfMs382D4zQU2ZRc8Uc3nuEZo1k2kf+1KfTrg4hrlWh73h9GI+dUWyo+DYCQzUBlPwcQ==} + cpu: [arm64] + os: [win32] + + '@oxlint-tsgolint/win32-x64@7.0.2005': + resolution: {integrity: sha512-ekU89cTGy9fpQzuvxIsFHrnoP8XoFjGIRgPEW6eqgY2NYjGy9pwpjF79o04WXRMJFKRrcaVqkZXUUBdLsqpQDw==} + cpu: [x64] + os: [win32] + + '@oxlint/binding-android-arm-eabi@1.90.0': + resolution: {integrity: sha512-sgfalb1HuxYjiAa4wESZ626z1FGusqNcXYHyB5oIOEprS2sbPg0UYEfo83uF1GNG70DIfZxHkXuE6KFrlSdn8Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxlint/binding-android-arm64@1.90.0': + resolution: {integrity: sha512-RcKhz1ETMq+fazE9TKS2+5NIRGwigm/nW8egqF0LI+A8Yw2iW5r0E/C3XAPRiwIm/vcPiutIRIa6IQCIKhZsTQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxlint/binding-darwin-arm64@1.90.0': + resolution: {integrity: sha512-PSrxMvP6mx+p1karZcUxLdy9lpaP+JWQPti4al9FgTaPhxE+pT/BjhGExloVVSWgZgIfOlLOjVyyq8BXlodhLQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxlint/binding-darwin-x64@1.90.0': + resolution: {integrity: sha512-OLbU9qsrV2Q8QxT2OEzOPdO8zCCpyI8qB+hDI8yr6RsYELtkf0FAZhJdfjM/RnLHKzt44HWwAPnk92vBtKofvw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxlint/binding-freebsd-x64@1.90.0': + resolution: {integrity: sha512-fBA4pWyVDARmNucQqpyFuPC49xYf1r+sX7dxPL5fNPQrSMLum39Sn56tZ9JPleWC7FzLPwSQ7plYYfirYBHF8A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxlint/binding-linux-arm-gnueabihf@1.90.0': + resolution: {integrity: sha512-zhxH78eP2nR6/pGdhBc7MIfjhhcgATeu8fkmkFJbuzfk6Cj0FzBxyEhL85yDqrCybjx+G2YDzZGsxIO9kvO4Iw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm-musleabihf@1.90.0': + resolution: {integrity: sha512-MvYmpHyJqUJjEvkZbJHdwfdL45cGn8EVBkYmoXFiaYFW9suoD3dbJl5mBdpy0DVgdjlyddmldbRtk3cCgETadQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm64-gnu@1.90.0': + resolution: {integrity: sha512-L13Sy+Kg0nZhwTsToniqjUFPA2TuM6962qCZ5Wp5KeB517Tw7ApdLTTtlb+bF86fcZZa2EtvCVvAJxk4Dya/MQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-arm64-musl@1.90.0': + resolution: {integrity: sha512-wFDdZWGpzIPFdJFjSLWnKB0TGzFriTKUIrl04iMqMyM9BBIJTuerfCHYa0WpDSjr5x3lcW/CHLyacSt886WpGg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-ppc64-gnu@1.90.0': + resolution: {integrity: sha512-FRywfn+MoKn8xpBSzgNwNVliSKRI2QXkxi/iF7o6FEQs8Bh8z2RpVTaFAcO3pchXjvB2eGNFIoLLQABIQ+u7VA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-gnu@1.90.0': + resolution: {integrity: sha512-IS2PaUgpc/qeLADTyhUNmdx3x4ijs9pjJdPKBYHaT+mAE7k3FsjnHPTjhpsak1b++h6CIPhv6WX9Z+y7Pw0voQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-musl@1.90.0': + resolution: {integrity: sha512-s7JFKRkGS8O7i2ZVODfuO++NC7sH6HDqpMn8lYxw91w0SXJOxnAVjQ8utvmDwLMMT0jaSkuOKuUYJDGDtu4sHQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-s390x-gnu@1.90.0': + resolution: {integrity: sha512-b0GxrOQr5VONCkd7KLSqmP6b6nqZuTpuS8QPQHzltmqdXP5bY0Jl0CZ0QmlCTrS3ExaLYbioFYOARzNbYvcApQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-gnu@1.90.0': + resolution: {integrity: sha512-iaJeShJtgUp8rZbt9YUdTAGOpmX5KogCLba17Jp1tWdJ3F4M3D2g2TKUyI1FMTHxKH9NNHuQcuC2kZRg6IV7yQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-musl@1.90.0': + resolution: {integrity: sha512-/aZoXnL5WBLCXuzfHqvEFXcm4iwYmr/cYByHDTXzLFzJdE5DC7bm6phpWqHv6BeqpVgY9IpBAxGDv2WEkl5JCg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxlint/binding-openharmony-arm64@1.90.0': + resolution: {integrity: sha512-SMhk7ozwoxYDKfYqGZCQEfULOKDneF9uhaoIf2neoDLWvNtjY9yVeL7YHmE5L9WdKvMpWNwwZxhenxBu6AgfOg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxlint/binding-win32-arm64-msvc@1.90.0': + resolution: {integrity: sha512-KBvR3A9fO7fCi2vCP8ifWvlia7tGEQV9NaYh+IGwa/7Groy48Mt/UaYqMK9/zOtAWl20BUCf6RPqzJ32fRw33Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxlint/binding-win32-ia32-msvc@1.90.0': + resolution: {integrity: sha512-+x42rDHQGbTCuT3EzpWAzhP3NoVPE/cJsG4gnrakOSg0olV+GCdMpPU23Nvrl3zZMnXxFZdTtDv4D3SuaA5ZeQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxlint/binding-win32-x64-msvc@1.90.0': + resolution: {integrity: sha512-30JiaFEBUB9peEOcvVM8ggo88SoN/IdSr9DW505JdBji/R6dM66gKEiG65hw6qcaF2f4mO0cEJ+RwRZprmun9g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@parcel/watcher@2.5.6': resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} engines: {node: '>= 10.0.0'} @@ -1631,9 +1792,6 @@ packages: '@pondwader/socks5-server@1.0.10': resolution: {integrity: sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==} - '@rtsao/scc@1.1.0': - resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@sec-ant/readable-stream@0.4.1': resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==} @@ -1724,9 +1882,6 @@ packages: '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - '@types/json5@0.0.29': - resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==} - '@types/junit-report-builder@3.0.2': resolution: {integrity: sha512-R5M+SYhMbwBeQcNXYWNCZkl09vkVfAtcPIaCGdzIkkbeaTrVbGQ7HVgi4s+EmM/M1K4ZuWQH0jGcvMvNePfxYA==} @@ -2247,52 +2402,52 @@ packages: resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==} engines: {node: '>=10.0.0'} - '@xterm/addon-clipboard@0.3.0-beta.303': - resolution: {integrity: sha512-AVw9y9f50uVcI1/LIzp4vkQzPXiRad8SFHjqo33kg7wWL4jes+Z/08jWDBLGvNfYNGhmElp9H2cg/ITErex55g==} + '@xterm/addon-clipboard@0.3.0-beta.335': + resolution: {integrity: sha512-LVuJcdUTMxzT9oWj5IrAaVe33pveD04izzIM5g3ny4pgbz0Csffn6qVmZ5SnwfJ08fp/0wDxRwnpcsd7cTpZBA==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-image@0.10.0-beta.301': - resolution: {integrity: sha512-PJZL4GlQ1ReIgbffFMaOAFxc3wOit21/G2UEM82RpH3hNHjn6MH8ilz3ToDeBjYuOqU7ienBaeIuMbNktX4/HA==} + '@xterm/addon-image@0.10.0-beta.332': + resolution: {integrity: sha512-9Ny3X2w41hTnr4pTraV0PkwhS4rEtUR6UkbBWJCu22pngzoSb7RdLDDi221aacsIKiKtQwQCIDVq3m6wGhw9Mg==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-ligatures@0.11.0-beta.301': - resolution: {integrity: sha512-8F3D/DHbi3W+ool0xIV90paDGJYqUU/SQ9Pdltgx2nw9QFFgjtq+OscXANhrNhDzIU80p2GCnwV0jW+a6Dal0w==} + '@xterm/addon-ligatures@0.11.0-beta.331': + resolution: {integrity: sha512-RZjGMHwraIB/fZEZOrhtUYxvJobGQGBEY3ao/hbi5oxwGfQoUlX6PaFTUN3KCX+zFBDgpvq70kK53wyTzcnXVQ==} engines: {node: '>8.0.0'} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-progress@0.3.0-beta.301': - resolution: {integrity: sha512-9V04P0yncSSOZTgNvlEo6D3xiaHxALqoxEgQqgGhf20mj2eOQE0sfVPRMtO6wJwi4uI2viORUkBuiYBObvif3g==} + '@xterm/addon-progress@0.3.0-beta.331': + resolution: {integrity: sha512-4PylaZeZnBeJmTLFZ76DAF/hmUW8kk0igYhDvgeVpLV5no/ud+hmtXXOFAC7BrtE5ltkW9fFjItm+cHXTj13+A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-search@0.17.0-beta.301': - resolution: {integrity: sha512-Dj8q+p2/5c4fcS4hag6QaXngxstnc4DdzREN/IhpGxz5a1JpW/3FnF9/JE1P1wvNLp9fApgGmZqBMW4xCF6HKg==} + '@xterm/addon-search@0.17.0-beta.331': + resolution: {integrity: sha512-oYdFS2BXVXzwosRJ9kf9niHABDaLBBk2YgAmCyYz3gQgqXb5omgQH2NcBESc1qqf0G5SzJRWTcFaNWE7aakd6A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-serialize@0.15.0-beta.301': - resolution: {integrity: sha512-zWT0Sy5GCSTnarAXRiicu3XYHgam8DPtpkWfSLPME+A3s7U1A6Jy+ZATt8vMkatyeVOPI0GICYRuQJLZVgnVow==} + '@xterm/addon-serialize@0.15.0-beta.331': + resolution: {integrity: sha512-UQL26TFwWulbhrvdLE21hx32hju5B6B9tTihqvd1XwfB7Fbje459/gC2Eha2Dane7YU+SZ+PIcsloA5zd4AwnQ==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-unicode11@0.10.0-beta.301': - resolution: {integrity: sha512-SS5BzfbvfFIikE4xZFAtHu6n0Kl5R1ZCPx41RL2WULLSE+HFo/WmYee53tMxNK/QUjpcQWepeVB7HebCPhHnig==} + '@xterm/addon-unicode11@0.10.0-beta.331': + resolution: {integrity: sha512-GW2EOP+4+ZXQS/KfTgriP2QxDOSMe9ffnEkq7tgIwAfiTUcE3X/oxn6wBNdyxuM/5mLyK7wzi1O8ycV83yAYPw==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-webgl@0.20.0-beta.300': - resolution: {integrity: sha512-BJQiOx8I+zz2woe+/E9nWprRRPevo9slPgyOd43E8o18aG307ccsyaTJoIbSu99uqfDoVLWDRLTy91ZXTFsdig==} + '@xterm/addon-webgl@0.20.0-beta.330': + resolution: {integrity: sha512-gcxemutOlpGCEnxZckSwR8oZ/twZXrcQw6N3aRcDVrPguIMr9YvrzegfllCo4WxRnOc4gWkHhjD1toX3emug3A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/headless@6.1.0-beta.303': - resolution: {integrity: sha512-FjPRg5OF0UdloypPRZcUdtpxaxYKk7FdNArgpOaedoj7UWzinB+THZyEY7t6QHRR5bjcbz7B7s4vX0Zo5LT6aw==} + '@xterm/headless@6.1.0-beta.335': + resolution: {integrity: sha512-3/hfyBw8B67K1x0yy7R6H8oodJgleTxCpuc57Ulwb5YLNc7kF6yMJF8ig/tk4vZilRzdSmoh1xFvwbBjgnU6hg==} - '@xterm/xterm@6.1.0-beta.304': - resolution: {integrity: sha512-Wq9d4qFYslYQBIan+riXotdyurtREc6v+HWdAwV6Y2JSDI9eJ1dkWm/fzYb2rCGgGnM3baiYuSK4Z6OLNKLzDw==} + '@xterm/xterm@6.1.0-beta.337': + resolution: {integrity: sha512-zstczNBAT/FaaWzCCoLx3DavRcAW0ndK7g/Y0893nPvZwWmjMU8WeuqJYqMRVommGwv1KRoxdlOOt0KukxHadA==} '@xtuc/ieee754@1.2.0': resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} @@ -2498,10 +2653,6 @@ packages: resolution: {integrity: sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==} engines: {node: '>=12.17'} - array-buffer-byte-length@1.0.2: - resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} - engines: {node: '>= 0.4'} - array-differ@1.0.0: resolution: {integrity: sha512-LeZY+DZDRnvP7eMuQ6LHfCzUGxAAIViUBliK24P3hWXL6y4SortgR6Nim6xrkfSLlmH0+k+9NYNwVC2s53ZrYQ==} engines: {node: '>=0.10.0'} @@ -2510,10 +2661,6 @@ packages: resolution: {integrity: sha512-zHjL5SZa68hkKHBFBK6DJCTtr9sfTCPCaph/L7tMSLcTFgy+zX7E+6q5UArbtOtMBCtxdICpfTCspRse+ywyXA==} engines: {node: '>=0.10.0'} - array-includes@3.1.9: - resolution: {integrity: sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==} - engines: {node: '>= 0.4'} - array-initial@1.1.0: resolution: {integrity: sha512-BC4Yl89vneCYfpLrs5JU2aAu9/a+xWbeKhvISg9PT7eWFB9UlRvI+rKEtk6mgxWr3dSkk9gQ8hCrdqt06NXPdw==} engines: {node: '>=0.10.0'} @@ -2546,22 +2693,6 @@ packages: resolution: {integrity: sha512-SleRWjh9JUud2wH1hPs9rZBZ33H6T9HOiL0uwGnGx9FpE6wKGyfWugmbkEOIs6qWrZhg0LWeLziLrEwQJhs5mQ==} engines: {node: '>=0.10.0'} - array.prototype.findlastindex@1.2.6: - resolution: {integrity: sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==} - engines: {node: '>= 0.4'} - - array.prototype.flat@1.3.3: - resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==} - engines: {node: '>= 0.4'} - - array.prototype.flatmap@1.3.3: - resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==} - engines: {node: '>= 0.4'} - - arraybuffer.prototype.slice@1.0.4: - resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} - engines: {node: '>= 0.4'} - arrify@1.0.1: resolution: {integrity: sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==} engines: {node: '>=0.10.0'} @@ -2589,10 +2720,6 @@ packages: async-each@1.0.3: resolution: {integrity: sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==} - async-function@1.0.0: - resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} - engines: {node: '>= 0.4'} - async-settle@1.0.0: resolution: {integrity: sha512-VPXfB4Vk49z1LHHodrEQ6Xf7W4gg1w0dAPROHngx7qgDjqmIQ+fXmwgGXTW/ITLai0YLSvWepJOP9EVpMnEAcw==} engines: {node: '>= 0.10'} @@ -3149,18 +3276,6 @@ packages: d@1.0.1: resolution: {integrity: sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==} - data-view-buffer@1.0.2: - resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} - engines: {node: '>= 0.4'} - - data-view-byte-length@1.0.2: - resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} - engines: {node: '>= 0.4'} - - data-view-byte-offset@1.0.1: - resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} - engines: {node: '>= 0.4'} - debounce@1.1.0: resolution: {integrity: sha512-ZQVKfRVlwRfD150ndzEK8M90ABT+Y/JQKs4Y7U4MXdpuoUkkrr4DwKbVux3YjylA5bUMUj0Nc3pMxPJX6N2QQQ==} @@ -3341,10 +3456,6 @@ packages: diffie-hellman@5.0.3: resolution: {integrity: sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==} - doctrine@2.1.0: - resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} - engines: {node: '>=0.10.0'} - dom-serializer@2.0.0: resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} @@ -3428,10 +3539,6 @@ packages: error-ex@1.3.2: resolution: {integrity: sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==} - es-abstract@1.24.2: - resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==} - engines: {node: '>= 0.4'} - es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -3451,14 +3558,6 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} - es-shim-unscopables@1.1.0: - resolution: {integrity: sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==} - engines: {node: '>= 0.4'} - - es-to-primitive@1.3.0: - resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==} - engines: {node: '>= 0.4'} - es5-ext@0.10.64: resolution: {integrity: sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==} engines: {node: '>=0.10'} @@ -3491,45 +3590,11 @@ packages: resolution: {integrity: sha512-cwGUs113TgmTQXecx5kfRjB7m0y2wkDLSadPTE2pK6M/wO4N8PjmUaoWOFNCP9MHgsiZwgqd5bZFnDCnszC56Q==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - eslint-import-resolver-node@0.3.10: - resolution: {integrity: sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==} - - eslint-module-utils@2.12.1: - resolution: {integrity: sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: '*' - eslint-import-resolver-node: '*' - eslint-import-resolver-typescript: '*' - eslint-import-resolver-webpack: '*' - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - eslint: - optional: true - eslint-import-resolver-node: - optional: true - eslint-import-resolver-typescript: - optional: true - eslint-import-resolver-webpack: - optional: true - eslint-plugin-header@3.1.1: resolution: {integrity: sha512-9vlKxuJ4qf793CmeeSrZUvVClw6amtpghq3CuWcB5cUNnWHQhgcqy5eF8oVKFk1G3Y/CbchGfEaw3wiIJaNmVg==} peerDependencies: eslint: '>=7.7.0' - eslint-plugin-import@2.32.0: - resolution: {integrity: sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9 - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - eslint-plugin-jsdoc@63.3.3: resolution: {integrity: sha512-xI4IeVRzRFA2DGHrPLIxF3U+oJHU3FE+P9Zb27fVs5dPHgfcpoAs0PyCbznVhK7pwR+9BPUztFeXSgpw/CL4Yg==} engines: {node: ^22.13.0 || >=24} @@ -3896,13 +3961,6 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - function.prototype.name@1.1.8: - resolution: {integrity: sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==} - engines: {node: '>= 0.4'} - - functions-have-names@1.2.3: - resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} - generator-function@2.0.1: resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} engines: {node: '>= 0.4'} @@ -3941,10 +3999,6 @@ packages: resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==} engines: {node: '>=18'} - get-symbol-description@1.1.0: - resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} - engines: {node: '>= 0.4'} - get-value@2.0.6: resolution: {integrity: sha512-Ln0UQDlxH1BapMu3GPtf7CuYNwRZf2gwCuPqbyG6pB8WfmFpzqcy4xtAaAMUhnNqjMKTiCPZG2oMT3YSx8U2NA==} engines: {node: '>=0.10.0'} @@ -4008,10 +4062,6 @@ packages: resolution: {integrity: sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==} engines: {node: '>=0.10.0'} - globalthis@1.0.4: - resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} - engines: {node: '>= 0.4'} - glogg@1.0.2: resolution: {integrity: sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA==} engines: {node: '>= 0.10'} @@ -4103,10 +4153,6 @@ packages: resolution: {integrity: sha512-C8vBJ8DwUCx19vhm7urhTuUsr4/IyP6l4VzNQDv+ryHQObW3TTTp9yB68WpYgRe2bbaGuZ/se74IqFeVnMnLZg==} engines: {node: '>=0.10.0'} - has-bigints@1.1.0: - resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} - engines: {node: '>= 0.4'} - has-flag@3.0.0: resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==} engines: {node: '>=4'} @@ -4118,10 +4164,6 @@ packages: has-property-descriptors@1.0.2: resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} - has-proto@1.2.0: - resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} - engines: {node: '>= 0.4'} - has-symbols@1.1.0: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} @@ -4275,10 +4317,6 @@ packages: engines: {node: '>= 0.8.0'} hasBin: true - internal-slot@1.1.0: - resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} - engines: {node: '>= 0.4'} - interpret@1.4.0: resolution: {integrity: sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==} engines: {node: '>= 0.10'} @@ -4317,21 +4355,9 @@ packages: resolution: {integrity: sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==} engines: {node: '>= 0.4'} - is-array-buffer@3.0.5: - resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} - engines: {node: '>= 0.4'} - is-arrayish@0.2.1: resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} - is-async-function@2.1.1: - resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==} - engines: {node: '>= 0.4'} - - is-bigint@1.1.0: - resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} - engines: {node: '>= 0.4'} - is-binary-path@1.0.1: resolution: {integrity: sha512-9fRVlXc0uCxEDj1nQzaWONSpbTfx0FmJfzHF7pwlI8DkWGoHBBea4Pg5Ky0ojwwxQmnSifgbKkI06Qv0Ljgj+Q==} engines: {node: '>=0.10.0'} @@ -4340,10 +4366,6 @@ packages: resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} engines: {node: '>=8'} - is-boolean-object@1.2.2: - resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} - engines: {node: '>= 0.4'} - is-buffer@1.1.6: resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==} @@ -4369,14 +4391,6 @@ packages: engines: {node: '>=0.10.0'} deprecated: Please upgrade to v1.0.1 - is-data-view@1.0.2: - resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} - engines: {node: '>= 0.4'} - - is-date-object@1.1.0: - resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} - engines: {node: '>= 0.4'} - is-deflate@1.0.0: resolution: {integrity: sha512-YDoFpuZWu1VRXlsnlYMzKyVRITXj7Ej/V9gXQ2/pAe7X1J7M/RNOqaIYi6qUn+B7nGyB9pDXrv02dsB58d2ZAQ==} @@ -4410,10 +4424,6 @@ packages: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} - is-finalizationregistry@1.1.1: - resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} - engines: {node: '>= 0.4'} - is-fullwidth-code-point@1.0.0: resolution: {integrity: sha512-1pqUqRjkhPJ9miNq9SwMfdvi6lBJcd6eFxvfaivQhaH3SgisfiuudvFntdKOmxuee/77l+FPjKrQjWvmPjWrRw==} engines: {node: '>=0.10.0'} @@ -4447,22 +4457,10 @@ packages: resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==} engines: {node: '>=12'} - is-map@2.0.3: - resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} - engines: {node: '>= 0.4'} - is-negated-glob@1.0.0: resolution: {integrity: sha512-czXVVn/QEmgvej1f50BZ648vUI+em0xqMq2Sn+QncCLN4zj1UAxlT+kw/6ggQTOaZPd1HqKQGEqbpQVtJucWug==} engines: {node: '>=0.10.0'} - is-negative-zero@2.0.3: - resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==} - engines: {node: '>= 0.4'} - - is-number-object@1.1.1: - resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} - engines: {node: '>= 0.4'} - is-number@3.0.0: resolution: {integrity: sha512-4cboCqIpliH+mAvFNegjZQ4kgKc3ZUhQVr3HvWbSh5q3WH2v82ct+T2Y1hdU5Gdtorx/cLifQjqCbL7bpznLTg==} engines: {node: '>=0.10.0'} @@ -4501,14 +4499,6 @@ packages: resolution: {integrity: sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==} engines: {node: '>=0.10.0'} - is-set@2.0.3: - resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} - engines: {node: '>= 0.4'} - - is-shared-array-buffer@1.0.4: - resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} - engines: {node: '>= 0.4'} - is-stream@1.1.0: resolution: {integrity: sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==} engines: {node: '>=0.10.0'} @@ -4517,14 +4507,6 @@ packages: resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==} engines: {node: '>=18'} - is-string@1.1.1: - resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} - engines: {node: '>= 0.4'} - - is-symbol@1.1.1: - resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} - engines: {node: '>= 0.4'} - is-typed-array@1.1.15: resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} engines: {node: '>= 0.4'} @@ -4551,18 +4533,6 @@ packages: resolution: {integrity: sha512-AhiROmoEFDSsjx8hW+5sGwgKVIORcXnrlAx/R0ZSeaPw70Vw0CqkGBBhHGL58Uox2eXnU1AnvXJl1XlyedO5bA==} engines: {node: '>=0.10.0'} - is-weakmap@2.0.2: - resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} - engines: {node: '>= 0.4'} - - is-weakref@1.1.1: - resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==} - engines: {node: '>= 0.4'} - - is-weakset@2.0.4: - resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} - engines: {node: '>= 0.4'} - is-windows@1.0.2: resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==} engines: {node: '>=0.10.0'} @@ -4581,9 +4551,6 @@ packages: isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} - isarray@2.0.5: - resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} - isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} @@ -4702,10 +4669,6 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} - json5@1.0.2: - resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==} - hasBin: true - json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} @@ -5159,10 +5122,6 @@ packages: resolution: {integrity: sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==} engines: {node: ^18 || ^20 || >= 21} - node-exports-info@1.6.0: - resolution: {integrity: sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==} - engines: {node: '>= 0.4'} - node-fetch@2.6.7: resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==} engines: {node: 4.x || >=6.0.0} @@ -5285,18 +5244,6 @@ packages: resolution: {integrity: sha512-c/K0mw/F11k4dEUBMW8naXUuBuhxRCfG7W+yFy8EcijU/rSmazOUd1XAEEe6bC0OuXY4HUKjTJv7xbxIMqdxrA==} engines: {node: '>=0.10.0'} - object.entries@1.1.9: - resolution: {integrity: sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==} - engines: {node: '>= 0.4'} - - object.fromentries@2.0.8: - resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==} - engines: {node: '>= 0.4'} - - object.groupby@1.0.3: - resolution: {integrity: sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==} - engines: {node: '>= 0.4'} - object.map@1.0.1: resolution: {integrity: sha512-3+mAJu2PLfnSVGHwIWubpOFLscJANBKuB/6A4CxBstc4aqwQY0FWcsppuy4jU5GSB95yES5JHSI+33AWuS4k6w==} engines: {node: '>=0.10.0'} @@ -5309,10 +5256,6 @@ packages: resolution: {integrity: sha512-naLhxxpUESbNkRqc35oQ2scZSJueHGQNUfMW/0U37IgN6tE2dgDWg3whf+NEliy3F/QysrO48XKUz/nGPe+AQw==} engines: {node: '>=0.10.0'} - object.values@1.2.1: - resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} - engines: {node: '>= 0.4'} - on-finished@2.4.1: resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} engines: {node: '>= 0.8'} @@ -5363,9 +5306,22 @@ packages: resolution: {integrity: sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==} deprecated: This package is no longer supported. - own-keys@1.0.1: - resolution: {integrity: sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==} - engines: {node: '>= 0.4'} + oxlint-tsgolint@7.0.2005: + resolution: {integrity: sha512-6ccPGu4u4J9bwYPHXBFPee3RZrX3BboRdU7k14zRDDB1lvN3O7J/vPRFdaEfa1+CWx4xnQQOp4ctoaF66oO0uw==} + hasBin: true + + oxlint@1.90.0: + resolution: {integrity: sha512-RkTN9EmgIUpLuhNoLhO3OliMGJlvb3Dk7XVjBZnfoMCHrVpuz5ESd97klfiyYeV7XfA2lNLnDCPMkUI+Qw5How==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + oxlint-tsgolint: '>=7.0.2005' + vite-plus: '*' + peerDependenciesMeta: + oxlint-tsgolint: + optional: true + vite-plus: + optional: true p-all@1.0.0: resolution: {integrity: sha512-OtbznqfGjQT+i89LK9C9YPh1G8d6n8xgsJ8yRVXrx6PRXrlOthNJhP+dHxrPopty8fugYb1DodpwrzP7z0Mtvw==} @@ -5786,18 +5742,10 @@ packages: resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} engines: {node: '>= 10.13.0'} - reflect.getprototypeof@1.0.10: - resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} - engines: {node: '>= 0.4'} - regex-not@1.0.2: resolution: {integrity: sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==} engines: {node: '>=0.10.0'} - regexp.prototype.flags@1.5.4: - resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} - engines: {node: '>= 0.4'} - remove-bom-buffer@3.0.0: resolution: {integrity: sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ==} engines: {node: '>=0.10.0'} @@ -5890,11 +5838,6 @@ packages: engines: {node: '>= 0.4'} hasBin: true - resolve@2.0.0-next.6: - resolution: {integrity: sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==} - engines: {node: '>= 0.4'} - hasBin: true - responselike@4.0.2: resolution: {integrity: sha512-cGk8IbWEAnaCpdAt1BHzJ3Ahz5ewDJa0KseTsE3qIRMJ3C698W8psM7byCeWVpd/Ha7FUYzuRVzXoKoM6nRUbA==} engines: {node: '>=20'} @@ -5932,20 +5875,12 @@ packages: run-parallel@1.1.10: resolution: {integrity: sha512-zb/1OuZ6flOlH6tQyMPUrE3x3Ulxjlo9WIVXR4yVYi4H9UXQaeIsPbLn2R3O3vQCnDKkAl2qHiuocKKX4Tz/Sw==} - safe-array-concat@1.1.4: - resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} - engines: {node: '>=0.4'} - safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - safe-push-apply@1.0.0: - resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} - engines: {node: '>= 0.4'} - safe-regex-test@1.1.0: resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} engines: {node: '>= 0.4'} @@ -6017,14 +5952,6 @@ packages: resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} engines: {node: '>= 0.4'} - set-function-name@2.0.2: - resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} - engines: {node: '>= 0.4'} - - set-proto@1.0.0: - resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} - engines: {node: '>= 0.4'} - set-value@2.0.1: resolution: {integrity: sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==} engines: {node: '>=0.10.0'} @@ -6206,10 +6133,6 @@ packages: resolution: {integrity: sha512-xhV7w8S+bUwlPTb4bAOUQhv8/cSS5offJuX8GQGq32ONF0ZtDWKfkdomM3HMRA+LhX6um/FZ0COqlwsjD53LeQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - stop-iteration-iterator@1.1.0: - resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} - engines: {node: '>= 0.4'} - stream-combiner@0.0.4: resolution: {integrity: sha512-rT00SPnTVyRsaSz5zgSPma/aHSOic5U1prhYdRy5HS2kTZviFpmDgzilbtsJsxiroqACmayynDN/9VzIbX5DOw==} @@ -6251,18 +6174,6 @@ packages: resolution: {integrity: sha512-k01swCJAgQmuADB0YIc+7TuatfNvTBVOoaUWJjTB9R4VJzR5vNWzf5t42ESVZFPS8xTySF7CAdV4t/aaIm3UnQ==} engines: {node: '>=16'} - string.prototype.trim@1.2.10: - resolution: {integrity: sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==} - engines: {node: '>= 0.4'} - - string.prototype.trimend@1.0.9: - resolution: {integrity: sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==} - engines: {node: '>= 0.4'} - - string.prototype.trimstart@1.0.8: - resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} - engines: {node: '>= 0.4'} - string_decoder@0.10.31: resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==} @@ -6289,10 +6200,6 @@ packages: resolution: {integrity: sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==} engines: {node: '>=0.10.0'} - strip-bom@3.0.0: - resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} - engines: {node: '>=4'} - strip-json-comments@2.0.1: resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} engines: {node: '>=0.10.0'} @@ -6504,9 +6411,6 @@ packages: ts-morph@25.0.1: resolution: {integrity: sha512-QJEiTdnz1YjrB3JFhd626gX4rKHDLSjSVMvGGG4v7ONc3RBwa0Eei98G9AT9uNFDMtV54JyuXsFeC+OH0n6bXQ==} - tsconfig-paths@3.15.0: - resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==} - tsec@0.2.7: resolution: {integrity: sha512-Pj9DuBBWLEo8p7QsbrEdXzW/u6QJBcib0ZGOTXkeSDx+PLXFY7hwyZE9Tfhp3TA3LQNpYouyT0WmzXRyUW4otQ==} hasBin: true @@ -6553,22 +6457,6 @@ packages: type@2.7.2: resolution: {integrity: sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw==} - typed-array-buffer@1.0.3: - resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} - engines: {node: '>= 0.4'} - - typed-array-byte-length@1.0.3: - resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} - engines: {node: '>= 0.4'} - - typed-array-byte-offset@1.0.4: - resolution: {integrity: sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==} - engines: {node: '>= 0.4'} - - typed-array-length@1.0.7: - resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==} - engines: {node: '>= 0.4'} - typedarray-to-buffer@3.1.5: resolution: {integrity: sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==} @@ -6618,10 +6506,6 @@ packages: resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==} engines: {node: '>=18'} - unbox-primitive@1.1.0: - resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} - engines: {node: '>= 0.4'} - unc-path-regex@0.1.2: resolution: {integrity: sha512-eXL4nmJT7oCpkZsHZUOJo8hcX3GbsiDOa0Qu9F646fi8dT3XuSVopVqAcEiVzSKKH7UoDti23wNX3qGFxcW5Qg==} engines: {node: '>=0.10.0'} @@ -6860,18 +6744,6 @@ packages: whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - which-boxed-primitive@1.1.1: - resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} - engines: {node: '>= 0.4'} - - which-builtin-type@1.2.1: - resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} - engines: {node: '>= 0.4'} - - which-collection@1.0.2: - resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} - engines: {node: '>= 0.4'} - which-module@1.0.0: resolution: {integrity: sha512-F6+WgncZi/mJDrammbTuHe1q0R5hOXv/mBaiNA2TCNT/LTHusX0V+CJnj9XT8ki5ln2UZyyddDgHfCzyrOH7MQ==} @@ -7892,6 +7764,81 @@ snapshots: '@opentelemetry/api@1.0.3': {} + '@oxlint-tsgolint/darwin-arm64@7.0.2005': + optional: true + + '@oxlint-tsgolint/darwin-x64@7.0.2005': + optional: true + + '@oxlint-tsgolint/linux-arm64@7.0.2005': + optional: true + + '@oxlint-tsgolint/linux-x64@7.0.2005': + optional: true + + '@oxlint-tsgolint/win32-arm64@7.0.2005': + optional: true + + '@oxlint-tsgolint/win32-x64@7.0.2005': + optional: true + + '@oxlint/binding-android-arm-eabi@1.90.0': + optional: true + + '@oxlint/binding-android-arm64@1.90.0': + optional: true + + '@oxlint/binding-darwin-arm64@1.90.0': + optional: true + + '@oxlint/binding-darwin-x64@1.90.0': + optional: true + + '@oxlint/binding-freebsd-x64@1.90.0': + optional: true + + '@oxlint/binding-linux-arm-gnueabihf@1.90.0': + optional: true + + '@oxlint/binding-linux-arm-musleabihf@1.90.0': + optional: true + + '@oxlint/binding-linux-arm64-gnu@1.90.0': + optional: true + + '@oxlint/binding-linux-arm64-musl@1.90.0': + optional: true + + '@oxlint/binding-linux-ppc64-gnu@1.90.0': + optional: true + + '@oxlint/binding-linux-riscv64-gnu@1.90.0': + optional: true + + '@oxlint/binding-linux-riscv64-musl@1.90.0': + optional: true + + '@oxlint/binding-linux-s390x-gnu@1.90.0': + optional: true + + '@oxlint/binding-linux-x64-gnu@1.90.0': + optional: true + + '@oxlint/binding-linux-x64-musl@1.90.0': + optional: true + + '@oxlint/binding-openharmony-arm64@1.90.0': + optional: true + + '@oxlint/binding-win32-arm64-msvc@1.90.0': + optional: true + + '@oxlint/binding-win32-ia32-msvc@1.90.0': + optional: true + + '@oxlint/binding-win32-x64-msvc@1.90.0': + optional: true + '@parcel/watcher@2.5.6': dependencies: detect-libc: 2.1.2 @@ -7917,8 +7864,6 @@ snapshots: '@pondwader/socks5-server@1.0.10': {} - '@rtsao/scc@1.1.0': {} - '@sec-ant/readable-stream@0.4.1': {} '@sindresorhus/base62@1.0.0': {} @@ -8013,8 +7958,6 @@ snapshots: '@types/json-schema@7.0.15': {} - '@types/json5@0.0.29': {} - '@types/junit-report-builder@3.0.2': {} '@types/kerberos@1.1.2': {} @@ -8624,43 +8567,43 @@ snapshots: '@xmldom/xmldom@0.8.15': {} - '@xterm/addon-clipboard@0.3.0-beta.303(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-clipboard@0.3.0-beta.335(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-image@0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-image@0.10.0-beta.332(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-ligatures@0.11.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-ligatures@0.11.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 lru-cache: 11.5.1 opentype.js: 2.0.0 - '@xterm/addon-progress@0.3.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-progress@0.3.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-search@0.17.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-search@0.17.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-serialize@0.15.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-serialize@0.15.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-unicode11@0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-unicode11@0.10.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-webgl@0.20.0-beta.300(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-webgl@0.20.0-beta.330(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/headless@6.1.0-beta.303': {} + '@xterm/headless@6.1.0-beta.335': {} - '@xterm/xterm@6.1.0-beta.304': {} + '@xterm/xterm@6.1.0-beta.337': {} '@xtuc/ieee754@1.2.0': {} @@ -8830,26 +8773,10 @@ snapshots: array-back@6.2.2: {} - array-buffer-byte-length@1.0.2: - dependencies: - call-bound: 1.0.4 - is-array-buffer: 3.0.5 - array-differ@1.0.0: {} array-each@1.0.1: {} - array-includes@3.1.9: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-object-atoms: 1.1.1 - get-intrinsic: 1.3.0 - is-string: 1.1.1 - math-intrinsics: 1.1.0 - array-initial@1.1.0: dependencies: array-slice: 1.1.0 @@ -8877,40 +8804,6 @@ snapshots: array-unique@0.3.2: {} - array.prototype.findlastindex@1.2.6: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-shim-unscopables: 1.1.0 - - array.prototype.flat@1.3.3: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-shim-unscopables: 1.1.0 - - array.prototype.flatmap@1.3.3: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-shim-unscopables: 1.1.0 - - arraybuffer.prototype.slice@1.0.4: - dependencies: - array-buffer-byte-length: 1.0.2 - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - is-array-buffer: 3.0.5 - arrify@1.0.1: {} asar@3.0.3: @@ -8939,8 +8832,6 @@ snapshots: async-each@1.0.3: {} - async-function@1.0.0: {} - async-settle@1.0.0: dependencies: async-done: 1.3.2 @@ -9564,24 +9455,6 @@ snapshots: es5-ext: 0.10.64 type: 1.2.0 - data-view-buffer@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-length@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-offset@1.0.1: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - debounce@1.1.0: {} debug-fabulous@1.1.0: @@ -9721,10 +9594,6 @@ snapshots: miller-rabin: 4.0.1 randombytes: 2.1.0 - doctrine@2.1.0: - dependencies: - esutils: 2.0.3 - dom-serializer@2.0.0: dependencies: domelementtype: 2.3.0 @@ -9812,63 +9681,6 @@ snapshots: dependencies: is-arrayish: 0.2.1 - es-abstract@1.24.2: - dependencies: - array-buffer-byte-length: 1.0.2 - arraybuffer.prototype.slice: 1.0.4 - available-typed-arrays: 1.0.7 - call-bind: 1.0.9 - call-bound: 1.0.4 - data-view-buffer: 1.0.2 - data-view-byte-length: 1.0.2 - data-view-byte-offset: 1.0.1 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-set-tostringtag: 2.1.0 - es-to-primitive: 1.3.0 - function.prototype.name: 1.1.8 - get-intrinsic: 1.3.0 - get-proto: 1.0.1 - get-symbol-description: 1.1.0 - globalthis: 1.0.4 - gopd: 1.2.0 - has-property-descriptors: 1.0.2 - has-proto: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.4 - internal-slot: 1.1.0 - is-array-buffer: 3.0.5 - is-callable: 1.2.7 - is-data-view: 1.0.2 - is-negative-zero: 2.0.3 - is-regex: 1.2.1 - is-set: 2.0.3 - is-shared-array-buffer: 1.0.4 - is-string: 1.1.1 - is-typed-array: 1.1.15 - is-weakref: 1.1.1 - math-intrinsics: 1.1.0 - object-inspect: 1.13.4 - object-keys: 1.1.1 - object.assign: 4.1.7 - own-keys: 1.0.1 - regexp.prototype.flags: 1.5.4 - safe-array-concat: 1.1.4 - safe-push-apply: 1.0.0 - safe-regex-test: 1.1.0 - set-proto: 1.0.0 - stop-iteration-iterator: 1.1.0 - string.prototype.trim: 1.2.10 - string.prototype.trimend: 1.0.9 - string.prototype.trimstart: 1.0.8 - typed-array-buffer: 1.0.3 - typed-array-byte-length: 1.0.3 - typed-array-byte-offset: 1.0.4 - typed-array-length: 1.0.7 - unbox-primitive: 1.1.0 - which-typed-array: 1.1.20 - es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -9886,16 +9698,6 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 - es-shim-unscopables@1.1.0: - dependencies: - hasown: 2.0.4 - - es-to-primitive@1.3.0: - dependencies: - is-callable: 1.2.7 - is-date-object: 1.1.0 - is-symbol: 1.1.1 - es5-ext@0.10.64: dependencies: es6-iterator: 2.0.3 @@ -9931,54 +9733,10 @@ snapshots: eslint-formatter-compact@8.40.0: {} - eslint-import-resolver-node@0.3.10: - dependencies: - debug: 3.2.7 - is-core-module: 2.16.1 - resolve: 2.0.0-next.6 - transitivePeerDependencies: - - supports-color - - eslint-module-utils@2.12.1(eslint-import-resolver-node@0.3.10)(eslint@10.8.0): - dependencies: - debug: 3.2.7 - optionalDependencies: - eslint: 10.8.0 - eslint-import-resolver-node: 0.3.10 - transitivePeerDependencies: - - supports-color - eslint-plugin-header@3.1.1(eslint@10.8.0): dependencies: eslint: 10.8.0 - eslint-plugin-import@2.32.0(eslint@10.8.0): - dependencies: - '@rtsao/scc': 1.1.0 - array-includes: 3.1.9 - array.prototype.findlastindex: 1.2.6 - array.prototype.flat: 1.3.3 - array.prototype.flatmap: 1.3.3 - debug: 3.2.7 - doctrine: 2.1.0 - eslint: 10.8.0 - eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.12.1(eslint-import-resolver-node@0.3.10)(eslint@10.8.0) - hasown: 2.0.4 - is-core-module: 2.16.1 - is-glob: 4.0.3 - minimatch: 3.1.5 - object.fromentries: 2.0.8 - object.groupby: 1.0.3 - object.values: 1.2.1 - semver: 6.3.1 - string.prototype.trimend: 1.0.9 - tsconfig-paths: 3.15.0 - transitivePeerDependencies: - - eslint-import-resolver-typescript - - eslint-import-resolver-webpack - - supports-color - eslint-plugin-jsdoc@63.3.3(eslint@10.8.0): dependencies: '@es-joy/jsdoccomment': 0.91.0 @@ -10444,17 +10202,6 @@ snapshots: function-bind@1.1.2: {} - function.prototype.name@1.1.8: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - functions-have-names: 1.2.3 - hasown: 2.0.4 - is-callable: 1.2.7 - - functions-have-names@1.2.3: {} - generator-function@2.0.1: {} gensync@1.0.0-beta.2: {} @@ -10492,12 +10239,6 @@ snapshots: '@sec-ant/readable-stream': 0.4.1 is-stream: 4.0.1 - get-symbol-description@1.1.0: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - get-value@2.0.6: {} github-from-package@0.0.0: {} @@ -10613,11 +10354,6 @@ snapshots: is-windows: 1.0.2 which: 1.3.1 - globalthis@1.0.4: - dependencies: - define-properties: 1.2.1 - gopd: 1.2.0 - glogg@1.0.2: dependencies: sparkles: 1.0.1 @@ -10787,8 +10523,6 @@ snapshots: dependencies: ansi-regex: 2.1.1 - has-bigints@1.1.0: {} - has-flag@3.0.0: {} has-flag@4.0.0: {} @@ -10797,10 +10531,6 @@ snapshots: dependencies: es-define-property: 1.0.1 - has-proto@1.2.0: - dependencies: - dunder-proto: 1.0.1 - has-symbols@1.1.0: {} has-tostringtag@1.0.2: @@ -10967,12 +10697,6 @@ snapshots: innosetup@6.4.1: {} - internal-slot@1.1.0: - dependencies: - es-errors: 1.3.0 - hasown: 2.0.4 - side-channel: 1.1.1 - interpret@1.4.0: {} interpret@3.1.1: {} @@ -11001,26 +10725,8 @@ snapshots: call-bind: 1.0.9 has-tostringtag: 1.0.2 - is-array-buffer@3.0.5: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - is-arrayish@0.2.1: {} - is-async-function@2.1.1: - dependencies: - async-function: 1.0.0 - call-bound: 1.0.4 - get-proto: 1.0.1 - has-tostringtag: 1.0.2 - safe-regex-test: 1.1.0 - - is-bigint@1.1.0: - dependencies: - has-bigints: 1.1.0 - is-binary-path@1.0.1: dependencies: binary-extensions: 1.13.1 @@ -11029,11 +10735,6 @@ snapshots: dependencies: binary-extensions: 2.2.0 - is-boolean-object@1.2.2: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - is-buffer@1.1.6: {} is-callable@1.2.7: {} @@ -11054,17 +10755,6 @@ snapshots: dependencies: kind-of: 6.0.3 - is-data-view@1.0.2: - dependencies: - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - is-typed-array: 1.1.15 - - is-date-object@1.1.0: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - is-deflate@1.0.0: {} is-descriptor@0.1.6: @@ -11091,10 +10781,6 @@ snapshots: is-extglob@2.1.1: {} - is-finalizationregistry@1.1.1: - dependencies: - call-bound: 1.0.4 - is-fullwidth-code-point@1.0.0: dependencies: number-is-nan: 1.0.1 @@ -11125,17 +10811,8 @@ snapshots: is-interactive@2.0.0: {} - is-map@2.0.3: {} - is-negated-glob@1.0.0: {} - is-negative-zero@2.0.3: {} - - is-number-object@1.1.1: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - is-number@3.0.0: dependencies: kind-of: 3.2.2 @@ -11167,27 +10844,10 @@ snapshots: dependencies: is-unc-path: 1.0.0 - is-set@2.0.3: {} - - is-shared-array-buffer@1.0.4: - dependencies: - call-bound: 1.0.4 - is-stream@1.1.0: {} is-stream@4.0.1: {} - is-string@1.1.1: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - - is-symbol@1.1.1: - dependencies: - call-bound: 1.0.4 - has-symbols: 1.1.0 - safe-regex-test: 1.1.0 - is-typed-array@1.1.15: dependencies: which-typed-array: 1.1.20 @@ -11206,17 +10866,6 @@ snapshots: is-valid-glob@1.0.0: {} - is-weakmap@2.0.2: {} - - is-weakref@1.1.1: - dependencies: - call-bound: 1.0.4 - - is-weakset@2.0.4: - dependencies: - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - is-windows@1.0.2: {} is-wsl@2.2.0: @@ -11231,8 +10880,6 @@ snapshots: isarray@1.0.0: {} - isarray@2.0.5: {} - isexe@2.0.0: {} isexe@3.1.1: {} @@ -11358,10 +11005,6 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} - json5@1.0.2: - dependencies: - minimist: 1.2.8 - json5@2.2.3: {} jsonfile@6.1.0: @@ -11897,13 +11540,6 @@ snapshots: node-addon-api@8.9.2: {} - node-exports-info@1.6.0: - dependencies: - array.prototype.flatmap: 1.3.3 - es-errors: 1.3.0 - object.entries: 1.1.9 - semver: 6.3.1 - node-fetch@2.6.7: dependencies: whatwg-url: 5.0.0 @@ -12027,26 +11663,6 @@ snapshots: for-own: 1.0.0 isobject: 3.0.1 - object.entries@1.1.9: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - object.fromentries@2.0.8: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-object-atoms: 1.1.1 - - object.groupby@1.0.3: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - object.map@1.0.1: dependencies: for-own: 1.0.0 @@ -12061,13 +11677,6 @@ snapshots: for-own: 1.0.0 make-iterator: 1.0.1 - object.values@1.2.1: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - on-finished@2.4.1: dependencies: ee-first: 1.1.1 @@ -12129,11 +11738,37 @@ snapshots: os-homedir: 1.0.2 os-tmpdir: 1.0.2 - own-keys@1.0.1: - dependencies: - get-intrinsic: 1.3.0 - object-keys: 1.1.1 - safe-push-apply: 1.0.0 + oxlint-tsgolint@7.0.2005: + optionalDependencies: + '@oxlint-tsgolint/darwin-arm64': 7.0.2005 + '@oxlint-tsgolint/darwin-x64': 7.0.2005 + '@oxlint-tsgolint/linux-arm64': 7.0.2005 + '@oxlint-tsgolint/linux-x64': 7.0.2005 + '@oxlint-tsgolint/win32-arm64': 7.0.2005 + '@oxlint-tsgolint/win32-x64': 7.0.2005 + + oxlint@1.90.0(oxlint-tsgolint@7.0.2005): + optionalDependencies: + '@oxlint/binding-android-arm-eabi': 1.90.0 + '@oxlint/binding-android-arm64': 1.90.0 + '@oxlint/binding-darwin-arm64': 1.90.0 + '@oxlint/binding-darwin-x64': 1.90.0 + '@oxlint/binding-freebsd-x64': 1.90.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.90.0 + '@oxlint/binding-linux-arm-musleabihf': 1.90.0 + '@oxlint/binding-linux-arm64-gnu': 1.90.0 + '@oxlint/binding-linux-arm64-musl': 1.90.0 + '@oxlint/binding-linux-ppc64-gnu': 1.90.0 + '@oxlint/binding-linux-riscv64-gnu': 1.90.0 + '@oxlint/binding-linux-riscv64-musl': 1.90.0 + '@oxlint/binding-linux-s390x-gnu': 1.90.0 + '@oxlint/binding-linux-x64-gnu': 1.90.0 + '@oxlint/binding-linux-x64-musl': 1.90.0 + '@oxlint/binding-openharmony-arm64': 1.90.0 + '@oxlint/binding-win32-arm64-msvc': 1.90.0 + '@oxlint/binding-win32-ia32-msvc': 1.90.0 + '@oxlint/binding-win32-x64-msvc': 1.90.0 + oxlint-tsgolint: 7.0.2005 p-all@1.0.0: dependencies: @@ -12531,31 +12166,11 @@ snapshots: dependencies: resolve: 1.22.11 - reflect.getprototypeof@1.0.10: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - get-intrinsic: 1.3.0 - get-proto: 1.0.1 - which-builtin-type: 1.2.1 - regex-not@1.0.2: dependencies: extend-shallow: 3.0.2 safe-regex: 1.1.0 - regexp.prototype.flags@1.5.4: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-errors: 1.3.0 - get-proto: 1.0.1 - gopd: 1.2.0 - set-function-name: 2.0.2 - remove-bom-buffer@3.0.0: dependencies: is-buffer: 1.1.6 @@ -12639,15 +12254,6 @@ snapshots: path-parse: 1.0.7 supports-preserve-symlinks-flag: 1.0.0 - resolve@2.0.0-next.6: - dependencies: - es-errors: 1.3.0 - is-core-module: 2.16.1 - node-exports-info: 1.6.0 - object-keys: 1.1.1 - path-parse: 1.0.7 - supports-preserve-symlinks-flag: 1.0.0 - responselike@4.0.2: dependencies: lowercase-keys: 3.0.0 @@ -12683,23 +12289,10 @@ snapshots: run-parallel@1.1.10: {} - safe-array-concat@1.1.4: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - has-symbols: 1.1.0 - isarray: 2.0.5 - safe-buffer@5.1.2: {} safe-buffer@5.2.1: {} - safe-push-apply@1.0.0: - dependencies: - es-errors: 1.3.0 - isarray: 2.0.5 - safe-regex-test@1.1.0: dependencies: call-bound: 1.0.4 @@ -12783,19 +12376,6 @@ snapshots: gopd: 1.2.0 has-property-descriptors: 1.0.2 - set-function-name@2.0.2: - dependencies: - define-data-property: 1.1.4 - es-errors: 1.3.0 - functions-have-names: 1.2.3 - has-property-descriptors: 1.0.2 - - set-proto@1.0.0: - dependencies: - dunder-proto: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - set-value@2.0.1: dependencies: extend-shallow: 2.0.1 @@ -13000,11 +12580,6 @@ snapshots: dependencies: bl: 5.1.0 - stop-iteration-iterator@1.1.0: - dependencies: - es-errors: 1.3.0 - internal-slot: 1.1.0 - stream-combiner@0.0.4: dependencies: duplexer: 0.1.1 @@ -13063,29 +12638,6 @@ snapshots: emoji-regex: 10.3.0 strip-ansi: 7.1.2 - string.prototype.trim@1.2.10: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-data-property: 1.1.4 - define-properties: 1.2.1 - es-abstract: 1.24.2 - es-object-atoms: 1.1.1 - has-property-descriptors: 1.0.2 - - string.prototype.trimend@1.0.9: - dependencies: - call-bind: 1.0.9 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - string.prototype.trimstart@1.0.8: - dependencies: - call-bind: 1.0.9 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - string_decoder@0.10.31: {} string_decoder@1.1.1: @@ -13110,8 +12662,6 @@ snapshots: dependencies: is-utf8: 0.2.1 - strip-bom@3.0.0: {} - strip-json-comments@2.0.1: {} strip-json-comments@3.1.1: {} @@ -13350,13 +12900,6 @@ snapshots: '@ts-morph/common': 0.26.1 code-block-writer: 13.0.3 - tsconfig-paths@3.15.0: - dependencies: - '@types/json5': 0.0.29 - json5: 1.0.2 - minimist: 1.2.8 - strip-bom: 3.0.0 - tsec@0.2.7(@typescript/typescript6@6.0.2): dependencies: glob: 7.2.3 @@ -13395,39 +12938,6 @@ snapshots: type@2.7.2: {} - typed-array-buffer@1.0.3: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-typed-array: 1.1.15 - - typed-array-byte-length@1.0.3: - dependencies: - call-bind: 1.0.9 - for-each: 0.3.5 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - - typed-array-byte-offset@1.0.4: - dependencies: - available-typed-arrays: 1.0.7 - call-bind: 1.0.9 - for-each: 0.3.5 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - reflect.getprototypeof: 1.0.10 - - typed-array-length@1.0.7: - dependencies: - call-bind: 1.0.9 - for-each: 0.3.5 - gopd: 1.2.0 - is-typed-array: 1.1.15 - possible-typed-array-names: 1.1.0 - reflect.getprototypeof: 1.0.10 - typedarray-to-buffer@3.1.5: dependencies: is-typedarray: 1.0.0 @@ -13482,13 +12992,6 @@ snapshots: uint8array-extras@1.5.0: {} - unbox-primitive@1.1.0: - dependencies: - call-bound: 1.0.4 - has-bigints: 1.1.0 - has-symbols: 1.1.0 - which-boxed-primitive: 1.1.1 - unc-path-regex@0.1.2: {} undefsafe@2.0.5: {} @@ -13812,37 +13315,6 @@ snapshots: tr46: 0.0.3 webidl-conversions: 3.0.1 - which-boxed-primitive@1.1.1: - dependencies: - is-bigint: 1.1.0 - is-boolean-object: 1.2.2 - is-number-object: 1.1.1 - is-string: 1.1.1 - is-symbol: 1.1.1 - - which-builtin-type@1.2.1: - dependencies: - call-bound: 1.0.4 - function.prototype.name: 1.1.8 - has-tostringtag: 1.0.2 - is-async-function: 2.1.1 - is-date-object: 1.1.0 - is-finalizationregistry: 1.1.1 - is-generator-function: 1.1.2 - is-regex: 1.2.1 - is-weakref: 1.1.1 - isarray: 2.0.5 - which-boxed-primitive: 1.1.1 - which-collection: 1.0.2 - which-typed-array: 1.1.20 - - which-collection@1.0.2: - dependencies: - is-map: 2.0.3 - is-set: 2.0.3 - is-weakmap: 2.0.2 - is-weakset: 2.0.4 - which-module@1.0.0: {} which-module@2.0.0: {} diff --git a/remote/package.json b/remote/package.json index 1eb834dfa25b..001e4f558618 100644 --- a/remote/package.json +++ b/remote/package.json @@ -20,6 +20,7 @@ "@parcel/watcher": "^2.5.6", "@vscode/copilot-api": "^0.5.2", "@vscode/deviceid": "^0.1.1", + "@vscode/diff": "0.0.2-128", "@vscode/fs-copyfile": "2.0.0", "@vscode/iconv-lite-umd": "0.7.1", "@vscode/native-watchdog": "^1.4.6", @@ -32,16 +33,16 @@ "@vscode/vscode-languagedetection": "1.0.23", "@vscode/windows-process-tree": "^0.8.0", "@vscode/windows-registry": "^1.3.0", - "@xterm/addon-clipboard": "^0.3.0-beta.303", - "@xterm/addon-image": "^0.10.0-beta.301", - "@xterm/addon-ligatures": "^0.11.0-beta.301", - "@xterm/addon-progress": "^0.3.0-beta.301", - "@xterm/addon-search": "^0.17.0-beta.301", - "@xterm/addon-serialize": "^0.15.0-beta.301", - "@xterm/addon-unicode11": "^0.10.0-beta.301", - "@xterm/addon-webgl": "^0.20.0-beta.300", - "@xterm/headless": "^6.1.0-beta.303", - "@xterm/xterm": "^6.1.0-beta.304", + "@xterm/addon-clipboard": "^0.3.0-beta.335", + "@xterm/addon-image": "^0.10.0-beta.332", + "@xterm/addon-ligatures": "^0.11.0-beta.331", + "@xterm/addon-progress": "^0.3.0-beta.331", + "@xterm/addon-search": "^0.17.0-beta.331", + "@xterm/addon-serialize": "^0.15.0-beta.331", + "@xterm/addon-unicode11": "^0.10.0-beta.331", + "@xterm/addon-webgl": "^0.20.0-beta.330", + "@xterm/headless": "^6.1.0-beta.335", + "@xterm/xterm": "^6.1.0-beta.337", "cookie": "^0.7.0", "detect-libc": "^2.1.2", "http-proxy-agent": "^7.0.0", diff --git a/remote/pnpm-lock.yaml b/remote/pnpm-lock.yaml index 7de604860d99..5bb82b355502 100644 --- a/remote/pnpm-lock.yaml +++ b/remote/pnpm-lock.yaml @@ -40,6 +40,9 @@ importers: '@vscode/deviceid': specifier: ^0.1.1 version: 0.1.5 + '@vscode/diff': + specifier: 0.0.2-128 + version: 0.0.2-128 '@vscode/fs-copyfile': specifier: 2.0.0 version: 2.0.0 @@ -77,35 +80,35 @@ importers: specifier: ^1.3.0 version: 1.3.0 '@xterm/addon-clipboard': - specifier: ^0.3.0-beta.303 - version: 0.3.0-beta.303(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.335 + version: 0.3.0-beta.335(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-image': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.332 + version: 0.10.0-beta.332(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-ligatures': - specifier: ^0.11.0-beta.301 - version: 0.11.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.11.0-beta.331 + version: 0.11.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-progress': - specifier: ^0.3.0-beta.301 - version: 0.3.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.331 + version: 0.3.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-search': - specifier: ^0.17.0-beta.301 - version: 0.17.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.17.0-beta.331 + version: 0.17.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-serialize': - specifier: ^0.15.0-beta.301 - version: 0.15.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.15.0-beta.331 + version: 0.15.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-unicode11': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.331 + version: 0.10.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-webgl': - specifier: ^0.20.0-beta.300 - version: 0.20.0-beta.300(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.20.0-beta.330 + version: 0.20.0-beta.330(@xterm/xterm@6.1.0-beta.337) '@xterm/headless': - specifier: ^6.1.0-beta.303 - version: 6.1.0-beta.303 + specifier: ^6.1.0-beta.335 + version: 6.1.0-beta.335 '@xterm/xterm': - specifier: ^6.1.0-beta.304 - version: 6.1.0-beta.304 + specifier: ^6.1.0-beta.337 + version: 6.1.0-beta.337 cookie: specifier: ^0.7.0 version: 0.7.2 @@ -181,6 +184,9 @@ importers: '@vscode/codicons': specifier: ^0.0.46-49 version: 0.0.46-49 + '@vscode/diff': + specifier: 0.0.2-128 + version: 0.0.2-128 '@vscode/iconv-lite-umd': specifier: 0.7.1 version: 0.7.1 @@ -191,32 +197,32 @@ importers: specifier: 1.0.23 version: 1.0.23 '@xterm/addon-clipboard': - specifier: ^0.3.0-beta.303 - version: 0.3.0-beta.303(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.335 + version: 0.3.0-beta.335(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-image': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.332 + version: 0.10.0-beta.332(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-ligatures': - specifier: ^0.11.0-beta.301 - version: 0.11.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.11.0-beta.331 + version: 0.11.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-progress': - specifier: ^0.3.0-beta.301 - version: 0.3.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.3.0-beta.331 + version: 0.3.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-search': - specifier: ^0.17.0-beta.301 - version: 0.17.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.17.0-beta.331 + version: 0.17.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-serialize': - specifier: ^0.15.0-beta.301 - version: 0.15.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.15.0-beta.331 + version: 0.15.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-unicode11': - specifier: ^0.10.0-beta.301 - version: 0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.10.0-beta.331 + version: 0.10.0-beta.331(@xterm/xterm@6.1.0-beta.337) '@xterm/addon-webgl': - specifier: ^0.20.0-beta.300 - version: 0.20.0-beta.300(@xterm/xterm@6.1.0-beta.304) + specifier: ^0.20.0-beta.330 + version: 0.20.0-beta.330(@xterm/xterm@6.1.0-beta.337) '@xterm/xterm': - specifier: ^6.1.0-beta.304 - version: 6.1.0-beta.304 + specifier: ^6.1.0-beta.337 + version: 6.1.0-beta.337 jschardet: specifier: 3.1.4 version: 3.1.4 @@ -427,6 +433,9 @@ packages: '@vscode/deviceid@0.1.5': resolution: {integrity: sha512-D0be67wWo7WyyBqHnRkL2bK7lp7CDH/EMN4kMV6INoKc7kxRL3nsTtngt9JZrOcZdnW59gquGRk+6KFIDyD3QA==} + '@vscode/diff@0.0.2-128': + resolution: {integrity: sha512-8Dk0Co0mU6gph7ZgthkeDCbHFuWLvMsS8RItCGL13hAGNVnd01KMCBVAYQDLhxFUh/VJ+as5arOMwtqL8YvKGA==} + '@vscode/fs-copyfile@2.0.0': resolution: {integrity: sha512-ARb4+9rN905WjJtQ2mSBG/q4pjJkSRun/MkfCeRkk7h/5J8w4vd18NCePFJ/ZucIwXx/7mr9T6nz9Vtt1tk7hg==} engines: {node: '>=22.6.0'} @@ -472,52 +481,52 @@ packages: '@vscode/windows-registry@1.3.0': resolution: {integrity: sha512-HGzILM/WfT/iFQs58q5+sj7bn+MfYD2pvTwbd9U11Faup9G/ZVAdYNi/d5Mmw0NKKupEHOpiyx/Ld92NkiYTaw==} - '@xterm/addon-clipboard@0.3.0-beta.303': - resolution: {integrity: sha512-AVw9y9f50uVcI1/LIzp4vkQzPXiRad8SFHjqo33kg7wWL4jes+Z/08jWDBLGvNfYNGhmElp9H2cg/ITErex55g==} + '@xterm/addon-clipboard@0.3.0-beta.335': + resolution: {integrity: sha512-LVuJcdUTMxzT9oWj5IrAaVe33pveD04izzIM5g3ny4pgbz0Csffn6qVmZ5SnwfJ08fp/0wDxRwnpcsd7cTpZBA==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-image@0.10.0-beta.301': - resolution: {integrity: sha512-PJZL4GlQ1ReIgbffFMaOAFxc3wOit21/G2UEM82RpH3hNHjn6MH8ilz3ToDeBjYuOqU7ienBaeIuMbNktX4/HA==} + '@xterm/addon-image@0.10.0-beta.332': + resolution: {integrity: sha512-9Ny3X2w41hTnr4pTraV0PkwhS4rEtUR6UkbBWJCu22pngzoSb7RdLDDi221aacsIKiKtQwQCIDVq3m6wGhw9Mg==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-ligatures@0.11.0-beta.301': - resolution: {integrity: sha512-8F3D/DHbi3W+ool0xIV90paDGJYqUU/SQ9Pdltgx2nw9QFFgjtq+OscXANhrNhDzIU80p2GCnwV0jW+a6Dal0w==} + '@xterm/addon-ligatures@0.11.0-beta.331': + resolution: {integrity: sha512-RZjGMHwraIB/fZEZOrhtUYxvJobGQGBEY3ao/hbi5oxwGfQoUlX6PaFTUN3KCX+zFBDgpvq70kK53wyTzcnXVQ==} engines: {node: '>8.0.0'} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-progress@0.3.0-beta.301': - resolution: {integrity: sha512-9V04P0yncSSOZTgNvlEo6D3xiaHxALqoxEgQqgGhf20mj2eOQE0sfVPRMtO6wJwi4uI2viORUkBuiYBObvif3g==} + '@xterm/addon-progress@0.3.0-beta.331': + resolution: {integrity: sha512-4PylaZeZnBeJmTLFZ76DAF/hmUW8kk0igYhDvgeVpLV5no/ud+hmtXXOFAC7BrtE5ltkW9fFjItm+cHXTj13+A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-search@0.17.0-beta.301': - resolution: {integrity: sha512-Dj8q+p2/5c4fcS4hag6QaXngxstnc4DdzREN/IhpGxz5a1JpW/3FnF9/JE1P1wvNLp9fApgGmZqBMW4xCF6HKg==} + '@xterm/addon-search@0.17.0-beta.331': + resolution: {integrity: sha512-oYdFS2BXVXzwosRJ9kf9niHABDaLBBk2YgAmCyYz3gQgqXb5omgQH2NcBESc1qqf0G5SzJRWTcFaNWE7aakd6A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-serialize@0.15.0-beta.301': - resolution: {integrity: sha512-zWT0Sy5GCSTnarAXRiicu3XYHgam8DPtpkWfSLPME+A3s7U1A6Jy+ZATt8vMkatyeVOPI0GICYRuQJLZVgnVow==} + '@xterm/addon-serialize@0.15.0-beta.331': + resolution: {integrity: sha512-UQL26TFwWulbhrvdLE21hx32hju5B6B9tTihqvd1XwfB7Fbje459/gC2Eha2Dane7YU+SZ+PIcsloA5zd4AwnQ==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-unicode11@0.10.0-beta.301': - resolution: {integrity: sha512-SS5BzfbvfFIikE4xZFAtHu6n0Kl5R1ZCPx41RL2WULLSE+HFo/WmYee53tMxNK/QUjpcQWepeVB7HebCPhHnig==} + '@xterm/addon-unicode11@0.10.0-beta.331': + resolution: {integrity: sha512-GW2EOP+4+ZXQS/KfTgriP2QxDOSMe9ffnEkq7tgIwAfiTUcE3X/oxn6wBNdyxuM/5mLyK7wzi1O8ycV83yAYPw==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/addon-webgl@0.20.0-beta.300': - resolution: {integrity: sha512-BJQiOx8I+zz2woe+/E9nWprRRPevo9slPgyOd43E8o18aG307ccsyaTJoIbSu99uqfDoVLWDRLTy91ZXTFsdig==} + '@xterm/addon-webgl@0.20.0-beta.330': + resolution: {integrity: sha512-gcxemutOlpGCEnxZckSwR8oZ/twZXrcQw6N3aRcDVrPguIMr9YvrzegfllCo4WxRnOc4gWkHhjD1toX3emug3A==} peerDependencies: - '@xterm/xterm': ^6.1.0-beta.304 + '@xterm/xterm': ^6.1.0-beta.337 - '@xterm/headless@6.1.0-beta.303': - resolution: {integrity: sha512-FjPRg5OF0UdloypPRZcUdtpxaxYKk7FdNArgpOaedoj7UWzinB+THZyEY7t6QHRR5bjcbz7B7s4vX0Zo5LT6aw==} + '@xterm/headless@6.1.0-beta.335': + resolution: {integrity: sha512-3/hfyBw8B67K1x0yy7R6H8oodJgleTxCpuc57Ulwb5YLNc7kF6yMJF8ig/tk4vZilRzdSmoh1xFvwbBjgnU6hg==} - '@xterm/xterm@6.1.0-beta.304': - resolution: {integrity: sha512-Wq9d4qFYslYQBIan+riXotdyurtREc6v+HWdAwV6Y2JSDI9eJ1dkWm/fzYb2rCGgGnM3baiYuSK4Z6OLNKLzDw==} + '@xterm/xterm@6.1.0-beta.337': + resolution: {integrity: sha512-zstczNBAT/FaaWzCCoLx3DavRcAW0ndK7g/Y0893nPvZwWmjMU8WeuqJYqMRVommGwv1KRoxdlOOt0KukxHadA==} agent-base@7.1.1: resolution: {integrity: sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==} @@ -1040,6 +1049,8 @@ snapshots: fs-extra: 11.2.0 uuid: 14.0.0 + '@vscode/diff@0.0.2-128': {} + '@vscode/fs-copyfile@2.0.0': dependencies: node-addon-api: 7.1.1 @@ -1097,43 +1108,43 @@ snapshots: '@vscode/windows-registry@1.3.0': {} - '@xterm/addon-clipboard@0.3.0-beta.303(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-clipboard@0.3.0-beta.335(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-image@0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-image@0.10.0-beta.332(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-ligatures@0.11.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-ligatures@0.11.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 lru-cache: 11.5.1 opentype.js: 2.0.0 - '@xterm/addon-progress@0.3.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-progress@0.3.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-search@0.17.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-search@0.17.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-serialize@0.15.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-serialize@0.15.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-unicode11@0.10.0-beta.301(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-unicode11@0.10.0-beta.331(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/addon-webgl@0.20.0-beta.300(@xterm/xterm@6.1.0-beta.304)': + '@xterm/addon-webgl@0.20.0-beta.330(@xterm/xterm@6.1.0-beta.337)': dependencies: - '@xterm/xterm': 6.1.0-beta.304 + '@xterm/xterm': 6.1.0-beta.337 - '@xterm/headless@6.1.0-beta.303': {} + '@xterm/headless@6.1.0-beta.335': {} - '@xterm/xterm@6.1.0-beta.304': {} + '@xterm/xterm@6.1.0-beta.337': {} agent-base@7.1.1: dependencies: diff --git a/remote/web/package.json b/remote/web/package.json index 5dd99c6957ba..aaf05cff5d88 100644 --- a/remote/web/package.json +++ b/remote/web/package.json @@ -1,24 +1,24 @@ { "name": "vscode-web", "version": "0.0.0", - "packageManager": "pnpm@12.16.0", "private": true, "dependencies": { "@microsoft/1ds-core-js": "^3.2.13", "@microsoft/1ds-post-js": "^3.2.13", "@vscode/codicons": "^0.0.46-49", + "@vscode/diff": "0.0.2-128", "@vscode/iconv-lite-umd": "0.7.1", "@vscode/tree-sitter-wasm": "^0.3.1", "@vscode/vscode-languagedetection": "1.0.23", - "@xterm/addon-clipboard": "^0.3.0-beta.303", - "@xterm/addon-image": "^0.10.0-beta.301", - "@xterm/addon-ligatures": "^0.11.0-beta.301", - "@xterm/addon-progress": "^0.3.0-beta.301", - "@xterm/addon-search": "^0.17.0-beta.301", - "@xterm/addon-serialize": "^0.15.0-beta.301", - "@xterm/addon-unicode11": "^0.10.0-beta.301", - "@xterm/addon-webgl": "^0.20.0-beta.300", - "@xterm/xterm": "^6.1.0-beta.304", + "@xterm/addon-clipboard": "^0.3.0-beta.335", + "@xterm/addon-image": "^0.10.0-beta.332", + "@xterm/addon-ligatures": "^0.11.0-beta.331", + "@xterm/addon-progress": "^0.3.0-beta.331", + "@xterm/addon-search": "^0.17.0-beta.331", + "@xterm/addon-serialize": "^0.15.0-beta.331", + "@xterm/addon-unicode11": "^0.10.0-beta.331", + "@xterm/addon-webgl": "^0.20.0-beta.330", + "@xterm/xterm": "^6.1.0-beta.337", "jschardet": "3.1.4", "katex": "^0.16.22", "tas-client": "0.4.6", diff --git a/resources/linux/snap/snapcraft.yaml b/resources/linux/snap/snapcraft.yaml index 34ecbc645923..a9e96aa6d616 100644 --- a/resources/linux/snap/snapcraft.yaml +++ b/resources/linux/snap/snapcraft.yaml @@ -82,6 +82,15 @@ parts: cd "/snap/$snap/current" && find . -type f,l -exec rm -f "$SNAPCRAFT_PRIME/{}" \; done patchelf --print-rpath $SNAPCRAFT_PRIME/usr/share/@@NAME@@/chrome_crashpad_handler + ARCH_TRIPLET="${SNAPCRAFT_ARCH_TRIPLET:-x86_64-linux-gnu}" + for f in \ + "$SNAPCRAFT_PRIME"/usr/share/@@NAME@@/resources/app/node_modules.asar.unpacked/@github/copilot-sdk-linux-*/prebuilds/linux-*/copilot-runtime \ + "$SNAPCRAFT_PRIME"/usr/share/@@NAME@@/resources/app/node_modules.asar.unpacked/@github/copilot-sdk-linux-*/prebuilds/linux-*/runtime.node \ + "$SNAPCRAFT_PRIME"/usr/share/@@NAME@@/resources/app/node_modules.asar.unpacked/@github/copilot-sdk-linux-*/prebuilds/linux-*/libssl.so.3; do + if [ -f "$f" ]; then + patchelf --force-rpath --set-rpath '$ORIGIN:/snap/core20/current/lib/'"$ARCH_TRIPLET" "$f" + fi + done apps: diff --git a/scripts/code-sessions-web.js b/scripts/code-sessions-web.js old mode 100644 new mode 100755 index bfd080389d2e..d6fab87e724f --- a/scripts/code-sessions-web.js +++ b/scripts/code-sessions-web.js @@ -15,7 +15,7 @@ const APP_ROOT = path.join(__dirname, '..'); async function main() { const args = minimist(process.argv.slice(2), { - boolean: ['help', 'no-open', 'skip-welcome', 'mock'], + boolean: ['help', 'no-open', 'skip-welcome', 'mock', 'mobile'], string: ['host', 'port'], }); @@ -26,7 +26,8 @@ async function main() { ' --port Port to bind to (default: 8081)\n' + ' --no-open Do not open browser automatically\n' + ' --skip-welcome Skip the sessions welcome overlay\n' + - ' --mock Load mock extension for E2E testing\n' + ' --mock Load mock extension for E2E testing\n' + + ' --mobile Serve the mobile (phone) workbench entry point\n' ); return; } @@ -34,18 +35,15 @@ async function main() { const HOST = args['host'] ?? 'localhost'; const PORT = parseInt(args['port'] ?? '8081', 10); - // Collect CSS module paths from the compiled output (same as @vscode/test-web does). - // These are turned into an import map so the browser can load `import './foo.css'` - // statements as JavaScript shims that inject the CSS via `_VSCODE_CSS_LOAD`. - const cssModules = collectCssFiles(path.join(APP_ROOT, 'out'), ''); - const server = http.createServer((req, res) => { const url = new URL(req.url, `http://${HOST}:${PORT}`); // Serve the sessions workbench HTML at the root if (url.pathname === '/' || url.pathname === '/index.html') { + // Refresh the import map on each page load to include newly compiled stylesheets. + const cssModules = collectCssFiles(path.join(APP_ROOT, 'out'), ''); res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(getSessionsHTML(HOST, PORT, cssModules, args['mock'])); + res.end(getSessionsHTML(HOST, PORT, cssModules, args['mock'], args['mobile'])); return; } @@ -79,7 +77,7 @@ async function main() { }); server.listen(PORT, HOST, () => { - console.log(`\n Sessions Web running at: http://${HOST}:${PORT}/\n`); + console.log(`\n Sessions Web${args['mobile'] ? ' (mobile)' : ''} running at: http://${HOST}:${PORT}/\n`); if (!args['no-open'] && args.open !== false) { const query = args['skip-welcome'] ? '?skip-sessions-welcome' : ''; open.default(`http://${HOST}:${PORT}/${query}`); @@ -90,7 +88,7 @@ async function main() { process.on('SIGTERM', () => { server.close(); process.exit(0); }); } -function getSessionsHTML(host, port, cssModules, useMock) { +function getSessionsHTML(host, port, cssModules, useMock, useMobile) { const baseUrl = `http://${host}:${port}`; const fileRoot = `${baseUrl}/out`; @@ -112,17 +110,34 @@ function getSessionsHTML(host, port, cssModules, useMock) { ? `additionalBuiltinExtensions: [{ scheme: 'http', authority: '${host}:${port}', path: '/src/vs/sessions/test/e2e/extensions/sessions-e2e-mock' }],` : ''; + // The mobile entry point is a separate, allow-listed bundle with its own + // workbench. The mock variant swaps in the same mock services as desktop. + const entryModule = useMobile + ? (useMock ? 'test/agents.web.mobile.test.internal' : 'agents.web.mobile.main.internal') + : (useMock ? 'test/sessions.web.test.internal' : 'sessions.web.main.internal'); + + // Expose safe-area insets without disabling browser zoom. + const viewportMeta = useMobile + ? ` + + + ` + : ``; + return ` - - Sessions + ${viewportMeta} + ${useMobile ? 'Agents' : 'Sessions'} + +`; + +export interface IAppWindowCaptureFeedbackOptions { + /** Whether to flash less, and keep the screenshot from moving. */ + readonly reduceMotion: boolean; +} + +/** How the feedback ends, see {@link AppWindowCaptureFeedback.end}. */ +export interface IAppWindowCaptureFeedbackEnd { + /** The screenshot as a `data:` URL, which the feedback needs when the capture didn't show it. */ + readonly image?: string; + /** The rectangle that the screenshot flies into, in screen coordinates. */ + readonly destination?: IRectangle; + /** The corner radius of the destination. */ + readonly radius?: number; +} + +/** The feedback of a capture, which the capture shows the screenshot in. */ +export interface IAppWindowCaptureOverlay { + /** Turns the window into its screenshot, a PNG, which lifts off the window. Resolves once the screenshot shows. */ + reveal(image: Buffer): Promise; + /** Puts out the flash when the capture has no screenshot to show yet, so that the window shows meanwhile. */ + dim(): Promise; +} + +/** + * Shows the user which window of another application VS Code captures: the window flashes, then turns into its + * screenshot, which lifts off the window and flies into the chat input that it goes to, where it fades as its + * attachment shows. It draws in a transparent panel above every other window, on the display of the captured window, + * even above applications in full screen. The panel ignores the mouse and never takes focus. + */ +export class AppWindowCaptureFeedback extends Disposable { + + /** The feedback of the capture that is under way, until the capture ends it. */ + private current: CaptureOverlay | undefined; + + private readonly overlays = new Set(); + + constructor(private readonly logService: ILogService) { + super(); + this._register(toDisposable(() => { + for (const overlay of this.overlays) { + overlay.dispose(); + } + })); + } + + /** Flashes the window at the given bounds, in screen coordinates, and ends the feedback that showed before. */ + show(bounds: IRectangle, options: IAppWindowCaptureFeedbackOptions): IAppWindowCaptureOverlay { + this.current?.dispose(); + const overlay = new CaptureOverlay(bounds, options, this.logService, () => { + this.overlays.delete(overlay); + if (this.current === overlay) { + this.current = undefined; + } + }); + this.overlays.add(overlay); + this.current = overlay; + return overlay; + } + + /** + * Ends the feedback. Given a destination on the display of the window, the screenshot flies into it, then fades as + * the destination shows under it; without one, it shrinks where the window is. Without a screenshot, the flash + * fades. Resolves once the screenshot covers the destination, or once the feedback is gone. + */ + async end(screenshot: IAppWindowCaptureFeedbackEnd | undefined): Promise { + const overlay = this.current; + this.current = undefined; + if (!overlay) { + return; + } + if (screenshot && await overlay.fly(screenshot)) { + void overlay.land().finally(() => overlay.dispose()); + return; + } + if (!screenshot) { + await overlay.fade(); + } + overlay.dispose(); + } +} + +class CaptureOverlay implements IAppWindowCaptureOverlay, IDisposable { + + private readonly window: BrowserWindow; + + /** The display that the overlay covers, in screen coordinates. */ + private readonly display: IRectangle; + + /** Resolves whether the overlay shows. */ + private readonly ready: Promise; + + /** Completes once the overlay is gone, when Electron leaves the page's functions that were running unsettled. */ + private readonly disposed = new DeferredPromise(); + + private readonly timeout: ReturnType; + + constructor(bounds: IRectangle, options: IAppWindowCaptureFeedbackOptions, private readonly logService: ILogService, private readonly onDidDispose: () => void) { + this.display = screen.getDisplayMatching(bounds).bounds; + this.window = new BrowserWindow({ + ...this.display, + // Unlike other windows, a panel shows above applications in full screen. + ...(isMacintosh ? { type: 'panel' } : {}), + show: false, + frame: false, + transparent: true, + backgroundColor: '#00000000', + hasShadow: false, + resizable: false, + movable: false, + minimizable: false, + maximizable: false, + fullscreenable: false, + focusable: false, + skipTaskbar: true, + alwaysOnTop: true, + hiddenInMissionControl: true, + enableLargerThanScreen: true, + webPreferences: { + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + spellcheck: false, + backgroundThrottling: false, + }, + }); + this.window.setIgnoreMouseEvents(true); + this.window.setAlwaysOnTop(true, 'screen-saver'); + // The captured window can be on another Space than VS Code, or in full screen. + this.window.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true }); + if (isMacintosh) { + this.window.excludedFromShownWindowsMenu = true; + } + + const target = { x: bounds.x - this.display.x, y: bounds.y - this.display.y, width: bounds.width, height: bounds.height }; + this.ready = this.load(`flash(${JSON.stringify(target)}, ${getWindowRadius(bounds, this.display)}, ${JSON.stringify(!!options.reduceMotion)})`); + this.timeout = setTimeout(() => this.dispose(), FEEDBACK_TIMEOUT); + } + + async reveal(image: Buffer): Promise { + await this.run(`reveal(${JSON.stringify(`data:image/png;base64,${image.toString('base64')}`)})`); + } + + async dim(): Promise { + await this.run('dim()'); + } + + /** Flies the screenshot into the destination, or shrinks it where the window is. Resolves whether it covers the destination. */ + async fly(screenshot: IAppWindowCaptureFeedbackEnd): Promise { + const destination = this.toOverlay(screenshot.destination); + const flown = await this.run(`fly(${JSON.stringify(destination ?? null)}, ${JSON.stringify(Number(screenshot.radius) || 0)}, ${JSON.stringify(screenshot.image ?? null)})`); + return flown && !!destination; + } + + land(): Promise { + return this.run('land()'); + } + + fade(): Promise { + return this.run('fade()'); + } + + dispose(): void { + clearTimeout(this.timeout); + void this.disposed.complete(); + if (!this.window.isDestroyed()) { + this.window.destroy(); + } + this.onDidDispose(); + } + + private async load(script: string): Promise { + try { + await this.window.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(OVERLAY_PAGE)}`); + if (this.window.isDestroyed()) { + return false; + } + this.window.showInactive(); + return await this.execute(script); + } catch (error) { + if (!this.window.isDestroyed()) { + this.logService.error('[AppWindowCaptureFeedback] Showing the feedback failed:', error); + } + return false; + } + } + + /** Runs a function of the page, and resolves whether it ran. */ + private async run(script: string): Promise { + try { + if (!await this.ready || this.window.isDestroyed()) { + return false; + } + return await this.execute(script); + } catch (error) { + if (!this.window.isDestroyed()) { + this.logService.error('[AppWindowCaptureFeedback] The feedback failed:', error); + } + return false; + } + } + + /** Runs a script in the page, and resolves whether it ran, or `false` once the overlay is gone. */ + private execute(script: string): Promise { + return Promise.race([this.window.webContents.executeJavaScript(script).then(() => true), this.disposed.p.then(() => false)]); + } + + /** The rectangle in the coordinates of the overlay, when its center is on the display of the overlay. */ + private toOverlay(rect: IRectangle | undefined): IRectangle | undefined { + if (!rect) { + return undefined; + } + const x = rect.x - this.display.x; + const y = rect.y - this.display.y; + const centerX = x + rect.width / 2; + const centerY = y + rect.height / 2; + return centerX >= 0 && centerY >= 0 && centerX <= this.display.width && centerY <= this.display.height ? { x, y, width: rect.width, height: rect.height } : undefined; + } +} + +/** The corner radius of a window of macOS, which macOS 26 (Darwin 25) rounds more. A window in full screen has none. */ +function getWindowRadius(bounds: IRectangle, display: IRectangle): number { + if (bounds.x <= display.x && bounds.y <= display.y && bounds.x + bounds.width >= display.x + display.width && bounds.y + bounds.height >= display.y + display.height) { + return 0; + } + return parseInt(release(), 10) >= 25 ? 16 : 10; +} diff --git a/src/vs/platform/native/electron-main/macScreenWindows.ts b/src/vs/platform/native/electron-main/macScreenWindows.ts new file mode 100644 index 000000000000..45dd379a9ba7 --- /dev/null +++ b/src/vs/platform/native/electron-main/macScreenWindows.ts @@ -0,0 +1,152 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { execFile } from 'child_process'; +import * as fs from 'fs'; +import { tmpdir } from 'os'; +import { join } from '../../../base/common/path.js'; +import { generateUuid } from '../../../base/common/uuid.js'; +import { ILogService } from '../../log/common/log.js'; +import { IScreenWindow, IScreenWindows } from '../common/appWindows.js'; + +/** + * Lists the normal windows of macOS with Core Graphics, front to back, including those on other Spaces, from JavaScript + * for Automation. Unlike their titles, which need the Screen Recording permission, where windows are is not private. + * It also tells the path of each window's application, and which windows are on a Space, through a private API of + * macOS, `CGSCopySpacesForWindows`: when that fails, it leaves this out. It prints them as JSON. + */ +const SCRIPT = `ObjC.import('AppKit'); +ObjC.import('CoreGraphics'); +function run() { + const frontmost = $.NSWorkspace.sharedWorkspace.frontmostApplication; + const windows = (ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionAll | $.kCGWindowListExcludeDesktopElements, $.kCGNullWindowID))) || []).filter(window => window.kCGWindowLayer === 0); + const onSpace = getOnSpace(windows); + const appPaths = new Map(); + return JSON.stringify({ + frontmostPid: frontmost.isNil() ? undefined : frontmost.processIdentifier, + windows: windows.map(window => ({ + id: window.kCGWindowNumber, + pid: window.kCGWindowOwnerPID, + layer: window.kCGWindowLayer, + alpha: window.kCGWindowAlpha, + bounds: { x: window.kCGWindowBounds.X, y: window.kCGWindowBounds.Y, width: window.kCGWindowBounds.Width, height: window.kCGWindowBounds.Height }, + onScreen: !!window.kCGWindowIsOnscreen, + onSpace: onSpace && onSpace.get(window.kCGWindowNumber), + title: window.kCGWindowName || undefined, + appPath: getAppPath(appPaths, window.kCGWindowOwnerPID), + })), + }); +} +function getOnSpace(windows) { + try { + ObjC.bindFunction('CGSMainConnectionID', ['int', []]); + ObjC.bindFunction('CGSCopySpacesForWindows', ['id', ['int', 'int', 'id']]); + const connection = $.CGSMainConnectionID(); + const onSpace = new Map(); + for (const window of windows) { + // The mask 7 includes the current Space, the others and the user's. + const spaces = ObjC.deepUnwrap($.CGSCopySpacesForWindows(connection, 7, $([window.kCGWindowNumber]))); + if (Array.isArray(spaces)) { + onSpace.set(window.kCGWindowNumber, spaces.length > 0); + } + } + return onSpace; + } catch (error) { + return undefined; + } +} +function getAppPath(appPaths, pid) { + if (!appPaths.has(pid)) { + const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(pid); + appPaths.set(pid, app.isNil() || app.bundleURL.isNil() ? undefined : app.bundleURL.path.js); + } + return appPaths.get(pid); +}`; + +/** How long listing the windows may take before a capture goes ahead without knowing where they are. */ +const TIMEOUT = 2000; + +/** How many of the applications that the user used last are looked up, which is enough to get past VS Code. */ +const MAX_RECENT_APPLICATIONS = 4; + +/** How long capturing a window may take. */ +const CAPTURE_TIMEOUT = 5000; + +/** Lists the windows of macOS and the applications that the user used, or returns `undefined` when it can't. */ +export async function getMacScreenWindows(logService: ILogService): Promise { + const [windows, recentPids] = await Promise.all([ + run('/usr/bin/osascript', ['-l', 'JavaScript', '-e', SCRIPT]).then(output => output === undefined ? undefined : parseScreenWindows(output)), + getRecentPids(), + ]); + if (!windows) { + logService.warn('[AppWindows] Listing the windows on screen failed, so captures do not show where the window is.'); + return undefined; + } + return { ...windows, recentPids }; +} + +/** The processes of the visible applications, from the one in front to the one used longest ago, as Launch Services orders them. */ +async function getRecentPids(): Promise { + const list = await run('/usr/bin/lsappinfo', ['visibleProcessList']); + const applications = Array.from(list?.matchAll(/(?ASN:0x[0-9a-f]+-0x[0-9a-f]+)/gi) ?? [], match => match.groups?.asn).slice(0, MAX_RECENT_APPLICATIONS); + const pids = await Promise.all(applications.map(async asn => { + const info = asn ? await run('/usr/bin/lsappinfo', ['info', '-only', 'pid', asn]) : undefined; + return Number(/"pid"=(?\d+)/.exec(info ?? '')?.groups?.pid); + })); + return pids.filter(pid => Number.isInteger(pid) && pid > 0); +} + +/** + * Captures a window of macOS as a PNG, without its shadow, with the system's `screencapture`. Unlike a desktop media + * stream, a single screenshot doesn't make macOS mark the window as shared, and it also captures windows on other + * Spaces. Returns `undefined` when the capture failed. + */ +export async function captureMacWindow(windowId: number, logService: ILogService): Promise { + const file = join(tmpdir(), `vscode-window-${generateUuid()}.png`); + try { + await new Promise((resolve, reject) => { + execFile('/usr/sbin/screencapture', [`-l${windowId}`, '-o', '-x', '-tpng', file], { timeout: CAPTURE_TIMEOUT }, error => error ? reject(error) : resolve()); + }); + return await fs.promises.readFile(file); + } catch (error) { + logService.error('[AppWindows] Capturing the window failed:', error); + return undefined; + } finally { + await fs.promises.rm(file, { force: true }); + } +} + +function run(command: string, args: readonly string[]): Promise { + return new Promise(resolve => { + execFile(command, args, { timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => resolve(error ? undefined : stdout)); + }); +} + +function parseScreenWindows(output: string): Omit | undefined { + let value: unknown; + try { + value = JSON.parse(output); + } catch { + return undefined; + } + const list = typeof value === 'object' && value !== null ? value as { readonly frontmostPid?: unknown; readonly windows?: unknown } : undefined; + if (!list || !Array.isArray(list.windows)) { + return undefined; + } + return { frontmostPid: typeof list.frontmostPid === 'number' ? list.frontmostPid : undefined, windows: list.windows.filter(isScreenWindow) }; +} + +function isScreenWindow(value: unknown): value is IScreenWindow { + if (typeof value !== 'object' || value === null) { + return false; + } + const window = value as Partial>; + const bounds = window.bounds as Partial> | undefined; + return typeof window.id === 'number' && typeof window.pid === 'number' && typeof window.layer === 'number' && typeof window.alpha === 'number' + && typeof window.onScreen === 'boolean' && (window.onSpace === undefined || typeof window.onSpace === 'boolean') + && (window.title === undefined || typeof window.title === 'string') && (window.appPath === undefined || typeof window.appPath === 'string') + && typeof bounds === 'object' && bounds !== null + && typeof bounds.x === 'number' && typeof bounds.y === 'number' && typeof bounds.width === 'number' && typeof bounds.height === 'number'; +} diff --git a/src/vs/platform/native/electron-main/nativeHostMainService.ts b/src/vs/platform/native/electron-main/nativeHostMainService.ts index 79ad57ce0a2e..6dd1b3fef2d3 100644 --- a/src/vs/platform/native/electron-main/nativeHostMainService.ts +++ b/src/vs/platform/native/electron-main/nativeHostMainService.ts @@ -35,7 +35,7 @@ import { IPartsSplash } from '../../theme/common/themeService.js'; import { IThemeMainService } from '../../theme/electron-main/themeMainService.js'; import { defaultWindowState, ICodeWindow, LoadReason } from '../../window/electron-main/window.js'; import { IColorScheme, IOpenedAuxiliaryWindow, IOpenedMainWindow, IOpenEmptyWindowOptions, IOpenWindowOptions, IPoint, IRectangle, IWindowOpenable } from '../../window/common/window.js'; -import { defaultBrowserWindowOptions, IWindowsMainService, OpenContext } from '../../windows/electron-main/windows.js'; +import { defaultBrowserWindowOptions, isBackgroundThrottlingAllowed, isHiddenWindowMode, IWindowsMainService, OpenContext } from '../../windows/electron-main/windows.js'; import { isWorkspaceIdentifier, toWorkspaceIdentifier } from '../../workspace/common/workspace.js'; import { IWorkspacesManagementMainService } from '../../workspaces/electron-main/workspacesManagementMainService.js'; import { VSBuffer } from '../../../base/common/buffer.js'; @@ -115,7 +115,7 @@ export class NativeHostMainService extends Disposable implements INativeHostMain ); this.onDidChangeWindowAlwaysOnTop = Event.any( - Event.None, // always on top is unsupported in main windows currently + Event.map(this.windowsMainService.onDidChangeAlwaysOnTop, e => ({ windowId: e.window.id, alwaysOnTop: e.alwaysOnTop })), Event.map(this.auxiliaryWindowsMainService.onDidChangeAlwaysOnTop, e => ({ windowId: e.window.id, alwaysOnTop: e.alwaysOnTop })) ); @@ -419,6 +419,10 @@ export class NativeHostMainService extends Disposable implements INativeHostMain } async maximizeWindow(windowId: number | undefined, options?: INativeHostOptions): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // maximize() would reveal the window + } + const window = this.windowById(options?.targetWindowId, windowId); window?.win?.maximize(); } @@ -434,6 +438,10 @@ export class NativeHostMainService extends Disposable implements INativeHostMain } async moveWindowTop(windowId: number | undefined, options?: INativeHostOptions): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // moveTop() would reveal the window + } + const window = this.windowById(options?.targetWindowId, windowId); window?.win?.moveTop(); } @@ -540,7 +548,7 @@ export class NativeHostMainService extends Disposable implements INativeHostMain this.logService.trace(`Setting background throttling for window ${windowId} to '${allowed}'`); - window?.win?.webContents?.setBackgroundThrottling(allowed); + window?.win?.webContents?.setBackgroundThrottling(isBackgroundThrottlingAllowed(this.environmentMainService, allowed)); } //#endregion @@ -1289,16 +1297,28 @@ export class NativeHostMainService extends Disposable implements INativeHostMain private contentTracingWindowId: number | undefined; async openDevTools(windowId: number | undefined, options?: Partial & INativeHostOptions): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // undocked DevTools would be shown and activate the application + } + const window = this.windowById(options?.targetWindowId, windowId); window?.win?.webContents.openDevTools(options?.mode ? { mode: options.mode, activate: options.activate } : undefined); } async toggleDevTools(windowId: number | undefined, options?: INativeHostOptions): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // undocked DevTools would be shown and activate the application + } + const window = this.windowById(options?.targetWindowId, windowId); window?.win?.webContents.toggleDevTools(); } async openDevToolsWindow(windowId: number | undefined, url: string): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // the window would be shown and focused + } + const parentWindow = this.codeWindowById(windowId); if (!parentWindow) { return; @@ -1326,6 +1346,10 @@ export class NativeHostMainService extends Disposable implements INativeHostMain } async openGPUInfoWindow(windowId: number | undefined): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // the window would be shown and focused + } + const parentWindow = this.codeWindowById(windowId); if (!parentWindow) { return; @@ -1348,6 +1372,10 @@ export class NativeHostMainService extends Disposable implements INativeHostMain } async openContentTracingWindow(): Promise { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // the window would be shown and focused + } + if (typeof this.contentTracingWindowId !== 'number') { // Disable ready-to-show event with paintWhenInitiallyHidden to // customize content tracing window below. diff --git a/src/vs/platform/native/test/common/appWindows.test.ts b/src/vs/platform/native/test/common/appWindows.test.ts new file mode 100644 index 000000000000..b2f5e9c08d9b --- /dev/null +++ b/src/vs/platform/native/test/common/appWindows.test.ts @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { excludeOwnWindowSources, getScreenWindowId, IScreenWindow, orderAppWindows } from '../../common/appWindows.js'; + +suite('excludeOwnWindowSources', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + test('leaves out the windows of VS Code by their handle, and keeps the order of the others', () => { + const sources = [{ id: 'window:11:0' }, { id: 'window:22:0' }, { id: 'window:33:1' }, { id: 'window:44:0' }]; + + assert.deepStrictEqual(excludeOwnWindowSources(sources, ['window:22:0', 'window:33:0', 'invalid']).map(source => source.id), ['window:11:0', 'window:44:0']); + }); +}); + +suite('getScreenWindowId', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + test('reads the number of a window of macOS from its source id', () => { + assert.deepStrictEqual(['window:4242:0', 'window:4242:1', 'screen:1:0', 'window:0x2a:0', 'window::0', 'invalid'].map(getScreenWindowId), [4242, 4242, undefined, undefined, undefined, undefined]); + }); +}); + +suite('orderAppWindows', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + const OWN_PID = 1; + const BROWSER_PID = 2; + const OTHER_PID = 3; + const EDITOR_PID = 4; + + function screenWindow(id: number, pid: number, options: { readonly layer?: number; readonly alpha?: number; readonly height?: number; readonly onScreen?: boolean; readonly onSpace?: boolean; readonly untitled?: boolean } = {}): IScreenWindow { + return { id, pid, layer: options.layer ?? 0, alpha: options.alpha ?? 1, bounds: { x: id, y: 0, width: 800, height: options.height ?? 600 }, onScreen: options.onScreen ?? true, onSpace: options.onSpace ?? true, title: options.untitled ? undefined : 'Window', appPath: undefined }; + } + + function order(sources: readonly string[], windows: readonly IScreenWindow[], frontmostPid: number | undefined, recentPids: readonly number[] = []) { + return orderAppWindows(sources.map(id => ({ id })), { frontmostPid, recentPids, windows }, OWN_PID).map(({ source, window }) => `${source?.id ?? 'off screen'} ${window ? window.bounds.x : '-'}`); + } + + test('puts the window to capture first: of the frontmost app unless it is VS Code, a normal window and big enough', () => { + const sources = ['window:10:0', 'window:20:0', 'window:30:0', 'window:40:0', 'window:50:0', 'window:60:0', 'window:70:0']; + // Front to back: a toolbar strip of the browser, a window of another app, the browser's window, a panel, a transparent window and a hidden one. + const windows = [ + screenWindow(20, BROWSER_PID, { height: 68 }), + screenWindow(30, OTHER_PID), + screenWindow(40, BROWSER_PID), + screenWindow(50, OTHER_PID, { layer: 3 }), + screenWindow(60, OTHER_PID, { alpha: 0 }), + screenWindow(70, OTHER_PID, { onScreen: false, onSpace: false }), + ]; + + assert.deepStrictEqual({ + browserInFront: order(sources, windows, BROWSER_PID), + vsCodeInFront: order(sources, windows, OWN_PID), + }, { + browserInFront: ['window:40:0 40', 'window:30:0 30', 'window:20:0 20', 'window:50:0 50', 'window:60:0 60', 'window:10:0 -', 'window:70:0 -'], + vsCodeInFront: ['window:30:0 30', 'window:40:0 40', 'window:20:0 20', 'window:50:0 50', 'window:60:0 60', 'window:10:0 -', 'window:70:0 -'], + }); + }); + + test('adds the titled windows on other Spaces after those to capture on screen: of the apps used last first, then front to back', () => { + const sources = ['window:10:0', 'window:20:0', 'window:60:0']; + // Front to back: the browser's window and its toolbar strip on screen, then windows that the screen doesn't show: + // another app's, VS Code's, the editor's, another app's that desktop media sources listed too, a hidden window of the + // editor with a title, an untitled one, a strip, and the browser's. + const windows = [ + screenWindow(10, BROWSER_PID), + screenWindow(20, BROWSER_PID, { height: 68 }), + screenWindow(30, OTHER_PID, { onScreen: false }), + screenWindow(40, OWN_PID, { onScreen: false }), + screenWindow(50, EDITOR_PID, { onScreen: false }), + screenWindow(60, OTHER_PID, { onScreen: false }), + screenWindow(70, EDITOR_PID, { onScreen: false, onSpace: false }), + screenWindow(80, EDITOR_PID, { onScreen: false, untitled: true }), + screenWindow(90, OTHER_PID, { onScreen: false, height: 68 }), + screenWindow(100, BROWSER_PID, { onScreen: false }), + ]; + + assert.deepStrictEqual(order(sources, windows, BROWSER_PID, [BROWSER_PID, OWN_PID, EDITOR_PID]), ['window:10:0 10', 'off screen 100', 'off screen 50', 'off screen 30', 'off screen 60', 'window:20:0 20']); + }); + + test('takes the window that the user left for VS Code when the screen shows none to capture, as in full screen', () => { + // Only VS Code shows, and on other Spaces: a hidden window of the browser with a title, the browser's window and another app's. + const windows = [ + screenWindow(10, OWN_PID), + screenWindow(20, BROWSER_PID, { onScreen: false, onSpace: false }), + screenWindow(30, BROWSER_PID, { onScreen: false }), + screenWindow(40, OTHER_PID, { onScreen: false }), + ]; + // Without the private API, which windows are on a Space is unknown: then only the front window of the app used last comes, when the screen shows none to capture. + const spacesUnknown = [...windows, screenWindow(50, OTHER_PID)].map(window => ({ ...window, onSpace: undefined })); + + assert.deepStrictEqual({ + browserUsedLast: order([], windows, OWN_PID, [OWN_PID, BROWSER_PID, OTHER_PID]), + otherUsedLast: order([], windows, OWN_PID, [OWN_PID, OTHER_PID, BROWSER_PID]), + spacesUnknown: order([], spacesUnknown, OWN_PID, [OWN_PID, BROWSER_PID, OTHER_PID]), + spacesUnknownOnlyVSCodeUsed: order([], spacesUnknown, OWN_PID, [OWN_PID]), + spacesUnknownWindowOnScreen: order(['window:50:0'], spacesUnknown, OTHER_PID, [OTHER_PID, BROWSER_PID]), + }, { + browserUsedLast: ['off screen 30', 'off screen 40'], + otherUsedLast: ['off screen 40', 'off screen 30'], + spacesUnknown: ['off screen 20'], + spacesUnknownOnlyVSCodeUsed: [], + spacesUnknownWindowOnScreen: ['window:50:0 50'], + }); + }); +}); diff --git a/src/vs/platform/path/common/pathService.ts b/src/vs/platform/path/common/pathService.ts index 997273669f65..7d14c1b12989 100644 --- a/src/vs/platform/path/common/pathService.ts +++ b/src/vs/platform/path/common/pathService.ts @@ -12,7 +12,7 @@ import { createDecorator } from '../../instantiation/common/instantiation.js'; export const IPathService = createDecorator('pathService'); export interface IResourcePathProvider { - getOperatingSystem(resource: URI): Promise; + getPath(resource: URI): Promise; } /** diff --git a/src/vs/platform/policy/common/copilotManagedSettings.ts b/src/vs/platform/policy/common/copilotManagedSettings.ts index fc1dc45a62c5..b722bf0ae943 100644 --- a/src/vs/platform/policy/common/copilotManagedSettings.ts +++ b/src/vs/platform/policy/common/copilotManagedSettings.ts @@ -24,18 +24,18 @@ function isManagedSettingInBlock(key: string, block: string): boolean { } /** - * The temporary harness control and informational organization communication do not contribute + * The harness permission controls and informational organization communication do not contribute * general presence-based governance. */ export function isManagedSettingGovernanceActive(key: string): boolean { - return !isManagedSettingInBlock(key, COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY) && !isManagedSettingInBlock(key, communicationBlockKey); + return !HARNESS_PERMISSION_KEYS.some(control => isManagedSettingInBlock(key, control)) && !isManagedSettingInBlock(key, communicationBlockKey); } -/** Detect raw governance without counting the Local-only harness control or its containing object. */ +/** Detect raw governance without counting the harness permission controls or their containing object. */ export function hasRawManagedSettings(data: RawManagedSettingsData | undefined): boolean { return data !== undefined && Object.entries(data).some(([key, value]) => { - if (key === 'vscode' && isManagedSettingsObject(value) && Object.hasOwn(value, 'temporaryAllowLocalHarness')) { - return Object.keys(value).some(key => isManagedSettingGovernanceActive(`vscode.${key}`)); + if (key === vscodeBlockKey && isManagedSettingsObject(value) && HARNESS_PERMISSION_KEYS.some(control => Object.hasOwn(value, control.slice(vscodeBlockKey.length + 1)))) { + return Object.keys(value).some(key => isManagedSettingGovernanceActive(`${vscodeBlockKey}.${key}`)); } return isManagedSettingGovernanceActive(key); }); @@ -95,6 +95,57 @@ export const COPILOT_TEMPORARY_DEFAULT_TO_LOCAL_HARNESS_KEY = 'vscode.temporaryD /** Temporary managed permission for Local, Claude, and Codex harnesses; only false prohibits them. */ export const COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY = 'vscode.temporaryAllowLocalHarness'; +/** + * Managed permission list for the third-party harnesses (carried as a JSON-encoded array of + * {@link ManagedThirdPartyHarness} IDs). Absent = managed-settings presence disables both; a + * present list permits exactly the harnesses it names, so `[]` denies both. Entries that are not + * a known ID are ignored. A listed harness is only exempt from the presence block: it is still + * ungoverned by Copilot runtime managed settings. + */ +export const COPILOT_ALLOWED_HARNESSES_KEY = 'vscode.allowedHarnesses'; + +/** The VS Code-specific managed preferences block. */ +const vscodeBlockKey = 'vscode'; + +/** Harness permissions, which are consumed on their own and never count as managed governance. */ +const HARNESS_PERMISSION_KEYS: readonly string[] = [COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, COPILOT_ALLOWED_HARNESSES_KEY]; + +/** A third-party harness that {@link COPILOT_ALLOWED_HARNESSES_KEY} can permit. */ +export type ManagedThirdPartyHarness = 'claude' | 'codex'; + +const MANAGED_THIRD_PARTY_HARNESSES: readonly string[] = ['claude', 'codex'] satisfies ManagedThirdPartyHarness[]; + +function isManagedThirdPartyHarness(value: unknown): value is ManagedThirdPartyHarness { + return typeof value === 'string' && MANAGED_THIRD_PARTY_HARNESSES.includes(value); +} + +/** An effective {@link COPILOT_ALLOWED_HARNESSES_KEY} list. */ +export interface IAllowedHarnesses { + /** The permitted harnesses. Duplicate entries are harmless. */ + readonly harnesses: readonly ManagedThirdPartyHarness[]; + /** Whether the list has entries that are not a known harness ID, which are ignored. */ + readonly hasUnrecognizedEntries: boolean; +} + +/** + * Parse an effective {@link COPILOT_ALLOWED_HARNESSES_KEY} value. Entries other than an exact + * harness ID are ignored rather than invalidating the list, so a list can name a harness that only + * newer clients know without older clients denying the ones they do know. Returns `undefined` for + * a value that is not a JSON array, which permits nothing. + */ +export function parseAllowedHarnesses(value: ManagedSettingValue): IAllowedHarnesses | undefined { + if (typeof value !== 'string') { + return undefined; + } + const errors: ParseError[] = []; + const entries: unknown = parse(value, errors, { disallowComments: true, allowTrailingComma: false }); + if (errors.length > 0 || !Array.isArray(entries)) { + return undefined; + } + const harnesses = entries.filter(isManagedThirdPartyHarness); + return { harnesses, hasUnrecognizedEntries: harnesses.length !== entries.length }; +} + /** Policy-only configuration projection of the Local harness escape hatch. */ export const TemporaryDefaultToLocalHarnessSettingId = 'chat.temporaryDefaultToLocalHarness'; @@ -173,6 +224,7 @@ export const MANAGED_SETTINGS_CONTROL_DEFINITIONS: IManagedSettingsPolicyDefinit [COPILOT_FORCE_REMOTE_SETTINGS_REFRESH_KEY]: { type: 'boolean' }, [COPILOT_STRICT_MARKETPLACES_KEY]: { type: 'string' }, [COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY]: { type: 'boolean' }, + [COPILOT_ALLOWED_HARNESSES_KEY]: { type: 'string' }, [COPILOT_SANDBOX_ENABLED_KEY]: { type: 'boolean' }, [COPILOT_SANDBOX_MCP_SERVERS_KEY]: { type: 'boolean' }, [COPILOT_SANDBOX_LSP_SERVERS_KEY]: { type: 'boolean' }, @@ -465,18 +517,42 @@ export function managedSettingsDisabledValue(policyData: IPolicyData): boolean | return policyData.managedSettingsActive === true ? false : undefined; } +const thirdPartyAgentEnabledValueCallbacks = new Map boolean | undefined>(); + /** - * `value` callback shared by the third-party agent harness policies (`Claude3PIntegration`, + * `value` callback for a third-party agent harness policy (`Claude3PIntegration`, * `Codex3PIntegration`): forces the harness off when the account disables chat preview features, - * when the user is governed by managed settings, or when Local harnesses are explicitly prohibited. + * when Local harnesses are explicitly prohibited, or when the user is governed by managed settings + * and the administrator has not permitted this harness. * * Managed settings are composed and enforced by the Copilot runtime and never reach the Claude or * Codex harnesses, so leaving them available would hand a governed user an ungoverned path around - * every managed control the enterprise set. + * every managed control the enterprise set. {@link COPILOT_ALLOWED_HARNESSES_KEY} is how an + * administrator accepts that for a harness: a present list replaces the presence block, permitting + * the harnesses it names and denying the others, while a value that is not a list permits none. + * Permitting a harness returns `undefined` rather than `true`, so the user's setting, rollout + * defaults, and every other denial still apply. + * + * Memoized per harness so repeated calls return the same reference, matching the identity contract + * {@link managedSettingValue} relies on for `isSamePolicyDefinition`. */ -export function thirdPartyAgentEnabledValue(policyData: IPolicyData): boolean | undefined { - return policyData.chat_preview_features_enabled === false || policyData.managedSettings?.[COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY] === false - ? false : managedSettingsDisabledValue(policyData); +export function thirdPartyAgentEnabledValue(harness: ManagedThirdPartyHarness): (policyData: IPolicyData) => boolean | undefined { + let callback = thirdPartyAgentEnabledValueCallbacks.get(harness); + if (!callback) { + callback = policyData => { + const managedSettings = policyData.managedSettings; + if (policyData.chat_preview_features_enabled === false || managedSettings?.[COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY] === false) { + return false; + } + const allowedHarnesses = managedSettings?.[COPILOT_ALLOWED_HARNESSES_KEY]; + if (allowedHarnesses === undefined) { + return managedSettingsDisabledValue(policyData); + } + return parseAllowedHarnesses(allowedHarnesses)?.harnesses.includes(harness) ? undefined : false; + }; + thirdPartyAgentEnabledValueCallbacks.set(harness, callback); + } + return callback; } export const INativeManagedSettingsService = createDecorator('nativeManagedSettingsService'); @@ -804,6 +880,12 @@ function encodeExtraMarketplaces(value: unknown, onWarn?: (msg: string) => void) const STRUCTURED_MANAGED_SETTINGS: readonly IStructuredManagedSetting[] = [ ...COPILOT_PERMISSION_RULES_KEYS.map(key => ({ key, encode: (value: unknown) => value })), + { + // Carried whatever its shape: an invalid value must still mask a weaker channel's list, + // which omitting it here would let through. `parseAllowedHarnesses` validates on read. + key: COPILOT_ALLOWED_HARNESSES_KEY, + encode: value => value, + }, { key: COPILOT_SANDBOX_ALLOWED_HOSTS_KEY, encode: encodeArray, diff --git a/src/vs/platform/policy/test/common/copilotManagedSettings.test.ts b/src/vs/platform/policy/test/common/copilotManagedSettings.test.ts index 6614d38a819b..05a8e16f17bc 100644 --- a/src/vs/platform/policy/test/common/copilotManagedSettings.test.ts +++ b/src/vs/platform/policy/test/common/copilotManagedSettings.test.ts @@ -8,7 +8,7 @@ import { IStringDictionary } from '../../../../base/common/collections.js'; import { IPolicyData } from '../../../../base/common/defaultAccount.js'; import { ManagedSettingsData, ManagedSettingValue } from '../../../../base/common/policy.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; -import { collectManagedSettingsDefinitions, COPILOT_COMMUNICATION_SUPPORT_URL_KEY, COPILOT_DEFAULT_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_ASSISTED_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_BYPASS_PERMISSIONS_MODE_KEY, managedDefaultConfigurationValue, COPILOT_FORCE_REMOTE_SETTINGS_REFRESH_KEY, COPILOT_MODEL_KEY, COPILOT_OTEL_CAPTURE_IDENTITY_KEY, COPILOT_PERMISSION_RULES_KEYS, COPILOT_SANDBOX_ALLOWED_HOSTS_KEY, COPILOT_SANDBOX_ALLOW_BYPASS_KEY, COPILOT_SANDBOX_ALLOW_DEV_TOOL_ACCESS_KEY, COPILOT_SANDBOX_ALLOW_LOCAL_NETWORK_KEY, COPILOT_SANDBOX_ALLOW_OUTBOUND_KEY, COPILOT_SANDBOX_AUTH_GH_KEY, COPILOT_SANDBOX_AUTH_GIT_KEY, COPILOT_SANDBOX_DENIED_PATHS_KEY, COPILOT_SANDBOX_ENABLED_KEY, COPILOT_SANDBOX_LSP_SERVERS_KEY, COPILOT_SANDBOX_MCP_SERVERS_KEY, COPILOT_SANDBOX_READONLY_PATHS_KEY, COPILOT_SANDBOX_READWRITE_PATHS_KEY, COPILOT_TEMPORARY_DEFAULT_TO_LOCAL_HARNESS_KEY, COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, COPILOT_TOP_LEVEL_MODEL_KEY, MANAGED_SETTINGS_CONTROL_DEFINITIONS, getManagedSupportUrl, hasManagedPermissionDenials, hasManagedSettingsDefinitions, hasRawManagedSettings, IManagedSettingsService, isManagedSettingGovernanceActive, NullManagedSettingsService, managedModelValue, managedSettingsDisabledValue, managedSettingValue, normalizeManagedSettings, projectManagedSettings, pickManagedSettings, requiresCopilotAgentHost, resolveForceRemoteSettingsRefresh } from '../../common/copilotManagedSettings.js'; +import { collectManagedSettingsDefinitions, COPILOT_ALLOWED_HARNESSES_KEY, COPILOT_COMMUNICATION_SUPPORT_URL_KEY, COPILOT_DEFAULT_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_ASSISTED_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_BYPASS_PERMISSIONS_MODE_KEY, managedDefaultConfigurationValue, COPILOT_FORCE_REMOTE_SETTINGS_REFRESH_KEY, COPILOT_MODEL_KEY, COPILOT_OTEL_CAPTURE_IDENTITY_KEY, COPILOT_PERMISSION_RULES_KEYS, COPILOT_SANDBOX_ALLOWED_HOSTS_KEY, COPILOT_SANDBOX_ALLOW_BYPASS_KEY, COPILOT_SANDBOX_ALLOW_DEV_TOOL_ACCESS_KEY, COPILOT_SANDBOX_ALLOW_LOCAL_NETWORK_KEY, COPILOT_SANDBOX_ALLOW_OUTBOUND_KEY, COPILOT_SANDBOX_AUTH_GH_KEY, COPILOT_SANDBOX_AUTH_GIT_KEY, COPILOT_SANDBOX_DENIED_PATHS_KEY, COPILOT_SANDBOX_ENABLED_KEY, COPILOT_SANDBOX_LSP_SERVERS_KEY, COPILOT_SANDBOX_MCP_SERVERS_KEY, COPILOT_SANDBOX_READONLY_PATHS_KEY, COPILOT_SANDBOX_READWRITE_PATHS_KEY, COPILOT_TEMPORARY_DEFAULT_TO_LOCAL_HARNESS_KEY, COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, COPILOT_TOP_LEVEL_MODEL_KEY, MANAGED_SETTINGS_CONTROL_DEFINITIONS, getManagedSupportUrl, hasManagedPermissionDenials, hasManagedSettingsDefinitions, hasRawManagedSettings, IManagedSettingsService, isManagedSettingGovernanceActive, NullManagedSettingsService, managedModelValue, managedSettingsDisabledValue, managedSettingValue, normalizeManagedSettings, projectManagedSettings, pickManagedSettings, requiresCopilotAgentHost, resolveForceRemoteSettingsRefresh, thirdPartyAgentEnabledValue } from '../../common/copilotManagedSettings.js'; import { PolicyDefinition } from '../../common/policy.js'; import { TestConfigurationService } from '../../../configuration/test/common/testConfigurationService.js'; @@ -156,6 +156,47 @@ suite('Copilot managed settings projection', () => { ], [{ [key]: false }, { [key]: false }, { [key]: true }]); }); + test('an allowed harnesses list permits the third-party harnesses it names and ignores other entries', () => { + const key = COPILOT_ALLOWED_HARNESSES_KEY; + const claude = thirdPartyAgentEnabledValue('claude'); + const codex = thirdPartyAgentEnabledValue('codex'); + const lists: readonly unknown[] = [undefined, ['claude', 'codex'], ['claude'], ['codex', 'codex'], ['future', 'claude', 7], [], ['Claude'], [['claude']], 'claude', null, { claude: true }]; + const results = lists.map(allowedHarnesses => { + const raw = { vscode: { allowedHarnesses } }; + const managedSettings = normalizeManagedSettings(raw); + return { + carried: managedSettings[key], + governance: hasRawManagedSettings(raw) || hasRawManagedSettings(managedSettings), + governed: [claude({ managedSettings, managedSettingsActive: true }), codex({ managedSettings, managedSettingsActive: true })], + ungoverned: [claude({ managedSettings }), codex({ managedSettings })], + }; + }); + const permitted = normalizeManagedSettings({ vscode: { allowedHarnesses: ['claude', 'codex'] } }); + assert.deepStrictEqual({ + results, + otherDenials: [ + claude({ managedSettings: permitted, chat_preview_features_enabled: false }), + codex({ managedSettings: { ...permitted, [COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY]: false } }), + ], + malformedJson: ['not json', '["claude"] trailing', '["claude",]', ''].map(value => claude({ managedSettings: { [key]: value } })), + sameCallback: thirdPartyAgentEnabledValue('claude') === claude, + }, { + results: [ + { carried: undefined, governance: false, governed: [false, false], ungoverned: [undefined, undefined] }, + { carried: '["claude","codex"]', governance: false, governed: [undefined, undefined], ungoverned: [undefined, undefined] }, + { carried: '["claude"]', governance: false, governed: [undefined, false], ungoverned: [undefined, false] }, + { carried: '["codex","codex"]', governance: false, governed: [false, undefined], ungoverned: [false, undefined] }, + { carried: '["future","claude",7]', governance: false, governed: [undefined, false], ungoverned: [undefined, false] }, + ...['[]', '["Claude"]', '[["claude"]]', '"claude"', 'null', '{"claude":true}'].map(carried => ( + { carried, governance: false, governed: [false, false], ungoverned: [false, false] } + )), + ], + otherDenials: [false, false], + malformedJson: [false, false, false, false], + sameCallback: true, + }); + }); + const definitions: IStringDictionary = { PolicyA: { type: 'boolean', diff --git a/src/vs/platform/protocol/electron-main/protocol.ts b/src/vs/platform/protocol/electron-main/protocol.ts index 593c37e44691..b5697a2358cd 100644 --- a/src/vs/platform/protocol/electron-main/protocol.ts +++ b/src/vs/platform/protocol/electron-main/protocol.ts @@ -50,4 +50,11 @@ export interface IProtocolMainService { * Registers the protocol used to load resources from a remote file system. */ registerManagedRemoteResourceProtocol(requestRemoteResource: (url: URI) => Promise): void; + + /** + * Reads a resource through the handler registered with {@link registerManagedRemoteResourceProtocol} + * without going through the protocol, which only serves requests from trusted frames. + * Callers must authorize the request themselves. + */ + requestManagedRemoteResource(url: URI): Promise; } diff --git a/src/vs/platform/protocol/electron-main/protocolMainService.ts b/src/vs/platform/protocol/electron-main/protocolMainService.ts index 15e27593953f..1061f6633225 100644 --- a/src/vs/platform/protocol/electron-main/protocolMainService.ts +++ b/src/vs/platform/protocol/electron-main/protocolMainService.ts @@ -27,6 +27,7 @@ export class ProtocolMainService extends Disposable implements IProtocolMainServ declare readonly _serviceBrand: undefined; private readonly validRoots = TernarySearchTree.forPaths(!isLinux); + private managedRemoteResourceHandler: ((request: GlobalRequest) => Promise) | undefined; private readonly validExtensions = new Set(['.svg', '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.mp4', '.otf', '.ttf']); // https://github.com/microsoft/vscode/issues/119384 constructor( @@ -81,11 +82,20 @@ export class ProtocolMainService extends Disposable implements IProtocolMainServ } registerManagedRemoteResourceProtocol(requestRemoteResource: (url: URI) => Promise): void { - session.defaultSession.protocol.handle( - Schemas.vscodeManagedRemoteResource, - createManagedRemoteResourceRequestHandler(requestRemoteResource, this.logService) - ); - this._register(toDisposable(() => session.defaultSession.protocol.unhandle(Schemas.vscodeManagedRemoteResource))); + const handler = createManagedRemoteResourceRequestHandler(requestRemoteResource, this.logService); + this.managedRemoteResourceHandler = handler; + session.defaultSession.protocol.handle(Schemas.vscodeManagedRemoteResource, handler); + this._register(toDisposable(() => { + this.managedRemoteResourceHandler = undefined; + session.defaultSession.protocol.unhandle(Schemas.vscodeManagedRemoteResource); + })); + } + + async requestManagedRemoteResource(url: URI): Promise { + if (!this.managedRemoteResourceHandler) { + return new Response('Remote resources are not available', { status: 503 }); + } + return this.managedRemoteResourceHandler(new Request(url.toString())); } //#region file:// diff --git a/src/vs/platform/quickinput/browser/media/quickInput.css b/src/vs/platform/quickinput/browser/media/quickInput.css index 4dcc37b522e3..414699a9fb4d 100644 --- a/src/vs/platform/quickinput/browser/media/quickInput.css +++ b/src/vs/platform/quickinput/browser/media/quickInput.css @@ -9,7 +9,7 @@ z-index: 2550; left: 50%; -webkit-app-region: no-drag; - border-radius: var(--vscode-cornerRadius-xLarge); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-xLarge)); box-shadow: var(--vscode-shadow-xl); } @@ -96,7 +96,7 @@ .quick-input-widget .monaco-action-bar .monaco-custom-toggle { margin-left: 0; - border-radius: 5px; + border-radius: var(--workbench-custom-controls-corner-radius, 5px); box-sizing: content-box; } @@ -163,7 +163,7 @@ } .quick-input-widget .quick-input-filter .monaco-inputbox { - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-medium)); } .quick-input-widget.hidden-input .quick-input-header { diff --git a/src/vs/platform/quickinput/browser/quickInputList.ts b/src/vs/platform/quickinput/browser/quickInputList.ts index 423e62011bac..d1c22ea08495 100644 --- a/src/vs/platform/quickinput/browser/quickInputList.ts +++ b/src/vs/platform/quickinput/browser/quickInputList.ts @@ -25,6 +25,7 @@ import { memoize } from '../../../base/common/decorators.js'; import { isCancellationError } from '../../../base/common/errors.js'; import { Emitter, Event, EventBufferer, IValueWithChangeEvent } from '../../../base/common/event.js'; import { IMatch } from '../../../base/common/filters.js'; +import { KeyCode } from '../../../base/common/keyCodes.js'; import { IMarkdownString } from '../../../base/common/htmlContent.js'; import { IParsedLabelWithIcons, getCodiconAriaLabel, matchesFuzzyIconAware, parseLabelWithIcons } from '../../../base/common/iconLabels.js'; import { Lazy } from '../../../base/common/lazy.js'; @@ -1181,7 +1182,7 @@ export class QuickInputList extends Disposable { // https://github.com/microsoft/vscode/issues/211976 if (this.accessibilityService.isScreenReaderOptimized()) { disposableTimeout(() => { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const focusedElement = this._tree.getHTMLElement().querySelector(`.monaco-list-row.focused`); const parent = focusedElement?.parentNode; if (focusedElement && parent) { @@ -1411,15 +1412,35 @@ export class QuickInputList extends Disposable { this.hoverDelegate.onDidHideHover?.(); this._lastHover.dispose(); if (hoverHadFocus) { - if (this._hoverFocusReturn?.isConnected) { - this._hoverFocusReturn.focus(); - } else { - this._tree.domFocus(); - } + this.returnFocusFromHover(); } } } + private returnFocusFromHover(): void { + if (this._hoverFocusReturn?.isConnected) { + this._hoverFocusReturn.focus(); + } else { + this._tree.domFocus(); + } + } + + private getOrCreateHoverHost(): HTMLElement { + if (!this._hoverHost) { + const hoverHost = this._hoverHost = dom.append(this._container, $('.quick-input-list-hover-host')); + // The hover disposes itself on Escape, which would move focus to the body and hide the + // picker without restoring focus. Move focus back into the picker first and let the + // event continue so Escape still closes the hover and the picker. Match the hover's + // own unmodified Escape check so other combinations leave focus in the hover. + this._register(dom.addDisposableListener(hoverHost, dom.EventType.KEY_DOWN, e => { + if (new StandardKeyboardEvent(e).equals(KeyCode.Escape) && dom.isAncestorOfActiveElement(hoverHost)) { + this.returnFocusFromHover(); + } + }, true)); + } + return this._hoverHost; + } + filter(query: string): boolean { this._lastQueryString = query; if (!(this._sortByLabel || this._matchOnLabel || this._matchOnDescription || this._matchOnDetail)) { @@ -1632,7 +1653,7 @@ export class QuickInputList extends Disposable { }, // Render inside the list so that focusing the hover does not hide the picker, but in // a viewport-sized host so that the quick input widget neither clips nor sizes it - container: this._hoverHost ??= dom.append(this._container, $('.quick-input-list-hover-host')), + container: this.getOrCreateHoverHost(), position: { hoverPosition: HoverPosition.RIGHT } diff --git a/src/vs/platform/quickinput/browser/tree/quickInputTreeController.ts b/src/vs/platform/quickinput/browser/tree/quickInputTreeController.ts index 893665466a97..e1b6315c6e83 100644 --- a/src/vs/platform/quickinput/browser/tree/quickInputTreeController.ts +++ b/src/vs/platform/quickinput/browser/tree/quickInputTreeController.ts @@ -300,9 +300,10 @@ export class QuickInputTreeController extends Disposable { })); this._register(this._checkboxStateHandler.onDidChangeCheckboxState(e => { - this.updateCheckboxState(e.item, e.checked === true, true); + // Checkbox listeners can replace the tree items, so establish focus before notifying them. this._tree.setFocus([e.item]); this._tree.setSelection([e.item]); + this.updateCheckboxState(e.item, e.checked === true, true); })); } diff --git a/src/vs/platform/quickinput/test/browser/quickinput.test.ts b/src/vs/platform/quickinput/test/browser/quickinput.test.ts index 87a2349917f3..ac7e98676ca4 100644 --- a/src/vs/platform/quickinput/test/browser/quickinput.test.ts +++ b/src/vs/platform/quickinput/test/browser/quickinput.test.ts @@ -5,14 +5,15 @@ import assert from 'assert'; import sinon from 'sinon'; -import { $, append, registerWindow } from '../../../../base/browser/dom.js'; +import { $, addDisposableListener, append, EventType, registerWindow } from '../../../../base/browser/dom.js'; import { ObjectTree } from '../../../../base/browser/ui/tree/objectTree.js'; import { unthemedInboxStyles } from '../../../../base/browser/ui/inputbox/inputBox.js'; import { unthemedButtonStyles } from '../../../../base/browser/ui/button/button.js'; import { unthemedListStyles } from '../../../../base/browser/ui/list/listWidget.js'; import { unthemedToggleStyles } from '../../../../base/browser/ui/toggle/toggle.js'; import { Event } from '../../../../base/common/event.js'; -import { DeferredPromise, raceTimeout } from '../../../../base/common/async.js'; +import { DeferredPromise, raceTimeout, timeout } from '../../../../base/common/async.js'; +import { IMarkdownString, MarkdownString } from '../../../../base/common/htmlContent.js'; import { unthemedCountStyles } from '../../../../base/browser/ui/countBadge/countBadge.js'; import { unthemedKeybindingLabelOptions } from '../../../../base/browser/ui/keybindingLabel/keybindingLabel.js'; import { unthemedProgressBarOptions } from '../../../../base/browser/ui/progressbar/progressbar.js'; @@ -201,6 +202,32 @@ suite('QuickInput', () => { // https://github.com/microsoft/vscode/issues/147543 assert.deepStrictEqual(states, controls.map(() => ({ supportsWidget: false, contentAttached: false }))); }); + test('quick tree checkbox clicks retain focus and selection when listeners replace items', () => { + controller.layout({ height: 500, width: 600 }, 0); + const picker = store.add(controller.createQuickTree()); + picker.sortByLabel = false; + picker.setItemTree([ + { id: 'first', label: 'First', checked: false }, + { id: 'second', label: 'Second', checked: false }, + ]); + store.add(picker.onDidChangeCheckboxState(() => { + picker.setItemTree(picker.itemTree.map(item => ({ ...item }))); + })); + picker.show(); + const list = fixture.querySelector('.quick-input-tree > .monaco-list')!; + const tree = getRegisteredLists().find(widget => widget.getHTMLElement() === list); + if (!(tree instanceof ObjectTree)) { + throw new Error('Expected the Quick Input tree'); + } + fixture.querySelectorAll('.quick-input-tree-entry .monaco-checkbox')[1].click(); + const replacement = picker.itemTree[1]; + assert.deepStrictEqual({ + checked: picker.checkedLeafItems.map(item => item.id), + focused: tree.getFocus()[0] === replacement, + selected: tree.getSelection()[0] === replacement, + }, { checked: ['second'], focused: true, selected: true }); + }); + test('quick widgets retain their content when shown again without disturbing focus on updates', () => { const picker = store.add(controller.createQuickWidget()); const content = mainWindow.document.createElement('input'); @@ -971,6 +998,10 @@ suite('QuickInput item hover layout', () => { let hoverService: HoverService; let fixture: HTMLElement; let showHoverResult: 'hover' | 'undefined'; + // Whether the picker stays open when focus leaves it + let ignoreFocusOut: boolean; + // Where focus returns to when the picker hides without a previously focused element to restore + let returnFocusTarget: HTMLElement | undefined; // Quick inputs are disposed (and hidden) before the controller that shows them let inputs: DisposableStore; @@ -1001,20 +1032,43 @@ suite('QuickInput item hover layout', () => { mightProducePrintableCharacter() { return false; }, softDispatch() { return NoMatchingKb; }, lookupKeybinding() { return undefined; }, + resolveKeyboardEvent() { + return { + getLabel() { return ''; }, + getAriaLabel() { return ''; }, + getElectronAccelerator() { return null; }, + getUserSettingsLabel() { return null; }, + isWYSIWYG() { return false; }, + hasMultipleChords() { return false; }, + getDispatchChords() { return [null]; }, + getSingleModifierDispatchChords() { return []; }, + getChords() { return []; } + }; + }, }); + // Link-producing stub of the markdown renderer, so that markdown tooltips contain a focusable link instantiationService.stub(IMarkdownRendererService, { - render() { return { element: document.createElement('div'), dispose() { } }; }, + render(markdown: IMarkdownString) { + const element = document.createElement('div'); + const link = document.createElement('a'); + link.href = '#'; + link.textContent = markdown.value; + element.appendChild(link); + return { element, dispose() { } }; + }, setDefaultCodeBlockRenderer() { } }); hoverService = store.add(instantiationService.createInstance(HoverService)); inputs = store.add(new DisposableStore()); showHoverResult = 'hover'; + ignoreFocusOut = true; + returnFocusTarget = undefined; controller = store.add(instantiationService.createInstance(QuickInputController, { container: fixture, idPrefix: 'testQuickInputHover', - ignoreFocusOut() { return true; }, - returnFocus() { }, + ignoreFocusOut() { return ignoreFocusOut; }, + returnFocus() { returnFocusTarget?.focus(); }, backKeybindingLabel() { return undefined; }, setContextKey() { return undefined; }, linkOpenerDelegate() { }, @@ -1039,9 +1093,9 @@ suite('QuickInput item hover layout', () => { return element; } - async function showPicker(labels: string[]): Promise> { + async function showPicker(labels: string[], tooltip: (label: string) => string | IMarkdownString = label => `Tooltip of ${label}`): Promise> { const picker = inputs.add(controller.createQuickPick()); - picker.items = labels.map(label => ({ label, tooltip: `Tooltip of ${label}` })); + picker.items = labels.map(label => ({ label, tooltip: tooltip(label) })); picker.show(); const container = widget(); // Stands in for `.modern-ui .quick-input-widget { overflow: hidden }` (roundedCorners.css), @@ -1243,6 +1297,127 @@ suite('QuickInput item hover layout', () => { }, { focusedBeforeHoverInPicker: true, hoverFocused: true, hoverShown: false, focusReturned: true }); }); + function pressEscape(target: HTMLElement, shiftKey = false): void { + target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, shiftKey, bubbles: true, cancelable: true })); + } + + /** + * Focuses an element outside of the picker, as an editor would be, and shows the picker + * from there with the hover of its first item. Escape hides the picker the way the + * `quickInput.hide` keybinding does: in the same dispatch, after the hover handled it. + */ + async function showPickerFromOutside(): Promise<{ outside: HTMLElement; hidden: () => boolean }> { + ignoreFocusOut = false; + const outside = append(fixture, $('input')); + outside.focus(); + // The test window may not have focus, in which case focus events carry no related target + // for the picker to remember, so it returns focus the way the workbench would + returnFocusTarget = outside; + const picker = await showPicker(['first'], label => new MarkdownString(`[Link of ${label}](https://example.com)`)); + await settle(); + let hidden = false; + inputs.add(picker.onDidHide(() => hidden = true)); + // Stands in for the keybinding dispatcher, which the stubbed keybinding service does not provide + inputs.add(addDisposableListener(mainWindow, EventType.KEY_DOWN, e => { + if (e.key === 'Escape') { + controller.currentQuickInput?.hide(); + } + })); + controller.toggleHover(); + return { outside, hidden: () => hidden }; + } + + async function pressEscapeOn(target: HTMLElement, outside: HTMLElement, hidden: () => boolean) { + target.focus(); + const targetFocused = mainWindow.document.activeElement === target; + pressEscape(target); + // The focus tracker of the picker reports blur asynchronously + await timeout(50); + return { + targetFocused, + hoverShown: !!fixture.querySelector('.workbench-hover'), + pickerHidden: hidden(), + focusRestored: mainWindow.document.activeElement === outside, + }; + } + + const escapeDismissedPicker = { targetFocused: true, hoverShown: false, pickerHidden: true, focusRestored: true }; + + test('closes the picker and restores focus when Escape is pressed on a link in the item hover', async () => { + const { outside, hidden } = await showPickerFromOutside(); + const link = fixture.querySelector('.workbench-hover a'); + assert.ok(link); + assert.deepStrictEqual(await pressEscapeOn(link, outside, hidden), escapeDismissedPicker); + }); + + test('closes the picker and restores focus when Escape is pressed on the item hover itself', async () => { + const { outside, hidden } = await showPickerFromOutside(); + const hover = fixture.querySelector('.monaco-hover'); + assert.ok(hover); + assert.deepStrictEqual(await pressEscapeOn(hover, outside, hidden), escapeDismissedPicker); + }); + + test('closes the picker and restores focus when Escape is pressed in the picker input while the item hover is shown', async () => { + const { outside, hidden } = await showPickerFromOutside(); + const input = widget().querySelector('.quick-input-box input'); + assert.ok(input); + // The hover is not dismissed by Escape here, but hidden along with the picker that contains it + const { targetFocused, pickerHidden, focusRestored } = await pressEscapeOn(input, outside, hidden); + assert.deepStrictEqual({ targetFocused, pickerHidden, focusRestored }, { targetFocused: true, pickerHidden: true, focusRestored: true }); + }); + + test('keeps focus on a link in the item hover when Shift+Escape is pressed', async () => { + ignoreFocusOut = false; + await showPicker(['first'], label => new MarkdownString(`[Link of ${label}](https://example.com)`)); + await settle(); + controller.toggleHover(); + const link = fixture.querySelector('.workbench-hover a'); + assert.ok(link); + link.focus(); + + pressEscape(link, true); + await timeout(50); + + assert.deepStrictEqual({ + hoverShown: !!fixture.querySelector('.workbench-hover'), + linkFocused: mainWindow.document.activeElement === link, + }, { hoverShown: true, linkFocused: true }); + }); + + test('focuses the list when Escape is pressed in the item hover after the previously focused element was removed', async () => { + ignoreFocusOut = false; + const picker = await showPicker(['first'], label => new MarkdownString(`[Link of ${label}](https://example.com)`)); + await settle(); + let hidden = false; + inputs.add(picker.onDidHide(() => hidden = true)); + // Focused when the hover is shown, so focus would return to it + const transient = append(widget(), $('button')); + transient.focus(); + controller.toggleHover(); + const link = fixture.querySelector('.workbench-hover a'); + assert.ok(link); + link.focus(); + transient.remove(); + const beforeEscape = { linkFocused: mainWindow.document.activeElement === link, transientConnected: transient.isConnected }; + + pressEscape(link); + await timeout(50); + + const list = fixture.querySelector('.quick-input-list'); + assert.ok(list); + assert.deepStrictEqual({ + beforeEscape, + hoverShown: !!fixture.querySelector('.workbench-hover'), + focusInList: list.contains(mainWindow.document.activeElement), + pickerHidden: hidden, + }, { + beforeEscape: { linkFocused: true, transientConnected: false }, + hoverShown: false, + focusInList: true, + pickerHidden: false, + }); + }); + test('keeps the widget settled when a visible picker is replaced and animates a new show', async () => { await showPicker(['first']); await settle(); diff --git a/src/vs/platform/remote/electron-browser/electronRemoteResourceLoader.ts b/src/vs/platform/remote/electron-browser/electronRemoteResourceLoader.ts index 1155015ed176..2918c9617213 100644 --- a/src/vs/platform/remote/electron-browser/electronRemoteResourceLoader.ts +++ b/src/vs/platform/remote/electron-browser/electronRemoteResourceLoader.ts @@ -10,6 +10,7 @@ import { Disposable } from '../../../base/common/lifecycle.js'; import { getMediaOrTextMime } from '../../../base/common/mime.js'; import { Schemas } from '../../../base/common/network.js'; import { URI } from '../../../base/common/uri.js'; +import { AGENT_HOST_SCHEME, toAgentHostUri } from '../../agentHost/common/agentHostUri.js'; import { IServerChannel } from '../../../base/parts/ipc/common/ipc.js'; import { FileOperationError, FileOperationResult, IFileContent, IFileService } from '../../files/common/files.js'; import { IBrowserResourceService } from '../../files/common/browserResourceService.js'; @@ -66,11 +67,13 @@ export class ElectronRemoteResourceLoader extends Disposable { let content: IFileContent; try { - const actual = uri.with({ - scheme: Schemas.vscodeRemote, - authority, - query: '', - }); + const actual = params.get('scheme') === AGENT_HOST_SCHEME + ? toAgentHostUri(URI.from({ scheme: Schemas.file, path: uri.path }), authority) + : uri.with({ + scheme: Schemas.vscodeRemote, + authority, + query: '', + }); content = await this.fileService.readFile(actual); } catch (e) { const str = encodeBase64(VSBuffer.fromString(e.message)); diff --git a/src/vs/platform/remote/electron-browser/remoteAuthorityResolverService.ts b/src/vs/platform/remote/electron-browser/remoteAuthorityResolverService.ts index 99157f24fa6e..1d8471541ffb 100644 --- a/src/vs/platform/remote/electron-browser/remoteAuthorityResolverService.ts +++ b/src/vs/platform/remote/electron-browser/remoteAuthorityResolverService.ts @@ -63,7 +63,7 @@ export class RemoteAuthorityResolverService extends Disposable implements IRemot if (!request.isResolved) { return null; } - const connectionToken = this._connectionTokens.get(authority); + const connectionToken = this._connectionTokens.get(authority) ?? request.value!.authority.connectionToken; return { connectTo: request.value!.authority.connectTo, connectionToken: connectionToken diff --git a/src/vs/platform/remote/test/electron-browser/electronRemoteResourceLoader.test.ts b/src/vs/platform/remote/test/electron-browser/electronRemoteResourceLoader.test.ts index cf4094dbbacb..4386223d9b20 100644 --- a/src/vs/platform/remote/test/electron-browser/electronRemoteResourceLoader.test.ts +++ b/src/vs/platform/remote/test/electron-browser/electronRemoteResourceLoader.test.ts @@ -15,7 +15,7 @@ import { IMainProcessService } from '../../../ipc/common/mainProcessService.js'; import { NODE_REMOTE_RESOURCE_CHANNEL_NAME, NODE_REMOTE_RESOURCE_IPC_METHOD_NAME, NodeRemoteResourceResponse } from '../../common/electronRemoteResources.js'; import { createBrowserResourceUriProvider, ElectronRemoteResourceLoader } from '../../electron-browser/electronRemoteResourceLoader.js'; import { BrowserResourceService } from '../../../files/browser/browserResourceService.js'; -import { AGENT_HOST_SCHEME, toAgentHostUri } from '../../../agentHost/common/agentHostUri.js'; +import { AGENT_HOST_SCHEME, fromAgentHostUri, toAgentHostUri } from '../../../agentHost/common/agentHostUri.js'; suite('ElectronRemoteResourceLoader', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -91,6 +91,37 @@ suite('ElectronRemoteResourceLoader', () => { }); }); + test('reads agent host files through the agent host file system', async () => { + const { channel, reads } = createLoader(); + const response = await request(channel, URI.from({ + scheme: Schemas.vscodeManagedRemoteResource, + authority: 'window:7', + path: '/a/index.html', + query: new URLSearchParams({ authority: 'host-a', scheme: AGENT_HOST_SCHEME }).toString(), + })); + + assert.deepStrictEqual({ + status: response.statusCode, + reads: reads.map(resource => resource.toString()), + }, { + status: 200, + reads: [toAgentHostUri(URI.file('/a/index.html'), 'host-a').toString()], + }); + }); + + test('reads agent host paths without applying the client OS path rules', async () => { + const { channel, reads } = createLoader(); + + await request(channel, URI.from({ + scheme: Schemas.vscodeManagedRemoteResource, + authority: 'window:7', + path: '/trusted/a\\b.html', + query: new URLSearchParams({ authority: 'host-a', scheme: AGENT_HOST_SCHEME }).toString(), + })); + + assert.deepStrictEqual(reads.map(resource => fromAgentHostUri(resource).path), ['/trusted/a\\b.html']); + }); + test('ignores downstream scheme substitution', async () => { const { loader, channel, reads } = createLoader(); const managedResource = loader.getResourceUriProvider()(URI.from({ diff --git a/src/vs/platform/remote/test/electron-browser/remoteAuthorityResolverService.test.ts b/src/vs/platform/remote/test/electron-browser/remoteAuthorityResolverService.test.ts index 6ad44083e4a3..3796d218ae3a 100644 --- a/src/vs/platform/remote/test/electron-browser/remoteAuthorityResolverService.test.ts +++ b/src/vs/platform/remote/test/electron-browser/remoteAuthorityResolverService.test.ts @@ -7,7 +7,7 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import product from '../../../product/common/product.js'; import { IProductService } from '../../../product/common/productService.js'; -import { RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode } from '../../common/remoteAuthorityResolver.js'; +import { RemoteAuthorityResolverError, RemoteAuthorityResolverErrorCode, WebSocketRemoteConnection } from '../../common/remoteAuthorityResolver.js'; import { RemoteAuthorityResolverService } from '../../electron-browser/remoteAuthorityResolverService.js'; suite('RemoteAuthorityResolverService', () => { @@ -28,4 +28,17 @@ suite('RemoteAuthorityResolverService', () => { } service.dispose(); }); + + test('getConnectionData falls back to the resolved authority token', async () => { + const productService: IProductService = { _serviceBrand: undefined, ...product }; + // eslint-disable-next-line local/code-no-any-casts + const service = new RemoteAuthorityResolverService(productService, undefined as any); + const result = service.resolveAuthority('test+x'); + service._setResolvedAuthority({ authority: 'test+x', connectTo: new WebSocketRemoteConnection('localhost', 1234), connectionToken: 'abc' }); + await result; + assert.strictEqual(service.getConnectionData('test+x')?.connectionToken, 'abc'); + service._setAuthorityConnectionToken('test+x', 'env'); + assert.strictEqual(service.getConnectionData('test+x')?.connectionToken, 'env'); + service.dispose(); + }); }); diff --git a/src/vs/platform/sandbox/common/terminalSandboxEngine.ts b/src/vs/platform/sandbox/common/terminalSandboxEngine.ts index 79b863a6d28b..2d6083278eb6 100644 --- a/src/vs/platform/sandbox/common/terminalSandboxEngine.ts +++ b/src/vs/platform/sandbox/common/terminalSandboxEngine.ts @@ -53,6 +53,8 @@ export interface ITerminalSandboxRuntimeInfo { nativeModulesDir?: string; /** Path of the node/electron executable used to run sandbox-runtime. */ execPath?: string; + /** Explicit runtime read paths, replacing automatic grants for the executable and its parent directory. */ + readPaths?: readonly string[]; /** * When true the engine prefixes the wrapped command with `ELECTRON_RUN_AS_NODE=1` * so the Electron binary acts as a Node.js executable. Set by hosts that resolve @@ -124,6 +126,7 @@ export class TerminalSandboxEngine extends Disposable { private _runtimeResolved = false; private _appRoot: string | undefined; private _execPath: string | undefined; + private _runtimeReadPaths: readonly string[] | undefined; private _runAsNode = false; private _userHome: URI | undefined; private _srtPath: string | undefined; @@ -611,6 +614,7 @@ export class TerminalSandboxEngine extends Disposable { const runtimeInfo = await this._host.getRuntimeInfo(); this._appRoot = runtimeInfo.appRoot; this._execPath = runtimeInfo.execPath; + this._runtimeReadPaths = runtimeInfo.readPaths; this._runAsNode = runtimeInfo.runAsNode ?? false; this._userHome = await this._host.getUserHome(); this._srtPath = this._pathJoin(this._appRoot, 'node_modules', '@vscode', 'sandbox-runtime', 'dist', 'cli.js'); @@ -963,6 +967,9 @@ export class TerminalSandboxEngine extends Disposable { } private _getSandboxRuntimeReadPaths(): string[] { + if (this._runtimeReadPaths !== undefined) { + return [...this._runtimeReadPaths]; + } if (!this._appRoot) { return []; } diff --git a/src/vs/platform/sandbox/test/common/terminalSandboxEngine.test.ts b/src/vs/platform/sandbox/test/common/terminalSandboxEngine.test.ts index ebf45c9213b6..a8613cdef97d 100644 --- a/src/vs/platform/sandbox/test/common/terminalSandboxEngine.test.ts +++ b/src/vs/platform/sandbox/test/common/terminalSandboxEngine.test.ts @@ -219,6 +219,28 @@ suite('TerminalSandboxEngine', () => { }); }); + test('explicit runtime read paths do not grant the executable parent or portable storage', async () => { + const appRoot = '/home/user/portable-code/resources/app'; + const executable = '/home/user/portable-code/code'; + const runtimeData = '/home/user/portable-code/icudtl.dat'; + const engine = store.add(instantiationService.createInstance(TerminalSandboxEngine, createHost({ + getRuntimeInfo: async () => ({ appRoot, execPath: executable, readPaths: [appRoot, executable, runtimeData] }), + }))); + const configPath = await engine.getSandboxConfigPath(); + ok(configPath); + const config = JSON.parse(createdFiles.get(configPath)!); + + deepStrictEqual({ + applicationReadPaths: config.filesystem.allowRead.filter((path: string) => path.startsWith('/home/user/portable-code')), + portableStorage: await engine.checkFileAccess('read', ['/home/user/portable-code/data/user-data/state.vscdb']), + applicationResources: await engine.checkFileAccess('read', [`${appRoot}/out/main.js`]), + }, { + applicationReadPaths: [appRoot, executable, runtimeData], + portableStorage: { allowed: false, denied: ['/home/user/portable-code/data/user-data/state.vscdb'] }, + applicationResources: { allowed: true, denied: [] }, + }); + }); + test('sandbox config respects explicitly disabled PTY access on macOS', async () => { setSandboxSetting(AgentSandboxSettingId.AgentSandboxAdvancedRuntime, { allowPty: false }); const host = createHost({ getOS: () => Promise.resolve(OperatingSystem.Macintosh) }); diff --git a/src/vs/platform/sign/browser/signService.ts b/src/vs/platform/sign/browser/signService.ts index c288b2e12faf..1352f9069047 100644 --- a/src/vs/platform/sign/browser/signService.ts +++ b/src/vs/platform/sign/browser/signService.ts @@ -14,7 +14,7 @@ import { ISignService } from '../common/sign.js'; declare namespace vsdaWeb { export function sign(salted_message: string): string; - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line local/code-class-name-pascal-case export class validator { free(): void; constructor(); diff --git a/src/vs/platform/sign/node/signService.ts b/src/vs/platform/sign/node/signService.ts index 2851c35d271f..8a1d8aa4ab4a 100644 --- a/src/vs/platform/sign/node/signService.ts +++ b/src/vs/platform/sign/node/signService.ts @@ -8,12 +8,12 @@ import { ISignService } from '../common/sign.js'; declare namespace vsda { // the signer is a native module that for historical reasons uses a lower case class name - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line local/code-class-name-pascal-case export class signer { sign(arg: string): string; } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line local/code-class-name-pascal-case export class validator { createNewMessage(arg: string): string; validate(arg: string): 'ok' | 'error'; diff --git a/src/vs/platform/terminal/common/terminal.ts b/src/vs/platform/terminal/common/terminal.ts index 2a2d34ed0b75..7bc2a77b4ae1 100644 --- a/src/vs/platform/terminal/common/terminal.ts +++ b/src/vs/platform/terminal/common/terminal.ts @@ -821,6 +821,11 @@ export interface ITerminalChildProcess { */ shouldPersist: boolean; + /** + * Whether this attachment resolves to a revived process that still needs to start. + */ + readonly isRevived?: boolean; + readonly onProcessData: Event; readonly onProcessReady: Event; readonly onProcessReplayComplete?: Event; @@ -836,6 +841,11 @@ export interface ITerminalChildProcess { */ start(): Promise; + /** + * Releases an allocated process without waiting for it to start. + */ + cancelBeforeStart?(): Promise; + /** * Detach the process from the UI and await reconnect. * @param forcePersist Whether to force the process to persist if it supports persistence. diff --git a/src/vs/platform/theme/common/sizeRegistry.ts b/src/vs/platform/theme/common/sizeRegistry.ts index 522cd4f5b367..9bee2b849b2c 100644 --- a/src/vs/platform/theme/common/sizeRegistry.ts +++ b/src/vs/platform/theme/common/sizeRegistry.ts @@ -7,3 +7,4 @@ export * from './sizeUtils.js'; // Make sure all size files are exported export * from './sizes/baseSizes.js'; +export * from './sizes/semanticSizes.js'; diff --git a/src/vs/platform/theme/common/sizeService.ts b/src/vs/platform/theme/common/sizeService.ts new file mode 100644 index 000000000000..54aedae6d26e --- /dev/null +++ b/src/vs/platform/theme/common/sizeService.ts @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Event } from '../../../base/common/event.js'; +import { createDecorator } from '../../instantiation/common/instantiation.js'; +import { SizeIdentifier, SizeValue } from './sizeUtils.js'; +import { IColorTheme } from './themeService.js'; + +export const ISizeService = createDecorator('sizeService'); +export const SIZE_CUSTOMIZATIONS_SETTING = 'workbench.sizeCustomizations'; + +/** Resolves validated semantic sizes for both CSS and programmatic consumers. */ +export interface ISizeService { + readonly _serviceBrand: undefined; + readonly onDidChangeSizes: Event; + getSize(id: SizeIdentifier, theme: IColorTheme): SizeValue | undefined; + /** Whether this token or one of its inherited defaults has a valid user override. */ + isCustomized(id: SizeIdentifier): boolean; +} diff --git a/src/vs/platform/theme/common/sizeUtils.ts b/src/vs/platform/theme/common/sizeUtils.ts index 0ac56dbca000..f41f10d29d71 100644 --- a/src/vs/platform/theme/common/sizeUtils.ts +++ b/src/vs/platform/theme/common/sizeUtils.ts @@ -32,10 +32,19 @@ export interface SizeValue { export interface SizeContribution { readonly id: SizeIdentifier; readonly description: string; - readonly defaults: SizeDefaults | SizeValue | null; + readonly defaults: SizeDefaults | SizeValue | SizeIdentifier | null; readonly deprecationMessage: string | undefined; + readonly customization: SizeCustomization | undefined; } +/** Numeric pixel customizations supported by a semantic size token. */ +export interface SizeCustomization { + readonly minimum: number; + readonly maximum: number; +} + +export type SizeCustomizations = Readonly>; + /** * Returns the css variable name for the given size identifier. Dots (`.`) are replaced with hyphens (`-`) and * everything is prefixed with `--vscode-`. @@ -110,7 +119,7 @@ export interface ISizeRegistry { * @param defaults The default values * @param description the description */ - registerSize(id: string, defaults: SizeDefaults | SizeValue | null, description: string): SizeIdentifier; + registerSize(id: string, defaults: SizeDefaults | SizeValue | SizeIdentifier | null, description: string, deprecationMessage?: string, customization?: SizeCustomization): SizeIdentifier; /** * Deregister a size from the registry. @@ -127,6 +136,10 @@ export interface ISizeRegistry { */ resolveDefaultSize(id: SizeIdentifier, theme: IColorTheme): SizeValue | undefined; + resolveSize(id: SizeIdentifier, theme: IColorTheme, customizations: SizeCustomizations): SizeValue | undefined; + + getSizeCustomizationSchema(): IJSONSchema; + /** * JSON schema for an object to assign size values to one of the size contributions. */ @@ -153,6 +166,7 @@ class SizeRegistry extends Disposable implements ISizeRegistry { private sizesById: { [key: string]: SizeContribution }; private sizeSchema: IJSONSchemaForSizes = { type: 'object', properties: {} }; + private sizeCustomizationSchema: IJSONSchemaForSizes = { type: 'object', properties: {}, additionalProperties: false }; private sizeReferenceSchema: IJSONSchema & { enum: string[]; enumDescriptions: string[] } = { type: 'string', enum: [], enumDescriptions: [] }; constructor() { @@ -170,14 +184,14 @@ class SizeRegistry extends Disposable implements ISizeRegistry { this._onDidChangeSchema.fire(); } - public registerSize(id: string, defaults: SizeDefaults | SizeValue | null, description: string, deprecationMessage?: string): SizeIdentifier { - const sizeContribution: SizeContribution = { id, description, defaults, deprecationMessage }; + public registerSize(id: string, defaults: SizeDefaults | SizeValue | SizeIdentifier | null, description: string, deprecationMessage?: string, customization?: SizeCustomization): SizeIdentifier { + const sizeContribution: SizeContribution = { id, description, defaults, deprecationMessage, customization }; this.sizesById[id] = sizeContribution; // Determine whether this token uses unitless values (e.g. font weights). // The pattern is chosen per-token so that length tokens still require a unit. const isUnitless = (() => { - if (!defaults) { return false; } + if (!defaults || typeof defaults === 'string') { return false; } if (isSizeDefaults(defaults)) { const sample = defaults.dark ?? defaults.light ?? defaults.hcDark ?? defaults.hcLight; return sample?.unit === ''; @@ -205,6 +219,17 @@ class SizeRegistry extends Disposable implements ISizeRegistry { description, ...propertySchema }; + if (customization) { + this.sizeCustomizationSchema.properties[id] = { + description, + type: 'integer', + minimum: customization.minimum, + maximum: customization.maximum, + deprecationMessage, + }; + } else { + delete this.sizeCustomizationSchema.properties[id]; + } this.sizeReferenceSchema.enum.push(id); this.sizeReferenceSchema.enumDescriptions.push(description); @@ -216,6 +241,7 @@ class SizeRegistry extends Disposable implements ISizeRegistry { public deregisterSize(id: string): void { delete this.sizesById[id]; delete this.sizeSchema.properties[id]; + delete this.sizeCustomizationSchema.properties[id]; const index = this.sizeReferenceSchema.enum.indexOf(id); if (index !== -1) { this.sizeReferenceSchema.enum.splice(index, 1); @@ -229,14 +255,38 @@ class SizeRegistry extends Disposable implements ISizeRegistry { } public resolveDefaultSize(id: SizeIdentifier, theme: IColorTheme): SizeValue | undefined { + return this.resolveSize(id, theme, {}); + } + + public resolveSize(id: SizeIdentifier, theme: IColorTheme, customizations: SizeCustomizations): SizeValue | undefined { + return this.resolveSizeWithReferences(id, theme, customizations, new Set()); + } + + private resolveSizeWithReferences(id: SizeIdentifier, theme: IColorTheme, customizations: SizeCustomizations, resolving: Set): SizeValue | undefined { + if (resolving.has(id)) { + throw new Error(`Circular size token reference: ${[...resolving, id].join(' -> ')}`); + } const sizeDesc = this.sizesById[id]; + const customized = customizations[id]; + if (sizeDesc?.customization && typeof customized === 'number' + && Number.isInteger(customized) && customized >= sizeDesc.customization.minimum && customized <= sizeDesc.customization.maximum) { + return size(customized); + } if (sizeDesc?.defaults) { + if (typeof sizeDesc.defaults === 'string') { + resolving.add(id); + return this.resolveSizeWithReferences(sizeDesc.defaults, theme, customizations, resolving); + } const sizeValue = isSizeDefaults(sizeDesc.defaults) ? sizeDesc.defaults[theme.type] : sizeDesc.defaults; return sizeValue ?? undefined; } return undefined; } + public getSizeCustomizationSchema(): IJSONSchema { + return this.sizeCustomizationSchema; + } + public getSizeSchema(): IJSONSchema { return this.sizeSchema; } @@ -263,8 +313,8 @@ class SizeRegistry extends Disposable implements ISizeRegistry { const sizeRegistry = new SizeRegistry(); platform.Registry.add(Extensions.SizeContribution, sizeRegistry); -export function registerSize(id: string, defaults: SizeDefaults | SizeValue | null, description: string, deprecationMessage?: string): SizeIdentifier { - return sizeRegistry.registerSize(id, defaults, description, deprecationMessage); +export function registerSize(id: string, defaults: SizeDefaults | SizeValue | SizeIdentifier | null, description: string, deprecationMessage?: string, customization?: SizeCustomization): SizeIdentifier { + return sizeRegistry.registerSize(id, defaults, description, deprecationMessage, customization); } export function getSizeRegistry(): ISizeRegistry { @@ -272,11 +322,16 @@ export function getSizeRegistry(): ISizeRegistry { } export const workbenchSizesSchemaId = 'vscode://schemas/workbench-sizes'; +export const sizeCustomizationsSchemaId = 'vscode://schemas/size-customizations'; const schemaRegistry = platform.Registry.as(JSONExtensions.JSONContribution); schemaRegistry.registerSchema(workbenchSizesSchemaId, sizeRegistry.getSizeSchema()); +schemaRegistry.registerSchema(sizeCustomizationsSchemaId, sizeRegistry.getSizeCustomizationSchema()); -const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(workbenchSizesSchemaId), 200); +const delayer = new RunOnceScheduler(() => { + schemaRegistry.notifySchemaChanged(workbenchSizesSchemaId); + schemaRegistry.notifySchemaChanged(sizeCustomizationsSchemaId); +}, 200); sizeRegistry.onDidChangeSchema(() => { if (!delayer.isScheduled()) { diff --git a/src/vs/platform/theme/common/sizes/semanticSizes.ts b/src/vs/platform/theme/common/sizes/semanticSizes.ts new file mode 100644 index 000000000000..f73f5b9f0b8c --- /dev/null +++ b/src/vs/platform/theme/common/sizes/semanticSizes.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 { localize } from '../../../../nls.js'; +import { registerSize } from '../sizeUtils.js'; +import { cornerRadiusLarge, cornerRadiusSmall, spacingSize40 } from './baseSizes.js'; + +const cornerRadiusCustomization = { minimum: 0, maximum: 8 }; + +export const controlsCornerRadius = registerSize('controls.cornerRadius', cornerRadiusSmall, + localize('controls.cornerRadius', "Shared corner radius for standard buttons, toolbar actions, text inputs, selects, checkboxes, toggles, and radio controls in editor and Agents windows. Individual button and input values override this value. Does not change tabs, circular or pill-shaped controls, or hit areas."), undefined, cornerRadiusCustomization); + +export const buttonsCornerRadius = registerSize('buttons.cornerRadius', controlsCornerRadius, + localize('buttons.cornerRadius', "Corner radius for standard text buttons, toolbar and icon actions, and split buttons. Joined button edges stay square. Inherits controls.cornerRadius unless overridden; circular and pill-shaped buttons are unchanged."), undefined, cornerRadiusCustomization); + +export const inputsCornerRadius = registerSize('inputs.cornerRadius', controlsCornerRadius, + localize('inputs.cornerRadius', "Corner radius for standard text inputs, find inputs, and select controls. Does not change the chat composer. Inherits controls.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const popupsCornerRadius = registerSize('popups.cornerRadius', cornerRadiusLarge, + localize('popups.cornerRadius', "Shared corner radius for custom menus, hovers, dialogs, and the Command Palette in editor and Agents windows, and for Modern UI editor pop-ups. Individual menu, hover, and dialog values override this value. Native operating system surfaces and notifications are unchanged."), undefined, cornerRadiusCustomization); + +export const menusCornerRadius = registerSize('menus.cornerRadius', popupsCornerRadius, + localize('menus.cornerRadius', "Corner radius for custom context menus, action pickers, and select-option pop-ups, including their backgrounds and clipping. Native menus are unchanged. Inherits popups.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const hoversCornerRadius = registerSize('hovers.cornerRadius', popupsCornerRadius, + localize('hovers.cornerRadius', "Corner radius for editor and workbench hovers and tooltips. Inherits popups.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const dialogsCornerRadius = registerSize('dialogs.cornerRadius', popupsCornerRadius, + localize('dialogs.cornerRadius', "Corner radius for custom dialogs inside editor and Agents windows. Native operating system dialogs are unchanged. Inherits popups.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const defaultCornerRadius = registerSize('default.cornerRadius', cornerRadiusLarge, + localize('default.cornerRadius', "Default corner radius for panel areas, in pixels. More specific sizes override this value. Controls, pop-ups, and the app window corners are unchanged."), undefined, cornerRadiusCustomization); + +export const panelsCornerRadius = registerSize('panels.cornerRadius', defaultCornerRadius, + localize('panels.cornerRadius', "Shared corner radius for side bars, the editor area, the tools panel, and Agents chat areas and pages. Inherits default.cornerRadius unless overridden. Individual areas can override this value."), undefined, cornerRadiusCustomization); + +export const agentsPanelsCornerRadius = registerSize('agentsWindow.panels.cornerRadius', panelsCornerRadius, + localize('agentsWindow.panels.cornerRadius', "Shared corner radius for panel areas in the Agents window only. Inherits panels.cornerRadius unless overridden. Individual Agents areas can override this value."), undefined, cornerRadiusCustomization); + +export const toolsPanelCornerRadius = registerSize('toolsPanel.cornerRadius', panelsCornerRadius, + localize('toolsPanel.cornerRadius', "Corner radius for the panel containing Terminal, Output, Problems, and Debug Console, wherever it is positioned. Inherits panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const primarySideBarCornerRadius = registerSize('primarySideBar.cornerRadius', panelsCornerRadius, + localize('primarySideBar.cornerRadius', "Corner radius for the editor window's Primary Side Bar, where Explorer, Search, and Source Control normally appear. Inherits panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const secondarySideBarCornerRadius = registerSize('secondarySideBar.cornerRadius', panelsCornerRadius, + localize('secondarySideBar.cornerRadius', "Corner radius for the editor window's Secondary Side Bar, often used for Chat. Inherits panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const editorAreaCornerRadius = registerSize('editorArea.cornerRadius', panelsCornerRadius, + localize('editorArea.cornerRadius', "Corner radius for the area containing file editors and their tabs. Does not change individual tab corners. Inherits panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const activityBarCornerRadius = registerSize('activityBar.cornerRadius', primarySideBarCornerRadius, + localize('activityBar.cornerRadius', "Corner radius for the Activity Bar containing the Explorer, Search, and Source Control icons. Does not change the icons or their buttons. Inherits primarySideBar.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const agentsChatPanelsCornerRadius = registerSize('agentsWindow.chatPanels.cornerRadius', agentsPanelsCornerRadius, + localize('agentsWindow.chatPanels.cornerRadius', "Corner radius of the outer panel frames containing conversations in the Agents window. Does not change individual messages, message bubbles, or the chat input. This does not affect the Chat side bar in the editor window; customize that side bar instead. Inherits agentsWindow.panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const pagesCornerRadius = registerSize('pages.cornerRadius', agentsPanelsCornerRadius, + localize('pages.cornerRadius', "Corner radius for pages such as Automations that open in place of chats in the Agents window. Inherits agentsWindow.panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const agentsEditorAreaCornerRadius = registerSize('agentsWindow.editorArea.cornerRadius', agentsPanelsCornerRadius, + localize('agentsWindow.editorArea.cornerRadius', "Corner radius for the file editor area in the Agents window only. Inherits agentsWindow.panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const agentsToolsPanelCornerRadius = registerSize('agentsWindow.toolsPanel.cornerRadius', agentsPanelsCornerRadius, + localize('agentsWindow.toolsPanel.cornerRadius', "Corner radius for the Terminal, Output, Problems, and Debug Console panel in the Agents window only. Inherits agentsWindow.panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +export const agentsSecondarySideBarCornerRadius = registerSize('agentsWindow.secondarySideBar.cornerRadius', agentsPanelsCornerRadius, + localize('agentsWindow.secondarySideBar.cornerRadius', "Corner radius for Files, Changes, and other side views in the Agents window only. Inherits agentsWindow.panels.cornerRadius unless overridden."), undefined, cornerRadiusCustomization); + +const panelSpacingCustomization = { minimum: 0, maximum: 16 }; + +export const panelsSpacing = registerSize('panels.spacing', spacingSize40, + localize('panels.spacing', "Space between panel areas in pixels, from 0 to 16. Applies to Modern UI editor windows and, unless overridden, the Agents window. Window-edge gutters and spacing inside controls are unchanged. Compact layouts remain gapless."), undefined, panelSpacingCustomization); + +export const agentsPanelsSpacing = registerSize('agentsWindow.panels.spacing', panelsSpacing, + localize('agentsWindow.panels.spacing', "Space between panel areas and between split chats in the Agents window only, in pixels from 0 to 16. Inherits panels.spacing unless overridden. Compact and phone layouts remain gapless; window-edge gutters are unchanged."), undefined, panelSpacingCustomization); diff --git a/src/vs/platform/theme/common/themeService.ts b/src/vs/platform/theme/common/themeService.ts index 1d1ea525996f..cba79418a057 100644 --- a/src/vs/platform/theme/common/themeService.ts +++ b/src/vs/platform/theme/common/themeService.ts @@ -263,6 +263,7 @@ export interface IPartsSplash { windowBorderRadius: string | undefined; modernUI: boolean; modernUICompact: boolean; + panelSpacing?: number; partBounds: { activityBar?: IPartsSplashPartBounds; sideBar: IPartsSplashPartBounds | undefined; @@ -278,6 +279,7 @@ export interface IPartsSplashPartBounds { left: number; width: number; height: number; + cornerRadius?: number; outerEdges?: { left: boolean; right: boolean; diff --git a/src/vs/platform/theme/test/common/sizeRegistry.test.ts b/src/vs/platform/theme/test/common/sizeRegistry.test.ts index eb2138790b83..6f577fec7b11 100644 --- a/src/vs/platform/theme/test/common/sizeRegistry.test.ts +++ b/src/vs/platform/theme/test/common/sizeRegistry.test.ts @@ -5,13 +5,96 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; -import { getSizeRegistry, registerSize, size, sizeForAllThemes, sizeValueToCss, asCssVariableName, asCssVariable } from '../../common/sizeRegistry.js'; +import { getSizeRegistry, registerSize, size, sizeForAllThemes, sizeValueToCss, asCssVariableName, asCssVariable, defaultCornerRadius, panelsCornerRadius, toolsPanelCornerRadius, primarySideBarCornerRadius, activityBarCornerRadius } from '../../common/sizeRegistry.js'; +import { TestColorTheme } from './testThemeService.js'; +import { toDisposable } from '../../../../base/common/lifecycle.js'; +import { ColorScheme } from '../../common/theme.js'; // Import baseSizes to ensure base size tokens are registered import { bodyFontSize, bodyFontSizeSmall, codiconFontSize, cornerRadiusMedium, cornerRadiusSmall, cornerRadiusLarge, strokeThickness } from '../../common/sizes/baseSizes.js'; suite('Size Registry', () => { - ensureNoDisposablesAreLeakedInTestSuite(); + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('resolves primitive, role and component sizes in specificity order', () => { + const registry = getSizeRegistry(); + const theme = new TestColorTheme(); + const tokens = [cornerRadiusLarge, defaultCornerRadius, panelsCornerRadius, toolsPanelCornerRadius, primarySideBarCornerRadius, activityBarCornerRadius]; + const resolve = (customizations: Record) => tokens.map(id => registry.resolveSize(id, theme, customizations)?.value); + assert.deepStrictEqual({ + defaults: resolve({}), + surface: resolve({ 'default.cornerRadius': 6 }), + part: resolve({ 'default.cornerRadius': 6, 'panels.cornerRadius': 4 }), + component: resolve({ 'panels.cornerRadius': 4, 'primarySideBar.cornerRadius': 2 }), + rail: resolve({ 'primarySideBar.cornerRadius': 2, 'activityBar.cornerRadius': 0 }), + primitiveOverrideIgnored: resolve({ 'cornerRadius.large': 0 }), + }, { + defaults: [8, 8, 8, 8, 8, 8], + surface: [8, 6, 6, 6, 6, 6], + part: [8, 6, 4, 4, 4, 4], + component: [8, 8, 4, 4, 2, 2], + rail: [8, 8, 8, 8, 2, 0], + primitiveOverrideIgnored: [8, 8, 8, 8, 8, 8], + }); + }); + + test('references retain per-theme primitive defaults', () => { + const base = registerSize('test.schemeSize', { light: size(3), dark: size(4), hcDark: size(5), hcLight: size(6) }, 'Test'); + store.add(toDisposable(() => getSizeRegistry().deregisterSize(base))); + const alias = registerSize('test.schemeAlias', base, 'Test'); + store.add(toDisposable(() => getSizeRegistry().deregisterSize(alias))); + assert.deepStrictEqual([ColorScheme.LIGHT, ColorScheme.DARK, ColorScheme.HIGH_CONTRAST_DARK, ColorScheme.HIGH_CONTRAST_LIGHT] + .map(type => getSizeRegistry().resolveDefaultSize(alias, new TestColorTheme({}, type))?.value), [3, 4, 5, 6]); + }); + + test('detects circular references rather than recursing indefinitely', () => { + const id = registerSize('test.cycle', 'test.cycle', 'Test'); + store.add(toDisposable(() => getSizeRegistry().deregisterSize(id))); + assert.throws(() => getSizeRegistry().resolveDefaultSize(id, new TestColorTheme()), /Circular size token reference/); + }); + + test('exposes only bounded semantic tokens in the customization schema', () => { + const schema = getSizeRegistry().getSizeCustomizationSchema(); + const properties = schema.properties!; + assert.deepStrictEqual({ + additionalProperties: schema.additionalProperties, + names: Object.keys(properties).sort(), + panel: { + type: properties[toolsPanelCornerRadius].type, + minimum: properties[toolsPanelCornerRadius].minimum, + maximum: properties[toolsPanelCornerRadius].maximum, + }, + primitive: properties[cornerRadiusLarge], + }, { + additionalProperties: false, + names: [ + 'activityBar.cornerRadius', + 'agentsWindow.chatPanels.cornerRadius', + 'agentsWindow.editorArea.cornerRadius', + 'agentsWindow.panels.cornerRadius', + 'agentsWindow.panels.spacing', + 'agentsWindow.secondarySideBar.cornerRadius', + 'agentsWindow.toolsPanel.cornerRadius', + 'buttons.cornerRadius', + 'controls.cornerRadius', + 'default.cornerRadius', + 'dialogs.cornerRadius', + 'editorArea.cornerRadius', + 'hovers.cornerRadius', + 'inputs.cornerRadius', + 'menus.cornerRadius', + 'pages.cornerRadius', + 'panels.cornerRadius', + 'panels.spacing', + 'popups.cornerRadius', + 'primarySideBar.cornerRadius', + 'secondarySideBar.cornerRadius', + 'toolsPanel.cornerRadius', + ], + panel: { type: 'integer', minimum: 0, maximum: 8 }, + primitive: undefined, + }); + }); test('registerSize should register a size token', () => { const id = registerSize('test.size', { dark: size(10, 'px'), light: size(10, 'px'), hcDark: size(10, 'px'), hcLight: size(10, 'px') }, 'Test size'); diff --git a/src/vs/platform/tunnel/node/tunnelService.ts b/src/vs/platform/tunnel/node/tunnelService.ts index fcaef2c9715f..76354e7e376a 100644 --- a/src/vs/platform/tunnel/node/tunnelService.ts +++ b/src/vs/platform/tunnel/node/tunnelService.ts @@ -50,7 +50,7 @@ export class NodeRemoteTunnel extends Disposable implements RemoteTunnel { private readonly _connectionListener: (socket: net.Socket) => void; private readonly _errorListener: () => void; - private readonly _socketsDispose: Map void> = new Map(); + private readonly _socketsDispose: Map void> = new Map(); constructor(options: IConnectionOptions, private readonly defaultTunnelHost: string, tunnelRemoteHost: string, tunnelRemotePort: number, private readonly suggestedLocalPort?: number) { super(); @@ -123,17 +123,12 @@ export class NodeRemoteTunnel extends Disposable implements RemoteTunnel { localSocket.write(dataChunk.buffer); } - localSocket.on('end', () => { - if (localSocket.localAddress) { - this._socketsDispose.delete(localSocket.localAddress); - } + localSocket.on('end', () => remoteSocket.end()); + localSocket.on('close', () => { + this._socketsDispose.delete(localSocket); remoteSocket.end(); }); - localSocket.on('close', () => remoteSocket.end()); localSocket.on('error', () => { - if (localSocket.localAddress) { - this._socketsDispose.delete(localSocket.localAddress); - } if (remoteSocket instanceof NodeSocket) { remoteSocket.socket.destroy(); } else { @@ -147,8 +142,8 @@ export class NodeRemoteTunnel extends Disposable implements RemoteTunnel { this._mirrorGenericSocket(localSocket, remoteSocket); } - if (localSocket.localAddress) { - this._socketsDispose.set(localSocket.localAddress, () => { + if (!localSocket.destroyed) { + this._socketsDispose.set(localSocket, () => { // Need to end instead of unpipe, otherwise whatever is connected locally could end up "stuck" with whatever state it had until manually exited. localSocket.end(); remoteSocket.end(); diff --git a/src/vs/platform/tunnel/test/node/fixtures/tunnelServiceConnection.ts b/src/vs/platform/tunnel/test/node/fixtures/tunnelServiceConnection.ts new file mode 100644 index 000000000000..554f25c51dcb --- /dev/null +++ b/src/vs/platform/tunnel/test/node/fixtures/tunnelServiceConnection.ts @@ -0,0 +1,93 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { once } from 'events'; +import * as net from 'net'; +import { raceTimeout } from '../../../../../base/common/async.js'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { PersistentProtocol } from '../../../../../base/parts/ipc/common/ipc.net.js'; +import { NodeSocket } from '../../../../../base/parts/ipc/node/ipc.net.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { TestConfigurationService } from '../../../../configuration/test/common/testConfigurationService.js'; +import { NullLogService } from '../../../../log/common/log.js'; +import { IProductService } from '../../../../product/common/productService.js'; +import { ConnectionType, HandshakeMessage } from '../../../../remote/common/remoteAgentConnection.js'; +import { RemoteConnectionType, WebSocketRemoteConnection } from '../../../../remote/common/remoteAuthorityResolver.js'; +import { RemoteSocketFactoryService } from '../../../../remote/common/remoteSocketFactoryService.js'; +import { TunnelService } from '../../../node/tunnelService.js'; + +const count = Number(process.argv[2]); +const disconnectFirst = process.argv[3] === 'true'; +assert.ok(count === 1 || count === 2); +const store = new DisposableStore(); +try { + const server = net.createServer(socket => { + const peer = store.add(new PersistentProtocol({ socket: store.add(new NodeSocket(socket)), sendKeepAlive: false })); + store.add(peer.onControlMessage(raw => { + const message: HandshakeMessage = JSON.parse(raw.toString()); + if (message.type === 'auth') { + peer.sendControl(VSBuffer.fromString(JSON.stringify({ type: 'sign', data: 'test', signedData: 'test' }))); + } else if (message.type === 'connectionType') { + assert.strictEqual(message.desiredConnectionType, ConnectionType.Tunnel); + peer.sendControl(VSBuffer.fromString(JSON.stringify({ type: 'ok' }))); + peer.dispose(); + socket.pipe(socket); + } + })); + }); + store.add(toDisposable(() => server.close())); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + + const remoteSocketFactoryService = new RemoteSocketFactoryService(); + store.add(remoteSocketFactoryService.register(RemoteConnectionType.WebSocket, { + supports: () => true, + connect: async () => { + const socket = store.add(new NodeSocket(net.createConnection({ host: '127.0.0.1', port: address.port }))); + await once(socket.socket, 'connect'); + return socket; + } + })); + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + const service = store.add(new TunnelService(remoteSocketFactoryService, store.add(new NullLogService()), { + _serviceBrand: undefined, + createNewMessage: async value => ({ id: 'test', data: value }), + validate: async () => true, + sign: async value => value + }, new class extends mock() { }(), configurationService)); + const tunnel = await service.openTunnel({ + getAddress: async () => ({ connectTo: new WebSocketRemoteConnection('127.0.0.1', address.port), connectionToken: undefined }) + }, '127.0.0.1', address.port, '127.0.0.1', 0); + assert.ok(tunnel && typeof tunnel !== 'string'); + assert.ok(tunnel.tunnelLocalPort); + + const clients: net.Socket[] = []; + for (let i = 0; i < count; i++) { + const client: net.Socket = net.createConnection({ host: '127.0.0.1', port: tunnel.tunnelLocalPort }); + store.add(toDisposable(() => client.destroy())); + const response: Promise = once(client, 'data'); + client.write('ready'); + assert.strictEqual((await response)[0].toString(), 'ready'); + clients.push(client); + } + + if (disconnectFirst) { + const first = clients.shift()!; + const firstClosed = once(first, 'close'); + first.end(); + await firstClosed; + } + const closed = Promise.all(clients.map(client => once(client, 'close'))); + await service.closeTunnel('127.0.0.1', address.port); + await raceTimeout(closed, 1000); + process.send?.(clients.map(client => client.destroyed)); +} finally { + store.dispose(); +} diff --git a/src/vs/platform/tunnel/test/node/tunnelService.test.ts b/src/vs/platform/tunnel/test/node/tunnelService.test.ts index f499977094a1..3c68eb118bbb 100644 --- a/src/vs/platform/tunnel/test/node/tunnelService.test.ts +++ b/src/vs/platform/tunnel/test/node/tunnelService.test.ts @@ -4,8 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { fork } from 'child_process'; import { once } from 'events'; import * as net from 'net'; +import { raceTimeout } from '../../../../base/common/async.js'; import { VSBuffer } from '../../../../base/common/buffer.js'; import { Emitter } from '../../../../base/common/event.js'; import { toDisposable } from '../../../../base/common/lifecycle.js'; @@ -13,6 +15,44 @@ import { ISocket, SocketCloseEvent, SocketCloseEventType } from '../../../../bas import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import { NodeRemoteTunnel } from '../../node/tunnelService.js'; +suite('TunnelService connections', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + async function closeTunnelWithClients(count: number, disconnectFirst = false) { + // Isolate the real handshake's process-scoped timeout cancellation sources. + const child = fork(new URL('./fixtures/tunnelServiceConnection.js', import.meta.url), [String(count), String(disconnectFirst)], { + env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, + execArgv: [], + silent: true + }); + store.add(toDisposable(() => { child.kill(); })); + const exited = once(child, 'exit'); + let stderr = ''; + child.stderr?.on('data', data => stderr += data.toString()); + try { + const result: boolean[][] | undefined = await raceTimeout(Promise.race([ + once(child, 'message'), + exited.then(([code]) => { throw new Error(`Tunnel fixture exited with code ${code}: ${stderr}`); }) + ]), 5000); + assert.ok(result, 'The loopback tunnel fixture must finish'); + return result[0]; + } finally { + child.kill(); + await exited; + } + } + + for (const count of [1, 2]) { + test(`closing a tunnel closes all ${count} active connections`, async () => { + assert.deepStrictEqual(await closeTunnelWithClients(count), Array(count).fill(true)); + }); + } + + test('closing one connection does not lose track of another connection', async () => { + assert.deepStrictEqual(await closeTunnelWithClients(2, true), [true]); + }); +}); + suite('NodeRemoteTunnel', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); diff --git a/src/vs/platform/update/common/update.config.contribution.ts b/src/vs/platform/update/common/update.config.contribution.ts index 00d5cf3e96e8..1974a3f452d4 100644 --- a/src/vs/platform/update/common/update.config.contribution.ts +++ b/src/vs/platform/update/common/update.config.contribution.ts @@ -99,6 +99,16 @@ configurationRegistry.registerConfiguration({ tags: ['usesOnlineServices'], agentsWindow: { default: false, readOnly: true }, }, + 'update.showReleaseHighlightsVideo': { + type: 'boolean', + default: false, + experiment: { mode: 'auto' }, + scope: ConfigurationScope.APPLICATION, + included: !isWeb, + description: localize('showReleaseHighlightsVideo', "Include an available highlights video when opening release notes. The video does not play automatically. Videos are fetched from a Microsoft online service."), + tags: ['usesOnlineServices'], + agentsWindow: { default: false, readOnly: true }, + }, 'update.showPostInstallInfo': { type: 'boolean', default: false, diff --git a/src/vs/platform/window/electron-main/window.ts b/src/vs/platform/window/electron-main/window.ts index b318f80f5ab3..0fdf26803614 100644 --- a/src/vs/platform/window/electron-main/window.ts +++ b/src/vs/platform/window/electron-main/window.ts @@ -147,6 +147,8 @@ export interface IWindowState { y?: number; mode?: WindowMode; zoomLevel?: number; + /** Restores this window's always-on-top state independently of other windows. */ + alwaysOnTop?: boolean; readonly display?: number; /** diff --git a/src/vs/platform/windows/electron-main/folderLocationsMainService.ts b/src/vs/platform/windows/electron-main/folderLocationsMainService.ts new file mode 100644 index 000000000000..469dccf3bb31 --- /dev/null +++ b/src/vs/platform/windows/electron-main/folderLocationsMainService.ts @@ -0,0 +1,141 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { extUriBiasedIgnorePathCase } from '../../../base/common/resources.js'; +import { Schemas } from '../../../base/common/network.js'; +import { URI } from '../../../base/common/uri.js'; +import { FileOperationResult, IFileService, toFileOperationResult } from '../../files/common/files.js'; +import { createDecorator } from '../../instantiation/common/instantiation.js'; +import { ILogService } from '../../log/common/log.js'; +import { IStateService } from '../../state/node/state.js'; +import { IWindowFolderLocation } from '../../window/common/window.js'; + +export const IFolderLocationsMainService = createDecorator('folderLocationsMainService'); + +/** The outcome of validating the alternate location a window is about to be opened at. */ +export interface IValidatedFolderLocation { + readonly folderLocation?: IWindowFolderLocation; + readonly folderLocationMissing?: { readonly label: string }; +} + +/** + * Remembers the alternate location each workspace folder was last at, so that a fresh open + * of the folder starts at it again, and validates a location before a window starts at it. + * Every `workspace` parameter is the workspace's own location (`IWorkspace.uri`). + */ +export interface IFolderLocationsMainService { + + readonly _serviceBrand: undefined; + + /** + * The alternate location the workspace was last at. Nothing remembered is trusted: + * it is validated before a window starts at it. + */ + getFolderLocation(workspace: URI): IWindowFolderLocation | undefined; + + /** Remembers the alternate location of the workspace, or forgets it when `undefined`. */ + updateFolderLocation(workspace: URI, location: IWindowFolderLocation | undefined): void; + + /** + * Decides whether a window can start at the candidate location of the workspace: only a local + * directory that is not known to be gone qualifies. If it is gone, the window opens at the + * workspace's own location, the remembered location is forgotten and the result tells the + * window, so that it can inform the user. If its existence cannot be determined (for example + * because of a permission or I/O error), the location is kept and remembered; the window then + * offers to return if no provider confirms it. + */ + validateFolderLocation(workspace: URI, candidate: IWindowFolderLocation | undefined): Promise; +} + +export class FolderLocationsMainService implements IFolderLocationsMainService { + + declare readonly _serviceBrand: undefined; + + private static readonly storageKey = 'folderLocations'; + + /** Bounds the state: folders that are never returned to their own location age out. */ + private static readonly maxEntries = 100; + + constructor( + @IStateService private readonly stateService: IStateService, + @IFileService private readonly fileService: IFileService, + @ILogService private readonly logService: ILogService + ) { } + + getFolderLocation(workspace: URI): IWindowFolderLocation | undefined { + const candidate = this.read()[extUriBiasedIgnorePathCase.getComparisonKey(workspace)]; + return isWindowFolderLocation(candidate) ? candidate : undefined; + } + + updateFolderLocation(workspace: URI, location: IWindowFolderLocation | undefined): void { + const entries = this.read(); + const key = extUriBiasedIgnorePathCase.getComparisonKey(workspace); + if (!location && entries[key] === undefined) { + return; + } + + // Re-inserted last, so that the oldest entries are the first to age out + delete entries[key]; + if (location) { + entries[key] = location; + } + + const keys = Object.keys(entries); + for (const oldest of keys.slice(0, Math.max(0, keys.length - FolderLocationsMainService.maxEntries))) { + delete entries[oldest]; + } + + this.stateService.setItem(FolderLocationsMainService.storageKey, entries); + } + + async validateFolderLocation(workspace: URI, candidate: IWindowFolderLocation | undefined): Promise { + if (!candidate) { + return {}; + } + + const location = parseUri(candidate.uri); + if (location?.scheme === Schemas.file && await this.exists(location) !== 'missing') { + return { folderLocation: candidate }; + } + + this.updateFolderLocation(workspace, undefined); + return { folderLocationMissing: { label: candidate.label } }; + } + + /** + * Only a definite answer counts as missing (not found, or not a directory). Other failures + * such as permission or I/O errors are transient or unrelated to the folder being gone. + */ + private async exists(location: URI): Promise<'exists' | 'missing' | 'unknown'> { + try { + return (await this.fileService.stat(location)).isDirectory ? 'exists' : 'missing'; + } catch (error) { + const result = toFileOperationResult(error); + if (result === FileOperationResult.FILE_NOT_FOUND || result === FileOperationResult.FILE_NOT_DIRECTORY) { + return 'missing'; + } + + this.logService.warn(`Could not determine whether the folder location ${location.fsPath} exists`, error); + return 'unknown'; + } + } + + private read(): Record { + const entries = this.stateService.getItem>(FolderLocationsMainService.storageKey); + return entries && typeof entries === 'object' ? { ...entries } : {}; + } +} + +function isWindowFolderLocation(candidate: Partial | undefined): candidate is IWindowFolderLocation { + return !!candidate && typeof candidate.uri === 'string' && !!parseUri(candidate.uri) && typeof candidate.label === 'string' && typeof candidate.providerId === 'string'; +} + +function parseUri(value: string): URI | undefined { + try { + return URI.parse(value); + } catch { + return undefined; // malformed remembered state is ignored + } +} diff --git a/src/vs/platform/windows/electron-main/windowImpl.ts b/src/vs/platform/windows/electron-main/windowImpl.ts index 8f69473fb8f2..3f38cac1e232 100644 --- a/src/vs/platform/windows/electron-main/windowImpl.ts +++ b/src/vs/platform/windows/electron-main/windowImpl.ts @@ -34,7 +34,7 @@ import { ITelemetryService } from '../../telemetry/common/telemetry.js'; import { ThemeIcon } from '../../../base/common/themables.js'; import { IThemeMainService } from '../../theme/electron-main/themeMainService.js'; import { getMenuBarVisibility, IFolderToOpen, INativeWindowConfiguration, IWindowSettings, IWorkspaceToOpen, MenuBarVisibility, hasNativeTitlebar, useNativeFullScreen, DEFAULT_CUSTOM_TITLEBAR_HEIGHT, TitlebarStyle, MenuSettings, getMacOSWindowControlsPosition } from '../../window/common/window.js'; -import { defaultBrowserWindowOptions, getAllWindowsExcludingOffscreen, IWindowsMainService, OpenContext, WindowStateValidator } from './windows.js'; +import { defaultBrowserWindowOptions, getAllWindowsExcludingOffscreen, isHiddenWindowMode, IWindowsMainService, OpenContext, WindowStateValidator } from './windows.js'; import { ISingleFolderWorkspaceIdentifier, IWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, toWorkspaceIdentifier } from '../../workspace/common/workspace.js'; import { IWorkspacesManagementMainService } from '../../workspaces/electron-main/workspacesManagementMainService.js'; import { IWindowState, ICodeWindow, ILoadEvent, WindowMode, WindowError, LoadReason, defaultWindowState, IBaseWindow } from '../../window/electron-main/window.js'; @@ -273,7 +273,8 @@ export abstract class BaseWindow extends Disposable implements IBaseWindow { } // Open devtools if instructed from command line args - if (this.environmentMainService.args['open-devtools'] === true) { + // (not in hidden mode: undocked DevTools would be shown) + if (this.environmentMainService.args['open-devtools'] === true && !isHiddenWindowMode(this.environmentMainService)) { win.webContents.openDevTools(); } @@ -351,6 +352,13 @@ export abstract class BaseWindow extends Disposable implements IBaseWindow { if (state.mode === WindowMode.Maximized || state.mode === WindowMode.Fullscreen) { + // maximize() and setFullScreen() would reveal a window that was never shown, + // so only give it the size it would have + if (isHiddenWindowMode(this.environmentMainService)) { + this._win?.setBounds(this.getDisplayArea(state.mode)); + return; + } + // this call may or may not show the window, depends // on the platform: currently on Windows and Linux will // show the window as active. To be on the safe side, @@ -376,6 +384,12 @@ export abstract class BaseWindow extends Disposable implements IBaseWindow { } } + protected getDisplayArea(mode: WindowMode.Maximized | WindowMode.Fullscreen): electron.Rectangle { + const display = this._win ? electron.screen.getDisplayMatching(this._win.getBounds()) : electron.screen.getPrimaryDisplay(); + + return mode === WindowMode.Fullscreen ? display.bounds : display.workArea; + } + private representedFilename: string | undefined; setRepresentedFilename(filename: string): void { @@ -435,6 +449,10 @@ export abstract class BaseWindow extends Disposable implements IBaseWindow { } focus(options?: { mode: FocusMode }): void { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // focusing would show the window and activate the application + } + switch (options?.mode ?? FocusMode.Transfer) { case FocusMode.Transfer: this.doFocusWindow(); @@ -578,6 +596,10 @@ export abstract class BaseWindow extends Disposable implements IBaseWindow { private joinNativeFullScreenTransition: DeferredPromise | undefined = undefined; toggleFullScreen(): void { + if (isHiddenWindowMode(this.environmentMainService)) { + return; // entering fullscreen would reveal the window (and switch Spaces on macOS) + } + this.setFullScreen(!this.isFullScreen, false); } @@ -1050,9 +1072,10 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { // Telemetry type WindowErrorClassification = { - type: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The type of window error to understand the nature of the error better.' }; + type: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'The type of window error to understand the nature of the error better.' }; reason: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The reason of the window error to understand the nature of the error better.' }; - code: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'The exit code of the window process to understand the nature of the error better' }; + code: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'The exit code of the window process to understand the nature of the error better' }; + isAgentsWindow: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether the window was an Agents window, to attribute window errors to it.' }; owner: 'bpasero'; comment: 'Provides insight into reasons the vscode window had an error.'; }; @@ -1060,11 +1083,13 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { type: WindowError; reason: string | undefined; code: number | undefined; + isAgentsWindow: boolean; }; this.telemetryService.publicLog2('windowerror', { type, reason: details?.reason, - code: details?.exitCode + code: details?.exitCode, + isAgentsWindow: !!this._config?.isSessionsWindow }); // Inform User if non-recoverable @@ -1547,6 +1572,7 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { x: this.windowState.x || 0, y: this.windowState.y || 0, zoomLevel: this.customZoomLevel, + alwaysOnTop: this._win.isAlwaysOnTop(), minimized: minimized || undefined }; } @@ -1589,6 +1615,7 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { } state.zoomLevel = this.customZoomLevel; + state.alwaysOnTop = this._win.isAlwaysOnTop(); return state; } @@ -1596,6 +1623,7 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { private restoreWindowState(state?: IWindowState): [IWindowState, boolean? /* has multiple displays */] { mark('code/willRestoreCodeWindowState'); + const alwaysOnTop = state?.alwaysOnTop; let hasMultipleDisplays = false; if (state) { @@ -1615,7 +1643,7 @@ export class CodeWindow extends BaseWindow implements ICodeWindow { mark('code/didRestoreCodeWindowState'); - return [state || defaultWindowState(), hasMultipleDisplays]; + return [{ ...(state || defaultWindowState()), alwaysOnTop }, hasMultipleDisplays]; } getBounds(): electron.Rectangle { diff --git a/src/vs/platform/windows/electron-main/windows.ts b/src/vs/platform/windows/electron-main/windows.ts index e3ca50abb1e0..73d4a95f3a76 100644 --- a/src/vs/platform/windows/electron-main/windows.ts +++ b/src/vs/platform/windows/electron-main/windows.ts @@ -33,6 +33,7 @@ export interface IWindowsMainService { readonly onDidMaximizeWindow: Event; readonly onDidUnmaximizeWindow: Event; readonly onDidChangeFullScreen: Event<{ window: ICodeWindow; fullscreen: boolean }>; + readonly onDidChangeAlwaysOnTop: Event<{ window: ICodeWindow; alwaysOnTop: boolean }>; readonly onDidTriggerSystemContextMenu: Event<{ readonly window: ICodeWindow; readonly x: number; readonly y: number }>; readonly onDidDestroyWindow: Event; @@ -144,6 +145,40 @@ export interface IDefaultBrowserWindowOptionsOverrides { backgroundColor?: string; } +/** + * Whether windows must never be shown or focused: `--hidden-window` is + * only honored when running extension tests (`--extensionTestsPath`). + */ +export function isHiddenWindowMode(environmentMainService: IEnvironmentMainService): boolean { + return environmentMainService.args['hidden-window'] === true && !!environmentMainService.extensionTestsLocationURI; +} + +/** + * Whether background throttling may be enabled at runtime: a hidden window + * is never visible, so throttling would apply to it permanently. + */ +export function isBackgroundThrottlingAllowed(environmentMainService: IEnvironmentMainService, allowed: boolean): boolean { + return allowed && !isHiddenWindowMode(environmentMainService); +} + +/** + * The mode an auxiliary window is restored into. Fullscreen is restored as + * maximized because auxiliary windows do not support restoring fullscreen. + */ +export function getAuxiliaryWindowRestoreMode(mode: WindowMode | undefined): WindowMode { + return mode === WindowMode.Maximized || mode === WindowMode.Fullscreen ? WindowMode.Maximized : WindowMode.Normal; +} + +/** + * The mode an auxiliary window is restored into when it is claimed. Prefer the + * mode requested at creation: `options.show` is also false for windows that are + * hidden with `--hidden-window`. Otherwise probe `options.show`, because + * maximized windows are never shown initially to reduce flicker. + */ +export function getClaimedAuxiliaryWindowMode(requestedMode: WindowMode | undefined, options: electron.BrowserWindowConstructorOptions): WindowMode { + return requestedMode ?? (options.show === false ? WindowMode.Maximized : WindowMode.Normal); +} + export function defaultBrowserWindowOptions(accessor: ServicesAccessor, windowState: IWindowState, overrides?: IDefaultBrowserWindowOptionsOverrides, webPreferences?: electron.WebPreferences): electron.BrowserWindowConstructorOptions & { experimentalDarkMode: boolean } { const themeMainService = accessor.get(IThemeMainService); const productService = accessor.get(IProductService); @@ -247,7 +282,7 @@ export function defaultBrowserWindowOptions(accessor: ServicesAccessor, windowSt } } - if (overrides?.alwaysOnTop) { + if (overrides?.alwaysOnTop ?? windowState.alwaysOnTop) { options.alwaysOnTop = true; } @@ -279,6 +314,14 @@ export function defaultBrowserWindowOptions(accessor: ServicesAccessor, windowSt }; } + if (isHiddenWindowMode(environmentMainService)) { + options.show = false; + options.webPreferences = { + ...options.webPreferences, + backgroundThrottling: false, // a never shown window must keep timers, animation frames and page visibility like a visible one + }; + } + return options; } diff --git a/src/vs/platform/windows/electron-main/windowsMainService.ts b/src/vs/platform/windows/electron-main/windowsMainService.ts index 44dcb40eb958..27ca31542757 100644 --- a/src/vs/platform/windows/electron-main/windowsMainService.ts +++ b/src/vs/platform/windows/electron-main/windowsMainService.ts @@ -207,6 +207,9 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic private readonly _onDidChangeFullScreen = this._register(new Emitter<{ window: ICodeWindow; fullscreen: boolean }>()); readonly onDidChangeFullScreen = this._onDidChangeFullScreen.event; + private readonly _onDidChangeAlwaysOnTop = this._register(new Emitter<{ window: ICodeWindow; alwaysOnTop: boolean }>()); + readonly onDidChangeAlwaysOnTop = this._onDidChangeAlwaysOnTop.event; + private readonly _onDidTriggerSystemContextMenu = this._register(new Emitter<{ window: ICodeWindow; x: number; y: number }>()); readonly onDidTriggerSystemContextMenu = this._onDidTriggerSystemContextMenu.event; @@ -1670,6 +1673,7 @@ export class WindowsMainService extends Disposable implements IWindowsMainServic disposables.add(createdWindow.onDidUnmaximize(() => this._onDidUnmaximizeWindow.fire(createdWindow))); disposables.add(createdWindow.onDidEnterFullScreen(() => this._onDidChangeFullScreen.fire({ window: createdWindow, fullscreen: true }))); disposables.add(createdWindow.onDidLeaveFullScreen(() => this._onDidChangeFullScreen.fire({ window: createdWindow, fullscreen: false }))); + disposables.add(createdWindow.onDidChangeAlwaysOnTop(alwaysOnTop => this._onDidChangeAlwaysOnTop.fire({ window: createdWindow, alwaysOnTop }))); disposables.add(createdWindow.onDidTriggerSystemContextMenu(({ x, y }) => this._onDidTriggerSystemContextMenu.fire({ window: createdWindow, x, y }))); const webContents = assertReturnsDefined(createdWindow.win?.webContents); diff --git a/src/vs/platform/windows/electron-main/windowsStateHandler.ts b/src/vs/platform/windows/electron-main/windowsStateHandler.ts index d44894a1f1c6..19c1172406f1 100644 --- a/src/vs/platform/windows/electron-main/windowsStateHandler.ts +++ b/src/vs/platform/windows/electron-main/windowsStateHandler.ts @@ -449,7 +449,8 @@ export class WindowsStateHandler extends Disposable { } else { state = { ...lastActiveState, - zoomLevel: undefined // do not inherit zoom level + zoomLevel: undefined, // do not inherit zoom level + alwaysOnTop: undefined }; } diff --git a/src/vs/platform/windows/test/electron-main/folderLocationsMainService.test.ts b/src/vs/platform/windows/test/electron-main/folderLocationsMainService.test.ts new file mode 100644 index 000000000000..006645137677 --- /dev/null +++ b/src/vs/platform/windows/test/electron-main/folderLocationsMainService.test.ts @@ -0,0 +1,152 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { VSBuffer } from '../../../../base/common/buffer.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { extUriBiasedIgnorePathCase } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { FileService } from '../../../files/common/fileService.js'; +import { createFileSystemProviderError, FileSystemProviderErrorCode, IStat } from '../../../files/common/files.js'; +import { InMemoryFileSystemProvider } from '../../../files/common/inMemoryFilesystemProvider.js'; +import { ILogService, NullLogService } from '../../../log/common/log.js'; +import { FolderLocationsMainService } from '../../electron-main/folderLocationsMainService.js'; + +class PermissionDeniedFileSystemProvider extends InMemoryFileSystemProvider { + override async stat(resource: URI): Promise { + throw createFileSystemProviderError('denied', FileSystemProviderErrorCode.NoPermissions); + } +} + +suite('FolderLocationsMainService', () => { + + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + async function create(options?: { initial?: Record; provider?: InMemoryFileSystemProvider }) { + const items = new Map(); + if (options?.initial) { + items.set('folderLocations', options.initial); + } + const state = { + getItem: (key: string) => items.get(key) as T | undefined, + setItem: (key: string, data: object | string | number | boolean | undefined | null) => { items.set(key, data); } + }; + + const warnings: string[] = []; + const logService = { warn: (message: string) => { warnings.push(message); } } as unknown as ILogService; + const fileService = ds.add(new FileService(new NullLogService())); + const provider = ds.add(options?.provider ?? new InMemoryFileSystemProvider()); + ds.add(fileService.registerProvider(Schemas.file, provider)); + await provider.mkdir(URI.file('/work')); + await provider.mkdir(URI.file('/work/repo.wt')); + await provider.mkdir(URI.file('/work/repo.wt/feature')); + await provider.writeFile(URI.file('/work/repo.wt/file'), VSBuffer.fromString('').buffer, { create: true, overwrite: true, unlock: false, atomic: false }); + + return { service: new FolderLocationsMainService(state as never, fileService, logService), items, warnings }; + } + + const workspace = URI.file('/work/repo'); + const location = { uri: 'file:///work/repo.wt/feature', label: 'feature', providerId: 'p' }; + + test('a remembered location is returned for a fresh open of its workspace only', async () => { + const { service } = await create(); + service.updateFolderLocation(workspace, location); + + assert.deepStrictEqual([service.getFolderLocation(workspace), service.getFolderLocation(URI.file('/work/repo.wt/feature')), service.getFolderLocation(URI.file('/work/other'))], [location, undefined, undefined]); + }); + + test('returning to the workspace clears the memory', async () => { + const { service } = await create(); + service.updateFolderLocation(workspace, location); + service.updateFolderLocation(workspace, undefined); + + assert.strictEqual(service.getFolderLocation(workspace), undefined); + }); + + test('case variants of the workspace share one entry on case-insensitive paths', async () => { + const { service, items } = await create(); + const variant = URI.file('/Work/Repo'); + const sameEntry = extUriBiasedIgnorePathCase.getComparisonKey(workspace) === extUriBiasedIgnorePathCase.getComparisonKey(variant); + service.updateFolderLocation(workspace, location); + const restored = service.getFolderLocation(variant); + service.updateFolderLocation(variant, undefined); + + assert.deepStrictEqual([restored, service.getFolderLocation(workspace), Object.keys(items.get('folderLocations') as object).length], sameEntry ? [location, undefined, 0] : [undefined, location, 1]); + }); + + test('malformed entries are ignored', async () => { + const { service } = await create({ initial: { [extUriBiasedIgnorePathCase.getComparisonKey(workspace)]: { uri: 1 } } }); + + assert.strictEqual(service.getFolderLocation(workspace), undefined); + }); + + test('a malformed remembered uri is ignored', async () => { + const { service } = await create({ initial: { [extUriBiasedIgnorePathCase.getComparisonKey(workspace)]: { ...location, uri: 'file:////work/alt' } } }); + + assert.strictEqual(service.getFolderLocation(workspace), undefined); + }); + + test('the oldest entries age out', async () => { + const { service } = await create(); + for (let i = 0; i < 105; i++) { + service.updateFolderLocation(URI.file(`/work/repo${i}`), location); + } + + assert.deepStrictEqual([service.getFolderLocation(URI.file('/work/repo0')), service.getFolderLocation(URI.file('/work/repo104'))], [undefined, location]); + }); + + suite('validateFolderLocation', () => { + + async function validate(options: Parameters[0], candidate: typeof location | undefined) { + const { service, warnings } = await create(options); + service.updateFolderLocation(workspace, location); + return { result: await service.validateFolderLocation(workspace, candidate), remembered: service.getFolderLocation(workspace), warnings: warnings.length }; + } + + test('an existing directory is kept and remembered', async () => { + assert.deepStrictEqual(await validate(undefined, location), { result: { folderLocation: location }, remembered: location, warnings: 0 }); + }); + + test('a missing location opens at the workspace, is reported and forgotten', async () => { + assert.deepStrictEqual(await validate(undefined, { ...location, uri: 'file:///work/repo.wt/gone' }), { result: { folderLocationMissing: { label: 'feature' } }, remembered: undefined, warnings: 0 }); + }); + + test('a file is a missing location', async () => { + assert.deepStrictEqual(await validate(undefined, { ...location, uri: 'file:///work/repo.wt/file' }), { result: { folderLocationMissing: { label: 'feature' } }, remembered: undefined, warnings: 0 }); + }); + + test('a remote location is not started at and is forgotten', async () => { + assert.deepStrictEqual(await validate(undefined, { ...location, uri: 'vscode-remote://host/work/repo.wt/feature' }), { result: { folderLocationMissing: { label: 'feature' } }, remembered: undefined, warnings: 0 }); + }); + + test('a malformed location is a missing location', async () => { + assert.deepStrictEqual(await validate(undefined, { ...location, uri: 'file:////work/alt' }), { result: { folderLocationMissing: { label: 'feature' } }, remembered: undefined, warnings: 0 }); + }); + + test('without a candidate nothing is validated or forgotten', async () => { + assert.deepStrictEqual(await validate(undefined, undefined), { result: {}, remembered: location, warnings: 0 }); + }); + + test('a location that cannot be determined is kept, remembered and logged', async () => { + assert.deepStrictEqual(await validate({ provider: new PermissionDeniedFileSystemProvider() }, location), { result: { folderLocation: location }, remembered: location, warnings: 1 }); + }); + + test('open, reload and restore resolve the same remembered location, until it is gone', async () => { + const { service } = await create(); + service.updateFolderLocation(workspace, location); + const resolve = () => service.validateFolderLocation(workspace, service.getFolderLocation(workspace)); + + const starts = [await resolve(), await resolve()]; + service.updateFolderLocation(workspace, { ...location, uri: 'file:///work/repo.wt/gone' }); + const afterDeletion = [await resolve(), await resolve()]; + + assert.deepStrictEqual({ starts, afterDeletion }, { + starts: [{ folderLocation: location }, { folderLocation: location }], + afterDeletion: [{ folderLocationMissing: { label: 'feature' } }, {}] + }); + }); + }); +}); diff --git a/src/vs/platform/windows/test/electron-main/windowImpl.test.ts b/src/vs/platform/windows/test/electron-main/windowImpl.test.ts index ebf1b6bce1ca..0bb33bbd8280 100644 --- a/src/vs/platform/windows/test/electron-main/windowImpl.test.ts +++ b/src/vs/platform/windows/test/electron-main/windowImpl.test.ts @@ -6,17 +6,28 @@ import assert from 'assert'; import type { BrowserWindow, BrowserWindowConstructorOptions, WebContents } from 'electron'; import sinon from 'sinon'; -import { isMacintosh } from '../../../../base/common/platform.js'; +import { isMacintosh, isWindows } from '../../../../base/common/platform.js'; import { upcastPartial } from '../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { IConfigurationService } from '../../../configuration/common/configuration.js'; import { TestConfigurationService } from '../../../configuration/test/common/testConfigurationService.js'; import { IEnvironmentMainService } from '../../../environment/electron-main/environmentMainService.js'; +import { TestInstantiationService } from '../../../instantiation/test/common/instantiationServiceMock.js'; import { NullLogService } from '../../../log/common/log.js'; +import { IProductService } from '../../../product/common/productService.js'; import { InMemoryTestStateMainService } from '../../../test/electron-main/workbenchTestServices.js'; +import { IThemeMainService } from '../../../theme/electron-main/themeMainService.js'; import { DEFAULT_CUSTOM_TITLEBAR_HEIGHT, getMacOSWindowControlsPosition } from '../../../window/common/window.js'; import { IWindowState, WindowMode } from '../../../window/electron-main/window.js'; +import { URI } from '../../../../base/common/uri.js'; +import { NativeParsedArgs } from '../../../environment/common/argv.js'; +import { FocusMode } from '../../../native/common/native.js'; import { release } from 'os'; import { BaseWindow } from '../../electron-main/windowImpl.js'; +import { defaultBrowserWindowOptions, getAuxiliaryWindowRestoreMode, getClaimedAuxiliaryWindowMode, isBackgroundThrottlingAllowed, isHiddenWindowMode } from '../../electron-main/windows.js'; + +const displayBounds = { x: 0, y: 0, width: 1440, height: 900 }; +const workArea = { x: 0, y: 25, width: 1440, height: 875 }; class TestWindow extends BaseWindow { readonly id = 1; @@ -29,11 +40,42 @@ class TestWindow extends BaseWindow { super.applyState(state, hasMultipleDisplays, minimized); } + protected override getDisplayArea(mode: WindowMode.Maximized | WindowMode.Fullscreen) { + return mode === WindowMode.Fullscreen ? displayBounds : workArea; + } + matches(_webContents: WebContents): boolean { return false; } } +suite('Window options - always on top', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createOptions(alwaysOnTop: boolean | undefined, override?: boolean) { + const configurationService = new TestConfigurationService({ window: { titleBarStyle: 'native' } }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IEnvironmentMainService, { appRoot: '', isBuilt: false, args: { _: [] } }); + instantiationService.stub(IProductService, { nameLong: 'Test' }); + instantiationService.stub(IThemeMainService, { getBackgroundColor: () => '#000000' }); + + return instantiationService.invokeFunction(defaultBrowserWindowOptions, { alwaysOnTop }, { alwaysOnTop: override }); + } + + test('restores saved always-on-top state while older state defaults to off', () => { + assert.deepStrictEqual([true, false, undefined].map(value => !!createOptions(value).alwaysOnTop), [true, false, false]); + }); + + test('explicit window options take precedence over restored state', () => { + assert.deepStrictEqual([ + !!createOptions(false, true).alwaysOnTop, + !!createOptions(true, false).alwaysOnTop + ], [true, false]); + }); +}); + suite('BaseWindow - window controls overlay', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -164,3 +206,136 @@ suite('BaseWindow - restoring a window state', () => { }); }); }); + +suite('BaseWindow - hidden window mode', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + teardown(() => sinon.restore()); + + function environment(args: Partial, extensionTests: boolean): IEnvironmentMainService { + return upcastPartial({ + args: { _: [], ...args }, + extensionTestsLocationURI: extensionTests ? URI.file('/tests') : undefined + }); + } + + test('isHiddenWindowMode requires --hidden-window together with --extensionTestsPath', () => { + assert.deepStrictEqual([ + isHiddenWindowMode(environment({}, false)), + isHiddenWindowMode(environment({}, true)), + isHiddenWindowMode(environment({ 'hidden-window': true }, false)), + isHiddenWindowMode(environment({ 'hidden-window': true }, true)), + ], [false, false, false, true]); + }); + + function createWindow(hidden: boolean) { + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + const window = store.add(new TestWindow( + configurationService, + new InMemoryTestStateMainService(), + environment({ 'hidden-window': hidden }, true), + store.add(new NullLogService()) + )); + const on = sinon.stub(); + const removeListener = sinon.stub(); + const maximize = sinon.stub(); + const show = sinon.stub(); + const focus = sinon.stub(); + const focusWebContents = sinon.stub(); + const setBounds = sinon.stub(); + const nativeWindow = upcastPartial({ + on, + removeListener, + setSheetOffset: sinon.stub(), + isMinimized: () => false, + maximize, + show, + focus, + setBounds, + webContents: upcastPartial({ focus: focusWebContents }), + }); + window.setWin(nativeWindow); + return { window, maximize, show, focus, focusWebContents, setBounds }; + } + + for (const hidden of [false, true]) { + test(`applyState ${hidden ? 'sizes to the work area without maximizing or showing' : 'maximizes and shows'} a maximized window (hidden: ${hidden})`, () => { + const { window, maximize, show, setBounds } = createWindow(hidden); + window.applyState({ mode: WindowMode.Maximized }, false); + + assert.deepStrictEqual([maximize.callCount, show.callCount, setBounds.args], hidden ? [0, 0, [[workArea]]] : [1, 1, []]); + }); + + test(`focus ${hidden ? 'is ignored' : 'focuses the window'} (hidden: ${hidden})`, () => { + const { window, focus, focusWebContents } = createWindow(hidden); + window.focus({ mode: FocusMode.Transfer }); + + assert.deepStrictEqual([focus.callCount, focusWebContents.callCount], hidden ? [0, 0] : [1, 1]); + }); + } + + test('applyState sizes a hidden fullscreen window to the display without maximizing, entering fullscreen or showing', () => { + const { window, maximize, show, setBounds } = createWindow(true); + const setFullScreen = sinon.stub(window as unknown as { setFullScreen(fullscreen: boolean, fromRestore: boolean): void }, 'setFullScreen'); + window.applyState({ mode: WindowMode.Fullscreen }, false); + + assert.deepStrictEqual([maximize.callCount, setFullScreen.callCount, show.callCount, setBounds.args], [0, 0, 0, [[displayBounds]]]); + }); + + test('background throttling cannot be re-enabled at runtime when hidden', () => { + assert.deepStrictEqual([ + isBackgroundThrottlingAllowed(environment({}, true), true), + isBackgroundThrottlingAllowed(environment({}, true), false), + isBackgroundThrottlingAllowed(environment({ 'hidden-window': true }, true), true), + isBackgroundThrottlingAllowed(environment({ 'hidden-window': true }, true), false), + ], [true, false, false, false]); + }); + + test('auxiliary windows restore the requested mode, not the visibility', () => { + assert.deepStrictEqual( + [undefined, WindowMode.Normal, WindowMode.Maximized, WindowMode.Fullscreen].map(getAuxiliaryWindowRestoreMode), + [WindowMode.Normal, WindowMode.Normal, WindowMode.Maximized, WindowMode.Maximized] + ); + }); + + test('a claimed auxiliary window uses the requested mode, not the visibility', () => { + assert.deepStrictEqual([ + getClaimedAuxiliaryWindowMode(WindowMode.Normal, { show: false }), + getClaimedAuxiliaryWindowMode(WindowMode.Maximized, { show: false }), + getClaimedAuxiliaryWindowMode(undefined, { show: false }), + getClaimedAuxiliaryWindowMode(undefined, {}), + ], [WindowMode.Normal, WindowMode.Maximized, WindowMode.Maximized, WindowMode.Normal]); + }); + + test('a normal hidden auxiliary window keeps its bounds and is neither maximized nor shown', () => { + const { window, maximize, show } = createWindow(true); + const setBounds = sinon.stub(); + Object.assign(window.win!, { setBounds }); + const bounds = { x: 10, y: 20, width: 800, height: 600 }; + window.applyState({ ...bounds, mode: getAuxiliaryWindowRestoreMode(WindowMode.Normal) }, true); + + assert.deepStrictEqual([setBounds.args, maximize.callCount, show.callCount], [isMacintosh || isWindows ? [[bounds]] : [], 0, 0]); + }); + + for (const hidden of [false, true]) { + test(`toggleFullScreen ${hidden ? 'does not change' : 'changes'} fullscreen (hidden: ${hidden})`, () => { + const { window } = createWindow(hidden); + const setFullScreen = sinon.stub(window as unknown as { setFullScreen(fullscreen: boolean, fromRestore: boolean): void }, 'setFullScreen'); + sinon.stub(window, 'isFullScreen').get(() => false); + window.toggleFullScreen(); + + assert.deepStrictEqual(setFullScreen.args, hidden ? [] : [[true, false]]); + }); + } + + for (const [mode, name] of [[FocusMode.Notify, 'Notify'], [FocusMode.Force, 'Force']] as const) { + test(`focus with mode ${name} touches neither window nor application when hidden`, () => { + const { window, show, focus } = createWindow(true); + const notifyFocus = sinon.spy(window as unknown as { showNotifyFocus(): void }, 'showNotifyFocus'); + window.focus({ mode }); + + assert.deepStrictEqual([notifyFocus.callCount, show.callCount, focus.callCount], [0, 0, 0]); + }); + } +}); diff --git a/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts b/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts index 0f65950da0bc..e0434bcdd267 100644 --- a/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts +++ b/src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts @@ -109,6 +109,14 @@ suite('Windows State Storing', () => { }; assertRestoring(windowState, 'minimized window'); + windowState = { + openedWindows: [ + { backupPath: testBackupPath1, uiState: { ...getUIState(), alwaysOnTop: true }, folderUri: testFolderURI }, + { backupPath: testBackupPath2, uiState: { ...getUIState(), alwaysOnTop: false }, folderUri: testRemoteFolderURI, remoteAuthority: 'bar' } + ] + }; + assertRestoring(windowState, 'independent always-on-top states'); + windowState = { lastActiveWindow: { backupPath: testBackupPath2, uiState: getUIState(), folderUri: testFolderURI }, openedWindows: [] diff --git a/src/vs/platform/workspace/common/folderLocations.ts b/src/vs/platform/workspace/common/folderLocations.ts new file mode 100644 index 000000000000..460f7984ef5d --- /dev/null +++ b/src/vs/platform/workspace/common/folderLocations.ts @@ -0,0 +1,128 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Event } from '../../../base/common/event.js'; +import { IDisposable } from '../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../base/common/themables.js'; +import { URI } from '../../../base/common/uri.js'; +import { createDecorator } from '../../instantiation/common/instantiation.js'; +import { IWorkspaceFolder } from './workspace.js'; + +/** + * An alternate location of a workspace folder. + */ +export interface IFolderLocation { + readonly uri: URI; + readonly label: string; + readonly description?: string; + readonly icon?: ThemeIcon; +} + +/** + * An alternate location together with the provider that resolved it. + */ +export interface IResolvedFolderLocation extends IFolderLocation { + readonly providerId: string; + + /** + * Whether the provider is part of the product. + */ + readonly builtIn: boolean; +} + +/** + * Knows the alternate locations of a workspace folder. + */ +export interface IWorkspaceFolderLocationProvider { + readonly id: string; + + /** + * The alternate locations of the folder whose primary location is `primary`. + */ + provideLocations(primary: URI, token: CancellationToken): Promise; + + /** + * Resolves `location` if it is an alternate location of the folder whose + * primary location is `primary`, as this provider knows it. + */ + resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise; +} + +/** + * Why the location of the workspace folder changed: `user` when the user picked it, + * `programmatic` for any other change. + */ +export type FolderLocationChangeReason = 'user' | 'programmatic'; + +export interface IFolderLocationChangeEvent { + + /** + * The workspace folder whose location changed, as it is after the change. + */ + readonly folder: IWorkspaceFolder; + + readonly reason: FolderLocationChangeReason; +} + +export const IWorkspaceFolderLocationService = createDecorator('workspaceFolderLocationService'); + +export interface IWorkspaceFolderLocationService { + readonly _serviceBrand: undefined; + + /** + * The alternate location `folder` is currently at, or `undefined` while it is at its own location + * or when its workspace does not support alternate locations. + */ + getLocation(folder: IWorkspaceFolder): IResolvedFolderLocation | undefined; + + /** + * Whether `folder` is opened at an alternate location. The service decides which workspaces support it. + */ + isAtAlternateLocation(folder: IWorkspaceFolder): boolean; + + /** + * Whether the location of `folder` can be set with `IWorkspaceEditingService.setFolderLocation`. + * This is the case for the folder of a local single-folder workspace. + */ + canSetLocation(folder: IWorkspaceFolder): boolean; + + /** + * Fires when the answer of `canSetLocation` may have changed, that is when the folders + * or the kind of the workspace change. + */ + readonly onDidChangeCanSetLocation: Event; + + /** + * Fires when the location of a folder changes. + */ + readonly onDidChangeLocation: Event; + + /** + * Fires when a provider is registered or unregistered. + */ + readonly onDidChangeProviders: Event; + + /** + * Records the location `folder` is at. Called by `IWorkspaceEditingService` + * and when restoring a location; do not use it to switch locations. + */ + setLocation(folder: IWorkspaceFolder, location: IResolvedFolderLocation | undefined, reason?: FolderLocationChangeReason): void; + + /** + * Registers a provider. Locations of `builtIn` providers inherit the trust of the primary location. + */ + registerProvider(provider: IWorkspaceFolderLocationProvider, options?: { readonly builtIn?: boolean }): IDisposable; + + /** + * The alternate locations of all providers for the folder at `primary`, without duplicates. + */ + getLocations(primary: URI, token: CancellationToken): Promise; + + /** + * Resolves `location` through the providers, or returns `undefined` if no provider knows it. + */ + resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise; +} diff --git a/src/vs/server/node/agentHostChannel.ts b/src/vs/server/node/agentHostChannel.ts index d31250427100..a7d21f06bf5a 100644 --- a/src/vs/server/node/agentHostChannel.ts +++ b/src/vs/server/node/agentHostChannel.ts @@ -17,6 +17,7 @@ import { Disposable, IDisposable } from '../../base/common/lifecycle.js'; import { connectionTokenQueryName } from '../../base/common/network.js'; import { isObject } from '../../base/common/types.js'; import { IPCServer, IServerChannel } from '../../base/parts/ipc/common/ipc.js'; +import { isRemoteAgentHostLocationPreference } from '../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; import type { IAgentHostIpcConnectionOptions } from '../../platform/agentHost/common/agentService.js'; import { ILogService } from '../../platform/log/common/log.js'; import type * as wsTypes from 'ws'; @@ -41,7 +42,8 @@ export type AgentHostUpstreamEndpointResolver = (options?: IAgentHostIpcConnecti function isConnectionOptions(value: unknown): value is IAgentHostIpcConnectionOptions { return isObject(value) && (!('env' in value) || isEnvironment(value.env)) - && (!('debugEnv' in value) || isEnvironment(value.debugEnv)); + && (!('debugEnv' in value) || isEnvironment(value.debugEnv)) + && (!('preferredAgentLocation' in value) || value.preferredAgentLocation === undefined || isRemoteAgentHostLocationPreference(value.preferredAgentLocation)); } function isEnvironment(value: unknown): value is IAgentHostIpcConnectionOptions['env'] { @@ -345,7 +347,7 @@ export class AgentHostChannel extends Disposable implements IServerCha switch (command) { case 'connect': if (arg !== undefined && !isConnectionOptions(arg)) { - throw new Error('Invalid agent host connection environment: expected string or null values'); + throw new Error('Invalid agent host connection options'); } this._logService.info(`[AgentHostChannel] Renderer ctx=${String(ctx)} requested connect to upstream`); await conn.connect(arg); diff --git a/src/vs/server/node/remoteExtensionHostAgentServer.ts b/src/vs/server/node/remoteExtensionHostAgentServer.ts index 72273fb3e8da..9bf5d40d28a3 100644 --- a/src/vs/server/node/remoteExtensionHostAgentServer.ts +++ b/src/vs/server/node/remoteExtensionHostAgentServer.ts @@ -54,12 +54,12 @@ function parseRequestUrl(requestUrl: string): URL | undefined { declare namespace vsda { // the signer is a native module that for historical reasons uses a lower case class name - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line local/code-class-name-pascal-case export class signer { sign(arg: string): string; } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line local/code-class-name-pascal-case export class validator { createNewMessage(arg: string): string; validate(arg: string): 'ok' | 'error'; @@ -609,7 +609,7 @@ export interface IServerAPI { dispose(): void; } -export async function createServer(address: string | net.AddressInfo | null, args: ServerParsedArgs, REMOTE_DATA_FOLDER: string, agentHostBridgeConnectionToken: string | undefined): Promise { +export async function createServer(address: string | net.AddressInfo | null, args: ServerParsedArgs, REMOTE_DATA_FOLDER: string): Promise { const connectionToken = await determineServerConnectionToken(args); if (connectionToken instanceof ServerConnectionTokenParseError) { @@ -650,7 +650,7 @@ export async function createServer(address: string | net.AddressInfo | null, arg }); const disposables = new DisposableStore(); - const { socketServer, instantiationService } = await setupServerServices(connectionToken, args, REMOTE_DATA_FOLDER, agentHostBridgeConnectionToken, disposables); + const { socketServer, instantiationService } = await setupServerServices(connectionToken, args, REMOTE_DATA_FOLDER, disposables); // Set the unexpected error handler after the services have been initialized, to avoid having // the telemetry service overwrite our handler diff --git a/src/vs/server/node/server.main.ts b/src/vs/server/node/server.main.ts index b8e08843caff..2aad9cf01432 100644 --- a/src/vs/server/node/server.main.ts +++ b/src/vs/server/node/server.main.ts @@ -12,7 +12,7 @@ import { createServer as doCreateServer, IServerAPI } from './remoteExtensionHos import { parseArgs, ErrorReporter } from '../../platform/environment/node/argv.js'; import { join, dirname } from '../../base/common/path.js'; import { performance } from 'perf_hooks'; -import { agentHostBridgeConnectionTokenEnvironmentVariable, serverOptions } from './serverEnvironmentService.js'; +import { serverOptions } from './serverEnvironmentService.js'; import product from '../../platform/product/common/product.js'; import * as perf from '../../base/common/performance.js'; @@ -35,8 +35,8 @@ const errorReporter: ErrorReporter = { }; const args = parseArgs(process.argv.slice(2), serverOptions, errorReporter); -const agentHostBridgeConnectionToken = process.env[agentHostBridgeConnectionTokenEnvironmentVariable]; -delete process.env[agentHostBridgeConnectionTokenEnvironmentVariable]; +// CLIs set this for servers that predate agent host discovery through the endpoint registry; keep it from child processes. +delete process.env['VSCODE_AGENT_HOST_BRIDGE_CONNECTION_TOKEN']; const REMOTE_DATA_FOLDER = args['server-data-dir'] || process.env['VSCODE_AGENT_FOLDER'] || join(os.homedir(), product.serverDataFolderName || '.vscode-remote'); const USER_DATA_PATH = args['user-data-dir'] || join(REMOTE_DATA_FOLDER, 'data'); @@ -69,5 +69,5 @@ export function spawnCli() { * invoked by server-main.js */ export function createServer(address: string | net.AddressInfo | null): Promise { - return doCreateServer(address, args, REMOTE_DATA_FOLDER, agentHostBridgeConnectionToken); + return doCreateServer(address, args, REMOTE_DATA_FOLDER); } diff --git a/src/vs/server/node/serverAgentHostManager.ts b/src/vs/server/node/serverAgentHostManager.ts index c169ba5827f4..820ccbfd8434 100644 --- a/src/vs/server/node/serverAgentHostManager.ts +++ b/src/vs/server/node/serverAgentHostManager.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { realpath } from 'fs/promises'; import { raceTimeout } from '../../base/common/async.js'; import { Event } from '../../base/common/event.js'; import { isObject, isStringArray } from '../../base/common/types.js'; @@ -13,6 +14,7 @@ import { reportAgentHostProcessError } from '../../platform/agentHost/common/age import type { IAgentHostProcessExitEvent } from '../../platform/agentHost/common/agentHostProcessExit.js'; import { AgentHostLaunchKind } from '../../platform/agentHost/common/agentHostTelemetry.js'; import { AgentHostIpcChannels, IAgentService, IAgentHostManagementService, IMissionControlOptions } from '../../platform/agentHost/common/agentService.js'; +import { reviveConnectionDiagnosticError } from '../../platform/agentHost/common/connectionDiagnostics.js'; import { createDecorator } from '../../platform/instantiation/common/instantiation.js'; import { ILogService, ILoggerService } from '../../platform/log/common/log.js'; import { RemoteLoggerChannelClient } from '../../platform/log/common/logIpc.js'; @@ -40,17 +42,22 @@ export interface IServerAgentHostManager { export interface IServerAgentHostManagerOptions { readonly startMode?: 'eager' | 'lazy'; - readonly githubEnvironment?: IMissionControlOptions; + readonly githubEnvironment?: IServerGithubEnvironmentOptions; readonly onGithubEnvironmentReady?: (environmentId: string) => void; readonly onRestartLimitReached?: () => void; } +interface IServerGithubEnvironmentOptions extends IMissionControlOptions { + /** Automatically discovered grants that may be omitted when unavailable. */ + readonly optionalRoots?: readonly string[]; +} + function isRecord(value: unknown): value is Record { return isObject(value); } /** Consumes the CLI's trusted bootstrap credential before spawning child processes. */ -export function readGithubEnvironmentOptions(env: NodeJS.ProcessEnv): IMissionControlOptions | undefined { +export function readGithubEnvironmentOptions(env: NodeJS.ProcessEnv): IServerGithubEnvironmentOptions | undefined { const value = env.VSCODE_CLI_GITHUB_ENVIRONMENT_OPTIONS; delete env.VSCODE_CLI_GITHUB_ENVIRONMENT_OPTIONS; if (value === undefined) { @@ -69,18 +76,31 @@ export function readGithubEnvironmentOptions(env: NodeJS.ProcessEnv): IMissionCo throw new Error('Invalid GitHub environment bootstrap options'); } const name = options.name; + const projects = options.projects; + const defaultDirectory = options.defaultDirectory; + const roots = options.roots; + const optionalRoots = options.optionalRoots; if (options.baseUrl !== 'https://api.github.com' || options.live !== true || typeof options.accountId !== 'string' || !/^\d+$/.test(options.accountId) || typeof options.credential !== 'string' || !options.credential.trim() - || !isStringArray(options.roots) || options.roots.length === 0 || options.roots.some(root => !root) + || !isStringArray(roots) || roots.length === 0 || roots.some(root => !root) + || (optionalRoots !== undefined && (!isStringArray(optionalRoots) || optionalRoots.some(root => !root))) + || (projects !== undefined && (!isStringArray(projects) || projects.some(project => !project))) + || (defaultDirectory !== undefined && (typeof defaultDirectory !== 'string' || !defaultDirectory)) || (name !== undefined && (typeof name !== 'string' || !name.trim()))) { throw new Error('Invalid GitHub environment bootstrap options'); } + if (optionalRoots?.some(root => !roots.includes(root) || projects?.includes(root) || root === defaultDirectory)) { + throw new Error('Invalid optional GitHub environment roots'); + } return { baseUrl: options.baseUrl, accountId: options.accountId, credential: options.credential, - roots: options.roots, + roots, + ...(optionalRoots !== undefined ? { optionalRoots } : {}), + ...(projects !== undefined ? { projects } : {}), + ...(defaultDirectory !== undefined ? { defaultDirectory } : {}), name, live: true, }; @@ -93,6 +113,7 @@ export function readGithubEnvironmentOptions(env: NodeJS.ProcessEnv): IMissionCo */ interface IConnectionTrackerService { readonly onDidChangeConnectionCount: Event; + readonly onDidChangeGitHubEnvironmentRegistered: Event; waitForConfiguredWebSocketServer(): Promise; } @@ -111,11 +132,12 @@ export class ServerAgentHostManager extends Disposable implements IServerAgentHo private readonly _connectionStore = this._register(new MutableDisposable()); private readonly _startMode: 'eager' | 'lazy'; - /** Lifetime token held while sessions are active or standalone WebSocket clients are connected. */ + /** Lifetime token held while sessions are active, standalone WebSocket clients are connected, or a client registered a GitHub environment. */ private readonly _lifetimeToken = this._register(new MutableDisposable()); private _hasActiveSessions = false; private _connectionCount = 0; + private _githubEnvironmentRegistered = false; constructor( private readonly _starter: IAgentHostStarter, @@ -209,7 +231,10 @@ export class ServerAgentHostManager extends Disposable implements IServerAgentHo await this._trackClientConnections(connection); if (this._options.githubEnvironment) { const management = ProxyChannel.toService(connection.client.getChannel(AgentHostIpcChannels.Management)); - await management.configureMissionControl(this._options.githubEnvironment); + const result = await management.configureMissionControl(await this._getGithubEnvironmentOptions(this._options.githubEnvironment)); + if (result) { + throw reviveConnectionDiagnosticError(result.error); + } const environmentId = await management.getMissionControlEnvironmentId(); if (!environmentId) { throw new Error('GitHub environment registration did not return an environment ID'); @@ -240,6 +265,23 @@ export class ServerAgentHostManager extends Disposable implements IServerAgentHo this._connectionStore.value = connection.store; } + private async _getGithubEnvironmentOptions(options: IServerGithubEnvironmentOptions): Promise { + const { optionalRoots, ...configuration } = options; + const roots: string[] = []; + for (const root of configuration.roots) { + if (optionalRoots?.includes(root)) { + try { + await realpath(root); + } catch (error) { + this._logService.warn('ServerAgentHostManager: skipping unavailable automatic GitHub environment root', root, error); + continue; + } + } + roots.push(root); + } + return { ...configuration, roots }; + } + private _handleUnexpectedExit(connection: IAgentHostConnection, e: IAgentHostProcessExitEvent): void { if (this._store.isDisposed || this._connection !== connection) { return; @@ -247,6 +289,7 @@ export class ServerAgentHostManager extends Disposable implements IServerAgentHo this._hasActiveSessions = false; this._connectionCount = 0; + this._githubEnvironmentRegistered = false; this._lifetimeToken.clear(); const willRestart = this._restartCount < Constants.MaxRestarts; @@ -322,11 +365,15 @@ export class ServerAgentHostManager extends Disposable implements IServerAgentHo this._connectionCount = count; this._updateLifetimeToken(); })); + connection.store.add(connectionTracker.onDidChangeGitHubEnvironmentRegistered(registered => { + this._githubEnvironmentRegistered = registered; + this._updateLifetimeToken(); + })); await connectionTracker.waitForConfiguredWebSocketServer(); } private _updateLifetimeToken(): void { - if (this._hasActiveSessions || this._connectionCount > 0) { + if (this._hasActiveSessions || this._connectionCount > 0 || this._githubEnvironmentRegistered) { this._lifetimeToken.value ??= this._serverLifetimeService.active('AgentHost'); } else { this._lifetimeToken.clear(); diff --git a/src/vs/server/node/serverEnvironmentService.ts b/src/vs/server/node/serverEnvironmentService.ts index 935468360027..2bad55ed7a3c 100644 --- a/src/vs/server/node/serverEnvironmentService.ts +++ b/src/vs/server/node/serverEnvironmentService.ts @@ -15,8 +15,6 @@ import { joinPath } from '../../base/common/resources.js'; import { join } from '../../base/common/path.js'; import { ProtocolConstants } from '../../base/parts/ipc/common/ipc.net.js'; -export const agentHostBridgeConnectionTokenEnvironmentVariable = 'VSCODE_AGENT_HOST_BRIDGE_CONNECTION_TOKEN'; - /** * Returns server arguments with connection tokens redacted for logging. */ @@ -103,10 +101,11 @@ export const serverOptions: OptionDescriptions> = { 'agent-host-port': { type: 'string', cat: 'o', args: 'port', description: nls.localize('agent-host-port', "The port the agent host WebSocket server should listen on.") }, 'agent-host-path': { type: 'string', cat: 'o', args: 'path', description: nls.localize('agent-host-path', "The path to a socket file for the agent host WebSocket server to listen on.") }, - 'agent-host-bridge-port': { type: 'string', cat: 'o', args: 'port', description: nls.localize('agent-host-bridge-port', "Bridge renderer agent-host traffic to an already-running agent host listening on this port. Does not spawn an agent host.") }, - 'agent-host-bridge-path': { type: 'string', cat: 'o', args: 'path', description: nls.localize('agent-host-bridge-path', "Bridge renderer agent-host traffic to an already-running agent host listening on this socket path. Does not spawn an agent host.") }, - 'agent-host-bridge-host': { type: 'string', cat: 'o', args: 'host', description: nls.localize('agent-host-bridge-host', "Host the externally-running agent host is reachable at when used with --agent-host-bridge-port. Defaults to localhost.") }, - 'agent-host-bridge-connection-token': { type: 'string', cat: 'o', args: 'token', description: nls.localize('agent-host-bridge-connection-token', "Connection token required by the externally-running agent host when used with --agent-host-bridge-port.") }, + // Ignored: CLIs pass these for servers that predate agent host discovery through the endpoint registry. + 'agent-host-bridge-port': { type: 'string' }, + 'agent-host-bridge-path': { type: 'string' }, + 'agent-host-bridge-host': { type: 'string' }, + 'agent-host-bridge-connection-token': { type: 'string' }, 'use-host-proxy': { type: 'boolean' }, 'without-browser-env-var': { type: 'boolean' }, diff --git a/src/vs/server/node/serverServices.ts b/src/vs/server/node/serverServices.ts index ed077663ba1a..d5b264cfb8f9 100644 --- a/src/vs/server/node/serverServices.ts +++ b/src/vs/server/node/serverServices.ts @@ -3,7 +3,6 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import * as fs from 'fs'; import { hostname, release } from 'os'; import { Emitter, Event } from '../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../base/common/lifecycle.js'; @@ -13,15 +12,16 @@ import { IURITransformer } from '../../base/common/uriIpc.js'; import { generateUuid } from '../../base/common/uuid.js'; import { getMachineId, getSqmMachineId, getDevDeviceId } from '../../base/node/id.js'; import { Promises } from '../../base/node/pfs.js'; +import { findFreePortFaster } from '../../base/node/ports.js'; import { ClientConnectionEvent, IMessagePassingProtocol, IPCServer, StaticRouter } from '../../base/parts/ipc/common/ipc.js'; import { ProtocolConstants } from '../../base/parts/ipc/common/ipc.net.js'; -import { createRandomIPCHandle } from '../../base/parts/ipc/node/ipc.net.js'; import { IConfigurationService } from '../../platform/configuration/common/configuration.js'; import { ConfigurationService } from '../../platform/configuration/common/configurationService.js'; import { ExtensionHostDebugBroadcastChannel } from '../../platform/debug/common/extensionHostDebugIpc.js'; import { IDownloadService } from '../../platform/download/common/download.js'; import { DownloadServiceChannelClient } from '../../platform/download/common/downloadIpc.js'; import { IEnvironmentService, INativeEnvironmentService } from '../../platform/environment/common/environment.js'; +import { getUserDataPath } from '../../platform/environment/node/userDataPath.js'; import { ExtensionGalleryServiceWithNoStorageService } from '../../platform/extensionManagement/common/extensionGalleryService.js'; import { IAllowedExtensionsService, IExtensionGalleryService } from '../../platform/extensionManagement/common/extensionManagement.js'; import { ExtensionSignatureVerificationService, IExtensionSignatureVerificationService } from '../../platform/extensionManagement/node/extensionSignatureVerificationService.js'; @@ -81,6 +81,8 @@ import { RemoteExtensionsScannerChannelName } from '../../platform/remote/common import { RemoteUserDataProfilesServiceChannel } from '../../platform/userDataProfile/common/userDataProfileIpc.js'; import { NodePtyHostStarter } from '../../platform/terminal/node/nodePtyHostStarter.js'; import { NodeAgentHostStarter } from '../../platform/agentHost/node/nodeAgentHostStarter.js'; +import { readLocalAgentHostEndpoint } from '../../platform/agentHost/node/localAgentHostMetadata.js'; +import { formatAgentHostUrlHost } from '../../platform/agentHost/node/sshRemoteAgentHostHelpers.js'; import '../../platform/agentHost/common/agentHostStarter.config.contribution.js'; import { readGithubEnvironmentOptions, ServerAgentHostManager } from './serverAgentHostManager.js'; import { AgentHostChannel, UnavailableAgentHostChannel } from './agentHostChannel.js'; @@ -110,7 +112,7 @@ import { SandboxHelperService } from '../../platform/sandbox/node/sandboxHelper. const eventPrefix = 'monacoworkbench'; -export async function setupServerServices(connectionToken: ServerConnectionToken, args: ServerParsedArgs, REMOTE_DATA_FOLDER: string, agentHostBridgeConnectionToken: string | undefined, disposables: DisposableStore) { +export async function setupServerServices(connectionToken: ServerConnectionToken, args: ServerParsedArgs, REMOTE_DATA_FOLDER: string, disposables: DisposableStore) { const githubEnvironment = readGithubEnvironmentOptions(process.env); if (githubEnvironment && !(args['agent-host-port'] || args['agent-host-path'])) { throw new Error('GitHub environment hosting requires an explicitly spawned agent host'); @@ -250,25 +252,7 @@ export async function setupServerServices(connectionToken: ServerConnectionToken }, process.exit); services.set(IServerLifetimeService, serverLifetimeService); - // ---- Agent host wiring ------------------------------------------------- - // - // Three independent configurations: - // - // 1. SPAWN: when `--agent-host-port` / `--agent-host-path` is set, this - // server spawns and owns an agent host child process, then bridges - // renderers to its configured endpoint. - // 2. BRIDGE: when `--agent-host-bridge-*` is set without spawn flags, - // register the `agentHostProxy` IPC channel so renderers can - // reach the agent host over the remote-agent connection. The upstream - // is one specified via `--agent-host-bridge-port` / - // `--agent-host-bridge-path` (e.g. when a CLI sidecar manages the - // agent host lifecycle). - // 3. DEFAULT: without either set of flags, lazily start a local agent host - // on a fresh socket when the first renderer connects. - // Resolver environment overrides are retained for this launch and crash recovery. - // - // The explicit configurations are deliberately separable so that scenarios - // with an externally-managed agent host don't accidentally fork a duplicate. + // Explicit endpoints are spawned; otherwise discover a shared host or lazily start a shareable TCP host. const spawnPort = args['agent-host-port']; const spawnPath = args['agent-host-path']; @@ -299,77 +283,35 @@ export async function setupServerServices(connectionToken: ServerConnectionToken await agentHostManager.ensureStarted(); } - // The bridge upstream defaults to the agent host this server just - // spawned, but ONLY when that endpoint is dialable at configuration - // time — i.e. an explicit non-zero port or a socket path. When - // `--agent-host-port=0` is used the OS picks a port at runtime that - // this server has no way of learning, so we refuse to register a - // bridge against a placeholder `0`; in that case the caller (the CLI - // `code tunnel` flow) is expected to capture the bound port from the - // AH's readiness line and pass it back as `--agent-host-bridge-port` - // on the renderer-serving servers. Explicit `--agent-host-bridge-*` - // always wins over the spawn fallback. + // A runtime-assigned port is not known here, so only bridge dialable spawn endpoints. const spawnPortNumber = spawnPort ? parseInt(spawnPort, 10) : NaN; const hasUsableSpawnPort = Number.isFinite(spawnPortNumber) && spawnPortNumber > 0; - const bridgePort = args['agent-host-bridge-port'] ?? (hasUsableSpawnPort ? spawnPort : undefined); - const bridgePath = args['agent-host-bridge-path'] ?? spawnPath; - const bridgeHost = args['agent-host-bridge-host'] ?? args.host ?? 'localhost'; - const bridgeToken = args['agent-host-bridge-connection-token'] - ?? agentHostBridgeConnectionToken - ?? ((bridgePort || bridgePath) && connectionToken.type === ServerConnectionTokenType.Mandatory - ? connectionToken.value - : undefined); - if (bridgePort || bridgePath) { + const bridgePort = hasUsableSpawnPort ? spawnPort : undefined; + const bridgeHost = args.host ?? 'localhost'; + if (bridgePort || spawnPath) { const agentHostBridge = disposables.add(new AgentHostChannel( socketServer, { host: bridgeHost, port: bridgePort, - socketPath: bridgePath, - connectionToken: bridgeToken, + socketPath: spawnPath, + connectionToken: connectionToken.type === ServerConnectionTokenType.Mandatory ? connectionToken.value : undefined, }, logService, )); socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, agentHostBridge); - logService.info(`[AgentHostChannel] Registered IPC channel '${AgentHostIpcChannels.RemoteProxy}' (upstream: ${bridgePath ?? `${bridgeHost}:${bridgePort}`})`); + logService.info(`[AgentHostChannel] Registered IPC channel '${AgentHostIpcChannels.RemoteProxy}' (upstream: ${spawnPath ?? `${bridgeHost}:${bridgePort}`})`); } else { socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, new UnavailableAgentHostChannel()); - logService.info(`[AgentHostChannel] Registered unavailable IPC channel '${AgentHostIpcChannels.RemoteProxy}': no --agent-host-bridge-port / --agent-host-bridge-path set.`); - } - } else if (args['agent-host-bridge-port'] || args['agent-host-bridge-path'] || args['agent-host-bridge-host'] || args['agent-host-bridge-connection-token'] || agentHostBridgeConnectionToken) { - const bridgePort = args['agent-host-bridge-port']; - const bridgePath = args['agent-host-bridge-path']; - const bridgeHost = args['agent-host-bridge-host'] ?? args.host ?? 'localhost'; - const bridgeToken = args['agent-host-bridge-connection-token'] ?? agentHostBridgeConnectionToken; - if (bridgePort || bridgePath) { - const agentHostBridge = disposables.add(new AgentHostChannel( - socketServer, - { - host: bridgeHost, - port: bridgePort, - socketPath: bridgePath, - connectionToken: bridgeToken, - }, - logService, - )); - socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, agentHostBridge); - logService.info(`[AgentHostChannel] Registered IPC channel '${AgentHostIpcChannels.RemoteProxy}' (upstream: ${bridgePath ?? `${bridgeHost}:${bridgePort}`})`); - } else { - socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, new UnavailableAgentHostChannel()); - logService.info(`[AgentHostChannel] Registered unavailable IPC channel '${AgentHostIpcChannels.RemoteProxy}': no --agent-host-bridge-port / --agent-host-bridge-path set.`); + logService.info(`[AgentHostChannel] Registered unavailable IPC channel '${AgentHostIpcChannels.RemoteProxy}': no dialable spawned endpoint.`); } } else { try { - const socketPath = createRandomIPCHandle(); + const registryUserDataPath = getUserDataPath({ _: [] }, productService.nameShort); + const host = '127.0.0.1'; const connectionToken = generateUuid(); - disposables.add(toDisposable(() => { - if (process.platform !== 'win32') { - void fs.promises.unlink(socketPath).catch(() => undefined); - } - })); - + let ownPort: Promise | undefined; const agentHostStarter = instantiationService.createInstance(NodeAgentHostStarter); - agentHostStarter.setWebSocketConfig({ socketPath, connectionToken }); const agentHostManager = disposables.add(instantiationService.createInstance( ServerAgentHostManager, agentHostStarter, @@ -378,16 +320,38 @@ export async function setupServerServices(connectionToken: ServerConnectionToken const agentHostBridge = disposables.add(new AgentHostChannel( socketServer, async options => { + const sharedEndpoint = await readLocalAgentHostEndpoint(registryUserDataPath, productService.quality, options?.preferredAgentLocation, logService).catch(error => { + logService.warn('[AgentHostChannel] Failed to read the agent host endpoint registry; starting our own agent host', error); + return undefined; + }); + if (sharedEndpoint) { + if (options?.env || options?.debugEnv) { + logService.trace('[AgentHostChannel] Ignoring renderer environment overrides for a shared agent host'); + } + return sharedEndpoint.endpoint.type === 'tcp' + ? { host: formatAgentHostUrlHost(sharedEndpoint.endpoint.host), port: String(sharedEndpoint.endpoint.port), connectionToken: sharedEndpoint.connectionToken } + : { socketPath: sharedEndpoint.endpoint.path, connectionToken: sharedEndpoint.connectionToken }; + } + ownPort ??= findFreePortFaster(10000 + Math.floor(Math.random() * 50000), 100, 5000, host).then(freePort => { + if (!freePort) { + ownPort = undefined; + throw new Error('No free port available for the agent host'); + } + const port = String(freePort); + agentHostStarter.setWebSocketConfig({ host, port, connectionToken, registryUserDataPath }); + return port; + }); + const port = await ownPort; if (options?.env || options?.debugEnv) { agentHostStarter.setEnvironment(options.env ?? {}, options.debugEnv); } await agentHostManager.ensureStarted(); - return { socketPath, connectionToken }; + return { host, port, connectionToken }; }, logService, )); socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, agentHostBridge); - logService.info(`[AgentHostChannel] Registered lazy IPC channel '${AgentHostIpcChannels.RemoteProxy}' (upstream: ${socketPath})`); + logService.info(`[AgentHostChannel] Registered lazy IPC channel '${AgentHostIpcChannels.RemoteProxy}' with shared endpoint discovery`); } catch (error) { socketServer.registerChannel(AgentHostIpcChannels.RemoteProxy, new UnavailableAgentHostChannel()); logService.error(`[AgentHostChannel] Failed to register IPC channel '${AgentHostIpcChannels.RemoteProxy}'`, error); diff --git a/src/vs/server/node/webClientServer.ts b/src/vs/server/node/webClientServer.ts index ebbfe1c59476..d7e01303c1d9 100644 --- a/src/vs/server/node/webClientServer.ts +++ b/src/vs/server/node/webClientServer.ts @@ -111,6 +111,7 @@ export async function serveFile(filePath: string, cacheControl: CacheControl, lo const APP_ROOT = dirname(FileAccess.asFileUri('').fsPath); const STATIC_PATH = `/static`; +const MANIFEST_PATH = `/resources/server/manifest.json`; const CALLBACK_PATH = `/callback`; const WEB_EXTENSION_PATH = `/web-extension-resource`; const webWorkerExtensionHostIframeScriptSHA = 'sha256-daEgfo2VIXpx2Np71KqCCbkeQwv+68vPrx54XRcbdcs='; @@ -157,6 +158,10 @@ export function createWorkbenchContentSecurityPolicy(scriptNonce: string, nlsBas ].join(' '); } +interface IWebManifest { + start_url: string; +} + export class WebClientServer { private readonly _webExtensionResourceUrlTemplate: URI | undefined; @@ -183,6 +188,9 @@ export class WebClientServer { */ async handle(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: URL, pathname: string): Promise { try { + if (pathname === `${STATIC_PATH}${MANIFEST_PATH}`) { + return await this._handleManifest(req, res); + } if (pathname.startsWith(STATIC_PATH) && pathname.charCodeAt(STATIC_PATH.length) === CharCode.Slash) { return this._handleStatic(req, res, pathname.substring(STATIC_PATH.length)); } @@ -206,6 +214,28 @@ export class WebClientServer { return serveError(req, res, 500, 'Internal Server Error.'); } } + + private async _handleManifest(req: http.IncomingMessage, res: http.ServerResponse): Promise { + const filePath = join(APP_ROOT, MANIFEST_PATH); + let manifest: IWebManifest; + try { + manifest = JSON.parse((await promises.readFile(filePath)).toString()); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return serveError(req, res, 404, 'Not found'); + } + throw error; + } + + manifest.start_url = posix.join(this._getEffectiveBasePath(req), '/'); + res.writeHead(200, { + 'Cache-Control': 'no-store', + 'Content-Type': 'application/json', + 'Vary': 'X-Forwarded-Prefix' + }); + return void res.end(JSON.stringify(manifest)); + } + /** * Handle HTTP requests for /static/* * @param resourcePath The path after /static/ @@ -300,15 +330,8 @@ export class WebClientServer { * Handle HTTP requests for / */ private async _handleRoot(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: URL): Promise { - - const getFirstHeader = (headerName: string) => { - const val = req.headers[headerName]; - return Array.isArray(val) ? val[0] : val; - }; - // Prefix routes with basePath for clients - const forwardedPrefix = getFirstHeader('x-forwarded-prefix'); - const basePath = forwardedPrefix && isSafeBasePath(forwardedPrefix) ? forwardedPrefix : this._basePath; + const basePath = this._getEffectiveBasePath(req); const queryConnectionTokens = parsedUrl.searchParams.getAll(connectionTokenQueryName); if (queryConnectionTokens.length === 1) { @@ -348,12 +371,12 @@ export class WebClientServer { let remoteAuthority = ( useTestResolver ? 'test+test' - : (getFirstHeader('x-original-host') || getFirstHeader('x-forwarded-host') || req.headers.host) + : (this._getFirstHeader(req, 'x-original-host') || this._getFirstHeader(req, 'x-forwarded-host') || req.headers.host) ); if (!remoteAuthority) { return serveError(req, res, 400, `Bad request.`); } - const forwardedPort = getFirstHeader('x-forwarded-port'); + const forwardedPort = this._getFirstHeader(req, 'x-forwarded-port'); if (forwardedPort) { remoteAuthority = replacePort(remoteAuthority, forwardedPort); } @@ -371,7 +394,7 @@ export class WebClientServer { if (this._logService.getLevel() === LogLevel.Trace) { ['x-original-host', 'x-forwarded-host', 'x-forwarded-port', 'host'].forEach(header => { - const value = getFirstHeader(header); + const value = this._getFirstHeader(req, header); if (value) { this._logService.trace(`[WebClientServer] ${header}: ${value}`); } @@ -500,6 +523,19 @@ export class WebClientServer { return void res.end(data); } + private _getEffectiveBasePath(req: http.IncomingMessage): string { + const forwardedPrefix = this._getFirstHeader(req, 'x-forwarded-prefix'); + if (forwardedPrefix && isSafeBasePath(forwardedPrefix)) { + return forwardedPrefix; + } + return this._basePath; + } + + private _getFirstHeader(req: http.IncomingMessage, headerName: string): string | undefined { + const value = req.headers[headerName]; + return Array.isArray(value) ? value[0] : value; + } + private _getScriptCspHashes(content: string): string[] { // Compute the CSP hashes for line scripts. Uses regex // which means it isn't 100% good. diff --git a/src/vs/server/test/node/agentHostChannel.test.ts b/src/vs/server/test/node/agentHostChannel.test.ts index fa5cb7835a09..71aad03358f4 100644 --- a/src/vs/server/test/node/agentHostChannel.test.ts +++ b/src/vs/server/test/node/agentHostChannel.test.ts @@ -177,15 +177,16 @@ suite('AgentHostChannel', () => { await channel.call('first', 'connect', { env: { GITHUB_TOKEN: 'codespace-token', GH_TOKEN: null, EMPTY: '' }, debugEnv: { Github_Token: 'debug-token' }, + preferredAgentLocation: 'editor', }); - await channel.call('second', 'connect', { env: { GITHUB_TOKEN: 'refreshed-codespace-token' } }); + await channel.call('second', 'connect', { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated' }); await channel.call('third', 'connect'); assert.deepStrictEqual({ beforeConnect, options }, { beforeConnect: 0, options: [ - { env: { GITHUB_TOKEN: 'codespace-token', GH_TOKEN: null, EMPTY: '' }, debugEnv: { Github_Token: 'debug-token' } }, - { env: { GITHUB_TOKEN: 'refreshed-codespace-token' } }, + { env: { GITHUB_TOKEN: 'codespace-token', GH_TOKEN: null, EMPTY: '' }, debugEnv: { Github_Token: 'debug-token' }, preferredAgentLocation: 'editor' }, + { env: { GITHUB_TOKEN: 'refreshed-codespace-token' }, preferredAgentLocation: 'dedicated' }, undefined, ], }); @@ -198,7 +199,7 @@ suite('AgentHostChannel', () => { assert.deepStrictEqual(upstreams.get('upstream-0')!.connectOptions, [undefined]); }); - test('rejects malformed connection environments before starting the host', async () => { + test('rejects malformed connection options before starting the host', async () => { const ipc = ds.add(new FakeIPCServer()); let resolveCount = 0; const channel = ds.add(new AgentHostChannel( @@ -211,8 +212,8 @@ suite('AgentHostChannel', () => { () => ds.add(new FakeUpstream()), )); - for (const options of [null, [], 'secret', { env: null }, { env: [] }, { env: 'secret' }, { env: { GITHUB_TOKEN: 123 } }, { debugEnv: null }, { debugEnv: [] }, { debugEnv: 'secret' }, { debugEnv: { GITHUB_TOKEN: 123 } }]) { - await assert.rejects(channel.call('renderer', 'connect', options), /Invalid agent host connection environment/); + for (const options of [null, [], 'secret', { env: null }, { env: [] }, { env: 'secret' }, { env: { GITHUB_TOKEN: 123 } }, { debugEnv: null }, { debugEnv: [] }, { debugEnv: 'secret' }, { debugEnv: { GITHUB_TOKEN: 123 } }, { preferredAgentLocation: null }, { preferredAgentLocation: 'standalone' }, { preferredAgentLocation: {} }, { preferredAgentLocation: 1 }]) { + await assert.rejects(channel.call('renderer', 'connect', options), /Invalid agent host connection options/); } assert.strictEqual(resolveCount, 0); }); diff --git a/src/vs/server/test/node/serverAgentHostManager.test.ts b/src/vs/server/test/node/serverAgentHostManager.test.ts index 5849dd8caa1a..ca93b8633299 100644 --- a/src/vs/server/test/node/serverAgentHostManager.test.ts +++ b/src/vs/server/test/node/serverAgentHostManager.test.ts @@ -4,13 +4,17 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { mkdir, mkdtemp, realpath, rm } from 'fs/promises'; +import { tmpdir } from 'os'; import { DeferredPromise } from '../../../base/common/async.js'; import { Emitter, Event } from '../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../base/common/lifecycle.js'; +import { join } from '../../../base/common/path.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { IChannel, IChannelClient } from '../../../base/parts/ipc/common/ipc.js'; import { IAgentHostConnection, IAgentHostStarter } from '../../../platform/agentHost/common/agent.js'; import { AgentHostIpcChannels } from '../../../platform/agentHost/common/agentService.js'; +import { getConnectionDiagnosticError } from '../../../platform/agentHost/common/connectionDiagnostics.js'; import { NullLogService, NullLoggerService } from '../../../platform/log/common/log.js'; import { NullTelemetryServiceShape } from '../../../platform/telemetry/common/telemetryUtils.js'; import { readGithubEnvironmentOptions, ServerAgentHostManager, type IServerAgentHostManagerOptions } from '../../node/serverAgentHostManager.js'; @@ -213,6 +217,10 @@ suite('ServerAgentHostManager', () => { starter.connectionTrackerChannel.getEmitter('onDidChangeConnectionCount').fire(count); } + function fireGitHubEnvironmentRegistered(registered: boolean): void { + starter.connectionTrackerChannel.getEmitter('onDidChangeGitHubEnvironmentRegistered').fire(registered); + } + test('no lifetime token initially', async () => { const manager = createManager(); await waitForStart(manager); @@ -235,12 +243,30 @@ suite('ServerAgentHostManager', () => { assert.strictEqual(readGithubEnvironmentOptions({}), undefined); }); + test('keeps GitHub environment filesystem grants separate from projects and the default directory', () => { + const options = { ...githubEnvironment, roots: ['C:\\project', 'C:\\', 'Q:\\'], optionalRoots: ['C:\\', 'Q:\\'], projects: ['C:\\project'], defaultDirectory: 'C:\\project' }; + const env = { VSCODE_CLI_GITHUB_ENVIRONMENT_OPTIONS: JSON.stringify(options) }; + assert.deepStrictEqual({ options: readGithubEnvironmentOptions(env), env }, { options, env: {} }); + }); + test('rejects malformed GitHub environment bootstrap and still removes the credential', () => { for (const value of [ '', 'null', '{}', JSON.stringify({ ...githubEnvironment, baseUrl: 'https://untrusted.example' }), JSON.stringify({ ...githubEnvironment, credential: '' }), JSON.stringify({ ...githubEnvironment, roots: [] }), JSON.stringify({ ...githubEnvironment, roots: [123] }), + JSON.stringify({ ...githubEnvironment, optionalRoots: null }), + JSON.stringify({ ...githubEnvironment, optionalRoots: [123] }), + JSON.stringify({ ...githubEnvironment, optionalRoots: [''] }), + JSON.stringify({ ...githubEnvironment, optionalRoots: ['/not-granted'] }), + JSON.stringify({ ...githubEnvironment, optionalRoots: ['/project'], projects: ['/project'] }), + JSON.stringify({ ...githubEnvironment, optionalRoots: ['/project'], defaultDirectory: '/project' }), + JSON.stringify({ ...githubEnvironment, projects: null }), + JSON.stringify({ ...githubEnvironment, projects: [123] }), + JSON.stringify({ ...githubEnvironment, projects: [''] }), + JSON.stringify({ ...githubEnvironment, defaultDirectory: null }), + JSON.stringify({ ...githubEnvironment, defaultDirectory: 123 }), + JSON.stringify({ ...githubEnvironment, defaultDirectory: '' }), JSON.stringify({ ...githubEnvironment, accountId: 'not-an-owner' }), JSON.stringify({ ...githubEnvironment, name: '' }), JSON.stringify({ ...githubEnvironment, name: null }), @@ -285,6 +311,53 @@ suite('ServerAgentHostManager', () => { }); }); + test('rechecks automatic GitHub environment roots after a crash without dropping explicit roots', async () => { + const directory = await realpath(await mkdtemp(join(tmpdir(), 'vscode-github-environment-'))); + const drive = join(directory, 'drive'); + try { + await mkdir(drive); + const configuration = { ...githubEnvironment, roots: [directory, drive], projects: [directory], defaultDirectory: directory }; + starter.managementChannel.setCallResult('getMissionControlEnvironmentId', 'environment-123'); + const manager = createManager({ githubEnvironment: { ...configuration, optionalRoots: [drive] } }); + await manager.ensureStarted(); + await rm(drive, { recursive: true }); + starter.fireProcessExit(1); + await manager.ensureStarted(); + await mkdir(drive); + starter.fireProcessExit(1); + await manager.ensureStarted(); + assert.deepStrictEqual(starter.managementChannel.calls.filter(call => call.command === 'configureMissionControl').map(call => call.arg), [ + [configuration], + [{ ...configuration, roots: [directory] }], + [configuration], + ]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + test('preserves a structured GitHub environment configuration failure instead of reporting a missing ID', async () => { + const failure = new Error('Socket error', { + cause: Object.assign(new Error('Network timed out'), { code: 'ETIMEDOUT' }), + }); + const diagnostic = getConnectionDiagnosticError(failure); + starter.managementChannel.setCallResult('configureMissionControl', { error: diagnostic }); + const ready: string[] = []; + const manager = createManager({ githubEnvironment, onGithubEnvironmentReady: id => ready.push(id) }); + let received: ReturnType | undefined; + try { + await manager.ensureStarted(); + assert.fail('Configuration must fail'); + } catch (error) { + received = getConnectionDiagnosticError(error); + } + assert.deepStrictEqual({ + error: received, ready, + lookedUpId: starter.managementChannel.calls.some(call => call.command === 'getMissionControlEnvironmentId'), + disposed: starter.connectionStores.every(store => store.isDisposed), + }, { error: diagnostic, ready: [], lookedUpId: false, disposed: true }); + }); + test('allows the CLI to gracefully shut down a registered GitHub environment', async () => { starter.managementChannel.setCallResult('getMissionControlEnvironmentId', 'environment-123'); const manager = createManager({ githubEnvironment }); @@ -371,28 +444,30 @@ suite('ServerAgentHostManager', () => { assert.strictEqual(lifetimeService.hasActiveConsumers, true); }); - test('releases token only when both sessions and standalone WebSocket connections are zero', async () => { + test('releases token only when sessions, standalone WebSocket connections and client GitHub environment registration are gone', async () => { const manager = createManager(); await waitForStart(manager); - - fireActiveSessions(1); - assert.strictEqual(lifetimeService.hasActiveConsumers, true); - - fireConnectionCount(1); - assert.strictEqual(lifetimeService.hasActiveConsumers, true); - - fireActiveSessions(0); - assert.strictEqual(lifetimeService.hasActiveConsumers, true); - - fireConnectionCount(0); - assert.strictEqual(lifetimeService.hasActiveConsumers, false); + const states: boolean[] = []; + for (const fire of [ + () => fireActiveSessions(1), + () => fireConnectionCount(1), + () => fireGitHubEnvironmentRegistered(true), + () => fireActiveSessions(0), + () => fireConnectionCount(0), + () => fireGitHubEnvironmentRegistered(false), + ]) { + fire(); + states.push(lifetimeService.hasActiveConsumers); + } + assert.deepStrictEqual(states, [true, true, true, true, true, false]); }); - test('process exit resets both signals and clears token', async () => { + test('process exit resets all signals and clears token', async () => { const manager = createManager(); await waitForStart(manager); fireActiveSessions(2); fireConnectionCount(1); + fireGitHubEnvironmentRegistered(true); assert.strictEqual(lifetimeService.hasActiveConsumers, true); starter.fireProcessExit(1); diff --git a/src/vs/server/test/node/webClientServerManifest.test.ts b/src/vs/server/test/node/webClientServerManifest.test.ts new file mode 100644 index 000000000000..056bcc57402a --- /dev/null +++ b/src/vs/server/test/node/webClientServerManifest.test.ts @@ -0,0 +1,135 @@ +/*--------------------------------------------------------------------------------------------- + * 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 type * as http from 'http'; +import { Writable } from 'stream'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { ICSSDevelopmentService } from '../../../platform/cssDev/node/cssDevService.js'; +import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../platform/log/common/log.js'; +import product from '../../../platform/product/common/product.js'; +import { IProductService } from '../../../platform/product/common/productService.js'; +import { IRequestService } from '../../../platform/request/common/request.js'; +import { NoneServerConnectionToken } from '../../node/serverConnectionToken.js'; +import { IServerEnvironmentService } from '../../node/serverEnvironmentService.js'; +import { WebClientServer } from '../../node/webClientServer.js'; + +interface TestResponse extends Writable { + readonly statusCode: number; + readonly responseHeaders: http.OutgoingHttpHeaders; + readonly body: string; + writeHead(statusCode: number, headers?: http.OutgoingHttpHeaders): TestResponse; +} + +suite('WebClientServer manifest', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function createServer(basePath: string): WebClientServer { + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IServerEnvironmentService, { isBuilt: false }); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IRequestService, {}); + instantiationService.stub(IProductService, { _serviceBrand: undefined, ...product }); + instantiationService.stub(ICSSDevelopmentService, { isEnabled: false }); + + return instantiationService.createInstance(WebClientServer, new NoneServerConnectionToken(), basePath, '/oss-dev'); + } + + function createResponse(): TestResponse { + const chunks: Buffer[] = []; + const response = new Writable({ + write(chunk, _encoding, callback) { + chunks.push(Buffer.from(chunk)); + callback(); + } + }) as TestResponse; + Object.defineProperties(response, { + body: { get: () => Buffer.concat(chunks).toString() }, + responseHeaders: { value: Object.create(null) }, + statusCode: { value: 0, writable: true } + }); + response.writeHead = (statusCode, headers = Object.create(null)) => { + Object.assign(response, { statusCode }); + Object.assign(response.responseHeaders, headers); + return response; + }; + return response; + } + + async function requestResource(server: WebClientServer, resourcePath: string, headers: http.IncomingHttpHeaders = {}, query = ''): Promise { + const response = createResponse(); + const pathname = `/static/${resourcePath}`; + const url = new URL(`http://localhost/oss-dev${pathname}${query}`); + await server.handle({ headers } as http.IncomingMessage, response as unknown as http.ServerResponse, url, pathname); + return response; + } + + function requestManifest(server: WebClientServer, headers: http.IncomingHttpHeaders = {}, query = ''): Promise { + return requestResource(server, 'resources/server/manifest.json', headers, query); + } + + test('should use the configured base path in start_url', async () => { + const response = await requestManifest(createServer('/code')); + + assert.strictEqual(JSON.parse(response.body).start_url, '/code/'); + }); + + test('should preserve the root start_url by default', async () => { + const response = await requestManifest(createServer('/')); + + assert.strictEqual(JSON.parse(response.body).start_url, '/'); + }); + + test('should prefer X-Forwarded-Prefix over the configured base path', async () => { + const response = await requestManifest(createServer('/code'), { 'x-forwarded-prefix': '/tenant/code' }); + + assert.strictEqual(JSON.parse(response.body).start_url, '/tenant/code/'); + }); + + test('should normalize a trailing slash and ignore the request query', async () => { + const configuredResponse = await requestManifest(createServer('/code/'), {}, '?v=1&tkn=synthetic'); + const forwardedResponse = await requestManifest(createServer('/ignored'), { 'x-forwarded-prefix': '/tenant/code/' }, '?v=1'); + + assert.deepStrictEqual([ + JSON.parse(configuredResponse.body).start_url, + JSON.parse(forwardedResponse.body).start_url + ], ['/code/', '/tenant/code/']); + }); + + test('should not cache a manifest that depends on forwarded headers', async () => { + const response = await requestManifest(createServer('/code'), { 'x-forwarded-prefix': '/tenant/code' }); + + assert.deepStrictEqual({ + statusCode: response.statusCode, + cacheControl: response.responseHeaders['Cache-Control'], + contentType: response.responseHeaders['Content-Type'], + etag: response.responseHeaders.Etag, + vary: response.responseHeaders.Vary + }, { + statusCode: 200, + cacheControl: 'no-store', + contentType: 'application/json', + etag: undefined, + vary: 'X-Forwarded-Prefix' + }); + }); + + test('should keep serving other resources through the static handler', async () => { + const response = await requestResource(createServer('/code'), 'resources/server/code-192.png'); + + assert.deepStrictEqual({ + statusCode: response.statusCode, + contentType: response.responseHeaders['Content-Type'], + hasEtag: typeof response.responseHeaders.Etag === 'string', + hasBody: response.body.length > 0 + }, { + statusCode: 200, + contentType: 'image/png', + hasEtag: true, + hasBody: true + }); + }); +}); diff --git a/src/vs/sessions/AI_CUSTOMIZATIONS.md b/src/vs/sessions/AI_CUSTOMIZATIONS.md index c3cc242c09a0..87000f7eabac 100644 --- a/src/vs/sessions/AI_CUSTOMIZATIONS.md +++ b/src/vs/sessions/AI_CUSTOMIZATIONS.md @@ -107,6 +107,8 @@ source providers Section counts and rendered rows consume the same filtered model so hidden or disabled sources cannot appear in one surface but not the other. +Controls belonging to an unfocused chat use a disposable session-scoped items model over the same discovery and filtering pipeline. Reading their counts and section links must not retarget the window's active customization harness. + Prompt-based items use the prompts service adapter. MCP servers, tools, plugins, and external harness items use their owning providers directly when their data does not fit the prompt-file contract. Host-published MCP items retain the runtime-reported configuration source through typed metadata and the shared item contract, independently of lifecycle state or the availability of a local configuration definition. `IAgentHostMcpServer.skillBundle` carries the raw skill-bundle identity and listed child count for effectively enabled MCP containers, allowing navigation from MCP rows to the same bundle in Skills without interpreting scoped server IDs. @@ -117,7 +119,7 @@ Marketplace composition supplies `ICustomizationMarketplaceProvider`s with uniqu Harnesses that provide `marketplaceManagementProvider` own their marketplace inventory and mutations. The management UI uses that provider exclusively and does not merge `chat.plugins.marketplaces`; each available provider marketplace is also projected as an independently selectable Discover source backed by the provider's browse operation. Harnesses without the capability retain the VS Code configuration-backed marketplace flow. Runtime-backed providers remain authoritative for managed-policy enforcement. -External `vscode://chat-plugin/add-marketplace?ref=owner/repo` and `vscode://chat-plugin/install?source=owner/repo&plugin=name` links use the Copilot Agent Host harness exclusively, never the configuration-backed marketplace or legacy plugin installer. Marketplace sources may also be URL-escaped Git URLs or base64-encoded references; plugin names are plain query-parameter values. Both routes require explicit consent before a marketplace mutation or plugin installation. They reuse an existing Copilot Agent Host session, or ask before opening and provisioning a new one. Installation first adds the marketplace, then resolves the exact named plugin through that marketplace's provider and installs it in the same session. Runtime policy enforcement remains authoritative, and failures do not fall back to another harness. +External `vscode://chat-plugin/add-marketplace?ref=owner/repo` and `vscode://chat-plugin/install?source=owner/repo&plugin=name` links target Copilot-native or VS Code-managed shared installation on the receiving machine, followed by source- and destination-aware consent. An optional `harness=copilot` or `harness=vscode` selects the owner and skips the target picker, but never bypasses consent; links without a harness ask the user to select the owner. Empty, repeated, and unsupported values are rejected. Sources may be URL-escaped Git URLs or base64-encoded references, including `#revision`; plugin names are plain query-parameter values. Copilot uses local management IPC and global SDK marketplace and plugin operations without creating or trusting a chat session or the open workspace. Unpinned Awesome Copilot plugin links resolve through the enabled GitHub Feed and its existing owner installation provider; other plugin links add the exact marketplace source, resolve the named plugin in that marketplace, and install its runtime-owned identity. VS Code uses its source installer and configuration-backed marketplace inventory, preserving marketplace trust and strict policy checks. Shared installation does not imply native Claude/Codex ownership or compatibility. Remote-workspace and web windows reject these links, failures never switch owners, and runtime policy enforcement remains authoritative for Copilot. Harnesses may supply an `ICustomizationMarketplaceInstallProvider`. Its SDK or runtime inventory is authoritative for installation identity, ownership, recovery, and removal; the workbench does not create a second durable installation record. The install service removes legacy machine-profile installation records without reading or migrating them. It projects provider inventory through the same immutable snapshot used by Skills, MCP, Discover, and management actions, and keeps only a bounded, in-memory association between a provider installation and catalog presentation metadata seen in the current window. That association can enrich installed rows with icons and descriptions but cannot make a resource installed. Provider inventory remains usable when the catalog is offline or no longer returns an entry, with fallback type icons and retained SDK catalog metadata. diff --git a/src/vs/sessions/MOBILE.md b/src/vs/sessions/MOBILE.md index f92e85e1df5e..27c6f551b78b 100644 --- a/src/vs/sessions/MOBILE.md +++ b/src/vs/sessions/MOBILE.md @@ -14,15 +14,27 @@ Mobile components are presentation adapters over shared Sessions services. They Alternative web entry points supply a workbench factory and select concrete presentations at startup. Shared contracts do not import their default implementations or choose a mobile fallback. Concrete replacements and their styles belong to the entry that selects them. -For starting browser sessions, each entry registers its `ISessionRepositoryPicker` implementation. Providers call that required service without selecting or importing a picker implementation; authentication, cancellation, and repository validation remain provider-owned. The regular entry registers the existing quick picker. Alternative entries can supply a sheet without changing the provider. +Shared session implementations live in `vs/workbench` and do not register themselves. Entries load the common session-service registrations and their own presentation registrations separately. Importing an implementation is not sufficient to activate its service or contribution. -`IChatViewFactory` supplies composer options, including editor metrics and new-session chrome. These options are forwarded to new-session, nested-chat, running-chat, and edited-request inputs; mode/model presentation does not control font sizing or clipboard access. Clipboard attachments are registered through the existing chat context-item mechanism by each entry. +For starting browser sessions, each entry registers its `ISessionRepositoryPicker` implementation. Providers call that required service without selecting or importing a picker implementation; authentication, cancellation, and repository validation remain provider-owned. The regular entry registers the existing quick picker, while the experimental mobile entry registers its repository sheet. + +`IChatViewFactory` supplies composer options, including editor metrics and new-session chrome. These options are forwarded to new-session, nested-chat, running-chat, and edited-request inputs; mode/model presentation does not control font sizing or clipboard access. Clipboard attachments are registered through the existing chat context-item mechanism by each entry. The experimental mobile entry reads the clipboard only after selection. Directly composed chat inputs, such as automation prompts, receive the same editor options from the view factory and pass them to their input component. -`ISessionsListPresentation` owns list chrome, interactions, and name editing. The regular implementation starts the list's inline editor; an alternative implementation can prompt before committing. Session and group changes still go through the list and its shared services. List dimensions are passed as component options. +The view factory also owns optional chat-background presentation for the session grid and transcript. Shared chat views receive a background adapter through their options rather than importing a renderer or configuration service. The regular entry supplies the background feature; the isolated mobile entry omits its presentation, registrations, and media. Both entries share built-in skill definitions and discovery; packaging a skill does not register the tools it uses. + +View factories receive the owning host's instantiation service for each view. Mobile headers use that same scope; they must not capture a global service or reuse another view's scope. + +`ISessionsListPresentation` owns list chrome, interactions, and name editing. The regular implementation starts the list's inline editor; the experimental implementation prompts before committing. Session and group changes still go through the list and its shared services. List dimensions are passed as component options. + +`IChatEditPresentationService` owns text-edit rendering and external-edit opening. The regular entry selects compare editors and ordinary editor navigation; the experimental entry selects edit rows and mobile overlays. Shared chat owns compare-model creation, and each returned presentation owns its rendering resources. Mobile diff overlays read through the standard text-model service, including in-memory snapshots. + +## Isolated web composition + +The experimental `agents.web.mobile.main.internal.ts` entry composes the shared core with an explicit set of contributions, a fixed phone workbench, and entry-owned presentation services. Existing desktop and web entries neither import its implementations nor activate its defaults. Ordinary production build targets do not include this entry; its opt-in [isolated package](../../../build/next/MOBILE.md) has separate assets and localization. -`IChatEditPresentationService` owns text-edit rendering and external-edit opening. The regular entry selects compare editors and ordinary editor navigation. Shared chat owns compare-model creation, and each returned presentation owns its rendering resources. Mobile diff overlays read through the standard text-model service, including in-memory snapshots. +After transpiling the checkout, `node scripts/code-sessions-web.js --mobile --no-open` serves this entry locally. Add `--mock` for the mock-services entry. This source launcher does not publish an artifact. ## Viewport classification @@ -42,7 +54,7 @@ Mobile navigation and transient overlays Desktop side parts do not remain as permanently visible columns. Their content is presented through mobile navigation, drawers, sheets, or full-screen overlays as appropriate. -The active session and chat remain owned by `ISessionsService`. Mobile navigation must not create a second active-session store. +The main window's session host identifies the session and chat shown on the phone. Mobile controls use that host or the explicit chat supplied by their input, while `ISessionsService` owns the shared grid and navigation operations. Mobile navigation must not create a second active-session store. The Sessions Part projects only the active session onto the phone surface while retaining the desktop split topology, sash allocations, and live views. Crossing the breakpoint in either direction adapts the existing part, regardless of which subclass was selected at startup. Phone dimensions do not overwrite desktop geometry; returning to a non-phone viewport restores that arrangement at the available size. Structural session changes made on phone still update the canonical grid. diff --git a/src/vs/sessions/SESSIONS.md b/src/vs/sessions/SESSIONS.md index 881dad0808bd..ea4fc3e41548 100644 --- a/src/vs/sessions/SESSIONS.md +++ b/src/vs/sessions/SESSIONS.md @@ -91,7 +91,7 @@ A session host (`ISessionHost`) is a surface that shows a chat: the main window, - **Lookups.** `ISessionHostService` finds hosts by id, window, editor group, chat, or session, returning the innermost match, and tells whether any host shows a session or chat. It has no selection. Which pane of the grid is the active one, and which panes are detached, only the grid knows: `ISessionsService.getPaneOfHost` gives the pane a host stands for (the active pane for the grid host, a view's pane for the host of a view of the grid, none for other hosts), and `isActivePane` and `isDetachedPane` answer for a host. `getHostOfSession` uses them to pick, of the panes of a window that show a session, the active one, else the one that is not detached. - **Focused host.** `IFocusedSessionHostService` is the window host that last gained focus; it stays while the app is in the background. Only window-independent consumers, such as voice, use it; UI uses the host it is in. - **Command targets.** `resolveSessionCommandTarget` resolves what a command acts on: a host its toolbar or menu passes (`createHostMenuOptions`), an editor or window context, a chat, or a session. Without arguments, it resolves the focused host. Arguments that name something that is not found resolve to `undefined`, and the command does nothing; it never falls back to the focused host. Commands of the main window's grid act on the grid's active pane (`ISessionsPartService.getActiveSessionView()`), and neither run nor match their keybindings while a chat window is the focused host. -- **Chat-host openers.** A surface outside the grid that shows chats, such as a chat window, registers an `IChatHostOpener`. Opening, revealing, opening beside, closing, and activating a chat it shows go through its opener; the grid is not touched. +- **Chat-host openers.** A surface outside the grid that shows chats, such as a chat window, registers an `IChatHostOpener`. Opening, revealing, opening beside, closing, and activating a chat it shows go through its opener; the grid is not touched. A new chat opened with a reference chat that such a surface shows, such as a side chat, `/btw` or a chat fork, opens beside that chat through the same opener, whatever its origin. - **New sessions in chat windows.** A chat window can show a new-session composer as a chat editor, which holds its drafts in a draft slot of its own (`INewSessionDraftHost`). New Session in a chat window (its command, its key while the chat window has focus, and the Sessions picker of the window) opens one as a tab of the window's active chat, or beside it, and shows the active one instead while that is unsent. It starts from the active chat's session: its workspace (including a Dev Container environment), agent, model and mode, and its custom group in the sessions list; the user can change them before sending. Until its session is sent, it stays in its window (moving it to the main window or another window is refused with the reason) and does not take the main window's global composer actions, such as tours or the workspace selection, nor Voice Mode, which keeps addressing the main window's composer. A foreground send turns the tab into the session's main chat in place, held out of the grid like the window's other chats. A background send keeps the tab a composer, reseeded with the same target: the session it starts shows only in the sessions list, and the composer's Open Session link opens it beside the composer. A failed background send gives its prompt back to the composer, or offers it in a notification. An unsent composer restores with its window after a reload, with its input. - **Grid exclusion.** A chat that a chat window shows is held out of the grid with `ISessionsService.hideChatFromGrid`, while that window shows it. The session leaves the grid when that was the only chat it showed there. - **Grid host.** `ISessionsService.gridHost` is the main window's host, which shows the grid's active pane. It is the one instance that `ISessionHostService` registers for the main window. The grid's own selection is internal to `ISessionsService`; others read the hosts. @@ -226,6 +226,8 @@ A contextual Agents Window invitation identifies an existing chat in the source The product protocol link `://agents/new?prompt=&workspace=` opens the Agents Window and applies its prompt and optional workspace through the same draft handoff. When `workspace` is omitted, the handoff explicitly selects No Workspace. Opening the link never submits the prompt, and an occupied composer remains unchanged. +A chat link opens by the same rules whether it is activated in the window, as `agent-host-session://…`, or reaches the Agents Window through the OS, as `://agents/agent-host-session/…`, the way canvases open chats. A link activated in a chat window opens there as a tab of the window's active chat, or beside it when opened to the side. A link the OS hands over counts as activated in the chat window that has focus when it arrives. A link from the main window, one that arrives while no chat window has focus, or one a tool or command opens, opens through the main window. + Automation editing uses an independent draft so it cannot replace the ordinary New Session composer. Providers advertise `supportsAutomationSessionConfiguration` when they restore `ISessionsProviderCreateSessionOptions.automationConfiguration` before the draft's first configuration resolution and implement `getAutomationSessionConfiguration` to capture the current template. The management service rejects canonical templates for providers without this capability, while deprecated flat aliases continue through ordinary model, mode, and permission operations. It distinguishes unsupported capture from a valid empty template, a replaced draft, and capture failure. Provider-specific configuration remains opaque to shared Sessions code. Scoped Automation and New Session surfaces consume the same provider menu contributions through the host they are in; providers may advertise presentation capabilities such as a combined phone Mode/Model picker without exposing provider identity checks to shared UI. diff --git a/src/vs/sessions/SESSIONS_LIST.md b/src/vs/sessions/SESSIONS_LIST.md index 90e3ec86cc3a..e8c5a4218ddc 100644 --- a/src/vs/sessions/SESSIONS_LIST.md +++ b/src/vs/sessions/SESSIONS_LIST.md @@ -82,17 +82,17 @@ Environment grouping uses the provider-neutral environment identity, combining s ### Inbox grouping -Inbox is an opt-in presentation of the same catalog, classified into Ready for you, Working, Ready to merge, On hold, and Done. On desktop, Pinned and the always-expanded primary Inbox occupy one scrolling region; the remaining categories and optional archived inventory occupy a bottom-anchored, independently scrolling region. Both regions share one list owner, classification, filters, triage, and attention lease. Selection, explicit reveal, search, and programmatic snapshots cover both regions; passive selection restoration must not expand a user-collapsed category. Category expansion is persisted by its existing identity. Phone retains a single grouped tree. +Inbox is an opt-in presentation of the same catalog, classified into Inbox, Working, Ready to merge, On hold, and Dismissed, with archived inventory in Done (or Archived, according to the archive wording setting). Desktop and phone use one scrolling tree. Pinned precedes the always-expanded Inbox; empty secondary categories are omitted. On hold contains workspace subgroups without changing saved custom-group membership. Selection, explicit reveal, search, and programmatic snapshots cover the whole tree; passive selection restoration must not expand a user-collapsed category. Category expansion is persisted by its existing identity. -`sessions.list.inboxEnabled` gates entry through menus, commands, and agent tools. Disabling it suspends a saved Inbox selection in favor of workspace grouping without clearing triage or presentation state; reenabling restores the selection unless the user chose another grouping. Pins remain visible above the categories; archived sessions remain separate. Custom memberships, automatic-section placement, and manual ordering are retained but do not determine Inbox placement. Comparison groups remain intact and follow their highest-attention participant. Switching out of Inbox restores ordinary organization. +Inbox is available through grouping menus, commands, and agent tools regardless of `sessions.list.inboxEnabled`. The setting chooses Inbox rather than Workspace as the default only when no explicit grouping is saved. Selecting any grouping, including the current default, persists that choice across setting changes and reloads. Pins remain visible above the categories; archived sessions remain separate. Custom memberships, automatic-section placement, and manual ordering are retained but do not determine Inbox placement. Comparison groups remain intact and follow their highest-attention participant. Switching out of Inbox restores ordinary organization. -The setting also enables Cmd/Ctrl+Enter for Send in Background and adds focus preservation and an Open Session confirmation to explicit background sends from the new-session composer. Existing Alt+Enter behavior and always-background composers remain available with the setting disabled. +Selecting Inbox grouping enables Cmd/Ctrl+Enter for Send in Background and adds focus preservation and an Open Session confirmation to explicit background sends from the new-session composer. Existing Alt+Enter behavior and always-background composers remain available in other groupings. -`ISessionsListModelService` owns profile-local triage state. Completed history from before the sidebar Inbox's first activation starts in Done unless it has an outstanding question or actionable notification. Return to Inbox and expired snoozes override that initial placement, including after reload. Subsequent Done decisions are explicit, reversible acknowledgements, not archiving, stopping, or deleting sessions. New activity or newly observed notification identities return acknowledged sessions to the inbox. Put on Hold persists until explicit resumption, regardless of new activity or reloads. Timed and until-activity snoozes share the On hold section but expire automatically; none of these states pauses execution. Pinning keeps even held sessions visible. New completions are never marked Done merely because time passes or a pull request merges. +`ISessionsListModelService` owns profile-local triage state. Completed history from before the sidebar Inbox's first activation starts in Dismissed unless it has an outstanding question, an actionable notification, or is unread and was modified today in the user's local calendar day. This unread exception uses the session's last-modified time, not its last-turn end time. Read-state and modification changes update this implicit placement without overriding explicit dismissal, hold, or snooze. Return to Inbox and expired snoozes override that initial placement, including after reload. Dismissal is an explicit, reversible acknowledgement, not archiving, stopping, or deleting sessions. The persisted `done` triage value and section identity retain their existing meaning. New activity or newly observed notification identities return acknowledged sessions to the inbox. Put on Hold persists until explicit resumption, regardless of new activity or reloads. Timed and until-activity snoozes share the On hold section but expire automatically into the category appropriate to current activity; none of these states pauses execution. Pinning keeps even held sessions visible. New completions are never dismissed merely because time passes or a pull request merges. `IInboxNotificationsService.sessionAttention` shares the original Inbox's notification-based classification and priority without importing its workflow decisions. A visible Inbox-mode list acquires attention tracking and releases it on hiding, leaving the mode, or disposal. Its first activation establishes a persisted, profile-local completion cutoff, independent of the canvas's cutoff, so late-arriving history does not appear as new work. That demand respects disabled AI and does not enable the Inbox canvas, generate previews, record canvas lifecycle telemetry, or establish the canvas's completion cutoff. -Inbox categories have fixed order; ordinary rows prioritize the shared notification priority and then recent activity. Placement drag and drop is unavailable in this mode rather than changing the saved project organization. Provider-owned nested chat moves are unchanged. +Inbox categories have fixed order; rows prioritize the shared notification priority and then the selected created-time or updated-time ordering. A session with multiple unarchived chats remains available in Inbox while one chat is working if another has completed, needs input, or has failed. Placement drag and drop is unavailable in this mode rather than changing the saved project organization. Provider-owned nested chat moves are unchanged. ### Nested custom groups diff --git a/src/vs/sessions/SESSION_COMPARISONS.md b/src/vs/sessions/SESSION_COMPARISONS.md index 3b8c563074f5..a1f179b1a4fe 100644 --- a/src/vs/sessions/SESSION_COMPARISONS.md +++ b/src/vs/sessions/SESSION_COMPARISONS.md @@ -50,7 +50,7 @@ Status, metrics, worktrees, changes, transcript access, and tool authorization a With Compare Models enabled and the experimental `sessions.chat.compareAgents.tools.enabled` setting opted into (default: `false`), Agents-window agents can use `getComparisonModels` to discover provider-local fixed model selections and configuration schemas, then `createModelComparison` to launch one scenario with two to ten attempts and an optional Judge and Synthesizer. Creation uses the caller's host, canonical project workspace, and provider-owned permission intent, including when the caller is a nested chat. Explicit folderless comparisons omit the workspace and branch but may include a Judge and Synthesizer. Creation uses normal tool approval, revalidates the prepared configuration before launch, and leaves the evaluator chat focused. Comparison participants cannot recursively launch comparisons. The comparison service remains the single owner of participant creation and lifecycle; these client tools do not invoke or change the native Agent Host `create_session` tool's private orchestration counters. -`listModelComparisons` reads persisted comparison records independently of sidebar filters, with bounded pages and optional archive, workspace, and ID filters. `readModelComparison` is read-only and available to any eligible agent in the window, not just the comparison's creator or Judge. It exposes the original task, stable attempt numbers including failed launches, per-chat state and bounded change evidence, available completion metrics, and the persisted structured verdict. Participant records include exact context targets for reachable attempt, Judge, and synthesis chats. `get_session_context` owns follow-up trajectory retrieval with its existing summary, digest, full, and recent-turn limits; unsupported providers and other hosts have explicit unavailable reasons rather than guessed targets. Archived records remain readable even when live worktrees or transcripts no longer exist. +Agent-created comparisons persist the exact initiating chat resource, separate from participant identities and the legacy owning session. `listModelComparisons` defaults to that chat's comparisons, independently of sidebar filters, with bounded pages and optional archive, workspace, and ID filters. Explicit `scope: "window"` includes other chats' comparisons, manual comparisons, and older records without an initiating chat. This is a discovery default, not an access boundary. `readModelComparison` is read-only and available to any eligible agent in the window, not just the comparison's creator or Judge. It exposes the original task, stable attempt numbers including failed launches, per-chat state and bounded change evidence, available completion metrics, and the persisted structured verdict. Participant records include exact context targets for reachable attempt, Judge, and synthesis chats. `get_session_context` owns follow-up trajectory retrieval with its existing summary, digest, full, and recent-turn limits; unsupported providers and other hosts have explicit unavailable reasons rather than guessed targets. Archived records remain readable even when live worktrees or transcripts no longer exist. These evaluator tools do not change the Judge/Synthesizer authorization of `readAttemptComparison` or the Judge-only write authority of `completeAttemptComparison`. Disabling the evaluator-tool setting removes all four evaluator tools and rejects pending invocations, including launches awaiting approval, without disabling manual comparisons or existing participant tools. Disabling comparison setup also removes evaluator tools and prevents new launches, while existing participant tools retain their completion/restoration behavior. Evaluation collections use existing comparison groups; agents orchestrate multiple tool calls and produce reports without a separate collection store, scheduler, or reporting UI. diff --git a/src/vs/sessions/agents.web.mobile.main.internal.ts b/src/vs/sessions/agents.web.mobile.main.internal.ts new file mode 100644 index 000000000000..79eb2702ac69 --- /dev/null +++ b/src/vs/sessions/agents.web.mobile.main.internal.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. + *--------------------------------------------------------------------------------------------*/ + +// This file is the web embedder entry point for the mobile Sessions workbench. +// It mirrors sessions.web.main.internal.ts but loads the allow-listed mobile +// entry point and creates the mobile workbench. + +import './agents.web.mobile.main.js'; +import { create as createSessionsWorkbench } from './browser/web.factory.js'; +import { createMobileSessionsWorkbench } from './browser/mobile/mobileWorkbench.js'; +import { IWorkbenchConstructionOptions } from '../workbench/browser/web.api.js'; +import { Disposable, IDisposable } from '../base/common/lifecycle.js'; +import { URI } from '../base/common/uri.js'; +import { Event, Emitter } from '../base/common/event.js'; +import { LogLevel } from '../platform/log/common/log.js'; + +/** + * Creates the mobile Sessions workbench in the provided container. + */ +function create(domElement: HTMLElement, options: IWorkbenchConstructionOptions): IDisposable { + return createSessionsWorkbench(domElement, options, createMobileSessionsWorkbench); +} + +export { + create, + URI, + Event, + Emitter, + Disposable, + LogLevel, +}; diff --git a/src/vs/sessions/agents.web.mobile.main.ts b/src/vs/sessions/agents.web.mobile.main.ts new file mode 100644 index 000000000000..b36a3eafc5a6 --- /dev/null +++ b/src/vs/sessions/agents.web.mobile.main.ts @@ -0,0 +1,335 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + + +// ####################################################################### +// ### ### +// ### Mobile web entry point of the Agents Window. ### +// ### ### +// ### This bundle is an ALLOW-LIST. It loads the services shared ### +// ### with the desktop bundles and then only the feature ### +// ### contributions a phone needs to manage chat sessions: ### +// ### the sessions list, the chat, the new-session composer, ### +// ### changes/diff review, account, and remote host connectivity. ### +// ### ### +// ### Do NOT import sessions.common.main.js or sessions.web.main.js ### +// ### here. If a feature is missing on the phone, add its ### +// ### contribution explicitly and give it a phone presentation. ### +// ### ### +// ####################################################################### + +//#region --- sessions core (services, parts, extension points) + +import './sessions.core.main.js'; +import './sessions.core.web.main.js'; + +//#endregion + + +//#region --- shared services the phone needs without their editors or views + +// Every registration here is a service that a shared component requires in its +// constructor even though the phone never shows the corresponding UI. Each is a +// coupling to break with a seam later; keeping them listed makes the debt visible. + +import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; + +// chatEditingService and agentSessionProjectionService query INotebookService to +// tell notebook URIs apart from text files. The notebook editor is not shipped. +import { INotebookService } from '../workbench/contrib/notebook/common/notebookService.js'; +import { NotebookService } from '../workbench/contrib/notebook/browser/services/notebookServiceImpl.js'; +import { INotebookEditorModelResolverService } from '../workbench/contrib/notebook/common/notebookEditorModelResolverService.js'; +import { NotebookModelResolverServiceImpl } from '../workbench/contrib/notebook/common/notebookEditorModelResolverServiceImpl.js'; +import { INotebookLoggingService } from '../workbench/contrib/notebook/common/notebookLoggingService.js'; +import { NotebookLoggingService } from '../workbench/contrib/notebook/browser/services/notebookLoggingServiceImpl.js'; +registerSingleton(INotebookService, NotebookService, InstantiationType.Delayed); +registerSingleton(INotebookEditorModelResolverService, NotebookModelResolverServiceImpl, InstantiationType.Delayed); +registerSingleton(INotebookLoggingService, NotebookLoggingService, InstantiationType.Delayed); + +// The telemetry contribution opens its log channel through IOutputService. The +// Output view is not shipped; showing a channel is a no-op on the phone. +import { IOutputService } from '../workbench/services/output/common/output.js'; +import { OutputService } from '../workbench/contrib/output/browser/outputServices.js'; +registerSingleton(IOutputService, OutputService, InstantiationType.Delayed); + +// chatEditingService resolves multi-file edits through IMultiDiffSourceResolverService. +// The phone reviews changes with its own diff overlays; the multi-diff editor is not shipped. +import { IMultiDiffSourceResolverService, MultiDiffSourceResolverService } from '../workbench/contrib/multiDiffEditor/browser/multiDiffSourceResolverService.js'; +registerSingleton(IMultiDiffSourceResolverService, MultiDiffSourceResolverService, InstantiationType.Delayed); + +// The chat outline creator requires IOutlineService. +import '../workbench/services/outline/browser/outlineService.js'; + +// Agent-host sessions (AgentHostSessionHandler) and the transcript parts that +// show a command the agent ran (ChatTerminalToolProgressPart and its +// confirmation) require ITerminalChatService. It tracks tool sessions and +// the read-only output sources that feed the command card; it creates no +// terminal. The terminal inline chat it was written for is not shipped. +import { ITerminalChatService } from '../workbench/contrib/terminal/browser/terminal.js'; +import { TerminalChatService } from '../workbench/contrib/terminalContrib/chat/browser/terminalChatService.js'; +registerSingleton(ITerminalChatService, TerminalChatService, InstantiationType.Delayed); + +//#endregion + + +//#region --- services forced by the extension host API surface + +// The extension host instantiates every `MainThread*` customer and then asserts +// that all of them exist (`ExtensionHostManager#_createExtensionHostCustomers`). +// A single missing service therefore breaks the whole extension host — and with +// it GitHub authentication and every extension-backed provider. Until the API +// layer supports optional customers, the phone must register the services the +// desktop-only customers depend on. Only service implementations are loaded +// here; the editors, views, and actions of these features stay out of the bundle. + +// MainThreadNotebook*, MainThreadNotebooksAndEditors, MainThreadNotebookRenderers +import { INotebookEditorService } from '../workbench/contrib/notebook/browser/services/notebookEditorService.js'; +import { NotebookEditorWidgetService } from '../workbench/contrib/notebook/browser/services/notebookEditorServiceImpl.js'; +import { INotebookCellStatusBarService } from '../workbench/contrib/notebook/common/notebookCellStatusBarService.js'; +import { NotebookCellStatusBarService } from '../workbench/contrib/notebook/browser/services/notebookCellStatusBarServiceImpl.js'; +import { INotebookRendererMessagingService } from '../workbench/contrib/notebook/common/notebookRendererMessagingService.js'; +import { NotebookRendererMessagingService } from '../workbench/contrib/notebook/browser/services/notebookRendererMessagingServiceImpl.js'; +import { INotebookKernelService, INotebookKernelHistoryService } from '../workbench/contrib/notebook/common/notebookKernelService.js'; +import { NotebookKernelService } from '../workbench/contrib/notebook/browser/services/notebookKernelServiceImpl.js'; +import { NotebookKernelHistoryService } from '../workbench/contrib/notebook/browser/services/notebookKernelHistoryServiceImpl.js'; +import { INotebookExecutionService } from '../workbench/contrib/notebook/common/notebookExecutionService.js'; +import { NotebookExecutionService } from '../workbench/contrib/notebook/browser/services/notebookExecutionServiceImpl.js'; +import { INotebookExecutionStateService } from '../workbench/contrib/notebook/common/notebookExecutionStateService.js'; +import { NotebookExecutionStateService } from '../workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl.js'; +registerSingleton(INotebookEditorService, NotebookEditorWidgetService, InstantiationType.Delayed); +registerSingleton(INotebookCellStatusBarService, NotebookCellStatusBarService, InstantiationType.Delayed); +registerSingleton(INotebookRendererMessagingService, NotebookRendererMessagingService, InstantiationType.Delayed); +registerSingleton(INotebookKernelService, NotebookKernelService, InstantiationType.Delayed); +registerSingleton(INotebookKernelHistoryService, NotebookKernelHistoryService, InstantiationType.Delayed); +registerSingleton(INotebookExecutionService, NotebookExecutionService, InstantiationType.Delayed); +registerSingleton(INotebookExecutionStateService, NotebookExecutionStateService, InstantiationType.Delayed); + +// MainThreadWebviewPanels, MainThreadEditorInsets, MainThreadWebviewsViews (and chat attachment widgets) +import '../workbench/contrib/webview/browser/webview.web.contribution.js'; +import { IWebviewWorkbenchService, WebviewEditorService } from '../workbench/contrib/webviewPanel/browser/webviewWorkbenchService.js'; +import { IWebviewViewService, WebviewViewService } from '../workbench/contrib/webviewView/browser/webviewViewService.js'; +registerSingleton(IWebviewWorkbenchService, WebviewEditorService, InstantiationType.Delayed); +registerSingleton(IWebviewViewService, WebviewViewService, InstantiationType.Delayed); + +// MainThreadInteractive +import { IInteractiveDocumentService, InteractiveDocumentService } from '../workbench/contrib/interactive/browser/interactiveDocumentService.js'; +registerSingleton(IInteractiveDocumentService, InteractiveDocumentService, InstantiationType.Delayed); + +// MainThreadCustomEditors +import { ICustomEditorService } from '../workbench/contrib/customEditor/common/customEditor.js'; +import { CustomEditorService } from '../workbench/contrib/customEditor/browser/customEditors.js'; +registerSingleton(ICustomEditorService, CustomEditorService, InstantiationType.Delayed); + +// MainThreadComments +import { ICommentService, CommentService } from '../workbench/contrib/comments/browser/commentService.js'; +registerSingleton(ICommentService, CommentService, InstantiationType.Delayed); + +// MainThreadSCM, MainThreadQuickDiff, MainThreadDocumentsAndEditors +import '../workbench/contrib/scm/browser/quickDiff.contribution.js'; + +// MainThreadTimeline, MainThreadShare +import '../workbench/contrib/timeline/browser/timeline.service.contribution.js'; +import '../workbench/contrib/share/browser/share.contribution.js'; + +// MainThreadBrowsers, MainThreadBrowserTunnelProxy (and chat attachment resolution) +import '../workbench/contrib/browserView/browser/browserView.contribution.js'; + +// MainThreadTerminalService, MainThreadTerminalShellIntegration, MainThreadTask. +// The terminal service layer and the three terminal features the API customer +// injects. No xterm instance is created unless a terminal is opened, and the +// phone's IAgentHostTerminalService never opens one. +import '../workbench/contrib/terminal/browser/terminal.contribution.js'; +import '../workbench/contrib/terminal/browser/terminal.web.contribution.js'; +import '../workbench/contrib/terminal/common/environmentVariable.contribution.js'; +import '../workbench/contrib/terminal/common/terminalExtensionPoints.contribution.js'; +import '../workbench/contrib/terminalContrib/links/browser/terminal.links.contribution.js'; +import '../workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.js'; +import '../workbench/contrib/terminalContrib/quickFix/browser/terminal.quickFix.contribution.js'; +import '../workbench/contrib/tasks/browser/taskService.js'; + +//#endregion + + +//#region --- workbench actions + +import '../workbench/browser/actions/textInputActions.js'; +import '../workbench/browser/actions/listCommands.js'; +import '../workbench/browser/actions/navigationActions.js'; +import '../workbench/browser/actions/widgetNavigationCommands.js'; + +//#endregion + + +//#region --- web bootstrap and phone presentation + +// Bottom-sheet dialogs in place of the standard web dialog handler. +import './browser/parts/dialogs/mobileDialog.web.contribution.js'; + +// Sessions browser bootstrap (workspace, configuration, storage). +import './browser/web.main.js'; + +// Per-session layout controller for the phone layout. +import './contrib/layout/browser/sessions.mobile.layout.contribution.js'; + +//#endregion + + +//#region --- workbench contributions the phone needs + +// Default Account +import '../workbench/services/accounts/browser/defaultAccount.js'; + +// Telemetry (chat markdown parts report AI edits through IAiEditTelemetryService) +import '../workbench/contrib/telemetry/browser/telemetry.contribution.js'; +import '../workbench/contrib/editTelemetry/browser/editTelemetry.contribution.js'; + +// Chat +import '../workbench/contrib/chat/browser/chat.shared.contribution.js'; +import '../workbench/contrib/mcp/browser/mcp.contribution.js'; +import '../workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.js'; +import '../workbench/contrib/chat/browser/contextContrib/chatContext.contribution.js'; +// "Add Context" opens the file picker through the anything quick-access +// provider; without this registration the action runs and shows nothing. +import '../workbench/contrib/search/browser/searchQuickAccess.contribution.js'; + +// Voice: speech-to-text is a first-class phone input +import '../workbench/contrib/speech/browser/speech.contribution.js'; +import '../workbench/contrib/agentsVoice/browser/agentsVoice.contribution.js'; +import './contrib/chat/browser/voiceBridge.contribution.js'; + +// Text files and editors (chat opens files and diffs through the editor service) +import '../workbench/contrib/files/browser/files.contribution.js'; +import '../workbench/contrib/bulkEdit/browser/bulkEditService.js'; +import '../workbench/contrib/codeEditor/browser/codeEditor.contribution.js'; +import '../workbench/contrib/markdown/browser/markdown.contribution.js'; + +// Editor services the chat input editors instantiate through editor contributions +import '../workbench/contrib/snippets/browser/snippets.service.contribution.js'; +import '../workbench/contrib/inlineCompletions/browser/renameSymbolTrackerService.js'; + +// Onboarding scenarios back the session archive suggestion shown in the chat view +import '../workbench/contrib/onboarding/browser/onboarding.contribution.js'; + +// Source control services (session changes are computed against git) +import '../workbench/contrib/git/browser/git.contributions.js'; +import '../workbench/contrib/scm/browser/scm.service.contribution.js'; + +// Links +import '../workbench/contrib/url/browser/url.contribution.js'; +import '../workbench/contrib/opener/browser/opener.contribution.js'; +import '../workbench/contrib/externalUriOpener/common/externalUriOpener.contribution.js'; + +// Authentication (sign-in flows and the `contributes.authentication` extension point) +import '../workbench/contrib/authentication/browser/authentication.contribution.js'; + +// Accessibility (accessible view and signals are injected by the chat widget) +import '../workbench/contrib/accessibility/browser/accessibility.contribution.js'; +import '../workbench/contrib/accessibilitySignals/browser/accessibilitySignal.contribution.js'; + +// Lists +import '../workbench/contrib/list/browser/list.contribution.js'; + +// Paste and drop into the chat input (images, files) +import '../workbench/contrib/dropOrPasteInto/browser/dropOrPasteInto.contribution.js'; + +// Extension host debugging service required by the web extension host +import '../workbench/contrib/debug/browser/extensionHostDebugService.js'; + +//#endregion + + +//#region --- sessions contributions the phone needs + +// Parts and shared sessions services +import './browser/paneCompositePartService.js'; +import './browser/parts/editorParts.js'; +import './browser/parts/sessionsParts.js'; +import './browser/parts/customViewGridParts.js'; +import './browser/parts/sessionsPartContent.registration.js'; +import './services/sessions/browser/sessionsWindowUsageService.js'; +import './services/sessions/browser/sessionsCoreServices.registration.js'; +import './services/workspaceFolderLabel/browser/workspaceFolderLabelService.js'; +import './services/mcp/browser/mcpWorkspaceInstallTargetService.js'; +import './services/customView/browser/customViewService.registration.js'; +import './services/activity/common/sessionActivityBarActivityService.registration.js'; + +// Account +import './contrib/accountMenu/browser/account.contribution.js'; + +// GitHub: the default Copilot sessions provider and the title bar resolve +// pull requests and blocked sessions through IGitHubService. +import './contrib/github/browser/github.contribution.js'; + +// Code review registers ICodeReviewService, which the changes service requires. +// Its actions are already gated off the phone layout. +import './contrib/codeReview/browser/codeReview.contributions.js'; + +// Chat and the new-session composer (includes the phone diff/changes overlays) +import './contrib/chat/browser/chat.contribution.js'; +import './contrib/chat/browser/sharedChatInputComposer.contribution.js'; +import './contrib/chat/browser/requestOriginProvider.contribution.js'; +import './contrib/sessions/browser/customizationsToolbar.contribution.js'; + +// Coupling debt: NewChatWidget takes IAquariumService in its constructor. +import './contrib/aquarium/browser/aquarium.contribution.js'; + +// Sessions list +import './contrib/sessions/browser/sessions.contribution.js'; + +// Coupling debt: sessions.contribution.ts registers the automations custom view, +// whose contribution takes IAutomationService in its constructor. +import './contrib/automations/browser/automations.contribution.js'; + +// Changes +import './contrib/changes/browser/changes.contribution.js'; + +// Session file system provider (needed to read files for diffs) +import './contrib/fileTreeView/browser/fileTreeView.contribution.js'; + +// Workspace resolution for new sessions +import './contrib/workspace/browser/workspace.contribution.js'; + +// Settings and policy +import './contrib/configuration/browser/configuration.contribution.js'; +import './contrib/policyBlocked/browser/policyBlocked.contribution.js'; +import '../workbench/services/policies/browser/managedSettingsUpdate.contribution.js'; + +// Providers: Copilot chat sessions +import './contrib/providers/copilotChatSessions/browser/copilotChatSessions.contribution.js'; + +// Providers: agent host (mode/model configuration, debug log export, subagents) +import './contrib/providers/agentHost/browser/agentHostSessionConfigPicker.contribution.js'; +import './contrib/providers/agentHost/browser/agentHostPolicyContinuationPresenter.contribution.js'; +import './contrib/providers/agentHost/browser/exportDebugLogsAction.js'; +import './contrib/providers/agentHost/browser/agentSessionSettings.contribution.js'; +import './contrib/providers/agentHost/browser/agentHostSettings.contribution.js'; +import './contrib/providers/agentHost/browser/openSubagentChat.contribution.js'; + +// Providers: remote agent hosts reachable from a phone (tunnels, WebSocket, cloud sandbox) +import './contrib/providers/remoteAgentHost/browser/webTunnelAgentHostService.contribution.js'; +import './contrib/providers/remoteAgentHost/browser/tunnelAgentHost.contribution.js'; +import './contrib/providers/remoteAgentHost/browser/webSocketAgentHost.contribution.js'; +import './contrib/providers/remoteAgentHost/browser/remoteAgentHost.contribution.js'; +import './contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.js'; +import './contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHost.contribution.js'; +import './contrib/providers/remoteAgentHost/browser/mobileHostFilter.contribution.js'; + +// Phone pickers for mode and model in the chat input +import './contrib/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.contribution.js'; +import './contrib/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.js'; + +// Agent feedback is not supported on web +import './contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.js'; + +//#endregion + + +//#region --- phone presentations of shared services + +// Must stay last: the service collection keeps the final registration for an +// id, so these override the implementations registered by everything above. +import './contrib/mobile/browser/mobile.contribution.js'; + +//#endregion diff --git a/src/vs/sessions/browser/actions/vscodeActions.ts b/src/vs/sessions/browser/actions/vscodeActions.ts index 64d771d3ae03..6bc10d87f2a2 100644 --- a/src/vs/sessions/browser/actions/vscodeActions.ts +++ b/src/vs/sessions/browser/actions/vscodeActions.ts @@ -13,6 +13,8 @@ import { Action2 } from '../../../platform/actions/common/actions.js'; import { AGENT_HOST_SCHEME, fromAgentHostUri } from '../../../platform/agentHost/common/agentHostUri.js'; import { IRemoteAgentHostService } from '../../../platform/agentHost/common/remoteAgentHostService.js'; import { IAgentHostConnectionsService } from '../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { ISSHRemoteAgentHostService } from '../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService } from '../../../platform/agentHost/common/tunnelAgentHost.js'; import { INotificationService } from '../../../platform/notification/common/notification.js'; import { ContextKeyExpr } from '../../../platform/contextkey/common/contextkey.js'; @@ -92,7 +94,7 @@ export class OpenInVSCodeAction extends Action2 { const remoteAuthority = resolveRemoteAuthority( activeSession.providerId, sessionsProvidersService, remoteAgentHostService); - const chatSession = getEditorWindowSessionResource(context?.chat.resource ?? activeSession.resource, activeSession.providerId, sessionsProvidersService, remoteAgentHostService, accessor.get(IAgentHostConnectionsService), accessor.get(ITunnelAgentHostService)); + const chatSession = getEditorWindowSessionResource(context?.chat.resource ?? activeSession.resource, activeSession.providerId, sessionsProvidersService, remoteAgentHostService, accessor.get(IAgentHostConnectionsService), accessor.get(ITunnelAgentHostService), accessor.get(ISSHRemoteAgentHostService), accessor.get(IRemoteAgentHostLocationPreferenceService)); if (URI.isUri(chatSession)) { params.set('session', chatSession.toString()); } else { diff --git a/src/vs/sessions/browser/agentsWindowMenus.ts b/src/vs/sessions/browser/agentsWindowMenus.ts index 738389f83ad0..e44b07ea6be5 100644 --- a/src/vs/sessions/browser/agentsWindowMenus.ts +++ b/src/vs/sessions/browser/agentsWindowMenus.ts @@ -68,7 +68,7 @@ export const AgentsWindowMenus = { * {@link AgentsWindowMenus.SessionActivityBarCanvas}, top to bottom, each shown under a title. */ export const SessionCanvasMenuGroup = { - /** The active chat's canvases whose tab was closed but which are still running. */ + /** The active chat's running canvases, whether or not their tab is open. */ Running: '1_running', /** The canvases that can be opened: the active chat's canvas types and the window's canvases. */ Available: '2_available', diff --git a/src/vs/sessions/browser/floatingAuxiliaryBarController.ts b/src/vs/sessions/browser/floatingAuxiliaryBarController.ts new file mode 100644 index 000000000000..8c2a6ab4b80e --- /dev/null +++ b/src/vs/sessions/browser/floatingAuxiliaryBarController.ts @@ -0,0 +1,660 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/floatingAuxiliaryBar.css'; +import { $, addDisposableListener, append, Dimension, EventType, getActiveElement, IDimension, isHTMLElement, trackFocus } from '../../base/browser/dom.js'; +import { GlobalPointerMoveMonitor } from '../../base/browser/globalPointerMoveMonitor.js'; +import { StandardKeyboardEvent } from '../../base/browser/keyboardEvent.js'; +import { ActionBar } from '../../base/browser/ui/actionbar/actionbar.js'; +import { ActionViewItem } from '../../base/browser/ui/actionbar/actionViewItems.js'; +import { ResizableHTMLElement } from '../../base/browser/ui/resizable/resizable.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, MutableDisposable, toDisposable } from '../../base/common/lifecycle.js'; +import { clamp } from '../../base/common/numbers.js'; +import { ThemeIcon } from '../../base/common/themables.js'; +import { assertReturnsDefined } from '../../base/common/types.js'; +import { localize } from '../../nls.js'; +import { IAccessibilityService } from '../../platform/accessibility/common/accessibility.js'; +import { IHoverService } from '../../platform/hover/browser/hover.js'; +import { registerIcon } from '../../platform/theme/common/iconRegistry.js'; +import { Part } from '../../workbench/browser/part.js'; + +const keepExpandedIcon = registerIcon('sessions-floating-details-keep-expanded', Codicon.pin, localize('floatingDetails.keepExpandedIcon', "Icon for keeping a floating panel expanded.")); +const pinnedIcon = registerIcon('sessions-floating-details-pinned', Codicon.pinned, localize('floatingDetails.pinnedIcon', "Icon for a floating panel that stays expanded.")); +const detailsIcon = registerIcon('sessions-floating-details-view', Codicon.listTree, localize('floatingDetails.viewIcon', "Icon for the floating details view.")); +const dragIcon = registerIcon('sessions-floating-details-drag', Codicon.gripper, localize('floatingDetails.dragIcon', "Icon for moving a floating panel.")); + +type FloatingDetailsState = 'collapsed' | 'preview' | 'pinned'; + +interface IFloatingDetailsPosition { + readonly horizontal: 'left' | 'right'; + readonly vertical: 'top' | 'bottom'; + readonly x: number; + readonly y: number; +} + +const defaultPosition: IFloatingDetailsPosition = { horizontal: 'right', vertical: 'top', x: 0, y: 0 }; + +class FloatingDetailsToggleViewItem extends ActionViewItem { + private stateIcon: HTMLElement | undefined; + + override render(container: HTMLElement): void { + super.render(container); + const label = assertReturnsDefined(this.label); + label.classList.add('floating-details-toggle'); + this.stateIcon = append(label, $('span.floating-details-state-icon', { 'aria-hidden': 'true' })); + } + + setIcon(icon: ThemeIcon): void { + assertReturnsDefined(this.stateIcon).className = `floating-details-state-icon ${ThemeIcon.asClassName(icon)}`; + } + + setExpanded(expanded: boolean, controlsId?: string): void { + this.label?.setAttribute('aria-expanded', String(expanded)); + if (controlsId) { + this.label?.setAttribute('aria-controls', controlsId); + } + } +} + +export interface IFloatingAuxiliaryBarHost { + getTitle(): string; + getIcon(): ThemeIcon | undefined; + isChangesViewActive(): boolean; + readonly onDidChangeTitle: Event; + getWidth(): number; + setWidth(width: number): void; + getHeight(): number; + setHeight(height: number): void; + getContentHeight(): number | undefined; + readonly onDidChangeContentHeight: Event; + setSizeToContent(enabled: boolean): void; + focusEditor(): void; +} + +/** Presents the existing details part as a non-modal, resizable editor overlay. */ +export class FloatingAuxiliaryBarController extends Disposable { + private static readonly GAP = 8; + private static readonly HEADER_HEIGHT = 32; + private readonly resizable = this._register(new ResizableHTMLElement()); + private readonly surface = append(this.resizable.domNode, $('.floating-details-surface')); + private readonly widthHandle: HTMLElement; + private readonly heightHandle: HTMLElement; + private readonly toggleAction: Action; + private readonly toggleViewItem: FloatingDetailsToggleViewItem; + private readonly titleIcon: HTMLElement; + private readonly titleText: HTMLElement; + private readonly dragHandle: HTMLElement; + private readonly dragMonitor = this._register(new GlobalPointerMoveMonitor()); + private position = defaultPosition; + private state: FloatingDetailsState = 'collapsed'; + private visible = false; + private pointerInside = false; + private resizing = false; + private renderedSize = new Dimension(0, 0); + private compactSize = new Dimension(0, 0); + private readonly motion = this._register(new MutableDisposable()); + private readonly hoverExit = this._register(new RunOnceScheduler(() => { + if (!this.hasFocus()) { + this.collapsePreview(); + } + }, 250)); + private readonly contentLayout = this._register(new RunOnceScheduler(() => this.layoutContent(), 0)); + + constructor( + private readonly editorContainer: HTMLElement, + private readonly auxiliaryBarPart: Pick, + private readonly host: IFloatingAuxiliaryBarHost, + @IAccessibilityService private readonly accessibilityService: IAccessibilityService, + @IHoverService hoverService: IHoverService, + ) { + super(); + this.resizable.domNode.classList.add('floating-details'); + this.resizable.domNode.setAttribute('role', 'region'); + const header = append(this.surface, $('.floating-details-header')); + const caption = append(header, $('.floating-details-caption')); + this.titleIcon = append(caption, $('span.floating-details-icon', { 'aria-hidden': 'true' })); + this.titleText = append(caption, $('span.floating-details-title')); + this._register(hoverService.setupDelayedHover(caption, () => ({ content: this.host.getTitle() }))); + this._register(addDisposableListener(caption, EventType.MOUSE_ENTER, (event: MouseEvent) => { + if (isHTMLElement(event.relatedTarget) && this.dragHandle.contains(event.relatedTarget)) { + this.preview(); + } + })); + this.toggleAction = this._register(new Action('sessions.floatingDetails.toggle', '', '', true, () => this.setPinned(this.state !== 'pinned'))); + let toggleViewItem: FloatingDetailsToggleViewItem | undefined; + const actions = this._register(new ActionBar(header, { + ariaLabel: localize('floatingDetails.actions', "Panel Actions"), + actionViewItemProvider: (action, options) => toggleViewItem = new FloatingDetailsToggleViewItem(undefined, action, { ...options, icon: false, label: false }), + })); + actions.push(this.toggleAction, { icon: true, label: false }); + this.toggleViewItem = assertReturnsDefined(toggleViewItem); + this._register(actions.onDidCancel(() => this.collapse())); + this.dragHandle = append(header, $('.floating-details-drag-handle', { role: 'button', tabIndex: 0 })); + append(this.dragHandle, $('span', { 'aria-hidden': 'true' })).classList.add(...ThemeIcon.asClassNameArray(dragIcon)); + this._register(hoverService.setupDelayedHover(this.dragHandle, { + content: localize('floatingDetails.moveHint', "Drag to move. Use Arrow keys to move, Shift for larger steps, or Home to reset. Double-click to reset the position."), + })); + this._register(addDisposableListener(this.dragHandle, EventType.POINTER_DOWN, (event: PointerEvent) => this.startDragging(event))); + this._register(addDisposableListener(this.dragHandle, 'pointercancel', () => this.dragMonitor.stopMonitoring(true))); + this._register(addDisposableListener(this.dragHandle, EventType.DBLCLICK, () => this.resetPosition())); + this._register(addDisposableListener(this.dragHandle, EventType.KEY_DOWN, event => { + const key = new StandardKeyboardEvent(event); + const step = key.shiftKey ? 50 : 10; + if (key.keyCode === KeyCode.Home) { + key.preventDefault(); + key.stopPropagation(); + this.resetPosition(); + } else if (key.keyCode >= KeyCode.LeftArrow && key.keyCode <= KeyCode.DownArrow) { + key.preventDefault(); + key.stopPropagation(); + this.move(key.keyCode === KeyCode.LeftArrow ? -step : key.keyCode === KeyCode.RightArrow ? step : 0, + key.keyCode === KeyCode.UpArrow ? -step : key.keyCode === KeyCode.DownArrow ? step : 0); + } + })); + this._register(addDisposableListener(actions.domNode, EventType.MOUSE_ENTER, () => this.preview())); + this.widthHandle = this.createResizeHandle('width'); + this.heightHandle = this.createResizeHandle('height'); + this.updateTitle(); + this._register(this.host.onDidChangeTitle(() => { + this.updateTitle(); + this.scheduleContentLayout(); + })); + this._register(this.host.onDidChangeContentHeight(() => this.scheduleContentLayout())); + this._register(accessibilityService.onDidChangeReducedMotion(() => { + if (accessibilityService.isMotionReduced() && this.motion.value) { + this.motion.clear(); + if (this.visible) { + this.layout(this.contentTop); + } + } + })); + this.resizable.preferredSize = new Dimension(300, 400); + this._register(this.resizable.onDidWillResize(() => { + this.hoverExit.cancel(); + this.resizing = true; + })); + this._register(this.resizable.onDidResize(event => { + if (this.visible && this.state !== 'collapsed') { + if (event.reset === 'height' || (event.north || event.south) && event.dimension.height !== this.renderedSize.height) { + this.host.setHeight(event.reset === 'height' ? 400 : event.dimension.height); + } + if (event.reset === 'width' || (event.east || event.west) && event.dimension.width !== this.renderedSize.width) { + this.host.setWidth(event.reset === 'width' ? 300 : event.dimension.width); + } + this.layout(this.contentTop); + } + if (event.done) { + this.resizing = false; + this.scheduleContentLayout(); + if (this.visible && !this.pointerInside) { + this.schedulePreviewCollapse(); + } + } + })); + this._register(addDisposableListener(this.resizable.domNode, EventType.MOUSE_ENTER, (event: MouseEvent) => { + this.hoverExit.cancel(); + this.pointerInside = true; + const grip = this.dragHandle.getBoundingClientRect(); + if (event.clientX < grip.left || event.clientX >= grip.right || event.clientY < grip.top || event.clientY >= grip.bottom) { + this.preview(); + } + })); + this._register(addDisposableListener(this.resizable.domNode, EventType.MOUSE_LEAVE, () => { + this.pointerInside = false; + if (!this.resizing && !this.dragMonitor.isMonitoring()) { + this.schedulePreviewCollapse(); + } + })); + this._register(addDisposableListener(this.resizable.domNode, EventType.FOCUS, () => { + if (this.state === 'collapsed') { + this.preview(); + this.toggleViewItem.focus(); + } + })); + const focus = this._register(trackFocus(this.resizable.domNode)); + this._register(focus.onDidFocus(() => { + this.hoverExit.cancel(); + const activeElement = getActiveElement(); + if (activeElement !== this.dragHandle && activeElement !== this.resizable.domNode) { + this.preview(); + } + })); + this._register(focus.onDidBlur(() => { + if (!this.pointerInside && !this.resizing && !this.dragMonitor.isMonitoring() && !this.hoverExit.isScheduled()) { + this.collapsePreview(); + } + })); + this._register(addDisposableListener(this.resizable.domNode, EventType.KEY_DOWN, event => { + if (!event.defaultPrevented && new StandardKeyboardEvent(event).keyCode === KeyCode.Escape) { + event.preventDefault(); + event.stopPropagation(); + this.collapse(); + } + })); + } + + private contentTop = 0; + + layout(contentTop: number): void { + this.stopDragging(); + this.motion.clear(); + this.contentTop = contentTop; + this.updateTitle(); + const part = this.auxiliaryBarPart.getContainer(); + if (!part) { + return; + } + this.visible = true; + this.editorContainer.classList.add('floating-details-visible'); + this.host.setSizeToContent(true); + if (part.id) { + this.toggleViewItem.setExpanded(this.state !== 'collapsed', part.id); + } + const focusedElement = getActiveElement(); + if (this.resizable.domNode.parentElement !== this.editorContainer) { + append(this.editorContainer, this.resizable.domNode); + } + if (part.parentElement !== this.surface) { + append(this.surface, part); + } + part.classList.add('floating-auxiliarybar'); + const { x, y, maxWidth, maxHeight } = this.getAvailableSpace(); + this.resizable.domNode.style.display = ''; + this.applyPosition(x, y); + this.resizable.domNode.style.maxWidth = `${maxWidth}px`; + const expanded = this.state !== 'collapsed'; + this.resizable.domNode.classList.toggle('collapsed', !expanded); + this.widthHandle.hidden = !expanded; + this.heightHandle.hidden = !expanded; + const left = this.position.horizontal === 'left'; + const bottom = this.position.vertical === 'bottom'; + this.resizable.enableSashes(expanded && bottom, expanded && left, expanded && !bottom, expanded && !left); + if (!expanded) { + this.resizable.domNode.style.width = 'max-content'; + this.resizable.domNode.style.height = `${Math.min(FloatingAuxiliaryBarController.HEADER_HEIGHT + 2, maxHeight)}px`; + part.style.display = 'none'; + if (isHTMLElement(focusedElement) && part.contains(focusedElement)) { + this.host.focusEditor(); + } + const bounds = this.resizable.domNode.getBoundingClientRect(); + this.compactSize = new Dimension(bounds.width, bounds.height); + return; + } + const heightLimits = this.getHeightLimits(maxHeight); + this.resizable.minSize = new Dimension(Math.min(220, maxWidth), heightLimits.minimum); + this.resizable.maxSize = new Dimension(maxWidth, heightLimits.maximum); + this.resizable.layout(heightLimits.height, this.host.getWidth()); + const { width, height } = this.resizable.size; + this.renderedSize = this.resizable.size; + this.resizable.domNode.style.width = `${width}px`; + this.resizable.domNode.style.height = `${height}px`; + part.style.display = ''; + part.style.position = 'absolute'; + part.style.left = left ? '0' : ''; + part.style.right = left ? '' : '0'; + part.style.top = bottom ? '' : `${FloatingAuxiliaryBarController.HEADER_HEIGHT}px`; + part.style.bottom = bottom ? `${FloatingAuxiliaryBarController.HEADER_HEIGHT}px` : ''; + part.style.width = `${Math.max(0, width - 2)}px`; + part.style.height = `${Math.max(0, height - FloatingAuxiliaryBarController.HEADER_HEIGHT - 2)}px`; + this.auxiliaryBarPart.layout(Math.max(0, width - 2), Math.max(0, height - FloatingAuxiliaryBarController.HEADER_HEIGHT - 2), + bottom ? this.editorContainer.clientHeight - FloatingAuxiliaryBarController.GAP - y - height : contentTop + FloatingAuxiliaryBarController.GAP + y + FloatingAuxiliaryBarController.HEADER_HEIGHT, + left ? FloatingAuxiliaryBarController.GAP + x : this.editorContainer.clientWidth - width - FloatingAuxiliaryBarController.GAP - x); + this.updateResizeHandle(this.widthHandle, width, this.resizable.minSize.width, maxWidth); + this.updateResizeHandle(this.heightHandle, height, this.resizable.minSize.height, heightLimits.maximum); + if (isHTMLElement(focusedElement) && part.contains(focusedElement) && getActiveElement() !== focusedElement) { + focusedElement.focus(); + } + } + + hide(): void { + this.stopDragging(); + this.hoverExit.cancel(); + this.motion.clear(); + this.visible = false; + this.editorContainer.classList.remove('floating-details-visible'); + this.contentLayout.cancel(); + this.host.setSizeToContent(false); + this.pointerInside = false; + this.resizing = false; + if (this.state === 'preview') { + this.setState('collapsed'); + } + const part = this.auxiliaryBarPart.getContainer(); + if (part?.parentElement === this.surface) { + const focusedElement = getActiveElement(); + part.style.left = ''; + part.style.bottom = ''; + append(this.editorContainer, part); + part.classList.remove('floating-auxiliarybar'); + if (isHTMLElement(focusedElement) && part.contains(focusedElement)) { + focusedElement.focus(); + } + } + this.resizable.domNode.style.display = 'none'; + } + + setPinned(pinned: boolean): void { + const keepPreview = this.visible && (this.pointerInside || this.hasFocus()); + this.setState(pinned ? 'pinned' : keepPreview ? 'preview' : 'collapsed'); + } + + /** Returns the effective expanded geometry without changing compact presentation. */ + getSize(): Dimension { + const { maxWidth, maxHeight } = this.getAvailableSpace(); + return new Dimension(clamp(this.host.getWidth(), Math.min(220, maxWidth), maxWidth), this.getHeightLimits(maxHeight).height); + } + + setSize(size: IDimension): void { + const current = this.getSize(); + const { maxWidth, maxHeight } = this.getAvailableSpace(); + const heightLimits = this.getHeightLimits(maxHeight); + const width = clamp(size.width, Math.min(220, maxWidth), maxWidth); + const height = clamp(size.height, heightLimits.minimum, heightLimits.maximum); + if (height !== current.height) { + this.host.setHeight(height); + } + if (width !== current.width) { + this.host.setWidth(width); + } + if (this.visible) { + this.layout(this.contentTop); + } + } + + hasFocus(): boolean { + const activeElement = getActiveElement(); + return !!activeElement && this.resizable.domNode.contains(activeElement); + } + + /** Opening an item immediately dismisses a preview without motion, but never a pinned panel. */ + onDidOpenItem(): void { + this.collapsePreview(false); + } + + private collapsePreview(animate = true): void { + if (this.state === 'preview') { + this.collapse(animate); + } + } + + private preview(): void { + if (this.state === 'collapsed' && !this.dragMonitor.isMonitoring()) { + this.setState('preview'); + } + } + + private schedulePreviewCollapse(): void { + if (this.state === 'preview' && this.visible && !this.pointerInside && !this.hasFocus() && !this.resizing && !this.dragMonitor.isMonitoring()) { + this.hoverExit.schedule(); + } + } + + private scheduleContentLayout(): void { + if (this.visible && this.state !== 'collapsed') { + this.contentLayout.schedule(); + } + } + + private getHeightLimits(availableHeight: number): { minimum: number; maximum: number; height: number } { + const contentHeight = this.host.getContentHeight(); + const maximum = Math.min(availableHeight, contentHeight === undefined ? availableHeight : contentHeight + FloatingAuxiliaryBarController.HEADER_HEIGHT + 2); + const minimum = Math.min(160, maximum); + return { minimum, maximum, height: clamp(this.host.getHeight(), minimum, maximum) }; + } + + private layoutContent(): void { + if (!this.visible || this.state === 'collapsed' || this.resizing || this.dragMonitor.isMonitoring()) { + return; + } + const limits = this.getHeightLimits(this.getAvailableSpace().maxHeight); + if (limits.height !== this.renderedSize.height || limits.maximum !== this.resizable.maxSize.height) { + const from = this.motion.value ? this.resizable.domNode.getBoundingClientRect() : undefined; + this.layout(this.contentTop); + if (from) { + this.animateFrame(from, this.resizable.domNode.getBoundingClientRect()); + } + } + } + + private getAvailableSize(): Dimension { + return new Dimension(Math.max(0, this.editorContainer.clientWidth - FloatingAuxiliaryBarController.GAP * 2), + Math.max(0, this.editorContainer.clientHeight - this.contentTop - FloatingAuxiliaryBarController.GAP * 2)); + } + + private getAvailableSpace(): { x: number; y: number; maxWidth: number; maxHeight: number } { + const area = this.getAvailableSize(); + const x = clamp(this.position.x, 0, Math.max(0, area.width - FloatingAuxiliaryBarController.HEADER_HEIGHT - 2)); + const y = clamp(this.position.y, 0, Math.max(0, area.height - FloatingAuxiliaryBarController.HEADER_HEIGHT - 2)); + return { x, y, maxWidth: area.width - x, maxHeight: area.height - y }; + } + + private applyPosition(x: number, y: number): void { + const element = this.resizable.domNode; + const left = this.position.horizontal === 'left'; + const bottom = this.position.vertical === 'bottom'; + element.classList.toggle('anchored-left', left); + element.classList.toggle('anchored-bottom', bottom); + element.style.left = left ? `${FloatingAuxiliaryBarController.GAP + x}px` : ''; + element.style.right = left ? '' : `${FloatingAuxiliaryBarController.GAP + x}px`; + element.style.top = bottom ? '' : `${this.contentTop + FloatingAuxiliaryBarController.GAP + y}px`; + element.style.bottom = bottom ? `${FloatingAuxiliaryBarController.GAP + y}px` : ''; + } + + private move(deltaX: number, deltaY: number): void { + const element = this.resizable.domNode; + const area = this.getAvailableSize(); + const bounds = element.getBoundingClientRect(); + const maximumX = Math.max(0, area.width - bounds.width); + const maximumY = Math.max(0, area.height - bounds.height); + const editor = this.editorContainer.getBoundingClientRect(); + const x = clamp(bounds.left - editor.left - this.editorContainer.clientLeft - FloatingAuxiliaryBarController.GAP + deltaX, 0, maximumX); + const y = clamp(bounds.top - editor.top - this.editorContainer.clientTop - this.contentTop - FloatingAuxiliaryBarController.GAP + deltaY, 0, maximumY); + const horizontal = this.state === 'collapsed' ? (x > maximumX / 2 ? 'right' : 'left') : this.position.horizontal; + const vertical = this.state === 'collapsed' ? (y > maximumY / 2 ? 'bottom' : 'top') : this.position.vertical; + this.position = { horizontal, vertical, x: horizontal === 'left' ? x : maximumX - x, y: vertical === 'top' ? y : maximumY - y }; + this.layout(this.contentTop); + } + + private startDragging(event: PointerEvent): void { + if (event.button !== 0 || !this.visible) { + return; + } + event.preventDefault(); + event.stopPropagation(); + this.hoverExit.cancel(); + this.layout(this.contentTop); + const origin = this.resizable.domNode.getBoundingClientRect(); + const area = this.getAvailableSize(); + const editor = this.editorContainer.getBoundingClientRect(); + const left = origin.left - editor.left - this.editorContainer.clientLeft - FloatingAuxiliaryBarController.GAP; + const top = origin.top - editor.top - this.editorContainer.clientTop - this.contentTop - FloatingAuxiliaryBarController.GAP; + const position = { + ...this.position, + x: this.position.horizontal === 'left' ? left : area.width - origin.width - left, + y: this.position.vertical === 'top' ? top : area.height - origin.height - top, + }; + let point = { x: event.clientX, y: event.clientY }; + this.resizable.domNode.classList.add('dragging'); + this.dragMonitor.startMonitoring(this.dragHandle, event.pointerId, event.buttons, next => { + const deltaX = next.clientX - event.clientX; + const deltaY = next.clientY - event.clientY; + point = { x: next.clientX, y: next.clientY }; + this.position = { + ...position, + x: clamp(position.x + (position.horizontal === 'left' ? deltaX : -deltaX), 0, Math.max(0, area.width - origin.width)), + y: clamp(position.y + (position.vertical === 'top' ? deltaY : -deltaY), 0, Math.max(0, area.height - origin.height)), + }; + this.applyPosition(this.position.x, this.position.y); + }, () => { + this.resizable.domNode.classList.remove('dragging'); + this.move(0, 0); + const bounds = this.resizable.domNode.getBoundingClientRect(); + this.pointerInside = point.x >= bounds.left && point.x < bounds.right && point.y >= bounds.top && point.y < bounds.bottom; + if (!this.pointerInside) { + this.schedulePreviewCollapse(); + } + }); + } + + private stopDragging(): void { + this.dragMonitor.stopMonitoring(false); + this.resizable.domNode.classList.remove('dragging'); + } + + private resetPosition(): void { + this.position = defaultPosition; + this.layout(this.contentTop); + } + + private setState(state: FloatingDetailsState, animate = true): void { + this.hoverExit.cancel(); + if (this.state === state) { + return; + } + const expanded = this.state !== 'collapsed'; + const from = this.visible ? this.resizable.domNode.getBoundingClientRect() : undefined; + if (!expanded && from && !this.motion.value) { + this.compactSize = new Dimension(from.width, from.height); + } + this.state = state; + this.updateTitle(); + if (this.visible && expanded !== (state !== 'collapsed')) { + this.layout(this.contentTop); + if (animate && from) { + this.animateFrame(from, this.resizable.domNode.getBoundingClientRect()); + } + } + } + + private animateFrame(from: DOMRectReadOnly, to: DOMRectReadOnly): void { + if (this.accessibilityService.isMotionReduced() + || !this.editorContainer.closest('.monaco-enable-motion') + || from.width <= 0 || from.height <= 0 + || from.width === to.width && from.height === to.height) { + return; + } + const element = this.resizable.domNode; + const collapsing = this.state === 'collapsed'; + const distance = Math.max(Math.abs(to.width - from.width), Math.abs(to.height - from.height)); + const fullDistance = Math.max(Math.abs(this.renderedSize.width - this.compactSize.width), Math.abs(this.renderedSize.height - this.compactSize.height)); + const large = fullDistance > 240; + const fullDuration = collapsing ? (large ? 150 : 100) : (large ? 250 : 200); + const duration = Math.max(50, Math.round(fullDuration * Math.min(1, distance / Math.max(1, fullDistance)))); + // Fluent's decelerate/accelerate curves distinguish the reveal from its quicker dismissal. + const easing = collapsing ? 'cubic-bezier(0.9, 0.1, 1, 0.2)' : 'cubic-bezier(0.1, 0.9, 0.2, 1)'; + const part = this.auxiliaryBarPart.getContainer(); + const wasInert = part?.inert; + if (collapsing && part) { + part.style.display = ''; + part.inert = true; + } + element.classList.add('animating'); + element.style.width = `${to.width}px`; + element.style.height = `${to.height}px`; + this.resizable.enableSashes(false, false, false, false); + const animation = element.animate([ + { width: `${from.width}px`, height: `${from.height}px` }, + { width: `${to.width}px`, height: `${to.height}px` }, + ], { duration, easing }); + this.motion.value = toDisposable(() => { + animation.onfinish = null; + animation.cancel(); + element.classList.remove('animating'); + if (collapsing && part) { + part.inert = wasInert ?? false; + if (this.state === 'collapsed') { + part.style.display = 'none'; + } + } + }); + animation.onfinish = () => { + this.motion.clear(); + if (this.visible) { + this.layout(this.contentTop); + } + }; + } + + private collapse(animate = true): void { + this.stopDragging(); + const activeElement = getActiveElement(); + const part = this.auxiliaryBarPart.getContainer(); + const restoreControlFocus = isHTMLElement(activeElement) && this.resizable.domNode.contains(activeElement) && !part?.contains(activeElement); + this.setState('collapsed', animate); + if (restoreControlFocus) { + this.host.focusEditor(); + } + } + + private createResizeHandle(dimension: 'width' | 'height'): HTMLElement { + const handle = append(this.resizable.domNode, $(`.floating-details-resize-${dimension}`, { + role: 'separator', + tabIndex: 0, + 'aria-orientation': dimension === 'width' ? 'vertical' : 'horizontal', + })); + this._register(addDisposableListener(handle, EventType.KEY_DOWN, event => { + const key = new StandardKeyboardEvent(event); + const step = key.shiftKey ? 50 : 10; + const decrease = dimension === 'width' ? (this.position.horizontal === 'left' ? KeyCode.LeftArrow : KeyCode.RightArrow) + : this.position.vertical === 'bottom' ? KeyCode.DownArrow : KeyCode.UpArrow; + const increase = dimension === 'width' ? (this.position.horizontal === 'left' ? KeyCode.RightArrow : KeyCode.LeftArrow) + : this.position.vertical === 'bottom' ? KeyCode.UpArrow : KeyCode.DownArrow; + if (key.keyCode !== decrease && key.keyCode !== increase && key.keyCode !== KeyCode.Home) { + return; + } + key.preventDefault(); + key.stopPropagation(); + const current = this.resizable.size[dimension]; + const next = key.keyCode === KeyCode.Home ? (dimension === 'width' ? 300 : 400) : current + (key.keyCode === increase ? step : -step); + const value = Math.max(this.resizable.minSize[dimension], Math.min(this.resizable.maxSize[dimension], next)); + if (key.keyCode === KeyCode.Home || value !== current) { + if (dimension === 'width') { + this.host.setWidth(key.keyCode === KeyCode.Home ? 300 : value); + } else { + this.host.setHeight(key.keyCode === KeyCode.Home ? 400 : value); + } + this.layout(this.contentTop); + } + })); + return handle; + } + + private updateTitle(): void { + const title = this.host.getTitle(); + this.resizable.domNode.classList.toggle('changes-view-active', this.host.isChangesViewActive()); + this.titleIcon.className = `floating-details-icon ${ThemeIcon.asClassName(this.host.getIcon() ?? detailsIcon)}`; + this.titleText.textContent = title; + this.toggleViewItem.setIcon(this.state === 'pinned' ? pinnedIcon : keepExpandedIcon); + this.resizable.domNode.setAttribute('aria-label', title); + const expanded = this.state !== 'collapsed'; + this.resizable.domNode.tabIndex = expanded ? -1 : 0; + this.toggleAction.label = this.state === 'pinned' + ? localize('floatingDetails.unpin', "Unpin {0}", title) + : this.state === 'preview' + ? localize('floatingDetails.keepExpanded', "Keep {0} Expanded", title) + : localize('floatingDetails.expand', "Expand {0}", title); + this.toggleAction.checked = this.state === 'pinned'; + this.toggleViewItem.setExpanded(expanded); + this.dragHandle.setAttribute('aria-label', localize('floatingDetails.move', "Move {0}. Use Arrow keys to move, Shift for larger steps, or Home to reset.", title)); + this.widthHandle.setAttribute('aria-label', localize('floatingDetails.resizeWidth', "Resize {0} Width. Use Left and Right Arrow keys.", title)); + this.heightHandle.setAttribute('aria-label', localize('floatingDetails.resizeHeight', "Resize {0} Height. Use Up and Down Arrow keys.", title)); + } + + private updateResizeHandle(handle: HTMLElement, value: number, min: number, max: number): void { + handle.setAttribute('aria-valuenow', String(value)); + handle.setAttribute('aria-valuemin', String(min)); + handle.setAttribute('aria-valuemax', String(max)); + } + + override dispose(): void { + this.hide(); + super.dispose(); + } +} diff --git a/src/vs/sessions/browser/layoutActions.ts b/src/vs/sessions/browser/layoutActions.ts index 18bfca48b7cd..3c84045ff269 100644 --- a/src/vs/sessions/browser/layoutActions.ts +++ b/src/vs/sessions/browser/layoutActions.ts @@ -24,7 +24,7 @@ import { SessionsWelcomeVisibleContext, DesktopLayoutContext, IsPhoneLayoutConte import { MenuActivityBarSize } from '../../workbench/browser/parts/activitybar/menuActivityBar.js'; import { setSessionActivityBarSize } from '../../workbench/browser/parts/sessions/sessionActivityBarHost.js'; import { IStorageService } from '../../platform/storage/common/storage.js'; -import { CustomViewVisibleContext, SessionActivityBarLayoutActionsContext } from '../common/agentsWindowContextKeys.js'; +import { CustomViewVisibleContext, SessionActivityBarDockedContext, SessionActivityBarLayoutActionsContext } from '../common/agentsWindowContextKeys.js'; import { IConfigurationService } from '../../platform/configuration/common/configuration.js'; import { SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING, SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../workbench/contrib/sessions/common/sessionConfig.js'; @@ -279,7 +279,7 @@ MenuRegistry.appendMenuItem(AgentsWindowMenus.TitleBarAccessibility, { }); // The Session Activity Bar hosts these toggles in place of the title bar while it shows its layout actions. -const titleBarPanelWhen = ContextKeyExpr.and(IsAuxiliaryWindowContext.toNegated(), SessionsWelcomeVisibleContext.toNegated(), IsPhoneLayoutContext.negate(), SessionActivityBarLayoutActionsContext.negate()); +const titleBarPanelWhen = ContextKeyExpr.and(IsAuxiliaryWindowContext.toNegated(), SessionsWelcomeVisibleContext.toNegated(), IsPhoneLayoutContext.negate(), SessionActivityBarLayoutActionsContext.negate(), SessionActivityBarDockedContext.negate()); const sessionActivityBarPanelWhen = ContextKeyExpr.and(IsAuxiliaryWindowContext.toNegated(), SessionActivityBarLayoutActionsContext); const showPanelCommand = { diff --git a/src/vs/sessions/browser/media/floatingAuxiliaryBar.css b/src/vs/sessions/browser/media/floatingAuxiliaryBar.css new file mode 100644 index 000000000000..078fbf31d138 --- /dev/null +++ b/src/vs/sessions/browser/media/floatingAuxiliaryBar.css @@ -0,0 +1,240 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Keep pane scrollbars below floating details without trapping the shared frame beneath webviews. */ +.agent-sessions-workbench.dock-detail-panel .part.editor.floating-details-visible:not(.modal-editor-part) > .content .editor-group-container > .editor-container { + isolation: isolate; +} + +.agent-sessions-workbench .floating-details { + position: absolute; + z-index: 10; +} + +.agent-sessions-workbench .floating-details-surface { + position: relative; + width: 100%; + height: 100%; + box-sizing: border-box; + overflow: hidden; + border: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, var(--vscode-editorWidget-border, transparent)); + border-radius: var(--vscode-cornerRadius-large); + background: var(--vscode-editorWidget-background); + box-shadow: var(--vscode-shadow-md); +} + +.agent-sessions-workbench .floating-details.collapsed .floating-details-surface { + width: max-content; + max-width: 100%; +} + +.agent-sessions-workbench .floating-details.animating .floating-details-surface { + width: 100%; +} + +.agent-sessions-workbench .floating-details.collapsed.animating { + pointer-events: none; +} + +.agent-sessions-workbench .floating-details.collapsed.animating .floating-details-header { + pointer-events: auto; +} + +.agent-sessions-workbench .floating-details-header { + display: flex; + align-items: center; + justify-content: space-between; + height: 32px; + font-size: var(--vscode-fontSize-label1); + color: var(--vscode-icon-foreground); +} + +.agent-sessions-workbench .floating-details.anchored-bottom .floating-details-header { + position: relative; + top: calc(100% - 32px); +} + +.agent-sessions-workbench .floating-details-drag-handle { + display: flex; + align-items: center; + justify-content: center; + flex: 0 0 var(--vscode-spacing-size240); + align-self: stretch; + border-radius: var(--vscode-cornerRadius-small); + cursor: grab; + touch-action: none; +} + +.agent-sessions-workbench .floating-details-drag-handle .codicon { + font-size: var(--vscode-codiconFontSize); + opacity: 0.5; +} + +.agent-sessions-workbench .floating-details-drag-handle:hover, +.agent-sessions-workbench .floating-details-header .action-label.floating-details-toggle:hover { + 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 .floating-details.dragging .floating-details-drag-handle { + background-color: var(--vscode-toolbar-activeBackground); +} + +.agent-sessions-workbench .floating-details.dragging .floating-details-drag-handle { + cursor: grabbing; +} + +.agent-sessions-workbench .floating-details.dragging .floating-details-drag-handle .codicon, +.agent-sessions-workbench .floating-details-drag-handle:hover .codicon, +.agent-sessions-workbench .floating-details-drag-handle:focus-visible .codicon, +.agent-sessions-workbench.hc-black .floating-details-drag-handle .codicon, +.agent-sessions-workbench.hc-light .floating-details-drag-handle .codicon { + opacity: 1; +} + +.agent-sessions-workbench .floating-details:focus-visible, +.agent-sessions-workbench .floating-details-drag-handle:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.agent-sessions-workbench .floating-details-title { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + font-weight: var(--vscode-fontWeight-semiBold); +} + +.agent-sessions-workbench .floating-details-caption { + display: flex; + align-items: center; + flex: 1; + min-width: 0; + gap: var(--vscode-spacing-size60); + padding: 0 var(--vscode-spacing-size80); + cursor: default; +} + +.agent-sessions-workbench .floating-details-header > .monaco-action-bar { + flex: 0 0 auto; +} + +.agent-sessions-workbench .floating-details.collapsed .floating-details-header > .monaco-action-bar { + display: none; +} + +.agent-sessions-workbench .floating-details-header .actions-container, +.agent-sessions-workbench .floating-details-header .action-item { + margin: 0; +} + +.agent-sessions-workbench .floating-details-header .action-label.floating-details-toggle { + display: flex; + align-items: center; + justify-content: center; + width: var(--vscode-spacing-size240); + height: var(--vscode-spacing-size240); + box-sizing: border-box; + padding: 0; + border-radius: var(--vscode-cornerRadius-small); + color: inherit; +} + +.agent-sessions-workbench .floating-details-icon, +.agent-sessions-workbench .floating-details-state-icon { + flex-shrink: 0; + font-size: var(--vscode-codiconFontSize); +} + +.agent-sessions-workbench.dock-detail-panel .part.auxiliarybar.floating-auxiliarybar { + --vscode-agentsDetail-background: var(--vscode-editorWidget-background); + --vscode-sideBar-background: var(--vscode-editorWidget-background); + border: 0; +} + +.agent-sessions-workbench.dock-detail-panel .part.auxiliarybar.floating-auxiliarybar::before { + display: none; +} + +.agent-sessions-workbench .floating-details-resize-width, +.agent-sessions-workbench .floating-details-resize-height { + position: absolute; + pointer-events: none; +} + +.agent-sessions-workbench .floating-details.anchored-left .floating-details-resize-width { + left: auto; + right: 0; +} + +.agent-sessions-workbench .floating-details.anchored-bottom .floating-details-resize-height { + bottom: auto; + top: 0; +} + +.agent-sessions-workbench .floating-details-resize-width { + left: 0; + top: 0; + width: var(--vscode-spacing-size40); + height: 100%; +} + +.agent-sessions-workbench .floating-details-resize-height { + left: 0; + bottom: 0; + width: 100%; + height: var(--vscode-spacing-size40); +} + +.agent-sessions-workbench .floating-details [role="separator"]:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: -1px; +} + +.agent-sessions-workbench.hc-black .floating-details-surface, +.agent-sessions-workbench.hc-light .floating-details-surface { + box-shadow: none; +} + +@supports (backdrop-filter: blur(12px)) and (background-color: color-mix(in srgb, black 92%, transparent)) { + @media (prefers-reduced-transparency: no-preference) and (forced-colors: none) { + .monaco-workbench.agent-sessions-workbench.modern-ui-frosted-glass:not(.hc-black):not(.hc-light) .floating-details-surface { + --modern-ui-glass-background: color-mix(in srgb, var(--vscode-editorWidget-background) var(--modern-ui-glass-opacity, 92%), transparent); + background: transparent; + isolation: isolate; + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + pointer-events: none; + background-color: var(--modern-ui-glass-background); + backdrop-filter: blur(12px); + } + + & .part.auxiliarybar.floating-auxiliarybar { + --vscode-agentsDetail-background: transparent; + --vscode-sideBar-background: transparent; + } + } + + .monaco-workbench.agent-sessions-workbench.modern-ui-frosted-glass:not(.hc-black):not(.hc-light) .floating-details.changes-view-active .floating-details-surface { + background: var(--vscode-editor-background); + + &::before { + display: none; + } + + @supports (color: rgb(from red r g b / 1)) { + background: rgb(from var(--vscode-editorWidget-background) r g b / 1); + } + } + } +} diff --git a/src/vs/sessions/browser/media/openInVSCode.css b/src/vs/sessions/browser/media/openInVSCode.css index 5d89e0be650f..5108484511c3 100644 --- a/src/vs/sessions/browser/media/openInVSCode.css +++ b/src/vs/sessions/browser/media/openInVSCode.css @@ -10,7 +10,7 @@ height: 22px; padding: 0 4px; margin: 0 4px 0 2px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); cursor: pointer; color: var(--vscode-titleBar-activeForeground); -webkit-app-region: no-drag; @@ -53,7 +53,7 @@ transition-duration: 0ms !important; } -.monaco-workbench .open-in-vscode-titlebar-widget:hover > .open-in-vscode-titlebar-widget-icon, +.monaco-workbench .open-in-vscode-titlebar-widget:is(:hover, .hovered) > .open-in-vscode-titlebar-widget-icon, .monaco-workbench .open-in-vscode-titlebar-widget:focus-visible > .open-in-vscode-titlebar-widget-icon { filter: none; } @@ -75,9 +75,9 @@ transition-delay: 200ms; } -.monaco-enable-motion .monaco-workbench .open-in-vscode-titlebar-widget:hover > .open-in-vscode-titlebar-widget-label, +.monaco-enable-motion .monaco-workbench .open-in-vscode-titlebar-widget:is(:hover, .hovered) > .open-in-vscode-titlebar-widget-label, .monaco-enable-motion .monaco-workbench .open-in-vscode-titlebar-widget:focus-visible > .open-in-vscode-titlebar-widget-label, -.monaco-workbench.monaco-enable-motion .open-in-vscode-titlebar-widget:hover > .open-in-vscode-titlebar-widget-label, +.monaco-workbench.monaco-enable-motion .open-in-vscode-titlebar-widget:is(:hover, .hovered) > .open-in-vscode-titlebar-widget-label, .monaco-workbench.monaco-enable-motion .open-in-vscode-titlebar-widget:focus-visible > .open-in-vscode-titlebar-widget-label { transition-delay: 0ms; } @@ -87,20 +87,9 @@ transition-duration: 0ms !important; } -.monaco-workbench .open-in-vscode-titlebar-widget:hover, -.monaco-workbench .open-in-vscode-titlebar-widget:focus-visible { - background-color: var(--vscode-toolbar-hoverBackground); - outline: none; -} - -.monaco-workbench .open-in-vscode-titlebar-widget:hover > .open-in-vscode-titlebar-widget-label, +.monaco-workbench .open-in-vscode-titlebar-widget:is(:hover, .hovered) > .open-in-vscode-titlebar-widget-label, .monaco-workbench .open-in-vscode-titlebar-widget:focus-visible > .open-in-vscode-titlebar-widget-label { max-width: 200px; opacity: 1; margin-left: 6px; } - -.monaco-workbench .open-in-vscode-titlebar-widget:focus-visible { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; -} diff --git a/src/vs/sessions/browser/media/sessionsSetUp.css b/src/vs/sessions/browser/media/sessionsSetUp.css index 7056164caed7..fa8e5028257a 100644 --- a/src/vs/sessions/browser/media/sessionsSetUp.css +++ b/src/vs/sessions/browser/media/sessionsSetUp.css @@ -55,7 +55,7 @@ margin: var(--vscode-spacing-size80) auto 0; padding: var(--vscode-spacing-size20) var(--vscode-spacing-size40); border: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); background-color: transparent; color: var(--vscode-descriptionForeground); font-size: var(--vscode-fontSize-body2); diff --git a/src/vs/sessions/browser/media/style.css b/src/vs/sessions/browser/media/style.css index ce26a8526a09..a9eb07cea31c 100644 --- a/src/vs/sessions/browser/media/style.css +++ b/src/vs/sessions/browser/media/style.css @@ -12,12 +12,71 @@ border-radius: var(--vscode-cornerRadius-small); } +.agent-sessions-workbench .monaco-action-bar:not(.vertical) .action-label { + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); +} + .agent-sessions-workbench .monaco-action-bar .action-item .action-label.separator { margin: 0px 4px !important; } .agent-sessions-workbench .monaco-dropdown-with-default { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); +} + +/* ---- Interactive Controls ---- */ + +.agent-sessions-interactive:not(.agent-sessions-interactive-list):is(:hover, .hovered):not(.disabled, :disabled, [aria-disabled='true'], :active, [aria-expanded='true'], [aria-pressed='true'], .menu-visible, :focus-visible, .focus-visible) { + background-color: var(--vscode-toolbar-hoverBackground); + outline: var(--vscode-strokeThickness) dashed var(--vscode-toolbar-hoverOutline, transparent); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.agent-sessions-interactive.agent-sessions-interactive-list:is(:hover, .hovered):not(.disabled, :disabled, [aria-disabled='true'], :active, [aria-expanded='true'], [aria-pressed='true'], :focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder, transparent); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.agent-sessions-interactive.agent-sessions-interactive-list:not(.checked, .selected, [aria-selected='true'], [aria-checked='true']):is(:hover, .hovered):not(.disabled, :disabled, [aria-disabled='true'], :active, [aria-expanded='true'], [aria-pressed='true'], :focus-visible, .focus-visible) { + background-color: var(--vscode-list-hoverBackground); +} + +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .agent-sessions-interactive:is(:active, [aria-expanded='true'], [aria-pressed='true']):not(.disabled, :disabled, [aria-disabled='true'], :focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.agent-sessions-interactive:is(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.agent-sessions-interactive.agent-sessions-interactive-list:is(:focus-visible, .focus-visible) { + outline-color: var(--vscode-list-focusOutline, var(--vscode-focusBorder)); +} + +:is(.hc-black, .hc-light) .agent-sessions-interactive-bordered:is(:hover, .hovered, :active, [aria-expanded='true'], [aria-pressed='true'], :focus-visible, .focus-visible):not(.disabled, :disabled, [aria-disabled='true']) { + border-color: transparent; +} + +:is(.hc-black, .hc-light) .agent-sessions-interactive-bordered:is(:focus-visible, .focus-visible) { + outline-width: calc(2 * var(--vscode-strokeThickness)); + outline-offset: calc(-2 * var(--vscode-strokeThickness)); +} + +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .monaco-button:is(:hover, .hovered):not(.disabled, :disabled, [aria-disabled='true'], :active, [aria-expanded='true'], [aria-pressed='true'], :focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .monaco-button:is(:active, [aria-expanded='true'], [aria-pressed='true']):not(.disabled, :disabled, [aria-disabled='true'], :focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .monaco-button:is(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); } /* ---- Scrollbars ---- */ @@ -92,7 +151,7 @@ } .agent-sessions-workbench .quick-input-header { - border-radius: var(--vscode-cornerRadius-xLarge); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-xLarge)); } /* ---- Sessions Context Menus ---- */ diff --git a/src/vs/sessions/browser/media/workbench.css b/src/vs/sessions/browser/media/workbench.css index b850fca53ee6..18730c5259ff 100644 --- a/src/vs/sessions/browser/media/workbench.css +++ b/src/vs/sessions/browser/media/workbench.css @@ -9,7 +9,8 @@ * The hover is portaled but mounts inside this workbench root, so it inherits this value. */ .monaco-workbench.agent-sessions-workbench { background-color: var(--vscode-agents-background); - --agents-floating-panel-gap: var(--vscode-agents-layout-floatingPanelGap); + --agents-floating-panel-gap: var(--vscode-agentsWindow-panels-spacing, var(--vscode-agents-layout-floatingPanelGap)); + --agents-outer-panel-gap: var(--vscode-agents-layout-floatingPanelGap); --part-grid-gap: var(--agents-floating-panel-gap); --agents-part-corner-radius: var(--vscode-cornerRadius-large); --agents-session-frame-inset: 0px; @@ -20,8 +21,29 @@ --modern-ui-notifications-block-start-inset: var(--vscode-spacing-size400); } +.monaco-workbench.agent-sessions-workbench:not(.modern-ui-compact) .agents-part-card { + --agents-component-corner-radius: var(--vscode-pages-cornerRadius, var(--agents-part-corner-radius)); +} + +.monaco-workbench.agent-sessions-workbench:not(.modern-ui-compact) .part.sessionspart { + --agents-component-corner-radius: var(--vscode-agentsWindow-chatPanels-cornerRadius, var(--agents-part-corner-radius)); +} + +.monaco-workbench.agent-sessions-workbench:not(.modern-ui-compact) .part.editor:not(.modal-editor-part) { + --agents-component-corner-radius: var(--vscode-agentsWindow-editorArea-cornerRadius, var(--agents-part-corner-radius)); +} + +.monaco-workbench.agent-sessions-workbench:not(.modern-ui-compact) .part.auxiliarybar { + --agents-component-corner-radius: var(--vscode-agentsWindow-secondarySideBar-cornerRadius, var(--agents-part-corner-radius)); +} + +.monaco-workbench.agent-sessions-workbench:not(.modern-ui-compact) .part.panel { + --agents-component-corner-radius: var(--vscode-agentsWindow-toolsPanel-cornerRadius, var(--agents-part-corner-radius)); +} + .monaco-workbench.agent-sessions-workbench.modern-ui-compact { --agents-floating-panel-gap: 0px; + --agents-outer-panel-gap: 0px; --agents-part-corner-radius: 0px; --agents-part-frame-border-width: var(--vscode-strokeThickness) 0 0 var(--vscode-strokeThickness); } @@ -31,11 +53,11 @@ } .monaco-workbench.agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):not(.modern-ui-compact):not(.nosessionspart) { - --agents-session-frame-inset: var(--vscode-strokeThickness); + --agents-session-frame-inset: min(var(--vscode-strokeThickness), var(--agents-floating-panel-gap)); } .monaco-workbench.agent-sessions-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs.dock-detail-panel.agents-side-pane-multiple-tabs:not(.phone-layout):not(.modern-ui-compact):not(.noeditorpane) { - --agents-side-pane-frame-inset: var(--vscode-strokeThickness); + --agents-side-pane-frame-inset: min(var(--vscode-strokeThickness), max(0px, calc(var(--agents-floating-panel-gap) - var(--agents-session-frame-inset)))); } /* ---- Workbench Shell ---- */ @@ -45,9 +67,9 @@ } .monaco-workbench.agent-sessions-workbench > .monaco-grid-view { - margin: 0 var(--agents-floating-panel-gap) var(--agents-floating-panel-gap) 0; + margin: 0 var(--agents-outer-panel-gap) var(--agents-outer-panel-gap) 0; width: auto; - height: calc(100% - var(--agents-floating-panel-gap)); + height: calc(100% - var(--agents-outer-panel-gap)); } /* Keep the title bar inset when compact content expands into the grid gutter. */ @@ -140,8 +162,8 @@ border-right-width: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; - border-top-left-radius: var(--agents-part-corner-radius); - border-bottom-left-radius: var(--agents-part-corner-radius); + border-top-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); + border-bottom-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); box-sizing: border-box; overflow: hidden; } @@ -152,12 +174,12 @@ .agent-sessions-workbench.noauxiliarybar .monaco-grid-view .part.editor:not(.modal-editor-part) { border-right-width: var(--vscode-strokeThickness); - border-top-right-radius: var(--agents-part-corner-radius); - border-bottom-right-radius: var(--agents-part-corner-radius); + border-top-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); + border-bottom-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); } .agent-sessions-workbench.nosidebar.nosessionspart:not(.phone-layout) .monaco-grid-view .part.editor:not(.modal-editor-part) { - margin-left: var(--agents-floating-panel-gap); + margin-left: var(--agents-outer-panel-gap); } /* Floating content card surface: its background, frame and corners. Shared by every @@ -166,7 +188,7 @@ .agent-sessions-workbench .agents-card-surface { background: var(--part-background); border: 1px solid var(--part-border-color, transparent); - border-radius: var(--agents-part-corner-radius); + border-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); box-sizing: border-box; } @@ -176,7 +198,7 @@ } .agent-sessions-workbench.nosidebar:not(.phone-layout) .agents-part-card { - margin-left: var(--agents-floating-panel-gap); + margin-left: var(--agents-outer-panel-gap); } .agent-sessions-workbench.noeditorpane .agents-part-card { @@ -185,7 +207,7 @@ /* Compensate for the inset session frame and any inset side-pane frame. */ .agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):not(.modern-ui-compact):not(.noeditorpane) .part.sessionspart.agents-part-card { - margin-right: calc(var(--agents-floating-panel-gap) - var(--agents-session-frame-inset) - var(--agents-side-pane-frame-inset)); + margin-right: max(0px, calc(var(--agents-floating-panel-gap) - var(--agents-session-frame-inset) - var(--agents-side-pane-frame-inset))); } .agent-sessions-workbench:not(.dock-detail-panel) .part.auxiliarybar { @@ -195,15 +217,15 @@ border: 1px solid var(--part-border-color, transparent); border-top-left-radius: 0; border-bottom-left-radius: 0; - border-top-right-radius: var(--agents-part-corner-radius); - border-bottom-right-radius: var(--agents-part-corner-radius); + border-top-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); + border-bottom-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); box-sizing: border-box; } .agent-sessions-workbench:not(.dock-detail-panel).nomaineditorarea .part.auxiliarybar { padding-left: 0; - border-top-left-radius: var(--agents-part-corner-radius); - border-bottom-left-radius: var(--agents-part-corner-radius); + border-top-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); + border-bottom-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); } .agent-sessions-workbench.modern-ui-compact:not(.dock-detail-panel) .part.auxiliarybar { @@ -215,15 +237,15 @@ } .agent-sessions-workbench .part.panel { - margin: calc(var(--agents-floating-panel-gap) - var(--agents-session-frame-inset)) 0 0 0; + margin: max(0px, calc(var(--agents-floating-panel-gap) - var(--agents-session-frame-inset))) 0 0 0; background: var(--part-background); border: 1px solid var(--part-border-color, transparent); - border-radius: var(--agents-part-corner-radius); + border-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); box-sizing: border-box; } .agent-sessions-workbench.nosidebar:not(.phone-layout) .part.panel { - margin-left: var(--agents-floating-panel-gap); + margin-left: var(--agents-outer-panel-gap); } .agent-sessions-workbench.panel-alignment-center:not(.noeditorpane) .part.panel { @@ -290,13 +312,19 @@ * topology nests Sessions below the panel and also has a sidebar sash. */ .agent-sessions-workbench:not(.noeditorpane) .monaco-sash.vertical.sessions-side-pane-divider { - width: max(var(--vscode-sash-size), var(--agents-floating-panel-gap)); - transform: translateX(calc((var(--vscode-sash-size) - max(var(--vscode-sash-size), var(--agents-floating-panel-gap)) - var(--agents-floating-panel-gap) + var(--agents-side-pane-frame-inset) + var(--agents-side-pane-frame-inset)) / 2)); + transform: translateX(calc((-1 * var(--agents-floating-panel-gap) + var(--agents-side-pane-frame-inset) + var(--agents-side-pane-frame-inset)) / 2)); } .agent-sessions-workbench:not(.nopanel) .monaco-split-view2.vertical:has(> .monaco-scrollable-element > .split-view-container > .split-view-view > .part.panel) > .sash-container > .monaco-sash.horizontal { - height: max(var(--vscode-sash-size), var(--agents-floating-panel-gap)); - transform: translateY(calc((var(--vscode-sash-size) - max(var(--vscode-sash-size), var(--agents-floating-panel-gap)) + var(--agents-floating-panel-gap) - var(--agents-session-frame-inset) - var(--agents-session-frame-inset)) / 2)); + transform: translateY(calc((var(--agents-floating-panel-gap) - var(--agents-session-frame-inset) - var(--agents-session-frame-inset)) / 2)); +} + +.agent-sessions-workbench .part.sessionspart .monaco-sash.part-grid-gap-sash.vertical { + transform: translateX(var(--agents-grid-gap-offset)); +} + +.agent-sessions-workbench .part.sessionspart .monaco-sash.part-grid-gap-sash.horizontal { + transform: translateY(var(--agents-grid-gap-offset)); } /* @@ -356,8 +384,8 @@ overflow: hidden; background: var(--vscode-editor-background); border-right-width: var(--vscode-strokeThickness); - border-top-right-radius: var(--agents-part-corner-radius); - border-bottom-right-radius: var(--agents-part-corner-radius); + border-top-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); + border-bottom-right-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius)); } .agent-sessions-workbench.dock-detail-panel .part.auxiliarybar { @@ -371,7 +399,7 @@ /* Only the card next to a native window corner follows the frame's inset curve. */ .monaco-workbench.agent-sessions-workbench.mac:not(.web):not(.fullscreen):not(.phone-layout):not(.modern-ui-compact) { - --agents-window-corner-radius: max(0px, calc(var(--window-corner-radius) - var(--agents-floating-panel-gap))); + --agents-window-corner-radius: max(0px, calc(var(--window-corner-radius) - var(--agents-outer-panel-gap))); &.nopanel.nosidebar .agents-part-card { border-bottom-left-radius: var(--agents-window-corner-radius); diff --git a/src/vs/sessions/browser/mobile/media/mobileChat.css b/src/vs/sessions/browser/mobile/media/mobileChat.css new file mode 100644 index 000000000000..a6aa346bd26f --- /dev/null +++ b/src/vs/sessions/browser/mobile/media/mobileChat.css @@ -0,0 +1,434 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* + * Phone grammar for the chat transcript and composer. Loaded only by the + * mobile web entry point (through `MobileWorkbench`). + * + * The transcript has one center of attention — the conversation. Everything + * else (footer actions, tool cards, edit rows) supports it: quiet at rest, + * revealed on intent, sized for a thumb. Type and radii come from the mobile + * token ramp in `mobileWorkbench.css`. + */ + +/* ---- Transcript ---------------------------------------------------------- */ + +.monaco-workbench.mobile-workbench .interactive-session .interactive-list .interactive-item-container { + padding: var(--vscode-spacing-size80) var(--vscode-spacing-size160); +} + +.monaco-workbench.mobile-workbench .interactive-session .interactive-item-container .value, +.monaco-workbench.mobile-workbench .interactive-session .interactive-item-container .rendered-markdown { + font-size: var(--vscode-fontSize-body1); + line-height: var(--mobile-line-height-body); +} + +/* Sent message: a pill in the card tint, right-aligned, generous padding. */ +.monaco-workbench.mobile-workbench .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown { + background-color: var(--vscode-chat-requestBubbleBackground, var(--mobile-surface-card)); + border-radius: var(--vscode-cornerRadius-large); + border-bottom-right-radius: var(--vscode-cornerRadius-xSmall); + padding: var(--vscode-spacing-size120) var(--vscode-spacing-size160); + max-width: 85%; +} + +/* Request hover affordances (edit, checkpoint) are desktop-only: reveal on hover. */ +.monaco-workbench.mobile-workbench .interactive-item-container.interactive-request .request-hover, +.monaco-workbench.mobile-workbench .interactive-item-container.interactive-request .header .monaco-toolbar, +.monaco-workbench.mobile-workbench .interactive-item-container .chat-request-timestamp-container { + display: none; +} + +/* Response: full width, no bubble; the agent is the only other party. */ +.monaco-workbench.mobile-workbench .interactive-item-container.interactive-response .header { + display: none; +} + +.monaco-workbench.mobile-workbench .interactive-item-container.interactive-response .value { + padding: 0; +} + +/* ---- Footer actions ------------------------------------------------------ */ + +/* Desktop reveals the footer on hover and lets it overlap the next row. On the + * phone it is a static, always-visible row of 44px targets under the response. */ +.monaco-workbench.mobile-workbench .interactive-item-container.interactive-response:not(.chat-response-loading) .chat-footer-toolbar { + display: flex; + opacity: 1; + height: auto; + min-height: var(--mobile-target); + padding-top: var(--vscode-spacing-size40); + position: static; + align-items: center; +} + +.monaco-workbench.mobile-workbench .interactive-item-container .chat-footer-toolbar .monaco-action-bar .actions-container { + gap: var(--vscode-spacing-size80); +} + +.monaco-workbench.mobile-workbench .interactive-item-container .chat-footer-toolbar .action-item > .action-label { + color: var(--vscode-descriptionForeground); +} + +.monaco-workbench.mobile-workbench .interactive-item-container .chat-footer-details { + display: none; +} + +/* ---- Code blocks --------------------------------------------------------- */ + +/* Code never widens the page: it scrolls inside its block. The block is an + * inner surface; its toolbar is a quiet overlay of 44px targets. */ +.monaco-workbench.mobile-workbench .interactive-result-code-block { + border-radius: var(--vscode-cornerRadius-medium); + background-color: var(--mobile-surface-card); + border: none; + overflow: hidden; + max-width: 100%; +} + +.monaco-workbench.mobile-workbench .interactive-result-code-block .monaco-editor, +.monaco-workbench.mobile-workbench .interactive-result-code-block .monaco-editor .monaco-editor-background { + background-color: var(--mobile-surface-card); +} + +.monaco-workbench.mobile-workbench .interactive-result-code-block .interactive-result-code-block-toolbar { + background: transparent; + border: none; +} + +.monaco-workbench.mobile-workbench .interactive-result-code-block .interactive-result-code-block-toolbar .action-item > .action-label { + min-height: var(--mobile-target); + min-width: var(--mobile-target); +} + +/* ---- Tool calls, thinking, confirmations --------------------------------- */ + +.monaco-workbench.mobile-workbench .chat-tool-invocation-part, +.monaco-workbench.mobile-workbench .chat-thinking-box, +.monaco-workbench.mobile-workbench .chat-confirmation-widget { + border-radius: var(--vscode-cornerRadius-medium); + background-color: var(--mobile-surface-card); + border: none; +} + +.monaco-workbench.mobile-workbench .chat-thinking-box .chat-thinking-item, +.monaco-workbench.mobile-workbench .chat-tool-invocation-part .chat-progress-content { + min-height: var(--mobile-target); + align-items: center; + font-size: var(--vscode-fontSize-body2); +} + +/* A confirmation has one primary action: full-width, 48px, filled. Secondary + * actions stack beneath it as text buttons. */ +.monaco-workbench.mobile-workbench .chat-confirmation-widget .chat-buttons-container { + flex-direction: column; + gap: var(--vscode-spacing-size80); + align-items: stretch; +} + +.monaco-workbench.mobile-workbench .chat-confirmation-widget .chat-buttons-container .monaco-button { + width: 100%; + min-height: 48px; + justify-content: center; + border-radius: var(--vscode-cornerRadius-small); + font-size: var(--vscode-fontSize-body1); +} + +.monaco-workbench.mobile-workbench .chat-confirmation-widget .chat-buttons-container .monaco-button.secondary { + background: transparent; + border: none; + color: var(--vscode-textLink-foreground); +} + +/* ---- Edit rows ----------------------------------------------------------- */ + +/* An edit is a 56px row: file icon, name, +/- counts, chevron. Tapping it opens + * the phone diff overlay. The inline diff editor never renders on the phone. */ +.monaco-workbench.mobile-workbench .chat-codeblock-pill-container { + min-height: var(--mobile-row); + align-items: center; +} + +.monaco-workbench.mobile-workbench .chat-codeblock-pill-widget { + min-height: var(--mobile-row); + padding: 0 var(--vscode-spacing-size160); + border-radius: var(--vscode-cornerRadius-medium); + background-color: var(--mobile-surface-card); + border: none; + font-size: var(--vscode-fontSize-body2); + flex: 1; + display: flex; + align-items: center; + gap: var(--vscode-spacing-size80); +} + +.monaco-workbench.mobile-workbench .chat-codeblock-pill-widget::after { + content: ''; + margin-left: auto; + width: 8px; + height: 8px; + border-right: 2px solid var(--vscode-descriptionForeground); + border-bottom: 2px solid var(--vscode-descriptionForeground); + transform: rotate(-45deg); + flex-shrink: 0; +} + +.monaco-workbench.mobile-workbench .chat-codeblock-pill-widget .label-added, +.monaco-workbench.mobile-workbench .chat-codeblock-pill-widget .label-removed { + font-size: var(--vscode-fontSize-label1); + font-variant-numeric: tabular-nums; +} + +.monaco-workbench.mobile-workbench .chat-codeblock-pill-widget:active { + background-color: var(--mobile-surface-pressed); +} + +/* ---- Composer ------------------------------------------------------------ */ + +.monaco-workbench.mobile-workbench .chat-phone-input-chip .chat-phone-input-chip-chevron { + font-size: var(--vscode-codiconFontSize-compact); + flex-shrink: 0; +} + +/* The composer is one surface with one row of controls, and that row has one + * tier: every control is a 36px round visual inside a 44px target, filled with + * the quiet control tint so it reads as a button and not as a glyph floating in + * the corner. Send is the single accent. The same grammar applies to the + * session composer (`.chat-input-container`) and the Home composer + * (`.new-chat-input-area`), which are different widgets on the desktop. */ + +/* Screen inset: 16px on a phone. Desktop centers its content at 32px; Home's + * phone shell uses 8px. Both become the one phone inset. */ +.monaco-workbench.mobile-workbench .session-view { + --session-view-content-horizontal-padding: var(--vscode-spacing-size160); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .new-chat-widget-container > .new-chat-widget-content { + box-sizing: border-box; + padding-inline: var(--vscode-spacing-size80); +} + +/* An explicitly enabled greeting replaces the legacy hero instead of overlapping it. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .new-chat-widget-content.welcome-phrases-visible .new-session-workspace-picker-container::before { + content: none; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .new-chat-widget-content.welcome-phrases-visible .new-session-welcome-message { + top: auto; + margin-top: auto; + margin-bottom: var(--vscode-spacing-size160); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .new-chat-widget-content.welcome-phrases-visible .new-session-workspace-picker-container { + max-height: max-content; + margin-top: 0; + margin-bottom: auto; +} + +/* The composer's color has one owner: `agentsChatInput.background`, which the + * shared sessions styles apply to both the input container and the editor's + * own background layer (the latter must stay solid for selection corners). + * Repainting the container with the card tint produced two surfaces — the + * inner editor showed as a rectangle of a different tint — so the phone uses + * the same token. It is restated with phone specificity because dev loaders + * that prepend `@import` rules invert the cascade, letting the workbench + * default (`input.background`) win over the sessions rule at equal + * specificity. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-container { + background-color: var(--vscode-agentsChatInput-background); + border-radius: var(--vscode-cornerRadius-xLarge); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-container { + padding: 0 var(--vscode-spacing-size80) var(--vscode-spacing-size80); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars { + align-items: center; + min-height: var(--mobile-target); + padding: 0; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .monaco-action-bar .actions-container { + gap: 0; +} + +/* Icon controls: Add Context, dictation, Send. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .action-item > .action-label.codicon { + position: relative; + box-sizing: border-box; + width: var(--mobile-control); + height: var(--mobile-control); + min-width: var(--mobile-control); + min-height: var(--mobile-control); + margin: 0; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: var(--vscode-cornerRadius-circle); + background-color: var(--mobile-control-fill); + color: var(--vscode-foreground); + font-size: var(--mobile-control-glyph); +} + +/* Controls sit 4px apart from one another: a 36px visual inside a 44px target. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .action-item { + margin: var(--vscode-spacing-size40); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-shared-chat-input .interactive-session .chat-input-toolbars > .chat-execute-toolbar .monaco-action-bar .action-item.chat-submit-button { + margin: var(--vscode-spacing-size40); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-shared-chat-input .interactive-session .chat-input-toolbars > .chat-execute-toolbar .monaco-action-bar .action-item.chat-submit-button, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-shared-chat-input .interactive-session .chat-input-toolbars > .chat-execute-toolbar .monaco-action-bar .action-item.chat-submit-button > .action-label { + width: var(--mobile-control); + height: var(--mobile-control); + border-radius: var(--vscode-cornerRadius-circle); +} + +/* The invisible part of the 44px target. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .action-item > .action-label.codicon::after { + content: ''; + position: absolute; + inset: calc(-1 * var(--vscode-spacing-size40)); +} + +/* Send is the one filled primary action on the screen; disabled, it stays in + * the row as a quiet control with a muted glyph. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .action-item.chat-submit-button > .action-label:not(.disabled) { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .action-item.chat-submit-button > .action-label.disabled { + color: var(--vscode-disabledForeground); + opacity: 1; +} + +/* The picker chip: a 36px pill in the same tint, label plus chevron. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-input-toolbars .chat-input-picker-item > .action-label.chat-phone-input-chip, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-chat-config-toolbar .monaco-action-bar .action-item > .action-label:not(.separator) { + box-sizing: border-box; + height: var(--mobile-control); + min-height: var(--mobile-control); + min-width: 0; + max-width: 100%; + padding: 0 var(--vscode-spacing-size120); + gap: var(--vscode-spacing-size40); + border-radius: var(--vscode-cornerRadius-circle); + background-color: var(--mobile-control-fill); + color: var(--vscode-foreground); + font-size: var(--vscode-fontSize-label1); + line-height: var(--mobile-line-height-label); +} + +/* Status pills under the composer (mode, approvals, context usage): one quiet + * pill style for all of them, label-role text, and an invisible 44px-tall hit + * area so they stay compact. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar { + padding: 0; + gap: var(--vscode-spacing-size40); + min-height: var(--mobile-target); + align-items: center; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .sessions-chat-picker-slot > .action-label, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .agent-host-chat-input-picker-slot > .action-label, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .chat-pill-item .monaco-button.chat-pill-button { + position: relative; + box-sizing: border-box; + height: 28px; + min-height: 28px; + min-width: 0; + padding: 0 var(--vscode-spacing-size100); + gap: var(--vscode-spacing-size40); + border-radius: var(--vscode-cornerRadius-circle); + border: none; + background-color: var(--mobile-control-fill); + color: var(--vscode-foreground); + font-size: var(--vscode-fontSize-label1); + line-height: var(--mobile-line-height-label); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .chat-context-usage-widget { + position: relative; + height: 28px; + box-sizing: border-box; + display: inline-flex; + align-items: center; + padding: 0 var(--vscode-spacing-size60); + border-radius: var(--vscode-cornerRadius-circle); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .sessions-chat-picker-slot > .action-label::after, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .agent-host-chat-input-picker-slot > .action-label::after, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .chat-pill-item .monaco-button.chat-pill-button::after, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .interactive-session .chat-secondary-toolbar .chat-context-usage-widget::after { + content: ''; + position: absolute; + left: 0; + right: 0; + top: 50%; + height: var(--mobile-target); + transform: translateY(-50%); +} + +/* ---- Home: where, then what and who -------------------------------------- */ + +/* The harness chip is a choice; with one harness there is no choice, so the + * chip goes away rather than sitting there disabled. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .new-chat-widget-container .sessions-chat-session-type-picker.disabled { + display: none; +} + +/* The place chip sits on its own row above the workspace and agent chips. It + * keeps the row's compact pill and grows the invisible 44px target that every + * phone control has. The pseudo-element lives on the action item, which also + * takes the tap (the pill itself clips for its ellipsis); the row reserves the + * height so the target is not cut off. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-new-session-place-row { + min-height: var(--mobile-target); + align-items: center; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-new-session-place-row .action-item.sessions-new-session-place { + position: relative; + cursor: pointer; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-new-session-place-row .action-item.sessions-new-session-place::after { + content: ''; + position: absolute; + left: calc(-1 * var(--vscode-spacing-size40)); + right: calc(-1 * var(--vscode-spacing-size40)); + top: 50%; + height: var(--mobile-target); + transform: translateY(-50%); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-new-session-place-row .action-item > .action-label { + min-height: 0; + min-width: 0; +} + +/* ---- Overlays that remain desktop widgets stay out of the way ------------ */ + +.monaco-workbench.mobile-workbench .chat-scroll-down { + bottom: calc(var(--vscode-spacing-size160) + env(safe-area-inset-bottom)); + width: var(--mobile-target); + height: var(--mobile-target); + border-radius: var(--vscode-cornerRadius-circle); +} + +/* ---- Diff review ---------------------------------------------------------- */ + +/* Code in the phone diff view reads at the label role (13px): small enough for + * a line of code to fit, never below the floor set for the phone. */ +.monaco-workbench.mobile-workbench .mobile-diff-output { + font-size: var(--vscode-fontSize-label1); + line-height: var(--mobile-line-height-label); +} diff --git a/src/vs/sessions/browser/mobile/media/mobileDrawer.css b/src/vs/sessions/browser/mobile/media/mobileDrawer.css new file mode 100644 index 000000000000..b113051295bf --- /dev/null +++ b/src/vs/sessions/browser/mobile/media/mobileDrawer.css @@ -0,0 +1,212 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* + * Phone grammar for the sessions drawer: a plain grouped list, the way a native + * inbox reads. Rows sit directly on one surface and are separated by a hairline + * that starts at the text edge; nothing is boxed per row. Section rows are + * uppercase labels, shortcut rows are navigation rows with a trailing chevron, + * and the tree reveals nothing on hover because there is no hover. Row heights + * are owned by `SessionsTreeDelegate` (phone constants); this file only styles + * what is inside them. The list root is `.sessions-list-control`; rows carry + * `session-list-{shortcut,section,inset}-row`. + * + * Selectors carry `.agent-sessions-workbench` so they outrank the shared + * `.agent-sessions-workbench.phone-layout` rules regardless of load order. + */ + +.monaco-workbench.agent-sessions-workbench.mobile-workbench { + /* Left padding + status glyph + gap: where row text starts and separators begin. */ + --mobile-list-text-inset: 46px; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .part.sidebar.mobile-overlay-sidebar { + background: var(--mobile-surface-card); +} + +.monaco-workbench.mobile-workbench .agent-sessions-control-container { + position: relative; +} + +/* Filter chips: 44px pills on the quiet control fill. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .mobile-session-filter-chips { + padding: var(--vscode-spacing-size80) var(--vscode-spacing-size160) var(--vscode-spacing-size120); + gap: var(--vscode-spacing-size80); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .mobile-session-filter-chip { + border-radius: var(--vscode-cornerRadius-circle); + font-size: var(--vscode-fontSize-body2); + padding: 0 var(--vscode-spacing-size160); + background-color: var(--mobile-control-fill); + border: none; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .mobile-session-filter-chip.icon-only { + padding: 0; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .mobile-session-filter-chip.active { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); +} + +/* ---- Rows: one surface, full width, no per-row card ---------------------- */ + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list .monaco-list-rows > .monaco-list-row { + background-color: transparent; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control.session-list-row-spacing .monaco-list-row:not(.sessions-list-header-row) { + left: 0; + right: 0; + width: 100%; + border-radius: 0; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control.session-list-row-spacing .monaco-list-row:is(.session-list-inset-row, .session-list-show-more-row, .session-list-show-more-folders-row) { + padding-bottom: 0; + background-clip: border-box; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row > .monaco-tl-row { + border-radius: 0; +} + +/* The hairline between session rows starts at the text edge, like a native inbox. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row.session-list-inset-row > .monaco-tl-row > .session-item, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row.session-list-inset-row > .monaco-tl-row > .session-chat-item { + background-image: linear-gradient(var(--mobile-separator), var(--mobile-separator)); + background-size: calc(100% - var(--mobile-list-text-inset)) var(--vscode-strokeThickness); + background-position: right bottom; + background-repeat: no-repeat; +} + +/* Press and selection tint the whole row; there is no focus ring on touch. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list .monaco-list-rows > .monaco-list-row:is(.selected, .focused) { + background-color: var(--vscode-list-inactiveSelectionBackground, var(--mobile-surface-pressed)); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list .monaco-list-rows > .monaco-list-row:active { + background-color: var(--mobile-surface-pressed); +} + +/* Sticky headers scroll over the list on the same surface, with a hairline edge. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-tree-sticky-container { + background-color: var(--mobile-surface-card); + box-shadow: 0 var(--vscode-strokeThickness) 0 var(--mobile-separator); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list .monaco-tree-sticky-row.monaco-list-row { + background-color: var(--mobile-surface-card); + background-image: none; +} + +/* The tree's own twistie and indent are not part of the phone grammar. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .monaco-tl-twistie { + display: none; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .monaco-tl-indent { + display: none; +} + +/* ---- Section rows: labels, not tree nodes ------------------------------- */ + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section { + padding: 0 var(--vscode-spacing-size160); + font-size: var(--vscode-fontSize-label1); + font-weight: var(--vscode-fontWeight-semiBold); + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--vscode-descriptionForeground); + border-radius: 0; +} + +/* Collapsible groups disclose from the trailing edge. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section .session-section-chevron.collapsible { + display: flex; + align-items: center; + order: 1; + margin-left: auto; + color: var(--vscode-descriptionForeground); +} + +/* Shortcut rows (Automations, …) navigate: sentence case, body size, trailing chevron. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section.session-section-shortcut { + font-size: var(--vscode-fontSize-body1); + font-weight: var(--vscode-fontWeight-regular); + text-transform: none; + letter-spacing: normal; + color: var(--vscode-foreground); + background-color: transparent; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section.session-section-shortcut .session-section-icon { + margin-right: var(--vscode-spacing-size100); + color: var(--vscode-descriptionForeground); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section.session-section-shortcut::after { + /* codicon-chevron-right */ + content: '\eab6'; + font-family: codicon; + font-size: var(--vscode-codiconFontSize); + margin-left: auto; + color: var(--vscode-descriptionForeground); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-section .session-section-toolbar { + display: none; +} + +/* ---- Session rows ------------------------------------------------------- */ + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .session-item { + margin: 0; + padding: 0 var(--vscode-spacing-size160); + background: transparent; + border-radius: 0; + box-shadow: none; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .session-item .session-icon { + width: 20px; + justify-content: center; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .session-item .session-main { + padding-left: var(--vscode-spacing-size100); + /* Row actions live in the long-press sheet, so the text owns the full width. */ + padding-right: 0; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .session-item .session-title { + font-size: var(--vscode-fontSize-body1); + line-height: 20px; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .session-item .session-details-row { + font-size: var(--vscode-fontSize-label1); + line-height: 16px; + max-height: 16px; + color: var(--vscode-descriptionForeground); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-title-toolbar { + display: none; +} + +/* "+N more" is a quiet link-colored row, no rule lines. */ +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-show-more { + font-size: var(--vscode-fontSize-body2); + color: var(--vscode-textLink-foreground); +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-show-more::before, +.monaco-workbench.agent-sessions-workbench.mobile-workbench .sessions-list-control .monaco-list-row .session-show-more::after { + display: none; +} diff --git a/src/vs/sessions/browser/mobile/media/mobilePullToRefresh.css b/src/vs/sessions/browser/mobile/media/mobilePullToRefresh.css new file mode 100644 index 000000000000..ba7a50a97c81 --- /dev/null +++ b/src/vs/sessions/browser/mobile/media/mobilePullToRefresh.css @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.mobile-pull-indicator { + position: absolute; + top: -44px; + left: 50%; + margin-left: -22px; + width: 44px; + height: 44px; + display: flex; + align-items: center; + justify-content: center; + border-radius: var(--vscode-cornerRadius-circle); + background: var(--mobile-surface-raised, var(--vscode-editorWidget-background)); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25); + opacity: 0; + pointer-events: none; + z-index: 5; + will-change: transform, opacity; +} + +.mobile-pull-indicator .mobile-pull-glyph { + font-size: 16px; + color: var(--vscode-foreground); + transition: transform 150ms ease-out; +} + +.mobile-pull-indicator.armed .mobile-pull-glyph { + transform: rotate(180deg); +} + +.mobile-pull-indicator.refreshing .mobile-pull-glyph { + transform: none; +} + +.mobile-pull-live { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); +} diff --git a/src/vs/sessions/browser/mobile/media/mobileWorkbench.css b/src/vs/sessions/browser/mobile/media/mobileWorkbench.css new file mode 100644 index 000000000000..52a28bf30f8e --- /dev/null +++ b/src/vs/sessions/browser/mobile/media/mobileWorkbench.css @@ -0,0 +1,266 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* + * Mobile design language — owned by `MobileWorkbench`, loaded only by the + * mobile web entry point. + * + * Section 1 re-ramps the design tokens the whole workbench already reads, so + * every shared component (chat transcript, lists, sheets, cards) moves to phone + * proportions from one place. Everything below section 1 is the phone *grammar*: + * layered surfaces instead of borders, 44px targets, reveal on intent (not hover), + * and motion that orients. Rules here are additive and describe the phone + * directly; they do not undo desktop rules. + * + * Palette stays VS Code: every color is a `--vscode-*` theme token. + */ + +/* ---- 1. Token ramp ------------------------------------------------------- */ + +.monaco-workbench.mobile-workbench { + /* Type roles keep their rank; sizes move to the phone scale. body1 never + * drops below 16px: iOS Safari zooms any focused input smaller than that. */ + --vscode-fontSize-heading1: 28px; + --vscode-fontSize-heading2: 20px; + --vscode-fontSize-heading3: 17px; + --vscode-fontSize-body1: 16px; + --vscode-fontSize-body2: 15px; + --vscode-fontSize-label1: 13px; + --vscode-fontSize-label2: 12px; + --vscode-fontSize-label3: 11px; + + /* Elevation tiers step up one notch: phone surfaces float more than desktop + * panes, so controls, inner containers, and sheets round accordingly. */ + --vscode-cornerRadius-xSmall: 6px; + --vscode-cornerRadius-small: 10px; + --vscode-cornerRadius-medium: 12px; + --vscode-cornerRadius-large: 16px; + --vscode-cornerRadius-xLarge: 20px; + + /* Phone-only tokens. Surfaces are layered by tint, not separated by lines. */ + --mobile-surface-page: var(--vscode-agents-background, var(--vscode-editor-background)); + --mobile-surface-card: var(--vscode-agentsPanel-background, var(--vscode-sideBar-background)); + --mobile-surface-raised: var(--vscode-editorWidget-background); + --mobile-surface-pressed: var(--vscode-toolbar-hoverBackground); + --mobile-separator: color-mix(in srgb, var(--vscode-foreground) 10%, transparent); + --mobile-target: 44px; + --mobile-row: 56px; + /* A composer control: a 36px round visual inside the 44px target. */ + --mobile-control: 36px; + --mobile-control-fill: color-mix(in srgb, var(--vscode-foreground) 7%, transparent); + --mobile-control-glyph: 18px; + --mobile-line-height-body: 24px; + --mobile-line-height-label: 18px; + --mobile-motion-push: 250ms; + --mobile-motion-fade: 150ms; + --mobile-ease-out: cubic-bezier(0.2, 0.8, 0.2, 1); + + background: var(--mobile-surface-page); + overscroll-behavior: none; + -webkit-tap-highlight-color: transparent; + -webkit-text-size-adjust: 100%; + font-size: var(--vscode-fontSize-body1); +} + +@media (prefers-reduced-motion: reduce) { + .monaco-workbench.mobile-workbench { + --mobile-motion-push: 0ms; + --mobile-motion-fade: 0ms; + } +} + +/* ---- 2. Touch targets ---------------------------------------------------- */ + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .action-item > .action-label.separator { + min-height: 0; + min-width: 1px; +} + +.monaco-workbench.agent-sessions-workbench.mobile-workbench .quick-input-widget .monaco-list-row { + min-height: 0; +} + +/* Every tappable control is at least 44px. Icons stay 16px inside the box. The + * chat input toolbars were exempted from the shared phone rule for density + * (phoneLayout.css); on the phone they are the most-tapped controls in the app, + * so the exemption is outranked here by naming the workbench class as well. + * Separators are action-bar items too, but not controls: they keep their + * hairline. */ +.monaco-workbench.mobile-workbench .action-item > .action-label:not(.separator), +.monaco-workbench.agent-sessions-workbench.mobile-workbench .chat-input-toolbars .action-item > .action-label:not(.separator), +.monaco-workbench.agent-sessions-workbench.mobile-workbench .quick-input-widget .action-item > .action-label:not(.separator), +.monaco-workbench.mobile-workbench .new-chat-bottom-container .action-item > .action-label:not(.separator), +.monaco-workbench.mobile-workbench .monaco-button, +.monaco-workbench.mobile-workbench .mobile-session-filter-chip { + min-height: var(--mobile-target); + min-width: var(--mobile-target); + box-sizing: border-box; +} + +.monaco-workbench.mobile-workbench .action-item > .action-label.codicon { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0; + border-radius: var(--vscode-cornerRadius-small); +} + +.monaco-workbench.mobile-workbench .action-item > .action-label:active, +.monaco-workbench.mobile-workbench button:active { + background-color: var(--mobile-surface-pressed); +} + +/* Dropdown-style pickers (model, mode, repository) read as pills. */ +.monaco-workbench.mobile-workbench .chat-input-toolbars .action-item > .action-label:not(.codicon), +.monaco-workbench.mobile-workbench .new-chat-bottom-container .sessions-chat-picker-slot, +.monaco-workbench.mobile-workbench .chat-input-picker-label { + font-size: var(--vscode-fontSize-label1); + line-height: var(--mobile-line-height-label); +} + +/* Top bar: the title fills the bar, so tapping anywhere on it opens the session + * switcher. */ +.monaco-workbench.mobile-workbench .mobile-top-bar .mobile-session-title { + height: 100%; + min-height: var(--mobile-target); +} + +/* Pills that must stay visually compact (the changes pill in the top bar, the + * desktop-web host selector when it renders in a phone layout) keep their size + * and grow an invisible 44px-tall hit area instead. The pseudo-element is out + * of flow, so layout does not change; taps on it reach the pill. The status + * pills under the composer and the place chip on Home use the same move in + * `mobileChat.css`. */ +.monaco-workbench.mobile-workbench .mobile-top-bar .mobile-changes-pill, +.monaco-workbench.mobile-workbench .agent-host-filter-combo .agent-host-filter-dropdown { + position: relative; +} + +.monaco-workbench.mobile-workbench .mobile-top-bar .mobile-changes-pill::after, +.monaco-workbench.mobile-workbench .agent-host-filter-combo .agent-host-filter-dropdown::after { + content: ''; + position: absolute; + left: calc(-1 * var(--vscode-spacing-size40)); + right: calc(-1 * var(--vscode-spacing-size40)); + top: 50%; + height: var(--mobile-target); + transform: translateY(-50%); +} + +/* ---- 3. Focus: keyboard only --------------------------------------------- */ + +.monaco-workbench.mobile-workbench :focus:not(:focus-visible) { + outline: none !important; +} + +/* A sheet's search field is a pill; the focus stroke follows the pill, not the + * rectangular input inside it (which the workbench's global input rule outlines). */ +.monaco-workbench.mobile-workbench .mobile-picker-sheet-search-input:focus { + outline: none; +} + +.monaco-workbench.mobile-workbench .mobile-picker-sheet-search:focus-within { + box-shadow: inset 0 0 0 var(--vscode-strokeThickness) var(--vscode-focusBorder); +} + +.monaco-workbench.mobile-workbench .monaco-list:not(.element-focused):focus::before { + display: none; +} + +/* ---- 4. Safe areas ------------------------------------------------------- */ + +.monaco-workbench.mobile-workbench .mobile-top-bar { + padding-top: env(safe-area-inset-top); + height: calc(48px + env(safe-area-inset-top)); + min-height: calc(48px + env(safe-area-inset-top)); + background: var(--mobile-surface-page); +} + +.monaco-workbench.mobile-workbench .interactive-input-part, +.monaco-workbench.mobile-workbench .new-chat-widget-container .new-chat-bottom-container { + padding-bottom: env(safe-area-inset-bottom); +} + +/* ---- 5. Motion ----------------------------------------------------------- */ + +/* A session surface entering the main area slides in from the trailing edge, + * like a pushed screen. Only the first paint animates; relayouts do not. */ +@keyframes mobile-push-in { + from { transform: translateX(24px); opacity: 0; } + to { transform: translateX(0); opacity: 1; } +} + +@keyframes mobile-fade-in { + from { opacity: 0; } + to { opacity: 1; } +} + +.monaco-workbench.mobile-workbench .part.sessions-part .session-view, +.monaco-workbench.mobile-workbench .part.sessions-part .chat-view { + animation: mobile-push-in var(--mobile-motion-push) var(--mobile-ease-out) both; +} + +.monaco-workbench.mobile-workbench .interactive-item-container { + animation: mobile-fade-in var(--mobile-motion-fade) ease-out both; +} + +/* ---- 6. Scroll edges ----------------------------------------------------- */ + +.monaco-workbench.mobile-workbench .interactive-list, +.monaco-workbench.mobile-workbench .part.sidebar .monaco-list { + mask-image: linear-gradient(to bottom, transparent 0, #000 12px, #000 calc(100% - 12px), transparent 100%); +} + +.monaco-workbench.mobile-workbench .monaco-scrollable-element > .scrollbar > .slider { + border-radius: var(--vscode-cornerRadius-circle); +} + +/* ---- 7. Notifications as snackbars --------------------------------------- */ + +/* Toasts already sit at the top under the safe area (phoneLayout.css). Here + * they become snackbars: one raised card per message, entering from the top + * edge they are anchored to, with a message clamped to two lines and actions + * that are real touch targets. The notification center keeps the full text. */ + +.monaco-workbench.mobile-workbench > .notifications-toasts .notification-toast-container > .notification-toast { + transform: translate3d(0, -16px, 0); + transition: transform var(--mobile-motion-push) var(--mobile-ease-out), opacity var(--mobile-motion-fade) ease-out; +} + +.monaco-workbench.mobile-workbench > .notifications-toasts .notification-toast-container > .notification-toast.notification-fade-in { + transform: none; +} + +.monaco-workbench.mobile-workbench > .notifications-toasts .notifications-list-container { + background: var(--mobile-surface-raised); + box-shadow: var(--vscode-shadow-lg); +} + +.monaco-workbench.mobile-workbench .notifications-list-container .notification-list-item { + padding: var(--vscode-spacing-size80) var(--vscode-spacing-size120); +} + +.monaco-workbench.mobile-workbench .notifications-list-container .notification-list-item .notification-list-item-message { + font-size: var(--vscode-fontSize-body2); + line-height: 20px; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.monaco-workbench.mobile-workbench .notifications-list-container .notification-list-item .notification-list-item-toolbar-container .action-label { + min-width: var(--mobile-target); + min-height: var(--mobile-target); + display: inline-flex; + align-items: center; + justify-content: center; +} + +.monaco-workbench.mobile-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container .monaco-button { + min-height: var(--mobile-target); + border-radius: var(--vscode-cornerRadius-circle); + padding: 0 var(--vscode-spacing-size160); +} diff --git a/src/vs/sessions/browser/mobile/mobilePullToRefresh.ts b/src/vs/sessions/browser/mobile/mobilePullToRefresh.ts new file mode 100644 index 000000000000..fc261fefd646 --- /dev/null +++ b/src/vs/sessions/browser/mobile/mobilePullToRefresh.ts @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/mobilePullToRefresh.css'; +import * as dom from '../../../base/browser/dom.js'; +import { Codicon } from '../../../base/common/codicons.js'; +import { onUnexpectedError } from '../../../base/common/errors.js'; +import { DisposableStore, IDisposable } from '../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../base/common/themables.js'; +import { localize } from '../../../nls.js'; + +const $ = dom.$; + +/** Finger travel (after the dead zone) that arms the refresh. */ +const TRIGGER_DISTANCE_PX = 72; +/** Where the indicator rests while a refresh runs. */ +const REFRESHING_OFFSET_PX = 48; +const MAX_PULL_PX = 96; +const DEAD_ZONE_PX = 10; +/** The indicator moves slower than the finger, like a stretched spring. */ +const RESISTANCE = 0.6; + +export interface IPullToRefreshOptions { + /** Whether the host list is scrolled to its top; pulls only begin there. */ + readonly isAtTop: () => boolean; + /** Performs the refresh. The indicator spins until the promise settles. */ + readonly refresh: () => Promise; +} + +/** + * Installs the pull-to-refresh gesture on a scrollable phone list. Dragging + * down from the top reveals a spinner that follows the finger with + * resistance; releasing past the threshold runs the refresh and holds the + * spinner until it settles. Honors `prefers-reduced-motion` by skipping the + * snap-back animation. + */ +export function installPullToRefresh(container: HTMLElement, options: IPullToRefreshOptions): IDisposable { + const store = new DisposableStore(); + + const indicator = dom.prepend(container, $('div.mobile-pull-indicator', { 'aria-hidden': 'true' })); + const glyph = dom.append(indicator, $('span.mobile-pull-glyph')); + glyph.classList.add(...ThemeIcon.asClassNameArray(Codicon.arrowDown)); + const live = dom.append(container, $('div.mobile-pull-live', { role: 'status', 'aria-live': 'polite' })); + + let startY: number | undefined; + let armed = false; + let refreshing = false; + + const setPull = (px: number, animate: boolean) => { + indicator.style.transition = animate && !dom.getWindow(container).matchMedia('(prefers-reduced-motion: reduce)').matches ? 'transform 200ms ease-out, opacity 200ms ease-out' : 'none'; + indicator.style.transform = `translateY(${px}px)`; + indicator.style.opacity = String(Math.min(1, px / REFRESHING_OFFSET_PX)); + }; + const setArmed = (value: boolean) => { + armed = value; + indicator.classList.toggle('armed', value); + }; + + store.add(dom.addDisposableListener(container, 'touchstart', (e: TouchEvent) => { + if (refreshing || e.touches.length !== 1 || !options.isAtTop()) { + startY = undefined; + return; + } + startY = e.touches[0].clientY; + }, { passive: true })); + + store.add(dom.addDisposableListener(container, 'touchmove', (e: TouchEvent) => { + if (startY === undefined || refreshing) { + return; + } + const delta = e.touches[0].clientY - startY - DEAD_ZONE_PX; + if (delta <= 0 || !options.isAtTop()) { + setPull(0, false); + setArmed(false); + return; + } + setPull(Math.min(MAX_PULL_PX, delta * RESISTANCE), false); + setArmed(delta >= TRIGGER_DISTANCE_PX); + }, { passive: true })); + + const end = async () => { + if (startY === undefined) { + return; + } + startY = undefined; + if (!armed || refreshing) { + setPull(0, true); + setArmed(false); + return; + } + refreshing = true; + indicator.classList.add('refreshing'); + glyph.className = `mobile-pull-glyph ${ThemeIcon.asClassName(ThemeIcon.modify(Codicon.loading, 'spin'))}`; + live.textContent = localize('mobilePullToRefresh.refreshing', "Refreshing"); + setPull(REFRESHING_OFFSET_PX, true); + try { + await options.refresh(); + live.textContent = localize('mobilePullToRefresh.done', "Refreshed"); + } catch (error) { + live.textContent = localize('mobilePullToRefresh.failed', "Could not refresh"); + throw error; + } finally { + refreshing = false; + indicator.classList.remove('refreshing'); + setArmed(false); + glyph.className = `mobile-pull-glyph ${ThemeIcon.asClassName(Codicon.arrowDown)}`; + setPull(0, true); + } + }; + store.add(dom.addDisposableListener(container, 'touchend', () => void end().catch(onUnexpectedError), { passive: true })); + store.add(dom.addDisposableListener(container, 'touchcancel', () => void end().catch(onUnexpectedError), { passive: true })); + + store.add({ dispose: () => { indicator.remove(); live.remove(); } }); + return store; +} diff --git a/src/vs/sessions/browser/mobile/mobileTitlebarPart.ts b/src/vs/sessions/browser/mobile/mobileTitlebarPart.ts new file mode 100644 index 000000000000..2c332e7909c2 --- /dev/null +++ b/src/vs/sessions/browser/mobile/mobileTitlebarPart.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 { addDisposableListener, EventHelper, EventType, getActiveElement, isHTMLElement } from '../../../base/browser/dom.js'; +import { Event } from '../../../base/common/event.js'; +import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; +import { autorun, observableSignalFromEvent } from '../../../base/common/observable.js'; +import { localize } from '../../../nls.js'; +import { SideBarVisibleContext } from '../../../workbench/common/contextkeys.js'; +import { IsNewChatSessionContext } from '../../../workbench/contrib/sessions/common/contextkeys.js'; +import { MobileTitlebarPart as BaseMobileTitlebarPart } from '../parts/mobile/mobileTitlebarPart.js'; + +/** Title and account-sheet presentation for the mobile workbench. */ +export class MobileTitlebarPart extends BaseMobileTitlebarPart { + + protected override registerTitleListener(): void { + const titleKeys = new Set([IsNewChatSessionContext.key, SideBarVisibleContext.key]); + const titleContext = observableSignalFromEvent(this, Event.filter(this.contextKeyService.onDidChangeContext, event => event.affectsSome(titleKeys))); + this._register(autorun(reader => { + titleContext.read(reader); + const session = this.mainWindowHost.session.read(reader); + const title = session?.title.read(reader); + if (SideBarVisibleContext.getValue(this.contextKeyService)) { + this.setTitle(localize('mobileTopBar.sessions', "Sessions")); + } else if (IsNewChatSessionContext.getValue(this.contextKeyService)) { + this.setTitle(localize('mobileTopBar.home', "Agents")); + } else { + this.setTitle(title || localize('mobileTopBar.newSession', "New Session")); + } + })); + } + + protected override createAccountSheet(panelStore: DisposableStore, closeSheet: () => void): { sheet: HTMLElement; closeButton: HTMLButtonElement; registerAction?: (button: HTMLButtonElement) => void } { + const opener = getActiveElement(); + const result = super.createAccountSheet(panelStore, closeSheet); + const { sheet, closeButton } = result; + sheet.setAttribute('role', 'dialog'); + sheet.setAttribute('aria-modal', 'true'); + sheet.setAttribute('tabindex', '-1'); + sheet.setAttribute('aria-label', localize('mobileAccount.title', "Account")); + panelStore.add(toDisposable(() => { + if (isHTMLElement(opener) && opener.isConnected) { + opener.focus(); + } + })); + let lastFocusTarget: HTMLElement = closeButton; + panelStore.add(addDisposableListener(sheet, EventType.KEY_DOWN, (event: KeyboardEvent) => { + if (event.key === 'Escape') { + EventHelper.stop(event, true); + closeSheet(); + return; + } + if (event.key !== 'Tab') { + return; + } + if (event.shiftKey && (event.target === closeButton || event.target === sheet)) { + EventHelper.stop(event, true); + lastFocusTarget.focus(); + } else if (!event.shiftKey && event.target === lastFocusTarget) { + EventHelper.stop(event, true); + closeButton.focus(); + } + })); + closeButton.focus(); + return { + ...result, + registerAction: button => { + if (!button.disabled) { + lastFocusTarget = button; + } + }, + }; + } +} diff --git a/src/vs/sessions/browser/mobile/mobileWorkbench.ts b/src/vs/sessions/browser/mobile/mobileWorkbench.ts new file mode 100644 index 000000000000..7ee72d43f999 --- /dev/null +++ b/src/vs/sessions/browser/mobile/mobileWorkbench.ts @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ServiceCollection } from '../../../platform/instantiation/common/serviceCollection.js'; +import { ILogService } from '../../../platform/log/common/log.js'; +import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; +import { SessionsLayoutPolicy } from '../layoutPolicy.js'; +import { IWorkbenchOptions, Workbench } from '../workbench.js'; +import { MobileWorkbench as BaseMobileWorkbench } from '../mobileWorkbench.js'; +import { MobileTitlebarPart } from './mobileTitlebarPart.js'; + +/** + * CSS class that marks the main container of the mobile workbench. Mobile-only + * stylesheets (`media/*.css`, loaded last by `contrib/mobile/browser/mobile.contribution.ts` + * so they are the final word in the cascade) target this class instead of + * overriding desktop rules under `.phone-layout`, so the phone presentation is + * additive rather than subtractive. + */ +export const MOBILE_WORKBENCH_CLASS = 'mobile-workbench'; + +/** + * The phone presentation of the Agents Window. + * + * The mobile workbench is selected by the mobile web entry point + * (`agents.web.mobile.main.ts`), never by measuring the window or sniffing + * the user agent at runtime. It fixes the viewport class to `phone` for the + * lifetime of the window, which makes every downstream consumer of + * {@link Workbench.viewportClass} — part factories, layout controllers, + * pickers, and `IsPhoneLayoutContext` — agree on the presentation from the + * first layout pass, and disables the desktop-to-phone morphing that the shared + * workbench performs when a viewport crosses the phone breakpoint. + * + * It shares the session model, services, providers, and chat widget with the + * desktop workbench; only composition and presentation differ. + */ +export class MobileWorkbench extends BaseMobileWorkbench { + readonly initialViewportClass = 'phone'; + + protected override createLayoutPolicy(): SessionsLayoutPolicy { + return new SessionsLayoutPolicy('phone'); + } + + protected override createMobileTitlebarPart(instantiationService: IInstantiationService): MobileTitlebarPart { + return instantiationService.createInstance(MobileTitlebarPart, this.mainContainer); + } + + override getLayoutClasses(): string[] { + return [...super.getLayoutClasses(), MOBILE_WORKBENCH_CLASS]; + } +} + +/** + * Creates the mobile workbench. Passed to the web bootstrap by the mobile + * entry point in place of the desktop `createSessionsWorkbench` factory. + */ +export function createMobileSessionsWorkbench(parent: HTMLElement, options: IWorkbenchOptions | undefined, serviceCollection: ServiceCollection, logService: ILogService): Workbench { + return new MobileWorkbench(parent, options, serviceCollection, logService); +} diff --git a/src/vs/sessions/browser/parts/auxiliaryBarPart.ts b/src/vs/sessions/browser/parts/auxiliaryBarPart.ts index d88a364a5221..bac46a162f50 100644 --- a/src/vs/sessions/browser/parts/auxiliaryBarPart.ts +++ b/src/vs/sessions/browser/parts/auxiliaryBarPart.ts @@ -308,7 +308,7 @@ export class AuxiliaryBarPart extends AbstractPaneCompositePart { const editorVisible = this.layoutService.isVisible(Parts.EDITOR_PART, mainWindow); const paddingLeft = editorVisible && !compact ? AuxiliaryBarPart.CONTENT_PADDING_LEFT : 0; const marginBottom = !this.layoutService.mainContainer.classList.contains('dock-detail-panel') - ? getSidePaneBottomFrameInset(this.layoutService.mainContainer) + ? getSidePaneBottomFrameInset(this.layoutService.mainContainer, this.layoutService.getPanelSpacing()) : AuxiliaryBarPart.MARGIN_BOTTOM; super.layout( diff --git a/src/vs/sessions/browser/parts/customViewGridPart.ts b/src/vs/sessions/browser/parts/customViewGridPart.ts index ae14996126af..99c57525f28b 100644 --- a/src/vs/sessions/browser/parts/customViewGridPart.ts +++ b/src/vs/sessions/browser/parts/customViewGridPart.ts @@ -124,7 +124,8 @@ export class CustomViewGridPart extends Part { this.agentWorkbenchLayoutService.isEditorPaneVisible(), this.layoutService.isVisible(Parts.SIDEBAR_PART), isPhoneLayout(this.layoutService), - this.layoutService.isModernUICompact() + this.layoutService.isModernUICompact(), + this.layoutService.getPanelSpacing() ); const { contentSize } = this.layoutContents(cardSize.width, cardSize.height); this._layoutNode(contentSize.width, contentSize.height); diff --git a/src/vs/sessions/browser/parts/editorPart.ts b/src/vs/sessions/browser/parts/editorPart.ts index a475503bf4fd..1c5ec5e1b30f 100644 --- a/src/vs/sessions/browser/parts/editorPart.ts +++ b/src/vs/sessions/browser/parts/editorPart.ts @@ -6,11 +6,12 @@ import { LayoutPriority } from '../../../base/browser/ui/splitview/splitview.js'; import { mainWindow } from '../../../base/browser/window.js'; import { MainEditorPart as MainEditorPartBase } from '../../../workbench/browser/parts/editor/editorPart.js'; +import { IEditorGroupViewOptions } from '../../../workbench/browser/parts/editor/editor.js'; import { Parts } from '../../../workbench/services/layout/browser/layoutService.js'; import { AGENTS_FLOATING_PANEL_GAP } from '../../../workbench/contrib/sessions/common/layoutConstants.js'; import { type IAgentWorkbenchLayoutService } from '../workbench.js'; import { AgentWorkbenchLayout } from '../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; -import { getSidePaneBottomFrameInset } from '../../../workbench/browser/parts/sessions/agentsPartCard.js'; +import { AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS, getSidePaneBottomFrameInset, getSidePaneFrameInset } from '../../../workbench/browser/parts/sessions/agentsPartCard.js'; import { EDITOR_PART_MINIMUM_WIDTH } from '../../../workbench/browser/parts/sessions/editorPartSizing.js'; import { isPhoneLayout } from '../../../workbench/browser/parts/sessions/mobileLayout.js'; @@ -20,6 +21,11 @@ export class MainEditorPart extends MainEditorPartBase { static readonly MARGIN_LEFT = 0; static readonly MARGIN_RIGHT = 0; + // The workbench's new tab button is not offered in the Agents window, which configures its own tab bar. + protected override getGroupViewOptions(): IEditorGroupViewOptions | undefined { + return undefined; + } + override get minimumWidth() { return Math.max(EDITOR_PART_MINIMUM_WIDTH, super.minimumWidth); } @@ -44,8 +50,15 @@ export class MainEditorPart extends MainEditorPartBase { && !this.layoutService.isVisible(Parts.SIDEBAR_PART) && !this.layoutService.isVisible(Parts.SESSIONS_PART) ? AGENTS_FLOATING_PANEL_GAP : MainEditorPart.MARGIN_LEFT; - const borderTotal = compact ? 0 : 2; - const bottomFrameInset = getSidePaneBottomFrameInset(this.layoutService.mainContainer); + const container = this.layoutService.mainContainer; + const spacing = this.layoutService.getPanelSpacing(); + const connectedFrame = !isPhoneLayout(this.layoutService) + && container.classList.contains('modern-ui-tabs') + && container.classList.contains('modern-ui-connected-editor-tabs') + && container.classList.contains('dock-detail-panel') + && container.classList.contains(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS); + const borderTotal = compact ? 0 : connectedFrame ? getSidePaneFrameInset(container, spacing) * 2 : 2; + const bottomFrameInset = getSidePaneBottomFrameInset(container, spacing); const adjustedWidth = width - MainEditorPart.MARGIN_RIGHT - marginLeft - borderTotal; const adjustedHeight = height - MainEditorPart.MARGIN_TOP - MainEditorPart.MARGIN_BOTTOM - borderTotal - bottomFrameInset; diff --git a/src/vs/sessions/browser/parts/media/editorPart.css b/src/vs/sessions/browser/parts/media/editorPart.css index e96ae0ad1b25..752d9da3aab0 100644 --- a/src/vs/sessions/browser/parts/media/editorPart.css +++ b/src/vs/sessions/browser/parts/media/editorPart.css @@ -15,8 +15,8 @@ border-right-width: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; - border-top-left-radius: var(--agents-part-corner-radius, var(--vscode-cornerRadius-large)); - border-bottom-left-radius: var(--agents-part-corner-radius, var(--vscode-cornerRadius-large)); + border-top-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius, var(--vscode-cornerRadius-large))); + border-bottom-left-radius: var(--agents-component-corner-radius, var(--agents-part-corner-radius, var(--vscode-cornerRadius-large))); box-sizing: border-box; overflow: hidden; } @@ -69,6 +69,7 @@ /* The group owns the connected frame; the outer card only reserves its space. */ .monaco-workbench.agent-sessions-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs.dock-detail-panel:not(.phone-layout) .part.editor.editor-tabs-multiple:not(.modal-editor-part) { border-color: transparent; + border-width: var(--agents-side-pane-frame-inset); } .monaco-workbench.agent-sessions-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs.dock-detail-panel:not(.phone-layout) .part.editor.editor-tabs-multiple:not(.modal-editor-part)::after { @@ -94,7 +95,7 @@ inset: 0; border: var(--vscode-strokeThickness) solid var(--modern-ui-connected-tab-border); border-width: var(--agents-part-frame-border-width, var(--vscode-strokeThickness)); - border-radius: max(0px, calc(var(--agents-part-corner-radius, var(--vscode-cornerRadius-large)) - var(--vscode-strokeThickness))); + border-radius: max(0px, calc(var(--agents-component-corner-radius, var(--agents-part-corner-radius, var(--vscode-cornerRadius-large))) - var(--agents-side-pane-frame-inset, var(--vscode-strokeThickness)))); box-sizing: border-box; pointer-events: none; z-index: 10; @@ -238,7 +239,7 @@ display: flex; align-items: center; justify-content: center; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--chat-tab-inactive-foreground, currentColor); } diff --git a/src/vs/sessions/browser/parts/media/projectBarPart.css b/src/vs/sessions/browser/parts/media/projectBarPart.css index 8c499fbddf68..fa97b276464c 100644 --- a/src/vs/sessions/browser/parts/media/projectBarPart.css +++ b/src/vs/sessions/browser/parts/media/projectBarPart.css @@ -50,19 +50,23 @@ cursor: pointer; } -.monaco-workbench .projectbar .action-item:focus { - outline: 0 !important; /* project bar indicates focus custom */ -} - -.monaco-workbench .projectbar .action-item:focus-visible::before { +.monaco-workbench .projectbar .action-item::before { content: ''; position: absolute; - inset: 6px; - border: 1px solid var(--vscode-focusBorder); + inset: var(--vscode-spacing-size60); + border: var(--vscode-strokeThickness) solid transparent; border-radius: var(--vscode-cornerRadius-small); pointer-events: none; } +.monaco-workbench .projectbar .action-item:focus { + outline: 0 !important; /* project bar indicates focus custom */ +} + +.monaco-workbench .projectbar .action-item:is(:focus-visible, .focus-visible)::before { + border-color: var(--vscode-focusBorder); +} + .monaco-workbench .projectbar .action-item .action-label { display: flex; align-items: center; @@ -70,11 +74,11 @@ width: 24px; height: 24px; font-size: 16px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-activityBar-inactiveForeground); } -.monaco-workbench .projectbar .action-item:hover .action-label { +.monaco-workbench .projectbar .action-item:is(:hover, .hovered) .action-label { color: var(--vscode-activityBar-foreground); } @@ -97,7 +101,7 @@ border-radius: var(--vscode-cornerRadius-medium); } -.monaco-workbench .projectbar .action-item.workspace-entry:hover .action-label.workspace-icon { +.monaco-workbench .projectbar .action-item.workspace-entry:is(:hover, .hovered) .action-label.workspace-icon { background-color: var(--vscode-activityBar-foreground); } @@ -111,7 +115,7 @@ border-radius: 0; } -.monaco-workbench .projectbar .action-item.workspace-entry:hover .action-label.workspace-icon.codicon-icon { +.monaco-workbench .projectbar .action-item.workspace-entry:is(:hover, .hovered) .action-label.workspace-icon.codicon-icon { background-color: transparent; color: var(--vscode-activityBar-foreground); } @@ -147,19 +151,22 @@ } /* High contrast styling */ -.monaco-workbench.hc-black .projectbar .action-item .action-label, -.monaco-workbench.hc-light .projectbar .action-item .action-label { +.monaco-workbench:is(.hc-black, .hc-light) .projectbar .action-item .action-label { padding: 6px; } -.monaco-workbench.hc-black .projectbar .action-item.checked .action-label::before, -.monaco-workbench.hc-light .projectbar .action-item.checked .action-label::before { - outline: 1px solid var(--vscode-contrastActiveBorder); +.monaco-workbench:is(.hc-black, .hc-light) .projectbar .action-item::before { + border-radius: 0; +} + +.monaco-workbench:is(.hc-black, .hc-light) .projectbar .action-item.checked:not(:focus-visible, .focus-visible)::before { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); } -.monaco-workbench.hc-black .projectbar .action-item:hover .action-label::before, -.monaco-workbench.hc-light .projectbar .action-item:hover .action-label::before { - outline: 1px dashed var(--vscode-contrastActiveBorder); +.monaco-workbench:is(.hc-black, .hc-light) .projectbar .action-item:not(.checked):is(:hover, .hovered):not(:focus-visible, .focus-visible)::before { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); } /* ===== Global Composite Bar (Accounts, Settings) at bottom ===== */ @@ -194,7 +201,7 @@ .monaco-workbench .projectbar > .content > .monaco-action-bar .action-item.active .action-label.codicon, .monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:focus .action-label.codicon, -.monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:hover .action-label.codicon { +.monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:is(:hover, .hovered) .action-label.codicon { color: var(--vscode-activityBar-foreground) !important; } @@ -258,6 +265,6 @@ .monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:active .profile-text-overlay, .monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:focus .profile-text-overlay, -.monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:hover .profile-text-overlay { +.monaco-workbench .projectbar > .content > .monaco-action-bar .action-item:is(:hover, .hovered) .profile-text-overlay { color: var(--vscode-activityBar-foreground); } diff --git a/src/vs/sessions/browser/parts/media/sidebarPart.css b/src/vs/sessions/browser/parts/media/sidebarPart.css index a2efe1dfdccf..2f98fca2519c 100644 --- a/src/vs/sessions/browser/parts/media/sidebarPart.css +++ b/src/vs/sessions/browser/parts/media/sidebarPart.css @@ -31,7 +31,7 @@ /* Toggled state for the sidebar toggle button in the sidebar title area */ .agent-sessions-workbench .part.sidebar > .composite.title > .global-actions-left .action-label.checked { background: var(--vscode-toolbar-activeBackground); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* Preserve toggled background when the toggle button is hovered or focused */ diff --git a/src/vs/sessions/browser/parts/media/titlebarpart.css b/src/vs/sessions/browser/parts/media/titlebarpart.css index 952ff2c76816..3b81116bd1b0 100644 --- a/src/vs/sessions/browser/parts/media/titlebarpart.css +++ b/src/vs/sessions/browser/parts/media/titlebarpart.css @@ -119,16 +119,20 @@ } .monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-right-layout-container { + padding-right: var(--vscode-spacing-size40); +} + +.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right.has-window-controls > .titlebar-right-layout-container:not(.titlebar-last-actions) { padding-right: var(--vscode-spacing-size80); } /* The last shown actions of a window with layout actions, such as a chat window, keep the inset of the main window's last * actions to the window's edge: its layout actions, or the actions before them while those show in its Session Activity Bar. */ .monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-actions-container.titlebar-last-actions { - padding-right: calc(var(--vscode-spacing-size80) + var(--vscode-agents-layout-floatingPanelGap)); + padding-right: calc(var(--vscode-spacing-size40) + var(--vscode-agents-layout-floatingPanelGap)); } -.monaco-workbench:not(.fullscreen) .part.titlebar > .sessions-titlebar-container.custom-window-controls > .titlebar-right > .titlebar-actions-container.titlebar-last-actions { +.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right.has-window-controls > .titlebar-actions-container.titlebar-last-actions { padding-right: var(--vscode-spacing-size80); } @@ -137,7 +141,7 @@ } .monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-screen-reader-container .monaco-button { - height: 22px; + height: var(--vscode-spacing-size240); padding: 0 var(--vscode-spacing-size80); } @@ -150,19 +154,52 @@ gap: 1px; } -.agent-sessions-workbench.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-session-actions-container .monaco-toolbar .actions-container > .action-item.open-in-vscode-titlebar-widget + .action-item { - margin-left: 5px; +.agent-sessions-workbench.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right .monaco-toolbar .actions-container { + gap: var(--vscode-spacing-size40); +} + +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item :is(.action-label, .monaco-button, .monaco-button-dropdown) { + box-sizing: border-box; + height: var(--vscode-spacing-size240); + min-height: var(--vscode-spacing-size240); +} + +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item .action-label { + min-width: var(--vscode-spacing-size240); + padding: var(--vscode-spacing-size40); + border-radius: var(--vscode-cornerRadius-small); +} + +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item :is(.action-label.codicon, .monaco-button.codicon) { + width: var(--vscode-spacing-size240); +} + +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item .monaco-button { + padding-block: 0; } -/* Add spacing between the session action group and the layout actions that follow it. */ -.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-session-actions-container:not(.has-no-actions) + :is(.titlebar-right-layout-container, .titlebar-window-layout-container):not(.has-no-actions) { +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item .monaco-button.codicon { + padding-inline: 0; + justify-content: center; +} + +.agent-sessions-workbench .sessions-titlebar-container > .titlebar-right .monaco-action-bar .action-item.changes-actions-bar { + margin-inline: 0; +} + +/* + * Add spacing between the session action group and the actions that follow it: extension actions or layout actions. + * Empty or overflowing extension actions don't take part, the layout actions after them get the spacing. + */ +.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-session-actions-container:not(.has-no-actions) + :is(.titlebar-extension-actions-container, .titlebar-right-layout-container, .titlebar-window-layout-container):not(.has-no-actions), +.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-session-actions-container:not(.has-no-actions) + .titlebar-extension-actions-container:is(.has-no-actions, .overflowing) + .titlebar-right-layout-container:not(.has-no-actions) { margin-left: var(--vscode-spacing-size40); } /* Toggled action buttons in session actions toolbar */ .monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-session-actions-container .action-label.checked { background: var(--vscode-toolbar-activeBackground); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* Secondary sidebar toggle uses icon variants for toggle state — no background needed */ diff --git a/src/vs/sessions/browser/parts/panelPart.ts b/src/vs/sessions/browser/parts/panelPart.ts index 132ddfd65ff9..bca1f42315dc 100644 --- a/src/vs/sessions/browser/parts/panelPart.ts +++ b/src/vs/sessions/browser/parts/panelPart.ts @@ -83,7 +83,6 @@ export class PanelPart extends AbstractPaneCompositePart { static readonly activePanelSettingsKey = 'workbench.agentsession.panelpart.activepanelid'; /** Visual margin values for the card-like appearance */ - static readonly MARGIN_TOP = AGENTS_FLOATING_PANEL_GAP; constructor( @INotificationService notificationService: INotificationService, @@ -239,17 +238,18 @@ export class PanelPart extends AbstractPaneCompositePart { // Layout content with reduced dimensions to account for visual margins and border. const compact = this.layoutService.isModernUICompact(); + const spacing = this.layoutService.getPanelSpacing(); const borderTotal = compact ? 0 : 2; const sessionFrameInset = this.layoutService.isVisible(Parts.SESSIONS_PART) - ? getSessionsPartFrameInset(this.layoutService.mainContainer) + ? getSessionsPartFrameInset(this.layoutService.mainContainer, spacing) : 0; - const marginTop = compact ? 0 : Math.max(0, PanelPart.MARGIN_TOP - sessionFrameInset); + const marginTop = compact ? 0 : Math.max(0, spacing - sessionFrameInset); const marginLeft = !compact && !isPhoneLayout(this.layoutService) && !this.layoutService.isVisible(Parts.SIDEBAR_PART) ? AGENTS_FLOATING_PANEL_GAP : 0; const editorPaneVisible = this.layoutService.isVisible(Parts.EDITOR_PART, mainWindow) || this.layoutService.isVisible(Parts.AUXILIARYBAR_PART); const marginRight = !compact && this.layoutService.getPanelAlignment() === 'center' && editorPaneVisible - ? AGENTS_FLOATING_PANEL_GAP + ? spacing : 0; super.layout( width - marginLeft - marginRight - borderTotal, diff --git a/src/vs/sessions/browser/parts/titlebarPart.ts b/src/vs/sessions/browser/parts/titlebarPart.ts index ba4456100465..365891a12868 100644 --- a/src/vs/sessions/browser/parts/titlebarPart.ts +++ b/src/vs/sessions/browser/parts/titlebarPart.ts @@ -26,6 +26,7 @@ import { Parts, IWorkbenchLayoutService, LayoutSettings, ModernUIDensity } from import { IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; import { IHostService } from '../../../workbench/services/host/browser/host.js'; import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../platform/actions/browser/toolbar.js'; +import { MenuId } from '../../../platform/actions/common/actions.js'; import { MenuWorkbenchButtonBar } from '../../../platform/actions/browser/buttonbar.js'; import { IEditorGroupsContainer } from '../../../workbench/services/editor/common/editorGroupsService.js'; import { CodeWindow, mainWindow } from '../../../base/browser/window.js'; @@ -350,6 +351,16 @@ export class TitlebarPart extends Part implements ITitlebarPart { toolbarOptions: { primaryGroup: () => true }, })); + // Extension contributed actions (before right toolbar) + const extensionActionsContainer = prepend(this.rightContent, $('div.titlebar-actions-container.titlebar-extension-actions-container')); + const extensionActionsToolBar = this._register(this.instantiationService.createInstance(MenuWorkbenchToolBar, extensionActionsContainer, MenuId.AgentsTitleBar, { + hoverDelegate, + contextMenu: AgentsWindowMenus.TitleBarContext, + hiddenItemStrategy: HiddenItemStrategy.NoHide, + telemetrySource: 'titlePart.extensions', + toolbarOptions: { primaryGroup: () => true }, + })); + // The layout actions of a window with layout modes (before right toolbar), such as a chat window: its Layout menu and // the buttons of its actions, which the user shows and hides from the context menu of the toolbar. const windowLayoutContainer = this.showsWindowLayoutActions ? prepend(this.rightContent, $('div.titlebar-actions-container.titlebar-window-layout-container')) : undefined; @@ -386,11 +397,12 @@ export class TitlebarPart extends Part implements ITitlebarPart { updateScreenReaderButtonBar(); this.overflowManagedToolBarElements.push(screenReaderToolBarElement); - this.rightToolBarElements.push(...[screenReaderToolBarElement, sessionActionsContainer, windowLayoutContainer, rightToolbarContainer].filter(isDefined)); + this.rightToolBarElements.push(...[screenReaderToolBarElement, sessionActionsContainer, windowLayoutContainer, extensionActionsContainer, rightToolbarContainer].filter(isDefined)); this.updateLastRightToolBar(); this.registerOverflowManagedToolBar(centerActionsContainer, centerActionsToolBar); this.registerOverflowManagedToolBar(centerNavContainer, centerNavToolBar); this.registerOverflowManagedToolBar(rightToolbarContainer, rightToolBar); + this.registerOverflowManagedToolBar(extensionActionsContainer, extensionActionsToolBar); this.registerOverflowManagedToolBar(sessionActionsContainer, sessionActionsToolBar); if (windowLayoutContainer && windowLayoutToolBar) { this.registerOverflowManagedToolBar(windowLayoutContainer, windowLayoutToolBar); @@ -460,6 +472,8 @@ export class TitlebarPart extends Part implements ITitlebarPart { } private updateTitleBarToolBarOverflow(): void { + const hasWindowControls = Array.from(this.rightContent.children).some(element => element.classList.contains('window-controls-container') && element.clientWidth > 0); + this.rightContent.classList.toggle('has-window-controls', hasWindowControls); this.updateOverflowingToolBars(); this.updateLastRightToolBar(); } @@ -515,7 +529,7 @@ export class TitlebarPart extends Part implements ITitlebarPart { } focus(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax (this.element.querySelector('[tabindex]:not([tabindex="-1"])') as HTMLElement | null)?.focus(); } diff --git a/src/vs/sessions/browser/widget/openInVSCodeWidget.ts b/src/vs/sessions/browser/widget/openInVSCodeWidget.ts index 100c7786b5b7..723e00417dc9 100644 --- a/src/vs/sessions/browser/widget/openInVSCodeWidget.ts +++ b/src/vs/sessions/browser/widget/openInVSCodeWidget.ts @@ -33,7 +33,7 @@ export class OpenInVSCodeTitleBarWidget extends BaseActionViewItem { override render(container: HTMLElement): void { super.render(container); - container.classList.add('open-in-vscode-titlebar-widget'); + container.classList.add('open-in-vscode-titlebar-widget', 'agent-sessions-interactive'); container.setAttribute('role', 'button'); // Set quality attribute for distro icon selection. Only set when quality is diff --git a/src/vs/sessions/browser/workbench.ts b/src/vs/sessions/browser/workbench.ts index 6f5c74d5e7aa..8751ed63ed85 100644 --- a/src/vs/sessions/browser/workbench.ts +++ b/src/vs/sessions/browser/workbench.ts @@ -17,7 +17,7 @@ import { onUnexpectedError, setUnexpectedErrorHandler } from '../../base/common/ import { isWindows, isLinux, isWeb, isNative, isMacintosh, isIOS } from '../../base/common/platform.js'; import { Parts, Position, PanelAlignment, IWorkbenchLayoutService, SINGLE_WINDOW_PARTS, MULTI_WINDOW_PARTS, IPartVisibilityChangeEvent, positionToString, LayoutSettings, ModernUIDensity } from '../../workbench/services/layout/browser/layoutService.js'; import { ILayoutOffsetInfo } from '../../platform/layout/browser/layoutService.js'; -import { Part } from '../../workbench/browser/part.js'; +import { Part, relayoutWorkbenchParts, updateSashEndpoints } from '../../workbench/browser/part.js'; import { Direction, ISerializableView, ISerializedGrid, ISerializedLeafNode, ISerializedNode, IViewSize, Orientation, SerializableGrid, Sizing } from '../../base/browser/ui/grid/grid.js'; import { IEditorGroupsService } from '../../workbench/services/editor/common/editorGroupsService.js'; import { ContentPart } from '../../workbench/browser/parts/editor/contentPart.js'; @@ -74,7 +74,7 @@ import { MenuActivityBarSize } from '../../workbench/browser/parts/activitybar/m import { CustomViewVisibleContext, EditorMaximizedContext } from '../common/agentsWindowContextKeys.js'; import { SessionsLayoutPolicy, ViewportClass } from './layoutPolicy.js'; import { ChatLayoutPresentation } from '../common/chatLayout.js'; -import { AGENTS_CARD_SURFACE_CLASS, AGENTS_PART_CARD_CLASS } from '../../workbench/browser/parts/sessions/agentsPartCard.js'; +import { AGENTS_CARD_SURFACE_CLASS, AGENTS_PART_CARD_CLASS, getSessionsPartFrameInset, getSidePaneFrameInset } from '../../workbench/browser/parts/sessions/agentsPartCard.js'; import { MobileNavigationStack } from './mobileNavigationStack.js'; import { MobileTitlebarPart } from './parts/mobile/mobileTitlebarPart.js'; import { observeSessionActivityBarSize, registerSessionActivityBarExternalHost, SessionActivityBarColumn } from '../../workbench/browser/parts/sessions/sessionActivityBarHost.js'; @@ -89,6 +89,9 @@ import { AGENTS_FLOATING_PANEL_GAP } from '../../workbench/contrib/sessions/comm import { SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING } from '../../workbench/contrib/sessions/common/sessionConfig.js'; import { observableConfigValue } from '../../platform/observable/common/platformObservableUtils.js'; import { logSettingExperimentTrigger } from '../../platform/telemetry/common/experimentTrigger.js'; +import { IThemeService } from '../../platform/theme/common/themeService.js'; +import { ISizeService } from '../../platform/theme/common/sizeService.js'; +import { agentsPanelsSpacing } from '../../platform/theme/common/sizeRegistry.js'; import { ITelemetryService } from '../../platform/telemetry/common/telemetry.js'; import { createMainWindowInstantiationService } from '../../workbench/services/sessions/browser/sessionHost.js'; import { AgentWorkbenchLayout, ISessionsHostLayoutService, ISessionsHostSidePane } from '../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; @@ -367,6 +370,7 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay //#region Properties readonly mainContainer = document.createElement('div'); + private panelSpacing = AGENTS_FLOATING_PANEL_GAP; get activeContainer(): HTMLElement { return this.getContainerFromDocument(getActiveDocument()); @@ -384,7 +388,7 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay if (targetDocument === this.mainContainer.ownerDocument) { return this.mainContainer; } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax return targetDocument.body.getElementsByClassName('monaco-workbench')[0] as HTMLElement; } } @@ -540,7 +544,7 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay // The viewport `` tag is injected by the shared workbench.html, // so we cannot use dom.ts `h()` to create it. Look it up by tag name // and filter by the `name` attribute to avoid a selector query. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const metaElements = mainWindow.document.head.getElementsByTagName('meta'); let viewportMeta: HTMLMetaElement | undefined; for (let i = 0; i < metaElements.length; i++) { @@ -603,6 +607,21 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay const lifecycleService = accessor.get(ILifecycleService); const storageService = accessor.get(IStorageService); const configurationService = accessor.get(IConfigurationService); + const sizeService = accessor.get(ISizeService); + const themeService = accessor.get(IThemeService); + const updatePanelSpacing = () => { + const spacing = sizeService.getSize(agentsPanelsSpacing, themeService.getColorTheme())!.value; + if (spacing !== this.panelSpacing) { + this.panelSpacing = spacing; + if (this.workbenchGrid) { + this.layout(); + relayoutWorkbenchParts(this.workbenchGrid); + this._layoutSidePane(); + } + } + }; + updatePanelSpacing(); + this._register(sizeService.onDidChangeSizes(updatePanelSpacing)); this.chatLayoutPresentation = this._register(new ChatLayoutPresentation(configurationService, this.agentWorkbenchLayout === AgentWorkbenchLayout.Desktop, this.layoutPolicy.isPhoneLayout)); const hostService = accessor.get(IHostService); const hoverService = accessor.get(IHoverService); @@ -1652,7 +1671,7 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay this._register(autorun(reader => { const value = size.read(reader); this.sessionActivityBarSizeKey?.set(value); - column.setLayout(this._gridGutter(), this.isModernUICompact(), value); + column.setLayout(this._sessionActivityBarColumnGap(), this.isModernUICompact(), value); })); viewMap[SessionActivityBarColumn.ID] = column; this._register(registerSessionActivityBarExternalHost(this.mainContainer, column)); @@ -1681,6 +1700,8 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay // width, so a later reveal must not force an even split over it. this._hasAppliedInitialEditorSplit = this.partVisibility.editor; + this._registerEditorPaneVisibilityClass(editorPart); + // Listen for part visibility changes (for parts in grid) for (const part of [titleBar, panelPart, sideBar, auxiliaryBarPart, sessionsPart, editorPart]) { this._register(part.onDidVisibilityChange(visible => { @@ -1740,6 +1761,14 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay })); } + /** + * Updates the side pane class as soon as the grid shows or hides the side pane's node, which is before the grid lays + * out that node and the parts beside it, whose frame insets depend on the class. + */ + private _registerEditorPaneVisibilityClass(editorPart: { readonly onDidVisibilityChange: Event }): void { + this._register(editorPart.onDidVisibilityChange(() => this._updateEditorPaneVisibilityClass())); + } + private _registerGridMaximizationListener(): void { this._register(this.workbenchGrid.onDidChangeViewMaximized(() => { this._fireDidChangePartVisibility(Parts.PANEL_PART, this.isVisible(Parts.PANEL_PART)); @@ -2131,12 +2160,17 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay return this.layoutPolicy.viewportClass.get() === 'phone' || this.isModernUICompact() ? 0 : AGENTS_FLOATING_PANEL_GAP; } + private _sessionActivityBarColumnGap(): number { + const frameInset = this.isEditorPaneVisible() ? getSidePaneFrameInset(this.mainContainer) : getSessionsPartFrameInset(this.mainContainer); + return Math.max(0, this._gridGutter() - frameInset); + } + protected _layoutGrid(): void { const mobileTopBarHeight = this.mobileTopBarElement?.offsetHeight ?? 0; // Keep the desktop grid margin stable when sidebar visibility changes. const gridGutterW = this._gridGutter(); const gridGutterH = gridGutterW; - this.sessionActivityBarColumn?.setLayout(gridGutterW, this.isModernUICompact(), this.sessionActivityBarSize?.get() ?? MenuActivityBarSize.Compact); + this.sessionActivityBarColumn?.setLayout(this._sessionActivityBarColumnGap(), this.isModernUICompact(), this.sessionActivityBarSize?.get() ?? MenuActivityBarSize.Compact); this.workbenchGrid.layout( this._mainContainerDimension.width - gridGutterW, this._mainContainerDimension.height - mobileTopBarHeight - gridGutterH @@ -2201,6 +2235,9 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay } private handleContainerDidLayout(container: HTMLElement, dimension: IDimension): void { + if (container === this.mainContainer && this.workbenchGrid) { + updateSashEndpoints(this.workbenchGrid.element, !this.isModernUICompact() && this.layoutPolicy.viewportClass.get() !== 'phone'); + } this._onDidLayoutContainer.fire({ container, dimension }); if (container === this.mainContainer) { this._onDidLayoutMainContainer.fire(dimension); @@ -2228,6 +2265,10 @@ export abstract class Workbench extends Disposable implements IAgentWorkbenchLay return this.layoutDensity === ModernUIDensity.Compact && this.layoutPolicy.viewportClass.get() !== 'phone'; } + getPanelSpacing(): number { + return this.isModernUICompact() || this.layoutPolicy.viewportClass.get() === 'phone' ? 0 : this.panelSpacing; + } + getLayoutClasses(): string[] { return coalesce([ !this.partVisibility.sidebar ? LayoutClasses.SIDEBAR_HIDDEN : undefined, diff --git a/src/vs/sessions/common/agentsWindowContextKeys.ts b/src/vs/sessions/common/agentsWindowContextKeys.ts index be4857b131ee..33d84c8f7595 100644 --- a/src/vs/sessions/common/agentsWindowContextKeys.ts +++ b/src/vs/sessions/common/agentsWindowContextKeys.ts @@ -5,7 +5,7 @@ import { localize } from '../../nls.js'; import { ContextKeyExpr, RawContextKey } from '../../platform/contextkey/common/contextkey.js'; -import { SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../workbench/contrib/sessions/common/sessionConfig.js'; +import { SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING, SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../workbench/contrib/sessions/common/sessionConfig.js'; import { DesktopLayoutContext, IsPhoneLayoutContext } from '../../workbench/contrib/sessions/common/contextkeys.js'; /* @@ -70,6 +70,15 @@ export const DesktopFilesTabAvailableContext = new RawContextKey('agent export const KeyboardVisibleContext = new RawContextKey('sessionsKeyboardVisible', false, localize('sessionsKeyboardVisible', "Whether the virtual keyboard is visible")); +/** Whether the docked Session Activity Bar makes the title bar's panel toggles redundant. */ +export const SessionActivityBarDockedContext = ContextKeyExpr.and( + DesktopLayoutContext, + IsPhoneLayoutContext.negate(), + EditorMaximizedContext.negate(), + ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_SETTING}`, true), + ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`, true), +)!; + /** * Whether the desktop layout shows the Session Activity Bar with its layout actions. It then hosts * the Toggle Side Panel and Toggle Panel actions in place of the title bar. The activity bar is diff --git a/src/vs/sessions/common/remoteWorkspaceHandoff.ts b/src/vs/sessions/common/remoteWorkspaceHandoff.ts index f2ecaf348652..b26658de20eb 100644 --- a/src/vs/sessions/common/remoteWorkspaceHandoff.ts +++ b/src/vs/sessions/common/remoteWorkspaceHandoff.ts @@ -28,8 +28,8 @@ export type RemoteAgentHostHandoffResult = /** Resolves to whether the host is connected once its connection settles. The service reports connection failures. */ readonly connected: Promise; /** - * Whether the remote's editor windows use the connected host as their own agent host. Only a tunnel's editor - * windows do, unless its gateway selected the agent host of an editor on the tunnel's machine instead. + * Whether the remote's editor windows use the connected host as their own agent host. SSH and tunnels share + * the standalone host unless an editor-owned endpoint was selected; WSL always shares it. */ readonly sharesEditorWindowAgentHost: () => boolean; readonly unavailableReason?: undefined; @@ -38,15 +38,13 @@ export type RemoteAgentHostHandoffResult = export const IRemoteWorkspaceHandoffService = createDecorator('remoteWorkspaceHandoffService'); -/** Hands folders and sessions of SSH, WSL and Tunnel editor windows to the remote agent host on the same machine. */ +/** Hands folders and sessions of SSH, WSL and Tunnel editor windows to their shared remote agent host, unless an editor-owned endpoint was selected. */ export interface IRemoteWorkspaceHandoffService { readonly _serviceBrand: undefined; /** - * Resolves a VS Code remote to the remote agent host on the same machine. - * Adds that host when the Agents Window does not know it yet, offering to - * sign in first when only an account that is not signed in can find or - * connect to it, and starts a user-initiated connection. + * Resolves an SSH, WSL or tunnel authority, adding the host if needed and starting a user-initiated connection. + * Offers sign-in first when a signed-out account is needed to find or connect to the host. */ resolveHost(remoteAuthority: string, token: CancellationToken): Promise; diff --git a/src/vs/sessions/contrib/accountMenu/browser/account.contribution.ts b/src/vs/sessions/contrib/accountMenu/browser/account.contribution.ts index 19533c661e9c..acc58ce73810 100644 --- a/src/vs/sessions/contrib/accountMenu/browser/account.contribution.ts +++ b/src/vs/sessions/contrib/accountMenu/browser/account.contribution.ts @@ -274,7 +274,7 @@ export class TitleBarAccountWidget extends BaseActionViewItem { super.render(container); this.container = container; - container.classList.add('sessions-account-titlebar-widget'); + container.classList.add('sessions-account-titlebar-widget', 'agent-sessions-interactive'); container.setAttribute('role', 'button'); container.tabIndex = 0; diff --git a/src/vs/sessions/contrib/accountMenu/browser/media/accountTitleBarWidget.css b/src/vs/sessions/contrib/accountMenu/browser/media/accountTitleBarWidget.css index 35dd6bcd6d1b..68eb5a8ef783 100644 --- a/src/vs/sessions/contrib/accountMenu/browser/media/accountTitleBarWidget.css +++ b/src/vs/sessions/contrib/accountMenu/browser/media/accountTitleBarWidget.css @@ -9,31 +9,25 @@ justify-content: center; gap: 0; position: relative; - height: 22px; - width: 22px; - min-width: 22px; + height: var(--vscode-spacing-size240); + width: var(--vscode-spacing-size240); + min-width: var(--vscode-spacing-size240); background: transparent; - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--vscode-cornerRadius-small); color: inherit; cursor: pointer; -webkit-app-region: no-drag; overflow: hidden; } -.agent-sessions-workbench .sessions-account-titlebar-widget:hover, -.agent-sessions-workbench .action-item:focus-within .sessions-account-titlebar-widget { - background: var(--vscode-toolbar-hoverBackground); -} - .agent-sessions-workbench .sessions-account-titlebar-widget:active, -.agent-sessions-workbench .sessions-account-titlebar-widget.menu-visible, -.agent-sessions-workbench .action-item:focus-within .sessions-account-titlebar-widget.menu-visible { +.agent-sessions-workbench .sessions-account-titlebar-widget.menu-visible { background: var(--vscode-toolbar-activeBackground); } -.agent-sessions-workbench .action-item:focus-within .sessions-account-titlebar-widget { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .sessions-account-titlebar-widget.menu-visible:not(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); } .agent-sessions-workbench .sessions-account-titlebar-widget-icon { @@ -69,12 +63,6 @@ display: none; } -/* Spacing between titlebar-right action items (account widget, update indicator, etc.) */ - -.monaco-workbench .part.titlebar > .sessions-titlebar-container > .titlebar-right > .titlebar-right-layout-container .monaco-action-bar .actions-container { - gap: 6px; -} - /* Badge on account icon */ .agent-sessions-workbench .sessions-account-titlebar-widget-badge { @@ -190,7 +178,7 @@ padding: 0 8px; font-size: var(--vscode-fontSize-label2); line-height: 20px; - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-medium)); } .monaco-hover.workbench-hover.sessions-account-titlebar-panel-hover, @@ -340,7 +328,7 @@ min-height: 24px; padding: 2px 6px; justify-content: flex-start; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); font-size: var(--vscode-fontSize-label1); line-height: 20px; color: var(--vscode-foreground); @@ -607,46 +595,8 @@ height: 26px; margin: 0; padding: 0 12px; - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-medium)); font-size: var(--vscode-fontSize-label1); font-weight: var(--vscode-fontWeight-semiBold); line-height: 1; } - -/* Motion animations */ - -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget { - transition: background-color 150ms ease-out; -} - -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget-icon, -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget-label, -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget-badge, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget-icon, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget-label, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget-badge { - transition: opacity 150ms ease-out, transform 150ms ease-out, background-color 150ms ease-out, color 150ms ease-out; -} - -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget:hover .sessions-account-titlebar-widget-badge, -.monaco-enable-motion .agent-sessions-workbench .sessions-account-titlebar-widget.menu-visible .sessions-account-titlebar-widget-badge, -.monaco-enable-motion .agent-sessions-workbench .action-item:focus-within .sessions-account-titlebar-widget .sessions-account-titlebar-widget-badge, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget:hover .sessions-account-titlebar-widget-badge, -.agent-sessions-workbench.monaco-enable-motion .sessions-account-titlebar-widget.menu-visible .sessions-account-titlebar-widget-badge, -.agent-sessions-workbench.monaco-enable-motion .action-item:focus-within .sessions-account-titlebar-widget .sessions-account-titlebar-widget-badge { - transform: scale(1.04); -} - -/* Reduced motion */ - -.monaco-reduce-motion .agent-sessions-workbench .sessions-account-titlebar-widget, -.monaco-reduce-motion .agent-sessions-workbench .sessions-account-titlebar-widget-icon, -.monaco-reduce-motion .agent-sessions-workbench .sessions-account-titlebar-widget-label, -.monaco-reduce-motion .agent-sessions-workbench .sessions-account-titlebar-widget-badge, -.agent-sessions-workbench.monaco-reduce-motion .sessions-account-titlebar-widget, -.agent-sessions-workbench.monaco-reduce-motion .sessions-account-titlebar-widget-icon, -.agent-sessions-workbench.monaco-reduce-motion .sessions-account-titlebar-widget-label, -.agent-sessions-workbench.monaco-reduce-motion .sessions-account-titlebar-widget-badge { - transition-duration: 0ms !important; -} diff --git a/src/vs/sessions/contrib/accountMenu/test/browser/accountTitleBarWidgetStyles.test.ts b/src/vs/sessions/contrib/accountMenu/test/browser/accountTitleBarWidgetStyles.test.ts new file mode 100644 index 000000000000..a5e01c740faf --- /dev/null +++ b/src/vs/sessions/contrib/accountMenu/test/browser/accountTitleBarWidgetStyles.test.ts @@ -0,0 +1,62 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../../../browser/media/style.css'; +import '../../browser/media/accountTitleBarWidget.css'; +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'; + +suite('Account Title Bar Widget Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('open state wins over hover while keyboard focus retains its own boundary', () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.hc-black')); + root.style.cssText = [ + '--vscode-strokeThickness: 1px', + '--vscode-toolbar-hoverBackground: #112233', + '--vscode-toolbar-activeBackground: #223344', + '--vscode-toolbar-hoverOutline: #445566', + '--vscode-contrastActiveBorder: #556677', + '--vscode-focusBorder: #778899', + ].join(';'); + store.add(toDisposable(() => root.remove())); + + const open = append(root, $('.sessions-account-titlebar-widget.agent-sessions-interactive.menu-visible.hovered')); + const focusedOpen = append(root, $('.sessions-account-titlebar-widget.agent-sessions-interactive.menu-visible.hovered.focus-visible')); + const describe = (element: HTMLElement) => { + const style = mainWindow.getComputedStyle(element); + return { + background: style.backgroundColor, + outlineColor: style.outlineColor, + outlineOffset: style.outlineOffset, + outlineStyle: style.outlineStyle, + outlineWidth: style.outlineWidth, + }; + }; + + assert.deepStrictEqual({ + open: describe(open), + focusedOpen: describe(focusedOpen), + }, { + open: { + background: 'rgb(34, 51, 68)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + focusedOpen: { + background: 'rgb(34, 51, 68)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + }); + }); +}); diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts index 0e33aa7e4489..a9f6465c94a9 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts @@ -183,7 +183,8 @@ class SubmitActiveSessionFeedbackAction extends Action2 { title: localize2('agentFeedback.submitFeedback', 'Submit Feedback'), icon: Codicon.comment, category: CHAT_CATEGORY, - precondition: ContextKeyExpr.and(ChatContextKeys.enabled, hasActiveSessionAgentFeedback), + f1: true, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, IsSessionsWindowContext, hasActiveSessionAgentFeedback), }); } diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts index 7535135cf09b..adcfe667cbe1 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts @@ -3,9 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { DisposableMap, DisposableStore, combinedDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { DisposableMap, DisposableStore, MutableDisposable, combinedDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { autorun, derived, IObservable, observableFromEvent, observableSignalFromEvent } from '../../../../base/common/observable.js'; import { Event } from '../../../../base/common/event.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { isEqual } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { isCodeEditor, isDiffEditor } from '../../../../editor/browser/editorBrowser.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'; @@ -21,7 +25,7 @@ import { getActiveResourceCandidates, getFeedbackSessionCandidates } from './age import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; import { ICodeReviewService } from '../../../../workbench/contrib/sessions/browser/codeReviewService.js'; import { EmptyFileEditorInput } from '../../../../workbench/contrib/sessions/browser/emptyFileEditorInput.js'; -import { getAcceptedAgentFeedbackCommentCount, getSessionEditorComments } from './sessionEditorComments.js'; +import { getAcceptedAgentFeedbackCommentCount, getSessionEditorComments, ISessionEditorComment } from './sessionEditorComments.js'; import { ISessionHostService, SessionHostKind } from '../../../../workbench/services/sessions/browser/sessionHost.js'; import { ISession } from '../../../../workbench/services/sessions/common/session.js'; @@ -37,6 +41,27 @@ export function getAgentFeedbackOverlayResourceCandidates(input: Parameters isEqual(comment.resourceUri, resourceUri) || comment.resourceUri.fsPath === resourceUri.fsPath); + if (commentsOfResource.length === 0 || commentsOfResource.some(comment => comment.id === currentAnchorId)) { + return undefined; + } + return commentsOfResource[0].id; +} + +/** + * The file that a diff editor shows: its modified side, or its original side when the modified side is the empty + * synthetic document that stands in for a deleted file, such as in the Changes editor. + */ +export function getDiffEditorResource(model: { readonly original: { readonly uri: URI }; readonly modified: { readonly uri: URI } }): URI { + const modified = model.modified.uri; + return modified.scheme === Schemas.inMemory && modified.path.startsWith('/synthetic/') ? model.original.uri : modified; +} + export class AgentFeedbackOverlayController { private readonly _store = new DisposableStore(); @@ -96,6 +121,49 @@ export class AgentFeedbackOverlayController { agentFeedbackService.onDidChangeFeedbackScope, )); + // When another file becomes active within the editor, such as a file picked in the Changes editor, anchor the + // navigation at that file's comments so that the counter shows where the user is. This only moves the counter: + // it does not reveal or focus the comment, which would scroll the file away from where the user put it. + const controlListener = this._store.add(new MutableDisposable()); + const syncNavigationAnchor = (pane: NonNullable) => { + const control = pane.getControl(); + const diffModel = isDiffEditor(control) ? control.getModel() : undefined; + const resourceUri = diffModel ? getDiffEditorResource(diffModel) : isCodeEditor(control) ? control.getModel()?.uri : undefined; + if (!resourceUri) { + return; + } + const candidates = getAgentFeedbackOverlayResourceCandidates(pane.input); + for (const { sessionResource } of getFeedbackSessionCandidates(candidates, candidate => agentFeedbackService.getFeedbackSessionResource(candidate, hostSession?.get()))) { + const comments = getSessionEditorComments( + sessionResource, + agentFeedbackService.getFeedback(sessionResource), + codeReviewService.getPRReviewState(sessionResource).get(), + agentFeedbackService.getVisibleResolvedFeedbackIds(sessionResource), + shouldIncludeRawPRReviewComments(agentFeedbackService, sessionResource), + ); + if (comments.length > 0) { + const currentAnchorId = comments[agentFeedbackService.getNavigationBearing(sessionResource, comments).activeIdx]?.id; + const anchorId = getNavigationAnchorForResource(comments, currentAnchorId, resourceUri); + if (anchorId) { + agentFeedbackService.setNavigationAnchor(sessionResource, anchorId, { reveal: false }); + } + return; + } + } + }; + const listenToActiveControl = () => { + const pane = group.activeEditorPane; + if (!pane) { + controlListener.clear(); + return; + } + controlListener.value = pane.onDidChangeControl(() => syncNavigationAnchor(pane)); + // The editor may have shown its file before the group announced it as active. + syncNavigationAnchor(pane); + }; + listenToActiveControl(); + this._store.add(group.onDidActiveEditorChange(listenToActiveControl)); + this._store.add(autorun(r => { activeSignal.read(r); diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts index 6a4f4c51ff4e..f35ae661ec1c 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorWidgetContribution.ts @@ -52,8 +52,8 @@ export class AgentFeedbackEditorWidgetContribution extends Disposable implements ) { super(); - this._store.add(this._agentFeedbackService.onDidChangeNavigation(sessionResource => { - if (this._sessionResource && sessionResource.toString() === this._sessionResource.toString()) { + this._store.add(this._agentFeedbackService.onDidChangeNavigation(({ sessionResource, reveal }) => { + if (reveal && this._sessionResource && sessionResource.toString() === this._sessionResource.toString()) { this._handleNavigation(); } })); @@ -231,7 +231,9 @@ export class AgentFeedbackEditorWidgetContribution extends Disposable implements shouldIncludeRawPRReviewComments(this._agentFeedbackService, this._sessionResource), ); const bearing = this._agentFeedbackService.getNavigationBearing(this._sessionResource, comments); - if (bearing.activeIdx < 0) { + // A passive anchor (set without reveal) must not expand, focus or scroll to its comment, + // also when widgets are created or rebuilt after it was set. + if (bearing.activeIdx < 0 || bearing.reveal === false) { return; } diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts index cf21f0319ec9..fd4648e07309 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts @@ -23,7 +23,7 @@ import { IFocusedSessionHostService } from '../../../../workbench/services/sessi import { ISessionsProvidersService } from '../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { editingEntriesContainResource } from '../../../../workbench/contrib/chat/browser/sessionResourceMatching.js'; import { changeMatchesResource, getActiveResourceCandidates } from './agentFeedbackEditorUtils.js'; -import { IAgentFeedbackContext, AGENT_FEEDBACK_NEW_SESSION_RESOURCE, INavigableSessionComment, IAcceptFeedbackOptions, IAgentFeedbackChangeEvent, IAgentFeedbackNavigationBearing, IAgentFeedbackCommentRevealEvent, IAgentFeedbackAddedEvent, IAgentFeedbackConvertedEvent, IAgentFeedbackReplyAddedEvent, IAgentFeedbackSubmittedEvent, ISubmitFeedbackOptions, IAgentFeedbackService } from '../../../../workbench/contrib/sessions/browser/agentFeedback.js'; +import { IAgentFeedbackContext, AGENT_FEEDBACK_NEW_SESSION_RESOURCE, INavigableSessionComment, IAcceptFeedbackOptions, IAgentFeedbackChangeEvent, IAgentFeedbackNavigationBearing, IAgentFeedbackNavigationChangeEvent, IAgentFeedbackCommentRevealEvent, IAgentFeedbackAddedEvent, IAgentFeedbackConvertedEvent, IAgentFeedbackReplyAddedEvent, IAgentFeedbackSubmittedEvent, ISubmitFeedbackOptions, IAgentFeedbackService } from '../../../../workbench/contrib/sessions/browser/agentFeedback.js'; import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; import { IChatWidget, IChatWidgetService } from '../../../../workbench/contrib/chat/browser/chat.js'; import { ILogService } from '../../../../platform/log/common/log.js'; @@ -57,7 +57,7 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe readonly onDidChangeFeedback = this._onDidChangeFeedback.event; private readonly _onDidChangeFeedbackVisibility = this._store.add(new Emitter()); readonly onDidChangeFeedbackVisibility = this._onDidChangeFeedbackVisibility.event; - private readonly _onDidChangeNavigation = this._store.add(new Emitter()); + private readonly _onDidChangeNavigation = this._store.add(new Emitter()); readonly onDidChangeNavigation = this._onDidChangeNavigation.event; private readonly _onDidRevealSessionComment = this._store.add(new Emitter()); readonly onDidRevealSessionComment = this._onDidRevealSessionComment.event; @@ -77,7 +77,8 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe /** sessionResource → recency sequence (set on every feedback change) */ private readonly _sessionUpdatedOrder = new Map(); private _sessionUpdatedSequence = 0; - private readonly _navigationAnchorBySession = new Map(); + /** sessionResource → navigation anchor, and whether editors may reveal and focus it */ + private readonly _navigationAnchorBySession = new Map(); private readonly _visibleResolvedFeedbackIds = new ResourceMap>(); /** fileResource → sessionResource active when the editor for that file was first seen */ @@ -255,7 +256,7 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe this._sessionUpdatedOrder.delete(key); } this._onDidChangeFeedback.fire({ sessionResource, feedbackItems }); - this._onDidChangeNavigation.fire(sessionResource); + this._onDidChangeNavigation.fire({ sessionResource, reveal: this._navigationAnchorBySession.get(key)?.reveal ?? true }); if (isEqual(sessionResource, AGENT_FEEDBACK_NEW_SESSION_RESOURCE)) { this._rebindNewSessionWorkspace(); } @@ -425,7 +426,7 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe removeFeedback(sessionResource: URI, feedbackId: string): void { const key = sessionResource.toString(); - if (this._navigationAnchorBySession.get(key) === feedbackId) { + if (this._navigationAnchorBySession.get(key)?.itemId === feedbackId) { this._navigationAnchorBySession.delete(key); } this._backendForSession(sessionResource).remove(sessionResource, feedbackId); @@ -665,7 +666,7 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe return undefined; } - const anchorId = this._navigationAnchorBySession.get(key); + const anchorId = this._navigationAnchorBySession.get(key)?.itemId; let anchorIndex = anchorId ? items.findIndex(item => item.id === anchorId) : -1; if (anchorIndex < 0 && !next) { @@ -681,21 +682,22 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe return item; } - setNavigationAnchor(sessionResource: URI, itemId: string | undefined): void { + setNavigationAnchor(sessionResource: URI, itemId: string | undefined, options?: { readonly reveal?: boolean }): void { const key = sessionResource.toString(); + const reveal = options?.reveal ?? true; if (itemId) { - this._navigationAnchorBySession.set(key, itemId); + this._navigationAnchorBySession.set(key, { itemId, reveal }); } else { this._navigationAnchorBySession.delete(key); } - this._onDidChangeNavigation.fire(sessionResource); + this._onDidChangeNavigation.fire({ sessionResource, reveal }); } getNavigationBearing(sessionResource: URI, items: readonly INavigableSessionComment[] = this.getFeedback(sessionResource)): IAgentFeedbackNavigationBearing { const key = sessionResource.toString(); - const anchorId = this._navigationAnchorBySession.get(key); - const activeIdx = anchorId ? items.findIndex(item => item.id === anchorId) : -1; - return { activeIdx, totalCount: items.length }; + const anchor = this._navigationAnchorBySession.get(key); + const activeIdx = anchor ? items.findIndex(item => item.id === anchor.itemId) : -1; + return { activeIdx, totalCount: items.length, reveal: anchor?.reveal ?? true }; } clearFeedback(sessionResource: URI): void { @@ -747,16 +749,20 @@ export class AgentFeedbackService extends Disposable implements IAgentFeedbackSe } const agentHost = this.isAgentHostSession(sessionResource); const feedbackIds = agentHost ? options.feedbackIds : undefined; - const acceptedItems = this.getFeedback(sessionResource).filter(item => - item.state === AgentFeedbackState.Accepted && (!feedbackIds || feedbackIds.includes(item.id))); - if (!acceptedItems.length) { + const selectedItems = this.getFeedback(sessionResource).filter(item => + (item.state === AgentFeedbackState.Accepted && (!feedbackIds || feedbackIds.includes(item.id))) + || (item.state === AgentFeedbackState.Created && options.feedbackIds?.includes(item.id))); + if (!selectedItems.length) { throw new Error(localize('agentFeedback.commentsUnavailable', "The selected comments are no longer available.")); } const annotationsResource = agentHost ? this._getAnnotationsBackend().getAnnotationsChannelResource(sessionResource) : undefined; await this._sessionsManagementService.sendRequestInBackground(session, chat, { query: options.query ?? '/act-on-feedback', - attachedContext: [createAgentFeedbackVariableEntry(sessionResource, acceptedItems, annotationsResource)], + attachedContext: [createAgentFeedbackVariableEntry(sessionResource, selectedItems, annotationsResource)], }); + for (const item of selectedItems) { + this.acceptFeedback(sessionResource, item.id); + } this.markFeedbackSubmitted(sessionResource, feedbackIds); options.onRequestAccepted?.(); return true; diff --git a/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css index aca45623be69..587b8e106a31 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css +++ b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css @@ -8,12 +8,19 @@ z-index: 10; } +/* The button replaces the hovered line number, so hide the digits it would otherwise only partially cover. */ +.monaco-editor .line-numbers.agent-feedback-glyph.line-hover { + color: transparent; +} + +/* Fixed width, aligned with the end of the line numbers, so the button doesn't grow with the line-number column. */ .monaco-editor .line-numbers.agent-feedback-glyph.line-hover::before { content: var(--vscode-icon-plus-content); font-family: var(--vscode-icon-plus-font-family); font-size: var(--vscode-codiconFontSize); position: absolute; - inset: 0; + inset: 0 0 0 auto; + width: var(--vscode-spacing-size200); z-index: 10; color: var(--vscode-editorGutter-commentGlyphForeground, var(--vscode-foreground)); background-color: var(--vscode-editorGutter-commentRangeForeground); diff --git a/src/vs/sessions/contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.ts b/src/vs/sessions/contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.ts index 38f4c931a564..c69d5570edfa 100644 --- a/src/vs/sessions/contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/nullAgentFeedbackService.contribution.ts @@ -9,7 +9,7 @@ import { constObservable } from '../../../../base/common/observable.js'; import { URI } from '../../../../base/common/uri.js'; import { IRange } from '../../../../editor/common/core/range.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; -import { AGENT_FEEDBACK_NEW_SESSION_RESOURCE, IAgentFeedbackAddedEvent, IAgentFeedbackChangeEvent, IAgentFeedbackCommentRevealEvent, IAgentFeedbackConvertedEvent, IAgentFeedbackNavigationBearing, IAgentFeedbackReplyAddedEvent, IAgentFeedbackService, IAgentFeedbackSubmittedEvent, INavigableSessionComment, IAgentFeedbackContext } from '../../../../workbench/contrib/sessions/browser/agentFeedback.js'; +import { AGENT_FEEDBACK_NEW_SESSION_RESOURCE, IAgentFeedbackAddedEvent, IAgentFeedbackChangeEvent, IAgentFeedbackCommentRevealEvent, IAgentFeedbackConvertedEvent, IAgentFeedbackNavigationBearing, IAgentFeedbackNavigationChangeEvent, IAgentFeedbackReplyAddedEvent, IAgentFeedbackService, IAgentFeedbackSubmittedEvent, INavigableSessionComment, IAgentFeedbackContext } from '../../../../workbench/contrib/sessions/browser/agentFeedback.js'; import { AgentFeedbackKind, AgentFeedbackState, IAgentFeedback } from '../../../../workbench/contrib/sessions/browser/agentFeedbackModel.js'; import { ICodeReviewSuggestion } from '../../../../workbench/contrib/sessions/browser/codeReviewService.js'; import { IFeedbackPullRequest } from '../../../../platform/agentHost/common/meta/agentFeedbackAnnotations.js'; @@ -26,7 +26,7 @@ class NullAgentFeedbackService extends Disposable implements IAgentFeedbackServi readonly onDidChangeFeedback = this._register(new Emitter()).event; readonly onDidChangeFeedbackVisibility = this._register(new Emitter()).event; - readonly onDidChangeNavigation = this._register(new Emitter()).event; + readonly onDidChangeNavigation = this._register(new Emitter()).event; readonly onDidRevealSessionComment = this._register(new Emitter()).event; readonly onDidChangeFeedbackScope = this._register(new Emitter()).event; readonly activeFeedbackSessionResource = constObservable(AGENT_FEEDBACK_NEW_SESSION_RESOURCE); diff --git a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorOverlay.test.ts b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorOverlay.test.ts index 7bb25ab3a469..15dbda6f61ae 100644 --- a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorOverlay.test.ts +++ b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorOverlay.test.ts @@ -8,6 +8,7 @@ import { Codicon } from '../../../../../base/common/codicons.js'; import { Event } from '../../../../../base/common/event.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; +import { Schemas } from '../../../../../base/common/network.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { IWorkbenchLayoutService } from '../../../../../workbench/services/layout/browser/layoutService.js'; @@ -21,7 +22,8 @@ import { Registry } from '../../../../../platform/registry/common/platform.js'; import { EditorExtensions, IEditorFactoryRegistry } from '../../../../../workbench/common/editor.js'; import { ICodeReviewService } from '../../../../../workbench/contrib/sessions/browser/codeReviewService.js'; import { EmptyFileEditorInput } from '../../../../../workbench/contrib/sessions/browser/emptyFileEditorInput.js'; -import { AgentFeedbackEditorOverlay, getAgentFeedbackOverlayResourceCandidates } from '../../browser/agentFeedbackEditorOverlay.js'; +import { AgentFeedbackEditorOverlay, getAgentFeedbackOverlayResourceCandidates, getDiffEditorResource, getNavigationAnchorForResource } from '../../browser/agentFeedbackEditorOverlay.js'; +import { ISessionEditorComment } from '../../browser/sessionEditorComments.js'; import { IAgentFeedbackService } from '../../../../../workbench/contrib/sessions/browser/agentFeedback.js'; import { constObservable } from '../../../../../base/common/observable.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; @@ -170,4 +172,43 @@ suite('AgentFeedbackEditorOverlay', () => { emptyFiles: [], }); }); + + test('anchors the navigation at the first comment of a file that is shown, unless it already is at one of its comments', () => { + const a = URI.file('/repo/a.ts'); + const b = URI.file('/repo/b.ts'); + const c = URI.file('/repo/c.ts'); + const comments = [ + upcastPartial({ id: 'a1', resourceUri: a }), + upcastPartial({ id: 'b1', resourceUri: b }), + upcastPartial({ id: 'b2', resourceUri: b }), + ]; + + assert.deepStrictEqual({ + anchorInOtherFile: getNavigationAnchorForResource(comments, 'a1', b), + noAnchor: getNavigationAnchorForResource(comments, undefined, b), + anchorInFile: getNavigationAnchorForResource(comments, 'b2', b), + fileWithoutComments: getNavigationAnchorForResource(comments, 'a1', c), + }, { + anchorInOtherFile: 'b1', + noAnchor: 'b1', + anchorInFile: undefined, + fileWithoutComments: undefined, + }); + }); + + test('uses the original file of a diff whose modified side is the empty document of a deleted file', () => { + const file = URI.file('/repo/a.ts'); + const synthetic = (id: string) => URI.from({ scheme: Schemas.inMemory, path: `/synthetic/${id}` }); + const diff = (original: URI, modified: URI) => getDiffEditorResource({ original: { uri: original }, modified: { uri: modified } }).toString(); + + assert.deepStrictEqual({ + modified: diff(URI.file('/repo/.git/a.ts'), file), + added: diff(synthetic('1'), file), + deleted: diff(file, synthetic('2')), + }, { + modified: file.toString(), + added: file.toString(), + deleted: file.toString(), + }); + }); }); diff --git a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorWidgetContribution.test.ts b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorWidgetContribution.test.ts index 9a4cab42b347..f8112d5bb600 100644 --- a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorWidgetContribution.test.ts +++ b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackEditorWidgetContribution.test.ts @@ -25,7 +25,7 @@ import { ServiceCollection } from '../../../../../platform/instantiation/common/ import { IMarkdownRendererService, MarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js'; import { ICodeReviewService, IPRReviewState, PRReviewStateKind } from '../../../../../workbench/contrib/sessions/browser/codeReviewService.js'; import { AgentFeedbackEditorWidgetContribution } from '../../browser/agentFeedbackEditorWidgetContribution.js'; -import { IAgentFeedbackChangeEvent, IAgentFeedbackService } from '../../../../../workbench/contrib/sessions/browser/agentFeedback.js'; +import { IAgentFeedbackChangeEvent, IAgentFeedbackNavigationChangeEvent, IAgentFeedbackService } from '../../../../../workbench/contrib/sessions/browser/agentFeedback.js'; import { AgentFeedbackKind, AgentFeedbackState, IAgentFeedback } from '../../../../../workbench/contrib/sessions/browser/agentFeedbackModel.js'; suite('AgentFeedbackEditorWidgetContribution', () => { @@ -39,7 +39,7 @@ suite('AgentFeedbackEditorWidgetContribution', () => { test('keeps grouped navigation visible without remeasuring previews on editor scroll', () => { const session = URI.parse('test://session/grouped-navigation'); - const navigation = store.add(new Emitter()); + const navigation = store.add(new Emitter()); let activeIdx = -1; let feedback: readonly IAgentFeedback[] = []; const services = new ServiceCollection(); @@ -100,7 +100,7 @@ suite('AgentFeedbackEditorWidgetContribution', () => { contribution = disposables.add(instantiationService.createInstance(AgentFeedbackEditorWidgetContribution, editor)); const navigate = (index: number) => { activeIdx = index; - navigation.fire(session); + navigation.fire({ sessionResource: session, reveal: true }); editor.render(); const widget = container.querySelector('.agent-feedback-widget')!; const card = widget.querySelector('.agent-feedback-widget-item.focused')!; @@ -143,6 +143,99 @@ suite('AgentFeedbackEditorWidgetContribution', () => { assert.deepStrictEqual({ states, firstAnchorAboveViewport, offscreenGroupHidden, previewMutations }, { states: [visible, visible], firstAnchorAboveViewport: true, offscreenGroupHidden: true, previewMutations: 0 }); }); + test('does not reveal or focus a passive anchor on initialization, rebuild or navigation change', () => { + const session = URI.parse('test://session/passive-navigation'); + const navigation = store.add(new Emitter()); + const changes = store.add(new Emitter()); + let activeIdx = -1; + let reveal = true; + let feedback: readonly IAgentFeedback[] = []; + const services = new ServiceCollection(); + services.set(IAgentFeedbackService, new class extends mock() { + override readonly onDidChangeFeedback = changes.event; + override readonly onDidChangeFeedbackVisibility = Event.None; + override readonly onDidChangeFeedbackScope = Event.None; + override readonly onDidChangeNavigation = navigation.event; + override getFeedbackSessionResource(): URI { return session; } + override getFeedback(): readonly IAgentFeedback[] { return feedback; } + override getVisibleResolvedFeedbackIds(): ReadonlySet { return new Set(); } + override isAgentHostSession(): boolean { return true; } + override hasLoadedFeedback(): boolean { return true; } + override getChatChanges() { return []; } + override getNavigationBearing() { return { activeIdx, totalCount: feedback.length, reveal }; } + }); + const prState = constObservable({ kind: PRReviewStateKind.None }); + services.set(ICodeReviewService, new class extends mock() { + override getPRReviewState() { return prState; } + }); + services.set(IContextMenuService, new class extends mock() { }()); + services.set(IDefaultAccountService, new class extends mock() { + override readonly onDidChangeDefaultAccount = Event.None; + override readonly currentDefaultAccount = null; + }); + services.set(IMarkdownRendererService, new SyncDescriptor(MarkdownRendererService)); + const states: Record = {}; + const lines = Array.from({ length: 80 }, (_, index) => `Line ${index + 1}`); + withTestCodeEditor(lines, { serviceCollection: services }, (testEditor, _viewModel, instantiationService) => { + const disposables = store.add(new DisposableStore()); + const container = append(mainWindow.document.body, $('div')); + container.style.width = '760px'; + container.style.height = '420px'; + const editor = disposables.add(instantiationService.createInstance(CodeEditorWidget, container, { + dimension: { width: 760, height: 420 }, + fontSize: 13, + lineHeight: 20, + minimap: { enabled: false }, + scrollBeyondLastLine: false, + smoothScrolling: false, + }, { contributions: [] })); + editor.setModel(testEditor.getModel()); + editor.render(); + feedback = Array.from({ length: 10 }, (_, index) => ({ + id: `feedback-${index}`, + text: 'Comment', + sessionResource: session, + resourceUri: editor.getModel()!.uri, + range: { startLineNumber: 2 + index * 8, startColumn: 1, endLineNumber: 2 + index * 8, endColumn: 1 }, + kind: AgentFeedbackKind.UserReview, + state: AgentFeedbackState.Accepted, + })); + const record = (name: string) => { + editor.render(); + states[name] = { + scrolled: editor.getScrollTop() > 0, + focused: container.querySelector('.agent-feedback-widget-item.focused') !== null, + }; + }; + let contribution: AgentFeedbackEditorWidgetContribution | undefined; + try { + // The anchor was set passively before this editor's contribution was created. + activeIdx = 9; + reveal = false; + contribution = disposables.add(instantiationService.createInstance(AgentFeedbackEditorWidgetContribution, editor)); + record('initialization'); + changes.fire({ sessionResource: session, feedbackItems: feedback }); + record('rebuild'); + navigation.fire({ sessionResource: session, reveal: false }); + record('passiveNavigation'); + reveal = true; + navigation.fire({ sessionResource: session, reveal: true }); + record('revealedNavigation'); + } finally { + contribution?.dispose(); + disposables.dispose(); + container.remove(); + } + }); + const passive = { scrolled: false, focused: false }; + assert.deepStrictEqual(states, { + initialization: passive, + rebuild: passive, + passiveNavigation: passive, + revealedNavigation: { scrolled: true, focused: true }, + }); + }); + for (const readonlyState of [AgentFeedbackState.Submitted, AgentFeedbackState.Resolved]) { for (const composer of ['edit', 'reply']) { test(`suspends and retains the ${composer} draft when feedback becomes ${readonlyState}`, () => { diff --git a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackService.test.ts b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackService.test.ts index 93845daf4cee..aed63889bb51 100644 --- a/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackService.test.ts +++ b/src/vs/sessions/contrib/agentFeedback/test/browser/agentFeedbackService.test.ts @@ -226,6 +226,25 @@ suite('AgentFeedbackService - Ordering', () => { assert.strictEqual(bearing.activeIdx, 2); }); + test('passive navigation anchors keep their reveal intent across feedback changes', () => { + const f1 = service.addFeedback(session, fileA, r(5), 'A:5'); + service.addFeedback(session, fileA, r(20), 'A:20'); + const reveals: boolean[] = []; + store.add(service.onDidChangeNavigation(event => reveals.push(event.reveal))); + + service.setNavigationAnchor(session, f1.id, { reveal: false }); + const passiveBearing = service.getNavigationBearing(session); + service.addFeedback(session, fileB, r(1), 'B:1'); + service.getNextFeedback(session, true); + const revealedBearing = service.getNavigationBearing(session); + + assert.deepStrictEqual({ passiveBearing, revealedBearing, reveals }, { + passiveBearing: { activeIdx: 0, totalCount: 2, reveal: false }, + revealedBearing: { activeIdx: 1, totalCount: 3, reveal: true }, + reveals: [false, false, true], + }); + }); + test('revealFeedback anchors the matching session editor comment so its widget expands', async () => { const f1 = service.addFeedback(session, fileA, r(5), 'A:5'); const f2 = service.addFeedback(session, fileA, r(20), 'A:20'); @@ -1102,6 +1121,50 @@ suite('AgentFeedbackService - Submit (agent host)', () => { }); }); + for (const agentHost of [true, false]) { + test(`background submission preserves Created comments on failure and submits only the selection on retry (agentHost=${agentHost})`, async () => { + if (!agentHost) { + providerId = 'legacy'; + } + const selected = service.addFeedback(session, fileA, r(1), 'Selected', undefined, undefined, undefined, AgentFeedbackKind.AgentReview, AgentFeedbackState.Created); + service.addFeedback(session, fileA, r(2), 'Other', undefined, undefined, undefined, AgentFeedbackKind.AgentReview, AgentFeedbackState.Created); + const events: string[] = []; + store.add(service.onDidConvertFeedback(() => events.push('accepted'))); + store.add(service.onDidSubmitFeedback(() => events.push('submitted'))); + const options = { targetChat: backgroundChat.resource, background: true, feedbackIds: [selected.id], onRequestAccepted: () => events.push('sent') }; + const pending = service.submitFeedback(session, options); + const before = service.getFeedback(session).map(item => item.state); + const rejection = assert.rejects(pending, /Unavailable/); + await backgroundAcceptance.error(new Error('Unavailable')); + await rejection; + const afterFailure = { states: service.getFeedback(session).map(item => item.state), events: [...events] }; + + backgroundAcceptance = new DeferredPromise(); + const retry = service.submitFeedback(session, options); + await backgroundAcceptance.complete(); + await retry; + + assert.deepStrictEqual({ + before, + afterFailure, + afterRetry: service.getFeedback(session).map(item => item.state), + attachments: backgroundCalls.map(call => { + const attachment = call.options.attachedContext?.[0]; + return attachment?.kind === 'agentFeedback' ? attachment.feedbackItems.map(item => item.id) : []; + }), + events, + widgetLookups, + }, { + before: [AgentFeedbackState.Created, AgentFeedbackState.Created], + afterFailure: { states: [AgentFeedbackState.Created, AgentFeedbackState.Created], events: [] }, + afterRetry: [agentHost ? AgentFeedbackState.Submitted : AgentFeedbackState.Resolved, AgentFeedbackState.Created], + attachments: [[selected.id], [selected.id]], + events: ['accepted', 'submitted', 'sent'], + widgetLookups: [], + }); + }); + } + test('attaches the just-submitted feedback to the request and clears the attachment afterwards', async () => { service.addFeedback(session, fileA, r(10), 'Please simplify'); diff --git a/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.contribution.ts b/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.contribution.ts new file mode 100644 index 000000000000..26e12a7e2c63 --- /dev/null +++ b/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.contribution.ts @@ -0,0 +1,754 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/agentsLauncher.css'; +import * as dom from '../../../../base/browser/dom.js'; +import { getZoomFactor } from '../../../../base/browser/browser.js'; +import { mainWindow } from '../../../../base/browser/window.js'; +import { raceTimeout } from '../../../../base/common/async.js'; +import { Event } from '../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; +import { combinedDisposable, Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { IObservable, constObservable } from '../../../../base/common/observable.js'; +import { isMacintosh } from '../../../../base/common/platform.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Action2, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr, IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; +import { IContextViewService } from '../../../../platform/contextview/browser/contextView.js'; +import { Context as SuggestContext } from '../../../../editor/contrib/suggest/browser/suggest.js'; +import { EditorContextKeys } from '../../../../editor/common/editorContextKeys.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { createDecorator, IInstantiationService, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { FocusMode, INativeHostService } from '../../../../platform/native/common/native.js'; +import { InQuickInputContextKey } from '../../../../platform/quickinput/browser/quickInput.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { editorBackground } from '../../../../platform/theme/common/colors/editorColors.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; +import { AGENTS_LAUNCHER_IPC_CHANNEL, IPoint, IRectangle } from '../../../../platform/window/common/window.js'; +import { ipcRenderer } from '../../../../base/parts/sandbox/electron-browser/globals.js'; +import { IAuxiliaryWindow, IAuxiliaryWindowService } from '../../../../workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { IChatWidget, IChatWidgetService } from '../../../../workbench/contrib/chat/browser/chat.js'; +import { AGENTS_LAUNCHER_COMMAND_ID } from '../../../../workbench/contrib/chat/common/constants.js'; +import { IChatEntitlementService } from '../../../../workbench/services/chat/common/chatEntitlementService.js'; +import { IChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; +import { AbstractChatView, INewSessionDraftHost } from '../../../../workbench/contrib/sessions/browser/parts/chatView.js'; +import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { SharedChatInputComposer } from '../../../../workbench/contrib/sessions/browser/chat/sharedChatInputComposer.js'; +import { ChatInputSupportsBackgroundContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { SessionsCategories } from '../../../../workbench/contrib/sessions/common/categories.js'; +import { ISession } from '../../../../workbench/services/sessions/common/session.js'; +import { createSessionHostServices, ISessionHostService, SessionHost, SessionHostKind } from '../../../../workbench/services/sessions/browser/sessionHost.js'; +import { ChatWindowComposerBackgroundSends, ChatWindowComposerModel, createChatWindowComposerResource } from '../../../../workbench/contrib/sessions/browser/chatEditor/chatWindowComposer.js'; +import { AgentsLauncherClickThrough, AgentsLauncherPresenter, computeAgentsLauncherLayout, DismissalCheck, dismissWhenAllowed, followOrdinarySend, IAgentsLauncherLayout } from './agentsLauncher.js'; + +const AGENTS_LAUNCHER_INITIAL_HEIGHT = 180; +const AGENTS_LAUNCHER_BLUR_HIDE_DELAY = 150; +/** How long the Agents Launcher stays transparent at most as it shows, waiting for its first frame. */ +const AGENTS_LAUNCHER_REVEAL_TIMEOUT = 150; +/** + * Whether the Agents Launcher's window is transparent around its card, with room for the composer's popups, and lets clicks through + * there. Only on macOS: on Linux, transparency depends on the compositor and a window that lets clicks through receives no mouse + * moves to stop; on Windows, some systems render transparent windows opaque black (electron/electron#40515). + */ +const AGENTS_LAUNCHER_TRANSPARENT = isMacintosh; +const HIDE_AGENTS_LAUNCHER_COMMAND_ID = 'workbench.action.hideAgentsLauncher'; +const AGENTS_LAUNCHER_SEND_IN_BACKGROUND_COMMAND_ID = 'workbench.action.agentsLauncher.sendInBackground'; + +const AgentsLauncherFocusContext = new RawContextKey('agentsLauncherFocus', false, localize('agentsLauncherFocus', "Whether focus is inside the Agents Launcher")); + +export const IAgentsLauncherService = createDecorator('agentsLauncherService'); + +/** Controls the Agents Launcher: the Agents window's persistent composer and its auxiliary window. */ +export interface IAgentsLauncherService { + readonly _serviceBrand: undefined; + readonly isVisible: IObservable; + /** Shows and focuses the Agents Launcher. */ + show(): Promise; + /** Hides the Agents Launcher while preserving its draft. */ + hide(): Promise; + /** Shows or hides the Agents Launcher. */ + toggle(): Promise; + /** Starts the composer's session in the background and keeps the Agents Launcher open, with a status that can open the session. */ + sendInBackground(): Promise; +} + +/** Returns whether a context view is visible, optionally in one particular window. */ +function isContextViewVisible(contextViewService: IContextViewService, targetWindow?: Window): boolean { + const element = contextViewService.getContextViewElement(); + return element.style.display !== 'none' && (!targetWindow || dom.getWindow(element) === targetWindow); +} + +/** The display the Agents Launcher shows on, and its work area, which leaves out its menu bar and dock. */ +interface IAgentsLauncherDisplay { + readonly bounds: IRectangle; + readonly workArea: IRectangle; +} + +/** Returns whether two window bounds are identical. */ +function equalBounds(first: IRectangle | undefined, second: IRectangle): boolean { + return !!first && first.x === second.x && first.y === second.y && first.width === second.width && first.height === second.height; +} + +function containsPoint(bounds: IRectangle, point: IPoint): boolean { + return point.x >= bounds.x && point.x < bounds.x + bounds.width && point.y >= bounds.y && point.y < bounds.y + bounds.height; +} + +/** Resolves once `targetWindow` has rendered a frame since the call, or after a timeout should it render none. */ +function whenRendered(targetWindow: Window): Promise { + // The second callback runs once the frame of the first one has been produced. + return raceTimeout(new Promise(resolve => targetWindow.requestAnimationFrame(() => targetWindow.requestAnimationFrame(() => resolve()))), AGENTS_LAUNCHER_REVEAL_TIMEOUT); +} + +/** Hosts the existing new-session composer in a reusable, always-on-top auxiliary window. */ +export class AgentsLauncherService extends Disposable implements IAgentsLauncherService { + + declare readonly _serviceBrand: undefined; + + private readonly _presenter = new AgentsLauncherPresenter({ + getWindowId: () => this._window?.window.vscodeWindowId, + prepare: () => this._prepareToShow(), + setOpacity: (targetWindowId, opacity) => this._nativeHostService.setWindowOpacity(opacity, { targetWindowId }), + position: async targetWindowId => { + if (this._lastLayout) { + await this._nativeHostService.positionWindow(this._lastLayout.window, { targetWindowId }); + } + }, + show: targetWindowId => { + this._logService.trace(`[AgentsLauncher] Showing window=${targetWindowId}`); + // Not a forced focus: that activates the whole application, while a panel takes focus without activating it. + return this._nativeHostService.showWindow({ targetWindowId }); + }, + focus: () => this._focusComposer(), + whenRendered: async () => { + if (this._window) { + await whenRendered(this._window.window); + } + }, + hide: async targetWindowId => { + this._logService.trace(`[AgentsLauncher] Hiding window=${targetWindowId}`); + // Where the pointer was is no longer known once hidden. + this._clickThrough?.resetPointer(undefined); + await this._nativeHostService.hideWindow({ targetWindowId }); + // Only once hidden, so that the composer does not change on screen, and unless shown again meanwhile. It stays + // rendered, but is a foreground chat only while the Agents Launcher is visible. + if (!this._presenter.visible.get()) { + this._view?.setVisible(false); + } + }, + }); + readonly isVisible: IObservable = this._presenter.visible; + + private readonly _auxiliaryWindow = this._register(new MutableDisposable()); + private readonly _windowDisposables = this._register(new DisposableStore()); + private readonly _blurHide = this._register(new MutableDisposable()); + private readonly _focusRequest = this._register(new MutableDisposable()); + /** Opens the session of the last send that leaves the Agents Launcher, once it has started. */ + private readonly _pendingOpen = this._register(new MutableDisposable()); + private readonly _backgroundSends: ChatWindowComposerBackgroundSends; + private readonly _composer: ChatWindowComposerModel; + private readonly _draftHost: INewSessionDraftHost; + + private _window: IAuxiliaryWindow | undefined; + private _windowCreation: Promise | undefined; + /** The element in the Agents Launcher's window that the composer renders into. */ + private _surface: HTMLElement | undefined; + private _view: AbstractChatView | undefined; + private _clickThrough: AgentsLauncherClickThrough | undefined; + private _display: IAgentsLauncherDisplay | undefined; + private _lastLayout: IAgentsLauncherLayout | undefined; + private _contentHeight = AGENTS_LAUNCHER_INITIAL_HEIGHT; + + constructor( + @IAuxiliaryWindowService private readonly _auxiliaryWindowService: IAuxiliaryWindowService, + @INativeHostService private readonly _nativeHostService: INativeHostService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IContextKeyService private readonly _contextKeyService: IContextKeyService, + @IContextViewService private readonly _contextViewService: IContextViewService, + @IQuickInputService private readonly _quickInputService: IQuickInputService, + @IThemeService private readonly _themeService: IThemeService, + @ISessionsService private readonly _sessionsService: ISessionsService, + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @IChatViewFactory private readonly _chatViewFactory: IChatViewFactory, + @IChatEntitlementService private readonly _chatEntitlementService: IChatEntitlementService, + @ISessionHostService private readonly _sessionHostService: ISessionHostService, + @IChatWidgetService private readonly _chatWidgetService: IChatWidgetService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + + this._backgroundSends = this._register(this._instantiationService.createInstance(ChatWindowComposerBackgroundSends)); + const composer = this._composer = this._register(this._instantiationService.createInstance( + ChatWindowComposerModel, + createChatWindowComposerResource(), + {}, + this._backgroundSends, + session => this._openStartedSession(session), + )); + // The composer sends in the background, so that a failure gives its prompt back here. A send the user did not ask to + // send in the background, as Send in Background does, also leaves the Agents Launcher for the Agents window. + this._draftHost = { + slot: composer.slot, + input: composer.input, + requestedTarget: composer.requestedTarget, + setRequestedTarget: (target, reason) => composer.setRequestedTarget(target, reason), + openStartedSession: session => composer.openStartedSession(session), + trackBackgroundSend: send => { + const tracking = composer.trackBackgroundSend(send); + return send.requestedInBackground ? tracking : combinedDisposable(tracking, this._openWhenStarted(send.session)); + }, + }; + + this._register(this._nativeHostService.onDidBlurMainOrAuxiliaryWindow(windowId => this._onWindowBlur(windowId))); + if (AGENTS_LAUNCHER_TRANSPARENT) { + this._register(this._nativeHostService.onDidChangeDisplay(() => void this._onDidChangeDisplay().catch(error => this._logService.error('[AgentsLauncher] Failed to lay out for the displays', error)))); + } + this._register(this._nativeHostService.onDidFocusMainOrAuxiliaryWindow(windowId => { + if (windowId === this._window?.window.vscodeWindowId) { + this._blurHide.clear(); + } + })); + this._register(this._chatEntitlementService.onDidChangeSentiment(() => { + if (this._chatEntitlementService.sentiment.hidden) { + this._destroyWindow('AI features hidden'); + } + })); + const enabledKeys = new Set([ChatContextKeys.enabled.key]); + this._register(this._contextKeyService.onDidChangeContext(event => { + if (event.affectsSome(enabledKeys) && !this._contextKeyService.contextMatchesRules(ChatContextKeys.enabled)) { + this._destroyWindow('Chat disabled'); + } + })); + } + + /** Shows, positions, and focuses the Agents Launcher. */ + show(): Promise { + return this._presenter.show(); + } + + /** Lays out the composer for a show, creating its window should there be none: resolves to the window to show, if any. */ + private async _prepareToShow(): Promise { + if (!this._isEnabled()) { + this._logService.trace('[AgentsLauncher] Show ignored because Chat is disabled'); + return undefined; + } + + const { display: bounds, workArea } = await this._nativeHostService.getCursorScreenPoint(); + const display = this._display = { bounds, workArea }; + // Created at the zoom level of the Agents window. + const auxiliaryWindow = await this._ensureWindow(this._computeLayout(display, getZoomFactor(mainWindow))); + if (!this._isEnabled()) { + this._destroyWindow('Chat disabled while opening'); + return undefined; + } + + const view = this._view; + if (auxiliaryWindow !== this._window || !view) { + return undefined; + } + + // Sized for the composer as it shows: its content can change while hidden, and on creation before it is first measured. + // Visible first, since its chat widget is hidden while it is, which collapses its input. + view.setVisible(true); + view.setActive(true); + const inputContent = view.inputContentElement; + if (inputContent && this._surface) { + this._contentHeight = this._measureContentHeight(this._surface, inputContent); + } + const layout = this._computeLayout(display, getZoomFactor(auxiliaryWindow.window)); + this._lastLayout = layout; + this._layoutView(auxiliaryWindow, view, layout); + const clickThrough = this._clickThrough; + if (clickThrough) { + // Where the pointer is now, rather than as the show began, before which the window may have been created. Until it moves, + // clicks go through should it rest outside what the launcher renders. + const version = clickThrough.pointerVersion; + const { point } = await this._nativeHostService.getCursorScreenPoint(); + if (auxiliaryWindow !== this._window) { + return undefined; + } + clickThrough.resetPointer(this._pointerInWindow(auxiliaryWindow, layout.window, point), version); + } + return auxiliaryWindow.window.vscodeWindowId; + } + + /** Where `point`, in the display's coordinates, is in the window laid out at `bounds`, in its CSS pixels, should it be over it. */ + private _pointerInWindow(auxiliaryWindow: IAuxiliaryWindow, bounds: IRectangle, point: IPoint): { readonly x: number; readonly y: number } | undefined { + if (!containsPoint(bounds, point)) { + return undefined; + } + const zoomFactor = getZoomFactor(auxiliaryWindow.window); + return { x: (point.x - bounds.x) / zoomFactor, y: (point.y - bounds.y) / zoomFactor }; + } + + /** Tells the click-through where a pointer at rest now is in the window, whose zoom or bounds changed beneath it. */ + private async _relocatePointer(auxiliaryWindow: IAuxiliaryWindow): Promise { + const clickThrough = this._clickThrough; + if (!clickThrough || !this._presenter.visible.get()) { + return; + } + const version = clickThrough.pointerVersion; + const { point } = await this._nativeHostService.getCursorScreenPoint(); + const layout = this._lastLayout; + if (auxiliaryWindow === this._window && layout && this._presenter.visible.get()) { + clickThrough.relocatePointer(this._pointerInWindow(auxiliaryWindow, layout.window, point), version); + } + } + + /** Lays a shown transparent window out again for the displays as they now are, as it keeps the size it was laid out for. */ + private async _onDidChangeDisplay(): Promise { + const auxiliaryWindow = this._window; + const surface = this._surface; + const inputContent = this._view?.inputContentElement; + // A hidden window is laid out again as it shows. + if (!auxiliaryWindow || !surface || !inputContent || !this._presenter.visible.get()) { + return; + } + const { display: bounds, workArea } = await this._nativeHostService.getCursorScreenPoint(); + if (auxiliaryWindow === this._window && this._presenter.visible.get()) { + this._display = { bounds, workArea }; + // Positioned again even should its layout not change, as the system may have moved or resized it. + this._lastLayout = undefined; + await this._resizeToContent(auxiliaryWindow, surface, inputContent); + } + } + + private _computeLayout(display: IAgentsLauncherDisplay, zoomFactor: number): IAgentsLauncherLayout { + return computeAgentsLauncherLayout(display.bounds, display.workArea, this._contentHeight, zoomFactor, AGENTS_LAUNCHER_TRANSPARENT); + } + + /** Lays the composer out for `layout`, which is in the display's coordinates rather than the window's CSS pixels. */ + private _layoutView(auxiliaryWindow: IAuxiliaryWindow, view: AbstractChatView, layout: IAgentsLauncherLayout): void { + const zoomFactor = getZoomFactor(auxiliaryWindow.window); + const { window, card } = layout; + if (AGENTS_LAUNCHER_TRANSPARENT && this._surface) { + this._surface.style.left = `${(card.x - window.x) / zoomFactor}px`; + this._surface.style.top = `${(card.y - window.y) / zoomFactor}px`; + this._surface.style.width = `${card.width / zoomFactor}px`; + this._surface.style.height = `${card.height / zoomFactor}px`; + } + view.layout(card.width / zoomFactor, card.height / zoomFactor, 0, 0); + } + + private _focusComposer(): void { + const auxiliaryWindow = this._window; + const view = this._view; + if (auxiliaryWindow && view) { + view.focus(); + this._focusRequest.value = dom.scheduleAtNextAnimationFrame(auxiliaryWindow.window, () => view.focus()); + } + } + + /** Hides the Agents Launcher without discarding its draft or closing its window. */ + hide(): Promise { + this._blurHide.clear(); + this._focusRequest.clear(); + // Hiding hides the window only: the composer stays rendered, so that it shows again exactly as it was, without a stale frame. + return this._presenter.hide(); + } + + /** Toggles the Agents Launcher while retaining the same composer and draft slot. */ + toggle(): Promise { + return this._presenter.visible.get() ? this.hide() : this.show(); + } + + async sendInBackground(): Promise { + const widget = this._getChatWidget(); + await (widget && SharedChatInputComposer.getBackgroundComposer(widget))?.submit(true); + } + + /** The chat widget of the composer in the Agents Launcher's window. */ + private _getChatWidget(): IChatWidget | undefined { + const container = this._window?.container; + return container && this._chatWidgetService.getAllWidgets().find(widget => dom.isAncestor(widget.domNode, container)); + } + + private _isEnabled(): boolean { + return !this._chatEntitlementService.sentiment.hidden && this._contextKeyService.contextMatchesRules(ChatContextKeys.enabled); + } + + /** Resolves to the Agents Launcher's window, which concurrent shows create once. */ + private _ensureWindow(layout: IAgentsLauncherLayout): Promise { + if (this._window) { + return Promise.resolve(this._window); + } + this._windowCreation ??= this._createWindow(layout).finally(() => { + this._windowCreation = undefined; + }); + return this._windowCreation; + } + + private async _createWindow(layout: IAgentsLauncherLayout): Promise { + this._logService.trace('[AgentsLauncher] Creating auxiliary window'); + const backgroundColor = this._themeService.getColorTheme().getColor(editorBackground)?.toString() ?? '#1E1E1E'; + const auxiliaryWindow = await this._auxiliaryWindowService.open({ + bounds: layout.window, + frameless: true, + alwaysOnTop: true, + panel: true, + // Transparent until the first show has painted it, as every show is. + opacity: 0, + disableFullscreen: true, + disableMaximize: true, + nativeTitlebar: false, + // A transparent window is not resized but laid out, as resizing can break its transparency, and the card draws its own shadow. + ...(AGENTS_LAUNCHER_TRANSPARENT ? { transparent: true, notResizable: true, noShadow: true } : { backgroundColor }), + }); + await auxiliaryWindow.whenStylesHaveLoaded; + + this._windowDisposables.clear(); + this._auxiliaryWindow.value = auxiliaryWindow; + this._window = auxiliaryWindow; + try { + this._renderComposer(auxiliaryWindow, layout); + } catch (error) { + // Never leave an empty floating window behind. + this._destroyWindow('Failed to render the composer'); + throw error; + } + return auxiliaryWindow; + } + + private _renderComposer(auxiliaryWindow: IAuxiliaryWindow, layout: IAgentsLauncherLayout): void { + const title = localize('agentsLauncher.title', "Agents Launcher"); + auxiliaryWindow.window.document.title = title; + // An element of its own rather than the window's container, whose classes follow those of the Agents window's container. + const surface = dom.append(auxiliaryWindow.container, dom.$('.agents-launcher', { role: 'dialog', 'aria-label': title })); + this._windowDisposables.add(toDisposable(() => surface.remove())); + this._surface = surface; + if (AGENTS_LAUNCHER_TRANSPARENT) { + // An attribute rather than a class, which would follow those of the Agents window's container too. + auxiliaryWindow.container.setAttribute('data-agents-launcher-transparent', ''); + this._trackClickThrough(auxiliaryWindow, surface); + } + + const scopedContextKeyService = this._windowDisposables.add(this._contextKeyService.createScoped(auxiliaryWindow.container)); + const focusContext = AgentsLauncherFocusContext.bindTo(scopedContextKeyService); + this._windowDisposables.add(toDisposable(() => focusContext.reset())); + const focusTracker = this._windowDisposables.add(dom.trackFocus(auxiliaryWindow.container)); + this._windowDisposables.add(focusTracker.onDidFocus(() => focusContext.set(true))); + this._windowDisposables.add(focusTracker.onDidBlur(() => focusContext.set(false))); + + // The composer's UI injects the host it is in: a window host of its own, which shows the composer's draft. + const host = new SessionHost({ + kind: SessionHostKind.ChatWindow, + parent: undefined, + session: this._composer.session, + chat: constObservable(undefined), + windowId: constObservable(auxiliaryWindow.window.vscodeWindowId), + contextKeyService: scopedContextKeyService, + }); + this._windowDisposables.add(this._sessionHostService.registerHost(host)); + const scopedInstantiationService = this._windowDisposables.add(this._instantiationService.createChild(createSessionHostServices(scopedContextKeyService, host))); + const view = this._windowDisposables.add(this._chatViewFactory.createNewChatView(false, { + backgroundSend: true, + newSessionDraft: this._draftHost, + session: this._composer.session, + hostVisible: constObservable(true), + // Kept rendered while hidden, it is a foreground chat only while visible. + hideChatWidgetWhileHidden: true, + renderChatPet: false, + renderAquarium: false, + }, scopedInstantiationService)); + this._view = view; + surface.appendChild(view.element); + view.setActive(true); + view.setVisible(true); + this._layoutView(auxiliaryWindow, view, layout); + + this._windowDisposables.add(auxiliaryWindow.onDidLayout(dimension => { + if (AGENTS_LAUNCHER_TRANSPARENT) { + // A transparent window keeps the size it was laid out for, which it cannot be resized from and is laid out again for as + // displays change: a change of its zoom changes the CSS pixels of the card, and of the pointer in it. + this._layoutView(auxiliaryWindow, view, this._lastLayout ?? layout); + void this._relocatePointer(auxiliaryWindow).catch(error => this._logService.error('[AgentsLauncher] Failed to locate the pointer', error)); + } else { + // The window is the card, at the size the user or the system resized it to. + view.layout(dimension.width, dimension.height, 0, 0); + } + })); + // A keyboard submit acts on the chat widget focused last, which a widget of the main window can become while this + // composer keeps the keyboard focus. Reclaim it before the keybinding service, which listens on the window, resolves + // the key. Only for keys typed into the input, which focusing the input then leaves focused rather than moving focus. + this._windowDisposables.add(dom.addDisposableListener(auxiliaryWindow.container, dom.EventType.KEY_DOWN, () => { + const lastFocused = this._chatWidgetService.lastFocusedWidget; + if (lastFocused && dom.isAncestor(lastFocused.domNode, auxiliaryWindow.container)) { + return; + } + const widget = this._getChatWidget(); + if (widget?.inputEditor.hasTextFocus()) { + this._logService.trace('[AgentsLauncher] Reclaiming the focused chat widget'); + widget.focusInput(); + } + }, true)); + this._windowDisposables.add(Event.once(auxiliaryWindow.onUnload)(() => this._onWindowUnload(auxiliaryWindow))); + + const inputContent = view.inputContentElement; + if (inputContent) { + const resizeObserver = this._windowDisposables.add(new dom.DisposableResizeObserver( + 'AgentsLauncher.inputContent', + () => void this._resizeToContent(auxiliaryWindow, surface, inputContent).catch(error => this._logService.error('[AgentsLauncher] Failed to resize', error)), + dom.getWindow(inputContent), + )); + this._windowDisposables.add(resizeObserver.observe(inputContent)); + this._windowDisposables.add(dom.scheduleAtNextAnimationFrame(auxiliaryWindow.window, () => void this._resizeToContent(auxiliaryWindow, surface, inputContent).catch(error => this._logService.error('[AgentsLauncher] Failed to resize', error)))); + } + } + + /** Lets clicks through the transparent window where it renders nothing. */ + private _trackClickThrough(auxiliaryWindow: IAuxiliaryWindow, surface: HTMLElement): void { + const targetWindowId = auxiliaryWindow.window.vscodeWindowId; + const clickThrough = this._clickThrough = this._windowDisposables.add(new AgentsLauncherClickThrough( + auxiliaryWindow.container, + surface, + ignore => void this._nativeHostService.setWindowIgnoreMouseEvents(ignore, { targetWindowId }).catch(error => this._logService.error('[AgentsLauncher] Failed to let clicks through', error)), + // Hides the launcher as a click that goes through does. With a popup open, the click closes only the popup, which loses focus to it. + () => { + if (!this._hasOwnedPopupOpen()) { + void this.hide().catch(error => this._logService.error('[AgentsLauncher] Failed to hide after a click outside', error)); + } + }, + )); + this._windowDisposables.add(toDisposable(() => { + if (this._clickThrough === clickThrough) { + this._clickThrough = undefined; + } + })); + } + + private async _resizeToContent(auxiliaryWindow: IAuxiliaryWindow, surface: HTMLElement, inputContent: HTMLElement): Promise { + // A hidden window is sized again as it shows. + if (auxiliaryWindow !== this._window || !this._display || !this._presenter.visible.get()) { + return; + } + this._contentHeight = this._measureContentHeight(surface, inputContent); + const layout = this._computeLayout(this._display, getZoomFactor(auxiliaryWindow.window)); + const previous = this._lastLayout; + if (previous && equalBounds(previous.window, layout.window) && equalBounds(previous.card, layout.card)) { + return; + } + this._lastLayout = layout; + // A transparent window has room for the card to grow in, so that typing resizes the card only. + const moved = !equalBounds(previous?.window, layout.window); + if (moved) { + await this._nativeHostService.positionWindow(layout.window, { targetWindowId: auxiliaryWindow.window.vscodeWindowId }); + } + if (this._view) { + this._layoutView(auxiliaryWindow, this._view, layout); + } + if (moved) { + await this._relocatePointer(auxiliaryWindow); + } + const { card } = layout; + this._logService.trace(`[AgentsLauncher] Resized card=${card.x},${card.y},${card.width},${card.height}`); + } + + /** + * The height in CSS pixels the card needs to fit the composer with the insets the stylesheet gives it: above it as + * laid out, below it the view's bottom padding and the surface's border. + */ + private _measureContentHeight(surface: HTMLElement, inputContent: HTMLElement): number { + const contentRect = inputContent.getBoundingClientRect(); + const contentTop = contentRect.top - surface.getBoundingClientRect().top; + const contentHeight = Math.max(inputContent.scrollHeight, contentRect.height); + const below = (this._view ? parseFloat(dom.getComputedStyle(this._view.element).paddingBottom) : 0) + parseFloat(dom.getComputedStyle(surface).borderBottomWidth); + return Math.ceil(contentTop + contentHeight + below); + } + + private _onWindowBlur(windowId: number): void { + const auxiliaryWindow = this._window; + if (!auxiliaryWindow || windowId !== auxiliaryWindow.window.vscodeWindowId || !this._presenter.visible.get()) { + return; + } + // Focusing the launcher again or hiding it clears the check; until then, a send or a popup of the launcher only defers hiding. + this._blurHide.value = dismissWhenAllowed(() => { + if (auxiliaryWindow !== this._window || !this._presenter.visible.get() || auxiliaryWindow.window.document.hasFocus()) { + return DismissalCheck.Keep; + } + return this._composer.input.get().attempt || this._hasOwnedPopupOpen() ? DismissalCheck.Defer : DismissalCheck.Dismiss; + }, AGENTS_LAUNCHER_BLUR_HIDE_DELAY, () => void this.hide().catch(error => this._logService.error('[AgentsLauncher] Failed to hide after blur', error))); + } + + private _hasOwnedPopupOpen(): boolean { + return !!this._quickInputService.currentQuickInput || !!this._window && isContextViewVisible(this._contextViewService, this._window.window); + } + + private async _openStartedSession(session: ISession): Promise { + this._logService.trace(`[AgentsLauncher] Opening started session=${session.sessionId}`); + this._pendingOpen.clear(); + await this.hide(); + try { + await this._sessionsService.openSession(session.resource, { source: 'chat', forceMainChat: true }); + } finally { + await this._nativeHostService.focusWindow({ mode: FocusMode.Force, targetWindowId: mainWindow.vscodeWindowId }); + } + } + + /** + * Leaves the Agents Launcher for the Agents window as the send of `draft` goes out, and opens its session there as soon as it + * has started. A failure is reported there, and the prompt goes back into the Agents Launcher's composer. Disposing the result, + * as the composer does for a send it does not dispatch, stays in the Agents Launcher. + */ + private _openWhenStarted(draft: ISession): IDisposable { + const pending = followOrdinarySend(this._sessionsManagementService, this._composer.slot, draft, { + leave: () => { + this._logService.trace(`[AgentsLauncher] Opening session=${draft.sessionId} once it has started`); + void (async () => { + await this.hide(); + await this._nativeHostService.focusWindow({ mode: FocusMode.Force, targetWindowId: mainWindow.vscodeWindowId }); + })().catch(error => this._logService.error('[AgentsLauncher] Failed to show the Agents window', error)); + }, + open: session => { + void this._sessionsService.openSession(session.resource, { source: 'chat', forceMainChat: true }) + .catch(error => this._logService.error('[AgentsLauncher] Failed to open the started session', error)); + }, + }); + this._pendingOpen.value = pending; + return toDisposable(() => { + if (this._pendingOpen.value === pending) { + this._pendingOpen.clear(); + } + }); + } + + private _onWindowUnload(auxiliaryWindow: IAuxiliaryWindow): void { + if (auxiliaryWindow !== this._window) { + return; + } + this._logService.trace(`[AgentsLauncher] Auxiliary window closed window=${auxiliaryWindow.window.vscodeWindowId}`); + this._window = undefined; + this._surface = undefined; + this._view = undefined; + this._display = undefined; + this._lastLayout = undefined; + this._presenter.reset(); + this._blurHide.clear(); + this._focusRequest.clear(); + this._windowDisposables.clear(); + this._auxiliaryWindow.clear(); + } + + private _destroyWindow(reason: string): void { + const auxiliaryWindow = this._window; + if (!auxiliaryWindow) { + return; + } + this._logService.trace(`[AgentsLauncher] Disposing auxiliary window: ${reason}`); + this._window = undefined; + this._surface = undefined; + this._view = undefined; + this._display = undefined; + this._lastLayout = undefined; + this._presenter.reset(); + this._blurHide.clear(); + this._focusRequest.clear(); + this._windowDisposables.clear(); + this._auxiliaryWindow.clear(); + } + + override dispose(): void { + this._destroyWindow('Agents window disposed'); + super.dispose(); + } +} + +/** Toggles the Agents Launcher when an editor window, such as the owner of a system-wide keybinding, asks the Agents window to. */ +class AgentsLauncherContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.agentsLauncher'; + + constructor( + @IAgentsLauncherService agentsLauncherService: IAgentsLauncherService, + @ILogService logService: ILogService, + ) { + super(); + const handleToggle = () => { + void agentsLauncherService.toggle().catch(error => logService.error('[AgentsLauncher] Failed to handle IPC toggle', error)); + }; + ipcRenderer.on(AGENTS_LAUNCHER_IPC_CHANNEL, handleToggle); + this._register(toDisposable(() => ipcRenderer.removeListener(AGENTS_LAUNCHER_IPC_CHANNEL, handleToggle))); + } +} + +registerSingleton(IAgentsLauncherService, AgentsLauncherService, InstantiationType.Delayed); +registerWorkbenchContribution2(AgentsLauncherContribution.ID, AgentsLauncherContribution, WorkbenchPhase.BlockStartup); + +registerAction2(class ShowAgentsLauncherAction extends Action2 { + constructor() { + super({ + id: AGENTS_LAUNCHER_COMMAND_ID, + title: localize2('showAgentsLauncher', "Show Agents Launcher"), + category: SessionsCategories.Sessions, + f1: true, + precondition: ChatContextKeys.enabled, + }); + } + + override run(accessor: ServicesAccessor): Promise { + return accessor.get(IAgentsLauncherService).toggle(); + } +}); + +registerAction2(class SendInBackgroundFromAgentsLauncherAction extends Action2 { + constructor() { + super({ + id: AGENTS_LAUNCHER_SEND_IN_BACKGROUND_COMMAND_ID, + title: localize2('agentsLauncherSendInBackground', "Start Session in Background"), + f1: false, + precondition: ContextKeyExpr.and( + ChatContextKeys.enabled, + ChatInputSupportsBackgroundContext, + ChatContextKeys.inputHasSendableContent, + ChatContextKeys.inputBlocked.negate(), + ChatContextKeys.chatSessionOptionsValid, + ), + keybinding: { + primary: KeyMod.CtrlCmd | KeyCode.Enter, + secondary: [KeyMod.Alt | KeyCode.Enter], + when: ContextKeyExpr.and(AgentsLauncherFocusContext, ChatContextKeys.inChatInput), + // Above the chat input's own Send in Background, which takes Cmd+Enter only with the inbox enabled, and sends the + // chat widget focused last rather than this one. + weight: KeybindingWeight.SessionsContrib + 1, + }, + }); + } + + override run(accessor: ServicesAccessor): Promise { + return accessor.get(IAgentsLauncherService).sendInBackground(); + } +}); + +registerAction2(class HideAgentsLauncherAction extends Action2 { + constructor() { + super({ + id: HIDE_AGENTS_LAUNCHER_COMMAND_ID, + title: localize2('hideAgentsLauncher', "Hide Agents Launcher"), + f1: false, + keybinding: { + primary: KeyCode.Escape, + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and( + AgentsLauncherFocusContext, + SuggestContext.Visible.toNegated(), + InQuickInputContextKey.toNegated(), + EditorContextKeys.hoverVisible.toNegated(), + EditorContextKeys.hasNonEmptySelection.toNegated(), + EditorContextKeys.hasMultipleSelections.toNegated(), + ), + }, + }); + } + + override run(accessor: ServicesAccessor): Promise | undefined { + if (accessor.get(IQuickInputService).currentQuickInput || isContextViewVisible(accessor.get(IContextViewService))) { + return undefined; + } + return accessor.get(IAgentsLauncherService).hide(); + } +}); diff --git a/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.ts b/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.ts new file mode 100644 index 000000000000..f3494a7baf1b --- /dev/null +++ b/src/vs/sessions/contrib/agentsLauncher/electron-browser/agentsLauncher.ts @@ -0,0 +1,391 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { disposableTimeout } from '../../../../base/common/async.js'; +import { Event } from '../../../../base/common/event.js'; +import { Disposable, DisposableMap, DisposableStore, IDisposable, MutableDisposable } from '../../../../base/common/lifecycle.js'; +import { IObservable, observableValue } from '../../../../base/common/observable.js'; +import { IRectangle } from '../../../../platform/window/common/window.js'; +import { INewSessionDraftSlot, ISessionsManagementService, trackNewSessionRequestEnd } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { ISession } from '../../../../workbench/services/sessions/common/session.js'; + +const AGENTS_LAUNCHER_WIDTH = 640; +const AGENTS_LAUNCHER_HORIZONTAL_MARGIN = 48; +const AGENTS_LAUNCHER_MIN_HEIGHT = 120; +const AGENTS_LAUNCHER_MAX_HEIGHT_RATIO = 0.6; +const AGENTS_LAUNCHER_TOP_RATIO = 0.22; +/** The room in CSS pixels that a transparent window leaves beside the card for its shadow. */ +const AGENTS_LAUNCHER_SHADOW_MARGIN = 24; + +/** Where the Agents Launcher shows: its window, and the card in it that holds the composer, both in the display's coordinates. */ +export interface IAgentsLauncherLayout { + readonly window: IRectangle; + readonly card: IRectangle; +} + +/** + * Lays out the Agents Launcher on the display beneath the pointer, whose `workArea` leaves out its menu bar and dock, for a composer whose + * content is `contentHeight` CSS pixels high at `zoomFactor`. The card is as wide as zoomed content allows. An opaque window is the card. + * A `transparent` one spans the height of the work area, so that the composer's popups, such as its pickers, which cannot show beyond the + * window, have the room above and below the card that the display has, and leaves room beside the card for its shadow. + */ +export function computeAgentsLauncherLayout(display: IRectangle, workArea: IRectangle, contentHeight: number, zoomFactor: number, transparent: boolean): IAgentsLauncherLayout { + const width = Math.min(Math.round(AGENTS_LAUNCHER_WIDTH * zoomFactor), Math.max(1, display.width - AGENTS_LAUNCHER_HORIZONTAL_MARGIN)); + const maximumHeight = Math.max(1, Math.floor(display.height * AGENTS_LAUNCHER_MAX_HEIGHT_RATIO)); + const height = Math.min(Math.max(Math.round(AGENTS_LAUNCHER_MIN_HEIGHT * zoomFactor), Math.ceil(contentHeight * zoomFactor)), maximumHeight); + const card = { + x: Math.round(display.x + (display.width - width) / 2), + y: Math.round(display.y + display.height * AGENTS_LAUNCHER_TOP_RATIO), + width, + height, + }; + if (!transparent) { + return { window: card, card }; + } + + // Always around the whole card, even where the work area leaves part of it out. + const margin = Math.round(AGENTS_LAUNCHER_SHADOW_MARGIN * zoomFactor); + const left = Math.min(card.x, Math.max(workArea.x, card.x - margin)); + const right = Math.max(card.x + card.width, Math.min(workArea.x + workArea.width, card.x + card.width + margin)); + const top = Math.min(card.y, workArea.y); + const bottom = Math.max(card.y + card.height, workArea.y + workArea.height); + return { window: { x: left, y: top, width: right - left, height: bottom - top }, card }; +} + +/** + * Lets clicks through the transparent window of the Agents Launcher where it renders nothing, so that they reach what is below it, which + * dismisses the launcher as it blurs. The window keeps receiving mouse moves meanwhile, and captures clicks again once the pointer is over + * what it renders: its card, or a popup. What the pointer is over is checked as it moves, as a drag ends, and as the window's content + * changes or moves beneath it, such as a popup opened or closed with the keyboard, or growing as it opens, while the pointer rests. + */ +export class AgentsLauncherClickThrough extends Disposable { + + private _ignoring: boolean | undefined; + /** Where the pointer is in the window's CSS pixels, as of its latest mouse event or show, should it be known. */ + private _pointer: { readonly x: number; readonly y: number } | undefined; + /** Whether a button is pressed, as while dragging a selection out of the card, which the window keeps receiving until released. */ + private _pressed = false; + /** Counts the pointer's mouse events and resets, so that a location sampled meanwhile, which is older, is not applied. */ + private _pointerVersion = 0; + private readonly _pendingCheck = this._register(new MutableDisposable()); + /** The open shadow roots in the window, which some popups render into, such as the editor's context menu, and which are watched too. */ + private readonly _shadowRoots = this._register(new DisposableMap()); + + /** + * @param _container The window's container, which holds the card and the popups. + * @param _card The card that holds the composer. + * @param _setIgnoreMouseEvents Lets mouse events through the window, or stops. + * @param onBackgroundMouseDown Called for a click outside the card that the window still receives, such as right after the pointer left it. + * @param _schedule Runs a check once for any number of content changes: at the next animation frame by default. + */ + constructor( + private readonly _container: HTMLElement, + private readonly _card: HTMLElement, + private readonly _setIgnoreMouseEvents: (ignore: boolean) => void, + onBackgroundMouseDown: () => void, + private readonly _schedule: (check: () => void) => IDisposable = check => dom.scheduleAtNextAnimationFrame(dom.getWindow(_container), check), + ) { + super(); + const targetDocument = _container.ownerDocument; + this._register(dom.addDisposableListener(targetDocument, dom.EventType.MOUSE_MOVE, (event: MouseEvent) => { + this._track(event); + if (!this._pressed) { + this._update(this._isContent(innermostTarget(event), event.clientX, event.clientY)); + } + }, true)); + this._register(dom.addDisposableListener(targetDocument, dom.EventType.MOUSE_UP, (event: MouseEvent) => { + this._track(event); + this._check(); + }, true)); + this._register(dom.addDisposableListener(targetDocument, dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { + this._track(event); + if (!this._isContent(innermostTarget(event), event.clientX, event.clientY)) { + this._update(false); + onBackgroundMouseDown(); + } + }, true)); + this._register(this._watch(_container)); + } + + /** The version of the pointer's location, to pass to {@link resetPointer} or {@link relocatePointer} with a location sampled as of it. */ + get pointerVersion(): number { + return this._pointerVersion; + } + + /** + * Sets where the pointer is as the launcher shows or hides, in the window's CSS pixels, or that it is not over the window, and checks + * what it is over. Unless the pointer moved since `version`, as of which `pointer` was sampled. + */ + resetPointer(pointer: { readonly x: number; readonly y: number } | undefined, version = this._pointerVersion): void { + if (version === this._pointerVersion) { + this._pointerVersion++; + this._pointer = pointer; + this._pressed = false; + this._check(); + } + } + + /** + * Sets where a pointer at rest is in the window's CSS pixels once the window's zoom or bounds changed, which changes where it is in the + * window though it did not move, or that it is not over the window, and checks what it is over. Unless the pointer moved since `version`, + * as of which `pointer` was sampled. + */ + relocatePointer(pointer: { readonly x: number; readonly y: number } | undefined, version: number): void { + if (version === this._pointerVersion) { + this._pointer = pointer; + this._check(); + } + } + + /** Checks what the pointer is over as `root`'s content changes or moves, including within the shadow roots it gains. */ + private _watch(root: HTMLElement | ShadowRoot): IDisposable { + const store = new DisposableStore(); + const scheduleCheck = () => { + if (this._pointer && !this._pendingCheck.value) { + this._pendingCheck.value = this._schedule(() => { + this._pendingCheck.clear(); + this._check(); + }); + } + }; + store.add(dom.sharedMutationObserver.observe(root, store, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style'] })(mutations => { + this._watchShadowRoots(mutations); + scheduleCheck(); + })); + // Animations and transitions, such as of a popup growing as it opens, move content without changing the DOM. + for (const type of ['animationend', 'animationcancel', 'transitionend', 'transitioncancel']) { + store.add(dom.addDisposableListener(root, type, scheduleCheck, true)); + } + return store; + } + + /** Watches the shadow roots of added elements, which the observer of their light DOM does not see into, until their host is removed. */ + private _watchShadowRoots(mutations: readonly MutationRecord[]): void { + const visit = (element: Element) => { + if (element.shadowRoot && !this._shadowRoots.has(element.shadowRoot)) { + this._shadowRoots.set(element.shadowRoot, this._watch(element.shadowRoot)); + } + for (const child of element.children) { + visit(child); + } + }; + for (const mutation of mutations) { + for (const node of mutation.addedNodes) { + if (dom.isHTMLElement(node)) { + visit(node); + } + } + } + for (const [shadowRoot] of this._shadowRoots) { + if (!shadowRoot.host.isConnected) { + this._shadowRoots.deleteAndDispose(shadowRoot); + } + } + } + + private _track(event: MouseEvent): void { + this._pointerVersion++; + this._pointer = { x: event.clientX, y: event.clientY }; + this._pressed = event.buttons !== 0; + } + + /** Checks what is under the pointer rather than an event's target, which an element that captured the pointer for a drag can be. */ + private _check(): void { + if (this._pointer && !this._pressed) { + const { x, y } = this._pointer; + this._update(this._isContent(this._elementFromPoint(x, y), x, y)); + } + } + + /** The element at a point, within the open shadow roots that some popups render into, such as the editor's context menu. */ + private _elementFromPoint(x: number, y: number): Element | null { + let element = this._container.ownerDocument.elementFromPoint(x, y); + while (element?.shadowRoot) { + const inner = element.shadowRoot.elementFromPoint(x, y); + if (!inner || inner === element) { + break; + } + element = inner; + } + return element; + } + + private _isContent(target: EventTarget | null, x: number, y: number): boolean { + const targetDocument = this._container.ownerDocument; + if (!target || target === targetDocument.documentElement || target === targetDocument.body || target === this._container) { + return false; + } + // The transparent block that a menu puts behind itself, to close on a click outside it, covers the whole window. Outside the card, + // clicks go through it, as they did beyond a window as small as the card, which closes the menu as the window blurs. + if (dom.isHTMLElement(target) && target.classList.contains('context-view-block')) { + const card = this._card.getBoundingClientRect(); + return x >= card.left && x < card.right && y >= card.top && y < card.bottom; + } + return true; + } + + private _update(overContent: boolean): void { + const ignore = !overContent; + if (ignore !== this._ignoring) { + this._ignoring = ignore; + this._setIgnoreMouseEvents(ignore); + } + } +} + +/** The element an event is dispatched to, within the open shadow roots that some popups render into, such as the editor's context menu. */ +function innermostTarget(event: MouseEvent): EventTarget | null { + return event.composedPath()[0] ?? event.target; +} + +/** The window operations that present the Agents Launcher, which {@link AgentsLauncherPresenter} sequences. */ +export interface IAgentsLauncherWindowPresentation { + /** The ID of the Agents Launcher's window, should it have one. */ + getWindowId(): number | undefined; + /** Creates the window should there be none, and lays it out to show: resolves to its ID, or to `undefined` should it be unable to show. */ + prepare(): Promise; + setOpacity(windowId: number, opacity: number): Promise; + /** Moves the window to the bounds {@link prepare} laid it out for. */ + position(windowId: number): Promise; + show(windowId: number): Promise; + focus(windowId: number): void; + /** Resolves once the window has rendered a frame since the call, or after a timeout should it render none. */ + whenRendered(windowId: number): Promise; + hide(windowId: number): Promise; +} + +/** + * Shows and hides the Agents Launcher's window as requested last. A show is a sequence of window operations, any of which a + * later request interrupts, so that a hide while showing never leaves the window shown, focused, or transparent. + */ +export class AgentsLauncherPresenter { + + private readonly _visible = observableValue(this, false); + /** Whether the Agents Launcher is requested to be visible, as of the latest show or hide. */ + readonly visible: IObservable = this._visible; + + /** Counts requests, so that each show continues only while it is the latest one. */ + private _generation = 0; + + constructor(private readonly _presentation: IAgentsLauncherWindowPresentation) { } + + async show(): Promise { + const generation = ++this._generation; + const isCurrent = () => generation === this._generation; + this._visible.set(true, undefined); + + let windowId: number | undefined; + try { + const id = windowId = await this._presentation.prepare(); + if (id === undefined) { + if (isCurrent()) { + this._visible.set(false, undefined); + } + return; + } + // Transparent until it has painted: a window shown again can present an old or empty frame for a moment, such + // as after it was hidden for a while, which flickers. + for (const step of [ + () => this._presentation.setOpacity(id, 0), + () => this._presentation.position(id), + () => this._presentation.show(id), + () => { + this._presentation.focus(id); + return this._presentation.whenRendered(id); + }, + () => this._presentation.setOpacity(id, 1), + ]) { + if (!isCurrent()) { + return this._abandon(id); + } + await step(); + } + } catch (error) { + if (isCurrent()) { + this._visible.set(false, undefined); + if (windowId !== undefined) { + await this._abandon(windowId); + } + } + throw error; + } + } + + async hide(): Promise { + this._generation++; + this._visible.set(false, undefined); + const windowId = this._presentation.getWindowId(); + if (windowId !== undefined) { + await this._presentation.hide(windowId); + } + } + + toggle(): Promise { + return this._visible.get() ? this.hide() : this.show(); + } + + /** Forgets the window, which has closed, without operating on it. */ + reset(): void { + this._generation++; + this._visible.set(false, undefined); + } + + /** Hides the window of an interrupted show unless a later show presents it. */ + private async _abandon(windowId: number): Promise { + // A hide before the window was created had no window to hide yet. + if (!this._visible.get()) { + await this._presentation.hide(windowId).catch(() => { /* the window may have closed meanwhile */ }); + } + } +} + +/** + * Follows an ordinary send of `draft`, one the user did not send in the background, by the Agents Launcher's composer of `slot`: + * calls `leave` as it goes out, and `open` with its session once it has started. Disposing the result stops following + * it, such as for a send that the composer does not dispatch. + */ +export function followOrdinarySend(sessionsManagementService: ISessionsManagementService, slot: INewSessionDraftSlot, draft: ISession, handlers: { leave(): void; open(session: ISession): void }): IDisposable { + const store = new DisposableStore(); + // A background send is accepted as it goes out, with the draft it sends. + store.add(Event.once(Event.filter(sessionsManagementService.onDidAcceptNewSessionRequest, ({ owner, session }) => owner === slot && session.sessionId === draft.sessionId))(() => handlers.leave())); + store.add(trackNewSessionRequestEnd(sessionsManagementService, slot, draft, ({ session, started }) => { + store.dispose(); + if (started) { + handlers.open(session); + } + })); + return store; +} + +/** What {@link dismissWhenAllowed} does as it checks: dismiss now, check again later, or stop checking. */ +export const enum DismissalCheck { + Dismiss, + Defer, + Keep, +} + +/** + * Calls `dismiss` `delay` milliseconds from now, should `check` then allow it. While `check` defers it, such as during a + * send or with a popup open, it checks again after each `delay`, so that the launcher still hides once nothing defers it. + * Disposing the result stops checking. + */ +export function dismissWhenAllowed(check: () => DismissalCheck, delay: number, dismiss: () => void): IDisposable { + const timer = new MutableDisposable(); + const schedule = () => { + timer.value = disposableTimeout(() => { + switch (check()) { + case DismissalCheck.Dismiss: + dismiss(); + break; + case DismissalCheck.Defer: + schedule(); + break; + } + }, delay); + }; + schedule(); + return timer; +} diff --git a/src/vs/sessions/contrib/agentsLauncher/electron-browser/media/agentsLauncher.css b/src/vs/sessions/contrib/agentsLauncher/electron-browser/media/agentsLauncher.css new file mode 100644 index 000000000000..d517e82caf41 --- /dev/null +++ b/src/vs/sessions/contrib/agentsLauncher/electron-browser/media/agentsLauncher.css @@ -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. + *--------------------------------------------------------------------------------------------*/ + +.agents-launcher { + width: 100%; + height: 100%; + box-sizing: border-box; + overflow: hidden; + background-color: var(--vscode-editor-background); + color: var(--vscode-foreground); + border: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border); + border-radius: var(--vscode-cornerRadius-large); +} + +/* + * A transparent window shows nothing but the card, which it lays out, and the composer's popups around it. The card draws its own + * shadow, since the window has no native one. + */ +.monaco-workbench[data-agents-launcher-transparent] { + background: transparent !important; + /* + * Frosted popups show the page behind them, blurred. Beside the card that is nothing but the apps below the window, which Chromium + * does not blur, so popups are opaque here. Above the inline value the frosted glass contribution sets on every workbench container. + */ + --modern-ui-glass-opacity: 100% !important; +} + +.monaco-workbench[data-agents-launcher-transparent]::before { + display: none; +} + +.monaco-workbench[data-agents-launcher-transparent] > .agents-launcher { + position: absolute; + box-shadow: var(--vscode-shadow-xl); +} + +.agents-launcher .chat-view { + box-sizing: border-box; + overflow: auto; + /* The picker row above the input pads itself: a smaller inset above it matches the sides and bottom. */ + padding: var(--vscode-spacing-size40) var(--vscode-spacing-size120) var(--vscode-spacing-size120); +} + +.agents-launcher .new-chat-widget-container, +.agents-launcher .new-chat-widget-container.revealed { + justify-content: flex-start; + overflow: visible; + padding: 0; +} + +.agents-launcher .new-chat-widget-content { + max-width: none; +} + +.agents-launcher .new-session-welcome-message, +.agents-launcher .new-session-below-input-surfaces, +.agents-launcher .new-session-send-status:empty { + display: none; +} + +.agents-launcher .new-session-workspace-picker-container, +.agents-launcher .experimental-new-session-composer .new-session-workspace-picker-container { + margin-top: 0; +} + +/* The status of a background start shows below the input, and takes no room until there is one. */ +.agents-launcher .new-session-send-status { + order: 1; + margin-top: var(--vscode-spacing-size80); + margin-bottom: 0; +} + +.agents-launcher .new-chat-widget-container.revealed .new-chat-input-container, +.agents-launcher .new-chat-widget-container.revealed .new-session-workspace-picker-container { + animation: none; +} diff --git a/src/vs/sessions/contrib/agentsLauncher/test/electron-browser/agentsLauncher.test.ts b/src/vs/sessions/contrib/agentsLauncher/test/electron-browser/agentsLauncher.test.ts new file mode 100644 index 000000000000..571c90531db0 --- /dev/null +++ b/src/vs/sessions/contrib/agentsLauncher/test/electron-browser/agentsLauncher.test.ts @@ -0,0 +1,419 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { INewSessionDraftSlot, INewSessionRequestAcceptedEvent, INewSessionRequestEndedEvent, ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { ISession } from '../../../../../workbench/services/sessions/common/session.js'; +import { IRectangle } from '../../../../../platform/window/common/window.js'; +import { AgentsLauncherClickThrough, AgentsLauncherPresenter, computeAgentsLauncherLayout, DismissalCheck, dismissWhenAllowed, followOrdinarySend, IAgentsLauncherWindowPresentation } from '../../electron-browser/agentsLauncher.js'; + +/** Records the window operations of a presenter, any of which a test can hold until it completes them. */ +class RecordingPresentation implements IAgentsLauncherWindowPresentation { + readonly operations: string[] = []; + readonly held = new Map; release: DeferredPromise }>(); + windowId: number | undefined; + /** The operation that fails, if any. */ + failing: string | undefined; + /** Whether the window cannot show, such as while Chat is disabled. */ + unavailable = false; + + /** Holds the next operation `name` until the returned promise's `release` completes. */ + hold(name: string) { + const held = { entered: new DeferredPromise(), release: new DeferredPromise() }; + this.held.set(name, held); + return held; + } + + getWindowId(): number | undefined { + return this.windowId; + } + + async prepare(): Promise { + await this._record('prepare'); + if (this.unavailable) { + return undefined; + } + this.windowId = 1; + return this.windowId; + } + + setOpacity(_windowId: number, opacity: number): Promise { + return this._record(`opacity ${opacity}`); + } + + position(): Promise { + return this._record('position'); + } + + show(): Promise { + return this._record('show'); + } + + focus(): void { + this.operations.push('focus'); + } + + whenRendered(): Promise { + return this._record('rendered'); + } + + hide(): Promise { + return this._record('hide'); + } + + private async _record(name: string): Promise { + this.operations.push(name); + const held = this.held.get(name); + if (held) { + this.held.delete(name); + held.entered.complete(); + await held.release.p; + } + if (name === this.failing) { + throw new Error(`${name} failed`); + } + } +} + +suite('Agents Launcher', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + const shown = ['opacity 0', 'position', 'show', 'focus', 'rendered', 'opacity 1']; + + test('toggles the window, hides it should a show fail, and shows none it cannot show', async () => { + const presentation = new RecordingPresentation(); + const presenter = new AgentsLauncherPresenter(presentation); + await presenter.toggle(); + await presenter.toggle(); + presentation.failing = 'show'; + const failure = await presenter.show().then(() => undefined, (error: Error) => error.message); + const visibleAfterFailure = presenter.visible.get(); + presentation.failing = undefined; + presentation.unavailable = true; + await presenter.show(); + + assert.deepStrictEqual({ visibleAfterFailure, failure, visible: presenter.visible.get(), operations: presentation.operations }, { + visibleAfterFailure: false, + failure: 'show failed', + visible: false, + operations: ['prepare', ...shown, 'hide', 'prepare', 'opacity 0', 'position', 'show', 'hide', 'prepare'], + }); + }); + + test('a show requested while an earlier one creates the window presents it', async () => { + const presentation = new RecordingPresentation(); + const presenter = new AgentsLauncherPresenter(presentation); + const prepare = presentation.hold('prepare'); + + const first = presenter.show(); + await prepare.entered.p; + await presenter.hide(); + await presenter.show(); + prepare.release.complete(); + await first; + + assert.deepStrictEqual({ visible: presenter.visible.get(), operations: presentation.operations }, { + visible: true, + operations: ['prepare', 'prepare', ...shown], + }); + }); + + test('leaves for the Agents window as an ordinary send goes out, and opens its session once it has started, but not one that failed or did not go out', () => { + const accepted = store.add(new Emitter()); + const ended = store.add(new Emitter()); + const replaced = store.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); + const service = upcastPartial({ onDidAcceptNewSessionRequest: accepted.event, onDidEndNewSessionRequest: ended.event, onDidReplaceNewDraftSession: replaced.event, onDidReplaceSession: Event.None }); + const slot = upcastPartial({ id: 'agentsLauncher' }); + const otherSlot = upcastPartial({ id: 'other' }); + const session = (sessionId: string) => upcastPartial({ sessionId }); + const follow = (scenario: (draft: ISession, following: IDisposable) => void) => { + const events: string[] = []; + const draft = session('draft'); + const following = followOrdinarySend(service, slot, draft, { leave: () => events.push('leave'), open: started => events.push(`open ${started.sessionId}`) }); + scenario(draft, following); + following.dispose(); + return events; + }; + + assert.deepStrictEqual({ + started: follow(draft => { + accepted.fire({ session: draft, owner: otherSlot, background: true }); + accepted.fire({ session: session('other'), owner: slot, background: true }); + accepted.fire({ session: draft, owner: slot, background: true }); + replaced.fire({ from: draft, to: session('prepared') }); + ended.fire({ session: session('prepared'), owner: otherSlot, started: true, readopted: false }); + ended.fire({ session: session('prepared'), owner: slot, started: true, readopted: false }); + }), + failed: follow(draft => { + accepted.fire({ session: draft, owner: slot, background: true }); + ended.fire({ session: draft, owner: slot, started: false, readopted: false, error: new Error('failed') }); + }), + notSent: follow((draft, following) => { + following.dispose(); + accepted.fire({ session: draft, owner: slot, background: true }); + ended.fire({ session: draft, owner: slot, started: true, readopted: false }); + }), + }, { + started: ['leave', 'open prepared'], + failed: ['leave'], + notSent: [], + }); + }); + + test('a hide while showing leaves the window hidden', async () => { + const presentation = new RecordingPresentation(); + const presenter = new AgentsLauncherPresenter(presentation); + const position = presentation.hold('position'); + + const show = presenter.show(); + await position.entered.p; + await presenter.hide(); + position.release.complete(); + await show; + + assert.deepStrictEqual({ visible: presenter.visible.get(), operations: presentation.operations }, { + visible: false, + operations: ['prepare', 'opacity 0', 'position', 'hide', 'hide'], + }); + }); + + test('a hide while creating the window hides it once created', async () => { + const presentation = new RecordingPresentation(); + const presenter = new AgentsLauncherPresenter(presentation); + const prepare = presentation.hold('prepare'); + + const show = presenter.show(); + await prepare.entered.p; + await presenter.hide(); + prepare.release.complete(); + await show; + + assert.deepStrictEqual({ visible: presenter.visible.get(), operations: presentation.operations }, { + visible: false, + operations: ['prepare', 'hide'], + }); + }); + + test('hides once it has left the launcher, checking again while a send or popup defers it, until it is kept', () => runWithFakedTimers({}, async () => { + const run = async (checks: DismissalCheck[], disposeAfter?: number) => { + const results = [...checks]; + let checked = 0, dismissed = 0; + const dismissal = dismissWhenAllowed(() => { checked++; return results.shift() ?? DismissalCheck.Defer; }, 150, () => dismissed++); + await timeout(disposeAfter ?? 150 * (checks.length + 2)); + dismissal.dispose(); + await timeout(1000); + return { checked, dismissed }; + }; + + assert.deepStrictEqual({ + dismissed: await run([DismissalCheck.Dismiss]), + deferred: await run([DismissalCheck.Defer, DismissalCheck.Defer, DismissalCheck.Dismiss]), + kept: await run([DismissalCheck.Defer, DismissalCheck.Keep]), + disposedWhileDeferred: await run([DismissalCheck.Defer, DismissalCheck.Defer, DismissalCheck.Dismiss], 400), + }, { + dismissed: { checked: 1, dismissed: 1 }, + deferred: { checked: 3, dismissed: 1 }, + kept: { checked: 2, dismissed: 0 }, + disposedWhileDeferred: { checked: 2, dismissed: 0 }, + }); + })); + + test('lets clicks through where the window renders nothing, checking again as a drag ends and as a popup opens or closes beneath a pointer at rest', async () => { + const place = (element: HTMLElement, x: number, y: number, width: number, height: number) => { + element.style.cssText = `position: absolute; left: ${x}px; top: ${y}px; width: ${width}px; height: ${height}px;`; + return element; + }; + const container = place(dom.$('.container'), 0, 0, 300, 300); + container.style.position = 'fixed'; + container.style.zIndex = '100000'; + const card = container.appendChild(place(dom.$('.card'), 10, 10, 100, 50)); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + + const events: string[] = []; + const scheduled: (() => void)[] = []; + const clickThrough = store.add(new AgentsLauncherClickThrough(container, card, ignore => events.push(ignore ? 'through' : 'capture'), () => events.push('background click'), check => { + scheduled.push(check); + return toDisposable(() => { + const index = scheduled.indexOf(check); + if (index >= 0) { + scheduled.splice(index, 1); + } + }); + })); + const flush = async () => { + await timeout(0); + for (const check of scheduled.splice(0)) { + check(); + } + }; + const mouse = (type: string, x: number, y: number, buttons = 0) => { + (mainWindow.document.elementFromPoint(x, y) ?? container).dispatchEvent(new MouseEvent(type, { bubbles: true, clientX: x, clientY: y, buttons })); + }; + + clickThrough.resetPointer({ x: 50, y: 30 }); + mouse('mousemove', 200, 250); + const popup = container.appendChild(place(dom.$('.popup'), 150, 200, 100, 100)); + await flush(); + popup.remove(); + await flush(); + mouse('mousemove', 50, 30); + mouse('mousedown', 50, 30, 1); + mouse('mousemove', 200, 250, 1); + mouse('mouseup', 200, 250); + events.push('|'); + const block = container.appendChild(place(dom.$('.context-view-block'), 0, 0, 300, 300)); + await flush(); + mouse('mousemove', 50, 30); + mouse('mousemove', 200, 250); + mouse('mousedown', 200, 250, 1); + events.push('|'); + clickThrough.resetPointer(undefined); + block.remove(); + container.appendChild(popup); + await flush(); + + assert.deepStrictEqual(events, [ + // Over the card as it shows, then the background, a popup opened and closed beneath the resting pointer, and a drag out of the card. + 'capture', 'through', 'capture', 'through', 'capture', 'through', '|', + // A menu's block is content over the card only, and a click outside the card that the window still receives goes through. + 'capture', 'through', 'background click', '|', + // Nothing checks while the pointer is not known to be over the window. + ]); + }); + + test('looks within shadow roots and checks again as content animates, or the window changes beneath a pointer at rest', async () => { + const place = (element: HTMLElement, x: number, y: number, width: number | string, height: number) => { + element.style.cssText = `position: absolute; left: ${x}px; top: ${y}px; width: ${typeof width === 'number' ? `${width}px` : width}; height: ${height}px;`; + return element; + }; + const container = place(dom.$('.container'), 0, 0, 300, 300); + container.style.position = 'fixed'; + container.style.zIndex = '100000'; + const card = container.appendChild(place(dom.$('.card'), 10, 10, 100, 50)); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + store.add(toDisposable(() => mainWindow.document.documentElement.style.removeProperty('--agents-launcher-test-width'))); + + const events: string[] = []; + const scheduled: (() => void)[] = []; + const clickThrough = store.add(new AgentsLauncherClickThrough(container, card, ignore => events.push(ignore ? 'through' : 'capture'), () => events.push('background click'), check => { + scheduled.push(check); + return toDisposable(() => { + const index = scheduled.indexOf(check); + if (index >= 0) { + scheduled.splice(index, 1); + } + }); + })); + const flush = async () => { + await timeout(0); + for (const check of scheduled.splice(0)) { + check(); + } + }; + // Dispatched to the innermost element at the point, through shadow roots, as the browser does. + const mouse = (type: string, x: number, y: number) => { + let target = mainWindow.document.elementFromPoint(x, y) ?? container; + for (let inner = target.shadowRoot?.elementFromPoint(x, y); inner && inner !== target; inner = target.shadowRoot?.elementFromPoint(x, y)) { + target = inner; + } + target.dispatchEvent(new MouseEvent(type, { bubbles: true, composed: true, clientX: x, clientY: y })); + }; + + // A menu that renders into a shadow root, with the block behind it that covers the whole window. + const host = container.appendChild(place(dom.$('.shadow-host'), 0, 0, 300, 300)); + const shadowRoot = host.attachShadow({ mode: 'open' }); + shadowRoot.appendChild(place(dom.$('.context-view-block'), 0, 0, 300, 300)); + shadowRoot.appendChild(place(dom.$('.menu'), 150, 10, 100, 50)); + clickThrough.resetPointer({ x: 50, y: 30 }); + mouse('mousemove', 200, 250); + mouse('mousemove', 200, 30); + mouse('mousedown', 200, 250); + events.push('|'); + // A submenu opened with the keyboard beneath the resting pointer, then closed, within the shadow root its host keeps. + const submenu = shadowRoot.appendChild(place(dom.$('.submenu'), 180, 230, 60, 60)); + await flush(); + submenu.style.display = 'none'; + await flush(); + events.push('|'); + host.remove(); + await flush(); + + // A popup that grows beneath the resting pointer as it opens, without changing the DOM, as a CSS animation does. + mainWindow.document.documentElement.style.setProperty('--agents-launcher-test-width', '20px'); + const popup = container.appendChild(place(dom.$('.popup'), 150, 200, 'var(--agents-launcher-test-width)', 100)); + await flush(); + mainWindow.document.documentElement.style.setProperty('--agents-launcher-test-width', '100px'); + await flush(); + events.push('animated'); + popup.dispatchEvent(new AnimationEvent('animationend', { bubbles: true })); + await flush(); + events.push('|'); + popup.remove(); + await flush(); + + // The window's zoom changes beneath the resting pointer, which is now over the card, but not as of a location sampled before it moved. + clickThrough.relocatePointer({ x: 60, y: 40 }, clickThrough.pointerVersion); + const sampled = clickThrough.pointerVersion; + mouse('mousemove', 200, 250); + clickThrough.relocatePointer({ x: 60, y: 40 }, sampled); + + assert.deepStrictEqual(events, [ + // Over the card as it shows, the shadow-hosted block outside the card, the menu, and a click on the block outside the card. + 'capture', 'through', 'capture', 'through', 'background click', '|', + // The submenu opened and closed beneath the pointer within the shadow root. + 'capture', 'through', '|', + // The popup grown beneath the pointer without changing the DOM, checked once its animation ends. + 'animated', 'capture', '|', + // Closing the popup, the pointer over the card once the window's zoom changed, and moved off it, which the older sample does not undo. + 'through', 'capture', 'through', + ]); + }); + + test('lays out the card within its display, and a transparent window around it spanning the height of the work area', () => { + const menuBarAndDock = { x: 0, y: 25, width: 1440, height: 800 }; + const layout = (display: IRectangle, workArea: IRectangle, contentHeight: number, zoomFactor = 1) => computeAgentsLauncherLayout(display, workArea, contentHeight, zoomFactor, true); + const layouts = [ + layout({ x: 0, y: 0, width: 1440, height: 900 }, menuBarAndDock, 200), + layout({ x: -1920, y: 0, width: 1920, height: 1080 }, { x: -1920, y: 0, width: 1920, height: 1080 }, 900), + layout({ x: 100, y: 50, width: 600, height: 300 }, { x: 100, y: 75, width: 600, height: 275 }, 80), + layout({ x: 0, y: 0, width: 40, height: 100 }, { x: 0, y: 0, width: 40, height: 100 }, 200), + layout({ x: 0, y: 0, width: 1440, height: 900 }, menuBarAndDock, 150, 1.5), + // A dock on the left that the card reaches into. + layout({ x: 0, y: 0, width: 800, height: 600 }, { x: 120, y: 25, width: 680, height: 575 }, 100), + ]; + const opaque = computeAgentsLauncherLayout({ x: 0, y: 0, width: 1440, height: 900 }, menuBarAndDock, 200, 1, false); + + assert.deepStrictEqual({ cards: layouts.map(({ card }) => card), windows: layouts.map(({ window }) => window), opaque }, { + cards: [ + { x: 400, y: 198, width: 640, height: 200 }, + { x: -1280, y: 238, width: 640, height: 648 }, + { x: 124, y: 116, width: 552, height: 120 }, + { x: 20, y: 22, width: 1, height: 60 }, + { x: 240, y: 198, width: 960, height: 225 }, + { x: 80, y: 132, width: 640, height: 120 }, + ], + windows: [ + { x: 376, y: 25, width: 688, height: 800 }, + { x: -1304, y: 0, width: 688, height: 1080 }, + { x: 100, y: 75, width: 600, height: 275 }, + { x: 0, y: 0, width: 40, height: 100 }, + { x: 204, y: 25, width: 1032, height: 800 }, + { x: 80, y: 25, width: 664, height: 575 }, + ], + // An opaque window is the card. + opaque: { window: { x: 400, y: 198, width: 640, height: 200 }, card: { x: 400, y: 198, width: 640, height: 200 } }, + }); + }); +}); diff --git a/src/vs/sessions/contrib/aquarium/browser/aquariumOverlay.ts b/src/vs/sessions/contrib/aquarium/browser/aquariumOverlay.ts index 474060b2e4ae..a77f18098693 100644 --- a/src/vs/sessions/contrib/aquarium/browser/aquariumOverlay.ts +++ b/src/vs/sessions/contrib/aquarium/browser/aquariumOverlay.ts @@ -122,7 +122,7 @@ export class AquariumService extends Disposable implements IAquariumService { } mountToggle(parent: HTMLElement): IMountedToggleHandle { - const button = $('button.agents-aquarium-toggle'); + const button = $('button.agents-aquarium-toggle.agent-sessions-interactive'); button.type = 'button'; this.updateToggleButtonVisual(button, !!this.activeRef.value); diff --git a/src/vs/sessions/contrib/aquarium/browser/media/aquarium.css b/src/vs/sessions/contrib/aquarium/browser/media/aquarium.css index 63176fa2c514..77334acc0294 100644 --- a/src/vs/sessions/contrib/aquarium/browser/media/aquarium.css +++ b/src/vs/sessions/contrib/aquarium/browser/media/aquarium.css @@ -204,20 +204,17 @@ transition: opacity 160ms ease-out, background-color 160ms ease-out, color 160ms ease-out; } -.agents-aquarium-toggle:hover { +.agents-aquarium-toggle:is(:hover, .hovered) { opacity: 1; - background: var(--vscode-toolbar-hoverBackground, rgba(255, 255, 255, 0.08)); } /* `.monaco-workbench` prefix to match the workbench's own `button:focus` * rule so we win the cascade without resorting to !important. */ -.monaco-workbench button.agents-aquarium-toggle:focus { +.monaco-workbench button.agents-aquarium-toggle:focus:not(:focus-visible) { outline: none; } .monaco-workbench button.agents-aquarium-toggle:focus-visible { opacity: 1; - outline: 1px solid var(--vscode-focusBorder); - outline-offset: 2px; } .agents-aquarium-toggle.active { diff --git a/src/vs/sessions/contrib/aquarium/test/browser/aquariumOverlay.test.ts b/src/vs/sessions/contrib/aquarium/test/browser/aquariumOverlay.test.ts index cd4b26ccc6b2..e92e3f68c5b9 100644 --- a/src/vs/sessions/contrib/aquarium/test/browser/aquariumOverlay.test.ts +++ b/src/vs/sessions/contrib/aquarium/test/browser/aquariumOverlay.test.ts @@ -55,6 +55,7 @@ suite('AquariumService', () => { const initial = { visible: service.actionVisible.get(), display: button?.style.display, + classes: button?.className, }; const hidden = service.toggleActionVisibility(); const afterHide = { @@ -75,7 +76,7 @@ suite('AquariumService', () => { shown, afterShow, }, { - initial: { visible: true, display: '' }, + initial: { visible: true, display: '', classes: 'agents-aquarium-toggle agent-sessions-interactive' }, hidden: false, afterHide: { visible: false, display: 'none', stored: false }, shown: true, diff --git a/src/vs/sessions/contrib/automations/browser/automationDialog.ts b/src/vs/sessions/contrib/automations/browser/automationDialog.ts index ad87785f7955..e4bb8744d094 100644 --- a/src/vs/sessions/contrib/automations/browser/automationDialog.ts +++ b/src/vs/sessions/contrib/automations/browser/automationDialog.ts @@ -2247,7 +2247,7 @@ export function renderForm( }, focusSaveError: focusDialogMessage, getFocusableElements: () => { - // eslint-disable-next-line no-restricted-syntax -- the dialog owns this form subtree and supplies its dynamic focus order. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- the dialog owns this form subtree and supplies its dynamic focus order. return Array.from(form.querySelectorAll('input, select, textarea, button, a[href], [tabindex]')); }, acceptPromptSuggestion: () => { diff --git a/src/vs/sessions/contrib/automations/browser/automationDialogService.ts b/src/vs/sessions/contrib/automations/browser/automationDialogService.ts index e0f6e684da19..df83e17f7f43 100644 --- a/src/vs/sessions/contrib/automations/browser/automationDialogService.ts +++ b/src/vs/sessions/contrib/automations/browser/automationDialogService.ts @@ -538,7 +538,7 @@ export class AutomationDialogService implements IAutomationDialogService { try { void dialog.show().then(() => closeDialog(undefined)); - // eslint-disable-next-line no-restricted-syntax -- Dialog owns its close toolbar and exposes no enablement API. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- Dialog owns its close toolbar and exposes no enablement API. closeToolbar = dialogElement?.querySelector('.dialog-toolbar') ?? undefined; focusFirst(); return await completion.p; diff --git a/src/vs/sessions/contrib/automations/browser/automationTools.ts b/src/vs/sessions/contrib/automations/browser/automationTools.ts index 85535a7c57e6..e49af6afbc01 100644 --- a/src/vs/sessions/contrib/automations/browser/automationTools.ts +++ b/src/vs/sessions/contrib/automations/browser/automationTools.ts @@ -20,7 +20,7 @@ import { IWorkbenchContribution } from '../../../../workbench/common/contributio import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { AutomationInterval, AutomationTarget, AutomationWorkspaceIsolation, IAutomationDescriptor, IAutomationRun, IAutomationSchedule, IAutomationSessionTemplate, isAutomationModelConfiguration } from '../../../../workbench/contrib/chat/common/automations/automation.js'; import { IAutomationRunDispatch, IAutomationRunner } from '../../../../workbench/contrib/chat/common/automations/automationRunner.js'; -import { type AutomationCatalogueState, type AutomationMutationGuard, AutomationMutationUncertainError, AutomationToolCatalog, AutomationSessionTemplateAuthorityError, AutomationUnavailableError, assertAutomationTargetAuthority, ConfigureAutomationToolReferenceName, IAutomationProviderConfiguration, IAutomationService, ICreateAutomationOptions, IDeleteAutomationOptions, IUpdateAutomationOptions, serializeAutomationEditableState } from '../../../../workbench/contrib/chat/common/automations/automationService.js'; +import { type AutomationCatalogueState, type AutomationMutationGuard, AutomationMutationUncertainError, AutomationToolCatalog, AutomationSessionTemplateAuthorityError, AutomationUnavailableError, assertAutomationTargetAuthority, ConfigureAutomationToolReferenceName, IAutomationProviderConfiguration, IAutomationService, ICreateAutomationOptions, IUpdateAutomationOptions, serializeAutomationEditableState } from '../../../../workbench/contrib/chat/common/automations/automationService.js'; import { ChatAutomationsEnabledContext, CHAT_AUTOMATIONS_ENABLED_SETTING } from '../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; import { getAutomationCronValidationError } from '../../../../workbench/contrib/chat/common/automations/schedule.js'; import { IChatAutomationConfiguredData } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; @@ -78,7 +78,6 @@ interface IAutomationToolOutput { } interface IAutomationListToolOutput extends IAutomationToolOutput { - readonly supportsDeleteHistoryChoice?: true; readonly availableOperations: readonly ('run' | 'update' | 'delete')[]; readonly activeRun?: Pick; } @@ -367,7 +366,7 @@ export class DeleteAutomationTool implements IToolImpl { icon: Codicon.trash, displayName: localize('automation.tool.delete.displayName', "Delete Automation"), userDescription: localize('automation.tool.delete.userDescription', "Delete a scheduled agent automation"), - modelDescription: 'Delete an automation by stable ID. Call listAutomations first to obtain the current ID and capabilities. Run history is deleted by default. Set deleteHistory to false to keep it only when supportsDeleteHistoryChoice is true. The current approval policy may approve the action automatically; otherwise the user is shown a Delete/Cancel confirmation.', + modelDescription: 'Delete an automation by stable ID and request deletion of its run history. Associated sessions, including follow-up conversations, may also be permanently deleted. Call listAutomations first to obtain the current ID and capabilities. The current approval policy may approve the action automatically; otherwise the user is shown a Delete/Cancel confirmation.', source: ToolDataSource.Internal, when: automationToolWhen, runsInWorkspace: false, @@ -379,10 +378,6 @@ export class DeleteAutomationTool implements IToolImpl { type: 'string', description: 'Stable automation ID from listAutomations.', }, - deleteHistory: { - type: 'boolean', - description: 'Whether to permanently delete run history. Defaults to true. Specify only when listAutomations reports supportsDeleteHistoryChoice.', - }, }, required: ['automationId'], }, @@ -394,20 +389,14 @@ export class DeleteAutomationTool implements IToolImpl { throw new AutomationToolInputError('Automations are disabled.'); } const automation = resolveAutomationInput(this.automationService, context.parameters, 'deleteAutomation'); - const options = resolveDeleteAutomationOptions(this.automationService, automation.id, context.parameters); return { invocationMessage: localize('automation.tool.delete.invocationMessage', "Deleting automation {0}", automation.name), pastTenseMessage: localize('automation.tool.delete.pastTenseMessage', "Deleted automation {0}", automation.name), confirmationMessages: { title: localize('automation.tool.delete.confirmationTitle', "Delete Automation?"), - message: new MarkdownString(options?.deleteHistory === false ? localize( - 'automation.tool.delete.keepHistoryConfirmation', - "Delete **{0}** (`{1}`)? Its saved configuration will be permanently removed. Run history will be kept.", - automation.name, - automation.id, - ) : localize( + message: new MarkdownString(localize( 'automation.tool.delete.confirmationMessage', - "Delete **{0}** (`{1}`)? Its saved configuration and run history will be permanently removed. Runs already in flight will continue.", + "Delete **{0}** (`{1}`)? This will permanently delete the automation, its run history, and the associated sessions. This cannot be undone. Runs already in flight will continue.", automation.name, automation.id, )), @@ -428,10 +417,8 @@ export class DeleteAutomationTool implements IToolImpl { } let automation: IAutomationDescriptor; - let options: IDeleteAutomationOptions | undefined; try { automation = resolveAutomationInput(this.automationService, invocation.parameters, 'deleteAutomation'); - options = resolveDeleteAutomationOptions(this.automationService, automation.id, invocation.parameters); } catch (error) { if (error instanceof AutomationToolInputError) { return automationToolError(error.message); @@ -444,7 +431,8 @@ export class DeleteAutomationTool implements IToolImpl { } try { - await this.automationService.deleteAutomation(automation.id, this.createMutationGuard(token), options); + await this.automationService.deleteAutomation(automation.id, this.createMutationGuard(token), + this.automationService.supportsDeleteHistoryChoice?.(automation.id) === true ? { deleteHistory: true } : undefined); } catch (error) { if (error instanceof AutomationToolMutationBlockedError) { return error.result; @@ -1240,7 +1228,6 @@ function toAutomationListToolOutput(automation: IAutomationDescriptor, automatio const activeRun = automationService.getActiveRunFor(automation.id); return { ...toAutomationToolOutput(automation), - ...(automationService.supportsDeleteHistoryChoice?.(automation.id) ? { supportsDeleteHistoryChoice: true as const } : {}), ...(activeRun ? { activeRun: { id: activeRun.id, status: activeRun.status, startedAt: activeRun.startedAt } } : {}), availableOperations: [ ...(automationService.canRunAutomation(automation.id) && getUncertainAutomationRun(automation, automationService) === undefined ? ['run'] as const : []), @@ -1347,7 +1334,7 @@ function resolveAutomationInput(automationService: IAutomationService, rawInput: if (!isRecord(rawInput)) { throw new AutomationToolInputError(`${toolName} input must be an object.`); } - assertKnownProperties(rawInput, toolName === 'deleteAutomation' ? ['automationId', 'deleteHistory'] : ['automationId'], `${toolName} input`); + assertKnownProperties(rawInput, ['automationId'], `${toolName} input`); const automationId = readOptionalNonEmptyString(rawInput, 'automationId'); if (!automationId) { throw new AutomationToolInputError('"automationId" is required.'); @@ -1359,20 +1346,6 @@ function resolveAutomationInput(automationService: IAutomationService, rawInput: return automation; } -function resolveDeleteAutomationOptions(service: IAutomationService, id: string, input: unknown): IDeleteAutomationOptions | undefined { - if (!isRecord(input)) { - throw new AutomationToolInputError('deleteAutomation input must be an object.'); - } - const deleteHistory = readOptionalBoolean(input, 'deleteHistory'); - if (deleteHistory === undefined) { - return undefined; - } - if (service.supportsDeleteHistoryChoice?.(id) !== true) { - throw new AutomationToolInputError('This provider does not support choosing whether to delete run history.'); - } - return { deleteHistory }; -} - function assertKnownProperties(value: Record, properties: readonly string[], field: string): void { const known = new Set(properties); const unexpected = Object.keys(value).find(key => !known.has(key)); diff --git a/src/vs/sessions/contrib/automations/browser/media/automationDialog.css b/src/vs/sessions/contrib/automations/browser/media/automationDialog.css index 9ff3a0db6ff8..113a359d735a 100644 --- a/src/vs/sessions/contrib/automations/browser/media/automationDialog.css +++ b/src/vs/sessions/contrib/automations/browser/media/automationDialog.css @@ -15,7 +15,7 @@ .automation-cloud-row { display: flex; align-items: center; - gap: var(--vscode-spacing-size80); + gap: var(--vscode-spacing-size60); padding: var(--vscode-spacing-size120) 0; } @@ -891,8 +891,21 @@ line-height: inherit; } +/* + * The workspace/session-type pickers here are rendered as + * `.monaco-action-bar` items, which size every `.codicon` to a fixed + * 16x16 box (`actionbar.css`) regardless of its compact font-size. + * That leaves ~2px of invisible padding on each side of the glyph, on + * top of `.sessions-chat-dropdown-label`'s own 6px `margin-left`, so + * the icon-to-label gap reads wider than the embedded chat input's + * pickers (which get an equivalent override scoped to + * `.interactive-input-part`). Shrink the box to the glyph itself so + * the label's 6px margin is the only remaining gap. + */ .automation-target-toolbar .sessions-chat-picker-slot .action-label > .codicon { font-size: var(--vscode-codiconFontSize-compact); + width: auto; + height: auto; } .automation-target-toolbar .sessions-chat-dropdown-chevron { @@ -1162,7 +1175,7 @@ .automation-target-toolbar .automation-form-branch-slot { display: inline-flex; align-items: center; - gap: var(--vscode-spacing-size40); + gap: var(--vscode-spacing-size60); box-sizing: border-box; height: 22px; padding: var(--vscode-spacing-size20) var(--vscode-spacing-size60); @@ -1202,12 +1215,24 @@ } .automation-target-toolbar .automation-form-branch-name { + /* The trigger already spaces its icon/label/chevron with `gap`; cancel + * the shared `.sessions-chat-dropdown-label` margin so it doesn't + * stack an extra 6px on top of that gap. */ + margin-left: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.automation-target-toolbar .automation-form-branch-slot > .codicon-chevron-down { + /* Same double-counting as the label above: the shared + * `.codicon-chevron-down` rule also adds its own 2px `margin-left`, + * which would stack on top of the trigger's `gap` and widen the + * label-to-chevron spacing to 8px. */ + margin-left: 0; +} + .automation-form-prompt-host .chat-secondary-toolbar .automation-form-harness-chip { display: inline-flex; align-items: center; diff --git a/src/vs/sessions/contrib/automations/test/browser/automationTools.test.ts b/src/vs/sessions/contrib/automations/test/browser/automationTools.test.ts index c18755b235b3..d773e61f343b 100644 --- a/src/vs/sessions/contrib/automations/test/browser/automationTools.test.ts +++ b/src/vs/sessions/contrib/automations/test/browser/automationTools.test.ts @@ -803,7 +803,7 @@ suite('AutomationTools', () => { result: JSON.parse(getText(result)), }, { confirmationTitle: 'Delete Automation?', - confirmationMessage: 'Delete **Daily review** (`automation-1`)? Its saved configuration and run history will be permanently removed. Runs already in flight will continue.', + confirmationMessage: 'Delete **Daily review** (`automation-1`)? This will permanently delete the automation, its run history, and the associated sessions. This cannot be undone. Runs already in flight will continue.', allowAutoConfirm: undefined, options: [ { id: 'delete', label: 'Delete', kind: ConfirmationOptionKind.Approve }, @@ -818,30 +818,63 @@ suite('AutomationTools', () => { }); }); - test('deleteAutomation confirms and forwards an explicit keep-history choice', async () => { - const automation = createAutomation(); - const options: (IDeleteAutomationOptions | undefined)[] = []; + for (const supportsHistoryChoice of [true, false]) { + test(`deleteAutomation always requests history deletion (history capability: ${supportsHistoryChoice})`, async () => { + const automation = createAutomation(); + const options: (IDeleteAutomationOptions | undefined)[] = []; + const service = new class extends FakeAutomationService { + override supportsDeleteHistoryChoice(): boolean { return supportsHistoryChoice; } + override async deleteAutomation(_id: string, guard?: AutomationMutationGuard, value?: IDeleteAutomationOptions): Promise { + guard?.(); + options.push(value); + } + }([automation]); + const tool = new DeleteAutomationTool(service, createConfigurationService()); + const parameters = { automationId: automation.id }; + const prepared = await tool.prepareToolInvocation({ parameters, toolCallId: 'delete', chatSessionResource: SESSION_RESOURCE }, CancellationToken.None); + await invoke(tool, parameters, SESSION_RESOURCE, CancellationToken.None, 'cancel'); + assert.deepStrictEqual(options, []); + await invoke(tool, parameters, SESSION_RESOURCE, CancellationToken.None, 'delete'); + const message = prepared.confirmationMessages?.message; + assert.deepStrictEqual({ + options, + confirmation: (typeof message === 'string' ? message : message?.value)?.includes('This cannot be undone'), + schema: tool.getToolData().inputSchema, + }, { + options: [supportsHistoryChoice ? { deleteHistory: true } : undefined], + confirmation: true, + schema: { + type: 'object', + additionalProperties: false, + properties: { automationId: { type: 'string', description: 'Stable automation ID from listAutomations.' } }, + required: ['automationId'], + }, + }); + }); + + test(`deleteAutomation rejects the removed history option (history capability: ${supportsHistoryChoice})`, async () => { + const automation = createAutomation(); + const service = new class extends FakeAutomationService { + override supportsDeleteHistoryChoice(): boolean { return supportsHistoryChoice; } + }([automation]); + const tool = new DeleteAutomationTool(service, createConfigurationService()); + const parameters = { automationId: automation.id, deleteHistory: false }; + await assert.rejects(tool.prepareToolInvocation({ parameters, toolCallId: 'keep', chatSessionResource: SESSION_RESOURCE }, CancellationToken.None), /unsupported "deleteHistory" property/); + const result = await invoke(tool, parameters, SESSION_RESOURCE, CancellationToken.None, 'delete'); + assert.deepStrictEqual({ deleted: service.deleted, error: result.toolResultError }, { + deleted: [], + error: 'deleteAutomation input has an unsupported "deleteHistory" property.', + }); + }); + } + + test('listAutomations does not advertise a history retention choice', async () => { const service = new class extends FakeAutomationService { override supportsDeleteHistoryChoice(): boolean { return true; } - override async deleteAutomation(_id: string, _guard?: AutomationMutationGuard, value?: IDeleteAutomationOptions): Promise { options.push(value); } - }([automation]); - const tool = new DeleteAutomationTool(service, createConfigurationService()); - const parameters = { automationId: automation.id, deleteHistory: false }; - const prepared = await tool.prepareToolInvocation({ parameters, toolCallId: 'keep', chatSessionResource: SESSION_RESOURCE }, CancellationToken.None); - await invoke(tool, parameters, SESSION_RESOURCE, CancellationToken.None, 'delete'); - const message = prepared.confirmationMessages?.message; - assert.deepStrictEqual({ - options, - confirmation: (typeof message === 'string' ? message : message?.value)?.includes('Run history will be kept.'), - }, { options: [{ deleteHistory: false }], confirmation: true }); - }); - - test('deleteAutomation rejects history options on unsupported providers', async () => { - const automation = createAutomation(); - const service = new FakeAutomationService([automation]); - const tool = new DeleteAutomationTool(service, createConfigurationService()); - const result = await invoke(tool, { automationId: automation.id, deleteHistory: false }, SESSION_RESOURCE, CancellationToken.None, 'delete'); - assert.deepStrictEqual({ deleted: service.deleted, rejected: getText(result).includes('does not support') }, { deleted: [], rejected: true }); + }([createAutomation()]); + const tool = createListAutomationsTool(service, createConfigurationService()); + const result = await invoke(tool, {}); + assert.strictEqual(getText(result).includes('supportsDeleteHistoryChoice'), false); }); test('deleteAutomation rejects stale IDs before confirmation', async () => { diff --git a/src/vs/sessions/contrib/browserView/browser/sessionBrowserNetwork.ts b/src/vs/sessions/contrib/browserView/browser/sessionBrowserNetwork.ts index 6ed8bd394581..ec88872a5d38 100644 --- a/src/vs/sessions/contrib/browserView/browser/sessionBrowserNetwork.ts +++ b/src/vs/sessions/contrib/browserView/browser/sessionBrowserNetwork.ts @@ -3,18 +3,24 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { equals } from '../../../../base/common/arrays.js'; import { structuralEquals } from '../../../../base/common/equals.js'; import { Emitter } from '../../../../base/common/event.js'; import { Sequencer } from '../../../../base/common/async.js'; import { Disposable, DisposableMap, IDisposable } from '../../../../base/common/lifecycle.js'; -import { derivedOpts, IReader, observableSignalFromEvent, runOnChange } from '../../../../base/common/observable.js'; +import { derivedOpts, IObservable, IReader, observableSignalFromEvent, runOnChange } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { AgentHostTcpSupport, getAgentHostTcpSupport } from '../../../../platform/agentHost/common/agentHostTcpSupport.js'; +import { getAgentHostPathStyle } from '../../../../platform/agentHost/common/agentHostPathStyle.js'; +import { readAgentHostResources } from '../../../../platform/agentHost/common/meta/agentHostResources.js'; import { agentHostAuthority } from '../../../../platform/agentHost/common/agentHostUri.js'; +import { PathStyle } from '../../../../platform/agentHost/common/state/protocol/common/commands.js'; import { BrowserViewStorageScope, getBrowserViewSessionAffinity, IBrowserViewNetwork, IBrowserViewOwner, toBrowserViewSessionOptions } from '../../../../platform/browserView/common/browserView.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { ILogService } from '../../../../platform/log/common/log.js'; +import { IWorkspaceTrustManagementService } from '../../../../platform/workspace/common/workspaceTrust.js'; import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; import { IWorkbenchContribution } from '../../../../workbench/common/contributions.js'; import { BrowserRemoteProxyEnabledSettingId, IBrowserViewNetworkStatus, IBrowserViewSessionRequest, IBrowserViewWorkbenchService } from '../../../../workbench/contrib/browserView/common/browserView.js'; @@ -63,6 +69,12 @@ export class SessionBrowserNetworkContribution extends Disposable implements IWo /** Browser tabs opened from the new-session composer. */ private readonly _composerTabs = this._register(new DisposableMap()); + /** The folders of the sessions on remote agent hosts that are trusted, for {@link IBrowserViewNetworkResolver.getTrustedFileRoots}. */ + private _trustedFileRoots: URI[] = []; + /** Recomputes of the trusted roots run one at a time, so the latest one wins. */ + private readonly _trustedFileRootsUpdates = new Sequencer(); + /** Whether the file system of each connected host (keyed by authority) distinguishes paths by case, once its operating system is known. */ + private readonly _caseSensitiveHosts: IObservable<{ readonly [authority: string]: boolean }>; /** Moves of composer tabs run one at a time, so each sees the tabs earlier moves created. */ private readonly _composerTabMoves = new Sequencer(); @@ -77,6 +89,7 @@ export class SessionBrowserNetworkContribution extends Disposable implements IWo @IUriIdentityService private readonly _uriIdentityService: IUriIdentityService, @IConfigurationService private readonly _configurationService: IConfigurationService, @ILogService private readonly _logService: ILogService, + @IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService, ) { super(); @@ -89,6 +102,26 @@ export class SessionBrowserNetworkContribution extends Disposable implements IWo const onDidChangeNetworkStatus = this._register(new Emitter()); this._register(runOnChange(statuses, () => onDidChangeNetworkStatus.fire())); + const onDidChangeFileAccess = this._register(new Emitter()); + const updateTrustedFileRoots = () => void this._trustedFileRootsUpdates.queue(async () => { + const roots = await this._computeTrustedFileRoots(); + const comparisonKeys = (uris: readonly URI[]) => uris.map(root => this._uriIdentityService.extUri.getComparisonKey(root)).sort(); + if (!equals(comparisonKeys(roots), comparisonKeys(this._trustedFileRoots))) { + this._trustedFileRoots = roots; + onDidChangeFileAccess.fire(); + } + }); + this._register(this._sessionsManagementService.onDidChangeSessions(updateTrustedFileRoots)); + this._register(this._workspaceTrustManagementService.onDidChangeTrust(updateTrustedFileRoots)); + this._register(this._workspaceTrustManagementService.onDidChangeTrustedFolders(updateTrustedFileRoots)); + // Connecting, disconnecting or finishing a handshake can reveal the path style of a host. + this._caseSensitiveHosts = derivedOpts({ owner: this, equalsFn: structuralEquals }, reader => { + connectionsChanged.read(reader); + return this._computeCaseSensitiveHosts(reader); + }); + this._register(runOnChange(this._caseSensitiveHosts, () => onDidChangeFileAccess.fire())); + updateTrustedFileRoots(); + this._register(this._browserViewService.registerNetworkResolver({ resolveNetwork: owner => { const host = this._resolveHost(owner); @@ -96,6 +129,9 @@ export class SessionBrowserNetworkContribution extends Disposable implements IWo return owner.type === 'agent' && !host ? null : this._getNetwork(host?.authority); }, resolveStorageAffinity: owner => this._getStorageAffinity(this._resolveHost(owner)), + getTrustedFileRoots: () => this._trustedFileRoots, + isPathCaseSensitive: network => this._caseSensitiveHosts.get()[network.authority], + onDidChangeFileAccess: onDidChangeFileAccess.event, getNetworkStatus: network => this._getNetworkStatus(network.authority, undefined), onDidChangeNetworkStatus: onDidChangeNetworkStatus.event, })); @@ -169,6 +205,43 @@ export class SessionBrowserNetworkContribution extends Disposable implements IWo return undefined; } + /** + * The working directories of all sessions on remote agent hosts, not just the focused one the window mounts. + * Follows the rule for mounting a session's folders: sessions that require workspace trust only count + * when their folder is trusted. + */ + private async _computeTrustedFileRoots(): Promise { + const candidates: { readonly folder: URI; readonly requiresTrust: boolean }[] = []; + for (const session of this._sessionsManagementService.getSessions()) { + const workspace = session.workspace.get(); + if (workspace && this._getNetwork(this._getSessionAuthority(session))) { + candidates.push(...workspace.folders.map(folder => ({ folder: folder.workingDirectory, requiresTrust: workspace.requiresWorkspaceTrust }))); + } + } + const trusted = await Promise.all(candidates.map(async ({ folder, requiresTrust }) => !requiresTrust || (await this._workspaceTrustManagementService.getUriTrustInfo(folder)).trusted)); + return candidates.filter((_, index) => trusted[index]).map(({ folder }) => folder); + } + + /** Looks up the path style of every connected host. Hosts whose platform and style are unknown are left out and treated as case-sensitive. */ + private _computeCaseSensitiveHosts(reader: IReader): { readonly [authority: string]: boolean } { + const hosts: { [authority: string]: boolean } = {}; + for (const { authority } of this._agentHostConnectionsService.connections) { + const connection = this._agentHostConnectionsService.getConnectionByAuthority(authority); + // Reading the handshake tracks it, so the style is picked up once it completes. + connection?.initializeResult?.read(reader); + const root = connection?.rootState?.value; + const platform = readAgentHostResources(root instanceof Error ? undefined : root)?.platform; + const pathStyle = connection && getAgentHostPathStyle(connection); + if (platform) { + // Posix path style also covers macOS, whose file systems are usually case-insensitive. + hosts[authority] = platform === 'linux'; + } else if (pathStyle) { + hosts[authority] = pathStyle === PathStyle.Posix; + } + } + return hosts; + } + private _getNetworkStatus(authority: string, reader: IReader | undefined): IBrowserViewNetworkStatus { const connection = this._agentHostConnectionsService.getConnectionByAuthority(authority); const support = getAgentHostTcpSupport(connection, reader); diff --git a/src/vs/sessions/contrib/browserView/test/browser/sessionBrowserNetwork.test.ts b/src/vs/sessions/contrib/browserView/test/browser/sessionBrowserNetwork.test.ts index 2a7eed8a6b50..8c9e2a72e690 100644 --- a/src/vs/sessions/contrib/browserView/test/browser/sessionBrowserNetwork.test.ts +++ b/src/vs/sessions/contrib/browserView/test/browser/sessionBrowserNetwork.test.ts @@ -3,6 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { withAgentHostResources } from '../../../../../platform/agentHost/common/meta/agentHostResources.js'; +import type { RootState } from '../../../../../platform/agentHost/common/state/sessionState.js'; import assert from 'assert'; import { timeout } from '../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; @@ -14,11 +16,12 @@ import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionInfo, IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { IAgentConnection } from '../../../../../platform/agentHost/common/agentService.js'; -import type { InitializeResult } from '../../../../../platform/agentHost/common/state/protocol/common/commands.js'; -import { agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { PathStyle, type InitializeResult } from '../../../../../platform/agentHost/common/state/protocol/common/commands.js'; +import { agentHostAuthority, fromAgentHostUri, toAgentHostUri } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { BrowserViewStorageScope, IBrowserViewOwner } from '../../../../../platform/browserView/common/browserView.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -59,6 +62,7 @@ suite('SessionBrowserNetworkContribution', () => { readonly editor?: Partial; readonly editorGroups?: Partial; readonly configuration?: TestConfigurationService; + readonly trust?: IWorkspaceTrustManagementService; }): IBrowserViewNetworkResolver { const instantiationService = store.add(new TestInstantiationService()); let resolver: IBrowserViewNetworkResolver | undefined; @@ -74,17 +78,20 @@ suite('SessionBrowserNetworkContribution', () => { onDidReplaceSession: Event.None, onDidReplaceNewDraftSession: Event.None, onDidDiscardNewSession: Event.None, + onDidChangeSessions: Event.None, + getSessions: () => [], ...services.sessionsManagement, })); instantiationService.stub(ISessionsService, upcastPartial({ activeSession: constObservable(undefined), ...services.sessions })); stubFocusedSessionHostFromSessionsService(instantiationService); instantiationService.stub(ISessionsProvidersService, upcastPartial({ ...services.providers })); - instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ connections: [], onDidChangeConnections: Event.None, ...services.connections })); + instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ connections: [], onDidChangeConnections: Event.None, getConnectionByAuthority: () => undefined, ...services.connections })); instantiationService.stub(IEditorService, upcastPartial({ onWillOpenEditor: Event.None, ...services.editor })); instantiationService.stub(IEditorGroupsService, upcastPartial({ groups: [], ...services.editorGroups })); instantiationService.stub(IUriIdentityService, upcastPartial({ extUri })); instantiationService.stub(ILogService, new NullLogService()); instantiationService.stub(IConfigurationService, services.configuration ?? new TestConfigurationService()); + instantiationService.stub(IWorkspaceTrustManagementService, services.trust ?? upcastPartial({ onDidChangeTrust: Event.None, onDidChangeTrustedFolders: Event.None, getUriTrustInfo: async uri => ({ uri, trusted: true }) })); store.add(instantiationService.createInstance(SessionBrowserNetworkContribution)); return resolver!; } @@ -148,6 +155,115 @@ suite('SessionBrowserNetworkContribution', () => { }); }); + test('keeps the folders of trusted sessions on remote hosts trusted after focus moves to another session', async () => { + const folder = (path: string) => toAgentHostUri(URI.file(path), 'ssh-host'); + const withFolder = (id: string, providerId: string, workingDirectory: URI, requiresWorkspaceTrust: boolean) => upcastPartial({ + sessionId: id, + resource: URI.parse(`session:/${id}`), + providerId, + workspace: constObservable(upcastPartial({ requiresWorkspaceTrust, folders: [upcastPartial({ root: workingDirectory, workingDirectory })] })), + }); + const first = withFolder('first', 'agenthost-ssh', folder('/first'), true); + const second = withFolder('second', 'agenthost-ssh', folder('/second'), true); + const untrusted = withFolder('untrusted', 'agenthost-ssh', folder('/untrusted'), true); + const local = withFolder('local', 'local-agent-host', URI.file('/local'), false); + const activeSession = observableValue('active', undefined); + const onDidChangeSessions = store.add(new Emitter()); + let sessions = [first, local, untrusted]; + const trustedPaths = new Set(['/first', '/second']); + const onDidChangeTrustedFolders = store.add(new Emitter()); + const trust = upcastPartial({ + onDidChangeTrust: Event.None, + onDidChangeTrustedFolders: onDidChangeTrustedFolders.event, + getUriTrustInfo: async uri => ({ uri, trusted: trustedPaths.has(fromAgentHostUri(uri).path) }), + }); + + const resolver = createResolver({ + sessionsManagement: { getSessions: () => sessions, onDidChangeSessions: onDidChangeSessions.event as never }, + sessions: { activeSession }, + connections: { + resolveSessionResourceIdentity: resource => ({ connectionAuthority: resource.path === '/local' ? AMBIENT_AGENT_HOST_AUTHORITY : 'ssh-host', backendSession: resource }), + }, + trust, + }); + let changes = 0; + store.add(resolver.onDidChangeFileAccess!(() => changes++)); + const roots = async () => { + await timeout(0); + return resolver.getTrustedFileRoots!().map(root => fromAgentHostUri(root).path); + }; + + activeSession.set(upcastPartial(first), undefined); + const focusedFirst = await roots(); + activeSession.set(upcastPartial(second), undefined); + onDidChangeSessions.fire(); + const afterFocusMoved = { roots: await roots(), changes }; + sessions = [first, second, local, untrusted]; + onDidChangeSessions.fire(); + const afterSessionAdded = { roots: await roots(), changes }; + trustedPaths.add('/untrusted'); + onDidChangeTrustedFolders.fire(); + + assert.deepStrictEqual({ focusedFirst, afterFocusMoved, afterSessionAdded, afterTrustChanged: { roots: await roots(), changes } }, { + focusedFirst: ['/first'], + afterFocusMoved: { roots: ['/first'], changes: 1 }, + afterSessionAdded: { roots: ['/first', '/second'], changes: 2 }, + afterTrustChanged: { roots: ['/first', '/second', '/untrusted'], changes: 3 }, + }); + }); + + test('tracks the path case sensitivity of connected hosts, including ones without sessions', async () => { + const handshake = observableValue('handshake', undefined); + const posix = upcastPartial({ initializeResult: constObservable(upcastPartial({ environment: { pathStyle: PathStyle.Posix } })) }); + const windows = upcastPartial({ initializeResult: handshake }); + const onDidChangeConnections = store.add(new Emitter()); + const connections = new Map([['posix-host', posix]]); + const listed = [upcastPartial({ authority: 'posix-host' })]; + const resolver = createResolver({ + connections: { + connections: listed, + onDidChangeConnections: onDidChangeConnections.event, + getConnectionByAuthority: authority => connections.get(authority), + }, + }); + let changes = 0; + store.add(resolver.onDidChangeFileAccess!(() => changes++)); + const caseSensitivity = () => ['posix-host', 'windows-host', 'unknown-host'].map(authority => resolver.isPathCaseSensitive!({ authority })); + + await timeout(10); + const initial = caseSensitivity(); + connections.set('windows-host', windows); + listed.push(upcastPartial({ authority: 'windows-host' })); + onDidChangeConnections.fire(); + await timeout(10); + const connecting = caseSensitivity(); + handshake.set(upcastPartial({ environment: { pathStyle: PathStyle.Windows } }), undefined); + await timeout(10); + + assert.deepStrictEqual({ initial, connecting, handshaken: caseSensitivity(), changes }, { + initial: [true, undefined, undefined], + connecting: [true, undefined, undefined], + handshaken: [true, false, undefined], + changes: 1, + }); + }); + + test('treats macOS agent hosts as case-insensitive despite their POSIX paths', () => { + const host = (platform: 'linux' | 'macos') => upcastPartial({ + initializeResult: constObservable(upcastPartial({ environment: { pathStyle: PathStyle.Posix } })), + rootState: upcastPartial({ value: upcastPartial({ _meta: withAgentHostResources(undefined, { platform }) }) }), + }); + const connections = new Map([['linux-host', host('linux')], ['mac-host', host('macos')]]); + const resolver = createResolver({ + connections: { + connections: ['linux-host', 'mac-host'].map(authority => upcastPartial({ authority })), + getConnectionByAuthority: authority => connections.get(authority), + }, + }); + + assert.deepStrictEqual(['linux-host', 'mac-host'].map(authority => resolver.isPathCaseSensitive!({ authority })), [true, false]); + }); + test('reports whether hosts are connected and can proxy browsers', () => { const connection = (initializeResult: IObservable) => upcastPartial({ openTcpConnection: async () => { throw new Error('unused'); }, initializeResult }); const handshake = observableValue('handshake', undefined); diff --git a/src/vs/sessions/contrib/canvases/common/sessionCanvas.ts b/src/vs/sessions/contrib/canvases/common/sessionCanvas.ts index 1f2877e73fd2..891ca44d9187 100644 --- a/src/vs/sessions/contrib/canvases/common/sessionCanvas.ts +++ b/src/vs/sessions/contrib/canvases/common/sessionCanvas.ts @@ -11,7 +11,7 @@ import { CanvasInput, getCanvasDefinitionInstanceId, getCanvasDefinitionLabels } import { SessionActiveChatCanvasReferenceKeysContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; import { ActiveSessionCanvasReferenceContext } from '../../../common/agentsWindowContextKeys.js'; import { IChat, ISession, ISessionCanvas, ISessionCanvasDefinition } from '../../../../workbench/services/sessions/common/session.js'; -import { type ICanvasReference } from '../../../../workbench/common/canvasReference.js'; +import { type ICanvasOwner, type ICanvasReference } from '../../../../workbench/common/canvasReference.js'; export const WindowCanvasesAvailableContext = new RawContextKey('windowCanvasesAvailable', false); export const SessionCanvasActivityBarToggledContext = ContextKeyExpr.and( @@ -41,8 +41,11 @@ export const ISessionCanvasRegistryService = createDecorator; /** Whether canvases are enabled and the active chat supports them, even when no canvas type is registered. */ readonly supportsCanvases: IObservable; readonly availableCanvases: IObservable; + /** Opens a new canvas of `canvas`'s type in the focused chat, beside any canvases of that type it already has. */ openCanvas(canvas: ISessionCanvasDefinition): Promise; } diff --git a/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasActions.ts b/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasActions.ts index 4c895783ac44..0cfc9cd82e29 100644 --- a/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasActions.ts +++ b/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasActions.ts @@ -21,9 +21,9 @@ import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actio import { INewSessionInAgentsWindowOptions } from '../../../../workbench/contrib/chat/common/chatSessionsService.js'; import { Menus, SessionActivityBarGroup } from '../../../../workbench/contrib/sessions/browser/menus.js'; import { AgentsWindowMenus, SessionCanvasMenuGroup } from '../../../browser/agentsWindowMenus.js'; -import { getCanvasInstanceLabels, ICanvasContextService, ICanvasReopenTarget, ICanvasService } from '../../../../workbench/contrib/canvases/common/canvas.js'; +import { getCanvasInstanceLabels, ICanvasContextService, ICanvasReopenTarget, ICanvasService, isCanvasOwner } from '../../../../workbench/contrib/canvases/common/canvas.js'; import { NEW_SESSION_ACTION_ID } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; -import { getSessionCanvasDefinitionInstanceId, getSessionCanvasDefinitionLabels, ISessionCanvasRegistryService, SessionCanvasActivityBarToggledContext, WindowCanvasesAvailableContext } from '../common/sessionCanvas.js'; +import { getSessionCanvasDefinitionLabels, ISessionCanvasRegistryService, SessionCanvasActivityBarToggledContext, WindowCanvasesAvailableContext } from '../common/sessionCanvas.js'; import { getCanvasReferenceKey } from '../../../../workbench/common/canvasReference.js'; export const OPEN_SESSION_CANVAS_COMMAND_ID = 'workbench.action.agentSessions.openCanvas'; @@ -169,11 +169,16 @@ export function registerSessionCanvasActions(canvasService: ICanvasService, regi store.add(autorun(reader => { const definitions = registryService.availableCanvases.read(reader); const definitionLabels = getSessionCanvasDefinitionLabels(definitions); - const targets = canvasService.reopenableCanvases.read(reader); + const canvases = activeCanvases.read(reader); + // Running lists the canvases the focused chat's canvas pill does, whether or not their tab is open, and not those + // of chats other windows show. + const owner = registryService.owner.read(reader); + const targets = owner + ? canvases.filter(({ reference, canvas }) => isCanvasOwner(reference, owner) && canvas.source !== undefined && canvasService.isOwnerPresentable(reference, reader)) + : []; const targetLabels = getCanvasInstanceLabels(targets.map(target => target.canvas)); - const definitionInstanceIds = new Set(definitions.map(getSessionCanvasDefinitionInstanceId)); // Without canvases of its own, the Session Activity Bar offers the same entries as Add Tab. - const inActivityBar = activeCanvases.read(reader).length === 0; + const inActivityBar = canvases.length === 0; const activeKeys = new Set(); for (let index = 0; index < definitions.length; index++) { const canvas = definitions[index]; @@ -191,16 +196,13 @@ export function registerSessionCanvasActions(canvasService: ICanvasService, regi } for (let index = 0; index < targets.length; index++) { const target = targets[index]; - if (target.canvas.instanceId && definitionInstanceIds.has(target.canvas.instanceId)) { - continue; - } const key = `reopen:${getCanvasReferenceKey(target.reference)}`; activeKeys.add(key); let registration = registrations.get(key); if (!registration) { registration = new CanvasMenuActionRegistration( `${REOPEN_SESSION_CANVAS_COMMAND_ID}.${++commandSequence}`, - () => canvasService.reopenCanvas(target.reference), + () => canvasService.revealCanvas(target.reference), ); registrations.set(key, registration); } diff --git a/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasService.ts b/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasService.ts index f49a5c380815..a21ff7eff0b4 100644 --- a/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasService.ts +++ b/src/vs/sessions/contrib/canvases/electron-browser/sessionCanvasService.ts @@ -9,7 +9,7 @@ import { autorun, constObservable, derived, derivedOpts, IObservable, IReader, o import { isEqual } from '../../../../base/common/resources.js'; import { URI } from '../../../../base/common/uri.js'; import { ILogService } from '../../../../platform/log/common/log.js'; -import { CanvasInput, ICanvasContext, ICanvasContextService, ICanvasDefinition, ICanvasService, ICanvasWorkingSets, isCanvasOwner } from '../../../../workbench/contrib/canvases/common/canvas.js'; +import { CanvasDefinitionOpener, CanvasInput, ICanvasContext, ICanvasContextService, ICanvasDefinition, ICanvasService, ICanvasWorkingSets, isCanvasOwner } from '../../../../workbench/contrib/canvases/common/canvas.js'; import { CanvasDefinitionStore } from '../../../../workbench/contrib/canvases/common/canvasDefinitionStore.js'; import { IEditorGroup, IEditorGroupsService } from '../../../../workbench/services/editor/common/editorGroupsService.js'; import { IChatService } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; @@ -20,7 +20,7 @@ import { ICustomViewService } from '../../../../workbench/contrib/sessions/brows import { IChat, ISession, ISessionCanvasDefinition } from '../../../../workbench/services/sessions/common/session.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ISessionEditorWorkingSetService } from '../../layout/common/sessionEditorWorkingSet.js'; -import { createSessionCanvasReference, getSessionCanvasDefinitionInstanceId, ISessionCanvasRegistryService } from '../common/sessionCanvas.js'; +import { ISessionCanvasRegistryService } from '../common/sessionCanvas.js'; import { IPinnedCanvasService } from '../../../../workbench/contrib/sessions/browser/pinnedCanvases.js'; import { canvasOwnerKey, ICanvas, ICanvasOwner, ICanvasReference } from '../../../../workbench/common/canvasReference.js'; @@ -254,8 +254,10 @@ export class SessionCanvasContextService extends Disposable implements ICanvasCo export class SessionCanvasRegistryService extends Disposable implements ISessionCanvasRegistryService { declare readonly _serviceBrand: undefined; + readonly owner: IObservable; readonly supportsCanvases: IObservable; readonly availableCanvases: IObservable; + private readonly opener = new CanvasDefinitionOpener(); constructor( @IFocusedSessionHostService private readonly focusedSessionHostService: IFocusedSessionHostService, @@ -264,6 +266,11 @@ export class SessionCanvasRegistryService extends Disposable implements ISession @ILogService logService: ILogService, ) { super(); + this.owner = derivedOpts({ owner: this, equalsFn: (a, b) => a === b || (!!a && !!b && isCanvasOwner(a, b)) }, reader => { + const session = focusedSessionHostService.focusedHost.read(reader).session.read(reader); + const chat = focusedSessionHostService.focusedHost.read(reader).chat.read(reader); + return session && chat ? { providerId: session.providerId, session: session.resource, chat: chat.resource } : undefined; + }); this.supportsCanvases = derived(this, reader => { const session = focusedSessionHostService.focusedHost.read(reader).session.read(reader); return !!session && !!focusedSessionHostService.focusedHost.read(reader).chat.read(reader) @@ -294,13 +301,8 @@ export class SessionCanvasRegistryService extends Disposable implements ISession if (!chat) { return; } - const instanceId = getSessionCanvasDefinitionInstanceId(canvas); - const existing = chat.canvases?.get()?.find(candidate => candidate.instanceId === instanceId); - if (existing?.source) { - await this.canvasService.revealCanvas(createSessionCanvasReference(session, chat, existing)); - return; - } - await this.sessionsManagementService.openCanvas(session, chat, canvas, instanceId); + const owner: ICanvasOwner = { providerId: session.providerId, session: session.resource, chat: chat.resource }; + await this.opener.open(owner, canvas, chat.canvases?.get() ?? [], instanceId => this.sessionsManagementService.openCanvas(session, chat, canvas, instanceId)); } } diff --git a/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasRegistryService.test.ts b/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasRegistryService.test.ts index b6889714aa48..9683b8b877dd 100644 --- a/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasRegistryService.test.ts +++ b/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasRegistryService.test.ts @@ -36,7 +36,7 @@ import { IChat, ISessionCanvas, ISessionCanvasDefinition, ISessionCapabilities } import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { NEW_SESSION_ACTION_ID } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; import { getSessionCanvasDefinitionInstanceId, WindowCanvasesAvailableContext } from '../../common/sessionCanvas.js'; -import { CREATE_SESSION_CANVAS_COMMAND_ID, DISCOVER_SESSION_CANVASES_COMMAND_ID, OPEN_SESSION_CANVAS_COMMAND_ID, registerSessionCanvasActions } from '../../electron-browser/sessionCanvasActions.js'; +import { CREATE_SESSION_CANVAS_COMMAND_ID, DISCOVER_SESSION_CANVASES_COMMAND_ID, OPEN_SESSION_CANVAS_COMMAND_ID, registerSessionCanvasActions, REOPEN_SESSION_CANVAS_COMMAND_ID } from '../../electron-browser/sessionCanvasActions.js'; import { SessionCanvasRegistryService } from '../../electron-browser/sessionCanvasService.js'; import { focusedSessionHostServiceOf, ITestSessionWithChat } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; import { getCanvasReferenceKey, ICanvasReference } from '../../../../../workbench/common/canvasReference.js'; @@ -84,6 +84,7 @@ suite('SessionCanvasRegistryService', () => { const canvasService = upcastPartial({ enabled, reopenableCanvases: observableValue('reopenableCanvases', []), + isOwnerPresentable: (_reference, reader) => enabled.read(reader), revealCanvas: async reference => { revealed.push(reference); }, reopenCanvas: async () => { }, }); @@ -583,6 +584,53 @@ suite('SessionCanvasRegistryService', () => { }); }); + test('lists the focused chat\'s running canvases as Running, open or not and not those of chats other windows show, and opens another one from Available', async () => { + const definition: ISessionCanvasDefinition = { + canvasId: 'timeline', extensionId: 'user:timeline', extensionSource: 'user', + displayName: 'Timeline', description: 'A timeline.', requiresInput: false, + }; + const harness = createHarness([definition]); + await waitForState(harness.registryService.availableCanvases, canvases => canvases.length === 1); + const instance = (instanceId: string): ISessionCanvas => ({ + resource: URI.parse(`agent-host-canvas:/session/${instanceId}`), instanceId, title: 'Timeline', + source: URI.parse(`https://example.com/${instanceId}`), extensionId: definition.extensionId, canvasId: definition.canvasId, + }); + const first = instance(getSessionCanvasDefinitionInstanceId(definition)); + harness.canvases.set([first], undefined); + // A chat window shows another chat, whose running canvas the canvas service presents there. + const otherWindowChat = { + owner: { providerId: 'local-agent-host', session: URI.parse('agent-host-session:/other'), chat: URI.parse('agent-host-chat:/other/main') }, + canvases: constObservable([{ ...instance('other-window'), title: 'Other Window Canvas' }]), + }; + const contextService = upcastPartial({ + contexts: derived(reader => [...harness.contextService.contexts.read(reader), otherWindowChat]), + }); + store.add(registerSessionCanvasActions(harness.canvasService, harness.registryService, contextService)); + const getEntries = () => MenuRegistry.getMenuItems(AgentsWindowMenus.SessionsEditorTabsBarAddTabCanvas) + .filter(isIMenuItem) + .filter(item => item.command.id.startsWith(`${OPEN_SESSION_CANVAS_COMMAND_ID}.`) || item.command.id.startsWith(`${REOPEN_SESSION_CANVAS_COMMAND_ID}.`)) + .sort((a, b) => (a.group ?? '').localeCompare(b.group ?? '') || (a.order ?? 0) - (b.order ?? 0)); + const titles = () => getEntries().map(item => `${item.group}:${typeof item.command.title === 'string' ? item.command.title : item.command.title.value}`); + const run = (index: number) => CommandsRegistry.getCommand(getEntries()[index].command.id)!.handler(upcastPartial({})); + const withOne = titles(); + await run(1); + harness.canvases.set([first, instance(harness.opened[0].instanceId), { ...instance('reconnecting'), source: undefined }], undefined); + const withTwo = titles(); + await run(0); + + assert.deepStrictEqual({ + withOne, + opened: harness.opened.map(entry => entry.instanceId), + withTwo, + revealed: harness.revealed.map(reference => reference.canvas.toString()), + }, { + withOne: ['1_running:Timeline', '2_available:Timeline'], + opened: [`${first.instanceId}-2`], + withTwo: ['1_running:Timeline (1)', '1_running:Timeline (2)', '2_available:Timeline'], + revealed: [first.resource.toString()], + }); + }); + test('offers Discover entries in the Canvas submenu whenever the chat supports canvases', async () => { const harness = createHarness([]); const registration = store.add(registerSessionCanvasActions(harness.canvasService, harness.registryService, harness.contextService)); diff --git a/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasService.test.ts b/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasService.test.ts index f147d1fcc5c7..61807b856698 100644 --- a/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasService.test.ts +++ b/src/vs/sessions/contrib/canvases/test/electron-browser/sessionCanvasService.test.ts @@ -53,6 +53,7 @@ import { getCanvasReferenceKey, ICanvas, ICanvasReference } from '../../../../.. suite('SessionCanvasService', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); const emptyRegistryService = upcastPartial({ + owner: constObservable({ providerId: 'local-agent-host', session: URI.parse('agent-host-session:/session'), chat: URI.parse('agent-host-chat:/session/main') }), supportsCanvases: constObservable(false), availableCanvases: constObservable([]), openCanvas: async () => { }, @@ -489,6 +490,135 @@ suite('SessionCanvasService', () => { }); }); + test('reloads a retained page through its network once and keeps a failed same-source reload cached', async () => { + const harness = createHarness(); + await harness.openSettled[0]; + await Promise.resolve(); + const input = harness.opened[0]; + const events: string[] = []; + const proxyReady = new DeferredPromise(); + const pageLoaded = new DeferredPromise(); + let fail = false; + let creates = 0; + const model = upcastPartial({ + network: { authority: 'ssh-remote+host' }, + onWillDispose: Event.None, + loadURL: async url => { + events.push(`load ${url}`); + if (fail) { + throw new Error('load failed'); + } + await pageLoaded.p; + }, + dispose: () => { }, + }); + harness.setCreateBrowserModelHandler(async () => { creates++; return model; }); + harness.setAcquireNetworkHandler(async network => { + events.push('acquire'); + await proxyReady.p; + return { object: network, dispose: () => events.push('release') }; + }); + const source = harness.canvas.source!; + await assert.rejects(harness.canvasService.resolveCanvasModel(input.reference, source, true), CancellationError); + await harness.canvasService.resolveCanvasModel(input.reference, source); + const first = harness.canvasService.resolveCanvasModel(input.reference, source, true); + const duplicate = harness.canvasService.resolveCanvasModel(input.reference, source, true); + const whileProxyStarts = [...events]; + proxyReady.complete(); + await timeout(0); + const whileLoading = [...events]; + pageLoaded.complete(); + const resolutions = await Promise.all([first, duplicate]); + fail = true; + await assert.rejects(harness.canvasService.resolveCanvasModel(input.reference, source, true), /load failed/); + const cached = await harness.canvasService.resolveCanvasModel(input.reference, source); + + assert.deepStrictEqual({ + creates, whileProxyStarts, whileLoading, events, + sameModel: [...resolutions, cached].every(resolution => resolution.model === model), + reused: [...resolutions, cached].map(resolution => resolution.reused), + }, { + creates: 1, whileProxyStarts: ['acquire'], whileLoading: ['acquire', 'load https://example.test/preview'], + events: ['acquire', 'load https://example.test/preview', 'release', 'acquire', 'load https://example.test/preview', 'release'], + sameModel: true, reused: [false, true, true], + }); + }); + + test('does not reload a stale retained source after its remote proxy becomes ready', async () => { + const results: { transition: string; events: string[] }[] = []; + for (const transition of ['membership', 'source', 'owner', 'dispose']) { + const harness = createHarness(); + await harness.openSettled[0]; + await Promise.resolve(); + const input = harness.opened[0]; + const events: string[] = []; + const proxyReady = new DeferredPromise(); + harness.setCreateBrowserModelHandler(async () => upcastPartial({ + network: { authority: 'ssh-remote+host' }, + onWillDispose: Event.None, + loadURL: async () => { events.push('load'); }, + dispose: () => { }, + })); + harness.setAcquireNetworkHandler(async network => { + events.push('acquire'); + await proxyReady.p; + return { object: network, dispose: () => events.push('release') }; + }); + const source = harness.canvas.source!; + await harness.canvasService.resolveCanvasModel(input.reference, source); + const reloading = harness.canvasService.resolveCanvasModel(input.reference, source, true); + const rejected = assert.rejects(reloading, CancellationError); + if (transition === 'membership') { + harness.canvases.set(undefined, undefined); + } else if (transition === 'source') { + harness.canvases.set([{ ...harness.canvas, source: undefined }], undefined); + } else if (transition === 'owner') { + harness.activeSession.set(undefined, undefined); + } else { + harness.canvasService.dispose(); + } + proxyReady.complete(); + await rejected; + results.push({ transition, events }); + } + + assert.deepStrictEqual(results, ['membership', 'source', 'owner', 'dispose'].map(transition => ({ transition, events: ['acquire', 'release'] }))); + }); + + test('reattaches the retained page without waiting for a manual reload that later fails', async () => { + const harness = createHarness(); + await harness.openSettled[0]; + await Promise.resolve(); + const input = harness.opened[0]; + const loading = new DeferredPromise(); + const model = upcastPartial({ + onWillDispose: Event.None, + loadURL: () => loading.p, + dispose: () => { }, + }); + harness.setCreateBrowserModelHandler(async () => model); + const source = harness.canvas.source!; + await harness.canvasService.resolveCanvasModel(input.reference, source); + const reloading = harness.canvasService.resolveCanvasModel(input.reference, source, true); + const failed = assert.rejects(reloading, /load failed/); + let reattached: ICanvasModelResolution | undefined; + let reattachError: Error | undefined; + const returning = harness.canvasService.resolveCanvasModel(input.reference, source).then( + resolution => { reattached = resolution; }, + error => { reattachError = error; }, + ); + await timeout(0); + const attachedBeforeFailure = reattached?.model === model; + loading.error(new Error('load failed')); + await Promise.all([returning, failed]); + const cached = await harness.canvasService.resolveCanvasModel(input.reference, source); + + assert.deepStrictEqual({ + attachedBeforeFailure, sameModel: reattached?.model === model, reused: reattached?.reused, + reattachError: reattachError?.message, cached: cached.model === model, + }, { attachedBeforeFailure: true, sameModel: true, reused: true, reattachError: undefined, cached: true }); + }); + test('waits for the remote network proxy before loading a returning source into the retained page, and holds it until the load settles', async () => { const pageLoaded = new DeferredPromise(); const { harness, input, events } = await createRetainedPageAwaitingProvider({ authority: 'ssh-remote+host' }, () => pageLoaded.p); @@ -792,7 +922,7 @@ suite('SessionCanvasService', () => { }); }); - test('contributes titled canvas instances to the Add Tab Canvas submenu', async () => { + test('contributes the chat\'s running canvases to the Add Tab Canvas submenu, with their tab open or closed', async () => { const canvases: ISessionCanvas[] = [ { resource: URI.parse('agent-host-canvas:/preview-editor'), instanceId: 'editor', title: 'Preview', source: URI.parse('https://example.test/editor') }, { resource: URI.parse('agent-host-canvas:/preview-sidebar'), instanceId: 'sidebar', title: 'Preview', source: URI.parse('https://example.test/sidebar') }, @@ -803,13 +933,15 @@ suite('SessionCanvasService', () => { ]; const { canvasService, canvases: canvasStates, contextService, opened } = createHarness(true, canvases); const registration = store.add(registerSessionCanvasActions(canvasService, emptyRegistryService, contextService)); - for (const input of [...opened]) { - input.dispose(); - } const getItems = () => MenuRegistry.getMenuItems(AgentsWindowMenus.SessionsEditorTabsBarAddTabCanvas) .filter(isIMenuItem) .filter(item => item.command.id.startsWith(`${REOPEN_SESSION_CANVAS_COMMAND_ID}.`)) .sort((first, second) => (first.order ?? 0) - (second.order ?? 0)); + const getTitles = () => getItems().map(item => typeof item.command.title === 'string' ? item.command.title : item.command.title.value); + const titlesWhileOpen = getTitles(); + for (const input of [...opened]) { + input.dispose(); + } const getSubmenus = () => MenuRegistry.getMenuItems(AgentsWindowMenus.SessionsEditorTabsBarAddTab) .filter(isISubmenuItem) .filter(item => item.submenu === AgentsWindowMenus.SessionsEditorTabsBarAddTabCanvas); @@ -831,13 +963,14 @@ suite('SessionCanvasService', () => { const refreshedItems = getItems(); await CommandsRegistry.getCommand(items[1].command.id)!.handler(upcastPartial({})); const remainingItems = getItems(); - const remainingTitles = remainingItems.map(item => typeof item.command.title === 'string' ? item.command.title : item.command.title.value); + const remainingTitles = getTitles(); const remainingCommandIds = remainingItems.map(item => item.command.id); const staleCommandsRegistered = initialCommandIds.map(id => CommandsRegistry.getCommand(id) !== undefined); registration.dispose(); assert.deepStrictEqual({ submenuTitles: submenus.map(item => typeof item.title === 'string' ? item.title : item.title.value), + titlesWhileOpen, titles: items.map(item => typeof item.command.title === 'string' ? item.command.title : item.command.title.value), groups: items.map(item => item.group), requiresChat: when.includes(ChatContextKeys.enabled.key), @@ -862,6 +995,7 @@ suite('SessionCanvasService', () => { remainingCommandsAfterDispose: remainingCommandIds.map(id => CommandsRegistry.getCommand(id) !== undefined), }, { submenuTitles: ['Canvas'], + titlesWhileOpen: ['Preview (editor, 2)', 'Preview (sidebar)', 'Preview (editor)', 'Dashboard', 'Logs (1)', 'Logs (1, 2)'], titles: ['Preview (editor, 2)', 'Preview (sidebar)', 'Preview (editor)', 'Dashboard', 'Logs (1)', 'Logs (1, 2)'], groups: ['1_running', '1_running', '1_running', '1_running', '1_running', '1_running'], requiresChat: true, @@ -877,13 +1011,13 @@ suite('SessionCanvasService', () => { reopenedResource: 'agent-host-canvas:/preview-sidebar', refreshedCommandIds: initialCommandIds, refreshedTitles: ['Preview', 'Preview Updated', 'Preview (editor)', 'Dashboard', 'Logs (1)', 'Logs (1, 2)'], - remainingTitles: ['Preview', 'Preview (editor)', 'Dashboard', 'Logs (1)', 'Logs (1, 2)'], - initialCommandsRegisteredAfterReopen: [true, false, true, true, true, true], + remainingTitles: ['Preview', 'Preview Updated', 'Preview (editor)', 'Dashboard', 'Logs (1)', 'Logs (1, 2)'], + initialCommandsRegisteredAfterReopen: [true, true, true, true, true, true], itemsAfterDispose: 0, submenusAfterDispose: 0, listSubmenusAfterDispose: 0, activityBarSubmenusAfterDispose: 0, - remainingCommandsAfterDispose: [false, false, false, false, false], + remainingCommandsAfterDispose: [false, false, false, false, false, false], }); }); diff --git a/src/vs/sessions/contrib/changes/browser/changesViewActions.ts b/src/vs/sessions/contrib/changes/browser/changesViewActions.ts index 84d1114238dd..bf77992bca1d 100644 --- a/src/vs/sessions/contrib/changes/browser/changesViewActions.ts +++ b/src/vs/sessions/contrib/changes/browser/changesViewActions.ts @@ -34,7 +34,7 @@ import { IViewsService } from '../../../../workbench/services/views/common/views import { MultiDiffEditor } from '../../../../workbench/contrib/multiDiffEditor/browser/multiDiffEditor.js'; import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; import { AgentsWindowMenus } from '../../../browser/agentsWindowMenus.js'; -import { SessionIsCreatedContext, DesktopDiffEditorInputActiveContext, DesktopLayoutContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { SessionArtifactIntegrationsEnabledContext, SessionIsCreatedContext, DesktopDiffEditorInputActiveContext, DesktopLayoutContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; import { CustomViewVisibleContext } from '../../../common/agentsWindowContextKeys.js'; import { logChangesViewViewModeChange } from '../../../../workbench/contrib/sessions/common/sessionsTelemetry.js'; import { resolveSessionCommandTarget } from '../../../../workbench/contrib/sessions/browser/sessionCommandTarget.js'; @@ -116,7 +116,9 @@ class OpenPullRequestAction extends Action2 { order: 9, when: ContextKeyExpr.and( IsSessionsWindowContext, - ActiveSessionContextKeys.HasPullRequest) + ActiveSessionContextKeys.HasPullRequest, + // The pull request artifact opens the pull request. + SessionArtifactIntegrationsEnabledContext.negate()) } }); } diff --git a/src/vs/sessions/contrib/changes/browser/checksActions.ts b/src/vs/sessions/contrib/changes/browser/checksActions.ts index 60c3dbbe5274..d5421d114ff7 100644 --- a/src/vs/sessions/contrib/changes/browser/checksActions.ts +++ b/src/vs/sessions/contrib/changes/browser/checksActions.ts @@ -15,7 +15,7 @@ import { IChatWidgetService } from '../../../../workbench/contrib/chat/browser/c import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { CHAT_CATEGORY } from '../../../../workbench/contrib/chat/browser/actions/chatActions.js'; import { IGitHubService } from '../../../../workbench/contrib/sessions/browser/github/githubService.js'; -import { SessionIsActiveContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { SessionArtifactIntegrationsEnabledContext, SessionIsActiveContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; import { resolveSessionCommandTarget } from '../../../../workbench/contrib/sessions/browser/sessionCommandTarget.js'; import { whenChatWidgetForSession } from '../../../../workbench/contrib/sessions/browser/chat/chatWidgetUtils.js'; import { submitFixCIChecks, hasActiveSessionFailedCIChecks, activeSessionCIFixRequested } from '../../../../workbench/contrib/sessions/browser/fixCIChecks.js'; @@ -38,7 +38,7 @@ class FixCIChecksAction extends Action2 { id: MenuId.AgentsChangesPrimaryActionSubMenu, group: '5_checks', order: 4, - when: ContextKeyExpr.and(IsSessionsWindowContext, hasActiveSessionFailedCIChecks, activeSessionCIFixRequested.negate()), + when: ContextKeyExpr.and(IsSessionsWindowContext, hasActiveSessionFailedCIChecks, activeSessionCIFixRequested.negate(), SessionArtifactIntegrationsEnabledContext.negate()), }], }); } diff --git a/src/vs/sessions/contrib/changes/test/browser/agentsDiffEditor.fixture.ts b/src/vs/sessions/contrib/changes/test/browser/agentsDiffEditor.fixture.ts index 09e06dfaab66..3283a762e109 100644 --- a/src/vs/sessions/contrib/changes/test/browser/agentsDiffEditor.fixture.ts +++ b/src/vs/sessions/contrib/changes/test/browser/agentsDiffEditor.fixture.ts @@ -182,6 +182,8 @@ class FixtureOverlayEditorGroup extends mock() implements IAgentFe this.activeEditor = input; this.activeEditorPane = new class extends mock() { override readonly input = input; + override readonly onDidChangeControl = Event.None; + override getControl() { return undefined; } }(); } diff --git a/src/vs/sessions/contrib/changes/test/browser/changesActionsBar.test.ts b/src/vs/sessions/contrib/changes/test/browser/changesActionsBar.test.ts index 8f1d8cacdb87..3f7bcc9b2c20 100644 --- a/src/vs/sessions/contrib/changes/test/browser/changesActionsBar.test.ts +++ b/src/vs/sessions/contrib/changes/test/browser/changesActionsBar.test.ts @@ -4,12 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { IAction, Separator, toAction } from '../../../../../base/common/actions.js'; import { Event } from '../../../../../base/common/event.js'; import { constObservable } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { IMenu, IMenuActionOptions, IMenuService, MenuId, MenuItemAction } from '../../../../../platform/actions/common/actions.js'; +import { IMenu, IMenuActionOptions, IMenuService, MenuId, MenuItemAction, SubmenuItemAction } from '../../../../../platform/actions/common/actions.js'; +import { AgentHostPullRequestOperationId } from '../../../../../platform/agentHost/common/agentHostChangesetOperationService.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; @@ -28,6 +30,7 @@ import { NullTelemetryService } from '../../../../../platform/telemetry/common/t import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; import { IChatPetService } from '../../../../../workbench/contrib/chat/browser/chatPetService.js'; import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; +import { SessionArtifactIntegrationsEnabledContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { IChat, ISessionChangeset, ISessionChangesetOperation, ISessionWorkspace, ISessionFolder, SessionChangesetOperationScope, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; import { IChangesSessionObservables, IChangesSessionScope, IChangesViewService } from '../../../../../workbench/contrib/sessions/common/changesViewService.js'; @@ -49,18 +52,21 @@ suite('ChangesActionsBar', () => { : arg; } - function createBar(providerId: string, getActionsOptions: Map = new Map(), { isMainWindowSession = false, operations = [] as ISessionChangesetOperation[] } = {}) { + function createBar(providerId: string, getActionsOptions: Map = new Map(), { isMainWindowSession = false, operations = [] as ISessionChangesetOperation[], artifactIntegrationsEnabled = false, toolbar = [] as [string, Array][] } = {}) { const menus: MenuId[] = []; const toolbarArgs: unknown[] = []; + const shownMenus: (readonly IAction[])[] = []; const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IMenuService, upcastPartial({ createMenu: (id: MenuId) => { menus.push(id); - return upcastPartial({ onDidChange: Event.None, getActions: (options?: IMenuActionOptions) => { getActionsOptions.set(id, options); if (id === MenuId.AgentsChangesToolbar) { toolbarArgs.push(options?.args ?? options?.arg); } return []; }, dispose: () => { } }); + return upcastPartial({ onDidChange: Event.None, getActions: (options?: IMenuActionOptions) => { getActionsOptions.set(id, options); if (id === MenuId.AgentsChangesToolbar) { toolbarArgs.push(options?.args ?? options?.arg); return toolbar; } return []; }, dispose: () => { } }); }, })); - instantiationService.stub(IContextKeyService, store.add(new ContextKeyService(new TestConfigurationService()))); - instantiationService.stub(IContextMenuService, upcastPartial({})); + const contextKeyService = store.add(new ContextKeyService(new TestConfigurationService())); + SessionArtifactIntegrationsEnabledContext.bindTo(contextKeyService).set(artifactIntegrationsEnabled); + instantiationService.stub(IContextKeyService, contextKeyService); + instantiationService.stub(IContextMenuService, upcastPartial({ showContextMenu: delegate => { shownMenus.push(delegate.getActions?.() ?? []); } })); instantiationService.stub(IContextViewService, upcastPartial({})); instantiationService.stub(IKeybindingService, new MockKeybindingService()); instantiationService.stub(ITelemetryService, NullTelemetryService); @@ -97,7 +103,7 @@ suite('ChangesActionsBar', () => { }; const container = document.createElement('div'); store.add(instantiationService.createInstance(ChangesActionsBar, container, source, new Set())); - return { menus, session, container, toolbarArgs }; + return { menus, session, container, toolbarArgs, shownMenus }; } test('renders the git variant for a non-agent-host source session', () => { @@ -142,6 +148,23 @@ suite('ChangesActionsBar', () => { }, { otherSession: true, mainWindowSession: false }); }); + test('a bar whose button an operation owns, such as Merge Changes, offers the actions of the submenus of its toolbar, such as Submit Feedback, in the dropdown of that button, since it renders only that button', () => { + const operations = [upcastPartial({ id: 'merge', label: 'Merge Changes', scopes: [SessionChangesetOperationScope.Changeset] })]; + const applyActions = new SubmenuItemAction({ title: 'Apply Actions', submenu: MenuId.AgentsChangesPrimaryActionSubMenu }, undefined, [ + toAction({ id: 'submitFeedback', label: 'Submit Feedback (3)', run: () => { } }), + new Separator(), + toAction({ id: 'fixChecks', label: 'Fix Checks', run: () => { } }), + ]); + const { container, shownMenus } = createBar('local-agent-host', new Map(), { operations, toolbar: [['navigation', [applyActions]]] }); + + container.querySelector('.monaco-dropdown-button')?.click(); + + assert.deepStrictEqual({ + button: container.querySelector('.monaco-button')?.textContent, + dropdown: shownMenus.map(actions => actions.map(action => action instanceof Separator ? '---' : action.label)), + }, { button: 'Merge Changes', dropdown: [['---', 'Submit Feedback (3)', 'Fix Checks']] }); + }); + test('the actions of its operations dropdown, such as Agent Merge, act on the session of the bar, such as that of a chat window, not on the active session', () => { const getActionsOptions = new Map(); const { session } = createBar('local-agent-host', getActionsOptions); @@ -150,6 +173,17 @@ suite('ChangesActionsBar', () => { assert.deepStrictEqual({ args: describeArg(options?.args, session), shouldForwardArgs: options?.shouldForwardArgs }, { args: ['session', undefined, 'bar window host'], shouldForwardArgs: true }); }); + test('leaves the pull request operations, such as Mark Ready and Merge, to the pull request artifact while artifact integrations apply to the session', () => { + const operations = [ + upcastPartial({ id: AgentHostPullRequestOperationId.MarkReady, label: 'Mark Ready', scopes: [SessionChangesetOperationScope.Changeset] }), + upcastPartial({ id: AgentHostPullRequestOperationId.Merge, label: 'Merge', scopes: [SessionChangesetOperationScope.Changeset] }), + upcastPartial({ id: 'sync', label: 'Sync Changes', scopes: [SessionChangesetOperationScope.Changeset] }), + ]; + const primaryLabel = (artifactIntegrationsEnabled: boolean) => createBar('local-agent-host', new Map(), { operations, artifactIntegrationsEnabled }).container.querySelector('.monaco-button')?.textContent; + + assert.deepStrictEqual({ disabled: primaryLabel(false), enabled: primaryLabel(true) }, { disabled: 'Mark Ready', enabled: 'Sync Changes' }); + }); + test('creates the scope from the active session observables only for the main window, from the window host of a pane', () => { const activeChanges = upcastPartial({ resourceObs: constObservable(undefined) }); const otherChanges = upcastPartial({ resourceObs: constObservable(undefined) }); diff --git a/src/vs/sessions/contrib/changes/test/browser/changesViewActions.test.ts b/src/vs/sessions/contrib/changes/test/browser/changesViewActions.test.ts index 70edbfdb3cbc..e84fe87fa407 100644 --- a/src/vs/sessions/contrib/changes/test/browser/changesViewActions.test.ts +++ b/src/vs/sessions/contrib/changes/test/browser/changesViewActions.test.ts @@ -55,14 +55,18 @@ import { IChat, ISessionChangeset, ISessionChangesSummary, ISessionFolder, ISess import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ActiveSessionContextKeys, ChangesContextKeys, ChangesViewMode } from '../../../../../workbench/contrib/sessions/common/changes.js'; import { IChangesSessionObservables, IChangesSessionScope, IChangesViewService, NoChangesEditorScope } from '../../../../../workbench/contrib/sessions/common/changesViewService.js'; -import { IsPhoneLayoutContext, SessionHasChangesContext, SessionHasWorkspaceContext, SessionIsCreatedContext, SessionWorkspaceIsVirtualContext, DesktopChangesEditorTransitionContext, DesktopDiffEditorInputActiveContext, DesktopLayoutContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { IsPhoneLayoutContext, SessionArtifactIntegrationsEnabledContext, SessionHasChangesContext, SessionHasWorkspaceContext, SessionIsCreatedContext, SessionWorkspaceIsVirtualContext, DesktopChangesEditorTransitionContext, DesktopDiffEditorInputActiveContext, DesktopLayoutContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { activeSessionCIFixRequested, hasActiveSessionFailedCIChecks } from '../../../../../workbench/contrib/sessions/browser/fixCIChecks.js'; import { CustomViewVisibleContext } from '../../../../common/agentsWindowContextKeys.js'; import { SessionChangesEditor } from '../../../../../workbench/contrib/sessionChanges/browser/sessionChangesEditor.js'; import { MultiDiffEditor } from '../../../../../workbench/contrib/multiDiffEditor/browser/multiDiffEditor.js'; import { CHANGES_HEADER_ACTIONS_ID, ChangesPickerActionItem, ChangesPickerSummary, isChangesActionsWorkspaceReady, unlockChatPetCreatePullRequestAchievement } from '../../../../../workbench/contrib/sessionChanges/browser/changesView.js'; import { SessionsChangesAccessibilityHelp } from '../../../../../workbench/contrib/sessionChanges/browser/sessionsChangesAccessibilityHelp.js'; import '../../browser/changesViewActions.js'; +import '../../../../browser/layoutActions.js'; +import { FIX_CI_CHECKS_COMMAND_ID } from '../../browser/checksActions.js'; import '../../../codeReview/browser/codeReview.contributions.js'; +import '../../../../browser/layoutActions.js'; // Awaited while this file loads so that the contribution's permanent registrations are in place before // any suite runs instead of being registered by this suite. @@ -128,6 +132,23 @@ suite('Changes View Actions', () => { }]); }); + test('the title bar leaves Fix Checks and Open Pull Request to the pull request artifact while artifact integrations apply to the session', () => { + const fixChecks = MenuRegistry.getMenuItems(MenuId.AgentsChangesPrimaryActionSubMenu).filter(isIMenuItem).find(item => item.command.id === FIX_CI_CHECKS_COMMAND_ID)!; + const openPullRequest = MenuRegistry.getMenuItems(MenuId.AgentsChangesToolbar).filter(isIMenuItem).find(item => item.command.id === 'workbench.action.agentSessions.openPullRequest')!; + const visible = (artifactIntegrationsEnabled: boolean) => { + const context = contextWith({ + [IsSessionsWindowContext.key]: true, + [ActiveSessionContextKeys.HasPullRequest.key]: true, + [hasActiveSessionFailedCIChecks.key]: true, + [activeSessionCIFixRequested.key]: false, + [SessionArtifactIntegrationsEnabledContext.key]: artifactIntegrationsEnabled, + }); + return [fixChecks, openPullRequest].map(item => item.when?.evaluate(context) ?? true); + }; + + assert.deepStrictEqual({ disabled: visible(false), enabled: visible(true) }, { disabled: [true, true], enabled: [false, false] }); + }); + suite('Open Changes', () => { const workspaceResource = URI.file('/workspace/file.ts'); const originalSnapshot = URI.parse('readonly-content:/before/file.ts'); diff --git a/src/vs/sessions/contrib/changes/test/browser/sessionActionContextKeys.test.ts b/src/vs/sessions/contrib/changes/test/browser/sessionActionContextKeys.test.ts index 4a167e156fba..f5fd555f048c 100644 --- a/src/vs/sessions/contrib/changes/test/browser/sessionActionContextKeys.test.ts +++ b/src/vs/sessions/contrib/changes/test/browser/sessionActionContextKeys.test.ts @@ -4,16 +4,21 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { Event } from '../../../../../base/common/event.js'; +import { constObservable, derived, observableValue } from '../../../../../base/common/observable.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { AgentHostPullRequestOperationId } from '../../../../../platform/agentHost/common/agentHostChangesetOperationService.js'; +import { ArtifactIntegrationsSettingId } from '../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; +import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; -import { DesktopChangesEditorTransitionContext, SessionHasOpenPullRequestContext, SessionPrimaryPullRequestOperationContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { DesktopChangesEditorTransitionContext, SessionArtifactIntegrationsEnabledContext, SessionHasOpenPullRequestContext, SessionPrimaryPullRequestOperationContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { ISessionChangeset, ISessionChangesetOperation } from '../../../../../workbench/services/sessions/common/session.js'; +import { createTestActiveSession } from '../../../../test/browser/sessionViewTestUtils.js'; +import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { GitHubCheckConclusion, GitHubCheckStatus, IGitHubCICheck } from '../../../../../workbench/contrib/sessions/common/github/types.js'; import { GitHubPullRequestCIModel } from '../../../../../workbench/contrib/sessions/browser/github/models/githubPullRequestCIModel.js'; import { PullRequestCheck } from '../../../../../platform/github/common/githubPullRequestService.js'; @@ -111,6 +116,28 @@ suite('Session Action Context Keys', () => { assert.deepStrictEqual({ unrelatedReads: afterUnrelated - afterBind, relatedTriggersRead: reads > afterUnrelated }, { unrelatedReads: 0, relatedTriggersRead: true }); }); + test('the artifact integrations key holds only while the setting is enabled and the session supports artifact integrations', async () => { + const instantiationService = workbenchInstantiationService(undefined, disposables); + const configuration = new TestConfigurationService({ [ArtifactIntegrationsSettingId]: false }); + disposables.add(configuration.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configuration); + // Binders registered by other contributions, such as Agent Merge's, look up the session's provider. + instantiationService.stub(ISessionsProvidersService, upcastPartial({ onDidChangeProviders: Event.None, getProvider: () => undefined })); + const supportsArtifactIntegrations = observableValue('supportsArtifactIntegrations', true); + const session = Object.assign(createTestActiveSession('session'), { capabilities: derived(reader => ({ supportsMultipleChats: false, supportsArtifactIntegrations: supportsArtifactIntegrations.read(reader) })) }); + const scoped = disposables.add(new ContextKeyService(new TestConfigurationService())); + disposables.add(bindSessionActionContextKeys(instantiationService, { ...createSource({}), session: constObservable(session) }, scoped)); + + const states = [SessionArtifactIntegrationsEnabledContext.getValue(scoped)]; + await configuration.setUserConfiguration(ArtifactIntegrationsSettingId, true); + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial({ affectsConfiguration: setting => setting === ArtifactIntegrationsSettingId })); + states.push(SessionArtifactIntegrationsEnabledContext.getValue(scoped)); + supportsArtifactIntegrations.set(false, undefined); + states.push(SessionArtifactIntegrationsEnabledContext.getValue(scoped)); + + assert.deepStrictEqual(states, [false, true, false]); + }); + test('runs registered binders for each bound source', () => { const instantiationService = workbenchInstantiationService(undefined, disposables); const globalService = disposables.add(new ContextKeyService(new TestConfigurationService())); diff --git a/src/vs/sessions/contrib/chat/browser/agentsWindowWorkspaceHandoff.ts b/src/vs/sessions/contrib/chat/browser/agentsWindowWorkspaceHandoff.ts index 49ed4977a76d..31f2e184b6e7 100644 --- a/src/vs/sessions/contrib/chat/browser/agentsWindowWorkspaceHandoff.ts +++ b/src/vs/sessions/contrib/chat/browser/agentsWindowWorkspaceHandoff.ts @@ -54,8 +54,15 @@ export class AgentsWindowWorkspaceHandoff extends Disposable { private readonly _pending = this._register(new MutableDisposable()); private readonly _notification = this._register(new MutableDisposable()); private _cancelPending: ((state: WorkspaceHandoffState) => void) | undefined; + private _startupProvidersRegistered = false; + /** + * @param whenStartupProvidersRegistered Settles once the providers that register during startup have + * registered. Several of them can accept the same folder, so resolving earlier can pick whichever registered + * first instead of the preferred provider, for example Cloud instead of This Computer for a local folder. + */ constructor( + private readonly whenStartupProvidersRegistered: Promise, @ISessionsService private readonly sessionsService: ISessionsService, @IFocusedSessionHostService private readonly _focusedSessionHostService: IFocusedSessionHostService, @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, @@ -72,6 +79,7 @@ export class AgentsWindowWorkspaceHandoff extends Disposable { ) { super(); this._register(lifecycleService.onWillShutdown(() => this.cancel())); + whenStartupProvidersRegistered.finally(() => this._startupProvidersRegistered = true).catch(() => undefined); } cancel(): void { @@ -184,6 +192,10 @@ export class AgentsWindowWorkspaceHandoff extends Disposable { folderUri = resolution.folderUri ?? folderUri; remoteUnavailableReason = resolution.unavailableReason; } + if (folderUri && !this._startupProvidersRegistered) { + onState('waitingForProvider'); + await raceCancellationError(this.whenStartupProvidersRegistered.catch(() => undefined), source.token); + } // A remote editor window must not fall back to an unrelated local folder. const remoteWithoutFolder = !!intent.remote && !intent.draft && !folderUri; let draftNeedsNavigation = !!intent.draft && !intent.revealNewSession; diff --git a/src/vs/sessions/contrib/chat/browser/chat.contribution.ts b/src/vs/sessions/contrib/chat/browser/chat.contribution.ts index e8cfc6e3919b..fc8e43c76d71 100644 --- a/src/vs/sessions/contrib/chat/browser/chat.contribution.ts +++ b/src/vs/sessions/contrib/chat/browser/chat.contribution.ts @@ -3,20 +3,15 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Schemas } from '../../../../base/common/network.js'; import { status } from '../../../../base/browser/ui/aria/aria.js'; -import { basename, isEqual } from '../../../../base/common/resources.js'; -import { URI } from '../../../../base/common/uri.js'; import { ServicesAccessor } from '../../../../editor/browser/editorExtensions.js'; import { localize, localize2 } from '../../../../nls.js'; import { Action2, MenuId, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; -import { ContextKeyExpr, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { KeyCode } from '../../../../base/common/keyCodes.js'; import { CommandsRegistry, ICommandService } from '../../../../platform/commands/common/commands.js'; -import { IFileDialogService } from '../../../../platform/dialogs/common/dialogs.js'; -import { IQuickInputService, IQuickPickItem, QuickPickInput } from '../../../../platform/quickinput/common/quickInput.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; import { SyncDescriptor } from '../../../../platform/instantiation/common/descriptors.js'; import { IEditorPaneRegistry, EditorPaneDescriptor } from '../../../../workbench/browser/editor.js'; @@ -26,53 +21,45 @@ import { EditorExtensions } from '../../../../workbench/common/editor.js'; import { AgentHostSandboxNotifications } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSandboxNotifications.js'; import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; import { resolveGridCommandView } from '../../../../workbench/contrib/sessions/browser/sessionCommandTarget.js'; -import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; -import { INewSessionInAgentsWindowOptions } from '../../../../workbench/contrib/chat/common/chatSessionsService.js'; import { BranchChatSessionAction } from './branchChatSessionAction.js'; -import { RunScriptContribution } from './runScriptAction.js'; import './nullInlineChatSessionService.js'; import './modelPicker.js'; -import '../../../../workbench/contrib/chat/browser/chatDefaultPresentation.contribution.js'; import './newSessionOnboardingTargets.js'; import './newSessionPickerTryout.js'; import './agentHostDelegation.js'; import './newSessionFolderQuickPickAction.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import { INewSessionComposerService, NewSessionComposerService } from '../../../../workbench/contrib/sessions/browser/newSessionComposerService.js'; -import { KeybindingsRegistry, KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; import { ISessionsTasksService, SessionsTasksService } from './sessionsTasksService.js'; import { ISessionTaskRunnerRegistry, SessionTaskRunnerRegistry } from './sessionTaskRunner.js'; -import { RegisterDefaultSessionTaskRunnersContribution } from './registerDefaultSessionTaskRunners.js'; import { AgenticPromptsService } from './promptsService.js'; import { IPromptsService } from '../../../../workbench/contrib/chat/common/promptSyntax/service/promptsService.js'; import { IAICustomizationWorkspaceService } from '../../../../workbench/contrib/chat/common/aiCustomizationWorkspaceService.js'; import { ICustomizationHarnessService } from '../../../../workbench/contrib/chat/common/customizationHarnessService.js'; import { SessionsAICustomizationWorkspaceService } from './aiCustomizationWorkspaceService.js'; import { SessionsCustomizationHarnessService } from './customizationHarnessService.js'; -import { IChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; -import { ChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chat/chatView.js'; import { CHAT_CATEGORY } from '../../../../workbench/contrib/chat/browser/actions/chatActions.js'; import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; -import { SessionComparisonAccessibleView, SessionsChatAccessibilityHelp } from './sessionsChatAccessibilityHelp.js'; +import { SessionComparisonAccessibleView } from './sessionsChatAccessibilityHelp.js'; import { SessionWorktreeCleanupAccessibilityHelp } from '../../sessionInputBanners/browser/sessionWorktreeCleanupAccessibilityHelp.js'; import { ArtifactDetailsAccessibilityHelp, ArtifactDetailsAccessibleView } from '../../../../workbench/contrib/sessions/browser/chat/artifactDetailsContextView.js'; import { SessionsOpenerParticipantContribution } from './sessionsOpenerParticipant.js'; import { OpenSessionLinkOpenerContribution } from './openSessionLinkOpener.contribution.js'; -import { WorktreeCreatedTaskDispatcher, AGENT_HOST_RUN_WORKTREE_CREATED_TASKS_SETTING } from './worktreeCreatedTaskDispatcher.js'; +import { SessionLinkAttachmentWidgetContribution } from './sessionLinkAttachmentWidget.js'; +import { AGENT_HOST_RUN_WORKTREE_CREATED_TASKS_SETTING } from './worktreeCreatedTaskDispatcher.js'; import { AGENT_SESSIONS_SCOPED_INPUT_HISTORY_SETTING } from '../../../../workbench/contrib/sessions/browser/chat/sessionsChatHistory.js'; import '../../sessions/browser/mobile/mobileOverlayContribution.js'; import { IsSessionsWindowContext } from '../../../../workbench/common/contextkeys.js'; -import { AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING, COLLAPSED_SESSION_OPTIONS_SHOW_ICONS_SETTING, COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_OPEN_IN_GRID_SETTING, COMPARE_AGENTS_SHOW_PICKER_HINT_SETTING, COMPARE_AGENTS_SHOW_SPOTLIGHT_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_ACTION_ID, NEW_SESSION_COMPOSER_OPTIONS_EXPANDED_SETTING, NEW_SESSION_CONNECTOR_RECOMMENDATIONS_SETTING, NEW_SESSION_WELCOME_MESSAGES_SETTING, NEW_SESSION_WELCOME_NAME_SETTING, NEW_SESSION_WELCOME_PHRASES_SETTING, REMOTE_ENVIRONMENTS_THIS_COMPUTER_SETTING, WORKSPACE_OPT_OUT_SETTING } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; -import { DesktopLayoutContext, IsPhoneLayoutContext, SessionsChatBackgroundAvailableContext, SessionsChatBackgroundImageConfiguredContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING, COLLAPSED_SESSION_OPTIONS_SHOW_ICONS_SETTING, COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_OPEN_IN_GRID_SETTING, COMPARE_AGENTS_SHOW_PICKER_HINT_SETTING, COMPARE_AGENTS_SHOW_SPOTLIGHT_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_COMPOSER_OPTIONS_EXPANDED_SETTING, NEW_SESSION_CONNECTOR_RECOMMENDATIONS_SETTING, NEW_SESSION_WELCOME_MESSAGES_SETTING, NEW_SESSION_WELCOME_NAME_SETTING, NEW_SESSION_WELCOME_PHRASES_SETTING, REMOTE_ENVIRONMENTS_THIS_COMPUTER_SETTING, WORKSPACE_OPT_OUT_SETTING } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; +import { DesktopLayoutContext, IsPhoneLayoutContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; import { SESSION_ACTIVITY_BAR_SETTING } from '../../../../workbench/contrib/sessions/common/sessionConfig.js'; import { TOGGLE_SESSION_ACTIVITY_BAR_COMMAND_ID } from '../../../browser/layoutActions.js'; import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; import { ISessionsChatViewStateService, SessionsChatViewStateService } from '../../../../workbench/contrib/sessions/browser/chat/chatViewStateService.js'; import { SessionsChatResponseFileChangesService } from './sessionTurnChanges.js'; import { IChatResponseFileChangesService } from '../../../../workbench/contrib/chat/browser/chatResponseFileChangesService.js'; -import { SessionsChatPetAchievementContribution } from './chatPetAchievements.js'; -import { AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING, AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_SETTING, AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING, AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_SETTING, chatBackgroundImageExtensions, chatBackgroundImageLayoutValues, ChatBackgroundImageLayout, chatBackgroundPresets, getChatBackgroundPresetLabel, ISessionsChatBackgroundService, SessionsChatBackgroundPreset, SessionsChatBackgroundService } from '../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; import { ISessionArchiveNudgeService, SESSION_ARCHIVE_NUDGE_SETTING, SessionArchiveNudgeContribution, SessionArchiveNudgeService } from '../../../../workbench/contrib/sessions/browser/chat/sessionArchiveNudge.js'; import { NewChatInSessionsWindowAction } from '../../../../workbench/contrib/sessions/browser/chat/newSessionAction.js'; import { HIDE_INACTIVE_COMPARISON_INPUTS_SETTING } from '../../../../workbench/contrib/sessions/common/sessionComparisonConstants.js'; @@ -80,8 +67,6 @@ import { appendNewSessionTitleBarMenuItem } from './newSessionTitleBarMenu.js'; import { FOCUS_NEW_SESSION_ENVIRONMENT_PICKER_COMMAND_ID, FOCUS_NEW_SESSION_HARNESS_PICKER_COMMAND_ID, FOCUS_NEW_SESSION_WORKSPACE_PICKER_COMMAND_ID, FOCUS_NEW_SESSION_BRANCH_PICKER_COMMAND_ID, FOCUS_NEW_SESSION_WORKTREE_PICKER_COMMAND_ID, FOCUS_SESSION_SYNC_ACTION_COMMAND_ID } from '../../../../workbench/contrib/sessions/common/sessionCommands.js'; import { FOCUS_NEW_SESSION_ENVIRONMENT_PICKER_KEYBINDING, FOCUS_NEW_SESSION_ENVIRONMENT_PICKER_WHEN, FOCUS_NEW_SESSION_HARNESS_PICKER_KEYBINDING, FOCUS_NEW_SESSION_HARNESS_PICKER_WHEN, FOCUS_NEW_SESSION_WORKSPACE_PICKER_KEYBINDING, FOCUS_NEW_SESSION_WORKSPACE_PICKER_WHEN, FOCUS_NEW_SESSION_BRANCH_PICKER_KEYBINDING, FOCUS_NEW_SESSION_BRANCH_PICKER_WHEN, FOCUS_NEW_SESSION_WORKTREE_PICKER_KEYBINDING, FOCUS_NEW_SESSION_WORKTREE_PICKER_WHEN, FOCUS_SESSION_SYNC_ACTION_KEYBINDING, FOCUS_SESSION_SYNC_ACTION_WHEN } from '../../../../workbench/contrib/sessions/browser/chat/newChatPickerKeybinding.js'; import { ISessionsPartService } from '../../../../workbench/services/sessions/browser/sessionsPartService.js'; -import { AGENT_SESSIONS_CHAT_BACKGROUND_IMAGE_TINT_SETTING, SessionsChatBackgroundTint, ToggleChatBackgroundTintAction } from './chatBackgroundTint.js'; -import { GetThemeColorsToolContribution } from './getThemeColorsTool.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { sessionStorageCleanupSuggestionConfigurationMigration } from '../../sessionInputBanners/browser/sessionStorageCleanupConfiguration.js'; import { AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING, ISessionWorktreeCleanupService, MANAGE_AGENT_SESSION_WORKTREES_COMMAND_ID, SessionWorktreeCleanupService } from '../../../../workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.js'; @@ -90,116 +75,11 @@ import { SessionWorktreeCleanupEditor } from '../../sessionInputBanners/browser/ import { INewChatVoiceTargetService, NewChatVoiceTargetService } from '../../../../workbench/contrib/sessions/browser/chat/newChatVoice.js'; import { ISessionChatPillsDebugService, SessionChatPillsDebugService } from '../../../../workbench/contrib/sessions/browser/chat/sessionChatInputToolbarDebug.js'; import { ADD_SESSION_REFERENCE_COMMAND, addSessionReference, IAddSessionReferenceArgs } from '../../../../workbench/contrib/sessions/browser/chat/sessionReferenceCompletions.js'; -import { PromptTemplatePlaceholderFocused, REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID, replaceActivePromptTemplatePlaceholder } from '../../../../workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.js'; +import { registerReplacePromptTemplatePlaceholderCommand } from '../../../../workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.js'; import { registerCompareAgentsSpotlightDescriptor } from '../../../../workbench/contrib/sessions/browser/chat/compareAgentsSpotlight.js'; import { registerWorktreeSuggestionTourDescriptor } from '../../../../workbench/contrib/sessions/browser/tours/worktreeSuggestionTour.js'; import { registerSessionArchiveTourDescriptor } from '../../../../workbench/contrib/sessions/browser/tours/sessionArchiveTour.js'; -const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_COMMAND_ID = 'workbench.action.chat.changeAgentSessionsBackground'; -const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_COMMAND_ID = 'workbench.action.chat.changeAgentSessionsBackgroundLayout'; -const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN = ContextKeyExpr.and(IsSessionsWindowContext, SessionsChatBackgroundAvailableContext); -const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN = ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, SessionsChatBackgroundImageConfiguredContext); -const GENERATE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN = ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.equals(`config.${AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING}`, true)); - -type RecentChatBackgroundTypeItem = IQuickPickItem & { - readonly kind: 'recentImage'; - readonly image: URI; -}; - -type ChatBackgroundTypeItem = IQuickPickItem & ({ - readonly kind: 'none' | SessionsChatBackgroundPreset | 'image' | 'generate'; -}) | RecentChatBackgroundTypeItem; - -const chatBackgroundTypeItems: ChatBackgroundTypeItem[] = [{ - kind: 'none', - label: localize('chat.agentSessions.backgroundType.none.label', "No Background"), - detail: localize('chat.agentSessions.backgroundType.none.detail', "Remove the current chat background."), -}, { - kind: 'codicons', - label: getChatBackgroundPresetLabel('codicons'), - detail: localize('chat.agentSessions.backgroundType.codicons.detail', "Use a theme-aware pattern of built-in VS Code icons."), -}, { - kind: 'koi-light', - label: getChatBackgroundPresetLabel('koi-light'), - detail: localize('chat.agentSessions.backgroundType.koiLight.detail', "Use an animated ASCII koi pond on a light background."), -}, { - kind: 'koi-dark', - label: getChatBackgroundPresetLabel('koi-dark'), - detail: localize('chat.agentSessions.backgroundType.koiDark.detail', "Use an animated ASCII koi pond on a dark background."), -}, { - kind: 'image', - label: localize('chat.agentSessions.backgroundType.image.label', "Image..."), - detail: localize('chat.agentSessions.backgroundType.image.detail', "Choose an image file from this machine."), -}]; - -const generateChatBackgroundTypeItem: ChatBackgroundTypeItem = { - kind: 'generate', - label: localize('chat.agentSessions.backgroundType.generate.label', "Generate Background..."), - detail: localize('chat.agentSessions.backgroundType.generate.detail', "Describe an image for an agent to generate and set in a new session."), -}; - -interface IChatBackgroundImageLayoutMetadata extends IQuickPickItem { - readonly detail: string; -} - -const chatBackgroundImageLayoutMetadata: Record = { - repeat: { - label: localize('chat.agentSessions.backgroundImageLayout.repeat.label', "Repeat"), - detail: localize('chat.agentSessions.backgroundImageLayout.repeat.description', "Repeats the image at its original size until it fills the chat background."), - }, - stretch: { - label: localize('chat.agentSessions.backgroundImageLayout.stretch.label', "Stretch"), - detail: localize('chat.agentSessions.backgroundImageLayout.stretch.description', "Stretches the image to fill the chat background."), - }, - center: { - label: localize('chat.agentSessions.backgroundImageLayout.center.label', "Center"), - detail: localize('chat.agentSessions.backgroundImageLayout.center.description', "Shows the image at its original size in the center."), - }, - top: { - label: localize('chat.agentSessions.backgroundImageLayout.top.label', "Top"), - detail: localize('chat.agentSessions.backgroundImageLayout.top.description', "Shows the image at its original size at the top center."), - }, - 'top-right': { - label: localize('chat.agentSessions.backgroundImageLayout.topRight.label', "Top Right"), - detail: localize('chat.agentSessions.backgroundImageLayout.topRight.description', "Shows the image at its original size in the top right."), - }, - 'top-left': { - label: localize('chat.agentSessions.backgroundImageLayout.topLeft.label', "Top Left"), - detail: localize('chat.agentSessions.backgroundImageLayout.topLeft.description', "Shows the image at its original size in the top left."), - }, - bottom: { - label: localize('chat.agentSessions.backgroundImageLayout.bottom.label', "Bottom"), - detail: localize('chat.agentSessions.backgroundImageLayout.bottom.description', "Shows the image at its original size at the bottom center."), - }, - 'bottom-right': { - label: localize('chat.agentSessions.backgroundImageLayout.bottomRight.label', "Bottom Right"), - detail: localize('chat.agentSessions.backgroundImageLayout.bottomRight.description', "Shows the image at its original size in the bottom right."), - }, - 'bottom-left': { - label: localize('chat.agentSessions.backgroundImageLayout.bottomLeft.label', "Bottom Left"), - detail: localize('chat.agentSessions.backgroundImageLayout.bottomLeft.description', "Shows the image at its original size in the bottom left."), - }, - left: { - label: localize('chat.agentSessions.backgroundImageLayout.left.label', "Left"), - detail: localize('chat.agentSessions.backgroundImageLayout.left.description', "Shows the image at its original size at the center left."), - }, - right: { - label: localize('chat.agentSessions.backgroundImageLayout.right.label', "Right"), - detail: localize('chat.agentSessions.backgroundImageLayout.right.description', "Shows the image at its original size at the center right."), - }, -}; - -const chatBackgroundImageLayoutItems = chatBackgroundImageLayoutValues.map(layout => ({ - layout, - ...chatBackgroundImageLayoutMetadata[layout], -})); - -const chatBackgroundImageLayoutEnumConfiguration = { - enum: [...chatBackgroundImageLayoutValues], - enumItemLabels: chatBackgroundImageLayoutItems.map(item => item.label), - enumDescriptions: chatBackgroundImageLayoutItems.map(item => item.detail), -}; - registerAction2(NewChatInSessionsWindowAction); appendNewSessionTitleBarMenuItem(); @@ -441,167 +321,6 @@ class HideNewSessionWelcomeMessageAction extends Action2 { registerAction2(HideNewSessionWelcomeMessageAction); -class SetChatBackgroundAction extends Action2 { - - constructor() { - super({ - id: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_COMMAND_ID, - title: localize2('chat.agentSessions.setBackground', "Set Background..."), - category: CHAT_CATEGORY, - precondition: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, - menu: [{ - id: MenuId.CommandPalette, - when: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, - }, { - id: Menus.SessionChatBackgroundContext, - group: 'navigation', - order: 1, - when: SessionsChatBackgroundAvailableContext, - }, { - id: MenuId.ChatContext, - group: 'zz_background', - order: 1, - when: ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, ChatContextKeys.contextMenuIsBackground), - }], - }); - } - - override async run(accessor: ServicesAccessor): Promise { - const backgroundService = accessor.get(ISessionsChatBackgroundService); - const quickInputService = accessor.get(IQuickInputService); - const fileDialogService = accessor.get(IFileDialogService); - const commandService = accessor.get(ICommandService); - const canGenerate = accessor.get(IContextKeyService).contextMatchesRules(GENERATE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN) - && accessor.get(ISessionsManagementService).isQuickChatTargetAvailable(); - const configuredBackground = backgroundService.getConfiguredBackground(); - const backgroundKind = configuredBackground?.kind === 'image' ? configuredBackground.preset ?? 'image' : configuredBackground?.kind ?? 'none'; - const recentImages = backgroundService.getRecentBackgroundImages(); - const recentItems: RecentChatBackgroundTypeItem[] = recentImages.map(image => ({ - kind: 'recentImage', - image, - label: basename(image) || image.fsPath, - detail: image.fsPath, - })); - const items: QuickPickInput[] = [...chatBackgroundTypeItems]; - if (canGenerate) { - items.push({ type: 'separator' }, generateChatBackgroundTypeItem); - } - if (recentItems.length > 0) { - items.push({ - type: 'separator', - label: localize('chat.agentSessions.backgroundType.recentlyUsed', "recently used"), - }, ...recentItems); - } - const currentImage = backgroundService.getConfiguredBackgroundImage(); - const backgroundType = await quickInputService.pick(items, { - title: localize('chat.agentSessions.setBackground.title', "Set Chat Background"), - placeHolder: localize('chat.agentSessions.setBackground.placeholder', "Select a background type"), - activeItem: backgroundKind === 'image' - ? recentItems.find(item => currentImage && isEqual(item.image, currentImage)) - : chatBackgroundTypeItems.find(item => item.kind === backgroundKind), - }); - if (!backgroundType) { - return; - } - if (backgroundType.kind === 'none') { - await backgroundService.clearBackground('backgroundPicker'); - status(localize('chat.agentSessions.clearBackground.cleared', "Chat background cleared.")); - return; - } - if (backgroundType.kind === 'codicons' || backgroundType.kind === 'koi-light' || backgroundType.kind === 'koi-dark') { - await backgroundService.setBackground(backgroundType.kind, 'backgroundPicker'); - status(localize('chat.agentSessions.setBackground.preset', "Chat background set to {0}.", backgroundType.label)); - return; - } - if (backgroundType.kind === 'recentImage') { - await backgroundService.setBackground(backgroundType.image, 'backgroundPicker'); - status(localize('chat.agentSessions.setBackground.recentImage', "Chat background image set to {0}.", backgroundType.label)); - return; - } - if (backgroundType.kind === 'generate') { - const options: INewSessionInAgentsWindowOptions = { - // The trailing space is outside the localized text so translations can't drop it before the caret. - prompt: `${localize('chat.agentSessions.generateBackground.prompt', "Generate a chat background of")} `, - prefillPrompt: true, - noWorkspace: true, - }; - await commandService.executeCommand(NEW_SESSION_ACTION_ID, options); - return; - } - - const selected = await fileDialogService.showOpenDialog({ - title: localize('chat.agentSessions.setBackground.dialogTitle', "Set Chat Background"), - openLabel: localize('chat.agentSessions.setBackground.openLabel', "Set Background"), - canSelectFiles: true, - canSelectFolders: false, - canSelectMany: false, - filters: [{ - name: localize('chat.agentSessions.changeBackground.images', "Images"), - extensions: [...chatBackgroundImageExtensions], - }], - availableFileSystems: [Schemas.file], - defaultUri: configuredBackground?.kind === 'image' && !configuredBackground.preset ? currentImage : undefined, - }); - const image = selected?.[0]; - if (!image) { - return; - } - - await backgroundService.setBackground(image, 'backgroundPicker'); - status(localize('chat.agentSessions.setBackground.image', "Chat background image set.")); - } -} - -registerAction2(SetChatBackgroundAction); - -class ChangeChatBackgroundLayoutAction extends Action2 { - - constructor() { - super({ - id: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_COMMAND_ID, - title: localize2('chat.agentSessions.changeBackgroundLayout', "Change Background Layout..."), - category: CHAT_CATEGORY, - precondition: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, - menu: [{ - id: MenuId.CommandPalette, - when: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, - }, { - id: Menus.SessionChatBackgroundContext, - group: 'navigation', - order: 2, - when: ContextKeyExpr.and(SessionsChatBackgroundAvailableContext, SessionsChatBackgroundImageConfiguredContext), - }, { - id: MenuId.ChatContext, - group: 'zz_background', - order: 2, - when: ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, ChatContextKeys.contextMenuIsBackground), - }], - }); - } - - override async run(accessor: ServicesAccessor): Promise { - const backgroundService = accessor.get(ISessionsChatBackgroundService); - const currentLayout = backgroundService.getBackgroundImageLayout(); - let selected: (typeof chatBackgroundImageLayoutItems)[number] | undefined; - try { - selected = await accessor.get(IQuickInputService).pick(chatBackgroundImageLayoutItems, { - title: localize('chat.agentSessions.changeBackgroundLayout.title', "Change Chat Background Layout"), - placeHolder: localize('chat.agentSessions.changeBackgroundLayout.placeholder', "Select how the background image is displayed"), - activeItem: chatBackgroundImageLayoutItems.find(item => item.layout === currentLayout), - onDidFocus: item => void backgroundService.setBackgroundImageLayout(item.layout, 'layoutPicker', false), - }); - } finally { - await backgroundService.setBackgroundImageLayout(selected?.layout ?? currentLayout, 'layoutPicker', selected !== undefined); - } - if (selected && selected.layout !== currentLayout) { - status(localize('chat.agentSessions.changeBackgroundLayout.changed', "Chat background layout changed to {0}.", selected.label)); - } - } -} - -registerAction2(ChangeChatBackgroundLayoutAction); -registerAction2(ToggleChatBackgroundTintAction); - const toggleSessionActivityBarCommand = { id: TOGGLE_SESSION_ACTIVITY_BAR_COMMAND_ID, title: localize('sessionActivityBar', "Session Activity Bar"), @@ -682,15 +401,13 @@ registerAction2(class DisableSessionStorageCleanupSuggestionsAction extends Acti registerAction2(BranchChatSessionAction); // register workbench contributions -registerWorkbenchContribution2(RunScriptContribution.ID, RunScriptContribution, WorkbenchPhase.AfterRestored); +// Desktop-only contributions (run scripts, task runners, chat pet) live in +// chat.desktop.contribution.ts so the phone bundle can omit them. registerWorkbenchContribution2(SessionsOpenerParticipantContribution.ID, SessionsOpenerParticipantContribution, WorkbenchPhase.BlockStartup); registerWorkbenchContribution2(OpenSessionLinkOpenerContribution.ID, OpenSessionLinkOpenerContribution, WorkbenchPhase.BlockStartup); -registerWorkbenchContribution2(RegisterDefaultSessionTaskRunnersContribution.ID, RegisterDefaultSessionTaskRunnersContribution, WorkbenchPhase.BlockStartup); -registerWorkbenchContribution2(WorktreeCreatedTaskDispatcher.ID, WorktreeCreatedTaskDispatcher, WorkbenchPhase.AfterRestored); -registerWorkbenchContribution2(SessionsChatPetAchievementContribution.ID, SessionsChatPetAchievementContribution, WorkbenchPhase.AfterRestored); +// Before chat inputs restore their drafts, whose session links become pills once a widget can show them. +registerWorkbenchContribution2(SessionLinkAttachmentWidgetContribution.ID, SessionLinkAttachmentWidgetContribution, WorkbenchPhase.BlockStartup); registerWorkbenchContribution2(SessionArchiveNudgeContribution.ID, SessionArchiveNudgeContribution, WorkbenchPhase.AfterRestored); -registerWorkbenchContribution2(SessionsChatBackgroundTint.ID, SessionsChatBackgroundTint, WorkbenchPhase.AfterRestored); -registerWorkbenchContribution2(GetThemeColorsToolContribution.ID, GetThemeColorsToolContribution, WorkbenchPhase.Eventually); registerWorkbenchContribution2(AgentHostSandboxNotifications.ID, AgentHostSandboxNotifications, WorkbenchPhase.AfterRestored); // register services @@ -702,19 +419,11 @@ registerSingleton(ISessionChatPillsDebugService, SessionChatPillsDebugService, I CommandsRegistry.registerCommand(ADD_SESSION_REFERENCE_COMMAND, (_accessor, args: IAddSessionReferenceArgs) => addSessionReference(args)); -KeybindingsRegistry.registerCommandAndKeybindingRule({ - id: REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID, - weight: KeybindingWeight.WorkbenchContrib + 2, - when: PromptTemplatePlaceholderFocused, - primary: KeyCode.Enter, - handler: () => replaceActivePromptTemplatePlaceholder(), -}); +registerReplacePromptTemplatePlaceholderCommand(); registerSingleton(IAICustomizationWorkspaceService, SessionsAICustomizationWorkspaceService, InstantiationType.Delayed); registerSingleton(ICustomizationHarnessService, SessionsCustomizationHarnessService, InstantiationType.Delayed); -registerSingleton(IChatViewFactory, ChatViewFactory, InstantiationType.Delayed); registerSingleton(ISessionsChatViewStateService, SessionsChatViewStateService, InstantiationType.Delayed); registerSingleton(IChatResponseFileChangesService, SessionsChatResponseFileChangesService, InstantiationType.Delayed); -registerSingleton(ISessionsChatBackgroundService, SessionsChatBackgroundService, InstantiationType.Delayed); registerSingleton(INewSessionComposerService, NewSessionComposerService, InstantiationType.Delayed); registerSingleton(ISessionArchiveNudgeService, SessionArchiveNudgeService, InstantiationType.Eager); registerSingleton(ISessionWorktreeCleanupService, SessionWorktreeCleanupService, InstantiationType.Delayed); @@ -725,7 +434,6 @@ registerWorktreeSuggestionTourDescriptor(); registerSessionArchiveTourDescriptor(); // register accessibility help -AccessibleViewRegistry.register(new SessionsChatAccessibilityHelp()); AccessibleViewRegistry.register(new ArtifactDetailsAccessibilityHelp()); AccessibleViewRegistry.register(new ArtifactDetailsAccessibleView()); AccessibleViewRegistry.register(new SessionWorktreeCleanupAccessibilityHelp()); @@ -740,7 +448,7 @@ Registry.as(ConfigurationExtensions.Configuration).regis scope: ConfigurationScope.APPLICATION, tags: ['experimental'], experiment: { mode: 'auto' }, - description: localize('chat.agentSessions.responseSelectionMenu.enabled', "Shows an enhanced action menu with Ask in a Side Chat, Quote, and Copy when selecting assistant response text in the Agents Window."), + description: localize('chat.agentSessions.responseSelectionMenu.enabled', "Controls whether an action menu with Ask in a Side Chat, Quote, and Copy appears when selecting assistant response text in the Agents Window."), }, [SESSION_ARCHIVE_NUDGE_SETTING]: { type: 'boolean', @@ -794,6 +502,7 @@ Registry.as(ConfigurationExtensions.Configuration).regis scope: ConfigurationScope.APPLICATION, markdownDescription: localize('sessions.chat.compareAgents.showSpotlight', "Show a one-time spotlight on Compare Models when an eligible model picker opens, introducing parallel models and agent harnesses, with an optional judge and synthesis where available. Does not appear if comparison setup has already been opened. Requires `#sessions.chat.compareAgents.enabled#` and `#onboarding.enabled#`."), tags: ['experimental'], + experiment: { mode: 'auto' }, }, [COMPARE_AGENTS_OPEN_IN_GRID_SETTING]: { type: 'boolean', @@ -841,7 +550,7 @@ Registry.as(ConfigurationExtensions.Configuration).regis type: 'boolean', default: false, scope: ConfigurationScope.WINDOW, - description: localize('sessions.chat.experimental.remoteEnvironmentsThisComputer', "Controls whether the Remote Environments editor shows a This Computer section for choosing how this computer is shared with other clients. Requires Remote Environments management."), + description: localize('sessions.chat.experimental.remoteEnvironmentsThisComputer', "Controls whether the Remote Environments editor shows a This Computer section for choosing how this computer is shared with other devices. Requires Remote Environments management."), tags: ['experimental'], experiment: { mode: 'auto' }, }, @@ -909,57 +618,6 @@ Registry.as(ConfigurationExtensions.Configuration).regis scope: ConfigurationScope.APPLICATION, tags: ['experimental'], }, - [AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING]: { - type: 'boolean', - default: false, - scope: ConfigurationScope.APPLICATION, - tags: ['advanced'], - experiment: { mode: 'auto' }, - markdownDescription: localize('chat.agentSessions.appearanceTools.enabled', "Enable the Get Theme Colors, Set Chat Background, and Screenshot Window tools and the built-in `generate-chat-background` skill in the Agents window. Disabling this does not remove existing backgrounds or affect the manual background controls."), - }, - [AGENT_SESSIONS_CHAT_BACKGROUND_IMAGE_TINT_SETTING]: { - type: 'boolean', - default: false, - scope: ConfigurationScope.APPLICATION, - description: localize('chat.agentSessions.backgroundImageTint', "Match the Agents window colors to your chat background image. Other windows keep their current theme. Not available in high contrast themes."), - tags: ['experimental'], - }, - [AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_SETTING]: { - type: 'string', - default: '', - scope: ConfigurationScope.MACHINE, - markdownDescription: localize('chat.agentSessions.preferredDarkBackgroundImage', "Specifies a built-in background (`codicons`, `koi-light`, or `koi-dark`), an absolute file path, or a `file` URI for the background displayed behind chat content in the Agents Window when using a dark color theme. The background is hidden in high contrast themes."), - examples: [...chatBackgroundPresets], - tags: ['experimental'], - ignoreSync: true, - }, - [AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_SETTING]: { - type: 'string', - default: '', - scope: ConfigurationScope.MACHINE, - markdownDescription: localize('chat.agentSessions.preferredLightBackgroundImage', "Specifies a built-in background (`codicons`, `koi-light`, or `koi-dark`), an absolute file path, or a `file` URI for the background displayed behind chat content in the Agents Window when using a light color theme. The background is hidden in high contrast themes."), - examples: [...chatBackgroundPresets], - tags: ['experimental'], - ignoreSync: true, - }, - [AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING]: { - type: 'string', - ...chatBackgroundImageLayoutEnumConfiguration, - default: 'repeat', - scope: ConfigurationScope.MACHINE, - markdownDescription: localize('chat.agentSessions.preferredDarkBackgroundImageLayout', "Controls how the chat background image is laid out in the Agents Window when using a dark color theme."), - tags: ['experimental'], - ignoreSync: true, - }, - [AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING]: { - type: 'string', - ...chatBackgroundImageLayoutEnumConfiguration, - default: 'repeat', - scope: ConfigurationScope.MACHINE, - markdownDescription: localize('chat.agentSessions.preferredLightBackgroundImageLayout', "Controls how the chat background image is laid out in the Agents Window when using a light color theme."), - tags: ['experimental'], - ignoreSync: true, - }, }, }); diff --git a/src/vs/sessions/contrib/chat/browser/chat.desktop.contribution.ts b/src/vs/sessions/contrib/chat/browser/chat.desktop.contribution.ts new file mode 100644 index 000000000000..e763350766b4 --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/chat.desktop.contribution.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 { registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { AccessibleViewType } from '../../../../platform/accessibility/browser/accessibleView.js'; +import { ChatHtmlPreviewAccessibleView } from '../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewEditorInput.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { DefaultChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chat/defaultChatViewFactory.js'; +import { IChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; +import '../../../../workbench/contrib/chat/browser/chatDefaultPresentation.contribution.js'; +import './chatBackground.contribution.js'; +import { SessionsChatPetAchievementContribution } from './chatPetAchievements.js'; +import { RegisterDefaultSessionTaskRunnersContribution } from './registerDefaultSessionTaskRunners.js'; +import { RunScriptContribution } from './runScriptAction.js'; +import { WorktreeCreatedTaskDispatcher } from './worktreeCreatedTaskDispatcher.js'; +import { SessionsChatAccessibilityHelp } from './sessionsChatAccessibilityHelp.js'; + +// Chat contributions that need the desktop (and desktop-web) workbench: running +// scripts and tasks in a terminal, chat backgrounds, and the chat pet. The shared registrations +// live in chat.contribution.ts; the phone bundle imports that file but not this one. + +registerWorkbenchContribution2(RunScriptContribution.ID, RunScriptContribution, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(RegisterDefaultSessionTaskRunnersContribution.ID, RegisterDefaultSessionTaskRunnersContribution, WorkbenchPhase.BlockStartup); +registerWorkbenchContribution2(WorktreeCreatedTaskDispatcher.ID, WorktreeCreatedTaskDispatcher, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(SessionsChatPetAchievementContribution.ID, SessionsChatPetAchievementContribution, WorkbenchPhase.AfterRestored); +registerSingleton(IChatViewFactory, DefaultChatViewFactory, InstantiationType.Delayed); +AccessibleViewRegistry.register(new SessionsChatAccessibilityHelp()); +// The expanded HTML preview is a webview editor, which the phone bundle does not register. +AccessibleViewRegistry.register(new ChatHtmlPreviewAccessibleView(AccessibleViewType.Help)); +AccessibleViewRegistry.register(new ChatHtmlPreviewAccessibleView(AccessibleViewType.View)); diff --git a/src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts b/src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts new file mode 100644 index 000000000000..7308695536ac --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/chatBackground.contribution.ts @@ -0,0 +1,355 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * 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 { Schemas } from '../../../../base/common/network.js'; +import { basename, isEqual } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ServicesAccessor } from '../../../../editor/browser/editorExtensions.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Action2, MenuId, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; +import { ContextKeyExpr, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IFileDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { IQuickInputService, IQuickPickItem, QuickPickInput } from '../../../../platform/quickinput/common/quickInput.js'; +import { Registry } from '../../../../platform/registry/common/platform.js'; +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { IsSessionsWindowContext } from '../../../../workbench/common/contextkeys.js'; +import { CHAT_CATEGORY } from '../../../../workbench/contrib/chat/browser/actions/chatActions.js'; +import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { INewSessionInAgentsWindowOptions } from '../../../../workbench/contrib/chat/common/chatSessionsService.js'; +import { AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING, AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_SETTING, AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING, AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_SETTING, chatBackgroundImageExtensions, chatBackgroundImageLayoutValues, ChatBackgroundImageLayout, chatBackgroundPresets, getChatBackgroundPresetLabel, ISessionsChatBackgroundService, SessionsChatBackgroundPreset, SessionsChatBackgroundService } from '../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; +import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; +import { AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, NEW_SESSION_ACTION_ID } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; +import { SessionsChatBackgroundAvailableContext, SessionsChatBackgroundImageConfiguredContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { AGENT_SESSIONS_CHAT_BACKGROUND_IMAGE_TINT_SETTING, SessionsChatBackgroundTint, ToggleChatBackgroundTintAction } from './chatBackgroundTint.js'; +import { GetThemeColorsToolContribution } from './getThemeColorsTool.js'; + +const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_COMMAND_ID = 'workbench.action.chat.changeAgentSessionsBackground'; +const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_COMMAND_ID = 'workbench.action.chat.changeAgentSessionsBackgroundLayout'; +const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN = ContextKeyExpr.and(IsSessionsWindowContext, SessionsChatBackgroundAvailableContext); +const CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN = ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, SessionsChatBackgroundImageConfiguredContext); +const GENERATE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN = ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.equals(`config.${AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING}`, true)); + +type RecentChatBackgroundTypeItem = IQuickPickItem & { + readonly kind: 'recentImage'; + readonly image: URI; +}; + +type ChatBackgroundTypeItem = IQuickPickItem & ({ + readonly kind: 'none' | SessionsChatBackgroundPreset | 'image' | 'generate'; +}) | RecentChatBackgroundTypeItem; + +const chatBackgroundTypeItems: ChatBackgroundTypeItem[] = [{ + kind: 'none', + label: localize('chat.agentSessions.backgroundType.none.label', "No Background"), + detail: localize('chat.agentSessions.backgroundType.none.detail', "Remove the current chat background."), +}, { + kind: 'codicons', + label: getChatBackgroundPresetLabel('codicons'), + detail: localize('chat.agentSessions.backgroundType.codicons.detail', "Use a theme-aware pattern of built-in VS Code icons."), +}, { + kind: 'koi-light', + label: getChatBackgroundPresetLabel('koi-light'), + detail: localize('chat.agentSessions.backgroundType.koiLight.detail', "Use an animated ASCII koi pond on a light background."), +}, { + kind: 'koi-dark', + label: getChatBackgroundPresetLabel('koi-dark'), + detail: localize('chat.agentSessions.backgroundType.koiDark.detail', "Use an animated ASCII koi pond on a dark background."), +}, { + kind: 'image', + label: localize('chat.agentSessions.backgroundType.image.label', "Image..."), + detail: localize('chat.agentSessions.backgroundType.image.detail', "Choose an image file from this machine."), +}]; + +const generateChatBackgroundTypeItem: ChatBackgroundTypeItem = { + kind: 'generate', + label: localize('chat.agentSessions.backgroundType.generate.label', "Generate Background..."), + detail: localize('chat.agentSessions.backgroundType.generate.detail', "Describe an image for an agent to generate and set in a new session."), +}; + +interface IChatBackgroundImageLayoutMetadata extends IQuickPickItem { + readonly detail: string; +} + +const chatBackgroundImageLayoutMetadata: Record = { + repeat: { + label: localize('chat.agentSessions.backgroundImageLayout.repeat.label', "Repeat"), + detail: localize('chat.agentSessions.backgroundImageLayout.repeat.description', "Repeats the image at its original size until it fills the chat background."), + }, + stretch: { + label: localize('chat.agentSessions.backgroundImageLayout.stretch.label', "Stretch"), + detail: localize('chat.agentSessions.backgroundImageLayout.stretch.description', "Stretches the image to fill the chat background."), + }, + center: { + label: localize('chat.agentSessions.backgroundImageLayout.center.label', "Center"), + detail: localize('chat.agentSessions.backgroundImageLayout.center.description', "Shows the image at its original size in the center."), + }, + top: { + label: localize('chat.agentSessions.backgroundImageLayout.top.label', "Top"), + detail: localize('chat.agentSessions.backgroundImageLayout.top.description', "Shows the image at its original size at the top center."), + }, + 'top-right': { + label: localize('chat.agentSessions.backgroundImageLayout.topRight.label', "Top Right"), + detail: localize('chat.agentSessions.backgroundImageLayout.topRight.description', "Shows the image at its original size in the top right."), + }, + 'top-left': { + label: localize('chat.agentSessions.backgroundImageLayout.topLeft.label', "Top Left"), + detail: localize('chat.agentSessions.backgroundImageLayout.topLeft.description', "Shows the image at its original size in the top left."), + }, + bottom: { + label: localize('chat.agentSessions.backgroundImageLayout.bottom.label', "Bottom"), + detail: localize('chat.agentSessions.backgroundImageLayout.bottom.description', "Shows the image at its original size at the bottom center."), + }, + 'bottom-right': { + label: localize('chat.agentSessions.backgroundImageLayout.bottomRight.label', "Bottom Right"), + detail: localize('chat.agentSessions.backgroundImageLayout.bottomRight.description', "Shows the image at its original size in the bottom right."), + }, + 'bottom-left': { + label: localize('chat.agentSessions.backgroundImageLayout.bottomLeft.label', "Bottom Left"), + detail: localize('chat.agentSessions.backgroundImageLayout.bottomLeft.description', "Shows the image at its original size in the bottom left."), + }, + left: { + label: localize('chat.agentSessions.backgroundImageLayout.left.label', "Left"), + detail: localize('chat.agentSessions.backgroundImageLayout.left.description', "Shows the image at its original size at the center left."), + }, + right: { + label: localize('chat.agentSessions.backgroundImageLayout.right.label', "Right"), + detail: localize('chat.agentSessions.backgroundImageLayout.right.description', "Shows the image at its original size at the center right."), + }, +}; + +const chatBackgroundImageLayoutItems = chatBackgroundImageLayoutValues.map(layout => ({ + layout, + ...chatBackgroundImageLayoutMetadata[layout], +})); + +const chatBackgroundImageLayoutEnumConfiguration = { + enum: [...chatBackgroundImageLayoutValues], + enumItemLabels: chatBackgroundImageLayoutItems.map(item => item.label), + enumDescriptions: chatBackgroundImageLayoutItems.map(item => item.detail), +}; + +class SetChatBackgroundAction extends Action2 { + + constructor() { + super({ + id: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_COMMAND_ID, + title: localize2('chat.agentSessions.setBackground', "Set Background..."), + category: CHAT_CATEGORY, + precondition: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, + menu: [{ + id: MenuId.CommandPalette, + when: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, + }, { + id: Menus.SessionChatBackgroundContext, + group: 'navigation', + order: 1, + when: SessionsChatBackgroundAvailableContext, + }, { + id: MenuId.ChatContext, + group: 'zz_background', + order: 1, + when: ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN, ChatContextKeys.contextMenuIsBackground), + }], + }); + } + + override async run(accessor: ServicesAccessor): Promise { + const backgroundService = accessor.get(ISessionsChatBackgroundService); + const quickInputService = accessor.get(IQuickInputService); + const fileDialogService = accessor.get(IFileDialogService); + const commandService = accessor.get(ICommandService); + const canGenerate = accessor.get(IContextKeyService).contextMatchesRules(GENERATE_AGENT_SESSIONS_CHAT_BACKGROUND_WHEN) + && accessor.get(ISessionsManagementService).isQuickChatTargetAvailable(); + const configuredBackground = backgroundService.getConfiguredBackground(); + const backgroundKind = configuredBackground?.kind === 'image' ? configuredBackground.preset ?? 'image' : configuredBackground?.kind ?? 'none'; + const recentImages = backgroundService.getRecentBackgroundImages(); + const recentItems: RecentChatBackgroundTypeItem[] = recentImages.map(image => ({ + kind: 'recentImage', + image, + label: basename(image) || image.fsPath, + detail: image.fsPath, + })); + const items: QuickPickInput[] = [...chatBackgroundTypeItems]; + if (canGenerate) { + items.push({ type: 'separator' }, generateChatBackgroundTypeItem); + } + if (recentItems.length > 0) { + items.push({ + type: 'separator', + label: localize('chat.agentSessions.backgroundType.recentlyUsed', "recently used"), + }, ...recentItems); + } + const currentImage = backgroundService.getConfiguredBackgroundImage(); + const backgroundType = await quickInputService.pick(items, { + title: localize('chat.agentSessions.setBackground.title', "Set Chat Background"), + placeHolder: localize('chat.agentSessions.setBackground.placeholder', "Select a background type"), + activeItem: backgroundKind === 'image' + ? recentItems.find(item => currentImage && isEqual(item.image, currentImage)) + : chatBackgroundTypeItems.find(item => item.kind === backgroundKind), + }); + if (!backgroundType) { + return; + } + if (backgroundType.kind === 'none') { + await backgroundService.clearBackground('backgroundPicker'); + status(localize('chat.agentSessions.clearBackground.cleared', "Chat background cleared.")); + return; + } + if (backgroundType.kind === 'codicons' || backgroundType.kind === 'koi-light' || backgroundType.kind === 'koi-dark') { + await backgroundService.setBackground(backgroundType.kind, 'backgroundPicker'); + status(localize('chat.agentSessions.setBackground.preset', "Chat background set to {0}.", backgroundType.label)); + return; + } + if (backgroundType.kind === 'recentImage') { + await backgroundService.setBackground(backgroundType.image, 'backgroundPicker'); + status(localize('chat.agentSessions.setBackground.recentImage', "Chat background image set to {0}.", backgroundType.label)); + return; + } + if (backgroundType.kind === 'generate') { + const options: INewSessionInAgentsWindowOptions = { + // The trailing space is outside the localized text so translations can't drop it before the caret. + prompt: `${localize('chat.agentSessions.generateBackground.prompt', "Generate a chat background of")} `, + prefillPrompt: true, + noWorkspace: true, + }; + await commandService.executeCommand(NEW_SESSION_ACTION_ID, options); + return; + } + + const selected = await fileDialogService.showOpenDialog({ + title: localize('chat.agentSessions.setBackground.dialogTitle', "Set Chat Background"), + openLabel: localize('chat.agentSessions.setBackground.openLabel', "Set Background"), + canSelectFiles: true, + canSelectFolders: false, + canSelectMany: false, + filters: [{ + name: localize('chat.agentSessions.changeBackground.images', "Images"), + extensions: [...chatBackgroundImageExtensions], + }], + availableFileSystems: [Schemas.file], + defaultUri: configuredBackground?.kind === 'image' && !configuredBackground.preset ? currentImage : undefined, + }); + const image = selected?.[0]; + if (!image) { + return; + } + + await backgroundService.setBackground(image, 'backgroundPicker'); + status(localize('chat.agentSessions.setBackground.image', "Chat background image set.")); + } +} + +class ChangeChatBackgroundLayoutAction extends Action2 { + + constructor() { + super({ + id: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_COMMAND_ID, + title: localize2('chat.agentSessions.changeBackgroundLayout', "Change Background Layout..."), + category: CHAT_CATEGORY, + precondition: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, + menu: [{ + id: MenuId.CommandPalette, + when: CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, + }, { + id: Menus.SessionChatBackgroundContext, + group: 'navigation', + order: 2, + when: ContextKeyExpr.and(SessionsChatBackgroundAvailableContext, SessionsChatBackgroundImageConfiguredContext), + }, { + id: MenuId.ChatContext, + group: 'zz_background', + order: 2, + when: ContextKeyExpr.and(CHANGE_AGENT_SESSIONS_CHAT_BACKGROUND_LAYOUT_WHEN, ChatContextKeys.contextMenuIsBackground), + }], + }); + } + + override async run(accessor: ServicesAccessor): Promise { + const backgroundService = accessor.get(ISessionsChatBackgroundService); + const currentLayout = backgroundService.getBackgroundImageLayout(); + let selected: (typeof chatBackgroundImageLayoutItems)[number] | undefined; + try { + selected = await accessor.get(IQuickInputService).pick(chatBackgroundImageLayoutItems, { + title: localize('chat.agentSessions.changeBackgroundLayout.title', "Change Chat Background Layout"), + placeHolder: localize('chat.agentSessions.changeBackgroundLayout.placeholder', "Select how the background image is displayed"), + activeItem: chatBackgroundImageLayoutItems.find(item => item.layout === currentLayout), + onDidFocus: item => void backgroundService.setBackgroundImageLayout(item.layout, 'layoutPicker', false), + }); + } finally { + await backgroundService.setBackgroundImageLayout(selected?.layout ?? currentLayout, 'layoutPicker', selected !== undefined); + } + if (selected && selected.layout !== currentLayout) { + status(localize('chat.agentSessions.changeBackgroundLayout.changed', "Chat background layout changed to {0}.", selected.label)); + } + } +} + +registerAction2(SetChatBackgroundAction); +registerAction2(ChangeChatBackgroundLayoutAction); +registerAction2(ToggleChatBackgroundTintAction); +registerWorkbenchContribution2(SessionsChatBackgroundTint.ID, SessionsChatBackgroundTint, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(GetThemeColorsToolContribution.ID, GetThemeColorsToolContribution, WorkbenchPhase.Eventually); +registerSingleton(ISessionsChatBackgroundService, SessionsChatBackgroundService, InstantiationType.Delayed); + +Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ + properties: { + [AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING]: { + type: 'boolean', + default: false, + scope: ConfigurationScope.APPLICATION, + tags: ['advanced'], + experiment: { mode: 'auto' }, + markdownDescription: localize('chat.agentSessions.appearanceTools.enabled', "Enable the Get Theme Colors, Set Chat Background, and Screenshot Window tools and the built-in `generate-chat-background` skill in the Agents window. Disabling this does not remove existing backgrounds or affect the manual background controls."), + }, + [AGENT_SESSIONS_CHAT_BACKGROUND_IMAGE_TINT_SETTING]: { + type: 'boolean', + default: false, + scope: ConfigurationScope.APPLICATION, + description: localize('chat.agentSessions.backgroundImageTint', "Match the Agents window colors to your chat background image. Other windows keep their current theme. Not available in high contrast themes."), + tags: ['experimental'], + }, + [AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_SETTING]: { + type: 'string', + default: '', + scope: ConfigurationScope.MACHINE, + markdownDescription: localize('chat.agentSessions.preferredDarkBackgroundImage', "Specifies a built-in background (`codicons`, `koi-light`, or `koi-dark`), an absolute file path, or a `file` URI for the background displayed behind chat content in the Agents Window when using a dark color theme. The background is hidden in high contrast themes."), + examples: [...chatBackgroundPresets], + tags: ['experimental'], + ignoreSync: true, + }, + [AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_SETTING]: { + type: 'string', + default: '', + scope: ConfigurationScope.MACHINE, + markdownDescription: localize('chat.agentSessions.preferredLightBackgroundImage', "Specifies a built-in background (`codicons`, `koi-light`, or `koi-dark`), an absolute file path, or a `file` URI for the background displayed behind chat content in the Agents Window when using a light color theme. The background is hidden in high contrast themes."), + examples: [...chatBackgroundPresets], + tags: ['experimental'], + ignoreSync: true, + }, + [AGENT_SESSIONS_PREFERRED_DARK_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING]: { + type: 'string', + ...chatBackgroundImageLayoutEnumConfiguration, + default: 'repeat', + scope: ConfigurationScope.MACHINE, + markdownDescription: localize('chat.agentSessions.preferredDarkBackgroundImageLayout', "Controls how the chat background image is laid out in the Agents Window when using a dark color theme."), + tags: ['experimental'], + ignoreSync: true, + }, + [AGENT_SESSIONS_PREFERRED_LIGHT_CHAT_BACKGROUND_IMAGE_LAYOUT_SETTING]: { + type: 'string', + ...chatBackgroundImageLayoutEnumConfiguration, + default: 'repeat', + scope: ConfigurationScope.MACHINE, + markdownDescription: localize('chat.agentSessions.preferredLightBackgroundImageLayout', "Controls how the chat background image is laid out in the Agents Window when using a light color theme."), + tags: ['experimental'], + ignoreSync: true, + }, + }, +}); diff --git a/src/vs/sessions/contrib/chat/browser/chatLinkRouting.ts b/src/vs/sessions/contrib/chat/browser/chatLinkRouting.ts new file mode 100644 index 000000000000..7c16609b8288 --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/chatLinkRouting.ts @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { URI } from '../../../../base/common/uri.js'; +import { IAgentHostConnectionsService, isDefaultChatLinkId } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IChatWindow, IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { ISession } from '../../../../workbench/services/sessions/common/session.js'; +import { isChatWindowChatGone } from '../../chatWindow/browser/chatWindowOpening.js'; +import { CHAT_WINDOWS_ENABLED_SETTING } from '../../chatWindow/common/chatWindows.js'; + +/** The chat window a link was activated in, and the chat of it the user activated it in. */ +export interface IChatWindowLinkSource { + readonly window: IChatWindow; + readonly chat: URI; +} + +/** + * The link source of the chat window a link was activated in, while chat windows are on. The window's active chat is the + * one the link was activated in: read it as the link is activated, as it can change while the link resolves. + */ +export function getChatWindowLinkSource(window: IChatWindow | undefined, configurationService: IConfigurationService): IChatWindowLinkSource | undefined { + if (!window || !configurationService.getValue(CHAT_WINDOWS_ENABLED_SETTING)) { + return undefined; + } + return { window, chat: window.chat.get() }; +} + +/** + * The chat a link names in `session`: the chat of its chat id, or the main chat without one, or when the id names the + * session's advertised default chat, as an opaque id or the chat's resource. + */ +export async function resolveLinkedChat(connectionsService: IAgentHostConnectionsService, session: ISession, chatId: string | undefined): Promise { + if (chatId) { + const resolution = connectionsService.resolveSessionResource(session.resource); + if (!resolution || !await isDefaultChatLinkId(resolution.connection, resolution.backendSession, chatId)) { + return session.resource.with({ fragment: chatId }); + } + } + return session.mainChat.get().resource; +} + +/** + * Opens a chat of a link in the chat window the link was activated in, as a tab of the chat it was activated in, or beside + * it when opened to the side. A chat that another chat window shows is revealed there, and one the main window's grid shows + * moves into this window. Returns false, for the main window to open it, when the chat window would end the chat, as it + * does an archived or gone one, or cannot resolve it, as it cannot a chat of a session that still loads. + */ +export async function openLinkedChatInChatWindow(chatWindowService: IChatWindowService, source: IChatWindowLinkSource, session: ISession, chatResource: URI, openToSide: boolean): Promise { + if (isChatWindowChatGone(session, chatResource, undefined)) { + return false; + } + return !!await chatWindowService.open(chatResource, { window: source.window, exactChat: true, ...(openToSide ? { beside: source.chat } : { tabOf: source.chat }) }); +} diff --git a/src/vs/sessions/contrib/chat/browser/media/runScriptAction.css b/src/vs/sessions/contrib/chat/browser/media/runScriptAction.css index c9f94af8a89b..519ef28f3ddb 100644 --- a/src/vs/sessions/contrib/chat/browser/media/runScriptAction.css +++ b/src/vs/sessions/contrib/chat/browser/media/runScriptAction.css @@ -45,7 +45,7 @@ gap: 2px; padding: 2px; border: 1px solid var(--vscode-widget-border, rgba(255, 255, 255, 0.06)); - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-controls-corner-radius, var(--vscode-cornerRadius-medium)); background-color: var(--vscode-input-background); } @@ -54,7 +54,7 @@ min-width: 76px; padding: 4px 8px; border: var(--vscode-strokeThickness) solid transparent; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-controls-corner-radius, var(--vscode-cornerRadius-small)); background: transparent; color: var(--vscode-foreground); font-size: var(--vscode-fontSize-label1); @@ -66,7 +66,7 @@ .run-script-action-section .monaco-custom-radio > .monaco-button:first-child, .run-script-action-section .monaco-custom-radio > .monaco-button:last-child { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-controls-corner-radius, var(--vscode-cornerRadius-small)); } .run-script-action-section .monaco-custom-radio > .monaco-button:not(.active):not(:last-child), @@ -136,7 +136,7 @@ width: fit-content; min-height: 28px; padding: 6px 12px; - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-medium)); } .agent-sessions-workbench.run-script-action-modal-visible .quick-input-widget .quick-input-titlebar { diff --git a/src/vs/sessions/contrib/chat/browser/media/sessionLinkAttachment.css b/src/vs/sessions/contrib/chat/browser/media/sessionLinkAttachment.css new file mode 100644 index 000000000000..2850b46cdcdd --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/media/sessionLinkAttachment.css @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* The status icon of the linked session, in the box that the icons of other pills take. */ +.interactive-session .chat-attached-context .chat-session-link-attachment .chat-session-link-attachment-icon { + display: inline-flex; + align-items: center; + justify-content: center; + align-self: center; + flex-shrink: 0; + width: 16px; + height: 16px; + margin-right: var(--vscode-spacing-size40); +} + +.interactive-session .chat-attached-context .chat-session-link-attachment .chat-session-link-attachment-icon:first-child { + margin-left: var(--vscode-spacing-size40); +} + +/* The status glyphs keep their base size, as in the sessions list, rather than scaling base glyphs that have compact variants. */ +.interactive-session .chat-attached-context .chat-session-link-attachment .chat-session-link-attachment-icon > .codicon { + font-size: var(--vscode-codiconFontSize, 16px); +} diff --git a/src/vs/sessions/contrib/chat/browser/openSessionLinkOpener.contribution.ts b/src/vs/sessions/contrib/chat/browser/openSessionLinkOpener.contribution.ts index 66e7792d4c55..f55380d7ce69 100644 --- a/src/vs/sessions/contrib/chat/browser/openSessionLinkOpener.contribution.ts +++ b/src/vs/sessions/contrib/chat/browser/openSessionLinkOpener.contribution.ts @@ -10,28 +10,21 @@ import { derivedOpts, IObservable, IReader, observableSignalFromEvent } from '.. import { isEqual } from '../../../../base/common/resources.js'; import { URI } from '../../../../base/common/uri.js'; import { localize } from '../../../../nls.js'; -import { IAgentHostConnectionsService, isDefaultChatLinkId } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IAgentHostConnectionsService } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { AGENT_HOST_CHAT_LINK_PATTERN, AGENT_HOST_SESSION_ONLY_LINK_PATTERN, AgentSessionLinkStatus, buildAgentSessionLinkPresentation, parseOpenSessionLinkChatId, parseOpenSessionLinkConnectionAuthority, parseOpenSessionLinkUri } from '../../../../platform/agentHost/common/openSessionLink.js'; import { ILinkPresentation, ILinkPresentationService, ILinkPresentationWatcher } from '../../../../platform/dataChannel/common/dataChannel.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { ILabelService } from '../../../../platform/label/common/label.js'; import { IOpenerService, OpenOptions } from '../../../../platform/opener/common/opener.js'; import { IWorkbenchContribution } from '../../../../workbench/common/contributions.js'; -import { IChatWindow, IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { ISessionSummaryHoverService } from '../../../../workbench/contrib/chat/browser/agentSessions/sessionSummaryHoverService.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ISession, SessionStatus } from '../../../../workbench/services/sessions/common/session.js'; import { ISessionsProvidersService } from '../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; -import { isChatWindowChatGone } from '../../chatWindow/browser/chatWindowOpening.js'; -import { CHAT_WINDOWS_ENABLED_SETTING } from '../../chatWindow/common/chatWindows.js'; import { getSessionSummaryHoverData } from '../../../../workbench/contrib/sessions/browser/sessionHoverContent.js'; - -/** The chat window a link was activated in, and the chat of it the user activated it in. */ -interface ILinkSource { - readonly window: IChatWindow; - readonly chat: URI; -} +import { getChatWindowLinkSource, IChatWindowLinkSource, openLinkedChatInChatWindow, resolveLinkedChat } from './chatLinkRouting.js'; /** * Handles `agent-host-session://` links (surfaced by the `create_session` / @@ -96,41 +89,28 @@ export class OpenSessionLinkOpenerContribution extends Disposable implements IWo : undefined; } - /** Whether `chatId` addresses the session's advertised default chat, which is the main chat. */ - private async _isDefaultChatId(session: ISession, chatId: string): Promise { - const resolution = this._connectionsService.resolveSessionResource(session.resource); - return !!resolution && await isDefaultChatLinkId(resolution.connection, resolution.backendSession, chatId); - } - /** * The chat window the user activated the link in, if one. Only a user gesture redirects: a link a tool, an extension * or a command opens keeps opening in the main window, whichever window has focus. So does any link while chat windows * are off. The window's active chat is the clicked one: activating a group of the window makes its chat the active one. */ - private _getSource(options: OpenOptions): ILinkSource | undefined { - if (!options.fromUserGesture || !this._configurationService.getValue(CHAT_WINDOWS_ENABLED_SETTING)) { + private _getSource(options: OpenOptions): IChatWindowLinkSource | undefined { + if (!options.fromUserGesture) { return undefined; } // A page such as a canvas has focus outside the workbench, so it names its window. - const window = this._chatWindowService.getWindow(options.sourceWindowId ?? getWindowId(getActiveWindow())); - // Read now, as the active chat can change while the link resolves - return window && { window, chat: window.chat.get() }; + return getChatWindowLinkSource(this._chatWindowService.getWindow(options.sourceWindowId ?? getWindowId(getActiveWindow())), this._configurationService); } - private async _open(resource: URI | string, openToSide: boolean, source: ILinkSource | undefined): Promise { + private async _open(resource: URI | string, openToSide: boolean, source: IChatWindowLinkSource | undefined): Promise { const session = this._findSessionForLink(resource); if (!session) { return false; } // An absent chat id means the session's main/default chat, not "no target chat" (see buildOpenSessionLinkUri). const chatId = parseOpenSessionLinkChatId(resource); - const chatResource = chatId && !await this._isDefaultChatId(session, chatId) ? session.resource.with({ fragment: chatId }) : session.mainChat.get().resource; - // A chat window ends a chat that is archived or gone, so the main window opens it as it does for a click there. - // Shown in another chat window, it is revealed there; in the main window's grid, it moves into this one. - // The chat window cannot resolve a chat of a session that still loads: the main window path waits for it. - const openedInWindow = source && !isChatWindowChatGone(session, chatResource, undefined) - && await this._chatWindowService.open(chatResource, { window: source.window, exactChat: true, ...(openToSide ? { beside: source.chat } : { tabOf: source.chat }) }); - if (openedInWindow) { + const chatResource = await resolveLinkedChat(this._connectionsService, session, chatId); + if (source && await openLinkedChatInChatWindow(this._chatWindowService, source, session, chatResource, openToSide)) { return true; } if (openToSide) { diff --git a/src/vs/sessions/contrib/chat/browser/promptsService.ts b/src/vs/sessions/contrib/chat/browser/promptsService.ts index 652ef1f79cd9..2a739b789c05 100644 --- a/src/vs/sessions/contrib/chat/browser/promptsService.ts +++ b/src/vs/sessions/contrib/chat/browser/promptsService.ts @@ -13,6 +13,7 @@ import { IAgentSkill, IBuiltinPromptPath, PromptsStorage } from '../../../../wor import { PromptsService } from '../../../../workbench/contrib/chat/common/promptSyntax/service/promptsServiceImpl.js'; import { AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; import { CHAT_AUTOMATIONS_ENABLED_SETTING } from '../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; +import { ChatConfiguration } from '../../../../workbench/contrib/chat/common/constants.js'; import { ChatAIDisabledSettingId } from '../../../../platform/chat/common/chatSettings.js'; /** URI root for built-in skills bundled with the Agents app. */ @@ -87,6 +88,10 @@ export class AgenticPromptsService extends PromptsService { private async getBuiltinSkillPaths(): Promise { const skills = await this.getBuiltinSkills(); return skills.filter(s => { + if (s.name === 'html-preview') { + return this.configurationService.getValue(ChatConfiguration.HtmlPreviewEnabled) === true + && !this.configurationService.getValue(ChatAIDisabledSettingId); + } if (s.name === 'automate') { return this.configurationService.getValue(CHAT_AUTOMATIONS_ENABLED_SETTING) === true && !this.configurationService.getValue(ChatAIDisabledSettingId); @@ -119,6 +124,7 @@ export class AgenticPromptsService extends PromptsService { protected override get onDidChangeBuiltinPromptFiles(): Event { return Event.map(Event.filter(this.configurationService.onDidChangeConfiguration, event => event.affectsConfiguration(AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING) + || event.affectsConfiguration(ChatConfiguration.HtmlPreviewEnabled) || event.affectsConfiguration(CHAT_AUTOMATIONS_ENABLED_SETTING) || event.affectsConfiguration(ChatAIDisabledSettingId)), () => PromptsType.skill); } diff --git a/src/vs/sessions/contrib/chat/browser/sessionLinkAttachmentWidget.ts b/src/vs/sessions/contrib/chat/browser/sessionLinkAttachmentWidget.ts new file mode 100644 index 000000000000..97faee22aae3 --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/sessionLinkAttachmentWidget.ts @@ -0,0 +1,274 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/sessionLinkAttachment.css'; +import * as dom from '../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js'; +import { StandardMouseEvent } from '../../../../base/browser/mouseEvent.js'; +import { Button } from '../../../../base/browser/ui/button/button.js'; +import { HoverStyle } from '../../../../base/browser/ui/hover/hover.js'; +import { createInstantHoverDelegate } from '../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { HoverPosition } from '../../../../base/browser/ui/hover/hoverWidget.js'; +import { Separator, toAction } from '../../../../base/common/actions.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { KeyCode } from '../../../../base/common/keyCodes.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { autorun, derived, IReader, observableSignalFromEvent } from '../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { URI } from '../../../../base/common/uri.js'; +import { localize } from '../../../../nls.js'; +import { IAgentHostConnectionsService } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { buildExternalOpenSessionLinkUri, parseOpenSessionLinkChatId, parseOpenSessionLinkConnectionAuthority, parseOpenSessionLinkTurnId, parseOpenSessionLinkUri } from '../../../../platform/agentHost/common/openSessionLink.js'; +import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; +import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IOpenerService } from '../../../../platform/opener/common/opener.js'; +import { IProductService } from '../../../../platform/product/common/productService.js'; +import { IWorkbenchContribution } from '../../../../workbench/common/contributions.js'; +import { IChatAttachmentWidgetInstance, IChatAttachmentWidgetRegistry } from '../../../../workbench/contrib/chat/browser/attachments/chatAttachmentWidgetRegistry.js'; +import { IChatRequestSessionLinkVariableEntry, isSessionLinkVariableEntry } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; +import { getChatCompletedStateIcon, getSessionAgentMergeConfigurationObservable, getSessionCompletedStateIcon } from '../../../../workbench/contrib/sessions/browser/sessionAgentMerge.js'; +import { getSessionConversationStatusLabel } from '../../../../workbench/contrib/sessions/browser/sessionConversationGroups.js'; +import { ISessionsProvidersService } from '../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { SessionStatusIcon } from '../../../../workbench/contrib/sessions/browser/sessionStatusIcon.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { getUntitledSessionTitle, ISession, SessionStatus } from '../../../../workbench/services/sessions/common/session.js'; +import { findSessionForOpenSessionLink } from './openSessionLinkOpener.contribution.js'; + +/** What the pill of a session link shows of the session or chat that it links to. */ +interface ISessionLinkState { + /** The session or chat whose status the pill shows. */ + readonly resource: URI; + readonly title: string; + readonly status: SessionStatus; + readonly isRead: boolean; + readonly isArchived: boolean; + readonly completedStateIcon: ThemeIcon | undefined; +} + +/** + * The pill of a link to an agent session in the chat input, see + * {@link IChatRequestSessionLinkVariableEntry}. It shows the title of the + * session, or of the chat that the link opens, with the status icon that the + * sessions list shows beside it, and opens it when activated. Its context menu + * copies the link. + */ +export class SessionLinkAttachmentWidget extends Disposable implements IChatAttachmentWidgetInstance { + + readonly element: HTMLElement; + + private readonly _onDidDelete = this._register(new Emitter()); + readonly onDidDelete = this._onDidDelete.event; + + private readonly _onDidOpen = this._register(new Emitter()); + readonly onDidOpen = this._onDidOpen.event; + + private readonly _chatId: string | undefined; + private _displayName: string; + private _tooltip = ''; + + /** The title of the linked session or chat, which changes along with it. */ + get displayName(): string { + return this._displayName; + } + + constructor( + private readonly _attachment: IChatRequestSessionLinkVariableEntry, + options: { shouldFocusClearButton: boolean; supportsDeletion: boolean }, + container: HTMLElement, + @IInstantiationService instantiationService: IInstantiationService, + @ISessionsManagementService sessionsManagementService: ISessionsManagementService, + @IAgentHostConnectionsService connectionsService: IAgentHostConnectionsService, + @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IOpenerService private readonly _openerService: IOpenerService, + @IContextMenuService private readonly _contextMenuService: IContextMenuService, + @IClipboardService private readonly _clipboardService: IClipboardService, + @IProductService private readonly _productService: IProductService, + @IHoverService hoverService: IHoverService, + ) { + super(); + + const link = this._attachment.value; + const backendSession = parseOpenSessionLinkUri(link); + const connectionAuthority = parseOpenSessionLinkConnectionAuthority(link); + this._chatId = parseOpenSessionLinkChatId(link); + // What the pill is called while this window does not know the session that the link opens. + const unknownName = this._chatId ? localize('sessionLinkAttachment.unknownChat', "Chat") : this._attachment.name; + this._displayName = unknownName; + + this.element = dom.append(container, dom.$('.chat-attached-context-attachment.chat-session-link-attachment')); + this.element.tabIndex = 0; + this.element.role = 'button'; + this.element.style.cursor = 'pointer'; + if (options.supportsDeletion) { + this._addRemoveHandlers(options.shouldFocusClearButton); + } + const iconContainer = dom.append(this.element, dom.$('span.chat-session-link-attachment-icon')); + iconContainer.ariaHidden = 'true'; + const label = dom.append(this.element, dom.$('span.chat-attached-context-custom-text')); + const statusIcon = this._register(instantiationService.createInstance(SessionStatusIcon, iconContainer)); + + const sessionsChanged = observableSignalFromEvent(this, sessionsManagementService.onDidChangeSessions); + const session = derived(this, reader => { + sessionsChanged.read(reader); + return backendSession ? findSessionForOpenSessionLink(backendSession, sessionsManagementService, connectionsService, connectionAuthority) : undefined; + }); + this._register(autorun(reader => { + const current = session.read(reader); + const state = current && this._readState(current, reader); + this._displayName = state?.title ?? unknownName; + label.textContent = this._displayName; + if (state) { + statusIcon.setStatus(state.status, state.isRead, state.isArchived, state.completedStateIcon, state.resource); + const statusLabel = getSessionConversationStatusLabel(state.status); + this._tooltip = localize('sessionLinkAttachment.tooltip', "{0} · {1}", state.title, statusLabel); + this.element.ariaLabel = this._chatId + ? localize('sessionLinkAttachment.chatAriaLabel', "Link to chat {0}, {1}", state.title, statusLabel) + : localize('sessionLinkAttachment.sessionAriaLabel', "Link to session {0}, {1}", state.title, statusLabel); + } else { + // The session is not one that this window knows, or not yet. + statusIcon.reset(); + dom.append(iconContainer, dom.$(ThemeIcon.asCSSSelector(this._chatId ? Codicon.commentDiscussion : Codicon.agent))); + this._tooltip = unknownName; + this.element.ariaLabel = this._chatId + ? localize('sessionLinkAttachment.unknownChatAriaLabel', "Link to chat") + : localize('sessionLinkAttachment.unknownSessionAriaLabel', "Link to session"); + } + })); + + this._register(hoverService.setupDelayedHover(this.element, () => ({ + content: this._tooltip, + style: HoverStyle.Pointer, + position: { hoverPosition: HoverPosition.BELOW }, + }), { groupId: 'chat-attachments' })); + + this._register(dom.addDisposableListener(this.element, dom.EventType.CLICK, e => { + if (dom.isHTMLElement(e.target) && e.target.closest('.monaco-button')) { + return; + } + dom.EventHelper.stop(e, true); + void this._open(); + })); + this._register(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, e => { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { + dom.EventHelper.stop(e, true); + void this._open(); + } + })); + this._register(dom.addDisposableListener(this.element, dom.EventType.CONTEXT_MENU, e => { + dom.EventHelper.stop(e, true); + this._showContextMenu(new StandardMouseEvent(dom.getWindow(this.element), e)); + })); + } + + /** The state of the chat that the link opens, as the sessions list shows it beside the chat, or else of the session. */ + private _readState(session: ISession, reader: IReader): ISessionLinkState { + const chat = this._chatId ? session.chats.read(reader).find(candidate => candidate.resource.fragment === this._chatId) : undefined; + // The Agent Merge configuration is cached per session and chat. + const agentMergeConfiguration = () => getSessionAgentMergeConfigurationObservable(session, this._sessionsProvidersService, this._configurationService, chat); + if (chat) { + return { + resource: chat.resource, + title: chat.title.read(reader) || localize('sessionLinkAttachment.untitledChat', "Untitled Chat"), + status: chat.status.read(reader), + isRead: chat.isRead.read(reader), + isArchived: chat.isArchived.read(reader), + completedStateIcon: getChatCompletedStateIcon(session, chat, reader, agentMergeConfiguration), + }; + } + return { + resource: session.resource, + title: session.title.read(reader) || getUntitledSessionTitle(session.isQuickChat?.read(reader) ?? false), + status: session.status.read(reader), + // As the sessions list reads a session's row, whose peer chats are read in their own rows. + isRead: session.mainChat.read(reader).isRead.read(reader), + isArchived: session.isArchived.read(reader), + completedStateIcon: getSessionCompletedStateIcon(session, reader, agentMergeConfiguration), + }; + } + + /** Removes the pill as the other attachment pills do: with its clear button, Delete or Backspace, or a middle click. */ + private _addRemoveHandlers(shouldFocusClearButton: boolean): void { + const hoverDelegate = this._register(createInstantHoverDelegate()); + const clearButton = this._register(new Button(this.element, { + supportIcons: true, + hoverDelegate, + title: localize('sessionLinkAttachment.remove', "Remove"), + })); + clearButton.element.tabIndex = -1; + clearButton.icon = Codicon.closeCompact; + this._register(clearButton.onDidClick(e => this._onDidDelete.fire(e))); + this._register(dom.addStandardDisposableListener(this.element, dom.EventType.KEY_DOWN, e => { + if (e.keyCode === KeyCode.Backspace || e.keyCode === KeyCode.Delete) { + dom.EventHelper.stop(e, true); + this._onDidDelete.fire(e.browserEvent); + } + })); + this._register(dom.addDisposableListener(this.element, dom.EventType.AUXCLICK, (e: MouseEvent) => { + if (e.button === 1 /* Middle Button */) { + dom.EventHelper.stop(e, true); + this._onDidDelete.fire(e); + } + })); + if (shouldFocusClearButton) { + clearButton.focus(); + } + } + + private async _open(): Promise { + await this._openerService.open(this._attachment.value, { fromUserGesture: true }); + this._onDidOpen.fire(); + } + + private _showContextMenu(anchor: StandardMouseEvent): void { + const open = toAction({ + id: 'chat.sessionLinkAttachment.open', + label: this._chatId ? localize('sessionLinkAttachment.openChat', "Open Chat") : localize('sessionLinkAttachment.openSession', "Open Session"), + run: () => this._open(), + }); + const copyLink = toAction({ + id: 'chat.sessionLinkAttachment.copyLink', + label: localize('sessionLinkAttachment.copyLink', "Copy Link"), + run: () => this._clipboardService.writeText(this._getShareableLink()), + }); + this._contextMenuService.showContextMenu({ + getAnchor: () => anchor, + getActions: () => Separator.join([open], [copyLink]), + }); + } + + /** The link that the sessions list copies for the session, which opens it from outside the window too. */ + private _getShareableLink(): string { + const link = this._attachment.value; + const backendSession = parseOpenSessionLinkUri(link); + return backendSession + ? buildExternalOpenSessionLinkUri(this._productService.urlProtocol, backendSession, this._chatId, parseOpenSessionLinkTurnId(link), parseOpenSessionLinkConnectionAuthority(link)) + : link.toString(); + } +} + +/** Shows the links to agent sessions in a chat input as {@link SessionLinkAttachmentWidget} pills. */ +export class SessionLinkAttachmentWidgetContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.sessionLinkAttachmentWidget'; + + constructor( + @IChatAttachmentWidgetRegistry registry: IChatAttachmentWidgetRegistry, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + this._register(registry.registerFactory('sessionLink', (attachment, options, container) => { + if (!isSessionLinkVariableEntry(attachment)) { + throw new Error('Expected a session link attachment'); + } + return instantiationService.createInstance(SessionLinkAttachmentWidget, attachment, options, container); + })); + } +} diff --git a/src/vs/sessions/contrib/chat/browser/sessionTurnChanges.ts b/src/vs/sessions/contrib/chat/browser/sessionTurnChanges.ts index 94af4ebb1f26..7bb6399eb7d3 100644 --- a/src/vs/sessions/contrib/chat/browser/sessionTurnChanges.ts +++ b/src/vs/sessions/contrib/chat/browser/sessionTurnChanges.ts @@ -13,10 +13,13 @@ import { IEditorService } from '../../../../workbench/services/editor/common/edi import { ISessionsHostLayoutService } from '../../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; import { isAgentHostProviderId } from '../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; -import { getWindowHost, IFocusedSessionHostService, ISessionHostService, SessionHostKind } from '../../../../workbench/services/sessions/browser/sessionHost.js'; +import { IFocusedSessionHostService, ISessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; import { IChat, ISession, ISessionChangeset, ISessionFileChange, TURN_CHANGES_CHANGESET_ID } from '../../../../workbench/services/sessions/common/session.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ISessionChangesEditorOptions, ISessionChangesService } from '../../../../workbench/contrib/sessionChanges/browser/sessionChangesService.js'; +import { getEditorTarget, revealEditorTarget } from '../../../../workbench/contrib/sessions/browser/chatWindowEditorTarget.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { IChangesViewService } from '../../../../workbench/contrib/sessions/common/changesViewService.js'; interface ISessionTransientTurnChanges { @@ -41,6 +44,8 @@ export class SessionsChatResponseFileChangesService extends AbstractChatResponse @ISessionsHostLayoutService private readonly _layoutService: ISessionsHostLayoutService, @IChangesViewService private readonly _changesViewService: IChangesViewService, @ISessionHostService private readonly _sessionHostService: ISessionHostService, + @IChatWindowService private readonly _chatWindowService: IChatWindowService, + @ILogService private readonly _logService: ILogService, ) { super(); } @@ -194,13 +199,23 @@ export class SessionsChatResponseFileChangesService extends AbstractChatResponse } private async _openSessionTurnChanges(session: ISession, chat: IChat, transientTurn?: ISessionTransientTurnChanges): Promise { + const chatHost = this._sessionHostService.getHostOfChat(chat.resource); + const target = getEditorTarget(this._chatWindowService, chatHost); + if (!target) { + this._logService.trace('[SessionsChatResponseFileChangesService] The chat window of the chat is not available, not opening its changes'); + return; + } + // A chat a chat window shows is already shown there; the main window, which may be the focused host, stays as it is. + const inChatWindow = target !== 'main'; const activeSession = this._focusedSessionHostService.focusedHost.get().session.get(); - if (!transientTurn && (!activeSession || !isEqual(activeSession.resource, session.resource) || !isEqual(this._focusedSessionHostService.focusedHost.get().chat.get()?.resource, chat.resource))) { + if (inChatWindow) { + // Nothing to activate. + } else if (!transientTurn && (!activeSession || !isEqual(activeSession.resource, session.resource) || !isEqual(this._focusedSessionHostService.focusedHost.get().chat.get()?.resource, chat.resource))) { await this._sessionsService.openChat(session, chat.resource, { preserveFocus: true }); } else if (!isEqual(activeSession?.resource, session.resource)) { this._sessionsService.showSession(session.resource, { preserveFocus: true }); } - this._layoutService.revealEditorPartExplicitly(); + revealEditorTarget(this._layoutService, target); const changesetSelection: ISessionChangesEditorOptions['changesetSelection'] = transientTurn ? { kind: 'transient', @@ -221,10 +236,9 @@ export class SessionsChatResponseFileChangesService extends AbstractChatResponse } satisfies ISessionChangeset, } : { kind: 'id', id: TURN_CHANGES_CHANGESET_ID }; - const chatHost = this._sessionHostService.getHostOfChat(chat.resource); await this._sessionChangesService.openChangesEditor(session.resource, { changesetSelection, - chatResource: chatHost && getWindowHost(chatHost).kind === SessionHostKind.ChatWindow ? chat.resource : undefined, - }); + chatResource: inChatWindow ? chat.resource : undefined, + }, inChatWindow ? target.mainPart.activeGroup : undefined); } } diff --git a/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts b/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts index 36d4879a41bf..616a1c39ce86 100644 --- a/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts +++ b/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts @@ -48,16 +48,20 @@ import { RemoteAgentHostAutoConnectSettingId, RemoteAgentHostsEnabledSettingId } import { IChatEntitlementService } from '../../../../workbench/services/chat/common/chatEntitlementService.js'; import { areDevContainerSamplesEnabled } from '../../../../workbench/contrib/sessions/common/devContainerAgentHostService.js'; import { CustomizationMarketplaceConfiguration } from '../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; +import { KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED } from '../../../../workbench/contrib/webview/browser/webview.js'; +import { ChatConfiguration } from '../../../../workbench/contrib/chat/common/constants.js'; import { readPaneSessions } from '../../../../workbench/services/sessions/browser/sessionGridPane.js'; export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementation { readonly priority = 120; readonly name = 'sessionsChat'; readonly type = AccessibleViewType.Help; - // A custom view replaces the chat surface this help describes, and the storage cleanup editor - // provides its own help, so this window-wide help does not apply in either case. - readonly when = ContextKeyExpr.and(IsSessionsWindowContext, CustomViewVisibleContext.negate(), SessionWorktreeCleanupEditorFocusedContext.negate()); + // Leave surfaces with their own help to their providers instead of this window-wide fallback. + readonly when = ContextKeyExpr.and(IsSessionsWindowContext, CustomViewVisibleContext.negate(), SessionWorktreeCleanupEditorFocusedContext.negate(), KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED.toNegated()); - constructor(private readonly _responseSelectionSupported = isResponseSelectionSupported()) { } + constructor( + private readonly _responseSelectionSupported = isResponseSelectionSupported(), + private readonly _supportsChatBackgrounds = true, + ) { } getProvider(accessor: ServicesAccessor) { const restoreFocus = createSessionsChatFocusRestorer(accessor); @@ -68,6 +72,12 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.overview', "You are in the Agents window. The Agents window is a dedicated workspace for working with AI agents. It provides a chat interface, a changes view for reviewing agent-generated changes, a file explorer, and customization options.")); content.push(getChatInputSessionLinkAccessibilityHelp()); if (!accessor.get(IChatEntitlementService).sentiment.hidden && configurationService.getValue('chat.disableAIFeatures') !== true) { + if (configurationService.getValue(ChatConfiguration.HtmlPreviewEnabled)) { + content.push(localize('sessionsChat.htmlPreview', "The {1} setting enables HTML previews in responses marked with an html-preview code fence. Previews display HTML and CSS without scripts, forms, external links, or external resources. Links to sections within the preview are supported. Inline previews grow to fit their content and scroll with the chat transcript. Previews have no title bar or permanent buttons. Use Tab to focus the HTML preview and press Shift+F10, or right-click it, to open its context menu. Choose Show Source to toggle the original HTML source; the menu item is checked while source is shown. The same menu offers Open Preview and Save HTML. Open Preview opens a larger editor with Find, Accessibility Help, and an Accessible View of the document text. Save HTML asks where to save a sanitized, self-contained HTML file and opens it using the existing file preview behavior. The saved file excludes scripts and unsupported controls; Show Source retains the original HTML. Find in Chat searches the original HTML and shows source when a match is selected, without moving focus out of Find. The original source is also available in the chat Accessible View{0}.", '', ChatConfiguration.HtmlPreviewEnabled)); + content.push(localize('sessionsChat.htmlPreviewSkill', "For visual reports, comparisons, diagrams, and static mockups, use the built-in /html-preview skill when it is enabled for your agent. Its authoring guidance follows the current VS Code theme and the preview's supported content.")); + } else { + content.push(localize('sessionsChat.htmlPreviewDisabled', "Inline HTML previews are disabled by {0}. Responses marked with an html-preview code fence are shown as source code. Enable this setting to render previews.", ChatConfiguration.HtmlPreviewEnabled)); + } content.push(localize('sessionsChat.remoteConnections.renameHelp', "In the Remote Connections menu, press Tab to reach the name link in the footer, then Enter or Space to rename the shared environment. The input starts with the current name. Enter saves the name shown on other clients, and Escape cancels. Shift+Tab returns to the connection options. Renaming while Off does not enable sharing.")); content.push(localize('sessionsChat.remoteConnections.policyHelp', "If GitHub Environments is disabled by your organization, the footer explains the restriction. Press Tab to reach View Setting and Enter to open the managed setting. Shift+Tab returns to the connection options.")); content.push(localize('sessionsChat.remoteConnections', "On desktop, the title bar offers Remote Connections. The preview setting chat.agentHost.remoteConnections selects the connection method. The Remote Connections button opens a menu that offers Off, Dev Tunnels, and GitHub Environments when available. Use Tab to reach the title bar, arrow keys to reach the button, Enter or Space to open it, Up and Down Arrow to choose an option, Enter to select, and Escape to close and return focus to the button. Selecting a method updates the setting and enables sharing. Selecting Off disables sharing without changing the preferred method. The footer shows the name used to identify this machine on other clients and whether it is shared or connecting. Changing the setting directly turns sharing off. The setting chat.agentHost.githubEnvironments.enabled controls GitHub Environments availability. If your organization disables it, the menu explains that you must contact your administrator. With GitHub environment selected, enabling sharing registers your local environment for remote owner access and allows clients authenticated as your GitHub account to read and modify files across this machine's accessible file systems, including sensitive files. Remote work uses the host's OAuth token by default, controlled by chat.agentHost.experimentalMissionControl.useLocalCredentials. Operating system permissions still apply. Local sessions continue using local IPC.")); @@ -100,8 +110,6 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat if (this._responseSelectionSupported) { if (configurationService.getValue(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING)) { content.push(localize('sessionsChat.responseSelectionMenu', "When you select assistant response text, an action menu appears. Press Tab to focus the menu, use the Up Arrow and Down Arrow keys to move between actions, and press Enter to activate one. Press Escape to dismiss the menu. Ask in a Side Chat opens a question input anchored to the selected text. Quote appends the selection as a blockquote in the chat input when the conversation is interactive. Copy copies the selected text.")); - } else { - content.push(localize('sessionsChat.responseSelectionInput', "When you select assistant response text, an Ask Question input appears. Type a side question and press Enter to send it, press Shift+Enter to insert a new line, or press Escape to dismiss the input.")); } } content.push(getModePickerAccessibilityHelp()); @@ -131,7 +139,7 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.clearWorkspace', "When the current environment and harness support chatting without a workspace, hover over or focus the workspace picker to reveal Chat without a workspace. Use Tab or the Left and Right arrow keys to reach this button, then Enter or Space to switch to Chat without discarding your prompt. You can send without choosing a workspace. Focus returns to the workspace picker so you can choose a workspace later. Chat remains available in the workspace list.")); } content.push(useAgentPickerInAttachContextMenu - ? localize('sessionsChat.newSessionInputControls.agentInAttachContext', "When an Agent picker is available in a new or running session, it appears in Add Context when the default agent is selected. Open Add Context and choose Agent to select an agent. While a custom agent is selected, the Agent picker appears in its usual position. Selecting the default agent moves it back into Add Context. Other new-session controls remain in their layout-specific positions. Use Tab to reach toolbar controls, arrow keys to navigate toolbar items, and Enter or Space to open a picker.") + ? localize('sessionsChat.newSessionInputControls.agentInAttachContext', "When an Agent picker is available in a new or running session, it appears in Add Context when the default agent is selected. Open Add Context and choose Agent to select an agent. A one-time spotlight may explain this change. Activate Understood or press Escape to dismiss it, or activate the highlighted Add Context action to open the menu and dismiss the tip. While a custom agent is selected, the Agent picker appears in its usual position. Selecting the default agent moves it back into Add Context. Other new-session controls remain in their layout-specific positions. Use Tab to reach toolbar controls, arrow keys to navigate toolbar items, and Enter or Space to open a picker.") : localize('sessionsChat.newSessionInputControls.experimental', "Inside the new-session prompt, the controls appear in this order: Add Context, Agent, Mode and Permissions, and Model. Which controls are available depends on the selected harness. Use Tab to reach the controls, arrow keys to navigate toolbar items, and Enter or Space to open a picker.")); content.push(localize('sessionsChat.compactSessionPickers', "When space is limited, the new-session pickers show icons instead of labels without moving to another row. The workspace name remains visible. Icon-only pickers retain their accessible names and tooltips; activate them to view and change the current selection.")); if (isMacintosh && !isWeb) { @@ -142,7 +150,7 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.terminalConfirmationExplain', "When a terminal command needs approval and the agent describes what it is for, the confirmation title includes that description, such as Run in terminal: followed by the description. In a conversation that supports side chats, use Tab to reach Explain and press Enter or Space to open a fresh side chat that explains only the terminal command, without the prior conversation as context. The confirmation stays pending until you allow or skip it.")); content.push(localize('sessionsChat.backgroundActivityProgressDropdown', "Running-subagent and background-command statuses at the bottom of a response open dropdowns showing only in-progress work, including subagents waiting for input. Finished subagents and background work disappear from these dropdowns as they complete, regardless of the input pills' Show All setting. When both kinds are running, one combined status opens a Background Activity dropdown containing both groups. The separate pills above the input keep their existing filters. Use Tab to focus the status and Enter or Space to open it, then the Up and Down arrow keys to choose an entry and Enter to open a subagent or the shell's live command details. Escape closes the dropdown and returns focus to the status. If the focused status disappears when work finishes, focus returns to the chat input. The label retains the progress shimmer; reduced motion shows static text.")); content.push(localize('sessionsChat.inputPills2', "When session metadata or active-turn status pills appear above the input, press Shift+Tab to reach them, use the Left and Right arrow keys to move between them, and press Enter or Space to activate one. Open the context menu{0} to choose which pills are shown. Pull Requests Options lets you show all pull requests or only open and draft ones. Subagent Options offers Show All and Show In Progress. These choices are remembered across sessions. If every entry of a pill is filtered out, its options are also available in any other pill's context menu or the toolbar context menu.", '')); - content.push(localize('sessionsChat.artifactIntegrationSetting', "The {0} setting enables live artifact details, actions, and Autopilot instead of Agent Merge. It is off by default. Switching pauses saved automation choices and stops automation-owned work without cancelling human-started work. Switching back can resume previously enabled rules; it does not grant new permission. Ordinary artifact links and recorded history remain available.", ArtifactIntegrationsSettingId)); + content.push(localize('sessionsChat.artifactIntegrationSetting', "The {0} setting enables live artifact details, actions, and Autopilot instead of Agent Merge. It is on by default in Insiders and off by default in Stable. Switching pauses saved automation choices and stops automation-owned work without cancelling human-started work. Switching back can resume previously enabled rules; it does not grant new permission. Ordinary artifact links and recorded history remain available.", ArtifactIntegrationsSettingId)); content.push(localize('sessionsChat.pullRequestArtifact', "Recorded GitHub pull request artifacts can show checks, merge conflicts, and unresolved review threads as additional pill sections. The checks section is hidden when there are no checks. Merge conflicts remain visible even without checks; activate Conflicts to open the branch-repair controls in the main details. Their details offer repair actions and separate, opt-in automation controls. Repair prompts require a matching checkout and instruct the agent to commit and push the repair. Automatically Mark Ready can exclude check-name patterns configured in Settings; automatic merging still requires every check to pass. The main details offer Mark Ready, Merge, and branch-update controls. Branch-discovered pull requests and reference links do not gain these automations.")); content.push(localize('sessionsChat.artifactSignIn', "When an artifact needs authentication, open its details and use Tab to reach Sign In. Enter or Space starts authentication in this window. The resource remains available from the linked title. Signing in does not enable automation.")); content.push(localize('sessionsChat.artifactAutomationNotices', "In Agent Host sessions, enabling, changing, or disabling an artifact automation adds a notice to the chat that recorded the artifact. Notices explain what will run automatically and why a rule was turned off, including unsuccessful attempts that caused automatic disablement. Use Tab to reach the notice and Enter or Space to expand or collapse its details. Notices raised while the agent is working appear after that turn finishes. Automatic repair prompts appear as messages in that chat without replacing your draft.")); @@ -151,8 +159,8 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.artifactAutopilot', "Autopilot groups the opt-in rules for automatic actions. It starts collapsed. Activate its heading to expand the rules, or use its separate switch to enable all available rules or turn them off. The trailing artifact pill section shows the number of enabled Autopilot rules and opens this section.")); content.push(localize('sessionsChat.artifactListInformation', "Artifact details remember the selected list tab when closed and reopened. A tab can offer an information icon; hover it or focus it and press Enter or Space to read the provider's explanation without changing tabs. The Comments tab describes which review comments it includes.")); content.push(localize('sessionsChat.artifactActionDisclosure', "Artifact actions appear as collapsed request cards with an action and resource label. Use Tab to reach the card and Enter or Space to expand it. The details are a snapshot from when the action started. Use arrow keys within a details list and Enter to open an item. Agent Message switches between these details and the full prompt. Open the accessible view{0} while the request is focused to read its snapshot as text.", '')); - content.push(localize('sessionsChat.artifactIntegrationGroups', "When two or more artifacts of the same kind share an integration group, such as several pull requests, they appear as one pill named by the integration, such as 4 Pull Requests. Its icon shows the state that needs attention most, and a trailing section counts their enabled Autopilot rules. Enter or Space opens a list above the pill with one toolbar per artifact, showing its state icon, label, status sections and title. Up and Down Arrow, Home and End move between artifacts; Left and Right Arrow move between an artifact's controls. Tab and Shift+Tab move through every control and stay in the list. Enter or Space on the label opens the artifact's details, and on a status section opens the matching list. The artifact's actions, such as Open, Open Pull Request Changes, Copy Link, Pin and Remove, follow its status sections. Pin moves the artifact into a pill of its own; that pill's context menu{0} and trailing button offer Unpin. Escape closes the list and returns focus to the pill.", '')); - content.push(localize('sessionsChat.artifactIntegrations', "Integrations decide which artifacts and references get pills of their own; those that are not grouped appear as individual pills above the input. Other integrated artifacts and references are listed in the Artifacts, References, Pull Requests or Issues pill with their integration's icon and label, where Enter or Space opens the artifact's details and the row's Open action opens the resource. Enter or Space on a main pill opens an input-width details panel above the pills without moving the conversation or draft. The selected pill has a highlighted border. Details show the linked title, state icon and up to three lines of the actual description. Copy Link and Remove Artifact appear in the footer. Left and Right Arrow, Home and End select a list tab. Clicking a tab focuses its first item; arrow keys navigate list rows and Enter opens an item. Some rows offer item actions, such as rerunning a check, which Tab reaches from the list. A pill's status section selects and focuses the corresponding list or action, including when already open. Lists show single-line rows, with full text available in hovers and the Accessible View. Actions below the lists run once; enabled actions come first in provider order, with the first action primary. Inapplicable actions are hidden and blocked actions explain why. Autopilot groups automatic rules below the lists, with an Activities card below it when history exists. Both cards start collapsed and remember expansion. Autopilot switches grant standing permission and may run immediately when conditions hold. Saved rules remain revocable while unavailable. Turning a rule off prevents new runs but does not cancel work already started. Some activity rows reveal their related chat message; others are informational. Clicking another artifact switches the panel. Clicking the active pill, Escape or Close dismisses it. Escape and Close restore pill focus; outside clicks dismiss without moving focus back. Use Tab and Shift+Tab between controls, Space to change a switch, and accessibility help or the Accessible View{0} to read the full content. Background prompts do not replace your draft, attachments or visible chat.", '')); + content.push(localize('sessionsChat.artifactIntegrationGroups', "When two or more artifacts of the same kind share an integration group, such as several pull requests, they appear as one pill named by the integration, such as 4 Pull Requests. Its icon shows the state that needs attention most, and a trailing section counts their enabled Autopilot rules. Enter or Space opens a list above the pill with one toolbar per artifact, showing its state icon, label, status sections and title. Up and Down Arrow, Home and End move between artifacts; Left and Right Arrow move between an artifact's controls. Tab and Shift+Tab move through every control and stay in the list. Enter or Space on the label opens the artifact's resource, such as the pull request, and on a status section opens the matching list in the artifact's details. An artifact without status sections offers a Details section that opens its details. The artifact's actions, such as Open Pull Request Changes, Copy Link, Pin and Remove, follow its status sections. Pin moves the artifact into a pill of its own; that pill's context menu{0} and trailing button offer Unpin. Escape closes the list and returns focus to the pill.", '')); + content.push(localize('sessionsChat.artifactIntegrations', "Integrations decide which artifacts and references get pills of their own; those that are not grouped appear as individual pills above the input. Other integrated artifacts and references are listed in the Artifacts, References, Pull Requests or Issues pill with their integration's icon and label, where Enter or Space opens the artifact's details and the row's Open action opens the resource. Enter or Space on a main pill opens its resource, such as the pull request. Its status sections, or a Details section when it has none, open an input-width details panel above the pills without moving the conversation or draft. The selected pill has a highlighted border. Details show the linked title, state icon and up to three lines of the actual description. Copy Link and Remove Artifact appear in the footer. Left and Right Arrow, Home and End select a list tab. Clicking a tab focuses its first item; arrow keys navigate list rows and Enter opens an item. Some rows offer item actions, such as rerunning a check, which Tab reaches from the list. A pill's status section selects and focuses the corresponding list or action, including when already open. Lists show single-line rows, with full text available in hovers and the Accessible View. Actions below the lists run once; enabled actions come first in provider order, with the first action primary. Inapplicable actions are hidden and blocked actions explain why. Autopilot groups automatic rules below the lists, with an Activities card below it when history exists. Both cards start collapsed and remember expansion. Autopilot switches grant standing permission and may run immediately when conditions hold. Saved rules remain revocable while unavailable. Turning a rule off prevents new runs but does not cancel work already started. Some activity rows reveal their related chat message; others are informational. Opening another artifact's details switches the panel. Activating the Details section again, Escape or Close dismisses it. Escape and Close restore pill focus; outside clicks dismiss without moving focus back. Use Tab and Shift+Tab between controls, Space to change a switch, and accessibility help or the Accessible View{0} to read the full content. Background prompts do not replace your draft, attachments or visible chat.", '')); content.push(localize('sessionsChat.removeSessionRecord', "Recorded artifacts and references offer Remove from Session for each row. Use Tab to reach row actions. When only one item is visible, use its pill hover actions or context menu instead. Removal waits for persistence and only deletes the session record; it does not delete the linked resource, close a pull request or issue, or remove independent session associations.")); content.push(localize('sessionsChat.generatedImageArtifacts', "Generated images from this chat automatically appear in the Generated Images section of the Artifacts pill, separate from other images and files. When Images Preview is enabled for chat, open an image and use the Left and Right Arrow keys to browse generated images and user attachments from the conversation. Images shown from the transcript do not offer Remove from Session unless they were also recorded as artifacts.")); content.push(localize('sessionsChat.imageDownloads', "Images Preview offers Download for the selected image. File, folder, and image rows in Artifacts and References that are on this device offer Reveal in Finder, Reveal in File Explorer, or Open Containing Folder, depending on your operating system. Files and folders from a remote device, such as one reached over SSH or a dev tunnel, offer Download... instead, as do other image rows. Download... asks where to save the item. Use Tab to reach these actions and Enter or Space to run them. When a pill contains a single item, these actions are also available in the pill hover and context menu. Opening an image in the new-session composer includes all images attached to that draft.")); @@ -163,7 +171,7 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.copySessionRecord', "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('sessionsChat.externalSessionFilter', "The Sessions list Filter Sessions menu includes a Created Externally submenu. Choose None, Recent, Last 24 Hours, Last 7 Days, or Last 30 Days to control which sessions from other applications are shown. Last 7 Days is the default. Show in External Section places these sessions in their own External section. This option is off by default, so external sessions appear alongside other sessions in their normal groups.")); content.push(localize('sessionsChat.sessionOrdering', "On desktop, the Filter Sessions menu offers Ordering and Grouping submenus. Grouping by Repository lists the sessions of each GitHub repository together, whether they run on This Computer, in Cloud, or on a remote host. Sessions without a GitHub repository stay in their workspace section. Grouping by Environment lists sessions together under This Computer, Cloud, or their remote host, across agents and workspaces. When grouping by Workspace, Repository, or Environment, Show switches between Recent and All sessions. Current choices are checked inside the submenus. Use the Right arrow key to open a submenu, the Left arrow key to return, and Enter or Space to choose an option.")); - content.push(localize('sessionsChat.inboxMode', "Enable the experimental {0} setting, then choose Grouping, Inbox Mode. On desktop, the pane is called Inbox and its primary sessions cannot be collapsed as a category. Pinned stays above them. Working, Ready to merge, On hold, and Done appear as counted categories at the bottom. Categories with sessions can be expanded, and multiple categories can stay open. Use Tab and Shift+Tab to move between the primary list and the categories, Up and Down Arrow to navigate each tree, and Left and Right Arrow to collapse or expand a category. When categories are expanded, Tab also reaches Resize Inbox Categories: Up and Down Arrow resize this region, Home minimizes it, and End maximizes it while keeping the primary list usable. Search covers both regions and restores their expansion when closed. On phone, Inbox mode retains a single grouped tree. Pinned sessions remain visible even while working or on hold. The primary Inbox prioritizes outstanding asks, failing CI, and Copilot review comments above completed work. Ready to merge follows the Inbox's passing-CI rules for open, non-draft pull requests. Completed history from before you first enable Inbox mode starts in Done unless it has an outstanding question or actionable notification. Choose Return to Inbox to bring an old session back. New completions stay in the inbox until you choose Dismiss from Inbox. This action uses a close icon and moves the item to Done without stopping or archiving the session, and new activity or a new notification brings it back. To archive the session instead, choose Mark Session as Done, which uses a checkmark. Both actions appear on row hover or keyboard focus and are also available in the context menu. Put on Hold keeps a session on hold until you choose Return to Inbox. Snooze also places sessions in On hold, but returns them at a time or on new activity. The Inbox triage actions support multiple selected sessions and show an Undo notice. Switching grouping restores your custom groups and ordering without moving Automations or Customizations.", SESSIONS_LIST_INBOX_ENABLED_SETTING)); + content.push(localize('sessionsChat.inboxMode', "Choose Grouping, Inbox Mode at any time. The experimental {0} setting makes Inbox Mode the default when you have not chosen a grouping; explicit choices are preserved. Pinned, Inbox, Working, Ready to merge, On hold, Dismissed, and Done share one scrolling tree. Empty secondary categories are hidden. Use Up and Down Arrow to navigate, Left and Right Arrow to expand categories, and Tab to reach row actions. Inbox cannot be collapsed. Search covers every category and restores expansion when closed. Inbox prioritizes outstanding asks, failing CI, and review comments; Ordering sorts sessions within each priority. A session with an available conversation stays in Inbox while another conversation is working. Ready to merge offers Merge Pull Request only when the provider supports it for the current pull request. Completed turns from before you first use Inbox mode start in Dismissed unless they need attention or the session is unread and was modified today in your local time. Explicit dismissal, hold, and snooze choices still apply to unread sessions. Dismissed does not mean the work is finished or archived. Choose Return to Inbox to bring a session back. Dismiss from Inbox uses a read-mail icon and moves the session to Dismissed without stopping or archiving it; new activity can bring it back. Mark Session as Done, available in the context menu, archives the session into Done. Put on Hold keeps a session on hold until explicitly resumed. On hold is grouped by workspace. Snooze replaces any dismissal and places the session on hold until its displayed wake-up time or new activity. When it wakes, activity determines whether it appears in Inbox, Working, or Ready to merge. Triage supports multiple selected sessions. Dismissal and bulk actions offer Undo; single-session hold, snooze, and resume do not cover the list with a banner. Switching grouping restores your custom groups and ordering without moving Automations or Customizations.", SESSIONS_LIST_INBOX_ENABLED_SETTING)); content.push(localize('sessionsChat.repositorySectionNewSession', "In a repository section with sessions in several environments, the New Session dropdown can start a session in each environment, in the workspace of its most recently created session there. Session rows in a repository section name their environment, except for This Computer.")); content.push(localize('sessionsChat.sessionFilters', "The Environment, Created In, and Harness submenus filter the Sessions list. Checked options are included. On This Computer and remote hosts, applications other than VS Code are hidden by default. Slack and Teams applications in Cloud are also hidden by default. Show Done, or Show Archived depending on your settings, includes archived sessions. Reset Filters restores these defaults and shows an Undo notice at the bottom of the Sessions list that restores your previous filters. On desktop, Compact View and Collapse All Groups are available from the Sessions More Actions menu. On phone, use Sort and Find to navigate the list.")); content.push(localize('sessionsChat.sessionCreationFilters', "Created In lists the applications that created sessions, grouped by This Computer, Cloud, and each remote host, with the environment in each application's name. VS Code is always offered for each available environment, even before you create a session there. Other applications are listed after a session created in them is discovered. Only applications from included environments are listed. Excluding an environment hides its applications without changing their selections; including it again restores them. Other list filters do not remove application choices. Included remote hosts retain their applications while cached sessions remain, even when disconnected. If no environments are included, select an environment first.")); @@ -186,8 +194,8 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat } content.push(localize('sessionsChat.delegatedMessage', "Messages sent by another session or chat show a source annotation above the message. Press Tab to focus the annotation, then press Enter or Space to open the source chat.")); content.push(archiveActionWording === ChatSessionArchiveActionWording.MarkAsDone - ? localize('sessionsChat.doneChat', "To mark an individual nested chat, including a /btw side chat, as done without marking its session as done, open the chat's context menu in the Sessions list or chat tab and choose Mark as Done. The chat is hidden from the Sessions list and closed, but is not deleted. Open the Sessions list Filter menu and enable Done to show it again, then open the chat's context menu and choose Restore.") - : localize('sessionsChat.archiveChat', "To archive an individual nested chat, including a /btw side chat, without archiving its session, open the chat's context menu in the Sessions list or chat tab and choose Archive. The chat is hidden from the Sessions list and closed, but is not deleted. Open the Sessions list Filter menu and enable Archived to show it again, then open the chat's context menu and choose Unarchive.")); + ? localize('sessionsChat.doneChat', "To mark an individual nested chat, including a /btw side chat, as done without marking its session as done, open the chat's context menu in the Sessions list or chat tab and choose Mark as Done. The chat is closed but not deleted, and gets its own row in the Sessions list while done content is shown. If it is hidden, open the Sessions list Filter menu and enable Done. To restore the chat, open its context menu and choose Restore.") + : localize('sessionsChat.archiveChat', "To archive an individual nested chat, including a /btw side chat, without archiving its session, open the chat's context menu in the Sessions list or chat tab and choose Archive. The chat is closed but not deleted, and gets its own row in the Sessions list while archived content is shown. If it is hidden, open the Sessions list Filter menu and enable Archived. To unarchive the chat, open its context menu and choose Unarchive.")); content.push(localize('sessionsChat.createdBySession', "When a session was created by another session, focus it in the Sessions list and use the Show Hover command{0}. Move focus to the Created by link, then press Enter or Space to open the creator session.", '')); if (areRemoteSessionToolsEnabled(configurationService)) { content.push(localize('sessionsChat.remoteDelegation', "Ask the agent to list remote agent hosts or create a remote session with platform and resource requirements. Creation uses the standard tool confirmation and does not change the focused chat. The result includes a link to the remote session. Remote sessions can send messages back to the originating chat while this Agents window remains connected.")); @@ -199,9 +207,10 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.compareAgentsConfiguration', "Comparison selections are kept while draft permissions or mode are updating. Run N Attempts is unavailable until the update finishes.")); content.push(localize('sessionsChat.compareAgentsFusion', "Copilot Fusion is available for comparison when your harness offers it. Open its Details to choose an effort level. Legacy Auto and standalone HydraFusion models are not offered for comparison.")); if (configurationService.getValue(COMPARE_AGENTS_TOOLS_ENABLED_SETTING)) { - content.push(localize('sessionsChat.compareAgentsTools', "You can also ask an agent to discover comparison models and launch evaluation scenarios using the current chat's workspace and permissions. When approval is required, review the scenario, models, and permissions in the normal tool confirmation before approving. The evaluator chat stays open. Ask an agent to list comparisons, read their results, or inspect available attempt and Judge conversations, including comparisons you created manually. Reading results does not submit a verdict or start synthesis.")); + content.push(localize('sessionsChat.compareAgentsTools', "You can also ask an agent to discover comparison models and launch evaluation scenarios using the current chat's workspace and permissions. When approval is required, review the scenario, models, and permissions in the normal tool confirmation before approving. The evaluator chat stays open. Use Tab to reach Open Comparison in the tool result and Enter to open the attempts in a grid. Ask an agent to list comparisons started by this chat, read their results, or inspect available attempt and Judge conversations. To discover comparisons from other chats or comparisons you created manually, ask it to list comparisons across the window. Reading results does not submit a verdict or start synthesis.")); } content.push(localize('sessionsChat.compareAgentsDiscovery', "The model picker offers Compare Models in the tab bar. Use Tab to reach it and Enter or Space to begin setup. Use Compare Models{0} from the new-session input or model picker to open comparison setup directly. Enable the experimental sessions.chat.compareAgents.showPickerHint setting to also show Send Query to Multiple Models at the bottom with your configured shortcut until you first open comparison setup. The tab-bar toggle remains available to return to single-model selection.", '')); + content.push(localize('sessionsChat.compareAgentsKeyboardAndSettings', "In comparison setup, use Up Arrow and Down Arrow to focus a model and Space or Enter to toggle its selection without closing the picker. The comparison parent in the Sessions list describes the original repository, base branch, isolation, attempt models, Judge, and Synthesizer to screen readers. The same saved settings are available by hovering over that parent.")); content.push(localize('sessionsChat.compareAgentsFolderless', "In a Chat with no workspace, comparisons run the prompt in separate workspace-less chats. Select at least two attempts, optionally configure a Judge and Synthesizer with Next, activate Done, then Run N Attempts. The Judge compares responses, and Synthesize combines their strongest parts into a new answer without changing the original chats.")); content.push(localize('sessionsChat.compareAgentsSpotlight', "Enable the experimental sessions.chat.compareAgents.showSpotlight setting for a one-time introduction when you open an eligible model picker, provided you have not opened comparison setup before. The spotlight describes parallel models and agent harnesses, plus optional judging and synthesis when available. Activate Understood or press Escape to dismiss it and return to the picker, or activate Compare Models to begin setup.")); content.push(localize('sessionsChat.compareAgents', "In the new-session input, open the model picker and activate Compare Models. In Attempts, check two to ten distinct models. Attempts inherit the current workspace, branch, agent, and permissions. Done and Next stay disabled until two to ten models are checked, and the footer shows how many are selected. Use Tab to reach Done and Next. In Judge, optionally select a model to review the attempts and recommend a winner. Leave Judge unselected and activate Done to run attempts without review. With a Judge selected, activate Next to choose an optional Synthesizer. Without a Synthesizer, review is available but synthesis is not. Activate a selected model again to clear it. Back preserves your choices. Done returns to the composer; activate Run N Attempts to launch. Escape closes the picker without launching. Open the comparison parent in the Sessions list to open every available attempt in a resizable grid. With two attempt panes, both chat inputs remain visible. With three or more, only the active attempt pane shows its chat input; focus another attempt pane to show its input. Screen-reader optimized mode keeps every attempt input visible. After the Judge finishes, its chat shows a scorecard: the winning model with the Judge's explanation, then a row for each attempt, recommended first, with a summary of its validation checks such as Tests passed or Not run, total time, and tokens. Use Tab to reach the Checks column header to hear what the checks cover. Focus the comparison result and use Open Accessible View{0} to read its verdict and attempt metrics as plain text. Use Tab to reach the attempt rows and Up Arrow or Down Arrow to move between them, then press Enter or Space to expand a row with the Judge's reasoning, what is worth keeping, gaps, each check's result, and Open Attempt N. Each row also has an Open button after its metrics that opens that attempt's session. Activate Open Attempt to open the recommended attempt, or use its adjacent dropdown to open another attempt. When synthesis is available, Synthesize starts the Judge's default plan. Open its More Actions menu and choose Additional Synthesis Instructions to enter requirements that are remembered and applied to recommended synthesis. Activate Start Synthesis with Instructions, or press Ctrl+Enter (Cmd+Enter on macOS) in that field, to start the recommended plan with those requirements. The additional instructions guide a new synthesis session and do not modify the original attempts.", '')); @@ -222,23 +231,24 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.newSessionPickers', "While focus is in a new-session composer or its pickers, open and focus the workspace picker{0} or the harness picker{1}. Focus either picker control and open its context menu{2} to configure its keybinding. The context menu also offers Collapse to Icon and Show Session Options Toggle. Hiding the toggle keeps the session options available, and the same context menu restores it. These choices persist after restarting.", ``, ``, '')); content.push(localize('sessionsChat.promptTemplatePlaceholder', "When the new-session prompt contains a highlighted task placeholder, place the caret inside it and replace it{0} to type your task.", ``)); content.push(configurationService.getValue(ArtifactIntegrationsSettingId) === true - ? localize('sessionsChat.feedbackComments.artifactIntegrations', "While the {0} setting is enabled, pull request failing-check and review-comment banners do not appear above the input. Open a recorded pull request artifact's details to review its checks and comments. In-product agent review comments still appear in a banner above the input.", ArtifactIntegrationsSettingId) + ? localize('sessionsChat.feedbackComments.artifactIntegrations', "While the {0} setting is enabled, pull request failing-check and review-comment banners do not appear above the input. Open a recorded pull request artifact's details to review its checks and comments. In-product agent review comments still appear in a banner above the input. For sessions that support artifact integrations, the title bar does not offer Fix Checks, Mark Ready, Merge, or Open Pull Request; use the pull request artifact's pill and details instead. Create PR remains in the title bar.", ArtifactIntegrationsSettingId) : localize('sessionsChat.feedbackComments', "When pull requests have failing checks or unreviewed comments, one banner appears above the input. If several pull requests need attention, use the Previous Banner and Next Banner buttons to move between them. A pull request with both failing checks and comments uses a split button. Activate the main action to address both. Open its More Actions menu to choose Fix Checks or Address Comments separately. Choose Reveal Checks in the More Actions menu to open the pull request. Choose Reveal Comments in the same menu to view the first comment. In-product agent review comments appear as their own carousel item.")); if (accessor.get(IConfigurationService).getValue(AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING)) { content.push(localize('sessionsChat.worktreeCleanupSuggestion', "When at least 20 inactive session worktrees are eligible for cleanup or eligible inactive worktrees can reclaim at least 5 GiB, a storage suggestion may appear below the Sessions list and is announced with the Open Worktree Cleanup Command Palette command. The command is also available from the Sessions More Actions menu. Active, running, needs-input, pinned, and recently used sessions are excluded. Use Tab or Shift+Tab to reach Open Worktree Cleanup, Don't Show Again, or Dismiss Session Storage Suggestion, then Enter or Space to activate it. Don't Show Again disables future suggestions and announcements across restarts. Press Escape while focus is in the suggestion to dismiss it for the current window. To stop these suggestions and announcements without using the suggestion itself, run Disable Session Storage Cleanup Suggestions from the Command Palette, or run Open Worktree Cleanup and clear the Suggest Cleaning Up Session Storage When It Grows Large checkbox.")); } if (accessor.get(IConfigurationService).getValue(SESSION_ARCHIVE_NUDGE_SETTING)) { content.push(localize('sessionsChat.compactArchiveNudge', "After you successfully use the suggestion to archive or mark a session as done three times, future suggestions appear in a compact layout without the explanation. The buttons wrap below the title when space is limited, while Dismiss stays at the top right. The keyboard order is Archive or Mark as Done, Configure, then Dismiss. Configure opens the same automatic cleanup settings.")); - content.push(localize('sessionsChat.archiveNudgeOnboarding', "The first time you activate the suggestion's Archive or Mark as Done button, a spotlight may reveal that session's action in the sessions list. It briefly waits for the list action to appear. The action waits until you activate the highlighted action, activate Understood, or press Escape to end the spotlight. Use Tab or Shift+Tab to move between the highlighted action and Understood, and Enter or Space to activate either. If the spotlight cannot be shown or is interrupted, the session is still archived or marked as done as long as the suggestion remains available. Once completed or skipped, the spotlight will not appear again.")); + content.push(localize('sessionsChat.archiveNudgeOnboarding', "The first time you activate the suggestion's Archive or Mark as Done button in a session's main chat, a spotlight may reveal that session's action in the sessions list. It briefly waits for the list action to appear. The action waits until you activate the highlighted action, activate Understood, or press Escape to end the spotlight. Use Tab or Shift+Tab to move between the highlighted action and Understood, and Enter or Space to activate either. If the spotlight cannot be shown or is interrupted, the session is still archived or marked as done as long as the suggestion remains available. Once completed or skipped, the spotlight will not appear again.")); content.push(archiveActionWording === ChatSessionArchiveActionWording.MarkAsDone - ? localize('sessionsChat.doneNudge', "When all GitHub pull requests associated with the current chat have merged and no chat in the session is working or waiting for input, a mark as done suggestion may appear above that chat's input. Use Tab or Shift+Tab to reach Mark as Done, Configure Automatic Cleanup, or Dismiss Mark as Done Suggestion, then Enter or Space to activate it. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Mark as Done\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismiss Mark as Done Suggestion, or Escape while the suggestion is focused, hides the suggestion for this session, including after a reload, until it is marked as done or deleted, and returns focus to the chat input. Marking the session as done hides it from the sessions list so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Done\" section of the sessions list. You can restore it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by restoring the session.") - : localize('sessionsChat.archiveNudge', "When all GitHub pull requests associated with the current chat have merged and no chat in the session is working or waiting for input, an archive suggestion may appear above that chat's input. Use Tab or Shift+Tab to reach Archive, Configure Automatic Cleanup, or Dismiss Archive Suggestion, then Enter or Space to activate it. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Archive\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismiss Archive Suggestion, or Escape while the suggestion is focused, hides the suggestion for this session, including after a reload, until it is archived or deleted, and returns focus to the chat input. Archiving the session hides it from the sessions list so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Archived\" section of the sessions list. You can unarchive it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by unarchiving the session.")); + ? localize('sessionsChat.doneNudge', "When all GitHub pull requests associated with the current chat have merged and no chat in the session is working or waiting for input, a mark as done suggestion may appear above that chat's input. Use Tab or Shift+Tab to reach Mark as Done, Configure Automatic Cleanup, or Dismiss Mark as Done Suggestion, then Enter or Space to activate it. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Mark as Done\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismiss Mark as Done Suggestion, or Escape while the suggestion is focused, hides the suggestion for this session, including after a reload, until it is marked as done or deleted, and returns focus to the chat input. Marking the session as done sets it aside so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Done\" section of the sessions list. You can restore it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by restoring the session. In a chat other than the session's main chat, the suggestion marks only that chat as done instead, and the session, its other chats, and its worktree are not affected. Look for the chat in the \"Done\" section of the sessions list.") + : localize('sessionsChat.archiveNudge', "When all GitHub pull requests associated with the current chat have merged and no chat in the session is working or waiting for input, an archive suggestion may appear above that chat's input. Use Tab or Shift+Tab to reach Archive, Configure Automatic Cleanup, or Dismiss Archive Suggestion, then Enter or Space to activate it. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Archive\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismiss Archive Suggestion, or Escape while the suggestion is focused, hides the suggestion for this session, including after a reload, until it is archived or deleted, and returns focus to the chat input. Archiving the session sets it aside so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Archived\" section of the sessions list. You can unarchive it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by unarchiving the session. In a chat other than the session's main chat, the suggestion archives only that chat instead, and the session, its other chats, and its worktree are not affected. Look for the chat in the \"Archived\" section of the sessions list.")); content.push(localize('sessionsChat.archiveNudgeContinuation', "Sending a new message after the suggestion appears hides it for those pull requests, including after a reload. It can appear again in a chat when a new pull request is added to that chat and all of its pull requests have merged.")); } content.push(localize('sessionsChat.feedbackAttachment', "When a feedback comments attachment appears above the input, focus it and press Enter or Space. A single comment opens directly. Multiple comments open a tree grouped by file; use the arrow keys to navigate, Enter to reveal a comment, and Escape to close the tree.")); content.push(localize('sessionsChat.editorCommentCards', "Editor comment cards show the author and line. Use Tab to reach the comment actions and See more or See less, and Enter or Space to activate them. When content is taller than the editor, Tab to the scrollable comments region and use the arrow keys to scroll. The More Actions menu includes Edit and Add to Comment. Share Comment with Agent accepts a review comment. Accepted means it is ready to submit; Investigating means it has been submitted to the agent.")); - content.push(localize('sessionsChat.inputBackground', "Use Send in Background{0} to start a new session without navigating into it. The started session appears in the Sessions list, and the composer resets for another prompt. With the Sessions list Inbox setting enabled, a confirmation offers Open Session when the send succeeds. Enter sends and opens the session as usual. You can change the background-send shortcuts in Keyboard Shortcuts.", ``)); + content.push(localize('sessionsChat.inputBackground', "Use Send in Background{0} to start a new session without navigating into it. The started session appears in the Sessions list, and the composer resets for another prompt. A notification offers Open Session when the send succeeds. Enter sends and opens the session as usual. You can change the background-send shortcuts in Keyboard Shortcuts.", ``)); content.push(localize('sessionsChat.workspace', "Use Tab or Shift+Tab to navigate to the workspace picker and choose a workspace for your session. Opening the picker focuses its search input so you can immediately type to filter workspaces. If quick chats are available, you can also choose Chat to start a workspace-less chat.")); + content.push(localize('sessionsChat.customizationsLocation', "The Chat: Customizations Location setting places Customizations below Sessions, at the top left of Sessions, in the Chat toolbar, or inside the input after the model pickers. Activate Customizations with Enter or Space to open its editor. Its hover contains counts and links for plugins, MCP servers, skills, instructions, and hooks. Needs attention links to customization migrations and MCP servers that require sign-in, showing up to two server names. Activate a server name to sign in directly; the sign-in count opens MCP server management. The footer offers Browse Additional and a settings gear named Change Button Location. Use Show or Focus Hover while the button is focused, then Tab or Shift+Tab to reach the links and Enter to activate them.")); content.push(localize('sessionsChat.pickerShortcuts', "While the new-session input has focus, open the environment picker{0}, branch picker{1}, or Branch/New Worktree picker{2}. Focus Sync Changes{3}, then press Enter to synchronize. These shortcuts are available only when the corresponding control is available and expand hidden session options before focusing them.", '', '', '', '')); content.push(localize('sessionsChat.removeWorkspace', "Workspace rows offer a Remove action. Use the arrow keys to focus a workspace, then Tab to reach its actions. Removed workspaces stay hidden across reloads until you browse to that workspace and successfully start a session from the new-session composer. Removing a workspace does not delete its sessions or files.")); content.push(accessor.get(IAccessibilityService).isScreenReaderOptimized() @@ -268,12 +278,14 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(getModelPickerConfigurationAccessibilityHelp()); content.push(localize('sessionsChat.mobileConfig', "On mobile, the mode and model pickers appear as tappable chips below the input. Tap a chip to open a bottom sheet where you can change the selection.")); content.push(localize('sessionsChat.history', "Use up and down arrows to navigate your request history in the input box.")); - content.push(localize('sessionsChat.background', "Outside high contrast themes, use Set Background to choose no background, the built-in theme-aware Codicons pattern, a new image, or one of the five most recently selected images. One randomly selected icon in the Codicons pattern is a Celebrate button; press Tab to find it, then press Enter or Space to activate it. Each activation selects another random icon as the next Celebrate button. Use Change Background Layout to choose whether an image repeats, stretches, or appears at an edge or corner for the current color theme. Moving through the layout picker previews each option; select one to save it, or press Escape to restore the previous layout. Both commands are available from the Command Palette and by right-clicking empty chat space. Change Background Layout is shown only for images. Background customization is unavailable while a high contrast theme is active.")); - content.push(localize('sessionsChat.backgroundTint', "When a background image is set, use Tint Window to Match Background in the Command Palette or the background context menu to turn matching window colors on or off. A check mark means tinting is enabled. Turning it off keeps the background image and restores the original window colors.")); - if (configurationService.getValue(AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING) === true) { - content.push(localize('sessionsChat.themeColorsTool', "You can ask the agent to read the current theme colors using Get Theme Colors in the Appearance tool group. This reports the palette without changing your theme or background.")); - content.push(localize('sessionsChat.generateBackgroundSkill', "To generate a chat background, ask the agent or type /generate-chat-background to use the built-in skill. It provides optional design guidance, applies the generated image, and checks it in a screenshot of the window when the required tools are available.")); - content.push(localize('sessionsChat.generateBackgroundEntry', "When workspace-less sessions are available, Set Background also offers Generate Background after a separator, between the background types and the recently used images. It opens a new workspace-less session whose input starts with Generate a chat background of, with the caret at the end so you can describe the image and send it.")); + if (this._supportsChatBackgrounds) { + content.push(localize('sessionsChat.background', "Outside high contrast themes, use Set Background to choose no background, the built-in theme-aware Codicons pattern, a new image, or one of the five most recently selected images. One randomly selected icon in the Codicons pattern is a Celebrate button; press Tab to find it, then press Enter or Space to activate it. Each activation selects another random icon as the next Celebrate button. Use Change Background Layout to choose whether an image repeats, stretches, or appears at an edge or corner for the current color theme. Moving through the layout picker previews each option; select one to save it, or press Escape to restore the previous layout. Both commands are available from the Command Palette and by right-clicking empty chat space. Change Background Layout is shown only for images. Background customization is unavailable while a high contrast theme is active.")); + content.push(localize('sessionsChat.backgroundTint', "When a background image is set, use Tint Window to Match Background in the Command Palette or the background context menu to turn matching window colors on or off. A check mark means tinting is enabled. Turning it off keeps the background image and restores the original window colors.")); + if (configurationService.getValue(AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING) === true) { + content.push(localize('sessionsChat.themeColorsTool', "You can ask the agent to read the current theme colors using Get Theme Colors in the Appearance tool group. This reports the palette without changing your theme or background.")); + content.push(localize('sessionsChat.generateBackgroundSkill', "To generate a chat background, ask the agent or type /generate-chat-background to use the built-in skill. It provides optional design guidance, applies the generated image, and checks it in a screenshot of the window when the required tools are available.")); + content.push(localize('sessionsChat.generateBackgroundEntry', "When workspace-less sessions are available, Set Background also offers Generate Background after a separator, between the background types and the recently used images. It opens a new workspace-less session whose input starts with Generate a chat background of, with the caret at the end so you can describe the image and send it.")); + } } content.push(localize('sessionsChat.vscodePet', "Use the checked Pet item in the new-session view context menu, or type /vscode-pet, to show or hide the VS Code pet above the input. Drag it horizontally to reposition it, or use Tab to focus it and the left and right arrow keys to move it. Press Enter or Space to show it some love.")); content.push(localize('sessionsChat.vscodePetPainting', "While an image-generation tool is running, the pet paints at a small easel, then returns to its normal activity. Reduced motion shows a still painting pose.")); @@ -307,7 +319,7 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat } const promoteNewChatAction = SessionsListPromoteNewChatActionContext.getValue(accessor.get(IContextKeyService)) ?? SESSIONS_LIST_PROMOTE_NEW_CHAT_ACTION_DEFAULT; if (configurationService.getValue(SESSIONS_LIST_INLINE_ACTIONS_SETTING) && !configurationService.getValue('chat.disableAIFeatures')) { - content.push(localize('sessionsChat.sessionsListInlineActions', "With sessions.list.inlineActions enabled, eligible rows show Fix Checks, Address Comments, or Fix Checks & Address Comments below the metadata. Use Tab or Shift+Tab to reach the button, and Enter or Space to activate it. The request runs in the background without opening the chat. A session row acts on its main chat; a nested chat row acts on that chat, even when multiple sessions are selected. Enabling this setting does not enable Agent Merge or change permissions.")); + content.push(localize('sessionsChat.sessionsListInlineActions', "With sessions.list.inlineActions enabled, eligible rows show Fix Checks, Address Comments, or Fix Checks & Address Comments below the metadata. Use Tab or Shift+Tab to reach the button, and Enter or Space to activate it. The request runs in the background without opening the chat. While sending, the button shows Sending... and is disabled. If sending fails, an error notification appears and the action remains available to retry. A session row acts on its main chat; a nested chat row acts on that chat, even when multiple sessions are selected. Enabling this setting does not enable Agent Merge or change permissions.")); } content.push(promoteNewChatAction ? archiveActionWording === ChatSessionArchiveActionWording.MarkAsDone @@ -335,12 +347,12 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.sessionGrid', "Session panes form a separate grid from the chat groups inside each session. Focus the session to the left{0}, right{1}, above{2}, or below{3}. The generic Navigate to the View on the Left{4}, Navigate to the View on the Right{5}, Navigate to the View Above{6}, and Navigate to the View Below{7} commands do the same while focus is in the session grid. The Session Layout menu and Command Palette offer Move Session Left, Right, Above, and Below, Increase or Decrease Session Width and Height, and Arrange Sessions in a Balanced Grid. Arranging preserves the conversations and does not change side panels. On a phone, only the active session is shown; returning to a wider window restores the desktop arrangement.", ``, ``, ``, ``, ``, ``, ``, ``)); content.push(localize('sessionsChat.detachChat', "To create an independent sub-session pane without dragging, focus the sub-session and run Detach Chat into New Pane{0} from the Command Palette. The new pane stays open when its parent pane closes.", '')); content.push(localize('sessionsChat.positionalPaneFocus', "Focus Session 1 in Grid{0} and the other numbered focus commands follow visual pane order, including independent sub-session panes even when their parent is closed. Focus Last Session in Grid{1} selects the last pane.", '', '')); - content.push(localize('sessionsChat.closeChat', "Activate a chat tab's close button to close (hide) that chat from the tab strip without deleting it; reopen it later from the Chats menu. The session's main chat cannot be closed.")); + content.push(localize('sessionsChat.closeChat', "Activate a chat tab's close button, or middle-click its tab or chat header, to close that chat without deleting it. Reopen it later from the Chats menu.")); content.push(localize('sessionsChat.navigateChatTabs', "When a chat tab is focused, use the left and right arrow keys to move to and activate an adjacent chat tab, or Home and End to activate the first and last tabs. Tabs that do not fit are scrolled into view when activated. You can also scroll the tab row with the mouse wheel or drag the horizontal scrollbar that appears when hovering over overflowing tabs.")); content.push(localize('sessionsChat.deleteChat', "Before a new nested session is committed, its session header and Sessions list row offer Delete without confirmation. After it is committed, those controls offer Archive or Mark as Done instead. To permanently delete a committed nested session, open the chat tab's context menu and choose Delete. This is destructive and cannot be undone.")); content.push(localize('sessionsChat.promptTimeline', "When the prompt timeline is enabled, a handle on the left edge of the transcript lists your prompts. Activate it to expand the list, use the up and down arrows (or Home and End) to move between prompts, Enter or Space to jump to a prompt, and Escape to dismiss the list and return focus to the handle. When a prompt title is pinned above the transcript, activate its title to jump to that prompt.")); content.push(localize('sessionsChat.find', "To search the chat transcript, invoke Find in Chat{0}. Find Next{1} and Find Previous{2} move between results, scrolling each one into view.", '', '', '')); - content.push(localize('sessionsChat.focusActiveSession', "Focus the active session{0}. The default Open Chat (Agent) shortcut also focuses the active session in the Agents window.", ``)); + content.push(localize('sessionsChat.focusActiveSession', "Focus the active session{0}, the default Open Chat (Agent) shortcut. In the Agents window, the Toggle Chat shortcut, including one you customize, opens the Sessions view{1}.", ``, '')); content.push(localize('sessionsChat.goBack', "Go back through visited sessions, the New Session view, custom views such as Automations, and canvas tabs such as Inbox{0}.", '')); content.push(localize('sessionsChat.goForward', "Go forward through visited sessions, views, and canvas tabs{0}. Reopening New Session, a custom view, or a canvas moves its single history entry to the most recent position.", '')); content.push(localize('sessionsChat.navigatePreviousSession', "Navigate to the previous session in the list{0}.", '')); diff --git a/src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts b/src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts index 55681e9d126a..ebff1eb32744 100644 --- a/src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts +++ b/src/vs/sessions/contrib/chat/browser/sharedChatInputComposer.contribution.ts @@ -30,8 +30,9 @@ import { getLabeledPickerResponsiveItems } from '../../../../workbench/contrib/s import { createNewSessionControlToolbar } from './newSessionConfigToolbars.js'; import { SharedChatInputComposer, SharedChatInputComposerBusyContext } from '../../../../workbench/contrib/sessions/browser/chat/sharedChatInputComposer.js'; import { ChatInputSupportsBackgroundContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { SessionsViewGroupingContext } from '../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; import { SEND_IN_BACKGROUND_COMMAND_ID } from '../../../../workbench/contrib/sessions/common/sessionCommands.js'; -import { SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { SessionsGrouping } from '../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; const COMPOSER_INITIALIZING_ACTION_ID = 'sessions.newChatComposer.initializing'; const COMPOSER_SENDING_ACTION_ID = 'sessions.newChatComposer.sending'; @@ -58,7 +59,7 @@ export class SendInBackgroundAction extends Action2 { weight: KeybindingWeight.SessionsContrib, }, { primary: KeyMod.CtrlCmd | KeyCode.Enter, - when: ContextKeyExpr.and(ChatContextKeys.inChatInput, ContextKeyExpr.equals(`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`, true)), + when: ContextKeyExpr.and(ChatContextKeys.inChatInput, SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Inbox)), weight: KeybindingWeight.SessionsContrib, }], }); diff --git a/src/vs/sessions/contrib/chat/browser/sideChatOrchestration.ts b/src/vs/sessions/contrib/chat/browser/sideChatOrchestration.ts index f546d4edef23..87bd985bf3b1 100644 --- a/src/vs/sessions/contrib/chat/browser/sideChatOrchestration.ts +++ b/src/vs/sessions/contrib/chat/browser/sideChatOrchestration.ts @@ -11,22 +11,32 @@ import { ISessionsService } from '../../../../workbench/contrib/sessions/browser import { IChat, ISession, ISideChatSelection } from '../../../../workbench/services/sessions/common/session.js'; import { ISendRequestOptions, ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; -/** Activates a new side chat in its own group before sending the request. */ +/** + * Opens a new side chat beside its source chat, in the chat window that shows the source chat or else in the grid, before + * sending the request. + */ export async function openAndSendSideChat( sessionsManagementService: ISessionsManagementService, sessionsService: ISessionsService, sessionsPartService: ISessionsPartService, session: ISession, sideChat: IChat, + sourceChat: URI, + sourceInGrid: boolean, requestOptions: ISendRequestOptions, ): Promise { - const opening = sessionsService.openChat(session, sideChat.resource); + const opening = sessionsService.openChat(session, sideChat.resource, { referenceChatResource: sourceChat }); const navigationRequest = sessionsService.navigationRequest.get(); await opening; if (sessionsService.navigationRequest.get() !== navigationRequest) { await sessionsManagementService.sendRequestInBackground(session, sideChat, requestOptions); return; } + if (!sourceInGrid) { + // A foreground send discards the main window's new-session draft and makes its slot follow the sent chat. + await sessionsManagementService.sendRequestInBackground(session, sideChat, requestOptions); + return; + } sessionsPartService.getSessionView(session.sessionId)?.splitChatToSide(sideChat.resource); await sessionsManagementService.sendRequest(session, sideChat, requestOptions); } @@ -73,7 +83,7 @@ export async function createAndSendSideChat( if (navigated) { await sessionsManagementService.sendRequestInBackground(session, sideChat, requestOptions); } else { - await openAndSendSideChat(sessionsManagementService, sessionsService, sessionsPartService, session, sideChat, requestOptions); + await openAndSendSideChat(sessionsManagementService, sessionsService, sessionsPartService, session, sideChat, sourceChat, inGrid, requestOptions); } return sideChat; } diff --git a/src/vs/sessions/contrib/chat/electron-browser/chat.contribution.ts b/src/vs/sessions/contrib/chat/electron-browser/chat.contribution.ts index 866614c43e4c..b817db76f8fb 100644 --- a/src/vs/sessions/contrib/chat/electron-browser/chat.contribution.ts +++ b/src/vs/sessions/contrib/chat/electron-browser/chat.contribution.ts @@ -18,7 +18,8 @@ import { toRemoteAgentHostSessionType } from '../../../../platform/agentHost/com import { buildExternalOpenSessionLinkUri, parseOpenSessionLinkChatId, parseOpenSessionLinkConnectionAuthority, parseOpenSessionLinkTurnId, parseOpenSessionLinkUri } from '../../../../platform/agentHost/common/openSessionLink.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { AgentHostByokLmHandler } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.js'; -import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { Registry } from '../../../../platform/registry/common/platform.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { IFocusedSessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; @@ -41,6 +42,7 @@ import { getNonArchivedSessionListCount } from '../../../../workbench/contrib/se import { INewSessionComposerService, NewSessionWorkspacePreselectionSource } from '../../../../workbench/contrib/sessions/browser/newSessionComposerService.js'; import { getAgentsWindowWorkspaceArgumentKind, getAgentsWindowWorkspaceArgumentRemoteKind, resolveAgentsWindowFolderIntent } from '../browser/agentsWindowOpenIntent.js'; import { findSessionForOpenSessionLink } from '../browser/openSessionLinkOpener.contribution.js'; +import { getChatWindowLinkSource, IChatWindowLinkSource, openLinkedChatInChatWindow, resolveLinkedChat } from '../browser/chatLinkRouting.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { AgentsWindowWorkspaceHandoff } from '../browser/agentsWindowWorkspaceHandoff.js'; import { SessionsWorkspaceSelectionTelemetry } from '../../sessions/browser/sessionsWorkspaceSelectionTelemetry.js'; @@ -54,6 +56,7 @@ import './chatBackgroundTool.contribution.js'; import { ScreenshotWindowToolContribution } from '../browser/screenshotWindowTool.js'; import { ISession, isSessionCreated } from '../../../../workbench/services/sessions/common/session.js'; import { IRemoteWorkspaceHandoffService, RemoteAgentHostHandoffResult } from '../../../common/remoteWorkspaceHandoff.js'; +import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { getRemoteName } from '../../../../platform/remote/common/remoteHosts.js'; /** Revokes editor request ownership when the next request is submitted here. */ @@ -112,9 +115,11 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb @IProductService private readonly productService: IProductService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IRemoteWorkspaceHandoffService private readonly remoteWorkspaceHandoffService: IRemoteWorkspaceHandoffService, + @IChatWindowService private readonly chatWindowService: IChatWindowService, ) { super(); - this._workspaceHandoff = this._register(instantiationService.createInstance(AgentsWindowWorkspaceHandoff)); + // Session providers register in contributions instantiated after restore. + this._workspaceHandoff = this._register(instantiationService.createInstance(AgentsWindowWorkspaceHandoff, Registry.as(WorkbenchExtensions.Workbench).whenRestored)); this._invitationOnboarding = this._register(instantiationService.createInstance(AgentsWindowInvitationOnboarding)); const handleSelectAgentsFolder = (_: unknown, ...args: unknown[]) => { this._workspaceHandoff.cancel(); @@ -259,6 +264,11 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb private async openExistingSession(sessionResource: URI, token: CancellationToken, remoteAuthority?: string): Promise<'unsupported' | undefined> { this.logService.info(`[AgentsHandoff] openExistingSession: target=${sessionResource.toString()}`); + const backendSession = parseOpenSessionLinkUri(sessionResource); + // The chat window that has focus as the link arrives is the one it was activated in, such as from its canvas: + // read it before waiting, as focus can move meanwhile. No chat window has focus while another app has it. + const linkSource = backendSession && getChatWindowLinkSource(this.chatWindowService.activeWindow, this.configurationService); + // Wait until initial restore has started so opening the target can cancel it, // without delaying the handoff until the intentionally deferred Eventually phase. await raceCancellation(this.lifecycleService.when(LifecyclePhase.Restored), token); @@ -267,9 +277,8 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb } this.logService.info('[AgentsHandoff] reached LifecyclePhase.Restored'); - const backendSession = parseOpenSessionLinkUri(sessionResource); if (backendSession) { - await this.sessionsPartService.getProgressIndicator().showWhile(this.resolveAndOpenSessionLink(sessionResource, backendSession, token)); + await this.sessionsPartService.getProgressIndicator().showWhile(this.resolveAndOpenSessionLink(sessionResource, backendSession, token, linkSource)); return undefined; } @@ -293,7 +302,7 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb return undefined; } - private async resolveAndOpenSessionLink(sessionLink: URI, backendSession: URI, token: CancellationToken): Promise { + private async resolveAndOpenSessionLink(sessionLink: URI, backendSession: URI, token: CancellationToken, linkSource: IChatWindowLinkSource | undefined): Promise { const authority = parseOpenSessionLinkConnectionAuthority(sessionLink); const session = await this.waitForSessionLinkAvailable(backendSession, token, undefined, authority); if (token.isCancellationRequested) { @@ -322,12 +331,17 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb } } - const chatId = parseOpenSessionLinkChatId(sessionLink); - const chatResource = chatId ? session.resource.with({ fragment: chatId }) : session.mainChat.get().resource; + const chatResource = await resolveLinkedChat(this.agentHostConnectionsService, session, parseOpenSessionLinkChatId(sessionLink)); if (token.isCancellationRequested) { return; } this.logService.info(`[AgentsHandoff] linked session available; opening ${chatResource.toString()}`); + if (linkSource && await openLinkedChatInChatWindow(this.chatWindowService, linkSource, session, chatResource, false)) { + return; + } + if (token.isCancellationRequested) { + return; + } await this.sessionsService.openChat(session, chatResource, { source: 'link' }); } @@ -392,11 +406,10 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb * Returns `'unsupported'` when this window does not share that agent host. */ private async resolveAndOpenRemoteSession(editorSessionResource: URI, remoteAuthority: string, token: CancellationToken): Promise<'unsupported' | undefined> { - // Only a tunnel's editor windows share their agent host with this window. Elsewhere, the editor's VS Code server - // runs its own agent host, with a session registry separate from that of the agent host this window starts. - // The window's folder is selected instead, without a notification. - if (getRemoteName(remoteAuthority) !== 'tunnel') { - this.logService.info(`[AgentsHandoff] sessions of ${getRemoteName(remoteAuthority)} windows are not shared with this window`); + // Unsupported remotes fall back to their source folder without a notification. + const remoteName = getRemoteName(remoteAuthority); + if (remoteName !== 'tunnel' && remoteName !== 'ssh-remote' && remoteName !== 'wsl') { + this.logService.info(`[AgentsHandoff] sessions of ${remoteName} windows are not shared with this window`); return 'unsupported'; } let host: RemoteAgentHostHandoffResult; @@ -418,7 +431,7 @@ export class SelectAgentsFolderContribution extends Disposable implements IWorkb return undefined; } if (!host.sharesEditorWindowAgentHost()) { - this.notificationService.warn(localize('agentsHandoff.remoteSessionOtherHost', "The session of your remote window can't be opened in the Agents Window, because the Agents Window is connected to a different agent host on the tunnel's machine than your remote window.")); + this.notificationService.warn(localize('agentsHandoff.remoteSessionOtherHost', "The session of your remote window can't be opened in the Agents Window, because the Agents Window is connected to a different agent host on the remote machine than your remote window.")); return 'unsupported'; } const sessionResource = editorSessionResource.with({ scheme: sessionType }); diff --git a/src/vs/sessions/contrib/chat/test/browser/agentsWindowWorkspaceHandoff.test.ts b/src/vs/sessions/contrib/chat/test/browser/agentsWindowWorkspaceHandoff.test.ts index 572aff149dcd..9741c8e34230 100644 --- a/src/vs/sessions/contrib/chat/test/browser/agentsWindowWorkspaceHandoff.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/agentsWindowWorkspaceHandoff.test.ts @@ -41,7 +41,7 @@ suite('Agents Window workspace handoff', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); const folderUri = URI.file('/private/from-editor'); - function createHarness() { + function createHarness(whenStartupProvidersRegistered: Promise = Promise.resolve()) { const instantiationService = disposables.add(new TestInstantiationService()); const composerService = disposables.add(new NewSessionComposerService()); const activeSession = observableValue('activeSession', undefined); @@ -61,6 +61,7 @@ suite('Agents Window workspace handoff', () => { const states: WorkspaceHandoffState[] = []; const openingOptions: boolean[] = []; let providerReady = true; + let providerId = 'local'; let acceptsWorkspace = (_folder: URI) => true; let viewReady = true; let applies = true; @@ -94,7 +95,7 @@ suite('Agents Window workspace handoff', () => { if (resolutionError) { throw resolutionError; } - return providerReady && acceptsWorkspace(folder) ? { providerId: 'local', workspace: upcastPartial({}) } : undefined; + return providerReady && acceptsWorkspace(folder) ? { providerId, workspace: upcastPartial({}) } : undefined; }, })); const sessionsPartService = upcastPartial({ @@ -158,11 +159,12 @@ suite('Agents Window workspace handoff', () => { })); instantiationService.stub(ICommandService, upcastPartial({ executeCommand: async () => undefined })); instantiationService.stub(ILogService, upcastPartial({ warn: () => { }, error: () => { } })); - const handoff = disposables.add(instantiationService.createInstance(AgentsWindowWorkspaceHandoff)); + const handoff = disposables.add(instantiationService.createInstance(AgentsWindowWorkspaceHandoff, whenStartupProvidersRegistered)); return { handoff, composerService, sessionsService, sessionsPartService, activeSession, initialRestoreComplete, onWillSend, states, selections, notifications, openingOptions, storage, drafts, draftOptions, noWorkspaceSelections, notificationMessages, remoteRequests, set providerReady(value: boolean) { providerReady = value; }, + set providerId(value: string) { providerId = value; }, set acceptsWorkspace(value: (folder: URI) => boolean) { acceptsWorkspace = value; }, set viewReady(value: boolean) { viewReady = value; }, set applies(value: boolean) { applies = value; }, @@ -211,6 +213,30 @@ suite('Agents Window workspace handoff', () => { }); + test('resolves the folder only after startup providers register, so an earlier provider is not pinned', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const startupProviders = new DeferredPromise(); + const harness = createHarness(startupProviders.p); + // Cloud registers first and accepts local folders; the preferred local provider registers later. + harness.providerId = 'cloud'; + const opening = harness.open(true); + await timeout(500); + const selectionsBeforeRegistration = harness.selections.length; + harness.providerId = 'local'; + await startupProviders.complete(); + await opening; + assert.deepStrictEqual({ + selectionsBeforeRegistration, + stages: [...new Set(harness.states)], + providers: harness.selections.map(entry => entry.options?.providerId), + }, { + selectionsBeforeRegistration: 0, + stages: ['waitingForSetup', 'waitingForSessionView', 'waitingForProvider', 'applied'], + providers: ['local'], + }); + }); + }); + for (const content of [ { inputText: 'Keep this draft', attachments: [] }, { inputText: '', attachments: [toFileVariableEntry(URI.file('/already-attached'))] }, diff --git a/src/vs/sessions/contrib/chat/test/browser/appearanceTools.test.ts b/src/vs/sessions/contrib/chat/test/browser/appearanceTools.test.ts index 992ef3efa115..a002d10f3a61 100644 --- a/src/vs/sessions/contrib/chat/test/browser/appearanceTools.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/appearanceTools.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import { VSBuffer } from '../../../../../base/common/buffer.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Event } from '../../../../../base/common/event.js'; +import { ResourceSet } from '../../../../../base/common/map.js'; import { Schemas } from '../../../../../base/common/network.js'; import { constObservable } from '../../../../../base/common/observable.js'; import { basename, dirname, joinPath } from '../../../../../base/common/resources.js'; @@ -28,11 +29,12 @@ import { IsSessionsWindowContext } from '../../../../../workbench/common/context import { enumerateLocalCustomizationsForHarness } from '../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalCustomizations.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { CHAT_AUTOMATIONS_ENABLED_SETTING } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; +import { ChatConfiguration } from '../../../../../workbench/contrib/chat/common/constants.js'; import { ICustomizationSyncProvider } from '../../../../../workbench/contrib/chat/common/customizationHarnessService.js'; import { IAgentPluginService } from '../../../../../workbench/contrib/chat/common/plugins/agentPluginService.js'; import { PromptsConfig } from '../../../../../workbench/contrib/chat/common/promptSyntax/config/config.js'; import { PromptFileSource, PromptsType } from '../../../../../workbench/contrib/chat/common/promptSyntax/promptTypes.js'; -import { ILocalPromptPath, PromptsStorage } from '../../../../../workbench/contrib/chat/common/promptSyntax/service/promptsService.js'; +import { IPromptPath, PromptsStorage } from '../../../../../workbench/contrib/chat/common/promptSyntax/service/promptsService.js'; import { PromptFilesLocator } from '../../../../../workbench/contrib/chat/common/promptSyntax/utils/promptFilesLocator.js'; import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; import { ISessionsChatBackgroundService } from '../../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; @@ -42,16 +44,17 @@ import { GetThemeColorsTool } from '../../browser/getThemeColorsTool.js'; import { ScreenshotWindowTool } from '../../browser/screenshotWindowTool.js'; import { AgenticPromptsService, BUILTIN_SKILLS_URI } from '../../browser/promptsService.js'; import { AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, NEW_SESSION_ACTION_ID } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; -import '../../browser/chat.contribution.js'; +import '../../browser/chatBackground.contribution.js'; const appearanceToolsProperty = Registry.as(ConfigurationExtensions.Configuration).getConfigurationProperties()[AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING]; suite('Sessions - Appearance tools', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); - async function setup(enabled: boolean, workspaceSkill = false) { + async function setup(enabled: boolean, overrideSkill?: { name: string; storage: PromptsStorage.local | PromptsStorage.user }, htmlPreviewEnabled = false) { const configuration = new TestConfigurationService({ [AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING]: enabled, + [ChatConfiguration.HtmlPreviewEnabled]: htmlPreviewEnabled, [PromptsConfig.USE_AGENT_SKILLS]: true, }); disposables.add(configuration.onDidChangeConfigurationEmitter); @@ -68,25 +71,29 @@ suite('Sessions - Appearance tools', () => { contextKeyService: () => context, }, disposables); instantiationService.stub(IAgentPluginService, { plugins: constObservable([]) }); - const localSkills: ILocalPromptPath[] = workspaceSkill ? [{ - uri: joinPath(BUILTIN_SKILLS_URI, '../../test-workspace/.github/skills/generate-chat-background/SKILL.md'), - name: 'generate-chat-background', - storage: PromptsStorage.local, - type: PromptsType.skill, - source: PromptFileSource.ConfigWorkspace, - }] : []; + const localSkills: (IPromptPath & { source: PromptFileSource })[] = []; + if (overrideSkill) { + const metadata = { + uri: joinPath(BUILTIN_SKILLS_URI, '../../test-workspace/.github/skills', overrideSkill.name, 'SKILL.md'), + name: overrideSkill.name, + type: PromptsType.skill, + }; + localSkills.push(overrideSkill.storage === PromptsStorage.local + ? { ...metadata, storage: PromptsStorage.local, source: PromptFileSource.ConfigWorkspace } + : { ...metadata, storage: PromptsStorage.user, source: PromptFileSource.ConfigPersonal }); + } instantiationService.stubInstance(PromptFilesLocator, { createFilesUpdatedEvent: () => ({ event: Event.None, dispose: () => { } }), createAgentInstructionsUpdatedEvent: () => ({ event: Event.None, dispose: () => { } }), getSourceFoldersInDiscoveryOrder: async () => [], - listFilesWithSource: async (type, storage) => type === PromptsType.skill && storage === PromptsStorage.local - ? localSkills.map(({ uri }) => ({ uri, source: PromptFileSource.ConfigWorkspace })) + listFilesWithSource: async (type, storage) => type === PromptsType.skill + ? localSkills.filter(skill => skill.storage === storage).map(({ uri, source }) => ({ uri, source })) : [], findAgentSkills: async () => localSkills, }); await Promise.all([ - ...['automate', 'commit', 'generate-chat-background'].map(name => ({ name, uri: joinPath(BUILTIN_SKILLS_URI, name, 'SKILL.md') })), - ...localSkills.map(skill => ({ name: 'generate-chat-background', uri: skill.uri })), + ...['automate', 'commit', 'generate-chat-background', 'html-preview'].map(name => ({ name, uri: joinPath(BUILTIN_SKILLS_URI, name, 'SKILL.md') })), + ...localSkills.map(skill => ({ name: skill.name, uri: skill.uri })), ].map(({ name, uri }) => files.writeFile(uri, VSBuffer.fromString(`---\nname: ${name}\ndescription: A test skill.\n---\nTest instructions.`)))); const service = disposables.add(instantiationService.createInstance(AgenticPromptsService)); @@ -108,9 +115,58 @@ suite('Sessions - Appearance tools', () => { builtinFiles: (await service.listPromptFilesForStorage(PromptsType.skill, PromptsStorage.builtIn, CancellationToken.None)).map(file => file.name).sort(), forwarded: (await enumerateLocalCustomizationsForHarness(service, syncProvider, 'agent-host-copilot', CancellationToken.None, undefined)).map(file => basename(dirname(file.uri))).sort(), }); - return { service, configuration, context, instantiationService, setEnabled: (value: boolean) => setSetting(AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, value), setSetting, snapshot }; + return { service, configuration, context, instantiationService, syncProvider, setEnabled: (value: boolean) => setSetting(AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, value), setSetting, snapshot }; + } + + for (const initiallyEnabled of [false, true]) { + test(`the html-preview skill follows HTML and AI settings across all discovery surfaces (initially enabled: ${initiallyEnabled})`, async () => { + const fixture = await setup(false, undefined, initiallyEnabled); + const visible = async () => Object.fromEntries(Object.entries(await fixture.snapshot()).map(([key, names]) => [key, names?.includes('html-preview') === true])); + const snapshots = [await visible()]; + await fixture.setSetting(ChatConfiguration.HtmlPreviewEnabled, !initiallyEnabled); + snapshots.push(await visible()); + await fixture.setSetting(ChatConfiguration.HtmlPreviewEnabled, true); + snapshots.push(await visible()); + await fixture.setSetting(ChatAIDisabledSettingId, true); + snapshots.push(await visible()); + await fixture.setSetting(ChatAIDisabledSettingId, false); + snapshots.push(await visible()); + assert.deepStrictEqual(snapshots, [initiallyEnabled, !initiallyEnabled, true, false, true].map(enabled => ({ + skills: enabled, slashCommands: enabled, allFiles: enabled, builtinFiles: enabled, forwarded: enabled, + }))); + }); + } + + for (const storage of [PromptsStorage.local, PromptsStorage.user] as const) { + test(`an html-preview ${storage} override takes precedence without being removed by the rendering setting`, async () => { + const fixture = await setup(false, { name: 'html-preview', storage }, true); + const origins = async () => (await fixture.service.findAgentSkills(CancellationToken.None))?.filter(skill => skill.name === 'html-preview').map(skill => skill.storage); + const enabled = await origins(); + await fixture.setSetting(ChatConfiguration.HtmlPreviewEnabled, false); + assert.deepStrictEqual({ enabled, disabled: await origins() }, { enabled: [storage], disabled: [storage] }); + }); } + test('the html-preview skill preserves user disablement when preview rendering is toggled', async () => { + const fixture = await setup(false, undefined, true); + const uri = joinPath(BUILTIN_SKILLS_URI, 'html-preview', 'SKILL.md'); + const forwarded = async () => (await enumerateLocalCustomizationsForHarness(fixture.service, fixture.syncProvider, 'agent-host-copilot', CancellationToken.None, undefined)) + .filter(file => basename(dirname(file.uri)) === 'html-preview') + .map(file => ({ uri: file.uri.toString(), disabled: file.disabled })); + const enabled = await forwarded(); + fixture.service.setDisabledPromptFiles(PromptsType.skill, new ResourceSet([uri])); + const disabled = await forwarded(); + await fixture.setSetting(ChatConfiguration.HtmlPreviewEnabled, false); + const hidden = await forwarded(); + await fixture.setSetting(ChatConfiguration.HtmlPreviewEnabled, true); + assert.deepStrictEqual({ enabled, disabled, hidden, reenabled: await forwarded() }, { + enabled: [{ uri: uri.toString(), disabled: false }], + disabled: [{ uri: uri.toString(), disabled: true }], + hidden: [], + reenabled: [{ uri: uri.toString(), disabled: true }], + }); + }); + test('the automate skill follows automation and AI enablement across discovery, slash commands, and harness sync', async () => { const fixture = await setup(false); const visible = async () => { @@ -162,7 +218,7 @@ suite('Sessions - Appearance tools', () => { } test('does not suppress a workspace skill with the same name', async () => { - const t = await setup(false, true); + const t = await setup(false, { name: 'generate-chat-background', storage: PromptsStorage.local }); const getOrigin = async () => (await t.service.findAgentSkills(CancellationToken.None))?.find(skill => skill.name === 'generate-chat-background')?.storage; const disabledOrigin = await getOrigin(); await t.setEnabled(true); diff --git a/src/vs/sessions/contrib/chat/test/browser/artifactIntegrationPresentation.fixture.ts b/src/vs/sessions/contrib/chat/test/browser/artifactIntegrationPresentation.fixture.ts index a5b8dc39350a..65d151108ec6 100644 --- a/src/vs/sessions/contrib/chat/test/browser/artifactIntegrationPresentation.fixture.ts +++ b/src/vs/sessions/contrib/chat/test/browser/artifactIntegrationPresentation.fixture.ts @@ -70,7 +70,7 @@ interface IArtifactFixtureOptions { /** Index of a group artifact pinned into a pill of its own. */ readonly pinned?: number; readonly openGroup?: boolean; - /** Index of the group row to open details for from the open group dropdown. */ + /** Index of the group row whose first status section, or Details section, opens its details from the open group dropdown. */ readonly openGroupDetails?: number; } @@ -233,7 +233,7 @@ function pullRequest(state: PullRequestState, options: IPullRequestFixtureOption ], merged: [section('checks', '6/6', Codicon.passFilledCompact, chartsGreen, 'All 6 checks passed')], closed: [], - loading: [section('availability', 'Loading status', Codicon.sync, chartsForeground)], + loading: [section('availability', 'Loading status', Codicon.circleFilled, chartsForeground)], unavailable: [], }; const automationOptions: readonly ArtifactAutomationOption[] = [ @@ -251,8 +251,8 @@ function pullRequest(state: PullRequestState, options: IPullRequestFixtureOption authentication: state === 'unavailable' ? { enabled: true } : undefined, actions: [ { id: 'markReady', label: 'Mark Ready', iconId: Codicon.gitPullRequest.id, kind: 'code' }, - { id: 'fixChecks', label: 'Fix Checks', iconId: Codicon.tools.id, kind: 'prompt' }, - { id: 'addressComments', label: 'Address Comments', iconId: Codicon.commentDiscussion.id, kind: 'prompt' }, + { id: 'fixChecks', label: 'Fix Checks', iconId: Codicon.lightbulb.id, kind: 'prompt' }, + { id: 'addressComments', label: 'Address Comments', iconId: Codicon.comment.id, kind: 'prompt' }, { id: 'merge', label: 'Merge', iconId: Codicon.gitMerge.id, kind: 'code' }, { id: 'refresh', label: 'Refresh Status', iconId: Codicon.refresh.id, kind: 'code' }, ], @@ -611,12 +611,16 @@ async function render(context: ComponentFixtureContext, data: IArtifactFixtureDa row.content.appendChild(widget.element); if (openDetails) { const sectionIndex = data.contribution.view.sections.findIndex(section => section.detailsId === openDetails); - const button = openDetails === 'actions' ? widget.element.querySelector('.artifact-integration-pill > .chat-pill-button') - : widget.element.querySelectorAll('.artifact-pill-sections [role="button"]')[sectionIndex]; - if (!button) { + const main = widget.element.querySelector('.artifact-integration-pill > .chat-pill-button'); + const section = widget.element.querySelectorAll('.artifact-pill-sections [role="button"]')[sectionIndex]; + if (openDetails === 'actions' && main) { + // The whole artifact's details, which its Details section opens while it has no status sections. + controller.toggle(presentation, main); + } else if (section) { + section.click(); + } else { throw new Error(`Missing artifact details control: ${openDetails}`); } - button.click(); await Promise.resolve(); const detailsId = data.contribution.view.main?.detailsId; const expectedDetails = detailsId ? data.details[detailsId] : undefined; @@ -702,7 +706,7 @@ async function renderGroup( rows[0]?.classList.add('hovered'); return; } - rows[options.openGroupDetails]?.querySelector('.artifact-group-row-main')?.click(); + rows[options.openGroupDetails]?.querySelector('.artifact-group-row-status')?.click(); await waitForFixtureDomCondition(container, () => !!container.querySelector('.artifact-integration-panel h2'), disposableStore); } diff --git a/src/vs/sessions/contrib/chat/test/browser/chatInput.fixture.ts b/src/vs/sessions/contrib/chat/test/browser/chatInput.fixture.ts index 9705d0a78dd8..35a2a6553912 100644 --- a/src/vs/sessions/contrib/chat/test/browser/chatInput.fixture.ts +++ b/src/vs/sessions/contrib/chat/test/browser/chatInput.fixture.ts @@ -28,8 +28,9 @@ import '../../../../../workbench/contrib/sessions/browser/chat/media/chatView.cs import '../../../../../workbench/contrib/sessions/browser/chat/media/chatInput.css'; /** - * Wraps the fixture context in `.agent-sessions-workbench > .part.sessionspart`, returning the sessions part as the input container by default. - * With a background, adds `.has-chat-background` and returns a nested `.chat-view` as the input container. + * Wraps the fixture context in `.agent-sessions-workbench > .part.sessionspart > .sessions-chat`, the root a session chat styles + * itself from, returning that root as the input container by default. + * With a background, adds `.has-chat-background` and returns a nested `.chat-view.sessions-chat` as the input container. */ function sessionsWindowContext(context: ComponentFixtureContext, withBackground = false): ComponentFixtureContext { context.container.classList.add('agent-sessions-workbench'); @@ -37,13 +38,16 @@ function sessionsWindowContext(context: ComponentFixtureContext, withBackground sessionsPart.classList.add('part', 'sessionspart', 'sessions-chat-surface'); context.container.appendChild(sessionsPart); if (!withBackground) { - return { ...context, container: sessionsPart }; + const chat = document.createElement('div'); + chat.classList.add('sessions-chat'); + sessionsPart.appendChild(chat); + return { ...context, container: chat }; } sessionsPart.classList.add('has-chat-background'); sessionsPart.style.backgroundImage = 'linear-gradient(135deg, var(--vscode-editor-background), var(--vscode-textLink-foreground))'; const chatView = document.createElement('div'); - chatView.classList.add('chat-view'); + chatView.classList.add('chat-view', 'sessions-chat'); sessionsPart.appendChild(chatView); return { ...context, container: chatView }; } @@ -159,7 +163,7 @@ export default defineThemedFixtureGroup({ path: 'sessions/chat/input/' }, { render: async context => { const sessionsContext = sessionsWindowContext(context); const chatView = document.createElement('div'); - chatView.classList.add('chat-view-chat', 'experimental-session-composer'); + chatView.classList.add('chat-view', 'sessions-chat', 'chat-view-chat', 'experimental-session-composer'); sessionsContext.container.appendChild(chatView); await renderChatInput({ ...sessionsContext, container: chatView }, { models: shortNameModels, diff --git a/src/vs/sessions/contrib/chat/test/browser/chatView.fixture.ts b/src/vs/sessions/contrib/chat/test/browser/chatView.fixture.ts index d53e1b2f8b0d..4ba7758ec86a 100644 --- a/src/vs/sessions/contrib/chat/test/browser/chatView.fixture.ts +++ b/src/vs/sessions/contrib/chat/test/browser/chatView.fixture.ts @@ -107,25 +107,47 @@ const stickyAssistantResponse = [ 'Switch between image, Codicons, and no background without rebuilding the sticky row or changing its keyboard and pointer behavior.', ].join('\n'); -async function renderChatView(context: ComponentFixtureContext, withBackground: boolean, options: IChatWidgetFixtureOptions, phoneLayout = false, experimentalComposerLayout = false): Promise { +/** + * Where a session chat shows: the Sessions part of the Agents window; the chat part of a chat window, an editor part of the + * Agents window's chat windows; or the chat part of an editor window, an editor part in a window without the Agents + * window's classes. The chat styles itself, so it looks the same in all of them. + */ +type ChatViewHost = 'agentsWindow' | 'chatWindow' | 'editorWindow'; + +async function renderChatView(context: ComponentFixtureContext, withBackground: boolean, options: IChatWidgetFixtureOptions, phoneLayout = false, experimentalComposerLayout = false, host: ChatViewHost = 'agentsWindow'): Promise { const { container, disposableStore } = context; const { renderChatWidget } = await import('../../../../../workbench/test/browser/componentFixtures/chat/chatWidget.fixture.js'); const width = options.width ?? fixtureWidth; const height = options.height ?? fixtureHeight; container.style.width = `${width}px`; container.style.height = `${height}px`; - container.classList.add('monaco-workbench', 'agent-sessions-workbench'); + container.classList.add('monaco-workbench'); + container.classList.toggle('agent-sessions-workbench', host !== 'editorWindow'); container.classList.toggle('phone-layout', phoneLayout); - const part = withBackground - ? createChatBackgroundPart(container, disposableStore) - : dom.append(container, dom.$('.part.sessionspart.sessions-chat-surface')); + // A chat part is an editor part in a cell of its window's grid, never the window's own editor part + const cell = host !== 'agentsWindow' ? dom.append(container, dom.$('.fixture-chat-part-cell')) : undefined; + if (cell) { + cell.style.width = '100%'; + cell.style.height = '100%'; + } + const part = cell + ? dom.append(cell, dom.$('.part.editor.sessions-chat-surface')) + : withBackground + ? createChatBackgroundPart(container, disposableStore) + : dom.append(container, dom.$('.part.sessionspart.sessions-chat-surface')); part.style.position = 'relative'; part.style.width = '100%'; part.style.height = '100%'; part.style.backgroundColor = asCssVariable(activeSessionViewBackground); + // A chat part shows the chat in its editor + const chatParent = host !== 'agentsWindow' ? dom.append(part, dom.$('.session-chat-view-editor.sessions-window-host')) : part; + if (chatParent !== part) { + chatParent.style.width = '100%'; + chatParent.style.height = '100%'; + } - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(chatParent, dom.$('.chat-view.sessions-chat')); chatView.classList.toggle('chat-view-chat', experimentalComposerLayout); chatView.classList.toggle('experimental-session-composer', experimentalComposerLayout); chatView.style.setProperty('--session-view-background', asCssVariable(activeSessionViewBackground)); @@ -198,7 +220,7 @@ function renderStatusPills(inputPart: ChatInputPart, instantiationService: IInst row.observe(pills.element, () => pills.getPillElements()); } -async function renderAssistantResponse(context: ComponentFixtureContext, withBackground: boolean): Promise { +async function renderAssistantResponse(context: ComponentFixtureContext, withBackground: boolean, host?: ChatViewHost): Promise { const { disposableStore } = context; await renderChatView(context, withBackground, { messages: [{ @@ -206,7 +228,7 @@ async function renderAssistantResponse(context: ComponentFixtureContext, withBac assistant: [{ kind: 'markdown', text: assistantResponse }], }], decorateInputPart: (inputPart, instantiationService) => renderStatusPills(inputPart, instantiationService, disposableStore), - }); + }, false, false, host); } async function renderStickyProgress(context: ComponentFixtureContext, options: { pills?: boolean; inline?: boolean; background?: boolean; image?: boolean; pet?: boolean }): Promise { @@ -623,6 +645,18 @@ export default defineThemedFixtureGroup({ path: 'sessions/chat/view/' }, { expectedVisualDescriptions: ['The Agents chat without a wallpaper keeps the assistant response unboxed. The heading, Markdown table, code editor, and response footer use the normal transcript alignment, while the user request and composer retain their established surfaces.'], render: context => renderAssistantResponse(context, false), }), + AssistantResponseInChatWindow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The same chat as AssistantResponsePlain, shown in the chat part of a chat window: the chat styles itself, so its transcript, response and composer look exactly as in the Agents window.'], + render: context => renderAssistantResponse(context, false, 'chatWindow'), + }), + AssistantResponseInEditorWindow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The same chat as AssistantResponseInChatWindow, shown in the chat part of an editor window, without any class of the Agents window: it looks exactly as in a chat window.'], + render: context => renderAssistantResponse(context, false, 'editorWindow'), + }), RequestLinkKeyboardFocus: defineComponentFixture({ labels: { kind: 'screenshot' }, additionalThemes: ['darkHighContrast', 'lightHighContrast'], diff --git a/src/vs/sessions/contrib/chat/test/browser/chatView.test.ts b/src/vs/sessions/contrib/chat/test/browser/chatView.test.ts index 592db124479f..a01314f869ec 100644 --- a/src/vs/sessions/contrib/chat/test/browser/chatView.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/chatView.test.ts @@ -72,7 +72,8 @@ import { ISessionsProvidersChangeEvent, ISessionsProvidersService, observeSessio import { ISessionHost } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { SessionsChatBackgroundRenderer, SessionsChatBackgroundReplica } from '../../../../../workbench/contrib/sessions/browser/chatBackgroundRenderer.js'; -import { ISessionsChatBackground } from '../../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; +import { ISessionsChatBackground, ISessionsChatBackgroundService } from '../../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; +import { DefaultChatViewFactory } from '../../../../../workbench/contrib/sessions/browser/chat/defaultChatViewFactory.js'; import { AGENTS_CENTERED_CONTENT_MAX_WIDTH } from '../../../../../workbench/contrib/sessions/common/layoutConstants.js'; import { ChatView, EXPERIMENTAL_SESSION_CHAT_INPUT_TRAILING_SPACE, findInitialTranscriptContextEntry, getChatRespondent, getInputOnlyProgressMessage, getInputOnlyResponseState, getInputOnlyResponseText, IInputOnlyStatus, needsConversationForInput, findTranscriptContextEntry, getSessionChatItemHorizontalPadding, getSessionComparisonRequestSummary, getTranscriptProgress, isFocusChatPillsKeyDown, NewChatView, shouldRenderRunningSessionSecondaryToolbar, shouldShowSessionChatTip, shouldShowTranscriptPreparationCompletion, shouldShowTranscriptPreparationProgress } from '../../../../../workbench/contrib/sessions/browser/chat/chatView.js'; import { SessionsChatViewStateService } from '../../../../../workbench/contrib/sessions/browser/chat/chatViewStateService.js'; @@ -90,7 +91,7 @@ import '../../../../../workbench/browser/media/style.css'; import '../../../../../workbench/contrib/chat/browser/widget/chatContentParts/media/chatAgentMergeContent.css'; import '../../../../../workbench/contrib/chat/browser/widget/chatContentParts/media/chatRequestOrigin.css'; import { ISelectWorkspaceOptions } from '../../../../../workbench/services/sessions/common/workspaceSelection.js'; -import { AbstractChatView } from '../../../../../workbench/contrib/sessions/browser/parts/chatView.js'; +import { AbstractChatView, IChatViewBackgroundReplica } from '../../../../../workbench/contrib/sessions/browser/parts/chatView.js'; import { SessionView } from '../../../../../workbench/contrib/sessions/browser/parts/sessionView.js'; import { IChatViewFactory } from '../../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; import { createSessionViewTestServices, createTestActiveSession, testPaneOf } from '../../../../test/browser/sessionViewTestUtils.js'; @@ -166,7 +167,7 @@ suite('Sessions - Chat View', () => { disposables.add(toDisposable(() => workbench.remove())); workbench.style.cssText = 'position: fixed; top: 0; left: 0; --vscode-spacing-size120: 12px; --vscode-spacing-size20: 2px; --vscode-spacing-size40: 4px; --vscode-spacing-size60: 6px; --vscode-spacing-size80: 8px; --vscode-spacing-size240: 24px; --vscode-strokeThickness: 1px;'; const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const view = dom.append(part, dom.$('.chat-view-chat')); + const view = dom.append(part, dom.$('.chat-view-chat.sessions-chat')); const session = dom.append(view, dom.$('.interactive-session.prompt-timeline-host.prompt-timeline-with-rail')); session.style.cssText = 'width: 480px; height: 300px; --prompt-timeline-bottom: 100px;'; const list = dom.append(session, dom.$('.interactive-list')); @@ -286,7 +287,7 @@ suite('Sessions - Chat View', () => { const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); const session = dom.append(part, dom.$('.session-view')); const group = dom.append(session, dom.$('.chat-group-view.active-group')); - const view = dom.append(group, dom.$('.chat-view')); + const view = dom.append(group, dom.$('.chat-view.sessions-chat')); const chat = dom.append(view, dom.$('.interactive-session')); const list = dom.append(chat, dom.$('.interactive-list')); const request = dom.append(list, dom.$('.interactive-item-container.interactive-request')); @@ -376,7 +377,7 @@ suite('Sessions - Chat View', () => { const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); const session = dom.append(part, dom.$('.session-view.is-active')); const group = dom.append(session, dom.$('.chat-group-view.active-group')); - const view = dom.append(group, dom.$('.chat-view')); + const view = dom.append(group, dom.$('.chat-view.sessions-chat')); const chat = dom.append(view, dom.$('.interactive-session')); const list = dom.append(chat, dom.$('.interactive-list')); list.style.transition = 'none'; @@ -590,7 +591,7 @@ suite('Sessions - Chat View', () => { for (const inputOnly of [false, true]) { test(`reads the widget offset only for a visible external banner and keeps input sizing independent for input-only hosts: ${inputOnly}`, () => { - const element = dom.$('.chat-view-chat'); + const element = dom.$('.chat-view-chat.sessions-chat'); const banner = dom.append(element, dom.$('.external-session-banner.hidden')); const progress = dom.append(element, dom.$('.monaco-progress-container')); const widgetContainer = dom.append(element, dom.$('.chat-view-widget')); @@ -637,7 +638,7 @@ suite('Sessions - Chat View', () => { } test('reads the widget offset only for a visible external banner or while showing only the input, and lays out the input with its room to grow', () => { - const element = dom.$('.chat-view-chat'); + const element = dom.$('.chat-view-chat.sessions-chat'); const banner = dom.append(element, dom.$('.external-session-banner.hidden')); const progress = dom.append(element, dom.$('.monaco-progress-container')); const widgetContainer = dom.append(element, dom.$('.chat-view-widget')); @@ -1134,7 +1135,7 @@ suite('Sessions - Chat View', () => { part.style.position = 'relative'; part.style.width = '600px'; part.style.height = '400px'; - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const interactiveList = dom.append(session, dom.$('.interactive-list')); const list = dom.append(interactiveList, dom.$('.monaco-list')); @@ -3223,6 +3224,44 @@ suite('Sessions - Chat View', () => { }); }); + test('only measures the surface on refresh when it shows codicons', async () => { + const clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth')!; + const measureRefreshes = async (background: ISessionsChatBackground | undefined) => { + const workbench = dom.$('.monaco-workbench.agent-sessions-workbench'); + const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); + dom.getWindow(workbench).document.body.appendChild(workbench); + const store = new DisposableStore(); + store.add(toDisposable(() => workbench.remove())); + const renderer = store.add(new SessionsChatBackgroundRenderer(part, true, () => 0.5)); + renderer.setBackground(background); + await timeout(20); + let reads = 0; + Object.defineProperty(part, 'clientWidth', { configurable: true, get() { reads++; return clientWidth.get!.call(this); } }); + dom.append(part, dom.$('.interactive-item-container')); + await timeout(20); + part.dispatchEvent(new Event('scroll')); + await timeout(20); + store.dispose(); + return reads; + }; + + assert.deepStrictEqual({ + none: await measureRefreshes(undefined), + image: await measureRefreshes({ + kind: 'image', + backgroundImage: 'url("file:///textures/kirby.png")', + backgroundRepeat: 'no-repeat', + backgroundSize: 'auto', + backgroundPosition: 'right bottom', + }), + measuresCodicons: await measureRefreshes({ kind: 'codicons' }) > 0, + }, { + none: 0, + image: 0, + measuresCodicons: true, + }); + }); + for (const interactive of [false, true]) { test(`only writes Codicon opacity when it changes (${interactive ? 'interactive' : 'decorative'})`, async () => { const codicons = { kind: 'codicons' } as const; @@ -3384,13 +3423,13 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-background', '#202020'); workbench.style.setProperty('--vscode-chat-requestBubbleBackground', 'rgba(255, 255, 255, 0.3)'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const request = dom.append(session, dom.$('.interactive-item-container.interactive-request')); const value = dom.append(request, dom.$('.value')); const bubble = dom.append(value, dom.$('.rendered-markdown')); const plainPart = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const plainChatView = dom.append(plainPart, dom.$('.chat-view')); + const plainChatView = dom.append(plainPart, dom.$('.chat-view.sessions-chat')); const plainSession = dom.append(plainChatView, dom.$('.interactive-session')); const plainRequest = dom.append(plainSession, dom.$('.interactive-item-container.interactive-request')); const plainValue = dom.append(plainRequest, dom.$('.value')); @@ -3418,7 +3457,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-background', '#202020'); workbench.style.setProperty('--vscode-chat-requestBubbleBackground', 'rgba(255, 255, 255, 0.3)'); const appendOrigin = (part: HTMLElement) => { - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); return dom.append(chatView, dom.$('.chat-request-origin')); }; const backgroundPart = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); @@ -3454,7 +3493,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-background', '#202020'); workbench.style.setProperty('--vscode-chat-requestBubbleBackground', 'rgba(255, 255, 255, 0.3)'); const appendAttachment = (part: HTMLElement) => { - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const request = dom.append(session, dom.$('.interactive-item-container.interactive-request')); const value = dom.append(request, dom.$('.value')); @@ -3487,7 +3526,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-background', '#202020'); workbench.style.setProperty('--vscode-chat-statusBackground', 'rgba(255, 255, 255, 0.3)'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const request = dom.append(session, dom.$('.interactive-item-container.interactive-request')); const actionRequest = disposables.add(new ChatActionRequestContentPart({ @@ -3527,7 +3566,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-background', '#202020'); workbench.style.setProperty('--vscode-chat-requestBubbleBackground', 'rgba(255, 255, 255, 0.3)'); const appendEditInput = (part: HTMLElement) => { - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const request = dom.append(session, dom.$('.interactive-item-container.interactive-request.editing')); const editContainer = dom.append(request, dom.$('.chat-edit-input-container')); @@ -3571,7 +3610,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--vscode-spacing-size80', '8px'); workbench.style.setProperty('--vscode-fontSize-label3', '10px'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const chatView = dom.append(part, dom.$('.chat-view-chat')); + const chatView = dom.append(part, dom.$('.chat-view-chat.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const request = dom.append(session, dom.$('.interactive-item-container.interactive-request.editing')); const editContainer = dom.append(request, dom.$('.chat-edit-input-container')); @@ -3621,7 +3660,7 @@ suite('Sessions - Chat View', () => { const workbench = dom.$('.monaco-workbench.agent-sessions-workbench'); workbench.style.setProperty('--session-view-background', '#202020'); const appendCheckpointRows = (part: HTMLElement) => { - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const checkpoint = dom.append(session, dom.$('.checkpoint-container')); const restore = dom.append(session, dom.$('.checkpoint-restore-container')); @@ -3681,14 +3720,14 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--vscode-spacing-size240', '24px'); workbench.style.setProperty('--vscode-spacing-size320', '32px'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const response = dom.append(session, dom.$('.interactive-item-container.interactive-response')); response.style.width = '600px'; const value = dom.append(response, dom.$('.value')); const footer = dom.append(response, dom.$('.chat-footer-toolbar')); const plainPart = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const plainChatView = dom.append(plainPart, dom.$('.chat-view')); + const plainChatView = dom.append(plainPart, dom.$('.chat-view.sessions-chat')); const plainSession = dom.append(plainChatView, dom.$('.interactive-session')); const plainResponse = dom.append(plainSession, dom.$('.interactive-item-container.interactive-response')); const createHighContrastResponse = (themeClass: 'hc-black' | 'hc-light') => { @@ -3703,7 +3742,7 @@ suite('Sessions - Chat View', () => { highContrastWorkbench.style.setProperty('--vscode-strokeThickness', '1px'); highContrastWorkbench.style.setProperty('--vscode-contrastBorder', '#ff0000'); const highContrastPart = dom.append(highContrastWorkbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const highContrastChatView = dom.append(highContrastPart, dom.$('.chat-view')); + const highContrastChatView = dom.append(highContrastPart, dom.$('.chat-view.sessions-chat')); const highContrastResponse = dom.append(highContrastChatView, dom.$('.interactive-item-container.interactive-response')); dom.getWindow(highContrastWorkbench).document.body.appendChild(highContrastWorkbench); return { highContrastWorkbench, highContrastResponse }; @@ -3800,7 +3839,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--vscode-button-secondaryBorder', '#808080'); workbench.style.setProperty('--vscode-strokeThickness', '1px'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view.chat-view-chat')); + const chatView = dom.append(part, dom.$('.chat-view.chat-view-chat.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const secondaryToolbar = dom.append(session, dom.$('.chat-secondary-toolbar')); const inputPart = dom.append(session, dom.$('.interactive-input-part')); @@ -3912,7 +3951,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--vscode-toolbar-activeBackground', 'rgba(0, 0, 0, 0.2)'); workbench.style.setProperty('--vscode-toolbar-hoverBackground', 'rgba(0, 0, 0, 0.12)'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); chatView.style.setProperty('--vscode-chat-list-background', '#ffffff'); const newChatWidget = dom.append(chatView, dom.$('.sessions-chat-widget')); const newChatContent = dom.append(newChatWidget, dom.$('.new-chat-widget-content')); @@ -3934,7 +3973,7 @@ suite('Sessions - Chat View', () => { newSessionView.style.setProperty('--vscode-button-secondaryBackground', 'rgba(0, 0, 0, 0)'); const newSessionViewContent = dom.append(newSessionView, dom.$('.session-view-content')); // Unlike the session chat, the new-session view has no chat list to set `--vscode-chat-list-background`. - const productionNewChatView = dom.append(newSessionViewContent, dom.$('.chat-view.chat-view-new')); + const productionNewChatView = dom.append(newSessionViewContent, dom.$('.chat-view.chat-view-new.sessions-chat')); const productionNewChatWidget = dom.append(productionNewChatView, dom.$('.sessions-chat-widget')); const productionNewChatContainer = dom.append(productionNewChatWidget, dom.$('.new-chat-widget-container')); const productionBottomContainer = dom.append(productionNewChatContainer, dom.$('.new-chat-bottom-container')); @@ -3955,7 +3994,7 @@ suite('Sessions - Chat View', () => { const peerExperimentalContent = dom.append(peerNewChatContainer, dom.$('.new-chat-widget-content.experimental-new-session-composer')); const peerExperimentalOptions = dom.append(peerExperimentalContent, dom.$('.new-chat-session-options')); const plainPart = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const plainChatView = dom.append(plainPart, dom.$('.chat-view')); + const plainChatView = dom.append(plainPart, dom.$('.chat-view.sessions-chat')); const plainSession = dom.append(plainChatView, dom.$('.interactive-session')); const plainSecondaryToolbar = dom.append(plainSession, dom.$('.chat-secondary-toolbar')); const plainSecondaryAction = dom.append(plainSecondaryToolbar, dom.$('.action-label')); @@ -4092,7 +4131,7 @@ suite('Sessions - Chat View', () => { test('keeps selected chat rows transparent in dark themes', () => { const workbench = dom.$('.monaco-workbench.vs-dark.agent-sessions-workbench'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const interactiveList = dom.append(chatView, dom.$('.interactive-list')); const list = dom.append(interactiveList, dom.$('.monaco-list')); const scrollable = dom.append(list, dom.$('.monaco-scrollable-element')); @@ -4136,7 +4175,7 @@ suite('Sessions - Chat View', () => { disposables.add(toDisposable(() => workbench.remove())); workbench.style.cssText = 'width: 500px; --vscode-spacing-size40: 4px; --vscode-spacing-size160: 16px; --vscode-spacing-size240: 24px;'; const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); session.style.height = '400px'; const list = dom.append(session, dom.$('.interactive-list')); @@ -4159,7 +4198,7 @@ suite('Sessions - Chat View', () => { const view: IStickyBackgroundChatView = Object.assign(Object.create(ChatView.prototype), { _widget: widget, _stickyScrollBackgroundReplica: { value: undefined }, - chatBackgroundService: { getBackground: () => background }, + _background: { hasBackground: () => !!background }, _chatItemHorizontalPadding: getSessionChatItemHorizontalPadding(false), }); const inputBottom = input.getBoundingClientRect().bottom; @@ -4202,7 +4241,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--session-view-content-horizontal-padding', `${padding}px`); } const part = dom.append(workbench, dom.$('.part.sessionspart')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session.chat-floating-persistent-content')); session.style.height = '400px'; const response = dom.append(session, dom.$('.interactive-item-container.interactive-response')); @@ -4264,7 +4303,7 @@ suite('Sessions - Chat View', () => { workbench.style.setProperty('--vscode-strokeThickness', '1px'); workbench.style.setProperty('--vscode-contrastBorder', '#ffffff'); const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session.chat-floating-persistent-content')); const response = dom.append(session, dom.$('.interactive-item-container.interactive-response')); const inputPart = dom.append(session, dom.$('.interactive-input-part')); @@ -4389,7 +4428,7 @@ suite('Sessions - Chat View', () => { const part = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface.has-chat-background')); const plainPart = dom.append(workbench, dom.$('.part.sessionspart.sessions-chat-surface')); const createStickyRequest = (parent: HTMLElement) => { - const chatView = dom.append(parent, dom.$('.chat-view')); + const chatView = dom.append(parent, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const interactiveList = dom.append(session, dom.$('.interactive-list')); const list = dom.append(interactiveList, dom.$('.monaco-list')); @@ -4448,7 +4487,7 @@ suite('Sessions - Chat View', () => { const workbench = dom.$('.monaco-workbench.vs-dark.agent-sessions-workbench'); const createShadows = (hasBackground: boolean) => { const part = dom.append(workbench, dom.$(`.part.sessionspart.sessions-chat-surface${hasBackground ? '.has-chat-background' : ''}`)); - const chatView = dom.append(part, dom.$('.chat-view')); + const chatView = dom.append(part, dom.$('.chat-view.sessions-chat')); const session = dom.append(chatView, dom.$('.interactive-session')); const interactiveList = dom.append(session, dom.$('.interactive-list')); const list = dom.append(interactiveList, dom.$('.monaco-list')); @@ -4791,8 +4830,14 @@ suite('Sessions - Chat View', () => { }; const codicons = { kind: 'codicons' } as const; const { store, chatView, stickyContainer, sourceRenderer } = createBackgroundReplicaHost(image); - const replicaSlot = store.add(new MutableDisposable()); + const replicaSlot = store.add(new MutableDisposable()); let background: ISessionsChatBackground | undefined = image; + const factory = new class extends DefaultChatViewFactory { + get background() { return this.viewOptions.background; } + }(upcastPartial({ + onDidChangeBackground: VSCodeEvent.None, + getBackground: () => background, + })); let stickyScrollDomNode: HTMLElement | undefined = stickyContainer; let paddingUpdates = 0; const view = Object.assign(Object.create(ChatView.prototype), { @@ -4803,7 +4848,7 @@ suite('Sessions - Chat View', () => { setPersistentContentHeight: () => { }, }, _stickyScrollBackgroundReplica: replicaSlot, - chatBackgroundService: { getBackground: () => background }, + _background: factory.background, _chatItemHorizontalPadding: getSessionChatItemHorizontalPadding(true), }) as IStickyBackgroundChatView; diff --git a/src/vs/sessions/contrib/chat/test/browser/htmlPreview.scenarios.md b/src/vs/sessions/contrib/chat/test/browser/htmlPreview.scenarios.md new file mode 100644 index 000000000000..d39bba29982f --- /dev/null +++ b/src/vs/sessions/contrib/chat/test/browser/htmlPreview.scenarios.md @@ -0,0 +1,88 @@ +# HTML response previews + +## Investigation + +- [Claude custom visuals in chat and Cowork](https://support.claude.com/en/articles/13979539-custom-visuals-in-chat-and-cowork) are generated HTML rendered inline, distinct from persistent artifacts. They can support charts, diagrams, comparisons, and interactive controls. +- [ChatGPT code blocks](https://help.openai.com/en/articles/20001246-working-with-writing-blocks-and-code-blocks-in-chatgpt) separate Code from Preview, render supported HTML and other formats in a sandbox, and can request permission for outside resources. +- [ChatGPT Intelligent UI](https://help.openai.com/en/articles/20001598-intelligent-ui-in-chatgpt) also composes text, visuals, and interactive elements directly in responses. Its public documentation describes behavior, not an implementation protocol to reuse. +- [Claude Code: The unreasonable effectiveness of HTML](https://claude.dev/blog/using-claude-code-the-unreasonable-effectiveness-of-html/) emphasizes navigable reports, plans, reviews, and reusable files. The larger reading surface, fragment links, sanitized export, and authoring skill support that workflow; its JavaScript-driven editors remain outside this static preview's scope. + +The reusable pattern is an explicit content boundary plus an isolated renderer, not relaxing Markdown sanitization. These sources document product behavior; they do not establish the vendors' private rendering or sandbox implementations. + +## Implemented scope + +The Agents window opts into a shared chat renderer for **explicit, closed `html-preview` fenced blocks in assistant responses**. The `chat.htmlPreview.enabled` setting defaults to `false`, so these blocks display as source code until it is enabled; changing it updates existing responses without reloading. Previously opened expanded editors remain independent snapshots. Ordinary `html` fences, user messages, raw HTML outside a fence, annotated file edits, and other chat surfaces keep their existing behavior. Providers do not need a new protocol response type: the original Markdown remains the persisted, copied, exported, and accessible response. + +The preview displays sanitized HTML, CSS, simple inline SVG, embedded PNG/JPEG/GIF/WebP images, native `details`/`summary` disclosures, and links to sections within the document. Fragment-only HTML anchors are normalized; malformed fragments, external navigation, and SVG links are removed. IDs that collide with document/form properties are namespaced along with fragment, ARIA, CSS and SVG references, preserving DOM-clobbering protections. Each preview uses a script-disabled VS Code webview with no local resource roots or service worker, disabled forms and command URIs, and a restrictive Content Security Policy. Active markup, foreign SVG content, and webview context attributes are removed. CSS is confined to the webview and cannot style the workbench. Network resources are blocked, including CSS imports and remote images. + +This is deliberately **not an arbitrary JavaScript/React app runtime**. Scripts, external libraries, fonts, external links, forms, and filesystem access are unavailable. Accessibility Help documents these restrictions; ordinary previews do not show a separate limitation row. The built-in [html-preview skill](../../../../skills/html-preview/SKILL.md) provides on-demand authoring guidance for visual reports, plans, reviews, comparisons, and mockups in any workspace. Its discovery, slash-command availability, and harness forwarding follow `chat.htmlPreview.enabled` and `chat.disableAIFeatures`, including live changes. Existing customization disablement is preserved; same-named user/workspace skills retain their normal precedence. The renderer does not require the skill to be invoked, and its instructions are not injected into every turn. Existing AI visibility and chat accessibility settings continue to apply; the rendering preference adds no runtime permission or policy. + +Inline previews blend into the response with no title bar, permanent buttons, border, or default background. Their typography follows chat, their default document padding is zero, and authored inner surfaces are preserved. Right-click or focus the preview and press Shift+F10 to open its context menu. **Show Source** uses the existing code editor and its copy actions. Transcript Find searches original HTML and reveals matching source without taking focus; it excludes preview controls from response-match locations. **Open Preview** opens an independent, script-disabled editor with Find, Accessibility Help, and an Accessible View of the document text; its reading position survives switching editor tabs. Expanded and exported documents retain their own background and padding. The expanded editor is a snapshot of that response; close it and reopen from chat after a window reload. Chat Accessibility Help documents these actions, and Chat Accessible View retains the original response. Webview failures and blocks over 64,000 UTF-16 code units explicitly fall back to source. The existing overall Markdown rendering limit is unchanged. Inline previews grow to their full content height, without a maximum height or custom scroll containment, and scroll with the transcript using standard webview wheel forwarding. Authored content remains directly under `body`, preserving grid/flex layouts and expanded-editor sticky positioning. An opt-in webview measurement rounds up natural height and includes horizontal scrollbar space using the existing height message, without new size fields or changes to other webviews' dimensions. + +**Save HTML...** asks for a filename and exports the sanitized document, including its restrictive CSP and the current theme variables it actually references. The exported file can be read offline without VS Code. Original scripts, unsupported controls, and external resource attributes are not exported; external CSS resource requests remain blocked by CSP. The original source remains available separately through Show Source. Successful saves open through the existing HTML file-artifact path on desktop, respecting editor associations; other resource schemes and web hosts use the normal editor. Saving does not fabricate an agent-authored artifact registration or send a new prompt. The saved file can be attached to a later chat and revised using normal file tools. + +## Try it + +Enable `chat.htmlPreview.enabled`, then ask an agent to respond using an `html-preview` fence, or invoke the built-in `/html-preview` skill when it is enabled for your agent: + +> Create a visual implementation plan comparing two approaches. Include a table of contents, a diagram, a small comparison table, and expandable risks. Keep it self-contained without JavaScript or external resources. + +For deterministic testing, use this response: + +````markdown +Here is the comparison: + +```html-preview + +

Choose an approach

+ +
+

Small change

Reuse the existing renderer.

+

Separate runtime

Needed for interactive applications.

+
+
Trade-offs

The smaller change does not execute scripts.

+``` + +Both approaches keep generated content separate from the workbench. +```` + +## Testing scenarios + +| Scenario | Expected result | Coverage | +| --- | --- | --- | +| Explicit response preview | HTML/CSS renders inline; Markdown before and after is unchanged; source retains exact original text. | Unit + live UI | +| Rendering preference | Leave `chat.htmlPreview.enabled` at its default (`false`), or disable it while a transcript is visible: explicit fences show source, without a preview or webview. Enable it to render previews without a reload. Other chat surfaces remain source-only, and rendering works without invoking the skill. | Chat-list unit + live UI | +| Ordinary HTML / user prompt / editor chat | Remains code; no HTML-preview webview is allocated. | Unit | +| Streaming and cancellation | No preview before a real closing fence, including a response stopped mid-block. A completed block may display while the remaining explanation streams. | Unit + live UI | +| Backtick and tilde fences | Matching fences of at least three characters work; short, mismatched, or closing fences indented more than three spaces do not trigger a preview, including for canceled responses. | Unit | +| Append-only response updates | Existing preview and source-toggle state survive; no duplicate webview or source editor. | Unit | +| Multiple previews / restored conversation | Independent previews and toggles; restored Markdown renders again without executing code or needing provider state. | Live UI | +| Preview actions | There is no header, permanent toolbar, border, or separate background. Tab/Shift+Tab reaches the labeled preview; Shift+F10 or right-click opens its menu; arrows and Enter activate actions. Show Source announces its checked state, moves focus to the selected view, and preserves the preview's disclosure state. Errors and oversized-output notices remain visible. Source mode retains standard editor context actions. | Unit + live UI | +| Code-block navigation | Next/Previous Code Block traverses mixed HTML previews and ordinary code blocks without restarting at the first/last block when a preview has focus. With Show Source active, navigation focuses its source editor. | Command + content-part unit tests + live UI | +| Transcript Find | Search for content inside a preview: source opens, the matching editor line is visible, and Find retains focus. Search for prose containing toolbar labels such as "Show Source": the prose is highlighted, not preview chrome, and unrelated previews stay in preview mode. | Real chat-list/Find integration + live UI | +| Expanded preview | Opens in the editor with the same sanitization, script prohibition, and offline CSP. Repeated activation, including after chat-row recycling, reuses the editor for the same block and source. Recycling the chat row does not close it. Find and section navigation work in a long report. Scroll down, switch to another editor tab, then return: the reading position is restored even though the hidden frame was released. | Overlay lifecycle unit + live UI | +| Safe export and reopening | Save a report containing scripts, forms, external URLs, CSS and SVG. Reopen the file offline: supported content and theme remain, including quoted Windows/Linux font families and subsequent theme variables; no script executes and no external content loads. Attach the saved file to a later chat for a revision. | Unit + live browser | +| Export cancellation and errors | Cancel creates no file. Write or editor-open failures surface an error; actions remain retryable and failed expanded editors are disposed. | Unit + live UI | +| Section navigation | A long report's table of contents reaches matching IDs, including encoded spaces and document/form names such as `title`, `timeline`, and `implementation`. Namespaced IDs keep ARIA references, CSS ID selectors and SVG fragment paints/markers consistent, without collisions with already-prefixed IDs. `#` scrolls to the top. Malformed escapes, command/file/external URLs and SVG links do not navigate. | Unit + live browser | +| Accessibility | Chat help documents all actions. Expanded-preview Help and Accessible View apply only while its content is focused, not while chat or the webview Find input is focused. Closing the accessible view restores preview focus only if that editor is still active. The Find hint follows the webview Find command's binding; chat Accessible View keeps original source. Disclosures and section links remain keyboard-operable. | Unit + live command routing + manual screen reader | +| Authoring guidance | The built-in `/html-preview` skill is not offered by default, because previews are off by default. An unrelated workspace offers it while HTML previews and AI features are enabled. Toggle either setting: discovery, slash commands, file listings and harness forwarding update without reloading. User-disabled skills stay disabled after toggling rendering; user/workspace overrides remain preferred. Guidance uses theme variables, transparent outer surfaces and accessible static content. | Built-in discovery + harness sync tests + packaged-resource verification | +| Layout and themes | Wide/narrow chat, light/dark/high-contrast themes, long output and zoom remain usable; generated CSS cannot affect adjacent messages or chrome. Body-owned grid/flex children keep their layout, and sticky navigation in the expanded editor follows the document scroll rather than an artificial overflow wrapper. | Unit height/layout tests + live UI | +| Full-height scrolling | A report taller than 600px and the viewport renders at its full measured height, with no vertical preview scrollbar. Scrolling over it scrolls the transcript. Resizing, native disclosures and forced 125%/150% display scales do not clip the final content. Horizontal scrollbar space contributes to natural height. No special wheel routing or containment is added for authored nested scroll areas. | Real preview layout + forced-scale browser checks + live UI | +| Iframe lifecycle | Hiding or virtualizing a preview disposes its webview before reattachment. Repeated hide/show, recycle and editor-tab cycles do not accumulate frames or mount listeners. Shell navigation is configured before insertion; sandbox flags and request-origin checks remain intact. Unsupported network permission names are not delegated. | Lifecycle/listener regressions + live repeated-cycle and console checks | +| Script / bridge injection | Script elements, event handlers, `javascript:` and `command:` links, and forged webview context cannot execute or invoke VS Code. | Unit + live browser | +| Network / navigation / local files | Remote images, CSS URLs/imports, frames, forms, redirects and file URLs do not load or navigate. Embedded raster images and simple SVG remain supported. | Unit sanitization + live browser CSP | +| Oversized content | At 64,000 code units a preview is allowed; above that the user sees an explicit notice and the original source, with no webview allocated. | Unit | +| Webview failure | Error is logged and announced; source remains available. | Unit | +| Visibility, remount and disposal | Scroll a completed preview fully out of the viewport, let other responses reuse its row, then return repeatedly, including after resizing the chat. Exercise both reconstruction and returning to an older cached part after toggling the same block in a replacement part. The existing bounded output-state cache retains source mode and reserved height per session/response/block; remounting synchronizes the visible mode and menu checked state before recreating a webview. Restored source mode defers webview creation until returning to preview, and a failed part stays in its source fallback. Disposing a response releases webview, listeners, and editor-pool reference. | Unit + real chat-list virtualization + live UI | + +Focused automated tests are in [chatMarkdownContentPart.test.ts](../../../../../workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts), [chatCodeblockActions.test.ts](../../../../../workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts), [chatListWidget.test.ts](../../../../../workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts), [webviewShellMessaging.test.ts](../../../../../workbench/contrib/webview/test/node/webviewShellMessaging.test.ts), [sessionsChatAccessibilityHelp.test.ts](./sessionsChatAccessibilityHelp.test.ts), and [appearanceTools.test.ts](./appearanceTools.test.ts). Coverage labels describe which validation to run, not a claim that every manual scenario has been executed. + +```bash +pnpm run build-fast --client-only +./scripts/test.sh --run src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts --run src/vs/workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts --run src/vs/workbench/contrib/webview/test/node/webviewShellMessaging.test.ts --run src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts +./scripts/test.sh --run src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts --run src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts --run src/vs/workbench/contrib/chat/test/browser/widget/chatFindModel.test.ts --grep "HTML preview|HTML webviews|ChatFind" +./scripts/test.sh --run src/vs/sessions/contrib/chat/test/browser/appearanceTools.test.ts --run src/vs/workbench/contrib/chat/test/browser/agentSessions/enumerateLocalCustomizationsForHarness.test.ts --run src/vs/workbench/contrib/chat/test/browser/agentSessions/resolveCustomizationRefs.test.ts --grep "Sessions - Appearance tools|enumerateLocalCustomizationsForHarness|resolveCustomizationRefs - built-in skills" +``` diff --git a/src/vs/sessions/contrib/chat/test/browser/nativeComponents.scenarios.md b/src/vs/sessions/contrib/chat/test/browser/nativeComponents.scenarios.md new file mode 100644 index 000000000000..8909a5ea0a9c --- /dev/null +++ b/src/vs/sessions/contrib/chat/test/browser/nativeComponents.scenarios.md @@ -0,0 +1,98 @@ +# Native components in responses + +## Scope + +The Agents window opts into a shared chat renderer for **explicit, closed `vscode-ui` fenced blocks in assistant responses**. A block composes components from a fixed catalogue: columns and stack layout, text, metric, badge, table, bar chart, and disclosure. VS Code renders them as ordinary DOM in the transcript, with its own typography, theme tokens, focus behavior, and scrolling. There is no webview or iframe. + +The agent supplies content, data, and composition. VS Code owns every component's implementation and appearance: the agent picks semantic variants, such as a positive tone, and the stylesheet maps them to registered theme colors, the chart palette, and the design-system spacing, radius, and type roles. Nothing in a block is evaluated. Tags and quoted literal attributes are the whole language; expressions, imports, scripts, HTML, classes, and styles are rejected. + +The `chat.nativeComponents.enabled` setting defaults to `false` and is experimental. While it is off, or AI features are disabled, these blocks display as source code; changing either setting updates existing responses without reloading. Ordinary code fences, user messages, annotated file edits, filtered responses, and other chat surfaces keep their existing behavior. Providers need no new protocol response type: the original Markdown remains the persisted, copied, and exported response. + +This is independent of HTML previews. `vscode-ui` and `html-preview` each have their own language, setting, renderer, and fallback, and enabling one does not affect the other. + +### Where the renderer lives + +Shared chat code holds only a small seam: the fence check, the renderer contract, and a registration point ([chatNativeComponents.ts](../../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponents.ts)). The parser, components, and stylesheet are registered by the desktop and desktop-web entry ([chat.desktop.contribution.ts](../../browser/chat.desktop.contribution.ts)). The phone bundle does not import that file, so it carries none of them: its stylesheet budget has no room for the component styles. On the phone, `vscode-ui` blocks are shown as source and the authoring skill is not offered. + +### Format + +The schema is versioned ([nativeComponents.ts](../../../../../workbench/contrib/chat/common/nativeComponents/nativeComponents.ts)). A fence that declares no version is version 1; a fence may declare one, as in `vscode-ui v1`. Any other fence option, and any version this build does not support, is rejected with a reason, so a later incompatible revision fails closed in older builds. + +A block is bounded: 32,000 characters, 2,000 components, 8 levels of nesting, 12 columns and 100 rows per table, and 24 bars per chart. A block that exceeds a bound, or contains anything outside the catalogue, is rejected as a whole rather than truncated. + +### Behavior + +- A block renders once its closing fence arrives, while the rest of the response keeps streaming. Until then, and whenever it does not validate, it is an ordinary code block; an invalid block also shows a short reason with the line. +- Visuals have no title bar or permanent buttons. Right-click a visual, or focus it and press Shift+F10, for **Show Source**, which toggles the original markup in the standard code editor. +- Columns share the width equally and wrap down to a single column as the chat narrows. A wide table scrolls inside its own box. Adjacent badges share a line. A long unbroken string wraps rather than widening the response. +- Whitespace in text collapses as it does in HTML, so a non-breaking space written as ` ` keeps a value and its unit together. +- A table is a real table with column headers. A bar chart is exposed as a table of its labels and values, and shows every value as text. A tone is an icon with a name, reinforced by color, never color alone. Disclosures are native and keyboard-operable. Keyboard focus draws a ring around the visual; a click inside it does not. +- The chat Accessible View presents each rendered visual as text: metrics as `label: value`, tables row by row, charts as labelled values. That includes a visual inside a list item or a block quote, and one whose block a file reference splits into several response parts. Blocks that are shown as source read as source. +- Transcript Find searches the original markup, as it does for any code block, and reveals the source when a match in it is selected. Rendered text is not matched a second time. +- The Show Source choice is remembered per block, as it is for HTML previews. Expanded disclosures are remembered while the window is open, so they survive scrolling a response out of view and back. + +The built-in [vscode-ui skill](../../../../skills/vscode-ui/SKILL.md) provides on-demand authoring guidance. It is offered only while native components and AI features are enabled, and only where they render. Rendering does not depend on the skill, and its instructions are not injected into every turn. + +## Try it + +Enable `chat.nativeComponents.enabled`, then ask an agent to answer with a `vscode-ui` fence, or invoke the built-in `/vscode-ui` skill: + +> Compare the full and incremental build times as a native visual, with the key numbers, a bar chart, and how you measured them. + +For deterministic testing, use this response: + +````markdown +The incremental build is considerably faster. + +```vscode-ui + + + + + +Passing +Draft + + + + + + Target + Before + After + Full build12.9 s12.4 s + Incremental build11.7 s1.8 s +
+ + Median of five runs on a warm cache. + +``` + +Most of the improvement comes from caching. +```` + +To see the fallback, change `` to ``: the block shows its source with "Line 8: Unknown component "Chart"". + +## Testing scenarios + +| Scenario | Expected result | Coverage | +| --- | --- | --- | +| Response visual | The components render inline between the surrounding Markdown; no frame is created; the source keeps the exact original text. | Unit | +| Rendering preference | With `chat.nativeComponents.enabled` at its default (`false`), or after turning it off while a transcript is visible, blocks show source. Turning it on renders them without a reload. `chat.disableAIFeatures` has the same effect. Changing `chat.htmlPreview.enabled` changes nothing here. Surfaces that did not opt in stay source-only. | Chat-list unit | +| Ordinary code, user prompt, filtered response, annotated file | Remains code; no visual is created. | Unit | +| Streaming | No visual before a real closing fence, including a response stopped mid-block. A closed block renders while the explanation after it streams, and is not rebuilt by later updates: an expanded disclosure and the source toggle stay as they are. | Unit | +| Fences | Backtick and tilde fences of at least three characters work, with an optional `v1`; a short or mismatched closing fence does not. | Unit | +| Strict validation | Unknown components and attributes, HTML tags, `style`, `class` and event attributes, expressions in braces, comments, imports, loose text, unquoted or repeated attributes, misplaced children, mismatched tags, and non-numeric bar values are each rejected with the line and a reason. | Parser unit | +| Limits | Each bound is accepted at the limit and rejected one past it. | Parser unit | +| Untrusted text | Markup-like text in every label, value, cell, caption, and summary is displayed literally; no element, class, or style comes from it. | Renderer unit | +| Invalid block | Source is shown with a readable notice; there is no Show Source toggle and no visual tab stop; code-block navigation focuses the source editor. | Unit | +| Show Source | Right-click or Shift+F10 opens a menu with Show Source, checked while source is shown. Toggling moves focus to what is shown. In source mode the editor's own context actions are offered too. | Unit + manual | +| Row recycling | Scroll a response with a visual far out of view and back, also after resizing the chat: one visual is shown, with the same disclosures expanded and the same source choice. A disposed part no longer reacts to its old elements. | Chat-list + unit | +| Narrow chat | Columns go from side by side to stacked; a wide table scrolls horizontally without widening the response; badges wrap; a long unbroken label, value, unit, or summary wraps. | Renderer unit (real layout) + fixture | +| Tables while streaming | A table inside a visual is never wrapped by the Markdown table scroller, however many updates follow; Markdown tables in the same response still are. | Unit | +| Themes | Light, dark, and both high-contrast themes; switching theme while a visual is shown updates it, because every color is a theme variable. | Fixture screenshots + manual for the live switch | +| Accessibility | Tab reaches the visual and draws a focus ring around it; a click inside it draws none. Disclosures toggle with Enter or Space; a screen reader finds a table with column headers, a chart as a table of labelled values, and named tone icons. The Accessible View shows the text alternative where the visual renders, also inside a list item or a block quote, and the source elsewhere, such as in a filtered response. Accessibility Help documents the feature only while it is enabled. | Unit + manual screen reader | +| Find | A match in prose is highlighted there and leaves the visual alone. A match in the markup reveals the source without taking focus from Find. Text that appears in both the markup and the rendered visual is never highlighted inside the visual. | Chat-list + Find unit | +| Authoring guidance | `/vscode-ui` is not offered by default. It appears across discovery, slash commands, file listings, and harness forwarding while the setting and AI features are on, and disappears when either is off or the renderer is absent. | Built-in discovery unit | +| Restored conversation | Reopen a session whose response contains a visual: the persisted Markdown renders again. | Manual | +| Phone | With the setting on, blocks show source and the skill is not offered. | Skill-gating unit + manual | diff --git a/src/vs/sessions/contrib/chat/test/browser/newChatWidget.fixture.ts b/src/vs/sessions/contrib/chat/test/browser/newChatWidget.fixture.ts index 240de4f90062..0e204c01f5e7 100644 --- a/src/vs/sessions/contrib/chat/test/browser/newChatWidget.fixture.ts +++ b/src/vs/sessions/contrib/chat/test/browser/newChatWidget.fixture.ts @@ -832,6 +832,7 @@ async function renderNewChatWidget(context: ComponentFixtureContext, options: IN const menuService = instantiationService.get(IMenuService) as FixtureMenuService; instantiationService.stub(IChatPhoneInputPresenter, { enabled: constObservable(phoneLayout) }); + instantiationService.stub(IViewsService, { getViewWithId: () => null }); if (connectorRecommendations) { menuService.addItem(MenuId.ChatTipToolbar, { command: { id: 'workbench.action.chat.previousTip', title: 'Previous tip', icon: Codicon.chevronLeft }, @@ -871,7 +872,6 @@ async function renderNewChatWidget(context: ComponentFixtureContext, options: IN instantiationService.stub(IAgentWorkbenchLayoutService, { mainContainer: container }); instantiationService.stub(ISessionsHostLayoutService, {}); instantiationService.stub(ISessionChangesService, {}); - instantiationService.stub(IViewsService, {}); instantiationService.set(ILayoutService, new class extends mock() { override readonly mainContainer = container; override readonly activeContainer = container; @@ -914,6 +914,7 @@ async function renderNewChatWidget(context: ComponentFixtureContext, options: IN session: activeSessionObservable, })); sessionViewContent.appendChild(view.element); + view.setVisible(true); view.layout(width, height, 0, 0); const targetWindow = dom.getWindow(container); const nextFrame = () => new Promise(resolve => targetWindow.requestAnimationFrame(() => resolve())); 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 10e111acd747..29a045734c24 100644 --- a/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts @@ -11,7 +11,7 @@ import { getBaseLayerHoverDelegate } from '../../../../../base/browser/ui/hover/ import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { DeferredPromise, raceCancellationError, timeout } from '../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; -import { CancellationError } from '../../../../../base/common/errors.js'; +import { CancellationError, errorHandler } from '../../../../../base/common/errors.js'; import { createErrorWithActions, isErrorWithActions } from '../../../../../base/common/errorMessage.js'; import { toAction } from '../../../../../base/common/actions.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; @@ -36,6 +36,7 @@ import { WelcomeName } from '../../../../../workbench/contrib/sessions/browser/c import { IStorageService, InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; +import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { TestExperimentTriggerTelemetryService } from '../../../../../platform/telemetry/test/common/experimentTriggerTestUtils.js'; import { COLLAPSED_SESSION_OPTIONS_SHOW_ICONS_SETTING, COMPARE_AGENTS_OPEN_IN_GRID_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_COMPOSER_OPTIONS_EXPANDED_SETTING, WORKSPACE_OPT_OUT_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; @@ -67,6 +68,9 @@ import { RemoteAgentHostConnectionStatus } from '../../../../../platform/agentHo import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IViewsService } from '../../../../../workbench/services/views/common/viewsService.js'; +import { SessionsView } from '../../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; +import { SessionsGrouping } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; @@ -315,13 +319,14 @@ interface ISessionOptionsPersistenceHarness { interface ISendHarness { readonly configurationService?: IConfigurationService; + readonly viewsService?: Pick; readonly _backgroundSend?: boolean; readonly _draftHost?: INewSessionDraftHost; readonly _backgroundSendStatus?: ISettableObservable; _lastBackgroundSentSessionResource?: URI; _lastBackgroundSendOptions?: ISendRequestOptions; readonly _newChatInput?: Pick; - readonly notificationService: { error(message: string | Error): void; info?(message: string): void }; + readonly notificationService: { error(message: string | Error): void; info?(message: string): void; prompt?: INotificationService['prompt'] }; readonly _pendingBackgroundSends: { set(key: object, value: IDisposable): void; deleteAndDispose(key: object): void }; readonly recentWorkspacesService: { restoreDismissedWorkspace(folderUri: URI): void }; readonly newSessionComposerService: { notifyWillSendRequest(options: ISendRequestOptions, selection: IWorkspaceSelectionSnapshot | undefined): void }; @@ -357,7 +362,7 @@ interface ISendHarness { } | undefined; }; readonly sessionComparisonService?: { startComparison(options: IStartSessionComparisonOptions): Promise<{ readonly id: string; readonly participants: readonly { readonly role: SessionComparisonParticipantRole; readonly sessionResource?: URI }[] }> }; - readonly sessionsService?: { unsetNewSession(): void; openSession(resource: URI, options: { readonly source: 'chat' }): Promise }; + readonly sessionsService?: { unsetNewSession(): void; openSession(resource: URI, options: IOpenSessionOptions): Promise }; readonly commandService?: { executeCommand(commandId: string, ...args: unknown[]): Promise }; readonly logService: { error(message: string, ...args: unknown[]): void }; _getComparisonBranch?(session: ISession): string | undefined; @@ -527,7 +532,7 @@ const getNoWorkspaceOption = Reflect.get(NewChatWidget.prototype, '_getNoWorkspa const getWorkspaceRoots = Reflect.get(NewChatWidget.prototype, '_getWorkspaceRoots') as (this: IWorkspaceRootsHarness, session: ISession) => readonly URI[]; const canSendRequestToWorkspace = Reflect.get(NewChatWidget.prototype, '_canSendRequestToWorkspace') as (this: ICanSendRequestToWorkspaceHarness, session: ISession, environment: ISessionCreationEnvironment, reader: IReader) => boolean; const restoreNoWorkspaceDraft = Reflect.get(NewChatWidget.prototype, '_restoreNoWorkspaceDraft') as (this: IRestoreNoWorkspaceDraftHarness) => Promise; -const handleWorkspaceSelection = Reflect.get(NewChatWidget.prototype, '_handleWorkspaceSelection') as (this: IHandleWorkspaceSelectionHarness, folderUri: URI | undefined) => Promise; +const handleWorkspaceSelection = Reflect.get(NewChatWidget.prototype, '_handleWorkspaceSelection') as (this: IHandleWorkspaceSelectionHarness, folderUri: URI | undefined, notByUser?: boolean) => Promise; const onWorkspaceSelected = Reflect.get(NewChatWidget.prototype, '_onWorkspaceSelected') as (this: IClearWorkspaceHarness, folderUri: URI | undefined) => Promise; const getWorkspaceOptOutTarget = Reflect.get(NewChatWidget.prototype, '_getWorkspaceOptOutTarget') as ( this: { readonly sessionsManagementService: Pick }, @@ -2320,16 +2325,19 @@ suite('NewChatWidget', () => { await option?.submenuActions?.[1].run(); assert.deepStrictEqual({ + ids: option?.submenuActions?.map(action => action.id), labels: option?.submenuActions?.map(action => action.label), icons: option?.submenuActions?.map(action => (action as { readonly icon?: { readonly id: string } }).icon?.id), selections, }, isWeb ? { + ids: undefined, labels: undefined, icons: undefined, selections: [], } : { + ids: ['newSessionWorkspacePicker.quickChat', 'newSessionWorkspacePicker.quickChat'], labels: ['This Computer', 'Test Remote'], icons: [Codicon.vm.id, Codicon.remote.id], selections: [{ providerId: 'agenthost-remote-test' }], @@ -4030,22 +4038,39 @@ suite('NewChatWidget', () => { }); }); - for (const [backgroundSend, inboxEnabled] of [[false, false], [false, true], [true, false]]) { - test(`confirms opted-in background sends and reseeds the workspace (always background: ${backgroundSend}, Inbox enabled: ${inboxEnabled})`, async () => { + for (const [backgroundSend, inboxSelected, openFails] of [[false, false, false], [false, true, false], [true, false, false], [false, true, true]]) { + test(`notifies background sends and reseeds the workspace, preserving hosted status (always background: ${backgroundSend}, Inbox selected: ${inboxSelected}, open fails: ${openFails})`, async () => { const onDidSendRequest = disposables.add(new Emitter()); const pendingSends = disposables.add(new DisposableMap()); const folderUri = URI.file('/dismissed'); const restored: URI[] = []; + const notifications: Parameters[] = []; + const opened: { resource: URI; options: IOpenSessionOptions }[] = []; + const openError = new Error('Session no longer available'); + const errors: Error[] = []; const session = upcastPartial({ sessionId: 'draft' }); const sentSession = upcastPartial({ resource: URI.parse('test-session:/started') }); let sentOptions: ISendRequestOptions | undefined; const picker = { selectedFolderUri: folderUri, validateSelectedWorkspace: async () => true, clearAttachedContext: () => { }, showPicker: () => { } }; const harness: ISendHarness = { - configurationService: new TestConfigurationService({ 'sessions.list.inboxEnabled': inboxEnabled }), + configurationService: new TestConfigurationService({ 'sessions.list.inboxEnabled': !inboxSelected }), + viewsService: { getViewWithId: () => upcastPartial({ grouping: inboxSelected ? SessionsGrouping.Inbox : SessionsGrouping.Workspace }) as T }, _backgroundSend: backgroundSend, _backgroundSendStatus: observableValue('sendStatus', undefined), _newChatInput: { hasInput: false }, - notificationService: { error: () => assert.fail('Unexpected error') }, + notificationService: { + error: () => assert.fail('Unexpected error'), + prompt: (...args) => { notifications.push(args); return upcastPartial>({}); }, + }, + sessionsService: { + unsetNewSession: () => assert.fail('Unexpected navigation'), + openSession: async (resource, options) => { + opened.push({ resource, options }); + if (openFails) { + throw openError; + } + }, + }, _pendingBackgroundSends: pendingSends, recentWorkspacesService: { restoreDismissedWorkspace: uri => restored.push(uri) }, _session: constObservable(session), @@ -4064,16 +4089,28 @@ suite('NewChatWidget', () => { _createNewSession: async () => { picker.selectedFolderUri = URI.file('/different-workspace'); }, }; await send.call(harness, 'hello', undefined, backgroundSend ? undefined : true); - const beforeSuccess = { restored: [...restored], status: harness._backgroundSendStatus?.get() }; + const beforeSuccess = { restored: [...restored], status: harness._backgroundSendStatus?.get(), notifications: notifications.length }; onDidSendRequest.fire(upcastPartial({ options: { query: 'unrelated' } })); - const afterUnrelatedSend = { restored: [...restored], status: harness._backgroundSendStatus?.get() }; + const afterUnrelatedSend = { restored: [...restored], status: harness._backgroundSendStatus?.get(), notifications: notifications.length }; assert.ok(sentOptions); onDidSendRequest.fire(upcastPartial({ options: sentOptions, session: sentSession })); - assert.deepStrictEqual({ beforeSuccess, afterUnrelatedSend, restored, pending: pendingSends.size, background: sentOptions.background, status: harness._backgroundSendStatus?.get(), resource: harness._lastBackgroundSentSessionResource }, { - beforeSuccess: { restored: [], status: undefined }, afterUnrelatedSend: { restored: [], status: undefined }, + const openedBeforeAction = [...opened]; + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + errorHandler.setUnexpectedErrorHandler(error => errors.push(error)); + try { + await notifications[0]?.[2][0].run(); + } finally { + errorHandler.setUnexpectedErrorHandler(previousHandler); + } + assert.deepStrictEqual({ beforeSuccess, afterUnrelatedSend, restored, pending: pendingSends.size, background: sentOptions.background, status: harness._backgroundSendStatus?.get(), resource: harness._lastBackgroundSentSessionResource, notifications: notifications.map(([severity, message, choices]) => ({ severity, message, choices: choices.map(choice => choice.label) })), openedBeforeAction, opened, errors }, { + beforeSuccess: { restored: [], status: undefined, notifications: 0 }, afterUnrelatedSend: { restored: [], status: undefined, notifications: 0 }, restored: [folderUri], pending: 0, background: true, - status: backgroundSend || inboxEnabled ? 'Message sent' : undefined, - resource: backgroundSend || inboxEnabled ? sentSession.resource : undefined, + status: backgroundSend ? 'Message sent' : undefined, + resource: backgroundSend ? sentSession.resource : undefined, + notifications: backgroundSend ? [] : [{ severity: Severity.Info, message: 'Message sent', choices: ['Open Session'] }], + openedBeforeAction: [], + opened: backgroundSend ? [] : [{ resource: sentSession.resource, options: { source: 'link', forceMainChat: true } }], + errors: openFails ? [openError] : [], }); }); } @@ -5506,6 +5543,32 @@ suite('NewChatWidget', () => { }); })); + test('a workspace selection the user did not make leaves focus in the input being typed in', async () => { + const input = append(mainWindow.document.body, $('input')); + const button = append(mainWindow.document.body, $('button')); + disposables.add(toDisposable(() => { input.remove(); button.remove(); })); + const run = async (notByUser: boolean, focused: HTMLElement) => { + let focusCalls = 0; + focused.focus(); + await handleWorkspaceSelection.call(upcastPartial({ + _environment: constObservable(undefined), + _workspaceOptOutEnabled: constObservable(false), + _newChatInput: { focus: () => focusCalls++ }, + _isCurrentWorkspaceSelection: () => true, + }), URI.file('/handed-off'), notByUser); + return focusCalls; + }; + assert.deepStrictEqual({ + byUserWhileTyping: await run(false, input), + notByUserWhileTyping: await run(true, input), + notByUserWhileNotTyping: await run(true, button), + }, { + byUserWhileTyping: 1, + notByUserWhileTyping: 0, + notByUserWhileNotTyping: 1, + }); + }); + for (const origin of [ WorkspaceSelectionOrigin.None, WorkspaceSelectionOrigin.CheckedWorkspace, WorkspaceSelectionOrigin.AgentsRecent, WorkspaceSelectionOrigin.VSCodeRecent, WorkspaceSelectionOrigin.VSCodeWorkspace, WorkspaceSelectionOrigin.ExistingSessions, WorkspaceSelectionOrigin.WindowContext, @@ -5696,6 +5759,87 @@ suite('NewChatWidget', () => { ]); }); + test('keeps comparison mode while the selected workspace is waiting for its replacement draft', () => { + const second = URI.file('/second'); + const isRepository = observableValue('isRepository', false); + const createWorkspace = (root: URI) => upcastPartial({ + folders: [{ root, workingDirectory: root, name: 'Workspace', description: '', gitRepository: upcastPartial({ isRepository }) }], + }); + const workspace = observableValue('workspace', undefined); + const loading = observableValue('loading', false); + const resolving = observableValue('resolving', false); + const isolationOptions = observableValue('isolationOptions', ['folder', 'worktree']); + const selectedFolder = observableValue('selectedFolder', undefined); + const session = observableValue('session', upcastPartial({ + workspace, loading, + mainChat: constObservable(upcastPartial({ resource: URI.parse('agent-host-copilot:/draft') })), + })); + const harness = { + _session: session, + _workspacePicker: { get selectedFolderUri() { return selectedFolder.get(); } }, + sessionsProvidersService: { + getProvider: () => ({ + id: LOCAL_AGENT_HOST_PROVIDER_ID, + getSessionConfig: () => ({ schema: { type: 'object', properties: { isolation: { type: 'string', title: 'Isolation', enum: isolationOptions.get() } } }, values: { isolation: 'folder' } }), + }), + }, + }; + const isPending = Reflect.get(NewChatWidget.prototype, '_isComparisonPending') as (this: typeof harness, reader: IReader, resolving: IObservable) => boolean; + const pending = derived(reader => { + selectedFolder.read(reader); + isolationOptions.read(reader); + return isPending.call(harness, reader, resolving); + }); + const available = observableValue('available', true); + const selection = disposables.add(new SessionComparisonModelSelection(available, undefined, undefined, undefined, pending, disposables.add(new InMemoryStorageService()), disposables.add(new TestInstantiationService()))); + selection.start(); + selection.select('one'); + selection.select('two'); + selection.next(); + selection.select('judge'); + selection.next(); + selection.select('synthesizer'); + selection.finish(); + const snapshots: { pending: boolean; enabled: boolean; judge: string | undefined; synthesizer: string | undefined }[] = []; + disposables.add(autorun(reader => snapshots.push({ + pending: pending.read(reader), + enabled: selection.enabled.read(reader), + judge: selection.judgeModelId.read(reader), + synthesizer: selection.synthesizerModelId.read(reader), + }))); + transaction(tx => { + selectedFolder.set(second, tx); + available.set(false, tx); + }); + transaction(tx => { + workspace.set(createWorkspace(second), tx); + resolving.set(true, tx); + }); + resolving.set(false, undefined); + transaction(tx => { + isRepository.set(true, tx); + available.set(true, tx); + }); + transaction(tx => { + isolationOptions.set(['folder'], tx); + isRepository.set(false, tx); + available.set(false, tx); + }); + selectedFolder.set(undefined, undefined); + transaction(tx => { + workspace.set(undefined, tx); + available.set(true, tx); + }); + assert.deepStrictEqual(snapshots, [ + { pending: false, enabled: true, judge: 'judge', synthesizer: 'synthesizer' }, + { pending: true, enabled: true, judge: 'judge', synthesizer: 'synthesizer' }, + { pending: false, enabled: true, judge: 'judge', synthesizer: 'synthesizer' }, + { pending: false, enabled: false, judge: 'judge', synthesizer: 'synthesizer' }, + { pending: true, enabled: true, judge: 'judge', synthesizer: 'synthesizer' }, + { pending: false, enabled: true, judge: 'judge', synthesizer: 'synthesizer' }, + ]); + }); + for (const committed of [false, true]) { test(`preserves comparison choices across workspace draft replacement and clearing (committed: ${committed})`, () => { const available = observableValue('available', true); diff --git a/src/vs/sessions/contrib/chat/test/browser/openSessionLinkOpener.test.ts b/src/vs/sessions/contrib/chat/test/browser/openSessionLinkOpener.test.ts index 648640d3a312..15e51cd26a35 100644 --- a/src/vs/sessions/contrib/chat/test/browser/openSessionLinkOpener.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/openSessionLinkOpener.test.ts @@ -36,6 +36,7 @@ import { IChat, ISession, SessionStatus } from '../../../../../workbench/service import { ISessionsProvider } from '../../../../../workbench/contrib/sessions/common/sessionsProvider.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { findSessionForOpenSessionLink, ISessionLinkChatState, ISessionLinkState, OpenSessionLinkOpenerContribution, readSessionState } from '../../browser/openSessionLinkOpener.contribution.js'; +import { MobileNullChatWindowService } from '../../../mobile/browser/mobileNullChatWindowService.js'; suite('OpenSessionLinkOpenerContribution', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -179,8 +180,8 @@ suite('OpenSessionLinkOpenerContribution', () => { sessionsProvidersService, sessionSummaryHoverService, new class extends mock() { }, - new class extends mock() { }, - new TestConfigurationService(), + new MobileNullChatWindowService(), + new TestConfigurationService({ [CHAT_WINDOWS_ENABLED_SETTING]: true }), )); if (!registeredOpener) { @@ -193,15 +194,17 @@ suite('OpenSessionLinkOpenerContribution', () => { await registeredOpener.open(buildOpenSessionLinkUri(sessionResource, 'chat-2', 'turn-1')), await registeredOpener.open(buildOpenSessionLinkUri(sessionResource), { openToSide: true }), await registeredOpener.open(buildOpenSessionLinkUri(sessionResource, 'chat-2', 'turn-1'), { openToSide: true }), + await registeredOpener.open(buildOpenSessionLinkUri(sessionResource), { fromUserGesture: true, sourceWindowId: 1 }), ], opened, }, { - results: [true, true, true, true], + results: [true, true, true, true, true], opened: [ 'chat:copilotcli:/session-1', 'chat:copilotcli:/session-1#chat-2', 'sessionSide:true:undefined', 'chatSide:copilotcli:/session-1#chat-2', + 'chat:copilotcli:/session-1', ], }); }); diff --git a/src/vs/sessions/contrib/chat/test/browser/responseSelectionResolver.test.ts b/src/vs/sessions/contrib/chat/test/browser/responseSelectionResolver.test.ts index 0dcedc4584cc..d1c420de8f4b 100644 --- a/src/vs/sessions/contrib/chat/test/browser/responseSelectionResolver.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/responseSelectionResolver.test.ts @@ -58,6 +58,8 @@ suite('resolveResponseSelection', () => { const store = disposables.add(new DisposableStore()); const doc = dom.getActiveDocument(); const widgetDomNode = doc.createElement('div'); + widgetDomNode.style.userSelect = 'text'; + widgetDomNode.style.webkitUserSelect = 'text'; doc.body.appendChild(widgetDomNode); store.add(toDisposable(() => widgetDomNode.remove())); return { store, doc, widgetDomNode }; @@ -501,6 +503,92 @@ suite('resolveResponseSelection', () => { assert.strictEqual(resolveResponseSelection(widget)?.text, 'hello world'); }); + for (const direction of ['forward', 'backward'] as const) { + test(`ignores unselectable metadata at the ${direction} native selection focus`, () => { + const { store, doc, widgetDomNode } = setup(); + const metadata = dom.$('div'); + metadata.style.userSelect = 'none'; + metadata.style.webkitUserSelect = 'none'; + dom.append(metadata, dom.$('span')).textContent = 'Completed 10 steps'; + const markdown = dom.$('.chat-markdown-part'); + const textNode = doc.createTextNode('hello world'); + markdown.appendChild(textNode); + widgetDomNode.append(...(direction === 'backward' ? [metadata, markdown] : [markdown, metadata])); + + const selection = dom.getWindow(widgetDomNode).getSelection(); + assert.ok(selection); + store.add(toDisposable(() => selection.removeAllRanges())); + selection.setBaseAndExtent( + textNode, + direction === 'backward' ? textNode.data.length : 0, + metadata, + direction === 'backward' ? 0 : metadata.childNodes.length, + ); + const response = makeResponse('turn-1'); + const widget = upcastPartial({ + domNode: widgetDomNode, + getElementFromNode: () => response, + }); + const resolved = resolveResponseSelection(widget); + + assert.deepStrictEqual({ + nativeText: selection.toString().trim(), + rangeIncludesMetadata: selection.getRangeAt(0).toString().includes('Completed 10 steps'), + response: resolved?.response, + text: resolved?.text, + direction: resolved?.direction, + focusContainer: resolved?.focusRange.startContainer, + focusOffset: resolved?.focusRange.startOffset, + }, { + nativeText: 'hello world', + rangeIncludesMetadata: true, + response, + text: selection.toString().trimEnd(), + direction, + focusContainer: textNode, + focusOffset: direction === 'backward' ? 0 : textNode.data.length - 1, + }); + }); + } + + test('preserves selectable markdown inside an unselectable ancestor', () => { + const { store, doc, widgetDomNode } = setup(); + const wrapper = dom.append(widgetDomNode, dom.$('div')); + wrapper.style.userSelect = 'none'; + wrapper.style.webkitUserSelect = 'none'; + dom.append(wrapper, dom.$('span')).textContent = 'Completed 10 steps'; + const markdown = dom.append(wrapper, dom.$('.chat-markdown-part')); + markdown.style.userSelect = 'text'; + markdown.style.webkitUserSelect = 'text'; + const textNode = doc.createTextNode('hello world'); + markdown.appendChild(textNode); + + const selection = dom.getWindow(widgetDomNode).getSelection(); + assert.ok(selection); + store.add(toDisposable(() => selection.removeAllRanges())); + selection.setBaseAndExtent(textNode, textNode.data.length, widgetDomNode, 0); + const response = makeResponse('turn-1'); + const widget = upcastPartial({ + domNode: widgetDomNode, + getElementFromNode: () => response, + }); + const resolved = resolveResponseSelection(widget); + + assert.deepStrictEqual({ + nativeText: selection.toString(), + response: resolved?.response, + text: resolved?.text, + direction: resolved?.direction, + focusContainer: resolved?.focusRange.startContainer, + }, { + nativeText: 'hello world', + response, + text: 'hello world', + direction: 'backward', + focusContainer: textNode, + }); + }); + test('rejects a selection outside the markdown scope', () => { const { store, doc, widgetDomNode } = setup(); const other = doc.createElement('div'); diff --git a/src/vs/sessions/contrib/chat/test/browser/responseSelectionSideChatController.test.ts b/src/vs/sessions/contrib/chat/test/browser/responseSelectionSideChatController.test.ts index 508c284f4ba7..deb1c64fcb4f 100644 --- a/src/vs/sessions/contrib/chat/test/browser/responseSelectionSideChatController.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/responseSelectionSideChatController.test.ts @@ -86,6 +86,7 @@ suite('ResponseSelectionSideChatController', () => { sendRequest?: ISessionsManagementService['sendRequest']; getElementFromNode?: IChatWidget['getElementFromNode']; enhancedSelectionMenu?: boolean; + showOnSelection?: boolean; responseSelectionSupported?: boolean; initialInput?: string; chatInteractivity?: ChatInteractivity; @@ -107,6 +108,8 @@ suite('ResponseSelectionSideChatController', () => { const markdown = doc.createElement('div'); markdown.classList.add('chat-markdown-part'); + markdown.style.userSelect = 'text'; + markdown.style.webkitUserSelect = 'text'; // Positioned so the selection's real client rects (the controller // measures the range itself) land at known coordinates. markdown.style.position = 'absolute'; @@ -361,6 +364,7 @@ suite('ResponseSelectionSideChatController', () => { const controller = store.add(instantiationService.createInstance(ResponseSelectionSideChatController, widget, options?.responseSelectionSupported ?? true, { useActionMenu: () => configurationService.getValue(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING) === true, + showOnSelection: options?.showOnSelection, onAction: (variant, action) => logResponseSelectionWidgetAction(instantiationService.get(ITelemetryService), variant, action), })); bindChat(controller, chat); @@ -699,7 +703,7 @@ suite('ResponseSelectionSideChatController', () => { assert.strictEqual(inputDomNode(controller).style.display, 'none'); }); - test('shows the enhanced action menu only when the experiment setting is enabled', () => { + test('shows the enhanced action menu when configured', () => { const { controller, setSelection } = setup({ enhancedSelectionMenu: true }); setSelection('hello world'); @@ -717,6 +721,55 @@ suite('ResponseSelectionSideChatController', () => { }); }); + test('updates response-selection menu visibility when configured', () => { + const { controller, setSelection, telemetryEvents } = setup({ enhancedSelectionMenu: true, showOnSelection: false }); + + setSelection('hello world'); + const initiallyVisible = menuDomNode(controller).style.display !== 'none'; + controller.setShowOnSelection(true); + const visibleAfterEnable = menuDomNode(controller).style.display !== 'none'; + controller.setShowOnSelection(false); + + assert.deepStrictEqual({ + initiallyVisible, + visibleAfterEnable, + visibleAfterDisable: menuDomNode(controller).style.display !== 'none', + telemetryEvents, + }, { + initiallyVisible: false, + visibleAfterEnable: true, + visibleAfterDisable: false, + telemetryEvents: [ + { name: 'vscodeAgents.responseSelectionWidget/action', data: { variant: 'actionMenu', action: 'shown' } }, + ], + }); + }); + + test('waits for an active pointer selection to settle when enabled', async () => { + const { controller, beginPointerSelection, finishPointerSelection, setSelection, telemetryEvents } = setup({ + enhancedSelectionMenu: true, + showOnSelection: false, + }); + + beginPointerSelection(); + setSelection('hello world'); + controller.setShowOnSelection(true); + const visibleDuringDrag = menuDomNode(controller).style.display !== 'none'; + await finishPointerSelection(); + + assert.deepStrictEqual({ + visibleDuringDrag, + visibleAfterRelease: menuDomNode(controller).style.display !== 'none', + telemetryEvents, + }, { + visibleDuringDrag: false, + visibleAfterRelease: true, + telemetryEvents: [ + { name: 'vscodeAgents.responseSelectionWidget/action', data: { variant: 'actionMenu', action: 'shown' } }, + ], + }); + }); + test('shows the enhanced action menu after pointer selection settles', async () => { const { controller, @@ -1736,6 +1789,59 @@ suite('ResponseSelectionSideChatController', () => { assert.strictEqual(notificationService.notifications[0].severity, Severity.Error); }); + test('preserves pending submission tracking when automatic selection UI is disabled', async () => { + let rejectCreate!: (error: Error) => void; + const pending = new Promise((_resolve, reject) => { rejectCreate = reject; }); + let createCalls = 0; + const { controller, setSelection, notificationService } = setup({ + enhancedSelectionMenu: true, + createSideChatInSession: async () => { + createCalls++; + return pending; + }, + }); + setSelection('hello world'); + triggerMenuAction(controller, 'Ask in a Side Chat'); + submitViaClick(controller, 'keep this question'); + + controller.setShowOnSelection(false); + controller.setShowOnSelection(true); + inputDomNode(controller).querySelector('.action-label')!.click(); + dispatchKey(inputTextArea(controller), 'Enter'); + const pendingState = { + busy: isInputBusy(controller), + disabled: inputTextArea(controller).disabled, + visible: inputDomNode(controller).style.display !== 'none', + createCalls, + }; + + rejectCreate(new Error('boom')); + await new Promise(resolve => setTimeout(resolve, 0)); + + assert.deepStrictEqual({ + pendingState, + busyAfterFailure: isInputBusy(controller), + disabledAfterFailure: inputTextArea(controller).disabled, + questionAfterFailure: inputTextArea(controller).value, + visibleAfterFailure: inputDomNode(controller).style.display !== 'none', + createCalls, + notifications: notificationService.notifications, + }, { + pendingState: { + busy: true, + disabled: true, + visible: true, + createCalls: 1, + }, + busyAfterFailure: false, + disabledAfterFailure: false, + questionAfterFailure: 'keep this question', + visibleAfterFailure: true, + createCalls: 1, + notifications: [{ severity: Severity.Error, message: 'The side chat could not be created.' }], + }); + }); + test('same-chat setChat (e.g. a status/interactivity update) preserves a visible draft', () => { const { controller, setSelection, chat } = setup(); setSelection('hello world'); 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 dd80ed0e11c5..5d6815168dc7 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts @@ -54,6 +54,7 @@ import { externalUriOpenersSettingId } from '../../../../../workbench/contrib/ex import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID, REMOTE_AGENT_HOST_PROVIDER_PREFIX } from '../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { IChatWindow, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { ISessionHost, SessionHostKind } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { ISessionGridPane } from '../../../../../workbench/services/sessions/browser/sessionGridPane.js'; @@ -87,6 +88,7 @@ suite('SessionChatInputToolbar', () => { chatModels: constObservable([]), })); instantiationService.stub(IChatImageCarouselService, upcastPartial({})); + instantiationService.stub(IChatWindowService, upcastPartial({ getWindow: () => undefined })); instantiationService.stub(IWorkbenchGitHubService, upcastPartial({ onDidChangeDefaultClient: Event.None, })); @@ -119,9 +121,16 @@ suite('SessionChatInputToolbar', () => { return { instantiationService, visibility, configuration }; } - async function createGitHubActivityBar(kind: SessionArtifactKind.PullRequest | SessionArtifactKind.Issue, providerId: string, getOpener?: IExternalUriOpenerService['getOpener']) { + async function createGitHubActivityBar(kind: SessionArtifactKind.PullRequest | SessionArtifactKind.Issue, providerId: string, getOpener?: IExternalUriOpenerService['getOpener'], inChatWindow = false, chatWindowRegistered = true) { const services = createServices(); const { instantiationService } = services; + const reveals: string[] = []; + if (inChatWindow) { + instantiationService.stub(ISessionHost, upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined, windowId: constObservable(7) })); + instantiationService.stub(IChatWindowService, upcastPartial({ + getWindow: windowId => windowId === 7 && chatWindowRegistered ? upcastPartial({ mainPart: upcastPartial({ activeGroup: upcastPartial({ id: 99 }), getGroup: id => id === 50 ? upcastPartial({ id }) : undefined }), showEditor: () => { reveals.push('chatWindow.showEditor'); } }) : undefined, + })); + } const extensionsChanged = store.add(new Emitter<{ added: []; removed: [] }>()); instantiationService.stub(IExtensionService, 'onDidChangeExtensions', extensionsChanged.event); if (getOpener) { @@ -177,7 +186,7 @@ suite('SessionChatInputToolbar', () => { isEditorPaneVisible: () => paneVisible || detailVisible, isVisible: part => part === Parts.EDITOR_PART ? paneVisible : detailVisible, hideSidePane: () => { paneVisible = false; detailVisible = false; stateChanged.fire(); }, - revealEditorPartExplicitly: () => { paneVisible = true; stateChanged.fire(); }, + revealEditorPartExplicitly: () => { reveals.push('main.revealEditorPartExplicitly'); paneVisible = true; stateChanged.fire(); }, })); stubSessionsHostLayout(instantiationService); instantiationService.stub(ISessionsService, 'panes', constObservable([])); @@ -193,7 +202,7 @@ suite('SessionChatInputToolbar', () => { store.add(autorun(reader => toolbar.activityBarActions.read(reader))); await timeout(0); return { - ...services, toolbar, session, main, peer, artifacts, artifact, opened, revealed, sentiment, pullRequest, extensionsChanged, + ...services, toolbar, session, main, peer, artifacts, artifact, opened, revealed, reveals, sentiment, pullRequest, extensionsChanged, setEditor: (input: EditorInput | undefined) => { editor = input; if (input && !editors.some(entry => entry.editor === input)) { @@ -235,6 +244,20 @@ suite('SessionChatInputToolbar', () => { assert.deepStrictEqual({ counts, lookups: lookups - before }, { counts: Array(10).fill(1), lookups: 0 }); }); + test('activity bar does not repeat opener checks when a state update recreates the same links', async () => { + let lookups = 0; + const { toolbar, artifacts } = await createGitHubActivityBar(SessionArtifactKind.PullRequest, LOCAL_AGENT_HOST_PROVIDER_ID, async () => { + lookups++; + return upcastPartial({ id: 'supported' }); + }); + const before = lookups; + for (let i = 0; i < 10; i++) { + artifacts.set(artifacts.get().map(entry => ({ ...entry, link: entry.link && URI.parse(entry.link.toString()) })), undefined); + await timeout(0); + } + assert.deepStrictEqual({ actions: toolbar.activityBarActions.get().length, lookups: lookups - before }, { actions: 1, lookups: 0 }); + }); + test('activity bar retains supported PRs while opener revalidation is pending', async () => { const { toolbar, instantiationService, extensionsChanged } = await createGitHubActivityBar(SessionArtifactKind.PullRequest, LOCAL_AGENT_HOST_PROVIDER_ID); let complete!: (value: IExternalUriOpener | undefined) => void; @@ -279,6 +302,20 @@ suite('SessionChatInputToolbar', () => { assert.deepStrictEqual({ before, after: toolbar.activityBarActions.get()[0].checked, opened }, { before: false, after: true, opened: [] }); }); + for (const { name, inChatWindow, registered, editorGroupId, expected } of [ + { name: 'the main window', inChatWindow: false, registered: true, editorGroupId: 1, expected: { reveals: ['main.revealEditorPartExplicitly'], revealed: [1] } }, + { name: 'the chat window that hosts the chat, from the group of another window', inChatWindow: true, registered: true, editorGroupId: 1, expected: { reveals: ['chatWindow.showEditor'], revealed: [99] } }, + { name: 'the chat window that hosts the chat, from its own group', inChatWindow: true, registered: true, editorGroupId: 50, expected: { reveals: ['chatWindow.showEditor'], revealed: [50] } }, + { name: 'no window when the chat window of the chat is not available', inChatWindow: true, registered: false, editorGroupId: 1, expected: { reveals: [], revealed: [] } }, + ]) { + test(`activity bar reveals an open ${kind} editor in ${name}`, async () => { + const { toolbar, setEditors, artifact, main, reveals, revealed } = await createGitHubActivityBar(kind, LOCAL_AGENT_HOST_PROVIDER_ID, undefined, inChatWindow, registered); + setEditors([{ editor: store.add(new TestEditorInput(artifact(1, main).link!, 'test.githubEditor')), groupId: editorGroupId }]); + await toolbar.activityBarActions.get()[0].run(); + assert.deepStrictEqual({ reveals, revealed: revealed.map(entry => entry.groupId) }, expected); + }); + } + test(`activity bar toggles ${kind} editors on repeated activation`, async () => { const { toolbar, setEditor, setPaneVisible, artifact, main, opened } = await createGitHubActivityBar(kind, LOCAL_AGENT_HOST_PROVIDER_ID); const editor = store.add(new TestEditorInput(artifact(1, main).link!, 'test.githubEditor')); @@ -1115,20 +1152,28 @@ suite('SessionChatInputToolbar', () => { mainChat: constObservable(mainChat), workspace: mainChat.workspace, }); - const opened: { resource: string; chatResource: string | undefined }[] = []; - instantiationService.stub(ISessionHost, upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined })); + const opened: { resource: string; chatResource: string | undefined; group: unknown }[] = []; + const calls: string[] = []; + const chatWindowGroup = { id: 42 }; + instantiationService.stub(IChatWindowService, upcastPartial({ + getWindow: windowId => windowId === 7 ? upcastPartial({ + mainPart: upcastPartial({ activeGroup: upcastPartial(chatWindowGroup) }), + showEditor: () => { calls.push('chatWindow.showEditor'); }, + }) : undefined, + })); + instantiationService.stub(ISessionHost, upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined, windowId: constObservable(7) })); instantiationService.stub(ISessionsService, 'getPaneOfHost', () => undefined); instantiationService.stub(ISessionsService, 'panes', constObservable([])); instantiationService.stub(ISessionsService, 'setActive', () => { }); instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({ // The dropdowns of the pills show in the container of their window. getContainer: window => window.document.body, - revealEditorPartExplicitly: () => { }, + revealEditorPartExplicitly: () => { calls.push('main.revealEditorPartExplicitly'); }, })); stubSessionsHostLayout(instantiationService); instantiationService.stub(ISessionChangesService, upcastPartial({ - openChangesEditor: async (resource, options) => { - opened.push({ resource: resource.toString(), chatResource: options?.chatResource?.toString() }); + openChangesEditor: async (resource, options, group) => { + opened.push({ resource: resource.toString(), chatResource: options?.chatResource?.toString(), group }); return undefined; }, })); @@ -1140,10 +1185,13 @@ suite('SessionChatInputToolbar', () => { pill.click(); } - assert.deepStrictEqual(opened, [ - { resource: 'session:1', chatResource: 'chat:nested' }, - { resource: 'session:1', chatResource: 'chat:main' }, - ]); + assert.deepStrictEqual({ opened, calls }, { + opened: [ + { resource: 'session:1', chatResource: 'chat:nested', group: chatWindowGroup }, + { resource: 'session:1', chatResource: 'chat:main', group: chatWindowGroup }, + ], + calls: ['chatWindow.showEditor', 'chatWindow.showEditor'], + }); }); test('uses one GitHub row presentation in dedicated, artifact, and reference collections', () => { @@ -1917,7 +1965,7 @@ suite('SessionChatInputToolbar', () => { toolbar.setSession(session, chat); const labels = () => Array.from(toolbar.element.querySelectorAll('.chat-pill-label'), label => label.textContent); const clickPill = () => { - const pill = toolbar.getChatPetPlatformElements()[0]; + const pill = toolbar.element.querySelector('.chat-pill-item > .chat-pill-button'); assert.ok(pill); pill.click(); }; @@ -2070,7 +2118,7 @@ suite('SessionChatInputToolbar', () => { }; }; const single = presentation(); - toolbar.getChatPetPlatformElements()[0]?.click(); + toolbar.element.querySelector('.chat-pill-item > .chat-pill-button')?.click(); toolbar.element.querySelector('.chat-pill-promoted-action')?.click(); canvases.set([preview, dashboard], undefined); const multiple = presentation(); @@ -2177,7 +2225,7 @@ suite('SessionChatInputToolbar', () => { : new MouseEvent('contextmenu', { bubbles: true })); return menuActions; }; - const subagentPill = toolbar.getChatPetPlatformElements().at(-1); + const subagentPill = [...toolbar.element.querySelectorAll('.chat-pill-item > .chat-pill-button')].at(-1); assert.ok(subagentPill); subagentPill.click(); hideDropdown?.(); @@ -2194,7 +2242,7 @@ suite('SessionChatInputToolbar', () => { visible: toolbar.visible, empty: toolbar.element.classList.contains('empty'), }; - const recoveryTarget = toolbar.getChatPetPlatformElements()[0] ?? toolbar.element.querySelector('.chat-pills-row-content'); + const recoveryTarget = toolbar.element.querySelector('.chat-pill-item > .chat-pill-button') ?? toolbar.element.querySelector('.chat-pills-row-content'); assert.ok(recoveryTarget); const recoveryOptions = openMenu(recoveryTarget).find(action => action instanceof SubmenuAction); assert.ok(recoveryOptions instanceof SubmenuAction); @@ -2471,7 +2519,7 @@ suite('SessionChatInputToolbar', () => { return { label: pill?.getAttribute('aria-label'), closed: !!pill?.querySelector(`.codicon-${Codicon.issueClosed.id}`), - open: !!pill?.querySelector(`.codicon-${Codicon.issueOpened.id}`), + open: !!pill?.querySelector(`.codicon-${Codicon.issues.id}`), }; }; const allClosed = presentation(); @@ -2736,7 +2784,7 @@ suite('SessionChatInputToolbar', () => { const group = toolbar.element.querySelector('.artifact-integration-group-pill')!; const promoted = { labels: integrated.map(pill => pill.querySelector('.chat-pill-label')?.textContent), - // Artifacts sharing an integration share one pill; the reference keeps its own. + // Artifacts sharing an integration share one pill; the reference stays in the References pill, which shows its only entry inline. group: group.querySelector('.chat-pill-label')?.textContent, referencesGrouped: !!toolbar.element.querySelector('[aria-label="Show 1 reference"]'), artifactsGrouped: !!toolbar.element.querySelector('[aria-label="Show 3 artifacts"]'), @@ -2847,7 +2895,7 @@ suite('SessionChatInputToolbar', () => { }); }); - test('decorates a promoted PR as a details disclosure and leaves reference links plain', async () => { + test('decorates a promoted PR with an integration pill whose main part opens the pull request, and leaves reference links plain', async () => { const { instantiationService } = createServices(true); const link = URI.parse('https://github.com/microsoft/vscode/pull/42'); const chat = upcastPartial({ resource: URI.parse('chat:main'), title: constObservable('Chat'), status: constObservable(SessionStatus.Completed) }); @@ -2903,11 +2951,134 @@ suite('SessionChatInputToolbar', () => { const contribution = snapshot.get().contributions[0]; snapshot.set({ ...snapshot.get(), contributions: [{ ...contribution, view: { ...contribution.view, sections: [contribution.view.sections[0]] } }] }, undefined); toolbar.element.querySelector('.artifact-integration-pill .chat-dropdown-pill-button')!.click(); + const openedByPill = opened; await toolbar.activityBarActions.get()[0].run(); assert.deepStrictEqual({ - initial, updated: labels(), integratedPills: toolbar.element.querySelectorAll('.artifact-integration-pill').length, opened, + initial, updated: labels(), integratedPills: toolbar.element.querySelectorAll('.artifact-integration-pill').length, openedByPill, 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: 1, referencesPresent: true }); + }, { initial: ['#42', '3/5', '2'], updated: ['#42', '3/5'], integratedPills: 1, openedByPill: 1, opened: 2, referencesPresent: true }); + }); + + test('offers the chat pet the whole integrated artifact pill, including its status sections', async () => { + const { instantiationService } = createServices(true); + const link = URI.parse('https://github.com/microsoft/vscode/pull/42'); + const chat = upcastPartial({ resource: URI.parse('chat:main'), title: constObservable('Chat'), status: constObservable(SessionStatus.Completed) }); + const session = upcastPartial({ + sessionId: 'quick-chat', resource: URI.parse('session:quick-chat'), + artifacts: constObservable([{ id: 'recorded', kind: SessionArtifactKind.PullRequest, label: 'Recorded title', isArtifact: true, isGitHub: true, link }]), + loading: constObservable(false), + capabilities: constObservable({ supportsMultipleChats: false, supportsRemoveArtifacts: true, supportsArtifactIntegrations: true }), + chats: constObservable([chat]), workspace: constObservable(undefined), + }); + const snapshot: ArtifactSnapshot = { + authority: { id: 'host', targetHost: 'self', location: 'host' }, session: 'session:quick-chat', + artifact: { id: 'recorded', label: 'Recorded title', resource: link.toString(), isArtifact: true }, + mainIntegrationId: 'github.pullRequest', runs: [], + contributions: [{ + integrationId: 'github.pullRequest', label: 'GitHub Pull Request', actions: [], options: [], + configuration: { revision: 0, values: {}, generations: {}, disablements: {} }, + view: { + availability: { kind: 'available' }, + main: { icon: { id: 'git-pull-request' }, label: '#42', detailsId: 'main' }, + groupId: 'github.pullRequest', + sections: [ + { id: 'checks', icon: { id: 'pending' }, label: '3/5', detailsId: 'checks' }, + { id: 'comments', icon: { id: 'comment-discussion' }, label: '2', detailsId: 'comments' }, + ], + stateActions: [], generalActions: [], automationAvailability: [], + }, + }], + }; + instantiationService.stub(IGitHubService, upcastPartial({ + createPullRequestModelReference: () => new ImmortalReference(upcastPartial({ pullRequest: constObservable(undefined) })), + })); + instantiationService.stub(ISessionsManagementService, upcastPartial({ + onDidChangeSessions: Event.None, + acquireArtifactIntegration: async () => new ImmortalReference(upcastPartial({ snapshot: constObservable(snapshot) })), + })); + const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined, undefined)); + toolbar.setSession(session, chat); + await timeout(0); + + // The pet must be able to stand on the sections joined to the pill, not only on its main button. + assert.deepStrictEqual(toolbar.getChatPetPlatformElements().map(platform => [...platform.querySelectorAll('.chat-pill-label')].map(label => label.textContent)), [['#42', '3/5', '2']]); + }); + + test('keeps a reference listed and pinnable in the References pill when the open-only filter hides the closed pull request it aliases', async () => { + const { instantiationService, visibility } = createServices(true); + const host = mainWindow.document.body.appendChild(document.createElement('div')); + host.classList.add('monaco-workbench'); + store.add(toDisposable(() => host.remove())); + const link = URI.parse('https://github.com/microsoft/vscode/pull/42'); + const chat = upcastPartial({ resource: URI.parse('chat:main'), title: constObservable('Chat'), status: constObservable(SessionStatus.Completed) }); + const session = upcastPartial({ + sessionId: 'quick-chat', providerId: 'provider', resource: URI.parse('session:quick-chat'), + artifacts: constObservable([ + { id: 'recorded', kind: SessionArtifactKind.PullRequest, label: 'Recorded title', isArtifact: true, isGitHub: true, link }, + { id: 'alias', kind: SessionArtifactKind.Website, label: 'Alias', isArtifact: false, link: URI.parse('https://github.com/microsoft/vscode/pull/42/files') }, + { id: 'plain', kind: SessionArtifactKind.Website, label: 'Plain', isArtifact: false, link: URI.parse('https://example.test/plain') }, + ]), + loading: constObservable(false), + capabilities: constObservable({ supportsMultipleChats: false, supportsRemoveArtifacts: true, supportsArtifactIntegrations: true }), + chats: constObservable([chat]), workspace: constObservable(undefined), + }); + const integrated = (id: string, label: string, resource: string): ArtifactSnapshot => ({ + authority: { id: 'host', targetHost: 'self', location: 'host' }, session: 'session:quick-chat', + artifact: { id, label, resource, isArtifact: id === 'recorded' }, + mainIntegrationId: 'github.pullRequest', runs: [], + contributions: [{ + integrationId: 'github.pullRequest', label: 'GitHub Pull Request', resourceKey: 'microsoft/vscode#42', actions: [], options: [], + configuration: { revision: 0, values: {}, generations: {}, disablements: {} }, + view: { + availability: { kind: 'available' }, main: { icon: { id: 'git-pull-request-closed' }, label: '#42', detailsId: 'main' }, groupId: 'github.pullRequest', + sections: [], stateActions: [], generalActions: [], automationAvailability: [], + }, + }], + }); + instantiationService.stub(IGitHubService, upcastPartial({ + createPullRequestModelReference: () => new ImmortalReference(upcastPartial({ pullRequest: constObservable(undefined) })), + })); + instantiationService.stub(ISessionsManagementService, upcastPartial({ + onDidChangeSessions: Event.None, + acquireArtifactIntegration: async (_session, id) => new ImmortalReference(upcastPartial({ + snapshot: constObservable(id === 'plain' + ? { ...integrated(id, 'Plain', 'https://example.test/plain'), contributions: [], mainIntegrationId: undefined } + : integrated(id, id === 'recorded' ? 'Recorded title' : 'Alias', id === 'recorded' ? link.toString() : `${link.toString()}/files`)), + })), + })); + let rows: { label: string | undefined; actions: readonly IAction[] }[] = []; + instantiationService.stub(IActionWidgetService, { + isVisible: false, + show: (_id, _preview, items) => { + rows = items.flatMap(item => item.item ? [{ label: item.label, actions: item.toolbarActions ?? [] }] : []); + }, + updateItems: () => { }, + hide: () => { }, + }); + visibility.pullRequests.setShowAll(false); + const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined, undefined)); + host.appendChild(toolbar.element); + toolbar.setSession(session, chat); + await timeout(0); + const pills = () => [...toolbar.element.querySelectorAll('.chat-pill-item')].map(pill => pill.querySelector('.chat-pill-button')?.getAttribute('aria-label')); + const filtered = pills(); + toolbar.element.querySelector('[aria-label="Show 2 references"]')!.click(); + const dropdown = rows.map(row => row.label); + await rows.find(row => row.label === '#42')!.actions.find(action => action.label.startsWith('Pin '))!.run(); + await timeout(0); + const pinned = pills(); + const unpin = toolbar.element.querySelector('.chat-pill-item.has-promoted-action .chat-pill-promoted-action'); + const unpinLabel = unpin?.getAttribute('aria-label'); + unpin?.click(); + await timeout(0); + assert.deepStrictEqual({ filtered, dropdown, pinned, unpinLabel, unpinned: pills() }, { + // The closed pull request is filtered out of the row, but the reference to it stays with the other references. + filtered: ['Show 2 references'], + dropdown: ['#42', 'Plain'], + pinned: ['Open #42', 'Open Plain'], + unpinLabel: 'Unpin #42', + unpinned: ['Show 2 references'], + }); }); test('lists integrated artifacts without a group ID in the Artifacts pill with their integration\'s icon, opening details on select, the resource from Open, and pinning with Unpin', async () => { diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionCustomizations.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionCustomizations.test.ts index 019f7515cec4..5c78c1a02413 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionCustomizations.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionCustomizations.test.ts @@ -13,7 +13,7 @@ suite('Session Customizations', () => { ensureNoDisposablesAreLeakedInTestSuite(); const customization = (id: string, kind: SessionCustomizationKind, name: string): ISessionChatCustomization => - ({ id, kind, name, uri: URI.file(`/repo/${id}.md`) }); + ({ id, kind, name, uri: URI.file(`/repo/${id}.md`) }); const sessionFolder = (name: string, workingDirectory: URI): ISessionFolder => ({ root: workingDirectory, workingDirectory, diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionLinkAttachmentWidget.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionLinkAttachmentWidget.test.ts new file mode 100644 index 000000000000..22eccdc5c9ce --- /dev/null +++ b/src/vs/sessions/contrib/chat/test/browser/sessionLinkAttachmentWidget.test.ts @@ -0,0 +1,163 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { IAction } from '../../../../../base/common/actions.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Event } from '../../../../../base/common/event.js'; +import { constObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { IAgentHostConnectionsService, IAgentHostSessionIdentity } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { buildOpenSessionLinkUri } from '../../../../../platform/agentHost/common/openSessionLink.js'; +import { IClipboardService } from '../../../../../platform/clipboard/common/clipboardService.js'; +import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IChatRequestSessionLinkVariableEntry } from '../../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; +import { ISessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; +import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { IChat, ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { SessionLinkAttachmentWidget } from '../../browser/sessionLinkAttachmentWidget.js'; + +suite('SessionLinkAttachmentWidget', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + const backendSession = URI.parse('copilotcli:/session-1'); + + function createWidget(sessions: readonly ISession[], link = URI.parse(buildOpenSessionLinkUri(backendSession))) { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(ISessionsManagementService, upcastPartial({ + getSessions: () => [...sessions], + onDidChangeSessions: Event.None, + })); + instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ + resolveSessionResourceIdentity: (resource: URI): IAgentHostSessionIdentity => ({ backendSession: resource.with({ scheme: 'copilotcli' }), backendSessionIsAdvertised: true, connectionAuthority: 'local' }), + })); + instantiationService.stub(ISessionsProvidersService, new class extends mock() { }); + // Names each icon after what the sessions list chooses it from. + instantiationService.stub(ISessionsListModelService, upcastPartial({ + getStatusIcon: (status, isRead, _isArchived, completedStateIcon) => ThemeIcon.fromId(`status-${status}${isRead ? '' : '-unread'}${completedStateIcon ? `-${completedStateIcon.id}` : ''}`), + })); + instantiationService.stub(IProductService, upcastPartial({ urlProtocol: 'code-oss' })); + // An in-progress session spins, as in the sessions list, where motion is allowed. + instantiationService.stub(IAccessibilityService, 'isMotionReduced', () => false); + const opened: string[] = []; + instantiationService.stub(IOpenerService, upcastPartial({ + open: async target => { + opened.push(target.toString()); + return true; + }, + })); + const contextMenus: IAction[][] = []; + instantiationService.stub(IContextMenuService, upcastPartial({ + showContextMenu: delegate => { contextMenus.push([...delegate.getActions?.() ?? []]); }, + })); + const copied: string[] = []; + instantiationService.stub(IClipboardService, upcastPartial({ + writeText: async text => { copied.push(text); }, + })); + + const attachment: IChatRequestSessionLinkVariableEntry = { kind: 'sessionLink', id: `sessionLink:${link}`, name: 'Session', value: link }; + const widget = store.add(instantiationService.createInstance(SessionLinkAttachmentWidget, attachment, { shouldFocusClearButton: false, supportsDeletion: true }, document.createElement('div'))); + const icon = () => { + const current = [...widget.element.querySelector('.chat-session-link-attachment-icon')!.children].filter(child => !(child as HTMLElement).dataset.iconFadingOut).at(-1)!; + return current.classList.contains('monaco-pixel-spinner') ? 'spinner' : [...current.classList].find(className => className.startsWith('codicon-')); + }; + const render = () => ({ + label: widget.element.querySelector('.chat-attached-context-custom-text')?.textContent, + displayName: widget.displayName, + icon: icon(), + ariaLabel: widget.element.ariaLabel, + }); + return { widget, render, opened, contextMenus, copied }; + } + + test('shows the title and status of the linked session as the sessions list does, and follows them', () => { + const status = observableValue('status', SessionStatus.InProgress); + const isRead = observableValue('isRead', true); + const completedStateIcon = observableValue('completedStateIcon', undefined); + const title = observableValue('title', 'Fix the login bug'); + const session = upcastPartial({ + resource: URI.parse('agent-host-copilotcli:/session-1'), + title, + status, + // The sessions list reads a session's row as read when its main chat is, whatever its peer chats are. + isRead: constObservable(false), + mainChat: constObservable(upcastPartial({ isRead })), + isArchived: constObservable(false), + completedStateIcon, + chats: constObservable([]), + }); + const { render } = createWidget([session]); + + const inProgress = render(); + status.set(SessionStatus.NeedsInput, undefined); + const needsInput = render(); + transaction(tx => { + status.set(SessionStatus.Completed, tx); + isRead.set(false, tx); + completedStateIcon.set(Codicon.gitPullRequest, tx); + title.set('Fixed the login bug', tx); + }); + const completed = render(); + + assert.deepStrictEqual({ inProgress, needsInput, completed }, { + inProgress: { label: 'Fix the login bug', displayName: 'Fix the login bug', icon: 'spinner', ariaLabel: 'Link to session Fix the login bug, In Progress' }, + needsInput: { label: 'Fix the login bug', displayName: 'Fix the login bug', icon: 'codicon-status-2', ariaLabel: 'Link to session Fix the login bug, Attention Needed' }, + completed: { label: 'Fixed the login bug', displayName: 'Fixed the login bug', icon: 'codicon-status-3-unread-git-pull-request', ariaLabel: 'Link to session Fixed the login bug, Completed' }, + }); + }); + + test('shows the chat that a chat link opens, and a session that the window does not know by the name of the link', () => { + const chat = upcastPartial({ + resource: URI.parse('agent-host-copilotcli:/session-1#chat-2'), + title: constObservable('Review the tests'), + status: constObservable(SessionStatus.Error), + isRead: constObservable(true), + isArchived: constObservable(false), + completedStateIcon: constObservable(undefined), + }); + const session = upcastPartial({ + resource: URI.parse('agent-host-copilotcli:/session-1'), + chats: constObservable([chat]), + workspace: constObservable(undefined), + }); + + assert.deepStrictEqual({ + chat: createWidget([session], URI.parse(buildOpenSessionLinkUri(backendSession, 'chat-2'))).render(), + unknown: createWidget([]).render(), + }, { + chat: { label: 'Review the tests', displayName: 'Review the tests', icon: 'codicon-status-4', ariaLabel: 'Link to chat Review the tests, Failed' }, + unknown: { label: 'Session', displayName: 'Session', icon: 'codicon-agent', ariaLabel: 'Link to session' }, + }); + }); + + test('opens the linked session when clicked, its context menu opens it or copies the link that the sessions list copies, and a middle click removes it', async () => { + const { widget, opened, contextMenus, copied } = createWidget([]); + let removed = 0; + store.add(widget.onDidDelete(() => removed++)); + + widget.element.click(); + widget.element.dispatchEvent(new MouseEvent('auxclick', { button: 1, bubbles: true, cancelable: true })); + widget.element.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + const actions = contextMenus[0]; + await actions.find(action => action.id === 'chat.sessionLinkAttachment.copyLink')?.run(); + await timeout(0); + + assert.deepStrictEqual({ opened, menu: actions.map(action => action.label), copied, removed }, { + removed: 1, + opened: ['agent-host-session://copilotcli/session-1'], + menu: ['Open Session', '', 'Copy Link'], + copied: ['code-oss://agents/agent-host-session/copilotcli/session-1'], + }); + }); +}); diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionTurnChanges.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionTurnChanges.test.ts index 20fbe6af767c..cc0c3a7af725 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionTurnChanges.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionTurnChanges.test.ts @@ -20,6 +20,8 @@ import { IChangesViewService } from '../../../../../workbench/contrib/sessions/c import { SessionsChatResponseFileChangesService } from '../../browser/sessionTurnChanges.js'; import { focusedSessionHostServiceOf, ITestSessionWithChat } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; import { isIChatSessionFileChange2 } from '../../../../../workbench/common/chatSessionFileChange.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IChatWindow, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { ISessionHost, ISessionHostService, SessionHostKind } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; suite('SessionTurnChanges', () => { @@ -31,6 +33,12 @@ suite('SessionTurnChanges', () => { }(); } + const noChatWindowService = new class extends mock() { + override getWindow(): IChatWindow | undefined { return undefined; } + }(); + const chatWindowServiceOf = (chatWindow: IChatWindow) => new class extends mock() { + override getWindow(windowId: number): IChatWindow | undefined { return windowId === 7 ? chatWindow : undefined; } + }(); const noChatWindows = new class extends mock() { override getHostOfChat(): ISessionHost | undefined { return undefined; @@ -100,6 +108,8 @@ suite('SessionTurnChanges', () => { layoutService, createChangesViewService(), noChatWindows, + noChatWindowService, + new NullLogService(), )); service.openChangesForRequest(chatResource, undefined, { isLastTurn: true }); @@ -190,6 +200,8 @@ suite('SessionTurnChanges', () => { layoutService, createChangesViewService(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable([{ @@ -294,6 +306,8 @@ suite('SessionTurnChanges', () => { layoutService, createChangesViewService(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable([]), @@ -315,7 +329,7 @@ suite('SessionTurnChanges', () => { mainChat: constObservable(mainWindowChat), activeChat: constObservable(chatWindowChat), }); - const chatWindowHost = upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined }); + const chatWindowHost = upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined, windowId: constObservable(7) }); const mainWindowHost = upcastPartial({ kind: SessionHostKind.MainWindow, parent: undefined }); const opened: object[] = []; const service = disposables.add(new SessionsChatResponseFileChangesService( @@ -349,6 +363,8 @@ suite('SessionTurnChanges', () => { return chatResource.toString() === chatWindowChat.resource.toString() ? chatWindowHost : mainWindowHost; } }(), + chatWindowServiceOf(upcastPartial({ mainPart: upcastPartial({}), showEditor: () => { } })), + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable([]), @@ -366,6 +382,63 @@ suite('SessionTurnChanges', () => { ]); }); + for (const registered of [true, false]) { + test(registered ? 'the changes of a chat shown in a chat window open there while the main window is the focused host, and leave the main window alone' : 'the changes of a chat in a chat window that is not available open nowhere, not even in the main window', async () => { + const chat = upcastPartial({ resource: URI.parse('chat:nested'), updatedAt: constObservable(new Date('2026-08-13T10:00:00Z')) }); + const session = upcastPartial({ + resource: URI.parse('agent-host:session'), + providerId: 'local-agent-host', + chats: constObservable([chat]), + mainChat: constObservable(chat), + activeChat: constObservable(chat), + }); + const otherSession = upcastPartial({ + resource: URI.parse('agent-host:other'), + chats: constObservable([]), + activeChat: constObservable(upcastPartial({ resource: URI.parse('chat:other') })), + }); + const chatWindowHost = upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined, windowId: constObservable(7) }); + const calls: string[] = []; + const group = { id: 42 }; + const chatWindow = upcastPartial({ + mainPart: upcastPartial({ activeGroup: upcastPartial(group) }), + showEditor: () => { calls.push('chatWindow.showEditor'); }, + }); + let openedIn: unknown; + const service = disposables.add(new SessionsChatResponseFileChangesService( + new class extends mock() { }(), + new class extends mock() { + override getSessionForChatResource() { + return { session, chat }; + } + }(), + new class extends mock() { + override async openChat(): Promise { calls.push('main.openChat'); } + override showSession(): void { calls.push('main.showSession'); } + }(), + // The main window stays the focused host, as it does while windows do not report focus. + focusedSessionHostServiceOf(constObservable(otherSession)), + new class extends mock() { + override async openChangesEditor(_resource: URI, _options?: ISessionChangesEditorOptions, targetGroup?: unknown): Promise { calls.push('openChangesEditor'); openedIn = targetGroup; return undefined; } + }(), + new class extends mock() { + override revealEditorPartExplicitly(): void { calls.push('main.revealEditorPartExplicitly'); } + }(), + createChangesViewService(), + new class extends mock() { + override getHostOfChat(): ISessionHost | undefined { return chatWindowHost; } + }(), + registered ? chatWindowServiceOf(chatWindow) : noChatWindowService, + new NullLogService(), + )); + + service.openChangesForRequest(chat.resource, 'latest', { isLastTurn: true }); + await timeout(0); + + assert.deepStrictEqual({ calls, openedIn }, registered ? { calls: ['chatWindow.showEditor', 'openChangesEditor'], openedIn: group } : { calls: [], openedIn: undefined }); + }); + } + test('selects the chat-owned Last Turn Changes when another chat is more recent', () => { const chatResource = URI.parse('chat:older'); const chat = upcastPartial({ @@ -430,6 +503,8 @@ suite('SessionTurnChanges', () => { }(), createChangesViewService(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable([{ @@ -479,6 +554,8 @@ suite('SessionTurnChanges', () => { new class extends mock() { }(), createChangesViewService(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('test', { getChangesForRequest: () => constObservable([{ @@ -536,6 +613,8 @@ suite('SessionTurnChanges', () => { override readonly activeSessionResourceObs = constObservable(session.resource); }(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable(AUTHORITATIVE_EMPTY_CHAT_RESPONSE_FILE_CHANGES), @@ -586,6 +665,8 @@ suite('SessionTurnChanges', () => { new class extends mock() { }(), changesViewService, noChatWindows, + noChatWindowService, + new NullLogService(), )); const stats = service.getChangeStatsForRequest(chatResource, 'request', { isLastTurn: true }); @@ -664,6 +745,8 @@ suite('SessionTurnChanges', () => { override readonly activeSessionResourceObs = constObservable(session.resource); }(), noChatWindows, + noChatWindowService, + new NullLogService(), )); disposables.add(service.registerProvider('chat', { getChangesForRequest: () => constObservable([{ @@ -735,6 +818,8 @@ suite('SessionTurnChanges', () => { override readonly activeSessionResourceObs = constObservable(session.resource); }(), noChatWindows, + noChatWindowService, + new NullLogService(), )); const stats = service.getChangeStatsForRequest(chatResource, 'request', { isLastTurn: true }); 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 d4c7adb9429c..d7b24c7d01c9 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts @@ -84,7 +84,7 @@ import { NullHoverService } from '../../../../../platform/hover/test/browser/nul import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; import { hasOnboardingTargetSelection, onDidSelectOnboardingTarget } from '../../../../../workbench/contrib/onboarding/browser/spotlight/onboardingTarget.js'; -import { ISessionCreationEnvironment } from '../../../../../workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.js'; +import { getDefaultSessionCreationEnvironment, ISessionCreationEnvironment } from '../../../../../workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.js'; // ---- Storage key (must match the one in sessionWorkspacePicker.ts) ---------- const STORAGE_KEY_RECENT_WORKSPACES = 'sessions.recentlyPickedWorkspaces'; @@ -1430,6 +1430,53 @@ suite('WorkspacePicker - Environment', () => { } } + for (const remote of [false, true]) { + test(`keeps repository and context actions available in ${remote ? 'remote' : 'local'} environments when Cloud has no creatable types`, async () => { + const providers = disposables.add(new MockSessionsProvidersService()); + const execution = createMockProvider(remote ? 'remote' : 'local-agent-host'); + const folder = remote ? URI.parse('vscode-agent-host://host/project') : URI.file('/agent-host/project'); + const environment: ISessionCreationEnvironment = { + id: execution.id, kind: remote ? 'remote' : 'local', label: remote ? 'Remote' : 'This Computer', + icon: Codicon.remote, providerIds: [execution.id], + }; + const repositoryRoot = URI.parse('github-remote-file://github/microsoft/vscode/HEAD'); + const repository = { ...createMockProvider('github').resolveWorkspace(repositoryRoot)!, group: SESSION_WORKSPACE_GROUP_GITHUB }; + const actions = ['Work in Repository...', 'Issue...', 'Pull Request...'].map((label, index) => ({ + ...makeBrowseAction('github', SESSION_WORKSPACE_GROUP_GITHUB, label), + attachesContext: index > 0, + run: async () => ({ ...repository, label }), + })); + providers.setProviders([ + { ...execution, supportsLocalWorkspaces: !remote, cloneRepository: async () => execution.resolveWorkspace(folder)! }, + { ...createMockProvider('github', { browseActions: actions }), supportsLocalWorkspaces: true, sessionTypes: [] }, + ]); + const canSelect: (string | undefined)[] = []; + const picker = createTestPicker(disposables, providers, undefined, undefined, DispatchingWorkspacePicker, {}, undefined, undefined, { + environment: constObservable(environment), restoreFromSessions: false, configuration: {}, + commandService: { executeCommand: async () => folder.fsPath as T }, + canSelectWorkspace: async (_uri, providerId) => { canSelect.push(providerId); return true; }, + }); + assert.ok(picker instanceof DispatchingWorkspacePicker); + const browseActions = picker.getItems().filter(item => item.item?.browseActionIndex !== undefined).map(item => item.label); + const attached: string[] = []; + disposables.add(picker.onDidSelectContext(context => attached.push(context.label))); + const accepted: boolean[] = []; + for (const action of actions) { + accepted.push(await picker.dispatchItem({ browseAction: action })); + } + assert.deepStrictEqual({ + browseActions, accepted, attached, canSelect, + folder: picker.selectedFolderUri?.toString(), + provider: picker.selectedResolved?.providerId, + }, { + browseActions: [...(remote ? [] : ['Open Folder...']), 'Work in Repository', 'Issue', 'Pull Request'], + accepted: [true, true, true], attached: ['Issue...', 'Pull Request...'], + canSelect: [execution.id, 'github', 'github'], + folder: folder.toString(), provider: execution.id, + }); + }); + } + test('reports failed container checks separately from unsupported folders', async () => { const expectedError = new Error('container detection failed'); const errors: Error[] = []; @@ -2320,8 +2367,8 @@ suite('WorkspacePicker - Connection Status', () => { triggerAriaLabel: container.querySelector('.action-label')?.getAttribute('aria-label'), }, { stableItemIds: [ - 'workspacePicker.workspace.file:///agent-host/project', - 'workspacePicker.workspace.file:///agent-host/project', + 'workspacePicker.workspace.0', + 'workspacePicker.workspace.0', ], initialSubmenu: [ { label: 'Use This Computer', tooltip: '', checked: true }, @@ -3528,6 +3575,28 @@ suite('WorkspacePicker - Connection Status', () => { }); }); + test('reloading a checked Cloud workspace retains Cloud when This Computer also resolves the folder', () => { + const folder = URI.file('/local/project'); + const local = createMockProvider('local-1'); + const cloud = createMockProvider('cloud'); + const storage = disposables.add(new TestStorageService()); + providersService.setProviders([cloud, local]); + const picker = createTestPicker(disposables, providersService, storage); + picker.setSelectedWorkspace(folder, { providerId: cloud.id, fireEvent: false }); + + const reloaded = createTestPicker(disposables, providersService, storage); + const environment = getDefaultSessionCreationEnvironment([ + { id: 'local', kind: 'local', label: 'This Computer', icon: Codicon.deviceDesktop, providerIds: [local.id] }, + { id: 'cloud', kind: 'cloud', label: 'Cloud', icon: Codicon.cloud, providerIds: [cloud.id] }, + ], reloaded.selectedFolderUri, reloaded.selectedResolved?.providerId, false, undefined, + reloaded.preselectionSource === NewSessionWorkspacePreselectionSource.CheckedWorkspace); + assert.deepStrictEqual({ + folder: reloaded.selectedFolderUri?.toString(), + provider: reloaded.selectedResolved?.providerId, + environment: environment?.id, + }, { folder: folder.toString(), provider: cloud.id, environment: 'cloud' }); + }); + test('local provider is never treated as unavailable', () => { const localProvider = createMockProvider('local-1'); @@ -7751,6 +7820,34 @@ suite('WorkspacePicker - Tab discovery', () => { assert.deepStrictEqual(picker.getItemsForFilter('folder-10').flatMap(entry => entry.item?.folderUri?.path ?? []), ['/local/folder-10']); }); + test('keeps workspace row IDs stable across filtering and refreshes', () => { + const storage = disposables.add(new TestStorageService()); + seedStorage(storage, ['first', 'second', 'third'].map(name => ({ + uri: URI.file(`/local/${name}`), + providerId: 'local-1', + checked: false, + }))); + providersService.setProviders([createMockProvider('local-1')]); + const picker = createTestablePicker(disposables, providersService, true, { restoreFromSessions: false }, undefined, storage); + const getWorkspaceIds = (items: readonly IActionListItem[]) => items + .filter(entry => entry.item?.folderUri) + .map(entry => ({ folder: entry.item?.folderUri?.path, id: entry.item?.id })); + + const initial = getWorkspaceIds(picker.getItems()); + const filtered = getWorkspaceIds(picker.getItemsForFilter('third')); + const refreshed = getWorkspaceIds(picker.getItemsForFilter('')); + + assert.deepStrictEqual({ initial, filtered, refreshed }, { + initial: [ + { folder: '/local/first', id: 'workspacePicker.workspace.0' }, + { folder: '/local/second', id: 'workspacePicker.workspace.1' }, + { folder: '/local/third', id: 'workspacePicker.workspace.2' }, + ], + filtered: [{ folder: '/local/third', id: 'workspacePicker.workspace.2' }], + refreshed: initial, + }); + }); + test('strips only trailing ellipses from unified browse action labels', () => { const labels = ['Repository...', 'Repository\u2026', 'Repo...sitory', 'Repo\u2026sitory', 'Repository']; providersService.setProviders([ 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 771c7115fdef..d3becbab2a41 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts @@ -29,7 +29,7 @@ import { ISessionsPartService } from '../../../../../workbench/services/sessions import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { IChat } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionComparison, ISessionComparisonService, SessionComparisonParticipantRole } from '../../../../../workbench/contrib/sessions/common/sessionComparison.js'; -import { AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING, AGENTS_PICKER_IN_ATTACH_CONTEXT_MENU_SETTING, COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_CONNECTOR_RECOMMENDATIONS_SETTING, NEW_SESSION_WELCOME_PHRASES_SETTING, WORKSPACE_OPT_OUT_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; +import { AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING, AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING, AGENTS_PICKER_IN_ATTACH_CONTEXT_MENU_SETTING, COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_CONNECTOR_RECOMMENDATIONS_SETTING, NEW_SESSION_WELCOME_PHRASES_SETTING, WORKSPACE_OPT_OUT_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { TestExperimentTriggerTelemetryService } from '../../../../../platform/telemetry/test/common/experimentTriggerTestUtils.js'; import { SESSION_ARCHIVE_NUDGE_SETTING } from '../../../../../workbench/contrib/sessions/browser/chat/sessionArchiveNudge.js'; @@ -45,6 +45,10 @@ import { DevContainerAgentHostEnabledSettingId, DevContainerSamplesEnabledSettin import { getCloudSandboxPreparationAccessibilityHelp } from '../../../../../workbench/contrib/chat/browser/actions/chatAccessibilityHelp.js'; import { CHAT_WINDOWS_ENABLED_SETTING } from '../../../chatWindow/common/chatWindows.js'; import type { SessionView } from '../../../../../workbench/contrib/sessions/browser/parts/sessionView.js'; +import { IsSessionsWindowContext } from '../../../../../workbench/common/contextkeys.js'; +import { KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED } from '../../../../../workbench/contrib/webview/browser/webview.js'; +import { WebviewFindAccessibilityHelp } from '../../../../../workbench/contrib/webview/browser/webviewFindAccessibilityHelp.js'; +import { ChatConfiguration } from '../../../../../workbench/contrib/chat/common/constants.js'; import { ITestSessionWithChat, testGridPane } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; suite('SessionsChatAccessibilityHelp', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -64,10 +68,29 @@ suite('SessionsChatAccessibilityHelp', () => { instantiationService.stub(IAgentHostFilterService, { selectedHost: undefined }); instantiationService.stub(IWorkbenchLayoutService, { mainContainer: mainWindow.document.createElement('div') }); instantiationService.stub(ISessionsHostLayoutService, {}); - return store.add(new SessionsChatAccessibilityHelp().getProvider(instantiationService)).provideContent() - .includes('With sessions.list.inlineActions enabled, eligible rows show Fix Checks, Address Comments, or Fix Checks & Address Comments below the metadata.'); + const content = store.add(new SessionsChatAccessibilityHelp().getProvider(instantiationService)).provideContent(); + return { + actions: content.includes('With sessions.list.inlineActions enabled, eligible rows show Fix Checks, Address Comments, or Fix Checks & Address Comments below the metadata.'), + retry: content.includes('If sending fails, an error notification appears and the action remains available to retry.'), + }; }); - assert.deepStrictEqual(results, [false, true, false]); + assert.deepStrictEqual(results, [{ actions: false, retry: false }, { actions: true, retry: true }, { actions: false, retry: false }]); + }); + + test('defers to webview Find help while the Find input is focused', () => { + const configuration = new TestConfigurationService(); + store.add(configuration.onDidChangeConfigurationEmitter); + const context = store.add(new ContextKeyService(configuration)); + IsSessionsWindowContext.bindTo(context).set(true); + const findFocused = KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED.bindTo(context); + const implementations = [new SessionsChatAccessibilityHelp(), new WebviewFindAccessibilityHelp()]; + assert.deepStrictEqual([false, true].map(focused => { + findFocused.set(focused); + return implementations + .filter(implementation => context.contextMatchesRules(implementation.when)) + .sort((a, b) => b.priority - a.priority) + .map(implementation => implementation.name); + }), [['sessionsChat'], ['webview-find']]); }); test('documents comment card previews, secondary actions and review states', () => { @@ -92,10 +115,15 @@ suite('SessionsChatAccessibilityHelp', () => { }, { preview: true, keyboard: true, scrolling: true, secondaryActions: true, states: true }); }); - for (const { aiDisabled, hidden } of [{ aiDisabled: false, hidden: false }, { aiDisabled: true, hidden: false }, { aiDisabled: false, hidden: true }]) { - test(`documents View Mode only when AI is visible (disabled: ${aiDisabled}, hidden: ${hidden})`, () => { + for (const { aiDisabled, hidden, htmlEnabled } of [ + { aiDisabled: false, hidden: false, htmlEnabled: true }, + { aiDisabled: true, hidden: false, htmlEnabled: true }, + { aiDisabled: false, hidden: true, htmlEnabled: true }, + { aiDisabled: false, hidden: false, htmlEnabled: false }, + ]) { + test(`documents View Mode only when AI is visible (disabled: ${aiDisabled}, hidden: ${hidden}, HTML: ${htmlEnabled})`, () => { const instantiation = store.add(new TestInstantiationService()); - const configuration = new TestConfigurationService({ 'chat.disableAIFeatures': aiDisabled }); + const configuration = new TestConfigurationService({ 'chat.disableAIFeatures': aiDisabled, [ChatConfiguration.HtmlPreviewEnabled]: htmlEnabled }); store.add(configuration.onDidChangeConfigurationEmitter); instantiation.stub(IConfigurationService, configuration); stubContextKeyService(instantiation, configuration); @@ -106,13 +134,30 @@ suite('SessionsChatAccessibilityHelp', () => { instantiation.stub(IWorkbenchLayoutService, { mainContainer: mainWindow.document.createElement('div') }); instantiation.stub(ISessionsHostLayoutService, {}); const help = store.add(new SessionsChatAccessibilityHelp().getProvider(instantiation)).provideContent(); + const visible = !aiDisabled && !hidden; + const rendersHtml = visible && htmlEnabled; assert.deepStrictEqual({ modes: help.includes('View Mode to select Compact, Verbose, or Conversation'), checked: help.includes('The active mode is checked'), setting: help.includes('Selecting a mode updates chat.persistentProgressVerbosity'), thinking: help.includes('only when a live section finishes with its header in view'), noBackfill: help.includes('Opening a chat, returning to it, scrolling or expanding existing sections never generates titles'), - }, { modes: !aiDisabled && !hidden, checked: !aiDisabled && !hidden, setting: !aiDisabled && !hidden, thinking: !aiDisabled && !hidden, noBackfill: !aiDisabled && !hidden }); + htmlPreview: help.includes('html-preview code fence'), + htmlSourceToggle: help.includes('Use Tab to focus the HTML preview and press Shift+F10'), + htmlAccessibleSource: help.includes('original source is also available in the chat Accessible View'), + htmlExport: help.includes('Save HTML asks where to save a sanitized, self-contained HTML file'), + htmlExpansion: help.includes('Open Preview opens a larger editor'), + htmlScrolling: help.includes('Inline previews grow to fit their content and scroll with the chat transcript.'), + htmlFindSource: help.includes('Find in Chat searches the original HTML and shows source'), + htmlSetting: help.includes(ChatConfiguration.HtmlPreviewEnabled), + htmlDisabled: help.includes('Inline HTML previews are disabled'), + htmlSkillAdvertised: help.includes('built-in /html-preview skill'), + }, { + modes: visible, checked: visible, setting: visible, thinking: visible, noBackfill: visible, + htmlPreview: visible, htmlSourceToggle: rendersHtml, htmlAccessibleSource: rendersHtml, htmlExport: rendersHtml, + htmlExpansion: rendersHtml, htmlScrolling: rendersHtml, htmlFindSource: rendersHtml, htmlSetting: visible, htmlDisabled: visible && !htmlEnabled, + htmlSkillAdvertised: rendersHtml, + }); }); } @@ -754,7 +799,7 @@ suite('SessionsChatAccessibilityHelp', () => { hasClearWorkspace: true, }, { - controls: 'When an Agent picker is available in a new or running session, it appears in Add Context when the default agent is selected. Open Add Context and choose Agent to select an agent. While a custom agent is selected, the Agent picker appears in its usual position. Selecting the default agent moves it back into Add Context. Other new-session controls remain in their layout-specific positions. Use Tab to reach toolbar controls, arrow keys to navigate toolbar items, and Enter or Space to open a picker.', + controls: 'When an Agent picker is available in a new or running session, it appears in Add Context when the default agent is selected. Open Add Context and choose Agent to select an agent. A one-time spotlight may explain this change. Activate Understood or press Escape to dismiss it, or activate the highlighted Add Context action to open the menu and dismiss the tip. While a custom agent is selected, the Agent picker appears in its usual position. Selecting the default agent moves it back into Add Context. Other new-session controls remain in their layout-specific positions. Use Tab to reach toolbar controls, arrow keys to navigate toolbar items, and Enter or Space to open a picker.', sync: 'When available for a folder session with incoming or outgoing commits, Sync Changes appears with the commit counts in the same repository toolbar as the worktree and branch controls above the input. It is hidden when New Worktree is selected. Use Tab and the arrow keys to reach it, then Enter or Space to synchronize the session\'s repository. The action is disabled while synchronization is running.', hasSessionOptions: true, sessionOptionsMentionsToggle: true, @@ -885,7 +930,7 @@ suite('SessionsChatAccessibilityHelp', () => { }); }); - test('describes the Ask Question input when the response-selection menu is disabled', () => { + test('omits response-selection help when the menu is disabled', () => { const instantiationService = store.add(new TestInstantiationService()); const configuration = new TestConfigurationService({ [AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING]: false, @@ -900,10 +945,7 @@ suite('SessionsChatAccessibilityHelp', () => { instantiationService.stub(ISessionsHostLayoutService, {}); const provider = store.add(new SessionsChatAccessibilityHelp(true).getProvider(instantiationService)); - assert.strictEqual( - provider.provideContent().split('\n').find(line => line.startsWith('When you select assistant response text')), - 'When you select assistant response text, an Ask Question input appears. Type a side question and press Enter to send it, press Shift+Enter to insert a new line, or press Escape to dismiss the input.', - ); + assert.strictEqual(provider.provideContent().split('\n').find(line => line.startsWith('When you select assistant response text')), undefined); }); test('describes the response-selection menu when enabled', () => { @@ -944,7 +986,8 @@ suite('SessionsChatAccessibilityHelp', () => { assert.deepStrictEqual({ listedInKindPills: content?.includes('Other integrated artifacts and references are listed in the Artifacts, References, Pull Requests or Issues pill'), listedRowDetails: content?.includes('where Enter or Space opens the artifact\'s details and the row\'s Open action opens the resource'), - mainDetails: content?.includes('Enter or Space on a main pill opens an input-width details panel'), + mainOpens: content?.includes('Enter or Space on a main pill opens its resource'), + mainDetails: content?.includes('or a Details section when it has none, open an input-width details panel'), runOnce: content?.includes('Actions below the lists run once'), standingPermission: content?.includes('standing permission'), turningOff: content?.includes('does not cancel work already started'), @@ -953,7 +996,7 @@ suite('SessionsChatAccessibilityHelp', () => { switchKeyboard: content?.includes('Space to change a switch'), listKeyboard: content?.includes('arrow keys navigate list rows'), oldActionsSegment: content?.includes('Actions button'), - }, { listedInKindPills: true, listedRowDetails: true, mainDetails: true, runOnce: true, standingPermission: true, turningOff: true, sharedAutomation: true, enabledAutomation: true, switchKeyboard: true, listKeyboard: true, oldActionsSegment: false }); + }, { listedInKindPills: true, listedRowDetails: true, mainOpens: true, mainDetails: true, runOnce: true, standingPermission: true, turningOff: true, sharedAutomation: true, enabledAutomation: true, switchKeyboard: true, listKeyboard: true, oldActionsSegment: false }); }); test('describes grouped artifact pills, their list navigation, and pinning', () => { @@ -974,10 +1017,11 @@ suite('SessionsChatAccessibilityHelp', () => { grouped: content?.includes('they appear as one pill named by the integration'), rows: content?.includes('Up and Down Arrow, Home and End move between artifacts'), controls: content?.includes('Left and Right Arrow move between an artifact\'s controls'), - details: content?.includes('opens the artifact\'s details'), + opens: content?.includes('Enter or Space on the label opens the artifact\'s resource'), + details: content?.includes('offers a Details section that opens its details'), pin: content?.includes('Pin moves the artifact into a pill of its own'), escape: content?.includes('Escape closes the list and returns focus to the pill'), - }, { grouped: true, rows: true, controls: true, details: true, pin: true, escape: true }); + }, { grouped: true, rows: true, controls: true, opens: true, details: true, pin: true, escape: true }); }); test('omits response-selection help when the widget is unsupported', () => { @@ -1150,6 +1194,22 @@ suite('SessionsChatAccessibilityHelp', () => { }, { activation: true, nextButton: true, tintKeyboardAccess: true, tintCheckedState: true, tintPreservesImage: true }); }); + test('mobile help omits unavailable background controls and generation even when appearance tools are configured', () => { + const instantiationService = store.add(new TestInstantiationService()); + const configuration = new TestConfigurationService({ [AGENT_SESSIONS_APPEARANCE_TOOLS_ENABLED_SETTING]: true }); + store.add(configuration.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configuration); + stubContextKeyService(instantiationService, configuration); + instantiationService.stub(ISessionsPartService, new class extends mock() { }()); + instantiationService.stub(ISessionsService, new class extends mock() { }()); + instantiationService.stub(IAgentHostFilterService, { selectedHost: undefined }); + instantiationService.stub(IWorkbenchLayoutService, { mainContainer: mainWindow.document.createElement('div') }); + instantiationService.stub(ISessionsHostLayoutService, {}); + const content = store.add(new SessionsChatAccessibilityHelp(undefined, false).getProvider(instantiationService)).provideContent(); + assert.deepStrictEqual(['Set Background', 'Change Background Layout', 'Tint Window to Match Background', 'Celebrate button', 'Get Theme Colors', '/generate-chat-background'] + .filter(text => content.includes(text)), []); + }); + test('describes generic directional navigation for the session grid', () => { const instantiationService = store.add(new TestInstantiationService()); const configuration = new TestConfigurationService(); @@ -1197,7 +1257,9 @@ suite('SessionsChatAccessibilityHelp', () => { assert.deepStrictEqual({ tools: [defaultHelp, enabledHelp, disabledHelp].map(content => content.includes('ask an agent to discover comparison models')), manualComparison: defaultHelp.includes('activate Compare Models'), - }, { tools: [false, true, false], manualComparison: true }); + openComparison: enabledHelp.includes('Use Tab to reach Open Comparison in the tool result and Enter'), + scopedDiscovery: enabledHelp.includes('list comparisons started by this chat'), + }, { tools: [false, true, false], manualComparison: true, openComparison: true, scopedDiscovery: true }); }); test('describes Run and Compare Agents only when enabled', async () => { diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionsWorkbenchFixtureUtils.ts b/src/vs/sessions/contrib/chat/test/browser/sessionsWorkbenchFixtureUtils.ts index db01b4734e5d..6821f855902d 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionsWorkbenchFixtureUtils.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionsWorkbenchFixtureUtils.ts @@ -126,6 +126,7 @@ export function createSessionsWorkbenchFixture(context: ComponentFixtureContext, } override isEditorPaneVisible() { return sidePaneVisible; } override isModernUICompact() { return options.compactDensity === true; } + override getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; } override getPanelAlignment() { return 'justify' as const; } override getContainer() { return container; } }(); diff --git a/src/vs/sessions/contrib/chat/test/browser/sharedChatInputComposerActions.test.ts b/src/vs/sessions/contrib/chat/test/browser/sharedChatInputComposerActions.test.ts index 16079b77f8cc..fde8694192cd 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sharedChatInputComposerActions.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sharedChatInputComposerActions.test.ts @@ -18,8 +18,10 @@ import { IChatWidget, IChatWidgetService } from '../../../../../workbench/contri import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { SharedChatInputComposer } from '../../../../../workbench/contrib/sessions/browser/chat/sharedChatInputComposer.js'; import { ChatInputSupportsBackgroundContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { SessionsViewGroupingContext } from '../../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; import { SEND_IN_BACKGROUND_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; import { SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { SessionsGrouping } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { SendInBackgroundAction } from '../../browser/sharedChatInputComposer.contribution.js'; suite('Send in Background', () => { @@ -32,7 +34,7 @@ suite('Send in Background', () => { item.command === SEND_IN_BACKGROUND_COMMAND_ID && item.keybinding?.getHashCode() === keybinding.getHashCode()); const when = rule?.when; assert.ok(when); - const values: Record = { + const values: Record = { [IsSessionsWindowContext.key]: true, [ChatContextKeys.enabled.key]: true, [ChatContextKeys.inChatInput.key]: true, @@ -40,9 +42,10 @@ suite('Send in Background', () => { [ChatContextKeys.inputHasSendableContent.key]: true, [ChatContextKeys.inputBlocked.key]: false, [ChatContextKeys.chatSessionOptionsValid.key]: true, - [`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`]: true, + [SessionsViewGroupingContext.key]: SessionsGrouping.Inbox, + [`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`]: false, }; - const matches = (overrides: Record = {}) => { + const matches = (overrides: Record = {}) => { const context: IContext = { getValue: (key: string) => ({ ...values, ...overrides })[key] as T | undefined }; return when.evaluate(context); }; @@ -55,11 +58,11 @@ suite('Send in Background', () => { empty: matches({ [ChatContextKeys.inputHasSendableContent.key]: false }), blocked: matches({ [ChatContextKeys.inputBlocked.key]: true }), invalidOptions: matches({ [ChatContextKeys.chatSessionOptionsValid.key]: false }), - inboxDisabled: matches({ [`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`]: false }), + workspaceGrouping: matches({ [SessionsViewGroupingContext.key]: SessionsGrouping.Workspace, [`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`]: true }), }, { composer: true, regularWindow: false, aiDisabled: false, toolbar: false, existingChat: false, empty: false, blocked: false, invalidOptions: false, - inboxDisabled: modifier === KeyMod.Alt, + workspaceGrouping: modifier === KeyMod.Alt, }); }); } diff --git a/src/vs/sessions/contrib/chat/test/browser/sideChatProvider.test.ts b/src/vs/sessions/contrib/chat/test/browser/sideChatProvider.test.ts index a5a6ab87d4d8..0281f13149df 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sideChatProvider.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sideChatProvider.test.ts @@ -73,11 +73,12 @@ suite('SessionsSideChatProviderContribution', () => { const activeSession = observableValue(store, session); const navigationRequest = observableValue(store, undefined); const gridSession = upcastPartial({ sessionId: 'grid', resource: URI.parse('test:///grid'), chats: constObservable([]), activeChat: constObservable(upcastPartial({ resource: URI.parse('test:///grid/chat') })) }); + const windowSessions = observableValue(store, options.inChatWindow ? [session] : []); const mainWindowSession = options.inChatWindow ? observableValue(store, gridSession) : activeSession; instantiationService.stub(ISessionHostService, sessionHostServiceOf(store, { mainWindowActiveSession: mainWindowSession, gridShown: options.inChatWindow ? derived(reader => [mainWindowSession.read(reader)]) : constObservable([session]), - windowSessions: constObservable(options.inChatWindow ? [session] : []), + windowSessions, })); let registered: SessionsSideChatProviderContribution | undefined; @@ -98,6 +99,7 @@ suite('SessionsSideChatProviderContribution', () => { const callOrder: string[] = []; const requests: ISendRequestOptions[] = []; const contextInheritance: (boolean | undefined)[] = []; + const openReferences: (string | undefined)[] = []; const sendRequest: ISessionsManagementService['sendRequest'] = async (_session, chat, requestOptions) => { callOrder.push(`send:${chat.resource.toString()}:${requestOptions.query}`); requests.push(requestOptions); @@ -127,8 +129,9 @@ suite('SessionsSideChatProviderContribution', () => { slotPanes: testGridPanes(constObservable([session])), activeSession, navigationRequest, - openChat: async (_session, chatUri) => { + openChat: async (_session, chatUri, openOptions) => { callOrder.push(`open:${chatUri.toString()}`); + openReferences.push(openOptions?.referenceChatResource?.toString()); if (options.fail === 'open') { throw new Error('Open failed'); } @@ -149,7 +152,7 @@ suite('SessionsSideChatProviderContribution', () => { })); store.add(instantiationService.createInstance(SessionsSideChatProviderContribution)); - return { provider: () => registered, callOrder, requests, contextInheritance, activeSession, activeChat, navigationRequest, session, mainWindowSession, gridSession }; + return { provider: () => registered, callOrder, openReferences, requests, contextInheritance, activeSession, activeChat, navigationRequest, session, mainWindowSession, gridSession, windowSessions }; } test('registers a provider that branches, opens, then sends on the side chat', async () => { @@ -221,7 +224,30 @@ suite('SessionsSideChatProviderContribution', () => { }); } - test('a side chat from a chat window is not sent in the background when the main window switches sessions meanwhile', async () => { + test('a side chat from a chat window opens beside its source chat there, and is not split in the main window grid', async () => { + const { provider, callOrder, openReferences, requests } = setup({ inChatWindow: true }); + + await provider()!.askInSideChat(sourceChat.resource, 'question'); + + assert.deepStrictEqual({ callOrder, openReferences, requests }, { + callOrder: ['create:turn-1:', `open:${sideChat.resource.toString()}`, `send:${sideChat.resource.toString()}:question`], + openReferences: [sourceChat.resource.toString()], + requests: [{ query: 'question', attachedContext: undefined, background: true }], + }); + }); + + test('a side chat from the main window opens beside its source chat and splits in the grid', async () => { + const { provider, callOrder, openReferences } = setup(); + + await provider()!.askInSideChat(sourceChat.resource, 'question'); + + assert.deepStrictEqual({ callOrder, openReferences }, { + callOrder: ['create:turn-1:', `open:${sideChat.resource.toString()}`, `split:${sideChat.resource.toString()}`, `send:${sideChat.resource.toString()}:question`], + openReferences: [sourceChat.resource.toString()], + }); + }); + + test('a side chat from a chat window is sent once in the background, so it neither discards the main window draft nor is it followed there', async () => { const creation = new DeferredPromise(); const harness = setup({ inChatWindow: true, onCreateSideChat: () => creation.p }); const request = harness.provider()!.askInSideChat(sourceChat.resource, 'question', undefined, undefined); @@ -232,7 +258,22 @@ suite('SessionsSideChatProviderContribution', () => { await creation.complete(); await request; - assert.deepStrictEqual(harness.requests.map(request => request.background ?? false), [false]); + assert.deepStrictEqual(harness.requests.map(request => request.background ?? false), [true]); + }); + + test('a side chat is sent in the background without opening or splitting when its source chat window closes while it is created', async () => { + const creation = new DeferredPromise(); + const harness = setup({ inChatWindow: true, onCreateSideChat: () => creation.p }); + const request = harness.provider()!.askInSideChat(sourceChat.resource, 'question'); + + harness.windowSessions.set([], undefined); + await creation.complete(); + await request; + + assert.deepStrictEqual({ callOrder: harness.callOrder, requests: harness.requests }, { + callOrder: ['create:turn-1:', `send:${sideChat.resource.toString()}:question`], + requests: [{ query: 'question', attachedContext: undefined, background: true }], + }); }); test('does not split or follow a side chat when navigation supersedes its pending open', async () => { diff --git a/src/vs/sessions/contrib/chat/test/electron-browser/agentsWindowWorkspaceHandoff.test.ts b/src/vs/sessions/contrib/chat/test/electron-browser/agentsWindowWorkspaceHandoff.test.ts index 950162b1e455..006b09b85a47 100644 --- a/src/vs/sessions/contrib/chat/test/electron-browser/agentsWindowWorkspaceHandoff.test.ts +++ b/src/vs/sessions/contrib/chat/test/electron-browser/agentsWindowWorkspaceHandoff.test.ts @@ -19,7 +19,7 @@ import { TestLifecycleService } from '../../../../../workbench/test/common/workb import { ISessionsWindowOpenContext, SessionsWindowOpenTelemetry } from '../../../sessions/browser/sessionsWindowOpenTelemetry.js'; import { AgentsWindowRequestActivity, SelectAgentsFolderContribution } from '../../electron-browser/chat.contribution.js'; import { Emitter } from '../../../../../base/common/event.js'; -import { ISession } from '../../../../../workbench/services/sessions/common/session.js'; +import { IChat, ISession } from '../../../../../workbench/services/sessions/common/session.js'; import { InMemoryStorageService } from '../../../../../platform/storage/common/storage.js'; import { IAgentsWindowWorkspaceHandoff } from '../../browser/agentsWindowWorkspaceHandoff.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -35,6 +35,13 @@ import { NullLogService } from '../../../../../platform/log/common/log.js'; import { extUri } from '../../../../../base/common/resources.js'; import { remoteAgentHostSessionTypeId } from '../../../../../platform/agentHost/common/agentHostSessionType.js'; import { RemoteAgentHostHandoffResult } from '../../../../common/remoteWorkspaceHandoff.js'; +import { observableValue } from '../../../../../base/common/observable.js'; +import { buildOpenSessionLinkUri } from '../../../../../platform/agentHost/common/openSessionLink.js'; +import { IChatWindow, IChatWindowOpenOptions } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { CHAT_WINDOWS_ENABLED_SETTING } from '../../../chatWindow/common/chatWindows.js'; +import { IAgentHostSessionResolution } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IAgentConnection } from '../../../../../platform/agentHost/common/agentService.js'; +import type { IAgentSessionMetadata } from '../../../../../platform/agentHost/common/agent.js'; const getSessionForResource = Reflect.get(SelectAgentsFolderContribution.prototype, 'getSessionForResource') as ( chatResource: URI, @@ -264,10 +271,16 @@ suite('Agents Window workspace handoff telemetry', () => { }); }); - test('opens sessions of tunnel editor windows under this window\'s connection and silently falls back for other remotes', async () => { + test('opens shared SSH, WSL and tunnel sessions and silently falls back for unsupported remotes', async () => { const sessionType = remoteAgentHostSessionTypeId('tunnel-box', 'copilotcli'); const known = URI.parse(`${sessionType}:/known#chat`); + const ssh = URI.parse(`${remoteAgentHostSessionTypeId('ssh-host', 'copilotcli')}:/known#chat`); + const wsl = URI.parse(`${remoteAgentHostSessionTypeId('wsl-Ubuntu', 'copilotcli')}:/known#chat`); + const knownResources = [known, ssh, wsl]; const hosts: Record = { + 'ssh-remote+host': { connectionAuthority: 'ssh-host', connected: Promise.resolve(true), sharesEditorWindowAgentHost: () => true }, + 'ssh-remote+editor': { connectionAuthority: 'ssh-editor', connected: Promise.resolve(true), sharesEditorWindowAgentHost: () => false }, + 'wsl+Ubuntu': { connectionAuthority: 'wsl-Ubuntu', connected: Promise.resolve(true), sharesEditorWindowAgentHost: () => true }, 'tunnel+box': { connectionAuthority: 'tunnel-box', connected: Promise.resolve(true), sharesEditorWindowAgentHost: () => true }, 'tunnel+editor': { connectionAuthority: 'tunnel-box', connected: Promise.resolve(true), sharesEditorWindowAgentHost: () => false }, 'tunnel+offline': { connectionAuthority: 'tunnel-offline', connected: Promise.resolve(false), sharesEditorWindowAgentHost: () => true }, @@ -284,8 +297,8 @@ suite('Agents Window workspace handoff telemetry', () => { logService: new NullLogService(), // Another chat of the same session is focused. _focusedSessionHostService: { focusedHost: { get: () => ({ chatResource: { get: () => URI.parse(`${sessionType}:/known#focused`) } }) } }, - waitForSessionAvailable: async (resource: URI) => extUri.isEqual(resource, known), - getSessionForResource: (resource: URI) => extUri.isEqual(resource, known) ? upcastPartial({ resource: known }) : undefined, + waitForSessionAvailable: async (resource: URI) => knownResources.some(known => extUri.isEqual(resource, known)), + getSessionForResource: (resource: URI) => knownResources.some(known => extUri.isEqual(resource, known)) ? upcastPartial({ resource }) : undefined, sessionsService: { openChat: async (_session: ISession, chatResource: URI) => { opened.push(chatResource.toString()); } }, }; for (const [remoteAuthority, resource] of [ @@ -296,18 +309,23 @@ suite('Agents Window workspace handoff telemetry', () => { ['tunnel+offline', 'agent-host-copilotcli:/known#chat'], ['tunnel+unknown', 'agent-host-copilotcli:/known#chat'], ['ssh-remote+host', 'agent-host-copilotcli:/known#chat'], + ['ssh-remote+editor', 'agent-host-copilotcli:/known#chat'], + ['wsl+Ubuntu', 'agent-host-copilotcli:/known#chat'], + ['dev-container+2f736f75726365', 'agent-host-copilotcli:/known#chat'], + ['codespaces+host', 'agent-host-copilotcli:/known#chat'], ]) { results.push(await harness.resolveAndOpenRemoteSession(URI.parse(resource), remoteAuthority, CancellationToken.None)); } assert.deepStrictEqual({ resolved, opened, notifications, results }, { - resolved: ['tunnel+box', 'tunnel+box', 'tunnel+box', 'tunnel+editor', 'tunnel+offline', 'tunnel+unknown'], - opened: [known.toString()], + resolved: ['tunnel+box', 'tunnel+box', 'tunnel+box', 'tunnel+editor', 'tunnel+offline', 'tunnel+unknown', 'ssh-remote+host', 'ssh-remote+editor', 'wsl+Ubuntu'], + opened: [known.toString(), ssh.toString(), wsl.toString()], notifications: [ 'The session of your remote window could not be found on the remote agent host.', - 'The session of your remote window can\'t be opened in the Agents Window, because the Agents Window is connected to a different agent host on the tunnel\'s machine than your remote window.', + 'The session of your remote window can\'t be opened in the Agents Window, because the Agents Window is connected to a different agent host on the remote machine than your remote window.', 'The session of your remote window could not be opened in the Agents Window. Tunnel \'unknown\' was not found for the signed-in accounts.', + 'The session of your remote window can\'t be opened in the Agents Window, because the Agents Window is connected to a different agent host on the remote machine than your remote window.', ], - results: [undefined, undefined, undefined, 'unsupported', undefined, undefined, 'unsupported'], + results: [undefined, undefined, undefined, 'unsupported', undefined, undefined, undefined, 'unsupported', undefined, 'unsupported', 'unsupported'], }); }); @@ -403,4 +421,93 @@ suite('Agents Window workspace handoff telemetry', () => { }); } } + + test('a session link that arrives while a chat window has focus, such as from its canvas, opens in that window as a click there does', async () => { + const lifecycleService = disposables.add(new TestLifecycleService()); + lifecycleService.usePhases = true; + const configurationService = new TestConfigurationService({ [CHAT_WINDOWS_ENABLED_SETTING]: true }); + disposables.add(configurationService.onDidChangeConfigurationEmitter); + const sessionResource = URI.parse('agent-host-copilotcli:/session-1'); + const chatResource = sessionResource.with({ fragment: 'chat-2' }); + const mainChat = upcastPartial({ resource: sessionResource, isArchived: observableValue('archived', false) }); + const chat = upcastPartial({ resource: chatResource, isArchived: observableValue('archived', false) }); + const session = upcastPartial({ resource: sessionResource, mainChat: observableValue('mainChat', mainChat), chats: observableValue('chats', [mainChat, chat]), loading: observableValue('loading', false) }); + const activatedChat = URI.parse('agent-host-copilotcli:/session-0'); + const activeChat = observableValue('activeChat', activatedChat); + const chatWindow = upcastPartial({ windowId: 42, chat: activeChat }); + let activeWindow: IChatWindow | undefined; + let resolvesInWindow = true; + let pendingWindowOpen: DeferredPromise | undefined; + let resolution: IAgentHostSessionResolution | undefined; + const log: string[] = []; + const harness = { + lifecycleService, + configurationService, + logService: new NullLogService(), + sessionsPartService: { getProgressIndicator: () => ({ showWhile: (promise: Promise) => promise }) }, + resolveAndOpenSessionLink: Reflect.get(SelectAgentsFolderContribution.prototype, 'resolveAndOpenSessionLink'), + waitForSessionLinkAvailable: async () => session, + sessionsProvidersService: { getProvider: () => undefined }, + agentHostConnectionsService: { resolveSessionResource: () => resolution }, + chatWindowService: { + get activeWindow() { return activeWindow; }, + open: async (resource: URI, options?: IChatWindowOpenOptions) => { + log.push(`window:${resource}:tabOf=${options?.tabOf}:beside=${options?.beside}:in=${options?.window === chatWindow}:exact=${options?.exactChat}`); + return pendingWindowOpen ? pendingWindowOpen.p : resolvesInWindow ? chatWindow : undefined; + }, + }, + sessionsService: { openChat: async (_session: ISession, resource: URI) => { log.push(`main:${resource}`); } }, + }; + const openExistingSession = Reflect.get(SelectAgentsFolderContribution.prototype, 'openExistingSession') as (this: typeof harness, resource: URI, token: CancellationToken) => Promise<'unsupported' | undefined>; + const link = URI.parse(buildOpenSessionLinkUri(URI.parse('copilotcli:/session-1'), 'chat-2')); + + // Focus and the active chat of the window change while the window restores: the link opens where it arrived. + activeWindow = chatWindow; + const restoring = openExistingSession.call(harness, link, CancellationToken.None); + activeWindow = undefined; + activeChat.set(URI.parse('agent-host-copilotcli:/session-9'), undefined); + lifecycleService.phase = LifecyclePhase.Restored; + await restoring; + activeChat.set(activatedChat, undefined); + // No chat window has focus: a canvas of the main window, or a link from another app while this one has no focus. + await openExistingSession.call(harness, link, CancellationToken.None); + // A chat the chat window cannot resolve + activeWindow = chatWindow; + resolvesInWindow = false; + await openExistingSession.call(harness, link, CancellationToken.None); + resolvesInWindow = true; + // A chat id that names the session's advertised default chat opens its main chat, as a click on the link does + const backendSession = URI.parse('copilotcli:/session-1'); + resolution = upcastPartial({ + backendSession, + connection: upcastPartial({ + getSubscriptionUnmanaged: () => undefined, + listSessions: async () => [upcastPartial({ session: backendSession, chats: [{ chat: URI.parse('ahp-chat:/11111111-1111-4111-8111-111111111111'), kind: 'default' }] })], + }), + }); + await openExistingSession.call(harness, URI.parse(buildOpenSessionLinkUri(backendSession, '11111111-1111-4111-8111-111111111111')), CancellationToken.None); + resolution = undefined; + // A newer opening supersedes the link while the chat window opens it, which then fails + const superseded = disposables.add(new CancellationTokenSource()); + pendingWindowOpen = new DeferredPromise(); + const opening = openExistingSession.call(harness, link, superseded.token); + await timeout(0); + superseded.cancel(); + await pendingWindowOpen.complete(undefined); + await opening; + pendingWindowOpen = undefined; + // Chat windows are off + await configurationService.setUserConfiguration(CHAT_WINDOWS_ENABLED_SETTING, false); + await openExistingSession.call(harness, link, CancellationToken.None); + + assert.deepStrictEqual(log, [ + `window:${chatResource}:tabOf=${activatedChat}:beside=undefined:in=true:exact=true`, + `main:${chatResource}`, + `window:${chatResource}:tabOf=${activatedChat}:beside=undefined:in=true:exact=true`, + `main:${chatResource}`, + `window:${sessionResource}:tabOf=${activatedChat}:beside=undefined:in=true:exact=true`, + `window:${chatResource}:tabOf=${activatedChat}:beside=undefined:in=true:exact=true`, + `main:${chatResource}`, + ]); + }); }); diff --git a/src/vs/sessions/contrib/chatEditor/browser/chatEditor.ts b/src/vs/sessions/contrib/chatEditor/browser/chatEditor.ts index a8e0f5b381ea..ac35effbc15d 100644 --- a/src/vs/sessions/contrib/chatEditor/browser/chatEditor.ts +++ b/src/vs/sessions/contrib/chatEditor/browser/chatEditor.ts @@ -34,6 +34,7 @@ import { ISessionsListModelService } from '../../../../workbench/contrib/session import { getChatCompletedStateIcon, ISessionAgentMergeConfiguration } from '../../../../workbench/contrib/sessions/browser/sessionAgentMerge.js'; import { getSessionChatAncestors } from '../../../../workbench/contrib/sessions/browser/parts/sessionHeaderBar.js'; import { getSessionConversationStatusAriaLabel } from '../../../../workbench/contrib/sessions/browser/sessionConversationGroups.js'; +import { ChatWindowSessionDropTarget } from '../../chatWindow/browser/chatWindowSessionDropTarget.js'; import { ISessionPaneContent } from '../../../../workbench/services/sessions/common/sessionPane.js'; /** The view type of the chat of a session, shown as an editor: the chat part of a chat window shows it. */ @@ -251,8 +252,8 @@ export class ChatEditorView extends Disposable implements IViewEditorView { /** Whether the view shows its title, the session header: not while its group shows its tabs, which show its actions. */ private readonly _providedTitleVisible = observableValue(this, true); - /** The title of the session header drags the chat. */ - get dragHandle(): HTMLElement { return this.sessionView.headerTitleElement; } + /** The session header drags the chat. */ + get dragHandle(): HTMLElement { return this.sessionView.headerElement; } /** The actions of the session header, which the tab bar of its group shows while the header hides. */ get titleMenu(): IEditorPaneTitleMenu { return this.sessionView.titleMenu; } @@ -286,6 +287,7 @@ export class ChatEditorView extends Disposable implements IViewEditorView { this.element = $('.session-chat-view-editor.sessions-window-host'); // The chat takes what is dropped on it, such as files to attach; editors dropped on the edges of its part split it. this._register(registerContentDropTarget(this.element)); + this._register(instantiationService.createInstance(ChatWindowSessionDropTarget, this.element, () => host?.content.get()?.chat.get().resource)); // The active editor, for what the chat shows, such as the checked entries of its Session Activity Bar, is the one of // its window's main part, as the main window's chat reads the one of its editor area. const scopedContextKeyService = this._scopedServices.add(contextKeyService.createScoped(this.element)); diff --git a/src/vs/sessions/contrib/chatEditor/browser/chatEditorContent.ts b/src/vs/sessions/contrib/chatEditor/browser/chatEditorContent.ts index 4f46a38a83bc..8f375c6c1c53 100644 --- a/src/vs/sessions/contrib/chatEditor/browser/chatEditorContent.ts +++ b/src/vs/sessions/contrib/chatEditor/browser/chatEditorContent.ts @@ -77,8 +77,8 @@ export class ChatEditorContent extends Disposable { readonly primaryChatView: IObservable; /** The top of {@link primaryChatView} while it shows only its input: below the bar of its group, as the session header hides then. */ readonly inputOnlyChatViewTop: IObservable; - /** The title of the session header. */ - get headerTitleElement(): HTMLElement { return this._header.titleElement; } + /** The session header. */ + get headerElement(): HTMLElement { return this._header.element; } /** The menu of the actions of the session header, with the context and the arguments they show and run with there. */ readonly titleMenu: IEditorPaneTitleMenu; @@ -122,7 +122,7 @@ export class ChatEditorContent extends Disposable { this._header = this._register(scopedInstantiationService.createInstance(SessionHeader)); this._showHeader = _hostOptions?.showHeader ?? true; this._header.setVisible(this._showHeader); - // Its title drags the editor that shows the chat (see `ChatEditorView.dragHandle`), which carries the session. + // It drags the editor that shows the chat (see `ChatEditorView.dragHandle`), which carries the session. this._header.setDragsEditor(true); this._headerContainer.appendChild(this._header.element); this.titleMenu = { menuId: Menus.SessionBarToolbar, contextKeyService: scopedContextKeyService, options: this._header.menuActionOptions }; diff --git a/src/vs/sessions/contrib/chatEditor/test/browser/chatEditor.test.ts b/src/vs/sessions/contrib/chatEditor/test/browser/chatEditor.test.ts index fe3b8a461f75..b0052bdc41ca 100644 --- a/src/vs/sessions/contrib/chatEditor/test/browser/chatEditor.test.ts +++ b/src/vs/sessions/contrib/chatEditor/test/browser/chatEditor.test.ts @@ -27,7 +27,7 @@ import { ChatModelStore, IStartSessionProps } from '../../../../../workbench/con import { IChatAgentService } from '../../../../../workbench/contrib/chat/common/participants/chatAgents.js'; import { CHAT_MODEL_HOLD_TIMEOUT } from '../../../chatWindow/browser/chatWindowOpening.js'; import { IChatModelReference, IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; -import { IChatWindow } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { IChatWindow, IChatWindowOpenOptions, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { IContentPart, IEditorGroup } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; import { testPaneContentOf } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; import { createSessionViewTestServices, createTestActiveSession } from '../../../../test/browser/sessionViewTestUtils.js'; @@ -41,7 +41,9 @@ import { MultipleSessionsVisibleContext, SessionInChatEditorContext } from '../. import { ThemeIcon } from '../../../../../base/common/themables.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { URI } from '../../../../../base/common/uri.js'; +import { fillSessionChatDragData } from '../../../../../workbench/contrib/sessions/browser/dnd.js'; import { Verbosity } from '../../../../../workbench/common/editor.js'; +import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { IChat, ISession, ISessionPreparationProgress, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; import { ChatEditorInput, getChatEditorInputDetails, ChatEditorView, IInputOnlySessionView, ISessionChatViewHost, SESSION_CHAT_VIEW_HOST_OPTIONS, SESSION_CHAT_VIEW_MINIMUM_HEIGHT, SESSION_CHAT_VIEW_TYPE, SessionChatViewInputOnly } from '../../browser/chatEditor.js'; @@ -241,6 +243,54 @@ suite('Session chat view editor', () => { assert.deepStrictEqual({ chatViews: chatViews.length, shownTabStrips: shownTabStrips.length, chatsToSwitchTo: view.element.querySelectorAll('.chat-composite-bar-tab').length - 1 }, { chatViews: 1, shownTabStrips: 0, chatsToSwitchTo: 0 }); }); + test('a chat of another window dragged over a chat editor shows where it opens, and opens beside the chat of the editor on drop', async () => { + const { instantiationService } = createServices(); + const opened: { chat: string; tabOf: string | undefined }[] = []; + const other = createTestActiveSession('other'); + instantiationService.stub(ISessionsManagementService, new class extends mock() { + override readonly onDidChangeSessions = Event.None; + override readonly onDidChangeSessionTypes = Event.None; + override getSessionForChatResource() { + const chat = new class extends mock() { + override readonly resource = other.mainChat.get().resource; + override readonly isArchived = constObservable(false); + }(); + const session = new class extends mock() { + override readonly loading = constObservable(false); + override readonly chats = constObservable([chat]); + override readonly mainChat = constObservable(chat); + }(); + return { session, chat }; + } + }()); + instantiationService.stub(IChatWindowService, new class extends mock() { + override getWindow() { return {} as ReturnType; } + override async open(chat: URI, options?: IChatWindowOpenOptions) { + opened.push({ chat: chat.toString(), tabOf: options?.tabOf?.toString() }); + return undefined; + } + }()); + const host: ISessionChatViewHost = { + content: constObservable(testPaneContentOf(createTestActiveSession('session'), () => { })), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + }; + const view = disposables.add(instantiationService.createInstance(ChatEditorView, host)); + mainWindow.document.body.appendChild(view.element); + disposables.add(toDisposable(() => view.element.remove())); + const dataTransfer = new DataTransfer(); + fillSessionChatDragData(new DragEvent('dragstart', { dataTransfer }), 'other', URI.parse('test-chat://other')); + + view.element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + const overlay = view.element.querySelector('.chat-window-session-drop-overlay'); + overlay?.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual({ overlay: !!overlay, opened }, { overlay: true, opened: [{ chat: 'test-chat://other', tabOf: 'test-chat://session' }] }); + }); + test('before its editor moves, the chat saves what it shows, such as where it is scrolled to, for the view where it moves to', () => { const { instantiationService, chatViews } = createServices(); const host: ISessionChatViewHost = { @@ -337,7 +387,7 @@ suite('Session chat view editor', () => { view.layout(400, 800, 0, 0); const read = () => { const header = view.element.querySelector('.session-header-bar'); - return { inCard: !!header && view.sessionView.element.contains(header), shown: !!header && header.style.display !== 'none', dragsSession: !!header?.draggable, titleDragsEditor: view.dragHandle === view.sessionView.headerTitleElement }; + return { inCard: !!header && view.sessionView.element.contains(header), shown: !!header && header.style.display !== 'none', dragsSession: !!header?.draggable, headerDragsEditor: view.dragHandle === view.sessionView.headerElement }; }; const modes: Record> = {}; @@ -348,7 +398,7 @@ suite('Session chat view editor', () => { window.toggleConversation(); const stackedConversation = read(); - const shown = { inCard: true, shown: true, dragsSession: false, titleDragsEditor: true }; + const shown = { inCard: true, shown: true, dragsSession: false, headerDragsEditor: true }; assert.deepStrictEqual({ modes, stackedConversation }, { modes: { [ChatWindowLayoutMode.SideBySide]: shown, diff --git a/src/vs/sessions/contrib/chatWindow/browser/chatWindowSessionDropTarget.ts b/src/vs/sessions/contrib/chatWindow/browser/chatWindowSessionDropTarget.ts new file mode 100644 index 000000000000..2e1474bba6c1 --- /dev/null +++ b/src/vs/sessions/contrib/chatWindow/browser/chatWindowSessionDropTarget.ts @@ -0,0 +1,182 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/chatWindowSessionDropTarget.css'; +import { $, addDisposableListener, DragAndDropObserver, EventHelper, EventType, getWindow, getWindowId, isHTMLElement } from '../../../../base/browser/dom.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { DisposableStore, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { LocalSelectionTransfer } from '../../../../platform/dnd/browser/dnd.js'; +import { activeContrastBorder } from '../../../../platform/theme/common/colorRegistry.js'; +import { IThemeService, Themable } from '../../../../platform/theme/common/themeService.js'; +import { InputDropTargetHints, isInputDropTarget } from '../../../../workbench/browser/dnd.js'; +import { EDITOR_DRAG_AND_DROP_BACKGROUND } from '../../../../workbench/common/theme.js'; +import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { DraggedSessionIdentifier, getSessionChatDragData, isSessionChatDrag, SessionsDataTransfers } from '../../../../workbench/contrib/sessions/browser/dnd.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { isChatWindowChatGone } from './chatWindowOpening.js'; + +/** + * Makes the chat of a chat window take the chats and sessions dragged onto it, such as a session of the sessions list or + * the tab of a chat of the main window: it opens each in the chat window, as a tab beside the chat. While the drag is + * over it, an overlay shows where it opens, and keeps the drag from scrolling what is under it. A chat that is archived or + * gone is not taken. What is dropped on an input, such as to attach it as context, stays the input's. + */ +export class ChatWindowSessionDropTarget extends Themable { + + private readonly _overlayStore = this._register(new MutableDisposable()); + + private readonly _sessionTransfer = LocalSelectionTransfer.getInstance(); + + /** + * @param _element The chat's element, which positions the overlay. + * @param _getChat The chat the element shows, which the dropped chats open beside. + */ + constructor( + private readonly _element: HTMLElement, + private readonly _getChat: () => URI | undefined, + @IThemeService themeService: IThemeService, + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @IChatWindowService private readonly _chatWindowService: IChatWindowService, + ) { + super(themeService); + + this._register(addDisposableListener(this._element, EventType.DRAG_ENTER, e => this._onDragEnter(e))); + } + + private _isSessionDrag(e: DragEvent): boolean { + return this._sessionTransfer.hasData(DraggedSessionIdentifier.prototype) || !!e.dataTransfer?.types.includes(SessionsDataTransfers.SESSION); + } + + /** Whether the drag, as far as it is known before it drops, carries a chat the window takes. */ + private _accepts(e: DragEvent): boolean { + if (isSessionChatDrag(e)) { + return true; + } + if (!this._isSessionDrag(e)) { + return false; + } + const dragged = this._sessionTransfer.getData(DraggedSessionIdentifier.prototype); + // Not known before it drops, when the drag is of another window's + return !dragged || dragged.some(item => !!item.resource && !!this._resolveSessionChat(item.resource)); + } + + private _resolveSessionChat(resource: URI): URI | undefined { + const session = this._sessionsManagementService.getSession(resource); + if (!session) { + return undefined; + } + const chat = session.mainChat.get().resource; + return isChatWindowChatGone(session, chat, undefined) ? undefined : chat; + } + + private _onDragEnter(e: DragEvent): void { + // An input under the drag that takes it, such as a chat input that attaches the dragged chat, takes it here. + if (isHTMLElement(e.target) && isInputDropTarget(e.target, e)) { + this._hideOverlay(); + return; + } + if (!this._accepts(e)) { + return; + } + if (!this._overlayStore.value) { + this._showOverlay(e); + } + } + + private _showOverlay(e: DragEvent): void { + const store = new DisposableStore(); + this._overlayStore.value = store; + const overlay = $('.chat-window-session-drop-overlay'); + const bounds = this._element.getBoundingClientRect(); + overlay.style.left = `${bounds.left}px`; + overlay.style.top = `${bounds.top}px`; + overlay.style.width = `${bounds.width}px`; + overlay.style.height = `${bounds.height}px`; + const indicator = $('.chat-window-session-drop-overlay-indicator'); + indicator.style.backgroundColor = this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND) || ''; + const border = this.getColor(activeContrastBorder); + if (border) { + indicator.style.outline = `2px dashed ${border}`; + indicator.style.outlineOffset = '-2px'; + } + overlay.appendChild(indicator); + this._element.appendChild(overlay); + store.add(toDisposable(() => overlay.remove())); + const inputHints = store.add(new InputDropTargetHints(this._element, overlay)); + inputHints.update(e); + store.add(addDisposableListener(getWindow(this._element), EventType.DRAG_END, () => this._hideOverlay())); + store.add(new DragAndDropObserver(overlay, { + onDragOver: ev => { + // An input that takes the drag takes it once the drag moves over it: the overlay, which covers the input + // until then, goes away. + if (isHTMLElement(ev.target) && isInputDropTarget(ev.target, ev, this._element)) { + this._hideOverlay(); + return; + } + inputHints.update(ev); + if (ev.dataTransfer) { + ev.dataTransfer.dropEffect = 'move'; + } + }, + onDragLeave: () => this._hideOverlay(), + onDragEnd: () => this._hideOverlay(), + onDrop: ev => { + EventHelper.stop(ev, true); + this._hideOverlay(); + this._handleDrop(ev); + }, + })); + } + + private _hideOverlay(): void { + this._overlayStore.clear(); + } + + /** The session of a drag from another window, whose payload is only in the data transfer. */ + private _readSessionPayload(e: DragEvent): DraggedSessionIdentifier[] { + try { + const payload = JSON.parse(e.dataTransfer?.getData(SessionsDataTransfers.SESSION) || '{}'); + if (typeof payload.sessionId === 'string' && typeof payload.resource === 'string') { + return [new DraggedSessionIdentifier(payload.sessionId, URI.parse(payload.resource))]; + } + } catch { + // Not a session payload + } + return []; + } + + private _handleDrop(e: DragEvent): void { + const chats: URI[] = []; + const chat = getSessionChatDragData(e); + if (chat) { + const resource = URI.parse(chat.resource); + const found = this._sessionsManagementService.getSessionForChatResource(resource); + if (found && !isChatWindowChatGone(found.session, resource, undefined)) { + chats.push(resource); + } + } else { + const dragged = this._sessionTransfer.getData(DraggedSessionIdentifier.prototype) ?? this._readSessionPayload(e); + this._sessionTransfer.clearData(DraggedSessionIdentifier.prototype); + for (const item of dragged) { + const resolved = item.resource && this._resolveSessionChat(item.resource); + if (resolved) { + chats.push(resolved); + } + } + } + const window = this._chatWindowService.getWindow(getWindowId(getWindow(this._element))); + if (!window || !chats.length) { + return; + } + void (async () => { + let tabOf = this._getChat(); + for (const resource of chats) { + await this._chatWindowService.open(resource, { window, exactChat: true, tabOf }); + tabOf = resource; + } + })().catch(onUnexpectedError); + } +} diff --git a/src/vs/sessions/contrib/chatWindow/browser/media/chatWindow.css b/src/vs/sessions/contrib/chatWindow/browser/media/chatWindow.css index 7b4eff91b3bb..f429349eb95d 100644 --- a/src/vs/sessions/contrib/chatWindow/browser/media/chatWindow.css +++ b/src/vs/sessions/contrib/chatWindow/browser/media/chatWindow.css @@ -58,7 +58,7 @@ --part-grid-card-radius: 0; } -/* The strip's column shows the window behind the strip, as the main window's column does: only the strip is framed. */ +/* The strip's column shows the window behind the strip, as the main window's column does. */ .monaco-workbench .agents-chat-window .part-grid-cell[data-part-grid-cell="strip"] > .part-grid-card { --part-grid-card-background: transparent; } @@ -90,7 +90,7 @@ } /* - * The strip fills its column from top to bottom, as the main window's does (`sessionActivityBar.css`), to the right of + * The strip follows the card frames, as the main window's does (`sessionActivityBar.css`), to the right of * the gap the column keeps to the cards (`getChatWindowStripWidth`). By rules of its own: those of the main window's * column follow the state of the main window, whose classes the workbench element of a chat window mirrors. */ @@ -105,8 +105,8 @@ right: 0; } -/* The cards beside it show their frames inset within them by the stroke, as the main window's chat does: moved toward - * them by as much, as beside that chat, so that the gap between them shows as wide as the gap between cards. */ -.monaco-workbench:not(.modern-ui-compact) .agents-chat-window .chat-window-strip > .session-activity-bar.docked { - right: var(--vscode-strokeThickness); +/* Follow the inset card frames independently of the main window's visibility state. */ +.monaco-workbench.modern-ui-tabs:not(.modern-ui-compact) .agents-chat-window .chat-window-strip > .session-activity-bar.docked { + top: var(--vscode-strokeThickness); + bottom: var(--vscode-strokeThickness); } diff --git a/src/vs/sessions/contrib/chatWindow/browser/media/chatWindowSessionDropTarget.css b/src/vs/sessions/contrib/chatWindow/browser/media/chatWindowSessionDropTarget.css new file mode 100644 index 000000000000..0a36826b8ccd --- /dev/null +++ b/src/vs/sessions/contrib/chatWindow/browser/media/chatWindowSessionDropTarget.css @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.chat-window-session-drop-overlay { + position: fixed; + z-index: 10000; +} + +.chat-window-session-drop-overlay > .chat-window-session-drop-overlay-indicator { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; /* important: do not steal events from the overlay */ +} diff --git a/src/vs/sessions/contrib/chatWindow/browser/openChatInWindow.ts b/src/vs/sessions/contrib/chatWindow/browser/openChatInWindow.ts index 776d73fa8a2e..49285076dba4 100644 --- a/src/vs/sessions/contrib/chatWindow/browser/openChatInWindow.ts +++ b/src/vs/sessions/contrib/chatWindow/browser/openChatInWindow.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ import { Codicon } from '../../../../base/common/codicons.js'; -import { isEqual } from '../../../../base/common/resources.js'; import { URI } from '../../../../base/common/uri.js'; import { localize2 } from '../../../../nls.js'; import { Action2, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; @@ -16,6 +15,7 @@ import { IChatWindowOpenOptions, IChatWindowService } from '../../../../workbenc import { resolveChatWindow } from '../../../../workbench/contrib/chatWindow/browser/chatWindowLayoutActions.js'; import { IEditorGroupsService } from '../../../../workbench/services/editor/common/editorGroupsService.js'; import { Menus, SessionHeaderMenus } from '../../../../workbench/contrib/sessions/browser/menus.js'; +import { editorWorkingSetOwnerIncludes, ISessionEditorWorkingSetService } from '../../layout/common/sessionEditorWorkingSet.js'; import { IAgentWorkbenchLayoutService } from '../../../browser/workbench.js'; import { SessionsCategories } from '../../../../workbench/contrib/sessions/common/categories.js'; import { SessionIsCreatedContext, SessionItemIsMultiSelectionContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; @@ -53,8 +53,8 @@ for (const [menu, command, precondition, when] of [ /** * Moves the chat `session` shows in the main window, or its main chat, to a chat window of its own: the main window then - * shows the session it showed before, or a new session. The chat takes the editors it has open in the main window along, - * to the main part beside it, but only while the main window shows that chat. + * shows the session it showed before, or a new session. The chat takes the editors its session has open in the main window + * along, to the main part beside it, whichever of the session's chats the main window shows. */ export async function openChatInWindow(accessor: ServicesAccessor, session: ISession, chat?: URI, options?: IChatWindowOpenOptions): Promise { const chatWindowService = accessor.get(IChatWindowService); @@ -65,20 +65,31 @@ export async function openChatInWindow(accessor: ServicesAccessor, session: ISes // The session's own slot, not a detached pane of one of its chats. const shown = sessionsService.slotPanes.get().find(pane => pane.session.get()?.sessionId === session.sessionId); const chatResource = chat ?? shown?.chat.get()?.resource; - // The main window's editors are the chat's while the main window is laid out for it and shows it as its active chat. - const mainWindowHost = getMainWindowHost(accessor.get(ISessionHostService)); - const ownsEditors = mainWindowHost.session.get()?.sessionId === session.sessionId - && (!chatResource || isEqual(mainWindowHost.chat.get()?.resource, chatResource)); + const workingSetService = accessor.get(ISessionEditorWorkingSetService); + const workingSetOwner = workingSetService.restoreState.get().owner; + const ownsEditors = getMainWindowHost(accessor.get(ISessionHostService)).session.get()?.sessionId === session.sessionId + && (!workingSetOwner || editorWorkingSetOwnerIncludes(workingSetOwner, session.resource, chatResource ?? session.resource)); // The editors moving out empty the main window's editor part: that is not the user closing them, so the main window // keeps its side pane as it is, for the session it shows next, as when it switches sessions. const suppression = ownsEditors ? layoutService.suppressEditorPartAutoVisibility() : undefined; + // A session another pane shows has its editors saved, not open in the main window. + const stashed = ownsEditors ? undefined : workingSetService.takeEditorsFor(session, chatResource ?? session.resource); try { - await chatWindowService.open(chatResource ?? session.resource, { + const window = await chatWindowService.open(chatResource ?? session.resource, { ...options, - editors: { ...options?.editors, moveFrom: ownsEditors ? editorGroupsService.mainPart.groups : [] }, + exactChat: !!chat, + editors: { + ...options?.editors, + moveFrom: ownsEditors ? editorGroupsService.mainPart.groups : [], + ...(stashed && { editors: stashed.editors, activeEditor: stashed.activeEditor }), + }, }); + if (window && stashed?.editors.every(editor => window.mainPart.groups.some(group => group.contains(editor)))) { + stashed.accept(); + } } finally { suppression?.dispose(); + stashed?.dispose(); } } diff --git a/src/vs/sessions/contrib/chatWindow/browser/sessionsChatWindowProvider.ts b/src/vs/sessions/contrib/chatWindow/browser/sessionsChatWindowProvider.ts index 700fdead402c..6181242b8333 100644 --- a/src/vs/sessions/contrib/chatWindow/browser/sessionsChatWindowProvider.ts +++ b/src/vs/sessions/contrib/chatWindow/browser/sessionsChatWindowProvider.ts @@ -7,10 +7,9 @@ import './media/chatWindow.css'; import { raceTimeout, timeout } from '../../../../base/common/async.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { Disposable, DisposableMap, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; -import { autorun, constObservable, derived, IObservable, IReader, ISettableObservable, observableFromEvent, observableSignalFromEvent, observableValue, transaction, waitForState } from '../../../../base/common/observable.js'; +import { autorun, constObservable, derived, IObservable, IReader, ISettableObservable, observableFromEvent, observableSignal, observableValue, transaction, waitForState } from '../../../../base/common/observable.js'; import { onUnexpectedError } from '../../../../base/common/errors.js'; import { extUri, isEqual } from '../../../../base/common/resources.js'; -import { DeepPartial } from '../../../../base/common/types.js'; import { URI } from '../../../../base/common/uri.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; @@ -18,9 +17,9 @@ import { IInstantiationService } from '../../../../platform/instantiation/common import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; import { IEditorGroupView, IEditorGroupViewOptions } from '../../../../workbench/browser/parts/editor/editor.js'; -import { GroupModelChangeKind, IEditorPartOptions } from '../../../../workbench/common/editor.js'; +import { GroupModelChangeKind } from '../../../../workbench/common/editor.js'; import { IChatService } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; -import { IChatWindow, IChatWindowChat, IChatWindowChrome, IChatWindowChromeElement, IChatWindowContent, IChatWindowEditors, IChatWindowLook, IChatWindowNewChatOptions, IChatWindowProvider, IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { getChatWindowMainPartOptions, IChatWindow, IChatWindowChat, IChatWindowChrome, IChatWindowChromeElement, IChatWindowContent, IChatWindowEditors, IChatWindowLook, IChatWindowNewChatOptions, IChatWindowProvider, IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { IChatEntitlementService } from '../../../../workbench/services/chat/common/chatEntitlementService.js'; import { IEditorGroup, IEditorGroupsService } from '../../../../workbench/services/editor/common/editorGroupsService.js'; import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; @@ -31,6 +30,7 @@ import { AgentsWindowMenus } from '../../../browser/agentsWindowMenus.js'; import { EmptyEditorGroupAddTab } from '../../../../workbench/browser/parts/sessions/emptyEditorGroupAddTab.js'; import { observeSessionActivityBarSize, registerSessionActivityBarExternalHost } from '../../../../workbench/browser/parts/sessions/sessionActivityBarHost.js'; import { MenuActivityBar, MenuActivityBarSize } from '../../../../workbench/browser/parts/activitybar/menuActivityBar.js'; +import { AgentsPartCard } from '../../../../workbench/browser/parts/sessions/agentsPartCard.js'; import { IStorageService } from '../../../../platform/storage/common/storage.js'; import { CustomViewVisibleContext } from '../../../common/agentsWindowContextKeys.js'; import { AGENTS_FLOATING_PANEL_GAP } from '../../../../workbench/contrib/sessions/common/layoutConstants.js'; @@ -70,16 +70,7 @@ const RESTORE_SESSION_TIMEOUT = 30_000; * its left, and a {@link MenuActivityBar} at the size chosen for the Session Activity Bar, which fills the rest. */ export function getChatWindowStripWidth(compact: boolean, size: MenuActivityBarSize): number { - return (compact ? 0 : AGENTS_FLOATING_PANEL_GAP) + MenuActivityBar.getWidth(compact, size); -} - -/** - * The options of the main part of a chat window: its tabs follow `workbench.editor.showTabs`, live, as the main window's - * editor area does; `none` shows as `single`, so that the part keeps its title with its actions. Double-clicking a tab - * does not maximize or expand a group: the window arranges its parts. - */ -export function getChatWindowMainPartOptions(showTabs: string | undefined): DeepPartial { - return { doubleClickTabToToggleEditorGroupSizes: 'off', ...(showTabs === 'none' ? { showTabs: 'single' } : undefined) }; + return (compact ? 0 : AGENTS_FLOATING_PANEL_GAP - AgentsPartCard.BORDER_WIDTH) + MenuActivityBar.getWidth(compact, size); } /** The options of the groups of the main part of a chat window: those of the main window's editor area of the Agents window. */ @@ -168,11 +159,14 @@ class SessionsChatWindowChat extends Disposable implements IChatWindowChat, ISes readonly isUnsentComposer: IObservable = derived(this, reader => !!this._composer.read(reader)); /** The session the chat was last known in, so that its end is known while the session no longer lists it. */ private _knownSession: ISession | undefined; + /** Whether its known session was removed, such as deleted: not hidden as its provider goes away, which removes nothing. */ + private _knownSessionRemoved = false; private readonly _onWillDispose = this._register(new Emitter()); readonly onWillDispose = this._onWillDispose.event; /** Keeps the chat out of the main window's grid while the window shows it. */ private readonly _gridHold = this._register(new MutableDisposable()); + private _heldSession: ISession | undefined; /** The views of its editor, the last of which shows it; see {@link view}. */ private readonly _attachedViews: ChatEditorContent[] = []; @@ -245,7 +239,19 @@ class SessionsChatWindowChat extends Disposable implements IChatWindowChat, ISes this._heldChat.hold(chatResource, this._boundCheck()); } - const sessionsChanged = observableSignalFromEvent(this, _sessionsManagementService.onDidChangeSessions); + // Once it knows its session, only sessions added, removed or replaced can change where its chat is: what changes in its + // session it reads from that session. So the many changes of other sessions, such as while they stream, pass it by. + // A replacement, such as a pending session committed under the same ID, comes as a change of another object. + const sessionsChanged = observableSignal(this); + this._register(_sessionsManagementService.onDidChangeSessions(e => { + const known = this._knownSession; + if (known && e.removed.some(removed => isEqual(removed.resource, known.resource))) { + this._knownSessionRemoved = true; + } + if (!known || e.added.length || e.removed.length || e.changed.some(changed => changed !== known && changed.sessionId === known.sessionId)) { + sessionsChanged.trigger(undefined); + } + })); this._register(autorun(reader => { sessionsChanged.read(reader); this._update(reader); @@ -307,18 +313,24 @@ class SessionsChatWindowChat extends Disposable implements IChatWindowChat, ISes owner.session.loading.read(reader); } this._knownSession = owner.session; + this._knownSessionRemoved = false; if (isChatWindowChatGone(owner.session, chatResource, reader)) { this._end(); return; } const shown = this._shown.get(); if (shown?.session !== owner.session || shown.chat !== owner.chat) { - const sessionChanged = shown?.session.sessionId !== owner.session.sessionId; this._shown.set({ session: owner.session, chat: owner.chat }, undefined); - if (sessionChanged) { - this._gridHold.value = this._sessionsService.hideChatFromGrid(owner.session, owner.chat.resource); - } } + if (this.window.read(reader) && this._heldSession?.sessionId !== owner.session.sessionId) { + this._heldSession = owner.session; + this._gridHold.value = this._sessionsService.hideChatFromGrid(owner.session, owner.chat.resource); + } + return; + } + if (this._knownSessionRemoved && !(this._knownSession && this._sessionsManagementService.getSession(this._knownSession.resource))) { + // Its session is gone, such as deleted: its chats with it, also while the session's last state still lists them + this._end(); return; } // Gone once the session it was in has loaded and no longer lists it, such as once it was deleted diff --git a/src/vs/sessions/contrib/chatWindow/test/browser/chatEditor.test.ts b/src/vs/sessions/contrib/chatWindow/test/browser/chatEditor.test.ts new file mode 100644 index 000000000000..de5985fa0dcc --- /dev/null +++ b/src/vs/sessions/contrib/chatWindow/test/browser/chatEditor.test.ts @@ -0,0 +1,769 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { autorun, constObservable, IObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { IViewEditorRegistry, ViewEditorExtensions } from '../../../../../workbench/browser/parts/editor/viewEditorRegistry.js'; +import { ChatWindowLayoutMode } from '../../../../../workbench/contrib/chatWindow/common/chatWindowLayout.js'; +import { $ } from '../../../../../base/browser/dom.js'; +import { setARIAContainer } from '../../../../../base/browser/ui/aria/aria.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { INewSessionDraftHost } from '../../../../../workbench/contrib/sessions/browser/parts/chatView.js'; +import { ISessionPaneContent } from '../../../../../workbench/services/sessions/common/sessionPane.js'; +import { Event } from '../../../../../base/common/event.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/virtualScheduling/index.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { ChatAgentLocation } from '../../../../../workbench/contrib/chat/common/constants.js'; +import { ChatModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { ChatModelStore, IStartSessionProps } from '../../../../../workbench/contrib/chat/common/model/chatModelStore.js'; +import { IChatAgentService } from '../../../../../workbench/contrib/chat/common/participants/chatAgents.js'; +import { CHAT_MODEL_HOLD_TIMEOUT } from '../../../../../workbench/contrib/sessions/browser/chatEditor/sessionChatOpening.js'; +import { IChatModelReference, IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; +import { IChatWindow, IChatWindowOpenOptions, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { IContentPart, IEditorGroup } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; +import { testPaneContentOf } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { createSessionViewTestServices, createTestActiveSession } from '../../../../test/browser/sessionViewTestUtils.js'; +import { isIMenuItem, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; +import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { CLOSE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; +// The session header's actions, which the tab bar shows for a chat while its header hides +import '../../../sessions/browser/sessionsActions.js'; +import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; +import { MultipleSessionsVisibleContext, SessionInChatEditorContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { fillSessionChatDragData } from '../../../../../workbench/contrib/sessions/browser/dnd.js'; +import { Verbosity } from '../../../../../workbench/common/editor.js'; +import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { IChat, ISession, ISessionPreparationProgress, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; +import { ISessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; +import { ChatEditorInput, getChatEditorInputDetails, ChatEditorView, IInputOnlySessionView, ISessionChatViewHost, SESSION_CHAT_VIEW_HOST_OPTIONS, SESSION_CHAT_VIEW_MINIMUM_HEIGHT, SESSION_CHAT_VIEW_TYPE, SessionChatViewInputOnly, registerSessionChatViewEditor } from '../../../../../workbench/contrib/sessions/browser/chatEditor/chatEditor.js'; +import { IChatEditorComposer } from '../../../../../workbench/contrib/sessions/browser/chatEditor/chatEditorContent.js'; +import { ChatWindowSessionDropTarget } from '../../browser/chatWindowSessionDropTarget.js'; + +suite('Session chat view editor', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** The services of a chat editor's view, with a chat service that has no chat model loaded. */ + function createServices() { + const services = createSessionViewTestServices(disposables); + services.instantiationService.stub(IChatService, new class extends mock() { + override acquireExistingSession() { return undefined; } + }()); + return services; + } + + const INPUT_HEIGHT = 100; + /** The top of the chat view while it shows only its input: below the bar of its group, the session header hidden then. */ + const CHAT_VIEW_TOP = 30; + + /** A chat view that shows only its input when asked to, unless it cannot, and shows the conversation when it needs it. */ + class TestChatView { + readonly inputOnly = observableValue('inputOnly', false); + readonly canShowInputOnly = observableValue('canShowInputOnly', true); + readonly inputOnlyHeight = observableValue('inputOnlyHeight', INPUT_HEIGHT); + enableInputOnly(options: { readonly inputOnly?: boolean }): void { this.setInputOnly(!!options.inputOnly); } + disableInputOnly(): void { this.inputOnly.set(false, undefined); } + setInputOnly(inputOnly: boolean): void { + if (!inputOnly || this.canShowInputOnly.get()) { + this.inputOnly.set(inputOnly, undefined); + } + } + /** Its input cannot show what it needs, such as a confirmation: it shows the conversation. */ + needConversation(): void { + this.canShowInputOnly.set(false, undefined); + this.inputOnly.set(false, undefined); + } + } + + function createInputOnly(options: { readonly inputOnly: boolean; readonly mode: ChatWindowLayoutMode }) { + const chatView = new TestChatView(); + const sessionView: IInputOnlySessionView = { + primaryChatView: constObservable(chatView) as IInputOnlySessionView['primaryChatView'], + inputOnlyChatViewTop: constObservable(CHAT_VIEW_TOP), + }; + const layoutMode = observableValue('layoutMode', options.mode); + const inputOnly = observableValue('inputOnly', options.inputOnly); + const resizing = observableValue('resizing', false); + const window = { + layoutMode: layoutMode as IObservable, + inputOnly: inputOnly as IObservable, + resizing: resizing as IObservable, + toggleConversation: () => { + if (layoutMode.get() === ChatWindowLayoutMode.Stacked) { + inputOnly.set(!inputOnly.get(), undefined); + } + }, + }; + const controller = disposables.add(new SessionChatViewInputOnly(sessionView, constObservable(window))); + const read = () => ({ shown: chatView.inputOnly.get(), chosen: inputOnly.get(), maximumHeight: controller.maximumHeight.get(), minimumHeight: controller.minimumHeight.get() }); + return { chatView, layoutMode, window, read, resizing, controller }; + } + + test('registers the chat of a session as a view editor, which shows its session as the chat windows did: its header, its Session Activity Bar and its pills', () => { + disposables.add(registerSessionChatViewEditor()); + const descriptor = Registry.as(ViewEditorExtensions.ViewEditors).get(SESSION_CHAT_VIEW_TYPE); + assert.deepStrictEqual({ registered: !!descriptor, name: descriptor?.name, options: SESSION_CHAT_VIEW_HOST_OPTIONS }, { + registered: true, + name: 'Chat', + options: { showHeader: true, showActivityBar: true, input: { showPills: true } }, + }); + }); + + test('in Stacked, the chat shows only its input as its window chose, and is as tall as its input then, but a pixel for its sash to drag; elsewhere it shows its conversation, unbounded', () => { + const { layoutMode, read, window } = createInputOnly({ inputOnly: true, mode: ChatWindowLayoutMode.Stacked }); + const stacked = read(); + window.toggleConversation(); + const conversation = read(); + window.toggleConversation(); + layoutMode.set(ChatWindowLayoutMode.SideBySide, undefined); + const sideBySide = read(); + + const collapsed = CHAT_VIEW_TOP + INPUT_HEIGHT; + assert.deepStrictEqual({ stacked, conversation, sideBySide }, { + stacked: { shown: true, chosen: true, maximumHeight: collapsed + 1, minimumHeight: collapsed }, + conversation: { shown: false, chosen: false, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: SESSION_CHAT_VIEW_MINIMUM_HEIGHT }, + sideBySide: { shown: false, chosen: true, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: SESSION_CHAT_VIEW_MINIMUM_HEIGHT }, + }); + }); + + test('the chat follows what the chat view shows, also when it shows the conversation on its own, without changing what the user chose', () => { + const { chatView, read } = createInputOnly({ inputOnly: true, mode: ChatWindowLayoutMode.Stacked }); + const inputOnly = read(); + chatView.needConversation(); + + assert.deepStrictEqual({ inputOnly, conversation: read() }, { + inputOnly: { shown: true, chosen: true, maximumHeight: CHAT_VIEW_TOP + INPUT_HEIGHT + 1, minimumHeight: CHAT_VIEW_TOP + INPUT_HEIGHT }, + conversation: { shown: false, chosen: true, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: SESSION_CHAT_VIEW_MINIMUM_HEIGHT }, + }); + }); + + test('dragged by the sash beside it, the chat showing only its input grows and shows its conversation once past its input, and only its input again once dragged back down to it (a snap); let go there, it is as tall as its input', async () => { + const { controller, read, resizing } = createInputOnly({ inputOnly: true, mode: ChatWindowLayoutMode.Stacked }); + const collapsed = CHAT_VIEW_TOP + INPUT_HEIGHT; + const dragTo = async (height: number) => { + controller.layout(height); + await timeout(0); + return read(); + }; + resizing.set(true, undefined); + const pressed = read(); + const slightlyUp = await dragTo(collapsed + 5); + const pastTheInput = await dragTo(collapsed + 60); + const backDown = await dragTo(collapsed + 2); + resizing.set(false, undefined); + + assert.deepStrictEqual({ pressed, slightlyUp, pastTheInput, backDown, letGo: read() }, { + pressed: { shown: true, chosen: true, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: collapsed }, + slightlyUp: { shown: true, chosen: true, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: collapsed }, + pastTheInput: { shown: false, chosen: false, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: Math.min(collapsed, SESSION_CHAT_VIEW_MINIMUM_HEIGHT) }, + backDown: { shown: true, chosen: true, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: collapsed }, + letGo: { shown: true, chosen: true, maximumHeight: collapsed + 1, minimumHeight: collapsed }, + }); + }); + + test('let go past its input, the chat shows its conversation at the height it was dragged to; laid out while not dragged, it does not change what it shows', async () => { + const { controller, read, resizing } = createInputOnly({ inputOnly: true, mode: ChatWindowLayoutMode.Stacked }); + const collapsed = CHAT_VIEW_TOP + INPUT_HEIGHT; + controller.layout(collapsed + 200); + await timeout(0); + const notDragged = read().chosen; + resizing.set(true, undefined); + controller.layout(collapsed + 200); + await timeout(0); + resizing.set(false, undefined); + + assert.deepStrictEqual({ notDragged, letGo: read() }, { + notDragged: true, + letGo: { shown: false, chosen: false, maximumHeight: Number.POSITIVE_INFINITY, minimumHeight: Math.min(collapsed, SESSION_CHAT_VIEW_MINIMUM_HEIGHT) }, + }); + }); + + test('what a drag of the sash showed is announced once, as it lets go: the conversation shown or hidden, and nothing for a drag that changed nothing', async () => { + const { controller, resizing } = createInputOnly({ inputOnly: true, mode: ChatWindowLayoutMode.Stacked }); + const ariaContainer = $('.aria-container'); + setARIAContainer(ariaContainer); + const collapsed = CHAT_VIEW_TOP + INPUT_HEIGHT; + const announced = () => ariaContainer.textContent ?? ''; + const drag = async (...heights: number[]) => { + ariaContainer.querySelectorAll('[aria-live]').forEach(element => element.textContent = ''); + resizing.set(true, undefined); + for (const height of heights) { + controller.layout(height); + await timeout(0); + } + const whileDragging = announced(); + resizing.set(false, undefined); + return { whileDragging, letGo: announced() }; + }; + + assert.deepStrictEqual({ + up: await drag(collapsed + 60), + upAndDownAndUp: await drag(collapsed + 60, collapsed + 2, collapsed + 80), + down: await drag(collapsed + 2), + nothing: await drag(collapsed + 3), + }, { + up: { whileDragging: '', letGo: 'Chat conversation shown' }, + upAndDownAndUp: { whileDragging: '', letGo: '' }, + down: { whileDragging: '', letGo: 'Chat conversation hidden' }, + nothing: { whileDragging: '', letGo: '' }, + }); + }); + + test('showing only the input, or the conversation, from the chat is what its window shows next time', () => { + const { chatView, read } = createInputOnly({ inputOnly: false, mode: ChatWindowLayoutMode.Stacked }); + chatView.setInputOnly(true); + const inputOnly = read().chosen; + chatView.setInputOnly(false); + + assert.deepStrictEqual({ inputOnly, conversation: read().chosen }, { inputOnly: true, conversation: false }); + }); + + test('a chat editor shows exactly one chat, with no tabs of chats in it, also of a session of several chats: its chats are editors of their own', () => { + const { instantiationService, chatViews } = createServices(); + const host: ISessionChatViewHost = { + content: constObservable(testPaneContentOf(createTestActiveSession('session', true, { chatCount: 3 }), () => { })), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + }; + const view = disposables.add(instantiationService.createInstance(ChatEditorView, host)); + view.layout(800, 600, 0, 0); + + const shownTabStrips = [...view.element.querySelectorAll('.session-chat-tabs-bar')].filter(strip => strip.style.display !== 'none'); + assert.deepStrictEqual({ chatViews: chatViews.length, shownTabStrips: shownTabStrips.length, chatsToSwitchTo: view.element.querySelectorAll('.chat-composite-bar-tab').length - 1 }, { chatViews: 1, shownTabStrips: 0, chatsToSwitchTo: 0 }); + }); + + test('a chat of another window dragged over a chat editor shows where it opens, and opens beside the chat of the editor on drop', async () => { + const { instantiationService } = createServices(); + const opened: { chat: string; tabOf: string | undefined }[] = []; + const other = createTestActiveSession('other'); + instantiationService.stub(ISessionsManagementService, new class extends mock() { + override readonly onDidChangeSessions = Event.None; + override readonly onDidChangeSessionTypes = Event.None; + override getSessionForChatResource() { + const chat = new class extends mock() { + override readonly resource = other.mainChat.get().resource; + override readonly isArchived = constObservable(false); + }(); + const session = new class extends mock() { + override readonly loading = constObservable(false); + override readonly chats = constObservable([chat]); + override readonly mainChat = constObservable(chat); + }(); + return { session, chat }; + } + }()); + instantiationService.stub(IChatWindowService, new class extends mock() { + override getWindow() { return {} as ReturnType; } + override async open(chat: URI, options?: IChatWindowOpenOptions) { + opened.push({ chat: chat.toString(), tabOf: options?.tabOf?.toString() }); + return undefined; + } + }()); + const host: ISessionChatViewHost = { + content: constObservable(testPaneContentOf(createTestActiveSession('session'), () => { })), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + // As a chat window's chat does + createDropTarget: (element, chat) => instantiationService.createInstance(ChatWindowSessionDropTarget, element, chat), + }; + const view = disposables.add(instantiationService.createInstance(ChatEditorView, host)); + mainWindow.document.body.appendChild(view.element); + disposables.add(toDisposable(() => view.element.remove())); + const dataTransfer = new DataTransfer(); + fillSessionChatDragData(new DragEvent('dragstart', { dataTransfer }), 'other', URI.parse('test-chat://other')); + + view.element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + const overlay = view.element.querySelector('.chat-window-session-drop-overlay'); + overlay?.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual({ overlay: !!overlay, opened }, { overlay: true, opened: [{ chat: 'test-chat://other', tabOf: 'test-chat://session' }] }); + }); + + test('before its editor moves, the chat saves what it shows, such as where it is scrolled to, for the view where it moves to', () => { + const { instantiationService, chatViews } = createServices(); + const host: ISessionChatViewHost = { + content: constObservable(testPaneContentOf(createTestActiveSession('session'), () => { })), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + }; + const view = disposables.add(instantiationService.createInstance(ChatEditorView, host)); + const saved: string[] = []; + for (const chatView of chatViews) { + chatView.saveViewState = () => saved.push(chatView.kind); + } + view.saveViewState(); + + assert.deepStrictEqual({ primary: view.sessionView.primaryChatView.get() === chatViews.at(-1), saved }, { primary: true, saved: ['chat'] }); + }); + test('only the window\'s active chat shows the Session Activity Bar: of two chats split in Stacked, the active one; with only its main part shown, still the active one, outside of its hidden chat', () => { + const { instantiationService } = createServices(); + const layoutMode = observableValue('layoutMode', ChatWindowLayoutMode.Stacked); + const window = upcastPartial({ + layoutMode, + inputOnly: constObservable(false), + resizing: constObservable(false), + mainPart: upcastPartial({ activeGroup: upcastPartial({ activeEditorPane: undefined, onDidActiveEditorChange: Event.None }), onDidChangeActiveGroup: Event.None }), + }); + const createView = (sessionId: string, active: boolean) => disposables.add(instantiationService.createInstance(ChatEditorView, { + content: constObservable(testPaneContentOf(createTestActiveSession(sessionId), () => { })), + window: constObservable(window), + active: constObservable(active), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + const views = [createView('a', true), createView('b', false)]; + const read = () => views.map(view => { + // What decides whether the group's Session Activity Bar shows, and where + const group = (view.sessionView as unknown as { readonly _group: { readonly groupActive: boolean; readonly _sessionVisible: boolean; readonly _sessionPartVisible: boolean } })._group; + return { active: group.groupActive, visible: group._sessionVisible, partVisible: group._sessionPartVisible }; + }); + + const stacked = read(); + layoutMode.set(ChatWindowLayoutMode.EditorOnly, undefined); + const editorOnly = read(); + + assert.deepStrictEqual({ stacked, editorOnly }, { + stacked: [{ active: true, visible: true, partVisible: true }, { active: false, visible: true, partVisible: true }], + editorOnly: [{ active: true, visible: false, partVisible: false }, { active: false, visible: false, partVisible: false }], + }); + }); + + test('a chat editor tells its host whether it shows the chat from the moment it attaches: not in a window that shows only its main part, until the window shows its chat', () => { + const { instantiationService } = createSessionViewTestServices(disposables); + const layoutMode = observableValue('layoutMode', ChatWindowLayoutMode.EditorOnly); + const window = upcastPartial({ + layoutMode, + inputOnly: constObservable(false), + resizing: constObservable(false), + mainPart: upcastPartial({ activeGroup: upcastPartial({ activeEditorPane: undefined, onDidActiveEditorChange: Event.None }), onDidChangeActiveGroup: Event.None }), + }); + // What the host sees of the view's visibility, from the moment it attaches, as a chat window's chat marks it read + const seen: boolean[] = []; + disposables.add(instantiationService.createInstance(ChatEditorView, { + content: constObservable(testPaneContentOf(createTestActiveSession('session'), () => { })), + window: constObservable(window), + active: constObservable(true), + attach: view => autorun(reader => { seen.push(view.visible.read(reader)); }), + view: constObservable(undefined), + })); + const editorOnly = [...seen]; + layoutMode.set(ChatWindowLayoutMode.SideBySide, undefined); + + assert.deepStrictEqual({ editorOnly, sideBySide: seen }, { editorOnly: [false], sideBySide: [false, true] }); + }); + + test('the session header shows at the top of the chat\'s card, as in the main window, in every layout mode, and hides while the chat shows only its input in Stacked; its title drags the editor of the chat', () => { + const { instantiationService } = createServices(); + const layoutMode = observableValue('layoutMode', ChatWindowLayoutMode.SideBySide); + const inputOnly = observableValue('inputOnly', true); + const window = upcastPartial({ + layoutMode, + inputOnly, + resizing: constObservable(false), + toggleConversation: () => inputOnly.set(!inputOnly.get(), undefined), + mainPart: upcastPartial({ activeGroup: upcastPartial({ activeEditorPane: undefined, onDidActiveEditorChange: Event.None }), onDidChangeActiveGroup: Event.None }), + }); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content: constObservable(testPaneContentOf(createTestActiveSession('session'), () => { })), + window: constObservable(window), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + view.layout(400, 800, 0, 0); + const read = () => { + const header = view.element.querySelector('.session-header-bar'); + return { inCard: !!header && view.sessionView.element.contains(header), shown: !!header && header.style.display !== 'none', dragsSession: !!header?.draggable, headerDragsEditor: view.dragHandle === view.sessionView.headerElement }; + }; + + const modes: Record> = {}; + for (const mode of [ChatWindowLayoutMode.SideBySide, ChatWindowLayoutMode.ChatOnly, ChatWindowLayoutMode.Stacked]) { + layoutMode.set(mode, undefined); + modes[mode] = read(); + } + window.toggleConversation(); + const stackedConversation = read(); + + const shown = { inCard: true, shown: true, dragsSession: false, headerDragsEditor: true }; + assert.deepStrictEqual({ modes, stackedConversation }, { + modes: { + [ChatWindowLayoutMode.SideBySide]: shown, + [ChatWindowLayoutMode.ChatOnly]: shown, + [ChatWindowLayoutMode.Stacked]: { ...shown, shown: false }, + }, + stackedConversation: shown, + }); + }); + + test('while the group of its editor shows its tabs, as it holds other editors too, the chat hides its session header, whose actions the tab bar shows for it, in its scope and on its session; alone in its group again, it shows its header', () => { + const { instantiationService } = createServices(); + const session = createTestActiveSession('session'); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content: constObservable(testPaneContentOf(session, () => { })), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + view.layout(400, 800, 0, 0); + const headerShown = () => view.element.querySelector('.session-header-bar')?.style.display !== 'none'; + + const alone = headerShown(); + view.setProvidedTitleVisible(false); + const withTabs = headerShown(); + view.setProvidedTitleVisible(true); + const aloneAgain = headerShown(); + + const { menuId, contextKeyService, options } = view.titleMenu; + assert.deepStrictEqual({ alone, withTabs, aloneAgain, menu: menuId.id, inChatEditorScope: SessionInChatEditorContext.getValue(contextKeyService), onSession: options.args?.[0] === session }, { + alone: true, + withTabs: false, + aloneAgain: true, + menu: Menus.SessionBarToolbar.id, + inChatEditorScope: true, + onSession: true, + }); + }); + + test('the tab of a chat shows its status as the sessions list does, spinning while in progress, its pull request once it is done, and its session in its tooltip and for screen readers; it changes only as these do', () => { + const status = observableValue('status', SessionStatus.InProgress); + const isRead = observableValue('isRead', true); + const pullRequest = observableValue('pullRequest', undefined); + const mainChat = upcastPartial({ resource: URI.parse('test-chat:/main'), title: constObservable('Main') }); + const chat = upcastPartial({ resource: URI.parse('test-chat:/side'), title: constObservable('Side chat'), status, isRead, isArchived: constObservable(false), completedStateIcon: pullRequest }); + const session = upcastPartial({ title: constObservable('The session'), mainChat: constObservable(mainChat), chats: constObservable([mainChat, chat]), isQuickChat: constObservable(false) }); + const sessionsListModelService = upcastPartial({ + getStatusIcon: (status, isRead, _isArchived, completedStateIcon) => ({ id: `${status}${isRead ? '' : '-unread'}${completedStateIcon ? `-${completedStateIcon.id}` : ''}` }), + }); + const input = disposables.add(new ChatEditorInput(chat.resource)); + input.setName('Side chat'); + let labelChanges = 0; + disposables.add(input.onDidChangeLabel(() => labelChanges++)); + disposables.add(autorun(reader => input.setDetails(getChatEditorInputDetails(session, chat, 'Side chat', reader, sessionsListModelService, () => constObservable(undefined))))); + const read = () => ({ icon: input.getIcon().id, title: input.getTitle(Verbosity.LONG), ariaLabel: input.getAriaLabel(), labelChanges }); + + const inProgress = read(); + isRead.set(true, undefined); + const unchanged = read(); + transaction(tx => { + status.set(SessionStatus.Completed, tx); + isRead.set(false, tx); + }); + const unread = read(); + transaction(tx => { + isRead.set(true, tx); + pullRequest.set(Codicon.gitPullRequest, tx); + }); + const withPullRequest = read(); + + assert.deepStrictEqual({ inProgress, unchanged, unread, withPullRequest }, { + inProgress: { icon: 'loading~spin', title: 'The session / Side chat', ariaLabel: 'The session / Side chat, State: In Progress', labelChanges: 1 }, + unchanged: { icon: 'loading~spin', title: 'The session / Side chat', ariaLabel: 'The session / Side chat, State: In Progress', labelChanges: 1 }, + unread: { icon: `${SessionStatus.Completed}-unread`, title: 'The session / Side chat', ariaLabel: 'The session / Side chat, State: Completed, unread', labelChanges: 2 }, + withPullRequest: { icon: `${SessionStatus.Completed}-${Codicon.gitPullRequest.id}`, title: 'The session / Side chat', ariaLabel: 'The session / Side chat, State: Completed', labelChanges: 3 }, + }); + }); + + test('the tab of a chat without details yet shows a chat and its name', () => { + const input = disposables.add(new ChatEditorInput(URI.parse('test-chat:/main'))); + input.setName('Main'); + + assert.deepStrictEqual({ icon: input.getIcon().id, title: input.getTitle(Verbosity.LONG), ariaLabel: input.getAriaLabel() }, { icon: Codicon.commentDiscussion.id, title: 'Main', ariaLabel: 'Main' }); + }); + + test('a chat editor shows a new-session composer until its session is created, without the session header: a send that prepares the session shows its chat, a failed one the composer again, and focus moves between them only where it was', () => { + const { instantiationService, chatViews } = createServices(); + const inProgress = observableValue('inProgress', false); + const preparationProgress = observableValue('preparationProgress', undefined); + const draft = createTestActiveSession('draft', false, { isNewSessionRequestInProgress: inProgress, preparationProgress }); + const content = observableValue('content', undefined); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content, + composer: constObservable({ draftHost: upcastPartial({}), session: constObservable(draft) }), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + mainWindow.document.body.appendChild(view.element); + disposables.add(toDisposable(() => view.element.remove())); + view.layout(800, 600, 0, 0); + const read = () => { + const shown = chatViews.filter(chatView => !chatView.disposed && view.element.contains(chatView.element)); + const header = view.element.querySelector('.session-header-bar'); + return { + shown: shown.map(chatView => chatView.kind), + focused: shown.find(chatView => chatView.element.contains(mainWindow.document.activeElement))?.kind, + header: !!header && header.style.display !== 'none', + label: view.sessionView.element.getAttribute('aria-label'), + }; + }; + chatViews.find(chatView => chatView.kind === 'newSession')!.focus(); + + const composing = read(); + transaction(tx => { + inProgress.set(true, tx); + preparationProgress.set({ message: 'Preparing', cancel: () => { } }, tx); + }); + const preparing = read(); + transaction(tx => { + inProgress.set(false, tx); + preparationProgress.set(undefined, tx); + }); + const failed = read(); + transaction(tx => { + draft.isCreated.set(true, tx); + content.set(testPaneContentOf(draft, () => { }), tx); + }); + const created = read(); + + assert.deepStrictEqual({ composing, preparing, failed, created, composerViewsLeft: chatViews.filter(chatView => !chatView.disposed && chatView.kind === 'newSession').length }, { + composing: { shown: ['newSession'], focused: 'newSession', header: false, label: 'Chat: New Session' }, + preparing: { shown: ['chat'], focused: 'chat', header: false, label: 'Chat: New Session' }, + failed: { shown: ['newSession'], focused: 'newSession', header: false, label: 'Chat: New Session' }, + created: { shown: ['chat'], focused: 'chat', header: true, label: 'Chat: Main Chat' }, + composerViewsLeft: 0, + }); + }); + + test('as its session\'s chat shows, the chat model the composer was bound to stays loaded, taken before the composer goes, until the chat editor shows other content, so the chat\'s view does not load the chat again from its provider; a composer that goes without its session showing takes nothing', () => { + const { instantiationService, chatViews } = createServices(); + const events: string[] = []; + instantiationService.stub(IChatService, new class extends mock() { + override acquireExistingSession(resource: URI) { + events.push(`take ${resource.toString()}${chatViews.some(chatView => chatView.kind === 'newSession' && !chatView.disposed) ? ' while the composer shows' : ''}`); + return upcastPartial({ dispose: () => events.push(`release ${resource.toString()}`) }); + } + }()); + const draft = createTestActiveSession('draft', false); + const content = observableValue('content', undefined); + const composer = observableValue('composer', { draftHost: upcastPartial({}), session: constObservable(draft) }); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content, + composer, + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + + transaction(tx => { + draft.isCreated.set(true, tx); + content.set(testPaneContentOf(draft, () => { }), tx); + }); + const created = events.splice(0); + const other = createTestActiveSession('other'); + content.set(testPaneContentOf(other, () => { }), undefined); + const otherContent = events.splice(0); + + // A composer that goes while nothing shows in its place, such as when it is closed. + const unsent = createTestActiveSession('unsent', false); + content.set(undefined, undefined); + composer.set({ draftHost: upcastPartial({}), session: constObservable(unsent) }, undefined); + composer.set(undefined, undefined); + const closed = events.splice(0); + + content.set(testPaneContentOf(draft, () => { }), undefined); + view.dispose(); + + assert.deepStrictEqual({ created, otherContent, closed, disposed: events }, { + created: ['take test-chat://draft while the composer shows'], + otherContent: ['release test-chat://draft'], + closed: [], + disposed: [], + }); + }); + + test('the chat model of a composer\'s session stays held only until the chat\'s view has bound to it, so that once its provider is replaced the view lets go of it, it is evicted and the chat loads again, without the chat editor changing what it shows; a view that never binds lets go of it after a while', () => runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 1_000 }, async () => { + const { instantiationService, chatViews } = createServices(); + const models = disposables.add(new ChatModelStore({ + createModel: props => { + const modelServices = disposables.add(new TestInstantiationService()); + modelServices.stub(ILogService, new NullLogService()); + modelServices.stub(IChatAgentService, new class extends mock() { + override getDefaultAgent() { return undefined; } + }()); + return modelServices.createInstance(ChatModel, undefined, { initialLocation: ChatAgentLocation.Chat, canUseTools: false, resource: props.sessionResource, disableBackgroundKeepAlive: true }); + }, + willDisposeModel: async () => { }, + }, new NullLogService())); + instantiationService.stub(IChatService, new class extends mock() { + override acquireExistingSession(resource: URI) { return models.acquireExisting(resource); } + }()); + const evicted: string[] = []; + disposables.add(models.onDidDisposeModel(model => evicted.push(model.sessionResource.toString()))); + + /** A chat editor whose composer, bound to its draft's chat model, sent its session: the session's chat shows instead. */ + const graduate = (id: string) => { + const draft = createTestActiveSession(id, false); + const resource = draft.mainChat.get().resource; + const props: IStartSessionProps = { sessionResource: resource, location: ChatAgentLocation.Chat, canUseTools: false }; + const composerModel = models.acquireOrCreate(props); + const original = composerModel.object; + const content = observableValue('content', undefined); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content, + composer: constObservable({ draftHost: upcastPartial({}), session: constObservable(draft) }), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + transaction(tx => { + draft.isCreated.set(true, tx); + content.set(testPaneContentOf(draft, () => { }), tx); + }); + // The composer's view went as the chat showed, and with it its model reference. + composerModel.dispose(); + const chatView = chatViews.filter(chatView => chatView.kind === 'chat' && !chatView.disposed).at(-1)!; + return { resource, props, original, chatView, content, view }; + }; + const isLoaded = (resource: URI) => !!models.get(resource); + + const bound = graduate('bound'); + const handedOff = isLoaded(bound.resource); + // The chat's view loads its chat and binds to the model that is still loaded. + bound.chatView.isLoadingTranscript.set(true, undefined); + const viewModel = models.acquireExisting(bound.resource)!; + bound.chatView.isLoadingTranscript.set(false, undefined); + await timeout(100); + const contentBefore = bound.content.get(); + // Its provider is replaced: the view lets go of the model and waits for it to be evicted before it loads the chat again. + viewModel.dispose(); + await models.waitForModelDisposals(); + const reloaded = disposables.add(models.acquireOrCreate(bound.props)); + const boundResult = { + handedOff, + evicted: evicted.includes(bound.resource.toString()), + fresh: reloaded.object !== bound.original, + sameContent: bound.content.get() === contentBefore, + sameChatView: !bound.chatView.disposed, + }; + + const unbound = graduate('unbound'); + await timeout(CHAT_MODEL_HOLD_TIMEOUT - 200); + const beforeTimeout = isLoaded(unbound.resource); + await timeout(200); + await models.waitForModelDisposals(); + const afterTimeout = isLoaded(unbound.resource); + + reloaded.dispose(); + await models.waitForModelDisposals(); + assert.deepStrictEqual({ bound: boundResult, unbound: { beforeTimeout, afterTimeout } }, { + bound: { handedOff: true, evicted: true, fresh: true, sameContent: true, sameChatView: true }, + unbound: { beforeTimeout: true, afterTimeout: false }, + }); + })); + + test('the actions its tab bar shows for a new-session composer do not offer Close Session, which has no pane to close there, also while the main window shows several sessions; once the session is created they do, as for any chat', () => { + const { instantiationService, contextKeyService } = createServices(); + const draft = createTestActiveSession('draft', false); + const content = observableValue('content', undefined); + const view = disposables.add(instantiationService.createInstance(ChatEditorView, { + content, + composer: constObservable({ draftHost: upcastPartial({}), session: constObservable(draft) }), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + const multipleSessions = MultipleSessionsVisibleContext.bindTo(contextKeyService); + const aiEnabled = ChatContextKeys.enabled.bindTo(contextKeyService); + // Its entry among the session header's actions, as the tab bar shows them while the header hides + const close = MenuRegistry.getMenuItems(view.titleMenu.menuId).filter(isIMenuItem).find(item => item.command.id === CLOSE_SESSION_COMMAND_ID && item.group === 'secondary/0_pane'); + const offersClose = (multiple: boolean, ai = true) => { + multipleSessions.set(multiple); + aiEnabled.set(ai); + return !!close && view.titleMenu.contextKeyService.contextMatchesRules(close.when); + }; + + const composer = { singleSession: offersClose(false), severalSessions: offersClose(true), aiHidden: offersClose(true, false) }; + draft.isCreated.set(true, undefined); + content.set(testPaneContentOf(draft, () => { }), undefined); + const created = { singleSession: offersClose(false), severalSessions: offersClose(true) }; + + assert.deepStrictEqual({ composer, created }, { + composer: { singleSession: false, severalSessions: false, aiHidden: false }, + created: { singleSession: true, severalSessions: true }, + }); + }); + + test('a send that reports more preparation progress keeps the chat it shows, and its focus; focus outside the chat editor stays there', () => { + const run = (focusOutside: boolean) => { + const store = disposables.add(new DisposableStore()); + const { instantiationService, chatViews } = createSessionViewTestServices(store); + const inProgress = observableValue('inProgress', false); + const preparationProgress = observableValue('preparationProgress', undefined); + const draft = createTestActiveSession('draft', false, { isNewSessionRequestInProgress: inProgress, preparationProgress }); + const view = store.add(instantiationService.createInstance(ChatEditorView, { + content: constObservable(undefined), + composer: constObservable({ draftHost: upcastPartial({}), session: constObservable(draft) }), + window: constObservable(undefined), + active: constObservable(true), + attach: () => Disposable.None, + view: constObservable(undefined), + })); + const outside = mainWindow.document.createElement('button'); + mainWindow.document.body.append(view.element, outside); + store.add(toDisposable(() => { view.element.remove(); outside.remove(); })); + view.layout(800, 600, 0, 0); + if (focusOutside) { + outside.focus(); + } else { + chatViews.find(chatView => chatView.kind === 'newSession')!.focus(); + } + const read = () => { + const preparation = chatViews.filter(chatView => chatView.kind === 'chat'); + return { created: preparation.length, shown: preparation.filter(chatView => !chatView.disposed && view.element.contains(chatView.element)).length, focus: mainWindow.document.activeElement === outside ? 'outside' : preparation.some(chatView => chatView.element.contains(mainWindow.document.activeElement)) ? 'chat' : 'elsewhere' }; + }; + + transaction(tx => { + inProgress.set(true, tx); + preparationProgress.set({ message: 'Cloning', cancel: () => { } }, tx); + }); + const first = read(); + preparationProgress.set({ message: 'Starting the container', cancel: () => { } }, undefined); + const second = read(); + store.dispose(); + return { first, second }; + }; + + assert.deepStrictEqual({ focusedInside: run(false), focusedOutside: run(true) }, { + focusedInside: { first: { created: 1, shown: 1, focus: 'chat' }, second: { created: 1, shown: 1, focus: 'chat' } }, + focusedOutside: { first: { created: 1, shown: 1, focus: 'outside' }, second: { created: 1, shown: 1, focus: 'outside' } }, + }); + }); + + test('a chat editor kept in its window refuses moves to other windows and to a new window with its reason; without that, it moves anywhere', () => { + const input = disposables.add(new ChatEditorInput(URI.parse('test:/chat'))); + const read = () => ({ sameWindow: input.canMove(1, 2), otherWindow: input.canMove(1, 3), newWindow: input.canMoveToNewWindow(1) }); + const free = read(); + input.setMoveRestriction({ reason: 'Send it first.', canMoveTo: group => group === 2 }); + const kept = read(); + input.setMoveRestriction(undefined); + + assert.deepStrictEqual({ free, kept, freeAgain: read() }, { + free: { sameWindow: true, otherWindow: true, newWindow: true }, + kept: { sameWindow: true, otherWindow: 'Send it first.', newWindow: 'Send it first.' }, + freeAgain: { sameWindow: true, otherWindow: true, newWindow: true }, + }); + }); +}); diff --git a/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowContribution.test.ts b/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowContribution.test.ts index 04f723fa5896..62c8fb308fa2 100644 --- a/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowContribution.test.ts +++ b/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowContribution.test.ts @@ -56,9 +56,12 @@ import { ResolvedKeybindingItem } from '../../../../../platform/keybinding/commo import { USLayoutResolvedKeybinding } from '../../../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; import { OperatingSystem } from '../../../../../base/common/platform.js'; import { MOVE_CHAT_TO_MAIN_WINDOW_COMMAND_ID, OPEN_ACTIVE_CHAT_IN_WINDOW_COMMAND_ID, OPEN_CHAT_IN_WINDOW_COMMAND_ID, OPEN_SESSION_IN_WINDOW_COMMAND_ID, openChatInWindow } from '../../browser/openChatInWindow.js'; +import { ISessionEditorWorkingSetRestoreState, ISessionEditorWorkingSetService } from '../../../layout/common/sessionEditorWorkingSet.js'; import { ITestSessionsService, ITestSessionWithChat, LegacyFakePaneState, stubMissingSessionHostsFromSessionsService, testGridPanes, withCreatedStatus } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; import { stubSessionsHostLayout } from '../../../../test/browser/sessionsHostLayoutTestUtils.js'; +const noEditorWorkingSetOwner = constObservable({ owner: undefined, restoring: false, applying: false }); + function evaluate(expression: ContextKeyExpression | undefined, values: Record): boolean { return expression?.evaluate({ getValue: (key: string) => values[key] as T | undefined } satisfies IContext) !== false; } @@ -366,6 +369,7 @@ suite('Chat window contribution', () => { })); stubMissingSessionHostsFromSessionsService(instantiationService); instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: [] }) })); + instantiationService.stub(ISessionEditorWorkingSetService, upcastPartial({ takeEditorsFor: () => undefined, restoreState: noEditorWorkingSetOwner })); let whileOpening: number | undefined; instantiationService.stub(IChatWindowService, upcastPartial({ open: async () => { @@ -385,6 +389,136 @@ suite('Chat window contribution', () => { }); }); + test('a chat of the session the main window shows takes the session\'s editors along when the window shows another chat of it, as the main window keeps the chat it shows', async () => { + const run = async () => { + const instantiationService = disposables.add(new TestInstantiationService()); + stubSessionsHostLayout(instantiationService); + instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({ suppressEditorPartAutoVisibility: () => toDisposable(() => { }) })); + const chat = (id: string) => ({ resource: URI.parse(`test:/chat/${id}`) }); + const pane = upcastPartial({ sessionId: 'alpha', resource: URI.parse('test:/alpha'), activeChat: constObservable(chat('shown')) as ITestSessionWithChat['activeChat'] }); + instantiationService.stub(ISessionsService, upcastPartial({ + gridShown: constObservable([pane]), + slotPanes: testGridPanes(constObservable([pane])), + mainWindowActiveSession: constObservable(pane), + })); + stubMissingSessionHostsFromSessionsService(instantiationService); + const mainGroups = [upcastPartial({ id: 1 })]; + instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: mainGroups }) })); + instantiationService.stub(ISessionEditorWorkingSetService, upcastPartial({ takeEditorsFor: () => undefined, restoreState: noEditorWorkingSetOwner })); + let moveFrom: readonly IEditorGroup[] | undefined; + instantiationService.stub(IChatWindowService, upcastPartial({ + open: async (_resource: URI, options?: { editors?: { moveFrom?: readonly IEditorGroup[] } }) => { + moveFrom = options?.editors?.moveFrom; + return undefined; + }, + })); + await instantiationService.invokeFunction(accessor => openChatInWindow(accessor, upcastPartial({ sessionId: 'alpha', resource: pane.resource }), chat('other').resource)); + return moveFrom?.length; + }; + + assert.strictEqual(await run(), 1); + }); + + test('with a working set per chat, opening another chat of the session the main window shows takes that chat\'s stash and leaves the shown chat\'s editors', async () => { + const instantiationService = disposables.add(new TestInstantiationService()); + stubSessionsHostLayout(instantiationService); + instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({ suppressEditorPartAutoVisibility: () => toDisposable(() => { }) })); + const chat = (id: string) => ({ resource: URI.parse(`test:/chat/${id}`) }); + const pane = upcastPartial({ sessionId: 'alpha', resource: URI.parse('test:/alpha'), activeChat: constObservable(chat('a')) as ITestSessionWithChat['activeChat'] }); + instantiationService.stub(ISessionsService, upcastPartial({ + gridShown: constObservable([pane]), + slotPanes: testGridPanes(constObservable([pane])), + mainWindowActiveSession: constObservable(pane), + })); + stubMissingSessionHostsFromSessionsService(instantiationService); + instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: [upcastPartial({ id: 1 })] }) })); + const saved = [upcastPartial({ typeId: 'saved' })]; + instantiationService.stub(ISessionEditorWorkingSetService, upcastPartial({ + restoreState: constObservable({ owner: { sessionResource: pane.resource, chatResource: chat('a').resource }, restoring: false, applying: false }), + takeEditorsFor: () => ({ editors: saved, activeEditor: saved[0], accept: () => { }, dispose: () => { } }), + })); + let opened: { moveFrom: number | undefined; takesSaved: boolean } | undefined; + instantiationService.stub(IChatWindowService, upcastPartial({ + open: async (_resource: URI, options?: { editors?: { moveFrom?: readonly IEditorGroup[]; editors?: readonly EditorInput[] } }) => { + opened = { moveFrom: options?.editors?.moveFrom?.length, takesSaved: options?.editors?.editors === saved }; + return undefined; + }, + })); + await instantiationService.invokeFunction(accessor => openChatInWindow(accessor, upcastPartial({ sessionId: 'alpha', resource: pane.resource }), chat('b').resource)); + + assert.deepStrictEqual(opened, { moveFrom: 0, takesSaved: true }); + }); + + test('a session another pane shows takes the editors it has saved along, which stay saved unless the window has them, and the main window\'s editors stay', async () => { + const run = async (windowHasEditors: boolean) => { + const instantiationService = disposables.add(new TestInstantiationService()); + stubSessionsHostLayout(instantiationService); + instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({ suppressEditorPartAutoVisibility: () => toDisposable(() => { }) })); + const chat = (id: string) => ({ resource: URI.parse(`test:/chat/${id}`) }); + const focused = upcastPartial({ sessionId: 'beta', resource: URI.parse('test:/beta'), activeChat: constObservable(chat('beta')) as ITestSessionWithChat['activeChat'] }); + const other = upcastPartial({ sessionId: 'alpha', resource: URI.parse('test:/alpha'), activeChat: constObservable(chat('alpha')) as ITestSessionWithChat['activeChat'] }); + instantiationService.stub(ISessionsService, upcastPartial({ + gridShown: constObservable([other, focused]), + slotPanes: testGridPanes(constObservable([other, focused])), + mainWindowActiveSession: constObservable(focused), + })); + stubMissingSessionHostsFromSessionsService(instantiationService); + instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: [upcastPartial({ id: 1 })] }) })); + const saved = [upcastPartial({ typeId: 'saved' })]; + const events: string[] = []; + instantiationService.stub(ISessionEditorWorkingSetService, upcastPartial({ + restoreState: noEditorWorkingSetOwner, + takeEditorsFor: (session: ISession) => session.sessionId === 'alpha' ? { editors: saved, activeEditor: saved[0], accept: () => events.push('accepted'), dispose: () => events.push('disposed') } : undefined, + })); + let opened: { moveFrom: number | undefined; editors: readonly EditorInput[] | undefined } | undefined; + instantiationService.stub(IChatWindowService, upcastPartial({ + open: async (_resource: URI, options?: { editors?: { moveFrom?: readonly IEditorGroup[]; editors?: readonly EditorInput[] } }) => { + opened = { moveFrom: options?.editors?.moveFrom?.length, editors: options?.editors?.editors }; + return upcastPartial({ mainPart: upcastPartial({ groups: [upcastPartial({ contains: () => windowHasEditors })] }) }); + }, + })); + await instantiationService.invokeFunction(accessor => openChatInWindow(accessor, upcastPartial({ sessionId: 'alpha', resource: other.resource }))); + return { moveFrom: opened?.moveFrom, takesSaved: opened?.editors === saved, events }; + }; + + assert.deepStrictEqual({ received: await run(true), notReceived: await run(false) }, { + received: { moveFrom: 0, takesSaved: true, events: ['accepted', 'disposed'] }, + notReceived: { moveFrom: 0, takesSaved: true, events: ['disposed'] }, + }); + }); + + test('a chat opened in a window opens exactly that chat, also its session\'s main chat, which is named by the session, while a session opens the chat it shows', async () => { + const instantiationService = disposables.add(new TestInstantiationService()); + stubSessionsHostLayout(instantiationService); + const shown = { resource: URI.parse('test:/chat/nested') }; + const pane = upcastPartial({ sessionId: 'alpha', activeChat: constObservable(shown) as ITestSessionWithChat['activeChat'] }); + instantiationService.stub(ISessionsService, upcastPartial({ + gridShown: constObservable([pane]), + slotPanes: testGridPanes(constObservable([pane])), + mainWindowActiveSession: constObservable(pane), + })); + stubMissingSessionHostsFromSessionsService(instantiationService); + instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({ suppressEditorPartAutoVisibility: () => toDisposable(() => { }) })); + instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: [] }) })); + instantiationService.stub(ISessionEditorWorkingSetService, upcastPartial({ takeEditorsFor: () => undefined, restoreState: noEditorWorkingSetOwner })); + const opened: { resource: string; exactChat: boolean | undefined }[] = []; + instantiationService.stub(IChatWindowService, upcastPartial({ + open: async (resource: URI, options?: { exactChat?: boolean }) => { + opened.push({ resource: resource.toString(), exactChat: options?.exactChat }); + return undefined; + }, + })); + const session = upcastPartial({ sessionId: 'alpha', resource: URI.parse('test:/alpha') }); + + await instantiationService.invokeFunction(accessor => openChatInWindow(accessor, session, session.resource)); + await instantiationService.invokeFunction(accessor => openChatInWindow(accessor, session)); + + assert.deepStrictEqual(opened, [ + { resource: 'test:/alpha', exactChat: true }, + { resource: 'test:/chat/nested', exactChat: false }, + ]); + }); + test('the keys of the Agents window\'s Add Tab commands and Run work in a chat window, Toggle Side Bar\'s does not; their menu entries stay in the main window', () => { for (const action of [NewChangesTabAction, NewFileTabAction, NewBrowserTabAction, NewSearchTabAction]) { disposables.add(registerAction2(action)); diff --git a/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowSessionDropTarget.test.ts b/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowSessionDropTarget.test.ts new file mode 100644 index 000000000000..e60168c7e708 --- /dev/null +++ b/src/vs/sessions/contrib/chatWindow/test/browser/chatWindowSessionDropTarget.test.ts @@ -0,0 +1,185 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { constObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { LocalSelectionTransfer } from '../../../../../platform/dnd/browser/dnd.js'; +import { registerInputDropTarget } from '../../../../../workbench/browser/dnd.js'; +import { IChatWindowOpenOptions, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { DraggedSessionIdentifier, fillSessionChatDragData } from '../../../../../workbench/contrib/sessions/browser/dnd.js'; +import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { IChat, ISession } from '../../../../../workbench/services/sessions/common/session.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { ChatWindowSessionDropTarget } from '../../browser/chatWindowSessionDropTarget.js'; + +suite('Chat Window Session Drop Target', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + const sessionResource = URI.parse('test-session:/a'); + const chatResource = URI.parse('test-chat:/a'); + const openChatResource = URI.parse('test-chat:/open'); + + function createSession(archived: boolean): ISession { + const chat = new class extends mock() { + override readonly resource = chatResource; + override readonly isArchived = constObservable(archived); + }(); + return new class extends mock() { + override readonly sessionId = 'session'; + override readonly resource = sessionResource; + override readonly loading = constObservable(false); + override readonly chats = constObservable([chat]); + override readonly mainChat = constObservable(chat); + }(); + } + + function setup(archived = false) { + const opened: { chat: string; tabOf: string | undefined; exactChat: boolean | undefined }[] = []; + const services = workbenchInstantiationService(undefined, store); + services.stub(ISessionsManagementService, new class extends mock() { + override getSession(resource: URI) { return resource.toString() === sessionResource.toString() ? createSession(archived) : undefined; } + override getSessionForChatResource(resource: URI) { + return resource.toString() === chatResource.toString() ? { session: createSession(archived), chat: createSession(archived).mainChat.get() } : undefined; + } + }()); + services.stub(IChatWindowService, new class extends mock() { + override getWindow() { return {} as ReturnType; } + override async open(chat: URI, options?: IChatWindowOpenOptions) { + opened.push({ chat: chat.toString(), tabOf: options?.tabOf?.toString(), exactChat: options?.exactChat }); + return undefined; + } + }()); + const element = $('.chat-view'); + element.style.cssText = 'width:400px;height:300px;'; + mainWindow.document.body.appendChild(element); + store.add(toDisposable(() => element.remove())); + store.add(services.createInstance(ChatWindowSessionDropTarget, element, () => openChatResource)); + return { element, opened }; + } + + function chatDragData(): DataTransfer { + const dataTransfer = new DataTransfer(); + fillSessionChatDragData(new DragEvent('dragstart', { dataTransfer }), 'session', chatResource); + return dataTransfer; + } + + const overlaySelector = '.chat-window-session-drop-overlay'; + + test('a session row dragged over the chat shows where it opens, and opens its chat beside the chat on drop', async () => { + const { element, opened } = setup(); + const transfer = LocalSelectionTransfer.getInstance(); + transfer.setData([new DraggedSessionIdentifier('session', sessionResource)], DraggedSessionIdentifier.prototype); + store.add(toDisposable(() => transfer.clearData(DraggedSessionIdentifier.prototype))); + const dataTransfer = new DataTransfer(); + dataTransfer.setData('application/vnd.code.session', JSON.stringify({ sessionId: 'session', resource: sessionResource.toString() })); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + const overlay = element.querySelector(overlaySelector); + assert.ok(overlay, 'shows an indicator that covers the chat'); + overlay.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual({ overlayRemoved: !element.querySelector(overlaySelector), opened }, { + overlayRemoved: true, + opened: [{ chat: chatResource.toString(), tabOf: openChatResource.toString(), exactChat: true }], + }); + }); + + test('a chat tab dragged over the chat opens that chat beside the chat on drop', async () => { + const { element, opened } = setup(); + const dataTransfer = new DataTransfer(); + fillSessionChatDragData(new DragEvent('dragstart', { dataTransfer }), 'session', chatResource); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + const overlay = element.querySelector(overlaySelector); + assert.ok(overlay); + overlay.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual(opened, [{ chat: chatResource.toString(), tabOf: openChatResource.toString(), exactChat: true }]); + }); + + test('a session row dragged from another window opens its chat from the typed payload on drop', async () => { + const { element, opened } = setup(); + const dataTransfer = new DataTransfer(); + dataTransfer.setData('application/vnd.code.session', JSON.stringify({ sessionId: 'session', resource: sessionResource.toString() })); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + const overlay = element.querySelector(overlaySelector); + assert.ok(overlay); + overlay.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual(opened, [{ chat: chatResource.toString(), tabOf: openChatResource.toString(), exactChat: true }]); + }); + + test('an archived session shows no indicator, and a drop opens nothing', async () => { + const { element, opened } = setup(true); + const transfer = LocalSelectionTransfer.getInstance(); + transfer.setData([new DraggedSessionIdentifier('session', sessionResource)], DraggedSessionIdentifier.prototype); + store.add(toDisposable(() => transfer.clearData(DraggedSessionIdentifier.prototype))); + const dataTransfer = new DataTransfer(); + dataTransfer.setData('application/vnd.code.session', '{}'); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + element.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual({ overlay: !!element.querySelector(overlaySelector), opened }, { overlay: false, opened: [] }); + }); + + test('an archived chat dragged as a tab shows where it opens, but a drop opens nothing', async () => { + const { element, opened } = setup(true); + const dataTransfer = new DataTransfer(); + fillSessionChatDragData(new DragEvent('dragstart', { dataTransfer }), 'session', chatResource); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + element.querySelector(overlaySelector)?.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + await timeout(0); + + assert.deepStrictEqual(opened, []); + }); + + test('the overlay covers exactly the chat, wherever the chat is', () => { + const { element } = setup(); + element.style.cssText = 'position:fixed;left:30px;top:40px;width:400px;height:300px;'; + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer: chatDragData() })); + const bounds = element.querySelector(overlaySelector)?.getBoundingClientRect(); + assert.deepStrictEqual(bounds && { left: bounds.left, top: bounds.top, width: bounds.width, height: bounds.height }, { left: 30, top: 40, width: 400, height: 300 }); + }); + + test('the overlay shows where an input that takes the drag is, and leaves the drag to the input once it moves over it', () => { + const { element } = setup(); + element.style.cssText = 'position:fixed;left:0;top:0;width:400px;height:300px;'; + const input = $('div'); + input.style.cssText = 'position:absolute;left:100px;top:200px;width:200px;height:50px;'; + element.appendChild(input); + store.add(registerInputDropTarget(input, { accepts: () => true, getHint: () => 'Drag here to attach' })); + const dataTransfer = chatDragData(); + + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer, clientX: 200, clientY: 100 })); + const overlay = element.querySelector(overlaySelector); + const hints = [...overlay?.querySelectorAll('.input-drop-target-hint') ?? []].map(hint => hint.textContent); + overlay?.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer, clientX: 200, clientY: 225 })); + + assert.deepStrictEqual({ hints, overlayOverInput: !!element.querySelector(overlaySelector) }, { hints: ['Drag here to attach'], overlayOverInput: false }); + }); + + test('files dragged over the chat show no indicator', () => { + const { element } = setup(); + const dataTransfer = new DataTransfer(); + dataTransfer.setData('text/plain', 'x'); + element.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer })); + assert.strictEqual(!!element.querySelector(overlaySelector), false); + }); +}); diff --git a/src/vs/sessions/contrib/chatWindow/test/browser/sessionsChatWindowProvider.test.ts b/src/vs/sessions/contrib/chatWindow/test/browser/sessionsChatWindowProvider.test.ts index d32736134f54..33e3ce85ab57 100644 --- a/src/vs/sessions/contrib/chatWindow/test/browser/sessionsChatWindowProvider.test.ts +++ b/src/vs/sessions/contrib/chatWindow/test/browser/sessionsChatWindowProvider.test.ts @@ -21,7 +21,7 @@ import { IContextKeyService } from '../../../../../platform/contextkey/common/co import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; import { IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; -import { IChatWindow, IChatWindowChat, IChatWindowOpenOptions, IChatWindowProvider, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { getChatWindowMainPartOptions, IChatWindow, IChatWindowChat, IChatWindowOpenOptions, IChatWindowProvider, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { ChatWindowsRestoration, OPEN_CHAT_WINDOWS_STORAGE_KEY } from '../../../../../workbench/contrib/chatWindow/browser/chatWindowsRestoration.js'; import { ChatWindowLayoutMode } from '../../../../../workbench/contrib/chatWindow/common/chatWindowLayout.js'; import { ChatWindow, ChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindowService.js'; @@ -65,7 +65,7 @@ import { MenuActivityBar, MenuActivityBarSize } from '../../../../../workbench/b import { IStorageService, StorageScope, StorageTarget, WillSaveStateReason } from '../../../../../platform/storage/common/storage.js'; import { TestStorageService } from '../../../../../workbench/test/common/workbenchTestServices.js'; import { AGENTS_FLOATING_PANEL_GAP } from '../../../../../workbench/contrib/sessions/common/layoutConstants.js'; -import { AGENTS_CHAT_WINDOW_CLASS, CHAT_WINDOW_MAIN_PART_GROUP_VIEW_OPTIONS, focusChatWindowUnlessFocused, getChatWindowMainPartOptions, SessionsChatWindowProvider } from '../../browser/sessionsChatWindowProvider.js'; +import { AGENTS_CHAT_WINDOW_CLASS, CHAT_WINDOW_MAIN_PART_GROUP_VIEW_OPTIONS, focusChatWindowUnlessFocused, SessionsChatWindowProvider } from '../../browser/sessionsChatWindowProvider.js'; import { DesktopMainEditorPart } from '../../../../browser/parts/desktopEditorPart.js'; import { IEditorGroupViewOptions } from '../../../../../workbench/browser/parts/editor/editor.js'; import { EditorInputCapabilities, GroupIdentifier, GroupModelChangeKind } from '../../../../../workbench/common/editor.js'; @@ -123,6 +123,8 @@ suite('Sessions chat window provider', () => { // The main window shows another session than those that move into it, such as one whose opening was cancelled const mainWindowActiveSession = constObservable(undefined); const onDidChangeSessions = store.add(new Emitter()); + /** How many times the chats looked their session up. */ + const lookups = { count: 0 }; const visibleSessions = observableValue('visibleSessions', []); const configuration = new TestConfigurationService({ [CHAT_WINDOWS_ENABLED_SETTING]: true }); const sentiment = observableValue('sentiment', {}); @@ -174,6 +176,7 @@ suite('Sessions chat window provider', () => { override getSession(resource: URI) { return sessions.find(session => session.resource.toString() === resource.toString()); } override getSessions() { return sessions; } override getSessionForChatResource(resource: URI) { + lookups.count++; for (const session of sessions) { const chat = session.chats.get().find(candidate => candidate.resource.toString() === resource.toString()); if (chat) { @@ -285,7 +288,7 @@ suite('Sessions chat window provider', () => { })); beforeProvider?.(storage); const provider = store.add(instantiationService.createInstance(SessionsChatWindowProvider)); - return { provider, chatWindowService, editorParts, storage, events, window, titleBars, opening, slots, onDidAcceptNewSessionRequest, onDidEndNewSessionRequest, windowInstantiationService: store.add(instantiationService.createChild(new ServiceCollection([IContextKeyService, store.add(new ContextKeyService(configuration))]))), onDidChangeSessions, sentiment, configuration, editorGroups, activeChat, chatHostOpenerService, visibleSessions }; + return { provider, lookups, chatWindowService, editorParts, storage, events, window, titleBars, opening, slots, onDidAcceptNewSessionRequest, onDidEndNewSessionRequest, windowInstantiationService: store.add(instantiationService.createChild(new ServiceCollection([IContextKeyService, store.add(new ContextKeyService(configuration))]))), onDidChangeSessions, sentiment, configuration, editorGroups, activeChat, chatHostOpenerService, visibleSessions }; } /** The window the chats show in: its active chat is `activeChat`. */ @@ -340,16 +343,33 @@ suite('Sessions chat window provider', () => { }); }); + test('a chat stays in the main window\'s grid until its window binds it, so that the editors of its session are there to move into the window; its window then keeps it out', async () => { + const store = disposables.add(new DisposableStore()); + const session = createSession('session', [createChat('main')]); + const { provider, events, windowInstantiationService } = createProvider(store, [session]); + + const content = (await provider.resolveContent(session.resource))!; + await content.resolveChat(session.resource); + const beforeBind = [...events]; + const binding = store.add(content.bind!(window, windowInstantiationService)); + const afterBind = [...events]; + binding.dispose(); + const afterUnbind = [...events]; + content.dispose(); + + assert.deepStrictEqual({ beforeBind, afterBind, afterUnbind }, { beforeBind: [], afterBind: ['hide session /main'], afterUnbind: ['hide session /main'] }); + }); + test('another resource of a chat a window shows, such as its session\'s, resolves to the entry the window has of it, not to one of its own', async () => { const store = disposables.add(new DisposableStore()); const session = createSession('session', [createChat('main')]); - const { provider, events } = createProvider(store, [session]); + const { provider } = createProvider(store, [session]); const content = store.add((await provider.resolveContent(session.resource))!); const shown = (await content.resolveChat(URI.parse('test:/main')))!; const ofSession = await content.resolveChat(session.resource); - assert.deepStrictEqual({ same: ofSession === shown, events }, { same: true, events: ['hide session /main'] }); + assert.deepStrictEqual({ same: ofSession === shown }, { same: true }); }); test('a session resolves to the chat its grid slot shows, unless the exact chat is asked for, which is its main chat', async () => { @@ -386,6 +406,64 @@ suite('Sessions chat window provider', () => { assert.deepStrictEqual(ended, ['/archived', '/deleted']); }); + test('a chat leaves its window once its session is removed, such as deleted, also while the session\'s last state still lists it; not as its provider goes away, which removes nothing', async () => { + const store = disposables.add(new DisposableStore()); + const session = createSession('session', [createChat('main')]); + const sessions = [session]; + const { provider, onDidChangeSessions } = createProvider(store, sessions); + const content = store.add((await provider.resolveContent(session.resource))!); + const chat = (await content.resolveChat(URI.parse('test:/main')))!; + const ended: string[] = []; + store.add(chat.onDidEnd(() => ended.push('ended'))); + + // Its provider goes away, which hides its sessions, and comes back + sessions.length = 0; + onDidChangeSessions.fire({ added: [], changed: [], removed: [] }); + sessions.push(session); + onDidChangeSessions.fire({ added: [session], changed: [], removed: [] }); + const afterProviderReturned = [...ended]; + // It is deleted, while its last state still lists the chat + sessions.length = 0; + onDidChangeSessions.fire({ added: [], changed: [], removed: [session] }); + + assert.deepStrictEqual({ afterProviderReturned, afterRemoved: ended }, { afterProviderReturned: [], afterRemoved: ['ended'] }); + }); + + test('a chat that knows its session looks it up again only as sessions are added or removed, not as sessions change, such as while they stream', async () => { + const store = disposables.add(new DisposableStore()); + const session = createSession('session', [createChat('main')]); + const other = createSession('other', [createChat('other-main')]); + const sessions = [session, other]; + const { provider, onDidChangeSessions, lookups } = createProvider(store, sessions); + const content = store.add((await provider.resolveContent(session.resource))!); + await content.resolveChat(URI.parse('test:/main')); + const before = lookups.count; + + for (let index = 0; index < 5; index++) { + onDidChangeSessions.fire({ added: [], changed: [other, session], removed: [] }); + } + const afterChanges = lookups.count - before; + onDidChangeSessions.fire({ added: [createSession('added', [createChat('added-main')])], changed: [], removed: [] }); + + assert.deepStrictEqual({ afterChanges, afterAdded: lookups.count - before }, { afterChanges: 0, afterAdded: 1 }); + }); + + test('a chat follows its session as it is replaced by another object with the same ID, such as a pending session that is committed, which comes only as a change', async () => { + const store = disposables.add(new DisposableStore()); + const pending = createSession('session', [createChat('main')]); + const sessions = [pending]; + const { provider, onDidChangeSessions } = createProvider(store, sessions); + const content = store.add((await provider.resolveContent(pending.resource))!); + const chat = asWindowChat((await content.resolveChat(URI.parse('test:/main')))!); + const before = chat.session.get() === pending; + + const committed = createSession('session', [createChat('main')]); + sessions[0] = committed; + onDidChangeSessions.fire({ added: [], changed: [committed], removed: [] }); + + assert.deepStrictEqual({ before, after: chat.session.get() === committed }, { before: true, after: true }); + }); + test('a chat is read once it shows: while it is the active chat of its window, also of a window without focus, and its editor shows it; a chat marked unread stays unread until its next turn ends, which marks it read while it shows', async () => { const store = disposables.add(new DisposableStore()); const unreadChat = (path: string) => Object.assign(createChat(path), { isRead: observableValue(`${path}.isRead`, false), lastTurnEnd: observableValue(`${path}.lastTurnEnd`, new Date(1)), updatedAt: constObservable(new Date(1)) }); @@ -560,9 +638,10 @@ suite('Sessions chat window provider', () => { const from = Object.assign(createSession('from', fromChats.get()), { chats: fromChats, dispose: () => disposed.push('from') }); const to = Object.assign(createSession('to', toChats.get()), { chats: toChats, dispose: () => disposed.push('to') }); const sessions = [from, to]; - const { provider, events, onDidChangeSessions } = createProvider(store, sessions); + const { provider, events, onDidChangeSessions, windowInstantiationService } = createProvider(store, sessions); const content = (await provider.resolveContent(URI.parse('test:/moved')))!; const chat = asWindowChat((await content.resolveChat(URI.parse('test:/moved')))!); + store.add(content.bind!(window, windowInstantiationService)); const before = chat.session.get() === from; transaction(tx => { @@ -710,7 +789,7 @@ suite('Sessions chat window provider', () => { const sizes: Record = {}; for (const size of [getSessionActivityBarSize(storage), MenuActivityBarSize.Normal, MenuActivityBarSize.Compact]) { setSessionActivityBarSize(storage, size); - mainColumn.setLayout(AGENTS_FLOATING_PANEL_GAP, false, size); + mainColumn.setLayout(AGENTS_FLOATING_PANEL_GAP - 1, false, size); sizes[`${Object.keys(sizes).length ? 'then ' : 'initially '}${size}`] = { chatWindow: strip.size.get(), mainWindow: mainColumn.minimumWidth }; } @@ -729,7 +808,7 @@ suite('Sessions chat window provider', () => { } }); - test('the strip of a chat window fills its column and keeps the main window\'s distances, to the card beside it and to the right edge of the window, inside the card of its column, which clips what it shows, in Default and Compact density, whatever the main window\'s state', () => { + test('the strip of a chat window aligns with the card frames and keeps the main window\'s distances, to the card beside it and to the right edge of the window, inside the card of its column, which clips what it shows, in Default and Compact density, whatever the main window\'s state', () => { const store = disposables.add(new DisposableStore()); const { provider, storage, windowInstantiationService, configuration } = createProvider(store, []); const part = (name: string) => new class extends mock() { @@ -771,7 +850,6 @@ suite('Sessions chat window provider', () => { const dock = (host: HTMLElement, size: MenuActivityBarSize) => { const docked = append(host, $('.menu-activity-bar.session-activity-bar.docked')); docked.classList.toggle('size-compact', size === MenuActivityBarSize.Compact); - docked.style.top = '0px'; return docked; }; // Between the boxes, and as they show: a card that leaves its frame to what it holds shows it inside its border @@ -782,7 +860,7 @@ suite('Sessions chat window provider', () => { const columnCard = column.closest('.part-grid-card') ?? column; return { width: stripRect.width, - fillsColumn: stripRect.top === rect(column).top && stripRect.bottom === rect(column).bottom, + verticalInsets: [stripRect.top - rect(column).top, rect(column).bottom - stripRect.bottom], insideItsCard: stripRect.left >= rect(columnCard).left && stripRect.right <= rect(columnCard).right, toCard: stripRect.left - rect(card).right, visibleToCard: stripRect.left - rect(card).right + frameInset, @@ -802,14 +880,16 @@ suite('Sessions chat window provider', () => { const main = createWorkbench(mainStore, compact, ['noeditorpane']); const gridGutter = compact ? 0 : AGENTS_FLOATING_PANEL_GAP; const mainColumn = mainStore.add(new SessionActivityBarColumn(constObservable(true))); - mainColumn.setLayout(gridGutter, compact, size); + mainColumn.setLayout(compact ? 0 : gridGutter - 1, compact, size); const columnLeft = windowWidth - gridGutter - mainColumn.minimumWidth; const chatCard = append(main, $('div')); chatCard.style.cssText = `position: fixed; top: 0; left: 0; width: ${columnLeft}px; height: ${windowHeight}px;`; append(main, mainColumn.element).style.cssText = `position: fixed; top: 0; left: ${columnLeft}px; width: ${mainColumn.minimumWidth}px; height: ${windowHeight}px;`; // Its chat shows its frame inset within its card (`--agents-session-frame-inset`) const sessionFrameInset = parseFloat(mainWindow.getComputedStyle(main).getPropertyValue('--agents-session-frame-inset')) || 0; - expected[density] = distances(dock(mainColumn.element, size), mainColumn.element, chatCard, sessionFrameInset); + const mainDistances = distances(dock(mainColumn.element, size), mainColumn.element, chatCard, sessionFrameInset); + expected[density] = mainDistances; + assert.strictEqual(mainDistances.visibleToCard, mainDistances.toEdge); mainStore.dispose(); // A chat window beside the chat, and beside its main part, whatever the state of the main window, whose classes it mirrors diff --git a/src/vs/sessions/contrib/codeReview/browser/codeReviewService.ts b/src/vs/sessions/contrib/codeReview/browser/codeReviewService.ts index e4eb9843c77e..3855b27ffc94 100644 --- a/src/vs/sessions/contrib/codeReview/browser/codeReviewService.ts +++ b/src/vs/sessions/contrib/codeReview/browser/codeReviewService.ts @@ -211,6 +211,13 @@ export class CodeReviewService extends Disposable implements ICodeReviewService this._disposePRReview(session.resource); } })); + // New-session drafts are deleted when discarded or replaced, without a session change event. + this._register(this._sessionsManagementService.onDidDiscardNewSession(session => this._disposePRReview(session.resource))); + this._register(this._sessionsManagementService.onDidReplaceNewDraftSession(({ from, to }) => { + if (!isEqual(from.resource, to.resource)) { + this._disposePRReview(from.resource); + } + })); } getPRReviewState(sessionResource: URI): IObservable { diff --git a/src/vs/sessions/contrib/codeReview/test/browser/codeReviewService.test.ts b/src/vs/sessions/contrib/codeReview/test/browser/codeReviewService.test.ts index 2c68c4d9ab2d..a86c31df78bd 100644 --- a/src/vs/sessions/contrib/codeReview/test/browser/codeReviewService.test.ts +++ b/src/vs/sessions/contrib/codeReview/test/browser/codeReviewService.test.ts @@ -54,7 +54,11 @@ suite('CodeReviewService', () => { class MockSessionsManagementService extends mock() { private readonly _onDidChangeSessions: Emitter; private readonly _activeSession: ReturnType>; + private readonly _onDidDiscardNewSession: Emitter; + private readonly _onDidReplaceNewDraftSession: Emitter<{ readonly from: ISession; readonly to: ISession }>; override readonly onDidChangeSessions: Event; + override readonly onDidDiscardNewSession: Event; + override readonly onDidReplaceNewDraftSession: Event<{ readonly from: ISession; readonly to: ISession }>; readonly activeSession: IObservable; private readonly _sessions = new Map(); @@ -63,6 +67,10 @@ suite('CodeReviewService', () => { super(); this._onDidChangeSessions = disposables.add(new Emitter()); this.onDidChangeSessions = this._onDidChangeSessions.event; + this._onDidDiscardNewSession = disposables.add(new Emitter()); + this.onDidDiscardNewSession = this._onDidDiscardNewSession.event; + this._onDidReplaceNewDraftSession = disposables.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); + this.onDidReplaceNewDraftSession = this._onDidReplaceNewDraftSession.event; this._activeSession = observableValue('test.activeSession', undefined); this.activeSession = this._activeSession; } @@ -148,6 +156,14 @@ suite('CodeReviewService', () => { changed: event?.changed ?? [], }); } + + fireDiscardNewSession(session: ISession): void { + this._onDidDiscardNewSession.fire(session); + } + + fireReplaceNewDraftSession(from: ISession, to: ISession): void { + this._onDidReplaceNewDraftSession.fire({ from, to }); + } } class MockReviewThreadsFetcher extends mock() { @@ -680,6 +696,18 @@ suite('CodeReviewService', () => { ['thread-200'], ); }); + + test('PR review state is released for discarded and replaced new-session drafts', () => { + const discarded = sessionsManagement.addSession(URI.parse('test://session/discarded')); + const replaced = sessionsManagement.addSession(URI.parse('test://session/replaced')); + const replacement = sessionsManagement.addSession(URI.parse('test://session/replacement')); + const states = [discarded, replaced, replacement].map(draft => service.getPRReviewState(draft.resource)); + + sessionsManagement.fireDiscardNewSession(discarded); + sessionsManagement.fireReplaceNewDraftSession(replaced, replacement); + + assert.deepStrictEqual([discarded, replaced, replacement].map((draft, index) => service.getPRReviewState(draft.resource) === states[index]), [false, false, true]); + }); }); suite('Code Review Contributions', () => { diff --git a/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css b/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css index b4b047304f95..a106a26a8e55 100644 --- a/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css +++ b/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css @@ -28,5 +28,5 @@ } .empty-file-editor-search .monaco-inputbox { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); } 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 b400fb3a3029..e13cdbb298e2 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 @@ -19,6 +19,7 @@ import { URI } from '../../../../../base/common/uri.js'; import { isEqual } from '../../../../../base/common/resources.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS } from '../../../../../workbench/browser/parts/sessions/agentsPartCard.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { IAccessibleViewService } from '../../../../../platform/accessibility/browser/accessibleView.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; @@ -289,9 +290,11 @@ suite('Sessions - Editor Contribution', () => { test('uses one connected group frame with or without docked details', () => { const workbench = appendElement(mainWindow.document.body, 'monaco-workbench modern-ui-tabs modern-ui-connected-editor-tabs agent-sessions-workbench dock-detail-panel'); + workbench.classList.add(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS); workbench.style.setProperty('--vscode-agentsPanel-border', '#888888'); workbench.style.setProperty('--vscode-editorGroupHeader-tabsBorder', '#445566'); workbench.style.setProperty('--vscode-cornerRadius-large', '8px'); + workbench.style.setProperty('--vscode-agents-layout-floatingPanelGap', '4px'); workbench.style.setProperty('--vscode-strokeThickness', '1px'); workbench.style.setProperty('--vscode-focusBorder', '#00ff00'); workbench.style.setProperty('--vscode-contrastBorder', '#888888'); diff --git a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionManageCommand.ts b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionManageCommand.ts new file mode 100644 index 000000000000..441eaa68d02c --- /dev/null +++ b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionManageCommand.ts @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../nls.js'; +import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { EXTENSIONS_AGENTS_WINDOW_MANAGEMENT } from '../../../../platform/extensions/common/extensions.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { AICustomizationManagementCommands } from '../../../../workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.js'; +import { AICustomizationManagementEditor } from '../../../../workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.js'; +import { AICustomizationManagementSection } from '../../../../workbench/contrib/chat/common/aiCustomizationWorkspaceService.js'; +import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; + +/** + * The Manage Extension command of the Agents window: shows the extension's page in the Extensions section of Agent + * Customizations, or searches for it there when it isn't installed. When the Agents window doesn't manage extensions, + * it says so instead. + */ +export async function manageExtension(accessor: ServicesAccessor, extensionId: string): Promise { + const configurationService = accessor.get(IConfigurationService); + const commandService = accessor.get(ICommandService); + const editorService = accessor.get(IEditorService); + const notificationService = accessor.get(INotificationService); + + if (configurationService.getValue(EXTENSIONS_AGENTS_WINDOW_MANAGEMENT)) { + await commandService.executeCommand(AICustomizationManagementCommands.OpenEditor, AICustomizationManagementSection.Extensions); + const section = editorService.activeEditorPane instanceof AICustomizationManagementEditor ? editorService.activeEditorPane.getActiveSectionWidget() : undefined; + if (section?.showExtension) { + section.showExtension(extensionId); + return; + } + } + + notificationService.info(localize('agentsWindowExtensions.cannotManage', "Extension '{0}' can't be managed in this window right now.", extensionId)); +} diff --git a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionPage.ts b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionPage.ts new file mode 100644 index 000000000000..ca6565b24482 --- /dev/null +++ b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionPage.ts @@ -0,0 +1,290 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as DOM from '../../../../base/browser/dom.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { CancellationError } from '../../../../base/common/errors.js'; +import { Event } from '../../../../base/common/event.js'; +import { IMarkdownString } from '../../../../base/common/htmlContent.js'; +import { Disposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { IPager } from '../../../../base/common/paging.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IExtensionInfo, IExtensionQueryOptions, InstallExtensionResult, InstallOptions, IQueryOptions } from '../../../../platform/extensionManagement/common/extensionManagement.js'; +import { areSameExtensions } from '../../../../platform/extensionManagement/common/extensionManagementUtil.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; +import { ProgressLocation } from '../../../../platform/progress/common/progress.js'; +import { ExtensionEditor } from '../../../../workbench/contrib/extensions/browser/extensionEditor.js'; +import { AutoUpdateConfigurationValue, ExtensionState, IExtension, IExtensionsNotification, IExtensionsWorkbenchService, InstallExtensionOptions } from '../../../../workbench/contrib/extensions/common/extensions.js'; +import { ExtensionsInput, IExtensionEditorOptions } from '../../../../workbench/contrib/extensions/common/extensionsInput.js'; +import { IEditorGroup } from '../../../../workbench/services/editor/common/editorGroupsService.js'; +import { EnablementState, IExtensionManagementServer } from '../../../../workbench/services/extensionManagement/common/extensionManagement.js'; +import { IExtensionsStatus } from '../../../../workbench/services/extensions/common/extensions.js'; + +/** + * What the Extensions section of Agent Customizations does for the extension pages that it shows, in place of the + * Extensions view and editor of editor windows. + */ +export interface IAgentsWindowExtensionPageHost { + /** Shows the page of an extension, such as of a dependency of the extension whose page is shown. */ + openExtensionPage(extension: IExtension, options: IExtensionEditorOptions | undefined): void; + /** Leaves the page and searches extensions, such as the extensions of a publisher. */ + search(text: string): void; + /** Uninstalls an extension with `uninstall` like the section does, once users confirm it, and returns whether it did. */ + uninstall(extension: IExtension, uninstall: () => Promise): Promise; + /** Called once installing an extension from its page installed it, which enabled it in the Agents window. */ + didInstall(extension: IExtension): void; +} + +/** + * The extensions workbench service of the extension pages that the Extensions section shows. Opening and searching + * extensions stays in the section, and like in the section, installing an extension also enables it in the Agents + * window, and uninstalling one asks users to confirm it first, as that also uninstalls it from VS Code. + */ +export class AgentsWindowExtensionPageWorkbenchService implements IExtensionsWorkbenchService { + declare readonly _serviceBrand: undefined; + + constructor( + private readonly delegate: IExtensionsWorkbenchService, + private readonly host: IAgentsWindowExtensionPageHost, + ) { } + + get onChange(): Event { return this.delegate.onChange; } + get onReset(): Event { return this.delegate.onReset; } + get onDidChangeExtensionsNotification(): Event { return this.delegate.onDidChangeExtensionsNotification; } + get local(): IExtension[] { return this.delegate.local; } + get installed(): IExtension[] { return this.delegate.installed; } + get outdated(): IExtension[] { return this.delegate.outdated; } + get whenInitialized(): Promise { return this.delegate.whenInitialized; } + + async open(extension: IExtension | string, options?: IExtensionEditorOptions): Promise { + const resolved = typeof extension === 'string' + ? this.delegate.installed.find(installed => areSameExtensions(installed.identifier, { id: extension })) ?? (await this.delegate.getExtensions([{ id: extension }], CancellationToken.None))[0] + : extension; + if (!resolved) { + throw new Error(`Extension not found. ${extension}`); + } + this.host.openExtensionPage(resolved, options); + } + + async openSearch(searchValue: string): Promise { + // The page searches the categories of extensions like the Extensions view does, which the Marketplace filters without + // the `@`, while it filters their publishers in the same way. + this.host.search(searchValue.replace(/@category:/g, 'category:')); + } + + install(id: string, installOptions?: InstallExtensionOptions, progressLocation?: ProgressLocation | string): Promise; + install(vsix: URI, installOptions?: InstallExtensionOptions, progressLocation?: ProgressLocation | string): Promise; + install(extension: IExtension, installOptions?: InstallExtensionOptions, progressLocation?: ProgressLocation | string): Promise; + async install(arg: string | URI | IExtension, installOptions?: InstallExtensionOptions, progressLocation?: ProgressLocation | string): Promise { + if (typeof arg === 'string') { + return this.delegate.install(arg, installOptions, progressLocation); + } + if (URI.isUri(arg)) { + return this.delegate.install(arg, installOptions, progressLocation); + } + // Updating an extension, or installing another version of it, keeps it enabled or disabled. + if (arg.state !== ExtensionState.Uninstalled) { + return this.delegate.install(arg, installOptions, progressLocation); + } + // Users install extensions here to use them here, and extensions that don't support the Agents window are disabled + // there by default. The extensions service enables them as it installs them, even if the section closes meanwhile. + const installed = await this.delegate.install(arg, { ...installOptions, enable: true }, progressLocation); + this.host.didInstall(installed); + return installed; + } + + async uninstall(extension: IExtension): Promise { + if (!await this.host.uninstall(extension, () => this.delegate.uninstall(extension))) { + // Like when users cancel uninstalling an extension from all profiles, which the Uninstall action ignores. + throw new CancellationError(); + } + } + + queryLocal(server?: IExtensionManagementServer): Promise { + return this.delegate.queryLocal(server); + } + + queryGallery(token: CancellationToken): Promise>; + queryGallery(options: IQueryOptions, token: CancellationToken): Promise>; + queryGallery(optionsOrToken: IQueryOptions | CancellationToken, token?: CancellationToken): Promise> { + return CancellationToken.isCancellationToken(optionsOrToken) + ? this.delegate.queryGallery(optionsOrToken) + : this.delegate.queryGallery(optionsOrToken, token ?? CancellationToken.None); + } + + getExtensions(extensionInfos: IExtensionInfo[], token: CancellationToken): Promise; + getExtensions(extensionInfos: IExtensionInfo[], options: IExtensionQueryOptions, token: CancellationToken): Promise; + getExtensions(extensionInfos: IExtensionInfo[], optionsOrToken: IExtensionQueryOptions | CancellationToken, token?: CancellationToken): Promise { + return CancellationToken.isCancellationToken(optionsOrToken) + ? this.delegate.getExtensions(extensionInfos, optionsOrToken) + : this.delegate.getExtensions(extensionInfos, optionsOrToken, token ?? CancellationToken.None); + } + + getResourceExtensions(locations: URI[], isWorkspaceScoped: boolean): Promise { + return this.delegate.getResourceExtensions(locations, isWorkspaceScoped); + } + + canInstall(extension: IExtension): Promise { + return this.delegate.canInstall(extension); + } + + installInServer(extension: IExtension, server: IExtensionManagementServer, installOptions?: InstallOptions): Promise { + return this.delegate.installInServer(extension, server, installOptions); + } + + downloadVSIX(extension: string, versionKind: 'prerelease' | 'release' | 'any'): Promise { + return this.delegate.downloadVSIX(extension, versionKind); + } + + togglePreRelease(extension: IExtension): Promise { + return this.delegate.togglePreRelease(extension); + } + + canSetLanguage(extension: IExtension): boolean { + return this.delegate.canSetLanguage(extension); + } + + setLanguage(extension: IExtension): Promise { + return this.delegate.setLanguage(extension); + } + + setEnablement(extensions: IExtension | IExtension[], enablementState: EnablementState): Promise { + // Like the section, changes only apply to the Agents window, which has a dedicated workspace, while the page's Enable + // and Disable actions would also enable or disable extensions in editor windows. + switch (enablementState) { + case EnablementState.EnabledGlobally: enablementState = EnablementState.EnabledWorkspace; break; + case EnablementState.DisabledGlobally: enablementState = EnablementState.DisabledWorkspace; break; + } + return this.delegate.setEnablement(extensions, enablementState); + } + + isAutoUpdateEnabledFor(extensionOrPublisher: IExtension | string): boolean { + return this.delegate.isAutoUpdateEnabledFor(extensionOrPublisher); + } + + updateAutoUpdateEnablementFor(extensionOrPublisher: IExtension | string, enable: boolean): Promise { + return this.delegate.updateAutoUpdateEnablementFor(extensionOrPublisher, enable); + } + + shouldRequireConsentToUpdate(extension: IExtension): Promise { + return this.delegate.shouldRequireConsentToUpdate(extension); + } + + updateAutoUpdateForAllExtensions(value: boolean): Promise { + return this.delegate.updateAutoUpdateForAllExtensions(value); + } + + getAutoUpdateValue(): AutoUpdateConfigurationValue { + return this.delegate.getAutoUpdateValue(); + } + + isAutoUpdateDelayed(extension: IExtension): boolean { + return this.delegate.isAutoUpdateDelayed(extension); + } + + getAutoUpdateDelayRemaining(extension: IExtension): number { + return this.delegate.getAutoUpdateDelayRemaining(extension); + } + + getAutoUpdateDelay(): number { + return this.delegate.getAutoUpdateDelay(); + } + + checkForUpdates(): Promise { + return this.delegate.checkForUpdates(); + } + + getExtensionRuntimeStatus(extension: IExtension): IExtensionsStatus | undefined { + return this.delegate.getExtensionRuntimeStatus(extension); + } + + updateAll(): Promise { + return this.delegate.updateAll(); + } + + updateRunningExtensions(message?: string): Promise { + return this.delegate.updateRunningExtensions(message); + } + + getExtensionsNotification(): IExtensionsNotification | undefined { + return this.delegate.getExtensionsNotification(); + } + + isExtensionIgnoredToSync(extension: IExtension): boolean { + return this.delegate.isExtensionIgnoredToSync(extension); + } + + toggleExtensionIgnoredToSync(extension: IExtension): Promise { + return this.delegate.toggleExtensionIgnoredToSync(extension); + } + + toggleApplyExtensionToAllProfiles(extension: IExtension): Promise { + return this.delegate.toggleApplyExtensionToAllProfiles(extension); + } +} + +/** + * Shows the pages of extensions in the Extensions section of Agent Customizations, with the editor that shows them in + * editor windows. + */ +export class AgentsWindowExtensionPage extends Disposable { + + readonly element: HTMLElement; + private readonly editor: ExtensionEditor; + private readonly input = this._register(new MutableDisposable()); + private cancellation: CancellationTokenSource | undefined; + + constructor( + container: HTMLElement, + group: IEditorGroup, + host: IAgentsWindowExtensionPageHost, + @IInstantiationService instantiationService: IInstantiationService, + @IExtensionsWorkbenchService extensionsWorkbenchService: IExtensionsWorkbenchService, + ) { + super(); + + this.element = DOM.append(container, DOM.$('.agents-window-extension-page')); + const pageInstantiationService = this._register(instantiationService.createChild(new ServiceCollection( + [IExtensionsWorkbenchService, new AgentsWindowExtensionPageWorkbenchService(extensionsWorkbenchService, host)], + ))); + this.editor = this._register(pageInstantiationService.createInstance(ExtensionEditor, group)); + this.editor.create(this.element); + this._register(toDisposable(() => this.cancellation?.dispose(true))); + + const resizeObserver = this._register(new DOM.DisposableResizeObserver('AgentsWindowExtensionPage', () => this.layout(), DOM.getWindow(container))); + this._register(resizeObserver.observe(this.element)); + } + + /** + * Shows the page of an extension. Focus stays where it is, rather than moving to the page's content once it loads. + */ + async show(extension: IExtension, options: IExtensionEditorOptions | undefined): Promise { + this.cancellation?.dispose(true); + const cancellation = this.cancellation = new CancellationTokenSource(); + const input = this.input.value = new ExtensionsInput(extension); + this.editor.setVisible(true); + await this.editor.setInput(input, { ...options, preserveFocus: true }, {}, cancellation.token); + this.layout(); + } + + /** + * Clears the page, which also releases the webviews that show its content. + */ + clear(): void { + this.cancellation?.dispose(true); + this.cancellation = undefined; + this.editor.clearInput(); + this.editor.setVisible(false); + this.input.clear(); + } + + layout(): void { + const { clientWidth, clientHeight } = this.element; + if (clientWidth > 0 && clientHeight > 0) { + this.editor.layout(new DOM.Dimension(clientWidth, clientHeight)); + } + } +} diff --git a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsAccessibilityHelp.ts b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsAccessibilityHelp.ts index dd59e6e05f64..9cc95b6d7aea 100644 --- a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsAccessibilityHelp.ts +++ b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsAccessibilityHelp.ts @@ -45,9 +45,10 @@ export class AgentsWindowExtensionsAccessibilityHelp implements IAccessibleViewI ...(autoEnable === true ? [localize('agentsWindowExtensions.help.autoEnabled', "Extensions that add AI features and don't rely on views, debugging, or other features that are unavailable in the Agents window are enabled automatically instead. You can disable them like any other extension.")] : []), ...(Array.isArray(autoEnable) && autoEnable.length > 0 ? [localize('agentsWindowExtensions.help.autoEnabledListed', "Some extensions that haven't declared support for the Agents window are enabled automatically instead. You can disable them like any other extension.")] : []), localize('agentsWindowExtensions.help.warnings', "Extensions that haven't declared support for the Agents window and contribute views, debuggers, status bar items, or walkthroughs, which are not supported in the Agents window, have a warning, which is read as part of the extension."), - localize('agentsWindowExtensions.help.navigation', "Use the search box to filter extensions by name, identifier, publisher, or description. Press Tab to move to the list, use the Up and Down Arrow keys to move between extensions, and press Space or Enter to enable or disable the focused extension. Use the Left and Right Arrow keys on a group to collapse or expand it."), + localize('agentsWindowExtensions.help.navigation', "Use the search box to filter extensions by name, identifier, publisher, or description. Press Tab to move to the list, use the Up and Down Arrow keys to move between extensions, and press Space to enable or disable the focused extension. Use the Left and Right Arrow keys on a group to collapse or expand it."), + localize('agentsWindowExtensions.help.page', "Press Enter on an extension to open its page in place of the list, like the extension editor in VS Code. The page shows the extension's details, features, changelog, and dependencies, and its actions, such as to install, enable or disable, or uninstall it. Installing an extension from its page also enables it in the Agents window, and uninstalling it also asks you to confirm it first. Opening an extension's page moves the focus to the Back to Extensions button before the section title. Press Tab to move through the page, and press Enter on the Back to Extensions button, or use Go Back{0}, to return to the list.", ''), localize('agentsWindowExtensions.help.actions', "Press Shift+F10 on an installed extension to open its actions, which enable or disable it, restart extensions when required, and uninstall it. Uninstalling an extension here also uninstalls it from VS Code, so you are asked to confirm it first, unless you chose not to be asked again. The {0} setting turns the confirmation back on.", AGENTS_WINDOW_CONFIRM_UNINSTALL_SETTING), - ...(marketplaceStatus === ExtensionGalleryManifestStatus.Available ? [localize('agentsWindowExtensions.help.marketplace', "Typing in the search box also searches the Marketplace. Installed extensions are read with the install count and rating that the Marketplace reports for them. Extensions it finds that aren't installed are listed under Marketplace, which expands with each new search, with their publisher, install count, and rating. Press Space or Enter on one to install it. To install another version, such as a pre-release, press Tab to move to its Install button, then the Right Arrow key to move to the menu of other versions. Installing an extension here also installs it in VS Code, and enables it in the Agents window. Like installed extensions, extensions that haven't declared support for the Agents window and contribute features that it doesn't support have a warning, and so do extensions that can't be installed, for example because your organization doesn't allow it. The warning says why, and is read as part of the extension. If the Marketplace can't be searched, a warning on the search box says that only installed extensions are shown.")] : []), + ...(marketplaceStatus === ExtensionGalleryManifestStatus.Available ? [localize('agentsWindowExtensions.help.marketplace', "Typing in the search box also searches the Marketplace. Installed extensions are read with the install count and rating that the Marketplace reports for them. Extensions it finds that aren't installed are listed under Marketplace, which expands with each new search, with their publisher, install count, and rating. Press Space on one to install it. To install another version, such as a pre-release, press Tab to move to its Install button, then the Right Arrow key to move to the menu of other versions. Installing an extension here also installs it in VS Code, and enables it in the Agents window. Like installed extensions, extensions that haven't declared support for the Agents window and contribute features that it doesn't support have a warning, and so do extensions that can't be installed, for example because your organization doesn't allow it. The warning says why, and is read as part of the extension. If the Marketplace can't be searched, a warning on the search box says that only installed extensions are shown.")] : []), ...(marketplaceStatus === ExtensionGalleryManifestStatus.RequiresSignIn ? [localize('agentsWindowExtensions.help.marketplaceRequiresSignIn', "The search box also searches the Marketplace once you sign in to it from the Extensions view in VS Code. Until then, only installed extensions are shown.")] : []), ...(marketplaceStatus === ExtensionGalleryManifestStatus.AccessDenied ? [localize('agentsWindowExtensions.help.marketplaceAccessDenied', "Your account does not have access to the Extensions Marketplace, so the search box only searches installed extensions.")] : []), localize('agentsWindowExtensions.help.restart', "When a change requires restarting extensions or reloading the window, the extension is marked as requiring a restart, and a Restart Extensions or Reload Window button appears on its row and next to the section title. The button next to the section title also appears when an extension that you uninstalled here keeps running until extensions restart. Press Shift+Tab from the search box to reach the button next to the section title."), diff --git a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsMarketplace.ts b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsMarketplace.ts index 64c2816e7640..d89e3c79fe38 100644 --- a/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsMarketplace.ts +++ b/src/vs/sessions/contrib/extensions/browser/agentsWindowExtensionsMarketplace.ts @@ -282,7 +282,7 @@ export class MarketplaceExtensionRowRenderer implements IListRenderer('agentsWindowExtensionPage', false, localize('agentsWindowExtensionPage', "Whether the Extensions section of Agent Customizations shows the page of an extension, where the focus is.")); + /** * How the user changed whether an extension runs in the Agents window: from its row, with its switch, Space or Enter, or its * menu, or by installing it from the Marketplace group, which enables it once it is installed. @@ -445,11 +459,13 @@ class ExtensionRowRenderer implements IListRenderer; constructor( container: HTMLElement, + private readonly group: IEditorGroup, @IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService, @IExtensionManifestPropertiesService private readonly extensionManifestPropertiesService: IExtensionManifestPropertiesService, @@ -498,13 +523,50 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto @IContextViewService contextViewService: IContextViewService, @IHoverService hoverService: IHoverService, @IExtensionService extensionService: IExtensionService, + @IContextKeyService contextKeyService: IContextKeyService, ) { super(); this.element = DOM.append(container, $('.agents-window-extensions')); + // The page of an extension, and the webviews that show its content, inherit their context from the section's. + this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); + this.showsPageContextKey = AgentsWindowExtensionPageContext.bindTo(this.contextKeyService); const header = DOM.append(this.element, $('.agents-window-extensions-header')); const titleRow = DOM.append(header, $('.agents-window-extensions-title-row')); + // Like the Back buttons of the other pages of Agent Customizations, shown while an extension's page is shown. + this.backButton = DOM.append(titleRow, $('button.editor-back-button.agents-window-extensions-back-button')); + this.backButton.type = 'button'; + const backLabel = localize('agentsWindowExtensions.back', "Back to Extensions"); + this.backButton.setAttribute('aria-label', backLabel); + DOM.append(this.backButton, $(ThemeIcon.asCSSSelector(Codicon.arrowLeft), { 'aria-hidden': 'true' })); + this._register(hoverService.setupDelayedHover(this.backButton, { content: backLabel, style: HoverStyle.Pointer })); + this._register(DOM.addDisposableListener(this.backButton, DOM.EventType.CLICK, () => this.closeExtensionPage(true))); + // The mouse's Back button returns to the list from an extension's page, like it returns to the previous editor from the + // Extensions editor in editor windows. The Agents window moves between sessions when users press it, and does so before + // the section can, so the section handles it on the way down from the window instead. Go Back's keybindings run the + // command below while the page shows. + const targetWindow = DOM.getWindow(container); + this._register(DOM.addDisposableListener(targetWindow, DOM.EventType.MOUSE_DOWN, event => this.handleMouseBack(event, true), true)); + this._register(DOM.addDisposableListener(targetWindow, DOM.EventType.MOUSE_UP, event => this.handleMouseBack(event, false), true)); + this._register(CommandsRegistry.registerCommand({ + id: AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID, + handler: () => this.closeExtensionPage(true), + metadata: { description: backLabel }, + })); + // Agent Customizations is a modal, which stops the keys of most workbench commands before they reach the keybindings, as + // it resolves them without the context of the section, where Go Back's keybindings run the command above instead. + this._register(DOM.addStandardDisposableListener(this.element, DOM.EventType.KEY_DOWN, event => { + if (!this.pageExtension) { + return; + } + const resolved = this.keybindingService.softDispatch(event, event.target); + if (resolved.kind === ResultKind.KbFound && resolved.commandId === AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID) { + event.preventDefault(); + event.stopPropagation(); + this.closeExtensionPage(true); + } + })); DOM.append(titleRow, $('h2.agents-window-extensions-title')).textContent = localize('agentsWindowExtensions.title', "Extensions"); this.runtimeActionButton = this._register(new Button(titleRow, { ...defaultButtonStyles, secondary: true, small: true })); this._register(this.runtimeActionButton.onDidClick(() => this.runRuntimeAction(this.runtimeAction))); @@ -568,8 +630,17 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: entry => entry.type === 'group-header' ? entry.label : entry.type === 'message' ? entry.text : entry.extension.displayName, }, + // Like the Extensions view, clicking an extension opens its page. + openOnSingleClick: true, }, )); + this._register(this.tree.onDidOpen(event => { + const entry = event.element; + // Opens extensions that users click. The section handles Enter itself, like Space. + if (entry?.type === 'extension' || entry?.type === 'marketplace') { + this.openExtensionPage(entry.extension, undefined); + } + })); this._register(this.tree.onDidChangeCollapseState(event => { const entry = event.node.element; if (entry?.type === 'group-header') { @@ -586,14 +657,18 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto return; } const entry = this.tree.getFocus()[0]; - if ((entry?.type === 'extension' || entry?.type === 'marketplace') && (event.keyCode === KeyCode.Space || event.keyCode === KeyCode.Enter)) { - event.preventDefault(); - event.stopPropagation(); - if (entry.type === 'marketplace') { - this.marketplaceRowRenderer.install(entry.extension); - } else if (this.canChangeEnablement(entry.extension)) { - this.setEnabled(entry.extension, !this.isEnabled(entry.extension)); - } + if ((entry?.type !== 'extension' && entry?.type !== 'marketplace') || (event.keyCode !== KeyCode.Enter && event.keyCode !== KeyCode.Space)) { + return; + } + event.preventDefault(); + event.stopPropagation(); + if (event.keyCode === KeyCode.Enter) { + // Like in the Extensions view. + this.openExtensionPage(entry.extension, undefined); + } else if (entry.type === 'marketplace') { + this.marketplaceRowRenderer.install(entry.extension); + } else if (this.canChangeEnablement(entry.extension)) { + this.setEnabled(entry.extension, !this.isEnabled(entry.extension)); } })); this._register(this.tree.onContextMenu(event => { @@ -653,22 +728,130 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto if (this.renderPending) { this.render(); } + } else { + // Like the other pages of Agent Customizations, leaving the section leaves the page, which releases its webviews. + this.closeExtensionPage(false); } this.layoutTree(); } layout(): void { this.layoutTree(); + this.page?.layout(); } focus(): void { - this.searchInput.focus(); + if (this.pageExtension) { + this.backButton.focus(); + } else { + this.searchInput.focus(); + } } setSearchQuery(query: string): void { + this.closeExtensionPage(false); this.searchInput.value = query; } + showExtension(extensionId: string): void { + const extension = this.extensionsWorkbenchService.local.find(extension => ExtensionIdentifier.equals(extension.identifier.id, extensionId)); + if (extension) { + this.openExtensionPage(extension, undefined); + } else { + this.setSearchQuery(extensionId); + } + } + + /** + * Shows the page of an extension in place of the list, with the editor that shows it in editor windows, or the page of + * another extension while one is shown, such as of one of its dependencies. + */ + private openExtensionPage(extension: IExtension, options: IExtensionEditorOptions | undefined): void { + if (!this.page) { + const pageInstantiationService = this._register(this.instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]))); + this.page = this._register(pageInstantiationService.createInstance(AgentsWindowExtensionPage, this.element, this.group, { + openExtensionPage: (extension, options) => this.openExtensionPage(extension, options), + search: text => this.search(text), + uninstall: (extension, uninstall) => this.uninstall(extension, uninstall), + didInstall: extension => this.onDidInstall(extension), + })); + } + const showsOtherExtension = !this.pageExtension || !ExtensionIdentifier.equals(this.pageExtension.identifier.id, extension.identifier.id); + this.pageExtension = extension; + this.showsPageContextKey.set(true); + this.element.classList.add('shows-extension-page'); + this.page.show(extension, options).catch(error => { + if (!isCancellationError(error)) { + this.notificationService.error(error); + } + }); + this.page.layout(); + if (showsOtherExtension) { + // The list is hidden, or the page's content is replaced, so the page's Back button gets the focus. Reading whether + // it is shown updates its styles, which WebKit doesn't do for the class above before focusing it, from Enter. + if (DOM.getComputedStyle(this.backButton).display !== 'none') { + this.backButton.focus(); + } + status(localize('agentsWindowExtensions.pageStatus', "{0}, extension details", extension.displayName)); + } + } + + /** + * Shows the list in place of an extension's page. With `focus`, focuses the extension that users opened, like after + * closing the Extensions editor, or the search box if it is no longer listed. + */ + private closeExtensionPage(focus: boolean): void { + if (!this.pageExtension) { + return; + } + this.pageExtension = undefined; + this.showsPageContextKey.set(false); + this.element.classList.remove('shows-extension-page'); + this.page?.clear(); + this.layoutTree(); + if (focus) { + const [focused] = this.tree.getFocus(); + if (focused && this.tree.hasElement(focused)) { + this.tree.reveal(focused); + this.tree.domFocus(); + } else { + this.searchInput.focus(); + } + } + } + + /** + * Shows the list and searches it, such as for the extensions of a publisher that users chose on an extension's page. + */ + private search(text: string): void { + this.setSearchQuery(text); + this.searchInput.focus(); + } + + /** + * Returns to the list when users press the mouse's Back button over an extension's page, unless they turned off + * navigating with it. Also handles releasing it, which would otherwise navigate. + */ + private handleMouseBack(event: MouseEvent, isMouseDown: boolean): void { + if (event.button !== 3) { + return; + } + if (isMouseDown) { + this.handlingMouseBack = !!this.pageExtension + && DOM.isHTMLElement(event.target) && DOM.isAncestor(event.target, this.element) + && !!this.configurationService.getValue(MOUSE_BACK_FORWARD_NAVIGATION_SETTING); + } + if (!this.handlingMouseBack) { + return; + } + DOM.EventHelper.stop(event, true); + if (isMouseDown) { + this.closeExtensionPage(true); + } else { + this.handlingMouseBack = false; + } + } + private scheduleRender(): void { if (this.visible) { // Suggestions that appear while the section is visible don't need a badge either. @@ -848,9 +1031,9 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto } /** - * Logs that installing an extension from the Marketplace group enabled it in the Agents window. The extensions service - * enables it as it installs it, only when the Agents window disables it by default, which leaves it enabled for the - * Agents window's workspace. + * Logs that installing an extension from the section, from its Marketplace group or its page, enabled it in the Agents + * window. The extensions service enables it as it installs it, only when the Agents window disables it by default, which + * leaves it enabled for the Agents window's workspace. */ private onDidInstall(extension: IExtension): void { const installed = this.extensionsWorkbenchService.local.find(local => local.local && ExtensionIdentifier.equals(local.identifier.id, extension.identifier.id)); @@ -981,7 +1164,7 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto ? localize('agentsWindowExtensions.uninstall', "Uninstall...") : localize('agentsWindowExtensions.uninstallWithoutConfirmation', "Uninstall"), enabled: canUninstall, - run: () => this.uninstall(extension), + run: () => this.uninstall(extension, () => this.runUninstallAction(extension)), })]; return Separator.join(state, manage); @@ -1001,7 +1184,11 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto /** * Uninstalls an extension like the Extensions view's Uninstall action, once users confirm, as it is also uninstalled from VS Code. */ - private async uninstall(extension: IExtension): Promise { + /** + * Uninstalls an extension with `uninstall`, like the Extensions view does, once users confirm it, as it is also + * uninstalled from VS Code, and returns whether it did. + */ + private async uninstall(extension: IExtension, uninstall: () => Promise): Promise { // The Extensions service confirms uninstalling an extension from all profiles itself. if (!this.uninstallsFromAllProfiles(extension) && this.confirmsUninstall()) { const { confirmed, checkboxChecked } = await this.dialogService.confirm({ @@ -1012,7 +1199,7 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto checkbox: { label: localize('agentsWindowExtensions.doNotAskAgain', "Do not ask me again") }, }); if (!confirmed) { - return; + return false; } if (checkboxChecked) { await this.configurationService.updateValue(AGENTS_WINDOW_CONFIRM_UNINSTALL_SETTING, false); @@ -1021,6 +1208,20 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto // Uninstalling an extension pack or a dependency can also uninstall other extensions. const installed = [...this.extensionsWorkbenchService.local]; + await uninstall(); + // Running extensions keep running until extensions restart, which the section offers once they are no longer listed. + const keepRunning = installed.filter(uninstalled => uninstalled.state === ExtensionState.Uninstalled && uninstalled.runtimeState); + if (keepRunning.length) { + keepRunning.forEach(uninstalled => this.uninstalledExtensions.add(uninstalled)); + this.scheduleRender(); + } + return true; + } + + /** + * Uninstalls an extension with the Extensions view's Uninstall action, which reports why it can't. + */ + private async runUninstallAction(extension: IExtension): Promise { const uninstallAction = this.instantiationService.createInstance(UninstallAction); try { uninstallAction.extension = extension; @@ -1028,12 +1229,6 @@ export class AgentsWindowExtensionsWidget extends Disposable implements IAICusto } finally { uninstallAction.dispose(); } - // Running extensions keep running until extensions restart, which the section offers once they are no longer listed. - const keepRunning = installed.filter(uninstalled => uninstalled.state === ExtensionState.Uninstalled && uninstalled.runtimeState); - if (keepRunning.length) { - keepRunning.forEach(uninstalled => this.uninstalledExtensions.add(uninstalled)); - this.scheduleRender(); - } } private updateRuntimeAction(extensions: readonly IExtension[]): void { diff --git a/src/vs/sessions/contrib/extensions/browser/extensions.contribution.ts b/src/vs/sessions/contrib/extensions/browser/extensions.contribution.ts index 21f51f91867b..9e1cc225c3a5 100644 --- a/src/vs/sessions/contrib/extensions/browser/extensions.contribution.ts +++ b/src/vs/sessions/contrib/extensions/browser/extensions.contribution.ts @@ -4,10 +4,13 @@ *--------------------------------------------------------------------------------------------*/ import { localize } from '../../../../nls.js'; +import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; +import { CommandsRegistry } from '../../../../platform/commands/common/commands.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { EXTENSION_IDENTIFIER_PATTERN } from '../../../../platform/extensionManagement/common/extensionManagement.js'; -import { EXTENSIONS_AGENTS_WINDOW_AUTO_ENABLE, EXTENSIONS_AGENTS_WINDOW_AUTO_ENABLE_EXTENSIONS, EXTENSIONS_AGENTS_WINDOW_MANAGEMENT } from '../../../../platform/extensions/common/extensions.js'; +import { EXTENSIONS_AGENTS_WINDOW_AUTO_ENABLE, EXTENSIONS_AGENTS_WINDOW_AUTO_ENABLE_EXTENSIONS, EXTENSIONS_AGENTS_WINDOW_MANAGEMENT, MANAGE_EXTENSION_COMMAND_ID } from '../../../../platform/extensions/common/extensions.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import product from '../../../../platform/product/common/product.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; @@ -17,9 +20,10 @@ import { AICustomizationManagementSection } from '../../../../workbench/contrib/ import { extensionsViewIcon } from '../../../../workbench/contrib/extensions/browser/extensionsIcons.js'; import { AgentsWindowExtensionAutoEnablementExperiment } from './agentsWindowExtensionAutoEnablementExperiment.js'; import { AgentsWindowExtensionAutoEnablementTelemetry } from './agentsWindowExtensionAutoEnablementTelemetry.js'; +import { manageExtension } from './agentsWindowExtensionManageCommand.js'; import { AgentsWindowExtensionsAccessibilityHelp } from './agentsWindowExtensionsAccessibilityHelp.js'; import { AGENTS_WINDOW_EXTENSION_SUGGESTIONS_SETTING, AgentsWindowExtensionSuggestionsService, getExtensionSuggestionsBadgeDescription, IAgentsWindowExtensionSuggestionsService } from '../../../../workbench/contrib/sessions/browser/agentsWindowExtensionSuggestions.js'; -import { AGENTS_WINDOW_CONFIRM_UNINSTALL_SETTING, AgentsWindowExtensionsWidget } from './agentsWindowExtensionsWidget.js'; +import { AGENTS_WINDOW_CONFIRM_UNINSTALL_SETTING, AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID, AgentsWindowExtensionPageContext, AgentsWindowExtensionsWidget } from './agentsWindowExtensionsWidget.js'; Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ id: 'extensions', @@ -83,6 +87,20 @@ registerSingleton(IAgentsWindowExtensionSuggestionsService, AgentsWindowExtensio // Requests the experiment values of extensions as early as possible, so that extensions start with their experiment value. registerWorkbenchContribution2(AgentsWindowExtensionAutoEnablementExperiment.ID, AgentsWindowExtensionAutoEnablementExperiment, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(AgentsWindowExtensionAutoEnablementTelemetry.ID, AgentsWindowExtensionAutoEnablementTelemetry, WorkbenchPhase.AfterRestored); +CommandsRegistry.registerCommand(MANAGE_EXTENSION_COMMAND_ID, manageExtension); + +// Like Go Back, which returns to the previous editor from the Extensions editor in editor windows, with its keybindings. The +// keybindings run from the page's webviews, which forward their keys to the window, and the section runs them elsewhere on +// the page, as Agent Customizations is a modal that stops the keys of most workbench commands. +KeybindingsRegistry.registerKeybindingRule({ + id: AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID, + // Higher than Go Back and Sessions: Go Back. + weight: KeybindingWeight.SessionsContrib + 1, + when: AgentsWindowExtensionPageContext, + win: { primary: KeyMod.Alt | KeyCode.LeftArrow, secondary: [KeyCode.BrowserBack] }, + mac: { primary: KeyMod.WinCtrl | KeyCode.Minus, secondary: [KeyCode.BrowserBack] }, + linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Minus, secondary: [KeyCode.BrowserBack] }, +}); aiCustomizationManagementSectionRegistry.register({ id: AICustomizationManagementSection.Extensions, @@ -93,7 +111,7 @@ aiCustomizationManagementSectionRegistry.register({ separatorBefore: true, supportsHarness: () => true, getBadge: accessor => accessor.get(IAgentsWindowExtensionSuggestionsService).showBadge.map(show => show ? getExtensionSuggestionsBadgeDescription() : undefined), - create: (instantiationService, container) => instantiationService.createInstance(AgentsWindowExtensionsWidget, container), + create: (instantiationService, container, group) => instantiationService.createInstance(AgentsWindowExtensionsWidget, container, group), }); AccessibleViewRegistry.register(new AgentsWindowExtensionsAccessibilityHelp()); diff --git a/src/vs/sessions/contrib/extensions/browser/media/agentsWindowExtensions.css b/src/vs/sessions/contrib/extensions/browser/media/agentsWindowExtensions.css index 51a0020d5160..7f36dd11acec 100644 --- a/src/vs/sessions/contrib/extensions/browser/media/agentsWindowExtensions.css +++ b/src/vs/sessions/contrib/extensions/browser/media/agentsWindowExtensions.css @@ -13,17 +13,53 @@ .agents-window-extensions > .agents-window-extensions-header, .agents-window-extensions > .agents-window-extensions-search, .agents-window-extensions > .agents-window-extensions-tree, -.agents-window-extensions > .agents-window-extensions-empty { +.agents-window-extensions > .agents-window-extensions-empty, +.agents-window-extensions > .agents-window-extension-page { width: min(calc(100% - var(--vscode-spacing-size400) - var(--vscode-spacing-size400)), 840px); margin-inline: auto; box-sizing: border-box; } +/* An extension's page shows in place of the section's description, search box, and list, with a Back button before its title. */ +.agents-window-extensions:not(.shows-extension-page) .agents-window-extensions-back-button, +.agents-window-extensions:not(.shows-extension-page) > .agents-window-extension-page, +.agents-window-extensions.shows-extension-page .agents-window-extensions-description, +.agents-window-extensions.shows-extension-page > :is(.agents-window-extensions-search, .agents-window-extensions-tree, .agents-window-extensions-empty) { + display: none; +} + +.agents-window-extensions > .agents-window-extension-page { + flex: 1; + min-height: 0; + overflow: hidden; +} + +/* + * Sits in the margin before the title, so that showing it doesn't move the title, which stays aligned with the content below. + * The content leaves a margin of at least --vscode-spacing-size400 on each side, which fits the button. + */ +.agents-window-extensions .agents-window-extensions-title-row > .agents-window-extensions-back-button { + position: absolute; + top: 50%; + right: 100%; + /* Like the section's other icon buttons, and as tall as the title row, so the section doesn't clip its focus ring. */ + width: var(--vscode-spacing-size240); + height: var(--vscode-spacing-size240); + margin-right: var(--vscode-spacing-size60); + translate: 0 -50%; +} + +/* Like the Back buttons of the other pages of Agent Customizations, the focus ring only shows for keyboard navigation. */ +.ai-customization-management-editor.pointer-focus .agents-window-extensions-back-button:focus { + outline: none; +} + .agents-window-extensions-header { flex-shrink: 0; } .agents-window-extensions-title-row { + position: relative; display: flex; align-items: center; gap: var(--vscode-spacing-size60); diff --git a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionManageCommand.test.ts b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionManageCommand.test.ts new file mode 100644 index 000000000000..d03d9b2e3dc6 --- /dev/null +++ b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionManageCommand.test.ts @@ -0,0 +1,74 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.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 { EXTENSIONS_AGENTS_WINDOW_MANAGEMENT } from '../../../../../platform/extensions/common/extensions.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INotification, INotificationHandle, INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { TestNotificationService } from '../../../../../platform/notification/test/common/testNotificationService.js'; +import { AICustomizationManagementCommands } from '../../../../../workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.js'; +import { AICustomizationManagementEditor } from '../../../../../workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.js'; +import { AICustomizationManagementSection } from '../../../../../workbench/contrib/chat/common/aiCustomizationWorkspaceService.js'; +import { IVisibleEditorPane } from '../../../../../workbench/common/editor.js'; +import { IEditorService } from '../../../../../workbench/services/editor/common/editorService.js'; +import { manageExtension } from '../../browser/agentsWindowExtensionManageCommand.js'; + +suite('AgentsWindowExtensionManageCommand', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + async function runManageExtension(management: boolean, options?: { showsExtensions: boolean }): Promise<{ commands: unknown[][]; notifications: string[]; shownExtensions: string[] }> { + const commands: unknown[][] = []; + const notifications: string[] = []; + const shownExtensions: string[] = []; + const activeEditorPane = options ? upcastPartial(Object.assign(Object.create(AICustomizationManagementEditor.prototype) as AICustomizationManagementEditor, { + getActiveSectionWidget: () => options.showsExtensions ? { showExtension: (extensionId: string) => { shownExtensions.push(extensionId); } } : {} + })) : undefined; + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, new TestConfigurationService({ [EXTENSIONS_AGENTS_WINDOW_MANAGEMENT]: management })); + instantiationService.stub(ICommandService, upcastPartial({ + executeCommand: async (id: string, ...args: unknown[]) => { commands.push([id, ...args]); return undefined; } + })); + instantiationService.stub(IEditorService, upcastPartial({ activeEditorPane })); + instantiationService.stub(INotificationService, new class extends TestNotificationService { + override notify(notification: INotification): INotificationHandle { + notifications.push(String(notification.message)); + return super.notify(notification); + } + }); + + await instantiationService.invokeFunction(accessor => manageExtension(accessor, 'pub.ext')); + return { commands, notifications, shownExtensions }; + } + + test('says that it can\'t manage the extension when the Agents window doesn\'t manage extensions', async () => { + assert.deepStrictEqual(await runManageExtension(false), { + commands: [], + notifications: ['Extension \'pub.ext\' can\'t be managed in this window right now.'], + shownExtensions: [], + }); + }); + + test('shows the extension\'s page in the Extensions section of Agent Customizations', async () => { + assert.deepStrictEqual(await runManageExtension(true, { showsExtensions: true }), { + commands: [[AICustomizationManagementCommands.OpenEditor, AICustomizationManagementSection.Extensions]], + notifications: [], + shownExtensions: ['pub.ext'], + }); + }); + + test('opens the Extensions section of Agent Customizations, and says when it can\'t show the extension there', async () => { + assert.deepStrictEqual(await runManageExtension(true, { showsExtensions: false }), { + commands: [[AICustomizationManagementCommands.OpenEditor, AICustomizationManagementSection.Extensions]], + notifications: ['Extension \'pub.ext\' can\'t be managed in this window right now.'], + shownExtensions: [], + }); + }); +}); diff --git a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionPage.test.ts b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionPage.test.ts new file mode 100644 index 000000000000..3f7821dfb2b4 --- /dev/null +++ b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionPage.test.ts @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { isCancellationError } from '../../../../../base/common/errors.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IExtensionInfo } from '../../../../../platform/extensionManagement/common/extensionManagement.js'; +import { ExtensionEditorTab, ExtensionState, IExtension, IExtensionsWorkbenchService, InstallExtensionOptions } from '../../../../../workbench/contrib/extensions/common/extensions.js'; +import { IExtensionEditorOptions } from '../../../../../workbench/contrib/extensions/common/extensionsInput.js'; +import { EnablementState } from '../../../../../workbench/services/extensionManagement/common/extensionManagement.js'; +import { AgentsWindowExtensionPageWorkbenchService } from '../../browser/agentsWindowExtensionPage.js'; + +function anExtension(id: string, state: ExtensionState): IExtension { + return new class extends mock() { + override readonly identifier = { id }; + override readonly state = state; + }(); +} + +suite('AgentsWindowExtensionPageWorkbenchService', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + const installedTools = anExtension('pub.tools', ExtensionState.Installed); + const marketplaceFormatter = anExtension('pub.formatter', ExtensionState.Uninstalled); + + /** + * Creates the service of an extension page, which records what it asks the extensions service and the section to do. + * Users confirm uninstalling extensions as `confirmsUninstall` says. + */ + function createService(confirmsUninstall = true) { + const calls: string[] = []; + const enablements: EnablementState[] = []; + const describe = (extension: IExtension, flags: readonly (string | false | undefined)[]) => { + const set = flags.filter(flag => !!flag); + return set.length ? `${extension.identifier.id} (${set.join(', ')})` : extension.identifier.id; + }; + const delegate = new class extends mock() { + override readonly installed = [installedTools]; + override async getExtensions(extensionInfos: IExtensionInfo[]) { + calls.push(`query ${extensionInfos.map(info => info.id).join(', ')}`); + return [marketplaceFormatter]; + } + override async install(extension: IExtension | URI | string, options?: InstallExtensionOptions) { + assert.ok(typeof extension !== 'string' && !URI.isUri(extension)); + calls.push(`install ${describe(extension, [options?.enable && 'enable', options?.installPreReleaseVersion && 'pre-release'])}`); + return extension; + } + override async uninstall(extension: IExtension) { + calls.push(`uninstall ${extension.identifier.id}`); + } + override async setEnablement(extensions: IExtension | IExtension[], enablementState: EnablementState) { + enablements.push(enablementState); + } + }; + const service = new AgentsWindowExtensionPageWorkbenchService(delegate, { + openExtensionPage: (extension, options: IExtensionEditorOptions | undefined) => calls.push(`open page ${describe(extension, [options?.tab && `tab ${options.tab}`])}`), + search: text => calls.push(`search ${text}`), + uninstall: async (extension, uninstall) => { + calls.push(`confirm uninstalling ${extension.identifier.id}`); + if (confirmsUninstall) { + await uninstall(); + } + return confirmsUninstall; + }, + didInstall: extension => calls.push(`installed ${extension.identifier.id}`), + }); + return { service, calls, enablements }; + } + + test('opens the pages of extensions, which it looks up by identifier, and searches extensions, in the section', async () => { + const { service, calls } = createService(); + + await service.open(marketplaceFormatter, { tab: ExtensionEditorTab.Changelog }); + await service.open('PUB.TOOLS'); + await service.open('pub.formatter'); + await service.openSearch('publisher:"Publisher"'); + await service.openSearch('@category:"Programming Languages"'); + + assert.deepStrictEqual(calls, [ + 'open page pub.formatter (tab changelog)', + 'open page pub.tools', + 'query pub.formatter', + 'open page pub.formatter', + 'search publisher:"Publisher"', + // Like the Marketplace filters categories. + 'search category:"Programming Languages"', + ]); + }); + + test('enables extensions in the Agents window when it installs them, but not when it updates them', async () => { + const { service, calls } = createService(); + + await service.install(marketplaceFormatter, { installPreReleaseVersion: true }); + await service.install(installedTools); + + assert.deepStrictEqual(calls, [ + 'install pub.formatter (enable, pre-release)', + 'installed pub.formatter', + 'install pub.tools', + ]); + }); + + test('enables and disables extensions only in the Agents window, like the section, which uses its dedicated workspace', async () => { + const { service, enablements } = createService(); + + for (const state of [EnablementState.EnabledGlobally, EnablementState.DisabledGlobally, EnablementState.EnabledWorkspace, EnablementState.DisabledWorkspace]) { + await service.setEnablement(installedTools, state); + } + + assert.deepStrictEqual(enablements, [EnablementState.EnabledWorkspace, EnablementState.DisabledWorkspace, EnablementState.EnabledWorkspace, EnablementState.DisabledWorkspace]); + }); + + test('uninstalls extensions once users confirm it, and cancels uninstalling them otherwise', async () => { + const confirmed = createService(true); + const cancelled = createService(false); + + await confirmed.service.uninstall(installedTools); + const error = await cancelled.service.uninstall(installedTools).then(() => undefined, error => error); + + assert.deepStrictEqual({ confirmed: confirmed.calls, cancelled: cancelled.calls, cancellation: isCancellationError(error) }, { + confirmed: ['confirm uninstalling pub.tools', 'uninstall pub.tools'], + cancelled: ['confirm uninstalling pub.tools'], + cancellation: true, + }); + }); +}); diff --git a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.fixture.ts b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.fixture.ts index a6d8daf1f0bb..264cf4fe3ff1 100644 --- a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.fixture.ts +++ b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.fixture.ts @@ -20,6 +20,7 @@ import { EnablementState, IWorkbenchExtensionEnablementService, IWorkbenchExtens import { IExtensionManifestPropertiesService } from '../../../../../workbench/services/extensions/common/extensionManifestPropertiesService.js'; import { IExtensionService } from '../../../../../workbench/services/extensions/common/extensions.js'; import { IHostService } from '../../../../../workbench/services/host/browser/host.js'; +import { IEditorGroup } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; import { IPreferencesService } from '../../../../../workbench/services/preferences/common/preferences.js'; import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; import { AgentsWindowExtensionsWidget } from '../../browser/agentsWindowExtensionsWidget.js'; @@ -181,7 +182,11 @@ function renderWidget(ctx: ComponentFixtureContext, options: { readonly extensio }, }); - const widget = ctx.disposableStore.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, host)); + // The editor group of the Agent Customizations editor, which the extension pages that the section shows need. + const group = new class extends mock() { + override readonly windowId = DOM.getWindow(host).vscodeWindowId; + }(); + const widget = ctx.disposableStore.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, host, group)); widget.setVisible(true); if (options.searchQuery) { widget.setSearchQuery(options.searchQuery); diff --git a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.test.ts b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.test.ts index c6eace399638..4568252e68e6 100644 --- a/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.test.ts +++ b/src/vs/sessions/contrib/extensions/test/browser/agentsWindowExtensionsWidget.test.ts @@ -4,11 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { addDisposableListener } from '../../../../../base/browser/dom.js'; +import { IKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { DeferredPromise, retry, timeout } from '../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { CancellationError } from '../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { constObservable } from '../../../../../base/common/observable.js'; @@ -26,6 +29,11 @@ import { IConfigurationService } from '../../../../../platform/configuration/com import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IConfirmation, IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { IContextKeyService, IContextKeyServiceTarget } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { ResolutionResult, ResultKind } from '../../../../../platform/keybinding/common/keybindingResolver.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { NullTelemetryServiceShape } from '../../../../../platform/telemetry/common/telemetryUtils.js'; @@ -35,10 +43,13 @@ import { EnablementState, IWorkbenchExtensionEnablementService, IWorkbenchExtens import { IExtensionManifestPropertiesService, SessionsWindowMissingFeature } from '../../../../../workbench/services/extensions/common/extensionManifestPropertiesService.js'; import { IExtensionService } from '../../../../../workbench/services/extensions/common/extensions.js'; import { IHostService } from '../../../../../workbench/services/host/browser/host.js'; +import { MOUSE_BACK_FORWARD_NAVIGATION_SETTING } from '../../../../../workbench/services/history/common/history.js'; +import { IEditorGroup } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; import { IPreferencesService } from '../../../../../workbench/services/preferences/common/preferences.js'; import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; -import { AgentsWindowExtensionGroup, AgentsWindowExtensionsWidget, getMissingFeaturesWarning, getSuggestedContributionLabels, groupAgentsWindowExtensions, IAgentsWindowExtensionsGroup } from '../../browser/agentsWindowExtensionsWidget.js'; +import { AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID, AgentsWindowExtensionGroup, AgentsWindowExtensionPageContext, AgentsWindowExtensionsWidget, getMissingFeaturesWarning, getSuggestedContributionLabels, groupAgentsWindowExtensions, IAgentsWindowExtensionsGroup } from '../../browser/agentsWindowExtensionsWidget.js'; import { AGENTS_WINDOW_MARKETPLACE_QUERY_SOURCE } from '../../browser/agentsWindowExtensionsMarketplace.js'; +import { AgentsWindowExtensionPage } from '../../browser/agentsWindowExtensionPage.js'; import { IAgentsWindowExtensionSuggestionsService } from '../../../../../workbench/contrib/sessions/browser/agentsWindowExtensionSuggestions.js'; interface ITestExtensionOptions { @@ -106,6 +117,15 @@ function stubMarketplaceServices(instantiationService: TestInstantiationService, instantiationService.stub(IOpenerService, new class extends mock() { }); } +/** + * The editor group of the Agent Customizations editor, which the extension pages that the section shows need. + */ +function anEditorGroup(): IEditorGroup { + return new class extends mock() { + override readonly windowId = mainWindow.vscodeWindowId; + }(); +} + /** * Returns the accessible names of the rendered tree rows in order, once `predicate` holds for them. */ @@ -120,6 +140,15 @@ async function waitForRowLabels(container: HTMLElement, predicate: (labels: read }, 100, 30); } +/** + * Focuses a Marketplace row like right-clicking it does, as clicking it opens the extension's page. Unit tests don't + * dispatch the keybindings that move the focus of workbench lists. + */ +function focusRow(row: HTMLElement): void { + row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 })); + assert.ok(row.classList.contains('focused'), row.getAttribute('aria-label') ?? ''); +} + function summarize(groups: readonly IAgentsWindowExtensionsGroup[]) { return groups.map(group => ({ group: group.group, entries: group.entries.map(entry => ({ id: entry.extension.identifier.id, nameMatches: entry.nameMatches })) })); } @@ -235,7 +264,7 @@ suite('AgentsWindowExtensionsWidget', () => { override dismissBadge() { dismissals++; } }); stubMarketplaceServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, mainWindow.document.createElement('div'))); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, mainWindow.document.createElement('div'), anEditorGroup())); onChange.fire(undefined); const beforeNavigation = dismissals; @@ -301,7 +330,7 @@ suite('AgentsWindowExtensionsWidget', () => { } }); stubMarketplaceServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); for (const name of ['Tools', 'Theme', 'Cancelled']) { @@ -361,7 +390,7 @@ suite('AgentsWindowExtensionsWidget', () => { override dismissBadge() { } }); stubMarketplaceServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); // Browser tests load component CSS asynchronously, and the tree only renders its rows once the CSS gives it a height. @@ -447,7 +476,7 @@ suite('AgentsWindowExtensionsWidget', () => { override canChangeWorkspaceEnablement() { return true; } }); stubSectionServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); widget.setSearchQuery('formatter'); @@ -523,7 +552,7 @@ suite('AgentsWindowExtensionsWidget', () => { } }); stubSectionServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); widget.setSearchQuery('tools'); @@ -539,10 +568,10 @@ suite('AgentsWindowExtensionsWidget', () => { return { button, menus, calls, events }; } - test('installs a Marketplace extension with Enter without opening the Extensions editor, and enables it in the Agents window as it installs it', async () => { + test('installs a Marketplace extension with Space without opening its page, and enables it in the Agents window as it installs it', async () => { const result = await installFromMarketplace(false, row => { - row.click(); - row.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + focusRow(row); + row.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', keyCode: 32, bubbles: true, cancelable: true })); }); assert.deepStrictEqual(result, { @@ -599,7 +628,7 @@ suite('AgentsWindowExtensionsWidget', () => { override canChangeWorkspaceEnablement() { return true; } }); stubSectionServices(instantiationService, options.marketplaceStatus, options.onDidChangeMarketplaceStatus); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); return { container, widget }; } @@ -635,7 +664,7 @@ suite('AgentsWindowExtensionsWidget', () => { override canChangeWorkspaceEnablement() { return true; } }); stubSectionServices(instantiationService, () => marketplaceStatus, onDidChangeMarketplaceStatus.event); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); const rows = (predicate: (labels: readonly string[]) => boolean) => retry(async () => { const rendered = [...container.querySelectorAll('.agents-window-extension-row')].map(row => ({ @@ -695,13 +724,13 @@ suite('AgentsWindowExtensionsWidget', () => { widget.setSearchQuery('tools'); const unfocused = await installButtonTabIndex(() => true); - unfocused.row.click(); + focusRow(unfocused.row); const focused = await installButtonTabIndex(tabIndex => tabIndex === 0); widget.setSearchQuery('tool'); await retry(async () => assert.strictEqual(queries.length, 2), 100, 30); // The list loses its focus when the new search replaces the focused row while it searches. const searchedAgain = await installButtonTabIndex(() => true); - searchedAgain.row.click(); + focusRow(searchedAgain.row); const refocused = await installButtonTabIndex(tabIndex => tabIndex === 0); assert.deepStrictEqual([unfocused, focused, searchedAgain, refocused].map(({ tabIndex }) => tabIndex), [-1, 0, -1, 0]); @@ -715,7 +744,7 @@ suite('AgentsWindowExtensionsWidget', () => { widget.setSearchQuery('tools'); const row = await waitForRow(container, 'Tools,', row => !!installButton(row)); - row.click(); + focusRow(row); await timeout(0); const whileResolving = { disabled: installButton(row)!.classList.contains('disabled'), tabIndex: installButton(row)!.tabIndex }; await installable.complete(true); @@ -829,7 +858,7 @@ suite('AgentsWindowExtensionsWidget', () => { } }); stubSectionServices(instantiationService); - const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container)); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); widget.setVisible(true); const moreActions = async (label: string) => (await waitForRow(container, label)).querySelector('.agents-window-extension-more-actions')!; @@ -857,4 +886,141 @@ suite('AgentsWindowExtensionsWidget', () => { rows: 0, }); }); + + test('opens the page of an extension in place of the list when the user clicks it or presses Enter, and returns to the list with the Back button, the mouse\'s Back button, or Go Back', async () => { + const container = createContainer(); + const tools = anExtension('pub.tools', { displayName: 'Tools', description: 'Adds tools.' }); + const configurationService = new TestConfigurationService({ [MOUSE_BACK_FORWARD_NAVIGATION_SETTING]: true }); + const instantiationService = workbenchInstantiationService(undefined, disposables); + instantiationService.stub(IConfigurationService, configurationService); + // Resolves the context of elements, where Go Back's keybindings return to the list while the page shows. + const contextKeyService = disposables.add(new ContextKeyService(configurationService)); + instantiationService.stub(IContextKeyService, contextKeyService); + instantiationService.stub(IExtensionsWorkbenchService, new class extends mock() { + override readonly local = [tools]; + override readonly onChange = Event.None; + override canSetLanguage() { return false; } + }); + instantiationService.stub(IWorkbenchExtensionEnablementService, new class extends mock() { + override isEnabledEnablementState() { return false; } + override canChangeWorkspaceEnablement() { return true; } + }); + // The pages that the section shows, which the Extensions editor renders like in editor windows. + const pages: string[] = []; + instantiationService.stubInstance(AgentsWindowExtensionPage, new class extends mock() { + override async show(extension: IExtension) { pages.push(`show ${extension.identifier.id}`); } + override clear() { pages.push('clear'); } + override layout() { } + override dispose() { } + }()); + stubSectionServices(instantiationService); + // Like on Windows, where Go Back's keybindings include Alt+Left while the page shows. + instantiationService.stub(IKeybindingService, 'softDispatch', (event: IKeyboardEvent, target: IContextKeyServiceTarget): ResolutionResult => event.altKey && event.keyCode === KeyCode.LeftArrow && contextKeyService.getContext(target).getValue(AgentsWindowExtensionPageContext.key) + ? { kind: ResultKind.KbFound, commandId: AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID, commandArgs: undefined, isBubble: false } + : { kind: ResultKind.NoMatchingKb }); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); + widget.setVisible(true); + const section = container.querySelector('.agents-window-extensions')!; + const title = container.querySelector('.agents-window-extensions-title')!; + const backButton = container.querySelector('.agents-window-extensions-back-button')!; + // The keys that reach Agent Customizations, which stops the keys of most workbench commands. + const modalKeys: string[] = []; + disposables.add(addDisposableListener(container, 'keydown', event => modalKeys.push(`${event.altKey ? 'Alt+' : ''}${event.key}`))); + const pressAlt = (key: 'ArrowLeft' | 'ArrowRight') => { + backButton.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode: key === 'ArrowLeft' ? 37 : 39, altKey: true, bubbles: true, cancelable: true })); + return modalKeys.splice(0); + }; + // The mouse buttons that reach the Agents window's own handling, which moves between sessions. + const windowMouseButtons: string[] = []; + disposables.add(addDisposableListener(container, 'mousedown', event => windowMouseButtons.push(`down ${event.button}`), true)); + disposables.add(addDisposableListener(container, 'mouseup', event => windowMouseButtons.push(`up ${event.button}`), true)); + const pressMouseBack = (target: HTMLElement) => { + target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 3 })); + target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, button: 3 })); + return windowMouseButtons.splice(0); + }; + // Whether the page shows in place of the list, what the page did, what has the focus, and whether Go Back returns to the list. + const state = () => ({ + page: section.classList.contains('shows-extension-page'), + pages: pages.splice(0), + focus: mainWindow.document.activeElement === backButton ? 'Back button' : mainWindow.document.activeElement?.closest('.monaco-list')?.querySelector('.monaco-list-row.focused')?.getAttribute('aria-label')?.split(',')[0], + goBackReturns: contextKeyService.getContext(title).getValue(AgentsWindowExtensionPageContext.key), + }); + + const row = await waitForRow(container, 'Tools,'); + const listMouseBack = pressMouseBack(title); + row.click(); + const clicked = state(); + backButton.click(); + const back = state(); + row.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + const entered = state(); + const mouseBack = { windowMouseButtons: pressMouseBack(title), ...state() }; + await configurationService.setUserConfiguration(MOUSE_BACK_FORWARD_NAVIGATION_SETTING, false); + row.click(); + const mouseBackTurnedOff = { windowMouseButtons: pressMouseBack(title), page: state().page }; + const otherKey = { modalKeys: pressAlt('ArrowRight'), page: state().page }; + const goBackKey = { modalKeys: pressAlt('ArrowLeft'), ...state() }; + const goBackKeyFromList = { modalKeys: pressAlt('ArrowLeft'), page: state().page }; + // Like Go Back's keybindings in the webviews that show the content of the page. + row.click(); + state(); + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand(AGENTS_WINDOW_EXTENSIONS_BACK_COMMAND_ID)!.handler(accessor)); + const goBack = state(); + + assert.deepStrictEqual({ listMouseBack, clicked, back, entered, mouseBack, mouseBackTurnedOff, otherKey, goBackKey, goBackKeyFromList, goBack }, { + // The Agents window keeps moving between sessions while the list shows. + listMouseBack: ['down 3', 'up 3'], + clicked: { page: true, pages: ['show pub.tools'], focus: 'Back button', goBackReturns: true }, + // Like closing the Extensions editor, returns the focus to the extension. + back: { page: false, pages: ['clear'], focus: 'Tools', goBackReturns: false }, + entered: { page: true, pages: ['show pub.tools'], focus: 'Back button', goBackReturns: true }, + mouseBack: { windowMouseButtons: [], page: false, pages: ['clear'], focus: 'Tools', goBackReturns: false }, + mouseBackTurnedOff: { windowMouseButtons: ['down 3', 'up 3'], page: true }, + otherKey: { modalKeys: ['Alt+ArrowRight'], page: true }, + goBackKey: { modalKeys: [], page: false, pages: ['clear'], focus: 'Tools', goBackReturns: false }, + // The keybindings do something else while the list shows. + goBackKeyFromList: { modalKeys: ['Alt+ArrowLeft'], page: false }, + goBack: { page: false, pages: ['clear'], focus: 'Tools', goBackReturns: false }, + }); + }); + + test('shows the page of an installed extension that another section links to, or searches for an extension that isn\'t installed', async () => { + const container = createContainer(); + const tools = anExtension('pub.tools', { displayName: 'Tools' }); + const instantiationService = workbenchInstantiationService(undefined, disposables); + instantiationService.stub(IExtensionsWorkbenchService, new class extends mock() { + override readonly local = [tools]; + override readonly onChange = Event.None; + override canSetLanguage() { return false; } + }); + instantiationService.stub(IWorkbenchExtensionEnablementService, new class extends mock() { + override isEnabledEnablementState() { return false; } + override canChangeWorkspaceEnablement() { return true; } + }); + const pages: string[] = []; + instantiationService.stubInstance(AgentsWindowExtensionPage, new class extends mock() { + override async show(extension: IExtension) { pages.push(`show ${extension.identifier.id}`); } + override clear() { pages.push('clear'); } + override layout() { } + override dispose() { } + }()); + stubSectionServices(instantiationService); + const widget = disposables.add(instantiationService.createInstance(AgentsWindowExtensionsWidget, container, anEditorGroup())); + widget.setVisible(true); + const section = container.querySelector('.agents-window-extensions')!; + const searchInput = container.querySelector('.agents-window-extensions-search input')!; + const state = () => ({ page: section.classList.contains('shows-extension-page'), pages: pages.splice(0), search: searchInput.value }); + + // Extension identifiers are case-insensitive. + widget.showExtension('PUB.Tools'); + const installed = state(); + widget.showExtension('pub.missing'); + const missing = state(); + + assert.deepStrictEqual({ installed, missing }, { + installed: { page: true, pages: ['show pub.tools'], search: '' }, + missing: { page: false, pages: ['clear'], search: 'pub.missing' }, + }); + }); }); diff --git a/src/vs/sessions/contrib/getStarted/browser/getStartedChecklistWidget.ts b/src/vs/sessions/contrib/getStarted/browser/getStartedChecklistWidget.ts index 113191f9787f..1c35f757d448 100644 --- a/src/vs/sessions/contrib/getStarted/browser/getStartedChecklistWidget.ts +++ b/src/vs/sessions/contrib/getStarted/browser/getStartedChecklistWidget.ts @@ -142,7 +142,7 @@ export class GetStartedChecklistWidget extends Disposable { const header = DOM.append(this.domNode, DOM.$('.get-started-header')); const bodyId = `get-started-body-${generateUuid()}`; - this._toggle = DOM.append(header, DOM.$('.get-started-toggle', { role: 'button', tabIndex: 0, 'aria-controls': bodyId })); + this._toggle = DOM.append(header, DOM.$('.get-started-toggle.agent-sessions-interactive.agent-sessions-interactive-list', { role: 'button', tabIndex: 0, 'aria-controls': bodyId })); this._chevron = DOM.append(this._toggle, DOM.$('span.get-started-chevron', { 'aria-hidden': 'true' })); DOM.append(this._toggle, DOM.$('span.get-started-title')).textContent = localize('getStarted.title', "Get started"); this._progress = DOM.append(this._toggle, DOM.$('span.get-started-progress')); @@ -300,7 +300,7 @@ export class GetStartedChecklistWidget extends Disposable { row.classList.toggle('just-completed', this._justCompleted.has(item.id)); const detailsId = `${this._body.id}-${item.id}`; - const header = DOM.append(row, DOM.$('.get-started-item-header', { + const header = DOM.append(row, DOM.$('.get-started-item-header.agent-sessions-interactive.agent-sessions-interactive-list', { role: 'button', tabIndex: index === this._focusedItemIndex ? 0 : -1, 'aria-expanded': String(active), diff --git a/src/vs/sessions/contrib/getStarted/browser/getStartedTourRunner.ts b/src/vs/sessions/contrib/getStarted/browser/getStartedTourRunner.ts index c7cea24a5ca9..43414b24238f 100644 --- a/src/vs/sessions/contrib/getStarted/browser/getStartedTourRunner.ts +++ b/src/vs/sessions/contrib/getStarted/browser/getStartedTourRunner.ts @@ -36,7 +36,7 @@ import { SessionChangesEditorInput } from '../../../../workbench/contrib/session import { IChangesViewService } from '../../../../workbench/contrib/sessions/common/changesViewService.js'; import { VIEW_SESSION_CHANGES_COMMAND_ID } from '../../../../workbench/contrib/sessions/common/changes.js'; import { ISessionChangesService } from '../../../../workbench/services/sessions/common/sessionChangesService.js'; -import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../../../../workbench/contrib/sessions/browser/automationsConstants.js'; +import { AUTOMATIONS_CUSTOM_VIEW_ID, AUTOMATIONS_TOUR_SEEN_KEY } from '../../../../workbench/contrib/sessions/browser/automationsConstants.js'; import { SessionsList } from '../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { SessionsView, SessionsViewId } from '../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; import { GetStartedItemId } from '../common/getStartedChecklist.js'; @@ -105,6 +105,7 @@ export class GetStartedTourRunner extends Disposable { const id = `${SHOW_ME_SCENARIO_PREFIX}${item}`; const scenario: IOnboardingScenario = { id, + seenKey: item === GetStartedItemId.Automation ? AUTOMATIONS_TOUR_SEEN_KEY : undefined, repeatable: true, when: ChatContextKeys.enabled, trigger: { kind: 'command', commandId: id }, diff --git a/src/vs/sessions/contrib/getStarted/browser/media/getStartedChecklist.css b/src/vs/sessions/contrib/getStarted/browser/media/getStartedChecklist.css index bfddc176fe4e..e142fe8beee7 100644 --- a/src/vs/sessions/contrib/getStarted/browser/media/getStartedChecklist.css +++ b/src/vs/sessions/contrib/getStarted/browser/media/getStartedChecklist.css @@ -42,10 +42,6 @@ cursor: pointer; } -.agent-sessions-get-started .get-started-toggle:hover { - background-color: var(--vscode-list-hoverBackground); -} - .agent-sessions-get-started .get-started-chevron { display: flex; flex-shrink: 0; @@ -110,10 +106,6 @@ cursor: pointer; } -.agent-sessions-get-started .get-started-item-header:hover { - background-color: var(--vscode-list-hoverBackground); -} - .agent-sessions-get-started .get-started-item-status { display: flex; flex-shrink: 0; diff --git a/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklist.fixture.ts b/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklist.fixture.ts index 2e8a3d8cd39d..8795370b7526 100644 --- a/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklist.fixture.ts +++ b/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklist.fixture.ts @@ -12,6 +12,7 @@ import { SessionStatus } from '../../../../../workbench/services/sessions/common import { renderSessionsListFixture } from '../../../sessions/test/browser/sessionsListFixtureUtils.js'; import { GET_STARTED_ITEM_IDS, GetStartedChecklistMode, GetStartedItemId } from '../../common/getStartedChecklist.js'; import { GetStartedChecklistWidget } from '../../browser/getStartedChecklistWidget.js'; +import '../../../../browser/media/style.css'; interface IChecklistFixtureState { readonly done?: readonly GetStartedItemId[]; @@ -19,6 +20,7 @@ interface IChecklistFixtureState { readonly finished?: boolean; readonly withoutAutomations?: boolean; readonly width?: number; + readonly interaction?: 'toggleHover' | 'itemHover' | 'itemFocus'; } function createChecklist(instantiationService: IInstantiationService, disposableStore: DisposableStore, state: IChecklistFixtureState): GetStartedChecklistWidget { @@ -38,12 +40,22 @@ function createChecklist(instantiationService: IInstantiationService, disposable }, { focusSessionsList: () => { }, animate: false })); } -function renderChecklist({ container, disposableStore, theme }: ComponentFixtureContext, state: IChecklistFixtureState): void { +function renderChecklist(context: ComponentFixtureContext, state: IChecklistFixtureState): void { + const { container, disposableStore, theme } = context; container.style.width = `${state.width ?? 300}px`; container.style.padding = '4px 0'; container.style.background = 'var(--vscode-agents-background)'; const instantiationService = createEditorServices(disposableStore, { colorTheme: theme }); - container.appendChild(createChecklist(instantiationService, disposableStore, state).domNode); + const widget = createChecklist(instantiationService, disposableStore, state); + container.appendChild(widget.domNode); + const target = state.interaction === 'toggleHover' + ? widget.domNode.querySelector('.get-started-toggle') + : widget.domNode.querySelector('.get-started-item-header'); + if (state.interaction === 'toggleHover' || state.interaction === 'itemHover') { + target?.classList.add('hovered'); + } else if (state.interaction === 'itemFocus' && target) { + context.focus({ focus: () => target.focus() }); + } } /** Renders the checklist where the sessions view places it, around the production sessions list of a new user. */ @@ -84,6 +96,9 @@ export default defineThemedFixtureGroup({ path: 'sessions/getStarted/' }, { Finished: defineComponentFixture({ render: context => renderChecklist(context, { done: GET_STARTED_ITEM_IDS, finished: true }) }), WithoutAutomations: defineComponentFixture({ render: context => renderChecklist(context, { done: [GetStartedItemId.StartSession], withoutAutomations: true }) }), Narrow: defineComponentFixture({ render: context => renderChecklist(context, { done: [GetStartedItemId.StartSession], width: 200 }) }), + ToggleHover: defineComponentFixture({ ...highContrast, render: context => renderChecklist(context, { done: [GetStartedItemId.StartSession], interaction: 'toggleHover' }) }), + ItemHover: defineComponentFixture({ ...highContrast, render: context => renderChecklist(context, { done: [GetStartedItemId.StartSession], interaction: 'itemHover' }) }), + ItemFocus: defineComponentFixture({ ...highContrast, render: context => renderChecklist(context, { done: [GetStartedItemId.StartSession], interaction: 'itemFocus' }) }), AboveSessions: defineComponentFixture({ render: context => renderInSessionsView(context, GetStartedChecklistMode.AboveSessions) }), BelowSessions: defineComponentFixture({ render: context => renderInSessionsView(context, GetStartedChecklistMode.BelowSessions) }), }); diff --git a/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklistWidget.test.ts b/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklistWidget.test.ts index 1db617cdf2cd..fdc44ff0a1fd 100644 --- a/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklistWidget.test.ts +++ b/src/vs/sessions/contrib/getStarted/test/browser/getStartedChecklistWidget.test.ts @@ -40,6 +40,7 @@ suite('GetStartedChecklistWidget', () => { }, { focusSessionsList: () => { }, animate: false })); const headers = () => [...widget.domNode.querySelectorAll('.get-started-item-header')]; return { + widget, headers, /** The item that shows its explanation and Show Me action, or `none`. */ expanded: () => { @@ -51,6 +52,17 @@ suite('GetStartedChecklistWidget', () => { }; } + test('uses the shared list interaction contract for its focusable rows', () => { + const checklist = createChecklist([]); + assert.deepStrictEqual({ + toggle: checklist.widget.domNode.querySelector('.get-started-toggle')?.className, + headers: checklist.headers().map(header => header.className), + }, { + toggle: 'get-started-toggle agent-sessions-interactive agent-sessions-interactive-list', + headers: GET_STARTED_ITEM_IDS.map(() => 'get-started-item-header agent-sessions-interactive agent-sessions-interactive-list'), + }); + }); + test('selecting an item expands it and collapses the one before, and selecting the expanded item collapses it', () => { const checklist = createChecklist([GetStartedItemId.StartSession]); const states: string[] = [checklist.expanded()]; diff --git a/src/vs/sessions/contrib/getStarted/test/browser/getStartedTourRunner.test.ts b/src/vs/sessions/contrib/getStarted/test/browser/getStartedTourRunner.test.ts index ef6018f658fa..5b2f669bd8bc 100644 --- a/src/vs/sessions/contrib/getStarted/test/browser/getStartedTourRunner.test.ts +++ b/src/vs/sessions/contrib/getStarted/test/browser/getStartedTourRunner.test.ts @@ -26,6 +26,7 @@ import { IWorkbenchLayoutService } from '../../../../../workbench/services/layou import { IViewsService } from '../../../../../workbench/services/views/common/viewsService.js'; import { WorkspaceHistoryLoadState } from '../../../../../workbench/services/sessions/common/workspaceSelection.js'; import { ICustomViewService } from '../../../../../workbench/contrib/sessions/browser/customView.js'; +import { AUTOMATIONS_TOUR_SEEN_KEY } from '../../../../../workbench/contrib/sessions/browser/automationsConstants.js'; import { IRecentWorkspace, ISessionsRecentWorkspacesService } from '../../../../../workbench/contrib/sessions/browser/sessionsRecentWorkspacesService.js'; import { IOpenNewSessionResult, ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { ISession, ISessionChangesSummary, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; @@ -72,7 +73,7 @@ suite('GetStartedTourRunner', () => { } /** Runs an item's tour, resolving its steps like the spotlight presentation does when the tour starts. */ - async function runTour(item: GetStartedItemId, scenario: IRunnerScenario) { + async function runTour(item: GetStartedItemId, scenario: IRunnerScenario, onScenario?: (scenario: IOnboardingScenario) => void) { const events: string[] = []; let steps: readonly ISpotlightStep[] = []; const activeSession = observableValue('activeSession', scenario.active && toActiveSession(scenario.active)); @@ -91,6 +92,9 @@ suite('GetStartedTourRunner', () => { instantiationService.stub(IOnboardingScenarioService, new class extends mock() { override async runScenario(id: string): Promise { const registered = onboardingScenarioRegistry.getScenario(id) as IOnboardingScenario | undefined; + if (registered) { + onScenario?.(registered); + } steps = await registered?.presentation.payload.resolveSteps?.() ?? []; for (const step of steps) { await step.onBeforeShow?.(); @@ -253,10 +257,17 @@ suite('GetStartedTourRunner', () => { }); }); - test('the automation tour opens Automations for its templates and create steps', async () => { - assert.deepStrictEqual((await runTour(GetStartedItemId.Automation, { sessions: [] })).events, [ - 'show sessions.customView.automations', - 'show sessions.customView.automations', - ]); + test('the automation tour introduces creation without preventing manual replay', async () => { + let seenKey: string | undefined; + let repeatable: boolean | undefined; + const result = await runTour(GetStartedItemId.Automation, { sessions: [] }, scenario => { + seenKey = scenario.seenKey; + repeatable = scenario.repeatable; + }); + assert.deepStrictEqual({ events: result.events, seenKey, repeatable }, { + events: ['show sessions.customView.automations', 'show sessions.customView.automations'], + seenKey: AUTOMATIONS_TOUR_SEEN_KEY, + repeatable: true, + }); }); }); diff --git a/src/vs/sessions/contrib/layout/browser/baseSessionLayoutController.ts b/src/vs/sessions/contrib/layout/browser/baseSessionLayoutController.ts index 2c12d804d831..109c160aadbd 100644 --- a/src/vs/sessions/contrib/layout/browser/baseSessionLayoutController.ts +++ b/src/vs/sessions/contrib/layout/browser/baseSessionLayoutController.ts @@ -42,7 +42,7 @@ import { IAgentWorkbenchLayoutService } from '../../../browser/workbench.js'; import { Menus, SessionActivityBarGroup } from '../../../../workbench/contrib/sessions/browser/menus.js'; import { AgentsWindowMenus } from '../../../browser/agentsWindowMenus.js'; import { SessionsWelcomeVisibleContext, IsQuickChatSessionContext, DesktopLayoutContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; -import { CustomViewVisibleContext, SessionActivityBarLayoutActionsContext } from '../../../common/agentsWindowContextKeys.js'; +import { CustomViewVisibleContext, SessionActivityBarDockedContext, SessionActivityBarLayoutActionsContext } from '../../../common/agentsWindowContextKeys.js'; import { TOGGLE_SIDE_PANEL_COMMAND_ID } from '../../../../workbench/contrib/sessions/common/sessionCommands.js'; import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; import { ChatWindowLayoutCommandsContext, toggleChatWindowEditorAsSidePanel } from '../../../../workbench/contrib/chatWindow/browser/chatWindowLayoutActions.js'; @@ -52,11 +52,12 @@ import { ISessionChangesService } from '../../../../workbench/contrib/sessionCha import { IChangesViewService } from '../../../../workbench/contrib/sessions/common/changesViewService.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { getMainWindowHost, ISessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; +import { EmptyFileEditorInput } from '../../../../workbench/contrib/sessions/browser/emptyFileEditorInput.js'; import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { ISessionsPartService } from '../../../../workbench/services/sessions/browser/sessionsPartService.js'; import { IChat, ISession, SessionStatus } from '../../../../workbench/services/sessions/common/session.js'; import { ChatLayoutOwnerKeyRegistry } from './chatLayoutOwnerKeys.js'; -import { ISessionEditorWorkingSetOwner, ISessionEditorWorkingSetService } from '../common/sessionEditorWorkingSet.js'; +import { ISessionEditorWorkingSetOwner, ISessionEditorWorkingSetService, IStashedSessionEditors } from '../common/sessionEditorWorkingSet.js'; import { IShownChat } from '../../../../workbench/services/sessions/common/sessionPane.js'; const secondarySidebarToggleClosedIcon = registerIcon('agent-secondary-sidebar-toggle-closed', Codicon.layoutSidebarRightOff, localize('agentSecondarySidebarToggleClosedIcon', "Icon for the sessions secondary sidebar when closed.")); @@ -160,6 +161,9 @@ export abstract class BaseLayoutController extends Disposable { protected readonly _panelViewBySession = new ResourceMap(); protected readonly _viewStateBySession = new ResourceMap(); protected readonly _workingSets = new ResourceMap(); + private readonly _stashLeases = new Set<{ key: URI | undefined }>(); + private readonly _unappliedWorkingSets = new ResourceSet(); + private _currentWorkingSetTarget: IEditorWorkingSetTarget | undefined; private readonly _legacyReferencedWorkingSetIds = new Set(); /** * [B2] Whether the editor part was hidden (e.g. the user closed the Side @@ -330,6 +334,8 @@ export abstract class BaseLayoutController extends Disposable { ? this._register(new ChatLayoutContext(this._layoutService.chatLayoutPresentation, this._mainWindowSession, this._mainWindowChat)) : undefined; + this._register(this._editorWorkingSetService.registerStashedEditorsProvider((session, chatResource) => this._takeStashedEditors(session, chatResource))); + // [B3] Restore persisted state (with one-time legacy migration). this._loadState(); @@ -538,6 +544,7 @@ export abstract class BaseLayoutController extends Disposable { }); let currentWorkingSetTarget = activeSessionForWorkingSet.get(); this._settledEditorWorkingSetKey = activeEditorWorkingSetTarget.get().key; + this._currentWorkingSetTarget = activeEditorWorkingSetTarget.get(); this._editorWorkingSetService.setCurrentOwner(activeEditorWorkingSetTarget.get().owner); // Working sets are always active: browser editors dock in the shared grid @@ -570,6 +577,7 @@ export abstract class BaseLayoutController extends Disposable { })); this._register(runOnChange(activeEditorWorkingSetTarget, (current, previous) => { + this._currentWorkingSetTarget = current; const shouldApply = !!previous.shown || (!!current.key && this._workingSets.has(current.key)); if (!shouldApply) { const previousPending = this._pendingEditorWorkingSetRestore; @@ -624,6 +632,7 @@ export abstract class BaseLayoutController extends Disposable { this._register(this._sessionManagementService.onDidChangeSessions(e => { const archivedSessions = e.changed.filter(session => session.isArchived.read(undefined)); for (const session of [...e.removed, ...archivedSessions]) { + this._forgetStashLeases(session.resource); this._deleteWorkingSet(session.resource); this._viewStateBySession.delete(session.resource); this._editorPartHiddenBySession.delete(session.resource); @@ -796,7 +805,7 @@ export abstract class BaseLayoutController extends Disposable { id: AgentsWindowMenus.TitleBarSessionMenu, group: 'navigation', order: 11, // After Open in VS Code (7), Run Script (8), and Toggle Panel (10) - when: ContextKeyExpr.and(IsAuxiliaryWindowContext.toNegated(), SessionsWelcomeVisibleContext.toNegated(), SessionActivityBarLayoutActionsContext.negate()) + when: ContextKeyExpr.and(IsAuxiliaryWindowContext.toNegated(), SessionsWelcomeVisibleContext.toNegated(), SessionActivityBarLayoutActionsContext.negate(), SessionActivityBarDockedContext.negate()) }, { // Replaces the title bar entry while the Session Activity Bar shows its layout actions. @@ -899,11 +908,19 @@ export abstract class BaseLayoutController extends Disposable { if (isEqual(oldKey, newKey)) { return; } + for (const lease of this._stashLeases) { + if (lease.key && isEqual(lease.key, oldKey)) { + lease.key = newKey; + } + } const workingSet = this._workingSets.get(oldKey); if (workingSet) { const previousAtNewKey = this._workingSets.get(newKey); this._workingSets.set(newKey, workingSet); this._workingSets.delete(oldKey); + if (this._unappliedWorkingSets.delete(oldKey)) { + this._unappliedWorkingSets.add(newKey); + } if (previousAtNewKey && previousAtNewKey.id !== workingSet.id) { this._releaseWorkingSetReference(previousAtNewKey); } @@ -933,6 +950,7 @@ export abstract class BaseLayoutController extends Disposable { private _forgetPeerChatState(keys: readonly URI[]): void { for (const key of keys) { + this._forgetStashLeases(key); this._deleteWorkingSet(key); this._viewStateBySession.delete(key); this._editorPartHiddenBySession.delete(key); @@ -1063,6 +1081,7 @@ export abstract class BaseLayoutController extends Disposable { const resource = URI.parse(entry.sessionResource); if (entry.editorWorkingSet) { this._workingSets.set(resource, entry.editorWorkingSet); + this._unappliedWorkingSets.add(resource); } if (this._isEditorPartVisibilityPerSession && entry.editorPartHidden !== undefined) { this._editorPartHiddenBySession.set(resource, entry.editorPartHidden); @@ -1157,6 +1176,7 @@ export abstract class BaseLayoutController extends Disposable { const resource = URI.parse(entry.sessionResource); if (entry.editorWorkingSet) { this._workingSets.set(resource, entry.editorWorkingSet); + this._unappliedWorkingSets.add(resource); } if (entry.auxiliaryBarState) { this._viewStateBySession.set(resource, { @@ -1282,6 +1302,9 @@ export abstract class BaseLayoutController extends Disposable { if (isStaleChatOwner() || !this._editorWorkingSetService.beginApply(owner)) { return; } + if (sessionResource) { + this._unappliedWorkingSets.delete(sessionResource); + } if (workingSet === 'empty' && sessionResource && isEqual(sessionResource, this._workingSetAdoptingReplacement)) { this._workingSetAdoptingReplacement = undefined; return; @@ -1396,6 +1419,10 @@ export abstract class BaseLayoutController extends Disposable { } private _saveWorkingSet(sessionResource: URI): void { + const mainEditors = this._editorGroupsService.mainPart.groups.flatMap(group => group.editors); + if (this._workingSets.has(sessionResource) && this._unappliedWorkingSets.has(sessionResource) && mainEditors.length > 0 && mainEditors.every(editor => editor instanceof EmptyFileEditorInput)) { + return; + } this._deleteWorkingSet(sessionResource); // Note: the editor part's hidden state is captured eagerly by the [B2] @@ -1407,6 +1434,75 @@ export abstract class BaseLayoutController extends Disposable { const workingSetName = `session-working-set:${sessionResource.toString()}`; const workingSet = this._editorGroupsService.saveWorkingSet(workingSetName); this._workingSets.set(sessionResource, workingSet); + this._unappliedWorkingSets.add(sessionResource); + } + } + + private _takeStashedEditors(session: ISession, chatResource: URI): IStashedSessionEditors | undefined { + const key = this._ownerKeyForChat(session.resource, chatResource, session.mainChat.get().resource); + const workingSet = key && this._workingSets.get(key); + if (!key || !workingSet) { + return undefined; + } + const resolved = this._editorGroupsService.resolveWorkingSet(workingSet); + if (!resolved) { + return undefined; + } + + this._workingSets.delete(key); + const lease: { key: URI | undefined } = { key }; + this._stashLeases.add(lease); + let settled = false; + return { + editors: resolved.editors, + activeEditor: resolved.activeEditor, + accept: () => { + if (!settled) { + settled = true; + this._stashLeases.delete(lease); + resolved.dispose(); + this._releaseWorkingSetReference(workingSet); + } + }, + dispose: () => { + if (settled) { + return; + } + settled = true; + this._stashLeases.delete(lease); + resolved.dispose(); + if (!lease.key || this._workingSets.has(lease.key)) { + this._releaseWorkingSetReference(workingSet); + } else { + this._workingSets.set(lease.key, workingSet); + this._reapplyRolledBackWorkingSet(lease.key); + } + } + }; + } + + private _reapplyRolledBackWorkingSet(key: URI): void { + const target = this._currentWorkingSetTarget; + if (!target?.owner || !isEqual(target.key, key)) { + return; + } + const mainEditors = this._editorGroupsService.mainPart.groups.flatMap(group => group.editors); + if (mainEditors.some(editor => !(editor instanceof EmptyFileEditorInput))) { + return; + } + this._applyPendingEditorWorkingSetRestore({ + key, + owner: target.owner, + isInitialRestore: false, + restore: this._editorWorkingSetService.beginRestore(target.owner), + }); + } + + private _forgetStashLeases(key: URI): void { + for (const lease of this._stashLeases) { + if (lease.key && isEqual(lease.key, key)) { + lease.key = undefined; + } } } diff --git a/src/vs/sessions/contrib/layout/browser/sessions.mobile.layout.contribution.ts b/src/vs/sessions/contrib/layout/browser/sessions.mobile.layout.contribution.ts new file mode 100644 index 000000000000..5645cdc48d58 --- /dev/null +++ b/src/vs/sessions/contrib/layout/browser/sessions.mobile.layout.contribution.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 { Disposable } from '../../../../base/common/lifecycle.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { ISessionEditorWorkingSetService, SessionEditorWorkingSetService } from '../common/sessionEditorWorkingSet.js'; +import { MobileLayoutController } from './mobileSessionLayoutController.js'; + +registerSingleton(ISessionEditorWorkingSetService, SessionEditorWorkingSetService, InstantiationType.Delayed); + +/** + * Layout contribution of the mobile web entry point. The phone presentation is + * declared by the entry point, so this always installs the + * {@link MobileLayoutController}; there is no runtime platform or viewport check. + */ +class MobileSessionsLayoutContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.mobileSessionsLayoutContribution'; + + constructor( + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + + this._register(instantiationService.createInstance(MobileLayoutController)); + } +} + +registerWorkbenchContribution2(MobileSessionsLayoutContribution.ID, MobileSessionsLayoutContribution, WorkbenchPhase.BlockRestore); diff --git a/src/vs/sessions/contrib/layout/common/sessionEditorWorkingSet.ts b/src/vs/sessions/contrib/layout/common/sessionEditorWorkingSet.ts index c612492d4c1b..8ed37b9b2324 100644 --- a/src/vs/sessions/contrib/layout/common/sessionEditorWorkingSet.ts +++ b/src/vs/sessions/contrib/layout/common/sessionEditorWorkingSet.ts @@ -7,6 +7,7 @@ import { IDisposable, toDisposable } from '../../../../base/common/lifecycle.js' import { IObservable, observableValue } from '../../../../base/common/observable.js'; import { isEqual } from '../../../../base/common/resources.js'; import { URI } from '../../../../base/common/uri.js'; +import { ISession } from '../../../../workbench/services/sessions/common/session.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { EditorInput } from '../../../../workbench/common/editor/editorInput.js'; @@ -37,6 +38,20 @@ export interface ISessionEditorWorkingSetRestoreState { readonly applying: boolean; } +/** + * The editors a session left behind in its saved editor working set, while another session + * is shown. The working set stays saved until {@link accept} is called. + */ +export interface IStashedSessionEditors extends IDisposable { + readonly editors: readonly EditorInput[]; + readonly activeEditor: EditorInput | undefined; + + /** The editors moved on to their new place: deletes the saved working set. Disposing afterwards keeps them open. */ + accept(): void; +} + +export type StashedSessionEditorsProvider = (session: ISession, chatResource: URI) => IStashedSessionEditors | undefined; + export const ISessionEditorWorkingSetService = createDecorator('sessionEditorWorkingSetService'); /** @@ -72,6 +87,14 @@ export interface ISessionEditorWorkingSetService { * may overlap; the owner of the most recent one is reported once all of them settle. */ beginRestore(owner: ISessionEditorWorkingSetOwner | undefined): IDisposable; + + registerStashedEditorsProvider(provider: StashedSessionEditorsProvider): IDisposable; + + /** + * Resolves the editors the session has saved in its editor working set, without showing them. + * Disposing the result without accepting it discards the resolved editors and keeps the working set. + */ + takeEditorsFor(session: ISession, chatResource: URI): IStashedSessionEditors | undefined; } export class SessionEditorWorkingSetService implements ISessionEditorWorkingSetService { @@ -83,6 +106,7 @@ export class SessionEditorWorkingSetService implements ISessionEditorWorkingSetS private _pendingRestores = 0; private readonly _editorsToRetain = new Set(); + private _stashedEditorsProvider: StashedSessionEditorsProvider | undefined; setCurrentOwner(owner: ISessionEditorWorkingSetOwner | undefined): void { this._restoreState.set(Object.freeze({ owner, restoring: this._pendingRestores !== 0, applying: false }), undefined); @@ -97,6 +121,19 @@ export class SessionEditorWorkingSetService implements ISessionEditorWorkingSetS return this._editorsToRetain.has(input); } + registerStashedEditorsProvider(provider: StashedSessionEditorsProvider): IDisposable { + this._stashedEditorsProvider = provider; + return toDisposable(() => { + if (this._stashedEditorsProvider === provider) { + this._stashedEditorsProvider = undefined; + } + }); + } + + takeEditorsFor(session: ISession, chatResource: URI): IStashedSessionEditors | undefined { + return this._stashedEditorsProvider?.(session, chatResource); + } + beginApply(owner: ISessionEditorWorkingSetOwner | undefined): boolean { const state = this._restoreState.get(); if (!state.restoring || !editorWorkingSetOwnersEqual(state.owner, owner)) { diff --git a/src/vs/sessions/contrib/layout/test/browser/baseSessionLayoutController.test.ts b/src/vs/sessions/contrib/layout/test/browser/baseSessionLayoutController.test.ts index 13d7896b75d6..5ca92e073b21 100644 --- a/src/vs/sessions/contrib/layout/test/browser/baseSessionLayoutController.test.ts +++ b/src/vs/sessions/contrib/layout/test/browser/baseSessionLayoutController.test.ts @@ -14,10 +14,12 @@ import { StorageScope, WillSaveStateReason } from '../../../../../platform/stora import { Parts } from '../../../../../workbench/services/layout/browser/layoutService.js'; import { ViewContainerLocation } from '../../../../../workbench/common/views.js'; import { TERMINAL_VIEW_ID } from '../../../../../workbench/contrib/terminal/common/terminal.js'; +import { EmptyFileEditorInput } from '../../../../../workbench/contrib/sessions/browser/emptyFileEditorInput.js'; +import { IEditorGroupsService } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; import { BaseLayoutController } from '../../browser/baseSessionLayoutController.js'; import { IMenuItem, isIMenuItem, MenuId, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; import { ContextKeyValue, IContext } from '../../../../../platform/contextkey/common/contextkey.js'; -import { SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING, SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; import { AgentsWindowMenus } from '../../../../browser/agentsWindowMenus.js'; import { SessionEditorWorkingSetService } from '../../common/sessionEditorWorkingSet.js'; @@ -25,7 +27,7 @@ import { SessionStatus } from '../../../../../workbench/services/sessions/common import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { constObservable, observableValue } from '../../../../../base/common/observable.js'; import { OS } from '../../../../../base/common/platform.js'; -import { mock } from '../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { KeybindingResolver, ResultKind } from '../../../../../platform/keybinding/common/keybindingResolver.js'; @@ -56,6 +58,8 @@ class TestRevealEmptyWorkingSetLayoutController extends BaseLayoutController { protected override _shouldHideEditorPartOnApply(editorPartHidden: boolean): boolean { return editorPartHidden; } } +const noOtherEditorParts = upcastPartial({ parts: [] }); + suite('BaseLayoutController', () => { const store = new DisposableStore(); @@ -144,6 +148,9 @@ suite('BaseLayoutController', () => { const scenarios: Record> = { layoutActions: base, layoutActionsOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING}`]: false }, + docked: { ...base, [`config.${SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING}`]: false, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, + dockedActivityBarOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_SETTING}`]: false, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, + dockedEditorMaximized: { ...base, editorMaximized: true, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, activityBarOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_SETTING}`]: false }, // The activity bar is hidden with the Sessions part while the editor is maximized, and in the phone layout. editorMaximized: { ...base, editorMaximized: true }, @@ -162,6 +169,9 @@ suite('BaseLayoutController', () => { placement: { layoutActions: ['activityBar'], layoutActionsOff: ['titleBar'], + docked: [], + dockedActivityBarOff: ['titleBar'], + dockedEditorMaximized: ['titleBar'], activityBarOff: ['titleBar'], editorMaximized: ['titleBar'], phoneLayout: ['titleBar'], @@ -489,6 +499,236 @@ suite('BaseLayoutController', () => { assert.deepStrictEqual(harness.activeGroupEditors.map(e => e.resource?.toString()), [regular.toString()]); }); + test('[B2] switching away from an applied session whose files moved to another window saves the placeholder-only set instead of keeping the stale one', async () => { + const workspaceFolders = [{ uri: URI.file('/repo') }]; + createController({ useModal: 'some', workspaceFolders }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.visibleEditorsList = [{}]; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + + const placeholder = store.add(new EmptyFileEditorInput(undefined, harness.layoutService, noOtherEditorParts)); + harness.activeGroupEditors = [placeholder]; + harness.visibleEditorsList = [placeholder, store.add(new TestStubEditorInput(URI.file('/repo/in-a-chat-window.ts')))]; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + + assert.deepStrictEqual(harness.saveWorkingSetCalls, [`session-working-set:${sessionA.resource.toString()}`, `session-working-set:${sessionB.resource.toString()}`, `session-working-set:${sessionA.resource.toString()}`]); + assert.strictEqual(harness.editorWorkingSetService.takeEditorsFor(sessionA, sessionA.mainChat.get().resource)?.editors.length, 0); + }); + + test('[B2] closing every file of a restored session while the empty-file placeholder remains saves the empty set when switching away', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + + const placeholder = store.add(new EmptyFileEditorInput(undefined, harness.layoutService, noOtherEditorParts)); + harness.activeGroupEditors = [placeholder]; + harness.visibleEditorsList = [placeholder]; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + + assert.deepStrictEqual(harness.activeGroupEditors.map(editor => editor.resource?.path), []); + }); + + test('a stash whose handoff fails while its session is focused again is applied to the main part', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + + const handle = harness.editorWorkingSetService.takeEditorsFor(sessionA, sessionA.mainChat.get().resource); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + const whileLeased = harness.activeGroupEditors.map(editor => editor.resource?.path); + handle?.dispose(); + await timeout(0); + + assert.deepStrictEqual({ whileLeased, afterFailure: harness.activeGroupEditors.map(editor => editor.resource?.path) }, { whileLeased: [], afterFailure: ['/repo/util.ts'] }); + }); + + test('takes the editors of a session whose working set is saved, which stay saved until the taker has them', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + + const taken = harness.editorWorkingSetService.takeEditorsFor(sessionA, sessionA.mainChat.get().resource); + const beforeAccept = harness.deleteWorkingSetCalls.length; + taken?.accept(); + + assert.deepStrictEqual({ + editors: taken?.editors.map(editor => editor.resource?.path), + deletedBeforeAccept: beforeAccept, + deletedAfterAccept: harness.deleteWorkingSetCalls, + takenAgain: harness.editorWorkingSetService.takeEditorsFor(sessionA, sessionA.mainChat.get().resource), + ofTheActiveSession: harness.editorWorkingSetService.takeEditorsFor(sessionB, sessionB.mainChat.get().resource), + }, { + editors: ['/repo/util.ts'], + deletedBeforeAccept: 0, + deletedAfterAccept: [`session-working-set:${sessionA.resource.toString()}`], + takenAgain: undefined, + ofTheActiveSession: undefined, + }); + }); + + test('hands a session\'s stashed editors to one taker at a time until it accepts or disposes', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + const chat = sessionA.mainChat.get().resource; + + const first = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + const whileTaken = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + first?.dispose(); + const afterDispose = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + afterDispose?.accept(); + afterDispose?.dispose(); + + assert.deepStrictEqual({ + first: first?.editors.length, + whileTaken, + afterDispose: afterDispose?.editors.length, + afterAccept: harness.editorWorkingSetService.takeEditorsFor(sessionA, chat), + }, { first: 1, whileTaken: undefined, afterDispose: 1, afterAccept: undefined }); + }); + + test('accepting a stash disposes the resolved editors the window did not adopt', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + + const handle = harness.editorWorkingSetService.takeEditorsFor(sessionA, sessionA.mainChat.get().resource); + handle?.accept(); + + assert.deepStrictEqual(handle?.editors.map(editor => editor.isDisposed()), [true]); + }); + + test('a stash taken for a window is not applied to the main part meanwhile, and the old handle never removes a newer stash', async () => { + createController({ useModal: 'some', workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + const chat = sessionA.mainChat.get().resource; + + const handle = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/newer.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + handle?.accept(); + handle?.dispose(); + const newer = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + + assert.deepStrictEqual({ + taken: handle?.editors.length, + newer: newer?.editors.map(editor => editor.resource?.path), + }, { taken: 1, newer: ['/repo/newer.ts'] }); + newer?.dispose(); + }); + + test('a stash whose handoff fails after its session was removed is not resurrected', async () => { + createController({ useModal: 'some', chatLayoutMode: 'chat', desktopLayout: true, workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + const chat = sessionA.mainChat.get().resource; + + const handle = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + harness.onDidChangeSessions.fire({ added: [], removed: [sessionA], changed: [] }); + handle?.dispose(); + + assert.deepStrictEqual({ + taken: handle?.editors.length, + afterDispose: harness.editorWorkingSetService.takeEditorsFor(sessionA, chat), + }, { taken: 1, afterDispose: undefined }); + }); + + test('a stash whose handoff fails after its session was replaced is restored under the replacement', async () => { + createController({ useModal: 'some', chatLayoutMode: 'chat', desktopLayout: true, workspaceFolders: [{ uri: URI.file('/repo') }] }); + + const sessionA = makeSession(URI.parse('session:a')); + const replacement = makeSession(URI.parse('session:a2')); + const sessionB = makeSession(URI.parse('session:b')); + harness.activeSessionObs.set(sessionA, undefined); + await timeout(0); + harness.activeGroupEditors = [store.add(new TestStubEditorInput(URI.file('/repo/util.ts')))]; + harness.visibleEditorsList = harness.activeGroupEditors; + harness.activeSessionObs.set(sessionB, undefined); + await timeout(0); + const chat = sessionA.mainChat.get().resource; + + const handle = harness.editorWorkingSetService.takeEditorsFor(sessionA, chat); + harness.onDidReplaceSession.fire({ from: sessionA, to: replacement }); + handle?.dispose(); + const restored = harness.editorWorkingSetService.takeEditorsFor(replacement, replacement.mainChat.get().resource); + + assert.deepStrictEqual({ + taken: handle?.editors.length, + restored: restored?.editors.map(editor => editor.resource?.path), + old: harness.editorWorkingSetService.takeEditorsFor(sessionA, chat), + }, { taken: 1, restored: ['/repo/util.ts'], old: undefined }); + restored?.dispose(); + }); + test('[B2] switching away keeps an untitled editor bound to a file path that has content and restores it on return', async () => { const workspaceFolders = [{ uri: URI.file('/repo') }]; createController({ useModal: 'some', workspaceFolders }); diff --git a/src/vs/sessions/contrib/layout/test/browser/desktopLayoutController.test.ts b/src/vs/sessions/contrib/layout/test/browser/desktopLayoutController.test.ts index c9788b46af2d..be42c992640a 100644 --- a/src/vs/sessions/contrib/layout/test/browser/desktopLayoutController.test.ts +++ b/src/vs/sessions/contrib/layout/test/browser/desktopLayoutController.test.ts @@ -47,6 +47,7 @@ import { ChangesViewPane } from '../../../../../workbench/contrib/sessionChanges import { REVEAL_CI_CHECKS_COMMAND_ID } from '../../../../../workbench/contrib/sessions/browser/fixCIChecks.js'; import { GitHubCheckConclusion, GitHubCheckStatus } from '../../../../../workbench/contrib/sessions/common/github/types.js'; import '../../../changes/browser/changesActions.js'; +import '../../../changes/browser/changesView.contribution.js'; import { SESSIONS_FILES_CONTAINER_ID } from '../../../files/browser/files.contribution.js'; import { NewChangesTabAction, NewFileTabAction } from '../../../editor/browser/addTabActions.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; diff --git a/src/vs/sessions/contrib/layout/test/browser/layoutControllerTestUtils.ts b/src/vs/sessions/contrib/layout/test/browser/layoutControllerTestUtils.ts index bba340387146..36e9085dbf72 100644 --- a/src/vs/sessions/contrib/layout/test/browser/layoutControllerTestUtils.ts +++ b/src/vs/sessions/contrib/layout/test/browser/layoutControllerTestUtils.ts @@ -846,6 +846,14 @@ export function createTestHarness(store: DisposableStore, options: ICreateOption workingSetContents.set(name, { resources, activeResource: harness.activeEditorInput?.resource }); return { id: name, name }; } + override resolveWorkingSet(workingSet: IEditorWorkingSet) { + const contents = workingSetContents.get(workingSet.id); + if (!contents) { + return undefined; + } + const editors = contents.resources.map(resource => store.add(new TestStubEditorInput(resource))); + return { editors, activeEditor: editors.find(editor => isEqual(editor.resource, contents.activeResource)), dispose: () => editors.forEach(editor => editor.dispose()) }; + } override async applyWorkingSet(workingSet: IEditorWorkingSet | 'empty') { harness.applyWorkingSetCalls.push(workingSet); const contents = workingSet === 'empty' ? { resources: [], activeResource: undefined } : workingSetContents.get(workingSet.id); diff --git a/src/vs/sessions/contrib/mobile/browser/media/mobileQuickInput.css b/src/vs/sessions/contrib/mobile/browser/media/mobileQuickInput.css new file mode 100644 index 000000000000..1ee3efa81fce --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/media/mobileQuickInput.css @@ -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. + *--------------------------------------------------------------------------------------------*/ + +/* Phone input sheet: a prompt, a 48px field, and one filled action. */ + +.mobile-content-sheet-body .mobile-quick-input-prompt { + margin: 0 0 var(--vscode-spacing-size120); + padding: 0 var(--vscode-spacing-size160); + font-size: var(--vscode-fontSize-body2); + color: var(--vscode-descriptionForeground); +} + +.mobile-content-sheet-body .mobile-quick-input-field { + display: block; + width: calc(100% - 2 * var(--vscode-spacing-size160)); + margin: 0 var(--vscode-spacing-size160); + min-height: 48px; + padding: 0 var(--vscode-spacing-size160); + box-sizing: border-box; + border-radius: var(--vscode-cornerRadius-small); + border: 1px solid var(--vscode-input-border, transparent); + background: var(--vscode-input-background); + color: var(--vscode-input-foreground); + font: inherit; + font-size: var(--vscode-fontSize-body1); +} + +.mobile-content-sheet-body .mobile-quick-input-field:focus { + outline: none; + border-color: var(--vscode-focusBorder); +} + +.mobile-content-sheet-body .mobile-quick-input-validation { + display: none; + margin: var(--vscode-spacing-size80) var(--vscode-spacing-size160) 0; + font-size: var(--vscode-fontSize-label1); + color: var(--vscode-inputValidation-errorForeground, var(--vscode-errorForeground)); +} + +.mobile-content-sheet-body .mobile-quick-input-validation.visible { + display: block; +} + +.mobile-content-sheet-body .mobile-quick-input-submit { + display: block; + width: calc(100% - 2 * var(--vscode-spacing-size160)); + margin: var(--vscode-spacing-size160) var(--vscode-spacing-size160) calc(var(--vscode-spacing-size160) + env(safe-area-inset-bottom)); + min-height: 48px; + border: none; + border-radius: var(--vscode-cornerRadius-small); + background: var(--vscode-button-background); + color: var(--vscode-button-foreground); + font: inherit; + font-size: var(--vscode-fontSize-body1); + font-weight: var(--vscode-fontWeight-semiBold); + cursor: pointer; +} + +.mobile-content-sheet-body .mobile-quick-input-submit:active { + background: var(--vscode-button-hoverBackground); +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts b/src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts new file mode 100644 index 000000000000..c4977a56f1da --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobile.contribution.ts @@ -0,0 +1,87 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IActionWidgetService } from '../../../../platform/actionWidget/browser/actionWidget.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; +import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { Extensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; +import { Registry } from '../../../../platform/registry/common/platform.js'; +import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { IAgentHostTerminalService } from '../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; +import { IAquariumService } from '../../../../workbench/contrib/sessions/browser/aquarium.js'; +import { IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { IScreenshotToolService } from '../../../../workbench/contrib/screenshotTool/browser/screenshotTool.js'; +import { IWorktreeSuggestionService } from '../../../../workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.js'; +import { IPinnedCanvasService } from '../../../../workbench/contrib/sessions/browser/pinnedCanvases.js'; +import { IWindowCanvasService } from '../../../../workbench/contrib/sessions/browser/windowCanvas.js'; +import { WindowCanvasService } from '../../../../workbench/contrib/sessions/browser/windowCanvasService.js'; +import { MobileActionWidgetService } from './mobileActionWidgetService.js'; +import { MobileContextMenuService } from './mobileContextMenuService.js'; +import { MobileKeybindingService } from './mobileKeybindingService.js'; +import { MobileNullAgentHostTerminalService } from './mobileNullAgentHostTerminalService.js'; +import { MobileNullAquariumService } from './mobileNullAquariumService.js'; +import { MobileNullChatWindowService } from './mobileNullChatWindowService.js'; +import { MobileNullScreenshotToolService } from './mobileNullScreenshotToolService.js'; +import { MobileNullPinnedCanvasService } from './mobileNullPinnedCanvasService.js'; +import { MobileNullWorktreeSuggestionService } from './mobileNullWorktreeSuggestionService.js'; +import { MobileQuickInputService } from './mobileQuickInputService.js'; +import { ISessionsListPresentation } from '../../../../workbench/contrib/sessions/browser/sessionsListPresentation.js'; +import { ISessionRepositoryPicker } from '../../../../workbench/contrib/sessions/browser/sessionRepositoryPicker.js'; +import { MobileSessionsListPresentation } from './mobileSessionsListPresentation.js'; +import { MobileRepositoryPicker } from './mobileRepositoryPicker.js'; +import { IChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; +import { MobileChatViewFactory } from './mobileChatViewFactory.js'; +import { IChatEditPresentationService } from '../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatEditPresentation.js'; +import { MobileChatEditPresenter } from './mobileChatEditPresenter.js'; +import { SessionsChatAccessibilityHelp } from '../../chat/browser/sessionsChatAccessibilityHelp.js'; +import './mobileClipboardImageContext.js'; +import './mobileBackgroundNotifier.js'; +import { mobileConfigurationDefaults } from './mobileConfigurationDefaults.js'; + +// Phone design language. Imported here, at the end of the mobile entry point, +// so these stylesheets are evaluated after every shared stylesheet: a phone rule +// then wins on source order at equal specificity instead of needing to outrank +// the desktop rule it adapts. The order within the three is page → chat → drawer. +import '../../../browser/mobile/media/mobileWorkbench.css'; +import '../../../browser/mobile/media/mobileChat.css'; +import '../../../browser/mobile/media/mobileDrawer.css'; + +// Phone presentations of shared services. Imported by the mobile entry point +// after every other registration, so these descriptors win when the service +// collection is populated (the last registration for an id is used). + +Registry.as(Extensions.Configuration).registerDefaultConfigurations([mobileConfigurationDefaults]); + +// Context menus are bottom action sheets. +registerSingleton(IContextMenuService, MobileContextMenuService, InstantiationType.Delayed); + +// Anchored action lists (configuration chips, mode/model/branch pickers) are +// bottom sheets. This is the service every such picker opens its popup through, +// so no caller can show the desktop widget on the phone. +registerSingleton(IActionWidgetService, MobileActionWidgetService, InstantiationType.Delayed); + +// Simple picks and prompts are bottom sheets; quick access keeps the shared controller. +registerSingleton(IQuickInputService, MobileQuickInputService, InstantiationType.Delayed); + +// Shortcuts still work with a paired keyboard, but labels stop advertising them. +registerSingleton(IKeybindingService, MobileKeybindingService, InstantiationType.Eager); + +// The phone bundle ships no terminal. See MobileNullAgentHostTerminalService. +registerSingleton(IAgentHostTerminalService, MobileNullAgentHostTerminalService, InstantiationType.Delayed); + +// The aquarium easter egg does not exist on the phone. See MobileNullAquariumService. +registerSingleton(IAquariumService, MobileNullAquariumService, InstantiationType.Delayed); +registerSingleton(IChatWindowService, MobileNullChatWindowService, InstantiationType.Delayed); +registerSingleton(IScreenshotToolService, MobileNullScreenshotToolService, InstantiationType.Delayed); +registerSingleton(IWorktreeSuggestionService, MobileNullWorktreeSuggestionService, InstantiationType.Delayed); +registerSingleton(IPinnedCanvasService, MobileNullPinnedCanvasService, InstantiationType.Delayed); +registerSingleton(IWindowCanvasService, WindowCanvasService, InstantiationType.Delayed); +registerSingleton(ISessionsListPresentation, MobileSessionsListPresentation, InstantiationType.Delayed); +registerSingleton(ISessionRepositoryPicker, MobileRepositoryPicker, InstantiationType.Delayed); +registerSingleton(IChatViewFactory, MobileChatViewFactory, InstantiationType.Delayed); +registerSingleton(IChatEditPresentationService, MobileChatEditPresenter, InstantiationType.Delayed); +AccessibleViewRegistry.register(new SessionsChatAccessibilityHelp(undefined, false)); diff --git a/src/vs/sessions/contrib/mobile/browser/mobileActionWidgetService.ts b/src/vs/sessions/contrib/mobile/browser/mobileActionWidgetService.ts new file mode 100644 index 000000000000..1362beefc113 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileActionWidgetService.ts @@ -0,0 +1,247 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IAnchor } from '../../../../base/browser/ui/contextview/contextview.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { IListAccessibilityProvider } from '../../../../base/browser/ui/list/listWidget.js'; +import { StandardMouseEvent } from '../../../../base/browser/mouseEvent.js'; +import { IAction } from '../../../../base/common/actions.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../base/common/lifecycle.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { ActionListItemKind, IActionListDelegate, IActionListItem, IActionListOptions, IActionListUpdateOptions } from '../../../../platform/actionWidget/browser/actionList.js'; +import { IActionWidgetService } from '../../../../platform/actionWidget/browser/actionWidget.js'; +import { ILayoutService } from '../../../../platform/layout/browser/layoutService.js'; +import { IMobilePickerSheetItem, IMobilePickerSheetItemsChangeEvent, showMobilePickerSheet } from '../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; + +/** What the phone needs to know about a shown widget until it closes. */ +interface IShownWidget { + readonly delegate: IActionListDelegate; + readonly dismiss: CancellationTokenSource; + readonly updateItems: (items: readonly IActionListItem[], focusItemId?: string, options?: IActionListUpdateOptions) => void; + hidden: boolean; + setFilter?: (value: string, focusItemId?: string) => void; +} + +/** + * Phone presentation of {@link IActionWidgetService}: every anchored action + * list — session configuration chips, mode and model pickers, branch and + * repository pickers — is shown as a bottom sheet instead of a popup anchored + * to a desktop control. + * + * Callers do not change: items, the delegate's `onSelect`/`onHide`/`onFilter` + * callbacks, and the convention of reading the checked state from the item + * payload are the same as the desktop list. Headers and separators become + * sheet sections, the optional filter becomes the sheet's search field, and + * footer actions become a trailing section of rows. Anchors are ignored: a + * sheet always comes from the bottom edge. + */ +export class MobileActionWidgetService extends Disposable implements IActionWidgetService { + + declare readonly _serviceBrand: undefined; + + private _shown: IShownWidget | undefined; + private readonly _shownStore = this._register(new MutableDisposable()); + + constructor( + @ILayoutService private readonly layoutService: ILayoutService, + ) { + super(); + } + + get isVisible(): boolean { + return !!this._shown; + } + + show( + _user: string, + _supportsPreview: boolean, + items: readonly IActionListItem[], + delegate: IActionListDelegate, + _anchor: HTMLElement | StandardMouseEvent | IAnchor, + _container: HTMLElement | undefined, + actionBarActions?: readonly IAction[], + accessibilityProvider?: Partial>>, + listOptions?: IActionListOptions, + ): void { + // One sheet at a time: a new request replaces the open one, like the + // desktop widget replaces its popup. + this.hide(true); + + const byId = new Map>(); + const footerById = new Map(); + const footerRows: IMobilePickerSheetItem[] = []; + let currentItems = items; + const toRows = (source: readonly IActionListItem[]): IMobilePickerSheetItem[] => { + byId.clear(); + const rows: IMobilePickerSheetItem[] = []; + let pendingSection: string | undefined; + for (const item of source) { + if (item.kind === ActionListItemKind.Header) { + pendingSection = item.label ?? item.group?.title ?? ''; + continue; + } + if (item.kind === ActionListItemKind.Separator) { + pendingSection = ''; + continue; + } + const payload = item.item as { id?: string; checked?: boolean } | undefined; + const id = typeof payload?.id === 'string' ? `action-widget-item-${payload.id}` : `action-widget-row-${byId.size}`; + byId.set(id, item); + const toggle = item.standaloneToggle ?? item.inlineToggle; + rows.push({ + id, + label: item.label ?? toggle?.label ?? '', + badge: item.badge, + description: item.detail ?? (typeof item.description === 'string' ? item.description : undefined), + icon: item.hideIcon ? undefined : item.group?.icon, + checked: toggle ? toggle.checked : payload?.checked, + disabled: item.disabled || toggle?.disabled, + sectionTitle: pendingSection, + }); + pendingSection = undefined; + } + return [...rows, ...footerRows]; + }; + + for (const action of actionBarActions ?? []) { + if (!action.enabled) { + continue; + } + const id = `action-widget-footer-${footerById.size}`; + footerById.set(id, action); + footerRows.push({ id, label: action.label, sectionTitle: footerById.size === 1 ? '' : undefined }); + } + const rows = toRows(currentItems); + if (rows.length === 0) { + delegate.onHide(true); + return; + } + + const store = new DisposableStore(); + this._shownStore.value = store; + const itemsChanged = store.add(new Emitter()); + const shown: IShownWidget = { + delegate: delegate as IActionListDelegate, + dismiss: store.add(new CancellationTokenSource()), + hidden: false, + updateItems: (nextItems, focusItemId, options) => { + currentItems = nextItems as readonly IActionListItem[]; + itemsChanged.fire({ + focusItemId: focusItemId ? `action-widget-item-${focusItemId}` : undefined, + focusFilter: options?.focusFilter, + }); + }, + }; + this._shown = shown; + const ariaLabel = accessibilityProvider?.getWidgetAriaLabel?.(); + const title = typeof ariaLabel === 'string' ? ariaLabel : (ariaLabel?.get() ?? localize('mobileActionWidget.title', "Options")); + const onFilter = delegate.onFilter; + const search = onFilter && listOptions?.showFilter + ? { + placeholder: listOptions.filterPlaceholder ?? localize('mobileActionWidget.filter', "Filter"), + replaceStaticItems: true, + onDidCreateFilter: (setFilter: (query: string, focusItemId?: string) => void) => { + shown.setFilter = (query, focusItemId) => setFilter(query, focusItemId ? `action-widget-item-${focusItemId}` : undefined); + if (listOptions.initialFilterValue || listOptions.initialFocusItemId) { + shown.setFilter(listOptions.initialFilterValue ?? '', listOptions.initialFocusItemId); + } + }, + loadItems: async (query: string, token: CancellationToken) => { + if (!query.trim()) { + return toRows(currentItems); + } + const filtered = await onFilter(query, token); + return token.isCancellationRequested ? [] : toRows(filtered); + }, + } + : undefined; + + showMobilePickerSheet(this.layoutService.mainContainer, title, rows, { + doneLabel: localize('mobileActionWidget.cancel', "Cancel"), + search, + dismissToken: shown.dismiss.token, + initialFocusItemId: listOptions?.initialFocusItemId ? `action-widget-item-${listOptions.initialFocusItemId}` : undefined, + itemProvider: { onDidChange: itemsChanged.event, getItems: () => toRows(currentItems) }, + }).then(pickedId => { + if (this._shown === shown) { + this._shown = undefined; + } + store.dispose(); + // A programmatic `hide()` already told the delegate; a pick that + // raced with it must not apply. + if (shown.hidden) { + return; + } + const picked = pickedId ? byId.get(pickedId) : undefined; + const footer = pickedId ? footerById.get(pickedId) : undefined; + if (picked) { + const toggle = picked.standaloneToggle ?? picked.inlineToggle; + if (toggle) { + toggle.onChange(!toggle.checked); + } else if (picked.item !== undefined) { + delegate.onSelect(picked.item); + } + } + // The delegate may have hidden the widget itself from `onSelect`. + if (!shown.hidden) { + shown.hidden = true; + delegate.onHide(!picked && !footer); + } + if (footer) { + Promise.resolve(footer.run()).catch(onUnexpectedError); + } + }, error => { + if (this._shown === shown) { + this._shown = undefined; + } + store.dispose(); + if (!shown.hidden) { + shown.hidden = true; + delegate.onHide(true); + } + onUnexpectedError(error); + }); + } + + updateItems(items: readonly IActionListItem[], focusItemId?: string, options?: IActionListUpdateOptions): void { + this._shown?.updateItems(items, focusItemId, options); + } + + getFocusedElement(): IActionListItem | undefined { + return undefined; + } + + focusItemById(_itemId: string): void { } + + collapseSection(): void { } + + expandSection(): void { } + + setFilter(value: string, focusItemId?: string): void { + this._shown?.setFilter?.(value, focusItemId); + } + + hide(didCancel?: boolean): void { + const shown = this._shown; + if (!shown || shown.hidden) { + return; + } + // The delegate hears about the hide exactly once, and the sheet closes + // even when the owner hides it programmatically (e.g. session switch). + shown.hidden = true; + this._shown = undefined; + shown.dismiss.cancel(); + this._shownStore.clear(); + shown.delegate.onHide(didCancel); + } + + override dispose(): void { + this.hide(true); + super.dispose(); + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileBackgroundNotifier.ts b/src/vs/sessions/contrib/mobile/browser/mobileBackgroundNotifier.ts new file mode 100644 index 000000000000..28be89f48daf --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileBackgroundNotifier.ts @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { addDisposableListener } from '../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../base/browser/window.js'; +import { RunOnceScheduler } from '../../../../base/common/async.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Disposable, DisposableMap, DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; +import { autorunDelta } from '../../../../base/common/observable.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { ISession, SessionStatus } from '../../../../workbench/services/sessions/common/session.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; + +/** Swallows the brief idle gap between a turn ending and a queued turn starting. */ +const COMPLETED_DELAY_MS = 1_500; + +export interface IMobileNotificationHost { + readonly permission: NotificationPermission; + isHidden(): boolean; + requestPermission(): Promise; + createNotification(title: string, options: NotificationOptions): EventTarget & { close(): void }; + focus(): void; + vibrate(pattern: VibratePattern): void; +} + +/** Notifies about current session changes while the phone app is hidden. */ +export class MobileBackgroundNotifier extends Disposable { + private readonly _statusListeners = this._register(new DisposableMap()); + private readonly _shown = this._register(new DisposableMap()); + + constructor( + private readonly _host: IMobileNotificationHost, + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @ISessionsService private readonly _sessionsService: ISessionsService, + ) { + super(); + + for (const session of this._sessionsManagementService.getSessions()) { + this._track(session); + } + this._register(this._sessionsManagementService.onDidChangeSessions(event => { + for (const session of event.removed) { + this._statusListeners.deleteAndDispose(session.sessionId); + this._close(session); + } + for (const session of event.added) { + this._track(session); + } + })); + this._register(this._sessionsManagementService.onDidReplaceSession(({ from, to }) => { + this._statusListeners.deleteAndDispose(from.sessionId); + this._close(from); + this._track(to); + })); + } + + private _track(session: ISession): void { + const store = new DisposableStore(); + this._statusListeners.set(session.sessionId, store); + let generation = 0; + const notify = (status: SessionStatus) => { + const currentGeneration = generation; + void this._notify(session, status, () => !store.isDisposed && generation === currentGeneration).catch(onUnexpectedError); + }; + const completed = store.add(new RunOnceScheduler(() => notify(SessionStatus.Completed), COMPLETED_DELAY_MS)); + store.add(autorunDelta(session.status, ({ lastValue, newValue }) => { + if (lastValue === undefined || lastValue === newValue) { + return; + } + generation++; + this._close(session); + if (newValue === SessionStatus.Completed) { + completed.schedule(); + } else { + completed.cancel(); + } + if (newValue === SessionStatus.NeedsInput || newValue === SessionStatus.Error) { + notify(newValue); + } + })); + } + + private async _notify(session: ISession, status: SessionStatus, isCurrent: () => boolean): Promise { + const canNotify = () => !this._store.isDisposed && isCurrent() && session.status.get() === status && this._host.isHidden(); + if (!canNotify()) { + return; + } + if (!(await this._ensurePermission()) || !canNotify()) { + return; + } + + const title = session.title.get(); + const body = status === SessionStatus.NeedsInput + ? localize('mobileNotify.needsInput', "Needs your input") + : status === SessionStatus.Error + ? localize('mobileNotify.failed', "Stopped with an error") + : localize('mobileNotify.completed', "Finished"); + + const notificationStore = new DisposableStore(); + this._shown.set(session.sessionId, notificationStore); + const notification = this._host.createNotification(title, { + body, + tag: session.resource.toString(), + icon: 'favicon.ico', + }); + notificationStore.add(toDisposable(() => notification.close())); + notificationStore.add(addDisposableListener(notification, 'click', () => { + this._host.focus(); + void this._sessionsService.openSession(session.resource, { source: 'notification' }).catch(onUnexpectedError); + this._close(session); + })); + + this._host.vibrate(status === SessionStatus.NeedsInput ? [60, 40, 60] : 40); + } + + private async _ensurePermission(): Promise { + if (this._host.permission === 'granted') { + return true; + } + if (this._host.permission === 'denied') { + return false; + } + try { + return (await this._host.requestPermission()) === 'granted'; + } catch { + return false; + } + } + + private _close(session: ISession): void { + this._shown.deleteAndDispose(session.sessionId); + } +} + +class MobileBackgroundNotifierContribution extends Disposable implements IWorkbenchContribution { + static readonly ID = 'workbench.contrib.mobileBackgroundNotifier'; + + constructor(@IInstantiationService instantiationService: IInstantiationService) { + super(); + if (typeof Notification === 'undefined') { + return; + } + this._register(instantiationService.createInstance(MobileBackgroundNotifier, { + get permission() { return Notification.permission; }, + isHidden: () => mainWindow.document.hidden, + requestPermission: () => Notification.requestPermission(), + createNotification: (title, options) => new Notification(title, options), + focus: () => mainWindow.focus(), + vibrate: pattern => mainWindow.navigator.vibrate?.(pattern), + })); + } +} + +registerWorkbenchContribution2(MobileBackgroundNotifierContribution.ID, MobileBackgroundNotifierContribution, WorkbenchPhase.Eventually); diff --git a/src/vs/sessions/contrib/mobile/browser/mobileChatEditPresenter.ts b/src/vs/sessions/contrib/mobile/browser/mobileChatEditPresenter.ts new file mode 100644 index 000000000000..54f4ffa297a1 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileChatEditPresenter.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { ChatEditCompareModelFactory, IChatEditDiff, IChatEditPresentationService } from '../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatEditPresentation.js'; +import { IChatExternalEdit } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; +import { IChatTextEditGroup } from '../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { IChatResponseViewModel } from '../../../../workbench/contrib/chat/common/model/chatViewModel.js'; +import { IMobileDiffViewData, MOBILE_OPEN_DIFF_VIEW_COMMAND_ID } from '../../../browser/parts/mobile/contributions/mobileDiffView.js'; +import { MobileChatEditRow } from './mobileChatEditRow.js'; + +export class MobileChatEditPresenter implements IChatEditPresentationService { + declare readonly _serviceBrand: undefined; + + constructor( + @ICommandService private readonly commandService: ICommandService, + @IInstantiationService private readonly instantiationService: IInstantiationService, + ) { } + + renderTextEdit(edit: IChatTextEditGroup, response: IChatResponseViewModel, createModel: ChatEditCompareModelFactory): MobileChatEditRow { + return this.instantiationService.createInstance(MobileChatEditRow, edit, response, createModel, diff => this.openDiff(diff)); + } + + async openExternalEdit(edit: IChatExternalEdit): Promise { + await this.openDiff({ + uri: edit.uri, + originalURI: edit.beforeContentUri, + modifiedURI: edit.editKind === 'delete' ? undefined : edit.afterContentUri ?? edit.uri, + added: edit.diff?.added ?? 0, + removed: edit.diff?.removed ?? 0, + }); + } + + private async openDiff(diff: IChatEditDiff): Promise { + const data: IMobileDiffViewData = { + diff: { + originalURI: diff.originalURI, + modifiedURI: diff.modifiedURI, + identical: false, + added: diff.added, + removed: diff.removed, + }, + }; + await this.commandService.executeCommand(MOBILE_OPEN_DIFF_VIEW_COMMAND_ID, data); + return true; + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileChatEditRow.ts b/src/vs/sessions/contrib/mobile/browser/mobileChatEditRow.ts new file mode 100644 index 000000000000..45eb1a88903b --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileChatEditRow.ts @@ -0,0 +1,95 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../base/common/codicons.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../base/common/observable.js'; +import { IEditorWorkerService } from '../../../../editor/common/services/editorWorker.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { ChatEditPillElement } from '../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatEditPillElement.js'; +import { ChatEditCompareModelFactory, IChatEditDiff, IChatEditPresentation } from '../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatEditPresentation.js'; +import { IChatEditingService } from '../../../../workbench/contrib/chat/common/editing/chatEditingService.js'; +import { IChatTextEditGroup } from '../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { IChatResponseViewModel } from '../../../../workbench/contrib/chat/common/model/chatViewModel.js'; + +/** A mobile edit row; compare models stay owned by the shared editing services. */ +export class MobileChatEditRow extends Disposable implements IChatEditPresentation { + readonly domNode: HTMLElement; + + constructor( + edit: IChatTextEditGroup, + response: IChatResponseViewModel, + createModel: ChatEditCompareModelFactory, + openDiff: (diff: IChatEditDiff) => Promise, + @IInstantiationService instantiationService: IInstantiationService, + @IEditorWorkerService editorWorkerService: IEditorWorkerService, + @IChatEditingService chatEditingService: IChatEditingService, + ) { + super(); + const pill = this._register(instantiationService.createInstance(ChatEditPillElement)); + this.domNode = pill.element; + pill.setUri(edit.uri); + pill.setStatus(Codicon.diff, localize('edited', "Edited")); + pill.setProgressFill(undefined); + pill.setLabelDetail(''); + + // Prefer the pre-edit snapshot: the live file may already include these edits. + const entry = chatEditingService.getEditingSession(response.sessionResource)?.getEntry(edit.uri); + if (entry) { + if (entry.linesAdded && entry.linesRemoved) { + const { linesAdded, linesRemoved } = entry; + this._register(autorun(reader => pill.setDiff({ added: linesAdded.read(reader), removed: linesRemoved.read(reader) }))); + } + this._register(pill.onDidClick(() => { + void openDiff({ + uri: edit.uri, originalURI: entry.originalURI, modifiedURI: entry.modifiedURI, + added: entry.linesAdded?.get() ?? 0, removed: entry.linesRemoved?.get() ?? 0, + }).catch(onUnexpectedError); + })); + return; + } + + const models = createModel().then(reference => { + if (this._store.isDisposed) { + reference.dispose(); + return undefined; + } + return this._register(reference).object; + }); + let stats = { added: 0, removed: 0 }; + void models.then(async models => { + if (!models) { + return; + } + const diff = await editorWorkerService.computeDiff(models.original.textEditorModel.uri, models.modified.textEditorModel.uri, { + ignoreTrimWhitespace: false, maxComputationTimeMs: 1000, computeMoves: false, + }, 'advanced'); + if (!diff || this._store.isDisposed) { + return; + } + stats = diff.changes.reduce((counts, change) => ({ + added: counts.added + change.modified.length, + removed: counts.removed + change.original.length, + }), { added: 0, removed: 0 }); + pill.setDiff(stats); + }).catch(onUnexpectedError); + this._register(pill.onDidClick(() => { + void models.then(models => { + if (models && !this._store.isDisposed) { + return openDiff({ + uri: edit.uri, originalURI: models.original.textEditorModel.uri, + modifiedURI: models.modified.textEditorModel.uri, ...stats, + }); + } + return undefined; + }).catch(onUnexpectedError); + })); + } + + layout(_width: number): void { } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileChatViewFactory.ts b/src/vs/sessions/contrib/mobile/browser/mobileChatViewFactory.ts new file mode 100644 index 000000000000..e17e90cec6ca --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileChatViewFactory.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IChatViewOptions } from '../../../../workbench/contrib/sessions/browser/parts/chatView.js'; +import { ChatViewFactory } from '../../../../workbench/contrib/sessions/browser/chat/chatView.js'; +import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; +import { renderMobileSessionToolbar } from './mobileSessionToolbar.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; + +export class MobileChatViewFactory extends ChatViewFactory { + protected override readonly viewOptions: IChatViewOptions = { + inputEditorOptions: { fontSize: 16, lineHeight: 24 }, + showEmptyStateIcon: false, + }; + + override createNewChatView(isNewChatInSession: boolean, options: IChatViewOptions, instantiationService: IInstantiationService) { + return super.createNewChatView(isNewChatInSession, { + renderNewSessionHeader: (container, before) => renderMobileSessionToolbar(instantiationService, container, 'sessions-new-session-place-row', Menus.NewSessionPlace, before), + ...options, + }, instantiationService); + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileClipboardImageContext.ts b/src/vs/sessions/contrib/mobile/browser/mobileClipboardImageContext.ts new file mode 100644 index 000000000000..702a53eee5a7 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileClipboardImageContext.ts @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { ClipboardImageContextValuePick } from '../../../../workbench/contrib/chat/browser/actions/chatContext.js'; +import { IChatContextPickService } from '../../../../workbench/contrib/chat/browser/attachments/chatContextPickService.js'; + +class MobileClipboardImageContextContribution extends Disposable { + constructor( + @IInstantiationService instantiationService: IInstantiationService, + @IChatContextPickService contextPickService: IChatContextPickService, + ) { + super(); + this._register(contextPickService.registerChatContextItem(instantiationService.createInstance(ClipboardImageContextValuePick, false))); + } +} + +registerWorkbenchContribution2('chat.mobileClipboardImageContext', MobileClipboardImageContextContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/sessions/contrib/mobile/browser/mobileConfigurationDefaults.ts b/src/vs/sessions/contrib/mobile/browser/mobileConfigurationDefaults.ts new file mode 100644 index 000000000000..4965a7c619ea --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileConfigurationDefaults.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IConfigurationDefaults } from '../../../../platform/configuration/common/configurationRegistry.js'; +import { PROMPT_TIMELINE_DISPLAY_SETTING } from '../../../../workbench/contrib/chat/common/promptTimeline.js'; +import { CloudSandboxEnabledSettingId } from '../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; +import { NEW_SESSION_WELCOME_PHRASES_SETTING } from '../../../../workbench/contrib/sessions/common/chatConstants.js'; + +/** Presentation defaults owned by the mobile entry; explicit user values and policy still win. */ +export const mobileConfigurationDefaults: IConfigurationDefaults = { + overrides: { + [CloudSandboxEnabledSettingId]: true, + // Desktop composer experiments must not change the mobile presentation between builds. + [NEW_SESSION_WELCOME_PHRASES_SETTING]: false, + // The prompt timeline rail is a 16px gutter handle that opens on hover; + // on a touch screen it is an unreachable target beside the transcript. + [PROMPT_TIMELINE_DISPLAY_SETTING]: 'off', + }, + donotCache: true, + preventExperimentOverride: true, + source: 'mobileDefaults', +}; diff --git a/src/vs/sessions/contrib/mobile/browser/mobileContextMenuService.ts b/src/vs/sessions/contrib/mobile/browser/mobileContextMenuService.ts new file mode 100644 index 000000000000..fdda4898033c --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileContextMenuService.ts @@ -0,0 +1,127 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IContextMenuDelegate } from '../../../../base/browser/contextmenu.js'; +import { IAction, Separator, SubmenuAction } from '../../../../base/common/actions.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { ContextMenuMenuDelegate } from '../../../../platform/contextview/browser/contextMenuService.js'; +import { IContextMenuMenuDelegate, IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; +import { IMenuService, MenuItemAction } from '../../../../platform/actions/common/actions.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { ILayoutService } from '../../../../platform/layout/browser/layoutService.js'; +import { IMobilePickerSheetItem, showMobilePickerSheet } from '../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; + +/** + * Phone presentation of {@link IContextMenuService}: every context menu — from + * long-pressed session rows to chat toolbars and editor gutters — is shown as a + * bottom action sheet instead of an anchored desktop menu widget. + * + * Callers do not change: `showContextMenu` accepts the same plain and menu-ID + * delegates as the desktop service and resolves them through the shared + * {@link ContextMenuMenuDelegate.transform}, so the actions, enablement, and + * action runner are identical to desktop; only the presentation differs. + * Submenus are flattened into titled sections because a sheet has no hover + * cascade. + */ +export class MobileContextMenuService extends Disposable implements IContextMenuService { + + declare readonly _serviceBrand: undefined; + + private readonly _onDidShowContextMenu = this._register(new Emitter()); + readonly onDidShowContextMenu = this._onDidShowContextMenu.event; + + private readonly _onDidHideContextMenu = this._register(new Emitter()); + readonly onDidHideContextMenu = this._onDidHideContextMenu.event; + + private _showing = false; + + constructor( + @ILayoutService private readonly layoutService: ILayoutService, + @IMenuService private readonly menuService: IMenuService, + @IContextKeyService private readonly contextKeyService: IContextKeyService, + ) { + super(); + } + + showContextMenu(delegate: IContextMenuDelegate | IContextMenuMenuDelegate): void { + if (this._showing) { + return; + } + + const resolved = ContextMenuMenuDelegate.transform(delegate, this.menuService, this.contextKeyService); + const actions = new Map(); + const items = this.toSheetItems(resolved.getActions(), actions); + if (items.length === 0) { + return; + } + + this._showing = true; + this._onDidShowContextMenu.fire(); + + showMobilePickerSheet(this.layoutService.mainContainer, localize('mobileContextMenu.title', "Actions"), items, { + doneLabel: localize('mobileContextMenu.cancel', "Cancel"), + }).then(pickedId => { + this._showing = false; + const action = pickedId ? actions.get(pickedId) : undefined; + resolved.onHide?.(!action); + this._onDidHideContextMenu.fire(); + + if (action) { + const context = resolved.getActionsContext?.(); + const run = resolved.actionRunner + ? resolved.actionRunner.run(action, context) + : action.run(context); + Promise.resolve(run).catch(onUnexpectedError); + } + }, error => { + this._showing = false; + this._onDidHideContextMenu.fire(); + onUnexpectedError(error); + }); + } + + private toSheetItems(actions: readonly IAction[], byId: Map, sectionTitle?: string): IMobilePickerSheetItem[] { + const items: IMobilePickerSheetItem[] = []; + let pendingSectionTitle: string | undefined = sectionTitle; + + for (const action of actions) { + if (action.id === 'sessionsViewPane.openToTheSide') { + continue; + } + if (action instanceof Separator) { + pendingSectionTitle = ''; + continue; + } + + if (action instanceof SubmenuAction) { + items.push(...this.toSheetItems(action.actions, byId, action.label)); + pendingSectionTitle = ''; + continue; + } + + // Command IDs can repeat in submenus, so allocate positions across the whole sheet. + const id = `${byId.size}:${action.id}`; + byId.set(id, action); + const icon = action instanceof MenuItemAction && ThemeIcon.isThemeIcon(action.item.icon) ? action.item.icon : undefined; + items.push({ + id, + label: action.label, + description: action.tooltip && action.tooltip !== action.label ? action.tooltip : undefined, + icon, + checked: action.checked || undefined, + disabled: !action.enabled, + sectionTitle: pendingSectionTitle, + }); + pendingSectionTitle = undefined; + } + + return items; + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileKeybindingService.ts b/src/vs/sessions/contrib/mobile/browser/mobileKeybindingService.ts new file mode 100644 index 000000000000..a79a7575f338 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileKeybindingService.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IFileService } from '../../../../platform/files/common/files.js'; +import { IKeyboardLayoutService } from '../../../../platform/keyboardLayout/common/keyboardLayout.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IExtensionService } from '../../../../workbench/services/extensions/common/extensions.js'; +import { IHostService } from '../../../../workbench/services/host/browser/host.js'; +import { WorkbenchKeybindingService } from '../../../../workbench/services/keybinding/browser/keybindingService.js'; +import { IUserDataProfileService } from '../../../../workbench/services/userDataProfile/common/userDataProfile.js'; + +/** + * Phone presentation of the keybinding service. + * + * Keybindings still resolve and dispatch, so a paired hardware keyboard works + * and every command keeps its shortcut. What changes is what the UI *says*: + * tooltips and labels no longer advertise shortcuts (`Add context (⌘/)`), + * because on a touch screen a shortcut hint is noise the user cannot act on. + */ +export class MobileKeybindingService extends WorkbenchKeybindingService { + + constructor( + @IContextKeyService contextKeyService: IContextKeyService, + @ICommandService commandService: ICommandService, + @ITelemetryService telemetryService: ITelemetryService, + @INotificationService notificationService: INotificationService, + @IUserDataProfileService userDataProfileService: IUserDataProfileService, + @IHostService hostService: IHostService, + @IExtensionService extensionService: IExtensionService, + @IFileService fileService: IFileService, + @IUriIdentityService uriIdentityService: IUriIdentityService, + @ILogService logService: ILogService, + @IKeyboardLayoutService keyboardLayoutService: IKeyboardLayoutService, + ) { + super(contextKeyService, commandService, telemetryService, notificationService, userDataProfileService, hostService, extensionService, fileService, uriIdentityService, logService, keyboardLayoutService); + } + + override appendKeybinding(label: string): string { + return label; + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullAgentHostTerminalService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullAgentHostTerminalService.ts new file mode 100644 index 000000000000..8a2666d03155 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullAgentHostTerminalService.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 { Disposable, DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; +import { constObservable, IObservable } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IAgentConnection } from '../../../../platform/agentHost/common/agentService.js'; +import { AgentHostOutputChannel } from '../../../../workbench/contrib/terminal/browser/agentHostOutputChannel.js'; +import { ITerminalChatService, ITerminalInstance } from '../../../../workbench/contrib/terminal/browser/terminal.js'; +import { IAgentHostEntry, IAgentHostTerminalCreateOptions, IAgentHostTerminalProfileInfo, IAgentHostTerminalService } from '../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; + +/** + * Phone implementation of {@link IAgentHostTerminalService}. + * + * The phone does not create agent-host terminals. The shared remote-agent-host chat + * contribution nevertheless requires this service to reconnect terminals when a + * host reconnects, so the phone provides an implementation that owns no + * terminals: reconnection reports nothing to recover, and creating or reviving + * a terminal is rejected with a user-facing message. + * + * Watching what an agent runs is a different matter: the chat transcript + * renders a command's output as a read-only card fed by an output source, which + * is a plain stream over the host connection and needs no terminal. The phone + * keeps that path so a user following along can see the output of commands, + * even though they cannot type into a shell. + */ +export class MobileNullAgentHostTerminalService extends Disposable implements IAgentHostTerminalService { + + declare readonly _serviceBrand: undefined; + + constructor( + @ITerminalChatService private readonly _terminalChatService: ITerminalChatService, + ) { + super(); + } + + readonly profiles: IObservable = constObservable([]); + + getProfileForConnection(_address: string): IAgentHostTerminalProfileInfo | undefined { + return undefined; + } + + registerEntry(_entry: IAgentHostEntry): IDisposable { + return Disposable.None; + } + + createTerminal(_connection: IAgentConnection, _options?: IAgentHostTerminalCreateOptions): Promise { + return Promise.reject(new Error(localize('mobile.terminalUnavailable', "Terminals are not available on this device."))); + } + + createTerminalForEntry(_address: string, _options?: IAgentHostTerminalCreateOptions): Promise { + return Promise.resolve(undefined); + } + + reconnectTerminals(_newConnection: IAgentConnection, _oldClientId: string): Promise<{ recovered: number; total: number }> { + return Promise.resolve({ recovered: 0, total: 0 }); + } + + reviveTerminal(_connection: IAgentConnection, _terminalUri: URI, _terminalToolSessionId: string): Promise { + return Promise.reject(new Error(localize('mobile.terminalUnavailable', "Terminals are not available on this device."))); + } + + attachOutputTerminal(connection: IAgentConnection, terminalUri: URI, terminalToolSessionId: string): IDisposable { + const store = new DisposableStore(); + const source = store.add(new AgentHostOutputChannel(connection, terminalUri)); + store.add(this._terminalChatService.registerOutputSource(terminalToolSessionId, source)); + return store; + } + + setDefaultCwd(_cwd: URI | undefined): void { } + + getAgentHostAddress(_instance: ITerminalInstance): string | undefined { + return undefined; + } + + isCommandExecuting(_instance: ITerminalInstance): boolean | undefined { + return undefined; + } + + markCommandPending(_instance: ITerminalInstance): void { } + + getCwd(_instance: ITerminalInstance): { readonly initial: string; readonly current: string } | undefined { + return undefined; + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullAquariumService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullAquariumService.ts new file mode 100644 index 000000000000..6a3351382923 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullAquariumService.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { constObservable, IObservable } from '../../../../base/common/observable.js'; +import { IAquariumService, IMountedToggleHandle } from '../../../../workbench/contrib/sessions/browser/aquarium.js'; + +/** + * Phone implementation of {@link IAquariumService}. The aquarium is a desktop + * easter egg drawn behind the new-session composer; on a phone it costs + * screen space and battery, so the phone mounts no toggle and never shows it. + * The new-session composer requires the service in its constructor, which is + * why a null implementation exists rather than the service being absent. + */ +export class MobileNullAquariumService extends Disposable implements IAquariumService { + + declare readonly _serviceBrand: undefined; + + readonly actionVisible: IObservable = constObservable(false); + + mountToggle(_parent: HTMLElement): IMountedToggleHandle { + return { setHostVisible: () => { }, dispose: () => { } }; + } + + toggleActionVisibility(): boolean { + return false; + } + + simulateStreak(_count: number, _alive: boolean): void { } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullChatWindowService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullChatWindowService.ts new file mode 100644 index 000000000000..05f815fe7f4a --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullChatWindowService.ts @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IDisposable } from '../../../../base/common/lifecycle.js'; +import { constObservable } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IChatWindow, IChatWindowNewChatOptions, IChatWindowOpenOptions, IChatWindowProvider, IChatWindowService } from '../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; + +const unavailableMessage = localize('mobile.chatWindowsUnavailable', "Separate chat windows are not available on this device."); + +export class MobileNullChatWindowService implements IChatWindowService { + declare readonly _serviceBrand: undefined; + + readonly windows = constObservable([]); + readonly hasProvider = constObservable(false); + readonly activeWindow = undefined; + + registerProvider(_provider: IChatWindowProvider): IDisposable { + throw new Error(unavailableMessage); + } + + async open(_chat: URI, _options?: IChatWindowOpenOptions): Promise { + throw new Error(unavailableMessage); + } + + getWindow(_windowId: number): IChatWindow | undefined { + return undefined; + } + + async moveToMainWindow(_window: IChatWindow): Promise { + throw new Error(unavailableMessage); + } + + async openNewChat(_window: IChatWindow, _options?: IChatWindowNewChatOptions): Promise { + throw new Error(unavailableMessage); + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullPinnedCanvasService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullPinnedCanvasService.ts new file mode 100644 index 000000000000..2f5ba2be76db --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullPinnedCanvasService.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 { constObservable, IReader } from '../../../../base/common/observable.js'; +// eslint-disable-next-line local/code-translation-remind -- The mobile entry has its own localization bundle. +import { localize } from '../../../../nls.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { ICanvas, ICanvasReference } from '../../../../workbench/common/canvasReference.js'; +import { IPinnedCanvas, IPinnedCanvasService, PinnedCanvasTarget } from '../../../../workbench/contrib/sessions/browser/pinnedCanvases.js'; + +const unavailableMessage = localize('mobile.pinnedCanvasesUnavailable', "Pinned canvases are not available on this device."); + +/** The shared sessions list requires this service without loading desktop canvas presentation. */ +export class MobileNullPinnedCanvasService implements IPinnedCanvasService { + declare readonly _serviceBrand: undefined; + + readonly enabled = constObservable(false); + readonly entries = constObservable([]); + readonly selected = constObservable(undefined); + + constructor( + @INotificationService private readonly notificationService: INotificationService, + ) { } + + getEntry(_target: PinnedCanvasTarget, _reader?: IReader): IPinnedCanvas | undefined { + return undefined; + } + + isPinned(_reference: ICanvasReference, _reader?: IReader): boolean { + return false; + } + + isShown(_reference: ICanvasReference, _reader?: IReader): boolean { + return false; + } + + getTrackedCanvas(_reference: ICanvasReference, _reader?: IReader): ICanvas | undefined { + return undefined; + } + + pin(_reference: ICanvasReference): boolean { + this.notificationService.error(unavailableMessage); + return false; + } + + unpin(_target: PinnedCanvasTarget): void { } + + async show(_target: PinnedCanvasTarget): Promise { + throw new Error(unavailableMessage); + } + + reconnect(_target: PinnedCanvasTarget): void { } + + async goToChat(_target: PinnedCanvasTarget): Promise { + throw new Error(unavailableMessage); + } + + async closeCanvas(_target: PinnedCanvasTarget): Promise { + throw new Error(unavailableMessage); + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullScreenshotToolService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullScreenshotToolService.ts new file mode 100644 index 000000000000..61c73dd4088c --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullScreenshotToolService.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 { CodeWindow } from '../../../../base/browser/window.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Event } from '../../../../base/common/event.js'; +// eslint-disable-next-line local/code-translation-remind -- The mobile entry has its own localization bundle. +import { localize } from '../../../../nls.js'; +import { IScreenshotToolCaptureEvent, IScreenshotToolEdit, IScreenshotToolEditable, IScreenshotToolImage, IScreenshotToolMarkUp, IScreenshotToolService, ScreenshotToolResult, ScreenshotToolSurface } from '../../../../workbench/contrib/screenshotTool/browser/screenshotTool.js'; + +const unavailableMessage = localize('mobile.screenshotToolUnavailable', "This screenshot tool is not available on this device."); + +/** Shared chat requires this service, but the phone does not ship desktop screenshot capture or markup. */ +export class MobileNullScreenshotToolService implements IScreenshotToolService { + declare readonly _serviceBrand: undefined; + + readonly isSupported = false; + readonly onDidChangeActive = Event.None; + + async capture(_targetWindow: CodeWindow, _token?: CancellationToken): Promise { + throw new Error(unavailableMessage); + } + + async captureWindow(_targetWindow: CodeWindow, _options?: { readonly afterRepaint?: boolean }): Promise { + throw new Error(unavailableMessage); + } + + async edit(_screenshot: IScreenshotToolEditable, _surface: ScreenshotToolSurface, _name?: string): Promise { + throw new Error(unavailableMessage); + } + + markUp(_container: HTMLElement, _screenshot: IScreenshotToolEditable | Promise, _surface: ScreenshotToolSurface): IScreenshotToolMarkUp { + throw new Error(unavailableMessage); + } + + registerEditableAttachment(_attachment: object, _screenshot: IScreenshotToolEditable): void { + throw new Error(unavailableMessage); + } + + getEditableAttachment(_attachment: object): IScreenshotToolEditable | undefined { + return undefined; + } + + focus(): void { } + + logCapture(_event: IScreenshotToolCaptureEvent): void { } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileNullWorktreeSuggestionService.ts b/src/vs/sessions/contrib/mobile/browser/mobileNullWorktreeSuggestionService.ts new file mode 100644 index 000000000000..506adba621ef --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileNullWorktreeSuggestionService.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { constObservable, IReader } from '../../../../base/common/observable.js'; +// eslint-disable-next-line local/code-translation-remind -- The mobile entry has its own localization bundle. +import { localize } from '../../../../nls.js'; +import { IActionListItem } from '../../../../platform/actionWidget/browser/actionList.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { IUncommittedChangesListItem, IWorktreeSuggestion, IWorktreeSuggestionService, WorktreeSpotlightChoice } from '../../../../workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.js'; +import { WorktreeSuggestionVariant } from '../../../../workbench/contrib/sessions/common/worktreeSuggestion.js'; +import { ISession, ISessionFileChange } from '../../../../workbench/services/sessions/common/session.js'; + +const unavailableMessage = localize('mobile.worktreeSuggestionsUnavailable', "Worktree suggestions are not available on this device."); + +/** Shared composers require this service, but worktree suggestion presentations do not support the phone. */ +export class MobileNullWorktreeSuggestionService implements IWorktreeSuggestionService { + declare readonly _serviceBrand: undefined; + + readonly variant = constObservable(WorktreeSuggestionVariant.Off); + readonly isPreviewing = constObservable(false); + + constructor( + @INotificationService private readonly notificationService: INotificationService, + ) { } + + getSuggestion(_session: ISession | undefined, _reader: IReader | undefined): IWorktreeSuggestion | undefined { + return undefined; + } + + reportWouldShow(): void { } + markShown(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion): void { } + markOpened(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion): void { } + markAccepted(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion): void { } + decline(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion): void { } + + hasDeclined(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion, _reader: IReader | undefined): boolean { + return false; + } + + async useWorktree(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion): Promise { + this.notificationService.error(unavailableMessage); + return false; + } + + getUncommittedChanges(_suggestion: IWorktreeSuggestion, _reader: IReader | undefined): readonly ISessionFileChange[] | undefined { + return undefined; + } + + async reviewChanges(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion, _change?: ISessionFileChange): Promise { + throw new Error(unavailableMessage); + } + + getUncommittedChangesListItems(_variant: WorktreeSuggestionVariant, _suggestion: IWorktreeSuggestion, _maxFiles: number): IActionListItem[] { + return []; + } + + isHintClosed(_reader: IReader | undefined): boolean { + return false; + } + + hasCreatedWorktreeSession(_reader: IReader | undefined): boolean { + return false; + } + + closeHint(_suggestion: IWorktreeSuggestion): void { } + + canShowSpotlight(): boolean { + return false; + } + + async showSendSpotlight(_suggestion: IWorktreeSuggestion, _options: { readonly reveal: () => void }): Promise { + return undefined; + } + + setPreview(_variant: WorktreeSuggestionVariant | undefined): void { + throw new Error(unavailableMessage); + } + + reset(): void { } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileQuickInputService.ts b/src/vs/sessions/contrib/mobile/browser/mobileQuickInputService.ts new file mode 100644 index 000000000000..5f51195d3e6d --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileQuickInputService.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 './media/mobileQuickInput.css'; +import * as dom from '../../../../base/browser/dom.js'; +import { raceCancellation } from '../../../../base/common/async.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { KeyCode } from '../../../../base/common/keyCodes.js'; +import { DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; +import Severity from '../../../../base/common/severity.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { ILayoutService } from '../../../../platform/layout/browser/layoutService.js'; +import { IOpenerService } from '../../../../platform/opener/common/opener.js'; +import { IInputOptions, IPickOptions, IQuickPickItem, QuickPickInput } from '../../../../platform/quickinput/common/quickInput.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; +import { QuickInputService } from '../../../../workbench/services/quickinput/browser/quickInputService.js'; +import { IMobilePickerSheetItem, showMobileContentSheet, showMobilePickerSheet } from '../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; + +const $ = dom.$; + +/** + * Phone presentation of the quick input. + * + * The one-shot `pick` and `input` calls that features use for simple choices + * and prompts render as bottom sheets. Everything else — quick access (the + * command palette, `#` and `@` pickers), multi-step pickers created through + * `createQuickPick`, and anything multi-select — keeps the shared controller, + * which the phone styles as a full-width panel. The service contract and the + * results callers receive are unchanged. + */ +export class MobileQuickInputService extends QuickInputService { + + constructor( + @IConfigurationService configurationService: IConfigurationService, + @IInstantiationService instantiationService: IInstantiationService, + @IKeybindingService keybindingService: IKeybindingService, + @IContextKeyService contextKeyService: IContextKeyService, + @IThemeService themeService: IThemeService, + @ILayoutService layoutService: ILayoutService, + @IOpenerService openerService: IOpenerService, + ) { + super(configurationService, instantiationService, keybindingService, contextKeyService, themeService, layoutService, openerService); + } + + override async pick>(picks: Promise[]> | QuickPickInput[], options?: O, token: CancellationToken = CancellationToken.None): Promise<(O extends { canPickMany: true } ? T[] : T) | undefined> { + if (options?.canPickMany || options?.quickNavigate || options?.contextKey) { + return super.pick(picks, options, token); + } + + const resolved = await raceCancellation(Promise.all([picks, options?.activeItem]), token); + if (!resolved || token.isCancellationRequested) { + return undefined; + } + const [resolvedPicks, activeItem] = resolved; + // Per-item buttons (remove from recents, configure, …) have no row + // affordance in the sheet; those pickers keep the shared controller. + if (resolvedPicks.some(pick => pick.type !== 'separator' && pick.buttons?.length)) { + return super.pick(picks, options, token); + } + + const byId = new Map(); + const items: IMobilePickerSheetItem[] = []; + let pendingSection: string | undefined; + for (const pick of resolvedPicks) { + if (pick.type === 'separator') { + pendingSection = pick.label ?? ''; + continue; + } + const id = `quick-pick-${byId.size}`; + byId.set(id, pick); + items.push({ + id, + label: stripIconSyntax(pick.label), + description: pick.detail ?? pick.description, + // Single-select pickers mark the current value either way. + checked: pick.picked || pick === activeItem || undefined, + disabled: pick.disabled, + sectionTitle: pendingSection, + }); + pendingSection = undefined; + } + + if (items.length === 0) { + return super.pick(picks, options, token); + } + + const title = options?.title ?? options?.placeHolder ?? localize('mobileQuickInput.pickTitle', "Choose"); + const pickedId = await showMobilePickerSheet(this.layoutService.mainContainer, title, items, { + dismissToken: token, + caption: options?.title ? options.placeHolder : undefined, + doneLabel: localize('mobileQuickInput.cancel', "Cancel"), + search: items.length > 8 + ? { + placeholder: localize('mobileQuickInput.search', "Search"), + loadItems: async query => { + const q = query.toLowerCase(); + return items.filter(item => item.label.toLowerCase().includes(q) || item.description?.toLowerCase().includes(q)); + }, + } + : undefined, + }); + if (token.isCancellationRequested || !pickedId) { + return undefined; + } + const picked = byId.get(pickedId); + return picked as (O extends { canPickMany: true } ? T[] : T) | undefined; + } + + override async input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise { + if (token.isCancellationRequested) { + return undefined; + } + let result: string | undefined; + const title = options.title ?? options.prompt ?? localize('mobileQuickInput.inputTitle', "Enter a value"); + await showMobileContentSheet(this.layoutService.mainContainer, title, (body, api) => { + const store = new DisposableStore(); + if (options.title && options.prompt) { + const prompt = dom.append(body, $('p.mobile-quick-input-prompt')); + prompt.textContent = options.prompt; + } + const input = dom.append(body, $('input.mobile-quick-input-field', { + type: options.password ? 'password' : 'text', + autocomplete: 'off', + autocapitalize: 'off', + autocorrect: 'off', + spellcheck: 'false', + })) as HTMLInputElement; + input.placeholder = options.placeHolder ?? ''; + input.value = options.value ?? ''; + if (options.valueSelection) { + input.setSelectionRange(options.valueSelection[0], options.valueSelection[1]); + } + const validation = dom.append(body, $('p.mobile-quick-input-validation')); + const submit = dom.append(body, $('button.mobile-quick-input-submit', { type: 'button' })) as HTMLButtonElement; + submit.textContent = localize('mobileQuickInput.ok', "OK"); + + let validationGeneration = 0; + const validate = async (value: string): Promise => { + if (!options.validateInput) { + return true; + } + const generation = ++validationGeneration; + const message = await options.validateInput(value); + if (store.isDisposed || token.isCancellationRequested) { + return false; + } + const text = typeof message === 'string' ? message : message?.content; + if (generation === validationGeneration && value === input.value) { + validation.textContent = text ?? ''; + validation.classList.toggle('visible', !!text); + } + // Info and warning messages are shown but do not block accepting. + return !text || (typeof message === 'object' && message !== null && message.severity < Severity.Error); + }; + store.add(dom.addDisposableListener(input, dom.EventType.INPUT, () => void validate(input.value).catch(onUnexpectedError))); + + const accept = async () => { + const value = input.value; + if (await validate(value) && !store.isDisposed && !token.isCancellationRequested) { + result = value; + api.close(); + } + }; + store.add(dom.addDisposableListener(submit, dom.EventType.CLICK, () => void accept().catch(onUnexpectedError))); + store.add(dom.addStandardDisposableListener(input, dom.EventType.KEY_DOWN, e => { + if (e.keyCode === KeyCode.Enter) { + e.preventDefault(); + void accept().catch(onUnexpectedError); + } + })); + api.setBodyFocusTargets([input, submit]); + const window = dom.getWindow(input); + const focusTimer = window.setTimeout(() => input.focus(), 50); + store.add(toDisposable(() => window.clearTimeout(focusTimer))); + store.add(token.onCancellationRequested(() => api.close())); + return store; + }, { doneLabel: localize('mobileQuickInput.cancel', "Cancel"), trapFocus: true }); + return token.isCancellationRequested ? undefined : result; + } +} + +function stripIconSyntax(label: string): string { + return label.replace(/\$\([a-z0-9-]+(~[a-z]+)?\)\s*/gi, '').trim(); +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileRepositoryPicker.ts b/src/vs/sessions/contrib/mobile/browser/mobileRepositoryPicker.ts new file mode 100644 index 000000000000..7adf61b1279f --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileRepositoryPicker.ts @@ -0,0 +1,198 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { raceCancellationError, RunOnceScheduler } from '../../../../base/common/async.js'; +import { cancelOnDispose, CancellationToken } from '../../../../base/common/cancellation.js'; +import { isCancellationError } from '../../../../base/common/errors.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../base/common/lifecycle.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { ILayoutService } from '../../../../platform/layout/browser/layoutService.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { ISessionRepositoryPicker } from '../../../../workbench/contrib/sessions/browser/sessionRepositoryPicker.js'; +import { isMobilePickerSheetTarget, showMobileContentSheet } from '../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; + +export class MobileRepositoryPicker extends Disposable implements ISessionRepositoryPicker { + declare readonly _serviceBrand: undefined; + + private readonly currentPick = this._register(new MutableDisposable()); + private previousFocus: HTMLElement | undefined; + + constructor( + @ILayoutService private readonly layoutService: ILayoutService, + @ILogService private readonly logService: ILogService, + ) { + super(); + } + + async pickRepository( + getRepositories: (query: string, token: CancellationToken) => Promise, + token: CancellationToken = CancellationToken.None, + ): Promise { + if (this._store.isDisposed || token.isCancellationRequested) { + return undefined; + } + + const focusedElement = dom.getActiveElement(); + const previousFocus = dom.isHTMLElement(focusedElement) && !isMobilePickerSheetTarget(focusedElement) ? focusedElement : this.previousFocus; + this.previousFocus = previousFocus; + const store = new DisposableStore(); + this.currentPick.value = store; + const pickToken = cancelOnDispose(store); + let selection: string | undefined; + + try { + await showMobileContentSheet(this.layoutService.mainContainer, localize('mobileRepositoryPicker.title', "Choose repository"), (body, api) => { + const sheetStore = new DisposableStore(); + const requests = sheetStore.add(new DisposableStore()); + const rowsStore = sheetStore.add(new DisposableStore()); + const searchRow = dom.append(body, dom.$('.mobile-picker-sheet-search')); + const input = dom.append(searchRow, dom.$('input.mobile-picker-sheet-search-input', { + type: 'search', autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off', spellcheck: 'false', + 'aria-label': localize('mobileRepositoryPicker.search', "Search repositories"), + })); + input.placeholder = localize('mobileRepositoryPicker.search', "Search repositories"); + const status = dom.append(body, dom.$('.mobile-picker-sheet-search-status', { role: 'status', 'aria-atomic': 'true' })); + const list = dom.append(body, dom.$('.mobile-picker-sheet-list', { role: 'list', 'aria-label': localize('mobileRepositoryPicker.results', "Repositories") })); + let buttons: HTMLButtonElement[] = []; + + const clearRows = () => { + if (list.contains(dom.getActiveElement())) { + input.focus(); + } + rowsStore.clear(); + dom.clearNode(list); + buttons = []; + api.setBodyFocusTargets([input]); + }; + const addRow = (label: string, accept: () => void) => { + const item = dom.append(list, dom.$('div', { role: 'listitem' })); + // Native buttons preserve scrolling without the Button widget's touch gesture interception. + const button = dom.append(item, dom.$('button.mobile-picker-sheet-item', { type: 'button' })); + const text = dom.append(button, dom.$('span.mobile-picker-sheet-text')); + dom.append(text, dom.$('span.mobile-picker-sheet-label')).textContent = label; + rowsStore.add(dom.addDisposableListener(button, dom.EventType.CLICK, event => { + dom.EventHelper.stop(event, true); + accept(); + })); + buttons.push(button); + api.setBodyFocusTargets([input, ...buttons]); + }; + const showLoading = () => { + requests.clear(); + clearRows(); + status.setAttribute('role', 'status'); + status.textContent = localize('mobileRepositoryPicker.loading', "Loading repositories…"); + list.setAttribute('aria-busy', 'true'); + }; + const updateItems = async () => { + const requestToken = cancelOnDispose(requests); + try { + const repositories = await raceCancellationError(getRepositories(input.value, requestToken), requestToken); + if (requestToken.isCancellationRequested) { + return; + } + status.textContent = repositories.length + ? repositories.length === 1 + ? localize('mobileRepositoryPicker.oneRepository', "1 repository") + : localize('mobileRepositoryPicker.count', "{0} repositories", repositories.length) + : localize('mobileRepositoryPicker.empty', "No repositories found. Try a different search."); + for (const repository of [...repositories].sort((a, b) => a.localeCompare(b))) { + addRow(repository, () => { + selection = repository; + api.close(); + }); + } + } catch (error) { + if (requestToken.isCancellationRequested) { + return; + } + if (isCancellationError(error)) { + api.close(); + return; + } + this.logService.error('Error fetching repositories', error); + status.setAttribute('role', 'alert'); + status.textContent = localize('mobileRepositoryPicker.loadFailed', "Could not load repositories. Check your GitHub sign-in and connection, then try again."); + addRow(localize('mobileRepositoryPicker.retry', "Try again"), () => { + showLoading(); + void updateItems(); + }); + } finally { + if (!requestToken.isCancellationRequested) { + list.setAttribute('aria-busy', 'false'); + } + } + }; + const search = sheetStore.add(new RunOnceScheduler(() => void updateItems(), 300)); + sheetStore.add(dom.addDisposableListener(input, dom.EventType.INPUT, () => { + showLoading(); + search.schedule(); + })); + sheetStore.add(dom.addDisposableListener(body, dom.EventType.KEY_DOWN, (event: KeyboardEvent) => { + if (event.isComposing) { + return; + } + const index = buttons.findIndex(button => button === event.target); + if (event.target !== input && index < 0) { + return; + } + let target: HTMLElement | undefined; + switch (event.key) { + case 'ArrowDown': + target = buttons[index + 1] ?? buttons[0]; + break; + case 'ArrowUp': + target = index === -1 ? buttons[buttons.length - 1] : buttons[index - 1] ?? input; + break; + case 'Home': + target = index >= 0 ? buttons[0] : undefined; + break; + case 'End': + target = index >= 0 ? buttons[buttons.length - 1] : undefined; + break; + case 'Enter': + dom.EventHelper.stop(event, true); + buttons[Math.max(index, 0)]?.click(); + return; + case ' ': + if (index >= 0) { + dom.EventHelper.stop(event, true); + buttons[index].click(); + } + return; + } + if (target) { + dom.EventHelper.stop(event, true); + target.focus(); + } + })); + sheetStore.add(token.onCancellationRequested(() => api.close())); + sheetStore.add(pickToken.onCancellationRequested(() => api.close())); + showLoading(); + input.focus(); + // Start after the shell has registered sheetStore so synchronous cancellation also cleans up. + search.schedule(0); + return sheetStore; + }, { + doneLabel: localize('mobileRepositoryPicker.cancel', "Cancel"), + trapFocus: true, + }); + return token.isCancellationRequested || pickToken.isCancellationRequested ? undefined : selection; + } finally { + store.dispose(); + if (this.currentPick.value === store) { + this.currentPick.clear(); + this.previousFocus = undefined; + } else if (this._store.isDisposed) { + this.previousFocus = undefined; + } + if (dom.isHTMLElement(previousFocus) && previousFocus.isConnected && dom.getActiveElement() === previousFocus.ownerDocument.body) { + previousFocus.focus(); + } + } + } +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileSessionToolbar.ts b/src/vs/sessions/contrib/mobile/browser/mobileSessionToolbar.ts new file mode 100644 index 000000000000..3a42874d613b --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileSessionToolbar.ts @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../../platform/actions/browser/toolbar.js'; +import { MenuId } from '../../../../platform/actions/common/actions.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; + +export function renderMobileSessionToolbar(instantiationService: IInstantiationService, container: HTMLElement, className: string, menu: MenuId, before?: HTMLElement): IDisposable { + const store = new DisposableStore(); + const row = dom.$(`div.${className}`); + store.add(toDisposable(() => row.remove())); + container.insertBefore(row, before ?? null); + const toolbar = store.add(instantiationService.createInstance(MenuWorkbenchToolBar, row, menu, { + hiddenItemStrategy: HiddenItemStrategy.NoHide, + toolbarOptions: { primaryGroup: () => true }, + })); + const update = () => row.toggleAttribute('hidden', toolbar.getItemsLength() === 0); + store.add(toolbar.onDidChangeMenuItems(update)); + update(); + return store; +} diff --git a/src/vs/sessions/contrib/mobile/browser/mobileSessionsListPresentation.ts b/src/vs/sessions/contrib/mobile/browser/mobileSessionsListPresentation.ts new file mode 100644 index 000000000000..0df698c8f4e6 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/browser/mobileSessionsListPresentation.ts @@ -0,0 +1,62 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IDisposable } from '../../../../base/common/lifecycle.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +// eslint-disable-next-line local/code-translation-remind -- Experimental entry is excluded from production translation resources. +import { localize } from '../../../../nls.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; +import { installPullToRefresh } from '../../../browser/mobile/mobilePullToRefresh.js'; +import { IAgentHostFilterService } from '../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { ISessionsListPresentation, SessionNameKind } from '../../../../workbench/contrib/sessions/browser/sessionsListPresentation.js'; +import { renderMobileSessionToolbar } from './mobileSessionToolbar.js'; + +export class MobileSessionsListPresentation implements ISessionsListPresentation { + declare readonly _serviceBrand: undefined; + readonly sectionRowHeight = 44; + + constructor( + @IInstantiationService private readonly instantiationService: IInstantiationService, + @IQuickInputService private readonly quickInputService: IQuickInputService, + @IAgentHostFilterService private readonly hostFilterService: IAgentHostFilterService, + ) { } + + editName(kind: SessionNameKind, value: string, _editInline: () => boolean, accept: (value: string) => void | Promise): boolean { + void this.promptForName(kind, value).then(async name => { + if (name !== undefined) { + await accept(name); + } + }).catch(onUnexpectedError); + return true; + } + + private async promptForName(kind: SessionNameKind, value: string): Promise { + const titles: Record = { + newGroup: localize('newGroup', "Name Group"), + group: localize('renameGroup', "Rename Group"), + session: localize('renameSession', "Rename Session"), + chat: localize('renameChat', "Rename Chat"), + }; + return (await this.quickInputService.input({ + title: titles[kind], value, valueSelection: [0, value.length], placeHolder: localize('name', "Name"), + }))?.trim(); + } + + renderHeader(container: HTMLElement): IDisposable { + return renderMobileSessionToolbar(this.instantiationService, container, 'mobile-sessions-drawer-header', Menus.MobileSessionsDrawerHeader); + } + + decorateList(container: HTMLElement, refresh: () => void, isAtTop: () => boolean): IDisposable { + return installPullToRefresh(container, { + isAtTop, + refresh: async () => { + refresh(); + await this.hostFilterService.rediscover(); + }, + }); + } +} diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileActionWidgetService.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileActionWidgetService.test.ts new file mode 100644 index 000000000000..77623765fbff --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileActionWidgetService.test.ts @@ -0,0 +1,169 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { toAction } from '../../../../../base/common/actions.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ActionListItemKind, IActionListItem } from '../../../../../platform/actionWidget/browser/actionList.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { MobileActionWidgetService } from '../../browser/mobileActionWidgetService.js'; + +suite('MobileActionWidgetService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createHarness() { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const service = store.add(new MobileActionWidgetService(upcastPartial({ mainContainer: container }))); + return { container, service }; + } + + for (const selectFooter of [false, true]) { + test(`updates a loading sheet in place and runs the latest ${selectFooter ? 'footer action' : 'item'}`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { container, service } = createHarness(); + const selected: { id: string; version: number }[] = []; + const hidden: (boolean | undefined)[] = []; + let footerRuns = 0; + const loading: IActionListItem<{ id: string; version: number }>[] = [ + { kind: ActionListItemKind.Action, label: 'Loading branches...', disabled: true }, + ]; + service.show('test', false, loading, { + onHide: cancelled => hidden.push(cancelled), + onSelect: item => selected.push(item), + }, container, undefined, [toAction({ id: 'manage', label: 'Manage branches', run: () => { footerRuns++; } })]); + const sheet = container.querySelector('.mobile-picker-sheet'); + service.updateItems([ + { kind: ActionListItemKind.Action, label: 'Main', item: { id: 'main', version: 1 } }, + { kind: ActionListItemKind.Action, label: 'Feature', item: { id: 'feature', version: 1 } }, + ], 'feature'); + const initialFocus = mainWindow.document.activeElement?.textContent; + service.updateItems([ + { kind: ActionListItemKind.Action, label: 'Main', item: { id: 'main', version: 2 } }, + { kind: ActionListItemKind.Action, label: 'Updated feature', item: { id: 'feature', version: 2 } }, + ]); + const rows = container.querySelectorAll('.mobile-picker-sheet-item'); + const updated = { + sameSheet: container.querySelector('.mobile-picker-sheet') === sheet, + labels: [...rows].map(row => row.textContent), + focus: mainWindow.document.activeElement?.textContent, + }; + rows[selectFooter ? 2 : 1].click(); + await timeout(500); + service.dispose(); + service.updateItems([]); + assert.deepStrictEqual({ initialFocus, updated, selected, footerRuns, hidden, remaining: container.childElementCount }, { + initialFocus: 'Feature', + updated: { sameSheet: true, labels: ['Main', 'Updated feature', 'Manage branches'], focus: 'Updated feature' }, + selected: selectFooter ? [] : [{ id: 'feature', version: 2 }], + footerRuns: selectFooter ? 1 : 0, + hidden: [false], + remaining: 0, + }); + }); + }); + } + + test('preserves the filter and rejects stale search results when items update', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { container, service } = createHarness(); + const oldItem: IActionListItem<{ id: string; version: number }> = { + kind: ActionListItemKind.Action, label: 'Model B', item: { id: 'b', version: 1 }, + }; + let items = [oldItem]; + const pending = new DeferredPromise[]>(); + let firstQuery = true; + const selected: { id: string; version: number }[] = []; + const hidden: (boolean | undefined)[] = []; + service.show('test', false, items, { + onHide: cancelled => hidden.push(cancelled), + onSelect: item => selected.push(item), + onFilter: async query => { + if (firstQuery) { + firstQuery = false; + return pending.p; + } + return items.filter(item => item.label?.includes(query)); + }, + }, container, undefined, undefined, undefined, { showFilter: true, initialFilterValue: 'Model B' }); + const sheet = container.querySelector('.mobile-picker-sheet'); + items = [ + { kind: ActionListItemKind.Action, label: 'Model A updated', item: { id: 'a', version: 2 } }, + { kind: ActionListItemKind.Action, label: 'Model B updated', item: { id: 'b', version: 2 } }, + ]; + service.updateItems(items, 'b', { focusFilter: true, preserveScrollPosition: true }); + await timeout(0); + const filter = container.querySelector('.mobile-picker-sheet-search-input')!; + const updated = { + query: filter.value, + label: container.querySelector('.mobile-picker-sheet-search-results')?.textContent, + filterFocused: mainWindow.document.activeElement === filter, + sameSheet: container.querySelector('.mobile-picker-sheet') === sheet, + }; + await pending.complete([oldItem]); + await timeout(0); + const afterStaleResult = container.querySelector('.mobile-picker-sheet-search-results')?.textContent; + service.setFilter(''); + await timeout(0); + const restored = container.querySelector('.mobile-picker-sheet-search-results')?.textContent; + container.querySelectorAll('.mobile-picker-sheet-search-results .mobile-picker-sheet-item')[1].click(); + await timeout(500); + assert.deepStrictEqual({ updated, afterStaleResult, restored, selected, hidden, remaining: container.childElementCount }, { + updated: { query: 'Model B', label: 'Model B updated', filterFocused: true, sameSheet: true }, + afterStaleResult: 'Model B updated', + restored: 'Model A updatedModel B updated', + selected: [{ id: 'b', version: 2 }], + hidden: [false], + remaining: 0, + }); + }); + }); + + test('updates an open filter and focuses the requested model without reopening', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { container, service } = createHarness(); + const items: IActionListItem<{ id: string }>[] = [ + { kind: ActionListItemKind.Action, label: 'Model A', item: { id: 'model-a' } }, + { kind: ActionListItemKind.Action, label: 'Model B', item: { id: 'model-b' } }, + ]; + const hidden: (boolean | undefined)[] = []; + service.show('test', false, items, { + onHide: cancelled => hidden.push(cancelled), + onSelect: () => { }, + onFilter: async query => items.filter(item => item.label?.includes(query)), + }, container, undefined, undefined, undefined, { showFilter: true, initialFilterValue: 'Model A' }); + await timeout(0); + const sheet = container.querySelector('.mobile-picker-sheet'); + const initial = container.querySelector('.mobile-picker-sheet-search-results')?.textContent; + service.setFilter('Model B', 'model-b'); + await timeout(0); + const updated = { + query: container.querySelector('.mobile-picker-sheet-search-input')?.value, + label: container.querySelector('.mobile-picker-sheet-search-results')?.textContent, + focused: mainWindow.document.activeElement?.textContent, + sameSheet: container.querySelector('.mobile-picker-sheet') === sheet, + }; + service.setFilter(''); + await timeout(0); + const restored = container.querySelector('.mobile-picker-sheet-search-results')?.textContent; + service.dispose(); + service.setFilter('Model B'); + await timeout(500); + assert.deepStrictEqual({ initial, updated, restored, hidden, remaining: container.childElementCount }, { + initial: 'Model A', + updated: { query: 'Model B', label: 'Model B', focused: 'Model B', sameSheet: true }, + restored: 'Model AModel B', + hidden: [true], + remaining: 0, + }); + }); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileBackgroundNotifier.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileBackgroundNotifier.test.ts new file mode 100644 index 000000000000..978066e2b335 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileBackgroundNotifier.test.ts @@ -0,0 +1,235 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; +import { ISessionsChangeEvent, ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { IMobileNotificationHost, MobileBackgroundNotifier } from '../../browser/mobileBackgroundNotifier.js'; + +class TestNotification extends EventTarget { + closeCount = 0; + + constructor(readonly title: string, readonly options: NotificationOptions) { + super(); + } + + close(): void { + this.closeCount++; + } +} + +class TestNotificationHost implements IMobileNotificationHost { + hidden = true; + permission: NotificationPermission = 'default'; + permissionRequests = 0; + focusCalls = 0; + readonly permissionResult = new DeferredPromise(); + readonly notifications: TestNotification[] = []; + readonly vibrations: VibratePattern[] = []; + + isHidden(): boolean { return this.hidden; } + requestPermission(): Promise { + this.permissionRequests++; + return this.permissionResult.p; + } + createNotification(title: string, options: NotificationOptions): TestNotification { + const notification = new TestNotification(title, options); + this.notifications.push(notification); + return notification; + } + focus(): void { this.focusCalls++; } + vibrate(pattern: VibratePattern): void { this.vibrations.push(pattern); } +} + +suite('MobileBackgroundNotifier', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createHarness() { + const host = new TestNotificationHost(); + const changed = store.add(new Emitter()); + const replaced = store.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); + const status = observableValue('status', SessionStatus.InProgress); + let session = upcastPartial({ + sessionId: 'session-one', resource: URI.parse('test-session:/one'), + title: constObservable('Background session'), status, + }); + const sessions = [session]; + const opened: string[] = []; + const notifier = store.add(new MobileBackgroundNotifier(host, + upcastPartial({ + getSessions: () => sessions, + onDidChangeSessions: changed.event, + onDidReplaceSession: replaced.event, + }), + upcastPartial({ + openSession: async resource => { opened.push(resource.toString()); }, + }), + )); + return { + host, status, notifier, opened, + replaceSession: (keepId: boolean) => { + const from = session; + const status = observableValue('replacementStatus', SessionStatus.InProgress); + session = upcastPartial({ + sessionId: keepId ? from.sessionId : 'session-two', resource: URI.parse('test-session:/two'), + title: constObservable('Replacement session'), status, + }); + sessions.splice(0, 1, session); + replaced.fire({ from, to: session }); + changed.fire({ added: [], removed: keepId ? [] : [from], changed: [session] }); + return status; + }, + removeSession: () => { + sessions.splice(0); + changed.fire({ added: [], removed: [session], changed: [] }); + }, + }; + } + + for (const keepId of [false, true]) { + test(`replacement with ${keepId ? 'the same' : 'a different'} ID closes old notifications and tracks the new session`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.host.permission = 'granted'; + h.status.set(SessionStatus.NeedsInput, undefined); + await timeout(0); + const oldNotification = h.host.notifications[0]; + const replacementStatus = h.replaceSession(keepId); + oldNotification.dispatchEvent(new Event('click')); + h.status.set(SessionStatus.Completed, undefined); + replacementStatus.set(SessionStatus.NeedsInput, undefined); + await timeout(1500); + h.host.notifications[1]?.dispatchEvent(new Event('click')); + await timeout(0); + assert.deepStrictEqual({ + notifications: h.host.notifications.map(notification => ({ + title: notification.title, tag: notification.options.tag, closed: notification.closeCount, + })), + opened: h.opened, + }, { + notifications: [ + { title: 'Background session', tag: 'test-session:/one', closed: 1 }, + { title: 'Replacement session', tag: 'test-session:/two', closed: 1 }, + ], + opened: ['test-session:/two'], + }); + }); + }); + + test(`replacement with ${keepId ? 'the same' : 'a different'} ID invalidates a pending permission request`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.status.set(SessionStatus.NeedsInput, undefined); + const replacementStatus = h.replaceSession(keepId); + replacementStatus.set(SessionStatus.NeedsInput, undefined); + await h.host.permissionResult.complete('granted'); + await timeout(0); + assert.deepStrictEqual({ + requests: h.host.permissionRequests, + notifications: h.host.notifications.map(notification => notification.options.tag), + }, { requests: 2, notifications: ['test-session:/two'] }); + }); + }); + } + + for (const change of ['disposed', 'visible', 'working', 'removed'] as const) { + test(`permission completion does not notify after the owner becomes ${change}`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.status.set(SessionStatus.NeedsInput, undefined); + switch (change) { + case 'disposed': h.notifier.dispose(); break; + case 'visible': h.host.hidden = false; break; + case 'working': h.status.set(SessionStatus.InProgress, undefined); break; + case 'removed': h.removeSession(); break; + } + await h.host.permissionResult.complete('granted'); + await timeout(0); + assert.deepStrictEqual({ + requests: h.host.permissionRequests, created: h.host.notifications.length, + vibrations: h.host.vibrations, opened: h.opened, + }, { requests: 1, created: 0, vibrations: [], opened: [] }); + }); + }); + } + + for (const [status, body] of [ + [SessionStatus.NeedsInput, 'Needs your input'], + [SessionStatus.Error, 'Stopped with an error'], + [SessionStatus.Completed, 'Finished'], + ] as const) { + test(`notifies a current hidden session for status ${status}`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.host.permission = 'granted'; + h.status.set(status, undefined); + await timeout(status === SessionStatus.Completed ? 1500 : 0); + h.notifier.dispose(); + assert.deepStrictEqual({ + requests: h.host.permissionRequests, + notifications: h.host.notifications.map(notification => ({ + title: notification.title, options: notification.options, closed: notification.closeCount, + })), + vibrations: h.host.vibrations, + }, { + requests: 0, + notifications: [{ title: 'Background session', options: { body, tag: 'test-session:/one', icon: 'favicon.ico' }, closed: 1 }], + vibrations: [status === SessionStatus.NeedsInput ? [60, 40, 60] : 40], + }); + }); + }); + } + + test('only the latest occurrence of a status can notify after permission resolves', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.status.set(SessionStatus.NeedsInput, undefined); + h.status.set(SessionStatus.InProgress, undefined); + h.status.set(SessionStatus.NeedsInput, undefined); + await h.host.permissionResult.complete('granted'); + await timeout(0); + assert.deepStrictEqual({ requests: h.host.permissionRequests, created: h.host.notifications.length }, { requests: 2, created: 1 }); + }); + }); + + test('denying requested permission does not create a notification', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.status.set(SessionStatus.NeedsInput, undefined); + await h.host.permissionResult.complete('denied'); + await timeout(0); + assert.deepStrictEqual({ requests: h.host.permissionRequests, created: h.host.notifications.length }, { requests: 1, created: 0 }); + }); + }); + + for (const closeWithClick of [false, true]) { + test(`${closeWithClick ? 'clicking' : 'disposing'} closes the notification and removes its click handler`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createHarness(); + h.host.permission = 'granted'; + h.status.set(SessionStatus.NeedsInput, undefined); + await timeout(0); + const notification = h.host.notifications[0]; + if (closeWithClick) { + notification.dispatchEvent(new Event('click')); + } + h.notifier.dispose(); + notification.dispatchEvent(new Event('click')); + await timeout(0); + assert.deepStrictEqual({ closed: notification.closeCount, focus: h.host.focusCalls, opened: h.opened }, { + closed: 1, focus: closeWithClick ? 1 : 0, opened: closeWithClick ? ['test-session:/one'] : [], + }); + }); + }); + } +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileChatEditRow.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileChatEditRow.test.ts new file mode 100644 index 000000000000..caed9c780a20 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileChatEditRow.test.ts @@ -0,0 +1,119 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { observableValue } from '../../../../../base/common/observable.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.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 { LineRange } from '../../../../../editor/common/core/ranges/lineRange.js'; +import { DetailedLineRangeMapping } from '../../../../../editor/common/diff/rangeMapping.js'; +import { ILanguageService } from '../../../../../editor/common/languages/language.js'; +import { ITextModel } from '../../../../../editor/common/model.js'; +import { IEditorWorkerService } from '../../../../../editor/common/services/editorWorker.js'; +import { IModelService } from '../../../../../editor/common/services/model.js'; +import { IResolvedTextEditorModel } from '../../../../../editor/common/services/resolverService.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; +import { ChatEditCompareModelFactory, IChatEditDiff } from '../../../../../workbench/contrib/chat/browser/widget/chatContentParts/chatEditPresentation.js'; +import { IChatEditingService, IChatEditingSession, IModifiedFileEntry } from '../../../../../workbench/contrib/chat/common/editing/chatEditingService.js'; +import { IChatTextEditGroup } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { IChatResponseViewModel } from '../../../../../workbench/contrib/chat/common/model/chatViewModel.js'; +import { MobileChatEditRow } from '../../browser/mobileChatEditRow.js'; + +suite('MobileChatEditRow', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const uri = URI.parse('test:/edit.ts'); + const originalURI = URI.parse('snapshot:/before'); + const modifiedURI = URI.parse('snapshot:/after'); + const edit = upcastPartial({ uri }); + const response = upcastPartial({ sessionResource: URI.parse('test:/session') }); + + function createHarness(entry?: IModifiedFileEntry) { + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ILabelService, upcastPartial({ + getUriBasenameLabel: () => 'edit.ts', + getUriLabel: uri => uri.toString(), + })); + instantiationService.stub(IModelService, upcastPartial({ getModel: () => null })); + instantiationService.stub(ILanguageService, upcastPartial({ guessLanguageIdByFilepathOrFirstLine: () => null })); + instantiationService.stub(IHoverService, NullHoverService); + instantiationService.stub(IChatEditingService, upcastPartial({ + getEditingSession: () => upcastPartial({ getEntry: () => entry }), + })); + const comparisons: [URI, URI][] = []; + instantiationService.stub(IEditorWorkerService, upcastPartial({ + computeDiff: async (original, modified) => { + comparisons.push([original, modified]); + return { identical: false, quitEarly: false, changes: [new DetailedLineRangeMapping(new LineRange(1, 2), new LineRange(1, 4), undefined)], moves: [] }; + }, + })); + const opened: IChatEditDiff[] = []; + return { + comparisons, opened, + create: (factory: ChatEditCompareModelFactory) => store.add(instantiationService.createInstance(MobileChatEditRow, edit, response, factory, async diff => { + opened.push(diff); + return true; + })), + }; + } + + test('uses editing snapshots and live counters instead of comparing an already-edited file', async () => { + const added = observableValue('added', 1); + const removed = observableValue('removed', 2); + const harness = createHarness(upcastPartial({ originalURI, modifiedURI, linesAdded: added, linesRemoved: removed })); + const row = harness.create(async () => assert.fail('An existing edit snapshot must not resolve the live file')); + added.set(7, undefined); + row.domNode.querySelector('[role="button"]')!.click(); + await timeout(0); + assert.deepStrictEqual({ comparisons: harness.comparisons, opened: harness.opened }, { + comparisons: [], + opened: [{ uri, originalURI, modifiedURI, added: 7, removed: 2 }], + }); + }); + + test('owns the fallback compare reference and computes counts for the opened diff', async () => { + const harness = createHarness(); + let disposed = 0; + const reference = Object.assign(store.add(toDisposable(() => disposed++)), { + object: { + originalSha1: 'before', + original: upcastPartial({ textEditorModel: upcastPartial({ uri: originalURI }) }), + modified: upcastPartial({ textEditorModel: upcastPartial({ uri: modifiedURI }) }), + }, + }); + const row = harness.create(async () => reference); + await timeout(0); + row.domNode.querySelector('[role="button"]')!.click(); + await timeout(0); + row.dispose(); + assert.deepStrictEqual({ comparisons: harness.comparisons, opened: harness.opened, disposed }, { + comparisons: [[originalURI, modifiedURI]], + opened: [{ uri, originalURI, modifiedURI, added: 3, removed: 1 }], + disposed: 1, + }); + }); + + test('disposes a compare reference that resolves after the row closes', async () => { + const harness = createHarness(); + const deferred = new DeferredPromise>>(); + const row = harness.create(() => deferred.p); + row.dispose(); + let disposed = 0; + await deferred.complete(Object.assign(store.add(toDisposable(() => disposed++)), { + object: { + originalSha1: '', + original: upcastPartial({}), + modified: upcastPartial({}), + }, + })); + await timeout(0); + assert.deepStrictEqual({ disposed, comparisons: harness.comparisons, opened: harness.opened }, { disposed: 1, comparisons: [], opened: [] }); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileComposerPresentation.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileComposerPresentation.test.ts new file mode 100644 index 000000000000..0661385070a0 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileComposerPresentation.test.ts @@ -0,0 +1,109 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom 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 '../../../../browser/parts/mobile/mobileChatShell.css'; +import '../../../../../workbench/contrib/sessions/browser/chat/media/chatWidget.css'; +import '../../../../../workbench/contrib/sessions/browser/chat/media/chatInput.css'; +import '../../../../../workbench/contrib/sessions/browser/chat/media/sharedChatInputComposer.css'; +import '../../../../../workbench/contrib/chat/browser/widget/media/chat.css'; +import '../../../../browser/mobile/media/mobileWorkbench.css'; +import '../../../../browser/mobile/media/mobileChat.css'; + +suite('Mobile composer presentation', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createRoot(theme: string, width = 390, height = 844) { + const root = dom.append(mainWindow.document.body, dom.$(`.monaco-workbench.agent-sessions-workbench.phone-layout.mobile-workbench.${theme}`)); + store.add(toDisposable(() => root.remove())); + root.style.position = 'relative'; + root.style.width = `${width}px`; + root.style.height = `${height}px`; + root.style.setProperty('--vscode-spacing-size40', '4px'); + root.style.setProperty('--vscode-spacing-size80', '8px'); + root.style.setProperty('--vscode-spacing-size120', '12px'); + root.style.setProperty('--vscode-spacing-size160', '16px'); + root.style.setProperty('--vscode-spacing-size200', '20px'); + root.style.setProperty('--vscode-spacing-size400', '40px'); + return root; + } + + for (const theme of ['vs', 'vs-dark', 'hc-light', 'hc-black']) { + test(`${theme}: shared composer actions respect visibility and retain touch targets`, () => { + const root = createRoot(theme); + const composer = dom.append(root, dom.$('.new-chat-input-container.sessions-shared-chat-input')); + composer.style.display = 'block'; + const chat = dom.append(composer, dom.$('.interactive-session')); + const toolbar = dom.append(chat, dom.$('.chat-input-toolbars')); + const execute = dom.append(toolbar, dom.$('.chat-execute-toolbar')); + const actionBar = dom.append(execute, dom.$('.monaco-action-bar')); + const actions = dom.append(actionBar, dom.$('ul.actions-container')); + const item = dom.append(actions, dom.$('li.action-item.chat-submit-button')); + const submit = dom.append(item, dom.$('a.action-label.codicon.codicon-arrow-up', { role: 'button' })); + item.style.display = 'none'; + const hidden = submit.getBoundingClientRect().height; + item.style.display = ''; + const available = { + height: submit.getBoundingClientRect().height, + touchInset: mainWindow.getComputedStyle(submit, '::after').top, + }; + item.style.display = 'none'; + assert.deepStrictEqual({ hidden, available, hiddenAgain: submit.getBoundingClientRect().height }, { + hidden: 0, + available: { height: 36, touchInset: '-4px' }, + hiddenAgain: 0, + }); + }); + + for (const [width, height] of [[320, 568], [390, 844], [844, 390]]) { + for (const experimentalLayout of [false, true]) { + test(`${theme}, ${width}x${height}, experimental layout ${experimentalLayout}: an enabled greeting replaces the logo and stays above the controls`, () => { + const root = createRoot(theme, width, height); + const container = dom.append(root, dom.$('.new-chat-widget-container.revealed')); + const content = dom.append(container, dom.$('.new-chat-widget-content.welcome-phrases-visible')); + content.classList.toggle('experimental-new-session-composer', experimentalLayout); + const welcome = dom.append(content, dom.$('.new-session-welcome-message')); + dom.append(welcome, dom.$('h2.new-session-welcome-message-title')).textContent = 'What are we building, Alexandra?'; + const workspace = dom.append(content, dom.$('.new-session-workspace-picker-container')); + const placeRow = dom.append(workspace, dom.$('.sessions-new-session-place-row')); + dom.append(placeRow, dom.$('button', { type: 'button' })).textContent = 'Cloud'; + const folderRow = dom.append(workspace, dom.$('.sessions-workspace-category-picker')); + dom.append(folderRow, dom.$('button', { type: 'button' })).textContent = 'example/project'; + const input = dom.append(content, dom.$('.new-chat-input-container')); + input.style.height = '112px'; + const welcomeRect = welcome.getBoundingClientRect(); + const workspaceRect = workspace.getBoundingClientRect(); + const inputRect = input.getBoundingClientRect(); + assert.deepStrictEqual({ + logo: mainWindow.getComputedStyle(workspace, '::before').content, + welcomeAboveControls: welcomeRect.bottom <= workspaceRect.top, + controlsAboveInput: workspaceRect.bottom <= inputRect.top, + welcomeWithinViewport: welcomeRect.left >= root.getBoundingClientRect().left && welcomeRect.right <= root.getBoundingClientRect().right, + inputWithinViewport: inputRect.bottom <= root.getBoundingClientRect().bottom, + }, { logo: 'none', welcomeAboveControls: true, controlsAboveInput: true, welcomeWithinViewport: true, inputWithinViewport: true }); + }); + } + } + } + + test('the original phone presentation is unchanged and mobile still has a hero when welcome phrases are off', () => { + const root = createRoot('vs-dark'); + const content = dom.append(root, dom.$('.new-chat-widget-content.welcome-phrases-visible')); + const workspace = dom.append(content, dom.$('.new-session-workspace-picker-container')); + const mobileWithGreeting = mainWindow.getComputedStyle(workspace, '::before').content; + content.classList.remove('welcome-phrases-visible'); + const mobileWithoutGreeting = mainWindow.getComputedStyle(workspace, '::before').content; + content.classList.add('welcome-phrases-visible'); + root.classList.remove('mobile-workbench'); + assert.deepStrictEqual({ + mobileWithGreeting, mobileWithoutGreeting, + fullPhone: mainWindow.getComputedStyle(workspace, '::before').content, + }, { mobileWithGreeting: 'none', mobileWithoutGreeting: '""', fullPhone: '""' }); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileConfigurationDefaults.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileConfigurationDefaults.test.ts new file mode 100644 index 000000000000..5b8dbb760b78 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileConfigurationDefaults.test.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { Event } from '../../../../../base/common/event.js'; +import { ResourceMap } from '../../../../../base/common/map.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { Configuration, ConfigurationModel } from '../../../../../platform/configuration/common/configurationModels.js'; +import { DefaultConfiguration } from '../../../../../platform/configuration/common/configurations.js'; +import { Extensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { ITreatmentWithAssignment, IWorkbenchAssignmentService } from '../../../../../workbench/services/assignment/common/assignmentService.js'; +import { ConfigurationDefaultOverridesContribution, WorkspaceService } from '../../../../../workbench/services/configuration/browser/configurationService.js'; +import { ExperimentalSettingsService } from '../../../../../workbench/services/configuration/common/experimentalSettings.js'; +import { IWorkbenchEnvironmentService } from '../../../../../workbench/services/environment/common/environmentService.js'; +import { IExtensionService } from '../../../../../workbench/services/extensions/common/extensions.js'; +import { NEW_SESSION_WELCOME_PHRASES_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; +import { mobileConfigurationDefaults } from '../../browser/mobileConfigurationDefaults.js'; +import '../../../chat/browser/chat.contribution.js'; + +suite('Mobile configuration defaults', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const keys = [NEW_SESSION_WELCOME_PHRASES_SETTING]; + const registry = Registry.as(Extensions.Configuration); + + test('entry-owned composer defaults reject experiment reassignment but still allow explicit user choices', async () => { + const logService = new NullLogService(); + const before = keys.map(key => registry.getConfigurationProperties()[key].default); + registry.registerDefaultConfigurations([mobileConfigurationDefaults]); + let contribution: ConfigurationDefaultOverridesContribution | undefined; + try { + const requested: string[] = []; + const processed = new DeferredPromise(); + const assignments = store.add(new ExperimentalSettingsService()); + contribution = store.add(new ConfigurationDefaultOverridesContribution( + upcastPartial({ + onDidRefetchAssignments: Event.None, + getTreatmentWithAssignment: async (name: string): Promise> => { + requested.push(name); + const assigned = keys.some(key => name === `config.${key}`); + return { value: assigned ? true as T : undefined, hasAssignment: Promise.resolve(assigned) }; + }, + }), + upcastPartial({ whenInstalledExtensionsRegistered: async () => true }), + upcastPartial({ reloadConfiguration: async () => { await processed.complete(); } }), + upcastPartial({ isSessionsWindow: true }), + logService, + assignments, + )); + await processed.p; + const defaults = await store.add(new DefaultConfiguration(logService)).initialize(); + const empty = ConfigurationModel.createEmptyModel(logService); + const user = ConfigurationModel.createEmptyModel(logService); + for (const key of keys) { + user.setValue(key, true); + } + const configuration = new Configuration(defaults, empty, empty, user, empty, empty, new ResourceMap(), empty, new ResourceMap(), logService); + assert.deepStrictEqual({ + mobileDefaults: keys.map(key => defaults.getValue(key)), + experimentRequests: requested.filter(name => keys.some(key => name === `config.${key}`)), + assigned: keys.map(key => assignments.hasAssignment(key)), + explicitValues: keys.map(key => configuration.getValue(key, {}, undefined)), + cacheDefaults: mobileConfigurationDefaults.donotCache, + }, { + mobileDefaults: [false], + experimentRequests: [], + assigned: [false], + explicitValues: [true], + cacheDefaults: true, + }); + } finally { + contribution?.dispose(); + registry.deregisterDefaultConfigurations([mobileConfigurationDefaults]); + } + assert.deepStrictEqual(keys.map(key => registry.getConfigurationProperties()[key].default), before); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileContextMenuService.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileContextMenuService.test.ts new file mode 100644 index 000000000000..d1c83423f898 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileContextMenuService.test.ts @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { SubmenuAction, toAction } from '../../../../../base/common/actions.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { MobileContextMenuService } from '../../browser/mobileContextMenuService.js'; + +suite('MobileContextMenuService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('runs the selected action when command IDs repeat across nested submenus', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const service = store.add(new MobileContextMenuService( + upcastPartial({ mainContainer: container }), + upcastPartial({}), + upcastPartial({}), + )); + const selected: string[] = []; + const actions = ['First', 'Second', 'Third'].map(label => toAction({ + id: 'repeated-command', label, run: () => { selected.push(label); }, + })); + const menu = [ + new SubmenuAction('first', 'First section', [actions[0]]), + new SubmenuAction('second', 'Second section', [new SubmenuAction('nested', 'Nested section', [actions[1]])]), + actions[2], + ]; + const hidden: boolean[] = []; + for (let index = 0; index < actions.length; index++) { + service.showContextMenu({ + getAnchor: () => container, + getActions: () => menu, + onHide: cancelled => hidden.push(!!cancelled), + }); + container.querySelectorAll('.mobile-picker-sheet-item')[index].click(); + await timeout(500); + } + assert.deepStrictEqual({ selected, hidden, remaining: container.childElementCount }, { + selected: ['First', 'Second', 'Third'], hidden: [false, false, false], remaining: 0, + }); + }); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileNullAgentHostTerminalService.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileNullAgentHostTerminalService.test.ts new file mode 100644 index 000000000000..5315cc5eab91 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileNullAgentHostTerminalService.test.ts @@ -0,0 +1,26 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ITerminalChatService, ITerminalInstance } from '../../../../../workbench/contrib/terminal/browser/terminal.js'; +import { MobileNullAgentHostTerminalService } from '../../browser/mobileNullAgentHostTerminalService.js'; + +suite('MobileNullAgentHostTerminalService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('reports unknown command and directory state for terminals it does not own', () => { + const service = store.add(new MobileNullAgentHostTerminalService(upcastPartial({}))); + const terminal = upcastPartial({ instanceId: 1 }); + service.markCommandPending(terminal); + assert.deepStrictEqual({ + profiles: service.profiles.get(), + address: service.getAgentHostAddress(terminal), + executing: service.isCommandExecuting(terminal), + cwd: service.getCwd(terminal), + }, { profiles: [], address: undefined, executing: undefined, cwd: undefined }); + }); +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobilePresentation.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobilePresentation.test.ts new file mode 100644 index 000000000000..da80640deef7 --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobilePresentation.test.ts @@ -0,0 +1,242 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as sinon from 'sinon'; +import * as dom from '../../../../../base/browser/dom.js'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { Event } from '../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { MenuWorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { IInputOptions, IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IChatExternalEdit } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; +import { ScreenshotContextValuePick } from '../../../../../workbench/contrib/chat/browser/actions/chatContext.js'; +import { IChatWidget } from '../../../../../workbench/contrib/chat/browser/chat.js'; +import { ICanvasReference } from '../../../../../workbench/common/canvasReference.js'; +import { IChatWindowProvider } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { ScreenshotToolSurface } from '../../../../../workbench/contrib/screenshotTool/browser/screenshotTool.js'; +import { IHostService } from '../../../../../workbench/services/host/browser/host.js'; +import { AbstractChatView, IChatViewOptions } from '../../../../../workbench/contrib/sessions/browser/parts/chatView.js'; +import { IMobileDiffViewData, MOBILE_OPEN_DIFF_VIEW_COMMAND_ID } from '../../../../browser/parts/mobile/contributions/mobileDiffView.js'; +import { IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { ISessionsListPresentation, SessionNameKind } from '../../../../../workbench/contrib/sessions/browser/sessionsListPresentation.js'; +import { createListHarness, createTestSession } from '../../../sessions/test/browser/sessionsListTestUtils.js'; +import { SessionsGrouping, SessionsList, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; +import { DefaultChatViewFactory } from '../../../../../workbench/contrib/sessions/browser/chat/defaultChatViewFactory.js'; +import { IChatViewFactory } from '../../../../../workbench/contrib/sessions/browser/chatViewFactory.js'; +import { IWorktreeSuggestion } from '../../../../../workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.js'; +import { WorktreeSuggestionVariant } from '../../../../../workbench/contrib/sessions/common/worktreeSuggestion.js'; +import { ISessionsChatBackgroundService } from '../../../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; +import { SessionsGridContent } from '../../../../../workbench/contrib/sessions/browser/parts/sessionsGridContent.js'; +import { ISessionsPartContentHost } from '../../../../../workbench/browser/parts/sessions/sessionsPartContent.js'; +import { MobileChatEditPresenter } from '../../browser/mobileChatEditPresenter.js'; +import { MobileChatViewFactory } from '../../browser/mobileChatViewFactory.js'; +import { MobileNullChatWindowService } from '../../browser/mobileNullChatWindowService.js'; +import { MobileNullPinnedCanvasService } from '../../browser/mobileNullPinnedCanvasService.js'; +import { MobileNullScreenshotToolService } from '../../browser/mobileNullScreenshotToolService.js'; +import { MobileNullWorktreeSuggestionService } from '../../browser/mobileNullWorktreeSuggestionService.js'; +import { MobileSessionsListPresentation } from '../../browser/mobileSessionsListPresentation.js'; + +suite('Mobile presentation composition', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + test('separate chat windows cannot be activated by mobile consumers', async () => { + const windows = new MobileNullChatWindowService(); + await assert.rejects(windows.open(URI.parse('chat:/test')), /Separate chat windows are not available/); + assert.throws(() => windows.registerProvider(upcastPartial({})), /Separate chat windows are not available/); + }); + + test('desktop screenshot capture and markup cannot be activated by mobile consumers', async () => { + const screenshots = new MobileNullScreenshotToolService(); + await assert.rejects(screenshots.capture(dom.getWindow(document.body)), /screenshot tool is not available/); + await assert.rejects(screenshots.edit({ + original: { dataUrl: 'data:image/png;base64,', width: 1, height: 1 }, + annotationState: undefined, + }, ScreenshotToolSurface.Chat), /screenshot tool is not available/); + }); + + test('chat screenshot attachments retain the existing browser capture path on mobile', async () => { + let captures = 0; + const host = new class extends mock() { + override async getScreenshot() { + captures++; + return VSBuffer.fromString('screenshot'); + } + }(); + const picker = new ScreenshotContextValuePick(host, new MobileNullScreenshotToolService()); + const attachment = await picker.asAttachment(upcastPartial({})); + assert.deepStrictEqual({ captures, kind: attachment?.kind }, { captures: 1, kind: 'image' }); + }); + + test('unsupported worktree suggestions report failure instead of claiming to switch isolation', async () => { + const errors: string[] = []; + const suggestions = new MobileNullWorktreeSuggestionService(upcastPartial({ + error: message => errors.push(String(message)), + })); + const switched = await suggestions.useWorktree(WorktreeSuggestionVariant.SpotlightOnSend, upcastPartial({})); + assert.deepStrictEqual({ switched, errors }, { + switched: false, + errors: ['Worktree suggestions are not available on this device.'], + }); + }); + + test('unsupported canvas pinning reports failure instead of claiming to pin a canvas', () => { + const errors: string[] = []; + const canvases = new MobileNullPinnedCanvasService(upcastPartial({ + error: message => errors.push(String(message)), + })); + const pinned = canvases.pin(upcastPartial({})); + assert.deepStrictEqual({ pinned, errors }, { + pinned: false, + errors: ['Pinned canvases are not available on this device.'], + }); + }); + + test('new-session headers retain the instantiation scope of their own view', () => { + const container = dom.append(document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const factory = new MobileChatViewFactory(); + const views = [false, true].map(isNewChatInSession => { + const scope = store.add(new TestInstantiationService()); + const createInstance = sinon.stub(scope, 'createInstance'); + createInstance.onFirstCall().returns(upcastPartial({})); + createInstance.onSecondCall().returns(upcastPartial({ + getItemsLength: () => 1, + onDidChangeMenuItems: Event.None, + dispose: () => { }, + })); + factory.createNewChatView(isNewChatInSession, {}, scope); + const options = createInstance.firstCall.args.at(-1) as IChatViewOptions; + return { createInstance, options }; + }); + for (const { options } of views) { + const before = dom.append(container, dom.$('div')); + store.add(options.renderNewSessionHeader!(container, before)); + } + assert.deepStrictEqual(views.map(({ createInstance }) => ({ + calls: createInstance.callCount, + headerConstructor: createInstance.secondCall.args[0], + })), views.map(() => ({ calls: 2, headerConstructor: MenuWorkbenchToolBar }))); + }); + + for (const mobile of [false, true]) { + test(`all chat views receive entry-owned input options (${mobile})`, () => { + const instantiationService = store.add(new TestInstantiationService()); + const createInstance = sinon.stub(instantiationService, 'createInstance').returns(upcastPartial({})); + const factory: IChatViewFactory = mobile ? new MobileChatViewFactory() : new DefaultChatViewFactory(upcastPartial({ + onDidChangeBackground: Event.None, + getBackground: () => ({ kind: 'codicons' }), + })); + assert.deepStrictEqual(factory.inputEditorOptions, mobile ? { fontSize: 16, lineHeight: 24 } : undefined); + const options: IChatViewOptions = { renderChatPet: false }; + factory.createNewChatView(false, options, instantiationService); + factory.createNewChatView(true, options, instantiationService); + factory.createChatView(instantiationService, options); + const passedOptions = createInstance.getCalls().map(call => call.args.at(-1) as IChatViewOptions); + assert.deepStrictEqual(passedOptions.map(value => ({ + input: value.inputEditorOptions, icon: value.showEmptyStateIcon, header: typeof value.renderNewSessionHeader, pet: value.renderChatPet, + background: value.background?.hasBackground() ?? false, + })), Array.from({ length: 3 }, (_, index) => ({ + input: mobile ? { fontSize: 16, lineHeight: 24 } : undefined, + icon: mobile ? false : undefined, header: mobile && index < 2 ? 'function' : 'undefined', pet: false, + background: !mobile, + }))); + }); + } + + test('mobile session grids create no background surface and require no background service', () => { + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IContextKeyService, new MockContextKeyService()); + instantiationService.stub(IThemeService, new TestThemeService()); + instantiationService.stub(IChatViewFactory, new MobileChatViewFactory()); + const grid = store.add(instantiationService.createInstance(SessionsGridContent, upcastPartial({}))); + const createInstance = sinon.spy(instantiationService, 'createInstance'); + const container = dom.$('div'); + grid.renderBackground(container); + assert.deepStrictEqual({ content: container.innerHTML, classes: container.className, created: createInstance.callCount }, { + content: '', classes: '', created: 0, + }); + }); + + for (const kind of ['newGroup', 'group', 'session', 'chat'] satisfies SessionNameKind[]) { + for (const value of [undefined, ' New name ']) { + test(`mobile ${kind} naming uses the prompt without inline fallback (${value})`, async () => { + const result = new DeferredPromise(); + const accepted: string[] = []; + let inputOptions: IInputOptions | undefined; + const quickInput = new class extends mock() { + override input(options: IInputOptions) { inputOptions = options; return result.p; } + }(); + const presenter = new MobileSessionsListPresentation(store.add(new TestInstantiationService()), quickInput, new class extends mock() { }()); + const started = presenter.editName(kind, 'Original', () => assert.fail('Inline editor must not be constructed'), name => { accepted.push(name); }); + await result.complete(value); + await timeout(0); + assert.deepStrictEqual({ started, selectedValue: inputOptions?.value, selection: inputOptions?.valueSelection, accepted, sectionRowHeight: presenter.sectionRowHeight }, { + started: true, selectedValue: 'Original', selection: [0, 8], accepted: value === undefined ? [] : ['New name'], sectionRowHeight: 44, + }); + }); + } + } + + for (const deleted of [false, true]) { + test(`external edit opens the mobile overlay, including missing diff counts (${deleted})`, async () => { + const calls: { id: string; data: IMobileDiffViewData }[] = []; + const command = new class extends mock() { + override async executeCommand(id: string, data: IMobileDiffViewData): Promise { + calls.push({ id, data }); + return undefined as T; + } + }(); + const presenter = new MobileChatEditPresenter(command, store.add(new TestInstantiationService())); + const uri = URI.parse('test:/file.ts'); + const original = URI.parse('test:/original.ts'); + await presenter.openExternalEdit(upcastPartial({ uri, beforeContentUri: original, editKind: deleted ? 'delete' : 'edit' })); + assert.deepStrictEqual(calls, [{ + id: MOBILE_OPEN_DIFF_VIEW_COMMAND_ID, + data: { diff: { originalURI: original, modifiedURI: deleted ? undefined : uri, identical: false, added: 0, removed: 0 } }, + }]); + }); + } + + for (const disposeBeforeAcceptance of [false, true]) { + test(`a prompted session rename remains list-owned and ignores a disposed list (${disposeBeforeAcceptance})`, async () => { + const { session } = createTestSession('Original'); + const prompt = new DeferredPromise(); + const harness = createListHarness(store, [session], instantiationService => { + const quickInput = new class extends mock() { + override input() { return prompt.p; } + }(); + instantiationService.stub(ISessionsListPresentation, new MobileSessionsListPresentation(instantiationService, quickInput, new class extends mock() { }())); + }); + const container = harness.createContainer(); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Workspace, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, sectionRowHeight: 44, + })); + list.layout(390, 600); + const started = list.beginRenameSession(session); + const inlineInput = container.querySelector('.session-title-input input'); + if (disposeBeforeAcceptance) { + list.dispose(); + } + await prompt.complete('Renamed'); + await timeout(0); + assert.deepStrictEqual({ started, inlineInput: !!inlineInput, renamed: harness.managementService.renamed.map(change => change.title) }, { + started: true, inlineInput: false, renamed: disposeBeforeAcceptance ? [] : ['Renamed'], + }); + }); + } +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileQuickInputService.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileQuickInputService.test.ts new file mode 100644 index 000000000000..0ff17b91c55a --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileQuickInputService.test.ts @@ -0,0 +1,140 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { CancellationTokenSource } from '../../../../../base/common/cancellation.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { IQuickPickItem } from '../../../../../platform/quickinput/common/quickInput.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { MobileQuickInputService } from '../../browser/mobileQuickInputService.js'; + +suite('MobileQuickInputService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const item: IQuickPickItem = { label: 'Choice' }; + + function createHarness() { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const instantiationService = workbenchInstantiationService(undefined, store.add(new DisposableStore())); + instantiationService.stub(ILayoutService, upcastPartial({ mainContainer: container })); + return { container, service: store.add(instantiationService.createInstance(MobileQuickInputService)) }; + } + + test('cancellation closes an open sheet and resolves the pending pick', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, container } = createHarness(); + const token = store.add(new CancellationTokenSource()); + const picked = service.pick([item], undefined, token.token); + await timeout(0); + const wasOpen = !!container.querySelector('.mobile-picker-sheet'); + token.cancel(); + await timeout(500); + assert.deepStrictEqual({ wasOpen, result: await picked, open: !!container.querySelector('.mobile-picker-sheet') }, { + wasOpen: true, result: undefined, open: false, + }); + }); + }); + + for (const waitingFor of ['items', 'active item'] as const) { + test(`cancellation does not wait for unresolved ${waitingFor}`, async () => { + const { service, container } = createHarness(); + const token = store.add(new CancellationTokenSource()); + const items = new DeferredPromise(); + const activeItem = new DeferredPromise(); + const result = service.pick(waitingFor === 'items' ? items.p : [item], waitingFor === 'active item' ? { activeItem: activeItem.p } : undefined, token.token); + token.cancel(); + assert.deepStrictEqual({ result: await result, children: container.childElementCount }, { result: undefined, children: 0 }); + }); + } + + test('an already-cancelled input never opens a sheet', async () => { + const { service, container } = createHarness(); + const token = store.add(new CancellationTokenSource()); + token.cancel(); + assert.deepStrictEqual({ result: await service.input({}, token.token), children: container.childElementCount }, { result: undefined, children: 0 }); + }); + + test('accepts the submitted value rather than an edit made during validation', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, container } = createHarness(); + const validation = new DeferredPromise(); + const values: string[] = []; + const result = service.input({ + value: 'Submitted', + validateInput: value => { + values.push(value); + return value === 'Submitted' ? validation.p : Promise.resolve('Invalid edit'); + }, + }); + container.querySelector('.mobile-quick-input-submit')!.click(); + const input = container.querySelector('.mobile-quick-input-field')!; + input.value = 'Edited'; + input.dispatchEvent(new Event('input')); + await timeout(0); + await validation.complete(undefined); + await timeout(500); + assert.deepStrictEqual({ values, result: await result, open: !!container.querySelector('.mobile-picker-sheet') }, { + values: ['Submitted', 'Edited'], result: 'Submitted', open: false, + }); + }); + }); + + test('only the latest validation result updates the message, even after returning to an earlier value', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, container } = createHarness(); + const validations: DeferredPromise[] = []; + const result = service.input({ + validateInput: () => { + const validation = new DeferredPromise(); + validations.push(validation); + return validation.p; + }, + }); + const input = container.querySelector('.mobile-quick-input-field')!; + for (const value of ['First', 'Second', 'First']) { + input.value = value; + input.dispatchEvent(new Event('input')); + } + await validations[2].complete(undefined); + await validations[1].complete('Stale second value'); + await validations[0].complete('Stale first value'); + await timeout(0); + const message = container.querySelector('.mobile-quick-input-validation')!; + const displayed = { text: message.textContent, visible: message.classList.contains('visible') }; + container.querySelector('.mobile-picker-sheet-done')!.click(); + await timeout(500); + assert.deepStrictEqual({ displayed, result: await result }, { + displayed: { text: '', visible: false }, result: undefined, + }); + }); + }); + + for (const cancelWithToken of [false, true]) { + test(`${cancelWithToken ? 'cancellation' : 'dismissal'} during validation cannot accept an input later`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, container } = createHarness(); + const token = store.add(new CancellationTokenSource()); + const validation = new DeferredPromise(); + const result = service.input({ value: 'Renamed', validateInput: () => validation.p }, token.token); + container.querySelector('.mobile-quick-input-submit')!.click(); + if (cancelWithToken) { + token.cancel(); + } else { + container.querySelector('.mobile-picker-sheet-done')!.click(); + } + await validation.complete(undefined); + await timeout(500); + assert.deepStrictEqual({ result: await result, children: container.childElementCount }, { result: undefined, children: 0 }); + }); + }); + } +}); diff --git a/src/vs/sessions/contrib/mobile/test/browser/mobileRepositoryPicker.test.ts b/src/vs/sessions/contrib/mobile/test/browser/mobileRepositoryPicker.test.ts new file mode 100644 index 000000000000..065c0dff38bf --- /dev/null +++ b/src/vs/sessions/contrib/mobile/test/browser/mobileRepositoryPicker.test.ts @@ -0,0 +1,539 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { CancellationError } from '../../../../../base/common/errors.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { isWeb } from '../../../../../base/common/platform.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ActionListItemKind } from '../../../../../platform/actionWidget/browser/actionList.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IEnvironmentService } from '../../../../../platform/environment/common/environment.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IsSessionsWindowContext } from '../../../../../workbench/common/contextkeys.js'; +import { IWorkbenchLayoutService } from '../../../../../workbench/services/layout/browser/layoutService.js'; +import { IChatEntitlementService } from '../../../../../workbench/services/chat/common/chatEntitlementService.js'; +import { TestChatEntitlementService } from '../../../../../workbench/test/common/workbenchTestServices.js'; +import { SessionWorktreeCleanupEditorFocusedContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { CustomViewVisibleContext } from '../../../../common/agentsWindowContextKeys.js'; +import { IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { ISessionsPartService } from '../../../../../workbench/services/sessions/browser/sessionsPartService.js'; +import { AgentWorkbenchLayout, ISessionsHostLayoutService } from '../../../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; +import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { GITHUB_REMOTE_FILE_SCHEME, ISessionWorkspaceBrowseAction, SESSION_WORKSPACE_GROUP_GITHUB } from '../../../../../workbench/services/sessions/common/session.js'; +import { showMobileWorkspacePickerSheet } from '../../../../../workbench/contrib/sessions/browser/chat/mobile/mobileWorkspacePickerSheet.js'; +import { SessionsChatAccessibilityHelp } from '../../../chat/browser/sessionsChatAccessibilityHelp.js'; +import { MobileRepositoryPicker } from '../../browser/mobileRepositoryPicker.js'; + +suite('MobileRepositoryPicker', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let clock: sinon.SinonFakeTimers; + + setup(() => { + clock = sinon.useFakeTimers(); + }); + + teardown(() => sinon.restore()); + + function createPicker() { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const trigger = dom.append(container, dom.$('button', { type: 'button' })); + trigger.textContent = 'Choose repository'; + trigger.focus(); + const errors: { message: string | Error; error?: Error }[] = []; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ILayoutService, { mainContainer: container }); + instantiationService.stub(ILogService, new class extends NullLogService { + override error(message: string | Error, error?: Error): void { + errors.push({ message, error }); + } + }()); + const picker = store.add(instantiationService.createInstance(MobileRepositoryPicker)); + return { picker, container, trigger, errors }; + } + + function getInput(container: HTMLElement): HTMLInputElement { + return container.querySelector('.mobile-picker-sheet-search-input')!; + } + + function getRows(container: HTMLElement): HTMLButtonElement[] { + return [...container.querySelectorAll('.mobile-picker-sheet-list button')]; + } + + function query(input: HTMLInputElement, value: string): void { + input.value = value; + input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + } + + function key(target: HTMLElement, value: string, shiftKey = false): void { + target.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: value, shiftKey, bubbles: true, cancelable: true })); + } + + (isWeb ? test : test.skip)('workspace GitHub header opens the mobile repository sheet without quick input', async () => { + // Exercise a shared document that already contains unrelated Quick Input widgets. + const unrelatedInputs = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => unrelatedInputs.remove())); + unrelatedInputs.hidden = true; + for (let index = 0; index < 4; index++) { + dom.append(unrelatedInputs, dom.$('.quick-input-widget')); + } + const existingQuickInputs = new Set(mainWindow.document.querySelectorAll('.quick-input-widget')); + const countNewQuickInputs = () => [...mainWindow.document.querySelectorAll('.quick-input-widget')] + .filter(widget => !existingQuickInputs.has(widget)).length; + const { picker, container, trigger, errors } = createPicker(); + container.classList.add('phone-layout'); + const layoutService = upcastPartial({ mainContainer: container }); + const queries: string[] = []; + let browseCalls = 0; + const selected = new DeferredPromise(); + const browseAction: ISessionWorkspaceBrowseAction = { + label: 'GitHub', icon: Codicon.github, providerId: 'test-github', group: SESSION_WORKSPACE_GROUP_GITHUB, + run: async () => { + browseCalls++; + await selected.complete(await picker.pickRepository(async query => { + queries.push(query); + return query === 'some-repo' ? ['Mixed.Owner/Some-Repo'] : ['Example/another']; + })); + return undefined; + }, + }; + const workspaceSheet = showMobileWorkspacePickerSheet(layoutService, trigger, [ + { + kind: ActionListItemKind.Action, + label: 'Example/recent', + item: { + folderUri: URI.from({ scheme: GITHUB_REMOTE_FILE_SCHEME, authority: 'github', path: '/Example/recent/HEAD' }), + providerId: browseAction.providerId, + }, + }, + { + kind: ActionListItemKind.Action, + label: browseAction.label, + group: { title: '', icon: browseAction.icon }, + item: { browseActionIndex: 0 }, + }, + ], item => { + assert.strictEqual(item.browseActionIndex, 0); + void browseAction.run().catch(error => selected.error(error)); + }, [browseAction]); + store.add(toDisposable(() => container.querySelector('.mobile-picker-sheet-done')?.click())); + const recentRow = getRows(container)[0]; + const workspaceState = { + title: container.querySelector('[role="dialog"]')?.ariaLabel, + rows: getRows(container).map(row => row.textContent), + recentVisible: recentRow.getBoundingClientRect().height > 0, + expanded: trigger.getAttribute('aria-expanded'), + browseCalls, + newQuickInputs: countNewQuickInputs(), + }; + container.querySelector('.mobile-picker-sheet-header-action[aria-label="GitHub"]')!.click(); + await clock.tickAsync(181); + await workspaceSheet; + const input = getInput(container); + const repositoryState = { + title: container.querySelector('[role="dialog"]')?.ariaLabel, + dialogs: container.querySelectorAll('[role="dialog"]').length, + expanded: trigger.getAttribute('aria-expanded'), + focused: dom.getActiveElement() === input, + newQuickInputs: countNewQuickInputs(), + }; + + const instantiationService = store.add(new TestInstantiationService()); + const configuration = new TestConfigurationService(); + store.add(configuration.onDidChangeConfigurationEmitter); + const contextKeys = store.add(new ContextKeyService(configuration)); + IsSessionsWindowContext.bindTo(contextKeys).set(true); + CustomViewVisibleContext.bindTo(contextKeys).set(false); + SessionWorktreeCleanupEditorFocusedContext.bindTo(contextKeys).set(false); + instantiationService.stub(IConfigurationService, configuration); + instantiationService.stub(IChatEntitlementService, new TestChatEntitlementService()); + instantiationService.stub(ITelemetryService, NullTelemetryService); + instantiationService.stub(IAccessibilityService, { isScreenReaderOptimized: () => false }); + instantiationService.stub(IContextKeyService, contextKeys); + instantiationService.stub(IEnvironmentService, { isBuilt: true }); + instantiationService.stub(IAgentHostFilterService, { selectedHost: undefined }); + instantiationService.stub(IWorkbenchLayoutService, layoutService); + instantiationService.stub(ISessionsHostLayoutService, { agentWorkbenchLayout: AgentWorkbenchLayout.Mobile }); + instantiationService.stub(ISessionsPartService, new class extends mock() { }()); + instantiationService.stub(ISessionsService, new class extends mock() { }()); + const help = new SessionsChatAccessibilityHelp(); + const helpProvider = store.add(help.getProvider(instantiationService)); + const helpContent = helpProvider.provideContent(); + trigger.focus(); + helpProvider.onClose(); + const accessibilityHelp = { + applies: contextKeys.contextMatchesRules(help.when), + search: helpContent.includes('When choosing a GitHub repository in the browser, search or enter a GitHub URL or owner/repository.'), + keyboard: helpContent.includes('Use the arrow keys to navigate results, Enter to select, and Escape to cancel.'), + verbosity: helpProvider.verbositySettingKey, + restoresSearchFocus: dom.getActiveElement() === input, + }; + + query(input, 'some-repo'); + await clock.tickAsync(300); + const searchState = { + rows: getRows(container).map(row => row.textContent), + newQuickInputs: countNewQuickInputs(), + }; + getRows(container)[0].click(); + await clock.tickAsync(180); + assert.deepStrictEqual({ + workspaceState, repositoryState, accessibilityHelp, searchState, queries, browseCalls, errors, + selection: await selected.p, + dialogs: container.querySelectorAll('[role="dialog"]').length, + focusRestored: dom.getActiveElement() === trigger, + newQuickInputs: countNewQuickInputs(), + }, { + workspaceState: { title: 'Choose Workspace', rows: ['Example/recent'], recentVisible: true, expanded: 'true', browseCalls: 0, newQuickInputs: 0 }, + repositoryState: { title: 'Choose repository', dialogs: 1, expanded: 'false', focused: true, newQuickInputs: 0 }, + accessibilityHelp: { applies: true, search: true, keyboard: true, verbosity: 'accessibility.verbosity.sessionsChat', restoresSearchFocus: true }, + searchState: { rows: ['Mixed.Owner/Some-Repo'], newQuickInputs: 0 }, + queries: ['', 'some-repo'], browseCalls: 1, errors: [], + selection: 'Mixed.Owner/Some-Repo', dialogs: 0, focusRestored: true, newQuickInputs: 0, + }); + }); + + test('shows loading and returns the original repository value from a touch selection', async () => { + const { picker, container, trigger } = createPicker(); + const repositories = new DeferredPromise(); + const result = picker.pickRepository(() => repositories.p); + const initial = { + message: container.querySelector('[role="status"]')?.textContent, + busy: container.querySelector('[role="list"]')?.getAttribute('aria-busy'), + focused: dom.getActiveElement() === getInput(container), + }; + await repositories.complete(['Zebra/Repo.Two', 'Mixed.Owner/Some-Repo']); + await clock.tickAsync(0); + const rows = getRows(container); + const labels = rows.map(row => row.textContent); + rows[0].dispatchEvent(new mainWindow.PointerEvent('click', { pointerType: 'touch', bubbles: true, cancelable: true })); + rows[1].click(); + await clock.tickAsync(180); + + assert.deepStrictEqual({ + initial, labels, selection: await result, + open: !!container.querySelector('.mobile-picker-sheet'), + focusRestored: dom.getActiveElement() === trigger, + }, { + initial: { message: 'Loading repositories…', busy: 'true', focused: true }, + labels: ['Mixed.Owner/Some-Repo', 'Zebra/Repo.Two'], + selection: 'Mixed.Owner/Some-Repo', + open: false, + focusRestored: true, + }); + }); + + test('supports arrow navigation, keyboard selection and focus containment', async () => { + const { picker, container, trigger } = createPicker(); + const result = picker.pickRepository(async () => ['owner/first', 'owner/last']); + await clock.tickAsync(0); + const input = getInput(container); + const rows = getRows(container); + const close = container.querySelector('.mobile-picker-sheet-done')!; + const dialog = container.querySelector('[role="dialog"]')!; + const accessible = { title: dialog.ariaLabel, modal: dialog.ariaModal, inputLabel: input.ariaLabel }; + const focus: boolean[] = []; + key(input, 'ArrowDown'); + focus.push(dom.getActiveElement() === rows[0]); + key(rows[0], 'End'); + focus.push(dom.getActiveElement() === rows[1]); + key(rows[1], 'Tab'); + focus.push(dom.getActiveElement() === close); + key(close, 'Tab', true); + focus.push(dom.getActiveElement() === rows[1]); + key(rows[1], 'Home'); + focus.push(dom.getActiveElement() === rows[0]); + key(rows[0], 'ArrowUp'); + focus.push(dom.getActiveElement() === input); + key(input, 'ArrowUp'); + focus.push(dom.getActiveElement() === rows[1]); + key(rows[1], 'Enter'); + await clock.tickAsync(180); + + assert.deepStrictEqual({ accessible, focus, selection: await result, focusRestored: dom.getActiveElement() === trigger }, { + accessible: { title: 'Choose repository', modal: 'true', inputLabel: 'Search repositories' }, + focus: [true, true, true, true, true, true, true], + selection: 'owner/last', + focusRestored: true, + }); + }); + + test('shows an empty state without accepting a nonexistent result', async () => { + const { picker, container } = createPicker(); + const result = picker.pickRepository(async () => []); + await clock.tickAsync(0); + key(getInput(container), 'Enter'); + const state = { + message: container.querySelector('[role="status"]')?.textContent, + busy: container.querySelector('[role="list"]')?.getAttribute('aria-busy'), + rows: getRows(container).length, + open: !!container.querySelector('.mobile-picker-sheet:not(.closing)'), + }; + container.querySelector('.mobile-picker-sheet-done')!.click(); + await clock.tickAsync(180); + assert.deepStrictEqual({ state, selection: await result }, { + state: { message: 'No repositories found. Try a different search.', busy: 'false', rows: 0, open: true }, + selection: undefined, + }); + }); + + test('cancels on each keystroke and ignores stale results before and after the debounce', async () => { + const { picker, container, errors } = createPicker(); + const requests: { query: string; token: CancellationToken; result: DeferredPromise }[] = []; + const result = picker.pickRepository((query, token) => { + const result = new DeferredPromise(); + requests.push({ query, token, result }); + return result.p; + }); + await clock.tickAsync(0); + const input = getInput(container); + query(input, 'old'); + const initiallyCancelled = requests[0].token.isCancellationRequested; + await requests[0].result.complete(['stale/initial']); + await clock.tickAsync(300); + query(input, 'latest'); + const oldCancelled = requests[1].token.isCancellationRequested; + await requests[1].result.complete(['stale/search']); + await clock.tickAsync(299); + const beforeDebounce = { queries: requests.map(request => request.query), rows: getRows(container).length }; + await clock.tickAsync(1); + await requests[2].result.complete(['current/result']); + await clock.tickAsync(0); + const labels = getRows(container).map(row => row.textContent); + key(input, 'Enter'); + await clock.tickAsync(180); + + assert.deepStrictEqual({ + initiallyCancelled, oldCancelled, beforeDebounce, labels, + queries: requests.map(request => request.query), errors, selection: await result, + }, { + initiallyCancelled: true, oldCancelled: true, + beforeDebounce: { queries: ['', 'old'], rows: 0 }, + labels: ['current/result'], queries: ['', 'old', 'latest'], errors: [], + selection: 'current/result', + }); + }); + + test('removes stale row handlers immediately when the query changes', async () => { + const { picker, container } = createPicker(); + const next = new DeferredPromise(); + const result = picker.pickRepository(query => query ? next.p : Promise.resolve(['previous/repository'])); + await clock.tickAsync(0); + const previous = getRows(container)[0]; + const input = getInput(container); + query(input, 'new'); + previous.click(); + key(input, 'Enter'); + const remainedOpen = !!container.querySelector('.mobile-picker-sheet:not(.closing)'); + await clock.tickAsync(300); + await next.complete(['new/repository']); + await clock.tickAsync(0); + getRows(container)[0].click(); + await clock.tickAsync(180); + assert.deepStrictEqual({ remainedOpen, selection: await result }, { remainedOpen: true, selection: 'new/repository' }); + }); + + test('does not open a sheet or start a request when already cancelled or disposed', async () => { + const { picker, container } = createPicker(); + let loads = 0; + const load = async () => { loads++; return ['owner/repo']; }; + const cancelled = await picker.pickRepository(load, CancellationToken.Cancelled); + picker.dispose(); + const disposed = await picker.pickRepository(load); + assert.deepStrictEqual({ cancelled, disposed, loads, open: !!container.querySelector('.mobile-picker-sheet') }, { + cancelled: undefined, disposed: undefined, loads: 0, open: false, + }); + }); + + test('cancellation before the initial request runs cancels the scheduled load', async () => { + const { picker, container } = createPicker(); + const cancellation = store.add(new CancellationTokenSource()); + let loads = 0; + const result = picker.pickRepository(async () => { loads++; return []; }, cancellation.token); + cancellation.cancel(); + await clock.tickAsync(180); + assert.deepStrictEqual({ selection: await result, loads, open: !!container.querySelector('.mobile-picker-sheet') }, { + selection: undefined, loads: 0, open: false, + }); + }); + + for (const dismissal of ['token', 'dispose', 'escape', 'backdrop', 'cancel'] as const) { + test(`${dismissal} cancels an unresolved load and removes input handlers`, async () => { + const { picker, container, trigger, errors } = createPicker(); + const cancellation = store.add(new CancellationTokenSource()); + const pending = new DeferredPromise(); + let loads = 0; + let requestToken = CancellationToken.None; + const result = picker.pickRepository((_query, token) => { + loads++; + requestToken = token; + return pending.p; + }, cancellation.token); + await clock.tickAsync(0); + const input = getInput(container); + switch (dismissal) { + case 'token': cancellation.cancel(); break; + case 'dispose': picker.dispose(); break; + case 'escape': key(input, 'Escape'); break; + case 'backdrop': container.querySelector('.mobile-picker-sheet-backdrop')!.click(); break; + case 'cancel': container.querySelector('.mobile-picker-sheet-done')!.click(); break; + } + const immediatelyCancelled = requestToken.isCancellationRequested; + query(input, 'must not load'); + await clock.tickAsync(500); + const selection = await result; + await pending.complete(['late/repository']); + await clock.tickAsync(0); + + assert.deepStrictEqual({ + immediatelyCancelled, selection, loads, errors, + open: !!container.querySelector('.mobile-picker-sheet'), + focusRestored: dom.getActiveElement() === trigger, + }, { immediatelyCancelled: true, selection: undefined, loads: 1, errors: [], open: false, focusRestored: true }); + }); + } + + test('dismissal cancels the pending search debounce', async () => { + const { picker, container } = createPicker(); + const queries: string[] = []; + const result = picker.pickRepository(async query => { queries.push(query); return []; }); + await clock.tickAsync(0); + query(getInput(container), 'never searched'); + container.querySelector('.mobile-picker-sheet-done')!.click(); + await clock.tickAsync(500); + assert.deepStrictEqual({ queries, selection: await result }, { queries: [''], selection: undefined }); + }); + + test('shows and logs load failures, then clears the error when retrying', async () => { + const { picker, container, errors } = createPicker(); + const failure = new Error('Repository request failed'); + let attempts = 0; + const result = picker.pickRepository(async () => { + if (++attempts === 1) { + throw failure; + } + return ['owner/recovered']; + }); + await clock.tickAsync(0); + const failedState = { + message: container.querySelector('[role="alert"]')?.textContent, + busy: container.querySelector('[role="list"]')?.getAttribute('aria-busy'), + rows: getRows(container).map(row => row.textContent), + }; + getRows(container)[0].click(); + await clock.tickAsync(0); + const recoveredState = { errors: container.querySelectorAll('[role="alert"]').length, rows: getRows(container).map(row => row.textContent) }; + getRows(container)[0].click(); + await clock.tickAsync(180); + + assert.deepStrictEqual({ failedState, errors, attempts, recoveredState, selection: await result }, { + failedState: { + message: 'Could not load repositories. Check your GitHub sign-in and connection, then try again.', + busy: 'false', rows: ['Try again'], + }, + errors: [{ message: 'Error fetching repositories', error: failure }], + attempts: 2, recoveredState: { errors: 0, rows: ['owner/recovered'] }, + selection: 'owner/recovered', + }); + }); + + test('a cancelled request rejection dismisses rather than leaving a loading sheet', async () => { + const { picker, container, errors } = createPicker(); + const result = picker.pickRepository(async () => { throw new CancellationError(); }); + await clock.tickAsync(180); + assert.deepStrictEqual({ selection: await result, errors, open: !!container.querySelector('.mobile-picker-sheet') }, { + selection: undefined, errors: [], open: false, + }); + }); + + test('a stale failed request cannot replace current results or report an error', async () => { + const { picker, container, errors } = createPicker(); + const initial = new DeferredPromise(); + const result = picker.pickRepository(query => query ? Promise.resolve(['current/repository']) : initial.p); + await clock.tickAsync(0); + query(getInput(container), 'current'); + await clock.tickAsync(300); + await initial.error(new Error('Stale failure')); + await clock.tickAsync(0); + const rows = getRows(container).map(row => row.textContent); + getRows(container)[0].click(); + await clock.tickAsync(180); + assert.deepStrictEqual({ rows, errors, selection: await result }, { + rows: ['current/repository'], errors: [], selection: 'current/repository', + }); + }); + + test('synchronous cancellation inside the loader disposes all sheet handlers', async () => { + const { picker, container } = createPicker(); + const cancellation = store.add(new CancellationTokenSource()); + let loads = 0; + let requestToken = CancellationToken.None; + const result = picker.pickRepository((_query, token) => { + loads++; + requestToken = token; + cancellation.cancel(); + return Promise.resolve([]); + }, cancellation.token); + const input = getInput(container); + await clock.tickAsync(0); + query(input, 'must not load'); + await clock.tickAsync(500); + assert.deepStrictEqual({ + selection: await result, loads, cancelled: requestToken.isCancellationRequested, + open: !!container.querySelector('.mobile-picker-sheet'), + }, { selection: undefined, loads: 1, cancelled: true, open: false }); + }); + + test('replacement keeps the new sheet focused and restores the original trigger', async () => { + const { picker, container, trigger } = createPicker(); + const first = new DeferredPromise(); + let firstToken = CancellationToken.None; + const firstPick = picker.pickRepository((_query, token) => { firstToken = token; return first.p; }); + await clock.tickAsync(0); + const secondPick = picker.pickRepository(async () => ['owner/second']); + await clock.tickAsync(180); + const firstSelection = await firstPick; + const secondFocused = dom.getActiveElement() === getInput(container); + getRows(container)[0].click(); + await clock.tickAsync(180); + await first.complete(['owner/first']); + assert.deepStrictEqual({ + firstSelection, firstCancelled: firstToken.isCancellationRequested, secondFocused, + secondSelection: await secondPick, focusRestored: dom.getActiveElement() === trigger, + }, { + firstSelection: undefined, firstCancelled: true, secondFocused: true, + secondSelection: 'owner/second', focusRestored: true, + }); + }); + + test('Enter while composing search text does not accept a repository', async () => { + const { picker, container } = createPicker(); + const result = picker.pickRepository(async () => ['owner/repository']); + await clock.tickAsync(0); + const input = getInput(container); + input.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: 'Enter', isComposing: true, bubbles: true, cancelable: true })); + const remainedOpen = !!container.querySelector('.mobile-picker-sheet:not(.closing)'); + key(input, 'Enter'); + await clock.tickAsync(180); + assert.deepStrictEqual({ remainedOpen, selection: await result }, { remainedOpen: true, selection: 'owner/repository' }); + }); +}); diff --git a/src/vs/sessions/contrib/modernUI/test/browser/frostedGlass.test.ts b/src/vs/sessions/contrib/modernUI/test/browser/frostedGlass.test.ts index d34b4c569f06..46d488d01ecf 100644 --- a/src/vs/sessions/contrib/modernUI/test/browser/frostedGlass.test.ts +++ b/src/vs/sessions/contrib/modernUI/test/browser/frostedGlass.test.ts @@ -5,9 +5,21 @@ import assert from 'assert'; import { getWindow } from '../../../../../base/browser/dom.js'; +import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; +import { timeout } from '../../../../../base/common/async.js'; import { Color, RGBA } from '../../../../../base/common/color.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { HoverWidget } from '../../../../../platform/hover/browser/hoverWidget.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { IMarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js'; import { append, createFrostedGlassOverlays, readColor, supportsGlass } from '../../../../../workbench/contrib/modernUI/test/browser/frostedGlassTestUtils.js'; +import '../../../../../workbench/contrib/sessions/browser/media/sessionsList.css'; import '../../../../browser/media/style.css'; import '../../../automations/browser/media/automationDialog.css'; import '../../../agentFeedback/browser/media/agentFeedbackEditorWidget.css'; @@ -38,6 +50,278 @@ suite('Agents frosted glass styles', () => { return { card, content }; } + function createSessionHover(content: HTMLElement) { + const root = append(document.body, 'monaco-workbench agent-sessions-workbench'); + store.add(toDisposable(() => root.remove())); + root.style.setProperty('--vscode-editorHoverWidget-background', '#242424'); + root.style.setProperty('--vscode-editorHoverWidget-border', '#5a7b9d'); + root.style.setProperty('--vscode-cornerRadius-large', '8px'); + + const target = append(root, 'target'); + target.style.cssText = 'position: fixed; top: 100px; left: 100px; width: 50px; height: 20px;'; + const services = store.add(new TestInstantiationService()); + services.stub(IConfigurationService, new TestConfigurationService()); + services.stub(IAccessibilityService, new TestAccessibilityService()); + services.stub(IKeybindingService, { lookupKeybinding: () => undefined }); + services.stub(IMarkdownRendererService, {}); + const hover = store.add(services.createInstance(HoverWidget, { + target, + content, + additionalClasses: ['sessions-list-hover'], + appearance: { showPointer: true }, + position: { hoverPosition: HoverPosition.RIGHT, forcePosition: true }, + persistence: { hideOnHover: false } + })); + hover.render(root); + const container = hover.domNode.parentElement!; + container.style.cssText += `position: fixed; left: ${hover.x}px; top: ${hover.y}px;`; + const scrollable = hover.domNode.querySelector('.monaco-scrollable-element')!; + return { root, hover, scrollable, container }; + } + + test('aligns the frosted session hover with shared bordered and borderless geometry', () => { + const content = document.createElement('div'); + content.textContent = 'Session details'; + const { root, hover, scrollable } = createSessionHover(content); + const state = () => { + const targetWindow = getWindow(hover.domNode); + const outer = targetWindow.getComputedStyle(hover.domNode); + const glass = targetWindow.getComputedStyle(hover.domNode, '::before'); + const bounds = hover.domNode.getBoundingClientRect(); + const glassWidth = parseFloat(glass.width) + parseFloat(glass.borderLeftWidth) + parseFloat(glass.borderRightWidth); + const glassHeight = parseFloat(glass.height) + parseFloat(glass.borderTopWidth) + parseFloat(glass.borderBottomWidth); + return { + outerRadius: outer.borderTopLeftRadius, + outerBorder: outer.borderTopStyle === 'none' ? undefined : outer.borderTopColor, + outerBorderStyle: outer.borderTopStyle, + outerBorderWidth: outer.borderTopWidth, + outerOverflow: outer.overflow, + glassRadius: glass.borderTopLeftRadius, + glassBorder: glass.borderTopColor, + glassBorderStyle: glass.borderTopStyle, + glassBorderWidth: glass.borderTopWidth, + glassClip: glass.clipPath, + glassBackgroundClip: glass.backgroundClip, + glassFilter: glass.backdropFilter, + sharesBorderBox: Math.abs(glassWidth - bounds.width) < 0.01 && Math.abs(glassHeight - bounds.height) < 0.01, + }; + }; + const original = { + outerBorder: getWindow(hover.domNode).getComputedStyle(hover.domNode).borderTopColor, + outerOverflow: getWindow(hover.domNode).getComputedStyle(hover.domNode).overflow, + innerRadius: getWindow(scrollable).getComputedStyle(scrollable).borderTopLeftRadius, + }; + root.classList.add('modern-ui-frosted-glass'); + + if (supportsGlass(root)) { + const radii = [0, 8, 12]; + const modes = [false, true]; + assert.deepStrictEqual(modes.flatMap(modernUI => { + root.classList.toggle('modern-ui', modernUI); + return radii.map(radius => { + root.style.setProperty('--vscode-cornerRadius-large', `${radius}px`); + return state(); + }); + }), modes.flatMap(() => radii.map(radius => ({ + outerRadius: `${radius}px`, + outerBorder: 'rgb(90, 123, 157)', + outerBorderStyle: 'solid', + outerBorderWidth: '1px', + outerOverflow: 'hidden', + glassRadius: `${radius}px`, + glassBorder: 'rgba(0, 0, 0, 0)', + glassBorderStyle: 'solid', + glassBorderWidth: '1px', + glassClip: 'padding-box', + glassBackgroundClip: 'padding-box', + glassFilter: 'blur(12px)', + sharesBorderBox: true, + })))); + root.style.setProperty('--vscode-editorHoverWidget-border', 'initial'); + assert.deepStrictEqual(state(), { + outerRadius: '12px', + outerBorder: undefined, + outerBorderStyle: 'none', + outerBorderWidth: '0px', + outerOverflow: 'hidden', + glassRadius: '12px', + glassBorder: 'rgba(0, 0, 0, 0)', + glassBorderStyle: 'none', + glassBorderWidth: '0px', + glassClip: 'padding-box', + glassBackgroundClip: 'padding-box', + glassFilter: 'blur(12px)', + sharesBorderBox: true, + }); + } + + root.style.setProperty('--vscode-cornerRadius-large', '8px'); + root.style.setProperty('--vscode-editorHoverWidget-border', '#5a7b9d'); + root.classList.remove('modern-ui-frosted-glass', 'modern-ui'); + assert.deepStrictEqual({ + outerBorder: getWindow(hover.domNode).getComputedStyle(hover.domNode).borderTopColor, + outerOverflow: getWindow(hover.domNode).getComputedStyle(hover.domNode).overflow, + innerRadius: getWindow(scrollable).getComputedStyle(scrollable).borderTopLeftRadius, + }, original); + }); + + for (const themeClass of ['hc-black', 'hc-light']) { + test(`keeps the session hover unchanged in ${themeClass}`, () => { + const { root, hover, scrollable } = createSessionHover(document.createElement('div')); + root.classList.add(themeClass); + const state = () => ({ + overflow: getWindow(hover.domNode).getComputedStyle(hover.domNode).overflow, + border: getWindow(hover.domNode).getComputedStyle(hover.domNode).borderTopColor, + innerRadius: getWindow(scrollable).getComputedStyle(scrollable).borderTopLeftRadius, + glassFilter: getWindow(hover.domNode).getComputedStyle(hover.domNode, '::before').backdropFilter, + }); + const original = state(); + root.classList.add('modern-ui-frosted-glass'); + assert.deepStrictEqual(state(), original); + }); + } + + test('keeps session hover links, scrolling, pointer, and fixed descendants usable with glass', async () => { + const content = document.createElement('div'); + content.style.cssText = 'width: 220px; height: 1200px;'; + const link = document.createElement('a'); + link.href = '#session-link'; + link.textContent = 'Open session'; + content.appendChild(link); + const fixed = append(content, 'fixed-descendant'); + fixed.style.cssText = 'position: fixed; left: 15px; top: 20px;'; + const { root, hover, scrollable, container } = createSessionHover(content); + const pointer = container.querySelector('.workbench-hover-pointer')!; + const pointerPosition = { className: pointer.className, top: pointer.style.top, left: pointer.style.left }; + const focusOutline = () => { + const style = getWindow(link).getComputedStyle(link); + return { + color: style.outlineColor, + style: style.outlineStyle, + width: style.outlineWidth, + offset: style.outlineOffset, + }; + }; + link.focus(); + const originalFocusOutline = focusOutline(); + root.classList.add('modern-ui-frosted-glass'); + const rect = link.getBoundingClientRect(); + const linkHit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2) === link; + let clicked = false; + link.addEventListener('click', event => { event.preventDefault(); clicked = true; }, { once: true }); + link.focus(); + link.click(); + const contents = hover.domNode.querySelector('.monaco-hover-content')!; + const wheel = new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: 100 }); + // Chromium's synthetic wheel event reports the legacy delta with the opposite sign. + Object.defineProperty(wheel, 'wheelDeltaY', { value: -120 }); + contents.dispatchEvent(wheel); + const scrollAfterWheel = contents.scrollTop; + scrollable.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + await timeout(0); + const slider = hover.domNode.querySelector('.scrollbar.vertical .slider')!; + const sliderRect = slider.getBoundingClientRect(); + const sliderX = sliderRect.left + sliderRect.width / 2; + const sliderY = sliderRect.top + sliderRect.height / 2; + const scrollbarHit = document.elementFromPoint(sliderX, sliderY) === slider; + const pointerEvent = { bubbles: true, cancelable: true, pointerId: 7, pointerType: 'mouse', button: 0, buttons: 1, clientX: sliderX }; + slider.dispatchEvent(new PointerEvent('pointerdown', { ...pointerEvent, clientY: sliderY })); + slider.dispatchEvent(new PointerEvent('pointermove', { ...pointerEvent, clientY: sliderY + 20 })); + slider.dispatchEvent(new PointerEvent('pointerup', { ...pointerEvent, clientY: sliderY + 20, buttons: 0 })); + + assert.deepStrictEqual({ + linkHit, + linkFocused: document.activeElement === link, + focusOutline: focusOutline(), + clicked, + scrolled: scrollAfterWheel > 0, + scrollbarHit, + dragged: contents.scrollTop > scrollAfterWheel, + pointerPosition: { className: pointer.className, top: pointer.style.top, left: pointer.style.left }, + fixedPosition: { left: fixed.getBoundingClientRect().left, top: fixed.getBoundingClientRect().top }, + }, { + linkHit: true, + linkFocused: true, + focusOutline: originalFocusOutline, + clicked: true, + scrolled: true, + scrollbarHit: true, + dragged: true, + pointerPosition, + fixedPosition: { left: 15, top: 20 }, + }); + }); + + (supportsGlass(document.body) ? test : test.skip)('aligns feedback card glass with its default, focused, and borderless curves', () => { + const { root } = createOverlays(); + root.style.setProperty('--vscode-focusBorder', '#ffdd11'); + const { card } = createCommentCard(root); + card.style.width = '120px'; + card.style.height = '60px'; + root.classList.add('modern-ui-frosted-glass'); + + const state = () => { + const targetWindow = getWindow(card); + const host = targetWindow.getComputedStyle(card); + const paint = targetWindow.getComputedStyle(card, '::before'); + const bounds = card.getBoundingClientRect(); + const paintWidth = parseFloat(paint.width) + parseFloat(paint.borderLeftWidth) + parseFloat(paint.borderRightWidth); + const paintHeight = parseFloat(paint.height) + parseFloat(paint.borderTopWidth) + parseFloat(paint.borderBottomWidth); + return { + hostRadius: host.borderTopLeftRadius, + hostBorder: `${host.borderTopStyle} ${host.borderTopWidth}`, + hostBorderColor: host.borderTopStyle === 'none' ? undefined : host.borderTopColor, + paintRadius: paint.borderTopLeftRadius, + paintBorder: `${paint.borderTopStyle} ${paint.borderTopWidth}`, + paintBorderColor: paint.borderTopColor, + paintClip: paint.clipPath, + paintBackgroundClip: paint.backgroundClip, + sharesBorderBox: Math.abs(paintWidth - bounds.width) < 0.01 && Math.abs(paintHeight - bounds.height) < 0.01, + }; + }; + const regular = state(); + card.classList.add('focused'); + const focused = state(); + card.classList.remove('focused'); + root.style.setProperty('--vscode-editorWidget-border', 'initial'); + + assert.deepStrictEqual({ regular, focused, borderless: state() }, { + regular: { + hostRadius: '8px', + hostBorder: 'solid 1px', + hostBorderColor: 'rgb(90, 123, 157)', + paintRadius: '8px', + paintBorder: 'solid 1px', + paintBorderColor: 'rgba(0, 0, 0, 0)', + paintClip: 'padding-box', + paintBackgroundClip: 'padding-box', + sharesBorderBox: true, + }, + focused: { + hostRadius: '8px', + hostBorder: 'solid 1px', + hostBorderColor: 'rgb(255, 221, 17)', + paintRadius: '8px', + paintBorder: 'solid 1px', + paintBorderColor: 'rgba(0, 0, 0, 0)', + paintClip: 'padding-box', + paintBackgroundClip: 'padding-box', + sharesBorderBox: true, + }, + borderless: { + hostRadius: '8px', + hostBorder: 'none 0px', + hostBorderColor: undefined, + paintRadius: '8px', + paintBorder: 'none 0px', + paintBorderColor: 'rgba(0, 0, 0, 0)', + paintClip: 'padding-box', + paintBackgroundClip: 'padding-box', + sharesBorderBox: true, + }, + }); + }); + for (const customBackground of [undefined, '#304050']) { test(`frosts comment cards using their ${customBackground ? 'custom' : 'menu'} background and configured opacity`, () => { const { root } = createOverlays(); diff --git a/src/vs/sessions/contrib/onboardingTours/browser/automationsTourContribution.ts b/src/vs/sessions/contrib/onboardingTours/browser/automationsTourContribution.ts new file mode 100644 index 000000000000..a46b037af5a7 --- /dev/null +++ b/src/vs/sessions/contrib/onboardingTours/browser/automationsTourContribution.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { derived } from '../../../../base/common/observable.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { onboardingScenarioRegistry } from '../../../../workbench/contrib/onboarding/common/onboardingRegistry.js'; +import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../../../../workbench/contrib/sessions/browser/automationsConstants.js'; +import { ICustomViewService } from '../../../../workbench/contrib/sessions/browser/customView.js'; +import { createAutomationsTour } from './tours/automationsTour.js'; + +export class AutomationsTourContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.contrib.onboardingTours.automationsTour'; + + constructor( + @ICustomViewService customViewService: ICustomViewService, + ) { + super(); + + const visible = derived(this, reader => customViewService.activeCustomView.read(reader)?.id === AUTOMATIONS_CUSTOM_VIEW_ID); + this._register(onboardingScenarioRegistry.register(createAutomationsTour(visible))); + } +} + +registerWorkbenchContribution2(AutomationsTourContribution.ID, AutomationsTourContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/sessions/contrib/onboardingTours/browser/onboardingTours.contribution.ts b/src/vs/sessions/contrib/onboardingTours/browser/onboardingTours.contribution.ts index 437cf9c7e195..ab95b0dbc449 100644 --- a/src/vs/sessions/contrib/onboardingTours/browser/onboardingTours.contribution.ts +++ b/src/vs/sessions/contrib/onboardingTours/browser/onboardingTours.contribution.ts @@ -9,6 +9,7 @@ // `vs/workbench/contrib/onboarding` and are booted from the workbench // contribution imported in the entry point. import './agentHostReadinessContext.js'; +import './automationsTourContribution.js'; import './newSessionTourContribution.js'; import './newSessionViewV2TourContribution.js'; import './newSessionViewV3TourContribution.js'; diff --git a/src/vs/sessions/contrib/onboardingTours/browser/tours/automationsTour.ts b/src/vs/sessions/contrib/onboardingTours/browser/tours/automationsTour.ts new file mode 100644 index 000000000000..2a19cd6bd455 --- /dev/null +++ b/src/vs/sessions/contrib/onboardingTours/browser/tours/automationsTour.ts @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IObservable } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { EditorPartModalVisibleContext } from '../../../../../workbench/common/contextkeys.js'; +import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { ChatAutomationsEnabledContext } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; +import { ISpotlightPayload, SPOTLIGHT_PRESENTATION_KIND } from '../../../../../workbench/contrib/onboarding/browser/spotlight/spotlightTypes.js'; +import { onboardingScenarioRegistry } from '../../../../../workbench/contrib/onboarding/common/onboardingRegistry.js'; +import { IOnboardingScenario } from '../../../../../workbench/contrib/onboarding/common/onboardingScenario.js'; +import { AUTOMATIONS_TOUR_SEEN_KEY } from '../../../../../workbench/contrib/sessions/browser/automationsConstants.js'; +import { SessionsWelcomeVisibleContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { ChatEntitlementContextKeys } from '../../../../../workbench/services/chat/common/chatEntitlementService.js'; +import { NewSessionOnboardingHandoffContext } from '../../../../common/agentsWindowContextKeys.js'; + +export const AUTOMATIONS_TOUR_ID = 'sessions.onboarding.automations'; + +onboardingScenarioRegistry.registerDescriptor({ id: AUTOMATIONS_TOUR_ID }); + +/** Introduces agent-assisted creation once, using the target shared by both catalogue states. */ +export function createAutomationsTour(signal: IObservable): IOnboardingScenario { + return { + id: AUTOMATIONS_TOUR_ID, + seenKey: AUTOMATIONS_TOUR_SEEN_KEY, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + ChatAutomationsEnabledContext, + ChatEntitlementContextKeys.Entitlement.signedOut.toNegated(), + EditorPartModalVisibleContext.toNegated(), + NewSessionOnboardingHandoffContext.toNegated(), + SessionsWelcomeVisibleContext.toNegated(), + ), + trigger: { kind: 'observable', signal }, + presentation: { + kind: SPOTLIGHT_PRESENTATION_KIND, + payload: { + steps: [{ + id: 'createWithAgent', + targetId: 'sessions.automations.create', + title: localize('sessions.onboarding.automations.title', "Create with agent"), + description: localize('sessions.onboarding.automations.description', "Closes Automations and starts a new session draft. Describe what you want automated and the agent sets it up."), + nextButtonLabel: localize('sessions.onboarding.automations.gotIt', "Got It"), + allowTargetInteraction: true, + advanceOnTargetClick: true, + hideNext: false, + }], + }, + }, + }; +} diff --git a/src/vs/sessions/contrib/onboardingTours/test/browser/automationsTour.test.ts b/src/vs/sessions/contrib/onboardingTours/test/browser/automationsTour.test.ts new file mode 100644 index 000000000000..ff730c4c6a1a --- /dev/null +++ b/src/vs/sessions/contrib/onboardingTours/test/browser/automationsTour.test.ts @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { Event } from '../../../../../base/common/event.js'; +import { observableValue } from '../../../../../base/common/observable.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; +import { InMemoryStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { EditorPartModalVisibleContext } from '../../../../../workbench/common/contextkeys.js'; +import { Memento } from '../../../../../workbench/common/memento.js'; +import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { ChatAutomationsEnabledContext } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; +import { onboardingScenarioRegistry } from '../../../../../workbench/contrib/onboarding/common/onboardingRegistry.js'; +import { OnboardingScenarioService } from '../../../../../workbench/contrib/onboarding/browser/onboardingService.js'; +import { onboardingPresentationRegistry } from '../../../../../workbench/contrib/onboarding/common/onboardingPresentation.js'; +import { OnboardingDismissReason, OnboardingOutcome } from '../../../../../workbench/contrib/onboarding/common/onboardingScenario.js'; +import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../../../../../workbench/contrib/sessions/browser/automationsConstants.js'; +import { ICustomViewDescriptor, ICustomViewService } from '../../../../../workbench/contrib/sessions/browser/customView.js'; +import { SessionsWelcomeVisibleContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { ChatEntitlementContextKeys } from '../../../../../workbench/services/chat/common/chatEntitlementService.js'; +import { NullWorkbenchAssignmentService } from '../../../../../workbench/services/assignment/test/common/nullAssignmentService.js'; +import { TestLifecycleService } from '../../../../../workbench/test/common/workbenchTestServices.js'; +import { NewSessionOnboardingHandoffContext } from '../../../../common/agentsWindowContextKeys.js'; +import { AutomationsTourContribution } from '../../browser/automationsTourContribution.js'; +import { AUTOMATIONS_TOUR_ID, createAutomationsTour } from '../../browser/tours/automationsTour.js'; + +suite('AutomationsTour', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + teardown(() => Memento.clear(StorageScope.APPLICATION)); + + test('a previously shown checklist tour suppresses the automatic introduction', async () => { + const storage = disposables.add(new InMemoryStorageService()); + const configuration = new TestConfigurationService(); + disposables.add(configuration.onDidChangeConfigurationEmitter); + const context = disposables.add(new ContextKeyService(configuration)); + ChatContextKeys.enabled.bindTo(context).set(true); + ChatAutomationsEnabledContext.bindTo(context).set(true); + const visible = observableValue('automationsVisible', false); + const intro = createAutomationsTour(visible); + const runs: string[] = []; + const kind = 'automations-introduction-test'; + disposables.add(onboardingPresentationRegistry.register({ + kind, + run: async scenario => { + runs.push(scenario.id); + return { outcome: OnboardingOutcome.Completed, shown: true, dismissReason: OnboardingDismissReason.Completed, lastStepIndex: 0, stepCount: 1 }; + }, + })); + const legacyTourId = 'sessions.getStarted.showMe.automation'; + disposables.add(onboardingScenarioRegistry.register({ + id: legacyTourId, + repeatable: true, + trigger: { kind: 'command', commandId: legacyTourId }, + presentation: { kind, payload: undefined }, + })); + disposables.add(onboardingScenarioRegistry.register({ ...intro, presentation: { ...intro.presentation, kind } })); + const service = disposables.add(new OnboardingScenarioService( + storage, context, configuration, disposables.add(new TestLifecycleService()), new NullWorkbenchAssignmentService(), + new class extends mock() { override publicLog2(): void { } }(), + new class extends mock() { override readonly hasDialog = false; override readonly onDidShowDialog = Event.None; }(), + )); + service.start(); + await service.runScenario(legacyTourId); + visible.set(true, undefined); + await timeout(0); + + assert.deepStrictEqual({ runs, introduced: service.hasBeenShown(AUTOMATIONS_TOUR_ID) }, { + runs: [legacyTourId], introduced: true, + }); + }); + + test('is eligible only while Automations is open, including a restored opening', () => { + const automations = upcastPartial({ id: AUTOMATIONS_CUSTOM_VIEW_ID }); + const activeCustomView = observableValue('activeCustomView', automations); + const contribution = disposables.add(new AutomationsTourContribution(new class extends mock() { + override readonly activeCustomView = activeCustomView; + }())); + const scenario = onboardingScenarioRegistry.getScenario(AUTOMATIONS_TOUR_ID)!; + const triggered = () => scenario.trigger.kind === 'observable' && scenario.trigger.signal.get(); + const restored = triggered(); + activeCustomView.set(undefined, undefined); + const hidden = triggered(); + activeCustomView.set(upcastPartial({ id: 'other' }), undefined); + const otherView = triggered(); + activeCustomView.set(automations, undefined); + const reopened = triggered(); + contribution.dispose(); + + assert.deepStrictEqual({ restored, hidden, otherView, reopened, unregistered: !onboardingScenarioRegistry.getScenario(AUTOMATIONS_TOUR_ID) }, { + restored: true, hidden: false, otherView: false, reopened: true, unregistered: true, + }); + }); + + test('suppresses the introduction when AI or Automations is disabled, signed out, or blocked', () => { + const configuration = new TestConfigurationService(); + disposables.add(configuration.onDidChangeConfigurationEmitter); + const context = disposables.add(new ContextKeyService(configuration)); + const enabled = ChatContextKeys.enabled.bindTo(context); + const automationsEnabled = ChatAutomationsEnabledContext.bindTo(context); + enabled.set(true); + automationsEnabled.set(true); + const blockers = [ + ChatEntitlementContextKeys.Entitlement.signedOut.bindTo(context), + EditorPartModalVisibleContext.bindTo(context), + NewSessionOnboardingHandoffContext.bindTo(context), + SessionsWelcomeVisibleContext.bindTo(context), + ]; + const scenario = createAutomationsTour(observableValue('visible', true)); + const eligible = () => context.contextMatchesRules(scenario.when); + const initial = eligible(); + enabled.set(false); + const aiDisabled = eligible(); + enabled.set(true); + automationsEnabled.set(false); + const automationsDisabled = eligible(); + automationsEnabled.set(true); + const blocked = blockers.map(blocker => { + blocker.set(true); + const result = eligible(); + blocker.set(false); + return result; + }); + + assert.deepStrictEqual({ initial, aiDisabled, automationsDisabled, blocked, unblocked: eligible() }, { + initial: true, aiDisabled: false, automationsDisabled: false, blocked: [false, false, false, false], unblocked: true, + }); + }); +}); diff --git a/src/vs/sessions/contrib/onboardingTours/test/browser/newSessionViewV3Prompt.test.ts b/src/vs/sessions/contrib/onboardingTours/test/browser/newSessionViewV3Prompt.test.ts index 6ec25867e4d0..1768d777cf2c 100644 --- a/src/vs/sessions/contrib/onboardingTours/test/browser/newSessionViewV3Prompt.test.ts +++ b/src/vs/sessions/contrib/onboardingTours/test/browser/newSessionViewV3Prompt.test.ts @@ -364,24 +364,24 @@ suite('NewSessionViewV3Prompt', () => { { kind: 'resolved', options: [ - { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, - { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, + { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issues', color: 'charts.green' } }, + { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issues', color: 'charts.green' } }, STANDARD_OPTIONS[0], ], }, { kind: 'resolved', options: [ - { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, - { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, + { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issues', color: 'charts.green' } }, + { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issues', color: 'charts.green' } }, { title: 'Resolve conflicts #20', description: 'Conflicted PR', icon: { id: 'git-pull-request-error', color: 'charts.orange' } }, ], }, { kind: 'resolved', options: [ - { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, - { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }, + { title: 'Tackle issue #14', description: 'Newest assigned issue', icon: { id: 'issues', color: 'charts.green' } }, + { title: 'Tackle issue #12', description: 'Older assigned issue', icon: { id: 'issues', color: 'charts.green' } }, { title: 'Resolve conflicts #20', description: 'Conflicted PR', icon: { id: 'git-pull-request-error', color: 'charts.orange' } }, ], }, @@ -508,7 +508,7 @@ suite('NewSessionViewV3Prompt', () => { { kind: 'resolved', options: [ - { title: 'Tackle issue #7', description: 'Ready issue', icon: { id: 'issue-opened', color: 'charts.green' } }, + { title: 'Tackle issue #7', description: 'Ready issue', icon: { id: 'issues', color: 'charts.green' } }, STANDARD_OPTIONS[0], STANDARD_OPTIONS[1], ], @@ -516,7 +516,7 @@ suite('NewSessionViewV3Prompt', () => { { kind: 'resolved', options: [ - { title: 'Tackle issue #7', description: 'Ready issue', icon: { id: 'issue-opened', color: 'charts.green' } }, + { title: 'Tackle issue #7', description: 'Ready issue', icon: { id: 'issues', color: 'charts.green' } }, STANDARD_OPTIONS[0], STANDARD_OPTIONS[1], ], @@ -557,7 +557,7 @@ suite('NewSessionViewV3Prompt', () => { }, { reviewLookupNeverResolves: true }, ); - const issueOption = { title: 'Tackle issue #14', description: 'Assigned issue', icon: { id: 'issue-opened', color: 'charts.green' } }; + const issueOption = { title: 'Tackle issue #14', description: 'Assigned issue', icon: { id: 'issues', color: 'charts.green' } }; const ciOption = { title: 'Fix CI #21', description: 'CI is failing', icon: { id: 'git-pull-request-error', color: 'charts.orange' } }; assert.deepStrictEqual({ @@ -648,7 +648,7 @@ suite('NewSessionViewV3Prompt', () => { { pullRequests: [], issues: [issue('Unknown linkage', '2026-08-07T13:00:00Z', 9)] }, { issueLinkageLookupNeverResolves: true }, ); - const issueOption = { title: 'Tackle issue #9', description: 'Unknown linkage', icon: { id: 'issue-opened', color: 'charts.green' } }; + const issueOption = { title: 'Tackle issue #9', description: 'Unknown linkage', icon: { id: 'issues', color: 'charts.green' } }; assert.deepStrictEqual({ states: summarizePromptOptionStates(result.promptOptionStates), diff --git a/src/vs/sessions/contrib/onboardingTours/test/browser/onboardingTourDescriptors.test.ts b/src/vs/sessions/contrib/onboardingTours/test/browser/onboardingTourDescriptors.test.ts index fbc766978b83..571961155a28 100644 --- a/src/vs/sessions/contrib/onboardingTours/test/browser/onboardingTourDescriptors.test.ts +++ b/src/vs/sessions/contrib/onboardingTours/test/browser/onboardingTourDescriptors.test.ts @@ -13,6 +13,7 @@ import { AGENTS_WINDOW_INVITATION_TOUR_ID } from '../../browser/tours/agentsWind import { NEW_SESSION_VIEW_V3_TOUR_ID, NEW_SESSION_VIEW_V3_VARIATIONS } from '../../browser/tours/newSessionViewV3Tour.js'; import { registerSessionArchiveTourDescriptor, SESSION_ARCHIVE_TOUR_ID } from '../../../../../workbench/contrib/sessions/browser/tours/sessionArchiveTour.js'; import { PARALLEL_TASKS_TOUR_ID } from '../../browser/tours/parallelTasksTour.js'; +import { AUTOMATIONS_TOUR_ID } from '../../browser/tours/automationsTour.js'; suite('OnboardingTourDescriptors', () => { @@ -31,6 +32,7 @@ suite('OnboardingTourDescriptors', () => { NEW_SESSION_VIEW_V3_TOUR_ID, SESSION_ARCHIVE_TOUR_ID, PARALLEL_TASKS_TOUR_ID, + AUTOMATIONS_TOUR_ID, ].filter(id => !descriptors.has(id)), []); assert.deepStrictEqual(NEW_SESSION_VIEW_V2_VARIATIONS, ['default', 'workspaceAndModel', 'mentalModelAndModels']); assert.deepStrictEqual(descriptors.get(NEW_SESSION_VIEW_V2_TOUR_ID)?.developerModeVariations, ['default', 'workspaceAndModel', 'mentalModelAndModels']); diff --git a/src/vs/sessions/contrib/providers/agentHost/browser/agentHostForkActions.ts b/src/vs/sessions/contrib/providers/agentHost/browser/agentHostForkActions.ts index f46cb11b3f49..5282973e2c0b 100644 --- a/src/vs/sessions/contrib/providers/agentHost/browser/agentHostForkActions.ts +++ b/src/vs/sessions/contrib/providers/agentHost/browser/agentHostForkActions.ts @@ -71,7 +71,7 @@ registerAction2(class extends ForkConversationAction { if (options?.toSide) { await sessionsService.openChatToSide(session, newChat.resource, { referenceChatResource: sourceSessionResource }); } else { - await sessionsService.openChat(session, newChat.resource); + await sessionsService.openChat(session, newChat.resource, { referenceChatResource: sourceSessionResource }); } } } catch (error) { @@ -109,7 +109,7 @@ registerAction2(class extends ForkConversationAction { if (options?.toSide) { await sessionsService.openChatToSide(parentSession, forkedSessionResource, { referenceChatResource: parentSessionResource }); } else { - await sessionsService.openChat(parentSession, forkedSessionResource); + await sessionsService.openChat(parentSession, forkedSessionResource, { referenceChatResource: parentSessionResource }); } return; } diff --git a/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatInputActionViewItem.ts b/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatInputActionViewItem.ts new file mode 100644 index 000000000000..b716e8658c9b --- /dev/null +++ b/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatInputActionViewItem.ts @@ -0,0 +1,84 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../../base/browser/dom.js'; +import { BaseActionViewItem } from '../../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { renderIcon } from '../../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { IAction } from '../../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { onUnexpectedError } from '../../../../../../base/common/errors.js'; +import { DisposableStore, IDisposable } from '../../../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../../../base/common/observable.js'; +import { localize } from '../../../../../../nls.js'; +import { IModePickerDelegate } from '../../../../../../workbench/contrib/chat/browser/widget/input/modePickerActionItem.js'; +import { IModelPickerDelegate } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.js'; + +/** The mobile composer uses a model label and chevron, without mode or provider icons. */ +export class MobileChatInputActionViewItem extends BaseActionViewItem { + private readonly renderDisposables = this._register(new DisposableStore()); + private trigger: HTMLElement | undefined; + private showing = false; + + constructor( + action: IAction, + private readonly mode: IModePickerDelegate, + private readonly model: IModelPickerDelegate, + private readonly showSheet: (target: HTMLElement) => Promise, + registerModelPicker: () => IDisposable, + ) { + super(undefined, action); + this._register(registerModelPicker()); + } + + override render(container: HTMLElement): void { + super.render(container); + this.renderDisposables.clear(); + container.classList.add('chat-input-picker-item'); + const trigger = this.trigger = dom.append(container, dom.$('a.action-label.chat-phone-input-chip')); + trigger.tabIndex = 0; + trigger.role = 'button'; + trigger.setAttribute('aria-haspopup', 'dialog'); + trigger.setAttribute('aria-expanded', 'false'); + const label = dom.append(trigger, dom.$('span.chat-input-picker-label')); + dom.append(trigger, renderIcon(Codicon.chevronDown)).classList.add('chat-phone-input-chip-chevron'); + this.renderDisposables.add(autorun(reader => { + const mode = this.mode.currentMode.read(reader).label.read(reader); + const name = this.model.currentModel.read(reader)?.metadata.name ?? localize('auto', "Auto"); + label.textContent = name; + trigger.ariaLabel = localize('pick', "Pick Mode and Model, {0}, {1}", mode, name); + })); + this.renderDisposables.add(dom.addDisposableListener(trigger, dom.EventType.KEY_DOWN, event => { + if (event.key === 'Enter' || event.key === ' ') { + this.onClick(event); + } + })); + } + + override onClick(event: dom.EventLike): void { + dom.EventHelper.stop(event, true); + void this.open().catch(onUnexpectedError); + } + + override focus(): void { + this.trigger?.focus(); + } + + private async open(): Promise { + if (!this.trigger || this.showing) { + return; + } + this.showing = true; + this.trigger.setAttribute('aria-expanded', 'true'); + try { + await this.showSheet(this.trigger); + } finally { + this.showing = false; + if (!this._store.isDisposed) { + this.trigger.setAttribute('aria-expanded', 'false'); + this.trigger.focus(); + } + } + } +} diff --git a/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts b/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts new file mode 100644 index 000000000000..f953518f8b12 --- /dev/null +++ b/src/vs/sessions/contrib/providers/agentHost/browser/mobile/mobileChatPhoneInputPresenter.ts @@ -0,0 +1,819 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ThemeIcon } from '../../../../../../base/common/themables.js'; +import { IAction, toAction } from '../../../../../../base/common/actions.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { autorun, constObservable, derived, IObservable } from '../../../../../../base/common/observable.js'; +import { Emitter } from '../../../../../../base/common/event.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { localize } from '../../../../../../nls.js'; +import { SessionConfigKey } from '../../../../../../platform/agentHost/common/sessionConfigKeys.js'; +import { ClaudeSessionConfigKey } from '../../../../../../platform/agentHost/common/claudeSessionConfigKeys.js'; +import { CodexSessionConfigKey } from '../../../../../../platform/agentHost/common/codexSessionConfigKeys.js'; +import { getSessionApprovalProperty, isSessionConfigWritable, validateSessionConfigWrite } from '../../../../../../platform/agentHost/common/sessionConfigProperties.js'; +import { ActionListItemKind } from '../../../../../../platform/actionWidget/browser/actionList.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { observableContextKey } from '../../../../../../platform/observable/common/platformObservableUtils.js'; +import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { IUriIdentityService } from '../../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IStorageService } from '../../../../../../platform/storage/common/storage.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../../../workbench/common/contributions.js'; +import { IToggleChatModeArgs, ToggleAgentModeActionId } from '../../../../../../workbench/contrib/chat/browser/actions/chatExecuteActions.js'; +import { ChatPetAchievementIds, didExplicitlyEnableChatPetAutopilot } from '../../../../../../workbench/contrib/chat/browser/chatPetAchievements.js'; +import { IChatPetService } from '../../../../../../workbench/contrib/chat/browser/chatPetService.js'; +import { IChatWidgetService } from '../../../../../../workbench/contrib/chat/browser/chat.js'; +import { ChatPhoneInputPresenterRequest, IChatPhoneInputPresenter, IChatPhoneInputSessionContext, IChatPhonePresenterImpl } from '../../../../../../workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { IModePickerDelegate } from '../../../../../../workbench/contrib/chat/browser/widget/input/modePickerActionItem.js'; +import { IModelPickerDelegate } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.js'; +import { getModelProviderIcon } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelProviderIcons.js'; +import { IChatMode } from '../../../../../../workbench/contrib/chat/common/chatModes.js'; +import { ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService, IModelConfigurationAccess } from '../../../../../../workbench/contrib/chat/common/languageModels.js'; +import { getModelConfigChoices, getModelConfigProperty, IModelConfigProperty, MODEL_CONFIG_GROUP_CONTEXT, MODEL_CONFIG_GROUP_EFFORT, setModelConfigValues } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerModelConfig.js'; +import { buildSpeedVariants } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerVariants.js'; +import type { SessionConfigPropertySchema } from '../../../../../../platform/agentHost/common/state/protocol/commands.js'; +import { IWorkbenchLayoutService } from '../../../../../../workbench/services/layout/browser/layoutService.js'; +import { getSessionConfigProvider, isAgentHostProvider } from '../../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; +import { ISessionsManagementService } from '../../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { showMobilePickerSheet, IMobilePickerSheetItem, MOBILE_PICKER_SHEET_CONFIRM } from '../../../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; +import { getAgentHostModeIcon } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostModeIcon.js'; +import { AgentHostPermissionPickerDelegate, isWellKnownAutoApproveSchema, isWellKnownClaudePermissionModeSchema, isWellKnownCodexApprovalsSchema, isWellKnownModeSchema, isWellKnownModeValue } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.js'; +import { normalizeModelPickerOptions } from '../../../../../../workbench/contrib/sessions/browser/chat/sessionModelPickerState.js'; +import { ISessionsProvider } from '../../../../../../workbench/contrib/sessions/common/sessionsProvider.js'; +import { createChatPhoneInputSessionContext, createChatPhoneInputTarget, IChatPhoneInputTarget, matchesChatPhoneInputTarget } from '../../../../../../workbench/contrib/sessions/browser/chatPhoneInputContext.js'; +import { MobileChatInputActionViewItem } from './mobileChatInputActionViewItem.js'; +import { PermissionPicker } from '../../../../../../workbench/contrib/sessions/providers/copilotChatSessions/browser/permissionPicker.js'; +import { IChat, ISession, ISessionAgentRef } from '../../../../../../workbench/services/sessions/common/session.js'; +import { ISessionHostService } from '../../../../../../workbench/services/sessions/browser/sessionHost.js'; +import { getAgentHostAgentPickerState, setAgentHostAgent } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentSelection.js'; + +/** + * Action id passed to the workbench `ToggleAgentModeActionId` command when + * the user picks a mode row. The arg shape is + * {@link IToggleChatModeArgs}. + */ +type ChatPhonePickerAction = + | { kind: 'mode'; mode: IChatMode } + | { kind: 'model'; model: ILanguageModelChatMetadataAndIdentifier } + | { kind: 'agentHostMode'; value: string } + | { kind: 'agentHostModel'; model: ILanguageModelChatMetadataAndIdentifier } + | { kind: 'modelConfig'; model: ILanguageModelChatMetadataAndIdentifier; access: IModelConfigurationAccess; key: string; value: unknown } + | { kind: 'sessionConfig'; property: string; value: unknown } + | { kind: 'providerPermissions'; property: string; value: unknown } + | { kind: 'permission'; action: IAction } + | { kind: 'agent'; agent: ISessionAgentRef | undefined } + | { kind: 'chooseModel' }; + +/** What the combined sheet is built from, so the model sheet can reuse it. */ +interface IChatPhoneSheet { + readonly items: IMobilePickerSheetItem[]; + readonly models: readonly ILanguageModelChatMetadataAndIdentifier[]; + readonly currentModel: ILanguageModelChatMetadataAndIdentifier | undefined; + /** Produces the action that selects a model in this request. */ + readonly selectModelAction: (model: ILanguageModelChatMetadataAndIdentifier) => ChatPhonePickerAction; +} + +/** Rows stay a comfortable thumb-list; above this the model sheet gets a search field. */ +const MODEL_SHEET_SEARCH_THRESHOLD = 8; + +/** + * Session-config properties that already have a dedicated phone presentation + * (mode row, permission sheet) or that the phone cannot act on, and so are not + * rendered as generic rows in the combined sheet. + */ +function isGenericPhoneSessionConfigProperty(property: string, schema: SessionConfigPropertySchema, isNewSession: boolean): boolean { + if (!isSessionConfigWritable(schema, isNewSession)) { + return false; + } + if (schema.type === 'boolean') { + return true; + } + if (schema.type !== 'string' || !schema.enum?.length) { + return false; + } + if (property === SessionConfigKey.Mode && isWellKnownModeSchema(schema)) { + return false; + } + if ((property === SessionConfigKey.AutoApprove && isWellKnownAutoApproveSchema(schema)) + || property === SessionConfigKey.Permissions) { + return false; + } + return true; +} + +type RegisterChatPhonePickerAction = (action: ChatPhonePickerAction) => string; + +function getActionKey(action: ChatPhonePickerAction): string { + switch (action.kind) { + case 'mode': return JSON.stringify([action.kind, action.mode.id]); + case 'agentHostMode': return JSON.stringify([action.kind, action.value]); + case 'model': + case 'agentHostModel': return JSON.stringify([action.kind, action.model.identifier]); + case 'modelConfig': return JSON.stringify([action.kind, action.model.identifier, action.key, action.value]); + case 'sessionConfig': + case 'providerPermissions': return JSON.stringify([action.kind, action.property, action.value]); + case 'permission': return JSON.stringify([action.kind, action.action.id]); + case 'agent': return JSON.stringify([action.kind, action.agent?.uri]); + case 'chooseModel': return action.kind; + } +} + +/** + * Sessions-side implementation of {@link IChatPhoneInputPresenter}. + * + * On phone-layout viewports of the agents window, intercepts the + * workbench {@link ChatInputPart}'s Mode + Model pickers and routes them + * through the shared {@link showMobilePickerSheet} bottom sheet — the + * same primitive used by the empty new-chat input (see + * {@link MobileChatInputConfigPicker}). Workbench code does not depend on + * the sheet primitive: it only sees the {@link IChatPhoneInputPresenter} + * decorator interface, so this wiring stays out of the workbench layer. + */ +class MobileChatPhoneInputPresenter extends Disposable implements IChatPhonePresenterImpl { + + readonly enabled: IObservable; + readonly supportsUnifiedConfiguration = true; + private readonly _openSheet = this._register(new MutableDisposable()); + + constructor( + @IContextKeyService contextKeyService: IContextKeyService, + @ICommandService private readonly _commandService: ICommandService, + @IWorkbenchLayoutService private readonly _layoutService: IWorkbenchLayoutService, + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @ISessionHostService private readonly _sessionHostService: ISessionHostService, + @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, + @IUriIdentityService private readonly _uriIdentityService: IUriIdentityService, + @IChatPetService private readonly _chatPetService: IChatPetService, + @ILanguageModelsService private readonly _languageModelsService: ILanguageModelsService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @INotificationService private readonly _notificationService: INotificationService, + @IChatPhoneInputPresenter private readonly _phonePresenter: IChatPhoneInputPresenter, + @IChatWidgetService private readonly _chatWidgetService: IChatWidgetService, + @IStorageService private readonly _storageService: IStorageService, + ) { + super(); + + // Track the phone-layout context key (`sessionsIsPhoneLayout`) so + // the workbench toolbar refreshes its action view items the moment + // we cross the phone breakpoint. This key is the source of truth + // for "is this viewport phone-classified" — the layout policy + // updates it through the workbench's main `layout()` pass. + const isPhoneCtx = observableContextKey('sessionsIsPhoneLayout', contextKeyService); + this.enabled = derived(this, reader => isPhoneCtx.read(reader) === true); + } + + createActionViewItem(action: IAction, mode: IModePickerDelegate, model: IModelPickerDelegate): MobileChatInputActionViewItem { + const request: ChatPhoneInputPresenterRequest = { + kind: 'delegates', modeDelegate: mode, modelDelegate: model, + }; + return new MobileChatInputActionViewItem(action, mode, model, target => this.showCombinedModeAndModelSheet(target, request), () => this._phonePresenter.registerSessionModelPicker({ + getSessionContext: () => this._getSessionContext(request), + modelDelegate: model, + selectModel: identifier => { + const selected = model.getModels().find(candidate => candidate.identifier === identifier && candidate.metadata.isUserSelectable !== false); + if (!selected) { + return false; + } + model.setModel(selected); + return true; + }, + })); + } + + async showCombinedModeAndModelSheet( + anchor: HTMLElement, + request: ChatPhoneInputPresenterRequest, + ): Promise { + const sessionContext = this._getSessionContext(request); + const target = createChatPhoneInputTarget(sessionContext, this._uriIdentityService); + const store = new DisposableStore(); + this._openSheet.value = store; + const cancellation = new CancellationTokenSource(); + store.add(toDisposable(() => cancellation.dispose(true))); + const provider = sessionContext && this._sessionsProvidersService.getProvider(sessionContext.providerId, sessionContext.sessionId); + const isCurrent = () => !cancellation.token.isCancellationRequested + && matchesChatPhoneInputTarget(target, this._getSessionContext(request), this._uriIdentityService) + && (!sessionContext || this._getSessionSource(sessionContext.chatResource, sessionContext) !== undefined) + && (!sessionContext || this._sessionsProvidersService.getProvider(sessionContext.providerId, sessionContext.sessionId) === provider); + const configProvider = provider && getSessionConfigProvider(provider); + const itemsChanged = store.add(new Emitter()); + const permissionStore = store.add(new DisposableStore()); + let permissionPicker: PermissionPicker | undefined; + let permissionDelegate: AgentHostPermissionPickerDelegate | undefined; + if (sessionContext && configProvider) { + store.add(configProvider.onDidChangeSessionConfig(id => { + if (id === sessionContext.sessionId) { + itemsChanged.fire(); + } + })); + store.add(autorun(reader => { + configProvider.isSessionConfigResolving(sessionContext.sessionId, sessionContext.chatResource).read(reader); + itemsChanged.fire(); + })); + } + try { + const idToAction = new Map(); + const actionIds = new Map(); + const registerAction = (action: ChatPhonePickerAction): string => { + const key = getActionKey(action); + const id = actionIds.get(key) ?? `chat-phone-picker-row-${actionIds.size}`; + actionIds.set(key, id); + idToAction.set(id, action); + return id; + }; + const buildSheet = () => { + idToAction.clear(); + const config = sessionContext && configProvider?.getSessionConfig(sessionContext.sessionId, sessionContext.chatResource); + if (sessionContext && getSessionApprovalProperty(config?.schema)) { + if (!permissionPicker) { + const source = this._getSessionSource(sessionContext.chatResource, sessionContext); + if (!source) { + throw new Error(localize('chatPhoneInput.sessionUnavailable', "This chat is no longer available.")); + } + permissionDelegate = permissionStore.add(this._instantiationService.createInstance(AgentHostPermissionPickerDelegate, { + session: constObservable(source.session), + chat: constObservable(source.chat), + })); + permissionPicker = permissionStore.add(this._instantiationService.createInstance(PermissionPicker, permissionDelegate)); + } + } else { + permissionStore.clear(); + permissionPicker = undefined; + permissionDelegate = undefined; + } + const sheet = this._buildSheet(request, this._getSessionContext(request), registerAction); + if (sheet && permissionPicker && permissionDelegate) { + this._pushPermissionItems(sheet.items, permissionPicker, isCurrent, registerAction, !permissionDelegate.isApplicable.get() || permissionDelegate.isResolving.get()); + } + return sheet; + }; + let openModelSheet: boolean; + do { + openModelSheet = false; + if (!isCurrent()) { + return; + } + let sheet = buildSheet(); + if (!sheet?.items.length) { + return; + } + const refreshItems = () => { + if (!isCurrent()) { + cancellation.cancel(); + return []; + } + sheet = buildSheet(); + return sheet?.items ?? []; + }; + const initialFocusItemId = sheet.items.find(item => { + const action = idToAction.get(item.id); + return request.initialSection === 'permissions' ? action?.kind === 'permission' || action?.kind === 'providerPermissions' + : request.initialSection === 'modelConfiguration' ? action?.kind === 'modelConfig' + : request.initialSection === 'model' ? action?.kind === 'chooseModel' + : request.initialSection === 'agent' ? action?.kind === 'agent' + : action?.kind === 'mode' || action?.kind === 'agentHostMode'; + })?.id; + await showMobilePickerSheet(this._layoutService.mainContainer, localize('chatPhoneInput.title', "Configure Session"), sheet.items, { + stayOpenOnSelect: true, + initialFocusItemId, + dismissToken: cancellation.token, + itemProvider: { onDidChange: itemsChanged.event, getItems: refreshItems }, + onDidSelect: async id => { + if (!isCurrent()) { + cancellation.cancel(); + return; + } + const action = idToAction.get(id); + if (action?.kind === 'chooseModel') { + openModelSheet = true; + return MOBILE_PICKER_SHEET_CONFIRM; + } + if (action) { + try { + await this._performAction(action, target, request, isCurrent); + } catch (error) { + this._notificationService.error(error); + } + } + if (!isCurrent()) { + cancellation.cancel(); + return; + } + return { items: refreshItems(), focusItemId: id }; + }, + }); + if (openModelSheet && isCurrent() && sheet) { + const chosen = await this._showModelSheet(sheet.models, sheet.currentModel, cancellation); + if (chosen && isCurrent()) { + await this._performAction(sheet.selectModelAction(chosen), target, request, isCurrent); + } + } + } while (openModelSheet); + } finally { + if (this._openSheet.value === store) { + this._openSheet.clear(); + if (anchor.isConnected) { + anchor.focus(); + } + } + } + } + + private _buildSheet( + request: ChatPhoneInputPresenterRequest, + session: IChatPhoneInputSessionContext | undefined, + registerAction: RegisterChatPhonePickerAction, + ): IChatPhoneSheet | undefined { + const rawProvider = session ? this._sessionsProvidersService.getProvider(session.providerId, session.sessionId) : undefined; + if (session && rawProvider) { + return this._buildSessionSheet(session, rawProvider, request, registerAction); + } + if (request.kind !== 'delegates') { + return request.modelDelegate ? this._buildDelegateSheet(undefined, request.modelDelegate, registerAction) : undefined; + } + return this._buildDelegateSheet(request.modeDelegate, request.modelDelegate, registerAction); + } + + private _buildSessionSheet( + session: IChatPhoneInputSessionContext, + provider: ISessionsProvider, + request: ChatPhoneInputPresenterRequest, + registerAction: RegisterChatPhonePickerAction, + ): IChatPhoneSheet { + const items: IMobilePickerSheetItem[] = []; + const configProvider = getSessionConfigProvider(provider); + const config = configProvider?.getSessionConfig(session.sessionId, session.chatResource); + const isNewSession = configProvider?.getCreateSessionConfig(session.sessionId) !== undefined; + const resolving = configProvider?.isSessionConfigResolving(session.sessionId, session.chatResource).get() === true; + if (isAgentHostProvider(provider) && provider.setAgent) { + const { agents, toPickerUri } = getAgentHostAgentPickerState(session.sessionId, provider); + const selectedAgent = toPickerUri(this._getSessionSource(session.chatResource, session)?.session.mode.get()?.id); + if (agents.length) { + items.push({ + id: registerAction({ kind: 'agent', agent: undefined }), + label: localize('chatPhoneInput.defaultAgent', "Default Agent"), + icon: Codicon.agent, + checked: !selectedAgent || selectedAgent === 'agent', + disabled: resolving, + sectionTitle: localize('chatPhoneInput.agentSection', "Agent"), + }); + for (const agent of agents) { + items.push({ + id: registerAction({ kind: 'agent', agent: { uri: agent.uri, name: agent.name } }), + label: agent.name, + description: agent.description, + checked: selectedAgent === agent.uri, + disabled: resolving, + }); + } + } + } + const modeSchema = config?.schema.properties[SessionConfigKey.Mode]; + const modeItems = (modeSchema && isWellKnownModeSchema(modeSchema)) + ? (modeSchema.enum ?? []).map((value, index) => ({ + value: String(value), + label: modeSchema.enumLabels?.[index] ?? String(value), + description: modeSchema.enumDescriptions?.[index], + })) + : []; + const rawCurrentMode = config?.values[SessionConfigKey.Mode] ?? modeSchema?.default; + const currentModeValue = typeof rawCurrentMode === 'string' && modeItems.some(item => item.value === rawCurrentMode) + ? rawCurrentMode + : modeItems[0]?.value; + + modeItems.forEach((item, index) => items.push({ + id: registerAction({ kind: 'agentHostMode', value: item.value }), + label: item.label, + description: item.description, + icon: getAgentHostModeIcon(item.value), + checked: item.value === currentModeValue, + disabled: resolving || !isSessionConfigWritable(modeSchema, isNewSession), + sectionTitle: index === 0 ? localize('chatPhoneInput.modeSection', "Agent Mode") : undefined, + })); + + const modelDelegate = this._getModelDelegate(request, session); + const models = (modelDelegate?.getModels() ?? provider.getModelsSnapshot(session.sessionId).models).filter(model => model.metadata.isUserSelectable !== false); + const composerModel = modelDelegate?.currentModel.get(); + const currentModel = (composerModel && (models.find(model => model.identifier === composerModel.identifier) ?? composerModel)) + ?? models.find(model => model.identifier === session.modelId); + const options = normalizeModelPickerOptions(provider.getModelPickerOptions(session.sessionId)); + this._pushModelRow(items, models, currentModel, options.showAutoModel, registerAction); + + const configAccess = modelDelegate?.modelConfiguration; + if (currentModel) { + if (configAccess) { + this._pushModelConfigItems(items, currentModel, configAccess, registerAction); + } + this._pushSpeedItems(items, models, currentModel, registerAction); + } + + // Remaining session settings the agent exposes (e.g. isolation, sandbox, + // network access). Each enum becomes a radio section; a boolean becomes + // an On/Off radio section, so the row the user taps carries the value it + // sets and the check always reflects the current state. + if (config) { + for (const [property, schema] of Object.entries(config.schema.properties)) { + if (!isGenericPhoneSessionConfigProperty(property, schema, isNewSession) || property === getSessionApprovalProperty(config.schema)?.key || property === SessionConfigKey.SandboxEnabled) { + continue; + } + const current = config.values[property] ?? schema.default; + if (schema.type === 'boolean') { + [true, false].forEach((value, index) => items.push({ + id: registerAction({ kind: 'sessionConfig', property, value }), + label: value ? localize('chatPhoneInput.on', "On") : localize('chatPhoneInput.off', "Off"), + description: index === 0 ? schema.description : undefined, + checked: current === value, + disabled: resolving, + sectionTitle: index === 0 ? schema.title : undefined, + })); + continue; + } + const permissions = property === ClaudeSessionConfigKey.PermissionMode && isWellKnownClaudePermissionModeSchema(schema) + || property === CodexSessionConfigKey.PermissionsPreset && isWellKnownCodexApprovalsSchema(schema); + (schema.enum ?? []).forEach((value, index) => items.push({ + id: registerAction({ kind: permissions ? 'providerPermissions' : 'sessionConfig', property, value }), + label: schema.enumLabels?.[index] ?? String(value), + description: schema.enumDescriptions?.[index], + checked: value === current, + disabled: resolving, + sectionTitle: index === 0 ? permissions ? localize('chatPhoneInput.permissionsSection', "Approvals") : schema.title : undefined, + })); + } + } + return { items, models, currentModel, selectModelAction: model => ({ kind: 'agentHostModel', model }) }; + } + + private _pushPermissionItems( + items: IMobilePickerSheetItem[], + picker: PermissionPicker, + isCurrent: () => boolean, + registerAction: RegisterChatPhonePickerAction, + disabled: boolean, + ): void { + let sectionTitle: string | undefined = localize('chatPhoneInput.permissionsSection', "Approvals"); + for (const item of picker.getActionListItems(isCurrent)) { + if (item.kind !== ActionListItemKind.Action || !item.item) { + continue; + } + const toggle = item.standaloneToggle; + if (toggle) { + for (const [index, checked] of [true, false].entries()) { + items.push({ + id: registerAction({ + kind: 'permission', action: toAction({ + id: `${item.item.id}.${checked}`, + label: item.item.label, + run: async () => { + if (isCurrent() && !toggle.disabled) { + await toggle.onChange(checked); + } + }, + }) + }), + label: checked ? localize('chatPhoneInput.on', "On") : localize('chatPhoneInput.off', "Off"), + checked: toggle.checked === checked, + disabled: disabled || toggle.disabled, + sectionTitle: index === 0 ? toggle.label : undefined, + }); + } + sectionTitle = ''; + continue; + } + items.push({ + id: registerAction({ kind: 'permission', action: item.item }), + label: item.label ?? item.item.label, + description: item.detail, + badge: item.badge, + icon: item.group?.icon, + checked: item.item.checked, + disabled: disabled || item.disabled, + sectionTitle: item.item.checked === undefined ? '' : sectionTitle, + }); + sectionTitle = undefined; + } + } + + private _pushSpeedItems(items: IMobilePickerSheetItem[], models: readonly ILanguageModelChatMetadataAndIdentifier[], currentModel: ILanguageModelChatMetadataAndIdentifier, registerAction: RegisterChatPhonePickerAction): void { + const variants = buildSpeedVariants(models).get(currentModel.identifier); + if (variants) { + [variants.standard, variants.fast].forEach((model, index) => items.push({ + id: registerAction({ kind: 'agentHostModel', model }), + label: index === 0 ? localize('chatPhoneInput.standardSpeed', "Standard") : localize('chatPhoneInput.fastSpeed', "Fast"), + checked: model.identifier === currentModel.identifier, + sectionTitle: index === 0 ? localize('chatPhoneInput.speedSection', "Speed") : undefined, + icon: index === 1 ? Codicon.zap : undefined, + })); + } + } + + private _buildDelegateSheet( + modeDelegate: IModePickerDelegate | undefined, + modelDelegate: IModelPickerDelegate, + registerAction: RegisterChatPhonePickerAction, + ): IChatPhoneSheet { + const items: IMobilePickerSheetItem[] = []; + if (modeDelegate) { + const modes = modeDelegate.currentChatModes.get(); + const currentMode = modeDelegate.currentMode.get(); + [...modes.builtin, ...modes.custom].forEach((mode, index) => { + const icon = mode.icon.get(); + items.push({ + id: registerAction({ kind: 'mode', mode }), + label: mode.label.get(), + icon: ThemeIcon.isThemeIcon(icon) ? icon : undefined, + checked: mode.id === currentMode.id, + sectionTitle: index === 0 ? localize('chatPhoneInput.modeSection', "Agent Mode") : undefined, + }); + }); + } + + const models = modelDelegate.getModels().filter(model => model.metadata.isUserSelectable !== false); + const currentModel = modelDelegate.currentModel.get(); + this._pushModelRow(items, models, currentModel, true, registerAction); + if (currentModel) { + this._pushModelConfigItems(items, currentModel, modelDelegate.modelConfiguration ?? this._languageModelsService, registerAction); + this._pushSpeedItems(items, models, currentModel, registerAction); + } + return { items, models, currentModel, selectModelAction: model => ({ kind: 'model', model }) }; + } + + /** + * One row summarizing the model in use. Tapping it opens the model sheet + * (see {@link _showModelSheet}) rather than listing every model inline. + */ + private _pushModelRow( + items: IMobilePickerSheetItem[], + models: readonly ILanguageModelChatMetadataAndIdentifier[], + currentModel: ILanguageModelChatMetadataAndIdentifier | undefined, + showAutoModel: boolean, + registerAction: RegisterChatPhonePickerAction, + ): void { + const sectionTitle = localize('chatPhoneInput.modelSection', "Model"); + if (models.length === 0 && !showAutoModel) { + items.push({ + id: 'chat-phone-picker-no-models', + label: localize('chatPhoneInput.noModels', "No models available"), + disabled: true, + sectionTitle, + }); + return; + } + items.push({ + id: registerAction({ kind: 'chooseModel' }), + label: currentModel?.metadata.name ?? localize('chatPhoneInput.autoModel', "Auto"), + description: models.length > 1 + ? localize('chatPhoneInput.modelRowDescription', "{0} models available", models.length) + : undefined, + icon: currentModel ? getModelProviderIcon(currentModel) : undefined, + navigates: true, + disabled: models.length === 0, + sectionTitle, + }); + } + + /** The model sheet: every model as a radio row, searchable once the list is long. */ + private async _showModelSheet( + models: readonly ILanguageModelChatMetadataAndIdentifier[], + currentModel: ILanguageModelChatMetadataAndIdentifier | undefined, + cancellation: CancellationTokenSource, + ): Promise { + const byId = new Map(); + const toItem = (model: ILanguageModelChatMetadataAndIdentifier, index: number): IMobilePickerSheetItem => { + const id = `chat-phone-model-${index}`; + byId.set(id, model); + return { + id, + label: model.metadata.name, + icon: getModelProviderIcon(model), + checked: model.identifier === currentModel?.identifier, + }; + }; + const items = models.map(toItem); + // With a search field the sheet renders the static rows and the results + // of the current query together, so the search source owns the whole + // list: every model for an empty query, a filtered set while typing. + const searchable = models.length > MODEL_SHEET_SEARCH_THRESHOLD; + const pickedId = await showMobilePickerSheet( + this._layoutService.mainContainer, + localize('chatPhoneInput.modelSheetTitle', "Model"), + searchable ? [] : items, + { + dismissToken: cancellation.token, + doneLabel: localize('chatPhoneInput.cancel', "Cancel"), + search: searchable + ? { + placeholder: localize('chatPhoneInput.searchModels', "Search models"), + loadItems: async query => { + const needle = query.trim().toLowerCase(); + return needle ? items.filter(item => item.label.toLowerCase().includes(needle)) : items; + }, + } + : undefined, + }, + ); + return pickedId ? byId.get(pickedId) : undefined; + } + + private _pushModelConfigItems( + items: IMobilePickerSheetItem[], + model: ILanguageModelChatMetadataAndIdentifier, + access: IModelConfigurationAccess, + registerAction: RegisterChatPhonePickerAction, + ): void { + const groups: [string, string][] = [ + [MODEL_CONFIG_GROUP_EFFORT, localize('chatPhoneInput.thinkingSection', "Thinking")], + [MODEL_CONFIG_GROUP_CONTEXT, localize('chatPhoneInput.contextSection', "Context")], + ]; + const properties: IModelConfigProperty[] = []; + for (const [group] of groups) { + const property = getModelConfigProperty(model, access, group); + if (property) { + properties.push(property); + } + } + const schema = access.getModelConfigurationSchema?.(model.identifier) ?? model.metadata.configurationSchema; + const values = access.getModelConfiguration(model.identifier); + for (const [key, propertySchema] of Object.entries(schema?.properties ?? {})) { + if (!properties.some(property => property.key === key) && (propertySchema.enum?.length || propertySchema.type === 'boolean')) { + properties.push({ + key, + schema: propertySchema.type === 'boolean' && !propertySchema.enum + ? { ...propertySchema, enum: [true, false], enumItemLabels: [localize('chatPhoneInput.on', "On"), localize('chatPhoneInput.off', "Off")] } + : propertySchema, + value: values && Object.hasOwn(values, key) ? values[key] : propertySchema.default, + }); + } + } + for (const property of properties) { + const title = property.schema.title ?? groups.find(([group]) => group === property.schema.group)?.[1] ?? property.key; + getModelConfigChoices(property).forEach((choice, index) => items.push({ + id: registerAction({ kind: 'modelConfig', model, access, key: property.key, value: choice.value }), + label: choice.label, + description: choice.description, + checked: choice.checked, + disabled: choice.readOnly, + sectionTitle: index === 0 ? title : undefined, + })); + } + } + + private async _performAction( + action: ChatPhonePickerAction, + target: IChatPhoneInputTarget | undefined, + request: ChatPhoneInputPresenterRequest, + isCurrent: () => boolean, + ): Promise { + const session = this._getSessionContext(request); + if (!matchesChatPhoneInputTarget(target, session, this._uriIdentityService)) { + return; + } + const provider = session ? this._sessionsProvidersService.getProvider(session.providerId, session.sessionId) : undefined; + const configProvider = provider && getSessionConfigProvider(provider); + + switch (action.kind) { + case 'mode': + if (request.kind === 'delegates') { + await this._commandService.executeCommand( + ToggleAgentModeActionId, + { modeId: action.mode.id, sessionResource: request.modeDelegate.sessionResource() } satisfies IToggleChatModeArgs, + ); + } + break; + case 'agentHostMode': + if (session && configProvider && !configProvider.isSessionConfigResolving(session.sessionId, session.chatResource).get()) { + const config = configProvider.getSessionConfig(session.sessionId, session.chatResource); + const schema = config?.schema.properties[SessionConfigKey.Mode]; + if (isSessionConfigWritable(schema, configProvider.getCreateSessionConfig(session.sessionId) !== undefined) && schema && isWellKnownModeValue(schema, action.value)) { + const previousMode = String(config?.values[SessionConfigKey.Mode] ?? schema.default ?? ''); + const operation = configProvider.setSessionConfigValue(session.sessionId, session.chatResource, SessionConfigKey.Mode, action.value); + configProvider.trackSessionConfigOperation?.(session.sessionId, operation); + await operation; + if (didExplicitlyEnableChatPetAutopilot(previousMode, action.value)) { + this._chatPetService.unlockAchievement(ChatPetAchievementIds.AutopilotEnabled); + } + } + } + break; + case 'model': + case 'agentHostModel': { + const modelDelegate = this._getModelDelegate(request, session); + if (modelDelegate) { + const model = modelDelegate.getModels().find(model => model.identifier === action.model.identifier && model.metadata.isUserSelectable !== false); + if (model) { + modelDelegate.setModel(model); + } + } else if (session) { + const picker = this._phonePresenter.getSessionModelPicker(session); + const selected = picker ? picker.selectModel(action.model.identifier) + : request.kind === 'session' && request.selectModel ? request.selectModel(action.model.identifier) + : this._chatWidgetService.getWidgetBySessionResource(session.chatResource)?.inputPart?.switchModelByIdentifier(action.model.identifier, true, true); + if (!selected) { + throw new Error(localize('chatPhoneInput.modelUnavailable', "This model is no longer available for this session.")); + } + } + break; + } + case 'modelConfig': { + const currentModelId = this._getModelDelegate(request, session)?.currentModel.get()?.identifier ?? session?.modelId; + const property = (action.access.getModelConfigurationSchema?.(action.model.identifier) ?? action.model.metadata.configurationSchema)?.properties?.[action.key]; + if (currentModelId === action.model.identifier && property && !property.readOnly && (!property.enum || property.enum.includes(action.value))) { + await setModelConfigValues(action.model, action.access, { [action.key]: action.value }); + } + break; + } + case 'sessionConfig': + case 'providerPermissions': + if (session && configProvider && !configProvider.isSessionConfigResolving(session.sessionId, session.chatResource).get()) { + const config = configProvider.getSessionConfig(session.sessionId, session.chatResource); + const isNewSession = configProvider.getCreateSessionConfig(session.sessionId) !== undefined; + if (config && isSessionConfigWritable(config.schema.properties[action.property], isNewSession)) { + validateSessionConfigWrite(config.schema, config.values, action.property, action.value, isNewSession); + const operation = configProvider.setSessionConfigValue(session.sessionId, session.chatResource, action.property, action.value); + configProvider.trackSessionConfigOperation?.(session.sessionId, operation); + await operation; + } + } + break; + case 'permission': + if (isCurrent() && action.action.enabled) { + await action.action.run(); + } + break; + case 'agent': + if (session && provider && isAgentHostProvider(provider) && provider.setAgent && !provider.isSessionConfigResolving(session.sessionId, session.chatResource).get()) { + const currentSession = this._getSessionSource(session.chatResource, session)?.session; + const agentUri = action.agent?.uri; + const agent = agentUri ? getAgentHostAgentPickerState(session.sessionId, provider).agents.find(candidate => candidate.uri === agentUri) : undefined; + if (currentSession && (!action.agent || agent)) { + setAgentHostAgent(currentSession, provider, agent, this._storageService); + } + } + break; + case 'chooseModel': + // Handled by the sheet loop, which opens the model sheet. + break; + } + } + + private _getModelDelegate(request: ChatPhoneInputPresenterRequest, session: IChatPhoneInputSessionContext | undefined): IModelPickerDelegate | undefined { + return request.modelDelegate ?? (session && this._phonePresenter.getSessionModelPicker(session)?.modelDelegate); + } + + private _getSessionSource(chatResource: URI, context?: IChatPhoneInputSessionContext): { session: ISession; chat: IChat } | undefined { + const matchesSession = (session: ISession) => !context || session.providerId === context.providerId && session.sessionId === context.sessionId; + // Draft composers and automation dialogs are excluded from getHostOfChat. + for (const host of this._sessionHostService.hosts.get()) { + const session = host.session.get(); + const chat = host.chat.get(); + if (session && chat && matchesSession(session) && this._uriIdentityService.extUri.isEqual(chat.resource, chatResource)) { + return { session, chat }; + } + } + const source = this._sessionsManagementService.getSessionForChatResource(chatResource); + return source && matchesSession(source.session) ? source : undefined; + } + + private _getSessionContext(request: ChatPhoneInputPresenterRequest): IChatPhoneInputSessionContext | undefined { + if (request.kind === 'session') { + return request.getSessionContext(); + } + const resource = request.modeDelegate.sessionResource(); + const source = resource && this._getSessionSource(resource); + return source ? createChatPhoneInputSessionContext(source.session, source.chat) : undefined; + } +} + +export class MobileChatPhoneInputPresenterContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.mobile.chatPhoneInputPresenter'; + + private readonly _registration = this._register(new MutableDisposable()); + + constructor( + @IChatPhoneInputPresenter presenter: IChatPhoneInputPresenter, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + + const impl = this._register(instantiationService.createInstance(MobileChatPhoneInputPresenter)); + + // Keep the registration mounted for the lifetime of the + // contribution. The workbench presenter's `enabled` observable + // already gates the actual sheet path on phone layout, so no + // dynamic mount/unmount is needed here. + this._registration.value = presenter.setImpl(impl); + } +} + +registerWorkbenchContribution2( + MobileChatPhoneInputPresenterContribution.ID, + MobileChatPhoneInputPresenterContribution, + WorkbenchPhase.BlockRestore, +); diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHost/agentHostSessionConfigPicker.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHost/agentHostSessionConfigPicker.test.ts index 6279df632ca5..bd4e8b53f3cd 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHost/agentHostSessionConfigPicker.test.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHost/agentHostSessionConfigPicker.test.ts @@ -68,7 +68,7 @@ import { WorktreeSuggestionVariant } from '../../../../../../../workbench/contri import '../../../../../../../workbench/contrib/sessions/browser/chat/media/chatWidget.css'; // The actions and menu items of the pickers, which the tests of their placement read, as the workbench registers them import '../../../browser/agentHostSessionConfigPicker.contribution.js'; -import { InSessionHostScopeContext, ISessionHost } from '../../../../../../../workbench/services/sessions/browser/sessionHost.js'; +import { InSessionHostScopeContext, ISessionHost, ISessionHostService } from '../../../../../../../workbench/services/sessions/browser/sessionHost.js'; import { ITestSessionWithChat, testChatSourceOf, testGridPanes } from '../../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; import { IChatSessionFileChange2 } from '../../../../../../../workbench/common/chatSessionFileChange.js'; @@ -320,6 +320,7 @@ function setupServices( }, } as Partial as IActionWidgetService); instantiationService.stub(IHoverService, NullHoverService); + instantiationService.stub(ISessionHostService, upcastPartial({ hosts: constObservable([]) })); instantiationService.stub(IKeybindingService, new MockKeybindingService()); instantiationService.stub(ISessionInputPickerVisibility, store.add(new SessionInputPickerVisibility())); instantiationService.stub(ITelemetryService, NullTelemetryService); @@ -1192,7 +1193,7 @@ suite('Agent Host Session Config Picker', () => { rows: [ 'Branch · Works alongside your 5 uncommitted files', 'New Worktree · Recommended · Creates a separate copy for this session', - '[5 Uncommitted Files]', + '[5 Modified Files]', 'app.ts', 'README.md', 'todo.ts', @@ -1201,7 +1202,7 @@ suite('Agent Host Session Config Picker', () => { header: undefined, className: 'sessions-chat-isolation-listed-changes', }, - ariaLabel: 'app.ts, 5 Uncommitted Files', + ariaLabel: 'app.ts, 5 Modified Files', calls: [ 'shown:uncommittedFilesCount', 'opened:uncommittedFilesCount', @@ -1256,6 +1257,31 @@ suite('Agent Host Session Config Picker', () => { }); }); + test('isolation picker recommends New Worktree with a secondary badge once the user has started a session in a new worktree', async () => { + const services = setupServices(store); + const suggestions = new TestWorktreeSuggestionService(WorktreeSuggestionVariant.InlineHint); + services.instantiationService.stub(IWorktreeSuggestionService, suggestions); + services.provider.config = makeRepoConfig('main', 'folder'); + services.workspaceObs.set(makeWorkspace(3), undefined); + const { container } = renderAttachedPicker(store, services); + const trigger = isolationSlot(container)!.querySelector('.action-label')!; + const recommendation = async () => { + trigger.click(); + await timeout(0); + const worktree = services.actionWidget.items.find(item => item.item?.value === 'worktree'); + return { badge: worktree?.badge, className: worktree?.className }; + }; + + const firstTime = await recommendation(); + suggestions.worktreeSessionCreated.set(true, undefined); + const afterWorktreeSession = await recommendation(); + + assert.deepStrictEqual({ firstTime, afterWorktreeSession }, { + firstTime: { badge: 'Recommended', className: undefined }, + afterWorktreeSession: { badge: 'Recommended', className: 'sessions-chat-config-secondary-badge' }, + }); + }); + test('uncommitted files count lists the files once they load while its picker is open, until it closes', async () => { const services = setupServices(store); const suggestions = new TestWorktreeSuggestionService(WorktreeSuggestionVariant.UncommittedFilesCount, undefined, 2); @@ -1276,8 +1302,8 @@ suite('Agent Host Session Config Picker', () => { assert.deepStrictEqual({ whileLoading, loaded, afterClosing: rows(), updates: services.actionWidget.events.filter(event => event === 'updateItems').length }, { whileLoading: ['Branch', 'New Worktree'], - loaded: ['Branch', 'New Worktree', '[2 Uncommitted Files]', 'app.ts', 'README.md'], - afterClosing: ['Branch', 'New Worktree', '[2 Uncommitted Files]', 'app.ts', 'README.md'], + loaded: ['Branch', 'New Worktree', '[2 Modified Files]', 'app.ts', 'README.md'], + afterClosing: ['Branch', 'New Worktree', '[2 Modified Files]', 'app.ts', 'README.md'], updates: 1, }); }); diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostAgentPicker.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostAgentPicker.test.ts index 3673d1a7ba7d..2d185535bec0 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostAgentPicker.test.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostAgentPicker.test.ts @@ -8,7 +8,7 @@ import { agentHostConnectionKinds } from '../../../../../../platform/agentHost/t import * as dom from '../../../../../../base/browser/dom.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { Disposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; -import { autorun, constObservable, observableValue } from '../../../../../../base/common/observable.js'; +import { autorun, constObservable, derived, observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; @@ -25,12 +25,13 @@ import { IChatWidget, IChatWidgetService } from '../../../../../../workbench/con import { IChatContextPickService } from '../../../../../../workbench/contrib/chat/browser/attachments/chatContextPickService.js'; import { ChatInputPart } from '../../../../../../workbench/contrib/chat/browser/widget/input/chatInputPart.js'; import { ChatContextKeys } from '../../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; -import { ChatMode, IChatMode } from '../../../../../../workbench/contrib/chat/common/chatModes.js'; +import { ChatMode, IChatMode, IChatModes } from '../../../../../../workbench/contrib/chat/common/chatModes.js'; import { INewSessionComposerService } from '../../../../../../workbench/contrib/sessions/browser/newSessionComposerService.js'; import { IChatViewModel } from '../../../../../../workbench/contrib/chat/common/model/chatViewModel.js'; import { IChatService } from '../../../../../../workbench/contrib/chat/common/chatService/chatService.js'; import { ILifecycleService } from '../../../../../../workbench/services/lifecycle/common/lifecycle.js'; -import { TestStorageService } from '../../../../../../workbench/test/common/workbenchTestServices.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../workbench/services/environment/common/environmentService.js'; +import { TestProductService, TestStorageService } from '../../../../../../workbench/test/common/workbenchTestServices.js'; import { Menus } from '../../../../../../workbench/contrib/sessions/browser/menus.js'; import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { IsPhoneLayoutContext, SessionProviderIdContext, SessionUsesCombinedConfigPickerContext } from '../../../../../../workbench/contrib/sessions/common/contextkeys.js'; @@ -44,6 +45,9 @@ import '../../browser/agentHostSessionConfigPicker.contribution.js'; import '../../browser/mobile/mobileChatInputConfigPicker.contribution.js'; import '../../../../chat/browser/modelPicker.js'; import { focusedSessionHostServiceOf, ITestSessionWithChat } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { AGENT_PICKER_SPOTLIGHT_ID } from '../../../../../../workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.js'; +import { AgentsWindowUsage } from '../../../../../../workbench/contrib/chat/common/agentsWindowUsage.js'; +import { onboardingScenarioRegistry } from '../../../../../../workbench/contrib/onboarding/common/onboardingRegistry.js'; suite('agentHostAgentPicker', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); @@ -52,6 +56,87 @@ suite('agentHostAgentPicker', () => { const beta: AgentCustomization = { type: CustomizationType.Agent, id: 'agent://b', uri: 'agent://b', name: 'beta', description: 'b desc' }; const agents: readonly AgentCustomization[] = [alpha, beta]; + for (const status of [SessionStatus.Untitled, SessionStatus.Completed]) { + test(`offers the shared spotlight for an eligible Agents-window composer (${status})`, async () => { + const configuration = new TestConfigurationService({ [AGENTS_PICKER_IN_ATTACH_CONTEXT_MENU_SETTING]: true }); + disposables.add(configuration.onDidChangeConfigurationEmitter); + const context = disposables.add(new ContextKeyService(configuration)); + const phone = IsPhoneLayoutContext.bindTo(context); + const mode = observableValue>('agent', undefined); + const resource = URI.parse('agent-host-copilot:/spotlight'); + const chat = upcastPartial({ resource, mode }); + const session = upcastPartial({ + resource, sessionId: 'spotlight', providerId: LOCAL_AGENT_HOST_PROVIDER_ID, + status: constObservable(status), activeChat: constObservable(chat), + }); + const root = dom.append(document.body, dom.$('div')); + const button = dom.append(root, dom.$('button')); + button.style.cssText = 'width: 28px; height: 28px;'; + disposables.add(toDisposable(() => root.remove())); + const modes = observableValue('modes', upcastPartial({ custom: [], onDidChange: Event.None })); + const input = upcastPartial({ + currentModeObs: derived(reader => ({ ...ChatMode.Agent, isBuiltin: true, id: mode.read(reader)?.id ?? ChatMode.Agent.id })), + currentChatModesObs: modes, + attachContextButtonElement: button, + onDidChangeAttachContextButton: Event.None, + onDidActivateAttachContext: Event.None, + }); + const widget = upcastPartial({ domNode: root, visible: true, input, inputPart: input }); + const provider = upcastPartial({ + id: LOCAL_AGENT_HOST_PROVIDER_ID, + getCustomAgents: () => [], getCustomizations: () => [], onDidChangeCustomAgents: Event.None, + }); + const providers = disposables.add(new SessionsProvidersService(upcastPartial({ willShutdown: false }))); + disposables.add(providers.registerProvider(provider)); + const storage = disposables.add(new TestStorageService()); + const usage = new AgentsWindowUsage(storage); + usage.recordSessionCreated(); + usage.recordSessionCreated(); + disposables.add(new AgentHostAgentPickerContribution( + new NullActionViewItemService(), + focusedSessionHostServiceOf(constObservable(session)), + providers, + upcastPartial({ getSession: () => undefined }), + upcastPartial({ + getWidgetBySessionResource: () => widget, + onDidAddWidget: Event.None, onDidRemoveWidget: Event.None, + onDidChangeWidgetVisibility: Event.None, onDidChangeFocusedSession: Event.None, + }), + storage, new NullLogService(), configuration, context, + upcastPartial({ registerChatContextItem: () => Disposable.None }), + new TestExperimentTriggerTelemetryService(), + upcastPartial({}), + upcastPartial({ isSessionsWindow: true }), + TestProductService, + )); + const scenario = onboardingScenarioRegistry.getScenario(AGENT_PICKER_SPOTLIGHT_ID)!; + const ready = () => scenario.trigger.kind === 'observable' && scenario.trigger.signal.get(); + const frame = () => new Promise(resolve => disposables.add(dom.scheduleAtNextAnimationFrame(dom.getWindow(button), resolve))); + await frame(); + const noCustomAgents = ready(); + modes.set(upcastPartial({ + custom: [{ ...ChatMode.Agent, id: alpha.uri, isBuiltin: false }], onDidChange: Event.None, + }), undefined); + await frame(); + const newUser = ready(); + usage.recordSessionCreated(); + await frame(); + const defaultAgent = ready(); + mode.set({ id: alpha.uri, kind: 'agent' }, undefined); + const customAgent = ready(); + mode.set(undefined, undefined); + await frame(); + const returnedToDefault = ready(); + phone.set(true); + const mobile = ready(); + phone.set(false); + await frame(); + assert.deepStrictEqual({ noCustomAgents, newUser, defaultAgent, customAgent, returnedToDefault, mobile, desktop: ready() }, { + noCustomAgents: false, newUser: false, defaultAgent: true, customAgent: false, returnedToDefault: true, mobile: false, desktop: true, + }); + }); + } + function controls(context: ContextKeyService, menu: MenuId): string[] { const ids = ['sessions.agentHost.agentPicker', 'sessions.agentHost.newSessionModePicker', 'sessions.modelPicker']; return MenuRegistry.getMenuItems(menu).filter(isIMenuItem) @@ -274,6 +359,8 @@ suite('agentHostAgentPicker', () => { upcastPartial({ registerChatContextItem: () => Disposable.None }), new TestExperimentTriggerTelemetryService(), upcastPartial({ notifyUserAgentSelection: ({ sessionId, agent }) => userSelections.push(`${sessionId} ${agent?.uri ?? 'default'}`) }), + upcastPartial({ isSessionsWindow: false }), + TestProductService, )); const snapshot = () => ({ mode: activeSession.get()?.mode.get()?.id, diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostChatInputPickersScope.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostChatInputPickersScope.test.ts index 5e0442a019c3..d3d688a98457 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostChatInputPickersScope.test.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostChatInputPickersScope.test.ts @@ -24,8 +24,8 @@ import { IsSessionsWindowContext } from '../../../../../../workbench/common/cont import { ChatContextKeys } from '../../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { SessionUsesExperimentalComposerLayoutContext } from '../../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { bindSessionHostScopeContext, createMainWindowInstantiationService, createSessionHostServices, InSessionHostScopeContext, ISessionHost, ISessionHostService, SessionHost, SessionHostKind } from '../../../../../../workbench/services/sessions/browser/sessionHost.js'; -import '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentPicker.js'; -import '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.js'; +import '../../browser/agentHostAgentPicker.contribution.js'; +import '../../browser/agentHostSessionConfigPicker.contribution.js'; /** The pickers of the session a chat input shows, contributed to the workbench's chat input menus. */ const PICKERS = new Set([ diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostForkActions.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostForkActions.test.ts index c4d8b8b15d5d..ad5bae4b8cfe 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostForkActions.test.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostForkActions.test.ts @@ -160,7 +160,7 @@ suite('Agent Host fork actions', () => { kind: multipleChats ? toSide ? 'chatToSide' : 'chat' : toSide ? 'sessionToSide' : 'session', resource: harness.forkChat.resource, options: multipleChats - ? toSide ? { referenceChatResource: harness.sourceChat.resource } : undefined + ? { referenceChatResource: harness.sourceChat.resource } : toSide ? { source: 'fork', referenceSessionId: harness.source.sessionId } : { source: 'fork' }, }], }); @@ -242,7 +242,7 @@ suite('Agent Host fork actions', () => { assert.deepStrictEqual({ forks: harness.forkCalls, opens: harness.opens }, { forks: [{ kind: multipleChats ? 'chat' : 'session', source: harness.sourceChat.resource, requestId: multipleChats ? 'request-2' : undefined }], - opens: [{ kind: multipleChats ? 'chat' : 'session', resource: harness.forkChat.resource, options: multipleChats ? undefined : { source: 'fork' } }], + opens: [{ kind: multipleChats ? 'chat' : 'session', resource: harness.forkChat.resource, options: multipleChats ? { referenceChatResource: harness.sourceChat.resource } : { source: 'fork' } }], }); }); } @@ -307,7 +307,7 @@ suite('Agent Host fork actions', () => { assert.deepStrictEqual({ beforeSecond, forks: harness.forkCalls.length, opens: harness.opens }, { beforeSecond: [], forks: 2, - opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: undefined }], + opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: { referenceChatResource: harness.sourceChat.resource } }], }); }); @@ -336,7 +336,7 @@ suite('Agent Host fork actions', () => { beforeInspection: [], choices: ['Inspect Target'], forks: [{ kind: 'chat', source: harness.sourceChat.resource, requestId: 'request-2' }], - opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: undefined }], + opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: { referenceChatResource: harness.sourceChat.resource } }], }); }); @@ -346,7 +346,7 @@ suite('Agent Host fork actions', () => { assert.deepStrictEqual({ forks: harness.forkCalls, opens: harness.opens }, { forks: [{ kind: 'chat', source: harness.sourceChat.resource, requestId: 'streaming-turn' }], - opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: undefined }], + opens: [{ kind: 'chat', resource: harness.forkChat.resource, options: { referenceChatResource: harness.sourceChat.resource } }], }); }); @@ -361,6 +361,15 @@ suite('Agent Host fork actions', () => { }); }); + test('opens a separately forked session without a reference chat, so a chat window source does not host it (follow-up of #347086)', async () => { + const harness = createHarness(false); + await harness.run(true); + + assert.deepStrictEqual(harness.opens.map(open => ({ kind: open.kind, hasReferenceChat: !!(open.options as { referenceChatResource?: unknown } | undefined)?.referenceChatResource })), [ + { kind: 'sessionToSide', hasReferenceChat: false }, + ]); + }); + test('waits for a separately forked session to appear before opening beside the source', async () => { const harness = createHarness(false); harness.setForkAvailable(false); diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostModePicker.fixture.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostModePicker.fixture.ts index 022a66e5a402..ea79d6a26743 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostModePicker.fixture.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostModePicker.fixture.ts @@ -15,7 +15,6 @@ import { IAgentHostEnablementService } from '../../../../../../platform/agentHos import { IAgentConnection, IAgentHostNetworkDiagnosticsInfo, IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; import { AgentSandboxSettingId } from '../../../../../../platform/sandbox/common/settings.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { getAgentHostOperatingSystem } from '../../../../../../platform/agentHost/common/agentHostOperatingSystem.js'; import { IAgentSubscription } from '../../../../../../platform/agentHost/common/state/agentSubscription.js'; import { ComponentToState, StateComponents } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { ActionType } from '../../../../../../platform/agentHost/common/state/protocol/actions.js'; @@ -53,10 +52,10 @@ import { ISessionsProvider } from '../../../../../../workbench/contrib/sessions/ import '../../../../../../workbench/contrib/sessions/browser/chat/media/chatWidget.css'; import '../../../../../../workbench/contrib/sessions/browser/chat/media/chatInput.css'; import '../../../../../browser/media/style.css'; -import { ITestSessionWithChat, testChatSourceOf } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { ITestSessionWithChat, stubSessionHosts, testChatSourceOf } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; -async function render(context: ComponentFixtureContext, mode: string, permissions: ChatPermissionLevel, sandboxed = false, openPermissions = false, options: { readonly editor?: boolean; readonly openMode?: boolean; readonly newChat?: boolean; readonly primary?: boolean; readonly compact?: boolean; readonly combined?: boolean; readonly phoneWidth?: number; readonly withheld?: 'policy' | 'unattributed' } = {}): Promise { - const { editor = false, openMode = false, newChat = false, primary = false, compact = false, combined = true, phoneWidth, withheld } = options; +async function render(context: ComponentFixtureContext, mode: string, permissions: ChatPermissionLevel, sandboxed = false, openPermissions = false, options: { readonly editor?: boolean; readonly openMode?: boolean; readonly newChat?: boolean; readonly primary?: boolean; readonly compact?: boolean; readonly combined?: boolean; readonly phoneWidth?: number; readonly withheld?: 'policy' | 'unattributed'; readonly hoveredItem?: string; readonly hoveredTrigger?: 'mode' | 'permissions' } = {}): Promise { + const { editor = false, openMode = false, newChat = false, primary = false, compact = false, combined = true, phoneWidth, withheld, hoveredItem, hoveredTrigger } = options; const { container, disposableStore, theme } = context; container.classList.add('monaco-workbench', 'interactive-session', 'modern-ui', 'monaco-enable-motion'); if (!editor) { @@ -141,6 +140,7 @@ async function render(context: ComponentFixtureContext, mode: string, permission override readonly activeChat = constObservable(upcastPartial({ resource: URI.parse('agent-host-copilotcli:/fixture') })); }()); const instantiationService = createEditorServices(disposableStore, { colorTheme: theme, additionalServices: registerWorkbenchServices }); + stubSessionHosts(instantiationService, disposableStore, { session }); const connection = new class extends mock() { override async getNetworkDiagnosticsInfo(): Promise { return { version: '1', os: 'linux', arch: 'x64', proxySettings: {}, proxyEnv: {}, endpoints: [] }; @@ -255,7 +255,6 @@ async function render(context: ComponentFixtureContext, mode: string, permission permissionPicker.render(permissionActionItem); showSeparatePermissions = () => permissionPicker.show(permissionActionItem); } - await getAgentHostOperatingSystem(hostService); } else { const picker = disposableStore.add(instantiationService.createInstance(AgentHostModePicker, testChatSourceOf(session))); picker.render(actionItem); @@ -274,7 +273,6 @@ async function render(context: ComponentFixtureContext, mode: string, permission showSeparatePermissions = () => permissionPicker.show(); } } - await getAgentHostOperatingSystem(connection); } if (openPermissions || editor || openMode) { await dom.getWindow(toolbar).document.fonts.ready; @@ -298,6 +296,22 @@ async function render(context: ComponentFixtureContext, mode: string, permission overlay.style.height = '100%'; disposableStore.add(toDisposable(() => overlay.querySelector('.mobile-picker-sheet-done')?.click())); } + if (hoveredItem) { + const row = [...container.querySelectorAll('.action-widget .monaco-list-row.action')] + .find(candidate => candidate.querySelector('.title')?.textContent === hoveredItem); + if (!row) { + throw new Error(`Expected mode picker item: ${hoveredItem}`); + } + row.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, movementX: 1 })); + } + if (hoveredTrigger) { + const selector = hoveredTrigger === 'mode' ? '.agent-host-mode-button' : '.agent-host-permissions-button'; + const button = toolbar.querySelector(selector); + if (!button) { + throw new Error(`Expected combined picker trigger: ${hoveredTrigger}`); + } + button.classList.add('hovered'); + } } export default defineThemedFixtureGroup({ path: 'sessions/agentHostModePicker' }, { @@ -308,11 +322,29 @@ export default defineThemedFixtureGroup({ path: 'sessions/agentHostModePicker' } SessionChatCompact: defineComponentFixture({ render: context => render(context, 'interactive', ChatPermissionLevel.AutoApprove, false, false, { primary: true, compact: true }), }), + SessionChatModeHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the Interactive half of the combined Mode and Permissions control. In high contrast themes, a dashed active-contrast boundary surrounds only that actionable half.'], + render: context => render(context, 'interactive', ChatPermissionLevel.Default, false, false, { primary: true, hoveredTrigger: 'mode' }), + }), + SessionChatPermissionsHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the Manual permissions half of the combined Mode and Permissions control. In high contrast themes, a dashed active-contrast boundary surrounds only that actionable half.'], + render: context => render(context, 'interactive', ChatPermissionLevel.Default, false, false, { primary: true, hoveredTrigger: 'permissions' }), + }), Manual: defineComponentFixture({ render: context => render(context, 'interactive', ChatPermissionLevel.Default) }), Assisted: defineComponentFixture({ render: context => render(context, 'plan', ChatPermissionLevel.Assisted) }), AllowAll: defineComponentFixture({ render: context => render(context, 'autopilot', ChatPermissionLevel.AutoApprove) }), Sandboxed: defineComponentFixture({ render: context => render(context, 'interactive', ChatPermissionLevel.Default, true) }), Mode: defineComponentFixture({ render: context => render(context, 'interactive', ChatPermissionLevel.Default, true, false, { openMode: true }) }), + ModeHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over Plan in the Agent Mode popup. In high contrast themes, the row uses a dashed active-contrast boundary rather than a solid keyboard-focus boundary.'], + render: context => render(context, 'interactive', ChatPermissionLevel.Default, true, false, { openMode: true, hoveredItem: 'Plan' }), + }), Permissions: defineComponentFixture({ render: context => render(context, 'interactive', ChatPermissionLevel.Default, true, true) }), AssistedPermissions: defineComponentFixture({ additionalThemes: ['darkHighContrast', 'lightHighContrast'], render: context => render(context, 'autopilot', ChatPermissionLevel.Assisted, false, true) }), SeparatePermissions: defineComponentFixture({ additionalThemes: ['darkHighContrast', 'lightHighContrast'], render: context => render(context, 'autopilot', ChatPermissionLevel.Assisted, false, true, { combined: false }) }), diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostSessionConfigPicker.fixture.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostSessionConfigPicker.fixture.ts index 0587b90511c4..10fcf5ec2f25 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostSessionConfigPicker.fixture.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentHostSessionConfigPicker.fixture.ts @@ -15,28 +15,49 @@ import { IContextViewService } from '../../../../../../platform/contextview/brow import { ContextViewService } from '../../../../../../platform/contextview/browser/contextViewService.js'; import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; +import { IChatEntitlementService } from '../../../../../../workbench/services/chat/common/chatEntitlementService.js'; import { IViewsService } from '../../../../../../workbench/services/views/common/viewsService.js'; import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; import { IAgentWorkbenchLayoutService } from '../../../../../browser/workbench.js'; import { ISessionsHostLayoutService } from '../../../../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; -import { IChat } from '../../../../../../workbench/services/sessions/common/session.js'; +import { IChat, ISessionChangeset, ISessionWorkspace, SessionStatus, UNCOMMITTED_CHANGES_CHANGESET_ID } from '../../../../../../workbench/services/sessions/common/session.js'; import { ISessionInputPickerVisibility, SessionInputPickerVisibility } from '../../../../../../workbench/contrib/sessions/common/sessionPickerVisibility.js'; +import { ISendRequestSentEvent, ISessionsManagementService } from '../../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { ISessionsProvider } from '../../../../../../workbench/contrib/sessions/common/sessionsProvider.js'; import { ISessionChangesService } from '../../../../../../workbench/contrib/sessionChanges/browser/sessionChangesService.js'; +import { IOnboardingScenarioService } from '../../../../../../workbench/contrib/onboarding/common/onboardingScenarioService.js'; import { AgentHostSessionConfigPicker } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.js'; -import { IWorktreeSuggestionService } from '../../../../../../workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.js'; +import { IWorktreeSuggestionService, WorktreeSuggestionService } from '../../../../../../workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.js'; +import { WorktreeSuggestionVariant } from '../../../../../../workbench/contrib/sessions/common/worktreeSuggestion.js'; import { NullWorktreeSuggestionService } from '../../../../../../workbench/contrib/sessions/test/browser/worktreeSuggestion/worktreeSuggestionTestUtils.js'; +import { IChatSessionFileChange2 } from '../../../../../../workbench/common/chatSessionFileChange.js'; import '../../../../../../workbench/contrib/sessions/browser/chat/media/chatWidget.css'; import '../../../../../browser/media/style.css'; import { ITestSessionWithChat, testChatSourceOf } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; -async function renderIsolationPicker({ container, disposableStore, theme }: ComponentFixtureContext, value: 'worktree' | 'folder', devContainer = false): Promise { +interface IIsolationPickerOptions { + readonly value: 'worktree' | 'folder'; + readonly devContainer?: boolean; + /** Suggests a new worktree for a folder with uncommitted files, counted after Branch and listed in the picker. */ + readonly uncommittedFiles?: { + /** Whether the user already started a session in a new worktree. */ + readonly worktreeSessionCreated: boolean; + }; +} + +const UNCOMMITTED_FILES = ['src/app.ts', 'README.md', 'src/todo.ts', 'src/store.ts', 'src/view.ts']; + +async function renderIsolationPicker({ container, disposableStore, theme }: ComponentFixtureContext, { value, devContainer = false, uncommittedFiles }: IIsolationPickerOptions): Promise { container.classList.add('monaco-workbench', 'agent-sessions-workbench'); container.style.width = '480px'; - container.style.height = '220px'; + container.style.height = uncommittedFiles ? '340px' : '220px'; container.style.padding = 'var(--vscode-spacing-size160)'; + if (uncommittedFiles) { + // The Git extension registers the color of modified files, which the fixture's color registry lacks. + container.style.setProperty('--vscode-gitDecoration-modifiedResourceForeground', theme.getColor('gitDecoration.modifiedResourceForeground')?.toString() ?? 'var(--vscode-editorWarning-foreground)'); + } const changed = disposableStore.add(new Emitter()); const config: ResolveSessionConfigResult = { schema: { @@ -63,14 +84,41 @@ async function renderIsolationPicker({ container, disposableStore, theme }: Comp changed.fire(sessionId); } override trackSessionConfigOperation(): void { } + override async setIsolationMode(): Promise { } + }(); + const workspace: ISessionWorkspace | undefined = uncommittedFiles && { + label: 'repo', + icon: { id: 'folder' }, + uri: URI.file('/repo'), + folders: [{ + root: URI.file('/repo'), + workingDirectory: URI.file('/repo'), + name: 'repo', + description: undefined, + gitRepository: { uri: URI.file('/repo'), workTreeUri: undefined, baseBranchName: undefined, branchName: 'main', uncommittedChanges: UNCOMMITTED_FILES.length, gitHubInfo: constObservable(undefined) }, + }], + requiresWorkspaceTrust: false, + isVirtualWorkspace: false, + }; + const changes = UNCOMMITTED_FILES.map((path, index): IChatSessionFileChange2 => ({ uri: URI.file(`/repo/${path}`), modifiedUri: URI.file(`/repo/${path}`), insertions: 12 - index * 2, deletions: index })); + const chat = new class extends mock() { + override readonly changesets = constObservable(uncommittedFiles ? [new class extends mock() { + override readonly id = UNCOMMITTED_CHANGES_CHANGESET_ID; + override readonly isEnabled = constObservable(true); + override readonly isLoadingChanges = constObservable(false); + override readonly changes = constObservable(changes); + }()] : undefined); }(); const session = constObservable(new class extends mock() { override readonly sessionId = 'fixture'; + override readonly resource = URI.parse('test-session:/fixture'); override readonly providerId = provider.id; - override readonly workspace = constObservable(undefined); - override readonly activeChat = constObservable(new class extends mock() { - override readonly changesets = constObservable(undefined); - }()); + override readonly status = constObservable(SessionStatus.Untitled); + override readonly loading = constObservable(false); + override readonly worktreePending = constObservable(false); + override readonly workspace = constObservable(workspace); + override readonly activeChat = constObservable(chat); + override readonly mainChat = constObservable(chat); }()); const instantiationService = createEditorServices(disposableStore, { colorTheme: theme, additionalServices: registerWorkbenchServices }); instantiationService.stub(ISessionInputPickerVisibility, disposableStore.add(new SessionInputPickerVisibility())); @@ -84,7 +132,20 @@ async function renderIsolationPicker({ container, disposableStore, theme }: Comp instantiationService.stub(ISessionsHostLayoutService, {}); instantiationService.stub(ISessionChangesService, {}); instantiationService.stub(IViewsService, {}); - instantiationService.stub(IWorktreeSuggestionService, new NullWorktreeSuggestionService()); + if (uncommittedFiles) { + const requestSent = disposableStore.add(new Emitter()); + instantiationService.stub(ISessionsManagementService, { onDidSendRequest: requestSent.event }); + instantiationService.stub(IChatEntitlementService, { sentimentObs: constObservable({}) }); + instantiationService.stub(IOnboardingScenarioService, {}); + const suggestions = disposableStore.add(instantiationService.createInstance(WorktreeSuggestionService)); + suggestions.setPreview(WorktreeSuggestionVariant.UncommittedFilesCount); + if (uncommittedFiles.worktreeSessionCreated) { + requestSent.fire({ session: session.get()!, chat, isNewSession: true, isNewChat: true, newSessionConfig: { isolation: 'worktree', providerConfig: {} }, options: { query: '' } }); + } + instantiationService.stub(IWorktreeSuggestionService, suggestions); + } else { + instantiationService.stub(IWorktreeSuggestionService, new NullWorktreeSuggestionService()); + } instantiationService.set(IQuickInputService, new class extends mock() { }()); instantiationService.set(ILayoutService, new class extends mock() { override readonly mainContainer = container; @@ -104,13 +165,20 @@ async function renderIsolationPicker({ container, disposableStore, theme }: Comp export default defineThemedFixtureGroup({ path: 'sessions/chat/isolationPicker/' }, { NewWorktree: defineComponentFixture({ - render: context => renderIsolationPicker(context, 'worktree'), + render: context => renderIsolationPicker(context, { value: 'worktree' }), }), Branch: defineComponentFixture({ additionalThemes: ['darkHighContrast', 'lightHighContrast'], - render: context => renderIsolationPicker(context, 'folder'), + render: context => renderIsolationPicker(context, { value: 'folder' }), }), DevContainer: defineComponentFixture({ - render: context => renderIsolationPicker(context, 'folder', true), + render: context => renderIsolationPicker(context, { value: 'folder', devContainer: true }), + }), + UncommittedFiles: defineComponentFixture({ + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderIsolationPicker(context, { value: 'folder', uncommittedFiles: { worktreeSessionCreated: false } }), + }), + UncommittedFilesAfterWorktreeSession: defineComponentFixture({ + render: context => renderIsolationPicker(context, { value: 'folder', uncommittedFiles: { worktreeSessionCreated: true } }), }), }); diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.snapshot.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.snapshot.ts new file mode 100644 index 000000000000..27d8147bd3fd --- /dev/null +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.snapshot.ts @@ -0,0 +1,247 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * What the Agents window's sessions list, composer and provider contributions register themselves, in the order they + * register it: the difference between loading what they import and also loading them. See agentsWindowRegistrations.test.ts. + */ +export const AGENTS_WINDOW_REGISTRATIONS: readonly string[] = [ + 'command sessionsViewPane.archiveSessionsWithUndo', + 'command sessionsViewPane.deleteSessionGroupWithUndo', + 'command sessionsViewPane.closeSession', + 'command sessionsViewPane.openSessionAtIndex', + 'command sessionsViewPane.openSessionAtIndex1', + 'command sessionsViewPane.openSessionAtIndex2', + 'command sessionsViewPane.openSessionAtIndex3', + 'command sessionsViewPane.openSessionAtIndex4', + 'command sessionsViewPane.openSessionAtIndex5', + 'command sessionsViewPane.openSessionAtIndex6', + 'command sessionsViewPane.openSessionAtIndex7', + 'command sessionsViewPane.openSessionAtIndex8', + 'command sessionsViewPane.openSessionAtIndex9', + 'command sessionsViewPane.navigatePreviousSession', + 'command sessionsViewPane.navigateNextSession', + 'command sessionsViewPane.showApplicationFilters', + 'command agentSessions.filter.external.none.sessionsviewexternalfilter', + 'command agentSessions.filter.external.recent.sessionsviewexternalfilter', + 'command agentSessions.filter.external.last24Hours.sessionsviewexternalfilter', + 'command agentSessions.filter.external.last7Days.sessionsviewexternalfilter', + 'command agentSessions.filter.external.last30Days.sessionsviewexternalfilter', + 'command sessionsViewPane.toggleExternalSessionsSection', + 'command sessionsViewPane.inboxMode', + 'command sessionsViewPane.sortByCreated', + 'command sessionsViewPane.sortByUpdated', + 'command sessionsViewPane.groupByWorkspace', + 'command sessionsViewPane.groupByRepository', + 'command sessionsViewPane.groupByTime', + 'command sessionsViewPane.groupByEnvironment', + 'command sessionsViewPane.groupByWorktree', + 'command sessionsViewPane.toggleCompact', + 'command sessionsViewPane.showRecentSessions', + 'command sessionsViewPane.showAllSessions', + 'command sessionsViewPane.collapseAllGroups', + 'command sessionsViewPane.refresh', + 'command sessionsViewPane.find', + 'command sessionsViewPane.closeFind', + 'command sessionsView.sectionNewSession', + 'command sessionsView.sectionNewSessionInEnvironment', + 'command sessionsView.newQuickChat', + 'command sessionsView.deleteEmptyGroup', + 'command sessionsView.newSessionInGroup', + 'command sessionsViewPane.openCustomizations', + 'command sessionsViewPane.pinSession', + 'command sessionsViewPane.unpinSession', + 'command sessionsViewPane.inboxResume', + 'command sessionsViewPane.inboxSnooze', + 'command sessionsViewPane.inboxMergePullRequest', + 'command sessionsViewPane.inboxHold', + 'command sessionsViewPane.showAutomationSessionInList', + 'command sessionsViewPane.hideAutomationSessionFromList', + 'command sessionsViewPane.importSession', + 'command sessions.list.openParentSession', + 'command sessionsViewPane.moveChatUp', + 'command sessionsViewPane.moveChatDown', + 'command sessionsViewPane.renameSession', + 'command sessionsViewPane.deleteSession', + 'command sessionsViewPane.markRead', + 'command sessionsViewPane.markUnread', + 'command agentSession.markRead', + 'command agentSession.markUnread', + 'command sessionsViewPane.markAllNestedRead', + 'command sessionsViewPane.openToTheSide', + 'command sessionsView.manageAutomations', + 'command sessionsView.markAllAutomationRunsRead', + 'command sessions.sendInBackground', + 'command sessions.sendLater', + 'command sessions.newChatComposer.initializing', + 'command sessions.newChatComposer.sending', + 'command sessions.newChatComposer.sessionControls', + 'command sessions.compareModels', + 'command sessions.modelPicker', + 'command sessions.agentHost.openAgentPicker', + 'command sessions.agentHost.agentPicker', + 'command sessions.agentHost.newSessionApprovePicker', + 'command sessions.agentHost.newSessionPermissionModePicker', + 'command sessions.agentHost.newSessionCodexApprovalsPicker', + 'command sessions.agentHost.newSessionModePicker', + 'command sessions.agentHost.runningSessionConfigPicker', + 'command sessions.agentHost.runningSessionPermissionModePicker', + 'command sessions.agentHost.runningSessionCodexApprovalsPicker', + 'command sessions.agentHost.runningSessionModePicker', + 'command sessions.sandbox.modePicker', + 'command sessions.sandbox.approvalPicker', + 'menu AutomationsDialogInputToolbar command sessions.modelPicker group navigation order 1 when chatIsEnabled && inAutomationsDialog && !sessionUsesCombinedConfigPicker || chatIsEnabled && inAutomationsDialog && !sessionsIsPhoneLayout', + 'menu AutomationsDialogInputToolbar command sessions.agentHost.agentPicker group navigation order -1 when chatIsEnabled && inAutomationsDialog && !sessionsIsPhoneLayout && sessionProviderId == \'local-agent-host\' || chatIsEnabled && inAutomationsDialog && !sessionsIsPhoneLayout && sessionProviderId =~ /^agenthost-/', + 'menu ChatExecuteSecondary command sessions.sendLater group navigation order 99 when chatIsEnabled && config.sessions.sendLater.enabled && isSessionsWindow && sessionsChatInputCanSchedule', + 'menu ChatInput command sessions.agentHost.agentPicker group navigation order 0 when chatIsAgentHostSession && inSessionHostScope && isSessionsWindow && !chatHasPendingDelegationTarget && !sessionsIsPhoneLayout', + 'menu ChatInput command sessions.agentHost.runningSessionConfigPicker group navigation order 0.2 when chatIsAgentHostSession && inSessionHostScope && sessionUsesExperimentalComposerLayout', + 'menu ChatInput command sessions.agentHost.runningSessionPermissionModePicker group navigation order 0.3 when chatIsAgentHostSession && inSessionHostScope && sessionUsesExperimentalComposerLayout', + 'menu ChatInput command sessions.agentHost.runningSessionCodexApprovalsPicker group navigation order 0.4 when chatIsAgentHostSession && inSessionHostScope && sessionUsesExperimentalComposerLayout', + 'menu ChatInput command sessions.agentHost.runningSessionModePicker group navigation order 0.1 when chatIsAgentHostSession && inSessionHostScope && sessionUsesExperimentalComposerLayout && !chatHasPendingDelegationTarget', + 'menu ChatInputSecondary command sessions.agentHost.runningSessionConfigPicker group navigation order 10 when chatIsAgentHostSession && inSessionHostScope && !sessionUsesExperimentalComposerLayout', + 'menu ChatInputSecondary command sessions.agentHost.runningSessionPermissionModePicker group navigation order 11 when chatIsAgentHostSession && inSessionHostScope && !sessionUsesExperimentalComposerLayout', + 'menu ChatInputSecondary command sessions.agentHost.runningSessionCodexApprovalsPicker group navigation order 12 when chatIsAgentHostSession && inSessionHostScope && !sessionUsesExperimentalComposerLayout', + 'menu ChatInputSecondary command sessions.agentHost.runningSessionModePicker group navigation order 9 when chatIsAgentHostSession && inSessionHostScope && !chatHasPendingDelegationTarget && !sessionUsesExperimentalComposerLayout', + 'menu CommandPalette command sessionsViewPane.closeSession group order when !editorIsOpen && !isNewChatSession', + 'menu CommandPalette command sessionsViewPane.navigatePreviousSession group order when ', + 'menu CommandPalette command sessionsViewPane.navigateNextSession group order when ', + 'menu CommandPalette command sessionsViewPane.inboxMode group order when chatIsEnabled && isSessionsWindow', + 'menu CommandPalette command sessionsViewPane.refresh group order when ', + 'menu CommandPalette command sessionsView.newQuickChat group order when agentHostEnabled && chatIsEnabled', + 'menu CommandPalette command sessions.sendInBackground group order when chatInputHasSendableContent && chatIsEnabled && chatSessionOptionsValid && isSessionsWindow && sessionsChatInputSupportsBackground && !chatInputBlocked', + 'menu CommandPalette command sessions.sendLater group order when chatInputHasSendableContent && chatIsEnabled && isSessionsWindow && sessionsChatInputCanSchedule && !chatInputBlocked', + 'menu CommandPalette command sessions.compareModels group order when chatIsEnabled && chatModelComparisonAvailable && isSessionsWindow', + 'menu NewSessions.ChatInputToolbar command workbench.action.chat.attachContext group navigation order -2 when ', + 'menu NewSessions.ChatInputToolbar command sessions.newChatComposer.initializing group navigation order 100 when sessionsSharedChatInputComposerBusy == \'initializing\'', + 'menu NewSessions.ChatInputToolbar command sessions.newChatComposer.sending group navigation order 100 when sessionsSharedChatInputComposerBusy == \'sending\'', + 'menu NewSessions.ChatInputToolbar command sessions.newChatComposer.sessionControls group navigation order 0 when ', + 'menu NewSessions.ChatInputToolbar command sessions.modelPicker group navigation order 1 when !sessionUsesCombinedConfigPicker || !sessionsIsPhoneLayout', + 'menu NewSessions.SessionControlMenu command sessions.agentHost.agentPicker group navigation order -1 when !inAutomationsDialog && !sessionsIsPhoneLayout && sessionProviderId == \'local-agent-host\' || !inAutomationsDialog && !sessionsIsPhoneLayout && sessionProviderId =~ /^agenthost-/', + 'menu NewSessions.SessionControlMenu command sessions.agentHost.newSessionApprovePicker group navigation order 1 when sessionProviderId == \'local-agent-host\' || sessionProviderId =~ /^agenthost-/', + 'menu NewSessions.SessionControlMenu command sessions.agentHost.newSessionPermissionModePicker group navigation order 2 when sessionProviderId == \'local-agent-host\' || sessionProviderId =~ /^agenthost-/', + 'menu NewSessions.SessionControlMenu command sessions.agentHost.newSessionCodexApprovalsPicker group navigation order 3 when sessionProviderId == \'local-agent-host\' || sessionProviderId =~ /^agenthost-/', + 'menu NewSessions.SessionControlMenu command sessions.agentHost.newSessionModePicker group navigation order 0 when !sessionsIsPhoneLayout && sessionProviderId == \'local-agent-host\' || !sessionsIsPhoneLayout && sessionProviderId =~ /^agenthost-/', + 'menu NewSessions.SessionControlMenu command sessions.sandbox.modePicker group navigation order 0 when chatIsEnabled && isNewChatSession && sessionProviderId == \'cloud-sandbox-creation\' || chatIsEnabled && isNewChatSession && sessionProviderId == \'default-copilot\'', + 'menu NewSessions.SessionControlMenu command sessions.sandbox.approvalPicker group navigation order 1 when chatIsEnabled && isNewChatSession && sessionProviderId == \'cloud-sandbox-creation\' || chatIsEnabled && isNewChatSession && sessionProviderId == \'default-copilot\'', + 'menu SessionGroupToolbar command sessionsView.deleteEmptyGroup group navigation order 2 when sessionGroup.isEmpty && !sessionGroup.isComparison', + 'menu SessionGroupToolbar command sessionsView.newSessionInGroup group navigation order 1 when !sessionGroup.isComparison', + 'menu SessionItemContextMenu command sessionsViewPane.openCustomizations group navigation order 6 when chatIsEnabled', + 'menu SessionItemContextMenu command sessionsViewPane.pinSession group 2_organize order 1 when !sessionIsArchived && !sessionItem.isPinned', + 'menu SessionItemContextMenu command sessionsViewPane.unpinSession group 2_organize order 1 when sessionItem.isPinned && !sessionIsArchived', + 'menu SessionItemContextMenu command sessionsViewPane.inboxResume group 1_state order 1 when chatIsEnabled && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\' && sessionItem.inboxState != \'\'', + 'menu SessionItemContextMenu command sessionsViewPane.inboxSnooze group 1_state order 1.5 when chatIsEnabled && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\'', + 'menu SessionItemContextMenu command sessionsViewPane.inboxMergePullRequest group 1_state order 0 when chatIsEnabled && sessionItem.canMergePullRequest && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\'', + 'menu SessionItemContextMenu command sessionsViewPane.inboxHold group 1_state order 1.25 when chatIsEnabled && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\' && sessionItem.inboxState != \'hold\'', + 'menu SessionItemContextMenu command sessionsViewPane.hideAutomationSessionFromList group 2_organize order 2 when chatAutomationsEnabled && chatIsEnabled && sessionItem.isAutomation && sessionItem.isInSessionsList', + 'menu SessionItemContextMenu command sessionsViewPane.importSession group navigation order 3 when chatIsEnabled && sessionItem.canImport && !sessionIsArchived', + 'menu SessionItemContextMenu command sessionsViewPane.renameSession group 4_manage order 2 when sessionSupportsRename', + 'menu SessionItemContextMenu command sessionsViewPane.deleteSession group 4_manage order 3 when sessionSupportsDelete', + 'menu SessionItemContextMenu command agentSession.markRead group 1_state order 1 when !sessionIsArchived && !sessionIsRead', + 'menu SessionItemContextMenu command agentSession.markUnread group 1_state order 1 when sessionIsRead && !sessionIsArchived', + 'menu SessionItemContextMenu command sessionsViewPane.markAllNestedRead group 1_state order 2 when sessionItem.hasUnreadNestedSessions', + 'menu SessionItemContextMenu submenu SessionsSessionItemOpenIn group navigation order 1 when chatIsEnabled && isSessionsWindow', + 'menu SessionItemToolbar command sessionsViewPane.pinSession group navigation order 1 when !sessionIsArchived && !sessionItem.isPinned && !sessionsListPromoteNewChatAction', + 'menu SessionItemToolbar command sessionsViewPane.unpinSession group navigation order 1 when sessionItem.isPinned && !sessionIsArchived && !sessionsListPromoteNewChatAction', + 'menu SessionItemToolbar command sessionsViewPane.inboxResume group navigation order 1 when chatIsEnabled && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\' && sessionItem.inboxState != \'\'', + 'menu SessionItemToolbar command sessionsViewPane.inboxMergePullRequest group navigation order 0 when chatIsEnabled && sessionItem.canMergePullRequest && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\'', + 'menu SessionItemToolbar command sessionsViewPane.importSession group navigation order 1.5 when chatIsEnabled && sessionItem.canImport && !sessionIsArchived', + 'menu SessionsAutomationsHistoryItemContext command sessionsViewPane.showAutomationSessionInList group 2_organize order 1 when chatAutomationsEnabled && chatIsEnabled && sessionItem.isAutomation && !sessionIsArchived && !sessionItem.isInSessionsList', + 'menu SessionsAutomationsHistoryItemContext command sessionsViewPane.hideAutomationSessionFromList group 2_organize order 2 when chatAutomationsEnabled && chatIsEnabled && sessionItem.isAutomation && sessionItem.isInSessionsList', + 'menu SessionSectionToolbar submenu SessionsViewExternalFilter group navigation order 0 when sessionSection.type == \'external\'', + 'menu SessionSectionToolbar command sessionsView.sectionNewSession group navigation order 0 when chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'environment\' || chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'repository\' || chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'workspace\'', + 'menu SessionSectionToolbar command sessionsView.sectionNewSession group navigation order 0 when !chatIsEnabled && sessionSection.type == \'environment\' || !chatIsEnabled && sessionSection.type == \'repository\' || !chatIsEnabled && sessionSection.type == \'workspace\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'environment\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'repository\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'workspace\'', + 'menu SessionSectionToolbar command sessionsView.newQuickChat group navigation order 0 when agentHostEnabled && chatIsEnabled && sessionSection.type == \'quickchats\'', + 'menu SessionsGoMenu command sessionsViewPane.navigatePreviousSession group 2_list_nav order 1 when ', + 'menu SessionsGoMenu command sessionsViewPane.navigateNextSession group 2_list_nav order 2 when ', + 'menu SessionsSessionBarToolbar command agentSession.markRead group secondary/1_state order 10 when sessionIsCreated && !sessionIsArchived && !sessionIsRead', + 'menu SessionsSessionBarToolbar command agentSession.markUnread group secondary/1_state order 10 when sessionIsCreated && sessionIsRead && !sessionIsArchived', + 'menu SessionsSessionChatItemContext command sessions.list.openParentSession group navigation order 1 when sessionChatItem.isStandalone', + 'menu SessionsSessionChatItemContext command sessionsViewPane.moveChatUp group 2_organize order 1 when chatIsEnabled && sessionChatItem.canMoveUp && sessionsViewPane.sorting == \'created\'', + 'menu SessionsSessionChatItemContext command sessionsViewPane.moveChatDown group 2_organize order 2 when chatIsEnabled && sessionChatItem.canMoveDown && sessionsViewPane.sorting == \'created\'', + 'menu SessionsSessionChatItemContext command agentSession.markRead group 1_state order 1 when sessionChatItem.canSetReadState && !sessionChatItem.isArchived && !sessionChatItem.isRead', + 'menu SessionsSessionChatItemContext command agentSession.markUnread group 1_state order 1 when sessionChatItem.canSetReadState && sessionChatItem.isRead && !sessionChatItem.isArchived', + 'menu SessionsSessionChatItemContext submenu SessionsSessionChatItemOpenIn group navigation order 1 when chatIsEnabled && isSessionsWindow', + 'menu SessionsSessionChatItemToolbar command sessions.list.openParentSession group navigation order 0 when sessionChatItem.isStandalone', + 'menu SessionsSessionGroupContext command sessionsView.newSessionInGroup group navigation order 1 when !sessionGroup.isComparison', + 'menu SessionsSessionHeaderContext command agentSession.markRead group secondary/1_state order 10 when sessionIsCreated && !sessionIsArchived && !sessionIsRead', + 'menu SessionsSessionHeaderContext command agentSession.markUnread group secondary/1_state order 10 when sessionIsCreated && sessionIsRead && !sessionIsArchived', + 'menu SessionsSessionItemOpenIn command sessionsViewPane.openToTheSide group navigation order 1 when isSessionsWindow', + 'menu SessionsSessionSectionContext submenu SessionsViewExternalFilter group 4_manage order 1 when sessionSection.type == \'external\'', + 'menu SessionsSessionSectionContext command sessionsView.sectionNewSession group navigation order 0 when chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'environment\' || chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'repository\' || chatIsEnabled && sessionSection.hasNonCloudRepository && sessionSection.type == \'workspace\'', + 'menu SessionsSessionSectionContext command sessionsView.sectionNewSession group navigation order 0 when !chatIsEnabled && sessionSection.type == \'environment\' || !chatIsEnabled && sessionSection.type == \'repository\' || !chatIsEnabled && sessionSection.type == \'workspace\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'environment\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'repository\' || !sessionSection.hasNonCloudRepository && sessionSection.type == \'workspace\'', + 'menu SessionsSessionSectionContext command sessionsView.newQuickChat group navigation order 0 when agentHostEnabled && chatIsEnabled && sessionSection.type == \'quickchats\'', + 'menu SessionsSidebarSessionsHeader submenu SessionsViewPaneFilterSubMenu group navigation order 10 when ', + 'menu SessionsSidebarSessionsHeader command sessionsViewPane.find group navigation order 20 when ', + 'menu SessionsSidebarSessionsHeader command sessionsViewPane.toggleCompact group 1_view order 0 when chatIsEnabled && !sessionsIsPhoneLayout', + 'menu SessionsSidebarSessionsHeader command sessionsViewPane.collapseAllGroups group 1_view order 1 when chatIsEnabled', + 'menu SessionsViewExternalFilter command agentSessions.filter.external.none.sessionsviewexternalfilter group 1_modes order 0 when ', + 'menu SessionsViewExternalFilter command agentSessions.filter.external.recent.sessionsviewexternalfilter group 1_modes order 1 when ', + 'menu SessionsViewExternalFilter command agentSessions.filter.external.last24Hours.sessionsviewexternalfilter group 1_modes order 2 when ', + 'menu SessionsViewExternalFilter command agentSessions.filter.external.last7Days.sessionsviewexternalfilter group 1_modes order 3 when ', + 'menu SessionsViewExternalFilter command agentSessions.filter.external.last30Days.sessionsviewexternalfilter group 1_modes order 4 when ', + 'menu SessionsViewExternalFilter command sessionsViewPane.toggleExternalSessionsSection group 2_grouping order 0 when chatIsEnabled', + 'menu SessionsViewGrouping command sessionsViewPane.inboxMode group 1_group order 4 when chatIsEnabled', + 'menu SessionsViewGrouping command sessionsViewPane.groupByWorkspace group 1_group order 1 when ', + 'menu SessionsViewGrouping command sessionsViewPane.groupByRepository group 1_group order 2 when ', + 'menu SessionsViewGrouping command sessionsViewPane.groupByTime group 1_group order 0 when ', + 'menu SessionsViewGrouping command sessionsViewPane.groupByEnvironment group 1_group order 3 when ', + 'menu SessionsViewGrouping command sessionsViewPane.groupByWorktree group 1_group order 3.5 when !isSessionsWindow', + 'menu SessionsViewOrdering command sessionsViewPane.sortByCreated group 1_sort order 0 when ', + 'menu SessionsViewOrdering command sessionsViewPane.sortByUpdated group 1_sort order 1 when ', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewOrdering group 1_presentation order 0 when ', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewGrouping group 1_presentation order 1 when ', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewShow group 1_presentation order 2 when sessionsViewPane.grouping == \'environment\' || sessionsViewPane.grouping == \'repository\' || sessionsViewPane.grouping == \'workspace\'', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewShow group 1_presentation order 2 when !isSessionsWindow && sessionsViewPane.grouping == \'worktree\'', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewSource group 2_filters order 1 when ', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewHarness group 2_filters order 2 when ', + 'menu SessionsViewPaneFilterSubMenu submenu SessionsViewExternalFilter group 3_visibility order 0 when ', + 'menu SessionsViewShow command sessionsViewPane.showRecentSessions group 1_show order 0 when sessionsViewPane.grouping == \'environment\' || sessionsViewPane.grouping == \'repository\' || sessionsViewPane.grouping == \'workspace\'', + 'menu SessionsViewShow command sessionsViewPane.showRecentSessions group 1_show order 0 when !isSessionsWindow && sessionsViewPane.grouping == \'worktree\'', + 'menu SessionsViewShow command sessionsViewPane.showAllSessions group 1_show order 1 when sessionsViewPane.grouping == \'environment\' || sessionsViewPane.grouping == \'repository\' || sessionsViewPane.grouping == \'workspace\'', + 'menu SessionsViewShow command sessionsViewPane.showAllSessions group 1_show order 1 when !isSessionsWindow && sessionsViewPane.grouping == \'worktree\'', + 'keybinding sessions.agentHost.openAgentPicker weight 101 when inChatInput && sessionActiveChatIsUntitled && sessionProviderId == \'local-agent-host\' || inChatInput && sessionActiveChatIsUntitled && sessionProviderId =~ /^agenthost-/', + 'keybinding agentSession.markRead weight 250 when isSessionsWindow && listFocus && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'keybinding agentSession.markUnread weight 250 when isSessionsWindow && listFocus && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'keybinding agentic.workbench.view.sessionsContainer weight 250 when viewContainer.agentic.workbench.view.sessionsContainer.enabled', + 'keybinding sessions.compareModels weight 250 when chatInputHasFocus && chatIsEnabled && chatModelComparisonAvailable && isSessionsWindow || chatIsEnabled && chatModelComparisonAvailable && chatModelComparisonPickerFocused && isSessionsWindow || chatIsEnabled && chatModelComparisonAvailable && inChatComposer && isSessionsWindow', + 'keybinding sessions.sendInBackground weight 250 when chatInputHasSendableContent && chatIsEnabled && chatSessionOptionsValid && inChatInput && isSessionsWindow && sessionsChatInputSupportsBackground && !chatInputBlocked', + 'keybinding sessions.sendInBackground weight 250 when chatInputHasSendableContent && chatIsEnabled && chatSessionOptionsValid && inChatInput && isSessionsWindow && sessionsChatInputSupportsBackground && !chatInputBlocked && sessionsViewPane.grouping == \'inbox\'', + 'keybinding sessionsView.newQuickChat weight 250 when agentHostEnabled && chatIsEnabled && isSessionsWindow && !editorAreaFocus', + 'keybinding sessionsViewPane.archiveSession weight 250 when isSessionsWindow && listFocus && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'keybinding sessionsViewPane.closeFind weight 250 when listFocus && sessionsListSearchOpen && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'keybinding sessionsViewPane.find weight 250 when listFocus && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'keybinding sessionsViewPane.moveChatDown weight 250 when chatIsEnabled && isSessionsWindow && listFocus && sessionChatItem.canMoveDown && sessionsList.focusedChatItem && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\' && sessionsViewPane.sorting == \'created\'', + 'keybinding sessionsViewPane.moveChatUp weight 250 when chatIsEnabled && isSessionsWindow && listFocus && sessionChatItem.canMoveUp && sessionsList.focusedChatItem && !inputFocus && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\' && sessionsViewPane.sorting == \'created\'', + 'keybinding sessionsViewPane.navigateNextSession weight 250 when isSessionsWindow && !editorAreaFocus', + 'keybinding sessionsViewPane.navigatePreviousSession weight 250 when isSessionsWindow && !editorAreaFocus', + 'keybinding sessionsViewPane.openSessionAtIndex1 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex2 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex3 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex4 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex5 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex6 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex7 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex8 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.openSessionAtIndex9 weight 250 when isSessionsWindow', + 'keybinding sessionsViewPane.renameSession weight 250 when inChat && isSessionsWindow && sessionSupportsRename && !sessionItem.isMultiSelection || isSessionsWindow && listFocus && !inputFocus && !sessionItem.isMultiSelection && !treestickyScrollFocused && focusedView == \'sessions.workbench.view.sessionsView\'', + 'configuration sessions.drafts.enabled', + 'configuration sessions.sendLater.enabled', + 'configuration sessions.sidebar.separateNavigation', + 'configuration sessions.list.groupExternalSessions', + 'configuration sessions.list.inboxEnabled', + 'configuration sessions.list.agentTools.enabled', + 'configuration sessions.list.externalApplicationBadge', + 'configuration sessions.list.externalApplicationBadgeShowFrom', + 'configuration sessions.list.showEmptyDefaultGroups', + 'configuration sessions.list.showUnreadInCollapsedSections', + 'configuration sessions.list.showArchivedByDefault', + 'configuration sessions.list.showAutomationSessions', + 'configuration sessions.list.indentItems', + 'configuration sessions.showChatTabs', + 'configuration sessions.markAsDoneConfetti', + 'configuration sessions.useWorktree', + 'singleton sessionAttentionService', + 'accessibleView sessions-list-notification help priority 110 when sessionsListNotificationFocused', +]; diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.test.ts new file mode 100644 index 000000000000..16bd6b68ee32 --- /dev/null +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/agentsWindowRegistrations.test.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 assert from 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { isIMenuItem, MenuId, MenuRegistry } from '../../../../../../platform/actions/common/actions.js'; +import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; +import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../../platform/configuration/common/configurationRegistry.js'; +import { getSingletonServiceDescriptors } from '../../../../../../platform/instantiation/common/extensions.js'; +import { KeybindingsRegistry } from '../../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { Registry } from '../../../../../../platform/registry/common/platform.js'; +import { AccessibleViewRegistry } from '../../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { AGENTS_WINDOW_REGISTRATIONS } from './agentsWindowRegistrations.snapshot.js'; +// The contributions whose registrations it snapshots +import '../../../../sessions/browser/sessions.contribution.js'; +import '../../../../sessions/browser/views/sessionsViewActions.js'; +import '../../../../chat/browser/sharedChatInputComposer.contribution.js'; +import '../../../../chat/browser/modelPicker.js'; +import '../../browser/localAgentHost.contribution.js'; +import '../../browser/agentHostAgentPicker.contribution.js'; +import '../../browser/agentHostSessionConfigPicker.contribution.js'; +import '../../../copilotChatSessions/browser/copilotChatSessions.contribution.js'; +import '../../../copilotChatSessions/browser/copilotChatSessionsActions.js'; + +/** + * What the registries hold, one line each, in the order they were registered: commands, the items of every menu, + * primary keybindings (with their weights, which order them), configuration keys, singletons and accessible views. + */ +function registrations(): string[] { + const result: string[] = []; + for (const id of CommandsRegistry.getCommands().keys()) { + result.push(`command ${id}`); + } + // Every menu, also those that are not static members of MenuId, by id: the order the menus were created in does not matter + const menus = [...(MenuId as unknown as { readonly _instances: ReadonlyMap })._instances.values()].sort((a, b) => a.id.localeCompare(b.id)); + for (const menu of menus) { + for (const item of MenuRegistry.getMenuItems(menu)) { + const target = isIMenuItem(item) ? `command ${item.command.id}${item.alt ? ` alt ${item.alt.id}` : ''}` : `submenu ${item.submenu.id}`; + result.push(`menu ${menu.id} ${target} group ${item.group ?? ''} order ${item.order ?? ''} when ${item.when?.serialize() ?? ''}`); + } + } + // Chords and secondary keybindings are resolved for the current OS, so only primary keybindings are listed, without their chords + for (const keybinding of KeybindingsRegistry.getDefaultKeybindings()) { + if (keybinding.weight2 === 0) { + result.push(`keybinding ${keybinding.command} weight ${keybinding.weight1} when ${keybinding.when?.serialize() ?? ''}`); + } + } + for (const key of Object.keys(Registry.as(ConfigurationExtensions.Configuration).getConfigurationProperties())) { + result.push(`configuration ${key}`); + } + for (const [id] of getSingletonServiceDescriptors()) { + result.push(`singleton ${id}`); + } + for (const implementation of AccessibleViewRegistry.getImplementations()) { + result.push(`accessibleView ${implementation.name} ${implementation.type} priority ${implementation.priority} when ${implementation.when?.serialize() ?? ''}`); + } + return result; +} + +/** + * What identifies a registration, regardless of how it is registered: a command, configuration key, singleton or + * accessible view by its line up to its details, a menu item by its menu and target, a keybinding by its command. + */ +function keyOf(registration: string): string { + const details = /^(menu .*?) group |^(keybinding .*?) weight |^(accessibleView \S+) /.exec(registration); + return details?.[1] ?? details?.[2] ?? details?.[3] ?? registration; +} + +suite('Agents window registrations', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('the Agents window registers the same commands, menu items, keybindings, settings, services and accessible views, each once', () => { + // Each line holds what orders it: a menu item's group, order and when, a keybinding's weight and when. In which + // order other suites loaded these contributions, and so registered them, depends on the tests that run. + // Everything registered under a key of the snapshot must be exactly its lines: no duplicates and no extra entries. + const keys = new Set(AGENTS_WINDOW_REGISTRATIONS.map(keyOf)); + const registered = registrations().filter(registration => keys.has(keyOf(registration))).sort(); + + assert.deepStrictEqual(registered, [...AGENTS_WINDOW_REGISTRATIONS].sort()); + }); +}); 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 dfc5f6c66f25..7e105095769e 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 @@ -94,6 +94,7 @@ import { devContainerSamples, devContainerSampleUri } from '../../../../../../pl import { IAgentCustomizationScope, IAgentHostActiveClientService } from '../../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostActiveClientService.js'; import { IAgentHostMcpAppToolsService } from '../../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostMcpAppToolsService.js'; import { LocalAgentHostSessionsProvider } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/localAgentHostSessionsProvider.js'; +import { AgentHostArtifactIntegrations } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostArtifactIntegrations.js'; import { AgentHostSessionAdapter, type IAgentHostAdapterOptions } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/baseAgentHostSessionsProvider.js'; import { withSessionInitiator } from '../../../../../../platform/agentHost/common/meta/agentSessionInitiatorMeta.js'; import { ILabelService } from '../../../../../../platform/label/common/label.js'; @@ -755,6 +756,7 @@ function createProvider(disposables: DisposableStore, agentHostService: MockAgen ], options?: { chatSessionsService?: Partial; sendRequest?: (resource: URI, message: string, options?: IChatSendRequestOptions) => Promise; acquireOrLoadSession?: (resource: URI) => Promise; languageModelsService?: Partial; languageModelIds?: string[]; lookupLanguageModel?: (modelId: string) => ILanguageModelChatMetadata | undefined; languageModelChanges?: Event; hiddenLanguageModelIds?: ReadonlySet; languageModelVisibilityChanges?: Event; getChatModel?: (resource: URI) => IChatModel | undefined; openSession?: boolean; configurationService?: IConfigurationService; activeSession?: IObservable; visibleSessions?: IObservable; windowSessions?: IObservable; activeClient?: Omit; sessionTools?: (resource: URI) => readonly ToolDefinition[]; mcpAppTools?: (resource: URI) => readonly ToolDefinition[]; activeClientAgents?: IObservable; activeClientScope?: (sessionType: string, roots: readonly URI[]) => IAgentCustomizationScope; storageService?: IStorageService; recentWorkspacesService?: ISessionsRecentWorkspacesService; isSessionsWindow?: boolean; confirmDelete?: boolean; workspaceTrusted?: boolean; requestWorkspaceTrust?: (uri: URI) => Promise; workspaceTrustBarrier?: DeferredPromise; workspaceTrustError?: Error; setUrisTrust?: (uris: URI[], trusted: boolean) => Promise; gitHubService?: IGitHubService; devContainerAgentHostService?: IDevContainerAgentHostService; sessionsProvidersService?: ISessionsProvidersService; pathService?: IPathService; labelService?: ILabelService; telemetryService?: ITelemetryService; providerCtor?: typeof LocalAgentHostSessionsProvider }): LocalAgentHostSessionsProvider { const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stubInstance(AgentHostArtifactIntegrations, { setConnection: () => { }, dispose: () => { } }); instantiationService.stub(IAgentHostService, agentHostService); instantiationService.stub(IAgentHostConnectionsService, new class extends mock() { private readonly _resources = new ResourceMap(); @@ -3592,6 +3594,36 @@ suite('LocalAgentHostSessionsProvider', () => { ]); })); + for (const rejected of [false, true]) { + test(`archive waits for host confirmation and propagates rejection=${rejected}`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const backend = URI.parse('opaque-session://tenant/archiving'); + const provider = createProvider(disposables, agentHost); + await timeout(0); + fireSessionAdded(agentHost, 'archiving', { resource: backend }); + await timeout(0); + const session = provider.getSessions()[0]; + const acknowledgement = new DeferredPromise(); + const dispatched = new DeferredPromise(); + const calls: string[] = []; + agentHost.dispatchConfirmed = async (channel, _subscription, action) => { + calls.push(channel); + await dispatched.complete(); + await acknowledgement.p; + return { channel, action, serverSeq: 1, origin: undefined, ...(rejected ? { rejectionReason: 'Archive denied' } : {}) }; + }; + let completed = false; + const archive = provider.archiveSession(session.sessionId).then(() => { completed = true; }); + const result = rejected ? assert.rejects(archive, /Archive denied/) : archive; + await dispatched.p; + const beforeAcknowledgement = completed; + await acknowledgement.complete(); + await result; + assert.deepStrictEqual({ beforeAcknowledgement, completed, archived: session.isArchived.get(), calls, released: agentHost.sessionUnsubscribeCounts.get(backend.toString()) }, { + beforeAcknowledgement: false, completed: !rejected, archived: !rejected, calls: [backend.toString()], released: 1, + }); + })); + } + test('a summaryChanged modifiedAt advances the last turn end like a listing', () => runWithFakedTimers({ useFakeTimers: true }, async () => { agentHost.addSession(createSession('turn-end', { summary: 'Turn End', modifiedTime: 1_000 })); const provider = createProvider(disposables, agentHost); @@ -4156,6 +4188,61 @@ suite('LocalAgentHostSessionsProvider', () => { }, { unavailable: [], source: { name: agent.name, uri: URI.parse(agent.uri) }, available: ids.slice(1), current: ids[2], cleared: ids }); }); + for (const disconnectDuringLoad of [false, true]) { + test(`background row sends reject an unavailable local host before optimistic submission and allow retry (disconnectDuringLoad=${disconnectDuringLoad})`, async () => { + const connected = observableValue('connected', true); + const host = new class extends MockAgentHostService { + override readonly connectionAvailable = connected; + }(); + disposables.add(toDisposable(() => host.dispose())); + host.addSession(createSession('retry', { summary: 'Retry' })); + let loads = 0; + let sends = 0; + let releases = 0; + const provider = createRefreshableProvider(disposables, host, { + acquireOrLoadSession: async () => { + loads++; + if (disconnectDuringLoad && loads === 1) { + connected.set(false, undefined); + } + return { + object: new class extends mock() { + override readonly inputModel = new class extends mock() { + override readonly state = constObservable(undefined); + override setState(): void { } + override clearState(): void { } + }(); + }(), + dispose: () => { releases++; }, + }; + }, + sendRequest: async () => { + sends++; + return { kind: 'sent', data: upcastPartial({}) }; + }, + }); + await provider.refreshForTest(); + const session = provider.getSessions()[0]; + const chat = session.mainChat.get(); + const management = createManagementService(disposables, provider); + if (!disconnectDuringLoad) { + connected.set(false, undefined); + } + await assert.rejects(management.sendRequestInBackground(session, chat, { query: '/fix-ci' }), /agent host is unavailable/); + const failed = { sends, loads, releases }; + connected.set(true, undefined); + await management.sendRequestInBackground(session, chat, { query: '/fix-ci' }); + const retried = { sends, loads, releases }; + connected.set(false, undefined); + await provider.sendRequest(session.sessionId, chat.resource, { query: 'Foreground request' }); + assert.deepStrictEqual({ failed, retried, foregroundSends: sends }, { + failed: { sends: 0, loads: disconnectDuringLoad ? 1 : 0, releases: disconnectDuringLoad ? 1 : 0 }, + retried: { sends: 1, loads: disconnectDuringLoad ? 2 : 1, releases: disconnectDuringLoad ? 2 : 1 }, + foregroundSends: 2, + }); + }); + } + test('agent metadata changes refresh model availability without changing the selected agent', async () => { const agent: AgentCustomization = { type: CustomizationType.Agent, id: 'required', uri: 'other-host:/required', name: 'Required', @@ -12537,12 +12624,23 @@ suite('LocalAgentHostSessionsProvider', () => { })); const recordedByEach = readIcons(); + // A chat that only references a pull request another chat created does not show its icon. + agentHost.setSessionState('multi-pr-icon', 'copilotcli', makeState(chats, { + defaultChat, + meta: withSessionArtifacts(discovered, [ + { id: 'main-pr', chat: defaultChat, type: SessionArtifactType.PullRequest, label: 'Main PR', isArtifact: true, isGitHub: true, link: 'https://github.com/microsoft/vscode/pull/2' }, + { id: 'peer-ref', chat: peerChat, type: SessionArtifactType.PullRequest, label: 'Peer reference', isArtifact: false, isGitHub: true, link: 'https://github.com/microsoft/vscode/pull/2' }, + ]), + })); + const referencedByPeer = readIcons(); + const openIcon = computePullRequestIcon(GitHubPullRequestState.Open).id; - assert.deepStrictEqual({ discoveredOnly, recordedByPeer, recordedByUnknownChat, recordedByEach }, { + assert.deepStrictEqual({ discoveredOnly, recordedByPeer, recordedByUnknownChat, recordedByEach, referencedByPeer }, { discoveredOnly: { session: openIcon, main: openIcon, peer: undefined }, recordedByPeer: { session: undefined, main: undefined, peer: openIcon }, recordedByUnknownChat: { session: undefined, main: undefined, peer: undefined }, recordedByEach: { session: openIcon, main: openIcon, peer: openIcon }, + referencedByPeer: { session: openIcon, main: openIcon, peer: undefined }, }); }); diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/mobileChatPhoneInputPresenter.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/mobileChatPhoneInputPresenter.test.ts new file mode 100644 index 000000000000..34939c991020 --- /dev/null +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/mobileChatPhoneInputPresenter.test.ts @@ -0,0 +1,996 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../../base/browser/window.js'; +import { EventType as TouchEventType } from '../../../../../../base/browser/touch.js'; +import { Action } from '../../../../../../base/common/actions.js'; +import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { constObservable, derived, observableValue } from '../../../../../../base/common/observable.js'; +import { extUri } from '../../../../../../base/common/resources.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; +import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; +import { MenuId, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { IActionWidgetService } from '../../../../../../platform/actionWidget/browser/actionWidget.js'; +import { IAgentHostEnablementService } from '../../../../../../platform/agentHost/common/agentHostEnablementService.js'; +import { IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; +import { agentHostConnectionKinds } from '../../../../../../platform/agentHost/test/common/testAgentHostResourceUriMappers.js'; +import { ResolveSessionConfigResult } from '../../../../../../platform/agentHost/common/state/protocol/commands.js'; +import { AgentCustomization, CustomizationType } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { ClaudeSessionConfigKey } from '../../../../../../platform/agentHost/common/claudeSessionConfigKeys.js'; +import { CodexSessionConfigKey } from '../../../../../../platform/agentHost/common/codexSessionConfigKeys.js'; +import { SessionConfigKey } from '../../../../../../platform/agentHost/common/sessionConfigKeys.js'; +import { IConfigurationService, IConfigurationValue } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; +import { TestDialogService } from '../../../../../../platform/dialogs/test/common/testDialogService.js'; +import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; +import { IStorageService, InMemoryStorageService } from '../../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IProductService } from '../../../../../../platform/product/common/productService.js'; +import { IUpdateService } from '../../../../../../platform/update/common/update.js'; +import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; +import { getSingletonServiceDescriptors } from '../../../../../../platform/instantiation/common/extensions.js'; +import { createServices } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { IUriIdentityService } from '../../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IChatPetService } from '../../../../../../workbench/contrib/chat/browser/chatPetService.js'; +import { IChatWidgetService } from '../../../../../../workbench/contrib/chat/browser/chat.js'; +import { ChatConfiguration } from '../../../../../../workbench/contrib/chat/common/constants.js'; +import { resetShownWarnings } from '../../../../../../workbench/contrib/chat/common/chatPermissionWarnings.js'; +import { ChatPhoneInputPresenterRequest, IChatPhoneInputPresenter, IChatPhoneInputSessionContext, IChatPhoneSessionModelPicker, MobileChatInputCombinedPickerActionItem } from '../../../../../../workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { whenModelConfigValuesSaved } from '../../../../../../workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerModelConfig.js'; +import { IChatMode, IChatModes } from '../../../../../../workbench/contrib/chat/common/chatModes.js'; +import { ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService, IModelConfigurationAccess } from '../../../../../../workbench/contrib/chat/common/languageModels.js'; +import { IWorkbenchLayoutService } from '../../../../../../workbench/services/layout/browser/layoutService.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../workbench/services/environment/common/environmentService.js'; +import { IPreferencesService } from '../../../../../../workbench/services/preferences/common/preferences.js'; +import { ChatEntitlement, IChatEntitlementService } from '../../../../../../workbench/services/chat/common/chatEntitlementService.js'; +import { TestChatEntitlementService, TestLifecycleService, TestWorkspaceTrustManagementService } from '../../../../../../workbench/test/common/workbenchTestServices.js'; +import { NullLanguageModelsService } from '../../../../../../workbench/contrib/chat/test/common/languageModels.js'; +import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; +import { ISessionsService } from '../../../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { ISessionsProvidersService, SessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { ISessionModelsSnapshot } from '../../../../../../workbench/contrib/sessions/common/sessionsProvider.js'; +import { MobileChatPhoneInputPresenterContribution } from '../../browser/mobile/mobileChatPhoneInputPresenter.js'; +import { INewChatModelPickerService, NewChatModelPickerService } from '../../../../../../workbench/contrib/sessions/browser/chat/newChatModelPicker.js'; +import { ModelPicker } from '../../../../chat/browser/modelPicker.js'; +import { ISessionModelSelection } from '../../../../../../workbench/contrib/sessions/browser/chat/sessionModelSelection.js'; +import { createModelSelectionState, normalizeModelPickerOptions } from '../../../../../../workbench/contrib/sessions/browser/chat/sessionModelPickerState.js'; +import { IChatSessionsService } from '../../../../../../workbench/contrib/chat/common/chatSessionsService.js'; +import { MockChatSessionsService } from '../../../../../../workbench/contrib/chat/test/common/mockChatSessionsService.js'; +import { ISessionsManagementService } from '../../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { IChat, ISession, ISessionAgentRef, SessionStatus } from '../../../../../../workbench/services/sessions/common/session.js'; +import { ISessionHost, SessionHostKind } from '../../../../../../workbench/services/sessions/browser/sessionHost.js'; +import { stubSessionHosts } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { MobilePermissionPicker } from '../../../../../../workbench/contrib/sessions/providers/copilotChatSessions/browser/mobilePermissionPicker.js'; +import { MobileAgentHostModePicker } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileAgentHostModePicker.js'; +import { AgentHostPermissionPickerDelegate } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.js'; +import { AgentHostSessionConfigPickerContribution } from '../../../../../../workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.js'; +import { Menus } from '../../../../../../workbench/contrib/sessions/browser/menus.js'; +import { ILifecycleService } from '../../../../../../workbench/services/lifecycle/common/lifecycle.js'; +import { IManagedSettingsService } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; + +suite('Mobile workbench - MobileChatPhoneInputPresenter', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => resetShownWarnings()); + + function createHarness(modelCount = 2, options: { + readonly cloud?: boolean; + readonly approvals?: boolean; + readonly speed?: boolean; + readonly confirmPermissions?: boolean; + readonly customAgents?: boolean; + readonly customAgentUri?: string; + readonly customAgentContainer?: 'directory' | 'plugin'; + readonly selectedAgentUri?: string; + readonly sourceAgentUri?: string; + readonly mapAgentHostResource?: (uri: URI) => URI; + readonly sandbox?: boolean; + readonly unpublishedDraft?: boolean; + readonly inputHostKind?: SessionHostKind.Composer | SessionHostKind.AutomationDialog; + } = {}) { + const container = dom.append(mainWindow.document.body, dom.$('div.phone-layout')); + store.add(toDisposable(() => container.remove())); + const contextKeys = new MockContextKeyService(); + contextKeys.createKey('sessionsIsPhoneLayout', true); + const models: ILanguageModelChatMetadataAndIdentifier[] = Array.from({ length: modelCount }, (_, index) => ({ + identifier: `copilot:model-${index}`, + metadata: { + extension: new ExtensionIdentifier('test.models'), + id: `model-${index}`, + name: `Model ${index}`, + vendor: 'copilot', + version: '1', + family: 'test', + maxInputTokens: 264000, + maxOutputTokens: 64000, + isDefaultForLocation: {}, + configurationSchema: { + properties: { + effort: { type: 'string', title: 'Reasoning', group: 'navigation', enum: ['low', 'high'], enumItemLabels: ['Low', 'High'], default: 'low' }, + context: { type: 'number', title: 'Context Window', group: 'tokens', enum: [264000, 1000000], enumItemLabels: ['264K', '1M'], default: 264000 }, + }, + }, + }, + })); + if (options.speed) { + models[1] = { ...models[0], identifier: 'copilot:model-0-fast', metadata: { ...models[0].metadata, id: 'model-0-fast', name: 'Model 0 Fast' } }; + } + const mode = upcastPartial({ id: 'agent', label: constObservable('Agent'), icon: constObservable(Codicon.copilot) }); + const currentModel = observableValue('model', models[0]); + const writes: { model: string; values: Record }[] = []; + const configuration = new Map>(); + const access: IModelConfigurationAccess = { + getModelConfiguration: model => configuration.get(model), + getModelConfigurationActions: () => [], + setModelConfiguration: async (model, values) => { + writes.push({ model, values }); + configuration.set(model, { ...configuration.get(model), ...values }); + }, + }; + let context: IChatPhoneInputSessionContext = { + providerId: options.cloud ? 'cloud-draft-creation' : LOCAL_AGENT_HOST_PROVIDER_ID, + sessionId: 'session-one', + sessionType: options.sandbox ? 'copilotcli' : 'test', + chatResource: URI.parse('chat:/one'), + modelId: models[0].identifier, + }; + const mainChat = upcastPartial({ + resource: context.chatResource, + modelId: derived(reader => currentModel.read(reader)?.identifier), + }); + const activeChat = observableValue('chat', mainChat); + const selectedAgent = observableValue<{ id: string; kind: string } | undefined>('agent', options.selectedAgentUri ? { id: options.selectedAgentUri, kind: 'agent' } : undefined); + const inputSession = constObservable(upcastPartial({ + providerId: context.providerId, + sessionId: context.sessionId, + sessionType: context.sessionType, + resource: URI.parse('session:/one'), + mainChat: constObservable(mainChat), + chats: activeChat.map(chat => chat === mainChat ? [chat] : [mainChat, chat]), + status: constObservable(SessionStatus.Untitled), + mode: selectedAgent, + })); + const inputSource = { session: inputSession, chat: activeChat }; + const configChanged = store.add(new Emitter()); + let config: ResolveSessionConfigResult | undefined = options.approvals ? { + schema: { + type: 'object', properties: { + mode: { type: 'string', title: 'Mode', enum: ['interactive', 'plan', 'autopilot'], enumLabels: ['Interactive', 'Plan', 'Autopilot'], default: 'interactive', sessionMutable: true }, + approvalMode: { type: 'string', title: 'Approvals', enum: ['manual', 'assisted', 'allow-all'], default: 'manual', sessionMutable: true }, + ...(options.sandbox ? { [SessionConfigKey.SandboxEnabled]: { type: 'string' as const, title: 'Sandbox', enum: ['on', 'off'], default: 'off', sessionMutable: true } } : {}), + } + }, + values: { mode: 'interactive', approvalMode: 'manual' }, + } : undefined; + const configWrites: { key: string; value: unknown }[] = []; + const resolving = observableValue('resolving', false); + const agentWrites: (ISessionAgentRef | undefined)[] = []; + let configSaveBarrier: DeferredPromise | undefined; + const configProvider = { + getSessionConfig: () => config, + getCreateSessionConfig: () => options.cloud || options.unpublishedDraft ? config?.values : undefined, + isSessionConfigResolving: () => resolving, + onDidChangeSessionConfig: configChanged.event, + setSessionConfigValue: async (_id: string, chat: URI, key: string, value: unknown) => { + assert.ok(extUri.isEqual(chat, context.chatResource)); + if (configSaveBarrier) { + resolving.set(true, undefined); + await configSaveBarrier.p; + } + configWrites.push({ key, value }); + if (config) { + config = { ...config, values: { ...config.values, [key]: value } }; + configChanged.fire(context.sessionId); + } + resolving.set(false, undefined); + }, + }; + const customAgent: AgentCustomization = { + type: CustomizationType.Agent, id: 'planner', uri: options.customAgentUri ?? 'file:///agents/planner.agent.md', + name: 'Planner', description: 'Plan the task', + }; + const provider = upcastPartial({ + ...configProvider, + id: context.providerId, + sessionConfig: configProvider, + getModelsSnapshot: () => upcastPartial({ models }), + getModelPickerOptions: () => ({ showAutoModel: true, useGroupedModelPicker: false, showFeatured: false, showUnavailableFeatured: false, showManageModelsAction: false }), + getAutomationModelConfiguration: () => assert.fail('A live picker must not use automation configuration'), + getSessions: () => options.unpublishedDraft ? [] : [inputSession.get()], + getCustomAgents: () => [customAgent], + getCustomizations: () => options.customAgentContainer === 'plugin' + ? [{ type: CustomizationType.Plugin, id: 'plugin', uri: 'file:///agents', name: 'Plugin', clientId: 'foreign', children: [customAgent] }] + : options.customAgentContainer === 'directory' + ? [{ type: CustomizationType.Directory, id: 'agents', uri: 'file:///agents', name: 'Agents', contents: CustomizationType.Agent, enabled: true, writable: true, children: [customAgent] }] + : [], + mapAgentHostResource: uri => options.mapAgentHostResource?.(uri) ?? uri, + resolveCustomAgent: (_id, uri) => uri === options.sourceAgentUri ? customAgent : undefined, + setAgent: options.customAgents ? (_sessionId, agent) => { + agentWrites.push(agent); + selectedAgent.set(agent && { id: agent.uri, kind: 'agent' }, undefined); + } : undefined, + }); + let policyRestricted = false; + const configurationService = new class extends TestConfigurationService { + override inspect(key: string): IConfigurationValue { + const value = super.inspect(key); + return { ...value, policyValue: policyRestricted && key === ChatConfiguration.GlobalAutoApprove ? value.value : undefined }; + } + }({ [ChatConfiguration.GlobalAutoApprove]: false }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const dialogService = new TestDialogService(undefined, { result: options.confirmPermissions ?? true }); + const errors: unknown[] = []; + const newChatModelPicker = new NewChatModelPickerService(); + const entitlementService = new TestChatEntitlementService(); + entitlementService.entitlement = ChatEntitlement.Pro; + const descriptor = getSingletonServiceDescriptors().find(([id]) => id === IChatPhoneInputPresenter)?.[1]; + assert.ok(descriptor); + const instantiationService = createServices(store.add(new DisposableStore()), [ + [IChatPhoneInputPresenter, descriptor.ctor], + [IContextKeyService, contextKeys], + [ICommandService, upcastPartial({})], + [IWorkbenchLayoutService, upcastPartial({ mainContainer: container })], + [ISessionsService, upcastPartial({ slotPanes: constObservable([]) })], + [ISessionsManagementService, upcastPartial({ + getSessionForChatResource: resource => { + for (const session of provider.getSessions()) { + const chat = session.chats.get().find(chat => extUri.isEqual(resource, chat.resource)); + if (chat) { + return { session, chat }; + } + } + return undefined; + }, + })], + [ILifecycleService, store.add(new TestLifecycleService())], + [IManagedSettingsService, upcastPartial({ onDidChangeManagedSettings: Event.None })], + [IAgentHostService, upcastPartial({})], + [ISessionsProvidersService, SessionsProvidersService], + [IUriIdentityService, upcastPartial({ extUri })], + [IChatPetService, upcastPartial({})], + [ILanguageModelsService, new class extends NullLanguageModelsService { + override getLanguageModelIds() { return models.map(model => model.identifier); } + override async setModelConfiguration() { assert.fail('The session-scoped model configuration must be used'); } + }()], + [IConfigurationService, configurationService], + [IDialogService, dialogService], + [IStorageService, store.add(new InMemoryStorageService())], + [IActionWidgetService, upcastPartial({ isVisible: false, hide: () => { } })], + [IHoverService, upcastPartial({ setupDelayedHover: () => Disposable.None })], + [ITelemetryService, NullTelemetryService], + [IOpenerService, upcastPartial({ open: async () => true })], + [IAgentHostEnablementService, upcastPartial({ + managedSandboxEnforced: constObservable(false), managedSandboxAllowsBypass: constObservable(false), + })], + [IWorkbenchEnvironmentService, upcastPartial({})], + [INotificationService, upcastPartial({ error: error => errors.push(error) })], + [IChatWidgetService, upcastPartial({ getWidgetBySessionResource: () => undefined })], + [IKeybindingService, new MockKeybindingService()], + [IProductService, upcastPartial({ version: '1.142.0', quality: 'dev' })], + [IDefaultAccountService, upcastPartial({})], + [IUpdateService, upcastPartial({})], + [IWorkspaceTrustManagementService, store.add(new TestWorkspaceTrustManagementService())], + [IWorkspaceTrustRequestService, upcastPartial({})], + [IChatEntitlementService, entitlementService], + [IPreferencesService, upcastPartial({})], + [IChatSessionsService, new MockChatSessionsService()], + [IActionViewItemService, getSingletonServiceDescriptors().find(([id]) => id === IActionViewItemService)![1].ctor], + [ISessionModelSelection, upcastPartial({ + state: derived(reader => createModelSelectionState(models, normalizeModelPickerOptions(undefined), currentModel.read(reader), undefined)), + modelConfiguration: access, + selectModel: identifier => { + const model = models.find(model => model.identifier === identifier); + if (!model) { + return false; + } + currentModel.set(model, undefined); + context = { ...context, modelId: model.identifier }; + return true; + }, + })], + ]); + const { mainHost, sessionHostService } = stubSessionHosts(instantiationService, store); + const inputHost = upcastPartial({ + ...inputSource, + id: 'input-host', + kind: options.inputHostKind ?? SessionHostKind.Composer, + parent: mainHost, + }); + const inputHostRegistration = store.add(sessionHostService.registerHost(inputHost)); + instantiationService.stub(ISessionHost, inputHost); + store.add(instantiationService.get(ISessionsProvidersService).registerProvider(provider)); + const presenter = instantiationService.get(IChatPhoneInputPresenter); + const enabledBefore = presenter.enabled.get(); + const contribution = store.add(instantiationService.createInstance(MobileChatPhoneInputPresenterContribution)); + const delegates: ChatPhoneInputPresenterRequest = { + kind: 'delegates', + modeDelegate: { + currentMode: constObservable(mode), + currentChatModes: constObservable(upcastPartial({ builtin: [mode], custom: [] })), + sessionResource: () => undefined, + }, + modelDelegate: { + currentModel, + getModels: () => models, + setModel: model => { + currentModel.set(model, undefined); + context = { ...context, modelId: model.identifier }; + }, + getPresentationOptions: () => ({ showFeatured: false, showAutoModel: true, showModelIcon: false, useGroupedModelPicker: false, showUnavailableFeatured: false, showManageModelsAction: false }), + modelConfiguration: access, + }, + }; + const session: ChatPhoneInputPresenterRequest = { + kind: 'session', + getSessionContext: () => context, + modelDelegate: delegates.modelDelegate, + selectModel: identifier => { + context = { ...context, modelId: identifier }; + return true; + }, + }; + const currentSheet = () => container.querySelector('.mobile-picker-sheet:not(.closing)'); + const row = (label: string) => { + const result = Array.from(currentSheet()?.querySelectorAll('.mobile-picker-sheet-item') ?? []) + .find(item => item.querySelector('.mobile-picker-sheet-label')?.textContent === label); + assert.ok(result, `Missing sheet row: ${label}`); + return result; + }; + const open = (request: ChatPhoneInputPresenterRequest) => { + const closed = presenter.showCombinedModeAndModelSheet(container, request); + store.add(toDisposable(() => currentSheet()?.querySelector('.mobile-picker-sheet-done')?.click())); + return closed; + }; + const close = () => currentSheet()?.querySelector('.mobile-picker-sheet-done')?.click(); + return { + container, presenter, contribution, enabledBefore, delegates, session, open, close, currentSheet, row, writes, access, currentModel, + switchChat: () => { + context = { ...context, chatResource: URI.parse('chat:/two') }; + activeChat.set(upcastPartial({ resource: context.chatResource, modelId: derived(reader => currentModel.read(reader)?.identifier) }), undefined); + }, + configWrites, errors, dialogService, configurationService, newChatModelPicker, instantiationService, + inputSession, inputSource, + unregisterInputHost: () => inputHostRegistration.dispose(), + models, resolving, agentWrites, + holdConfigSave: (barrier: DeferredPromise) => { configSaveBarrier = barrier; }, + updateConfig: (next: ResolveSessionConfigResult) => { config = next; configChanged.fire(context.sessionId); }, + restrictPermissions: () => { policyRestricted = true; }, + waitForSelection: async () => { + const busy = currentSheet()?.querySelector('[aria-busy="true"]'); + if (busy) { + await new Promise(resolve => { + const observer = new mainWindow.MutationObserver(() => { + if (busy.getAttribute('aria-busy') !== 'true') { + observer.disconnect(); + resolve(); + } + }); + store.add(toDisposable(() => observer.disconnect())); + observer.observe(busy, { attributes: true, attributeFilter: ['aria-busy'] }); + }); + } + assert.ok(!currentSheet()?.querySelector('[aria-busy="true"]')); + }, + }; + } + + for (const provider of ['claude', 'codex'] as const) { + for (const running of [false, true]) { + test(`${provider} ${running ? 'running' : 'draft'} approvals pill uses the same sheet and advertised values`, async () => { + const harness = createHarness(); + const key = provider === 'claude' ? ClaudeSessionConfigKey.PermissionMode : CodexSessionConfigKey.PermissionsPreset; + const value = provider === 'claude' ? 'acceptEdits' : 'auto-review'; + harness.updateConfig({ + schema: { type: 'object', properties: { [key]: { type: 'string', title: 'Approvals', enum: ['default', value], enumLabels: ['Manual', 'Selected permissions'], default: 'default', sessionMutable: true } } }, + values: { [key]: 'default' }, + }); + const { instantiationService } = harness; + store.add(instantiationService.createInstance(AgentHostSessionConfigPickerContribution)); + const actionId = `sessions.agentHost.${running ? 'running' : 'new'}Session${provider === 'claude' ? 'PermissionMode' : 'CodexApprovals'}Picker`; + const factory = instantiationService.get(IActionViewItemService).lookUp(running ? MenuId.ChatInputSecondary : Menus.NewSessionControl, actionId)!; + const action = instantiationService.createInstance(MenuItemAction, { id: actionId, title: 'Approvals' }, undefined, undefined, undefined, undefined); + const picker = store.add(factory(action, {}, instantiationService, mainWindow.vscodeWindowId)!); + const host = dom.append(harness.container, dom.$('div')); + picker.render(host); + host.querySelector('.action-label')!.click(); + const title = harness.currentSheet()?.querySelector('.mobile-picker-sheet-title')?.textContent; + harness.row('Selected permissions').click(); + await harness.waitForSelection(); + harness.close(); + await timeout(300); + assert.deepStrictEqual({ title, writes: harness.configWrites }, { title: 'Configure Session', writes: [{ key, value }] }); + }); + } + } + + for (const control of ['model name', 'model details', 'mode', 'permissions', 'running permissions'] as const) { + test(`${control} pill opens Configure Session rather than a desktop popup`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const harness = createHarness(2, { cloud: control !== 'running permissions', approvals: true }); + const { instantiationService } = harness; + instantiationService.stub(INewChatModelPickerService, harness.newChatModelPicker); + const toolbar = dom.append(harness.container, dom.$('div')); + const modelPicker = store.add(instantiationService.createInstance(ModelPicker, constObservable(false))); + modelPicker.render(dom.append(toolbar, dom.$('div'))); + let trigger: HTMLElement; + if (control === 'model name' || control === 'model details') { + trigger = toolbar.querySelector(control === 'model name' ? '.model-picker-name' : '.model-picker-config')!; + trigger.dispatchEvent(new mainWindow.Event(TouchEventType.Tap, { bubbles: true })); + trigger.dispatchEvent(new mainWindow.MouseEvent('mousedown', { button: 0, bubbles: true })); + } else if (control === 'mode') { + const picker = store.add(instantiationService.createInstance(MobileAgentHostModePicker, harness.inputSource)); + trigger = picker.render(dom.append(toolbar, dom.$('div'))); + trigger.click(); + } else if (control === 'permissions') { + const delegate = store.add(instantiationService.createInstance(AgentHostPermissionPickerDelegate, harness.inputSource)); + const picker = store.add(instantiationService.createInstance(MobilePermissionPicker, delegate)); + const host = dom.append(toolbar, dom.$('div')); + picker.render(host); + trigger = host.querySelector('.action-label')!; + trigger.click(); + trigger.dispatchEvent(new mainWindow.Event(TouchEventType.Tap, { bubbles: true })); + } else { + store.add(instantiationService.createInstance(AgentHostSessionConfigPickerContribution)); + const actionId = 'sessions.agentHost.runningSessionConfigPicker'; + const factory = instantiationService.get(IActionViewItemService).lookUp(MenuId.ChatInputSecondary, actionId)!; + assert.ok(factory); + const action = instantiationService.createInstance(MenuItemAction, { id: actionId, title: 'Approvals' }, undefined, undefined, undefined, undefined); + const picker = store.add(factory(action, {}, instantiationService, mainWindow.vscodeWindowId)!); + const host = dom.append(toolbar, dom.$('div')); + picker.render(host); + trigger = host.querySelector('.action-label')!; + trigger.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + } + const state = { + title: harness.currentSheet()?.querySelector('.mobile-picker-sheet-title')?.textContent, + sheets: harness.container.querySelectorAll('.mobile-picker-sheet:not(.closing)').length, + desktop: harness.container.querySelectorAll('.context-view, .quick-input-widget, .model-picker-tabbed-widget').length, + sections: Array.from(harness.currentSheet()?.querySelectorAll('.mobile-picker-sheet-section-title') ?? [], element => element.textContent), + }; + harness.close(); + await timeout(500); + assert.deepStrictEqual({ ...state, focused: mainWindow.document.activeElement === trigger }, { + title: 'Configure Session', sheets: 1, desktop: 0, + sections: ['Agent Mode', 'Model', 'Reasoning', 'Context Window', 'Approvals'], + focused: true, + }); + }); + }); + } + + test('finds the originating input by provider, session and chat, and removes disposed registrations', () => { + const { presenter } = createHarness(); + const context = { providerId: 'host-one', sessionId: 'opaque-session', sessionType: 'copilot', chatResource: URI.parse('ahp-session:/same'), modelId: undefined }; + const makePicker = (providerId: string): IChatPhoneSessionModelPicker => ({ + getSessionContext: () => ({ ...context, providerId }), + selectModel: () => true, + }); + const expected = makePicker('host-one'); + const registration = store.add(presenter.registerSessionModelPicker(expected)); + store.add(presenter.registerSessionModelPicker(makePicker('host-two'))); + const matched = presenter.getSessionModelPicker(context) === expected; + const wrongSession = presenter.getSessionModelPicker({ ...context, sessionId: 'different' }); + const wrongChat = presenter.getSessionModelPicker({ ...context, chatResource: URI.parse('ahp-session:/another') }); + registration.dispose(); + assert.deepStrictEqual({ matched, wrongSession, wrongChat, afterDispose: presenter.getSessionModelPicker(context) }, { + matched: true, wrongSession: undefined, wrongChat: undefined, afterDispose: undefined, + }); + }); + + test('an input constructed before phone activation registers its selection callback when the presenter becomes enabled', () => { + const harness = createHarness(); + const enabled = observableValue('enabled', false); + store.add(harness.presenter.setImpl({ enabled, supportsUnifiedConfiguration: true, showCombinedModeAndModelSheet: async () => { } })); + harness.instantiationService.stub(INewChatModelPickerService, harness.newChatModelPicker); + store.add(harness.instantiationService.createInstance(ModelPicker, constObservable(false))); + const context = harness.session.getSessionContext()!; + const before = harness.presenter.getSessionModelPicker(context); + enabled.set(true, undefined); + const selected = harness.presenter.getSessionModelPicker(context)?.selectModel(harness.models[1].identifier); + enabled.set(false, undefined); + assert.deepStrictEqual({ before, selected, model: harness.currentModel.get()?.identifier, after: harness.presenter.getSessionModelPicker(context) }, { + before: undefined, selected: true, model: harness.models[1].identifier, after: undefined, + }); + }); + + test('registers and removes the experimental implementation through the existing presenter hook', () => { + const { presenter, contribution, enabledBefore } = createHarness(); + const enabledDuring = presenter.enabled.get(); + contribution.dispose(); + assert.deepStrictEqual([enabledBefore, enabledDuring, presenter.enabled.get()], [false, true, false]); + }); + + test('the factory renders the mobile button and coalesces keyboard, click and tap activation', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const harness = createHarness(); + const { modeDelegate, modelDelegate } = harness.delegates; + const action = store.add(new Action('test.config', 'Configure')); + const item = harness.presenter.createActionViewItem?.(action, modeDelegate, modelDelegate); + assert.ok(item); + store.add(item); + const buttonContainer = dom.append(harness.container, dom.$('div')); + item.render(buttonContainer); + const trigger = buttonContainer.querySelector('.chat-phone-input-chip')!; + const icons = Array.from(trigger.querySelectorAll('.codicon'), element => element.className); + trigger.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })); + trigger.click(); + trigger.dispatchEvent(new mainWindow.Event(TouchEventType.Tap, { bubbles: true, cancelable: true })); + const opened = { + sheets: harness.container.querySelectorAll('.mobile-picker-sheet:not(.closing)').length, + expanded: trigger.getAttribute('aria-expanded'), + }; + harness.close(); + await timeout(500); + assert.deepStrictEqual({ label: trigger.textContent, icons, opened, expanded: trigger.getAttribute('aria-expanded'), focused: mainWindow.document.activeElement === trigger }, { + label: 'Model 0', + icons: ['codicon codicon-chevron-down chat-phone-input-chip-chevron'], + opened: { sheets: 1, expanded: 'true' }, + expanded: 'false', + focused: true, + }); + }); + }); + + test('the original full-workbench button keeps its mode icon and needs no custom factory', () => { + const harness = createHarness(); + harness.contribution.dispose(); + const { modeDelegate, modelDelegate } = harness.delegates; + const action = store.add(new Action('test.config', 'Configure')); + const customItem = harness.presenter.createActionViewItem?.(action, modeDelegate, modelDelegate); + const item = store.add(harness.instantiationService.createInstance(MobileChatInputCombinedPickerActionItem, action, modeDelegate, modelDelegate)); + const buttonContainer = dom.append(harness.container, dom.$('div')); + item.render(buttonContainer); + assert.deepStrictEqual({ + customItem, + label: buttonContainer.querySelector('.chat-input-picker-label')?.textContent, + modeIcon: !!buttonContainer.querySelector('.codicon-copilot'), + chevron: !!buttonContainer.querySelector('.chat-phone-input-chip-chevron'), + }, { customItem: undefined, label: 'Model 0', modeIcon: true, chevron: false }); + }); + + for (const source of ['delegates', 'session'] as const) { + test(`${source} retains model, reasoning and context choices with scoped writes`, async () => { + const harness = createHarness(); + const closed = harness.open(harness[source]); + const sections = Array.from(harness.currentSheet()!.querySelectorAll('.mobile-picker-sheet-section-title'), element => element.textContent); + const modelNavigates = !!harness.row('Model 0').querySelector('.mobile-picker-sheet-chevron'); + harness.row('High').click(); + await harness.waitForSelection(); + harness.row('1M').click(); + await whenModelConfigValuesSaved(harness.access); + await harness.waitForSelection(); + const checked = Array.from(harness.currentSheet()!.querySelectorAll('.mobile-picker-sheet-item.checked .mobile-picker-sheet-label'), element => element.textContent); + harness.close(); + await closed; + assert.deepStrictEqual({ sections, modelNavigates, checked, writes: harness.writes }, { + sections: [...(source === 'delegates' ? ['Agent Mode'] : []), 'Model', 'Reasoning', 'Context Window'], + modelNavigates: true, + checked: [...(source === 'delegates' ? ['Agent'] : []), 'High', '1M'], + writes: [ + { model: 'copilot:model-0', values: { effort: 'high' } }, + { model: 'copilot:model-0', values: { context: 1000000 } }, + ], + }); + }); + } + + test('does not apply configuration from an open sheet after switching chats', async () => { + const harness = createHarness(); + const closed = harness.open(harness.session); + harness.switchChat(); + harness.row('High').click(); + harness.close(); + await closed; + assert.deepStrictEqual(harness.writes, []); + }); + + for (const cloud of [false, true]) { + test(`${cloud ? 'Cloud draft' : 'running session'} includes permissions and saves confirmed choices through the existing picker`, async () => { + const harness = createHarness(2, { cloud, approvals: true }); + const closed = harness.open({ ...harness.session, initialSection: 'permissions' }); + const initialFocus = mainWindow.document.activeElement?.textContent; + harness.row('Allow all').click(); + await harness.waitForSelection(); + const checked = harness.row('Allow all').getAttribute('aria-current'); + harness.row('Plan').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ initialFocus, checked, writes: harness.configWrites, errors: harness.errors }, { + initialFocus: 'Manual permissionsAsks when approval settings don\'t apply', + checked: 'true', + writes: [{ key: 'approvalMode', value: 'allow-all' }, { key: 'mode', value: 'plan' }], + errors: [], + }); + }); + } + + for (const { hostKind, delegates } of [ + { hostKind: SessionHostKind.Composer, delegates: false }, + { hostKind: SessionHostKind.AutomationDialog, delegates: false }, + { hostKind: SessionHostKind.Composer, delegates: true }, + ] as const) { + test(`unpublished ${hostKind} draft keeps configuration scoped to its input (${delegates ? 'delegates' : 'session'})`, async () => { + const harness = createHarness(2, { + unpublishedDraft: true, inputHostKind: hostKind, approvals: true, speed: true, customAgents: true, + }); + const request: ChatPhoneInputPresenterRequest = delegates ? { + ...harness.delegates, + modeDelegate: { ...harness.delegates.modeDelegate, sessionResource: () => harness.inputSource.chat.get().resource }, + } : harness.session; + const closed = harness.open(request); + try { + harness.row('Allow all').click(); + await harness.waitForSelection(); + harness.row('Plan').click(); + await harness.waitForSelection(); + harness.row('Planner').click(); + await harness.waitForSelection(); + harness.row('Fast').click(); + await harness.waitForSelection(); + harness.row('High').click(); + await harness.waitForSelection(); + assert.deepStrictEqual({ + config: harness.configWrites, + agents: harness.agentWrites, + agentChecked: harness.row('Planner').getAttribute('aria-current'), + model: harness.currentModel.get()?.identifier, + modelConfiguration: harness.writes, + errors: harness.errors, + }, { + config: [{ key: 'approvalMode', value: 'allow-all' }, { key: 'mode', value: 'plan' }], + agents: [{ uri: 'file:///agents/planner.agent.md', name: 'Planner' }], + agentChecked: 'true', + model: 'copilot:model-0-fast', + modelConfiguration: [{ model: 'copilot:model-0-fast', values: { effort: 'high' } }], + errors: [], + }); + } finally { + harness.close(); + await closed; + } + }); + } + + test('a disposed draft input cannot apply a pending permission confirmation', async () => { + const harness = createHarness(2, { unpublishedDraft: true, approvals: true }); + const closed = harness.open(harness.session); + try { + harness.row('Allow all').click(); + harness.unregisterInputHost(); + await harness.waitForSelection(); + assert.deepStrictEqual({ writes: harness.configWrites, errors: harness.errors }, { writes: [], errors: [] }); + } finally { + harness.close(); + await closed; + } + }); + + test('a running input configures its own chat when the host shows another chat', async () => { + const harness = createHarness(2, { approvals: true }); + const targetChat = harness.inputSource.chat.get(); + harness.inputSource.chat.set({ ...targetChat, resource: URI.parse('chat:/other') }, undefined); + const closed = harness.open({ + ...harness.delegates, + modeDelegate: { ...harness.delegates.modeDelegate, sessionResource: () => targetChat.resource }, + }); + harness.row('Allow all').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ writes: harness.configWrites, errors: harness.errors }, { + writes: [{ key: 'approvalMode', value: 'allow-all' }], errors: [], + }); + }); + + for (const outcome of ['cancel', 'changed chat', 'changed policy'] as const) { + test(`permission ${outcome} does not write or show an unconfirmed checkmark`, async () => { + const harness = createHarness(2, { cloud: true, approvals: true, confirmPermissions: outcome !== 'cancel' }); + const closed = harness.open(harness.session); + harness.row('Allow all').click(); + if (outcome === 'changed chat') { + harness.switchChat(); + } else if (outcome === 'changed policy') { + harness.restrictPermissions(); + } + await harness.waitForSelection(); + const checked = outcome === 'changed chat' ? undefined : harness.row('Manual permissions').getAttribute('aria-current'); + harness.close(); + await closed; + assert.deepStrictEqual({ writes: harness.configWrites, checked, errors: harness.errors }, { + writes: [], checked: outcome === 'changed chat' ? undefined : 'true', errors: [], + }); + }); + } + + test('enterprise policy disables elevated permission rows in Configure Session', async () => { + const harness = createHarness(2, { cloud: true, approvals: true }); + harness.restrictPermissions(); + const closed = harness.open(harness.session); + const disabled = ['Manual permissions', 'Assisted permissions', 'Allow all'].map(label => harness.row(label).disabled); + harness.close(); + await closed; + assert.deepStrictEqual(disabled, [false, true, true]); + }); + + test('Cloud draft speed and model configuration use the owning model delegate', async () => { + const harness = createHarness(2, { cloud: true, speed: true }); + const closed = harness.open({ ...harness.session, initialSection: 'modelConfiguration' }); + const focus = mainWindow.document.activeElement?.textContent; + harness.row('Fast').click(); + await harness.waitForSelection(); + harness.row('High').click(); + await harness.waitForSelection(); + const checked = harness.row('Fast').getAttribute('aria-current'); + harness.close(); + await closed; + assert.deepStrictEqual({ focus, checked, model: harness.currentModel.get()?.identifier, writes: harness.writes }, { + focus: 'Low', checked: 'true', model: 'copilot:model-0-fast', + writes: [{ model: 'copilot:model-0-fast', values: { effort: 'high' } }], + }); + }); + + test('the current input model wins while the provider model snapshot catches up', async () => { + const harness = createHarness(2, { cloud: true }); + harness.currentModel.set(harness.models[1], undefined); + const closed = harness.open(harness.session); + const displayed = harness.row('Model 1').textContent; + harness.row('High').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ displayed, writes: harness.writes }, { + displayed: 'Model 12 models available', writes: [{ model: 'copilot:model-1', values: { effort: 'high' } }], + }); + }); + + test('custom agent selection and clearing preserve the existing provider contract', async () => { + const harness = createHarness(2, { customAgents: true }); + const closed = harness.open(harness.session); + harness.row('Planner').click(); + await harness.waitForSelection(); + const checked = harness.row('Planner').getAttribute('aria-current'); + harness.row('Default Agent').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ checked, writes: harness.agentWrites }, { + checked: 'true', writes: [{ uri: 'file:///agents/planner.agent.md', name: 'Planner' }, undefined], + }); + }); + + test('a composer can configure its model before a provider session exists', async () => { + const harness = createHarness(); + const closed = harness.open({ ...harness.session, getSessionContext: () => undefined }); + harness.row('High').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual(harness.writes, [{ model: 'copilot:model-0', values: { effort: 'high' } }]); + }); + + test('custom agent selection preserves an opaque provider-advertised URI', async () => { + const uri = 'custom-agent://other-host/catalogue/opaque-agent?revision=42'; + const harness = createHarness(2, { + customAgents: true, customAgentUri: uri, + mapAgentHostResource: () => assert.fail('Standalone advertised agents must not be remapped'), + }); + const closed = harness.open(harness.session); + harness.row('Planner').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual(harness.agentWrites, [{ uri, name: 'Planner' }]); + }); + + for (const kind of agentHostConnectionKinds) { + for (const container of ['directory', 'plugin'] as const) { + for (const selection of ['host', 'client', 'draft source'] as const) { + test(`normalizes ${container} agents in ${kind.name} from ${selection} selection`, async () => { + const hostUri = URI.parse('file:///agents/planner.agent.md'); + const clientUri = kind.toClient(hostUri).toString(); + const sourceUri = 'client-agent:/draft-source'; + const harness = createHarness(2, { + customAgents: true, + customAgentUri: hostUri.toString(), + customAgentContainer: container, + mapAgentHostResource: uri => kind.resourceUris.fromAgentHost(uri), + selectedAgentUri: selection === 'host' ? hostUri.toString() : selection === 'client' ? clientUri : sourceUri, + sourceAgentUri: sourceUri, + }); + const closed = harness.open(harness.session); + const checked = harness.row('Planner').getAttribute('aria-current'); + harness.row('Default Agent').click(); + await harness.waitForSelection(); + harness.row('Planner').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ checked, writes: harness.agentWrites }, { + checked: 'true', writes: [undefined, { uri: clientUri, name: 'Planner' }], + }); + }); + } + } + } + + test('running permissions use the live input model-configuration store rather than the automation store', async () => { + const harness = createHarness(2, { approvals: true }); + const editorWrites: Record[] = []; + let editorValues: Record = { effort: 'low' }; + const editorAccess: IModelConfigurationAccess = { + getModelConfiguration: () => editorValues, + getModelConfigurationActions: () => [], + setModelConfiguration: async (_id, values) => { + editorWrites.push(values); + editorValues = { ...editorValues, ...values }; + }, + }; + const action = store.add(new Action('running.model', 'Model')); + const item = harness.presenter.createActionViewItem!(action, { + ...harness.delegates.modeDelegate, + sessionResource: () => harness.inputSource.chat.get().resource, + }, { ...harness.delegates.modelDelegate, modelConfiguration: editorAccess })!; + store.add(item); + item.render(dom.append(harness.container, dom.$('div'))); + const { instantiationService } = harness; + store.add(instantiationService.createInstance(AgentHostSessionConfigPickerContribution)); + const actionId = 'sessions.agentHost.runningSessionConfigPicker'; + const factory = instantiationService.get(IActionViewItemService).lookUp(MenuId.ChatInputSecondary, actionId)!; + const permissionAction = instantiationService.createInstance(MenuItemAction, { id: actionId, title: 'Approvals' }, undefined, undefined, undefined, undefined); + const picker = store.add(factory(permissionAction, {}, instantiationService, mainWindow.vscodeWindowId)!); + const host = dom.append(harness.container, dom.$('div')); + picker.render(host); + host.querySelector('.action-label')!.click(); + harness.row('High').click(); + await harness.waitForSelection(); + harness.close(); + await timeout(300); + assert.deepStrictEqual({ editorWrites, automationWrites: harness.writes }, { editorWrites: [{ effort: 'high' }], automationWrites: [] }); + }); + + test('sandbox changes await resolution and leave the refreshed controls enabled', async () => { + const harness = createHarness(2, { approvals: true, sandbox: true }); + const barrier = new DeferredPromise(); + harness.holdConfigSave(barrier); + const closed = harness.open(harness.session); + harness.row('On').click(); + const pending = { + busy: !!harness.currentSheet()?.querySelector('[aria-busy="true"]'), + resolving: harness.resolving.get(), + }; + await barrier.complete(); + await harness.waitForSelection(); + const enabled = ['On', 'Off', 'Allow all', 'Plan'].map(label => !harness.row(label).disabled); + const checked = harness.row('On').getAttribute('aria-current'); + harness.close(); + await closed; + assert.deepStrictEqual({ pending, enabled, checked, writes: harness.configWrites }, { + pending: { busy: true, resolving: true }, enabled: [true, true, true, true], checked: 'true', + writes: [{ key: SessionConfigKey.SandboxEnabled, value: 'on' }], + }); + }); + + test('late-resolving permissions appear without reopening the sheet or moving model focus', async () => { + const harness = createHarness(); + harness.resolving.set(true, undefined); + const closed = harness.open({ ...harness.session, initialSection: 'model' }); + const sheet = harness.currentSheet(); + harness.updateConfig({ + schema: { + type: 'object', properties: { + approvalMode: { type: 'string', title: 'Approvals', enum: ['manual', 'allow-all'], default: 'manual', sessionMutable: true }, + mode: { type: 'string', title: 'Mode', enum: ['interactive', 'plan'], default: 'interactive', sessionMutable: true }, + } + }, + values: { approvalMode: 'manual', mode: 'interactive' }, + }); + harness.resolving.set(false, undefined); + const state = { + sameSheet: sheet === harness.currentSheet(), + focused: mainWindow.document.activeElement?.querySelector('.mobile-picker-sheet-label')?.textContent, + permissionEnabled: !harness.row('Allow all').disabled, + }; + harness.row('Allow all').click(); + await harness.waitForSelection(); + harness.close(); + await closed; + assert.deepStrictEqual({ ...state, writes: harness.configWrites }, { + sameSheet: true, focused: 'Model 0', permissionEnabled: true, writes: [{ key: 'approvalMode', value: 'allow-all' }], + }); + }); + + test('a failed model-configuration save reports the error and keeps the saved value checked', async () => { + const harness = createHarness(); + const failure = new Error('Could not save configuration'); + harness.access.setModelConfiguration = async () => { throw failure; }; + const closed = harness.open(harness.session); + harness.row('High').click(); + await harness.waitForSelection(); + const selected = harness.row('Low').getAttribute('aria-current'); + harness.close(); + await closed; + assert.deepStrictEqual({ errors: harness.errors, selected }, { errors: [failure], selected: 'true' }); + }); + + test('read-only configuration and resolving permissions cannot be changed from the sheet', async () => { + const harness = createHarness(2, { approvals: true }); + harness.models[0].metadata.configurationSchema!.properties!.effort.readOnly = true; + harness.resolving.set(true, undefined); + const closed = harness.open(harness.session); + const disabled = ['High', 'Plan', 'Allow all'].map(label => harness.row(label).disabled); + harness.close(); + await closed; + assert.deepStrictEqual({ disabled, configWrites: harness.configWrites, writes: harness.writes }, { disabled: [true, true, true], configWrites: [], writes: [] }); + }); + + for (const source of ['delegates', 'session'] as const) { + test(`${source} searchable model selection rebuilds configuration for the new model`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const harness = createHarness(9); + const closed = harness.open(harness[source]); + harness.row('Model 0').click(); + await timeout(500); + const search = harness.currentSheet()!.querySelector('.mobile-picker-sheet-search-input')!; + assert.ok(search); + search.value = 'Model 8'; + search.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + await timeout(500); + const results = Array.from(harness.currentSheet()!.querySelectorAll('.mobile-picker-sheet-label'), element => element.textContent); + harness.row('Model 8').click(); + await timeout(500); + const title = harness.currentSheet()!.querySelector('.mobile-picker-sheet-title')?.textContent; + const label = harness.row('Model 8').querySelector('.mobile-picker-sheet-label')?.textContent; + harness.row('High').click(); + await whenModelConfigValuesSaved(harness.access); + harness.close(); + await closed; + assert.deepStrictEqual({ + results, title, label, writes: harness.writes, + selected: source === 'delegates' ? harness.currentModel.get()?.identifier : harness.session.getSessionContext()?.modelId, + }, { + results: ['Model 8'], + title: 'Configure Session', + label: 'Model 8', + selected: 'copilot:model-8', + writes: [{ model: 'copilot:model-8', values: { effort: 'high' } }], + }); + }); + }); + } + + test('does not reopen configuration for a different chat after nested model selection', async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const harness = createHarness(9); + const closed = harness.open(harness.session); + harness.row('Model 0').click(); + await timeout(500); + harness.switchChat(); + harness.row('Model 8').click(); + await timeout(500); + await closed; + assert.deepStrictEqual({ sheet: harness.currentSheet(), model: harness.session.getSessionContext()?.modelId, writes: harness.writes }, { + sheet: null, model: 'copilot:model-0', writes: [], + }); + }); + }); +}); diff --git a/src/vs/sessions/contrib/providers/copilotChatSessions/test/browser/copilotChatSessionsProvider.test.ts b/src/vs/sessions/contrib/providers/copilotChatSessions/test/browser/copilotChatSessionsProvider.test.ts index 0b44028e5b39..0db95836ba70 100644 --- a/src/vs/sessions/contrib/providers/copilotChatSessions/test/browser/copilotChatSessionsProvider.test.ts +++ b/src/vs/sessions/contrib/providers/copilotChatSessions/test/browser/copilotChatSessionsProvider.test.ts @@ -5,10 +5,13 @@ import assert from 'assert'; import { spy } from 'sinon'; +import * as dom from '../../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../../base/browser/window.js'; import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { IDefaultAccount, IEntitlementsData } from '../../../../../../base/common/defaultAccount.js'; import { DisposableStore, ImmortalReference, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { URI } from '../../../../../../base/common/uri.js'; @@ -19,6 +22,7 @@ import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js' import { autorun, constObservable, observableValue } from '../../../../../../base/common/observable.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; @@ -26,6 +30,8 @@ import { IFileDialogService } from '../../../../../../platform/dialogs/common/di import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStatWithPartialMetadata } from '../../../../../../platform/files/common/files.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; +import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; import { TestStorageService } from '../../../../../../workbench/test/common/workbenchTestServices.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; @@ -83,6 +89,8 @@ import { SessionModelSelection } from '../../../../../../workbench/contrib/sessi import { ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { stubSessionsHostLayout } from '../../../../../test/browser/sessionsHostLayoutTestUtils.js'; import { ITestShownChat, testChatSourceOf } from '../../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { getSessionCreationEnvironments } from '../../../../../../workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.js'; +import { MobileRepositoryPicker } from '../../../../mobile/browser/mobileRepositoryPicker.js'; // ---- Helpers ---------------------------------------------------------------- @@ -219,12 +227,14 @@ function serializeCreationReference(reference: ISessionCreationReference | undef } interface ICreateProviderOptions { + readonly defaultAccountService?: IDefaultAccountService; readonly draftPreparation?: ICloudSandboxDraftPreparationService; readonly chatModels?: IChatService['chatModels']; readonly providerMode?: 'default' | 'sandbox'; readonly commandService?: ICommandService; readonly repositoryPicker?: Pick; readonly sessionRepositoryPicker?: ISessionRepositoryPicker; + readonly quickInputService?: IQuickInputService; readonly notificationErrors?: string[]; readonly getOptionGroups?: () => IChatSessionProviderOptionGroup[] | undefined; readonly languageModelsService?: Partial; @@ -362,7 +372,7 @@ function createProviderWithConfig( ): { provider: CopilotChatSessionsProvider; configService: TestConfigurationService; labelService: MockLabelService } { const instantiationService = disposables.add(new TestInstantiationService()); instantiationService.stubInstance(CloudSandboxModels, upcastPartial({ models: [], ready: true, onDidChange: Event.None, load: () => { }, dispose: () => { } })); - instantiationService.stub(IDefaultAccountService, { currentDefaultAccount: null, onDidChangeDefaultAccount: Event.None, getDefaultAccount: async () => null }); + instantiationService.stub(IDefaultAccountService, opts?.defaultAccountService ?? { currentDefaultAccount: null, onDidChangeDefaultAccount: Event.None, getDefaultAccount: async () => null }); instantiationService.stub(IChatEntitlementService, { sentiment: {}, onDidChangeSentiment: Event.None }); instantiationService.stub(IWorkbenchGitHubService, { onDidChangeDefaultClient: Event.None }); @@ -373,6 +383,9 @@ function createProviderWithConfig( instantiationService.stub(ILogService, opts?.logService ?? new NullLogService()); instantiationService.stub(IContextKeyService, disposables.add(new MockContextKeyService())); instantiationService.stub(IStorageService, opts?.storageService ?? disposables.add(new TestStorageService())); + if (opts?.quickInputService) { + instantiationService.stub(IQuickInputService, opts.quickInputService); + } instantiationService.stub(IFileDialogService, {}); instantiationService.stub(ICommandService, opts?.commandService ?? { executeCommand: async () => undefined }); instantiationService.stub(IAgentSessionsService, { @@ -710,6 +723,7 @@ suite('CopilotChatSessionsProvider', () => { gitHubService, repositoryPicker: { pickRepository: async (getRepositories, _options, token) => { + assert.strictEqual(_options, undefined); steps.push('picker'); const repositories = await getRepositories('https://github.com/microsoft/vscode.git', token ?? CancellationToken.None); return { repository: repositories[0] }; @@ -756,6 +770,143 @@ suite('CopilotChatSessionsProvider', () => { }); } + function createMobileRepositoryPicker() { + const container = dom.append(mainWindow.document.body, dom.$('div')); + disposables.add(toDisposable(() => container.remove())); + let quickPickCalls = 0; + const quickInputService = new class extends mock() { + override createQuickPick(): never { + quickPickCalls++; + throw new Error('The mobile repository picker must not create a desktop quick pick'); + } + }(); + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IInstantiationService, instantiationService); + instantiationService.stub(ILayoutService, { mainContainer: container }); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IQuickInputService, quickInputService); + const sessionRepositoryPicker = disposables.add(instantiationService.createInstance(MobileRepositoryPicker)); + return { container, sessionRepositoryPicker, quickInputService, getQuickPickCalls: () => quickPickCalls }; + } + + for (const providerMode of ['default', 'sandbox'] as const) { + (isWeb ? test : test.skip)(`uses the entry-owned repository sheet without creating quick input (${providerMode})`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const mobile = createMobileRepositoryPicker(); + const steps: string[] = []; + const gitHubService = new class extends TestGitHubService { + override async authenticateForRepositoryAccess(): Promise { + steps.push('authenticate'); + } + override async getRepositories(query: string): Promise { + steps.push(`search:${query}`); + return [{ owner: 'Mixed.Owner', name: 'Some-Repo', fullName: 'Mixed.Owner/Some-Repo', defaultBranch: 'main', isPrivate: true, description: '' }]; + } + }(); + const errors: string[] = []; + const provider = createProvider(disposables, model, { + providerMode, gitHubService, notificationErrors: errors, ...mobile, + }); + const selected = provider.browseActions[0].run(); + await timeout(1); + const input = mobile.container.querySelector('.mobile-picker-sheet-search-input')!; + input.value = 'https://github.com/Mixed.Owner/Some-Repo.git'; + input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + await timeout(301); + const row = mobile.container.querySelector('.mobile-picker-sheet-item')!; + const label = row.textContent; + row.click(); + const workspace = await selected; + assert.deepStrictEqual({ + steps, label, errors, quickPickCalls: mobile.getQuickPickCalls(), + uri: workspace?.uri.toString(), root: workspace?.folders[0].root.toString(), + }, { + steps: ['authenticate', 'search:', 'search:Mixed.Owner/Some-Repo'], + label: 'Mixed.Owner/Some-Repo', errors: [], quickPickCalls: 0, + uri: 'https://github.com/Mixed.Owner/Some-Repo', + root: 'github-remote-file://github/Mixed.Owner/Some-Repo/HEAD', + }); + }); + }); + } + + for (const disposeProvider of [false, true]) { + (isWeb ? test : test.skip)(`cancelling the entry-owned repository sheet does not fall back to quick input (dispose provider: ${disposeProvider})`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const mobile = createMobileRepositoryPicker(); + const repository = new DeferredPromise(); + let requestToken = CancellationToken.None; + const gitHubService = new class extends TestGitHubService { + override getRepositories(_query: string, token: CancellationToken): Promise { + requestToken = token; + return repository.p; + } + }(); + const provider = createProvider(disposables, model, { gitHubService, ...mobile }); + const selected = provider.browseActions[0].run(); + await timeout(1); + if (disposeProvider) { + provider.dispose(); + } else { + mobile.container.querySelector('.mobile-picker-sheet-done')!.click(); + } + const workspace = await selected; + await repository.complete([]); + assert.deepStrictEqual({ + workspace, cancelled: requestToken.isCancellationRequested, quickPickCalls: mobile.getQuickPickCalls(), + open: !!mobile.container.querySelector('.mobile-picker-sheet'), + }, { workspace: undefined, cancelled: true, quickPickCalls: 0, open: false }); + }); + }); + } + + for (const changesWhilePicking of [false, true]) { + (isWeb ? test : test.skip)(`keeps enterprise-host validation around the entry-owned repository sheet (changes during picker: ${changesWhilePicking})`, async () => { + await runWithFakedTimers({ useFakeTimers: true }, async () => { + const mobile = createMobileRepositoryPicker(); + const gitHubService = new class extends TestGitHubService { + override async getRepositories(): Promise { + return [{ owner: 'owner', name: 'repo', fullName: 'owner/repo', defaultBranch: 'main', isPrivate: true, description: '' }]; + } + }(); + gitHubService.enterpriseHost = changesWhilePicking ? undefined : 'example.ghe.com'; + const errors: string[] = []; + const provider = createProvider(disposables, model, { gitHubService, notificationErrors: errors, ...mobile }); + const selected = provider.browseActions[0].run(); + await timeout(1); + const opened = !!mobile.container.querySelector('.mobile-picker-sheet'); + if (changesWhilePicking) { + gitHubService.enterpriseHost = 'example.ghe.com'; + mobile.container.querySelector('.mobile-picker-sheet-item')!.click(); + } + assert.deepStrictEqual({ + workspace: await selected, opened, errors, quickPickCalls: mobile.getQuickPickCalls(), + }, { + workspace: undefined, opened: changesWhilePicking, quickPickCalls: 0, + errors: ['Error: This picker supports github.com repositories only. Switch to a github.com account, then try again.'], + }); + }); + }); + } + + (isWeb ? test : test.skip)('provider disposal during authentication never opens the entry-owned repository sheet', async () => { + const mobile = createMobileRepositoryPicker(); + const authentication = new DeferredPromise(); + const gitHubService = new class extends TestGitHubService { + override authenticateForRepositoryAccess(): Promise { + return authentication.p; + } + }(); + const provider = createProvider(disposables, model, { gitHubService, ...mobile }); + const selected = provider.browseActions[0].run(); + provider.dispose(); + const workspace = await selected; + await authentication.complete(); + assert.deepStrictEqual({ + workspace, open: !!mobile.container.querySelector('.mobile-picker-sheet'), quickPickCalls: mobile.getQuickPickCalls(), + }, { workspace: undefined, open: false, quickPickCalls: 0 }); + }); + for (const changesWhilePicking of [false, true]) { (isWeb ? test : test.skip)(`rejects enterprise identities instead of creating github.com workspaces (changes during picker: ${changesWhilePicking})`, async () => { const gitHubService = new TestGitHubService(); @@ -1192,6 +1343,115 @@ suite('CopilotChatSessionsProvider', () => { // ---- getSessionTypes ------- + for (const providerMode of ['default', 'sandbox'] as const) { + test(`cloud session entitlement updates creation choices without removing history (${providerMode})`, async () => { + let cloudSessionsEnabled: boolean | undefined; + const accountChanged = disposables.add(new Emitter()); + const defaultAccountService = new class extends mock() { + override readonly onDidChangeDefaultAccount = accountChanged.event; + override get currentDefaultAccount(): IDefaultAccount { + return upcastPartial({ + entitlementsData: upcastPartial({ cloud_sessions_enabled: cloudSessionsEnabled }), + }); + } + override async getDefaultAccount() { return this.currentDefaultAccount; } + }(); + model.addSession(createMockAgentSession(URI.from({ scheme: AgentSessionProviders.Cloud, path: '/existing' }))); + const { provider, configService } = createProviderWithConfig(disposables, model, { providerMode, defaultAccountService }); + await configService.setUserConfiguration(CloudSandboxEnabledSettingId, true); + await configService.setUserConfiguration(RemoteAgentHostsEnabledSettingId, true); + const existing = provider.getSessions(); + let sessionTypeChanges = 0; + let capabilityChanges = 0; + disposables.add(provider.onDidChangeSessionTypes(() => sessionTypeChanges++)); + disposables.add(provider.onDidChangeCapabilities(() => capabilityChanges++)); + const workspace = URI.from({ scheme: GITHUB_REMOTE_FILE_SCHEME, authority: 'github', path: '/owner/repo/HEAD' }); + const workspaceProvider: ISessionsProvider = provider; + const availability = () => ({ + environments: getSessionCreationEnvironments([provider]).map(environment => environment.id), + sessionTypes: provider.getSessionTypes(workspace).map(type => type.id), + advertisedTypes: provider.sessionTypes.map(type => type.id), + workspaceSelection: workspaceProvider.supportsWorkspaceSelection !== false, + quickChats: provider.supportsQuickChats, + history: provider.getSessions().map(session => session.sessionId), + }); + const snapshots = [availability()]; + for (const enabled of [false, true, undefined]) { + cloudSessionsEnabled = enabled; + accountChanged.fire(defaultAccountService.currentDefaultAccount); + snapshots.push(availability()); + } + const available = { + environments: ['cloud'], + sessionTypes: [providerMode === 'sandbox' ? CopilotSandboxSessionType.id : CopilotCloudSessionType.id], + advertisedTypes: [providerMode === 'sandbox' ? CopilotSandboxSessionType.id : CopilotCloudSessionType.id], + workspaceSelection: true, + quickChats: true, + history: existing.map(session => session.sessionId), + }; + assert.deepStrictEqual({ + snapshots, sessionTypeChanges, capabilityChanges, + }, { + snapshots: [available, { ...available, environments: [], sessionTypes: [], advertisedTypes: [], quickChats: false }, available, available], + sessionTypeChanges: 2, capabilityChanges: 2, + }); + }); + + test(`refreshes cloud creation choices after delayed account initialization (${providerMode})`, async () => { + const initialization = new DeferredPromise(); + let account: IDefaultAccount | null = null; + const defaultAccountService = new class extends mock() { + override readonly onDidChangeDefaultAccount = Event.None; + override get currentDefaultAccount() { return account; } + override getDefaultAccount() { return initialization.p; } + }(); + const provider = createProvider(disposables, model, { providerMode, defaultAccountService }); + const before = getSessionCreationEnvironments([provider]).map(environment => environment.id); + const changes: string[][] = []; + let capabilityChanges = 0; + disposables.add(provider.onDidChangeSessionTypes(() => changes.push(getSessionCreationEnvironments([provider]).map(environment => environment.id)))); + disposables.add(provider.onDidChangeCapabilities(() => capabilityChanges++)); + account = upcastPartial({ + entitlementsData: upcastPartial({ cloud_sessions_enabled: false }), + }); + await initialization.complete(account); + + assert.deepStrictEqual({ + before, changes, capabilityChanges, + after: getSessionCreationEnvironments([provider]).map(environment => environment.id), + }, { before: ['cloud'], changes: [[]], capabilityChanges: 1, after: [] }); + }); + + test(`disabled cloud session entitlement rejects new and stale drafts (${providerMode})`, async () => { + let cloudSessionsEnabled = true; + const defaultAccountService = new class extends mock() { + override readonly onDidChangeDefaultAccount = Event.None; + override get currentDefaultAccount(): IDefaultAccount { + return upcastPartial({ + entitlementsData: upcastPartial({ cloud_sessions_enabled: cloudSessionsEnabled }), + }); + } + override async getDefaultAccount() { return this.currentDefaultAccount; } + }(); + const draftPreparation = createDraftPreparationStub(); + const prepare = spy(draftPreparation, 'prepare'); + const { provider, configService } = createProviderWithConfig(disposables, model, { providerMode, defaultAccountService, draftPreparation }); + await configService.setUserConfiguration(CloudSandboxEnabledSettingId, true); + await configService.setUserConfiguration(RemoteAgentHostsEnabledSettingId, true); + const workspace = URI.from({ scheme: GITHUB_REMOTE_FILE_SCHEME, authority: 'github', path: '/owner/repo/HEAD' }); + const sessionType = providerMode === 'sandbox' ? CopilotSandboxSessionType.id : CopilotCloudSessionType.id; + const draft = provider.createNewSession(workspace, sessionType); + cloudSessionsEnabled = false; + + assert.throws(() => provider.createNewSession(workspace, sessionType), /Cloud session creation is not available for your account/); + assert.throws(() => provider.createQuickChat(sessionType), /Cloud session creation is not available for your account/); + provider.prepareNewSessionWhileComposing(draft.sessionId); + await assert.rejects(provider.prepareNewSession(draft.sessionId, CancellationToken.None, 'hello'), /Cloud session creation is not available for your account/); + await assert.rejects(provider.sendRequest(draft.sessionId, draft.mainChat.get().resource, { query: 'hello' }), /Cloud session creation is not available for your account/); + assert.deepStrictEqual({ preparations: prepare.callCount, draftRetained: provider.getSession(draft.sessionId) !== undefined }, { preparations: 0, draftRetained: true }); + }); + } + test('getSessionTypes returns only Cloud for a remote workspace', () => { const provider = createProvider(disposables, model); const types = provider.getSessionTypes(URI.from({ scheme: GITHUB_REMOTE_FILE_SCHEME, path: '/owner/repo' })); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostDrawerHeader.css b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostDrawerHeader.css new file mode 100644 index 000000000000..3e4e24322354 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostDrawerHeader.css @@ -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. + *--------------------------------------------------------------------------------------------*/ + +/* + * The drawer header row: the place sessions run, named once at the top of the + * list like a workspace switcher. A 40px tile carries the place's icon; the + * two text lines are title and detail; the chevron says it opens a sheet. + */ + +.mobile-sessions-drawer-header { + flex-shrink: 0; +} + +.mobile-sessions-drawer-header .monaco-toolbar, +.mobile-sessions-drawer-header .monaco-action-bar, +.mobile-sessions-drawer-header .actions-container, +.mobile-sessions-drawer-header .action-item, +.mobile-sessions-drawer-header .host-drawer-header { + display: block; + width: 100%; +} + +.host-drawer-header-row { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size120); + width: 100%; + min-height: var(--mobile-target, 44px); + margin: 0; + padding: var(--vscode-spacing-size100) var(--vscode-spacing-size160) var(--vscode-spacing-size120); + border: none; + background: transparent; + color: var(--vscode-foreground); + font-family: inherit; + text-align: left; + cursor: pointer; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; +} + +.host-drawer-header-row:active { + background: var(--vscode-toolbar-hoverBackground); +} + +.host-drawer-header-tile { + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 40px; + height: 40px; + border-radius: var(--vscode-cornerRadius-medium); + background: color-mix(in srgb, var(--vscode-foreground) 8%, transparent); + color: var(--vscode-descriptionForeground); +} + +.mobile-sessions-drawer-header .host-drawer-header-row .host-drawer-header-tile .codicon, +.mobile-sessions-drawer-header .host-drawer-header-row .host-drawer-header-chevron .codicon { + color: inherit; +} + +.host-drawer-header-tile .codicon { + font-size: var(--vscode-codiconFontSize); +} + +.host-drawer-header-tile.place { + background: color-mix(in srgb, var(--vscode-textLink-foreground, var(--vscode-button-background)) 14%, transparent); + color: var(--vscode-textLink-foreground, var(--vscode-button-background)); +} + +.host-drawer-header-text { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size20); +} + +.host-drawer-header-title { + font-size: var(--vscode-fontSize-heading3, 17px); + font-weight: var(--vscode-fontWeight-semiBold); + line-height: 1.25; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.host-drawer-header-subtitle { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size60); + font-size: var(--vscode-fontSize-label1, 13px); + line-height: 1.25; + color: var(--vscode-descriptionForeground); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.host-drawer-header-chevron { + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 24px; + color: var(--vscode-descriptionForeground); +} + +.host-drawer-header-chevron .codicon { + font-size: var(--vscode-codiconFontSize); +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostPlaceChip.css b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostPlaceChip.css new file mode 100644 index 000000000000..7ff0b2c3ac79 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/hostPlaceChip.css @@ -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. + *--------------------------------------------------------------------------------------------*/ + +/* + * The "where it runs" chip on the phone's new-session screen: a row of its own + * above the workspace and agent chips. The chip itself is one of the row's + * pills (`.sessions-chat-picker-slot .action-label`, see `chatWidget.css`); + * this file only lays out the row. No accent color and no status: the place + * is a fact, not a call to action, and connection state belongs to the sheet. + */ + +.sessions-new-session-place-row { + display: flex; + justify-content: center; + width: 100%; + box-sizing: border-box; + padding: 0 var(--vscode-spacing-size160); + margin-bottom: var(--vscode-spacing-size80); +} + +.sessions-new-session-place-row[hidden] { + display: none; +} + +.sessions-new-session-place-row .monaco-toolbar, +.sessions-new-session-place-row .monaco-action-bar, +.sessions-new-session-place-row .actions-container { + display: flex; + justify-content: center; + max-width: 100%; +} + +.sessions-new-session-place-row .action-item.sessions-new-session-place { + display: block; + max-width: 100%; +} + +.sessions-new-session-place-row .sessions-new-session-place-trigger { + max-width: 100%; +} + +.sessions-new-session-place-icon { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/mobileHostPickerSheet.css b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/mobileHostPickerSheet.css new file mode 100644 index 000000000000..c05a958376d3 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/media/mobileHostPickerSheet.css @@ -0,0 +1,256 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* + * Body of the experimental "Where sessions run" sheet (`MobileHostPickerSheet`). The shell + * (overlay, handle, title row, close) comes from the shared mobile sheet; the + * rows here follow the same grammar as `mobilePickerSheet.css` rows — 36px + * icon tile, 56px row, selection as a filled row — so every sheet in the + * phone app reads alike. + */ + +.host-picker-overlay .mobile-content-sheet-body { + padding-bottom: var(--vscode-spacing-size80); +} + +/* ---- Rows ---------------------------------------------------------------- */ + +.host-picker-row { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size120); + width: calc(100% - 2 * var(--vscode-spacing-size80)); + min-height: 56px; + margin: var(--vscode-spacing-size20) var(--vscode-spacing-size80); + padding: var(--vscode-spacing-size80) var(--vscode-spacing-size120); + border: none; + border-radius: var(--vscode-cornerRadius-xLarge); + background: transparent; + color: inherit; + font-family: inherit; + font-size: 15px; + text-align: left; + cursor: pointer; + touch-action: pan-y; + -webkit-tap-highlight-color: transparent; +} + +.host-picker-row:focus:not(:focus-visible) { + outline: none; +} + +.host-picker-row:active { + background: var(--vscode-toolbar-hoverBackground); +} + +.host-picker-row.checked { + background: var(--vscode-list-activeSelectionBackground, var(--vscode-toolbar-hoverBackground)); + color: var(--vscode-list-activeSelectionForeground, inherit); +} + +.host-picker-row-icon { + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 36px; + height: 36px; + border-radius: var(--vscode-cornerRadius-large); + background: color-mix(in srgb, var(--vscode-foreground) 8%, transparent); + color: var(--vscode-descriptionForeground); +} + +.host-picker-row-icon .codicon { + font-size: 18px; +} + +.host-picker-row.checked .host-picker-row-icon { + background: color-mix(in srgb, var(--vscode-textLink-foreground, var(--vscode-button-background)) 18%, transparent); + color: var(--vscode-textLink-foreground, var(--vscode-button-background)); +} + +/* "Add a computer…" draws an outlined tile: an empty slot, not a thing. */ +.host-picker-row-icon.add { + background: transparent; + box-shadow: inset 0 0 0 var(--vscode-strokeThickness) color-mix(in srgb, var(--vscode-foreground) 20%, transparent); + color: var(--vscode-textLink-foreground, var(--vscode-button-background)); +} + +.host-picker-row-text { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size20); +} + +.host-picker-row-label { + font-size: 16px; + font-weight: var(--vscode-fontWeight-semiBold); + line-height: 1.2; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.host-picker-row.navigates .host-picker-row-label { + font-weight: 500; +} + +.host-picker-row-description { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size60); + font-size: 12px; + line-height: 1.2; + color: var(--vscode-descriptionForeground); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.host-picker-row-check, +.host-picker-row-chevron { + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 20px; + height: 20px; +} + +.host-picker-row-check { + color: var(--vscode-textLink-foreground, var(--vscode-button-background)); +} + +.host-picker-row-check .codicon { + font-size: 14px; +} + +.host-picker-row-chevron { + color: var(--vscode-descriptionForeground); + opacity: 0.8; +} + +/* Glyphs take their container's color; the workbench's generic + * `.codicon[class*='codicon-']` rule would otherwise paint them icon-gray. */ +.host-picker-overlay .host-picker-row .host-picker-row-icon .codicon, +.host-picker-overlay .host-picker-row .host-picker-row-check .codicon, +.host-picker-overlay .host-picker-row .host-picker-row-chevron .codicon, +.host-picker-overlay .host-picker-section .host-picker-section-action .codicon { + color: inherit; +} + +/* ---- Connection state in words, with a dot for a glance ------------------ */ + +.host-picker-status-dot { + display: inline-block; + flex-shrink: 0; + width: 7px; + height: 7px; + border-radius: var(--vscode-cornerRadius-circle); + box-shadow: inset 0 0 0 1.5px var(--vscode-descriptionForeground); +} + +.host-picker-status-dot.connected { + background: var(--vscode-testing-iconPassed, var(--vscode-debugIcon-startForeground, #388a34)); + box-shadow: none; +} + +.host-picker-status-dot.connecting { + background: var(--vscode-charts-yellow, var(--vscode-editorWarning-foreground)); + box-shadow: none; + animation: host-picker-blink 1s ease-in-out infinite; +} + +.host-picker-row-description:has(> .host-picker-status-dot.connected) { + color: var(--vscode-testing-iconPassed, var(--vscode-debugIcon-startForeground, #388a34)); +} + +/* ---- Section: "Your computers" with its Refresh action ------------------- */ + +.host-picker-section { + display: flex; + align-items: center; + padding: 14px var(--vscode-spacing-size160) var(--vscode-spacing-size60) var(--vscode-spacing-size120); + font-size: 13px; + color: var(--vscode-descriptionForeground); +} + +.host-picker-section-title { + flex: 1; + min-width: 0; +} + +.host-picker-section-action { + display: inline-flex; + align-items: center; + gap: var(--vscode-spacing-size40); + min-height: 32px; + margin: -6px calc(-1 * var(--vscode-spacing-size80)) -6px 0; + padding: 0 var(--vscode-spacing-size80); + border: none; + border-radius: var(--vscode-cornerRadius-small); + background: transparent; + color: var(--vscode-textLink-foreground, var(--vscode-button-background)); + font-family: inherit; + font-size: 13px; + font-weight: 500; + cursor: pointer; + touch-action: manipulation; + -webkit-tap-highlight-color: transparent; +} + +.host-picker-section-action:active { + opacity: 0.6; +} + +.host-picker-section-action.discovering { + color: var(--vscode-descriptionForeground); + cursor: default; +} + +.host-picker-section-action-icon .codicon { + font-size: 13px; +} + +.host-picker-section-action.discovering .host-picker-section-action-icon .codicon { + animation: host-picker-spin 1s linear infinite; +} + +/* ---- Hint and empty copy ------------------------------------------------- */ + +.host-picker-hint, +.host-picker-empty { + margin: var(--vscode-spacing-size20) var(--vscode-spacing-size200) var(--vscode-spacing-size60); + font-size: 13px; + line-height: 18px; + color: var(--vscode-descriptionForeground); +} + +.host-picker-hint code { + padding: 1px var(--vscode-spacing-size40); + border-radius: var(--vscode-cornerRadius-xSmall); + background: color-mix(in srgb, var(--vscode-foreground) 8%, transparent); + color: var(--vscode-foreground); + font-family: var(--monaco-monospace-font, monospace); + font-size: 12px; +} + +@keyframes host-picker-blink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.35; } +} + +@keyframes host-picker-spin { + to { transform: rotate(360deg); } +} + +@media (prefers-reduced-motion: reduce) { + .host-picker-status-dot.connecting, + .host-picker-section-action.discovering .host-picker-section-action-icon .codicon { + animation: none; + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/missionControlAgentHost.contribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/missionControlAgentHost.contribution.ts index dff7698e19af..312e3f9d5794 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/missionControlAgentHost.contribution.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/missionControlAgentHost.contribution.ts @@ -17,7 +17,7 @@ import { MissionControlAgentHostContribution } from '../../../../../workbench/co registerWorkbenchContribution2(MissionControlAgentHostContribution.ID, MissionControlAgentHostContribution, WorkbenchPhase.AfterRestored); MenuRegistry.appendMenuItem(Menus.SessionWorkspaceManage, { - command: { id: RemoteAgentHostCommandIds.connectViaMissionControl, title: localize('connectMissionControlHost', "GitHub Environments..."), icon: Codicon.remote }, + command: { id: RemoteAgentHostCommandIds.connectViaMissionControl, title: localize('connectMissionControlHost', "GitHub Environments..."), tooltip: localize('connectMissionControlHostTooltip', "Connect to a computer shared through GitHub Environments"), icon: Codicon.remote }, when: ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.not('config.chat.disableAIFeatures'), ContextKeyExpr.equals(`config.${RemoteAgentHostsEnabledSettingId}`, true), ContextKeyExpr.equals(`config.${GitHubEnvironmentsEnabledSettingId}`, true), GitHubEnvironmentsAvailableContext), group: '1_add', order: 5, diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileAgentHostFilterService.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileAgentHostFilterService.ts new file mode 100644 index 000000000000..97435779d566 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileAgentHostFilterService.ts @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../../base/common/codicons.js'; +import { localize } from '../../../../../nls.js'; +import { AgentHostFilterService } from '../../../../../workbench/contrib/sessions/browser/agentHostFilterService.js'; +import { IAgentHostFilterEntry } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; + +export function isImplicitlyConnectedHost(entry: IAgentHostFilterEntry): boolean { + return entry.grouped && !entry.connectable && entry.sessionCreationProviderId !== undefined; +} + +function presentHost(host: IAgentHostFilterEntry): IAgentHostFilterEntry { + return host.id === 'githubsandbox' + ? { ...host, label: localize('cloud', "Cloud"), description: host.label, icon: Codicon.cloud } + : host; +} + +/** The experimental client prefers Cloud and presents the provider name as its description. */ +export class MobileAgentHostFilterService extends AgentHostFilterService { + protected override automaticSelectionRank(entry: IAgentHostFilterEntry): number { + return isImplicitlyConnectedHost(entry) ? -1 : super.automaticSelectionRank(entry); + } + + override get hosts(): readonly IAgentHostFilterEntry[] { + return super.hosts.map(presentHost); + } + + override get selectedHost(): IAgentHostFilterEntry | undefined { + const host = super.selectedHost; + return host && presentHost(host); + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostDrawerHeaderViewItem.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostDrawerHeaderViewItem.ts new file mode 100644 index 000000000000..516eee00f96c --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostDrawerHeaderViewItem.ts @@ -0,0 +1,129 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/hostDrawerHeader.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; +import { Gesture, EventType as TouchEventType } from '../../../../../base/browser/touch.js'; +import { BaseActionViewItem } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { renderLabelWithIcons } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { IAction } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; +import { localize } from '../../../../../nls.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IAgentHostFilterEntry, IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { isImplicitlyConnectedHost } from './mobileAgentHostFilterService.js'; +import { describeComputerStatus, MobileHostPickerSheet } from './mobileHostPickerSheet.js'; + +const $ = dom.$; + +/** + * The row at the top of the phone sessions drawer that names the place the + * list is scoped to — "Cloud · GitHub Sandboxes", or one of the user's + * computers with its connection state — and opens the + * {@link MobileHostPickerSheet} on tap. Living in the drawer makes switching + * reachable from an open session, where the title bar belongs to the session. + */ +export class MobileHostDrawerHeaderViewItem extends BaseActionViewItem { + + private readonly _sheet: MobileHostPickerSheet; + private _row: HTMLButtonElement | undefined; + private _tile: HTMLElement | undefined; + private _title: HTMLElement | undefined; + private _subtitle: HTMLElement | undefined; + + constructor( + action: IAction, + @IAgentHostFilterService private readonly _filterService: IAgentHostFilterService, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(undefined, action); + this._sheet = this._register(instantiationService.createInstance(MobileHostPickerSheet)); + this._register(this._filterService.onDidChange(() => this._update())); + this._register(this._filterService.onDidChangeDiscovering(() => this._update())); + } + + override render(container: HTMLElement): void { + super.render(container); + if (!this.element) { + return; + } + this.element.classList.add('host-drawer-header'); + + const button = this._row = dom.append(this.element, $('button.host-drawer-header-row.agent-sessions-interactive.agent-sessions-interactive-list', { type: 'button' })) as HTMLButtonElement; + button.setAttribute('aria-haspopup', 'dialog'); + this._tile = dom.append(button, $('span.host-drawer-header-tile')); + const text = dom.append(button, $('span.host-drawer-header-text')); + this._title = dom.append(text, $('span.host-drawer-header-title')); + this._subtitle = dom.append(text, $('span.host-drawer-header-subtitle')); + dom.append(button, $('span.host-drawer-header-chevron')).append(...renderLabelWithIcons(`$(${Codicon.chevronDown.id})`)); + + this._register(Gesture.addTarget(button)); + for (const eventType of [dom.EventType.CLICK, TouchEventType.Tap]) { + this._register(dom.addDisposableListener(button, eventType, e => { + dom.EventHelper.stop(e, true); + this._sheet.show(); + })); + } + this._register(dom.addDisposableListener(button, dom.EventType.KEY_DOWN, e => { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { + dom.EventHelper.stop(e, true); + this._sheet.show(); + } + })); + + this._update(); + } + + override focus(): void { + this._row?.focus(); + } + + private _update(): void { + if (!this._tile || !this._title || !this._subtitle || !this._row) { + return; + } + const selected = this._filterService.selectedHost; + const row = this._row; + + dom.clearNode(this._tile); + dom.clearNode(this._subtitle); + this._tile.classList.remove('place', 'computer'); + + if (!selected) { + this._tile.classList.add('computer'); + this._tile.append(...renderLabelWithIcons(`$(${Codicon.remote.id})`)); + this._title.textContent = localize('hostDrawer.noPlace', "Where sessions run"); + this._subtitle.textContent = this._filterService.isDiscovering + ? localize('hostDrawer.searching', "Searching…") + : localize('hostDrawer.choose', "Choose a place"); + row.setAttribute('aria-label', localize('hostDrawer.noPlace.aria', "Where sessions run. Choose a place.")); + return; + } + + if (isImplicitlyConnectedHost(selected)) { + this._tile.classList.add('place'); + this._tile.append(...renderLabelWithIcons(`$(${selected.icon.id})`)); + this._title.textContent = selected.label; + this._subtitle.textContent = selected.description ?? ''; + row.setAttribute('aria-label', localize('hostDrawer.place.aria', "Sessions run in {0}, {1}. Change where sessions run.", selected.label, selected.description ?? '')); + return; + } + + this._renderComputer(selected, row); + } + + private _renderComputer(computer: IAgentHostFilterEntry, row: HTMLElement): void { + this._tile!.classList.add('computer'); + this._tile!.append(...renderLabelWithIcons(`$(${Codicon.vm.id})`)); + this._title!.textContent = computer.label; + const status = describeComputerStatus(computer.status); + dom.append(this._subtitle!, $(`span.host-picker-status-dot.${computer.status}`)); + dom.append(this._subtitle!, $('span')).textContent = status; + row.setAttribute('aria-label', localize('hostDrawer.computer.aria', "Sessions run on {0}, {1}. Change where sessions run.", computer.label, status)); + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostFilter.contribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostFilter.contribution.ts new file mode 100644 index 000000000000..7fbb8c9ce837 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostFilter.contribution.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { localize2 } from '../../../../../nls.js'; +import { IActionViewItemService } from '../../../../../platform/actions/browser/actionViewItemService.js'; +import { Action2, registerAction2 } from '../../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IsWebContext } from '../../../../../platform/contextkey/common/contextkeys.js'; +import { IsAuxiliaryWindowContext } from '../../../../../workbench/common/contextkeys.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../../workbench/common/contributions.js'; +import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; +import { IsPhoneLayoutContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { MobileHostDrawerHeaderViewItem } from './mobileHostDrawerHeaderViewItem.js'; +import { MobileHostPlaceChipViewItem } from './mobileHostPlaceChipViewItem.js'; +import { InstantiationType, registerSingleton } from '../../../../../platform/instantiation/common/extensions.js'; +import { IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { MobileAgentHostFilterService } from './mobileAgentHostFilterService.js'; + +registerSingleton(IAgentHostFilterService, MobileAgentHostFilterService, InstantiationType.Delayed); + +const PICK_MOBILE_HOST_FILTER_ID = 'sessions.mobile.agentHostFilter.pick'; + +registerAction2(class PickMobileAgentHostFilterAction extends Action2 { + constructor() { + super({ + id: PICK_MOBILE_HOST_FILTER_ID, + title: localize2('mobileAgentHostFilter.pick', "Select Agent Host"), + f1: false, + menu: [Menus.MobileSessionsDrawerHeader, Menus.NewSessionPlace].map(id => ({ + id, + group: 'navigation', + order: 0, + when: ContextKeyExpr.and(IsWebContext, IsAuxiliaryWindowContext.toNegated(), IsPhoneLayoutContext, ChatContextKeys.enabled), + })), + }); + } + + override async run(): Promise { + // Selection is handled by the mobile action view items. + } +}); + +/** Registers the redesigned host picker only in the experimental mobile entry. */ +export class MobileAgentHostFilterContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.contrib.mobileAgentHostFilter'; + + constructor( + @IActionViewItemService actionViewItemService: IActionViewItemService, + ) { + super(); + + const registered = this._register(new Emitter()); + this._register(actionViewItemService.register( + Menus.MobileSessionsDrawerHeader, + PICK_MOBILE_HOST_FILTER_ID, + (action, _options, instantiationService) => instantiationService.createInstance(MobileHostDrawerHeaderViewItem, action), + registered.event, + )); + this._register(actionViewItemService.register( + Menus.NewSessionPlace, + PICK_MOBILE_HOST_FILTER_ID, + (action, _options, instantiationService) => instantiationService.createInstance(MobileHostPlaceChipViewItem, action), + registered.event, + )); + + // Refresh already-created toolbars once without rebuilding them on host updates. + queueMicrotask(() => registered.fire()); + } +} + +registerWorkbenchContribution2(MobileAgentHostFilterContribution.ID, MobileAgentHostFilterContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPickerSheet.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPickerSheet.ts new file mode 100644 index 000000000000..b9fc2e170927 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPickerSheet.ts @@ -0,0 +1,476 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/mobileHostPickerSheet.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { Gesture, EventType as TouchEventType } from '../../../../../base/browser/touch.js'; +import { renderLabelWithIcons } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize } from '../../../../../nls.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { ITunnelInfo, TUNNEL_ADDRESS_PREFIX } from '../../../../../platform/agentHost/common/tunnelAgentHost.js'; +import { IMobileContentSheetApi, isMobilePickerSheetTarget, showMobileContentSheet } from '../../../../../workbench/contrib/sessions/browser/mobile/mobilePickerSheet.js'; +import { AgentHostFilterConnectionStatus, IAgentHostFilterEntry, IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { isImplicitlyConnectedHost } from './mobileAgentHostFilterService.js'; +import { ShowConnectionDiagnosticsCommandId } from '../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/connectionDiagnostics.js'; +import { RemoteAgentHostCommandIds } from '../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/remoteAgentHostCommandIds.js'; +import { MobileTunnelConnection } from './mobileTunnelConnection.js'; + +const $ = dom.$; + +/** The command a user runs on their own machine to make it reachable here. */ +const TUNNEL_COMMAND = 'code tunnel'; + +/** Append `text`, rendering every occurrence of `code` as inline code. */ +function appendTextWithCode(target: HTMLElement, text: string, code: string): void { + const parts = text.split(code); + parts.forEach((part, index) => { + if (index > 0) { + target.append($('code', undefined, code)); + } + if (part) { + target.append(part); + } + }); +} + +/** + * Give focus back to whatever opened a sheet once it is gone, unless something + * else (the next sheet, a quick pick) has taken focus in the meantime. + */ +function restoreFocus(opener: Element | null): void { + const active = dom.getActiveElement(); + if ((!active || active === active.ownerDocument.body) && dom.isHTMLElement(opener) && opener.isConnected) { + opener.focus(); + } +} + +/** Status words for a computer the user connects to, as shown under its name. */ +export function describeComputerStatus(status: AgentHostFilterConnectionStatus): string { + switch (status) { + case AgentHostFilterConnectionStatus.Connected: + return localize('hostPicker.status.connected', "Connected"); + case AgentHostFilterConnectionStatus.Connecting: + return localize('hostPicker.status.connecting', "Connecting…"); + case AgentHostFilterConnectionStatus.Disconnected: + default: + return localize('hostPicker.status.offline', "Offline"); + } +} + +/** + * Phone sheet for choosing where sessions are listed and started. + * + * Places that need no connection from the user (Cloud) come first and carry + * no status. The user's own computers follow under their own heading with + * their connection state in words, and the section always ends in a way to + * add another computer, so self-hosting stays discoverable without being the + * default. Opened from the drawer header row and from the title bar pill. + */ +export class MobileHostPickerSheet extends Disposable { + + private _api: IMobileContentSheetApi | undefined; + /** What had focus when the sheet opened; focus returns there once every sheet is gone. */ + private _opener: Element | null = null; + + /** Waits for the host entry of a computer that was just added, so it can be selected. */ + private readonly _pendingSelection = this._register(new MutableDisposable()); + + constructor( + @IAgentHostFilterService private readonly _filterService: IAgentHostFilterService, + @ICommandService private readonly _commandService: ICommandService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + @ILayoutService private readonly _layoutService: ILayoutService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @INotificationService private readonly _notificationService: INotificationService, + ) { + super(); + } + + get isOpen(): boolean { + return this._api !== undefined; + } + + override dispose(): void { + this._api?.close(); + super.dispose(); + } + + show(): void { + if (this._api) { + return; + } + // Remember what to hand focus back to, unless focus is still inside a + // sheet that is on its way out (reopened within its close animation). + const active = dom.getActiveElement(); + if (!(dom.isHTMLElement(active) && isMobilePickerSheetTarget(active))) { + this._opener = active; + } + void showMobileContentSheet(this._layoutService.mainContainer, localize('hostPicker.title', "Where sessions run"), (body, api) => { + this._api = api; + const store = new DisposableStore(); + store.add({ dispose: () => { if (this._api === api) { this._api = undefined; } } }); + api.overlay.classList.add('host-picker-overlay'); + + // Static frame: places above, the computers section header (with + // its Refresh action) in the middle, computers below. Only the two + // lists are rebuilt on updates, so focus on Refresh survives them. + const placesList = dom.append(body, $('div.host-picker-places')); + const section = dom.append(body, $('div.host-picker-section')); + dom.append(section, $('span.host-picker-section-title')).textContent = localize('hostPicker.yourComputers', "Your computers"); + const refresh = this._renderRefreshAction(section, store); + const computersList = dom.append(body, $('div.host-picker-computers')); + + const bodyStore = store.add(new DisposableStore()); + const rowsById = new Map(); + let focusTargets: HTMLElement[] = []; + const render = () => { + const focusedId = [...rowsById].find(([, row]) => row === dom.getActiveElement())?.[0]; + bodyStore.clear(); + dom.clearNode(placesList); + dom.clearNode(computersList); + rowsById.clear(); + const placeRows = this._renderPlaces(placesList, api, bodyStore, rowsById); + const computerRows = this._renderComputers(computersList, api, bodyStore, rowsById); + focusTargets = [...placeRows, refresh, ...computerRows]; + api.setBodyFocusTargets(focusTargets); + if (focusedId !== undefined) { + (rowsById.get(focusedId) ?? defaultFocus()).focus(); + } + }; + // The selected place, else the first one, else Refresh. + const defaultFocus = () => rowsById.get(this._filterService.selectedHostId ?? '') ?? rowsById.values().next().value ?? refresh; + render(); + store.add(this._filterService.onDidChange(render)); + store.add(this._filterService.onDidChangeDiscovering(render)); + defaultFocus().focus(); + return store; + }, { + caption: localize('hostPicker.caption', "Sessions are listed and started in the place you choose."), + iconClose: true, + trapFocus: true, + headerActions: [{ id: 'information', label: localize('hostPicker.information', "Connection Information"), icon: Codicon.info }], + onHeaderAction: () => { + this._api?.close(); + void this._commandService.executeCommand(ShowConnectionDiagnosticsCommandId); + }, + }).then(() => restoreFocus(this._opener)); + } + + private _renderPlaces(list: HTMLElement, api: IMobileContentSheetApi, store: DisposableStore, rowsById: Map): HTMLElement[] { + const selectedId = this._filterService.selectedHostId; + const rows: HTMLElement[] = []; + for (const place of this._filterService.hosts.filter(isImplicitlyConnectedHost)) { + const row = this._renderPlaceRow(list, store, place, place.id === selectedId, () => { + this._filterService.setSelectedHostId(place.id); + api.close(); + }); + rowsById.set(place.id, row); + rows.push(row); + } + return rows; + } + + /** + * The user's computers, or how to get one. The section is always shown: + * Refresh is how a machine that just started its tunnel appears, and the + * hint says what to run there. + */ + private _renderComputers(list: HTMLElement, api: IMobileContentSheetApi, store: DisposableStore, rowsById: Map): HTMLElement[] { + const selectedId = this._filterService.selectedHostId; + const computers = this._filterService.hosts.filter(host => !isImplicitlyConnectedHost(host)); + const canAddComputers = this._configurationService.getValue(RemoteAgentHostsEnabledSettingId) === true; + const rows: HTMLElement[] = []; + + if (computers.length === 0) { + if (canAddComputers) { + appendTextWithCode(dom.append(list, $('p.host-picker-hint')), localize('hostPicker.noComputers', "Run sessions on your own machine. Start {0} there, then add it here.", TUNNEL_COMMAND), TUNNEL_COMMAND); + } else { + dom.append(list, $('p.host-picker-empty')).textContent = this._filterService.isDiscovering + ? localize('hostPicker.searching', "Searching for your computers…") + : localize('hostPicker.noComputersFound', "No computers found yet."); + } + } + + for (const computer of computers) { + const row = this._renderComputerRow(list, store, computer, computer.id === selectedId, () => { + this._filterService.setSelectedHostId(computer.id); + if (computer.status === AgentHostFilterConnectionStatus.Disconnected) { + void this._filterService.reconnect(computer.id); + } + api.close(); + }); + rowsById.set(computer.id, row); + rows.push(row); + } + + if (canAddComputers) { + rows.push(this._renderRow(list, store, { + icon: Codicon.add, + iconClass: 'add', + label: localize('hostPicker.addComputer', "Add a computer…"), + description: localize('hostPicker.addComputer.description', "Dev Tunnel or address"), + navigates: true, + ariaLabel: localize('hostPicker.addComputer.aria', "Add a computer. Dev Tunnel or address."), + }, () => { + api.close(); + this._showAddComputer(); + })); + } + return rows; + } + + private _renderPlaceRow(body: HTMLElement, store: DisposableStore, place: IAgentHostFilterEntry, checked: boolean, select: () => void): HTMLElement { + return this._renderRow(body, store, { + icon: place.icon, + iconClass: 'place', + label: place.label, + description: place.description, + checked, + ariaLabel: place.description + ? localize('hostPicker.place.aria', "{0}, {1}", place.label, place.description) + : place.label, + }, select); + } + + private _renderComputerRow(body: HTMLElement, store: DisposableStore, computer: IAgentHostFilterEntry, checked: boolean, select: () => void): HTMLElement { + const status = describeComputerStatus(computer.status); + const offline = computer.status === AgentHostFilterConnectionStatus.Disconnected; + return this._renderRow(body, store, { + icon: Codicon.vm, + iconClass: 'computer', + label: computer.label, + description: offline + ? localize('hostPicker.offlineReconnect', "{0} · Tap to reconnect", status) + : status, + statusClass: computer.status, + checked, + ariaLabel: offline + ? localize('hostPicker.computer.offline.aria', "{0}, offline. Select to reconnect.", computer.label) + : localize('hostPicker.computer.aria', "{0}, {1}", computer.label, status), + }, select); + } + + private _renderRow(body: HTMLElement, store: DisposableStore, row: { + readonly icon: ThemeIcon; + readonly iconClass: string; + readonly label: string; + readonly description?: string; + readonly statusClass?: string; + readonly checked?: boolean; + readonly navigates?: boolean; + readonly ariaLabel: string; + }, select: () => void): HTMLElement { + const button = dom.append(body, $('button.host-picker-row.agent-sessions-interactive.agent-sessions-interactive-list', { type: 'button' })) as HTMLButtonElement; + button.classList.toggle('checked', row.checked === true); + button.classList.toggle('navigates', row.navigates === true); + // Rows with a `checked` state are one choice among several; the rest + // (drill-downs, one-shot actions) are plain buttons. + if (row.checked !== undefined) { + button.setAttribute('role', 'menuitemradio'); + button.setAttribute('aria-checked', String(row.checked)); + } + button.setAttribute('aria-label', row.ariaLabel); + + const icon = dom.append(button, $(`span.host-picker-row-icon.${row.iconClass}`)); + icon.append(...renderLabelWithIcons(`$(${row.icon.id})`)); + + const text = dom.append(button, $('span.host-picker-row-text')); + dom.append(text, $('span.host-picker-row-label')).textContent = row.label; + if (row.description) { + const description = dom.append(text, $('span.host-picker-row-description')); + if (row.statusClass) { + dom.append(description, $(`span.host-picker-status-dot.${row.statusClass}`)); + } + dom.append(description, $('span')).textContent = row.description; + } + + if (row.navigates) { + dom.append(button, $('span.host-picker-row-chevron')).append(...renderLabelWithIcons(`$(${Codicon.chevronRight.id})`)); + } else if (row.checked) { + dom.append(button, $('span.host-picker-row-check')).append(...renderLabelWithIcons(`$(${Codicon.check.id})`)); + } + + store.add(Gesture.addTarget(button)); + for (const eventType of [dom.EventType.CLICK, TouchEventType.Tap]) { + store.add(dom.addDisposableListener(button, eventType, e => { + dom.EventHelper.stop(e, true); + select(); + })); + } + return button; + } + + private _renderRefreshAction(section: HTMLElement, store: DisposableStore): HTMLButtonElement { + const action = dom.append(section, $('button.host-picker-section-action.agent-sessions-interactive', { type: 'button' })) as HTMLButtonElement; + const icon = dom.append(action, $('span.host-picker-section-action-icon')); + icon.append(...renderLabelWithIcons(`$(${Codicon.refresh.id})`)); + const label = dom.append(action, $('span')); + const update = () => { + const discovering = this._filterService.isDiscovering; + action.classList.toggle('discovering', discovering); + action.setAttribute('aria-disabled', String(discovering)); + label.textContent = discovering + ? localize('hostPicker.refreshing', "Searching…") + : localize('hostPicker.refresh', "Refresh"); + action.setAttribute('aria-label', discovering + ? localize('hostPicker.refreshing.aria', "Searching for your computers") + : localize('hostPicker.refresh.aria', "Look for your computers again")); + }; + update(); + store.add(this._filterService.onDidChangeDiscovering(update)); + store.add(Gesture.addTarget(action)); + for (const eventType of [dom.EventType.CLICK, TouchEventType.Tap]) { + store.add(dom.addDisposableListener(action, eventType, e => { + dom.EventHelper.stop(e, true); + if (!this._filterService.isDiscovering) { + void this._filterService.rediscover(); + } + })); + } + return action; + } + + /** Second sheet: the web-valid ways to register one of the user's machines. */ + private _showAddComputer(): void { + void showMobileContentSheet(this._layoutService.mainContainer, localize('hostPicker.add.title', "Add a computer"), (body, api) => { + const store = new DisposableStore(); + api.overlay.classList.add('host-picker-overlay'); + const run = (commandId: string) => { + api.close(); + void this._commandService.executeCommand(commandId); + }; + const tunnel = this._renderRow(body, store, { + icon: Codicon.remote, + iconClass: 'computer', + label: localize('hostPicker.add.tunnel', "Dev Tunnel"), + description: localize('hostPicker.add.tunnel.description', "Recommended · choose one of your tunnels"), + navigates: true, + ariaLabel: localize('hostPicker.add.tunnel.aria', "Dev Tunnel. Recommended. Choose one of your tunnels."), + }, () => { + api.close(); + this._showTunnels(); + }); + const address = this._renderRow(body, store, { + icon: Codicon.globe, + iconClass: 'computer', + label: localize('hostPicker.add.address', "Address"), + description: localize('hostPicker.add.address.description', "Paste ws://host:port from the agent host"), + navigates: true, + ariaLabel: localize('hostPicker.add.address.aria', "Address. Paste a WebSocket address from the agent host."), + }, () => run(RemoteAgentHostCommandIds.addRemoteAgentHost)); + appendTextWithCode(dom.append(body, $('p.host-picker-hint')), localize('hostPicker.add.hint', "On the computer, run {0} and keep it running. It appears here as a Dev Tunnel the next time you refresh.", TUNNEL_COMMAND), TUNNEL_COMMAND); + api.setBodyFocusTargets([tunnel, address]); + tunnel.focus(); + return store; + }, { + caption: localize('hostPicker.add.caption', "Your sessions on that machine show up here, and new ones can run there."), + iconClose: true, + trapFocus: true, + }).then(() => restoreFocus(this._opener)); + } + + /** + * Third sheet: the account's dev tunnels, each a computer that can be + * added with one tap. Shares the sign-in, listing and connect steps with + * the desktop command; only the presentation is the phone's own. + */ + private _showTunnels(): void { + void showMobileContentSheet(this._layoutService.mainContainer, localize('hostPicker.tunnels.title', "Dev Tunnels"), (body, api) => { + const store = new DisposableStore(); + api.overlay.classList.add('host-picker-overlay'); + const list = dom.append(body, $('div.host-picker-computers')); + const message = dom.append(body, $('p.host-picker-empty')); + message.setAttribute('role', 'status'); + message.textContent = localize('hostPicker.tunnels.loading', "Looking for your tunnels…"); + let open = true; + store.add({ dispose: () => { open = false; } }); + void this._loadTunnels().then(tunnels => { + if (!open) { + return; + } + if (!tunnels) { + api.close(); + return; + } + if (tunnels.length === 0) { + dom.clearNode(message); + appendTextWithCode(message, localize('hostPicker.tunnels.none', "No tunnels found. On the computer, run {0} and keep it running, then try again.", TUNNEL_COMMAND), TUNNEL_COMMAND); + return; + } + message.remove(); + const rows = tunnels.map(tunnel => { + const online = tunnel.hostConnectionCount > 0; + return this._renderRow(list, store, { + icon: Codicon.vm, + iconClass: 'computer', + label: tunnel.name, + description: online + ? localize('hostPicker.tunnels.online', "{0} · Online", tunnel.tunnelId) + : localize('hostPicker.tunnels.offline', "{0} · Offline", tunnel.tunnelId), + statusClass: online ? AgentHostFilterConnectionStatus.Connected : AgentHostFilterConnectionStatus.Disconnected, + ariaLabel: online + ? localize('hostPicker.tunnels.online.aria', "{0}, online. Add this computer.", tunnel.name) + : localize('hostPicker.tunnels.offline.aria', "{0}, offline. Add this computer.", tunnel.name), + }, () => { + api.close(); + void this._addTunnel(tunnel); + }); + }); + api.setBodyFocusTargets(rows); + rows[0].focus(); + }); + return store; + }, { + caption: localize('hostPicker.tunnels.caption', "Computers your GitHub account can reach. Tap one to add it."), + iconClose: true, + trapFocus: true, + }).then(() => restoreFocus(this._opener)); + } + + /** The tunnels to offer, or `undefined` when sign-in or listing failed (already reported). */ + private async _loadTunnels(): Promise { + try { + return await this._instantiationService.createInstance(MobileTunnelConnection).list(); + } catch (err) { + this._notificationService.error(localize('hostPicker.tunnels.failed', "Failed to list dev tunnels: {0}", err instanceof Error ? err.message : String(err))); + return undefined; + } + } + + /** Connect the tunnel and make the new computer the place sessions run. */ + private async _addTunnel(tunnel: ITunnelInfo): Promise { + try { + await this._instantiationService.createInstance(MobileTunnelConnection).connect(tunnel); + } catch (error) { + this._notificationService.error(localize('hostPicker.tunnels.connectFailed', "Failed to connect to tunnel '{0}': {1}", tunnel.name, error instanceof Error ? error.message : String(error))); + return; + } + const address = `${TUNNEL_ADDRESS_PREFIX}${tunnel.tunnelId}`; + const select = (): boolean => { + const host = this._filterService.hosts.find(h => h.address === address); + if (host) { + this._filterService.setSelectedHostId(host.id); + } + return !!host; + }; + if (!select()) { + // The provider for a freshly connected tunnel registers a moment + // later; select it as soon as it shows up. + this._pendingSelection.value = this._filterService.onDidChange(() => { + if (select()) { + this._pendingSelection.clear(); + } + }); + } + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPlaceChipViewItem.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPlaceChipViewItem.ts new file mode 100644 index 000000000000..2c8b3f4a0242 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileHostPlaceChipViewItem.ts @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/hostPlaceChip.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; +import { BaseActionViewItem } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { IAction } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; +import { localize } from '../../../../../nls.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IAgentHostFilterService } from '../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { isImplicitlyConnectedHost } from './mobileAgentHostFilterService.js'; +import { describeComputerStatus, MobileHostPickerSheet } from './mobileHostPickerSheet.js'; + +const $ = dom.$; + +/** + * The chip on the phone's new-session screen that names where the session + * will run, on its own row above the workspace and agent chips. It is built + * like those chips (icon · label · chevron on an `a.action-label` inside a + * picker slot) so the row's styles dress it, carries no connection state (the + * sheet shows that), and opens the + * {@link MobileHostPickerSheet} on tap — the same sheet the drawer header + * opens, so choosing a place for a new session never leaves Home. + */ +export class MobileHostPlaceChipViewItem extends BaseActionViewItem { + + private readonly _sheet: MobileHostPickerSheet; + private _trigger: HTMLAnchorElement | undefined; + private _icon: HTMLElement | undefined; + private _label: HTMLElement | undefined; + + constructor( + action: IAction, + @IAgentHostFilterService private readonly _filterService: IAgentHostFilterService, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(undefined, action); + this._sheet = this._register(instantiationService.createInstance(MobileHostPickerSheet)); + this._register(this._filterService.onDidChange(() => this._update())); + this._register(this._filterService.onDidChangeDiscovering(() => this._update())); + } + + override render(container: HTMLElement): void { + super.render(container); + if (!this.element) { + return; + } + this.element.classList.add('sessions-chat-picker-slot', 'sessions-workspace-category-picker-slot', 'sessions-new-session-place'); + + const trigger = this._trigger = dom.append(this.element, $('a.action-label.sessions-new-session-place-trigger')) as HTMLAnchorElement; + trigger.tabIndex = 0; + trigger.role = 'button'; + trigger.setAttribute('aria-haspopup', 'dialog'); + this._icon = dom.append(trigger, $('span.sessions-new-session-place-icon')); + this._label = dom.append(trigger, $('span.sessions-chat-dropdown-label')); + const chevron = dom.append(trigger, renderIcon(Codicon.chevronDownCompact)); + chevron.classList.add('sessions-chat-dropdown-chevron'); + chevron.setAttribute('aria-hidden', 'true'); + + this._register(dom.addDisposableListener(trigger, dom.EventType.KEY_DOWN, e => { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { + dom.EventHelper.stop(e, true); + this._sheet.show(); + } + })); + + this._update(); + } + + /** + * The base view item routes every click and tap on the action item here. + * The item is the whole target — the pill and, on the phone, the invisible + * 44px area around it — so this is where the sheet opens. + */ + override onClick(event: dom.EventLike): void { + dom.EventHelper.stop(event, true); + this._sheet.show(); + } + + override focus(): void { + this._trigger?.focus(); + } + + private _update(): void { + if (!this._trigger || !this._icon || !this._label) { + return; + } + const selected = this._filterService.selectedHost; + dom.clearNode(this._icon); + + if (!selected) { + this._icon.append(renderIcon(Codicon.remote)); + this._label.textContent = this._filterService.isDiscovering + ? localize('placeChip.searching', "Searching…") + : localize('placeChip.none', "Where to run"); + this._trigger.setAttribute('aria-label', localize('placeChip.none.aria', "Choose where the new session runs")); + return; + } + + if (isImplicitlyConnectedHost(selected)) { + this._icon.append(renderIcon(selected.icon)); + this._label.textContent = selected.label; + this._trigger.setAttribute('aria-label', selected.description + ? localize('placeChip.place.aria', "New session runs in {0}, {1}. Change where it runs.", selected.label, selected.description) + : localize('placeChip.place.short.aria', "New session runs in {0}. Change where it runs.", selected.label)); + return; + } + + // A computer: its glyph and name. Connection state is the sheet's business. + this._icon.append(renderIcon(Codicon.vm)); + this._label.textContent = selected.label; + this._trigger.setAttribute('aria-label', localize('placeChip.computer.aria', "New session runs on {0}, {1}. Change where it runs.", selected.label, describeComputerStatus(selected.status))); + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileTunnelConnection.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileTunnelConnection.ts new file mode 100644 index 000000000000..92f788246627 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/mobileTunnelConnection.ts @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ITunnelAgentHostService, ITunnelInfo, isTunnelHosted } from '../../../../../platform/agentHost/common/tunnelAgentHost.js'; +import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IRemoteTunnelService } from '../../../../../platform/remoteTunnel/common/remoteTunnel.js'; +import { IAuthenticationService } from '../../../../../workbench/services/authentication/common/authentication.js'; +import { localize } from '../../../../../nls.js'; +import { IConnectionDiagnosticsService } from '../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/connectionDiagnostics.js'; + +/** Mobile picker orchestration over the existing authentication and tunnel services. */ +export class MobileTunnelConnection { + constructor( + @ITunnelAgentHostService private readonly tunnels: ITunnelAgentHostService, + @IConnectionDiagnosticsService private readonly diagnostics: IConnectionDiagnosticsService, + @IRemoteTunnelService private readonly remoteTunnel: IRemoteTunnelService, + @IAuthenticationService private readonly authentication: IAuthenticationService, + @IProductService private readonly product: IProductService, + @INotificationService private readonly notifications: INotificationService, + ) { } + + async list(): Promise { + const scopes = this.product.tunnelApplicationConfig?.authenticationProviders?.github?.scopes ?? []; + if (!(await this.authentication.getSessions('github', scopes)).length) { + await this.authentication.createSession('github', scopes, { activateImmediate: true }); + } + const [tunnels, status] = await Promise.all([ + this.diagnostics.trackDiscovery('mobile-add-computer', onDiagnostic => this.tunnels.listTunnels({ authProvider: 'github', onDiagnostic })), + this.remoteTunnel.getTunnelStatus(), + ]); + return tunnels.filter(tunnel => !isTunnelHosted(status.type === 'connected' ? status.info : undefined, tunnel)) + .sort((a, b) => a.name.localeCompare(b.name)); + } + + async connect(tunnel: ITunnelInfo): Promise { + const progress = this.notifications.notify({ + severity: Severity.Info, + message: localize('connecting', "Connecting to tunnel '{0}'...", tunnel.name), + progress: { infinite: true }, + }); + try { + this.tunnels.clearTunnelDismissal(tunnel.tunnelId); + await this.tunnels.connect(tunnel, 'github', { userInitiated: true }); + } finally { + progress.close(); + } + } +} diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts index d6682650cce7..14bd4160060d 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts @@ -27,7 +27,7 @@ import { IOpenerService } from '../../../../../platform/opener/common/opener.js' import { ILogService } from '../../../../../platform/log/common/log.js'; import { addWebSocketRemoteAgentHostEntry, IRemoteAgentHostService, parseRemoteAgentHostInput, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostInputValidationError, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; -import { computeSSHConnectionKey, ISSHRemoteAgentHostService, isSSHHostKeyDeniedError, SSHAuthMethod, type ISSHAgentHostConfig, type ISSHResolvedConfig } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { computeSSHConnectionKey, ISSHRemoteAgentHostService, isSSHHostKeyDeniedError, SSHAuthMethod, type ISSHAgentHostConfig, type ISSHResolvedConfig, type SSHAgentHostConnectionRequest } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { isTunnelHosted, ITunnelAgentHostService, TUNNEL_ADDRESS_PREFIX, type ITunnelInfo } from '../../../../../platform/agentHost/common/tunnelAgentHost.js'; import { IWSLRemoteAgentHostService, WSL_INSTALL_DOCS_URL, type IWSLDistro } from '../../../../../platform/agentHost/common/wslRemoteAgentHost.js'; import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; @@ -413,20 +413,10 @@ async function connectToConfiguredSSHHost( const port = resolvedConfig.port !== 22 ? resolvedConfig.port : undefined; const suggestedName = hostAlias; - // Pass through the first resolved IdentityFile (if any) as the explicit - // key. The main process is responsible for de-duplicating against its - // default-key scan, so we don't need to filter here. const defaultKeyPath = resolvedConfig.identityFile[0]; if (username) { - const config: ISSHAgentHostConfig = { - host, - port, - username, - authMethod: SSHAuthMethod.Agent, - privateKeyPath: defaultKeyPath, - identityAgent: resolvedConfig.identityAgent, - agentForward: resolvedConfig.forwardAgent || undefined, + const config: SSHAgentHostConnectionRequest = { name: suggestedName, sshConfigHost: hostAlias, }; @@ -564,7 +554,7 @@ async function promptForCredentialsAndConnect( export async function connectWithProgress( accessor: ServicesAccessor, - config: ISSHAgentHostConfig, + config: SSHAgentHostConnectionRequest, displayHost: string, ): Promise { const sshService = accessor.get(ISSHRemoteAgentHostService); @@ -669,6 +659,7 @@ registerAction2(class extends Action2 { id: RemoteAgentHostCommandIds.connectViaSSH, title: localize2('connectViaSSH', "Connect to Remote Agent Host via SSH"), shortTitle: localize2('connectViaSSHShort', "SSH..."), + tooltip: localize2('connectViaSSHTooltip', "Connect to a computer over SSH"), category: SessionsCategories.Sessions, f1: true, icon: Codicon.remote, @@ -1113,6 +1104,7 @@ registerAction2(class extends Action2 { id: RemoteAgentHostCommandIds.connectViaTunnel, title: localize2('connectViaTunnel', "Connect to Remote Agent Host via Dev Tunnel"), shortTitle: localize2('connectViaTunnelShort', "Dev Tunnels..."), + tooltip: localize2('connectViaTunnelTooltip', "Connect to a computer shared through a dev tunnel"), category: SessionsCategories.Sessions, f1: true, icon: Codicon.remote, @@ -1283,6 +1275,7 @@ registerAction2(class extends Action2 { id: RemoteAgentHostCommandIds.connectViaWSL, title: localize2('connectViaWSL', "Connect to Remote Agent Host via WSL"), shortTitle: localize2('connectViaWSLShort', "WSL..."), + tooltip: localize2('connectViaWSLTooltip', "Run sessions in a WSL distribution on this computer"), category: SessionsCategories.Sessions, f1: true, icon: Codicon.terminalLinux, diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteWorkspaceHandoffService.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteWorkspaceHandoffService.ts index 24ece7f44840..43cfb946d1ca 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteWorkspaceHandoffService.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteWorkspaceHandoffService.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ import { raceCancellationError } from '../../../../../base/common/async.js'; -import { decodeHex } from '../../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; import { CancellationError, isCancellationError } from '../../../../../base/common/errors.js'; @@ -16,7 +15,8 @@ import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { agentHostAuthority, toAgentHostUri } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { addSSHRemoteAgentHostEntry, getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; -import { computeSSHConnectionKey, ISSHRemoteAgentHostService } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { computeSSHConnectionKey, ISSHRemoteAgentHostService, parseSSHRemoteAuthority } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService, TunnelAuthenticationRequiredError } from '../../../../../platform/agentHost/common/tunnelAgentHost.js'; import { IWSLRemoteAgentHostService, WSL_ADDRESS_PREFIX } from '../../../../../platform/agentHost/common/wslRemoteAgentHost.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; @@ -29,6 +29,7 @@ import { getRemoteName } from '../../../../../platform/remote/common/remoteHosts import { IStorageService } from '../../../../../platform/storage/common/storage.js'; import { IAgentHostSessionsProvider, isAgentHostProvider } from '../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { IRemoteWorkspaceFolder, IRemoteWorkspaceHandoffService, RemoteAgentHostHandoffResult, RemoteWorkspaceHandoffResult } from '../../../../common/remoteWorkspaceHandoff.js'; +import { getEditorWindowSessionUnsupportedReason } from '../../../../../workbench/contrib/sessions/browser/openInVSCodeUtils.js'; import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; /** How long to wait for a host's provider after adding the host. */ @@ -44,12 +45,6 @@ type RemoteMachine = /** A parsed machine; an undefined WSL distribution is the default one. */ type ParsedRemoteMachine = RemoteMachine | { readonly kind: 'wsl'; readonly distro: undefined }; -interface ISSHHost { - readonly hostName: string; - readonly user?: string; - readonly port?: number; -} - /** * Parses SSH, WSL and Tunnel remote authorities as their extensions do: * - Remote - SSH (`HostInfo.parse`): hex-encoded JSON or a plain `[user@]host[:port]`. Its host name doubles as an @@ -66,7 +61,10 @@ export function parseRemoteMachine(remoteAuthority: string): ParsedRemoteMachine } switch (remoteName) { case 'ssh-remote': { - const parsed = readSSHAuthorityObject(host) ?? parseSSHHostString(host); + const parsed = parseSSHRemoteAuthority(remoteAuthority); + if (!parsed) { + return undefined; + } return parsed.user === undefined && parsed.port === undefined ? { kind: 'ssh', sshConfigHost: parsed.hostName } : { kind: 'ssh', hostName: parsed.hostName, user: parsed.user, port: parsed.port }; @@ -83,38 +81,6 @@ export function parseRemoteMachine(remoteAuthority: string): ParsedRemoteMachine } } -function readSSHAuthorityObject(host: string): ISSHHost | undefined { - try { - const value: { hostName?: unknown; user?: unknown; port?: unknown } = JSON.parse(decodeHex(host).toString()); - if (typeof value?.hostName !== 'string' || !value.hostName) { - return undefined; - } - return { - hostName: value.hostName, - user: typeof value.user === 'string' && value.user ? value.user : undefined, - port: typeof value.port === 'number' ? value.port : undefined, - }; - } catch { - // Plain host names are not hex-encoded JSON. - return undefined; - } -} - -/** Mirrors `HostInfo.fromString` of Remote - SSH. An address with more than one colon is an IPv6 address. */ -function parseSSHHostString(host: string): ISSHHost { - const { user, address = host } = /^(?:(?.*)@)?(?
.+?)$/.exec(host)?.groups ?? {}; - const toPort = (port: string | undefined) => port ? parseInt(port, 10) : undefined; - const bracketed = /^\[(?.+?)\](?::(?\d+))?$/.exec(address)?.groups; - if (bracketed) { - return { hostName: bracketed.hostName, user: user || undefined, port: toPort(bracketed.port) }; - } - if (address.indexOf(':') !== address.lastIndexOf(':')) { - return { hostName: address, user: user || undefined }; - } - const withPort = /^(?.+?)(?::(?\d+))?$/.exec(address)?.groups; - return { hostName: withPort?.hostName ?? address, user: user || undefined, port: toPort(withPort?.port) }; -} - function isDefaultDistro(machine: ParsedRemoteMachine): machine is { readonly kind: 'wsl'; readonly distro: undefined } { return machine.kind === 'wsl' && machine.distro === undefined; } @@ -188,6 +154,7 @@ export class RemoteWorkspaceHandoffService extends Disposable implements IRemote @INotificationService private readonly _notificationService: INotificationService, @IDialogService private readonly _dialogService: IDialogService, @ILogService private readonly _logService: ILogService, + @IRemoteAgentHostLocationPreferenceService private readonly _locationPreferenceService: IRemoteAgentHostLocationPreferenceService, ) { super(); this._register(toDisposable(() => this._connections.dispose(true))); @@ -249,12 +216,10 @@ export class RemoteWorkspaceHandoffService extends Disposable implements IRemote return { unavailableReason: localize('remoteWorkspaceHandoff.addFailed', "'{0}' could not be added as a remote agent host: {1}", machine ? getMachineLabel(machine) : remoteAuthority, toErrorMessage(error)) }; } const address = getEntryAddress(entry); - const isTunnel = entry.connection.type === RemoteAgentHostEntryType.Tunnel; return { connectionAuthority: agentHostAuthority(address), connected: this._connect(address, machine), - // A tunnel's editor windows reach its standalone agent host, which its gateway may not have selected. - sharesEditorWindowAgentHost: () => isTunnel && this._tunnelService.getSelectedServerType(address) !== 'editor', + sharesEditorWindowAgentHost: () => getEditorWindowSessionUnsupportedReason(entry, this._tunnelService, this._sshService, this._locationPreferenceService) === undefined, }; } diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/sshAgentHost.contribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/sshAgentHost.contribution.ts index bbd63c4373a4..6946ced680a7 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/sshAgentHost.contribution.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/sshAgentHost.contribution.ts @@ -7,8 +7,7 @@ import { IntervalTimer } from '../../../../../base/common/async.js'; import { isCancellationError } from '../../../../../base/common/errors.js'; import { StopWatch } from '../../../../../base/common/stopwatch.js'; import { type IRemoteAgentHostEntry, IRemoteAgentHostService, type IRemoteAgentHostSSHConnection, getEntryAddress, getEntryTypeConfig, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId, RemoteAgentHostsSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; -import { computeReconnectDelay } from '../../../../../platform/agentHost/common/reconnectPolicy.js'; -import { computeSSHConnectionKey, isSSHHostKeyDeniedError, ISSHRemoteAgentHostService, SSHAuthMethod } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { computeSSHConnectionKey, isSSHAuthenticationFailedError, isSSHHostKeyDeniedError, ISSHRemoteAgentHostService, SSHAuthMethod } from '../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; @@ -24,7 +23,7 @@ const SSH_RECONNECT_PERIODIC_INTERVAL_MS = 60_000; /** Returns whether an SSH reconnect failure requires pausing retries. */ export function shouldPauseSSHReconnectAfterFailure(err: unknown): boolean { - return isCancellationError(err) || isSSHHostKeyDeniedError(err); + return isCancellationError(err) || isSSHHostKeyDeniedError(err) || isSSHAuthenticationFailedError(err); } export class SSHAgentHostContribution extends ManagedReconnectAgentHostContribution implements IWorkbenchContribution { @@ -46,22 +45,16 @@ export class SSHAgentHostContribution extends ManagedReconnectAgentHostContribut super(remoteAgentHostService, configurationService, logService, instantiationService, sessionsProvidersService, notificationService); this._register(this._remoteAgentHostService.onDidChangeConfiguredEntries(() => this._reconcile())); - this._register(this._remoteAgentHostService.onDidChangeConnections(() => { - this._resumeSSHReconnects(); - this._reconcile(); - })); + this._register(this._remoteAgentHostService.onDidChangeConnections(() => this._reconcile())); this._register(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(RemoteAgentHostsSettingId) || e.affectsConfiguration(RemoteAgentHostsEnabledSettingId)) { - this._resumeSSHReconnects(); this._reconcile(); } })); - this._register(new IntervalTimer()).cancelAndSet(() => { - this._resumeSSHReconnects(); - this._reconcile(); - }, SSH_RECONNECT_PERIODIC_INTERVAL_MS); + // The connection service owns retries; the periodic sweep only reconciles providers. + this._register(new IntervalTimer()).cancelAndSet(() => this._reconcile(), SSH_RECONNECT_PERIODIC_INTERVAL_MS); this._reconcile(); } @@ -125,37 +118,24 @@ export class SSHAgentHostContribution extends ManagedReconnectAgentHostContribut return; } this._reconnectStates.get(sshConfigHost)?.resetForResume(); - await this._attemptSSHReconnect(sshConfigHost, name, address, true); - } - - private async _disconnectSSHOnDemand(connection: IRemoteAgentHostSSHConnection): Promise { - if (connection.sshConfigHost) { - this._reconnectStates.deleteAndDispose(connection.sshConfigHost); - } - await disconnectSSHEntry(connection, this._remoteAgentHostService, this._sshService); - } - - private async _attemptSSHReconnect(sshConfigHost: string, name: string, address: string, userInitiated: boolean): Promise { - const reconnectPolicy = getEntryTypeConfig(RemoteAgentHostEntryType.SSH).reconnect; - const attempt = (this._reconnectStates.get(sshConfigHost)?.attempts ?? 0) + 1; const stopwatch = StopWatch.create(false); await this._attemptManagedReconnect({ kind: 'SSH', key: sshConfigHost, address, - userInitiated, - reconnectPolicy, + userInitiated: true, + reconnectPolicy: getEntryTypeConfig(RemoteAgentHostEntryType.SSH).reconnect, shouldPause: shouldPauseSSHReconnectAfterFailure, - requiresUserInitiatedResume: isSSHHostKeyDeniedError, - getPauseReason: err => isSSHHostKeyDeniedError(err) ? 'host key denial' : 'user cancellation', + requiresUserInitiatedResume: shouldPauseSSHReconnectAfterFailure, + getPauseReason: err => isSSHHostKeyDeniedError(err) ? 'host key denial' : isSSHAuthenticationFailedError(err) ? 'authentication failure' : 'user cancellation', doConnect: async () => { try { - this._remoteAgentHostService.reconnect(address, userInitiated); + this._remoteAgentHostService.reconnect(address, true); await this._remoteAgentHostService.waitForConnection(address); logSSHConnectAttempt(this._telemetryService, { operation: 'reconnect', - userInitiated, - attempt, + userInitiated: true, + attempt: 1, durationMs: stopwatch.elapsed(), success: true, willRetry: false, @@ -163,8 +143,8 @@ export class SSHAgentHostContribution extends ManagedReconnectAgentHostContribut } catch (err) { logSSHConnectAttempt(this._telemetryService, { operation: 'reconnect', - userInitiated, - attempt, + userInitiated: true, + attempt: 1, durationMs: stopwatch.elapsed(), success: false, willRetry: false, @@ -173,29 +153,14 @@ export class SSHAgentHostContribution extends ManagedReconnectAgentHostContribut throw err; } }, - schedule: state => { - state.scheduleRetry(computeReconnectDelay(reconnectPolicy, state.attempts), () => { - void this._attemptSSHReconnect(sshConfigHost, name, address, false); - }); - }, }); } - private _resumeSSHReconnects(): void { - let resumed = 0; - for (const entry of this._getProviderEntries()) { - if (entry.connection.type !== RemoteAgentHostEntryType.SSH || !entry.connection.sshConfigHost) { - continue; - } - const state = this._reconnectStates.get(entry.connection.sshConfigHost); - if (state?.resumeAutomatically()) { - resumed++; - void this._attemptSSHReconnect(entry.connection.sshConfigHost, entry.name, getEntryAddress(entry), false); - } - } - if (resumed > 0) { - this._logService.info(`[RemoteAgentHost] Resuming SSH auto-reconnect for ${resumed} paused host(s)`); + private async _disconnectSSHOnDemand(connection: IRemoteAgentHostSSHConnection): Promise { + if (connection.sshConfigHost) { + this._reconnectStates.deleteAndDispose(connection.sshConfigHost); } + await disconnectSSHEntry(connection, this._remoteAgentHostService, this._sshService); } } diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/devContainerAgentHostConnector.contribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/devContainerAgentHostConnector.contribution.ts index d55b9283a7f1..2db275662c6e 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/devContainerAgentHostConnector.contribution.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/devContainerAgentHostConnector.contribution.ts @@ -5,11 +5,13 @@ import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { CancellationError, isCancellationError } from '../../../../../base/common/errors.js'; +import { StopWatch } from '../../../../../base/common/stopwatch.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { StringSHA1 } from '../../../../../base/common/hash.js'; import { basename, getComparisonKey } from '../../../../../base/common/resources.js'; import { combinedDisposable, Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; import { waitForState } from '../../../../../base/common/observable.js'; +import { env } from '../../../../../base/common/process.js'; import { URI } from '../../../../../base/common/uri.js'; import { generateUuid } from '../../../../../base/common/uuid.js'; import { Schemas } from '../../../../../base/common/network.js'; @@ -21,7 +23,7 @@ import { AgentHostClientConnectionKind } from '../../../../../platform/agentHost import { AgentHostAhpJsonlLoggingSettingId } from '../../../../../platform/agentHost/common/agentService.js'; import { AhpJsonlLogger } from '../../../../../platform/agentHost/common/ahpJsonlLogger.js'; import { AgentHostClientProxy } from '../../../../../platform/agentHost/browser/agentHostClientProxy.js'; -import { DEV_CONTAINER_AGENT_HOST_CHANNEL, IDevContainerAgentHostConfig, IDevContainerAgentHostMainService, IDevContainerAgentHostOutput, IDevContainerAgentHostSandboxSupport } from '../../../../../platform/agentHost/common/devContainerAgentHost.js'; +import { DEV_CONTAINER_AGENT_HOST_CHANNEL, IDevContainerAgentHostConfig, IDevContainerAgentHostMainService, IDevContainerAgentHostOutput, IDevContainerAgentHostSandboxSupport, IDevContainerAgentHostUserStateReport } from '../../../../../platform/agentHost/common/devContainerAgentHost.js'; import { findDevContainerSample, IDevContainerSampleSource } from '../../../../../platform/agentHost/common/devContainerSamples.js'; import { ReconnectingRelayTransport, type IRelayConnectionHandle, type IRelayMessage } from '../../../../../platform/agentHost/common/relayTransport.js'; import { getEntryAddress, IRemoteAgentHostService, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; @@ -38,7 +40,7 @@ import { Registry } from '../../../../../platform/registry/common/platform.js'; import { ITelemetryService, TelemetryLevel } from '../../../../../platform/telemetry/common/telemetry.js'; import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../../workbench/common/contributions.js'; import { Extensions, IOutputChannelRegistry, IOutputService } from '../../../../../workbench/services/output/common/output.js'; -import { areDevContainerSamplesEnabled, DevContainerAgentHostEnabledSettingId, DevContainerIdleTimeoutSettingId, DevContainerSamplesEnabledSettingId, DevContainerWorktreeEnabledSettingId, IDevContainerAgentHostConnection, IDevContainerAgentHostConnector, IDevContainerAgentHostService } from '../../../../../workbench/contrib/sessions/common/devContainerAgentHostService.js'; +import { areDevContainerSamplesEnabled, DevContainerAgentHostEnabledSettingId, DevContainerIdleTimeoutSettingId, DevContainerSamplesEnabledSettingId, DevContainerStateVolumeEnabledSettingId, DevContainerWorktreeEnabledSettingId, IDevContainerAgentHostConnection, IDevContainerAgentHostConnector, IDevContainerAgentHostService } from '../../../../../workbench/contrib/sessions/common/devContainerAgentHostService.js'; import { ISessionsRecentWorkspacesService } from '../../../../../workbench/contrib/sessions/browser/sessionsRecentWorkspacesService.js'; import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { devContainerSourcePath, getDevContainerSourceEntry, resolveDevContainerSourceConnection } from '../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/devContainerSource.js'; @@ -59,6 +61,89 @@ type DevContainerEnvironmentClassification = { type DevContainerEnvironment = Omit; +type DevContainerStateVolumeEvent = { + stage: string; + outcome: string; + reason: string | undefined; + step: string | undefined; + target: string | undefined; + skipReasons: string | undefined; + exitCode: number | undefined; + restoredFolders: number | undefined; + movedFolders: number | undefined; + createdFolders: number | undefined; + existingFolders: number | undefined; + skippedFolders: number | undefined; + errorMessage: string | undefined; + enabled: boolean; + sample: boolean; + remote: boolean; +}; + +type DevContainerStateVolumeClassification = { + owner: 'chrmarti'; + comment: 'Reports how keeping user and agent state on a per-container volume went, to evaluate the chat.agentHost.devContainer.stateVolume.enabled experiment.'; + stage: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The stage: mount (adding the volume), up (starting the container), link (linking state folders to it) or userCommands (lifecycle commands, which run after linking).' }; + outcome: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The stage outcome, e.g., added, existingContainer, linked, noMount, homeNotFound, succeeded or failed.' }; + reason: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Fixed identifier of the operation that failed.' }; + step: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Fixed identifier of the link script step that failed.' }; + target: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the volume is mounted at /workspaces or at a separate folder.' }; + skipReasons: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Fixed identifiers of why state folders were not persisted, e.g., because they are already mounted.' }; + exitCode: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Exit code of the failed command.' }; + restoredFolders: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of state folders restored from an earlier container.' }; + movedFolders: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of existing state folders moved to the volume.' }; + createdFolders: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of new state folders created on the volume.' }; + existingFolders: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of state folders that were already linked.' }; + skippedFolders: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of state folders not persisted.' }; + errorMessage: { classification: 'CallstackOrException'; purpose: 'FeatureInsight'; comment: 'Error message of a failed stage without command lines, ids and the container user; the telemetry service also redacts paths and secrets.' }; + enabled: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the chat.agentHost.devContainer.stateVolume.enabled setting is on. Linking also runs for containers created with it on.' }; + sample: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the container is for a Dev Container sample.' }; + remote: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the container runs on a remote Docker host through SSH, Tunnel or WSL.' }; +}; + +export function reportDevContainerUserState(telemetryService: ITelemetryService, report: IDevContainerAgentHostUserStateReport, enabled: boolean, sample: boolean, remote: boolean): void { + telemetryService.publicLog2('vscodeAgents.devContainer/stateVolume', { + stage: report.stage, + outcome: report.outcome, + reason: report.reason, + step: report.step, + target: report.target, + skipReasons: report.skipReasons || undefined, + exitCode: report.exitCode, + restoredFolders: report.restoredFolders, + movedFolders: report.movedFolders, + createdFolders: report.createdFolders, + existingFolders: report.existingFolders, + skippedFolders: report.skippedFolders, + errorMessage: report.errorMessage, + enabled, + sample, + remote, + }); +} + +type DevContainerConnectEvent = { + success: boolean; + cancelled: boolean; + reconnect: boolean; + stateVolume: boolean; + sample: boolean; + remote: boolean; + durationMs: number; +}; + +type DevContainerConnectClassification = { + owner: 'chrmarti'; + comment: 'Reports whether starting a Dev Container and its Agent Host succeeded, to compare reliability with and without the chat.agentHost.devContainer.stateVolume.enabled experiment.'; + success: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether the Dev Container and its Agent Host started.' }; + cancelled: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether the attempt failed because it was cancelled.' }; + reconnect: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether this is an automatic reconnect rather than the initial connection.' }; + stateVolume: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether user state was kept on a per-container volume.' }; + sample: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the container is for a Dev Container sample.' }; + remote: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the container runs on a remote Docker host through SSH, Tunnel or WSL.' }; + durationMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Duration of the attempt in milliseconds.' }; +}; + async function hasDevContainerConfiguration(workspaceUri: URI, fileService: IFileService): Promise { const configurations = await Promise.all([ fileService.exists(URI.joinPath(workspaceUri, '.devcontainer', 'devcontainer.json')), @@ -165,6 +250,8 @@ export class RemoteDevContainerService extends Disposable implements IDevContain readonly onDidOutput = this._output.event; private readonly _sandboxSupport = this._register(new Emitter()); readonly onDidChangeSandboxSupport = this._sandboxSupport.event; + private readonly _userState = this._register(new Emitter()); + readonly onDidReportUserState = this._userState.event; private readonly _connections = new Map(); private _disposed = false; @@ -206,6 +293,9 @@ export class RemoteDevContainerService extends Disposable implements IDevContain if (service.onDidChangeSandboxSupport) { store.add(Event.filter(service.onDidChangeSandboxSupport, event => event.connectionId === config.connectionId)(event => this._sandboxSupport.fire(event))); } + if (service.onDidReportUserState) { + store.add(Event.filter(service.onDidReportUserState, event => event.connectionId === config.connectionId)(event => this._userState.fire(event))); + } return await service.connect(config); } catch (error) { if (this._connections.get(config.connectionId) === entry) { @@ -325,6 +415,7 @@ export class DevContainerAgentHostConnector extends Disposable implements IDevCo @IRemoteAgentHostService private readonly _remoteAgentHostService: IRemoteAgentHostService, @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, @IRequestService private readonly _requestService: IRequestService, + @ITelemetryService private readonly _telemetryService: ITelemetryService, ) { super(); this._mainService = ProxyChannel.toService( @@ -390,12 +481,36 @@ export class DevContainerAgentHostConnector extends Disposable implements IDevCo const name = sourceEntry ? `${basename(workspaceUri)} Dev Container (${sourceEntry.name})` : `${basename(workspaceUri)} Dev Container`; const connectionStore = new DisposableStore(); const outputWriter = connectionStore.add(new DevContainerOutputWriter(mainService, connectionId, workspaceUri, this._outputService)); - const connectionIds = new Set([connectionId]); + // Whether each connection keeps user state on a volume. + const connectionIds = new Map(); const cancellationListener = token.onCancellationRequested(() => { void mainService.disconnect(connectionId).catch(error => { this._logService.warn('[DevContainerAgentHostConnector] Failed to cancel connection', error); }); }); + const connect = async (config: IDevContainerAgentHostConfig, reconnect: boolean) => { + // Read on every connect, so a container created on reconnect follows the current setting. + const persistUserState = this._configurationService.getValue(DevContainerStateVolumeEnabledSettingId) === true; + connectionIds.set(config.connectionId, persistUserState); + const stopWatch = StopWatch.create(false); + const report = (success: boolean, cancelled: boolean) => this._telemetryService.publicLog2('vscodeAgents.devContainer/connect', { + success, + cancelled, + reconnect, + stateVolume: persistUserState, + sample: !!sample, + remote: !!sourceEntry, + durationMs: stopWatch.elapsed(), + }); + try { + const connected = await mainService.connect(persistUserState ? { ...config, persistUserState } : config); + report(true, false); + return connected; + } catch (error) { + report(false, isCancellationError(error) || (!reconnect && token.isCancellationRequested)); + throw error; + } + }; try { if (mainService.onDidChangeSandboxSupport) { connectionStore.add(mainService.onDidChangeSandboxSupport(event => { @@ -404,13 +519,21 @@ export class DevContainerAgentHostConnector extends Disposable implements IDevCo } })); } - let result = await mainService.connect({ + if (mainService.onDidReportUserState) { + connectionStore.add(mainService.onDidReportUserState(event => { + const persistUserState = connectionIds.get(event.connectionId); + if (persistUserState !== undefined) { + reportDevContainerUserState(this._telemetryService, event, persistUserState, !!sample, !!sourceEntry); + } + })); + } + let result = await connect({ connectionId, ...source, name, resume: options?.resume ?? true, ...(options?.sandboxEnabled !== undefined ? { sandboxEnabled: options.sandboxEnabled } : {}), - }); + }, false); if (token.isCancellationRequested) { throw new CancellationError(); } @@ -433,16 +556,15 @@ export class DevContainerAgentHostConnector extends Disposable implements IDevCo } const reconnectConnectionId = generateUuid(); - connectionIds.add(reconnectConnectionId); outputWriter.addConnection(reconnectConnectionId); try { - result = await mainService.connect({ + result = await connect({ connectionId: reconnectConnectionId, ...source, name, resume: false, ...(options?.sandboxEnabled !== undefined ? { sandboxEnabled: options.sandboxEnabled } : {}), - }); + }, true); return { connectionId: reconnectConnectionId, close: async () => { @@ -488,7 +610,7 @@ export class DevContainerAgentHostConnector extends Disposable implements IDevCo isEnabled: () => result.sharesClientNetwork === true && this._configurationService.getValue('http.systemCertificates') !== false, loadCertificates: () => this._requestService.loadCertificates(), }, - clientProxy: remoteService ? undefined : this._instantiationService.createInstance(AgentHostClientProxy, () => result.sharesClientNetwork === true), + clientProxy: remoteService ? undefined : this._instantiationService.createInstance(AgentHostClientProxy, () => result.sharesClientNetwork === true, env), transportFactory, transportDisposable: combinedDisposable( connectionStore, @@ -567,6 +689,14 @@ Registry.as(ConfigurationExtensions.Configuration).regis tags: ['experimental'], experiment: { mode: 'auto' }, }, + [DevContainerStateVolumeEnabledSettingId]: { + type: 'boolean', + description: localize('chat.agentHost.devContainer.stateVolume.enabled', "Keep user and agent state of new Dev Containers, including agent sessions and worktrees, on a per-container volume across rebuilds."), + default: false, + scope: ConfigurationScope.APPLICATION, + tags: ['experimental'], + experiment: { mode: 'auto' }, + }, [DevContainerSamplesEnabledSettingId]: { type: 'boolean', description: localize('chat.agentHost.devContainer.samples.enabled', "Show Dev Container samples in the Agents window workspace picker. The sample is cloned into a Docker volume and started when you send the first prompt. Requires Dev Container Agent Host sessions to be enabled."), diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/remotes.contribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/remotes.contribution.ts index 422f4ba45e65..08fedb00390f 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/remotes.contribution.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/electron-browser/remotes.contribution.ts @@ -97,12 +97,13 @@ class RemotesAccessibleView implements IAccessibleViewImplementation { { type: this.type }, () => this.type === AccessibleViewType.Help ? [ localize('remotes.help.overview', "Remote Environments lists known SSH hosts and Dev Tunnels in a table grouped by connection type. Open it with Manage Remote Environments in the Command Palette, from the Sessions section's More Actions menu, from the Remote Connections menu in the title bar, or with Manage Remote Environments in the Environment picker. WSL distributions are also available on Windows. When enabled and available, GitHub Environments lists known user-shared machines, including offline machines. The columns are Name, Status, and Actions. This computer's own Dev Tunnel and GitHub environment are not listed, because this window already runs sessions on this computer."), - ...(showThisComputer ? [localize('remotes.help.thisComputer', "The This Computer section above the Other Environments table shows how this computer is shared with other clients. Its Remote Connections options are Off, GitHub Environments when available, and Dev Tunnels; they match the Remote Connections menu in the title bar. Use Tab to reach the options and the arrow keys to move between them, then press Enter or Space to choose one. Choosing an option starts or stops sharing; the status next to the options announces the result. Rename Sharing Name changes the name other clients see. Local sessions keep running directly on this computer whether sharing is on or off.")] : []), + ...(showThisComputer ? [localize('remotes.help.thisComputer', "The This Computer section above the Other Environments table shows how this computer is shared with other devices. Its Allow Connections Here options are Off, GitHub Environments when available, and Dev Tunnels; they match the Remote Connections menu in the title bar. Use Tab to reach the options and the arrow keys to move between them, then press Enter or Space to choose one. Choosing an option starts or stops sharing; the status next to the options announces the result. Rename Sharing Name changes the name other devices see. Local sessions keep running directly on this computer whether sharing is on or off.")] : []), localize('remotes.help.environments', "For GitHub Environments, Connect is disabled when the owning application is offline. Disconnect retains the environment and follows its existing reconnection preferences. Rename applies only to the current account and profile. Delete asks for confirmation before removing the user-shared environment registration and disconnecting this client. It does not delete files on the machine. The environment can reappear if its owning application registers it again. The GitHub Environments gear opens its settings."), localize('remotes.help.navigation', "Type in Search to filter remotes by name, address, or connection type. Clear Search and Collapse All are at the right of the search field; use Tab to reach these actions and Left and Right Arrow to move between them. Clear Search returns focus to the input. Collapse All preserves the search text. Groups without matches are hidden while searching. Use Down Arrow from Search to enter the table. Use Up and Down Arrow to navigate rows. On a group, use Left and Right Arrow to collapse or expand it, or press Enter to toggle it. Visibility icons are always shown; other row actions appear on hover or keyboard focus. On a remote, press Tab to reach its actions and use Left and Right Arrow to move between Connect or Disconnect and Rename. Use Enter or Space to activate an action. Resize columns by dragging their boundaries. Narrow windows scroll horizontally."), - localize('remotes.help.connection', "Status labels include Connected, Connecting, and Disconnected. A warning indicates that a connection you requested failed. Hover the warning or open the Accessible View to read the error. Automatic connection failures do not create a warning, but automatic retries retain an existing warning until they finish. A failed retry updates the error; a successful retry clears it. GitHub environments whose owning application is not online show Offline. Use Connect or Disconnect to manage the connection. Connection actions are unavailable while connecting or reconnecting. Disconnect follows the existing remote behavior and may remove it from the picker."), + localize('remotes.help.connection', "Status labels include Connected, Connecting, and Disconnected. A warning indicates that a connection you requested failed. Hover the warning or open the Accessible View to read the error. Automatic connection failures do not create a warning, but automatic retries retain an existing warning until they finish. A failed retry updates the error; a successful retry clears it. GitHub environments whose owning application is not online show Host offline. Use Connect or Disconnect to manage the connection. Connection actions are unavailable while connecting or reconnecting. Disconnect follows the existing remote behavior and may remove it from the picker."), localize('remotes.help.visibility', "Use the eye action at the start of an eligible remote row to show or hide it in the Environment and workspace pickers. Focus the row and press Tab, then Enter or Space to toggle it. Hidden remotes remain in this editor with a dimmed name and a Show action. Remotes that cannot currently appear have a disabled unavailable indicator instead of an eye; hover it or open the Accessible View for the reason. Newly discovered remotes must first be connected, and offline shared environments must come online. Your hidden preference is retained while a remote is unavailable. Choosing a folder through a remote subpicker shows that remote again. Hiding a remote does not prevent sending an existing draft when the remote is available and connected. This preference is local to your profile on this machine and does not connect, disconnect, or remove sessions."), localize('remotes.help.manage', "Rename changes the remote's display name in this client. Leave the name empty to restore its default. Copy Address copies a remote's connection address without connecting, including while it is offline or busy. SSH and tunnel rows offer Change Preferred Agent Location, which uses the existing choice of a dedicated process or remote editor window and reconnects after saving. Cancelling leaves the preference unchanged. Incompatible hosts offer Update Server when they advertise an update method. This reports progress and reconnects after the server restarts. Environment and supported tunnel rows also offer Delete with confirmation. Deleting a tunnel removes its service-side registration and disconnects its clients, without deleting remote files. A tunnel currently hosted by this application must be stopped before it can be deleted. A deleted tunnel may reappear if a machine starts hosting it again. Saved SSH connections offer Delete only after discovery confirms the host is absent from SSH configuration. Deleting one asks for confirmation, forgets the saved connection, and disconnects this client without editing SSH configuration or remote files. Use the arrow keys to reach these row actions. WSL distributions must be managed at the source."), + localize('remotes.help.gitHubEnvironment', "When GitHub Environments are enabled and available, connected SSH, WSL, and tunnel rows whose agent host supports it offer Share as GitHub Environment. This toggle registers the remote's agent host as a GitHub environment for your GitHub account, so other applications that support GitHub environments can use it. A shared remote stays listed under its own group instead of GitHub Environments, and its name is followed by a GitHub icon; hover it or open the Accessible View for its state. Sharing continues while this client is disconnected, and is restored when the remote's agent host restarts and this client reconnects. Choose the toggle again to stop sharing, including a remote you shared from another client with the same GitHub account. If another GitHub account or the remote itself already shares it, the toggle is unavailable and the remote's state explains why. Deleting a remote in this editor also stops sharing it."), localize('remotes.help.discovery', "Refresh looks for remotes without connecting. Its icon spins while discovery is running. Each group also shows a spinner after its count while that group's discovery is running. A failed group immediately shows a warning instead of its spinner, even if other groups are still loading. The tooltip and group label explain the problem; the Window log contains diagnostic details. If tunnel sign-in permissions are missing, a Sign In action appears instead of an error. Focus that row and press Tab, then Enter or Space to sign in and grant access to your tunnels. Sign In is disabled with a spinner while sign-in is in progress. This refreshes the list without connecting to a remote. Known locations remain available, and Refresh retries discovery."), localize('remotes.help.setup', "Empty groups show setup guidance and a documentation link. Focus the placeholder row and press Tab to reach its link. Groups with documentation also have an info action that opens the same guide, even when they contain remotes or are collapsed. Focus the group and use Tab and the arrow keys to reach its actions. The SSH settings action opens your user SSH config in a modal editor and creates it if necessary. The Dev Tunnels group has an Open Dev Tunnels Settings action. After configuring a host, return to Remotes and choose Refresh."), ].join('\n\n') : editor.getAccessibilityContent(), diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnostics.fixture.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnostics.fixture.ts index e07fb0518b87..38ed5d4ff875 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnostics.fixture.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnostics.fixture.ts @@ -9,12 +9,14 @@ import { Event } from '../../../../../../base/common/event.js'; import { Disposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; import { IChatEntitlementService } from '../../../../../../workbench/services/chat/common/chatEntitlementService.js'; import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices, waitForFixtureCondition } from '../../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; import { IAgentHostFilterService } from '../../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; import { IConnectionDiagnosticsService, IConnectionDiagnosticsSnapshot, ShowConnectionDiagnosticsCommandId } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/connectionDiagnostics.js'; import { showConnectionDiagnosticsSheet } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/connectionDiagnosticsReport.js'; import { MobileHostFilterActionViewItem } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/mobileHostFilterActionViewItem.js'; +import { MobileHostDrawerHeaderViewItem } from '../../browser/mobileHostDrawerHeaderViewItem.js'; const snapshotContent: Omit = { capturedAt: '2026-09-14T19:00:00.000Z', @@ -194,7 +196,7 @@ async function renderReport(context: ComponentFixtureContext, width: number, exp }, 'Connection diagnostics fixture did not settle its layout'); } -function renderEmptyPicker(context: ComponentFixtureContext): void { +function renderEmptyPicker(context: ComponentFixtureContext, experimentalMobile = false): void { const { container, disposableStore, theme } = context; container.classList.add('monaco-workbench'); container.style.width = '390px'; @@ -225,12 +227,21 @@ function renderEmptyPicker(context: ComponentFixtureContext): void { return undefined as T; } }()); + reg.defineInstance(ILayoutService, new class extends mock() { + override readonly mainContainer = container; + override readonly activeContainer = container; + override readonly onDidLayoutContainer = Event.None; + override getContainer() { return container; } + }()); }, }); - const trigger = dom.append(container, dom.$('div')); - const widget = disposableStore.add(instantiationService.createInstance(MobileHostFilterActionViewItem, disposableStore.add(new Action('hosts', 'Hosts')))); + const trigger = dom.append(container, dom.$(experimentalMobile ? 'div.mobile-sessions-drawer-header' : 'div')); + const action = disposableStore.add(new Action('hosts', 'Hosts')); + const widget = disposableStore.add(experimentalMobile + ? instantiationService.createInstance(MobileHostDrawerHeaderViewItem, action) + : instantiationService.createInstance(MobileHostFilterActionViewItem, action)); widget.render(trigger); - trigger.querySelector('.agent-host-filter-dropdown')!.click(); + trigger.querySelector(experimentalMobile ? '.host-drawer-header-row' : '.agent-host-filter-dropdown')!.click(); } function defineReportFixture(width: number, expandClient = false): ReturnType { @@ -248,4 +259,5 @@ export default defineThemedFixtureGroup({ path: 'sessions/connectionDiagnostics/ ClientExpanded: defineReportFixture(390, true), NarrowClientExpanded: defineReportFixture(320, true), EmptyHostPicker: defineComponentFixture({ render: renderEmptyPicker }), + ExperimentalMobileEmptyHostPicker: defineComponentFixture({ render: context => renderEmptyPicker(context, true) }), }); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnosticsReport.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnosticsReport.test.ts index c08b91b8672c..e029e40b7e00 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnosticsReport.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/connectionDiagnosticsReport.test.ts @@ -9,7 +9,7 @@ import * as dom from '../../../../../../base/browser/dom.js'; import { Gesture, EventType as TouchEventType } from '../../../../../../base/browser/touch.js'; import { ensureCodeWindow, mainWindow } from '../../../../../../base/browser/window.js'; import { Action } from '../../../../../../base/common/actions.js'; -import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { Event } from '../../../../../../base/common/event.js'; @@ -26,9 +26,11 @@ import { IContextKeyService } from '../../../../../../platform/contextkey/common import { Context } from '../../../../../../platform/contextkey/browser/contextKeyService.js'; import { CommandsRegistry, ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IContextMenuService } from '../../../../../../platform/contextview/browser/contextView.js'; +import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../../platform/hover/test/browser/nullHoverService.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -48,6 +50,8 @@ import { ConnectionDiagnosticsContribution } from '../../browser/connectionDiagn import { SessionsChatAccessibilityHelp } from '../../../../chat/browser/sessionsChatAccessibilityHelp.js'; import { HostFilterActionViewItem } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/hostFilterActionViewItem.js'; import { MobileHostFilterActionViewItem } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/mobileHostFilterActionViewItem.js'; +import { MobileHostDrawerHeaderViewItem } from '../../browser/mobileHostDrawerHeaderViewItem.js'; +import { RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; suite('ConnectionDiagnosticsReport', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -724,65 +728,79 @@ suite('ConnectionDiagnosticsReport', () => { assert.deepStrictEqual({ disposeCount, overlays: container.childElementCount }, { disposeCount: 1, overlays: 0 }); }); - for (const hostCount of [0, 1]) { - test(`mobile picker opens information after removing its sheet with ${hostCount} hosts`, () => { - const container = dom.append(mainWindow.document.body, dom.$('div.monaco-workbench')); - store.add(toDisposable(() => container.remove())); - const trigger = dom.append(container, dom.$('div')); - const commands: { id: string; pickerOpen: boolean }[] = []; - class TestMobileHostFilter extends MobileHostFilterActionViewItem { - open(): void { - this._showMenu(new mainWindow.Event('click')); - } - } - const widget = store.add(new TestMobileHostFilter( - store.add(new Action('hosts', 'Hosts')), - new class extends mock() { + for (const experimentalMobile of [false, true]) { + for (const hostCount of [0, 1]) { + test(`${experimentalMobile ? 'experimental mobile' : 'full web responsive'} picker opens information after removing its sheet with ${hostCount} hosts`, async () => { + const container = dom.append(mainWindow.document.body, dom.$('div.monaco-workbench')); + store.add(toDisposable(() => container.remove())); + const trigger = dom.append(container, dom.$('div.mobile-sessions-drawer-header')); + const commands: { id: string; pickerOpen: boolean }[] = []; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IAgentHostFilterService, new class extends mock() { override readonly onDidChange = Event.None; override readonly onDidChangeDiscovering = Event.None; override readonly hosts = hostCount ? [{ id: 'mock', label: 'Mock host', providerIds: ['mock'], grouped: false, address: 'tunnel:mock', icon: Codicon.remote, status: AgentHostFilterConnectionStatus.Connected, connectable: true }] : []; override readonly selectedHost = this.hosts[0]; + override readonly selectedHostId = this.hosts[0]?.id; override readonly isDiscovering = false; - }(), - new class extends mock() { }(), - { ...NullHoverService }, - new class extends mock() { + }()); + instantiationService.stub(ICommandService, new class extends mock() { override async executeCommand(id: string): Promise { - commands.push({ id, pickerOpen: !!container.querySelector('[role="dialog"]') }); + commands.push({ id, pickerOpen: !!container.querySelector('[role="dialog"]:not(.closing)') }); return undefined as T; } - }(), - )); - widget.render(trigger); - widget.open(); - const diagnostics = container.querySelector('.host-picker-sheet-heading .host-picker-sheet-information'); - assert.deepStrictEqual({ - empty: container.querySelector('.host-picker-sheet-empty')?.textContent, - diagnostics: diagnostics?.getAttribute('aria-label'), - inlineInformation: trigger.querySelectorAll('.agent-host-filter-diagnostics').length, - statusAnnounced: trigger.querySelector('.agent-host-filter-dropdown')?.getAttribute('aria-label')?.includes('Current host status: Connected.'), - }, { - empty: hostCount ? undefined : 'No hosts found yet.', - diagnostics: 'Open Connection Information', - inlineInformation: 0, - statusAnnounced: hostCount > 0, + }()); + instantiationService.stub(IConfigurationService, new TestConfigurationService({ [RemoteAgentHostsEnabledSettingId]: true })); + instantiationService.stub(INotificationService, new class extends mock() { }()); + instantiationService.stub(IContextMenuService, new class extends mock() { }()); + instantiationService.stub(IHoverService, { ...NullHoverService }); + instantiationService.stub(ILayoutService, new class extends mock() { + override readonly mainContainer = container; + }()); + const action = store.add(new Action('hosts', 'Hosts')); + const widget = store.add(experimentalMobile + ? instantiationService.createInstance(MobileHostDrawerHeaderViewItem, action) + : instantiationService.createInstance(MobileHostFilterActionViewItem, action)); + widget.render(trigger); + const row = trigger.querySelector(experimentalMobile ? '.host-drawer-header-row' : '.agent-host-filter-dropdown')!; + row.focus(); + row.click(); + const information = () => container.querySelector(experimentalMobile + ? '.host-picker-overlay .mobile-picker-sheet:not(.closing) .mobile-picker-sheet-header-action:not(.mobile-picker-sheet-done)' + : '.host-picker-sheet-information'); + assert.deepStrictEqual({ + hint: !!container.querySelector('.host-picker-hint'), + computers: container.querySelectorAll(experimentalMobile ? '.host-picker-computers [role="menuitemradio"]' : '.host-picker-sheet-item').length, + information: information()?.getAttribute('aria-label'), + title: container.querySelector(experimentalMobile ? '.mobile-picker-sheet-title' : '.host-picker-sheet-title')?.textContent, + empty: container.querySelector('.host-picker-sheet-empty')?.textContent, + }, { + hint: experimentalMobile && hostCount === 0, + computers: hostCount, + information: experimentalMobile ? 'Connection Information' : 'Open Connection Information', + title: experimentalMobile ? 'Where sessions run' : 'Hosts', + empty: !experimentalMobile && hostCount === 0 ? 'No hosts found yet.' : undefined, + }); + information()!.click(); + await Promise.resolve(); + row.click(); + information()!.click(); + // The shell removes a closing sheet after its 180ms slide-down. + await timeout(250); + assert.deepStrictEqual({ + commands, + focusRestored: dom.getActiveElement() === (experimentalMobile ? row : trigger), + sheets: container.querySelectorAll('.host-picker-overlay, .host-picker-sheet-overlay').length, + }, { + commands: [ + { id: ShowConnectionDiagnosticsCommandId, pickerOpen: false }, + { id: ShowConnectionDiagnosticsCommandId, pickerOpen: false }, + ], + focusRestored: true, + sheets: 0, + }); }); - diagnostics!.dispatchEvent(new mainWindow.Event(TouchEventType.Tap, { bubbles: true, cancelable: true })); - widget.open(); - container.querySelector('.host-picker-sheet-information')!.click(); - assert.deepStrictEqual({ - commands, - focusRestored: dom.getActiveElement() === trigger, - sheets: container.querySelectorAll('.host-picker-sheet-overlay').length, - }, { - commands: [ - { id: ShowConnectionDiagnosticsCommandId, pickerOpen: false }, - { id: ShowConnectionDiagnosticsCommandId, pickerOpen: false }, - ], - focusRestored: true, - sheets: 0, - }); - }); + } } for (const verbosity of [true, false]) { diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/hostFilter.contribution.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/hostFilter.contribution.test.ts index e19a1e0be367..ea09411a706e 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/hostFilter.contribution.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/hostFilter.contribution.test.ts @@ -12,8 +12,10 @@ import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; import { MenuWorkbenchToolBar } from '../../../../../../platform/actions/browser/toolbar.js'; -import { IMenuService, MenuId, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; +import { IMenuService, isIMenuItem, MenuId, MenuItemAction, MenuRegistry } 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 { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { ContextMenuHandler } from '../../../../../../platform/contextview/browser/contextMenuHandler.js'; import { IContextMenuService, IContextViewService } from '../../../../../../platform/contextview/browser/contextView.js'; @@ -25,6 +27,7 @@ import { createServices } from '../../../../../../platform/instantiation/test/co import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; import { MockContextKeyService, MockKeybindingService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; @@ -32,11 +35,13 @@ import { Menus } from '../../../../../../workbench/contrib/sessions/browser/menu import { AgentsWindowMenus } from '../../../../../browser/agentsWindowMenus.js'; import { AgentHostFilterConnectionStatus, IAgentHostFilterEntry, IAgentHostFilterService } from '../../../../../../workbench/contrib/sessions/common/agentHostFilter.js'; import { AgentHostFilterContribution } from '../../browser/hostFilter.contribution.js'; +import { MobileAgentHostFilterContribution } from '../../browser/mobileHostFilter.contribution.js'; suite('AgentHostFilterContribution', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); async function createPicker(menuId: MenuId, labels = ['First', 'Second'], status = AgentHostFilterConnectionStatus.Connected) { + const experimentalMobile = menuId === Menus.NewSessionPlace || menuId === Menus.MobileSessionsDrawerHeader; const container = document.body.appendChild(document.createElement('div')); container.classList.add('monaco-workbench'); disposables.add({ dispose: () => container.remove() }); @@ -65,7 +70,8 @@ suite('AgentHostFilterContribution', () => { const descriptor = getSingletonServiceDescriptors().find(([id]) => id === IActionViewItemService)?.[1]; assert.ok(descriptor); const action = upcastPartial({ - id: 'sessions.agentHostFilter.pick', label: 'Select Agent Host', enabled: true, run: async () => { }, + id: experimentalMobile ? 'sessions.mobile.agentHostFilter.pick' : 'sessions.agentHostFilter.pick', + label: 'Select Agent Host', enabled: true, run: async () => { }, }); const instantiationService = createServices(disposables.add(new DisposableStore()), [ [IActionViewItemService, descriptor.ctor], @@ -76,6 +82,8 @@ suite('AgentHostFilterContribution', () => { [IHoverService, NullHoverService], [ITelemetryService, NullTelemetryService], [ICommandService, upcastPartial({})], + [IConfigurationService, new TestConfigurationService()], + [INotificationService, new TestNotificationService()], [ILayoutService, upcastPartial({ mainContainer: container, activeContainer: container, getContainer: () => container, onDidLayoutContainer: Event.None, @@ -98,10 +106,14 @@ suite('AgentHostFilterContribution', () => { }, }); disposables.add(instantiationService.createInstance(MenuWorkbenchToolBar, container, menuId, undefined)); - assert.strictEqual(container.querySelector('.agent-host-filter-combo'), null); - disposables.add(instantiationService.createInstance(AgentHostFilterContribution)); + const customSelector = menuId === Menus.NewSessionPlace ? '.sessions-new-session-place' + : menuId === Menus.MobileSessionsDrawerHeader ? '.host-drawer-header' : '.agent-host-filter-combo'; + assert.strictEqual(container.querySelector(customSelector), null); + disposables.add(experimentalMobile + ? instantiationService.createInstance(MobileAgentHostFilterContribution) + : instantiationService.createInstance(AgentHostFilterContribution)); await Promise.resolve(); - assert.ok(container.querySelector('.agent-host-filter-combo'), 'cold-start registration replaces the default action view item'); + assert.ok(container.querySelector(customSelector), 'cold-start registration replaces the default action view item'); disposables.add({ dispose: () => contextView.hideContextView() }); return { container, contextView, filterService, operations, getMenuActions: () => menuActions, @@ -153,6 +165,19 @@ suite('AgentHostFilterContribution', () => { assert.deepStrictEqual({ selected: filterService.selectedHostId, operations }, { selected: 'First', operations: ['rediscover'] }); }); + test('full and experimental mobile contributions use separate menu placements', () => { + const menus = [Menus.SidebarAgentHost, AgentsWindowMenus.MobileTitleBarCenter, Menus.MobileSessionsDrawerHeader, Menus.NewSessionPlace]; + assert.deepStrictEqual(menus.map(menu => MenuRegistry.getMenuItems(menu) + .filter(isIMenuItem) + .map(item => item.command.id) + .filter(id => id === 'sessions.agentHostFilter.pick' || id === 'sessions.mobile.agentHostFilter.pick')), [ + ['sessions.agentHostFilter.pick'], + ['sessions.agentHostFilter.pick'], + ['sessions.mobile.agentHostFilter.pick'], + ['sessions.mobile.agentHostFilter.pick'], + ]); + }); + test('sidebar menu survives host and discovery updates and still selects a host', async () => { const { container, contextView, filterService, updateStatus, setDiscovering } = await createPicker(Menus.SidebarAgentHost); const button = container.querySelector('.agent-host-filter-button'); @@ -181,79 +206,125 @@ suite('AgentHostFilterContribution', () => { assert.strictEqual(filterService.selectedHostId, 'Second'); }); - test('mobile sheet survives host and discovery updates with live status', async () => { - const { container, updateStatus, setDiscovering } = await createPicker(AgentsWindowMenus.MobileTitleBarCenter); - const button = container.querySelector('.agent-host-filter-dropdown'); - assert.ok(button); - button.click(); - const sheet = container.querySelector('.host-picker-sheet'); - assert.ok(sheet); - assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); - - updateStatus(); - setDiscovering(true); - assert.deepStrictEqual({ - sameButton: container.querySelector('.agent-host-filter-dropdown') === button, - sameSheet: container.querySelector('.host-picker-sheet') === sheet, - connected: sheet.isConnected, - discovering: button.classList.contains('discovering'), - hasConnectingStatus: sheet.textContent?.includes('Connecting'), - selectedHostFocused: document.activeElement === sheet.querySelector('[aria-checked="true"]'), - }, { sameButton: true, sameSheet: true, connected: true, discovering: true, hasConnectingStatus: true, selectedHostFocused: true }); - setDiscovering(false); - assert.ok(sheet.isConnected); - assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); - }); + for (const { name, menu, triggerSelector, sheetSelector, refreshSelector, controls } of [ + { + name: 'full web responsive picker', + menu: AgentsWindowMenus.MobileTitleBarCenter, + triggerSelector: '.agent-host-filter-dropdown', + sheetSelector: '.host-picker-sheet', + refreshSelector: '.host-picker-sheet-action', + controls: ['.host-picker-sheet-action', '.host-picker-sheet-information', '.host-picker-sheet-close:not(.host-picker-sheet-information)'], + }, + { + name: 'experimental mobile place picker', + menu: Menus.NewSessionPlace, + triggerSelector: '.sessions-new-session-place-trigger', + sheetSelector: '.host-picker-overlay .mobile-picker-sheet', + refreshSelector: '.host-picker-section-action', + controls: ['.host-picker-section-action', '.mobile-picker-sheet-header-action:not(.mobile-picker-sheet-done)', '.mobile-picker-sheet-done'], + }, + { + name: 'experimental mobile drawer picker', + menu: Menus.MobileSessionsDrawerHeader, + triggerSelector: '.host-drawer-header-row', + sheetSelector: '.host-picker-overlay .mobile-picker-sheet', + refreshSelector: '.host-picker-section-action', + controls: ['.host-picker-section-action', '.mobile-picker-sheet-header-action:not(.mobile-picker-sheet-done)', '.mobile-picker-sheet-done'], + }, + ]) { + test(`${name} survives host and discovery updates with live status`, async () => { + const { container, updateStatus, setDiscovering } = await createPicker(menu); + const button = container.querySelector(triggerSelector); + assert.ok(button); + button.click(); + const sheet = container.querySelector(sheetSelector); + assert.ok(sheet); + assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); - test('mobile updates preserve the focused unselected host without stealing focus from other controls', async () => { - const { container, updateStatus, setDiscovering } = await createPicker(AgentsWindowMenus.MobileTitleBarCenter); - const button = container.querySelector('.agent-host-filter-dropdown'); - assert.ok(button); - button.click(); - const sheet = container.querySelector('.host-picker-sheet'); - assert.ok(sheet); - const secondHost = () => { - const row = sheet.querySelector('[aria-checked="false"]'); - assert.ok(row); - return row; - }; - secondHost().focus(); - updateStatus(); - assert.strictEqual(document.activeElement, secondHost()); - setDiscovering(true); - assert.strictEqual(document.activeElement, secondHost()); - setDiscovering(false); - assert.strictEqual(document.activeElement, secondHost()); + updateStatus(); + setDiscovering(true); + assert.deepStrictEqual({ + sameButton: container.querySelector(triggerSelector) === button, + sameSheet: container.querySelector(sheetSelector) === sheet, + connected: sheet.isConnected, + hasConnectingStatus: sheet.textContent?.includes('Connecting'), + selectedHostFocused: document.activeElement === sheet.querySelector('[aria-checked="true"]'), + }, { sameButton: true, sameSheet: true, connected: true, hasConnectingStatus: true, selectedHostFocused: true }); + setDiscovering(false); + assert.ok(sheet.isConnected); + assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); + }); - for (const selector of ['.host-picker-sheet-action', '.host-picker-sheet-information', '.host-picker-sheet-close:not(.host-picker-sheet-information)']) { - const control: HTMLElement | null = sheet.querySelector(selector); - assert.ok(control); - control.focus(); + test(`${name} preserves focus across host and discovery updates`, async () => { + const { container, updateStatus, setDiscovering } = await createPicker(menu); + const button = container.querySelector(triggerSelector); + assert.ok(button); + button.click(); + const sheet = container.querySelector(sheetSelector); + assert.ok(sheet); + const secondHost = () => { + const row = sheet.querySelector('[aria-checked="false"]'); + assert.ok(row); + return row; + }; + secondHost().focus(); updateStatus(); + assert.strictEqual(document.activeElement, secondHost()); setDiscovering(true); + assert.strictEqual(document.activeElement, secondHost()); setDiscovering(false); - assert.strictEqual(document.activeElement, control); - } + assert.strictEqual(document.activeElement, secondHost()); - const outside = container.appendChild(document.createElement('button')); - outside.focus(); - updateStatus(); - assert.strictEqual(document.activeElement, outside); - }); + for (const selector of controls) { + const control: HTMLElement | null = sheet.querySelector(selector); + assert.ok(control); + control.focus(); + updateStatus(); + setDiscovering(true); + setDiscovering(false); + assert.strictEqual(document.activeElement, control); + } - test('mobile focus falls back inside the sheet when the focused host disappears', async () => { - const { container, removeHost } = await createPicker(AgentsWindowMenus.MobileTitleBarCenter); - const button = container.querySelector('.agent-host-filter-dropdown'); - assert.ok(button); - button.click(); - const sheet = container.querySelector('.host-picker-sheet'); - assert.ok(sheet); - const secondHost = sheet.querySelector('[aria-checked="false"]'); - assert.ok(secondHost); - secondHost.focus(); - removeHost('Second'); - assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); - removeHost('First'); - assert.strictEqual(document.activeElement, sheet.querySelector('.host-picker-sheet-action')); + const outside = container.appendChild(document.createElement('button')); + outside.focus(); + updateStatus(); + assert.strictEqual(document.activeElement, outside); + }); + + test(`${name} keeps focus inside when the focused host disappears`, async () => { + const { container, removeHost } = await createPicker(menu); + const button = container.querySelector(triggerSelector); + assert.ok(button); + button.click(); + const sheet = container.querySelector(sheetSelector); + assert.ok(sheet); + const secondHost = sheet.querySelector('[aria-checked="false"]'); + assert.ok(secondHost); + secondHost.focus(); + removeHost('Second'); + assert.strictEqual(document.activeElement, sheet.querySelector('[aria-checked="true"]')); + removeHost('First'); + assert.strictEqual(document.activeElement, sheet.querySelector(refreshSelector)); + }); + + test(`${name} selects the same shared host`, async () => { + const { container, filterService } = await createPicker(menu); + container.querySelector(triggerSelector)!.click(); + container.querySelector(`${sheetSelector} [aria-checked="false"]`)!.click(); + assert.strictEqual(filterService.selectedHostId, 'Second'); + }); + } + + test('experimental place chip keeps its entry icon without a status badge', async () => { + const { container, updateStatus } = await createPicker(Menus.NewSessionPlace); + updateStatus(); + const icon = container.querySelector('.sessions-new-session-place-icon')!; + assert.deepStrictEqual({ + glyphs: Array.from(icon.children, element => element.className), + statusBadge: container.querySelector('.sessions-new-session-place-status'), + }, { + glyphs: ['codicon codicon-vm'], + statusBadge: null, + }); }); }); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/missionControlAgentHostContribution.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/missionControlAgentHostContribution.test.ts index eaa0675981ba..7f21c25a5529 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/missionControlAgentHostContribution.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/missionControlAgentHostContribution.test.ts @@ -8,12 +8,12 @@ import { DeferredPromise } from '../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { CancellationError } from '../../../../../../base/common/errors.js'; import { Disposable, DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; -import { autorun, observableSignalFromEvent, observableValue } from '../../../../../../base/common/observable.js'; +import { autorun, derived, IObservable, observableSignalFromEvent, observableValue, transaction } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { isIMenuItem, MenuId, MenuRegistry } from '../../../../../../platform/actions/common/actions.js'; -import { GitHubEnvironmentsAvailableContext, GitHubEnvironmentsEnabledSettingId, IMissionControlEnvironmentService, IMissionControlHost, IMissionControlSharingService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { GitHubEnvironmentsAvailableContext, GitHubEnvironmentsEnabledSettingId, IMissionControlEnvironmentService, IMissionControlHost, IMissionControlSharingService, IRemoteGitHubEnvironmentSharingService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { IAgentConnection, IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; import { AgentHostConnectionsService } from '../../../../../../platform/agentHost/browser/agentHostConnectionsService.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; @@ -25,6 +25,7 @@ import { TestConfigurationService } from '../../../../../../platform/configurati import { Context } from '../../../../../../platform/contextkey/browser/contextKeyService.js'; import { IsDevelopmentContext, ProductQualityContext } from '../../../../../../platform/contextkey/common/contextkeys.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../../platform/label/common/label.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; @@ -121,11 +122,16 @@ suite('Mission Control native provider inventory', () => { storage?: InMemoryStorageService; connect?: () => Promise; refresh?: () => Promise; + discoveredOnlineHostIds?: IObservable>; sharedStartupFirst?: boolean; } = {}) { const instantiation = store.add(new TestInstantiationService()); const hosts = observableValue('hosts', []); const ownEnvironmentId = observableValue('ownEnvironmentId', undefined); + const sharedRemoteEnvironmentIds = observableValue>('sharedRemoteEnvironmentIds', new Set()); + instantiation.stub(IRemoteGitHubEnvironmentSharingService, new class extends mock() { + override readonly environmentIds = sharedRemoteEnvironmentIds; + }()); let account = 'first'; const created: { provider: TestProvider; options: IEntryDrivenProviderOptions }[] = []; const actions: string[] = []; @@ -193,7 +199,7 @@ suite('Mission Control native provider inventory', () => { upcastPartial({ onAgentHostStart: Event.None, onAgentHostExit: Event.None }), instantiation.get(IRemoteAgentHostService), upcastPartial({ registerPathProvider: () => Disposable.None }), - new NullLogService(), + upcastPartial({ registerFormatter: () => Disposable.None }), )); instantiation.stub(IAgentHostConnectionsService, resolutionService); instantiation.stub(INotificationService, new TestNotificationService()); @@ -207,6 +213,8 @@ suite('Mission Control native provider inventory', () => { }()); instantiation.stub(IMissionControlEnvironmentService, new class extends mock() { override readonly hosts = hosts; + override readonly discoveredOnlineHostIds = options.discoveredOnlineHostIds ?? derived(this, reader => + new Set(hosts.read(reader).filter(host => host.status === 'online').map(host => host.id))); override readonly ownEnvironmentId = ownEnvironmentId; override readonly enabled = true; override get accountKey() { return account; } @@ -239,7 +247,7 @@ suite('Mission Control native provider inventory', () => { } })); return { - hosts, ownEnvironmentId, created, actions, contribution, configuration, sharedProjects, recentQueries, providerChanges, providersService, resolutionService, rediscover, sharedStartup, setConnectionStatus, + hosts, ownEnvironmentId, sharedRemoteEnvironmentIds, created, actions, contribution, configuration, sharedProjects, recentQueries, providerChanges, providersService, resolutionService, rediscover, sharedStartup, setConnectionStatus, whenConnected: (id: string) => { const isConnected = () => RemoteAgentHostConnectionStatus.isConnected(connections.get(`cloudsandbox:${id}`)?.status); return isConnected() ? Promise.resolve() : Event.toPromise(Event.filter(connectionsChanged.event, isConnected), connectionListeners); @@ -299,11 +307,13 @@ suite('Mission Control native provider inventory', () => { }); } - test('marks this computer\'s environment as its local registration and keeps it out of the picker and auto-connect', async () => { - const { hosts, ownEnvironmentId, created, actions, rediscover } = fixture('profile', { web: true }); + test('keeps this computer\'s environment and remotes shared by this client out of the picker and auto-connect', async () => { + const { hosts, ownEnvironmentId, sharedRemoteEnvironmentIds, created, actions, rediscover } = fixture('profile', { web: true }); ownEnvironmentId.set('own', undefined); + sharedRemoteEnvironmentIds.set(new Set(['shared']), undefined); hosts.set([ { id: 'own', name: 'This Machine', kind: 'user-local', status: 'online' }, + { id: 'shared', name: 'Shared SSH Host', kind: 'user-local', status: 'online' }, { id: 'other', name: 'Other Machine', kind: 'user-local', status: 'online' }, ], undefined); await rediscover(); @@ -317,6 +327,7 @@ suite('Mission Control native provider inventory', () => { }, { providers: [ { address: 'cloudsandbox:own', localRegistration: 'githubEnvironment', pickerVisible: false }, + { address: 'cloudsandbox:shared', localRegistration: undefined, pickerVisible: false }, { address: 'cloudsandbox:other', localRegistration: undefined, pickerVisible: true }, ], connects: ['connect:other'], @@ -453,6 +464,60 @@ suite('Mission Control native provider inventory', () => { }); }); + for (const web of [false, true]) { + for (const outcome of ['online', 'offline', 'failure'] as const) { + test(`cached online hosts wait for fresh ${outcome} discovery on ${web ? 'web' : 'desktop'}`, async () => { + const storage = store.add(new InMemoryStorageService()); + const first = fixture('profile', { storage, autoConnect: false }); + const host: IMissionControlHost = { id: 'environment', name: 'Machine', kind: 'user-local', status: 'online' }; + first.hosts.set([host], undefined); + await first.created[0].provider.connect(); + first.contribution.dispose(); + + const discovery = new DeferredPromise(); + const discoveredOnlineHostIds = observableValue>('discoveredOnlineHostIds', new Set()); + const reopened = fixture('profile', { + storage, web, discoveredOnlineHostIds, + refresh: async () => { + await discovery.p; + if (outcome === 'failure') { + throw new Error('Discovery unavailable'); + } + transaction(tx => { + reopened.hosts.set([{ ...host, status: outcome }], tx); + discoveredOnlineHostIds.set(new Set(outcome === 'online' ? [host.id] : []), tx); + }); + }, + }); + reopened.hosts.set([host], undefined); + const beforeDiscovery = { + providers: reopened.created.length, + connects: reopened.actions.filter(action => action.startsWith('connect:')), + }; + const refresh = reopened.rediscover(); + await discovery.complete(); + const refreshed = await refresh; + const automaticConnects = reopened.actions.filter(action => action.startsWith('connect:')); + if (outcome === 'failure') { + await reopened.created[0].provider.connect(); + } + assert.deepStrictEqual({ + beforeDiscovery, refreshed, automaticConnects, + status: reopened.hosts.get()[0].status, + connects: reopened.actions.filter(action => action.startsWith('connect:')), + disposed: reopened.created[0].provider.disposed, + }, { + beforeDiscovery: { providers: 1, connects: [] }, + refreshed: outcome !== 'failure', + automaticConnects: outcome === 'online' ? ['connect:environment'] : [], + status: outcome === 'offline' ? 'offline' : 'online', + connects: outcome === 'offline' ? [] : ['connect:environment'], + disposed: false, + }); + }); + } + } + test('desktop waits for remembered hosts to come online and respects the auto-connect setting', async () => { const storage = store.add(new InMemoryStorageService()); const first = fixture('profile', { storage }); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileAgentHostFilterService.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileAgentHostFilterService.test.ts new file mode 100644 index 000000000000..d19c6dadb9b7 --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileAgentHostFilterService.test.ts @@ -0,0 +1,75 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Codicon } from '../../../../../../base/common/codicons.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { constObservable } from '../../../../../../base/common/observable.js'; +import { isWeb } from '../../../../../../base/common/platform.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { InMemoryStorageService, IStorageService } from '../../../../../../platform/storage/common/storage.js'; +import { IAgentHostSessionsProvider } from '../../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; +import { AgentHostFilterService } from '../../../../../../workbench/contrib/sessions/browser/agentHostFilterService.js'; +import { ISessionsProvidersChangeEvent, ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { MobileAgentHostFilterService } from '../../browser/mobileAgentHostFilterService.js'; + +suite('MobileAgentHostFilterService isolation', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const cloud = { id: 'githubsandbox', label: 'GitHub Sandboxes', connectable: false, sessionCreationProviderId: 'cloud-creation', order: 1 }; + + function create(mobile: boolean) { + const changed = store.add(new Emitter()); + const providers = [upcastPartial({ + id: 'agenthost-computer', label: 'Computer', icon: Codicon.remote, + remoteAddress: 'tunnel:computer', + connectionStatus: constObservable(RemoteAgentHostConnectionStatus.connected), + })]; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ISessionsProvidersService, upcastPartial({ + onDidChangeProviders: changed.event, getProviders: () => providers, + getProvider: () => undefined, + })); + instantiationService.stub(IRemoteAgentHostService, upcastPartial({ + onDidChangeConfiguredEntries: Event.None, configuredEntries: [], + })); + const configuration = new TestConfigurationService({ [RemoteAgentHostsEnabledSettingId]: true }); + store.add(configuration.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configuration); + instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); + return store.add(mobile + ? instantiationService.createInstance(MobileAgentHostFilterService) + : instantiationService.createInstance(AgentHostFilterService)); + } + + for (const mobile of [false, true]) { + test(`${mobile ? 'mobile' : 'full'} default and label stay entry-specific after delayed Cloud discovery`, () => { + const service = create(mobile); + const before = service.selectedHostId; + const registration = store.add(service.registerHostGroup(cloud)); + const after = service.selectedHostId; + const entry = service.hosts.find(host => host.id === cloud.id)!; + registration.dispose(); + assert.deepStrictEqual({ before, after, removed: service.selectedHostId, label: entry.label, description: entry.description }, { + before: isWeb ? 'agenthost-computer' : undefined, + after: isWeb ? mobile ? cloud.id : 'agenthost-computer' : undefined, + removed: isWeb ? 'agenthost-computer' : undefined, + label: mobile ? 'Cloud' : 'GitHub Sandboxes', + description: mobile ? 'GitHub Sandboxes' : undefined, + }); + }); + + test(`${mobile ? 'mobile' : 'full'} preserves an explicit computer selection`, () => { + const service = create(mobile); + service.setSelectedHostId('agenthost-computer'); + store.add(service.registerHostGroup(cloud)); + assert.strictEqual(service.selectedHostId, isWeb ? 'agenthost-computer' : undefined); + }); + } +}); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileHostPickerStyles.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileHostPickerStyles.test.ts new file mode 100644 index 000000000000..5704839bed6c --- /dev/null +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/mobileHostPickerStyles.test.ts @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../../../../browser/media/style.css'; +import '../../browser/media/mobileHostPickerSheet.css'; +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'; + +suite('MobileHostPicker Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('selected rows preserve their selected palette while hovered', () => { + const results = ['vs', 'vs-dark', 'hc-black', 'hc-light'].map(theme => { + const root = append(mainWindow.document.body, $(`.monaco-workbench.agent-sessions-workbench.${theme}`)); + root.style.setProperty('--vscode-list-hoverBackground', '#f0f0f0'); + root.style.setProperty('--vscode-list-activeSelectionBackground', '#0060c0'); + root.style.setProperty('--vscode-list-activeSelectionForeground', '#ffffff'); + root.style.setProperty('--vscode-contrastActiveBorder', theme.startsWith('hc-') ? '#f38518' : 'transparent'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + store.add(toDisposable(() => root.remove())); + const row = append(root, $('button.host-picker-row.agent-sessions-interactive.agent-sessions-interactive-list.checked.hovered', { 'aria-checked': 'true' })); + const style = mainWindow.getComputedStyle(row); + return { + background: style.backgroundColor, + foreground: style.color, + }; + }); + + assert.deepStrictEqual(results, [ + { background: 'rgb(0, 96, 192)', foreground: 'rgb(255, 255, 255)' }, + { background: 'rgb(0, 96, 192)', foreground: 'rgb(255, 255, 255)' }, + { background: 'rgb(0, 96, 192)', foreground: 'rgb(255, 255, 255)' }, + { background: 'rgb(0, 96, 192)', foreground: 'rgb(255, 255, 255)' }, + ]); + }); +}); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHost.contribution.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHost.contribution.test.ts index c39d7722c691..eacff0ecb679 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHost.contribution.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHost.contribution.test.ts @@ -58,7 +58,7 @@ interface IRemoteAuthNotificationHarness { _instantiationService: TestInstantiationService; _connectionCustomizations: { get(address: string): IRemoteAgentHostConnectionCustomization | undefined }; _logService: NullLogService; - _handleAuthenticationRequiredNotification(address: string, connection: Pick, notification: INotification): void; + _handleAuthenticationRequiredNotification(address: string, connection: Pick, notification: INotification): void; _authenticateCallback(address: string, connection: Pick, reason?: AuthRequiredReason): IAgentConnection['authenticate']; } @@ -415,6 +415,7 @@ suite('RemoteAgentHost auth notifications', () => { instantiationService.stub(ILogService, logService); const authenticateCalls: Parameters[0][] = []; const connection = { + rootState: upcastPartial>({ value: { agents: [] } }), authenticate: async (params: Parameters[0]) => { authenticateCalls.push(params); return { authenticated: true }; @@ -477,8 +478,9 @@ suite('RemoteAgentHost auth notifications', () => { }; const notification: INotification = { type: NotificationType.AuthRequired, channel: 'ahp-root://', resource, reason: AuthRequiredReason.Required }; - contribution._handleAuthenticationRequiredNotification('host-one', { authenticate: async request => { calls.push(`one:${request.token}`); return { authenticated: true }; } }, notification); - contribution._handleAuthenticationRequiredNotification('host-two', { authenticate: async request => { calls.push(`two:${request.token}`); return { authenticated: true }; } }, notification); + const rootState = upcastPartial>({ value: { agents: [] } }); + contribution._handleAuthenticationRequiredNotification('host-one', { rootState, authenticate: async request => { calls.push(`one:${request.token}`); return { authenticated: true }; } }, notification); + contribution._handleAuthenticationRequiredNotification('host-two', { rootState, authenticate: async request => { calls.push(`two:${request.token}`); return { authenticated: true }; } }, notification); await timeout(0); assert.deepStrictEqual(calls, ['one:session-token', 'two:session-token']); @@ -520,7 +522,10 @@ suite('RemoteAgentHost auth notifications', () => { scopes_supported: ['session:read'], }; const notification: INotification = { type: NotificationType.AuthRequired, channel: 'ahp-root://', resource, reason: AuthRequiredReason.Expired }; - const connection: Pick = { authenticate: async request => { envelopes.push(request.token); return { authenticated: true }; } }; + const connection: Pick = { + rootState: upcastPartial>({ value: { agents: [] } }), + authenticate: async request => { envelopes.push(request.token); return { authenticated: true }; }, + }; contribution._handleAuthenticationRequiredNotification(address, connection, notification); await timeout(0); 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 94bb7ae379f9..d87c5d3a8d88 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 @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { Event } from '../../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; import { observableValue } from '../../../../../../base/common/observable.js'; import { OS } from '../../../../../../base/common/platform.js'; import { DeferredPromise } from '../../../../../../base/common/async.js'; @@ -16,7 +16,7 @@ import { toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { GitHubEnvironmentsAvailableContext, GitHubEnvironmentsEnabledSettingId } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; -import { ISSHRemoteAgentHostService, SSHAuthMethod, type ISSHAgentHostConfig } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { ISSHRemoteAgentHostService, SSHAuthMethod, type ISSHAgentHostConfig, type SSHAgentHostConnectionRequest } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../../platform/contextkey/browser/contextKeyService.js'; @@ -46,7 +46,7 @@ import { Menus } from '../../../../../../workbench/contrib/sessions/browser/menu import '../../browser/missionControlAgentHost.contribution.js'; import { getSessionCreationEnvironments } from '../../../../../../workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.js'; import { IWSLRemoteAgentHostService } from '../../../../../../platform/agentHost/common/wslRemoteAgentHost.js'; -import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; +import { IQuickInputService, QuickInputHideReason, type IQuickPick, type IQuickPickItem } from '../../../../../../platform/quickinput/common/quickInput.js'; import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; @@ -247,6 +247,46 @@ suite('Remote Agent Host actions', () => { }); } + test('configured SSH selection does not turn preflight settings into explicit connection overrides', async () => { + const instantiation = store.add(new TestInstantiationService()); + const accepted = store.add(new Emitter()); + const hidden = store.add(new Emitter()); + const requests: SSHAgentHostConnectionRequest[] = []; + instantiation.stub(IInstantiationService, instantiation); + instantiation.stub(ICommandService, {}); + instantiation.stub(INotificationService, new TestNotificationService()); + instantiation.stub(ITelemetryService, NullTelemetryService); + instantiation.stub(IRemoteAgentHostService, { connections: [] }); + instantiation.stub(IQuickInputService, { + createQuickPick: () => new class extends mock>() { + override items: readonly T[] = []; + override get selectedItems(): readonly T[] { return this.items.slice(0, 1); } + override readonly onDidChangeValue = Event.None; + override readonly onDidTriggerButton = Event.None; + override readonly onDidAccept = Event.map(accepted.event, () => ({ inBackground: false })); + override readonly onDidHide = Event.map(hidden.event, () => ({ reason: QuickInputHideReason.Gesture })); + override show(): void { accepted.fire(); } + override hide(): void { hidden.fire(); } + override dispose(): void { } + }(), + }); + instantiation.stub(ISSHRemoteAgentHostService, { + listSSHConfigHosts: async () => ['myalias'], + resolveSSHConfig: async () => ({ + hostname: 'old-target', user: 'old-user', port: 2222, identityFile: ['/old/key'], + identityAgent: '/old/agent', forwardAgent: true, userKnownHostsFiles: [], globalKnownHostsFiles: [], + strictHostKeyChecking: undefined, + }), + onDidReportConnectProgress: Event.None, + connect: async request => { + requests.push(request); + throw new CancellationError(); + }, + }); + await instantiation.invokeFunction(accessor => CommandsRegistry.getCommand(RemoteAgentHostCommandIds.connectViaSSH)!.handler(accessor)); + assert.deepStrictEqual(requests, [{ sshConfigHost: 'myalias', name: 'myalias' }]); + }); + test('reuses an existing SSH connection when reopening the folder picker', async () => { const instantiationService = store.add(new TestInstantiationService()); let connectCalls = 0; diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts index 80f5f813aaa1..7bc8fd7e3bf6 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostSessionsProvider.test.ts @@ -4573,7 +4573,7 @@ suite('RemoteAgentHostSessionsProvider', () => { upcastPartial({ onAgentHostStart: Event.None, onAgentHostExit: Event.None }), new NullRemoteAgentHostService(), upcastPartial({ registerPathProvider: () => Disposable.None }), - new NullLogService(), + upcastPartial({ registerFormatter: () => Disposable.None }), )); let notifications = 0; disposables.add(resolutions.onDidChangeSessionResolution(() => notifications++)); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteWorkspaceHandoffService.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteWorkspaceHandoffService.test.ts index 0bb0e1622525..fc37268643dc 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteWorkspaceHandoffService.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteWorkspaceHandoffService.test.ts @@ -14,7 +14,9 @@ import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { agentHostAuthority, fromAgentHostUri } from '../../../../../../platform/agentHost/common/agentHostUri.js'; import { getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, readSSHRemoteAgentHostEntries, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; -import { ISSHRemoteAgentHostService, ISSHResolvedConfig } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { RemoteAgentHostLocationPreferenceService } from '../../../../../../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; +import { ISSHAgentHostConnection, ISSHRemoteAgentHostService, ISSHResolvedConfig } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ICachedTunnel, ITunnelAgentHostService, ITunnelInfo, TunnelAuthenticationRequiredError, TunnelGatewayServerType } from '../../../../../../platform/agentHost/common/tunnelAgentHost.js'; import { IWSLCachedDistro, IWSLRemoteAgentHostService } from '../../../../../../platform/agentHost/common/wslRemoteAgentHost.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; @@ -39,6 +41,7 @@ suite('RemoteWorkspaceHandoffService', () => { function createHarness(options: { readonly entries?: readonly IRemoteAgentHostEntry[]; + readonly sshConnections?: readonly ISSHAgentHostConnection[]; readonly enabled?: boolean; readonly distros?: readonly string[]; readonly defaultDistro?: string; @@ -63,6 +66,7 @@ suite('RemoteWorkspaceHandoffService', () => { instantiationService.stub(IConfigurationService, new TestConfigurationService({ [RemoteAgentHostsEnabledSettingId]: options.enabled ?? true })); instantiationService.stub(IRemoteAgentHostService, upcastPartial({ configuredEntries: options.entries ?? [] })); instantiationService.stub(ISSHRemoteAgentHostService, upcastPartial({ + connections: options.sshConnections ?? [], resolveSSHConfig: async host => { await options.lookupGate; return upcastPartial({ hostname: `${host}.example.com`, user: 'resolved-user', port: 2222 }); @@ -95,6 +99,8 @@ suite('RemoteWorkspaceHandoffService', () => { getProviders: () => providers, onDidChangeProviders: providersChanged.event, })); + const locationPreferences = disposables.add(new RemoteAgentHostLocationPreferenceService(storage)); + instantiationService.stub(IRemoteAgentHostLocationPreferenceService, locationPreferences); instantiationService.stub(IStorageService, storage); instantiationService.stub(IProgressService, upcastPartial({ withProgress: (_options, task) => task(upcastPartial({ report: () => { } })) })); instantiationService.stub(INotificationService, upcastPartial({ error: message => { errors.push(String(message)); } })); @@ -109,7 +115,7 @@ suite('RemoteWorkspaceHandoffService', () => { instantiationService.stub(ILogService, new NullLogService()); const service = disposables.add(instantiationService.createInstance(RemoteWorkspaceHandoffService)); return { - service, storage, calls, errors, dialogs, + service, storage, calls, errors, dialogs, locationPreferences, addProvider: (address: string, connect: (status: ISettableObservable) => Promise, initialStatus: RemoteAgentHostConnectionStatus = RemoteAgentHostConnectionStatus.disconnected) => { const status = observableValue('status', initialStatus); const provider = upcastPartial({ @@ -148,6 +154,7 @@ suite('RemoteWorkspaceHandoffService', () => { 'wsl+ubuntu@tunnel+surface', 'wsl+ubuntu%40tunnel+surface', 'tunnel+my-tunnel', + 'dev-container+2f736f75726365', 'codespaces+name', 'ssh-remote+', ].map(parseRemoteMachine), [ @@ -165,6 +172,7 @@ suite('RemoteWorkspaceHandoffService', () => { { kind: 'tunnel', name: 'my-tunnel' }, undefined, undefined, + undefined, ]); }); @@ -408,27 +416,45 @@ suite('RemoteWorkspaceHandoffService', () => { }); }); - test('shares the editor windows\' agent host only with tunnels whose gateway did not select an editor\'s agent host', async () => { + test('shares remote editor hosts unless an editor-owned endpoint lacks a matching preference', async () => { const tunnelEntry = (label: string): IRemoteAgentHostEntry => ({ name: label, connection: { type: RemoteAgentHostEntryType.Tunnel, tunnelId: `${label}-id`, clusterId: 'usw2', label } }); - const ssh: IRemoteAgentHostEntry = { name: 'myhost', connection: { type: RemoteAgentHostEntryType.SSH, address: 'ssh:myhost', sshConfigHost: 'myhost', hostName: 'myhost.example.com' } }; + const sshEntry = (host: string): IRemoteAgentHostEntry => ({ name: host, connection: { type: RemoteAgentHostEntryType.SSH, address: `ssh:${host}`, sshConfigHost: host, hostName: `${host}.example.com` } }); + const [sshStandalone, sshEditor, sshLegacy] = ['standalone', 'editor', 'legacy'].map(sshEntry); + const wsl: IRemoteAgentHostEntry = { name: 'Ubuntu', connection: { type: RemoteAgentHostEntryType.WSL, address: 'wsl:Ubuntu', distro: 'Ubuntu' } }; const [standalone, editor, protocolV5, unselected] = ['standalone', 'editor', 'v5', 'unselected'].map(tunnelEntry); + const entries = [sshStandalone, sshEditor, sshLegacy, wsl, standalone, editor, protocolV5, unselected]; + const sshConnections: ISSHAgentHostConnection[] = []; const harness = createHarness({ - entries: [ssh, standalone, editor, protocolV5, unselected], + entries, + sshConnections, selectedServerTypes: { [getEntryAddress(standalone)]: 'standalone', [getEntryAddress(editor)]: 'editor', [getEntryAddress(protocolV5)]: 'unknown' }, }); const hosts = []; - for (const remoteAuthority of ['ssh-remote+myhost', 'tunnel+standalone', 'tunnel+editor', 'tunnel+v5', 'tunnel+unselected']) { + for (const remoteAuthority of ['ssh-remote+standalone', 'ssh-remote+editor', 'ssh-remote+legacy', 'wsl+Ubuntu', 'tunnel+standalone', 'tunnel+editor', 'tunnel+v5', 'tunnel+unselected']) { hosts.push(await harness.service.resolveHost(remoteAuthority, CancellationToken.None)); } - for (const entry of [ssh, standalone, editor, protocolV5, unselected]) { + // SSH endpoint selection arrives during connect, after resolving the host. + sshConnections.push( + upcastPartial({ localAddress: getEntryAddress(sshEditor), serverType: 'editor' }), + upcastPartial({ localAddress: getEntryAddress(sshStandalone), serverType: 'standalone' }), + upcastPartial({ localAddress: getEntryAddress(sshLegacy) }), + ); + for (const entry of entries) { harness.addProvider(getEntryAddress(entry), () => assert.fail('A connected host must not reconnect'), RemoteAgentHostConnectionStatus.connected); } assert.deepStrictEqual(await Promise.all(hosts.map(async host => ({ connected: await host.connected, shares: host.sharesEditorWindowAgentHost?.() }))), [ + { connected: true, shares: true }, { connected: true, shares: false }, { connected: true, shares: true }, + { connected: true, shares: true }, + { connected: true, shares: true }, { connected: true, shares: false }, { connected: true, shares: true }, { connected: true, shares: true }, ]); + harness.locationPreferences.setPreference(getEntryAddress(sshEditor), 'editor'); + harness.locationPreferences.setPreference(getEntryAddress(editor), 'editor'); + // Tunnel editor windows are named by label, so they cannot follow the stored preference. + assert.deepStrictEqual([hosts[1].sharesEditorWindowAgentHost?.(), hosts[5].sharesEditorWindowAgentHost?.()], [true, false]); }); }); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/sshAgentHost.contribution.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/sshAgentHost.contribution.test.ts index f31a7bd191a8..77eece3c8431 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/sshAgentHost.contribution.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/sshAgentHost.contribution.test.ts @@ -6,14 +6,198 @@ import assert from 'assert'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { CancellationError } from '../../../../../../base/common/errors.js'; +import { Emitter } from '../../../../../../base/common/event.js'; +import { DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { mock } from '../../../../../../base/test/common/mock.js'; import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { IRemoteAgentHostSSHConnection, RemoteAgentHostEntryType } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; -import { SSHHostKeyDeniedError } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { getEntryAddress, IRemoteAgentHostService, IRemoteAgentHostSSHConnection, RemoteAgentHostAutoConnectSettingId, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId, RemoteAgentHostsSettingId, type IRemoteAgentHostConnectionInfo, type IRemoteAgentHostEntry } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { ISSHRemoteAgentHostService, SSHAuthenticationFailedError, SSHHostKeyDeniedError } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; +import { IConfigurationService, type IConfigurationChangeEvent } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { categorizeSSHConnectError } from '../../../../../../workbench/contrib/sessions/common/sessionsTelemetry.js'; +import { ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { type IEntryDrivenProviderOptions } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/entryDrivenProviderContribution.js'; import { ManagedReconnectState } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/managedReconnectAgentHostContribution.js'; -import { shouldPauseSSHReconnectAfterFailure } from '../../browser/sshAgentHost.contribution.js'; +import { RemoteAgentHostSessionsProvider } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/remoteAgentHostSessionsProvider.js'; import { disconnectSSHEntry, sshConnectionKey } from '../../../../../../workbench/contrib/sessions/providers/remoteAgentHost/browser/remoteHostOptions.js'; +import { shouldPauseSSHReconnectAfterFailure, SSHAgentHostContribution } from '../../browser/sshAgentHost.contribution.js'; + +suite('SSHAgentHostContribution reconnect ownership', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createHarness(autoConnect: boolean, connect: () => Promise) { + const connectionsChanged = store.add(new Emitter()); + const entriesChanged = store.add(new Emitter()); + const configuration = new TestConfigurationService({ + [RemoteAgentHostsEnabledSettingId]: true, + [RemoteAgentHostAutoConnectSettingId]: autoConnect, + }); + store.add(configuration.onDidChangeConfigurationEmitter); + let entries: IRemoteAgentHostEntry[] = [{ + name: 'Machine', + connection: { type: RemoteAgentHostEntryType.SSH, address: 'ssh:machine', sshConfigHost: 'machine', hostName: 'machine.example' }, + }]; + const calls: { address: string; userInitiated: boolean | undefined }[] = []; + const remote = new class extends mock() { + override readonly onDidChangeConfiguredEntries = entriesChanged.event; + override readonly onDidChangeConnections = connectionsChanged.event; + override readonly connections = []; + override get configuredEntries() { return entries; } + override reconnect(address: string, userInitiated?: boolean): void { + calls.push({ address, userInitiated }); + } + override async waitForConnection(address: string): Promise { + await connect(); + return { address, name: 'Machine', status: RemoteAgentHostConnectionStatus.connected }; + } + override async removeRemoteAgentHost(address: string): Promise { + entries = entries.filter(entry => getEntryAddress(entry) !== address); + entriesChanged.fire(); + connectionsChanged.fire(); + } + }(); + const instantiation = store.add(new TestInstantiationService()); + instantiation.stub(IRemoteAgentHostService, remote); + instantiation.stub(ISSHRemoteAgentHostService, { + disconnect: async () => { }, + }); + instantiation.stub(IConfigurationService, configuration); + instantiation.stub(ILogService, store.add(new NullLogService())); + instantiation.stub(ISessionsProvidersService, {}); + instantiation.stub(INotificationService, new TestNotificationService()); + instantiation.stub(ITelemetryService, NullTelemetryService); + const providers = new Map(); + let reconciliations = 0; + const contribution = store.add(instantiation.createInstance(class extends SSHAgentHostContribution { + protected override _reconcile(): void { + reconciliations++; + super._reconcile(); + } + + protected override _createProvider(address: string, name: string, options: IEntryDrivenProviderOptions) { + const provider = new class extends mock() { + override get defaultLabel(): string { return name; } + override setConnectionStatus(): void { } + override unpublishCachedSessions(): void { } + }(); + const resources = new DisposableStore(); + this._providerStores.set(address, resources); + this._providerInstances.set(address, provider); + providers.set(address, options); + resources.add(toDisposable(() => { + this._providerInstances.delete(address); + providers.delete(address); + })); + return provider; + } + })); + const provider = providers.get('ssh:machine'); + assert.ok(provider?.connectOnDemand && provider.disconnectOnDemand); + return { + calls, connectionsChanged, entriesChanged, configuration, contribution, remote, + connect: provider.connectOnDemand, + disconnect: provider.disconnectOnDemand, + getReconciliations: () => reconciliations, + fireConfigurationChange: (key: string) => configuration.onDidChangeConfigurationEmitter.fire(new class extends mock() { + override affectsConfiguration(section: string): boolean { return section === key; } + }()), + }; + } + + for (const autoConnect of [false, true]) { + for (const { name, error } of [ + { name: 'cancellation', error: new CancellationError() }, + { name: 'host key denial', error: new SSHHostKeyDeniedError('machine') }, + { name: 'authentication failure', error: new SSHAuthenticationFailedError('Credentials rejected') }, + { name: 'network failure', error: new Error('connect ETIMEDOUT') }, + ]) { + test(`${name} is not retried by provider events or timers (auto-connect ${autoConnect})`, () => runWithFakedTimers({}, async () => { + let failure: Error | undefined = error; + const harness = createHarness(autoConnect, async () => { + if (failure) { + throw failure; + } + }); + await harness.connect(); + harness.connectionsChanged.fire(); + harness.entriesChanged.fire(); + harness.fireConfigurationChange(RemoteAgentHostsSettingId); + harness.fireConfigurationChange(RemoteAgentHostAutoConnectSettingId); + harness.fireConfigurationChange(RemoteAgentHostsEnabledSettingId); + await timeout(180_000); + const afterFailure = harness.calls.slice(); + + failure = undefined; + await harness.connect(); + harness.connectionsChanged.fire(); + await timeout(60_000); + harness.contribution.dispose(); + + assert.deepStrictEqual({ afterFailure, afterExplicitReconnect: harness.calls }, { + afterFailure: [{ address: 'ssh:machine', userInitiated: true }], + afterExplicitReconnect: [ + { address: 'ssh:machine', userInitiated: true }, + { address: 'ssh:machine', userInitiated: true }, + ], + }); + })); + } + } + + test('joins an in-flight explicit connection without starting another attempt', () => runWithFakedTimers({}, async () => { + const connected = new DeferredPromise(); + const harness = createHarness(false, () => connected.p); + const first = harness.connect(); + const second = harness.connect(); + harness.connectionsChanged.fire(); + await timeout(60_000); + await connected.complete(); + await Promise.all([first, second]); + harness.contribution.dispose(); + + assert.deepStrictEqual(harness.calls, [{ address: 'ssh:machine', userInitiated: true }]); + })); + + test('removing a cancelled host cannot revive it on a later event or timer', () => runWithFakedTimers({}, async () => { + const harness = createHarness(true, async () => { throw new CancellationError(); }); + await harness.connect(); + await harness.disconnect(); + harness.connectionsChanged.fire(); + await timeout(180_000); + harness.contribution.dispose(); + + assert.deepStrictEqual({ calls: harness.calls, entries: harness.remote.configuredEntries }, { + calls: [{ address: 'ssh:machine', userInitiated: true }], + entries: [], + }); + })); + + test('periodic reconciliation preserves offline providers without dialing and stops on disposal', () => runWithFakedTimers({}, async () => { + const harness = createHarness(false, async () => { }); + const initial = harness.getReconciliations(); + await timeout(60_000); + const afterTimer = harness.getReconciliations(); + harness.contribution.dispose(); + harness.connectionsChanged.fire(); + harness.entriesChanged.fire(); + harness.fireConfigurationChange(RemoteAgentHostsSettingId); + await timeout(180_000); + + assert.deepStrictEqual({ + initial, + afterTimer, + afterDisposal: harness.getReconciliations(), + calls: harness.calls, + }, { initial: 1, afterTimer: 2, afterDisposal: 2, calls: [] }); + })); +}); suite('SSH reconnect state', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -104,14 +288,16 @@ suite('SSH reconnect state', () => { suite('shouldPauseSSHReconnectAfterFailure', () => { ensureNoDisposablesAreLeakedInTestSuite(); - test('pauses reconnect after cancellation or host key denial but not after regular failures', () => { + test('pauses reconnect after cancellation, host key denial, or authentication rejection but not after regular failures', () => { assert.deepStrictEqual({ cancellation: shouldPauseSSHReconnectAfterFailure(new CancellationError()), hostKeyDenial: shouldPauseSSHReconnectAfterFailure(new SSHHostKeyDeniedError('test-host')), + authenticationFailure: shouldPauseSSHReconnectAfterFailure(new SSHAuthenticationFailedError('Credentials rejected')), regularError: shouldPauseSSHReconnectAfterFailure(new Error('boom')), }, { cancellation: true, hostKeyDenial: true, + authenticationFailure: true, regularError: false, }); }); diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/devContainerAgentHostConnector.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/devContainerAgentHostConnector.test.ts index 0634e8abc87b..e88e02595033 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/devContainerAgentHostConnector.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/devContainerAgentHostConnector.test.ts @@ -15,7 +15,7 @@ import { URI } from '../../../../../../base/common/uri.js'; import { hasKey } from '../../../../../../base/common/types.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { IDevContainerAgentHostConfig, IDevContainerAgentHostMainService } from '../../../../../../platform/agentHost/common/devContainerAgentHost.js'; +import { IDevContainerAgentHostConfig, IDevContainerAgentHostMainService, IDevContainerAgentHostUserStateReport } from '../../../../../../platform/agentHost/common/devContainerAgentHost.js'; import { devContainerSamples, devContainerSampleUri, IDevContainerSampleSource } from '../../../../../../platform/agentHost/common/devContainerSamples.js'; import { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; import { AGENT_HOST_SCHEME, agentHostAuthority } from '../../../../../../platform/agentHost/common/agentHostUri.js'; @@ -30,8 +30,9 @@ import { ISharedProcessService } from '../../../../../../platform/ipc/electron-b import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { Registry } from '../../../../../../platform/registry/common/platform.js'; import { ITelemetryData, ITelemetryService, TelemetryLevel } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { IOutputChannel, IOutputService } from '../../../../../../workbench/services/output/common/output.js'; -import { DevContainerAgentHostEnabledSettingId, DevContainerIdleTimeoutSettingId, DevContainerSamplesEnabledSettingId, DevContainerWorktreeEnabledSettingId } from '../../../../../../workbench/contrib/sessions/common/devContainerAgentHostService.js'; +import { DevContainerAgentHostEnabledSettingId, DevContainerIdleTimeoutSettingId, DevContainerSamplesEnabledSettingId, DevContainerStateVolumeEnabledSettingId, DevContainerWorktreeEnabledSettingId } from '../../../../../../workbench/contrib/sessions/common/devContainerAgentHostService.js'; import { WorkspaceHistoryLoadState } from '../../../../../../workbench/services/sessions/common/workspaceSelection.js'; import { ISessionFolder, ISessionWorkspace } from '../../../../../../workbench/services/sessions/common/session.js'; import { ISessionsProvidersService } from '../../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; @@ -46,14 +47,17 @@ suite('Dev Container Agent Host Connector', () => { const devContainerAgentHostEnabledProperty = configurationRegistry.getConfigurationProperties()[DevContainerAgentHostEnabledSettingId]; const devContainerIdleTimeoutProperty = configurationRegistry.getConfigurationProperties()[DevContainerIdleTimeoutSettingId]; const devContainerWorktreeEnabledProperty = configurationRegistry.getExcludedConfigurationProperties()[DevContainerWorktreeEnabledSettingId]; + const devContainerStateVolumeEnabledProperty = configurationRegistry.getConfigurationProperties()[DevContainerStateVolumeEnabledSettingId]; const devContainerSamplesProperty = configurationRegistry.getConfigurationProperties()[DevContainerSamplesEnabledSettingId]; for (const sandboxEnabled of [false, true]) { - test(`relay reconnect retains requested sandbox options (requested: ${sandboxEnabled})`, async () => { + test(`relay reconnect retains requested sandbox options and reads the state volume setting again (requested: ${sandboxEnabled})`, async () => { const configs: IDevContainerAgentHostConfig[] = []; + const events: Array<{ eventName: string; data: unknown }> = []; const service = new class extends mock() { override readonly onDidOutput = Event.None; override readonly onDidChangeSandboxSupport = Event.None; + override readonly onDidReportUserState = Event.None; override readonly onDidRelayMessage = Event.None; override readonly onDidRelayActivity = Event.None; override readonly onDidRelayClose = Event.None; @@ -64,10 +68,15 @@ suite('Dev Container Agent Host Connector', () => { } override async disconnect() { } }(); + const configuration = new TestConfigurationService({ + [DevContainerSamplesEnabledSettingId]: true, + [DevContainerAgentHostEnabledSettingId]: true, + [RemoteAgentHostsEnabledSettingId]: true, + }); const connector = store.add(new DevContainerAgentHostConnector( new class extends mock() { override getChannel(): IChannel { - const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport'] }); + const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport', 'onDidReportUserState'] }); return { listen: (event, arg) => channel.listen(undefined, event, arg), call: (command, arg) => channel.call(undefined, command, arg), @@ -76,11 +85,7 @@ suite('Dev Container Agent Host Connector', () => { }(), store.add(new TestInstantiationService()), store.add(new NullLogService()), - new TestConfigurationService({ - [DevContainerSamplesEnabledSettingId]: true, - [DevContainerAgentHostEnabledSettingId]: true, - [RemoteAgentHostsEnabledSettingId]: true, - }), + configuration, new class extends mock() { }(), new class extends mock() { override getChannel() { @@ -91,6 +96,13 @@ suite('Dev Container Agent Host Connector', () => { new class extends mock() { }(), new class extends mock() { }(), new class extends mock() { override async loadCertificates(): Promise { return ['CLIENT CA']; } }(), + new class extends mock() { + override publicLog2(eventName: string, data?: ITelemetryData): void { + const { durationMs, ...rest } = data as { durationMs: unknown }; + assert.strictEqual(typeof durationMs, 'number'); + events.push({ eventName, data: rest }); + } + }(), )); const target = await connector.createConnection(devContainerSampleUri(devContainerSamples[0]), 'devcontainer:sample', CancellationToken.None, { resume: true, sandboxEnabled }); store.add(target.transportDisposable!); @@ -98,13 +110,25 @@ suite('Dev Container Agent Host Connector', () => { const first = store.add(target.transportFactory()); assert.ok(isClientTransport(first)); await first.connect(); + // A container created on reconnect follows the current setting. + await configuration.setUserConfiguration(DevContainerStateVolumeEnabledSettingId, true); const reconnected = store.add(target.transportFactory()); assert.ok(isClientTransport(reconnected)); await reconnected.connect(); - assert.deepStrictEqual(configs.map(config => ({ resume: config.resume, sandboxEnabled: config.sandboxEnabled })), [ - { resume: true, sandboxEnabled }, - { resume: false, sandboxEnabled }, - ]); + const connected = { success: true, cancelled: false, sample: true, remote: false }; + assert.deepStrictEqual({ + configs: configs.map(config => ({ resume: config.resume, sandboxEnabled: config.sandboxEnabled, persistUserState: config.persistUserState })), + events, + }, { + configs: [ + { resume: true, sandboxEnabled, persistUserState: undefined }, + { resume: false, sandboxEnabled, persistUserState: true }, + ], + events: [ + { eventName: 'vscodeAgents.devContainer/connect', data: { ...connected, reconnect: false, stateVolume: false } }, + { eventName: 'vscodeAgents.devContainer/connect', data: { ...connected, reconnect: true, stateVolume: true } }, + ], + }); }); } @@ -134,6 +158,7 @@ suite('Dev Container Agent Host Connector', () => { const service = new class extends mock() { override readonly onDidOutput = Event.None; override readonly onDidChangeSandboxSupport = Event.None; + override readonly onDidReportUserState = Event.None; override readonly onDidRelayMessage = Event.None; override readonly onDidRelayActivity = Event.None; override readonly onDidRelayClose = Event.None; @@ -150,7 +175,7 @@ suite('Dev Container Agent Host Connector', () => { const connector = store.add(new DevContainerAgentHostConnector( new class extends mock() { override getChannel(): IChannel { - const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport'] }); + const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport', 'onDidReportUserState'] }); return { listen: (event, arg) => channel.listen(undefined, event, arg), call: (command, arg) => channel.call(undefined, command, arg), @@ -172,6 +197,7 @@ suite('Dev Container Agent Host Connector', () => { new class extends mock() { }(), new class extends mock() { }(), new class extends mock() { override async loadCertificates(): Promise { return ['CLIENT CA']; } }(), + NullTelemetryService, )); const source = devContainerSampleUri(devContainerSamples[0]); await connector.isAvailable(source); @@ -215,6 +241,7 @@ suite('Dev Container Agent Host Connector', () => { override readonly onDidRelayClose = Event.None; override readonly onDidCloseConnection = Event.None; override readonly onDidChangeSandboxSupport = support.event; + override readonly onDidReportUserState = Event.None; override async connect(config: IDevContainerAgentHostConfig): Promise { support.fire({ connectionId: config.connectionId, supported: false }); throw new Error('Unsupported sandbox startup'); @@ -222,7 +249,7 @@ suite('Dev Container Agent Host Connector', () => { override async disconnect(): Promise { } }(); const service = remote ? store.add(new RemoteDevContainerService(async () => main, new NullLogService())) : main; - const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport'] }); + const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport', 'onDidReportUserState'] }); const connector = store.add(new DevContainerAgentHostConnector( new class extends mock() { override getChannel(): IChannel { @@ -244,6 +271,7 @@ suite('Dev Container Agent Host Connector', () => { new class extends mock() { }(), new class extends mock() { }(), new class extends mock() { override async loadCertificates(): Promise { return ['CLIENT CA']; } }(), + NullTelemetryService, )); const workspace = URI.file('/unsupported-project'); const observed: { workspace: string; supported: boolean }[] = []; @@ -251,6 +279,74 @@ suite('Dev Container Agent Host Connector', () => { await assert.rejects(connector.createConnection(workspace, 'devcontainer:unsupported', CancellationToken.None, { resume: true, sandboxEnabled: true }), /Unsupported sandbox startup/); assert.deepStrictEqual(observed, [{ workspace: workspace.toString(), supported: false }]); }); + + test(`logs user state reports before a failed connection (remote facade: ${remote})`, async () => { + const userState = store.add(new Emitter()); + const configs: IDevContainerAgentHostConfig[] = []; + const main = new class extends mock() { + override readonly onDidOutput = Event.None; + override readonly onDidRelayMessage = Event.None; + override readonly onDidRelayActivity = Event.None; + override readonly onDidRelayClose = Event.None; + override readonly onDidCloseConnection = Event.None; + override readonly onDidChangeSandboxSupport = Event.None; + override readonly onDidReportUserState = userState.event; + override async connect(config: IDevContainerAgentHostConfig): Promise { + configs.push(config); + userState.fire({ connectionId: 'other', stage: 'mount', outcome: 'added' }); + userState.fire({ connectionId: config.connectionId, stage: 'mount', outcome: 'added', target: 'workspaces' }); + userState.fire({ connectionId: config.connectionId, stage: 'link', outcome: 'failed', reason: 'script', step: 'folders', exitCode: 1, target: 'workspaces', movedFolders: 1, skippedFolders: 2, skipReasons: 'mounted,symlink', errorMessage: 'Cannot link user state (exit 1):' }); + throw new Error('Lifecycle failed'); + } + override async disconnect(): Promise { } + }(); + const service = remote ? store.add(new RemoteDevContainerService(async () => main, new NullLogService())) : main; + const channel = ProxyChannel.fromService(service, store.add(new DisposableStore()), { unbufferedEvents: ['onDidChangeSandboxSupport', 'onDidReportUserState'] }); + const events: Array<{ eventName: string; data: ITelemetryData | undefined }> = []; + const connector = store.add(new DevContainerAgentHostConnector( + new class extends mock() { + override getChannel(): IChannel { + return { + listen: (event, arg) => channel.listen(undefined, event, arg), + call: (command, arg) => channel.call(undefined, command, arg), + }; + } + }(), + store.add(new TestInstantiationService()), + new NullLogService(), + new TestConfigurationService({ [DevContainerAgentHostEnabledSettingId]: true, [RemoteAgentHostsEnabledSettingId]: true, [DevContainerStateVolumeEnabledSettingId]: true }), + new class extends mock() { }(), + new class extends mock() { + override getChannel() { return new class extends mock() { override append() { } }(); } + override async showChannel(): Promise { } + }(), + new class extends mock() { }(), + new class extends mock() { }(), + new class extends mock() { }(), + new class extends mock() { }(), + new class extends mock() { + override publicLog2(eventName: string, data?: ITelemetryData): void { + if (eventName === 'vscodeAgents.devContainer/connect') { + const { durationMs, ...rest } = data as { durationMs: unknown }; + assert.strictEqual(typeof durationMs, 'number'); + events.push({ eventName, data: rest }); + } else { + events.push({ eventName, data }); + } + } + }(), + )); + await assert.rejects(connector.createConnection(URI.file('/project'), 'devcontainer:project', CancellationToken.None), /Lifecycle failed/); + const unset = { reason: undefined, step: undefined, target: undefined, skipReasons: undefined, exitCode: undefined, restoredFolders: undefined, movedFolders: undefined, createdFolders: undefined, existingFolders: undefined, skippedFolders: undefined, errorMessage: undefined, enabled: true, sample: false, remote: false }; + assert.deepStrictEqual({ persistUserState: configs.map(config => config.persistUserState), events }, { + persistUserState: [true], + events: [ + { eventName: 'vscodeAgents.devContainer/stateVolume', data: { ...unset, stage: 'mount', outcome: 'added', target: 'workspaces' } }, + { eventName: 'vscodeAgents.devContainer/stateVolume', data: { ...unset, stage: 'link', outcome: 'failed', reason: 'script', step: 'folders', exitCode: 1, target: 'workspaces', movedFolders: 1, skippedFolders: 2, skipReasons: 'mounted,symlink', errorMessage: 'Cannot link user state (exit 1):' } }, + { eventName: 'vscodeAgents.devContainer/connect', data: { success: false, cancelled: false, reconnect: false, stateVolume: true, sample: false, remote: false } }, + ], + }); + }); } test('sample availability requires its setting and Docker without reading a host workspace', async () => { @@ -525,6 +621,7 @@ suite('Dev Container Agent Host Connector', () => { }(), new class extends mock() { }(), new class extends mock() { override async loadCertificates(): Promise { return ['CLIENT CA']; } }(), + NullTelemetryService, )); const available = await connector.isAvailable(workspaceUri); supported = false; @@ -695,6 +792,20 @@ suite('Dev Container Agent Host Connector', () => { }); }); + test('registers an experimental setting for keeping Dev Container state on a volume', () => { + assert.deepStrictEqual({ + default: devContainerStateVolumeEnabledProperty.default, + scope: devContainerStateVolumeEnabledProperty.scope, + tags: devContainerStateVolumeEnabledProperty.tags, + experiment: devContainerStateVolumeEnabledProperty.experiment, + }, { + default: false, + scope: ConfigurationScope.APPLICATION, + tags: ['experimental', 'onExP'], + experiment: { mode: 'auto' }, + }); + }); + test('rejects connections when Dev Container or remote Agent Hosts are disabled', () => { const configurationService = (devContainerAgentHostsEnabled: boolean, remoteAgentHostsEnabled: boolean) => new TestConfigurationService({ [DevContainerAgentHostEnabledSettingId]: devContainerAgentHostsEnabled, @@ -752,6 +863,7 @@ suite('Dev Container Agent Host Connector', () => { new class extends mock() { }(), new class extends mock() { }(), new class extends mock() { override async loadCertificates(): Promise { return ['CLIENT CA']; } }(), + NullTelemetryService, )); await assert.rejects( diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/remotesEditor.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/remotesEditor.test.ts index 61dcf7e5b753..e805b83fa683 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/remotesEditor.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/electron-browser/remotesEditor.test.ts @@ -65,6 +65,7 @@ class TestRemotesModel extends Disposable implements IRemotesModel { async copyAddress(): Promise { } async changePreferredAgentLocation(): Promise { } async updateServer(): Promise { } + async setSharedAsGitHubEnvironment(): Promise { } async deleteTunnel(): Promise { } async deleteSSHHost(): Promise { } async remove(): Promise { } @@ -81,10 +82,14 @@ class TestRemoteTunnelService extends mock() { override readonly onDidChangeTunnelStatus = this.onDidChangeStatusEmitter.event; override readonly onDidChangeMode = Event.None; override async getMode(): Promise { return INACTIVE_TUNNEL_MODE; } - override async getTunnelStatus(): Promise { return { type: 'disconnected' }; } + private status: TunnelStatus = { type: 'disconnected' }; + override async getTunnelStatus(): Promise { return this.status; } override async getTunnelName(): Promise { return 'my-workstation'; } override async stopTunnel(): Promise { } - fireStatus(status: TunnelStatus): void { this.onDidChangeStatusEmitter.fire(status); } + fireStatus(status: TunnelStatus): void { + this.status = status; + this.onDidChangeStatusEmitter.fire(status); + } dispose(): void { this.onDidChangeStatusEmitter.dispose(); } } @@ -227,11 +232,11 @@ suite('RemotesEditor', () => { before: { name: 'my-workstation', options: ['Off (selected)', 'GitHub Environments (Preview)', 'Dev Tunnels'], status: 'Remote connections are off.' }, after: { name: 'my-workstation', options: ['Off', 'GitHub Environments (Preview)', 'Dev Tunnels (selected)'], status: 'Remote connections are on via Dev Tunnels.' }, commands: [TOGGLE_REMOTE_CONNECTIONS_COMMAND_ID], - accessible: 'This Computer\nSharing name: my-workstation\nRemote connections are on via Dev Tunnels.\nLocal sessions run directly here. Sharing lets other clients access agents and folders on this computer.\nLearn More: https://aka.ms/vscode-agent-environments', + accessible: 'This Computer\nSharing name: my-workstation\nRemote connections are on via Dev Tunnels.\nLocal sessions run directly here. Sharing lets other devices use agents and folders on this computer. Files and tools stay here.\nLearn More: https://aka.ms/vscode-agent-environments', optionNames: [ - 'Off: Only accessible from this machine.', - 'GitHub Environments (Preview): Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot.', - 'Dev Tunnels: Access workspaces and agents on this machine from VS Code or vscode.dev/agents.', + 'Off: Don\'t allow connections from other devices through this app.', + 'GitHub Environments (Preview): Continue agent sessions across supported Copilot apps, VS Code, and vscode.dev/agents. Agents use folders and tools on this computer; features vary by app.', + 'Dev Tunnels: Use agents and folders on this computer from VS Code or vscode.dev/agents. For full-editor access, use Remote Tunnels.', ], }); }); diff --git a/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionInspector.test.ts b/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionInspector.test.ts index 707a92aa7ec2..c0d339b9dfe5 100644 --- a/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionInspector.test.ts +++ b/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionInspector.test.ts @@ -7,7 +7,7 @@ import assert from 'assert'; import { DeferredPromise } from '../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; -import { DisposableStore, IReference } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, IReference } from '../../../../../base/common/lifecycle.js'; import { observableValue } from '../../../../../base/common/observable.js'; import { hasKey } from '../../../../../base/common/types.js'; import { URI } from '../../../../../base/common/uri.js'; @@ -27,6 +27,7 @@ import { buildChatUri, buildDefaultChatUri, ChatState, ComponentToState, createC import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { TestPathService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; @@ -139,7 +140,7 @@ suite('RemoteSessionInspector', () => { } override getConnectionByAuthority(authority: string) { return this.getConnection(authority); } }(); - const connections = store.add(new AgentHostConnectionsService(local, remoteService, new TestPathService(), new NullLogService())); + const connections = store.add(new AgentHostConnectionsService(local, remoteService, new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); const providersService = new class extends mock() { override getProviders() { return catalogOnly ? [upcastPartial({ diff --git a/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionMessageRouter.test.ts b/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionMessageRouter.test.ts index 81c9e01e61cc..406e3ae0958a 100644 --- a/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionMessageRouter.test.ts +++ b/src/vs/sessions/contrib/remoteSessions/test/browser/remoteSessionMessageRouter.test.ts @@ -7,7 +7,7 @@ import assert from 'assert'; import { DeferredPromise } from '../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; -import { DisposableStore, IReference, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, IReference, toDisposable } from '../../../../../base/common/lifecycle.js'; import { constObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; import { isEqual } from '../../../../../base/common/resources.js'; import { hasKey } from '../../../../../base/common/types.js'; @@ -33,7 +33,7 @@ import { buildChatUri, buildDefaultChatUri, buildSubagentChatUri, ChatState, Com import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; -import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; import { IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; import { messageToRequestOrigin } from '../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; @@ -209,7 +209,7 @@ suite('RemoteSessionMessageRouter', () => { } override getConnectionByAuthority(authority: string): IAgentConnection | undefined { return this.getConnection(authority); } }(); - const connections = store.add(new AgentHostConnectionsService(local, remoteService, new TestPathService(), new NullLogService())); + const connections = store.add(new AgentHostConnectionsService(local, remoteService, new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); const sessions = ['agent-host-copilot', 'remote-first-copilot', 'remote-second-copilot'].map((scheme, index) => { const resource = URI.from({ scheme, path: '/same-id' }); const chats = ['', 'original-chat', 'other-chat'].map(fragment => upcastPartial({ diff --git a/src/vs/sessions/contrib/sessionComparison/browser/modelEvaluationTools.ts b/src/vs/sessions/contrib/sessionComparison/browser/modelEvaluationTools.ts index e7257776e6bd..1543a5057ba0 100644 --- a/src/vs/sessions/contrib/sessionComparison/browser/modelEvaluationTools.ts +++ b/src/vs/sessions/contrib/sessionComparison/browser/modelEvaluationTools.ts @@ -5,7 +5,7 @@ import { CancellationToken } from '../../../../base/common/cancellation.js'; import { Codicon } from '../../../../base/common/codicons.js'; -import { escapeMarkdownSyntaxTokens, MarkdownString } from '../../../../base/common/htmlContent.js'; +import { createCommandUri, escapeMarkdownSyntaxTokens, MarkdownString } from '../../../../base/common/htmlContent.js'; import { IJSONSchema } from '../../../../base/common/jsonSchema.js'; import { Disposable, DisposableStore } from '../../../../base/common/lifecycle.js'; import { autorun } from '../../../../base/common/observable.js'; @@ -31,6 +31,7 @@ import { ISessionsProvidersService } from '../../../../workbench/contrib/session import { IChat, ISession } from '../../../../workbench/services/sessions/common/session.js'; import { getSessionComparisonChat, getSessionComparisonWorkspaceError, ISessionComparison, ISessionComparisonService, IStartSessionComparisonOptions, COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, SESSION_COMPARISON_MAX_ATTEMPTS, SESSION_COMPARISON_MIN_ATTEMPTS, SessionComparisonLaunchError, SessionComparisonParticipantRole } from '../../../../workbench/contrib/sessions/common/sessionComparison.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { OPEN_SESSION_COMPARISON_COMMAND_ID } from '../../../../workbench/contrib/sessions/common/sessionComparisonConstants.js'; import { getManifestSessionStatus, ReadSessionComparisonTool } from './sessionComparisonTool.js'; type EvaluationToolName = 'getComparisonModels' | 'createModelComparison' | 'listModelComparisons' | 'readModelComparison'; @@ -54,7 +55,7 @@ const definitions: Record) { - if (input.includeArchived !== undefined && typeof input.includeArchived !== 'boolean' + private list(input: Record, originatingChatResource: URI | undefined) { + if (input.scope !== undefined && input.scope !== 'chat' && input.scope !== 'window' + || input.includeArchived !== undefined && typeof input.includeArchived !== 'boolean' || input.workspace !== undefined && typeof input.workspace !== 'string' || input.cursor !== undefined && typeof input.cursor !== 'string' || input.comparisonIds !== undefined && (!Array.isArray(input.comparisonIds) || input.comparisonIds.length > 100 || !input.comparisonIds.every(id => typeof id === 'string'))) { throw new EvaluationInputError('Invalid comparison list filters.'); } + if (input.scope !== 'window' && !originatingChatResource) { + throw new EvaluationInputError('The calling chat is unavailable. Use scope "window" to discover comparisons across this Agents window.'); + } const ids = Array.isArray(input.comparisonIds) ? input.comparisonIds : undefined; const workspace = typeof input.workspace === 'string' ? URI.parse(input.workspace) : undefined; const comparisons = this.comparisons.comparisons.get() - .filter(comparison => (input.includeArchived === true || comparison.archivedAt === undefined) + .filter(comparison => (input.scope === 'window' || isEqual(comparison.originatingChatResource, originatingChatResource)) + && (input.includeArchived === true || comparison.archivedAt === undefined) && (!workspace || isEqual(comparison.workspace, workspace)) && (!ids || ids.includes(comparison.id))) .slice().sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id)); const cursorIndex = input.cursor === undefined ? -1 : comparisons.findIndex(comparison => comparison.id === input.cursor); diff --git a/src/vs/sessions/contrib/sessionComparison/browser/sessionComparisonTool.ts b/src/vs/sessions/contrib/sessionComparison/browser/sessionComparisonTool.ts index 28e6f1365a06..4b69a8496155 100644 --- a/src/vs/sessions/contrib/sessionComparison/browser/sessionComparisonTool.ts +++ b/src/vs/sessions/contrib/sessionComparison/browser/sessionComparisonTool.ts @@ -95,7 +95,8 @@ export class ReadSessionComparisonTool implements IToolImpl { if (!comparison) { return toolError(`Comparison '${input.comparisonId}' does not exist.`); } - const invokingParticipant = invocation.context && this.comparisonService.getParticipantForChat(comparison.id, invocation.context.sessionResource); + const invokingChat = invocation.originatingChatResource ?? invocation.context?.sessionResource; + const invokingParticipant = invokingChat && this.comparisonService.getParticipantForChat(comparison.id, invokingChat); if (!invokingParticipant || ![SessionComparisonParticipantRole.Judge, SessionComparisonParticipantRole.Synthesis].includes(invokingParticipant.role)) { return toolError('Only the Judge or synthesis session for this comparison can read its manifest.'); } @@ -288,14 +289,15 @@ export class CompleteSessionComparisonTool implements IToolImpl { async invoke(invocation: IToolInvocation, _countTokens: CountTokensCallback, _progress: ToolProgress, _token: CancellationToken): Promise { const input = parseInput(invocation.parameters); - if (!input) { - return toolError('The comparison verdict input is invalid. Keep explanation to one sentence, provide concise comparison, validation, codeQuality, and solution rationale points, and use a consistent state and source pair for every validation category.'); + if (typeof input === 'string') { + return toolError(`The comparison verdict input is invalid. ${input}`); } const comparison = resolveComparison(this.comparisonService, input.comparisonId); if (!comparison) { return toolError(`Comparison '${input.comparisonId}' does not exist.`); } - const invokingParticipant = invocation.context && this.comparisonService.getParticipantForChat(comparison.id, invocation.context.sessionResource); + const invokingChat = invocation.originatingChatResource ?? invocation.context?.sessionResource; + const invokingParticipant = invokingChat && this.comparisonService.getParticipantForChat(comparison.id, invokingChat); if (invokingParticipant?.role !== SessionComparisonParticipantRole.Judge) { return toolError('Only the judge session for this comparison can submit its verdict.'); } @@ -393,31 +395,64 @@ function parseReadInput(value: unknown): IReadSessionComparisonInput | undefined : undefined; } -function parseInput(value: unknown): ICompleteSessionComparisonInput | undefined { - const rationale = isRecord(value) ? parseRationale(value.rationale) : undefined; - if (!isRecord(value) - || typeof value.comparisonId !== 'string' - || typeof value.recommendedAttemptNumber !== 'number' - || !isConciseText(value.explanation, MaxExplanationLength) - || !rationale - || !isStringArray(value.conflicts) - || !Array.isArray(value.attempts) - || Object.hasOwn(value, 'decisionSections')) { - return undefined; +function parseInput(value: unknown): ICompleteSessionComparisonInput | string { + if (!isRecord(value)) { + return 'Input must be an object.'; + } + if (typeof value.comparisonId !== 'string') { + return 'comparisonId must be a string.'; + } + if (typeof value.recommendedAttemptNumber !== 'number') { + return 'recommendedAttemptNumber must be an integer attemptNumber from readAttemptComparison.'; + } + if (!isConciseText(value.explanation, MaxExplanationLength)) { + return conciseTextError('explanation', MaxExplanationLength); + } + const rationale = parseRationale(value.rationale); + if (typeof rationale === 'string') { + return rationale; + } + if (!isStringArray(value.conflicts)) { + return stringArrayError('conflicts', value.conflicts); + } + if (!Array.isArray(value.attempts)) { + return 'attempts must be an array with one finding per attemptNumber from readAttemptComparison.'; + } + if (Object.hasOwn(value, 'decisionSections')) { + return 'decisionSections is not supported; remove it and use rationale.'; } const attempts: ICompleteSessionComparisonAttemptInput[] = []; - for (const attempt of value.attempts) { - if (!isRecord(attempt) - || typeof attempt.attemptNumber !== 'number' - || typeof attempt.summary !== 'string' - || !isRecord(attempt.validation) - || !isValidationEvidence(attempt.validation.tests) - || !isValidationEvidence(attempt.validation.build) - || !isValidationEvidence(attempt.validation.lint) - || !isValidationEvidence(attempt.validation.diagnostics) - || !isStringArray(attempt.unresolvedIssues) - || !isStringArray(attempt.notableDifferences)) { - return undefined; + for (const [index, attempt] of value.attempts.entries()) { + const path = `attempts[${index}]`; + if (!isRecord(attempt)) { + return `${path} must be an object.`; + } + if (typeof attempt.attemptNumber !== 'number') { + return `${path}.attemptNumber must be an integer attemptNumber from readAttemptComparison.`; + } + if (typeof attempt.summary !== 'string') { + return `${path}.summary must be a string.`; + } + if (!isRecord(attempt.validation)) { + return `${path}.validation must contain tests, build, lint, and diagnostics evidence.`; + } + if (!isValidationEvidence(attempt.validation.tests)) { + return validationEvidenceError(`${path}.validation.tests`); + } + if (!isValidationEvidence(attempt.validation.build)) { + return validationEvidenceError(`${path}.validation.build`); + } + if (!isValidationEvidence(attempt.validation.lint)) { + return validationEvidenceError(`${path}.validation.lint`); + } + if (!isValidationEvidence(attempt.validation.diagnostics)) { + return validationEvidenceError(`${path}.validation.diagnostics`); + } + if (!isStringArray(attempt.unresolvedIssues)) { + return stringArrayError(`${path}.unresolvedIssues`, attempt.unresolvedIssues); + } + if (!isStringArray(attempt.notableDifferences)) { + return stringArrayError(`${path}.notableDifferences`, attempt.notableDifferences); } attempts.push({ attemptNumber: attempt.attemptNumber, @@ -442,13 +477,21 @@ function parseInput(value: unknown): ICompleteSessionComparisonInput | undefined }; } -function parseRationale(value: unknown): ISessionComparisonRationale | undefined { - if (!isRecord(value) - || !isConciseText(value.comparison, MaxRationalePointLength) - || !isConciseText(value.validation, MaxRationalePointLength) - || !isConciseText(value.codeQuality, MaxRationalePointLength) - || !isConciseText(value.solution, MaxRationalePointLength)) { - return undefined; +function parseRationale(value: unknown): ISessionComparisonRationale | string { + if (!isRecord(value)) { + return 'rationale must contain comparison, validation, codeQuality, and solution strings.'; + } + if (!isConciseText(value.comparison, MaxRationalePointLength)) { + return conciseTextError('rationale.comparison', MaxRationalePointLength); + } + if (!isConciseText(value.validation, MaxRationalePointLength)) { + return conciseTextError('rationale.validation', MaxRationalePointLength); + } + if (!isConciseText(value.codeQuality, MaxRationalePointLength)) { + return conciseTextError('rationale.codeQuality', MaxRationalePointLength); + } + if (!isConciseText(value.solution, MaxRationalePointLength)) { + return conciseTextError('rationale.solution', MaxRationalePointLength); } return { comparison: value.comparison, @@ -458,6 +501,21 @@ function parseRationale(value: unknown): ISessionComparisonRationale | undefined }; } +function conciseTextError(path: string, maxLength: number): string { + return `${path} must be a non-empty, single-line string of at most ${maxLength} characters.`; +} + +function stringArrayError(path: string, value: unknown): string { + const invalidIndex = Array.isArray(value) ? value.findIndex(item => typeof item !== 'string') : -1; + return invalidIndex >= 0 + ? `${path}[${invalidIndex}] must be a string.` + : `${path} must be an array of strings; use [] when there are none.`; +} + +function validationEvidenceError(path: string): string { + return `${path} must pair passed/failed with attemptReport/judgeRun, notRun/unknown with attemptReport/judgeRun/unavailable, or notApplicable with notApplicable.`; +} + function isConciseText(value: unknown, maxLength: number): value is string { return typeof value === 'string' && value.trim().length > 0 && value.length <= maxLength && !value.includes('\n'); } diff --git a/src/vs/sessions/contrib/sessionComparison/test/browser/modelEvaluationTools.test.ts b/src/vs/sessions/contrib/sessionComparison/test/browser/modelEvaluationTools.test.ts index 1c009e6ac79a..228cf55c0786 100644 --- a/src/vs/sessions/contrib/sessionComparison/test/browser/modelEvaluationTools.test.ts +++ b/src/vs/sessions/contrib/sessionComparison/test/browser/modelEvaluationTools.test.ts @@ -30,6 +30,7 @@ import { ILifecycleService } from '../../../../../workbench/services/lifecycle/c import { IChat, ISession, ISessionWorkspace, SessionStatus, SessionTypeAuthRequirement } from '../../../../../workbench/services/sessions/common/session.js'; import { COMPARE_AGENTS_ENABLED_SETTING, COMPARE_AGENTS_TOOLS_ENABLED_SETTING, ISessionComparison, ISessionComparisonService, IStartSessionComparisonOptions, SessionComparisonLaunchError, SessionComparisonParticipantRole } from '../../../../../workbench/contrib/sessions/common/sessionComparison.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { OPEN_SESSION_COMPARISON_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionComparisonConstants.js'; import { ModelEvaluationTool, ModelEvaluationToolContribution } from '../../browser/modelEvaluationTools.js'; const callerResource = URI.parse('test:/parent#evaluator'); @@ -99,7 +100,7 @@ suite('ModelEvaluationTools', () => { getParticipantForChat: (id, resource) => comparisons.get().find(comparison => comparison.id === id)?.participants.find(participant => isEqual(participant.chatResource, resource)), startComparison: async options => { launches.push(options); - const created = comparison({ judgeHarness: options.judgeHarness }); + const created = comparison({ judgeHarness: options.judgeHarness, originatingChatResource: options.originatingChatResource }); comparisons.set([...comparisons.get(), created], undefined); return created; }, @@ -184,6 +185,13 @@ suite('ModelEvaluationTools', () => { ]); }); + test('keeps comparison IDs available for tools without encouraging them in user-facing replies', () => { + const fixture = setup(); + for (const name of ['createModelComparison', 'listModelComparisons', 'readModelComparison'] as const) { + assert.match(fixture.tool(name).getToolData().modelDescription, /Keep comparisonId internal unless the user explicitly requests it; refer to comparisons by title in user-facing replies/, name); + } + }); + test('disabling evaluator tools rejects all invocations including a previously prepared launch', async () => { const fixture = setup(); const tool = fixture.tool('createModelComparison'); @@ -212,17 +220,56 @@ suite('ModelEvaluationTools', () => { assert.deepStrictEqual({ waitsForApprovalObserver: tool.getToolData().canRequestPreApproval, confirmed: !!prepared.confirmationMessages, + originatingChat: options.originatingChatResource?.toString(), workspace: options.workspace?.toString(), branch: options.branch, prompt: options.prompt, models: options.attempts.map(attempt => [attempt.harness.modelId, attempt.harness.modelConfiguration, attempt.harness.permissionId]), judge: options.judgeHarness?.modelId, nestedSource: fixture.permissionChats.every(resource => isEqual(resource, callerResource)), }, { - waitsForApprovalObserver: true, confirmed: true, workspace: project.toString(), branch: 'main', prompt: input.prompt, + waitsForApprovalObserver: true, confirmed: true, originatingChat: callerResource.toString(), workspace: project.toString(), branch: 'main', prompt: input.prompt, models: [['model', { thinkingLevel: 'high' }, 'default'], ['model', { thinkingLevel: 'high' }, 'default']], judge: 'model', nestedSource: true, }); }); + test('returns a persistent keyboard-operable link to the launched comparison without opening it', async () => { + const fixture = setup(); + const output = await invoke(fixture.tool('createModelComparison'), launchInput(), true); + assert.ok(isMarkdownString(output.toolResultMessage)); + const message: IMarkdownString = JSON.parse(JSON.stringify(output.toolResultMessage)); + const opened: { command: string; args: string[] }[] = []; + const rendered = store.add(renderMarkdown(message, { + ...getChatMarkdownRenderOptions(), + actionHandler: href => { + const command = URI.parse(href); + opened.push({ command: command.path, args: JSON.parse(decodeURIComponent(command.query)) }); + }, + })); + mainWindow.document.body.appendChild(rendered.element); + store.add(toDisposable(() => rendered.element.remove())); + const link = rendered.element.querySelector('a'); + assert.ok(link); + const initiallyOpened = [...opened]; + link.focus(); + link.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + link.dispatchEvent(new mainWindow.MouseEvent('click', { bubbles: true, cancelable: true, button: 0 })); + assert.deepStrictEqual({ + trusted: message.isTrusted, + label: link.textContent, + focused: mainWindow.document.activeElement === link, + initiallyOpened, + opened, + comparisonId: JSON.parse(text(output)).comparisonId, + }, { + trusted: { enabledCommands: [OPEN_SESSION_COMPARISON_COMMAND_ID] }, + label: 'Open Comparison', + focused: true, + initiallyOpened: [], + opened: Array(2).fill({ command: OPEN_SESSION_COMPARISON_COMMAND_ID, args: ['comparison'] }), + comparisonId: 'comparison', + }); + }); + test('preserves a nested caller workspace under a quick-chat parent', async () => { const fixture = setup({ quickChat: true }); fixture.provider.getSessionOwnConfig = () => ({ @@ -555,9 +602,9 @@ suite('ModelEvaluationTools', () => { const fixture = setup(); fixture.comparisons.set(Array.from({ length: 27 }, (_, index) => comparison({ id: `c${index}`, createdAt: index, archivedAt: index === 26 ? 1 : undefined })), undefined); const tool = fixture.tool('listModelComparisons'); - const first: { comparisons: { comparisonId: string }[]; nextCursor: string } = JSON.parse(text(await invoke(tool, {}))); - const second: { comparisons: { comparisonId: string }[] } = JSON.parse(text(await invoke(tool, { cursor: first.nextCursor }))); - const archived: { comparisons: { comparisonId: string }[] } = JSON.parse(text(await invoke(tool, { comparisonIds: ['c26'], includeArchived: true }))); + const first: { comparisons: { comparisonId: string }[]; nextCursor: string } = JSON.parse(text(await invoke(tool, { scope: 'window' }))); + const second: { comparisons: { comparisonId: string }[] } = JSON.parse(text(await invoke(tool, { scope: 'window', cursor: first.nextCursor }))); + const archived: { comparisons: { comparisonId: string }[] } = JSON.parse(text(await invoke(tool, { scope: 'window', comparisonIds: ['c26'], includeArchived: true }))); assert.deepStrictEqual({ first: first.comparisons.map(item => item.comparisonId), second: second.comparisons.map(item => item.comparisonId), archived: archived.comparisons.map(item => item.comparisonId), @@ -566,15 +613,60 @@ suite('ModelEvaluationTools', () => { }); }); - test('lists comparisons without a caller or rendering context', async () => { + test('requires explicit window scope when listing without a caller or rendering context', async () => { const fixture = setup(); fixture.comparisons.set([comparison()], undefined); - const output = await fixture.tool('listModelComparisons').invoke({ - callId: 'call', toolId: 'test', parameters: {}, context: undefined, + const tool = fixture.tool('listModelComparisons'); + const invokeWithoutCaller = (parameters: Record) => tool.invoke({ + callId: 'call', toolId: 'test', parameters, context: undefined, }, async () => 0, progress, CancellationToken.None); - assert.strictEqual(output.toolResultError, undefined); - const page: { comparisons: { comparisonId: string }[] } = JSON.parse(text(output)); - assert.deepStrictEqual(page.comparisons.map(item => item.comparisonId), ['comparison']); + const unscoped = await invokeWithoutCaller({}); + const window = await invokeWithoutCaller({ scope: 'window' }); + const page: { comparisons: { comparisonId: string }[] } = JSON.parse(text(window)); + assert.deepStrictEqual({ + unscopedError: unscoped.toolResultError, + windowError: window.toolResultError, + comparisons: page.comparisons.map(item => item.comparisonId), + }, { + unscopedError: 'The calling chat is unavailable. Use scope "window" to discover comparisons across this Agents window.', + windowError: undefined, + comparisons: ['comparison'], + }); + }); + + test('defaults to the exact initiating chat even when another chat ran the same prompt more recently', async () => { + const fixture = setup(); + const otherChat = callerResource.with({ fragment: 'other' }); + fixture.comparisons.set([ + comparison({ id: 'mine', createdAt: 1, originatingChatResource: callerResource }), + comparison({ id: 'other', createdAt: 2, originatingChatResource: otherChat }), + comparison({ id: 'manual', createdAt: 3 }), + comparison({ id: 'archived', createdAt: 4, originatingChatResource: callerResource, archivedAt: 1 }), + ], undefined); + const tool = fixture.tool('listModelComparisons'); + const list = async (parameters: Record, originatingChatResource = callerResource) => { + const output = await tool.invoke({ + callId: 'call', toolId: 'test', parameters, originatingChatResource, + context: { sessionResource: otherChat }, + }, async () => 0, progress, CancellationToken.None); + const page: { comparisons: { comparisonId: string; originatingChatResource?: string }[] } = JSON.parse(text(output)); + return page.comparisons.map(item => [item.comparisonId, item.originatingChatResource]); + }; + assert.deepStrictEqual({ + mine: await list({}), + other: await list({}, otherChat), + archived: await list({ includeArchived: true }), + explicitIds: await list({ comparisonIds: ['other'] }), + window: await list({ scope: 'window' }), + invalidScope: (await invoke(tool, { scope: 'unknown' })).toolResultError, + }, { + mine: [['mine', callerResource.toString()]], + other: [['other', otherChat.toString()]], + archived: [['archived', callerResource.toString()], ['mine', callerResource.toString()]], + explicitIds: [], + window: [['manual', undefined], ['other', otherChat.toString()], ['mine', callerResource.toString()]], + invalidScope: 'Invalid comparison list filters.', + }); }); test('discovers and reads comparisons with the authoritative caller independently of rendering context', async () => { diff --git a/src/vs/sessions/contrib/sessionComparison/test/browser/sessionComparisonTool.test.ts b/src/vs/sessions/contrib/sessionComparison/test/browser/sessionComparisonTool.test.ts index 1166751c11f9..3f2589597a20 100644 --- a/src/vs/sessions/contrib/sessionComparison/test/browser/sessionComparisonTool.test.ts +++ b/src/vs/sessions/contrib/sessionComparison/test/browser/sessionComparisonTool.test.ts @@ -343,6 +343,100 @@ suite('SessionComparisonTool', () => { }); }); + test('authorizes headless Judge and synthesis calls by their exact originating chats', async () => { + const base = stubComparison(); + const parentResource = URI.parse('test:/parent'); + const judgeChat = parentResource.with({ fragment: 'judge' }); + const synthesisChat = parentResource.with({ fragment: 'synthesis' }); + const comparison: ISessionComparison = { + ...base, + participants: [...base.participants.map(participant => participant.role === SessionComparisonParticipantRole.Judge + ? { ...participant, sessionResource: parentResource, chatResource: judgeChat } + : participant), { + id: 'synthesis', + role: SessionComparisonParticipantRole.Synthesis, + harness: base.judgeHarness!, + sessionResource: parentResource, + chatResource: synthesisChat, + }], + }; + let submitted: ISessionComparisonVerdict | undefined; + const service = stubComparisonService({ + getComparison: () => comparison, + submitVerdict: (_id, verdict) => submitted = verdict, + }); + const readTool = new ReadSessionComparisonTool(service, upcastPartial({ getSession: () => undefined })); + const completeTool = new CompleteSessionComparisonTool(service); + const judgeManifest = await invoke(readTool, { comparisonId: comparison.id }, undefined, judgeChat); + const synthesisManifest = await invoke(readTool, { comparisonId: comparison.id }, undefined, synthesisChat); + const verdict = await invoke(completeTool, verdictInput(), undefined, judgeChat); + const synthesisDenied = await invoke(completeTool, verdictInput(), undefined, synthesisChat); + + assert.deepStrictEqual({ + judgeManifest: JSON.parse(getText(judgeManifest)).comparisonId, + synthesisManifest: JSON.parse(getText(synthesisManifest)).comparisonId, + verdict: JSON.parse(getText(verdict)), + recommended: submitted?.recommendedParticipantId, + synthesisDenied: getText(synthesisDenied), + }, { + judgeManifest: comparison.id, + synthesisManifest: comparison.id, + verdict: { status: 'submitted', comparisonId: comparison.id }, + recommended: 'attempt', + synthesisDenied: 'Only the judge session for this comparison can submit its verdict.', + }); + }); + + for (const scenario of [ + { name: 'headless attempt', origin: attemptResource, context: undefined }, + { name: 'headless foreign chat', origin: URI.parse('test:/foreign-judge'), context: undefined }, + { name: 'missing caller', origin: undefined, context: undefined }, + { name: 'attempt with Judge presentation context', origin: attemptResource, context: judgeResource }, + { name: 'foreign chat with Judge presentation context', origin: URI.parse('test:/foreign-judge'), context: judgeResource }, + ]) { + test(`rejects unauthorized originating chats: ${scenario.name}`, async () => { + const comparison = stubComparison(); + let submitted = false; + const service = stubComparisonService({ + getComparison: () => comparison, + submitVerdict: () => submitted = true, + }); + const readTool = new ReadSessionComparisonTool(service, upcastPartial({})); + const completeTool = new CompleteSessionComparisonTool(service); + + assert.deepStrictEqual({ + read: getText(await invoke(readTool, { comparisonId: comparison.id }, scenario.context, scenario.origin)), + complete: getText(await invoke(completeTool, verdictInput(), scenario.context, scenario.origin)), + submitted, + }, { + read: 'Only the Judge or synthesis session for this comparison can read its manifest.', + complete: 'Only the judge session for this comparison can submit its verdict.', + submitted: false, + }); + }); + } + + test('uses the originating Judge chat instead of a different presentation context', async () => { + const comparison = stubComparison(); + let submitted = false; + const service = stubComparisonService({ + getComparison: () => comparison, + submitVerdict: () => submitted = true, + }); + const readTool = new ReadSessionComparisonTool(service, upcastPartial({ getSession: () => undefined })); + const completeTool = new CompleteSessionComparisonTool(service); + + assert.deepStrictEqual({ + read: JSON.parse(getText(await invoke(readTool, { comparisonId: comparison.id }, attemptResource, judgeResource))).comparisonId, + complete: JSON.parse(getText(await invoke(completeTool, verdictInput(), attemptResource, judgeResource))), + submitted, + }, { + read: comparison.id, + complete: { status: 'submitted', comparisonId: comparison.id }, + submitted: true, + }); + }); + for (const scenario of [ { name: 'changed model', initialModelId: 'original', currentModelId: 'replacement', sessionAvailable: true, differs: true }, { name: 'unchanged model', initialModelId: 'original', currentModelId: 'original', sessionAvailable: true, differs: false }, @@ -628,7 +722,7 @@ suite('SessionComparisonTool', () => { }], }, judgeResource); - assert.strictEqual(getText(result), 'The comparison verdict input is invalid. Keep explanation to one sentence, provide concise comparison, validation, codeQuality, and solution rationale points, and use a consistent state and source pair for every validation category.'); + assert.strictEqual(getText(result), 'The comparison verdict input is invalid. attempts[0].validation.tests must pair passed/failed with attemptReport/judgeRun, notRun/unknown with attemptReport/judgeRun/unavailable, or notApplicable with notApplicable.'); }); test('records automatic review evidence provenance in the verdict', async () => { @@ -720,10 +814,94 @@ suite('SessionComparisonTool', () => { }], }, judgeResource); - assert.strictEqual(getText(result), 'The comparison verdict input is invalid. Keep explanation to one sentence, provide concise comparison, validation, codeQuality, and solution rationale points, and use a consistent state and source pair for every validation category.'); + assert.strictEqual(getText(result), 'The comparison verdict input is invalid. rationale.solution must be a non-empty, single-line string of at most 180 characters.'); + }); + + for (const scenario of [ + { field: 'explanation', value: 'x'.repeat(241), expected: 'explanation must be a non-empty, single-line string of at most 240 characters.' }, + { field: 'explanation', value: ' \t ', expected: 'explanation must be a non-empty, single-line string of at most 240 characters.' }, + { field: 'explanation', value: 'First line.\nSecond line.', expected: 'explanation must be a non-empty, single-line string of at most 240 characters.' }, + ...['comparison', 'validation', 'codeQuality', 'solution'].map(category => ({ + field: 'rationale', value: { ...rationaleInput(), [category]: undefined }, + expected: `rationale.${category} must be a non-empty, single-line string of at most 180 characters.`, + })), + { field: 'conflicts', value: [false], expected: 'conflicts[0] must be a string.' }, + { field: 'attempts', value: undefined, expected: 'attempts must be an array with one finding per attemptNumber from readAttemptComparison.' }, + { field: 'decisionSections', value: [], expected: 'decisionSections is not supported; remove it and use rationale.' }, + ]) { + test(`reports malformed verdict field: ${scenario.expected}`, async () => { + const tool = new CompleteSessionComparisonTool(stubComparisonService({})); + const result = await invoke(tool, { ...verdictInput(), [scenario.field]: scenario.value }, judgeResource); + + assert.strictEqual(getText(result), `The comparison verdict input is invalid. ${scenario.expected}`); + }); + } + + for (const scenario of [ + { field: 'unresolvedIssues', value: undefined, expected: 'attempts[0].unresolvedIssues must be an array of strings; use [] when there are none.' }, + { field: 'unresolvedIssues', value: 'None', expected: 'attempts[0].unresolvedIssues must be an array of strings; use [] when there are none.' }, + { field: 'unresolvedIssues', value: ['Valid issue', null], expected: 'attempts[0].unresolvedIssues[1] must be a string.' }, + { field: 'notableDifferences', value: {}, expected: 'attempts[0].notableDifferences must be an array of strings; use [] when there are none.' }, + ...['tests', 'build', 'lint', 'diagnostics'].map(category => ({ + field: 'validation', + value: { ...verdictInput().attempts[0].validation, [category]: { state: 'passed', source: 'unavailable' } }, + expected: `attempts[0].validation.${category} must pair passed/failed with attemptReport/judgeRun, notRun/unknown with attemptReport/judgeRun/unavailable, or notApplicable with notApplicable.`, + })), + ]) { + test(`reports malformed attempt field: ${scenario.expected}`, async () => { + const tool = new CompleteSessionComparisonTool(stubComparisonService({})); + const input = verdictInput(); + const result = await invoke(tool, { + ...input, + attempts: [{ ...input.attempts[0], [scenario.field]: scenario.value }], + }, judgeResource); + + assert.strictEqual(getText(result), `The comparison verdict input is invalid. ${scenario.expected}`); + }); + } + + test('accepts concise verdict strings at the schema length limits', async () => { + const comparison = stubComparison(); + let submitted: ISessionComparisonVerdict | undefined; + const tool = new CompleteSessionComparisonTool(stubComparisonService({ + getComparison: () => comparison, + submitVerdict: (_id, verdict) => submitted = verdict, + })); + const result = await invoke(tool, { + ...verdictInput(), + explanation: 'x'.repeat(240), + rationale: { comparison: 'x'.repeat(180), validation: 'x'.repeat(180), codeQuality: 'x'.repeat(180), solution: 'x'.repeat(180) }, + }, judgeResource); + + assert.deepStrictEqual({ + result: JSON.parse(getText(result)), + explanationLength: submitted?.explanation.length, + rationaleLengths: Object.values(submitted?.rationale ?? {}).map(point => point.length), + }, { + result: { status: 'submitted', comparisonId: comparison.id }, + explanationLength: 240, + rationaleLengths: [180, 180, 180, 180], + }); }); }); +function verdictInput() { + return { + comparisonId: 'comparison', + recommendedAttemptNumber: 1, + explanation: 'The implementation is correct and focused.', + rationale: rationaleInput(), + conflicts: [], + attempts: [{ + attemptNumber: 1, + summary: 'Focused implementation with passing tests.', + validation: { tests: passedEvidence(), build: passedEvidence(), lint: passedEvidence(), diagnostics: passedEvidence() }, + unresolvedIssues: [], + notableDifferences: [], + }], + }; +} + function passedEvidence() { return { state: SessionComparisonValidationState.Passed, @@ -796,12 +974,13 @@ function stubAttemptSession(): ISession { }); } -async function invoke(tool: ReadSessionComparisonTool | CompleteSessionComparisonTool, parameters: Record, sessionResource: URI): Promise { +async function invoke(tool: ReadSessionComparisonTool | CompleteSessionComparisonTool, parameters: Record, sessionResource: URI | undefined, originatingChatResource?: URI): Promise { return tool.invoke({ callId: 'call', toolId: 'tool', parameters, - context: { sessionResource }, + originatingChatResource, + context: sessionResource ? { sessionResource } : undefined, }, async () => 0, progress, CancellationToken.None); } diff --git a/src/vs/sessions/contrib/sessionInputBanners/browser/media/sessionWorktreeCleanupEditor.css b/src/vs/sessions/contrib/sessionInputBanners/browser/media/sessionWorktreeCleanupEditor.css index ed0daa6abc02..5f2f4a596168 100644 --- a/src/vs/sessions/contrib/sessionInputBanners/browser/media/sessionWorktreeCleanupEditor.css +++ b/src/vs/sessions/contrib/sessionInputBanners/browser/media/sessionWorktreeCleanupEditor.css @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ .session-worktree-cleanup-editor { + position: relative; height: 100%; overflow: hidden; } @@ -26,49 +27,30 @@ display: flow-root; } -.session-worktree-cleanup-intro, .session-worktree-cleanup-automatic > p { color: var(--vscode-descriptionForeground); } -.session-worktree-cleanup-intro h2 { - color: var(--vscode-foreground); - font-size: var(--vscode-fontSize-heading2); - font-weight: var(--vscode-fontWeight-semiBold); - margin: 0 0 var(--vscode-spacing-size80); -} - -.session-worktree-cleanup-intro p { - margin: 0; - line-height: 1.4; +.session-worktree-cleanup-measurement-progress { + position: absolute; + top: 0; + left: 0; + right: 0; } .session-worktree-cleanup-controls { display: flex; align-items: center; - flex-wrap: wrap; gap: var(--vscode-spacing-size80); - margin: var(--vscode-spacing-size200) 0 var(--vscode-spacing-size120); + margin-left: auto; } -.session-worktree-cleanup-controls label, .session-worktree-cleanup-setting { display: flex; align-items: center; gap: var(--vscode-spacing-size80); } -.session-worktree-cleanup-controls label { - cursor: default; -} - -.session-worktree-cleanup-controls select { - cursor: pointer; - max-width: 100%; - min-width: 0; -} - -.session-worktree-cleanup-controls select, .session-worktree-cleanup-setting input[type="number"] { color: var(--vscode-input-foreground); background: var(--vscode-input-background); @@ -77,6 +59,13 @@ padding: var(--vscode-spacing-size40) var(--vscode-spacing-size60); } +.session-worktree-cleanup-controls.age-filtered .session-worktree-cleanup-age, +.session-worktree-cleanup-controls.workspace-filtered .session-worktree-cleanup-workspace { + color: var(--vscode-inputOption-activeForeground); + background: var(--vscode-inputOption-activeBackground); + outline: var(--vscode-strokeThickness) solid var(--vscode-inputOption-activeBorder); +} + .session-worktree-cleanup-summary-row { display: flex; align-items: center; @@ -112,22 +101,6 @@ flex-shrink: 0; } -.session-worktree-cleanup-info { - display: inline-flex; - align-items: center; - justify-content: center; - padding: 0; - color: var(--vscode-descriptionForeground); - background: transparent; - border: 0; - cursor: pointer; -} - -.session-worktree-cleanup-info:focus-visible { - outline: var(--vscode-focusBorder) solid var(--vscode-strokeThickness); - outline-offset: var(--vscode-strokeThickness); -} - .session-worktree-cleanup-list { flex: 1; min-height: 0; @@ -137,6 +110,8 @@ } .session-worktree-cleanup-summary-row.hidden, +.session-worktree-cleanup-summary.hidden, +.session-worktree-cleanup-action.hidden, .session-worktree-cleanup-progress.hidden, .session-worktree-cleanup-available-heading.hidden, .session-worktree-cleanup-list.hidden, @@ -229,6 +204,8 @@ } .session-worktree-cleanup-session-link { + align-self: flex-start; + max-width: 100%; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; @@ -283,14 +260,6 @@ color: var(--vscode-descriptionForeground); } -.session-worktree-cleanup-automatic > summary:hover { - background: var(--vscode-toolbar-hoverBackground); -} - -.session-worktree-cleanup-automatic > summary:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); -} - .session-worktree-cleanup-setting { min-height: 36px; } diff --git a/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupAccessibilityHelp.ts b/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupAccessibilityHelp.ts index d9cd3b06794d..7a6a1ea218fb 100644 --- a/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupAccessibilityHelp.ts +++ b/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupAccessibilityHelp.ts @@ -26,15 +26,15 @@ export class SessionWorktreeCleanupAccessibilityHelp implements IAccessibleViewI const previouslyFocused = getActiveElement(); const content: string[] = [ localize('sessionWorktreeCleanupHelp.allWorktreesOverview', "You are in the Worktree Cleanup editor. It lists local agent session worktrees with an available cleanup action, plus worktrees being measured or cleaned up and confirmed removals from this editor. Remote worktrees and other worktrees that cannot currently be cleaned up are hidden. Normal cleanup commits uncommitted changes before removing a worktree. Cleaning up a session marks it as done; you can restore the session later to recreate its worktree from committed changes."), - localize('sessionWorktreeCleanupHelp.workspaceAndAgeFilters', "Use the Untouched For selector to filter by inactivity starting at one day, or choose Any time to include sessions used today. When worktrees belong to multiple workspaces, use the Workspace selector to show one workspace or All workspaces. Filters limit both the table and cleanup selection. Changing workspace clears the selection."), - localize('sessionWorktreeCleanupHelp.activeMeasurementProgress', "A status line above the results reports the number of worktrees processed out of the scan total, independently of the filters. Sessions marked as done are not measured and are excluded from the scan total. Failed measurements count as processed. The final count remains visible when the scan completes."), + localize('sessionWorktreeCleanupHelp.workspaceAndAgeMenus', "Use the Filter by Inactivity menu above the table to filter by inactivity starting at one day, or choose Any Time to include sessions used today. When worktrees belong to multiple workspaces, use the Filter by Workspace menu to show one workspace or All Workspaces. The menu buttons announce the current choices, and the active options are checked in each menu. Use Tab to reach the toolbar, arrow keys to move between its buttons, and Enter or Space to open a menu. Escape closes it. Filters limit both the table and cleanup selection. Changing workspace clears the selection. Filters remain available when no worktrees match."), + localize('sessionWorktreeCleanupHelp.activeMeasurementProgress', "A progress indicator is shown while worktree storage is being measured and disappears when the scan completes. You can select worktrees and start cleanup without waiting for size estimates. Sessions marked as done are not measured."), localize('sessionWorktreeCleanupHelp.cachedActiveSizes', "Supported hosts save worktree sizes in the session database. Opening or refreshing cleanup reuses unchanged idle sizes and measures new, changed, or active worktrees. Done sessions are excluded from disk scans; their cleanup status can still be refreshed. Automatic storage hint checks use the same saved sizes and are limited to once an hour through existing triggers, without a recurring timer."), - localize('sessionWorktreeCleanupHelp.storageStates', "Disk usage shows an estimate, Measuring, Not measured, or Measurement failed. Done sessions and worktrees without a listed session are intentionally not measured. Mixed selections report known storage and the number of unmeasured worktrees, not a complete estimate. Disk usage is not guaranteed freed space."), - localize('sessionWorktreeCleanupHelp.inventory', "One table lists actionable worktrees, pending cleanup, and confirmed removals. Each row has a title or branch, workspace, last session activity, disk usage, and status. Checkout paths are available in title tooltips and row announcements. Nothing is selected automatically. Select rows using their checkboxes, then activate Clean Up Worktrees to clean up the selection. Worktrees without a listed session have no session activity date. The Select All checkbox in the first column header includes every matching selectable worktree, including off-screen rows. It is mixed when some worktrees are selected. Use Tab to focus it and Space to select all or clear the selection."), - localize('sessionWorktreeCleanupHelp.sorting', "The table defaults to Session Recency, oldest first, with worktrees without a session date last. Use Sort by to choose Session Recency, oldest or newest first, Size, largest first, or Status. Status orders sessions marked as done with a remaining worktree first, then worktrees without a matching session, other sessions with a worktree, and confirmed removed worktrees last. Within each status group, larger known sizes come first. Done sessions are labeled Session marked as done, alongside any cleanup progress. Sorting preserves your checkbox choices and does not rescan storage. Rows stay in place while a cleanup batch runs so you can track its progress."), + localize('sessionWorktreeCleanupHelp.storageStates', "Disk usage shows an estimate, Measuring, Not measured, or Measurement failed. During cleanup, the last known estimate remains unchanged, or Pending removal is shown if no estimate was available. Once removal is confirmed, disk usage shows zero. Done sessions and worktrees without a listed session are intentionally not measured. Mixed selections report known storage and the number of unmeasured worktrees, not a complete estimate. Disk usage is not guaranteed freed space."), + localize('sessionWorktreeCleanupHelp.inventory', "One table lists actionable worktrees, pending cleanup, and confirmed removals. Sessions sharing a checkout are grouped so worktrees are counted once. Cleanup marks all associated sessions as done, and activity uses the most recently updated session. Each row has a title or branch, workspace, last session activity, disk usage, and status. Checkout paths are available in title tooltips and row announcements. Nothing is selected automatically. Select rows using their checkboxes or by clicking outside the session link, then activate Clean Up Worktrees. Worktrees without a listed session have no session activity date. The Select All checkbox in the first column header includes every matching selectable worktree, including off-screen rows. It is mixed when some worktrees are selected. Use Tab to focus it and Space to select all or clear the selection."), + localize('sessionWorktreeCleanupHelp.sortMenu', "The table defaults to Session Recency, oldest first, with worktrees without a session date last. Use the Sort Worktrees menu to choose Session Recency, oldest or newest first, Size, largest first, or Status. The current sort order is checked. Status orders sessions marked as done with a remaining worktree first, then worktrees without a matching session, other sessions with a worktree, and confirmed removed worktrees last. Within each status group, larger known sizes come first. Done sessions are labeled Session marked as done, alongside any cleanup progress. Sorting preserves your checkbox choices and does not rescan storage. Rows stay in place while a cleanup batch runs so you can track its progress."), localize('sessionWorktreeCleanupHelp.managedWorktrees', "Only managed agent worktrees are eligible, including agent branches created with a configured prefix. Failed and blocked worktrees are hidden, and failure counts are not shown. Errors are still reported through notifications and logs. Hiding a worktree does not confirm its files were removed. The host retains its background cleanup records and safety checks. All worktrees require explicit selection, including worktrees without a listed session. Explicit checkbox choices survive updates and age-filter changes."), localize('sessionWorktreeCleanupHelp.inventoryNavigation', "The inventory has one vertical scroll area. Columns can be resized; headers and rows scroll horizontally together in narrow windows. Only nearby rows are rendered. Use {0} and {1} for rows, {2} and {3} for pages, and {4} and {5} for the first and last rows. Use {6} to open the focused session and Space to toggle its checkbox. Tab reaches the focused row's checkbox and session link. Row announcements include position, checkout path, activity, storage, and cleanup status.", '', '', '', '', '', '', ''), - localize('sessionWorktreeCleanupHelp.cleanupDiskUsage', "Activate Clean Up Worktrees to schedule removal of the selected sessions' worktrees and mark those sessions as done after confirmation. It is disabled until at least one session is selected. Its label reports the selected worktree count and, when every selected session has a size estimate, their estimated disk usage."), + localize('sessionWorktreeCleanupHelp.cleanupDiskUsage', "Activate Clean Up Worktrees to schedule removal of the selected sessions' worktrees and mark those sessions as done after confirmation. It is disabled until at least one worktree is selected. Its label reports the selected worktree count, and its accessible label includes known disk usage estimates. Disk usage is only an estimate, not guaranteed freed space."), localize('sessionWorktreeCleanupHelp.batchLifecycle', "Confirmed cleanup continues when this editor closes. Reopening reconnects to queued and pending requests without showing failed requests. Closing does not cancel accepted host removals. Pending work cannot be submitted twice, and one scheduling failure does not stop the rest of the batch. The batch summary reports only pending work and confirmed removals, independently of filters. Rows update in place as cleanup progresses. Confirmed removals remain visible with zero disk usage, no checkbox or cleanup action, and usable session links until this editor closes."), localize('sessionWorktreeCleanupHelp.failedCleanup', "Failed worktrees do not reappear with repeated Retry or Force Remove actions. Refresh inventory to check current host state. A failed or unavailable existence check is not confirmed removal."), localize('sessionWorktreeCleanupHelp.collapsedSettings', "Automatic Cleanup is collapsed above the inventory. Focus its gear-labeled heading and press Enter or Space to expand it. In short windows, the controls and settings scroll separately above the inventory, without scrolling the inventory inside either area. Changes are saved immediately. Checkboxes enable automatic completion or deletion of merged pull request sessions; adjacent inputs set retention days. Another checkbox controls storage cleanup suggestions."), diff --git a/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupEditor.ts b/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupEditor.ts index 8da5fec8a67e..0d123189f7bd 100644 --- a/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupEditor.ts +++ b/src/vs/sessions/contrib/sessionInputBanners/browser/sessionWorktreeCleanupEditor.ts @@ -6,12 +6,15 @@ import * as dom from '../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js'; import { Button } from '../../../../base/browser/ui/button/button.js'; +import { DropdownMenuActionViewItem } from '../../../../base/browser/ui/dropdown/dropdownActionViewItem.js'; import { getDefaultHoverDelegate } from '../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { renderIcon } from '../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { ProgressBar } from '../../../../base/browser/ui/progressbar/progressbar.js'; import { DomScrollableElement } from '../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { ITableColumn, ITableRenderer } from '../../../../base/browser/ui/table/table.js'; import { Checkbox, TriStateCheckbox } from '../../../../base/browser/ui/toggle/toggle.js'; import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { Action, IAction, toAction } from '../../../../base/common/actions.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { RunOnceScheduler } from '../../../../base/common/async.js'; import { fromNow } from '../../../../base/common/date.js'; @@ -25,14 +28,17 @@ import { ScrollbarVisibility } from '../../../../base/common/scrollable.js'; import { ThemeIcon } from '../../../../base/common/themables.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { ByteSize } from '../../../../platform/files/common/files.js'; +import { WorkbenchToolBar } from '../../../../platform/actions/browser/toolbar.js'; +import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { IEditorOptions } from '../../../../platform/editor/common/editor.js'; import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { ILabelService } from '../../../../platform/label/common/label.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { RawWorkbenchListFocusContextKey, WorkbenchTable } from '../../../../platform/list/browser/listService.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; -import { defaultButtonStyles, defaultCheckboxStyles } from '../../../../platform/theme/browser/defaultStyles.js'; +import { defaultButtonStyles, defaultCheckboxStyles, defaultProgressBarStyles } from '../../../../platform/theme/browser/defaultStyles.js'; import { IThemeService } from '../../../../platform/theme/common/themeService.js'; import { IStorageService } from '../../../../platform/storage/common/storage.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; @@ -43,7 +49,7 @@ import { IEditorGroup } from '../../../../workbench/services/editor/common/edito import { ChatConfiguration } from '../../../../workbench/contrib/chat/common/constants.js'; import { SessionWorktreeCleanupEditorFocusedContext } from '../../../../workbench/contrib/sessions/common/contextkeys.js'; import { ISessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; -import { AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING, CLEANUP_THRESHOLD_BYTES, CLEANUP_THRESHOLD_WORKTREES, getWorktreeCleanupDiskUsage, getWorktreeCleanupId, getWorktreeCleanupTitle, ISessionWorktree, ISessionWorktreeCleanupCandidate, ISessionWorktreeCleanupService, ISessionWorktreeMeasurementProgress, isWorktreeCleanupBranchSupported, SessionWorktreeCleanupProgress, SessionWorktreeCleanupState } from '../../../../workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.js'; +import { AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING, CLEANUP_THRESHOLD_BYTES, CLEANUP_THRESHOLD_WORKTREES, getWorktreeCleanupDiskUsage, getWorktreeCleanupId, getWorktreeCleanupLastActivity, getWorktreeCleanupSessions, getWorktreeCleanupTitle, ISessionWorktree, ISessionWorktreeCleanupCandidate, ISessionWorktreeCleanupService, ISessionWorktreeMeasurementProgress, isWorktreeCleanupBranchSupported, SessionWorktreeCleanupProgress, SessionWorktreeCleanupState } from '../../../../workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.js'; import { SessionWorktreeCleanupEditorInput } from './sessionWorktreeCleanupEditorInput.js'; import './media/sessionWorktreeCleanupEditor.css'; @@ -65,6 +71,9 @@ function getWorktreeStatusOrder(worktree: ISessionWorktree): number { } function getWorktreeSessionLabel(worktree: ISessionWorktree): string { + if (worktree.sessions && worktree.sessions.length > 1) { + return localize('sessionWorktreeCleanup.sharedSessions', "{0} sessions", worktree.sessions.length); + } return worktree.session ? worktree.session.isArchived.get() || worktree.cleanupState === 'archived' ? localize('sessionWorktreeCleanup.sessionMarkedAsDone', "Session marked as done") @@ -72,9 +81,9 @@ function getWorktreeSessionLabel(worktree: ISessionWorktree): string { : localize('sessionWorktreeCleanup.noMatchingSession', "No matching session"); } -function getWorktreePath(worktree: ISessionWorktree): string { - return worktree.unlinkedWorktree ? URI.parse(worktree.unlinkedWorktree.worktree).path - : worktree.session.workspace.get()?.folders.flatMap(folder => folder.gitRepository?.workTreeUri?.path ?? []).join(', ') +function getWorktreePath(worktree: ISessionWorktree, labelService: ILabelService): string { + return worktree.unlinkedWorktree ? labelService.getUriLabel(URI.parse(worktree.unlinkedWorktree.worktree)) + : [...new Set(getWorktreeCleanupSessions(worktree).flatMap(session => session.workspace.get()?.folders.flatMap(folder => folder.gitRepository?.workTreeUri ? [labelService.getUriLabel(folder.gitRepository.workTreeUri)] : []) ?? []))].join(', ') || localize('sessionWorktreeCleanup.pathUnavailable', "Checkout path unavailable"); } @@ -127,13 +136,20 @@ export class SessionWorktreeCleanupEditor extends EditorPane { private readonly controlsScrollables: { element: HTMLElement; scrollable: DomScrollableElement }[] = []; private readonly cellHoverOptions = { groupId: generateUuid() }; private selectAllCheckbox: TriStateCheckbox | undefined; - private workspaceOptionsSignature = ''; + private controlsToolbar: WorkbenchToolBar | undefined; + private controls: HTMLElement | undefined; + private hasWorkspaceFilter = false; + private workspaceOptions: { key: string; label: string }[] = []; + private readonly ageFilterAction = this._register(new Action('worktreeCleanup.age', localize('sessionWorktreeCleanup.filterByAge', "Filter by Inactivity"), `${ThemeIcon.asClassName(Codicon.filter)} session-worktree-cleanup-age`)); + private readonly workspaceFilterAction = this._register(new Action('worktreeCleanup.workspace', localize('sessionWorktreeCleanup.filterByWorkspace', "Filter by Workspace"), `${ThemeIcon.asClassName(Codicon.folder)} session-worktree-cleanup-workspace`)); + private readonly sortAction = this._register(new Action('worktreeCleanup.sort', localize('sessionWorktreeCleanup.sort', "Sort Worktrees"), `${ThemeIcon.asClassName(Codicon.sortPrecedence)} session-worktree-cleanup-sort`)); private container: HTMLElement | undefined; private list: HTMLElement | undefined; private summary: HTMLElement | undefined; private summaryMessage: HTMLElement | undefined; private summaryRow: HTMLElement | undefined; private measurementProgress: HTMLElement | undefined; + private measurementProgressBar: ProgressBar | undefined; private emptyState: HTMLElement | undefined; private emptyStateMessage: HTMLElement | undefined; private cleanupButton: Button | undefined; @@ -145,8 +161,6 @@ export class SessionWorktreeCleanupEditor extends EditorPane { private refreshRestoredCleanup = false; private isSchedulingCleanup = false; private cleanupGeneration = 0; - private ageSelect: HTMLSelectElement | undefined; - private workspaceSelect: HTMLSelectElement | undefined; private selectedWorkspace = ''; private layoutDimension: dom.Dimension | undefined; private minimumAgeDays = 0; @@ -183,6 +197,8 @@ export class SessionWorktreeCleanupEditor extends EditorPane { @IContextKeyService private readonly contextKeyService: IContextKeyService, @ISessionsService private readonly sessionsService: ISessionsService, @IInstantiationService private readonly instantiationService: IInstantiationService, + @ILabelService private readonly labelService: ILabelService, + @IContextMenuService private readonly contextMenuService: IContextMenuService, ) { super(SessionWorktreeCleanupEditor.ID, group, telemetryService, themeService, storageService); this._register(toDisposable(() => { @@ -200,7 +216,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { } for (const id of this.observedCleanupIds) { const entry = this.cleanupBatch.get(id); - if (!operationIds.has(id) && entry?.candidate.session && !entry.candidate.session.isArchived.read(undefined)) { + if (!operationIds.has(id) && entry && getWorktreeCleanupSessions(entry.candidate).some(session => !session.isArchived.read(undefined))) { this.cleanupBatch.delete(id); this.restoredCleanupIds.delete(id); this.cleaningSessionIds.delete(id); @@ -235,65 +251,27 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.editorDisposables.add(toDisposable(() => focusedContext.reset())); parent.appendChild(this.container); const content = dom.append(this.container, dom.$('.session-worktree-cleanup-content')); + this.renderAutomaticCleanup(this.createControlsScrollable(content)); const controlsContent = this.createControlsScrollable(content); - const intro = dom.append(controlsContent, dom.$('.session-worktree-cleanup-intro')); - dom.append(intro, dom.$('h2', undefined, localize('sessionWorktreeCleanup.introHeading', "Free up local disk space"))); - dom.append(intro, dom.$('p', undefined, localize('sessionWorktreeCleanup.introSelection', "Select sessions to clean up their worktrees."))); - - const controls = dom.append(controlsContent, dom.$('.session-worktree-cleanup-controls')); - const ageLabel = dom.append(controls, dom.$('label', undefined, localize('sessionWorktreeCleanup.ageLabel', "Untouched for"))); - const ageSelect = dom.append(ageLabel, dom.$('select.session-worktree-cleanup-age')) as HTMLSelectElement; - this.ageSelect = ageSelect; - for (const days of MINIMUM_AGE_OPTIONS) { - const option = dom.append(ageSelect, dom.$('option')) as HTMLOptionElement; - option.value = String(days); - option.textContent = days === 0 - ? localize('sessionWorktreeCleanup.anyTime', "Any time") - : days === 1 - ? localize('sessionWorktreeCleanup.oneDay', "1 day") - : localize('sessionWorktreeCleanup.days', "{0} days", days); - option.selected = days === this.minimumAgeDays; - } - this.editorDisposables.add(dom.addDisposableListener(ageSelect, dom.EventType.CHANGE, () => { - this.minimumAgeDays = Number(ageSelect.value); - void this.load(); + this.measurementProgress = dom.append(this.container, dom.$('.session-worktree-cleanup-measurement-progress')); + this.measurementProgressBar = this.editorDisposables.add(new ProgressBar(this.measurementProgress, { + ...defaultProgressBarStyles, + ariaLabel: localize('sessionWorktreeCleanup.measuringStorage', "Measuring worktree storage"), })); - const workspaceLabel = dom.append(controls, dom.$('label', undefined, localize('sessionWorktreeCleanup.workspaceLabel', "Workspace"))); - this.workspaceSelect = dom.append(workspaceLabel, dom.$('select.session-worktree-cleanup-workspace')); - this.renderWorkspaceOptions(); - this.editorDisposables.add(dom.addDisposableListener(this.workspaceSelect, dom.EventType.CHANGE, () => { - this.selectedWorkspace = this.workspaceSelect!.value; - this.selectedSessionIds.clear(); - this.renderRows(); - })); - const sortLabel = dom.append(controls, dom.$('label', undefined, localize('sessionWorktreeCleanup.sortBy', "Sort by"))); - const sortSelect = dom.append(sortLabel, dom.$('select.session-worktree-cleanup-sort')); - dom.append(sortSelect, dom.$('option', { value: 'size' }, localize('sessionWorktreeCleanup.largestFirst', "Size (Largest First)"))); - dom.append(sortSelect, dom.$('option', { value: 'oldest' }, localize('sessionWorktreeCleanup.oldestFirst', "Session Recency (Oldest First)"))); - dom.append(sortSelect, dom.$('option', { value: 'recent' }, localize('sessionWorktreeCleanup.recentFirst', "Session Recency (Newest First)"))); - dom.append(sortSelect, dom.$('option', { value: 'status' }, localize('sessionWorktreeCleanup.sortByStatus', "Status"))); - sortSelect.value = this.sortOrder; - this.editorDisposables.add(dom.addDisposableListener(sortSelect, dom.EventType.CHANGE, () => { - this.sortOrder = sortSelect.value === 'status' ? 'status' : sortSelect.value === 'recent' ? 'recent' : sortSelect.value === 'oldest' ? 'oldest' : 'size'; - this.pinnedDisplayOrder = undefined; - this.renderRows(); - })); - this.measurementProgress = dom.append(controlsContent, dom.$('p.session-worktree-cleanup-measurement-progress', { role: 'status', 'aria-live': 'polite' })); dom.hide(this.measurementProgress); const summaryRow = this.summaryRow = dom.append(controlsContent, dom.$('.session-worktree-cleanup-summary-row')); this.summary = dom.append(summaryRow, dom.$('.session-worktree-cleanup-summary')); this.summaryMessage = dom.append(this.summary, dom.$('span', { role: 'status', 'aria-live': 'polite' })); - const eligibilityInfo = dom.append(this.summary, dom.$('button.session-worktree-cleanup-info', { - type: 'button', - 'aria-label': localize('sessionWorktreeCleanup.eligibilityInfo', "Show cleanup eligibility details"), + this.controls = dom.append(summaryRow, dom.$('.session-worktree-cleanup-controls')); + this.controlsToolbar = this.editorDisposables.add(this.instantiationService.createInstance(WorkbenchToolBar, this.controls, { + ariaLabel: localize('sessionWorktreeCleanup.controlsLabel', "Worktree Filters and Sorting"), + actionViewItemProvider: (action, options) => new DropdownMenuActionViewItem(action, { + getActions: () => action === this.ageFilterAction ? this.getAgeActions() : action === this.workspaceFilterAction ? this.getWorkspaceActions() : this.getSortActions(), + }, this.contextMenuService, { ...options, classNames: action.class }), })); - eligibilityInfo.appendChild(renderIcon(Codicon.info)); - const eligibilityHover = this.editorDisposables.add(this.hoverService.setupManagedHover(getDefaultHoverDelegate('element'), eligibilityInfo, localize( - 'sessionWorktreeCleanup.eligibilityDetails', - "Select worktrees, then use Clean Up Worktrees to clean up the selection. Nothing is selected automatically. Failed worktrees and worktrees without an available cleanup action are hidden. Hiding a worktree does not confirm its files were removed. Pending cleanup and completed results remain available for tracking. Done sessions and worktrees without a listed session are not measured. Disk usage is an estimate, not guaranteed freed space.", - ))); - this.editorDisposables.add(dom.addDisposableListener(eligibilityInfo, dom.EventType.CLICK, () => eligibilityHover.show(true))); + this.controlsToolbar.setActions([this.ageFilterAction, this.sortAction]); + this.renderWorkspaceOptions(); this.cleanupButton = this.editorDisposables.add(new Button(summaryRow, defaultButtonStyles)); this.cleanupButton.label = localize('sessionWorktreeCleanup.cleanupButton', "Clean Up Worktrees"); this.cleanupButton.element.classList.add('session-worktree-cleanup-action'); @@ -317,7 +295,6 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.selectedSessionIds = checked ? new Set(selectable.map(worktree => getWorktreeCleanupId(worktree))) : new Set(); this.renderRows(); })); - this.renderAutomaticCleanup(this.createControlsScrollable(content)); this.list = dom.append(content, dom.$('.session-worktree-cleanup-list')); this.mainWorktreeTable = this.createWorktreeTable(this.list, localize('sessionWorktreeCleanup.tableLabel', "Agent session worktrees"), selectAll); this.emptyState = dom.append(content, dom.$('.session-worktree-cleanup-empty', { role: 'status' })); @@ -361,12 +338,69 @@ export class SessionWorktreeCleanupEditor extends EditorPane { showAllWorktrees(): void { this.minimumAgeDays = 0; - if (this.ageSelect) { - this.ageSelect.value = '0'; - } + this.updateFilterLabels(); void this.load(); } + private getAgeActions(): IAction[] { + return MINIMUM_AGE_OPTIONS.map(days => toAction({ + id: `age.${days}`, + label: this.getAgeLabel(days), + checked: days === this.minimumAgeDays, + run: () => { + this.minimumAgeDays = days; + this.updateFilterLabels(); + void this.load(); + }, + })); + } + + private getAgeLabel(days: number): string { + return days === 0 ? localize('sessionWorktreeCleanup.anyTime', "Any Time") + : days === 1 ? localize('sessionWorktreeCleanup.untouchedOneDay', "Untouched for 1 Day") + : localize('sessionWorktreeCleanup.untouchedDays', "Untouched for {0} Days", days); + } + + private getWorkspaceActions(): IAction[] { + return [{ key: '', label: localize('sessionWorktreeCleanup.allWorkspaces', "All Workspaces") }, ...this.workspaceOptions].map(({ key, label }) => toAction({ + id: 'worktreeCleanup.filterWorkspace', + label, + checked: key === this.selectedWorkspace, + run: () => { + this.selectedWorkspace = key; + this.selectedSessionIds.clear(); + this.renderRows(); + }, + })); + } + + private getSortActions(): IAction[] { + return [ + { order: 'size', label: localize('sessionWorktreeCleanup.largestFirst', "Size (Largest First)") }, + { order: 'oldest', label: localize('sessionWorktreeCleanup.oldestFirst', "Session Recency (Oldest First)") }, + { order: 'recent', label: localize('sessionWorktreeCleanup.recentFirst', "Session Recency (Newest First)") }, + { order: 'status', label: localize('sessionWorktreeCleanup.sortByStatus', "Status") }, + ].map(({ order, label }) => toAction({ + id: `sort.${order}`, + label, + checked: order === this.sortOrder, + run: () => { + this.sortOrder = order === 'status' ? 'status' : order === 'recent' ? 'recent' : order === 'oldest' ? 'oldest' : 'size'; + this.pinnedDisplayOrder = undefined; + this.updateFilterLabels(); + this.renderRows(); + }, + })); + } + + private updateFilterLabels(): void { + this.ageFilterAction.label = localize('sessionWorktreeCleanup.ageFilterLabel', "Filter by Inactivity: {0}", this.getAgeLabel(this.minimumAgeDays)); + this.workspaceFilterAction.label = localize('sessionWorktreeCleanup.workspaceFilterLabel', "Filter by Workspace: {0}", this.workspaceOptions.find(option => option.key === this.selectedWorkspace)?.label ?? localize('sessionWorktreeCleanup.allWorkspaces', "All Workspaces")); + this.sortAction.label = localize('sessionWorktreeCleanup.sortLabel', "Sort Worktrees: {0}", this.getSortActions().find(action => action.checked)!.label); + this.controls?.classList.toggle('age-filtered', this.minimumAgeDays !== 0); + this.controls?.classList.toggle('workspace-filtered', this.selectedWorkspace !== ''); + } + override layout(dimension: dom.Dimension): void { this.layoutDimension = dimension; if (this.container) { @@ -428,12 +462,11 @@ export class SessionWorktreeCleanupEditor extends EditorPane { if (this.measurementProgress) { const total = measurementProgress?.totalWorktrees ?? worktrees.reduce((count, worktree) => count + worktree.worktreeCount, 0); const processed = measurementProgress?.scannedWorktrees ?? worktrees.reduce((count, worktree) => count + (worktree.isMeasuring ? 0 : worktree.worktreeCount), 0); - dom.setVisibility(total > 0, this.measurementProgress); - const progress = processed < total - ? localize('sessionWorktreeCleanup.measurementProgress', "Measuring worktree storage: {0} of {1} worktrees processed.", processed, total) - : localize('sessionWorktreeCleanup.measurementComplete', "Worktree storage scan complete: {0} of {1} worktrees processed.", processed, total); - if (this.measurementProgress.textContent !== progress) { - this.measurementProgress.textContent = progress; + dom.setVisibility(processed < total, this.measurementProgress); + if (processed < total) { + this.measurementProgressBar?.infinite(); + } else { + this.measurementProgressBar?.stop(); } } this.updateCleanupBatch(); @@ -447,12 +480,8 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.selectedSessionIds.delete(sessionId); } } - if (this.ageSelect) { - this.ageSelect.disabled = false; - } - if (this.workspaceSelect) { - this.workspaceSelect.disabled = false; - } + this.ageFilterAction.enabled = true; + this.workspaceFilterAction.enabled = true; this.renderRows(); }; // Publish the first and final snapshots immediately; combine intermediate results into @@ -481,12 +510,8 @@ export class SessionWorktreeCleanupEditor extends EditorPane { } }; this.updateMeasuredWorktrees = scheduleUpdate; - if (this.ageSelect) { - this.ageSelect.disabled = true; - } - if (this.workspaceSelect) { - this.workspaceSelect.disabled = true; - } + this.ageFilterAction.enabled = false; + this.workspaceFilterAction.enabled = false; if (this.cleanupButton) { this.cleanupButton.enabled = false; } @@ -499,6 +524,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { dom.hide(this.measurementProgress); } if (this.summaryMessage) { + this.summary?.classList.remove('hidden'); this.summaryMessage.textContent = localize('sessionWorktreeCleanup.loading', "Measuring worktree storage..."); } } @@ -531,11 +557,9 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.notificationService.error(error); } } finally { - if (version === this.renderVersion && !this._store.isDisposed && this.ageSelect) { - this.ageSelect.disabled = false; - if (this.workspaceSelect) { - this.workspaceSelect.disabled = false; - } + if (version === this.renderVersion && !this._store.isDisposed) { + this.ageFilterAction.enabled = true; + this.workspaceFilterAction.enabled = true; this.updateScrollDimensions(); } } @@ -619,7 +643,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { }, )); if (selectAll) { - // eslint-disable-next-line no-restricted-syntax -- Table does not expose a header renderer. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- Table does not expose a header renderer. const selectionHeader = table.getHTMLElement().querySelector('.monaco-table-th[data-col-index="0"]')!; selectionHeader.classList.add('session-worktree-cleanup-select-all'); const headerContext = this.editorDisposables.add(this.contextKeyService.createScoped(selectionHeader)); @@ -629,7 +653,14 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.tableScrollables.set(table, scrollable); this.editorDisposables.add(table.onDidFocus(() => { const activeElement = dom.getActiveElement(); - if (!dom.isHTMLElement(activeElement) || activeElement.parentElement !== table.getHTMLElement()) { + if (!dom.isHTMLElement(activeElement)) { + return; + } + if (activeElement.parentElement !== table.getHTMLElement()) { + const focusedRow = [...this.renderedCells].find(([, cells]) => [...cells.values()].some(cell => cell.container.contains(activeElement))); + if (focusedRow) { + table.setFocus([table.indexOf(focusedRow[0])]); + } return; } this.tableFocusElements.set(table, activeElement); @@ -649,6 +680,15 @@ export class SessionWorktreeCleanupEditor extends EditorPane { this.setWorktreeSelected(worktree, !this.isWorktreeSelected(worktree)); } })); + this.editorDisposables.add(table.onMouseClick(event => { + const target = event.browserEvent.target; + if (event.element && dom.isHTMLElement(target) && !target.closest('a, button, [role="checkbox"]')) { + const worktree = this.displayWorktreesById.get(event.element); + if (worktree) { + this.setWorktreeSelected(worktree, !this.isWorktreeSelected(worktree)); + } + } + })); this.editorDisposables.add(table.onDidOpen(event => { if (event.element && event.browserEvent instanceof dom.getWindow(container).KeyboardEvent && (!event.browserEvent.target || event.browserEvent.target === this.tableFocusElements.get(table))) { const worktree = this.displayWorktreesById.get(event.element)!; @@ -686,10 +726,11 @@ export class SessionWorktreeCleanupEditor extends EditorPane { } private getWorktreeAriaLabel(worktree: ISessionWorktree): string { + const updatedAt = getWorktreeCleanupLastActivity(worktree); return localize('sessionWorktreeCleanup.rowDiskUsageAndSessionLabel', "{0}, workspace {1}, last used {2}, disk usage {3}. {4}. {5} {6}", - localize('sessionWorktreeCleanup.titleAndPath', "{0}, worktree path {1}", getWorktreeCleanupTitle(worktree), getWorktreePath(worktree)), + localize('sessionWorktreeCleanup.titleAndPath', "{0}, worktree path {1}", getWorktreeCleanupTitle(worktree), getWorktreePath(worktree, this.labelService)), getWorktreeWorkspace(worktree)?.label ?? localize('sessionWorktreeCleanup.unknownWorkspace', "Unknown workspace"), - worktree.session ? fromNow(worktree.session.updatedAt.get(), true, true) : localize('sessionWorktreeCleanup.noActivity', "No session activity available"), + updatedAt ? fromNow(updatedAt, true, true) : localize('sessionWorktreeCleanup.noActivity', "No session activity available"), this.getWorktreeStorageLabel(worktree, true), getWorktreeSessionLabel(worktree), this.getWorktreeCleanupLabel(worktree, this.isWorktreeCleaning(worktree)) ?? '', @@ -749,37 +790,33 @@ export class SessionWorktreeCleanupEditor extends EditorPane { } private renderWorkspaceOptions(): void { - if (!this.workspaceSelect) { - return; - } const workspaces = new Map(this.getDisplayWorktrees().flatMap(worktree => { const workspace = getWorktreeWorkspace(worktree); return workspace ? [[extUri.getComparisonKey(workspace.uri), workspace] as const] : []; })); - dom.setVisibility(workspaces.size > 1, this.workspaceSelect.parentElement!); if (workspaces.size <= 1 || !workspaces.has(this.selectedWorkspace)) { this.selectedWorkspace = ''; } - const signature = JSON.stringify([...workspaces].map(([key, workspace]) => [key, workspace.label])); - if (signature === this.workspaceOptionsSignature) { - this.workspaceSelect.value = this.selectedWorkspace; - return; - } - this.workspaceOptionsSignature = signature; - dom.clearNode(this.workspaceSelect); - dom.append(this.workspaceSelect, dom.$('option', { value: '' }, localize('sessionWorktreeCleanup.allWorkspaces', "All workspaces"))); const labelCounts = new Map(); for (const workspace of workspaces.values()) { labelCounts.set(workspace.label, (labelCounts.get(workspace.label) ?? 0) + 1); } const sortedWorkspaces = [...workspaces].sort((a, b) => a[1].label.localeCompare(b[1].label)); - for (const [key, workspace] of sortedWorkspaces) { + this.workspaceOptions = sortedWorkspaces.map(([key, workspace]) => { const label = labelCounts.get(workspace.label)! > 1 ? localize('sessionWorktreeCleanup.workspaceWithPath', "{0} ({1})", workspace.label, workspace.uri.toString(true)) : workspace.label; - dom.append(this.workspaceSelect, dom.$('option', { value: key }, label)); + return { key, label }; + }); + if (this.hasWorkspaceFilter !== (workspaces.size > 1)) { + const hadFocus = this.controls?.contains(dom.getActiveElement()); + this.hasWorkspaceFilter = workspaces.size > 1; + this.controlsToolbar?.setActions(this.hasWorkspaceFilter ? [this.ageFilterAction, this.workspaceFilterAction, this.sortAction] : [this.ageFilterAction, this.sortAction]); + if (hadFocus) { + this.controlsToolbar?.focus(); + } } - this.workspaceSelect.value = this.selectedWorkspace; + this.updateFilterLabels(); } private getDisplayWorktrees(): readonly ISessionWorktree[] { @@ -797,7 +834,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { return this.getDisplayWorktrees().filter(worktree => { const workspace = getWorktreeWorkspace(worktree); return (!this.selectedWorkspace || (workspace && extUri.getComparisonKey(workspace.uri) === this.selectedWorkspace)) - && (this.minimumAgeDays === 0 || !worktree.session || worktree.session.updatedAt.get().getTime() <= cutoff); + && (this.minimumAgeDays === 0 || !worktree.session || getWorktreeCleanupLastActivity(worktree)!.getTime() <= cutoff); }); } @@ -825,10 +862,10 @@ export class SessionWorktreeCleanupEditor extends EditorPane { const visible = this.getVisibleWorktrees(); const selectable = visible.filter(worktree => this.isManuallySelectable(worktree)); const estimatedBytes = getWorktreeCleanupDiskUsage(selectable); - const selectableWorktrees = selectable.reduce((total, worktree) => total + worktree.worktreeCount, 0); const totalWorktrees = visible.reduce((total, worktree) => total + (this.cleanupBatch.get(getWorktreeCleanupId(worktree))?.state === 'removed' ? 0 : worktree.worktreeCount), 0); const isEmpty = visible.length === 0; - this.summaryRow?.classList.toggle('hidden', totalWorktrees === 0); + this.summary?.classList.toggle('hidden', totalWorktrees === 0); + this.cleanupButton?.element.classList.toggle('hidden', totalWorktrees === 0); this.list.classList.toggle('hidden', isEmpty); this.emptyState?.classList.toggle('hidden', !isEmpty); if (this.emptyStateMessage) { @@ -836,9 +873,10 @@ export class SessionWorktreeCleanupEditor extends EditorPane { ? localize('sessionWorktreeCleanup.noWorktrees', "No worktrees to clean up.") : localize('sessionWorktreeCleanup.noMatchingWorktrees', "No worktrees match the selected filters."); } + const countLabel = totalWorktrees === 1 ? localize('sessionWorktreeCleanup.oneWorktreeSummary', "1 worktree.") : localize('sessionWorktreeCleanup.worktreeSummary', "{0} worktrees.", totalWorktrees); const summary = estimatedBytes !== undefined && estimatedBytes > 0 - ? localize('sessionWorktreeCleanup.matchingWorktreeDiskUsageSummary', "{0} of {1} matching worktrees can be cleaned up. Estimated disk usage: {2}.", selectableWorktrees, totalWorktrees, ByteSize.formatSize(estimatedBytes)) - : localize('sessionWorktreeCleanup.matchingWorktreeSummaryNoStorage', "{0} of {1} matching worktrees can be cleaned up.", selectableWorktrees, totalWorktrees); + ? localize('sessionWorktreeCleanup.worktreeDiskUsageSummary', "{0} Estimated disk usage: {1}.", countLabel, ByteSize.formatSize(estimatedBytes)) + : countLabel; const partialStorage = getPartialStorageLabel(selectable); const summaryWithStorage = partialStorage ? localize('sessionWorktreeCleanup.partialStorageSummary', "{0} Estimated disk usage: {1}.", summary, partialStorage) : summary; if (this.summaryMessage.textContent !== summaryWithStorage) { @@ -863,10 +901,10 @@ export class SessionWorktreeCleanupEditor extends EditorPane { return aPinnedIndex - bPinnedIndex; } if (this.sortOrder === 'recent') { - return (b.session?.updatedAt.get().getTime() ?? -1) - (a.session?.updatedAt.get().getTime() ?? -1); + return (getWorktreeCleanupLastActivity(b)?.getTime() ?? -1) - (getWorktreeCleanupLastActivity(a)?.getTime() ?? -1); } if (this.sortOrder === 'oldest') { - return (a.session?.updatedAt.get().getTime() ?? Number.MAX_SAFE_INTEGER) - (b.session?.updatedAt.get().getTime() ?? Number.MAX_SAFE_INTEGER); + return (getWorktreeCleanupLastActivity(a)?.getTime() ?? Number.MAX_SAFE_INTEGER) - (getWorktreeCleanupLastActivity(b)?.getTime() ?? Number.MAX_SAFE_INTEGER); } if (this.sortOrder === 'status') { const statusOrder = getWorktreeStatusOrder(a) - getWorktreeStatusOrder(b); @@ -902,7 +940,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { (checkbox?.isConnected ? checkbox : cells?.get('title')?.focusTarget)?.focus(); } } else { - this.ageSelect?.focus(); + this.controlsToolbar?.focus(); } } this.updateCleanupButton(); @@ -959,7 +997,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { if (session) { void this.sessionsService.openSession(session.resource).catch(error => this.notificationService.error(error)); } else if (template.worktree?.unlinkedWorktree) { - this.hoverService.showInstantHover({ ...this.cellHoverOptions, target: titleLink, content: URI.parse(template.worktree.unlinkedWorktree.worktree).path }, true); + this.hoverService.showInstantHover({ ...this.cellHoverOptions, target: titleLink, content: getWorktreePath(template.worktree, this.labelService) }, true); } }; disposables.add(dom.addDisposableListener(titleLink, dom.EventType.CLICK, openSession)); @@ -976,9 +1014,11 @@ export class SessionWorktreeCleanupEditor extends EditorPane { const title = getWorktreeCleanupTitle(worktree); titleLink.textContent = title; titleLink.setAttribute('role', worktree.session ? 'link' : 'button'); - const path = getWorktreePath(worktree); + const path = getWorktreePath(worktree, this.labelService); const hoverTitle = worktree.session ? localize('sessionWorktreeCleanup.openSession', "Open {0}", title) : title; - dynamicDisposables.add(this.hoverService.setupDelayedHoverAtMouse(titleLink, { content: `${hoverTitle}\n${path}` }, this.cellHoverOptions)); + dynamicDisposables.add(this.hoverService.setupDelayedHoverAtMouse(titleLink, { + content: localize('sessionWorktreeCleanup.titleHover', "{0}\nWorktree: {1}", hoverTitle, path), + }, this.cellHoverOptions)); titleLink.setAttribute('aria-description', path); }; } else { @@ -988,10 +1028,12 @@ export class SessionWorktreeCleanupEditor extends EditorPane { const workspace = getWorktreeWorkspace(worktree); container.textContent = workspace?.label ?? localize('sessionWorktreeCleanup.unknownWorkspace', "Unknown workspace"); if (workspace) { - dynamicDisposables.add(this.hoverService.setupDelayedHoverAtMouse(container, { content: workspace.description ? `${workspace.label}\n${workspace.description}\n${workspace.uri.toString(true)}` : workspace.uri.toString(true) }, this.cellHoverOptions)); + dynamicDisposables.add(this.hoverService.setupDelayedHoverAtMouse(container, { + content: localize('sessionWorktreeCleanup.workspacePath', "Repository: {0}", this.labelService.getUriLabel(workspace.uri)), + }, this.cellHoverOptions)); } } else if (column === 'lastUsed') { - const updatedAt = worktree.session?.updatedAt.get(); + const updatedAt = getWorktreeCleanupLastActivity(worktree); container.textContent = updatedAt ? fromNow(updatedAt, true, true) : localize('sessionWorktreeCleanup.noSessionActivity', "No session activity"); if (updatedAt) { dynamicDisposables.add(this.hoverService.setupDelayedHoverAtMouse(container, { content: updatedAt.toLocaleString() }, this.cellHoverOptions)); @@ -1070,6 +1112,12 @@ export class SessionWorktreeCleanupEditor extends EditorPane { if (worktree.worktreeExists === false) { return ByteSize.formatSize(0); } + if (this.isWorktreeCleaning(worktree)) { + const sizeBeforeCleanup = this.cleanupBatch.get(getWorktreeCleanupId(worktree))?.candidate.sizeBytes; + return sizeBeforeCleanup === undefined + ? localize('sessionWorktreeCleanup.pendingRemovalStorage', "Pending removal") + : ByteSize.formatSize(sizeBeforeCleanup); + } return worktree.cleanupState === 'archived' || worktree.session?.isArchived.get() || worktree.unlinkedWorktree ? accessible ? worktree.unlinkedWorktree ? localize('sessionWorktreeCleanup.unlinkedStorage', "Not measured for worktrees without a listed session") : localize('sessionWorktreeCleanup.doneStorage', "Not measured for done sessions") : localize('sessionWorktreeCleanup.notMeasured', "Not measured") : worktree.isMeasuring @@ -1084,7 +1132,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { const batch = this.cleanupBatch.get(getWorktreeCleanupId(worktree)); return [ getWorktreeCleanupTitle(worktree), - worktree.session?.updatedAt.get().getTime(), + getWorktreeCleanupLastActivity(worktree)?.getTime(), workspace?.label, workspace?.description, workspace?.uri.toString(), @@ -1201,13 +1249,9 @@ export class SessionWorktreeCleanupEditor extends EditorPane { const selectedSize = selectedBytes === undefined ? getPartialStorageLabel(selected) : ByteSize.formatSize(selectedBytes); this.cleanupButton.label = selected.length === 0 ? localize('sessionWorktreeCleanup.cleanupButton', "Clean Up Worktrees") - : selectedSize === undefined - ? selectedWorktrees === 1 - ? localize('sessionWorktreeCleanup.cleanupSelectionOne', "Clean Up 1 Worktree") - : localize('sessionWorktreeCleanup.cleanupSelection', "Clean Up {0} Worktrees", selectedWorktrees) - : selectedWorktrees === 1 - ? localize('sessionWorktreeCleanup.cleanupSelectionWithSizeOne', "Clean Up 1 Worktree (~{0})", selectedSize) - : localize('sessionWorktreeCleanup.cleanupSelectionWithSize', "Clean Up {0} Worktrees (~{1})", selectedWorktrees, selectedSize); + : selectedWorktrees === 1 + ? localize('sessionWorktreeCleanup.cleanupSelectionOne', "Clean Up 1 Worktree") + : localize('sessionWorktreeCleanup.cleanupSelection', "Clean Up {0} Worktrees", selectedWorktrees); this.cleanupButton.element.setAttribute('aria-label', selected.length === 0 || selectedSize === undefined ? this.cleanupButton.label : selectedWorktrees === 1 @@ -1219,13 +1263,11 @@ export class SessionWorktreeCleanupEditor extends EditorPane { private getSelected(): ISessionWorktreeCleanupCandidate[] { return this.getVisibleWorktrees() .filter(worktree => this.isManuallySelectable(worktree) && this.selectedSessionIds.has(getWorktreeCleanupId(worktree))) - .map(worktree => worktree.session - ? { session: worktree.session, sizeBytes: worktree.sizeBytes, worktreeCount: worktree.worktreeCount } - : { unlinkedWorktree: worktree.unlinkedWorktree, sizeBytes: worktree.sizeBytes, worktreeCount: worktree.worktreeCount }); + .map(worktree => ({ ...worktree })); } private isManuallySelectable(worktree: ISessionWorktree): boolean { - return !worktree.isMeasuring && !this.hasRemovalIssue(worktree) && this.canScheduleCleanup(worktree); + return !this.hasRemovalIssue(worktree) && this.canScheduleCleanup(worktree); } private canScheduleCleanup(worktree: ISessionWorktree): boolean { @@ -1235,7 +1277,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { ? !!worktree.unlinkedWorktree.branch && !worktree.cleanupStatusError && !worktree.worktreeCheckError && worktree.cleanupStatus?.state !== 'inUse' && !this.hasPendingCleanup(worktree) : worktree.cleanupState === 'archived' ? !!worktree.cleanupStatus && !this.hasPendingCleanup(worktree) - : !worktree.session.isArchived.get() && worktree.sizeBytes !== undefined && (worktree.cleanupState === 'eligible' || worktree.cleanupState === 'active' || worktree.cleanupState === 'needsInput')); + : !worktree.session.isArchived.get() && (worktree.cleanupState === 'eligible' || worktree.cleanupState === 'active' || worktree.cleanupState === 'needsInput')); } private isWorktreeInProgress(worktree: ISessionWorktree): boolean { @@ -1395,7 +1437,7 @@ export class SessionWorktreeCleanupEditor extends EditorPane { private renderAutomaticCleanup(content: HTMLElement): void { const section = dom.append(content, dom.$('details.session-worktree-cleanup-automatic')); - const summary = dom.append(section, dom.$('summary')); + const summary = dom.append(section, dom.$('summary.agent-sessions-interactive.agent-sessions-interactive-bordered')); const icon = dom.append(summary, renderIcon(Codicon.settingsGear)); icon.setAttribute('aria-hidden', 'true'); dom.append(summary, dom.$('span', undefined, localize('sessionWorktreeCleanup.automaticHeading', "Automatic Cleanup"))); diff --git a/src/vs/sessions/contrib/sessionInputBanners/test/browser/sessionWorktreeCleanupEditor.test.ts b/src/vs/sessions/contrib/sessionInputBanners/test/browser/sessionWorktreeCleanupEditor.test.ts index 1ca11b7239eb..c80dd87a29c2 100644 --- a/src/vs/sessions/contrib/sessionInputBanners/test/browser/sessionWorktreeCleanupEditor.test.ts +++ b/src/vs/sessions/contrib/sessionInputBanners/test/browser/sessionWorktreeCleanupEditor.test.ts @@ -8,6 +8,7 @@ import { spy, stub } from 'sinon'; import * as dom from '../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { IAction } from '../../../../../base/common/actions.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { getErrorMessage } from '../../../../../base/common/errors.js'; @@ -19,10 +20,12 @@ import { runWithFakedTimers } from '../../../../../base/test/common/virtualSched import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; import { KeybindingsRegistry } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; import { IListService, ListService, WorkbenchTable } from '../../../../../platform/list/browser/listService.js'; import { INotificationService } from '../../../../../platform/notification/common/notification.js'; @@ -37,6 +40,7 @@ import '../../../../../workbench/browser/actions/listCommands.js'; suite('SessionWorktreeCleanupEditor', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const contextMenus = new WeakMap readonly IAction[]>(); function createEditor(cleanupService: Partial = {}, contextKeyService?: IContextKeyService) { const instantiationService = workbenchInstantiationService(undefined, disposables); @@ -44,6 +48,7 @@ suite('SessionWorktreeCleanupEditor', () => { instantiationService.stub(IContextKeyService, contextKeyService); } instantiationService.stub(IListService, disposables.add(new ListService())); + instantiationService.stub(ILabelService, upcastPartial({ getUriLabel: uri => uri.fsPath })); const configuration = new TestConfigurationService({ [ChatConfiguration.AutoMarkAsDoneMergedSessionsAfterDays]: 0, [ChatConfiguration.AutoDeleteMarkedAsDoneMergedSessionsAfterDays]: 0, @@ -63,8 +68,20 @@ suite('SessionWorktreeCleanupEditor', () => { instantiationService.stub(ISessionsService, upcastPartial({ openSession: async resource => { opened.push(resource.toString()); return undefined; } })); const errors: string[] = []; instantiationService.stub(INotificationService, upcastPartial({ error: error => errors.push(getErrorMessage(error)) })); - const editor = disposables.add(instantiationService.createInstance(SessionWorktreeCleanupEditor, new TestEditorGroupView(1))); const container = dom.append(mainWindow.document.body, dom.$('div')); + let menuActions: readonly IAction[] = []; + let closeMenu: (() => void) | undefined; + instantiationService.stub(IContextMenuService, upcastPartial({ + showContextMenu: delegate => { + menuActions = delegate.getActions?.() ?? []; + closeMenu = () => delegate.onHide?.(false); + }, + })); + contextMenus.set(container, () => { + closeMenu?.(); + return menuActions; + }); + const editor = disposables.add(instantiationService.createInstance(SessionWorktreeCleanupEditor, new TestEditorGroupView(1))); disposables.add(toDisposable(() => container.remove())); editor.create(container); editor.layout(new dom.Dimension(1200, 1000)); @@ -96,10 +113,22 @@ suite('SessionWorktreeCleanupEditor', () => { container.querySelector('.session-worktree-cleanup-select-all [role="checkbox"]')!.click(); } + function menuActions(container: HTMLElement, menu: 'age' | 'workspace' | 'sort') { + container.querySelector(`.session-worktree-cleanup-${menu}`)!.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + return contextMenus.get(container)!(); + } + + function chooseOption(container: HTMLElement, menu: 'age' | 'workspace' | 'sort', value: string): void { + const workspaceLabel = menu === 'workspace' && value ? URI.parse(value).path.split('/').pop() : 'All Workspaces'; + const action = menuActions(container, menu).find(action => menu === 'workspace' + ? action.label === workspaceLabel || action.label === `${workspaceLabel} (${value})` + : action.id === `${menu}.${value}`); + assert.ok(action, `Missing ${menu} option: ${value}`); + void action.run(); + } + function sortWorktrees(container: HTMLElement, order: string): void { - const sort = container.querySelector('.session-worktree-cleanup-sort')!; - sort.value = order; - sort.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'sort', order); } test('shows ownership once for idle worktrees and hides failed worktrees without hiding progress', async () => { @@ -142,7 +171,7 @@ suite('SessionWorktreeCleanupEditor', () => { titles: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), recoveryControls: container.querySelectorAll('.session-worktree-cleanup-retry, .session-worktree-cleanup-force-remove, .session-worktree-cleanup-view').length, summary: container.querySelector('.session-worktree-cleanup-summary')?.textContent, - }, { titles: ['eligible'], recoveryControls: 0, summary: '1 of 1 matching worktrees can be cleaned up. Estimated disk usage: 100B.' }); + }, { titles: ['eligible'], recoveryControls: 0, summary: '1 worktree. Estimated disk usage: 100B.' }); }); test('shows an honest empty state and keeps settings when nothing can be cleaned up', async () => { @@ -435,7 +464,7 @@ suite('SessionWorktreeCleanupEditor', () => { region.scrollTop = region.scrollHeight; const last = region.lastElementChild!.getBoundingClientRect(); const bounds = region.getBoundingClientRect(); - return { scrollable: region.scrollHeight > region.clientHeight, lastControlReachable: last.bottom <= bounds.bottom + 1 }; + return { lastControlReachable: last.bottom <= bounds.bottom + 1 }; }); assert.deepStrictEqual({ regionBounds, @@ -445,7 +474,7 @@ suite('SessionWorktreeCleanupEditor', () => { inventoryOutsideControls: !inventory.closest('.session-worktree-cleanup-controls-content'), virtualized: container.querySelectorAll('.session-worktree-cleanup-row').length < 20, }, { - regionBounds: [{ scrollable: true, lastControlReachable: true }, { scrollable: true, lastControlReachable: true }], + regionBounds: [{ lastControlReachable: true }, { lastControlReachable: true }], settingsVisible: true, settingsAboveInventory: true, inventoryVisible: true, inventoryOutsideControls: true, virtualized: true, }); }); @@ -509,13 +538,13 @@ suite('SessionWorktreeCleanupEditor', () => { selectable: checkbox.getAttribute('aria-disabled'), titleRole: title.getAttribute('role'), titleTabIndex: title.tabIndex, - announcesPath: title.closest('.monaco-list-row')?.getAttribute('aria-label')?.includes('/repos/app.worktrees/recovered'), + announcesPath: title.closest('.monaco-list-row')?.getAttribute('aria-label')?.includes(URI.file('/repos/app.worktrees/recovered').fsPath), inspectedPaths: showHover.args.map(([options, focus]) => ({ content: options.content, focus })), }, { title: 'agents/recovered', storage: 'Not measured', lastUsed: 'No session activity', selected: 'false', selectable: null, titleRole: 'button', titleTabIndex: 0, announcesPath: true, - inspectedPaths: Array.from({ length: 2 }, () => ({ content: '/repos/app.worktrees/recovered', focus: true })), + inspectedPaths: Array.from({ length: 2 }, () => ({ content: URI.file('/repos/app.worktrees/recovered').fsPath, focus: true })), }); checkbox.click(); container.querySelector('.session-worktree-cleanup-action')!.click(); @@ -715,7 +744,7 @@ suite('SessionWorktreeCleanupEditor', () => { storage: row.querySelector('.storage')?.textContent, checkbox: row.querySelector('[role="checkbox"]'), })) - }, { rows: [{ title: 'agents/removed', reason: 'Worktree removed', path: '/repos/app.worktrees/removed', storage: '0B', checkbox: null }] }); + }, { rows: [{ title: 'agents/removed', reason: 'Worktree removed', path: URI.file('/repos/app.worktrees/removed').fsPath, storage: '0B', checkbox: null }] }); })); test('live results preserve selection and show verified removals despite stale host errors without showing failures', () => runWithFakedTimers({ useFakeTimers: true }, async () => { @@ -769,21 +798,17 @@ suite('SessionWorktreeCleanupEditor', () => { title: row.querySelector('a')?.textContent, checked: row.querySelector('[role="checkbox"]')?.getAttribute('aria-checked'), })); - const sort = container.querySelector('.session-worktree-cleanup-sort')!; - const defaultSort = sort.value; + const defaultSort = menuActions(container, 'sort').find(action => action.checked)?.id; const states = [rows()]; - sort.value = 'size'; - sort.dispatchEvent(new mainWindow.Event('change')); + sortWorktrees(container, 'size'); container.querySelector('.session-worktree-cleanup-row [role="checkbox"]')!.click(); states.push(rows()); - sort.value = 'recent'; - sort.dispatchEvent(new mainWindow.Event('change')); + sortWorktrees(container, 'recent'); states.push(rows()); - sort.value = 'size'; - sort.dispatchEvent(new mainWindow.Event('change')); + sortWorktrees(container, 'size'); states.push(rows()); assert.deepStrictEqual({ defaultSort, states }, { - defaultSort: 'oldest', states: [ + defaultSort: 'sort.oldest', states: [ [{ title: 'older-large', checked: 'false' }, { title: 'newer-small', checked: 'false' }, { title: 'agents/unknown-age', checked: 'false' }], [{ title: 'older-large', checked: 'true' }, { title: 'newer-small', checked: 'false' }, { title: 'agents/unknown-age', checked: 'false' }], [{ title: 'newer-small', checked: 'false' }, { title: 'older-large', checked: 'true' }, { title: 'agents/unknown-age', checked: 'false' }], @@ -823,9 +848,7 @@ suite('SessionWorktreeCleanupEditor', () => { .filter(row => row.querySelector('[aria-checked="true"]')) .map(row => row.querySelector('a')?.textContent).sort(); const selectedBefore = selectedIds(); - const sort = container.querySelector('.session-worktree-cleanup-sort')!; - sort.value = 'status'; - sort.dispatchEvent(new mainWindow.Event('change')); + sortWorktrees(container, 'status'); assert.deepStrictEqual({ scans, titles: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), @@ -907,13 +930,10 @@ suite('SessionWorktreeCleanupEditor', () => { }, }); await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); - const workspace = container.querySelector('.session-worktree-cleanup-workspace')!; - workspace.value = URI.file('/repos/app').toString(); - workspace.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'workspace', URI.file('/repos/app').toString()); publish?.(worktrees); await timeout(100); - workspace.value = URI.file('/repos/other').toString(); - workspace.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'workspace', URI.file('/repos/other').toString()); const checkbox = () => container.querySelector('.session-worktree-cleanup-list .session-worktree-cleanup-row [role="checkbox"]')!; const toggle = selection === 'row' ? checkbox() @@ -930,10 +950,8 @@ suite('SessionWorktreeCleanupEditor', () => { await timeout(0); } states.push(checkbox().getAttribute('aria-checked')); - const age = container.querySelector('.session-worktree-cleanup-age')!; for (const days of [7, 0]) { - age.value = String(days); - age.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'age', String(days)); await timeout(0); states.push(checkbox().getAttribute('aria-checked')); } @@ -944,16 +962,13 @@ suite('SessionWorktreeCleanupEditor', () => { test('does not preselect unknown-age unlinked worktrees under an age filter but preserves explicit selection', async () => { const unlinked = createUnlinkedWorktree('leftover'); const { container, cleaned } = await openEditor([unlinked]); - const age = container.querySelector('.session-worktree-cleanup-age')!; const checkbox = () => container.querySelector('.session-worktree-cleanup-row [role="checkbox"]')!; const states = [checkbox().getAttribute('aria-checked')]; - age.value = '7'; - age.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'age', '7'); await timeout(0); states.push(checkbox().getAttribute('aria-checked')); checkbox().click(); - age.value = '30'; - age.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'age', '30'); await timeout(0); states.push(checkbox().getAttribute('aria-checked')); container.querySelector('.session-worktree-cleanup-action')!.click(); @@ -975,13 +990,15 @@ suite('SessionWorktreeCleanupEditor', () => { assert.deepStrictEqual({ opened, heading: container.querySelector('details > summary')?.textContent, + headingClass: container.querySelector('details > summary')?.className, loading: container.querySelector('.session-worktree-cleanup-summary')?.textContent, - pickerDisabled: container.querySelector('select')?.disabled, + pickerDisabled: container.querySelector('.session-worktree-cleanup-age')?.getAttribute('aria-disabled'), }, { opened: true, heading: 'Automatic Cleanup', + headingClass: 'agent-sessions-interactive agent-sessions-interactive-bordered', loading: 'Measuring worktree storage...', - pickerDisabled: true, + pickerDisabled: 'true', }); } finally { await worktrees.complete([]); @@ -990,8 +1007,8 @@ suite('SessionWorktreeCleanupEditor', () => { assert.deepStrictEqual({ emptyStateVisible: !container.querySelector('.session-worktree-cleanup-empty')?.classList.contains('hidden'), - pickerDisabled: container.querySelector('select')?.disabled, - }, { emptyStateVisible: true, pickerDisabled: false }); + pickerDisabled: container.querySelector('.session-worktree-cleanup-age')?.getAttribute('aria-disabled'), + }, { emptyStateVisible: true, pickerDisabled: 'false' }); }); test('updates individual sizes without waiting for all scans or resetting selections', () => runWithFakedTimers({ useFakeTimers: true }, async () => { @@ -1105,9 +1122,7 @@ suite('SessionWorktreeCleanupEditor', () => { container.querySelector('.session-worktree-cleanup-select-all [role="checkbox"]')!.click(); container.querySelector('.session-worktree-cleanup-action')!.click(); await timeout(0); - const picker = container.querySelector('.session-worktree-cleanup-workspace')!; - picker.value = URI.file('/repos/app').toString(); - picker.dispatchEvent(new mainWindow.Event('change')); + chooseOption(container, 'workspace', URI.file('/repos/app').toString()); container.querySelector('.session-worktree-cleanup-select-all [role="checkbox"]')!.click(); container.querySelector('.session-worktree-cleanup-action')!.click(); await timeout(0); @@ -1328,6 +1343,54 @@ suite('SessionWorktreeCleanupEditor', () => { ]); }); + test('row background selects without opening a session and child focus updates keyboard navigation', async () => { + const { editor, container, opened, instantiationService } = createEditor({ + getWorktrees: async () => [createWorktree('first', '/repos/app'), createWorktree('second', '/repos/app')], + }); + await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); + await timeout(0); + const rows = container.querySelectorAll('.session-worktree-cleanup-row'); + const titleCell = rows[1].querySelector('.title')!; + const link = titleCell.querySelector('a')!; + const checkbox = rows[1].querySelector('[role="checkbox"]')!; + titleCell.click(); + const selectedWithoutOpening = { selected: checkbox.getAttribute('aria-checked'), opened: [...opened] }; + focusElement(link); + const table = instantiationService.get(IListService).lastFocusedList; + assert.ok(table instanceof WorkbenchTable); + const focused = table.getFocusedElements(); + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand('list.focusUp')!.handler(accessor)); + const afterUp = table.getFocusedElements(); + link.click(); + assert.deepStrictEqual({ + selectedWithoutOpening, focused, afterUp, opened, + linkFitsText: link.getBoundingClientRect().width < titleCell.getBoundingClientRect().width / 2, + }, { + selectedWithoutOpening: { selected: 'true', opened: [] }, focused: ['second'], afterUp: ['first'], + opened: ['test:/second'], linkFitsText: true, + }); + }); + + test('selection is available while measuring and survives the final size update', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const worktree = createWorktree('measuring', '/repos/app'); + const finished = new DeferredPromise(); + const { editor, container } = createEditor({ + getWorktrees: async (_age, update) => { update?.([{ ...worktree, sizeBytes: undefined, isMeasuring: true }]); return finished.p; }, + }); + await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); + await timeout(100); + const checkbox = container.querySelector('.session-worktree-cleanup-row [role="checkbox"]')!; + checkbox.click(); + const action = container.querySelector('.session-worktree-cleanup-action')!; + const before = { selected: checkbox.getAttribute('aria-checked'), enabled: action.getAttribute('aria-disabled') }; + await finished.complete([worktree]); + await timeout(100); + assert.deepStrictEqual({ + before, selected: container.querySelector('.session-worktree-cleanup-row [role="checkbox"]')?.getAttribute('aria-checked'), + label: action.getAttribute('aria-label'), + }, { before: { selected: 'true', enabled: 'false' }, selected: 'true', label: 'Clean Up 1 Worktree, estimated disk usage 100B' }); + })); + test('preserves table focus through reordering and moves to an actionable row when the focused row becomes protected', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const first = createWorktree('first', '/repos/app'); const second = createWorktree('second', '/repos/app'); @@ -1435,7 +1498,7 @@ suite('SessionWorktreeCleanupEditor', () => { }); })); - test('keeps overall measurement counts across filters and includes failed measurements', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('shows scan progress across filters only while measurement is pending', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const finished = new DeferredPromise(); let publish: ((worktrees: readonly ISessionWorktree[], progress?: ISessionWorktreeMeasurementProgress) => void) | undefined; const first = { ...createWorktree('first', '/repos/app'), worktreeCount: 2 }; @@ -1451,36 +1514,27 @@ suite('SessionWorktreeCleanupEditor', () => { }); await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); const progress = container.querySelector('.session-worktree-cleanup-measurement-progress')!; - const counts = [progress.textContent]; + const visible = [progress.style.display !== 'none']; try { publish?.([first, pending], { scannedWorktrees: 3, totalWorktrees: 4 }); await timeout(100); - counts.push(progress.textContent); - const workspace = container.querySelector('.session-worktree-cleanup-workspace')!; - workspace.value = URI.file('/repos/other').toString(); - workspace.dispatchEvent(new mainWindow.Event('change')); - counts.push(progress.textContent); + visible.push(progress.style.display !== 'none'); + chooseOption(container, 'workspace', URI.file('/repos/other').toString()); + visible.push(progress.style.display !== 'none'); } finally { publish?.([first, failed], { scannedWorktrees: 4, totalWorktrees: 4 }); await finished.complete([first, failed]); await timeout(0); } - counts.push(progress.textContent); + visible.push(progress.style.display !== 'none'); assert.deepStrictEqual({ - counts, + visible, sameStatus: container.querySelector('.session-worktree-cleanup-measurement-progress') === progress, - role: progress.getAttribute('role'), - visible: progress.style.display !== 'none', + label: progress.querySelector('[role="progressbar"]')?.getAttribute('aria-label'), }, { - counts: [ - 'Measuring worktree storage: 0 of 4 worktrees processed.', - 'Measuring worktree storage: 3 of 4 worktrees processed.', - 'Measuring worktree storage: 3 of 4 worktrees processed.', - 'Worktree storage scan complete: 4 of 4 worktrees processed.', - ], + visible: [true, true, true, false], sameStatus: true, - role: 'status', - visible: true, + label: 'Measuring worktree storage', }); })); @@ -1571,17 +1625,15 @@ suite('SessionWorktreeCleanupEditor', () => { }); await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); await timeout(0); - const picker = container.querySelector('.session-worktree-cleanup-workspace')!; const selectWorkspace = (path: string) => { - picker.value = URI.file(path).toString(); - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + chooseOption(container, 'workspace', URI.file(path).toString()); }; selectWorkspace('/repos/app'); container.querySelector('.session-worktree-cleanup-row:not(.header) [role="checkbox"]')!.click(); container.querySelector('.session-worktree-cleanup-action')!.click(); await timeout(2_100); const completed = { - workspace: picker.value, + workspace: menuActions(container, 'workspace').find(action => action.checked)?.label, rows: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), reason: rowStatus(container), }; @@ -1607,24 +1659,33 @@ suite('SessionWorktreeCleanupEditor', () => { }, { requests: [['first']], checked: [['first']], - completed: { workspace: URI.file('/repos/app').toString(), rows: ['first'], reason: 'Worktree removed' }, + completed: { workspace: 'app (file:///repos/app)', rows: ['first'], reason: 'Worktree removed' }, failure: undefined, restoredFilter: 'Worktree removed', reopened: [], }); })); - test('keeps row order stable while archived sizes are hidden and cleanup status changes', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('keeps pre-cleanup sizes and row order until removal is confirmed', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const first = { ...createWorktree('first', '/repos/app'), sizeBytes: 300 }; const second = { ...createWorktree('second', '/repos/app'), sizeBytes: 200 }; const existing = { ...createWorktree('existing', '/repos/app', 'archived'), sizeBytes: 100 }; + const scheduling = new DeferredPromise(); let archived = false; let checks = 0; const { editor, container } = createEditor({ getWorktrees: async () => archived ? [{ ...first, sizeBytes: undefined, cleanupState: 'archived', cleanupStatus: { state: 'pending' } }, { ...second, sizeBytes: undefined, cleanupState: 'archived', cleanupStatus: { state: 'pending' } }, existing] : [first, second, existing], - cleanupWorktrees: async (candidates, onProgress) => { archived = true; return scheduleCleanup(candidates, onProgress); }, + cleanupWorktrees: async (candidates, onProgress) => { + onProgress?.({ state: 'started' }); + await scheduling.p; + archived = true; + for (const candidate of candidates) { + onProgress?.({ state: 'scheduled', candidate }); + } + return true; + }, refreshPendingCleanup: async () => ++checks === 1 ? [{ ...first, sizeBytes: undefined, cleanupState: 'archived', cleanupStatus: { state: 'running' } }, { ...second, sizeBytes: undefined, cleanupState: 'archived', cleanupStatus: { state: 'pending' } }, existing] : [removedWorktree(first), removedWorktree(second), existing], @@ -1633,18 +1694,53 @@ suite('SessionWorktreeCleanupEditor', () => { await timeout(0); selectAllWorktrees(container); container.querySelector('.session-worktree-cleanup-action')!.click(); + const storage = () => [...container.querySelectorAll('.session-worktree-cleanup-row:not(.header) .storage')].map(cell => cell.textContent); + const queuedStorage = storage(); + await scheduling.complete(); + await timeout(0); + const pendingStorage = storage(); await timeout(2_100); const rowsAfterShrink = [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent); + const runningStorage = storage(); + const accessibleStorage = container.querySelector('.monaco-list-row')?.getAttribute('aria-label')?.includes('disk usage 300B.'); await timeout(4_100); assert.deepStrictEqual({ + queuedStorage, + pendingStorage, + runningStorage, + accessibleStorage, rowsAfterShrink, rowsAfterRemoval: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), + removedStorage: storage(), }, { + queuedStorage: ['300B', '200B'], + pendingStorage: ['300B', '200B'], + runningStorage: ['300B', '200B'], + accessibleStorage: true, rowsAfterShrink: ['first', 'second'], rowsAfterRemoval: ['first', 'second'], + removedStorage: ['0B', '0B'], }); })); + test('shows pending removal rather than not measured when cleanup starts without a size estimate', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const worktree = { ...createWorktree('unmeasured', '/repos/app'), sizeBytes: undefined }; + let archived = false; + const { editor, container } = createEditor({ + getWorktrees: async () => [archived ? { ...worktree, cleanupState: 'archived', cleanupStatus: { state: 'pending' } } : worktree], + cleanupWorktrees: async (candidates, onProgress) => { archived = true; return scheduleCleanup(candidates, onProgress); }, + }); + await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); + await timeout(0); + selectAllWorktrees(container); + container.querySelector('.session-worktree-cleanup-action')!.click(); + await timeout(0); + assert.deepStrictEqual({ + storage: container.querySelector('.session-worktree-cleanup-row:not(.header) .storage')?.textContent, + accessible: container.querySelector('.monaco-list-row')?.getAttribute('aria-label')?.includes('disk usage Pending removal'), + }, { storage: 'Pending removal', accessible: true }); + })); + test('limits existence polling without claiming removal when the host has no cleanup status support', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const worktree = createWorktree('first', '/repos/app'); let archived = false; @@ -1968,7 +2064,7 @@ suite('SessionWorktreeCleanupEditor', () => { states: [false, true, false], focused: true, configureActions: 0, - intro: 'Free up local disk space', + intro: undefined, }); }); @@ -2030,17 +2126,15 @@ suite('SessionWorktreeCleanupEditor', () => { const states = [selectionState()]; container.querySelector('.session-worktree-cleanup-row:not(.header) [role="checkbox"]')!.click(); states.push(selectionState()); - const picker = container.querySelector('.session-worktree-cleanup-workspace')!; - picker.value = URI.file('/other/app').toString(); - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + chooseOption(container, 'workspace', URI.file('/other/app').toString()); states.push(selectionState()); container.querySelector('.session-worktree-cleanup-select-all [role="checkbox"]')!.click(); states.push(selectionState()); assert.deepStrictEqual(states, [ - { label: 'Clean Up 3 Worktrees (~400B)', accessibleLabel: 'Clean Up 3 Worktrees, estimated disk usage 400B', disabled: 'false' }, - { label: 'Clean Up 1 Worktree (~100B)', accessibleLabel: 'Clean Up 1 Worktree, estimated disk usage 100B', disabled: 'false' }, + { label: 'Clean Up 3 Worktrees', accessibleLabel: 'Clean Up 3 Worktrees, estimated disk usage 400B', disabled: 'false' }, + { label: 'Clean Up 1 Worktree', accessibleLabel: 'Clean Up 1 Worktree, estimated disk usage 100B', disabled: 'false' }, { label: 'Clean Up Worktrees', accessibleLabel: 'Clean Up Worktrees', disabled: 'true' }, - { label: 'Clean Up 1 Worktree (~100B)', accessibleLabel: 'Clean Up 1 Worktree, estimated disk usage 100B', disabled: 'false' }, + { label: 'Clean Up 1 Worktree', accessibleLabel: 'Clean Up 1 Worktree, estimated disk usage 100B', disabled: 'false' }, ]); }); @@ -2073,11 +2167,11 @@ suite('SessionWorktreeCleanupEditor', () => { storage: ['Not measured', '1.00GB'], checked: ['true', 'true'], archivedLabel: true, - summary: '2 of 2 matching worktrees can be cleaned up. Estimated disk usage: 1.00GB known, 1 unmeasured.', - button: 'Clean Up 2 Worktrees (~1.00GB known, 1 unmeasured)', + summary: '2 worktrees. Estimated disk usage: 1.00GB known, 1 unmeasured.', + button: 'Clean Up 2 Worktrees', accessibleButton: 'Clean Up 2 Worktrees, estimated disk usage 1.00GB known, 1 unmeasured', }, - activeOnly: 'Clean Up 1 Worktree (~1.00GB)', + activeOnly: 'Clean Up 1 Worktree', archivedOnly: 'Clean Up 1 Worktree', cleaned: [['archived']], }); @@ -2315,7 +2409,7 @@ suite('SessionWorktreeCleanupEditor', () => { checks: 2, errors: ['Host disconnected'], summary: 'Cleanup: 1 worktree removed.', reason: 'Worktree removed', - controlsHidden: true, + controlsHidden: false, }); })); @@ -2413,17 +2507,15 @@ suite('SessionWorktreeCleanupEditor', () => { createWorktree('third', '/repos/app'), createWorktree('unique', '/repos/zeta'), ]); - const picker = container.querySelector('.session-worktree-cleanup-workspace')!; - const options = [...picker.options].map(option => option.textContent); - picker.value = URI.file('/repos/app').toString(); - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + const options = menuActions(container, 'workspace').map(action => action.label); + chooseOption(container, 'workspace', URI.file('/repos/app').toString()); const rows = [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent); container.querySelector('.session-worktree-cleanup-select-all [role="checkbox"]')!.click(); container.querySelector('.session-worktree-cleanup-action')!.click(); await timeout(0); assert.deepStrictEqual({ options, rows, cleaned }, { - options: ['All workspaces', 'app (file:///repos/app)', 'app (file:///other/app)', 'zeta'], + options: ['All Workspaces', 'app (file:///repos/app)', 'app (file:///other/app)', 'zeta'], rows: ['first', 'third'], cleaned: [['first', 'third']], }); @@ -2432,8 +2524,6 @@ suite('SessionWorktreeCleanupEditor', () => { test('shows the workspace picker only when multiple distinct workspaces are available', async () => { let worktrees: readonly ISessionWorktree[] = []; const { editor, container } = createEditor({ getWorktrees: async () => worktrees }); - const picker = container.querySelector('.session-worktree-cleanup-workspace')!; - const label = picker.parentElement!; const states = []; for (const nextWorktrees of [ [], @@ -2446,23 +2536,21 @@ suite('SessionWorktreeCleanupEditor', () => { editor.showAllWorktrees(); await timeout(0); states.push({ - visible: mainWindow.getComputedStyle(label).display !== 'none', - ariaHidden: label.getAttribute('aria-hidden'), - selected: picker.value, + visible: !!container.querySelector('.session-worktree-cleanup-workspace'), + filtered: container.querySelector('.session-worktree-cleanup-controls')?.classList.contains('workspace-filtered'), rows: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), }); if (worktrees.some(worktree => getWorktreeCleanupId(worktree) === 'other')) { - picker.value = URI.file('/repos/app').toString(); - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + chooseOption(container, 'workspace', URI.file('/repos/app').toString()); } } assert.deepStrictEqual(states, [ - { visible: false, ariaHidden: 'true', selected: '', rows: [] }, - { visible: false, ariaHidden: 'true', selected: '', rows: ['first', 'second'] }, - { visible: true, ariaHidden: null, selected: '', rows: ['first', 'other'] }, - { visible: false, ariaHidden: 'true', selected: '', rows: ['first', 'second'] }, - { visible: false, ariaHidden: 'true', selected: '', rows: [] }, + { visible: false, filtered: false, rows: [] }, + { visible: false, filtered: false, rows: ['first', 'second'] }, + { visible: true, filtered: false, rows: ['first', 'other'] }, + { visible: false, filtered: false, rows: ['first', 'second'] }, + { visible: false, filtered: false, rows: [] }, ]); }); @@ -2471,12 +2559,10 @@ suite('SessionWorktreeCleanupEditor', () => { createWorktree('recent', '/repos/app'), createWorktree('old', '/repos/app', 'eligible', 30), ]); - const picker = container.querySelector('.session-worktree-cleanup-age')!; const rows = () => [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent); const states = [rows()]; for (const days of [7, 60, 0]) { - picker.value = String(days); - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + chooseOption(container, 'age', String(days)); await timeout(0); states.push(rows()); } @@ -2487,6 +2573,71 @@ suite('SessionWorktreeCleanupEditor', () => { }); }); + test('keeps the active inactivity filter reachable when no worktrees match', async () => { + const { container, ages } = await openEditor([createWorktree('recent', '/repos/app')]); + chooseOption(container, 'age', '90'); + await timeout(0); + const emptyState = { + message: container.querySelector('.session-worktree-cleanup-empty')?.textContent, + controlsHidden: container.querySelector('.session-worktree-cleanup-summary-row')?.classList.contains('hidden'), + filterLabel: container.querySelector('.session-worktree-cleanup-age')?.getAttribute('aria-label'), + filtered: container.querySelector('.session-worktree-cleanup-controls')?.classList.contains('age-filtered'), + checked: menuActions(container, 'age').find(action => action.checked)?.id, + }; + chooseOption(container, 'age', '0'); + await timeout(0); + assert.deepStrictEqual({ + emptyState, + ages, + rows: [...container.querySelectorAll('.session-worktree-cleanup-session-link')].map(link => link.textContent), + filtered: container.querySelector('.session-worktree-cleanup-controls')?.classList.contains('age-filtered'), + }, { + emptyState: { + message: 'No worktrees match the selected filters.', + controlsHidden: false, + filterLabel: 'Filter by Inactivity: Untouched for 90 Days', + filtered: true, + checked: 'age.90', + }, + ages: [0, 90, 0], + rows: ['recent'], + filtered: false, + }); + }); + + test('shows loading and failure feedback when clearing an empty inactivity filter', async () => { + const finished = new DeferredPromise(); + const worktree = createWorktree('recent', '/repos/app'); + let reloading = false; + const { editor, container, errors } = createEditor({ + getWorktrees: async age => age === 90 ? [] : reloading ? finished.p : [worktree], + }); + await editor.setInput(disposables.add(new SessionWorktreeCleanupEditorInput()), undefined, {}, CancellationToken.None); + await timeout(0); + chooseOption(container, 'age', '90'); + await timeout(0); + const summary = container.querySelector('.session-worktree-cleanup-summary')!; + const emptySummaryHidden = summary.classList.contains('hidden'); + + reloading = true; + chooseOption(container, 'age', '0'); + const loading = { hidden: summary.classList.contains('hidden'), message: summary.textContent }; + await finished.error(new Error('Inventory unavailable')); + await timeout(0); + + assert.deepStrictEqual({ + emptySummaryHidden, + loading, + failure: { hidden: summary.classList.contains('hidden'), message: summary.textContent }, + errors, + }, { + emptySummaryHidden: true, + loading: { hidden: false, message: 'Measuring worktree storage...' }, + failure: { hidden: false, message: 'Worktree storage could not be measured.' }, + errors: ['Inventory unavailable'], + }); + }); + test('allows manually selecting active sessions and sessions waiting for input', async () => { const { container, cleaned } = await openEditor([ createWorktree('active', '/repos/app', 'active'), @@ -2508,7 +2659,7 @@ suite('SessionWorktreeCleanupEditor', () => { checked: rows.map(row => row.querySelector('[role="checkbox"]')?.getAttribute('aria-checked')), cleaned, }, { - summary: '2 of 2 matching worktrees can be cleaned up. Estimated disk usage: 200B.', + summary: '2 worktrees. Estimated disk usage: 200B.', selectAllDisabled: 'false', initialChecked: ['false', 'false'], disabled: [null, null], @@ -2553,21 +2704,29 @@ suite('SessionWorktreeCleanupEditor', () => { }); })); - test('shows a clickable cursor over filter and sort pickers but not their labels', async () => { + test('uses labeled menu buttons for filters and sorting beside the inventory summary', async () => { const { container } = await openEditor([ createWorktree('first', '/repos/app'), createWorktree('second', '/repos/other'), ]); - const labels = [...container.querySelectorAll('.session-worktree-cleanup-controls label')]; - - assert.deepStrictEqual(labels.map(label => ({ - labelCursor: mainWindow.getComputedStyle(label).cursor, - pickerCursor: mainWindow.getComputedStyle(label.querySelector('select')!).cursor, - })), [ - { labelCursor: 'default', pickerCursor: 'pointer' }, - { labelCursor: 'default', pickerCursor: 'pointer' }, - { labelCursor: 'default', pickerCursor: 'pointer' }, - ]); + const buttons = [...container.querySelectorAll('.session-worktree-cleanup-controls .action-label')]; + + assert.deepStrictEqual({ + buttons: buttons.map(button => ({ + label: button.getAttribute('aria-label'), + menu: button.getAttribute('aria-haspopup'), + })), + selects: container.querySelectorAll('select').length, + settingsBeforeSummary: !!(container.querySelector('details')!.compareDocumentPosition(container.querySelector('.session-worktree-cleanup-summary')!) & mainWindow.Node.DOCUMENT_POSITION_FOLLOWING), + }, { + buttons: [ + { label: 'Filter by Inactivity: Any Time', menu: 'true' }, + { label: 'Filter by Workspace: All Workspaces', menu: 'true' }, + { label: 'Sort Worktrees: Session Recency (Oldest First)', menu: 'true' }, + ], + selects: 0, + settingsBeforeSummary: true, + }); }); test('allows cleaning up worktrees used less than seven days ago', async () => { @@ -2578,27 +2737,25 @@ suite('SessionWorktreeCleanupEditor', () => { return []; }, }); - const picker = container.querySelector('select')!; - const options = Array.from(picker.options, option => ({ value: option.value, label: option.textContent })); - picker.value = '1'; - picker.dispatchEvent(new Event(dom.EventType.CHANGE)); + const options = menuActions(container, 'age').map(action => ({ value: action.id, label: action.label })); + chooseOption(container, 'age', '1'); await timeout(0); editor.showAllWorktrees(); await timeout(0); - assert.deepStrictEqual({ options: options.slice(0, 4), ages, selected: picker.value }, { + assert.deepStrictEqual({ options: options.slice(0, 4), ages, selected: menuActions(container, 'age').find(action => action.checked)?.id }, { options: [ - { value: '0', label: 'Any time' }, - { value: '1', label: '1 day' }, - { value: '3', label: '3 days' }, - { value: '7', label: '7 days' }, + { value: 'age.0', label: 'Any Time' }, + { value: 'age.1', label: 'Untouched for 1 Day' }, + { value: 'age.3', label: 'Untouched for 3 Days' }, + { value: 'age.7', label: 'Untouched for 7 Days' }, ], ages: [1, 0], - selected: '0', + selected: 'age.0', }); }); - test('groups cleanup guidance under a heading and keeps collapsed settings above inventory', () => { + test('keeps collapsed settings above inventory without redundant introductory guidance', () => { const { container } = createEditor(); const settings = container.querySelector('details')!; const inventory = container.querySelector('.session-worktree-cleanup-list')!; @@ -2610,11 +2767,9 @@ suite('SessionWorktreeCleanupEditor', () => { settingsCollapsed: !settings.open, settingsBeforeInventory: !!(settings.compareDocumentPosition(inventory) & mainWindow.Node.DOCUMENT_POSITION_FOLLOWING), }, { - introParagraphs: 1, - heading: 'Free up local disk space', - instructions: [ - 'Select sessions to clean up their worktrees.', - ], + introParagraphs: 0, + heading: undefined, + instructions: [], settingsCollapsed: true, settingsBeforeInventory: true, }); diff --git a/src/vs/sessions/contrib/sessions/browser/customizationsToolbar.contribution.ts b/src/vs/sessions/contrib/sessions/browser/customizationsToolbar.contribution.ts index 3f8379ac18b8..879de768128c 100644 --- a/src/vs/sessions/contrib/sessions/browser/customizationsToolbar.contribution.ts +++ b/src/vs/sessions/contrib/sessions/browser/customizationsToolbar.contribution.ts @@ -8,7 +8,7 @@ import '../../../../workbench/contrib/sessions/browser/media/customizationsToolb import { Codicon } from '../../../../base/common/codicons.js'; import { Disposable, DisposableStore } from '../../../../base/common/lifecycle.js'; import { localize } from '../../../../nls.js'; -import { Action2, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { Action2, MenuId, MenuItemAction, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; import { IActionViewItemService } from '../../../../platform/actions/browser/actionViewItemService.js'; import { ContextKeyExpr, ContextKeyExpression, IContextKey, IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; @@ -20,7 +20,7 @@ import { IAICustomizationItemsModel } from '../../../../workbench/contrib/chat/b import { ILanguageModelToolsService } from '../../../../workbench/contrib/chat/common/tools/languageModelToolsService.js'; import { IAgentHostToolSetEnablementService, isCopilotCliSessionType } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostToolSetEnablementService.js'; import { Menus } from '../../../../workbench/contrib/sessions/browser/menus.js'; -import { BaseActionViewItem, IBaseActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { BaseActionViewItem, IActionViewItemOptions, IBaseActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; import { IAction } from '../../../../base/common/actions.js'; import { $, append } from '../../../../base/browser/dom.js'; import { autorun } from '../../../../base/common/observable.js'; @@ -39,6 +39,19 @@ import { IOpenAICustomizationsCommandOptions, OPEN_AI_CUSTOMIZATIONS_COMMAND_ID import { IHoverService } from '../../../../platform/hover/browser/hover.js'; import { getExtensionSuggestionsBadgeDescription, IAgentsWindowExtensionSuggestionsService } from '../../../../workbench/contrib/sessions/browser/agentsWindowExtensionSuggestions.js'; import { ICustomizationItemConfig, readCustomizationCount, CUSTOMIZATION_ITEMS } from '../../../../workbench/contrib/sessions/browser/customizationItems.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { ChatAgentLocation, ChatConfiguration } from '../../../../workbench/contrib/chat/common/constants.js'; +import { ChatCustomizationsLocation, ChatCustomizationsLocationContext, resolveChatCustomizationsLocation } from '../../../../workbench/contrib/chat/common/customizationsLocation.js'; +import { SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING } from '../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { ChatCustomizationsActionViewItem, ChatCustomizationsHover } from '../../../../workbench/contrib/chat/browser/aiCustomization/chatCustomizationsHover.js'; +import { ChatCustomizationsTelemetry } from '../../../../workbench/contrib/chat/browser/aiCustomization/chatCustomizationsTelemetry.js'; +import { ICustomizationMigrationService } from '../../../../workbench/contrib/chat/common/promptSyntax/service/customizationMigrationService.js'; +import { getIgnoredCustomizationMigrationGroups } from '../../../../workbench/contrib/chat/browser/aiCustomization/customizationMigrationIgnoredGroups.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; +import { getChatSessionType } from '../../../../workbench/contrib/chat/common/model/chatUri.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; /** * Per-section context key indicating whether the active harness exposes @@ -67,10 +80,11 @@ const CUSTOMIZATION_OVERVIEW_ITEM: ICustomizationItemConfig = { icon: Codicon.home, }; -async function openCustomizationOverviewPage(editorService: IEditorService, harnessService: ICustomizationHarnessService, focusedSessionHostService: IFocusedSessionHostService, options?: IOpenAICustomizationsCommandOptions): Promise { - const session = focusedSessionHostService.focusedHost.get().session.get(); - if (session) { - harnessService.setActiveSession(session.resource); +async function openCustomizationOverviewPage(editorService: IEditorService, harnessService: ICustomizationHarnessService, focusedSessionHostService: IFocusedSessionHostService, options?: IOpenAICustomizationsCommandOptions, targetSession?: ISession, targetResource?: URI): Promise { + const session = targetSession ?? (targetResource ? undefined : focusedSessionHostService.focusedHost.get().session.get()); + const resource = targetResource ?? session?.resource; + if (resource) { + harnessService.setActiveSession(resource); } const input = AICustomizationManagementEditorInput.getOrCreate(); @@ -121,6 +135,7 @@ export class CustomizationLinkViewItem extends BaseActionViewItem { @IAgentHostToolSetEnablementService private readonly _toolEnablementService: IAgentHostToolSetEnablementService, @IAgentsWindowExtensionSuggestionsService private readonly _extensionSuggestionsService: IAgentsWindowExtensionSuggestionsService, @IHoverService private readonly _hoverService: IHoverService, + @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(undefined, action, options); this._viewItemDisposables = this._register(new DisposableStore()); @@ -152,6 +167,9 @@ export class CustomizationLinkViewItem extends BaseActionViewItem { this.updateEnabled(); this._viewItemDisposables.add(this._button.onDidClick(() => { + if (this._config.id === CUSTOMIZATION_OVERVIEW_ITEM.id) { + this.instantiationService.createInstance(ChatCustomizationsTelemetry).logInteraction('buttonClicked', 'sidebar'); + } this.actionRunner.run(this._action, this._context); })); @@ -222,6 +240,21 @@ export class CustomizationLinkViewItem extends BaseActionViewItem { } } +class SessionsCustomizationsActionViewItemFactory { + constructor( + @IInstantiationService private readonly instantiationService: IInstantiationService, + @IAgentsWindowExtensionSuggestionsService private readonly extensionSuggestionsService: IAgentsWindowExtensionSuggestionsService, + ) { } + + create(action: MenuItemAction, options: IActionViewItemOptions, location: 'sidebar' | 'chatToolbar' | 'chatInput'): ChatCustomizationsActionViewItem { + return this.instantiationService.createInstance( + ChatCustomizationsActionViewItem, action, options, + this.instantiationService.createInstance(ChatCustomizationsHover), + location, undefined, location === 'sidebar', this.extensionSuggestionsService.showBadge, + ); + } +} + // --- Register actions and view items --- // export class CustomizationsToolbarContribution extends Disposable implements IWorkbenchContribution { @@ -233,9 +266,65 @@ export class CustomizationsToolbarContribution extends Disposable implements IWo @IInstantiationService instantiationService: IInstantiationService, @ICustomizationHarnessService harnessService: ICustomizationHarnessService, @IContextKeyService contextKeyService: IContextKeyService, + @IConfigurationService configurationService: IConfigurationService, ) { super(); + const location = ChatCustomizationsLocationContext.bindTo(contextKeyService); + const updateLocation = () => location.set(resolveChatCustomizationsLocation( + configurationService.getValue(ChatConfiguration.ChatCustomizationsLocation), + true, + configurationService.getValue(SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING), + )); + updateLocation(); + this._register(configurationService.onDidChangeConfiguration(event => { + if (event.affectsConfiguration(ChatConfiguration.ChatCustomizationsLocation) || event.affectsConfiguration(SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING)) { + updateLocation(); + } + })); + const openCustomizations = 'sessions.openCustomizationsAtLocation'; + this._register(registerAction2(class extends Action2 { + constructor() { + super({ + id: openCustomizations, + title: localize('customizationsEntryPoint', "Customizations"), + precondition: ChatContextKeys.enabled, + }); + } + async run(accessor: ServicesAccessor, context?: unknown): Promise { + const hostService = accessor.get(IFocusedSessionHostService); + const editorService = accessor.get(IEditorService); + const harnessService = accessor.get(ICustomizationHarnessService); + const sessionsService = accessor.get(ISessionsManagementService); + const hover = accessor.get(IInstantiationService).createInstance(ChatCustomizationsHover); + const resource = hover.getSessionResource(context); + const target = sessionsService.getSession(resource) ?? sessionsService.getSessionForChatResource(resource)?.session; + const ignored = getIgnoredCustomizationMigrationGroups(accessor.get(IStorageService), getChatSessionType(resource), hover.getProjectRoot(resource)); + const hint = await accessor.get(ICustomizationMigrationService).computeMigrationHint(resource, CancellationToken.None, ignored); + await openCustomizationOverviewPage(editorService, harnessService, hostService, { migration: !!hint }, target, resource); + } + })); + for (const menu of [Menus.SessionBarToolbar, Menus.NewSessionGlobalToolbar, Menus.SidebarCustomizationsEntryPoint, MenuId.ChatExecute]) { + const sidebar = menu === Menus.SidebarCustomizationsEntryPoint; + const input = menu === MenuId.ChatExecute; + const when = ContextKeyExpr.and(ChatContextKeys.enabled, ChatCustomizationsLocationContext.isEqualTo(input ? 'chatInput' : sidebar ? 'sidebar' : 'chatToolbar')); + this._register(MenuRegistry.appendMenuItem(menu, { + command: { + id: openCustomizations, + title: localize('customizationsEntryPoint', "Customizations"), + icon: sidebar ? undefined : Codicon.extensions, + }, + group: 'navigation', + order: input ? -12 : 6, + when: input + ? ContextKeyExpr.and(when, ChatContextKeys.location.isEqualTo(ChatAgentLocation.Chat), ChatContextKeys.inQuickChat.negate(), ChatContextKeys.currentlyEditing.negate()) + : when, + })); + this._register(actionViewItemService.register(menu, openCustomizations, (action, options, scopedInstantiationService) => action instanceof MenuItemAction + ? scopedInstantiationService.createInstance(SessionsCustomizationsActionViewItemFactory).create(action, options, input ? 'chatInput' : sidebar ? 'sidebar' : 'chatToolbar') + : undefined, undefined)); + } + // Per-section visibility context keys, kept in sync with the active // harness's `hiddenSections`. Each customization action's menu entry // is gated on its key so that harnesses (e.g. Claude, AHP) which diff --git a/src/vs/sessions/contrib/sessions/browser/media/automationsCards.css b/src/vs/sessions/contrib/sessions/browser/media/automationsCards.css index e10cd7bfd648..bf2c2c6da6c0 100644 --- a/src/vs/sessions/contrib/sessions/browser/media/automationsCards.css +++ b/src/vs/sessions/contrib/sessions/browser/media/automationsCards.css @@ -140,11 +140,6 @@ display: none; } -.automations-ownership-summary:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); - outline-offset: var(--vscode-strokeThickness); -} - .automations-ownership-chevron, .automations-ownership-info { display: inline-flex; @@ -215,13 +210,25 @@ touch-action: manipulation; } -.automations-card:hover { - background-color: var(--vscode-list-hoverBackground); +.automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered:has(> .automations-card-actions:is(:hover, .hovered, .menu-open)) { + background-color: transparent; + outline: none; } -.automations-card:has(> .automations-card-main:focus-visible) { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; +:is(.hc-black, .hc-light) .automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered:has(> .automations-card-actions:is(:hover, .hovered, .menu-open)) { + border-color: var(--vscode-editorWidget-border); +} + +.automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered:has(> .automations-card-main:is(:focus-visible, .focus-visible)) { + background-color: transparent; + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +:is(.hc-black, .hc-light) .automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered:has(> .automations-card-main:is(:focus-visible, .focus-visible)) { + border-color: transparent; + outline-width: calc(2 * var(--vscode-strokeThickness)); + outline-offset: calc(-2 * var(--vscode-strokeThickness)); } /* Card Main Content */ @@ -354,9 +361,9 @@ opacity: 0; } -.automations-card:hover .automations-card-actions, +.automations-card:is(:hover, .hovered) .automations-card-actions, .automations-card:focus-within .automations-card-actions, -.automations-card .automations-card-actions.menu-open { +.automations-card .automations-card-actions:is(.hovered, .menu-open) { opacity: 1; } @@ -368,7 +375,7 @@ height: 24px; padding: 0; border: none; - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); background: transparent; color: var(--vscode-icon-foreground); cursor: pointer; @@ -380,11 +387,6 @@ background-color: var(--vscode-toolbar-hoverBackground); } -.automations-card-actions .monaco-button.automations-card-action-button:focus-visible { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; -} - .automations-card-actions .monaco-button.automations-card-action-button.disabled { opacity: 0.4; cursor: default; @@ -426,6 +428,23 @@ font-size: 12px; } +.automations-cards-create-dropdown > .automations-cards-create-button, +.automations-cards-create-dropdown > .automations-cards-state-create-button { + max-width: none; + margin-top: 0; + white-space: nowrap; +} + +.automations-cards-state > .automations-cards-create-dropdown { + margin-top: var(--vscode-spacing-size120); +} + +/* The header's flex row would otherwise leave the chevron shorter than the primary button. */ +.custom-view-header-actions .monaco-button-dropdown > .monaco-button.monaco-dropdown-button { + height: auto; + align-self: stretch; +} + /* Loading and error states */ .automations-cards-state { display: flex; @@ -484,6 +503,31 @@ margin-top: var(--vscode-spacing-size40); } +.automations-cards-partial-state-content { + min-width: 0; +} + +.automations-cards-partial-state-message { + display: inline; +} + +.automations-cards-partial-state-message:not(:empty) + .automations-manage-remotes { + margin-left: var(--vscode-spacing-size80); +} + +.automations-manage-remotes { + display: inline-flex; + align-items: center; + gap: var(--vscode-spacing-size60); + font-size: var(--vscode-fontSize-label1); +} + +.automations-manage-remotes-count { + color: var(--vscode-descriptionForeground); + font-style: italic; + white-space: nowrap; +} + .automations-cards-partial-state { display: flex; align-items: center; @@ -547,11 +591,6 @@ display: none; } -.automations-template-section-summary:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); - outline-offset: var(--vscode-strokeThickness); -} - .automations-template-section-chevron { display: inline-flex; align-items: center; @@ -622,15 +661,6 @@ touch-action: manipulation; } -.automations-template-card:hover { - background-color: var(--vscode-list-hoverBackground); -} - -.automations-template-card:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); - outline-offset: calc(-1 * var(--vscode-strokeThickness)); -} - .automations-template-card-name { display: flex; align-items: center; diff --git a/src/vs/sessions/contrib/sessions/browser/media/newSessionActionViewItem.css b/src/vs/sessions/contrib/sessions/browser/media/newSessionActionViewItem.css index 69542790edcf..79c87b6ffe4f 100644 --- a/src/vs/sessions/contrib/sessions/browser/media/newSessionActionViewItem.css +++ b/src/vs/sessions/contrib/sessions/browser/media/newSessionActionViewItem.css @@ -15,7 +15,7 @@ unscoped so the widget renders identically wherever it is mounted. */ padding: 2px 8px; font-size: var(--vscode-fontSize-label1, 12px); line-height: 18px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); border: var(--vscode-strokeThickness) solid var(--vscode-agentsNewSessionButton-border, var(--vscode-button-border, transparent)); background-color: var(--vscode-agentsNewSessionButton-background, transparent); color: var(--vscode-agentsNewSessionButton-foreground, var(--vscode-foreground)); diff --git a/src/vs/sessions/contrib/sessions/browser/media/sessionsTitleBarWidget.css b/src/vs/sessions/contrib/sessions/browser/media/sessionsTitleBarWidget.css index c2e6f53172cb..28627768436e 100644 --- a/src/vs/sessions/contrib/sessions/browser/media/sessionsTitleBarWidget.css +++ b/src/vs/sessions/contrib/sessions/browser/media/sessionsTitleBarWidget.css @@ -37,12 +37,18 @@ transition: opacity 120ms ease-out; } -.command-center .agent-sessions-titlebar-container:hover { +.command-center .agent-sessions-titlebar-container:is(:hover, .hovered) { color: var(--vscode-commandCenter-activeForeground); background-color: var(--vscode-commandCenter-activeBackground); border-color: var(--vscode-commandCenter-activeBorder); } +:is(.hc-black, .hc-light) .command-center .agent-sessions-titlebar-container:not(.agent-sessions-titlebar-requires-input, .agent-sessions-titlebar-approved):is(:hover, .hovered):not(:focus-visible) { + border-color: transparent; + outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + /* Session pill - clickable area for session picker, fills the command center box */ .command-center .agent-sessions-titlebar-container .agent-sessions-titlebar-pill { display: flex; @@ -59,9 +65,17 @@ opacity: 0.6; } -.command-center .agent-sessions-titlebar-container:focus { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; +.monaco-workbench .command-center .agent-sessions-titlebar-container:focus:not(:focus-visible) { + outline: none; +} + +.command-center .agent-sessions-titlebar-container:focus-visible { + outline: var(--vscode-strokeThickness, 1px) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + +:is(.hc-black, .hc-light) .command-center .agent-sessions-titlebar-container:focus-visible { + border-color: transparent; } /* Center group: workspace icon and folder */ diff --git a/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts b/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts index d87af2ed15ee..4de44f96059a 100644 --- a/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts +++ b/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts @@ -18,7 +18,10 @@ import { NEW_SESSION_BUTTON_STYLE_SETTING, NEW_SESSION_BUTTON_STYLE_TREATMENT, N import { SessionsView, SessionsViewId } from '../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; import { AutomationsCustomViewContribution } from './views/automationsView.js'; import './views/sessionsViewActions.js'; -import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { getEnabledViewContainerContextKey } from '../../../../workbench/common/contextkeys.js'; +import { ChatViewContainerId, ChatViewOpenKeybindings } from '../../../../workbench/contrib/chat/browser/chat.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationNode, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { SESSIONS_LIST_INDENT_ITEMS_SETTING, SESSIONS_LIST_SHOW_ARCHIVED_BY_DEFAULT_SETTING, SESSIONS_LIST_SHOW_EMPTY_DEFAULT_GROUPS_SETTING, SESSIONS_LIST_SHOW_UNREAD_IN_COLLAPSED_SECTIONS_SETTING, SessionsListStateMigrationContribution } from '../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { SessionsMouseNavigationContribution } from './sessionsMouseNavigation.js'; @@ -46,13 +49,22 @@ const agentSessionsViewContainer: ViewContainer = Registry.as pinned > custom group > ungr const resetFilters = optionalBoolean(operation, 'resetFilters'); const filters = this.readFilters(operation, list); - // Validate before changing anything, so a rejected operation changes nothing. - if (grouping === SessionsGrouping.Inbox && !this.configurationService.getValue(SESSIONS_LIST_INBOX_ENABLED_SETTING)) { - throw new SessionsListToolInputError(`Inbox Mode requires "${SESSIONS_LIST_INBOX_ENABLED_SETTING}" to be enabled.`); - } if (resetFilters) { view.resetFilters(); } @@ -503,7 +499,7 @@ const organizeInputSchema: IJSONSchema & { type: 'object' } = { 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, or use inbox triage categories (setView). Inbox mode requires sessions.list.inboxEnabled. It preserves custom organization and presents attention-state categories as collapsible groups, with pinned sessions always visible.' }, + grouping: { type: 'string', enum: Object.values(SessionsGrouping), description: 'Section the list by workspace, repository, environment, or date, or use inbox triage categories (setView). Inbox mode preserves custom organization and presents attention-state categories as collapsible groups, with pinned sessions always visible.' }, sorting: { type: 'string', enum: Object.values(SessionsSorting), description: 'Sort sessions by creation or last update time (setView).' }, filters: { type: 'array', diff --git a/src/vs/sessions/contrib/sessions/browser/sessionsTitleBarWidget.ts b/src/vs/sessions/contrib/sessions/browser/sessionsTitleBarWidget.ts index fcda8b81834d..4826244148ba 100644 --- a/src/vs/sessions/contrib/sessions/browser/sessionsTitleBarWidget.ts +++ b/src/vs/sessions/contrib/sessions/browser/sessionsTitleBarWidget.ts @@ -397,7 +397,11 @@ export class SessionsTitleBarWidget extends BaseActionViewItem { workspaceEl.textContent = contextTitle; workspaceGroup.appendChild(workspaceEl); centerGroup.appendChild(workspaceGroup); - this._dynamicDisposables.add(this.hoverService.setupManagedHover(this.options.hoverDelegate ?? getDefaultHoverDelegate('element'), workspaceEl, contextTitle)); + this._dynamicDisposables.add(this.hoverService.setupManagedHover( + this.options.hoverDelegate ?? getDefaultHoverDelegate('element'), + workspaceEl, + () => workspaceEl.scrollWidth > workspaceEl.clientWidth ? contextTitle : undefined, + )); } if (workspaceInfo?.branch) { @@ -413,7 +417,11 @@ export class SessionsTitleBarWidget extends BaseActionViewItem { branchEl.textContent = workspaceInfo.branch; branchGroup.appendChild(branchEl); centerGroup.appendChild(branchGroup); - this._dynamicDisposables.add(this.hoverService.setupManagedHover(this.options.hoverDelegate ?? getDefaultHoverDelegate('element'), branchEl, workspaceInfo.branch)); + this._dynamicDisposables.add(this.hoverService.setupManagedHover( + this.options.hoverDelegate ?? getDefaultHoverDelegate('element'), + branchEl, + () => branchEl.scrollWidth > branchEl.clientWidth ? workspaceInfo.branch : undefined, + )); } sessionPill.appendChild(centerGroup); diff --git a/src/vs/sessions/contrib/sessions/browser/views/automationCataloguePresentation.ts b/src/vs/sessions/contrib/sessions/browser/views/automationCataloguePresentation.ts index 52d3c18026ce..0ca2c07c934d 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/automationCataloguePresentation.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/automationCataloguePresentation.ts @@ -5,6 +5,9 @@ import { groupByMap } from '../../../../../base/common/collections.js'; import { localize } from '../../../../../nls.js'; +import { cloudSandboxAddress } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; +import { agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { getEntryAddress, IRemoteAgentHostEntry, RemoteAgentHostEntryType } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import type { IAutomationDescriptor } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; import type { IAutomationProviderDescriptor } from '../../../../../workbench/contrib/chat/common/automations/automationService.js'; @@ -20,6 +23,44 @@ export function getAutomationOwnershipGroups(automations: readonly IAutomationDe ].filter(group => group.automations.length > 0 || group.ownership === 'user' && automations.some(automation => automation.ownership === 'repository')); } +export interface IAutomationRemoteStatusPresentation { + readonly tunnelEntries: readonly IRemoteAgentHostEntry[]; + readonly replacedTunnelProviderIds: ReadonlySet; + readonly ignoredGitHubEnvironmentProviderIds: ReadonlySet; + readonly visibleUnavailableProviders: readonly IAutomationProviderDescriptor[]; + readonly suppressedAllReasons: boolean; +} + +export function getAutomationRemoteStatusPresentation( + unavailableProviders: readonly IAutomationProviderDescriptor[], + configuredEntries: readonly IRemoteAgentHostEntry[], + githubEnvironmentIds: readonly string[], + replaceTunnelWarnings: boolean, +): IAutomationRemoteStatusPresentation { + const tunnelEntries = configuredEntries.filter(entry => entry.connection.type === RemoteAgentHostEntryType.Tunnel); + const tunnelProviderIds = new Set(tunnelEntries.map(entry => `agenthost-${agentHostAuthority(getEntryAddress(entry))}`)); + const githubEnvironmentProviderIds = new Set(githubEnvironmentIds + .map(environmentId => `agenthost-${agentHostAuthority(cloudSandboxAddress(environmentId))}`)); + const replacedTunnelProviderIds = new Set(replaceTunnelWarnings + ? unavailableProviders + .filter(provider => provider.unavailableReasonCode === 'disconnected' && tunnelProviderIds.has(provider.id)) + .map(provider => provider.id) + : []); + const ignoredGitHubEnvironmentProviderIds = new Set(unavailableProviders + .filter(provider => provider.unavailableReasonCode === 'disconnected' && githubEnvironmentProviderIds.has(provider.id)) + .map(provider => provider.id)); + const visibleUnavailableProviders = unavailableProviders.filter(provider => + !ignoredGitHubEnvironmentProviderIds.has(provider.id) + && !replacedTunnelProviderIds.has(provider.id)); + return { + tunnelEntries, + replacedTunnelProviderIds, + ignoredGitHubEnvironmentProviderIds, + visibleUnavailableProviders, + suppressedAllReasons: unavailableProviders.length > 0 && visibleUnavailableProviders.length === 0, + }; +} + export function getUnavailableAutomationsReasons(unavailableProviders: readonly IAutomationProviderDescriptor[]): string[] { const reasons: string[] = []; const groups = groupByMap( diff --git a/src/vs/sessions/contrib/sessions/browser/views/automationRunProgress.ts b/src/vs/sessions/contrib/sessions/browser/views/automationRunProgress.ts index c140370dee2b..430e94798d61 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/automationRunProgress.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/automationRunProgress.ts @@ -5,9 +5,20 @@ import { IReader } from '../../../../../base/common/observable.js'; import { isEqual } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; import { IAutomationRun } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; import { IChatModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +export function isLocalAutomationRunStarting(run: IAutomationRun, hasPresentedSession: (resource: URI) => boolean, hasSession: (resource: URI) => boolean): boolean { + if (run.externalResource || run.status === 'failed') { + return false; + } + if (!run.sessionResource) { + return run.status === 'pending' || run.status === 'running'; + } + return !hasPresentedSession(run.sessionResource) && (run.status !== 'completed' || hasSession(run.sessionResource)); +} + /** Overlays newer local conversation progress without changing authoritative history. */ export function automationRunWithLocalProgress(run: IAutomationRun, models: Iterable, reader?: IReader): IAutomationRun { if (!run.externalResource || !run.sessionResource) { diff --git a/src/vs/sessions/contrib/sessions/browser/views/automationsAccessibility.ts b/src/vs/sessions/contrib/sessions/browser/views/automationsAccessibility.ts index 0d1231060047..eae56da036fc 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/automationsAccessibility.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/automationsAccessibility.ts @@ -5,8 +5,13 @@ import { localize } from '../../../../../nls.js'; import { getActiveElement, isHTMLElement } from '../../../../../base/browser/dom.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType } from '../../../../../platform/accessibility/browser/accessibleView.js'; import { AccessibleViewRegistry, IAccessibleViewImplementation } from '../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IMissionControlEnvironmentService } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { IRemoteAgentHostService, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { AccessibilityVerbositySettingId } from '../../../../../workbench/contrib/accessibility/browser/accessibilityConfiguration.js'; import { IAutomationDescriptor, IAutomationRun, IAutomationSchedule } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; @@ -20,9 +25,10 @@ import { IWorkbenchLayoutService, Parts } from '../../../../../workbench/service import { AutomationsCustomViewFocusContext } from '../../../../common/agentsWindowContextKeys.js'; import { SESSIONS_LIST_SHOW_AUTOMATION_SESSIONS_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; import { IAutomationTemplate, readAutomationTemplates } from './automationTemplates.js'; -import { formatUnavailableAutomationsMessage, getAutomationOwnershipGroups } from './automationCataloguePresentation.js'; -import { automationRunWithLocalProgress } from './automationRunProgress.js'; +import { formatUnavailableAutomationsMessage, getAutomationOwnershipGroups, getAutomationRemoteStatusPresentation } from './automationCataloguePresentation.js'; +import { automationRunWithLocalProgress, isLocalAutomationRunStarting } from './automationRunProgress.js'; class AutomationsCustomViewAccessibilityHelp implements IAccessibleViewImplementation { readonly type = AccessibleViewType.Help; @@ -41,6 +47,7 @@ class AutomationsCustomViewAccessibilityHelp implements IAccessibleViewImplement const pluginTemplatesVisible = templates.some(template => !!template.source); const content = [ localize('automationsCustomView.help.overview', "You are in the Automations view. It contains available automation cards followed by run history. Loading, unavailable, and error messages indicate that the catalogue may be incomplete."), + localize('automationsCustomView.help.manageRemotes', "When a dev tunnel is disconnected and remote management is enabled, the unavailable message shows how many dev tunnels are detected followed by Manage Remotes. Tab to this link and press Enter or Space to open Remote Environments, where you can manage dev tunnels. GitHub Environments do not appear in Automations warnings or this count."), localize('automationsCustomView.help.disabled', "Disabled automations are grouped above templates in the Disabled automations section, which starts collapsed. Press Enter or Space on its heading to expand or collapse it. The expansion state is remembered on this machine. Run history and the Accessible View still include disabled automations."), localize('automationsCustomView.help.authority', "Automations run on their selected provider, not in this window. Creation and changes require an available provider that supports automations. Run now requests execution from that provider; a disconnected or unsupported provider never falls back to local execution. To use another provider, duplicate the automation. The original history stays with its provider, and an enabled original keeps scheduling until you disable it."), ...(builtInTemplatesVisible ? [ @@ -52,7 +59,10 @@ class AutomationsCustomViewAccessibilityHelp implements IAccessibleViewImplement localize('automationsCustomView.help.pluginTemplates', "The Templates from Plugins section is available whenever enabled plugins provide templates. Press Enter or Space on its disclosure control to expand or collapse it. A blue marker indicates templates added since the section was last expanded. Plugin templates start disabled."), ] : []), localize('automationsCustomView.help.sharing', "Use Import Automation in the view header, or drop one .automation.md file anywhere in the view, to review a shared Automation blueprint. Imported Automations start disabled. For Agent Host automations, open the context menu and choose Export to save a portable blueprint. Cloud automations do not currently offer Export."), - localize('automationsCustomView.help.cards2', "For saved automations, Tab to a card's Edit control and action buttons. Use Left Arrow and Right Arrow to move between Run now and More Actions. Press Enter or Space to activate a control. Edit, or clicking anywhere else on the card, opens the automation dialog. More Actions opens the automation menu. Duplicate opens a prefilled New automation dialog for portable schedules and is unavailable for event-triggered automations. Disable prevents future runs, and Delete asks for confirmation. When the provider supports it, clear Delete Run History in that confirmation to keep previous runs. Run now requests execution from the selected provider when available."), + localize('automationsCustomView.help.creation', "Create with Agent opens a new session with /automate prefilled and the input focused. This button is in the empty state, or in the view header once automations exist. Choose Create Manually from its adjacent More Actions dropdown to open the automation dialog. In the header, use Left Arrow and Right Arrow to move between the button and dropdown; in the empty state, use Tab and Shift+Tab. Press Enter or Space to activate either control. Create Manually remains available while chat is not ready."), + localize('automationsCustomView.help.spotlight', "On your first visit, a spotlight introduces Create with Agent. Press Escape or activate Got It to dismiss it, or activate the highlighted button to start creating. The introduction does not appear again."), + localize('automationsCustomView.help.replaceDraft', "When saved drafts are disabled and your new-session draft contains text or attachments, Create with Agent asks before replacing its text with /automate. Existing attachments are kept. Choose View Draft to return to the new session page without changing the draft, or Cancel to stay in Automations. With saved drafts enabled, this warning is skipped."), + localize('automationsCustomView.help.cards2', "For saved automations, Tab to a card's Edit control and action buttons. Use Left Arrow and Right Arrow to move between Run now and More Actions. Press Enter or Space to activate a control. Edit, or clicking anywhere else on the card, opens the automation dialog. More Actions opens the automation menu. Duplicate opens a prefilled New automation dialog for portable schedules and is unavailable for event-triggered automations. Disable prevents future runs. Delete asks for confirmation and warns that the automation, its run history, and associated sessions will be permanently deleted and that this cannot be undone. Run now requests execution from the selected provider when available."), localize('automationsCustomView.help.externalDefinition', "For cloud automation cards, More Actions also offers Open on GitHub to open the automation's details in your browser."), localize('automationsCustomView.help.ownership', "Saved cards are grouped under collapsible Your automations and Shared automations sections. Press Enter or Space on a section header to expand or collapse it. The Shared automations info icon explains who can view and edit those automations. Cloud creation has an Owner control after Tools. Use the arrow keys to choose Only me or Repository; Only me is the default. Ownership cannot be changed when editing. Repository readers can view Shared automations; writers can manage them. A failed save leaves the dialog open with the server's explanation above Create."), localize('automationsCustomView.help.dialog', "In the automation dialog, Target controls are above the prompt. Agent and model pickers are inside the prompt input, and execution mode and permission controls are below it. Use Tab and Shift+Tab to move between fields and pickers. When creating an automation, you only need to enter a prompt. An empty name is derived from the prompt, and the target defaults to No workspace unless one is already supplied. An available Agent Host that supports the target is still required."), @@ -63,7 +73,7 @@ class AutomationsCustomViewAccessibilityHelp implements IAccessibleViewImplement ...(accessor.get(ISessionsManagementService).getAllProviderSessionTypes().some(type => automationService.getProviderConfiguration?.(type.providerId)?.sessionTypes.includes(type.sessionType.id)) ? [ localize('automationsCustomView.help.cloudDialog', "When creating an automation and cloud automations are enabled, a Run in the cloud switch, described as Preview, follows the Name field; press Space to turn it on or off. If cloud automations cannot be reached when you turn it on, the switch turns back off and a message asks you to try again in a few moments. When it is on, Cloud is the agent and the workspace picker lists Git-backed workspaces. Only GitHub repositories that support cloud automation management can be selected; unavailable repositories are announced with the reason. Choose Add repository to search for a repository or paste its URL. A matching local folder is retained. If cloud automations become unavailable while the switch is on, Cloud stays selected and Create is unavailable until they return or, for a new automation, you turn the switch off. Turning the switch off restores the previous local workspace and agent, or otherwise selects Copilot when it is available. Cloud models are configured in the prompt section. In the Tools section, the button shows All tools allowed or the number of tools allowed. Activate it to open a searchable checklist of the tools GitHub offers, grouped by category. Categories start collapsed; use Right Arrow to expand one. Press Space to toggle a tool or category. Each change applies immediately to the dialog; Enter or Escape closes the checklist without discarding changes. Save or Create saves the automation. New automations start with every listed tool selected. While the list loads the button is unavailable, and if it cannot be loaded a Retry button appears. Trigger follows the tools controls. Scheduled triggers display local time; GitHub stores a fixed UTC schedule, so the local run time may shift when daylight saving time changes. When editing a cloud automation, the switch and workspace picker are disabled because changing the repository or provider requires duplication. Editing preserves enabled state; enable or disable an automation from its card."), ] : []), - localize('automationsCustomView.help.history', "Run history is grouped by date. While a run is waiting for its session, a lightweight row shows the automation name with a Working... description. Once the session is available, use Up Arrow and Down Arrow to navigate the Sessions list, Enter to open, and Tab to reach Stop, the configured Archive or Mark as Done action, or Delete when available. Open a row's context menu, for example with Shift+F10, to rename it, change its active or read state, or delete it. Delete permanently deletes the session and removes it from run history after confirmation. When a removed automation retains history, the context menu also offers Delete Run History. The row says Deleting... while deletion is in progress. If deletion is interrupted, it offers Retry Delete Run History."), + localize('automationsCustomView.help.history', "Run history is grouped by date. While a run is waiting for its session, its automation card reports Running. Once the session is available, use Up Arrow and Down Arrow to navigate the Sessions list, Enter to open, and Tab to reach Stop, the configured Archive or Mark as Done action, or Delete when available. Open a row's context menu, for example with Shift+F10, to rename it, change its active or read state, or delete it. Delete permanently deletes the session and removes it from run history after confirmation. When a removed automation retains history, the context menu also offers Delete Run History. The row says Deleting... while deletion is in progress. If deletion is interrupted, it offers Retry Delete Run History."), localize('automationsCustomView.help.sessionsList', "Run sessions are listed here rather than in the Sessions list. Open a run's context menu and choose Show in Sessions List to also list its session there, or Hide from Sessions List to list it only here again, even after later messages. The {0} setting controls when run sessions automatically also appear in the Sessions list: always, after you send a message in one, or never.", SESSIONS_LIST_SHOW_AUTOMATION_SESSIONS_SETTING), localize('automationsCustomView.help.cloudHistory', "Cloud history shows the repository, status, and last updated time even when no local session is available. When a cloud run has a session on GitHub that is not yet loaded in VS Code, click its row, or Tab to its title and press Enter or Space, to open that exact session. Tab to a row's toolbar and use Left Arrow and Right Arrow to reach Open on GitHub and Stop when supported. Archive or Mark as Done is unavailable until the cloud run and its conversation have finished. It changes local session state, not the task on GitHub. Stop requests remote cancellation; the status changes when GitHub reports it. Follow-up requests show conversation progress and restart bounded history discovery. Use Refresh in the view header to reload definitions and history. Active cloud runs refresh every 15 seconds without moving the history rows; idle definitions do not poll."), localize('automationsCustomView.help.read', "Completed and failed runs that have not been opened are announced as unread. Use Mark all as read in the history header, or focus the Automations sidebar shortcut and press Shift+F10 to choose Mark All as Read from its context menu. This marks available completed and failed runs as read, except cloud runs with an active follow-up."), @@ -91,28 +101,55 @@ class AutomationsCustomViewAccessibleView implements IAccessibleViewImplementati const sessionsManagementService = accessor.get(ISessionsManagementService); const chatService = accessor.get(IChatService); const agentPluginService = accessor.get(IAgentPluginService); + const configurationService = accessor.get(IConfigurationService); + const remoteAgentHostService = accessor.get(IRemoteAgentHostService); + const missionControlEnvironmentService = accessor.get(IMissionControlEnvironmentService); const restoreFocus = createFocusRestorer(layoutService); return new AccessibleContentProvider( AccessibleViewProviderId.Automations, { type: AccessibleViewType.View }, - () => buildAutomationsAccessibleContent( - automationService.automations.get(), - automationService.runs.get().filter(run => - run.status === 'pending' - || run.status === 'running' - || !!run.externalResource - || (!!run.sessionResource && !!sessionsManagementService.getSession(run.sessionResource)) - || automationService.getAutomationHistoryState?.(run.automationId) !== undefined - ), - automationService.catalogueState.get(), - readAutomationTemplates(agentPluginService.plugins.get()), - automationService.unavailableProviders.get(), - automationService.historyState?.get(), - chatService.chatModels.get(), - id => automationService.getAutomationHistoryName?.(id), - id => automationService.getAutomationHistoryState?.(id), - id => automationService.canDeleteAutomationHistory?.(id) === true, - ), + () => { + const runs = automationService.runs.get(); + const sessions = sessionsManagementService.getSessions(); + const hasCatalogedSession = (resource: URI) => sessions.some(session => isEqual(session.resource, resource)); + const hasSession = (resource: URI) => sessionsManagementService.getSession(resource) !== undefined; + const startingAutomationIds = new Set(runs + .filter(run => isLocalAutomationRunStarting(run, hasCatalogedSession, hasSession)) + .map(run => run.automationId)); + const catalogueState = automationService.catalogueState.get(); + const unavailableProviders = automationService.unavailableProviders.get(); + const remoteManagementEnabled = configurationService.getValue(RemoteAgentHostsEnabledSettingId) + && configurationService.getValue(ENVIRONMENT_PICKER_SETTING) + && configurationService.getValue(ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING); + const remoteStatusPresentation = getAutomationRemoteStatusPresentation( + unavailableProviders, + remoteAgentHostService.configuredEntries, + missionControlEnvironmentService.hosts.get().map(host => host.id), + remoteManagementEnabled, + ); + return buildAutomationsAccessibleContent( + automationService.automations.get(), + runs.filter(run => { + const retainedHistory = automationService.getAutomationHistoryState?.(run.automationId) !== undefined; + return retainedHistory || ( + !isLocalAutomationRunStarting(run, hasCatalogedSession, hasSession) + && ( + !!run.externalResource + || (!!run.sessionResource && hasCatalogedSession(run.sessionResource)) + ) + ); + }), + catalogueState === 'unavailable' && remoteStatusPresentation.suppressedAllReasons ? 'ready' : catalogueState, + readAutomationTemplates(agentPluginService.plugins.get()), + remoteStatusPresentation.visibleUnavailableProviders, + automationService.historyState?.get(), + chatService.chatModels.get(), + id => automationService.getAutomationHistoryName?.(id), + id => automationService.getAutomationHistoryState?.(id), + id => automationService.canDeleteAutomationHistory?.(id) === true, + startingAutomationIds, + ); + }, restoreFocus, AccessibilityVerbositySettingId.Automations, ); @@ -130,7 +167,7 @@ function createFocusRestorer(layoutService: IWorkbenchLayoutService): () => void }; } -export function buildAutomationsAccessibleContent(automations: readonly IAutomationDescriptor[], runs: readonly IAutomationRun[], catalogueState: AutomationCatalogueState, templates: readonly IAutomationTemplate[] = readAutomationTemplates([]), unavailableProviders: readonly IAutomationProviderDescriptor[] = [], historyState?: AutomationCatalogueState, chatModels: Iterable = [], historyName?: (id: string) => string | undefined, retainedHistoryState?: (id: string) => AutomationHistoryState | undefined, canDeleteRetainedHistory?: (id: string) => boolean): string { +export function buildAutomationsAccessibleContent(automations: readonly IAutomationDescriptor[], runs: readonly IAutomationRun[], catalogueState: AutomationCatalogueState, templates: readonly IAutomationTemplate[] = readAutomationTemplates([]), unavailableProviders: readonly IAutomationProviderDescriptor[] = [], historyState?: AutomationCatalogueState, chatModels: Iterable = [], historyName?: (id: string) => string | undefined, retainedHistoryState?: (id: string) => AutomationHistoryState | undefined, canDeleteRetainedHistory?: (id: string) => boolean, startingAutomationIds: ReadonlySet = new Set()): string { const lines = [localize('automationsAccessibleView.title', "Automations")]; const builtInTemplates = templates.filter(template => !template.source); const pluginTemplates = templates.filter(template => !!template.source); @@ -145,9 +182,14 @@ export function buildAutomationsAccessibleContent(automations: readonly IAutomat } for (const automation of group.automations) { lines.push(''); - lines.push(automation.enabled - ? localize('automationsAccessibleView.automation', "{0}, enabled", automation.name) - : localize('automationsAccessibleView.automationDisabled', "{0}, disabled", automation.name)); + const starting = startingAutomationIds.has(automation.id); + lines.push(starting + ? automation.enabled + ? localize('automationsAccessibleView.automationRunning', "{0}, enabled, Running", automation.name) + : localize('automationsAccessibleView.automationDisabledRunning', "{0}, disabled, Running", automation.name) + : automation.enabled + ? localize('automationsAccessibleView.automation', "{0}, enabled", automation.name) + : localize('automationsAccessibleView.automationDisabled', "{0}, disabled", automation.name)); const triggers = automationTriggerSummary(automation.cloudTrigger?.triggers ?? {}); lines.push(triggers ? localize('automationsAccessibleView.triggers', "Triggers: {0}", triggers) : localize('automationsAccessibleView.schedule', "Schedule: {0}", formatSchedule(automation.schedule))); diff --git a/src/vs/sessions/contrib/sessions/browser/views/automationsView.ts b/src/vs/sessions/contrib/sessions/browser/views/automationsView.ts index acfba5b7a3e9..f4fc12f6efc0 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/automationsView.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/automationsView.ts @@ -4,11 +4,12 @@ *--------------------------------------------------------------------------------------------*/ import '../media/automationsCards.css'; +import '../../../../../workbench/contrib/sessions/browser/media/disclosure.css'; import './automationsAccessibility.js'; import * as DOM from '../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; -import { Button, ButtonBar, IButton } from '../../../../../base/browser/ui/button/button.js'; +import { Button, ButtonBar, ButtonWithDropdown, IButton } from '../../../../../base/browser/ui/button/button.js'; import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { defaultButtonStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; @@ -28,6 +29,11 @@ import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { HoverStyle } from '../../../../../base/browser/ui/hover/hover.js'; import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { Link } from '../../../../../platform/opener/browser/link.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { getEntryAddress, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { normalizeRemoteAgentHostAddress } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { IMissionControlEnvironmentService } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { WorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import type { IAutomationDescriptor, IAutomationRun, IAutomationSchedule, AutomationTarget } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; @@ -72,15 +78,20 @@ import { Action2, MenuItemAction, MenuRegistry, registerAction2 } from '../../.. import { IActionViewItemService } from '../../../../../platform/actions/browser/actionViewItemService.js'; import { ChatSessionArchiveActionWording, ChatSessionArchiveActionWordingSettingId, getChatSessionArchiveActionPresentation, getChatSessionArchiveActionWording } from '../../../../../platform/chat/common/sessionArchiveActions.js'; import { BaseActionViewItem, IActionViewItemOptions } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; -import { Action, IAction } from '../../../../../base/common/actions.js'; +import { Action, IAction, toAction } from '../../../../../base/common/actions.js'; import { SessionIsArchivedContext, SessionIsReadContext, SessionSupportsRenameContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { AutomationsCustomViewFocusContext, AutomationsHasItemsContext } from '../../../../common/agentsWindowContextKeys.js'; import { SessionsFlatList, SessionItemStatusContext, formatSessionListTime } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../../../../../workbench/contrib/sessions/browser/automationsConstants.js'; -import { ARCHIVE_SESSION_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, RENAME_SESSION_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; +import { ARCHIVE_SESSION_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, OPEN_REMOTES_EDITOR_COMMAND_ID, RENAME_SESSION_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; +import { ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING, NEW_SESSION_ACTION_ID } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; +import { INewSessionInAgentsWindowOptions } from '../../../../../workbench/contrib/chat/common/chatSessionsService.js'; +import { INewSessionComposerService } from '../../../../../workbench/contrib/sessions/browser/newSessionComposerService.js'; +import { ISessionDraftsService } from '../../../../../workbench/contrib/sessions/browser/sessionDraftsService.js'; +import { readNewChatDraftState } from '../../../../../workbench/contrib/sessions/common/newChatDraftState.js'; import { IAutomationTemplate, readAutomationTemplates } from './automationTemplates.js'; -import { getAutomationOwnershipGroups, getUnavailableAutomationsReasons } from './automationCataloguePresentation.js'; -import { automationRunWithLocalProgress } from './automationRunProgress.js'; +import { getAutomationOwnershipGroups, getAutomationRemoteStatusPresentation, getUnavailableAutomationsReasons } from './automationCataloguePresentation.js'; +import { automationRunWithLocalProgress, isLocalAutomationRunStarting } from './automationRunProgress.js'; import { logAutomationViewShown, withAutomationDialogPersistenceTelemetry } from '../../../automations/browser/automationTelemetry.js'; const $ = DOM.$; @@ -101,9 +112,10 @@ function canArchiveAutomationSession(session: ISession, reader?: IReader): boole } export const SEEN_PLUGIN_AUTOMATION_TEMPLATES_STORAGE_KEY = 'sessions.automations.seenPluginTemplateIds'; export const DISABLED_AUTOMATIONS_EXPANDED_STORAGE_KEY = 'sessions.automations.disabledExpanded'; -/** Onboarding spotlight targets, referenced by the Get Started checklist tours. */ +/** Onboarding spotlight targets shared by automatic introductions and checklist tours. */ const AUTOMATION_TEMPLATES_ONBOARDING_TARGET_ID = 'sessions.automations.templates'; const CREATE_AUTOMATION_ONBOARDING_TARGET_ID = 'sessions.automations.create'; +const CREATE_AUTOMATION_WITH_AGENT_COMMAND_ID = 'sessions.automations.createWithAgent'; const AutomationCardCanDeleteContext = new RawContextKey('sessionsAutomationCardCanDelete', false); const AutomationCardCanUpdateContext = new RawContextKey('sessionsAutomationCardCanUpdate', false); const AutomationCardHasExternalResourceContext = new RawContextKey('sessionsAutomationCardHasExternalResource', false); @@ -310,6 +322,7 @@ export class AutomationsCardsWidget extends Disposable { } } this.historySection.render(allRuns, sessions); + this.cardsSection.setPresentedRunIds(sessions.keys()); })); const refreshScheduler = this._register(new RunOnceScheduler(() => { void refresh(); @@ -362,6 +375,7 @@ class AutomationCardsSection extends Disposable { private readonly persistentCards = new Map(); private readonly ownershipSections = new Map(); private readonly latestAutomations = new Map(); + private readonly presentedRunIds = observableValue>(this, new Set()); private readonly emptyStateDisposables = this._register(new DisposableStore()); private readonly templateDisposables = this._register(new DisposableStore()); private readonly stateDisposables = this._register(new DisposableStore()); @@ -386,6 +400,9 @@ class AutomationCardsSection extends Disposable { private visibleContainer: HTMLElement | undefined; private partialState: AutomationCatalogueState = 'ready'; private partialUnavailableProviders: readonly IAutomationProviderDescriptor[] = []; + private manageRemotesVisible = false; + private managedDisconnectedProviderIds: ReadonlySet = new Set(); + private ignoredGitHubEnvironmentProviderIds: ReadonlySet = new Set(); private pendingFocusAutomationId: string | undefined; private focusRequestGeneration = 0; @@ -404,6 +421,12 @@ class AutomationCardsSection extends Disposable { @IContextKeyService private readonly contextKeyService: IContextKeyService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @ITelemetryService private readonly telemetryService: ITelemetryService, + @IInstantiationService private readonly instantiationService: IInstantiationService, + @ICommandService private readonly commandService: ICommandService, + @INotificationService private readonly notificationService: INotificationService, + @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, + @IRemoteAgentHostService private readonly remoteAgentHostService: IRemoteAgentHostService, + @IMissionControlEnvironmentService private readonly missionControlEnvironmentService: IMissionControlEnvironmentService, ) { super(); this.seenPluginTemplateIds = this.readSeenPluginTemplateIds(); @@ -420,7 +443,8 @@ class AutomationCardsSection extends Disposable { this.partialErrorIcon = DOM.append(this.partialStateContainer, $('span.automations-cards-partial-state-icon')); this.partialErrorIcon.classList.add(...ThemeIcon.asClassNameArray(Codicon.warning)); this.partialErrorIcon.setAttribute('aria-hidden', 'true'); - this.partialStateMessage = DOM.append(this.partialStateContainer, $('div.automations-cards-partial-state-message')); + const partialStateContent = DOM.append(this.partialStateContainer, $('.automations-cards-partial-state-content')); + this.partialStateMessage = DOM.append(partialStateContent, $('div.automations-cards-partial-state-message')); this.emptyContainer = DOM.append(parent, $('.automations-cards-empty')); this.emptyContainer.style.display = 'none'; this.loadingContainer = DOM.append(parent, $('.automations-cards-state.automations-cards-loading')); @@ -431,6 +455,8 @@ class AutomationCardsSection extends Disposable { const unavailableState = this.renderUnavailableState(); this.unavailableCreateButton = unavailableState.createButton; this.unavailableDescription = unavailableState.description; + this.renderManageRemotesLink(partialStateContent); + this.renderManageRemotesLink(unavailableState.manageRemotesTarget); this.errorContainer = DOM.append(parent, $('.automations-cards-state.automations-cards-error')); this.errorContainer.style.display = 'none'; this.errorCreateButton = this.renderErrorState(); @@ -616,11 +642,7 @@ class AutomationCardsSection extends Disposable { const showTemplateSections = templates.length > 0; this.templatesContainer.style.display = showTemplateSections ? '' : 'none'; - if (unavailableProviders.length > 0) { - this.renderUnavailableMessage(this.unavailableDescription, unavailableProviders); - } else { - this.unavailableDescription.textContent = localize('automationsUnavailableDescription', "One or more providers are disconnected, disabled, or do not support automations."); - } + this.renderUnavailableMessage(this.unavailableDescription, unavailableProviders); const nextContainer = automations.length === 0 ? this.getEmptyStateContainer(catalogueState) : this.container; const previousContainer = this.visibleContainer; if (previousContainer !== nextContainer) { @@ -649,7 +671,7 @@ class AutomationCardsSection extends Disposable { const disposables = new DisposableStore(); const section = $('details.automations-ownership-section'); section.open = true; - const summary = DOM.append(section, $('summary.automations-ownership-summary')); + const summary = DOM.append(section, $('summary.automations-ownership-summary.agent-sessions-interactive.agent-sessions-interactive-list.sessions-disclosure')); const chevron = DOM.append(summary, $('span.automations-ownership-chevron')); chevron.classList.add(...ThemeIcon.asClassNameArray(Codicon.chevronRight)); chevron.setAttribute('aria-hidden', 'true'); @@ -735,7 +757,7 @@ class AutomationCardsSection extends Disposable { private renderCard(automation: IAutomationDescriptor): IAutomationCardEntry { const disposables = new DisposableStore(); const wrapper = $('.automations-card-wrapper'); - const card = DOM.append(wrapper, $('.automations-card')); + const card = DOM.append(wrapper, $('.automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered')); card.setAttribute('role', 'group'); const cardContextKeyService = disposables.add(this.contextKeyService.createScoped(card)); const canDeleteContext = AutomationCardCanDeleteContext.bindTo(cardContextKeyService); @@ -757,12 +779,21 @@ class AutomationCardsSection extends Disposable { const promptEl = DOM.append(main, $('.automations-card-prompt')); const promptHover = disposables.add(this.hoverService.setupManagedHover(getDefaultHoverDelegate('element'), promptEl, () => promptEl.textContent ?? '')); + const promptFocusHover = disposables.add(new MutableDisposable()); disposables.add(DOM.addDisposableListener(main, DOM.EventType.FOCUS, () => { if (main.matches(':focus-visible')) { - promptHover.show(); + promptFocusHover.value = this.hoverService.showInstantHover({ + content: promptEl.textContent ?? '', + target: promptEl, + appearance: { showPointer: true }, + position: { hoverPosition: HoverPosition.BELOW }, + }); } })); - disposables.add(DOM.addDisposableListener(main, DOM.EventType.BLUR, () => promptHover.hide())); + disposables.add(DOM.addDisposableListener(main, DOM.EventType.BLUR, () => { + promptHover.hide(); + promptFocusHover.clear(); + })); const metaEl = DOM.append(main, $('.automations-card-meta')); const scheduleEl = DOM.append(metaEl, $('span.automations-card-meta-item.automations-card-schedule')); @@ -851,9 +882,11 @@ class AutomationCardsSection extends Disposable { disposables.add(autorun(reader => { const starting = startingRuns.read(reader); const runs = this.automationService.runs.read(reader); + const presentedRunIds = this.presentedRunIds.read(reader); const state = this.automationService.catalogueState.read(reader); const historyState = this.automationService.historyState?.read(reader); - if (starting && (runs.some(run => run.automationId === automation.id && !starting.has(run.id)) + if (starting && (runs.some(run => run.automationId === automation.id && !starting.has(run.id) + && !isLocalAutomationRunStarting(run, () => presentedRunIds.has(run.id), resource => this.sessionsManagementService.getSession(resource) !== undefined)) || (state === 'unavailable' && !this.automationService.canRunAutomation(automation.id)) || state === 'error' || historyState === 'error')) { startingRuns.set(undefined, undefined); } @@ -877,9 +910,6 @@ class AutomationCardsSection extends Disposable { const scheduleChanged = !previous || enabledChanged || formatSchedule(previous.schedule) !== formatSchedule(automation.schedule) || automationTriggerSummary(previous.cloudTrigger?.triggers ?? {}) !== triggerSummary; const nameChanged = !previous || previous.name !== automation.name; - if (nameChanged || scheduleChanged) { - card.card.setAttribute('aria-label', localize('automationCard', "{0} — {1}", automation.name, automation.enabled ? triggerSummary ?? schedule : schedule)); - } if (nameChanged) { card.main.setAttribute('aria-label', localize('editAutomationNamed', "Edit automation {0}", automation.name)); card.actions.setAttribute('aria-label', localize('automationActions', "Actions for {0}", automation.name)); @@ -921,13 +951,23 @@ class AutomationCardsSection extends Disposable { card.moreActionsButton.focus(); } card.runButton.element.style.display = eventTriggered ? 'none' : ''; - const starting = card.startingRuns.get() !== undefined; + const starting = card.startingRuns.get() !== undefined || this.automationService.runs.get().some(run => + run.automationId === automation.id + && isLocalAutomationRunStarting(run, () => this.presentedRunIds.get().has(run.id), resource => this.sessionsManagementService.getSession(resource) !== undefined) + ); card.startingIcon.style.display = starting ? '' : 'none'; card.promptEl.textContent = starting ? localize('automationStarting', "Starting run...") : automation.prompt; card.runButton.enabled = !starting && this.automationService.canRunAutomation(automation.id); const label = starting ? localize('running', "Running") : localize('runNow', "Run now"); card.runButton.setAriaLabel(label); card.runButton.setTitle(label); + const triggerSummary = automationTriggerSummary(automation.cloudTrigger?.triggers ?? {}); + const schedule = automation.enabled ? triggerSummary ?? formatSchedule(automation.schedule) : localize('disabled', "Disabled"); + card.card.setAttribute('aria-label', localize('automationCard', "{0} — {1}", automation.name, starting ? localize('running', "Running") : schedule)); + } + + setPresentedRunIds(runIds: Iterable): void { + this.presentedRunIds.set(new Set(runIds), undefined); } private createIconButton(buttonBar: ButtonBar, icon: ThemeIcon, tooltip: string, disabled: boolean): IButton { @@ -988,16 +1028,42 @@ class AutomationCardsSection extends Disposable { title.textContent = localize('noAutomationsYet', "No automations yet"); const desc = DOM.append(container, $('p.automations-cards-empty-description')); desc.textContent = localize('noAutomationsDesc', "Describe what you want to automate, then choose when it runs."); + return this.renderCreateWithAgentButton(container, disposables, 'automations-cards-create-button'); + } - const createButton = disposables.add(new Button(container, { + /** Renders Create with Agent, with Create Manually in its dropdown. */ + private renderCreateWithAgentButton(container: HTMLElement, disposables: DisposableStore, buttonClassName: string): IButton { + const label = localize('createWithAgent', "Create with Agent"); + const createButton = disposables.add(new ButtonWithDropdown(container, { ...defaultButtonStyles, - title: localize('createAutomation', "Create Automation"), + title: label, + contextMenuProvider: this.contextMenuService, + actions: [toAction({ id: 'sessions.automations.createManually', label: localize('createManually', "Create Manually"), run: () => this.openCreateDialog() })], + addPrimaryActionToDropdown: false, + })); + createButton.label = label; + createButton.element.classList.add('automations-cards-create-dropdown'); + createButton.primaryButton.element.classList.add(buttonClassName); + const updateEnabled = () => { + createButton.primaryButton.enabled = this.contextKeyService.contextMatchesRules(ChatContextKeys.enabled); + }; + updateEnabled(); + const enabledContextKeys = new Set([ChatContextKeys.enabled.key]); + disposables.add(this.contextKeyService.onDidChangeContext(event => { + if (event.affectsSome(enabledContextKeys)) { + updateEnabled(); + } + })); + disposables.add(createButton.onDidClick(() => { + void this.commandService.executeCommand(CREATE_AUTOMATION_WITH_AGENT_COMMAND_ID).catch(error => { + if (!isCancellationError(error)) { + this.logService.error('[Automations] Failed to open agent creation session', error); + this.notificationService.error(localize('automationsAgentCreationFailed', "Could not open a session to create an automation: {0}", getErrorMessage(error))); + } + }); })); - createButton.label = localize('createAutomation', "Create Automation"); - createButton.element.classList.add('automations-cards-create-button'); - disposables.add(createButton.onDidClick(() => this.openCreateDialog())); disposables.add(markOnboardingTarget(createButton.element, CREATE_AUTOMATION_ONBOARDING_TARGET_ID, { - onDidActivate: Event.map(createButton.onDidClick, () => undefined), + onDidActivate: Event.map(Event.any(createButton.onDidClick, createButton.dropdownButton.onDidClick), () => undefined), })); return createButton; } @@ -1049,7 +1115,7 @@ class AutomationCardsSection extends Disposable { private renderTemplateSection(options: IAutomationTemplateSectionOptions): IRenderedAutomationTemplateSection { const section = DOM.append(this.templatesContainer, $(`details.automations-template-section.${options.className}`)); section.open = options.expanded; - const summary = DOM.append(section, $('summary.automations-template-section-summary')); + const summary = DOM.append(section, $('summary.automations-template-section-summary.agent-sessions-interactive.agent-sessions-interactive-list.sessions-disclosure')); const chevron = DOM.append(summary, $('span.automations-template-section-chevron')); chevron.classList.add(...ThemeIcon.asClassNameArray(Codicon.chevronRight)); chevron.setAttribute('aria-hidden', 'true'); @@ -1139,15 +1205,87 @@ class AutomationCardsSection extends Disposable { return this.renderStateCreateButton(this.loadingContainer); } - private renderUnavailableState(): { readonly createButton: IButton; readonly description: HTMLElement } { - const icon = DOM.append(this.unavailableContainer, $('span.automations-cards-state-icon')); - icon.classList.add(...ThemeIcon.asClassNameArray(Codicon.debugDisconnect)); - icon.setAttribute('aria-hidden', 'true'); + private renderUnavailableState(): { readonly createButton: IButton; readonly description: HTMLElement; readonly manageRemotesTarget: HTMLElement } { const title = DOM.append(this.unavailableContainer, $('h3.automations-cards-state-title')); - title.textContent = localize('automationsUnavailable', "Some automations are unavailable"); - const description = DOM.append(this.unavailableContainer, $('div.automations-cards-state-description')); + title.textContent = localize('noAutomationsYet', "No automations yet"); + const emptyDescription = DOM.append(this.unavailableContainer, $('p.automations-cards-state-description')); + emptyDescription.textContent = localize('noAutomationsDesc', "Describe what you want to automate, then choose when it runs."); + const manageRemotesTarget = DOM.append(this.unavailableContainer, $('div.automations-manage-remotes-target')); + const description = DOM.append(this.unavailableContainer, $('div.automations-cards-state-description.automations-cards-unavailable-message')); description.textContent = localize('automationsUnavailableDescription', "One or more providers are disconnected, disabled, or do not support automations."); - return { createButton: this.renderStateCreateButton(this.unavailableContainer), description }; + return { createButton: this.renderStateCreateButton(this.unavailableContainer), description, manageRemotesTarget }; + } + + private renderManageRemotesLink(parent: HTMLElement): void { + const container = DOM.append(parent, $('span.automations-manage-remotes')); + const count = DOM.append(container, $('span.automations-manage-remotes-count')); + count.setAttribute('aria-hidden', 'true'); + this._register(this.instantiationService.createInstance(Link, container, { + label: localize('automationsManageRemotes', "Manage Remotes"), + href: `command:${OPEN_REMOTES_EDITOR_COMMAND_ID}`, + }, { + opener: () => { + void this.commandService.executeCommand(OPEN_REMOTES_EDITOR_COMMAND_ID).catch(error => { + this.logService.error('[Automations] Failed to open Remote Environments.', error); + this.notificationService.error(error); + }); + }, + })); + const link = container.lastElementChild as HTMLAnchorElement; + const configurationChanged = observableSignalFromEvent(this, this.configurationService.onDidChangeConfiguration); + const remoteHostsChanged = observableSignalFromEvent(this, Event.any( + this.remoteAgentHostService.onDidChangeConnections, + this.remoteAgentHostService.onDidChangeConfiguredEntries, + )); + this._register(autorun(reader => { + configurationChanged.read(reader); + remoteHostsChanged.read(reader); + const catalogueState = this.automationService.catalogueState.read(reader); + const automations = this.automationService.automations.read(reader); + const unavailableProviders = this.automationService.unavailableProviders.read(reader); + const configuredEntries = this.remoteAgentHostService.configuredEntries; + const remoteManagementEnabled = this.configurationService.getValue(RemoteAgentHostsEnabledSettingId) + && this.configurationService.getValue(ENVIRONMENT_PICKER_SETTING) + && this.configurationService.getValue(ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING); + const presentation = getAutomationRemoteStatusPresentation( + unavailableProviders, + configuredEntries, + this.missionControlEnvironmentService.hosts.read(reader).map(host => host.id), + remoteManagementEnabled, + ); + const managedDisconnectedProviderIds = presentation.replacedTunnelProviderIds; + const ignoredGitHubEnvironmentProviderIds = presentation.ignoredGitHubEnvironmentProviderIds; + const visible = catalogueState === 'unavailable' && managedDisconnectedProviderIds.size > 0; + const connectedAddresses = new Set(this.remoteAgentHostService.connections + .filter(connection => RemoteAgentHostConnectionStatus.isConnected(connection.status)) + .map(connection => normalizeRemoteAgentHostAddress(connection.address))); + const connectedCount = presentation.tunnelEntries.filter(entry => + connectedAddresses.has(normalizeRemoteAgentHostAddress(getEntryAddress(entry))) + ).length; + const countLabel = localize('automationsDetectedRemotes', "{0}/{1} remotes detected", connectedCount, presentation.tunnelEntries.length); + count.textContent = countLabel; + link.setAttribute('aria-label', localize('automationsManageRemotesWithCount', "{0}, Manage Remotes", countLabel)); + if (!visible && container.contains(DOM.getActiveElement())) { + this.focusRoot.focus(); + } + container.style.display = visible ? '' : 'none'; + const managedProvidersChanged = managedDisconnectedProviderIds.size !== this.managedDisconnectedProviderIds.size + || [...managedDisconnectedProviderIds].some(id => !this.managedDisconnectedProviderIds.has(id)); + const ignoredProvidersChanged = ignoredGitHubEnvironmentProviderIds.size !== this.ignoredGitHubEnvironmentProviderIds.size + || [...ignoredGitHubEnvironmentProviderIds].some(id => !this.ignoredGitHubEnvironmentProviderIds.has(id)); + if (this.manageRemotesVisible !== visible || managedProvidersChanged || ignoredProvidersChanged) { + this.manageRemotesVisible = visible; + this.managedDisconnectedProviderIds = managedDisconnectedProviderIds; + this.ignoredGitHubEnvironmentProviderIds = ignoredGitHubEnvironmentProviderIds; + if (catalogueState === 'unavailable') { + this.renderUnavailableMessage(this.unavailableDescription, unavailableProviders); + const hasPartialMessage = this.renderUnavailableMessage(this.partialStateMessage, unavailableProviders); + if (automations.length > 0) { + this.partialStateContainer.style.display = hasPartialMessage || visible ? '' : 'none'; + } + } + } + })); } private renderErrorState(): IButton { @@ -1163,14 +1301,7 @@ class AutomationCardsSection extends Disposable { } private renderStateCreateButton(container: HTMLElement): IButton { - const createButton = this.stateDisposables.add(new Button(container, { - ...defaultButtonStyles, - title: localize('createAutomation', "Create Automation"), - })); - createButton.label = localize('createAutomation', "Create Automation"); - createButton.element.classList.add('automations-cards-state-create-button'); - this.stateDisposables.add(createButton.onDidClick(() => this.openCreateDialog())); - return createButton; + return this.renderCreateWithAgentButton(container, this.stateDisposables, 'automations-cards-state-create-button'); } private renderPartialState(catalogueState: AutomationCatalogueState, unavailableProviders: readonly IAutomationProviderDescriptor[]): void { @@ -1194,25 +1325,35 @@ class AutomationCardsSection extends Disposable { this.partialStateContainer.style.display = ''; this.partialStateContainer.classList.toggle('automations-cards-partial-state-error', isError); if (catalogueState === 'unavailable') { - this.renderUnavailableMessage(this.partialStateMessage, unavailableProviders); + const hasMessage = this.renderUnavailableMessage(this.partialStateMessage, unavailableProviders); + this.partialStateContainer.style.display = hasMessage || this.manageRemotesVisible ? '' : 'none'; } else { + this.partialStateMessage.style.display = ''; this.partialStateMessage.textContent = localize('automationsPartialLoadError', "Some automations could not be loaded."); } } - private renderUnavailableMessage(container: HTMLElement, unavailableProviders: readonly IAutomationProviderDescriptor[]): void { - const reasons = getUnavailableAutomationsReasons(unavailableProviders); + private renderUnavailableMessage(container: HTMLElement, unavailableProviders: readonly IAutomationProviderDescriptor[]): boolean { + const visibleProviders = unavailableProviders.filter(provider => + !this.ignoredGitHubEnvironmentProviderIds.has(provider.id) + && (!this.manageRemotesVisible || !this.managedDisconnectedProviderIds.has(provider.id))); + const reasons = getUnavailableAutomationsReasons(visibleProviders); + const suppressedAllReasons = unavailableProviders.length > 0 && visibleProviders.length === 0; + container.style.display = suppressedAllReasons ? 'none' : ''; if (reasons.length === 1) { container.textContent = reasons[0]; } else if (reasons.length > 1) { DOM.reset(container, $('ul.automations-unavailable-reasons', undefined, ...reasons.map(reason => $('li', undefined, reason)))); - } else { + } else if (!suppressedAllReasons) { container.textContent = localize('automationsPartialUnavailable', "Some automations are unavailable."); + } else { + DOM.clearNode(container); } + return !suppressedAllReasons; } private renderTemplateCard(container: HTMLElement, template: IAutomationTemplate): void { - const card = DOM.append(container, $('button.automations-template-card', { type: 'button' })); + const card = DOM.append(container, $('button.automations-template-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered', { type: 'button' })); const schedule = formatSchedule(template.schedule); card.setAttribute('aria-label', template.source ? localize('usePluginAutomationTemplate', "Use template: {0}, {1}, from {2}", template.name, schedule, template.source.label) @@ -1336,7 +1477,7 @@ class AutomationCardsSection extends Disposable { this.errorCreateButton.focus(); return; case 'ready': - (this.emptyCreateButton?.element ?? this.focusRoot).focus(); + (this.emptyCreateButton ?? this.focusRoot).focus(); } } @@ -1561,8 +1702,6 @@ class AutomationHistorySection extends Disposable { const visibleRuns = runs.filter(run => sessions.has(run.id) || !!run.externalResource - || isTemporaryAutomationRun(run) - || (!!run.sessionResource && !!this.sessionsManagementService.getSession(run.sessionResource)) ); const historyOwners = new Map(); for (const run of runs) { @@ -2294,10 +2433,6 @@ function isUnreadAutomationRun(run: IAutomationRun, session: ISession | undefine return completed && !!session && !session.isRead.read(reader); } -function isTemporaryAutomationRun(run: IAutomationRun): boolean { - return run.status === 'pending' || run.status === 'running'; -} - function formatSchedule(schedule: IAutomationSchedule): string { const localSchedule = automationScheduleToLocal(schedule); const { interval, scheduleHour, scheduleMinute } = localSchedule; @@ -2504,6 +2639,16 @@ async function showAutomationsDisabled(dialogService: IDialogService): Promise { + this._register(actionViewItemService.register(AgentsWindowMenus.CustomViewAutomations, CREATE_AUTOMATION_WITH_AGENT_COMMAND_ID, (action, options, instantiationService) => { if (!(action instanceof MenuItemAction)) { return undefined; } - return instantiationService.createInstance(AutomationHeaderButtonActionViewItem, undefined, action, options, false, undefined, CREATE_AUTOMATION_ONBOARDING_TARGET_ID); + const createManually = toAction({ id: 'sessions.automations.createManually', label: localize('createManually', "Create Manually"), run: () => commandService.executeCommand('sessionsView.newAutomation') }); + return instantiationService.createInstance(AutomationHeaderSplitButtonActionViewItem, action, options, [createManually], CREATE_AUTOMATION_ONBOARDING_TARGET_ID); })); this._register(actionViewItemService.register(AgentsWindowMenus.CustomViewAutomations, 'sessions.automations.import', (action, options, instantiationService) => { if (!(action instanceof MenuItemAction)) { @@ -2854,6 +3000,89 @@ class AutomationHeaderButtonActionViewItem extends BaseActionViewItem { } } +/** Header Create with Agent split button, using the same {@link ButtonWithDropdown} as the empty state. */ +class AutomationHeaderSplitButtonActionViewItem extends BaseActionViewItem { + + private button: ButtonWithDropdown | undefined; + + constructor( + action: IAction, + options: IActionViewItemOptions, + private readonly dropdownActions: readonly IAction[], + private readonly onboardingTargetId: string | undefined, + @IContextMenuService private readonly contextMenuService: IContextMenuService, + ) { + super(undefined, action, options); + } + + override render(container: HTMLElement): void { + this.element = container; + const label = localize('createWithAgent', "Create with Agent"); + const button = this.button = this._register(new ButtonWithDropdown(container, { + ...defaultButtonStyles, + title: this._action.label, + contextMenuProvider: this.contextMenuService, + actions: this.dropdownActions, + addPrimaryActionToDropdown: false, + })); + button.label = label; + this._register(button.onDidClick(() => this.actionRunner.run(this._action, this._context))); + this._register(DOM.addDisposableListener(button.primaryButton.element, DOM.EventType.KEY_DOWN, event => { + if (new StandardKeyboardEvent(event).equals(KeyCode.RightArrow)) { + this.focus(true); + DOM.EventHelper.stop(event, true); + } + })); + this._register(DOM.addDisposableListener(button.dropdownButton.element, DOM.EventType.KEY_DOWN, event => { + if (this._action.enabled && new StandardKeyboardEvent(event).equals(KeyCode.LeftArrow)) { + this.focus(); + DOM.EventHelper.stop(event, true); + } + })); + if (this.onboardingTargetId) { + this._register(markOnboardingTarget(button.element, this.onboardingTargetId, { + onDidActivate: Event.map(Event.any(button.onDidClick, button.dropdownButton.onDidClick), () => undefined), + })); + } + this.updateEnabled(); + } + + override isEnabled(): boolean { + return this._action.enabled || this.dropdownActions.some(action => action.enabled); + } + + override focus(fromRight = false): void { + if (!this.button) { + return; + } + const dropdown = fromRight || !this._action.enabled; + this.button.primaryButton.element.tabIndex = dropdown ? -1 : 0; + this.button.dropdownButton.element.tabIndex = dropdown ? 0 : -1; + (dropdown ? this.button.dropdownButton : this.button.primaryButton).focus(); + } + + override blur(): void { + this.button?.primaryButton.element.blur(); + this.button?.dropdownButton.element.blur(); + this.setFocusable(false); + } + + override setFocusable(focusable: boolean): void { + if (this.button) { + this.button.primaryButton.element.tabIndex = focusable && this._action.enabled ? 0 : -1; + this.button.dropdownButton.element.tabIndex = focusable && !this._action.enabled ? 0 : -1; + } + } + + protected override updateEnabled(): void { + if (this.button) { + const focusable = this.button.primaryButton.element.tabIndex === 0 || this.button.dropdownButton.element.tabIndex === 0; + this.button.primaryButton.enabled = this._action.enabled; + this.setFocusable(focusable); + } + } +} + async function refreshAutomations(automationService: IAutomationService, logService: ILogService, notificationService?: INotificationService, options?: IAutomationRefreshOptions): Promise { try { await automationService.refresh?.(options); @@ -2908,7 +3137,6 @@ registerAction2(class NewAutomationAction extends Action2 { id: 'sessionsView.newAutomation', title: localize2('newAutomation', "New Automation"), precondition: ChatAutomationsEnabledContext, - menu: [{ id: AgentsWindowMenus.CustomViewAutomations, group: 'navigation', order: 1, when: ContextKeyExpr.and(ChatAutomationsEnabledContext, AutomationsHasItemsContext) }], }); } override async run(accessor: ServicesAccessor): Promise { @@ -2937,6 +3165,49 @@ registerAction2(class NewAutomationAction extends Action2 { } }); +registerAction2(class CreateAutomationWithAgentAction extends Action2 { + constructor() { + super({ + id: CREATE_AUTOMATION_WITH_AGENT_COMMAND_ID, + title: localize2('createAutomationWithAgent', "Create Automation with Agent"), + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatAutomationsEnabledContext), + // The empty state hosts this button until the first automation exists. + menu: [{ id: AgentsWindowMenus.CustomViewAutomations, group: 'navigation', order: 1, when: ContextKeyExpr.and(ChatAutomationsEnabledContext, AutomationsHasItemsContext) }], + }); + } + override async run(accessor: ServicesAccessor): Promise { + const commandService = accessor.get(ICommandService); + const dialogService = accessor.get(IDialogService); + const sessionsService = accessor.get(ISessionsService); + const mountedDraftHasInput = accessor.get(INewSessionComposerService).hasDraftInput; + const savedDraft = mountedDraftHasInput === undefined ? readNewChatDraftState(accessor.get(IStorageService)) : undefined; + const hasDraftInput = mountedDraftHasInput ?? (!!savedDraft?.inputText || !!savedDraft?.attachments.length); + if (hasDraftInput && !accessor.get(ISessionDraftsService).enabled.get()) { + const { result } = await dialogService.prompt({ + type: 'warning', + message: localize('replaceAutomationDraft', "Replace your existing draft?"), + detail: localize('replaceAutomationDraftDetail', "This action will overwrite the existing new session draft, it will not be recoverable."), + buttons: [ + { label: localize('replaceAutomationDraftButton', "Replace Draft"), run: () => true }, + { label: localize('viewAutomationDraftButton', "View Draft"), run: () => false }, + ], + cancelButton: true, + }); + if (result !== true) { + if (result === false) { + await sessionsService.openNewSession(); + } + return; + } + } + const options: INewSessionInAgentsWindowOptions = { + prompt: '/automate ', + prefillPrompt: true, + }; + await commandService.executeCommand(NEW_SESSION_ACTION_ID, options); + } +}); + registerAction2(class ImportAutomationAction extends Action2 { constructor() { super({ @@ -3218,6 +3489,21 @@ async function setAutomationEnabled(accessor: ServicesAccessor, automation: IAut await showAutomationsDisabled(dialogService); return; } + if (!enabled && automation.ownership === 'repository') { + const confirmed = await dialogService.confirm({ + type: 'warning', + message: localize('confirmDisableSharedAutomation', "Disable automation \"{0}\"?", automation.name), + detail: getSharedAutomationWarning('disable'), + primaryButton: localize('disable', "Disable"), + }); + if (!confirmed.confirmed) { + return; + } + if (!automationsEnabled()) { + await showAutomationsDisabled(dialogService); + return; + } + } try { const result = await automationService.updateAutomationIfUnchanged(automation.id, { enabled }, automation, () => { if (!automationsEnabled()) { diff --git a/src/vs/sessions/contrib/sessions/browser/views/sessionsViewActions.ts b/src/vs/sessions/contrib/sessions/browser/views/sessionsViewActions.ts index c138ef72fe8e..aa42ad89e6a7 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/sessionsViewActions.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/sessionsViewActions.ts @@ -29,10 +29,10 @@ import { IViewsService } from '../../../../../workbench/services/views/common/vi import { CLOSE_MOBILE_SIDEBAR_DRAWER_COMMAND_ID } from '../../../../browser/workbench.js'; import { EditorsVisibleContext, EditorAreaFocusContext, FocusedViewContext, IsSessionsWindowContext } from '../../../../../workbench/common/contextkeys.js'; import { SessionsCategories } from '../../../../../workbench/contrib/sessions/common/categories.js'; -import { SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; import { ARCHIVE_CHAT_COMMAND_ID, ARCHIVE_SESSION_COMMAND_ID, ARCHIVE_SESSION_GROUP_COMMAND_ID, ARCHIVE_SESSIONS_WITH_UNDO_COMMAND_ID, DELETE_SESSION_GROUP_WITH_UNDO_COMMAND_ID, HIDE_AUTOMATION_SESSION_FROM_LIST_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, RENAME_SESSION_COMMAND_ID, SHOW_AUTOMATION_SESSION_IN_LIST_COMMAND_ID, SHOW_SESSION_APPLICATION_FILTERS_COMMAND_ID, UNARCHIVE_CHAT_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; import { IsPhoneLayoutContext, SessionSupportsDeleteContext, SessionSupportsRenameContext, IsNewChatSessionContext, SessionActiveChatCanArchiveContext, SessionActiveChatIsUntitledContext, SessionHeaderTargetsChatContext, SessionIsArchivedContext, SessionIsCreatedContext, SessionIsReadContext, SessionItemIsMultiSelectionContext, SessionsListPromoteNewChatActionContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; -import { canStartNewSessionLike, getNewSessionSources, getSessionListChats, isAutomationSession, SessionItemInboxStateContext, SessionItemCanImportContext, SessionItemContextMenuId, SessionItemIsAutomationContext, SessionItemIsInSessionsListContext, SessionItemOrganizeMenuGroup, SessionItemHasUnreadNestedSessionsContext, SessionSectionToolbarMenuId, SessionGroupToolbarMenuId, SessionSectionTypeContext, SessionSectionHasNonCloudRepositoryContext, SessionGroupHasVisibleSessionsContext, SessionGroupIsEmptyContext, SessionGroupIsComparisonContext, IsSessionPinnedContext, SessionsGrouping, SessionsSorting, ISessionSection, ISessionGroupItem, NEW_SESSION_FOR_WORKSPACE_ACTION_ID, NEW_SESSION_IN_ENVIRONMENT_ACTION_ID, ISessionChatItem, SessionChatItemCanArchiveContext, SessionChatItemCanMoveDownContext, SessionChatItemCanMoveUpContext, SessionChatItemCanSetReadStateContext, SessionChatItemIsArchivedContext, SessionChatItemIsReadContext, SessionChatItemIsStandaloneContext, SessionChatItemIsUntitledContext, SessionsListFocusedChatItemContext, SessionsListSearchOpenContext } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; +import { canStartNewSessionLike, getNewSessionSources, getSessionListChats, isAutomationSession, SessionItemInboxStateContext, SessionItemCanMergePullRequestContext, SessionItemCanImportContext, SessionItemContextMenuId, SessionItemIsAutomationContext, SessionItemIsInSessionsListContext, SessionItemOrganizeMenuGroup, SessionItemHasUnreadNestedSessionsContext, SessionSectionToolbarMenuId, SessionGroupToolbarMenuId, SessionSectionTypeContext, SessionSectionHasNonCloudRepositoryContext, SessionGroupHasVisibleSessionsContext, SessionGroupIsEmptyContext, SessionGroupIsComparisonContext, IsSessionPinnedContext, SessionsGrouping, SessionsSorting, ISessionSection, ISessionGroupItem, NEW_SESSION_FOR_WORKSPACE_ACTION_ID, NEW_SESSION_IN_ENVIRONMENT_ACTION_ID, ISessionChatItem, SessionChatItemCanArchiveContext, SessionChatItemCanMoveDownContext, SessionChatItemCanMoveUpContext, SessionChatItemCanSetReadStateContext, SessionChatItemIsArchivedContext, SessionChatItemIsReadContext, SessionChatItemIsStandaloneContext, SessionChatItemIsUntitledContext, SessionsListFocusedChatItemContext, SessionsListSearchOpenContext } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { getChatCapabilities, IChat, ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionGroupsService } from '../../../../../workbench/contrib/sessions/browser/sessionGroupsService.js'; import { ISessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; @@ -60,7 +60,8 @@ import { WorkspaceSelectionOrigin } from '../../../../../workbench/services/sess import { AccessibleViewType } from '../../../../../platform/accessibility/browser/accessibleView.js'; import { AccessibleViewRegistry } from '../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { SessionsListNotificationFocused } from '../../../../../workbench/contrib/sessions/browser/views/sessionsListNotification.js'; -import { SessionInboxAction } from '../../../../../workbench/contrib/sessions/common/sessionInbox.js'; +import { getSessionInboxSection, SessionInboxAction, SessionInboxSection } from '../../../../../workbench/contrib/sessions/common/sessionInbox.js'; +import { getInboxPullRequestMergeOperation, IInboxNotificationsService } from '../../../../../workbench/contrib/sessions/common/inboxNotificationsService.js'; AccessibleViewRegistry.register({ name: 'sessions-list-notification', @@ -477,7 +478,6 @@ MenuRegistry.appendMenuItem(Menus.SessionSectionContext, { // Sort / Group Actions const InboxModeContext = SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Inbox); -const InboxModeEnabledContext = ContextKeyExpr.equals(`config.${SESSIONS_LIST_INBOX_ENABLED_SETTING}`, true); registerAction2(class InboxModeAction extends Action2 { constructor() { @@ -486,9 +486,9 @@ registerAction2(class InboxModeAction extends Action2 { title: localize2('inboxMode', "Inbox Mode"), category: SessionsCategories.Sessions, f1: true, - precondition: ContextKeyExpr.and(IsSessionsWindowContext, ChatContextKeys.enabled, InboxModeEnabledContext), + precondition: ContextKeyExpr.and(IsSessionsWindowContext, ChatContextKeys.enabled), toggled: InboxModeContext, - menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 4, when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeEnabledContext) }], + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 4, when: ChatContextKeys.enabled }], }); } run(accessor: ServicesAccessor): void { @@ -1235,6 +1235,10 @@ function triageSessions(modelService: ISessionsListModelService, viewsService: I : action === undefined ? localize('inboxResumed', "{0} returned to inbox", targets.length) : action === 'hold' ? localize('inboxHeld', "{0} put on hold", targets.length) : localize('inboxSnoozed', "{0} snoozed", targets.length); + if (targets.length === 1 && action !== 'done') { + status(message); + return; + } viewsService.getViewWithId(SessionsViewId)?.listNotification?.show({ message, help: localize('inboxTriageHelp', "This changes only Inbox mode. It does not stop or archive sessions. Undo restores the previous triage state unless it has changed since."), @@ -1248,13 +1252,14 @@ registerAction2(class DismissInboxSessionAction extends Action2 { super({ id: 'sessionsViewPane.inboxDone', title: localize2('inboxDismiss', "Dismiss from Inbox"), - icon: Codicon.close, + icon: Codicon.mailRead, precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ id, group: id === Menus.SessionItemToolbar ? 'navigation' : '1_state', order: id === Menus.SessionItemToolbar ? 4 : 2, - when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), SessionItemInboxStateContext.notEqualsTo('done')), + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), + id === Menus.SessionItemToolbar ? SessionItemInboxStateContext.isEqualTo('') : SessionItemInboxStateContext.notEqualsTo('done')), })), keybinding: { primary: KeyCode.Delete, @@ -1274,7 +1279,7 @@ registerAction2(class ResumeInboxSessionAction extends Action2 { super({ id: 'sessionsViewPane.inboxResume', title: localize2('inboxResume', "Return to Inbox"), - icon: Codicon.discard, + icon: Codicon.inbox, precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ id, @@ -1317,7 +1322,7 @@ registerAction2(class SnoozeInboxSessionAction extends Action2 { { label: localize('snoozeWeek', "In One Week"), value: morning(7) }, { label: localize('snoozeActivity', "Until New Activity"), value: 'untilActivity' as const }, { label: localize('snoozeDate', "Pick a Date and Time..."), value: 'custom' as const }, - ], { placeHolder: localize('snoozePlaceholder', "When should these sessions return?") }); + ], { placeHolder: localize('snoozeReturnPlaceholder', "When should these sessions leave On hold? They will return to Inbox, Working, or Ready to merge based on their activity.") }); if (!picked) { return; } @@ -1347,6 +1352,36 @@ registerAction2(class SnoozeInboxSessionAction extends Action2 { } }); +registerAction2(class MergeInboxPullRequestAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.inboxMergePullRequest', + title: localize2('inboxMergePullRequest', "Merge Pull Request"), + icon: Codicon.gitMerge, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionItemCanMergePullRequestContext, SessionItemIsMultiSelectionContext.negate()), + menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ + id, + group: 'navigation', + order: 0, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), SessionItemCanMergePullRequestContext), + })), + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise { + const sessions = getSessionActionTargets(accessor, context); + const session = sessions.length === 1 ? sessions[0] : undefined; + const attention = accessor.get(IInboxNotificationsService).sessionAttention.get(); + const model = accessor.get(ISessionsListModelService); + const merge = session && !session.isArchived.get() + && getSessionInboxSection(session, model.getInboxState(session), undefined, attention.get(session.sessionId)) === SessionInboxSection.ReadyToMerge + ? getInboxPullRequestMergeOperation(session) : undefined; + if (!merge) { + throw new Error(localize('inboxMergeUnavailable', "This pull request is no longer available to merge.")); + } + await merge.changeset.invokeOperation(merge.operation.id); + } +}); + registerAction2(class HoldInboxSessionAction extends Action2 { constructor() { super({ @@ -1481,7 +1516,8 @@ for (const id of [Menus.SessionItemToolbar, SessionItemContextMenuId]) { }, group: id === Menus.SessionItemToolbar ? 'navigation' : '4_manage', order: id === Menus.SessionItemToolbar ? 3 : 2.5, - when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate()), + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), + id === Menus.SessionItemToolbar ? SessionItemInboxStateContext.isEqualTo('done') : undefined), }); } @@ -1519,9 +1555,6 @@ abstract class BaseArchiveSessionAction extends Action2 { const configurationService = accessor.get(IConfigurationService); const accessibilityService = accessor.get(IAccessibilityService); const accessibilitySignalService = accessor.get(IAccessibilitySignalService); - for (const session of sessions) { - await sessionsManagementService.archiveSession(session); - } if ( sessions.length > 0 && configurationService.getValue(SESSIONS_MARK_AS_DONE_CONFETTI_SETTING) @@ -1529,6 +1562,9 @@ abstract class BaseArchiveSessionAction extends Action2 { ) { void accessibilitySignalService.playSignal(AccessibilitySignal.confetti); } + for (const session of sessions) { + await sessionsManagementService.archiveSession(session); + } } } diff --git a/src/vs/sessions/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.fixture.ts b/src/vs/sessions/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.fixture.ts index cd2dc20d1515..7107b3bc6757 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.fixture.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.fixture.ts @@ -183,10 +183,10 @@ function createMockHarnessService(hiddenSections: readonly string[] = []): ICust // Render helper // ============================================================================ -function renderWidget(ctx: ComponentFixtureContext, options?: { mcpServerCount?: number; counts?: ICustomizationCounts; hiddenSections?: readonly string[]; height?: number; extensionSuggestions?: boolean; collapsed?: boolean }): void { +function renderWidget(ctx: ComponentFixtureContext, options?: { mcpServerCount?: number; counts?: ICustomizationCounts; hiddenSections?: readonly string[]; height?: number; extensionSuggestions?: boolean; collapsed?: boolean; headerHovered?: boolean }): void { ctx.container.style.width = '300px'; ctx.container.style.height = `${options?.height ?? 260}px`; - ctx.container.style.backgroundColor = 'var(--vscode-sideBar-background)'; + ctx.container.style.backgroundColor = 'var(--vscode-agents-background)'; const actionViewItemService = new FixtureActionViewItemService(); @@ -241,8 +241,20 @@ function renderWidget(ctx: ComponentFixtureContext, options?: { mcpServerCount?: ctx.disposableStore.add( instantiationService.createInstance(AICustomizationShortcutsWidget, ctx.container, undefined) ); - if (options?.collapsed) { - ctx.container.querySelector('.ai-customization-header')?.click(); + if (options?.collapsed || options?.headerHovered) { + const header = ctx.container.querySelector('.ai-customization-header'); + if (!header) { + throw new Error('Expected the customizations header.'); + } + if (options.collapsed) { + header.click(); + } + if (options.headerHovered) { + header.classList.add('hovered'); + } + } + if (options?.headerHovered) { + ctx.container.querySelector('.ai-customization-header')?.classList.add('hovered'); } } @@ -257,6 +269,21 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { render: (ctx) => renderWidget(ctx), }), + ExpandedHeaderHovered: defineComponentFixture({ + labels: { kind: 'screenshot' }, + render: (ctx) => renderWidget(ctx, { headerHovered: true }), + }), + + CollapsedHeaderHovered: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: (ctx) => renderWidget(ctx, { + collapsed: true, + headerHovered: true, + counts: { skills: 30, instructions: 16 }, + }), + }), + MinimumHeight: defineComponentFixture({ labels: { kind: 'screenshot' }, render: (ctx) => renderWidget(ctx, { height: 129 }), @@ -293,5 +320,15 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { counts: { skills: 30, instructions: 16 }, }), }), + CollapsedHeaderHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The collapsed Customizations header is hovered. In high contrast themes, a dashed active-contrast outline surrounds the header.'], + render: ctx => renderWidget(ctx, { + collapsed: true, + headerHovered: true, + counts: { skills: 30, instructions: 16 }, + }), + }), }); diff --git a/src/vs/sessions/contrib/sessions/test/browser/automationDeletion.fixture.ts b/src/vs/sessions/contrib/sessions/test/browser/automationDeletion.fixture.ts new file mode 100644 index 000000000000..f44542336489 --- /dev/null +++ b/src/vs/sessions/contrib/sessions/test/browser/automationDeletion.fixture.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Dialog } from '../../../../../base/browser/ui/dialog/dialog.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IConfirmation, IConfirmationResult, IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; +import { defaultButtonStyles, defaultCheckboxStyles, defaultDialogStyles, defaultInputBoxStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; +import { IAutomationDescriptor } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; +import { IAutomationService } from '../../../../../workbench/contrib/chat/common/automations/automationService.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; +import '../../browser/views/automationsView.js'; + +export default defineThemedFixtureGroup({ path: 'sessions/automationDeletion/' }, { + Confirmation: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast'], + render: renderConfirmation, + }), +}); + +async function renderConfirmation(ctx: ComponentFixtureContext): Promise { + ctx.container.style.width = '700px'; + ctx.container.style.height = '320px'; + const shown = new DeferredPromise(); + const automation: IAutomationDescriptor = { + id: 'daily-review', + name: 'Daily review', + prompt: 'Review the workspace', + schedule: { interval: 'hourly', scheduleHour: 0, scheduleMinute: 0, scheduleDay: 0 }, + target: { kind: 'workspace', folderUri: URI.file('/workspace'), isolation: { kind: 'default' } }, + enabled: true, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + }; + const instantiationService = createEditorServices(ctx.disposableStore, { + colorTheme: ctx.theme, + additionalServices: reg => { + reg.defineInstance(IConfigurationService, new TestConfigurationService({ chat: { automations: { enabled: true } } })); + reg.defineInstance(IAutomationService, new class extends mock() { + override canDeleteAutomation(): boolean { return true; } + override supportsDeleteHistoryChoice(): boolean { return true; } + override async deleteAutomation(): Promise { } + }()); + reg.defineInstance(IDialogService, new class extends mock() { + override async confirm(confirmation: IConfirmation): Promise { + const dialog = ctx.disposableStore.add(new Dialog(ctx.container, confirmation.message, [confirmation.primaryButton ?? 'Yes', 'Cancel'], { + cancelId: 1, + detail: typeof confirmation.detail === 'string' ? confirmation.detail : confirmation.detail?.value, + type: typeof confirmation.type === 'string' ? confirmation.type : 'question', + checkboxLabel: confirmation.checkbox?.label, + checkboxChecked: confirmation.checkbox?.checked, + buttonStyles: defaultButtonStyles, + checkboxStyles: defaultCheckboxStyles, + inputBoxStyles: defaultInputBoxStyles, + dialogStyles: defaultDialogStyles, + })); + const result = dialog.show(); + void shown.complete(); + try { + const { button, checkboxChecked } = await result; + return { confirmed: button === 0, checkboxChecked }; + } finally { + dialog.dispose(); + } + } + }()); + }, + }); + const command = CommandsRegistry.getCommand('sessions.automations.delete'); + if (!command) { + throw new Error('Automation deletion command is not registered'); + } + void Promise.resolve(instantiationService.invokeFunction(accessor => command.handler(accessor, automation))).catch(error => shown.error(error)); + await shown.p; +} diff --git a/src/vs/sessions/contrib/sessions/test/browser/automationsStyles.test.ts b/src/vs/sessions/contrib/sessions/test/browser/automationsStyles.test.ts new file mode 100644 index 000000000000..8a8b9d4fe599 --- /dev/null +++ b/src/vs/sessions/contrib/sessions/test/browser/automationsStyles.test.ts @@ -0,0 +1,118 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../../../browser/media/style.css'; +import '../../browser/media/automationsCards.css'; +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'; + +suite('Automations Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('keyboard-focused cards retain their focus boundary while hovered', () => { + const describe = (theme: 'vs' | 'hc-black') => { + const root = append(mainWindow.document.body, $(`.monaco-workbench.agent-sessions-workbench.${theme}`)); + root.style.cssText = [ + '--vscode-strokeThickness: 1px', + '--vscode-editorWidget-border: #112233', + '--vscode-list-hoverBackground: #223344', + '--vscode-contrastActiveBorder: #445566', + '--vscode-focusBorder: #778899', + ].join(';'); + store.add(toDisposable(() => root.remove())); + + const card = append(root, $('.automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered.hovered')); + append(card, $('button.automations-card-main.focus-visible')); + const style = mainWindow.getComputedStyle(card); + return { + background: style.backgroundColor, + borderColor: style.borderColor, + outlineColor: style.outlineColor, + outlineOffset: style.outlineOffset, + outlineStyle: style.outlineStyle, + outlineWidth: style.outlineWidth, + }; + }; + + assert.deepStrictEqual({ + defaultTheme: describe('vs'), + highContrast: describe('hc-black'), + }, { + defaultTheme: { + background: 'rgba(0, 0, 0, 0)', + borderColor: 'rgb(17, 34, 51)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + highContrast: { + background: 'rgba(0, 0, 0, 0)', + borderColor: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-2px', + outlineStyle: 'solid', + outlineWidth: '2px', + }, + }); + }); + + test('nested action hover and open states do not outline the parent card', () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.hc-black')); + root.style.cssText = [ + '--vscode-strokeThickness: 1px', + '--vscode-editorWidget-border: #112233', + '--vscode-list-hoverBackground: #223344', + '--vscode-toolbar-hoverBackground: #334455', + '--vscode-contrastActiveBorder: #445566', + ].join(';'); + store.add(toDisposable(() => root.remove())); + + const card = append(root, $('.automations-card.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered.hovered')); + append(card, $('button.automations-card-main')); + const actions = append(card, $('.automations-card-actions.hovered')); + const button = append(actions, $('button.monaco-button.automations-card-action-button.hovered')); + const readOutline = (element: HTMLElement) => { + const style = mainWindow.getComputedStyle(element); + return { + color: style.outlineStyle === 'none' ? 'none' : style.outlineColor, + style: style.outlineStyle, + width: style.outlineStyle === 'none' ? '0px' : style.outlineWidth, + }; + }; + const hovered = { + card: { + background: mainWindow.getComputedStyle(card).backgroundColor, + borderColor: mainWindow.getComputedStyle(card).borderColor, + outline: readOutline(card), + }, + button: readOutline(button), + }; + button.setAttribute('aria-expanded', 'true'); + actions.classList.add('menu-open'); + const open = { + card: readOutline(card), + button: readOutline(button), + }; + + assert.deepStrictEqual({ hovered, open }, { + hovered: { + card: { + background: 'rgba(0, 0, 0, 0)', + borderColor: 'rgb(17, 34, 51)', + outline: { color: 'none', style: 'none', width: '0px' }, + }, + button: { color: 'rgb(68, 85, 102)', style: 'dashed', width: '1px' }, + }, + open: { + card: { color: 'none', style: 'none', width: '0px' }, + button: { color: 'rgb(68, 85, 102)', style: 'solid', width: '1px' }, + }, + }); + }); +}); diff --git a/src/vs/sessions/contrib/sessions/test/browser/automationsView.fixture.ts b/src/vs/sessions/contrib/sessions/test/browser/automationsView.fixture.ts index 7edd5dc92366..c558452bc104 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/automationsView.fixture.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/automationsView.fixture.ts @@ -19,13 +19,19 @@ import { ContextKeyService } from '../../../../../platform/contextkey/browser/co import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { HoverService } from '../../../../../platform/hover/browser/hoverService.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; import { IListService, ListService } from '../../../../../platform/list/browser/listService.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; import { IMarkdownRendererService, MarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js'; import { InMemoryStorageService } from '../../../../../platform/storage/common/storage.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { getEntryAddress, IRemoteAgentHostConnectionInfo, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { IMissionControlEnvironmentService, IMissionControlHost } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { IAutomationDescriptor, IAutomationRun } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; import { IAutomationDialogService } from '../../../../../workbench/contrib/chat/common/automations/automationDialogService.js'; import { ChatAutomationsEnabledContext } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; @@ -38,7 +44,7 @@ import { ContributionEnablementState } from '../../../../../workbench/contrib/ch import { IAgentPlugin, IAgentPluginService } from '../../../../../workbench/contrib/chat/common/plugins/agentPluginService.js'; import { IVoicePlaybackService } from '../../../../../workbench/contrib/chat/common/voicePlaybackService.js'; import { stubSessionHosts, testGridPanes } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; -import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices, waitForFixtureDomCondition } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; import { CustomViewNode } from '../../../../browser/parts/customViewNode.js'; import { CustomViewService } from '../../../../services/customView/browser/customViewService.js'; import { ICustomViewService } from '../../../../../workbench/contrib/sessions/browser/customView.js'; @@ -48,7 +54,9 @@ import { ISessionsService } from '../../../../../workbench/contrib/sessions/brow import { IChat, ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../../../../../workbench/contrib/sessions/browser/automationsConstants.js'; +import { ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; import { AutomationsCustomViewContribution } from '../../browser/views/automationsView.js'; +import '../../../../browser/media/style.css'; const WORKSPACE = URI.parse('file:///workspaces/vscode'); const ITestAgentSessionsService = createDecorator('agentSessions'); @@ -107,6 +115,33 @@ class FixtureAutomationService extends mock() { override canDeleteAutomation(): boolean { return true; } } +class FixtureRemoteAgentHostService extends mock() { + + override readonly onDidChangeConnections = Event.None; + override readonly onDidChangeConfiguredEntries = Event.None; + override readonly configuredEntries: readonly IRemoteAgentHostEntry[]; + override readonly connections: readonly IRemoteAgentHostConnectionInfo[]; + + constructor(entries: readonly IRemoteAgentHostEntry[]) { + super(); + const tunnelCount = entries.filter(entry => entry.connection.type === RemoteAgentHostEntryType.Tunnel).length; + const fillerEntries = Array.from({ length: tunnelCount > 0 ? Math.max(0, 5 - tunnelCount) : 0 }, (_, index): IRemoteAgentHostEntry => ({ + name: `Remote host ${tunnelCount + index + 1}`, + connection: { + type: RemoteAgentHostEntryType.Tunnel, + tunnelId: `fixture-${tunnelCount + index + 1}`, + clusterId: 'test', + }, + })); + this.configuredEntries = [...entries, ...fillerEntries]; + this.connections = this.configuredEntries.map(entry => ({ + name: entry.name, + address: getEntryAddress(entry), + status: RemoteAgentHostConnectionStatus.disconnected, + })); + } +} + class FixtureSessionsManagementService extends mock() { private readonly sessions = new Map(); @@ -195,11 +230,28 @@ interface IAutomationsFixtureOptions { readonly followUp?: boolean; readonly historyState?: AutomationCatalogueState; readonly emptyHistory?: boolean; + readonly remoteEntries?: readonly IRemoteAgentHostEntry[]; + readonly githubEnvironments?: readonly IMissionControlHost[]; + readonly interaction?: 'cardHover' | 'cardActionHover' | 'cardActionOpen' | 'cardFocus' | 'templateHover' | 'templateSectionHover'; } +const TUNNEL_ENTRIES: readonly IRemoteAgentHostEntry[] = [ + { name: 'Remote build host', connection: { type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'build', clusterId: 'test' } }, + { name: 'Remote test host', connection: { type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'test', clusterId: 'test' } }, +]; +const GITHUB_ENVIRONMENT_ENTRY: IRemoteAgentHostEntry = { + name: 'GitHub Environment', + connection: { + type: RemoteAgentHostEntryType.CloudSandbox, + address: 'cloudsandbox:environment', + environmentId: 'environment', + environmentKind: 'user-local', + }, +}; +const remoteProviderId = (entry: IRemoteAgentHostEntry) => `agenthost-${agentHostAuthority(getEntryAddress(entry))}`; const UNAVAILABLE_PROVIDERS: readonly IAutomationProviderDescriptor[] = [ - { id: 'remote-build-host', label: 'Remote build host', unavailableReasonCode: 'disconnected' }, - { id: 'remote-test-host', label: 'Remote test host', unavailableReasonCode: 'disconnected' }, + { id: remoteProviderId(TUNNEL_ENTRIES[0]), label: TUNNEL_ENTRIES[0].name, unavailableReasonCode: 'disconnected' }, + { id: remoteProviderId(TUNNEL_ENTRIES[1]), label: TUNNEL_ENTRIES[1].name, unavailableReasonCode: 'disconnected' }, { id: 'windows-host', label: 'Windows host', unavailableReasonCode: 'disabled' }, { id: 'linux-host', label: 'Linux host', unavailableReasonCode: 'unsupported' }, { id: 'mac-host', label: 'Mac host', unavailableReasonCode: 'incompatible' }, @@ -247,11 +299,24 @@ export default defineThemedFixtureGroup({ path: 'sessions/automations/' }, { Unavailable: defineComponentFixture({ labels: { kind: 'screenshot' }, additionalThemes: ['darkHighContrast'], - render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, catalogueState: 'unavailable', unavailableProviders: [UNAVAILABLE_PROVIDERS[0]] }), + expectedVisualDescriptions: ['The unavailable empty state has no disconnected icon. No automations yet is followed by its description, then an italic remote detection count and Manage Remotes link.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, catalogueState: 'unavailable', unavailableProviders: [UNAVAILABLE_PROVIDERS[0]], remoteEntries: TUNNEL_ENTRIES }), + }), + GitHubEnvironmentUnavailable: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['A disconnected GitHub Environment does not add a warning or remote count to the normal No automations yet empty state.'], + render: ctx => renderAutomations(ctx, { + width: 1000, + height: 620, + populated: false, + catalogueState: 'unavailable', + unavailableProviders: [{ id: remoteProviderId(GITHUB_ENVIRONMENT_ENTRY), label: GITHUB_ENVIRONMENT_ENTRY.name, unavailableReasonCode: 'disconnected' }], + githubEnvironments: [{ id: 'environment', name: GITHUB_ENVIRONMENT_ENTRY.name, kind: 'user-local', status: 'offline' }], + }), }), UnavailableMultipleReasons: defineComponentFixture({ labels: { kind: 'screenshot' }, - render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, catalogueState: 'unavailable', unavailableProviders: UNAVAILABLE_PROVIDERS }), + render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, catalogueState: 'unavailable', unavailableProviders: UNAVAILABLE_PROVIDERS, remoteEntries: TUNNEL_ENTRIES }), }), NarrowUnavailable: defineComponentFixture({ labels: { kind: 'screenshot' }, @@ -262,7 +327,19 @@ export default defineThemedFixtureGroup({ path: 'sessions/automations/' }, { }), PartialUnavailable: defineComponentFixture({ labels: { kind: 'screenshot' }, - render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, catalogueState: 'unavailable', unavailableProviders: [UNAVAILABLE_PROVIDERS[0]] }), + additionalThemes: ['darkHighContrast'], + expectedVisualDescriptions: ['The unavailable banner below the automation cards shows an italic remote detection count followed by a Manage Remotes text link instead of the disconnected-host warning.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, catalogueState: 'unavailable', unavailableProviders: [UNAVAILABLE_PROVIDERS[0]], remoteEntries: TUNNEL_ENTRIES }), + }), + PartialDisconnectedRemotes: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['The unavailable banner shows an italic remote detection count followed by a Manage Remotes text link without listing the disconnected hosts.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, catalogueState: 'unavailable', unavailableProviders: UNAVAILABLE_PROVIDERS.slice(0, 2), remoteEntries: TUNNEL_ENTRIES }), + }), + NarrowPartialDisconnectedRemotes: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['At a narrow width, the unavailable banner keeps the italic remote detection count and Manage Remotes link readable without clipping either.'], + render: ctx => renderAutomations(ctx, { width: 520, height: 720, populated: true, catalogueState: 'unavailable', unavailableProviders: UNAVAILABLE_PROVIDERS.slice(0, 2), remoteEntries: TUNNEL_ENTRIES }), }), PartialUnavailableMultipleReasons: defineComponentFixture({ labels: { kind: 'screenshot' }, @@ -272,6 +349,7 @@ export default defineThemedFixtureGroup({ path: 'sessions/automations/' }, { populated: true, catalogueState: 'unavailable', unavailableProviders: UNAVAILABLE_PROVIDERS, + remoteEntries: TUNNEL_ENTRIES, }), }), PartialError: defineComponentFixture({ @@ -286,6 +364,40 @@ export default defineThemedFixtureGroup({ path: 'sessions/automations/' }, { labels: { kind: 'screenshot' }, render: ctx => renderAutomations(ctx, { width: 520, height: 720, populated: true }), }), + CardHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, interaction: 'cardHover' }), + }), + CardActionHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the More Actions control. In high contrast themes, only the action has a dashed active-contrast boundary; the parent card does not.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, interaction: 'cardActionHover' }), + }), + CardActionOpen: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The More Actions control is open. In high contrast themes, only the action has a solid active-contrast boundary; the parent card does not.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, interaction: 'cardActionOpen' }), + }), + CardFocus: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The real automation card button has keyboard focus. In high contrast themes, the card has a two-stroke inset solid focus boundary and the production prompt hover is visible.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 720, populated: true, interaction: 'cardFocus' }), + }), + TemplateHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, interaction: 'templateHover' }), + }), + TemplateSectionHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the Built-in Templates disclosure. In high contrast themes, a dashed active-contrast outline surrounds the section header.'], + render: ctx => renderAutomations(ctx, { width: 1000, height: 620, populated: false, interaction: 'templateSectionHover' }), + }), CloudHistory: defineComponentFixture({ additionalThemes: ['darkHighContrast'], render: ctx => renderAutomations(ctx, { width: 1000, height: 850, populated: true, cloud: true }), @@ -307,16 +419,20 @@ export default defineThemedFixtureGroup({ path: 'sessions/automations/' }, { }), }); -function renderAutomations(ctx: ComponentFixtureContext, options: IAutomationsFixtureOptions): void { +async function renderAutomations(ctx: ComponentFixtureContext, options: IAutomationsFixtureOptions): Promise { const data = options.repositoryOnly ? createRepositoryOnlyData() : options.cloud ? createCloudData() : options.populated ? createPopulatedData() : { automations: [], runs: [] }; const configurationService = new TestConfigurationService({ chat: { automations: { enabled: true } }, + [RemoteAgentHostsEnabledSettingId]: true, + [ENVIRONMENT_PICKER_SETTING]: true, + [ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]: true, }); const contextKeyService = new ContextKeyService(configurationService); const actionViewItemService = new FixtureActionViewItemService(); const customViewService = ctx.disposableStore.add(new CustomViewService(new NullLogService(), ctx.disposableStore.add(new InMemoryStorageService()))); const runs = options.emptyHistory ? [] : data.runs; const automationService = new FixtureAutomationService(data.automations, runs, options.catalogueState ?? 'ready', options.unavailableProviders ?? []); + const remoteAgentHostService = new FixtureRemoteAgentHostService(options.remoteEntries ?? []); automationService.historyState = constObservable(options.historyState ?? 'ready'); const sessionsManagementService = new FixtureSessionsManagementService(options.cloud && !options.nativeCloud ? [] : runs); const agentPluginService = new class extends mock() { @@ -346,6 +462,14 @@ function renderAutomations(ctx: ComponentFixtureContext, options: IAutomationsFi colorTheme: ctx.theme, additionalServices: reg => { registerWorkbenchServices(reg); + if (options.interaction === 'cardFocus') { + reg.definePartialInstance(ILayoutService, { getContainer: () => ctx.container }); + reg.define(IHoverService, class extends HoverService { + override showInstantHover(options: Parameters[0]) { + return super.showInstantHover({ ...options, container: ctx.container }, false); + } + }); + } reg.defineInstance(IActionViewItemService, actionViewItemService); reg.define(IListService, ListService); reg.define(IMarkdownRendererService, MarkdownRendererService); @@ -358,6 +482,11 @@ function renderAutomations(ctx: ComponentFixtureContext, options: IAutomationsFi override readonly extUri = new ExtUri(() => true); }()); reg.defineInstance(IAutomationService, automationService); + reg.defineInstance(IRemoteAgentHostService, remoteAgentHostService); + reg.defineInstance(IMissionControlEnvironmentService, new class extends mock() { + override readonly enabled = true; + override readonly hosts = constObservable(options.githubEnvironments ?? []); + }()); reg.defineInstance(IAutomationRunner, new class extends mock() { }()); reg.defineInstance(IAutomationDialogService, new class extends mock() { }()); reg.defineInstance(IAgentPluginService, agentPluginService); @@ -401,24 +530,55 @@ function renderAutomations(ctx: ComponentFixtureContext, options: IAutomationsFi }); stubSessionHosts(instantiationService, ctx.disposableStore); - ctx.disposableStore.add(instantiationService.createInstance(AutomationsCustomViewContribution)); - customViewService.showCustomView(AUTOMATIONS_CUSTOM_VIEW_ID); - const descriptor = customViewService.activeCustomView.get(); - if (!descriptor) { - throw new Error('Automations custom view was not registered'); - } - ctx.container.classList.add('monaco-workbench'); + if (options.interaction === 'cardActionHover' || options.interaction === 'cardActionOpen') { + ctx.container.classList.add('agent-sessions-workbench'); + } ctx.container.style.width = `${options.width}px`; ctx.container.style.height = `${options.height}px`; ctx.container.style.setProperty('--session-view-background', 'var(--vscode-agentsPanel-background, var(--vscode-sideBar-background))'); ctx.container.style.setProperty('--session-view-foreground', 'var(--vscode-agentsPanel-foreground, var(--vscode-sideBar-foreground))'); ctx.container.style.backgroundColor = 'var(--session-view-background)'; + ctx.disposableStore.add(instantiationService.createInstance(AutomationsCustomViewContribution)); + customViewService.showCustomView(AUTOMATIONS_CUSTOM_VIEW_ID); + const descriptor = customViewService.activeCustomView.get(); + if (!descriptor) { + throw new Error('Automations custom view was not registered'); + } + const node = ctx.disposableStore.add(instantiationService.createInstance(CustomViewNode, descriptor)); node.element.style.height = '100%'; ctx.container.appendChild(node.element); node.layout(options.width, options.height); + if (options.interaction === 'cardHover') { + node.element.querySelector('.automations-card')?.classList.add('hovered'); + } else if (options.interaction === 'cardActionHover' || options.interaction === 'cardActionOpen') { + const card = node.element.querySelector('.automations-card'); + const actions = card?.querySelector('.automations-card-actions'); + const action = card?.querySelector('.automations-card-more-actions-button'); + if (!card || !actions || !action) { + throw new Error('Automation card action was not rendered'); + } + card.classList.add('hovered'); + actions.classList.add('hovered'); + action.classList.add('hovered'); + if (options.interaction === 'cardActionOpen') { + actions.classList.add('menu-open'); + action.setAttribute('aria-expanded', 'true'); + } + } else if (options.interaction === 'cardFocus') { + const main = node.element.querySelector('.automations-card-main'); + if (!main) { + throw new Error('Automation card was not rendered'); + } + ctx.focus({ focus: () => main.focus({ focusVisible: true }) }); + await waitForFixtureDomCondition(ctx.container.ownerDocument.body, () => ctx.container.ownerDocument.querySelector('.monaco-hover') !== null, ctx.disposableStore); + } else if (options.interaction === 'templateHover') { + node.element.querySelector('.automations-template-card')?.classList.add('hovered'); + } else if (options.interaction === 'templateSectionHover') { + node.element.querySelector('.automations-template-section-summary')?.classList.add('hovered'); + } if (options.showDropTarget) { const dataTransfer = new DataTransfer(); dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([URI.file('/shared/review.automation.md').toString()])); diff --git a/src/vs/sessions/contrib/sessions/test/browser/automationsView.test.ts b/src/vs/sessions/contrib/sessions/test/browser/automationsView.test.ts index 39947b2653c2..9125f0f52d2f 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/automationsView.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/automationsView.test.ts @@ -30,13 +30,16 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { AccessibleViewRegistry } from '../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; -import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { getEntryAddress, IRemoteAgentHostConnectionInfo, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { IMissionControlEnvironmentService, IMissionControlHost } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { CommandsRegistry, ICommandService } from '../../../../../platform/commands/common/commands.js'; import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IContextMenuMenuDelegate, IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; -import { IConfirmation, IConfirmationResult, IDialogService, IFileDialogService, ISaveDialogOptions } from '../../../../../platform/dialogs/common/dialogs.js'; +import { IConfirmation, IConfirmationResult, IDialogService, IFileDialogService, IPrompt, ISaveDialogOptions } from '../../../../../platform/dialogs/common/dialogs.js'; import { IFileContent, IFileService, IFileStatWithMetadata } from '../../../../../platform/files/common/files.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; @@ -56,7 +59,7 @@ import { IAutomationRunDispatch, IAutomationRunner, IAutomationRunOperation } fr import { AutomationCatalogueState, AutomationMutationGuard, IAutomationProviderConfiguration, IAutomationProviderDescriptor, IAutomationRefreshOptions, IAutomationService, ICreateAutomationOptions, IDeleteAutomationOptions, IGuardedAutomationUpdateResult, IUpdateAutomationOptions } from '../../../../../workbench/contrib/chat/common/automations/automationService.js'; import { ContributionEnablementState } from '../../../../../workbench/contrib/chat/common/enablement.js'; import { IAgentPlugin, IAgentPluginService } from '../../../../../workbench/contrib/chat/common/plugins/agentPluginService.js'; -import { openOnboardingTarget } from '../../../../../workbench/contrib/onboarding/browser/spotlight/onboardingTarget.js'; +import { openOnboardingTarget, resolveOnboardingTarget } from '../../../../../workbench/contrib/onboarding/browser/spotlight/onboardingTarget.js'; import { ICustomViewDescriptor, ICustomViewService } from '../../../../../workbench/contrib/sessions/browser/customView.js'; import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; @@ -77,12 +80,17 @@ import { ISessionsProvidersService } from '../../../../../workbench/contrib/sess import { IVoicePlaybackService } from '../../../../../workbench/contrib/chat/common/voicePlaybackService.js'; import { IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; import { IChatModel, IChatRequestModel, IChatResponseModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { toPasteVariableEntry } from '../../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; +import { INewSessionComposerService, NewSessionComposerService } from '../../../../../workbench/contrib/sessions/browser/newSessionComposerService.js'; +import { ISessionDraftsService } from '../../../../../workbench/contrib/sessions/browser/sessionDraftsService.js'; +import { readNewChatDraftState, writeNewChatDraftState } from '../../../../../workbench/contrib/sessions/common/newChatDraftState.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { IMenuService, MenuId, registerAction2 } from '../../../../../platform/actions/common/actions.js'; import { MenuService } from '../../../../../platform/actions/common/menuService.js'; import { AgentsWindowMenus } from '../../../../browser/agentsWindowMenus.js'; import { ArchiveSessionAction } from '../../browser/views/sessionsViewActions.js'; -import { HIDE_AUTOMATION_SESSION_FROM_LIST_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, SHOW_AUTOMATION_SESSION_IN_LIST_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; +import { HIDE_AUTOMATION_SESSION_FROM_LIST_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, OPEN_REMOTES_EDITOR_COMMAND_ID, SHOW_AUTOMATION_SESSION_IN_LIST_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; +import { ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING, ENVIRONMENT_PICKER_SETTING } from '../../../../../workbench/contrib/sessions/common/chatConstants.js'; import { TestCommandService } from './sessionsListTestUtils.js'; import { TestDataTelemetryService } from '../../../../../platform/telemetry/test/common/testTelemetryService.js'; import { stubSessionsHostLayout } from '../../../../test/browser/sessionsHostLayoutTestUtils.js'; @@ -398,9 +406,16 @@ class FakeDialogService extends mock() { readonly errors: { message: string; detail: string }[] = []; readonly infos: string[] = []; readonly confirmations: IConfirmation[] = []; + readonly prompts: IPrompt[] = []; readonly errorCalled = new DeferredPromise(); readonly infoCalled = new DeferredPromise(); confirmResult: IConfirmationResult = { confirmed: false }; + promptButtonIndex = -1; + + override async prompt(prompt: IPrompt) { + this.prompts.push(prompt); + return { result: await prompt.buttons?.[this.promptButtonIndex]?.run({}) }; + } override async confirm(confirmation: IConfirmation): Promise { this.confirmations.push(confirmation); @@ -443,6 +458,7 @@ class FakeSessionsService extends mock() { readonly activeSession = constObservable(undefined); readonly openGate = new DeferredPromise(); openCalls = 0; + openNewSessionCalls = 0; error: Error | undefined; constructor(private readonly onOpen: () => Promise) { @@ -457,6 +473,11 @@ class FakeSessionsService extends mock() { } await this.onOpen(); } + + override async openNewSession() { + this.openNewSessionCalls++; + return { session: undefined, trustDeclined: false }; + } } class FakeSessionsManagementService extends mock() implements IDisposable { @@ -477,6 +498,7 @@ class FakeSessionsManagementService extends mock() i } sessionExists = true; private firstSessionCataloged = true; + onGetSessions: (() => void) | undefined; readonly isRead = observableValue(this, false); readonly secondIsRead = observableValue(this, false); readonly isArchived = observableValue(this, false); @@ -569,6 +591,7 @@ class FakeSessionsManagementService extends mock() i readonly markAllReadCompleted = new DeferredPromise(); override getSessions(): ISession[] { + this.onGetSessions?.(); if (!this.sessionExists) { return []; } @@ -674,6 +697,70 @@ class FakeSessionsManagementService extends mock() i } } +class FakeRemoteAgentHostService extends mock() implements IDisposable { + private readonly connectionsEmitter = new Emitter(); + private readonly configuredEntriesEmitter = new Emitter(); + private _connections: readonly IRemoteAgentHostConnectionInfo[] = []; + private _configuredEntries: readonly IRemoteAgentHostEntry[] = []; + + override readonly onDidChangeConnections = this.connectionsEmitter.event; + override readonly onDidChangeConfiguredEntries = this.configuredEntriesEmitter.event; + + override get connections(): readonly IRemoteAgentHostConnectionInfo[] { + return this._connections; + } + + override get configuredEntries(): readonly IRemoteAgentHostEntry[] { + return this._configuredEntries; + } + + setConnections(connections: readonly IRemoteAgentHostConnectionInfo[]): void { + this._connections = connections; + this.connectionsEmitter.fire(); + } + + setConfiguredEntries(configuredEntries: readonly IRemoteAgentHostEntry[]): void { + this._configuredEntries = configuredEntries; + this.configuredEntriesEmitter.fire(); + } + + dispose(): void { + this.connectionsEmitter.dispose(); + this.configuredEntriesEmitter.dispose(); + } +} + +class FakeMissionControlEnvironmentService extends mock() { + override readonly hosts = observableValue(this, []); + + setHosts(hosts: readonly IMissionControlHost[]): void { + this.hosts.set(hosts, undefined); + } +} + +function tunnelEntry(name: string, tunnelId: string): IRemoteAgentHostEntry { + return { + name, + connection: { type: RemoteAgentHostEntryType.Tunnel, tunnelId, clusterId: 'test' }, + }; +} + +function githubEnvironmentEntry(name: string, environmentId: string): IRemoteAgentHostEntry { + return { + name, + connection: { + type: RemoteAgentHostEntryType.CloudSandbox, + address: `cloudsandbox:${environmentId}`, + environmentId, + environmentKind: 'user-local', + }, + }; +} + +function providerId(entry: IRemoteAgentHostEntry): string { + return `agenthost-${agentHostAuthority(getEntryAddress(entry))}`; +} + suite('AutomationsCardsWidget', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); let archiveActionRegistration: IDisposable; @@ -681,6 +768,14 @@ suite('AutomationsCardsWidget', () => { suiteSetup(() => archiveActionRegistration = registerAction2(ArchiveSessionAction)); suiteTeardown(() => archiveActionRegistration.dispose()); + // Animation frames stay real: a frame requested from a faked clock and dropped by restore() + // leaves the window's shared animation frame runner blocked for every later test. + function useFakeTimersWithRealAnimationFrames() { + const clock = useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] }); + disposables.add(toDisposable(() => clock.restore())); + return clock; + } + function getSessionAction(widget: AutomationsCardsWidget, label: string): HTMLElement | undefined { return [...widget.element.querySelectorAll('.automations-run-session-list .action-label')] .find(element => element.getAttribute('aria-label') === label || element.title === label); @@ -691,7 +786,18 @@ suite('AutomationsCardsWidget', () => { return !!button && button.style.display !== 'none'; } - function setup(archiveWording: 'archive' | 'done' = 'archive', hoverService: IHoverService = NullHoverService, fileService?: IFileService, storageService?: IStorageService) { + function setup( + archiveWording: 'archive' | 'done' = 'archive', + hoverService: IHoverService = NullHoverService, + fileService?: IFileService, + storageService?: IStorageService, + initialState?: { + readonly catalogueState: AutomationCatalogueState; + readonly unavailableProviders: readonly IAutomationProviderDescriptor[]; + readonly configuredEntries: readonly IRemoteAgentHostEntry[]; + readonly githubEnvironments?: readonly IMissionControlHost[]; + }, + ) { const automationService = new FakeAutomationService(); const automationDialogService = new FakeAutomationDialogService(); const agentPluginService = new FakeAgentPluginService(); @@ -700,11 +806,24 @@ suite('AutomationsCardsWidget', () => { const runner = new FakeRunner(); const sessionsManagementService = disposables.add(new FakeSessionsManagementService()); const sessionsService = new FakeSessionsService(() => sessionsManagementService.markRead(sessionsManagementService.session)); - const configurationService = new TestConfigurationService({ chat: { automations: { enabled: true }, experimental: { sessionArchiveActionWording: archiveWording } } }); + const configurationService = new TestConfigurationService({ + chat: { automations: { enabled: true }, experimental: { sessionArchiveActionWording: archiveWording } }, + [RemoteAgentHostsEnabledSettingId]: initialState !== undefined, + [ENVIRONMENT_PICKER_SETTING]: initialState !== undefined, + [ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]: initialState !== undefined, + }); const logService = new TestLogService(); const commandService = new TestCommandService(); const keybindingService = new TestKeybindingService(); const telemetryService = new TestDataTelemetryService(); + const remoteAgentHostService = disposables.add(new FakeRemoteAgentHostService()); + const missionControlEnvironmentService = new FakeMissionControlEnvironmentService(); + if (initialState) { + automationService.setUnavailableProviders(initialState.unavailableProviders); + automationService.setCatalogueState(initialState.catalogueState); + remoteAgentHostService.setConfiguredEntries(initialState.configuredEntries); + missionControlEnvironmentService.setHosts(initialState.githubEnvironments ?? []); + } const store = disposables.add(new DisposableStore()); store.add(toDisposable(() => ModifierKeyEmitter.disposeInstance())); const instantiationService = workbenchInstantiationService(undefined, store); @@ -730,7 +849,11 @@ suite('AutomationsCardsWidget', () => { instantiationService.stub(IDialogService, dialogService); instantiationService.stub(IAutomationRunner, runner); instantiationService.stub(ISessionsService, sessionsService); + instantiationService.stub(INewSessionComposerService, disposables.add(new NewSessionComposerService())); + instantiationService.stub(ISessionDraftsService, { enabled: constObservable(false) }); instantiationService.stub(ISessionsManagementService, sessionsManagementService); + instantiationService.stub(IRemoteAgentHostService, remoteAgentHostService); + instantiationService.stub(IMissionControlEnvironmentService, missionControlEnvironmentService); instantiationService.stub(IConfigurationService, configurationService); if (fileService) { instantiationService.stub(IFileService, fileService); @@ -783,7 +906,7 @@ suite('AutomationsCardsWidget', () => { const widget = disposables.add(instantiationService.createInstance(AutomationsCardsWidget)); document.body.append(widget.element); disposables.add(toDisposable(() => widget.element.remove())); - return { agentPluginService, automationService, automationDialogService, commandService, configurationService, contextKeyService, contextMenuService, dialogService, instantiationService, keybindingService, logService, runner, sessionsManagementService, sessionsService, shownAutomationSessionIds, telemetryService, widget, refreshErrors, opened, chatModels, windowFocus, actionFactories }; + return { agentPluginService, automationService, automationDialogService, commandService, configurationService, contextKeyService, contextMenuService, dialogService, instantiationService, keybindingService, logService, missionControlEnvironmentService, remoteAgentHostService, runner, sessionsManagementService, sessionsService, shownAutomationSessionIds, telemetryService, widget, refreshErrors, opened, chatModels, windowFocus, actionFactories }; } function renderRefreshButton({ instantiationService, contextKeyService, actionFactories }: ReturnType): HTMLElement { @@ -1125,7 +1248,7 @@ suite('AutomationsCardsWidget', () => { assert.deepStrictEqual({ initial, resolved: sessionsManagementService.resolved, becameOpenable, removed: !cloudRow.classList.contains('can-open') && !cloudRow.querySelector('.session-main')!.hasAttribute('tabindex'), - }, { initial: [{ highlightable: false, role: null }, { highlightable: false, role: null }], resolved: [], becameOpenable: true, removed: true }); + }, { initial: [{ highlightable: false, role: null }], resolved: [], becameOpenable: true, removed: true }); }); test('cloud fallback toolbar actions do not also open the session', async () => { @@ -1176,9 +1299,205 @@ suite('AutomationsCardsWidget', () => { assert.deepStrictEqual({ initiallyVisible, hidden, restored: hasRefresh() }, { initiallyVisible: true, hidden: true, restored: true }); }); + test('header offers Create with Agent once automations exist, with Create Manually in its dropdown', async () => { + const { actionFactories, automationService, commandService, contextKeyService, contextMenuService, instantiationService, widget } = setup(); + const loadingTarget = widget.element.querySelector('.automations-cards-loading [data-onboarding-id="sessions.automations.create"]')!; + automationService.setCatalogueState('ready'); + const emptyTarget = widget.element.querySelector('.automations-cards-empty [data-onboarding-id="sessions.automations.create"]')!; + const headerActions = () => instantiationService.get(IMenuService).getMenuActions(AgentsWindowMenus.CustomViewAutomations, contextKeyService) + .flatMap(([, actions]) => actions); + const empty = headerActions().map(action => action.id); + automationService.setAutomations([automation()]); + const populated = headerActions().map(action => action.id); + const executed: unknown[][] = []; + const execute = stub(commandService, 'executeCommand').callsFake(async (commandId: string, ...args: unknown[]) => { + executed.push([commandId, ...args]); + if (commandId === 'sessions.automations.createWithAgent') { + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand(commandId)!.handler(accessor)); + } + return undefined; + }); + disposables.add(toDisposable(() => execute.restore())); + const action = headerActions().find(action => action.id === 'sessions.automations.createWithAgent')!; + const container = document.createElement('div'); + document.body.append(container); + disposables.add(toDisposable(() => container.remove())); + disposables.add(actionFactories.get(action.id)!(action, {}, instantiationService, 1)!).render(container); + + const [primary, chevron] = container.querySelectorAll('.monaco-button'); + const headerTarget = resolveOnboardingTarget(getWindow(container), 'sessions.automations.create')!; + let activations = 0; + disposables.add(headerTarget.onDidActivate!(() => activations++)); + primary.click(); + await timeout(0); + chevron.click(); + const dropdown = contextMenuService.delegate!.getActions(); + await dropdown[0].run(); + + assert.deepStrictEqual({ + empty, populated, + spotlightButtons: [loadingTarget, emptyTarget, headerTarget.element].map(target => Array.from(target.querySelectorAll('.monaco-button')).map(button => button.getAttribute('aria-label'))), + activations, label: primary.textContent, dropdown: dropdown.map(action => action.label), executed, + }, { + empty: ['sessions.automations.import', 'sessions.automations.refresh'], + populated: ['sessions.automations.createWithAgent', 'sessions.automations.import', 'sessions.automations.refresh'], + spotlightButtons: [ + ['Create with Agent', 'More Actions...'], + ['Create with Agent', 'More Actions...'], + ['Create Automation with Agent', 'More Actions...'], + ], + activations: 2, + label: 'Create with Agent', + dropdown: ['Create Manually'], + executed: [ + ['sessions.automations.createWithAgent'], + ['workbench.action.sessions.newChat', { prompt: '/automate ', prefillPrompt: true }], + ['sessionsView.newAutomation'], + ], + }); + }); + + for (const content of ['empty', 'text', 'attachment', 'mounted'] as const) { + for (const choice of ['cancel', 'replace', 'view'] as const) { + test(`Create with Agent handles ${choice} for a ${content} draft`, async () => { + const storageService = disposables.add(new InMemoryStorageService()); + const { commandService, dialogService, instantiationService, sessionsService } = setup('archive', NullHoverService, undefined, storageService); + const draft = { + inputText: content === 'text' ? 'Keep my draft' : '', + attachments: content === 'attachment' ? [toPasteVariableEntry('Notes', 'Attached notes', { id: 'notes' })] : [], + }; + writeNewChatDraftState(storageService, draft); + const savedDraft = readNewChatDraftState(storageService); + if (content === 'mounted') { + instantiationService.stub(INewSessionComposerService, { hasDraftInput: true }); + } + dialogService.promptButtonIndex = choice === 'replace' ? 0 : choice === 'view' ? 1 : -1; + const execute = stub(commandService, 'executeCommand').resolves(); + disposables.add(toDisposable(() => execute.restore())); + + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand('sessions.automations.createWithAgent')!.handler(accessor)); + + assert.deepStrictEqual({ + prompts: dialogService.prompts.map(prompt => ({ + type: prompt.type, message: prompt.message, detail: prompt.detail, + buttons: prompt.buttons?.map(button => button.label), cancelButton: prompt.cancelButton, + })), + commands: execute.args, + draftNavigations: sessionsService.openNewSessionCalls, + savedDraft: readNewChatDraftState(storageService), + }, { + prompts: content === 'empty' ? [] : [{ + type: 'warning', + message: 'Replace your existing draft?', + detail: 'This action will overwrite the existing new session draft, it will not be recoverable.', + buttons: ['Replace Draft', 'View Draft'], + cancelButton: true, + }], + commands: content === 'empty' || choice === 'replace' + ? [['workbench.action.sessions.newChat', { prompt: '/automate ', prefillPrompt: true }]] + : [], + draftNavigations: content !== 'empty' && choice === 'view' ? 1 : 0, + savedDraft, + }); + }); + } + } + + for (const source of ['saved', 'mounted'] as const) { + test(`Create with Agent skips the ${source} draft warning only while saved drafts are enabled`, async () => { + const storageService = disposables.add(new InMemoryStorageService()); + const { commandService, dialogService, instantiationService, sessionsService } = setup('archive', NullHoverService, undefined, storageService); + writeNewChatDraftState(storageService, { + inputText: 'Keep my draft', + attachments: [toPasteVariableEntry('Notes', 'Attached notes', { id: 'notes' })], + }); + const savedDraft = readNewChatDraftState(storageService); + if (source === 'mounted') { + instantiationService.stub(INewSessionComposerService, { hasDraftInput: true }); + } + const enabled = observableValue('savedDraftsEnabled', true); + instantiationService.stub(ISessionDraftsService, { enabled }); + const execute = stub(commandService, 'executeCommand').resolves(); + disposables.add(toDisposable(() => execute.restore())); + const invoke = () => instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand('sessions.automations.createWithAgent')!.handler(accessor)); + + await invoke(); + const enabledPrompts = dialogService.prompts.length; + enabled.set(false, undefined); + await invoke(); + + assert.deepStrictEqual({ + enabledPrompts, + disabledPrompts: dialogService.prompts.length, + commands: execute.args, + draftNavigations: sessionsService.openNewSessionCalls, + savedDraft: readNewChatDraftState(storageService), + }, { + enabledPrompts: 0, + disabledPrompts: 1, + commands: [['workbench.action.sessions.newChat', { prompt: '/automate ', prefillPrompt: true }]], + draftNavigations: 0, + savedDraft, + }); + }); + } + + for (const chatEnabled of [true, false]) { + test(`header split button supports toolbar navigation and manual creation (chat enabled: ${chatEnabled})`, async () => { + const { actionFactories, automationService, contextKeyService, contextMenuService, instantiationService } = setup(); + ChatContextKeys.enabled.bindTo(contextKeyService).set(chatEnabled); + automationService.setAutomations([automation()]); + const actions = instantiationService.get(IMenuService).getMenuActions(AgentsWindowMenus.CustomViewAutomations, contextKeyService) + .flatMap(([, actions]) => actions); + const create = actions.find(action => action.id === 'sessions.automations.createWithAgent')!; + const container = document.createElement('div'); + document.body.append(container); + disposables.add(toDisposable(() => container.remove())); + const toolbar = disposables.add(new ActionBar(container, { + actionViewItemProvider: (action, options) => actionFactories.get(action.id)?.(action, options, instantiationService, 1), + })); + toolbar.push([create, disposables.add(new Action('other', 'Other'))]); + const [primary, dropdown] = container.querySelectorAll('.monaco-button'); + const other = container.querySelector('.action-label')!; + const wrapper = primary.closest('.action-item')!; + const initialTabStops = [wrapper, primary, dropdown, other].map(element => element.tabIndex); + const key = (key: string, keyCode: number) => { + document.activeElement!.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true })); + document.activeElement!.dispatchEvent(new KeyboardEvent('keyup', { key, keyCode, bubbles: true })); + }; + toolbar.focus(0); + const entry = document.activeElement === (chatEnabled ? primary : dropdown); + if (chatEnabled) { + key('ArrowRight', 39); + } + const rightToDropdown = document.activeElement === dropdown; + key('Enter', 13); + const menu = contextMenuService.delegate!.getActions().map(action => action.label); + contextMenuService.delegate!.onHide?.(false); + key('ArrowRight', 39); + const rightToOther = document.activeElement === other; + key('ArrowLeft', 37); + const leftFromOther = document.activeElement === dropdown; + if (chatEnabled) { + key('ArrowLeft', 37); + } + const leftWithinSplit = document.activeElement === (chatEnabled ? primary : dropdown); + toolbar.setFocusable(false); + + assert.deepStrictEqual({ + initialTabStops, primaryDisabled: primary.getAttribute('aria-disabled'), entry, rightToDropdown, menu, + rightToOther, leftFromOther, leftWithinSplit, + finalTabStops: [wrapper, primary, dropdown, other].map(element => element.tabIndex), + }, { + initialTabStops: [-1, chatEnabled ? 0 : -1, chatEnabled ? -1 : 0, -1], + primaryDisabled: String(!chatEnabled), entry: true, rightToDropdown: true, menu: ['Create Manually'], + rightToOther: true, leftFromOther: true, leftWithinSplit: true, finalTabStops: [-1, -1, -1, -1], + }); + }); + } + test('refreshes every 60 seconds while visible without refreshing on window focus or overlapping requests', async () => { - const clock = useFakeTimers(); - disposables.add(toDisposable(() => clock.restore())); + const clock = useFakeTimersWithRealAnimationFrames(); const { widget, automationService, windowFocus } = setup(); await clock.tickAsync(0); await clock.tickAsync(30_000); @@ -1206,8 +1525,7 @@ suite('AutomationsCardsWidget', () => { }); test('a manual refresh in its history phase postpones the timer until 60 seconds after completion', async () => { - const clock = useFakeTimers(); - disposables.add(toDisposable(() => clock.restore())); + const clock = useFakeTimersWithRealAnimationFrames(); const { widget, automationService, instantiationService } = setup(); await clock.tickAsync(59_000); const pending = new DeferredPromise(); @@ -1233,8 +1551,7 @@ suite('AutomationsCardsWidget', () => { }); test('automatic refresh failures are logged without toasts while explicit refresh reports the error', async () => { - const clock = useFakeTimers(); - disposables.add(toDisposable(() => clock.restore())); + const clock = useFakeTimersWithRealAnimationFrames(); const { widget, automationService, logService, refreshErrors, instantiationService } = setup(); const failure = new Error('Offline'); automationService.refreshFailure = failure; @@ -1699,7 +2016,7 @@ suite('AutomationsCardsWidget', () => { emptyPersonal: { title: 'No automations yet', description: 'Describe what you want to automate, then choose when it runs.', - button: 'Create Automation', + button: 'Create with Agent', accessible: true, }, }); @@ -1850,36 +2167,92 @@ suite('AutomationsCardsWidget', () => { assert.strictEqual(automationDialogService.lastOptions?.existing?.enabled, false); }); - test('preserves a temporary Working row until its session resolves', () => { - const { automationService, widget } = setup(); + test('keeps a local run on its card until the session resolves without reviving after deletion', async () => { + const { automationService, sessionsManagementService, widget } = setup(); automationService.setAutomations([automation()]); const pendingRun = run({ status: 'pending', sessionResource: undefined }); automationService.setRuns([pendingRun]); - const temporaryRow = widget.element.querySelector('.automations-temporary-run'); - const spinner = widget.element.querySelector('.automations-temporary-run .session-icon .monaco-pixel-spinner'); + const card = widget.element.querySelector('.automations-card')!; + const runButton = card.querySelector('.automations-card-run-button')!; + const pending = { + historyRows: widget.element.querySelectorAll('.automations-history-group-runs .session-item').length, + prompt: card.querySelector('.automations-card-prompt')?.textContent, + buttonDisabled: runButton.getAttribute('aria-disabled'), + buttonLabel: runButton.getAttribute('aria-label'), + cardLabel: card.getAttribute('aria-label'), + }; automationService.setRuns([{ ...pendingRun, status: 'running' }]); - const runningRow = widget.element.querySelector('.automations-temporary-run'); - const runningSpinner = widget.element.querySelector('.automations-temporary-run .session-icon .monaco-pixel-spinner'); + const running = { + historyRows: widget.element.querySelectorAll('.automations-history-group-runs .session-item').length, + cardLabel: card.getAttribute('aria-label'), + }; automationService.setRuns([{ ...pendingRun, status: 'running', sessionResource: SESSION_RESOURCE }]); + const resolved = { + historyRows: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, + prompt: card.querySelector('.automations-card-prompt')?.textContent, + buttonDisabled: runButton.getAttribute('aria-disabled'), + buttonLabel: runButton.getAttribute('aria-label'), + cardLabel: card.getAttribute('aria-label'), + }; + const completedRun = { ...pendingRun, status: 'completed' as const, sessionResource: SESSION_RESOURCE }; + automationService.setRuns([completedRun]); + await sessionsManagementService.deleteSession(sessionsManagementService.session); + const deleted = { + historyRows: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, + prompt: card.querySelector('.automations-card-prompt')?.textContent, + buttonDisabled: runButton.getAttribute('aria-disabled'), + buttonLabel: runButton.getAttribute('aria-label'), + cardLabel: card.getAttribute('aria-label'), + }; + automationService.setRuns([{ ...completedRun, sessionResource: undefined }]); assert.deepStrictEqual({ - title: temporaryRow?.querySelector('.session-title')?.textContent, - status: temporaryRow?.querySelector('.session-description')?.textContent, - rowPreserved: runningRow === temporaryRow, - spinnerPreserved: runningSpinner === spinner, - spinnerUsesSharedIconSlot: spinner?.parentElement?.classList.contains('session-icon'), - temporaryRowsAfterCommit: widget.element.querySelectorAll('.automations-temporary-run').length, - sessionRowsAfterCommit: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, + pending, + running, + resolved, + deleted, + sessionlessCompleted: { + historyRows: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, + prompt: card.querySelector('.automations-card-prompt')?.textContent, + buttonDisabled: runButton.getAttribute('aria-disabled'), + buttonLabel: runButton.getAttribute('aria-label'), + cardLabel: card.getAttribute('aria-label'), + }, }, { - title: 'Daily review', - status: 'Working...', - rowPreserved: true, - spinnerPreserved: true, - spinnerUsesSharedIconSlot: true, - temporaryRowsAfterCommit: 0, - sessionRowsAfterCommit: 1, + pending: { + historyRows: 0, + prompt: 'Starting run...', + buttonDisabled: 'true', + buttonLabel: 'Running', + cardLabel: 'Daily review — Running', + }, + running: { + historyRows: 0, + cardLabel: 'Daily review — Running', + }, + resolved: { + historyRows: 1, + prompt: automation().prompt, + buttonDisabled: 'false', + buttonLabel: 'Run now', + cardLabel: 'Daily review — Hourly', + }, + deleted: { + historyRows: 0, + prompt: automation().prompt, + buttonDisabled: 'false', + buttonLabel: 'Run now', + cardLabel: 'Daily review — Hourly', + }, + sessionlessCompleted: { + historyRows: 0, + prompt: automation().prompt, + buttonDisabled: 'false', + buttonLabel: 'Run now', + cardLabel: 'Daily review — Hourly', + }, }); }); @@ -1896,7 +2269,7 @@ suite('AutomationsCardsWidget', () => { row.querySelector('.monaco-highlighted-label')?.textContent ?? row.querySelector('.session-title')?.textContent); automationService.setRuns([local, cloud]); const pending = titles(); - const cloudRow = [...widget.element.querySelectorAll('.automations-temporary-run')][1]; + const cloudRow = widget.element.querySelector('.automations-temporary-run')!; const cloudAction = cloudRow.querySelector('[aria-label="Open on GitHub"]')!; cloudAction.focus(); automationService.setRuns([{ ...local, status: 'running', sessionResource: SESSION_RESOURCE }, cloud]); @@ -1907,7 +2280,7 @@ suite('AutomationsCardsWidget', () => { pending, running, completed: titles(), cloudFocusPreserved, cloudRowPreserved: widget.element.querySelector('.automations-temporary-run') === cloudRow, }, { - pending: ['Daily review', 'Cloud review'], running: ['Daily review', 'Cloud review'], + pending: ['Cloud review'], running: ['Daily review', 'Cloud review'], completed: ['Daily review', 'Cloud review'], cloudFocusPreserved: true, cloudRowPreserved: true, }); }); @@ -1937,7 +2310,7 @@ suite('AutomationsCardsWidget', () => { }); }); - test('keeps a temporary row until a terminal run enters the committed session catalog', () => { + test('waits for the committed session catalog before showing local history', () => { const { automationService, sessionsManagementService, widget } = setup(); automationService.setAutomations([automation()]); sessionsManagementService.setFirstSessionCataloged(false); @@ -1949,15 +2322,25 @@ suite('AutomationsCardsWidget', () => { temporaryRows: widget.element.querySelectorAll('.automations-temporary-run').length, sessionRows: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, }; + let transition: { cardLabel: string | null | undefined; sessionRows: number } | undefined; + sessionsManagementService.onGetSessions = () => transition ??= { + cardLabel: widget.element.querySelector('.automations-card')?.getAttribute('aria-label'), + sessionRows: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, + }; sessionsManagementService.setFirstSessionCataloged(true); assert.deepStrictEqual({ beforeCatalogCommit, + transition, temporaryRowsAfterCommit: widget.element.querySelectorAll('.automations-temporary-run').length, sessionRowsAfterCommit: widget.element.querySelectorAll('.automations-run-session-list .session-item').length, }, { beforeCatalogCommit: { - temporaryRows: 1, + temporaryRows: 0, + sessionRows: 0, + }, + transition: { + cardLabel: 'Daily review — Running', sessionRows: 0, }, temporaryRowsAfterCommit: 0, @@ -2060,12 +2443,12 @@ suite('AutomationsCardsWidget', () => { assert.strictEqual(remainingGroups.length, 0, 'groups should be removed when empty'); }); - test('run feedback survives acknowledgement and refresh until a new run appears', async () => { - const clock = useFakeTimers(); - disposables.add(toDisposable(() => clock.restore())); + test('run feedback survives acknowledgement and refresh until the new run session appears', async () => { + const clock = useFakeTimersWithRealAnimationFrames(); const { automationService, runner, widget } = setup(); automationService.setAutomations([automation()]); - automationService.setRuns([run({ sessionResource: undefined })]); + const previousRun = run({ status: 'failed', sessionResource: undefined }); + automationService.setRuns([previousRun]); const dispatched = new DeferredPromise(); runner.whenDispatched = dispatched.p; const runButton = widget.element.querySelector('.automations-card-run-button')!; @@ -2089,14 +2472,18 @@ suite('AutomationsCardsWidget', () => { await dispatched.complete({ kind: 'accepted' }); await clock.tickAsync(10_000); automationService.setAutomations([automation({ prompt: 'Updated prompt' })]); - automationService.setRuns([run({ sessionResource: undefined }), run({ id: 'unrelated', automationId: 'other', sessionResource: undefined })]); + automationService.setRuns([previousRun, run({ id: 'unrelated', automationId: 'other', sessionResource: undefined })]); runButton.click(); const accepted = state(); - automationService.setRuns([run({ sessionResource: undefined }), run({ id: 'new-run', status: 'pending', sessionResource: undefined })]); - assert.deepStrictEqual({ starting, accepted, restored: state(), requests: runner.runCalls }, { + automationService.setRuns([previousRun, run({ id: 'new-run', status: 'pending', sessionResource: undefined })]); + const pending = state(); + automationService.setRuns([previousRun, run({ id: 'new-run', status: 'running', sessionResource: SESSION_RESOURCE })]); + assert.deepStrictEqual({ starting, accepted, pending, restored: state(), cardLabel: widget.element.querySelector('.automations-card')?.getAttribute('aria-label'), requests: runner.runCalls }, { starting: { disabled: 'true', label: 'Running', spinner: true, prompt: 'Starting run...' }, accepted: { disabled: 'true', label: 'Running', spinner: true, prompt: 'Starting run...' }, + pending: { disabled: 'true', label: 'Running', spinner: true, prompt: 'Starting run...' }, restored: { disabled: 'false', label: 'Run now', spinner: false, prompt: 'Updated prompt' }, + cardLabel: 'Daily review — Hourly', requests: 1, }); widget.dispose(); @@ -2152,10 +2539,13 @@ suite('AutomationsCardsWidget', () => { await timeout(0); const accepted = readState(); automationService.setRuns([run({ sessionResource: undefined, status: 'pending' })]); - assert.deepStrictEqual({ starting, accepted, discovered: readState() }, { + const discovered = readState(); + automationService.setRuns([run({ sessionResource: undefined, status: 'failed' })]); + assert.deepStrictEqual({ starting, accepted, discovered, failed: readState() }, { starting: { prompt: 'Starting run...', spinner: true, disabled: 'true' }, accepted: { prompt: 'Starting run...', spinner: true, disabled: 'true' }, - discovered: { prompt: automation().prompt, spinner: false, disabled: 'false' }, + discovered: { prompt: 'Starting run...', spinner: true, disabled: 'true' }, + failed: { prompt: automation().prompt, spinner: false, disabled: 'false' }, }); }); @@ -2189,6 +2579,23 @@ suite('AutomationsCardsWidget', () => { }); }); + test('uses the shared list interaction contract for custom controls', () => { + const { automationService, widget } = setup(); + automationService.setAutomations([automation()]); + + assert.deepStrictEqual({ + ownershipSummary: widget.element.querySelector('.automations-ownership-summary')?.className, + card: widget.element.querySelector('.automations-card')?.className, + templateSummary: widget.element.querySelector('.automations-template-section-summary')?.className, + templateCard: widget.element.querySelector('.automations-template-card')?.className, + }, { + ownershipSummary: 'automations-ownership-summary agent-sessions-interactive agent-sessions-interactive-list sessions-disclosure', + card: 'automations-card agent-sessions-interactive agent-sessions-interactive-list agent-sessions-interactive-bordered', + templateSummary: 'automations-template-section-summary agent-sessions-interactive agent-sessions-interactive-list sessions-disclosure', + templateCard: 'automations-template-card agent-sessions-interactive agent-sessions-interactive-list agent-sessions-interactive-bordered', + }); + }); + test('empty state is rendered once across repeated empty updates', () => { const { automationService, widget } = setup(); @@ -2663,6 +3070,7 @@ suite('AutomationsCardsWidget', () => { loading: widget.element.querySelector('.automations-cards-loading')?.style.display, unavailable: widget.element.querySelector('.automations-cards-unavailable')?.style.display, error: widget.element.querySelector('.automations-cards-error')?.style.display, + title: widget.element.querySelector('.automations-cards-unavailable .automations-cards-state-title')?.textContent, createButton: widget.element.querySelector('.automations-cards-unavailable .automations-cards-state-create-button')?.textContent, templates: widget.element.querySelectorAll('.automations-template-card').length, }; @@ -2674,9 +3082,9 @@ suite('AutomationsCardsWidget', () => { }; assert.deepStrictEqual({ loadingState, errorState, unavailableState, readyState }, { - loadingState: { loading: '', error: 'none', createButton: 'Create Automation', templates: AUTOMATION_TEMPLATES.length }, - errorState: { loading: 'none', error: '', createButton: 'Create Automation', description: 'The complete automation catalogue could not be read.', templates: AUTOMATION_TEMPLATES.length }, - unavailableState: { loading: 'none', unavailable: '', error: 'none', createButton: 'Create Automation', templates: AUTOMATION_TEMPLATES.length }, + loadingState: { loading: '', error: 'none', createButton: 'Create with Agent', templates: AUTOMATION_TEMPLATES.length }, + errorState: { loading: 'none', error: '', createButton: 'Create with Agent', description: 'The complete automation catalogue could not be read.', templates: AUTOMATION_TEMPLATES.length }, + unavailableState: { loading: 'none', unavailable: '', error: 'none', title: 'No automations yet', createButton: 'Create with Agent', templates: AUTOMATION_TEMPLATES.length }, readyState: { loading: 'none', error: 'none', templates: AUTOMATION_TEMPLATES.length }, }); }); @@ -2688,13 +3096,13 @@ suite('AutomationsCardsWidget', () => { automationService.setUnavailableProviders([{ id: 'remote-build-host', label: 'Remote build host' }]); automationService.setCatalogueState('unavailable'); const partialState = widget.element.querySelector('.automations-cards-partial-state'); - const unavailableMessage = partialState?.textContent; + const unavailableMessage = partialState?.querySelector('.automations-cards-partial-state-message')?.textContent; automationService.setCatalogueState('error'); assert.deepStrictEqual({ loadingDisplay, unavailableMessage, - errorMessage: widget.element.querySelector('.automations-cards-partial-state')?.textContent, + errorMessage: widget.element.querySelector('.automations-cards-partial-state-message')?.textContent, savedCards: widget.element.querySelectorAll('.automations-card').length, appearsAfterCards: partialState?.previousElementSibling?.classList.contains('automations-cards-grid'), templatesDisplay: widget.element.querySelector('.automations-templates')?.style.display, @@ -2726,17 +3134,197 @@ suite('AutomationsCardsWidget', () => { }); }); - test('create remains available after a catalogue error', async () => { - const { automationDialogService, automationService, widget } = setup(); + test('create with agent and create manually remain available after a catalogue error', async () => { + const { automationDialogService, automationService, commandService, contextMenuService, widget } = setup(); automationService.setCatalogueState('error'); - - widget.element.querySelector('.automations-cards-error .automations-cards-state-create-button')?.click(); + const executed: string[] = []; + const execute = stub(commandService, 'executeCommand').callsFake(async (commandId: string) => { executed.push(commandId); return undefined; }); + disposables.add(toDisposable(() => execute.restore())); + + const errorState = widget.element.querySelector('.automations-cards-error')!; + errorState.querySelector('.automations-cards-state-create-button')!.click(); + errorState.querySelector('.monaco-dropdown-button')!.click(); + const dropdown = contextMenuService.delegate!.getActions(); + await dropdown[0].run(); await Promise.resolve(); - assert.strictEqual(automationDialogService.showCalls, 1); + assert.deepStrictEqual({ + label: errorState.querySelector('.automations-cards-state-create-button')?.textContent, + executed, + dropdown: dropdown.map(action => action.label), + manualDialogs: automationDialogService.showCalls, + }, { + label: 'Create with Agent', + executed: ['sessions.automations.createWithAgent'], + dropdown: ['Create Manually'], + manualDialogs: 1, + }); + }); + + test('empty-state split buttons keep manual creation available while chat readiness changes', async () => { + const { automationDialogService, automationService, commandService, contextKeyService, contextMenuService, widget } = setup(); + const execute = stub(commandService, 'executeCommand').resolves(); + disposables.add(toDisposable(() => execute.restore())); + automationService.setCatalogueState('ready'); + const chatEnabled = ChatContextKeys.enabled.bindTo(contextKeyService); + chatEnabled.set(false); + const primary = widget.element.querySelector('.automations-cards-empty .automations-cards-create-button')!; + primary.click(); + primary.parentElement!.querySelector('.monaco-dropdown-button')!.click(); + await contextMenuService.delegate!.getActions()[0].run(); + const unavailable = { disabled: primary.getAttribute('aria-disabled'), agentCalls: execute.callCount, manualDialogs: automationDialogService.showCalls }; + chatEnabled.set(true); + primary.click(); + + assert.deepStrictEqual({ unavailable, restored: primary.getAttribute('aria-disabled'), agentCalls: execute.callCount }, { + unavailable: { disabled: 'true', agentCalls: 0, manualDialogs: 1 }, restored: 'false', agentCalls: 1, + }); + }); + + test('in-view Create with Agent failures are logged and surfaced in every catalogue state', async () => { + const { automationService, commandService, logService, refreshErrors, widget } = setup(); + const failure = new Error('Session could not open'); + const execute = stub(commandService, 'executeCommand').rejects(failure); + disposables.add(toDisposable(() => execute.restore())); + const states: readonly AutomationCatalogueState[] = ['loading', 'ready', 'unavailable', 'error']; + for (const state of states) { + automationService.setCatalogueState(state); + const selector = state === 'ready' ? '.automations-cards-empty .automations-cards-create-button' : `.automations-cards-${state} .automations-cards-state-create-button`; + widget.element.querySelector(selector)!.click(); + await timeout(0); + } + + assert.deepStrictEqual({ + notifications: refreshErrors, + logs: logService.errors.map(entry => ({ message: entry.message, error: entry.args[0] })), + }, { + notifications: states.map(() => 'Could not open a session to create an automation: Session could not open'), + logs: states.map(() => ({ message: '[Automations] Failed to open agent creation session', error: failure })), + }); + }); + + test('renders an initially unavailable disconnected remote without reading uninitialized state', () => { + const entry = tunnelEntry('Remote host', 'remote'); + const { widget } = setup('archive', NullHoverService, undefined, undefined, { + catalogueState: 'unavailable', + unavailableProviders: [{ id: providerId(entry), label: entry.name, unavailableReasonCode: 'disconnected' }], + configuredEntries: [entry], + }); + + assert.deepStrictEqual({ + count: widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes-count')?.textContent, + warningDisplay: widget.element.querySelector('.automations-cards-unavailable-message')?.style.display, + previousSibling: widget.element.querySelector('.automations-manage-remotes-target')?.previousElementSibling?.className, + hasIcon: !!widget.element.querySelector('.automations-cards-unavailable .automations-cards-state-icon'), + }, { + count: '0/1 remotes detected', + warningDisplay: 'none', + previousSibling: 'automations-cards-state-description', + hasIcon: false, + }); + }); + + test('restores the partial warning message when a disconnected catalogue becomes an error', async () => { + const { automationService, configurationService, remoteAgentHostService, widget } = setup(); + for (const setting of [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]) { + await configurationService.setUserConfiguration(setting, true); + } + const entry = tunnelEntry('Remote host', 'remote'); + remoteAgentHostService.setConfiguredEntries([entry]); + automationService.setAutomations([automation()]); + automationService.setUnavailableProviders([{ id: providerId(entry), label: entry.name, unavailableReasonCode: 'disconnected' }]); + automationService.setCatalogueState('unavailable'); + const message = widget.element.querySelector('.automations-cards-partial-state-message')!; + const disconnectedDisplay = message.style.display; + automationService.setCatalogueState('error'); + + assert.deepStrictEqual({ + disconnectedDisplay, + errorDisplay: message.style.display, + error: message.textContent, + }, { + disconnectedDisplay: 'none', + errorDisplay: '', + error: 'Some automations could not be loaded.', + }); }); for (const hasSavedAutomations of [false, true]) { + test(`opens Manage Remotes from disconnected providers ${hasSavedAutomations ? 'with' : 'without'} saved automations`, async () => { + const { automationService, widget, configurationService, commandService, remoteAgentHostService } = setup(); + const settings = [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]; + const setSetting = async (setting: string, value: boolean) => { + await configurationService.setUserConfiguration(setting, value); + configurationService.onDidChangeConfigurationEmitter.fire({ + source: ConfigurationTarget.USER, + affectedKeys: new Set([setting]), + change: { keys: [setting], overrides: [] }, + affectsConfiguration: key => key === setting, + }); + }; + for (const setting of settings) { + await setSetting(setting, true); + } + const entries = [ + tunnelEntry('Host 1', 'host-1'), + tunnelEntry('Host 2', 'host-2'), + ]; + remoteAgentHostService.setConfiguredEntries(entries); + automationService.setAutomations(hasSavedAutomations ? [automation()] : []); + automationService.setUnavailableProviders(entries.map(entry => ({ + id: providerId(entry), + label: entry.name, + unavailableReasonCode: 'disconnected' as const, + }))); + automationService.setCatalogueState('unavailable'); + const selector = hasSavedAutomations ? '.automations-cards-partial-state' : '.automations-cards-unavailable'; + const container = widget.element.querySelector(`${selector} .automations-manage-remotes`)!; + const link = container.querySelector('.monaco-link')!; + const description = widget.element.querySelector(hasSavedAutomations ? '.automations-cards-partial-state-message' : '.automations-cards-unavailable-message')!; + const initial = { + display: container.style.display, + label: link.textContent, + role: link.getAttribute('role'), + tabIndex: link.tabIndex, + count: container.querySelector('.automations-manage-remotes-count')?.textContent, + ariaLabel: link.getAttribute('aria-label'), + children: [...container.children].map(child => child.className), + disconnectedWarningDisplay: description.style.display, + }; + link.click(); + dispatchKeydown(link, { key: 'Enter', keyCode: 13 }); + dispatchKeydown(link, { key: ' ', keyCode: 32 }); + await Promise.resolve(); + automationService.setUnavailableProviders([{ id: providerId(entries[0]), label: entries[0].name, unavailableReasonCode: 'disconnected' }]); + const singleRemote = container.style.display; + const disabledSettings = []; + for (const setting of settings) { + await setSetting(setting, false); + disabledSettings.push(container.style.display); + await setSetting(setting, true); + } + const restored = container.style.display; + automationService.setUnavailableProviders([{ id: providerId(entries[0]), label: entries[0].name, unavailableReasonCode: 'unsupported' }]); + const unsupported = { control: container.style.display, warning: description.textContent, warningDisplay: description.style.display }; + automationService.setUnavailableProviders([{ id: providerId(entries[0]), label: entries[0].name, unavailableReasonCode: 'disconnected' }]); + automationService.setCatalogueState('ready'); + assert.deepStrictEqual({ + initial, singleRemote, disabledSettings, restored, unsupported, ready: container.style.display, + sameLink: container.querySelector('.monaco-link') === link, + commands: commandService.calls.map(call => call.commandId), + }, { + initial: { + display: '', label: 'Manage Remotes', role: 'button', tabIndex: 0, + count: '0/2 remotes detected', ariaLabel: '0/2 remotes detected, Manage Remotes', + children: ['automations-manage-remotes-count', 'monaco-link'], disconnectedWarningDisplay: 'none', + }, + singleRemote: '', disabledSettings: ['none', 'none', 'none'], restored: '', ready: 'none', + unsupported: { control: 'none', warning: 'Automations are not supported on Host 1.', warningDisplay: '' }, + sameLink: true, + commands: [OPEN_REMOTES_EDITOR_COMMAND_ID, OPEN_REMOTES_EDITOR_COMMAND_ID, OPEN_REMOTES_EDITOR_COMMAND_ID], + }); + }); + test(`groups unavailable providers into visual and accessible bullet lists ${hasSavedAutomations ? 'with' : 'without'} saved automations`, () => { const { automationService, widget } = setup(); const automations = hasSavedAutomations ? [automation()] : []; @@ -2748,7 +3336,7 @@ suite('AutomationsCardsWidget', () => { ]; automationService.setUnavailableProviders(providers); automationService.setCatalogueState('unavailable'); - const selector = hasSavedAutomations ? '.automations-cards-partial-state-message' : '.automations-cards-unavailable .automations-cards-state-description'; + const selector = hasSavedAutomations ? '.automations-cards-partial-state-message' : '.automations-cards-unavailable-message'; const description = widget.element.querySelector(selector)!; const reasons = [ 'The agent host is disconnected on Host 1, Host 3.', @@ -2785,6 +3373,184 @@ suite('AutomationsCardsWidget', () => { }); } + test('preserves local disconnected and generic unavailable warnings', async () => { + const { automationService, configurationService, remoteAgentHostService, widget } = setup(); + for (const setting of [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]) { + await configurationService.setUserConfiguration(setting, true); + } + const remote = tunnelEntry('Remote host', 'remote'); + remoteAgentHostService.setConfiguredEntries([remote]); + automationService.setUnavailableProviders([ + { id: providerId(remote), label: remote.name, unavailableReasonCode: 'disconnected' }, + { id: 'local-agent-host', label: 'This Computer', unavailableReasonCode: 'disconnected' }, + ]); + automationService.setCatalogueState('unavailable'); + const warning = widget.element.querySelector('.automations-cards-unavailable-message')!; + const remoteReplaced = { + control: widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes')?.style.display, + warning: warning.textContent, + warningDisplay: warning.style.display, + }; + automationService.setUnavailableProviders([]); + const generic = { warning: warning.textContent, warningDisplay: warning.style.display }; + + assert.deepStrictEqual({ remoteReplaced, generic }, { + remoteReplaced: { + control: '', + warning: 'The agent host is disconnected on This Computer.', + warningDisplay: '', + }, + generic: { + warning: 'Some automations are unavailable.', + warningDisplay: '', + }, + }); + }); + + test('ignores disconnected GitHub Environments and excludes them from the remote count', async () => { + const { automationService, configurationService, instantiationService, missionControlEnvironmentService, remoteAgentHostService, widget } = setup(); + for (const setting of [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]) { + await configurationService.setUserConfiguration(setting, true); + } + const tunnel = tunnelEntry('benbox3', 'benbox3'); + const environment = githubEnvironmentEntry('CPC-bevil', 'environment'); + remoteAgentHostService.setConfiguredEntries([tunnel]); + remoteAgentHostService.setConnections([{ + name: tunnel.name, + address: getEntryAddress(tunnel), + status: RemoteAgentHostConnectionStatus.connected, + }]); + missionControlEnvironmentService.setHosts([{ + id: 'environment', + name: environment.name, + kind: 'user-local', + status: 'offline', + }]); + automationService.setUnavailableProviders([{ + id: providerId(environment), + label: environment.name, + unavailableReasonCode: 'disconnected', + }]); + automationService.setCatalogueState('unavailable'); + + const emptyState = { + controlDisplay: widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes')?.style.display, + count: widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes-count')?.textContent, + warningDisplay: widget.element.querySelector('.automations-cards-unavailable-message')?.style.display, + }; + automationService.setAutomations([automation()]); + const savedState = { + bannerDisplay: widget.element.querySelector('.automations-cards-partial-state')?.style.display, + warningDisplay: widget.element.querySelector('.automations-cards-partial-state-message')?.style.display, + }; + instantiationService.stub(IAgentWorkbenchLayoutService, new class extends mock() { }); + stubSessionsHostLayout(instantiationService); + const accessibleView = AccessibleViewRegistry.getImplementations().find(implementation => implementation.name === 'sessions-automations-view')!; + const accessibleProvider = disposables.add(instantiationService.invokeFunction(accessor => accessibleView.getProvider(accessor))!); + const accessibleContent = accessibleProvider.provideContent(); + + assert.deepStrictEqual({ + emptyState, savedState, accessible: { + includesEnvironment: accessibleContent.includes(environment.name), + includesUnavailable: accessibleContent.includes('Some automations are unavailable.'), + } + }, { + emptyState: { + controlDisplay: 'none', + count: '1/1 remotes detected', + warningDisplay: 'none', + }, + savedState: { + bannerDisplay: 'none', + warningDisplay: 'none', + }, + accessible: { + includesEnvironment: false, + includesUnavailable: false, + }, + }); + }); + + test('updates Manage Remotes detected count for connection and configured-entry changes', async () => { + const { automationService, configurationService, remoteAgentHostService, widget } = setup(); + const settings = [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]; + for (const setting of settings) { + await configurationService.setUserConfiguration(setting, true); + } + configurationService.onDidChangeConfigurationEmitter.fire({ + source: ConfigurationTarget.USER, + affectedKeys: new Set(settings), + change: { keys: settings, overrides: [] }, + affectsConfiguration: key => settings.includes(key), + }); + + const entries = Array.from({ length: 5 }, (_, index) => tunnelEntry(`Host ${index + 1}`, `host-${index + 1}`)); + const githubEnvironment = githubEnvironmentEntry('GitHub Environment', 'environment'); + const connection = (index: number, status: RemoteAgentHostConnectionStatus): IRemoteAgentHostConnectionInfo => ({ + name: entries[index].name, + address: getEntryAddress(entries[index]), + status, + }); + + remoteAgentHostService.setConfiguredEntries([...entries, githubEnvironment]); + remoteAgentHostService.setConnections([ + connection(0, RemoteAgentHostConnectionStatus.connected), + connection(1, RemoteAgentHostConnectionStatus.connected), + connection(2, RemoteAgentHostConnectionStatus.connecting), + connection(3, RemoteAgentHostConnectionStatus.reconnecting), + connection(4, RemoteAgentHostConnectionStatus.disconnected), + ]); + automationService.setUnavailableProviders([{ id: providerId(entries[0]), label: entries[0].name, unavailableReasonCode: 'disconnected' }]); + automationService.setCatalogueState('unavailable'); + + const count = widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes-count'); + const link = widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes .monaco-link'); + assert.ok(count); + assert.ok(link); + + const snapshots: { readonly text: string; readonly ariaLabel: string | null }[] = []; + const snapshot = () => snapshots.push({ text: count.textContent ?? '', ariaLabel: link.getAttribute('aria-label') }); + snapshot(); + + remoteAgentHostService.setConnections([ + connection(0, RemoteAgentHostConnectionStatus.reconnecting), + connection(1, RemoteAgentHostConnectionStatus.connecting), + connection(2, RemoteAgentHostConnectionStatus.disconnected), + ]); + snapshot(); + + remoteAgentHostService.setConnections([connection(0, RemoteAgentHostConnectionStatus.connected)]); + remoteAgentHostService.setConfiguredEntries(entries.slice(0, 4)); + snapshot(); + + remoteAgentHostService.setConfiguredEntries([...entries.slice(0, 4), tunnelEntry('Host 6', 'host-6'), githubEnvironment]); + snapshot(); + + assert.deepStrictEqual(snapshots, [ + { text: '2/5 remotes detected', ariaLabel: '2/5 remotes detected, Manage Remotes' }, + { text: '0/5 remotes detected', ariaLabel: '0/5 remotes detected, Manage Remotes' }, + { text: '1/4 remotes detected', ariaLabel: '1/4 remotes detected, Manage Remotes' }, + { text: '1/5 remotes detected', ariaLabel: '1/5 remotes detected, Manage Remotes' }, + ]); + }); + + test('reports Manage Remotes command failures', async () => { + const { automationService, widget, configurationService, commandService, refreshErrors, remoteAgentHostService } = setup(); + for (const setting of [RemoteAgentHostsEnabledSettingId, ENVIRONMENT_PICKER_SETTING, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]) { + await configurationService.setUserConfiguration(setting, true); + } + const entry = tunnelEntry('Host 1', 'host-1'); + remoteAgentHostService.setConfiguredEntries([entry]); + automationService.setUnavailableProviders([{ id: providerId(entry), label: entry.name, unavailableReasonCode: 'disconnected' }]); + automationService.setCatalogueState('unavailable'); + const failure = new Error('Remote Environments could not be opened'); + const stubbedCommand = stub(commandService, 'executeCommand').rejects(failure); + disposables.add(toDisposable(() => stubbedCommand.restore())); + widget.element.querySelector('.automations-cards-unavailable .automations-manage-remotes .monaco-link')!.click(); + await Promise.resolve(); + assert.deepStrictEqual(refreshErrors, [String(failure)]); + }); + test('collapses built-in templates when saved automations become available', () => { const { automationService, widget } = setup(); @@ -2833,25 +3599,39 @@ suite('AutomationsCardsWidget', () => { test('card keyboard focus exposes the full current prompt without changing pointer hover targets', () => { const shown: string[] = []; - let target: HTMLElement | undefined; + const focusTargets: string[] = []; + let pointerTarget: HTMLElement | undefined; let hidden = 0; - let disposed = false; + let pointerDisposed = false; + let focusDisposed = 0; const hoverService: IHoverService = { ...NullHoverService, setupManagedHover: (delegate, element, content, options) => { if (!element.classList.contains('automations-card-prompt')) { return NullHoverService.setupManagedHover(delegate, element, content, options); } - target = element; + pointerTarget = element; return { - show: () => { - const value = typeof content === 'function' ? content() : content; - assert.ok(typeof value === 'string'); - shown.push(value); - }, + show: () => { }, hide: () => { hidden++; }, update: () => { }, - dispose: () => { disposed = true; }, + dispose: () => { pointerDisposed = true; }, + }; + }, + showInstantHover: options => { + assert.ok(options.target instanceof HTMLElement); + assert.ok(typeof options.content === 'string'); + focusTargets.push(options.target.className); + shown.push(options.content); + let isDisposed = false; + return { + get isDisposed() { return isDisposed; }, + dispose: () => { + if (!isDisposed) { + isDisposed = true; + focusDisposed++; + } + }, }; }, }; @@ -2873,12 +3653,14 @@ suite('AutomationsCardsWidget', () => { main.dispatchEvent(new FocusEvent('blur')); widget.dispose(); assert.deepStrictEqual({ - target: target?.className, shown, hidden, disposed, + pointerTarget: pointerTarget?.className, focusTargets, shown, hidden, pointerDisposed, focusDisposed, }, { - target: 'automations-card-prompt', + pointerTarget: 'automations-card-prompt', + focusTargets: ['automations-card-prompt', 'automations-card-prompt'], shown: [prompt, `${prompt}Updated.`], hidden: 2, - disposed: true, + pointerDisposed: true, + focusDisposed: 2, }); }); @@ -3719,6 +4501,36 @@ suite('AutomationsCardsWidget', () => { }); }); + test('disabling a shared automation warns that the change affects other users', async () => { + const { automationService, dialogService, instantiationService } = setup(); + const source = automation({ ownership: 'repository' }); + automationService.setAutomations([source]); + const command = CommandsRegistry.getCommand('sessions.automations.disable'); + assert.ok(command); + + await instantiationService.invokeFunction(accessor => command.handler(accessor, source)); + dialogService.confirmResult = { confirmed: true }; + await instantiationService.invokeFunction(accessor => command.handler(accessor, source)); + + assert.deepStrictEqual({ + confirmations: dialogService.confirmations, + updateCalls: automationService.guardedUpdateCalls, + }, { + confirmations: [{ + type: 'warning', + message: 'Disable automation "Daily review"?', + detail: 'WARNING: This is a shared automation, this will disable it for everyone in this repository.', + primaryButton: 'Disable', + }, { + type: 'warning', + message: 'Disable automation "Daily review"?', + detail: 'WARNING: This is a shared automation, this will disable it for everyone in this repository.', + primaryButton: 'Disable', + }], + updateCalls: [{ id: source.id, patch: { enabled: false }, expected: source }], + }); + }); + test('disable conflicts are logged and reported to the user', async () => { const { automationService, dialogService, instantiationService, logService } = setup(); const source = automation(); @@ -3761,7 +4573,7 @@ suite('AutomationsCardsWidget', () => { }]); }); - test('capable providers offer keeping history with its accessible owner name', async () => { + test('capable providers always delete all history without offering a choice', async () => { const { automationService, dialogService, instantiationService } = setup(); const source = automation(); automationService.setAutomations([source]); @@ -3771,23 +4583,34 @@ suite('AutomationsCardsWidget', () => { const command = CommandsRegistry.getCommand('sessions.automations.delete'); assert.ok(command); await instantiationService.invokeFunction(accessor => command.handler(accessor, source)); - const accessible = buildAutomationsAccessibleContent([], automationService.runs.get(), 'ready', [], [], 'ready', [], () => source.name, () => 'retained', () => true); assert.deepStrictEqual({ - checkbox: dialogService.confirmations[0].checkbox, + confirmation: dialogService.confirmations[0], options: automationService.deleteOptions, runs: automationService.runs.get().length, - accessible: { - owner: accessible.includes('Daily review,'), - retained: accessible.includes('Run history for Daily review is retained. Use the run context menu to delete it.'), - }, }, { - checkbox: { label: 'Delete Run History', checked: true }, - options: [{ deleteHistory: false }], - runs: 1, - accessible: { owner: true, retained: true }, + confirmation: { + type: 'warning', + message: 'Delete automation "Daily review"?', + detail: 'This will permanently delete the automation, its run history, and the associated sessions. This cannot be undone.', + primaryButton: 'Delete', + }, + options: [{ deleteHistory: true }], + runs: 0, }); }); + test('previously retained history keeps its accessible owner and deletion guidance', () => { + const { automationService } = setup(); + automationService.setRuns([run()]); + const accessible = buildAutomationsAccessibleContent([], automationService.runs.get(), 'ready', [], [], 'ready', [], () => 'Daily review', () => 'retained', () => true); + assert.deepStrictEqual({ + owner: accessible.includes('Daily review,'), + retained: accessible.includes('Run history for Daily review is retained. Use the run context menu to delete it.'), + runs: automationService.runs.get().length, + deleteCalls: automationService.deleteCalls, + }, { owner: true, retained: true, runs: 1, deleteCalls: [] }); + }); + test('delete context menu action confirms before deleting the automation and its history', async () => { const { automationService, contextMenuService, dialogService, instantiationService, widget } = setup(); const source = automation(); @@ -3808,12 +4631,14 @@ suite('AutomationsCardsWidget', () => { runs: automationService.runs.get(), }, { confirmations: [{ + type: 'warning', message: 'Delete automation "Daily review"?', - detail: 'This will permanently delete the automation and its run history.', + detail: 'This will permanently delete the automation, its run history, and the associated sessions. This cannot be undone.', primaryButton: 'Delete', }, { + type: 'warning', message: 'Delete automation "Daily review"?', - detail: 'This will permanently delete the automation and its run history.', + detail: 'This will permanently delete the automation, its run history, and the associated sessions. This cannot be undone.', primaryButton: 'Delete', }], deleteCalls: [source.id], @@ -3822,6 +4647,30 @@ suite('AutomationsCardsWidget', () => { }); }); + test('deleting a shared automation warns that the change affects other users', async () => { + const { automationService, dialogService, instantiationService } = setup(); + const source = automation({ ownership: 'repository' }); + automationService.setAutomations([source]); + dialogService.confirmResult = { confirmed: true }; + const command = CommandsRegistry.getCommand('sessions.automations.delete'); + assert.ok(command); + + await instantiationService.invokeFunction(accessor => command.handler(accessor, source)); + + assert.deepStrictEqual({ + confirmation: dialogService.confirmations[0], + deleteCalls: automationService.deleteCalls, + }, { + confirmation: { + type: 'warning', + message: 'Delete automation "Daily review"?', + detail: 'WARNING: This is a shared automation, this will delete it for everyone in this repository.\n\nThis will permanently delete the automation, its run history, and the associated sessions. This cannot be undone.', + primaryButton: 'Delete', + }, + deleteCalls: [source.id], + }); + }); + test('delete context menu action is disabled when deletion is unsupported', async () => { const { automationService, contextKeyService, contextMenuService, dialogService, instantiationService, widget } = setup(); automationService.canDelete = false; @@ -4662,6 +5511,74 @@ suite('AutomationsCardsWidget', () => { ); }); + test('accessible view reports unresolved local startup on the card without a history row', () => { + const { automationService, sessionsManagementService, instantiationService } = setup(); + instantiationService.stub(IAgentWorkbenchLayoutService, new class extends mock() { }); + stubSessionsHostLayout(instantiationService); + const accessibleView = AccessibleViewRegistry.getImplementations().find(implementation => implementation.name === 'sessions-automations-view'); + if (!accessibleView) { + throw new Error('Expected the sessions automations accessible view'); + } + const accessibleProvider = instantiationService.invokeFunction(accessor => accessibleView.getProvider(accessor)); + if (!accessibleProvider) { + throw new Error('Expected the sessions automations accessible view provider'); + } + disposables.add(accessibleProvider); + automationService.setAutomations([ + automation(), + automation({ id: 'disabled', name: 'Disabled review', enabled: false }), + ]); + automationService.setRuns([ + run({ status: 'pending', sessionResource: undefined }), + run({ id: 'disabled-run', automationId: 'disabled', status: 'pending', sessionResource: undefined }), + ]); + let sessionCatalogReads = 0; + sessionsManagementService.onGetSessions = () => sessionCatalogReads++; + + const content = accessibleProvider.provideContent(); + + assert.deepStrictEqual({ + enabledCardRunning: content.includes('Daily review, enabled, Running'), + disabledCardRunning: content.includes('Disabled review, disabled, Running'), + historyRun: content.includes('Daily review, Pending, started'), + sessionCatalogReads, + }, { + enabledCardRunning: true, + disabledCardRunning: true, + historyRun: false, + sessionCatalogReads: 1, + }); + }); + + test('accessible view preserves retained history while its completed session is not cataloged', () => { + const { automationService, sessionsManagementService, instantiationService } = setup(); + instantiationService.stub(IAgentWorkbenchLayoutService, new class extends mock() { }); + stubSessionsHostLayout(instantiationService); + const accessibleView = AccessibleViewRegistry.getImplementations().find(implementation => implementation.name === 'sessions-automations-view'); + if (!accessibleView) { + throw new Error('Expected the sessions automations accessible view'); + } + const accessibleProvider = instantiationService.invokeFunction(accessor => accessibleView.getProvider(accessor)); + if (!accessibleProvider) { + throw new Error('Expected the sessions automations accessible view provider'); + } + disposables.add(accessibleProvider); + automationService.historyStates.set('automation-1', 'retained'); + automationService.setAutomations([]); + automationService.setRuns([run({ status: 'completed', sessionResource: SESSION_RESOURCE })]); + sessionsManagementService.setFirstSessionCataloged(false); + + const content = accessibleProvider.provideContent(); + + assert.deepStrictEqual({ + owner: content.includes('Daily review, Completed, started'), + guidance: content.includes('Run history for Daily review is retained. Use the run context menu to delete it.'), + }, { + owner: true, + guidance: true, + }); + }); + test('accessible local progress clears stale descriptions only while active', () => { const external = run({ status: 'failed', updatedAt: '2026-01-01T00:00:00Z', @@ -4833,6 +5750,19 @@ suite('AutomationsCardsWidget', () => { assert.ok(provider); disposables.add(provider); assert.ok(provider.provideContent().includes('When creating an automation, you only need to enter a prompt. An empty name is derived from the prompt, and the target defaults to No workspace unless one is already supplied. An available Agent Host that supports the target is still required.')); + assert.deepStrictEqual(provider.provideContent().split('\n').filter(line => line.startsWith('Create with Agent')), [ + 'Create with Agent opens a new session with /automate prefilled and the input focused. This button is in the empty state, or in the view header once automations exist. Choose Create Manually from its adjacent More Actions dropdown to open the automation dialog. In the header, use Left Arrow and Right Arrow to move between the button and dropdown; in the empty state, use Tab and Shift+Tab. Press Enter or Space to activate either control. Create Manually remains available while chat is not ready.', + ]); + assert.ok(provider.provideContent().includes('Existing attachments are kept. Choose View Draft to return to the new session page without changing the draft, or Cancel to stay in Automations.')); + }); + + test('accessibility help explains the disconnected remote management link', () => { + const { instantiationService } = setup(); + instantiationService.stub(IAgentWorkbenchLayoutService, new class extends mock() { }); + stubSessionsHostLayout(instantiationService); + const help = AccessibleViewRegistry.getImplementations().find(implementation => implementation.name === 'sessions-automations-help')!; + const provider = disposables.add(instantiationService.invokeFunction(accessor => help.getProvider(accessor))!); + assert.ok(provider.provideContent().includes('the unavailable message shows how many dev tunnels are detected followed by Manage Remotes. Tab to this link and press Enter or Space to open Remote Environments, where you can manage dev tunnels. GitHub Environments do not appear in Automations warnings or this count.')); }); test('accessibility help explains showing run sessions in the Sessions list', () => { diff --git a/src/vs/sessions/contrib/sessions/test/browser/customizationsToolbar.test.ts b/src/vs/sessions/contrib/sessions/test/browser/customizationsToolbar.test.ts index 9b5e00c9d1ab..0902bb276930 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/customizationsToolbar.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/customizationsToolbar.test.ts @@ -56,6 +56,8 @@ import { IAgentsWindowExtensionSuggestionsService } from '../../../../../workben import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; import { focusedSessionHostServiceOf, ITestSessionWithChat } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { ChatCustomizationsTelemetry } from '../../../../../workbench/contrib/chat/browser/aiCustomization/chatCustomizationsTelemetry.js'; function createExtensionSuggestionsService(showBadge: IObservable): IAgentsWindowExtensionSuggestionsService { return new class extends mock() { @@ -67,6 +69,14 @@ suite('Customizations toolbar', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); const copilotCliToolCount = [...getCopilotCliBuiltinToolSet().getTools()].length; + function telemetryInstantiationService(onActivation: () => void = () => { }) { + const instantiationService = workbenchInstantiationService({}, disposables); + instantiationService.stubInstance(ChatCustomizationsTelemetry, new class extends mock() { + override logInteraction() { onActivation(); } + }); + return instantiationService; + } + test('does not include standalone Remotes management in Customizations', () => { assert.ok(CUSTOMIZATION_ITEMS.every(item => item.id !== 'sessions.customization.remotes')); }); @@ -156,6 +166,7 @@ suite('Customizations toolbar', () => { override getActiveDescriptor() { return upcastPartial({ hiddenSections: [] }); } }, disposables.add(new MockContextKeyService()), + new TestConfigurationService(), )); const palette = MenuRegistry.getMenuItems(MenuId.CommandPalette).filter(isIMenuItem).find(item => item.command.id === EXTENSIONS_VIEWLET_ID); const keybinding = keybindingsOnLoad[0]; @@ -212,6 +223,7 @@ suite('Customizations toolbar', () => { override getActiveDescriptor() { return upcastPartial({ hiddenSections: activeHarness.get() === 'vscode' ? [] : [AICustomizationManagementSection.Extensions] }); } }, contextKeyService, + configurationService, )); // As the Keyboard Shortcuts editor of editor windows writes them, scoped to the Extensions view container's enablement like the default keybinding there. @@ -399,19 +411,21 @@ suite('Customizations toolbar', () => { test('renders one focus target and runs its action once', async () => { let runCount = 0; + let activationCount = 0; const action = disposables.add(new Action('test.customization', 'Customization', undefined, true, () => { runCount++; })); const item = disposables.add(new CustomizationLinkViewItem( action, {}, - { id: 'test.customization', label: 'Customization', icon: Codicon.settingsGear }, + { id: 'sessions.customization.overview', label: 'Customization', icon: Codicon.settingsGear }, new class extends mock() { }, new class extends mock() { }, new class extends mock() { }, new class extends mock() { }, createExtensionSuggestionsService(constObservable(false)), NullHoverService, + telemetryInstantiationService(() => activationCount++), )); const container = mainWindow.document.createElement('div'); item.render(container); @@ -423,10 +437,12 @@ suite('Customizations toolbar', () => { buttonCount: container.querySelectorAll('.customization-link-button').length, focusableCount: container.querySelectorAll('a, button').length, runCount, + activationCount, }, { buttonCount: 1, focusableCount: 1, runCount: 1, + activationCount: 1, }); }); @@ -450,6 +466,7 @@ suite('Customizations toolbar', () => { new class extends mock() { }, createExtensionSuggestionsService(showBadge), hoverService, + telemetryInstantiationService(), )); const container = mainWindow.document.createElement('div'); item.render(container); @@ -486,6 +503,7 @@ suite('Customizations toolbar', () => { new class extends mock() { }, createExtensionSuggestionsService(constObservable(false)), NullHoverService, + telemetryInstantiationService(), ); const actionBar = disposables.add(new ActionBar(container, { actionViewItemProvider: action => createViewItem(action), diff --git a/src/vs/sessions/contrib/sessions/test/browser/pendingSessionsList.test.ts b/src/vs/sessions/contrib/sessions/test/browser/pendingSessionsList.test.ts new file mode 100644 index 000000000000..97da3342efa4 --- /dev/null +++ b/src/vs/sessions/contrib/sessions/test/browser/pendingSessionsList.test.ts @@ -0,0 +1,383 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { IContextMenuDelegate } from '../../../../../base/browser/contextmenu.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { IAction, toAction } from '../../../../../base/common/actions.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { getComparisonKey } from '../../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { IListService, ListService } from '../../../../../platform/list/browser/listService.js'; +import '../../../../../workbench/browser/actions/listCommands.js'; +import { ISessionsListModelService, SessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; +import { IPendingSessionItem, IPendingSessionSection } from '../../../../../workbench/contrib/sessions/browser/views/pendingSessions.js'; +import { SessionsGrouping, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; +import { TestSessionsList } from '../../../../../workbench/contrib/sessions/test/browser/views/testSessionsList.js'; +import { createListHarness, createTestSession, IListHarness } from './sessionsListTestUtils.js'; + +suite('Sessions - pending list items', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function item(id: string, options: Partial = {}): IPendingSessionItem { + return { + pendingSession: true, id, kind: 'draft', title: id, description: 'Unsent request', + providerId: 'test', sessionType: 'copilot', harness: 'copilot', environmentId: 'local', applicationId: 'vscode', + actions: [], open: async () => { }, ...options, + }; + } + + function openFocusedItem(harness: IListHarness, list: TestSessionsList): void { + list.focus(); + if (!mainWindow.document.hasFocus()) { + list.element.querySelector('.monaco-list')!.dispatchEvent(new FocusEvent('focus')); + } + harness.instantiationService.invokeFunction(CommandsRegistry.getCommand('list.select')!.handler); + } + + for (const grouping of [SessionsGrouping.Workspace, SessionsGrouping.Repository, SessionsGrouping.Environment, SessionsGrouping.Date, SessionsGrouping.Inbox]) { + test(`drafts and new-session schedules share Drafts after Pinned in ${grouping}`, () => { + const pinned = createTestSession('pinned').session; + const regular = createTestSession('regular').session; + const harness = createListHarness(disposables, [pinned, regular], { pinnedSessionIds: new Set(['pinned']) }); + if (grouping === SessionsGrouping.Inbox) { + const model = disposables.add(harness.instantiationService.createInstance(SessionsListModelService)); + harness.instantiationService.stub(ISessionsListModelService, model); + model.pinSession(pinned); + } + const pendingSections = observableValue('pending', [ + { id: 'drafts', label: 'Drafts', items: [item('z-draft'), item('a-draft')] }, + ]); + const scheduledSessions = observableValue('scheduled', [item('send-later', { kind: 'scheduled' })]); + const create = () => disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => grouping, sorting: () => SessionsSorting.Updated, pendingSections, + scheduledSessions, onSessionOpen: () => { }, + })); + const list = create(); + list.layout(800, 400); + const initialSection = list.getTreeSnapshot().find(node => node.type === 'section' && node.id === 'drafts'); + const count = list.getItemRow({ section: 'drafts' })!.querySelector('.session-section-count')!; + const initial = { collapsed: initialSection?.type === 'section' && initialSection.collapsed, count: count.textContent, countVisible: mainWindow.getComputedStyle(count).display !== 'none' }; + list.setItemCollapsed({ section: 'drafts' }, false); + const expandedSection = create().getTreeSnapshot().find(node => node.type === 'section' && node.id === 'drafts'); + const headers = list.getTreeSnapshot().flatMap(node => node.type === 'section' ? [node.id] : []).slice(0, 2); + const scheduledRow = !!list.getItemRow({ pendingSession: 'send-later' }); + const draftTitles = [...list.element.querySelectorAll('.session-title')].map(element => element.textContent).filter(title => title?.endsWith('-draft')); + list.setItemCollapsed({ section: 'drafts' }, true); + const scheduledCollapsed = !list.getItemRow({ pendingSession: 'send-later' }); + pendingSections.set([], undefined); + const scheduledOnlySection = list.getTreeSnapshot().some(node => node.type === 'section' && node.id === 'drafts'); + scheduledSessions.set([], undefined); + list.update(); + const empty = list.getTreeSnapshot().filter(node => node.type !== 'session').map(node => node.id); + pendingSections.set([{ id: 'drafts', label: 'Drafts', items: [item('reappeared')] }], undefined); + const restored = create(); + const restoredSection = restored.getTreeSnapshot().find(node => node.type !== 'session' && node.id === 'drafts'); + assert.deepStrictEqual({ + initial, expandedRestored: expandedSection?.type === 'section' && !expandedSection.collapsed, + headers, draftTitles, scheduledRow, scheduledCollapsed, scheduledOnlySection, + emptyHasPending: empty.includes('drafts') || empty.includes('scheduled'), + restoredCollapsed: restoredSection?.type === 'section' && restoredSection.collapsed, + }, { initial: { collapsed: true, count: '3', countVisible: true }, expandedRestored: true, headers: ['pinned', 'drafts'], draftTitles: ['z-draft', 'a-draft'], scheduledRow: true, scheduledCollapsed: true, scheduledOnlySection: true, emptyHasPending: false, restoredCollapsed: true }); + }); + } + + test('scheduled-only Drafts retains schedule metadata and works without ordinary saved drafts', () => { + const harness = createListHarness(disposables, []); + const pendingSections = observableValue('drafts', [ + { id: 'drafts', label: 'Drafts', items: [item('ordinary-draft')] }, + ]); + const scheduledSessions = observableValue('scheduled', [ + item('Follow up', { kind: 'scheduled', folderUri: URI.file('/workspace/vscode'), description: 'Scheduled for tomorrow at 10:00 AM' }), + ]); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + pendingSections, scheduledSessions, schedulingEnabled: constObservable(true), onSessionOpen: () => { }, + })); + list.layout(800, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + list.filters.setScheduledOnly(true); + const row = list.getItemRow({ pendingSession: 'Follow up' })!; + const filtered = { + draftHidden: !list.getItemRow({ pendingSession: 'ordinary-draft' }), + description: row.querySelector('.session-details-row')?.textContent, + clock: mainWindow.getComputedStyle(row.querySelector('.session-scheduled-indicator')!).display, + ariaLabel: row.getAttribute('aria-label'), + }; + pendingSections.set([], undefined); + const schedulesWithoutSavedDrafts = [...list.element.querySelectorAll('.session-section-label')].map(element => element.textContent); + scheduledSessions.set([], undefined); + list.update(); + assert.deepStrictEqual({ + filtered, schedulesWithoutSavedDrafts, + emptySections: list.element.querySelectorAll('.session-section-label').length, + }, { + filtered: { + draftHidden: true, description: 'vscode - Scheduled for tomorrow at 10:00 AM', clock: 'flex', + ariaLabel: 'Follow up, scheduled, vscode - Scheduled for tomorrow at 10:00 AM', + }, + schedulesWithoutSavedDrafts: ['Drafts'], emptySections: 0, + }); + }); + + test('omitting pending input leaves normal row dispatch and session inventory unchanged', async () => { + const session = createTestSession('normal').session; + const harness = createListHarness(disposables, [session]); + harness.instantiationService.stub(IListService, disposables.add(new ListService())); + const opened: string[] = []; + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + onSessionOpen: resource => { opened.push(resource.toString()); }, + })); + list.layout(400, 400); + list.setFocusedItem({ session: session.resource }); + openFocusedItem(harness, list); + await timeout(0); + assert.deepStrictEqual({ + opened, inventory: list.getVisibleSessions().map(session => session.sessionId), + pending: list.getTreeSnapshot().some(node => node.type === 'section' && (node.id === 'drafts' || node.id === 'scheduled')), + }, { opened: [session.resource.toString()], inventory: ['normal'], pending: false }); + }); + + for (const indentItems of [false, true]) { + test(`draft and scheduled rows use normal session dots and indentation with indentItems=${indentItems}`, () => { + const session = createTestSession('normal').session; + const harness = createListHarness(disposables, [session], instantiationService => { + instantiationService.stub(IConfigurationService, new TestConfigurationService({ 'sessions.list.indentItems': indentItems })); + }); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + pendingSections: constObservable([ + { id: 'drafts', label: 'Drafts', items: [item('draft')] }, + ]), scheduledSessions: constObservable([item('scheduled', { kind: 'scheduled' })]), onSessionOpen: () => { }, + })); + list.layout(800, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + const draft = list.getItemRow({ pendingSession: 'draft' })!.querySelector('.session-item')!; + for (const size of [2, 6, 16]) { + list.element.style.setProperty(`--vscode-spacing-size${size * 10}`, `${size}px`); + } + const normal = list.getItemRow({ session: session.resource })!.querySelector('.session-item')!; + const scheduled = list.getItemRow({ pendingSession: 'scheduled' })!.querySelector('.session-item')!; + const appearance = (element: HTMLElement) => ({ + icon: element.querySelector('.session-icon > span')?.className, + indent: mainWindow.getComputedStyle(element).marginLeft, + }); + assert.deepStrictEqual([appearance(draft), appearance(scheduled)], [appearance(normal), appearance(normal)]); + }); + } + + test('keyboard opens pending items without normal session actions, and context actions disable for multi-select', async () => { + const harness = createListHarness(disposables, []); + harness.instantiationService.stub(IListService, disposables.add(new ListService())); + let actions: readonly IAction[] = []; + harness.instantiationService.stub(IContextMenuService, new class extends mock() { + override showContextMenu(delegate: IContextMenuDelegate): void { actions = delegate.getActions(); } + }); + const opened: string[] = []; + let discarded = 0; + const first = item('first', { + open: async () => { opened.push('pending'); }, + actions: [toAction({ id: 'discard', label: 'Discard Draft', run: () => { discarded++; } })], + }); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + pendingSections: constObservable([{ id: 'drafts', label: 'Drafts', items: [first, item('second')] }]), + onSessionOpen: () => { opened.push('session'); }, + })); + list.layout(400, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + list.setFocusedItem({ pendingSession: 'first' }); + openFocusedItem(harness, list); + const tree = list.element.querySelector('.monaco-list')!; + await timeout(0); + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'F10', keyCode: 121, shiftKey: true, bubbles: true })); + tree.dispatchEvent(new KeyboardEvent('keyup', { key: 'F10', keyCode: 121, shiftKey: true, bubbles: true })); + const single = actions.map(action => [action.id, action.enabled]); + await actions[0]?.run(); + list.setSelectedItems([{ pendingSession: 'first' }, { pendingSession: 'second' }]); + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'F10', keyCode: 121, shiftKey: true, bubbles: true })); + tree.dispatchEvent(new KeyboardEvent('keyup', { key: 'F10', keyCode: 121, shiftKey: true, bubbles: true })); + const multiple = actions.map(action => [action.id, action.enabled]); + await actions[0]?.run(); + const row = list.getItemRow({ pendingSession: 'first' }); + assert.deepStrictEqual({ + opened, single, multiple, discarded, + draggable: row?.draggable, normalInventory: list.getVisibleSessions(), + focusedSessions: list.getFocusedSessions(), + ariaLabel: row?.getAttribute('aria-label'), + }, { + opened: ['pending'], single: [['discard', true]], multiple: [['discard', false]], discarded: 1, + draggable: false, normalInventory: [], focusedSessions: [], + ariaLabel: 'first, draft, Unsent request', + }); + }); + + test('drafts expose only Delete as a focus-revealed inline action without opening the row', async () => { + const harness = createListHarness(disposables, []); + const invoked: string[] = []; + const draft = item('draft', { + open: async () => { invoked.push('open'); }, + actions: [ + toAction({ id: 'sessions.drafts.resume', label: 'Resume Draft', class: ThemeIcon.asClassName(Codicon.play), run: () => { invoked.push('resume'); } }), + toAction({ id: 'sessions.drafts.delete', label: 'Delete Draft', class: ThemeIcon.asClassName(Codicon.trash), run: () => { invoked.push('delete'); } }), + ], + }); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + pendingSections: constObservable([{ id: 'drafts', label: 'Drafts', items: [draft] }]), + onSessionOpen: () => { invoked.push('session'); }, + })); + list.layout(400, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + const row = list.getItemRow({ pendingSession: 'draft' })!; + const toolbar = row.querySelector('.session-title-toolbar')!; + const resting = mainWindow.getComputedStyle(toolbar).display; + list.setFocusedItem({ pendingSession: 'draft' }); + const focused = mainWindow.getComputedStyle(toolbar).display; + const actions = [...toolbar.querySelectorAll('.action-label')]; + actions.forEach(action => action.click()); + await timeout(0); + assert.deepStrictEqual({ + resting, focused, invoked, + labels: actions.map(action => action.getAttribute('aria-label')), + icons: actions.map(action => ['codicon-play', 'codicon-trash'].filter(icon => action.classList.contains(icon))), + overflow: !!toolbar.querySelector('.codicon-ellipsis'), + }, { + resting: 'none', focused: 'block', invoked: ['delete'], + labels: ['Delete Draft'], icons: [['codicon-trash']], overflow: false, + }); + }); + + test('pending search matches descriptions and workspace paths without leaving empty sections', async () => { + const harness = createListHarness(disposables, []); + const container = harness.createContainer(); + const findWidgetContainer = append(container, $('div')); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, container, { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, findWidgetContainer, + pendingSections: constObservable([ + { id: 'drafts', label: 'Drafts', items: [item('Fix layout', { folderUri: URI.file('/workspace/editor'), description: 'Tomorrow afternoon' })] }, + ]), + scheduledSessions: constObservable([item('Other task', { kind: 'scheduled' })]), + onSessionOpen: () => { }, + })); + list.layout(600, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + list.openFind(); + const input = findWidgetContainer.querySelector('input')!; + input.value = 'editor tomorrow'; + input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + const matching = { + titles: [...list.element.querySelectorAll('.session-title')].map(element => element.textContent), + headers: [...list.element.querySelectorAll('.session-section-label')].map(element => element.textContent), + }; + input.value = 'unmatched'; + input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + const unmatched = list.element.querySelectorAll('.session-section-label').length; + list.closeFind(); + await timeout(350); + assert.deepStrictEqual({ matching, unmatched }, { matching: { titles: ['Fix layout'], headers: ['Drafts'] }, unmatched: 0 }); + }); + + test('revealing a draft expands its section and selects it without taking composer focus', () => { + const harness = createListHarness(disposables, []); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + pendingSections: constObservable([{ id: 'drafts', label: 'Drafts', items: [item('draft')] }]), + onSessionOpen: () => { }, + })); + list.layout(800, 400); + const input = append(list.element.parentElement!, $('input')); + input.focus(); + const revealed = list.revealPendingSession('draft'); + const row = list.getItemRow({ pendingSession: 'draft' }); + assert.deepStrictEqual({ + revealed, selected: row?.getAttribute('aria-selected'), + focused: row?.classList.contains('focused'), inputFocused: mainWindow.document.activeElement === input, + }, { revealed: true, selected: 'true', focused: true, inputFocused: true }); + }); + + test('scheduled filtering and indicators update without duplicating conversations or affecting the disabled feature', () => { + const scheduled = createTestSession('scheduled').session; + const normal = createTestSession('normal').session; + const harness = createListHarness(disposables, [scheduled, normal]); + const schedulingEnabled = observableValue('enabled', true); + const scheduledSessionResources = observableValue>('scheduled resources', new Set([scheduled.resource.toString()])); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => SessionsGrouping.Date, sorting: () => SessionsSorting.Created, + schedulingEnabled, scheduledSessionResources, + pendingSections: constObservable([{ id: 'drafts', label: 'Drafts', items: [item('draft')] }]), + onSessionOpen: () => { }, + })); + list.layout(800, 400); + const row = list.getItemRow({ session: scheduled.resource })!; + const indicator = row.querySelector('.session-scheduled-indicator')!; + const before = { indicator: mainWindow.getComputedStyle(indicator).display, aria: row.getAttribute('aria-label')?.includes('has scheduled messages') }; + row.classList.add('hovered'); + const hovered = mainWindow.getComputedStyle(indicator).display; + row.classList.remove('hovered'); + list.filters.setScheduledOnly(true); + const filtered = list.getVisibleSessions().map(session => session.sessionId); + const draftHidden = !list.getItemRow({ pendingSession: 'draft' }); + scheduledSessionResources.set(new Set(), undefined); + list.update(); + const afterDispatch = list.getVisibleSessions().map(session => session.sessionId); + schedulingEnabled.set(false, undefined); + list.update(); + assert.deepStrictEqual({ + before, hovered, filtered, draftHidden, afterDispatch, + disabled: list.getVisibleSessions().map(session => session.sessionId).sort(), + indicatorHidden: mainWindow.getComputedStyle(list.getItemRow({ session: scheduled.resource })!.querySelector('.session-scheduled-indicator')!).display, + }, { + before: { indicator: 'flex', aria: true }, hovered: 'none', filtered: ['scheduled'], draftHidden: true, afterDispatch: [], + disabled: ['normal', 'scheduled'], indicatorHidden: 'none', + }); + }); + + test('pending filtering composes harness, environment and application with strict Inbox workspace scope', () => { + const harness = createListHarness(disposables, []); + let grouping = SessionsGrouping.Workspace; + const folder = URI.file('/work/project'); + const drafts = [ + item('local', { folderUri: folder }), + item('remote', { folderUri: folder, environmentId: 'remote' }), + item('claude', { folderUri: folder, harness: 'claude' }), + item('external', { folderUri: folder, applicationId: 'cli' }), + item('no-workspace', { isQuickChat: true }), + item('unknown-workspace'), + ]; + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => grouping, sorting: () => SessionsSorting.Created, + pendingSections: constObservable([{ id: 'drafts', label: 'Drafts', items: drafts }]), onSessionOpen: () => { }, + })); + list.layout(800, 400); + list.setItemCollapsed({ section: 'drafts' }, false); + const visible = () => drafts.filter(item => !!list.getItemRow({ pendingSession: item.id })).map(item => item.id); + list.filters.setExcluded({ kind: 'harness', id: 'claude' }, true); + list.filters.setExcluded({ kind: 'environment', id: 'remote' }, true); + const ordinary = visible(); + grouping = SessionsGrouping.Inbox; + list.filters.setInboxWorkspace({ environment: 'remote', resource: getComparisonKey(folder), label: 'Project' }); + const inbox = visible(); + list.filters.setInboxEnvironment({ id: 'local', label: 'Local' }); + list.filters.setInboxWorkspace('none'); + const noWorkspace = visible(); + list.filters.setInboxWorkspace({ environment: 'missing', resource: getComparisonKey(folder), label: 'Missing host' }); + const unavailable = visible(); + assert.deepStrictEqual({ ordinary, inbox, noWorkspace, unavailable }, { + ordinary: ['local', 'no-workspace', 'unknown-workspace'], inbox: ['remote'], noWorkspace: ['no-workspace'], unavailable: [], + }); + }); +}); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessions.contribution.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessions.contribution.test.ts index 3e5e92327eaa..c17287f36051 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessions.contribution.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessions.contribution.test.ts @@ -4,11 +4,13 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { decodeKeybinding } from '../../../../../base/common/keybindings.js'; import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { OperatingSystem } from '../../../../../base/common/platform.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; import { Registry } from '../../../../../platform/registry/common/platform.js'; -import { Extensions as ViewContainerExtensions, IViewContainersRegistry } from '../../../../../workbench/common/views.js'; import { SESSIONS_MARK_AS_DONE_CONFETTI_SETTING } from '../../../../../platform/chat/common/sessionArchiveActions.js'; import { SESSIONS_LIST_INDENT_ITEMS_SETTING, SESSIONS_LIST_SHOW_ARCHIVED_BY_DEFAULT_SETTING, SESSIONS_LIST_SHOW_UNREAD_IN_COLLAPSED_SECTIONS_SETTING } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { ExternalSessionApplicationBadgeMode, SESSIONS_CHAT_TABS_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SessionsChatTabsMode } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; @@ -91,7 +93,7 @@ suite('Sessions Contribution', () => { }); }); - test('hides archived sessions by default with automatic experiments', () => { + test('shows archived sessions by default with automatic experiments', () => { assert.deepStrictEqual({ type: showArchivedByDefaultProperty.type, default: showArchivedByDefaultProperty.default, @@ -100,7 +102,7 @@ suite('Sessions Contribution', () => { experiment: showArchivedByDefaultProperty.experiment, }, { type: 'boolean', - default: false, + default: true, scope: ConfigurationScope.APPLICATION, tags: ['experimental', 'advanced', 'onExP'], experiment: { mode: 'auto' }, @@ -149,8 +151,28 @@ suite('Sessions Contribution', () => { }); }); - test('opens the Sessions view with Ctrl/Cmd+0, leaving Ctrl/Cmd+Shift+X to managing extensions like it opens the Extensions view in editor windows', () => { - const sessionsContainer = Registry.as(ViewContainerExtensions.ViewContainersRegistry).get('agentic.workbench.view.sessionsContainer'); - assert.deepStrictEqual({ registered: !!sessionsContainer, keybindings: sessionsContainer?.openCommandActionDescriptor?.keybindings }, { registered: true, keybindings: { primary: KeyMod.CtrlCmd | KeyCode.Digit0 } }); + test('opens the Sessions view with the keybindings of Toggle Chat in editor windows, including the user\'s, outranking Open Chat', () => { + const getKeybindings = (os: OperatingSystem) => KeybindingsRegistry.getDefaultKeybindingsForOS(os) + .filter(item => item.command === 'agentic.workbench.view.sessionsContainer') + .map(item => ({ keybinding: item.keybinding?.getHashCode(), weight: item.weight1, when: item.when?.serialize() })); + const expected = (keybinding: number, os: OperatingSystem) => [{ + keybinding: decodeKeybinding(keybinding, os)!.getHashCode(), + weight: KeybindingWeight.SessionsContrib, + when: 'viewContainer.agentic.workbench.view.sessionsContainer.enabled', + }]; + + assert.deepStrictEqual({ + windows: getKeybindings(OperatingSystem.Windows), + mac: getKeybindings(OperatingSystem.Macintosh), + linux: getKeybindings(OperatingSystem.Linux), + aliases: KeybindingsRegistry.getKeybindingAliases() + .filter(alias => alias.command === 'agentic.workbench.view.sessionsContainer') + .map(alias => ({ source: alias.source, when: alias.when.serialize() })), + }, { + windows: expected(KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyI, OperatingSystem.Windows), + mac: expected(KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KeyI, OperatingSystem.Macintosh), + linux: expected(KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyI, OperatingSystem.Linux), + aliases: [{ source: 'workbench.panel.chat', when: 'viewContainer.agentic.workbench.view.sessionsContainer.enabled' }], + }); }); }); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsActions.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsActions.test.ts index 9a968ec93bd2..1d664a338afd 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsActions.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsActions.test.ts @@ -75,6 +75,7 @@ import { IAgentHostSessionsProvider } from '../../../../../workbench/contrib/ses import { IsAuxiliaryWindowContext, IsSessionsWindowContext } from '../../../../../workbench/common/contextkeys.js'; import { IFocusedSessionHostService, ISessionHost, ISessionHostService, SessionHostKind } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; import { IChatWindow, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; +import { ISessionEditorWorkingSetService, SessionEditorWorkingSetService } from '../../../layout/common/sessionEditorWorkingSet.js'; import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { ChatHostOpenerService, IChatHostOpenerService } from '../../../../../workbench/services/sessions/browser/chatHostOpener.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; @@ -214,7 +215,7 @@ suite('Sessions - Actions', () => { }, { toolbar: [ { id: 'sessions.chatCompositeBar.addChat', group: 'navigation', order: 1, when: 'sessionSupportsMultipleChats && sessionsListPromoteNewChatAction && !sessionIsArchived && !sessionItem.inExternalSection && !sessionItem.isCloud' }, - { id: ARCHIVE_SESSION_COMMAND_ID, group: 'navigation', order: 3, when: 'chatIsEnabled && !sessionIsArchived && sessionsViewPane.grouping == \'inbox\'' }, + { id: ARCHIVE_SESSION_COMMAND_ID, group: 'navigation', order: 3, when: 'chatIsEnabled && !sessionIsArchived && sessionItem.inboxState == \'done\' && sessionsViewPane.grouping == \'inbox\'' }, { id: ARCHIVE_SESSION_COMMAND_ID, group: 'navigation', order: 2, when: '!sessionIsArchived && sessionsViewPane.grouping != \'inbox\'' }, { id: 'sessionsViewPane.pinSession', group: 'navigation', order: 1, when: '!sessionIsArchived && !sessionItem.isPinned && !sessionsListPromoteNewChatAction' }, { id: 'sessionsViewPane.unpinSession', group: 'navigation', order: 1, when: 'sessionItem.isPinned && !sessionIsArchived && !sessionsListPromoteNewChatAction' }, @@ -2786,6 +2787,7 @@ suite('Sessions - Actions', () => { instantiationService.stub(ISessionsService, upcastPartial({ slotPanes: constObservable([]) })); instantiationService.stub(IEditorGroupsService, upcastPartial({ mainPart: upcastPartial({ groups: [] }) })); instantiationService.stub(IAgentWorkbenchLayoutService, upcastPartial({})); + instantiationService.stub(ISessionEditorWorkingSetService, new SessionEditorWorkingSetService()); instantiationService.stub(ISessionHostService, upcastPartial({ getHostOfWindow: () => upcastPartial({ kind: SessionHostKind.MainWindow, session: constObservable(undefined), chat: constObservable(undefined) }) })); const picked = upcastPartial({ sessionId: 'picked', resource: URI.parse('test-session:/picked') }); await instantiationService.invokeFunction(accessor => openPickedSessionInChatWindow(accessor, picked, chatWindow, { preserveFocus: false, toSide: false })); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsArchiveActions.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsArchiveActions.test.ts index 15ec71e5253d..9bb02cb7140f 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsArchiveActions.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsArchiveActions.test.ts @@ -152,7 +152,7 @@ suite('Sessions - Bulk archive undo', () => { const context = kind === 'group' ? upcastPartial({ group, sessions: ownSessions, subtreeSessions: targets, - comparison: withComparison ? { id: 'comparison', title: group.name, launching: state.launching, summary: () => '' } : undefined, + comparison: withComparison ? { id: 'comparison', title: group.name, launching: state.launching, summary: () => '', configuration: '' } : undefined, }) : { id: kind === 'workspace' ? 'workspace:test' : 'today', label: 'Section', sessions: targets } satisfies ISessionSection; return instantiationService.invokeFunction(accessor => action.run(accessor, context)); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsFocusActiveSessionKeybinding.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsFocusActiveSessionKeybinding.test.ts index 978d6c3dafee..2ca908bb472c 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsFocusActiveSessionKeybinding.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsFocusActiveSessionKeybinding.test.ts @@ -17,25 +17,25 @@ suite('Sessions - Focus Active Session keybinding', () => { ensureNoDisposablesAreLeakedInTestSuite(); - function getRule(os: OperatingSystem, keybinding: number) { - const hash = decodeKeybinding(keybinding, os)!.getHashCode(); + function getKeybindings(os: OperatingSystem) { return KeybindingsRegistry.getDefaultKeybindingsForOS(os) - .find(item => item.command === FOCUS_ACTIVE_SESSION_COMMAND_ID && item.keybinding?.getHashCode() === hash); + .filter(item => item.command === FOCUS_ACTIVE_SESSION_COMMAND_ID) + .map(item => ({ keybinding: item.keybinding?.getHashCode(), weight: item.weight1 })); } - test('aliases the platform Open Chat (Agent) keybinding', () => { - const windowsRule = getRule(OperatingSystem.Windows, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyI); - const macRule = getRule(OperatingSystem.Macintosh, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyI); - const linuxRule = getRule(OperatingSystem.Linux, KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.KeyI); + function expected(keybinding: number, os: OperatingSystem) { + return [{ keybinding: decodeKeybinding(keybinding, os)!.getHashCode(), weight: KeybindingWeight.SessionsContrib }]; + } + test('aliases the platform Open Chat (Agent) keybinding, leaving the Open Chat keybinding to the Sessions view', () => { assert.deepStrictEqual({ - windows: { weight: windowsRule?.weight1, secondary: windowsRule?.weight2 }, - mac: { weight: macRule?.weight1, secondary: macRule?.weight2 }, - linux: { weight: linuxRule?.weight1, secondary: linuxRule?.weight2 }, + windows: getKeybindings(OperatingSystem.Windows), + mac: getKeybindings(OperatingSystem.Macintosh), + linux: getKeybindings(OperatingSystem.Linux), }, { - windows: { weight: KeybindingWeight.SessionsContrib, secondary: -1 }, - mac: { weight: KeybindingWeight.SessionsContrib, secondary: -1 }, - linux: { weight: KeybindingWeight.SessionsContrib, secondary: -1 }, + windows: expected(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyI, OperatingSystem.Windows), + mac: expected(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyI, OperatingSystem.Macintosh), + linux: expected(KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.KeyI, OperatingSystem.Linux), }); }); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsInboxScope.fixture.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsInboxScope.fixture.ts new file mode 100644 index 000000000000..f88d53d1c73e --- /dev/null +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsInboxScope.fixture.ts @@ -0,0 +1,71 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { constObservable } from '../../../../../base/common/observable.js'; +import { ActionWidgetService, IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; +import { IContextViewService } from '../../../../../platform/contextview/browser/contextView.js'; +import { ContextViewService } from '../../../../../platform/contextview/browser/contextViewService.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { IListService, ListService } from '../../../../../platform/list/browser/listService.js'; +import { SessionsInboxScope } from '../../../../../workbench/contrib/sessions/browser/views/sessionsInboxScope.js'; +import { getInboxWorkspaceFilter, SessionsListFilters } from '../../../../../workbench/contrib/sessions/browser/views/sessionsListFilters.js'; +import { buildTestSession } from '../../../../../workbench/contrib/sessions/test/common/testSessionBuilder.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; +import { TestLayoutService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import '../../../../../workbench/contrib/sessions/browser/media/sessionsViewPane.css'; + +function renderScope({ container, disposableStore, theme }: ComponentFixtureContext, options: { selected?: boolean; disconnected?: boolean; unavailable?: boolean; width?: number; picker?: 'workspace' | 'environment' } = {}): void { + const width = options.width ?? 340; + const canvasWidth = options.picker ? 960 : width; + container.style.width = `${canvasWidth}px`; + if (options.picker) { + container.style.height = '240px'; + } + container.style.backgroundColor = 'var(--vscode-sideBar-background)'; + const pane = append(container, $('.agent-sessions-viewpane')); + pane.style.width = `${width}px`; + const instantiationService = createEditorServices(disposableStore, { + colorTheme: theme, + additionalServices: reg => { + registerWorkbenchServices(reg); + reg.define(IListService, ListService); + reg.define(IContextViewService, ContextViewService); + reg.define(IActionWidgetService, ActionWidgetService); + reg.defineInstance(ILayoutService, new class extends TestLayoutService { + override mainContainer = container; + override activeContainer = container; + override containers = [container]; + override mainContainerDimension = { width: canvasWidth, height: 400 }; + override activeContainerDimension = this.mainContainerDimension; + override getContainer() { return container; } + }()); + }, + }); + const session = buildTestSession({ + id: 'workspace', title: 'Review navigation', workspace: 'agent-host-protocol-and-workbench-navigation', environment: 'ssh:work', + }).session; + const environment = { id: 'ssh:work', label: 'Development Workstation', isConnected: constObservable(!options.disconnected) }; + const filters = disposableStore.add(instantiationService.createInstance(SessionsListFilters)); + if (options.selected) { + filters.setInboxEnvironment(environment); + filters.setInboxWorkspace(getInboxWorkspaceFilter(session)); + } + const scope = disposableStore.add(instantiationService.createInstance(SessionsInboxScope, pane, filters, + constObservable(options.unavailable ? [] : [session]), constObservable(options.unavailable ? [] : [environment]), constObservable(new Set()))); + if (options.picker) { + scope.element.querySelector(`.${options.picker}-picker .action-label`)!.click(); + } +} + +export default defineThemedFixtureGroup({ path: 'sessions/' }, { + All: defineComponentFixture({ render: context => renderScope(context), additionalThemes: ['darkHighContrast', 'lightHighContrast'] }), + Selected: defineComponentFixture({ render: context => renderScope(context, { selected: true }), additionalThemes: ['darkHighContrast', 'lightHighContrast'] }), + Disconnected: defineComponentFixture({ render: context => renderScope(context, { selected: true, disconnected: true }) }), + Unavailable: defineComponentFixture({ render: context => renderScope(context, { selected: true, unavailable: true }) }), + Narrow: defineComponentFixture({ render: context => renderScope(context, { selected: true, width: 220 }), additionalThemes: ['darkHighContrast', 'lightHighContrast'] }), + WorkspaceDropdown: defineComponentFixture({ render: context => renderScope(context, { selected: true, width: 480, picker: 'workspace' }), additionalThemes: ['darkHighContrast', 'lightHighContrast'] }), + EnvironmentDropdown: defineComponentFixture({ render: context => renderScope(context, { selected: true, picker: 'environment' }), additionalThemes: ['darkHighContrast', 'lightHighContrast'] }), +}); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsList.fixture.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsList.fixture.ts index a22c8bf9525a..e3e4027ef3cc 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsList.fixture.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsList.fixture.ts @@ -721,6 +721,26 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { additionalThemes: ['darkHighContrast'], expectedVisualDescriptions: ['The pointer is over the Release work group header. It shows its hover background, a chevron in place of the group icon, and New Session and Archive All actions on the right.'], }), + SessionsList_Groups_CustomColors: defineSessionsListFixture({ + sessions: GROUP_SESSIONS, + groups: [{ ...RELEASE_GROUP, color: 'charts.blue' }, TRIAGE_GROUP], + view: { height: 440 }, + }, { + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Release work uses its assigned blue color for both its icon and its readable group name. The uncustomized Triage and workspace headers and session names retain their normal colors. High-contrast themes retain their normal label colors.'], + }), + SessionsList_Groups_CustomColorsCompact: defineSessionsListFixture({ + sessions: GROUP_SESSIONS, + groups: [{ ...RELEASE_GROUP, color: 'charts.blue' }, { ...TRIAGE_GROUP, color: 'charts.orange' }], + view: { compact: true, height: 300 }, + interaction: { hovered: { group: 'release' }, focused: { group: 'triage' } }, + }, { + deferPaint: true, + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['In compact mode the hovered Release work name retains a readable blue color even when its icon yields to the chevron. The keyboard-focused Triage name keeps its assigned orange, matching its unfocused color, and uncustomized workspace and session names remain unchanged. High-contrast themes retain their normal label colors.'], + }), SessionsList_Groups_FocusedHeader: defineSessionsListFixture({ sessions: GROUP_SESSIONS, groups: [RELEASE_GROUP], @@ -899,7 +919,8 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { interaction: { hovered: { section: 'repository:microsoft/vscode' } }, }, { labels: { kind: 'screenshot' }, - expectedVisualDescriptions: ['The pointer is over the microsoft/vscode repository header. It shows its hover background, a chevron in place of the repository icon, and on the right a New Session button with a dropdown arrow followed by an Archive All action.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the microsoft/vscode repository header. It shows its hover background, a chevron in place of the repository icon, and on the right a New Session button with a dropdown arrow followed by an Archive All action. In high contrast themes, a dashed active-contrast outline surrounds the header.'], }), //#endregion @@ -1008,7 +1029,8 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { view: { compact: true, width: 380 }, }, { labels: { kind: 'screenshot', blocksCi: true }, - expectedVisualDescriptions: ['A compact vscode workspace section shows three sessions. The first session expands with a truncated input-needed callout but no button. The second expands with a terminal-command approval callout and an Allow button. The completed third session remains a single compact title row.'], + additionalThemes: ['light2026', 'quietLight', 'solarizedLight', 'darkModern', 'darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['A compact vscode workspace section shows three sessions. The first session expands with a truncated input-needed callout but no button. The second expands with a terminal-command approval callout and an Allow button. The completed third session remains a single compact title row. In high contrast themes, needs-input rows have a separate straight yellow left-edge marker, inset from the rounded corners, instead of a tinted background.'], }), SessionsList_CompactSessionRename: defineSessionsListFixture({ sessions: COMPACT_RENAME_SESSIONS, @@ -1046,12 +1068,23 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { additionalThemes: ['darkHighContrast'], expectedVisualDescriptions: ['A keyboard-focused compact session shows its parent Pin and Mark as Done actions. Its active child is hidden, its done child is in the collapsed Done section, and the parent remains a single compact row.'], }), + SessionsList_CompactNestedChatsCollapsedHover: defineSessionsListFixture({ + sessions: [ARCHIVED_CHAT_SESSION], + view: { compact: true, showArchived: true, width: 340, collapsed: [{ session: 'nested-archive' }] }, + interaction: { hovered: { session: 'nested-archive' } }, + settings: { [ChatSessionArchiveActionWordingSettingId]: ChatSessionArchiveActionWording.MarkAsDone }, + }, { + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over a collapsed compact parent session. Its nested chats remain hidden and its row actions show. In high contrast themes, a dashed active-contrast outline surrounds the parent row.'], + }), SessionsList_CompactNestedChatApprovals: defineSessionsListFixture({ sessions: [NESTED_CHAT_APPROVAL_SESSION], view: { compact: true, width: 340, height: 300 }, }, { labels: { kind: 'screenshot', blocksCi: true }, - expectedVisualDescriptions: ['A compact session and two of its three nested chats each show their own terminal approval and Allow button. Task B has no approval and remains a single compact row; the expanded approval rows do not overlap adjacent children.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['A compact session and two of its three nested chats each show their own terminal approval and Allow button. Task B has no approval and remains a single compact row; the expanded approval rows do not overlap adjacent children. In high contrast themes, only the needs-input rows have a separate straight yellow left-edge marker, inset from the rounded corners, without a tinted background.'], }), //#endregion 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 bd52c12f8ae0..4330ce21cdc8 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts @@ -9,19 +9,21 @@ import { IAgentFeedbackService } from '../../../../../workbench/contrib/sessions import assert from 'assert'; import sinon from 'sinon'; import { $, append, scheduleAtNextAnimationFrame } from '../../../../../base/browser/dom.js'; -import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; -import { IDelayedHoverOptions } from '../../../../../base/browser/ui/hover/hover.js'; +import { DeferredPromise, retry, timeout } from '../../../../../base/common/async.js'; +import { IDelayedHoverOptions, isManagedHoverTooltipMarkdownString } from '../../../../../base/browser/ui/hover/hover.js'; import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { Color } from '../../../../../base/common/color.js'; import { IMarkdownString, MarkdownString } from '../../../../../base/common/htmlContent.js'; import { findOnboardingTarget, markOnboardingTarget, resolveOnboardingTarget } from '../../../../../workbench/contrib/onboarding/browser/spotlight/onboardingTarget.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; +import { extractChatReferenceDropData } from '../../../../../platform/dnd/browser/dnd.js'; import { ExtUri, isEqual } from '../../../../../base/common/resources.js'; import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { autorun, constObservable, derived, IObservable, IReader, ISettableObservable, observableFromEvent, observableValue, transaction } from '../../../../../base/common/observable.js'; -import { isMacintosh, OS } from '../../../../../base/common/platform.js'; +import { isMacintosh, isWindows, OS } from '../../../../../base/common/platform.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { URI } from '../../../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; @@ -59,6 +61,9 @@ import { InMemoryStorageService, IStorageService, StorageScope, StorageTarget } import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { NullTelemetryServiceShape } from '../../../../../platform/telemetry/common/telemetryUtils.js'; import { TestExperimentTriggerTelemetryService } from '../../../../../platform/telemetry/test/common/experimentTriggerTestUtils.js'; +import { ColorScheme } from '../../../../../platform/theme/common/theme.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { TestColorTheme, TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; import { IAutomationDescriptor, IAutomationRun } from '../../../../../workbench/contrib/chat/common/automations/automation.js'; import { IAutomationService } from '../../../../../workbench/contrib/chat/common/automations/automationService.js'; import { ChatAutomationsEnabledContext } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; @@ -116,7 +121,8 @@ import { TestSessionsList } from '../../../../../workbench/contrib/sessions/test import { getSessionEnvironments } from '../../../../../workbench/contrib/sessions/browser/views/sessionsListFilters.js'; import { getSessionInboxSection, SessionInboxSection } from '../../../../../workbench/contrib/sessions/common/sessionInbox.js'; import { IInboxNotificationsService, IInboxSessionAttention, InboxNotificationPriority, InboxTab } from '../../../../../workbench/contrib/sessions/common/inboxNotificationsService.js'; -import { ITestSessionWithChat, testGridPanes } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { ITestSessionWithChat, ITestShownChat, stubSessionHosts, testGridPanes } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; +import { IAICustomizationWorkspaceService } from '../../../../../workbench/contrib/chat/common/aiCustomizationWorkspaceService.js'; function clickRow(row: HTMLElement, modifiers: MouseEventInit = {}): void { row.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, ...modifiers })); @@ -301,7 +307,7 @@ suite('Sessions - SessionsList', () => { providers.fire({ added: [], removed: [] }); }; return { - harness, list, management, original, changes, invalidateCatalogue, + harness, list, management, original, changes, invalidateCatalogue, container, counts: () => ({ reads, updates }), titles: () => [...container.querySelectorAll('.session-title')].map(element => element.textContent), }; @@ -331,7 +337,7 @@ suite('Sessions - SessionsList', () => { }); }); - for (const operation of ['added', 'removed', 'changed'] as const) { + for (const operation of ['added', 'removed'] as const) { test(`keeps concrete session ${operation} synchronous and cancels a redundant queued refresh`, async () => { const fixture = await createFixture(); fixture.invalidateCatalogue(); @@ -340,7 +346,7 @@ suite('Sessions - SessionsList', () => { fixture.changes.fire({ added: operation === 'added' ? [replacement] : [], removed: operation === 'removed' ? [fixture.original] : [], - changed: operation === 'changed' ? [replacement] : [], + changed: [], }); const immediate = { ...fixture.counts(), titles: fixture.titles() }; await nextFrame(); @@ -352,6 +358,21 @@ suite('Sessions - SessionsList', () => { }); } + test('coalesces concrete metadata changes without losing the latest catalogue', async () => { + const fixture = await createFixture(); + const replacement = createTestSession('Replacement').session; + fixture.management.sessions = [replacement]; + fixture.changes.fire({ added: [], removed: [], changed: [replacement] }); + fixture.changes.fire({ added: [], removed: [], changed: [replacement] }); + const immediate = { ...fixture.counts(), titles: fixture.titles() }; + await nextFrame(); + + assert.deepStrictEqual({ immediate, settled: { ...fixture.counts(), titles: fixture.titles() } }, { + immediate: { reads: 0, updates: 0, titles: ['Original'] }, + settled: { reads: 1, updates: 1, titles: ['Replacement'] }, + }); + }); + for (const explicit of ['refresh', 'update'] as const) { test(`an explicit ${explicit} reads the latest pending catalogue synchronously`, async () => { const fixture = await createFixture(); @@ -430,6 +451,52 @@ suite('Sessions - SessionsList', () => { reads: 2, updates: 2, titles: ['Latest'], }); }); + + for (const trigger of ['refresh', 'reveal'] as const) { + test(`defers metadata changes raised while ${trigger} renders a lazy row`, async () => { + const fixture = await createFixture(); + fixture.list.layout(trigger === 'refresh' ? 400 : 90, 400); + const base = createTestSession('Lazy', { createdAt: trigger === 'reveal' ? new Date(0) : new Date() }).session; + let subscribed = false; + const onDidResolveTimestamp: Event = () => { + if (!subscribed) { + subscribed = true; + fixture.changes.fire({ added: [], removed: [], changed: [lazy] }); + } + return toDisposable(() => { }); + }; + const lazy: ISession = { + ...base, + mainChat: constObservable({ + ...base.mainChat.get(), + updatedAt: observableFromEvent(disposables, onDidResolveTimestamp, () => undefined), + }), + }; + fixture.management.sessions = [ + ...Array.from({ length: 4 }, (_, index) => createTestSession(`Session ${index}`).session), + lazy, + ]; + fixture.list.refresh(); + if (trigger === 'reveal') { + assert.strictEqual(subscribed, false); + fixture.list.revealItem({ session: lazy.resource }); + } + const immediate = fixture.counts(); + await nextFrame(); + const rows = [...fixture.container.querySelectorAll('.monaco-list-rows > .monaco-list-row')] + .sort((a, b) => Number(a.dataset.index) - Number(b.dataset.index)) + .map(row => row.getBoundingClientRect()); + + assert.deepStrictEqual({ + subscribed, immediate, settled: fixture.counts(), + title: fixture.list.getItemRow({ session: lazy.resource })?.querySelector('.session-title')?.textContent, + disjoint: rows.every((row, index) => index === 0 || rows[index - 1].bottom <= row.top), + }, { + subscribed: true, immediate: { reads: 1, updates: 1 }, settled: { reads: 2, updates: 2 }, + title: 'Lazy', disjoint: true, + }); + }); + } }); test('uses the large radius token for list hovers even when pointer styles load later', () => { @@ -500,11 +567,10 @@ suite('Sessions - SessionsList', () => { const initialHeight = peerRow().getBoundingClientRect().height; await configuration.setUserConfiguration(SESSIONS_LIST_INLINE_ACTIONS_SETTING, true); configuration.onDidChangeConfigurationEmitter.fire(upcastPartial({ affectsConfiguration: key => key === SESSIONS_LIST_INLINE_ACTIONS_SETTING })); - await timeout(50); list.setSelectedItems([{ session: a.session.resource }, { session: b.session.resource }]); + await retry(async () => assert.strictEqual(peerRow().getBoundingClientRect().height - initialHeight, 32), 10, 100); const button = list.getItemRow({ session: a.session.resource, chat: peer.resource })?.querySelector('.session-inline-actions .monaco-button'); assert.ok(button); - const heightIncrease = peerRow().getBoundingClientRect().height - initialHeight; button.focus(); button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); const footerFocused = !!mainWindow.document.activeElement?.closest('.sessions-list-inbox-footer'); @@ -517,9 +583,9 @@ suite('Sessions - SessionsList', () => { await configuration.setUserConfiguration(SESSIONS_LIST_INLINE_ACTIONS_SETTING, true); configuration.onDidChangeConfigurationEmitter.fire(upcastPartial({ affectsConfiguration: key => key === SESSIONS_LIST_INLINE_ACTIONS_SETTING })); list.setVisible(false); - assert.deepStrictEqual({ initial, submitted, opened, activeObservers, disabledObservers, remainingObservers: observers, heightIncrease, footerFocused }, { + assert.deepStrictEqual({ initial, submitted, opened, activeObservers, disabledObservers, remainingObservers: observers, footerFocused }, { initial: { buttons: 0, observers: 0 }, submitted: [peer.resource.toString()], opened: 0, activeObservers: 3, disabledObservers: 0, remainingObservers: 0, - heightIncrease: 32, footerFocused: grouping === SessionsGrouping.Inbox, + footerFocused: false, }); }); } @@ -587,11 +653,11 @@ suite('Sessions - SessionsList', () => { override readonly automations = constObservable([]); override readonly runs = constObservable([]); }; - let hoverOptions: Parameters[1] | undefined; + let hoverOptions: Parameters[2] | undefined; const hoverService = new class extends mock() { - override setupDelayedHover(...args: Parameters): ReturnType { - hoverOptions = args[1]; - return NullHoverService.setupDelayedHover(...args); + override setupManagedHover(...args: Parameters): ReturnType { + hoverOptions = args[2]; + return NullHoverService.setupManagedHover(...args); } }; const customizationMigrationsAvailable = observableValue(disposables, true); @@ -623,28 +689,19 @@ suite('Sessions - SessionsList', () => { collapsible: false, collapsed: false, }), 0, template); - const readHoverOptions = () => typeof hoverOptions === 'function' ? hoverOptions() : hoverOptions; + const readHoverOptions = () => { + const content = typeof hoverOptions === 'function' ? hoverOptions() : hoverOptions; + return isManagedHoverTooltipMarkdownString(content) ? content.markdownNotSupportedFallback : undefined; + }; const hoverWithMigration = readHoverOptions(); customizationMigrationsAvailable.set(false, undefined); assert.deepStrictEqual({ - contentWithMigration: hoverWithMigration?.content, - contentWithoutMigration: readHoverOptions()?.content, - presentation: hoverWithMigration && { - additionalClasses: hoverWithMigration.additionalClasses, - appearance: hoverWithMigration.appearance, - position: hoverWithMigration.position, - persistence: hoverWithMigration.persistence, - }, + contentWithMigration: hoverWithMigration, + contentWithoutMigration: readHoverOptions(), }, { contentWithMigration: 'Some customizations need an update to keep working.', - contentWithoutMigration: 'Customizations', - presentation: { - additionalClasses: ['sessions-list-hover'], - appearance: { showPointer: true }, - position: { hoverPosition: HoverPosition.RIGHT, forcePosition: true }, - persistence: { hideOnHover: false }, - }, + contentWithoutMigration: 'Session Customizations', }); }); @@ -659,11 +716,11 @@ suite('Sessions - SessionsList', () => { override readonly automations = constObservable([]); override readonly runs = constObservable([]); }; - let hoverOptions: Parameters[1] | undefined; + let hoverOptions: Parameters[2] | undefined; const hoverService = new class extends mock() { - override setupDelayedHover(...args: Parameters): ReturnType { - hoverOptions = args[1]; - return NullHoverService.setupDelayedHover(...args); + override setupManagedHover(...args: Parameters): ReturnType { + hoverOptions = args[2]; + return NullHoverService.setupManagedHover(...args); } }; const customizationMigrationsAvailable = observableValue(disposables, false); @@ -702,7 +759,10 @@ suite('Sessions - SessionsList', () => { collapsed: false, }), 0, template); const readState = () => ({ - hover: (typeof hoverOptions === 'function' ? hoverOptions() : hoverOptions)?.content, + hover: (() => { + const content = typeof hoverOptions === 'function' ? hoverOptions() : hoverOptions; + return isManagedHoverTooltipMarkdownString(content) ? content.markdownNotSupportedFallback : undefined; + })(), hasDot: template.icon.classList.contains('codicon-circle-filled'), iconColor: template.icon.style.color, }); @@ -724,7 +784,7 @@ suite('Sessions - SessionsList', () => { iconColor: 'var(--vscode-activityBarBadge-background)', }, withoutSignals: { - hover: 'Customizations', + hover: 'Session Customizations', hasDot: false, iconColor: '', }, @@ -888,6 +948,39 @@ suite('Sessions - SessionsList', () => { }); }); + test('moves Customizations without moving other navigation shortcuts', () => { + const harness = createListHarness(disposables, []); + const container = harness.createContainer(); + const navigationContainer = mainWindow.document.createElement('div'); + const listContainer = mainWindow.document.createElement('div'); + container.append(navigationContainer, listContainer); + let showCustomizations = true; + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, listContainer, { + grouping: () => SessionsGrouping.Date, + sorting: () => SessionsSorting.Created, + showNavigationShortcuts: () => true, + showCustomizations: () => showCustomizations, + navigationContainer, + onSessionOpen: () => { }, + })); + list.layout(300, 400); + const snapshot = () => ({ + customizations: navigationContainer.querySelectorAll('.session-section-customizations').length, + newSession: navigationContainer.querySelectorAll('.session-section-new-session').length, + }); + const shown = snapshot(); + showCustomizations = false; + list.updateNavigationVisibility(); + const hidden = snapshot(); + showCustomizations = true; + list.updateNavigationVisibility(); + assert.deepStrictEqual({ shown, hidden, restored: snapshot() }, { + shown: { customizations: 1, newSession: 1 }, + hidden: { customizations: 0, newSession: 1 }, + restored: { customizations: 1, newSession: 1 }, + }); + }); + test('opens Inbox from the navigation list and hides it when disabled', async () => { const harness = createListHarness(disposables, [], instantiationService => { const contextKeyService = disposables.add(new ContextKeyService(new TestConfigurationService())); @@ -954,7 +1047,7 @@ suite('Sessions - SessionsList', () => { const snapshot = () => ({ navigation: Array.from(navigationContainer.querySelectorAll('.session-section-label')).map(element => element.textContent), treeStartsWithAutomations: listContainer.querySelector('.monaco-list-row .session-section-label')?.textContent === 'Automations', - categoriesContainAutomations: listContainer.querySelector('.sessions-list-inbox-footer')?.textContent?.includes('Automations'), + categoriesContainAutomations: !!listContainer.querySelector('.sessions-list-inbox-footer')?.textContent?.includes('Automations'), }); const regular = snapshot(); grouping = SessionsGrouping.Inbox; @@ -1155,7 +1248,15 @@ suite('Sessions - SessionsList', () => { test('opens migrations from Customizations only while migration attention is active', async () => { const customizationMigrationsAvailable = observableValue(disposables, true); - const harness = createListHarness(disposables, []); + const events: { name?: string; data?: unknown }[] = []; + const harness = createListHarness(disposables, [], instantiationService => { + instantiationService.stub(IAICustomizationWorkspaceService, new class extends mock() { + override readonly isSessionsWindow = true; + }()); + instantiationService.stub(ITelemetryService, new class extends NullTelemetryServiceShape { + override publicLog2(name?: string, data?: unknown): void { events.push({ name, data }); } + }()); + }); const container = harness.createContainer(); const navigationContainer = mainWindow.document.createElement('div'); const listContainer = mainWindow.document.createElement('div'); @@ -1178,13 +1279,19 @@ suite('Sessions - SessionsList', () => { clickRow(customizationsRow); await Promise.resolve(); - assert.deepStrictEqual(harness.commandService.calls, [{ - commandId: OPEN_AI_CUSTOMIZATIONS_COMMAND_ID, - args: [{ migration: true }], - }, { - commandId: OPEN_AI_CUSTOMIZATIONS_COMMAND_ID, - args: [], - }]); + assert.deepStrictEqual({ commands: harness.commandService.calls, events }, { + commands: [{ + commandId: OPEN_AI_CUSTOMIZATIONS_COMMAND_ID, + args: [{ migration: true }], + }, { + commandId: OPEN_AI_CUSTOMIZATIONS_COMMAND_ID, + args: [], + }], + events: Array(2).fill({ + name: 'chatCustomizationEntryPoint.interaction', + data: { action: 'buttonClicked', location: 'sessionsHeader', configuredLocation: 'unknown', windowKind: 'agents', target: 'none' }, + }), + }); }); test('lists pinned canvases below Customizations, highlights the shown one, and hides the group when empty', async () => { @@ -2275,17 +2382,117 @@ suite('Sessions - SessionsList', () => { const collapsed = getHeader()?.querySelector('.session-section-chevron')?.className; getHeader()?.click(); const expanded = getHeader()?.querySelector('.session-section-chevron')?.className; + const disclosureRow = getHeader()?.closest('.monaco-list-row')?.classList.contains('sessions-disclosure-row'); - assert.deepStrictEqual({ stickyHeaders, collapsed, expanded }, { + assert.deepStrictEqual({ stickyHeaders, collapsed, expanded, disclosureRow }, { stickyHeaders: [label], collapsed: 'session-section-chevron collapsible codicon codicon-chevron-right', expanded: 'session-section-chevron collapsible codicon codicon-chevron-down', + disclosureRow: true, }); }); } }); suite('row feedback', () => { + for (const { compact, customGroup } of [false, true].flatMap(compact => [false, true].map(customGroup => ({ compact, customGroup })))) { + test(`group label colors persist across interaction states and preserve contrast and reset (${compact ? 'compact' : 'default'}, ${customGroup ? 'custom group' : 'workspace'})`, () => { + const session = createTestSession('Session').session; + const group: ISessionGroup = { id: 'group', name: 'Custom Group', createdAt: 1 }; + const harness = createListHarness(disposables, [session], customGroup ? { + groups: [group], + memberships: new Map([[session.sessionId, group.id]]), + } : {}); + const themeService = new TestThemeService(); + harness.instantiationService.stub(IThemeService, themeService); + const container = harness.createContainer(); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Workspace, + sorting: () => SessionsSorting.Created, + compact: () => compact, + onSessionOpen: () => { }, + })); + list.layout(700, 400); + container.style.setProperty('--vscode-terminal-ansiYellow', '#e5e510'); + const label = () => [...container.querySelectorAll('.session-section-label')] + .find(label => label.textContent === (customGroup ? group.name : 'Workspace'))!; + const appearance = () => ({ + color: label().style.getPropertyValue('--session-group-foreground'), + interactionColors: ['focus', 'selection', 'inactive-focus', 'inactive-selection'] + .map(state => label().style.getPropertyValue(`--session-group-${state}-foreground`)), + }); + const initial = appearance(); + const groupsService = harness.instantiationService.get(ISessionGroupsService); + const setColor = (color: string | undefined) => customGroup + ? groupsService.setGroupColor(group.id, color) + : groupsService.setSectionColor('workspace:Workspace', color); + setColor('terminal.ansiYellow'); + const contrasts = []; + for (const background of ['#181818', '#ffffff']) { + for (const color of ['#000000', '#cd3131', '#0dbc79', '#e5e510', '#2472c8', '#bc3fbc', '#11a8cd', '#ffffff', '#11a8cd66', '#ffffff00']) { + const theme = new TestColorTheme({ + 'agents.background': background, + 'list.hoverBackground': '#88888822', + 'terminal.ansiYellow': color, + }); + themeService.setTheme(theme); + const base = Color.fromHex(background); + const hover = theme.getColor('list.hoverBackground')!.flatten(base); + contrasts.push( + base.getContrastRatio(Color.fromHex(label().style.getPropertyValue('--session-group-foreground'))) >= 4.5, + hover.getContrastRatio(Color.fromHex(label().style.getPropertyValue('--session-group-hover-foreground'))) >= 4.5, + ); + } + } + themeService.setTheme(new TestColorTheme({ + 'agents.background': '#181818', + 'list.hoverBackground': '#88888822', + 'terminal.ansiYellow': '#e5e510', + })); + const interactionColors = [false, true].flatMap(collapsed => { + if (collapsed) { + list.collapseAllSections(); + } + const row = label().closest('.monaco-list-row')!; + row.style.color = 'rgb(12, 34, 56)'; + return [[], ['hovered'], ['focused'], ['selected'], ['focused', 'hovered'], ['selected', 'hovered']].map(classes => { + row.classList.remove('focused', 'selected', 'hovered'); + row.classList.add(...classes); + const icon = label().closest('.session-section')!.querySelector('.session-section-icon')!; + return { + label: mainWindow.getComputedStyle(label()).color, + icon: mainWindow.getComputedStyle(icon).color, + }; + }); + }); + label().closest('.monaco-list-row')!.classList.remove('focused', 'selected', 'hovered'); + const highContrast = [ColorScheme.HIGH_CONTRAST_DARK, ColorScheme.HIGH_CONTRAST_LIGHT].map(type => { + themeService.setTheme(new TestColorTheme({}, type)); + return appearance(); + }); + const translucentBackgrounds = ['#00000000', '#ffffff00', '#18181880'].map(background => { + themeService.setTheme(new TestColorTheme({ + 'agents.background': background, + 'terminal.ansiYellow': '#ffffff', + })); + return appearance(); + }); + themeService.setTheme(new TestColorTheme({ + 'agents.background': '#181818', + 'terminal.ansiYellow': '#e5e510', + })); + setColor(undefined); + assert.deepStrictEqual({ initial, contrasts, interactionColors, highContrast, translucentBackgrounds, reset: appearance() }, { + initial: { color: '', interactionColors: ['', '', '', ''] }, + contrasts: Array(40).fill(true), + interactionColors: Array(12).fill({ label: 'rgb(229, 229, 16)', icon: 'rgb(229, 229, 16)' }), + highContrast: Array(2).fill({ color: '', interactionColors: ['', '', '', ''] }), + translucentBackgrounds: Array(3).fill({ color: '', interactionColors: ['', '', '', ''] }), + reset: { color: '', interactionColors: ['', '', '', ''] }, + }); + }); + } + test('keeps custom group toolbar at the trailing edge', () => { const group: ISessionGroup = { id: 'group', name: 'Custom Group', createdAt: 1 }; const session = createTestSession('session').session; @@ -2448,8 +2655,10 @@ suite('Sessions - SessionsList', () => { memberships: new Map([[session.sessionId, group.id]]), }); const snapshot = () => { - const icon = getHeader(container, group.name).querySelector('.session-section-icon')!; - return { rocket: icon.classList.contains('codicon-rocket'), color: icon.style.color, unread: !!icon.querySelector('.codicon-circle-filled') }; + const header = getHeader(container, group.name); + const icon = header.querySelector('.session-section-icon')!; + const label = header.querySelector('.session-section-label')!; + return { rocket: icon.classList.contains('codicon-rocket'), color: icon.style.color, unread: !!icon.querySelector('.codicon-circle-filled'), labelColor: label.style.getPropertyValue('--session-group-foreground') }; }; const expanded = snapshot(); list.collapseAllSections(); @@ -2457,9 +2666,9 @@ suite('Sessions - SessionsList', () => { isRead.set(true, undefined); const collapsedRead = snapshot(); assert.deepStrictEqual({ expanded, collapsedUnread, collapsedRead }, { - expanded: { rocket: true, color: 'var(--vscode-charts-blue)', unread: false }, - collapsedUnread: { rocket: false, color: '', unread: true }, - collapsedRead: { rocket: true, color: 'var(--vscode-charts-blue)', unread: false }, + expanded: { rocket: true, color: 'var(--vscode-charts-blue)', unread: false, labelColor: 'var(--vscode-charts-blue)' }, + collapsedUnread: { rocket: false, color: '', unread: true, labelColor: 'var(--vscode-charts-blue)' }, + collapsedRead: { rocket: true, color: 'var(--vscode-charts-blue)', unread: false, labelColor: 'var(--vscode-charts-blue)' }, }); }); @@ -2742,7 +2951,7 @@ suite('Sessions - SessionsList', () => { hiddenNeedsInput: true, states: ['none', 'needsInput', 'unread', 'needsInput', 'unread', 'needsInput', 'none', 'needsInput', 'unread', 'none'], preservesReportQuestionIcon: true, - color: 'var(--vscode-list-warningForeground)', + color: 'var(--vscode-agentSessionNeedsInput-foreground)', needsInputAria: `${label}, 6, session needs attention`, unreadAria: `${label}, 6, contains unread sessions`, expandedPulse: false, @@ -2890,7 +3099,7 @@ suite('Sessions - SessionsList', () => { }, { hasSpinner: false, hasReportQuestionIcon: true, - color: 'var(--vscode-list-warningForeground)', + color: 'var(--vscode-agentSessionNeedsInput-foreground)', ariaLabel: 'Workspace, 1, session needs attention', }); }); @@ -3881,6 +4090,30 @@ suite('Sessions - SessionsList', () => { }); }); + test('hides older workspaces behind a more row only when more than two workspaces exist', () => { + const daysAgo = (days: number) => new Date(Date.now() - days * 86_400_000); + const render = (workspaceCount: number) => { + const harness = createListHarness(disposables, Array.from({ length: workspaceCount }, (_, index) => + createTestSession(`session-${index}`, { workspaceLabel: `workspace-${index}`, workspaceResource: URI.parse(`file:///workspace-${index}`), createdAt: daysAgo(index === 0 ? 0 : 5 + index) }).session)); + const container = harness.createContainer(400, 1400); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Workspace, + sorting: () => SessionsSorting.Created, + onSessionOpen: () => { }, + })); + list.layout(1400, 400); + return { + sessions: list.getVisibleSessions().length, + showMore: [...container.querySelectorAll('.monaco-list-rows .session-show-more-label')].map(label => label.textContent), + }; + }; + + assert.deepStrictEqual({ two: render(2), three: render(3) }, { + two: { sessions: 2, showMore: [] }, + three: { sessions: 1, showMore: ['+2 more workspaces'] }, + }); + }); + for (const grouping of [SessionsGrouping.Workspace, SessionsGrouping.Repository]) { test(`caps the Chats section like a workspace until the user chooses otherwise (${grouping})`, () => { const harness = createListHarness(disposables, Array.from({ length: 8 }, (_, index) => @@ -4438,6 +4671,7 @@ suite('Sessions - SessionsList', () => { ...grouped, createTestSession('recent', { workspaceLabel: 'Recent', createdAt: new Date(now - 10_000) }).session, createTestSession('claude', { workspaceLabel: 'Recent', harness: 'claude', createdAt: new Date(now - 20_000) }).session, + createTestSession('second', { workspaceLabel: 'Second', createdAt: new Date(now - 30_000) }).session, createTestSession('old', { workspaceLabel: 'Old', createdAt: new Date(now - 10 * 24 * 60 * 60 * 1000) }).session, ], { groups: [group], memberships: new Map(grouped.map(session => [session.sessionId, group.id])) }); const showMoreLabels = () => [...container.querySelectorAll('.monaco-list-rows .session-show-more-label')]; @@ -4464,22 +4698,22 @@ suite('Sessions - SessionsList', () => { assert.deepStrictEqual({ before, reset, undone: state() }, { before: { - sessions: ['group-0', 'group-1', 'group-2', 'group-3', 'group-4', 'recent', 'old'], + sessions: ['group-0', 'group-1', 'group-2', 'group-3', 'group-4', 'recent', 'second', 'old'], showMore: ['+2 more', 'Show fewer workspaces'], excludeArchived: false, stored: { filters: [['["harness","claude"]', true]], excludeArchived: false, sessionGroupExpansionState: { 'group:group-a': false } }, }, reset: { - sessions: ['group-0', 'group-1', 'group-2', 'group-3', 'group-4', 'group-5', 'group-6', 'recent', 'claude'], + sessions: ['group-0', 'group-1', 'group-2', 'group-3', 'group-4', 'group-5', 'group-6', 'recent', 'claude', 'second'], showMore: ['Show less', '+1 more workspace'], excludeArchived: true, - stored: { filters: undefined, excludeArchived: true, sessionGroupExpansionState: undefined }, + stored: { filters: undefined, excludeArchived: undefined, sessionGroupExpansionState: undefined }, }, undone: before, }); }); - test('undoing a reset restores Show All and an archived filter that follows its default setting', () => { + test('a reset leaves the archived filter following its default setting, and undoing it restores Show All', () => { const { list, stored } = createList([createTestSession('session').session], {}, true); list.setWorkspaceGroupCapped(false); const state = () => ({ capped: list.isWorkspaceGroupCapped(), excludeArchived: list.isExcludeArchived(), storedExcludeArchived: stored('excludeArchived') }); @@ -4491,7 +4725,7 @@ suite('Sessions - SessionsList', () => { assert.deepStrictEqual({ before, reset, undone: state() }, { before: { capped: false, excludeArchived: false, storedExcludeArchived: undefined }, - reset: { capped: true, excludeArchived: true, storedExcludeArchived: true }, + reset: { capped: true, excludeArchived: false, storedExcludeArchived: undefined }, undone: { capped: false, excludeArchived: false, storedExcludeArchived: undefined }, }); }); @@ -4638,6 +4872,7 @@ suite('Sessions - SessionsList', () => { const sessions = Array.from({ length: 8 }, (_, index) => repositorySession(`Local ${index}`, 'local', index)); const { list, container } = render([ ...sessions, + repositorySession('Host session', 'host', 9), repositorySession('Old cloud session', 'cloud', 10 * 24 * 60), ], {}, true, SessionsGrouping.Environment); const snapshot = () => ({ @@ -4654,10 +4889,10 @@ suite('Sessions - SessionsList', () => { list.setWorkspaceGroupCapped(false); assert.deepStrictEqual({ recent, moreAria, expanded, all: snapshot() }, { - recent: { titles: sessions.slice(0, 5).map(session => session.title.get()), more: ['+3 more', '+1 more environment'] }, + recent: { titles: [...sessions.slice(0, 5).map(session => session.title.get()), 'Host session'], more: ['+3 more', '+1 more environment'] }, moreAria: 'Show 1 more environment', - expanded: { titles: [...sessions.slice(0, 5).map(session => session.title.get()), 'Old cloud session'], more: ['+3 more', 'Show fewer environments'] }, - all: { titles: [...sessions.map(session => session.title.get()), 'Old cloud session'], more: [] }, + expanded: { titles: [...sessions.slice(0, 5).map(session => session.title.get()), 'Host session', 'Old cloud session'], more: ['+3 more', 'Show fewer environments'] }, + all: { titles: [...sessions.map(session => session.title.get()), 'Old cloud session', 'Host session'], more: [] }, }); }); @@ -5166,7 +5401,7 @@ suite('Sessions - SessionsList', () => { const done = createTestSession('done').session; const archived = createTestSession('archived', { isArchived: true }).session; const sections = groupSessionsForList([idle, working, finished, failing, pinned, waiting, done, snoozed, archived], - SessionsGrouping.Inbox, SessionsSorting.Created, session => session === pinned, undefined, 'Archived', true, [], + SessionsGrouping.Inbox, SessionsSorting.Updated, session => session === pinned, undefined, 'Archived', true, [], session => session === done ? SessionInboxSection.Done : session === snoozed ? SessionInboxSection.OnHold : getSessionInboxSection(session), session => session === failing || session === waiting ? InboxNotificationPriority.Now : InboxNotificationPriority.Later); assert.deepStrictEqual(sections.map(section => [section.id, section.sessions.map(session => session.sessionId)]), [ @@ -5180,6 +5415,58 @@ suite('Sessions - SessionsList', () => { ]); }); + test('inbox honors Created and Updated sorting within attention priorities', () => { + const older = createSession('older', { createdAt: new Date(1), updatedAt: new Date(4) }); + const newer = createSession('newer', { createdAt: new Date(2), updatedAt: new Date(3) }); + const urgent = createSession('urgent', { createdAt: new Date(0), updatedAt: new Date(0) }); + const order = (sorting: SessionsSorting) => groupSessionsForList([older, newer, urgent], SessionsGrouping.Inbox, sorting, () => false, + session => session === older ? Number.MAX_SAFE_INTEGER : 0, undefined, true, [], () => SessionInboxSection.ReadyForYou, + session => session === urgent ? InboxNotificationPriority.Now : InboxNotificationPriority.Later) + .find(section => section.id === SessionInboxSection.ReadyForYou)!.sessions.map(session => session.sessionId); + assert.deepStrictEqual([order(SessionsSorting.Created), order(SessionsSorting.Updated)], [ + ['urgent', 'newer', 'older'], ['urgent', 'older', 'newer'], + ]); + }); + + test('inbox keeps a completed parent available while a child works, except when explicitly triaged', () => { + const built = buildTestSession({ + id: 'parent', title: 'Parent', status: SessionStatus.InProgress, mainChatStatus: SessionStatus.Completed, + chats: [{ id: 'child', title: 'Child', status: SessionStatus.InProgress }], + }); + const attention: IInboxSessionAttention = { tab: InboxTab.Working, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: false }; + const completedParent = getSessionInboxSection(built.session, undefined, undefined, attention); + const held = getSessionInboxSection(built.session, { kind: 'hold' }, undefined, attention); + built.mainChat.status.set(SessionStatus.InProgress, undefined); + const bothWorking = getSessionInboxSection(built.session, undefined, undefined, attention); + built.mainChat.status.set(SessionStatus.Completed, undefined); + built.mainChat.isArchived.set(true, undefined); + assert.deepStrictEqual({ completedParent, held, bothWorking, archivedParent: getSessionInboxSection(built.session, undefined, undefined, attention) }, { + completedParent: SessionInboxSection.ReadyForYou, held: SessionInboxSection.OnHold, + bothWorking: SessionInboxSection.Working, archivedParent: SessionInboxSection.Working, + }); + }); + + test('inbox exposes the snooze deadline visually and to screen readers', () => { + const session = buildTestSession({ id: 'snoozed', title: 'Snoozed', workspace: 'Project' }).session; + const harness = createListHarness(disposables, [session]); + const model = disposables.add(harness.instantiationService.createInstance(SessionsListModelService)); + harness.instantiationService.stub(ISessionsListModelService, model); + const until = new Date(2099, 0, 1, 9); + model.setInboxState([session], until.getTime()); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, + })); + list.layout(600, 400); + list.setHeaderCollapsed(SessionInboxSection.OnHold, false); + const row = list.getItemRow({ session: session.resource })!; + const description = `Snoozed until ${until.toLocaleString()}`; + assert.deepStrictEqual({ + visible: row.textContent?.includes(description), + accessible: row.getAttribute('aria-label')?.includes(description), + archived: session.isArchived.get(), + }, { visible: true, accessible: true, archived: false }); + }); + test('inbox renders historical and explicit triage state and restores custom placement when leaving the mode', async () => { const grouped = createTestSession('grouped'); const running = createTestSession('running', { status: SessionStatus.InProgress, updatedAt: new Date(1) }); @@ -5208,7 +5495,7 @@ suite('Sessions - SessionsList', () => { let grouping = SessionsGrouping.Inbox; const container = harness.createContainer(); const list = disposables.add(harness.instantiationService.createInstance(SessionsList, container, { - grouping: () => grouping, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, + grouping: () => grouping, sorting: () => SessionsSorting.Updated, onSessionOpen: () => { }, })); list.setVisible(true); list.layout(800, 320); @@ -5217,10 +5504,14 @@ suite('Sessions - SessionsList', () => { }]); const initial = snapshot(); const initialTracking = tracking; + grouped.isRead.set(false, undefined); + await retry(async () => assert.deepStrictEqual(snapshot().find(section => section.id === SessionInboxSection.ReadyForYou)?.sessions, ['grouped']), 10, 100); + grouped.isRead.set(true, undefined); + await retry(async () => assert.deepStrictEqual(snapshot(), initial), 10, 100); running.status.set(SessionStatus.NeedsInput, undefined); attention.set(new Map([...attention.get(), ['ready', { tab: InboxTab.ReadyForYou, priority: InboxNotificationPriority.Now, notificationIds: ['review'], isHistoricalCompletion: false }]]), undefined); await new Promise(resolve => disposables.add(scheduleAtNextAnimationFrame(mainWindow, () => resolve()))); - const readyForYou = list.getTreeSnapshot().flatMap(node => node.type === 'session' ? [node.session.sessionId] : []); + const readyForYou = list.getTreeSnapshot().flatMap(node => node.type === 'section' && node.id === SessionInboxSection.ReadyForYou ? node.children.flatMap(child => child.type === 'session' ? [child.session.sessionId] : []) : []); list.setVisible(false); const hiddenTracking = tracking; list.setVisible(true); @@ -5235,9 +5526,9 @@ suite('Sessions - SessionsList', () => { assert.deepStrictEqual({ initial, readyForYou, restored, archived: grouped.isArchived.get(), tracking: [initialTracking, hiddenTracking, shownTracking, ordinaryTracking, tracking] }, { initial: [ { id: 'pinned', sessions: ['pinned'] }, + { id: SessionInboxSection.ReadyForYou, sessions: [] }, { id: SessionInboxSection.Working, sessions: ['running'] }, { id: SessionInboxSection.ReadyToMerge, sessions: ['ready'] }, - { id: SessionInboxSection.OnHold, sessions: [] }, { id: SessionInboxSection.Done, sessions: ['grouped'] }, ], readyForYou: ['ready', 'running'], restored: ['grouped'], archived: false, tracking: [1, 0, 1, 0, 0], @@ -5278,6 +5569,7 @@ suite('Sessions - SessionsList', () => { const tabElements = container.querySelectorAll('[role="tablist"], [role="tab"], [role="tabpanel"]').length; list.setItemCollapsed({ section: SessionInboxSection.Working }, true); const revealed = list.reveal(held.resource); + const revealedVisible = list.getVisibleSessions().map(session => session.sessionId); grouping = SessionsGrouping.Workspace; list.update(); grouping = SessionsGrouping.Inbox; @@ -5293,68 +5585,52 @@ suite('Sessions - SessionsList', () => { list.dispose(); const restored = snapshot(create().list); assert.deepStrictEqual({ - groups, tabElements, revealed, afterGroupingChange, restored, + groups, tabElements, revealed, revealedVisible, afterGroupingChange, restored, triage: [model.getInboxState(held)?.kind, model.getInboxState(done)?.kind], }, { groups: [ ['pinned', ['pinned']], - ['ready', []], + [SessionInboxSection.ReadyForYou, ['ready']], [SessionInboxSection.Working, ['working']], [SessionInboxSection.ReadyToMerge, ['merge']], - [SessionInboxSection.OnHold, ['held']], + [SessionInboxSection.OnHold, []], [SessionInboxSection.Done, ['done']], ], tabElements: 0, revealed: true, - afterGroupingChange: { workingCollapsed: true, sessions: ['pinned', 'ready', 'held'] }, - restored: { workingCollapsed: true, sessions: ['pinned', 'ready', 'held'] }, + revealedVisible: ['pinned', 'ready', 'held', 'done'], + afterGroupingChange: { workingCollapsed: true, sessions: ['pinned', 'ready', 'done'] }, + restored: { workingCollapsed: true, sessions: ['pinned', 'ready', 'done'] }, triage: ['hold', 'done'], }); }); - test('empty inbox categories keep counts aligned and cannot expand, including after their sessions leave', () => { + test('empty inbox categories disappear and reappear as sessions arrive', () => { const harness = createListHarness(disposables, []); harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); const container = harness.createContainer(); - container.style.setProperty('--vscode-spacing-size40', '4px'); const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, container, { grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, })); list.layout(400, 320); - const workingRow = () => list.getItemRow({ section: SessionInboxSection.Working })!; - const countRight = (section: SessionInboxSection) => list.getItemRow({ section })!.querySelector('.session-section-count')!.getBoundingClientRect().right; - const alignment = () => countRight(SessionInboxSection.Working) - countRight(SessionInboxSection.ReadyToMerge); - const emptyState = () => ({ - chevron: !!workingRow().querySelector('.session-section-chevron.collapsible'), - expanded: workingRow().getAttribute('aria-expanded'), - canExpand: list.setItemCollapsed({ section: SessionInboxSection.Working }, false), - }); - const initial = emptyState(); - const rest = alignment(); - workingRow().classList.add('hovered'); - const hovered = alignment(); - workingRow().classList.remove('hovered'); - list.setFocusedItem({ section: SessionInboxSection.Working }); - list.focus(); - const focused = alignment(); - + const sections = () => list.getTreeSnapshot().flatMap(node => node.type === 'section' ? [node.id] : []); + const initial = sections(); harness.managementService.sessions = [createTestSession('working', { status: SessionStatus.InProgress }).session]; list.refresh(); list.setHeaderCollapsed(SessionInboxSection.Working, false); - const populated = workingRow().getAttribute('aria-expanded'); + const populated = { sections: sections(), visible: list.getVisibleSessions().map(session => session.sessionId) }; harness.managementService.sessions = []; list.refresh(); - assert.deepStrictEqual({ initial, rest, hovered, focused, populated, emptied: emptyState() }, { - initial: { chevron: false, expanded: null, canExpand: false }, - rest: 0, hovered: 0, focused: 0, - populated: 'true', - emptied: { chevron: false, expanded: null, canExpand: false }, + assert.deepStrictEqual({ initial, populated, emptied: sections() }, { + initial: [SessionInboxSection.ReadyForYou], + populated: { sections: [SessionInboxSection.ReadyForYou, SessionInboxSection.Working], visible: ['working'] }, + emptied: [SessionInboxSection.ReadyForYou], }); }); - test('inbox footer stays anchored, expands independently, resizes by keyboard, and never collapses primary sessions', () => { + test('inbox uses one scrolling tree and keeps its primary category expanded', () => { const ready = createTestSession('ready').session; - const working = Array.from({ length: 20 }, (_, i) => createTestSession(`working-${i}`, { status: SessionStatus.InProgress }).session); + const working = Array.from({ length: 20 }, (_, i) => createTestSession(`working-${i}`, { status: SessionStatus.InProgress, createdAt: new Date(100 - i) }).session); const harness = createListHarness(disposables, [ready, ...working]); harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); const container = harness.createContainer(); @@ -5362,68 +5638,43 @@ suite('Sessions - SessionsList', () => { grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, })); list.layout(600, 320); - const footer = container.querySelector('.sessions-list-inbox-footer')!; const primary = container.querySelector('.sessions-list-primary')!; - const initial = { height: footer.clientHeight, ready: list.getVisibleSessions().map(session => session.sessionId) }; + const initial = list.getVisibleSessions().map(session => session.sessionId); list.setHeaderCollapsed(SessionInboxSection.Working, false); - const expanded = footer.clientHeight; - const handle = container.querySelector('.sessions-list-inbox-resize')!; - handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })); - const resized = footer.clientHeight; + const expanded = list.getVisibleSessions().length; + list.reveal(working[19].resource); + const scrolled = list.scrollTop > 0; list.layout(800, 320); - const manualSizePreserved = footer.clientHeight === resized; - handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true })); - const bounded = primary.clientHeight >= list.getItemRow({ session: ready.resource })!.clientHeight; - const bottom = Math.round(footer.getBoundingClientRect().bottom - list.element.getBoundingClientRect().bottom); + const resized = primary.clientHeight; list.collapseAllSections(); assert.deepStrictEqual({ - initial, grew: expanded > initial.height, shrank: resized < expanded, manualSizePreserved, bounded, bottom, + initial, expanded, scrolled, resized, trees: container.querySelectorAll('[role="tree"]').length, visible: list.getVisibleSessions().map(session => session.sessionId), collapsibleInbox: list.setItemCollapsed({ section: SessionInboxSection.ReadyForYou }, true), - footerRestored: footer.clientHeight === initial.height, }, { - initial: { height: 104, ready: ['ready'] }, grew: true, shrank: true, manualSizePreserved: true, bounded: true, bottom: 0, - visible: ['ready'], collapsibleInbox: false, footerRestored: true, + initial: ['ready'], expanded: 21, scrolled: true, resized: 800, trees: 1, + visible: ['ready'], collapsibleInbox: false, }); }); - test('expanded inbox categories reclaim unused space and rebalance when primary sessions change', () => { - const working = Array.from({ length: 20 }, (_, i) => createTestSession(`working-${i}`, { status: SessionStatus.InProgress }).session); - const ready = Array.from({ length: 20 }, (_, i) => createTestSession(`ready-${i}`).session); - const harness = createListHarness(disposables, working); - harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); + test('inbox groups held sessions by workspace without changing their custom membership', () => { + const a = buildTestSession({ id: 'a', title: 'A', workspace: 'Alpha' }).session; + const b = buildTestSession({ id: 'b', title: 'B', workspace: 'Beta' }).session; + const harness = createListHarness(disposables, [a, b], { groups: [{ id: 'saved', name: 'Saved', createdAt: 1 }], memberships: new Map([['a', 'saved']]) }); + const model = disposables.add(harness.instantiationService.createInstance(SessionsListModelService)); + harness.instantiationService.stub(ISessionsListModelService, model); + model.setInboxState([a, b], 'hold'); const container = harness.createContainer(); const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, container, { grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, })); list.layout(600, 320); - list.setHeaderCollapsed(SessionInboxSection.Working, false); - const footer = container.querySelector('.sessions-list-inbox-footer')!; - const primary = container.querySelector('.sessions-list-primary')!; - const empty = { categoriesUseSpareSpace: footer.clientHeight > 500, emptyMessageVisible: primary.clientHeight >= 26 }; - - harness.managementService.sessions = [...ready.slice(0, 2), ...working]; - list.refresh(); - const few = { - categoriesUseSpareSpace: footer.clientHeight > 500, - inboxRowsFit: ready.slice(0, 2).every(session => list.getItemRow({ session: session.resource })!.getBoundingClientRect().bottom <= primary.getBoundingClientRect().bottom), - }; - - harness.managementService.sessions = [...ready, ...working]; - list.refresh(); - const full = { primaryHeight: primary.clientHeight, footerHeight: footer.clientHeight }; - - harness.managementService.sessions = working; - list.refresh(); - const reclaimed = footer.clientHeight > 500; - list.layout(300, 320); - const smallWindow = { categoriesUseSpareSpace: footer.clientHeight > 250, emptyMessageVisible: primary.clientHeight >= 26 }; - assert.deepStrictEqual({ empty, few, full, reclaimed, smallWindow }, { - empty: { categoriesUseSpareSpace: true, emptyMessageVisible: true }, - few: { categoriesUseSpareSpace: true, inboxRowsFit: true }, - full: { primaryHeight: 360, footerHeight: 240 }, - reclaimed: true, - smallWindow: { categoriesUseSpareSpace: true, emptyMessageVisible: true }, + list.setHeaderCollapsed(SessionInboxSection.OnHold, false); + const held = list.getTreeSnapshot().find(node => node.type === 'section' && node.id === SessionInboxSection.OnHold); + const groups = held?.type === 'section' ? held.children.flatMap(node => node.type === 'section' ? [{ id: node.id, sessions: node.children.flatMap(child => child.type === 'session' ? [child.session.sessionId] : []) }] : []) : []; + assert.deepStrictEqual({ groups, membership: harness.instantiationService.get(ISessionGroupsService).getGroupOfSession('a') }, { + groups: [{ id: 'inbox:onHold:workspace:Alpha', sessions: ['a'] }, { id: 'inbox:onHold:workspace:Beta', sessions: ['b'] }], + membership: 'saved', }); }); @@ -5516,7 +5767,7 @@ suite('Sessions - SessionsList', () => { }; list.closeFind(); await timeout(350); - assert.deepStrictEqual(focus, { footer: grouping === SessionsGrouping.Inbox, primary: grouping !== SessionsGrouping.Inbox, session: 'working' }); + assert.deepStrictEqual(focus, { footer: false, primary: true, session: 'working' }); }); } } @@ -6868,11 +7119,161 @@ suite('Sessions - SessionsList', () => { assert.deepStrictEqual(headers(), ['Triage', 'Recent', 'Release work', 'Older', 'Archived']); }); + + test('headers dropped onto "+N more workspaces" or a workspace it reveals land above it', () => { + const now = Date.now(); + const daysAgo = (days: number) => new Date(now - days * 24 * 60 * 60_000); + const sessions = [ + createTestSession('Fresh', { workspaceLabel: 'recent', createdAt: daysAgo(0) }).session, + createTestSession('Alpha', { workspaceLabel: 'alpha', createdAt: daysAgo(10) }).session, + createTestSession('Bravo', { workspaceLabel: 'bravo', createdAt: daysAgo(11) }).session, + createTestSession('Charlie', { workspaceLabel: 'charlie', createdAt: daysAgo(12) }).session, + ]; + const harness = createListHarness(disposables, sessions); + const storageService = harness.instantiationService.get(IStorageService); + storageService.store('sessionsListControl.groups', JSON.stringify({ groups: [triage], membership: {} }), 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({ + onDidChangeSessions: Event.None, + onDidDeleteSession: Event.None, + onDidArchiveSession: Event.None, + onWillSendRequest: Event.None, + onDidReplaceNewDraftSession: Event.None, + onDidReplaceSession: Event.None, + onDidStartSession: Event.None, + onDidDiscardNewSession: Event.None, + onDidAcceptNewSessionRequest: Event.None, + onDidEndNewSessionRequest: Event.None, + onDidMoveChat: Event.None, + getSessions: () => sessions, + getInFlightNewSessionRequests: () => [], + getSession: () => undefined, + }), orderService))); + const container = harness.createContainer(400, 800); + harness.store.add(harness.instantiationService.createInstance(TestSessionsList, container, { + grouping: () => SessionsGrouping.Workspace, + sorting: () => SessionsSorting.Created, + onSessionOpen: () => { }, + })).layout(800, 400); + const rows = () => [...container.querySelectorAll('.monaco-list-row')].sort((a, b) => parseFloat(a.style.top) - parseFloat(b.style.top)); + const rowLabel = (row: HTMLElement) => row.querySelector('.session-group, .session-section') ? labelOf(row) : row.querySelector('.session-show-more-label')?.textContent; + const headers = () => rows().flatMap(row => rowLabel(row) ?? []); + const rowNamed = (label: string) => { + const row = rows().find(candidate => rowLabel(candidate) === label); + assert.ok(row, `Expected a "${label}" row`); + return row; + }; + const drag = (source: string, target: string, fraction: number) => { + let feedback: string[] = []; + dragRow(rowNamed(source), rowNamed(target), fraction, () => { + feedback = rows().filter(row => /drop-target/.test(row.className)).map(row => `${rowLabel(row)}: ${[...row.classList].filter(name => name.startsWith('drop-target')).join(' ')}`); + }); + return { feedback, headers: headers() }; + }; + + const collapsed = headers(); + const triageOntoMore = drag('Triage', '+3 more workspaces', 0.5); + clickRow(rowNamed('+3 more workspaces')); + const expanded = headers(); + const charlieOntoAlpha = drag('charlie', 'alpha', 0.1); + const bravoOntoShowFewer = drag('bravo', 'Show fewer workspaces', 0.5); + clickRow(rowNamed('Show fewer workspaces')); + + assert.deepStrictEqual({ collapsed, triageOntoMore, expanded, charlieOntoAlpha, bravoOntoShowFewer, collapsedAgain: headers() }, { + collapsed: ['Triage', 'recent', '+3 more workspaces'], + triageOntoMore: { feedback: ['+3 more workspaces: drop-target-before'], headers: ['recent', 'Triage', '+3 more workspaces'] }, + expanded: ['recent', 'Triage', 'alpha', 'bravo', 'charlie', 'Show fewer workspaces'], + // A revealed workspace dropped among the revealed ones lands above them and stays visible. + charlieOntoAlpha: { feedback: ['alpha: drop-target-before'], headers: ['recent', 'Triage', 'charlie', 'alpha', 'bravo', 'Show fewer workspaces'] }, + bravoOntoShowFewer: { feedback: ['alpha: drop-target-before'], headers: ['recent', 'Triage', 'charlie', 'bravo', 'alpha', 'Show fewer workspaces'] }, + collapsedAgain: ['recent', 'Triage', 'charlie', 'bravo', '+1 more workspace'], + }); + }); }); suite('section collapse persistence', () => { const group: ISessionGroup = { id: 'group-1', name: 'My Group', createdAt: 1 }; + test('revealing an active nested chat does not persist its Inbox category expansion', async () => { + const foreground = buildTestSession({ + id: 'foreground', title: 'Foreground', status: SessionStatus.InProgress, + chats: [{ id: 'peer', title: 'Peer', status: SessionStatus.InProgress }], + }); + const peer = foreground.chats.get('peer')!; + const background = createTestSession('background', { status: SessionStatus.InProgress }).session; + const shown = observableValue(disposables, undefined); + const harness = createListHarness(disposables, [foreground.session]); + harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); + stubSessionHosts(harness.instantiationService, disposables, { session: shown }); + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, + })); + list.layout(400, 320); + list.setItemCollapsed({ section: SessionInboxSection.Working }, true); + shown.set({ session: foreground.session, chat: peer.chat }, undefined); + await retry(async () => assert.strictEqual(list.getItemRow({ section: SessionInboxSection.Working })?.getAttribute('aria-expanded'), 'true'), 10, 100); + list.refresh(); + const viewing = list.getItemRow({ section: SessionInboxSection.Working })?.getAttribute('aria-expanded'); + shown.set(undefined, undefined); + transaction(tx => { + foreground.status.set(SessionStatus.Completed, tx); + foreground.mainChat.status.set(SessionStatus.Completed, tx); + peer.status.set(SessionStatus.Completed, tx); + }); + list.update(); + harness.managementService.sessions.push(background); + list.refresh(); + assert.deepStrictEqual({ + viewing, + backgroundExpanded: list.getItemRow({ section: SessionInboxSection.Working })?.getAttribute('aria-expanded'), + count: list.getItemRow({ section: SessionInboxSection.Working })?.querySelector('.session-section-count')?.textContent, + }, { viewing: 'true', backgroundExpanded: 'false', count: '1' }); + }); + + for (const savedCollapsed of [undefined, true, false]) { + test(`viewing a Working session does not expand later background sessions (saved collapse: ${savedCollapsed})`, () => { + const foreground = createTestSession('foreground', { status: SessionStatus.InProgress }); + const background = createTestSession('background', { status: SessionStatus.InProgress }).session; + const another = createTestSession('another', { status: SessionStatus.InProgress }).session; + const harness = createListHarness(disposables, [foreground.session]); + harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); + const storageService = harness.instantiationService.get(IStorageService); + if (savedCollapsed !== undefined) { + storageService.store('sessionsListControl.sectionCollapseState', JSON.stringify({ [SessionInboxSection.Working]: savedCollapsed }), StorageScope.PROFILE, StorageTarget.USER); + } + const list = disposables.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, + })); + list.layout(400, 320); + const snapshot = () => ({ + expanded: list.getItemRow({ section: SessionInboxSection.Working })?.getAttribute('aria-expanded'), + count: list.getItemRow({ section: SessionInboxSection.Working })?.querySelector('.session-section-count')?.textContent, + }); + list.reveal(foreground.session.resource); + list.refresh(); + const viewing = snapshot(); + foreground.status.set(SessionStatus.Completed, undefined); + list.update(); + const empty = snapshot(); + harness.managementService.sessions.push(background); + list.refresh(); + const firstBackground = snapshot(); + harness.managementService.sessions.push(another); + list.refresh(); + const secondBackground = snapshot(); + list.reveal(background.resource); + list.refresh(); + assert.deepStrictEqual({ viewing, empty, firstBackground, secondBackground, opened: snapshot() }, { + viewing: { expanded: 'true', count: '1' }, + empty: { expanded: undefined, count: undefined }, + firstBackground: { expanded: savedCollapsed === false ? 'true' : 'false', count: '1' }, + secondBackground: { expanded: savedCollapsed === false ? 'true' : 'false', count: '2' }, + opened: { expanded: 'true', count: '2' }, + }); + }); + } + function createHarness(seededState?: Record) { const grouped = createTestSession('Grouped', { workspaceLabel: 'vscode' }).session; const ungrouped = createTestSession('Ungrouped', { workspaceLabel: 'vscode' }).session; @@ -7389,6 +7790,11 @@ suite('Sessions - SessionsList', () => { suite('comparison groups', () => { const group: ISessionGroup = { id: 'comparison-group', name: 'Compare: Improve the picker', createdAt: 1 }; + const comparisonConfiguration = [ + 'Original comparison settings', `Repository: ${isWindows ? '\\workspace' : '~/workspace'}`, 'Isolation: Separate worktrees', + 'Attempt 1: Copilot · Claude Opus 5', 'Attempt 2: Copilot · Balance', + 'Judge: Copilot · Claude Opus 5', 'Synthesizer: Copilot · Claude Opus 5', + ].join('\n'); function renderComparison(verdict?: ISessionComparison['verdict'], sessionVariant: 'all' | 'attempt1' | 'none' | 'launching' = 'all', pinnedSessionIds: ReadonlySet = new Set(), includeOrdinaryWorkspace = false, grouping = SessionsGrouping.Workspace, sectionParent?: ISessionGroup, configure?: (harness: ReturnType) => void, mixedHarnesses = false, presentation: { compact?: boolean; phone?: boolean } = {}) { const attempt1 = createTestSession('Stored attempt one', { resourceId: 'attempt-1', status: SessionStatus.InProgress }); @@ -7513,7 +7919,7 @@ suite('Sessions - SessionsList', () => { test('inbox keeps comparisons together, prioritizes input over recency, ignores manual sorting, and hides group archiving', () => { const { harness, list, container, attempt1, attempt2, judge, synthesis } = renderComparison(undefined, 'all', new Set(), false, SessionsGrouping.Inbox, undefined, harness => { - harness.managementService.sessions.push(createTestSession('Recent', { resourceId: 'recent', updatedAt: new Date(2100, 0, 1) }).session); + harness.managementService.sessions.push(createTestSession('Recent', { resourceId: 'recent', createdAt: new Date(2100, 0, 1), updatedAt: new Date(2100, 0, 1) }).session); const model = disposables.add(harness.instantiationService.createInstance(SessionsListModelService)); harness.instantiationService.stub(ISessionsListModelService, model); model.applySortChanges('created', new Map([['group:comparison-group', Number.MAX_SAFE_INTEGER]]), []); @@ -7524,7 +7930,7 @@ suite('Sessions - SessionsList', () => { harness.instantiationService.stub(IMenuService, disposables.add(harness.instantiationService.createInstance(MenuService))); disposables.add(harness.instantiationService.createInstance(SessionsArchiveActionsContribution)); }); - const order = () => list.getTreeSnapshot().flatMap(node => node.type === 'session' ? [node.session.sessionId] : node.type === 'group' ? [node.id] : []); + const order = () => list.getTreeSnapshot().flatMap(node => node.type === 'section' && node.id === SessionInboxSection.ReadyForYou ? node.children.flatMap(child => child.type === 'session' ? [child.session.sessionId] : child.type === 'group' ? [child.id] : []) : []); attempt1.status.set(SessionStatus.NeedsInput, undefined); list.update(true); const waiting = order(); @@ -7537,6 +7943,30 @@ suite('Sessions - SessionsList', () => { }); }); + test('comparison parent exposes saved model configurations in its hover and accessible label', () => { + const hovers = new Map IDelayedHoverOptions>(); + const { container, harness } = renderComparison(undefined, 'all', new Set(), false, SessionsGrouping.Workspace, undefined, harness => { + harness.instantiationService.stub(IHoverService, { + ...NullHoverService, + setupDelayedHover: (target, options) => { + hovers.set(target, typeof options === 'function' ? options : () => options); + return toDisposable(() => hovers.delete(target)); + }, + }); + }, true); + const parent = container.querySelector('.session-comparison-group')!; + const content = hovers.get(parent)?.().content; + const ariaLabel = parent.closest('.monaco-list-row')?.getAttribute('aria-label'); + assert.deepStrictEqual({ + content, + accessible: typeof content === 'string' && ariaLabel?.includes(content), + }, { + content: comparisonConfiguration.replace('Attempt 2: Copilot', 'Attempt 2: Claude'), + accessible: true, + }); + harness.store.dispose(); + }); + test('inbox groups retain comparison groups in their highest-attention category', () => { const { list, attempt1 } = renderComparison(undefined, 'all', new Set(), false, SessionsGrouping.Inbox, undefined, harness => { harness.managementService.sessions.push(createTestSession('Recent', { resourceId: 'recent' }).session); @@ -7545,12 +7975,7 @@ suite('Sessions - SessionsList', () => { attempt1.status.set(SessionStatus.NeedsInput, undefined); list.update(true); assert.deepStrictEqual(list.getTreeSnapshot().map(node => node.type === 'session' ? [node.session.sessionId, []] : [node.id, node.children.map(child => child.type === 'session' ? child.session.sessionId : child.id)]), [ - ['group:comparison-group', ['synthesis', 'judge', 'attempt-1', 'attempt-2']], - ['recent', []], - [SessionInboxSection.Working, []], - [SessionInboxSection.ReadyToMerge, []], - [SessionInboxSection.OnHold, []], - [SessionInboxSection.Done, []], + [SessionInboxSection.ReadyForYou, ['group:comparison-group', 'recent']], ]); }); @@ -7747,7 +8172,7 @@ suite('Sessions - SessionsList', () => { title: 'Improve the picker', summary: 'Comparison · 2 attempts working', layersIcon: true, - ariaLabel: 'Improve the picker, Comparison · 2 attempts working', + ariaLabel: `Improve the picker, Comparison · 2 attempts working, ${comparisonConfiguration}`, connector: null, childOrder: [ 'session-section-chevron collapsible codicon codicon-chevron-down', @@ -8558,7 +8983,7 @@ suite('Sessions - SessionsList', () => { ariaLabel: parent?.closest('.monaco-list-row')?.getAttribute('aria-label'), }, { summary: 'Comparison · Review ready', - ariaLabel: 'Improve the picker, Comparison · Review ready', + ariaLabel: `Improve the picker, Comparison · Review ready, ${comparisonConfiguration}`, }); }); }); @@ -9222,7 +9647,7 @@ suite('Sessions - SessionsList', () => { solidTitle: true, inProgress: false, warningIcon: true, - color: 'var(--vscode-list-warningForeground)', + color: 'var(--vscode-agentSessionNeedsInput-foreground)', ariaLabel: 'Waiting, updated now, State: Attention Needed', }); }); @@ -9787,6 +10212,32 @@ suite('Sessions - SessionsList', () => { return [...container.querySelectorAll('.session-chat-title')].map(element => element.textContent ?? ''); } + test('marks a collapsed parent session, but not a leaf session, as a disclosure row', () => { + const main = createChat('Main chat', ChatOriginKind.User); + const peer = createChat('Peer chat', ChatOriginKind.User); + const parentBase = createTestSession('Parent').session; + const parent: ISession = { + ...parentBase, + chats: constObservable([main, peer]), + mainChat: constObservable(main), + capabilities: constObservable({ supportsMultipleChats: true }), + }; + const parentContainer = renderSessionChatsList(parent, undefined, false, false).container; + const leafContainer = renderSessionChatsList(createTestSession('Leaf').session, undefined, false, false).container; + const parentRow = parentContainer.querySelector('.session-item')?.closest('.monaco-list-row'); + const leafRow = leafContainer.querySelector('.session-item')?.closest('.monaco-list-row'); + + assert.deepStrictEqual({ + parentCollapsed: parentRow?.getAttribute('aria-expanded'), + parentDisclosure: parentRow?.classList.contains('sessions-disclosure-row'), + leafDisclosure: leafRow?.classList.contains('sessions-disclosure-row'), + }, { + parentCollapsed: 'false', + parentDisclosure: true, + leafDisclosure: false, + }); + }); + /** Section, session and chat rows top to bottom, indented by nesting; done sessions and standalone chats are marked. */ function renderedTreeRows(container: HTMLElement): string[] { return [...container.querySelectorAll('.monaco-list-row')] @@ -10425,6 +10876,21 @@ suite('Sessions - SessionsList', () => { }); }); + test('labels the row of a multi-folder session with the folder of its main chat', () => { + const folder = (name: string): ISessionFolder => ({ root: URI.file(`/workspace/${name}`), workingDirectory: URI.file(`/workspace/${name}`), name, description: undefined }); + const engineering = folder('engineering'); + const tools = folder('tools'); + const rowLabel = (session: ISession) => renderSessionChatsList(session, undefined, false, false).container.querySelector('.session-item .session-badge')?.textContent; + + assert.deepStrictEqual({ + mainChatMovedToOtherFolder: rowLabel(createMultiFolderSession([engineering, tools], [[tools], [engineering]])), + mainChatInFirstFolder: rowLabel(createMultiFolderSession([engineering, tools], [[engineering], [tools]])), + }, { + mainChatMovedToOtherFolder: 'tools', + mainChatInFirstFolder: 'engineering', + }); + }); + test('shows the own folder of a chat in a quick chat and no folder for its scratch chats', () => { const repo = { root: URI.file('/workspace/repo'), workingDirectory: URI.file('/workspace/repo'), name: 'repo', description: undefined }; const base = createTestSession('Quick chat', { isQuickChat: true }).session; @@ -11777,7 +12243,8 @@ suite('Sessions - SessionsList', () => { }; const container = renderSessionChats(session, undefined, true); - container.style.setProperty('--vscode-list-warningForeground', 'rgb(255, 0, 0)'); + container.style.setProperty('--vscode-list-warningForeground', 'rgb(0, 0, 255)'); + container.style.setProperty('--vscode-agentSessionNeedsInput-foreground', 'rgb(255, 0, 0)'); const parent = container.querySelector('.session-item')!; const child = container.querySelector('.session-chat-item')!; assert.deepStrictEqual([parent, child].map(item => { @@ -11797,6 +12264,74 @@ suite('Sessions - SessionsList', () => { ]); }); + for (const themeClass of ['hc-black', 'hc-light']) { + test(`needs-input rows use left-edge markers instead of tint in ${themeClass}`, () => { + const main = createChat('Main chat', undefined, ChatInteractivity.Full, SessionStatus.NeedsInput); + const waiting = createChat('Waiting chat', ChatOriginKind.User, ChatInteractivity.Full, SessionStatus.NeedsInput); + const session: ISession = { + ...createTestSession('Session', { status: SessionStatus.NeedsInput }).session, + chats: constObservable([main, waiting]), + mainChat: constObservable(main), + capabilities: constObservable({ supportsMultipleChats: true }), + }; + const container = renderSessionChats(session); + container.classList.add(themeClass); + container.style.setProperty('--vscode-spacing-size20', '2px'); + container.style.setProperty('--vscode-spacing-size40', '4px'); + container.style.setProperty('--vscode-agentSessionNeedsInput-foreground', 'rgb(255, 211, 112)'); + const parent = container.querySelector('.session-item')!; + const child = container.querySelector('.session-chat-item')!; + + assert.deepStrictEqual([parent, child].map(item => { + const row = item.closest('.monaco-list-row')!; + const background = item === parent ? row : item; + const style = mainWindow.getComputedStyle(background); + const indicator = item.querySelector('.session-attention-indicator')!; + const indicatorStyle = mainWindow.getComputedStyle(indicator); + const initial = { + background: style.backgroundColor, + borderWidth: style.borderLeftWidth, + marker: { + ariaHidden: indicator.getAttribute('aria-hidden'), + display: indicatorStyle.display, + width: indicatorStyle.width, + top: indicatorStyle.top, + bottom: indicatorStyle.bottom, + cornerRadius: indicatorStyle.borderRadius, + color: indicatorStyle.backgroundColor, + pointerEvents: indicatorStyle.pointerEvents, + }, + }; + const height = row.getBoundingClientRect().height; + const title = item.querySelector('.session-title, .session-chat-title')!; + const titleLeft = title.getBoundingClientRect().left; + row.classList.add('selected'); + const selected = { + markerDisplay: mainWindow.getComputedStyle(indicator).display, + sameHeight: row.getBoundingClientRect().height === height, + sameTitlePosition: title.getBoundingClientRect().left === titleLeft, + }; + row.classList.remove('selected'); + return { initial, selected }; + }), [ + { + initial: { + background: 'rgba(0, 0, 0, 0)', borderWidth: '0px', + marker: { ariaHidden: 'true', display: 'block', width: '2px', top: '4px', bottom: '4px', cornerRadius: '0px', color: 'rgb(255, 211, 112)', pointerEvents: 'none' }, + }, + selected: { markerDisplay: 'none', sameHeight: true, sameTitlePosition: true }, + }, + { + initial: { + background: 'rgba(0, 0, 0, 0)', borderWidth: '0px', + marker: { ariaHidden: 'true', display: 'block', width: '2px', top: '4px', bottom: '4px', cornerRadius: '0px', color: 'rgb(255, 211, 112)', pointerEvents: 'none' }, + }, + selected: { markerDisplay: 'none', sameHeight: true, sameTitlePosition: true }, + }, + ]); + }); + } + test('needs-input chat row keeps its attention indicator without looping animations', () => { const main = createChat('Main chat'); const waiting = createChat('Waiting chat', ChatOriginKind.User, ChatInteractivity.Full, SessionStatus.NeedsInput); @@ -12319,6 +12854,57 @@ suite('Sessions - SessionsList', () => { ]); }); + for (const themeClass of ['hc-black', 'hc-light']) { + test(`keeps grid-pin and attention markers separate in ${themeClass}`, () => { + const session = createTestSession('Pinned needs input', { status: SessionStatus.NeedsInput }).session; + const sticky = observableValue('sticky', true); + const gridSession = upcastPartial({ ...session, sticky }); + const harness = createListHarness(disposables, [session], instantiationService => { + instantiationService.stub(ISessionsService, new class extends mock() { + readonly activeSession = constObservable(undefined); + readonly gridShown = constObservable([gridSession]); + override readonly slotPanes = testGridPanes(this.gridShown); + }); + }); + const container = harness.createContainer(); + container.classList.add(themeClass); + container.style.setProperty('--vscode-spacing-size20', '2px'); + container.style.setProperty('--vscode-spacing-size40', '4px'); + container.style.setProperty('--vscode-spacing-size80', '8px'); + container.style.setProperty('--vscode-focusBorder', 'rgb(0, 128, 255)'); + container.style.setProperty('--vscode-agentSessionNeedsInput-foreground', 'rgb(255, 211, 112)'); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Date, + sorting: () => SessionsSorting.Created, + onSessionOpen: () => { }, + })); + list.layout(300, 400); + const item = container.querySelector('.session-item.needs-input')!; + const indicator = item.querySelector('.session-attention-indicator')!; + const snapshot = () => { + const pin = mainWindow.getComputedStyle(item, '::before'); + const attention = mainWindow.getComputedStyle(indicator); + const pinRight = Number.parseFloat(pin.left) + Number.parseFloat(pin.width); + const attentionLeft = indicator.getBoundingClientRect().left - item.getBoundingClientRect().left; + return { + pinned: item.classList.contains('sticky'), + idle: !item.closest('.monaco-list-row')!.matches('.selected, .focused, :hover'), + attentionVisible: attention.display === 'block', + attentionColor: attention.backgroundColor, + separateFromPin: pin.content === 'none' || pinRight <= attentionLeft, + pinColor: pin.content === 'none' ? undefined : pin.backgroundColor, + }; + }; + const pinned = snapshot(); + sticky.set(false, undefined); + + assert.deepStrictEqual({ pinned, unpinned: snapshot() }, { + pinned: { pinned: true, idle: true, attentionVisible: true, attentionColor: 'rgb(255, 211, 112)', separateFromPin: true, pinColor: 'rgb(0, 128, 255)' }, + unpinned: { pinned: false, idle: true, attentionVisible: true, attentionColor: 'rgb(255, 211, 112)', separateFromPin: true, pinColor: undefined }, + }); + }); + } + test('coalesces restored active chat selection without flashing the parent session', async () => { const main = createChat('Main chat'); const first = createChat('First chat', ChatOriginKind.User); @@ -12541,6 +13127,49 @@ suite('Sessions - SessionsList', () => { }); }); + test('drags a session, and a nested chat, with a reference to the chat it stands for, which a chat input can attach', () => { + const main = createChat('Main chat'); + const peer = createChat('Peer chat', ChatOriginKind.User); + const base = createTestSession('Session').session; + const session: ISession = { + ...base, + chats: constObservable([main, peer]), + mainChat: constObservable(main), + capabilities: constObservable({ supportsMultipleChats: true }), + }; + const toBackend = (resource: URI) => resource.with({ scheme: 'backend-chat' }); + const provider: ISessionsProvider = upcastPartial({ + id: LOCAL_AGENT_HOST_PROVIDER_ID, + environment: { id: 'local', label: 'This Computer' }, + getBackendChatResource: toBackend, + }); + const { container } = renderSessionChatsList(session, undefined, false, true, false, instantiationService => { + instantiationService.stub(ISessionsProvidersService, new class extends mock() { + override readonly onDidChangeProviders = Event.None; + override getProviders() { return [provider]; } + override getProvider(): T | undefined { return provider as T; } + }); + }); + const rowOf = (selector: string, title: string) => [...container.querySelectorAll(selector)] + .find(element => element.textContent === title)?.closest('.monaco-list-row'); + const dragReference = (row: HTMLElement | null | undefined) => { + assert.ok(row); + const dataTransfer = new DataTransfer(); + row.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer })); + const reference = extractChatReferenceDropData(new DragEvent('dragover', { dataTransfer })); + row.dispatchEvent(new DragEvent('dragend', { bubbles: true, cancelable: true, dataTransfer })); + return reference; + }; + + assert.deepStrictEqual({ + session: dragReference(rowOf('.session-title', 'Session')), + chat: dragReference(rowOf('.session-chat-title', 'Peer chat')), + }, { + session: { chatResource: toBackend(main.resource).toString(), clientResource: main.resource.toString(), title: 'Main chat' }, + chat: { chatResource: toBackend(peer.resource).toString(), clientResource: peer.resource.toString(), title: 'Peer chat' }, + }); + }); + test('drops a session onto a nested chat row below the chat\'s session', () => { const now = Date.now(); const main = createChat('Main chat'); @@ -13226,37 +13855,54 @@ suite('Sessions - SessionsList', () => { } } - test('keeps the static warning tint on a sticky needs-input session row', async () => { - const main = createChat('Main chat', ChatOriginKind.User, ChatInteractivity.Full, SessionStatus.NeedsInput); - const peers = Array.from({ length: 30 }, (_, index) => createChat(`Chat ${index}`, ChatOriginKind.User)); - const session: ISession = { - ...createTestSession('Pending approval', { status: SessionStatus.NeedsInput }).session, - chats: constObservable([main, ...peers]), - mainChat: constObservable(main), - capabilities: constObservable({ supportsMultipleChats: true }), - }; - const harness = createListHarness(disposables, [session]); - const container = harness.createContainer(400, 600); - container.style.setProperty('--vscode-list-warningForeground', 'rgb(255, 0, 0)'); - const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { - grouping: () => SessionsGrouping.Date, - sorting: () => SessionsSorting.Created, - compact: () => true, - onSessionOpen: () => { }, - })); - list.layout(600, 400); - setSessionChatsExpanded(container, true); - await timeout(0); - const tree = Reflect.get(list, 'tree') as { scrollTop: number }; - let stickyImage: string | undefined; - for (let position = 0; position < 900 && !stickyImage; position += 75) { - tree.scrollTop = position; + for (const themeClass of ['', 'hc-black', 'hc-light']) { + test(`keeps the attention ${themeClass ? 'marker' : 'tint'} on a sticky needs-input session row${themeClass ? ` in ${themeClass}` : ''}`, async () => { + const main = createChat('Main chat', ChatOriginKind.User, ChatInteractivity.Full, SessionStatus.NeedsInput); + const peers = Array.from({ length: 30 }, (_, index) => createChat(`Chat ${index}`, ChatOriginKind.User)); + const session: ISession = { + ...createTestSession('Pending approval', { status: SessionStatus.NeedsInput }).session, + chats: constObservable([main, ...peers]), + mainChat: constObservable(main), + capabilities: constObservable({ supportsMultipleChats: true }), + }; + const harness = createListHarness(disposables, [session]); + const container = harness.createContainer(400, 600); + if (themeClass) { + container.classList.add(themeClass); + } + container.style.setProperty('--vscode-spacing-size20', '2px'); + container.style.setProperty('--vscode-list-warningForeground', 'rgb(0, 0, 255)'); + container.style.setProperty('--vscode-agentSessionNeedsInput-foreground', 'rgb(255, 0, 0)'); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Date, + sorting: () => SessionsSorting.Created, + compact: () => true, + onSessionOpen: () => { }, + })); + list.layout(600, 400); + setSessionChatsExpanded(container, true); await timeout(0); - const sticky = Array.from(container.querySelectorAll('.monaco-tree-sticky-row')).find(row => row.querySelector('.session-item.needs-input')); - stickyImage = sticky ? mainWindow.getComputedStyle(sticky).backgroundImage : undefined; - } - assert.ok(stickyImage && stickyImage !== 'none'); - }); + const tree = Reflect.get(list, 'tree') as { scrollTop: number }; + let sticky: HTMLElement | undefined; + for (let position = 0; position < 900 && !sticky; position += 75) { + tree.scrollTop = position; + await timeout(0); + sticky = Array.from(container.querySelectorAll('.monaco-tree-sticky-row')).find(row => row.querySelector('.session-item.needs-input')); + } + assert.ok(sticky); + const style = mainWindow.getComputedStyle(sticky); + const indicator = sticky.querySelector('.session-attention-indicator')!; + assert.deepStrictEqual({ + hasTint: style.backgroundImage !== 'none', + borderWidth: style.borderLeftWidth, + hasAttentionMarker: mainWindow.getComputedStyle(indicator).display === 'block', + }, { + hasTint: !themeClass, + borderWidth: '0px', + hasAttentionMarker: !!themeClass, + }); + }); + } test('renders a pending approval on the owning chat row only, not on its siblings', () => { const main = createChat('Main chat'); @@ -13931,6 +14577,57 @@ suite('Sessions - SessionsList', () => { }); }); + test('names the folder an approval\'s command runs in, so the same command in two folders looks different', () => { + const approvals = new Map(); + const sessions = ([ + ['Test web', './test.sh', '/work/web'], + ['Test api', './test.sh', '/work/api\u202e'], + ['Push', 'git push origin main', undefined], + ] as const).map(([title, label, workingDirectory], index) => { + const { session } = createTestSession(title, { workspaceLabel: 'vscode', status: SessionStatus.NeedsInput, createdAt: new Date(Date.now() - index * 1000) }); + const resource = session.mainChat.get().resource.toString(); + approvals.set(resource, { + approvalId: resource, + kind: AgentSessionApprovalKind.Terminal, + label, + languageId: 'shellscript', + executionTarget: workingDirectory ? { workingDirectory } : undefined, + since: new Date(), + confirm: () => { }, + }); + return session; + }); + const approvalModel = new class extends mock() { + override getApproval(resource: URI): IObservable { + return constObservable(approvals.get(resource.toString())); + } + }(); + const harness = createListHarness(disposables, sessions); + const container = harness.createContainer(); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Date, + sorting: () => SessionsSorting.Created, + compact: () => true, + onSessionOpen: () => { }, + approvalModel, + })); + list.layout(500, 400); + + assert.deepStrictEqual([...container.querySelectorAll('.monaco-list-row')].flatMap(row => { + const approvalRow = row.querySelector('.session-approval-row.visible:not(.session-input-needed-row)'); + return approvalRow ? [{ + command: approvalRow.querySelector('.session-approval-label > .code')?.textContent, + directory: approvalRow.querySelector('.session-approval-working-directory-path')?.textContent, + allowAriaLabel: approvalRow.querySelector('.session-approval-button .monaco-button')?.getAttribute('aria-label'), + height: row.style.height, + }] : []; + }), [ + { command: './test.sh', directory: '/work/web', allowAriaLabel: 'Allow once: ./test.sh (Working directory: /work/web)', height: '80px' }, + { command: './test.sh', directory: '/work/api\\u{202e}', allowAriaLabel: 'Allow once: ./test.sh (Working directory: /work/api\\u{202e})', height: '80px' }, + { command: 'git push origin main', directory: undefined, allowAriaLabel: 'Allow once: git push origin main', height: '62px' }, + ]); + }); + test('refreshes compact presentation across phone layout transitions', () => { const session = createTestSession('Responsive compact session', { workspaceLabel: 'vscode', diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListChatMoveDnd.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListChatMoveDnd.test.ts index 4714bcc32858..48f077bf2f62 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListChatMoveDnd.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListChatMoveDnd.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import { ListViewTargetSector } from '../../../../../base/browser/ui/list/listView.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { setARIAContainer } from '../../../../../base/browser/ui/aria/aria.js'; +import { scheduleAtNextAnimationFrame } from '../../../../../base/browser/dom.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { constObservable, IObservable, ISettableObservable, observableValue } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; @@ -588,6 +589,12 @@ suite('Move Chats Drag and Drop - sessions list feedback', () => { (session.chats as ISettableObservable).set(chats, undefined); } + async function nextFrame(): Promise { + await new Promise(resolve => { + disposables.add(scheduleAtNextAnimationFrame(mainWindow, () => resolve(), -1000)); + }); + } + /** * Renders the sessions list with moving chats on, recording the moves it makes and any dialog it shows. With * `realListModel`, the list keeps its state in the real list model service, recording the storage keys it writes. @@ -742,7 +749,7 @@ suite('Move Chats Drag and Drop - sessions list feedback', () => { drop: async () => { targetElement.dispatchEvent(event('drop')); sourceRow.dispatchEvent(new DragEvent('dragend', { bubbles: true, dataTransfer })); - await timeout(0); + await nextFrame(); }, end: () => sourceRow.dispatchEvent(new DragEvent('dragend', { bubbles: true, dataTransfer })), }; @@ -946,7 +953,7 @@ suite('Move Chats Drag and Drop - sessions list feedback', () => { const keys = { a: focus(a), fixed: focus(fixed), c: focus(c) }; const movedFixed = list.list.moveChat(new SessionChatItem(own, fixed), 'up'); const movedC = list.list.moveChat(new SessionChatItem(own, c), 'up'); - await timeout(0); + await nextFrame(); const movedFirst = list.list.moveChat(new SessionChatItem(own, a), 'up'); assert.deepStrictEqual({ @@ -1030,7 +1037,7 @@ suite('Move Chats Drag and Drop - sessions list feedback', () => { const c = own.chats.get()[3]; list.list.moveChat(new SessionChatItem(own, c), 'up'); - await timeout(0); + await nextFrame(); assert.deepStrictEqual({ moves: list.moves, moved: list.chatRows(), focused: list.rendered().focused, selected: list.rendered().selected }, { moves: ['c -> Own after a'], @@ -1263,6 +1270,26 @@ suite('Move Chats Drag and Drop - sessions list feedback', () => { }); }); + test('after a same-session reorder, the list reveals the moved chat at its new position below the view', async () => { + const own = listSession('Own', ['a', 'b', 'c', 'd', 'e']); + const list = render([own], { height: 180, simulateMoves: true }); + list.setExpanded('Own', true); + await settle(); + const lastShownBefore = list.rendered().rows.includes('e'); + + await list.dragOver('a', 'Own', 0.5).drop(); + await settle(); + const after = list.rendered(); + + assert.deepStrictEqual({ lastShownBefore, moves: list.moves, movedShown: after.rows.includes('a'), focused: after.focused, selected: after.selected }, { + lastShownBefore: false, + moves: ['a -> Own after e'], + movedShown: true, + focused: ['a'], + selected: [], + }); + }); + test('after a move, the selection stays on the open chat, which is not the one the list reveals and focuses', async () => { const open = listSession('Open', []); const single = listSession('Single', [], listChat('Moved')); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListContextMenu.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListContextMenu.test.ts index 084a6bd78a5e..83374b979066 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListContextMenu.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListContextMenu.test.ts @@ -38,6 +38,7 @@ import { ARCHIVE_SESSION_COMMAND_ID, DELETE_SESSION_GROUP_WITH_UNDO_COMMAND_ID, import { SessionsListPromoteNewChatActionContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; import { ISessionGroup } from '../../../../../workbench/contrib/sessions/browser/sessionGroupsService.js'; +import { ISessionsListModelService, SessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; import { ISessionsPartService } from '../../../../../workbench/services/sessions/browser/sessionsPartService.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { ChatInteractivity, IChat, ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; @@ -117,6 +118,9 @@ suite('Sessions list context menus', () => { pinnedSessionIds, }); const commandService = harness.instantiationService.get(ICommandService); + if (grouping === SessionsGrouping.Inbox) { + harness.instantiationService.stub(ISessionsListModelService, disposables.add(harness.instantiationService.createInstance(SessionsListModelService))); + } harness.instantiationService.stub(IContextKeyService, contextKeyService); harness.instantiationService.stub(IContextMenuService, contextMenuService); harness.instantiationService.stub(IMenuService, new class extends mock() { @@ -206,6 +210,15 @@ suite('Sessions list context menus', () => { } }); + test('inbox does not offer unsupported group creation in empty space or category menus', () => { + const { container, contextMenuService } = createList(false, false, SessionsGrouping.Inbox); + dispatchContextMenu(container.querySelector('.monaco-list-rows')!); + const empty = contextMenuService.delegate?.getActions().some(action => action.id === 'sessions.createGroup') ?? false; + dispatchContextMenu(container.querySelector('.session-section')!); + const section = contextMenuService.delegate?.getActions().some(action => action.id === 'sessions.createGroup') ?? false; + assert.deepStrictEqual({ empty, section }, { empty: false, section: false }); + }); + test('multiselection disables single-session context menu actions', async () => { const first = createTestSession('First'); const second = createTestSession('Second'); @@ -286,6 +299,7 @@ suite('Sessions list context menus', () => { menu: [ 'Open in', 'New Nested Session', + 'Open Customizations', '---', 'Mark as Unread', 'Mark as Done', @@ -385,6 +399,7 @@ suite('Sessions list context menus', () => { }, { menu: [ 'Open in', + 'Open Customizations', '---', 'Mark as Unread', 'Mark as Done', diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts index 3459170facd2..b3099307a781 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts @@ -56,12 +56,18 @@ import { defaultMenuStyles } from '../../../../../platform/theme/browser/default import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { EditorMarkdownCodeBlockRenderer } from '../../../../../editor/browser/widget/markdownRenderer/browser/editorMarkdownCodeBlockRenderer.js'; import { AgentSessionApprovalKind, AgentSessionApprovalModel, IAgentSessionApprovalInfo } from '../../../../../workbench/contrib/chat/browser/agentSessions/agentSessionApprovalModel.js'; +import { IAgentHostCustomizationService } from '../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.js'; +import { IAICustomizationItemsModel } from '../../../../../workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { IAICustomizationWorkspaceService } from '../../../../../workbench/contrib/chat/common/aiCustomizationWorkspaceService.js'; import { ChatAutomationsEnabledContext } from '../../../../../workbench/contrib/chat/common/automations/automationsEnabled.js'; import { IAutomationService } from '../../../../../workbench/contrib/chat/common/automations/automationService.js'; import { IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; import { IChatSessionItemArchiveState } from '../../../../../workbench/contrib/chat/common/chatSessionsService.js'; import { IChatWidgetService } from '../../../../../workbench/contrib/chat/browser/chat.js'; +import { ICustomizationHarnessService } from '../../../../../workbench/contrib/chat/common/customizationHarnessService.js'; +import { ICustomizationMigrationService } from '../../../../../workbench/contrib/chat/common/promptSyntax/service/customizationMigrationService.js'; +import { IMcpService } from '../../../../../workbench/contrib/mcp/common/mcpTypes.js'; import { IChatEntitlementService, IChatSentiment } from '../../../../../workbench/services/chat/common/chatEntitlementService.js'; import { IChatModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; import { IVoicePlaybackService } from '../../../../../workbench/contrib/chat/common/voicePlaybackService.js'; @@ -131,6 +137,7 @@ export interface ISessionsListFixtureGroup { /** Fixture-local id used by row references. */ readonly id: string; readonly name: string; + readonly color?: string; /** Ids of the member sessions. */ readonly sessions?: readonly string[]; /** Fixture id of the group this group is nested in, listed before it. */ @@ -711,6 +718,15 @@ export async function renderSessionsListFixture(context: ComponentFixtureContext override createPullRequestCIModelReference(_owner: string, _repo: string, number: number) { return new ImmortalReference(ciModels.get(number)!); } }()); reg.defineInstance(IChatWidgetService, new class extends mock() { }()); + reg.defineInstance(IAICustomizationItemsModel, new class extends mock() { }()); + reg.defineInstance(ICustomizationHarnessService, new class extends mock() { + override readonly activeSessionResource = constObservable(URI.parse('copilot:/fixture')); + override getActiveDescriptor() { return { id: 'copilot', label: 'Copilot', icon: Codicon.copilot }; } + }()); + reg.defineInstance(IAICustomizationWorkspaceService, new class extends mock() { }()); + reg.defineInstance(IMcpService, new class extends mock() { }()); + reg.defineInstance(IAgentHostCustomizationService, new class extends mock() { }()); + reg.defineInstance(ICustomizationMigrationService, new class extends mock() { }()); reg.defineInstance(IAgentFeedbackService, new class extends mock() { override readonly onDidChangeFeedback = Event.None; override getFeedbackObservable(resource: URI) { return feedback.map(items => items.filter(item => isEqual(item.sessionResource, resource))); } @@ -996,6 +1012,9 @@ function seedListState(instantiationService: TestInstantiationService, state: IS throw new Error(`Fixture group '${group.id}' must be listed after its parent '${group.parent}'.`); } const created = groupsService.createGroup(group.name, (group.sessions ?? []).map(id => getSession(id).session.sessionId), parentId); + if (group.color !== undefined) { + groupsService.setGroupColor(created.id, group.color); + } groupIds.set(group.id, created.id); if (parentId === undefined) { topLevelIds.push(getSessionGroupSectionId(created.id)); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListTestUtils.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTestUtils.ts index b4c2e0c4beb3..4ec6333b4257 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListTestUtils.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTestUtils.ts @@ -423,6 +423,14 @@ export function createListHarness(disposables: Pick, ses appearanceChanges.fire({ groupsChanged: false, membershipChanged: new Set() }); } override getGroups() { return [...groups]; } + override setGroupColor(groupId: string, color: string | undefined): void { + const index = groups.findIndex(group => group.id === groupId); + if (index < 0) { + throw new Error(`Unknown test group: ${groupId}`); + } + groups[index] = { ...groups[index], color }; + appearanceChanges.fire({ groupsChanged: true, membershipChanged: new Set() }); + } override getTree() { return new SessionGroupTree(groups); } override getGroup(groupId: string) { return groups.find(group => group.id === groupId); } override getGroupOfSession(sessionId: string) { return memberships.get(sessionId); } diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts index 192a8eb031c5..0fb3de65b559 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts @@ -220,20 +220,19 @@ suite('Sessions - Sessions list tools', () => { }); }); - test('rejects disabled inbox grouping before changing filters and allows it after opt-in', async () => { - const { organize, read, list, configurationService } = setup([session('Alpha', 1)], { realListModel: true }); - list.filters.setExcluded({ kind: 'harness', id: 'claude' }, true); - const rejected = await organize({ action: 'setView', grouping: 'inbox', resetFilters: true }); - const unchanged = { grouping: (await read()).view.grouping, excluded: list.filters.isExcluded({ kind: 'harness', id: 'claude' }) }; - await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, true); - const accepted = await organize({ action: 'setView', grouping: 'inbox' }); - assert.deepStrictEqual({ rejected: rejected.results, unchanged, accepted: accepted.results, grouping: (await read()).view.grouping }, { - rejected: [{ action: 'setView', ok: false, error: 'Inbox Mode requires "sessions.list.inboxEnabled" to be enabled.' }], - unchanged: { grouping: 'workspace', excluded: true }, - accepted: [{ action: 'setView', ok: true }], - grouping: 'inbox', + for (const enabled of [false, true]) { + test(`allows inbox grouping regardless of the default setting (${enabled})`, async () => { + const { organize, read, list, configurationService } = setup([session('Alpha', 1)], { realListModel: true }); + await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, enabled); + list.filters.setExcluded({ kind: 'harness', id: 'claude' }, true); + const result = await organize({ action: 'setView', grouping: 'inbox', resetFilters: true }); + assert.deepStrictEqual({ results: result.results, grouping: (await read()).view.grouping, excluded: list.filters.isExcluded({ kind: 'harness', id: 'claude' }) }, { + results: [{ action: 'setView', ok: true }], + grouping: 'inbox', + excluded: false, + }); }); - }); + } test('refuses to read or change the list while the setting is off', async () => { const { invokeRaw, configurationService, harness } = setup([session('Alpha', 1)]); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsSessionManagementActions.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsSessionManagementActions.test.ts index be2b976b9673..5072322d77d9 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsSessionManagementActions.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsSessionManagementActions.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise } from '../../../../../base/common/async.js'; import { decodeKeybinding } from '../../../../../base/common/keybindings.js'; import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { constObservable } from '../../../../../base/common/observable.js'; @@ -468,23 +469,38 @@ suite('Sessions - Session management actions', () => { }); }); - test('plays the confetti signal after keyboard archive when animation is enabled', async () => { + test('plays the confetti signal optimistically when keyboard archive is requested', async () => { const enabled = createActionHarness([createTestSession('Enabled').session], undefined); const disabled = createActionHarness([createTestSession('Disabled').session], undefined, undefined, undefined, false, { confettiEnabled: false }); const reducedMotion = createActionHarness([createTestSession('Reduced motion').session], undefined, undefined, undefined, false, { reducedMotion: true }); - - await enabled.instantiationService.invokeFunction(accessor => new ArchiveSessionAction().run(accessor)); + const failed = createActionHarness([createTestSession('Failed').session], undefined); + const completion = new DeferredPromise(); + enabled.managementService.archiveSession = async () => completion.p; + failed.managementService.archiveSession = async () => { throw new Error('Archive failed'); }; + + const archive = enabled.instantiationService.invokeFunction(accessor => new ArchiveSessionAction().run(accessor)); + const enabledBeforeCompletion = [...enabled.playedSignals]; + await completion.complete(); + await archive; await disabled.instantiationService.invokeFunction(accessor => new ArchiveSessionAction().run(accessor)); await reducedMotion.instantiationService.invokeFunction(accessor => new ArchiveSessionAction().run(accessor)); + await assert.rejects( + () => failed.instantiationService.invokeFunction(accessor => new ArchiveSessionAction().run(accessor)), + /Archive failed/, + ); assert.deepStrictEqual({ + enabledBeforeCompletion, enabled: enabled.playedSignals, disabled: disabled.playedSignals, reducedMotion: reducedMotion.playedSignals, + failed: failed.playedSignals, }, { + enabledBeforeCompletion: [AccessibilitySignal.confetti], enabled: [AccessibilitySignal.confetti], disabled: [], reducedMotion: [], + failed: [AccessibilitySignal.confetti], }); }); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsTitleBarWidget.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsTitleBarWidget.test.ts index 9ac34ca00171..c7b3a7b4c6ad 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsTitleBarWidget.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsTitleBarWidget.test.ts @@ -16,6 +16,7 @@ import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { IOpenSessionOptions, ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; import { ISession } from '../../../../../workbench/services/sessions/common/session.js'; +import { ISessionEditorWorkingSetService, SessionEditorWorkingSetService } from '../../../layout/common/sessionEditorWorkingSet.js'; import { SessionsTitleBarWidget } from '../../browser/sessionsTitleBarWidget.js'; import { ISessionHost, ISessionHostService, SessionHostKind } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; import { IChatWindow, IChatWindowService } from '../../../../../workbench/contrib/chatWindow/browser/chatWindow.js'; @@ -70,6 +71,7 @@ suite('SessionsTitleBarWidget', () => { [IEditorGroupsService, upcastPartial({})], [IWorkbenchLayoutService, upcastPartial({})], [ISessionHostService, upcastPartial({ getHostOfWindow: () => upcastPartial({ session: constObservable(undefined), chat: constObservable(undefined) }) })], + [ISessionEditorWorkingSetService, new SessionEditorWorkingSetService()], ]); const accessor: ServicesAccessor = { get: (id: ServiceIdentifier) => services.get(id) as T }; Reflect.set(widget, '_windowHost', upcastPartial({ kind: SessionHostKind.ChatWindow, parent: undefined, windowId: constObservable(7) })); @@ -130,16 +132,30 @@ suite('SessionsTitleBarWidget', () => { Reflect.set(widget, '_isQuickChat', false); Reflect.set(widget, '_sessionTitle', undefined); const hoverDelegate: IHoverDelegate = { placement: 'element', delay: 500, showHover: () => undefined }; - const hovers: { content: string | undefined; sharedDelegate: boolean }[] = []; + const hovers: { target: HTMLElement; content: () => string | undefined; sharedDelegate: boolean }[] = []; Reflect.set(widget, 'options', { hoverDelegate }); Reflect.set(widget, 'hoverService', upcastPartial({ - setupManagedHover: (delegate, _target, content) => { - hovers.push({ content: typeof content === 'string' ? content : undefined, sharedDelegate: delegate === hoverDelegate }); + setupManagedHover: (delegate, target, content) => { + hovers.push({ + target, + content: typeof content === 'function' ? content as () => string | undefined : () => typeof content === 'string' ? content : undefined, + sharedDelegate: delegate === hoverDelegate, + }); return { ...Disposable.None, show: () => { }, hide: () => { }, update: () => { } }; }, })); renderActiveSession.call(widget); + const workspaceHover = hovers.find(hover => hover.target.classList.contains('agent-sessions-titlebar-workspace'))!; + const branchHover = hovers.find(hover => hover.target.classList.contains('agent-sessions-titlebar-branch'))!; + Object.defineProperties(workspaceHover.target, { + clientWidth: { configurable: true, value: 100 }, + scrollWidth: { configurable: true, value: 100 }, + }); + Object.defineProperties(branchHover.target, { + clientWidth: { configurable: true, value: 80 }, + scrollWidth: { configurable: true, value: 160 }, + }); assert.deepStrictEqual({ ariaLabel: container.getAttribute('aria-label'), @@ -148,7 +164,7 @@ suite('SessionsTitleBarWidget', () => { workspaceIcon: !!container.querySelector('.codicon-worktree-compact'), branchIcon: !!container.querySelector('.codicon-git-branch-compact'), branch: container.querySelector('.agent-sessions-titlebar-branch')?.textContent, - hovers, + hovers: hovers.map(hover => ({ content: hover.content(), sharedDelegate: hover.sharedDelegate })), nativeTitles: container.querySelectorAll('[title]').length, }, { ariaLabel: 'Show Sessions: vscode, branch feature/session-branch', @@ -158,7 +174,7 @@ suite('SessionsTitleBarWidget', () => { branchIcon: true, branch: 'feature/session-branch', hovers: [ - { content: 'vscode', sharedDelegate: true }, + { content: undefined, sharedDelegate: true }, { content: 'feature/session-branch', sharedDelegate: true }, ], nativeTitles: 0, 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 570ef2aa10d4..4d7ecf255def 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts @@ -7,15 +7,16 @@ import assert from 'assert'; import { IContextMenuDelegate } from '../../../../../base/browser/contextmenu.js'; import { $, getActiveElement } from '../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../base/browser/window.js'; +import { timeout } from '../../../../../base/common/async.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { DisposableStore, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { observableValue } from '../../../../../base/common/observable.js'; +import { constObservable, observableValue } from '../../../../../base/common/observable.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { isICommandActionToggleInfo } from '../../../../../platform/action/common/action.js'; import { getActionBarActions } from '../../../../../platform/actions/browser/menuEntryActionViewItem.js'; -import { isIMenuItem, isISubmenuItem, MenuId, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; +import { IMenuService, isIMenuItem, isISubmenuItem, MenuId, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; import { MenuService } from '../../../../../platform/actions/common/menuService.js'; import { ChatExternalSessionsMode } from '../../../../../platform/chat/common/chatSettings.js'; import { ChatSessionArchiveActionWording, ChatSessionArchiveActionWordingSettingId } from '../../../../../platform/chat/common/sessionArchiveActions.js'; @@ -23,7 +24,7 @@ import { CommandsRegistry } from '../../../../../platform/commands/common/comman import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; -import { IContextKey } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IContextKey, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { ContextMenuHandler } from '../../../../../platform/contextview/browser/contextMenuHandler.js'; import { IContextViewService } from '../../../../../platform/contextview/browser/contextView.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; @@ -33,16 +34,19 @@ import { TestNotificationService } from '../../../../../platform/notification/te import { IInputOptions, IQuickInputService, IQuickPickItem } from '../../../../../platform/quickinput/common/quickInput.js'; import { InMemoryStorageService } from '../../../../../platform/storage/common/storage.js'; import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IsSessionsWindowContext } from '../../../../../workbench/common/contextkeys.js'; import { ChatConfiguration } from '../../../../../workbench/contrib/chat/common/constants.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { IViewsService } from '../../../../../workbench/services/views/common/viewsService.js'; import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; -import { IsPhoneLayoutContext, SessionIsArchivedContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; +import { IsPhoneLayoutContext, SessionIsArchivedContext, SessionItemIsMultiSelectionContext } from '../../../../../workbench/contrib/sessions/common/contextkeys.js'; import { ARCHIVE_SESSION_COMMAND_ID, SHOW_SESSION_APPLICATION_FILTERS_COMMAND_ID } from '../../../../../workbench/contrib/sessions/common/sessionCommands.js'; import { SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; -import { ISession, ISessionEnvironment } from '../../../../../workbench/services/sessions/common/session.js'; +import { ISession, ISessionChangeset, ISessionChangesetOperation, ISessionEnvironment, SessionChangesetOperationScope, SessionChangesetOperationStatus } from '../../../../../workbench/services/sessions/common/session.js'; +import { IInboxNotificationsService, IInboxSessionAttention, InboxNotificationPriority, InboxTab } from '../../../../../workbench/contrib/sessions/common/inboxNotificationsService.js'; import { buildTestSession } from '../../../../../workbench/contrib/sessions/test/common/testSessionBuilder.js'; -import { SessionItemContextMenuId, SessionItemInboxStateContext, SessionsGrouping, SessionsList, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; +import { TestSessionsList } from '../../../../../workbench/contrib/sessions/test/browser/views/testSessionsList.js'; +import { SessionItemCanMergePullRequestContext, SessionItemContextMenuId, SessionItemInboxStateContext, SessionsGrouping, SessionsList, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { ISessionsListModelService, SessionsListModelService } from '../../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; import { SessionsListFilters } from '../../../../../workbench/contrib/sessions/browser/views/sessionsListFilters.js'; import { ISessionsListNotice, SessionsListNotification } from '../../../../../workbench/contrib/sessions/browser/views/sessionsListNotification.js'; @@ -184,9 +188,10 @@ suite('Sessions - View Menu', () => { }); }); - test('inbox mode is offered only when the experimental setting and AI are enabled', async () => { + test('inbox mode is always offered with AI enabled regardless of the default setting', async () => { const { snapshot, configurationService, contextKeyService } = createMenu(); - const offered = () => snapshot(Menus.SessionsViewGrouping).some(item => item.title === 'Inbox Mode'); + IsSessionsWindowContext.bindTo(contextKeyService).set(true); + const offered = () => snapshot(Menus.SessionsViewGrouping).some(item => item.title === 'Inbox Mode' && item.enabled); const initial = offered(); await configurationService.updateValue(SESSIONS_LIST_INBOX_ENABLED_SETTING, true); const enabled = offered(); @@ -195,7 +200,7 @@ suite('Sessions - View Menu', () => { ChatContextKeys.enabled.bindTo(contextKeyService).set(true); await configurationService.updateValue(SESSIONS_LIST_INBOX_ENABLED_SETTING, false); assert.deepStrictEqual({ initial, enabled, hiddenAI, disabled: offered() }, { - initial: false, enabled: true, hiddenAI: false, disabled: false, + initial: true, enabled: true, hiddenAI: false, disabled: true, }); }); @@ -215,12 +220,13 @@ suite('Sessions - View Menu', () => { ChatContextKeys.enabled.bindTo(contextKeyService).set(false); assert.deepStrictEqual({ ordinary, ordinaryFilter, active, done, held, hidden: actions(), inboxFilter: archiveFilter() }, { ordinary: [], ordinaryFilter: ['Show Done'], active: ['Put on Hold', 'Snooze...', 'Dismiss from Inbox', 'Mark Session as Done'], done: ['Return to Inbox', 'Put on Hold', 'Snooze...', 'Mark Session as Done'], - held: ['Return to Inbox', 'Snooze...', 'Dismiss from Inbox', 'Mark Session as Done'], hidden: [], inboxFilter: ['Show Archived'], + held: ['Return to Inbox', 'Snooze...', 'Dismiss from Inbox', 'Mark Session as Done'], hidden: [], inboxFilter: ['Show Done'], }); }); test('inbox rows have distinct dismiss and archive actions in the toolbar and context menu', () => { const { grouping, contextKeyService } = createMenu(); + SessionItemInboxStateContext.bindTo(contextKeyService); const actions = (menu: MenuId) => MenuRegistry.getMenuItems(menu) .filter(isIMenuItem) .filter(item => ['sessionsViewPane.inboxDone', ARCHIVE_SESSION_COMMAND_ID].includes(item.command.id) && contextKeyService.contextMatchesRules(item.when)) @@ -237,11 +243,11 @@ suite('Sessions - View Menu', () => { const archived = snapshot(); archivedContext.set(false); ChatContextKeys.enabled.bindTo(contextKeyService).set(false); - const dismissAction = ['sessionsViewPane.inboxDone', 'Dismiss from Inbox', Codicon.close]; + const dismissAction = ['sessionsViewPane.inboxDone', 'Dismiss from Inbox', Codicon.mailRead]; const archiveAction = [ARCHIVE_SESSION_COMMAND_ID, 'Mark Session as Done', Codicon.check]; assert.deepStrictEqual({ ordinary, active, dismissed, archived, hidden: snapshot() }, { ordinary: { toolbar: [], contextMenu: [] }, - active: { toolbar: [archiveAction, dismissAction], contextMenu: [dismissAction, archiveAction] }, + active: { toolbar: [dismissAction], contextMenu: [dismissAction, archiveAction] }, dismissed: { toolbar: [archiveAction], contextMenu: [archiveAction] }, archived: { toolbar: [], contextMenu: [] }, hidden: { toolbar: [], contextMenu: [] }, @@ -278,6 +284,111 @@ suite('Sessions - View Menu', () => { }); }); + test('single-session inbox hold, resume, and snooze avoid Undo banners but dismissal retains one', async () => { + const session = buildTestSession({ id: 'session', title: 'Session' }).session; + const harness = createListHarness(store, [session]); + const model = store.add(harness.instantiationService.createInstance(SessionsListModelService)); + harness.instantiationService.stub(ISessionsListModelService, model); + const notices: ISessionsListNotice[] = []; + harness.instantiationService.stub(IViewsService, upcastPartial({}), 'getViewWithId', () => + upcastPartial({ listNotification: upcastPartial({ show: notice => notices.push(notice) }) })); + harness.instantiationService.stub(IQuickInputService, upcastPartial({}), 'pick', async (items: IQuickPickItem[]) => items[0]); + const counts: number[] = []; + for (const action of ['inboxHold', 'inboxResume', 'inboxSnooze', 'inboxDone']) { + await CommandsRegistry.getCommand(`sessionsViewPane.${action}`)!.handler(harness.instantiationService, session); + counts.push(notices.length); + } + assert.deepStrictEqual({ counts, archived: session.isArchived.get() }, { counts: [0, 0, 0, 1], archived: false }); + }); + + test('inbox merge uses only the available provider operation and rejects stale or multiple targets', async () => { + const built = buildTestSession({ id: 'merge', title: 'Merge', workspace: 'Project', repository: 'owner/repo', pullRequest: { number: 1, title: 'PR' } }); + const operations = observableValue('operations', [{ + id: 'pr-merge', label: 'Merge', scopes: [SessionChangesetOperationScope.Changeset], status: SessionChangesetOperationStatus.Idle, + }]); + const calls: string[] = []; + const changeset = upcastPartial({ + isEnabled: constObservable(true), operations, + invokeOperation: async id => { calls.push(id); }, + }); + const session: ISession = { ...built.session, mainChat: constObservable({ ...built.mainChat.chat, changesets: constObservable([changeset]) }) }; + const harness = createListHarness(store, [session]); + const model = store.add(harness.instantiationService.createInstance(SessionsListModelService)); + harness.instantiationService.stub(ISessionsListModelService, model); + const attention = new Map([[session.sessionId, { tab: InboxTab.ReadyToMerge, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: false }]]); + harness.instantiationService.stub(IInboxNotificationsService, upcastPartial({ sessionAttention: constObservable(attention) })); + const run = async (target: ISession | ISession[] = session) => CommandsRegistry.getCommand('sessionsViewPane.inboxMergePullRequest')!.handler(harness.instantiationService, target); + await run(); + await assert.rejects(run([session, session]), /no longer available/); + model.setInboxState([session], 'hold'); + await assert.rejects(run(), /no longer available/); + model.setInboxState([session], undefined); + operations.set([{ ...operations.get()[0], status: SessionChangesetOperationStatus.Disabled }], undefined); + await assert.rejects(run(), /no longer available/); + assert.deepStrictEqual(calls, ['pr-merge']); + }); + + test('inbox merge menus are AI-gated and disable multi-selection', () => { + const { grouping, contextKeyService } = createMenu(); + grouping.set(SessionsGrouping.Inbox); + SessionItemCanMergePullRequestContext.bindTo(contextKeyService).set(true); + const multiple = SessionItemIsMultiSelectionContext.bindTo(contextKeyService); + const snapshot = () => MenuRegistry.getMenuItems(Menus.SessionItemToolbar).filter(isIMenuItem) + .filter(item => item.command.id === 'sessionsViewPane.inboxMergePullRequest' && contextKeyService.contextMatchesRules(item.when)) + .map(item => contextKeyService.contextMatchesRules(item.command.precondition)); + const available = snapshot(); + multiple.set(true); + const multi = snapshot(); + ChatContextKeys.enabled.bindTo(contextKeyService).set(false); + assert.deepStrictEqual({ available, multi, hidden: snapshot() }, { available: [true], multi: [false], hidden: [] }); + }); + + test('inbox merge toolbar follows actual selection and ignores unrelated selected rows', async () => { + const built = buildTestSession({ id: 'merge', title: 'Merge', workspace: 'Project', repository: 'owner/repo', pullRequest: { number: 1, title: 'PR' } }); + const changeset = upcastPartial({ + isEnabled: constObservable(true), + operations: constObservable([{ id: 'pr-merge', label: 'Merge', scopes: [SessionChangesetOperationScope.Changeset], status: SessionChangesetOperationStatus.Idle }]), + }); + const session: ISession = { ...built.session, mainChat: constObservable({ ...built.mainChat.chat, changesets: constObservable([changeset]) }) }; + const others = ['first', 'second'].map(id => buildTestSession({ id, title: id }).session); + const harness = createListHarness(store, [session, ...others]); + harness.instantiationService.stub(ISessionsListModelService, store.add(harness.instantiationService.createInstance(SessionsListModelService))); + const attention = new Map([[session.sessionId, { tab: InboxTab.ReadyToMerge, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: false }]]); + harness.instantiationService.stub(IInboxNotificationsService, upcastPartial({ + sessionAttention: constObservable(attention), acquireSessionAttention: () => toDisposable(() => { }), + })); + const context = store.add(new ContextKeyService(harness.instantiationService.get(IConfigurationService))); + ChatContextKeys.enabled.bindTo(context).set(true); + SessionsViewGroupingContext.bindTo(context).set(SessionsGrouping.Inbox); + harness.instantiationService.stub(IContextKeyService, context); + harness.instantiationService.stub(IMenuService, store.add(harness.instantiationService.createInstance(MenuService))); + const list = store.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(), { + grouping: () => SessionsGrouping.Inbox, sorting: () => SessionsSorting.Created, onSessionOpen: () => { }, + })); + list.layout(600, 400); + list.reveal(session.resource); + const button = () => list.getItemRow({ session: session.resource })!.querySelector('.session-title-toolbar [aria-label="Merge Pull Request"]')!; + const select = async (sessions: readonly ISession[]) => { + assert.ok(list.setSelectedItems(sessions.map(session => ({ session: session.resource })))); + await timeout(100); + return button().getAttribute('aria-disabled') === 'true'; + }; + const single = await select([session]); + const multiple = await select([session, others[0]]); + button().click(); + await timeout(0); + const blockedCalls = harness.commandService.calls.filter(call => call.commandId === 'sessionsViewPane.inboxMergePullRequest'); + const unrelated = await select(others); + const restored = await select([session]); + button().click(); + await timeout(0); + const calls = harness.commandService.calls.filter(call => call.commandId === 'sessionsViewPane.inboxMergePullRequest'); + assert.deepStrictEqual({ single, multiple, unrelated, restored, blockedCalls, calls }, { + single: false, multiple: true, unrelated: false, restored: false, blockedCalls: [], + calls: [{ commandId: 'sessionsViewPane.inboxMergePullRequest', args: [[session]] }], + }); + }); + test('inbox snooze handles cancellation, timed presets, and validated custom dates', async () => { const session = buildTestSession({ id: 'first', title: 'First' }).session; const harness = createListHarness(store, [session]); @@ -510,6 +621,7 @@ suite('Sessions - View Menu', () => { { title: 'Workspace', group: '1_group', checked: false }, { title: 'Repository', group: '1_group', checked: false }, { title: 'Environment', group: '1_group', checked: true }, + { title: 'Inbox Mode', group: '1_group', checked: false, enabled: false }, ], environmentShow: [ { title: 'Recent', group: '1_show', checked: false }, @@ -525,6 +637,7 @@ suite('Sessions - View Menu', () => { { title: 'Workspace', group: '1_group', checked: false }, { title: 'Repository', group: '1_group', checked: false }, { title: 'Environment', group: '1_group', checked: false }, + { title: 'Inbox Mode', group: '1_group', checked: false, enabled: false }, ], show: [ { title: 'Recent', group: '1_show', checked: false }, diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsViewPane.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsViewPane.test.ts index 6e10c18bd0ed..caeef7512ac0 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsViewPane.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsViewPane.test.ts @@ -4,26 +4,36 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { DeferredPromise } from '../../../../../base/common/async.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { SplitView, Sizing } from '../../../../../base/browser/ui/splitview/splitview.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { constObservable, IObservable, observableValue } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; -import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { ISessionGridPane } from '../../../../../workbench/services/sessions/browser/sessionGridPane.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; -import { InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { InMemoryStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; import { Workbench } from '../../../../browser/workbench.js'; -import { ISession } from '../../../../../workbench/services/sessions/common/session.js'; +import { ISession, SessionStatus } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionComparison, SessionComparisonParticipantRole } from '../../../../../workbench/contrib/sessions/common/sessionComparison.js'; import { AICustomizationShortcutsWidget } from '../../../../../workbench/contrib/sessions/browser/aiCustomizationShortcutsWidget.js'; import { getCustomizationsPresentation, SessionsView } from '../../../../../workbench/contrib/sessions/browser/views/sessionsView.js'; import { SessionsGrouping, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; import { SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../../../../workbench/contrib/sessions/common/sessionConfig.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { SessionViewFloatingToolbar } from '../../../../../workbench/contrib/sessions/browser/parts/sessionHeaderBar.js'; +import { ISessionHost } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; +import { IMenuService, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; +import { MenuService } from '../../../../../platform/actions/common/menuService.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { Menus } from '../../../../../workbench/contrib/sessions/browser/menus.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { ChatCustomizationsLocation } from '../../../../../workbench/contrib/chat/common/customizationsLocation.js'; import '../../../../../workbench/contrib/sessions/browser/media/sessionsViewPane.css'; const registerEditorTabHeightClass = Reflect.get(Workbench.prototype, 'registerEditorTabHeightClass') as (this: { @@ -53,6 +63,94 @@ const updateHeaderLayout = Reflect.get(SessionsView.prototype, 'updateHeaderLayo suite('Sessions - SessionsViewPane', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + test('keeps global customization actions operable before a draft session is bound', async () => { + const configurationService = new TestConfigurationService(); + disposables.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = workbenchInstantiationService({ + configurationService: () => configurationService, + contextKeyService: () => disposables.add(new ContextKeyService(configurationService)), + }, disposables); + instantiationService.stub(ISessionHost, upcastPartial({})); + const calls: string[] = []; + instantiationService.stub(ICommandService, new class extends mock() { + override async executeCommand(id: string): Promise { calls.push(id); return undefined; } + }); + instantiationService.stub(IMenuService, disposables.add(instantiationService.createInstance(MenuService))); + for (const menu of [Menus.NewSessionGlobalToolbar, Menus.SessionBarToolbar]) { + disposables.add(MenuRegistry.appendMenuItem(menu, { + command: { id: 'test.globalCustomization', title: 'Customizations', icon: Codicon.extensions }, + group: 'navigation', + })); + } + const toolbar = disposables.add(instantiationService.createInstance(SessionViewFloatingToolbar)); + mainWindow.document.body.appendChild(toolbar.element); + disposables.add(toDisposable(() => toolbar.element.remove())); + toolbar.setSession(undefined); + const visibleButtons = () => [...toolbar.element.querySelectorAll('.codicon-extensions')] + .filter(button => button.closest('.chat-composite-bar-toolbar')!.style.display !== 'none'); + const button = visibleButtons()[0]; + assert.ok(button, toolbar.element.outerHTML); + button.click(); + await timeout(0); + const unbound = visibleButtons().length; + toolbar.setSession(upcastPartial({ resource: URI.parse('agent-host-copilot:/draft'), status: constObservable(SessionStatus.Untitled) })); + const bound = visibleButtons().length; + visibleButtons()[0].click(); + await timeout(0); + toolbar.setSession(undefined); + assert.deepStrictEqual({ calls, unbound, bound, unboundAgain: visibleButtons().length }, { + calls: ['test.globalCustomization', 'test.globalCustomization'], unbound: 1, bound: 1, unboundAgain: 1, + }); + }); + + test('layout refresh keeps the chosen placement independent of navigation and phone transitions', () => { + const container = mainWindow.document.createElement('div'); + const location = observableValue(disposables, 'chatInput'); + const navigation = observableValue(disposables, true); + const calls: Array<[string, boolean]> = []; + const host = { + layoutService: { mainContainer: container }, + scopedContextKeyService: { contextMatchesRules: () => true }, + chatEntitlementService: { sentimentObs: constObservable({ hidden: false }) }, + separateNavigation: navigation, + customizationsLocation: location, + updateCustomizationsPresentation: (presentation: string, shortcuts: boolean) => calls.push([presentation, shortcuts]), + }; + const refresh = Reflect.get(SessionsView.prototype, 'refreshCustomizationsPresentation') as (this: typeof host) => void; + refresh.call(host); + container.classList.add('phone-layout'); + refresh.call(host); + container.classList.remove('phone-layout'); + refresh.call(host); + location.set('sessionsHeader', undefined); + navigation.set(false, undefined); + refresh.call(host); + location.set('sidebar', undefined); + navigation.set(true, undefined); + refresh.call(host); + assert.deepStrictEqual(calls, [['hidden', true], ['hidden', false], ['hidden', true], ['treatment', false], ['control', true]]); + }); + + test('floating toolbar view items follow their own draft rather than the focused session', () => { + const host = { + _session: undefined as ISession | undefined, + _sessionDisposables: disposables.add(new MutableDisposable()), + _sessionHost: upcastPartial({}), + _menuActionArgs: [] as unknown[], + _toolbar: { context: undefined as ISession | undefined }, + _toolbarContainer: { style: { display: '' } }, + _globalToolbarContainer: { style: { display: '' } }, + _setVisible: () => { }, + }; + const setSession = SessionViewFloatingToolbar.prototype.setSession as (this: typeof host, session: ISession | undefined) => void; + const contexts: Array = []; + for (const resource of [URI.parse('agent-host-copilot:/draft'), URI.parse('agent-host-claude:/draft'), undefined]) { + setSession.call(host, resource ? upcastPartial({ resource, status: constObservable(SessionStatus.Untitled) }) : undefined); + contexts.push(host._toolbar.context?.resource.toString()); + } + assert.deepStrictEqual(contexts, ['agent-host-copilot:/draft', 'agent-host-claude:/draft', undefined]); + }); + test('offers and selects environment grouping in the mobile sheet', async () => { const container = mainWindow.document.createElement('div'); const selected = new DeferredPromise(); @@ -63,6 +161,7 @@ suite('Sessions - SessionsViewPane', () => { grouping: SessionsGrouping.Environment, currentSorting: SessionsSorting.Created, configurationService, + chatEntitlementService: { sentiment: { hidden: false } }, setGrouping: (grouping: SessionsGrouping) => selected.complete(grouping), setSorting: () => assert.fail('Expected grouping selection'), }; @@ -77,13 +176,12 @@ suite('Sessions - SessionsViewPane', () => { assert.deepStrictEqual({ checked, selected: await selected.p }, { checked: 'true', selected: SessionsGrouping.Environment }); }); - test('suspends saved inbox grouping while disabled without losing the choice', async () => { + test('uses the setting as the grouping default until an explicit choice is saved', async () => { const configurationService = new TestConfigurationService(); disposables.add(configurationService.onDidChangeConfigurationEmitter); const storageService = disposables.add(new InMemoryStorageService()); - storageService.store('sessionsViewPane.grouping', SessionsGrouping.Inbox, StorageScope.PROFILE, StorageTarget.USER); const host = { - currentGrouping: SessionsGrouping.Inbox, + currentGrouping: undefined as SessionsGrouping | undefined, configurationService, storageService, get grouping(): SessionsGrouping { return Reflect.get(SessionsView.prototype, 'grouping', this); }, @@ -91,29 +189,55 @@ suite('Sessions - SessionsViewPane', () => { }; const setGrouping = SessionsView.prototype.setGrouping as (this: typeof host, grouping: SessionsGrouping) => void; const initial = host.grouping; - assert.throws(() => setGrouping.call(host, SessionsGrouping.Inbox), /Enable sessions.list.inboxEnabled/); await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, true); const enabled = host.grouping; await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, false); const disabled = host.grouping; + setGrouping.call(host, SessionsGrouping.Inbox); const saved = storageService.get('sessionsViewPane.grouping', StorageScope.PROFILE); + const selected = host.grouping; await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, true); const restored = host.grouping; - await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, false); setGrouping.call(host, SessionsGrouping.Workspace); + await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, false); await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, true); - assert.deepStrictEqual({ initial, enabled, disabled, saved, restored, changed: host.grouping }, { + assert.deepStrictEqual({ initial, enabled, disabled, saved, selected, restored, changed: host.grouping }, { initial: SessionsGrouping.Workspace, enabled: SessionsGrouping.Inbox, disabled: SessionsGrouping.Workspace, saved: SessionsGrouping.Inbox, + selected: SessionsGrouping.Inbox, restored: SessionsGrouping.Inbox, changed: SessionsGrouping.Workspace, }); }); + for (const enabled of [false, true]) { + test(`persists an explicit selection of the default grouping (${enabled})`, async () => { + const configurationService = new TestConfigurationService({ [SESSIONS_LIST_INBOX_ENABLED_SETTING]: enabled }); + disposables.add(configurationService.onDidChangeConfigurationEmitter); + const storageService = disposables.add(new InMemoryStorageService()); + const host = { + currentGrouping: undefined as SessionsGrouping | undefined, + configurationService, + storageService, + get grouping(): SessionsGrouping { return Reflect.get(SessionsView.prototype, 'grouping', this); }, + updateHeaderLayout: () => { }, + }; + const initial = host.grouping; + const setGrouping = SessionsView.prototype.setGrouping as (this: typeof host, grouping: SessionsGrouping) => void; + setGrouping.call(host, initial); + await configurationService.setUserConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING, !enabled); + const saved = storageService.get('sessionsViewPane.grouping', StorageScope.PROFILE); + assert.deepStrictEqual({ selected: host.grouping, saved }, { + selected: enabled ? SessionsGrouping.Inbox : SessionsGrouping.Workspace, + saved: enabled ? SessionsGrouping.Inbox : SessionsGrouping.Workspace, + }); + }); + } + for (const { enabled, hidden } of [{ enabled: false, hidden: false }, { enabled: true, hidden: false }, { enabled: true, hidden: true }]) { - test(`mobile inbox option respects enablement (${enabled}) and hidden AI (${hidden})`, async () => { + test(`mobile inbox option ignores default setting (${enabled}) and respects hidden AI (${hidden})`, async () => { const container = mainWindow.document.createElement('div'); const selected = new DeferredPromise(); const configurationService = new TestConfigurationService({ [SESSIONS_LIST_INBOX_ENABLED_SETTING]: enabled }); @@ -134,8 +258,8 @@ suite('Sessions - SessionsViewPane', () => { const workspace = options.find(row => row.textContent?.trim() === 'Group by Workspace')!; (inbox ?? workspace).click(); assert.deepStrictEqual({ offered: !!inbox, selected: await selected.p }, { - offered: enabled && !hidden, - selected: enabled && !hidden ? SessionsGrouping.Inbox : SessionsGrouping.Workspace, + offered: !hidden, + selected: !hidden ? SessionsGrouping.Inbox : SessionsGrouping.Workspace, }); }); } @@ -156,6 +280,19 @@ suite('Sessions - SessionsViewPane', () => { }); }); + test('explicit customization locations override either sidebar arrangement', () => { + assert.deepStrictEqual([false, true].map(navigation => ({ + sidebar: getCustomizationsPresentation(false, true, false, navigation, 'sidebar'), + header: getCustomizationsPresentation(false, true, false, navigation, 'sessionsHeader'), + toolbar: getCustomizationsPresentation(false, true, false, navigation, 'chatToolbar'), + input: getCustomizationsPresentation(false, true, false, navigation, 'chatInput'), + hidden: getCustomizationsPresentation(false, true, true, navigation, 'sidebar'), + })), [ + { sidebar: 'control', header: 'treatment', toolbar: 'hidden', input: 'hidden', hidden: 'hidden' }, + { sidebar: 'control', header: 'treatment', toolbar: 'hidden', input: 'hidden', hidden: 'hidden' }, + ]); + }); + test('preserves Customizations and Automations focus while switching presentations', () => { const updatePresentation = Reflect.get(SessionsView.prototype, 'updateCustomizationsPresentation') as (this: ReturnType, presentation: 'hidden' | 'control' | 'treatment') => void; @@ -179,6 +316,7 @@ suite('Sessions - SessionsViewPane', () => { }; const rearrangeContextValues: boolean[] = []; const host = { + configurationService: new TestConfigurationService(), customizationsPresentation: presentation, customizationsNavigationVisible: { set: () => { } }, sessionsListRearrangeContext: { set: (value: boolean) => rearrangeContextValues.push(value) }, @@ -273,6 +411,7 @@ suite('Sessions - SessionsViewPane', () => { const host = { layoutService: { mainContainer }, instantiationService, + configurationService: new TestConfigurationService(), sidebarSplitViewContainer: container, sidebarSplitView: splitView, customizationsPaneDisposables, diff --git a/src/vs/sessions/contrib/sessions/test/electron-browser/sessionsListFocusRing.test.ts b/src/vs/sessions/contrib/sessions/test/electron-browser/sessionsListFocusRing.test.ts index 3db88ccb44ef..523b7f87550b 100644 --- a/src/vs/sessions/contrib/sessions/test/electron-browser/sessionsListFocusRing.test.ts +++ b/src/vs/sessions/contrib/sessions/test/electron-browser/sessionsListFocusRing.test.ts @@ -6,16 +6,20 @@ import assert from 'assert'; import * as dom from '../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../base/browser/window.js'; +import { Color } from '../../../../../base/common/color.js'; import { constObservable, observableValue } from '../../../../../base/common/observable.js'; import { ipcRenderer } from '../../../../../base/parts/sandbox/electron-browser/globals.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { TestColorTheme, TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; import { ChatContextKeys } from '../../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; import { ICustomViewDescriptor, ICustomViewService } from '../../../../../workbench/contrib/sessions/browser/customView.js'; import { IPinnedCanvas, IPinnedCanvasService, PINNED_CANVAS_PAGE_ID, PinnedCanvasState } from '../../../../../workbench/contrib/sessions/browser/pinnedCanvases.js'; +import { ISessionGroup, ISessionGroupsService } from '../../../../../workbench/contrib/sessions/browser/sessionGroupsService.js'; import { SessionsGrouping, SessionsList, SessionsSorting } from '../../../../../workbench/contrib/sessions/browser/views/sessionsList.js'; -import { createListHarness } from '../browser/sessionsListTestUtils.js'; +import { createListHarness, createTestSession } from '../browser/sessionsListTestUtils.js'; /** Focus styles only match while the document has focus, so give the test's web contents real focus. */ async function setWebContentsFocus(focused: boolean): Promise { @@ -26,11 +30,89 @@ async function setWebContentsFocus(focused: boolean): Promise { await changed; } -suite('SessionsList - pinned canvas focus ring', () => { +suite('SessionsList - focused row styles', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); setup(() => setWebContentsFocus(true)); + for (const { compact, customGroup } of [false, true].flatMap(compact => [false, true].map(customGroup => ({ compact, customGroup })))) { + test(`group label contrast follows rendered focus and selection surfaces (${compact ? 'compact' : 'default'}, ${customGroup ? 'custom group' : 'workspace'})`, () => { + const session = createTestSession('Session').session; + const group: ISessionGroup = { id: 'group', name: 'Custom Group', createdAt: 1 }; + const harness = createListHarness(disposables, [session], customGroup ? { + groups: [group], + memberships: new Map([[session.sessionId, group.id]]), + } : {}); + const themeService = new TestThemeService(); + harness.instantiationService.stub(IThemeService, themeService); + const container = harness.createContainer(); + const list = harness.store.add(harness.instantiationService.createInstance(SessionsList, container, { + grouping: () => SessionsGrouping.Workspace, + sorting: () => SessionsSorting.Created, + compact: () => compact, + onSessionOpen: () => { }, + })); + list.layout(700, 400); + const groupsService = harness.instantiationService.get(ISessionGroupsService); + if (customGroup) { + groupsService.setGroupColor(group.id, 'terminal.ansiBlue'); + } else { + groupsService.setSectionColor('workspace:Workspace', 'terminal.ansiBlue'); + } + const label = [...container.querySelectorAll('.session-section-label')] + .find(label => label.textContent === (customGroup ? group.name : 'Workspace'))!; + const row = label.closest('.monaco-list-row')!; + const listElement = row.closest('.monaco-list')!; + const results = []; + const expected = []; + for (const background of ['#ffffff', '#181818']) { + const colors: Record = { + 'agents.background': background, + 'terminal.ansiBlue': '#0060c0', + 'list.hoverBackground': '#88888822', + 'list.focusBackground': '#e5e510', + 'list.activeSelectionBackground': '#0060c0', + 'list.inactiveFocusBackground': '#ffffff80', + 'list.inactiveSelectionBackground': '#101010cc', + }; + themeService.setTheme(new TestColorTheme(colors)); + for (const [id, value] of Object.entries(colors)) { + container.style.setProperty(`--vscode-${id.replaceAll('.', '-')}`, value); + } + for (const active of [false, true]) { + if (active) { + listElement.focus(); + } else { + listElement.blur(); + } + for (const classes of [[], ['hovered'], ['focused'], ['selected'], ['focused', 'hovered'], ['selected', 'hovered'], ['focused', 'selected'], ['focused', 'selected', 'hovered']]) { + row.classList.remove('focused', 'selected', 'hovered'); + row.classList.add(...classes); + const stateBackground = classes.includes('selected') + ? active ? 'list.activeSelectionBackground' : 'list.inactiveSelectionBackground' + : classes.includes('focused') + ? active ? 'list.focusBackground' : 'list.inactiveFocusBackground' + : classes.includes('hovered') ? 'list.hoverBackground' : 'agents.background'; + const base = Color.fromHex(background); + const surface = Color.Format.CSS.parse(mainWindow.getComputedStyle(row).backgroundColor)!.flatten(base); + const foreground = Color.Format.CSS.parse(mainWindow.getComputedStyle(label).color)!; + results.push({ + active: listElement.matches(':focus'), + surface: surface.toString(), + readable: surface.getContrastRatio(foreground) >= 4.5, + }); + expected.push({ + active, + surface: Color.fromHex(colors[stateBackground]).flatten(base).toString(), + readable: true, + }); + } + } + } + assert.deepStrictEqual(results, expected); + }); + } + test('a press does not ring the pinned canvas row the page shows, while keyboard focus does, in both sidebar layouts', async () => { const plan = upcastPartial({ id: 'plan', diff --git a/src/vs/sessions/contrib/terminal/browser/sessionsTerminalContribution.ts b/src/vs/sessions/contrib/terminal/browser/sessionsTerminalContribution.ts index f07cc1c71c44..46190e8930a0 100644 --- a/src/vs/sessions/contrib/terminal/browser/sessionsTerminalContribution.ts +++ b/src/vs/sessions/contrib/terminal/browser/sessionsTerminalContribution.ts @@ -5,7 +5,7 @@ import { Codicon } from '../../../../base/common/codicons.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; -import { autorun, derived, IReader } from '../../../../base/common/observable.js'; +import { autorun, derived, IObservable, IReader } from '../../../../base/common/observable.js'; import { isEqual } from '../../../../base/common/resources.js'; import { Schemas } from '../../../../base/common/network.js'; import { URI } from '../../../../base/common/uri.js'; @@ -17,10 +17,12 @@ import { IInstantiationService } from '../../../../platform/instantiation/common import { IFileService } from '../../../../platform/files/common/files.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { IWorkbenchContribution, getWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; -import { IAgentHostTerminalService } from '../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; +import { IAgentHostTerminalProfileInfo, IAgentHostTerminalService } from '../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; import { ITerminalGroupService, ITerminalInstance, ITerminalLocationOptions, ITerminalService } from '../../../../workbench/contrib/terminal/browser/terminal.js'; import { TerminalCapability } from '../../../../platform/terminal/common/capabilities/capabilities.js'; +import { TerminalLocation } from '../../../../platform/terminal/common/terminal.js'; import { IPathService } from '../../../../workbench/services/path/common/pathService.js'; +import { IViewsService } from '../../../../workbench/services/views/common/viewsService.js'; import { isAgentHostProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { getMainWindowHost, ISessionHost, ISessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; @@ -99,7 +101,9 @@ function getSessionWorktreeCwd(session: ISession): URI | undefined { /** * Manages terminal instances in the sessions window, ensuring: - * - A terminal exists for the active session's worktree (or repository if no worktree). + * - A terminal exists for the active session's worktree (or repository if no worktree) + * while the terminal view is visible. Sessions whose terminal is never shown + * do not get one, so they don't keep idle shells alive. * - Terminals are tracked per session id and shown/hidden based on that association. * - Terminals created before session-id tracking fall back to initial cwd matching * until they are associated with a session in this window. @@ -115,11 +119,17 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben private _activeSessionId: string | undefined; private readonly _sessionTerminals = new Map>(); private readonly _trackedTerminalScopes = new Map(); - private readonly _standaloneTerminalIds = new Set(); /** Terminals that chat windows show, which the terminal panel leaves to them. */ private readonly _chatWindowTerminalIds = new Set(); /** In-flight terminal work for drafts, retained only until each operation settles. */ private readonly _pendingTerminalOperations = new Map(); + /** + * Set while the terminal view is open without terminals: it creates one + * itself, which becomes the active session's terminal. + */ + private _terminalViewOpenedEmpty = false; + /** The Agent Host profile set as the default profile for the active session, if any. */ + private readonly _defaultProfileOverride: IObservable; private readonly _sessionTerminalGenerations = new Map(); /** @@ -144,6 +154,8 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben @IPathService private readonly _pathService: IPathService, @IFileService private readonly _fileService: IFileService, @ITerminalProfileService private readonly _terminalProfileService: ITerminalProfileService, + @IViewsService private readonly _viewsService: IViewsService, + @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, ) { super(); this._mainWindowHost = getMainWindowHost(sessionHostService); @@ -157,7 +169,7 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben } } - const profileOverride = derived(reader => { + this._defaultProfileOverride = derived(reader => { const session = this._mainWindowHost.session.read(reader); if (!session || session.providerId === LOCAL_AGENT_HOST_PROVIDER_ID) { return; // no need to override local default profiles with the local AH @@ -173,7 +185,7 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben }); this._register(autorun(reader => { - const profile = profileOverride.read(reader); + const profile = this._defaultProfileOverride.read(reader); if (profile) { reader.store.add(this._terminalProfileService.overrideDefaultProfile( profile.extensionIdentifier, profile.profileId, @@ -226,12 +238,42 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben this._onActiveSessionChanged(session, chat, info); })); + // Terminals are created lazily: when the terminal view is shown, give the + // active session the terminal it skipped while the view was hidden. + this._register(this._viewsService.onDidChangeViewVisibility(e => { + if (e.id !== TERMINAL_VIEW_ID) { + return; + } + // The view creates a terminal when it opens empty; that terminal becomes + // the session's terminal, so do not create a second one. + this._terminalViewOpenedEmpty = e.visible && this._terminalGroupService.groups.length === 0; + if (e.visible && !this._terminalViewOpenedEmpty) { + this._onTerminalViewShown(); + } + })); + this._register(this._terminalService.onDidCreateInstance(instance => { + if (this._terminalViewOpenedEmpty && this._couldBeTerminalViewShell(instance)) { + this._terminalViewOpenedEmpty = false; + // The terminal group fires this event before it registers the instance, + // synchronously after it; until then the terminal service does not know it. + queueMicrotask(() => this._adoptTerminalViewTerminal(instance)); + } + })); + // Repeated New Session actions replace one draft with another. Transfer - // the old draft's terminals when both drafts use the same cwd and backend. + // the old draft's terminals when both drafts use the same cwd and backend; + // otherwise release them, like those of a discarded draft, so a later + // session in their cwd and backend reuses them instead of creating new ones. this._register(this._sessionsManagementService.onDidReplaceNewDraftSession(({ from, to }) => { this._onDidReplaceNewDraftSession(from, to); })); + // A discarded draft no longer owns its terminals: release them so the + // next session in the same cwd reuses them instead of creating new ones. + this._register(this._sessionsManagementService.onDidDiscardNewSession(session => { + this._onDidDiscardNewSession(session); + })); + // When a session is replaced (untitled → committed graduation), transfer // tracked terminals from the old session id to the new one so they are // not orphaned and closed by the removal cleanup. @@ -243,7 +285,6 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben // (e.g. user closes a terminal tab) so the map doesn't hold stale entries. this._register(this._terminalService.onDidDisposeInstance(instance => { this._removeTerminalFromTrackedSessions(instance.instanceId); - this._standaloneTerminalIds.delete(instance.instanceId); this._chatWindowTerminalIds.delete(instance.instanceId); })); @@ -350,7 +391,76 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben } } - private async _ensureTerminal(cwd: URI, focus: boolean, session?: ISession, generation?: number, requireCwdMatch = false, location?: ITerminalLocationOptions): Promise { + /** + * Gives the active session the terminal it skipped while the terminal view + * was hidden, reusing a terminal in its cwd when there is one. + */ + private async _onTerminalViewShown(): Promise { + const session = this._mainWindowHost.session.get(); + if (!session || session.loading.get() || session.isArchived.get() || session.worktreePending?.get() || !this._isSessionRemoteHostAvailable(session)) { + return undefined; + } + this._activeKey = undefined; + this._activeAgentHostAddress = undefined; + this._activeSessionId = undefined; + await this._onActiveSessionChanged(session, this._mainWindowHost.chat.get()); + return session; + } + + /** + * Whether the terminal could be the one the terminal view creates when it + * opens empty: a shell in the panel that no editor, task, extension or + * restored terminal session asked for. It may run on a custom pty, since + * an Agent Host profile can be the default profile; the custom ptys of + * tasks, extensions and revived Agent Host terminals carry the flags below. + */ + private _couldBeTerminalViewShell(instance: ITerminalInstance): boolean { + const config = instance.shellLaunchConfig; + return instance.target === TerminalLocation.Panel + && !config.hideFromUser + && !config.isFeatureTerminal + && !config.isExtensionOwnedTerminal + && config.type !== 'Task' + && !config.extHostTerminalId + && !config.attachPersistentProcess; + } + + /** + * Makes the terminal the terminal view created when it opened empty the + * active session's terminal, then shows the session's terminals. + */ + private _adoptTerminalViewTerminal(instance: ITerminalInstance): void { + const session = this._mainWindowHost.session.get(); + const sessionId = this._activeSessionId; + const key = this._activeKey; + const agentHostAddress = this._activeAgentHostAddress; + const available = this._getAvailableTerminal(instance, 'adopt the terminal view terminal'); + if (available && session && sessionId === session.sessionId && key !== undefined && this._getTrackedTerminalsForSession(sessionId).length === 0) { + if (this._isTerminalViewShellOnBackend(available, agentHostAddress)) { + this._logService.trace(`[SessionsTerminal] Adopting terminal ${available.instanceId} the terminal view created for session ${sessionId}`); + this._trackTerminalsForSession(sessionId, [available], { sessionId, key, agentHostAddress }); + } else { + this._logService.trace(`[SessionsTerminal] Not adopting terminal ${available.instanceId}; it does not run where session ${sessionId} runs its terminals`); + } + } + this._onTerminalViewShown(); + } + + /** + * Whether the terminal the terminal view created runs on the given backend: + * the session's Agent Host, or a local shell for a local session. A custom + * pty whose Agent Host is unknown runs on neither. + */ + private _isTerminalViewShellOnBackend(instance: ITerminalInstance, agentHostAddress: string | undefined): boolean { + const instanceAgentHostAddress = this._agentHostTerminalService.getAgentHostAddress(instance); + if (instanceAgentHostAddress !== undefined) { + return instanceAgentHostAddress === agentHostAddress; + } + return !instance.shellLaunchConfig.customPtyImplementation + && (agentHostAddress === undefined || agentHostAddress === LOCAL_AGENT_HOST_ADDRESS); + } + + private async _ensureTerminal(cwd: URI, focus: boolean, session?: ISession, generation?: number, requireCwdMatch = false, location?: ITerminalLocationOptions, createIfMissing = true): Promise { if (session && this._isTerminalOperationCancelled(session, generation)) { return []; } @@ -369,6 +479,10 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben } } + if (existing.length === 0 && !createIfMissing) { + return []; + } + if (existing.length === 0) { try { const instance = await this._createTerminalForSession(cwd, session, location); @@ -519,7 +633,10 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben this._activeAgentHostAddress = targetAgentHostAddress; this._activeSessionId = session.sessionId; - const instances = await this._ensureTerminal(targetPath, false, session, generation, true); + // Only create a terminal when the user can see it; otherwise reuse the + // session's existing terminals and let the view create one when shown. + const createIfMissing = this._viewsService.isViewVisible(TERMINAL_VIEW_ID); + const instances = await this._ensureTerminal(targetPath, false, session, generation, true, undefined, createIfMissing); // If the active session or key changed while we were awaiting, a newer // call has taken over — skip the visibility update to avoid flicker. @@ -543,7 +660,7 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben if (instance.shellLaunchConfig.hideFromUser) { continue; } - if (options?.excludeTracked && (this._isTerminalTracked(instance.instanceId) || this._standaloneTerminalIds.has(instance.instanceId))) { + if (options?.excludeTracked && this._isTerminalTracked(instance.instanceId)) { continue; } try { @@ -609,23 +726,46 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben if (fromCwd === toCwd && fromAgentHostAddress === toAgentHostAddress) { this._transferTerminals(from.sessionId, to.sessionId); } else { - this._rehomeTerminals(from.sessionId); + this._releaseTerminals(from.sessionId, 'replaced'); + } + } + + private _onDidDiscardNewSession(session: ISession): void { + const pendingOperation = this._pendingTerminalOperations.get(session.sessionId); + if (pendingOperation) { + pendingOperation.replaced = true; } + this._releaseTerminals(session.sessionId, 'discarded'); } - private _rehomeTerminals(sessionId: string): void { - const terminals = this._getTrackedTerminalsForSession(sessionId); - for (const terminal of terminals) { - this._standaloneTerminalIds.add(terminal.instanceId); - this._trackedTerminalScopes.delete(terminal.instanceId); + /** + * Releases the terminals of a draft that no longer owns them. They keep + * their scope, so only a later session in the same cwd and on the same + * backend reuses them, and the panel shows them only for such a session. + */ + private _releaseTerminals(sessionId: string, reason: 'discarded' | 'replaced'): void { + const terminalIds = this._sessionTerminals.get(sessionId); + if (!terminalIds) { + return; } - if (terminals.length > 0) { - this._logService.trace(`[SessionsTerminal] Rehomed ${terminals.length} terminal(s) from session ${sessionId}`); + // Those a chat window shows stay the draft's: as the window moves on to another session, it gives them back to the + // panel, rather than taking them for that session, and no other session reuses them meanwhile. + const released = [...terminalIds].filter(id => !this._chatWindowTerminalIds.has(id)); + released.forEach(id => terminalIds.delete(id)); + if (released.length > 0) { + this._logService.trace(`[SessionsTerminal] Released ${released.length} terminal(s) of ${reason} session ${sessionId}`); + } + if (terminalIds.size === 0) { + this._sessionTerminals.delete(sessionId); } - this._sessionTerminals.delete(sessionId); } private _transferTerminals(fromSessionId: string, toSessionId: string): void { + // A session can be replaced by one with the same id (e.g. a draft that + // graduates in place): its terminals already belong to the target. + if (fromSessionId === toSessionId) { + return; + } const terminalIds = this._sessionTerminals.get(fromSessionId); if (terminalIds && terminalIds.size > 0) { let targetIds = this._sessionTerminals.get(toSessionId); @@ -683,9 +823,10 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben } private _removeTerminalFromTrackedSessions(instanceId: number): void { + // Also of a terminal no session tracks any longer, such as one of a discarded draft. + this._trackedTerminalScopes.delete(instanceId); for (const [sessionId, terminalIds] of this._sessionTerminals) { terminalIds.delete(instanceId); - this._trackedTerminalScopes.delete(instanceId); if (terminalIds.size === 0) { this._sessionTerminals.delete(sessionId); } @@ -737,7 +878,7 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben for (const instance of [...this._terminalService.instances]) { // Skip hidden tool terminals — managed by the chat tool lifecycle - if (instance.shellLaunchConfig.hideFromUser || this._standaloneTerminalIds.has(instance.instanceId) || this._chatWindowTerminalIds.has(instance.instanceId)) { + if (instance.shellLaunchConfig.hideFromUser || this._chatWindowTerminalIds.has(instance.instanceId)) { continue; } const currentInstance = this._getAvailableTerminal(instance, 'update terminal visibility'); @@ -778,7 +919,7 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben let mostRecent: ITerminalInstance | undefined; let mostRecentTimestamp = -1; for (const instance of foreground) { - if (this._standaloneTerminalIds.has(instance.instanceId) || this._chatWindowTerminalIds.has(instance.instanceId)) { + if (this._chatWindowTerminalIds.has(instance.instanceId)) { continue; } if (!await this._terminalMatchesScope(instance, activeKey, activeAgentHostAddress)) { @@ -859,7 +1000,6 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben } if (untrackedWorktreeTerminalIds.has(instance.instanceId) && (this._isTerminalTracked(instance.instanceId) - || this._standaloneTerminalIds.has(instance.instanceId) || this._terminalService.activeInstance?.instanceId === instance.instanceId)) { continue; } @@ -904,14 +1044,12 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben for (const instance of this._terminalService.instances) { if (!instance.shellLaunchConfig.attachPersistentProcess || instance.shellLaunchConfig.hideFromUser - || this._isTerminalTracked(instance.instanceId) - || this._standaloneTerminalIds.has(instance.instanceId)) { + || this._isTerminalTracked(instance.instanceId)) { continue; } try { if (isEqual(URI.file(await instance.getInitialCwd()), resource) - && !this._isTerminalTracked(instance.instanceId) - && !this._standaloneTerminalIds.has(instance.instanceId)) { + && !this._isTerminalTracked(instance.instanceId)) { result.push(instance); } } catch { @@ -924,7 +1062,6 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben async dumpTracking(): Promise { console.log(`[SessionsTerminal] Active key: ${this._activeKey ?? ''}`); console.log(`[SessionsTerminal] Session terminals: ${JSON.stringify([...this._sessionTerminals.entries()].map(([sessionId, terminalIds]) => [sessionId, [...terminalIds]]))}`); - console.log(`[SessionsTerminal] Standalone terminals: ${JSON.stringify([...this._standaloneTerminalIds])}`); console.log('[SessionsTerminal] === All Terminals ==='); for (const instance of this._terminalService.instances) { let cwd = ''; @@ -1000,7 +1137,6 @@ export class SessionsTerminalContribution extends Disposable implements IWorkben // or on another host than the session's, which matching the session's terminals checks then. this._removeTerminalFromTrackedSessions(instance.instanceId); this._trackedTerminalScopes.delete(instance.instanceId); - this._standaloneTerminalIds.delete(instance.instanceId); this._trackTerminalsForSession(session.sessionId, [instance]); } diff --git a/src/vs/sessions/contrib/terminal/test/browser/sessionsTerminalContribution.test.ts b/src/vs/sessions/contrib/terminal/test/browser/sessionsTerminalContribution.test.ts index 42b984f129c0..9869887c2c09 100644 --- a/src/vs/sessions/contrib/terminal/test/browser/sessionsTerminalContribution.test.ts +++ b/src/vs/sessions/contrib/terminal/test/browser/sessionsTerminalContribution.test.ts @@ -7,9 +7,9 @@ import assert from 'assert'; import { DeferredPromise } from '../../../../../base/common/async.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; -import { Emitter } from '../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; import { constObservable, IReader, observableValue } from '../../../../../base/common/observable.js'; -import { IAgentHostTerminalCreateOptions, IAgentHostTerminalService } from '../../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; +import { IAgentHostTerminalCreateOptions, IAgentHostTerminalProfileInfo, IAgentHostTerminalService } from '../../../../../workbench/contrib/terminal/browser/agentHostTerminalService.js'; import { ITerminalProfileService, TERMINAL_VIEW_ID, TerminalCommandId } from '../../../../../workbench/contrib/terminal/common/terminal.js'; import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; @@ -18,8 +18,9 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { mock } from '../../../../../base/test/common/mock.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { NullLogService, ILogService } from '../../../../../platform/log/common/log.js'; -import { ITerminalInstance, ITerminalService } from '../../../../../workbench/contrib/terminal/browser/terminal.js'; +import { ITerminalGroup, ITerminalGroupService, ITerminalInstance, ITerminalService } from '../../../../../workbench/contrib/terminal/browser/terminal.js'; import { ITerminalCapabilityStore, ICommandDetectionCapability, TerminalCapability } from '../../../../../platform/terminal/common/capabilities/capabilities.js'; +import { TerminalLocation } from '../../../../../platform/terminal/common/terminal.js'; import { toAgentHostUri } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { AgentSessionProviders } from '../../../../../workbench/contrib/chat/browser/agentSessions/agentSessions.js'; import { ChatInteractivity, IChat, ISession, ISessionWorkspace, SessionRemoteConnectionFailureReason, SessionRemoteConnectionStatus } from '../../../../../workbench/services/sessions/common/session.js'; @@ -67,6 +68,8 @@ type TestTerminalInstance = ITerminalInstance & { _testSetDisposed(disposed: boolean): void; _testSetInitialCwdBarrier(barrier: Promise | undefined): void; _testSetShellLaunchConfig(shellLaunchConfig: ITerminalInstance['shellLaunchConfig']): void; + /** Makes the process start: its cwd stays unknown, as `''`, until it is ready. */ + _testSetProcessStarting(): DeferredPromise; }; type TestActiveSession = ITestSessionWithChat & { @@ -237,6 +240,8 @@ function makeTerminalInstance(id: number, cwd: string): TestTerminalInstance { const commandHistory: { timestamp: number }[] = []; let isDisposed = false; let initialCwdBarrier: Promise | undefined; + let processReady = Promise.resolve(); + let processStarting = false; let shellLaunchConfig: ITerminalInstance['shellLaunchConfig'] = {} as ITerminalInstance['shellLaunchConfig']; const capabilities = { get(cap: TerminalCapability) { @@ -251,9 +256,13 @@ function makeTerminalInstance(id: number, cwd: string): TestTerminalInstance { instanceId: id, get isDisposed() { return isDisposed; }, get shellLaunchConfig() { return shellLaunchConfig; }, + get processReady() { return processReady; }, + target: TerminalLocation.Panel, + onDisposed: Event.None, + onExit: Event.None, async getInitialCwd() { await initialCwdBarrier; - return cwd; + return processStarting ? '' : cwd; }, capabilities, _testCommandHistory: commandHistory, @@ -266,6 +275,12 @@ function makeTerminalInstance(id: number, cwd: string): TestTerminalInstance { _testSetShellLaunchConfig(value: ITerminalInstance['shellLaunchConfig']) { shellLaunchConfig = value; }, + _testSetProcessStarting() { + const ready = new DeferredPromise(); + processStarting = true; + processReady = ready.p.then(() => { processStarting = false; }); + return ready; + }, } as unknown as TestTerminalInstance; } @@ -280,6 +295,7 @@ suite('SessionsTerminalContribution', () => { let onDidChangeSessions: Emitter; let onDidReplaceSession: Emitter<{ readonly from: ISession; readonly to: ISession }>; let onDidReplaceNewDraftSession: Emitter<{ readonly from: ISession; readonly to: ISession }>; + let onDidDiscardNewSession: Emitter; let onDidCreateInstance: Emitter; let onDidDisposeInstance: Emitter; @@ -287,6 +303,7 @@ suite('SessionsTerminalContribution', () => { let agentHostTerminalAddresses: string[]; /** The agent host each agent host terminal runs on, keyed by instance id. */ let agentHostTerminalAddressById: Map; + let agentHostProfilesAvailable: boolean; let terminalCreationBarriers: Map>; let terminalCreationStarted: string[]; let activeInstanceSet: number[]; @@ -307,11 +324,15 @@ suite('SessionsTerminalContribution', () => { let sessionProviders: Map; let instantiationService: TestInstantiationService; let cwdExists: (uri: URI) => boolean; + let terminalViewVisible: boolean; + let terminalGroupCount: number; + let viewVisibilityEmitter: Emitter<{ id: string; visible: boolean }>; setup(() => { createdTerminals = []; agentHostTerminalAddresses = []; agentHostTerminalAddressById = new Map(); + agentHostProfilesAvailable = true; terminalCreationBarriers = new Map(); terminalCreationStarted = []; activeInstanceSet = []; @@ -337,6 +358,7 @@ suite('SessionsTerminalContribution', () => { onDidChangeSessions = store.add(new Emitter()); onDidReplaceSession = store.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); onDidReplaceNewDraftSession = store.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); + onDidDiscardNewSession = store.add(new Emitter()); onDidCreateInstance = store.add(new Emitter()); onDidDisposeInstance = store.add(new Emitter()); @@ -346,6 +368,7 @@ suite('SessionsTerminalContribution', () => { override readonly onDidChangeSessions = onDidChangeSessions.event; override readonly onDidReplaceSession = onDidReplaceSession.event; override readonly onDidReplaceNewDraftSession = onDidReplaceNewDraftSession.event; + override readonly onDidDiscardNewSession = onDidDiscardNewSession.event; override getSessions(): ISession[] { return [...allSessions]; } }); instantiationService.stub(ISessionsService, new class extends mock() { @@ -422,7 +445,9 @@ suite('SessionsTerminalContribution', () => { instantiationService.stub(IAgentHostTerminalService, new class extends mock() { override readonly profiles = constObservable([]); - override getProfileForConnection() { return undefined; } + override getProfileForConnection(address: string): IAgentHostTerminalProfileInfo | undefined { + return agentHostProfilesAvailable ? { extensionIdentifier: 'vscode.agent-host-terminal', profileId: `agent-host-${address}`, title: address, address } : undefined; + } override setDefaultCwd(cwd: URI | undefined): void { defaultCwdCalls.push(cwd); } override async createTerminalForEntry(address: string, options?: IAgentHostTerminalCreateOptions): Promise { const cwd = typeof options?.cwd === 'string' ? URI.file(options.cwd) : options?.cwd; @@ -453,9 +478,16 @@ suite('SessionsTerminalContribution', () => { instantiationService.stub(IContextKeyService, store.add(new MockContextKeyService())); + terminalGroupCount = 1; + instantiationService.stub(ITerminalGroupService, new class extends mock() { + override get groups(): ITerminalGroup[] { return new Array(terminalGroupCount); } + }); + + terminalViewVisible = true; + viewVisibilityEmitter = store.add(new Emitter<{ id: string; visible: boolean }>()); instantiationService.stub(IViewsService, new class extends mock() { - override isViewVisible(): boolean { return false; } - override onDidChangeViewVisibility = store.add(new Emitter<{ id: string; visible: boolean }>()).event; + override isViewVisible(id: string): boolean { return id === TERMINAL_VIEW_ID && terminalViewVisible; } + override onDidChangeViewVisibility = viewVisibilityEmitter.event; }); contribution = store.add(instantiationService.createInstance(SessionsTerminalContribution)); @@ -483,6 +515,309 @@ suite('SessionsTerminalContribution', () => { assert.strictEqual(createdTerminals[0].cwd.fsPath, repoUri.fsPath); }); + // --- Terminal view hidden: create terminals lazily --- + + test('does not create terminals for sessions while the terminal view is hidden', async () => { + terminalViewVisible = false; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + activeSessionObs.set(makeAgentSession({ sessionId: 'session-b', worktree: URI.file('/worktree-b'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + assert.deepStrictEqual(createdTerminals.map(t => t.cwd.fsPath), []); + }); + + test('creates the terminal of the active session when the terminal view becomes visible', async () => { + terminalViewVisible = false; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + activeSessionObs.set(makeAgentSession({ sessionId: 'session-b', worktree: URI.file('/worktree-b'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + + assert.deepStrictEqual(createdTerminals.map(t => t.cwd.fsPath), [URI.file('/worktree-b').fsPath]); + }); + + test('adopts the terminal the terminal view creates when it opens empty', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + const session = makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }); + activeSessionObs.set(session, undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), backgrounded: [...backgroundedInstances] }, { created: [], backgrounded: [] }); + }); + + test('adopts the terminal the terminal view creates before its shell starts', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + const ready = viewTerminal._testSetProcessStarting(); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), disposed: disposedInstances.map(i => i.instanceId) }, { created: [], disposed: [] }); + ready.complete(); + }); + + test('adopts the Agent Host terminal the terminal view creates before its shell starts', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + sessionProviders.set('agenthost-one', { id: 'agenthost-one', remoteAddress: 'ssh-remote+one' } as unknown as ISessionsProvider); + activeSessionObs.set(makeAgentSession({ sessionId: 'test:host-one', providerId: 'agenthost-one', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + // With the session's Agent Host profile as the default profile, the view creates + // its terminal through AgentHostTerminalService.createTerminal, on a custom pty. + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + viewTerminal._testSetShellLaunchConfig({ customPtyImplementation: () => { throw new Error('not started in this test'); }, name: 'Agent Host', hostLabel: 'one', isRemotePty: true, isFeatureTerminal: false } as ITerminalInstance['shellLaunchConfig']); + const ready = viewTerminal._testSetProcessStarting(); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + // AgentHostTerminalService knows the terminal's host as soon as the instance exists. + agentHostTerminalAddressById.set(viewTerminal.instanceId, 'ssh-remote+one'); + onDidCreateInstance.fire(viewTerminal); + await tick(); + + assert.deepStrictEqual({ created: agentHostTerminalAddresses, disposed: disposedInstances.map(i => i.instanceId) }, { created: [], disposed: [] }); + ready.complete(); + }); + + test('adopts the terminal the terminal view creates before its terminal group registers it', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + const worktreeUri = URI.file('/remote/worktree'); + sessionProviders.set('agenthost-test', { id: 'agenthost-test', remoteAddress: 'remote-test' } as unknown as ISessionsProvider); + activeSessionObs.set(makeAgentSession({ providerId: 'agenthost-test', worktree: toAgentHostUri(worktreeUri, 'remote-test'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, worktreeUri.fsPath); + viewTerminal._testSetShellLaunchConfig({ customPtyImplementation: () => { throw new Error('not started in this test'); }, name: 'Agent Host', hostLabel: 'remote-test', isRemotePty: true, isFeatureTerminal: false } as ITerminalInstance['shellLaunchConfig']); + agentHostTerminalAddressById.set(viewTerminal.instanceId, 'remote-test'); + // The terminal group fires onDidCreateInstance before it adds the instance to its group, + // and a remote session's cwd needs no check on disk before the session's terminals are read. + onDidCreateInstance.fire(viewTerminal); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + await tick(); + + assert.deepStrictEqual({ created: agentHostTerminalAddresses, backgrounded: [...backgroundedInstances] }, { created: [], backgrounded: [] }); + }); + + test('does not adopt an Agent Host terminal on another host that is created while the terminal view opens empty', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + sessionProviders.set('agenthost-two', { id: 'agenthost-two', remoteAddress: 'ssh-remote+two' } as unknown as ISessionsProvider); + activeSessionObs.set(makeAgentSession({ sessionId: 'test:host-two', providerId: 'agenthost-two', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + // The user creates a terminal on another Agent Host while the session's host is the default profile. + const otherHostTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + otherHostTerminal._testSetShellLaunchConfig({ customPtyImplementation: () => { throw new Error('not started in this test'); }, name: 'Agent Host', hostLabel: 'one', isRemotePty: true, isFeatureTerminal: false } as ITerminalInstance['shellLaunchConfig']); + terminalInstances.set(otherHostTerminal.instanceId, otherHostTerminal); + terminalGroupCount = 1; + agentHostTerminalAddressById.set(otherHostTerminal.instanceId, 'ssh-remote+one'); + onDidCreateInstance.fire(otherHostTerminal); + await tick(); + + assert.deepStrictEqual({ created: agentHostTerminalAddresses, backgrounded: [...backgroundedInstances] }, { created: ['ssh-remote+two'], backgrounded: [otherHostTerminal.instanceId] }); + }); + + test('does not adopt a custom pty terminal of an unknown host for a remote session whose host is the default profile', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + sessionProviders.set('agenthost-two', { id: 'agenthost-two', remoteAddress: 'ssh-remote+two' } as unknown as ISessionsProvider); + activeSessionObs.set(makeAgentSession({ sessionId: 'test:host-two', providerId: 'agenthost-two', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + // A custom pty that no Agent Host created, such as an extension's pseudoterminal, or an + // Agent Host terminal on host one whose host the view could not tell when it was created. + const otherTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + otherTerminal._testSetShellLaunchConfig({ customPtyImplementation: () => { throw new Error('not started in this test'); }, name: 'Agent Host', hostLabel: 'one', isRemotePty: true, isFeatureTerminal: false } as ITerminalInstance['shellLaunchConfig']); + terminalInstances.set(otherTerminal.instanceId, otherTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(otherTerminal); + await Promise.resolve(); + agentHostTerminalAddressById.set(otherTerminal.instanceId, 'ssh-remote+one'); + await tick(); + + assert.deepStrictEqual({ created: agentHostTerminalAddresses, backgrounded: [...backgroundedInstances] }, { created: ['ssh-remote+two'], backgrounded: [otherTerminal.instanceId] }); + }); + + test('does not adopt a custom pty terminal the terminal view creates for a local session', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + // The user's default profile is a contributed profile that runs on a custom pty. + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + viewTerminal._testSetShellLaunchConfig({ customPtyImplementation: () => { throw new Error('not started in this test'); }, name: 'Contributed', isFeatureTerminal: false } as ITerminalInstance['shellLaunchConfig']); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), backgrounded: [...backgroundedInstances] }, { created: [URI.file('/worktree-a').fsPath], backgrounded: [viewTerminal.instanceId] }); + }); + + test('does not adopt a local terminal the terminal view creates for an Agent Host session without a profile', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + agentHostProfilesAvailable = false; + sessionProviders.set('agenthost-one', { id: 'agenthost-one', remoteAddress: 'ssh-remote+one' } as unknown as ISessionsProvider); + activeSessionObs.set(makeAgentSession({ sessionId: 'test:host-one', providerId: 'agenthost-one', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + // Without an Agent Host profile to make the default, the view starts a local shell. + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + assert.deepStrictEqual({ created: agentHostTerminalAddresses, backgrounded: [...backgroundedInstances] }, { created: ['ssh-remote+one'], backgrounded: [viewTerminal.instanceId] }); + }); + + test('does not create a second terminal when the terminal view is shown again while its terminal starts', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + const ready = viewTerminal._testSetProcessStarting(); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: false }); + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + ready.complete(); + await tick(); + + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), disposed: disposedInstances.map(i => i.instanceId) }, { created: [], disposed: [] }); + }); + + test('adopts the terminal the terminal view creates outside the session cwd', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/configured-cwd').fsPath); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + // It is the terminal the view shows, for example with `terminal.integrated.cwd` set. + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), disposed: disposedInstances.map(i => i.instanceId) }, { created: [], disposed: [] }); + }); + + test('does not take a terminal created elsewhere for the terminal view terminal', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + const editorTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/elsewhere').fsPath); + editorTerminal.target = TerminalLocation.Editor; + const extensionTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/elsewhere').fsPath); + extensionTerminal._testSetShellLaunchConfig({ isExtensionOwnedTerminal: true } as ITerminalInstance['shellLaunchConfig']); + const taskTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/elsewhere').fsPath); + taskTerminal._testSetShellLaunchConfig({ type: 'Task' } as ITerminalInstance['shellLaunchConfig']); + for (const unrelated of [editorTerminal, extensionTerminal, taskTerminal]) { + terminalInstances.set(unrelated.instanceId, unrelated); + onDidCreateInstance.fire(unrelated); + } + await tick(); + const viewTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/worktree-a').fsPath); + terminalInstances.set(viewTerminal.instanceId, viewTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(viewTerminal); + await tick(); + + // Switching to another session moves only the adopted view terminal to the background. + activeSessionObs.set(makeAgentSession({ sessionId: 'session-b', worktree: URI.file('/worktree-b'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + assert.deepStrictEqual({ created: createdTerminals.map(t => t.cwd.fsPath), backgrounded: [...backgroundedInstances].includes(viewTerminal.instanceId) }, { created: [URI.file('/worktree-b').fsPath], backgrounded: true }); + }); + + test('creates the terminal when the terminal view is shown again after it opened empty without creating one', async () => { + terminalViewVisible = false; + terminalGroupCount = 0; + activeSessionObs.set(makeAgentSession({ sessionId: 'session-a', worktree: URI.file('/worktree-a'), providerType: AgentSessionProviders.Background }), undefined); + await tick(); + + // For example with `terminal.integrated.hideOnStartup`, the view closes again without creating a terminal. + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + terminalViewVisible = false; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: false }); + await tick(); + const userTerminal = makeTerminalInstance(nextInstanceId++, URI.file('/elsewhere').fsPath); + terminalInstances.set(userTerminal.instanceId, userTerminal); + terminalGroupCount = 1; + onDidCreateInstance.fire(userTerminal); + terminalViewVisible = true; + viewVisibilityEmitter.fire({ id: TERMINAL_VIEW_ID, visible: true }); + await tick(); + + assert.deepStrictEqual(createdTerminals.map(t => t.cwd.fsPath), [URI.file('/worktree-a').fsPath]); + }); + // --- Missing local working directory: defer until it exists --- test('does not create a local terminal when the working directory does not exist', async () => { @@ -1070,7 +1405,61 @@ suite('SessionsTerminalContribution', () => { }); }); - test('rehomes terminals when replacement drafts use different cwd values', async () => { + test('reuses the terminal of a discarded draft for the next session in the same cwd', async () => { + const cwd = URI.file('/worktree'); + const draftSession = makeAgentSession({ sessionId: 'test:draft', worktree: cwd, providerType: AgentSessionProviders.Background }); + const nextSession = makeAgentSession({ sessionId: 'test:next', worktree: cwd, providerType: AgentSessionProviders.Background }); + + await contribution.ensureTerminal(cwd, false, draftSession); + onDidDiscardNewSession.fire(draftSession); + const result = await contribution.ensureTerminal(cwd, false, nextSession); + + assert.deepStrictEqual({ + result: result.map(instance => instance.instanceId), + created: createdTerminals.length, + disposed: disposedInstances.map(instance => instance.instanceId), + }, { + result: [1], + created: 1, + disposed: [], + }); + }); + + test('keeps the terminal a chat window shows of a discarded draft the draft\'s, for the window to give back to the panel, rather than to another session', async () => { + const cwd = URI.file('/worktree'); + const draftSession = makeAgentSession({ sessionId: 'test:draft', worktree: cwd, providerType: AgentSessionProviders.Background }); + const nextSession = makeAgentSession({ sessionId: 'test:next', worktree: cwd, providerType: AgentSessionProviders.Background }); + const shown = (await contribution.createChatWindowTerminal(draftSession, draftSession.activeChat.get()))!; + + onDidDiscardNewSession.fire(draftSession); + const ownerAfterDiscard = contribution.getChatWindowTerminalOwner(shown); + const next = await contribution.ensureTerminal(cwd, false, nextSession); + + assert.deepStrictEqual({ + ownerAfterDiscard, + ownerAfterNext: contribution.getChatWindowTerminalOwner(shown), + next: next.map(instance => instance.instanceId), + }, { + ownerAfterDiscard: 'test:draft', + ownerAfterNext: 'test:draft', + next: [shown.instanceId + 1], + }); + }); + + test('forgets the scope of the terminal of a discarded draft as it closes', async () => { + const cwd = URI.file('/worktree'); + const draftSession = makeAgentSession({ sessionId: 'test:draft', worktree: cwd, providerType: AgentSessionProviders.Background }); + const [terminal] = await contribution.ensureTerminal(cwd, false, draftSession); + onDidDiscardNewSession.fire(draftSession); + + (terminal as TestTerminalInstance)._testSetDisposed(true); + terminalInstances.delete(terminal.instanceId); + onDidDisposeInstance.fire(terminal); + + assert.deepStrictEqual([...(contribution as unknown as { _trackedTerminalScopes: Map })._trackedTerminalScopes.keys()], []); + }); + + test('reuses the terminal of a replaced draft when a later draft returns to its cwd', async () => { const firstCwd = URI.file('/worktree-one'); const secondCwd = URI.file('/worktree-two'); const thirdSession = makeAgentSession({ sessionId: 'test:third-draft', worktree: firstCwd, providerType: AgentSessionProviders.Background }); @@ -1098,17 +1487,40 @@ suite('SessionsTerminalContribution', () => { backgrounded: moveToBackgroundCalls, disposed: disposedInstances.map(instance => instance.instanceId), }, { - createdCwds: [firstCwd.fsPath, secondCwd.fsPath, firstCwd.fsPath], + createdCwds: [firstCwd.fsPath, secondCwd.fsPath], firstStillAlive: true, secondStillAlive: true, - thirdTerminalId: 3, - activeTerminalId: 3, - backgrounded: [], + thirdTerminalId: 1, + activeTerminalId: 1, + backgrounded: [1, 2], disposed: [], }); }); - test('rehomes a same-cwd terminal when the Agent Host backend changes', async () => { + test('keeps one terminal per cwd while replacement drafts alternate between cwd values', async () => { + const cwds = [URI.file('/worktree-one'), URI.file('/worktree-two')]; + const sessions = Array.from({ length: 6 }, (_, index) => makeAgentSession({ sessionId: `test:draft-${index}`, worktree: cwds[index % 2], providerType: AgentSessionProviders.Background })); + + activeSessionObs.set(sessions[0], undefined); + await tick(); + for (let index = 1; index < sessions.length; index++) { + onDidReplaceNewDraftSession.fire({ from: sessions[index - 1], to: sessions[index] }); + activeSessionObs.set(sessions[index], undefined); + await tick(); + } + + assert.deepStrictEqual({ + createdCwds: createdTerminals.map(terminal => terminal.cwd.fsPath), + activeTerminalId: activeInstanceId, + disposed: disposedInstances.map(instance => instance.instanceId), + }, { + createdCwds: [cwds[0].fsPath, cwds[1].fsPath], + activeTerminalId: 2, + disposed: [], + }); + }); + + test('does not reuse the terminal of a replaced draft on another Agent Host backend', async () => { const cwd = URI.file('/worktree'); sessionProviders.set('agenthost-one', new class extends mock() { override readonly id = 'agenthost-one'; @@ -1149,12 +1561,12 @@ suite('SessionsTerminalContribution', () => { agentHostAddresses: ['ssh-remote+one', 'ssh-remote+two'], firstStillAlive: true, secondTerminalId: 2, - backgrounded: [], + backgrounded: [1], disposed: [], }); }); - test('allows generic lookup to reuse a standalone terminal', async () => { + test('allows generic lookup to reuse the terminal of a replaced draft', async () => { const firstCwd = URI.file('/worktree-one'); const secondCwd = URI.file('/worktree-two'); const firstSession = makeAgentSession({ sessionId: 'test:first-draft', worktree: firstCwd, providerType: AgentSessionProviders.Background }); @@ -2333,6 +2745,23 @@ suite('SessionsTerminalContribution', () => { assert.strictEqual(result[0].instanceId, terminalId); }); + test('keeps tracking terminals when a session is replaced by one with the same id, so deleting it later closes them', async () => { + const worktreeUri = URI.file('/worktree'); + const draftSession = makeAgentSession({ sessionId: 'test:same', worktree: worktreeUri, providerType: AgentSessionProviders.Background }); + const committedSession = makeAgentSession({ sessionId: 'test:same', worktree: worktreeUri, providerType: AgentSessionProviders.Background }); + + await contribution.ensureTerminal(worktreeUri, false, draftSession); + onDidReplaceSession.fire({ from: draftSession, to: committedSession }); + + // The user moved on to another session: the terminal went to the background. + activeInstanceId = undefined; + backgroundedInstances.add(1); + onDidChangeSessions.fire({ added: [], removed: [committedSession], changed: [] }); + await tick(); + + assert.deepStrictEqual(disposedInstances.map(instance => instance.instanceId), [1]); + }); + test('cleans up tracked terminal ids when terminals are externally disposed', async () => { const worktreeUri = URI.file('/worktree'); const session = makeAgentSession({ sessionId: 'test:session', worktree: worktreeUri, providerType: AgentSessionProviders.Background }); diff --git a/src/vs/sessions/contrib/workspace/test/browser/workspaceFolderManagement.test.ts b/src/vs/sessions/contrib/workspace/test/browser/workspaceFolderManagement.test.ts index 3b8af0f6624c..e71bfe15e82a 100644 --- a/src/vs/sessions/contrib/workspace/test/browser/workspaceFolderManagement.test.ts +++ b/src/vs/sessions/contrib/workspace/test/browser/workspaceFolderManagement.test.ts @@ -4,12 +4,13 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { mainWindow } from '../../../../../base/browser/window.js'; import { Emitter } from '../../../../../base/common/event.js'; -import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { constObservable, IObservable, observableValue } from '../../../../../base/common/observable.js'; import { extUri } from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { Codicon } from '../../../../../base/common/codicons.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 { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { IWorkspace, IWorkspaceContextService, IWorkspaceFolder, IWorkspaceFoldersChangeEvent, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; @@ -20,6 +21,9 @@ import { IWorkspaceFolderLabelService } from '../../../../../workbench/services/ import { IHistoryService } from '../../../../../workbench/services/history/common/history.js'; import { ChatInteractivity, IChat, ISessionFolder, ISessionGitRepository, ISessionWorkspace } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionsService } from '../../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { IHostService } from '../../../../../workbench/services/host/browser/host.js'; +import { IFocusedSessionHostService, ISessionHost, ISessionHostService, SessionHostContent } from '../../../../../workbench/services/sessions/browser/sessionHost.js'; +import { FocusedSessionHostService } from '../../../../../workbench/contrib/sessions/browser/sessionHostService.js'; import { WorkspaceFolderManagementContribution } from '../../browser/workspaceFolderManagement.js'; import { focusedSessionHostServiceOf, ITestSessionWithChat } from '../../../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; @@ -164,7 +168,7 @@ suite('WorkspaceFolderManagementContribution', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); - function createContribution() { + function createContribution(createFocusedSessionHostService?: () => IFocusedSessionHostService) { const activeSession = observableValue('activeSession', undefined); const workspaceEditing = new TestWorkspaceEditing(); const workspaceTrust = new TestWorkspaceTrust(); @@ -198,7 +202,7 @@ suite('WorkspaceFolderManagementContribution', () => { }; const contribution = disposables.add(new WorkspaceFolderManagementContribution( - focusedSessionHostServiceOf(sessionsService.activeSession), + createFocusedSessionHostService?.() ?? focusedSessionHostServiceOf(sessionsService.activeSession), uriIdentityService, workspaceContextService, workspaceEditing, @@ -533,4 +537,47 @@ suite('WorkspaceFolderManagementContribution', () => { removed: [[trustedFolder.workingDirectory.toString()]], }); }); + + test('follows the focused host to the main window when focus returns from a chat window', async () => { + const mainWindowId = mainWindow.vscodeWindowId; + const chatWindowId = mainWindowId + 1000; + const onDidChangeActiveWindow = disposables.add(new Emitter()); + const mainChat = observableValue('mainChat', undefined); + const windowChat = observableValue('windowChat', undefined); + const makeHost = (windowId: number, chat: IObservable) => upcastPartial({ + windowId: constObservable(windowId), + parent: undefined, + content: constObservable({ kind: 'chat' } as SessionHostContent), + chat, + }); + const mainHost = makeHost(mainWindowId, mainChat); + const chatWindowHost = makeHost(chatWindowId, windowChat); + const sessionHostService = upcastPartial({ + hosts: constObservable([mainHost, chatWindowHost]), + getHostOfWindow: (windowId: number) => windowId === chatWindowId ? chatWindowHost : mainHost, + }); + const hostService = upcastPartial({ onDidChangeActiveWindow: onDidChangeActiveWindow.event }); + const { workspaceEditing } = createContribution(() => disposables.add(new FocusedSessionHostService(sessionHostService, hostService))); + const chatOf = (path: string): IChat => ({ ...stubChat, workspace: constObservable(makeWorkspace(localFolder(path), false)) }); + + windowChat.set(chatOf('/alpha'), undefined); + onDidChangeActiveWindow.fire(chatWindowId); + await settle(); + const whileChatWindowFocused = workspaceEditing.folders.map(folder => folder.uri.path); + mainChat.set(chatOf('/beta'), undefined); + await settle(); + const afterMainChatChanged = workspaceEditing.folders.map(folder => folder.uri.path); + onDidChangeActiveWindow.fire(mainWindowId); + await settle(); + + assert.deepStrictEqual({ + whileChatWindowFocused, + afterMainChatChanged, + afterMainFocused: workspaceEditing.folders.map(folder => folder.uri.path), + }, { + whileChatWindowFocused: ['/alpha'], + afterMainChatChanged: ['/alpha'], + afterMainFocused: ['/beta'], + }); + }); }); diff --git a/src/vs/sessions/contrib/worktreeSuggestion/test/browser/worktreeSuggestionService.test.ts b/src/vs/sessions/contrib/worktreeSuggestion/test/browser/worktreeSuggestionService.test.ts index 978fcfb64670..16ce5a3e3870 100644 --- a/src/vs/sessions/contrib/worktreeSuggestion/test/browser/worktreeSuggestionService.test.ts +++ b/src/vs/sessions/contrib/worktreeSuggestion/test/browser/worktreeSuggestionService.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { Event } from '../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; import { timeout } from '../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; @@ -36,6 +36,7 @@ import { IsPhoneLayoutContext } from '../../../../../workbench/contrib/sessions/ import { ISessionsProvidersService } from '../../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; import { IChat, ISessionChangeset, ISessionFileChange, ISessionWorkspace, SessionStatus, UNCOMMITTED_CHANGES_CHANGESET_ID } from '../../../../../workbench/services/sessions/common/session.js'; import { ISessionsProvider } from '../../../../../workbench/contrib/sessions/common/sessionsProvider.js'; +import { ISendRequestSentEvent, ISessionsManagementService } from '../../../../../workbench/contrib/sessions/common/sessionsManagement.js'; import { CHANGES_VIEW_ID } from '../../../../../workbench/contrib/sessions/common/changes.js'; import { ISessionChangesEditorOptions, ISessionChangesService } from '../../../../../workbench/services/sessions/common/sessionChangesService.js'; import { WORKTREE_SUGGESTION_SETTING, WORKTREE_SUGGESTION_TOUR_ID, WorktreeSuggestionVariant } from '../../../../../workbench/contrib/sessions/common/worktreeSuggestion.js'; @@ -136,6 +137,7 @@ suite('WorktreeSuggestionService', () => { const notifications: unknown[] = []; const onboarding: string[] = []; const shownTours = new Set(options.spotlightShown ? [WORKTREE_SUGGESTION_TOUR_ID] : []); + const onDidSendRequest = store.add(new Emitter()); const service = store.add(new WorktreeSuggestionService( configuration, storage, @@ -220,8 +222,11 @@ suite('WorktreeSuggestionService', () => { } }(), new NullLogService(), + new class extends mock() { + override readonly onDidSendRequest = onDidSendRequest.event; + }(), )); - return { service, storage, telemetry, isolationChanges, opened, notifications, onboarding }; + return { service, storage, telemetry, isolationChanges, opened, notifications, onboarding, onDidSendRequest }; } function summarize(suggestion: IWorktreeSuggestion | undefined) { @@ -326,7 +331,7 @@ suite('WorktreeSuggestionService', () => { }, { initially: false, afterClosing: true, - stored: { hintClosed: true }, + stored: { hintClosed: true, worktreeSessionCreated: false }, inPreview: false, afterClosingInPreview: true, inNextPreview: false, @@ -336,6 +341,41 @@ suite('WorktreeSuggestionService', () => { }); }); + test('remembers a new session started in a new worktree, also during a preview, until reset', () => { + const { service, onDidSendRequest } = createService(); + const created = () => service.hasCreatedWorktreeSession(undefined); + const send = (isNewSession: boolean, isolation: 'worktree' | 'folder' | undefined) => onDidSendRequest.fire({ + session: createSession(), + chat: new class extends mock() { }(), + isNewSession, + isNewChat: true, + newSessionConfig: { isolation, providerConfig: {} }, + options: { query: 'task' }, + }); + + const initially = created(); + send(true, 'folder'); + send(false, 'worktree'); + send(true, undefined); + const afterOtherRequests = created(); + service.setPreview(WorktreeSuggestionVariant.UncommittedFilesCount); + const inPreview = created(); + send(true, 'worktree'); + const afterWorktreeSessionInPreview = created(); + service.setPreview(undefined); + const afterPreview = created(); + service.reset(); + + assert.deepStrictEqual({ initially, afterOtherRequests, inPreview, afterWorktreeSessionInPreview, afterPreview, afterReset: created() }, { + initially: false, + afterOtherRequests: false, + inPreview: false, + afterWorktreeSessionInPreview: true, + afterPreview: true, + afterReset: false, + }); + }); + test('reports each response once per session, and keeps suggesting after the user accepts or declines one', async () => { const variant = WorktreeSuggestionVariant.UncommittedFilesCount; const { service, telemetry, isolationChanges } = createService({ variant }); diff --git a/src/vs/sessions/electron-browser/actions/vscodeActions.ts b/src/vs/sessions/electron-browser/actions/vscodeActions.ts index 2d38a641b2e4..3bc444e51e75 100644 --- a/src/vs/sessions/electron-browser/actions/vscodeActions.ts +++ b/src/vs/sessions/electron-browser/actions/vscodeActions.ts @@ -14,6 +14,8 @@ import { localize2 } from '../../../nls.js'; import { Action2 } from '../../../platform/actions/common/actions.js'; import { IRemoteAgentHostService } from '../../../platform/agentHost/common/remoteAgentHostService.js'; import { IAgentHostConnectionsService } from '../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { ISSHRemoteAgentHostService } from '../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService } from '../../../platform/agentHost/common/tunnelAgentHost.js'; import { INotificationService } from '../../../platform/notification/common/notification.js'; import { KeyCode, KeyMod } from '../../../base/common/keyCodes.js'; @@ -32,7 +34,7 @@ import { OpenInVSCodeTitleBarWidget } from '../../browser/widget/openInVSCodeWid import { IActionViewItemService } from '../../../platform/actions/browser/actionViewItemService.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; import { Disposable } from '../../../base/common/lifecycle.js'; -import { getEditorWindowSessionResource, notifyEditorWindowSessionUnsupported, resolveRemoteFolderUri } from '../../../workbench/contrib/sessions/browser/openInVSCodeUtils.js'; +import { getEditorWindowSessionResource, notifyEditorWindowSessionUnsupported, resolveRemoteAuthority, resolveRemoteFolderUri } from '../../../workbench/contrib/sessions/browser/openInVSCodeUtils.js'; import { INativeHostService } from '../../../platform/native/common/native.js'; import { IFolderToOpen, IOpenedMainWindow } from '../../../platform/window/common/window.js'; import { ILabelService, Verbosity } from '../../../platform/label/common/label.js'; @@ -80,7 +82,8 @@ export async function openSessionInVSCode(accessor: ServicesAccessor, session: I const folders = (chat ?? session?.mainChat.get())?.workspace.get()?.folders; if (!session || !folders?.length) { - return nativeHostService.openWindow(); + const remoteAuthority = session && resolveRemoteAuthority(session.providerId, sessionsProvidersService, remoteAgentHostService); + return nativeHostService.openWindow(remoteAuthority ? { remoteAuthority } : undefined); } const foldersToOpen: IFolderToOpen[] = []; @@ -96,7 +99,7 @@ export async function openSessionInVSCode(accessor: ServicesAccessor, session: I } const chatSessionToOpen = getChatSessionToOpenInEditor(session, chat); - const editorChatSession = chatSessionToOpen && getEditorWindowSessionResource(chatSessionToOpen, session.providerId, sessionsProvidersService, remoteAgentHostService, agentHostConnectionsService, tunnelAgentHostService); + const editorChatSession = chatSessionToOpen && getEditorWindowSessionResource(chatSessionToOpen, session.providerId, sessionsProvidersService, remoteAgentHostService, agentHostConnectionsService, tunnelAgentHostService, accessor.get(ISSHRemoteAgentHostService), accessor.get(IRemoteAgentHostLocationPreferenceService)); if (typeof editorChatSession === 'string') { notifyEditorWindowSessionUnsupported(notificationService, editorChatSession); } diff --git a/src/vs/sessions/services/extensionRecommendations/common/extensionRecommendationsService.ts b/src/vs/sessions/services/extensionRecommendations/common/extensionRecommendationsService.ts new file mode 100644 index 000000000000..975ea439af48 --- /dev/null +++ b/src/vs/sessions/services/extensionRecommendations/common/extensionRecommendationsService.ts @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IStringDictionary } from '../../../../base/common/collections.js'; +import { Event } from '../../../../base/common/event.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IExtensionRecommendationReason, IExtensionRecommendationsService } from '../../../../workbench/services/extensionRecommendations/common/extensionRecommendations.js'; + +/** + * The Agents window doesn't recommend extensions, but shows extension pages, which show why extensions are recommended. + */ +export class NullExtensionRecommendationsService implements IExtensionRecommendationsService { + readonly _serviceBrand: undefined; + + readonly onDidChangeRecommendations = Event.None; + + getAllRecommendationsWithReason(): IStringDictionary { + return {}; + } + + async getImportantRecommendations(): Promise { + return []; + } + + async getOtherRecommendations(): Promise { + return []; + } + + getFileBasedRecommendations(): string[] { + return []; + } + + async getExeBasedRecommendations(): Promise<{ important: string[]; others: string[] }> { + return { important: [], others: [] }; + } + + async getConfigBasedRecommendations(): Promise<{ important: string[]; others: string[] }> { + return { important: [], others: [] }; + } + + async getWorkspaceRecommendations(): Promise> { + return []; + } + + getKeymapRecommendations(): string[] { + return []; + } + + getLanguageRecommendations(): string[] { + return []; + } + + getRemoteRecommendations(): string[] { + return []; + } +} diff --git a/src/vs/sessions/services/sessions/browser/sessionsCoreServices.registration.ts b/src/vs/sessions/services/sessions/browser/sessionsCoreServices.registration.ts new file mode 100644 index 000000000000..90d176405749 --- /dev/null +++ b/src/vs/sessions/services/sessions/browser/sessionsCoreServices.registration.ts @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { IAgentHostCustomizationService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.js'; +import { AgentHostCustomizationService } from '../../../../workbench/contrib/sessions/browser/agentHostCustomizationService.js'; +import { ISessionsService, SessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; +import { ISessionHostService, IFocusedSessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; +import { SessionHostService, FocusedSessionHostService } from '../../../../workbench/contrib/sessions/browser/sessionHostService.js'; +import { IChatHostOpenerService, ChatHostOpenerService } from '../../../../workbench/services/sessions/browser/chatHostOpener.js'; +import { ISessionsListModelService, SessionsListModelService } from '../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; +import { ISessionGroupsService, SessionGroupsService } from '../../../../workbench/contrib/sessions/browser/sessionGroupsService.js'; +import { ISessionComparisonService } from '../../../../workbench/contrib/sessions/common/sessionComparison.js'; +import { SessionComparisonService } from '../../../../workbench/contrib/sessions/browser/sessionComparisonService.js'; +import { ISessionSectionOrderService, SessionSectionOrderService } from '../../../../workbench/services/sessions/browser/sessionSectionOrderService.js'; +import { ISessionOpenTelemetryService, SessionOpenTelemetryService } from '../../../../workbench/contrib/sessions/browser/sessionOpenTelemetryService.js'; +import { ISessionsProvidersService, SessionsProvidersService } from '../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; +import { ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService } from '../../../../workbench/contrib/sessions/browser/sessionsRecentWorkspacesService.js'; +import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; +import { SessionsManagementService } from '../../../../workbench/contrib/sessions/browser/sessionsManagementService.js'; +import { ISessionChangesStatsCache, SessionChangesStatsCache } from '../../../../workbench/services/sessions/common/sessionChangesStatsCache.js'; + +// The session services are implemented in modules that do not register themselves, so that a window loads them only +// when its entry point imports this module. +registerSingleton(ISessionsProvidersService, SessionsProvidersService, InstantiationType.Delayed); +registerSingleton(IAgentHostCustomizationService, AgentHostCustomizationService, InstantiationType.Delayed); +registerSingleton(IChatHostOpenerService, ChatHostOpenerService, InstantiationType.Delayed); +registerSingleton(ISessionsListModelService, SessionsListModelService, InstantiationType.Delayed); +registerSingleton(ISessionChangesStatsCache, SessionChangesStatsCache, InstantiationType.Delayed); +registerSingleton(ISessionOpenTelemetryService, SessionOpenTelemetryService, InstantiationType.Delayed); +registerSingleton(ISessionsService, SessionsService, InstantiationType.Eager); +registerSingleton(ISessionHostService, SessionHostService, InstantiationType.Delayed); +registerSingleton(IFocusedSessionHostService, FocusedSessionHostService, InstantiationType.Delayed); +registerSingleton(ISessionSectionOrderService, SessionSectionOrderService, InstantiationType.Delayed); +registerSingleton(ISessionGroupsService, SessionGroupsService, InstantiationType.Delayed); +registerSingleton(ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService, InstantiationType.Delayed); +registerSingleton(ISessionComparisonService, SessionComparisonService, InstantiationType.Delayed); +registerSingleton(ISessionsManagementService, SessionsManagementService, InstantiationType.Eager); diff --git a/src/vs/sessions/services/sessions/browser/sessionsServices.registration.ts b/src/vs/sessions/services/sessions/browser/sessionsServices.registration.ts index e95f9ab38724..384b3a7e82bc 100644 --- a/src/vs/sessions/services/sessions/browser/sessionsServices.registration.ts +++ b/src/vs/sessions/services/sessions/browser/sessionsServices.registration.ts @@ -3,47 +3,15 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import './sessionsCoreServices.registration.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; -import { IAgentHostCustomizationService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.js'; -import { AgentHostCustomizationService } from '../../../../workbench/contrib/sessions/browser/agentHostCustomizationService.js'; -import { ISessionsService, SessionsService } from '../../../../workbench/contrib/sessions/browser/sessionsService.js'; -import { ISessionHostService, IFocusedSessionHostService } from '../../../../workbench/services/sessions/browser/sessionHost.js'; -import { SessionHostService, FocusedSessionHostService } from '../../../../workbench/contrib/sessions/browser/sessionHostService.js'; -import { IChatHostOpenerService, ChatHostOpenerService } from '../../../../workbench/services/sessions/browser/chatHostOpener.js'; -import { ISessionsListModelService, SessionsListModelService } from '../../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; -import { ISessionGroupsService, SessionGroupsService } from '../../../../workbench/contrib/sessions/browser/sessionGroupsService.js'; -import { ISessionComparisonService } from '../../../../workbench/contrib/sessions/common/sessionComparison.js'; -import { SessionComparisonService } from '../../../../workbench/contrib/sessions/browser/sessionComparisonService.js'; -import { ISessionSectionOrderService, SessionSectionOrderService } from '../../../../workbench/services/sessions/browser/sessionSectionOrderService.js'; import { IAgentHostFilterService } from '../../../../workbench/contrib/sessions/common/agentHostFilter.js'; import { AgentHostFilterService } from '../../../../workbench/contrib/sessions/browser/agentHostFilterService.js'; import { ISessionRepositoryPicker } from '../../../../workbench/contrib/sessions/browser/sessionRepositoryPicker.js'; import { DefaultSessionRepositoryPicker } from '../../../../workbench/contrib/sessions/browser/defaultSessionRepositoryPicker.js'; import { ISessionsListPresentation } from '../../../../workbench/contrib/sessions/browser/sessionsListPresentation.js'; import { DefaultSessionsListPresentation } from '../../../../workbench/contrib/sessions/browser/defaultSessionsListPresentation.js'; -import { ISessionOpenTelemetryService, SessionOpenTelemetryService } from '../../../../workbench/contrib/sessions/browser/sessionOpenTelemetryService.js'; -import { ISessionsProvidersService, SessionsProvidersService } from '../../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; -import { ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService } from '../../../../workbench/contrib/sessions/browser/sessionsRecentWorkspacesService.js'; -import { ISessionsManagementService } from '../../../../workbench/contrib/sessions/common/sessionsManagement.js'; -import { SessionsManagementService } from '../../../../workbench/contrib/sessions/browser/sessionsManagementService.js'; -import { ISessionChangesStatsCache, SessionChangesStatsCache } from '../../../../workbench/services/sessions/common/sessionChangesStatsCache.js'; -// The session services are implemented in modules that do not register themselves, so that a window loads them only -// when its entry point imports this module. -registerSingleton(ISessionsProvidersService, SessionsProvidersService, InstantiationType.Delayed); -registerSingleton(IAgentHostCustomizationService, AgentHostCustomizationService, InstantiationType.Delayed); -registerSingleton(IChatHostOpenerService, ChatHostOpenerService, InstantiationType.Delayed); -registerSingleton(ISessionsListModelService, SessionsListModelService, InstantiationType.Delayed); -registerSingleton(ISessionChangesStatsCache, SessionChangesStatsCache, InstantiationType.Delayed); -registerSingleton(ISessionOpenTelemetryService, SessionOpenTelemetryService, InstantiationType.Delayed); -registerSingleton(ISessionsService, SessionsService, InstantiationType.Eager); -registerSingleton(ISessionHostService, SessionHostService, InstantiationType.Delayed); -registerSingleton(IFocusedSessionHostService, FocusedSessionHostService, InstantiationType.Delayed); -registerSingleton(ISessionSectionOrderService, SessionSectionOrderService, InstantiationType.Delayed); -registerSingleton(ISessionGroupsService, SessionGroupsService, InstantiationType.Delayed); -registerSingleton(ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService, InstantiationType.Delayed); -registerSingleton(ISessionComparisonService, SessionComparisonService, InstantiationType.Delayed); registerSingleton(IAgentHostFilterService, AgentHostFilterService, InstantiationType.Delayed); registerSingleton(ISessionRepositoryPicker, DefaultSessionRepositoryPicker, InstantiationType.Delayed); registerSingleton(ISessionsListPresentation, DefaultSessionsListPresentation, InstantiationType.Delayed); -registerSingleton(ISessionsManagementService, SessionsManagementService, InstantiationType.Eager); diff --git a/src/vs/sessions/services/sessions/test/browser/sessionNavigation.test.ts b/src/vs/sessions/services/sessions/test/browser/sessionNavigation.test.ts index ce748bd0ab04..0be7f800fc29 100644 --- a/src/vs/sessions/services/sessions/test/browser/sessionNavigation.test.ts +++ b/src/vs/sessions/services/sessions/test/browser/sessionNavigation.test.ts @@ -273,6 +273,7 @@ class MockSessionStore implements ISessionsManagementService { setActive(_session: ISession): void { throw new Error('not implemented'); } cancelCurrentRequest(_session: ISession): Promise { throw new Error('not implemented'); } archiveSession(_session: ISession): Promise { throw new Error('not implemented'); } + prepareSessionWorktreeCleanup(_session: ISession): Promise { throw new Error('not implemented'); } importSession(_session: ISession): Promise { throw new Error('not implemented'); } unarchiveSession(_session: ISession): Promise { throw new Error('not implemented'); } archiveChat(_session: ISession, _chat: IChat): Promise { throw new Error('not implemented'); } diff --git a/src/vs/sessions/services/sessions/test/browser/sessionsManagementService.test.ts b/src/vs/sessions/services/sessions/test/browser/sessionsManagementService.test.ts index c3d8cdbd178f..98cbc8435a83 100644 --- a/src/vs/sessions/services/sessions/test/browser/sessionsManagementService.test.ts +++ b/src/vs/sessions/services/sessions/test/browser/sessionsManagementService.test.ts @@ -5804,6 +5804,69 @@ suite('SessionsManagementService', () => { }); }); + for (const { timing, preserveCustomView } of [ + { timing: 'before', preserveCustomView: false }, + { timing: 'during', preserveCustomView: false }, + { timing: 'during', preserveCustomView: true }, + ] as const) { + test(`restoreVisibleSessions ${preserveCustomView ? 'does not surface the hidden' : 'retains the visible'} workspace draft created ${timing} startup restoration`, async () => { + const folderUri = URI.file('/project'); + const workspace: ISessionWorkspace = { + uri: folderUri, + label: 'project', + icon: Codicon.folder, + folders: [{ root: folderUri, workingDirectory: folderUri, name: 'project', description: undefined }], + requiresWorkspaceTrust: false, + isVirtualWorkspace: false, + }; + const draft = stubSession({ + sessionId: 'workspace-draft', + providerId: 'test', + status: constObservable(SessionStatus.Untitled), + workspace: constObservable(workspace), + }); + const requests: { sessionId: string; chatResource: URI; query: string }[] = []; + const provider = new class extends TestSessionsProvider { + override getSessions(): ISession[] { return []; } + override resolveWorkspace(): ISessionWorkspace { return workspace; } + override async sendRequest(sessionId: string, chatResource: URI, options: ISendRequestOptions): Promise { + requests.push({ sessionId, chatResource, query: options.query }); + return draft; + } + }(draft); + const { service, view } = createSessionsManagementService(draft, disposables, provider); + let restoring: Promise | undefined; + if (timing === 'during') { + restoring = view.restoreVisibleSessions(); + } + await view.openNewSession({ folderUri, preserveNavigation: true, preserveCustomView }); + await (restoring ?? view.restoreVisibleSessions()); + + const active = activeSessionOf(view); + const restored = { + visible: slotSessionsOf(view).map(session => session?.sessionId), + active: active?.sessionId, + workspace: active?.workspace.get(), + pending: service.newSession.get()?.sessionId, + restoreComplete: view.initialRestoreComplete.get(), + }; + if (!preserveCustomView && active) { + await service.sendNewChatRequest(active, { query: 'hello' }); + } + + assert.deepStrictEqual({ restored, requests }, { + restored: { + visible: [preserveCustomView ? undefined : draft.sessionId], + active: preserveCustomView ? undefined : draft.sessionId, + workspace: preserveCustomView ? undefined : workspace, + pending: draft.sessionId, + restoreComplete: true, + }, + requests: preserveCustomView ? [] : [{ sessionId: draft.sessionId, chatResource: draft.mainChat.get().resource, query: 'hello' }], + }); + }); + } + test('restoreVisibleSessions prepares only the active session', async () => { const session = stubSession({ sessionId: 'remote', @@ -6535,6 +6598,46 @@ suite('SessionsManagementService', () => { assert.deepStrictEqual(service.getInFlightNewSessionRequests(), []); }); + for (const background of [false, true]) { + for (const quickChat of [false, true]) { + test(`rejects an unavailable ${quickChat ? 'quick-chat' : 'workspace'} type before consuming a ${background ? 'background' : 'foreground'} draft`, async () => { + const session = stubSession({ + sessionId: 'draft', providerId: 'test', + status: constObservable(SessionStatus.Untitled), + isQuickChat: constObservable(quickChat), + }); + const calls: string[] = []; + const provider = new class extends TestSessionsProvider { + override readonly sessionTypes: ISessionType[] = [{ id: 'test', label: 'Test', icon: Codicon.vm, authRequirement: SessionTypeAuthRequirement.GitHub }]; + override readonly supportsQuickChats = true; + override createQuickChat() { return session; } + override resolveWorkspace(folderUri: URI): ISessionWorkspace { + return { uri: folderUri, label: 'Workspace', icon: Codicon.folder, folders: [], requiresWorkspaceTrust: false, isVirtualWorkspace: false }; + } + override async prepareNewSession(): Promise { + calls.push('prepare'); + throw new Error('unavailable'); + } + override deleteNewSession() { calls.push('delete'); } + override async sendRequest() { calls.push('send'); return session; } + }(session); + const { service } = createSessionsManagementService(session, disposables, provider); + const draft = quickChat ? service.createQuickChat() : service.createNewSession(URI.file('/workspace')); + provider.sessionTypes.splice(0); + const draftChanges: (string | undefined)[] = []; + disposables.add(autorun(reader => draftChanges.push(service.newSession.read(reader)?.sessionId))); + + await assert.rejects(service.sendNewChatRequest(draft, { query: 'keep my prompt', background }), /Test is no longer available for new sessions/); + + assert.deepStrictEqual({ + calls, draftChanges, + draft: service.newSession.get()?.sessionId, + inFlight: service.getInFlightNewSessionRequests(), + }, { calls: [], draftChanges: ['draft'], draft: 'draft', inFlight: [] }); + }); + } + } + test('sendNewChatRequest with background resolves before preparation and routes the replacement in the background', async () => { const chat: IChat = { ...stubChat, resource: URI.parse('test:///chat') }; const session = stubSession({ @@ -9437,6 +9540,62 @@ suite('SessionsManagementService', () => { }); }); + for (const origin of [ChatOriginKind.SideChat, ChatOriginKind.Fork, ChatOriginKind.Tool]) { + for (const toSide of [false, true]) { + test(`a ${origin} chat opened ${toSide ? 'to the side ' : ''}with a reference chat that a chat window shows opens beside it in that window, not in the grid`, async () => { + const sessionB = multiChatSession('B', [chat('mainB'), chat('newB', SessionStatus.Completed, origin)]); + const [mainB, newB] = sessionB.chats.get(); + const { view } = setup([sessionB]); + await view.openSession(sessionB.resource); + const beside: string[] = []; + disposables.add(chatHostOpeners.get(view)!.register({ + showsChat: shown => shown.toString() === mainB.resource.toString(), + reveal: async () => { }, + openBeside: async (opened, reference) => { beside.push(`${opened.path} beside ${reference.path}`); }, + close: async () => ({ restore: async () => { } }), + })); + const gridBefore = { active: activeChatOf(view)?.title.get(), closed: closedTitles(view) }; + + if (toSide) { + await view.openChatToSide(sessionB, newB.resource, { referenceChatResource: mainB.resource }); + } else { + await view.openChat(sessionB, newB.resource, { referenceChatResource: mainB.resource }); + } + + assert.deepStrictEqual({ beside, grid: { active: activeChatOf(view)?.title.get(), closed: closedTitles(view) } }, { + beside: ['/chat/newB beside /chat/mainB'], + grid: gridBefore, + }); + }); + } + } + + test('a chat opened with a reference chat that no opener shows any more opens in the grid, whatever other openers show', async () => { + const sessionB = multiChatSession('B', [chat('mainB'), chat('newB', SessionStatus.Completed, ChatOriginKind.SideChat)]); + const [mainB, newB] = sessionB.chats.get(); + const { view } = setup([sessionB]); + await view.openSession(sessionB.resource); + const beside: string[] = []; + let windowShowsReference = true; + disposables.add(chatHostOpeners.get(view)!.register({ + showsChat: shown => windowShowsReference && shown.toString() === mainB.resource.toString(), + reveal: async () => { }, + openBeside: async opened => { beside.push(`closing window ${opened.path}`); }, + close: async () => ({ restore: async () => { } }), + })); + disposables.add(chatHostOpeners.get(view)!.register({ + showsChat: shown => shown.toString() === 'test:///other', + reveal: async () => { }, + openBeside: async opened => { beside.push(`other window ${opened.path}`); }, + close: async () => ({ restore: async () => { } }), + })); + windowShowsReference = false; + + await view.openChat(sessionB, newB.resource, { referenceChatResource: mainB.resource }); + + assert.deepStrictEqual({ beside, active: activeChatOf(view)?.title.get() }, { beside: [], active: 'newB' }); + }); + test('a session-list open selects the main chat instead of the previously active chat', async () => { const sessionA = multiChatSession('A', [chat('mainA'), chat('sideA', SessionStatus.Completed, ChatOriginKind.SideChat)]); const sessionB = multiChatSession('B', [chat('mainB')]); diff --git a/src/vs/sessions/sessions.common.main.ts b/src/vs/sessions/sessions.common.main.ts index c009042d65d2..98a7e0e9bfc8 100644 --- a/src/vs/sessions/sessions.common.main.ts +++ b/src/vs/sessions/sessions.common.main.ts @@ -147,6 +147,7 @@ import '../workbench/services/chat/common/chatEntitlementService.js'; import '../workbench/services/log/common/defaultLogLevels.js'; import '../workbench/services/agentHost/common/agentHostResourceService.js'; import '../platform/agentHost/browser/agentHostConnectionsService.js'; +import '../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; import '../platform/agentHost/browser/agentHostEnablementService.js'; import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; @@ -333,8 +334,11 @@ import { IExtensionsWorkbenchService } from '../workbench/contrib/extensions/com import { ExtensionsWorkbenchService } from '../workbench/contrib/extensions/browser/extensionsWorkbenchService.js'; import { IExtensionRecommendationNotificationService } from '../platform/extensionRecommendations/common/extensionRecommendations.js'; import { NullExtensionRecommendationNotificationService } from './services/extensionRecommendations/common/extensionRecommendationNotificationService.js'; +import { IExtensionRecommendationsService } from '../workbench/services/extensionRecommendations/common/extensionRecommendations.js'; +import { NullExtensionRecommendationsService } from './services/extensionRecommendations/common/extensionRecommendationsService.js'; registerSingleton(IExtensionsWorkbenchService, ExtensionsWorkbenchService, InstantiationType.Eager /* Auto updates extensions */); registerSingleton(IExtensionRecommendationNotificationService, NullExtensionRecommendationNotificationService, InstantiationType.Delayed); +registerSingleton(IExtensionRecommendationsService, NullExtensionRecommendationsService, InstantiationType.Delayed); // Output View import '../workbench/contrib/output/browser/output.contribution.js'; @@ -479,6 +483,7 @@ import './browser/layoutActions.js'; import './contrib/accountMenu/browser/account.contribution.js'; import './contrib/aiCustomizationTreeView/browser/aiCustomizationTreeView.contribution.js'; +import './contrib/chat/browser/chat.desktop.contribution.js'; import './contrib/chat/browser/chat.contribution.js'; import './contrib/chat/browser/sharedChatInputComposer.contribution.js'; import './contrib/chat/browser/requestOriginProvider.contribution.js'; diff --git a/src/vs/sessions/sessions.core.main.ts b/src/vs/sessions/sessions.core.main.ts new file mode 100644 index 000000000000..86d514c3a612 --- /dev/null +++ b/src/vs/sessions/sessions.core.main.ts @@ -0,0 +1,221 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + + +// Mobile's service allow-list; full entries preserve their own registration order. + +//#region --- editor/workbench core + +import '../editor/editor.all.js'; +import { getColorRegistry } from '../platform/theme/common/colorUtils.js'; +import { PANEL_BACKGROUND } from '../workbench/common/theme.js'; +import { TERMINAL_BACKGROUND_COLOR } from '../workbench/contrib/terminal/common/terminalColorRegistry.js'; + +import '../workbench/api/browser/extensionHost.contribution.js'; +import '../workbench/browser/workbench.contribution.js'; +import '../workbench/contrib/modernUI/browser/media/notificationsDialogs.css'; +import { agentsPanelBackground } from '../workbench/contrib/sessions/common/theme.js'; +import './common/sizes.js'; +import './contrib/providers/remoteAgentHost/browser/connectionDiagnostics.contribution.js'; + +getColorRegistry().updateDefaultColor(PANEL_BACKGROUND, agentsPanelBackground); +getColorRegistry().updateDefaultColor(TERMINAL_BACKGROUND_COLOR, agentsPanelBackground); + +//#endregion + + +//#region --- API Extension Points + +import '../workbench/services/actions/common/menusExtensionPoint.js'; +import '../workbench/api/common/configurationExtensionPoint.js'; +import '../workbench/api/browser/viewsExtensionPoint.js'; + +//#endregion + + +//#region --- workbench parts + +import '../workbench/browser/parts/editor/editor.contribution.js'; +// import '../workbench/browser/parts/editor/editorParts.js'; +// import '../workbench/browser/parts/paneCompositePartService.js'; +import '../workbench/browser/parts/banner/bannerPart.js'; +import '../workbench/browser/parts/statusbar/statusbarPart.js'; + +//#endregion + + +//#region --- workbench services + +import '../platform/actions/common/actions.contribution.js'; +import '../platform/undoRedo/common/undoRedoService.js'; +import '../platform/mcp/common/mcpResourceScannerService.js'; +import '../workbench/services/workspaces/common/editSessionIdentityService.js'; +import '../workbench/services/workspaces/common/canonicalUriService.js'; +import '../workbench/services/extensions/browser/extensionUrlHandler.js'; +import '../workbench/services/keybinding/common/keybindingEditing.js'; +import '../workbench/services/decorations/browser/decorationsService.js'; +import '../workbench/services/dialogs/common/dialogService.js'; +import '../workbench/services/progress/browser/progressService.js'; +import '../workbench/services/editor/browser/codeEditorService.js'; +import '../workbench/services/preferences/browser/preferencesService.js'; +import '../workbench/services/configuration/common/jsonEditingService.js'; +import '../workbench/services/textmodelResolver/common/textModelResolverService.js'; +import '../workbench/services/editor/browser/editorService.js'; +import '../workbench/services/editor/browser/editorResolverService.js'; +import '../workbench/services/aiEmbeddingVector/common/aiEmbeddingVectorService.js'; +import '../workbench/services/aiRelatedInformation/common/aiRelatedInformationService.js'; +import '../workbench/services/aiSettingsSearch/common/aiSettingsSearchService.js'; +import '../workbench/services/history/browser/historyService.js'; +import '../workbench/services/activity/browser/activityService.js'; +import '../workbench/services/keybinding/browser/keybindingService.js'; +import '../workbench/services/untitled/common/untitledTextEditorService.js'; +import '../workbench/services/textresourceProperties/common/textResourcePropertiesService.js'; +import '../workbench/services/textfile/common/textEditorService.js'; +import '../workbench/services/language/common/languageService.js'; +import '../workbench/services/model/common/modelService.js'; +import '../workbench/services/notebook/common/notebookDocumentService.js'; +import '../workbench/services/commands/common/commandService.js'; +import '../workbench/services/themes/browser/workbenchThemeService.js'; +import '../workbench/services/label/common/labelService.js'; +import '../workbench/services/extensions/common/extensionManifestPropertiesService.js'; +import '../workbench/services/extensionManagement/common/extensionGalleryService.js'; +import '../workbench/services/extensionManagement/browser/extensionEnablementService.js'; +import '../workbench/services/extensionManagement/browser/builtinExtensionsScannerService.js'; +import '../workbench/services/extensionRecommendations/common/extensionIgnoredRecommendationsService.js'; +import '../workbench/services/extensionRecommendations/common/workspaceExtensionsConfig.js'; +import '../workbench/services/extensionManagement/common/extensionFeaturesManagemetService.js'; +import '../workbench/services/notification/common/notificationService.js'; +import '../workbench/services/userDataSync/common/userDataSyncUtil.js'; +import '../workbench/services/userDataProfile/browser/userDataProfileImportExportService.js'; +import '../workbench/services/userDataProfile/browser/userDataProfileManagement.js'; +import '../workbench/services/userDataProfile/common/remoteUserDataProfiles.js'; +import '../workbench/services/remote/common/remoteExplorerService.js'; +import '../workbench/services/remote/common/remoteExtensionsScanner.js'; +import '../workbench/services/terminal/common/embedderTerminalService.js'; +import '../workbench/services/workingCopy/common/workingCopyService.js'; +import '../workbench/services/workingCopy/common/workingCopyFileService.js'; +import '../workbench/services/workingCopy/common/workingCopyEditorService.js'; +import '../workbench/services/filesConfiguration/common/filesConfigurationService.js'; +import '../workbench/services/views/browser/viewDescriptorService.js'; +import '../workbench/services/views/browser/viewsService.js'; +import '../workbench/services/quickinput/browser/quickInputService.js'; +import '../workbench/services/userDataSync/browser/userDataSyncWorkbenchService.js'; +import '../workbench/services/authentication/browser/authenticationService.js'; +import '../workbench/services/authentication/browser/authenticationExtensionsService.js'; +import '../workbench/services/authentication/browser/authenticationUsageService.js'; +import '../workbench/services/authentication/browser/authenticationAccessService.js'; +import '../workbench/services/authentication/browser/authenticationMcpUsageService.js'; +import '../workbench/services/authentication/browser/authenticationMcpAccessService.js'; +import '../workbench/services/authentication/browser/authenticationMcpService.js'; +import '../workbench/services/authentication/browser/dynamicAuthenticationProviderStorageService.js'; +import '../workbench/services/authentication/browser/authenticationQueryService.js'; +import '../workbench/services/github/browser/githubService.js'; +import '../platform/hover/browser/hoverService.js'; +import '../platform/userInteraction/browser/userInteractionServiceImpl.js'; +import '../workbench/services/assignment/common/assignmentService.js'; +import '../workbench/services/languageDetection/browser/languageDetectionWorkerServiceImpl.js'; +import '../editor/common/services/languageFeaturesService.js'; +import '../editor/common/services/semanticTokensStylingService.js'; +import '../editor/common/services/treeViewsDndService.js'; +import '../workbench/services/textMate/browser/textMateTokenizationFeature.contribution.js'; +import '../workbench/services/treeSitter/browser/treeSitter.contribution.js'; +import '../workbench/services/userActivity/common/userActivityService.js'; +import '../workbench/services/userActivity/browser/userActivityBrowser.js'; +import '../workbench/services/userAttention/browser/userAttentionBrowser.js'; +import '../workbench/services/editor/browser/editorPaneService.js'; +import '../workbench/services/editor/common/customEditorLabelService.js'; +import '../workbench/services/dataChannel/browser/dataChannelService.js'; +import '../workbench/services/inlineCompletions/common/inlineCompletionsUnification.js'; +import '../workbench/services/chat/common/chatEntitlementService.js'; +import '../workbench/services/log/common/defaultLogLevels.js'; +import '../workbench/services/agentHost/common/agentHostResourceService.js'; +import '../platform/agentHost/browser/agentHostConnectionsService.js'; +import '../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; +import '../platform/agentHost/browser/agentHostEnablementService.js'; + +import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; +import { GlobalExtensionEnablementService } from '../platform/extensionManagement/common/extensionEnablementService.js'; +import { IAllowedExtensionsService, IGlobalExtensionEnablementService } from '../platform/extensionManagement/common/extensionManagement.js'; +import { ContextViewService } from '../platform/contextview/browser/contextViewService.js'; +import { IContextViewService } from '../platform/contextview/browser/contextView.js'; +import { ArtifactIntegrationRegistry, IArtifactIntegrationRegistry } from '../platform/artifactIntegrations/common/artifactIntegrationRegistry.js'; +import { IListService, ListService } from '../platform/list/browser/listService.js'; +import { MarkerDecorationsService } from '../editor/common/services/markerDecorationsService.js'; +import { IMarkerDecorationsService } from '../editor/common/services/markerDecorations.js'; +import { IMarkerService } from '../platform/markers/common/markers.js'; +import { MarkerService } from '../platform/markers/common/markerService.js'; +import { ContextKeyService } from '../platform/contextkey/browser/contextKeyService.js'; +import { IContextKeyService } from '../platform/contextkey/common/contextkey.js'; +import { ITextResourceConfigurationService } from '../editor/common/services/textResourceConfiguration.js'; +import { TextResourceConfigurationService } from '../editor/common/services/textResourceConfigurationService.js'; +import { IDownloadService } from '../platform/download/common/download.js'; +import { DownloadService } from '../platform/download/common/downloadService.js'; +import { OpenerService } from '../editor/browser/services/openerService.js'; +import { IOpenerService } from '../platform/opener/common/opener.js'; +import { IgnoredExtensionsManagementService, IIgnoredExtensionsManagementService } from '../platform/userDataSync/common/ignoredExtensions.js'; +import { ExtensionStorageService, IExtensionStorageService } from '../platform/extensionManagement/common/extensionStorage.js'; +import { IUserDataSyncLogService } from '../platform/userDataSync/common/userDataSync.js'; +import { UserDataSyncLogService } from '../platform/userDataSync/common/userDataSyncLog.js'; +import { AllowedExtensionsService } from '../platform/extensionManagement/common/allowedExtensionsService.js'; +import { IAllowedMcpServersService, IMcpGalleryService } from '../platform/mcp/common/mcpManagement.js'; +import { McpGalleryService } from '../platform/mcp/common/mcpGalleryService.js'; +import { AllowedMcpServersService } from '../platform/mcp/common/allowedMcpServersService.js'; +import { IWebWorkerService } from '../platform/webWorker/browser/webWorkerService.js'; +import { WebWorkerService } from '../platform/webWorker/browser/webWorkerServiceImpl.js'; +import { ISessionsSetUpService, SessionsSetUpService } from './browser/sessionsSetUpService.js'; +import { AgentHostMcpOAuthMetadataService, IAgentHostMcpOAuthMetadataService } from '../platform/agentHost/common/agentHostMcpOAuthMetadataService.js'; + +registerSingleton(IArtifactIntegrationRegistry, ArtifactIntegrationRegistry, InstantiationType.Delayed); +registerSingleton(IUserDataSyncLogService, UserDataSyncLogService, InstantiationType.Delayed); +registerSingleton(IAllowedExtensionsService, AllowedExtensionsService, InstantiationType.Delayed); +registerSingleton(IIgnoredExtensionsManagementService, IgnoredExtensionsManagementService, InstantiationType.Delayed); +registerSingleton(IGlobalExtensionEnablementService, GlobalExtensionEnablementService, InstantiationType.Delayed); +registerSingleton(IExtensionStorageService, ExtensionStorageService, InstantiationType.Delayed); +registerSingleton(IContextViewService, ContextViewService, InstantiationType.Delayed); +registerSingleton(IListService, ListService, InstantiationType.Delayed); +registerSingleton(IMarkerDecorationsService, MarkerDecorationsService, InstantiationType.Delayed); +registerSingleton(IMarkerService, MarkerService, InstantiationType.Delayed); +registerSingleton(IContextKeyService, ContextKeyService, InstantiationType.Delayed); +registerSingleton(ITextResourceConfigurationService, TextResourceConfigurationService, InstantiationType.Delayed); +registerSingleton(IDownloadService, DownloadService, InstantiationType.Delayed); +registerSingleton(IOpenerService, OpenerService, InstantiationType.Delayed); +registerSingleton(IWebWorkerService, WebWorkerService, InstantiationType.Delayed); +registerSingleton(IMcpGalleryService, McpGalleryService, InstantiationType.Delayed); +registerSingleton(IAllowedMcpServersService, AllowedMcpServersService, InstantiationType.Delayed); +registerSingleton(ISessionsSetUpService, SessionsSetUpService, InstantiationType.Delayed); +registerSingleton(IAgentHostMcpOAuthMetadataService, AgentHostMcpOAuthMetadataService, InstantiationType.Delayed); + +//#endregion + + +//#region --- shared services registered by contribution areas + +// Testing (service) +import { NullTestProfileService, NullTestResultService, NullTestService } from '../workbench/contrib/testing/common/nullTestingService.js'; +import { ITestProfileService } from '../workbench/contrib/testing/common/testProfileService.js'; +import { ITestResultService } from '../workbench/contrib/testing/common/testResultService.js'; +import { ITestService } from '../workbench/contrib/testing/common/testService.js'; +registerSingleton(ITestService, NullTestService, InstantiationType.Delayed); +registerSingleton(ITestProfileService, NullTestProfileService, InstantiationType.Delayed); +registerSingleton(ITestResultService, NullTestResultService, InstantiationType.Delayed); + + +// Debug (service) +import { NullDebugService, NullDebugVisualizerService } from '../workbench/contrib/debug/common/nullDebugService.js'; +import { IDebugService } from '../workbench/contrib/debug/common/debug.js'; +import { IDebugVisualizerService } from '../workbench/contrib/debug/common/debugVisualizers.js'; +registerSingleton(IDebugService, NullDebugService, InstantiationType.Delayed); +registerSingleton(IDebugVisualizerService, NullDebugVisualizerService, InstantiationType.Delayed); + + +// Extensions Management +import { IExtensionsWorkbenchService } from '../workbench/contrib/extensions/common/extensions.js'; +import { ExtensionsWorkbenchService } from '../workbench/contrib/extensions/browser/extensionsWorkbenchService.js'; +import { IExtensionRecommendationNotificationService } from '../platform/extensionRecommendations/common/extensionRecommendations.js'; +import { NullExtensionRecommendationNotificationService } from './services/extensionRecommendations/common/extensionRecommendationNotificationService.js'; +registerSingleton(IExtensionsWorkbenchService, ExtensionsWorkbenchService, InstantiationType.Eager /* Auto updates extensions */); +registerSingleton(IExtensionRecommendationNotificationService, NullExtensionRecommendationNotificationService, InstantiationType.Delayed); + +//#endregion diff --git a/src/vs/sessions/sessions.core.web.main.ts b/src/vs/sessions/sessions.core.web.main.ts new file mode 100644 index 000000000000..30062b4d5e58 --- /dev/null +++ b/src/vs/sessions/sessions.core.web.main.ts @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + + +// Mobile's browser service bindings; full web retains its own registration order. + +import './sessions.core.main.js'; + + +//#region --- workbench services (browser equivalents of the electron services) + +import '../workbench/services/integrity/browser/integrityService.js'; +import '../workbench/services/search/browser/searchService.js'; +import '../workbench/services/textfile/browser/browserTextFileService.js'; +import '../workbench/services/keybinding/browser/keyboardLayoutService.js'; +import '../workbench/services/extensions/browser/extensionService.js'; +import '../workbench/services/extensionManagement/browser/extensionsProfileScannerService.js'; +import '../workbench/services/extensions/browser/extensionsScannerService.js'; +import '../workbench/services/extensionManagement/browser/webExtensionsScannerService.js'; +import '../workbench/services/extensionManagement/common/extensionManagementServerService.js'; +import '../workbench/services/mcp/browser/mcpWorkbenchManagementService.js'; +import '../workbench/services/extensionManagement/browser/extensionGalleryManifestService.js'; +import '../workbench/services/telemetry/browser/telemetryService.js'; +import '../workbench/services/url/browser/urlService.js'; +import '../workbench/services/update/browser/updateService.js'; +import '../workbench/services/workspaces/browser/workspacesService.js'; +import '../workbench/services/workspaces/browser/workspaceEditingService.js'; +import '../workbench/services/dialogs/browser/fileDialogService.js'; +import '../workbench/services/host/browser/browserHostService.js'; +import '../platform/meteredConnection/browser/meteredConnectionService.js'; +import '../workbench/services/lifecycle/browser/lifecycleService.js'; +import '../workbench/services/clipboard/browser/clipboardService.js'; +import '../workbench/services/localization/browser/localeService.js'; +import '../workbench/services/path/browser/pathService.js'; +import '../workbench/services/themes/browser/browserHostColorSchemeService.js'; +import '../workbench/services/encryption/browser/encryptionService.js'; +import '../workbench/services/imageResize/browser/imageResizeService.js'; +import '../workbench/services/secrets/browser/secretStorageService.js'; +import '../workbench/services/workingCopy/browser/workingCopyBackupService.js'; +import '../workbench/services/tunnel/browser/tunnelService.js'; +import '../workbench/services/files/browser/elevatedFileService.js'; +import '../workbench/services/workingCopy/browser/workingCopyHistoryService.js'; +import '../workbench/services/userDataSync/browser/webUserDataSyncEnablementService.js'; +import '../workbench/services/userDataProfile/browser/userDataProfileStorageService.js'; +import '../workbench/services/configurationResolver/browser/configurationResolverService.js'; +import '../platform/extensionResourceLoader/browser/extensionResourceLoaderService.js'; +import '../workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.js'; +import '../workbench/services/power/browser/powerService.js'; +import '../workbench/services/localTranscription/browser/localTranscriptionService.js'; +import '../platform/sandbox/browser/sandboxHelperService.js'; +import '../platform/remoteTunnel/browser/remoteTunnelService.js'; + +import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; +import { IAccessibilityService } from '../platform/accessibility/common/accessibility.js'; +import { IContextMenuService } from '../platform/contextview/browser/contextView.js'; +import { ContextMenuService } from '../platform/contextview/browser/contextMenuService.js'; +import { IExtensionTipsService } from '../platform/extensionManagement/common/extensionManagement.js'; +import { ExtensionTipsService } from '../platform/extensionManagement/common/extensionTipsService.js'; +import { IWorkbenchExtensionManagementService } from '../workbench/services/extensionManagement/common/extensionManagement.js'; +import { ExtensionManagementService } from '../workbench/services/extensionManagement/common/extensionManagementService.js'; +import { UserDataSyncMachinesService, IUserDataSyncMachinesService } from '../platform/userDataSync/common/userDataSyncMachines.js'; +import { IUserDataSyncStoreService, IUserDataSyncService, IUserDataAutoSyncService, IUserDataSyncLocalStoreService, IUserDataSyncResourceProviderService } from '../platform/userDataSync/common/userDataSync.js'; +import { UserDataSyncStoreService } from '../platform/userDataSync/common/userDataSyncStoreService.js'; +import { UserDataSyncLocalStoreService } from '../platform/userDataSync/common/userDataSyncLocalStoreService.js'; +import { UserDataSyncService } from '../platform/userDataSync/common/userDataSyncService.js'; +import { IUserDataSyncAccountService, UserDataSyncAccountService } from '../platform/userDataSync/common/userDataSyncAccount.js'; +import { UserDataAutoSyncService } from '../platform/userDataSync/common/userDataAutoSyncService.js'; +import { AccessibilityService } from '../platform/accessibility/browser/accessibilityService.js'; +import { ICustomEndpointTelemetryService } from '../platform/telemetry/common/telemetry.js'; +import { NullEndpointTelemetryService } from '../platform/telemetry/common/telemetryUtils.js'; +import './services/title/browser/titleService.js'; +import { ITimerService, TimerService } from '../workbench/services/timer/browser/timerService.js'; +import { IDiagnosticsService, NullDiagnosticsService } from '../platform/diagnostics/common/diagnostics.js'; +import { ILanguagePackService } from '../platform/languagePacks/common/languagePacks.js'; +import { WebLanguagePacksService } from '../platform/languagePacks/browser/languagePacks.js'; +import { IWebContentExtractorService, NullWebContentExtractorService, ISharedWebContentExtractorService, NullSharedWebContentExtractorService } from '../platform/webContentExtractor/common/webContentExtractor.js'; +import { IMcpGalleryManifestService } from '../platform/mcp/common/mcpGalleryManifest.js'; +import { WorkbenchMcpGalleryManifestService } from '../workbench/services/mcp/browser/mcpGalleryManifestService.js'; +import { UserDataSyncResourceProviderService } from '../platform/userDataSync/common/userDataSyncResourceProvider.js'; +import { IRemoteAgentHostService } from '../platform/agentHost/common/remoteAgentHostService.js'; +import { AgentsWindowRemoteAgentHostService } from '../platform/agentHost/browser/remoteAgentHostServiceImpl.js'; +import { ISSHRemoteAgentHostService } from '../platform/agentHost/common/sshRemoteAgentHost.js'; +import { NullSSHRemoteAgentHostService } from '../platform/agentHost/browser/nullSshRemoteAgentHostService.js'; +import { IWSLRemoteAgentHostService } from '../platform/agentHost/common/wslRemoteAgentHost.js'; +import { NullWSLRemoteAgentHostService } from '../platform/agentHost/browser/nullWslRemoteAgentHostService.js'; +import { IAgentHostService } from '../platform/agentHost/common/agentService.js'; +import { EditorRemoteAgentHostServiceClient } from '../workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.js'; +import '../workbench/services/agentHost/browser/webAgentHostEnablementService.js'; +import { BrowserAgentHostDebugLogsExportService, IAgentHostDebugLogsExportService } from '../workbench/contrib/chat/browser/actions/exportAgentHostDebugLogsAction.js'; + +registerSingleton(IWorkbenchExtensionManagementService, ExtensionManagementService, InstantiationType.Delayed); +registerSingleton(IAccessibilityService, AccessibilityService, InstantiationType.Delayed); +registerSingleton(IContextMenuService, ContextMenuService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncStoreService, UserDataSyncStoreService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncMachinesService, UserDataSyncMachinesService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncLocalStoreService, UserDataSyncLocalStoreService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncAccountService, UserDataSyncAccountService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncService, UserDataSyncService, InstantiationType.Delayed); +registerSingleton(IUserDataSyncResourceProviderService, UserDataSyncResourceProviderService, InstantiationType.Delayed); +registerSingleton(IUserDataAutoSyncService, UserDataAutoSyncService, InstantiationType.Eager); +registerSingleton(IExtensionTipsService, ExtensionTipsService, InstantiationType.Delayed); +registerSingleton(ITimerService, TimerService, InstantiationType.Delayed); +registerSingleton(ICustomEndpointTelemetryService, NullEndpointTelemetryService, InstantiationType.Delayed); +registerSingleton(IDiagnosticsService, NullDiagnosticsService, InstantiationType.Delayed); +registerSingleton(ILanguagePackService, WebLanguagePacksService, InstantiationType.Delayed); +registerSingleton(IWebContentExtractorService, NullWebContentExtractorService, InstantiationType.Delayed); +registerSingleton(ISharedWebContentExtractorService, NullSharedWebContentExtractorService, InstantiationType.Delayed); +registerSingleton(IMcpGalleryManifestService, WorkbenchMcpGalleryManifestService, InstantiationType.Delayed); +registerSingleton(IRemoteAgentHostService, AgentsWindowRemoteAgentHostService, InstantiationType.Delayed); +registerSingleton(ISSHRemoteAgentHostService, NullSSHRemoteAgentHostService, InstantiationType.Delayed); +registerSingleton(IWSLRemoteAgentHostService, NullWSLRemoteAgentHostService, InstantiationType.Delayed); +registerSingleton(IAgentHostService, EditorRemoteAgentHostServiceClient, InstantiationType.Delayed); +registerSingleton(IAgentHostDebugLogsExportService, BrowserAgentHostDebugLogsExportService, InstantiationType.Delayed); + +//#endregion diff --git a/src/vs/sessions/sessions.desktop.main.ts b/src/vs/sessions/sessions.desktop.main.ts index ed1532ca33c0..682584b9c8a3 100644 --- a/src/vs/sessions/sessions.desktop.main.ts +++ b/src/vs/sessions/sessions.desktop.main.ts @@ -113,8 +113,6 @@ import { ILocalGitService } from '../platform/git/common/localGitService.js'; import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; import { IRemoteAgentHostService } from '../platform/agentHost/common/remoteAgentHostService.js'; import { AgentsWindowRemoteAgentHostService } from '../platform/agentHost/browser/remoteAgentHostServiceImpl.js'; -import { IRemoteAgentHostLocationPreferenceService } from '../platform/agentHost/common/remoteAgentHostLocationPreference.js'; -import { RemoteAgentHostLocationPreferenceService } from '../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; import { ISSHHostKeyTrustService } from '../platform/agentHost/common/sshHostKeyTrust.js'; import { SSHHostKeyTrustService } from '../platform/agentHost/browser/sshHostKeyTrustService.js'; import { registerSharedProcessRemoteService } from '../platform/ipc/electron-browser/services.js'; @@ -129,7 +127,6 @@ registerSingleton(IUserDataInitializationService, new SyncDescriptor(UserDataIni // runs git locally via the shared process. registerSingleton(IPluginGitService, NativePluginGitCommandService, InstantiationType.Delayed); registerSingleton(IRemoteAgentHostService, AgentsWindowRemoteAgentHostService, InstantiationType.Delayed); -registerSingleton(IRemoteAgentHostLocationPreferenceService, RemoteAgentHostLocationPreferenceService, InstantiationType.Delayed); registerSingleton(ISSHHostKeyTrustService, SSHHostKeyTrustService, InstantiationType.Delayed); registerSharedProcessRemoteService(ILocalGitService, 'localGit'); diff --git a/src/vs/sessions/sessions.web.main.ts b/src/vs/sessions/sessions.web.main.ts index 6c84c7059455..3fb568315b89 100644 --- a/src/vs/sessions/sessions.web.main.ts +++ b/src/vs/sessions/sessions.web.main.ts @@ -109,8 +109,6 @@ import { WorkbenchMcpGalleryManifestService } from '../workbench/services/mcp/br import { UserDataSyncResourceProviderService } from '../platform/userDataSync/common/userDataSyncResourceProvider.js'; import { IRemoteAgentHostService } from '../platform/agentHost/common/remoteAgentHostService.js'; import { AgentsWindowRemoteAgentHostService } from '../platform/agentHost/browser/remoteAgentHostServiceImpl.js'; -import { IRemoteAgentHostLocationPreferenceService } from '../platform/agentHost/common/remoteAgentHostLocationPreference.js'; -import { RemoteAgentHostLocationPreferenceService } from '../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; import { ISSHRemoteAgentHostService } from '../platform/agentHost/common/sshRemoteAgentHost.js'; import { NullSSHRemoteAgentHostService } from '../platform/agentHost/browser/nullSshRemoteAgentHostService.js'; import { IWSLRemoteAgentHostService } from '../platform/agentHost/common/wslRemoteAgentHost.js'; @@ -139,7 +137,6 @@ registerSingleton(IWebContentExtractorService, NullWebContentExtractorService, I registerSingleton(ISharedWebContentExtractorService, NullSharedWebContentExtractorService, InstantiationType.Delayed); registerSingleton(IMcpGalleryManifestService, WorkbenchMcpGalleryManifestService, InstantiationType.Delayed); registerSingleton(IRemoteAgentHostService, AgentsWindowRemoteAgentHostService, InstantiationType.Delayed); -registerSingleton(IRemoteAgentHostLocationPreferenceService, RemoteAgentHostLocationPreferenceService, InstantiationType.Delayed); registerSingleton(ISSHRemoteAgentHostService, NullSSHRemoteAgentHostService, InstantiationType.Delayed); registerSingleton(IWSLRemoteAgentHostService, NullWSLRemoteAgentHostService, InstantiationType.Delayed); registerSingleton(IAgentHostService, EditorRemoteAgentHostServiceClient, InstantiationType.Delayed); diff --git a/src/vs/sessions/skills/automate/SKILL.md b/src/vs/sessions/skills/automate/SKILL.md index 08a8775c3340..7afdfc8657f9 100644 --- a/src/vs/sessions/skills/automate/SKILL.md +++ b/src/vs/sessions/skills/automate/SKILL.md @@ -1,6 +1,7 @@ --- name: automate description: 'Propose an automation from a completed task or a new idea, then create it after approval. Use when the user asks to create an automation or wants scheduled local or cloud agent work.' +argument-hint: Describe a task, schedule, and where it should run --- diff --git a/src/vs/sessions/skills/html-preview/SKILL.md b/src/vs/sessions/skills/html-preview/SKILL.md new file mode 100644 index 000000000000..2d595a2816ff --- /dev/null +++ b/src/vs/sessions/skills/html-preview/SKILL.md @@ -0,0 +1,59 @@ +--- +name: html-preview +description: Create visual reports, implementation plans, code-review explainers, comparisons, diagrams, and static UI mockups as inline HTML previews in the Agents window. Use when the user asks for visual or rendered output, not ordinary HTML code examples. +--- + + +# HTML previews + +Use HTML when layout helps the user understand or review the result. Keep short explanations and ordinary code examples in Markdown. Honor the user's requested format; do not turn every answer into HTML. + +This is on-demand authoring guidance bundled with the Agents window, available across workspaces when HTML previews and AI features are enabled. Rendering does not depend on invoking this skill. + +## Produce a preview + +Return the document in a closed Markdown code fence with the language `html-preview`. Ordinary `html` fences remain source code. The preview appears after its closing fence arrives. + +The `chat.htmlPreview.enabled` setting controls inline rendering in the Agents window and is off by default. While it is off, these fences display as source code. Do not change the user's setting unless asked. + +- Use self-contained HTML and CSS, tables, simple inline SVG, and native `details`/`summary` disclosures. +- Use headings, text labels, meaningful image descriptions, and readable contrast. Do not rely on color alone to convey findings or status. +- For long reports, provide a table of contents with links such as `Risks` and matching element IDs. Only links within the same document work. Put external citations and workspace source links in Markdown outside the preview. +- Prefer fluid layouts and wrapping text. Keep wide tables and code samples scrollable rather than clipping them. +- Inline previews expand to fit their content and scroll with the transcript. Prefer content-based heights over viewport-height layouts. +- Inline previews have no surrounding title bar, border, or permanent buttons. Leave `html` and `body` backgrounds, typography, and outer padding unset so the renderer can match the surrounding chat. Use explicit backgrounds only for meaningful inner surfaces. +- Use semantic VS Code theme variables instead of hardcoded light/dark colors. Prefer inherited text color, `var(--vscode-descriptionForeground, GrayText)` for secondary text, `var(--vscode-editorWidget-background, Canvas)` for an inner panel, `var(--vscode-widget-border, currentColor)` for its border, and `var(--vscode-textLink-foreground, LinkText)` for links. +- For charts, use the `--vscode-charts-blue`, `--vscode-charts-green`, and other chart palette variables with `currentColor` fallbacks. Include labels or patterns and a data table or text explanation; color alone is not sufficient. +- Use VS Code spacing, radius, and type-role variables where applicable, with standalone fallbacks. Keep chrome quiet, make the main finding lead, and avoid giving every section a competing card or accent color. +- Scripts, JavaScript event handlers, forms, inputs, buttons, embedded frames, canvas applications, external links, remote images, stylesheets, fonts, and network requests are not supported. Do not promise sliders, draggable boards, live charts, or working export buttons. +- For interaction, use native disclosures and section links instead of script-dependent tabs or controls. If the user needs a running application, explain that it requires a separate application workflow. +- Embedded PNG, JPEG, GIF, and WebP data images are supported; prefer simple inline SVG for diagrams so output stays compact. +- Keep each preview below 64,000 characters and the overall response concise. Split a large explanation into focused sections or previews instead of embedding large assets. + +Example: + +````markdown +Here are the options: + +```html-preview + +

Choose an approach

+ +
+

Small change

Reuse the existing renderer.

+

Separate runtime

Supports a full interactive application.

+
+
Risks and trade-offs

The smaller change does not execute scripts.

+``` +```` + +## Read, save, and iterate + +When rendering is enabled, right-click the preview or focus it and press Shift+F10 for **Show Source**, **Open Preview**, and **Save HTML**. Open Preview opens a larger reading surface. Save HTML exports a sanitized, self-contained HTML file with the current theme and opens it through the normal file-preview behavior. Expanded and exported documents retain their own background and padding. It does not save hidden JavaScript or unsupported controls from the original source. + +Do not claim a file was created merely because a preview rendered. The user can choose Save HTML, or explicitly ask you to create an HTML artifact using the available file tools. Only create a file when the requested deliverable calls for one; keep it self-contained and script-free, and use the existing artifact-registration tool when available. + +For revisions, use the existing response or the saved file supplied by the user as context. Preserve its structure, factual content, section IDs, and intended format while making the requested changes. Keep any raw-source export distinct from a sanitized preview export; never suggest that preview restrictions automatically apply to arbitrary HTML opened elsewhere. diff --git a/src/vs/sessions/skills/vscode-ui/SKILL.md b/src/vs/sessions/skills/vscode-ui/SKILL.md new file mode 100644 index 000000000000..265f464624be --- /dev/null +++ b/src/vs/sessions/skills/vscode-ui/SKILL.md @@ -0,0 +1,73 @@ +--- +name: vscode-ui +description: Present metrics, comparisons, tables, bar charts, and expandable details as native visuals inside an Agents window response. Use when numbers or a comparison are clearer shown than described. Not for diagrams, mockups, or standalone documents. +--- + + +# Native visuals + +Use a native visual when showing data helps the user more than describing it: a few key numbers, a before-and-after comparison, a small table, or a bar chart. VS Code renders the visual itself, so it matches the user's theme and reads as part of the answer. Keep the explanation in ordinary Markdown around it, and honor the format the user asked for; most answers need no visual. + +This is on-demand authoring guidance bundled with the Agents window. It is available while native visuals and AI features are enabled. Rendering does not depend on invoking this skill. + +## Write a visual + +Put the components in a closed Markdown code fence with the language `vscode-ui`. The visual appears once the closing fence arrives. Start the fence at the beginning of a line, not inside a list item or a block quote. + +````markdown +The incremental build is considerably faster. + +```vscode-ui + + + + + + + + + + Median of five runs on a warm cache. + +``` + +Most of the improvement comes from caching. +```` + +The `chat.nativeComponents.enabled` setting controls rendering in the Agents window and is off by default. While it is off, the block is shown as source code. Do not change the user's setting unless asked. + +## Components + +You supply content, data, and composition. VS Code owns how every component looks, so there is nothing to style. + +| Component | Attributes | Content | +| --- | --- | --- | +| `Stack` | none | Components, laid out top to bottom. | +| `Columns` | none | Components, laid out side by side in equal columns that stack when the chat is narrow. | +| `Text` | `variant`: `body` (default), `heading`, or `caption` | Plain text. | +| `Metric` | `label` and `value` (required), `delta`, `tone` | None. | +| `Badge` | `tone` | Plain text. Adjacent badges share a line. | +| `Table` | `caption` | Every `Column`, then every `Row`. | +| `Column` | `align`: `start` (default) or `end` | The column's header text. Use `end` for numbers. | +| `Row` | none | One `Cell` per column. | +| `Cell` | none | Plain text. | +| `BarChart` | `title` (required), `unit` | One `Bar` per value. | +| `Bar` | `label` and `value` (required) | None. | +| `Disclosure` | `summary` (required) | Components, hidden until the user expands them. | + +A `tone` is `neutral` (default), `positive`, `negative`, or `warning`. It states what a value means; VS Code chooses the icon and color. Use a tone only where the meaning matters, not for decoration. + +## Rules + +The block is checked strictly. If anything in it is not valid, the user sees the source and the reason instead of the visual. + +- Use only the components and attributes above. Names are case-sensitive. +- Write every attribute value as a quoted literal, such as `value="12.4"`. Expressions in braces, imports, scripts, HTML tags, comments, classes, styles, and colors are not supported. +- Put text only inside `Text`, `Badge`, `Column`, and `Cell`. It is plain text: Markdown and nested tags are not interpreted. +- Write `<`, `>`, `&`, `"`, `{`, and `}` for a literal `<`, `>`, `&`, `"`, `{`, and `}`. +- A `Bar` value is a number that is not negative, written with digits only, such as `12.4`. Put the unit in the chart's `unit` attribute, not in the value. +- A `Metric` value is text, so it can carry its unit, such as `1.8 s`. +- Limits: 32,000 characters, 2,000 components, 8 levels of nesting, 12 columns and 100 rows per table, and 24 bars per chart. Summarize or split larger data. +- Links, images, and code do not belong in a visual. Put them in Markdown outside the block. + +For a diagram, a mockup, or a layout that these components cannot express, use Markdown, or an HTML preview when that is available. diff --git a/src/vs/sessions/test/agents.web.mobile.test.internal.ts b/src/vs/sessions/test/agents.web.mobile.test.internal.ts new file mode 100644 index 000000000000..6496c49024ff --- /dev/null +++ b/src/vs/sessions/test/agents.web.mobile.test.internal.ts @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Test entry point for the mobile Agents workbench with mock services. +// Mirrors agents.web.mobile.main.internal.ts but uses TestSessionsBrowserMain. + +import '../agents.web.mobile.main.js'; +import { create as createTestSessionsWorkbench } from './web.test.factory.js'; +import { createMobileSessionsWorkbench } from '../browser/mobile/mobileWorkbench.js'; +import { IWorkbenchConstructionOptions } from '../../workbench/browser/web.api.js'; +import { Disposable, IDisposable } from '../../base/common/lifecycle.js'; +import { URI } from '../../base/common/uri.js'; +import { Event, Emitter } from '../../base/common/event.js'; +import { LogLevel } from '../../platform/log/common/log.js'; + +/** + * Creates the mobile Sessions workbench with mock services for E2E testing. + */ +function create(domElement: HTMLElement, options: IWorkbenchConstructionOptions): IDisposable { + return createTestSessionsWorkbench(domElement, options, createMobileSessionsWorkbench); +} + +export { + create, + URI, + Event, + Emitter, + Disposable, + LogLevel, +}; diff --git a/src/vs/sessions/test/browser/actionList.fixture.ts b/src/vs/sessions/test/browser/actionList.fixture.ts index 23429cbe7589..af3bc9ee01f8 100644 --- a/src/vs/sessions/test/browser/actionList.fixture.ts +++ b/src/vs/sessions/test/browser/actionList.fixture.ts @@ -67,6 +67,7 @@ export default defineThemedFixtureGroup({ path: 'sessions/actionList' }, { }), MouseNavigation: defineComponentFixture({ additionalThemes: ['light2026', 'darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer-focused action-list row uses the list hover fill. In high contrast themes, it has a dashed active-contrast boundary rather than a solid keyboard-focus boundary.'], render: context => renderActionList(context, 'mouse'), }), NarrowContextDetails: defineComponentFixture({ diff --git a/src/vs/sessions/test/browser/agentsPartCard.test.ts b/src/vs/sessions/test/browser/agentsPartCard.test.ts index f6f0478ad65f..db25832091fd 100644 --- a/src/vs/sessions/test/browser/agentsPartCard.test.ts +++ b/src/vs/sessions/test/browser/agentsPartCard.test.ts @@ -11,15 +11,21 @@ import assert from 'assert'; import sinon from 'sinon'; import { $, append } from '../../../base/browser/dom.js'; import { mainWindow } from '../../../base/browser/window.js'; -import { toDisposable } from '../../../base/common/lifecycle.js'; +import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; +import { createStyleSheet } from '../../../base/browser/domStylesheets.js'; +import { TestConfigurationService } from '../../../platform/configuration/test/common/testConfigurationService.js'; +import { NullLogService } from '../../../platform/log/common/log.js'; +import { SIZE_CUSTOMIZATIONS_SETTING } from '../../../platform/theme/common/sizeService.js'; +import { TestColorTheme } from '../../../platform/theme/test/common/testThemeService.js'; +import { WorkbenchSizeService } from '../../../workbench/services/themes/browser/workbenchSizeService.js'; +import { generateColorThemeCSS } from '../../../workbench/services/themes/browser/colorThemeCss.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { MainEditorPart as MainEditorPartBase } from '../../../workbench/browser/parts/editor/editorPart.js'; import { AbstractPaneCompositePart } from '../../../workbench/browser/parts/paneCompositePart.js'; -import { Parts } from '../../../workbench/services/layout/browser/layoutService.js'; import { MODERN_SASH_GRIP_FOREGROUND } from '../../../workbench/common/theme.js'; -import { generateColorThemeCSS } from '../../../workbench/services/themes/browser/colorThemeCss.js'; import { ColorThemeData } from '../../../workbench/services/themes/common/colorThemeData.js'; import { AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS, getAgentsPartCardContentSize, getSessionsPartCardMarginRight, getSessionsPartFrameInset, getSidePaneBottomFrameInset, getSidePaneFrameInset } from '../../../workbench/browser/parts/sessions/agentsPartCard.js'; +import { Parts } from '../../../workbench/services/layout/browser/layoutService.js'; import { CustomViewGridPart } from '../../browser/parts/customViewGridPart.js'; import { AgentWorkbenchLayout } from '../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; import { MainEditorPart } from '../../browser/parts/editorPart.js'; @@ -54,6 +60,114 @@ suite('Sessions - Agents Part Card', () => { return { container, card }; } + for (const compact of [false, true]) { + test(`resolves component-specific semantic corners in Agents with compact layout ${compact}`, () => { + const configuration = new TestConfigurationService({ + [SIZE_CUSTOMIZATIONS_SETTING]: { + 'panels.cornerRadius': 3, + 'agentsWindow.toolsPanel.cornerRadius': 1, + 'agentsWindow.chatPanels.cornerRadius': 2, + 'agentsWindow.editorArea.cornerRadius': 4, + 'pages.cornerRadius': 5, + 'agentsWindow.secondarySideBar.cornerRadius': 6, + }, + }); + store.add(configuration.onDidChangeConfigurationEmitter); + const sizes = store.add(new WorkbenchSizeService(configuration, store.add(new NullLogService()))); + const sheet = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + sheet.textContent = generateColorThemeCSS(new TestColorTheme(), '.semantic-agents-sizes', undefined, undefined, sizes).code; + const { container, card } = createCard(true, true, false, compact); + container.classList.add('semantic-agents-sizes', 'modern-ui-tabs', 'modern-ui-connected-editor-tabs'); + card.classList.add('part', 'sessionspart'); + const session = append(card, $('.session-view')); + const customView = append(container, $('.agents-part-card.agents-card-surface')); + const grid = append(container, $('.monaco-grid-view')); + const editor = append(grid, $('.part.editor')); + const auxiliary = append(grid, $('.part.auxiliarybar')); + const panel = append(grid, $('.part.panel')); + const read = (element: HTMLElement) => { + const css = mainWindow.getComputedStyle(element); + return [css.borderTopLeftRadius, css.borderTopRightRadius, css.borderBottomRightRadius, css.borderBottomLeftRadius]; + }; + assert.deepStrictEqual([card, session, customView, editor, auxiliary, panel].map(read), compact + ? Array.from({ length: 6 }, () => ['0px', '0px', '0px', '0px']) + : [ + ['2px', '2px', '2px', '2px'], + ['1px', '1px', '1px', '1px'], + ['5px', '5px', '5px', '5px'], + ['4px', '0px', '0px', '4px'], + ['0px', '6px', '6px', '0px'], + ['1px', '1px', '1px', '1px'], + ]); + }); + } + + for (const spacing of [0, 1, 4, 8, 16]) { + for (const connected of [false, true]) { + test(`matches ${spacing}px Agents gaps and content sizes with ${connected ? 'connected' : 'pill'} tabs`, () => { + const { container, card } = createCard(true, true); + container.classList.add('modern-ui-tabs', 'dock-detail-panel', AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS); + container.classList.toggle('modern-ui-connected-editor-tabs', connected); + container.style.setProperty('--vscode-agentsWindow-panels-spacing', `${spacing}px`); + container.style.setProperty('--vscode-sash-size', '4px'); + card.classList.add('part', 'sessionspart'); + const row = append(container, $('.monaco-grid-view')); + row.style.display = 'flex'; + row.style.position = 'relative'; + const allocation = append(row, $('.session-allocation')); + allocation.style.cssText = 'width: 500px; height: 300px; flex-shrink: 0;'; + append(allocation, card); + card.style.height = '100%'; + const sessionInset = getSessionsPartFrameInset(container, spacing); + const sideInset = getSidePaneFrameInset(container, spacing); + const margin = getSessionsPartCardMarginRight(container, spacing); + const cardSize = getAgentsPartCardContentSize(500, 300, true, true, false, false, margin, sessionInset); + const content = append(card, $('.content')); + content.style.width = `${cardSize.width}px`; + content.style.height = `${cardSize.height}px`; + const session = append(content, $('.session-view')); + session.style.cssText = 'width: 100%; height: 100%;'; + const editor = append(row, $('.part.editor.editor-tabs-multiple')); + editor.style.cssText = 'width: 300px; height: 300px; flex-shrink: 0;'; + const divider = append(row, $('.monaco-sash.vertical.sessions-side-pane-divider')); + divider.style.left = '498px'; + const targetWindow = mainWindow; + const actualGap = editor.getBoundingClientRect().left + sideInset - session.getBoundingClientRect().right; + const cssSessionInset = targetWindow.getComputedStyle(container).getPropertyValue('--agents-session-frame-inset'); + const cssSideInset = targetWindow.getComputedStyle(container).getPropertyValue('--agents-side-pane-frame-inset'); + const sashBounds = divider.getBoundingClientRect(); + const sessionBounds = session.getBoundingClientRect(); + assert.deepStrictEqual({ + actualGap, + contentWidth: content.clientWidth, + availableWidth: card.clientWidth, + contentHeight: content.clientHeight, + availableHeight: card.clientHeight, + insets: [sessionInset, sideInset], + borderWidths: [targetWindow.getComputedStyle(card).borderLeftWidth, targetWindow.getComputedStyle(editor).borderLeftWidth], + nonnegativeMargins: Number.parseFloat(targetWindow.getComputedStyle(card).marginRight) >= 0, + sashSize: sashBounds.width, + sashCenter: sashBounds.left + sashBounds.width / 2 - sessionBounds.right, + outerGutter: targetWindow.getComputedStyle(row).marginRight, + insetVariablesPresent: cssSessionInset.length > 0 && cssSideInset.length > 0, + }, { + actualGap: spacing, + contentWidth: cardSize.width, + availableWidth: cardSize.width, + contentHeight: cardSize.height, + availableHeight: cardSize.height, + insets: [Math.min(1, spacing), connected ? Math.min(1, Math.max(0, spacing - 1)) : 0], + borderWidths: [`${sessionInset}px`, connected ? `${sideInset}px` : '1px'], + nonnegativeMargins: true, + sashSize: 4, + sashCenter: spacing / 2, + outerGutter: '4px', + insetVariablesPresent: true, + }); + }); + } + } + for (const compact of [false, true]) { for (const { sidebarVisible, editorPaneVisible, contentWidth } of [ { sidebarVisible: true, editorPaneVisible: true, contentWidth: 794 }, @@ -240,6 +354,7 @@ suite('Sessions - Agents Part Card', () => { mainContainer: container, agentWorkbenchLayout: AgentWorkbenchLayout.Desktop, isModernUICompact: () => false, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.EDITOR_PART || partId === Parts.SESSIONS_PART || partId === Parts.PANEL_PART, @@ -313,6 +428,7 @@ suite('Sessions - Agents Part Card', () => { mainContainer: container, agentWorkbenchLayout: AgentWorkbenchLayout.Mobile, isModernUICompact: () => false, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.EDITOR_PART || partId === Parts.AUXILIARYBAR_PART || partId === Parts.SESSIONS_PART @@ -371,6 +487,7 @@ suite('Sessions - Agents Part Card', () => { layoutService: { mainContainer: container, isModernUICompact: () => false, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.PANEL_PART || partId === Parts.SIDEBAR_PART || (partId === Parts.SESSIONS_PART && sessionsVisible), @@ -432,6 +549,7 @@ suite('Sessions - Agents Part Card', () => { mainContainer: workbench, agentWorkbenchLayout: desktop ? AgentWorkbenchLayout.Desktop : AgentWorkbenchLayout.Mobile, isModernUICompact: () => false, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.EDITOR_PART || (partId === Parts.SIDEBAR_PART && state.sidebar) || (partId === Parts.SESSIONS_PART && state.sessions), @@ -480,6 +598,7 @@ suite('Sessions - Agents Part Card', () => { mainContainer: workbench, agentWorkbenchLayout: desktop ? AgentWorkbenchLayout.Desktop : AgentWorkbenchLayout.Mobile, isModernUICompact: () => compact, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.EDITOR_PART, }, }; @@ -553,6 +672,7 @@ suite('Sessions - Agents Part Card', () => { layoutService: { mainContainer: container, isModernUICompact: () => compact, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: () => true, getPanelAlignment: () => 'justify' as const, }, @@ -595,6 +715,7 @@ suite('Sessions - Agents Part Card', () => { layoutService: { mainContainer: container, isModernUICompact: () => false, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId === Parts.PANEL_PART || (partId === Parts.SIDEBAR_PART && sidebarVisible) || ((partId === Parts.EDITOR_PART || partId === Parts.AUXILIARYBAR_PART) && editorPaneVisible), @@ -638,7 +759,7 @@ suite('Sessions - Agents Part Card', () => { test('keeps connected chat and editor frames flush in compact density', () => { const { container, card } = createCard(true, true); - container.classList.add('modern-ui-tabs', 'modern-ui-connected-editor-tabs', 'dock-detail-panel'); + container.classList.add('modern-ui-tabs', 'modern-ui-connected-editor-tabs', 'dock-detail-panel', AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS); container.style.setProperty('--modern-ui-connected-tab-border', '#808080'); container.style.setProperty('--vscode-editorGroupHeader-tabsBorder', '#808080'); card.classList.add('part', 'sessionspart', 'sessions-chat-surface'); @@ -757,6 +878,7 @@ suite('Sessions - Agents Part Card', () => { const layoutService = { mainContainer: container, isModernUICompact: () => true, + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: () => true, getPanelAlignment: () => 'justify' as const, }; @@ -841,6 +963,7 @@ suite('Sessions - Agents Part Card', () => { layoutService: { mainContainer: container, isModernUICompact: () => compact && !container.classList.contains('phone-layout'), + getPanelSpacing() { return this.isModernUICompact() ? 0 : 4; }, isVisible: (partId: Parts) => partId !== Parts.SIDEBAR_PART, }, agentWorkbenchLayoutService: { diff --git a/src/vs/sessions/test/browser/chatCompositeBar.test.ts b/src/vs/sessions/test/browser/chatCompositeBar.test.ts index 84ca1aae45eb..d9013a757302 100644 --- a/src/vs/sessions/test/browser/chatCompositeBar.test.ts +++ b/src/vs/sessions/test/browser/chatCompositeBar.test.ts @@ -199,6 +199,7 @@ interface IChatCompositeBarHarness { readonly activeChatResource: ISettableObservable; readonly visible: ISettableObservable; readonly showSessionActions: ISettableObservable; + readonly renamedChats: readonly string[]; } function createHarness(disposables: Pick, options?: { readonly isAgentHost?: boolean; readonly isQuickChat?: boolean; readonly standaloneChat?: boolean; readonly resizeObserverCtor?: typeof ResizeObserver; readonly mainIsRead?: boolean; readonly secondaryIsRead?: boolean; readonly secondaryArchived?: boolean; readonly secondaryCanArchive?: boolean; readonly terminalControls?: boolean; readonly sessionSupportsRename?: boolean; readonly secondaryHarness?: string; readonly knownHarnesses?: IObservable; readonly accessibilityService?: IAccessibilityService; readonly providerLookup?: (providerId: string, sessionId?: string) => ISessionsProvider | undefined }): IChatCompositeBarHarness { @@ -257,8 +258,12 @@ function createHarness(disposables: Pick, options?: { re }); instantiationService.stub(ISessionsService, sessionsService); instantiationService.stub(IEditorGroupsService, editorGroupsService); + const renamedChats: string[] = []; instantiationService.stub(ISessionsManagementService, new class extends mock() { override readonly onDidChangeSessions = Event.None; + override async renameChat(_session: ISession, chatResource: URI, title: string): Promise { + renamedChats.push(`${chatResource.toString()}: ${title}`); + } }()); instantiationService.stub(ISessionsPartService, new class extends mock() { }); instantiationService.stub(ISessionsProvidersService, new class extends mock() { @@ -285,7 +290,7 @@ function createHarness(disposables: Pick, options?: { re container.appendChild(bar.element); const tabs = Array.from(bar.element.querySelectorAll('.chat-composite-bar-tab')); - return { store, instantiationService, commandService, contextMenuService, sessionsService, editorGroupsService, bar, container, session, tabs, chats, activeChatResource, visible, showSessionActions }; + return { store, instantiationService, commandService, contextMenuService, sessionsService, editorGroupsService, bar, container, session, tabs, chats, activeChatResource, visible, showSessionActions, renamedChats }; } suite('Sessions - ChatCompositeBar', () => { @@ -1593,6 +1598,26 @@ suite('Sessions - ChatCompositeBar', () => { }); }); + test('rename input commits on Enter and on blur, and Escape cancels', () => { + const { renamedChats, tabs } = createHarness(disposables); + const rename = (title: string, end: (input: HTMLInputElement) => void) => { + tabs[1].dispatchEvent(new MouseEvent(EventType.DBLCLICK, { bubbles: true, button: 0, cancelable: true })); + const input = tabs[1].querySelector('.chat-composite-bar-tab-input input')!; + input.value = title; + end(input); + }; + const pressKey = (input: HTMLInputElement, key: string, keyCode: number) => input.dispatchEvent(new KeyboardEvent(EventType.KEY_DOWN, { key, code: key, keyCode, bubbles: true, cancelable: true })); + + rename('Committed on Enter', input => pressKey(input, 'Enter', 13)); + rename('Committed on blur', input => input.dispatchEvent(new FocusEvent(EventType.BLUR))); + rename('Cancelled with Escape', input => { + pressKey(input, 'Escape', 27); + input.dispatchEvent(new FocusEvent(EventType.BLUR)); + }); + + assert.deepStrictEqual(renamedChats, ['test-chat://secondary: Committed on Enter', 'test-chat://secondary: Committed on blur']); + }); + test('rename input lets clipboard and editing shortcuts reach the workbench keybinding dispatcher without driving the tab', () => { const { container, sessionsService, tabs } = createHarness(disposables); const bubbled: string[] = []; diff --git a/src/vs/sessions/test/browser/chatGroupsView.test.ts b/src/vs/sessions/test/browser/chatGroupsView.test.ts index f40d5f4ce308..a13981a64d44 100644 --- a/src/vs/sessions/test/browser/chatGroupsView.test.ts +++ b/src/vs/sessions/test/browser/chatGroupsView.test.ts @@ -25,7 +25,7 @@ import { IMenu, IMenuService, MenuId, MenuItemAction } from '../../../platform/a import { Menus } from '../../../workbench/contrib/sessions/browser/menus.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; import { ICommandService } from '../../../platform/commands/common/commands.js'; -import { UNARCHIVE_CHAT_COMMAND_ID } from '../../../workbench/contrib/sessions/common/sessionCommands.js'; +import { CLOSE_CHAT_COMMAND_ID, UNARCHIVE_CHAT_COMMAND_ID } from '../../../workbench/contrib/sessions/common/sessionCommands.js'; import { LocalSelectionTransfer } from '../../../platform/dnd/browser/dnd.js'; import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ColorScheme } from '../../../platform/theme/common/theme.js'; @@ -84,6 +84,7 @@ class TestChatView extends AbstractChatView { constructor( readonly kind: ChatViewKind, @IContextKeyService contextKeyService: IContextKeyService, + @ISessionHost readonly host: ISessionHost, ) { super(); this._register(contextKeyService.createScoped(this.element)); @@ -248,8 +249,11 @@ class TestSessionsService extends mock() { this.activeSession.set(session, undefined); } - override async closeChat(_session: ISession, chat: IChat): Promise { + override async closeChat(session: ISession, chat: IChat): Promise { this.closedChats.push(chat.resource.toString()); + if (session instanceof TestActiveSession) { + session.visibleChatTabs.set(session.visibleChatTabs.get().filter(candidate => candidate !== chat), undefined); + } } override closeSession(session: ISession | undefined): void { @@ -260,6 +264,17 @@ class TestSessionsService extends mock() { } } +class TestCommandService extends mock() { + readonly calls: { readonly id: string; readonly args: readonly unknown[] }[] = []; + handler: ((id: string, args: readonly unknown[]) => Promise) | undefined; + + override async executeCommand(id: string, ...args: unknown[]): Promise { + this.calls.push({ id, args }); + await this.handler?.(id, args); + return undefined; + } +} + class TestSessionsProvidersService extends mock() { override readonly onDidChangeProviders = Event.None; provider: ISessionsProvider | undefined; @@ -309,6 +324,7 @@ interface IChatGroupsHarness { readonly instantiationService: TestInstantiationService; readonly sessionsService: TestSessionsService; readonly sessionsProvidersService: TestSessionsProvidersService; + readonly commandService: TestCommandService; readonly chatViewFactory: TestChatViewFactory; readonly configurationService: TestConfigurationService; readonly chatHostOpenerService: ChatHostOpenerService; @@ -336,6 +352,7 @@ function createHarness(disposables: Pick, tabsReplaceHea instantiationService.stub(ISessionActivityBarActivityService, store.add(new SessionActivityBarActivityService())); } const sessionsService = new TestSessionsService(); + const commandService = new TestCommandService(); const chatViewFactory = new TestChatViewFactory(); const configurationService = new TestConfigurationService({ [SESSIONS_CHAT_TABS_SETTING]: SessionsChatTabsMode.Multiple }); instantiationService.stub(IConfigurationService, configurationService); @@ -348,8 +365,9 @@ function createHarness(disposables: Pick, tabsReplaceHea override readonly partOptions = DEFAULT_EDITOR_PART_OPTIONS; }()); instantiationService.stub(ISessionsService, sessionsService); + instantiationService.stub(ICommandService, commandService); // The window host shows the active session, as the main window's does. - const windowHost = upcastPartial({ kind: SessionHostKind.MainWindow, parent: undefined, session: sessionsService.activeSession, chat: derived(reader => sessionsService.activeSession.read(reader)?.activeChat.read(reader)) }); + const windowHost = upcastPartial({ id: 'main-window', kind: SessionHostKind.MainWindow, parent: undefined, session: sessionsService.activeSession, chat: derived(reader => sessionsService.activeSession.read(reader)?.activeChat.read(reader)), commandContext: { sessionHostId: 'main-window' } }); instantiationService.stub(ISessionHost, windowHost); const focus = { viewWindow: true }; instantiationService.stub(ISessionsManagementService, new class extends mock() { @@ -368,7 +386,7 @@ function createHarness(disposables: Pick, tabsReplaceHea view.setSingleGroupTabsReplaceHeader(tabsReplaceHeader); mainWindow.document.body.appendChild(view.element); store.add(toDisposable(() => view.element.remove())); - return { instantiationService, sessionsService, sessionsProvidersService, chatViewFactory, configurationService, chatHostOpenerService, view, focus }; + return { instantiationService, sessionsService, sessionsProvidersService, commandService, chatViewFactory, configurationService, chatHostOpenerService, view, focus }; } function readBanner(view: ChatGroupsView): { readonly visible: boolean; readonly message: string | undefined; readonly action: string | undefined } { @@ -535,7 +553,7 @@ suite('Sessions - ChatGroupsView', () => { test('renders vertically split chats as independent panels', async () => { const { view } = createHarness(disposables); const workbench = $('.monaco-workbench.agent-sessions-workbench.mac.macos-tahoe.modern-ui-tabs.modern-ui-connected-editor-tabs.nopanel.noeditorpane.nosidebar'); - workbench.style.cssText = '--agents-floating-panel-gap: 4px; --agents-part-corner-radius: 8px; --vscode-strokeThickness: 1px; --window-corner-radius: 16px; --modern-ui-connected-tab-border: #445566; --session-view-background: #112233; --vscode-inactiveSessionView-background: #112233;'; + workbench.style.cssText = '--vscode-agents-layout-floatingPanelGap: 4px; --agents-floating-panel-gap: 4px; --agents-part-corner-radius: 8px; --vscode-strokeThickness: 1px; --window-corner-radius: 16px; --modern-ui-connected-tab-border: #445566; --session-view-background: #112233; --vscode-inactiveSessionView-background: #112233;'; const card = $('.part.sessionspart.sessions-chat-surface.agents-part-card.agents-card-surface'); const sessionView = $('.session-view.independent-chat-groups'); sessionView.appendChild(view.element); @@ -898,6 +916,22 @@ suite('Sessions - ChatGroupsView', () => { }); }); + test('each group of a split session gives its chat view its own chat', async () => { + const { sessionsService, view, chatViewFactory } = createHarness(disposables); + const main = createChat('main'); + const child = createChat('child', SessionStatus.Completed, main.resource); + const session = new TestActiveSession([main, child]); + sessionsService.activeSession.set(session, undefined); + view.setSession(paneContent(view, session), options); + view.layout(800, 600, 0, 0); + view.splitChatToSide(child.resource); + await timeout(0); + + assert.deepStrictEqual( + chatViewFactory.views.filter(v => !v.isDisposed).map(v => v.host.chat.get()?.resource.toString()), + [main.resource.toString(), child.resource.toString()]); + }); + test('expands a collapsed group when its chat becomes active without taking focus', async () => { const { sessionsService, view } = createHarness(disposables); const main = createChat('main'); @@ -1208,6 +1242,59 @@ suite('Sessions - ChatGroupsView', () => { }); }); + test('middle-clicking a chat header closes only that chat group', async () => { + const { commandService, configurationService, sessionsService, view } = createHarness(disposables); + const main = createChat('main'); + const secondary = createChat('secondary'); + const session = new TestActiveSession([main, secondary]); + view.setSession(paneContent(view, session), options); + view.splitChatToSide(secondary.resource); + await configurationService.setUserConfiguration(SESSIONS_CHAT_TABS_SETTING, SessionsChatTabsMode.Single); + configurationService.onDidChangeConfigurationEmitter.fire({ + source: ConfigurationTarget.USER, + affectedKeys: new Set([SESSIONS_CHAT_TABS_SETTING]), + change: { keys: [SESSIONS_CHAT_TABS_SETTING], overrides: [] }, + affectsConfiguration: key => key === SESSIONS_CHAT_TABS_SETTING, + }); + commandService.handler = async (id, args) => { + assert.strictEqual(id, CLOSE_CHAT_COMMAND_ID); + const chat = args[1] as IChat; + await view.closeChatGroup(chat.resource); + await sessionsService.closeChat(session, chat); + }; + const headers = view.element.querySelectorAll('.chat-composite-bar-session-title'); + const event = new MouseEvent('auxclick', { bubbles: true, button: 1, cancelable: true }); + + headers[1].dispatchEvent(event); + await timeout(0); + + assert.deepStrictEqual({ + defaultPrevented: event.defaultPrevented, + command: commandService.calls.map(call => ({ + id: call.id, + sessionMatches: call.args[0] === session, + chatMatches: call.args[1] === secondary, + hostContext: call.args[2], + })), + groupCount: view.groupCount.get(), + closedChats: sessionsService.closedChats, + groupChats: view['_groups'][0].resourceIds.get(), + visibleChats: session.visibleChatTabs.get().map(chat => chat.resource.toString()), + }, { + defaultPrevented: true, + command: [{ + id: CLOSE_CHAT_COMMAND_ID, + sessionMatches: true, + chatMatches: true, + hostContext: { sessionHostId: 'main-window' }, + }], + groupCount: 1, + closedChats: [secondary.resource.toString()], + groupChats: [main.resource.toString()], + visibleChats: [main.resource.toString()], + }); + }); + test('single mode replaces the current peer instead of stacking it behind the opened peer', async () => { const { configurationService, sessionsService, view } = createHarness(disposables); const main = createChat('main'); diff --git a/src/vs/sessions/test/browser/dockedAuxiliaryBarController.test.ts b/src/vs/sessions/test/browser/dockedAuxiliaryBarController.test.ts new file mode 100644 index 000000000000..e748767bd801 --- /dev/null +++ b/src/vs/sessions/test/browser/dockedAuxiliaryBarController.test.ts @@ -0,0 +1,277 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Event } from '../../../base/common/event.js'; +import { toDisposable } from '../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { IAccessibilityService } from '../../../platform/accessibility/common/accessibility.js'; +import { NullHoverService } from '../../../platform/hover/test/browser/nullHoverService.js'; +import { Part } from '../../../workbench/browser/part.js'; +import { DockedAuxiliaryBarController, IDockedAuxiliaryBarHost } from '../../browser/dockedAuxiliaryBarController.js'; +import { FloatingAuxiliaryBarController } from '../../browser/floatingAuxiliaryBarController.js'; +import { DetailsPosition } from '../../../workbench/contrib/sessions/common/sessionConfig.js'; +import '../../browser/media/workbench.css'; + +suite('Sessions - Docked Details Position', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createHost() { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.dock-detail-panel')); + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-agentsPanel-border', '#abcdef'); + store.add(toDisposable(() => root.remove())); + const editor = append(root, $('.part.editor')); + const part = append(editor, $('.part.auxiliarybar')); + Object.defineProperties(editor, { clientWidth: { value: 800 }, clientHeight: { value: 600 } }); + editor.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600); + let position: DetailsPosition = 'right'; + let width = 260; + let height = 200; + let visible = true; + let editorVisible = true; + let contentTop = 65; + let floating = false; + let collapses = 0; + let insets = [0, 0, 0, 0]; + let lastLayout: number[] = []; + const auxiliaryBarPart = upcastPartial({ + getContainer: () => part, + layout: (width, height, top, left) => { part.style.height = ''; lastLayout = [width, height, top, left]; }, + }); + const host: IDockedAuxiliaryBarHost = { + getPosition: () => position, + getWidth: () => width, setWidth: value => { width = value; }, + getHeight: () => height, setHeight: value => { height = value; }, + isEditorAreaVisible: () => true, + isEditorVisible: () => editorVisible, + isAuxiliaryBarVisible: () => visible, + hideAuxiliaryBar: () => { visible = false; collapses++; }, + setEditorContentInsets: (right, top, bottom, left) => { insets = [right, top, bottom, left]; }, + getTabsHeight: () => 33, + getEditorContentTop: () => contentTop, + }; + const controller = store.add(new DockedAuxiliaryBarController(editor, auxiliaryBarPart, host, { + isEnabled: () => floating, + createController: () => new FloatingAuxiliaryBarController(editor, auxiliaryBarPart, { + getTitle: () => 'Files', getIcon: () => undefined, isChangesViewActive: () => false, onDidChangeTitle: Event.None, + getWidth: () => 260, setWidth: () => { }, + getHeight: () => 400, setHeight: () => { }, + getContentHeight: () => undefined, onDidChangeContentHeight: Event.None, setSizeToContent: () => { }, + focusEditor: () => { }, + }, upcastPartial({ isMotionReduced: () => true, onDidChangeReducedMotion: Event.None }), NullHoverService), + })); + return { + editor, part, controller, + getWidth: () => width, + setPosition: (value: DetailsPosition) => { position = value; controller.layout(); }, + setEditorVisible: (value: boolean) => { editorVisible = value; controller.layout(); }, + setContentTop: (value: number) => { contentTop = value; controller.layout(); }, + setFloating: (value: boolean) => { floating = value; controller.layout(); }, + show: () => { visible = true; controller.layout(); }, + hide: () => { visible = false; controller.layout(); }, + snapshot: () => ({ insets, layout: lastLayout, requestedHeight: height, collapses }), + }; + } + + test('places details above or below main content, never outside the editor frame', () => { + const { part, editor, controller, setPosition, snapshot } = createHost(); + controller.layout(); + const right = snapshot(); + setPosition('left'); + const left = { ...snapshot(), anchors: [part.style.left, part.style.right] }; + setPosition('top'); + const top = { ...snapshot(), allocatedHeight: part.style.height }; + setPosition('bottom'); + const bottom = { ...snapshot(), allocatedHeight: part.style.height }; + setPosition('right'); + assert.deepStrictEqual({ right, left, top, bottom, restored: snapshot(), anchors: [part.style.left, part.style.right], parentPreserved: part.parentElement === editor }, { + right: { insets: [260, 0, 0, 0], layout: [260, 567, 33, 540], requestedHeight: 200, collapses: 0 }, + left: { insets: [0, 0, 0, 260], layout: [260, 567, 33, 0], requestedHeight: 200, collapses: 0, anchors: ['0px', ''] }, + top: { insets: [0, 200, 0, 0], layout: [800, 199, 65, 0], requestedHeight: 200, collapses: 0, allocatedHeight: '200px' }, + bottom: { insets: [0, 0, 200, 0], layout: [800, 199, 400, 0], requestedHeight: 200, collapses: 0, allocatedHeight: '200px' }, + anchors: ['', '0px'], + restored: right, parentPreserved: true, + }); + }); + + test('left details resize from the right edge, reset, and retain their width after collapse', () => { + const { editor, part, controller, setPosition, snapshot, getWidth, show } = createHost(); + setPosition('left'); + const sash = editor.querySelector('.monaco-sash.vertical:not(.disabled)')!; + const drag = (from: number, to: number) => { + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: from, clientY: 100, bubbles: true })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: to, clientY: 100 })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: to, clientY: 100 })); + }; + const initialSash = sash.style.left; + drag(260, 320); + const resized = getWidth(); + sash.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const reset = getWidth(); + drag(300, 0); + controller.layout(); + const collapsed = part.style.display; + show(); + const style = mainWindow.getComputedStyle(part); + assert.deepStrictEqual({ initialSash, resized, reset, collapsed, width: getWidth(), restored: snapshot(), border: [style.borderLeftWidth, style.borderRightWidth] }, { + initialSash: '258px', resized: 320, reset: 300, collapsed: 'none', width: 300, + restored: { insets: [0, 0, 0, 300], layout: [300, 567, 33, 0], requestedHeight: 200, collapses: 1 }, + border: ['0px', '1px'], + }); + }); + + for (const position of ['top', 'bottom'] as const) { + test(`${position} sash resizes, resets, collapses, and restores the remembered height`, () => { + const { editor, part, controller, setPosition, snapshot, show } = createHost(); + setPosition(position); + const sash = editor.querySelector('.monaco-sash.horizontal:not(.disabled)')!; + const drag = (from: number, to: number) => { + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: 400, clientY: from, bubbles: true })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 400, clientY: to })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: 400, clientY: to })); + }; + drag(300, position === 'top' ? 360 : 240); + const resized = snapshot().requestedHeight; + sash.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const reset = snapshot().requestedHeight; + drag(300, position === 'top' ? 0 : 600); + controller.layout(); + const collapsed = part.style.display; + show(); + assert.deepStrictEqual({ resized, reset, collapsed, restored: snapshot() }, { + resized: 260, reset: 240, collapsed: 'none', + restored: { + insets: position === 'top' ? [0, 240, 0, 0] : [0, 0, 240, 0], + layout: [800, 239, position === 'top' ? 65 : 360, 0], + requestedHeight: 240, collapses: 1, + }, + }); + }); + } + + test('detail-only presentation fills the frame below tabs and disables the local sash', () => { + const { editor, setPosition, setEditorVisible, snapshot } = createHost(); + setPosition('bottom'); + setEditorVisible(false); + assert.deepStrictEqual({ state: snapshot(), enabledSashes: editor.querySelectorAll('.monaco-sash:not(.disabled)').length }, { + state: { insets: [0, 0, 0, 0], layout: [800, 566, 33, 0], requestedHeight: 200, collapses: 0 }, enabledSashes: 0, + }); + }); + + test('floating presentation overrides stacking and restores the selected position when disabled', () => { + const { editor, part, setPosition, setFloating, snapshot } = createHost(); + setPosition('top'); + setFloating(true); + const floating = { insets: snapshot().insets, overlay: part.classList.contains('floating-auxiliarybar') }; + setFloating(false); + assert.deepStrictEqual({ floating, restored: snapshot(), parentPreserved: part.parentElement === editor }, { + floating: { insets: [0, 0, 0, 0], overlay: true }, + restored: { insets: [0, 200, 0, 0], layout: [800, 199, 65, 0], requestedHeight: 200, collapses: 0 }, + parentPreserved: true, + }); + }); + + test('floating details start and reset below the editor selector and follow header height changes', () => { + const { editor, controller, setFloating, setContentTop, snapshot } = createHost(); + setFloating(true); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + const initial = widget.style.top; + grip.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', keyCode: 40, bubbles: true })); + const moved = parseFloat(widget.style.top) > parseFloat(initial); + grip.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const reset = widget.style.top; + setContentTop(97); + const tallerHeader = widget.style.top; + setContentTop(33); + controller.revealFloatingDetails(); + assert.deepStrictEqual({ initial, moved, reset, tallerHeader, tabsOnly: widget.style.top, expandedContentTop: snapshot().layout[2] }, { + initial: '73px', moved: true, reset: '73px', tallerHeader: '105px', tabsOnly: '41px', expandedContentTop: 73, + }); + }); + + test('left details clear their inset in floating mode and restore their docked edge afterward', () => { + const { part, setPosition, setFloating, setEditorVisible, snapshot, editor } = createHost(); + setPosition('left'); + setFloating(true); + const floating = { insets: snapshot().insets, left: part.classList.contains('docked-auxiliarybar-left') }; + setFloating(false); + const restored = { insets: snapshot().insets, anchors: [part.style.left, part.style.right] }; + setEditorVisible(false); + assert.deepStrictEqual({ floating, restored, detailOnly: snapshot().layout, enabledSashes: editor.querySelectorAll('.monaco-sash:not(.disabled)').length }, { + floating: { insets: [0, 0, 0, 0], left: false }, + restored: { insets: [0, 0, 0, 260], anchors: ['0px', ''] }, + detailOnly: [800, 567, 33, 0], enabledSashes: 0, + }); + }); + + test('a view-focus request pins floating details even when its controller has not been created yet', () => { + const { editor, part, controller, hide, show, setFloating } = createHost(); + hide(); + setFloating(true); + controller.revealFloatingDetails(); + show(); + controller.onDidOpenItem(); + assert.deepStrictEqual({ + expanded: editor.querySelector('.floating-details-header .action-label')?.getAttribute('aria-expanded'), + label: editor.querySelector('.floating-details-header .action-label')?.getAttribute('aria-label'), + body: part.style.display, + }, { expanded: 'true', label: 'Unpin Files', body: '' }); + }); + + test('a completed view-focus request does not re-pin an unpinned preview on later layouts', () => { + const { editor, controller, setFloating } = createHost(); + setFloating(true); + controller.revealFloatingDetails(); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + widget.querySelector('.floating-details-toggle')!.click(); + const unpinned = widget.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed'); + controller.layout(); + assert.deepStrictEqual({ + unpinned, afterLayout: widget.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed'), + expanded: !widget.classList.contains('collapsed'), + }, { unpinned: 'false', afterLayout: 'false', expanded: true }); + }); + + test('leaving floating mode cancels a pending view-focus pin request', () => { + const { editor, controller, setFloating, hide, show } = createHost(); + hide(); + setFloating(true); + controller.revealFloatingDetails(); + setFloating(false); + show(); + setFloating(true); + assert.deepStrictEqual({ + pinned: editor.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed'), + collapsed: editor.querySelector('.floating-details')?.classList.contains('collapsed'), + }, { pinned: 'false', collapsed: true }); + }); + + test('exposes sizing only for the active floating presentation', () => { + const { controller, setFloating, setEditorVisible, hide, show } = createHost(); + setFloating(true); + const active = controller.floatingDetails; + hide(); + const hidden = controller.floatingDetails; + show(); + setEditorVisible(false); + const detailsOnly = controller.floatingDetails; + setEditorVisible(true); + const restored = controller.floatingDetails === active; + setFloating(false); + assert.deepStrictEqual({ + active: !!active, hidden, detailsOnly, restored, docked: controller.floatingDetails, + }, { active: true, hidden: undefined, detailsOnly: undefined, restored: true, docked: undefined }); + }); + + test('constrains detail height while reserving editor space and never overflows a small frame', () => { + assert.deepStrictEqual([535, 200, 80, 0].map(available => DockedAuxiliaryBarController.getEffectiveHeight(1000, available)), [415, 120, 80, 0]); + }); +}); diff --git a/src/vs/sessions/test/browser/editorGroupStateInPlace.test.ts b/src/vs/sessions/test/browser/editorGroupStateInPlace.test.ts index 1317fbabfecf..6f8d1349b9d8 100644 --- a/src/vs/sessions/test/browser/editorGroupStateInPlace.test.ts +++ b/src/vs/sessions/test/browser/editorGroupStateInPlace.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { equals } from '../../../base/common/arrays.js'; import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; import { basename } from '../../../base/common/resources.js'; import { URI } from '../../../base/common/uri.js'; @@ -71,7 +72,12 @@ suite('Sessions - Apply editor group state in place', () => { const tabRows: string[][] = []; const store = new DisposableStore(); store.add(group.onDidModelChange(() => editorCounts.push(group.count))); - const observer = new MutationObserver(() => tabRows.push(group.editors.map(editor => basename(editor.resource!)))); + const observer = new MutationObserver(() => { + const row = group.editors.map(editor => basename(editor.resource!)); + if (!equals(tabRows.at(-1), row)) { + tabRows.push(row); + } + }); observer.observe(part.element, { subtree: true, childList: true, attributes: true }); store.add(toDisposable(() => observer.disconnect())); return { diff --git a/src/vs/sessions/test/browser/editorPart.test.ts b/src/vs/sessions/test/browser/editorPart.test.ts index fee409598569..58710a341928 100644 --- a/src/vs/sessions/test/browser/editorPart.test.ts +++ b/src/vs/sessions/test/browser/editorPart.test.ts @@ -12,6 +12,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/comm // eslint-disable-next-line local/code-import-patterns import { createBrowserWelcome } from '../../../workbench/contrib/browserView/browser/browserWelcome.js'; import { renderSessionsEmptyState } from '../../../workbench/browser/parts/sessions/sessionsEmptyState.js'; +import { AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS } from '../../../workbench/browser/parts/sessions/agentsPartCard.js'; import '../../browser/parts/media/editorPart.css'; import '../../browser/media/workbench.css'; import '../../browser/media/style.css'; @@ -149,7 +150,9 @@ suite('Sessions - EditorPart', () => { test('connected detail tabs keep rounded corners while sharing the single card frame', () => { const workbench = appendElement(mainWindow.document.body, 'monaco-workbench agent-sessions-workbench modern-ui-tabs modern-ui-connected-editor-tabs dock-detail-panel'); + workbench.classList.add(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS); for (const [name, value] of Object.entries({ + '--vscode-agents-layout-floatingPanelGap': '4px', '--vscode-spacing-size20': '2px', '--vscode-spacing-size40': '4px', '--vscode-spacing-size60': '6px', diff --git a/src/vs/sessions/test/browser/floatingAuxiliaryBarController.test.ts b/src/vs/sessions/test/browser/floatingAuxiliaryBarController.test.ts new file mode 100644 index 000000000000..9dce4ade2a23 --- /dev/null +++ b/src/vs/sessions/test/browser/floatingAuxiliaryBarController.test.ts @@ -0,0 +1,1616 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import { $, append, getActiveElement } from '../../../base/browser/dom.js'; +import { mainWindow } from '../../../base/browser/window.js'; +import { Emitter } from '../../../base/common/event.js'; +import { timeout } from '../../../base/common/async.js'; +import { Codicon } from '../../../base/common/codicons.js'; +import { MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { FloatingAuxiliaryBarController } from '../../browser/floatingAuxiliaryBarController.js'; +import { DockedAuxiliaryBarController } from '../../browser/dockedAuxiliaryBarController.js'; +import { upcastPartial } from '../../../base/test/common/mock.js'; +import { Part } from '../../../workbench/browser/part.js'; +import { AbstractPaneCompositePart } from '../../../workbench/browser/parts/paneCompositePart.js'; +import { DesktopAuxiliaryBarPart } from '../../browser/parts/desktopAuxiliaryBarPart.js'; +import { PaneComposite } from '../../../workbench/browser/panecomposite.js'; +import { ViewPane } from '../../../workbench/browser/parts/views/viewPane.js'; +import { ViewPaneContainer } from '../../../workbench/browser/parts/views/viewPaneContainer.js'; +import { IView, ViewContainerLocation } from '../../../workbench/common/views.js'; +import { ViewsService } from '../../../workbench/services/views/browser/viewsService.js'; +import { IAccessibilityService } from '../../../platform/accessibility/common/accessibility.js'; +import { NullHoverService } from '../../../platform/hover/test/browser/nullHoverService.js'; +import { getIconRegistry } from '../../../platform/theme/common/iconRegistry.js'; +import { runWithFakedTimers } from '../../../base/test/common/virtualScheduling/index.js'; +import '../../browser/media/workbench.css'; +import '../../../base/browser/ui/scrollbar/media/scrollbars.css'; +import '../../../workbench/contrib/sessions/browser/parts/media/sessionActivityBar.css'; + +suite('Sessions - Floating Details', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createHost(pinned = true, contentHeight: number | undefined = undefined, relayoutOnWidthChange = false) { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.dock-detail-panel')); + store.add(toDisposable(() => root.remove())); + Object.assign(root.style, { position: 'fixed', top: '0', left: '0', width: '800px', height: '600px' }); + root.style.setProperty('--vscode-spacing-size80', '8px'); + root.style.setProperty('--vscode-spacing-size240', '24px'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-fontWeight-semiBold', '600'); + const editor = append(root, $('.part.editor', { tabIndex: 0 })); + Object.assign(editor.style, { position: 'relative', width: '800px', height: '600px', border: '0', boxSizing: 'border-box' }); + const part = append(editor, $('.part.auxiliarybar', { id: 'floating-details-test-body' })); + const tree = append(part, $('div', { role: 'tree', tabIndex: 0 })); + let width = 800; + let height = 600; + let requestedWidth = 300; + let requestedHeight = 400; + let collapses = 0; + let title = 'Files'; + let changesViewActive = false; + const titleChanges = store.add(new Emitter()); + const motionChanges = store.add(new Emitter()); + const contentChanges = store.add(new Emitter()); + let sizeToContent = false; + let reducedMotion = false; + const accessibilityService = upcastPartial({ + isMotionReduced: () => reducedMotion, + onDidChangeReducedMotion: motionChanges.event, + }); + const layouts: { width: number; height: number }[] = []; + editor.getBoundingClientRect = () => new DOMRect(0, 0, width, height); + const auxiliaryBarPart = { + getContainer: () => part, + layout: (width: number, height: number) => { layouts.push({ width, height }); }, + }; + const host = { + getTitle: () => title, + getIcon: () => title === 'Changes' ? Codicon.diff : Codicon.files, + isChangesViewActive: () => changesViewActive, + onDidChangeTitle: titleChanges.event, + getWidth: () => requestedWidth, + setWidth: (value: number) => { + requestedWidth = value; + if (relayoutOnWidthChange) { + controller.layout(33); + } + }, + getHeight: () => requestedHeight, + setHeight: (value: number) => { requestedHeight = value; }, + getContentHeight: () => contentHeight, + onDidChangeContentHeight: contentChanges.event, + setSizeToContent: (value: boolean) => { sizeToContent = value; }, + focusEditor: () => { collapses++; editor.focus(); }, + }; + const controller = store.add(new FloatingAuxiliaryBarController(editor, auxiliaryBarPart, host, accessibilityService, NullHoverService)); + controller.setPinned(pinned); + return { + editor, part, tree, controller, layouts, host, auxiliaryBarPart, accessibilityService, + setContentHeight: (value: number | undefined) => { contentHeight = value; contentChanges.fire(); }, + isSizeToContent: () => sizeToContent, + setReducedMotion: (value: boolean) => { reducedMotion = value; motionChanges.fire(); }, + setTitle: (value: string) => { title = value; titleChanges.fire(); }, + resize: (nextWidth: number, nextHeight: number) => { + width = nextWidth; + height = nextHeight; + Object.assign(editor.style, { width: `${width}px`, height: `${height}px` }); + }, + setChangesViewActive: (value: boolean) => { changesViewActive = value; titleChanges.fire(); }, + snapshot: () => { + const overlay = editor.querySelector('.floating-details')!; + return { + width: overlay.style.width, height: overlay.style.height, top: overlay.style.top, + requestedWidth, requestedHeight, collapses, + layout: layouts.at(-1), + }; + }, + }; + } + + function drag(handle: HTMLElement, deltaX: number, deltaY: number): void { + const bounds = handle.getBoundingClientRect(); + const pointer = { pointerId: 1, button: 0, buttons: 1, bubbles: true, clientX: bounds.x + bounds.width / 2, clientY: bounds.y + bounds.height / 2 }; + handle.dispatchEvent(new PointerEvent('pointerdown', pointer)); + handle.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: pointer.clientX + deltaX, clientY: pointer.clientY + deltaY })); + handle.dispatchEvent(new PointerEvent('pointerup', { ...pointer, buttons: 0, clientX: pointer.clientX + deltaX, clientY: pointer.clientY + deltaY })); + } + + test('layout size requests resize both floating dimensions with a synchronously relayouting width host', () => { + const { controller, snapshot } = createHost(true, undefined, true); + controller.layout(33); + const before = controller.getSize(); + controller.setSize({ width: 360, height: 460 }); + const after = controller.getSize(); + assert.deepStrictEqual({ + before: [before.width, before.height], after: [after.width, after.height], + requested: [snapshot().requestedWidth, snapshot().requestedHeight], rendered: [snapshot().width, snapshot().height], + }, { before: [300, 400], after: [360, 460], requested: [360, 460], rendered: ['360px', '460px'] }); + }); + + test('layout size requests honor short content without clobbering the saved limit and preserve compact presentation', async () => { + const { controller, snapshot, setContentHeight, editor } = createHost(true, 44, true); + controller.layout(33); + const short = controller.getSize(); + controller.setSize({ width: short.width + 60, height: short.height + 60 }); + const fitted = { height: snapshot().height, limit: snapshot().requestedHeight, width: snapshot().requestedWidth }; + setContentHeight(1000); + await timeout(0); + controller.setPinned(false); + controller.setSize({ width: 320, height: 420 }); + const compact = { collapsed: editor.querySelector('.floating-details')!.classList.contains('collapsed'), height: snapshot().height }; + controller.setPinned(true); + assert.deepStrictEqual({ + short: [short.width, short.height], fitted, compact, + expanded: [controller.getSize().width, controller.getSize().height], limit: snapshot().requestedHeight, + }, { + short: [300, 78], fitted: { height: '78px', limit: 400, width: 360 }, + compact: { collapsed: true, height: '34px' }, expanded: [320, 420], limit: 420, + }); + }); + + test('fits short lists without changing the saved height limit and grows or shrinks with content', async () => { + const { controller, setContentHeight, snapshot, isSizeToContent } = createHost(true, 44); + controller.layout(33); + const short = snapshot(); + setContentHeight(1000); + await timeout(0); + const large = snapshot(); + setContentHeight(22); + await timeout(0); + const shrunk = snapshot(); + setContentHeight(undefined); + await timeout(0); + assert.deepStrictEqual({ + short: [short.height, short.layout?.height, short.requestedHeight], + large: [large.height, large.layout?.height, large.requestedHeight], + shrunk: [shrunk.height, shrunk.layout?.height, shrunk.requestedHeight], + unknown: [snapshot().height, snapshot().requestedHeight], sizing: isSizeToContent(), + }, { + short: ['78px', 44, 400], large: ['400px', 366, 400], shrunk: ['56px', 22, 400], + unknown: ['400px', 400], sizing: true, + }); + }); + + test('content fitting preserves the height limit through width resizing, bounds, and reset', async () => { + const { editor, controller, host, snapshot, setContentHeight, resize } = createHost(true, 44); + host.setHeight(250); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const sash = widget.querySelector('.monaco-sash.vertical:not(.disabled)')!; + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: 500, clientY: 200, bubbles: true })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 460, clientY: 200 })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: 460, clientY: 200 })); + const resized = snapshot(); + const height = widget.querySelector('.floating-details-resize-height')!; + height.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', keyCode: 40, bubbles: true })); + const unchanged = snapshot().requestedHeight; + height.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', keyCode: 36, bubbles: true })); + const reset = snapshot(); + host.setHeight(200); + widget.querySelector('.monaco-sash.horizontal:not(.disabled)')!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const mouseReset = snapshot(); + setContentHeight(1000); + await timeout(0); + resize(800, 140); + controller.layout(33); + const bounded = snapshot(); + resize(800, 600); + controller.layout(33); + assert.deepStrictEqual({ + resized: [resized.requestedWidth, resized.requestedHeight, resized.height], unchanged, + reset: [reset.requestedHeight, reset.height], mouseReset: [mouseReset.requestedHeight, mouseReset.height], + bounded: [bounded.height, bounded.requestedHeight], + restored: [snapshot().height, snapshot().requestedHeight], + }, { + resized: [340, 250, '78px'], unchanged: 250, reset: [400, '78px'], mouseReset: [400, '78px'], + bounded: ['91px', 400], restored: ['400px', 400], + }); + }); + + test('a width-only sash drag preserves the saved height when content grows between mousemoves', async () => { + const { editor, controller, host, snapshot, setContentHeight } = createHost(true, 44, true); + host.setHeight(250); + controller.layout(33); + const sash = editor.querySelector('.floating-details .monaco-sash.vertical:not(.disabled)')!; + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: 500, clientY: 200, bubbles: true })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 480, clientY: 200 })); + setContentHeight(1000); + await timeout(0); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 460, clientY: 200 })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 440, clientY: 200 })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: 440, clientY: 200 })); + await timeout(0); + assert.deepStrictEqual({ + width: snapshot().requestedWidth, height: snapshot().requestedHeight, rendered: snapshot().height, + }, { width: 360, height: 250, rendered: '250px' }); + }); + + test('content notifications do not expand a collapsed widget or alter its pin state', async () => { + const { editor, controller, setContentHeight, snapshot, isSizeToContent } = createHost(false, 44); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + setContentHeight(88); + await timeout(0); + const compact = snapshot().height; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const preview = snapshot().height; + controller.setPinned(true); + setContentHeight(22); + await timeout(0); + const pinned = { height: snapshot().height, pressed: widget.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed') }; + controller.hide(); + setContentHeight(1000); + await timeout(0); + assert.deepStrictEqual({ compact, preview, pinned, sizing: isSizeToContent(), hidden: widget.style.display }, { + compact: '34px', preview: '122px', pinned: { height: '56px', pressed: 'true' }, sizing: false, hidden: 'none', + }); + }); + + test('drags the compact widget in both axes without pinning or changing expanded dimensions', () => { + const { editor, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + const before = widget.getBoundingClientRect(); + const handle = grip.getBoundingClientRect(); + widget.dispatchEvent(new MouseEvent('mouseenter', { clientX: handle.x + handle.width / 2, clientY: handle.y + handle.height / 2 })); + drag(grip, -100, 80); + const after = widget.getBoundingClientRect(); + assert.deepStrictEqual({ + movement: [after.x - before.x, after.y - before.y], + collapsed: widget.classList.contains('collapsed'), + pinned: widget.querySelector('.action-label')?.getAttribute('aria-pressed'), + dragging: widget.classList.contains('dragging'), + preferences: [snapshot().requestedWidth, snapshot().requestedHeight], + }, { movement: [-100, 80], collapsed: true, pinned: 'false', dragging: false, preferences: [300, 400] }); + }); + + test('keeps the grip stationary when expanding upward and rightward from the bottom-left corner', () => { + const { editor, part, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + drag(grip, -2000, 2000); + const compact = widget.getBoundingClientRect(); + const headerTop = grip.getBoundingClientRect().top; + controller.setPinned(true); + const expanded = widget.getBoundingClientRect(); + const header = grip.getBoundingClientRect(); + const content = part.getBoundingClientRect(); + const widthHandle = widget.querySelector('.floating-details-resize-width')!; + const heightHandle = widget.querySelector('.floating-details-resize-height')!; + assert.deepStrictEqual({ + compact: [compact.left, compact.bottom], + expanded: [expanded.left, expanded.bottom, expanded.width, expanded.height], + headerStayed: header.top === headerTop, + contentAboveHeader: content.bottom <= header.top, + edges: [mainWindow.getComputedStyle(widthHandle).right, mainWindow.getComputedStyle(heightHandle).top], + sashes: [...widget.querySelectorAll('.monaco-sash:not(.disabled)')].map(sash => sash.classList.contains('vertical') ? 'vertical' : 'horizontal').sort(), + }, { + compact: [8, 592], expanded: [8, 592, 300, 400], headerStayed: true, contentAboveHeader: true, + edges: ['0px', '0px'], sashes: ['horizontal', 'vertical'], + }); + }); + + test('dragging uses client coordinates without accumulating the editor frame border', () => { + const { editor, controller } = createHost(false); + Object.assign(editor.style, { border: '1px solid black', boxSizing: 'border-box' }); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const before = widget.getBoundingClientRect(); + drag(widget.querySelector('.floating-details-drag-handle')!, -60, 80); + const after = widget.getBoundingClientRect(); + assert.deepStrictEqual([after.left - before.left, after.top - before.top], [-60, 80]); + }); + + test('dragging an expanded pinned panel preserves its state, dimensions, and position through hide and show', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + drag(widget.querySelector('.floating-details-drag-handle')!, -100, 100); + widget.dispatchEvent(new MouseEvent('mouseleave')); + controller.onDidOpenItem(); + controller.hide(); + controller.layout(33); + assert.deepStrictEqual({ + position: [widget.style.right, widget.style.top], + pinned: widget.querySelector('.action-label')?.getAttribute('aria-pressed'), + collapsed: widget.classList.contains('collapsed'), + dimensions: [snapshot().requestedWidth, snapshot().requestedHeight], + }, { position: ['108px', '141px'], pinned: 'true', collapsed: false, dimensions: [300, 400] }); + }); + + test('the drag grip supports keyboard movement, larger steps, reset, and contextual labels without expanding', () => { + const { editor, controller, setTitle } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + grip.focus(); + const press = (key: string, keyCode: number, shiftKey = false) => grip.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, shiftKey, bubbles: true, cancelable: true })); + press('ArrowLeft', 37); + press('ArrowDown', 40, true); + const moved = [widget.style.right, widget.style.top]; + press('Home', 36); + const reset = [widget.style.right, widget.style.top]; + press('ArrowLeft', 37, true); + grip.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + setTitle('Changes'); + assert.deepStrictEqual({ + moved, reset, doubleClickReset: [widget.style.right, widget.style.top], + collapsed: widget.classList.contains('collapsed'), + role: grip.getAttribute('role'), tabIndex: grip.tabIndex, label: grip.getAttribute('aria-label'), + decorative: grip.querySelector('span')?.getAttribute('aria-hidden'), + focused: getActiveElement() === grip, + }, { + moved: ['18px', '91px'], reset: ['8px', '41px'], doubleClickReset: ['8px', '41px'], + collapsed: true, role: 'button', tabIndex: 0, label: 'Move Changes. Use Arrow keys to move, Shift for larger steps, or Home to reset.', + decorative: 'true', focused: true, + }); + }); + + test('keeps dragged positions within the editor when resized and restores the preferred position afterward', () => { + const { editor, controller, resize, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + drag(widget.querySelector('.floating-details-drag-handle')!, -100, 120); + const original = widget.getBoundingClientRect(); + resize(180, 140); + controller.layout(33); + const small = widget.getBoundingClientRect(); + resize(800, 600); + controller.layout(33); + const restored = widget.getBoundingClientRect(); + assert.deepStrictEqual({ + contained: small.left >= 8 && small.right <= 172 && small.top >= 41 && small.bottom <= 132, + restored: [restored.left, restored.top], original: [original.left, original.top], + preferences: [snapshot().requestedWidth, snapshot().requestedHeight], + }, { contained: true, restored: [original.left, original.top], original: [original.left, original.top], preferences: [300, 400] }); + }); + + test('hiding or disposing during a drag removes pointer monitoring and ignores late pointer events', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + const pointer = { pointerId: 1, button: 0, buttons: 1, bubbles: true }; + grip.dispatchEvent(new PointerEvent('pointerdown', pointer)); + controller.hide(); + const position = widget.style.cssText; + mainWindow.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: 100, clientY: 100 })); + mainWindow.dispatchEvent(new PointerEvent('pointerup', { ...pointer, buttons: 0 })); + const hidden = { unchanged: widget.style.cssText === position, dragging: widget.classList.contains('dragging') }; + controller.layout(33); + grip.dispatchEvent(new PointerEvent('pointerdown', pointer)); + controller.dispose(); + mainWindow.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: 200, clientY: 200 })); + assert.deepStrictEqual({ hidden, removed: !editor.contains(widget), dragging: widget.classList.contains('dragging') }, { + hidden: { unchanged: true, dragging: false }, removed: true, dragging: false, + }); + }); + + test('canceling a pointer drag releases monitoring and allows hover previews again', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + const bounds = grip.getBoundingClientRect(); + const pointer = { pointerId: 1, button: 0, buttons: 1, bubbles: true, clientX: bounds.x + bounds.width / 2, clientY: bounds.y + bounds.height / 2 }; + grip.dispatchEvent(new PointerEvent('pointerdown', pointer)); + grip.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: pointer.clientX - 50 })); + grip.dispatchEvent(new PointerEvent('pointercancel', { ...pointer, buttons: 0 })); + const position = widget.style.cssText; + grip.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: pointer.clientX - 100 })); + const released = { dragging: widget.classList.contains('dragging'), unchanged: widget.style.cssText === position }; + widget.dispatchEvent(new MouseEvent('mouseenter')); + assert.deepStrictEqual({ released, preview: !widget.classList.contains('collapsed') }, { + released: { dragging: false, unchanged: true }, preview: true, + }); + }); + + test('a preview cannot time out during dragging and uses the exit grace after releasing outside', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const grip = widget.querySelector('.floating-details-drag-handle')!; + const pointer = { pointerId: 1, button: 0, buttons: 1, bubbles: true, clientX: 790, clientY: 50 }; + grip.dispatchEvent(new PointerEvent('pointerdown', pointer)); + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(300); + const during = widget.classList.contains('collapsed'); + grip.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: 1000, clientY: 50 })); + grip.dispatchEvent(new PointerEvent('pointerup', { ...pointer, buttons: 0 })); + await timeout(249); + const grace = widget.classList.contains('collapsed'); + await timeout(1); + assert.deepStrictEqual({ during, grace, collapsed: widget.classList.contains('collapsed') }, { during: false, grace: false, collapsed: true }); + })); + + test('Escape cancels a compact-widget drag and restores editor focus', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + grip.focus(); + const pointer = { pointerId: 1, button: 0, buttons: 1, bubbles: true }; + grip.dispatchEvent(new PointerEvent('pointerdown', pointer)); + grip.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + const position = widget.style.cssText; + mainWindow.dispatchEvent(new PointerEvent('pointermove', { ...pointer, clientX: 100, clientY: 100 })); + assert.deepStrictEqual({ + unchanged: widget.style.cssText === position, dragging: widget.classList.contains('dragging'), + collapsed: widget.classList.contains('collapsed'), focused: getActiveElement() === editor, + }, { unchanged: true, dragging: false, collapsed: true, focused: true }); + }); + + test('keyboard resizing grows away from the anchored bottom and left edges', () => { + const { editor, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + drag(widget.querySelector('.floating-details-drag-handle')!, -2000, 2000); + controller.setPinned(true); + widget.querySelector('.floating-details-resize-width')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', keyCode: 39, bubbles: true })); + widget.querySelector('.floating-details-resize-height')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', keyCode: 38, bubbles: true })); + const bounds = widget.getBoundingClientRect(); + assert.deepStrictEqual({ dimensions: [snapshot().requestedWidth, snapshot().requestedHeight], edges: [bounds.left, bounds.bottom] }, { + dimensions: [310, 410], edges: [8, 592], + }); + }); + + for (const corner of [{ x: -2000, y: 2000 }, { x: 2000, y: -2000 }]) { + test(`keeps content and the header fixed during motion from corner ${corner.x},${corner.y}`, async () => { + const { editor, part, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const grip = widget.querySelector('.floating-details-drag-handle')!; + drag(grip, corner.x, corner.y); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + const header = grip.getBoundingClientRect().top; + controller.setPinned(true); + const animation = widget.getAnimations()[0]; + assert.ok(animation); + const before = part.getBoundingClientRect(); + animation.pause(); + animation.currentTime = 75; + const middle = part.getBoundingClientRect(); + assert.deepStrictEqual({ + content: [middle.left, middle.top], expectedContent: [before.left, before.top], + header: grip.getBoundingClientRect().top, expectedHeader: header, + }, { content: [before.left, before.top], expectedContent: [before.left, before.top], header, expectedHeader: header }); + const finished = new Promise(resolve => animation.addEventListener('finish', resolve, { once: true })); + animation.finish(); + await finished; + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing); + closing.pause(); + closing.currentTime = Number(closing.effect!.getTiming().duration) / 2; + const closingContent = part.getBoundingClientRect(); + assert.deepStrictEqual({ + content: [closingContent.left, closingContent.top], + header: grip.getBoundingClientRect().top, inert: part.inert, + }, { content: [before.left, before.top], header, inert: true }); + }); + } + + for (const theme of ['vs-dark', 'vs', 'hc-black', 'hc-light']) { + test(`uses the chat action widget's surface, border, shadow, and icon colors in ${theme}`, () => { + const { editor, part, controller } = createHost(false); + const root = editor.closest('.monaco-workbench')!; + root.classList.add(theme); + root.style.setProperty('--vscode-editorWidget-background', '#203040'); + root.style.setProperty('--vscode-editorWidget-border', '#506070'); + root.style.setProperty('--vscode-icon-foreground', '#8090a0'); + root.style.setProperty('--vscode-agentsDetail-background', '#aabbcc'); + root.style.setProperty('--vscode-shadow-md', '0 2px 4px #102030'); + const reference = append(root, $('.menu-activity-bar.session-activity-bar.floating')); + part.style.backgroundColor = 'var(--vscode-agentsDetail-background)'; + controller.layout(33); + const surface = mainWindow.getComputedStyle(editor.querySelector('.floating-details-surface')!); + const chat = mainWindow.getComputedStyle(reference); + assert.deepStrictEqual({ + background: surface.backgroundColor, border: surface.borderTopColor, + shadow: surface.boxShadow, + icon: mainWindow.getComputedStyle(editor.querySelector('.floating-details-icon')!).color, + body: mainWindow.getComputedStyle(part).backgroundColor, + }, { + background: chat.backgroundColor, border: chat.borderTopColor, + shadow: theme.startsWith('hc-') ? 'none' : chat.boxShadow, + icon: 'rgb(128, 144, 160)', body: chat.backgroundColor, + }); + }); + } + + test('starts as a compact floating widget without changing expanded size preferences', () => { + const { editor, part, controller, snapshot } = createHost(false); + Object.assign(editor.style, { position: 'relative', width: '800px', height: '600px' }); + controller.layout(33); + const control = editor.querySelector('.action-label')!; + const widget = editor.querySelector('.floating-details')!; + assert.deepStrictEqual({ + collapsed: widget.classList.contains('collapsed'), + width: widget.style.width, height: widget.style.height, + label: control.getAttribute('aria-label'), + expanded: control.getAttribute('aria-expanded'), + tabIndex: control.tabIndex, + controls: control.getAttribute('aria-controls'), + body: part.style.display, + resizeHandles: [...widget.querySelectorAll('[role="separator"]')].map(handle => handle.hidden), + sashes: widget.querySelectorAll('.monaco-sash:not(.disabled)').length, + preferences: [snapshot().requestedWidth, snapshot().requestedHeight], + }, { + collapsed: true, width: 'max-content', height: '34px', label: 'Expand Files', + expanded: 'false', tabIndex: 0, controls: 'floating-details-test-body', body: 'none', + resizeHandles: [true, true], sashes: 0, preferences: [300, 400], + }); + }); + + for (const theme of ['vs-dark', 'vs', 'hc-black', 'hc-light']) { + test(`indicates pin state with its glyph and ARIA state without a persistent background in ${theme}`, () => { + const { editor, controller } = createHost(false); + const root = editor.closest('.monaco-workbench')!; + root.classList.add(theme); + root.style.setProperty('--vscode-toolbar-activeBackground', '#abcdef'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const button = widget.querySelector('.floating-details-toggle')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const preview = mainWindow.getComputedStyle(button).backgroundColor; + button.click(); + const pinned = { + background: mainWindow.getComputedStyle(button).backgroundColor, + glyph: !!button.querySelector('.codicon-sessions-floating-details-pinned'), + pressed: button.getAttribute('aria-pressed'), + }; + button.click(); + assert.deepStrictEqual({ + preview, pinned, + unpinned: { + background: mainWindow.getComputedStyle(button).backgroundColor, + glyph: !!button.querySelector('.codicon-sessions-floating-details-keep-expanded'), + pressed: button.getAttribute('aria-pressed'), + }, + }, { + preview: 'rgba(0, 0, 0, 0)', + pinned: { background: 'rgba(0, 0, 0, 0)', glyph: true, pressed: 'true' }, + unpinned: { background: 'rgba(0, 0, 0, 0)', glyph: true, pressed: 'false' }, + }); + }); + } + + test('only exposes the pin toggle while expanded and restores the compact focus target on Escape', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const button = widget.querySelector('.floating-details-toggle')!; + const collapsed = { visible: button.checkVisibility(), tabIndex: widget.tabIndex }; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const preview = { + visible: button.checkVisibility(), tabIndex: widget.tabIndex, + icon: !!button.querySelector('.codicon-sessions-floating-details-keep-expanded'), + label: button.getAttribute('aria-label'), + }; + button.click(); + const expanded = { + visible: button.checkVisibility(), + pinnedIcon: !!button.querySelector('.codicon-sessions-floating-details-pinned'), + pressed: button.getAttribute('aria-pressed'), + }; + button.click(); + const unpinned = { + visible: button.checkVisibility(), pressed: button.getAttribute('aria-pressed'), expanded: button.getAttribute('aria-expanded'), + pinIcon: !!button.querySelector('.codicon-sessions-floating-details-keep-expanded'), + }; + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + assert.deepStrictEqual({ + collapsed, preview, expanded, unpinned, + restored: { visible: button.checkVisibility(), tabIndex: widget.tabIndex }, + iconDefault: getIconRegistry().getIcon('sessions-floating-details-keep-expanded')?.defaults, + pinnedIconDefault: getIconRegistry().getIcon('sessions-floating-details-pinned')?.defaults, + }, { + collapsed: { visible: false, tabIndex: 0 }, + preview: { visible: true, tabIndex: -1, icon: true, label: 'Keep Files Expanded' }, + expanded: { visible: true, pinnedIcon: true, pressed: 'true' }, + unpinned: { visible: true, pressed: 'false', expanded: 'true', pinIcon: true }, + restored: { visible: false, tabIndex: 0 }, iconDefault: Codicon.pin, pinnedIconDefault: Codicon.pinned, + }); + }); + + test('pointer exit waits for a short grace period before returning to the compact widget', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, part, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const control = widget.querySelector('.action-label')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const preview = { label: control.getAttribute('aria-label'), expanded: control.getAttribute('aria-expanded'), body: part.style.display, height: widget.style.height }; + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(249); + const duringGrace = widget.classList.contains('collapsed'); + await timeout(1); + assert.deepStrictEqual({ preview, duringGrace, collapsed: widget.classList.contains('collapsed'), body: part.style.display, preferences: [snapshot().requestedWidth, snapshot().requestedHeight] }, { + preview: { label: 'Keep Files Expanded', expanded: 'true', body: '', height: '400px' }, + duringGrace: false, collapsed: true, body: 'none', preferences: [300, 400], + }); + })); + + test('re-entering or pinning cancels a pending mouse-exit collapse', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(150); + widget.dispatchEvent(new MouseEvent('mouseenter')); + await timeout(500); + const reentered = widget.classList.contains('collapsed'); + widget.dispatchEvent(new MouseEvent('mouseleave')); + controller.setPinned(true); + await timeout(500); + assert.deepStrictEqual({ + reentered, pinned: widget.classList.contains('collapsed'), + label: widget.querySelector('.action-label')?.getAttribute('aria-label'), + }, { reentered: false, pinned: false, label: 'Unpin Files' }); + })); + + test('opening a file collapses a preview but clicking or expanding a folder does not', () => { + const { editor, tree, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + tree.focus(); + tree.dispatchEvent(new MouseEvent('click', { bubbles: true })); + const afterFolderClick = widget.classList.contains('collapsed'); + controller.onDidOpenItem(); + assert.deepStrictEqual({ + afterFolderClick, afterOpen: widget.classList.contains('collapsed'), + focusRestored: getActiveElement() === editor, restores: snapshot().collapses, + }, { afterFolderClick: false, afterOpen: true, focusRestored: true, restores: 1 }); + }); + + for (const phase of ['expanded', 'opening', 'pending dismissal']) { + test(`item selection instantly collapses an unpinned ${phase} preview without any exit animation`, async () => { + const { editor, tree, part, controller, snapshot } = createHost(false); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const opening = widget.getAnimations()[0]; + assert.ok(opening); + if (phase === 'opening') { + opening.pause(); + opening.currentTime = 40; + } else { + const finished = new Promise(resolve => opening.addEventListener('finish', resolve, { once: true })); + opening.finish(); + await finished; + } + tree.focus(); + if (phase === 'pending dismissal') { + widget.dispatchEvent(new MouseEvent('mouseleave')); + } + controller.onDidOpenItem(); + assert.deepStrictEqual({ + collapsed: widget.classList.contains('collapsed'), + height: widget.getBoundingClientRect().height, + animations: widget.getAnimations().length, + animating: widget.classList.contains('animating'), + body: part.style.display, + inert: part.inert, + expanded: widget.querySelector('.floating-details-toggle')?.getAttribute('aria-expanded'), + focusedEditor: getActiveElement() === editor, + preferences: [snapshot().requestedWidth, snapshot().requestedHeight], + sashes: widget.querySelectorAll('.monaco-sash:not(.disabled)').length, + }, { + collapsed: true, height: 34, animations: 0, animating: false, + body: 'none', inert: false, expanded: 'false', focusedEditor: true, + preferences: [300, 400], sashes: 0, + }); + }); + } + + test('item selection preserves pinned motion but instantly collapses after unpinning', () => { + const { editor, part, controller } = createHost(false); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const opening = widget.getAnimations()[0]; + assert.ok(opening); + opening.pause(); + opening.currentTime = 40; + controller.setPinned(true); + controller.onDidOpenItem(); + const pinned = { + sameMotion: widget.getAnimations()[0] === opening, + expanded: !widget.classList.contains('collapsed'), + bodyVisible: part.checkVisibility(), + }; + controller.setPinned(false); + controller.onDidOpenItem(); + assert.deepStrictEqual({ + pinned, collapsed: widget.classList.contains('collapsed'), + animations: widget.getAnimations().length, height: widget.getBoundingClientRect().height, + cancelled: opening.playState, body: part.style.display, + }, { + pinned: { sameMotion: true, expanded: true, bodyVisible: true }, + collapsed: true, animations: 0, height: 34, cancelled: 'idle', body: 'none', + }); + }); + + test('unpinning keeps the hovered view expanded and resumes the exit grace period', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, part, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const control = widget.querySelector('.action-label')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + control.focus(); + control.click(); + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(500); + controller.onDidOpenItem(); + const pinned = { label: control.getAttribute('aria-label'), expanded: control.getAttribute('aria-expanded'), body: part.style.display }; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const bounds = widget.getBoundingClientRect(); + control.click(); + await timeout(500); + const unpinned = { + collapsed: widget.classList.contains('collapsed'), pressed: control.getAttribute('aria-pressed'), + label: control.getAttribute('aria-label'), focused: getActiveElement() === control, + dimensions: [widget.getBoundingClientRect().width, widget.getBoundingClientRect().height], + restores: snapshot().collapses, + }; + editor.focus(); + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(249); + const duringGrace = widget.classList.contains('collapsed'); + await timeout(1); + assert.deepStrictEqual({ pinned, unpinned, duringGrace, collapsed: widget.classList.contains('collapsed'), restores: snapshot().collapses }, { + pinned: { label: 'Unpin Files', expanded: 'true', body: '' }, + unpinned: { collapsed: false, pressed: 'false', label: 'Keep Files Expanded', focused: true, dimensions: [bounds.width, bounds.height], restores: 0 }, + duringGrace: false, collapsed: true, restores: 0, + }); + })); + + test('pointer exit cannot collapse a preview while its tree keeps keyboard focus', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, tree, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + tree.focus(); + tree.dispatchEvent(new FocusEvent('focus')); + widget.dispatchEvent(new MouseEvent('mouseleave')); + await timeout(500); + const focused = { + expanded: !widget.classList.contains('collapsed'), focus: getActiveElement() === tree, + restores: snapshot().collapses, + }; + editor.focus(); + tree.dispatchEvent(new FocusEvent('blur')); + await timeout(0); + assert.deepStrictEqual({ + focused, collapsed: widget.classList.contains('collapsed'), focus: getActiveElement() === editor, + }, { focused: { expanded: true, focus: true, restores: 0 }, collapsed: true, focus: true }); + })); + + test('keyboard focus previews the widget, Enter pins it, and Escape collapses it with editor focus', () => { + const { editor, controller, snapshot } = createHost(false); + controller.layout(33); + const control = editor.querySelector('.action-label')!; + const widget = editor.querySelector('.floating-details')!; + widget.focus(); + // Background Electron windows can defer native focus events. + widget.dispatchEvent(new FocusEvent('focus')); + control.dispatchEvent(new FocusEvent('focus')); + const preview = control.getAttribute('aria-label'); + const focused = getActiveElement() === control; + const focusRestores = snapshot().collapses; + const controlSize = control.getBoundingClientRect(); + control.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + control.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + const pinned = control.getAttribute('aria-label'); + control.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + control.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + const unpinned = { expanded: control.getAttribute('aria-expanded'), pressed: control.getAttribute('aria-pressed'), focused: getActiveElement() === control }; + control.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + assert.deepStrictEqual({ + preview, pinned, unpinned, focused, focusRestores, controlVisible: controlSize.width > 0 && controlSize.height > 0, collapsed: control.getAttribute('aria-expanded'), + focusRestored: getActiveElement() === editor, restores: snapshot().collapses, + }, { preview: 'Keep Files Expanded', pinned: 'Unpin Files', unpinned: { expanded: 'true', pressed: 'false', focused: true }, focused: true, focusRestores: 0, controlVisible: true, collapsed: 'false', focusRestored: true, restores: 1 }); + }); + + test('unpinning preserves tree focus and dismisses the preview only after focus leaves', async () => { + const { editor, tree, controller, snapshot } = createHost(); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + tree.focus(); + tree.dispatchEvent(new FocusEvent('focus')); + controller.setPinned(false); + const unpinned = { + expanded: !widget.classList.contains('collapsed'), focused: getActiveElement() === tree, + pressed: widget.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed'), + }; + editor.focus(); + tree.dispatchEvent(new FocusEvent('blur')); + await timeout(0); + assert.deepStrictEqual({ + unpinned, collapsed: widget.classList.contains('collapsed'), focusedEditor: getActiveElement() === editor, + restores: snapshot().collapses, + }, { unpinned: { expanded: true, focused: true, pressed: 'false' }, collapsed: true, focusedEditor: true, restores: 0 }); + }); + + test('moving keyboard focus from the drag grip to the compact widget reveals and focuses Keep Expanded', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const button = widget.querySelector('.floating-details-toggle')!; + widget.querySelector('.floating-details-drag-handle')!.focus(); + const collapsed = widget.classList.contains('collapsed'); + widget.focus(); + widget.dispatchEvent(new FocusEvent('focus')); + assert.deepStrictEqual({ + collapsed, expanded: !widget.classList.contains('collapsed'), + focused: getActiveElement() === button, visible: button.checkVisibility(), + }, { collapsed: true, expanded: true, focused: true, visible: true }); + }); + + test('focusing the already expanded region does not move focus to its action button', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + widget.focus(); + widget.dispatchEvent(new FocusEvent('focus')); + assert.deepStrictEqual({ expanded: !widget.classList.contains('collapsed'), focused: getActiveElement() === widget }, { + expanded: true, focused: true, + }); + }); + + test('keyboard focus leaving an unpinned preview collapses it without stealing focus', async () => { + const { editor, controller, snapshot } = createHost(false); + controller.layout(33); + const control = editor.querySelector('.action-label')!; + const widget = editor.querySelector('.floating-details')!; + widget.focus(); + widget.dispatchEvent(new FocusEvent('focus')); + editor.focus(); + control.dispatchEvent(new FocusEvent('blur')); + await timeout(0); + assert.deepStrictEqual({ + expanded: control.getAttribute('aria-expanded'), + focusedEditor: getActiveElement() === editor, restores: snapshot().collapses, + }, { expanded: 'false', focusedEditor: true, restores: 0 }); + }); + + test('collapsing and expanding preserves the resizable frame dimensions', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + controller.setPinned(false); + const compactHeight = editor.querySelector('.floating-details')!.style.height; + controller.setPinned(true); + assert.deepStrictEqual({ compactHeight, restored: snapshot() }, { + compactHeight: '34px', + restored: { width: '300px', height: '400px', top: '41px', requestedWidth: 300, requestedHeight: 400, collapses: 0, layout: { width: 298, height: 366 } }, + }); + }); + + test('uses Fluent reveal/dismiss curves and clips stationary content instead of blanking it during collapse', async () => { + const { editor, part, controller, snapshot } = createHost(); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const contentBounds = part.getBoundingClientRect(); + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing?.effect instanceof KeyframeEffect); + const closeFrames = closing.effect.getKeyframes(); + const closingState = { + duration: closing.effect.getTiming().duration, + easing: closing.effect.getTiming().easing, + shrinks: Number.parseFloat(String(closeFrames[0].width)) > Number.parseFloat(String(closeFrames[1].width)), + heights: closeFrames.map(frame => frame.height), + contentAnimations: part.getAnimations().length, + contentVisible: part.checkVisibility(), + contentInert: part.inert, + pointerEvents: mainWindow.getComputedStyle(widget).pointerEvents, + sashes: widget.querySelectorAll('.monaco-sash:not(.disabled)').length, + }; + closing.pause(); + closing.currentTime = 75; + const closingContent = part.getBoundingClientRect(); + const closed = new Promise(resolve => closing.addEventListener('finish', resolve, { once: true })); + closing.finish(); + await closed; + const compact = { + width: widget.style.width, height: widget.style.height, animating: widget.classList.contains('animating'), + contentVisible: part.checkVisibility(), contentInert: part.inert, + }; + controller.setPinned(true); + const opening = widget.getAnimations()[0]; + assert.ok(opening?.effect instanceof KeyframeEffect); + const openFrames = opening.effect.getKeyframes(); + const opened = new Promise(resolve => opening.addEventListener('finish', resolve, { once: true })); + opening.finish(); + await opened; + assert.deepStrictEqual({ + closingState, compact, + stationaryContent: [closingContent.left, closingContent.top, closingContent.width, closingContent.height], + opening: { + duration: opening.effect.getTiming().duration, easing: opening.effect.getTiming().easing, + grows: Number.parseFloat(String(openFrames[0].width)) < Number.parseFloat(String(openFrames[1].width)), heights: openFrames.map(frame => frame.height), + }, + expanded: { width: widget.style.width, height: widget.style.height, animations: widget.getAnimations().length, sashes: widget.querySelectorAll('.monaco-sash:not(.disabled)').length }, + preferences: [snapshot().requestedWidth, snapshot().requestedHeight], + }, { + closingState: { + duration: 150, easing: 'cubic-bezier(0.9, 0.1, 1, 0.2)', shrinks: true, heights: ['400px', '34px'], + contentAnimations: 0, contentVisible: true, contentInert: true, pointerEvents: 'none', sashes: 0, + }, + compact: { width: 'max-content', height: '34px', animating: false, contentVisible: false, contentInert: false }, + stationaryContent: [contentBounds.left, contentBounds.top, contentBounds.width, contentBounds.height], + opening: { duration: 250, easing: 'cubic-bezier(0.1, 0.9, 0.2, 1)', grows: true, heights: ['34px', '400px'] }, + expanded: { width: '300px', height: '400px', animations: 0, sashes: 2 }, + preferences: [300, 400], + }); + }); + + test('gives short content a faster reveal and dismissal without scaling or sliding the tree', async () => { + const { editor, part, controller, host } = createHost(false, 44); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + // The motion is short when neither the width nor the height changes by more than 240px. The compact caption's + // width depends on the browser's font metrics, so the width is set relative to it. + host.setWidth(widget.getBoundingClientRect().width + 200); + controller.setPinned(true); + const opening = widget.getAnimations()[0]; + assert.ok(opening?.effect instanceof KeyframeEffect); + const reveal = { + duration: opening.effect.getTiming().duration, easing: opening.effect.getTiming().easing, + heights: opening.effect.getKeyframes().map(frame => frame.height), + }; + const opened = new Promise(resolve => opening.addEventListener('finish', resolve, { once: true })); + opening.finish(); + await opened; + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing?.effect instanceof KeyframeEffect); + assert.deepStrictEqual({ + reveal, dismiss: { duration: closing.effect.getTiming().duration, easing: closing.effect.getTiming().easing }, + tree: { transform: mainWindow.getComputedStyle(part).transform, animations: part.getAnimations().length }, + }, { + reveal: { duration: 200, easing: 'cubic-bezier(0.1, 0.9, 0.2, 1)', heights: ['34px', '78px'] }, + dismiss: { duration: 100, easing: 'cubic-bezier(0.9, 0.1, 1, 0.2)' }, + tree: { transform: 'none', animations: 0 }, + }); + }); + + test('measures a changed compact caption before choosing its motion distance and duration', () => { + const { editor, controller, host, setTitle } = createHost(false, 44); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + setTitle('A Much Longer View Name'); + const compact = widget.getBoundingClientRect(); + host.setWidth(compact.width + 230); + controller.setPinned(true); + const opening = widget.getAnimations()[0]; + assert.ok(opening?.effect instanceof KeyframeEffect); + assert.deepStrictEqual({ + duration: opening.effect.getTiming().duration, + continuous: Math.abs(Number.parseFloat(String(opening.effect.getKeyframes()[0].width)) - compact.width) < 0.1, + }, { duration: 200, continuous: true }); + }); + + test('rapid hover reversal starts from the current size and pinning does not restart the motion', () => { + const { editor, part, controller } = createHost(); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing); + closing.pause(); + closing.currentTime = 75; + const partial = widget.getBoundingClientRect(); + widget.dispatchEvent(new MouseEvent('mouseenter')); + const opening = widget.getAnimations()[0]; + assert.ok(opening?.effect instanceof KeyframeEffect); + const frames = opening.effect.getKeyframes(); + controller.setPinned(true); + const sameAfterPin = widget.getAnimations()[0] === opening; + controller.setPinned(false); + assert.deepStrictEqual({ + cancelled: closing.playState, + continuesWidth: Math.abs(Number.parseFloat(String(frames[0].width)) - partial.width) < 0.1, + continuesHeight: Math.abs(Number.parseFloat(String(frames[0].height)) - partial.height) < 0.1, + target: [frames[1].width, frames[1].height], + duration: opening.effect.getTiming().duration, + contentInteractive: !part.inert && part.checkVisibility(), + sameAfterPin, sameAfterUnpin: widget.getAnimations()[0] === opening, + }, { + cancelled: 'idle', continuesWidth: true, continuesHeight: true, target: ['300px', '400px'], + duration: Math.max(50, Math.round(250 * Math.max(Math.abs(300 - partial.width), Math.abs(400 - partial.height)) / 366)), + contentInteractive: true, sameAfterPin: true, sameAfterUnpin: true, + }); + }); + + test('reverses a partial reveal with a shorter dismissal and keeps the content clipped and inert', () => { + const { editor, part, controller } = createHost(false); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + controller.setPinned(true); + const opening = widget.getAnimations()[0]; + assert.ok(opening); + opening.pause(); + opening.currentTime = 25; + const partial = widget.getBoundingClientRect(); + const content = part.getBoundingClientRect(); + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing?.effect instanceof KeyframeEffect); + const frames = closing.effect.getKeyframes(); + closing.pause(); + closing.currentTime = 25; + const clippedContent = part.getBoundingClientRect(); + assert.deepStrictEqual({ + cancelled: opening.playState, + continuous: Math.abs(Number.parseFloat(String(frames[0].width)) - partial.width) < 0.1 && Math.abs(Number.parseFloat(String(frames[0].height)) - partial.height) < 0.1, + faster: Number(closing.effect.getTiming().duration) < 150, + content: [clippedContent.left, clippedContent.top, clippedContent.width, clippedContent.height], + inert: part.inert, + }, { + cancelled: 'idle', continuous: true, faster: true, + content: [content.left, content.top, content.width, content.height], inert: true, + }); + }); + + test('retargets an active reveal smoothly when intrinsic content height arrives', async () => { + const { editor, controller, setContentHeight, snapshot } = createHost(false); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + controller.setPinned(true); + const opening = widget.getAnimations()[0]; + assert.ok(opening); + opening.pause(); + opening.currentTime = 60; + const partial = widget.getBoundingClientRect(); + setContentHeight(44); + await timeout(0); + const retargeted = widget.getAnimations()[0]; + assert.ok(retargeted?.effect instanceof KeyframeEffect); + const frames = retargeted.effect.getKeyframes(); + const retarget = { + cancelled: opening.playState, + continuous: Math.abs(Number.parseFloat(String(frames[0].width)) - partial.width) < 0.1 && Math.abs(Number.parseFloat(String(frames[0].height)) - partial.height) < 0.1, + target: [frames[1].width, frames[1].height], + }; + const finished = new Promise(resolve => retargeted.addEventListener('finish', resolve, { once: true })); + retargeted.finish(); + await finished; + assert.deepStrictEqual({ retarget, height: widget.style.height, preference: snapshot().requestedHeight }, { + retarget: { cancelled: 'idle', continuous: true, target: ['300px', '78px'] }, height: '78px', preference: 400, + }); + }); + + for (const cancel of ['reduced motion', 'layout', 'hide', 'dispose']) { + test(`cleans up clipped exit content immediately on ${cancel}`, () => { + const { editor, part, controller, setReducedMotion } = createHost(); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + controller.setPinned(false); + const closing = widget.getAnimations()[0]; + assert.ok(closing); + if (cancel === 'reduced motion') { + setReducedMotion(true); + } else if (cancel === 'layout') { + controller.layout(33); + } else if (cancel === 'hide') { + controller.hide(); + } else { + controller.dispose(); + } + assert.deepStrictEqual({ + animation: closing.playState, animating: widget.classList.contains('animating'), + content: part.style.display, inert: part.inert, + }, { animation: 'idle', animating: false, content: 'none', inert: false }); + }); + } + + test('reduced motion skips transitions and cancels an in-progress transition immediately', () => { + const { editor, controller, setReducedMotion } = createHost(); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + setReducedMotion(true); + controller.setPinned(false); + const reduced = { width: widget.style.width, height: widget.style.height, animations: widget.getAnimations().length }; + setReducedMotion(false); + controller.setPinned(true); + const animation = widget.getAnimations()[0]; + assert.ok(animation); + setReducedMotion(true); + assert.deepStrictEqual({ + reduced, + cancelled: animation.playState, + expanded: { width: widget.style.width, height: widget.style.height, animations: widget.getAnimations().length, animating: widget.classList.contains('animating') }, + }, { + reduced: { width: 'max-content', height: '34px', animations: 0 }, + cancelled: 'idle', + expanded: { width: '300px', height: '400px', animations: 0, animating: false }, + }); + }); + + test('hiding the surface dismisses previews but preserves explicitly pinned state', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + controller.hide(); + controller.layout(33); + const restoredPreview = widget.classList.contains('collapsed'); + controller.setPinned(true); + controller.hide(); + controller.layout(33); + assert.deepStrictEqual({ restoredPreview, restoredPinned: widget.classList.contains('collapsed') }, { + restoredPreview: true, restoredPinned: false, + }); + }); + + test('view focus commands reveal floating content before the tree is focused', async () => { + const calls: string[] = []; + const open = sinon.stub(AbstractPaneCompositePart.prototype, 'openPaneComposite').callsFake(async (_id, focus) => { + calls.push(`open:${focus}`); + return undefined; + }); + store.add(toDisposable(() => open.restore())); + const host = { beforeFocus: () => calls.push('reveal') }; + const openPane = Reflect.get(DesktopAuxiliaryBarPart.prototype, 'openPaneComposite') as (this: typeof host, id: string, focus: boolean) => ReturnType; + await openPane.call(host, 'files', false); + await openPane.call(host, 'files', true); + assert.deepStrictEqual(calls, ['open:false', 'reveal', 'open:true']); + }); + + test('opening an individual view reveals and pins floating details before focusing its tree', async () => { + const { editor, tree, part, controller } = createHost(false); + controller.layout(33); + const calls: string[] = []; + const view = upcastPartial({ + id: 'files', + setExpanded: () => false, + focus: () => { + calls.push(part.style.display === 'none' ? 'focus:hidden' : 'focus:visible'); + tree.focus(); + }, + }); + const container = upcastPartial({ getView: () => view }); + Object.setPrototypeOf(container, ViewPaneContainer.prototype); + const composite = upcastPartial({}); + Object.setPrototypeOf(composite, PaneComposite.prototype); + Reflect.set(composite, 'viewPaneContainer', container); + let activeComposite: PaneComposite | undefined = composite; + const auxiliaryBar = upcastPartial({ + getActivePaneComposite: () => activeComposite, + beforeFocus: () => { calls.push('reveal'); controller.setPinned(true); }, + }); + Object.setPrototypeOf(auxiliaryBar, DesktopAuxiliaryBarPart.prototype); + Reflect.set(auxiliaryBar, 'contentHeightListener', store.add(new MutableDisposable())); + Reflect.set(auxiliaryBar, 'focusPreparation', store.add(new MutableDisposable())); + Reflect.set(auxiliaryBar, '_onDidChangeContentHeight', store.add(new Emitter())); + auxiliaryBar.setSizeToContent(false); + const open = sinon.stub(AbstractPaneCompositePart.prototype, 'openPaneComposite').callsFake(async (_id, focus) => { + calls.push(`open:${focus}`); + return composite; + }); + store.add(toDisposable(() => open.restore())); + const viewsHost = { + viewDescriptorService: { + getViewContainerByViewId: () => ({ id: 'files-container' }), + getViewContainerModel: () => ({ activeViewDescriptors: [{ id: 'files' }] }), + getViewContainerLocation: () => ViewContainerLocation.AuxiliaryBar, + }, + paneCompositeService: { + getPaneComposite: () => ({ id: 'files-container', name: 'Files' }), + openPaneComposite: (id: string, _location: ViewContainerLocation, focus?: boolean) => auxiliaryBar.openPaneComposite(id, focus), + }, + }; + Object.setPrototypeOf(viewsHost, ViewsService.prototype); + const openView = Reflect.get(ViewsService.prototype, 'openView') as (this: typeof viewsHost, id: string, focus: boolean) => Promise; + await openView.call(viewsHost, 'files', false); + const nonFocusingOpen = editor.querySelector('.floating-details')!.classList.contains('collapsed'); + const opened = await openView.call(viewsHost, 'files', true); + assert.deepStrictEqual({ + nonFocusingOpen, opened: opened === view, focused: getActiveElement() === tree, + pinned: editor.querySelector('.floating-details-toggle')?.getAttribute('aria-pressed'), calls, + }, { nonFocusingOpen: true, opened: true, focused: true, pinned: 'true', calls: ['open:undefined', 'open:undefined', 'reveal', 'focus:visible'] }); + + activeComposite = undefined; + auxiliaryBar.setSizeToContent(false); + controller.setPinned(false); + controller.hide(); + controller.layout(33); + calls.length = 0; + container.openView('files', true); + assert.deepStrictEqual(calls, ['focus:hidden']); + }); + + test('focus preparation is opt-in and is released without changing ordinary container focus', () => { + const calls: string[] = []; + const view = upcastPartial({ isExpanded: () => true, focus: () => calls.push('focus') }); + const container = upcastPartial({}); + Object.setPrototypeOf(container, ViewPaneContainer.prototype); + Reflect.set(container, 'paneItems', [{ pane: view }]); + container.focus(); + const preparation = store.add(container.setFocusPreparation(() => calls.push('prepare'))); + container.focus(); + preparation.dispose(); + container.focus(); + assert.deepStrictEqual(calls, ['focus', 'prepare', 'focus', 'focus']); + }); + + test('a preview stays open during resize and uses the exit grace period after releasing outside it', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { editor, controller, snapshot } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + const sash = widget.querySelector('.monaco-sash.vertical:not(.disabled)')!; + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: 500, clientY: 200, bubbles: true })); + widget.dispatchEvent(new MouseEvent('mouseleave')); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 480, clientY: 200 })); + const duringDrag = widget.classList.contains('collapsed'); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: 480, clientY: 200 })); + const afterRelease = widget.classList.contains('collapsed'); + await timeout(250); + assert.deepStrictEqual({ duringDrag, afterRelease, afterDrag: widget.classList.contains('collapsed'), preferences: [snapshot().requestedWidth, snapshot().requestedHeight] }, { + duringDrag: false, afterRelease: false, afterDrag: true, preferences: [320, 400], + }); + })); + + test('late resize events cannot reopen a hidden floating surface', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const sash = widget.querySelector('.monaco-sash.vertical:not(.disabled)')!; + sash.dispatchEvent(new MouseEvent('mousedown', { clientX: 500, clientY: 200, bubbles: true })); + controller.hide(); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: 450, clientY: 200 })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: 450, clientY: 200 })); + assert.deepStrictEqual({ display: widget.style.display, preferences: [snapshot().requestedWidth, snapshot().requestedHeight] }, { + display: 'none', preferences: [300, 400], + }); + }); + + test('overlays the existing tree below tabs and restores it when hidden or disposed', () => { + const { editor, part, tree, controller, snapshot } = createHost(); + tree.focus(); + controller.layout(33); + const overlay = snapshot(); + const focusedInOverlay = getActiveElement() === tree; + const isolated = editor.classList.contains('floating-details-visible'); + controller.hide(); + const restored = part.parentElement === editor && getActiveElement() === tree; + const restoredStacking = !editor.classList.contains('floating-details-visible'); + controller.layout(33); + controller.dispose(); + assert.deepStrictEqual({ + overlay, focusedInOverlay, isolated, restored, restoredStacking, + disposed: part.parentElement === editor && !editor.querySelector('.floating-details'), + disposedStacking: !editor.classList.contains('floating-details-visible'), + }, { + overlay: { width: '300px', height: '400px', top: '41px', requestedWidth: 300, requestedHeight: 400, collapses: 0, layout: { width: 298, height: 366 } }, + focusedInOverlay: true, isolated: true, restored: true, restoredStacking: true, disposed: true, disposedStacking: true, + }); + }); + + for (const glass of [false, true]) { + test(`keeps editor scrollbars behind the ${glass ? 'frosted' : 'solid'} floating panel without blocking either scrollbar`, () => { + const { editor, part, controller, resize } = createHost(); + const width = Math.min(800, mainWindow.document.documentElement.clientWidth); + const height = Math.min(600, mainWindow.document.documentElement.clientHeight); + resize(width, height); + const root = editor.closest('.monaco-workbench')!; + root.classList.toggle('modern-ui-frosted-glass', glass); + root.style.setProperty('--vscode-spacing-size80', '8px'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + Object.assign(root.style, { position: 'fixed', top: '0', left: '0', width: `${width}px`, height: `${height}px` }); + Object.assign(editor.style, { position: 'relative', overflow: 'hidden' }); + const content = append(editor, $('.content')); + Object.assign(content.style, { position: 'absolute', inset: '0' }); + const group = append(content, $('.editor-group-container')); + Object.assign(group.style, { position: 'absolute', inset: '0' }); + const pane = append(group, $('.editor-container')); + Object.assign(pane.style, { position: 'absolute', inset: '0' }); + const editorScroll = append(pane, $('.monaco-scrollable-element')); + Object.assign(editorScroll.style, { position: 'absolute', inset: '0' }); + const editorScrollbar = append(editorScroll, $('.scrollbar.vertical.visible')); + Object.assign(editorScrollbar.style, { position: 'absolute', right: '0', top: '0', width: '14px', height: '100%' }); + const panelScroll = append(part, $('.monaco-scrollable-element')); + Object.assign(panelScroll.style, { position: 'absolute', inset: '0' }); + const panelScrollbar = append(panelScroll, $('.scrollbar.vertical.visible')); + Object.assign(panelScrollbar.style, { position: 'absolute', right: '0', top: '0', width: '14px', height: '100%' }); + + controller.layout(33); + const overlay = editor.querySelector('.floating-details')!; + const panelBounds = panelScrollbar.getBoundingClientRect(); + const scrollbarBounds = editorScrollbar.getBoundingClientRect(); + const left = Math.max(panelBounds.left, scrollbarBounds.left); + const right = Math.min(panelBounds.right, scrollbarBounds.right); + assert.ok(right > left, 'The scrollbar tracks must overlap for this regression test'); + const x = (left + right) / 2; + const y = panelBounds.top + 60; + const panelOnTop = panelScrollbar.contains(mainWindow.document.elementFromPoint(x, y)); + const outsideY = (overlay.getBoundingClientRect().bottom + scrollbarBounds.bottom) / 2; + const editorOutsidePanel = editorScrollbar.contains(mainWindow.document.elementFromPoint(x, outsideY)); + controller.hide(); + part.style.display = 'none'; + const editorAfterCollapse = editorScrollbar.contains(mainWindow.document.elementFromPoint(x, y)); + assert.deepStrictEqual({ panelOnTop, editorOutsidePanel, editorAfterCollapse }, { + panelOnTop: true, editorOutsidePanel: true, editorAfterCollapse: true, + }); + }); + } + + test('constrains both dimensions without losing requested sizes on window resize', () => { + const { controller, resize, snapshot } = createHost(); + resize(180, 140); + controller.layout(33); + const small = snapshot(); + resize(800, 600); + controller.layout(33); + const restored = snapshot(); + resize(0, 0); + controller.layout(33); + assert.deepStrictEqual({ small, restored, zero: snapshot() }, { + small: { width: '164px', height: '91px', top: '41px', requestedWidth: 300, requestedHeight: 400, collapses: 0, layout: { width: 162, height: 57 } }, + restored: { width: '300px', height: '400px', top: '41px', requestedWidth: 300, requestedHeight: 400, collapses: 0, layout: { width: 298, height: 366 } }, + zero: { width: '0px', height: '0px', top: '41px', requestedWidth: 300, requestedHeight: 400, collapses: 0, layout: { width: 0, height: 0 } }, + }); + }); + + test('supports keyboard resizing, reset, bounds, and Escape with focus restoration', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + const width = editor.querySelector('.floating-details-resize-width')!; + const height = editor.querySelector('.floating-details-resize-height')!; + const press = (target: HTMLElement, key: string, keyCode: number, shiftKey = false) => target.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, shiftKey, bubbles: true, cancelable: true })); + width.focus(); + press(width, 'ArrowLeft', 37, true); + height.focus(); + press(height, 'ArrowDown', 40); + const resized = snapshot(); + press(width, 'Home', 36); + press(height, 'Home', 36); + const reset = snapshot(); + for (let i = 0; i < 20; i++) { + press(width, 'ArrowRight', 39, true); + press(height, 'ArrowUp', 38, true); + } + const bounded = snapshot(); + press(height, 'Escape', 27); + assert.deepStrictEqual({ + resized: [resized.requestedWidth, resized.requestedHeight], + reset: [reset.requestedWidth, reset.requestedHeight], + bounded: [bounded.requestedWidth, bounded.requestedHeight], + aria: [width.getAttribute('role'), width.getAttribute('aria-valuenow'), height.getAttribute('aria-valuenow')], + collapses: snapshot().collapses, + focusRestored: getActiveElement() === editor, + }, { + resized: [350, 410], reset: [300, 400], bounded: [220, 160], + aria: ['separator', '220', '160'], collapses: 1, focusRestored: true, + }); + }); + + test('resizes from both mouse sashes and resets dimensions on double click', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + const width = editor.querySelector('.floating-details .monaco-sash.vertical:not(.disabled)')!; + const height = editor.querySelector('.floating-details .monaco-sash.horizontal:not(.disabled)')!; + const drag = (handle: HTMLElement, x: number, y: number, toX: number, toY: number) => { + handle.dispatchEvent(new MouseEvent('mousedown', { clientX: x, clientY: y, bubbles: true, cancelable: true })); + mainWindow.dispatchEvent(new MouseEvent('mousemove', { clientX: toX, clientY: toY, bubbles: true })); + mainWindow.dispatchEvent(new MouseEvent('mouseup', { clientX: toX, clientY: toY, bubbles: true })); + }; + drag(width, 500, 200, 460, 200); + drag(height, 650, 440, 650, 490); + const resized = snapshot(); + width.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + height.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const reset = snapshot(); + assert.deepStrictEqual({ resized: [resized.requestedWidth, resized.requestedHeight], reset: [reset.requestedWidth, reset.requestedHeight] }, { + resized: [340, 450], reset: [300, 400], + }); + }); + + test('uses a passive contextual caption beside the labelled pin toggle', () => { + const { editor, controller, snapshot } = createHost(); + controller.layout(33); + const button = editor.querySelector('[aria-label="Unpin Files"]')!; + const pinnedIcon = button.querySelector('.floating-details-state-icon')?.classList.contains('codicon-sessions-floating-details-pinned'); + button.focus(); + button.click(); + assert.deepStrictEqual({ + caption: editor.querySelector('.floating-details-title')?.textContent, + label: button.textContent, + pinnedIcon, + icon: editor.querySelector('.floating-details-icon')?.classList.contains('codicon-files'), + noChevron: !button.querySelector('.codicon-chevron-down'), + semibold: mainWindow.getComputedStyle(editor.querySelector('.floating-details-title')!).fontWeight, + decorative: editor.querySelector('.floating-details-icon')?.getAttribute('aria-hidden'), + role: button.getAttribute('role'), + collapses: snapshot().collapses, + focused: getActiveElement() === button, + }, { + caption: 'Files', label: '', pinnedIcon: true, icon: true, noChevron: true, semibold: '600', decorative: 'true', role: 'button', collapses: 0, focused: true, + }); + }); + + test('header and caption clicks never change pin state; only the icon button toggles it', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const header = widget.querySelector('.floating-details-header')!; + const caption = widget.querySelector('.floating-details-caption')!; + const title = caption.querySelector('.floating-details-title')!; + const viewIcon = caption.querySelector('.floating-details-icon')!; + const button = header.querySelector('.floating-details-toggle')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + for (const element of [header, caption, title, viewIcon]) { + element.click(); + } + const preview = { pinned: button.getAttribute('aria-pressed'), collapsed: widget.classList.contains('collapsed') }; + button.click(); + for (const element of [header, caption, title, viewIcon]) { + element.click(); + } + const pinned = { pinned: button.getAttribute('aria-pressed'), collapsed: widget.classList.contains('collapsed') }; + const bounds = button.getBoundingClientRect(); + button.click(); + assert.deepStrictEqual({ + preview, pinned, collapsed: widget.classList.contains('collapsed'), + titleInsideButton: button.contains(title), + captionRole: caption.getAttribute('role'), + captionCursor: mainWindow.getComputedStyle(caption).cursor, + captionBackground: mainWindow.getComputedStyle(caption).backgroundColor, + buttonSize: [bounds.width, bounds.height], + }, { + preview: { pinned: 'false', collapsed: false }, pinned: { pinned: 'true', collapsed: false }, collapsed: false, + titleInsideButton: false, captionRole: null, captionCursor: 'default', captionBackground: 'rgba(0, 0, 0, 0)', + buttonSize: [24, 24], + }); + }); + + test('Escape does not immediately reopen the caption underneath the pointer', () => { + const { editor, controller } = createHost(false); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const button = widget.querySelector('.floating-details-toggle')!; + const caption = widget.querySelector('.floating-details-caption')!; + widget.dispatchEvent(new MouseEvent('mouseenter')); + button.click(); + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + caption.dispatchEvent(new MouseEvent('mouseenter', { relatedTarget: button })); + const minimized = widget.classList.contains('collapsed'); + widget.dispatchEvent(new MouseEvent('mouseleave')); + widget.dispatchEvent(new MouseEvent('mouseenter')); + assert.deepStrictEqual({ minimized, reopened: !widget.classList.contains('collapsed'), visible: button.checkVisibility() }, { + minimized: true, reopened: true, visible: true, + }); + }); + + test('updates the caption, region, action, and resize labels when the active view changes', () => { + const { editor, controller, setTitle } = createHost(); + controller.layout(33); + setTitle('Changes'); + assert.deepStrictEqual({ + caption: editor.querySelector('.floating-details-title')?.textContent, + icon: editor.querySelector('.floating-details-icon')?.classList.contains('codicon-diff'), + region: editor.querySelector('.floating-details')?.getAttribute('aria-label'), + action: editor.querySelector('.action-label')?.getAttribute('aria-label'), + width: editor.querySelector('.floating-details-resize-width')?.getAttribute('aria-label'), + height: editor.querySelector('.floating-details-resize-height')?.getAttribute('aria-label'), + }, { + caption: 'Changes', icon: true, region: 'Changes', action: 'Unpin Changes', + width: 'Resize Changes Width. Use Left and Right Arrow keys.', + height: 'Resize Changes Height. Use Up and Down Arrow keys.', + }); + }); + + test('marks the floating panel as opaque only while Changes is active', () => { + const { editor, controller, setChangesViewActive } = createHost(); + controller.layout(33); + const widget = editor.querySelector('.floating-details')!; + const states = [widget.classList.contains('changes-view-active')]; + setChangesViewActive(true); + states.push(widget.classList.contains('changes-view-active')); + setChangesViewActive(false); + states.push(widget.classList.contains('changes-view-active')); + + assert.deepStrictEqual(states, [false, true, false]); + }); + + test('floating contents do not inherit the pane reveal slide or fade', () => { + const { editor, part, controller } = createHost(); + editor.closest('.monaco-workbench')!.classList.add('monaco-enable-motion'); + controller.layout(33); + const style = mainWindow.getComputedStyle(part); + assert.deepStrictEqual({ + duration: style.transitionDuration, + margins: [style.marginTop, style.marginRight, style.marginBottom, style.marginLeft], + opacity: style.opacity, + animations: part.getAnimations().length, + }, { duration: '0s', margins: ['0px', '0px', '0px', '0px'], opacity: '1', animations: 0 }); + }); + + test('clears floating left/bottom anchors before docking the existing tree on the right', () => { + const { editor, part, host, auxiliaryBarPart, accessibilityService } = createHost(false); + let floating = true; + const controller = store.add(new DockedAuxiliaryBarController(editor, upcastPartial(auxiliaryBarPart), { + getPosition: () => 'right', + getHeight: () => 240, setHeight: () => { }, getEditorContentTop: () => 65, + getWidth: host.getWidth, setWidth: host.setWidth, + isEditorAreaVisible: () => true, isEditorVisible: () => true, isAuxiliaryBarVisible: () => true, + hideAuxiliaryBar: host.focusEditor, setEditorContentInsets: () => { }, getTabsHeight: () => 33, + }, { + isEnabled: () => floating, + createController: () => new FloatingAuxiliaryBarController(editor, auxiliaryBarPart, host, accessibilityService, NullHoverService), + })); + controller.layout(); + const grip = editor.querySelector('.floating-details-drag-handle')!; + drag(grip, -2000, 2000); + controller.revealFloatingDetails(); + controller.layout(); + const anchored = [part.style.left, part.style.bottom]; + floating = false; + controller.layout(); + assert.deepStrictEqual({ + anchored, docked: [part.style.left, part.style.bottom, part.style.right], + x: part.getBoundingClientRect().left - editor.getBoundingClientRect().left, + }, { anchored: ['0px', '32px'], docked: ['', '', '0px'], x: 500 }); + }); + + test('switches docked and floating presentations without replacing the tree or reserving editor width', () => { + const { editor, part, tree, host, auxiliaryBarPart, accessibilityService } = createHost(); + let floating = true; + let editorVisible = true; + let auxiliaryBarVisible = true; + let inset = -1; + const controller = store.add(new DockedAuxiliaryBarController(editor, upcastPartial(auxiliaryBarPart), { + getPosition: () => 'right', + getHeight: () => 240, setHeight: () => { }, getEditorContentTop: () => 65, + getWidth: host.getWidth, setWidth: host.setWidth, + isEditorAreaVisible: () => true, + isEditorVisible: () => editorVisible, + isAuxiliaryBarVisible: () => auxiliaryBarVisible, + hideAuxiliaryBar: host.focusEditor, + setEditorContentInsets: value => { inset = value; }, + getTabsHeight: () => 33, + }, { + isEnabled: () => floating, + createController: () => new FloatingAuxiliaryBarController(editor, auxiliaryBarPart, host, accessibilityService, NullHoverService), + })); + controller.layout(); + const overlaid = { inset, floating: part.classList.contains('floating-auxiliarybar') }; + floating = false; + controller.layout(); + const docked = { inset, parent: part.parentElement === editor, tree: part.firstChild === tree }; + floating = true; + editorVisible = false; + controller.layout(); + const detailsOnly = { inset, width: part.style.width, floating: part.classList.contains('floating-auxiliarybar') }; + auxiliaryBarVisible = false; + controller.layout(); + assert.deepStrictEqual({ overlaid, docked, detailsOnly, hidden: part.style.display }, { + overlaid: { inset: 0, floating: true }, + docked: { inset: 300, parent: true, tree: true }, + detailsOnly: { inset: 800, width: '800px', floating: false }, + hidden: 'none', + }); + }); +}); diff --git a/src/vs/sessions/test/browser/interactionStyles.fixture.ts b/src/vs/sessions/test/browser/interactionStyles.fixture.ts new file mode 100644 index 000000000000..41b50499cece --- /dev/null +++ b/src/vs/sessions/test/browser/interactionStyles.fixture.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 '../../browser/media/style.css'; +import '../../../base/browser/ui/button/button.css'; +import * as DOM from '../../../base/browser/dom.js'; +import { Button } from '../../../base/browser/ui/button/button.js'; +import { defaultButtonStyles } from '../../../platform/theme/browser/defaultStyles.js'; +import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup } from '../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; + +type InteractionState = 'rest' | 'hovered' | 'focus-visible' | 'disabled'; + +function renderControl(container: HTMLElement, label: string, classes: readonly string[], state: InteractionState): void { + const control = DOM.append(container, DOM.$('button', { type: 'button' }, label)) as HTMLButtonElement; + control.classList.add(...classes, state); + control.disabled = state === 'disabled'; + control.style.padding = '4px 8px'; + control.style.border = 'var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, transparent)'; + control.style.background = 'transparent'; + control.style.color = 'inherit'; +} + +function renderStateColumn(context: ComponentFixtureContext, state: InteractionState): void { + const { container, disposableStore } = context; + const column = DOM.append(container, DOM.$('.interaction-state-column')); + column.style.display = 'flex'; + column.style.flexDirection = 'column'; + column.style.gap = '8px'; + DOM.append(column, DOM.$('strong', undefined, state)); + renderControl(column, 'Toolbar control', ['agent-sessions-interactive'], state); + renderControl(column, 'List control', ['agent-sessions-interactive', 'agent-sessions-interactive-list'], state); + const button = disposableStore.add(new Button(column, defaultButtonStyles)); + button.label = 'Standard button'; + button.enabled = state !== 'disabled'; + button.element.classList.add(state); +} + +function renderInteractionStyles(context: ComponentFixtureContext): void { + const { container } = context; + container.classList.add('monaco-workbench', 'agent-sessions-workbench'); + container.style.display = 'grid'; + container.style.gridTemplateColumns = 'repeat(4, minmax(0, 1fr))'; + container.style.gap = '16px'; + container.style.width = '760px'; + container.style.padding = '24px'; + container.style.boxSizing = 'border-box'; + container.style.background = 'var(--vscode-agentsPanel-background)'; + container.style.color = 'var(--vscode-foreground)'; + + for (const state of ['rest', 'hovered', 'focus-visible', 'disabled'] as const) { + renderStateColumn(context, state); + } +} + +export default defineThemedFixtureGroup({ path: 'sessions/interactionStyles/' }, { + StateMatrix: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: renderInteractionStyles, + }), +}); diff --git a/src/vs/sessions/test/browser/interactionStyles.test.ts b/src/vs/sessions/test/browser/interactionStyles.test.ts new file mode 100644 index 000000000000..8d84d75eeeca --- /dev/null +++ b/src/vs/sessions/test/browser/interactionStyles.test.ts @@ -0,0 +1,247 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../browser/media/style.css'; +import '../../browser/parts/media/projectBarPart.css'; +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'; + +suite('Sessions Interaction Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createRoot(): HTMLElement { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.hc-black')); + root.style.cssText = [ + '--vscode-strokeThickness: 1px', + '--vscode-spacing-size60: 6px', + '--vscode-cornerRadius-small: 4px', + '--vscode-toolbar-hoverBackground: #112233', + '--vscode-toolbar-hoverOutline: #445566', + '--vscode-list-hoverBackground: #223344', + '--vscode-list-activeSelectionBackground: #334455', + '--vscode-list-activeSelectionForeground: #ffffff', + '--vscode-contrastActiveBorder: #556677', + '--vscode-focusBorder: #778899', + '--vscode-list-focusOutline: #99aabb', + '--vscode-activityBar-inactiveForeground: #aabbcc', + '--vscode-activityBar-foreground: #ddeeff', + '--vscode-activityBar-background: #010203', + ].join(';'); + store.add(toDisposable(() => root.remove())); + return root; + } + + function getInteractionStyles(element: Element): { + readonly background: string; + readonly outlineColor: string; + readonly outlineOffset: string; + readonly outlineStyle: string; + readonly outlineWidth: string; + } { + const style = mainWindow.getComputedStyle(element); + const hasOutline = style.outlineStyle !== 'none'; + return { + background: style.backgroundColor, + outlineColor: hasOutline ? style.outlineColor : 'none', + outlineOffset: style.outlineOffset, + outlineStyle: style.outlineStyle, + outlineWidth: hasOutline ? style.outlineWidth : '0px', + }; + } + + test('shared controls preserve toolbar and list interaction semantics in high contrast', () => { + const root = createRoot(); + const toolbarHover = append(root, $('.agent-sessions-interactive.hovered')); + const listHover = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.hovered')); + const toolbarFocus = append(root, $('.agent-sessions-interactive.focus-visible')); + const listFocus = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.focus-visible')); + const toolbarFocusHover = append(root, $('.agent-sessions-interactive.focus-visible.hovered')); + const listFocusHover = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.focus-visible.hovered')); + const borderedFocus = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered.focus-visible')); + const borderedFocusHover = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.agent-sessions-interactive-bordered.focus-visible.hovered')); + const disabledHover = append(root, $('.agent-sessions-interactive.hovered.disabled')); + const pressedHover = append(root, $('.agent-sessions-interactive.hovered', { 'aria-pressed': 'true' })); + const expandedListHover = append(root, $('.agent-sessions-interactive.agent-sessions-interactive-list.hovered', { 'aria-expanded': 'true' })); + const buttonHover = append(root, $('.monaco-button.hovered')); + const buttonExpandedHover = append(root, $('.monaco-button.hovered', { 'aria-expanded': 'true' })); + const buttonFocusHover = append(root, $('.monaco-button.focus-visible.hovered')); + + assert.deepStrictEqual({ + toolbarHover: getInteractionStyles(toolbarHover), + listHover: getInteractionStyles(listHover), + toolbarFocus: getInteractionStyles(toolbarFocus), + listFocus: getInteractionStyles(listFocus), + toolbarFocusHover: getInteractionStyles(toolbarFocusHover), + listFocusHover: getInteractionStyles(listFocusHover), + borderedFocus: getInteractionStyles(borderedFocus), + borderedFocusHover: getInteractionStyles(borderedFocusHover), + disabledHover: getInteractionStyles(disabledHover), + pressedHover: getInteractionStyles(pressedHover), + expandedListHover: getInteractionStyles(expandedListHover), + buttonHover: getInteractionStyles(buttonHover), + buttonExpandedHover: getInteractionStyles(buttonExpandedHover), + buttonFocusHover: getInteractionStyles(buttonFocusHover), + }, { + toolbarHover: { + background: 'rgb(17, 34, 51)', + outlineColor: 'rgb(68, 85, 102)', + outlineOffset: '-1px', + outlineStyle: 'dashed', + outlineWidth: '1px', + }, + listHover: { + background: 'rgb(34, 51, 68)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'dashed', + outlineWidth: '1px', + }, + toolbarFocus: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + listFocus: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(153, 170, 187)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + toolbarFocusHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + listFocusHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(153, 170, 187)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + borderedFocus: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(153, 170, 187)', + outlineOffset: '-2px', + outlineStyle: 'solid', + outlineWidth: '2px', + }, + borderedFocusHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(153, 170, 187)', + outlineOffset: '-2px', + outlineStyle: 'solid', + outlineWidth: '2px', + }, + disabledHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'none', + outlineOffset: '0px', + outlineStyle: 'none', + outlineWidth: '0px', + }, + pressedHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + expandedListHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + buttonHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'dashed', + outlineWidth: '1px', + }, + buttonExpandedHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + buttonFocusHover: { + background: 'rgba(0, 0, 0, 0)', + outlineColor: 'rgb(119, 136, 153)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + }); + }); + + test('project bar states share one high contrast indicator geometry', () => { + const root = createRoot(); + const projectBar = append(root, $('.projectbar')); + const item = append(projectBar, $('.action-item.workspace-entry')); + append(item, $('span.action-label.workspace-icon')); + const readIndicator = () => { + const style = mainWindow.getComputedStyle(item, '::before'); + const hasOutline = style.outlineStyle !== 'none'; + return { + inset: [style.top, style.right, style.bottom, style.left], + borderColor: style.borderColor, + borderRadius: style.borderRadius, + outlineColor: hasOutline ? style.outlineColor : 'none', + outlineOffset: style.outlineOffset, + outlineStyle: style.outlineStyle, + outlineWidth: hasOutline ? style.outlineWidth : '0px', + }; + }; + + item.classList.add('hovered'); + const hovered = readIndicator(); + item.classList.replace('hovered', 'checked'); + const checked = readIndicator(); + item.classList.replace('checked', 'focus-visible'); + const focused = readIndicator(); + + assert.deepStrictEqual({ hovered, checked, focused }, { + hovered: { + inset: ['6px', '6px', '6px', '6px'], + borderColor: 'rgba(0, 0, 0, 0)', + borderRadius: '0px', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'dashed', + outlineWidth: '1px', + }, + checked: { + inset: ['6px', '6px', '6px', '6px'], + borderColor: 'rgba(0, 0, 0, 0)', + borderRadius: '0px', + outlineColor: 'rgb(85, 102, 119)', + outlineOffset: '-1px', + outlineStyle: 'solid', + outlineWidth: '1px', + }, + focused: { + inset: ['6px', '6px', '6px', '6px'], + borderColor: 'rgb(119, 136, 153)', + borderRadius: '0px', + outlineColor: 'none', + outlineOffset: '0px', + outlineStyle: 'none', + outlineWidth: '0px', + }, + }); + }); +}); diff --git a/src/vs/sessions/test/browser/layoutActions.test.ts b/src/vs/sessions/test/browser/layoutActions.test.ts index 478c2db33009..2b7e626133b2 100644 --- a/src/vs/sessions/test/browser/layoutActions.test.ts +++ b/src/vs/sessions/test/browser/layoutActions.test.ts @@ -235,6 +235,9 @@ suite('Sessions - Layout Actions', () => { const scenarios: Record> = { layoutActions: base, layoutActionsOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING}`]: false }, + docked: { ...base, [`config.${SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING}`]: false, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, + dockedActivityBarOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_SETTING}`]: false, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, + dockedEditorMaximized: { ...base, editorMaximized: true, [`config.${SESSION_ACTIVITY_BAR_FIXED_COLUMN_SETTING}`]: true }, activityBarOff: { ...base, [`config.${SESSION_ACTIVITY_BAR_SETTING}`]: false }, // The activity bar is hidden with the Sessions part while the editor is maximized, and in the phone layout. editorMaximized: { ...base, editorMaximized: true }, @@ -251,6 +254,9 @@ suite('Sessions - Layout Actions', () => { placement: { layoutActions: ['activityBar'], layoutActionsOff: ['titleBar'], + docked: [], + dockedActivityBarOff: ['titleBar'], + dockedEditorMaximized: ['titleBar'], activityBarOff: ['titleBar'], editorMaximized: ['titleBar'], // The phone layout has its own panel controls. @@ -294,7 +300,6 @@ suite('Sessions - Layout Actions', () => { order: item.order, icon: ThemeIcon.isThemeIcon(item.command.icon) ? item.command.icon.id : undefined, hasToggledState: Boolean(item.command.toggled), - when: item.when?.serialize(), })) .sort((a, b) => (a.icon ?? '').localeCompare(b.icon ?? '')); @@ -310,15 +315,12 @@ suite('Sessions - Layout Actions', () => { order: 10, icon: Codicon.layoutPanel.id, hasToggledState: false, - // Hidden while the Session Activity Bar shows its layout actions. - when: 'editorMaximized && panelVisible && !isAuxiliaryWindow && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || panelVisible && !agentSessionsDesktopLayout && !isAuxiliaryWindow && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || panelVisible && !config.sessions.sessionActivityBar.showLayoutActions && !isAuxiliaryWindow && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || panelVisible && !config.sessions.showSessionActivityBar && !isAuxiliaryWindow && !sessionsIsPhoneLayout && !sessionsWelcomeVisible', }, { group: 'navigation', order: 10, icon: Codicon.layoutPanelOff.id, hasToggledState: false, - when: 'editorMaximized && !isAuxiliaryWindow && !panelVisible && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || !agentSessionsDesktopLayout && !isAuxiliaryWindow && !panelVisible && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || !config.sessions.sessionActivityBar.showLayoutActions && !isAuxiliaryWindow && !panelVisible && !sessionsIsPhoneLayout && !sessionsWelcomeVisible || !config.sessions.showSessionActivityBar && !isAuxiliaryWindow && !panelVisible && !sessionsIsPhoneLayout && !sessionsWelcomeVisible', }, ], terminalActionPresent: false, diff --git a/src/vs/sessions/test/browser/mobilePullToRefresh.test.ts b/src/vs/sessions/test/browser/mobilePullToRefresh.test.ts new file mode 100644 index 000000000000..f75128c63954 --- /dev/null +++ b/src/vs/sessions/test/browser/mobilePullToRefresh.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 'assert'; +import * as dom from '../../../base/browser/dom.js'; +import { mainWindow } from '../../../base/browser/window.js'; +import { DeferredPromise } from '../../../base/common/async.js'; +import { errorHandler, setUnexpectedErrorHandler } from '../../../base/common/errors.js'; +import { toDisposable } from '../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { installPullToRefresh } from '../../browser/mobile/mobilePullToRefresh.js'; + +suite('Mobile pull to refresh', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + for (const endEvent of ['touchend', 'touchcancel']) { + test(`${endEvent} reports a rejected refresh and resets the indicator`, async () => { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const error = new Error('Refresh failed'); + const reported = new DeferredPromise(); + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + store.add(toDisposable(() => setUnexpectedErrorHandler(previousHandler))); + setUnexpectedErrorHandler(error => { void reported.complete(error); }); + let refreshCount = 0; + store.add(installPullToRefresh(container, { + isAtTop: () => true, + refresh: async () => { refreshCount++; throw error; }, + })); + + // WebKit exposes Touch but does not support constructing it. + for (const [type, clientY] of [['touchstart', 100], ['touchmove', 200]] as const) { + container.dispatchEvent(Object.assign(new mainWindow.Event(type), { touches: [{ clientY }] })); + } + container.dispatchEvent(new mainWindow.Event(endEvent)); + const failure = await reported.p; + const indicator = container.querySelector('.mobile-pull-indicator')!; + assert.deepStrictEqual({ + reported: failure === error, refreshCount, + refreshing: indicator.classList.contains('refreshing'), + armed: indicator.classList.contains('armed'), + transform: indicator.style.transform, + message: container.querySelector('.mobile-pull-live')?.textContent, + }, { reported: true, refreshCount: 1, refreshing: false, armed: false, transform: 'translateY(0px)', message: 'Could not refresh' }); + }); + } +}); diff --git a/src/vs/sessions/test/browser/mobileTitlebarPart.test.ts b/src/vs/sessions/test/browser/mobileTitlebarPart.test.ts new file mode 100644 index 000000000000..e1888fe84308 --- /dev/null +++ b/src/vs/sessions/test/browser/mobileTitlebarPart.test.ts @@ -0,0 +1,290 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../base/browser/dom.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 { constObservable, observableValue } from '../../../base/common/observable.js'; +import { URI } from '../../../base/common/uri.js'; +import { mock } from '../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { MenuWorkbenchToolBar } from '../../../platform/actions/browser/toolbar.js'; +import { IMenuService, MenuItemAction } 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 { ContextKeyService } from '../../../platform/contextkey/browser/contextKeyService.js'; +import { ContextKeyExpr, IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; +import { IDefaultAccountService } from '../../../platform/defaultAccount/common/defaultAccount.js'; +import { IHoverService } from '../../../platform/hover/browser/hover.js'; +import { NullHoverService } from '../../../platform/hover/test/browser/nullHoverService.js'; +import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { SideBarVisibleContext } from '../../../workbench/common/contextkeys.js'; +import { ACCOUNTS_AVATAR_SETTING, IAuthenticationService } from '../../../workbench/services/authentication/common/authentication.js'; +import { ChatEntitlement, IChatEntitlementService } from '../../../workbench/services/chat/common/chatEntitlementService.js'; +import { IChatDashboardService } from '../../browser/chatDashboardService.js'; +import { MobileTitlebarPart as MobileWorkbenchTitlebarPart } from '../../browser/mobile/mobileTitlebarPart.js'; +import { MOBILE_OPEN_CHANGES_VIEW_COMMAND_ID } from '../../browser/parts/mobile/contributions/mobileChangesView.js'; +import { MobileTitlebarPart } from '../../browser/parts/mobile/mobileTitlebarPart.js'; +import { IsNewChatSessionContext } from '../../../workbench/contrib/sessions/common/contextkeys.js'; +import { IChat, ISession, ISessionFileChange, SessionStatus } from '../../../workbench/services/sessions/common/session.js'; +import { stubSessionHosts } from '../../../workbench/contrib/sessions/test/browser/sessionHostTestUtils.js'; + +function query(container: ParentNode, selector: string): T { + const element = container.querySelector(selector); + assert.ok(element, selector); + return element; +} + +async function createHarness(store: Pick, ctor: typeof MobileTitlebarPart) { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IHoverService, { ...NullHoverService }); + const configurationService = new TestConfigurationService({ [ACCOUNTS_AVATAR_SETTING]: false }); + store.add(configurationService.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configurationService); + const contextKeyService = store.add(new ContextKeyService(configurationService)); + instantiationService.stub(IContextKeyService, contextKeyService); + const isNewChat = IsNewChatSessionContext.bindTo(contextKeyService); + const sidebarVisible = SideBarVisibleContext.bindTo(contextKeyService); + isNewChat.set(true); + sidebarVisible.set(false); + + const title = observableValue('title', 'First session'); + const changes = observableValue('changes', []); + const chat = new class extends mock() { + override readonly changes = changes; + }(); + const session = new class extends mock() { + override readonly title = title; + override readonly status = constObservable(SessionStatus.Completed); + }(); + const activeSession = observableValue('activeSession', undefined); + stubSessionHosts(instantiationService, store, { + session: activeSession.map(session => session && { session, chat }), + }); + instantiationService.stub(IDefaultAccountService, { + onDidChangeDefaultAccount: Event.None, + getDefaultAccount: async () => null, + }); + instantiationService.stub(IAuthenticationService, { + onDidChangeSessions: Event.None, + getSessions: async () => [{ id: 'test-session', accessToken: '', scopes: [], account: { id: 'test-account', label: 'Test Account' } }], + }); + instantiationService.stub(IChatEntitlementService, { + onDidChangeEntitlement: Event.None, + onDidChangeSentiment: Event.None, + onDidChangeQuotaExceeded: Event.None, + onDidChangeQuotaRemaining: Event.None, + entitlement: ChatEntitlement.Pro, + sentiment: {}, + quotas: {}, + }); + let dashboardDisposals = 0; + instantiationService.stub(IChatDashboardService, { + createDashboardElement: dashboardStore => { + dashboardStore.add(toDisposable(() => dashboardDisposals++)); + return dom.$('div', undefined, 'Account status'); + }, + }); + const commands: string[] = []; + instantiationService.stub(ICommandService, { + executeCommand: async id => { commands.push(id); return undefined; }, + }); + const actions = ['First', 'Last', 'Disabled'].map(label => instantiationService.createInstance(MenuItemAction, { + id: `test.${label}`, + title: label, + precondition: label === 'Disabled' ? ContextKeyExpr.false() : undefined, + }, undefined, undefined, undefined, undefined)); + instantiationService.stub(IMenuService, { + createMenu: () => ({ + onDidChange: Event.None, + getActions: () => [['navigation', actions]], + dispose: () => { }, + }), + }); + let itemCount = 0; + let toolbarFocusCount = 0; + const menuChanged = store.add(new Emitter()); + const toolbar = new class extends mock() { + override getItemsLength(): number { return itemCount; } + override get onDidChangeMenuItems(): Event { return Event.map(menuChanged.event, () => this); } + override focus(): void { toolbarFocusCount++; } + override dispose(): void { } + }(); + instantiationService.stubInstance(MenuWorkbenchToolBar, toolbar); + + const bar = store.add(instantiationService.createInstance(ctor, container)); + await timeout(0); + return { + bar, container, title, changes, session, activeSession, isNewChat, sidebarVisible, commands, + getDashboardDisposals: () => dashboardDisposals, + getToolbarFocusCount: () => toolbarFocusCount, + setToolbarItems: (count: number) => { itemCount = count; menuChanged.fire(toolbar); }, + }; +} + +suite('Sessions - MobileTitlebarPart isolation', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + for (const ctor of [MobileTitlebarPart, MobileWorkbenchTitlebarPart]) { + const mobileWorkbench = ctor === MobileWorkbenchTitlebarPart; + const titlebar = mobileWorkbench ? 'mobile workbench titlebar' : 'responsive titlebar'; + + test(`${titlebar} keeps its own title presentation and disposes subscriptions`, async () => { + const h = await createHarness(store, ctor); + const titleElement = query(h.container, '.mobile-session-title'); + const titles = [titleElement.textContent]; + h.activeSession.set(h.session, undefined); + titles.push(titleElement.textContent); + h.isNewChat.set(false); + titles.push(titleElement.textContent); + h.sidebarVisible.set(true); + titles.push(titleElement.textContent); + h.title.set('Renamed session', undefined); + titles.push(titleElement.textContent); + h.sidebarVisible.set(false); + titles.push(titleElement.textContent); + h.title.set('', undefined); + titles.push(titleElement.textContent); + h.bar.setTitle('Override'); + titles.push(titleElement.textContent); + h.bar.dispose(); + h.title.set('After disposal', undefined); + h.isNewChat.set(true); + h.sidebarVisible.set(true); + titles.push(titleElement.textContent); + + assert.deepStrictEqual(titles, mobileWorkbench + ? ['Agents', 'Agents', 'First session', 'Sessions', 'Sessions', 'Renamed session', 'New Session', 'Override', 'Override'] + : ['New Session', 'First session', 'First session', 'First session', 'Renamed session', 'Renamed session', 'New Session', 'Override', 'Override']); + }); + + test(`${titlebar} preserves the shared toolbar, changes pill and navigation actions`, async () => { + const h = await createHarness(store, ctor); + const titleElement = query(h.container, '.mobile-session-title'); + const newSession = query(h.container, '.mobile-new-session-button'); + const account = query(h.container, '.mobile-account-indicator'); + const changes = query(h.container, '.mobile-changes-pill'); + let newSessionClicks = 0; + let titleClicks = 0; + let sidebarClicks = 0; + store.add(h.bar.onDidClickNewSession(() => newSessionClicks++)); + store.add(h.bar.onDidClickTitle(() => titleClicks++)); + store.add(h.bar.onDidClickHamburger(() => sidebarClicks++)); + h.activeSession.set(h.session, undefined); + h.changes.set([{ modifiedUri: URI.file('/test/file.ts'), insertions: 3, deletions: 1 }], undefined); + h.setToolbarItems(1); + h.sidebarVisible.set(true); + h.bar.focus(); + const welcome = { + showActions: h.bar.element.classList.contains('show-actions'), + newSession: newSession.style.display, account: account.style.display, changes: changes.style.display, + toolbarFocusCount: h.getToolbarFocusCount(), + }; + h.isNewChat.set(false); + h.bar.focus(); + const inChat = { + showActions: h.bar.element.classList.contains('show-actions'), + newSession: newSession.style.display, account: account.style.display, changes: changes.style.display, + titleFocused: dom.getActiveElement() === titleElement, + added: query(h.container, '.mobile-changes-pill-added').textContent, + removed: query(h.container, '.mobile-changes-pill-removed').textContent, + }; + changes.click(); + newSession.click(); + titleElement.click(); + query(h.bar.element, '.mobile-top-bar-button').click(); + h.isNewChat.set(true); + h.setToolbarItems(0); + h.bar.focus(); + assert.deepStrictEqual({ + welcome, inChat, newSessionClicks, titleClicks, sidebarClicks, commands: h.commands, + emptyToolbar: !h.bar.element.classList.contains('show-actions') && dom.getActiveElement() === titleElement, + changesHidden: changes.style.display, + }, { + welcome: { showActions: true, newSession: 'none', account: '', changes: 'none', toolbarFocusCount: 1 }, + inChat: { showActions: false, newSession: '', account: 'none', changes: '', titleFocused: true, added: '+3', removed: '-1' }, + newSessionClicks: 1, titleClicks: 1, sidebarClicks: 1, commands: [MOBILE_OPEN_CHANGES_VIEW_COMMAND_ID], + emptyToolbar: true, changesHidden: 'none', + }); + }); + + test(`${titlebar} keeps account presentation defaults and cleans up repeated sheets`, async () => { + const h = await createHarness(store, ctor); + const account = query(h.container, '.mobile-account-indicator'); + account.focus(); + account.click(); + const sheet = query(h.container, '.mobile-account-sheet'); + const close = query(sheet, '.mobile-account-sheet-close'); + const initial = { + role: sheet.getAttribute('role'), modal: sheet.getAttribute('aria-modal'), + label: sheet.getAttribute('aria-label'), tabIndex: sheet.getAttribute('tabindex'), + focus: dom.getActiveElement() === close ? 'close' : dom.getActiveElement() === account ? 'account' : 'other', + profile: query(sheet, '.mobile-account-sheet-name').textContent, + }; + close.click(); + const closed = { + sheetRemoved: !sheet.isConnected, + accountFocused: dom.getActiveElement() === account, + dashboardDisposals: h.getDashboardDisposals(), + }; + account.click(); + account.click(); + account.click(); + h.bar.dispose(); + const staleEscape = new mainWindow.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + sheet.dispatchEvent(staleEscape); + assert.deepStrictEqual({ + initial, closed, remaining: h.container.childElementCount, + dashboardDisposals: h.getDashboardDisposals(), staleEscapeHandled: staleEscape.defaultPrevented, + }, { + initial: { + role: mobileWorkbench ? 'dialog' : null, modal: mobileWorkbench ? 'true' : null, + label: mobileWorkbench ? 'Account' : null, tabIndex: mobileWorkbench ? '-1' : null, + focus: mobileWorkbench ? 'close' : 'account', profile: 'Test Account', + }, + closed: { sheetRemoved: true, accountFocused: true, dashboardDisposals: 1 }, + remaining: 0, dashboardDisposals: 3, staleEscapeHandled: false, + }); + }); + } + + test('mobile workbench account sheet wraps focus past disabled actions and restores it on Escape and action invocation', async () => { + const h = await createHarness(store, MobileWorkbenchTitlebarPart); + const account = query(h.container, '.mobile-account-indicator'); + account.focus(); + account.click(); + const sheet = query(h.container, '.mobile-account-sheet'); + const close = query(sheet, '.mobile-account-sheet-close'); + const lastAction = query(sheet, '[aria-label="Last"]'); + const backward = new mainWindow.KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true }); + close.dispatchEvent(backward); + const wrappedBackward = dom.getActiveElement() === lastAction; + const forward = new mainWindow.KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true }); + lastAction.dispatchEvent(forward); + const wrappedForward = dom.getActiveElement() === close; + const escape = new mainWindow.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + close.dispatchEvent(escape); + const dismissed = !sheet.isConnected && dom.getActiveElement() === account; + account.click(); + query(h.container, '[aria-label="First"]').click(); + + assert.deepStrictEqual({ + wrappedBackward, wrappedForward, handled: [backward.defaultPrevented, forward.defaultPrevented, escape.defaultPrevented], + dismissed, accountFocused: dom.getActiveElement() === account, + sheetRemoved: !h.container.querySelector('.mobile-account-sheet'), + commands: h.commands, dashboardDisposals: h.getDashboardDisposals(), + }, { + wrappedBackward: true, wrappedForward: true, handled: [true, true, true], + dismissed: true, accountFocused: true, sheetRemoved: true, + commands: ['test.First'], dashboardDisposals: 2, + }); + }); +}); diff --git a/src/vs/sessions/test/browser/popupHover.fixture.ts b/src/vs/sessions/test/browser/popupHover.fixture.ts new file mode 100644 index 000000000000..08ac11be1191 --- /dev/null +++ b/src/vs/sessions/test/browser/popupHover.fixture.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../browser/media/style.css'; +import * as DOM from '../../../base/browser/dom.js'; +import { Menu } from '../../../base/browser/ui/menu/menu.js'; +import { Action } from '../../../base/common/actions.js'; +import { isHighContrast } from '../../../platform/theme/common/theme.js'; +import { defaultMenuStyles } from '../../../platform/theme/browser/defaultStyles.js'; +import { ActionListItemKind, ActionListWidget, IActionListItem } from '../../../platform/actionWidget/browser/actionList.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup } from '../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; + +function renderPopupHover(context: ComponentFixtureContext): void { + const { container, disposableStore, theme } = context; + container.classList.add('monaco-workbench', 'agent-sessions-workbench'); + container.style.display = 'flex'; + container.style.alignItems = 'flex-start'; + container.style.gap = '24px'; + container.style.width = '680px'; + container.style.padding = '24px'; + container.style.boxSizing = 'border-box'; + container.style.background = 'var(--vscode-agents-background)'; + + const instantiationService = createEditorServices(disposableStore, { colorTheme: theme }); + const actionListHost = DOM.append(container, DOM.$('.action-widget')); + actionListHost.style.width = '300px'; + const items: IActionListItem[] = [ + { kind: ActionListItemKind.Action, item: 'interactive', label: 'Interactive', detail: 'Step-by-step collaboration' }, + { kind: ActionListItemKind.Action, item: 'plan', label: 'Plan', detail: 'Plan first, execute when ready' }, + { kind: ActionListItemKind.Action, item: 'autopilot', label: 'Autopilot', detail: 'Works autonomously' }, + ]; + const actionList = disposableStore.add(instantiationService.createInstance( + ActionListWidget, + 'popupHoverActionList', + false, + items, + { onHide: () => { }, onSelect: () => { } }, + undefined, + { showFilter: false, wrapDetails: true }, + )); + actionListHost.appendChild(actionList.domNode); + actionList.layout(actionList.computeListHeight()); + actionList.focus(); + const actionRow = actionList.domNode.querySelectorAll('.monaco-list-row.action')[1]; + actionRow.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, movementX: 1 })); + + const menuHost = DOM.append(container, DOM.$('.popup-hover-menu')); + menuHost.style.width = '300px'; + const menu = disposableStore.add(new Menu(menuHost, [ + disposableStore.add(new Action('ordering', 'Ordering')), + disposableStore.add(new Action('grouping', 'Grouping')), + disposableStore.add(new Action('show', 'Show')), + ], {}, defaultMenuStyles)); + menu.focus(true); + const menuRow = menuHost.querySelectorAll('.action-item')[1]; + menuRow.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, movementX: 1 })); + + if (isHighContrast(theme.type)) { + const actionOutline = DOM.getWindow(actionRow).getComputedStyle(actionRow).outlineStyle; + const menuItem = menuRow.querySelector('.action-menu-item')!; + const menuOutline = DOM.getWindow(menuItem).getComputedStyle(menuItem).outlineStyle; + if (actionOutline !== 'dashed' || menuOutline !== 'dashed') { + throw new Error(`Expected dashed HC pointer outlines, got action list ${actionOutline} and menu ${menuOutline}`); + } + } +} + +export default defineThemedFixtureGroup({ path: 'sessions/popupHover/' }, { + ActionListAndMenu: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The action-list Plan row and context-menu Grouping row are pointer-hovered. In high contrast themes, both use the same dashed active-contrast boundary.'], + render: renderPopupHover, + }), +}); diff --git a/src/vs/sessions/test/browser/sessionActivityBar.test.ts b/src/vs/sessions/test/browser/sessionActivityBar.test.ts index df08db079d91..50c9c5a1f635 100644 --- a/src/vs/sessions/test/browser/sessionActivityBar.test.ts +++ b/src/vs/sessions/test/browser/sessionActivityBar.test.ts @@ -48,6 +48,10 @@ import { IconBadge, NumberBadge } from '../../../workbench/services/activity/com import { TestContextViewService } from './testContextViewService.js'; import '../../../base/browser/ui/tree/media/tree.css'; import '../../../workbench/contrib/sessions/browser/parts/media/sessionView.css'; +// eslint-disable-next-line local/code-import-patterns +import '../../../workbench/contrib/modernUI/browser/media/tabs.css'; +// eslint-disable-next-line local/code-import-patterns +import '../../../workbench/contrib/modernUI/browser/media/connectedEditorTabs.css'; import { LayoutModeContext } from '../../../workbench/common/contextkeys.js'; import { IWindowCommandContext } from '../../../workbench/common/windowCommandContext.js'; import { stubSessionsHostLayout } from './sessionsHostLayoutTestUtils.js'; @@ -437,7 +441,7 @@ suite('Sessions - Session Activity Bar', () => { grip.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); const reset = top(); inColumn.set(true, undefined); - const inColumnState = { top: element.style.top, grip: mainWindow.getComputedStyle(grip).display !== 'none' }; + const inColumnState = { top: mainWindow.getComputedStyle(element).top, grip: mainWindow.getComputedStyle(grip).display !== 'none' }; assert.deepStrictEqual({ dragged, bottomGap, bottomGapAfterAreaGrew, reset, inColumn: inColumnState }, { dragged: 94, @@ -487,7 +491,7 @@ suite('Sessions - Session Activity Bar', () => { const element = docked.element!; const host = element.parentElement!; // As the hosts lay it out: to the left of the column they keep. - const chat = append(host, $('.chat-view')); + const chat = append(host, $('.chat-view.sessions-chat')); chat.style.cssText = `position: absolute; top: 0; left: 0; height: 100%; width: calc(100% - ${docked.reservedWidth.get()}px);`; const bounds = element.getBoundingClientRect(); const button = element.querySelector('.action-label')!.getBoundingClientRect(); @@ -639,6 +643,8 @@ suite('Sessions - Session Activity Bar', () => { test('in the main window\'s column, takes the size chosen for it, and beside a chat is always compact', () => { const { createDocked, root, setSize } = createActivityBar(store, [changes, browser]); + root.style.setProperty('--vscode-spacing-size40', '4px'); + root.style.setProperty('--vscode-spacing-size80', '8px'); const hostElement = append(root, $('.session-activity-bar-column.session-activity-bar-host')); const inColumn = observableValue('inColumn', true); store.add(registerSessionActivityBarExternalHost(root, { element: hostElement, active: inColumn, fullSize: true, setOccupied: () => { } })); @@ -646,7 +652,10 @@ suite('Sessions - Session Activity Bar', () => { docked.layout(0, 400); docked.setActive(true); const element = docked.element!; - const state = () => ({ compact: element.classList.contains('size-compact'), floating: element.classList.contains('floating') }); + const state = () => { + const [first, second] = [...element.querySelectorAll('.action-label:not(.separator)')].map(entry => entry.getBoundingClientRect()); + return { compact: element.classList.contains('size-compact'), floating: element.classList.contains('floating'), gap: second.top - first.bottom }; + }; const initial = state(); setSize(MenuActivityBarSize.Normal); @@ -657,14 +666,111 @@ suite('Sessions - Session Activity Bar', () => { const backInColumn = state(); setSize(MenuActivityBarSize.Compact); const compact = state(); + root.classList.add('modern-ui-compact'); + const compactDensity = state(); + + assert.deepStrictEqual({ initial, normalSize, besideChat, backInColumn, compact, compactDensity }, { + initial: { compact: true, floating: false, gap: 4 }, + normalSize: { compact: false, floating: false, gap: 8 }, + besideChat: { compact: true, floating: true, gap: 0 }, + backInColumn: { compact: false, floating: false, gap: 8 }, + compact: { compact: true, floating: false, gap: 4 }, + compactDensity: { compact: true, floating: false, gap: 4 }, + }); + }); + + test('aligns the docked strip with inset frames without horizontal movement and defaults to transparent customizable chrome', () => { + const { createDocked, root } = createActivityBar(store, [changes, browser]); + root.classList.add('agent-sessions-workbench', 'modern-ui-tabs'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-modernActivityBar-border', 'red'); + root.style.setProperty('--vscode-modernActivityBar-background', 'red'); + const hostElement = append(root, $('.session-activity-bar-column.session-activity-bar-host')); + hostElement.style.cssText = '--vscode-spacing-size60: 6px; --vscode-spacing-size240: 24px; width: 38px; height: 200px;'; + store.add(registerSessionActivityBarExternalHost(root, { element: hostElement, active: observableValue('active', true), fullSize: true, setOccupied: () => { } })); + const docked = createDocked(); + docked.layout(40, 400); + docked.setActive(true); + const element = docked.element!; + const geometry = () => { + const bounds = element.getBoundingClientRect(); + const hostBounds = hostElement.getBoundingClientRect(); + return { + insets: [bounds.top - hostBounds.top, hostBounds.bottom - bounds.bottom, hostBounds.right - bounds.right], + border: mainWindow.getComputedStyle(element).borderRightColor, + background: mainWindow.getComputedStyle(element).backgroundColor, + }; + }; + const open = geometry(); + root.classList.add('noeditorpane'); + const closed = geometry(); + root.classList.remove('noeditorpane'); + const reopened = geometry(); + root.classList.add('modern-ui-compact', 'hc-black'); + const compact = geometry(); + root.classList.remove('modern-ui-compact', 'hc-black'); + root.classList.add('hc-light'); + const highContrastLight = geometry(); + root.classList.remove('modern-ui-tabs'); + const legacy = geometry(); + root.style.setProperty('--vscode-agentsActivityBar-background', '#123456'); + root.style.setProperty('--vscode-agentsActivityBar-border', '#abcdef'); + const customized = geometry(); + root.style.removeProperty('--vscode-agentsActivityBar-background'); + root.style.removeProperty('--vscode-agentsActivityBar-border'); + const reset = geometry(); + + assert.deepStrictEqual({ open, closed, reopened, compact, highContrastLight, legacy, customized, reset }, { + open: { insets: [1, 1, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + closed: { insets: [1, 1, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + reopened: { insets: [1, 1, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + compact: { insets: [0, 0, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + highContrastLight: { insets: [1, 1, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + legacy: { insets: [0, 0, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + customized: { insets: [0, 0, 0], border: 'rgb(171, 205, 239)', background: 'rgb(18, 52, 86)' }, + reset: { insets: [0, 0, 0], border: 'rgba(0, 0, 0, 0)', background: 'rgba(0, 0, 0, 0)' }, + }); + }); - assert.deepStrictEqual({ initial, normalSize, besideChat, backInColumn, compact }, { - initial: { compact: true, floating: false }, - normalSize: { compact: false, floating: false }, - besideChat: { compact: true, floating: true }, - backInColumn: { compact: false, floating: false }, - compact: { compact: true, floating: false }, + test('aligns the first docked control with the connected panel header icons as tab height and layout density change', () => { + const { createDocked, root } = createActivityBar(store, [changes, browser]); + root.classList.add('modern-ui-tabs', 'modern-ui-connected-editor-tabs'); + root.style.cssText = '--vscode-spacing-size20: 2px; --vscode-spacing-size40: 4px; --vscode-spacing-size60: 6px; --vscode-spacing-size80: 8px; --vscode-spacing-size200: 20px; --vscode-spacing-size240: 24px; --vscode-strokeThickness: 1px;'; + const editor = append(root, $('.part.editor')); + editor.style.cssText = 'position: absolute; top: 0; width: 400px;'; + const group = append(append(editor, $('.content')), $('.editor-group-container.active')); + const title = append(group, $('.title.tabs')); + const row = append(title, $('.tabs-and-actions-container')); + append(append(row, $('.tabs-container')), $('.tab')); + const toolbars = append(row, $('.editor-toolbars')); + const actions = append(toolbars, $('.editor-actions')); + const actionBar = append(append(actions, $('.monaco-toolbar')), $('.monaco-action-bar')); + const icon = append(append(append(actionBar, $('ul.actions-container')), $('li.action-item')), $('a.action-label.codicon')); + const hostElement = append(root, $('.session-activity-bar-column.session-activity-bar-host')); + hostElement.style.cssText = 'position: absolute; top: 0; width: 34px; height: 200px;'; + store.add(registerSessionActivityBarExternalHost(root, { element: hostElement, active: observableValue('active', true), fullSize: true, setOccupied: () => { } })); + const docked = createDocked(); + docked.setActive(true); + docked.layout(0, 200); + const states = [false, true, false].map(compactDensity => { + root.classList.toggle('modern-ui-compact', compactDensity); + return [false, true, false].map(compactTabs => { + root.classList.toggle('editor-tabs-compact-height', compactTabs); + title.classList.toggle('compact-height', compactTabs); + const control = docked.element!.querySelector('.action-label')!.getBoundingClientRect(); + const header = icon.getBoundingClientRect(); + return { + offset: control.top + control.height / 2 - header.top - header.height / 2, + center: control.top + control.height / 2 - hostElement.getBoundingClientRect().top, + }; + }); }); + + assert.deepStrictEqual(states, Array.from({ length: 3 }, () => [ + { offset: 0, center: 15.5 }, + { offset: 0, center: 13.5 }, + { offset: 0, center: 15.5 }, + ])); }); test('right-clicking an entry or the rest of the strip offers to hide the activity bar and lists the entries to show, the rest of the strip without the actions of an entry', () => { diff --git a/src/vs/sessions/test/browser/sessionGridLayout.test.ts b/src/vs/sessions/test/browser/sessionGridLayout.test.ts index dac3f375cb7d..ec5d0905185e 100644 --- a/src/vs/sessions/test/browser/sessionGridLayout.test.ts +++ b/src/vs/sessions/test/browser/sessionGridLayout.test.ts @@ -19,6 +19,7 @@ import '../../browser/media/workbench.css'; import '../../../workbench/contrib/sessions/browser/parts/media/chatCompositeBar.css'; import '../../../workbench/browser/parts/sessions/media/sessionsPart.css'; import '../../../workbench/contrib/sessions/browser/parts/media/sessionsGridContent.css'; +import '../../../workbench/browser/media/part.css'; suite('Sessions - Grid Layout', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -143,6 +144,62 @@ suite('Sessions - Grid Layout', () => { }); }); + for (const gap of [1, 4, 7, 8, 16]) { + test(`centers thin split-chat sashes and meets adjoining ${gap}px gap midpoints`, () => { + const { grid, a, b, c } = harness(); + const root = document.createElement('div'); + root.className = 'monaco-workbench agent-sessions-workbench'; + root.style.cssText = '--vscode-sash-size: 4px; --vscode-sash-hover-size: 4px; width: 1200px; height: 600px; position: relative;'; + const part = root.appendChild(document.createElement('div')); + part.className = 'part sessionspart'; + part.style.cssText = 'width: 1200px; height: 600px;'; + part.appendChild(grid.element); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + grid.reconcile([a, b, c], 'a'); + grid.layout(1200, 600, 0, 0, false, gap); + const bounds = (view: View) => { + const leaf = view.element.parentElement!; + const rect = leaf.getBoundingClientRect(); + const css = mainWindow.getComputedStyle(leaf); + return { + left: rect.left + Number.parseFloat(css.borderLeftWidth), + right: rect.right - Number.parseFloat(css.borderRightWidth), + top: rect.top + Number.parseFloat(css.borderTopWidth), + bottom: rect.bottom - Number.parseFloat(css.borderBottomWidth), + }; + }; + const aBounds = bounds(a.view); + const bBounds = bounds(b.view); + const cBounds = bounds(c.view); + const gapped = Array.from(grid.element.querySelectorAll(`.monaco-sash.${GRID_GAP_SASH_CLASS}`)) + .map(sash => { + const vertical = sash.classList.contains('vertical'); + const rect = sash.getBoundingClientRect(); + const hover = mainWindow.getComputedStyle(sash, '::before'); + const size = vertical ? rect.width : rect.height; + const center = (vertical ? rect.left : rect.top) + size / 2; + const expectedCenter = vertical ? (aBounds.right + bBounds.left) / 2 : (bBounds.bottom + cBounds.top) / 2; + return { + size, + hoverSize: Number.parseFloat(vertical ? hover.width : hover.height), + centerOffset: center - expectedCenter, + meetsCrossing: vertical || Math.abs(rect.left - (aBounds.right + bBounds.left) / 2) < 0.01, + }; + }); + grid.layout(1200, 600, 0, 0, false, 0); + assert.deepStrictEqual({ + gapped, + cleared: Array.from(grid.element.querySelectorAll('.monaco-sash')).every(sash => !sash.classList.contains(GRID_GAP_SASH_CLASS) + && sash.style.getPropertyValue('--agents-grid-gap-offset') === '' + && !sash.classList.contains('workbench-sash-start-at-gap') && !sash.classList.contains('workbench-sash-end-at-gap')), + }, { + gapped: Array.from({ length: 2 }, () => ({ size: 4, hoverSize: 4, centerOffset: 0, meetsCrossing: true })), + cleared: true, + }); + }); + } + test('hides the gripper when a constrained session sash is disabled', () => { const { grid, a, b } = harness(); const workbench = mainWindow.document.createElement('div'); diff --git a/src/vs/sessions/test/browser/sessionView.test.ts b/src/vs/sessions/test/browser/sessionView.test.ts index 6eacc7aae935..492ece2e2b30 100644 --- a/src/vs/sessions/test/browser/sessionView.test.ts +++ b/src/vs/sessions/test/browser/sessionView.test.ts @@ -8,6 +8,8 @@ import { $, append, EventType } from '../../../base/browser/dom.js'; import { SessionView } from '../../../workbench/contrib/sessions/browser/parts/sessionView.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; +import { Emitter } from '../../../base/common/event.js'; +import { IViewSize } from '../../../base/browser/ui/grid/grid.js'; import { constObservable, disposableObservableValue, observableValue } from '../../../base/common/observable.js'; import { mock } from '../../../base/test/common/mock.js'; import { ISession, ISessionPreparationProgress, SessionStatus } from '../../../workbench/services/sessions/common/session.js'; @@ -417,7 +419,7 @@ suite('Sessions - Session View', () => { const header = append(headerHost, $('.chat-composite-bar.session-header-bar')); const action = append(header, $('button')); const content = append(session, $('.session-view-content')); - const view = append(content, $('.chat-view')); + const view = append(content, $('.chat-view.sessions-chat')); const chat = append(view, $('.interactive-session')); const list = append(chat, $('.interactive-list')); const timeline = append(chat, $('.prompt-timeline-rail')); @@ -573,6 +575,7 @@ suite('Sessions - Session View', () => { const groupsLayout: number[] = []; const view: SessionView = Object.assign(Object.create(SessionView.prototype), { _headerHeight: observableValue('headerHeight', 0), + _onDidChange: disposables.add(new Emitter()), element, _isPartVisible: true, _isLeafVisible: true, @@ -601,8 +604,11 @@ suite('Sessions - Session View', () => { const header = { visible: true, height: 35 }; const element = document.createElement('div'); const centeredContentContainer = document.createElement('div'); + const onDidChange = disposables.add(new Emitter()); const view: SessionView = Object.assign(Object.create(SessionView.prototype), { _headerHeight: observableValue('headerHeight', 0), + _onDidChange: onDidChange, + onDidChange: onDidChange.event, element, _isPartVisible: true, _isLeafVisible: true, @@ -616,6 +622,9 @@ suite('Sessions - Session View', () => { _standaloneView: { get: () => undefined }, _preparationView: constObservable(undefined), }); + // The session grid re-reads the minimum height, which includes the header, when the view reports a constraint change. + const minimumHeights = [view.minimumHeight]; + disposables.add(view.onDidChange(size => minimumHeights.push(size === undefined ? view.minimumHeight : -1))); view.layoutContainer(1200, 800, 10, 20); const beforeContents = { calls: layouts.length, headerWidth: centeredContentContainer.style.width }; view.layoutContents(); @@ -630,7 +639,7 @@ suite('Sessions - Session View', () => { view.layoutContents(); view.layout(1000, 0, 30, 40); view.layout(1000, 700, 30, 40); - assert.deepStrictEqual({ beforeContents, layouts }, { + assert.deepStrictEqual({ beforeContents, layouts, minimumHeights }, { beforeContents: { calls: 0, headerWidth: '1200px' }, layouts: [ [1200, 765, 45, 20, 0], @@ -639,6 +648,7 @@ suite('Sessions - Session View', () => { [1000, 700, 30, 40, 0], [1000, 700, 30, 40, 0], ], + minimumHeights: [200, 235, 245, 200], }); }); diff --git a/src/vs/sessions/test/browser/sessionViewTestUtils.ts b/src/vs/sessions/test/browser/sessionViewTestUtils.ts index 8a33e67acc61..b4b1a4797886 100644 --- a/src/vs/sessions/test/browser/sessionViewTestUtils.ts +++ b/src/vs/sessions/test/browser/sessionViewTestUtils.ts @@ -29,6 +29,7 @@ import { ISessionsHostLayoutService } from '../../../workbench/services/sessions import { SessionBranchPickerVisibleContext, SessionEnvironmentPickerVisibleContext, SessionHarnessPickerVisibleContext, SessionIsolationPickerVisibleContext, SessionSyncActionVisibleContext, SessionWorkspacePickerVisibleContext, SessionWorktreePickerVisibleContext } from '../../../workbench/contrib/sessions/common/contextkeys.js'; import { SESSIONS_CHAT_TABS_SETTING, SessionsChatTabsMode } from '../../../workbench/contrib/sessions/common/sessionConfig.js'; import { ISessionsChatBackground, ISessionsChatBackgroundService } from '../../../workbench/contrib/sessions/browser/chatBackgroundService.js'; +import { SessionsChatSurface } from '../../../workbench/contrib/sessions/browser/sessionsChatSurface.js'; import { IChatViewFactory } from '../../../workbench/contrib/sessions/browser/chatViewFactory.js'; import { ISessionsListModelService } from '../../../workbench/contrib/sessions/browser/sessionsListModelService.js'; import { ISessionGridSlot, ISessionsPartService, SessionGridRequest } from '../../../workbench/services/sessions/browser/sessionsPartService.js'; @@ -117,6 +118,9 @@ export function createSessionViewTestServices(store: Pick() { + override createChatBackground(container: HTMLElement, scopedInstantiationService: IInstantiationService) { + return scopedInstantiationService.createInstance(SessionsChatSurface, container); + } override createNewChatView(isNewChatInSession: boolean, _options: IChatViewOptions, scopedInstantiationService?: IInstantiationService): AbstractChatView { return createChatView(isNewChatInSession ? 'newChatInSession' : 'newSession', scopedInstantiationService); } @@ -164,6 +168,7 @@ export function createSessionsPartTestHarness(store: Pick { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -363,6 +364,42 @@ suite('Sessions - Sessions Part', () => { assert.deepStrictEqual(observations, [['698px', '698px'], ['698px', '698px']]); }); + for (const created of [false, true]) { + test(`top bars only show a grab cursor with multiple visible chat panels (created: ${created})`, async () => { + const { part, content, configurationService } = createSessionsPartTestHarness(store); + await configurationService.setUserConfiguration(SESSIONS_CHAT_TABS_SETTING, SessionsChatTabsMode.Single); + const session = createTestActiveSession('session', created, { chatCount: 2 }); + const other = createTestActiveSession('other'); + renderTestPanes(content, [session], session); + part.layout(1202, 802, 0, 0); + const view = content.getSessionView(session.sessionId)!; + const readTopBars = () => Array.from(view.element.querySelectorAll('.session-header-bar, .chat-composite-bar-toolbar-floating')) + .filter(element => mainWindow.getComputedStyle(element).display !== 'none') + .map(element => ({ cursor: mainWindow.getComputedStyle(element).cursor, draggable: element.draggable })); + const single = readTopBars(); + + const [pane] = renderTestPanes(content, [session, other], session); + const multiple = readTopBars(); + content.toggleMaximizePane(pane); + const maximized = readTopBars(); + content.toggleMaximizePane(pane); + const restored = readTopBars(); + renderTestPanes(content, [session], session); + const singleAgain = readTopBars(); + + const normal = [{ cursor: 'default', draggable: true }]; + const grab = [{ cursor: 'grab', draggable: true }]; + assert.deepStrictEqual({ single, multiple, maximized, restored, singleAgain }, { + single: normal, multiple: grab, maximized: normal, restored: grab, singleAgain: normal, + }); + + if (created) { + await view.openChatToSide(session.chats.get()[1].resource); + assert.deepStrictEqual(readTopBars(), [...grab, ...grab]); + } + }); + } + test('aggregates chats actually shown across splits, maximization, and part visibility', async () => { const { part, content } = createSessionsPartTestHarness(store); const splitSession = createTestActiveSession('split', true, { chatCount: 2 }); diff --git a/src/vs/sessions/test/browser/titlebarPart.test.ts b/src/vs/sessions/test/browser/titlebarPart.test.ts index 9fb86b7fd1c8..d6db2f666d42 100644 --- a/src/vs/sessions/test/browser/titlebarPart.test.ts +++ b/src/vs/sessions/test/browser/titlebarPart.test.ts @@ -32,6 +32,12 @@ import '../../../workbench/contrib/modernUI/browser/media/titlebar.css'; // eslint-disable-next-line local/code-import-patterns -- Use the rendered command center's sizing and border. import '../../contrib/sessions/browser/media/sessionsTitleBarWidget.css'; import '../../browser/media/workbench.css'; +// eslint-disable-next-line local/code-import-patterns -- Include the production styles of the right-hand title-bar controls. +import '../../../workbench/contrib/sessionChanges/browser/media/sessionChangesEditor.css'; +// eslint-disable-next-line local/code-import-patterns, local/code-layering -- Include the shared remote-connections control's CSS without its Electron implementation. +import '../../../workbench/contrib/chat/electron-browser/media/tunnelHost.css'; +// eslint-disable-next-line local/code-import-patterns -- Include the production account control's styling. +import '../../contrib/accountMenu/browser/media/accountTitleBarWidget.css'; suite('Sessions - Titlebar Part', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -207,19 +213,69 @@ suite('Sessions - Titlebar Part', () => { const lastIs = (name: string, inset: number) => ({ last: [name], insets: name === 'layout' ? { session: '0px', layout: `${inset}px` } : { session: `${inset}px` }, edge: inset }); assert.deepStrictEqual({ inTitleBar, inStrip, backInTitleBar, mainMarked: mainPart.element.querySelectorAll('.titlebar-last-actions').length }, { - inTitleBar: { default: lastIs('layout', 12), customWindowControls: lastIs('layout', 8), customWindowControlsFullscreen: lastIs('layout', 12) }, - inStrip: { default: lastIs('session', 12), customWindowControls: lastIs('session', 8), customWindowControlsFullscreen: lastIs('session', 12) }, - backInTitleBar: lastIs('layout', 12), + inTitleBar: { default: lastIs('layout', 8), customWindowControls: lastIs('layout', 8), customWindowControlsFullscreen: lastIs('layout', 8) }, + inStrip: { default: lastIs('session', 8), customWindowControls: lastIs('session', 8), customWindowControlsFullscreen: lastIs('session', 8) }, + backInTitleBar: lastIs('layout', 8), mainMarked: 0, }); }); for (const platform of ['mac', 'windows', 'linux', 'web']) { + test(`uses the tighter ${platform} title-bar inset whenever right-side window controls take no space`, () => { + const { part } = createTitlebar(); + const root = append(mainWindow.document.body, $(`.monaco-workbench.agent-sessions-workbench.${platform}`)); + store.add(toDisposable(() => root.remove())); + root.style.cssText = 'width: 800px; --vscode-agents-layout-floatingPanelGap: 4px; --vscode-spacing-size40: 4px; --vscode-spacing-size80: 8px;'; + const content = append(append(root, $('.part.titlebar')), $('.titlebar-container.sessions-titlebar-container.has-center')); + const left = append(content, $('.titlebar-left')); + append(content, $('.titlebar-center')); + const right = append(content, $('.titlebar-right')); + const toolbar = append(right, $('.titlebar-actions-container.titlebar-right-layout-container')); + const controls = append(right, $('.window-controls-container')); + controls.style.width = '138px'; + Reflect.set(part, 'rootContainer', content); + Reflect.set(part, 'rightContent', right); + const read = () => { + updateTitleBarToolBarOverflow.call(part); + return { + hasControls: right.classList.contains('has-window-controls'), + inset: mainWindow.getComputedStyle(toolbar).paddingRight, + }; + }; + const shown = read(); + controls.style.display = 'none'; + const hidden = read(); + controls.style.display = ''; + controls.style.width = '0px'; + const emptyOverlay = read(); + controls.style.width = '138px'; + const restored = read(); + root.classList.add('fullscreen'); + const fullscreen = read(); + root.classList.remove('fullscreen'); + const exitedFullscreen = read(); + left.appendChild(controls); + const controlsOnLeft = read(); + right.appendChild(controls); + const controlsOnRight = read(); + + assert.deepStrictEqual({ shown, hidden, emptyOverlay, restored, fullscreen, exitedFullscreen, controlsOnLeft, controlsOnRight }, { + shown: { hasControls: true, inset: '8px' }, + hidden: { hasControls: false, inset: '4px' }, + emptyOverlay: { hasControls: false, inset: '4px' }, + restored: { hasControls: true, inset: '8px' }, + fullscreen: { hasControls: false, inset: '4px' }, + exitedFullscreen: { hasControls: true, inset: '8px' }, + controlsOnLeft: { hasControls: false, inset: '4px' }, + controlsOnRight: { hasControls: true, inset: '8px' }, + }); + }); + for (const auxiliary of [false, true]) { test(`optically centers ${platform} ${auxiliary ? 'auxiliary' : 'main'} title-bar contents in default density`, () => { const root = append(mainWindow.document.body, $(`.monaco-workbench.agent-sessions-workbench.${platform}`)); store.add(toDisposable(() => root.remove())); - root.style.cssText = 'width: 800px; --vscode-spacing-size20: 2px; --vscode-spacing-size80: 8px; --vscode-commandCenter-border: transparent;'; + root.style.cssText = 'width: 800px; --vscode-spacing-size20: 2px; --vscode-spacing-size80: 8px; --vscode-spacing-size240: 24px; --vscode-commandCenter-border: transparent;'; const grid = auxiliary ? root : append(root, $('.monaco-grid-view')); const titlebar = append(grid, $('.part.titlebar')); const content = append(titlebar, $('.titlebar-container.sessions-titlebar-container.has-center')); @@ -262,7 +318,7 @@ suite('Sessions - Titlebar Part', () => { }); const expected = (height: number, offset: number) => actions.map((_, index) => { - const gap = (height - (index === 2 ? 24 : 22)) / 2; + const gap = (height - (index === 2 || index >= 4 ? 24 : 22)) / 2; return { top: gap + offset, bottom: gap - offset }; }); const defaultDensity = expected(44, 1); @@ -274,7 +330,7 @@ suite('Sessions - Titlebar Part', () => { test(`keeps ${platform} ${auxiliary ? 'auxiliary' : 'main'} title-bar outer spacing unchanged across densities`, () => { const root = append(mainWindow.document.body, $(`.monaco-workbench.agent-sessions-workbench.${platform}`)); store.add(toDisposable(() => root.remove())); - root.style.cssText = 'width: 800px; --vscode-agents-layout-floatingPanelGap: 4px; --vscode-spacing-size80: 8px;'; + root.style.cssText = 'width: 800px; --vscode-agents-layout-floatingPanelGap: 4px; --vscode-spacing-size80: 8px; --vscode-spacing-size40: 4px;'; const grid = auxiliary ? root : append(root, $('.monaco-grid-view')); const titlebar = append(grid, $('.part.titlebar')); titlebar.style.height = '35px'; @@ -289,6 +345,7 @@ suite('Sessions - Titlebar Part', () => { const rightAction = append(rightToolbar, $('.action-label')); rightAction.style.cssText = 'width: 40px; height: 22px; flex-shrink: 0;'; const windowControls = platform === 'windows' ? append(right, $('.window-controls-container')) : undefined; + right.classList.toggle('has-window-controls', !!windowControls); const states = [false, true, false].map(compact => { root.classList.toggle('modern-ui-compact', compact); @@ -316,7 +373,7 @@ suite('Sessions - Titlebar Part', () => { right: outerInset, center: auxiliary ? 400 : 398, leftAction: 0, - rightAction: outerInset + 8 + (windowControls ? 138 : 0), + rightAction: outerInset + (windowControls ? 8 + 138 : 4), rightActionWidth: 40, rightActionHeight: 22, windowControlsRight: windowControls ? outerInset : undefined, @@ -326,6 +383,107 @@ suite('Sessions - Titlebar Part', () => { } } + test('aligns right-hand controls across themes and density transitions without resizing shared workbench controls', () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench')); + store.add(toDisposable(() => root.remove())); + root.style.cssText = 'width: 800px; --vscode-spacing-size20: 2px; --vscode-spacing-size40: 4px; --vscode-spacing-size80: 8px; --vscode-spacing-size240: 24px; --vscode-cornerRadius-small: 4px; --vscode-cornerRadius-medium: 6px; --vscode-codiconFontSize: 16px;'; + const titlebar = append(root, $('.part.titlebar')); + const content = append(titlebar, $('.titlebar-container.sessions-titlebar-container')); + const right = append(content, $('.titlebar-right')); + const toolbar = append(right, $('.titlebar-actions-container.titlebar-right-layout-container')); + const actions = append(append(append(toolbar, $('.monaco-toolbar')), $('.monaco-action-bar')), $('ul.actions-container')); + const changes = append(actions, $('li.action-item.changes-actions-bar')); + const buttonBar = store.add(new ButtonBar(changes)); + const primary = buttonBar.addButton({}); + primary.label = 'Create PR'; + const split = buttonBar.addButtonWithDropdown({ actions: [], contextMenuProvider: { showContextMenu: () => { } } }); + split.label = 'Sync Changes'; + const secondary = buttonBar.addButton({ secondary: true }); + secondary.element.classList.add('monaco-text-button', 'codicon'); + const remote = append(append(actions, $('li.action-item')), $('a.action-label.codicon.tunnel-host-toggle')); + append(append(remote, $('span.tunnel-host-icon')), $('span.codicon')); + const layout = append(append(actions, $('li.action-item')), $('a.action-label.codicon')); + const account = append(actions, $('li.action-item.sessions-account-titlebar-widget')); + const avatar = append(account, $('img.sessions-account-titlebar-widget-avatar.visible')); + const controls = [primary.element, split.element, secondary.element, remote, layout, account]; + const read = (element: HTMLElement) => { + const bounds = element.getBoundingClientRect(); + const style = mainWindow.getComputedStyle(element); + return { height: bounds.height, radius: style.borderRadius }; + }; + const states = ['vs', 'vs-dark', 'hc-black', 'hc-light'].flatMap(theme => { + root.classList.add(theme); + const states = [false, true, false].map(compact => { + root.classList.toggle('modern-ui-compact', compact); + titlebar.style.height = `${compact ? 35 : 44}px`; + return { + controls: controls.map(read), + iconWidths: [secondary.element, remote, layout, account].map(element => element.getBoundingClientRect().width), + gap: mainWindow.getComputedStyle(actions).gap, + avatar: read(avatar), + splitCorners: [...split.element.querySelectorAll('.monaco-button')].map(element => mainWindow.getComputedStyle(element).borderRadius), + splitIconAlignment: mainWindow.getComputedStyle(split.element.querySelector('.monaco-dropdown-button')!).justifyContent, + }; + }); + root.classList.remove(theme); + return states; + }); + const shared = append(mainWindow.document.body, $('.monaco-workbench')); + store.add(toDisposable(() => shared.remove())); + shared.style.setProperty('--vscode-cornerRadius-medium', '6px'); + const sharedActions = append(append(shared, $('.monaco-action-bar')), $('li.action-item')); + const sharedAction = append(sharedActions, $('a.action-label.codicon')); + const sharedRemote = append(sharedActions, $('a.action-label.codicon.tunnel-host-toggle')); + sharedRemote.style.setProperty('--vscode-cornerRadius-small', '4px'); + + assert.deepStrictEqual({ states, shared: read(sharedAction), sharedRemoteHeight: sharedRemote.getBoundingClientRect().height }, { + states: Array.from({ length: 12 }, () => ({ + controls: controls.map((_, index) => ({ height: 24, radius: index === 1 ? '0px' : '4px' })), + iconWidths: [24, 24, 24, 24], + gap: '4px', + avatar: { height: 18, radius: '50%' }, + splitCorners: ['4px 0px 0px 4px', '0px 4px 4px 0px'], + splitIconAlignment: 'center', + })), + shared: { height: 22, radius: '6px' }, + sharedRemoteHeight: 16, + }); + }); + + test('keeps profile feedback immediate and badges stationary across motion settings', () => { + const parent = append(mainWindow.document.body, $('div')); + store.add(toDisposable(() => parent.remove())); + const root = append(parent, $('.monaco-workbench.agent-sessions-workbench')); + const account = append(root, $('.action-item.sessions-account-titlebar-widget', { tabindex: '0' })); + const parts = [ + account, + append(account, $('.sessions-account-titlebar-widget-icon')), + append(account, $('.sessions-account-titlebar-widget-label')), + append(account, $('.sessions-account-titlebar-widget-badge')), + ]; + const states = [parent, root].flatMap(motionContainer => ['monaco-enable-motion', 'monaco-reduce-motion', 'monaco-enable-motion'].flatMap(motion => { + motionContainer.classList.add(motion); + const states = [false, true, false].map(menuVisible => { + account.classList.toggle('menu-visible', menuVisible); + if (menuVisible) { + account.focus(); + } else { + account.blur(); + } + return parts.map(element => { + const style = mainWindow.getComputedStyle(element); + return { transitionDuration: style.transitionDuration, animationName: style.animationName, transform: style.transform }; + }); + }); + motionContainer.classList.remove(motion); + return states; + })); + + assert.deepStrictEqual(states, Array.from({ length: 18 }, () => parts.map(() => ({ + transitionDuration: '0s', animationName: 'none', transform: 'none', + })))); + }); + for (const platform of ['windows', 'linux']) { for (const auxiliary of [false, true]) { test(`preserves ${platform} ${auxiliary ? 'auxiliary' : 'main'} window-control edge targets across densities and zoom levels`, () => { diff --git a/src/vs/sessions/test/browser/vscodeActions.test.ts b/src/vs/sessions/test/browser/vscodeActions.test.ts index 80cb4e29ab5a..d0007748a3de 100644 --- a/src/vs/sessions/test/browser/vscodeActions.test.ts +++ b/src/vs/sessions/test/browser/vscodeActions.test.ts @@ -9,10 +9,14 @@ import { URI } from '../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { agentHostAuthority, toAgentHostUri } from '../../../platform/agentHost/common/agentHostUri.js'; -import { IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostEntryType } from '../../../platform/agentHost/common/remoteAgentHostService.js'; +import { getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostEntryType } from '../../../platform/agentHost/common/remoteAgentHostService.js'; +import { remoteAgentHostSessionTypeId } from '../../../platform/agentHost/common/agentHostSessionType.js'; import { IAgentHostConnectionsService } from '../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IRemoteAgentHostLocationPreferenceService, RemoteAgentHostLocationPreference } from '../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { ISSHAgentHostConnection, ISSHRemoteAgentHostService } from '../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService } from '../../../platform/agentHost/common/tunnelAgentHost.js'; import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INotificationService } from '../../../platform/notification/common/notification.js'; import { IOpenerService } from '../../../platform/opener/common/opener.js'; import { IProductService } from '../../../platform/product/common/productService.js'; import { NullTelemetryService } from '../../../platform/telemetry/common/telemetryUtils.js'; @@ -62,6 +66,8 @@ suite('Web Open in Editor', () => { getEntryByAddress: () => ({ name: 'Remote host', connection }), })); instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ resolveSessionResourceIdentity: () => undefined })); + instantiationService.stub(IRemoteAgentHostLocationPreferenceService, upcastPartial({ getPreference: () => undefined })); + instantiationService.stub(ISSHRemoteAgentHostService, upcastPartial({ connections: [] })); instantiationService.stub(ITunnelAgentHostService, upcastPartial({ getSelectedServerType: () => undefined })); instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(IProductService, upcastPartial({ urlProtocol: 'vscode-test' })); @@ -91,6 +97,59 @@ suite('Web Open in Editor', () => { }]); }); } + + for (const [connection, serverType, preference] of [ + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'standalone', undefined], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', undefined], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', 'editor'], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', 'dedicated'], + [{ type: RemoteAgentHostEntryType.WSL, address: 'wsl:Ubuntu', distro: 'Ubuntu' }, undefined, undefined], + [{ type: RemoteAgentHostEntryType.DevContainer, address: 'devcontainer:host', hostPath: '/source/project' }, undefined, undefined], + ] satisfies [IRemoteAgentHostEntry['connection'], ISSHAgentHostConnection['serverType'], RemoteAgentHostLocationPreference | undefined][]) { + test(`hands off ${connection.type} sessions when the editor follows the selected host (${serverType ?? 'standalone'}, ${preference ?? 'no preference'})`, async () => { + const instantiationService = store.add(new TestInstantiationService()); + const entry = { name: 'Remote host', connection }; + const address = getEntryAddress(entry); + const authority = agentHostAuthority(address); + const folder = toAgentHostUri(URI.file('/project'), authority); + const resource = URI.from({ scheme: remoteAgentHostSessionTypeId(authority, 'copilotcli'), path: '/session', fragment: 'chat' }); + const chat = upcastPartial({ + resource, + workspace: constObservable(upcastPartial({ folders: [{ workingDirectory: folder, root: folder, name: 'project', description: undefined }] })), + }); + const session = upcastPartial({ resource, providerId: 'test', activeChat: constObservable(chat) }); + const provider: ISessionsProvider = upcastPartial({ id: 'agenthost-test', remoteAddress: address }); + const sessions: (string | null)[] = []; + const notifications: string[] = []; + instantiationService.stub(ISessionsProvidersService, upcastPartial({ getProvider: () => provider as T })); + instantiationService.stub(IRemoteAgentHostService, upcastPartial({ getEntryByAddress: () => entry })); + instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ + resolveSessionResourceIdentity: () => ({ connectionAuthority: authority, backendSession: URI.parse('copilotcli:/session') }), + })); + instantiationService.stub(IRemoteAgentHostLocationPreferenceService, upcastPartial({ getPreference: key => key === address ? preference : undefined })); + instantiationService.stub(ISSHRemoteAgentHostService, upcastPartial({ + connections: [upcastPartial({ localAddress: address, serverType })], + })); + instantiationService.stub(ITunnelAgentHostService, upcastPartial({ getSelectedServerType: () => undefined })); + instantiationService.stub(INotificationService, upcastPartial({ info: message => { notifications.push(String(message)); } })); + instantiationService.stub(ITelemetryService, NullTelemetryService); + instantiationService.stub(IProductService, upcastPartial({ urlProtocol: 'vscode-test' })); + instantiationService.stub(IOpenerService, upcastPartial({ + open: async resource => { + sessions.push(new URLSearchParams((typeof resource === 'string' ? URI.parse(resource) : resource).query).get('session')); + return true; + }, + })); + + await instantiationService.invokeFunction(accessor => new OpenInVSCodeAction().run(accessor, { session, chat })); + + const sharesAgentHost = serverType !== 'editor' || preference === 'editor'; + assert.deepStrictEqual({ sessions, notifications }, { + sessions: [sharesAgentHost ? 'agent-host-copilotcli:/session#chat' : null], + notifications: !sharesAgentHost ? ['The session\'s folder was opened in a new editor window, but the session can\'t be opened there. This window is connected to a different agent host on the remote machine than the one its editor windows use.'] : [], + }); + }); + } }); suite('Open in Editor in Agents windows', () => { diff --git a/src/vs/sessions/test/browser/workbench.test.ts b/src/vs/sessions/test/browser/workbench.test.ts index 176aa943dd19..b3330a6ff400 100644 --- a/src/vs/sessions/test/browser/workbench.test.ts +++ b/src/vs/sessions/test/browser/workbench.test.ts @@ -151,6 +151,7 @@ suite('Sessions - Workbench', () => { const createDesktopGridDescriptor = Reflect.get(Workbench.prototype, 'createDesktopGridDescriptor') as (this: IGridDescriptorTestHarness, width: number, height: number) => TestSerializedGrid; const loadPanelAlignment = Reflect.get(Workbench.prototype, '_loadPanelAlignment') as (this: Pick, storageService: { get(key: string, scope: StorageScope): string | undefined }) => PanelAlignment; const setPanelAlignment = Workbench.prototype.setPanelAlignment as (this: IPanelAlignmentTestHarness, alignment: PanelAlignment) => void; + const registerEditorPaneVisibilityClass = Reflect.get(Workbench.prototype, '_registerEditorPaneVisibilityClass') as (this: object, editorPart: { readonly onDidVisibilityChange: BaseEvent }) => void; const registerGridMaximizationListener = Reflect.get(Workbench.prototype, '_registerGridMaximizationListener') as (this: { workbenchGrid: Pick; _register(disposable: T): T; @@ -876,6 +877,30 @@ suite('Sessions - Workbench', () => { }); }); + test('updates the editor pane class when the grid shows or hides the side pane node', () => { + const disposables = new DisposableStore(); + const editorPartVisibility = disposables.add(new Emitter()); + const classToggles: string[] = []; + let editorNodeVisible = false; + const host = { + workbenchGrid: { isViewVisible: () => editorNodeVisible }, + editorPartView: {}, + mainContainer: { classList: { toggle: (name: string, force: boolean) => classToggles.push(`${name}:${force}`) } }, + _register: (disposable: T) => disposables.add(disposable), + _updateEditorPaneVisibilityClass: Reflect.get(Workbench.prototype, '_updateEditorPaneVisibilityClass'), + isEditorPaneVisible: isDesktopEditorPaneVisible, + }; + + registerEditorPaneVisibilityClass.call(host, { onDidVisibilityChange: editorPartVisibility.event }); + editorNodeVisible = true; + editorPartVisibility.fire(true); + editorNodeVisible = false; + editorPartVisibility.fire(false); + disposables.dispose(); + + assert.deepStrictEqual(classToggles, ['noeditorpane:false', 'noeditorpane:true']); + }); + test('reads the desktop editor grid node visibility', () => { const host = createHost({ single: true, partVisibility: { editor: false, auxiliaryBar: true } }) as ITestWorkbench & { workbenchGrid: { isViewVisible(view: object): boolean }; @@ -1193,6 +1218,55 @@ suite('Sessions - Workbench', () => { ]); }); + test('lays out the activity bar with equal gaps beside inset frames and the window edge without moving it when details close', () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs.dock-detail-panel')); + root.style.cssText = 'position: relative; width: 800px; height: 200px; --vscode-strokeThickness: 1px;'; + store.add(toDisposable(() => root.remove())); + const frame = append(root, $('div')); + frame.style.cssText = 'position: absolute; top: 0; height: 200px;'; + const column = store.add(new SessionActivityBarColumn(constObservable(true))); + append(root, column.element); + const strip = append(column.element, $('.session-activity-bar.docked')); + strip.style.width = '30px'; + const host = { + mainContainer: root, + sessionActivityBarColumn: column, + layoutDensity: ModernUIDensity.Default, + layoutPolicy: { viewportClass: { get: () => 'desktop' } }, + _mainContainerDimension: { width: 800, height: 200 }, + isEditorPaneVisible: () => !root.classList.contains('noeditorpane'), + workbenchGrid: { + layout: (width: number, height: number) => { + const inset = root.classList.contains('modern-ui-compact') ? 0 : 1; + column.element.style.cssText = `position: absolute; left: ${width - column.minimumWidth}px; width: ${column.minimumWidth}px; height: ${height}px;`; + frame.style.width = `${width - column.minimumWidth - inset}px`; + }, + }, + }; + Object.setPrototypeOf(host, Workbench.prototype); + const layout = Reflect.get(Workbench.prototype, '_layoutGrid') as (this: typeof host) => void; + const gaps = (classes: string, compact = false) => { + root.classList.remove('noeditorpane', AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS, 'modern-ui-compact'); + root.classList.add(...classes.split(' ')); + host.layoutDensity = compact ? ModernUIDensity.Compact : ModernUIDensity.Default; + layout.call(host); + const bounds = strip.getBoundingClientRect(); + return { gaps: [bounds.left - frame.getBoundingClientRect().right, root.getBoundingClientRect().right - bounds.right], right: bounds.right }; + }; + + assert.deepStrictEqual({ + open: gaps(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS), + closed: gaps('noeditorpane'), + reopened: gaps(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS), + compact: gaps('modern-ui-compact', true), + }, { + open: { gaps: [4, 4], right: root.getBoundingClientRect().right - 4 }, + closed: { gaps: [4, 4], right: root.getBoundingClientRect().right - 4 }, + reopened: { gaps: [4, 4], right: root.getBoundingClientRect().right - 4 }, + compact: { gaps: [0, 0], right: root.getBoundingClientRect().right }, + }); + }); + test('applies layout density at startup and relayouts changes without changing phone gutters', async () => { const configuration = new TestConfigurationService({ [LayoutSettings.MODERN_UI]: false, diff --git a/src/vs/sessions/test/browser/workbenchFactory.test.ts b/src/vs/sessions/test/browser/workbenchFactory.test.ts index 8bf5a4a2e591..358597b29681 100644 --- a/src/vs/sessions/test/browser/workbenchFactory.test.ts +++ b/src/vs/sessions/test/browser/workbenchFactory.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { AgentWorkbenchLayout } from '../../../workbench/services/sessions/browser/sessionsHostLayoutService.js'; import { getSessionsWorkbenchLayout } from '../../browser/workbenchFactory.js'; +import { MobileWorkbench } from '../../browser/mobile/mobileWorkbench.js'; suite('Sessions Workbench Factory', () => { @@ -25,4 +26,11 @@ suite('Sessions Workbench Factory', () => { AgentWorkbenchLayout.Desktop, ]); }); + + test('the experimental entry keeps the mobile workbench kind on desktop-sized hosts', () => { + assert.deepStrictEqual([ + getSessionsWorkbenchLayout(1200, { isWeb: true, isMobile: false }), + MobileWorkbench.prototype.agentWorkbenchLayout, + ], [AgentWorkbenchLayout.Desktop, AgentWorkbenchLayout.Mobile]); + }); }); diff --git a/src/vs/sessions/test/e2e/package.json b/src/vs/sessions/test/e2e/package.json index 4837237bb49f..8fc7af880ecc 100644 --- a/src/vs/sessions/test/e2e/package.json +++ b/src/vs/sessions/test/e2e/package.json @@ -1,7 +1,6 @@ { "name": "sessions-e2e-tests", "version": "0.0.1", - "packageManager": "pnpm@12.16.0", "private": true, "description": "Automated E2E tests for the Agent Sessions window using playwright-cli", "scripts": { diff --git a/src/vs/sessions/test/electron-browser/vscodeActions.test.ts b/src/vs/sessions/test/electron-browser/vscodeActions.test.ts index c46476d548eb..202935bfb07a 100644 --- a/src/vs/sessions/test/electron-browser/vscodeActions.test.ts +++ b/src/vs/sessions/test/electron-browser/vscodeActions.test.ts @@ -13,20 +13,22 @@ import { URI } from '../../../base/common/uri.js'; import { getChatSessionToOpenInEditor, openSessionInVSCode, returnToVSCodeEditor, shouldShowReturnToVSCodeEditor } from '../../electron-browser/actions/vscodeActions.js'; import { IChat, ISession, SessionStatus } from '../../../workbench/services/sessions/common/session.js'; import { ISessionsProvidersService } from '../../../workbench/contrib/sessions/browser/sessionsProvidersService.js'; -import { IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostEntryType } from '../../../platform/agentHost/common/remoteAgentHostService.js'; +import { getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostEntryType } from '../../../platform/agentHost/common/remoteAgentHostService.js'; import { Codicon } from '../../../base/common/codicons.js'; import { agentHostAuthority, agentHostLabelFormatter, toAgentHostUri } from '../../../platform/agentHost/common/agentHostUri.js'; import { IAgentHostSessionsProvider } from '../../../workbench/contrib/sessions/common/agentHostSessionsProvider.js'; import { ISessionsProvider } from '../../../workbench/contrib/sessions/common/sessionsProvider.js'; import { LabelService } from '../../../workbench/services/label/common/labelService.js'; import { workbenchInstantiationService } from '../../../workbench/test/browser/workbenchTestServices.js'; -import { OperatingSystem } from '../../../base/common/platform.js'; import { splitRecentLabel } from '../../../base/common/labels.js'; import { ILabelService } from '../../../platform/label/common/label.js'; import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IAgentHostConnectionsService } from '../../../platform/agentHost/common/agentHostConnectionsService.js'; import { remoteAgentHostSessionTypeId } from '../../../platform/agentHost/common/agentHostSessionType.js'; import { INotificationService } from '../../../platform/notification/common/notification.js'; +import { IRemoteAgentHostLocationPreferenceService, RemoteAgentHostLocationPreference } from '../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { PathStyle } from '../../../platform/agentHost/common/state/protocol/common/commands.js'; +import { ISSHAgentHostConnection, ISSHRemoteAgentHostService } from '../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService, TunnelGatewayServerType } from '../../../platform/agentHost/common/tunnelAgentHost.js'; suite('VS Code Actions', () => { @@ -40,9 +42,11 @@ suite('VS Code Actions', () => { instantiationService = workbenchInstantiationService(undefined, disposables); labelService = disposables.add(instantiationService.createInstance(LabelService)); instantiationService.stub(ILabelService, labelService); - instantiationService.stub(ISessionsProvidersService, new class extends mock() { }()); + instantiationService.stub(ISessionsProvidersService, upcastPartial({ getProvider: () => undefined })); instantiationService.stub(IRemoteAgentHostService, new class extends mock() { }()); instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ resolveSessionResourceIdentity: () => undefined })); + instantiationService.stub(IRemoteAgentHostLocationPreferenceService, upcastPartial({ getPreference: () => undefined })); + instantiationService.stub(ISSHRemoteAgentHostService, upcastPartial({ connections: [] })); instantiationService.stub(ITunnelAgentHostService, upcastPartial({ getSelectedServerType: () => undefined })); notifications = []; instantiationService.stub(INotificationService, upcastPartial({ info: message => { notifications.push(String(message)); } })); @@ -124,20 +128,57 @@ suite('VS Code Actions', () => { }]); }); - test('opens an empty editor window when the active chat has no workspace', async () => { - const calls: { empty: boolean }[] = []; + test('opens an empty local editor window without a remote session workspace', async () => { + const calls: (IOpenEmptyWindowOptions | IWindowOpenable[] | undefined)[] = []; const nativeHostService = new class extends mock() { override async openWindow(toOpen?: IOpenEmptyWindowOptions | IWindowOpenable[]): Promise { - calls.push({ empty: !Array.isArray(toOpen) }); + calls.push(toOpen); } }(); instantiationService.stub(INativeHostService, nativeHostService); + await instantiationService.invokeFunction(openSessionInVSCode, undefined); await instantiationService.invokeFunction(openSessionInVSCode, createSession('no-workspace', true)); + await instantiationService.invokeFunction(openSessionInVSCode, createSession('empty-workspace', true, [])); - assert.deepStrictEqual(calls, [{ empty: true }]); + assert.deepStrictEqual(calls, [undefined, undefined, undefined]); }); + for (const [connection, remoteAuthority] of [ + [{ type: RemoteAgentHostEntryType.SSH, address: 'test:host', hostName: 'host', sshConfigHost: 'my-ssh-host' }, 'ssh-remote+my-ssh-host'], + [{ type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'host', clusterId: 'region' }, 'tunnel+host.region'], + [{ type: RemoteAgentHostEntryType.WSL, address: 'test:host', distro: 'Ubuntu' }, 'wsl+Ubuntu'], + [{ type: RemoteAgentHostEntryType.CloudSandbox, address: 'test:host', environmentId: 'environment' }, undefined], + [{ type: RemoteAgentHostEntryType.WebSocket, address: 'test:host' }, undefined], + ] satisfies [IRemoteAgentHostEntry['connection'], string | undefined][]) { + test(`opens an empty ${remoteAuthority ? 'remote' : 'local'} editor for a folderless ${connection.type} chat`, async () => { + const calls: { toOpen?: IOpenEmptyWindowOptions | IWindowOpenable[]; options?: IOpenWindowOptions }[] = []; + const provider: ISessionsProvider = upcastPartial({ id: 'agenthost-test', remoteAddress: 'test:host' }); + instantiationService.stub(ISessionsProvidersService, { getProvider: () => provider as T }); + instantiationService.stub(IRemoteAgentHostService, { getEntryByAddress: () => ({ name: 'Remote host', connection }) }); + instantiationService.stub(INativeHostService, new class extends mock() { + override async openWindow(toOpen?: IOpenEmptyWindowOptions | IWindowOpenable[], options?: IOpenWindowOptions): Promise { + calls.push({ toOpen, options }); + } + }()); + + await instantiationService.invokeFunction(openSessionInVSCode, createSession('no-workspace', true)); + await instantiationService.invokeFunction(openSessionInVSCode, createSession('empty-workspace', true, [])); + await instantiationService.invokeFunction( + openSessionInVSCode, + createSession('parent', true, [toAgentHostUri(URI.file('/remote/project'), agentHostAuthority('test:host'))]), + createSession('nested', true).mainChat.get(), + ); + + const toOpen = remoteAuthority ? { remoteAuthority } : undefined; + assert.deepStrictEqual(calls, [ + { toOpen, options: undefined }, + { toOpen, options: undefined }, + { toOpen, options: undefined }, + ]); + }); + } + test('opens the clicked nested chat and its workspace instead of the active chat', async () => { const calls: { folders: string[]; chat: string | undefined }[] = []; const session = createSession('parent', true, [URI.file('/active')]); @@ -196,19 +237,24 @@ suite('VS Code Actions', () => { }); } - for (const [connection, selectedServerType] of [ - [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host' }, undefined], - [{ type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'host', clusterId: 'region' }, 'standalone'], - [{ type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'host', clusterId: 'region' }, 'editor'], - [{ type: RemoteAgentHostEntryType.WSL, address: 'wsl:Ubuntu', distro: 'Ubuntu' }, undefined], - [{ type: RemoteAgentHostEntryType.DevContainer, address: 'devcontainer:host', hostPath: '/source/project' }, undefined], - ] satisfies [IRemoteAgentHostEntry['connection'], TunnelGatewayServerType | undefined][]) { - test(`preserves supported ${connection.type} workspace and hands off only the chats of a tunnel's standalone agent host (${selectedServerType ?? 'no gateway'})`, async () => { + for (const [connection, selectedServerType, preference] of [ + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'standalone', undefined], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', undefined], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', 'editor'], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, 'editor', 'dedicated'], + [{ type: RemoteAgentHostEntryType.SSH, address: 'ssh:host', hostName: 'host', sshConfigHost: 'host' }, undefined, undefined], + [{ type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'host', clusterId: 'region' }, 'standalone', undefined], + [{ type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'host', clusterId: 'region' }, 'editor', undefined], + [{ type: RemoteAgentHostEntryType.WSL, address: 'wsl:Ubuntu', distro: 'Ubuntu' }, undefined, undefined], + [{ type: RemoteAgentHostEntryType.DevContainer, address: 'devcontainer:host', hostPath: '/source/project' }, undefined, undefined], + ] satisfies [IRemoteAgentHostEntry['connection'], TunnelGatewayServerType | undefined, RemoteAgentHostLocationPreference | undefined][]) { + test(`preserves supported ${connection.type} workspace and hands off chats from shared hosts (${selectedServerType ?? 'unspecified'}, ${preference ?? 'no preference'})`, async () => { const calls: { folders?: { uri: URI; label: string | undefined }[]; options?: IOpenWindowOptions }[] = []; - const folder = toAgentHostUri(URI.file('/remote/project'), agentHostAuthority('test:host')); const entry: IRemoteAgentHostEntry = { name: 'Remote host', connection }; - const provider: ISessionsProvider = upcastPartial({ id: 'agenthost-test', remoteAddress: 'test:host' }); - const formatter = agentHostLabelFormatter(folder.authority, OperatingSystem.Linux); + const address = getEntryAddress(entry); + const folder = toAgentHostUri(URI.file('/remote/project'), agentHostAuthority(address)); + const provider: ISessionsProvider = upcastPartial({ id: 'agenthost-test', remoteAddress: address }); + const formatter = agentHostLabelFormatter(folder.authority, PathStyle.Posix); disposables.add(labelService.registerFormatter({ ...formatter, formatting: { ...formatter.formatting, workspaceSuffix: entry.name }, @@ -223,11 +269,17 @@ suite('VS Code Actions', () => { instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ resolveSessionResourceIdentity: resource => ({ connectionAuthority: folder.authority, backendSession: resource.with({ scheme: 'copilotcli', fragment: '' }) }), })); + instantiationService.stub(IRemoteAgentHostLocationPreferenceService, upcastPartial({ getPreference: key => key === address ? preference : undefined })); + instantiationService.stub(ISSHRemoteAgentHostService, upcastPartial({ + connections: [ + upcastPartial({ localAddress: 'ssh:another-host', serverType: 'editor' }), + upcastPartial({ localAddress: address, serverType: selectedServerType }), + ], + })); instantiationService.stub(ITunnelAgentHostService, upcastPartial({ getSelectedServerType: () => selectedServerType })); const resource = URI.from({ scheme: remoteAgentHostSessionTypeId(folder.authority, 'copilotcli'), path: '/remote', fragment: 'chat' }); await instantiationService.invokeFunction(openSessionInVSCode, createSession('remote', true, [folder], resource)); - const isTunnel = connection.type === RemoteAgentHostEntryType.Tunnel; - const sharesAgentHost = isTunnel && selectedServerType !== 'editor'; + const sharesAgentHost = selectedServerType !== 'editor' || preference === 'editor'; assert.deepStrictEqual({ folders: calls[0].folders?.map(folder => ({ scheme: folder.uri.scheme, path: folder.uri.path, label: folder.label, title: folder.label && splitRecentLabel(folder.label).name })), options: calls[0].options, @@ -235,9 +287,7 @@ suite('VS Code Actions', () => { }, { folders: [{ scheme: 'vscode-remote', path: '/remote/project', label: '/remote/project [Remote host]', title: 'project [Remote host]' }], options: { forceNewWindow: true, chatSessionToOpen: sharesAgentHost ? URI.from({ scheme: 'agent-host-copilotcli', path: '/remote', fragment: 'chat' }) : undefined }, - notifications: sharesAgentHost ? [] : [isTunnel - ? 'The session\'s folder was opened in a new editor window, but the session can\'t be opened there. This window is connected to a different agent host on the tunnel\'s machine than the one its editor windows use.' - : 'The session\'s folder was opened in a new editor window, but editor windows can\'t open sessions from this remote yet. Only local and tunnel sessions can be opened there.'], + notifications: sharesAgentHost ? [] : ['The session\'s folder was opened in a new editor window, but the session can\'t be opened there. This window is connected to a different agent host on the remote machine than the one its editor windows use.'], }); }); } @@ -246,7 +296,7 @@ suite('VS Code Actions', () => { const calls: { uri: URI; label: string | undefined; title: string | undefined }[][] = []; const authority = agentHostAuthority('test:host'); const folders = ['/c:/remote/project', '/d:/other/repository'].map(path => toAgentHostUri(URI.from({ scheme: 'file', path }), authority)); - const formatter = agentHostLabelFormatter(authority, OperatingSystem.Windows); + const formatter = agentHostLabelFormatter(authority, PathStyle.Windows); disposables.add(labelService.registerFormatter({ ...formatter, formatting: { ...formatter.formatting, workspaceSuffix: 'Windows dev box' }, diff --git a/src/vs/sessions/test/sessions.web.test.internal.ts b/src/vs/sessions/test/sessions.web.test.internal.ts index 7573c7421ebc..a84960f4d21e 100644 --- a/src/vs/sessions/test/sessions.web.test.internal.ts +++ b/src/vs/sessions/test/sessions.web.test.internal.ts @@ -7,6 +7,7 @@ // Mirrors sessions.web.main.internal.ts but uses TestSessionsBrowserMain. import '../sessions.web.main.js'; +import './web.test.terminal.js'; import { create } from './web.test.factory.js'; import { URI } from '../../base/common/uri.js'; import { Event, Emitter } from '../../base/common/event.js'; diff --git a/src/vs/sessions/test/web.test.factory.ts b/src/vs/sessions/test/web.test.factory.ts index 1889be32753d..fc1f2420c16e 100644 --- a/src/vs/sessions/test/web.test.factory.ts +++ b/src/vs/sessions/test/web.test.factory.ts @@ -5,6 +5,7 @@ import { IWorkbench, IWorkbenchConstructionOptions } from '../../workbench/browser/web.api.js'; import { TestSessionsBrowserMain } from './web.test.js'; +import { SessionsWorkbenchFactory } from '../browser/workbenchFactory.js'; import { IDisposable, toDisposable } from '../../base/common/lifecycle.js'; import { mark } from '../../base/common/performance.js'; import { DeferredPromise } from '../../base/common/async.js'; @@ -13,13 +14,16 @@ const workbenchPromise = new DeferredPromise(); /** * Creates the Sessions workbench with mock services for E2E testing. + * + * @param workbenchFactory Optional factory selecting the workbench presentation + * under test (defaults to the classic desktop workbench). */ -export function create(domElement: HTMLElement, options: IWorkbenchConstructionOptions): IDisposable { +export function create(domElement: HTMLElement, options: IWorkbenchConstructionOptions, workbenchFactory?: SessionsWorkbenchFactory): IDisposable { mark('code/didLoadWorkbenchMain'); let instantiatedWorkbench: IWorkbench | undefined = undefined; - new TestSessionsBrowserMain(domElement, options).open().then(workbench => { + new TestSessionsBrowserMain(domElement, options, workbenchFactory).open().then(workbench => { instantiatedWorkbench = workbench; workbenchPromise.complete(workbench); }); diff --git a/src/vs/sessions/test/web.test.terminal.ts b/src/vs/sessions/test/web.test.terminal.ts new file mode 100644 index 000000000000..de6041d4d2d2 --- /dev/null +++ b/src/vs/sessions/test/web.test.terminal.ts @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from '../../base/common/event.js'; +import { Disposable } from '../../base/common/lifecycle.js'; +import { IProcessEnvironment } from '../../base/common/platform.js'; +import { URI } from '../../base/common/uri.js'; +import { Registry } from '../../platform/registry/common/platform.js'; +import { ITerminalBackend, ITerminalBackendRegistry, IProcessReadyEvent, IProcessProperty, ProcessPropertyType, TerminalExtensions, ITerminalProcessOptions, IShellLaunchConfig } from '../../platform/terminal/common/terminal.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../workbench/common/contributions.js'; +import { ITerminalService } from '../../workbench/contrib/terminal/browser/terminal.js'; + +/** + * Registers an in-memory terminal backend so E2E scenarios that open a + * terminal do not need a pty host. Loaded only by the desktop web test entry + * point: the mobile bundle ships no terminal service. + */ +class MockTerminalBackendContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.test.mockTerminalBackend'; + + constructor( + @ITerminalService private readonly terminalService: ITerminalService, + ) { + super(); + this.registerMockTerminalBackend(); + } + + private registerMockTerminalBackend(): void { + const backend = this.createMockTerminalBackend(); + Registry.as(TerminalExtensions.Backend).registerTerminalBackend(backend); + this.terminalService.registerProcessSupport(true); + console.log('[Sessions Web Test] Registered mock terminal backend'); + } + + private createMockTerminalBackend(): ITerminalBackend { + return { + remoteAuthority: undefined, + isResponsive: true, + whenReady: Promise.resolve(), + setReady: () => { }, + onDidRequestDetach: Event.None, + attachToProcess: async () => { throw new Error('Not supported'); }, + attachToRevivedProcess: async () => { throw new Error('Not supported'); }, + listProcesses: async () => [], + getProfiles: async () => [], + getDefaultSystemShell: async () => '/bin/mock-shell', + getShellEnvironment: async () => ({}), + setTerminalLayoutInfo: async () => { }, + getTerminalLayoutInfo: async () => undefined, + reduceConnectionGraceTime: async () => { }, + requestDetachInstance: async () => undefined, + acceptDetachInstanceReply: async () => { }, + persistTerminalState: async () => { }, + createProcess: async (_shellLaunchConfig: IShellLaunchConfig, _cwd: string | URI, _cols: number, _rows: number, _unicodeVersion: string, _env: IProcessEnvironment, _options: ITerminalProcessOptions, _shouldPersist: boolean) => { + const onProcessData = new Emitter(); + const onProcessReady = new Emitter(); + const onProcessExit = new Emitter(); + const onDidChangeHasChildProcesses = new Emitter(); + const onDidChangeProperty = new Emitter>(); + + // Resolve cwd from createProcess arg or shellLaunchConfig + const rawCwd = _cwd || _shellLaunchConfig.cwd; + const cwd = !rawCwd ? '/' : typeof rawCwd === 'string' ? rawCwd : rawCwd.path; + console.log(`[Sessions Web Test] Mock terminal createProcess cwd: '${cwd}' (raw _cwd: '${_cwd}', slc.cwd: '${_shellLaunchConfig.cwd}')`); + + // Fire ready after a microtask so the terminal service can wire up listeners + setTimeout(() => { + onProcessReady.fire({ pid: 1, cwd, windowsPty: undefined }); + }, 0); + + return { + id: 0, + shouldPersist: false, + onProcessData: onProcessData.event, + onProcessReady: onProcessReady.event, + onDidChangeHasChildProcesses: onDidChangeHasChildProcesses.event, + onDidChangeProperty: onDidChangeProperty.event, + onProcessExit: onProcessExit.event, + start: async () => undefined, + shutdown: async () => { }, + input: async () => { }, + sendSignal: () => { }, + resize: () => { }, + clearBuffer: () => { }, + acknowledgeDataEvent: () => { }, + setUnicodeVersion: async () => { }, + getInitialCwd: async () => cwd, + getCwd: async () => cwd, + getLatency: async () => [], + processBinary: async () => { }, + refreshProperty: async (property: ProcessPropertyType) => { throw new Error(`Not supported: ${property}`); }, + updateProperty: async () => { }, + clearUnrespondedRequest: () => { }, + }; + }, + getWslPath: async (original: string, _direction: 'unix-to-win' | 'win-to-unix') => original, + getEnvironment: async () => ({}), + getLatency: async () => [], + getPerformanceMarks: async () => [], + updateTitle: async () => { }, + updateIcon: async () => { }, + setNextCommandId: async () => { }, + restartPtyHost: () => { }, + installAutoReply: async () => { }, + uninstallAllAutoReplies: async () => { }, + onPtyHostUnresponsive: Event.None, + onPtyHostResponsive: Event.None, + onPtyHostRestart: Event.None, + }; + } + +} + +registerWorkbenchContribution2(MockTerminalBackendContribution.ID, MockTerminalBackendContribution, WorkbenchPhase.BlockStartup); diff --git a/src/vs/sessions/test/web.test.ts b/src/vs/sessions/test/web.test.ts index 39c519d869a5..fabd7ee40bad 100644 --- a/src/vs/sessions/test/web.test.ts +++ b/src/vs/sessions/test/web.test.ts @@ -22,21 +22,20 @@ import { URI } from '../../base/common/uri.js'; import { Disposable } from '../../base/common/lifecycle.js'; import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../workbench/common/contributions.js'; import { IChatProgress } from '../../workbench/contrib/chat/common/chatService/chatService.js'; -import { IChatSessionsService, IChatSessionItem, ChatSessionStatus, IChatSessionHistoryItem, IChatSessionItemsDelta } from '../../workbench/contrib/chat/common/chatSessionsService.js'; +import { IChatSessionsService, IChatSessionItem, ChatSessionStatus, IChatSessionHistoryItem, IChatSessionItemsDelta, IChatSessionProviderOptionItem } from '../../workbench/contrib/chat/common/chatSessionsService.js'; import { IGitService, IGitExtensionDelegate, IGitRepository } from '../../workbench/contrib/git/common/gitService.js'; import { IFileService } from '../../platform/files/common/files.js'; -import { ITerminalService } from '../../workbench/contrib/terminal/browser/terminal.js'; -import { ITerminalBackend, ITerminalBackendRegistry, IProcessReadyEvent, IProcessProperty, ProcessPropertyType, TerminalExtensions, ITerminalProcessOptions, IShellLaunchConfig } from '../../platform/terminal/common/terminal.js'; -import { IProcessEnvironment } from '../../base/common/platform.js'; -import { Registry } from '../../platform/registry/common/platform.js'; import { InMemoryFileSystemProvider } from '../../platform/files/common/inMemoryFilesystemProvider.js'; import { VSBuffer } from '../../base/common/buffer.js'; import { SyncDescriptor } from '../../platform/instantiation/common/descriptors.js'; import { getSingletonServiceDescriptors } from '../../platform/instantiation/common/extensions.js'; import { ServiceIdentifier } from '../../platform/instantiation/common/instantiation.js'; -import { IWorkbench } from '../../workbench/browser/web.api.js'; +import { IWorkbench, IWorkbenchConstructionOptions } from '../../workbench/browser/web.api.js'; import { isEqual } from '../../base/common/resources.js'; import { IChatSessionFileChange } from '../../workbench/common/chatSessionFileChange.js'; +import { SessionsWorkbenchFactory } from '../browser/workbenchFactory.js'; +import { IAgentHostFilterService } from '../../workbench/contrib/sessions/common/agentHostFilter.js'; +import { ILanguageModelChatMetadata, ILanguageModelsService } from '../../workbench/contrib/chat/common/languageModels.js'; /** * Mock files pre-seeded in the in-memory file system. These match the @@ -260,13 +259,11 @@ class MockChatAgentContribution extends Disposable implements IWorkbenchContribu constructor( @IChatAgentService private readonly chatAgentService: IChatAgentService, @IChatSessionsService private readonly chatSessionsService: IChatSessionsService, - @ITerminalService private readonly terminalService: ITerminalService, ) { super(); this._register(this._itemsChangedEmitter); this.registerMockAgents(); this.registerMockSessionProvider(); - this.registerMockTerminalBackend(); } /** @@ -434,100 +431,118 @@ class MockChatAgentContribution extends Disposable implements IWorkbenchContribu console.warn(`[Sessions Web Test] Failed to register session provider for ${scheme}:`, err); } } - } - private registerMockTerminalBackend(): void { - const terminalService = this.terminalService; - const backend = this.createMockTerminalBackend(); - Registry.as(TerminalExtensions.Backend).registerTerminalBackend(backend); - terminalService.registerProcessSupport(true); - console.log('[Sessions Web Test] Registered mock terminal backend'); + // Cloud sessions take their model list from the provider's `models` + // option group rather than from registered language models; without it + // the composer reports "No models available" and cannot send. + const mockModel: IChatSessionProviderOptionItem = { id: 'mock-gpt', name: 'Mock GPT', default: true }; + this.chatSessionsService.setOptionGroupsForSessionType('copilot-cloud-agent', 0, [{ + id: 'models', + name: 'Models', + selected: mockModel, + items: [mockModel, { id: 'mock-gpt-mini', name: 'Mock GPT Mini' }], + }]); } +} - private createMockTerminalBackend(): ITerminalBackend { - return { - remoteAuthority: undefined, - isVirtualProcess: false, - isResponsive: true, - whenReady: Promise.resolve(), - setReady: () => { }, - onDidRequestDetach: Event.None, - attachToProcess: async () => { throw new Error('Not supported'); }, - attachToRevivedProcess: async () => { throw new Error('Not supported'); }, - listProcesses: async () => [], - getProfiles: async () => [], - getDefaultProfile: async () => undefined, - getDefaultSystemShell: async () => '/bin/mock-shell', - getShellEnvironment: async () => ({}), - setTerminalLayoutInfo: async () => { }, - getTerminalLayoutInfo: async () => undefined, - reduceConnectionGraceTime: () => { }, - requestDetachInstance: () => { }, - acceptDetachInstanceReply: () => { }, - persistTerminalState: () => { }, - createProcess: async (_shellLaunchConfig: IShellLaunchConfig, _cwd: string | URI, _cols: number, _rows: number, _unicodeVersion: string, _env: IProcessEnvironment, _options: ITerminalProcessOptions, _shouldPersist: boolean) => { - const onProcessData = new Emitter(); - const onProcessReady = new Emitter(); - const onProcessExit = new Emitter(); - const onDidChangeHasChildProcesses = new Emitter(); - const onDidChangeProperty = new Emitter>(); - - // Resolve cwd from createProcess arg or shellLaunchConfig - const rawCwd = _cwd || _shellLaunchConfig.cwd; - const cwd = !rawCwd ? '/' : typeof rawCwd === 'string' ? rawCwd : rawCwd.path; - console.log(`[Sessions Web Test] Mock terminal createProcess cwd: '${cwd}' (raw _cwd: '${_cwd}', slc.cwd: '${_shellLaunchConfig.cwd}')`); - - // Fire ready after a microtask so the terminal service can wire up listeners - setTimeout(() => { - onProcessReady.fire({ pid: 1, cwd, windowsPty: undefined }); - }, 0); - - return { - id: 0, - shouldPersist: false, - onProcessData: onProcessData.event, - onProcessReady: onProcessReady.event, - onDidChangeHasChildProcesses: onDidChangeHasChildProcesses.event, - onDidChangeProperty: onDidChangeProperty.event, - onProcessExit: onProcessExit.event, - start: async () => undefined, - shutdown: async () => { }, - input: async () => { }, - resize: () => { }, - clearBuffer: () => { }, - acknowledgeDataEvent: () => { }, - setUnicodeVersion: async () => { }, - getInitialCwd: async () => cwd, - getCwd: async () => cwd, - getLatency: async () => [], - processBinary: async () => { }, - refreshProperty: async (property: ProcessPropertyType) => { throw new Error(`Not supported: ${property}`); }, - updateProperty: async () => { }, - clearUnrespondedRequest: () => { }, - }; - }, - getWslPath: async (original: string, _direction: 'unix-to-win' | 'win-to-unix') => original, - getEnvironment: async () => ({}), - getLatency: async () => [], - getPerformanceMarks: () => [], - updateTitle: async () => { }, - updateIcon: async () => { }, - setNextCommandId: async () => { }, - restartPtyHost: () => { }, - installAutoReply: async () => { }, - uninstallAllAutoReplies: async () => { }, - onPtyHostUnresponsive: Event.None, - onPtyHostResponsive: Event.None, - onPtyHostRestart: Event.None, - onPtyHostConnected: Event.None, - } as unknown as ITerminalBackend; +// Register the contribution so it runs during workbench startup +registerWorkbenchContribution2(MockChatAgentContribution.ID, MockChatAgentContribution, WorkbenchPhase.BlockStartup); + +// --------------------------------------------------------------------------- +// MockAgentHostGroupContribution — the web composer hides behind a "connect a +// host" empty state until at least one agent host is known. Declare a mock +// host that creates sessions through the mock Copilot provider so the E2E +// harness reaches the composer without a tunnel. +// --------------------------------------------------------------------------- + +class MockAgentHostGroupContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.test.mockAgentHostGroup'; + + constructor( + @IAgentHostFilterService agentHostFilterService: IAgentHostFilterService, + ) { + super(); + this._register(agentHostFilterService.registerHostGroup({ + id: 'mock-host', + label: 'Mock Host', + connectable: false, + sessionCreationProviderId: 'default-copilot', + })); + console.log('[Sessions Web Test] Registered mock agent host group'); } +} + +registerWorkbenchContribution2(MockAgentHostGroupContribution.ID, MockAgentHostGroupContribution, WorkbenchPhase.BlockStartup); + +// --------------------------------------------------------------------------- +// MockLanguageModelContribution — the composer's Send button stays disabled +// until a user-selectable model exists. Register a mock vendor and one model +// that streams a canned reply. +// --------------------------------------------------------------------------- + +class MockLanguageModelContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.test.mockLanguageModel'; + constructor( + @ILanguageModelsService languageModelsService: ILanguageModelsService, + ) { + super(); + + const vendor = 'mock-vendor'; + const metadata: ILanguageModelChatMetadata = { + extension: new ExtensionIdentifier('vscode.sessions-e2e-mock'), + name: 'Mock GPT', + id: 'mock-gpt', + vendor, + version: '1.0', + family: 'mock', + maxInputTokens: 128000, + maxOutputTokens: 8192, + isDefaultForLocation: { [ChatAgentLocation.Chat]: true }, + isUserSelectable: true, + capabilities: { agentMode: true, toolCalling: true, vision: false }, + // Expose a reasoning-effort setting so the model picker (and the + // phone's Configure Session sheet) show a Thinking section. + configurationSchema: { + type: 'object', + properties: { + reasoningEffort: { + type: 'string', + group: 'navigation', + enum: ['low', 'medium', 'high'], + enumItemLabels: ['Low', 'Medium', 'High'], + default: 'medium', + description: 'How much reasoning the mock model does before answering.', + }, + }, + }, + }; + languageModelsService.deltaLanguageModelChatProviderDescriptors([{ vendor, displayName: 'Mock Vendor', configuration: undefined, managementCommand: undefined, when: undefined }], []); + // Models are resolved when the provider reports a change, not when it + // registers, so announce once after registering or the picker stays empty. + const onDidChange = this._register(new Emitter()); + this._register(languageModelsService.registerLanguageModelProvider(vendor, { + onDidChange: onDidChange.event, + provideLanguageModelChatInfo: async () => [{ metadata, identifier: `${vendor}/${metadata.id}` }], + sendChatRequest: async () => ({ + stream: (async function* () { + yield { type: 'text', value: 'This is a mock model response.' } as const; + })(), + result: Promise.resolve(undefined), + }), + provideTokenCount: async (_modelId, message) => (typeof message === 'string' ? message : JSON.stringify(message)).length / 4, + })); + onDidChange.fire(); + void languageModelsService.selectLanguageModels({ vendor }).then(ids => { + console.log(`[Sessions Web Test] Registered mock language model; resolved ${ids.length} model(s): ${ids.join(', ')}; known ids: ${languageModelsService.getLanguageModelIds().join(', ')}`); + }); + } } -// Register the contribution so it runs during workbench startup -registerWorkbenchContribution2(MockChatAgentContribution.ID, MockChatAgentContribution, WorkbenchPhase.BlockStartup); +registerWorkbenchContribution2(MockLanguageModelContribution.ID, MockLanguageModelContribution, WorkbenchPhase.BlockStartup); // --------------------------------------------------------------------------- // MockGitService — resolves immediately instead of waiting 10s for delegate @@ -555,6 +570,19 @@ export class TestSessionsBrowserMain extends SessionsBrowserMain { private _savedDescriptors: [ServiceIdentifier, SyncDescriptor][] = []; + /** + * @param workbenchFactory Creates the workbench under test. Defaults to the + * classic desktop workbench (never the single-pane variant) so existing E2E + * scenarios keep their layout; the mobile test entry passes the mobile factory. + */ + constructor( + domElement: HTMLElement, + configuration: IWorkbenchConstructionOptions, + workbenchFactory: SessionsWorkbenchFactory = (parent, options, serviceCollection, logService) => new SessionsWorkbench(parent, options, serviceCollection, logService), + ) { + super(domElement, configuration, workbenchFactory); + } + override async open(): Promise { // Patch the global singleton registry BEFORE super.open() calls initServices(). // getSingletonServiceDescriptors() returns the mutable internal array, so @@ -591,10 +619,17 @@ export class TestSessionsBrowserMain extends SessionsBrowserMain { private preseedFolder(storageService: IStorageService): void { const mockFolderUri = URI.from({ scheme: 'mock-fs', authority: 'mock-repo', path: '/mock-repo' }); + // The Copilot provider only resolves `file:` and GitHub workspaces, so also + // seed a GitHub-shaped repository the web picker can list and create a + // cloud session for. + const mockGitHubRepoUri = URI.from({ scheme: 'github-remote-file', authority: 'github', path: '/mock-owner/mock-repo/HEAD' }); const providerId = 'default-copilot'; // Seed recent workspaces so resolveWorkspace() can hydrate the selection - const recentWorkspaces = JSON.stringify([{ uri: mockFolderUri.toJSON(), providerId, checked: true }]); + const recentWorkspaces = JSON.stringify([ + { uri: mockFolderUri.toJSON(), providerId, checked: true }, + { uri: mockGitHubRepoUri.toJSON(), providerId, checked: false }, + ]); storageService.store('sessions.recentlyPickedWorkspaces', recentWorkspaces, StorageScope.PROFILE, StorageTarget.MACHINE); console.log(`[Sessions Web Test] Pre-seeded folder: ${mockFolderUri.toString()}`); @@ -606,6 +641,6 @@ export class TestSessionsBrowserMain extends SessionsBrowserMain { this.preseedFolder(serviceCollection.get(IStorageService) as IStorageService); - return new SessionsWorkbench(domElement, undefined, serviceCollection, logService); + return super.createWorkbench(domElement, serviceCollection, logService); } } diff --git a/src/vs/workbench/api/browser/mainThreadAuthentication.ts b/src/vs/workbench/api/browser/mainThreadAuthentication.ts index 6aaccb13dbb2..d1baeafb4f24 100644 --- a/src/vs/workbench/api/browser/mainThreadAuthentication.ts +++ b/src/vs/workbench/api/browser/mainThreadAuthentication.ts @@ -132,7 +132,7 @@ class MainThreadAuthenticationProviderWithChallenges extends MainThreadAuthentic export class MainThreadAuthentication extends Disposable implements MainThreadAuthenticationShape { private readonly _proxy: Proxied; - private readonly _registrations = this._register(new DisposableMap()); + private readonly _registrations = this._register(new DisposableMap; dispose(): void }>()); private _sentProviderUsageEvents = new Set(); private _suppressUnregisterEvent = false; @@ -162,6 +162,7 @@ export class MainThreadAuthentication extends Disposable implements MainThreadAu this._register(this.authenticationService.onDidChangeSessions(e => this._proxy.$onDidChangeAuthenticationSessions(e.providerId, e.label))); this._register(this.authenticationService.onDidUnregisterAuthenticationProvider(e => { if (!this._suppressUnregisterEvent) { + this._registrations.deleteAndDispose(e.id); this._proxy.$onDidUnregisterAuthenticationProvider(e.id); } })); @@ -249,7 +250,6 @@ export class MainThreadAuthentication extends Disposable implements MainThreadAu this.telemetryService.publicLog2<{ id: string }, AuthProviderNotDeclaredClassification>('authentication.providerNotDeclared', { id }); } const emitter = new Emitter(); - this._registrations.set(id, emitter); const supportedAuthorizationServerUris = (supportedAuthorizationServers ?? []).map(i => URI.revive(i)); const provider = supportsChallenges @@ -271,18 +271,24 @@ export class MainThreadAuthentication extends Disposable implements MainThreadAu resourceServer ? URI.revive(resourceServer) : undefined, emitter ); + this._registrations.set(id, { + emitter, + dispose: () => { + emitter.dispose(); + // Suppress the owning host's unregister event during cleanup. + this._suppressUnregisterEvent = true; + try { + this.authenticationService.unregisterAuthenticationProvider(id); + } finally { + this._suppressUnregisterEvent = false; + } + } + }); this.authenticationService.registerAuthenticationProvider(id, provider); } async $unregisterAuthenticationProvider(id: string): Promise { this._registrations.deleteAndDispose(id); - // The ext host side already unregisters the provider, so we can suppress the event here. - this._suppressUnregisterEvent = true; - try { - this.authenticationService.unregisterAuthenticationProvider(id); - } finally { - this._suppressUnregisterEvent = false; - } } async $ensureProvider(id: string): Promise { @@ -292,9 +298,9 @@ export class MainThreadAuthentication extends Disposable implements MainThreadAu } async $sendDidChangeSessions(providerId: string, event: Dto): Promise { - const obj = this._registrations.get(providerId); - if (obj instanceof Emitter) { - obj.fire({ + const registration = this._registrations.get(providerId); + if (registration) { + registration.emitter.fire({ added: event.added?.map(reviveAuthenticationSession), removed: event.removed?.map(reviveAuthenticationSession), changed: event.changed?.map(reviveAuthenticationSession) diff --git a/src/vs/workbench/api/browser/mainThreadChatAgents2.ts b/src/vs/workbench/api/browser/mainThreadChatAgents2.ts index 4a887e5c8926..be1320de5c70 100644 --- a/src/vs/workbench/api/browser/mainThreadChatAgents2.ts +++ b/src/vs/workbench/api/browser/mainThreadChatAgents2.ts @@ -504,19 +504,25 @@ export class MainThreadChatAgents2 extends Disposable implements MainThreadChatA if (progress.kind === 'beginToolInvocation') { // Begin a streaming tool invocation - this._languageModelToolsService.beginToolCall({ - toolCallId: progress.toolCallId, - toolId: progress.toolName, - chatRequestId: requestId, - sessionResource: chatSession?.sessionResource, - subagentInvocationId: progress.subagentInvocationId, - }); + try { + this._languageModelToolsService.beginToolCall({ + toolCallId: progress.toolCallId, + toolId: progress.toolName, + chatRequestId: requestId, + sessionResource: chatSession?.sessionResource, + subagentInvocationId: progress.subagentInvocationId, + }); + } catch (error) { + this._logService.error(`MainThreadChatAgents2#$handleProgressChunk: Failed to begin tool invocation ${progress.toolCallId}`, error); + } continue; } if (progress.kind === 'updateToolInvocation') { // Update the streaming data for an existing tool invocation - this._languageModelToolsService.updateToolStream(progress.toolCallId, progress.streamData?.partialInput, CancellationToken.None); + this._languageModelToolsService.updateToolStream(progress.toolCallId, progress.streamData?.partialInput, CancellationToken.None).catch(error => { + this._logService.error(`MainThreadChatAgents2#$handleProgressChunk: Failed to update tool invocation ${progress.toolCallId}`, error); + }); continue; } diff --git a/src/vs/workbench/api/browser/mainThreadChatArtifactIntegrations.ts b/src/vs/workbench/api/browser/mainThreadChatArtifactIntegrations.ts index 4c11811ad61f..a5e331afde01 100644 --- a/src/vs/workbench/api/browser/mainThreadChatArtifactIntegrations.ts +++ b/src/vs/workbench/api/browser/mainThreadChatArtifactIntegrations.ts @@ -82,9 +82,9 @@ export class MainThreadChatArtifactIntegrations extends Disposable implements Ma } : {}), createResource: async (match, _context, token) => { const resourceHandle = this.nextResourceHandle++; - const resource = new ExtensionArtifactResource(this.proxy, resourceHandle, (detailsId, canLoadMore, owner) => { + const resource = new ExtensionArtifactResource(this.proxy, resourceHandle, (detailsId, canLoadMore, initial, received, owner) => { const detailsHandle = this.nextDetailsHandle++; - const details = new ExtensionArtifactDetails(this.proxy, resourceHandle, detailsHandle, detailsId, canLoadMore, () => { + const details = new ExtensionArtifactDetails(this.proxy, resourceHandle, detailsHandle, detailsId, canLoadMore, initial, received, () => { this.details.deleteAndLeak(detailsHandle); owner.deleteAndLeak(detailsHandle); }); @@ -263,12 +263,14 @@ class ExtensionArtifactResource extends Disposable { }); private readonly details = this._register(new DisposableMap()); private initialDetails: Readonly> = {}; + /** The details the extension last sent for each details ID, to any of this resource's details models. */ + private readonly latestDetails = new Map(); private actions: readonly ChatArtifactActionDto[] = []; constructor( private readonly proxy: ExtHostChatArtifactIntegrationsShape, readonly handle: number, - private readonly createDetails: (detailsId: string, canLoadMore: boolean, owner: DisposableMap) => ExtensionArtifactDetails, + private readonly createDetails: (detailsId: string, canLoadMore: boolean, initial: ArtifactDetails | undefined, received: (details: ArtifactDetails) => void, owner: DisposableMap) => ExtensionArtifactDetails, release: () => void, ) { super(); @@ -331,9 +333,10 @@ class ExtensionArtifactResource extends Disposable { throw new Error(localize('extensionArtifactDetailsUnavailable', "The artifact details are no longer available.")); } const initial = this.initialDetails[detailsId]; - const details = this.createDetails(detailsId, initial?.canLoadMore ?? false, this.details); - details.accept(initial?.details); - return details; + // A new model shows the latest details until its own arrive, rather than those from when the resource was + // created, so a synchronous read, such as of the item an action runs for, sees items listed since. + return this.createDetails(detailsId, initial?.canLoadMore ?? false, this.latestDetails.get(detailsId) ?? initial?.details, + details => this.latestDetails.set(detailsId, details), this.details); }, activateAutomation: context => activate(context, reason => error.set(reason, undefined)), dispose: () => { }, @@ -359,16 +362,22 @@ class ExtensionArtifactDetails extends Disposable implements IArtifactDetailsMod private readonly handle: number, detailsId: string, canLoadMore: boolean, + initial: ArtifactDetails | undefined, + /** Reports the details the extension sends for this model. */ + private readonly received: (details: ArtifactDetails) => void, release: () => void, ) { super(); this.canLoadMore = canLoadMore; this._register(toDisposable(release)); + if (initial) { + this.value.set(initial, undefined); + } void this.proxy.$acquireDetails(resourceHandle, handle, detailsId).then(result => { if (!this._store.isDisposed) { this.initialized = true; this.canLoadMore = result.canLoadMore; - this.value.set(result.details, undefined); + this.accept(result.details); } }, error => { if (!this._store.isDisposed) { @@ -383,9 +392,10 @@ class ExtensionArtifactDetails extends Disposable implements IArtifactDetailsMod }); } - accept(details: ArtifactDetails | undefined): void { - if (!this._store.isDisposed && details) { + accept(details: ArtifactDetails): void { + if (!this._store.isDisposed) { this.value.set(details, undefined); + this.received(details); } } diff --git a/src/vs/workbench/api/browser/mainThreadDocuments.ts b/src/vs/workbench/api/browser/mainThreadDocuments.ts index 9827a1a573f0..a15dedee6487 100644 --- a/src/vs/workbench/api/browser/mainThreadDocuments.ts +++ b/src/vs/workbench/api/browser/mainThreadDocuments.ts @@ -303,7 +303,8 @@ export class MainThreadDocuments extends Disposable implements MainThreadDocumen associatedResource, languageId: options?.language, initialValue: options?.content, - encoding: options?.encoding + encoding: options?.encoding, + origin: 'extensionApi' }); if (options?.encoding) { await model.setEncoding(options.encoding); diff --git a/src/vs/workbench/api/browser/mainThreadDocumentsAndEditors.ts b/src/vs/workbench/api/browser/mainThreadDocumentsAndEditors.ts index a16c68f6f703..17e82f287939 100644 --- a/src/vs/workbench/api/browser/mainThreadDocumentsAndEditors.ts +++ b/src/vs/workbench/api/browser/mainThreadDocumentsAndEditors.ts @@ -38,11 +38,13 @@ import { IQuickDiffModelService } from '../../contrib/scm/browser/quickDiffModel class TextEditorSnapshot { readonly id: string; + readonly model: ITextModel; constructor( readonly editor: IActiveCodeEditor, ) { - this.id = `${editor.getId()},${editor.getModel().id}`; + this.model = editor.getModel(); + this.id = `${editor.getId()},${this.model.id}`; } } @@ -126,7 +128,7 @@ class MainThreadDocumentAndEditorStateComputer { @IPaneCompositePartService private readonly _paneCompositeService: IPaneCompositePartService, ) { this._modelService.onModelAdded(this._updateStateOnModelAdd, this, this._toDispose); - this._modelService.onModelRemoved(_ => this._updateState(), this, this._toDispose); + this._modelService.onModelRemoved(this._updateStateOnModelRemove, this, this._toDispose); this._editorService.onDidActiveEditorChange(_ => this._updateState(), this, this._toDispose); this._codeEditorService.onCodeEditorAdd(this._onDidAddEditor, this, this._toDispose); @@ -188,6 +190,37 @@ class MainThreadDocumentAndEditorStateComputer { )); } + private _updateStateOnModelRemove(model: ITextModel): void { + if (!this._currentState) { + // too early + this._updateState(); + return; + } + + if (!this._currentState.documents.has(model)) { + // not synchronized (too large, simple widget), nothing to remove + return; + } + + for (const snapshot of this._currentState.textEditors.values()) { + if (snapshot.model === model) { + // an editor shows this model, compute the full state + this._updateState(); + return; + } + } + + // small (fast) delta, avoids recomputing the full state for each + // removed model which is quadratic when many models are disposed at once + this._currentState.documents.delete(model); + + this._onDidChangeState(new DocumentAndEditorStateDelta( + [model], [], + [], [], + undefined, undefined + )); + } + private _updateState(widgetFocusCandidate?: ICodeEditor): void { // models: ignore too large models diff --git a/src/vs/workbench/api/browser/mainThreadGitHub.ts b/src/vs/workbench/api/browser/mainThreadGitHub.ts index fe66622617a6..b125794d8196 100644 --- a/src/vs/workbench/api/browser/mainThreadGitHub.ts +++ b/src/vs/workbench/api/browser/mainThreadGitHub.ts @@ -21,7 +21,7 @@ import { extHostNamedCustomer, IExtHostContext } from '../../services/extensions import { IWorkbenchGitHubService } from '../../services/github/common/githubService.js'; import { GitHubErrorCodeDto, GitHubResultDto, IGitHubCreateGistDto, IGitHubErrorDto, IGitHubGistDto, MainContext, MainThreadGitHubShape } from '../common/extHost.protocol.js'; -/** The initial proposal binds only GitHub.com sessions; Enterprise sessions are not selectable. */ +/** The internal module binds only GitHub.com sessions; Enterprise sessions are not selectable. */ const gitHubProviderId = 'github'; /** One extension-host lease; the client is set once acquisition completes. */ @@ -44,7 +44,7 @@ class GitHubOperationError extends Error { } /** - * Executes the proposed `vscode.github` API through the workbench GitHub service, which routes to the shared + * Executes the internal `@vscode/internal-github` module through the workbench GitHub service, which routes to the shared * process on desktop and runs locally in browser deployments. The extension host only chooses a session id; * this side resolves it, enforces the extension's account access, and never returns credentials. */ diff --git a/src/vs/workbench/api/browser/mainThreadLanguageFeatures.ts b/src/vs/workbench/api/browser/mainThreadLanguageFeatures.ts index 72a0b27cc656..41dac259c87b 100644 --- a/src/vs/workbench/api/browser/mainThreadLanguageFeatures.ts +++ b/src/vs/workbench/api/browser/mainThreadLanguageFeatures.ts @@ -185,6 +185,16 @@ export class MainThreadLanguageFeatures extends Disposable implements MainThread })); } + // --- structural diff + + $registerStructuralDiffProvider(handle: number, selector: IDocumentFilterDto[]): void { + this._registrations.set(handle, this._languageFeaturesService.structuralDiffProvider.register(selector, { + provideStructuralDiff: (originalModel, modifiedModel, context, token) => { + return this._proxy.$provideStructuralDiff(handle, originalModel.uri, originalModel.getVersionId(), modifiedModel.uri, modifiedModel.getVersionId(), context, token); + } + })); + } + // --- code lens $registerCodeLensSupport(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void { diff --git a/src/vs/workbench/api/browser/mainThreadMessageService.ts b/src/vs/workbench/api/browser/mainThreadMessageService.ts index b0f4abd95555..b57f19f9189e 100644 --- a/src/vs/workbench/api/browser/mainThreadMessageService.ts +++ b/src/vs/workbench/api/browser/mainThreadMessageService.ts @@ -12,6 +12,7 @@ import { IDialogService, IPromptButton } from '../../../platform/dialogs/common/ import { INotificationService, INotificationSource, NotificationPriority } from '../../../platform/notification/common/notification.js'; import { Event } from '../../../base/common/event.js'; import { ICommandService } from '../../../platform/commands/common/commands.js'; +import { MANAGE_EXTENSION_COMMAND_ID } from '../../../platform/extensions/common/extensions.js'; import { IExtensionService } from '../../services/extensions/common/extensions.js'; import { IDisposable } from '../../../base/common/lifecycle.js'; import { legacyExtensionLinkParsing } from '../../../platform/notification/common/notificationLegacy.js'; @@ -87,7 +88,7 @@ export class MainThreadMessageService implements MainThreadMessageServiceShape { id: options.source.identifier.value, label: nls.localize('manageExtension', "Manage Extension"), run: () => { - return this._commandService.executeCommand('_extensions.manage', options.source!.identifier.value); + return this._commandService.executeCommand(MANAGE_EXTENSION_COMMAND_ID, options.source!.identifier.value); } }), NotificationActionTelemetryId.ManageExtension)); } diff --git a/src/vs/workbench/api/browser/mainThreadProgress.ts b/src/vs/workbench/api/browser/mainThreadProgress.ts index 6e20f387a24f..a4e7f739c89f 100644 --- a/src/vs/workbench/api/browser/mainThreadProgress.ts +++ b/src/vs/workbench/api/browser/mainThreadProgress.ts @@ -7,6 +7,7 @@ import { IProgress, IProgressService, IProgressStep, ProgressLocation, IProgress import { MainThreadProgressShape, MainContext, ExtHostProgressShape, ExtHostContext, IProgressOptionsDto, IProgressStepDto } from '../common/extHost.protocol.js'; import { extHostNamedCustomer, IExtHostContext } from '../../services/extensions/common/extHostCustomers.js'; import { ICommandService } from '../../../platform/commands/common/commands.js'; +import { MANAGE_EXTENSION_COMMAND_ID } from '../../../platform/extensions/common/extensions.js'; import { localize } from '../../../nls.js'; import { onUnexpectedExternalError } from '../../../base/common/errors.js'; import { toAction } from '../../../base/common/actions.js'; @@ -53,7 +54,7 @@ export class MainThreadProgress implements MainThreadProgressShape { secondaryActions: [withNotificationActionTelemetry(toAction({ id: extensionId, label: localize('manageExtension', "Manage Extension"), - run: () => this._commandService.executeCommand('_extensions.manage', extensionId) + run: () => this._commandService.executeCommand(MANAGE_EXTENSION_COMMAND_ID, extensionId) }), NotificationActionTelemetryId.ManageExtension)] }; diff --git a/src/vs/workbench/api/browser/mainThreadSearch.ts b/src/vs/workbench/api/browser/mainThreadSearch.ts index c89fd7e4e168..92372f724f54 100644 --- a/src/vs/workbench/api/browser/mainThreadSearch.ts +++ b/src/vs/workbench/api/browser/mainThreadSearch.ts @@ -15,6 +15,7 @@ import { revive } from '../../../base/common/marshalling.js'; import * as Constants from '../../contrib/search/common/constants.js'; import { IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; import { AISearchKeyword } from '../../services/search/common/searchExtTypes.js'; +import { getOrSet } from '../../../base/common/map.js'; @extHostNamedCustomer(MainContext.MainThreadSearch) export class MainThreadSearch implements MainThreadSearchShape { @@ -101,10 +102,13 @@ class SearchOperation { private static _idPool = 0; + /** File-only matches use URI keys, with shared authority strings when casing must be preserved. */ + private readonly matches = new Map(); + private readonly authorities = new Map(); + constructor( readonly progress?: (match: IFileMatch | AISearchKeyword) => unknown, readonly id: number = ++SearchOperation._idPool, - readonly matches = new Map(), readonly keywords: AISearchKeyword[] = [] ) { // @@ -112,7 +116,7 @@ class SearchOperation { addMatch(match: IFileMatch): void { const existingMatch = this.matches.get(match.resource.toString()); - if (existingMatch) { + if (existingMatch && typeof existingMatch !== 'string') { // TODO@rob clean up text/file result types // If a file search returns the same file twice, we would enter this branch. // It's possible that could happen, #90813 @@ -126,6 +130,44 @@ class SearchOperation { this.progress?.(match); } + addFileMatch(resource: URI): void { + const key = resource.toString(); + if (this.matches.has(key)) { + return; + } + + const parsed = URI.parse(key); + // URI formatting can normalize drive-letter casing. + const preservesComponents = parsed.scheme === resource.scheme + && parsed.path === resource.path + && parsed.query === resource.query + && parsed.fragment === resource.fragment; + if (!preservesComponents) { + this.matches.set(key, { resource }); + } else { + this.matches.set(key, parsed.authority === resource.authority + ? undefined + : getOrSet(this.authorities, resource.authority, resource.authority)); + } + } + + getResults(): IFileMatch[] { + const results = new Array(this.matches.size); + let index = 0; + for (const [key, match] of this.matches) { + // Release serialized results as their URI objects are materialized. + this.matches.delete(key); + if (typeof match === 'object') { + results[index++] = match; + } else { + const resource = URI.parse(key); + results[index++] = { resource: match === undefined ? resource : resource.with({ authority: match }) }; + } + } + this.authorities.clear(); + return results; + } + addKeyword(result: AISearchKeyword): void { this.keywords.push(result); this.progress?.(result); @@ -179,7 +221,7 @@ class RemoteSearchProvider implements ISearchResultProvider, IDisposable { return Promise.resolve(searchP).then((result: ISearchCompleteStats) => { this._searches.delete(search.id); - return { results: Array.from(search.matches.values()), aiKeywords: Array.from(search.keywords), stats: result.stats, limitHit: result.limitHit, messages: result.messages }; + return { results: search.getResults(), aiKeywords: Array.from(search.keywords), stats: result.stats, limitHit: result.limitHit, messages: result.messages }; }, err => { this._searches.delete(search.id); return Promise.reject(err); @@ -202,9 +244,7 @@ class RemoteSearchProvider implements ISearchResultProvider, IDisposable { if ((result).results) { searchOp.addMatch(revive((result))); } else { - searchOp.addMatch({ - resource: URI.revive(result) - }); + searchOp.addFileMatch(URI.revive(result)); } }); } diff --git a/src/vs/workbench/api/browser/mainThreadTesting.ts b/src/vs/workbench/api/browser/mainThreadTesting.ts index b2369b89fad8..4ec1e7835921 100644 --- a/src/vs/workbench/api/browser/mainThreadTesting.ts +++ b/src/vs/workbench/api/browser/mainThreadTesting.ts @@ -5,6 +5,7 @@ import { VSBuffer } from '../../../base/common/buffer.js'; import { CancellationToken } from '../../../base/common/cancellation.js'; +import { onUnexpectedError } from '../../../base/common/errors.js'; import { Event } from '../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; import { ISettableObservable, observableValue, transaction } from '../../../base/common/observable.js'; @@ -19,8 +20,9 @@ import { LiveTestResult } from '../../contrib/testing/common/testResult.js'; import { ITestResultService } from '../../contrib/testing/common/testResultService.js'; import { IMainThreadTestController, ITestService } from '../../contrib/testing/common/testService.js'; import { CoverageDetails, ExtensionRunTestsRequest, IFileCoverage, ITestItem, ITestMessage, ITestRunProfile, ITestRunTask, ResolvedTestRunRequest, TestControllerCapability, TestResultState, TestRunProfileBitset, TestsDiffOp } from '../../contrib/testing/common/testTypes.js'; +import { SerializableObjectWithBuffers } from '../../services/extensions/common/proxyIdentifier.js'; import { IExtHostContext, extHostNamedCustomer } from '../../services/extensions/common/extHostCustomers.js'; -import { ExtHostContext, ExtHostTestingShape, ILocationDto, ITestControllerPatch, MainContext, MainThreadTestingShape } from '../common/extHost.protocol.js'; +import { ExtHostContext, ExtHostTestingShape, ILocationDto, ITestControllerPatch, MainContext, MainThreadTestingShape, TestRunUpdate } from '../common/extHost.protocol.js'; @extHostNamedCustomer(MainContext.MainThreadTesting) export class MainThreadTesting extends Disposable implements MainThreadTestingShape { @@ -129,6 +131,29 @@ export class MainThreadTesting extends Disposable implements MainThreadTestingSh /** * @inheritdoc */ + $applyTestRunUpdates(controllerId: string, runId: string, updates: SerializableObjectWithBuffers): void { + for (const update of updates.value) { + try { + switch (update.type) { + case 'tests': + this.$addTestsToRun(controllerId, runId, update.tests); + break; + case 'state': + this.$updateTestStateInRun(runId, update.taskId, update.testId, update.state, update.duration); + break; + case 'messages': + this.$appendTestMessagesInRun(runId, update.taskId, update.testId, update.messages); + break; + case 'output': + this.$appendOutputToRun(runId, update.taskId, typeof update.output === 'string' ? VSBuffer.fromString(update.output) : update.output, update.location, update.testId); + break; + } + } catch (error) { + onUnexpectedError(error); + } + } + } + $addTestsToRun(controllerId: string, runId: string, tests: ITestItem.Serialized[]): void { this.withLiveRun(runId, r => r.addTestChainToRun(controllerId, tests.map(t => ITestItem.deserialize(this.uriIdentityService, t)))); diff --git a/src/vs/workbench/api/common/extHost.api.impl.ts b/src/vs/workbench/api/common/extHost.api.impl.ts index c42da7f6e97f..ae7ce27be234 100644 --- a/src/vs/workbench/api/common/extHost.api.impl.ts +++ b/src/vs/workbench/api/common/extHost.api.impl.ts @@ -122,7 +122,6 @@ import { ExtHostWebviewPanels } from './extHostWebviewPanels.js'; import { ExtHostWebviewViews } from './extHostWebviewView.js'; import { IExtHostWindow } from './extHostWindow.js'; import { IExtHostPower } from './extHostPower.js'; -import { createGitHubApi, ExtHostGitHub, GitHubError } from './extHostGitHub.js'; import { IExtHostWorkspace } from './extHostWorkspace.js'; import { ExtHostChatContext } from './extHostChatContext.js'; import { ExtHostChatDebug } from './extHostChatDebug.js'; @@ -254,7 +253,6 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I const extHostTesting = rpcProtocol.set(ExtHostContext.ExtHostTesting, accessor.get(IExtHostTesting)); const extHostUriOpeners = rpcProtocol.set(ExtHostContext.ExtHostUriOpeners, new ExtHostUriOpeners(rpcProtocol)); const extHostProfileContentHandlers = rpcProtocol.set(ExtHostContext.ExtHostProfileContentHandlers, new ExtHostProfileContentHandlers(rpcProtocol)); - const extHostGitHub = new ExtHostGitHub(rpcProtocol.getProxy(MainContext.MainThreadGitHub)); const extHostChatOutputRenderer = rpcProtocol.set(ExtHostContext.ExtHostChatOutputRenderer, new ExtHostChatOutputRenderer(rpcProtocol, extHostWebviews)); rpcProtocol.set(ExtHostContext.ExtHostInteractive, new ExtHostInteractive(rpcProtocol, extHostNotebook, extHostDocumentsAndEditors, extHostCommands, extHostLogService)); const extHostLanguageModelTools = rpcProtocol.set(ExtHostContext.ExtHostLanguageModelTools, new ExtHostLanguageModelTools(rpcProtocol, extHostLanguageModels)); @@ -731,6 +729,9 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable { return extHostLanguageFeatures.registerDocumentSymbolProvider(extension, checkSelector(selector), provider, metadata); }, + registerStructuralDiffProvider(selector: vscode.DocumentSelector, provider: vscode.StructuralDiffProvider): vscode.Disposable { + return extHostLanguageFeatures.registerStructuralDiffProvider(extension, checkSelector(selector), provider); + }, registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable { return extHostLanguageFeatures.registerWorkspaceSymbolProvider(extension, provider); }, @@ -2000,9 +2001,6 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I } }; - // namespace: github - const github = createGitHubApi(extension, extHostGitHub); - // eslint-disable-next-line local/code-no-dangerous-type-assertions return { version: initData.version, @@ -2015,7 +2013,6 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I debug, env, extensions, - github, interactive, l10n, languages, @@ -2100,7 +2097,6 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I FoldingRange: extHostTypes.FoldingRange, FoldingRangeKind: extHostTypes.FoldingRangeKind, FunctionBreakpoint: extHostTypes.FunctionBreakpoint, - GitHubError: GitHubError, InlineCompletionItem: extHostTypes.InlineSuggestion, InlineCompletionList: extHostTypes.InlineSuggestionList, Hover: extHostTypes.Hover, @@ -2134,6 +2130,8 @@ export function createApiFactoryAndRegisterActors(accessor: ServicesAccessor): I SnippetString: extHostTypes.SnippetString, SourceBreakpoint: extHostTypes.SourceBreakpoint, StandardTokenType: extHostTypes.StandardTokenType, + StructuralDiffClassification: extHostTypes.StructuralDiffClassification, + StructuralDiffTag: extHostTypes.StructuralDiffTag, SyntaxHighlightingTokenFontStyle: extHostTypes.SyntaxHighlightingTokenFontStyle, StatusBarAlignment: extHostTypes.StatusBarAlignment, SymbolInformation: extHostTypes.SymbolInformation, diff --git a/src/vs/workbench/api/common/extHost.protocol.ts b/src/vs/workbench/api/common/extHost.protocol.ts index 1795f73e9331..cfe2f2188693 100644 --- a/src/vs/workbench/api/common/extHost.protocol.ts +++ b/src/vs/workbench/api/common/extHost.protocol.ts @@ -533,6 +533,7 @@ export interface IInlineCompletionChangeHintDto { export interface MainThreadLanguageFeaturesShape extends IDisposable { $unregister(handle: number): void; $registerDocumentSymbolProvider(handle: number, selector: IDocumentFilterDto[], label: string): void; + $registerStructuralDiffProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerCodeLensSupport(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitCodeLensEvent(eventHandle: number, event?: any): void; $registerDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void; @@ -3078,6 +3079,7 @@ export interface IDocumentDropEditDto { export interface ExtHostLanguageFeaturesShape { $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise; + $provideStructuralDiff(handle: number, originalResource: UriComponents, originalVersion: number, modifiedResource: UriComponents, modifiedVersion: number, context: languages.StructuralDiffContext, token: CancellationToken): Promise; $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise; $resolveCodeLens(handle: number, symbol: ICodeLensDto, token: CancellationToken): Promise; $releaseCodeLenses(handle: number, id: number): void; @@ -3951,6 +3953,12 @@ export interface ITestControllerPatch { capabilities?: TestControllerCapability; } +export type TestRunUpdate = + | { type: 'tests'; tests: ITestItem.Serialized[] } + | { type: 'state'; taskId: string; testId: string; state: TestResultState; duration?: number } + | { type: 'messages'; taskId: string; testId: string; messages: ITestMessage.Serialized[] } + | { type: 'output'; taskId: string; output: string | VSBuffer; location?: ILocationDto; testId?: string }; + export interface MainThreadTestingShape { // --- test lifecycle: @@ -3981,6 +3989,9 @@ export interface MainThreadTestingShape { // --- test run handling: + /** Applies ordered test run updates sent in a single message. */ + $applyTestRunUpdates(controllerId: string, runId: string, updates: SerializableObjectWithBuffers): void; + /** Request by an extension to run tests. */ $runTests(req: ResolvedTestRunRequest, token: CancellationToken): Promise; /** diff --git a/src/vs/workbench/api/common/extHostApiCommands.ts b/src/vs/workbench/api/common/extHostApiCommands.ts index 2785bbd7290b..fbffa4d74290 100644 --- a/src/vs/workbench/api/common/extHostApiCommands.ts +++ b/src/vs/workbench/api/common/extHostApiCommands.ts @@ -382,6 +382,12 @@ const newCommands: ApiCommand[] = [ return undefined; }) ), + // --- structural diff + new ApiCommand( + 'vscode.executeStructuralDiffProvider', '_executeStructuralDiffProvider', 'Execute structural diff provider.', + [ApiCommandArgument.Uri.with('original', 'Uri of the original text document'), ApiCommandArgument.Uri.with('modified', 'Uri of the modified text document')], + new ApiCommandResult('A promise that resolves to a StructuralDiffResult, or undefined when no provider supplies a result.', result => result ? typeConverters.StructuralDiff.to(result) : undefined) + ), // --- notebooks new ApiCommand( diff --git a/src/vs/workbench/api/common/extHostCommands.ts b/src/vs/workbench/api/common/extHostCommands.ts index 52ea83148a76..df215792948d 100644 --- a/src/vs/workbench/api/common/extHostCommands.ts +++ b/src/vs/workbench/api/common/extHostCommands.ts @@ -17,7 +17,7 @@ import { revive } from '../../../base/common/marshalling.js'; import { IRange, Range } from '../../../editor/common/core/range.js'; import { IPosition, Position } from '../../../editor/common/core/position.js'; import { URI } from '../../../base/common/uri.js'; -import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; +import { DisposableStore, IDisposable, toDisposable } from '../../../base/common/lifecycle.js'; import { createDecorator } from '../../../platform/instantiation/common/instantiation.js'; import { IExtHostRpcService } from './extHostRpcService.js'; import { ISelection } from '../../../editor/common/core/selection.js'; @@ -51,6 +51,7 @@ export class ExtHostCommands implements ExtHostCommandsShape { private readonly _commands = new Map(); private readonly _apiCommands = new Map(); + private readonly _executionParticipants = new Set<(command: string) => void>(); #telemetry: MainThreadTelemetryShape; private readonly _logService: ILogService; @@ -117,6 +118,12 @@ export class ExtHostCommands implements ExtHostCommandsShape { this._argumentProcessors.push(processor); } + /** Registers synchronous preparation to run before dispatching a command. */ + registerExecutionParticipant(participant: (command: string) => void): IDisposable { + this._executionParticipants.add(participant); + return toDisposable(() => this._executionParticipants.delete(participant)); + } + registerApiCommand(apiCommand: ApiCommand): extHostTypes.Disposable { @@ -176,6 +183,9 @@ export class ExtHostCommands implements ExtHostCommandsShape { } private async _doExecuteCommand(id: string, args: unknown[], retry: boolean): Promise { + for (const participant of this._executionParticipants) { + participant(id); + } if (this._commands.has(id)) { // - We stay inside the extension host and support diff --git a/src/vs/workbench/api/common/extHostDocumentContentProviders.ts b/src/vs/workbench/api/common/extHostDocumentContentProviders.ts index cf67e3e17476..bdd812a58f72 100644 --- a/src/vs/workbench/api/common/extHostDocumentContentProviders.ts +++ b/src/vs/workbench/api/common/extHostDocumentContentProviders.ts @@ -14,6 +14,8 @@ import { Schemas } from '../../../base/common/network.js'; import { ILogService } from '../../../platform/log/common/log.js'; import { CancellationToken } from '../../../base/common/cancellation.js'; import { splitLines } from '../../../base/common/strings.js'; +import { SequencerByKey } from '../../../base/common/async.js'; +import { getComparisonKey } from '../../../base/common/resources.js'; export class ExtHostDocumentContentProvider implements ExtHostDocumentContentProvidersShape { @@ -45,9 +47,9 @@ export class ExtHostDocumentContentProvider implements ExtHostDocumentContentPro let subscription: IDisposable | undefined; if (typeof provider.onDidChange === 'function') { - let lastEvent: Promise | undefined; + const documentUpdateQueue = new SequencerByKey(); - subscription = provider.onDidChange(async uri => { + subscription = provider.onDidChange(uri => { if (uri.scheme !== scheme) { this._logService.warn(`Provider for scheme '${scheme}' is firing event for schema '${uri.scheme}' which will be IGNORED`); return; @@ -57,38 +59,30 @@ export class ExtHostDocumentContentProvider implements ExtHostDocumentContentPro return; } - if (lastEvent) { - await lastEvent; - } - - const thisEvent = this.$provideTextDocumentContent(handle, uri) - .then(async value => { - if (!value && typeof value !== 'string') { - return; - } - - const document = this._documentsAndEditors.getDocument(uri); - if (!document) { - // disposed in the meantime - return; - } - - // create lines and compare - const lines = splitLines(value); - - // broadcast event when content changed - if (!document.equalLines(lines)) { - return this._proxy.$onVirtualDocumentChange(uri, value); - } - }) - .catch(onUnexpectedError) - .finally(() => { - if (lastEvent === thisEvent) { - lastEvent = undefined; - } - }); - - lastEvent = thisEvent; + documentUpdateQueue.queue(getComparisonKey(uri), async () => { + if (!this._documentContentProviders.has(handle)) { + return; + } + + const value = await this.$provideTextDocumentContent(handle, uri); + if (!value && typeof value !== 'string') { + return; + } + + const document = this._documentsAndEditors.getDocument(uri); + if (!document) { + // disposed in the meantime + return; + } + + // create lines and compare + const lines = splitLines(value); + + // broadcast event when content changed + if (!document.equalLines(lines)) { + return this._proxy.$onVirtualDocumentChange(uri, value); + } + }).catch(onUnexpectedError); }); } return new Disposable(() => { diff --git a/src/vs/workbench/api/common/extHostGitHub.ts b/src/vs/workbench/api/common/extHostGitHub.ts index b8e6f1539ed5..6028987b1b0d 100644 --- a/src/vs/workbench/api/common/extHostGitHub.ts +++ b/src/vs/workbench/api/common/extHostGitHub.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import type * as vscode from 'vscode'; +import type * as internalGitHub from '@vscode/internal-github'; import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js'; import { CancellationError, illegalArgument } from '../../../base/common/errors.js'; import { URI } from '../../../base/common/uri.js'; import { IExtensionDescription } from '../../../platform/extensions/common/extensions.js'; -import { checkProposedApiEnabled } from '../../services/extensions/common/extensions.js'; import { GitHubErrorCodeDto, GitHubResultDto, IGitHubGistDto, MainThreadGitHubShape } from './extHost.protocol.js'; export class GitHubError extends Error { @@ -31,14 +31,14 @@ export class ExtHostGitHub { constructor(private readonly _proxy: MainThreadGitHubShape) { } - async getClient(extension: IExtensionDescription, sessionId: string, token: vscode.CancellationToken | undefined): Promise { + async getClient(extension: IExtensionDescription, sessionId: string, token: vscode.CancellationToken | undefined): Promise { if (typeof sessionId !== 'string' || !sessionId) { throw illegalArgument('sessionId'); } const client = await this._acquire(token, (handle, token) => this._proxy.$getClient(handle, extension.identifier.value, sessionId, token)); - const gists: vscode.GitHubGists = Object.freeze({ + const gists: internalGitHub.GitHubGists = Object.freeze({ get: (gistId: string, token?: vscode.CancellationToken) => client.run(token, (handle, token) => this._proxy.$getGist(handle, gistId, token)).then(toGist), - create: (gist: vscode.GitHubGistCreateOptions, token?: vscode.CancellationToken) => client.run(token, (handle, token) => this._proxy.$createGist(handle, { + create: (gist: internalGitHub.GitHubGistCreateOptions, token?: vscode.CancellationToken) => client.run(token, (handle, token) => this._proxy.$createGist(handle, { public: gist?.public, files: gist?.files, }, token)).then(toGist), @@ -46,9 +46,9 @@ export class ExtHostGitHub { return Object.freeze({ gists, dispose: () => client.dispose() }); } - async getAnonymousClient(extension: IExtensionDescription, token: vscode.CancellationToken | undefined): Promise { + async getAnonymousClient(extension: IExtensionDescription, token: vscode.CancellationToken | undefined): Promise { const client = await this._acquire(token, (handle, token) => this._proxy.$getAnonymousClient(handle, extension.identifier.value, token)); - const gists: vscode.GitHubGistReader = Object.freeze({ + const gists: internalGitHub.GitHubGistReader = Object.freeze({ get: (gistId: string, token?: vscode.CancellationToken) => client.run(token, (handle, token) => this._proxy.$getGist(handle, gistId, token)).then(toGist), }); return Object.freeze({ gists, dispose: () => client.dispose() }); @@ -126,22 +126,59 @@ class ExtHostGitHubClient { } /** - * Creates the `vscode.github` namespace for one extension; every entry point requires the `github` proposal. + * Built-in extensions that may import {@link internalGitHubModuleName}. Eligibility is an explicit + * allowlist of built-in extensions; the module name alone is not access control. */ -export function createGitHubApi(extension: IExtensionDescription, extHostGitHub: ExtHostGitHub): typeof vscode.github { - return { - getClient(sessionId: string, token?: vscode.CancellationToken) { - checkProposedApiEnabled(extension, 'github'); - return extHostGitHub.getClient(extension, sessionId, token); - }, - getAnonymousClient(token?: vscode.CancellationToken) { - checkProposedApiEnabled(extension, 'github'); - return extHostGitHub.getAnonymousClient(extension, token); - }, - }; +const internalGitHubConsumers: ReadonlySet = new Set([ + 'vscode.configuration-editing', +]); + +export const internalGitHubModuleName = '@vscode/internal-github'; + +/** + * Creates the `@vscode/internal-github` module for one extension. The extension identity is bound + * here, so the importer cannot request a client on behalf of another extension. + */ +export function createInternalGitHubModule(extension: IExtensionDescription, extHostGitHub: ExtHostGitHub): typeof internalGitHub { + return Object.freeze({ + getClient: (sessionId: string, token?: vscode.CancellationToken) => extHostGitHub.getClient(extension, sessionId, token), + getAnonymousClient: (token?: vscode.CancellationToken) => extHostGitHub.getAnonymousClient(extension, token), + GitHubError, + }); +} + +/** + * Provides `@vscode/internal-github` to eligible built-in extensions through the extension host's + * `require` interception (CommonJS, in the node and web worker hosts). Native ESM importers are not + * supported and fail to resolve the module. An importer that cannot be identified, is not built in + * or is not on the allowlist is rejected; there is no fallback identity. + */ +export class InternalGitHubModuleFactory { + + readonly nodeModuleName = internalGitHubModuleName; + + private readonly _modules = new Map(); + + constructor( + private readonly _extensionPaths: { findSubstr(uri: URI): IExtensionDescription | undefined }, + private readonly _extHostGitHub: ExtHostGitHub, + ) { } + + load(_request: string, parent: URI): typeof internalGitHub { + const extension = this._extensionPaths.findSubstr(parent); + if (!extension || !extension.isBuiltin || !internalGitHubConsumers.has(extension.identifier.value)) { + throw new Error(`Cannot find module '${internalGitHubModuleName}'`); + } + let module = this._modules.get(extension.identifier.value); + if (!module) { + module = createInternalGitHubModule(extension, this._extHostGitHub); + this._modules.set(extension.identifier.value, module); + } + return module; + } } -function toGist(dto: IGitHubGistDto): vscode.GitHubGist { +function toGist(dto: IGitHubGistDto): internalGitHub.GitHubGist { return Object.freeze({ id: dto.id, htmlUrl: URI.parse(dto.htmlUrl), diff --git a/src/vs/workbench/api/common/extHostLanguageFeatures.ts b/src/vs/workbench/api/common/extHostLanguageFeatures.ts index eb92d60e2610..eb5b01d0e632 100644 --- a/src/vs/workbench/api/common/extHostLanguageFeatures.ts +++ b/src/vs/workbench/api/common/extHostLanguageFeatures.ts @@ -7,8 +7,8 @@ import type * as vscode from 'vscode'; import { asArray, coalesce, isFalsyOrEmpty, isNonEmptyArray } from '../../../base/common/arrays.js'; import { raceCancellationError } from '../../../base/common/async.js'; import { VSBuffer } from '../../../base/common/buffer.js'; -import { CancellationToken } from '../../../base/common/cancellation.js'; -import { NotImplementedError, isCancellationError } from '../../../base/common/errors.js'; +import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js'; +import { CancellationError, NotImplementedError, isCancellationError } from '../../../base/common/errors.js'; import { IdGenerator } from '../../../base/common/idGenerator.js'; import { DisposableStore, Disposable as CoreDisposable } from '../../../base/common/lifecycle.js'; import { equals, mixin } from '../../../base/common/objects.js'; @@ -103,6 +103,51 @@ class DocumentSymbolAdapter { } } +class StructuralDiffAdapter { + + constructor( + private readonly _documents: ExtHostDocuments, + private readonly _provider: vscode.StructuralDiffProvider, + ) { } + + async provideStructuralDiff(originalResource: URI, originalVersion: number, modifiedResource: URI, modifiedVersion: number, context: languages.StructuralDiffContext, token: CancellationToken): Promise { + const originalDocument = this._documents.getDocument(originalResource); + const modifiedDocument = this._documents.getDocument(modifiedResource); + const isStale = () => originalDocument.isClosed || modifiedDocument.isClosed + || originalDocument.version !== originalVersion || modifiedDocument.version !== modifiedVersion; + if (token.isCancellationRequested || isStale()) { + throw new CancellationError(); + } + + const disposables = new DisposableStore(); + const source = disposables.add(new CancellationTokenSource(token)); + disposables.add(this._documents.onDidChangeDocument(() => { + if (isStale()) { + source.cancel(); + } + })); + disposables.add(this._documents.onDidRemoveDocument(document => { + if (document === originalDocument || document === modifiedDocument) { + source.cancel(); + } + })); + try { + const result = await raceCancellationError(Promise.resolve(this._provider.provideStructuralDiff( + originalDocument, + modifiedDocument, + typeConvert.StructuralDiffContext.to(context), + source.token, + )), source.token); + if (source.token.isCancellationRequested || isStale()) { + throw new CancellationError(); + } + return result ? typeConvert.StructuralDiff.from(result) : undefined; + } finally { + disposables.dispose(); + } + } +} + class CodeLensAdapter { private readonly _cache = new Cache('CodeLens'); @@ -2141,7 +2186,7 @@ class DocumentDropEditAdapter { } } -type Adapter = DocumentSymbolAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter +type Adapter = DocumentSymbolAdapter | StructuralDiffAdapter | CodeLensAdapter | DefinitionAdapter | HoverAdapter | DocumentHighlightAdapter | MultiDocumentHighlightAdapter | ReferenceAdapter | CodeActionAdapter | DocumentPasteEditProvider | DocumentFormattingAdapter | RangeFormattingAdapter | OnTypeFormattingAdapter | NavigateTypeAdapter | RenameAdapter @@ -2277,6 +2322,19 @@ export class ExtHostLanguageFeatures extends CoreDisposable implements extHostPr return this._withAdapter(handle, DocumentSymbolAdapter, adapter => adapter.provideDocumentSymbols(URI.revive(resource), token), undefined, token); } + // --- structural diff + + registerStructuralDiffProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.StructuralDiffProvider): vscode.Disposable { + checkProposedApiEnabled(extension, 'structuralDiff'); + const handle = this._addNewAdapter(new StructuralDiffAdapter(this._documents, provider), extension); + this._proxy.$registerStructuralDiffProvider(handle, this._transformDocumentSelector(selector, extension)); + return this._createDisposable(handle); + } + + $provideStructuralDiff(handle: number, originalResource: UriComponents, originalVersion: number, modifiedResource: UriComponents, modifiedVersion: number, context: languages.StructuralDiffContext, token: CancellationToken): Promise { + return this._withAdapter(handle, StructuralDiffAdapter, adapter => adapter.provideStructuralDiff(URI.revive(originalResource), originalVersion, URI.revive(modifiedResource), modifiedVersion, context, token), undefined, token); + } + // --- code lens registerCodeLensProvider(extension: IExtensionDescription, selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable { diff --git a/src/vs/workbench/api/common/extHostNotebookKernels.ts b/src/vs/workbench/api/common/extHostNotebookKernels.ts index 26ba550555f2..157089a8846d 100644 --- a/src/vs/workbench/api/common/extHostNotebookKernels.ts +++ b/src/vs/workbench/api/common/extHostNotebookKernels.ts @@ -169,7 +169,7 @@ export class ExtHostNotebookKernels implements ExtHostNotebookKernelsShape { const myToken = ++tokenPool; Promise.resolve().then(() => { if (myToken === tokenPool) { - this._proxy.$updateKernel(handle, data); + this._proxy.$updateKernel(handle, { ...data, supportedLanguages: data.supportedLanguages ?? [] }); } }); }; diff --git a/src/vs/workbench/api/common/extHostRequireInterceptor.ts b/src/vs/workbench/api/common/extHostRequireInterceptor.ts index e118ff77012b..c22f86436cc2 100644 --- a/src/vs/workbench/api/common/extHostRequireInterceptor.ts +++ b/src/vs/workbench/api/common/extHostRequireInterceptor.ts @@ -16,6 +16,7 @@ import { IExtHostInitDataService } from './extHostInitDataService.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; import { ExtensionPaths, IExtHostExtensionService } from './extHostExtensionService.js'; import { ILogService } from '../../../platform/log/common/log.js'; +import { ExtHostGitHub, InternalGitHubModuleFactory } from './extHostGitHub.js'; import { escapeRegExpCharacters } from '../../../base/common/strings.js'; @@ -45,6 +46,7 @@ export abstract class RequireInterceptor { @IExtHostExtensionService private readonly _extHostExtensionService: IExtHostExtensionService, @IExtHostInitDataService private readonly _initData: IExtHostInitDataService, @ILogService private readonly _logService: ILogService, + @IExtHostRpcService private readonly _rpcService: IExtHostRpcService, ) { this._factories = new Map(); this._alternatives = []; @@ -60,6 +62,7 @@ export abstract class RequireInterceptor { const extensionPaths = await this._extHostExtensionService.getExtensionPathIndex(); this.register(new VSCodeNodeModuleFactory(this._apiFactory, extensionPaths, this._extensionRegistry, configProvider, this._logService)); + this.register(new InternalGitHubModuleFactory(extensionPaths, new ExtHostGitHub(this._rpcService.getProxy(MainContext.MainThreadGitHub)))); this.register(this._instaService.createInstance(NodeModuleAliasingModuleFactory)); if (this._initData.remote.isRemote) { this.register(this._instaService.createInstance(OpenNodeModuleFactory, extensionPaths, this._initData.environment.appUriScheme)); diff --git a/src/vs/workbench/api/common/extHostTask.ts b/src/vs/workbench/api/common/extHostTask.ts index 17091b0eb98f..74decec81cae 100644 --- a/src/vs/workbench/api/common/extHostTask.ts +++ b/src/vs/workbench/api/common/extHostTask.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ import { URI, UriComponents } from '../../../base/common/uri.js'; -import { asPromise } from '../../../base/common/async.js'; import { Event, Emitter } from '../../../base/common/event.js'; import { MainContext, MainThreadTaskShape, ExtHostTaskShape } from './extHost.protocol.js'; @@ -651,10 +650,10 @@ export abstract class ExtHostTaskBase implements ExtHostTaskShape, IExtHostTask protected abstract provideTasksInternal(validTypes: { [key: string]: boolean }, taskIdPromises: Promise[], handler: HandlerData, value: vscode.Task[] | null | undefined): { tasks: tasks.ITaskDTO[]; extension: IExtensionDescription }; - public $provideTasks(handle: number, validTypes: { [key: string]: boolean }): Promise { + public async $provideTasks(handle: number, validTypes: { [key: string]: boolean }): Promise { const handler = this._handlers.get(handle); if (!handler) { - return Promise.reject(new Error('no handler found')); + throw new Error('no handler found'); } // Set up a list of task ID promises that we can wait on @@ -666,17 +665,10 @@ export abstract class ExtHostTaskBase implements ExtHostTaskShape, IExtHostTask // thread, which is too late for us because we need to save an map // from an ID to the custom execution function. (Kind of a cart before the horse problem). const taskIdPromises: Promise[] = []; - const fetchPromise = asPromise(() => handler.provider.provideTasks(CancellationToken.None)).then(value => { - return this.provideTasksInternal(validTypes, taskIdPromises, handler, handler.isDisposed ? [] : value); - }); - - return new Promise((resolve) => { - fetchPromise.then((result) => { - Promise.all(taskIdPromises).then(() => { - resolve(handler.isDisposed ? { tasks: [], extension: handler.extension } : result); - }); - }); - }); + const value = await handler.provider.provideTasks(CancellationToken.None); + const result = this.provideTasksInternal(validTypes, taskIdPromises, handler, handler.isDisposed ? [] : value); + await Promise.all(taskIdPromises); + return handler.isDisposed ? { tasks: [], extension: handler.extension } : result; } protected abstract resolveTaskInternal(resolvedTaskDTO: tasks.ITaskDTO): Promise; diff --git a/src/vs/workbench/api/common/extHostTesting.ts b/src/vs/workbench/api/common/extHostTesting.ts index 2fcbf60e3cf1..cb1387d4a5da 100644 --- a/src/vs/workbench/api/common/extHostTesting.ts +++ b/src/vs/workbench/api/common/extHostTesting.ts @@ -24,10 +24,11 @@ import { TestId, TestPosition } from '../../contrib/testing/common/testId.js'; import { InvalidTestItemError } from '../../contrib/testing/common/testItemCollection.js'; import { AbstractIncrementalTestCollection, CoverageDetails, ICallProfileRunHandler, ISerializedTestResults, IStartControllerTests, IStartControllerTestsResult, ITestErrorMessage, ITestItem, ITestItemContext, ITestMessageMenuArgs, ITestRunProfile, IncrementalChangeCollector, IncrementalTestCollectionItem, InternalTestItem, TestControllerCapability, TestMessageFollowupRequest, TestMessageFollowupResponse, TestResultState, TestsDiff, TestsDiffOp, isStartControllerTests } from '../../contrib/testing/common/testTypes.js'; import { checkProposedApiEnabled } from '../../services/extensions/common/extensions.js'; -import { ExtHostTestingShape, ILocationDto, MainContext, MainThreadTestingShape } from './extHost.protocol.js'; +import { ExtHostTestingShape, ILocationDto, MainContext, MainThreadTestingShape, TestRunUpdate } from './extHost.protocol.js'; import { IExtHostCommands } from './extHostCommands.js'; import { IExtHostDocumentsAndEditors } from './extHostDocumentsAndEditors.js'; import { IExtHostRpcService } from './extHostRpcService.js'; +import { BatchedTestRunRpc } from './extHostTestingBatchedRpc.js'; import { ExtHostTestItemCollection, TestItemImpl, TestItemRootImpl, toItemFromContext } from './extHostTestItem.js'; import * as Convert from './extHostTypeConverters.js'; import { FileCoverage, TestRunProfileBase, TestRunRequest } from './extHostTypes.js'; @@ -45,8 +46,6 @@ type DefaultProfileChangeEvent = Map(); - export const IExtHostTesting = createDecorator('IExtHostTesting'); export interface IExtHostTesting extends ExtHostTesting { readonly _serviceBrand: undefined; @@ -55,6 +54,8 @@ export interface IExtHostTesting extends ExtHostTesting { export class ExtHostTesting extends Disposable implements ExtHostTestingShape { declare readonly _serviceBrand: undefined; + /** Bounded to the same 32 snapshots exposed through results. */ + private readonly testResultInternalIDs = new Map(); private readonly resultsChangedEmitter = this._register(new Emitter()); protected readonly controllers = new Map(); private readonly proxy: MainThreadTestingShape; @@ -76,7 +77,12 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { super(); this.proxy = rpc.getProxy(MainContext.MainThreadTesting); this.observer = new TestObservers(this.proxy); - this.runTracker = new TestRunCoordinator(this.proxy, logService); + this.runTracker = this._register(new TestRunCoordinator(this.proxy, logService)); + this._register(commands.registerExecutionParticipant(command => { + if (command.startsWith('testing.') || command === 'vscode.peekTestError') { + this.runTracker.flushUpdates(); + } + })); commands.registerArgumentProcessor({ processArgument: arg => { @@ -201,10 +207,10 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { }, invalidateTestResults: items => { if (items === undefined) { - this.proxy.$markTestRetired(undefined); + this.runTracker.markTestRetired(undefined); } else { const itemsArr = items instanceof Array ? items : [items]; - this.proxy.$markTestRetired(itemsArr.map(i => TestId.fromExtHostTestItem(i!, controllerId).toString())); + this.runTracker.markTestRetired(itemsArr.map(i => TestId.fromExtHostTestItem(i!, controllerId).toString())); } }, set resolveHandler(fn) { @@ -403,7 +409,7 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { this.proxy.$getCoverageDetails(r.id, taskWithCoverage, uri, token).then(r => r.map(Convert.TestCoverage.to)); } - testResultInternalIDs.set(o, r.id); + this.testResultInternalIDs.set(o, r.id); return o; }) .concat(this.results) @@ -411,6 +417,13 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { .slice(0, 32), ); + const retained = new Set(this.results); + for (const result of this.testResultInternalIDs.keys()) { + if (!retained.has(result)) { + this.testResultInternalIDs.delete(result); + } + } + this.resultsChangedEmitter.fire(); } @@ -463,7 +476,7 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { /** @inheritdoc */ public async $provideTestFollowups(req: TestMessageFollowupRequest, token: CancellationToken): Promise { - const results = this.results.find(r => testResultInternalIDs.get(r) === req.resultId); + const results = this.results.find(r => this.testResultInternalIDs.get(r) === req.resultId); const test = results && findTestInResultSnapshot(TestId.fromString(req.extId), results?.results); if (!test) { return []; @@ -583,6 +596,7 @@ export class ExtHostTesting extends Disposable implements ExtHostTestingShape { if (tracker.hasRunningTasks && !token.isCancellationRequested) { await Event.toPromise(tracker.onEnd); } + tracker.flushUpdates(); } } } @@ -600,6 +614,11 @@ const enum TestRunTrackerState { Ended, } +/** Includes byte output accepted by the runtime for compatibility with test adapters. */ +interface TestRun extends vscode.TestRun { + appendOutput(output: string | Uint8Array, location?: vscode.Location, test?: vscode.TestItem): void; +} + class TestRunTracker extends Disposable { private state = TestRunTrackerState.Running; private running = 0; @@ -635,6 +654,7 @@ class TestRunTracker extends Disposable { private readonly logService: ILogService, private readonly profile: vscode.TestRunProfile | undefined, private readonly extension: IExtensionDescription, + private readonly batchedRpc: BatchedTestRunRpc, parentToken?: CancellationToken, ) { super(); @@ -705,14 +725,14 @@ class TestRunTracker extends Disposable { } /** Creates the public test run interface to give to extensions. */ - public createRun(name: string | undefined): vscode.TestRun { + public createRun(name: string | undefined): TestRun { const runId = this.dto.id; const ctrlId = this.dto.controllerId; const taskId = generateUuid(); const guardTestMutation = (fn: (test: vscode.TestItem, ...args: Args) => void) => (test: vscode.TestItem, ...args: Args) => { - if (ended) { + if (ended || this._store.isDisposed) { this.logService.warn(`Setting the state of test "${test.id}" is a no-op after the run ends.`); return; } @@ -733,7 +753,7 @@ class TestRunTracker extends Disposable { } } - this.proxy.$appendTestMessagesInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), converted); + this.addUpdate({ type: 'messages', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), messages: converted }); }; let ended = false; @@ -743,13 +763,13 @@ class TestRunTracker extends Disposable { // one-off map used to associate test items with incrementing IDs in `addCoverage`. // There's no need to include their entire ID, we just want to make sure they're // stable and unique. Normal map is okay since TestRun lifetimes are limited. - const run: vscode.TestRun = { + const run: TestRun = { isPersisted: this.dto.isPersisted, token: cts.token, name, onDidDispose: this.onDidDispose, addCoverage: (coverage) => { - if (ended) { + if (ended || this._store.isDisposed) { return; } @@ -767,46 +787,44 @@ class TestRunTracker extends Disposable { // ID at the time when the coverage report is generated so we can reference // it later if needeed. this.publishedCoverage.set(id, { report: coverage, extIds: includesTests.map(t => TestId.fromExtHostTestItem(t, ctrlId).toString()) }); + this.flushUpdates(); this.proxy.$appendCoverage(runId, taskId, Convert.TestCoverage.fromFile(ctrlId, id, coverage)); }, //#region state mutation enqueued: guardTestMutation(test => { - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), TestResultState.Queued); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Queued }); }), skipped: guardTestMutation(test => { - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), TestResultState.Skipped); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Skipped }); }), started: guardTestMutation(test => { - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), TestResultState.Running); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Running }); }), errored: guardTestMutation((test, messages, duration) => { appendMessages(test, messages); - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), TestResultState.Errored, duration); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Errored, duration }); }), failed: guardTestMutation((test, messages, duration) => { appendMessages(test, messages); - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, ctrlId).toString(), TestResultState.Failed, duration); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Failed, duration }); }), passed: guardTestMutation((test, duration) => { - this.proxy.$updateTestStateInRun(runId, taskId, TestId.fromExtHostTestItem(test, this.dto.controllerId).toString(), TestResultState.Passed, duration); + this.addUpdate({ type: 'state', taskId, testId: TestId.fromExtHostTestItem(test, ctrlId).toString(), state: TestResultState.Passed, duration }); }), //#endregion - appendOutput: (output, location?: vscode.Location, test?: vscode.TestItem) => { - if (ended) { + appendOutput: (output: string | Uint8Array, location?: vscode.Location, test?: vscode.TestItem) => { + if (ended || this._store.isDisposed) { return; } - if (test) { this.ensureTestIsKnown(test); } - this.proxy.$appendOutputToRun( - runId, - taskId, - VSBuffer.fromString(output), - location && Convert.location.from(location), - test && TestId.fromExtHostTestItem(test, ctrlId).toString(), - ); + this.addUpdate({ + type: 'output', taskId, output: typeof output === 'string' ? output : VSBuffer.wrap(output), + location: location && Convert.location.from(location), + testId: test && TestId.fromExtHostTestItem(test, ctrlId).toString(), + }); }, end: () => { if (ended) { @@ -814,6 +832,7 @@ class TestRunTracker extends Disposable { } ended = true; + this.flushUpdates(); this.proxy.$finishedTestRunTask(runId, taskId); if (!--this.running) { this.markEnded(); @@ -821,6 +840,7 @@ class TestRunTracker extends Disposable { } }; + this.flushUpdates(); this.running++; this.tasks.set(taskId, { run, cts }); this.proxy.$startedTestRunTask(runId, { @@ -873,10 +893,19 @@ class TestRunTracker extends Disposable { test = test.parent || root; } - this.proxy.$addTestsToRun(this.dto.controllerId, this.dto.id, chain); + this.addUpdate({ type: 'tests', tests: chain }); + } + + private addUpdate(update: TestRunUpdate): void { + this.batchedRpc.add(this.dto.controllerId, this.dto.id, update); + } + + public flushUpdates(): void { + this.batchedRpc.flush(); } public override dispose(): void { + this.flushUpdates(); this.markEnded(); super.dispose(); } @@ -886,9 +915,10 @@ class TestRunTracker extends Disposable { * Queues runs for a single extension and provides the currently-executing * run so that `createTestRun` can be properly correlated. */ -export class TestRunCoordinator { +export class TestRunCoordinator extends Disposable { private readonly tracked = new Map(); private readonly trackedById = new Map(); + private readonly batchedRpc: BatchedTestRunRpc; public get trackers() { return this.tracked.values(); @@ -897,7 +927,10 @@ export class TestRunCoordinator { constructor( private readonly proxy: MainThreadTestingShape, private readonly logService: ILogService, - ) { } + ) { + super(); + this.batchedRpc = this._register(new BatchedTestRunRpc(proxy)); + } /** * Gets a coverage report for a given run and task ID. @@ -907,18 +940,29 @@ export class TestRunCoordinator { return this.trackedById.get(runId)?.getCoverageDetails(id, testId, token) || []; } + /** Publishes queued test registrations and states before retiring their results. */ + public markTestRetired(testIds: string[] | undefined): void { + this.flushUpdates(); + this.proxy.$markTestRetired(testIds); + } + + /** Publishes the pending batch without scanning historical trackers. */ + public flushUpdates(): void { + this.batchedRpc.flush(); + } + /** * Disposes the test run, called when the main thread is no longer interested * in associated data. */ public disposeTestRun(runId: string) { - this.trackedById.get(runId)?.dispose(); - this.trackedById.delete(runId); - for (const [req, { id }] of this.tracked) { - if (id === runId) { + for (const [req, tracker] of this.tracked) { + if (tracker.id === runId) { + tracker.dispose(); this.tracked.delete(req); } } + this.trackedById.delete(runId); } /** @@ -949,7 +993,7 @@ export class TestRunCoordinator { /** * Implements the public `createTestRun` API. */ - public createTestRun(extension: IExtensionDescription, controllerId: string, collection: ExtHostTestItemCollection, request: vscode.TestRunRequest, name: string | undefined, persist: boolean): vscode.TestRun { + public createTestRun(extension: IExtensionDescription, controllerId: string, collection: ExtHostTestItemCollection, request: vscode.TestRunRequest, name: string | undefined, persist: boolean): TestRun { const existing = this.tracked.get(request); if (existing) { return existing.createRun(name); @@ -979,11 +1023,20 @@ export class TestRunCoordinator { } private getTracker(req: vscode.TestRunRequest, dto: TestRunDto, profile: vscode.TestRunProfile | undefined, extension: IExtensionDescription, token?: CancellationToken) { - const tracker = new TestRunTracker(dto, this.proxy, this.logService, profile, extension, token); + const tracker = new TestRunTracker(dto, this.proxy, this.logService, profile, extension, this.batchedRpc, token); this.tracked.set(req, tracker); this.trackedById.set(tracker.id, tracker); return tracker; } + + public override dispose(): void { + for (const tracker of this.tracked.values()) { + tracker.dispose(); + } + this.tracked.clear(); + this.trackedById.clear(); + super.dispose(); + } } const tryGetProfileFromTestRunReq = (request: vscode.TestRunRequest) => { diff --git a/src/vs/workbench/api/common/extHostTestingBatchedRpc.ts b/src/vs/workbench/api/common/extHostTestingBatchedRpc.ts new file mode 100644 index 000000000000..0338b77907de --- /dev/null +++ b/src/vs/workbench/api/common/extHostTestingBatchedRpc.ts @@ -0,0 +1,98 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RunOnceScheduler } from '../../../base/common/async.js'; +import { VSBuffer } from '../../../base/common/buffer.js'; +import { IMarkdownString } from '../../../base/common/htmlContent.js'; +import { Disposable } from '../../../base/common/lifecycle.js'; +import { TestMessageType } from '../../contrib/testing/common/testTypes.js'; +import { SerializableObjectWithBuffers } from '../../services/extensions/common/proxyIdentifier.js'; +import { MainThreadTestingShape, TestRunUpdate } from './extHost.protocol.js'; + +/** Batches ordered test run updates, flushing when the run or controller changes. */ +export class BatchedTestRunRpc extends Disposable { + private pendingUpdates: TestRunUpdate[] = []; + private pendingSize = 0; + private controllerId: string | undefined; + private runId: string | undefined; + private readonly scheduler = this._register(new RunOnceScheduler(() => this.flush(), 0)); + + constructor( + private readonly proxy: Pick, + ) { + super(); + } + + /** Queues an update, flushing when either the payload or entry limit is reached. */ + public add(controllerId: string, runId: string, update: TestRunUpdate): void { + if (this._store.isDisposed) { + return; + } + + // State updates are the hot path; avoid serializing them to estimate size. + let size: number; + if (update.type === 'state') { + size = update.taskId.length + update.testId.length; + } else if (update.type === 'output') { + const { output, ...metadata } = update; + // String encoding creates owned bytes; extension-owned bytes need a snapshot. + const buffer = typeof output === 'string' ? VSBuffer.fromString(output) : output.clone(); + size = buffer.byteLength + JSON.stringify(metadata).length; + update = { ...update, output: buffer }; + } else { + if (update.type === 'messages') { + update = { + ...update, + messages: update.messages.map(message => message.type === TestMessageType.Error && typeof message.message !== 'string' + ? { ...message, message: snapshotMarkdownTrust(message.message) } + : message), + }; + } else if (update.type === 'tests') { + update = { + ...update, + tests: update.tests.map(test => test.error && typeof test.error !== 'string' + ? { ...test, error: snapshotMarkdownTrust(test.error) } + : test), + }; + } + size = JSON.stringify(update).length; + } + + if (this.controllerId !== controllerId || this.runId !== runId || this.pendingSize + size > 64 * 1024) { + this.flush(); + } + this.controllerId = controllerId; + this.runId = runId; + this.pendingUpdates.push(update); + this.pendingSize += size; + if (this.pendingUpdates.length >= 1024 || this.pendingSize >= 64 * 1024) { + this.flush(); + } else if (!this.scheduler.isScheduled()) { + this.scheduler.schedule(); + } + } + + /** Delivers all earlier updates before a lifecycle or result-reading RPC. */ + public flush(): void { + this.scheduler.cancel(); + if (this.pendingUpdates.length) { + const updates = this.pendingUpdates; + this.pendingUpdates = []; + this.pendingSize = 0; + this.proxy.$applyTestRunUpdates(this.controllerId!, this.runId!, new SerializableObjectWithBuffers(updates)); + } + } + + public override dispose(): void { + this.flush(); + super.dispose(); + } +} + +function snapshotMarkdownTrust(markdown: IMarkdownString): IMarkdownString { + return typeof markdown.isTrusted === 'object' + ? { ...markdown, isTrusted: { enabledCommands: [...markdown.isTrusted.enabledCommands] } } + : markdown; +} diff --git a/src/vs/workbench/api/common/extHostTreeViews.ts b/src/vs/workbench/api/common/extHostTreeViews.ts index 6bfddce2fde1..2511340b4986 100644 --- a/src/vs/workbench/api/common/extHostTreeViews.ts +++ b/src/vs/workbench/api/common/extHostTreeViews.ts @@ -944,34 +944,39 @@ class ExtHostTreeView extends Disposable { private _createTreeNode(element: T, extensionTreeItem: vscode.TreeItem, parent: TreeNode | Root): TreeNode { this._validateTreeItem(extensionTreeItem); - const disposableStore = this._register(new DisposableStore()); - const handle = this._createHandle(element, extensionTreeItem, parent); - const icon = this._getLightIconPath(extensionTreeItem); - const item: ITreeItem = { - handle, - parentHandle: parent ? parent.item.handle : undefined, - label: toTreeItemLabel(extensionTreeItem.label, this._extension), - description: extensionTreeItem.description, - resourceUri: extensionTreeItem.resourceUri, - tooltip: this._getTooltip(extensionTreeItem.tooltip), - command: this._getCommand(disposableStore, extensionTreeItem.command), - contextValue: extensionTreeItem.contextValue, - icon, - iconDark: this._getDarkIconPath(extensionTreeItem) || icon, - themeIcon: this._getThemeIcon(extensionTreeItem), - collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? extHostTypes.TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, - accessibilityInformation: extensionTreeItem.accessibilityInformation, - checkbox: this._getCheckbox(extensionTreeItem), - }; - - return { - item, - extensionItem: extensionTreeItem, - parent, - children: undefined, - disposableStore, - dispose(): void { disposableStore.dispose(); } - }; + const disposableStore = new DisposableStore(); + try { + const handle = this._createHandle(element, extensionTreeItem, parent); + const icon = this._getLightIconPath(extensionTreeItem); + const item: ITreeItem = { + handle, + parentHandle: parent ? parent.item.handle : undefined, + label: toTreeItemLabel(extensionTreeItem.label, this._extension), + description: extensionTreeItem.description, + resourceUri: extensionTreeItem.resourceUri, + tooltip: this._getTooltip(extensionTreeItem.tooltip), + command: this._getCommand(disposableStore, extensionTreeItem.command), + contextValue: extensionTreeItem.contextValue, + icon, + iconDark: this._getDarkIconPath(extensionTreeItem) || icon, + themeIcon: this._getThemeIcon(extensionTreeItem), + collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? extHostTypes.TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, + accessibilityInformation: extensionTreeItem.accessibilityInformation, + checkbox: this._getCheckbox(extensionTreeItem), + }; + + return { + item, + extensionItem: extensionTreeItem, + parent, + children: undefined, + disposableStore, + dispose(): void { disposableStore.dispose(); } + }; + } catch (err) { + disposableStore.dispose(); + throw err; + } } private _getThemeIcon(extensionTreeItem: vscode.TreeItem): extHostTypes.ThemeIcon | undefined { @@ -1100,6 +1105,7 @@ class ExtHostTreeView extends Disposable { } private _addAllToClear(): void { + this._addTreeToClear(this._roots); this._roots = undefined; this._nodes.forEach(node => { this._nodesToClear.add(node); @@ -1109,11 +1115,23 @@ class ExtHostTreeView extends Disposable { this._childrenFetchTokens.clear(); } + /** + * Adds the given nodes and all their descendants to the nodes to clear. A node replaced in `_nodes` by a node + * for the same element under another parent is only reachable through its parent's children. + */ + private _addTreeToClear(nodes: readonly TreeNode[] | undefined): void { + for (const node of nodes ?? []) { + this._nodesToClear.add(node); + this._addTreeToClear(node.children); + } + } + private _clearNodes(nodes: TreeNode[]): void { dispose(nodes); } private _clearAll(): void { + this._addTreeToClear(this._roots); this._roots = undefined; this._elements.clear(); dispose(this._nodes.values()); @@ -1124,9 +1142,8 @@ class ExtHostTreeView extends Disposable { } override dispose() { - super.dispose(); - this._refreshCancellationSource.dispose(); - this._clearAll(); + this._refreshCancellationSource.dispose(); + super.dispose(); } } diff --git a/src/vs/workbench/api/common/extHostTypeConverters.ts b/src/vs/workbench/api/common/extHostTypeConverters.ts index 349842956929..84fafc0411ea 100644 --- a/src/vs/workbench/api/common/extHostTypeConverters.ts +++ b/src/vs/workbench/api/common/extHostTypeConverters.ts @@ -882,6 +882,111 @@ export namespace DocumentSymbol { } } +export namespace StructuralDiffContext { + export function to(context: languages.StructuralDiffContext): vscode.StructuralDiffContext { + return { + changes: context.changes.map(change => ({ + originalRange: Range.to(change.originalRange), + modifiedRange: Range.to(change.modifiedRange), + })), + }; + } +} + +export namespace StructuralDiff { + /** + * Converts the result of a provider. The main thread validates the result, so values are passed on unchanged or + * checked before they are converted, because a conversion must not turn an invalid value into a valid one. + */ + export function from(diff: vscode.StructuralDiff): languages.StructuralDiff { + return { + root: nodeFrom(diff.root), + isIncomplete: diff.isIncomplete, + }; + } + + function nodeFrom(node: vscode.StructuralDiffNode): languages.StructuralDiffNode { + return { + id: node.id, + originalItem: node.originalItem && itemFrom(node, 'original', node.originalItem), + modifiedItem: node.modifiedItem && itemFrom(node, 'modified', node.modifiedItem), + originalChanges: node.originalChanges.map(coverage => coverageFrom(node, 'original', coverage)), + modifiedChanges: node.modifiedChanges.map(coverage => coverageFrom(node, 'modified', coverage)), + // Only a missing list means no children, so that null does not become a valid value. + children: node.children === undefined ? [] : node.children.map(nodeFrom), + }; + } + + function itemFrom(node: vscode.StructuralDiffNode, side: 'original' | 'modified', item: vscode.StructuralDiffItem): languages.StructuralDiffItem { + // SymbolKind.from turns unknown kinds and numeric strings, such as '0', into valid kinds. + if (typeof item.kind !== 'number' || typeof types.SymbolKind[item.kind] !== 'string') { + throw new Error(`Invalid structural diff: node '${node.id}' has an invalid ${side} item kind`); + } + return { + name: item.name, + detail: item.detail, + kind: SymbolKind.from(item.kind), + range: rangeFrom(node, `${side} item range`, item.range), + selectionRange: item.selectionRange && rangeFrom(node, `${side} selection range`, item.selectionRange), + }; + } + + function coverageFrom(node: vscode.StructuralDiffNode, side: 'original' | 'modified', coverage: vscode.StructuralDiffCoverage): languages.StructuralDiffCoverage { + return { + textChangeIndex: coverage.textChangeIndex, + range: rangeFrom(node, `${side} change range`, coverage.range), + classification: coverage.classification, + tags: Array.isArray(coverage.tags) ? coverage.tags.slice() : coverage.tags, + }; + } + + function rangeFrom(node: vscode.StructuralDiffNode, description: string, range: vscode.Range): editorRange.IRange { + // Range.from turns lines and characters that are not numbers, such as null, into numbers. + if (!types.Range.isRange(range)) { + throw new Error(`Invalid structural diff: node '${node.id}' has an invalid ${description}`); + } + return Range.from(range); + } + + export function to(result: languages.StructuralDiffResult): vscode.StructuralDiffResult { + return { + root: nodeTo(result.root), + isIncomplete: result.isIncomplete, + context: StructuralDiffContext.to(result.context), + }; + } + + function nodeTo(node: languages.StructuralDiffNode): vscode.StructuralDiffNode { + return { + id: node.id, + originalItem: node.originalItem && itemTo(node.originalItem), + modifiedItem: node.modifiedItem && itemTo(node.modifiedItem), + originalChanges: node.originalChanges.map(coverageTo), + modifiedChanges: node.modifiedChanges.map(coverageTo), + children: node.children.map(nodeTo), + }; + } + + function itemTo(item: languages.StructuralDiffItem): vscode.StructuralDiffItem { + return { + name: item.name, + detail: item.detail, + kind: SymbolKind.to(item.kind), + range: Range.to(item.range), + selectionRange: item.selectionRange && Range.to(item.selectionRange), + }; + } + + function coverageTo(coverage: languages.StructuralDiffCoverage): vscode.StructuralDiffCoverage { + return { + textChangeIndex: coverage.textChangeIndex, + range: Range.to(coverage.range), + classification: coverage.classification, + tags: coverage.tags?.slice(), + }; + } +} + export namespace CallHierarchyItem { export function to(item: extHostProtocol.ICallHierarchyItemDto): types.CallHierarchyItem { diff --git a/src/vs/workbench/api/common/extHostTypes.ts b/src/vs/workbench/api/common/extHostTypes.ts index 8dd173e24099..b0903e0aeb53 100644 --- a/src/vs/workbench/api/common/extHostTypes.ts +++ b/src/vs/workbench/api/common/extHostTypes.ts @@ -300,6 +300,18 @@ export class DocumentSymbol { } } +export enum StructuralDiffClassification { + Declaration = 1, + Header = 2, + Implementation = 3, + Dependency = 4, + Other = 5, +} + +export enum StructuralDiffTag { + Test = 1, +} + export enum CodeActionTriggerKind { Invoke = 1, diff --git a/src/vs/workbench/api/test/browser/extHostDocumentContentProvider.test.ts b/src/vs/workbench/api/test/browser/extHostDocumentContentProvider.test.ts index 4f83fc7d9997..a10f43c2d0a4 100644 --- a/src/vs/workbench/api/test/browser/extHostDocumentContentProvider.test.ts +++ b/src/vs/workbench/api/test/browser/extHostDocumentContentProvider.test.ts @@ -12,15 +12,17 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/c import { ExtHostDocumentContentProvider } from '../../common/extHostDocumentContentProviders.js'; import { Emitter } from '../../../../base/common/event.js'; import { MainThreadDocumentContentProvidersShape } from '../../common/extHost.protocol.js'; -import { timeout } from '../../../../base/common/async.js'; +import { DeferredPromise, timeout } from '../../../../base/common/async.js'; import { runWithFakedTimers } from '../../../../base/test/common/timeTravelScheduler.js'; +import { CancellationError } from '../../../../base/common/errors.js'; suite('ExtHostDocumentContentProvider', () => { - ensureNoDisposablesAreLeakedInTestSuite(); + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); const resource = URI.parse('foo:bar'); let documentContentProvider: ExtHostDocumentContentProvider; + let documentsAndEditors: ExtHostDocumentsAndEditors; let mainThreadContentProvider: MainThreadDocumentContentProvidersShape; const changes: [uri: UriComponents, value: string][] = []; @@ -45,7 +47,7 @@ suite('ExtHostDocumentContentProvider', () => { }; const ehContext = SingleProxyRPCProtocol(mainThreadContentProvider); - const documentsAndEditors = new ExtHostDocumentsAndEditors(ehContext, new NullLogService()); + documentsAndEditors = new ExtHostDocumentsAndEditors(ehContext, new NullLogService()); documentsAndEditors.$acceptDocumentsAndEditorsDelta({ addedDocuments: [{ isDirty: false, @@ -96,5 +98,192 @@ suite('ExtHostDocumentContentProvider', () => { }); }); + test('applies three rapid content updates in order', async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + const contents = ['first', 'second', 'third']; + let counter = 0; + + disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + async provideTextDocumentContent() { + const content = contents[counter++]; + await timeout(content === 'second' ? 20 : 0); + return content; + } + })); + + emitter.fire(resource); + emitter.fire(resource); + emitter.fire(resource); + + await timeout(100); + + assert.deepStrictEqual(changes.map(([, value]) => value), contents); + }); + }); + + test('refreshes independent documents while another refresh is pending', async () => { + await runWithFakedTimers({}, async () => { + const firstResource = resource.with({ path: 'first' }); + const otherResource = resource.with({ path: 'other' }); + documentsAndEditors.$acceptDocumentsAndEditorsDelta({ + addedDocuments: [firstResource, otherResource].map(uri => ({ + isDirty: false, + languageId: 'foo', + uri, + versionId: 1, + lines: ['foo'], + EOL: '\n', + encoding: 'utf8' + })) + }); + const emitter = disposables.add(new Emitter()); + const firstContent = new DeferredPromise(); + const slowContent = new DeferredPromise(); + disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + provideTextDocumentContent(uri) { + if (uri.path === firstResource.path) { + return firstContent.p; + } + return uri.path === resource.path ? slowContent.p : 'fast'; + } + })); + + try { + emitter.fire(firstResource); + emitter.fire(resource); + emitter.fire(otherResource); + await firstContent.complete('first'); + await timeout(100); + + assert.deepStrictEqual(changes.filter(([uri]) => uri.path === otherResource.path).map(([, value]) => value), ['fast']); + } finally { + await firstContent.complete('first'); + await slowContent.complete('slow'); + await timeout(100); + } + }); + }); + + test('continues queued refreshes after rejection and unchanged content', async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + const contents = [undefined, 'foo', '', 'updated']; + let counter = 0; + disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + async provideTextDocumentContent() { + const content = contents[counter++]; + if (content === undefined) { + throw new CancellationError(); + } + return content; + } + })); + + for (const _ of contents) { + emitter.fire(resource); + } + await timeout(100); + + assert.deepStrictEqual(changes.map(([, value]) => value), ['', 'updated']); + }); + }); + test('ignores content returned after the document closes', async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + const content = new DeferredPromise(); + disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + provideTextDocumentContent() { + return content.p; + } + })); + + try { + emitter.fire(resource); + await timeout(0); + documentsAndEditors.$acceptDocumentsAndEditorsDelta({ removedDocuments: [resource] }); + } finally { + await content.complete('updated'); + await timeout(100); + } + + assert.deepStrictEqual(changes, []); + }); + }); + + test('ignores change events after provider disposal', async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + let calls = 0; + const registration = disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + provideTextDocumentContent() { + calls++; + return 'updated'; + } + })); + + registration.dispose(); + emitter.fire(resource); + await timeout(100); + + assert.strictEqual(calls, 0); + }); + }); + + test('ignores refreshes queued immediately before provider disposal', async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + let calls = 0; + const registration = disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + provideTextDocumentContent() { + calls++; + return 'updated'; + } + })); + + emitter.fire(resource); + registration.dispose(); + await timeout(100); + + assert.deepStrictEqual({ calls, changes }, { calls: 0, changes: [] }); + }); + }); + + for (const queueAnotherRefresh of [false, true]) { + test(`finishes an in-flight refresh after provider disposal${queueAnotherRefresh ? ' without starting queued refreshes' : ''}`, async () => { + await runWithFakedTimers({}, async () => { + const emitter = disposables.add(new Emitter()); + const content = new DeferredPromise(); + let calls = 0; + const registration = disposables.add(documentContentProvider.registerTextDocumentContentProvider(resource.scheme, { + onDidChange: emitter.event, + provideTextDocumentContent() { + calls++; + return content.p; + } + })); + + try { + emitter.fire(resource); + await timeout(0); + if (queueAnotherRefresh) { + emitter.fire(resource); + } + registration.dispose(); + } finally { + await content.complete('updated'); + await timeout(100); + } + + assert.deepStrictEqual({ calls, changes: changes.map(([, value]) => value) }, { calls: 1, changes: ['updated'] }); + }); + }); + } }); diff --git a/src/vs/workbench/api/test/browser/extHostLanguageFeatures.test.ts b/src/vs/workbench/api/test/browser/extHostLanguageFeatures.test.ts index 10a1e5fdfbb9..a4055582a5fd 100644 --- a/src/vs/workbench/api/test/browser/extHostLanguageFeatures.test.ts +++ b/src/vs/workbench/api/test/browser/extHostLanguageFeatures.test.ts @@ -73,6 +73,7 @@ suite('ExtHostLanguageFeatures', function () { let languageFeaturesService: ILanguageFeaturesService; let originalErrorHandler: (e: any) => any; let instantiationService: TestInstantiationService; + let extHostDocumentsAndEditors: ExtHostDocumentsAndEditors; setup(() => { @@ -107,7 +108,7 @@ suite('ExtHostLanguageFeatures', function () { originalErrorHandler = errorHandler.getUnexpectedErrorHandler(); setUnexpectedErrorHandler(() => { }); - const extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(rpcProtocol, new NullLogService()); + extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(rpcProtocol, new NullLogService()); extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({ addedDocuments: [{ isDirty: false, @@ -340,6 +341,100 @@ suite('ExtHostLanguageFeatures', function () { assert.deepStrictEqual(value.map(s => s.name), ['containers', 'container 0', 'name', 'ports', 'ports 0', 'containerPort']); }); + suite('Structural diff', () => { + const extension = { ...defaultExtension, enabledApiProposals: ['structuralDiff'] }; + let originalModel: ITextModel; + const context: languages.StructuralDiffContext = { + changes: [{ + originalRange: new EditorRange(1, 1, 1, 5), + modifiedRange: new EditorRange(1, 1, 1, 5), + }], + }; + + setup(() => { + originalModel = disposables.add(createTextModel(model.getValue(), undefined, undefined, URI.parse('far://testing/original.a'))); + extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({ + addedDocuments: [{ + isDirty: false, + versionId: originalModel.getVersionId(), + languageId: originalModel.getLanguageId(), + uri: originalModel.uri, + lines: originalModel.getLinesContent(), + EOL: originalModel.getEOL(), + encoding: 'utf8', + }], + }); + }); + + function createResult(): vscode.StructuralDiff { + const fullRange = new types.Range(0, 0, model.getLineCount() - 1, model.getLineMaxColumn(model.getLineCount()) - 1); + return { + root: { + id: 'file', + originalItem: { name: 'original.a', kind: types.SymbolKind.File, range: fullRange }, + modifiedItem: { name: 'file.a', kind: types.SymbolKind.File, range: fullRange }, + originalChanges: [], + modifiedChanges: [], + children: [], + }, + isIncomplete: true, + }; + } + + function provide(): Promise { + const provider = languageFeaturesService.structuralDiffProvider.ordered(model)[0]; + return Promise.resolve(provider.provideStructuralDiff(originalModel, model, context, CancellationToken.None)); + } + + test('registers and unregisters providers', async () => { + const registration = disposables.add(extHost.registerStructuralDiffProvider(extension, defaultSelector, { + provideStructuralDiff: () => undefined, + })); + await rpcProtocol.sync(); + const before = languageFeaturesService.structuralDiffProvider.all(model).length; + registration.dispose(); + await rpcProtocol.sync(); + assert.deepStrictEqual([before, languageFeaturesService.structuralDiffProvider.all(model).length], [1, 0]); + }); + + test('forwards both documents and the text changes and returns the converted result', async () => { + let received: { uris: string[]; contents: string[]; versions: number[]; context: vscode.StructuralDiffContext } | undefined; + const fullRange = { ...model.getFullModelRange() }; + disposables.add(extHost.registerStructuralDiffProvider(extension, defaultSelector, { + provideStructuralDiff: (originalDocument, modifiedDocument, value) => { + received = { + uris: [originalDocument.uri.toString(), modifiedDocument.uri.toString()], + contents: [originalDocument.getText(), modifiedDocument.getText()], + versions: [originalDocument.version, modifiedDocument.version], + context: value, + }; + return createResult(); + }, + })); + await rpcProtocol.sync(); + const result = await provide(); + assert.deepStrictEqual({ received, result }, { + received: { + uris: [originalModel.uri.toString(), model.uri.toString()], + contents: [originalModel.getValue(), model.getValue()], + versions: [originalModel.getVersionId(), model.getVersionId()], + context: { changes: [{ originalRange: new types.Range(0, 0, 0, 4), modifiedRange: new types.Range(0, 0, 0, 4) }] }, + }, + result: { + root: { + id: 'file', + originalItem: { name: 'original.a', kind: languages.SymbolKind.File, range: fullRange }, + modifiedItem: { name: 'file.a', kind: languages.SymbolKind.File, range: fullRange }, + originalChanges: [], + modifiedChanges: [], + children: [], + }, + isIncomplete: true, + }, + }); + }); + }); + // --- code lens test('CodeLens, evil provider', async () => { diff --git a/src/vs/workbench/api/test/browser/extHostNotebookKernel.test.ts b/src/vs/workbench/api/test/browser/extHostNotebookKernel.test.ts index 6e233f93e6e3..ad67df50fa64 100644 --- a/src/vs/workbench/api/test/browser/extHostNotebookKernel.test.ts +++ b/src/vs/workbench/api/test/browser/extHostNotebookKernel.test.ts @@ -30,6 +30,7 @@ import { ExtHostFileSystemInfo } from '../../common/extHostFileSystemInfo.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import { ExtHostSearch } from '../../common/extHostSearch.js'; import { URITransformerService } from '../../common/extHostUriTransformerService.js'; +import { TestMainThreadNotebookKernels } from './TestMainThreadNotebookKernels.js'; suite('NotebookKernel', function () { let rpcProtocol: TestRPCProtocol; @@ -198,6 +199,30 @@ suite('NotebookKernel', function () { assert.strictEqual(first.label, 'Far'); }); + for (const supportedLanguages of [undefined, []]) { + test(`reset supported languages with ${supportedLanguages === undefined ? 'undefined' : 'an empty array'}`, async function () { + const mainThreadKernels = disposables.add(new TestMainThreadNotebookKernels(rpcProtocol)); + rpcProtocol.set(MainContext.MainThreadNotebookKernels, mainThreadKernels.instance); + const kernel = disposables.add(extHostNotebookKernels.createNotebookController(nullExtensionDescription, 'foo', '*', 'Foo')); + kernel.supportedLanguages = ['javascript']; + await rpcProtocol.sync(); + + const registeredKernel = mainThreadKernels.getKernel('nullExtensionDescription/foo')!; + assert.deepStrictEqual(registeredKernel.supportedLanguages, ['javascript']); + + kernel.supportedLanguages = supportedLanguages; + await rpcProtocol.sync(); + + assert.deepStrictEqual({ + apiLanguages: kernel.supportedLanguages, + mainThreadLanguages: registeredKernel.supportedLanguages + }, { + apiLanguages: supportedLanguages, + mainThreadLanguages: ['typescript', 'javascript', 'python'] + }); + }); + } + test('execute - simple createNotebookCellExecution', function () { const kernel = disposables.add(extHostNotebookKernels.createNotebookController(nullExtensionDescription, 'foo', '*', 'Foo')); diff --git a/src/vs/workbench/api/test/browser/extHostTask.test.ts b/src/vs/workbench/api/test/browser/extHostTask.test.ts new file mode 100644 index 000000000000..7e5b6357f40b --- /dev/null +++ b/src/vs/workbench/api/test/browser/extHostTask.test.ts @@ -0,0 +1,97 @@ +/*--------------------------------------------------------------------------------------------- + * 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 type * as vscode from 'vscode'; +import { DeferredPromise, raceTimeout } from '../../../../base/common/async.js'; +import { mock } from '../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { NullLogService } from '../../../../platform/log/common/log.js'; +import { nullExtensionDescription } from '../../../services/extensions/common/extensions.js'; +import { MainThreadTaskShape } from '../../common/extHost.protocol.js'; +import { WorkerExtHostTask } from '../../common/extHostTask.js'; +import { CustomExecution, Task, TaskScope } from '../../common/extHostTypes.js'; +import { SingleProxyRPCProtocol } from '../common/testRPCProtocol.js'; + +suite('ExtHostTask', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + class TestExtHostTask extends WorkerExtHostTask { + dispose(): void { + this._onDidExecuteTask.dispose(); + this._onDidTerminateTask.dispose(); + this._onDidTaskProcessStarted.dispose(); + this._onDidTaskProcessEnded.dispose(); + this._onDidStartTaskProblemMatchers.dispose(); + this._onDidEndTaskProblemMatchers.dispose(); + } + } + + function createTaskService(provider: vscode.TaskProvider, createTaskId: () => Promise = async () => 'task-id'): TestExtHostTask { + const proxy = new class extends mock() { + override async $registerSupportedExecutions(): Promise { } + override $registerTaskSystem(): void { } + override async $registerTaskProvider(): Promise { } + override async $unregisterTaskProvider(): Promise { } + override $createTaskId(): Promise { return createTaskId(); } + }; + const service = store.add(new TestExtHostTask( + SingleProxyRPCProtocol(proxy), undefined!, undefined!, undefined!, undefined!, undefined!, + store.add(new NullLogService()), undefined! + )); + store.add(service.registerTaskProvider(nullExtensionDescription, 'test', provider)); + return service; + } + + for (const asynchronous of [false, true]) { + test(`propagates ${asynchronous ? 'asynchronous' : 'synchronous'} provider failures`, async () => { + const expected = new Error('provider failed'); + const service = createTaskService({ + provideTasks: () => { + if (asynchronous) { + return Promise.reject(expected); + } + throw expected; + }, + resolveTask: () => undefined + }); + const result = await raceTimeout(service.$provideTasks(0, {}).then(() => undefined, error => error), 100); + assert.strictEqual(result, expected); + }); + } + + function customTask(): Task { + return new Task({ type: 'test' }, TaskScope.Workspace, 'test', 'test', new CustomExecution(async () => { + throw new Error('Discovery must not execute the task'); + })); + } + + test('propagates task ID failures', async () => { + const expected = new Error('task ID failed'); + const service = createTaskService({ provideTasks: () => [customTask()], resolveTask: () => undefined }, async () => { throw expected; }); + const result = await raceTimeout(service.$provideTasks(0, { test: true }).then(() => undefined, error => error), 100); + assert.strictEqual(result, expected); + }); + + test('waits for custom task IDs before returning tasks', async () => { + const id = new DeferredPromise(); + const requested = new DeferredPromise(); + const service = createTaskService({ provideTasks: () => [customTask()], resolveTask: () => undefined }, () => { + requested.complete(); + return id.p; + }); + const result = service.$provideTasks(0, { test: true }); + await requested.p; + assert.strictEqual(await raceTimeout(result, 0), undefined); + await id.complete('task-id'); + assert.strictEqual((await result).tasks.length, 1); + }); + + test('accepts an empty provider result', async () => { + const service = createTaskService({ provideTasks: () => undefined, resolveTask: () => undefined }); + assert.deepStrictEqual((await service.$provideTasks(0, {})).tasks, []); + }); +}); diff --git a/src/vs/workbench/api/test/browser/extHostTesting.test.ts b/src/vs/workbench/api/test/browser/extHostTesting.test.ts index 823f16fb5923..ebccbf397674 100644 --- a/src/vs/workbench/api/test/browser/extHostTesting.test.ts +++ b/src/vs/workbench/api/test/browser/extHostTesting.test.ts @@ -8,28 +8,33 @@ import * as sinon from 'sinon'; import { DeferredPromise, timeout } from '../../../../base/common/async.js'; import { VSBuffer } from '../../../../base/common/buffer.js'; import { CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { errorHandler } from '../../../../base/common/errors.js'; import { Event } from '../../../../base/common/event.js'; import { Iterable } from '../../../../base/common/iterator.js'; -import { toDisposable } from '../../../../base/common/lifecycle.js'; import { URI } from '../../../../base/common/uri.js'; import { mock, mockObject, MockObject } from '../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import * as editorRange from '../../../../editor/common/core/range.js'; import { ExtensionIdentifier, IExtensionDescription } from '../../../../platform/extensions/common/extensions.js'; import { NullLogService } from '../../../../platform/log/common/log.js'; -import { MainThreadTestingShape } from '../../common/extHost.protocol.js'; +import { NullTelemetryService } from '../../../../platform/telemetry/common/telemetryUtils.js'; +import { SerializableObjectWithBuffers } from '../../../services/extensions/common/proxyIdentifier.js'; +import { MainContext, MainThreadCommandsShape, MainThreadTestingShape, TestRunUpdate } from '../../common/extHost.protocol.js'; import { ExtHostCommands } from '../../common/extHostCommands.js'; import { ExtHostDocumentsAndEditors } from '../../common/extHostDocumentsAndEditors.js'; import { IExtHostTelemetry } from '../../common/extHostTelemetry.js'; +import { BatchedTestRunRpc } from '../../common/extHostTestingBatchedRpc.js'; import { ExtHostTesting, TestRunCoordinator, TestRunDto, TestRunProfileImpl } from '../../common/extHostTesting.js'; import { ExtHostTestItemCollection, TestItemImpl } from '../../common/extHostTestItem.js'; import * as convert from '../../common/extHostTypeConverters.js'; -import { Location, MarkdownString, Position, Range, TestMessage, TestRunProfileKind, TestRunRequest as TestRunRequestImpl, TestTag } from '../../common/extHostTypes.js'; -import { AnyCallRPCProtocol } from '../common/testRPCProtocol.js'; +import { FileCoverage, Location, MarkdownString, Position, Range, TestMessage, TestRunProfileKind, TestRunRequest as TestRunRequestImpl, TestTag } from '../../common/extHostTypes.js'; +import { MainThreadTesting } from '../../browser/mainThreadTesting.js'; +import { SingleProxyRPCProtocol, TestRPCProtocol } from '../common/testRPCProtocol.js'; import { TestId } from '../../../contrib/testing/common/testId.js'; -import { TestDiffOpType, TestItemExpandState, TestMessageType, TestsDiff, TestsDiffOp } from '../../../contrib/testing/common/testTypes.js'; +import { LiveTestResult } from '../../../contrib/testing/common/testResult.js'; +import { ITestItem, ITestMessage, ITestRunTask, TestDiffOpType, TestItemExpandState, TestMessageType, TestResultState, TestRunProfileBitset, TestsDiff, TestsDiffOp } from '../../../contrib/testing/common/testTypes.js'; import { nullExtensionDescription } from '../../../services/extensions/common/extensions.js'; -import type { TestController, TestItem, TestRunProfile, TestRunRequest } from 'vscode'; +import type { TestController, TestItem, TestRun, TestRunProfile, TestRunRequest } from 'vscode'; const simplify = (item: TestItem) => ({ id: item.id, @@ -914,6 +919,106 @@ suite('ExtHost Testing', () => { // }); }); + test('transfers ordered test updates and output through RPC', async () => { + const calls: string[] = []; + const receiver = new class extends mock() { + override $addTestsToRun = sinon.stub().callsFake(() => calls.push('tests')); + override $updateTestStateInRun = sinon.stub().callsFake(() => calls.push('state')); + override $appendOutputToRun = sinon.stub().callsFake(() => calls.push('output')); + override $appendTestMessagesInRun = sinon.stub().callsFake(() => calls.push('messages')); + override $applyTestRunUpdates(controllerId: string, runId: string, updates: SerializableObjectWithBuffers) { + MainThreadTesting.prototype.$applyTestRunUpdates.call(this, controllerId, runId, updates); + } + }; + const rpc = new TestRPCProtocol(); + rpc.set(MainContext.MainThreadTesting, receiver); + await rpc.getProxy(MainContext.MainThreadTesting).$applyTestRunUpdates('ctrl', 'run', new SerializableObjectWithBuffers([ + { type: 'tests', tests: [] }, + { type: 'state', taskId: 'task', testId: 'test', state: TestResultState.Running }, + { type: 'output', taskId: 'task', testId: 'test', output: 'hello \u2713' }, + { type: 'output', taskId: 'task', testId: 'test', output: VSBuffer.wrap(new Uint8Array([0x00, 0xe2, 0x9c])) }, + { type: 'output', taskId: 'task', testId: 'test', output: VSBuffer.wrap(new Uint8Array([0x93, 0xff])) }, + { type: 'messages', taskId: 'task', testId: 'test', messages: [] }, + { type: 'state', taskId: 'task', testId: 'test', state: TestResultState.Passed, duration: 2 }, + ])); + assert.deepStrictEqual(calls, ['tests', 'state', 'output', 'output', 'output', 'messages', 'state']); + assert.deepStrictEqual(receiver.$appendOutputToRun.args, [ + ['run', 'task', VSBuffer.fromString('hello \u2713'), undefined, 'test'], + ['run', 'task', VSBuffer.wrap(new Uint8Array([0x00, 0xe2, 0x9c])), undefined, 'test'], + ['run', 'task', VSBuffer.wrap(new Uint8Array([0x93, 0xff])), undefined, 'test'], + ]); + }); + + test('batched RPC owns byte output and flushes once on disposal', async () => { + const batches: string[][] = []; + const receiver = new class extends mock() { + override $appendOutputToRun = sinon.stub(); + override $applyTestRunUpdates(controllerId: string, runId: string, updates: SerializableObjectWithBuffers) { + batches.push(updates.value.map(update => update.type)); + MainThreadTesting.prototype.$applyTestRunUpdates.call(this, controllerId, runId, updates); + } + }; + const rpc = new TestRPCProtocol(); + rpc.set(MainContext.MainThreadTesting, receiver); + const batchedRpc = ds.add(new BatchedTestRunRpc(rpc.getProxy(MainContext.MainThreadTesting))); + const bytes = new Uint8Array([0x00, 0xff, 0xe2]); + batchedRpc.add('ctrl', 'run', { type: 'output', taskId: 'task', output: VSBuffer.wrap(bytes.subarray(1)) }); + bytes.fill(0); + batchedRpc.add('ctrl', 'run', { type: 'output', taskId: 'task', output: 'after' }); + batchedRpc.dispose(); + batchedRpc.add('ctrl', 'run', { type: 'output', taskId: 'task', output: 'ignored' }); + await rpc.sync(); + assert.deepStrictEqual({ batches, output: receiver.$appendOutputToRun.args }, { + batches: [['output', 'output']], + output: [ + ['run', 'task', VSBuffer.wrap(new Uint8Array([0xff, 0xe2])), undefined, undefined], + ['run', 'task', VSBuffer.fromString('after'), undefined, undefined], + ], + }); + }); + + + test('flushes controller boundaries in call order within a shared run', () => { + const proxy = mockObject()(); + const rpc = ds.add(new BatchedTestRunRpc(proxy)); + rpc.add('first', 'run', { type: 'output', taskId: 'one', output: 'one' }); + rpc.add('second', 'run', { type: 'output', taskId: 'two', output: 'two' }); + rpc.add('first', 'run', { type: 'output', taskId: 'three', output: 'three' }); + rpc.flush(); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([controllerId, runId, updates]) => ({ controllerId, runId, taskIds: updates.value.map((update: TestRunUpdate) => update.type === 'tests' ? undefined : update.taskId) })), [ + { controllerId: 'first', runId: 'run', taskIds: ['one'] }, + { controllerId: 'second', runId: 'run', taskIds: ['two'] }, + { controllerId: 'first', runId: 'run', taskIds: ['three'] }, + ]); + }); + + test('continues applying a batch after an update handler throws', async () => { + const calls: string[] = []; + const error = new Error('Unknown task'); + const reportError = sinon.stub(errorHandler, 'onUnexpectedError'); + const receiver = new class extends mock() { + override $updateTestStateInRun(_runId: string, taskId: string) { + if (taskId === 'unknown') { + throw error; + } + calls.push(taskId); + } + override $appendOutputToRun() { calls.push('output'); } + override $applyTestRunUpdates(controllerId: string, runId: string, updates: SerializableObjectWithBuffers) { + MainThreadTesting.prototype.$applyTestRunUpdates.call(this, controllerId, runId, updates); + } + }; + const rpc = new TestRPCProtocol(); + rpc.set(MainContext.MainThreadTesting, receiver); + await rpc.getProxy(MainContext.MainThreadTesting).$applyTestRunUpdates('ctrl', 'run', new SerializableObjectWithBuffers([ + { type: 'state', taskId: 'first', testId: 'test', state: TestResultState.Running }, + { type: 'state', taskId: 'unknown', testId: 'test', state: TestResultState.Running }, + { type: 'output', taskId: 'first', output: 'still delivered' }, + { type: 'state', taskId: 'last', testId: 'test', state: TestResultState.Passed }, + ])); + assert.deepStrictEqual({ calls, errors: reportError.args }, { calls: ['first', 'output', 'last'], errors: [[error]] }); + }); + suite('TestRunTracker', () => { let proxy: MockObject; let c: TestRunCoordinator; @@ -923,6 +1028,7 @@ suite('ExtHost Testing', () => { let req: TestRunRequest; let dto: TestRunDto; + let clock: sinon.SinonFakeTimers; // eslint-disable-next-line local/code-no-any-casts const ext: IExtensionDescription = {} as any; @@ -930,12 +1036,31 @@ suite('ExtHost Testing', () => { for (const { id } of c.trackers) { c.disposeTestRun(id); } + clock.restore(); }); setup(async () => { proxy = mockObject()(); + proxy.$applyTestRunUpdates.callsFake((controllerId: string, runId: string, updates: SerializableObjectWithBuffers) => { + for (const update of updates.value) { + switch (update.type) { + case 'tests': + proxy.$addTestsToRun(controllerId, runId, update.tests); + break; + case 'state': + proxy.$updateTestStateInRun(runId, update.taskId, update.testId, update.state, update.duration); + break; + case 'messages': + proxy.$appendTestMessagesInRun(runId, update.taskId, update.testId, update.messages); + break; + case 'output': + proxy.$appendOutputToRun(runId, update.taskId, typeof update.output === 'string' ? VSBuffer.fromString(update.output) : update.output, update.location, update.testId); + break; + } + } + }); cts = new CancellationTokenSource(); - c = new TestRunCoordinator(proxy, new NullLogService()); + c = ds.add(new TestRunCoordinator(proxy, new NullLogService())); configuration = new TestRunProfileImpl(mockObject()(), new Map(), new Set(), Event.None, 'ctrlId', 42, 'Do Run', TestRunProfileKind.Run, () => { }, false); @@ -956,6 +1081,199 @@ suite('ExtHost Testing', () => { runId: 'run-id', testIds: [single.root.id], }, single); + clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + }); + + test('batches ordered state, message, and output updates', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!.children.get('id-aa')!; + task.started(test); + task.appendOutput('hello', undefined, test); + task.failed(test, new TestMessage('failure'), 2); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + clock.tick(0); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)), [['tests', 'state', 'output', 'messages', 'state']]); + task.passed(test, 3); + task.end(); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 2); + assert.ok(proxy.$finishedTestRunTask.calledAfter(proxy.$applyTestRunUpdates)); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 2); + }); + + test('flushes earlier updates before starting another task', () => { + const first = c.createTestRun(ext, 'ctrlId', single, req, 'first', false); + first.appendOutput('hello'); + const second = c.createTestRun(ext, 'ctrlId', single, req, 'second', false); + assert.ok(proxy.$startedTestRunTask.getCall(1).calledAfter(proxy.$applyTestRunUpdates.getCall(0))); + assert.strictEqual(proxy.$applyTestRunUpdates.firstCall.args[2].value[0].taskId, proxy.$startedTestRunTask.firstCall.args[1].id); + first.end(); + second.end(); + }); + + test('sends included tests before publishing coverage', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!.children.get('id-aa')!; + task.addCoverage(new FileCoverage(URI.file('/coverage.ts'), { covered: 1, total: 1 }, undefined, undefined, [test])); + assert.strictEqual(proxy.$addTestsToRun.callCount, 1); + assert.ok(proxy.$appendCoverage.calledAfter(proxy.$applyTestRunUpdates)); + task.end(); + }); + + test('bounds batches during a synchronous stream of updates', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!.children.get('id-aa')!; + for (let i = 0; i < 2048; i++) { + task.started(test); + } + task.end(); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.length), [1024, 1024, 1]); + }); + + for (const kind of ['string', 'bytes'] as const) { + test(`flushes large ${kind} output without waiting for a timer`, () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + task.appendOutput(kind === 'string' ? 'x'.repeat(64 * 1024) : new Uint8Array(64 * 1024)); + assert.deepStrictEqual(proxy.$appendOutputToRun.args.map(args => args[2].byteLength), [64 * 1024]); + task.end(); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + }); + } + + for (const kind of ['string', 'bytes'] as const) { + test(`batches ${kind} output as buffers and bounds its cumulative byte payload`, () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const output = kind === 'string' ? '\u2713'.repeat(14 * 1024) : new Uint8Array(42 * 1024).fill(0x61); + task.appendOutput(output); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + task.appendOutput(output); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + task.end(); + assert.deepStrictEqual({ + batchLengths: proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.length), + binaryOutput: proxy.$applyTestRunUpdates.args.every(([, , updates]) => updates.value.every((update: TestRunUpdate) => update.type === 'output' && update.output instanceof VSBuffer)), + outputSizes: proxy.$appendOutputToRun.args.map(args => args[2].byteLength), + }, { batchLengths: [1, 1], binaryOutput: true, outputSizes: [42 * 1024, 42 * 1024] }); + }); + } + + test('preserves split UTF-8 byte output and its order with batched updates', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!; + const firstChunk = new Uint8Array([0xe2, 0x9c]); + task.started(test); + task.appendOutput('before '); + task.appendOutput(firstChunk, undefined, test); + firstChunk.fill(0); + task.appendOutput(new Uint8Array([0x93]), undefined, test); + task.appendOutput(' after'); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + task.end(); + + assert.deepStrictEqual({ + output: VSBuffer.concat(proxy.$appendOutputToRun.args.map(args => args[2])).toString(), + registeredBeforeOutput: proxy.$addTestsToRun.calledBefore(proxy.$appendOutputToRun), + byteTestIds: proxy.$appendOutputToRun.args.slice(1, 3).map(args => args[4]), + batches: proxy.$applyTestRunUpdates.callCount, + }, { output: 'before \u2713 after', registeredBeforeOutput: true, byteTestIds: ['ctrlId\0id-a', 'ctrlId\0id-a'], batches: 1 }); + }); + + test('ignores byte output after the tracker is disposed', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + c.disposeTestRun(Iterable.first(c.trackers)!.id); + task.appendOutput(new Uint8Array([0x61])); + assert.strictEqual(proxy.$appendOutputToRun.called, false); + }); + + + for (const outputLength of [100, 64 * 1024]) { + test(`encodes ${outputLength} string bytes once while snapshotting extension bytes`, () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const clone = sinon.spy(VSBuffer.prototype, 'clone'); + task.appendOutput('x'.repeat(outputLength)); + assert.strictEqual(clone.callCount, 0); + const bytes = new Uint8Array([97, 98]); + task.appendOutput(bytes); + assert.strictEqual(clone.callCount, 1); + bytes.fill(0); + task.end(); + assert.deepStrictEqual(proxy.$appendOutputToRun.args.map(args => args[2].toString()), ['x'.repeat(outputLength), 'ab']); + }); + } + + for (const target of ['message', 'registration'] as const) { + test(`snapshots the Markdown trust object and command array for a ${target}`, () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const item = single.root.children.get('id-a')!; + const commands = ['original']; + const trust = { enabledCommands: commands }; + const markdown = new MarkdownString('Original message'); + markdown.isTrusted = trust; + if (target === 'message') { + task.failed(item, new TestMessage(markdown)); + } else { + item.error = markdown; + task.started(item); + } + commands.push('later'); + trust.enabledCommands = ['replacement']; + markdown.value = 'Changed message'; + clock.tick(0); + const actual = target === 'message' + ? proxy.$appendTestMessagesInRun.firstCall.args[3][0].message + : proxy.$addTestsToRun.firstCall.args[2].find((test: ITestItem.Serialized) => test.extId === 'ctrlId\0id-a')!.error; + assert.ok(actual && typeof actual !== 'string'); + assert.strictEqual(actual.value, 'Original message'); + assert.deepStrictEqual(actual.isTrusted, { enabledCommands: ['original'] }); + assert.notStrictEqual(actual.isTrusted, trust); + task.end(); + }); + } + + test('bounds cumulative failure snapshot payloads before the timer fires', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!; + const message = TestMessage.diff('failure', 'e'.repeat(20 * 1024), 'a'.repeat(20 * 1024)); + task.failed(test, message); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + task.failed(test, message); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + task.end(); + + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)), [ + ['tests', 'messages', 'state'], ['messages', 'state'], + ]); + }); + + test('flushes oversized failure messages separately and resets the payload budget', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!; + task.failed(test, new TestMessage('x'.repeat(64 * 1024))); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)), [['tests'], ['messages']]); + task.appendOutput('small'); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 2); + task.end(); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.lastCall.args[2].value.map((update: TestRunUpdate) => update.type), ['state', 'output']); + }); + + test('counts registration payloads toward the batch limit', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const test = single.root.children.get('id-a')!; + test.label = 'x'.repeat(64 * 1024); + task.started(test); + assert.deepStrictEqual(proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)), [['tests']]); + task.end(); + }); + + test('flushes pending updates and cancels the timer when disposed', () => { + const task = c.createTestRun(ext, 'ctrlId', single, req, 'run', false); + const tracker = Iterable.first(c.trackers)!; + task.appendOutput('hello'); + c.disposeTestRun(tracker.id); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); }); test('tracks a run started from a main thread request', () => { @@ -968,6 +1286,7 @@ suite('ExtHost Testing', () => { assert.strictEqual(tracker.hasRunningTasks, true); task1.appendOutput('hello'); + clock.tick(0); const taskId = proxy.$appendOutputToRun.args[0]?.[1]; assert.deepStrictEqual([['run-id', taskId, VSBuffer.fromString('hello'), undefined, undefined]], proxy.$appendOutputToRun.args); task1.end(); @@ -981,9 +1300,180 @@ suite('ExtHost Testing', () => { assert.strictEqual(tracker.hasRunningTasks, false); }); + + for (const flush of ['timer', 'task end', 'result disposal'] as const) { + test(`preserves interleaved independent run updates on ${flush}`, () => { + const first = c.createTestRun(ext, 'ctrlId', single, req, 'first', true); + const second = c.createTestRun(ext, 'ctrlId', single, { ...req }, 'second', true); + const one = single.root.children.get('id-a')!.children.get('id-aa')!; + const two = single.root.children.get('id-a')!.children.get('id-ab')!; + const three = single.root.children.get('id-a')!; + first.started(one); + second.started(two); + first.started(three); + if (flush === 'timer') { + clock.tick(0); + } else if (flush === 'task end') { + first.end(); + } else { + c.disposeTestRun(proxy.$startedExtensionTestRun.firstCall.args[0].id); + } + assert.deepStrictEqual(proxy.$updateTestStateInRun.args.map(args => args[2]), [one, two, three].map(test => TestId.fromExtHostTestItem(test, 'ctrlId').toString())); + second.passed(two, 1); + clock.tick(0); + assert.deepStrictEqual(proxy.$updateTestStateInRun.lastCall.args.slice(2), [TestId.fromExtHostTestItem(two, 'ctrlId').toString(), TestResultState.Passed, 1]); + first.end(); + second.end(); + }); + } + + test('flushes pending updates without visiting historical trackers', () => { + for (let i = 0; i < 256; i++) { + c.createTestRun(ext, 'ctrlId', single, { ...req }, `previous ${i}`, true).end(); + } + const historicalFlushes = [...c.trackers].map(tracker => sinon.spy(tracker, 'flushUpdates')); + const active = c.createTestRun(ext, 'ctrlId', single, req, 'active', true); + const test = single.root.children.get('id-a')!; + active.started(test); + c.flushUpdates(); + c.markTestRetired(undefined); + clock.tick(0); + assert.deepStrictEqual({ + historicalFlushes: historicalFlushes.reduce((sum, spy) => sum + spy.callCount, 0), + updates: proxy.$updateTestStateInRun.args.map(args => args[2]), + batches: proxy.$applyTestRunUpdates.callCount, + }, { historicalFlushes: 0, updates: [TestId.fromExtHostTestItem(test, 'ctrlId').toString()], batches: 1 }); + active.end(); + }); + + for (const flush of ['timer', 'task end', 'result disposal'] as const) { + test(`preserves interleaved profile updates on ${flush}`, () => { + const sharedDto = new TestRunDto('ctrlId', dto.id, true, single); + const secondProfile = ds.add(new TestRunProfileImpl(proxy, new Map(), new Set(), Event.None, 'ctrlId', 43, 'Second', TestRunProfileKind.Run, () => { }, false)); + const secondRequest = { ...req, profile: secondProfile }; + c.prepareForMainThreadTestRun(ext, req, sharedDto, configuration, cts.token); + c.prepareForMainThreadTestRun(ext, secondRequest, sharedDto, secondProfile, cts.token); + const firstDisposed = sinon.stub(); + const secondDisposed = sinon.stub(); + const first = c.createTestRun(ext, 'ctrlId', single, req, 'first', true); + const second = c.createTestRun(ext, 'ctrlId', single, secondRequest, 'second', true); + ds.add(first.onDidDispose(firstDisposed)); + ds.add(second.onDidDispose(secondDisposed)); + const one = single.root.children.get('id-a')!.children.get('id-aa')!; + const two = single.root.children.get('id-a')!.children.get('id-ab')!; + const three = single.root.children.get('id-a')!; + first.started(one); + second.started(two); + first.started(three); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + if (flush === 'timer') { + clock.tick(0); + } else if (flush === 'task end') { + second.end(); + assert.ok(proxy.$finishedTestRunTask.calledAfter(proxy.$applyTestRunUpdates)); + first.passed(one); + clock.tick(0); + } else { + c.disposeTestRun(sharedDto.id); + assert.strictEqual(firstDisposed.callCount, 1); + assert.strictEqual(secondDisposed.callCount, 1); + first.started(one); + second.appendOutput('ignored'); + } + assert.deepStrictEqual(proxy.$updateTestStateInRun.args.slice(0, 3).map(args => args[2]), [one, two, three].map(item => TestId.fromExtHostTestItem(item, 'ctrlId').toString())); + const count = proxy.$applyTestRunUpdates.callCount; + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, count); + if (flush !== 'result disposal') { + first.end(); + second.end(); + } + }); + } + + for (const firstToEnd of ['first', 'second'] as const) { + test(`preserves both profiles' results when the ${firstToEnd} profile ends first`, () => { + const sharedDto = new TestRunDto('ctrlId', dto.id, true, single); + const result = ds.add(new LiveTestResult(sharedDto.id, false, { group: TestRunProfileBitset.Run, targets: [] }, 0, NullTelemetryService)); + const uriIdentity = { asCanonicalUri: (uri: URI) => uri }; + proxy.$startedTestRunTask.callsFake((_runId: string, task: ITestRunTask) => result.addTask(task)); + proxy.$finishedTestRunTask.callsFake((_runId: string, taskId: string) => result.markTaskComplete(taskId)); + proxy.$addTestsToRun.callsFake((controllerId: string, _runId: string, tests: ITestItem.Serialized[]) => result.addTestChainToRun(controllerId, tests.map(test => ITestItem.deserialize(uriIdentity, test)))); + proxy.$updateTestStateInRun.callsFake((_runId: string, taskId: string, testId: string, state: TestResultState, duration?: number) => result.updateState(testId, taskId, state, duration)); + proxy.$appendTestMessagesInRun.callsFake((_runId: string, taskId: string, testId: string, messages: ITestMessage.Serialized[]) => { + for (const message of messages) { + result.appendMessage(testId, taskId, ITestMessage.deserialize(uriIdentity, message)); + } + }); + + const secondProfile = ds.add(new TestRunProfileImpl(proxy, new Map(), new Set(), Event.None, 'ctrlId', 43, 'Second', TestRunProfileKind.Run, () => { }, false)); + const secondRequest = { ...req, profile: secondProfile }; + ds.add(c.prepareForMainThreadTestRun(ext, req, sharedDto, configuration, cts.token)); + ds.add(c.prepareForMainThreadTestRun(ext, secondRequest, sharedDto, secondProfile, cts.token)); + const first = c.createTestRun(ext, 'ctrlId', single, req, 'first', true); + const second = c.createTestRun(ext, 'ctrlId', single, secondRequest, 'second', true); + const test = single.root.children.get('id-a')!.children.get('id-aa')!; + const testId = TestId.fromExtHostTestItem(test, 'ctrlId').toString(); + first.started(test); + second.started(test); + first.failed(test, new TestMessage('first profile failure'), 2); + second.passed(test, 3); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 0); + + const endingOrder = firstToEnd === 'first' ? [first, second] : [second, first]; + endingOrder[0].end(); + const registered = result.getStateById(testId)!; + assert.deepStrictEqual(registered.tasks.map(task => task.state), [TestResultState.Failed, TestResultState.Passed]); + endingOrder[1].end(); + clock.tick(0); + const actual = result.getStateById(testId)!; + assert.deepStrictEqual({ + sameItem: actual === registered, + states: actual.tasks.map(task => task.state), + durations: actual.tasks.map(task => task.duration), + messages: actual.tasks.map(task => task.messages.map(message => message.type === TestMessageType.Error ? message.message : undefined)), + computedState: actual.computedState, + rootState: result.getStateById('ctrlId')!.computedState, + counts: [result.counts[TestResultState.Unset], result.counts[TestResultState.Failed], result.counts[TestResultState.Passed]], + }, { + sameItem: true, + states: [TestResultState.Failed, TestResultState.Passed], + durations: [2, 3], + messages: [['first profile failure'], []], + computedState: TestResultState.Failed, + rootState: TestResultState.Failed, + counts: [2, 1, 0], + }); + }); + } + + for (const invalidateAll of [false, true]) { + test(`flushes every profile sharing a run ID before retiring ${invalidateAll ? 'all results' : 'a test'}`, () => { + const secondProfile = ds.add(new TestRunProfileImpl(proxy, new Map(), new Set(), Event.None, 'ctrlId', 43, 'Second', TestRunProfileKind.Run, () => { }, false)); + const secondRequest = { ...req, profile: secondProfile }; + ds.add(c.prepareForMainThreadTestRun(ext, req, dto, configuration, cts.token)); + ds.add(c.prepareForMainThreadTestRun(ext, secondRequest, dto, secondProfile, cts.token)); + const first = c.createTestRun(ext, 'ctrlId', single, req, 'first', true); + const second = c.createTestRun(ext, 'ctrlId', single, secondRequest, 'second', true); + first.started(single.root.children.get('id-a')!); + second.started(single.root.children.get('id-b')!); + const calls: string[] = []; + proxy.$applyTestRunUpdates.callsFake(() => calls.push('updates')); + proxy.$markTestRetired.callsFake(() => calls.push('retire')); + + c.markTestRetired(invalidateAll ? undefined : ['ctrlId\0id-a']); + + assert.deepStrictEqual({ calls, runIds: proxy.$applyTestRunUpdates.args.map(args => args[1]) }, { + calls: ['updates', 'retire'], runIds: ['run-id'], + }); + clock.tick(0); + assert.deepStrictEqual(calls, ['updates', 'retire']); + first.end(); + second.end(); + }); + } + test('run cancel force ends after a timeout', () => { - const clock = sinon.useFakeTimers(); - ds.add(toDisposable(() => clock.restore())); const tracker = ds.add(c.prepareForMainThreadTestRun(ext, req, dto, configuration, cts.token)); const task = c.createTestRun(ext, 'ctrl', single, req, 'run1', true); const onEnded = sinon.stub(); @@ -1063,6 +1553,7 @@ suite('ExtHost Testing', () => { assert.deepStrictEqual(proxy.$addTestsToRun.args, expectedArgs); task1.passed(single.root.children.get('id-a')!.children.get('id-aa')!); + clock.tick(0); expectedArgs.push([ 'ctrlId', tracker.id, @@ -1075,6 +1566,7 @@ suite('ExtHost Testing', () => { assert.deepStrictEqual(proxy.$addTestsToRun.args, expectedArgs); task1.enqueued(single.root.children.get('id-a')!.children.get('id-ab')!); + clock.tick(0); expectedArgs.push([ 'ctrlId', tracker.id, @@ -1086,6 +1578,7 @@ suite('ExtHost Testing', () => { assert.deepStrictEqual(proxy.$addTestsToRun.args, expectedArgs); task1.passed(single.root.children.get('id-a')!.children.get('id-ab')!); + clock.tick(0); assert.deepStrictEqual(proxy.$addTestsToRun.args, expectedArgs); task1.end(); @@ -1101,6 +1594,7 @@ suite('ExtHost Testing', () => { const message1 = new TestMessage('some message'); message1.location = new Location(URI.file('/a.txt'), new Position(0, 0)); task.failed(test1, message1); + clock.tick(0); const args = proxy.$appendTestMessagesInRun.args[0]; assert.deepStrictEqual(proxy.$appendTestMessagesInRun.args[0], [ @@ -1120,6 +1614,7 @@ suite('ExtHost Testing', () => { // should use test location as default task.failed(test2, new TestMessage('some message')); + clock.tick(0); assert.deepStrictEqual(proxy.$appendTestMessagesInRun.args[1], [ args[0], args[1], @@ -1144,8 +1639,12 @@ suite('ExtHost Testing', () => { task.failed(single.root, new TestMessage('some message')); task.appendOutput('output'); + assert.doesNotThrow(() => task.appendOutput(undefined!)); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.called, false); assert.strictEqual(proxy.$addTestsToRun.called, false); + assert.strictEqual(proxy.$updateTestStateInRun.called, false); assert.strictEqual(proxy.$appendOutputToRun.called, false); assert.strictEqual(proxy.$appendTestMessagesInRun.called, false); }); @@ -1163,6 +1662,7 @@ suite('ExtHost Testing', () => { task1.passed(childA); task1.passed(childB); + clock.tick(0); assert.deepStrictEqual(proxy.$addTestsToRun.args, [ [ 'ctrl', @@ -1182,6 +1682,8 @@ suite('ExtHost Testing', () => { suite('service', () => { let ctrl: TestExtHostTesting; + let proxy: MockObject; + let commands: ExtHostCommands; class TestExtHostTesting extends ExtHostTesting { public getProfileInternalId(ctrl: TestController, profile: TestRunProfile) { @@ -1196,19 +1698,125 @@ suite('ExtHost Testing', () => { } setup(() => { - const rpcProtocol = AnyCallRPCProtocol(); + proxy = mockObject()(); + const rpcProtocol = SingleProxyRPCProtocol(proxy); + commands = new ExtHostCommands(rpcProtocol, new NullLogService(), new class extends mock() { + override onExtensionError(): boolean { + return true; + } + }); ctrl = ds.add(new TestExtHostTesting( rpcProtocol, new NullLogService(), - new ExtHostCommands(rpcProtocol, new NullLogService(), new class extends mock() { - override onExtensionError(): boolean { - return true; - } - }), + commands, new ExtHostDocumentsAndEditors(rpcProtocol, new NullLogService()), )); }); + for (const command of ['vscode.peekTestError', 'testing.openOutputPeek']) { + test(`publishes pending failures before executing ${command}`, async () => { + const controller = ds.add(ctrl.createTestController(nullExtensionDescription, 'ctrl', 'tests')); + const item = controller.createTestItem('test', 'test'); + controller.items.add(item); + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const run = controller.createTestRun(new TestRunRequestImpl()); + try { + const calls: string[] = []; + proxy.$applyTestRunUpdates.callsFake(() => calls.push('updates')); + proxy.$executeCommand.callsFake(async id => { calls.push(id); return undefined; }); + run.failed(item, new TestMessage('failure')); + await commands.executeCommand('unrelated.command'); + await commands.executeCommand(command, 'ctrl\0test'); + assert.deepStrictEqual({ calls, updates: proxy.$applyTestRunUpdates.args.flatMap(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)) }, { + calls: ['unrelated.command', 'updates', command], updates: ['tests', 'messages', 'state'], + }); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + } finally { + run.end(); + await ctrl.$disposeRun(proxy.$startedExtensionTestRun.firstCall.args[0].id); + clock.restore(); + } + }); + } + + for (const rejects of [false, true]) { + test(`publishes final updates before a cancelled profile ${rejects ? 'rejects' : 'returns'}`, async () => { + const controller = ds.add(ctrl.createTestController(nullExtensionDescription, 'ctrl', 'tests')); + const item = controller.createTestItem('test', 'test'); + controller.items.add(item); + const started = new DeferredPromise(); + const finish = new DeferredPromise(); + let run: TestRun | undefined; + const profile = ds.add(controller.createRunProfile('run', TestRunProfileKind.Run, async request => { + run = controller.createTestRun(request); + await started.complete(); + await finish.p; + run.failed(item, new TestMessage('final failure')); + run.appendOutput('final output', undefined, item); + if (rejects) { + throw new Error('handler failure'); + } + })); + const cts = ds.add(new CancellationTokenSource()); + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const result = ctrl.$runControllerTests([{ + controllerId: 'ctrl', runId: 'run', profileId: ctrl.getProfileInternalId(controller, profile), + testIds: ['ctrl\0test'], excludeExtIds: [], + }], cts.token); + await started.p; + cts.cancel(); + await finish.complete(); + const response = await result; + assert.deepStrictEqual({ + response, + updates: proxy.$applyTestRunUpdates.args.map(([, , updates]) => updates.value.map((update: TestRunUpdate) => update.type)), + ended: proxy.$finishedTestRunTask.called, + }, { response: [rejects ? { error: 'Error: handler failure' } : {}], updates: [['tests', 'messages', 'state', 'output']], ended: false }); + clock.tick(0); + assert.strictEqual(proxy.$applyTestRunUpdates.callCount, 1); + } finally { + await finish.complete(); + run?.end(); + await ctrl.$disposeRun('run'); + clock.restore(); + } + }); + } + + for (const invalidateAll of [false, true]) { + test(`sends pending run updates before retiring ${invalidateAll ? 'all results' : 'specified tests'}`, async () => { + const controller = ds.add(ctrl.createTestController(nullExtensionDescription, 'ctrl', 'tests')); + const item = controller.createTestItem('test', 'test'); + controller.items.add(item); + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const runs = [controller.createTestRun(new TestRunRequestImpl()), controller.createTestRun(new TestRunRequestImpl())]; + try { + const calls: string[] = []; + proxy.$applyTestRunUpdates.callsFake(() => calls.push('updates')); + proxy.$markTestRetired.callsFake(() => calls.push('retire')); + runs[0].started(item); + runs[1].passed(item, 1); + controller.invalidateTestResults(invalidateAll ? undefined : [item]); + assert.deepStrictEqual({ calls, ids: proxy.$markTestRetired.firstCall.args }, { + calls: ['updates', 'updates', 'retire'], + ids: [invalidateAll ? undefined : ['ctrl\0test']], + }); + clock.tick(0); + assert.deepStrictEqual(calls, ['updates', 'updates', 'retire']); + } finally { + for (const run of runs) { + run.end(); + } + for (const [run] of proxy.$startedExtensionTestRun.args) { + await ctrl.$disposeRun(run.id); + } + clock.restore(); + } + }); + } + test('disposing an observer stops its events while another observer remains live', async () => { const retired = ds.add(ctrl.createTestObserver()); const live = ds.add(ctrl.createTestObserver()); diff --git a/src/vs/workbench/api/test/browser/extHostTreeViews.test.ts b/src/vs/workbench/api/test/browser/extHostTreeViews.test.ts index 5bffd63bca9c..1315a851cd74 100644 --- a/src/vs/workbench/api/test/browser/extHostTreeViews.test.ts +++ b/src/vs/workbench/api/test/browser/extHostTreeViews.test.ts @@ -5,14 +5,14 @@ import assert from 'assert'; import * as sinon from 'sinon'; -import { Emitter } from '../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; import { ExtHostTreeViews } from '../../common/extHostTreeViews.js'; import { ExtHostCommands } from '../../common/extHostCommands.js'; import { MainThreadTreeViewsShape, MainContext, MainThreadCommandsShape } from '../../common/extHost.protocol.js'; import { TreeDataProvider, TreeItem, DataTransfer as ApiDataTransfer, DataTransferItem as ApiDataTransferItem, TreeDragAndDropController } from 'vscode'; import { TestRPCProtocol } from '../common/testRPCProtocol.js'; import { mock } from '../../../../base/test/common/mock.js'; -import { TreeItemCollapsibleState, ITreeItem, IRevealOptions } from '../../../common/views.js'; +import { TreeItemCollapsibleState, ITreeItem, IRevealOptions, TreeCommand } from '../../../common/views.js'; import { NullLogService } from '../../../../platform/log/common/log.js'; import type { IDisposable } from '../../../../base/common/lifecycle.js'; import { nullExtensionDescription as extensionsDescription } from '../../../services/extensions/common/extensions.js'; @@ -61,6 +61,7 @@ suite('ExtHostTreeView', function () { } let testObject: ExtHostTreeViews; + let extHostCommands: ExtHostCommands; let target: RecordingShape; let onDidChangeTreeNode: Emitter<{ key: string } | undefined>; let onDidChangeTreeNodeWithId: Emitter<{ key: string }>; @@ -89,7 +90,7 @@ suite('ExtHostTreeView', function () { override $registerCommand() { } }); target = new RecordingShape(); - testObject = store.add(new ExtHostTreeViews(target, new ExtHostCommands( + extHostCommands = new ExtHostCommands( rpcProtocol, new NullLogService(), new class extends mock() { @@ -97,7 +98,8 @@ suite('ExtHostTreeView', function () { return true; } } - ), new NullLogService())); + ); + testObject = store.add(new ExtHostTreeViews(target, extHostCommands, new NullLogService())); onDidChangeTreeNode = new Emitter<{ key: string } | undefined>(); onDidChangeTreeNodeWithId = new Emitter<{ key: string }>(); testObject.createTreeView('testNodeTreeProvider', { treeDataProvider: aNodeTreeDataProvider() }, extensionsDescription); @@ -650,6 +652,73 @@ suite('ExtHostTreeView', function () { treeView2.dispose(); }); + /** + * Fires a root change on a view-specific event and waits until the view has refreshed. + * The suite's shared change events also refresh the views created in setup. + */ + async function refreshRoot(onDidChange: Emitter<{ key: string } | undefined>): Promise { + const refreshed = Event.toPromise(target.onRefresh.event); + onDidChange.fire(undefined); + await refreshed; + } + + test('repeated root refreshes do not grow the tree view store (#346620)', () => runWithFakedTimers({}, async () => { + const onDidChange = store.add(new Emitter<{ key: string } | undefined>()); + const treeView = testObject.createTreeView('leakTestProvider', { treeDataProvider: { ...aNodeTreeDataProvider(), onDidChangeTreeData: onDidChange.event } }, extensionsDescription); + const treeViews: Map = Reflect.get(testObject, '_treeViews'); + const viewStore: { _toDispose: Set } = Reflect.get(treeViews.get('leakTestProvider')!, '_store'); + + await testObject.$getChildren('leakTestProvider'); + await refreshRoot(onDidChange); + await testObject.$getChildren('leakTestProvider'); + const sizeAfterFirstRefresh = viewStore._toDispose.size; + for (let i = 0; i < 5; i++) { + await refreshRoot(onDidChange); + await testObject.$getChildren('leakTestProvider'); + } + + assert.strictEqual(viewStore._toDispose.size, sizeAfterFirstRefresh); + await treeView.dispose(); + })); + + test('tree nodes replaced by a duplicate element are released on refresh and dispose', () => runWithFakedTimers({}, async () => { + const onDidChange = store.add(new Emitter<{ key: string } | undefined>()); + const shared = { key: 'shared' }; + const treeView = testObject.createTreeView<{ key: string }>('duplicateElementTreeProvider', { + treeDataProvider: { + getChildren: element => element ? (element === shared ? [] : [shared]) : [{ key: 'p1' }, { key: 'p2' }], + getTreeItem: element => ({ + label: element.key, + collapsibleState: element === shared ? TreeItemCollapsibleState.None : TreeItemCollapsibleState.Collapsed, + command: { command: 'testCommand', title: 'Test', arguments: [element.key] } + }), + onDidChangeTreeData: onDidChange.event + } + }, extensionsDescription); + // Expanding both parents creates a node for the shared element under each of them. The second node replaces the first in the element cache. + const expandSharedCommands = async () => { + const commands: TreeCommand[] = []; + for (const root of unBatchChildren(await testObject.$getChildren('duplicateElementTreeProvider'))!) { + commands.push(unBatchChildren(await testObject.$getChildren('duplicateElementTreeProvider', [root.handle]))![0].command!); + } + return commands; + }; + const isCached = (commands: TreeCommand[]) => commands.map(command => extHostCommands.converter.fromInternal(command) !== undefined); + + const initialCommands = await expandSharedCommands(); + await refreshRoot(onDidChange); + await expandSharedCommands(); + await refreshRoot(onDidChange); + const latestCommands = await expandSharedCommands(); + const initialCachedAfterRefreshes = isCached(initialCommands); + await treeView.dispose(); + + assert.deepStrictEqual( + { initialCachedAfterRefreshes, latestCachedAfterDispose: isCached(latestCommands) }, + { initialCachedAfterRefreshes: [false, false], latestCachedAfterDispose: [false, false] } + ); + })); + test('reveal will throw an error if getParent is not implemented', () => { const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aNodeTreeDataProvider() }, extensionsDescription); return treeView.reveal({ key: 'a' }) @@ -661,7 +730,7 @@ suite('ExtHostTreeView', function () { const treeView = testObject.createTreeView('treeDataProvider', { treeDataProvider: aCompleteNodeTreeDataProvider() }, extensionsDescription); const expected = { item: - { handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed }, + { handle: '0/0:a', label: { label: 'a' }, collapsibleState: TreeItemCollapsibleState.Collapsed }, parentChain: [] }; return treeView.reveal({ key: 'a' }) diff --git a/src/vs/workbench/api/test/browser/mainThreadAuthentication.test.ts b/src/vs/workbench/api/test/browser/mainThreadAuthentication.test.ts index 91977349c862..14e1dbb3530e 100644 --- a/src/vs/workbench/api/test/browser/mainThreadAuthentication.test.ts +++ b/src/vs/workbench/api/test/browser/mainThreadAuthentication.test.ts @@ -4,15 +4,30 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { VSBuffer } from '../../../../base/common/buffer.js'; +import { isCancellationError } from '../../../../base/common/errors.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { upcastPartial } from '../../../../base/test/common/mock.js'; +import { AuthenticationAccessService } from '../../../services/authentication/browser/authenticationAccessService.js'; +import { AuthenticationService } from '../../../services/authentication/browser/authenticationService.js'; +import { IDynamicAuthenticationProviderStorageService } from '../../../services/authentication/common/dynamicAuthenticationProviderStorage.js'; +import { IExtHostContext } from '../../../services/extensions/common/extHostCustomers.js'; +import { RPCProtocol } from '../../../services/extensions/common/rpcProtocol.js'; +import { ExtensionHostKind } from '../../../services/extensions/common/extensionHostKind.js'; +import { TestEnvironmentService } from '../../../test/browser/workbenchTestServices.js'; +import { TestExtensionService, TestProductService, TestStorageService } from '../../../test/common/workbenchTestServices.js'; +import { NullLogService } from '../../../../platform/log/common/log.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { ExtHostAuthenticationShape, ExtHostContext, MainContext, MainThreadAuthenticationShape } from '../../common/extHost.protocol.js'; import { URI, UriComponents } from '../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; -import { AuthenticationSession } from '../../../services/authentication/common/authentication.js'; -import { Dto } from '../../../services/extensions/common/proxyIdentifier.js'; -import { reviveAuthenticationSession } from '../../browser/mainThreadAuthentication.js'; +import { AuthenticationSession, IAuthenticationExtensionsService } from '../../../services/authentication/common/authentication.js'; +import { Dto, Proxied } from '../../../services/extensions/common/proxyIdentifier.js'; +import { MainThreadAuthentication, reviveAuthenticationSession } from '../../browser/mainThreadAuthentication.js'; suite('MainThreadAuthentication', () => { - ensureNoDisposablesAreLeakedInTestSuite(); + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); const iconComponents: UriComponents = { scheme: 'https', authority: 'example.com', path: '/avatar.png', query: '', fragment: '' }; @@ -42,4 +57,148 @@ suite('MainThreadAuthentication', () => { ] ); }); + + suite('provider lifecycle', () => { + const authorizationServer = URI.parse('https://auth.example.com'); + const resourceServer = URI.parse('https://mcp.example.com'); + let authenticationService: AuthenticationService; + + setup(() => { + const storageService = disposables.add(new TestStorageService()); + const accessService = disposables.add(new AuthenticationAccessService(storageService, TestProductService)); + authenticationService = disposables.add(new AuthenticationService(new TestExtensionService(), accessService, TestEnvironmentService, new NullLogService())); + }); + + function createHost(sessionId: string, rpc?: RPCProtocol) { + const unregistered: string[] = []; + let clientRegistrationWrites = 0; + let stopped = false; + const proxy = upcastPartial>({ + $onDidChangeAuthenticationSessions: async () => { }, + $onDidUnregisterAuthenticationProvider: async id => { unregistered.push(id); }, + $getSessions: async () => { + assert.strictEqual(stopped, false, 'must not use the stopped extension host'); + return [{ id: sessionId, accessToken: 'test-token', scopes: [], account: { id: 'account', label: 'Account' } }]; + } + }); + const context = upcastPartial({ + getProxy: rpc ? identifier => rpc.getProxy(identifier) : () => proxy as unknown as Proxied, + extensionHostKind: ExtensionHostKind.LocalProcess + }); + const dynamicStorage = upcastPartial({ + onDidChangeTokens: Event.None, + storeClientRegistration: async () => { clientRegistrationWrites++; } + }); + const mainThread = disposables.add(new MainThreadAuthentication( + context, TestProductService, authenticationService, + upcastPartial({ onDidChangeAccountPreference: Event.None }), + undefined!, undefined!, undefined!, undefined!, undefined!, + upcastPartial({ publicLog2: () => { } }), undefined!, new NullLogService(), undefined!, + dynamicStorage, undefined!, undefined!, undefined!, undefined! + )); + return { + mainThread, unregistered, + get clientRegistrationWrites() { return clientRegistrationWrites; }, + stop: () => { stopped = true; mainThread.dispose(); } + }; + } + + function registerDynamicProvider(host: { mainThread: Pick }) { + return host.mainThread.$registerDynamicAuthenticationProvider({ + id: 'dynamic-provider', label: 'dynamic-provider', supportsMultipleAccounts: true, clientId: 'test-client', + authorizationServer: authorizationServer.toJSON(), resourceServer: resourceServer.toJSON() + }); + } + + test('removes host-owned dynamic providers without changing persisted registration', async () => { + const host = createHost('first-host'); + await registerDynamicProvider(host); + assert.strictEqual(await authenticationService.getOrActivateProviderIdForServer(authorizationServer, resourceServer), 'dynamic-provider'); + host.stop(); + assert.strictEqual(authenticationService.isAuthenticationProviderRegistered('dynamic-provider'), false); + assert.strictEqual(await authenticationService.getOrActivateProviderIdForServer(authorizationServer, resourceServer), undefined); + assert.strictEqual(host.clientRegistrationWrites, 1); + assert.deepStrictEqual(host.unregistered, []); + }); + + test('does not echo explicit provider unregistration to its owning host', async () => { + const host = createHost('first-host'); + await registerDynamicProvider(host); + await host.mainThread.$unregisterAuthenticationProvider('dynamic-provider'); + assert.strictEqual(authenticationService.isAuthenticationProviderRegistered('dynamic-provider'), false); + assert.strictEqual(host.clientRegistrationWrites, 1); + assert.deepStrictEqual(host.unregistered, []); + host.stop(); + assert.deepStrictEqual(host.unregistered, []); + }); + + test('releases a registration when the provider is unregistered externally', async () => { + const firstHost = createHost('first-host'); + await registerDynamicProvider(firstHost); + authenticationService.unregisterAuthenticationProvider('dynamic-provider'); + assert.deepStrictEqual(firstHost.unregistered, ['dynamic-provider']); + + const secondHost = createHost('second-host'); + await registerDynamicProvider(secondHost); + firstHost.stop(); + assert.deepStrictEqual(firstHost.unregistered, ['dynamic-provider']); + assert.deepStrictEqual(secondHost.unregistered, []); + const sessions = await authenticationService.getSessions('dynamic-provider'); + assert.strictEqual(sessions[0].id, 'second-host'); + }); + + test('notifies other hosts when the owning host stops', async () => { + const firstHost = createHost('first-host'); + const secondHost = createHost('second-host'); + await registerDynamicProvider(firstHost); + firstHost.stop(); + assert.deepStrictEqual(firstHost.unregistered, []); + assert.deepStrictEqual(secondHost.unregistered, ['dynamic-provider']); + }); + + test('rediscovers dynamic providers after RPC and customer disposal', async () => { + function createRpcHost(sessionId: string) { + const mainMessages = disposables.add(new Emitter()); + const extHostMessages = disposables.add(new Emitter()); + const mainRpc = disposables.add(new RPCProtocol({ + onMessage: mainMessages.event, + send: message => { queueMicrotask(() => extHostMessages.fire(message)); } + })); + const extHostRpc = disposables.add(new RPCProtocol({ + onMessage: extHostMessages.event, + send: message => { queueMicrotask(() => mainMessages.fire(message)); } + })); + const host = createHost(sessionId, mainRpc); + mainRpc.set(MainContext.MainThreadAuthentication, host.mainThread); + extHostRpc.set(ExtHostContext.ExtHostAuthentication, upcastPartial({ + $getSessions: async () => [{ id: sessionId, accessToken: 'test-token', scopes: [], account: { id: 'account', label: 'Account' } }] + })); + return { + mainThread: extHostRpc.getProxy(MainContext.MainThreadAuthentication), + stop: () => { + // Model ExtensionHostManager.dispose(): close RPC before disposing customers. + mainRpc.dispose(); + host.stop(); + extHostRpc.dispose(); + } + }; + } + + const first = createRpcHost('first-host'); + await registerDynamicProvider(first); + const oldProvider = authenticationService.getProvider('dynamic-provider'); + assert.strictEqual((await authenticationService.getSessions('dynamic-provider'))[0].id, 'first-host'); + + first.stop(); + // This is RPCProtocol's real cancellation, not a stopped-host test stub. + await assert.rejects(oldProvider.getSessions(undefined, {}), isCancellationError); + assert.strictEqual(await authenticationService.getOrActivateProviderIdForServer(authorizationServer, resourceServer), undefined); + + const second = createRpcHost('second-host'); + await registerDynamicProvider(second); + assert.strictEqual((await authenticationService.getSessions('dynamic-provider'))[0].id, 'second-host'); + second.stop(); + }); + }); + }); diff --git a/src/vs/workbench/api/test/browser/mainThreadChatAgents2.test.ts b/src/vs/workbench/api/test/browser/mainThreadChatAgents2.test.ts index bf09fc9a6311..5a89d70f5c2d 100644 --- a/src/vs/workbench/api/test/browser/mainThreadChatAgents2.test.ts +++ b/src/vs/workbench/api/test/browser/mainThreadChatAgents2.test.ts @@ -5,6 +5,7 @@ import assert from 'assert'; import * as sinon from 'sinon'; +import { DeferredPromise } from '../../../../base/common/async.js'; import { CancellationToken } from '../../../../base/common/cancellation.js'; import { Event } from '../../../../base/common/event.js'; import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; @@ -47,12 +48,15 @@ suite('MainThreadChatAgents2', function () { let mockChatService: MockChatService; let agentImpl: IChatAgentImplementation; let warnings: string[]; + let errors: sinon.SinonSpy; + let toolsService: ILanguageModelToolsService; let resolveInvoke: (result: unknown) => void; setup(async function () { disposables = new DisposableStore(); instantiationService = new TestInstantiationService(); warnings = []; + errors = sinon.spy(); // `$invokeAgent` is kept pending so the `_pendingProgress` entry registered at // the start of `invoke` stays alive while we route a usage chunk through it. @@ -94,6 +98,7 @@ suite('MainThreadChatAgents2', function () { }); instantiationService.stub(ILogService, new class extends NullLogService { override warn(message: string) { warnings.push(message); } + override error = errors; }); instantiationService.stub(IExtensionService, new TestExtensionService()); instantiationService.stub(IUriIdentityService, new class extends mock() { }); @@ -105,7 +110,11 @@ suite('MainThreadChatAgents2', function () { override onDidChangeSlashCommands = Event.None; override onDidChangeHooks = Event.None; }); - instantiationService.stub(ILanguageModelToolsService, new class extends mock() { }); + toolsService = new class extends mock() { + override beginToolCall() { return undefined; } + override async updateToolStream() { } + }; + instantiationService.stub(ILanguageModelToolsService, toolsService); instantiationService.stub(ICustomizationHarnessService, new class extends mock() { }); instantiationService.stub(ITelemetryService, new class extends mock() { }); instantiationService.stub(IAgentPluginService, new class extends mock() { @@ -194,4 +203,39 @@ suite('MainThreadChatAgents2', function () { assert.strictEqual(forwarded.filter(p => p.kind === 'usage').length, 0); assert.ok(warnings.some(w => w.includes('req-orphan')), `expected a warning mentioning the requestId, got: ${JSON.stringify(warnings)}`); }); + + test('logs denied tool chunks without dropping markdown or waiting for streaming callbacks', async function () { + const sessionResource = URI.parse('vscode-chat:/streaming-session'); + addSession(sessionResource, []); + const beginError = new Error('Tool disabled by policy'); + const updateError = new Error('Streaming tool disabled by policy'); + sinon.stub(toolsService, 'beginToolCall').throws(beginError); + const pendingUpdate = new DeferredPromise(); + const update = sinon.stub(toolsService, 'updateToolStream'); + update.onFirstCall().rejects(updateError); + update.onSecondCall().returns(pendingUpdate.p); + const forwarded: IChatProgress[] = []; + const invoke = agentImpl.invoke(makeRequest('req-stream', sessionResource), parts => forwarded.push(...parts), [], CancellationToken.None); + const before: IChatProgress = { kind: 'markdownContent', content: { value: 'Before' } }; + const after: IChatProgress = { kind: 'markdownContent', content: { value: 'After' } }; + + await mainThread.$handleProgressChunk('req-stream', [ + before, + { kind: 'beginToolInvocation', toolCallId: 'denied-begin', toolName: 'extensionTool' }, + { kind: 'updateToolInvocation', toolCallId: 'denied-update', streamData: { partialInput: {} } }, + { kind: 'updateToolInvocation', toolCallId: 'pending-update', streamData: { partialInput: {} } }, + after, + ]); + await pendingUpdate.complete(); + resolveInvoke({}); + await invoke; + + assert.deepStrictEqual({ forwarded, errors: errors.args }, { + forwarded: [before, after], + errors: [ + ['MainThreadChatAgents2#$handleProgressChunk: Failed to begin tool invocation denied-begin', beginError], + ['MainThreadChatAgents2#$handleProgressChunk: Failed to update tool invocation denied-update', updateError], + ], + }); + }); }); diff --git a/src/vs/workbench/api/test/browser/mainThreadChatArtifactIntegrations.test.ts b/src/vs/workbench/api/test/browser/mainThreadChatArtifactIntegrations.test.ts index 950bad71551c..9ac3cf87e883 100644 --- a/src/vs/workbench/api/test/browser/mainThreadChatArtifactIntegrations.test.ts +++ b/src/vs/workbench/api/test/browser/mainThreadChatArtifactIntegrations.test.ts @@ -602,14 +602,15 @@ suite('Chat artifact integration extension bridge', () => { items: details.details.get().items.map(item => ({ id: item.id, actions: item.actions })), direct: observation.itemActionRuns, rejected, reused, prepared: prepared.map(context => context.input), - prompts: prompts.map(request => request.chat), + prompts: prompts.map(request => ({ chat: request.chat, action: request.presentation?.action, items: request.presentation?.details.flatMap(details => details.items.map(item => item.id)) })), invalid: errors.filter(error => error.includes('Invalid extension details')).length, }, { itemActions: [{ id: 'fix', label: 'Fix', iconId: 'sparkle', actionId: 'analyze' }, { id: 'copyLink', label: 'Copy Link', iconId: 'link' }], items: [{ id: 'one', actions: ['fix', 'copyLink'] }, { id: 'two', actions: ['copyLink'] }], direct: ['two:copyLink'], rejected: ['rejected', 'rejected'], reused: 'rejected', prepared: [input], - prompts: ['vendor-chat://invoking'], + // The list was added after the integration was created, yet the request presents the item it ran for. + prompts: [{ chat: 'vendor-chat://invoking', action: { label: 'Fix', iconId: 'sparkle' }, items: ['one'] }], invalid: 1, }); }); diff --git a/src/vs/workbench/api/test/browser/mainThreadDocumentsAndEditors.test.ts b/src/vs/workbench/api/test/browser/mainThreadDocumentsAndEditors.test.ts index b1d0fec72dd7..38c044437d99 100644 --- a/src/vs/workbench/api/test/browser/mainThreadDocumentsAndEditors.test.ts +++ b/src/vs/workbench/api/test/browser/mainThreadDocumentsAndEditors.test.ts @@ -168,6 +168,18 @@ suite('MainThreadDocumentsAndEditors', () => { assert.strictEqual(delta.newActiveEditor, undefined); }); + test('Model#remove', () => { + disposables.add(modelService.createModel('farboo', null)); + const model = modelService.createModel('boofar', null); + deltas.length = 0; + + model.dispose(); + + assert.deepStrictEqual(deltas.map(delta => ({ ...delta, removedDocuments: delta.removedDocuments?.map(uri => URI.revive(uri).toString()) })), [ + { removedDocuments: [model.uri.toString()] } + ]); + }); + test('ignore huge model', function () { const oldLimit = TextModel._MODEL_SYNC_LIMIT; diff --git a/src/vs/workbench/api/test/browser/mainThreadSearch.test.ts b/src/vs/workbench/api/test/browser/mainThreadSearch.test.ts new file mode 100644 index 000000000000..b23cc6851829 --- /dev/null +++ b/src/vs/workbench/api/test/browser/mainThreadSearch.test.ts @@ -0,0 +1,158 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Disposable } from '../../../../base/common/lifecycle.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { URI, UriComponents } from '../../../../base/common/uri.js'; +import { mock } 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 { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { TestInstantiationService } from '../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { MockContextKeyService } from '../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../platform/telemetry/common/telemetryUtils.js'; +import { IFileMatch, ISearchCompleteStats, ISearchResultProvider, ISearchService, isFileMatch, QueryType, SearchProviderType } from '../../../services/search/common/search.js'; +import { MainThreadSearch } from '../../browser/mainThreadSearch.js'; +import { ExtHostSearchShape } from '../../common/extHost.protocol.js'; +import { SingleProxyRPCProtocol } from '../common/testRPCProtocol.js'; + +suite('MainThreadSearch', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const folder = URI.from({ scheme: Schemas.vscodeRemote, authority: 'ssh-remote+host', path: '/workspace' }); + + function createSearch(type: SearchProviderType, provide: (session: number) => Promise) { + const instantiationService = disposables.add(new TestInstantiationService()); + let provider: ISearchResultProvider | undefined; + instantiationService.stub(ISearchService, { + registerSearchResultProvider(_scheme, _type, value) { + provider = value; + return Disposable.None; + } + }); + instantiationService.stub(ITelemetryService, NullTelemetryService); + instantiationService.stub(IConfigurationService, new TestConfigurationService()); + instantiationService.stub(IContextKeyService, new MockContextKeyService()); + + const proxy = new class extends mock() { + override $enableExtensionHostSearch(): void { } + override $provideFileSearchResults(_handle: number, session: number): Promise { + return provide(session); + } + override $provideTextSearchResults(_handle: number, session: number): Promise { + return provide(session); + } + }; + const customer = disposables.add(instantiationService.createInstance(MainThreadSearch, SingleProxyRPCProtocol(proxy))); + if (type === SearchProviderType.file) { + customer.$registerFileSearchProvider(0, folder.scheme); + } else { + customer.$registerTextSearchProvider(0, folder.scheme); + } + assert.ok(provider); + return { customer, provider }; + } + + function components({ scheme, authority, path, query, fragment }: URI): UriComponents { + return { scheme, authority, path, query, fragment }; + } + + test('file search preserves components, ordering, and duplicates across batches', async () => { + const resources = [ + folder.with({ path: '/workspace/a #?%é.txt', query: 'q=#?', fragment: 'part #1' }), + URI.from({ scheme: Schemas.file, path: '/C:/workspace/Mixed.txt' }), + URI.from({ scheme: Schemas.https, authority: 'user:pass@EXAMPLE.COM:8080', path: '/D:/Case.txt' }), + folder.with({ authority: 'SSH-REMOTE+HOST', path: '/workspace/case.txt' }), + folder.with({ path: '/workspace/a//b.txt' }), + folder.with({ path: '/workspace/a/b.txt' }) + ]; + const { customer, provider } = createSearch(SearchProviderType.file, async session => { + customer.$handleFileMatch(0, session, resources.slice(0, 3).map(uri => uri.toJSON())); + await Promise.resolve(); + customer.$handleFileMatch(0, session, [ + ...resources.slice(3).map(uri => uri.toJSON()), + resources[3].with({ authority: 'ssh-remote+host' }).toJSON(), + resources[0].toJSON() + ]); + return { messages: [], limitHit: false }; + }); + + const result = await provider.fileSearch({ type: QueryType.File, folderQueries: [{ folder }] }); + assert.deepStrictEqual({ + resources: result.results.map(match => components(match.resource)), + limitHit: result.limitHit + }, { resources: resources.map(components), limitHit: false }); + }); + + test('file search returns all results across large batches', async () => { + const count = 25005; + const { customer, provider } = createSearch(SearchProviderType.file, async session => { + for (let start = 0; start < count; start += 512) { + customer.$handleFileMatch(0, session, Array.from({ length: Math.min(512, count - start) }, (_, index) => + folder.with({ path: `/workspace/file-${start + index}.txt` }).toJSON())); + } + return { messages: [] }; + }); + + const result = await provider.fileSearch({ type: QueryType.File, folderQueries: [{ folder }] }); + assert.deepStrictEqual(result.results.map(match => match.resource.path), + Array.from({ length: count }, (_, index) => `/workspace/file-${index}.txt`)); + }); + + test('file search does not retain URI objects for ordinary or mixed-case remote authorities', async () => { + const resources = [ + folder.with({ path: '/workspace/ordinary.txt' }), + folder.with({ authority: 'wsl+Ubuntu', path: '/workspace/first.txt' }), + folder.with({ authority: 'wsl+UBUNTU', path: '/workspace/second.txt' }), + folder.with({ authority: 'wsl+Ubuntu', path: '/workspace/third.txt' }) + ]; + let retainedTypes: string[] = []; + const { customer, provider } = createSearch(SearchProviderType.file, async session => { + customer.$handleFileMatch(0, session, resources.map(uri => uri.toJSON())); + const searches: Map }> = Reflect.get(provider, '_searches'); + retainedTypes = [...searches.get(session)!.matches.values()].map(value => typeof value); + return { messages: [] }; + }); + + const result = await provider.fileSearch({ type: QueryType.File, folderQueries: [{ folder }] }); + assert.deepStrictEqual({ + retainedTypes, + resources: result.results.map(match => components(match.resource)) + }, { + retainedTypes: ['undefined', 'string', 'string', 'string'], + resources: resources.map(components) + }); + }); + + test('text search still merges matches and reports progress', async () => { + const resource = folder.with({ path: '/workspace/file.txt' }); + const progress: IFileMatch[] = []; + const { customer, provider } = createSearch(SearchProviderType.text, async session => { + customer.$handleTextMatch(0, session, [{ resource: resource.toJSON(), results: [{ text: 'first', lineNumber: 1 }] }]); + customer.$handleTextMatch(0, session, [{ resource: resource.toJSON(), results: [{ text: 'second', lineNumber: 2 }] }]); + return { messages: [] }; + }); + + const result = await provider.textSearch({ + type: QueryType.Text, + folderQueries: [{ folder }], + contentPattern: { pattern: 'text' } + }, item => { + if (isFileMatch(item)) { + progress.push(item); + } + }, CancellationToken.None); + assert.deepStrictEqual({ + results: result.results.map(match => ({ resource: components(match.resource), results: match.results })), + progressCount: progress.length + }, { + results: [{ resource: components(resource), results: [{ text: 'first', lineNumber: 1 }, { text: 'second', lineNumber: 2 }] }], + progressCount: 2 + }); + }); +}); diff --git a/src/vs/workbench/api/test/common/extHostGitHub.test.ts b/src/vs/workbench/api/test/common/extHostGitHub.test.ts index 03ae62f9566f..2a042c162f6c 100644 --- a/src/vs/workbench/api/test/common/extHostGitHub.test.ts +++ b/src/vs/workbench/api/test/common/extHostGitHub.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import type * as vscode from 'vscode'; +import type * as internalGitHub from '@vscode/internal-github'; import { DeferredPromise } from '../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; import { CancellationError } from '../../../../base/common/errors.js'; @@ -13,7 +13,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/c import { ExtensionIdentifier, IExtensionDescription } from '../../../../platform/extensions/common/extensions.js'; import { nullExtensionDescription } from '../../../services/extensions/common/extensions.js'; import { GitHubResultDto, IGitHubCreateGistDto, IGitHubGistDto, MainThreadGitHubShape } from '../../common/extHost.protocol.js'; -import { createGitHubApi, ExtHostGitHub, GitHubError } from '../../common/extHostGitHub.js'; +import { createInternalGitHubModule, ExtHostGitHub, GitHubError, InternalGitHubModuleFactory } from '../../common/extHostGitHub.js'; const gistDto: IGitHubGistDto = { id: 'gist-id', htmlUrl: 'https://gist.github.com/gist-id', @@ -63,8 +63,8 @@ class TestMainThreadGitHub implements MainThreadGitHubShape { } } -function extension(enabledApiProposals: string[]): IExtensionDescription { - return { ...nullExtensionDescription, identifier: new ExtensionIdentifier('vscode.configuration-editing'), enabledApiProposals }; +function extension(id = 'vscode.configuration-editing', isBuiltin = true): IExtensionDescription { + return { ...nullExtensionDescription, identifier: new ExtensionIdentifier(id), isBuiltin }; } async function rejection(promise: Thenable): Promise<{ type: string; code?: string; status?: number; message: string }> { @@ -80,22 +80,39 @@ async function rejection(promise: Thenable): Promise<{ type: string; co suite('ExtHostGitHub', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - function setup(proposals = ['github']) { + function setup() { const mainThread = new TestMainThreadGitHub(); - const api = createGitHubApi(extension(proposals), new ExtHostGitHub(mainThread)); + const api = createInternalGitHubModule(extension(), new ExtHostGitHub(mainThread)); return { mainThread, api }; } - test('requires the github API proposal', async () => { - const { api, mainThread } = setup(['profileContentHandlers']); - assert.throws(() => api.getClient('session'), /CANNOT use API proposal: github/); - assert.throws(() => api.getAnonymousClient(), /CANNOT use API proposal: github/); - assert.deepStrictEqual({ methods: Object.keys(api).sort(), calls: mainThread.calls }, { - methods: ['getAnonymousClient', 'getClient'], - calls: [], + test('provides the module only to eligible built-in importers, bound per extension', async () => { + const mainThread = new TestMainThreadGitHub(); + const eligible = extension(); + const others = [extension('vscode.git'), extension('vscode.configuration-editing', false)]; + const byPath = new Map([['/eligible/a.js', eligible], ['/other/a.js', others[0]], ['/thirdparty/a.js', others[1]]]); + const factory = new InternalGitHubModuleFactory({ findSubstr: uri => byPath.get(uri.path) }, new ExtHostGitHub(mainThread)); + + const module = factory.load('@vscode/internal-github', URI.file('/eligible/a.js')); + const same = module === factory.load('@vscode/internal-github', URI.file('/eligible/a.js')); + const rejected = ['/other/a.js', '/thirdparty/a.js', '/unknown/a.js'].map(path => { + try { + factory.load('@vscode/internal-github', URI.file(path)); + return 'loaded'; + } catch (error) { + return error.message; + } }); - }); + (await module.getAnonymousClient()).dispose(); + assert.deepStrictEqual({ + name: factory.nodeModuleName, same, frozen: Object.isFrozen(module), error: module.GitHubError === GitHubError, rejected, calls: mainThread.calls, + }, { + name: '@vscode/internal-github', same: true, frozen: true, error: true, + rejected: Array(3).fill(`Cannot find module '@vscode/internal-github'`), + calls: [['getAnonymousClient', 0, 'vscode.configuration-editing'], ['releaseClient', 0]], + }); + }); test('binds the requested session, maps gists and releases once on dispose', async () => { const { api, mainThread } = setup(); const client = await api.getClient('selected-session'); @@ -160,7 +177,7 @@ suite('ExtHostGitHub', () => { test('propagates request errors and cancellation, and cancels in-flight requests on dispose', async () => { const { api, mainThread } = setup(); - const client: vscode.GitHubAnonymousClient = await api.getAnonymousClient(); + const client: internalGitHub.GitHubAnonymousClient = await api.getAnonymousClient(); mainThread.operation = async () => ({ kind: 'error', error: { code: 'notFound', message: 'Not Found', status: 404 } }); const notFound = await rejection(client.gists.get('missing')); diff --git a/src/vs/workbench/api/test/common/extHostStructuralDiff.test.ts b/src/vs/workbench/api/test/common/extHostStructuralDiff.test.ts new file mode 100644 index 000000000000..1397e20d38d0 --- /dev/null +++ b/src/vs/workbench/api/test/common/extHostStructuralDiff.test.ts @@ -0,0 +1,352 @@ +/*--------------------------------------------------------------------------------------------- + * 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 type * as vscode from 'vscode'; +import { DeferredPromise } from '../../../../base/common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { isCancellationError } from '../../../../base/common/errors.js'; +import { URI, UriComponents } from '../../../../base/common/uri.js'; +import { mock } from '../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { Range } from '../../../../editor/common/core/range.js'; +import { StructuralDiffClassification, StructuralDiffContext, StructuralDiffResult, StructuralDiffTag, SymbolKind } from '../../../../editor/common/languages.js'; +import { NullLogService } from '../../../../platform/log/common/log.js'; +import { nullExtensionDescription } from '../../../services/extensions/common/extensions.js'; +import { SerializableObjectWithBuffers } from '../../../services/extensions/common/proxyIdentifier.js'; +import { ExtHostContext, MainContext, MainThreadCommandsShape, MainThreadLanguageFeaturesShape } from '../../common/extHost.protocol.js'; +import { NullApiDeprecationService } from '../../common/extHostApiDeprecationService.js'; +import { ExtHostApiCommands } from '../../common/extHostApiCommands.js'; +import { ExtHostCommands } from '../../common/extHostCommands.js'; +import { ExtHostDiagnostics } from '../../common/extHostDiagnostics.js'; +import { ExtHostDocuments } from '../../common/extHostDocuments.js'; +import { ExtHostDocumentsAndEditors } from '../../common/extHostDocumentsAndEditors.js'; +import { ExtHostLanguageFeatures } from '../../common/extHostLanguageFeatures.js'; +import { IExtHostTelemetry } from '../../common/extHostTelemetry.js'; +import * as types from '../../common/extHostTypes.js'; +import { URITransformerService } from '../../common/extHostUriTransformerService.js'; +import { TestRPCProtocol } from './testRPCProtocol.js'; + +suite('ExtHost structural diff', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const originalUri = URI.parse('test:/original.ts'); + const modifiedUri = URI.parse('test:/modified.ts'); + const extension = { ...nullExtensionDescription, enabledApiProposals: ['structuralDiff'] }; + const context: StructuralDiffContext = { + changes: [{ originalRange: new Range(1, 1, 1, 2), modifiedRange: new Range(1, 1, 1, 2) }], + }; + let documentsAndEditors: ExtHostDocumentsAndEditors; + let documents: ExtHostDocuments; + let features: ExtHostLanguageFeatures; + let handle: number; + let rpc: TestRPCProtocol; + + setup(() => { + handle = -1; + rpc = store.add(new TestRPCProtocol()); + rpc.set(MainContext.MainThreadLanguageFeatures, new class extends mock() { + override $registerStructuralDiffProvider(value: number): void { + handle = value; + } + override $unregister(): void { } + }); + documentsAndEditors = new ExtHostDocumentsAndEditors(rpc, new NullLogService()); + documents = store.add(new ExtHostDocuments(rpc, documentsAndEditors)); + documentsAndEditors.$acceptDocumentsAndEditorsDelta({ + addedDocuments: [ + { uri: originalUri, lines: ['a'], EOL: '\n', versionId: 1, languageId: 'typescript', isDirty: false, encoding: 'utf8' }, + { uri: modifiedUri, lines: ['b'], EOL: '\n', versionId: 1, languageId: 'typescript', isDirty: false, encoding: 'utf8' }, + ], + }); + features = store.add(new ExtHostLanguageFeatures( + rpc, + new URITransformerService(null), + documents, + new class extends mock() { }, + new class extends mock() { }, + new NullLogService(), + NullApiDeprecationService, + new class extends mock() { + override onExtensionError(): boolean { return true; } + }, + )); + rpc.set(ExtHostContext.ExtHostLanguageFeatures, features); + }); + + teardown(() => rpc.sync()); + + async function register(provider: vscode.StructuralDiffProvider): Promise { + store.add(features.registerStructuralDiffProvider(extension, { language: 'typescript' }, provider)); + await rpc.sync(); + assert.ok(handle >= 0); + } + + function provide(token: CancellationToken = CancellationToken.None, originalVersion = 1, modifiedVersion = 1) { + return rpc.getProxy(ExtHostContext.ExtHostLanguageFeatures).$provideStructuralDiff(handle, originalUri, originalVersion, modifiedUri, modifiedVersion, context, token); + } + + test('requires the proposal before registering', () => { + assert.throws(() => features.registerStructuralDiffProvider(nullExtensionDescription, '*', { + provideStructuralDiff: () => undefined, + }), /CANNOT use API proposal: structuralDiff/); + assert.strictEqual(handle, -1); + }); + + test('converts both snapshots, paired ranges and nested classifications', async () => { + let received: { texts: string[]; uris: string[]; context: vscode.StructuralDiffContext } | undefined; + await register({ + provideStructuralDiff: (original, modified, value) => { + received = { texts: [original.getText(), modified.getText()], uris: [original.uri.toString(), modified.uri.toString()], context: value }; + const item = { name: 'file.ts', kind: types.SymbolKind.File, range: new types.Range(0, 0, 0, 1) }; + return { + root: { + id: 'file', originalItem: item, modifiedItem: item, originalChanges: [], modifiedChanges: [], + children: [{ + id: 'member', + originalItem: { name: 'oldName', detail: 'old', kind: types.SymbolKind.Method, range: item.range, selectionRange: item.range }, + modifiedItem: { name: 'newName', detail: 'new', kind: types.SymbolKind.Method, range: item.range, selectionRange: item.range }, + originalChanges: [{ textChangeIndex: 0, range: item.range, classification: types.StructuralDiffClassification.Header, tags: [types.StructuralDiffTag.Test] }], + modifiedChanges: [{ textChangeIndex: 0, range: item.range, classification: types.StructuralDiffClassification.Implementation, tags: [] }], + children: [], + }], + }, + isIncomplete: false, + }; + }, + }); + const result = await provide(); + const range = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 2 }; + assert.deepStrictEqual({ received, child: result?.root.children[0], isIncomplete: result?.isIncomplete }, { + received: { + texts: ['a', 'b'], + uris: [originalUri.toString(), modifiedUri.toString()], + context: { changes: [{ originalRange: new types.Range(0, 0, 0, 1), modifiedRange: new types.Range(0, 0, 0, 1) }] }, + }, + child: { + id: 'member', + originalItem: { name: 'oldName', detail: 'old', kind: SymbolKind.Method, range, selectionRange: range }, + modifiedItem: { name: 'newName', detail: 'new', kind: SymbolKind.Method, range, selectionRange: range }, + originalChanges: [{ textChangeIndex: 0, range, classification: StructuralDiffClassification.Header, tags: [StructuralDiffTag.Test] }], + modifiedChanges: [{ textChangeIndex: 0, range, classification: StructuralDiffClassification.Implementation, tags: [] }], + children: [], + }, + isIncomplete: false, + }); + }); + + for (const side of ['original', 'modified'] as const) { + test(`preserves ${side}-only items and incomplete results`, async () => { + await register({ + provideStructuralDiff: () => { + const item = { name: 'file.ts', kind: types.SymbolKind.File, range: new types.Range(0, 0, 0, 1) }; + return { + root: { + id: 'file', originalItem: item, modifiedItem: item, originalChanges: [], modifiedChanges: [], + children: [{ + id: side, + [`${side}Item`]: { name: 'member', kind: types.SymbolKind.Property, range: item.range }, + originalChanges: [], modifiedChanges: [], children: [], + }], + }, + isIncomplete: true, + }; + }, + }); + const result = await provide(); + assert.deepStrictEqual({ child: result?.root.children[0], isIncomplete: result?.isIncomplete }, { + child: { + id: side, + [`${side}Item`]: { name: 'member', kind: SymbolKind.Property, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 2 } }, + originalChanges: [], modifiedChanges: [], children: [], + }, + isIncomplete: true, + }); + }); + } + + for (const result of [null, undefined]) { + test(`returns undefined when the provider returns ${result}`, async () => { + await register({ provideStructuralDiff: () => result }); + assert.strictEqual(await provide(), undefined); + }); + } + + test('converts omitted children to an empty list', async () => { + const file = { name: 'file.ts', kind: types.SymbolKind.File, range: new types.Range(0, 0, 0, 1) }; + await register({ + provideStructuralDiff: () => ({ root: { id: 'file', originalItem: file, modifiedItem: file, originalChanges: [], modifiedChanges: [] }, isIncomplete: false }), + }); + assert.deepStrictEqual((await provide())?.root.children, []); + }); + + for (const side of ['original', 'modified'] as const) { + test(`rejects a stale ${side} snapshot before invocation`, async () => { + let called = false; + await register({ provideStructuralDiff: () => { called = true; return undefined; } }); + await assert.rejects(provide(CancellationToken.None, side === 'original' ? 2 : 1, side === 'modified' ? 2 : 1), isCancellationError); + assert.strictEqual(called, false); + }); + } + + for (const reason of ['caller', 'original changed', 'modified changed', 'original closed', 'modified closed'] as const) { + test(`cancels a pending extension provider when ${reason}`, async () => { + const source = store.add(new CancellationTokenSource()); + const started = new DeferredPromise(); + const pending = new DeferredPromise(); + await register({ + provideStructuralDiff: (_original, _modified, _context, token) => { + started.complete(token); + return pending.p; + }, + }); + const rejected = assert.rejects(provide(source.token), isCancellationError); + const providerToken = await started.p; + const uri = reason.startsWith('original') ? originalUri : modifiedUri; + if (reason === 'caller') { + source.cancel(); + } else if (reason.endsWith('closed')) { + documentsAndEditors.$acceptDocumentsAndEditorsDelta({ removedDocuments: [uri] }); + } else { + documents.$acceptModelChanged(uri, { + changes: [{ range: new Range(1, 1, 1, 2), rangeOffset: 0, rangeLength: 1, text: 'c' }], + eol: '\n', versionId: 2, isUndoing: false, isRedoing: false, isFlush: false, isEolChange: false, detailedReason: undefined, + }, false); + } + await rejected; + assert.strictEqual(providerToken.isCancellationRequested, true); + await pending.complete(undefined); + }); + } + + test('propagates provider errors', async () => { + await register({ provideStructuralDiff: () => { throw new Error('Provider failed'); } }); + await assert.rejects(provide(), /Provider failed/); + }); + + function resultWith(member: Partial): vscode.StructuralDiff { + const file = { name: 'file.ts', kind: types.SymbolKind.File, range: new types.Range(0, 0, 0, 1) }; + return { + root: { + id: 'file', originalItem: file, modifiedItem: file, originalChanges: [], modifiedChanges: [], + children: [{ id: 'member', originalChanges: [], modifiedChanges: [], children: [], ...member }], + }, + isIncomplete: true, + }; + } + + const member = { name: 'member', kind: types.SymbolKind.Property, range: new types.Range(0, 0, 0, 1) }; + const change = { textChangeIndex: 0, range: member.range, classification: types.StructuralDiffClassification.Implementation }; + const nullLine = { start: { line: null, character: 0 }, end: { line: 0, character: 1 } } as unknown as vscode.Range; + const convertibleValues: [string, Partial, RegExp][] = [ + ['an unknown kind', { modifiedItem: { ...member, kind: 99 as vscode.SymbolKind } }, /Invalid structural diff: node 'member' has an invalid modified item kind/], + ['a kind that is a numeric string', { modifiedItem: { ...member, kind: '0' as unknown as vscode.SymbolKind } }, /Invalid structural diff: node 'member' has an invalid modified item kind/], + ['an item range with a line that is not a number', { originalItem: { ...member, range: nullLine } }, /Invalid structural diff: node 'member' has an invalid original item range/], + ['a selection range with a line that is not a number', { modifiedItem: { ...member, selectionRange: nullLine } }, /Invalid structural diff: node 'member' has an invalid modified selection range/], + ['a change range with a line that is not a number', { modifiedItem: member, modifiedChanges: [{ ...change, range: nullLine }] }, /Invalid structural diff: node 'member' has an invalid modified change range/], + ]; + for (const [description, node, expected] of convertibleValues) { + test(`rejects ${description} instead of converting it to a valid value`, async () => { + await register({ provideStructuralDiff: () => resultWith(node) }); + await assert.rejects(provide(), expected); + }); + } + + test('passes tags that are not an array on for validation instead of dropping them', async () => { + await register({ provideStructuralDiff: () => resultWith({ modifiedItem: member, modifiedChanges: [{ ...change, tags: null as unknown as vscode.StructuralDiffTag[] }] }) }); + assert.strictEqual((await provide())?.root.children[0].modifiedChanges[0].tags, null); + }); + + test('runtime enum values match the core contract', () => { + assert.deepStrictEqual({ + classification: types.StructuralDiffClassification, + tag: types.StructuralDiffTag, + }, { + classification: StructuralDiffClassification, + tag: StructuralDiffTag, + }); + }); +}); + +suite('ExtHost structural diff API command', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const originalUri = URI.parse('test:/original.ts'); + const modifiedUri = URI.parse('test:/modified.ts'); + const range = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 2 }; + const apiRange = new types.Range(0, 0, 0, 1); + let rpc: TestRPCProtocol; + let commands: ExtHostCommands; + let executed: { id: string; uris: string[] }[]; + let internalResult: StructuralDiffResult | undefined; + + setup(() => { + executed = []; + internalResult = undefined; + rpc = store.add(new TestRPCProtocol()); + rpc.set(MainContext.MainThreadCommands, new class extends mock() { + override $registerCommand(): void { } + override $unregisterCommand(): void { } + override $fireCommandActivationEvent(): void { } + override async $executeCommand(id: string, args: unknown[] | SerializableObjectWithBuffers): Promise { + const values = args instanceof SerializableObjectWithBuffers ? args.value : args; + executed.push({ id, uris: values.map(value => URI.revive(value as UriComponents).toString()) }); + return internalResult; + } + }); + commands = new ExtHostCommands(rpc, new NullLogService(), new class extends mock() { }); + ExtHostApiCommands.register(commands); + }); + + teardown(() => rpc.sync()); + + test('forwards both resources and converts the result to API types', async () => { + const item = { name: 'file.ts', detail: 'detail', kind: SymbolKind.File, range, selectionRange: range }; + internalResult = { + root: { + id: 'file', originalItem: item, modifiedItem: item, originalChanges: [], modifiedChanges: [], + children: [{ + id: 'member', + originalItem: { ...item, name: 'oldName', kind: SymbolKind.Method }, + modifiedItem: { ...item, name: 'newName', kind: SymbolKind.Method }, + originalChanges: [{ textChangeIndex: 0, range, classification: StructuralDiffClassification.Header, tags: [StructuralDiffTag.Test] }], + modifiedChanges: [{ textChangeIndex: 0, range, classification: StructuralDiffClassification.Implementation, tags: [] }], + children: [], + }], + }, + isIncomplete: true, + context: { changes: [{ originalRange: range, modifiedRange: range }] }, + }; + const result = await commands.executeCommand('vscode.executeStructuralDiffProvider', originalUri, modifiedUri); + const apiItem = { name: 'file.ts', detail: 'detail', kind: types.SymbolKind.File, range: apiRange, selectionRange: apiRange }; + assert.deepStrictEqual({ executed, result }, { + executed: [{ id: '_executeStructuralDiffProvider', uris: [originalUri.toString(), modifiedUri.toString()] }], + result: { + root: { + id: 'file', originalItem: apiItem, modifiedItem: apiItem, originalChanges: [], modifiedChanges: [], + children: [{ + id: 'member', + originalItem: { ...apiItem, name: 'oldName', kind: types.SymbolKind.Method }, + modifiedItem: { ...apiItem, name: 'newName', kind: types.SymbolKind.Method }, + originalChanges: [{ textChangeIndex: 0, range: apiRange, classification: types.StructuralDiffClassification.Header, tags: [types.StructuralDiffTag.Test] }], + modifiedChanges: [{ textChangeIndex: 0, range: apiRange, classification: types.StructuralDiffClassification.Implementation, tags: [] }], + children: [], + }], + }, + isIncomplete: true, + context: { changes: [{ originalRange: apiRange, modifiedRange: apiRange }] }, + }, + }); + }); + + test('resolves to undefined when no provider supplies a result', async () => { + const result = await commands.executeCommand('vscode.executeStructuralDiffProvider', originalUri, modifiedUri); + assert.deepStrictEqual({ executed: executed.length, result }, { executed: 1, result: undefined }); + }); + + test('rejects invalid arguments without executing the internal command', async () => { + await assert.rejects(commands.executeCommand('vscode.executeStructuralDiffProvider', originalUri), /Invalid argument 'modified'/); + await assert.rejects(commands.executeCommand('vscode.executeStructuralDiffProvider', 'test:/original.ts', modifiedUri), /Invalid argument 'original'/); + assert.deepStrictEqual(executed, []); + }); +}); diff --git a/src/vs/workbench/api/test/common/testRPCProtocol.ts b/src/vs/workbench/api/test/common/testRPCProtocol.ts index a794359ce4bb..93ce6adcee7e 100644 --- a/src/vs/workbench/api/test/common/testRPCProtocol.ts +++ b/src/vs/workbench/api/test/common/testRPCProtocol.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { isThenable } from '../../../../base/common/async.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; import { CharCode } from '../../../../base/common/charCode.js'; import { IExtHostRpcService } from '../../common/extHostRpcService.js'; import { IExtHostContext } from '../../../services/extensions/common/extHostCustomers.js'; @@ -159,6 +160,10 @@ function simulateWireTransfer(obj: T): T { return obj; } + if (CancellationToken.isCancellationToken(obj)) { + return obj; + } + if (Array.isArray(obj)) { // eslint-disable-next-line local/code-no-any-casts return obj.map(simulateWireTransfer) as any; diff --git a/src/vs/workbench/browser/actions/listCommands.ts b/src/vs/workbench/browser/actions/listCommands.ts index 9f7594a22c20..685191c1b523 100644 --- a/src/vs/workbench/browser/actions/listCommands.ts +++ b/src/vs/workbench/browser/actions/listCommands.ts @@ -716,11 +716,11 @@ KeybindingsRegistry.registerCommandAndKeybindingRule({ // As the tree does not know anything about the rendered DOM elements // we have to traverse the dom to find the HTMLElements const treeDOM = lastFocusedList.getHTMLElement(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const scrollableElement = treeDOM.querySelector('.monaco-scrollable-element'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const listRows = scrollableElement?.querySelector('.monaco-list-rows'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const focusedElement = listRows?.querySelector('.focused'); if (!focusedElement) { return; @@ -741,7 +741,7 @@ function getCustomHoverForElement(element: HTMLElement): HTMLElement | undefined // Only consider children that are not action items or have a tabindex // as these element are focusable and the user is able to trigger them already - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const noneFocusableElementWithHover = element.querySelector('[custom-hover="true"]:not([tabindex]):not(.action-item)'); if (noneFocusableElementWithHover) { return noneFocusableElementWithHover as HTMLElement; diff --git a/src/vs/workbench/browser/chatPills.ts b/src/vs/workbench/browser/chatPills.ts index fccd2dce5018..b6ffa55f000f 100644 --- a/src/vs/workbench/browser/chatPills.ts +++ b/src/vs/workbench/browser/chatPills.ts @@ -691,14 +691,23 @@ export class ChatPillsWidget extends Disposable { /** Returns the rendered button for each pill. */ getPillElements(): readonly HTMLElement[] { - const elements: HTMLElement[] = []; + return this._getPillViewItems().flatMap(viewItem => viewItem.buttonElement ? [viewItem.buttonElement] : []); + } + + /** Returns the rendered item for each pill, which spans its button and any segments joined to it. */ + getPillItemElements(): readonly HTMLElement[] { + return this._getPillViewItems().flatMap(viewItem => viewItem.buttonElement && viewItem.element ? [viewItem.element] : []); + } + + private _getPillViewItems(): readonly ChatPillActionViewItemBase[] { + const viewItems: ChatPillActionViewItemBase[] = []; for (let index = 0; index < this._toolbar.getItemsLength(); index++) { const viewItem = this._toolbar.getItemViewItem(index); - if (viewItem instanceof ChatPillActionViewItemBase && viewItem.buttonElement) { - elements.push(viewItem.buttonElement); + if (viewItem instanceof ChatPillActionViewItemBase) { + viewItems.push(viewItem); } } - return elements; + return viewItems; } focusFirst(): boolean { diff --git a/src/vs/workbench/browser/dnd.ts b/src/vs/workbench/browser/dnd.ts index 7cdd638ad5b8..9a1647f32bd7 100644 --- a/src/vs/workbench/browser/dnd.ts +++ b/src/vs/workbench/browser/dnd.ts @@ -3,9 +3,11 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import './media/dnd.css'; import { DataTransfers, IDragAndDropData } from '../../base/browser/dnd.js'; -import { DragAndDropObserver, EventType, addDisposableListener, getActiveWindow, onDidRegisterWindow } from '../../base/browser/dom.js'; +import { $, DragAndDropObserver, EventType, addDisposableListener, append, getActiveWindow, getWindow, onDidRegisterWindow } from '../../base/browser/dom.js'; import { DragMouseEvent } from '../../base/browser/mouseEvent.js'; +import { renderFormattedText } from '../../base/browser/formattedTextRenderer.js'; import { IListDragAndDrop } from '../../base/browser/ui/list/list.js'; import { ElementsDragAndDropData, ListViewTargetSector } from '../../base/browser/ui/list/listView.js'; import { ITreeDragOverReaction } from '../../base/browser/ui/tree/tree.js'; @@ -38,22 +40,49 @@ import { IEditorOptions } from '../../platform/editor/common/editor.js'; import { mainWindow } from '../../base/browser/window.js'; import { BroadcastDataChannel } from '../../base/browser/broadcast.js'; -const inputDropTargets = new Set(); +/** + * An input, such as a chat input, that takes the drags it accepts before the placement targets of the pane that + * encloses it, such as a grid that opens what is dropped on it. + */ +export interface IInputDropTarget { + + /** Whether the input takes the drag: placement takes a drag that the input does not, also over the input. */ + accepts(event: DragEvent): boolean; + + /** + * The element around the input, such as the whole chat widget of a chat input, whose drags the input takes too where + * nothing around it takes them, such as a drag that a placement overlay lets through while a key is held. Only the + * input itself when not set. + */ + readonly area?: HTMLElement; + + /** + * What a placement overlay that covers the input says over it, such as that a drag over it attaches what is dragged, + * as formatted text (see {@link renderFormattedText}). With a `passThroughModifier`, the key that lets the drag + * through the overlay into the input's {@link area} where it is, it also says that holding that key does the same. + */ + getHint(passThroughModifier: string | undefined): string; +} -/** Registers an input that handles drops before its enclosing pane's placement targets. */ -export function registerInputDropTarget(element: HTMLElement): IDisposable { - inputDropTargets.add(element); - return toDisposable(() => inputDropTargets.delete(element)); +const inputDropTargets = new Map(); + +/** Registers an input that takes the drags it accepts before its enclosing pane's placement targets. */ +export function registerInputDropTarget(element: HTMLElement, target: IInputDropTarget): IDisposable { + inputDropTargets.set(element, target); + return toDisposable(() => { + if (inputDropTargets.get(element) === target) { + inputDropTargets.delete(element); + } + }); } /** - * Whether `element` is (in) a registered input drop target, or `point` is over - * one, such as while an overlay covers it. With a `scope`, only inputs inside - * it count for `point`: an input that something else covers, such as a modal - * over the main editor area, does not. + * Whether the drag is over a registered input that takes it: `element` is (in) such an input, or the drag's position is + * over one, such as while an overlay covers it. With a `scope`, only inputs inside it count for the position: an input + * that something else covers, such as a modal over the main editor area, does not. */ -export function isInputDropTarget(element: HTMLElement, point?: { readonly clientX: number; readonly clientY: number }, scope?: HTMLElement): boolean { - return isRegisteredDropTarget(inputDropTargets, element, point, scope); +export function isInputDropTarget(element: HTMLElement, event: DragEvent, scope?: HTMLElement): boolean { + return isRegisteredDropTarget(inputDropTargets, element, event, scope, input => !!inputDropTargets.get(input)?.accepts(event)); } const contentDropTargets = new Set(); @@ -75,43 +104,155 @@ export function isContentDropTarget(element: HTMLElement, point?: { readonly cli return isRegisteredDropTarget(contentDropTargets, element, point, scope); } -function isRegisteredDropTarget(targets: ReadonlySet, element: HTMLElement, point: { readonly clientX: number; readonly clientY: number } | undefined, scope: HTMLElement | undefined): boolean { +const passThroughDropTargets = new Map boolean>(); + +/** + * Registers a pane, such as the editor area, whose placement overlay lets the drags that `letsThrough` tells through to + * what it covers, such as a drag dropped into an editor while a key is held. + */ +export function registerPassThroughDropTarget(element: HTMLElement, letsThrough: (event: DragEvent) => boolean): IDisposable { + passThroughDropTargets.set(element, letsThrough); + return toDisposable(() => { + if (passThroughDropTargets.get(element) === letsThrough) { + passThroughDropTargets.delete(element); + } + }); +} + +/** + * Whether the drag reaches `element` as a pane around it lets it through, such as the chat of a chat editor while the key + * to drop into the editor is held: an input there that takes the drag shows so, as it does with the drag over it. + */ +export function isPassThroughDrag(element: HTMLElement, event: DragEvent): boolean { + for (const [pane, letsThrough] of passThroughDropTargets) { + if (pane.contains(element) && letsThrough(event)) { + return true; + } + } + return false; +} + +/** + * @param accepts whether a registered target takes the drag; asked last, for the targets under the drag only, as it runs + * on every `dragover` and can cost more than the position checks. + */ +function isRegisteredDropTarget(targets: ReadonlySet | ReadonlyMap, element: HTMLElement, point: { readonly clientX: number; readonly clientY: number } | undefined, scope: HTMLElement | undefined, accepts?: (target: HTMLElement) => boolean): boolean { for (let target: HTMLElement | null = element; target; target = target.parentElement) { - if (targets.has(target)) { + if (targets.has(target) && (!accepts || accepts(target))) { return true; } } if (point) { - return [...targets].some(target => { - if (scope && !scope.contains(target)) { - return false; + for (const target of targets.keys()) { + if ((!scope || scope.contains(target)) && target.ownerDocument === element.ownerDocument && isOver(target, point) && (!accepts || accepts(target))) { + return true; } - const bounds = target.getBoundingClientRect(); - return target.ownerDocument === element.ownerDocument && bounds.width > 0 && bounds.height > 0 - && point.clientX >= bounds.left && point.clientX <= bounds.right && point.clientY >= bounds.top && point.clientY <= bounds.bottom; - }); + } } return false; } -export function getInputDropTargets(container: HTMLElement): readonly HTMLElement[] { - return [...inputDropTargets].filter(target => container.contains(target)); +/** Whether `point` is over `element`, which shows. */ +function isOver(element: HTMLElement, point: { readonly clientX: number; readonly clientY: number }): boolean { + const bounds = element.getBoundingClientRect(); + return bounds.width > 0 && bounds.height > 0 + && point.clientX >= bounds.left && point.clientX <= bounds.right && point.clientY >= bounds.top && point.clientY <= bounds.bottom; } -/** Leaves registered inputs outside a placement overlay's pointer hit region. */ -export function getInputDropTargetClipPath(container: HTMLElement, overlay: HTMLElement = container): string { - const bounds = overlay.getBoundingClientRect(); - const holes = getInputDropTargets(container).flatMap(input => { - const rect = input.getBoundingClientRect(); - const left = Math.max(0, rect.left - bounds.left); - const top = Math.max(0, rect.top - bounds.top); - const right = Math.min(bounds.width, rect.right - bounds.left); - const bottom = Math.min(bounds.height, rect.bottom - bounds.top); - return right > left && bottom > top - ? [`${left}px ${top}px, ${right}px ${top}px, ${right}px ${bottom}px, ${left}px ${bottom}px, ${left}px ${top}px, 0 0`] - : []; - }); - return holes.length ? `polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ${holes.join(', ')})` : ''; +interface IInputDropTargetHint { + readonly element: HTMLElement; + readonly label: HTMLElement; + text: string | undefined; +} + +/** + * Shows, on a placement overlay that covers the registered inputs inside `scope` that take the drag, where they are: an + * outline around each with its {@link IInputDropTarget.getHint hint}. The overlay takes the drag until it moves over such + * an input, which then takes it instead (see {@link isInputDropTarget}). + */ +export class InputDropTargetHints extends Disposable { + + private readonly element: HTMLElement; + private readonly hints = new Map(); + + private _inputTakesPassThrough = false; + + /** + * Whether, where the drag last was, an input takes the drag that the `passThroughModifier` lets through: its hint says + * so, in place of what the overlay says holding the key does. + */ + get inputTakesPassThrough(): boolean { + return this._inputTakesPassThrough; + } + + /** + * @param passThroughModifier the key, as it shows, that lets a drag through the overlay to what the overlay covers, + * such as into an editor, while it is held + */ + constructor(private readonly scope: HTMLElement, overlay: HTMLElement, private readonly passThroughModifier?: string) { + super(); + + this.element = append(overlay, $('.input-drop-target-hints', { 'aria-hidden': 'true' })); + this._register(toDisposable(() => this.element.remove())); + } + + /** Shows the hints over the inputs that take the drag, or none without a drag, such as for one that no input takes. */ + update(event: DragEvent | undefined): void { + // Measures everything before it changes the DOM, as this runs on every `dragover`: the window then lays out once, + // not once per input. + const layouts = new Map(); + let inputTakesPassThrough = false; + const bounds = this.element.getBoundingClientRect(); + if (event) { + for (const [input, target] of inputDropTargets) { + if (!this.scope.contains(input)) { + continue; + } + const rect = input.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0 || !target.accepts(event)) { + continue; + } + + // The drag that the key lets through goes to what is under it: the input takes it there inside its area only. + const takesPassThrough = !!this.passThroughModifier && isOver(target.area ?? input, event); + inputTakesPassThrough ||= takesPassThrough; + layouts.set(input, { + rect, + // Shaped as the input is, whose corners depend on where it shows and on what is docked on it. + borderRadius: getWindow(input).getComputedStyle(input).borderRadius, + text: target.getHint(takesPassThrough ? this.passThroughModifier : undefined), + }); + } + } + this._inputTakesPassThrough = inputTakesPassThrough; + + for (const [input, hint] of this.hints) { + if (!layouts.has(input)) { + hint.element.remove(); + this.hints.delete(input); + } + } + + for (const [input, { rect, borderRadius, text }] of layouts) { + let hint = this.hints.get(input); + if (!hint) { + const element = append(this.element, $('.input-drop-target-hint')); + hint = { element, label: append(element, $('span.input-drop-target-hint-label')), text: undefined }; + this.hints.set(input, hint); + } + + if (hint.text !== text) { + hint.text = text; + renderFormattedText(text, undefined, hint.label); + } + + hint.element.style.top = `${rect.top - bounds.top}px`; + hint.element.style.left = `${rect.left - bounds.left}px`; + hint.element.style.width = `${rect.width}px`; + hint.element.style.height = `${rect.height}px`; + hint.element.style.borderRadius = borderRadius; + } + } } //#region Editor / Resources DND diff --git a/src/vs/workbench/browser/layout.ts b/src/vs/workbench/browser/layout.ts index 0c06ee52d361..1df7c2c2a2f6 100644 --- a/src/vs/workbench/browser/layout.ts +++ b/src/vs/workbench/browser/layout.ts @@ -26,7 +26,7 @@ import { IBrowserWorkbenchEnvironmentService } from '../services/environment/bro import { IEditorService } from '../services/editor/common/editorService.js'; import { EditorGroupLayout, GroupActivationReason, GroupOrientation, GroupsOrder, IEditorGroupsService } from '../services/editor/common/editorGroupsService.js'; import { SerializableGrid, ISerializableView, ISerializedGrid, Orientation, ISerializedNode, ISerializedLeafNode, Direction, IViewSize, Sizing } from '../../base/browser/ui/grid/grid.js'; -import { Part } from './part.js'; +import { Part, relayoutWorkbenchParts, updateSashEndpoints } from './part.js'; import { IStatusbarService } from '../services/statusbar/browser/statusbar.js'; import { IFileService } from '../../platform/files/common/files.js'; import { isCodeEditor } from '../../editor/browser/editorBrowser.js'; @@ -34,6 +34,8 @@ import { coalesce } from '../../base/common/arrays.js'; import { assertReturnsDefined } from '../../base/common/types.js'; import { INotificationService, NotificationsFilter } from '../../platform/notification/common/notification.js'; import { IThemeService } from '../../platform/theme/common/themeService.js'; +import { ISizeService } from '../../platform/theme/common/sizeService.js'; +import { panelsSpacing } from '../../platform/theme/common/sizeRegistry.js'; import { isHighContrast } from '../../platform/theme/common/theme.js'; import { WINDOW_ACTIVE_BORDER, WINDOW_INACTIVE_BORDER } from '../common/theme.js'; import { LineNumbersType } from '../../editor/common/config/editorOptions.js'; @@ -217,7 +219,7 @@ export abstract class Layout extends Disposable implements IWorkbenchLayoutServi if (targetDocument === this.mainContainer.ownerDocument) { return this.mainContainer; // main window } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax return targetDocument.body.getElementsByClassName('monaco-workbench')[0] as HTMLElement; // auxiliary window } } @@ -309,6 +311,7 @@ export abstract class Layout extends Disposable implements IWorkbenchLayoutServi private logService!: ILogService; private telemetryService!: ITelemetryService; private auxiliaryWindowService!: IAuxiliaryWindowService; + private panelSpacing = 4; private state!: ILayoutState; private stateModel!: LayoutStateModel; @@ -335,6 +338,19 @@ export abstract class Layout extends Disposable implements IWorkbenchLayoutServi this.logService = accessor.get(ILogService); this.telemetryService = accessor.get(ITelemetryService); this.auxiliaryWindowService = accessor.get(IAuxiliaryWindowService); + const sizeService = accessor.get(ISizeService); + const updatePanelSpacing = () => { + const spacing = sizeService.getSize(panelsSpacing, this.themeService.getColorTheme())!.value; + if (spacing !== this.panelSpacing) { + this.panelSpacing = spacing; + if (this.workbenchGrid && this.isFloatingPanelsEnabled()) { + this.layout(); + relayoutWorkbenchParts(this.workbenchGrid); + } + } + }; + updatePanelSpacing(); + this._register(sizeService.onDidChangeSizes(updatePanelSpacing)); // Parts this.editorService = accessor.get(IEditorService); @@ -537,6 +553,9 @@ export abstract class Layout extends Disposable implements IWorkbenchLayoutServi private handleContainerDidLayout(container: HTMLElement, dimension: IDimension): void { if (container === this.mainContainer) { + if (this.workbenchGrid) { + updateSashEndpoints(this.workbenchGrid.element, this.isFloatingPanelsEnabled() && !this.isModernUICompact()); + } this._onDidLayoutMainContainer.fire(dimension); } @@ -640,6 +659,10 @@ export abstract class Layout extends Disposable implements IWorkbenchLayoutServi return this.isFloatingPanelsEnabled() && this.configurationService.getValue(LayoutSettings.MODERN_UI_DENSITY) === ModernUIDensity.Compact; } + getPanelSpacing(): number { + return this.isModernUICompact() ? 0 : this.panelSpacing; + } + private updateFloatingPanels(): void { // Floating panels is a main-window concept: only the main container hosts // the side bars and bottom panel. Scope the class (and therefore the CSS diff --git a/src/vs/workbench/browser/media/chatPills.css b/src/vs/workbench/browser/media/chatPills.css index b06954b59c98..9235f202d42b 100644 --- a/src/vs/workbench/browser/media/chatPills.css +++ b/src/vs/workbench/browser/media/chatPills.css @@ -116,9 +116,12 @@ outline-offset: -1px !important; } +/* Segments stretch to the pill's height, so an icon-only segment, whose compact + glyph is shorter than a label's line box, lines up with its labelled neighbours. */ .chat-pill-sections { display: flex; - align-items: center; + align-self: stretch; + align-items: stretch; min-width: 0; border-radius: inherit; } @@ -133,6 +136,7 @@ } .chat-pill-item.chat-pill-segmented > .monaco-button.chat-pill-button { + align-self: stretch; border-start-start-radius: inherit; border-end-start-radius: inherit; border-inline-start-width: var(--vscode-strokeThickness); diff --git a/src/vs/workbench/browser/media/dnd.css b/src/vs/workbench/browser/media/dnd.css new file mode 100644 index 000000000000..2c4d13448a00 --- /dev/null +++ b/src/vs/workbench/browser/media/dnd.css @@ -0,0 +1,48 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Shown on a placement overlay over the inputs that take the drag instead when it moves over them. */ +.input-drop-target-hints { + position: absolute; + inset: 0; + /* Above the overlay's tint, so that the hints read clearly over it. */ + z-index: 1; + overflow: hidden; + pointer-events: none; +} + +.input-drop-target-hints > .input-drop-target-hint { + position: absolute; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + /* Thicker than the one stroke, and as bright as the hint's text: it marks where the drag goes, as a focus indicator does. */ + border: 2px dashed var(--vscode-editorGroup-dropIntoPromptForeground); +} + +.input-drop-target-hints > .input-drop-target-hint > .input-drop-target-hint-label { + max-width: calc(100% - 2 * var(--vscode-spacing-size80)); + padding: var(--vscode-spacing-size40) var(--vscode-spacing-size80); + border: var(--vscode-strokeThickness) solid var(--vscode-editorGroup-dropIntoPromptBorder, transparent); + border-radius: var(--vscode-cornerRadius-small); + color: var(--vscode-editorGroup-dropIntoPromptForeground); + background-color: var(--vscode-editorGroup-dropIntoPromptBackground); + line-height: normal; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* The key to hold, in what a drop overlay says, shown as a keybinding. */ +#monaco-workbench-editor-drop-overlay .editor-group-overlay-drop-into-prompt i, +.input-drop-target-hints > .input-drop-target-hint > .input-drop-target-hint-label i { + padding: 0 8px; + border: 1px solid hsla(0,0%,80%,.4); + margin: 0 1px; + border-radius: 5px; + background-color: rgba(255, 255, 255, 0.05); + font-style: normal; +} diff --git a/src/vs/workbench/browser/media/floatingPanels.css b/src/vs/workbench/browser/media/floatingPanels.css index 5f318a1a0a92..732424a42782 100644 --- a/src/vs/workbench/browser/media/floatingPanels.css +++ b/src/vs/workbench/browser/media/floatingPanels.css @@ -22,10 +22,12 @@ */ .monaco-workbench.floating-panels { - --modern-ui-floating-card-margin: var(--vscode-spacing-size40); + --modern-ui-floating-card-margin: var(--vscode-panels-spacing, var(--vscode-spacing-size40)); --modern-ui-floating-card-inner-margin: var(--vscode-spacing-sizeNone); --modern-ui-floating-card-outer-margin: var(--vscode-spacing-size40); --modern-ui-floating-card-statusbar-margin: var(--vscode-spacing-size40); + /* Match native border snapping across display scaling and window zoom. */ + --modern-ui-floating-card-stroke-width: calc(max(1px, round(down, var(--vscode-strokeThickness) * var(--window-device-pixel-ratio, 1), 1px)) / var(--window-device-pixel-ratio, 1)); } .monaco-workbench.floating-panels.modern-ui-compact { @@ -34,21 +36,19 @@ --modern-ui-floating-card-statusbar-margin: var(--vscode-spacing-sizeNone); --modern-ui-floating-card-border-color: transparent; --modern-ui-editor-border-color: transparent; - /* Match native border snapping across display scaling and window zoom. */ - --modern-ui-floating-card-stroke-width: calc(max(1px, round(down, var(--vscode-strokeThickness) * var(--window-device-pixel-ratio, 1), 1px)) / var(--window-device-pixel-ratio, 1)); } .monaco-workbench.floating-panels .part.sidebar, .monaco-workbench.floating-panels .part.auxiliarybar { --modern-ui-floating-card-edge-color: var(--modern-ui-floating-card-border-color, var(--vscode-surface-border, var(--vscode-widget-border, transparent))); - margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-margin) var(--modern-ui-floating-card-margin); + margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-statusbar-margin) var(--modern-ui-floating-card-margin); border: 1px solid var(--modern-ui-floating-card-edge-color) !important; /* The shorthand has to out-weigh the inline border color the pane composite part writes, * so the edge a card gives up to a shared seam is reassigned through these properties * instead — that keeps the state rules below on the normal cascade. */ border-left-color: var(--modern-ui-floating-card-seam-left-color, var(--modern-ui-floating-card-edge-color)) !important; border-right-color: var(--modern-ui-floating-card-seam-right-color, var(--modern-ui-floating-card-edge-color)) !important; - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--vscode-primarySideBar-cornerRadius, var(--vscode-cornerRadius-large)); background-color: var(--vscode-surface-background) !important; color: var(--vscode-surface-foreground); } @@ -76,9 +76,9 @@ /* Keep the panel surface aligned with the panel theme background in light theme. */ .monaco-workbench.floating-panels .part.panel { - margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-margin) var(--modern-ui-floating-card-margin); + margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-statusbar-margin) var(--modern-ui-floating-card-margin); border: 1px solid var(--modern-ui-floating-card-border-color, var(--vscode-modernPanel-border, var(--vscode-surface-border, var(--vscode-widget-border, transparent)))) !important; - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--vscode-toolsPanel-cornerRadius, var(--vscode-cornerRadius-large)); background-color: var(--vscode-panel-background) !important; color: var(--vscode-surface-foreground); } @@ -121,6 +121,11 @@ border-radius: var(--vscode-cornerRadius-large, 8px); } +.monaco-workbench.floating-panels .part.editor:not(.modal-editor-part) > .content, +.monaco-workbench.floating-panels .webview-overlay-content:not(.webview-overlay-modal) { + border-radius: var(--vscode-editorArea-cornerRadius, var(--vscode-cornerRadius-large, 8px)); +} + /* Compact parts meet each other and the window chrome edge-to-edge. */ .monaco-workbench.floating-panels.modern-ui-compact .part:is(.sidebar, .panel, .auxiliarybar), .monaco-workbench.floating-panels.modern-ui-compact .part.editor > .content, @@ -130,6 +135,7 @@ /* Keep the auxiliary bar background aligned with the primary sidebar in light theme. */ .monaco-workbench.floating-panels .part.auxiliarybar { + border-radius: var(--vscode-secondarySideBar-cornerRadius, var(--vscode-cornerRadius-large)); background-color: var(--vscode-sideBar-background) !important; } @@ -176,7 +182,7 @@ /* Main editor: float like the other cards. */ .monaco-workbench.floating-panels > .monaco-grid-view .part.editor { - margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-margin) var(--modern-ui-floating-card-margin); + margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-statusbar-margin) var(--modern-ui-floating-card-margin); } .monaco-workbench.floating-panels.top-window-edge > .monaco-grid-view .part.editor { @@ -227,9 +233,9 @@ * keep their inset whatever the gutter is. The card width and the item centering below * both derive from it, and `ActivitybarPart.floatingHorizontalGutter` reserves it. */ --modern-ui-activitybar-lane: var(--vscode-spacing-size80); - margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-margin); + margin: var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-inner-margin) var(--modern-ui-floating-card-statusbar-margin); width: calc(var(--activity-bar-width, 48px) + var(--modern-ui-activitybar-lane)); - height: calc(100% - var(--modern-ui-floating-card-margin)); + height: calc(100% - var(--modern-ui-floating-card-statusbar-margin)); padding-left: var(--vscode-spacing-sizeNone); padding-right: var(--vscode-spacing-sizeNone); border: 1px solid var(--modern-ui-floating-card-border-color, var(--vscode-modernActivityBar-border, var(--vscode-surface-border, var(--vscode-widget-border, transparent)))); @@ -241,38 +247,38 @@ .monaco-workbench.floating-panels .part.activitybar.left { margin-left: var(--modern-ui-floating-card-outer-margin); margin-right: var(--modern-ui-floating-card-inner-margin); - border-radius: var(--vscode-cornerRadius-large) 0 0 var(--vscode-cornerRadius-large); + border-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)) 0 0 var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } .monaco-workbench.floating-panels .part.activitybar.right { margin-left: var(--modern-ui-floating-card-inner-margin); margin-right: var(--modern-ui-floating-card-outer-margin); - border-radius: 0 var(--vscode-cornerRadius-large) var(--vscode-cornerRadius-large) 0; + border-radius: 0 var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)) var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)) 0; } /* A horizontal panel can shorten the primary side bar while the activity bar stays full-height. * Round the rail corner exposed beyond the attached side bar. Compact density stays connected. */ .monaco-workbench.floating-panels:not(.modern-ui-compact).panel-position-top:not(.nopanel):is(.panel-alignment-justify, .panel-alignment-left) .part.activitybar.left { - border-top-right-radius: var(--vscode-cornerRadius-large); + border-top-right-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } .monaco-workbench.floating-panels:not(.modern-ui-compact).panel-position-top:not(.nopanel):is(.panel-alignment-justify, .panel-alignment-right) .part.activitybar.right { - border-top-left-radius: var(--vscode-cornerRadius-large); + border-top-left-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } .monaco-workbench.floating-panels:not(.modern-ui-compact).panel-position-bottom:not(.nopanel):is(.panel-alignment-justify, .panel-alignment-left) .part.activitybar.left { - border-bottom-right-radius: var(--vscode-cornerRadius-large); + border-bottom-right-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } .monaco-workbench.floating-panels:not(.modern-ui-compact).panel-position-bottom:not(.nopanel):is(.panel-alignment-justify, .panel-alignment-right) .part.activitybar.right { - border-bottom-left-radius: var(--vscode-cornerRadius-large); + border-bottom-left-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } /* With the primary side bar collapsed there is no card to connect to, so the rail closes up * as a standalone panel with every corner rounded. Its border is already opaque on all four * sides. Compact density keeps its cards joined edge to edge, so it is excluded. */ .monaco-workbench.floating-panels:not(.modern-ui-compact).nosidebar .part.activitybar { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--vscode-activityBar-cornerRadius, var(--vscode-cornerRadius-large)); } /* A left-hand rail gets its gap for free from the leading margin of the card beside it. A @@ -286,7 +292,7 @@ .monaco-workbench.floating-panels.top-window-edge .part.activitybar { margin-top: var(--modern-ui-floating-card-outer-margin); - height: calc(100% - var(--modern-ui-floating-card-outer-margin) - var(--modern-ui-floating-card-margin)); + height: calc(100% - var(--modern-ui-floating-card-outer-margin) - var(--modern-ui-floating-card-statusbar-margin)); } /* Compact density treats the status bar as chrome outside the cluster, so the rail's @@ -550,53 +556,26 @@ } } -/* - * Floating cards use the density-specific leading margin and no trailing margin, so - * adjacent cards are separated by the configured gap. - * A grid sash is centered on the grid boundary, but because the two card margins - * differ, that boundary is offset from the gap's midpoint by half the margin - * difference. At the default 4px size the sash already matches the gap width and only - * needs recentering. Grow grid sashes configured below the gap width to 4px, preserve - * larger configured sizes, and compensate for that symmetric growth while shifting - * the sash onto the gap midpoint. This keeps the hit region reaching both card edges - * and the highlight (`:before`, itself centered in the sash) centered in the gap for - * any configured sash size. Part-internal sashes and the hidden-panel reveal sash - * retain their own geometry. - */ +/* Leading card margins shift the visible gap away from the logical grid boundary. */ .monaco-workbench.floating-panels .monaco-sash.vertical:not(.part .monaco-sash) { - /* Thickness: at least the gap, but never smaller than the configured sash size. */ - width: max(var(--vscode-sash-size), var(--modern-ui-floating-card-margin)); - /* Shift onto the gap midpoint (half the margin difference), compensating for the symmetric growth. */ - transform: translateX(calc((var(--modern-ui-floating-card-margin) - var(--modern-ui-floating-card-inner-margin)) / 2 - (max(var(--vscode-sash-size), var(--modern-ui-floating-card-margin)) - var(--vscode-sash-size)) / 2)); + transform: translateX(calc((var(--modern-ui-floating-card-margin) - var(--modern-ui-floating-card-inner-margin)) / 2)); } .monaco-workbench.floating-panels:not(.nopanel) .monaco-sash.horizontal:not(.part .monaco-sash) { - height: max(var(--vscode-sash-size), var(--modern-ui-floating-card-margin)); - transform: translateY(calc((var(--modern-ui-floating-card-margin) - var(--modern-ui-floating-card-inner-margin)) / 2 - (max(var(--vscode-sash-size), var(--modern-ui-floating-card-margin)) - var(--vscode-sash-size)) / 2)); + transform: translateY(calc((var(--modern-ui-floating-card-margin) - var(--modern-ui-floating-card-inner-margin)) / 2)); } -/* - * A vertical grid sash (between the editor and a side/auxiliary bar) spans the full - * height of the content region, but the floating cards it divides are inset from the - * region by the card margins. Left unadjusted, the hover highlight (`:before`) - * overshoots into those gaps — the reported "sash extends past the panels". Anchor the - * highlight with `top`/`bottom` (rather than `height`) so the two insets compose - * independently across layouts. The base follows the 4px outer shell gutter on - * the bottom while cards meet the title or banner at the top. Only the highlight is inset; the sash hit region is - * unchanged. In non-justify alignments a full-height side bar (spanning both the panel - * and editor rows) keeps its own margins, so its highlight may sit up to a card margin - * short on the abutting edge — an accepted minor cosmetic gap. - */ +/* Exterior ends stop at card gutters; junction markers instead meet the adjoining gap center. */ .monaco-workbench.floating-panels .monaco-sash.vertical:not(.part .monaco-sash)::before { - top: var(--modern-ui-floating-card-inner-margin); - bottom: var(--modern-ui-floating-card-statusbar-margin); + top: var(--workbench-sash-highlight-start, var(--modern-ui-floating-card-inner-margin)); + bottom: var(--workbench-sash-highlight-end, var(--modern-ui-floating-card-statusbar-margin)); height: auto; } /* At the top window edge the cards take the outer gutter. Inset the sash * highlight to match so it doesn't overshoot above the cards. */ .monaco-workbench.floating-panels.top-window-edge .monaco-sash.vertical:not(.part .monaco-sash)::before { - top: var(--modern-ui-floating-card-outer-margin); + top: var(--workbench-sash-highlight-start, var(--modern-ui-floating-card-outer-margin)); } /* @@ -607,35 +586,24 @@ * the normal zero trailing margin. */ .monaco-workbench.floating-panels.nostatusbar:is(:not(.panel-position-bottom), .nopanel) .monaco-sash.vertical:not(.part .monaco-sash)::before { - bottom: var(--modern-ui-floating-card-outer-margin); + bottom: var(--workbench-sash-highlight-end, var(--modern-ui-floating-card-outer-margin)); } -/* - * A horizontal grid sash (the resize handle between the editor and a top/bottom panel) - * draws its hover highlight full-width, but the panel card it divides is inset from the - * column's side edges by the floating card margins — so the line overshoots both ends. - * Anchor the highlight with `left`/`right` (rather than `width`) so each side composes - * independently: the base uses the panel card's leading and trailing margins. Either - * margin switches to the outer gutter when the panel is the outermost card on that - * window edge; mirror that with the `.floating-panel-outer-left` / `.floating-panel-outer-right` - * classes set on the workbench root (propagated from the panel's outer-edge state in - * paneCompositePart) so the highlight tracks the same margins the card uses, per layout. - * Both-edges is handled automatically since the two rules touch independent properties. - */ +/* Interior ends reach gap midpoints; window-facing ends retain their perimeter gutter. */ .monaco-workbench.floating-panels:not(.nopanel) .monaco-sash.horizontal:not(.part .monaco-sash)::before { - left: var(--modern-ui-floating-card-margin); - right: var(--modern-ui-floating-card-inner-margin); + left: var(--workbench-sash-highlight-start, calc(var(--modern-ui-floating-card-margin) / 2)); + right: var(--workbench-sash-highlight-end, calc(-1 * var(--modern-ui-floating-card-margin) / 2)); width: auto; } /* Panel owns the left cluster edge; match its outer gutter. */ .monaco-workbench.floating-panels:not(.nopanel).floating-panel-outer-left .monaco-sash.horizontal:not(.part .monaco-sash)::before { - left: var(--modern-ui-floating-card-outer-margin); + left: var(--workbench-sash-highlight-start, var(--modern-ui-floating-card-outer-margin)); } /* Panel owns the right cluster edge; match its outer gutter. */ .monaco-workbench.floating-panels:not(.nopanel).floating-panel-outer-right .monaco-sash.horizontal:not(.part .monaco-sash)::before { - right: var(--modern-ui-floating-card-outer-margin); + right: var(--workbench-sash-highlight-end, var(--modern-ui-floating-card-outer-margin)); } /* diff --git a/src/vs/workbench/browser/media/part.css b/src/vs/workbench/browser/media/part.css index a9cd407de3c4..77d734440046 100644 --- a/src/vs/workbench/browser/media/part.css +++ b/src/vs/workbench/browser/media/part.css @@ -8,6 +8,24 @@ overflow: hidden; } +.monaco-workbench .monaco-sash.workbench-sash-start-at-gap { + --workbench-sash-highlight-start: 0px; +} + +.monaco-workbench .monaco-sash.workbench-sash-end-at-gap { + --workbench-sash-highlight-end: 0px; +} + +.monaco-workbench .monaco-sash.vertical:is(.workbench-sash-start-at-gap, .workbench-sash-end-at-gap) { + top: var(--workbench-sash-start, 0px); + height: calc(100% - var(--workbench-sash-start, 0px) - var(--workbench-sash-end, 0px)); +} + +.monaco-workbench .monaco-sash.horizontal:is(.workbench-sash-start-at-gap, .workbench-sash-end-at-gap) { + left: var(--workbench-sash-start, 0px); + width: calc(100% - var(--workbench-sash-start, 0px) - var(--workbench-sash-end, 0px)); +} + .monaco-workbench .part > .drop-block-overlay.visible { visibility: visible; } @@ -95,4 +113,3 @@ top: 33px; /* at the bottom of the 35px height title container */ z-index: 5; /* on top of things */ } - diff --git a/src/vs/workbench/browser/part.ts b/src/vs/workbench/browser/part.ts index dc347513bf2a..93bfe14410cd 100644 --- a/src/vs/workbench/browser/part.ts +++ b/src/vs/workbench/browser/part.ts @@ -7,9 +7,9 @@ import './media/part.css'; import './media/floatingPanels.css'; import { Component } from '../common/component.js'; import { IThemeService, IColorTheme } from '../../platform/theme/common/themeService.js'; -import { Dimension, size, IDimension, getActiveDocument, prepend, IDomPosition } from '../../base/browser/dom.js'; +import { Dimension, size, IDimension, getActiveDocument, prepend, IDomPosition, isHTMLElement } from '../../base/browser/dom.js'; import { IStorageService } from '../../platform/storage/common/storage.js'; -import { ISerializableView, IViewSize } from '../../base/browser/ui/grid/grid.js'; +import { Grid, GridNode, ISerializableView, IViewSize, isGridBranchNode } from '../../base/browser/ui/grid/grid.js'; import { Event, Emitter } from '../../base/common/event.js'; import { IWorkbenchLayoutService } from '../services/layout/browser/layoutService.js'; import { assertReturnsDefined } from '../../base/common/types.js'; @@ -28,6 +28,91 @@ export interface ILayoutContentResult { readonly footerSize: IDimension; } +/** Reapplies content metrics when allocations are unchanged and the grid would skip its leaves. */ +export function relayoutWorkbenchParts(grid: Grid): void { + const relayout = (node: GridNode): void => { + if (isGridBranchNode(node)) { + node.children.forEach(relayout); + } else if (node.cachedVisibleSize === undefined && node.box.width > 0 && node.box.height > 0) { + node.view.layout(node.box.width, node.box.height, node.box.top, node.box.left); + } + }; + relayout(grid.getViews()); +} + +/** Meets perpendicular dividers at their visible gap centers without changing sash thickness. */ +export function updateSashEndpoints(gridElement: HTMLElement, enabled: boolean): void { + const elements: HTMLElement[] = []; + const findChild = (element: Element, className: string) => Array.from(element.children) + .find((child): child is HTMLElement => isHTMLElement(child) && child.classList.contains(className)); + const visit = (branch: HTMLElement): void => { + const split = findChild(branch, 'monaco-split-view2'); + const sashContainer = split && findChild(split, 'sash-container'); + if (sashContainer) { + elements.push(...Array.from(sashContainer.children).filter(isHTMLElement).filter(child => child.classList.contains('monaco-sash'))); + } + const scrollable = split && findChild(split, 'monaco-scrollable-element'); + const views = scrollable && findChild(scrollable, 'split-view-container'); + for (const view of views?.children ?? []) { + const child = view.firstElementChild; + if (isHTMLElement(child) && child.classList.contains('monaco-grid-branch-node')) { + visit(child); + } + } + }; + const branch = findChild(gridElement, 'monaco-grid-branch-node'); + if (branch) { + visit(branch); + } + const topLevel = !gridElement.closest('.part'); + const root = gridElement.closest('.monaco-workbench'); + const panelHasNoGap = root?.classList.contains('nopanel') + || (root?.classList.contains('floating-panels') && root.classList.contains('nomaineditorarea')); + const sashes = elements.flatMap(element => { + const vertical = element.classList.contains('vertical'); + const parent = element.parentElement; + if (!enabled || !parent || element.classList.contains('disabled') || (topLevel && panelHasNoGap && !vertical) + || parent.clientWidth === 0 || parent.clientHeight === 0) { + return []; + } + const position = Number.parseFloat(vertical ? element.style.left : element.style.top); + if (!Number.isFinite(position)) { + return []; + } + const bounds = parent.getBoundingClientRect(); + const rect = element.getBoundingClientRect(); + const scaleX = bounds.width / parent.clientWidth; + const scaleY = bounds.height / parent.clientHeight; + return [{ + element, + vertical, + nativeCenter: vertical ? bounds.left + position * scaleX + rect.width / 2 : bounds.top + position * scaleY + rect.height / 2, + center: vertical ? rect.left + rect.width / 2 : rect.top + rect.height / 2, + start: vertical ? bounds.top : bounds.left, + end: vertical ? bounds.bottom : bounds.right, + scale: vertical ? scaleY : scaleX, + }]; + }); + for (const element of elements) { + const sash = sashes.find(sash => sash.element === element); + for (const edge of ['start', 'end'] as const) { + const crossing = sash && sashes.find(candidate => candidate.vertical !== sash.vertical + && Math.abs(candidate.nativeCenter - sash[edge]) <= 0.5 + && sash.nativeCenter >= candidate.start - 0.5 && sash.nativeCenter <= candidate.end + 0.5); + element.classList.toggle(`workbench-sash-${edge}-at-gap`, !!crossing); + const property = `--workbench-sash-${edge}`; + if (sash && crossing) { + const value = `${(edge === 'start' ? crossing.center - sash.start : sash.end - crossing.center) / sash.scale}px`; + if (element.style.getPropertyValue(property) !== value) { + element.style.setProperty(property, value); + } + } else { + element.style.removeProperty(property); + } + } + } +} + /** * Parts are layed out in the workbench and have their own layout that * arranges an optional title and mandatory content area to show content. @@ -135,6 +220,7 @@ export abstract class Part extends Componen } this.parent.appendChild(footerContainer); + this.parent.classList.add('has-footer'); footerContainer.classList.add('header-or-footer'); footerContainer.classList.add('footer'); @@ -156,6 +242,7 @@ export abstract class Part extends Componen if (this.footerArea) { this.footerArea.remove(); this.footerArea = undefined; + this.parent?.classList.remove('has-footer'); this.partLayout?.setFooterVisibility(false); this.relayout(); } diff --git a/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts b/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts index 584b13144bfd..ae0a09c34ce2 100644 --- a/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts +++ b/src/vs/workbench/browser/parts/activitybar/activitybarPart.ts @@ -405,14 +405,11 @@ export class ActivitybarPart extends Part { return { top: 0, bottom: 0 }; } - const margin = getFloatingPanelMargin(this.layoutService); const outerMargin = getFloatingPanelOuterMargin(this.layoutService); const border = ActivitybarPart.FLOATING_BORDER; return { top: border + (isFloatingTopEdgeExposed(this.layoutService, mainWindow) ? outerMargin : FLOATING_PANEL_INNER_MARGIN), - bottom: border + (this.layoutService.isModernUICompact() - ? outerMargin - : this.layoutService.isVisible(Parts.STATUSBAR_PART, mainWindow) ? margin : outerMargin) + bottom: border + outerMargin }; } @@ -460,7 +457,7 @@ export class ActivityBarCompositeBar extends PaneCompositeBar { options.fillExtraContextMenuActions(actions, e); this.fillContextMenuActions(actions, e); } - }, part, paneCompositePart, instantiationService, storageService, extensionService, viewDescriptorService, viewService, contextKeyService, environmentService, layoutService); + }, part, paneCompositePart, instantiationService, storageService, extensionService, viewDescriptorService, viewService, contextKeyService, environmentService, layoutService, configurationService); if (globalActivities) { this.globalCompositeBar = this._register(instantiationService.createInstance(GlobalCompositeBar, () => this.getContextMenuActions(), (theme: IColorTheme) => this.options.colors(theme), this.options.activityHoverOptions)); diff --git a/src/vs/workbench/browser/parts/auxiliarybar/media/auxiliaryBarPart.css b/src/vs/workbench/browser/parts/auxiliarybar/media/auxiliaryBarPart.css index c94d7e903ce6..824fc70e3035 100644 --- a/src/vs/workbench/browser/parts/auxiliarybar/media/auxiliaryBarPart.css +++ b/src/vs/workbench/browser/parts/auxiliarybar/media/auxiliaryBarPart.css @@ -66,18 +66,18 @@ left: 5px; /* place icon in center */ } -.monaco-workbench .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-top-color: var(--vscode-panelTitle-activeBorder) !important; } -.monaco-workbench .part.auxiliarybar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.auxiliarybar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-top-color: var(--vscode-activityBarTop-activeBorder) !important; } -.monaco-workbench .part.auxiliarybar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.auxiliarybar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-bottom-color: var(--vscode-activityBarTop-activeBorder) !important; } diff --git a/src/vs/workbench/browser/parts/chat/chatHostPart.ts b/src/vs/workbench/browser/parts/chat/chatHostPart.ts new file mode 100644 index 000000000000..113b14f6ec40 --- /dev/null +++ b/src/vs/workbench/browser/parts/chat/chatHostPart.ts @@ -0,0 +1,178 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/chatHostPart.css'; +import { $, append, getComputedStyle } from '../../../../base/browser/dom.js'; +import { LayoutPriority } from '../../../../base/browser/ui/splitview/splitview.js'; +import { mainWindow } from '../../../../base/browser/window.js'; +import { IDisposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; +import { IContentPart } from '../../../services/editor/common/editorGroupsService.js'; +import { getFloatingEditorVerticalMargins, getFloatingEditorVerticalOuterEdges, getFloatingPaneCompositeHorizontalMargins, IWorkbenchLayoutService, Parts } from '../../../services/layout/browser/layoutService.js'; +import { Part } from '../../part.js'; + +/** + * The chat part of a window: a part of the workbench grid, beside the editor area, that shows the content a feature gives + * it, such as an editor part with chats. It knows nothing of that content but its size and its layout. A feature that + * shows a chat part creates it while the window starts (see `Layout.registerPart`), and hides or shows it through the + * layout service. + */ +export class ChatHostPart extends Part { + + /** The least width of the part, whatever its content needs less. */ + static readonly MINIMUM_WIDTH = 280; + + override readonly maximumWidth: number = Number.POSITIVE_INFINITY; + override readonly minimumHeight: number = 0; + override readonly maximumHeight: number = Number.POSITIVE_INFINITY; + + /** The editor area takes the width a window gains or loses first; the chat part keeps its own. */ + readonly priority = LayoutPriority.Low; + + private _content: IContentPart | undefined; + private readonly _contentListener = this._register(new MutableDisposable()); + private _contentArea: HTMLElement | undefined; + private _horizontalMargins = 0; + private _visible = false; + /** The widths of the edge of what it shows, read once, until they can change: its content, the theme, or the window's classes change. */ + private _contentEdge: ICardEdge | undefined; + + constructor( + @IThemeService themeService: IThemeService, + @IStorageService storageService: IStorageService, + @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, + ) { + super(Parts.CHAT_PART, { hasTitle: false }, themeService, storageService, layoutService); + } + + override get minimumWidth(): number { + return Math.max(ChatHostPart.MINIMUM_WIDTH, this._content?.minimumWidth ?? 0) + this._horizontalMargins; + } + + /** Shows `content`, until the returned disposable is disposed; the owner of the content disposes the content. */ + setContent(content: IContentPart): IDisposable { + // What it showed stops showing: its owner still disposes it, and disposing its handle then leaves this content alone + const previous = this._content; + if (previous && previous !== content) { + (previous.element as HTMLElement).remove(); + previous.setVisible(false); + } + this._content = content; + this._contentEdge = undefined; + this._contentArea?.appendChild(content.element as HTMLElement); + this._contentListener.value = content.onDidChange(() => this._onDidChange.fire(undefined)); + content.setVisible(this._visible); + this.relayoutContent(); + // Its least width follows what it shows: the grid sizes it again + this._onDidChange.fire(undefined); + return toDisposable(() => { + if (this._content === content) { + this._content = undefined; + this._contentListener.clear(); + (content.element as HTMLElement).remove(); + this._onDidChange.fire(undefined); + } + }); + } + + /** Moves focus into what the part shows. */ + focusContent(): void { + this._content?.activeGroup.focus(); + } + + protected override createContentArea(parent: HTMLElement): HTMLElement { + // The edge of what it shows follows the window's classes, such as for Modern UI, floating panels, or their density. + // The window lays out as they change, before this observer runs: lay out what it shows again, at its new edge + const classObserver = new MutationObserver(() => { + this._contentEdge = undefined; + this.relayoutContent(); + }); + classObserver.observe(this.layoutService.mainContainer, { attributes: true, attributeFilter: ['class'] }); + this._register(toDisposable(() => classObserver.disconnect())); + + this.element = parent; + this._contentArea = append(parent, $('.content')); + if (this._content) { + this._contentArea.appendChild(this._content.element as HTMLElement); + } + return this._contentArea; + } + + override layout(width: number, height: number, top: number, left: number): void { + super.layout(width, height, top, left); + + // With floating panels the part floats as a card, as the editor beside it does, and reserves the same margins + let marginLeft = 0, marginRight = 0, marginTop = 0, marginBottom = 0; + if (this.layoutService.isFloatingPanelsEnabled()) { + ({ left: marginLeft, right: marginRight } = getFloatingPaneCompositeHorizontalMargins(this.layoutService, Parts.CHAT_PART)); + ({ top: marginTop, bottom: marginBottom } = getFloatingEditorVerticalMargins(this.layoutService, mainWindow)); + } + // The edge it shares with the title bar is drawn as the other cards at that edge draw it (chatHostPart.css) + this.element.classList.toggle('floating-part-outer-top', getFloatingEditorVerticalOuterEdges(this.layoutService).top); + this.element.style.margin = `${marginTop}px ${marginRight}px ${marginBottom}px ${marginLeft}px`; + this.element.style.width = `calc(100% - ${marginLeft + marginRight}px)`; + this.element.style.height = `calc(100% - ${marginTop + marginBottom}px)`; + this._horizontalMargins = marginLeft + marginRight; + + // It draws no frame (chatHostPart.css). What it shows draws its own card edge, such as an editor part the editor card's + // edge (editorBorder.css), inside its box: it lays out within that edge, which the part would clip otherwise + const edge = this._content ? this._getContentEdge(this._content.element as HTMLElement) : NO_EDGE; + const contentWidth = Math.max(0, width - marginLeft - marginRight - edge.left - edge.right); + const contentHeight = Math.max(0, height - marginTop - marginBottom - edge.top - edge.bottom); + this._content?.layout(contentWidth, contentHeight, top + marginTop + edge.top, left + marginLeft + edge.left); + } + + override updateStyles(): void { + super.updateStyles(); + this._contentEdge = undefined; + } + + private _getContentEdge(element: HTMLElement): ICardEdge { + if (this._contentEdge) { + return this._contentEdge; + } + const edge = getCardEdge(element); + // Not yet in the window, it has no styles to read: read them again on the next layout + if (element.isConnected) { + this._contentEdge = edge; + } + return edge; + } + + override setVisible(visible: boolean): void { + this._visible = visible; + this._content?.setVisible(visible); + super.setVisible(visible); + } + + private relayoutContent(): void { + const dimension = this.dimension; + const position = this.contentPosition; + if (dimension && position) { + this.layout(dimension.width, dimension.height, position.top, position.left); + } + } + + toJSON(): object { + return { type: Parts.CHAT_PART }; + } +} + +interface ICardEdge { + readonly top: number; + readonly right: number; + readonly bottom: number; + readonly left: number; +} + +const NO_EDGE: ICardEdge = { top: 0, right: 0, bottom: 0, left: 0 }; + +/** The widths of the border that `element` draws, as its styles give them. */ +function getCardEdge(element: HTMLElement): ICardEdge { + const style = getComputedStyle(element); + const width = (value: string) => parseFloat(value) || 0; + return { top: width(style.borderTopWidth), right: width(style.borderRightWidth), bottom: width(style.borderBottomWidth), left: width(style.borderLeftWidth) }; +} diff --git a/src/vs/workbench/browser/parts/chat/media/chatHostPart.css b/src/vs/workbench/browser/parts/chat/media/chatHostPart.css new file mode 100644 index 000000000000..bb2c512b0e1d --- /dev/null +++ b/src/vs/workbench/browser/parts/chat/media/chatHostPart.css @@ -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. + *--------------------------------------------------------------------------------------------*/ + +.monaco-workbench .part.chat { + box-sizing: border-box; + overflow: hidden; +} + +.monaco-workbench .part.chat > .content { + width: 100%; + height: 100%; +} + +/* + * The chat part only places what it shows: it draws no frame of its own. What it shows draws its card's edge, as the editor + * part does the editor card's (editorBorder.css), so that the chat part is one card with one edge, as the cards beside it + * are. With floating panels it is rounded as they are. + */ +.monaco-workbench.floating-panels .part.chat { + border-radius: var(--vscode-editorArea-cornerRadius, var(--vscode-cornerRadius-large)); +} + +.monaco-workbench.floating-panels.modern-ui-compact .part.chat { + border-radius: 0; +} + +/* + * The part reserves the margins of its card itself, as the other cards do (`ChatHostPart.layout`). The editor part it shows + * is not the main editor: it takes none of the main editor's card margins (`floatingPanels.css`), which would double the + * gap to the card beside it and move its top and bottom edges off those of the cards beside it. + */ +.monaco-workbench.floating-panels > .monaco-grid-view .part.chat > .content .part.editor { + margin: 0; +} + +/* + * What the part shows draws its card's edge inside its own box, and what it lays over itself, such as a chat background, + * stays inside that edge rather than covering it. + */ +.monaco-workbench .part.chat > .content .part.editor { + position: relative; +} + +/* In compact density each card draws its own top edge at the title bar, as the editor card beside it does. */ +.monaco-workbench.modern-ui.floating-panels.modern-ui-compact .part.chat.floating-part-outer-top > .content .part.editor { + --modern-ui-floating-card-top-border-color: var(--modern-ui-floating-card-stroke-color); +} diff --git a/src/vs/workbench/browser/parts/compositeBar.ts b/src/vs/workbench/browser/parts/compositeBar.ts index 8d1020b66217..4e89e8f7c1c8 100644 --- a/src/vs/workbench/browser/parts/compositeBar.ts +++ b/src/vs/workbench/browser/parts/compositeBar.ts @@ -380,7 +380,7 @@ export class CompositeBar extends Widget implements ICompositeBar { if (this.model.activate(id)) { // Update if current composite is neither visible nor pinned // or previous active composite is not pinned - if (this.visibleComposites.indexOf(id) === - 1 || (!!this.model.activeItem && !this.model.activeItem.pinned) || (previousActiveItem && !previousActiveItem.pinned)) { + if (this.visibleComposites.indexOf(id) === -1 || (!!this.model.activeItem && !this.model.activeItem.pinned) || (previousActiveItem && !previousActiveItem.pinned)) { this.updateCompositeSwitcher(); } } diff --git a/src/vs/workbench/browser/parts/compositeBarActions.ts b/src/vs/workbench/browser/parts/compositeBarActions.ts index fe7bce2f083d..bc6a58a1be1c 100644 --- a/src/vs/workbench/browser/parts/compositeBarActions.ts +++ b/src/vs/workbench/browser/parts/compositeBarActions.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import './media/paneCompositePart.css'; import { localize } from '../../../nls.js'; import { Action, IAction, Separator } from '../../../base/common/actions.js'; import { $, addDisposableListener, append, clearNode, EventHelper, EventType, getDomNodePagePosition, hide, show } from '../../../base/browser/dom.js'; @@ -278,7 +279,9 @@ export class CompositeBarActionViewItem extends BaseActionViewItem { this.badgeContent = append(this.badge, $('.badge-content')); // pane composite bar active border + background - append(container, $('.active-item-indicator')); + const indicator = append(container, $('.active-item-indicator')); + append(indicator, $('.tab-connected-edge')).setAttribute('aria-hidden', 'true'); + append(container, $('span.tab-divider')).setAttribute('aria-hidden', 'true'); hide(this.badge); diff --git a/src/vs/workbench/browser/parts/editor/auxiliaryEditorPart.ts b/src/vs/workbench/browser/parts/editor/auxiliaryEditorPart.ts index b71633f0656f..890579180d7c 100644 --- a/src/vs/workbench/browser/parts/editor/auxiliaryEditorPart.ts +++ b/src/vs/workbench/browser/parts/editor/auxiliaryEditorPart.ts @@ -443,11 +443,11 @@ export class AuxiliaryEditorPartImpl extends EditorPart implements IAuxiliaryEdi return; // disabled, auxiliary editor part state is tracked outside } - close(): boolean { - return this.doClose(true /* merge all confirming editors to main part */); + close(options?: { preserveFocus?: boolean }): boolean { + return this.doClose(true /* merge all confirming editors to main part */, options); } - private doClose(mergeConfirmingEditorsToMainPart: boolean): boolean { + private doClose(mergeConfirmingEditorsToMainPart: boolean, options?: { preserveFocus?: boolean }): boolean { let result = true; if (mergeConfirmingEditorsToMainPart) { @@ -457,7 +457,7 @@ export class AuxiliaryEditorPartImpl extends EditorPart implements IAuxiliaryEdi } // Then merge remaining to main part - result = this.mergeGroupsToMainPart(); + result = this.mergeGroupsToMainPart(undefined, options); if (!result) { return false; // Do not close when editors could not be merged back } diff --git a/src/vs/workbench/browser/parts/editor/editor.ts b/src/vs/workbench/browser/parts/editor/editor.ts index deb4ae19c933..c6087f21b4d3 100644 --- a/src/vs/workbench/browser/parts/editor/editor.ts +++ b/src/vs/workbench/browser/parts/editor/editor.ts @@ -381,6 +381,9 @@ export interface IEditorGroupView extends IDisposable, ISerializableView, IEdito readonly disposed: boolean; + /** Whether the active editor is still being opened. */ + readonly isOpeningEditor: boolean; + setActive(isActive: boolean): void; notifyIndexChanged(newIndex: number): void; diff --git a/src/vs/workbench/browser/parts/editor/editorAddTabControl.ts b/src/vs/workbench/browser/parts/editor/editorAddTabControl.ts index c9a29026c56a..53d8efaa5441 100644 --- a/src/vs/workbench/browser/parts/editor/editorAddTabControl.ts +++ b/src/vs/workbench/browser/parts/editor/editorAddTabControl.ts @@ -19,8 +19,11 @@ import { IContextKeyService } from '../../../../platform/contextkey/common/conte import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { IEditorCommandsContext } from '../../../common/editor.js'; +const addTabActionId = 'editor.tabs.addTab'; + export interface IEditorAddTabControlOptions { /** @@ -64,6 +67,7 @@ export class EditorAddTabControl extends Disposable { @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, + @ITelemetryService telemetryService: ITelemetryService, ) { super(); @@ -73,7 +77,7 @@ export class EditorAddTabControl extends Disposable { const menu = this._register(menuService.createMenu(menuId, contextKeyService)); const getActions = () => getFlatActionBarActions(menu.getActions({ shouldForwardArgs: true })); const addTabAction = toAction({ - id: 'editor.tabs.addTab', + id: addTabActionId, label: localize('addTab', "Add Tab"), class: ThemeIcon.asClassName(Codicon.add), run: () => { } @@ -88,6 +92,7 @@ export class EditorAddTabControl extends Disposable { })); toolbar.context = options?.context; toolbar.setActions([addTabAction]); + this._registerMenuTelemetry(menuId, dropdown, toolbar, telemetryService); const updateVisibility = () => this.element.classList.toggle('hidden', getActions().length === 0); updateVisibility(); @@ -99,4 +104,42 @@ export class EditorAddTabControl extends Disposable { } })); } + + /** + * Logs the journey through the menu: it was opened, then an entry was picked or it was dismissed. + */ + private _registerMenuTelemetry(menuId: MenuId, dropdown: DropdownMenuActionViewItem, toolbar: WorkbenchToolBar, telemetryService: ITelemetryService): void { + type EditorAddTabMenuEvent = { kind: 'opened' | 'picked' | 'dismissed'; menuId: string; entry: string | undefined }; + type EditorAddTabMenuClassification = { + owner: 'hediet'; + comment: 'How the add tab (+) button at the end of the editor tabs is used.'; + kind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'opened: the menu was opened. picked: an entry was picked. dismissed: the menu was closed without picking an entry.' }; + menuId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The menu of the button, e.g. the one of the workbench or of the Agents window.' }; + entry: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The command id of the picked entry.' }; + }; + const log = (kind: EditorAddTabMenuEvent['kind'], entry?: string) => telemetryService.publicLog2('editorAddTabMenu', { kind, menuId: menuId.id, entry }); + + let picked = false; + // The dropdown runs its entries with the action runner of the toolbar + this._register(toolbar.actionRunner.onWillRun(e => { + if (e.action.id === addTabActionId) { + return; + } + picked = true; + log('picked', e.action.id); + })); + this._register(dropdown.onDidChangeVisibility(visible => { + if (visible) { + picked = false; + log('opened'); + return; + } + // The menu hides before the picked entry runs, in the same task + queueMicrotask(() => { + if (!picked) { + log('dismissed'); + } + }); + })); + } } diff --git a/src/vs/workbench/browser/parts/editor/editorCommands.ts b/src/vs/workbench/browser/parts/editor/editorCommands.ts index c4bf3aeecc2d..df8bd3f41d72 100644 --- a/src/vs/workbench/browser/parts/editor/editorCommands.ts +++ b/src/vs/workbench/browser/parts/editor/editorCommands.ts @@ -41,6 +41,7 @@ import { OpenWithEditorPicker } from '../../../services/editor/browser/openWithE import { IEditorService, SIDE_GROUP } from '../../../services/editor/common/editorService.js'; import { IPathService } from '../../../services/path/common/pathService.js'; import { ITextFileService } from '../../../services/textfile/common/textfiles.js'; +import { IUntitledDocumentTelemetryService } from '../../../services/untitled/common/untitledDocumentTelemetry.js'; import { IUntitledTextEditorService } from '../../../services/untitled/common/untitledTextEditorService.js'; import { IWorkingCopyEditorService } from '../../../services/workingCopy/common/workingCopyEditorService.js'; import { IWorkingCopyService } from '../../../services/workingCopy/common/workingCopyService.js'; @@ -959,6 +960,7 @@ function registerCloseEditorCommands() { const editorService = accessor.get(IEditorService); const editorResolverService = accessor.get(IEditorResolverService); const telemetryService = accessor.get(ITelemetryService); + const untitledDocumentTelemetryService = accessor.get(IUntitledDocumentTelemetryService); const textFileService = accessor.get(ITextFileService); const workingCopyService = accessor.get(IWorkingCopyService); const workingCopyEditorService = accessor.get(IWorkingCopyEditorService); @@ -1042,6 +1044,7 @@ function registerCloseEditorCommands() { ext: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'File extension for the resource' }; from: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The editor view type the resource is switched from' }; to: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The editor view type the resource is switched to' }; + untitledDocumentId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The untitledDocumentId of the untitledDocument events, if the resource is untitled' }; }; type WorkbenchEditorReopenEvent = { @@ -1049,13 +1052,15 @@ function registerCloseEditorCommands() { ext: string; from: string; to: string; + untitledDocumentId: string | undefined; }; telemetryService.publicLog2('workbenchEditorReopen', { scheme: editorToResolve.resource?.scheme ?? '', ext: editorToResolve.resource ? extname(editorToResolve.resource) : '', from: editor.editorId ?? '', - to: resolvedEditor.editor.editorId ?? '' + to: resolvedEditor.editor.editorId ?? '', + untitledDocumentId: untitledDocumentTelemetryService.getUntitledDocumentId(editorToResolve.resource), }); } } diff --git a/src/vs/workbench/browser/parts/editor/editorDropTarget.ts b/src/vs/workbench/browser/parts/editor/editorDropTarget.ts index e592abe6a963..4e4c281a68ef 100644 --- a/src/vs/workbench/browser/parts/editor/editorDropTarget.ts +++ b/src/vs/workbench/browser/parts/editor/editorDropTarget.ts @@ -19,7 +19,7 @@ import { activeContrastBorder } from '../../../../platform/theme/common/colorReg import { IThemeService, Themable } from '../../../../platform/theme/common/themeService.js'; import { isTemporaryWorkspace, IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js'; import { CodeDataTransfers, containsDragType, Extensions as DragAndDropExtensions, IDragAndDropContributionRegistry, LocalSelectionTransfer } from '../../../../platform/dnd/browser/dnd.js'; -import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, extractTreeDropData, getInputDropTargetClipPath, isContentDropTarget, isInputDropTarget, ResourcesDropHandler } from '../../dnd.js'; +import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, extractTreeDropData, InputDropTargetHints, isContentDropTarget, isInputDropTarget, registerPassThroughDropTarget, ResourcesDropHandler } from '../../dnd.js'; import { DEFAULT_EDITOR_MIN_DIMENSIONS, GroupTransferKind, IEditorGroupsView, IEditorGroupView, prepareMoveCopyEditors } from './editor.js'; import { EditorInputCapabilities, IEditorIdentifier, IUntypedEditorInput } from '../../../common/editor.js'; import { EditorInput } from '../../../common/editor/editorInput.js'; @@ -55,13 +55,17 @@ function isDropIntoEditorEnabledGlobally(configurationService: IConfigurationSer return configurationService.getValue('editor.dropIntoEditor.enabled'); } +/** The key, as it shows, that drops into the editor while it is held (see {@link isDragIntoEditorEvent}). */ +const DROP_INTO_EDITOR_MODIFIER_LABEL = isMacintosh ? '⇧' : 'Shift'; + function isDragIntoEditorEvent(e: DragEvent): boolean { return e.shiftKey; } /** - * Whether a drag, other than of a group, is over a registered input drop target (or an element inside one) inside - * `scope`, the group under the drag. Such inputs handle the drop themselves: the editor drop overlay has holes over them. + * Whether a drag, other than of a group, is over a registered input drop target that takes it (or an element inside one) + * inside `scope`, the group under the drag. Such inputs handle the drop themselves: the editor drop overlay, which shows + * where they are, goes away over them. */ function isInputDropTargetEvent(e: DragEvent, scope: HTMLElement, isDraggingGroup: boolean): boolean { return !isDraggingGroup && isHTMLElement(e.target) && isInputDropTarget(e.target, e, scope); @@ -225,6 +229,7 @@ class DropOverlay extends Themable { private container: HTMLElement | undefined; private overlay: HTMLElement | undefined; private dropIntoPromptElement?: HTMLSpanElement; + private inputHints: InputDropTargetHints | undefined; private currentDropOperation: IDropOperation | undefined; @@ -242,6 +247,7 @@ class DropOverlay extends Themable { constructor( private readonly groupView: IEditorGroupView, private readonly supportsSplitting: boolean, + event: DragEvent, @IThemeService themeService: IThemeService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @@ -257,12 +263,12 @@ class DropOverlay extends Themable { this.enableDropIntoEditor = isDropIntoEditorEnabledGlobally(this.configurationService) && this.isDropIntoActiveEditorEnabled(); - this.create(); + this.create(event); dropOverlays.add(this); } - private create(): void { + private create(event: DragEvent): void { const overlayOffsetHeight = this.getOverlayOffsetHeight(); // Container @@ -272,7 +278,6 @@ class DropOverlay extends Themable { // Parent this.groupView.element.appendChild(container); - this.updateInputClipPath(container); this.groupView.element.classList.add('dragged-over'); this._register(toDisposable(() => { container.remove(); @@ -284,11 +289,15 @@ class DropOverlay extends Themable { container.appendChild(this.overlay); if (this.enableDropIntoEditor) { - this.dropIntoPromptElement = renderFormattedText(localize('dropIntoEditorPrompt', "Hold __{0}__ to drop into editor", isMacintosh ? '⇧' : 'Shift'), {}); + this.dropIntoPromptElement = renderFormattedText(localize('dropIntoEditorPrompt', "Hold __{0}__ to drop into editor", DROP_INTO_EDITOR_MODIFIER_LABEL), {}); this.dropIntoPromptElement.classList.add('editor-group-overlay-drop-into-prompt'); this.overlay.appendChild(this.dropIntoPromptElement); } + // Inputs that take the drag when it moves over them, or, such as a chat input in a chat editor, when it drops into the editor + this.inputHints = this._register(new InputDropTargetHints(this.groupView.element, container, this.enableDropIntoEditor ? DROP_INTO_EDITOR_MODIFIER_LABEL : undefined)); + this.updateInputHints(event); + // Overlay Event Handling this.registerListeners(container); @@ -333,10 +342,16 @@ class DropOverlay extends Themable { const isDraggingGroup = this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype); const isDraggingEditor = this.editorTransfer.hasData(DraggedEditorIdentifier.prototype); + // An input that takes the drag takes it once the drag moves over it: + // the overlay, which covers the input until then, goes away + if (isInputDropTargetEvent(e, this.groupView.element, isDraggingGroup)) { + this.dispose(); + return; + } + // Content that handles drops takes the drop, except for editors and // groups: editors go into the group in its center, as tabs, and split - // it at its edges; groups only split it, also from its center. Inputs - // take drops through the overlay's holes. + // it at its edges; groups only split it, also from its center. const overContent = isContentDropTargetEvent(e, this.groupView.element); if ( (this.enableDropIntoEditor && isDragIntoEditorEvent(e)) || @@ -377,10 +392,8 @@ class DropOverlay extends Themable { // editor group splitting support based on setting and // keymodifiers used. const { x, y } = getDropAreaPosition(e, this.groupView); + this.updateInputHints(e); this.positionOverlay(x, y, isDraggingGroup, this.isSplittingEnabled(e), overContent && isDraggingGroup, overContent); - if (this.container) { - this.updateInputClipPath(this.container); - } // Make sure to stop any running cleanup scheduler to remove the overlay if (this.cleanupOverlayScheduler.isScheduled()) { @@ -435,8 +448,9 @@ class DropOverlay extends Themable { })); } - private updateInputClipPath(container: HTMLElement): void { - container.style.clipPath = this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype) ? '' : getInputDropTargetClipPath(this.groupView.element, container); + private updateInputHints(event: DragEvent): void { + // Inputs do not take groups + this.inputHints?.update(this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype) ? undefined : event); } private isDropIntoActiveEditorEnabled(): boolean { @@ -766,7 +780,8 @@ class DropOverlay extends Themable { if (!this.dropIntoPromptElement) { return; } - this.dropIntoPromptElement.style.opacity = showing ? '1' : '0'; + // Where an input takes what drops into the editor, such as a chat input in a chat editor, its hint says so instead + this.dropIntoPromptElement.style.opacity = showing && !this.inputHints?.inputTakesPassThrough ? '1' : '0'; } contains(element: HTMLElement): boolean { @@ -818,6 +833,9 @@ export class EditorDropTarget extends Themable { } private registerListeners(): void { + // The drags let through reach what is under the overlays, such as the input of a chat editor, which takes them + this._register(registerPassThroughDropTarget(this.container, e => this.letsDragThrough(e))); + this._register(addDisposableListener(this.container, EventType.DRAG_ENTER, e => this.onDragEnter(e))); this._register(addDisposableListener(this.container, EventType.DRAG_LEAVE, () => this.onDragLeave())); this._register(addDisposableListener(this.container, EventType.DRAG_OVER, e => this.onDragOverContent(e), true /* before the content handles it */)); @@ -826,8 +844,13 @@ export class EditorDropTarget extends Themable { } } + /** Whether the drag goes to the editors, without an overlay: as one dropped into an editor while the key is held. */ + private letsDragThrough(event: DragEvent): boolean { + return isDropIntoEditorEnabledGlobally(this.configurationService) && isDragIntoEditorEvent(event); + } + private onDragEnter(event: DragEvent): void { - if (isDropIntoEditorEnabledGlobally(this.configurationService) && isDragIntoEditorEvent(event)) { + if (this.letsDragThrough(event)) { return; } @@ -882,15 +905,15 @@ export class EditorDropTarget extends Themable { } // Create overlay over target - this.createOverlay(target); + this.createOverlay(target, event); } } - private createOverlay(target: HTMLElement): void { + private createOverlay(target: HTMLElement, event: DragEvent): void { if (!this.overlay) { const targetGroupView = this.findTargetGroupView(target); if (targetGroupView) { - this._overlay = this.instantiationService.createInstance(DropOverlay, targetGroupView, this.delegate.supportsSplitting !== false); + this._overlay = this.instantiationService.createInstance(DropOverlay, targetGroupView, this.delegate.supportsSplitting !== false, event); } } } @@ -915,7 +938,7 @@ export class EditorDropTarget extends Themable { if (!this.overlay) { this.updateContainer(true); - this.createOverlay(event.target); + this.createOverlay(event.target, event); } // The overlay shows for this drag already, and the content under it diff --git a/src/vs/workbench/browser/parts/editor/editorGroupView.ts b/src/vs/workbench/browser/parts/editor/editorGroupView.ts index 4926b8455908..7c2b709f14b5 100644 --- a/src/vs/workbench/browser/parts/editor/editorGroupView.ts +++ b/src/vs/workbench/browser/parts/editor/editorGroupView.ts @@ -121,6 +121,9 @@ export class EditorGroupView extends Themable implements IEditorGroupView { private readonly model: EditorGroupModel; private active: boolean | undefined; + private editorOpenOperation: object | undefined; + get isOpeningEditor(): boolean { return this.editorOpenOperation !== undefined; } + private lastLayout: IDomNodePagePosition | undefined; private readonly scopedInstantiationService: IInstantiationService; @@ -425,6 +428,7 @@ export class EditorGroupView extends Themable implements IEditorGroupView { this.editorService.openEditor({ resource: undefined, + untitledOrigin: 'emptyGroupDoubleClick', options: { pinned: true, override: DEFAULT_EDITOR_ASSOCIATION.id @@ -602,7 +606,7 @@ export class EditorGroupView extends Themable implements IEditorGroupView { // Show active editor (intentionally not using async to keep // `restoreEditors` from executing in same stack) - const result = this.doShowEditor(activeEditor, { active: true, isNew: false /* restored */ }, options, internalOptions).then(() => { + const result = this.withEditorActionsPending(() => this.doShowEditor(activeEditor, { active: true, isNew: false /* restored */ }, options, internalOptions)).then(() => { // Set focused now if this is the active group and focus has // not changed meanwhile. This prevents focus from being @@ -1310,34 +1314,58 @@ export class EditorGroupView extends Themable implements IEditorGroupView { } } - // Update model and make sure to continue to use the editor we get from - // the model. It is possible that the editor was already opened and we - // want to ensure that we use the existing instance in that case. - const { editor: openedEditor, isNew } = this.model.openEditor(editor, openEditorOptions); + const showEditor = () => { + // Update model and make sure to continue to use the editor we get from + // the model. It is possible that the editor was already opened and we + // want to ensure that we use the existing instance in that case. + const { editor: openedEditor, isNew } = this.model.openEditor(editor, openEditorOptions); - // Conditionally lock the group - if ( - isNew && // only if this editor was new for the group - this.count === 1 && // only when this editor was the first editor in the group - this.editorPartsView.groups.length > 1 // only allow auto locking if more than 1 group is opened - ) { - // only when the editor identifier is configured as such - if (openedEditor.editorId && this.groupsView.partOptions.autoLockGroups?.has(openedEditor.editorId)) { - this.lock(true); + // Conditionally lock the group + if ( + isNew && // only if this editor was new for the group + this.count === 1 && // only when this editor was the first editor in the group + this.editorPartsView.groups.length > 1 // only allow auto locking if more than 1 group is opened + ) { + // only when the editor identifier is configured as such + if (openedEditor.editorId && this.groupsView.partOptions.autoLockGroups?.has(openedEditor.editorId)) { + this.lock(true); + } } - } - // Show editor - const showEditorResult = this.doShowEditor(openedEditor, { active: !!openEditorOptions.active, isNew }, options, internalOptions); + // Show editor + const showEditorResult = this.doShowEditor(openedEditor, { active: !!openEditorOptions.active, isNew }, options, internalOptions); + + // Finally make sure the group is active or restored as instructed + if (activateGroup) { + this.groupsView.activateGroup(this); + } else if (restoreGroup) { + this.groupsView.restoreGroup(this); + } + + return showEditorResult; + }; - // Finally make sure the group is active or restored as instructed - if (activateGroup) { - this.groupsView.activateGroup(this); - } else if (restoreGroup) { - this.groupsView.restoreGroup(this); + const editorToOpen = this.model.findEditor(editor, openEditorOptions)?.[0] ?? editor; + if (openEditorOptions.active && (!this.activeEditorPane?.input?.matches(editorToOpen) || options?.forceReload)) { + return this.withEditorActionsPending(showEditor); } - return showEditorResult; + return showEditor(); + } + + private async withEditorActionsPending(openEditor: () => Promise): Promise { + const operation = this.editorOpenOperation = {}; + this.titleControl.updateEditorActions(); + try { + return await openEditor(); + } finally { + if (this.editorOpenOperation === operation) { + this.editorOpenOperation = undefined; + if (!this.disposed) { + this.titleControl.updateEditorActions(); + } + } + } } private doShowEditor(editor: EditorInput, context: { active: boolean; isNew: boolean }, options?: IEditorOptions, internalOptions?: IInternalEditorOpenOptions): Promise { diff --git a/src/vs/workbench/browser/parts/editor/editorGroupWatermark.ts b/src/vs/workbench/browser/parts/editor/editorGroupWatermark.ts index 18769852553a..97b5592d1ff2 100644 --- a/src/vs/workbench/browser/parts/editor/editorGroupWatermark.ts +++ b/src/vs/workbench/browser/parts/editor/editorGroupWatermark.ts @@ -314,12 +314,15 @@ export class EditorGroupWatermark extends Disposable { } } -class WatermarkActionViewItem extends BaseActionViewItem { +/** + * A row of the editor group watermark: icon, label and keybinding. Also used by the empty editor hint. + */ +export class WatermarkActionViewItem extends BaseActionViewItem { constructor( action: IAction, private readonly icon: ThemeIcon, - private readonly keybinding: ResolvedKeybinding, + private readonly keybinding: ResolvedKeybinding | undefined, @IHoverService private readonly hoverService: IHoverService, ) { super(undefined, action); @@ -329,13 +332,16 @@ class WatermarkActionViewItem extends BaseActionViewItem { const row = append(container, $('a.action-label.watermark-entry')); super.render(row); row.setAttribute('role', 'button'); - row.setAttribute('aria-label', localize('watermark.shortcutAriaLabel', "{0} ({1})", this._action.label, this.keybinding.getAriaLabel())); + const keybindingAriaLabel = this.keybinding?.getAriaLabel(); + row.setAttribute('aria-label', keybindingAriaLabel ? localize('watermark.shortcutAriaLabel', "{0} ({1})", this._action.label, keybindingAriaLabel) : this._action.label); const icon = append(row, renderIcon(this.icon)); icon.classList.add('watermark-icon'); icon.setAttribute('aria-hidden', 'true'); append(row, $('span.watermark-label')).textContent = this._action.label; - this._register(new KeybindingLabel(append(row, $('span.watermark-keybinding')), OS, defaultKeybindingLabelStyles)).set(this.keybinding); + if (this.keybinding) { + this._register(new KeybindingLabel(append(row, $('span.watermark-keybinding')), OS, defaultKeybindingLabelStyles)).set(this.keybinding); + } this._register(this.hoverService.setupDelayedHover(row, { content: this._action.label })); } } diff --git a/src/vs/workbench/browser/parts/editor/editorPart.ts b/src/vs/workbench/browser/parts/editor/editorPart.ts index d0320a097f7b..458b409ab880 100644 --- a/src/vs/workbench/browser/parts/editor/editorPart.ts +++ b/src/vs/workbench/browser/parts/editor/editorPart.ts @@ -33,6 +33,7 @@ import { SIDE_GROUP } from '../../../services/editor/common/editorService.js'; import { IBoundarySashes } from '../../../../base/browser/ui/sash/sash.js'; import { IHostService } from '../../../services/host/browser/host.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { MenuId } from '../../../../platform/actions/common/actions.js'; import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; import { EditorAreaFocusContext, EditorPartMaximizedEditorGroupContext, EditorPartMultipleEditorGroupsContext, EditorTabsVisibleContext, IsTopRightEditorGroupContext } from '../../../common/contextkeys.js'; import { mainWindow } from '../../../../base/browser/window.js'; @@ -1068,7 +1069,7 @@ export class EditorPart extends Part implements IEditorPart, options: { index: actualIndex, inactive, - preserveFocus: inactive + preserveFocus: inactive || options?.preserveFocus } }); } @@ -1125,7 +1126,7 @@ export class EditorPart extends Part implements IEditorPart, * the check of explicit transfers: each editor is still asked as it * moves (see `EditorInput.canMove`), and one that cannot go stays. */ - protected mergeGroupsToMainPart(targetPart: IEditorGroupsView = this.editorPartsView.mainPart): boolean { + protected mergeGroupsToMainPart(targetPart: IEditorGroupsView = this.editorPartsView.mainPart, options?: { preserveFocus?: boolean }): boolean { if (!this.groups.some(group => group.count > 0)) { return true; // skip if we have no editors opened } @@ -1147,9 +1148,12 @@ export class EditorPart extends Part implements IEditorPart, // Try to reduce the impact of closing this part // as much as possible by not changing existing // editors in the main part. - preserveExistingIndex: true + preserveExistingIndex: true, + preserveFocus: options?.preserveFocus }, GroupMergeReason.Close); - targetGroup.focus(); + if (!options?.preserveFocus) { + targetGroup.focus(); + } return result; } @@ -1820,4 +1824,9 @@ export class MainEditorPart extends EditorPart { ) { super(editorPartsView, Parts.EDITOR_PART, '', mainWindow.vscodeWindowId, instantiationService, themeService, configurationService, storageService, layoutService, hostService, contextKeyService); } + + // The new tab button shows while its menu has entries, which the `workbench.editor.experimental.newTabButton` setting controls. + protected override getGroupViewOptions(): IEditorGroupViewOptions | undefined { + return { menuIds: { tabsBarAddTab: MenuId.EditorTabsBarAddTab } }; + } } diff --git a/src/vs/workbench/browser/parts/editor/editorParts.ts b/src/vs/workbench/browser/parts/editor/editorParts.ts index 0ccdfed55ca8..3dda31425210 100644 --- a/src/vs/workbench/browser/parts/editor/editorParts.ts +++ b/src/vs/workbench/browser/parts/editor/editorParts.ts @@ -4,10 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import { localize } from '../../../../nls.js'; -import { EditorGroupLayout, GroupActivationReason, GroupDirection, GroupLocation, GroupOrientation, GroupsArrangement, GroupsOrder, IAuxiliaryEditorPart, IEditorGroupContextKeyProvider, IEditorDropTargetDelegate, IEditorGroupsService, IEditorSideGroup, IEditorWorkingSet, IFindGroupScope, IMergeGroupOptions, IEditorWorkingSetOptions, IEditorPart, IModalEditorPart, IEditorGroupActivationEvent, ICreateEditorPartOptions, IContentPart, getWindowMainPart } from '../../../services/editor/common/editorGroupsService.js'; +import { EditorGroupLayout, GroupActivationReason, GroupDirection, GroupLocation, GroupOrientation, GroupsArrangement, GroupsOrder, IAuxiliaryEditorPart, IEditorGroupContextKeyProvider, IEditorDropTargetDelegate, IEditorGroupsService, IEditorSideGroup, IEditorWorkingSet, IFindGroupScope, IMergeGroupOptions, IEditorWorkingSetOptions, IEditorPart, IModalEditorPart, IEditorGroupActivationEvent, ICreateEditorPartOptions, IContentPart, IResolvedEditorWorkingSet, getWindowMainPart } from '../../../services/editor/common/editorGroupsService.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { DisposableMap, DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; -import { GroupIdentifier, IEditorPartOptions } from '../../../common/editor.js'; +import { EditorsOrder, GroupIdentifier, IEditorPartOptions } from '../../../common/editor.js'; +import { ISerializedNode } from '../../../../base/browser/ui/grid/gridview.js'; +import { EditorGroupModel, isSerializedEditorGroupModel } from '../../../common/editor/editorGroupModel.js'; +import { EditorInput } from '../../../common/editor/editorInput.js'; +import { deepClone } from '../../../../base/common/objects.js'; import { EditorPart, IEditorPartUIState, MainEditorPart } from './editorPart.js'; import { IEditorGroupView, IEditorPartsView } from './editor.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; @@ -24,7 +28,7 @@ import { IThemeService } from '../../../../platform/theme/common/themeService.js import { IAuxiliaryWindowOpenOptions, IAuxiliaryWindowService } from '../../../services/auxiliaryWindow/browser/auxiliaryWindowService.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { ContextKeyValue, IContextKey, IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; -import { addDisposableListener, EventType, getActiveElement, getWindow, getWindowById, IDimension, isAncestor, isHTMLElement } from '../../../../base/browser/dom.js'; +import { addDisposableListener, EventType, getActiveElement, getWindow, getWindowById, IDimension, isAncestor, isAncestorOfActiveElement, isHTMLElement } from '../../../../base/browser/dom.js'; import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; import { IEditorService } from '../../../services/editor/common/editorService.js'; import { DeepPartial } from '../../../../base/common/types.js'; @@ -733,7 +737,7 @@ export class EditorParts extends MultiWindowParts { + private async applyState(state: IEditorPartsUIState | 'empty', options?: { preserveFocus?: boolean }): Promise { // Before closing windows, try to close as many editors as // possible, but skip over those that would trigger a dialog @@ -749,7 +753,7 @@ export class EditorParts extends MultiWindowParts ({ id: workingSet.id, name: workingSet.name })); } + resolveWorkingSet(workingSet: IEditorWorkingSet): IResolvedEditorWorkingSet | undefined { + const state = this.editorWorkingSets[this.indexOfWorkingSet(workingSet) ?? -1]; + if (!state) { + return undefined; + } + + const editors: EditorInput[] = []; + let activeEditor: EditorInput | undefined; + let complete = true; + const canonicalOf = (editor: EditorInput): EditorInput => { + const existing = editors.find(candidate => candidate.matches(editor)); + if (existing) { + if (existing !== editor) { + this.disposeUnshownEditors([editor]); + } + return existing; + } + editors.push(editor); + return editor; + }; + const collect = (node: ISerializedNode): void => { + if (node.type === 'branch') { + node.data.forEach(collect); + return; + } + + if (!isSerializedEditorGroupModel(node.data)) { + return; + } + const model = this.instantiationService.createInstance(EditorGroupModel, deepClone(node.data)); + try { + const groupEditors = model.getEditors(EditorsOrder.SEQUENTIAL); + complete &&= groupEditors.length === node.data.editors.length; + const groupActiveEditor = model.activeEditor ?? undefined; + for (const editor of groupEditors) { + const canonical = canonicalOf(editor); + if (node.data.id === state.main.activeGroup && editor === groupActiveEditor) { + activeEditor = canonical; + } + } + } finally { + model.dispose(); + } + }; + try { + collect(state.main.serializedGrid.root); + } catch (error) { + this.disposeUnshownEditors(editors); + throw error; + } + + if (!complete) { + this.disposeUnshownEditors(editors); + return undefined; + } + + return { editors, activeEditor, dispose: () => this.disposeUnshownEditors(editors) }; + } + + private disposeUnshownEditors(editors: readonly EditorInput[]): void { + for (const editor of editors) { + if (!this.groups.some(group => group.contains(editor, { strictEquals: true }))) { + editor.dispose(); + } + } + } + deleteWorkingSet(workingSet: IEditorWorkingSet): void { const index = this.indexOfWorkingSet(workingSet); if (typeof index === 'number') { @@ -814,22 +885,39 @@ export class EditorParts extends MultiWindowParts this.parts.some(part => { + const container = part.getContainer(); + return !part.isTransient && !!container && isAncestorOfActiveElement(container); + }); + // Apply state: begin with auxiliary windows first because it helps to keep // editors around that need confirmation by moving them into the main part. // Also, in rare cases, the auxiliary part may not be able to apply the state // for certain editors that cannot move to the main part. - const applied = await this.applyState(workingSetState === 'empty' ? workingSetState : workingSetState.auxiliary); + const applied = await this.applyState(workingSetState === 'empty' ? workingSetState : workingSetState.auxiliary, options); if (!applied) { return false; } await this.mainPart.applyState(workingSetState === 'empty' ? workingSetState : workingSetState.main, options); // Restore Focus unless instructed otherwise - if (!options?.preserveFocus) { + { const mostRecentActivePart = this.mostRecentActiveParts.find(part => !part.isTransient); // parts owned by someone else are not part of working sets if (mostRecentActivePart) { await mostRecentActivePart.whenReady; - mostRecentActivePart.activeGroup.focus(); + + // The editors of the new state open without being awaited: focus can only reach + // the active editor once it is there. + await mostRecentActivePart.activeGroup.whenRestored; + + // With preserved focus, only recover focus that is lost or still in an editor + // part: the user may have moved it elsewhere while the state was applied. + const activeElement = getActiveElement(); + if (!options?.preserveFocus || !activeElement || activeElement === activeElement.ownerDocument.body || isEditorFocus()) { + mostRecentActivePart.activeGroup.focus(); + } } } diff --git a/src/vs/workbench/browser/parts/editor/editorStatus.ts b/src/vs/workbench/browser/parts/editor/editorStatus.ts index 05a7a1132435..af9de75fbb94 100644 --- a/src/vs/workbench/browser/parts/editor/editorStatus.ts +++ b/src/vs/workbench/browser/parts/editor/editorStatus.ts @@ -1294,6 +1294,7 @@ export class ChangeLanguageAction extends Action2 { languageSupport.setLanguageId(languageSelection.languageId, ChangeLanguageAction.ID); if (resource?.scheme === Schemas.untitled) { + // TODO@hediet: remove once `documentLanguageChanged` (see untitledDocumentTelemetry.ts) has enough data, it covers this event type SetUntitledDocumentLanguageEvent = { to: string; from: string; modelPreference: string }; type SetUntitledDocumentLanguageClassification = { owner: 'TylerLeonhardt'; diff --git a/src/vs/workbench/browser/parts/editor/editorTabsControl.ts b/src/vs/workbench/browser/parts/editor/editorTabsControl.ts index 3a346205bece..c8330623fcb0 100644 --- a/src/vs/workbench/browser/parts/editor/editorTabsControl.ts +++ b/src/vs/workbench/browser/parts/editor/editorTabsControl.ts @@ -90,6 +90,7 @@ export interface IEditorTabsControl extends IDisposable { unstickEditor(editor: EditorInput): void; setActive(isActive: boolean): void; updateEditorSelections(): void; + updateEditorActions(): void; updateEditorLabel(editor: EditorInput): void; updateEditorCapabilities(editor: EditorInput): void; updateEditorDirty(editor: EditorInput): void; @@ -227,6 +228,7 @@ export abstract class EditorTabsControl extends Themable implements IEditorTabsC parent.appendChild(this.editorLayoutActionsToolbarContainer); this.handleEditorLayoutActionsToolBarVisibility(this.editorLayoutActionsToolbarContainer); + this.updateEditorActionsPendingState(); } protected createAddTabControl(parent: HTMLElement, menuId: MenuId, before?: HTMLElement, onDidChangeVisibility?: () => void): HTMLElement { @@ -376,8 +378,22 @@ export abstract class EditorTabsControl extends Themable implements IEditorTabsC return createActionViewItem(this.instantiationService, action, { ...options, menuAsChild: this.renderDropdownAsChildElement }); } + updateEditorActions(): void { + this.updateEditorActionsPendingState(); + this.updateEditorActionsToolbar(); + } + + private updateEditorActionsPendingState(): void { + for (const container of [this.editorActionsToolbarContainer, this.editorLayoutActionsToolbarContainer]) { + if (container) { + container.inert = this.groupView.isOpeningEditor; + container.setAttribute('aria-busy', String(this.groupView.isOpeningEditor)); + } + } + } + protected updateEditorActionsToolbar(): void { - if (!this.editorActionsEnabled) { + if (!this.editorActionsEnabled || this.groupView.isOpeningEditor) { return; } @@ -397,6 +413,7 @@ export abstract class EditorTabsControl extends Themable implements IEditorTabsC protected updateEditorLayoutActionsToolbar(): void { if ( !this.editorActionsEnabled || + this.groupView.isOpeningEditor || !this.editorLayoutActionsToolbarContainer || !this.editorLayoutActionsToolbar ) { diff --git a/src/vs/workbench/browser/parts/editor/editorTitleControl.ts b/src/vs/workbench/browser/parts/editor/editorTitleControl.ts index 7d686396407a..1d99f0c5a929 100644 --- a/src/vs/workbench/browser/parts/editor/editorTitleControl.ts +++ b/src/vs/workbench/browser/parts/editor/editorTitleControl.ts @@ -148,6 +148,10 @@ export class EditorTitleControl extends Themable { this.editorTabsControl.updateEditorSelections(); } + updateEditorActions(): void { + this.editorTabsControl.updateEditorActions(); + } + updateEditorLabel(editor: EditorInput): void { this.editorTabsControl.updateEditorLabel(editor); if (this.groupView.activeEditor === editor) { diff --git a/src/vs/workbench/browser/parts/editor/media/editordroptarget.css b/src/vs/workbench/browser/parts/editor/media/editordroptarget.css index deb238a8de88..f8e0c8b5bfea 100644 --- a/src/vs/workbench/browser/parts/editor/media/editordroptarget.css +++ b/src/vs/workbench/browser/parts/editor/media/editordroptarget.css @@ -41,15 +41,6 @@ transition: opacity 150ms ease-out; } -#monaco-workbench-editor-drop-overlay .editor-group-overlay-drop-into-prompt i /* Style keybinding */ { - padding: 0 8px; - border: 1px solid hsla(0,0%,80%,.4); - margin: 0 1px; - border-radius: 5px; - background-color: rgba(255, 255, 255, 0.05); - font-style: normal; -} - .monaco-workbench.monaco-enable-motion #monaco-workbench-editor-drop-overlay > .editor-group-overlay-indicator.overlay-move-transition { transition: top 70ms ease-out, left 70ms ease-out, width 70ms ease-out, height 70ms ease-out, opacity 150ms ease-out; } diff --git a/src/vs/workbench/browser/parts/editor/media/editorgroupview.css b/src/vs/workbench/browser/parts/editor/media/editorgroupview.css index 42ff37576cbb..e47c995da583 100644 --- a/src/vs/workbench/browser/parts/editor/media/editorgroupview.css +++ b/src/vs/workbench/browser/parts/editor/media/editorgroupview.css @@ -177,7 +177,8 @@ display: block; } -.monaco-workbench .editor-group-watermark .watermark-entry { +.monaco-workbench .editor-group-watermark .watermark-entry, +.monaco-workbench .empty-editor-hint-actions .watermark-entry { display: flex; align-items: center; gap: var(--vscode-spacing-size80); @@ -191,25 +192,29 @@ text-decoration: none; } -.monaco-workbench .editor-group-watermark .watermark-entry:hover { +.monaco-workbench .editor-group-watermark .watermark-entry:hover, +.monaco-workbench .empty-editor-hint-actions .watermark-entry:hover { background-color: var(--vscode-toolbar-hoverBackground); outline: var(--vscode-strokeThickness) dashed var(--vscode-toolbar-hoverOutline); outline-offset: calc(-1 * var(--vscode-strokeThickness)); } -.monaco-workbench .editor-group-watermark .watermark-entry:focus-visible { +.monaco-workbench .editor-group-watermark .watermark-entry:focus-visible, +.monaco-workbench .empty-editor-hint-actions .watermark-entry:focus-visible { outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); outline-offset: calc(-1 * var(--vscode-strokeThickness)); } -.monaco-workbench .editor-group-watermark .watermark-entry > .watermark-icon { +.monaco-workbench .editor-group-watermark .watermark-entry > .watermark-icon, +.monaco-workbench .empty-editor-hint-actions .watermark-entry > .watermark-icon { flex: 0 0 auto; width: var(--vscode-codiconFontSize); font-size: var(--vscode-codiconFontSize); color: var(--vscode-descriptionForeground); } -.monaco-workbench .editor-group-watermark .watermark-label { +.monaco-workbench .editor-group-watermark .watermark-label, +.monaco-workbench .empty-editor-hint-actions .watermark-label { flex: 1 1 auto; min-width: 0; overflow: hidden; @@ -217,7 +222,8 @@ white-space: nowrap; } -.monaco-workbench .editor-group-watermark .watermark-keybinding { +.monaco-workbench .editor-group-watermark .watermark-keybinding, +.monaco-workbench .empty-editor-hint-actions .watermark-keybinding { flex: 0 0 auto; color: var(--vscode-descriptionForeground); } diff --git a/src/vs/workbench/browser/parts/editor/modalEditorPart.ts b/src/vs/workbench/browser/parts/editor/modalEditorPart.ts index f00d983f1cf2..bee9fca55008 100644 --- a/src/vs/workbench/browser/parts/editor/modalEditorPart.ts +++ b/src/vs/workbench/browser/parts/editor/modalEditorPart.ts @@ -59,7 +59,7 @@ const MODAL_SIDEBAR_BORDER_RIGHT = 1; // matches CSS border-right on sidebar con const MODAL_FOCUSABLE_SELECTOR = 'a[href], area[href], button, input, select, textarea, iframe, object, embed, [contenteditable="true"], [tabindex]'; function getModalTabbableElements(modalElement: HTMLElement): HTMLElement[] { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const elements = Array.from(modalElement.querySelectorAll(MODAL_FOCUSABLE_SELECTOR)) .filter(element => { if (element.tabIndex < 0 || element.matches(':disabled') || element.closest('[inert]')) { diff --git a/src/vs/workbench/browser/parts/editor/multiEditorTabsControl.ts b/src/vs/workbench/browser/parts/editor/multiEditorTabsControl.ts index a360cdf8b739..b67d48d0768b 100644 --- a/src/vs/workbench/browser/parts/editor/multiEditorTabsControl.ts +++ b/src/vs/workbench/browser/parts/editor/multiEditorTabsControl.ts @@ -450,6 +450,7 @@ export class MultiEditorTabsControl extends EditorTabsControl { this.editorService.openEditor({ resource: undefined, + untitledOrigin: 'tabBarDoubleClick', options: { pinned: true, index: this.groupView.count, // always at the end @@ -585,7 +586,7 @@ export class MultiEditorTabsControl extends EditorTabsControl { // Figure out scrolling direction but ignore it if too subtle let tabSwitchDirection: number; - if (e.deltaX + e.deltaY < - MultiEditorTabsControl.MOUSE_WHEEL_DISTANCE_THRESHOLD) { + if (e.deltaX + e.deltaY < -MultiEditorTabsControl.MOUSE_WHEEL_DISTANCE_THRESHOLD) { tabSwitchDirection = -1; } else if (e.deltaX + e.deltaY > MultiEditorTabsControl.MOUSE_WHEEL_DISTANCE_THRESHOLD) { tabSwitchDirection = 1; @@ -2208,11 +2209,11 @@ export class MultiEditorTabsControl extends EditorTabsControl { const actionPadding = Number.parseFloat(style.getPropertyValue('--modern-ui-tab-action-fit-padding')) || 28; const currentActionPadding = Number.parseFloat(tab.classList.contains('tab-actions-left') ? style.paddingLeft : style.paddingRight); const intrinsicWidth = hasPersistentAction ? width + Math.max(0, actionPadding - currentActionPadding) : width; - /* eslint-disable no-restricted-syntax -- IconLabel exposes its root, but not its text-layout elements. */ + /* eslint-disable eslint-js/no-restricted-syntax -- IconLabel exposes its root, but not its text-layout elements. */ const label = tab.querySelector('.tab-label'); const name = label?.querySelector('.monaco-icon-name-container'); const labelContainer = label?.querySelector('.monaco-icon-label-container'); - /* eslint-enable no-restricted-syntax */ + /* eslint-enable eslint-js/no-restricted-syntax */ const nameWidth = name ? Number.parseFloat(targetWindow.getComputedStyle(name).width) : 0; const adornmentWidth = label && labelContainer ? Number.parseFloat(targetWindow.getComputedStyle(label).width) - Number.parseFloat(targetWindow.getComputedStyle(labelContainer).width) : 0; const borderWidth = Number.parseFloat(style.borderLeftWidth) + Number.parseFloat(style.borderRightWidth); diff --git a/src/vs/workbench/browser/parts/editor/multiRowEditorTabsControl.ts b/src/vs/workbench/browser/parts/editor/multiRowEditorTabsControl.ts index 332334ab55a0..3931e4c04849 100644 --- a/src/vs/workbench/browser/parts/editor/multiRowEditorTabsControl.ts +++ b/src/vs/workbench/browser/parts/editor/multiRowEditorTabsControl.ts @@ -181,6 +181,11 @@ export class MultiRowEditorControl extends Disposable implements IEditorTabsCont this.unstickyEditorTabsControl.updateEditorSelections(); } + updateEditorActions(): void { + this.stickyEditorTabsControl.updateEditorActions(); + this.unstickyEditorTabsControl.updateEditorActions(); + } + updateEditorLabel(editor: EditorInput): void { this.getEditorTabsController(editor).updateEditorLabel(editor); } diff --git a/src/vs/workbench/browser/parts/editor/newTabButton.ts b/src/vs/workbench/browser/parts/editor/newTabButton.ts new file mode 100644 index 000000000000..447eec6708a8 --- /dev/null +++ b/src/vs/workbench/browser/parts/editor/newTabButton.ts @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { ILocalizedString } from '../../../../nls.js'; +import { Action2, MenuId } from '../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr, ContextKeyExpression } from '../../../../platform/contextkey/common/contextkey.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { EditorTabsVisibleContext } from '../../../common/contextkeys.js'; +import { isEditorCommandsContext } from '../../../common/editor.js'; +import { IEditorGroup, IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.js'; + +export const NEW_TAB_BUTTON_SETTING = 'workbench.editor.experimental.newTabButton'; + +/** + * False while the new tab button replaces the new tab buttons of individual editors, such as the `+` of a chat editor: + * the setting is on and the tabs, which show the button, are visible. + */ +export const NewTabButtonHidden = ContextKeyExpr.or(ContextKeyExpr.notEquals(`config.${NEW_TAB_BUTTON_SETTING}`, true), EditorTabsVisibleContext.negate()); + +export interface INewTabButtonEntry { + readonly id: string; + readonly title: ILocalizedString; + readonly icon: ThemeIcon; + readonly order: number; + /** Hides the entry while the feature it opens is not available. */ + readonly when?: ContextKeyExpression; +} + +/** + * An entry of the new tab (`+`) button at the end of the editor tab bar ({@link MenuId.EditorTabsBarAddTab}), shown + * while {@link NEW_TAB_BUTTON_SETTING} is on. It opens its tab in the group of the button it was picked from. + * The button logs `editorAddTabMenu` telemetry for opening its menu and picking an entry. + */ +export abstract class NewTabButtonEntryAction extends Action2 { + + constructor(entry: INewTabButtonEntry) { + super({ + id: entry.id, + title: entry.title, + icon: entry.icon, + f1: false, + menu: { + id: MenuId.EditorTabsBarAddTab, + group: 'navigation', + order: entry.order, + when: ContextKeyExpr.and(ContextKeyExpr.equals(`config.${NEW_TAB_BUTTON_SETTING}`, true), entry.when) + } + }); + } + + override run(accessor: ServicesAccessor, ...args: unknown[]): Promise { + const editorGroupsService = accessor.get(IEditorGroupsService); + const context = args.find(isEditorCommandsContext); + const group = (context && editorGroupsService.getGroup(context.groupId)) ?? editorGroupsService.activeGroup; + // Commands that open in the active group then open in the group of the button. + editorGroupsService.activateGroup(group); + + return this.openTab(accessor, group); + } + + /** + * Opens the new tab. The accessor is only valid until the first `await`. + */ + protected abstract openTab(accessor: ServicesAccessor, group: IEditorGroup): Promise; +} diff --git a/src/vs/workbench/browser/parts/editor/textResourceEditor.ts b/src/vs/workbench/browser/parts/editor/textResourceEditor.ts index 147f439bb355..5bf2f43a389c 100644 --- a/src/vs/workbench/browser/parts/editor/textResourceEditor.ts +++ b/src/vs/workbench/browser/parts/editor/textResourceEditor.ts @@ -213,7 +213,9 @@ export class TextResourceEditor extends AbstractTextResourceEditor { } const opts = this.modelService.getCreationOptions(textModel.getLanguageId(), textModel.uri, textModel.isForSimpleWidget); - textModel.detectIndentation(opts.insertSpaces, opts.tabSize); + if (opts.detectIndentation) { + textModel.detectIndentation(opts.insertSpaces, opts.tabSize); + } } } } diff --git a/src/vs/workbench/browser/parts/editor/viewEditorPane.ts b/src/vs/workbench/browser/parts/editor/viewEditorPane.ts index 53f2a5740c7f..3c0bea388971 100644 --- a/src/vs/workbench/browser/parts/editor/viewEditorPane.ts +++ b/src/vs/workbench/browser/parts/editor/viewEditorPane.ts @@ -242,8 +242,8 @@ export class ViewEditorPane extends EditorPane { disposables.add(new DragAndDropObserver(handle, { onDragStart: e => { - // Text fields in the handle, such as a rename, keep the mouse - if (isHTMLElement(e.target) && isEditableElement(e.target)) { + // Text fields in the handle, such as a rename, keep the mouse, as does what the handle's container already declined + if (e.defaultPrevented || (isHTMLElement(e.target) && isEditableElement(e.target))) { e.preventDefault(); return; } diff --git a/src/vs/workbench/browser/parts/media/paneCompositePart.css b/src/vs/workbench/browser/parts/media/paneCompositePart.css index 399e77730cf1..b5fd7ab2331d 100644 --- a/src/vs/workbench/browser/parts/media/paneCompositePart.css +++ b/src/vs/workbench/browser/parts/media/paneCompositePart.css @@ -3,6 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +.monaco-workbench .monaco-action-bar .action-item > .tab-divider { + display: none; + position: absolute; + pointer-events: none; +} + .monaco-workbench .pane-composite-part > .title.has-composite-bar > .title-actions .monaco-action-bar .actions-container { justify-content: flex-end; } @@ -348,13 +354,13 @@ border-bottom-color: transparent !important; /* hides border on clicked state */ } -.monaco-workbench .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before, -.monaco-workbench .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { border-top-color: var(--vscode-focusBorder) !important; border-top-width: 2px; } -.monaco-workbench .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { border-bottom-color: var(--vscode-focusBorder) !important; border-bottom-width: 2px; } diff --git a/src/vs/workbench/browser/parts/paneCompositeBar.ts b/src/vs/workbench/browser/parts/paneCompositeBar.ts index ee76b0ef3b4f..83595a023725 100644 --- a/src/vs/workbench/browser/parts/paneCompositeBar.ts +++ b/src/vs/workbench/browser/parts/paneCompositeBar.ts @@ -6,12 +6,13 @@ import { localize } from '../../../nls.js'; import { ActionsOrientation } from '../../../base/browser/ui/actionbar/actionbar.js'; import { IActivityService } from '../../services/activity/common/activity.js'; -import { IWorkbenchLayoutService, Parts } from '../../services/layout/browser/layoutService.js'; +import { IWorkbenchLayoutService, LayoutSettings, Parts } from '../../services/layout/browser/layoutService.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; import { IDisposable, DisposableStore, Disposable, DisposableMap, combinedDisposable } from '../../../base/common/lifecycle.js'; import { IColorTheme } from '../../../platform/theme/common/themeService.js'; import { CompositeBar, ICompositeBarItem, CompositeDragAndDrop } from './compositeBar.js'; import { Dimension, isMouseEvent } from '../../../base/browser/dom.js'; +import { mainWindow } from '../../../base/browser/window.js'; import { createCSSRule } from '../../../base/browser/domStylesheets.js'; import { asCSSUrl } from '../../../base/browser/cssValue.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../platform/storage/common/storage.js'; @@ -31,6 +32,7 @@ import { GestureEvent } from '../../../base/browser/touch.js'; import { IPaneCompositePart } from './paneCompositePart.js'; import { IConfigurationService } from '../../../platform/configuration/common/configuration.js'; import { IViewsService } from '../../services/views/common/viewsService.js'; +import { RunOnceScheduler } from '../../../base/common/async.js'; interface IPlaceholderViewContainer { readonly id: string; @@ -95,6 +97,8 @@ export class PaneCompositeBar extends Disposable { private readonly compositeActions = this._register(new DisposableMap void }>()); private hasExtensionsRegistered: boolean = false; + private dimension: Dimension | undefined; + private needsSizeRecompute = false; constructor( private readonly location: ViewContainerLocation, @@ -109,6 +113,7 @@ export class PaneCompositeBar extends Disposable { @IContextKeyService protected readonly contextKeyService: IContextKeyService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IWorkbenchLayoutService protected readonly layoutService: IWorkbenchLayoutService, + @IConfigurationService configurationService: IConfigurationService, ) { super(); @@ -129,6 +134,19 @@ export class PaneCompositeBar extends Disposable { this.compositeBar = this.createCompositeBar(cachedItems); this.onDidRegisterViewContainers(this.getViewContainers()); this.registerListeners(); + + if (this.options.recomputeSizes) { + // Measure after the Modern UI contribution has applied the new tab geometry. + const recomputeSizes = this._register(new RunOnceScheduler(() => { + this.needsSizeRecompute = true; + this.recomputeSizesIfVisible(); + }, 0)); + this._register(configurationService.onDidChangeConfiguration(e => { + if (e.affectsConfiguration(LayoutSettings.MODERN_UI) || e.affectsConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE)) { + recomputeSizes.schedule(); + } + })); + } } private createCompositeBar(cachedItems: ICompositeBarItem[]) { @@ -515,7 +533,16 @@ export class PaneCompositeBar extends Disposable { } layout(width: number, height: number): void { - this.compositeBar.layout(new Dimension(width, height)); + this.dimension = new Dimension(width, height); + this.compositeBar.layout(this.dimension); + this.recomputeSizesIfVisible(); + } + + private recomputeSizesIfVisible(): void { + if (this.needsSizeRecompute && this.dimension && this.dimension.width > 0 && this.dimension.height > 0 && this.layoutService.isVisible(this.part, mainWindow)) { + this.needsSizeRecompute = false; + this.compositeBar.recomputeSizes(); + } } private getViewContainer(id: string): ViewContainer | undefined { diff --git a/src/vs/workbench/browser/parts/partGrid/partGrid.ts b/src/vs/workbench/browser/parts/partGrid/partGrid.ts index 3e8504d0a646..0489f441827e 100644 --- a/src/vs/workbench/browser/parts/partGrid/partGrid.ts +++ b/src/vs/workbench/browser/parts/partGrid/partGrid.ts @@ -1100,12 +1100,20 @@ export class PartGrid extends Disposable { * cell takes, so that the other cells keep their sizes. */ private addCell(cell: PartGridCell, location: PartGridLocation, size: number | undefined, donorId?: string): void { + // A cell that does not show, such as a part without editors, joins at its size without taking any room: the cells + // beside it keep their sizes until it shows + const invisible = !this.isCellVisible(cell.id); if (!this.grid) { this.setGrid(new PartGridLayout(cell, { proportionalLayout: true })); } else if (hasKey(location, { reference: true })) { - this.grid.addView(cell, size ?? Sizing.Split, this.getCell(location.reference), location.direction); + const reference = this.getCell(location.reference); + const referenceSize = this.grid.getViewSize(reference); + const half = Math.round((location.direction === Direction.Up || location.direction === Direction.Down ? referenceSize.height : referenceSize.width) / 2); + // Beside a cell that does not show either, it shows in the row or column they then share as before: that would + // have nothing to show + this.grid.addView(cell, invisible && this.grid.isViewVisible(reference) ? Sizing.Invisible(size ?? half) : size ?? Sizing.Split, reference, location.direction); } else { - this.addAtEdge(cell, location.edge, size, donorId); + this.addAtEdge(cell, location.edge, size, donorId, invisible); } this.updateAllVisibility(); @@ -1203,8 +1211,8 @@ export class PartGrid extends Disposable { return this.empty.has(id); } - private addAtEdge(cell: PartGridCell, edge: Direction, size: number | undefined, donorId?: string): void { - addAtEdge(this.arrangement(), cell, edge, size, donorId); + private addAtEdge(cell: PartGridCell, edge: Direction, size: number | undefined, donorId?: string, invisible = false): void { + addAtEdge(this.arrangement(), cell, edge, size, donorId, invisible); } /** @@ -1443,6 +1451,15 @@ export class PartGrid extends Disposable { return this.grid ? this.grid.getViewSize(this.getCell(id)) : { width: 0, height: 0 }; } + /** + * The least size of a cell, with the frame of its card, which the grid + * holds it to. + */ + getCellMinimumSize(id: string): IViewSize { + const cell = this.getCell(id); + return { width: cell.minimumWidth, height: cell.minimumHeight }; + } + /** * Resizes a cell; a dimension left out keeps its size. */ @@ -1655,7 +1672,7 @@ export class PartGrid extends Disposable { changed = cell.setLook(insets, frames[index]) || changed; }); - updateGridGapSashes(grid, true); + updateGridGapSashes(grid, true, this.gap); // Insets change the size constraints of the cells if (changed && relayout) { @@ -1663,6 +1680,14 @@ export class PartGrid extends Disposable { } } + /** + * The topology, sizes and visibility of the cells of the grid, without the + * state of the parts in them; see {@link createState}. + */ + serializeGrid(): ISerializedGrid | undefined { + return this.grid?.serialize(); + } + /** * Returns the topology, sizes and visibility of the grid and the state of * each part in it, to restore it with {@link restore}. @@ -1827,41 +1852,41 @@ export function getGridWithViewOnTop(state: ISerializedGrid, id: string): ISeria return { root: { type: 'branch', data: [pinned, ...below], size: state.width }, orientation: Orientation.VERTICAL, width: state.width, height: state.height }; } -function addAtEdge(arrangement: IArrangement, cell: T, edge: Direction, size: number | undefined, donorId?: string): void { +function addAtEdge(arrangement: IArrangement, cell: T, edge: Direction, size: number | undefined, donorId?: string, invisible = false): void { const grid = arrangement.grid; const orientation = edge === Direction.Up || edge === Direction.Down ? Orientation.VERTICAL : Orientation.HORIZONTAL; const atEnd = edge === Direction.Right || edge === Direction.Down; - if (addBesideSpanningViews(arrangement, cell, orientation, atEnd, size)) { + if (addBesideSpanningViews(arrangement, cell, orientation, atEnd, size, invisible)) { return; } - if (addAtEdgeOfParts(arrangement, cell, orientation, atEnd, size, donorId)) { + if (addAtEdgeOfParts(arrangement, cell, orientation, atEnd, size, donorId, invisible)) { return; } const root = grid.getViews(); const edgeChild = root.children[atEnd ? root.children.length - 1 : 0]; + const extent = orientation === Orientation.VERTICAL ? grid.height : grid.width; // Beside the only cell, or beside a cell at that edge of the root // along the grid's orientation, the grid adds it in place if (!isGridBranchNode(edgeChild) && (root.children.length === 1 || (grid.orientation === orientation && donorId === undefined))) { - grid.addView(cell, size ?? Sizing.Distribute, edgeChild.view, edge); + grid.addView(cell, invisible ? Sizing.Invisible(size ?? Math.round(extent / (root.children.length + 1))) : size ?? Sizing.Distribute, edgeChild.view, edge); return; } // Otherwise the grid is rebuilt with the cell at the edge of its root const state = grid.serialize(); - const extent = orientation === Orientation.VERTICAL ? state.height : state.width; const children = state.root.type === 'branch' ? state.root.data : [state.root]; let cellSize = Math.min(size ?? Math.round(extent / (grid.orientation === orientation ? root.children.length + 1 : 2)), extent); let newRoot: ISerializedNode; if (grid.orientation === orientation) { - const donated = takeRoom(arrangement, children, cellSize, size, donorId); + const donated = invisible ? { children, size: cellSize } : takeRoom(arrangement, children, cellSize, size, donorId); cellSize = donated.size; - const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize }; + const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize, ...(invisible ? { visible: false } : {}) }; newRoot = { ...state.root, type: 'branch', data: atEnd ? [...donated.children, added] : [added, ...donated.children] }; } else { - const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize }; - const rest: ISerializedNode = { type: 'branch', data: children, size: Math.max(0, extent - cellSize) }; + const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize, ...(invisible ? { visible: false } : {}) }; + const rest: ISerializedNode = { type: 'branch', data: children, size: invisible ? extent : Math.max(0, extent - cellSize) }; newRoot = { type: 'branch', data: atEnd ? [rest, added] : [added, rest], size: orientation === Orientation.VERTICAL ? state.width : state.height }; } arrangement.replace({ root: newRoot, orientation, width: state.width, height: state.height }); @@ -1874,7 +1899,7 @@ function addAtEdge(arrangement: IArrangement, cell: * spanning past the cell. Returns whether it added the cell: not without such * chrome there. */ -function addBesideSpanningViews(arrangement: IArrangement, cell: T, orientation: Orientation, atEnd: boolean, size: number | undefined): boolean { +function addBesideSpanningViews(arrangement: IArrangement, cell: T, orientation: Orientation, atEnd: boolean, size: number | undefined, invisible: boolean): boolean { const state = arrangement.grid.serialize(); // Chrome along the left or right edge spans the window from top to bottom, beside cells at its top or bottom edge const spansAlongEdge = (id: string) => { @@ -1916,15 +1941,17 @@ function addBesideSpanningViews(arrangement: IArrangeme return false; } + const [only] = parts; + const shows = (child: ISerializedNode) => child.type !== 'leaf' || child.visible !== false; + // Not where nothing else in that column (or row) shows, which would then have nothing to show + const hides = invisible && (parts.length !== 1 || only.type !== 'branch' || only.data.some(shows)); const cellSize = Math.min(size ?? Math.round(extent / 2), extent); - const rest = Math.max(0, extent - cellSize); - const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize }; + const rest = hides ? extent : Math.max(0, extent - cellSize); + const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize, ...(hides ? { visible: false } : {}) }; let beside: ISerializedNode; - const [only] = parts; if (parts.length === 1 && only.type === 'branch') { // A column (or row) along the edge already: the cell joins it at that end, and what shows in it makes room. Hidden // children take no room: they keep the size they had, to show at again. - const shows = (child: ISerializedNode) => child.type !== 'leaf' || child.visible !== false; const total = only.data.reduce((sum, child) => sum + (shows(child) ? child.size ?? 0 : 0), 0); const factor = total ? rest / total : 1; const data = only.data.map(child => shows(child) ? { ...child, size: Math.round((child.size ?? 0) * factor) } : child); @@ -1949,7 +1976,7 @@ function addBesideSpanningViews(arrangement: IArrangeme * holds the parts: a cell added there goes beside the parts, and the * views keep spanning the window. Returns whether it added the cell. */ -function addAtEdgeOfParts(arrangement: IArrangement, cell: T, orientation: Orientation, atEnd: boolean, size: number | undefined, donorId: string | undefined): boolean { +function addAtEdgeOfParts(arrangement: IArrangement, cell: T, orientation: Orientation, atEnd: boolean, size: number | undefined, donorId: string | undefined, invisible: boolean): boolean { const state = arrangement.grid.serialize(); const isView = (child: ISerializedNode) => child.type === 'leaf' && !arrangement.isPart((child.data as { id: string }).id); const path: number[] = []; @@ -1982,13 +2009,14 @@ function addAtEdgeOfParts(arrangement: IArrangement, const extent = orientation === Orientation.VERTICAL ? state.height : state.width; const cellSize = Math.min(size ?? Math.round(extent / (nodeOrientation === orientation ? node.data.length + 1 : 2)), extent); let replacement: ISerializedNode; + const hidden = invisible ? { visible: false } : {}; if (nodeOrientation === orientation) { - const donated = takeRoom(arrangement, node.data, cellSize, size, donorId); - const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: donated.size }; + const donated = invisible ? { children: node.data, size: cellSize } : takeRoom(arrangement, node.data, cellSize, size, donorId); + const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: donated.size, ...hidden }; replacement = { ...node, data: [...donated.children.slice(0, index), added, ...donated.children.slice(index)] }; } else { - const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize }; - const rest: ISerializedNode = { type: 'branch', data: node.data, size: Math.max(0, (node.size ?? extent) - cellSize) }; + const added: ISerializedNode = { type: 'leaf', data: cell.toJSON(), size: cellSize, ...hidden }; + const rest: ISerializedNode = { type: 'branch', data: node.data, size: invisible ? node.size ?? extent : Math.max(0, (node.size ?? extent) - cellSize) }; replacement = { type: 'branch', data: atEnd ? [rest, added] : [added, rest], size: node.size }; } diff --git a/src/vs/workbench/browser/parts/partGrid/partGridGap.ts b/src/vs/workbench/browser/parts/partGrid/partGridGap.ts index ff526f30acf3..17c0ffe6fe1c 100644 --- a/src/vs/workbench/browser/parts/partGrid/partGridGap.ts +++ b/src/vs/workbench/browser/parts/partGrid/partGridGap.ts @@ -69,7 +69,7 @@ function getDirectChild(element: Element, className: string): HTMLElement | unde } /** Marks only the gap sashes owned by this grid, excluding grids nested inside its leaves. */ -export function updateGridGapSashes(grid: Grid, enabled: boolean): void { +export function updateGridGapSashes(grid: Grid, enabled: boolean, gap: number): void { const visit = (element: HTMLElement, node: GridNode): void => { if (!isGridBranchNode(node)) { return; @@ -98,6 +98,11 @@ export function updateGridGapSashes(grid: Grid, enabled: boo for (const sash of sashes) { sash.classList.toggle(GRID_GAP_SASH_CLASS, enabled); + if (enabled) { + sash.style.setProperty('--agents-grid-gap-offset', `${Math.floor(gap / 2) - gap / 2}px`); + } else { + sash.style.removeProperty('--agents-grid-gap-offset'); + } } for (let index = 0; index < node.children.length; index++) { const childElement = views[index]?.firstElementChild; diff --git a/src/vs/workbench/browser/parts/sessions/agentsPartCard.ts b/src/vs/workbench/browser/parts/sessions/agentsPartCard.ts index 66c4a3bc7341..2f91df00edc2 100644 --- a/src/vs/workbench/browser/parts/sessions/agentsPartCard.ts +++ b/src/vs/workbench/browser/parts/sessions/agentsPartCard.ts @@ -36,29 +36,32 @@ export const AgentsPartCard = { } as const; /** Returns the inset between the Sessions Part allocation and its visible session frames. */ -export function getSessionsPartFrameInset(container: HTMLElement): number { +export function getSessionsPartFrameInset(container: HTMLElement, spacing: number = AGENTS_FLOATING_PANEL_GAP): number { return container.classList.contains('modern-ui-tabs') && !container.classList.contains('modern-ui-compact') && !container.classList.contains('phone-layout') && !container.classList.contains('nosessionspart') - ? AgentsPartCard.BORDER_WIDTH + ? Math.min(AgentsPartCard.BORDER_WIDTH, spacing) : 0; } /** Returns the inset between the side-pane allocation and its connected editor frame. */ -export function getSidePaneFrameInset(container: HTMLElement): number { - return getSessionsPartFrameInset(container) > 0 +export function getSidePaneFrameInset(container: HTMLElement, spacing: number = AGENTS_FLOATING_PANEL_GAP): number { + const sessionInset = getSessionsPartFrameInset(container, spacing); + return container.classList.contains('modern-ui-tabs') + && !container.classList.contains('modern-ui-compact') + && !container.classList.contains('phone-layout') && container.classList.contains('dock-detail-panel') && container.classList.contains('modern-ui-connected-editor-tabs') && container.classList.contains(AGENTS_SIDE_PANE_MULTIPLE_TABS_CLASS) && !container.classList.contains('noeditorpane') - ? AgentsPartCard.BORDER_WIDTH + ? Math.min(AgentsPartCard.BORDER_WIDTH, Math.max(0, spacing - sessionInset)) : 0; } /** Returns the amount needed to align an outer side-pane frame with Sessions above a justified panel. */ -export function getSidePaneBottomFrameInset(container: HTMLElement): number { - const sessionFrameInset = getSessionsPartFrameInset(container); +export function getSidePaneBottomFrameInset(container: HTMLElement, spacing: number = AGENTS_FLOATING_PANEL_GAP): number { + const sessionFrameInset = getSessionsPartFrameInset(container, spacing); if (sessionFrameInset === 0 || container.classList.contains('noeditorpane') || container.classList.contains('nopanel') @@ -66,26 +69,26 @@ export function getSidePaneBottomFrameInset(container: HTMLElement): number { return 0; } - return Math.max(0, sessionFrameInset - getSidePaneFrameInset(container)); + return Math.max(0, sessionFrameInset - getSidePaneFrameInset(container, spacing)); } /** Returns the Sessions Part margin that preserves the visible gap beside the side pane. */ -export function getSessionsPartCardMarginRight(container: HTMLElement): number { - const sessionFrameInset = getSessionsPartFrameInset(container); +export function getSessionsPartCardMarginRight(container: HTMLElement, spacing: number = AGENTS_FLOATING_PANEL_GAP): number { + const sessionFrameInset = getSessionsPartFrameInset(container, spacing); if (sessionFrameInset === 0) { - return AgentsPartCard.MARGIN_RIGHT; + return spacing; } - return Math.max(0, AgentsPartCard.MARGIN_RIGHT - sessionFrameInset - getSidePaneFrameInset(container)); + return Math.max(0, spacing - sessionFrameInset - getSidePaneFrameInset(container, spacing)); } /** Content box of a card part, filling the grid in compact or phone layouts. */ -export function getAgentsPartCardContentSize(width: number, height: number, editorPaneVisible: boolean, sidebarVisible: boolean, phoneLayout: boolean, compact = false, editorPaneMarginRight: number = AgentsPartCard.MARGIN_RIGHT): { readonly width: number; readonly height: number } { +export function getAgentsPartCardContentSize(width: number, height: number, editorPaneVisible: boolean, sidebarVisible: boolean, phoneLayout: boolean, compact = false, editorPaneMarginRight: number = AgentsPartCard.MARGIN_RIGHT, borderWidth: number = AgentsPartCard.BORDER_WIDTH): { readonly width: number; readonly height: number } { if (phoneLayout || compact) { return { width, height }; } - const borderTotal = AgentsPartCard.BORDER_WIDTH * 2; + const borderTotal = borderWidth * 2; const marginLeft = sidebarVisible ? AgentsPartCard.MARGIN_LEFT : AgentsPartCard.MARGIN_LEFT_NO_SIDEBAR; const marginRight = editorPaneVisible ? editorPaneMarginRight diff --git a/src/vs/workbench/browser/parts/sessions/sessionGridLayout.ts b/src/vs/workbench/browser/parts/sessions/sessionGridLayout.ts index 52049cb240f1..74fd18ca9626 100644 --- a/src/vs/workbench/browser/parts/sessions/sessionGridLayout.ts +++ b/src/vs/workbench/browser/parts/sessions/sessionGridLayout.ts @@ -11,6 +11,7 @@ import { Disposable, IDisposable, MutableDisposable } from '../../../../base/com import { isSessionGridLeafData, projectSessionGrid, ISessionGridPlacement } from './sessionGridState.js'; import { Color } from '../../../../base/common/color.js'; import { getGridBottomCornerViews, getGridEdgeInsets, IGridEdgeInsets, NO_GRID_EDGE_INSETS, updateGridGapSashes } from '../partGrid/partGridGap.js'; +import { updateSashEndpoints } from '../../part.js'; export interface ISessionGridView extends IView { /** Applies the allocated geometry without laying out descendants. */ @@ -451,7 +452,7 @@ export class SessionGridLayout extends Disposable { const hasGaps = this.gap > 0 && this.leaves.size > 1 && projectedId === undefined; this.element.classList.toggle('session-grid-has-gaps', hasGaps); if (this.grid.value) { - updateGridGapSashes(this.grid.value, hasGaps); + updateGridGapSashes(this.grid.value, hasGaps, this.gap); } let bottomLeftId = projectedId; let bottomRightId = projectedId; @@ -487,6 +488,9 @@ export class SessionGridLayout extends Disposable { this.grid.value?.layout(width, height, top, left); this.gridLaidOut = true; } + if (this.grid.value) { + updateSashEndpoints(this.grid.value.element, hasGaps); + } const projected = projectedId && this.leaves.get(projectedId); const dimensions = this.phone ? this.phoneDimensions : this.dimensions; if (projected && dimensions) { diff --git a/src/vs/workbench/browser/parts/sessions/sessionsPart.ts b/src/vs/workbench/browser/parts/sessions/sessionsPart.ts index 1007140a5c86..8de3cff3267d 100644 --- a/src/vs/workbench/browser/parts/sessions/sessionsPart.ts +++ b/src/vs/workbench/browser/parts/sessions/sessionsPart.ts @@ -16,9 +16,8 @@ import { ProgressBar } from '../../../../base/browser/ui/progressbar/progressbar import { defaultProgressBarStyles } from '../../../../platform/theme/browser/defaultStyles.js'; import { IProgressIndicator } from '../../../../platform/progress/common/progress.js'; import { AbstractProgressScope, ScopedProgressIndicator } from '../../../services/progress/browser/progressIndicator.js'; -import { applyAgentsPartCardStyles, getAgentsPartCardContentSize, getSessionsPartCardMarginRight } from './agentsPartCard.js'; +import { applyAgentsPartCardStyles, getAgentsPartCardContentSize, getSessionsPartCardMarginRight, getSessionsPartFrameInset } from './agentsPartCard.js'; import { isPhoneLayout } from './mobileLayout.js'; -import { AGENTS_FLOATING_PANEL_GAP } from '../../../common/agentsSizes.js'; import { ISessionsHostLayoutService } from '../../../services/sessions/browser/sessionsHostLayoutService.js'; import { ISessionsPartContent, ISessionsPartContentHost, ISessionsPartContentLayout, SessionsPartContentRegistry } from './sessionsPartContent.js'; @@ -189,6 +188,11 @@ export class SessionsPart extends Part implements ISessionsPartContentHost { const phoneLayout = isPhoneLayout(this.layoutService); const compactLayout = this.layoutService.isModernUICompact(); + const spacing = this.layoutService.getPanelSpacing(); + const container = this.layoutService.mainContainer; + const borderWidth = !phoneLayout && container.classList.contains('modern-ui-tabs') + ? getSessionsPartFrameInset(container, spacing) + : 1; const cardSize = getAgentsPartCardContentSize( width, height, @@ -196,14 +200,15 @@ export class SessionsPart extends Part implements ISessionsPartContentHost { this.layoutService.isVisible(Parts.SIDEBAR_PART), phoneLayout, compactLayout, - getSessionsPartCardMarginRight(this.layoutService.mainContainer) + getSessionsPartCardMarginRight(container, spacing), + borderWidth ); // Size the content area with the reduced dimensions. const { contentSize } = this.layoutContents(cardSize.width, cardSize.height); // Layout the content within the content area. - const gap = phoneLayout || compactLayout ? 0 : AGENTS_FLOATING_PANEL_GAP; + const gap = phoneLayout || compactLayout ? 0 : spacing; this.layoutContent(contentSize.width, contentSize.height, top, left, { phoneLayout, gap }); // Store the full grid-allocated dimensions so that Part.relayout() works correctly. diff --git a/src/vs/workbench/browser/parts/sidebar/media/sidebarpart.css b/src/vs/workbench/browser/parts/sidebar/media/sidebarpart.css index decb51aba558..8ba4d8cd64ea 100644 --- a/src/vs/workbench/browser/parts/sidebar/media/sidebarpart.css +++ b/src/vs/workbench/browser/parts/sidebar/media/sidebarpart.css @@ -87,15 +87,15 @@ left: 5px; /* place icon in center */ } -.monaco-workbench .part.sidebar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.sidebar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before, -.monaco-workbench .part.sidebar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.sidebar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-top-color: var(--vscode-activityBarTop-activeBorder) !important; } -.monaco-workbench .part.sidebar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.monaco-workbench .part.sidebar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.sidebar > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-bottom-color: var(--vscode-activityBarTop-activeBorder) !important; } diff --git a/src/vs/workbench/browser/parts/statusbar/statusbarActions.ts b/src/vs/workbench/browser/parts/statusbar/statusbarActions.ts index 08794f0900d4..15b5fbb434b5 100644 --- a/src/vs/workbench/browser/parts/statusbar/statusbarActions.ts +++ b/src/vs/workbench/browser/parts/statusbar/statusbarActions.ts @@ -17,6 +17,7 @@ import { StatusbarViewModel } from './statusbarModel.js'; import { StatusBarFocused } from '../../../common/contextkeys.js'; import { getActiveWindow } from '../../../../base/browser/dom.js'; import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { MANAGE_EXTENSION_COMMAND_ID } from '../../../../platform/extensions/common/extensions.js'; export class ToggleStatusbarEntryVisibilityAction extends Action { @@ -56,7 +57,7 @@ export class ManageExtensionAction extends Action { } override run(): Promise { - return this.commandService.executeCommand('_extensions.manage', this.extensionId); + return this.commandService.executeCommand(MANAGE_EXTENSION_COMMAND_ID, this.extensionId); } } diff --git a/src/vs/workbench/browser/parts/titlebar/commandCenterLabel.ts b/src/vs/workbench/browser/parts/titlebar/commandCenterLabel.ts new file mode 100644 index 000000000000..f225cf949959 --- /dev/null +++ b/src/vs/workbench/browser/parts/titlebar/commandCenterLabel.ts @@ -0,0 +1,74 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IHoverDelegate } from '../../../../base/browser/ui/hover/hoverDelegate.js'; +import { renderIcon } from '../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Disposable, MutableDisposable } from '../../../../base/common/lifecycle.js'; +import { localize } from '../../../../nls.js'; +import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { IFolderLocation } from '../../../../platform/workspace/common/folderLocations.js'; + +/** + * Renders the label of the command center into an element. While the folder is at an alternate location this is + * the location's icon, the name and a branch-style group with the location description. + */ +export class CommandCenterLabel extends Disposable { + + private readonly hovers = this._register(new MutableDisposable()); + + constructor( + private readonly labelElement: HTMLElement, + private readonly hoverDelegate: IHoverDelegate, + @IHoverService private readonly hoverService: IHoverService + ) { + super(); + } + + update(text: string, location: IFolderLocation | undefined): void { + this.hovers.clear(); + const labelElement = this.labelElement; + labelElement.classList.toggle('has-folder-location', !!location); + labelElement.removeAttribute('aria-label'); + if (!location) { + labelElement.textContent = text; + return; + } + + const description = location.description; + const nameGroup = document.createElement('span'); + nameGroup.classList.add('folder-location-name-group'); + const icon = renderIcon(location.icon ?? Codicon.gitBranchCheckout); + icon.classList.add('folder-location-icon'); + icon.ariaHidden = 'true'; + const name = document.createElement('span'); + name.classList.add('folder-location-name'); + name.textContent = text; + nameGroup.append(icon, name); + const children: HTMLElement[] = [nameGroup]; + + if (description) { + const separator = document.createElement('span'); + separator.classList.add('folder-location-separator'); + separator.ariaHidden = 'true'; + separator.textContent = '·'; + const branchGroup = document.createElement('span'); + branchGroup.classList.add('folder-location-branch-group'); + this.hovers.value = this.hoverService.setupManagedHover(this.hoverDelegate, branchGroup, description); + const branchIcon = renderIcon(Codicon.gitBranchCompact); + branchIcon.classList.add('folder-location-branch-icon'); + branchIcon.ariaHidden = 'true'; + const branch = document.createElement('span'); + branch.classList.add('folder-location-branch'); + branch.textContent = description; + branchGroup.append(branchIcon, branch); + children.push(separator, branchGroup); + labelElement.setAttribute('aria-label', localize('label.withFolderLocationBranch', "{0}, branch {1}", text, description)); + } else { + labelElement.setAttribute('aria-label', text); + } + labelElement.replaceChildren(...children); + } +} diff --git a/src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css b/src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css index 68961abf8b25..0b1f7da17ae7 100644 --- a/src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css +++ b/src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css @@ -264,8 +264,10 @@ } .monaco-workbench .part.titlebar > .titlebar-container.counter-zoom .menubar .menubar-menu-button > .menubar-menu-items-holder.monaco-menu-container, -.monaco-workbench .part.titlebar > .titlebar-container.counter-zoom .monaco-toolbar .dropdown-action-container { - zoom: var(--zoom-factor); /* helps to position the menu properly when counter zooming */ +.monaco-workbench .part.titlebar > .titlebar-container.counter-zoom .shadow-root-host, +.monaco-workbench .part.titlebar > .titlebar-container.counter-zoom .context-view:not(.monaco-submenu) { + /* Counter-zoom menus hosted in the titlebar so they match window zoom. Submenus are excluded because they inherit the zoom of their parent menu */ + zoom: var(--zoom-factor); } /* Resizer */ diff --git a/src/vs/workbench/browser/parts/titlebar/menubarControl.ts b/src/vs/workbench/browser/parts/titlebar/menubarControl.ts index 16a2a7d97a30..880538be4cdc 100644 --- a/src/vs/workbench/browser/parts/titlebar/menubarControl.ts +++ b/src/vs/workbench/browser/parts/titlebar/menubarControl.ts @@ -478,7 +478,7 @@ export class CustomMenubarControl extends MenubarControl { return undefined; } - // Menu bar lives in the title bar when the activity bar is at the top or bottom + // Menu bar lives in the title bar when the activity bar is at the top, bottom or hidden if (isCompactMenuInTitlebar(this.configurationService)) { return { horizontal: HorizontalDirection.Right, vertical: VerticalDirection.Below }; } diff --git a/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts b/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts index 5c45ec9238d8..bfc24071ac0b 100644 --- a/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts +++ b/src/vs/workbench/browser/parts/titlebar/titlebarPart.ts @@ -433,7 +433,7 @@ export class BrowserTitlebarPart extends Part implements ITitlebarPart { /** * Installs, uninstalls or recreates the custom menu bar so that it matches the * current configuration. The title bar owns the menu bar when it is not compact, - * and also when it is compact but the activity bar is at the top or bottom (see + * and also when it is compact but the activity bar is at the top, bottom or hidden (see * {@link isCompactMenuInTitlebar}). The compact mode of a menu bar is fixed at * creation, so the control is recreated when it changes. */ @@ -1026,7 +1026,7 @@ export class BrowserTitlebarPart extends Part implements ITitlebarPart { if (this.customMenubar.value) { this.customMenubar.value.toggleFocus(); } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax (this.element.querySelector('[tabindex]:not([tabindex="-1"])') as HTMLElement | null)?.focus(); } } diff --git a/src/vs/workbench/browser/parts/views/treeView.ts b/src/vs/workbench/browser/parts/views/treeView.ts index 75399b805c2a..647cfb246e4e 100644 --- a/src/vs/workbench/browser/parts/views/treeView.ts +++ b/src/vs/workbench/browser/parts/views/treeView.ts @@ -1005,7 +1005,7 @@ abstract class AbstractTreeView extends Disposable implements ITreeView { getOptimalWidth(): number { if (this.tree) { const parentNode = this.tree.getHTMLElement(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const childNodes = ([] as HTMLElement[]).slice.call(parentNode.querySelectorAll('.outline-item-label > a')); return DOM.getLargestChildWidth(parentNode, childNodes); } @@ -1202,37 +1202,33 @@ class TreeDataSource implements IAsyncDataSource { return !!this.treeView.dataProvider && (element.collapsibleState !== TreeItemCollapsibleState.None); } - private batch: ITreeItem[] | undefined; - private batchPromise: Promise<(readonly ITreeItem[])[] | undefined> | undefined; + private pendingBatch: { readonly elements: ITreeItem[]; readonly children: Promise<(readonly ITreeItem[])[] | undefined> } | undefined; async getChildren(element: ITreeItem): Promise { const dataProvider = this.treeView.dataProvider; if (!dataProvider) { return []; } - if (this.batch === undefined) { - this.batch = [element]; - this.batchPromise = undefined; - } else { - this.batch.push(element); - } - const indexInBatch = this.batch.length - 1; - return new Promise((resolve, reject) => { - setTimeout(async () => { - const batch = this.batch; - this.batch = undefined; - if (!this.batchPromise) { - this.batchPromise = this.withProgress(doGetChildrenOrBatch(dataProvider, batch)); - } - try { - const result = await this.batchPromise; - resolve((result && (indexInBatch < result.length)) ? result[indexInBatch] : []); - } catch (e) { - if (!(e.message).startsWith('Bad progress location:')) { - reject(e); - } - } - }, 0); - }); + // Calls made in the same tick share one request. Each call reads its children from the batch it joined, so calls + // made once that request is sent, such as from the continuation of an earlier call, start a new batch. + if (!this.pendingBatch) { + const elements: ITreeItem[] = []; + const children = timeout(0).then(() => { + this.pendingBatch = undefined; + return this.withProgress(doGetChildrenOrBatch(dataProvider, elements)); + }); + this.pendingBatch = { elements, children }; + } + const batch = this.pendingBatch; + const index = batch.elements.push(element) - 1; + try { + const children = await batch.children; + return children?.[index] ?? []; + } catch (e) { + if ((e.message).startsWith('Bad progress location:')) { + return []; + } + throw e; + } } } diff --git a/src/vs/workbench/browser/style.ts b/src/vs/workbench/browser/style.ts index 9250ef3f2800..1fe67bb55f7c 100644 --- a/src/vs/workbench/browser/style.ts +++ b/src/vs/workbench/browser/style.ts @@ -29,7 +29,7 @@ registerThemingParticipant((theme, collector) => { const titleBackground = theme.getColor(TITLE_BAR_ACTIVE_BACKGROUND); if (titleBackground) { const metaElementId = 'monaco-workbench-meta-theme-color'; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let metaElement = mainWindow.document.getElementById(metaElementId) as HTMLMetaElement | null; if (!metaElement) { metaElement = createMetaElement(); diff --git a/src/vs/workbench/browser/workbench.contribution.ts b/src/vs/workbench/browser/workbench.contribution.ts index 75c746cf9eb6..68009b37598b 100644 --- a/src/vs/workbench/browser/workbench.contribution.ts +++ b/src/vs/workbench/browser/workbench.contribution.ts @@ -17,6 +17,7 @@ import { CustomEditorLabelService } from '../services/editor/common/customEditor import { MOUSE_BACK_FORWARD_NAVIGATION_SETTING } from '../services/history/common/history.js'; import { ActivityBarPosition, EditorActionsLocation, EditorTabsMode, LayoutSettings, ModernUIDensity, ModernUIEditorTabStyle, ModernUIFrostedGlassOpacity } from '../services/layout/browser/layoutService.js'; import { defaultWindowTitle, defaultWindowTitleSeparator } from './parts/titlebar/windowTitle.js'; +import { NEW_TAB_BUTTON_SETTING } from './parts/editor/newTabButton.js'; const registry = Registry.as(ConfigurationExtensions.Configuration); @@ -93,6 +94,13 @@ const registry = Registry.as(ConfigurationExtensions.Con 'markdownDescription': localize({ comment: ['{0}, {1} will be a setting name rendered as a link'], key: 'wrapTabs' }, "Controls whether tabs should be wrapped over multiple lines when exceeding available space or whether a scrollbar should appear instead. This value is ignored when {0} is not set to '{1}'.", '`#workbench.editor.showTabs#`', '`multiple`'), 'default': false }, + [NEW_TAB_BUTTON_SETTING]: { + 'type': 'boolean', + tags: ['experimental', 'onExp'], + 'markdownDescription': localize('newTabButton', "Controls whether the editor tab bar shows a button to open a new tab, such as a new untitled file or a chat."), + 'default': false, + experiment: { mode: 'auto' } + }, 'workbench.editor.scrollToSwitchTabs': { 'type': 'boolean', 'markdownDescription': localize({ comment: ['{0}, {1} will be a setting name rendered as a link'], key: 'scrollToSwitchTabs' }, "Controls whether scrolling over tabs will open them or not. By default tabs will only reveal upon scrolling, but not open. You can press and hold the Shift-key while scrolling to change this behavior for that duration. This value is ignored when {0} is not set to {1}.", '`#workbench.editor.showTabs#`', '`multiple`'), @@ -170,6 +178,13 @@ const registry = Registry.as(ConfigurationExtensions.Con 'default': 'text', 'markdownDescription': localize("workbench.editor.empty.hint", "Controls if the empty editor text hint should be visible in the editor.") }, + 'workbench.editor.experimental.emptyEditorHintActions': { + 'type': 'boolean', + 'default': false, + 'tags': ['experimental', 'onExp'], + 'experiment': { mode: 'auto' }, + 'markdownDescription': localize("workbench.editor.experimental.emptyEditorHintActions", "Controls whether the empty editor hint of new untitled files shows a list of actions instead of a single line. Only applies when `#workbench.editor.empty.hint#` is `text`.") + }, 'workbench.editor.languageDetection': { type: 'boolean', default: true, diff --git a/src/vs/workbench/common/agentsColors.ts b/src/vs/workbench/common/agentsColors.ts index 5c3d6ddc5b02..70870e6a45d6 100644 --- a/src/vs/workbench/common/agentsColors.ts +++ b/src/vs/workbench/common/agentsColors.ts @@ -9,11 +9,18 @@ import { localize } from '../../nls.js'; import { Color } from '../../base/common/color.js'; import { darken, lighten, registerColor, transparent } from '../../platform/theme/common/colorUtils.js'; import { contrastBorder, focusBorder } from '../../platform/theme/common/colorRegistry.js'; -import { editorWidgetBackground, editorWidgetBorder, editorBackground, toolbarHoverBackground } from '../../platform/theme/common/colors/editorColors.js'; +import { editorWidgetBackground, editorWidgetBorder, editorBackground, editorWarningForeground, toolbarHoverBackground } from '../../platform/theme/common/colors/editorColors.js'; import { foreground } from '../../platform/theme/common/colors/baseColors.js'; import { buttonBackground, buttonSecondaryBorder, inputBackground, inputBorder, inputForeground, inputPlaceholderForeground } from '../../platform/theme/common/colors/inputColors.js'; +import { listWarningForeground } from '../../platform/theme/common/colors/listColors.js'; import { ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_BADGE_FOREGROUND, SIDE_BAR_BACKGROUND, SIDE_BAR_FOREGROUND } from './theme.js'; +export const agentSessionNeedsInputForeground = registerColor( + 'agentSessionNeedsInput.foreground', + { dark: listWarningForeground, light: '#B36B00', hcDark: editorWarningForeground, hcLight: '#806600' }, + localize('agentSessionNeedsInput.foreground', 'Foreground color of agent session indicators that need input, including row markers in high contrast themes.') +); + // ============================================================================ // Shell background (used by the gradient system) // ============================================================================ @@ -60,6 +67,16 @@ export const agentsBottomPanelBorder = registerColor( localize('agentsBottomPanel.border', 'Border color of the bottom panel in the agent sessions window.') ); +export const agentsActivityBarBackground = registerColor( + 'agentsActivityBar.background', Color.transparent, + localize('agentsActivityBar.background', 'Background color of the docked Session Activity Bar in the Agents window.') +); + +export const agentsActivityBarBorder = registerColor( + 'agentsActivityBar.border', Color.transparent, + localize('agentsActivityBar.border', 'Border color of the docked Session Activity Bar in the Agents window.') +); + // ============================================================================ // Gradient background tint // ============================================================================ diff --git a/src/vs/workbench/common/chatIssue.ts b/src/vs/workbench/common/chatIssue.ts index 58c3fe52cc99..0571db1dc552 100644 --- a/src/vs/workbench/common/chatIssue.ts +++ b/src/vs/workbench/common/chatIssue.ts @@ -10,7 +10,7 @@ import type { GitHubIssue } from '../../platform/github/common/githubQueryServic /** Computes the shared issue glyph and state color used by chat/session pills. */ export function computeIssueIcon(state: GitHubIssue['state'], stateReason: GitHubIssue['stateReason']): ThemeIcon { if (state === 'open') { - return { ...Codicon.issueOpened, color: themeColorFromId('charts.green') }; + return { ...Codicon.issues, color: themeColorFromId('charts.green') }; } if (stateReason === 'not_planned' || stateReason === 'duplicate') { return { ...Codicon.issueClosed, color: themeColorFromId('descriptionForeground') }; diff --git a/src/vs/workbench/common/editor.ts b/src/vs/workbench/common/editor.ts index e9b0ce3e0b10..f69cd131404d 100644 --- a/src/vs/workbench/common/editor.ts +++ b/src/vs/workbench/common/editor.ts @@ -498,8 +498,18 @@ export interface IUntitledTextResourceEditorInput extends IBaseTextResourceEdito * - they will not ask for a file path when saving but use the associated path */ readonly resource: URI | undefined; + + /** + * Where the untitled editor is created from. Only used for telemetry. + */ + readonly untitledOrigin?: UntitledTextEditorOrigin; } +/** + * Where a new untitled text editor is created from. Only used for telemetry. + */ +export type UntitledTextEditorOrigin = 'newFileCommand' | 'tabBarDoubleClick' | 'emptyGroupDoubleClick' | 'newTabButton' | 'extensionApi' | 'chat'; + /** * A resource side by side editor input shows 2 editors side by side but * without highlighting any differences. diff --git a/src/vs/workbench/common/sessionComparisonConstants.ts b/src/vs/workbench/common/sessionComparisonConstants.ts new file mode 100644 index 000000000000..69dd82b44286 --- /dev/null +++ b/src/vs/workbench/common/sessionComparisonConstants.ts @@ -0,0 +1,6 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const OPEN_SESSION_COMPARISON_COMMAND_ID = 'sessions.openComparison'; diff --git a/src/vs/workbench/common/theme.ts b/src/vs/workbench/common/theme.ts index 9634bef5f727..25e07c279ff6 100644 --- a/src/vs/workbench/common/theme.ts +++ b/src/vs/workbench/common/theme.ts @@ -107,7 +107,7 @@ export const TAB_BORDER = registerColor('tab.border', { hcLight: contrastBorder, }, localize('tabBorder', "Border around tabs. Tabs are the containers for editors in the editor area. Multiple tabs can be opened in one editor group. There can be multiple editor groups.")); -export const TAB_DIVIDER = registerColor('tab.divider', TAB_BORDER, localize('tabDivider', "Color of dividers between editor tabs.")); +export const TAB_DIVIDER = registerColor('tab.divider', TAB_BORDER, localize('tabDivider', "Color of dividers between tabs.")); export const TAB_LAST_PINNED_BORDER = registerColor('tab.lastPinnedBorder', { dark: treeIndentGuidesStroke, diff --git a/src/vs/workbench/contrib/agentsVoice/browser/agentsVoiceWindowService.ts b/src/vs/workbench/contrib/agentsVoice/browser/agentsVoiceWindowService.ts index fe7e7968a5d2..320c0efaf7a3 100644 --- a/src/vs/workbench/contrib/agentsVoice/browser/agentsVoiceWindowService.ts +++ b/src/vs/workbench/contrib/agentsVoice/browser/agentsVoiceWindowService.ts @@ -326,7 +326,7 @@ export class AgentsVoiceWindowService extends Disposable implements IAgentsVoice } private _doResizeWindow(auxiliaryWindow: IAuxiliaryWindow): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const pill = auxiliaryWindow.container.querySelector('div') as HTMLElement | null; if (!pill) { return; } void pill.offsetWidth; diff --git a/src/vs/workbench/contrib/agentsVoice/browser/voiceModeOnboarding.ts b/src/vs/workbench/contrib/agentsVoice/browser/voiceModeOnboarding.ts index 26fb4d2715b0..bc5e7bcfa66a 100644 --- a/src/vs/workbench/contrib/agentsVoice/browser/voiceModeOnboarding.ts +++ b/src/vs/workbench/contrib/agentsVoice/browser/voiceModeOnboarding.ts @@ -1044,7 +1044,7 @@ export class VoiceModeOnboardingBanner extends ChatInputNoticeWidget implements // else, so make them real controls: reachable by Tab and operable by // Enter or Space like any other button. The renderer owns this DOM, so a // selector is the only handle on it - same as the empty-editor hint. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const link of description.querySelectorAll('a')) { link.tabIndex = 0; link.setAttribute('role', 'button'); diff --git a/src/vs/workbench/contrib/browserView/browser/browserView.contribution.ts b/src/vs/workbench/contrib/browserView/browser/browserView.contribution.ts index 95824a5478af..3943ee89d12a 100644 --- a/src/vs/workbench/contrib/browserView/browser/browserView.contribution.ts +++ b/src/vs/workbench/contrib/browserView/browser/browserView.contribution.ts @@ -7,8 +7,9 @@ import { registerSingleton, InstantiationType } from '../../../../platform/insta import { IBrowserViewWorkbenchService, IBrowserViewCDPService, IBrowserViewModel, IBrowserViewContextualFilter, IBrowserViewOpenHandler, IBrowserViewWorkbenchCreateOptions, IBrowserViewNetworkProxyProvider, IBrowserViewNetworkResolver, IBrowserViewNetworkStatus } from '../common/browserView.js'; import type { PreferredGroup } from '../../../services/editor/common/editorService.js'; import { Event } from '../../../../base/common/event.js'; +import { Schemas } from '../../../../base/common/network.js'; import { Disposable, IDisposable, IReference } from '../../../../base/common/lifecycle.js'; -import { IBrowserViewEditorOpenOptions, IBrowserViewNetwork } from '../../../../platform/browserView/common/browserView.js'; +import { IBrowserViewEditorOpenOptions, IBrowserViewNetwork, IBrowserViewNetworkFileSystem } from '../../../../platform/browserView/common/browserView.js'; import { CDPEvent, CDPRequest, CDPResponse } from '../../../../platform/browserView/common/cdp/types.js'; import { BrowserEditorInput, IBrowserEditorInputData } from '../common/browserEditorInput.js'; @@ -19,6 +20,10 @@ class WebBrowserViewWorkbenchService implements IBrowserViewWorkbenchService { return undefined; } + getNetworkFileSystem(): IBrowserViewNetworkFileSystem { + return { scheme: Schemas.vscodeRemote, caseSensitive: true }; + } + async acquireNetwork(): Promise> { return { object: undefined, dispose: () => { } }; } diff --git a/src/vs/workbench/contrib/browserView/common/browserEditorInput.ts b/src/vs/workbench/contrib/browserView/common/browserEditorInput.ts index 748d0beb443c..7e5a47be63a6 100644 --- a/src/vs/workbench/contrib/browserView/common/browserEditorInput.ts +++ b/src/vs/workbench/contrib/browserView/common/browserEditorInput.ts @@ -23,7 +23,7 @@ import { logBrowserOpen } from '../../../../platform/browserView/common/browserV import { LRUCachedFunction } from '../../../../base/common/cache.js'; import { Disposable, DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; import { Emitter, Event } from '../../../../base/common/event.js'; -import { BrowserViewStorageScope, IBrowserViewNetwork, isBrowserViewAssociatedResourceNavigation, toBrowserViewSessionOptions } from '../../../../platform/browserView/common/browserView.js'; +import { BrowserViewStorageScope, getBrowserViewPathComparer, IBrowserViewNetwork, isBrowserViewAssociatedResourceNavigation, remoteUrlToFileUrl, splitUrlSuffix, toBrowserViewSessionOptions } from '../../../../platform/browserView/common/browserView.js'; const LOADING_SPINNER_SVG = (color: string | undefined) => ` @@ -189,12 +189,26 @@ export class BrowserEditorInput extends EditorInput { return this._initialData.session; } - /** The remote network this view was opened for, or `undefined` for the local network. */ + /** The remote network this tab was requested to open on, or `undefined` for the local network. Fixed by the saved session, unlike {@link activeNetwork}. */ get network(): IBrowserViewNetwork | undefined { const session = this._initialData.session; return session?.scope === BrowserViewStorageScope.Global ? undefined : session?.network; } + /** The network the page actually runs on, which may be the local network the requested {@link network} fell back to. Falls back to the request before the model resolves. */ + get activeNetwork(): IBrowserViewNetwork | undefined { + return this.model ? this.model.network : this.network; + } + + /** Whether navigating to {@link target} keeps the page on the {@link associatedResource}, apart from its query and fragment. */ + isAssociatedResourceNavigation(target: string): boolean { + if (!this._associatedResource) { + return false; + } + const network = this.activeNetwork; + return isBrowserViewAssociatedResourceNavigation(this._associatedResource, target, network, getBrowserViewPathComparer(network && this.browserViewWorkbenchService.getNetworkFileSystem(network).caseSensitive)); + } + get url(): string | undefined { return this._model?.url || this._initialData.url; } @@ -400,9 +414,10 @@ export class BrowserEditorInput extends EditorInput { const currentUrl = this.url; let renamedUrl = currentUrl; - if (currentUrl && isBrowserViewAssociatedResourceNavigation(this._associatedResource, currentUrl)) { - const currentResource = URI.parse(currentUrl); - renamedUrl = target.with({ query: currentResource.query, fragment: currentResource.fragment }).toString(); + if (currentUrl && this.isAssociatedResourceNavigation(currentUrl)) { + // Map the target to the URL the page displays first, then carry over the page's query and fragment as written. + const { query, fragment } = splitUrlSuffix(currentUrl); + renamedUrl = splitUrlSuffix(remoteUrlToFileUrl(this.activeNetwork, target.toString())).base + query + fragment; } return { editor: { diff --git a/src/vs/workbench/contrib/browserView/common/browserView.ts b/src/vs/workbench/contrib/browserView/common/browserView.ts index 3e811926b36a..862bf15660a7 100644 --- a/src/vs/workbench/contrib/browserView/common/browserView.ts +++ b/src/vs/workbench/contrib/browserView/common/browserView.ts @@ -3,11 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { isWindows } from '../../../../base/common/platform.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { structuralEquals } from '../../../../base/common/equals.js'; import { Disposable, DisposableStore, IDisposable, IReference } from '../../../../base/common/lifecycle.js'; import { URI } from '../../../../base/common/uri.js'; +import { Schemas } from '../../../../base/common/network.js'; import { VSBuffer } from '../../../../base/common/buffer.js'; import { CDPEvent, CDPRequest, CDPResponse } from '../../../../platform/browserView/common/cdp/types.js'; import { ITunnelProxyInfo } from '../../../../platform/tunnel/common/tunnelProxy.js'; @@ -63,8 +65,10 @@ import { IBrowserViewHost, IBrowserViewAccessibilitySnapshot, IBrowserViewNetwork, + IBrowserViewNetworkFileSystem, IBrowserViewSessionOptions, getBrowserViewSessionNetwork, + BROWSER_REMOTE_FILE_SCHEMES, } from '../../../../platform/browserView/common/browserView.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { isLocalhostAuthority } from '../../../../platform/url/common/trustedDomains.js'; @@ -84,6 +88,28 @@ export const enum BrowserViewSharingState { Unavailable = 'unavailable', } +/** + * Normalizes a URL for browser navigation: adds the default scheme when missing, and for `file:` URLs + * decodes a percent-encoded Windows drive-letter colon (`file:///c%3A/x.html` becomes `file:///c:/x.html`) + * because external shells cannot resolve the encoded form. All other escapes are preserved. The drive-letter + * rewrite only applies on Windows, where `/c:/` is a drive; elsewhere it is an ordinary directory name. + */ +export function normalizeBrowserViewUrl(url: string, windows = isWindows): string { + // Prepend http:// for bare localhost authorities (e.g. "localhost:3000"). + if (/^localhost(:|\/|$)/i.test(url)) { + url = 'http://' + url; + } else if (!URL.parse(url)?.protocol) { + // No scheme — default to http://; sites typically upgrade to https://. + url = 'http://' + url; + } + + if (windows && /^file:/i.test(url)) { + url = url.replace(/^(file:\/\/[^/]*\/[a-zA-Z])%3A/i, '$1:'); + } + + return url; +} + /** Whether a browser URL belongs to the same destination host as the target URL. */ export function browserViewUrlMatches(candidateUrl: string | undefined, targetUrl: string, includeBlank = false): boolean { const target = URL.parse(targetUrl); @@ -204,6 +230,11 @@ export type IBrowserViewSessionRequest = IBrowserViewSessionOptions | { readonly network?: IBrowserViewNetwork; }; +/** Local file resources in a remote context need an isolated session on the local network. */ +export function getLocalFileBrowserViewSession(resource: URI | undefined, network: IBrowserViewNetwork | undefined): IBrowserViewSessionOptions | undefined { + return resource?.scheme === Schemas.file && network ? { scope: BrowserViewStorageScope.Ephemeral } : undefined; +} + /** View state carried in editor options and saved with browser tabs. */ export interface IBrowserEditorViewState { readonly url?: string; @@ -264,9 +295,15 @@ export interface IBrowserViewOpenHandler { shouldOpenEditor(input: BrowserEditorInput, owner: IBrowserViewOwner, editorOptions: IBrowserViewEditorOpenOptions): boolean; } +/** Resource schemes of HTML files that can be opened in the integrated browser. */ +export const BROWSER_FILE_SCHEMES: readonly string[] = [Schemas.file, ...BROWSER_REMOTE_FILE_SCHEMES]; + /** Whether browser views may use remote networks (see {@link IBrowserViewNetworkResolver}). */ export const BrowserRemoteProxyEnabledSettingId = 'workbench.browser.enableRemoteProxy'; +/** Whether the page is dimmed while something overlaps it (the screenshot swap happens regardless). */ +export const BrowserDimOverlaySettingId = 'workbench.browser.dimOnOverlay'; + /** * Resolves the opening network and optional workspace storage partition, * for windows whose views can belong to different networks (the Agents @@ -288,6 +325,15 @@ export interface IBrowserViewNetworkResolver { * Called synchronously alongside {@link resolveNetwork}. */ resolveStorageAffinity?(owner: IBrowserViewOwner): string | undefined; + /** Trusted folders on the file systems of the networks this resolver resolves views to, which tabs of any session may load files from. */ + getTrustedFileRoots?(): readonly URI[]; + /** + * Whether the file system of a network distinguishes paths by case, or `undefined` if unknown. + * Only asked for networks that are not the window's own remote. + */ + isPathCaseSensitive?(network: IBrowserViewNetwork): boolean | undefined; + /** Fires when what tabs may read from the networks' file systems may have changed: {@link getTrustedFileRoots} or {@link isPathCaseSensitive}. */ + readonly onDidChangeFileAccess?: Event; /** The status of a network this resolver resolves views to. */ getNetworkStatus(network: IBrowserViewNetwork): IBrowserViewNetworkStatus; /** Fires when the status of any network may have changed. */ @@ -341,6 +387,12 @@ export interface IBrowserViewWorkbenchService { */ resolveNetwork(owner: IBrowserViewOwner): IBrowserViewNetwork | undefined; + /** + * The file system behind a remote network: the scheme of the URIs that read it (`vscode-remote` for the window's own remote, + * otherwise the agent host scheme), and whether it distinguishes paths by case (strict if unknown). + */ + getNetworkFileSystem(network: IBrowserViewNetwork): IBrowserViewNetworkFileSystem; + /** * Hold a network's proxy until the returned reference is disposed, so * pages created on that network outside the workbench (e.g. by automation) @@ -888,15 +940,7 @@ export class BrowserViewModel extends Disposable implements IBrowserViewModel { this.logNavigationTelemetry(options?.source ?? 'urlInput', url); this._onWillNavigate.fire(url); - // Prepend http:// for bare localhost authorities (e.g. "localhost:3000"). - if (/^localhost(:|\/|$)/i.test(url)) { - url = 'http://' + url; - } else if (!URL.parse(url)?.protocol) { - // No scheme — default to http://; sites typically upgrade to https://. - url = 'http://' + url; - } - - return this.browserViewService.loadURL(this.id, url); + return this.browserViewService.loadURL(this.id, normalizeBrowserViewUrl(url)); } async goBack(): Promise { diff --git a/src/vs/workbench/contrib/browserView/electron-browser/browserView.contribution.ts b/src/vs/workbench/contrib/browserView/electron-browser/browserView.contribution.ts index 403f2e821c17..2caa7e02c335 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/browserView.contribution.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/browserView.contribution.ts @@ -14,9 +14,12 @@ import { BrowserViewUri } from '../../../../platform/browserView/common/browserV import { registerSingleton, InstantiationType } from '../../../../platform/instantiation/common/extensions.js'; import { IEditorResolverService, RegisteredEditorPriority } from '../../../services/editor/common/editorResolverService.js'; import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { Schemas } from '../../../../base/common/network.js'; +import { AGENT_HOST_SCHEME } from '../../../../platform/agentHost/common/agentHostUri.js'; +import { IWorkbenchEnvironmentService } from '../../../services/environment/common/environmentService.js'; import { generateUuid } from '../../../../base/common/uuid.js'; -import { IBrowserViewCDPService, IBrowserViewWorkbenchService } from '../common/browserView.js'; +import { BROWSER_FILE_SCHEMES, BrowserRemoteProxyEnabledSettingId, IBrowserViewCDPService, IBrowserViewWorkbenchService } from '../common/browserView.js'; import { BrowserViewWorkbenchService } from './browserViewWorkbenchService.js'; import { BrowserViewCDPService } from './browserViewCDPService.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; @@ -64,6 +67,8 @@ class BrowserEditorResolverContribution implements IWorkbenchContribution { @IEditorResolverService editorResolverService: IEditorResolverService, @IBrowserViewWorkbenchService browserViewWorkbenchService: IBrowserViewWorkbenchService, @ITelemetryService telemetryService: ITelemetryService, + @IConfigurationService configurationService: IConfigurationService, + @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, ) { editorResolverService.registerEditor( `${Schemas.vscodeBrowser}:/**`, @@ -103,41 +108,48 @@ class BrowserEditorResolverContribution implements IWorkbenchContribution { } ); - for (const extension of ['html', 'htm', 'mhtml', 'mht']) { - editorResolverService.registerEditor( - `${Schemas.file}:/**/*.${extension}`, - { - id: BrowserEditorInput.EDITOR_ID, - label: localize('browser.htmlEditorLabel', "Integrated Browser"), - priority: RegisteredEditorPriority.option - }, - { - canSupportResource: resource => resource.scheme === Schemas.file, - singlePerResource: true - }, - { - createEditorInput: ({ resource, options }) => { - logBrowserOpen(telemetryService, 'fileResource'); + // Only the Agents window has a network resolver for agent hosts. + const fileSchemes = BROWSER_FILE_SCHEMES.filter(scheme => scheme !== AGENT_HOST_SCHEME || environmentService.isSessionsWindow); + for (const scheme of fileSchemes) { + for (const extension of ['html', 'htm', 'mhtml', 'mht']) { + editorResolverService.registerEditor( + `${scheme}:/**/*.${extension}`, + { + id: BrowserEditorInput.EDITOR_ID, + label: localize('browser.htmlEditorLabel', "Integrated Browser"), + priority: RegisteredEditorPriority.option + }, + { + canSupportResource: resource => resource.scheme === scheme && ( + scheme === Schemas.file || + !!configurationService.getValue(BrowserRemoteProxyEnabledSettingId) + ), + singlePerResource: true + }, + { + createEditorInput: ({ resource, options }) => { + logBrowserOpen(telemetryService, 'fileResource'); - const viewState = reviveBrowserEditorViewState(options?.viewState); - const browserInput = browserViewWorkbenchService.getOrCreateLazy({ - id: generateUuid(), - associatedResource: resource, - ...viewState, - url: viewState.url ?? resource.toString() - }); - void browserInput.resolve(); + const viewState = reviveBrowserEditorViewState(options?.viewState); + const browserInput = browserViewWorkbenchService.getOrCreateLazy({ + id: generateUuid(), + associatedResource: resource, + ...viewState, + url: viewState.url ?? resource.toString() + }); + void browserInput.resolve(); - return { - editor: browserInput, - options: { - pinned: true, - ...options - } - }; + return { + editor: browserInput, + options: { + pinned: true, + ...options + } + }; + } } - } - ); + ); + } } } } diff --git a/src/vs/workbench/contrib/browserView/electron-browser/browserViewWorkbenchService.ts b/src/vs/workbench/contrib/browserView/electron-browser/browserViewWorkbenchService.ts index 1fe4bcbbc845..478de934627e 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/browserViewWorkbenchService.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/browserViewWorkbenchService.ts @@ -3,9 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { BrowserViewChangeEvent, BrowserViewEventData, BrowserViewCommandId, BrowserViewPresentation, BrowserViewSessionSelector, BrowserViewStorageScope, getBrowserViewSessionAffinity, getBrowserViewSessionNetwork, IBrowserViewEditorOpenOptions, IBrowserViewInfo, IBrowserViewNetwork, IBrowserViewOwner, IBrowserViewService, IBrowserViewTheme, ipcBrowserViewChannelName, reviveBrowserViewInfo, IBrowserViewSessionOptions, toBrowserViewSessionOptions } from '../../../../platform/browserView/common/browserView.js'; +import { BrowserViewChangeEvent, BrowserViewEventData, BrowserViewCommandId, BrowserViewPresentation, BrowserViewSessionSelector, BrowserViewStorageScope, getBrowserViewRemoteFile, getBrowserViewSessionAffinity, getBrowserViewSessionNetwork, IBrowserViewEditorOpenOptions, IBrowserViewInfo, IBrowserViewNetwork, IBrowserViewOwner, IBrowserViewNetworkFileSystem, IBrowserViewRemoteNetwork, IBrowserViewService, IBrowserViewTheme, ipcBrowserViewChannelName, reviveBrowserViewInfo, IBrowserViewSessionOptions, toBrowserViewSessionOptions } from '../../../../platform/browserView/common/browserView.js'; import { matchesBrowserViewSandboxSession } from '../../../../platform/browserView/common/browserViewGroup.js'; -import { BrowserRemoteProxyEnabledSettingId, BrowserViewEventEmitters, createBrowserViewEventEmitters, BrowserViewSharingState, IBrowserViewWorkbenchService, IBrowserViewModel, BrowserViewModel, IBrowserViewContextualFilter, IBrowserViewFilterContext, IBrowserViewOpenHandler, IBrowserViewWorkbenchCreateOptions, IBrowserViewNetworkProxyProvider, IBrowserViewNetworkResolver, IBrowserViewNetworkStatus, IBrowserViewSessionRequest } from '../common/browserView.js'; +import { BrowserRemoteProxyEnabledSettingId, BrowserViewEventEmitters, createBrowserViewEventEmitters, BrowserViewSharingState, getLocalFileBrowserViewSession, IBrowserViewWorkbenchService, IBrowserViewModel, BrowserViewModel, IBrowserViewContextualFilter, IBrowserViewFilterContext, IBrowserViewOpenHandler, IBrowserViewWorkbenchCreateOptions, IBrowserViewNetworkProxyProvider, IBrowserViewNetworkResolver, IBrowserViewNetworkStatus, IBrowserViewSessionRequest, normalizeBrowserViewUrl } from '../common/browserView.js'; import { IMainProcessService } from '../../../../platform/ipc/common/mainProcessService.js'; import { ProxyChannel } from '../../../../base/parts/ipc/common/ipc.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; @@ -37,12 +37,14 @@ import { ChatEditorInput } from '../../chat/browser/widgetHosts/editor/chatEdito import { IChatWidgetService } from '../../chat/browser/chat.js'; import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; import { URI } from '../../../../base/common/uri.js'; -import { isEqual } from '../../../../base/common/resources.js'; +import { extUri, isEqual } from '../../../../base/common/resources.js'; import { Schemas } from '../../../../base/common/network.js'; import { getCopilotRootPaths } from '../../../../platform/environment/common/copilotHome.js'; import { ICopilotHomeService } from '../../../services/environment/common/copilotHomeService.js'; import { localChatSessionType } from '../../chat/common/chatSessionsService.js'; import { INativeWorkbenchEnvironmentService } from '../../../services/environment/electron-browser/environmentService.js'; +import { FileSystemProviderCapabilities, IFileService } from '../../../../platform/files/common/files.js'; +import { AGENT_HOST_SCHEME } from '../../../../platform/agentHost/common/agentHostUri.js'; import { ITunnelProxyInfo } from '../../../../platform/tunnel/common/tunnelProxy.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { DeferredPromise, raceCancellationError, raceTimeout } from '../../../../base/common/async.js'; @@ -163,6 +165,7 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @INotificationService private readonly notificationService: INotificationService, @ILabelService private readonly labelService: ILabelService, + @IFileService private readonly fileService: IFileService, @IUnattendedRestartService unattendedRestartService: IUnattendedRestartService, ) { super(); @@ -185,6 +188,11 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV this._register(this.workspaceTrustManagementService.onDidChangeTrustedFolders(() => void this._updateWindowConfiguration())); this._register(this.workspaceTrustManagementService.onDidChangeTrust(() => void this._updateWindowConfiguration())); this._register(this.workspaceContextService.onDidChangeWorkspaceFolders(() => void this._updateWindowConfiguration())); + this._register(Event.any<{ readonly scheme: string }>(this.fileService.onDidChangeFileSystemProviderRegistrations, this.fileService.onDidChangeFileSystemProviderCapabilities)(e => { + if (e.scheme === Schemas.vscodeRemote) { + void this._updateWindowConfiguration(); + } + })); this._register(this.contextKeyService.onDidChangeContext(e => { if (e.affectsSome(chatEnabledKeys)) { void this._updateWindowConfiguration(); @@ -294,12 +302,16 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV } this._networkResolver = resolver; const statusListener = resolver.onDidChangeNetworkStatus(() => this._onDidChangeNetworkStatus.fire()); + const fileAccessListener = resolver.onDidChangeFileAccess?.(() => void this._updateWindowConfiguration()); this._onDidChangeNetworkStatus.fire(); + void this._updateWindowConfiguration(); return toDisposable(() => { statusListener.dispose(); + fileAccessListener?.dispose(); if (this._networkResolver === resolver) { this._networkResolver = undefined; this._onDidChangeNetworkStatus.fire(); + void this._updateWindowConfiguration(); } }); } @@ -565,7 +577,7 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV if (!this._known.has(id)) { // Capture the opening context before any asynchronous work. const owner = createOptions?.owner ?? { type: 'user' }; - const requested = createOptions?.session ?? this._resolveSessionRequest(owner, data.session); + const requested = createOptions?.session ?? this._resolveSessionRequest(owner, data.session, associatedResource); data = { ...data, session: typeof requested === 'string' ? undefined : requested }; const cancellation = new CancellationTokenSource(); const input = this.instantiationService.createInstance(BrowserEditorInput, data, async () => { @@ -585,7 +597,7 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV session, initialAudiences: createOptions?.initialAudiences, sandboxNetworkRestrictions: createOptions?.sandboxNetworkRestrictions, - initialUrl: createOptions ? createOptions.initialUrl : data.url, + initialUrl: createOptions ? createOptions.initialUrl : input.url && normalizeBrowserViewUrl(input.url), openSource: createOptions?.openSource }); } finally { @@ -622,12 +634,16 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV } /** Fill missing session options from the opening context and configured storage. */ - private _resolveSessionRequest(owner: IBrowserViewOwner, request?: IBrowserViewSessionRequest): IBrowserViewSessionOptions { + private _resolveSessionRequest(owner: IBrowserViewOwner, request?: IBrowserViewSessionRequest, associatedResource?: URI): IBrowserViewSessionOptions { if (request?.scope !== undefined) { return request; } if (!request) { const network = this.resolveNetwork(owner); + const localFileSession = getLocalFileBrowserViewSession(associatedResource, network); + if (localFileSession) { + return localFileSession; + } request = { network, affinity: network && this._networkResolver?.resolveStorageAffinity?.(owner) }; } const configured = this.configurationService.getValue('workbench.browser.dataStorage') ?? 'default'; @@ -928,25 +944,49 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV } private _updateWindowConfiguration(): Promise { + const trustedRoots = this._getTrustedFileRoots(); + const trustAllFiles = !this.workspaceTrustEnablementService.isWorkspaceTrustEnabled(); return this._browserViewService.updateWindowConfiguration(this._mainWindowId, { theme: this._getTheme(), keybindings: this._getKeybindings(), aiFeaturesDisabled: !this.contextKeyService.contextMatchesRules(ChatContextKeys.enabled), maxHistoryEntries: this.configurationService.getValue(BrowserMaxHistoryEntriesSettingId), - networkProxies: this._getNetworkProxies(), - trustedFileRoots: this._getTrustedFileRoots(), - trustAllFiles: !this.workspaceTrustEnablementService.isWorkspaceTrustEnabled(), + remoteNetworks: this._getRemoteNetworks(trustedRoots, trustAllFiles), + trustedLocalFileRoots: trustedRoots.filter(root => root.scheme === Schemas.file).map(root => root.fsPath), + trustAllLocalFiles: trustAllFiles, }); } - private _getNetworkProxies(): { [authority: string]: ITunnelProxyInfo } { - const networkProxies: { [authority: string]: ITunnelProxyInfo } = {}; + /** The remote networks with a published proxy, each with the trusted folders on its file system. */ + private _getRemoteNetworks(trustedRoots: readonly URI[], trustAllFiles: boolean): { [authority: string]: IBrowserViewRemoteNetwork } { + const remoteRoots = trustedRoots.flatMap(root => getBrowserViewRemoteFile(root) ?? []); + const remoteNetworks: { [authority: string]: IBrowserViewRemoteNetwork } = {}; for (const [authority, entry] of this._networkProxies) { - if (entry.info) { - networkProxies[authority] = entry.info; + if (!entry.info) { + continue; } + const fileSystem = this.getNetworkFileSystem({ authority }); + const { scheme } = fileSystem; + remoteNetworks[authority] = { + proxy: entry.info, + ...fileSystem, + trustedRoots: remoteRoots.filter(root => root.scheme === scheme && extUri.isEqualAuthority(root.authority, authority)).map(root => root.fileUri.path), + trustAllFiles: scheme === Schemas.vscodeRemote && trustAllFiles, + }; } - return networkProxies; + return remoteNetworks; + } + + getNetworkFileSystem(network: IBrowserViewNetwork): IBrowserViewNetworkFileSystem { + if (network.authority === this.environmentService.remoteAuthority) { + // Defaults to case-sensitive, which is the strict choice, until the remote's file system is registered. + const root = URI.from({ scheme: Schemas.vscodeRemote, authority: network.authority, path: '/' }); + return { + scheme: Schemas.vscodeRemote, + caseSensitive: !this.fileService.hasProvider(root) || this.fileService.hasCapability(root, FileSystemProviderCapabilities.PathCaseSensitive) + }; + } + return { scheme: AGENT_HOST_SCHEME, caseSensitive: this._networkResolver?.isPathCaseSensitive?.(network) ?? true }; } private _getKeybindings(): { [commandId: string]: string } { @@ -980,21 +1020,18 @@ export class BrowserViewWorkbenchService extends Disposable implements IBrowserV }; } - private _getTrustedFileRoots(): string[] { + /** The candidate trusted roots on any file system. Local ones go to the window configuration as paths; remote ones are matched to the network of their scheme and authority. */ + private _getTrustedFileRoots(): URI[] { // Trust Copilot roots so agents can create HTML files and open them in the browser. - const roots = new Set(getCopilotRootPaths(this.environmentService.userHome.fsPath, this.copilotHomeService.home.fsPath)); + const roots = getCopilotRootPaths(this.environmentService.userHome.fsPath, this.copilotHomeService.home.fsPath).map(path => URI.file(path)); if (this.workspaceTrustManagementService.isWorkspaceTrusted()) { for (const folder of this.workspaceContextService.getWorkspace().folders) { - if (folder.uri.scheme === Schemas.file) { - roots.add(folder.uri.fsPath); - } - } - } - for (const uri of this.workspaceTrustManagementService.getTrustedUris()) { - if (uri.scheme === Schemas.file) { - roots.add(uri.fsPath); + roots.push(folder.uri); } } - return [...roots]; + // The resolver applies workspace trust to each session folder itself. + roots.push(...this._networkResolver?.getTrustedFileRoots?.() ?? []); + roots.push(...this.workspaceTrustManagementService.getTrustedUris()); + return roots; } } diff --git a/src/vs/workbench/contrib/browserView/electron-browser/features/browserAutoReloadFeatures.ts b/src/vs/workbench/contrib/browserView/electron-browser/features/browserAutoReloadFeatures.ts index d124d468c8ec..fa0296039eb7 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/features/browserAutoReloadFeatures.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/features/browserAutoReloadFeatures.ts @@ -15,7 +15,7 @@ import { Schemas } from '../../../../../base/common/network.js'; import { URI } from '../../../../../base/common/uri.js'; import { DropdownWithPrimaryActionViewItem } from '../../../../../platform/actions/browser/dropdownWithPrimaryActionViewItem.js'; import { MenuItemAction } from '../../../../../platform/actions/common/actions.js'; -import { BrowserViewCommandId } from '../../../../../platform/browserView/common/browserView.js'; +import { BrowserViewCommandId, fileUrlToRemoteUri } from '../../../../../platform/browserView/common/browserView.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from '../../../../../platform/configuration/common/configurationRegistry.js'; import { FileChangeType, IFileService } from '../../../../../platform/files/common/files.js'; @@ -65,6 +65,7 @@ export class BrowserAutoReloadWatcher extends Disposable { input: BrowserEditorInput, enabled: boolean, private readonly _fileService: IFileService, + private readonly _browserViewWorkbenchService: IBrowserViewWorkbenchService, ) { super(); this._enabled = enabled; @@ -108,10 +109,12 @@ export class BrowserAutoReloadWatcher extends Disposable { return; } - const uri = getFileUri(model.url); - if (!uri) { + const fileUri = getFileUri(model.url); + if (!fileUri) { return; } + // Sessions on a remote network serve `file:` URLs from the remote's file system, which the window reads by remote or agent host URI. + const uri = model.network ? fileUrlToRemoteUri(model.network, this._browserViewWorkbenchService.getNetworkFileSystem(model.network).scheme, fileUri) : fileUri; const store = new DisposableStore(); const scheduler = store.add(new RunOnceScheduler(() => { @@ -191,7 +194,7 @@ export class BrowserAutoReloadService extends Disposable implements IBrowserAuto for (const [browserId, input] of browserViews) { if (!this._watchers.has(browserId)) { - const watcher = new BrowserAutoReloadWatcher(input, this.isEnabled(browserId), this._fileService); + const watcher = new BrowserAutoReloadWatcher(input, this.isEnabled(browserId), this._fileService, this._browserViewWorkbenchService); this._watchers.set(browserId, { input, watcher }); } } diff --git a/src/vs/workbench/contrib/browserView/electron-browser/features/browserRemoteFeatures.ts b/src/vs/workbench/contrib/browserView/electron-browser/features/browserRemoteFeatures.ts index bd61a325007f..68120e6f67f0 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/features/browserRemoteFeatures.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/features/browserRemoteFeatures.ts @@ -7,6 +7,7 @@ import { localize } from '../../../../../nls.js'; import { $ } from '../../../../../base/browser/dom.js'; import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { matchesScheme, Schemas } from '../../../../../base/common/network.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { BrowserEditor, BrowserEditorContribution, BrowserWidgetLocation, IBrowserEditorWidget } from '../browserEditor.js'; import { BrowserRemoteProxyEnabledSettingId, IBrowserViewModel, IBrowserViewWorkbenchService } from '../../common/browserView.js'; @@ -73,11 +74,7 @@ class BrowserRemoteIndicatorContribution extends BrowserEditorContribution { // The network the tab was opened for, which it may not be able to use. const network = this.editor.input?.network; if (model) { - if (model.url.startsWith('file://') && (network || model.network)) { - isVisible = true; - isWarning = true; - statusMessage = localize('browser.connectedLocally.file', "File URLs are served locally, not over the remote connection."); - } else if (model.network) { + if (model.network) { isVisible = true; const { label: host, connected } = this.browserViewWorkbenchService.getNetworkStatus(model.network); if (connected) { @@ -92,6 +89,9 @@ class BrowserRemoteIndicatorContribution extends BrowserEditorContribution { const fallback = this.getLocalFallback(model, network); isWarning = fallback.isWarning; statusMessage = fallback.message; + } else if (matchesScheme(model.url, Schemas.file) && this.browserViewWorkbenchService.resolveNetwork(model.owner)) { + isVisible = true; + statusMessage = localize('browser.localFile', "This file is local and served from this machine, not over the remote connection."); } } @@ -109,6 +109,9 @@ class BrowserRemoteIndicatorContribution extends BrowserEditorContribution { /** Why a tab opened for a remote network uses the local one. Deliberate choices are not warnings. */ private getLocalFallback(model: IBrowserViewModel, network: IBrowserViewNetwork): { message: string; isWarning: boolean } { + if (model.url.startsWith('file://')) { + return { message: localize('browser.connectedLocally.file', "File URLs are served locally, not over the remote connection."), isWarning: true }; + } const networkStatus = this.browserViewWorkbenchService.getNetworkStatus(network); if (model.storageScope === BrowserViewStorageScope.Global) { return { message: localize('browser.localFallback.global', "Connected locally. Browsers using global storage load pages from your local network, not from {0}.", networkStatus.label), isWarning: false }; diff --git a/src/vs/workbench/contrib/browserView/electron-browser/features/browserTabManagementFeatures.ts b/src/vs/workbench/contrib/browserView/electron-browser/features/browserTabManagementFeatures.ts index af0141688186..21d92911e56a 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/features/browserTabManagementFeatures.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/features/browserTabManagementFeatures.ts @@ -22,9 +22,10 @@ import { generateUuid } from '../../../../../base/common/uuid.js'; import { BrowserEditorInput } from '../../common/browserEditorInput.js'; import { logBrowserOpen } from '../../../../../platform/browserView/common/browserViewTelemetry.js'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from '../../../../../platform/contextkey/common/contextkey.js'; +import { AGENT_HOST_SCHEME } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { BrowserViewCommandId } from '../../../../../platform/browserView/common/browserView.js'; import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../common/contributions.js'; -import { IBrowserViewModel, IBrowserViewWorkbenchService } from '../../common/browserView.js'; +import { BROWSER_FILE_SCHEMES, BrowserRemoteProxyEnabledSettingId, BrowserDimOverlaySettingId, getLocalFileBrowserViewSession, IBrowserViewModel, IBrowserViewWorkbenchService } from '../../common/browserView.js'; import { BrowserNewTabPlacementSettingId } from '../browserViewWorkbenchService.js'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from '../../../../../platform/configuration/common/configurationRegistry.js'; import { workbenchConfigurationNodeBase } from '../../../../common/configuration.js'; @@ -32,8 +33,10 @@ import { isLocalhostAuthority, isAllInterfacesAuthority } from '../../../../../p import { IConfigurationService, isConfigured } from '../../../../../platform/configuration/common/configuration.js'; import { ICommandService } from '../../../../../platform/commands/common/commands.js'; import { ExternalUriOpenerPriority } from '../../../../../editor/common/languages.js'; +import { registerBuiltInExternalUriOpener } from '../../../externalUriOpener/common/configuration.js'; import { IExternalOpenerProvider, IExternalUriOpener, IExternalUriOpenerService } from '../../../externalUriOpener/common/externalUriOpenerService.js'; import { ToggleTitleBarConfigAction } from '../../../../browser/parts/titlebar/titlebarActions.js'; +import { NewTabButtonEntryAction } from '../../../../browser/parts/editor/newTabButton.js'; import { Registry } from '../../../../../platform/registry/common/platform.js'; import { match } from '../../../../../base/common/glob.js'; import { $, addDisposableListener, EventType } from '../../../../../base/browser/dom.js'; @@ -349,8 +352,19 @@ class OpenIntegratedBrowserAction extends Action2 { class OpenFileInIntegratedBrowserAction extends Action2 { constructor() { - const IS_SUPPORTED_LOCAL_BROWSER_FILE = ContextKeyExpr.and( - ResourceContextKey.Scheme.isEqualTo(Schemas.file), + const IS_SUPPORTED_BROWSER_FILE = ContextKeyExpr.and( + // Remote files can only be loaded by tabs on a remote network, which needs the remote proxy. + ContextKeyExpr.or( + ResourceContextKey.Scheme.isEqualTo(Schemas.file), + ContextKeyExpr.and( + ContextKeyExpr.has(`config.${BrowserRemoteProxyEnabledSettingId}`), + // Only the Agents window has a network resolver for agent hosts. + ContextKeyExpr.or( + ResourceContextKey.Scheme.isEqualTo(Schemas.vscodeRemote), + ContextKeyExpr.and(ResourceContextKey.Scheme.isEqualTo(AGENT_HOST_SCHEME), IsSessionsWindowContext), + ), + ), + ), ContextKeyExpr.regex(ResourceContextKey.Extension.key, /\.(?:html?|mht(?:ml)?)$/i), ); super({ @@ -359,25 +373,25 @@ class OpenFileInIntegratedBrowserAction extends Action2 { category: BrowserActionCategory, icon: Codicon.globe, f1: true, - precondition: IS_SUPPORTED_LOCAL_BROWSER_FILE, + precondition: IS_SUPPORTED_BROWSER_FILE, menu: [ { id: MenuId.ExplorerContext, group: 'navigation', order: 29, - when: IS_SUPPORTED_LOCAL_BROWSER_FILE, + when: IS_SUPPORTED_BROWSER_FILE, }, { id: MenuId.EditorTitleContext, group: '1_open', order: 5, - when: IS_SUPPORTED_LOCAL_BROWSER_FILE, + when: IS_SUPPORTED_BROWSER_FILE, }, { id: MenuId.EditorTitle, group: 'navigation', order: 99, - when: IS_SUPPORTED_LOCAL_BROWSER_FILE, + when: IS_SUPPORTED_BROWSER_FILE, }, ] }); @@ -389,7 +403,7 @@ class OpenFileInIntegratedBrowserAction extends Action2 { const browserViewService = accessor.get(IBrowserViewWorkbenchService); // Resolve the file URI from the context or the active editor - const fileUri = resource ?? EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { filterByScheme: [Schemas.file], supportSideBySide: SideBySideEditor.PRIMARY }); + const fileUri = resource ?? EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { filterByScheme: [...BROWSER_FILE_SCHEMES], supportSideBySide: SideBySideEditor.PRIMARY }); if (!fileUri) { return; } @@ -397,7 +411,8 @@ class OpenFileInIntegratedBrowserAction extends Action2 { logBrowserOpen(telemetryService, 'openFileCommand'); const browserUri = BrowserViewUri.forId(generateUuid()); - await editorService.openEditor({ resource: browserUri, options: { viewState: { url: fileUri.toString() } } }, await browserViewService.getPreferredGroup()); + const session = getLocalFileBrowserViewSession(fileUri, browserViewService.resolveNetwork({ type: 'user' })); + await editorService.openEditor({ resource: browserUri, options: { viewState: { url: fileUri.toString(), session } } }, await browserViewService.getPreferredGroup()); } } @@ -556,6 +571,21 @@ MenuRegistry.appendMenuItem(MenuId.EditorTitle, { registerAction2(QuickOpenBrowserAction); registerAction2(OpenIntegratedBrowserAction); +registerAction2(class OpenIntegratedBrowserFromNewTabButtonAction extends NewTabButtonEntryAction { + constructor() { + super({ + id: BrowserViewCommandId.Open + '.fromNewTabButton', + title: localize2('browser.openFromNewTabButton', "New Integrated Browser"), + icon: Codicon.globe, + order: 4, + }); + } + + // Opens where the browser opens new tabs, by default in the (now active) group of the button. + protected override openTab(accessor: ServicesAccessor): Promise { + return accessor.get(ICommandService).executeCommand(BrowserViewCommandId.Open); + } +}); registerAction2(OpenFileInIntegratedBrowserAction); registerAction2(OpenOrListBrowsersAction); registerAction2(NewTabAction); @@ -616,6 +646,8 @@ export class LocalhostLinkOpenerContribution extends Disposable implements IWork super(); this._register(externalUriOpenerService.registerExternalOpenerProvider(this)); + // The Simple Browser opener delegates to the Integrated Browser, so only this one is offered + this._register(registerBuiltInExternalUriOpener(LocalhostLinkOpenerContribution.OPENER_ID, localize('browser.externalUriOpener.description', "Open in the Integrated Browser."), ['simpleBrowser.open'])); } async *getOpeners(targetUri: URI): AsyncIterable { @@ -954,6 +986,15 @@ Registry.as(ConfigurationExtensions.Configuration).regis ), agentsWindow: { default: true }, }, + [BrowserDimOverlaySettingId]: { + type: 'boolean', + default: true, + experiment: { mode: 'startup' }, + markdownDescription: localize( + { comment: ['This is the description for a setting.'], key: 'browser.dimOnOverlay' }, + "Controls whether the Integrated Browser page is dimmed when a temporary element, such as a context menu or tooltip, overlaps it and causes it to pause. The page is paused regardless of this setting." + ), + }, [BrowserNewTabPlacementSettingId]: { type: 'string', enum: ['activeGroup', 'sideGroup', 'window'], diff --git a/src/vs/workbench/contrib/browserView/electron-browser/media/browser.css b/src/vs/workbench/contrib/browserView/electron-browser/media/browser.css index 4aca7a0fc028..95313e8d23a5 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/media/browser.css +++ b/src/vs/workbench/contrib/browserView/electron-browser/media/browser.css @@ -63,7 +63,7 @@ min-width: 0; background-color: var(--vscode-input-background); border: 1px solid var(--vscode-input-border); - border-radius: var(--vscode-cornerRadius-medium); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-medium)); &:has(.browser-url-display:focus) { border-color: var(--vscode-focusBorder); @@ -84,7 +84,7 @@ white-space: nowrap; background-color: var(--vscode-editorWidget-background); color: var(--vscode-disabledForeground); - border-radius: var(--vscode-cornerRadius-small) 0 0 var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)) 0 0 var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); &.connected { background-color: var(--vscode-statusBarItem-remoteBackground); diff --git a/src/vs/workbench/contrib/browserView/electron-browser/overlayManager.ts b/src/vs/workbench/contrib/browserView/electron-browser/overlayManager.ts index c10ff6a2909e..c83adbee0b15 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/overlayManager.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/overlayManager.ts @@ -117,14 +117,14 @@ export class BrowserOverlayManager extends Disposable implements IBrowserOverlay this._overlayCollections.set(overlayDefinition.className, { type: overlayDefinition.type, // We need dynamic collections for overlay detection, using getElementsByClassName is intentional here - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax collection: this.targetWindow.document.getElementsByClassName(overlayDefinition.className) }); } // Initialize live collection for shadow root hosts // We need dynamic collections for overlay detection, using getElementsByClassName is intentional here - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this._shadowRootHostCollection = this.targetWindow.document.getElementsByClassName('shadow-root-host'); // Setup structural observer to watch for element additions/removals @@ -180,7 +180,7 @@ export class BrowserOverlayManager extends Disposable implements IBrowserOverlay cache = []; for (const overlayDefinition of OVERLAY_DEFINITIONS) { // We need to query shadow roots for overlay detection, using querySelectorAll is intentional here - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const elements = shadowRoot.querySelectorAll(`.${overlayDefinition.className}`); for (const element of elements) { cache.push({ element: element as HTMLElement, type: overlayDefinition.type }); diff --git a/src/vs/workbench/contrib/browserView/electron-browser/tools/browserToolHelpers.ts b/src/vs/workbench/contrib/browserView/electron-browser/tools/browserToolHelpers.ts index 184a968bd854..b2ebe0f97b09 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/tools/browserToolHelpers.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/tools/browserToolHelpers.ts @@ -6,7 +6,7 @@ import { MarkdownString } from '../../../../../base/common/htmlContent.js'; import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; -import { IBrowserViewNetwork, isBrowserViewAssociatedResourceNavigation } from '../../../../../platform/browserView/common/browserView.js'; +import { IBrowserViewNetwork } from '../../../../../platform/browserView/common/browserView.js'; import { BrowserViewUri } from '../../../../../platform/browserView/common/browserViewUri.js'; import { IInvokeFunctionResult, IPlaywrightService } from '../../../../../platform/browserView/common/playwrightService.js'; import { IAgentNetworkFilterService } from '../../../../../platform/networkFilter/common/networkFilterService.js'; @@ -29,7 +29,12 @@ export const DEFAULT_ELEMENT_LABEL = localize('browser.element', 'element'); * Falls back to a default string when no session context is available. */ export function getSessionId(invocation: IToolInvocation): string { - return invocation.context?.sessionResource?.toString() ?? ''; + return getSessionIdForResource(invocation.context?.sessionResource); +} + +/** The session ID of a chat session resource, or a default string without one. */ +export function getSessionIdForResource(sessionResource: URI | undefined): string { + return sessionResource?.toString() ?? ''; } export interface FormatBrowserEditorLinesOptions { @@ -75,7 +80,7 @@ export function formatBrowserEditorList(editorService: IEditorService, editors: } export function getBrowserPageResourceNavigationError(editor: BrowserEditorInput | undefined, target: string): string | undefined { - if (!editor?.associatedResource || isBrowserViewAssociatedResourceNavigation(editor.associatedResource, target)) { + if (!editor?.associatedResource || editor.isAssociatedResourceNavigation(target)) { return undefined; } @@ -343,9 +348,7 @@ export function findExistingPagesByHost( if (options?.sharingState && editor.model?.sharingState !== options.sharingState) { continue; } - // A page uses the network of its model once created, which may be the local network it fell back to. - const pageNetwork = editor.model ? editor.model.network : editor.network; - if (pageNetwork?.authority !== network?.authority) { + if (editor.activeNetwork?.authority !== network?.authority) { continue; } if (browserViewUrlMatches(editor.url, url, options?.includeBlank)) { diff --git a/src/vs/workbench/contrib/browserView/electron-browser/tools/navigateBrowserTool.ts b/src/vs/workbench/contrib/browserView/electron-browser/tools/navigateBrowserTool.ts index 75483832705c..1185c9b19570 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/tools/navigateBrowserTool.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/tools/navigateBrowserTool.ts @@ -7,10 +7,11 @@ import type { CancellationToken } from '../../../../../base/common/cancellation. import { Codicon } from '../../../../../base/common/codicons.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; import { localize } from '../../../../../nls.js'; +import { IBrowserViewNetwork, remoteUrlToFileUrl } from '../../../../../platform/browserView/common/browserView.js'; import { IPlaywrightService } from '../../../../../platform/browserView/common/playwrightService.js'; import { ToolDataSource, type CountTokensCallback, type IPreparedToolInvocation, type IToolData, type IToolImpl, type IToolInvocation, type IToolInvocationPreparationContext, type IToolResult, type ToolProgress } from '../../../chat/common/tools/languageModelToolsService.js'; import { IAgentNetworkFilterService } from '../../../../../platform/networkFilter/common/networkFilterService.js'; -import { createBrowserPageLink, errorResult, getBrowserNetworkPolicyError, getBrowserPageResourceNavigationError, getExternalTunnelNetworkPolicyError, getSessionId, playwrightInvoke, remoteUrlRewriteNotice, rewriteRemoteLocalhostUrl } from './browserToolHelpers.js'; +import { createBrowserPageLink, errorResult, getBrowserNetworkPolicyError, getBrowserPageResourceNavigationError, getExternalTunnelNetworkPolicyError, getSessionId, playwrightInvoke, remoteUrlRewriteNotice, rewriteRemoteLocalhostUrl, getSessionIdForResource } from './browserToolHelpers.js'; import { BrowserChatToolReferenceName } from '../../../../../platform/browserView/common/browserChatToolReferenceNames.js'; import { IBrowserViewWorkbenchService } from '../../common/browserView.js'; import { IRemoteExplorerService } from '../../../../services/remote/common/remoteExplorerService.js'; @@ -97,7 +98,9 @@ export class NavigateBrowserTool implements IToolImpl { throw new Error(resourceNavigationError); } - const networkPolicyError = getBrowserNetworkPolicyError(params.url, this.agentNetworkFilterService); + const pageNetwork = this.getPageNetwork(params.pageId, getSessionIdForResource(context.chatSessionResource)); + // A resource of the page's remote is loaded as a `file:` URL, so the policy applies to that. + const networkPolicyError = getBrowserNetworkPolicyError(remoteUrlToFileUrl(pageNetwork, params.url), this.agentNetworkFilterService); if (networkPolicyError) { throw new Error(networkPolicyError); } @@ -131,7 +134,10 @@ export class NavigateBrowserTool implements IToolImpl { case 'forward': return playwrightInvoke(this.playwrightService, sessionId, params.pageId, (page) => page.goForward({ waitUntil: 'domcontentloaded' })); default: { - const networkPolicyError = getBrowserNetworkPolicyError(params.url!, this.agentNetworkFilterService); + const network = this.getPageNetwork(params.pageId, sessionId); + // A resource of the page's remote is loaded as a `file:` URL, so the policy, the rewrite and the navigation use that. + const url = remoteUrlToFileUrl(network, params.url!); + const networkPolicyError = getBrowserNetworkPolicyError(url, this.agentNetworkFilterService); if (networkPolicyError) { return errorResult(networkPolicyError); } @@ -144,9 +150,7 @@ export class NavigateBrowserTool implements IToolImpl { // A page on the local network in a remote workspace runs locally and cannot reach the // remote's localhost directly. Rewrite to the forwarded local address (if // any) so the page can be reached. The page keeps the network it was created with. - const model = this.browserViewService.getKnownBrowserViews().get(params.pageId)?.model; - const usesRemoteNetwork = model ? !!model.network : !!this.browserViewService.resolveNetwork({ type: 'agent', sessionId }); - const rewrite = rewriteRemoteLocalhostUrl(params.url!, this.remoteExplorerService, usesRemoteNetwork); + const rewrite = rewriteRemoteLocalhostUrl(url, this.remoteExplorerService, !!network); const tunnelPolicyError = getExternalTunnelNetworkPolicyError(rewrite, this.agentNetworkFilterService); if (tunnelPolicyError) { return errorResult(tunnelPolicyError); @@ -165,4 +169,10 @@ export class NavigateBrowserTool implements IToolImpl { const editor = this.browserViewService.getKnownBrowserViews().get(pageId); return getBrowserPageResourceNavigationError(editor, target); } + + /** The network of the page, or the one a new page of the session would use before it has a model. */ + private getPageNetwork(pageId: string, sessionId: string): IBrowserViewNetwork | undefined { + const model = this.browserViewService.getKnownBrowserViews().get(pageId)?.model; + return model ? model.network : this.browserViewService.resolveNetwork({ type: 'agent', sessionId }); + } } diff --git a/src/vs/workbench/contrib/browserView/electron-browser/webContentsViewHost.ts b/src/vs/workbench/contrib/browserView/electron-browser/webContentsViewHost.ts index 6b06a6acc5aa..b74dfd1c23ee 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/webContentsViewHost.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/webContentsViewHost.ts @@ -12,9 +12,10 @@ import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { localize } from '../../../../nls.js'; import { IBrowserViewKeyDownEvent } from '../../../../platform/browserView/common/browserView.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; import { ILogService } from '../../../../platform/log/common/log.js'; -import { IBrowserViewModel } from '../common/browserView.js'; +import { BrowserDimOverlaySettingId, IBrowserViewModel } from '../common/browserView.js'; import { BrowserOverlayManager, BrowserOverlayType } from './overlayManager.js'; const originalHtmlElementFocus = HTMLElement.prototype.focus; @@ -31,6 +32,7 @@ export class WebContentsViewHost extends Disposable { private _model: IBrowserViewModel | undefined; private _editorVisible = false; private _overlayObscured = false; + private _notificationObscured = false; private _hiddenAsAnchor = false; private readonly _placeholderScreenshot = $('.browser-placeholder-screenshot'); @@ -49,9 +51,16 @@ export class WebContentsViewHost extends Disposable { private readonly ensureBrowserFocus: () => void, @ILogService private readonly logService: ILogService, @IKeybindingService private readonly keybindingService: IKeybindingService, + @IConfigurationService private readonly configurationService: IConfigurationService, ) { super(); + this._register(this.configurationService.onDidChangeConfiguration(e => { + if (e.affectsConfiguration(BrowserDimOverlaySettingId)) { + this._refresh(); + } + })); + this._overlayManager = this._register(new BrowserOverlayManager(targetWindow)); const message = $('.browser-overlay-paused-message'); const heading = $('.browser-overlay-paused-heading'); @@ -183,7 +192,9 @@ export class WebContentsViewHost extends Disposable { const placeholderActive = !!this._model?.url && !this._model.error; this._placeholderScreenshot.style.display = placeholderActive ? '' : 'none'; const pauseActive = !!this._model?.url && this._editorVisible && this._overlayObscured; - this._overlayPauseElement.classList.toggle('visible', pauseActive); + // Notifications always dim the page and show the banner; the setting covers other overlays. + const dim = pauseActive && (this._notificationObscured || this.configurationService.getValue(BrowserDimOverlaySettingId) !== false); + this._overlayPauseElement.classList.toggle('visible', dim); if (!this._model) { return; } @@ -220,9 +231,11 @@ export class WebContentsViewHost extends Disposable { } const overlays = this._overlayManager.getOverlappingOverlays(this._container); const obscured = overlays.length > 0; - this._overlayPauseElement.classList.toggle('show-message', overlays.some(overlay => overlay.type === BrowserOverlayType.Notification)); - if (obscured !== this._overlayObscured) { + const notificationObscured = overlays.some(overlay => overlay.type === BrowserOverlayType.Notification); + this._overlayPauseElement.classList.toggle('show-message', notificationObscured); + if (obscured !== this._overlayObscured || notificationObscured !== this._notificationObscured) { this._overlayObscured = obscured; + this._notificationObscured = notificationObscured; this._refresh(); } } @@ -235,7 +248,7 @@ export class WebContentsViewHost extends Disposable { return; } try { - const screenshot = await model.captureScreenshot({ quality: 80 }); + const screenshot = await model.captureScreenshot({ quality: 80, includeDevTools: true }); if (this._model === model && sequence === this._screenshotSequence && !model.error) { this._setBackgroundImage(screenshot); } diff --git a/src/vs/workbench/contrib/browserView/test/common/browserView.test.ts b/src/vs/workbench/contrib/browserView/test/common/browserView.test.ts index d1961fbafb4c..20e641f1401b 100644 --- a/src/vs/workbench/contrib/browserView/test/common/browserView.test.ts +++ b/src/vs/workbench/contrib/browserView/test/common/browserView.test.ts @@ -15,7 +15,7 @@ import { IAgentNetworkFilterService } from '../../../../../platform/networkFilte import { IStorageService } from '../../../../../platform/storage/common/storage.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { IBrowserZoomService } from '../../common/browserZoomService.js'; -import { BrowserViewModel, BrowserViewSharingState, createBrowserViewEventEmitters, IBrowserViewWorkbenchService } from '../../common/browserView.js'; +import { BrowserViewModel, BrowserViewSharingState, createBrowserViewEventEmitters, IBrowserViewWorkbenchService, normalizeBrowserViewUrl } from '../../common/browserView.js'; suite('BrowserViewModel', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -135,3 +135,43 @@ function createInitialState(storageScope: BrowserViewStorageScope, audiences: IB audiences, }; } + +suite('normalizeBrowserViewUrl', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('decodes only the drive-letter colon in file URLs', () => { + assert.deepStrictEqual( + [ + 'file:///c%3A/docs/x.html', + 'file:///C%3a/docs/x.html', + 'file:///c%3A/docs/a%20b%231.html?q=%3A#h%3A', + 'file:///c%3A/docs/report%2520final.html', + 'file:///c%3A/docs/dir%3Afile.html', + 'file:///c:/docs/x.html', + 'file:///home/u/c%3A/x.html', + 'file:///home/u/x.html', + ].map(url => normalizeBrowserViewUrl(url, true)), + [ + 'file:///c:/docs/x.html', + 'file:///C:/docs/x.html', + 'file:///c:/docs/a%20b%231.html?q=%3A#h%3A', + 'file:///c:/docs/report%2520final.html', + 'file:///c:/docs/dir%3Afile.html', + 'file:///c:/docs/x.html', + 'file:///home/u/c%3A/x.html', + 'file:///home/u/x.html', + ]); + }); + + test('leaves file URLs unchanged outside Windows', () => { + assert.deepStrictEqual( + ['file:///c%3A/docs/x.html', 'file:///c:/docs/x.html'].map(url => normalizeBrowserViewUrl(url, false)), + ['file:///c%3A/docs/x.html', 'file:///c:/docs/x.html']); + }); + + test('keeps defaulting the scheme', () => { + assert.deepStrictEqual( + ['localhost:3000', 'example.com', 'https://example.com'].map(url => normalizeBrowserViewUrl(url)), + ['http://localhost:3000', 'http://example.com', 'https://example.com']); + }); +}); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/browserEditorInput.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/browserEditorInput.test.ts index 58ac73612120..97807f3ecac9 100644 --- a/src/vs/workbench/contrib/browserView/test/electron-browser/browserEditorInput.test.ts +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/browserEditorInput.test.ts @@ -11,7 +11,8 @@ import { hasKey } from '../../../../../base/common/types.js'; import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { mock } from '../../../../../base/test/common/mock.js'; -import { BrowserViewStorageScope, IBrowserViewEditorOpenOptions, IBrowserViewNavigationEvent, IBrowserViewNetwork } from '../../../../../platform/browserView/common/browserView.js'; +import { BrowserViewStorageScope, IBrowserViewEditorOpenOptions, IBrowserViewNavigationEvent, IBrowserViewNetwork, IBrowserViewNetworkFileSystem } from '../../../../../platform/browserView/common/browserView.js'; +import { toAgentHostUri } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { BrowserViewUri } from '../../../../../platform/browserView/common/browserViewUri.js'; import { IContextKeyService, RawContextKey } from '../../../../../platform/contextkey/common/contextkey.js'; import { BrowserEditorInput, BrowserEditorSerializer, IBrowserEditorInputData } from '../../common/browserEditorInput.js'; @@ -38,6 +39,10 @@ class TestBrowserViewWorkbenchService implements IBrowserViewWorkbenchService { return undefined; } + getNetworkFileSystem(): IBrowserViewNetworkFileSystem { + return { scheme: 'vscode-remote', caseSensitive: true }; + } + async acquireNetwork(): Promise> { return { object: undefined, dispose: () => { } }; } @@ -476,4 +481,32 @@ suite('BrowserEditorInput', () => { } }); }); + + test('follows renames of agent host files and uses the network of the resolved model', async () => { + const associatedResource = toAgentHostUri(URI.file('/repo/index.html'), 'host'); + const target = toAgentHostUri(URI.file('/repo/renamed.html'), 'host'); + const session = { scope: BrowserViewStorageScope.Workspace, network: { authority: 'host' } } as const; + const input = createInput({ id: 'agent-host', associatedResource, session, url: 'file:///repo/index.html?view=preview#content' }); + const before = await input.rename(1, target); + input.model = new class extends mock() { + override readonly network = undefined; + override readonly onDidChangeFavicon = Event.None; + override readonly onDidChangeLoadingState = Event.None; + override readonly onDidChangeTitle = Event.None; + override readonly onDidNavigate = Event.None; + override readonly onWillDispose = Event.None; + override readonly onDidClose = Event.None; + override dispose() { } + }; + + assert.deepStrictEqual({ + renamed: (before?.editor as IUntypedEditorInput).options?.viewState, + localModelNetwork: input.activeNetwork, + localModelNavigation: getBrowserPageResourceNavigationError(input, 'file:///repo/index.html?x=1'), + }, { + renamed: { url: 'file:///repo/renamed.html?view=preview#content', title: undefined, favicon: undefined, session }, + localModelNetwork: undefined, + localModelNavigation: 'This browser page is associated with a resource and cannot be navigated to a different resource. Only query and fragment changes are allowed. Use a different page or open a new one with the open_browser_page tool.', + }); + }); }); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/browserViewWorkbenchService.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/browserViewWorkbenchService.test.ts index 91d1a6555d8f..6b66487ae5a4 100644 --- a/src/vs/workbench/contrib/browserView/test/electron-browser/browserViewWorkbenchService.test.ts +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/browserViewWorkbenchService.test.ts @@ -8,27 +8,35 @@ import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; +import { BrowserViewUri } from '../../../../../platform/browserView/common/browserViewUri.js'; +import { Schemas } from '../../../../../base/common/network.js'; import { ProxyChannel } from '../../../../../base/parts/ipc/common/ipc.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { BrowserViewEvent, BrowserViewPresentation, BrowserViewStorageScope, browserZoomDefaultIndex, IBrowserViewCreateOptions, IBrowserViewInfo, IBrowserViewNetwork, IBrowserViewWindowConfiguration, serializeBrowserViewInfo } from '../../../../../platform/browserView/common/browserView.js'; +import { BrowserViewCommandId, BrowserViewEvent, BrowserViewPresentation, BrowserViewStorageScope, browserZoomDefaultIndex, IBrowserViewCreateOptions, IBrowserViewInfo, IBrowserViewNetwork, IBrowserViewWindowConfiguration, serializeBrowserViewInfo } from '../../../../../platform/browserView/common/browserView.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ITunnelProxyInfo } from '../../../../../platform/tunnel/common/tunnelProxy.js'; import { IMainProcessService } from '../../../../../platform/ipc/common/mainProcessService.js'; import { IAgentNetworkFilterService } from '../../../../../platform/networkFilter/common/networkFilterService.js'; +import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; import { IWorkspaceTrustEnablementService, IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; import { INativeWorkbenchEnvironmentService } from '../../../../services/environment/electron-browser/environmentService.js'; import { ICopilotHomeService } from '../../../../../platform/environment/common/copilotHome.js'; import { TestCopilotHomeService } from '../../../../../platform/environment/test/common/testCopilotHomeService.js'; +import { EditorInput } from '../../../../common/editor/editorInput.js'; +import { IResourceEditorInput } from '../../../../../platform/editor/common/editor.js'; +import { reviveBrowserEditorViewState } from '../../common/browserEditorInput.js'; import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; import { IBrowserViewNetworkResolver, IBrowserViewWorkbenchService } from '../../common/browserView.js'; import { IBrowserZoomService } from '../../common/browserZoomService.js'; import { BrowserViewWorkbenchService } from '../../electron-browser/browserViewWorkbenchService.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { IEditorGroup, IEditorGroupsService, IEditorPart } from '../../../../services/editor/common/editorGroupsService.js'; -import { ACTIVE_GROUP, PreferredGroup, SIDE_GROUP } from '../../../../services/editor/common/editorService.js'; +import { ACTIVE_GROUP, IEditorService, PreferredGroup, SIDE_GROUP } from '../../../../services/editor/common/editorService.js'; import { IUnattendedRestartService } from '../../../../services/lifecycle/common/unattendedRestart.js'; +import '../../electron-browser/features/browserTabManagementFeatures.js'; suite('BrowserViewWorkbenchService', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -41,6 +49,10 @@ suite('BrowserViewWorkbenchService', () => { }; } + function proxiesOf(config: IBrowserViewWindowConfiguration | undefined) { + return Object.fromEntries(Object.entries(config?.remoteNetworks ?? {}).map(([authority, network]) => [authority, network.proxy])); + } + function createService(remoteAuthority?: string, editorGroupsService?: IEditorGroupsService) { const disposables = store.add(new DisposableStore()); const events = store.add(new Emitter()); @@ -105,7 +117,7 @@ suite('BrowserViewWorkbenchService', () => { instantiationService.stub(IBrowserViewWorkbenchService, service); const workspaceTrustService = instantiationService.get(IWorkspaceTrustManagementService); const unattendedRestartService = instantiationService.get(IUnattendedRestartService); - return { service, events, creationOptions, loadedUrls, windowConfigurations, configurationService, workspaceTrustService, publishing, unattendedRestartService }; + return { service, events, creationOptions, loadedUrls, windowConfigurations, configurationService, workspaceTrustService, publishing, unattendedRestartService, instantiationService }; } function info(id: string, presentation = BrowserViewPresentation.Listed): IBrowserViewInfo { @@ -231,6 +243,40 @@ suite('BrowserViewWorkbenchService', () => { assert.deepStrictEqual({ preferred: typeof preferred === 'object' ? (preferred as IEditorGroup).id : preferred, addedBeside }, { preferred: 3, addedBeside: [2] }); }); + for (const { name, savedUrl, requestedUrl } of [ + { name: 'uses the requested URL', savedUrl: 'http://localhost:3000/previous', requestedUrl: 'http://localhost:3000/requested' }, + { name: 'normalizes the requested URL', savedUrl: 'http://localhost:3000/requested', requestedUrl: 'localhost:3000/requested' }, + ]) { + test(`${name} when the open command reuses an unresolved restored tab`, async () => { + const { service, events, creationOptions, instantiationService } = createService(); + events.fire([{ type: 'snapshot', windowId: 1, views: [] }, []]); + const input = store.add(service.getOrCreateLazy({ + id: 'restored', url: savedUrl, + })); + let openedExisting = false; + instantiationService.stub(IEditorService, 'openEditor', async (editor: EditorInput) => { + openedExisting = editor === input; + await input.resolve(); + return undefined; + }); + + await instantiationService.invokeFunction(CommandsRegistry.getCommand(BrowserViewCommandId.Open)!.handler, { + url: requestedUrl, + reuseUrlFilter: 'http://localhost:3000/**', + }); + + assert.deepStrictEqual({ + openedExisting, + createdUrls: creationOptions.map(options => options.initialUrl), + url: input.model?.url, + }, { + openedExisting: true, + createdUrls: ['http://localhost:3000/requested'], + url: 'http://localhost:3000/requested', + }); + }); + } + test('preserves restored metadata on early disposal without overriding fresh native state', async () => { const { service, events } = createService(); const results = []; @@ -381,7 +427,7 @@ suite('BrowserViewWorkbenchService', () => { const local = store.add(service.getOrCreateLazy({ id: 'local', session: {} })); const [remoteModel, , fallbackModel] = await Promise.all([remote.resolve(), workspaceless.resolve(), fallback.resolve(), local.resolve()]); const automationHold = await service.acquireNetwork({ authority: 'legacy' }); - const networkProxies = windowConfigurations.at(-1)?.networkProxies; + const networkProxies = proxiesOf(windowConfigurations.at(-1)); remote.dispose(); workspaceless.dispose(); automationHold.dispose(); @@ -590,6 +636,49 @@ suite('BrowserViewWorkbenchService', () => { }); }); + test('opens local files of a remote workspace in an isolated session on the local network', async () => { + const { service, events, creationOptions } = createService('ssh-remote+host'); + events.fire([{ type: 'snapshot', windowId: 1, views: [] }, []]); + registerProxyProvider(service, []); + + const local = store.add(service.getOrCreateLazy({ id: 'local', associatedResource: URI.file('/Users/me/index.html') })); + const remote = store.add(service.getOrCreateLazy({ id: 'remote', associatedResource: URI.from({ scheme: Schemas.vscodeRemote, authority: 'ssh-remote+host', path: '/home/index.html' }) })); + await local.resolve(); + await remote.resolve(); + + assert.deepStrictEqual(creationOptions.map(options => options.session), [ + { scope: BrowserViewStorageScope.Ephemeral }, + { scope: BrowserViewStorageScope.Workspace, network: { authority: 'ssh-remote+host' } }, + ]); + }); + + test('opens local files through the open file action on the local network without an associated resource and restores their session', async () => { + const { service, events, creationOptions, instantiationService } = createService('ssh-remote+host'); + events.fire([{ type: 'snapshot', windowId: 1, views: [] }, []]); + registerProxyProvider(service, []); + instantiationService.stub(IEditorService, 'openEditor', async (editor: IResourceEditorInput) => { + const id = BrowserViewUri.getId(editor.resource); + assert.ok(id); + const input = store.add(service.getOrCreateLazy({ id, ...reviveBrowserEditorViewState(editor.options?.viewState) })); + await input.resolve(); + const restored = store.add(service.getOrCreateLazy({ ...input.serialize(), id: 'restored' })); + await restored.resolve(); + return undefined; + }); + + await instantiationService.invokeFunction(CommandsRegistry.getCommand(BrowserViewCommandId.OpenFile)!.handler, URI.file('/Users/me/index.html')); + + assert.deepStrictEqual(creationOptions.map(options => ({ + session: options.session, + associatedResource: options.associatedResource, + initialUrl: options.initialUrl, + })), Array(2).fill({ + session: { scope: BrowserViewStorageScope.Ephemeral }, + associatedResource: undefined, + initialUrl: 'file:///Users/me/index.html', + })); + }); + function proxy(port: number): ITunnelProxyInfo { return { url: `https://127.0.0.1:${port}`, host: '127.0.0.1', port, credentials: { username: 'u', password: `p${port}` }, certFingerprint: `f${port}` }; } @@ -652,7 +741,7 @@ suite('BrowserViewWorkbenchService', () => { void acquired.complete(proxy(1)); } await model; - results[phase] = { createdBeforeReplacement, networkProxies: windowConfigurations.at(-1)?.networkProxies }; + results[phase] = { createdBeforeReplacement, networkProxies: proxiesOf(windowConfigurations.at(-1)) }; } const expected = { createdBeforeReplacement: 0, networkProxies: { 'ssh-remote+host': proxy(2) } }; @@ -682,7 +771,7 @@ suite('BrowserViewWorkbenchService', () => { store.add(service.registerNetworkProxyProvider({ acquire: async () => proxy(2), release: () => { } })); await timeout(0); - assert.deepStrictEqual(windowConfigurations.at(-1)?.networkProxies, { 'ssh-remote+host': proxy(2) }); + assert.deepStrictEqual(proxiesOf(windowConfigurations.at(-1)), { 'ssh-remote+host': proxy(2) }); }); test('releases a proxy whose last view closed while it was published', async () => { @@ -701,9 +790,28 @@ suite('BrowserViewWorkbenchService', () => { published.complete(); await assert.rejects(model); - assert.deepStrictEqual({ calls, networkProxies: windowConfigurations.at(-1)?.networkProxies }, { + assert.deepStrictEqual({ calls, networkProxies: proxiesOf(windowConfigurations.at(-1)) }, { calls: ['acquire ssh-remote+host', 'release ssh-remote+host'], networkProxies: {}, }); }); + + test('publishes the trusted roots of each remote with its network', async () => { + const { service, events, windowConfigurations, instantiationService } = createService('ssh-remote+host'); + instantiationService.stub(IWorkspaceTrustManagementService, 'getTrustedUris', () => [ + URI.from({ scheme: 'vscode-remote', authority: 'ssh-remote+host', path: '/repo' }), + URI.file('/local'), + ]); + events.fire([{ type: 'snapshot', windowId: 1, views: [] }, []]); + store.add(service.registerNetworkProxyProvider({ acquire: async () => proxy(1), release: () => { } })); + const input = store.add(service.getOrCreateLazy({ id: 'page', url: 'http://page/' })); + await input.resolve(); + + const { remoteNetworks, trustedLocalFileRoots, trustAllLocalFiles } = windowConfigurations.at(-1)!; + assert.deepStrictEqual({ remoteNetworks, trustedLocalFileRoots, trustAllLocalFiles }, { + remoteNetworks: { 'ssh-remote+host': { proxy: proxy(1), scheme: 'vscode-remote', trustedRoots: ['/repo'], trustAllFiles: true, caseSensitive: true } }, + trustedLocalFileRoots: [URI.file('/home/test/.copilot').fsPath, instantiationService.get(IWorkspaceContextService).getWorkspace().folders[0].uri.fsPath, URI.file('/local').fsPath], + trustAllLocalFiles: true, + }); + }); }); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserAutoReloadFeatures.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserAutoReloadFeatures.test.ts index f49983c1d2d8..c3fdd363d237 100644 --- a/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserAutoReloadFeatures.test.ts +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserAutoReloadFeatures.test.ts @@ -7,16 +7,22 @@ import assert from 'assert'; import { timeout } from '../../../../../../base/common/async.js'; import { Emitter } from '../../../../../../base/common/event.js'; import { Disposable } from '../../../../../../base/common/lifecycle.js'; +import { toAgentHostUri } from '../../../../../../platform/agentHost/common/agentHostUri.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { IBrowserViewNavigationEvent, IBrowserViewVisibilityEvent } from '../../../../../../platform/browserView/common/browserView.js'; +import { IBrowserViewNavigationEvent, IBrowserViewNetwork, IBrowserViewVisibilityEvent } from '../../../../../../platform/browserView/common/browserView.js'; import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { FileChangesEvent, FileChangeType, IFileService, IFileSystemWatcher } from '../../../../../../platform/files/common/files.js'; import { BrowserEditorInput } from '../../../common/browserEditorInput.js'; import { IBrowserViewModel, IBrowserViewWorkbenchService } from '../../../common/browserView.js'; import { BrowserAutoReloadService, BrowserAutoReloadWatcher } from '../../../electron-browser/features/browserAutoReloadFeatures.js'; +function networkFiles(remoteAuthority?: string) { + return upcastPartial({ getNetworkFileSystem: (network: IBrowserViewNetwork) => ({ scheme: network.authority === remoteAuthority ? 'vscode-remote' : 'vscode-agent-host', caseSensitive: true }) }); +} + suite('Browser Auto Reload Features', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); @@ -25,8 +31,8 @@ suite('Browser Auto Reload Features', () => { const fileService = new TestFileService(); const emptyModel = disposables.add(new TestBrowserViewModel('')); const httpModel = disposables.add(new TestBrowserViewModel('https://example.com')); - disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(emptyModel).input, true, fileService.service)); - disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(httpModel).input, true, fileService.service)); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(emptyModel).input, true, fileService.service, networkFiles())); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(httpModel).input, true, fileService.service, networkFiles())); assert.deepStrictEqual(fileService.snapshot(), { resources: [], @@ -42,10 +48,23 @@ suite('Browser Auto Reload Features', () => { }); }); + test('watches remote files by the window remote authority or agent host', () => { + const fileService = new TestFileService(); + const remoteModel = disposables.add(new TestBrowserViewModel('file:///workspace/a.html', { authority: 'ssh-remote+host' })); + const agentHostModel = disposables.add(new TestBrowserViewModel('file:///workspace/b.html', { authority: 'other' })); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(remoteModel).input, true, fileService.service, networkFiles('ssh-remote+host'))); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(agentHostModel).input, true, fileService.service, networkFiles('ssh-remote+host'))); + + assert.deepStrictEqual(fileService.snapshot().resources, [ + URI.from({ scheme: 'vscode-remote', authority: 'ssh-remote+host', path: '/workspace/a.html' }).toString(), + toAgentHostUri(URI.file('/workspace/b.html'), 'other').toString(), + ]); + }); + test('watches file URLs and replaces the watcher on navigation', () => { const fileService = new TestFileService(); const model = disposables.add(new TestBrowserViewModel('file:///workspace/index.html?theme=dark#section')); - const watcher = disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service)); + const watcher = disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service, networkFiles())); assert.deepStrictEqual(fileService.snapshot(), { resources: ['file:///workspace/index.html'], @@ -79,7 +98,7 @@ suite('Browser Auto Reload Features', () => { return runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 10_000 }, async () => { const fileService = new TestFileService(); const model = disposables.add(new TestBrowserViewModel('file:///workspace/index.html')); - disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service)); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service, networkFiles())); fileService.fire(URI.file('/workspace/unrelated.html')); fileService.fire(URI.file('/workspace/index.html'), FileChangeType.DELETED); @@ -97,7 +116,7 @@ suite('Browser Auto Reload Features', () => { return runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 10_000 }, async () => { const fileService = new TestFileService(); const model = disposables.add(new TestBrowserViewModel('file:///workspace/index.html')); - disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service)); + disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service, networkFiles())); model.setVisible(false); fileService.fire(URI.file('/workspace/index.html')); @@ -120,7 +139,7 @@ suite('Browser Auto Reload Features', () => { return runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 10_000 }, async () => { const fileService = new TestFileService(); const model = disposables.add(new TestBrowserViewModel('file:///workspace/index.html')); - const watcher = disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service)); + const watcher = disposables.add(new BrowserAutoReloadWatcher(new TestBrowserEditorInput(model).input, true, fileService.service, networkFiles())); model.setVisible(false); fileService.fire(URI.file('/workspace/index.html')); @@ -206,12 +225,13 @@ class TestBrowserViewModel extends Disposable { readonly model: IBrowserViewModel; - constructor(url: string) { + constructor(url: string, network?: { authority: string }) { super(); this._url = url; const thisTest = this; this.model = { id: url, + network: network as IBrowserViewModel['network'], get url() { return thisTest._url; }, get visible() { return thisTest._visible; }, onDidNavigate: this._onDidNavigate.event, diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserEditorChatFeatures.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserEditorChatFeatures.test.ts new file mode 100644 index 000000000000..69f8abb32aa6 --- /dev/null +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/features/browserEditorChatFeatures.test.ts @@ -0,0 +1,127 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../../base/browser/window.js'; +import { decodeBase64, VSBuffer } from '../../../../../../base/common/buffer.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IBrowserViewCaptureScreenshotOptions, IBrowserViewRect } from '../../../../../../platform/browserView/common/browserView.js'; +import { IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; +import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; +import { IChatWidget, IChatWidgetService } from '../../../../chat/browser/chat.js'; +import { IChatPetService } from '../../../../chat/browser/chatPetService.js'; +import { IChatRequestVariableEntry } from '../../../../chat/common/attachments/chatVariableEntries.js'; +import { IChatService } from '../../../../chat/common/chatService/chatService.js'; +import { IScreenshotToolService } from '../../../../screenshotTool/browser/screenshotTool.js'; +import { createTestScreenshotToolService } from '../../../../screenshotTool/test/browser/screenshotToolTestUtils.js'; +import { IBrowserViewModel } from '../../../common/browserView.js'; +import { BrowserEditor } from '../../../electron-browser/browserEditor.js'; +import { BrowserEditorChatIntegration } from '../../../electron-browser/features/browserEditorChatFeatures.js'; + +suite('Browser screenshot actions', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createPng(width: number, height: number): VSBuffer { + const canvas = $('canvas'); + canvas.width = width; + canvas.height = height; + return decodeBase64(canvas.toDataURL('image/png').split(',')[1]); + } + + function create(url = 'http://localhost:3000/') { + const instantiationService = workbenchInstantiationService(undefined, store); + const { service, telemetry } = createTestScreenshotToolService(store); + instantiationService.stub(IScreenshotToolService, service); + const attached: IChatRequestVariableEntry[] = []; + const widget = upcastPartial({ viewModel: upcastPartial>({}), attachmentModel: upcastPartial({ addContext: (...entries: IChatRequestVariableEntry[]) => { attached.push(...entries); } }) }); + instantiationService.stub(IChatWidgetService, upcastPartial({ revealWidget: async () => widget })); + instantiationService.stub(IChatService, upcastPartial({ onDidSubmitRequest: Event.None })); + instantiationService.stub(IChatPetService, upcastPartial({})); + const warnings: string[] = []; + instantiationService.stub(IDialogService, upcastPartial({ + confirm: async options => { + warnings.push(options.message); + return { confirmed: false }; + }, + })); + const pageCaptures: IBrowserViewCaptureScreenshotOptions[] = []; + const areaSelections: (boolean | undefined)[] = []; + const onDidPickArea = store.add(new Emitter()); + const page = { pickedArea: undefined as IBrowserViewRect | undefined }; + const model = upcastPartial({ + url, + isAreaSelectionActive: false, + onDidPickArea: onDidPickArea.event, + // The page's own area picker reports the area that the user dragged, or nothing when cancelled. + toggleAreaSelection: async enabled => { + areaSelections.push(enabled); + onDidPickArea.fire(page.pickedArea); + }, + captureScreenshot: async options => { + pageCaptures.push({ ...options }); + return createPng(4, 2); + }, + }); + const editor = upcastPartial({ onDidChangeModel: Event.None, model, window: mainWindow, ensureBrowserFocus: () => { } }); + const feature = store.add(instantiationService.createInstance(BrowserEditorChatIntegration, editor)); + return { feature, service, telemetry, attached, warnings, pageCaptures, areaSelections, page }; + } + + test('each action captures the page itself and attaches the capture right away, where it can be marked up', async () => { + const { feature, service, telemetry, attached, pageCaptures, areaSelections, page } = create(); + await feature.addScreenshotToChat(); + page.pickedArea = { x: 10, y: 20, width: 30, height: 40 }; + await feature.addAreaScreenshotToChat(); + page.pickedArea = undefined; + await feature.addAreaScreenshotToChat(); + await feature.addFullPageScreenshotToChat(); + assert.deepStrictEqual({ + pageCaptures, + areaSelections, + attached: attached.map(entry => ({ name: entry.name, mimeType: entry.kind === 'image' ? entry.mimeType : undefined, markUp: service.getEditableAttachment(entry)?.original.width })), + tool: service.requests, + captures: telemetry.captures, + }, { + pageCaptures: [ + { quality: 80 }, + { quality: 80, pageRect: { x: 10, y: 20, width: 30, height: 40 }, awaitNextPaint: true }, + { fullPage: true, format: 'png' }, + ], + areaSelections: [true, true], + attached: [ + { name: 'Browser Screenshot', mimeType: 'image/jpeg', markUp: 4 }, + { name: 'Browser Area Screenshot', mimeType: 'image/jpeg', markUp: 4 }, + { name: 'Browser Full Page Screenshot', mimeType: 'image/png', markUp: 4 }, + ], + // The page's own capture and area picker are used rather than the screenshot tool's selection. + tool: [], + captures: [ + { entryPoint: 'browserScreenshot', outcome: 'attached', mode: 'page' }, + { entryPoint: 'browserAreaScreenshot', outcome: 'attached', mode: 'area' }, + { entryPoint: 'browserAreaScreenshot', outcome: 'cancelled', mode: 'none' }, + { entryPoint: 'browserFullPageScreenshot', outcome: 'attached', mode: 'fullPage' }, + ], + }); + }); + + test('warns before attaching a capture of an untrusted page', async () => { + const attach = async (url: string) => { + const { feature, attached, warnings, telemetry } = create(url); + await feature.addScreenshotToChat(); + // The warning is cancelled, which attaches nothing. + return { warnings: warnings.length, attached: attached.length, outcome: telemetry.captures.map(capture => capture.outcome) }; + }; + assert.deepStrictEqual({ + localPage: await attach('http://localhost:3000/'), + untrustedPage: await attach('https://example.com/'), + }, { + localPage: { warnings: 0, attached: 1, outcome: ['attached'] }, + untrustedPage: { warnings: 1, attached: 0, outcome: ['cancelled'] }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/tools/navigateBrowserTool.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/tools/navigateBrowserTool.test.ts index 5f81caa0a377..aefe02daab8c 100644 --- a/src/vs/workbench/contrib/browserView/test/electron-browser/tools/navigateBrowserTool.test.ts +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/tools/navigateBrowserTool.test.ts @@ -18,6 +18,7 @@ import { BrowserEditorInput } from '../../../common/browserEditorInput.js'; import { NavigateBrowserTool } from '../../../electron-browser/tools/navigateBrowserTool.js'; import { IToolInvocation, ToolProgress } from '../../../../chat/common/tools/languageModelToolsService.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { toAgentHostUri } from '../../../../../../platform/agentHost/common/agentHostUri.js'; function createRemoteExplorerService(localUri: string): IRemoteExplorerService { return upcastPartial({ @@ -174,6 +175,72 @@ suite('NavigateBrowserTool', () => { }); }); + test('maps remote resource URLs to the file URL of the page\'s network before navigating', async () => { + const networkFilterService = disposables.add(new AgentNetworkFilterService(new TestConfigurationService())); + const navigationUrls: (string | undefined)[] = []; + const page = upcastPartial({ model: upcastPartial({ network: { authority: 'host' } }) }); + const tool = new NavigateBrowserTool( + upcastPartial({ + invokeFunction: async (_sessionId, _pageId, _fnDef, args) => { + navigationUrls.push(typeof args?.[0] === 'string' ? args[0] : undefined); + return { summary: '' }; + }, + }), + networkFilterService, + upcastPartial({ getKnownBrowserViews: () => new Map([['page', page]]), resolveNetwork: () => undefined }), + upcastPartial({}), + ); + + for (const url of ['vscode-remote://host/repo/index.html?view=preview#top', 'vscode-remote://other/repo/index.html']) { + await tool.invoke( + upcastPartial({ parameters: { pageId: 'page', type: 'url', url } }), + async () => 0, + upcastPartial({ report: () => { } }), + CancellationToken.None, + ); + } + + assert.deepStrictEqual(navigationUrls, ['file:///repo/index.html?view=preview#top', 'vscode-remote://other/repo/index.html']); + }); + + test('applies network policy to the file URL of a remote resource of the page\'s network', async () => { + const checked: string[] = []; + const networkFilterService = upcastPartial({ + isUriAllowed: uri => { + checked.push(uri.toString()); + return uri.scheme === 'file'; + }, + formatError: uri => `Blocked ${uri.toString()}`, + }); + const navigationUrls: (string | undefined)[] = []; + const tool = new NavigateBrowserTool( + upcastPartial({ + invokeFunction: async (_sessionId, _pageId, _fnDef, args) => { + navigationUrls.push(typeof args?.[0] === 'string' ? args[0] : undefined); + return { summary: '' }; + }, + }), + networkFilterService, + upcastPartial({ getKnownBrowserViews: () => new Map(), resolveNetwork: () => ({ authority: 'host-a' }) }), + upcastPartial({}), + ); + const parameters = { pageId: 'page', type: 'url', url: toAgentHostUri(URI.file('/repo/index.html'), 'host-a').toString() }; + + await tool.prepareToolInvocation({ parameters, toolCallId: 'test-tool-call', chatSessionResource: undefined }, CancellationToken.None); + const result = await tool.invoke( + upcastPartial({ parameters }), + async () => 0, + upcastPartial({ report: () => { } }), + CancellationToken.None, + ); + + assert.deepStrictEqual({ checked: [...new Set(checked)], error: result.toolResultError, navigationUrls }, { + checked: ['file:///repo/index.html'], + error: undefined, + navigationUrls: ['file:///repo/index.html'], + }); + }); + test('allows a loopback forwarded destination as tunnel transport', async () => { const configService = new TestConfigurationService(); configService.setUserConfiguration(AgentNetworkDomainSettingId.NetworkFilter, true); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewHost.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewHost.test.ts index 3600424e9199..835a18d1fa00 100644 --- a/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewHost.test.ts +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewHost.test.ts @@ -10,9 +10,12 @@ import { Event } from '../../../../../base/common/event.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; import { MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { IBrowserViewCaptureScreenshotOptions } from '../../../../../platform/browserView/common/browserView.js'; import { IBrowserViewModel } from '../../common/browserView.js'; import { WebContentsViewHost } from '../../electron-browser/webContentsViewHost.js'; @@ -43,6 +46,7 @@ suite('WebContentsViewHost', () => { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(ILogService, new NullLogService()); instantiationService.stub(IKeybindingService, new MockKeybindingService()); + instantiationService.stub(IConfigurationService, new TestConfigurationService()); const host = store.add(instantiationService.createInstance(WebContentsViewHost, mainWindow, () => { })); host.setModel(model); @@ -84,6 +88,7 @@ suite('WebContentsViewHost', () => { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(ILogService, new NullLogService()); instantiationService.stub(IKeybindingService, new MockKeybindingService()); + instantiationService.stub(IConfigurationService, new TestConfigurationService()); const host = store.add(instantiationService.createInstance(WebContentsViewHost, mainWindow, () => { })); host.setModel(model); @@ -99,4 +104,89 @@ suite('WebContentsViewHost', () => { visibleAfterFrame: false, }); }); + + test('dims the page for overlays only when the setting is enabled', async () => { + const model = upcastPartial({ + url: 'https://example.test', + error: undefined, + screenshot: undefined, + focused: false, + visible: true, + onDidChangeVisibility: Event.None, + onDidKeyCommand: Event.None, + onDidNavigate: Event.None, + onDidChangeLoadingState: Event.None, + onWillDispose: Event.None, + setVisible: async () => { }, + captureScreenshot: () => new Promise(() => { }), + }); + const configurationService = new TestConfigurationService({ workbench: { browser: { dimOnOverlay: false } } }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IKeybindingService, new MockKeybindingService()); + instantiationService.stub(IConfigurationService, configurationService); + const host = store.add(instantiationService.createInstance(WebContentsViewHost, mainWindow, () => { })); + + const place = (className: string) => { + const element = mainWindow.document.createElement('div'); + element.className = className; + element.style.cssText = 'position:fixed;left:0;top:0;width:100px;height:100px'; + mainWindow.document.body.appendChild(element); + store.add({ dispose: () => element.remove() }); + return element; + }; + const container = place('test-browser-container'); + host.onContainerCreated(container); + host.setModel(model); + host.setVisible(true); + + const menu = place('monaco-menu-container'); + host.layout(); + const disabled = host.pauseElement.classList.contains('visible'); + + await configurationService.setUserConfiguration('workbench.browser.dimOnOverlay', true); + configurationService.onDidChangeConfigurationEmitter.fire({ source: ConfigurationTarget.USER, affectedKeys: new Set(['workbench.browser.dimOnOverlay']), change: { keys: [], overrides: [] }, affectsConfiguration: () => true }); + const enabled = host.pauseElement.classList.contains('visible'); + + menu.remove(); + host.layout(); + const cleared = host.pauseElement.classList.contains('visible'); + + await configurationService.setUserConfiguration('workbench.browser.dimOnOverlay', false); + place('notifications-center'); + host.layout(); + const notification = host.pauseElement.classList.contains('visible') && host.pauseElement.classList.contains('show-message'); + + assert.deepStrictEqual({ disabled, enabled, cleared, notification }, { disabled: false, enabled: true, cleared: false, notification: true }); + }); + + test('requests DevTools in the placeholder screenshot', () => { + const requests: (IBrowserViewCaptureScreenshotOptions | undefined)[] = []; + const model = upcastPartial({ + url: 'https://example.test', + error: undefined, + screenshot: undefined, + focused: false, + visible: true, + onDidChangeVisibility: Event.None, + onDidKeyCommand: Event.None, + onDidNavigate: Event.None, + onDidChangeLoadingState: Event.None, + onWillDispose: Event.None, + setVisible: async () => { }, + captureScreenshot: (options?: IBrowserViewCaptureScreenshotOptions) => { + requests.push(options); + return new Promise(() => { }); + }, + }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IKeybindingService, new MockKeybindingService()); + instantiationService.stub(IConfigurationService, new TestConfigurationService()); + const host = store.add(instantiationService.createInstance(WebContentsViewHost, mainWindow, () => { })); + + host.setModel(model); + + assert.deepStrictEqual({ captured: requests.length > 0, allIncludeDevTools: requests.every(options => options?.includeDevTools) }, { captured: true, allIncludeDevTools: true }); + }); }); diff --git a/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewRendererFeature.test.ts b/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewRendererFeature.test.ts new file mode 100644 index 000000000000..8ac957f8c8ce --- /dev/null +++ b/src/vs/workbench/contrib/browserView/test/electron-browser/webContentsViewRendererFeature.test.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 assert from 'assert'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ISizeService } from '../../../../../platform/theme/common/sizeService.js'; +import { IColorTheme, IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { TestColorTheme } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { IBrowserViewModel } from '../../common/browserView.js'; +import { BrowserEditor } from '../../electron-browser/browserEditor.js'; +import { WebContentsViewRendererFeature } from '../../electron-browser/features/webContentsViewRendererFeature.js'; +import { WebContentsViewHost } from '../../electron-browser/webContentsViewHost.js'; + +suite('WebContentsViewRendererFeature', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('re-lays out native view corners after size styles propagate and cancels pending work on disposal', async () => { + const sizesChanged = store.add(new Emitter()); + const themeChanged = store.add(new Emitter()); + const instantiation = store.add(new TestInstantiationService()); + instantiation.stubInstance(WebContentsViewHost, { dispose() { } }); + instantiation.stub(ISizeService, { onDidChangeSizes: sizesChanged.event }); + instantiation.stub(IThemeService, { onDidColorThemeChange: themeChanged.event }); + let radius = 8; + const layouts: number[] = []; + const model = new class extends mock() { }(); + const editor = new class extends mock() { + override get window() { return mainWindow; } + override get model() { return model; } + override readonly onDidChangeModel = Event.None; + override layout() { layouts.push(radius); } + }(); + const feature = store.add(instantiation.createInstance(WebContentsViewRendererFeature, editor)); + sizesChanged.fire(); + sizesChanged.fire(); + await Promise.resolve().then(() => { radius = 0; }); + await new Promise(resolve => mainWindow.requestAnimationFrame(() => resolve())); + themeChanged.fire(new TestColorTheme()); + radius = 4; + await new Promise(resolve => mainWindow.requestAnimationFrame(() => resolve())); + sizesChanged.fire(); + feature.dispose(); + radius = 8; + await new Promise(resolve => mainWindow.requestAnimationFrame(() => resolve())); + assert.deepStrictEqual(layouts, [0, 4]); + }); +}); diff --git a/src/vs/workbench/contrib/canvases/browser/canvasContextPicker.ts b/src/vs/workbench/contrib/canvases/browser/canvasContextPicker.ts index 471073fb882b..c98defef8635 100644 --- a/src/vs/workbench/contrib/canvases/browser/canvasContextPicker.ts +++ b/src/vs/workbench/contrib/canvases/browser/canvasContextPicker.ts @@ -9,10 +9,10 @@ import { IDisposable } from '../../../../base/common/lifecycle.js'; import { observableFromEvent } from '../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../base/common/themables.js'; import { localize } from '../../../../nls.js'; -import { IMenu, IMenuService, MenuId } from '../../../../platform/actions/common/actions.js'; +import { getMenuActionGroupTitle, IMenu, IMenuService, MenuId } from '../../../../platform/actions/common/actions.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; import { ChatAgentLocation } from '../../chat/common/constants.js'; -import { IChatContextPicker, IChatContextPickerItem, IChatContextPickerPickItem, IChatContextPickService } from '../../chat/browser/attachments/chatContextPickService.js'; +import { ChatContextPick, IChatContextPicker, IChatContextPickerItem, IChatContextPickerPickItem, IChatContextPickService } from '../../chat/browser/attachments/chatContextPickService.js'; import { ChatViewId, IChatWidget, isIChatViewViewContext } from '../../chat/browser/chat.js'; export function registerCanvasContextPicker( @@ -61,7 +61,7 @@ class CanvasContextPickerPick implements IChatContextPickerItem { placeholder: localize('chatContext.canvases.placeholder', "Select a canvas"), picks: () => observableFromEvent(menu, menu.onDidChange, () => ({ busy: false, - picks: this.getActions(menu).map(action => this.toPick(action)), + picks: this.getPicks(menu), })), dispose: () => menu.dispose(), }; @@ -71,6 +71,20 @@ class CanvasContextPickerPick implements IChatContextPickerItem { return menu.getActions().flatMap(([, actions]) => actions).filter(action => action.id !== Separator.ID); } + /** The picks of the menu's actions, each titled group under its title, as a menu shows them. */ + private getPicks(menu: IMenu): ChatContextPick[] { + const picks: ChatContextPick[] = []; + for (const [, groupActions] of menu.getActions()) { + const actions = groupActions.filter(action => action.id !== Separator.ID); + const title = actions.length > 0 ? getMenuActionGroupTitle(actions[0]) : undefined; + if (title) { + picks.push({ type: 'separator', label: title }); + } + picks.push(...actions.map(action => this.toPick(action))); + } + return picks; + } + private toPick(action: IAction): IChatContextPickerPickItem { return { label: action.label, diff --git a/src/vs/workbench/contrib/canvases/browser/canvasIcons.ts b/src/vs/workbench/contrib/canvases/browser/canvasIcons.ts new file mode 100644 index 000000000000..b1d5da0657a1 --- /dev/null +++ b/src/vs/workbench/contrib/canvases/browser/canvasIcons.ts @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { asCSSUrl } from '../../../../base/browser/cssValue.js'; +import { createStyleSheet } from '../../../../base/browser/domStylesheets.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { hash } from '../../../../base/common/hash.js'; +import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { URI } from '../../../../base/common/uri.js'; + +interface ICanvasIconStyle { + readonly className: string; + readonly store: DisposableStore; + references: number; +} + +/** By icon data URI path, which holds the whole image, the style that shows it while anything does. */ +const iconStyles = new Map(); + +/** CSS classes that show a canvas's icon, kept until they are disposed. */ +export interface ICanvasIconClasses extends IDisposable { + readonly classes: readonly string[]; +} + +/** + * The CSS classes that show a canvas's icon in a place that takes icon classes, or its default codicon when it has none. + * The icon is an image in its own colors at the base icon size, decorative beside the canvas's label; a surface that + * shows compact icons sizes it down as it does its codicons. The image's style stays only while something that holds + * its classes lives. + */ +export function acquireCanvasIconClasses(icon: URI | undefined): ICanvasIconClasses { + if (!icon) { + return { classes: ThemeIcon.asClassNameArray(Codicon.preview), dispose: () => { } }; + } + const key = icon.path; + let style = iconStyles.get(key); + if (!style) { + style = { className: getIconClassName(key), store: new DisposableStore(), references: 0 }; + const rule = `.${style.className} { display: inline-block; flex-shrink: 0; width: var(--vscode-codiconFontSize, 16px); height: var(--vscode-codiconFontSize, 16px); background: center / contain no-repeat ${asCSSUrl(icon)}; }`; + createStyleSheet(undefined, element => element.textContent = rule, style.store); + iconStyles.set(key, style); + } + style.references++; + const acquired = style; + let released = false; + return { + classes: [acquired.className], + dispose: () => { + if (released) { + return; + } + released = true; + if (--acquired.references === 0) { + iconStyles.delete(key); + acquired.store.dispose(); + } + }, + }; +} + +/** A class name for the image, the same each time it is shown so that showing it again does not change its element. */ +function getIconClassName(key: string): string { + const base = `canvas-image-icon-${(hash(key) >>> 0).toString(36)}`; + let className = base; + for (let collision = 1; [...iconStyles.values()].some(style => style.className === className); collision++) { + className = `${base}-${collision}`; + } + return className; +} + diff --git a/src/vs/workbench/contrib/canvases/browser/editorCanvasActions.ts b/src/vs/workbench/contrib/canvases/browser/editorCanvasActions.ts index cc5ca2239fa6..eb85d0be7f8b 100644 --- a/src/vs/workbench/contrib/canvases/browser/editorCanvasActions.ts +++ b/src/vs/workbench/contrib/canvases/browser/editorCanvasActions.ts @@ -15,7 +15,7 @@ import { ILogService } from '../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; import { ChatViewId, IChatWidget, IChatWidgetService, isIChatViewViewContext } from '../../chat/browser/chat.js'; import { ChatContextKeys } from '../../chat/common/actions/chatContextKeys.js'; -import { getCanvasDefinitionInstanceId, getCanvasDefinitionLabels, getCanvasInstanceLabels, ICanvasContext, ICanvasDefinition, ICanvasService, isCanvasOwner } from '../common/canvas.js'; +import { CanvasDefinitionOpener, getCanvasDefinitionLabels, getCanvasInstanceLabels, ICanvasContext, ICanvasDefinition, ICanvasService, isCanvasOwner } from '../common/canvas.js'; import { CanvasDefinitionStore } from '../common/canvasDefinitionStore.js'; import { canvasOwnerKey, getCanvasReferenceKey, ICanvasOwner, ICanvasReference } from '../../../common/canvasReference.js'; @@ -25,7 +25,7 @@ export const ChatNewCanvasMenuId = new MenuId('ChatNewCanvasMenu'); /** The groups of {@link ChatNewCanvasMenuId}, top to bottom, the same as in the Agents window's Canvas menus. */ const CanvasMenuGroup = { - /** The chat's canvases whose tab was closed but which are still running. */ + /** The chat's running canvases, whether or not their tab is open. */ Running: '1_running', /** The chat's canvas types, which open a canvas. */ Available: '2_available', @@ -107,19 +107,22 @@ export function registerEditorCanvasActions( observableSignalFromEvent(reader.store, definitionProvider.onDidChangeDefinitions).read(reader); return { owner: context.owner, listCanvases: () => definitionProvider.listCanvases() }; }, '[EditorCanvasActions]', logService)).definitions; + const opener = new CanvasDefinitionOpener(); let commandSequence = 0; store.add(autorun(reader => { const context = currentContext.read(reader); const definitions = availableDefinitions.read(reader); + // Running lists the canvases the chat's canvas pill does, whether or not their tab is open. const targets = context - ? canvasService.reopenableCanvases.read(reader).filter(target => isCanvasOwner(target.reference, context.owner)) + ? (context.canvases.read(reader) ?? []) + .map(canvas => ({ reference: { ...context.owner, canvas: canvas.resource }, canvas })) + .filter(({ reference, canvas }) => canvas.source !== undefined && canvasService.isOwnerPresentable(reference, reader)) : []; const activeKeys = new Set(); if (context) { const ownerKey = canvasOwnerKey(context.owner); const definitionLabels = getCanvasDefinitionLabels(definitions); - const definitionInstanceIds = new Set(definitions.map(getCanvasDefinitionInstanceId)); for (let index = 0; index < definitions.length; index++) { const canvas = definitions[index]; const label = definitionLabels[index]; @@ -141,22 +144,19 @@ export function registerEditorCanvasActions( const targetLabels = getCanvasInstanceLabels(targets.map(target => target.canvas)); for (let index = 0; index < targets.length; index++) { const target = targets[index]; - if (target.canvas.instanceId && definitionInstanceIds.has(target.canvas.instanceId)) { - continue; - } const label = targetLabels[index]; const key = `reopen:${getCanvasReferenceKey(target.reference)}`; activeKeys.add(key); let registration = registrations.get(key); if (!registration) { - registration = new CanvasMenuActionRegistration(`${REOPEN_EDITOR_CANVAS_COMMAND_ID}.${++commandSequence}`, () => reopenCanvas(target.reference, label)); + registration = new CanvasMenuActionRegistration(`${REOPEN_EDITOR_CANVAS_COMMAND_ID}.${++commandSequence}`, () => revealCanvas(target.reference, label)); registrations.set(key, registration); } registration.update( label, CanvasMenuGroup.Running, index, - () => reopenCanvas(target.reference, label), + () => revealCanvas(target.reference, label), ); } } @@ -177,34 +177,29 @@ export function registerEditorCanvasActions( : undefined; })); + /** Opens a new canvas of `canvas`'s type, beside any canvases of that type the chat already has. */ async function openCanvasDefinition(owner: ICanvasOwner, canvas: ICanvasDefinition, label: string): Promise { const context = currentContext.get(); + const definitionProvider = context?.definitionProvider; const definitionAvailable = availableDefinitions.get().some(candidate => candidate.extensionId === canvas.extensionId && candidate.canvasId === canvas.canvasId); - if (!canvasService.enabled.get() || !context?.definitionProvider || !isCanvasOwner(context.owner, owner) || !definitionAvailable) { + if (!canvasService.enabled.get() || !context || !definitionProvider || !isCanvasOwner(context.owner, owner) || !definitionAvailable) { return; } try { - const instanceId = getCanvasDefinitionInstanceId(canvas); - const existing = context.canvases.get()?.find(candidate => candidate.instanceId === instanceId); - if (existing) { - await canvasService.revealCanvas({ ...context.owner, canvas: existing.resource }); - if (existing.source) { - return; - } - } - await context.definitionProvider.openCanvas(canvas, instanceId); + await opener.open(context.owner, canvas, context.canvases.get() ?? [], instanceId => definitionProvider.openCanvas(canvas, instanceId)); } catch (error) { notificationService.error(localize('editorCanvas.openFailed', "Could not open canvas {0}: {1}", label, toErrorMessage(error))); } } - async function reopenCanvas(reference: ICanvasReference, label: string): Promise { + /** Shows a running canvas of the chat: focuses its tab, or opens it again once the tab was closed. */ + async function revealCanvas(reference: ICanvasReference, label: string): Promise { const context = currentContext.get(); if (!canvasService.enabled.get() || !context || !isCanvasOwner(context.owner, reference)) { return; } try { - await canvasService.reopenCanvas(reference); + await canvasService.revealCanvas(reference); } catch (error) { notificationService.error(localize('editorCanvas.openFailed', "Could not open canvas {0}: {1}", label, toErrorMessage(error))); } diff --git a/src/vs/workbench/contrib/canvases/common/agentHostCanvas.ts b/src/vs/workbench/contrib/canvases/common/agentHostCanvas.ts index 50ed658c19e5..717eb1a60199 100644 --- a/src/vs/workbench/contrib/canvases/common/agentHostCanvas.ts +++ b/src/vs/workbench/contrib/canvases/common/agentHostCanvas.ts @@ -14,7 +14,7 @@ import { getInlineToolInput, parsePartialToolInput } from '../../../../platform/ import { IAgentSubscription, observableFromSubscription } from '../../../../platform/agentHost/common/state/agentSubscription.js'; import { CanvasReference, CanvasState } from '../../../../platform/agentHost/common/state/protocol/channels-canvas/state.js'; import { ActionType, type ActionEnvelope } from '../../../../platform/agentHost/common/state/sessionActions.js'; -import { ChatState, ResponsePartKind, StateComponents, ToolCallStatus } from '../../../../platform/agentHost/common/state/sessionState.js'; +import { ActiveTurn, ChatState, ResponsePartKind, StateComponents, ToolCallStatus, Turn } from '../../../../platform/agentHost/common/state/sessionState.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { ICanvasContext, ICanvasDefinition, ICanvasDefinitionProvider, ICanvasOpenRequest } from './canvas.js'; import { ICanvas, ICanvasOwner } from '../../../common/canvasReference.js'; @@ -115,32 +115,58 @@ export function getAgentHostCanvasDefinitionsChangedEvent(subscription: IAgentSu ); } +/** + * Latest `open_canvas` request per instance for a completed history. The reducer never mutates a `turns` array or a completed turn in place + * (every change allocates a new array), so the result is keyed by array identity. The backward scan is resumable and stops once the requested instances are resolved. + */ +const completedOpenRequests = new WeakMap; nextTurnIndex: number }>(); + +function collectOpenRequests(turn: Turn | ActiveTurn, requests: Map, instances: ReadonlySet | undefined): void { + const parts = turn.responseParts; + for (let partIndex = parts.length - 1; partIndex >= 0; partIndex--) { + const part = parts[partIndex]; + if (part.kind !== ResponsePartKind.ToolCall || part.toolCall.toolName !== 'open_canvas') { + continue; + } + const call = part.toolCall; + if (call.status !== ToolCallStatus.Running && call.status !== ToolCallStatus.Completed && call.status !== ToolCallStatus.Cancelled) { + continue; + } + const input = getInlineToolInput(call.toolInput); + const instanceId = input ? parsePartialToolInput(input)?.instanceId : undefined; + if (typeof instanceId === 'string' && (!instances || instances.has(instanceId)) && !requests.has(instanceId)) { + requests.set(instanceId, { + id: `${turn.id}\u0000${call.toolCallId}`, + succeeded: call.status === ToolCallStatus.Completed && call.success, + ...(call.status === ToolCallStatus.Running ? { pending: true } : {}), + }); + } + } +} + function getOpenRequests(chat: ChatState | undefined, canvases: readonly ICanvas[] | undefined): ReadonlyMap { const requests = new Map(); const instances = new Set(canvases?.flatMap(canvas => canvas.instanceId ? [canvas.instanceId] : []) ?? []); if (!chat || instances.size === 0) { return requests; } - const turns = chat.activeTurn ? [...chat.turns, chat.activeTurn] : chat.turns; - for (let turnIndex = turns.length - 1; turnIndex >= 0 && requests.size < instances.size; turnIndex--) { - const turn = turns[turnIndex]; - for (let partIndex = turn.responseParts.length - 1; partIndex >= 0; partIndex--) { - const part = turn.responseParts[partIndex]; - if (part.kind !== ResponsePartKind.ToolCall || part.toolCall.toolName !== 'open_canvas') { - continue; - } - const call = part.toolCall; - if (call.status !== ToolCallStatus.Running && call.status !== ToolCallStatus.Completed && call.status !== ToolCallStatus.Cancelled) { - continue; - } - const input = getInlineToolInput(call.toolInput); - const instanceId = input ? parsePartialToolInput(input)?.instanceId : undefined; - if (typeof instanceId === 'string' && instances.has(instanceId) && !requests.has(instanceId)) { - requests.set(instanceId, { - id: `${turn.id}\u0000${call.toolCallId}`, - succeeded: call.status === ToolCallStatus.Completed && call.success, - ...(call.status === ToolCallStatus.Running ? { pending: true } : {}), - }); + if (chat.activeTurn) { + collectOpenRequests(chat.activeTurn, requests, instances); + } + if (requests.size < instances.size) { + let completed = completedOpenRequests.get(chat.turns); + if (!completed) { + completedOpenRequests.set(chat.turns, completed = { requests: new Map(), nextTurnIndex: chat.turns.length - 1 }); + } + // Resume the backward scan only as far as needed to resolve the current instances. + const isResolved = (instanceId: string) => requests.has(instanceId) || completed.requests.has(instanceId); + while (completed.nextTurnIndex >= 0 && !Array.from(instances).every(isResolved)) { + collectOpenRequests(chat.turns[completed.nextTurnIndex--], completed.requests, undefined); + } + for (const instanceId of instances) { + const request = completed.requests.get(instanceId); + if (request && !requests.has(instanceId)) { + requests.set(instanceId, request); } } } diff --git a/src/vs/workbench/contrib/canvases/common/agentHostCanvasConsent.ts b/src/vs/workbench/contrib/canvases/common/agentHostCanvasConsent.ts new file mode 100644 index 000000000000..9be823b847d2 --- /dev/null +++ b/src/vs/workbench/contrib/canvases/common/agentHostCanvasConsent.ts @@ -0,0 +1,183 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { toAction } from '../../../../base/common/actions.js'; +import { toErrorMessage } from '../../../../base/common/errorMessage.js'; +import { getErrorMessage, isCancellationError } from '../../../../base/common/errors.js'; +import Severity from '../../../../base/common/severity.js'; +import { localize } from '../../../../nls.js'; +import { AgentExtensionConsentOption, type AgentCanvasOpenAnswer, type AgentCanvasOpenFailure, type AgentCanvasOpenResult, type IAgentExtensionConsentRequest } from '../../../../platform/agentHost/common/agent.js'; +import { IDialogService, type IPromptButton } from '../../../../platform/dialogs/common/dialogs.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { IProgressService, ProgressLocation } from '../../../../platform/progress/common/progress.js'; +import type { ICanvasOpenOptions } from '../../../common/canvasReference.js'; + +/** How long an open the user asked for may take before it shows progress, so that opening a running canvas shows none. */ +const CANVAS_OPEN_PROGRESS_DELAY_MS = 500; + +/** A canvas did not open because the user did not allow its extension to load. */ +export class CanvasExtensionConsentDeniedError extends Error { + constructor(readonly consent: IAgentExtensionConsentRequest, readonly retryable: boolean) { + super(getDeniedMessage(consent, retryable)); + this.name = 'CanvasExtensionConsentDeniedError'; + } +} + +/** A canvas did not open for a reason its host reported. */ +export class CanvasOpenFailedError extends Error { + constructor(readonly failure: AgentCanvasOpenFailure) { + super(getFailureMessage(failure)); + this.name = 'CanvasOpenFailedError'; + } + + /** Whether opening the canvas again can succeed. */ + get retryable(): boolean { + return this.failure === 'reloaded'; + } +} + +/** + * Opens an agent host canvas, asking the user in a modal dialog whenever the canvas's extension needs consent to load. + * Throws {@link CanvasExtensionConsentDeniedError} when the user does not allow it, and {@link CanvasOpenFailedError} + * when the host reports why the canvas did not open. + */ +export async function openCanvasWithExtensionConsent(dialogService: IDialogService, open: (answer?: AgentCanvasOpenAnswer) => Promise, options?: ICanvasOpenOptions): Promise { + let result = await open(options?.retryDeniedConsent ? { kind: 'retry' } : undefined); + while (result.kind === 'consentRequired') { + const optionId = await askForExtensionConsent(dialogService, result.consent); + result = await open({ kind: 'consent', consentId: result.consent.id, optionId }); + } + if (result.kind === 'consentDenied') { + throw new CanvasExtensionConsentDeniedError(result.consent, result.retryable); + } + if (result.kind === 'failed') { + throw new CanvasOpenFailedError(result.failure); + } +} + +/** + * Opens a canvas the user asked for through `open`, showing progress while it takes long, as it does when its extension + * starts on first use, and reports a failure with the way to recover from it. + */ +export async function openCanvasForUser(progressService: IProgressService, notificationService: INotificationService, label: string, open: (options?: ICanvasOpenOptions) => Promise): Promise { + const openWithProgress = (options?: ICanvasOpenOptions) => progressService.withProgress({ + location: ProgressLocation.Notification, + title: localize('canvasOpen.progress', "Opening canvas {0}...", label), + delay: CANVAS_OPEN_PROGRESS_DELAY_MS, + }, () => open(options)); + try { + await openWithProgress(); + } catch (error) { + notifyCanvasOpenFailure(notificationService, error, label, openWithProgress); + } +} + +/** + * Reports a canvas the user asked for that did not open, offering to try again when that can help. A canvas closed while + * it opened, or an open the user cancelled, is not reported. Each attempt is reported in turn, so that trying again asks + * again for consent whenever the latest attempt was declined. + */ +export function notifyCanvasOpenFailure(notificationService: INotificationService, error: unknown, label: string, open: (options?: ICanvasOpenOptions) => Promise): void { + if (isCancellationError(error)) { + return; + } + if (error instanceof CanvasExtensionConsentDeniedError) { + notifyWithRetry(notificationService, Severity.Warning, error.message, label, open, { retryDeniedConsent: true }); + } else if (error instanceof CanvasOpenFailedError) { + if (error.retryable) { + notifyWithRetry(notificationService, Severity.Warning, getFailureMessage(error.failure, label), label, open, undefined); + } else if (error.failure !== 'dismissed') { + notificationService.notify({ severity: error.failure === 'unavailable' ? Severity.Warning : Severity.Error, message: getFailureMessage(error.failure, label) }); + } + } else { + notificationService.error(localize('canvasOpen.failed', "Could not open canvas {0}: {1}", label, toErrorMessage(error))); + } +} + +/** Reports a canvas, named `label`, that did not open, keeping a way to try again with `options` until it opens. */ +function notifyWithRetry(notificationService: INotificationService, severity: Severity, message: string, label: string, open: (options?: ICanvasOpenOptions) => Promise, options: ICanvasOpenOptions | undefined): void { + notificationService.notify({ + severity, + message, + // A declined extension's canvases leave the canvas menus until a retry succeeds, so keep the way to try again in view. + sticky: true, + actions: { + primary: [toAction({ + id: 'canvas.retryExtensionConsent', + label: localize('canvasExtensionConsent.tryAgain', "Try Again"), + run: () => open(options).catch(retryError => { + if (isCancellationError(retryError) || retryError instanceof CanvasExtensionConsentDeniedError || retryError instanceof CanvasOpenFailedError) { + notifyCanvasOpenFailure(notificationService, retryError, label, open); + } else { + // A retry that failed otherwise, for example while the chat is busy, keeps the way to try again. + notifyWithRetry(notificationService, Severity.Error, getErrorMessage(retryError), label, open, options); + } + }), + })], + }, + }); +} + +async function askForExtensionConsent(dialogService: IDialogService, consent: IAgentExtensionConsentRequest): Promise { + const environment = consent.kind === 'environment'; + const items = consent.items.join(', '); + const buttons: IPromptButton[] = [ + { label: localize({ key: 'canvasExtensionConsent.allow', comment: ['&& denotes a mnemonic'] }, "&&Allow"), run: () => AgentExtensionConsentOption.Allow }, + ]; + if (consent.persistable) { + buttons.push( + { label: localize({ key: 'canvasExtensionConsent.alwaysAllow', comment: ['&& denotes a mnemonic'] }, "Al&&ways Allow"), run: () => AgentExtensionConsentOption.AlwaysAllow }, + { label: localize({ key: 'canvasExtensionConsent.never', comment: ['&& denotes a mnemonic'] }, "&&Never"), run: () => AgentExtensionConsentOption.Never }, + ); + } + const { result } = await dialogService.prompt({ + type: Severity.Warning, + message: environment + ? localize('canvasExtensionConsent.environment.message', "Allow extension '{0}' to read sensitive environment variables?", consent.displayName) + : localize('canvasExtensionConsent.capabilities.message', "Allow extension '{0}' to load with extra permissions?", consent.displayName), + detail: environment + ? localize('canvasExtensionConsent.environment.detail', "'{0}' requested: {1}\n\nTheir values may be credentials. Once allowed, the extension can send them anywhere or pass them to processes it starts. If you don't allow access, the extension won't load.", consent.extensionName, items) + : localize('canvasExtensionConsent.capabilities.detail', "'{0}' requested these permissions: {1}\n\nIf you don't allow them, the extension won't load.", consent.extensionName, items), + buttons, + cancelButton: { label: localize('canvasExtensionConsent.notNow', "Not Now"), run: () => AgentExtensionConsentOption.NotNow }, + }); + return result ?? AgentExtensionConsentOption.NotNow; +} + +function getDeniedMessage(consent: IAgentExtensionConsentRequest, retryable: boolean): string { + if (consent.kind === 'environment') { + return retryable + ? localize('canvasExtensionConsent.environment.denied', "The canvas did not open because extension '{0}' was not allowed to read sensitive environment variables.", consent.displayName) + : localize('canvasExtensionConsent.environment.never', "The canvas did not open because you chose to never allow extension '{0}' to read sensitive environment variables. To be asked again, remove it from Extension Permission Approvals in the host settings, then select Try Again.", consent.displayName); + } + return retryable + ? localize('canvasExtensionConsent.capabilities.denied', "The canvas did not open because extension '{0}' was not allowed to load with the permissions it requested.", consent.displayName) + : localize('canvasExtensionConsent.capabilities.never', "The canvas did not open because you chose to never allow extension '{0}' to load with the permissions it requested. To be asked again, remove it from Extension Permission Approvals in the host settings, then select Try Again.", consent.displayName); +} + +/** Why a canvas did not open, naming it when `label` is known. */ +function getFailureMessage(failure: AgentCanvasOpenFailure, label?: string): string { + switch (failure) { + case 'dismissed': + // Never reported: the canvas was closed on purpose. + return localize('canvasOpen.dismissed', "The canvas was closed while it opened."); + case 'reloaded': + return label + ? localize('canvasOpen.reloaded.named', "Canvas {0} did not open because its extensions were reloaded while its extension started.", label) + : localize('canvasOpen.reloaded', "The canvas did not open because its extensions were reloaded while its extension started."); + case 'mismatchedDeclaration': + return label + ? localize('canvasOpen.mismatchedDeclaration.named', "Canvas {0} was withdrawn because its extension registered it differently from its extension.json declaration. The extension must register exactly what it declares.", label) + : localize('canvasOpen.mismatchedDeclaration', "The canvas was withdrawn because its extension registered it differently from its extension.json declaration. The extension must register exactly what it declares."); + case 'startFailed': + return label + ? localize('canvasOpen.startFailed.named', "Canvas {0} did not open because its extension did not start. Check the extension for errors.", label) + : localize('canvasOpen.startFailed', "The canvas did not open because its extension did not start. Check the extension for errors."); + case 'unavailable': + return label + ? localize('canvasOpen.unavailable.named', "Canvas {0} is no longer available. Its extension may have been disabled, removed, or failed to start.", label) + : localize('canvasOpen.unavailable', "The canvas is no longer available. Its extension may have been disabled, removed, or failed to start."); + } +} diff --git a/src/vs/workbench/contrib/canvases/common/canvas.ts b/src/vs/workbench/contrib/canvases/common/canvas.ts index 1646ae0e8166..6d200d4135bb 100644 --- a/src/vs/workbench/contrib/canvases/common/canvas.ts +++ b/src/vs/workbench/contrib/canvases/common/canvas.ts @@ -18,7 +18,7 @@ import { EditorInput } from '../../../common/editor/editorInput.js'; import { IEditorGroup, IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.js'; import { IWorkbenchEnvironmentService } from '../../../services/environment/common/environmentService.js'; import type { IBrowserViewModel } from '../../browserView/common/browserView.js'; -import { ICanvas, ICanvasOwner, ICanvasReference } from '../../../common/canvasReference.js'; +import { canvasOwnerKey, ICanvas, ICanvasOwner, ICanvasReference } from '../../../common/canvasReference.js'; /** Reveals a live canvas beside its owning chat, reopening its closed tab. Takes an {@link ICanvasReference}. */ export const REVEAL_CANVAS_COMMAND_ID = 'workbench.action.agentSessions.revealCanvas'; @@ -191,9 +191,9 @@ export interface ICanvasService { /** * Resolves the live browser model retained for this presentation, creating it once when needed. * A retained model keeps its last page while the provider is temporarily unavailable, then - * loads the next source in place. + * loads the next source in place. Reloading requires a retained page and a current live source. */ - resolveCanvasModel(reference: ICanvasReference, source: URI): Promise; + resolveCanvasModel(reference: ICanvasReference, source: URI, reload?: boolean): Promise; } export function isCanvasOwner(first: ICanvasOwner, second: ICanvasOwner): boolean { @@ -230,9 +230,13 @@ export function getCanvasInstanceLabels(canvases: readonly ICanvas[]): readonly const titleIndex = (titleIndexes.get(canvas.title) ?? 0) + 1; titleIndexes.set(canvas.title, titleIndex); - const instanceLabel = canvas.instanceId && instanceIdCounts.get(canvas.instanceId) === 1 - ? canvas.instanceId - : String(titleIndex); + // Identifiers generated for a registered canvas type do not tell its instances apart for users; their numbers do. + const definitionIndex = getCanvasDefinitionInstanceIndex(canvas); + const instanceLabel = definitionIndex !== undefined + ? String(definitionIndex) + : canvas.instanceId && instanceIdCounts.get(canvas.instanceId) === 1 + ? canvas.instanceId + : String(titleIndex); let label = localize('canvas.instanceTitle', "{0} ({1})", canvas.title, instanceLabel); let collisionIndex = 2; while (usedLabels.has(label)) { @@ -275,8 +279,8 @@ export function getCanvasDefinitionLabels(canvases: readonly ICanvasDefinition[] const CANVAS_INSTANCE_ID_MAX_LENGTH = 128; -/** Produces the stable instance identifier used when directly opening a registered canvas type. */ -export function getCanvasDefinitionInstanceId(canvas: ICanvasDefinition): string { +/** Produces the stable instance identifier of the first canvas opened directly from a registered canvas type. */ +export function getCanvasDefinitionInstanceId(canvas: Pick): string { const raw = `${canvas.extensionId}-${canvas.canvasId}`; const normalized = raw .replace(/[^A-Za-z0-9._-]+/g, '-') @@ -294,6 +298,83 @@ export function getCanvasDefinitionInstanceId(canvas: ICanvasDefinition): string return `${base}${hashSuffix}`; } +/** The instance identifier of the `index`th canvas opened from a registered canvas type, counting from 1. */ +function getIndexedCanvasDefinitionInstanceId(canvas: Pick, index: number): string { + const instanceId = getCanvasDefinitionInstanceId(canvas); + if (index <= 1) { + return instanceId; + } + const suffix = `-${index}`; + return `${instanceId.slice(0, CANVAS_INSTANCE_ID_MAX_LENGTH - suffix.length)}${suffix}`; +} + +/** + * Produces the instance identifier of a new canvas of a registered canvas type: the type's stable instance identifier + * while it is not in `used`, else the first free numbered one. + */ +function getNewCanvasDefinitionInstanceId(canvas: ICanvasDefinition, used: ReadonlySet): string { + for (let index = 1; ; index++) { + const instanceId = getIndexedCanvasDefinitionInstanceId(canvas, index); + if (!used.has(instanceId)) { + return instanceId; + } + } +} + +/** + * Opens new canvases of registered canvas types, each with an instance identifier of its own. An identifier is reserved + * for its owner from the open request until the owner's canvases include it, so that opens that overlap, or that the + * host has yet to publish, never share one. A failed open releases its identifier. + */ +export class CanvasDefinitionOpener { + + /** By owner, the reserved instance identifiers, and whether their open succeeded. */ + private readonly reservations = new Map>(); + + /** Opens a new canvas of `canvas`'s type beside `canvases`, the owner's current canvases, through `open`. */ + async open(owner: ICanvasOwner, canvas: ICanvasDefinition, canvases: readonly ICanvas[], open: (instanceId: string) => Promise): Promise { + const key = canvasOwnerKey(owner); + const reserved = this.reservations.get(key) ?? new Map(); + this.reservations.set(key, reserved); + const used = new Set(canvases.flatMap(candidate => candidate.instanceId ? [candidate.instanceId] : [])); + for (const [instanceId, opened] of reserved) { + if (opened && used.has(instanceId)) { + reserved.delete(instanceId); + } + used.add(instanceId); + } + const instanceId = getNewCanvasDefinitionInstanceId(canvas, used); + reserved.set(instanceId, false); + try { + await open(instanceId); + } catch (error) { + reserved.delete(instanceId); + if (reserved.size === 0 && this.reservations.get(key) === reserved) { + this.reservations.delete(key); + } + throw error; + } + reserved.set(instanceId, true); + } +} + +/** + * The number of `canvas` among the canvases of its registered canvas type, counting from 1, when its instance identifier + * is one {@link CanvasDefinitionOpener} produces. + */ +function getCanvasDefinitionInstanceIndex(canvas: ICanvas): number | undefined { + if (!canvas.instanceId || !canvas.extensionId || !canvas.canvasId) { + return undefined; + } + const type = { extensionId: canvas.extensionId, canvasId: canvas.canvasId }; + if (canvas.instanceId === getCanvasDefinitionInstanceId(type)) { + return 1; + } + const suffix = /-(?\d+)$/.exec(canvas.instanceId)?.groups?.index; + const index = suffix !== undefined ? Number(suffix) : undefined; + return index !== undefined && canvas.instanceId === getIndexedCanvasDefinitionInstanceId(type, index) ? index : undefined; +} + /** Returns whether a registered extension canvas can be opened without another input flow. */ export function isOpenableExtensionCanvasDefinition(canvas: ICanvasDefinition): boolean { return !canvas.requiresInput && ( diff --git a/src/vs/workbench/contrib/canvases/electron-browser/canvasService.ts b/src/vs/workbench/contrib/canvases/electron-browser/canvasService.ts index 68110968de52..d84719e883d2 100644 --- a/src/vs/workbench/contrib/canvases/electron-browser/canvasService.ts +++ b/src/vs/workbench/contrib/canvases/electron-browser/canvasService.ts @@ -333,7 +333,7 @@ export class CanvasService extends Disposable implements ICanvasService { return input; } - async resolveCanvasModel(reference: ICanvasReference, source: URI): Promise { + async resolveCanvasModel(reference: ICanvasReference, source: URI, reload = false): Promise { const key = getCanvasReferenceKey(reference); if (!isEqual(this.presentations.get(key)?.canvas?.source, source)) { // A view outside the editor working set, such as a pinned canvas page, observes the canvas @@ -341,18 +341,19 @@ export class CanvasService extends Disposable implements ICanvasService { // reconciliation completes synchronously, so judge the source only once the update settled. await Promise.resolve(); } - const presentation = this.presentations.get(key) ?? this.createExternalPresentation(reference, source); - if (this._store.isDisposed || !presentation || !isEqual(presentation.canvas?.source, source)) { + const presentation = this.presentations.get(key) ?? (reload ? undefined : this.createExternalPresentation(reference, source)); + if (this._store.isDisposed || !presentation || !isEqual(presentation.canvas?.source, source) + || (reload && (!presentation.model || !this.isLiveSource(reference, source)))) { throw new CancellationError(); } + if (!reload && presentation.model && isEqual(presentation.modelSource, source)) { + return { model: presentation.model, reused: true }; + } if (presentation.modelPromise && isEqual(presentation.modelPromise.source, source)) { return { model: await presentation.modelPromise.value, reused: true }; } - if (presentation.model && isEqual(presentation.modelSource, source)) { - return { model: presentation.model, reused: true }; - } if (presentation.model) { - return { model: await this.navigatePresentationModel(presentation, presentation.model, source), reused: false }; + return { model: await this.navigatePresentationModel(presentation, presentation.model, source, reload), reused: false }; } this.disposePresentationModel(presentation); const generation = ++presentation.modelGeneration; @@ -385,12 +386,23 @@ export class CanvasService extends Disposable implements ICanvasService { return { model: await value, reused: false }; } - /** Loads a new source into the retained page, so it is replaced in place without detaching its view or moving focus. */ - private navigatePresentationModel(presentation: ICanvasPresentation, model: IBrowserViewModel, source: URI): Promise { + private isLiveSource(reference: ICanvasReference, source: URI): boolean { + const canvas = this.lookupCanvas(reference)?.canvas; + return !this._store.isDisposed && canvas?.instanceId !== undefined && isEqual(canvas.source, source) && this.isPresentable(reference); + } + + /** Loads a source into the retained page without detaching its view or moving focus. */ + private navigatePresentationModel(presentation: ICanvasPresentation, model: IBrowserViewModel, source: URI, reload = false): Promise { const generation = ++presentation.modelGeneration; - // The page leaves its previous source even if this navigation is superseded, so returning to that source must load it again. - presentation.modelSource = undefined; - const isCurrent = () => presentation.model === model && presentation.modelGeneration === generation && isEqual(presentation.canvas?.source, source); + // Keep same-source reloads cached so revisiting a failure never retries it automatically. + if (!reload || !isEqual(presentation.modelSource, source)) { + presentation.modelSource = undefined; + } + const isCurrent = () => presentation.model === model && presentation.modelGeneration === generation + && isEqual(presentation.canvas?.source, source) && (!reload || this.isLiveSource(presentation.reference, source)); + if (!isCurrent()) { + throw new CancellationError(); + } const url = source.toString(true); const network = model.network; const loaded = network ? this.loadOnRemoteNetwork(model, network, url, isCurrent) : model.loadURL(url); diff --git a/src/vs/workbench/contrib/canvases/electron-browser/canvasView.ts b/src/vs/workbench/contrib/canvases/electron-browser/canvasView.ts index 3038d06cc5a8..b481067c7988 100644 --- a/src/vs/workbench/contrib/canvases/electron-browser/canvasView.ts +++ b/src/vs/workbench/contrib/canvases/electron-browser/canvasView.ts @@ -7,6 +7,7 @@ import './media/sessionCanvas.css'; import { getZoomFactor, onDidChangeZoomLevel } from '../../../../base/browser/browser.js'; import { $, isAncestorOfActiveElement, scheduleAtNextAnimationFrame } from '../../../../base/browser/dom.js'; import { status } from '../../../../base/browser/ui/aria/aria.js'; +import { Button } from '../../../../base/browser/ui/button/button.js'; import { CodeWindow } from '../../../../base/browser/window.js'; import { disposableTimeout } from '../../../../base/common/async.js'; import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; @@ -26,6 +27,7 @@ import { IInstantiationService } from '../../../../platform/instantiation/common import { ILogService } from '../../../../platform/log/common/log.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { defaultButtonStyles } from '../../../../platform/theme/browser/defaultStyles.js'; import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js'; import { IBrowserViewModel } from '../../browserView/common/browserView.js'; import { focusWebContentsViewContainer, WebContentsViewHost } from '../../browserView/electron-browser/webContentsViewHost.js'; @@ -102,6 +104,7 @@ export class CanvasView extends Disposable { private readonly wrapper: HTMLElement; private readonly container: HTMLElement; private readonly message: HTMLElement; + private readonly reloadButton: Button; /** The last frame of the canvas this view switched away from, shown until the next canvas is revealed. */ private readonly heldFrame: HTMLElement; private readonly heldFrameRelease = this._register(new MutableDisposable()); @@ -159,9 +162,16 @@ export class CanvasView extends Disposable { this.container.setAttribute('role', 'group'); this.container.setAttribute('aria-label', localize('canvas.content', "Canvas content. Use Accessibility Help for keyboard navigation.")); const placeholder = $('.browser-placeholder-contents'); + const canvasStatus = $('.session-canvas-status'); this.message = $('.session-canvas-message'); this.message.setAttribute('role', 'status'); - placeholder.appendChild(this.message); + canvasStatus.appendChild(this.message); + this.reloadButton = this._register(new Button(canvasStatus, defaultButtonStyles)); + this.reloadButton.label = localize('canvas.reload', "Reload Canvas"); + this.reloadButton.enabled = false; + this.reloadButton.element.style.display = 'none'; + this._register(this.reloadButton.onDidClick(() => this._reload())); + placeholder.appendChild(canvasStatus); this.container.appendChild(placeholder); this.wrapper.appendChild(this.container); this.element.appendChild(this.wrapper); @@ -256,7 +266,34 @@ export class CanvasView extends Disposable { this.heldFrame.style.backgroundImage = ''; } - private async _load(input: ICanvasViewInput, key: string): Promise { + private _reload(): void { + if (!this.reloadButton.enabled || this.loadingKey !== undefined || !this.model?.error || this._store.isDisposed || !this._measure().visible) { + return; + } + const input = this.currentInput.get(); + const canvas = input?.canvas.get(); + if (!input || !canvas?.source || input.membershipPending.get() || !this.canvasService.enabled.get() + || !this.canvasService.isPresentable(input.reference) || !this._presents(input)) { + return; + } + void this._load(input, getLoadKey(canvas.resource, canvas.source), true); + } + + private _updateReloadButton(): void { + const available = !!this.model?.error && this.loadingKey === undefined && !this.reconnecting; + // Moving focus to the container while loading can focus the native page before it is ready. + const loadingFocused = (this.loadingKey !== undefined || this.reconnecting) && this.reloadButton.hasFocus(); + if (!available && !loadingFocused && this.reloadButton.hasFocus() && this.targetWindow.document.hasFocus() && this._measure().visible) { + const input = this.currentInput.get(); + if (input && this.canvasService.isPresentable(input.reference)) { + focusWebContentsViewContainer(this.container); + } + } + this.reloadButton.enabled = available; + this.reloadButton.element.style.display = available || loadingFocused ? '' : 'none'; + } + + private async _load(input: ICanvasViewInput, key: string, reload = false): Promise { const canvas = input.canvas.get(); if (canvas === undefined || canvas.source === undefined) { return; @@ -264,17 +301,21 @@ export class CanvasView extends Disposable { // The page of this canvas stays presented while its new source loads into it in place, but no longer counts as showing its last source. if (this._presents(input)) { this.loadedKey = undefined; + if (reload) { + this.message.textContent = localize('canvas.pageLoading', "Loading canvas page…"); + } } else { this._detach(localize('canvas.loading', "Loading canvas…")); } const sequence = ++this.loadSequence; this.loadingKey = key; + this._updateReloadButton(); const stopwatch = StopWatch.create(); let outcome: CanvasLoadEvent['outcome'] = 'error'; let reused = false; try { const source = canvas.source; - const resolution = await this.canvasService.resolveCanvasModel(input.reference, source); + const resolution = await this.canvasService.resolveCanvasModel(input.reference, source, reload); const model = resolution.model; reused = resolution.reused; if (!this._isCurrent(input, source, sequence)) { @@ -298,12 +339,19 @@ export class CanvasView extends Disposable { const current = this._isCurrent(input, canvas.source, sequence); outcome = !current ? 'interrupted' : isCancellationError(error) ? 'cancelled' : 'error'; if (current && !isCancellationError(error)) { - this._detach(localize('canvas.loadFailed', "The canvas could not be loaded.")); + const message = localize('canvas.loadFailed', "The canvas could not be loaded."); + if (reload && this._presents(input)) { + this.loadedKey = key; + this.message.textContent = message; + } else { + this._detach(message); + } this.logService.error(`${this.options.logPrefix} Failed to load canvas`); } } finally { if (sequence === this.loadSequence && this.loadingKey === key) { this.loadingKey = undefined; + this._updateReloadButton(); } if (!reused) { this.telemetryService.publicLog2('agentCanvas.loadCompleted', { @@ -351,6 +399,7 @@ export class CanvasView extends Disposable { } this.modelLifetime.clear(); this.model = model; + this._updateReloadButton(); this.modelCanvas = undefined; this.layoutSequence++; this._presentationVisible.set(false, undefined); @@ -392,6 +441,7 @@ export class CanvasView extends Disposable { this.message.textContent = event.error ? localize('canvas.pageFailed', "The canvas page failed to load.") : event.loading ? localize('canvas.pageLoading', "Loading canvas page…") : ''; + this._updateReloadButton(); })); this.modelLifetime.add(model.onDidNavigate(() => this.invalidateSemanticContent())); this.modelLifetime.add(model.onDidRequestOpenExternal(url => { @@ -402,6 +452,7 @@ export class CanvasView extends Disposable { return; } this.model = undefined; + this._updateReloadButton(); this.modelCanvas = undefined; this.loadedKey = undefined; this.host.setModel(undefined); @@ -467,6 +518,7 @@ export class CanvasView extends Disposable { return; } this.reconnecting = reconnecting; + this._updateReloadButton(); this.element.classList.toggle('provider-reconnecting', reconnecting); if (reconnecting) { // A copy, because the host clears its own screenshot when the retained page fails to load. @@ -598,15 +650,23 @@ export class CanvasView extends Disposable { createAccessibleProvider(type: AccessibleViewType): AccessibleContentProvider { const input = this.currentInput.get(); - const help = this.options.getHelpContent(); + const reloadFocused = this.reloadButton.hasFocus(); + const help = [ + this.options.getHelpContent(), + localize('canvas.help.reload', "If the canvas page fails while its provider is available, use Reload Canvas to reload the page."), + ].join('\n\n'); this.semanticText = localize('canvas.reading', "Reading accessible canvas content…"); return new AccessibleContentProvider( AccessibleViewProviderId.SessionCanvas, { type, language: 'plaintext' }, () => type === AccessibleViewType.Help ? help : this.semanticText, () => { - if (input && this.currentInput.get() === input && this._presentationVisible.get() && this.canvasService.isPresentable(input.reference)) { - this.focus(); + if (input && this.currentInput.get() === input && this._measure().visible && this.canvasService.isPresentable(input.reference)) { + if (reloadFocused && this.reloadButton.enabled) { + this.reloadButton.focus(); + } else { + this.focus(); + } } }, AccessibilityVerbositySettingId.SessionCanvas, diff --git a/src/vs/workbench/contrib/canvases/electron-browser/media/sessionCanvas.css b/src/vs/workbench/contrib/canvases/electron-browser/media/sessionCanvas.css index 57cc1d295d85..5e4bbe62f95f 100644 --- a/src/vs/workbench/contrib/canvases/electron-browser/media/sessionCanvas.css +++ b/src/vs/workbench/contrib/canvases/electron-browser/media/sessionCanvas.css @@ -20,12 +20,14 @@ border-radius: 0; } -.session-canvas-editor .session-canvas-message { +.session-canvas-editor .session-canvas-status { position: absolute; inset: 0; display: flex; + flex-direction: column; align-items: center; justify-content: center; + gap: var(--vscode-spacing-size120); padding: var(--vscode-spacing-size160); color: var(--vscode-descriptionForeground); font-size: var(--vscode-fontSize-body1); @@ -37,6 +39,11 @@ display: none; } +.session-canvas-editor .session-canvas-status > .monaco-button { + width: auto; + pointer-events: auto; +} + /* * Last frames of pages the view keeps hidden: the previous canvas's, held while the next one loads so a * switch does not flash, and a copy of this canvas's, frozen while its provider reconnects. @@ -69,7 +76,7 @@ } } -.session-canvas-editor.provider-reconnecting .session-canvas-message { +.session-canvas-editor.provider-reconnecting .session-canvas-status { z-index: 1; margin: auto; width: fit-content; diff --git a/src/vs/workbench/contrib/canvases/test/browser/canvasContextPicker.test.ts b/src/vs/workbench/contrib/canvases/test/browser/canvasContextPicker.test.ts index b5c48a09aa3d..812753f7dbb6 100644 --- a/src/vs/workbench/contrib/canvases/test/browser/canvasContextPicker.test.ts +++ b/src/vs/workbench/contrib/canvases/test/browser/canvasContextPicker.test.ts @@ -25,21 +25,20 @@ import { isChatViewCanvasContextPickerWidget, registerCanvasContextPicker } from suite('CanvasContextPicker', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - test('appears after Sessions and runs Canvas menu actions without attaching context', async () => { + test('appears after Sessions and runs Canvas menu actions under their group titles without attaching context', async () => { const runs: string[] = []; let disposedMenus = 0; const contextKeyService = new MockContextKeyService(); const commandService = upcastPartial({ executeCommand: async id => { runs.push(id); return undefined; }, }); - const actions = [ - new MenuItemAction({ id: 'registered', title: 'Registered Canvas' }, undefined, undefined, undefined, undefined, contextKeyService, commandService), - new MenuItemAction({ id: 'dismissed', title: 'Dismissed Canvas' }, undefined, undefined, undefined, undefined, contextKeyService, commandService), - ]; const menuService = upcastPartial({ createMenu: () => upcastPartial({ onDidChange: Event.None, - getActions: () => [['navigation', actions]], + getActions: () => [ + ['1_running', [new MenuItemAction({ id: 'dismissed', title: 'Dismissed Canvas' }, undefined, { groupTitle: 'Running' }, undefined, undefined, contextKeyService, commandService)]], + ['2_available', [new MenuItemAction({ id: 'registered', title: 'Registered Canvas' }, undefined, { groupTitle: 'Available' }, undefined, undefined, contextKeyService, commandService)]], + ], dispose: () => disposedMenus++, }), }); @@ -64,9 +63,12 @@ suite('CanvasContextPicker', () => { } const pickerStore = new DisposableStore(); const picksObservable = pickerPicks(constObservable(''), CancellationToken.None); + let rows: string[] = []; let picks: IChatContextPickerPickItem[] = []; pickerStore.add(autorun(reader => { - picks = picksObservable.read(reader).picks.filter(isChatContextPickerPickItem); + const allPicks = picksObservable.read(reader).picks; + rows = allPicks.map(pick => isChatContextPickerPickItem(pick) ? pick.label : `-- ${pick.label}`); + picks = allPicks.filter(isChatContextPickerPickItem); })); const results = []; for (const pick of picks) { @@ -79,7 +81,7 @@ suite('CanvasContextPicker', () => { label: canvas.label, ordinal: canvas.ordinal, enabled, - picks: picks.map(pick => pick.label), + rows, results, runs, disposedMenus, @@ -87,9 +89,9 @@ suite('CanvasContextPicker', () => { label: 'Canvas...', ordinal: -401, enabled: true, - picks: ['Registered Canvas', 'Dismissed Canvas'], + rows: ['-- Running', 'Dismissed Canvas', '-- Available', 'Registered Canvas'], results: ['noop', 'noop'], - runs: ['registered', 'dismissed'], + runs: ['dismissed', 'registered'], disposedMenus: 2, }); }); diff --git a/src/vs/workbench/contrib/canvases/test/browser/editorCanvasActions.test.ts b/src/vs/workbench/contrib/canvases/test/browser/editorCanvasActions.test.ts index 2dbb410c19b2..81bf34a1991c 100644 --- a/src/vs/workbench/contrib/canvases/test/browser/editorCanvasActions.test.ts +++ b/src/vs/workbench/contrib/canvases/test/browser/editorCanvasActions.test.ts @@ -20,7 +20,7 @@ import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js import { IChatModel } from '../../../chat/common/model/chatModel.js'; import { IChatViewModel } from '../../../chat/common/model/chatViewModel.js'; import { ChatNewCanvasMenuId, OPEN_EDITOR_CANVAS_COMMAND_ID, registerEditorCanvasActions, REOPEN_EDITOR_CANVAS_COMMAND_ID } from '../../browser/editorCanvasActions.js'; -import { getCanvasDefinitionInstanceId, ICanvasContext, ICanvasDefinition, ICanvasReopenTarget, ICanvasService } from '../../common/canvas.js'; +import { getCanvasDefinitionInstanceId, ICanvasContext, ICanvasDefinition, ICanvasService } from '../../common/canvas.js'; import { ICanvas } from '../../../../common/canvasReference.js'; suite('EditorCanvasActions', () => { @@ -82,7 +82,13 @@ suite('EditorCanvasActions', () => { title: 'Counter', source: undefined, }; - const canvases = observableValue('canvases', [existing, unavailableProject]); + const preview: ICanvas = { + resource: URI.parse('agent-host-canvas:/preview'), + instanceId: 'preview-secondary', + title: 'Preview', + source: URI.parse('https://example.test/preview'), + }; + const canvases = observableValue('canvases', [existing, unavailableProject, preview]); const context: ICanvasContext = { owner, canvases, @@ -113,33 +119,12 @@ suite('EditorCanvasActions', () => { onDidAddWidget: widgetAdded.event, onDidRemoveWidget: widgetRemoved.event, }); - const stableTarget: ICanvasReopenTarget = { - reference: { ...owner, canvas: URI.parse('agent-host-canvas:/project-counter') }, - canvas: { - resource: URI.parse('agent-host-canvas:/project-counter'), - instanceId: getCanvasDefinitionInstanceId(projectDefinition), - title: 'Counter', - source: URI.parse('https://example.test/project-counter'), - }, - }; - const secondaryTarget: ICanvasReopenTarget = { - reference: { ...owner, canvas: URI.parse('agent-host-canvas:/preview') }, - canvas: { - resource: URI.parse('agent-host-canvas:/preview'), - instanceId: 'preview-secondary', - title: 'Preview', - source: URI.parse('https://example.test/preview'), - }, - }; const enabled = observableValue('enabled', true); - const reopenableCanvases = observableValue('reopenableCanvases', [stableTarget, secondaryTarget]); const revealed: string[] = []; - const reopened: string[] = []; const canvasService = upcastPartial({ enabled, - reopenableCanvases, + isOwnerPresentable: (_reference, reader) => enabled.read(reader), revealCanvas: async reference => { revealed.push(reference.canvas.toString()); }, - reopenCanvas: async reference => { reopened.push(reference.canvas.toString()); }, }); const registration = registerEditorCanvasActions( canvasService, @@ -203,7 +188,6 @@ suite('EditorCanvasActions', () => { listCalls, opened, revealed, - reopened, unchangedSubmenuRetained: unchangedSubmenus[0] === initialSubmenus[0], refreshedTitles: refreshedItems.map(item => typeof item.command.title === 'string' ? item.command.title : item.command.title.value), uninitializedItems: uninitializedItems.length, @@ -216,17 +200,19 @@ suite('EditorCanvasActions', () => { }, { submenuTitles: ['Canvas'], submenuGroups: ['z_canvas'], - initialTitles: ['Preview', 'Counter (Project Counter)', 'Counter (User Counter)'], - groups: ['1_running', '2_available', '2_available'], - groupTitles: ['Running', 'Available', 'Available'], - requiresChat: [true, true, true], + initialTitles: ['Counter', 'Preview', 'Counter (Project Counter)', 'Counter (User Counter)'], + groups: ['1_running', '1_running', '2_available', '2_available'], + groupTitles: ['Running', 'Running', 'Available', 'Available'], + requiresChat: [true, true, true, true], listCalls: 4, opened: [{ canvas: 'project:counter', - instanceId: getCanvasDefinitionInstanceId(projectDefinition), + instanceId: `${getCanvasDefinitionInstanceId(projectDefinition)}-2`, + }, { + canvas: 'user:counter', + instanceId: `${getCanvasDefinitionInstanceId(userDefinition)}-2`, }], - revealed: ['agent-host-canvas:/project-counter', 'agent-host-canvas:/user-counter'], - reopened: ['agent-host-canvas:/preview'], + revealed: ['agent-host-canvas:/user-counter', 'agent-host-canvas:/preview'], unchangedSubmenuRetained: true, refreshedTitles: ['Counter', 'Preview', 'Chart'], uninitializedItems: 0, @@ -289,7 +275,6 @@ suite('EditorCanvasActions', () => { const enabled = observableValue('enabled', true); const canvasService = upcastPartial({ enabled, - reopenableCanvases: observableValue('reopenableCanvases', []), }); const registration = registerEditorCanvasActions( canvasService, diff --git a/src/vs/workbench/contrib/canvases/test/common/agentHostCanvas.test.ts b/src/vs/workbench/contrib/canvases/test/common/agentHostCanvas.test.ts index 2ae98237445e..b792e8e091af 100644 --- a/src/vs/workbench/contrib/canvases/test/common/agentHostCanvas.test.ts +++ b/src/vs/workbench/contrib/canvases/test/common/agentHostCanvas.test.ts @@ -14,7 +14,7 @@ import { IAgentCanvasCloseRequest, IAgentCanvasInfo, IAgentCanvasOpenRequest, IA import { IAgentSubscription } from '../../../../../platform/agentHost/common/state/agentSubscription.js'; import { CanvasReference, CanvasState } from '../../../../../platform/agentHost/common/state/protocol/channels-canvas/state.js'; import { ActionType, type ActionEnvelope } from '../../../../../platform/agentHost/common/state/sessionActions.js'; -import { ChatState, ComponentToState, ResponsePartKind, StateComponents, ToolCallCompletedState, ToolCallConfirmationReason, ToolCallStatus, Turn } from '../../../../../platform/agentHost/common/state/sessionState.js'; +import { ChatState, ComponentToState, ResponsePartKind, StateComponents, ToolCallCompletedState, ToolCallConfirmationReason, ToolCallStatus, Turn, type ActiveTurn, type ResponsePart } from '../../../../../platform/agentHost/common/state/sessionState.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; import { AgentHostCanvas, AgentHostCanvasCollection, getAgentHostCanvasDefinitionsChangedEvent } from '../../common/agentHostCanvas.js'; import { ICanvas, ICanvasOwner } from '../../../../common/canvasReference.js'; @@ -204,6 +204,95 @@ suite('AgentHost canvases', () => { }); }); + test('does not rescan completed history while the active turn streams', () => { + const uiState: CanvasState = { ...state, instanceId: 'ui-opened' }; + const uiResource = URI.parse('ahp-canvas:/host-specific/ui-opened'); + const connection = new class extends mock() { + override readonly initializeResult = constObservable(undefined); + override getSubscription(_kind: T, channel: URI): IReference> { + const value = (channel.toString() === uiResource.toString() ? uiState : state) as ComponentToState[T]; + return { + object: { value, verifiedValue: value, onDidChange: Event.None, onWillApplyAction: Event.None, onDidApplyAction: Event.None }, + dispose: () => { }, + }; + } + }(); + const createCall = (toolCallId: string, instanceId: string, status: ToolCallStatus.Running | ToolCallStatus.Completed) => ({ + toolCallId, toolName: 'open_canvas', displayName: 'Open Canvas', + invocationMessage: 'Opening canvas', pastTenseMessage: 'Opened canvas', + status, success: true, confirmed: ToolCallConfirmationReason.NotNeeded, toolInput: JSON.stringify({ instanceId }), + } as ToolCallCompletedState); + let completedReads = 0; + const completedParts: ResponsePart[] = [{ kind: ResponsePartKind.ToolCall, toolCall: createCall('first', 'preview', ToolCallStatus.Completed) }]; + let olderReads = 0; + const older = upcastPartial({ + id: 'older', get responseParts() { + olderReads++; + return []; + }, + }); + const completed = upcastPartial({ + id: 'turn', get responseParts() { + completedReads++; + return completedParts; + }, + }); + const turns = [older, completed]; + const createChat = (activeTurn?: ActiveTurn) => upcastPartial({ resource: owner.chat.toString(), turns, activeTurn }); + const chat = observableValue('chat', createChat()); + const references = constObservable([{ resource: resource.toString() }, { resource: uiResource.toString() }]); + const context = store.add(new AgentHostCanvasCollection(owner.providerId, connection, new NullLogService())).createContext(owner, references, chat); + const requests: unknown[] = []; + store.add(autorun(reader => { + const current = context.openRequests?.read(reader); + requests.push([current?.get('preview')?.id, current?.get('ui-opened')?.id, current?.get('ui-opened')?.pending]); + })); + const streaming = (text: string) => upcastPartial({ id: 'active', responseParts: [{ kind: ResponsePartKind.Markdown, id: 'text', content: text }] }); + chat.set(createChat(streaming('a')), undefined); + chat.set(createChat(streaming('ab')), undefined); + chat.set(createChat(upcastPartial({ id: 'active', responseParts: [{ kind: ResponsePartKind.ToolCall, toolCall: createCall('second', 'ui-opened', ToolCallStatus.Running) }] })), undefined); + + assert.deepStrictEqual({ requests, completedReads, olderReads }, { + requests: [ + ['turn\u0000first', undefined, undefined], + ['turn\u0000first', 'active\u0000second', true], + ], + completedReads: 1, + olderReads: 1, + }); + }); + + test('stops scanning completed history once the requested instances are resolved', () => { + let olderReads = 0; + const older = upcastPartial({ + id: 'older', get responseParts() { + olderReads++; + return []; + }, + }); + const newest = upcastPartial({ + id: 'newest', responseParts: [{ + kind: ResponsePartKind.ToolCall, toolCall: { + toolCallId: 'open', toolName: 'open_canvas', status: ToolCallStatus.Completed, success: true, toolInput: JSON.stringify({ instanceId: 'preview' }), + } as ToolCallCompletedState, + }], + }); + const connection = new class extends mock() { + override readonly initializeResult = constObservable(undefined); + override getSubscription(_kind: T, _channel: URI): IReference> { + const value = state as ComponentToState[T]; + return { + object: { value, verifiedValue: value, onDidChange: Event.None, onWillApplyAction: Event.None, onDidApplyAction: Event.None }, + dispose: () => { }, + }; + } + }(); + const chat = constObservable(upcastPartial({ resource: owner.chat.toString(), turns: [older, newest] })); + const context = store.add(new AgentHostCanvasCollection(owner.providerId, connection, new NullLogService())).createContext(owner, constObservable([{ resource: resource.toString() }]), chat); + + assert.deepStrictEqual({ id: context.openRequests?.get().get('preview')?.id, olderReads }, { id: 'newest\u0000open', olderReads: 0 }); + }); + test('projects live metadata while leaving transient sources out of channel identity', () => { const canvas = new AgentHostCanvas(resource, state, new NullLogService()); assert.deepStrictEqual({ resource: canvas.resource.toString(), title: canvas.title, source: canvas.source?.toString() }, { diff --git a/src/vs/workbench/contrib/canvases/test/common/agentHostCanvasConsent.test.ts b/src/vs/workbench/contrib/canvases/test/common/agentHostCanvasConsent.test.ts new file mode 100644 index 000000000000..e7d80ce02f95 --- /dev/null +++ b/src/vs/workbench/contrib/canvases/test/common/agentHostCanvasConsent.test.ts @@ -0,0 +1,187 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { CancellationError } from '../../../../../base/common/errors.js'; +import Severity from '../../../../../base/common/severity.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { AgentExtensionConsentOption, type AgentCanvasOpenAnswer, type AgentCanvasOpenResult, type IAgentExtensionConsentRequest } from '../../../../../platform/agentHost/common/agent.js'; +import type { IDialogService, IPromptWithCustomCancel } from '../../../../../platform/dialogs/common/dialogs.js'; +import type { INotification, INotificationHandle } from '../../../../../platform/notification/common/notification.js'; +import { TestNotificationService } from '../../../../../platform/notification/test/common/testNotificationService.js'; +import { IProgress, IProgressNotificationOptions, IProgressService, IProgressStep, Progress, ProgressLocation } from '../../../../../platform/progress/common/progress.js'; +import type { ICanvasOpenOptions } from '../../../../common/canvasReference.js'; +import { CanvasExtensionConsentDeniedError, CanvasOpenFailedError, notifyCanvasOpenFailure, openCanvasForUser, openCanvasWithExtensionConsent } from '../../common/agentHostCanvasConsent.js'; + +suite('Agent host canvas extension consent', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + class RecordingNotificationService extends TestNotificationService { + readonly notifications: INotification[] = []; + override notify(notification: INotification): INotificationHandle { + this.notifications.push(notification); + return super.notify(notification); + } + } + + const variable = 'BLACKBIRD_AUTH_METIS_API_KEY'; + const consent = (persistable: boolean): IAgentExtensionConsentRequest => ({ id: 'consent-1', kind: 'environment', extensionName: 'user:demo', displayName: 'demo', items: [variable], persistable }); + + /** Records each prompt and answers it with the button whose label it names, or with the cancel button as Escape does. */ + function createDialog(choices: string[]) { + const prompts: { message: string; detail: unknown; buttons: string[]; cancel: string | undefined }[] = []; + const dialogService = { + async prompt(prompt: IPromptWithCustomCancel) { + const buttons = prompt.buttons ?? []; + prompts.push({ message: prompt.message, detail: prompt.detail, buttons: buttons.map(button => button.label), cancel: prompt.cancelButton.label }); + const choice = choices.shift(); + const button = buttons.find(candidate => candidate.label === choice) ?? prompt.cancelButton; + return { result: await button.run({ checkboxChecked: false }) }; + }, + } as Partial as IDialogService; + return { dialogService, prompts }; + } + + function createHost(results: AgentCanvasOpenResult[]) { + const answers: (AgentCanvasOpenAnswer | undefined)[] = []; + return { + answers, + open: async (answer?: AgentCanvasOpenAnswer) => { + answers.push(answer); + const result = results.shift(); + assert.ok(result); + return result; + }, + }; + } + + test('asks with the variable names, answers Not Now on Escape and reports a retryable denial', async () => { + const { dialogService, prompts } = createDialog([]); + const host = createHost([{ kind: 'consentRequired', consent: consent(false) }, { kind: 'consentDenied', consent: consent(false), retryable: true }]); + const error = await openCanvasWithExtensionConsent(dialogService, host.open).then(() => undefined, error => error); + assert.ok(error instanceof CanvasExtensionConsentDeniedError); + assert.deepStrictEqual({ prompts, answers: host.answers, message: error.message, retryable: error.retryable }, { + prompts: [{ + message: `Allow extension 'demo' to read sensitive environment variables?`, + detail: `'user:demo' requested: ${variable}\n\nTheir values may be credentials. Once allowed, the extension can send them anywhere or pass them to processes it starts. If you don't allow access, the extension won't load.`, + buttons: ['&&Allow'], + cancel: 'Not Now', + }], + answers: [undefined, { kind: 'consent', consentId: 'consent-1', optionId: AgentExtensionConsentOption.NotNow }], + message: `The canvas did not open because extension 'demo' was not allowed to read sensitive environment variables.`, + retryable: true, + }); + }); + + test('a retry asks the host to retry first, and a persistable request offers Always Allow and Never', async () => { + const { dialogService, prompts } = createDialog(['Al&&ways Allow']); + const host = createHost([{ kind: 'consentRequired', consent: consent(true) }, { kind: 'opened' }]); + await openCanvasWithExtensionConsent(dialogService, host.open, { retryDeniedConsent: true }); + assert.deepStrictEqual({ buttons: prompts.map(prompt => prompt.buttons), answers: host.answers }, { + buttons: [['&&Allow', 'Al&&ways Allow', '&&Never']], + answers: [{ kind: 'retry' }, { kind: 'consent', consentId: 'consent-1', optionId: AgentExtensionConsentOption.AlwaysAllow }], + }); + }); + + test('chooses each Try Again from the latest failure, keeps it after a failed retry, but not after a cancelled one', async () => { + const notificationService = new RecordingNotificationService(); + const notifications = notificationService.notifications; + const opens: (ICanvasOpenOptions | undefined)[] = []; + const failures: Error[] = [ + new CanvasOpenFailedError('reloaded'), + new CanvasExtensionConsentDeniedError(consent(true), true), + new Error('Try again after the chat finishes its current work.'), + new CancellationError(), + ]; + const open = async (options?: ICanvasOpenOptions) => { + opens.push(options); + // eslint-disable-next-line no-throw-literal + throw failures.shift()!; + }; + notifyCanvasOpenFailure(notificationService, new CanvasExtensionConsentDeniedError(consent(true), false), 'Board', open); + for (let index = 0; index < 4; index++) { + await notifications[index].actions?.primary?.[0].run(); + } + assert.deepStrictEqual({ + opens, + notifications: notifications.map(notification => ({ + severity: notification.severity, + message: notification.message, + sticky: notification.sticky, + actions: notification.actions?.primary?.map(action => action.label), + })), + }, { + // A retry after a reload asks again for consent only once the extension is declined again. + opens: [{ retryDeniedConsent: true }, undefined, { retryDeniedConsent: true }, { retryDeniedConsent: true }], + notifications: [ + { severity: Severity.Warning, message: `The canvas did not open because you chose to never allow extension 'demo' to read sensitive environment variables. To be asked again, remove it from Extension Permission Approvals in the host settings, then select Try Again.`, sticky: true, actions: ['Try Again'] }, + { severity: Severity.Warning, message: 'Canvas Board did not open because its extensions were reloaded while its extension started.', sticky: true, actions: ['Try Again'] }, + { severity: Severity.Warning, message: `The canvas did not open because extension 'demo' was not allowed to read sensitive environment variables.`, sticky: true, actions: ['Try Again'] }, + { severity: Severity.Error, message: 'Try again after the chat finishes its current work.', sticky: true, actions: ['Try Again'] }, + ], + }); + }); + + test('reports why the host did not open a canvas', async () => { + const host = createHost([{ kind: 'failed', failure: 'mismatchedDeclaration' }]); + const error = await openCanvasWithExtensionConsent(createDialog([]).dialogService, host.open).then(() => undefined, error => error); + assert.ok(error instanceof CanvasOpenFailedError); + assert.deepStrictEqual({ failure: error.failure, retryable: error.retryable }, { failure: 'mismatchedDeclaration', retryable: false }); + }); + + test('shows progress while a canvas the user asked for opens, ignores a dismissal, and offers Try Again only when it can help', async () => { + const notificationService = new RecordingNotificationService(); + const progress: unknown[] = []; + const progressService = { + withProgress: (options: IProgressNotificationOptions, task: (progress: IProgress) => Promise) => { + progress.push({ location: options.location, title: options.title, delay: options.delay }); + return task(Progress.None); + }, + } as Partial as IProgressService; + const failures: (Error | undefined)[] = [ + new CanvasOpenFailedError('dismissed'), + new CanvasOpenFailedError('reloaded'), + undefined, + new CanvasOpenFailedError('startFailed'), + new CanvasExtensionConsentDeniedError(consent(false), true), + undefined, + new Error('The canvas could not reach its database.'), + ]; + const opens: (ICanvasOpenOptions | undefined)[] = []; + const open = async (options?: ICanvasOpenOptions) => { + opens.push(options); + const failure = failures.shift(); + if (failure) { + throw failure; + } + }; + const tryAgain = () => notificationService.notifications.at(-1)!.actions!.primary![0].run(); + await openCanvasForUser(progressService, notificationService, 'Board', open); + await openCanvasForUser(progressService, notificationService, 'Board', open); + await tryAgain(); + await openCanvasForUser(progressService, notificationService, 'Board', open); + await openCanvasForUser(progressService, notificationService, 'Board', open); + await tryAgain(); + await openCanvasForUser(progressService, notificationService, 'Board', open); + assert.deepStrictEqual({ + progress, + opens, + notifications: notificationService.notifications.map(notification => ({ + severity: notification.severity, + message: notification.message, + actions: notification.actions?.primary?.map(action => action.label), + })), + }, { + progress: new Array(7).fill({ location: ProgressLocation.Notification, title: 'Opening canvas Board...', delay: 500 }), + opens: [undefined, undefined, undefined, undefined, undefined, { retryDeniedConsent: true }, undefined], + notifications: [ + { severity: Severity.Warning, message: 'Canvas Board did not open because its extensions were reloaded while its extension started.', actions: ['Try Again'] }, + { severity: Severity.Error, message: 'Canvas Board did not open because its extension did not start. Check the extension for errors.', actions: undefined }, + { severity: Severity.Warning, message: `The canvas did not open because extension 'demo' was not allowed to read sensitive environment variables.`, actions: ['Try Again'] }, + { severity: Severity.Error, message: 'Could not open canvas Board: The canvas could not reach its database.', actions: undefined }, + ], + }); + }); +}); diff --git a/src/vs/workbench/contrib/canvases/test/common/canvas.test.ts b/src/vs/workbench/contrib/canvases/test/common/canvas.test.ts index f8d42f06f606..26281f92444a 100644 --- a/src/vs/workbench/contrib/canvases/test/common/canvas.test.ts +++ b/src/vs/workbench/contrib/canvases/test/common/canvas.test.ts @@ -4,14 +4,15 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise } from '../../../../../base/common/async.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 { Verbosity } from '../../../../common/editor.js'; import { IEditorGroup, IEditorGroupsService, IEditorPart } from '../../../../services/editor/common/editorGroupsService.js'; import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; -import { CanvasInput, canPresentCanvasInGroup, ICanvasContextService } from '../../common/canvas.js'; -import { ICanvas } from '../../../../common/canvasReference.js'; +import { CanvasDefinitionOpener, CanvasInput, canPresentCanvasInGroup, getCanvasDefinitionInstanceId, getCanvasInstanceLabels, ICanvasContextService, ICanvasDefinition } from '../../common/canvas.js'; +import { ICanvas, ICanvasOwner } from '../../../../common/canvasReference.js'; suite('CanvasInput', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -120,3 +121,87 @@ suite('CanvasInput', () => { ]); }); }); + +suite('Canvas instance identifiers', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + const definition = (extensionId: string): ICanvasDefinition => ({ + canvasId: 'main', extensionId, extensionSource: 'project', displayName: 'Counter', description: 'A counter.', requiresInput: false, + }); + const instance = (type: ICanvasDefinition, instanceId: string, title = 'Counter'): ICanvas => ({ + resource: URI.parse(`canvas:/${instanceId}`), instanceId, title, source: undefined, extensionId: type.extensionId, canvasId: type.canvasId, + }); + const owner = (chat: string): ICanvasOwner => ({ providerId: 'local', session: URI.parse('session:/owner'), chat: URI.parse(`chat:/${chat}`) }); + + test('numbers new instances of a registered canvas type and labels them by their numbers', async () => { + const counter = definition('project:counter'); + const long = definition(`project:${'a'.repeat(140)}`); + const allocate = async (type: ICanvasDefinition, canvases: readonly ICanvas[]) => { + let allocated = ''; + await new CanvasDefinitionOpener().open(owner('main'), type, canvases, async instanceId => { allocated = instanceId; }); + return allocated; + }; + const first = await allocate(counter, []); + const second = await allocate(counter, [instance(counter, first), instance(counter, 'sidebar')]); + const gap = await allocate(counter, [instance(counter, first), instance(counter, `${first}-3`)]); + const longFirst = await allocate(long, []); + const longSecond = await allocate(long, [instance(long, longFirst)]); + + const base = getCanvasDefinitionInstanceId(counter); + assert.deepStrictEqual({ + first, + second, + gap, + longSecond: { length: longSecond.length, suffix: longSecond.slice(-2), sharesPrefix: longFirst.startsWith(longSecond.slice(0, -2)) }, + labels: getCanvasInstanceLabels([ + instance(counter, second), + instance(counter, 'sidebar'), + instance(counter, first), + instance(long, longSecond, 'Long'), + instance(long, longFirst, 'Long'), + ]), + }, { + first: base, + second: `${base}-2`, + gap: `${base}-2`, + longSecond: { length: 128, suffix: '-2', sharesPrefix: true }, + labels: ['Counter (2)', 'Counter (sidebar)', 'Counter (1)', 'Long (2)', 'Long (1)'], + }); + }); + + test('reserves the identifiers of overlapping opens until the chat publishes them, and releases those of failed opens', async () => { + const counter = definition('project:counter'); + const base = getCanvasDefinitionInstanceId(counter); + const opener = new CanvasDefinitionOpener(); + const requested: string[] = []; + const pending: DeferredPromise[] = []; + const open = (canvases: readonly ICanvas[], chat = 'main') => opener.open(owner(chat), counter, canvases, instanceId => { + requested.push(`${chat}:${instanceId.replace(base, 'base')}`); + const request = new DeferredPromise(); + pending.push(request); + return request.p; + }); + + const first = open([]); + const second = open([]); + const otherChat = open([], 'other'); + await pending[1].error(new Error('open failed')); + await assert.rejects(second, /open failed/); + await pending[0].complete(); + await pending[2].complete(); + await Promise.all([first, otherChat]); + // The first canvas is not published yet: its identifier stays reserved, while the failed one is free again. + const third = open([]); + await pending[3].complete(); + await third; + // Once published, canvases closed later free their identifiers. + const fourth = open([instance(counter, base), instance(counter, `${base}-2`)]); + await pending[4].complete(); + await fourth; + const fifth = open([instance(counter, `${base}-2`)]); + await pending[5].complete(); + await fifth; + + assert.deepStrictEqual(requested, ['main:base', 'main:base-2', 'other:base', 'main:base-2', 'main:base-3', 'main:base']); + }); +}); diff --git a/src/vs/workbench/contrib/canvases/test/electron-browser/canvasEditor.test.ts b/src/vs/workbench/contrib/canvases/test/electron-browser/canvasEditor.test.ts index 4f45e6f16b5b..ddca6261d1d5 100644 --- a/src/vs/workbench/contrib/canvases/test/electron-browser/canvasEditor.test.ts +++ b/src/vs/workbench/contrib/canvases/test/electron-browser/canvasEditor.test.ts @@ -18,7 +18,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { runWithFakedTimers } from '../../../../../base/test/common/virtualScheduling/runWithFakedTimers.js'; import { IAccessibleViewService, AccessibleViewType } from '../../../../../platform/accessibility/browser/accessibleView.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; -import { IBrowserViewBounds, IBrowserViewLoadingEvent } from '../../../../../platform/browserView/common/browserView.js'; +import { IBrowserViewBounds, IBrowserViewLoadError, IBrowserViewLoadingEvent } from '../../../../../platform/browserView/common/browserView.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IOpenerService, OpenOptions } from '../../../../../platform/opener/common/opener.js'; import { IEditorGroup, IEditorGroupsService, IEditorPart } from '../../../../services/editor/common/editorGroupsService.js'; @@ -48,6 +48,7 @@ suite('CanvasEditor', () => { let disposed = 0; let created = 0; const requested: string[] = []; + const reloads: boolean[] = []; const openExternal = store.add(new Emitter()); const opened: Array<{ resource: string; options: OpenOptions | undefined }> = []; const modelAttached = new DeferredPromise(); @@ -55,8 +56,11 @@ suite('CanvasEditor', () => { const warningLogged = new DeferredPromise(); const ownerVisible = observableValue('ownerVisible', true); const loadingState = store.add(new Emitter()); + let modelError: IBrowserViewLoadError | undefined; + store.add(loadingState.event(event => { modelError = event.error; })); const model = upcastPartial({ url: 'https://example.test', + get error() { return modelError; }, screenshot: harnessOptions?.screenshot, onDidChangeFocus: Event.None, onDidChangeLoadingState: loadingState.event, @@ -82,7 +86,7 @@ suite('CanvasEditor', () => { enabled: observableValue('enabled', true), isOwnerPresentable: (_reference, reader) => ownerVisible.read(reader), isPresentable: (_reference, reader) => ownerVisible.read(reader), - resolveCanvasModel: async (_reference, source) => { created++; requested.push(source.toString()); return { model: await view, reused: false }; }, + resolveCanvasModel: async (_reference, source, reload = false) => { created++; requested.push(source.toString()); reloads.push(reload); return { model: await view, reused: false }; }, }); instantiationService.stub(IAccessibilityService, { isScreenReaderOptimized: () => false }); instantiationService.stub(IAccessibleViewService, {}); @@ -126,8 +130,10 @@ suite('CanvasEditor', () => { editor, input, model, visible, attached, ownerVisible, openExternal, opened, modelAttached, openerCalled, warningLogged, parent, log, nativeBounds, errors, get disposed() { return disposed; }, get created() { return created; }, - requested, + requested, reloads, loadingState, + failPage: () => loadingState.fire({ loading: false, error: { url: model.url, errorCode: -102, errorDescription: 'ERR_CONNECTION_REFUSED' } }), + reloadButton: () => parent.querySelector('.session-canvas-status [role="button"]')!, frozenFrame: () => parent.querySelector('.session-canvas-frozen-frame')?.style.backgroundImage, message: () => parent.querySelector('.session-canvas-message')?.textContent, reconnecting: () => !!parent.querySelector('.session-canvas-editor.provider-reconnecting'), @@ -356,6 +362,128 @@ suite('CanvasEditor', () => { assert.deepStrictEqual({ created: harness.created, attached: harness.attached.includes(harness.model) }, { created: 0, attached: false }); }); + test('offers manual reload only for a failed attached page and ignores duplicate activation while pending', async () => { + const harness = createHarness(); + await harness.show(); + await harness.open(); + await harness.modelAttached.p; + await timeout(0); + const button = harness.reloadButton(); + const healthyOffered = button.style.display !== 'none'; + harness.failPage(); + const failedOffered = button.style.display !== 'none'; + const pending = new DeferredPromise(); + harness.setView(pending.p); + button.focus(); + button.click(); + button.click(); + const pendingOffered = button.style.display !== 'none'; + const pendingDisabled = button.getAttribute('aria-disabled'); + const focusTarget = harness.parent.appendChild($('button')); + focusTarget.focus(); + harness.loadingState.fire({ loading: true }); + harness.loadingState.fire({ loading: false }); + pending.complete(harness.model); + await timeout(0); + + assert.deepStrictEqual({ + healthyOffered, failedOffered, pendingOffered, pendingDisabled, + afterOffered: button.style.display !== 'none', + focusPreserved: harness.parent.ownerDocument.activeElement === focusTarget, + reloads: harness.reloads, + message: harness.message(), + attachments: harness.attached.length, + }, { + healthyOffered: false, failedOffered: true, pendingOffered: true, pendingDisabled: 'true', + afterOffered: false, focusPreserved: true, reloads: [false, true], message: '', attachments: 1, + }); + }); + + test('keeps a failed reload attached and retryable instead of recreating its page', async () => { + const harness = createHarness(); + await harness.show(); + await harness.open(); + await harness.modelAttached.p; + await timeout(0); + harness.failPage(); + const pending = new DeferredPromise(); + harness.setView(pending.p); + harness.reloadButton().click(); + pending.error(new Error('load failed')); + await timeout(0); + const afterFailure = { offered: harness.reloadButton().style.display !== 'none', attached: harness.attached.at(-1) === harness.model, message: harness.message() }; + harness.setView(Promise.resolve(harness.model)); + harness.reloadButton().click(); + harness.loadingState.fire({ loading: true }); + harness.loadingState.fire({ loading: false }); + await timeout(0); + + assert.deepStrictEqual({ afterFailure, reloads: harness.reloads, attachments: harness.attached.length, errors: harness.errors, message: harness.message() }, { + afterFailure: { offered: true, attached: true, message: 'The canvas could not be loaded.' }, + reloads: [false, true, true], attachments: 1, errors: ['[CanvasEditor] Failed to load canvas'], message: '', + }); + }); + + test('drops stale reload completions and activation after source, owner or view lifetime changes', async () => { + const results: { transition: string; offered: boolean; reloads: boolean[]; message: string | null | undefined }[] = []; + for (const transition of ['source', 'membership', 'owner', 'clear', 'dispose']) { + const harness = createHarness(); + harness.editor.setVisible(true); + await harness.open(); + await harness.modelAttached.p; + await timeout(0); + harness.failPage(); + const button = harness.reloadButton(); + const pending = new DeferredPromise(); + harness.setView(pending.p); + button.click(); + if (transition === 'source' || transition === 'membership') { + const canvas = harness.input.canvas.get()!; + harness.input.setCanvas({ ...canvas, source: undefined }, transition === 'membership'); + } else if (transition === 'owner') { + harness.ownerVisible.set(false, undefined); + } else if (transition === 'clear') { + harness.editor.clearInput(); + } else { + harness.editor.dispose(); + } + button.click(); + pending.complete(harness.model); + await timeout(0); + results.push({ transition, offered: button.style.display !== 'none', reloads: harness.reloads, message: harness.message() }); + harness.editor.dispose(); + harness.parent.remove(); + } + + assert.deepStrictEqual(results, [ + { transition: 'source', offered: false, reloads: [false, true], message: 'Reconnecting to the canvas provider…' }, + { transition: 'membership', offered: false, reloads: [false, true], message: 'Reconnecting to the canvas provider…' }, + { transition: 'owner', offered: false, reloads: [false, true], message: 'This canvas is only shown beside its owning conversation.' }, + { transition: 'clear', offered: false, reloads: [false, true], message: '' }, + { transition: 'dispose', offered: false, reloads: [false, true], message: undefined }, + ]); + }); + + test('preserves reload button focus while the provider reconnects and disables stale activation', async () => { + const harness = createHarness(); + await harness.show(); + await harness.open(); + await harness.modelAttached.p; + await timeout(0); + harness.failPage(); + const button = harness.reloadButton(); + button.focus(); + harness.input.setCanvas({ ...harness.input.canvas.get()!, source: undefined }, true); + await timeout(0); + button.click(); + + assert.deepStrictEqual({ + reconnecting: harness.reconnecting(), visible: button.style.display !== 'none', + disabled: button.getAttribute('aria-disabled'), focused: harness.parent.ownerDocument.activeElement === button, + reloads: harness.reloads, + }, { reconnecting: true, visible: true, disabled: 'true', focused: true, reloads: [false] }); + }); + test('loads a returning source while a newer in-place load is still pending', async () => { const harness = createHarness(); await harness.open(); @@ -392,6 +520,8 @@ suite('CanvasEditor', () => { harness.loadingState.fire({ loading: false, error: { url: 'https://example.test/', errorCode: -102, errorDescription: 'ERR_CONNECTION_REFUSED' } }); const whileReconnecting = { frame: harness.frozenFrame(), message: harness.message() }; harness.input.setCanvas({ ...canvas, source: URI.parse('http://127.0.0.1:54321/') }); + harness.loadingState.fire({ loading: true }); + harness.loadingState.fire({ loading: false }); await timeout(0); assert.deepStrictEqual({ whileReconnecting, afterReconnect: { frame: harness.frozenFrame(), message: harness.message() } }, { diff --git a/src/vs/workbench/contrib/chat/browser/accessibility/chatAccessibilityProvider.ts b/src/vs/workbench/contrib/chat/browser/accessibility/chatAccessibilityProvider.ts index d22fbc845a1b..cd8311c864e0 100644 --- a/src/vs/workbench/contrib/chat/browser/accessibility/chatAccessibilityProvider.ts +++ b/src/vs/workbench/contrib/chat/browser/accessibility/chatAccessibilityProvider.ts @@ -13,7 +13,7 @@ import { IContextKeyService } from '../../../../../platform/contextkey/common/co import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/accessibilityConfiguration.js'; -import { migrateLegacyTerminalToolSpecificData } from '../../common/chat.js'; +import { getTerminalExecutionTargetDescription, migrateLegacyTerminalToolSpecificData } from '../../common/chat.js'; import { getExplicitFileOrImageAttachmentSummary } from '../../common/attachments/chatVariableEntries.js'; import { IChatToolInvocation } from '../../common/chatService/chatService.js'; import { IChatResponseViewModel, isRequestVM, isResponseVM } from '../../common/model/chatViewModel.js'; @@ -59,6 +59,10 @@ export const getToolConfirmationAlert = (accessor: ServicesAccessor, toolInvocat if (v.toolSpecificData.kind === 'terminal') { const terminalData = migrateLegacyTerminalToolSpecificData(v.toolSpecificData); input = terminalData.commandLine.toolEdited ?? terminalData.commandLine.original; + const executionTarget = getTerminalExecutionTargetDescription(terminalData); + if (executionTarget) { + input = localize('terminalInputWithExecutionTarget', "{0} ({1})", input, executionTarget); + } } else if (v.toolSpecificData.kind === 'extensions') { input = JSON.stringify(v.toolSpecificData.extensions); } else if (v.toolSpecificData.kind === 'input') { diff --git a/src/vs/workbench/contrib/chat/browser/accessibility/chatResponseAccessibleView.ts b/src/vs/workbench/contrib/chat/browser/accessibility/chatResponseAccessibleView.ts index 8c04feb95cfd..062dcb822920 100644 --- a/src/vs/workbench/contrib/chat/browser/accessibility/chatResponseAccessibleView.ts +++ b/src/vs/workbench/contrib/chat/browser/accessibility/chatResponseAccessibleView.ts @@ -13,10 +13,11 @@ import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType, IAccessibleViewContentProvider } from '../../../../../platform/accessibility/browser/accessibleView.js'; import { IAccessibleViewImplementation } from '../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { IStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/accessibilityConfiguration.js'; -import { migrateLegacyTerminalToolSpecificData } from '../../common/chat.js'; +import { getTerminalExecutionTargetDescription, migrateLegacyTerminalToolSpecificData } from '../../common/chat.js'; import { autoModeRoutingTitle } from '../../common/chatAutoModeExplainability.js'; import { formatChatToolError } from '../../common/chatProgressFormatting.js'; import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; @@ -26,12 +27,13 @@ import { getChatRequestAccessibleText } from '../chatRequestText.js'; import { IToolResultInputOutputDetails, IToolResultOutputDetails, isToolResultInputOutputDetails, isToolResultOutputDetails, toolContentToA11yString } from '../../common/tools/languageModelToolsService.js'; import { ChatTreeItem, IChatWidget, IChatWidgetService } from '../chat.js'; import { isLocation, Location } from '../../../../../editor/common/languages.js'; +import { EditorContextKeys } from '../../../../../editor/common/editorContextKeys.js'; export class ChatResponseAccessibleView implements IAccessibleViewImplementation { readonly priority = 100; readonly name = 'panelChat'; readonly type = AccessibleViewType.View; - readonly when = ChatContextKeys.inChatSession; + readonly when = ContextKeyExpr.and(ChatContextKeys.inChatSession, EditorContextKeys.hoverFocused.negate()); getProvider(accessor: ServicesAccessor) { const widgetService = accessor.get(IChatWidgetService); const storageService = accessor.get(IStorageService); @@ -97,7 +99,9 @@ export function getToolSpecificDataDescription(toolSpecificData: ToolSpecificDat if (isLegacyChatTerminalToolInvocationData(toolSpecificData) || toolSpecificData.kind === 'terminal') { const terminalData = migrateLegacyTerminalToolSpecificData(toolSpecificData); - return terminalData.commandLine.userEdited ?? terminalData.commandLine.toolEdited ?? terminalData.commandLine.original; + const commandLine = terminalData.commandLine.userEdited ?? terminalData.commandLine.toolEdited ?? terminalData.commandLine.original; + const executionTarget = getTerminalExecutionTargetDescription(terminalData); + return executionTarget ? localize('terminalCommandWithExecutionTarget', "{0} ({1})", commandLine, executionTarget) : commandLine; } switch (toolSpecificData.kind) { diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityActions.ts index b3a4dacda31f..bf93db996aaa 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityActions.ts @@ -71,7 +71,7 @@ class AnnounceChatConfirmationAction extends Action2 { // Reveal the response so its confirmation widget is rendered (the // chat list is virtualized — querying before reveal can miss it). pendingWidget.reveal(lastResponse); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const confirmationWidgets = pendingWidget.domNode.querySelectorAll('.chat-confirmation-widget-container[tabindex]'); if (confirmationWidgets.length > 0) { firstConfirmationElement = confirmationWidgets[confirmationWidgets.length - 1]; diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index ea74e3a79a09..b1f31cdb5531 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -78,11 +78,14 @@ export function getChatViewModeAccessibilityHelp(): string { } export function getChatThinkingTitleAccessibilityHelp(): string { - return localize('chat.thinkingGeneratedTitles', "Completed thinking headers show Finished thinking until a summary is available, in every thinking style and progress layout. A single extracted reasoning heading is used directly without a model request. Multiple headings remain in the details and are used as the input for a generated summary. When chat.agent.thinking.generateTitles is enabled, a new summary is requested only when a live section finishes with its header in view. Opening a chat, returning to it, scrolling or expanding existing sections never generates titles. Sections that finish off-screen or in background chats do not request titles, and leaving the view cancels work that no visible chat needs. Existing summaries are reused. All reasoning headings and content remain available in the expandable details."); + return localize('chat.thinkingGeneratedTitles', "Completed thinking headers show Finished thinking until a summary is available, in every thinking style, and in every progress layout except Conversation. A single extracted reasoning heading is used directly without a model request. Multiple headings remain in the details and are used as the input for a generated summary. When chat.agent.thinking.generateTitles is enabled, a new summary is requested only when a live section finishes with its header in view. Opening a chat, returning to it, scrolling or expanding existing sections never generates titles. Sections that finish off-screen or in background chats do not request titles, and leaving the view cancels work that no visible chat needs. Existing summaries are reused. A Conversation section never uses a reasoning heading or a generated summary as its header: it shows what its tool calls did, or how long it thought when it has none. All reasoning headings and content remain available in the expandable details."); } export function getChatInputSessionLinkAccessibilityHelp(): string { - return localize('chat.inputSessionLinks', "Session links in the chat input can be opened without sending your message. Place the cursor in a session link and run Open Link{0} from the Command Palette, or use the editor's modifier-click gesture.", ''); + return [ + localize('chat.inputSessionLinks', "Session links in the chat input can be opened without sending your message. Place the cursor in a session link and run Open Link{0} from the Command Palette, or use the editor's modifier-click gesture.", ''), + localize('chat.inputSessionLinkPills', "In the Agents window, when {0} is enabled, a session link becomes a pill that shows the title and status of the session or chat that it opens, while the prompt keeps the link. Place the cursor right after the pill and press Enter{1} to open it, or open its context menu{2} to copy its link.", ChatConfiguration.InlineAttachmentsEnabled, '', ''), + ].join('\n'); } export function getCloudSandboxPreparationAccessibilityHelp(): string { @@ -106,7 +109,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui } content.push(localize('chat.attachments.filesPicker', "To attach files without searching a workspace, open Add Context{0} and choose Files. Select one or more files in the file dialog and choose Attach. In the simplified file dialog, use the checkboxes or Space to select items and Enter to attach them. Images can also be attached when the chat and selected model support them. Closing the dialog returns focus to the chat input.", '')); if (!isSessionsWindow && type !== 'inlineChat' && type !== 'quickChat') { - content.push(localize('chat.agentPickerInAttachContext', "When {0} is enabled, the default Agent picker is in Add Context. Open Add Context and choose Agent to change agents. Non-default selections remain visible in the toolbar; selecting the default Agent moves the picker back into Add Context and returns focus to the input. The Open Agent Picker shortcut{1} still opens the picker.", ChatConfiguration.AgentsPickerInAttachContextMenu, '')); + content.push(localize('chat.agentPickerInAttachContext', "When {0} is enabled, the default Agent picker is in Add Context. Open Add Context and choose Agent to change agents. A one-time spotlight introduces the + menu when onboarding is enabled. Choose Understood or press Escape to dismiss it, or activate the highlighted + menu. Non-default selections remain visible in the toolbar; selecting the default Agent moves the picker back into Add Context and returns focus to the input. The Open Agent Picker shortcut{1} still opens the picker.", ChatConfiguration.AgentsPickerInAttachContextMenu, '')); } const hasSessionWorkingSet = sessionWorkingSetEnabled && !isSessionsWindow && type !== 'inlineChat' && type !== 'quickChat'; if (hasSessionWorkingSet) { @@ -128,6 +131,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(getChatViewModeAccessibilityHelp()); content.push(localize('chat.agentRequiredModels', "When the selected agent requires specific models, the model picker only offers those models. Its footer explains that the agent defines the models. Use Tab to reach the agent link, then Enter or Space to open its definition.")); content.push(localize('chat.permissionLevelPolicy', "When Assisted permissions or Allow all is unavailable for a session, the option remains in the permissions picker as a disabled option with its reason, such as Disabled by your organization. Its hover also explains the restriction. Disabled options cannot be selected.")); + content.push(localize('chat.manageToolApprovals', "Run Chat: Manage Tool Approval from the Command Palette to manage approval rules. Expand the terminal tool to change or delete user command rules, or choose Add Command Rule. Expand the fetch tool and choose Add URL Pattern to allow requests without approving responses. Enter accepts a new rule and Escape cancels. These settings also apply to local Agent Host sessions, not remote hosts.")); content.push(localize('chat.historyRefresh', "Cloud sandbox conversations can show previously loaded messages while refreshing silently. If recent messages cannot be loaded, use Tab to reach Refresh in the banner and press Enter or Space. Refresh retries recorded history without restarting the session, waking its environment, or sending your draft.")); content.push(localize('chat.remoteConnections.renameHelp', "In the Remote Connections menu, press Tab to reach the name link in the footer, then Enter or Space to rename the shared environment. The input starts with the current name. Enter saves the name shown on other clients, and Escape cancels. Shift+Tab returns to the connection options. Renaming while Off does not enable sharing.")); content.push(localize('chat.remoteConnections.policyHelp', "If GitHub Environments is disabled by your organization, the footer explains the restriction. Press Tab to reach View Setting and Enter to open the managed setting. Shift+Tab returns to the connection options.")); @@ -150,12 +154,13 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.agentsWindowInvitation', "A running Agent Host chat may show an invitation to continue or view your sessions in the Agents Window. Only one invitation is shown across editor windows at a time. Use Tab or Shift+Tab to reach its action, Don't Show Again, or Dismiss notification. The action opens the Agents Window and highlights this session's row in the sessions list when onboarding is enabled. By default, it also opens this chat. Choose Next to highlight the New Session button, which you can activate to start another task. Disable chat.agentsWindowBanner.revealCurrentSession to open the New Session view instead and only highlight the invited session's row. Use Tab or Shift+Tab to move between the tour actions and any interactive highlighted control. Choose Understood to finish the tour, or press Escape to dismiss it. Sending another message or completing a task does not dismiss the invitation. It is temporarily hidden while the session needs attention. Dismiss notification snoozes invitations until you have created five more Agent Host sessions in editor windows and at least 24 hours have passed since the invitation appeared. Don't Show Again turns off all future Agents Window invitations.")); } if (type === 'panelChat') { + content.push(localize('chat.customizationsLocation', "Use the Customizations button to open the Customizations editor. The Chat: Customizations Location setting moves it between the Chat toolbar and the input, after the model pickers. Its hover contains counts and links for available plugins, MCP servers, skills, instructions, and hooks. Needs attention links to customization migrations and MCP servers that require sign-in, showing up to two server names. Activate a server name to sign in directly; the sign-in count opens MCP server management. The footer offers Browse Additional and a settings gear named Change Button Location. Focus the button and use Show or Focus Hover, then Tab or Shift+Tab to reach these links and Enter to activate them; Enter or Space on the button opens Customizations.")); content.push(localize('chat.customizationMigrations', "When workspace customizations need an update, a notice above the new-chat input shows how many need attention. Use Tab to reach Review Migrations and open the Migrations page. Dismiss Migration Notice for This Workspace hides the notice for that workspace, including after restarting, and returns focus to the input. The Customizations toolbar button also announces when migrations are available.")); } if (sessionArchiveNudgeShown) { content.push(sessionArchiveActionWording === ChatSessionArchiveActionWording.MarkAsDone - ? localize('chat.sessionDoneNudge', "A mark as done suggestion appears above the chat input when the session's pull requests are merged. Use Tab or Shift+Tab to reach Mark as Done, Configure Automatic Cleanup, or Dismiss Mark as Done Suggestion, then press Enter or Space. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Mark as Done\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismissing the suggestion, including with Escape while it is focused, returns to the chat input. Marking the session as done hides it from the sessions list so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Done\" section of the sessions list. You can restore it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by restoring the session.") - : localize('chat.sessionArchiveNudge', "An archive suggestion appears above the chat input when the session's pull requests are merged. Use Tab or Shift+Tab to reach Archive, Configure Automatic Cleanup, or Dismiss Archive Suggestion, then press Enter or Space. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Archive\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismissing the suggestion, including with Escape while it is focused, returns to the chat input. Archiving the session hides it from the sessions list so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Archived\" section of the sessions list. You can unarchive it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by unarchiving the session.")); + ? localize('chat.sessionDoneNudge', "A mark as done suggestion appears above the chat input when the session's pull requests are merged. Use Tab or Shift+Tab to reach Mark as Done, Configure Automatic Cleanup, or Dismiss Mark as Done Suggestion, then press Enter or Space. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Mark as Done\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismissing the suggestion, including with Escape while it is focused, returns to the chat input. Marking the session as done sets it aside so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Done\" section of the sessions list. You can restore it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by restoring the session. In a chat other than the session's main chat, the suggestion marks only that chat as done instead, and the session, its other chats, and its worktree are not affected.") + : localize('chat.sessionArchiveNudge', "An archive suggestion appears above the chat input when the session's pull requests are merged. Use Tab or Shift+Tab to reach Archive, Configure Automatic Cleanup, or Dismiss Archive Suggestion, then press Enter or Space. Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions. The explanation under What Does \"Archive\" Do? is collapsed by default. Use Tab to reach it and Enter or Space to expand or collapse it. Dismissing the suggestion, including with Escape while it is focused, returns to the chat input. Archiving the session sets it aside so you can focus on your remaining tasks. The session is not deleted. Ask your agent to find it, or look in the \"Archived\" section of the sessions list. You can unarchive it anytime. The worktree created for the session, if any, will be deleted. You can recreate it by unarchiving the session. In a chat other than the session's main chat, the suggestion archives only that chat instead, and the session, its other chats, and its worktree are not affected.")); } if (type === 'panelChat' || type === 'quickChat' || type === 'editsView' || type === 'agentView') { content.push(localize('chat.modelPicker.autoMode', "In the model picker, Auto is the first model in the Copilot tab and is selected like any other model. Provider tabs and search remain available. Browsing another provider does not change the selected model.")); @@ -175,6 +180,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.localModel.rows', "On-device models: when this device has an NVIDIA GPU that can run one, the model picker lists it in its On This Device tab, right after the Copilot tab, in Copilot chats that run on the local agent host. From the model list, use Left and Right Arrow to switch tabs and Up and Down Arrow to focus a model's row. Each model has a single row, like a cloud model's: its name, an Active badge while it is loaded or loading, and the effort level and context size, such as Medium and 128K. A screen reader also reads the model's state while it isn't ready, such as Downloading 42% or Not loaded; the detail page and the notice above the chat input show it too. Tab reaches the row's only button, labelled with the model's effort level and context size, or, for a model that isn't downloaded, Download (Set Up for model files already on this device), the download's progress, such as 42%, or Paused; it opens the model's detail page; Right Arrow on the row opens it too. Actions such as Retry, Pause, Resume, Download and Set Up are on the detail page, and those for a running, paused or failed step also in the notice above the chat input. Pause stops a download or update so it can be resumed later; Cancel takes back a model change, keeping the loaded model while the change waits for running responses, or stops loading a model, and Stop Now ends the responses a model change is waiting for. Once chosen, these read Pausing, Cancelling or Stopping and can't be chosen again until the model's state changes. A model that isn't downloaded can't be selected: a screen reader reads Not downloaded with its row, and Enter opens its detail page, which has its license, size and Download button. Enter on an installed model selects it and starts loading it right away, without asking. Only one on-device model is loaded at a time: selecting another one unloads the loaded one once its running responses finish, and the notice above the chat input shows how many responses it is waiting for, then the load, with Cancel.")); content.push(localize('chat.localModel.details', "A model's detail page has a heading for each section; the first, the model's name, also gives the model's state, such as Ready or Downloading 41%. Its header has icon buttons named after the model; Tab reaches them and Left and Right Arrow move between them. The first shows the state and what it does: Load for a model that isn't loaded, which loads it right away; Resume while it is paused; Stop while it is loaded; and while the model is busy, an in-progress indicator named with the state and the action that stops it, such as Loading, Cancel, or Downloading 41%, Pause, or Cancel while a model change waits for running responses, which keeps the loaded model. Once chosen, it reads Pausing, Cancelling or Stopping and can't be chosen again until the state changes. Then come Update, when an update is available, with its size, and Remove, which asks first. Use Tab and Shift+Tab to move between its links, buttons, choices and switches, Back to Models to return to the list, and Escape to close the picker. A warning at the top says when this device doesn't have the GPU memory for the model at its context size. To download a model, its page states the download size, the free space needed, the source and the license; choosing Download, or Set Up for model files already on this device, agrees to exactly what the page shows and downloads it in the background. Downloading doesn't need llama.cpp, but loading a model does, and VS Code doesn't install it. When no llama-server is set, or the one set doesn't support the model or is too old, loading the model shows an error on its page and in the notice above the chat input, with Get llama.cpp, which opens directions for getting a build that supports the model, Open Settings, which opens the Llama Server Path setting (chat.copilot.localModel.llamaServerPath) to point to its llama-server, and Retry. While a model downloads, its page shows a progress bar and the time remaining. While it loads, the page shows Loading model or Warming up, or Reloading when a new context size loads it again, or Retrying without speculative decoding, and why, when this llama.cpp build crashed with it, and, when an earlier load of the same model and context size took a known time, a progress bar and the time remaining estimated from it, which counts down and reads Almost done once that time has passed; a screen reader hears when the step changes. An installed model's page has an Effort Level choice when the model supports it, which sets its effort level for this chat, like a cloud model's effort level, without reloading it; the row and the readout show the new level. It also has a Context choice of the model's context sizes, each read with the GPU memory it needs. Changing the context size of a loaded model reloads it right away without asking, once its running responses finish; for a model that isn't loaded, it applies the next time it loads. In these choices, use the arrow keys to move between options, then Enter or Space to choose one. The page also has the Use in Auto switch, which lets Auto run some requests on this device with cloud fallback. The page updates in place as the model's state changes, and a change of state is announced.")); content.push(localize('chat.localModel.notice', "While an on-device model is selected, the readout beside the model name in the chat input shows its state while it isn't ready, such as Loading, Reloading or Not loaded, and its effort level and context size once it is; a screen reader hears all of them, and the readout opens the model's detail page. On-device models show no notifications. Instead, one notice above the chat input shows an error, a running download, a model loading or reloading or another step with a progress bar and the busy indicator of an active session, or a pause, with its actions, such as the Pause, Cancel or Stop Now button, Retry, Resume or Review, which opens the model's detail page; use Tab or Shift+Tab to reach them. The notice has no Details action: the model's detail page opens from the readout or the model picker. A load's progress is estimated from the last comparable load, with a time remaining that counts down on screen and then reads almost done; the first load shows no estimate. After Pause, Cancel or Stop Now, the notice says Pausing, Cancelling or Stopping right away, and so does the button, which can't be chosen again. While a selected model waits for the loaded model's running responses, the notice says how many it waits for, with Stop Now, which asks first, and Cancel, which keeps the loaded model; a load always has Cancel. For a screen reader its text updates are throttled, and it hears when the step changes, pauses or fails. When an on-device model is ready, the same notice offers to switch to it. Use in Auto is off until you turn it on in the model's detail page, where its description also says that local models may not use the same safety filters as GitHub Copilot-provided models. With Auto selected and Use in Auto on, Auto may run some requests on this device and uses a cloud model when the device can't respond; a reply that ran on this device shows On-device after the model name, and a notice tells you the first time a cloud model was used instead in a chat. The Command Palette also has Set Up On-Device Model, which opens the detail page of the model to set up, and Cancel On-Device Model Download, Resume On-Device Model Download, Retry On-Device Model Setup, Update On-Device Model, Remove On-Device Model, Start On-Device Model, Stop On-Device Model and Make On-Device Model Active.")); + content.push(localize('chat.localModel.fusion', "When Auto is presented as Copilot Fusion, the Use in Auto switch reads Use in Copilot Fusion, and on-device model notices, reply labels, and suggestions to use Auto name Copilot Fusion instead.")); } content.push(localize('chat.fileChangesDisclosure', 'File change summaries show the total files, additions, and deletions. Focus the disclosure and press Enter or Space to show or hide the individual files. Focus an additions and deletions label and press Enter or Space to open the changes in a diff editor.')); } @@ -225,10 +231,12 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.vscodePetJumpGame', "When the new-session welcome heading is visible, focus Blobby with Tab, open its context menu{0}, choose Play Jump Game with the arrow keys, and press Enter. This moves Blobby to the welcome perch and starts the game without dragging, including with reduced motion enabled. Hold Space to charge and release it to jump; use Left and Right Arrow to hop or aim. Higher sections add moving ledges, crumbling ledges, and wall-bounce challenges. Hops counts new highest-platform landings, with your locally saved high score underneath. Accessibility help and the accessible view pause the game, including moving platforms and crumble timers. Press Escape to return to the perch, or Tab back to the input to end the game.", '')); } content.push(localize('chat.blobby', "Type /blobby to unlock the True Name achievement without sending a chat request. If Blobby is off, the command turns it on; if it is already on, it opens the Color tab in Customize Blobby. Change Color in the pet's context menu always opens Color, where Stable and Insiders are free choices. True Name unlocks solid presets and custom colors; activating that achievement also opens Color. Use the color picker or enter an opaque hex color such as #ff8800, then activate Apply Color. Unapplied custom colors are discarded when you leave the tab or close the modal. Apply to, at the top of the Achievements and Color tabs, chooses whether a hat or color changes Both Windows, only the Editor Window, or only the Agents Window. Both Windows is selected whenever Customize Blobby opens.")); + content.push(localize('chat.inputSkills', "To open a skill accepted from slash-command suggestions, place the cursor within its reference, not after it, in the chat input or while editing a sent message. Open the Command Palette{0} and run Chat: Open Skill at Cursor. This opens the bound skill file without sending your message. Skills without a resource cannot be opened. In a sent message, use Tab to focus a skill link and Enter to open it.", '')); if (inlineAttachmentsEnabled) { content.push(localize('chat.attachments.inline', "Attached context, such as files, folders, images, symbols, tools, and pull requests, appears as pills inline with your prompt, where it was added. Each pill counts as one character: use the arrow keys to move across it, hold Shift to select it, and press Backspace or Delete to remove it along with its attachment. Undo restores it. The attachment's name is announced as the cursor moves across it. When the cursor is right after a pill for a file, folder, or other resource, the pill is highlighted, and Enter opens it{0} instead of sending the request, while opening the context menu{1} shows the pill's context menu. Dropped files are inserted where they are dropped, and other attachments at the cursor. References you type with # or @, and tool references, also become pills. To inspect a pill, place the cursor next to it and invoke Show or Focus Hover{2}. Sent requests show the same pills inline. The prompt sent to the agent mentions each pill where it appears by its attachment's name and location, and attaches each attachment once, however often it is mentioned. To show attachments above the input instead, turn off {3}.", '', '', '', ChatConfiguration.InlineAttachmentsEnabled)); content.push(localize('chat.attachments.inlineMove', "Drag a pill to move it within the same chat input. Only that pill moves, even when other text is selected. The insertion marker shows where it will be placed. Press Escape or drop outside the input to cancel. To move a pill with the keyboard, select it with Shift and an arrow key, cut{0}, move the cursor, and paste{1}. Undo{2} reverses a drag move.", '', '', '')); content.push(localize('chat.attachments.removal', 'To remove attached contexts, focus an attachment and press Delete or Backspace.')); + content.push(localize('chat.attachments.githubHover', "Hover over an inline GitHub issue or pull request pill to preview details after the configured workbench hover delay. Moving the keyboard cursor immediately after the pill also reveals the same preview without moving focus out of the composer. Click the pill or press Enter while it is highlighted to open the referenced item instead of sending the request. Invoke Show or Focus Hover{0} to enter the editor hover, which supports Accessible View{1} and Accessibility Help{2}. Escape dismisses the preview without changing your draft.", '', '', '')); } else { if (supportsFileReferences) { content.push(localize('chat.attachments.inlineReferences', 'To mention an attached context item at a specific position without removing it from the attached context, type # or @ and select the attachment from the suggestions.')); @@ -236,6 +244,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui } content.push(localize('chat.attachments.removal', 'To remove attached contexts, focus an attachment and press Delete or Backspace.')); } + content.push(localize('chat.attachments.githubRequestPills', "A GitHub issue or pull request pill in a sent request previews its details after the configured workbench hover delay when you hover over it or use Tab to focus it. Click the pill, or press Enter or Space while it is focused, to open the referenced item instead of editing the request. Escape dismisses the preview.")); content.push(localize('workbench.action.chat.toggleSpeechToText', 'To dictate your request into the input box, invoke the Dictate command{0}. Invoke it again to stop; recording start and stop are indicated by accessibility signals.', '')); content.push(localize('workbench.action.chat.cancelSpeechToText', 'While dictating, invoke the Cancel Dictation command{0} to stop and discard the dictated text.', '')); content.push(localize('chat.speechToText.contextMenu', 'To choose a microphone or turn off dictation or Voice Mode, focus the microphone button in the input toolbar and open its context menu{0} (for example Shift+F10).', '')); @@ -275,7 +284,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('workbench.action.chat.focusLastFocusedItem', 'To return to the last chat response you focused, invoke the Focus Last Focused Chat Response command{0}.', getChatFocusKeybindingLabel(keybindingService, type, 'lastFocused'))); content.push(localize('workbench.action.chat.focusInput', 'To focus the input box for chat requests, invoke the Focus Chat Input command{0}.', getChatFocusKeybindingLabel(keybindingService, type, 'input'))); content.push(localize('chat.progressVerbosity', 'As the chat request is being processed, you will hear verbose progress updates if the request takes more than 4 seconds. This includes information like searched text for with X results, created file , or read file . This can be disabled with accessibility.verboseChatProgressUpdates.')); - content.push(localize('chat.persistentProgress', "The {0} setting defaults to Draw in all versions of VS Code. Experiments can override the default; an explicit setting takes precedence. Choose Draw, Draw (Monochrome), or Draw (Monochrome, No Icon) to keep a working progress indicator at the bottom until the response finishes. When the response finishes, its toolbar takes the indicator's place. Draw ties and unravels the VS Code mark with fast parabolic ribbon motion and a brief rest between loops. The No Icon variant hides only the decorative VS Code icon; progress text and spoken updates are unchanged. The {1} setting defaults to Compact: tool calls preview while running, then collapse in place to a single summary row when thinking or response text resumes, or the response finishes. Choose Verbose to keep tool chains expanded without a group header or an internal scrolling limit. Choose Conversation to collapse reasoning and tool calls together into one section between response text; the section starts collapsed, its header names the current tool call, or the heading of the current reasoning summary (Thinking when the reasoning has no heading), while it runs, and shows a generated summary or Finished thinking once it finishes. Use Tab to focus a summary and press Enter or Space to expand or collapse its tool calls. Automatic collapse waits until keyboard focus leaves the group. Completed responses still follow {2}. Except in Conversation, reasoning appears separately as collapsible previews; focus a reasoning header and press Enter or Space to expand or collapse it. Standalone tools keep their decorative icons. Terminal activity animations and subagent pills are unchanged. The indicator reports counts of running subagents and background commands, including work started in earlier requests, whether the main response is progressing or idle. Requests for your input, approval, plan review, or authentication take priority over these counts. After 90 seconds without response activity and with no active tools, progress tasks, or known background work, it reports that the response is taking longer than usual. Long-running foreground terminal commands do not trigger this message. Reduced motion disables the collapse animation and the Conversation header's transitions between steps, and keeps the indicator visible without animation. Spoken progress updates are controlled by accessibility.verboseChatProgressUpdates.", ChatConfiguration.PersistentProgress, ChatConfiguration.PersistentProgressVerbosity, ChatConfiguration.CollapseCompletedResponses)); + content.push(localize('chat.persistentProgress', "The {0} setting defaults to Draw in all versions of VS Code. Experiments can override the default; an explicit setting takes precedence. Choose Draw, Draw (Monochrome), or Draw (Monochrome, No Icon) to keep a working progress indicator at the bottom until the response finishes. When the response finishes, its toolbar takes the indicator's place. Draw ties and unravels the VS Code mark with fast parabolic ribbon motion and a brief rest between loops. The No Icon variant hides only the decorative VS Code icon; progress text and spoken updates are unchanged. The {1} setting defaults to Compact: tool calls preview while running, then collapse in place to a single summary row when thinking or response text resumes, or the response finishes. Choose Verbose to keep tool chains expanded without a group header or an internal scrolling limit. Choose Conversation to collapse reasoning and tool calls together into one section between response text; the section starts collapsed, its header names the current tool call, or the heading of the current reasoning summary (Thinking, followed by the first line of the reasoning, when the reasoning has no heading), while it runs. Once it finishes, the header shows what its tool calls did, followed by the time its reasoning and tool calls took when all of it was recorded; a section without tool calls shows how long it thought. Inside a section with tool calls, each reasoning run is a row naming how long it thought; focus the row and press Enter or Space to expand or collapse its reasoning. Use Tab to focus a summary and press Enter or Space to expand or collapse its tool calls. Automatic collapse waits until keyboard focus leaves the group. Completed responses still follow {2}. Except in Conversation, reasoning appears separately as collapsible previews; focus a reasoning header and press Enter or Space to expand or collapse it. Standalone tools keep their decorative icons. Terminal activity animations and subagent pills are unchanged. The indicator reports counts of running subagents and background commands, including work started in earlier requests, whether the main response is progressing or idle. Requests for your input, approval, plan review, or authentication take priority over these counts. After 90 seconds without response activity and with no active tools, progress tasks, or known background work, it reports that the response is taking longer than usual. Long-running foreground terminal commands do not trigger this message. Reduced motion disables the collapse animation and the Conversation header's transitions between steps, and keeps the indicator visible without animation. Spoken progress updates are controlled by accessibility.verboseChatProgressUpdates.", ChatConfiguration.PersistentProgress, ChatConfiguration.PersistentProgressVerbosity, ChatConfiguration.CollapseCompletedResponses)); content.push(getChatThinkingTitleAccessibilityHelp()); content.push(localize('chat.persistentProgressSticky', "When {0} is disabled, which is the default, and the input is below the conversation, the working progress indicator stays above the input's status pills when it would otherwise scroll out of view. Without pills, it stays directly above the input. Scrolling back to its position returns it to the response. Enable {0} to show the normal input border instead of sticky progress. Its progress action, when available, remains reachable with Tab or Shift+Tab. Moving the indicator does not repeat spoken progress updates.", ChatConfiguration.ProgressBorder)); content.push(localize('chat.persistentProgressHandoff', "While a response is running, automatically collapsing a reasoning or tool preview keeps a visible header in place. If the header is above the visible content but its details are visible, it moves below the pinned prompt, or to the top of the viewport when there is no pinned prompt. Only the space needed for the visible viewport is reserved. That space is removed when the response finishes or is stopped, after any pending transition and content rendering finish. Expanding a preview consumes reserved space as its content grows. Scrolling to the bottom removes the reserved space. Manual collapses do not add padding. The following response content appears after an automatic collapse finishes. Reduced motion skips this delay. If keyboard focus keeps a preview open, new content continues to appear without waiting for focus to move.")); @@ -290,7 +299,8 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui } content.push(localize('workbench.action.chat.announceConfirmation', "To focus pending chat confirmation dialogs or MCP authentication prompts, invoke the Chat: Focus Chat Confirmation command{0}. Use Tab to reach a button and Enter or Space to activate it. Invoke the command again to return to the chat input.", '')); content.push(localize('chat.mcpAuthenticationProgress', "After you activate Authenticate, authentication progress and its outcome are announced. Errors are announced through notifications. An incomplete or cancelled attempt is not reported as a success.")); - content.push(localize('chat.sandboxPathGrant', "When a sandbox confirmation offers path access, review the granted path and whether it allows reading or reading and writing. A grant may cover a folder rather than only the blocked file. The header asks to add access to user sandbox settings and retry. Allow saves access in your user settings and retries inside the sandbox. These settings are shared with connected agent hosts across workspaces and sessions. Skip declines access. Use Tab to reach these choices.")); + content.push(localize('chat.sandboxPathGrant', "When a sandbox confirmation offers path access, review the granted path and whether it allows reading or reading and writing. A grant may cover a folder rather than only the blocked file. Allow for This Session is the default: access is shared by chats in this session and saved when you resume it, without changing user settings. When supported for the chat's workspace folders, the approval dropdown offers Allow for This Workspace. This saves access privately on the agent host for chats using the same folders, without changing workspace settings. Allow for This User saves access in your user settings and shares it with connected agent hosts across workspaces and sessions. All scopes retry inside the sandbox and remain subject to your organization's restrictions. Skip declines access. Use Tab to reach More Actions, Enter or Space to open the approval dropdown, Up or Down Arrow to choose a scope, and Enter to approve. Escape closes the dropdown without approving.")); + content.push(localize('chat.sandboxSessionPath', "Session folders may be labeled with this session or another session's name. This describes the location, not the duration of access.")); content.push(localize('chat.assistedPermissionsFeedback', "Some Assisted permissions confirmations include an optional feedback field before their buttons. Use Tab to reach it and describe what the approval system should have understood, then choose a button or accept the confirmation{0}. The feedback is sent with your decision to help improve Assisted permissions. It doesn't change the decision or teach Copilot a rule, and it isn't saved with the chat.", '')); content.push(localize('chat.showHiddenTerminals', 'If there are any hidden chat terminals, you can view them by invoking the View Hidden Chat Terminals command{0}.', '')); content.push(localize('chat.focusMostRecentTerminal', 'To focus the last chat terminal that ran a tool, invoke the Focus Most Recent Chat Terminal command{0}.', ``)); @@ -302,7 +312,8 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.scrollQuestionDetails', "The question title stays visible while its details and answers scroll together. Use Tab to focus Question details, then use the arrow keys or Page Up and Page Down to scroll.")); content.push(localize('chat.maximizeQuestion', "Use the Maximize button in the question header to give a long question more room, and Restore Size to shrink it again. Escape also restores the size.")); content.push(localize('chat.questionPrimaryButton', "The primary button scrolls to the answers while they are out of view. Once they are visible, it moves to the next question or submits.")); - content.push(localize('chat.questionYesNo', "Yes or no questions are answered with the No and Yes buttons. When allowed, type a custom answer in the Something else field instead.")); + content.push(localize('chat.questionYesNo', "Yes or no questions use a single-select list with Yes followed by No. Use the arrow keys to select an option and Enter to confirm.")); + content.push(localize('chat.questionCustomAnswer', "When a custom answer is allowed, Down Arrow from the last option moves to the custom answer field below the options, and Up Arrow at the start of the field returns to the last option. In single-select questions, a selected option is the answer and any custom answer text is kept but ignored; typing in the field answers with the text instead.")); content.push(localize('chat.previousQuestionCarouselQuestion', 'When a chat question is focused, move to the previous question{0}.', '')); content.push(localize('chat.nextQuestionCarouselQuestion', 'When a chat question is focused, move to the next question{0}.', '')); content.push(localize('chat.planReviewEditor', 'When a plan is ready for review, open it from the chat response to edit the plan and add line comments. Use the editor toolbar to navigate, clear, or submit feedback. Choose an implementation action from the plan review in Chat.')); diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatActions.ts index 51ecb78f089d..983e534628dd 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatActions.ts @@ -9,6 +9,7 @@ import { WorkbenchActionExecutedClassification, WorkbenchActionExecutedEvent } f import { coalesce } from '../../../../../base/common/arrays.js'; import { timeout } from '../../../../../base/common/async.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { ChatCustomizationsLocationContext } from '../../common/customizationsLocation.js'; import { safeIntl } from '../../../../../base/common/date.js'; import { Event } from '../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; @@ -23,9 +24,9 @@ import { EditorAction2 } from '../../../../../editor/browser/editorExtensions.js import { IRange } from '../../../../../editor/common/core/range.js'; import { localize, localize2 } from '../../../../../nls.js'; import { Action2, ICommandPaletteOptions, MenuId, MenuRegistry, registerAction2 } from '../../../../../platform/actions/common/actions.js'; -import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { CommandsRegistry, ICommandService } from '../../../../../platform/commands/common/commands.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; -import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyExpr, ContextKeyExpression, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IsLinuxContext, IsWindowsContext } from '../../../../../platform/contextkey/common/contextkeys.js'; import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; @@ -38,11 +39,12 @@ import product from '../../../../../platform/product/common/product.js'; import { GitHubPaths, IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { ActiveEditorContext } from '../../../../common/contextkeys.js'; -import { IViewDescriptorService, ViewContainerLocation } from '../../../../common/views.js'; +import { ViewContainerLocation } from '../../../../common/views.js'; import { ChatEntitlement, IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; import { ACTIVE_GROUP, AUX_WINDOW_GROUP, SIDE_GROUP } from '../../../../services/editor/common/editorService.js'; +import { IEditorGroup } from '../../../../services/editor/common/editorGroupsService.js'; +import { NewTabButtonEntryAction, NewTabButtonHidden } from '../../../../browser/parts/editor/newTabButton.js'; import { IHostService } from '../../../../services/host/browser/host.js'; -import { IWorkbenchLayoutService, Parts } from '../../../../services/layout/browser/layoutService.js'; import { IPreferencesService } from '../../../../services/preferences/common/preferences.js'; import { IViewsService } from '../../../../services/views/common/viewsService.js'; import { EXTENSIONS_CATEGORY, IExtensionsWorkbenchService } from '../../../extensions/common/extensions.js'; @@ -54,9 +56,11 @@ import { IChatInputNoticeHubService } from '../widget/input/chatInputNoticeHub.j import { ModifiedFileEntryState } from '../../common/editing/chatEditingService.js'; import { IChatModel, IChatResponseModel } from '../../common/model/chatModel.js'; import { ChatMode, IChatMode } from '../../common/chatModes.js'; +import { agentReg } from '../../common/requestParser/chatRequestParser.js'; import { ElicitationState, IChatService, IChatToolInvocation } from '../../common/chatService/chatService.js'; import { ISCMHistoryItemChangeRangeVariableEntry, ISCMHistoryItemChangeVariableEntry } from '../../common/attachments/chatVariableEntries.js'; import { IChatRequestViewModel, IChatResponseViewModel, isRequestVM } from '../../common/model/chatViewModel.js'; +import { IChatViewHostService } from '../chatViewHost.js'; import { IChatWidgetHistoryService } from '../../common/widget/chatWidgetHistoryService.js'; import { ChatAgentLocation, ChatConfiguration, ChatModeKind, ChatProgressAnimation, ChatProgressVerbosity, getDefaultNewChatSessionTypeAndReason } from '../../common/constants.js'; import { AICustomizationManagementCommands } from '../aiCustomization/aiCustomizationManagement.js'; @@ -69,13 +73,16 @@ import { IChatEditorOptions } from '../widgetHosts/editor/chatEditor.js'; import { ChatEditorInput, showClearEditingSessionConfirmation } from '../widgetHosts/editor/chatEditorInput.js'; import { convertBufferToScreenshotVariable } from '../attachments/chatScreenshotContext.js'; import { getChatSessionType, getNewChatSessionResource } from '../../common/model/chatUri.js'; -import { localChatSessionType } from '../../common/chatSessionsService.js'; +import { isAgentHostSessionResource, localChatSessionType } from '../../common/chatSessionsService.js'; import { getDocumentationUrl, PromptsType } from '../../common/promptSyntax/promptTypes.js'; import { generateUuid } from '../../../../../base/common/uuid.js'; import { ChatViewPane } from '../widgetHosts/viewPane/chatViewPane.js'; export const CHAT_CATEGORY = localize2('chat.category', 'Chat'); +/** Opens host-wide tool approvals for an agent host session; resolves false when the host is unavailable. */ +export const MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID = '_chat.agentHost.manageToolApprovals'; + const COPILOT_CLI_AGENT_HOST_PROVIDER_ID = 'copilotcli'; export const ACTION_ID_NEW_CHAT = `workbench.action.chat.newChat`; @@ -267,8 +274,19 @@ export interface IChatViewOpenRequestEntry { const OPEN_CHAT_QUOTA_EXCEEDED_DIALOG = 'workbench.action.chat.openQuotaExceededDialog'; +/** Whether opening chat with `opts`, or in `mode`, asks for what only local chat serves: Ask or Edit mode, or a chat participant. */ +function requiresLocalChat(opts: IChatViewOpenOptions | undefined, mode: IChatMode | undefined, chatAgentService: IChatAgentService): boolean { + const kind = opts?.mode ?? mode?.kind; + if (kind === ChatModeKind.Ask || kind === ChatModeKind.Edit) { + return true; + } + // Only a registered participant needs local chat: a query may start with `@` for other reasons, such as a decorator + const name = opts?.query?.trimStart().match(agentReg)?.[1]; + return !!name && (chatAgentService.getAgentsByName(name).length > 0 || !!chatAgentService.getAgentByFullyQualifiedId(name)); +} + abstract class OpenChatGlobalAction extends Action2 { - constructor(overrides: Pick, private readonly mode?: IChatMode) { + constructor(overrides: Pick, private readonly mode?: IChatMode, precondition?: ContextKeyExpression) { super({ ...overrides, icon: Codicon.chatSparkle, @@ -277,6 +295,7 @@ abstract class OpenChatGlobalAction extends Action2 { precondition: ContextKeyExpr.and( ChatContextKeys.Setup.hidden.negate(), ChatContextKeys.Setup.disabledInWorkspace.negate(), + precondition, ) }); } @@ -284,8 +303,16 @@ abstract class OpenChatGlobalAction extends Action2 { override async run(accessor: ServicesAccessor, opts?: string | IChatViewOpenOptions): Promise { opts = typeof opts === 'string' ? { query: opts } : opts; - const chatService = accessor.get(IChatService); const widgetService = accessor.get(IChatWidgetService); + // The Agents view shows sessions, not local chat: what only local chat serves is not available there. The Ask and Edit + // mode actions are disabled by their precondition; this covers what a precondition cannot see, the arguments, such as + // a mode or a chat participant that the caller asks for. + if (accessor.get(IContextKeyService).getContextKeyValue(ChatContextKeys.agentsViewActive.key) && requiresLocalChat(opts, this.mode, accessor.get(IChatAgentService))) { + accessor.get(INotificationService).info(localize('chat.localChatUnavailable', "Ask and Edit modes and chat participants are not available while the Agents view is enabled.")); + return; + } + + const chatService = accessor.get(IChatService); const toolsService = accessor.get(ILanguageModelToolsService); const hostService = accessor.get(IHostService); const chatAgentService = accessor.get(IChatAgentService); @@ -640,7 +667,7 @@ export abstract class ModeOpenChatGlobalAction extends OpenChatGlobalAction { id: getOpenChatActionIdForMode(mode), title: localize2('openChatMode', "Open Chat ({0})", mode.label.get()), keybinding - }, mode); + }, mode, mode.kind === ChatModeKind.Ask || mode.kind === ChatModeKind.Edit ? ChatContextKeys.agentsViewActive.negate() : undefined); } } @@ -741,39 +768,11 @@ export function registerChatActions() { } async run(accessor: ServicesAccessor) { - const layoutService = accessor.get(IWorkbenchLayoutService); - const viewsService = accessor.get(IViewsService); - const viewDescriptorService = accessor.get(IViewDescriptorService); const widgetService = accessor.get(IChatWidgetService); - - const chatLocation = viewDescriptorService.getViewLocationById(ChatViewId); - const chatVisible = viewsService.isViewVisible(ChatViewId); - if (chatVisible) { - this.updatePartVisibility(layoutService, chatLocation, false); - } else { - this.updatePartVisibility(layoutService, chatLocation, true); + if (await accessor.get(IChatViewHostService).toggle()) { (await widgetService.revealWidget())?.focusInput(); } } - - private updatePartVisibility(layoutService: IWorkbenchLayoutService, location: ViewContainerLocation | null, visible: boolean): void { - let part: Parts.PANEL_PART | Parts.SIDEBAR_PART | Parts.AUXILIARYBAR_PART | undefined; - switch (location) { - case ViewContainerLocation.Panel: - part = Parts.PANEL_PART; - break; - case ViewContainerLocation.Sidebar: - part = Parts.SIDEBAR_PART; - break; - case ViewContainerLocation.AuxiliaryBar: - part = Parts.AUXILIARYBAR_PART; - break; - } - - if (part) { - layoutService.setPartHidden(!visible, part); - } - } }); @@ -802,7 +801,7 @@ export function registerChatActions() { }, { id: MenuId.EditorTitle, group: 'navigation', - when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('copilot'), ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('new-session'), ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('comment')), + when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), NewTabButtonHidden, ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('copilot'), ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('new-session'), ChatContextKeys.newChatButtonExperimentIcon.notEqualsTo('comment')), order: 1 }], }); @@ -815,6 +814,24 @@ export function registerChatActions() { } }); + registerAction2(class NewChatEditorFromNewTabButtonAction extends NewTabButtonEntryAction { + constructor() { + super({ + id: ACTION_ID_OPEN_CHAT + '.fromNewTabButton', + title: localize2('interactiveSession.open', "New Chat Editor"), + icon: Codicon.commentDiscussion, + order: 3, + when: ChatContextKeys.enabled + }); + } + + protected override openTab(accessor: ServicesAccessor, group: IEditorGroup): Promise { + const widgetService = accessor.get(IChatWidgetService); + const input = getNewChatEditorInput(accessor); + return widgetService.openSession(input.resource, group, input.options); + } + }); + registerAction2(class NewChatEditorCopilotIconAction extends Action2 { constructor() { super({ @@ -827,7 +844,7 @@ export function registerChatActions() { menu: [{ id: MenuId.EditorTitle, group: 'navigation', - when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('copilot')), + when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), NewTabButtonHidden, ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('copilot')), order: 1 }], }); @@ -852,7 +869,7 @@ export function registerChatActions() { menu: [{ id: MenuId.EditorTitle, group: 'navigation', - when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('new-session')), + when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), NewTabButtonHidden, ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('new-session')), order: 1 }], }); @@ -877,7 +894,7 @@ export function registerChatActions() { menu: [{ id: MenuId.EditorTitle, group: 'navigation', - when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('comment')), + when: ContextKeyExpr.and(ActiveEditorContext.isEqualTo(ChatEditorInput.EditorID), NewTabButtonHidden, ChatContextKeys.newChatButtonExperimentIcon.isEqualTo('comment')), order: 1 }], }); @@ -1631,6 +1648,7 @@ export function registerChatActions() { when: ContextKeyExpr.and( ChatContextKeys.enabled, ContextKeyExpr.equals('view', ChatViewId), + ChatCustomizationsLocationContext.isEqualTo('chatToolbar'), ), order: 6 }); @@ -1954,6 +1972,18 @@ registerAction2(class EditToolApproval extends Action2 { async run(accessor: ServicesAccessor, scope?: 'workspace' | 'profile' | 'session'): Promise { const confirmationService = accessor.get(ILanguageModelToolsConfirmationService); const toolsService = accessor.get(ILanguageModelToolsService); + const commandService = accessor.get(ICommandService); + const notificationService = accessor.get(INotificationService); + if (scope === undefined) { + const sessionResource = accessor.get(IChatWidgetService).lastFocusedWidget?.viewModel?.sessionResource; + if (sessionResource && isAgentHostSessionResource(sessionResource)) { + if (!CommandsRegistry.getCommand(MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID) + || !await commandService.executeCommand(MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID, sessionResource)) { + notificationService.info(localize('chat.agentHostToolApprovalsUnavailable', "Tool approvals for this agent host are not available yet. Try again once it has connected.")); + } + return; + } + } confirmationService.manageConfirmationPreferences([...toolsService.getAllToolsIncludingDisabled()], scope ? { defaultScope: scope } : undefined); } }); diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.ts index 2ccc116bdd58..6cb052a470c1 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { getActiveElement, isHTMLElement } from '../../../../../base/browser/dom.js'; import { AsyncIterableProducer } from '../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../base/common/codicons.js'; @@ -417,7 +418,7 @@ export function registerChatCodeBlockActions(): DisposableStore { const chatSessionsService = accessor.get(IChatSessionsService); const sessionTelemetry = isResponseVM(context.element) ? getChatSessionTelemetryIds(context.element.sessionResource, accessor.get(IAgentHostConnectionsService)) : undefined; - const editor = await editorService.openEditor({ contents: context.code, languageId: context.languageId, resource: undefined } satisfies IUntitledTextResourceEditorInput); + const editor = await editorService.openEditor({ contents: context.code, languageId: context.languageId, resource: undefined, untitledOrigin: 'chat' } satisfies IUntitledTextResourceEditorInput); if (editor && isResponseVM(context.element)) { const requestId = context.element.requestId; @@ -555,8 +556,10 @@ export function registerChatCodeBlockActions(): DisposableStore { const editor = codeEditorService.getFocusedCodeEditor(); const editorUri = editor?.getModel()?.uri; - const curCodeBlockInfo = editorUri ? widget.getCodeBlockInfoForEditor(editorUri) : undefined; - const focused = !widget.inputEditor.hasWidgetFocus() && widget.getFocus(); + let curCodeBlockInfo = editorUri ? widget.getCodeBlockInfoForEditor(editorUri) : undefined; + const activeElement = getActiveElement(); + const focusedItem = isHTMLElement(activeElement) ? widget.getElementFromNode(activeElement) : undefined; + const focused = !widget.inputEditor.hasWidgetFocus() && (focusedItem ?? widget.getFocus()); const focusedResponse = isResponseVM(focused) ? focused : undefined; const elementId = curCodeBlockInfo?.elementId; @@ -567,6 +570,7 @@ export function registerChatCodeBlockActions(): DisposableStore { return; } + curCodeBlockInfo ??= widget.getCodeBlockInfosForResponse(currentResponse).find(block => block?.isFocused); widget.reveal(currentResponse); const responseCodeblocks = widget.getCodeBlockInfosForResponse(currentResponse); const focusIdx = curCodeBlockInfo ? diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatCopyActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatCopyActions.ts index 1e19f67d6d31..86d6fdb4e0d2 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatCopyActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatCopyActions.ts @@ -429,7 +429,7 @@ export function registerChatCopyActions() { // Otherwise, fallback to querying from the active element if (!selectedElement) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax selectedElement = activeElement?.querySelector(`.${katexContainerClassName}`) ?? null; } diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts index 29afaafc628a..65ddedbf7a32 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts @@ -220,6 +220,7 @@ export class ChatSubmitAction extends SubmitAction { keybinding: { when: ContextKeyExpr.and( ChatContextKeys.inChatInput, + EditorContextKeys.hoverFocused.negate(), ChatContextKeys.withinEditSessionDiff.negate(), ), primary: KeyCode.Enter, diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatNewActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatNewActions.ts index fbc2c5363489..f98ca54fa580 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatNewActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatNewActions.ts @@ -185,7 +185,8 @@ export function registerNewChatActions() { title: localize2('chat.newLocalChat.label', "New Local Chat"), category: CHAT_CATEGORY, icon: Codicon.plus, - precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.location.isEqualTo(ChatAgentLocation.Chat)), + // The Agents view does not show local chat + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.location.isEqualTo(ChatAgentLocation.Chat), ChatContextKeys.agentsViewActive.negate()), f1: false, }); } diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatPluginActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatPluginActions.ts index 2a39bea9161a..b1997971f111 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatPluginActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatPluginActions.ts @@ -18,7 +18,9 @@ import { IDialogService, IFileDialogService } from '../../../../../platform/dial import { IFileService } from '../../../../../platform/files/common/files.js'; import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; +import { IProgressService, ProgressLocation } from '../../../../../platform/progress/common/progress.js'; import { IQuickInputButton, IQuickInputService, IQuickPickItem, QuickPickInput } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; import { IExtensionsWorkbenchService } from '../../../extensions/common/extensions.js'; import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; import { AICustomizationManagementCommands, AICustomizationManagementSection } from '../../common/aiCustomizationWorkspaceService.js'; @@ -47,6 +49,11 @@ export class ManagePluginsAction extends Action2 { } async run(accessor: ServicesAccessor): Promise { + // The Agents window has no Extensions view, so show the plugins in Chat Customizations instead. + if (accessor.get(IWorkbenchEnvironmentService).isSessionsWindow) { + await accessor.get(ICommandService).executeCommand(AICustomizationManagementCommands.OpenEditor, AICustomizationManagementSection.Plugins); + return; + } accessor.get(IExtensionsWorkbenchService).openSearch('@agentPlugins '); } } @@ -87,6 +94,7 @@ export class InstallFromSourceAction extends Action2 { const fileDialogService = accessor.get(IFileDialogService); const customizationHarnessService = accessor.get(ICustomizationHarnessService); const notificationService = accessor.get(INotificationService); + const progressService = accessor.get(IProgressService); const store = new DisposableStore(); const inputBox = store.add(quickInputService.createInputBox()); @@ -136,7 +144,11 @@ export class InstallFromSourceAction extends Action2 { let success: boolean; let installedUri: URI | undefined; if (pluginInstallProvider) { - await pluginInstallProvider.installFromSource(sessionResource, source); + await progressService.withProgress({ + location: ProgressLocation.Notification, + title: localize('installingPluginFromSource', "Installing plugin from source..."), + cancellable: false, + }, () => pluginInstallProvider.installFromSource(sessionResource, source)); success = true; } else { const result = await pluginInstallService.installPluginFromSource(source); diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatQueueActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatQueueActions.ts index 55f970ff7cc1..153bf5a3c249 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatQueueActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatQueueActions.ts @@ -7,6 +7,7 @@ import { Codicon } from '../../../../../base/common/codicons.js'; import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { URI } from '../../../../../base/common/uri.js'; import { ServicesAccessor } from '../../../../../editor/browser/editorExtensions.js'; +import { EditorContextKeys } from '../../../../../editor/common/editorContextKeys.js'; import { localize, localize2 } from '../../../../../nls.js'; import { Action2, MenuId, MenuRegistry, registerAction2 } from '../../../../../platform/actions/common/actions.js'; import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; @@ -83,6 +84,7 @@ export class ChatQueueMessageAction extends Action2 { }, { when: ContextKeyExpr.and( ChatContextKeys.inChatInput, + EditorContextKeys.hoverFocused.negate(), queuingActionsPresent, effectiveDefaultIsQueue, ), @@ -129,6 +131,7 @@ export class ChatSteerWithMessageAction extends Action2 { keybinding: [{ when: ContextKeyExpr.and( ChatContextKeys.inChatInput, + EditorContextKeys.hoverFocused.negate(), queuingActionsPresent, effectiveDefaultIsSteer, ), diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatScreenshotContextPicker.ts b/src/vs/workbench/contrib/chat/browser/actions/chatScreenshotContextPicker.ts new file mode 100644 index 000000000000..e5f3eaaee0fc --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/actions/chatScreenshotContextPicker.ts @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getWindow } from '../../../../../base/browser/dom.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { StopWatch } from '../../../../../base/common/stopwatch.js'; +import { generateUuid } from '../../../../../base/common/uuid.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IHostService } from '../../../../services/host/browser/host.js'; +import { getScreenshotToolImageData, IScreenshotToolService, ScreenshotToolEntryPoint, ScreenshotToolMode, ScreenshotToolOutcome } from '../../../screenshotTool/browser/screenshotTool.js'; +import { IChatRequestVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import { IChatContextPickService } from '../attachments/chatContextPickService.js'; +import { convertBufferToScreenshotVariable } from '../attachments/chatScreenshotContext.js'; +import { IChatWidget } from '../chat.js'; +import { ScreenshotContextValuePick } from './chatContext.js'; + +export class DesktopScreenshotContextValuePick extends ScreenshotContextValuePick { + constructor( + @IHostService hostService: IHostService, + @IScreenshotToolService private readonly _screenshotToolService: IScreenshotToolService, + ) { + super(hostService); + } + + override async asAttachment(widget: IChatWidget): Promise { + if (!this._screenshotToolService.isSupported) { + return super.asAttachment(widget); + } + const stopWatch = StopWatch.create(false); + const result = await this._screenshotToolService.capture(getWindow(widget.domNode)); + widget.focusInput(); + if (result.kind !== 'captured') { + this._logCapture(result.kind, result.mode, stopWatch); + return undefined; + } + const { data, mimeType } = getScreenshotToolImageData(result.image); + this._logCapture('attached', result.mode, stopWatch); + const entry = { ...convertBufferToScreenshotVariable(data, mimeType), id: generateUuid() }; + this._screenshotToolService.registerEditableAttachment(entry, { original: result.image, annotationState: undefined }); + return entry; + } + + private _logCapture(outcome: ScreenshotToolOutcome, mode: ScreenshotToolMode, stopWatch: StopWatch): void { + this._screenshotToolService.logCapture({ entryPoint: ScreenshotToolEntryPoint.ChatAddContext, outcome, mode, durationMs: stopWatch.elapsed() }); + } +} + +export class ScreenshotContextContribution extends Disposable { + constructor( + @IInstantiationService instantiationService: IInstantiationService, + @IChatContextPickService contextPickService: IChatContextPickService, + ) { + super(); + this._register(contextPickService.registerChatContextItem(instantiationService.createInstance(DesktopScreenshotContextValuePick))); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentCustomizationItemProvider.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentCustomizationItemProvider.ts index b1f831108ef5..03e0ad6806ff 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentCustomizationItemProvider.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentCustomizationItemProvider.ts @@ -28,6 +28,7 @@ import { getAgentHostCustomizationSource, getAgentHostCustomizationUri } from '. import { readMcpServerDisplayName, readMcpServerSource } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; import { readAgentCustomizationMeta } from '../../../../../../platform/agentHost/common/meta/agentCustomizationMeta.js'; import { readCustomizationDiscoveryMeta } from '../../../../../../platform/agentHost/common/meta/customizationDiscoveryMeta.js'; +import { readCustomizationOrganizationMeta } from '../../../../../../platform/agentHost/common/meta/customizationOrganizationMeta.js'; import { AICustomizationScope, AICustomizationScopes, AICustomizationSource, AICustomizationSources } from '../../../common/aiCustomizationWorkspaceService.js'; import { PromptsType, Target } from '../../../common/promptSyntax/promptTypes.js'; import { getAgentHookMetadata } from '../../../common/promptSyntax/hookTypes.js'; @@ -135,6 +136,7 @@ export class AgentCustomizationItemProvider extends Disposable implements ICusto statusMessage: toStatusMessage(customization.load), enabled: isCustomizationEnabled(customization), disabledReason: getCustomizationDisabledReason(customization), + organizationControl: readCustomizationOrganizationMeta(customization), extensionId: undefined, pluginUri: uri, userInvocable: undefined, @@ -221,6 +223,8 @@ export class AgentCustomizationItemProvider extends Disposable implements ICusto source, scope, origin: source === AICustomizationSources.builtin ? { kind: 'harness' } : undefined, + // Hooks from managed policy can't be disabled by the user. + organizationControl: child.type === CustomizationType.Hook && discovery?.source === 'policy' ? (child.enabled === false ? {} : { requiredEnabled: true }) : undefined, delivery: isRemote ? SYNCED_FROM_CLIENT : undefined, groupKey, badge, @@ -310,13 +314,14 @@ export class AgentCustomizationItemProvider extends Disposable implements ICusto id: uri.toString(), kind: isAsk ? ChatModeKind.Ask : undefined, uri, + sourceUri: sources[index].sourceUri, name: agent.name, description: agent.description, sessionTypes: sessionTypes, enabled: true, // fill default/empty values for all other properties they will not be used by the UI // when making a request, all that's needed is the agent id. - source: sources[index], + source: sources[index].source, tools: undefined, agents: undefined, argumentHint: undefined, @@ -513,7 +518,7 @@ export class AgentCustomizationItemProvider extends Disposable implements ICusto return sessionAgents.length > 0 ? sessionAgents : this._draftCustomAgents?.get() ?? []; } - private async getAgentSources(sessionResource: URI, agents: readonly AgentCustomization[], token: CancellationToken): Promise { + private async getAgentSources(sessionResource: URI, agents: readonly AgentCustomization[], token: CancellationToken): Promise { let extensionFiles: readonly IPromptPath[] = []; try { extensionFiles = await this._promptsService.listPromptFilesForStorage(PromptsType.agent, PromptStorage.extension, token); @@ -613,7 +618,7 @@ export class AgentCustomizationItemProvider extends Disposable implements ICusto const source: IAgentSource = extensionId ? { storage: PromptStorage.extension, extensionId: new ExtensionIdentifier(extensionId) } : { storage: readAgentCustomizationMeta(agent)['vscode.chatMode'] === 'ask' ? PromptStorage.builtIn : PromptStorage.local }; - return { ...source, label: disambiguatedLabels[index] }; + return { source: { ...source, label: disambiguatedLabels[index] }, sourceUri: origins.get(agent)?.uri }; }); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts index 4c8ee99a5c5e..ec0e7ba75aba 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.ts @@ -21,8 +21,10 @@ import { IDefaultAccountService } from '../../../../../../platform/defaultAccoun import type { IDefaultAccount } from '../../../../../../base/common/defaultAccount.js'; import { deriveGitHubEndpoints } from '../../../../../../platform/github/common/githubEndpoints.js'; import { gitHubCopilotResource } from '../../../../../../platform/agentHost/common/githubEndpoints.js'; +import { copilotEntraAuthorizationServer, copilotEntraClientId, copilotEntraDiscoveryResource, copilotEntraResources, isCopilotEntraResource } from '../../../../../../platform/agentHost/common/copilotEntraAuthentication.js'; import { type McpAuthRequirement, type McpOAuthClient, type ModelSelection, type ProtectedResourceMetadata } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; import type { AuthenticateTarget, McpServerAuthenticateTarget } from '../../../../../../platform/agentHost/common/state/sessionProtocol.js'; +import { AuthRequiredReason } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; import type { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; @@ -75,6 +77,11 @@ export function modelRequiresAgentAuthentication(agent: AgentInfo | undefined, m return !selectedModel || readAgentModelByokIdentifier(selectedModel) === undefined; } +interface IForwardedAuthenticationIdentity { + readonly sessionId: string; + readonly accountId: string; +} + /** * Tracks the last bearer token pushed to a given agent host connection * for each protected resource, so that redundant `authenticate` RPCs can @@ -85,8 +92,8 @@ export function modelRequiresAgentAuthentication(agent: AgentInfo | undefined, m * when the connection is disposed. */ export class AgentHostAuthTokenCache { - private readonly _completedTokens = new Map(); - private readonly _pendingAuthentications = new Map }>(); + private readonly _completedTokens = new Map(); + private readonly _pendingAuthentications = new Map; readonly identity?: IForwardedAuthenticationIdentity }>(); private readonly _keyGenerations = new Map(); private readonly _rejectedSessions = new Map(); private _globalGeneration = 0; @@ -95,7 +102,7 @@ export class AgentHostAuthTokenCache { * Forwards a token once per resource/scope/target combination. Same-token callers share * and await an in-flight authentication. */ - async authenticate(resource: string, scopes: readonly string[] | undefined, token: string, authenticate: () => Promise, accountId?: string, entitlement?: IAgentEntitlementHint, target?: AuthenticateTarget): Promise { + async authenticate(resource: string, scopes: readonly string[] | undefined, token: string, authenticate: () => Promise, accountId?: string, entitlement?: IAgentEntitlementHint, target?: AuthenticateTarget, identity?: IForwardedAuthenticationIdentity): Promise { const credentialKey = JSON.stringify([token, accountId, entitlement?.trackingId, entitlement?.sku]); const key = this._key(resource, scopes, target); const globalGeneration = this._globalGeneration; @@ -107,6 +114,7 @@ export class AgentHostAuthTokenCache { if (!this._isCurrentGeneration(key, globalGeneration, keyGeneration)) { throw new CancellationError(); } + this._completedTokens.set(key, { credentialKey, token, identity }); return false; } @@ -118,10 +126,11 @@ export class AgentHostAuthTokenCache { if (!this._isCurrentGeneration(key, globalGeneration, keyGeneration)) { throw new CancellationError(); } - return this.authenticate(resource, scopes, token, authenticate, accountId, entitlement, target); + return this.authenticate(resource, scopes, token, authenticate, accountId, entitlement, target, identity); } - if (this._completedTokens.get(key) === credentialKey) { + if (this._completedTokens.get(key)?.credentialKey === credentialKey) { + this._completedTokens.set(key, { credentialKey, token, identity }); return false; } @@ -130,9 +139,9 @@ export class AgentHostAuthTokenCache { if (!this._isCurrentGeneration(key, globalGeneration, keyGeneration)) { throw new CancellationError(); } - this._completedTokens.set(key, credentialKey); + this._completedTokens.set(key, { credentialKey, token, identity }); })(); - this._pendingAuthentications.set(key, { credentialKey, promise }); + this._pendingAuthentications.set(key, { credentialKey, token, promise, identity }); try { await promise; return true; @@ -175,10 +184,41 @@ export class AgentHostAuthTokenCache { } } + getSessionId(resource: string, scopes: readonly string[] | undefined): string | undefined { + const key = this._key(resource, scopes); + return (this._pendingAuthentications.get(key)?.identity ?? this._completedTokens.get(key)?.identity)?.sessionId; + } + + getAccountId(resource: string, scopes: readonly string[] | undefined): string | undefined { + const key = this._key(resource, scopes); + return (this._pendingAuthentications.get(key)?.identity ?? this._completedTokens.get(key)?.identity)?.accountId; + } + + /** Allows a retry while retaining sign-out ownership and the last token for freshness challenges. */ + invalidate(resource: string, scopes: readonly string[] | undefined): void { + const key = this._key(resource, scopes); + const previous = this._pendingAuthentications.get(key) ?? this._completedTokens.get(key); + this.clear(resource, scopes ?? []); + if (previous?.identity) { + this._completedTokens.set(key, { identity: previous.identity, token: previous.token }); + } + } + rejectSession(resource: string, scopes: readonly string[] | undefined, session: AuthenticationSession): void { this._rejectedSessions.set(this._key(resource, scopes), { id: session.id, accessToken: session.accessToken, accountId: session.account.id }); } + /** Quarantines the credential previously sent for an expired challenge without losing sign-out ownership. */ + rejectForwardedSession(resource: string, scopes: readonly string[] | undefined): boolean { + const key = this._key(resource, scopes); + const current = this._pendingAuthentications.get(key) ?? this._completedTokens.get(key); + if (!current?.token || !current.identity) { + return this._rejectedSessions.has(key); + } + this._rejectedSessions.set(key, { id: current.identity.sessionId, accountId: current.identity.accountId, accessToken: current.token }); + return true; + } + getRejectedSession(resource: string, scopes: readonly string[] | undefined): RejectedAuthenticationSession | undefined { return this._rejectedSessions.get(this._key(resource, scopes)); } @@ -305,7 +345,7 @@ export class AgentHostAuthenticationRecovery { } recover(accessor: ServicesAccessor, resource: ProtectedResourceMetadata, options: IAgentHostAuthenticationOptions): Promise { - const key = protectedResourceAuthenticationKey(resource); + const key = protectedResourceAuthenticationKey(resource) + (isCopilotEntraResource(resource) ? `:${options.challengeReason ?? AuthRequiredReason.Required}` : ''); const pendingRecovery = this._pendingRecoveries.get(key); if (pendingRecovery) { return pendingRecovery; @@ -327,6 +367,10 @@ export class AgentHostAuthenticationRecovery { const authenticationService = accessor.get(IAuthenticationService); const defaultAccountService = accessor.get(IDefaultAccountService); const commandService = accessor.get(ICommandService); + if (isCopilotEntraResource(resource)) { + await recoverCopilotEntraAuthentication(authenticationService, defaultAccountService, logService, resource, options); + return; + } if (await options.renewAuthentication?.(resource)) { throwIfAuthenticationStale(options); logService.info(`${options.logPrefix} Renewed authentication for resource: ${resource.resource}`); @@ -383,7 +427,7 @@ export class AgentHostAuthenticationRecovery { if (isNewAlternative) { options.authTokenCache?.rejectSession(resource.resource, scopes, currentSession); } - options.authTokenCache?.clear(resource.resource, isNewAlternative ? scopes : resource.scopes_supported); + options.authTokenCache?.invalidate(resource.resource, isNewAlternative ? scopes : resource.scopes_supported); if (await forwardAuthenticationToken(options, resource.resource, scopes, session, candidateResolution.providerId, candidateResolution.entitlement)) { this._resentTokens.set(key, session.accessToken); logService.info(`${options.logPrefix} Authenticating for resource: ${resource.resource}`); @@ -397,7 +441,7 @@ export class AgentHostAuthenticationRecovery { return; } - options.authTokenCache?.clear(resource.resource, resource.scopes_supported); + options.authTokenCache?.invalidate(resource.resource, resource.scopes_supported); reportAgentHostAuthRecovery(this._telemetryService, { trigger: 'hostChallenge', action: 'prompt', @@ -570,6 +614,7 @@ export interface IAgentHostAuthenticateRequest { export interface IAgentHostAuthenticationOptions { readonly authTokenCache?: AgentHostAuthTokenCache; readonly logPrefix: string; + readonly challengeReason?: AuthRequiredReason; /** Prefer this signed-in session's account when several accounts can satisfy the resource. */ readonly preferredSessionId?: string; readonly isCurrent?: () => boolean; @@ -636,7 +681,7 @@ async function forwardAuthenticationToken( const token = session?.accessToken ?? ''; const rejectedSession = options.target ? undefined : options.authTokenCache?.getRejectedSession(resource, scopes); // The lookup may have started before this session was quarantined. - if (rejectedSession && rejectedSession.id === session?.id && rejectedSession.accessToken === token) { + if (rejectedSession && rejectedSession.accessToken === token && (providerId === 'microsoft' || rejectedSession.id === session?.id)) { throw new CancellationError(); } const request = { @@ -644,7 +689,8 @@ async function forwardAuthenticationToken( ...(options.target ? { target: options.target } : {}), }; if (options.authTokenCache) { - return options.authTokenCache.authenticate(resource, scopes ?? [], token, () => options.authenticate(request), authenticationAccountId(readAuthenticationAccount(request)), readAgentEntitlementHint(request), options.target); + const identity = session?.id && session.account ? { sessionId: session.id, accountId: session.account.id } : undefined; + return options.authTokenCache.authenticate(resource, scopes ?? [], token, () => options.authenticate(request), authenticationAccountId(readAuthenticationAccount(request)), readAgentEntitlementHint(request), options.target, identity); } await options.authenticate(request); return true; @@ -661,6 +707,7 @@ function toAuthenticateRequest( const account = providerId && session?.account?.id ? { providerId, accountId: session.account.id, + ...(providerId === 'microsoft' && session.account.label ? { label: session.account.label } : {}), ...(session.authorizationServer ? { authorizationServer: session.authorizationServer.toString() } : {}), } : undefined; return { @@ -780,6 +827,10 @@ export async function revokeAuthenticationForRemovedSessions( if (reconciledResources.has(key)) { continue; } + if (await revokeCopilotEntraAuthentication(resource, providerId, removedSessions, options)) { + reconciledResources.add(key); + continue; + } if (!removedSessionsCouldSatisfyResource(removedSessions, scopes)) { continue; } @@ -828,6 +879,20 @@ function removedSessionsCouldSatisfyResource(removedSessions: readonly Pick[], options: IAgentHostAuthenticationOptions): Promise { + if (providerId !== 'microsoft' || !isCopilotEntraResource(resource)) { + return false; + } + const scopes = resource.scopes_supported ?? []; + const sessionId = options.authTokenCache?.getSessionId(resource.resource, scopes); + if (removedSessions.some(session => session.id === sessionId)) { + throwIfAuthenticationStale(options); + options.authTokenCache?.clear(resource.resource, scopes); + await forwardAuthenticationToken(options, resource.resource, scopes, undefined); + } + return true; +} + async function resourceMatchesAuthenticationProvider( authenticationService: IAuthenticationService, resource: ProtectedResourceMetadata, @@ -866,9 +931,15 @@ async function authenticateProtectedResourceWithServices( options: IResolvedAgentHostAuthenticationOptions, ): Promise { throwIfAuthenticationStale(options); + if (await revokeChangedCopilotEntraAccount(authenticationService, defaultAccountService, resource, options)) { + return false; + } const resolution = await resolveSessionForProtectedResource(authenticationService, defaultAccountService, logService, resource, options); throwIfAuthenticationStale(options); if (resolution.kind === 'signedOut' && resolution.accountMismatch) { + if (!canRevokeCopilotEntraAuthentication(resource, options)) { + return false; + } // A credential forwarded for another account must not outlive the user's switch away from it. if (await forwardAuthenticationToken(options, resource.resource, resource.scopes_supported ?? [], undefined)) { logService.info(`${options.logPrefix} Clearing authentication for resource the default account cannot satisfy: ${resource.resource}`); @@ -889,6 +960,31 @@ async function authenticateProtectedResourceWithServices( return true; } +function canRevokeCopilotEntraAuthentication(resource: ProtectedResourceMetadata, options: IAgentHostAuthenticationOptions): boolean { + return !isCopilotEntraResource(resource) || options.authTokenCache?.getSessionId(resource.resource, resource.scopes_supported) !== undefined; +} + +async function revokeChangedCopilotEntraAccount(authenticationService: IAuthenticationService, defaultAccountService: IDefaultAccountService, resource: ProtectedResourceMetadata, options: IAgentHostAuthenticationOptions): Promise { + const forwardedAccount = options.authTokenCache?.getAccountId(resource.resource, resource.scopes_supported); + if (!isCopilotEntraResource(resource) || forwardedAccount === undefined) { + return false; + } + const defaultAccount = defaultAccountService.currentDefaultAccount; + const identity = await resolveCopilotEntraIdentity(authenticationService, defaultAccount, resource); + throwIfAuthenticationStale(options); + if (defaultAccountService.currentDefaultAccount !== defaultAccount) { + throw new CancellationError(); + } + if (identity?.account.id === forwardedAccount) { + return false; + } + await forwardAuthenticationToken(options, resource.resource, resource.scopes_supported, undefined); + for (const ownedResource of [copilotEntraDiscoveryResource, ...copilotEntraResources.values()]) { + options.authTokenCache?.clear(ownedResource); + } + return true; +} + /** * Defaults to the cached rejection; pass null for an unfiltered lookup. */ @@ -900,6 +996,9 @@ async function resolveSessionForProtectedResource( options: Pick, rejectedSession: RejectedAuthenticationSession | null = options.authTokenCache?.getRejectedSession(resource.resource, resource.scopes_supported) ?? null, ): Promise { + if (isCopilotEntraResource(resource)) { + return resolveCopilotEntraSession(authenticationService, defaultAccountService, resource, rejectedSession); + } const resolution = await resolveAuthenticationSessionForResource( URI.parse(resource.resource), resource.authorization_servers ?? [], @@ -950,6 +1049,83 @@ async function resolveSessionForProtectedResource( }; } +async function recoverCopilotEntraAuthentication(authenticationService: IAuthenticationService, defaultAccountService: IDefaultAccountService, logService: ILogService, resource: ProtectedResourceMetadata, options: IResolvedAgentHostAuthenticationOptions): Promise { + if (options.challengeReason === AuthRequiredReason.Expired && !options.authTokenCache?.rejectForwardedSession(resource.resource, resource.scopes_supported)) { + logService.info(`${options.logPrefix} Microsoft credential freshness cannot be established silently; explicit authentication is required.`); + return; + } + options.authTokenCache?.invalidate(resource.resource, resource.scopes_supported); + await authenticateProtectedResourceWithServices(authenticationService, defaultAccountService, logService, resource, options); +} + +function isCurrentCopilotEntraAccount(defaultAccount: IDefaultAccount | null, identity: AuthenticationSession): boolean { + return defaultAccount?.authenticationProvider.id === 'microsoft' && defaultAccount.sessionId === identity.id; +} + +async function resolveCopilotEntraSession(authenticationService: IAuthenticationService, defaultAccountService: IDefaultAccountService, resource: ProtectedResourceMetadata, rejectedSession: RejectedAuthenticationSession | null): Promise { + const identity = await resolveCopilotEntraIdentity(authenticationService, defaultAccountService.currentDefaultAccount, resource); + if (!identity) { + return { kind: 'signedOut', accountMismatch: true }; + } + const sessions = await authenticationService.getSessions('microsoft', resource.scopes_supported ?? [], { + account: identity.account, + authorizationServer: URI.parse(copilotEntraAuthorizationServer), + clientId: copilotEntraClientId, + silent: true, + }, true); + if (!isCurrentCopilotEntraAccount(defaultAccountService.currentDefaultAccount, identity)) { + return { kind: 'signedOut', accountMismatch: true }; + } + const selection = selectAuthenticationSession(sessions.filter(session => rejectedSession === null || session.accessToken !== rejectedSession.accessToken), resource.scopes_supported ?? [], { + accountId: identity.account.id, + fallbackToSoleAccount: false, + }); + return selection.kind === 'selected' + ? { kind: 'resolved', providerId: 'microsoft', session: selection.session, match: selection.match } + : { kind: 'signedOut' }; +} + +async function resolveCopilotEntraIdentity(authenticationService: IAuthenticationService, defaultAccount: IDefaultAccount | null | undefined, resource: ProtectedResourceMetadata): Promise { + if (defaultAccount?.authenticationProvider.id !== 'microsoft') { + return undefined; + } + const providerId = await authenticationService.getOrActivateProviderIdForServer(URI.parse(copilotEntraAuthorizationServer), URI.parse(resource.resource)); + if (providerId !== 'microsoft') { + return undefined; + } + const sessions = await authenticationService.getSessions(providerId, undefined, { silent: true, clientId: copilotEntraClientId }, true); + return sessions.find(session => session.id === defaultAccount.sessionId); +} + +async function createCopilotEntraSession(authenticationService: IAuthenticationService, defaultAccountService: IDefaultAccountService, resource: ProtectedResourceMetadata, options: IAgentHostAuthenticationOptions): Promise { + const identity = await resolveCopilotEntraIdentity(authenticationService, defaultAccountService.currentDefaultAccount, resource); + throwIfAuthenticationStale(options); + if (!identity) { + throw new Error(localize('agentHost.microsoftAccountRequired', "Sign in with the intended Microsoft account before retrying.")); + } + assertCurrentCopilotEntraAccount(defaultAccountService.currentDefaultAccount, identity); + const session = await authenticationService.createSession('microsoft', resource.scopes_supported ?? [], { + account: identity.account, + authorizationServer: URI.parse(copilotEntraAuthorizationServer), + clientId: copilotEntraClientId, + }); + throwIfAuthenticationStale(options); + assertCurrentCopilotEntraAccount(defaultAccountService.currentDefaultAccount, identity); + if (session.account.id !== identity.account.id) { + throw new Error(localize('agentHost.microsoftAccountChanged', "The Microsoft account changed. Retry with the original account.")); + } + if (!session.accessToken || !resource.scopes_supported?.every(scope => session.scopes.includes(scope))) { + throw new Error(localize('agentHost.microsoftCredentialMismatch', "Microsoft sign-in did not provide the requested credential.")); + } + return session; +} + +function assertCurrentCopilotEntraAccount(defaultAccount: IDefaultAccount | null, identity: AuthenticationSession): void { + if (!isCurrentCopilotEntraAccount(defaultAccount, identity)) { + throw new Error(localize('agentHost.microsoftAccountChanged', "The Microsoft account changed. Retry with the original account.")); + } +} + function selectFewestScopes(sessions: readonly AuthenticationSession[]): AuthenticationSession | undefined { return findFirstMin(sessions, compareBy(session => new Set(session.scopes).size, numberComparator)); } @@ -1002,6 +1178,9 @@ export async function resolveAuthenticationInteractively( const resolvedOptions = resolveAuthenticationOptions(accessor, options); for (const resource of protectedResources) { throwIfAuthenticationStale(options); + if (await revokeChangedCopilotEntraAccount(authenticationService, defaultAccountService, resource, options)) { + return false; + } const scopes = resource.scopes_supported ?? []; const rejectedSession = options.authTokenCache?.getRejectedSession(resource.resource, scopes); const existingSessionResolution = await resolveSessionForProtectedResource(authenticationService, defaultAccountService, logService, resource, resolvedOptions); @@ -1048,6 +1227,9 @@ async function forceAuthenticationInteractively( const data: AgentHostAuthSignInData = { trigger, result: 'failed', credentialChanged: undefined, sessionMatch: undefined }; try { const scopes = resource.scopes_supported ?? []; + if (isCopilotEntraResource(resource)) { + return await forceCopilotEntraAuthenticationInteractively(authenticationService, defaultAccountService, resource, options, data, challengedToken); + } const setupResult = await commandService.executeCommand(CHAT_SETUP_ACTION_ID, undefined, { telemetrySource: 'agentHost', forceSignInDialog: true, @@ -1094,6 +1276,26 @@ async function forceAuthenticationInteractively( } } +async function forceCopilotEntraAuthenticationInteractively( + authenticationService: IAuthenticationService, + defaultAccountService: IDefaultAccountService, + resource: ProtectedResourceMetadata, + options: IResolvedAgentHostAuthenticationOptions, + data: AgentHostAuthSignInData, + challengedToken: string | undefined, +): Promise { + if (await revokeChangedCopilotEntraAccount(authenticationService, defaultAccountService, resource, options)) { + return undefined; + } + const scopes = resource.scopes_supported ?? []; + const session = await createCopilotEntraSession(authenticationService, defaultAccountService, resource, options); + options.authTokenCache?.invalidate(resource.resource, scopes); + await forwardAuthenticationToken(options, resource.resource, scopes, session, 'microsoft'); + data.result = 'tokenForwarded'; + data.credentialChanged = challengedToken === undefined ? undefined : session.accessToken !== challengedToken; + return session; +} + /** * Forwards the GitHub Copilot credential of the account that authorized Copilot Connectors, without prompting and * preferring that account's session that also grants the Connector scope. Connector-owned servers use this diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts index 4388a93a39e1..8b88086e4cac 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostByokLmHandler.ts @@ -18,6 +18,8 @@ import { IByokLmModelInfo, IByokLmOutputItem, IByokLmReasoningItem, + IByokLmStreamDelta, + IByokLmStreamDeltaBody, } from '../../../../../../platform/agentHost/common/agentHostByokLm.js'; import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; @@ -55,6 +57,14 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok /** Fires when the renderer's BYOK models change, so the node agent host re-enumerates. */ readonly onDidChangeModels = this._onDidChangeModels.event; + private readonly _onDidDelta = this._register(new Emitter()); + /** + * Fires each piece of a {@link chat} response as the language model produces + * it, so the node agent host can proxy it before the call completes. Deltas + * are published only for requests that carry a `requestId`. + */ + readonly onDidDelta = this._onDidDelta.event; + constructor( @ILanguageModelsService private readonly _languageModelsService: ILanguageModelsService, @ILogService private readonly _logService: ILogService, @@ -109,6 +119,9 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok const output: IByokLmOutputItem[] = []; const customToolNames = new Set(request.tools?.filter(tool => tool.type === 'custom').map(tool => tool.name)); const completedReasoningSummaryParts = new Set(); + // Each delta is published immediately before it is folded into `output`, + // so the delta stream reproduces the result the caller finally receives. + const emit = this._deltaEmitter(request.requestId); let responseId: string | undefined; let usage: IByokLmChatResult['usage']; const streaming = (async () => { @@ -116,28 +129,32 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok const parts = Array.isArray(part) ? part : [part]; for (const p of parts) { if (p.type === 'text') { + emit?.({ kind: 'text', delta: p.value }); this._appendTextOutput(output, p.value); } else if (p.type === 'thinking') { if (p.metadata?.[VSCODE_REASONING_SUMMARY_PART_DONE] === true) { completedReasoningSummaryParts.add(p.id); } else { const startsNewSummaryPart = p.value.length > 0 && completedReasoningSummaryParts.delete(p.id); - this._appendReasoningOutput(output, p, startsNewSummaryPart); + this._appendReasoningOutput(output, p, startsNewSummaryPart, emit); } } else if (p.type === 'tool_use') { - if (customToolNames.has(p.name)) { + const isCustom = customToolNames.has(p.name); + const value = isCustom ? this._customToolInput(p.parameters) : JSON.stringify(p.parameters ?? {}); + emit?.({ kind: 'toolCall', callId: p.toolCallId, name: p.name, isCustom, value }); + if (isCustom) { output.push({ type: 'custom_tool_call', callId: p.toolCallId, name: p.name, - input: this._customToolInput(p.parameters), + input: value, }); } else { output.push({ type: 'function_call', callId: p.toolCallId, name: p.name, - argumentsJson: JSON.stringify(p.parameters ?? {}), + argumentsJson: value, }); } } else if (p.type === 'data' && p.mimeType === STATEFUL_MARKER_MIME_TYPE) { @@ -347,12 +364,31 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok } } - private _appendReasoningOutput(output: IByokLmOutputItem[], part: Extract, startsNewSummaryPart: boolean): void { + private _appendReasoningOutput(output: IByokLmOutputItem[], part: Extract, startsNewSummaryPart: boolean, emit?: (delta: IByokLmStreamDeltaBody) => void): void { if (part.metadata?.vscode_reasoning_done === true) { return; } const summary = Array.isArray(part.value) ? part.value : [part.value]; const encryptedContent = this._encodeReasoningMetadata(part.metadata); + const previous = output.at(-1); + // Whether the fold below extends the open reasoning item instead of starting + // a new one, which is the only case `startsNewSummaryPart` distinguishes. + const extendsOpenItem = previous?.type === 'reasoning' && previous.id === part.id; + if (emit) { + // One delta per summary entry the fold adds, so replaying the deltas + // reproduces this item's `summary` array entry for entry. + const encrypted = encryptedContent === undefined ? {} : { encryptedContent }; + if (Array.isArray(part.value)) { + for (const entry of part.value) { + emit({ kind: 'reasoning', id: part.id, delta: entry, newSummaryPart: true, ...encrypted }); + } + if (part.value.length === 0) { + emit({ kind: 'reasoning', id: part.id, delta: '', newSummaryPart: false, ...encrypted }); + } + } else { + emit({ kind: 'reasoning', id: part.id, delta: part.value, newSummaryPart: !extendsOpenItem || startsNewSummaryPart, ...encrypted }); + } + } const reasoning: IByokLmReasoningItem = { type: 'reasoning', id: part.id, @@ -360,7 +396,6 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok encryptedContent, metadata: part.metadata, }; - const previous = output.at(-1); if (previous?.type === 'reasoning' && previous.id === reasoning.id) { output[output.length - 1] = { ...previous, @@ -408,6 +443,18 @@ export class AgentHostByokLmHandler extends Disposable implements IAgentHostByok return metadata as Record; } + /** + * A publisher for `requestId`'s deltas, or `undefined` when the caller did not + * ask for a stream. The node agent host mints `requestId` only for requests + * whose own HTTP response is a stream. + */ + private _deltaEmitter(requestId: string | undefined): ((delta: IByokLmStreamDeltaBody) => void) | undefined { + if (requestId === undefined) { + return undefined; + } + return delta => this._onDidDelta.fire({ ...delta, requestId }); + } + private _customToolInput(parameters: unknown): string { if (typeof parameters === 'object' && parameters !== null) { const input = Object.getOwnPropertyDescriptor(parameters, 'input')?.value; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatContribution.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatContribution.ts index 4cbfce43c241..3d70419ca565 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatContribution.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatContribution.ts @@ -17,7 +17,7 @@ import { affectsAgentHostProviderPreference, getPolicyUnavailableLocalAgentHostP import { IAgentHostEnablementService } from '../../../../../../platform/agentHost/common/agentHostEnablementService.js'; import { AGENT_HOST_SCHEME, agentHostAuthority, createAgentHostResourceUriMapper, LOCAL_AGENT_HOST_AUTHORITY, registerLocalAgentHostWindowScheme } from '../../../../../../platform/agentHost/common/agentHostUri.js'; import { type ProtectedResourceMetadata } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; -import { NotificationType } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; +import { AuthRequiredReason, NotificationType } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; import { type AgentInfo, type RootState } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { CHATGPT_SUBSCRIPTION_MODEL_SOURCE_ID } from '../../../../../../platform/agentHost/common/agentModelSource.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; @@ -243,7 +243,7 @@ export class AgentHostContribution extends Disposable implements IWorkbenchContr if (notification.type !== NotificationType.AuthRequired) { return; } - this._authenticateNotificationResource(notification.resource); + this._authenticateNotificationResource(notification.resource, notification.reason); })); store.add(this._defaultAccountService.onDidChangeDefaultAccount(() => { this._authenticateWithServer(this._getRootAgents()).catch(() => { /* best-effort */ }); @@ -535,7 +535,7 @@ export class AgentHostContribution extends Disposable implements IWorkbenchContr } } - private _authenticateNotificationResource(protectedResource: ProtectedResourceMetadata): void { + private _authenticateNotificationResource(protectedResource: ProtectedResourceMetadata, reason?: AuthRequiredReason): void { const generation = this._authenticationGeneration; if (!this._isAuthenticationCurrent(generation)) { return; @@ -543,6 +543,7 @@ export class AgentHostContribution extends Disposable implements IWorkbenchContr this._agentHostService.setAuthenticationPending(true); this._instantiationService.invokeFunction(accessor => this._authRecovery.recover(accessor, protectedResource, { authTokenCache: this._authTokenCache, + challengeReason: reason, logPrefix: '[AgentHost]', isCurrent: () => this._isAuthenticationCurrent(generation), authenticate: request => this._authenticateIfCurrent(request, generation), diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatInputPicker.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatInputPicker.ts index e3fd8bf32e2a..d25bcfbbf998 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatInputPicker.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostChatInputPicker.ts @@ -52,6 +52,7 @@ import { AgentSandboxEnabledSettingValue, AgentSandboxEnabledValue, AgentSandbox import { IAction, toAction } from '../../../../../../base/common/actions.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import type { IChatWidget } from '../../chat.js'; import { ChatConfiguration, ChatPermissionLevel, isChatPermissionLevel } from '../../../common/constants.js'; import { IChatSessionsService, SessionType } from '../../../common/chatSessionsService.js'; @@ -193,6 +194,7 @@ function toActionItems(property: string, items: readonly IConfigPickerItem[], cu label: sandboxToggle.label, group: { title: '', icon: Codicon.shield }, standaloneToggle: sandboxToggle, + hover: sandboxToggle.title ? { content: sandboxToggle.title } : undefined, item: { value: '__sandboxToggle', label: sandboxToggle.label, checked: false }, }); } @@ -443,7 +445,7 @@ export class AgentHostChatInputPicker extends Disposable { private _pickerVisible = false; private _generic = false; private _initialResolved: { readonly sessionResource: URI; readonly result: ResolveSessionConfigResult } | undefined; - private readonly _initialConfig = this._register(new AgentHostInitialSessionConfig(error => this._logService.warn('[AgentHostChatInputPicker] Failed to resolve initial session configuration', error))); + private readonly _initialConfig: AgentHostInitialSessionConfig; private readonly _renderDisposables = this._register(new DisposableStore()); private readonly _splitTrigger = this._register(new MutableDisposable()); private readonly _pickerDisposables = this._register(new DisposableStore()); @@ -488,9 +490,12 @@ export class AgentHostChatInputPicker extends Disposable { @IContextViewService private readonly _contextViewService: IContextViewService, @IManagedSettingsService private readonly _managedSettingsService: IManagedSettingsService, @IChatSessionsService private readonly _chatSessionsService: IChatSessionsService, + @IWorkspaceTrustManagementService workspaceTrustManagementService: IWorkspaceTrustManagementService, ) { super(); + this._initialConfig = this._register(new AgentHostInitialSessionConfig(error => this._logService.warn('[AgentHostChatInputPicker] Failed to resolve initial session configuration', error), workspaceTrustManagementService)); + this._register(this._initialConfig.onDidInvalidate(() => this._invalidateInitialResolve())); this._register(toDisposable(() => { this._container = undefined; this._trigger = undefined; @@ -698,12 +703,20 @@ export class AgentHostChatInputPicker extends Disposable { const localBackend = toAgentHostBackendSessionUri(sessionResource, this._connectionsService); if (localBackend && localProvider && isUntitledChatSession(sessionResource) && !provisionalBackend) { this._subRef.clear(); + this._draftListeners.add(this._newSessionFolderService.onDidChangeFolder(resource => { + if (isEqual(resource, sessionResource)) { + this._invalidateInitialResolve(); + } + })); + this._draftListeners.add(this._workspaceContextService.onDidChangeWorkspaceFolders(() => this._invalidateInitialResolve())); const prepared = this._provisional.getResolvedConfig(sessionResource) ?? this._provisional.getPreparedSessionConfig(sessionResource); if (prepared) { this._initialResolved = { sessionResource, result: prepared }; - } else if (!this._initialResolved || this._initialResolved.sessionResource.toString() !== sessionResource.toString()) { - this._initialResolved = undefined; + } else { void this._refreshInitialResolved(sessionResource, localProvider, resolution); + if (this._initialResolved?.result !== this._initialConfig.value) { + this._initialResolved = undefined; + } } // Eagerly create a provisional backend session so even users // who never touch a chip still get their picker defaults @@ -787,6 +800,15 @@ export class AgentHostChatInputPicker extends Disposable { this._renderChip(); } + private _invalidateInitialResolve(): void { + const sessionResource = this._widget.viewModel?.sessionResource; + if (sessionResource && isUntitledChatSession(sessionResource) && getLocalAgentHostSessionProvider(sessionResource)) { + this._initialResolved = undefined; + this._cancelInitialResolve(); + this._reattach(); + } + } + private _cancelInitialResolve(): void { this._initialConfig.clear(); } @@ -1254,7 +1276,7 @@ export class AgentHostChatInputPicker extends Disposable { } previousToggle = standaloneToggle; this._actionWidgetService.updateItems(actionItems.map(item => item.standaloneToggle - ? { ...item, standaloneToggle } + ? { ...item, standaloneToggle, hover: standaloneToggle?.title ? { content: standaloneToggle.title } : undefined } : item)); })); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostConfigEditor.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostConfigEditor.ts index a4d46d40008b..76a2548d60eb 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostConfigEditor.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostConfigEditor.ts @@ -8,6 +8,7 @@ import { Emitter } from '../../../../../../base/common/event.js'; import { parse, ParseError } from '../../../../../../base/common/json.js'; import { IJSONSchema } from '../../../../../../base/common/jsonSchema.js'; import { Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { ResourceMap } from '../../../../../../base/common/map.js'; import { URI } from '../../../../../../base/common/uri.js'; import { createFileSystemProviderError, @@ -199,6 +200,8 @@ export abstract class AbstractAgentHostConfigFileSystemProvider()); readonly onDidChangeFile = this._onDidChangeFile.event; + private readonly _lastStats = new ResourceMap<{ readonly content: string; readonly mtime: number }>(); + constructor( @ILogService protected readonly _logService: ILogService, ) { @@ -305,7 +308,7 @@ export abstract class AbstractAgentHostConfigFileSystemProvider { throw createFileSystemProviderError('readdir not supported', FileSystemProviderErrorCode.NoPermissions); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.ts index 44b137d80081..5e77a19cd20b 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.ts @@ -30,6 +30,7 @@ import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from import type { IMcpServerConfiguration } from '../../../../../../platform/mcp/common/mcpPlatformTypes.js'; import { IRecordedCustomizationMarketplaceResource, ICustomizationMarketplaceInstallProvider } from '../../../common/customizationMarketplaceInstallService.js'; import { ICustomizationMarketplaceInfo, ICustomizationMarketplaceManagementProvider, ICustomizationMarketplaceSearchProvider, ICustomizationMcpConfigurationProvider, ICustomizationPluginInstallProvider } from '../../../common/customizationHarnessService.js'; +import { customizationSearchMatchesAny } from '../../../common/aiCustomizationSearch.js'; import { IAgentHostCustomizationService } from './agentHostCustomizationService.js'; import { getGitHubMcpRegistryIcon } from '../../aiCustomization/githubMcpRegistryIcons.js'; import { ContributionEnablementState } from '../../../common/enablement.js'; @@ -245,11 +246,16 @@ export class AgentHostCustomizationMarketplaceInstallProvider extends Disposable return this.agentHostService.listPluginMarketplaces(this.providerId, this.getBackendSession(sessionResource), this.agentHostCustomizationService.getBackendChatResource?.(sessionResource)); } - async add(sessionResource: URI, source: string) { + async add(sessionResource: URI | undefined, source: string) { if (!this.agentHostService.addPluginMarketplace) { throw new Error(localize('agentHost.marketplaceManagement.addUnavailable', "The selected agent does not support adding marketplaces.")); } - const result = await this.agentHostService.addPluginMarketplace(this.providerId, this.getBackendSession(sessionResource), source, this.agentHostCustomizationService.getBackendChatResource?.(sessionResource)); + const result = await this.agentHostService.addPluginMarketplace( + this.providerId, + sessionResource ? this.getBackendSession(sessionResource) : undefined, + source, + sessionResource ? this.agentHostCustomizationService.getBackendChatResource?.(sessionResource) : undefined, + ); this.fireMarketplacesChanged(); return result; } @@ -264,9 +270,9 @@ export class AgentHostCustomizationMarketplaceInstallProvider extends Disposable } const plugins = await this.agentHostService.browsePluginMarketplace(this.providerId, this.getBackendSession(sessionResource), marketplace.name, this.agentHostCustomizationService.getBackendChatResource?.(sessionResource)); this.throwIfCancelled(token); - const query = options.query?.trim().toLowerCase(); + const query = options.query?.trim() ?? ''; const matching = query - ? plugins.filter(plugin => plugin.name.toLowerCase().includes(query) || plugin.description?.toLowerCase().includes(query)) + ? plugins.filter(plugin => customizationSearchMatchesAny(query, [plugin.name, plugin.description])) : plugins; const offset = Number(options.cursor ?? 0); const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts index d2b6cd22f70c..4b00df1f7700 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts @@ -12,7 +12,8 @@ import { getErrorMessage, isCancellationError } from '../../../../../../base/com import { StringSHA1 } from '../../../../../../base/common/hash.js'; import { Disposable, DisposableResourceMap, DisposableStore, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ResourceSet } from '../../../../../../base/common/map.js'; -import { AgentHostMcpServers, AgentHostMcpServersConfigKey } from '../../../../../../platform/agentHost/common/agentHostSchema.js'; +import { AgentHostMcpServers, AgentHostMcpServersConfigKey, IPermissionsValue } from '../../../../../../platform/agentHost/common/agentHostSchema.js'; +import { SessionConfigKey } from '../../../../../../platform/agentHost/common/sessionConfigKeys.js'; import { affectsAgentHostProviderPreference, IAgentConnection, isLocalAgentHostProviderDisabledByPolicy } from '../../../../../../platform/agentHost/common/agentService.js'; import { getAgentHostCustomizationUri } from '../../../common/agentHostSessionCustomizations.js'; import { IAgentHostResourceUriMapper } from '../../../../../../platform/agentHost/common/agentHostUri.js'; @@ -101,6 +102,12 @@ export interface IAgentHostCustomizationService { */ getMcpServers(sessionResource: URI): readonly IAgentHostMcpServer[]; + /** Returns host-wide permissions, or undefined when the host does not advertise writable permissions. */ + getHostPermissions(sessionResource: URI): IPermissionsValue | undefined; + + /** Updates host-wide permissions on the connection backing the session. */ + setHostPermissions(sessionResource: URI, permissions: IPermissionsValue): void; + /** * Adds (or replaces) an agent-host-level MCP server in the root config of * the agent host backing `sessionResource`. The write is routed to the @@ -168,6 +175,13 @@ export class NullAgentHostCustomizationService implements IAgentHostCustomizatio getMcpServers(_sessionResource: URI): readonly IAgentHostMcpServer[] { return []; } + getHostPermissions(_sessionResource: URI): IPermissionsValue | undefined { + return undefined; + } + setHostPermissions(_sessionResource: URI, _permissions: IPermissionsValue): void { + // no-op + } + addMcpServer(_sessionResource: URI, _name: string, _config: IMcpServerConfiguration): void { // no-op } @@ -490,6 +504,21 @@ export abstract class AbstractAgentHostCustomizationService extends Disposable i } } + getHostPermissions(sessionResource: URI): IPermissionsValue | undefined { + const rootConfig = this._resolveTarget(sessionResource)?.rootConfig; + const permissionsSchema = rootConfig?.schema.properties[SessionConfigKey.Permissions]; + if (!rootConfig || !permissionsSchema || permissionsSchema.readOnly) { + return undefined; + } + // The host validates permissions when it reads them, so use the published value as is. + const value = rootConfig.values[SessionConfigKey.Permissions] as Partial | undefined; + return { ...value, allow: value?.allow ?? [], deny: value?.deny ?? [] }; + } + + setHostPermissions(sessionResource: URI, permissions: IPermissionsValue): void { + this._resolveTarget(sessionResource)?.setRootConfigValue(SessionConfigKey.Permissions, permissions); + } + addMcpServer(sessionResource: URI, name: string, config: IMcpServerConfiguration): void { const target = this._resolveTarget(sessionResource); const existingServers = target?.rootConfig?.values?.[AgentHostMcpServersConfigKey]; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostEditReview.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostEditReview.ts index 1a866d451adc..37591453017e 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostEditReview.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostEditReview.ts @@ -8,7 +8,7 @@ import { cancelOnDispose, CancellationToken } from '../../../../../../base/commo import { toErrorMessage } from '../../../../../../base/common/errorMessage.js'; import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Event } from '../../../../../../base/common/event.js'; -import { Disposable, DisposableStore, IReference } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableResourceMap, DisposableStore, IReference } from '../../../../../../base/common/lifecycle.js'; import { ResourceMap, ResourceSet } from '../../../../../../base/common/map.js'; import { autorun, constObservable, derived, derivedOpts, IObservable, IReader, ITransaction, observableFromEvent, observableSignalFromEvent, observableValue, transaction } from '../../../../../../base/common/observable.js'; import { basename, isEqual } from '../../../../../../base/common/resources.js'; @@ -57,6 +57,7 @@ const DIFF_TIMEOUT_MS = 1000; const WORKING_SET_READY_TIMEOUT_MS = 30_000; class EditReviewSynchronizationError extends Error { } +class EditReviewSupersededError extends EditReviewSynchronizationError { } /** A file of the session's Working Set, and the version of its changes that the agent host published with it. */ interface IWorkingSetFileChange { @@ -109,7 +110,7 @@ class AgentHostEditReviewEntry extends ChatEditingModifiedDocumentEntry { } /** Connects the entry to the Working Set file it reviews; called right after creating it. */ - connect(operations: IWorkingSetOperations, file: IWorkingSetFile, edit: StringEdit): void { + connect(operations: IWorkingSetOperations, file: IWorkingSetFile, edit: StringEdit, refreshReview: () => void): void { this._operations = operations; this._file = file; // Before the first diff starts, the original takes the document's line endings, which edits map onto. @@ -119,6 +120,9 @@ class AgentHostEditReviewEntry extends ChatEditingModifiedDocumentEntry { if (e.isEolChange) { this._matchLineEndings(); } + if (!this._isExternalEditInProgress && (e.isUndoing || e.isRedoing || e.detailedReasons.some(reason => reason.metadata.source === 'reloadFromDisk'))) { + refreshReview(); + } })); } @@ -153,6 +157,11 @@ class AgentHostEditReviewEntry extends ChatEditingModifiedDocumentEntry { } } + /** The agent host decides what is undone, so a document back at its baseline, as while its changes are stashed, stays undecided. */ + protected override _rejectsWhenResetToInitialContent(): boolean { + return false; + } + /** Changes the agent host didn't keep stay undecided. */ override acceptDeferred() { const file = this.file; @@ -258,6 +267,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat /** Runs operations one at a time, since each one changes the Working Set the next one checks. */ private readonly _operations = new Sequencer(); private readonly _blockedFiles = new ResourceSet(); + private readonly _suspendedEntries = this._register(new DisposableResourceMap()); private readonly _lifetimeToken = cancelOnDispose(this._store); constructor( @@ -332,7 +342,8 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat for (const file of files) { if (file.editing) { // An edit starts immediately, even while an earlier update is being read or diffed. - this._entries.get(this._uriIdentityService.asCanonicalUri(file.diff.modifiedURI))?.setEditing(true); + const resource = this._uriIdentityService.asCanonicalUri(file.diff.modifiedURI); + (this._entries.get(resource) ?? this._suspendedEntries.get(resource))?.setEditing(true); } } if (current && state?.status !== ChangesetStatus.Ready) { @@ -428,7 +439,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat const resource = this._uriIdentityService.asCanonicalUri(file.diff.modifiedURI); listed.add(resource); if (file.editing) { - this._entries.get(resource)?.setEditing(true); + (this._entries.get(resource) ?? this._suspendedEntries.get(resource))?.setEditing(true); continue; } try { @@ -454,18 +465,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat if (isCancellationError(error) || token.isCancellationRequested) { return; } - this._logService.error(`[AgentHostEditReview] Could not review ${resource}`, error); - if (error instanceof EditReviewSynchronizationError) { - const entry = this._entries.get(resource); - if (entry) { - entry.setEditing(false); - this._removeEntry(entry); - } - if (!this._blockedFiles.has(resource)) { - this._blockedFiles.add(resource); - this._notificationService.warn(localize('agentHostEditReview.reconcileFailed', "Could not update editor review for '{0}': {1} Your text has been preserved. Resolve the file's changes and save or revert it to resume editor review.", basename(resource), error.message)); - } - } + this._handleReviewError(resource, error); } } if (token.isCancellationRequested) { @@ -474,6 +474,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat for (const resource of this._blockedFiles) { if (!listed.has(resource)) { this._blockedFiles.delete(resource); + this._suspendedEntries.deleteAndDispose(resource); } } for (const entry of [...this._entries.values()]) { @@ -483,6 +484,58 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat } } + private _handleReviewError(resource: URI, error: unknown): void { + this._logService.error(`[AgentHostEditReview] Could not review ${resource}`, error); + if (error instanceof EditReviewSynchronizationError) { + const entry = this._entries.get(resource) ?? this._suspendedEntries.get(resource); + if (entry) { + entry.setEditing(false); + if (this._entries.has(resource)) { + this._suspendedEntries.set(resource, entry.acquire()); + this._removeEntry(entry); + } + } + if (!this._blockedFiles.has(resource)) { + this._blockedFiles.add(resource); + this._notificationService.warn(localize('agentHostEditReview.reconcileFailed', "Could not update editor review for '{0}': {1} Your text has been preserved. Resolve the file's changes and save or revert it to resume editor review.", basename(resource), error.message)); + } + } + } + + /** Rebase reloads and undo/redo against recorded edits, since their replacements can include unchanged agent text. */ + private _refreshReview(entry: AgentHostEditReviewEntry): void { + void this._updates.queue(async () => { + const file = entry.file; + const isCurrent = () => { + if (this._lifetimeToken.isCancellationRequested || !this._isReviewing(entry) + || entry.file !== file || entry.isAgentEditing || entry.state.get() !== ModifiedFileEntryState.Modified) { + return false; + } + const workingSet = this._workingSet.get(); + const state = workingSet?.state.get(); + const latest = workingSet && state ? this._findWorkingSetFile(state, workingSet, entry) : undefined; + return !!latest && !latest.editing && isSameWorkingSetFile(latest, file); + }; + if (!isCurrent()) { + return; + } + try { + const prepared = await this._prepareFile(file, entry.modifiedModel, this._lifetimeToken, entry.originalModel); + if (isCurrent()) { + await entry.update(file, prepared.original, prepared.edit); + } + } catch (error) { + if (isCurrent()) { + if (error instanceof EditReviewSupersededError) { + this._refreshReview(entry); + } else if (!isCancellationError(error)) { + this._handleReviewError(entry.modifiedURI, error); + } + } + } + }); + } + private async _updateFile(resource: URI, change: IWorkingSetFileChange, token: CancellationToken): Promise { const existing = this._entries.get(resource); if (existing && isSameWorkingSetFile(existing.file, change)) { @@ -492,7 +545,8 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat return; } const contents = await this._readContents(change.diff); - const entry = this._entries.get(resource); + const suspended = this._suspendedEntries.get(resource); + const entry = this._entries.get(resource) ?? suspended; if (this._store.isDisposed || token.isCancellationRequested) { return; } @@ -500,6 +554,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat if (entry) { this._removeEntry(entry); } + this._suspendedEntries.deleteAndDispose(resource); return; } if (entry?.state.get() === ModifiedFileEntryState.Modified) { @@ -510,8 +565,15 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat return; } const file = { ...change, ...contents }; - const prepared = await this._prepareFile(file, entry.modifiedModel, token); + const trackedOriginal = suspended && isSameWorkingSetFile(suspended.file, file) ? suspended.originalModel : undefined; + const prepared = await this._prepareFile(file, entry.modifiedModel, token, trackedOriginal); await entry.update(file, prepared.original, prepared.edit); + if (token.isCancellationRequested || this._store.isDisposed) { + return; + } + if (this._suspendedEntries.deleteAndLeak(resource)) { + this._entries.set(resource, entry); + } entry.updateTelemetryInfo(this._getTelemetryInfo()); this._entriesObs.set([...this._entries.values()], undefined); return; @@ -520,6 +582,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat // The user decided on the earlier changes, so the file is reviewed anew. this._removeEntry(entry); } + this._suspendedEntries.deleteAndDispose(resource); await this._createEntry(resource, { ...change, ...contents }, token); } @@ -559,7 +622,7 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat file.diff.isCreated ? ChatEditKind.Created : ChatEditKind.Modified, prepared.original, ); - entry.connect(this, file, prepared.edit); + entry.connect(this, file, prepared.edit, () => this._refreshReview(entry)); entry.setEditing(file.editing); // Agent changes wait for a decision, whatever the auto-accept delay. entry.enableReviewModeUntilSettled(); @@ -567,30 +630,34 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat this._entriesObs.set([...this._entries.values()], undefined); } - private async _prepareFile(file: IWorkingSetFile, model: ITextModel, token: CancellationToken): Promise<{ original: string; edit: StringEdit }> { + private async _prepareFile(file: IWorkingSetFile, model: ITextModel, token: CancellationToken, trackedOriginal?: ITextModel): Promise<{ original: string; edit: StringEdit }> { for (let attempt = 0; attempt < 2; attempt++) { - if (token.isCancellationRequested || model.isDisposed()) { + if (token.isCancellationRequested || model.isDisposed() || trackedOriginal?.isDisposed()) { throw new CancellationError(); } const version = model.getVersionId(); + const originalVersion = trackedOriginal?.getVersionId(); const live = model.getValue(); - const original = await getReviewedOriginal(file, live, model.getEOL(), this._editorWorkerService); - if (token.isCancellationRequested || model.isDisposed()) { + const original = await getReviewedOriginal(file, live, model.getEOL(), this._editorWorkerService, trackedOriginal?.getValue()); + if (token.isCancellationRequested || model.isDisposed() || trackedOriginal?.isDisposed()) { throw new CancellationError(); } - if (version !== model.getVersionId()) { + if (version !== model.getVersionId() || originalVersion !== trackedOriginal?.getVersionId()) { continue; } + if (original === undefined) { + throw new EditReviewSynchronizationError(localize('agentHostEditReview.impreciseDiff', "The file's changes could not be compared precisely.")); + } const edit = await computeEdit(original, live, this._editorWorkerService) ?? StringEdit.replace(OffsetRange.ofLength(original.length), live).removeCommonSuffixAndPrefix(original); - if (token.isCancellationRequested || model.isDisposed()) { + if (token.isCancellationRequested || model.isDisposed() || trackedOriginal?.isDisposed()) { throw new CancellationError(); } - if (version === model.getVersionId()) { + if (version === model.getVersionId() && originalVersion === trackedOriginal?.getVersionId()) { return { original, edit }; } } - throw new EditReviewSynchronizationError(localize('agentHostEditReview.prepareChanged', "The document changed while its changes were being compared.")); + throw new EditReviewSupersededError(localize('agentHostEditReview.prepareChanged', "The document changed while its changes were being compared.")); } /** Reads a file's baseline and current content, unless they aren't UTF-8 text, as the agent host compares them. */ @@ -903,18 +970,46 @@ export class AgentHostEditReview extends Disposable implements IWorkingSetOperat } /** - * The content to compare a document with: its Working Set baseline, with the - * changes made to the document since the session last recorded it moved into - * it. As in the Working Set, changes that touch the agent's stay with them. + * Reconciles the Working Set baseline without expanding an existing review, or returns undefined if precise comparison is unavailable. + * A document that matches the recorded content holds only the agent's changes, so it is compared with the baseline itself. */ -async function getReviewedOriginal(file: IWorkingSetFile, live: string, eol: string, workerService: IEditorWorkerService): Promise { +async function getReviewedOriginal(file: IWorkingSetFile, live: string, eol: string, workerService: IEditorWorkerService, trackedOriginal?: string): Promise { const baseline = withLineEndings(file.baseline, eol); const current = withLineEndings(file.current, eol); if (live === current) { return baseline; } + if (trackedOriginal === live) { + return live; + } const [agent, user] = await Promise.all([computeEdit(baseline, current, workerService), computeEdit(current, live, workerService)]); - return agent && user ? user.rebaseSkipConflicting(agent.inverse(baseline)).apply(baseline) : baseline; + if (!agent || !user) { + return undefined; + } + const original = user.rebaseSkipConflicting(agent.inverse(baseline)).apply(baseline); + if (trackedOriginal === undefined || trackedOriginal === original) { + return original; + } + const [pending, adjustments] = await Promise.all([computeEdit(trackedOriginal, live, workerService, true), computeEdit(trackedOriginal, original, workerService, true)]); + if (!pending || !adjustments) { + return undefined; + } + let pendingIndex = 0; + const refinements = adjustments.replacements.filter(adjustment => { + while (pendingIndex < pending.replacements.length) { + const replacement = pending.replacements[pendingIndex]; + const range = replacement.replaceRange; + if (range.containsRange(adjustment.replaceRange)) { + return replacement.equals(adjustment); + } + if (range.endExclusive > adjustment.replaceRange.start) { + return false; + } + pendingIndex++; + } + return false; + }); + return new StringEdit(refinements).apply(trackedOriginal); } /** @@ -963,11 +1058,11 @@ function toTextRange(lines: LineRange): TextRange { } /** The edit that turns `original` into `modified`, as their diff spells it out, or `undefined` if the diff times out. */ -async function computeEdit(original: string, modified: string, workerService: IEditorWorkerService): Promise { +async function computeEdit(original: string, modified: string, workerService: IEditorWorkerService, computeRawChanges = false): Promise { if (original === modified) { return StringEdit.empty; } - const diff = await workerService.computeStringEditFromDiffWithMetadata(original, modified, { maxComputationTimeMs: DIFF_TIMEOUT_MS }, 'advanced'); + const diff = await workerService.computeStringEditFromDiffWithMetadata(original, modified, { maxComputationTimeMs: DIFF_TIMEOUT_MS, computeRawChanges }, 'advanced'); return diff.isCoarse ? undefined : diff.edit; } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostFirstResponseTelemetry.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostFirstResponseTelemetry.ts index bb38dda0a409..9da400761736 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostFirstResponseTelemetry.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostFirstResponseTelemetry.ts @@ -26,6 +26,7 @@ export interface IAgentHostFirstResponseEvent { sessionTurnKind: 'first' | 'later' | 'unknown'; invocationKind: 'newTurn' | 'existingTurn' | 'subagent' | 'unknown'; firstResponseTextMs?: number; + firstResponseOrReasoningMs?: number; rootToolCallsBeforeFirstText?: number; rendererRootInvocationOrdinal?: number; trustInteractionRequired: boolean; @@ -35,7 +36,7 @@ export interface IAgentHostFirstResponseEvent { export type AgentHostFirstResponseClassification = { owner: 'amunger'; - comment: 'Measures local Agent Host invocation to first nonempty live root response text, not physical submission or paint.'; + comment: 'Measures local Agent Host invocation to first nonempty live root response text, and to first response text or reasoning, not physical submission or paint.'; schemaVersion: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Version of the invocation timing contract.' }; requestId: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Actual client request and protocol turn identifier.' }; provider: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Agent Host provider identifier.' }; @@ -43,9 +44,10 @@ export type AgentHostFirstResponseClassification = { agentSessionId?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Backend session identifier.' }; chatId?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Backend chat identifier.' }; outcome: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Terminal invocation outcome, including cancellation before dispatch.' }; - sessionTurnKind: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the observed chat has prior turns; unknown before state hydration.' }; + sessionTurnKind: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the default chat of the session has prior turns. Unknown for turns in other chats of the session, such as added, forked or side chats, and for invocations that ended before their chat was resolved.' }; invocationKind: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'New local root turn, existing or resumed turn, subagent turn, or unknown before hydration. Existing and subagent turns are excluded from first-response comparisons.' }; firstResponseTextMs?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Monotonic milliseconds from invocation entry through preparation to first nonwhitespace live root markdown emission; absent without text.' }; + firstResponseOrReasoningMs?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Monotonic milliseconds from invocation entry through preparation to the first nonwhitespace live root markdown or reasoning emission, whichever came first; never later than firstResponseTextMs, and absent without either. Excludes replayed, subagent, and tool output.' }; rootToolCallsBeforeFirstText?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Distinct live root tool calls presented before first root text; excludes child calls and replay, and is absent without qualifying text. Not a model-call count.' }; rendererRootInvocationOrdinal?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'One-based root invocation attempt ordinal across providers in this renderer lifetime, including declined and resumed attempts; absent for subagents or unresolved routing.' }; trustInteractionRequired: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether this invocation requested an interactive decision for untrusted workspace or resource access. Exclude these rows from primary latency comparisons.' }; @@ -53,9 +55,10 @@ export type AgentHostFirstResponseClassification = { hasResponseText: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether this invocation emitted nonwhitespace live root response text.' }; }; -/** Tracks only explicitly observed live text; callers must not feed replay, reasoning, or tool output. */ +/** Tracks only explicitly observed live root output; callers must not feed replay, subagent, or tool output, and must report reasoning through `observeReasoning`. */ export class AgentHostFirstResponseTiming { private firstResponseTextMs: number | undefined; + private firstResponseOrReasoningMs: number | undefined; private readonly rootToolCallIds = new Set(); constructor(private readonly clock: Pick = StopWatch.create()) { } @@ -63,6 +66,13 @@ export class AgentHostFirstResponseTiming { observeText(text: string): void { if (this.firstResponseTextMs === undefined && text.trim().length > 0) { this.firstResponseTextMs = this.clock.elapsed(); + this.firstResponseOrReasoningMs ??= this.firstResponseTextMs; + } + } + + observeReasoning(text: string): void { + if (this.firstResponseOrReasoningMs === undefined && text.trim().length > 0) { + this.firstResponseOrReasoningMs = this.clock.elapsed(); } } @@ -72,11 +82,12 @@ export class AgentHostFirstResponseTiming { } } - finish(context: Omit): IAgentHostFirstResponseEvent { + finish(context: Omit): IAgentHostFirstResponseEvent { return { schemaVersion: 1, ...context, firstResponseTextMs: this.firstResponseTextMs, + firstResponseOrReasoningMs: this.firstResponseOrReasoningMs, rootToolCallsBeforeFirstText: this.firstResponseTextMs === undefined ? undefined : this.rootToolCallIds.size, totalElapsedMs: this.clock.elapsed(), hasResponseText: this.firstResponseTextMs !== undefined, diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostGenericConfigChips.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostGenericConfigChips.ts index c430c53898cf..dbee909a8f8b 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostGenericConfigChips.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostGenericConfigChips.ts @@ -5,7 +5,7 @@ import * as dom from '../../../../../../base/browser/dom.js'; import { Event } from '../../../../../../base/common/event.js'; -import { Disposable, DisposableMap, IDisposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableMap, DisposableStore, IDisposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; import { isEqual } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; @@ -21,6 +21,7 @@ import { IAgentHostSessionWorkingDirectoryResolver } from './agentHostSessionWor import { IAgentHostNewSessionFolderService } from './agentHostNewSessionFolderService.js'; import { IAgentHostUntitledProvisionalSessionService } from './agentHostUntitledProvisionalSessionService.js'; import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import { getLocalAgentHostSessionProvider, resolveAgentHostChatSession, toAgentHostBackendSessionUri } from './agentHostSessionUri.js'; import { AgentHostInitialSessionConfig, retrySessionConfigSubscriptionOnCreation } from './agentHostSessionConfigSubscription.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; @@ -42,6 +43,7 @@ export class AgentHostGenericConfigChips extends Disposable { private _container: HTMLElement | undefined; private readonly _chips = this._register(new DisposableMap()); + private readonly _draftListeners = this._register(new DisposableStore()); private readonly _chipElements = new Map(); /** Subscription to the active session, replaced when its resource or owning connection changes. */ @@ -51,7 +53,7 @@ export class AgentHostGenericConfigChips extends Disposable { }>()); private _initialResolved: { readonly sessionResource: URI; readonly result: ResolveSessionConfigResult } | undefined; - private readonly _initialConfig = this._register(new AgentHostInitialSessionConfig(error => this._logService.warn('[AgentHostGenericConfigChips] Failed to resolve initial session configuration', error))); + private readonly _initialConfig: AgentHostInitialSessionConfig; constructor( private readonly _widget: IChatWidget, @@ -64,8 +66,11 @@ export class AgentHostGenericConfigChips extends Disposable { @ILogService private readonly _logService: ILogService, @IAgentHostService agentHostService: IAgentHostService, @IConfigurationService private readonly _configurationService: IConfigurationService, + @IWorkspaceTrustManagementService workspaceTrustManagementService: IWorkspaceTrustManagementService, ) { super(); + this._initialConfig = this._register(new AgentHostInitialSessionConfig(error => this._logService.warn('[AgentHostGenericConfigChips] Failed to resolve initial session configuration', error), workspaceTrustManagementService)); + this._register(this._initialConfig.onDidInvalidate(() => this._invalidateInitialResolve())); this._register(this._widget.onDidChangeViewModel(() => this._reattach())); this._register(this._configurationService.onDidChangeConfiguration(event => { if (affectsAgentHostProviderPreference(event, true)) { @@ -117,6 +122,7 @@ export class AgentHostGenericConfigChips extends Disposable { } private _reattach(): void { + this._draftListeners.clear(); const sessionResource = this._widget.viewModel?.sessionResource; const localProvider = sessionResource ? getLocalAgentHostSessionProvider(sessionResource) : undefined; const provisionalBackend = sessionResource ? this._provisional.get(sessionResource) : undefined; @@ -133,12 +139,20 @@ export class AgentHostGenericConfigChips extends Disposable { const localBackend = toAgentHostBackendSessionUri(sessionResource, this._connectionsService); if (localBackend && localProvider && isUntitledChatSession(sessionResource) && !provisionalBackend) { this._subRef.clear(); + this._draftListeners.add(this._newSessionFolderService.onDidChangeFolder(resource => { + if (isEqual(resource, sessionResource)) { + this._invalidateInitialResolve(); + } + })); + this._draftListeners.add(this._workspaceContextService.onDidChangeWorkspaceFolders(() => this._invalidateInitialResolve())); const prepared = this._provisional.getResolvedConfig(sessionResource) ?? this._provisional.getPreparedSessionConfig(sessionResource); if (prepared) { this._initialResolved = { sessionResource, result: prepared }; - } else if (!this._initialResolved || this._initialResolved.sessionResource.toString() !== sessionResource.toString()) { - this._initialResolved = undefined; + } else { void this._refreshInitialResolved(sessionResource, localProvider, resolution); + if (this._initialResolved?.result !== this._initialConfig.value) { + this._initialResolved = undefined; + } } this._sync(); return; @@ -172,6 +186,15 @@ export class AgentHostGenericConfigChips extends Disposable { this._sync(); } + private _invalidateInitialResolve(): void { + const sessionResource = this._widget.viewModel?.sessionResource; + if (sessionResource && isUntitledChatSession(sessionResource) && getLocalAgentHostSessionProvider(sessionResource)) { + this._initialResolved = undefined; + this._cancelInitialResolve(); + this._reattach(); + } + } + private _cancelInitialResolve(): void { this._initialConfig.clear(); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalCustomizations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalCustomizations.ts index 068e2aea09b2..a3132adcf2ce 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalCustomizations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalCustomizations.ts @@ -310,21 +310,11 @@ export async function resolveCustomizationRefs( } // Plugin prompt discovery is not guaranteed to be hydrated before an agent - // host registration resolves (notably in the Agents window). Include every - // enabled plugin with a concrete contribution directly; `pluginRefs` + // host registration resolves (notably in the Agents window), and plugins can + // ship content only the agent host runtime understands (for example Copilot + // extensions with canvases). Include every installed plugin; `pluginRefs` // de-duplicates those already found through prompt-file enumeration. for (const plugin of plugins) { - if (pluginRefs.has(plugin.uri.toString())) { - continue; - } - if (plugin.hooks.get().length === 0 - && plugin.commands.get().length === 0 - && plugin.skills.get().length === 0 - && plugin.agents.get().length === 0 - && plugin.instructions.get().length === 0 - && plugin.mcpServerDefinitions.get().length === 0) { - continue; - } addPluginRef(plugin); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalModelSupport.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalModelSupport.ts index 32290263a6d7..046ac1430e3c 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalModelSupport.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLocalModelSupport.ts @@ -137,6 +137,8 @@ export interface ILocalModelTurnPresentationContext { readonly resolveCloudModelName: (rawModelId: string) => string | undefined; /** Auto explainability is hidden: name no cloud model the router picked. */ readonly hideCloudModelName?: boolean; + /** Auto is presented as Copilot Fusion, so the labels name it that way. */ + readonly fusion?: boolean; } /** @@ -162,7 +164,9 @@ export function getLocalModelTurnPresentation(execution: ILocalTurnExecution, co switch (execution.execution) { case 'local': { return { - name: localize({ key: 'agentHost.localModel.labelLocal', comment: ['{0} is a model name followed by "On-device", e.g. "MAI Code 1.1 Flash · On-device"'] }, "Auto ({0})", onDeviceName), + name: context.fusion + ? localize({ key: 'agentHost.localModel.labelLocalFusion', comment: ['{0} is a model name followed by "On-device", e.g. "MAI Code 1.1 Flash · On-device"'] }, "Copilot Fusion ({0})", onDeviceName) + : localize({ key: 'agentHost.localModel.labelLocal', comment: ['{0} is a model name followed by "On-device", e.g. "MAI Code 1.1 Flash · On-device"'] }, "Auto ({0})", onDeviceName), routed: { id: context.localModelId ?? execution.familyId ?? onDeviceName, name: onDeviceName }, billed: context.localModelId ? { rawModelId: context.localModelId, name: onDeviceName } : undefined, }; @@ -170,16 +174,28 @@ export function getLocalModelTurnPresentation(execution: ILocalTurnExecution, co case 'fallback': { const hover = localize('agentHost.localModel.fallbackHover', "The on-device model was unavailable, so a cloud model was used."); return { - name: localize('agentHost.localModel.labelFallback', "Auto ({0})", cloudName), + name: context.fusion + ? localize('agentHost.localModel.labelFallbackFusion', "Copilot Fusion ({0})", cloudName) + : localize('agentHost.localModel.labelFallback', "Auto ({0})", cloudName), hover, - routed: cloudModelId ? { id: cloudModelId, name: cloudName, reason: localize('agentHost.localModel.fallbackReason', "Auto routed task to {0}. {1}", cloudName, hover) } : undefined, + routed: cloudModelId ? { + id: cloudModelId, + name: cloudName, + reason: context.fusion + ? localize('agentHost.localModel.fallbackReasonFusion', "Copilot Fusion routed task to {0}. {1}", cloudName, hover) + : localize('agentHost.localModel.fallbackReason', "Auto routed task to {0}. {1}", cloudName, hover), + } : undefined, billed: cloudModelId ? { rawModelId: cloudModelId, name: cloudName } : undefined, }; } case 'mixed': { - const reason = localize('agentHost.localModel.mixedReason', "Auto ran part of this task on this device and part on {0}.", cloudName); + const reason = context.fusion + ? localize('agentHost.localModel.mixedReasonFusion', "Copilot Fusion ran part of this task on this device and part on {0}.", cloudName) + : localize('agentHost.localModel.mixedReason', "Auto ran part of this task on this device and part on {0}.", cloudName); return { - name: localize('agentHost.localModel.labelMixed', "Auto (On-device + {0})", cloudName), + name: context.fusion + ? localize('agentHost.localModel.labelMixedFusion', "Copilot Fusion (On-device + {0})", cloudName) + : localize('agentHost.localModel.labelMixed', "Auto (On-device + {0})", cloudName), hover: reason, routed: cloudModelId ? { id: cloudModelId, name: cloudName, reason } : undefined, billed: cloudModelId ? { rawModelId: cloudModelId, name: cloudName } : undefined, @@ -246,8 +262,11 @@ export class AgentHostLocalModelSupport extends Disposable { return this._isEnabled() ? getLocalModelDisplayName(this._getStatus(), rawModelId) : undefined; } - /** The label of a turn that reported on-device execution, or `undefined` to keep the existing label. */ - getTurnPresentation(usage: UsageInfo | undefined, selectedRawModelId: string | undefined, resolveCloudModelName: (rawModelId: string) => string | undefined, hideCloudModelName: boolean | undefined): ILocalModelTurnPresentation | undefined { + /** + * The label of a turn that reported on-device execution, or `undefined` to keep the existing label. + * @param fusion Whether the chat's Auto model is presented as Copilot Fusion. + */ + getTurnPresentation(usage: UsageInfo | undefined, selectedRawModelId: string | undefined, resolveCloudModelName: (rawModelId: string) => string | undefined, hideCloudModelName: boolean | undefined, fusion?: boolean): ILocalModelTurnPresentation | undefined { const execution = readLocalModelTurnExecution(usage); if (!execution || execution.execution === 'unknown') { return undefined; @@ -256,11 +275,14 @@ export class AgentHostLocalModelSupport extends Disposable { const isAuto = selectedRawModelId === AUTO_RAW_MODEL_ID || !!resolution; const localModelId = resolution?.chosenModel ?? usage?.model ?? selectedRawModelId; const localName = getLocalModelDisplayName(this._getStatus(), localModelId, execution.familyId); - return getLocalModelTurnPresentation(execution, { isAuto, localName, localModelId, resolveCloudModelName, hideCloudModelName }); + return getLocalModelTurnPresentation(execution, { isAuto, localName, localModelId, resolveCloudModelName, hideCloudModelName, fusion }); } - /** Shows the one-time fallback notice for a session when a live turn fell back from the on-device model to the cloud. */ - noteCompletedTurn(sessionResource: URI, usage: UsageInfo | undefined): void { + /** + * Shows the one-time fallback notice for a session when a live turn fell back from the on-device model to the cloud. + * @param fusion Whether the chat's Auto model is presented as Copilot Fusion. + */ + noteCompletedTurn(sessionResource: URI, usage: UsageInfo | undefined, fusion?: boolean): void { const execution = readLocalModelTurnExecution(usage); const key = sessionResource.toString(); if (execution?.execution !== 'fallback' || this._fallbackNoticeShown.has(key)) { @@ -273,7 +295,9 @@ export class AgentHostLocalModelSupport extends Disposable { id: `localModel.fallback.${key}`, sessionResources: [sessionResource], severity: ChatInputNotificationSeverity.Info, - message: localize('agentHost.localModel.fallbackNotice', "{0} couldn't respond, so Auto used a cloud model.", name), + message: fusion + ? localize('agentHost.localModel.fallbackNoticeFusion', "{0} couldn't respond, so Copilot Fusion used a cloud model.", name) + : localize('agentHost.localModel.fallbackNotice', "{0} couldn't respond, so Auto used a cloud model.", name), description: undefined, actions: [], dismissible: true, @@ -282,8 +306,11 @@ export class AgentHostLocalModelSupport extends Disposable { }); } - /** The pre-send guard: `true` when the request may be sent; otherwise its draft goes back to the input and a notice offers to load the model, switch, or use Auto. */ - async checkBeforeSend(request: IChatAgentRequest, rawModelId: string | undefined): Promise { + /** + * The pre-send guard: `true` when the request may be sent; otherwise its draft goes back to the input and a notice offers to load the model, switch, or use Auto. + * @param fusion Whether the chat's Auto model is presented as Copilot Fusion. + */ + async checkBeforeSend(request: IChatAgentRequest, rawModelId: string | undefined, fusion?: boolean): Promise { if (!rawModelId || !this._isEnabled() || !this._getStatus()) { return true; } @@ -299,7 +326,7 @@ export class AgentHostLocalModelSupport extends Disposable { this._logService.info(`[AgentHost] On-device model '${identifierForLog(check.familyId)}' isn't loaded; keeping the draft`); this._restoreDraft(request); void this._chatService.removeRequest(request.sessionResource, request.requestId).catch(onUnexpectedError); - this._showModelNotActiveNotice(request.sessionResource, check, status); + this._showModelNotActiveNotice(request.sessionResource, check, status, fusion); return false; } @@ -327,7 +354,7 @@ export class AgentHostLocalModelSupport extends Disposable { return `localModel.modelNotActive.${sessionResource.toString()}`; } - private _showModelNotActiveNotice(sessionResource: URI, check: Extract, status: ILocalModelStatusV1 | undefined): void { + private _showModelNotActiveNotice(sessionResource: URI, check: Extract, status: ILocalModelStatusV1 | undefined, fusion: boolean | undefined): void { const id = this._notificationId(sessionResource); const family = status?.families.find(candidate => candidate.familyId === check.familyId); const activeFamily = check.activeFamilyId ? status?.families.find(candidate => candidate.familyId === check.activeFamilyId) : undefined; @@ -355,7 +382,9 @@ export class AgentHostLocalModelSupport extends Disposable { } actions.push({ kind: ChatInputNotificationActionKind.SwitchToModel, - label: localize('agentHost.localModel.useAuto', "Use Auto"), + label: fusion + ? localize('agentHost.localModel.useFusion', "Use Copilot Fusion") + : localize('agentHost.localModel.useAuto', "Use Auto"), matchesModel: model => isAutoLanguageModel(model) && model.metadata.targetChatSessionType === this._sessionType, requireUniqueModel: true, telemetryActionId: 'localModel.useAuto', diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSandboxNotification.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSandboxNotification.ts index 8d7fe16aa7a4..db50aeb44e20 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSandboxNotification.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSandboxNotification.ts @@ -283,9 +283,10 @@ export class AgentHostSandboxNotification extends Disposable { : localize({ key: 'agentHost.sandboxCertificateMissingDetail', comment: ['{0} is a Markdown link labeled "Learn more" that opens certificate trust documentation.'], - }, "Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. {0}.", learnMore.value)); + }, "Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. You can install it later from the Command Palette with Sandbox: Manage Trusted CA. {0}.", learnMore.value)); this._notificationService.setNotification({ id: this._certificateId, + placement: !hasError && !this._certificateOperation && !this._certificateRefreshing ? 'transcript' : undefined, inputUri, severity: ChatInputNotificationSeverity.Info, message: this._certificateRefreshing @@ -310,6 +311,7 @@ export class AgentHostSandboxNotification extends Disposable { label: localize('agentHost.installSandboxCertificate', "Install"), tooltip: localize('agentHost.installSandboxCertificateTooltip', "Install the sandbox certificate on this chat's agent host"), commandId: this._installCommandId, + primary: true, keepOpen: true, }] : [], ...(this._certificateOperation || this._certificateRefreshing ? { progress: {} } : {}), diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionConfigSubscription.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionConfigSubscription.ts index 801bae5c0206..1a7e3e061c0d 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionConfigSubscription.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionConfigSubscription.ts @@ -3,7 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { Emitter } from '../../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { ResourceMap } from '../../../../../../base/common/map.js'; import { equals } from '../../../../../../base/common/objects.js'; import { isEqual } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; @@ -13,10 +15,40 @@ import { SessionState } from '../../../../../../platform/agentHost/common/state/ import { NotificationType } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; import { IAgentHostSessionResolution } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { ResolveSessionConfigResult } from '../../../../../../platform/agentHost/common/state/protocol/commands.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; -/** Shares initial config reads until the chat, owning connection, backend, working directory or defaults change. */ +const pendingTargetFolderTrustChecks = new WeakMap>>(); + +/** Shares concurrent target-folder trust checks, falling back to workspace trust only when no folder is known. */ +export async function isAgentHostTargetFolderTrusted(workingDirectory: URI | undefined, workspaceTrustManagementService: IWorkspaceTrustManagementService): Promise { + if (!workingDirectory) { + return workspaceTrustManagementService.isWorkspaceTrusted(); + } + let checks = pendingTargetFolderTrustChecks.get(workspaceTrustManagementService); + if (!checks) { + checks = new ResourceMap(); + pendingTargetFolderTrustChecks.set(workspaceTrustManagementService, checks); + } + let check = checks.get(workingDirectory); + if (!check) { + check = workspaceTrustManagementService.getUriTrustInfo(workingDirectory).then(info => info.trusted); + checks.set(workingDirectory, check); + } + try { + return await check; + } finally { + if (checks.get(workingDirectory) === check) { + checks.delete(workingDirectory); + } + } +} + +/** Shares initial config reads until the chat, owning connection, backend, working directory, defaults or trust change. */ export class AgentHostInitialSessionConfig extends Disposable { + private readonly _onDidInvalidate = this._register(new Emitter()); + readonly onDidInvalidate = this._onDidInvalidate.event; private _generation = 0; + private _trustCheckGeneration: number | undefined; private _value: ResolveSessionConfigResult | undefined; private _request: { readonly sessionResource: URI; @@ -27,9 +59,23 @@ export class AgentHostInitialSessionConfig extends Disposable { readonly promise: Promise; } | undefined; - constructor(private readonly _onError: (error: unknown) => void) { + constructor( + private readonly _onError: (error: unknown) => void, + @IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService, + ) { super(); this._register(toDisposable(() => this.clear())); + const invalidate = () => { + this.clear(); + this._onDidInvalidate.fire(); + }; + this._register(this._workspaceTrustManagementService.onDidChangeTrust(invalidate)); + this._register(this._workspaceTrustManagementService.onDidChangeTrustedFolders(() => { + // A pending source lookup returns current trust after its own folder notifications. + if (this._trustCheckGeneration === undefined) { + invalidate(); + } + })); } get value(): ResolveSessionConfigResult | undefined { return this._value; } @@ -48,6 +94,7 @@ export class AgentHostInitialSessionConfig extends Disposable { clear(): void { this._generation++; + this._trustCheckGeneration = undefined; this._request = undefined; this._value = undefined; } @@ -61,12 +108,29 @@ export class AgentHostInitialSessionConfig extends Disposable { return current.promise; } const generation = ++this._generation; + this._trustCheckGeneration = generation; this._value = undefined; - const operation = Promise.resolve().then(() => generation === this._generation ? resolution.connection.resolveSessionConfig({ - provider, - workingDirectory, - ...(config ? { config } : {}), - }) : undefined); + const operation = Promise.resolve().then(async () => { + if (generation !== this._generation) { + return undefined; + } + let trusted: boolean; + try { + trusted = await isAgentHostTargetFolderTrusted(workingDirectory, this._workspaceTrustManagementService); + } finally { + if (this._trustCheckGeneration === generation) { + this._trustCheckGeneration = undefined; + } + } + if (!trusted || generation !== this._generation) { + return undefined; + } + return resolution.connection.resolveSessionConfig({ + provider, + workingDirectory, + ...(config ? { config } : {}), + }); + }); const promise = this._read(operation, generation); this._request = { sessionResource, provider, resolution, workingDirectory, config, promise }; return promise; @@ -76,7 +140,11 @@ export class AgentHostInitialSessionConfig extends Disposable { try { const result = await operation; if (generation === this._generation) { - this._value = result; + if (result === undefined) { + this.clear(); + } else { + this._value = result; + } return result; } return undefined; 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 f97b9a4ea5e4..f955941f013a 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts @@ -27,7 +27,7 @@ import { AgentHostSteeringMessageHandoff } from './agentHostSteeringMessageHando import { MicrotaskDelay } from '../../../../../../base/common/symbols.js'; import { Mutable } from '../../../../../../base/common/types.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { generateUuid } from '../../../../../../base/common/uuid.js'; +import { generateUuid, isUUID } from '../../../../../../base/common/uuid.js'; import { getOlderHostSubagentChatUri } from '../../../../../../platform/agentHost/browser/agentHostOlderHostCompatibility.js'; import { AccessibilitySignal, IAccessibilitySignalService } from '../../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.js'; import { IAccessibilityService } from '../../../../../../platform/accessibility/common/accessibility.js'; @@ -60,9 +60,10 @@ import { readToolCallMeta, readAgentToolOutputDelta } from '../../../../../../pl import { readMcpRoutingServers, readMcpServerConnectorName } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; import { filterSessionConfigValues } from '../../../../../../platform/agentHost/common/sessionConfigProperties.js'; import { readAttachmentDetail, withAttachmentDetail } from '../../../../../../platform/agentHost/common/meta/attachmentMeta.js'; +import { withHumanChatInputResponse } from '../../../../../../platform/agentHost/common/meta/agentChatInputResponseMeta.js'; import { AgentPermissionDecisionSource, readAgentPermissionResponseMeta, toAgentPermissionResponseMeta } from '../../../../../../platform/agentHost/common/meta/agentPermissionResponseMeta.js'; import { readArtifactIntegrationRequest } from '../../../../../../platform/agentHost/common/meta/agentHostArtifactIntegrationMeta.js'; -import { readCompletionAttachmentMeta } from '../../../../../../platform/agentHost/common/meta/agentCompletionAttachmentMeta.js'; +import { getCompletionDescription, readCompletionAttachmentMeta } from '../../../../../../platform/agentHost/common/meta/agentCompletionAttachmentMeta.js'; import { readSlashCommandResource, type ISlashCommandResource } from '../../../../../../platform/agentHost/common/meta/agentSlashCommandOutputMeta.js'; import { IRemoteAgentHostService } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { AgentHostClientConnectionKind, agentHostClientConnectionKindValidator } from '../../../../../../platform/agentHost/common/agentHostTelemetry.js'; @@ -79,7 +80,7 @@ import { ChatTruncatedAction } from '../../../../../../platform/agentHost/common import { CompletionItemKind as AhpCompletionItemKind, ContentEncoding, type CompletionItem as AhpCompletionItem } from '../../../../../../platform/agentHost/common/state/protocol/commands.js'; import { BackgroundWorkKind, ConfirmationOptionKind, CustomizationType, JsonPrimitive, McpServerAuthRequiredState, McpServerStatus, SessionInputRequestKind, SessionLifecycle, TerminalClaimKind, ToolCallContributorKind, ToolResultContentType, type ConfirmationOption, type ProtectedResourceMetadata, type SessionActiveClient, type SessionInputRequest, type SessionToolClientExecutionRequest, type ToolDefinition } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; import { compareProtocolVersions } from '../../../../../../platform/agentHost/common/state/protocol/version/registry.js'; -import { ActionType, ChatTurnStartedAction, isChatAction, type ClientChatAction, type ClientSessionAction } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; +import { ActionType, ChatTurnStartedAction, isChatAction, type ChatInputCompletedAction, type ClientChatAction, type ClientSessionAction } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; import { AuthenticateTargetKind, AhpErrorCodes, AHP_AUTH_REQUIRED, AHP_NOT_FOUND, JsonRpcErrorCodes, ProtocolError } from '../../../../../../platform/agentHost/common/state/sessionProtocol.js'; import { ChangesetStatus, ChatOriginKind, getSessionChatResource, getErrorResponsePart, getInlineToolInput, getTurnError, isChatReadOnly, MessageAttachmentKind, MessageKind, PendingMessageKind, ResponsePartKind, ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, SessionStatus, StateComponents, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallStatus, TurnState, mergeSessionWithDefaultChat, readSessionScratchFolders, readSessionWorkspaceless, type ChatState, type ISessionFileDiff, type ISessionWithDefaultChat, type ICompletedToolCall, type InputRequestResponsePart, type MarkdownResponsePart, type Message, type MessageAttachment, type MessageAnnotationsAttachment, type MessageChatAttachment, type MessageResourceAttachment, type MessageEmbeddedResourceAttachment, type ModelSelection, type PendingMessage, type ReasoningResponsePart, type RootState, type ChatInputAnswer, type ChatInputQuestion, type ChatSummary, type SessionState, type StringOrMarkdown, type ToolCallPendingConfirmationState, type ToolCallResponsePart, type ToolCallRunningState, type ToolCallState, type ToolInput, type Turn, type UsageInfo } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; @@ -175,7 +176,7 @@ import { ICopilotHomeService } from '../../../../../services/environment/common/ import { toolDataToDefinition } from './agentHostToolUtils.js'; import { IAgentHostUntitledProvisionalSessionService } from './agentHostUntitledProvisionalSessionService.js'; import { IAgentHostImportConversation, IAgentHostImportConversationStore } from './agentHostImportConversationStore.js'; -import { activeTurnToProgress, appendToolOutput, BOOLEAN_TRUE_OPTION_ID, canOwnSubagentChat, chatUsageToSessionCost, completedToolCallToEditParts, completedToolCallToSerialized, containsAutomaticReplyAnswer, convertProtocolAnswers, createInputRequestCarousel, createInputRequestPlanReview, finalizeToolInvocation, formatTurnResponseDetails, getAgentHostActivityProgressId, getElicitationInputRequestPresentation, getTerminalContent, isEmptyFormInputRequest, isSubagentTool, makeAhpTerminalToolSessionId, messageAttachmentsToVariableData, messageToRequestOrigin, messageToRequestSource, messageToVariableData, parseAhpTerminalToolSessionId, reasoningPartToThinking, rewriteAgentHostLinkTarget, shouldObserveSubagentChat, stringOrMarkdownToString, systemNotificationToChatPart, toolCallAuthenticationServer, toolCallStateToInvocation, toolCallStateToPreparedInvocation, toolCallStateToStreamingInvocation, turnsToHistory, turnToResponseDetails, turnToResultMetadata, updateRunningToolSpecificData, updateStreamingToolInvocation, usageInfoToAutoModeResolution, usageInfoToChatUsage, usageInfoToQuotas, type IAgentHostToolInvocationOptions, type ITurnModelInfo, type TurnModelLookup } from './stateToProgressAdapter.js'; +import { activeTurnToProgress, appendToolOutput, BOOLEAN_TRUE_OPTION_ID, canOwnSubagentChat, chatUsageToSessionCost, completedToolCallToEditParts, completedToolCallToSerialized, containsAutomaticReplyAnswer, convertProtocolAnswers, createInputRequestCarousel, createInputRequestPlanReview, finalizeToolInvocation, formatTurnResponseDetails, getAgentHostActivityProgressId, getElicitationInputRequestPresentation, getTerminalContent, isEmptyFormInputRequest, isModelRouterPickSettled, isSubagentTool, makeAhpTerminalToolSessionId, messageAttachmentsToVariableData, messageToRequestOrigin, messageToRequestSource, messageToVariableData, parseAhpTerminalToolSessionId, reasoningPartToThinking, rewriteAgentHostLinkTarget, shouldObserveSubagentChat, stringOrMarkdownToString, systemNotificationToChatPart, toolCallAuthenticationServer, toolCallStateToInvocation, toolCallStateToPreparedInvocation, toolCallStateToStreamingInvocation, turnsToHistory, turnToResponseDetails, turnToResultMetadata, updateRunningToolSpecificData, updateStreamingToolInvocation, usageInfoToAutoModeResolution, usageInfoToChatUsage, usageInfoToQuotas, type IAgentHostToolInvocationOptions, type ITurnModelInfo, type TurnModelLookup } from './stateToProgressAdapter.js'; import { isCopilotHydraFusionModelId } from '../../../../../../platform/agentHost/common/copilotCliConfig.js'; import { getFusionAutoModeTierLabel } from '../../../../../../platform/agentHost/common/autoModeTiers.js'; import { getFusionTierLabel } from '../../widget/input/modelPicker/modelPickerPresentation.js'; @@ -299,6 +300,8 @@ interface IObserveTurnOptions { /** Receives the final turn for structured result and error details, never markdown progress. */ readonly onTurnEnded?: (lastTurn: Turn | undefined) => void; readonly onResponseText?: (text: string) => void; + /** Receives live reasoning deltas of this turn; never set for subagent or replaying observers. */ + readonly onResponseReasoning?: (text: string) => void; readonly onOpenResponseResource?: (resource: ISlashCommandResource) => void; /** * When set, this turn is being observed as part of a subagent session. @@ -683,8 +686,7 @@ async function resolveToolInput(connection: IAgentConnection, toolInput: ToolInp /** * Converts carousel answers (IChatQuestionAnswers) to protocol - * ChatInputAnswer records, handling text, single-select, - * boolean, and multi-select answer shapes. + * ChatInputAnswer records, preserving the question kind for freeform selections. */ export function convertCarouselAnswers(raw: IChatQuestionAnswers, questions: readonly ChatInputQuestion[] = []): Record { const answers: Record = {}; @@ -716,13 +718,13 @@ export function convertCarouselAnswers(raw: IChatQuestionAnswers, questions: rea value: single.selectedValue === BOOLEAN_TRUE_OPTION_ID, }, }; - } else if (single.selectedValue) { + } else if (single.selectedValue || (single.freeformValue && questionKinds.get(qId) === ChatInputQuestionKind.SingleSelect)) { // Single-select answer answers[qId] = { state: ChatInputAnswerState.Submitted, value: { kind: ChatInputAnswerValueKind.Selected, - value: single.selectedValue, + value: single.selectedValue ?? '', freeformValues: single.freeformValue ? [single.freeformValue] : undefined, }, }; @@ -1676,16 +1678,24 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC * Resolves the signed-in user's plan context for chat error formatting. * The agent host does not know the user's plan, so quota/rate-limit * messages are personalized here from `IChatEntitlementService`. + * @param sessionResource The chat whose Auto model rate-limit messages suggest switching to. */ - private _chatErrorContext(): IChatErrorContext { + private _chatErrorContext(sessionResource: URI | undefined): IChatErrorContext { const quotas = this._chatEntitlementService.quotas; return { copilotPlan: getCopilotPlanFromEntitlement(this._chatEntitlementService.entitlement), isUsageBasedBilling: quotas.usageBasedBilling, quotaResetDate: quotas.resetDate, + autoModelFusion: !!sessionResource && this._isAutoModelFusion(sessionResource), }; } + /** Whether the Auto model of the chat `sessionResource` is presented as Copilot Fusion, as its host advertised. */ + private _isAutoModelFusion(sessionResource: URI): boolean { + const autoModelId = this._toLanguageModelId(sessionResource, AUTO_RAW_MODEL_ID); + return !!autoModelId && !!this._languageModelsService.lookupLanguageModel(autoModelId)?.autoModelFusion; + } + async provideChatInputCompletions(sessionResource: URI, params: IChatInputCompletionsParams, token: CancellationToken): Promise { let backendSession: URI; if (isUntitledChatSession(sessionResource)) { @@ -1761,19 +1771,19 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC ...(attachment._meta !== undefined && { _meta: attachment._meta }), }, attachment.label !== raw.insertText ? attachment.label : undefined); } - if (completionMeta?.kind === 'skill') { + return this._createCompletionItem(raw, text, { kind: 'text' }, attachment.label !== raw.insertText ? attachment.label : undefined); + } + case MessageAttachmentKind.Resource: { + const uri = this._config.connection.resourceUris.fromAgentHost(typeof attachment.uri === 'string' ? URI.parse(attachment.uri, attachment.displayKind === 'skill') : URI.from(attachment.uri)); + if (attachment.displayKind === 'skill') { return this._createCompletionItem(raw, text, { kind: 'skill', - uri: this._config.connection.resourceUris.fromAgentHost(URI.parse(completionMeta.uri)), - ...(completionMeta.displayName !== undefined ? { displayName: completionMeta.displayName } : {}), - ...(completionMeta.description !== undefined ? { description: completionMeta.description } : {}), + uri, + displayName: attachment.label.replace(/^\//, ''), + description: getCompletionDescription(attachment), ...(attachment._meta !== undefined && { _meta: attachment._meta }), }); } - return this._createCompletionItem(raw, text, { kind: 'text' }, attachment.label !== raw.insertText ? attachment.label : undefined); - } - case MessageAttachmentKind.Resource: { - const uri = this._config.connection.resourceUris.fromAgentHost(typeof attachment.uri === 'string' ? URI.parse(attachment.uri) : URI.from(attachment.uri)); return this._createCompletionItem(raw, text, { kind: 'resource', uri, @@ -1843,6 +1853,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC let chatTitle: string | undefined; let draftInputState: ISerializableChatModelInputState | undefined; let draftModelId: string | undefined; + let draftModelConfiguration: ModelSelection['config']; let sessionSubscription: IAgentSubscription | undefined; let chatSubscription: IAgentSubscription | undefined; const historySubagentObservations = new DisposableStore(); @@ -1892,6 +1903,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const draft = sessionState.draft ?? emptyDraftFromLastTurn(sessionState); draftInputState = this._draftToInputState(sessionResource, draft); draftModelId = this._toLanguageModelId(sessionResource, draft?.model?.id); + draftModelConfiguration = draft?.model?.config; if (!sessionState.draft && draft) { this._config.connection.dispatch(chatURI, { type: ActionType.ChatDraftChanged, draft }); } @@ -1907,10 +1919,10 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC this._config.agentId, this._config.connectionAuthority, lookup, - this._chatErrorContext(), + this._chatErrorContext(sessionResource), this._config.connection.initializeResult.get()?.terminalCommandPrefix, this._config.connection.resourceUris, - turn => this._getTurnErrorDetails(turn, allowTurnResume), + turn => this._getTurnErrorDetails(sessionResource, turn, allowTurnResume), readAgentContextUsage(sessionState, sessionState.turns.at(-1)?.usage), this._managedPluginRetryTarget(resolvedSession, chatURI), )); @@ -2065,7 +2077,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC }); return Promise.resolve(); }, - draftInputState ? { editingSession: undefined, inputState: draftInputState, ...(draftModelId ? { selectedModelId: draftModelId } : {}) } : undefined, + draftInputState ? { editingSession: undefined, inputState: draftInputState, ...(draftModelId ? { selectedModelId: draftModelId, ...(draftModelConfiguration ? { selectedModelConfiguration: draftModelConfiguration } : {}) } : {}) } : undefined, initialProgress?.filter(part => !isUnstartedSubagent(part)), historySubagentObservations, () => { @@ -2290,7 +2302,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // On-device models: a chat bound to an installed model that isn't loaded keeps its draft. if (!this._isSubagentChat(this._resolveSessionUri(request.sessionResource).toString(), invocationChat) && !request.acceptedConfirmationData?.length && !request.rejectedConfirmationData?.length - && !await this._localModels.checkBeforeSend(request, this._extractRawModelId(request.userSelectedModelId))) { + && !await this._localModels.checkBeforeSend(request, this._extractRawModelId(request.userSelectedModelId), this._isAutoModelFusion(request.sessionResource))) { return {}; } @@ -2389,13 +2401,16 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC }; failureStage = 'prepareTurn'; - const completedTurn = await this._handleTurn(resolvedSession, request, measuredProgress, cancellationToken, stage => failureStage = stage, invocationKind === 'newTurn' ? text => firstResponse.observeText(text) : undefined); - this._localModels.noteCompletedTurn(request.sessionResource, completedTurn?.usage); + const timesFirstResponse = invocationKind === 'newTurn'; + const completedTurn = await this._handleTurn(resolvedSession, request, measuredProgress, cancellationToken, stage => failureStage = stage, + timesFirstResponse ? text => firstResponse.observeText(text) : undefined, + timesFirstResponse ? text => firstResponse.observeReasoning(text) : undefined); + this._localModels.noteCompletedTurn(request.sessionResource, completedTurn?.usage, this._isAutoModelFusion(request.sessionResource)); outcome = completedTurn?.state === TurnState.Error ? 'error' : completedTurn?.state === TurnState.Cancelled || cancellationToken.isCancellationRequested ? 'cancelled' : completedTurn ? 'success' : 'notDispatched'; const details = this._getTurnResponseDetails(request.sessionResource, resolvedSession, completedTurn); - const errorDetails = this._getTurnErrorDetails(completedTurn); + const errorDetails = this._getTurnErrorDetails(request.sessionResource, completedTurn); const metadata = turnToResultMetadata(completedTurn); return { @@ -2466,7 +2481,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC * non-error turns. Falls back to the raw error when no structured chat * error was forwarded in `_meta`. */ - private _getTurnErrorDetails(turn: Turn | undefined, allowResume = true): IChatResponseErrorDetails | undefined { + private _getTurnErrorDetails(sessionResource: URI, turn: Turn | undefined, allowResume = true): IChatResponseErrorDetails | undefined { const errorPart = getErrorResponsePart(turn); const error = getTurnError(turn); if (!error) { @@ -2482,7 +2497,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC }; } const isExecutionInterrupted = error.errorType === 'executionInterrupted'; - const forwardedDetails = getChatErrorDetailsFromMeta(error, this._chatErrorContext()); + const forwardedDetails = getChatErrorDetailsFromMeta(error, this._chatErrorContext(sessionResource)); const details: IChatResponseErrorDetails = isExecutionInterrupted ? { ...forwardedDetails, @@ -3018,8 +3033,8 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const lookup = this._createTurnModelLookup(sessionResource, lastTurnModelSelection(state)?.id); const allowTurnResume = !this._isChatReadOnly(sessionStr, chatURI); chatSession.updateHistory(turnsToHistory(backendSession, state.turns, this._config.agentId, this._config.connectionAuthority, - lookup, this._chatErrorContext(), this._config.connection.initializeResult.get()?.terminalCommandPrefix, - this._config.connection.resourceUris, turn => this._getTurnErrorDetails(turn, allowTurnResume), + lookup, this._chatErrorContext(sessionResource), this._config.connection.initializeResult.get()?.terminalCommandPrefix, + this._config.connection.resourceUris, turn => this._getTurnErrorDetails(sessionResource, turn, allowTurnResume), readAgentContextUsage(state, state.turns.at(-1)?.usage), this._managedPluginRetryTarget(backendSession, chatURI))); }; let previousContextUsage = currentState ? readAgentContextUsage(currentState, currentState.turns.at(-1)?.usage) : undefined; @@ -3681,7 +3696,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC ? turnToResponseDetails(lastTurn, this._createTurnModelLookup(chatSession.sessionResource, lastTurn.message.model?.id)) : undefined; const chatURI = this._getChatURI(chatSession.sessionResource); - const errorDetails = this._getTurnErrorDetails(lastTurn, !this._isChatReadOnly(backendSession.toString(), chatURI)); + const errorDetails = this._getTurnErrorDetails(chatSession.sessionResource, lastTurn, !this._isChatReadOnly(backendSession.toString(), chatURI)); const metadata = turnToResultMetadata(lastTurn); if (details || errorDetails || metadata) { void this._applyObservedTurnResult(chatSession, turnId, { @@ -3808,6 +3823,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC cancellationToken: CancellationToken, onFailureStage: (stage: AgentHostInvocationFailureStage) => void, onResponseText?: (text: string) => void, + onResponseReasoning?: (text: string) => void, ): Promise { if (this._isInvocationAbandoned(cancellationToken)) { return; @@ -3856,33 +3872,42 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC throw new Error(localize('agentHost.askUnavailable', "Agent mode is disabled and this host does not provide the selected read-only Ask agent.")); } } - this._clientDispatchedTurnIds.add(turnId); - - // If the chat model has fewer previous requests than the protocol has - // turns, a checkpoint was restored or a message was edited. Dispatch - // session/truncated so the server drops the stale tail. + // Commit the checkpoint's undo/redo branch before sending against the host's history. const chatModel = this._chatService.getSession(request.sessionResource); - const protocolState = this._getSessionState(session.toString(), chatURI); - if (chatModel && protocolState?.turns.length) { - // -2 since -1 will already be the current request - const previousRequestIndex = chatModel.getRequests().findIndex(i => i.id === request.requestId) - 1; - const previousRequest = previousRequestIndex >= 0 ? chatModel.getRequests()[previousRequestIndex] : undefined; - if (!previousRequest && protocolState.turns.length > 0) { + const chatSubscription = this._ensureChatSubscription(session.toString(), chatURI); + const protocolState = chatSubscription.verifiedValue; + if (chatModel && protocolState && !(protocolState instanceof Error) && protocolState.turns.length) { + const requests = chatModel.getRequests(); + const requestIndex = requests.findIndex(i => i.id === request.requestId); + const previousRequestIds = new Set(requests.slice(0, Math.max(0, requestIndex)).map(request => request.id)); + // Failed, unsent requests have no host turn and must not hide a truncation that still needs committing. + const seenAtIndex = protocolState.turns.findLastIndex(turn => previousRequestIds.has(turn.id)); + if (seenAtIndex < protocolState.turns.length - 1) { const truncateAction: ChatTruncatedAction = { type: ActionType.ChatTruncated, + ...(seenAtIndex >= 0 ? { turnId: protocolState.turns[seenAtIndex].id } : {}), }; - this._dispatchAction(session, truncateAction, turnChannel); - } else { - const seenAtIndex = protocolState.turns.findIndex(t => t.id === previousRequest!.id); - if (seenAtIndex !== -1 && seenAtIndex < protocolState.turns.length - 1) { - const truncateAction: ChatTruncatedAction = { - type: ActionType.ChatTruncated, - turnId: previousRequest!.id, - }; - this._dispatchAction(session, truncateAction, turnChannel); + this._steeringMessageHandoffs.get(turnChannel)?.clear(); + const store = new DisposableStore(); + const source = store.add(new CancellationTokenSource(cancellationToken)); + store.add(this._lifetime.token.onCancellationRequested(() => source.cancel())); + try { + // Optimistic state is not a barrier: the host may still be rewriting persisted history. + const acknowledgement = await this._config.connection.dispatchConfirmed( + turnChannel, chatSubscription, truncateAction, source.token, + ); + if (acknowledgement.rejectionReason) { + throw new Error(localize('agentHost.truncationRejected', "Chat history could not be restored: {0}", acknowledgement.rejectionReason)); + } + } finally { + store.dispose(); + } + if (this._isInvocationAbandoned(cancellationToken)) { + return; } } } + this._clientDispatchedTurnIds.add(turnId); // Dispatch session/turnStarted — the server will call sendMessage on // the provider as a side effect. @@ -3967,6 +3992,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC sink: progress, cancellationToken, onResponseText, + onResponseReasoning, onOpenResponseResource: request.message.trimStart().startsWith('/') ? resource => { resourceOpens.push(openResponseResource(resource).catch(error => { @@ -4260,6 +4286,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC }); const responseParts$ = derived(reader => turn$.read(reader)?.responseParts ?? []); const usage$ = derived(reader => turn$.read(reader)?.usage); + const routerPickSettled$ = derived(reader => isModelRouterPickSettled(mergedState$.read(reader)?.turns ?? [], opts.turnId, modelRouterNameFromModelId(turn$.read(reader)?.message.model?.id))); store.add(autorun(reader => { const state = mergedState$.read(reader); if (state?.turns.some(turn => turn.id === opts.turnId)) { @@ -4420,8 +4447,10 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const turn = turn$.read(reader); const selectedModelId = turn?.message?.model?.id; const resolution = this._createTurnModelLookup(opts.sessionResource, selectedModelId, this._hideAutoExplainability.read(reader)) - .toAutoModeResolution?.(usage$.read(reader)); - if (!resolution || (!resolution.resolved && turn?.message.text.startsWith('/')) || equals(lastAutoModeResolution, resolution)) { + .toAutoModeResolution?.(usage$.read(reader), lastAutoModeResolution !== undefined && !lastAutoModeResolution.resolved); + // An unresolved row is skipped for a slash command, and for a model router that already picked for this chat and is not picking again. + const skipUnresolved = !resolution?.resolved && (turn?.message.text.startsWith('/') || routerPickSettled$.read(reader)); + if (!resolution || skipUnresolved || equals(lastAutoModeResolution, resolution)) { return; } lastAutoModeResolution = resolution; @@ -4866,7 +4895,8 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC let lastDuration = initial?.reasoningDurationMs; store.add(autorun(reader => { const part = part$.read(reader); - const progress = reasoningPartToThinking(part, part.content.substring(lastEmitted)); + const delta = part.content.substring(lastEmitted); + const progress = reasoningPartToThinking(part, delta); if (!part.content || (part.content.length <= lastEmitted && progress.reasoningStartedAt === lastStartedAt && progress.reasoningDurationMs === lastDuration)) { return; @@ -4874,6 +4904,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC lastEmitted = part.content.length; lastStartedAt = progress.reasoningStartedAt; lastDuration = progress.reasoningDurationMs; + opts.onResponseReasoning?.(delta); opts.sink([progress]); })); } @@ -5664,21 +5695,11 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC if (store.isDisposed || completedFromServer) { return; } - if (!result.answers) { - this._config.connection.dispatch(opts.chatURI, { - type: ActionType.ChatInputCompleted, - requestId: inputReq.id, - response: ChatInputResponseKind.Cancel, - }); - } else { - const answers = convertCarouselAnswers(result.answers, inputReq.questions); - this._config.connection.dispatch(opts.chatURI, { - type: ActionType.ChatInputCompleted, - requestId: inputReq.id, - response: ChatInputResponseKind.Accept, - answers, - }); - } + const completed: ChatInputCompletedAction = result.answers + ? { type: ActionType.ChatInputCompleted, requestId: inputReq.id, response: ChatInputResponseKind.Accept, answers: convertCarouselAnswers(result.answers, inputReq.questions) } + : { type: ActionType.ChatInputCompleted, requestId: inputReq.id, response: ChatInputResponseKind.Cancel }; + // The same completions follow cancellation, disposal, and answers submitted for the person. + this._config.connection.dispatch(opts.chatURI, carousel.submittedByUser ? withHumanChatInputResponse(completed) : completed); }); if (opts.cancellationToken.isCancellationRequested) { @@ -5747,11 +5768,9 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const completion = result ? planReview.toInputCompletion(result) : { response: ChatInputResponseKind.Cancel }; - this._config.connection.dispatch(opts.chatURI, { - type: ActionType.ChatInputCompleted, - requestId: inputReq.id, - ...completion, - }); + const completed: ChatInputCompletedAction = { type: ActionType.ChatInputCompleted, requestId: inputReq.id, ...completion }; + // A dismissal and a voice answer resolve the same promise without the person using the review. + this._config.connection.dispatch(opts.chatURI, result && review.submittedByUser ? withHumanChatInputResponse(completed) : completed); }); if (opts.cancellationToken.isCancellationRequested) { @@ -5925,18 +5944,20 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const url = inputReq.url; let completionDispatched = false; let completedFromServer = false; - const settle = (response: ChatInputResponseKind): ElicitationState => { + // `byUser` marks the person's own choice of a button; any other settlement stays unattributed. + const settle = (response: ChatInputResponseKind, byUser = false): ElicitationState => { if (completionDispatched || completedFromServer) { return part.state.get(); } completionDispatched = true; part.state.set(response === ChatInputResponseKind.Accept ? ElicitationState.Accepted : ElicitationState.Rejected, undefined); - this._config.connection.dispatch(opts.chatURI, { + const completed: ChatInputCompletedAction = { type: ActionType.ChatInputCompleted, requestId: inputReq.id, response, ...(response === ChatInputResponseKind.Accept && !url ? { answers: {} } : {}), - }); + }; + this._config.connection.dispatch(opts.chatURI, byUser ? withHumanChatInputResponse(completed) : completed); return part.state.get(); }; @@ -5953,11 +5974,12 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC return part.state.get(); } if (!url) { - return settle(ChatInputResponseKind.Accept); + return settle(ChatInputResponseKind.Accept, true); } try { + // A URL that did not open is declined for the person, who chose to open it. const opened = await this._openerService.open(url, { allowCommands: false }); - return settle(opened ? ChatInputResponseKind.Accept : ChatInputResponseKind.Decline); + return opened ? settle(ChatInputResponseKind.Accept, true) : settle(ChatInputResponseKind.Decline); } catch { return settle(ChatInputResponseKind.Decline); } @@ -5966,7 +5988,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC if (completionDispatched || completedFromServer || store.isDisposed) { return part.state.get(); } - return settle(ChatInputResponseKind.Decline); + return settle(ChatInputResponseKind.Decline, true); }, ); @@ -7840,11 +7862,13 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // Model ids are provider-scoped, so another provider's model of the same name keeps its own id. const isCopilotFusionTier = (rawModelId: string | undefined) => this._config.provider === COPILOT_CLI_AGENT_PROVIDER_ID && isCopilotHydraFusionModelId(rawModelId); const fusionModelName = (rawModelId: string) => localize({ key: 'agentHost.fusionTierResponseModelFallback', comment: ['{0} is an effort level of Copilot Fusion, e.g. Max'] }, "Copilot Fusion {0}", getFusionAutoModeTierLabel(rawModelId)); + // Whether this chat's Auto is presented as Copilot Fusion, as its host advertised. + const isAutoFusion = () => !!lookupRawModel(AUTO_RAW_MODEL_ID)?.model.autoModelFusion; // On-device attribution: what actually ran, from the turn's usage, named from host status. const localTurn = (usage: UsageInfo | undefined) => this._localModels.getTurnPresentation(usage, fallbackRawModelId, rawModelId => { const resolved = lookupRawModel(rawModelId); return resolved && displayName(resolved); - }, hideAutoExplainability); + }, hideAutoExplainability, isAutoFusion()); return { toLanguageModelId: (rawModelId) => this._toLanguageModelId(sessionResource, resolveRaw(rawModelId)), isFusionModel: rawModelId => this._config.provider === COPILOT_CLI_AGENT_PROVIDER_ID && isCopilotHydraFusionModelId(rawModelId), @@ -7891,24 +7915,31 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const modelName = knownModel ? displayName(knownModel) : rawBilledId && isCopilotFusionTier(rawBilledId) ? fusionModelName(rawBilledId) : rawBilledId; return modelId && modelName ? { modelId, modelName, ...(runtimeModelConfiguration ? { runtimeModelConfiguration } : {}) } : undefined; }, - toAutoModeResolution: usage => { + toAutoModeResolution: (usage, settlesPendingRow) => { const routed = readUsageInfoMeta(usage).modelRouted; if (routed) { + // A router that picks once per chat has nothing new to report on a later turn, but a row already showing "picking a model" still has to settle. + if (routed.kept && routed.firstTurnOnly && !settlesPendingRow) { + return undefined; + } const routedModel = lookupRawModel(routed.chosenModel); const previousModel = routed.switchedFrom ? lookupRawModel(routed.switchedFrom) : undefined; return { kind: 'autoModeResolution', resolved: { id: routed.chosenModel, name: routedModel ? displayName(routedModel) : routed.chosenModel }, - router: routed.router, + router: routed.routerLabel ?? routed.router, + ...(routed.playbook ? { playbook: routed.playbook } : {}), preference: routed.preference, effort: routed.effort, + ...(routed.contextTokens ? { contextSize: routed.contextTokens } : {}), switchedFrom: routed.switchedFrom && (previousModel ? displayName(previousModel) : routed.switchedFrom), defaulted: routed.defaulted, kept: routed.kept, }; } if (isModelRouterModelId(fallbackRawModelId)) { - return { kind: 'autoModeResolution', router: modelRouterNameFromModelId(fallbackRawModelId) }; + // The router's picker row carries its display name. + return { kind: 'autoModeResolution', router: lookupRawModel(fallbackRawModelId)?.model.name ?? modelRouterNameFromModelId(fallbackRawModelId) }; } const resolution = readUsageInfoMeta(usage).autoModeResolved; const isAutoTurn = fallbackRawModelId === AUTO_RAW_MODEL_ID || !!resolution; @@ -7920,14 +7951,16 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // Router has not answered yet; Fusion's HydraFusion tiers never do. return lookupModel(fallbackRawModelId)?.model.autoModelFusion ? undefined : { kind: 'autoModeResolution' }; } + const fusion = isAutoFusion() ? { fusion: true } : {}; const localRouted = localTurn(usage)?.routed; if (localRouted) { - return { kind: 'autoModeResolution', resolved: localRouted }; + return { kind: 'autoModeResolution', resolved: localRouted, ...fusion }; } const resolved = lookupRawModel(resolution.chosenModel); // Named the same way as the footer, so the two agree. const name = resolved && displayName(resolved); - return usageInfoToAutoModeResolution(usage, name); + const resolutionPart = usageInfoToAutoModeResolution(usage, name); + return resolutionPart && { ...resolutionPart, ...fusion }; }, }; } @@ -8415,6 +8448,9 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const displayKind = detail.type.replaceAll('_', '-'); return this._toSimpleAttachment(v.name, v.value instanceof URI ? v.value.toString() : typeof v.value === 'string' ? v.value : undefined, v._meta, displayKind, referenceRange); } + if (typeof v.value === 'string') { + return this._toSimpleAttachment(v.name, v.value, v._meta, undefined, referenceRange); + } if (v.value instanceof URI && (v.value.scheme === Schemas.http || v.value.scheme === Schemas.https)) { return this._toSimpleAttachment(v.name, v.value.toString(), v._meta, undefined, referenceRange); } @@ -8424,7 +8460,18 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC return this._toSimpleAttachment(v.name, undefined, v._meta, 'command', referenceRange); } if (agentHostCompletionKind === AgentHostCompletionReferenceKind.Skill) { - return this._toSimpleAttachment(v.name, undefined, v._meta, 'skill', referenceRange); + if (isUUID(v.id)) { + this._logService.warn('[AgentHost] Skipping a legacy skill reference without a resource URI'); + return undefined; + } + return { + type: MessageAttachmentKind.Resource, + uri: this._config.connection.resourceUris.toAgentHost(URI.parse(v.id, true)).toString(), + label: v.name, + displayKind: 'skill', + ...(referenceRange ? { range: referenceRange } : {}), + ...(v._meta ? { _meta: v._meta } : {}), + }; } if (isChatReferenceVariableEntry(v)) { return this._toChatReferenceAttachment(v, referenceRange); 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 d00994477267..cc0b47c10d6d 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts @@ -73,6 +73,7 @@ import { openChatFileChanges } from '../../editorChatResponseFileChangesService. import { confirmUndoAllEdits } from '../../chatEditing/chatEditing.js'; import { ChatInputPills, StandardChatInputPillSources } from '../../chatInputPills.js'; import { ChatArtifactPillSource, mergeChatArtifactSections } from '../../chatArtifactPillSource.js'; +import { ChatDockedViewsControl } from '../../chatDockedViews/chatDockedViewsControl.js'; import { SessionBackgroundShellsControl } from '../../sessionBackgroundShellsControl.js'; import { createSessionPullRequestPillData, type IChatPullRequestPillEntry } from '../../sessionPullRequestPill.js'; import { SessionCustomizations } from '../../sessionCustomizations.js'; @@ -1058,6 +1059,7 @@ export class AgentHostSessionInputPills extends Disposable { const chat = chatResource.read(reader); return session && chat ? JSON.stringify([getLocalAgentHostSessionProvider(session), session.toString(), chat.toString()]) : undefined; }))); + const dockedViews = this._register(instantiationService.createInstance(ChatDockedViewsControl, this._widget.inputPart.persistentContentContainerElement, this._widget.domNode, sessionResource)); const inputPills = this._register(instantiationService.createInstance(ChatInputPills, this._widget.inputPart.persistentContentContainerElement, { debugName: 'AgentHostSessionInputPills.content', compact, @@ -1068,9 +1070,10 @@ export class AgentHostSessionInputPills extends Disposable { return sources.sources.filter(source => source.kind === SessionChatPillKind.Artifacts); } const offeredSources = canvases.offered.read(reader) ? sources.sources : sources.sources.filter(source => source.kind !== SessionChatPillKind.Canvases); - return changesPillHidden.read(reader) + const visibleSources = changesPillHidden.read(reader) ? offeredSources.filter(source => source.kind !== SessionChatPillKind.Changes) : offeredSources; + return [...dockedViews.pillSources.read(reader), ...visibleSources]; }), offeredKinds: SESSION_CHAT_PILL_KINDS, focusFallback: () => this._widget.focusInput(), @@ -1079,14 +1082,16 @@ export class AgentHostSessionInputPills extends Disposable { this._register(this._widget.inputPart.registerChatPetHorizontalPlatformProvider({ onDidChange: inputPills.onDidChange, - getElements: () => inputPills.getPillElements(), + getElements: () => inputPills.getPillItemElements(), })); - const updateVisibility = (visible: boolean) => { + const pillsVisible = observableFromEvent(this, inputPills.onDidChangeVisibility, () => inputPills.visible); + this._register(autorun(reader => { + const visible = pillsVisible.read(reader); + // Docked views float with the pills, so the transcript reserves room for both. + const height = (visible ? CHAT_INPUT_PILLS_ROW_HEIGHT : 0) + dockedViews.height.read(reader); this._widget.inputPart.persistentContentContainerElement.classList.toggle(chatPersistentContentVisibleClass, visible); - this._widget.setPersistentContentHeight(visible ? CHAT_INPUT_PILLS_ROW_HEIGHT : undefined); - }; - this._register(inputPills.onDidChangeVisibility(updateVisibility)); - updateVisibility(inputPills.visible); + this._widget.setPersistentContentHeight(height > 0 ? height : undefined); + })); } /** Overridable so tests can drive customization resolution deterministically; `undefined` uses the idle scheduler. */ diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts index 1cd0d8fed3d1..eb5095dbf798 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts @@ -64,6 +64,8 @@ interface IAgentHostCheckpoint { * regardless of how many tool calls it ran. The `stopId` parameters on * {@link restoreSnapshot}, {@link getSnapshotUri}, and {@link getSnapshotContents} * are accepted for interface compatibility but ignored. + * The forward branch remains available for redo until the next prompt commits + * the truncation of the host's conversation history. * * Hydrated by the session handler as turns and tool calls arrive, with * optional turn changesets resolved when checkpoint content is needed. diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostToolApprovals.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostToolApprovals.ts new file mode 100644 index 000000000000..e1682eff9a7a --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostToolApprovals.ts @@ -0,0 +1,164 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { raceTimeout } from '../../../../../../base/common/async.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { localize } from '../../../../../../nls.js'; +import { mcpServerRule, mcpToolRule } from '../../../../../../platform/agentHost/common/permissionRules.js'; +import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; +import { ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; +import { isAgentHostSessionResource, isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; +import { InternalFetchWebPageToolId } from '../../../common/tools/builtinTools/tools.js'; +import { ILanguageModelToolsConfirmationService, IToolPreApprovalStore } from '../../../common/tools/languageModelToolsConfirmationService.js'; +import { ILanguageModelToolsService, IToolData, ToolDataSource } from '../../../common/tools/languageModelToolsService.js'; +import { TerminalToolId } from '../../../common/tools/terminalToolIds.js'; +import { MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID } from '../../actions/chatActions.js'; +import { getMcpServerDisplayLabel, IAgentHostCustomizationService } from './agentHostCustomizationService.js'; + +const LIST_TOOLS_TIMEOUT_MS = 5000; + +CommandsRegistry.registerCommand(MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID, (accessor: ServicesAccessor, sessionResource: URI) => manageAgentHostToolApprovals( + sessionResource, + accessor.get(IAgentHostCustomizationService), + accessor.get(ILanguageModelToolsConfirmationService), + accessor.get(ILanguageModelToolsService), + !accessor.get(IWorkbenchEnvironmentService).remoteAuthority, +)); + +/** Opens host-wide tool approvals for an agent-host session, returning false when its root config is unavailable. */ +export function manageAgentHostToolApprovals( + sessionResource: URI, + customizationService: IAgentHostCustomizationService, + confirmationService: ILanguageModelToolsConfirmationService, + toolsService: ILanguageModelToolsService, + mirrorsLocalSettings: boolean, +): boolean { + if (!isAgentHostSessionResource(sessionResource)) { + return false; + } + const initialPermissions = customizationService.getHostPermissions(sessionResource); + if (!initialPermissions) { + return false; + } + const approvalOverrides = new Map(); + const rules = [...initialPermissions.allow, ...initialPermissions.deny, ...(initialPermissions.ask ?? [])]; + const servers = customizationService.getMcpServers(sessionResource).filter(server => { + const rule = mcpServerRule(server.name); + return rule !== undefined && (server.enabled || rules.some(value => value === rule || value.startsWith(`Mcp(${server.name}/`))); + }); + const toolsById = new Map(); + const toolNames = new Map(); + const addMcpTool = (target: Map, server: typeof servers[number], name: string, displayName: string) => { + if (mcpToolRule(server.name, name) === undefined) { + return; + } + const id = `agentHostMcp:${server.name}/${name}`; + const label = getMcpServerDisplayLabel(server); + toolNames.set(id, { server: server.name, tool: name }); + target.set(id, { + id, + displayName, + modelDescription: '', + canRequestPreApproval: true, + source: { type: 'mcp', label, serverLabel: label, instructions: undefined, collectionId: server.name, definitionId: server.name }, + }); + }; + for (const server of servers) { + const prefix = `Mcp(${server.name}/`; + for (const rule of initialPermissions.allow) { + if (rule.startsWith(prefix) && rule.endsWith(')')) { + const name = rule.slice(prefix.length, -1); + addMcpTool(toolsById, server, name, name); + } + } + } + const tools = [...toolsById.values()]; + const discoveredTools = observableValue('agentHostToolApprovals.discoveredTools', []); + const isDiscovering = observableValue('agentHostToolApprovals.isDiscovering', servers.some(server => !!server.listTools)); + + // URL and terminal approval settings are mirrored only into the local agent host. + if (mirrorsLocalSettings && isLocalAgentHostTarget(sessionResource.scheme)) { + for (const toolId of [InternalFetchWebPageToolId, TerminalToolId.RunInTerminal]) { + const tool = toolsService.getTool(toolId); + if (tool) { + tools.push(tool); + } else if (toolId === InternalFetchWebPageToolId) { + tools.push({ + id: InternalFetchWebPageToolId, + displayName: localize('agentHost.fetchWebPage', "Fetch Web Page"), + modelDescription: '', + source: ToolDataSource.Internal, + }); + } + } + } + + const getHostPermissions = () => { + const permissions = customizationService.getHostPermissions(sessionResource); + if (permissions) { + for (const [rule, approved] of approvalOverrides) { + if (permissions.allow.includes(rule) === approved) { + approvalOverrides.delete(rule); + } + } + } + return permissions; + }; + const setRuleApproved = (rule: string | undefined, approved: boolean) => { + if (rule === undefined) { + return; + } + const permissions = getHostPermissions(); + if (!permissions) { + return; + } + approvalOverrides.set(rule, approved); + const allow = new Set(permissions.allow); + for (const [overriddenRule, overriddenApproved] of approvalOverrides) { + if (overriddenApproved) { + allow.add(overriddenRule); + } else { + allow.delete(overriddenRule); + } + } + customizationService.setHostPermissions(sessionResource, { ...permissions, allow: [...allow] }); + }; + const isRuleApproved = (rule: string | undefined) => { + const permissions = getHostPermissions(); + return rule !== undefined && (approvalOverrides.get(rule) ?? permissions?.allow.includes(rule) ?? false); + }; + const getToolRule = (tool: IToolData) => { + const name = toolNames.get(tool.id); + return name ? mcpToolRule(name.server, name.tool) : undefined; + }; + const preApprovalStore: IToolPreApprovalStore = { + discoveredTools, + isDiscovering, + servers: servers.map(server => ({ id: server.name, label: getMcpServerDisplayLabel(server) })), + placeholder: localize('agentHost.configureToolApprovals', "Configure tool approvals for the agent host"), + isServerApproved: serverId => isRuleApproved(mcpServerRule(serverId)), + setServerApproved: (serverId, approved) => setRuleApproved(mcpServerRule(serverId), approved), + isToolApproved: tool => isRuleApproved(getToolRule(tool)), + setToolApproved: (tool, approved) => setRuleApproved(getToolRule(tool), approved), + }; + confirmationService.manageConfirmationPreferences(tools, { preApprovalStore }); + void (async () => { + const discoveredToolsById = new Map(); + await Promise.allSettled(servers.map(async server => { + if (!server.listTools) { + return; + } + const listedTools = await raceTimeout(server.listTools(), LIST_TOOLS_TIMEOUT_MS); + for (const tool of listedTools ?? []) { + addMcpTool(discoveredToolsById, server, tool.name, tool.title ?? tool.annotations?.title ?? tool.name); + } + discoveredTools.set([...discoveredToolsById.values()], undefined); + })); + isDiscovering.set(false, undefined); + })(); + return true; +} diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.ts index 3ac591e52b80..b77da0cff68c 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.ts @@ -85,6 +85,7 @@ import { IAgentHostNewSessionFolderService, computeDesiredWorkingDirectories, co import { IAgentCustomizationScope, IAgentHostActiveClientService } from './agentHostActiveClientService.js'; import { type IAgentHostImportConversation, IAgentHostImportConversationStore } from './agentHostImportConversationStore.js'; import { getLocalAgentHostSessionProvider } from './agentHostSessionUri.js'; +import { isAgentHostTargetFolderTrusted } from './agentHostSessionConfigSubscription.js'; export const IAgentHostUntitledProvisionalSessionService = createDecorator('agentHostUntitledProvisionalSessionService'); @@ -122,7 +123,7 @@ export interface IAgentHostUntitledProvisionalSessionService { */ getInitialSessionConfig(): Record | undefined; - /** Resolves a new editor chat's initial picker configuration before its widget is shown. */ + /** Resolves a trusted new editor chat's initial picker configuration before its widget is shown. */ prepareSessionConfig(sessionResource: URI, token?: CancellationToken): Promise; /** Initial presentation only; hydrated host state and explicit draft edits take precedence. */ @@ -415,7 +416,7 @@ export class AgentHostUntitledProvisionalSessionService extends Disposable imple bindRootState(); this._register(this._agentHostService.onAgentHostStart(bindRootState)); this._register(this._agentHostService.onAgentHostStart(() => this._retryPendingBackendDisposals())); - this._register(this._agentHostService.onAgentHostStart(() => { + this._register(Event.any(this._agentHostService.onAgentHostStart, this._workspaceTrustManagementService.onDidChangeTrust, this._workspaceTrustManagementService.onDidChangeTrustedFolders)(() => { this._preparedConfigGeneration++; this._preparedConfigs.clear(); })); @@ -547,9 +548,17 @@ export class AgentHostUntitledProvisionalSessionService extends Disposable imple const workingDirectory = this._newSessionFolderService.resolveNewSessionPrimary(sessionResource); const config = this._getInitialConfig(); this._resolvedConfigConnections.set(sessionResource, resolution); - const result = await raceTimeout(raceCancellation(resolution.connection.resolveSessionConfig({ - provider, workingDirectory, config, - }), token), SessionConfigPreparationTimeout, () => { + const resolveConfig = async () => { + if (!await isAgentHostTargetFolderTrusted(workingDirectory, this._workspaceTrustManagementService) + || token.isCancellationRequested || this._store.isDisposed || generation !== this._preparedConfigGeneration || this._resolvedConfigRequestSeq.get(sessionResource) !== seq + || !isEqual(workingDirectory, this._newSessionFolderService.resolveNewSessionPrimary(sessionResource)) + || !this._isCurrentConfigConnection(sessionResource, resolution) + || isLocalAgentHostProviderDisabledByPolicy(provider, this._configurationService)) { + return undefined; + } + return resolution.connection.resolveSessionConfig({ provider, workingDirectory, config }); + }; + const result = await raceTimeout(raceCancellation(resolveConfig(), token), SessionConfigPreparationTimeout, () => { this._logService.warn('[AgentHostProvisional] Initial session configuration timed out; continuing without prepared pickers'); }); if (!result || token.isCancellationRequested || generation !== this._preparedConfigGeneration || this._resolvedConfigRequestSeq.get(sessionResource) !== seq @@ -769,7 +778,7 @@ export class AgentHostUntitledProvisionalSessionService extends Disposable imple const metadata = this.getInitialSessionMetadata(sessionResource); // Prewarming is silent; first Send owns interactive trust, so never create in an untrusted target. - if (!await this._isTargetFolderTrusted(workingDirectory)) { + if (!await isAgentHostTargetFolderTrusted(workingDirectory, this._workspaceTrustManagementService)) { await this._retireGeneration(sessionResource, entry); return undefined; } @@ -871,20 +880,6 @@ export class AgentHostUntitledProvisionalSessionService extends Disposable imple } } - /** - * Whether the folder the provisional agent would run in is trusted. When a - * working directory is known (it may be a standalone folder outside the - * open workspace, e.g. a per-session folder), gate on that folder's trust; - * otherwise fall back to whole-workspace trust. - */ - private async _isTargetFolderTrusted(workingDirectory: URI | undefined): Promise { - if (workingDirectory) { - const { trusted } = await this._workspaceTrustManagementService.getUriTrustInfo(workingDirectory); - return trusted; - } - return this._workspaceTrustManagementService.isWorkspaceTrusted(); - } - tryRebind( oldSessionResource: URI, newSessionResource: URI, diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/copilotCliBuiltinToolSet.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/copilotCliBuiltinToolSet.ts index c601e267b986..6cc1faf83df0 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/copilotCliBuiltinToolSet.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/copilotCliBuiltinToolSet.ts @@ -37,6 +37,7 @@ function getCopilotCliTools(): readonly { readonly name: string; readonly descri { name: 'glob', description: localize('copilotCliTool.glob', "Find files matching patterns") }, { name: 'grep (or rg)', description: localize('copilotCliTool.grep', "Search for text in files") }, { name: 'skill', description: localize('copilotCliTool.skill', "Invoke custom skills") }, + { name: 'read_resource', description: localize('copilotCliTool.readResource', "Read MCP resources") }, { name: 'web_fetch', description: localize('copilotCliTool.webFetch', "Fetch and parse web content") }, ]; } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/localModelReadyNotification.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/localModelReadyNotification.ts index 169989c784bf..e393d6959041 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/localModelReadyNotification.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/localModelReadyNotification.ts @@ -95,11 +95,13 @@ export interface ILocalModelReadyOfferInput { readonly family: ILocalModelFamilyV1; readonly flavor: LocalModelReadyOfferFlavor; readonly currentModel: ILanguageModelChatMetadataAndIdentifier | undefined; + /** Whether the local Copilot host's Auto is presented as Copilot Fusion. */ + readonly autoModelFusion?: boolean; } /** The ready offer's description and actions for one chat input; the primary action is always last. */ export function resolveLocalModelReadyOfferBody(input: ILocalModelReadyOfferInput): IChatInputNotificationBody { - const { status, family } = input; + const { status, family, autoModelFusion } = input; const name = family.displayName; const readyOfferId = family.readyOfferId ?? ''; const currentModelKind = getLocalModelCurrentModelKind(input.currentModel, status); @@ -141,7 +143,9 @@ export function resolveLocalModelReadyOfferBody(input: ILocalModelReadyOfferInpu const tooSlow = family.autoCapable && status.active?.familyId === family.familyId && status.active.autoEligible === false; return { description: tooSlow - ? localize('localModel.ready.tooSlow', "It's too slow on this device for Auto, but you can select it directly.") + ? autoModelFusion + ? localize('localModel.ready.tooSlowFusion', "It's too slow on this device for Copilot Fusion, but you can select it directly.") + : localize('localModel.ready.tooSlow', "It's too slow on this device for Auto, but you can select it directly.") : localize('localModel.ready.directOnly', "Select it directly to run on your device."), actions: [notNow, switchToLocal(true)], }; @@ -149,10 +153,14 @@ export function resolveLocalModelReadyOfferBody(input: ILocalModelReadyOfferInpu if (currentModelKind === 'auto') { return { - description: localize('localModel.ready.auto', "Auto can now run some requests on this device, with cloud fallback. New Auto chats will use it."), + description: autoModelFusion + ? localize('localModel.ready.autoFusion', "Copilot Fusion can now run some requests on this device, with cloud fallback. New Copilot Fusion chats will use it.") + : localize('localModel.ready.auto', "Auto can now run some requests on this device, with cloud fallback. New Auto chats will use it."), actions: [switchToLocal(false), notNow, { kind: ChatInputNotificationActionKind.Command, - label: localize('localModel.ready.newAutoChat', "New Auto Chat"), + label: autoModelFusion + ? localize('localModel.ready.newFusionChat', "New Copilot Fusion Chat") + : localize('localModel.ready.newAutoChat', "New Auto Chat"), commandId: LOCAL_MODEL_NEW_AUTO_CHAT_COMMAND_ID, commandArgs: [readyOfferId, currentModelKind], primary: true, @@ -163,14 +171,18 @@ export function resolveLocalModelReadyOfferBody(input: ILocalModelReadyOfferInpu const useAuto: IChatInputNotificationAction = { kind: ChatInputNotificationActionKind.SwitchToModel, - label: localize('localModel.ready.useAuto', "Use Auto"), + label: autoModelFusion + ? localize('localModel.ready.useFusion', "Use Copilot Fusion") + : localize('localModel.ready.useAuto', "Use Auto"), matchesModel: matchesLocalCopilotAuto, requireUniqueModel: true, primary: false, telemetryActionId: 'useAuto', }; return { - description: localize('localModel.ready.server', "Run this chat on your device, or let Auto choose between local and cloud."), + description: autoModelFusion + ? localize('localModel.ready.serverFusion', "Run this chat on your device, or let Copilot Fusion choose between local and cloud.") + : localize('localModel.ready.server', "Run this chat on your device, or let Auto choose between local and cloud."), actions: [useAuto, notNow, switchToLocal(true)], }; } @@ -292,15 +304,16 @@ export class LocalModelReadyNotificationContribution extends Disposable { private _createNotification(readyOfferId: string, family: ILocalModelFamilyV1, flavor: LocalModelReadyOfferFlavor, inputUri: URI | undefined): IChatInputNotification { const familyId = family.familyId; - const resolve = (currentModel: ILanguageModelChatMetadataAndIdentifier | undefined): IChatInputNotificationBody => { + const resolve = (currentModel: ILanguageModelChatMetadataAndIdentifier | undefined, models: readonly ILanguageModelChatMetadataAndIdentifier[]): IChatInputNotificationBody => { const status = this._status.get(); const current = status?.families.find(candidate => candidate.familyId === familyId); if (!status || !current) { return { description: undefined, actions: [] }; } - return resolveLocalModelReadyOfferBody({ status, family: current, flavor: getLocalModelReadyOfferFlavor(status, current, true) ?? flavor, currentModel }); + const autoModelFusion = models.some(model => matchesLocalCopilotAuto(model) && !!model.metadata.autoModelFusion); + return resolveLocalModelReadyOfferBody({ status, family: current, flavor: getLocalModelReadyOfferFlavor(status, current, true) ?? flavor, currentModel, autoModelFusion }); }; - const initial = resolve(undefined); + const initial = resolve(undefined, []); return { id: LOCAL_MODEL_READY_OFFER_NOTIFICATION_PREFIX + readyOfferId, telemetryId: 'localModel.ready', @@ -316,7 +329,7 @@ export class LocalModelReadyNotificationContribution extends Disposable { const current = this._status.get()?.families.find(candidate => candidate.familyId === familyId); return !context.modelState.currentModel || !matchesLocalModelRow(current?.install?.modelId)(context.modelState.currentModel); }, - resolveBody: context => resolve(context.modelState.currentModel), + resolveBody: context => resolve(context.modelState.currentModel, context.modelState.models), onDidShow: context => this._recordShown(readyOfferId, context.modelState.currentModel), dismissible: true, onDismiss: () => this._acknowledge(readyOfferId), diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostChatInputPicker.css b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostChatInputPicker.css index e3c90c5ef339..b4af4928ecc9 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostChatInputPicker.css +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostChatInputPicker.css @@ -38,7 +38,7 @@ box-sizing: border-box; height: var(--chat-input-control-height); padding: 0 var(--vscode-spacing-size60); - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); color: var(--vscode-icon-foreground); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostModePicker.css b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostModePicker.css index 046c2a728262..7c68c131c716 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostModePicker.css +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/agentHostModePicker.css @@ -131,7 +131,7 @@ display: flex; height: var(--chat-input-control-height); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); overflow: visible; background: transparent; color: var(--vscode-icon-foreground); @@ -150,10 +150,6 @@ background-color: var(--vscode-toolbar-hoverBackground); } -.monaco-workbench .monaco-action-bar:not(.vertical) .action-item .action-label.agent-host-mode-permissions-trigger:hover:not(.disabled) { - outline: none; -} - .agent-host-permissions-button .agent-host-mode-permission-summary { margin-left: 0; } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts index bc818ae9f4cc..418cf1a918a8 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.ts @@ -26,7 +26,9 @@ import { getToolKind as getProtocolToolKind } from '../../../../../../platform/a import { copilotCliToolInputContract, readToolCallMeta, readToolCallPresentation, type IAgentToolOutputChunk } from '../../../../../../platform/agentHost/common/meta/agentToolCallMeta.js'; import { readImageGenerationToolMetadata } from '../../../../../../platform/agentHost/common/meta/agentImageGenerationMeta.js'; import { readAttachmentDetail } from '../../../../../../platform/agentHost/common/meta/attachmentMeta.js'; +import { getCompletionDescription, readCompletionAttachmentMeta, restoreLegacySkillAttachment } from '../../../../../../platform/agentHost/common/meta/agentCompletionAttachmentMeta.js'; import { COPILOT_HYDRA_FUSION_MODEL_ID } from '../../../../../../platform/agentHost/common/copilotCliConfig.js'; +import { modelRouterNameFromModelId } from '../../../../../../platform/agentHost/common/modelRouter.js'; import { getChatErrorDetailsFromMeta, IChatErrorContext } from '../../../common/chatErrorMessages.js'; import { AICustomizationManagementCommands, AICustomizationManagementSection } from '../../../common/aiCustomizationWorkspaceService.js'; import { AGENT_HOST_SCHEME, createAgentHostResourceUriMapper, type IAgentHostResourceUriMapper, toAgentHostContentUri, toAgentHostUri } from '../../../../../../platform/agentHost/common/agentHostUri.js'; @@ -49,6 +51,7 @@ import { normalizeFileEdit } from '../../../../../../platform/agentHost/common/f import { AgentSession } from '../../../../../../platform/agentHost/common/agentService.js'; import product from '../../../../../../platform/product/common/product.js'; import { ConfigureAutomationToolReferenceName } from '../../../common/automations/automationService.js'; +import { OPEN_SESSION_COMPARISON_COMMAND_ID } from '../../../../../common/sessionComparisonConstants.js'; import { formatCopilotCreditsLabel, getSubagentIsActive, ElicitationState, type ChatExternalEditKind, type ChatMcpAppData, type IChatAgentFeedbackReviewConfirmationData, type IChatAutomationConfiguredData, type IChatAutoModeResolutionPart, type IChatExternalEdit, type IChatGeneratedImageData, type IChatMcpAuthenticationRequiredServer, type IChatModifiedFilesConfirmationData, type IChatProgress, type IChatQuestion, type IChatQuestionAnswerValue, type IChatQuestionAnswers, type IChatResponseErrorDetails, type IChatSearchToolInvocationData, type IChatSessionTargetData, type IChatSubagentToolInvocationData, type IChatTerminalToolInvocationData, type IChatThinkingPart, type IChatToolInputInvocationData, type IChatToolInvocationSerialized, type IChatUsage, type IChatUsagePromptTokenDetail, ToolConfirmKind, AgentFeedbackReviewCommandId } from '../../../common/chatService/chatService.js'; import { isTerminalCommandPrompt, type IChatSessionHistoryItem } from '../../../common/chatSessionsService.js'; import { type IQuotaSnapshot, type IRateLimitSnapshot } from '../../../../../services/chat/common/chatEntitlementService.js'; @@ -57,7 +60,8 @@ import { ChatPlanReviewData } from '../../../common/model/chatProgressTypes/chat import { ChatQuestionCarouselData } from '../../../common/model/chatProgressTypes/chatQuestionCarouselData.js'; import { type ChatRequestSource, type IChatRequestVariableData, type IChatSessionCost } from '../../../common/model/chatModel.js'; import { ChatRequestOriginKind, type IChatRequestOrigin } from '../../../common/chatRequestOrigin.js'; -import { AgentHostCompletionReferenceKind, restoreChatTranscriptContextVariableEntry, restorePasteVariableEntryFromAttachment, toAgentHostCompletionVariableEntryFromMetadata, type IAgentFeedbackVariableEntry, type IChatRequestVariableEntry, type IElementVariableEntry } from '../../../common/attachments/chatVariableEntries.js'; +import { AgentHostCompletionReferenceKind, restoreChatTranscriptContextVariableEntry, restorePasteVariableEntryFromAttachment, toAgentHostCompletionVariableEntry, type IAgentFeedbackVariableEntry, type IChatRequestVariableEntry, type IElementVariableEntry } from '../../../common/attachments/chatVariableEntries.js'; +import { GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX } from '../../../common/attachments/chatInlineAttachments.js'; import { type IToolConfirmationMessages, type IToolData, type IPreparedToolInvocation, type IToolResult, type IToolResultInputOutputDetails, ToolDataSource, ToolInvocationPresentation } from '../../../common/tools/languageModelToolsService.js'; import { ChatToolInvocationSummary, getToolInvocationSummaryFromInput } from '../../../common/tools/toolInvocationSummary.js'; import { MCP } from '../../../../mcp/common/modelContextProtocol.js'; @@ -589,7 +593,7 @@ function getToolSummary(tc: ToolCallState, resourceUris: IAgentHostResourceUriMa if (tc.contributor || meta['vscode.toolInputContract'] !== copilotCliToolInputContract) { return { kind: 'unknown' }; } - return getToolInvocationSummaryFromInput(tc.toolName, getToolRawInput(tc), uri => resourceUris.fromAgentHost(uri)) ?? { kind: 'unknown' }; + return getToolInvocationSummaryFromInput(tc.toolName, getToolRawInput(tc), uri => resourceUris.fromAgentHost(uri), meta['vscode.viewedResourceType']) ?? { kind: 'unknown' }; } function buildMcpAppToolInputData(tc: ToolCallState, connectionAuthority: string, existingRawInput?: unknown): IChatToolInputInvocationData | undefined { @@ -837,8 +841,11 @@ export interface TurnModelLookup { toResponseDetails(rawModelId: string | undefined, usage: UsageInfo | undefined, responseModelId?: string): string | undefined; /** Whether a raw AHP model id names this provider's fusion routing model. */ isFusionModel?(rawModelId: string | undefined): boolean; - /** Returns the Auto model routing part carried by this usage report, if any. */ - toAutoModeResolution?(usage: UsageInfo | undefined): IChatAutoModeResolutionPart | undefined; + /** + * Returns the Auto model routing part carried by this usage report, if any. A report with nothing + * new to show returns none, unless `settlesPendingRow` says a row that is still routing is waiting on it. + */ + toAutoModeResolution?(usage: UsageInfo | undefined, settlesPendingRow?: boolean): IChatAutoModeResolutionPart | undefined; /** * Returns the identity and display name of the model a turn bills to, reading Auto's pick * when it routed and folding back to "Auto" while explainability is hidden. @@ -914,6 +921,34 @@ export function formatTurnResponseDetails( return [displayName, model.pricing].filter(Boolean).join(' · '); } +/** + * Whether a model router that picks once per chat has already picked for this chat. A later turn + * that selects it keeps that pick without being routed, so there is no routing to report. As on + * the host, a model picked by hand or another router selected since then means it routes afresh. + */ +export function isModelRouterPickSettled(turns: readonly Turn[], turnId: string, routerName: string | undefined): boolean { + if (!routerName) { + return false; + } + for (let i = turns.length - 1; i >= 0; i--) { + if (turns[i].id === turnId) { + continue; + } + const routed = readUsageInfoMeta(turns[i].usage).modelRouted; + if (routed) { + return routed.router === routerName && routed.firstTurnOnly === true; + } + // A turn since that pick that selected a model by hand, or another router. A restored turn + // that asked for a router and got no pick has the model it ran on as its selection, so the + // router it asked for is read from its usage, as the host does. + const requested = turns[i].message.model?.id; + if (requested && (modelRouterNameFromModelId(requested) ?? readUsageInfoMeta(turns[i].usage).modelRouterUnrouted) !== routerName) { + return false; + } + } + return false; +} + /** Converts an agent-host Auto routing result into the shared chat UI part. */ export function usageInfoToAutoModeResolution(usage: UsageInfo | undefined, resolvedModelName: string | undefined): IChatAutoModeResolutionPart | undefined { const resolution = readUsageInfoMeta(usage).autoModeResolved; @@ -980,10 +1015,7 @@ function getCopilotCredits(usage: UsageInfo | undefined): number | undefined { if (typeof totalNanoAiu === 'number' && totalNanoAiu >= 0) { return totalNanoAiu / 1_000_000_000; } - const cost = meta?.cost; - return typeof cost === 'number' && cost >= 0 - ? cost - : undefined; + return undefined; } /** @@ -1520,6 +1552,9 @@ function aggregateAgentFeedbackAttachments(attachments: readonly MessageAttachme } function messageAttachmentToVariableEntry(attachment: MessageAttachment, resourceUris: IAgentHostResourceUriMapper, messageText?: string): IChatRequestVariableEntry | undefined { + if (attachment.type === MessageAttachmentKind.Simple) { + attachment = restoreLegacySkillAttachment(attachment) ?? attachment; + } if (isAgentFeedbackAttachment(attachment)) { const metadata = getAgentFeedbackAttachmentMetadata(attachment); if (metadata) { @@ -1544,8 +1579,15 @@ function messageAttachmentToVariableEntry(attachment: MessageAttachment, resourc if (isSessionReferenceTrajectoryAttachment(attachment)) { return undefined; } - const uri = resourceUris.fromAgentHost(URI.parse(attachment.uri)); + const uri = resourceUris.fromAgentHost(URI.parse(attachment.uri, attachment.displayKind === 'skill')); const name = attachment.label; + if (attachment.displayKind === 'skill') { + const description = getCompletionDescription(attachment); + return { + ...toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, name, uri, attachment._meta), + ...(description !== undefined ? { modelDescription: description } : {}), + }; + } const id = uri.toString() + (attachment.selection ? `:${attachment.selection.range.start.line}-${attachment.selection.range.end.line}` : ''); @@ -1620,9 +1662,12 @@ function messageAttachmentToVariableEntry(attachment: MessageAttachment, resourc return restoreChatReferenceVariableEntryFromAttachment(attachment, messageText); } - const agentHostCompletionKind = getAgentHostCompletionKind(attachment); - if (agentHostCompletionKind !== undefined) { - return toAgentHostCompletionVariableEntryFromMetadata(agentHostCompletionKind, attachment.label, attachment._meta); + if (attachment.type === MessageAttachmentKind.Simple && attachment.displayKind === 'command') { + const metadata = readCompletionAttachmentMeta(attachment); + return toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Command, attachment.label, metadata?.command, attachment._meta); + } + if (attachment.type === MessageAttachmentKind.Simple && attachment.displayKind === 'skill') { + return toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, attachment.label, undefined, attachment._meta); } const modelRepresentation = attachment.type === MessageAttachmentKind.Simple ? attachment.modelRepresentation : undefined; @@ -1670,6 +1715,10 @@ function messageAttachmentToVariableEntry(attachment: MessageAttachment, resourc if (pasteEntry) { return pasteEntry; } + const gitHubContextEntry = restoreGitHubContextVariableEntry(attachment, modelRepresentation); + if (gitHubContextEntry) { + return gitHubContextEntry; + } const detail = readAttachmentDetail(attachment); const reference = detail?.url && URL.canParse(detail.url) && ['http:', 'https:'].includes(new URL(detail.url).protocol) ? URI.parse(detail.url) : undefined; return { @@ -1682,6 +1731,26 @@ function messageAttachmentToVariableEntry(attachment: MessageAttachment, resourc }; } +/** + * Restores the attachment of a GitHub issue or pull request, which says only its + * link. History keeps what the attachment says but not its id and icon, by which + * the link in the request is shown as the pill of the attachment. + */ +function restoreGitHubContextVariableEntry(attachment: MessageAttachment, modelRepresentation: string | undefined): IChatRequestVariableEntry | undefined { + const groups = modelRepresentation === undefined ? undefined : /^GitHub context: (?https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/(?issues|pull)\/\d+)$/.exec(modelRepresentation)?.groups; + if (!groups) { + return undefined; + } + return { + kind: 'generic', + id: `${GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX}${groups.link}`, + name: attachment.label, + icon: groups.kind === 'issues' ? Codicon.issues : Codicon.gitPullRequest, + value: modelRepresentation, + _meta: attachment._meta, + }; +} + function restoreElementVariableEntry(attachment: MessageAttachment, modelRepresentation: string | undefined): IElementVariableEntry | undefined { if (attachment.displayKind !== AgentHostElementAttachmentDisplayKind || modelRepresentation === undefined) { return undefined; @@ -1698,19 +1767,6 @@ function restoreElementVariableEntry(attachment: MessageAttachment, modelReprese }; } -function getAgentHostCompletionKind(attachment: MessageAttachment): AgentHostCompletionReferenceKind | undefined { - if (attachment.type !== MessageAttachmentKind.Simple) { - return undefined; - } - switch (attachment.displayKind) { - case 'command': - return AgentHostCompletionReferenceKind.Command; - case 'skill': - return AgentHostCompletionReferenceKind.Skill; - } - return undefined; -} - function textRangeToIRange(range: TextRange): IRange { return { startLineNumber: range.start.line + 1, @@ -1999,6 +2055,7 @@ function buildTerminalToolSpecificData( ? { ...existing?.commandLine, original: nextCommand } : existing?.commandLine ?? { original: '' }; const nextOutput = getTerminalOutput(tc); + const executionTarget = getTerminalExecutionTarget(tc); // Spread `existing` so any field set by a prior pass (notably the // async-populated AHP fields and anything we don't explicitly handle) // is preserved unless we have a fresh value to override it with. @@ -2018,6 +2075,20 @@ function buildTerminalToolSpecificData( terminalCommandUri: terminalContentUri ? URI.parse(terminalContentUri) : existing?.terminalCommandUri, isPty: terminalContent?.isPty ?? existing?.isPty, terminalCommandOutput: nextOutput ?? existing?.terminalCommandOutput, + ...(executionTarget ? { executionTarget } : {}), + }; +} + +function getTerminalExecutionTarget(tc: ToolCallState): IChatTerminalToolInvocationData['executionTarget'] { + const meta = readToolCallMeta(tc); + const workingDirectory = meta['vscode.terminalWorkingDirectory']; + const environment = meta['vscode.terminalEnvironment']; + if (!workingDirectory && !environment) { + return undefined; + } + return { + ...(workingDirectory ? { workingDirectory } : {}), + ...(environment ? { environment } : {}), }; } @@ -2217,6 +2288,35 @@ function buildAutomationConfiguredToolData(tc: ToolCallState): IChatAutomationCo } } +function modelComparisonReference(tc: ToolCallState): IMarkdownString | undefined { + if (tc.status !== ToolCallStatus.Completed || !tc.success + || tc.toolName !== 'createModelComparison' && tc.toolName !== 'vscode_createModelComparison') { + return undefined; + } + const output = getToolOutputText(tc); + if (!output) { + return undefined; + } + let parsed: { comparisonId?: unknown } | null; + try { + parsed = JSON.parse(output); + } catch (error) { + if (error instanceof SyntaxError) { + return undefined; + } + throw error; + } + if (typeof parsed?.comparisonId !== 'string' || !parsed.comparisonId) { + return undefined; + } + return withCommandLink( + localize('agentHost.modelComparison.started', "Started model comparison."), + OPEN_SESSION_COMPARISON_COMMAND_ID, + [parsed.comparisonId], + localize('agentHost.modelComparison.open', "Open Comparison"), + ); +} + /** * Derives a title for the "Open Session" button from a session tool's arguments — * the `prompt` (create_session/create_chat) or `message` (send_message) it was @@ -2336,6 +2436,7 @@ export function completedToolCallToSerialized(tc: ICompletedToolCall, subAgentIn let pastTenseMsg = imageTerminalMessage ?? (isSuccess ? stringOrMarkdownToString(presentation.pastTenseMessage, connectionAuthority) ?? invocationMsg : invocationMsg); + pastTenseMsg = modelComparisonReference(tc) ?? pastTenseMsg; // Tools that render a bespoke, client-authored message override both the // invocation and past-tense text here. Add new per-tool cases alongside. if (isAddCommentTool(tc.toolName)) { @@ -3208,6 +3309,12 @@ export function finalizeToolInvocation(invocation: ChatToolInvocation, tc: ToolC const isTerminal = isTerminalToolCall(tc, invocation.toolSpecificData?.kind); invocation.summary = getToolSummary(tc, resourceUris); + // A call that asked for approval is marked to hide once it settles, which suits one the user + // declined. One that was approved ran, so it stays in the transcript like any other call. + if (isCompleted && invocation.presentation === ToolInvocationPresentation.HiddenAfterComplete) { + invocation.presentation = undefined; + } + if (!isTerminal && invocation.toolSpecificData?.kind === 'search' && getToolKind(tc) !== 'search') { invocation.toolSpecificData = buildMcpAppToolInputData(tc, connectionAuthority); } @@ -3285,7 +3392,7 @@ export function finalizeToolInvocation(invocation: ChatToolInvocation, tc: ToolC }; } if (isCompleted && !isTerminal) { - invocation.pastTenseMessage = stringOrMarkdownToString(readToolCallPresentation(tc).pastTenseMessage, connectionAuthority); + invocation.pastTenseMessage = modelComparisonReference(tc) ?? stringOrMarkdownToString(readToolCallPresentation(tc).pastTenseMessage, connectionAuthority); } const imageTerminalMessage = getImageGenerationTerminalMessage(tc); if (imageTerminalMessage) { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionApprovalModel.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionApprovalModel.ts index 355c4707be95..330f2fe8d711 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionApprovalModel.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionApprovalModel.ts @@ -9,7 +9,7 @@ import { autorun, autorunIterableDelta, IObservable, ISettableObservable, observ import { URI } from '../../../../../base/common/uri.js'; import { migrateLegacyTerminalToolSpecificData } from '../../common/chat.js'; import { IChatModel, IChatResponseModel } from '../../common/model/chatModel.js'; -import { IChatService, IChatToolInvocation, ToolConfirmKind } from '../../common/chatService/chatService.js'; +import { IChatService, IChatTerminalToolInvocationData, IChatToolInvocation, ToolConfirmKind } from '../../common/chatService/chatService.js'; import { ILanguageService } from '../../../../../editor/common/languages/language.js'; /** @@ -30,6 +30,8 @@ export interface IAgentSessionApprovalInfo { readonly kind: AgentSessionApprovalKind; readonly label: string; readonly languageId: string | undefined; + /** Where a terminal command runs, when its producer reports it. */ + readonly executionTarget?: IChatTerminalToolInvocationData['executionTarget']; readonly since: Date; confirm(): void; } @@ -97,7 +99,8 @@ export class AgentSessionApprovalModel extends Disposable { if (current === value) { return; } - if (current !== undefined && value !== undefined && current.approvalId === value.approvalId && current.kind === value.kind && current.label === value.label && current.languageId === value.languageId) { + if (current !== undefined && value !== undefined && current.approvalId === value.approvalId && current.kind === value.kind && current.label === value.label && current.languageId === value.languageId + && current.executionTarget?.workingDirectory === value.executionTarget?.workingDirectory && current.executionTarget?.environment === value.executionTarget?.environment) { return; } settable.set(value, undefined); @@ -132,11 +135,13 @@ export class AgentSessionApprovalModel extends Disposable { const detail = title ? typeof title === 'string' ? title : renderAsPlaintext(title) : needsInput.detail; let label: string; let languageId: string | undefined; + let executionTarget: IChatTerminalToolInvocationData['executionTarget']; let kind: AgentSessionApprovalKind; if (part.toolSpecificData?.kind === 'terminal') { const terminalData = migrateLegacyTerminalToolSpecificData(part.toolSpecificData); label = terminalData.presentationOverrides?.commandLine ?? terminalData.commandLine.forDisplay ?? terminalData.commandLine.userEdited ?? terminalData.commandLine.toolEdited ?? terminalData.commandLine.original; languageId = this._languageService.getLanguageIdByLanguageName(terminalData.presentationOverrides?.language ?? terminalData.language) ?? undefined; + executionTarget = terminalData.executionTarget; kind = AgentSessionApprovalKind.Terminal; } else if (detail) { label = detail; @@ -153,6 +158,7 @@ export class AgentSessionApprovalModel extends Disposable { kind, label, languageId, + executionTarget, since: new Date(), confirm: () => IChatToolInvocation.confirmWith(part, { type: ToolConfirmKind.UserAction, ...(selectedButton ? { selectedButton } : {}) }), }); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts index 4d61403f8620..25522f4d7bd9 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts @@ -53,6 +53,8 @@ export class ToggleShowAgentSessionsAction extends Action2 { super({ id: 'workbench.action.chat.toggleShowAgentSessions', title: localize2('chat.showSessions', "Show Sessions"), + // The sessions of the Chat view, which does not show while the Agents view replaces it + precondition: ChatContextKeys.agentsViewActive.negate(), toggled: ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), menu: { id: MenuId.ChatWelcomeContext, @@ -86,7 +88,7 @@ export class SetAgentSessionsOrientationStackedAction extends Action2 { id: 'workbench.action.chat.setAgentSessionsOrientationStacked', title: localize2('chat.sessionsOrientation.stacked', "Stacked"), toggled: ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsOrientation}`, 'stacked'), - precondition: ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), + precondition: ContextKeyExpr.and(ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), ChatContextKeys.agentsViewActive.negate()), menu: { id: agentSessionsOrientationSubmenu, group: 'navigation', @@ -109,7 +111,7 @@ export class SetAgentSessionsOrientationSideBySideAction extends Action2 { id: 'workbench.action.chat.setAgentSessionsOrientationSideBySide', title: localize2('chat.sessionsOrientation.sideBySide', "Side by Side"), toggled: ContextKeyExpr.notEquals(`config.${ChatConfiguration.ChatViewSessionsOrientation}`, 'stacked'), - precondition: ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), + precondition: ContextKeyExpr.and(ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), ChatContextKeys.agentsViewActive.negate()), menu: { id: agentSessionsOrientationSubmenu, group: 'navigation', @@ -1257,6 +1259,7 @@ export class ShowAgentSessionsSidebar extends UpdateChatViewWidthAction { precondition: ContextKeyExpr.and( ChatContextKeys.enabled, ChatContextKeys.agentSessionsViewerOrientation.isEqualTo(AgentSessionsViewerOrientation.Stacked), + ChatContextKeys.agentsViewActive.negate(), ), f1: true, category: AGENT_SESSIONS_CATEGORY, @@ -1280,6 +1283,7 @@ export class HideAgentSessionsSidebar extends UpdateChatViewWidthAction { precondition: ContextKeyExpr.and( ChatContextKeys.enabled, ChatContextKeys.agentSessionsViewerOrientation.isEqualTo(AgentSessionsViewerOrientation.SideBySide), + ChatContextKeys.agentsViewActive.negate(), ), f1: true, category: AGENT_SESSIONS_CATEGORY, @@ -1300,7 +1304,7 @@ export class ToggleAgentSessionsSidebar extends Action2 { super({ id: ToggleAgentSessionsSidebar.ID, title: ToggleAgentSessionsSidebar.TITLE, - precondition: ChatContextKeys.enabled, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.agentsViewActive.negate()), f1: true, category: AGENT_SESSIONS_CATEGORY, }); @@ -1331,7 +1335,8 @@ export class FocusAgentSessionsAction extends Action2 { title: localize2('chat.focusAgentSessionsViewer.label', "Focus Agent Sessions"), precondition: ContextKeyExpr.and( ChatContextKeys.enabled, - ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true) + ContextKeyExpr.equals(`config.${ChatConfiguration.ChatViewSessionsEnabled}`, true), + ChatContextKeys.agentsViewActive.negate(), ), category: AGENT_SESSIONS_CATEGORY, f1: true, diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsBanner.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsBanner.ts index a9a70796cea2..0419a5af27f1 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsBanner.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsBanner.ts @@ -11,7 +11,7 @@ import { localize } from '../../../../../nls.js'; import { ICommandService, CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; -import { logSettingExperimentTrigger } from '../../../../../platform/telemetry/common/experimentTrigger.js'; +import { logExperimentTrigger, logSettingExperimentTrigger } from '../../../../../platform/telemetry/common/experimentTrigger.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; @@ -34,19 +34,33 @@ type AgentsBannerClickedClassification = { export interface IAgentsBannerResult { readonly element: HTMLElement; readonly disposables: DisposableStore; - /** Whether the banner is shown, see {@link canShowAgentsBanner}. */ + /** Whether the banner is shown, that is, whether {@link isAgentsWindowAvailable} holds. */ readonly visible: IObservable; } -/** Returns whether the desktop Agents window is available and agent mode and AI features are enabled. */ -export function canShowAgentsBanner(chatEntitlementService: IChatEntitlementService, configurationService: IConfigurationService): boolean { +/** + * Returns whether the desktop Agents window is available and agent mode and AI features are enabled. + * The banner is shown while this holds, and its button either offers GitHub sign-in or opens the + * Agents window (see {@link createAgentsBanner}). + * + * Matches `OPEN_AGENTS_WINDOW_PRECONDITION`: chat that is merely disabled does not count as + * unavailable, because new profiles keep the chat extension disabled until chat setup completes. + */ +export function isAgentsWindowAvailable(chatEntitlementService: IChatEntitlementService, configurationService: IConfigurationService): boolean { const sentiment = chatEntitlementService.sentiment; - if (sentiment.hidden || sentiment.disabled || configurationService.getValue(ChatConfiguration.AgentEnabled) === false) { + if (sentiment.hidden || sentiment.disabledInWorkspace || configurationService.getValue(ChatConfiguration.AgentEnabled) === false) { return false; } return !!CommandsRegistry.getCommand(OPEN_WORKSPACE_IN_AGENTS_WINDOW_COMMAND_ID); } +/** + * The experiment trigger that the banner logs in every arm of the {@link ChatConfiguration.WelcomePageAgentsWindowGraphic} + * experiment when the graphic could be seen while more than one editor window is open. Only then does the `auto` graphic + * differ from `windowComparison` (it shows `manyWindowsToOne`), so this limits an analysis to where these arms differ. + */ +export const AGENTS_WINDOW_GRAPHIC_MULTIPLE_EDITOR_WINDOWS_TREATMENT = `config.${ChatConfiguration.WelcomePageAgentsWindowGraphic}.multipleEditorWindows`; + export interface IAgentsBannerOptions { /** Dot-separated CSS classes for the banner container (e.g. 'my-banner' or 'foo.bar'). */ readonly cssClass: string; @@ -59,8 +73,16 @@ export interface IAgentsBannerOptions { * The trigger of {@link ChatConfiguration.WelcomePageAgentsWindowSectionStyle} is logged in the same * moment once `shownDesign` has a value, since that style only applies while a graphic is shown. It * doesn't wait for the page to decide whether the graphic fits, because the style changes that decision. + * + * {@link AGENTS_WINDOW_GRAPHIC_MULTIPLE_EDITOR_WINDOWS_TREATMENT} is logged in the same moment once + * `hasMultipleEditorWindows` is true. */ - readonly graphic?: { readonly element: HTMLElement; readonly shownDesign: IObservable; readonly isExposed: IObservable }; + readonly graphic?: { + readonly element: HTMLElement; + readonly shownDesign: IObservable; + readonly isExposed: IObservable; + readonly hasMultipleEditorWindows: IObservable; + }; } /** @@ -83,14 +105,14 @@ export function createAgentsBanner( const element = $(`.${options.cssClass}`, {}, ...(options.graphic ? [options.graphic.element] : []), button); const visible = observableValue('agentsBannerVisible', false); const updateVisibility = () => { - const isVisible = canShowAgentsBanner(chatEntitlementService, configurationService); + const isVisible = isAgentsWindowAvailable(chatEntitlementService, configurationService); setVisibility(isVisible, element); button.disabled = !isVisible; visible.set(isVisible, undefined); }; updateVisibility(); if (options.graphic) { - const { shownDesign, isExposed } = options.graphic; + const { shownDesign, isExposed, hasMultipleEditorWindows } = options.graphic; disposables.add(autorun(reader => { if (!visible.read(reader) || !isExposed.read(reader)) { return; @@ -99,6 +121,9 @@ export function createAgentsBanner( if (shownDesign.read(reader) !== undefined) { logSettingExperimentTrigger(telemetryService, ChatConfiguration.WelcomePageAgentsWindowSectionStyle); } + if (hasMultipleEditorWindows.read(reader)) { + logExperimentTrigger(telemetryService, AGENTS_WINDOW_GRAPHIC_MULTIPLE_EDITOR_WINDOWS_TREATMENT); + } })); } disposables.add(chatEntitlementService.onDidChangeSentiment(updateVisibility)); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsControl.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsControl.ts index 59755031083f..2af75ac346f1 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsControl.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsControl.ts @@ -551,7 +551,7 @@ export class AgentSessionsControl extends Disposable implements IAgentSessionsCo let sectionLabel: string | undefined; // Section header — querySelector is needed to identify elements within virtualized list rows - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const sectionHeaderEl = row.querySelector('.agent-session-section-label'); if (sectionHeaderEl) { sectionLabel = sectionHeaderEl.textContent ?? undefined; @@ -559,7 +559,7 @@ export class AgentSessionsControl extends Disposable implements IAgentSessionsCo // Show-more element if (!sectionLabel) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const showMoreEl = row.querySelector('.agent-session-show-more'); if (showMoreEl) { sectionLabel = showMoreEl.getAttribute('data-section-label') ?? undefined; @@ -568,7 +568,7 @@ export class AgentSessionsControl extends Disposable implements IAgentSessionsCo // Session item — use data-section-label attribute if (!sectionLabel) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const sessionItem = row.querySelector('.agent-session-item[data-section-label]'); if (sessionItem) { sectionLabel = sessionItem.getAttribute('data-section-label') ?? undefined; @@ -579,7 +579,7 @@ export class AgentSessionsControl extends Disposable implements IAgentSessionsCo // inside a row with a session item, keep the current state // (prevents collapse when hovering toolbar icons, diff stats, etc.) if (!sectionLabel) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax if (row.querySelector('.agent-session-item')) { return; } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsViewer.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsViewer.ts index 5caa173e6193..8af6d8618dd2 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsViewer.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsViewer.ts @@ -43,6 +43,7 @@ import { renderAsPlaintext } from '../../../../../base/browser/markdownRenderer. import { MarkdownString, IMarkdownString } from '../../../../../base/common/htmlContent.js'; import { AgentSessionHoverWidget } from './agentSessionHoverWidget.js'; import { AgentSessionChatToolbar, AgentSessionProviders, getAgentSessionProvider, getAgentSessionProviderIcon } from './agentSessions.js'; +import { agentSessionNeedsInputForeground } from '../../../../common/agentsColors.js'; import { AgentSessionsGrouping, AgentSessionsSorting } from './agentSessionsFilter.js'; import { autorun, IObservable } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; @@ -196,7 +197,7 @@ export function getAgentSessionStatusIcon(session: IAgentSession): ThemeIcon { } if (session.status === AgentSessionStatus.NeedsInput) { - return { ...Codicon.reportQuestion, color: themeColorFromId('list.warningForeground') }; + return { ...Codicon.reportQuestion, color: themeColorFromId(agentSessionNeedsInputForeground) }; } if (session.status === AgentSessionStatus.Failed) { @@ -280,6 +281,7 @@ export class AgentSessionRenderer extends Disposable implements ICompressibleTre const elements = h( 'div.agent-session-item@item', [ + h('span.agent-session-attention-indicator', { 'aria-hidden': 'true' }), h('div.agent-session-icon-col', [ h('div.agent-session-icon@icon') ]), @@ -815,6 +817,7 @@ export class AgentSessionChatRenderer implements ICompressibleTreeRenderer = this._shownDesign; + private readonly _hasMultipleEditorWindows = observableValue(this, undefined); + /** + * Whether more than one editor window is open, or `undefined` until the windows have been counted. + * {@link AgentsWindowGraphicVariant.Auto} picks its graphic from this. The windows are counted for every + * variant, so that the page can log an experiment trigger for this case in every experiment arm. + */ + readonly hasMultipleEditorWindows: IObservable = this._hasMultipleEditorWindows; + /** * How the graphic, its captions and the Agents window button should be set apart from the rest of the page, * see {@link ChatConfiguration.WelcomePageAgentsWindowSectionStyle}. The page that shows the graphic applies it. @@ -75,12 +83,9 @@ export class AgentsWindowGraphic extends Disposable { () => getAgentsWindowSectionStyle(configurationService), ); - // Count the editor windows when the graphic is shown, and only when the graphic depends on them - const hasMultipleEditorWindows = observableValue(this, undefined); + // Count the editor windows whenever the setting changes, for every variant, see hasMultipleEditorWindows this._register(autorun(reader => { - if (variant.read(reader) !== AgentsWindowGraphicVariant.Auto) { - return; - } + variant.read(reader); let disposed = false; reader.store.add(toDisposable(() => disposed = true)); const update = async () => { @@ -91,13 +96,13 @@ export class AgentsWindowGraphic extends Disposable { onUnexpectedError(error); } if (!disposed) { - hasMultipleEditorWindows.set(hasMultiple, undefined); + this._hasMultipleEditorWindows.set(hasMultiple, undefined); } }; update(); })); - const design = derived(this, reader => resolveAgentsWindowGraphicDesign(variant.read(reader), hasMultipleEditorWindows.read(reader))); + const design = derived(this, reader => resolveAgentsWindowGraphicDesign(variant.read(reader), this._hasMultipleEditorWindows.read(reader))); this._register(autorun(reader => { const shownDesign = design.read(reader); reset(this.element, ...(shownDesign ? [renderAgentsWindowGraphic(shownDesign)] : [])); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/experiments/unifiedQuickAccess.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/experiments/unifiedQuickAccess.ts index 91d2a01a0673..295aae49a5fb 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/experiments/unifiedQuickAccess.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/experiments/unifiedQuickAccess.ts @@ -269,16 +269,16 @@ export class UnifiedQuickAccess extends Disposable { this._currentDisposables.delete(showDisposable); // Find the quick input widget container via layout service - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const quickInputWidget = this.layoutService.activeContainer.querySelector('.quick-input-widget'); if (!quickInputWidget) { return; } // Find the header element (contains input box) and list element - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const header = quickInputWidget.querySelector('.quick-input-header'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const list = quickInputWidget.querySelector('.quick-input-list'); if (!header || !list) { return; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/media/agentsessionsviewer.css b/src/vs/workbench/contrib/chat/browser/agentSessions/media/agentsessionsviewer.css index a411f01395fe..09dc99225b1c 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/media/agentsessionsviewer.css +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/media/agentsessionsviewer.css @@ -27,12 +27,28 @@ } /* Suppressed while selected so the selection highlight is not overpainted. */ - .monaco-list-row:not(.selected):not(.focused):not(:hover):has(.agent-session-icon.needs-input) { - background-color: color-mix(in srgb, var(--vscode-list-warningForeground) 8%, transparent); + .monaco-list-row:not(.selected):not(.focused):not(:hover):has(.agent-session-icon.needs-input), + .monaco-list-row:not(.selected):not(.focused):not(:hover) .agent-session-chat-item.needs-input { + background-color: color-mix(in srgb, var(--vscode-agentSessionNeedsInput-foreground) 8%, transparent); + + :is(.hc-black, .hc-light) & { + background-color: transparent; + + .agent-session-attention-indicator { + display: block; + } + } } - .monaco-list-row:not(.selected):not(.focused):not(:hover) .agent-session-chat-item.needs-input { - background-color: color-mix(in srgb, var(--vscode-list-warningForeground) 8%, transparent); + .agent-session-attention-indicator { + display: none; + position: absolute; + top: var(--vscode-spacing-size40); + bottom: var(--vscode-spacing-size40); + left: 0; + width: var(--vscode-spacing-size20); + background-color: var(--vscode-agentSessionNeedsInput-foreground); + pointer-events: none; } .monaco-list-row .force-no-twistie { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessionsConfiguration.ts b/src/vs/workbench/contrib/chat/browser/agentSessionsConfiguration.ts index 817d9cb3bce8..80ad45c3687c 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessionsConfiguration.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessionsConfiguration.ts @@ -6,9 +6,10 @@ import * as nls from '../../../../nls.js'; import { AgentHostAutoArchiveMergedSessionsAfterDaysConfigKey, AgentHostAutoDeleteArchivedMergedSessionsAfterDaysConfigKey } from '../../../../platform/agentHost/common/agentHostSchema.js'; import { AgentHostActiveAgentTitleGenerationSettingId, AgentHostDeferredTitleGenerationSettingId, AgentHostTitleGenerationSettingId } from '../../../../platform/agentHost/common/agentService.js'; -import { CopilotImageGenerationEnabledSettingId, CopilotImageGenerationModelSettingId } from '../../../../platform/agentHost/common/copilotCliConfig.js'; +import { CopilotCliConfigKey, CopilotImageGenerationEnabledSettingId, CopilotImageGenerationModelSettingId } from '../../../../platform/agentHost/common/copilotCliConfig.js'; import { migrateLegacyImageGenerationSetting } from '../../../../platform/agentHost/common/imageGenerationConfiguration.js'; import { migrateLegacyTitleGenerationSettings } from '../../../../platform/agentHost/common/titleGenerationConfiguration.js'; +import { AgentHostCopilotM365EnabledSettingId } from '../../../../platform/chat/common/chatSettings.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationPropertySchema, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import product from '../../../../platform/product/common/product.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; @@ -110,6 +111,15 @@ for (const key of [ChatConfiguration.AgentsParallelWorkBannerEnabled, ChatConfig Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ id: 'chat', properties: { + [AgentHostCopilotM365EnabledSettingId]: { + type: 'boolean', + markdownDescription: nls.localize('chat.agentHost.copilot.m365.enabled', "Enable Microsoft 365 Copilot access and account choice for Copilot Agent Host sessions. When disabled, Microsoft sign-in continues to use GitHub Copilot only.\n\nChanging this setting requires restarting VS Code. It does not switch your active account or service; sign out and sign back in to change accounts."), + default: false, + scope: ConfigurationScope.APPLICATION, + tags: ['experimental', 'advanced'], + experiment: { mode: 'startup' }, + agentHost: { key: CopilotCliConfigKey.M365Enabled }, + }, [ChatConfiguration.AgentsPickerInAttachContextMenu]: { type: 'boolean', default: false, diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemSource.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemSource.ts index b7a75d584c0e..e96a7cb46905 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemSource.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemSource.ts @@ -24,7 +24,7 @@ import { IProductService } from '../../../../../platform/product/common/productS import { IPathService } from '../../../../services/path/common/pathService.js'; import { AICustomizationScope, AICustomizationScopes, AICustomizationSources, IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; import { RecordedCustomizationMarketplaceInstallState } from '../../common/customizationMarketplaceInstallService.js'; -import { ICustomizationItem, ICustomizationItemProvider, ICustomizationSourceFolder, isLegacyDeliveryGroupKey } from '../../common/customizationHarnessService.js'; +import { ICustomizationItem, ICustomizationItemProvider, ICustomizationOrganizationControl, ICustomizationSourceFolder, isLegacyDeliveryGroupKey } from '../../common/customizationHarnessService.js'; import { parseHooksFromFile } from '../../common/promptSyntax/hookCompatibility.js'; import { formatHookCommandLabel } from '../../common/promptSyntax/hookSchema.js'; import { HOOK_METADATA } from '../../common/promptSyntax/hookTypes.js'; @@ -109,6 +109,8 @@ export interface IAICustomizationListItem { readonly status?: 'loading' | 'loaded' | 'degraded' | 'error'; /** Human-readable status detail (e.g. error message or warning). */ readonly statusMessage?: string; + /** Set when the user's organization manages this item. */ + readonly organizationControl?: ICustomizationOrganizationControl; /** When true, this item can be selected for syncing to a remote harness. */ readonly syncable?: boolean; /** When true, this syncable item is currently selected for syncing. */ @@ -222,6 +224,7 @@ export async function expandHookFileItems( status: item.status, statusMessage: item.statusMessage, disabledReason: item.disabledReason, + organizationControl: item.organizationControl, userInvocable: item.userInvocable, }); } @@ -292,6 +295,7 @@ export class AICustomizationItemNormalizer { extensionId, status: item.status, statusMessage: item.statusMessage, + organizationControl: item.organizationControl, }; } diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.ts index 25fa6fbdef95..5f64b0b1ace2 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.ts @@ -5,7 +5,7 @@ import { RunOnceScheduler } from '../../../../../base/common/async.js'; import { onUnexpectedError } from '../../../../../base/common/errors.js'; -import { Disposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { ResourceMap } from '../../../../../base/common/map.js'; import { autorun, derived, IObservable, ISettableObservable, observableValue } from '../../../../../base/common/observable.js'; import { basename, isEqual } from '../../../../../base/common/resources.js'; @@ -17,7 +17,8 @@ import { IProductService } from '../../../../../platform/product/common/productS import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; import { IPathService } from '../../../../services/path/common/pathService.js'; import { IAICustomizationWorkspaceService, AICustomizationManagementSection } from '../../common/aiCustomizationWorkspaceService.js'; -import { ICustomizationHarnessService, IHarnessDescriptor, isPluginCustomizationItem, isSyncedFromClientCustomizationItem } from '../../common/customizationHarnessService.js'; +import { CustomizationHarnessServiceBase, ICustomizationHarnessService, IHarnessDescriptor, isPluginCustomizationItem, isSyncedFromClientCustomizationItem } from '../../common/customizationHarnessService.js'; +import { ServiceCollection } from '../../../../../platform/instantiation/common/serviceCollection.js'; import { ICustomizationMarketplaceInstallService } from '../../common/customizationMarketplaceInstallService.js'; import { IAgentPluginService } from '../../common/plugins/agentPluginService.js'; import { PromptsType } from '../../common/promptSyntax/promptTypes.js'; @@ -62,6 +63,8 @@ export const IAICustomizationItemsModel = createDecorator; + whenSectionLoaded(section: ItemsModelSection | typeof AICustomizationManagementSection.Plugins): Promise; } export class AICustomizationItemsModel extends Disposable implements IAICustomizationItemsModel { @@ -115,6 +118,7 @@ export class AICustomizationItemsModel extends Disposable implements IAICustomiz private pendingRefetchSource: IAICustomizationItemSource | undefined; private readonly refetchObservedScheduler = this._register(new RunOnceScheduler(() => { const source = this.pendingRefetchSource; + this.pendingRefetchSource = undefined; if (!source || this._store.isDisposed) { return; } @@ -142,6 +146,7 @@ export class AICustomizationItemsModel extends Disposable implements IAICustomiz }); private pluginCountObserved = false; private pluginFetchSeq = 0; + private pluginPending: Promise = Promise.resolve(); /** * Sections that have been observed at least once. The model only fetches on * demand: first `getItems`/`getCount` for a section triggers an initial fetch, @@ -223,6 +228,20 @@ export class AICustomizationItemsModel extends Disposable implements IAICustomiz return this.perSection.get(section)!; } + createSessionModel(sessionResource: URI): IDisposable & { readonly model: IAICustomizationItemsModel } { + const store = new DisposableStore(); + try { + const harness = store.add(new CustomizationHarnessServiceBase(this.harnessService.availableHarnesses.get(), getChatSessionType(sessionResource), this.promptsService)); + harness.setActiveSession(sessionResource); + const instantiationService = store.add(this.instantiationService.createChild(new ServiceCollection([ICustomizationHarnessService, harness]))); + const model = store.add(instantiationService.createInstance(AICustomizationItemsModel)); + return { model, dispose: () => store.dispose() }; + } catch (error) { + store.dispose(); + throw error; + } + } + getCount(section: ItemsModelSection): IObservable { this.markObserved(section); return this.perSectionCount.get(section)!; @@ -239,7 +258,17 @@ export class AICustomizationItemsModel extends Disposable implements IAICustomiz return this.getOrCreateSource(activeSessionResource, descriptor); } - whenSectionLoaded(section: ItemsModelSection): Promise { + whenSectionLoaded(section: ItemsModelSection | typeof AICustomizationManagementSection.Plugins): Promise { + if (this.pendingRefetchSource) { + const source = this.pendingRefetchSource; + this.pendingRefetchSource = undefined; + this.refetchObservedScheduler.cancel(); + this.refetchObserved(source); + } + if (section === AICustomizationManagementSection.Plugins) { + this.markPluginCountObserved(); + return this.pluginPending; + } this.markObserved(section); return this.perSectionPending.get(section) ?? Promise.resolve(); } @@ -346,7 +375,7 @@ export class AICustomizationItemsModel extends Disposable implements IAICustomiz .map(item => ({ name: item.name ?? '', enabled: item.enabled !== false })); }); - pending.then(plugins => { + this.pluginPending = pending.then(plugins => { if (this._store.isDisposed) { return; } diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationListWidget.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationListWidget.ts index 0044f126f1d3..6f814313fe0c 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationListWidget.ts @@ -7,6 +7,7 @@ import './media/aiCustomizationManagement.css'; import * as DOM from '../../../../../base/browser/dom.js'; import * as aria from '../../../../../base/browser/ui/aria/aria.js'; import { ActionBar } from '../../../../../base/browser/ui/actionbar/actionbar.js'; +import { ActionViewItem } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { Schemas } from '../../../../../base/common/network.js'; @@ -21,7 +22,7 @@ import { IInstantiationService } from '../../../../../platform/instantiation/com import { WorkbenchObjectTree } from '../../../../../platform/list/browser/listService.js'; import { IListContextMenuEvent, IListVirtualDelegate, IListRenderer } from '../../../../../base/browser/ui/list/list.js'; import { RenderIndentGuides } from '../../../../../base/browser/ui/tree/abstractTree.js'; -import { IObjectTreeElement, ITreeContextMenuEvent, ObjectTreeElementCollapseState } from '../../../../../base/browser/ui/tree/tree.js'; +import { IObjectTreeElement, ITreeContextMenuEvent } from '../../../../../base/browser/ui/tree/tree.js'; import { IPromptsService, PromptsStorage } from '../../common/promptSyntax/service/promptsService.js'; import { PromptsType } from '../../common/promptSyntax/promptTypes.js'; import { agentIcon, instructionsIcon, promptIcon, skillIcon, hookIcon, userIcon, workspaceIcon, builtinIcon } from './aiCustomizationIcons.js'; @@ -55,6 +56,7 @@ import { getCustomizationSecondaryText, MiddleEllipsisPathLabel } from './aiCust import { renderCustomizationMarketplaceIcon } from './aiCustomizationPresentation.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { ICustomizationHarnessService } from '../../common/customizationHarnessService.js'; +import { CustomizationOrganizationPolicyNotice, getOrganizationManagedTooltip, OrganizationManagedTag } from './customizationOrganizationPolicy.js'; import { ICommandService } from '../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { ICustomizationMarketplaceService } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; @@ -90,6 +92,7 @@ type CustomizationEditorSearchClassification = { const ITEM_HEIGHT = 44; const GROUP_HEADER_HEIGHT = 36; const GROUP_HEADER_HEIGHT_WITH_SEPARATOR = 40; +const MORE_ACTION_ID = 'aiCustomization.moreActions'; /** * Represents a collapsible group header in the list. @@ -152,7 +155,7 @@ interface IAICustomizationItemTemplateData { readonly typeIcon: HTMLElement; readonly nameLabel: HighlightedLabel; readonly badge: HTMLElement; - readonly tag: HTMLElement; + readonly managedTag: OrganizationManagedTag; readonly statusIcon: HTMLElement; readonly descriptionContainer: HTMLElement; readonly description: HighlightedLabel; @@ -162,6 +165,12 @@ interface IAICustomizationItemTemplateData { readonly elementDisposables: DisposableStore; readonly iconDisposables: DisposableStore; currentItemId: string | undefined; + menuActionViewItem: AICustomizationMenuActionViewItem | undefined; +} + +interface IItemContextMenuLifecycle { + readonly onShow: () => void; + readonly onHide: () => void; } interface IContributionSourcePresentation { @@ -183,6 +192,18 @@ interface IGroupHeaderTemplateData { readonly elementDisposables: DisposableStore; } +class AICustomizationMenuActionViewItem extends ActionViewItem { + override render(container: HTMLElement): void { + super.render(container); + this.label?.setAttribute('aria-haspopup', 'menu'); + this.setExpanded(false); + } + + setExpanded(expanded: boolean): void { + this.label?.setAttribute('aria-expanded', String(expanded)); + } +} + /** * Renderer for collapsible group headers (Workspace, User, Extensions). * Note: Click handling is done via the list's onDidOpen event, not here. @@ -286,9 +307,10 @@ class AICustomizationItemRenderer implements IListRenderer(); private focusedItemId: string | undefined; + private menuOpenItemId: string | undefined; constructor( - private readonly showItemActions: (item: IAICustomizationListItem, anchor: HTMLElement) => void, + private readonly showItemActions: (item: IAICustomizationListItem, anchor: HTMLElement, lifecycle: IItemContextMenuLifecycle) => void, private readonly presentation: IAICustomizationItemPresentation, @IHoverService private readonly hoverService: IHoverService, @ILabelService private readonly labelService: ILabelService, @@ -325,7 +347,7 @@ class AICustomizationItemRenderer implements IListRenderer action.id === MORE_ACTION_ID + ? new AICustomizationMenuActionViewItem(undefined, action, options) + : createActionViewItem(this.instantiationService, action, options), })); // Keep the inline actions out of the document tab order by default. Only the // focused row's action bar is made tab-focusable (see `setFocusedItemId`), @@ -350,7 +374,7 @@ class AICustomizationItemRenderer implements IListRenderer { templateData.actionBar.clear(); + templateData.menuActionViewItem = undefined; if (element.promptType === PromptsType.agent || element.promptType === PromptsType.skill || element.promptType === PromptsType.instructions || element.promptType === PromptsType.hook) { const moreAction = templateData.elementDisposables.add(new Action( - 'aiCustomization.moreActions', + MORE_ACTION_ID, localize('customizationMoreActionsAria', "More actions for {0}", displayName), ThemeIcon.asClassName(Codicon.ellipsis), true, - () => this.showItemActions(element, templateData.actionsContainer), + () => this.showItemActions(element, templateData.actionsContainer, { + onShow: () => this.setMenuOpenItemId(element.id), + onHide: () => { + if (this.menuOpenItemId === element.id) { + this.setMenuOpenItemId(undefined); + } + }, + }), )); templateData.actionBar.push(moreAction, { icon: true, label: false }); + const menuActionViewItem = templateData.actionBar.viewItems.find(item => item.action.id === MORE_ACTION_ID); + templateData.menuActionViewItem = menuActionViewItem instanceof AICustomizationMenuActionViewItem ? menuActionViewItem : undefined; } else { const actions = menu.getActions({ arg: context, shouldForwardArgs: true }); const { primary } = getContextMenuActions(actions, 'inline'); templateData.actionBar.push(primary, { icon: true, label: false }); } + this.updateMenuOpenState(templateData); }; updateActions(); templateData.elementDisposables.add(menu.onDidChange(updateActions)); @@ -581,6 +618,7 @@ class AICustomizationItemRenderer implements IListRenderer(); + /** The section whose tree is rendered, so that only a section change starts the tree from scratch. */ + private renderedTreeSection: AICustomizationManagementSection | undefined; private _layoutDeferred = false; private lastLayoutWidth = 0; private lastLayoutHeight = 0; @@ -917,6 +972,9 @@ export class AICustomizationListWidget extends Disposable { this.openerService.open(URI.parse(href)); } })); + this.organizationPolicyNotice = this._register(this.instantiationService.createInstance(CustomizationOrganizationPolicyNotice)); + this.sectionTitleHeader.appendChild(this.organizationPolicyNotice.element); + this.organizationPolicyNotice.setSection(this.currentSection); // Re-layout when the header height changes (e.g. description wraps, // or CSS adjustments alter padding) so the list's allotted height stays @@ -1000,7 +1058,7 @@ export class AICustomizationListWidget extends Disposable { // Create list const itemRenderer = this.instantiationService.createInstance( AICustomizationItemRenderer, - (item: IAICustomizationListItem, anchor: HTMLElement) => this.showItemContextMenu(item, anchor), + (item: IAICustomizationListItem, anchor: HTMLElement, lifecycle: IItemContextMenuLifecycle) => this.showItemContextMenu(item, anchor, lifecycle), { getOriginLabel: origin => this.getOriginLabel(origin), getContributionSource: item => this.getContributionSource(item), @@ -1043,7 +1101,6 @@ export class AICustomizationListWidget extends Disposable { }, multipleSelectionSupport: false, openOnSingleClick: true, - expandOnlyOnTwistieClick: entry => entry.type !== 'skill-bundle', } )); @@ -1062,6 +1119,13 @@ export class AICustomizationListWidget extends Disposable { } else { this.expandedSkillBundles.add(entry.item.id); } + } else if (entry?.type === 'group-header' && !this.searchQuery.trim()) { + const key = this.getCollapsedGroupKey(entry.groupKey); + if (event.node.collapsed) { + this.collapsedGroups.add(key); + } else { + this.collapsedGroups.delete(key); + } } })); @@ -1078,7 +1142,7 @@ export class AICustomizationListWidget extends Disposable { // so the focus indicator is visible instead of requiring the user to // press an arrow key first. this._register(this.list.onDidFocus(() => { - focusFirstCustomizationTreeItem(this.list, this.displayEntries, entry => entry.type !== 'group-header'); + focusFirstCustomizationTreeItem(this.list, this.displayEntries, entry => entry.type !== 'group-header' && this.isEntryVisible(entry)); })); this._register(this.list.onContextMenu(e => this.onContextMenu(e))); @@ -1105,7 +1169,7 @@ export class AICustomizationListWidget extends Disposable { this.showItemContextMenu(e.element.item, e.anchor); } - private showItemContextMenu(item: IAICustomizationListItem, anchor: IListContextMenuEvent['anchor']): void { + private showItemContextMenu(item: IAICustomizationListItem, anchor: IListContextMenuEvent['anchor'], lifecycle?: IItemContextMenuLifecycle): void { // Create context for the menu actions const context: Record = { uri: item.uri.toString(), @@ -1129,6 +1193,7 @@ export class AICustomizationListWidget extends Disposable { overlayPairs.push([AI_CUSTOMIZATION_ITEM_PLUGIN_URI_KEY, item.pluginUri.toString()]); overlayPairs.push([AI_CUSTOMIZATION_ITEM_PLUGIN_REQUIRED_KEY, isPluginUriRequiredByPolicy(this.agentPluginService, item.pluginUri)]); } + const menuDisposables = new DisposableStore(); const overlay = this.contextKeyService.createOverlay(overlayPairs); // Get menu actions, excluding inline actions to avoid duplicates @@ -1142,11 +1207,11 @@ export class AICustomizationListWidget extends Disposable { // Add copy path actions (not shown for built-in items where the path is an implementation detail) const copyActions = item.isBuiltin || !hasReadableCustomizationContent(item.uri) ? [] : [ new Separator(), - new Action('copyFullPath', localize('copyFullPath', "Copy Full Path"), undefined, true, async () => { + menuDisposables.add(new Action('copyFullPath', localize('copyFullPath', "Copy Full Path"), undefined, true, async () => { const path = item.uri.scheme === Schemas.file ? item.uri.fsPath : item.uri.toString(true); await this.clipboardService.writeText(path); - }), - new Action('copyRelativePath', localize('copyRelativePath', "Copy Relative Path"), undefined, true, async () => { + })), + menuDisposables.add(new Action('copyRelativePath', localize('copyRelativePath', "Copy Relative Path"), undefined, true, async () => { const basePath = this.workspaceService.getActiveProjectRoot(); if (basePath && item.uri.fsPath.startsWith(basePath.fsPath)) { const relative = item.uri.fsPath.substring(basePath.fsPath.length + 1); @@ -1156,12 +1221,24 @@ export class AICustomizationListWidget extends Disposable { const relativePath = this.labelService.getUriLabel(item.uri, { relative: true }); await this.clipboardService.writeText(relativePath); } - }), + })), ]; + const menuActions = [...secondary, ...copyActions]; + if (menuActions.length === 0) { + menuDisposables.dispose(); + return; + } + + lifecycle?.onShow(); this.contextMenuService.showContextMenu({ getAnchor: () => anchor, - getActions: () => [...secondary, ...copyActions], + getActions: () => menuActions, + autoSelectItem: lifecycle ? true : undefined, + onHide: () => { + menuDisposables.dispose(); + lifecycle?.onHide(); + }, }); } @@ -1178,6 +1255,7 @@ export class AICustomizationListWidget extends Disposable { } this.currentSection = section; this.updateSectionHeader(); + this.organizationPolicyNotice.setSection(section); const modelSection = toItemsModelSection(section); if (!modelSection) { @@ -1685,6 +1763,7 @@ export class AICustomizationListWidget extends Disposable { * Commits the current displayEntries to the list and updates empty state. */ private commitDisplayEntries(): void { + this.renderedTreeSection = undefined; this.list.setChildren(null, this.displayEntries.map(element => ({ element }))); this.updateEmptyState(); } @@ -1736,6 +1815,7 @@ export class AICustomizationListWidget extends Disposable { } return entries; }; + const isFiltering = !!this.searchQuery.trim(); const children: IObjectTreeElement[] = groups.map(group => { this.displayEntries.push(group.element); const fileEntries = group.children.filter((element): element is IFileItemEntry => element.type !== 'group-header'); @@ -1743,12 +1823,18 @@ export class AICustomizationListWidget extends Disposable { return { element: group.element, collapsible: true, - collapsed: ObjectTreeElementCollapseState.PreserveOrExpanded, + collapsed: !isFiltering && group.element.type === 'group-header' && this.collapsedGroups.has(this.getCollapsedGroupKey(group.element.groupKey)), children: entries, }; }); - this.list.setChildren(null); + // Update the rows of the same section in place, keeping focus and the + // scroll position; only a new section starts from an empty tree. + if (this.renderedTreeSection !== this.currentSection) { + this.renderedTreeSection = this.currentSection; + this.list.setChildren(null); + } this.list.setChildren(null, children); + this.moveFocusOutOfCollapsedGroups(); this.updateAddButton(); this.updateEmptyState(); } @@ -2079,6 +2165,10 @@ export class AICustomizationListWidget extends Disposable { this.announceItemCount(this.filterItems()); const entry = this.displayEntries.find(entry => entry.type === 'skill-bundle' && entry.item.skillBundle?.id === bundleId); if (entry) { + const group = this.list.getParentElement(entry); + if (group?.type === 'group-header') { + this.collapsedGroups.delete(this.getCollapsedGroupKey(group.groupKey)); + } this.list.expandTo(entry); this.list.expand(entry); this.list.reveal(entry); @@ -2107,12 +2197,45 @@ export class AICustomizationListWidget extends Disposable { */ focusList(): void { this.list.domFocus(); - const firstItem = this.displayEntries.find(entry => entry.type !== 'group-header'); + const firstItem = this.displayEntries.find(entry => entry.type !== 'group-header' && this.isEntryVisible(entry)) ?? this.displayEntries[0]; if (firstItem) { this.list.setFocus([firstItem]); } } + /** + * Moves focus from an entry hidden inside a collapsed group (for example a + * search result once the search is cleared) to its nearest visible ancestor, + * so a focused row and active descendant remain. + */ + private moveFocusOutOfCollapsedGroups(): void { + const [focused] = this.list.getFocus(); + if (!focused || !this.list.hasElement(focused) || this.isEntryVisible(focused)) { + return; + } + let ancestor = this.list.getParentElement(focused); + while (ancestor && !this.isEntryVisible(ancestor)) { + ancestor = this.list.getParentElement(ancestor); + } + this.list.setFocus(ancestor ? [ancestor] : []); + } + + /** + * Whether the entry has a row in the list, that is, it is not inside a + * collapsed group or skill bundle. + */ + private isEntryVisible(entry: IListEntry): boolean { + if (!this.list.hasElement(entry)) { + return false; + } + for (let parent = this.list.getParentElement(entry); parent; parent = this.list.getParentElement(parent)) { + if (this.list.isCollapsed(parent)) { + return false; + } + } + return true; + } + /** * Scrolls the list so the last item is visible. */ diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.contribution.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.contribution.ts index 413bb88565f9..612db3bbd4c9 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.contribution.ts @@ -72,6 +72,7 @@ import { AICustomizationManagementEditor, CopilotConnectorDetailOpenResult } fro import { AICustomizationManagementEditorInput } from './aiCustomizationManagementEditorInput.js'; import './customizationMarketplace.contribution.js'; import './customizationMigrationAccessibility.js'; +import './chatCustomizations.contribution.js'; import { CustomizationMigrationResultToolContribution } from './customizationMigrationResultTool.js'; //#region Telemetry diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.ts index 74b9736c23ac..f3fd118c7cfc 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagement.ts @@ -13,6 +13,8 @@ import { MenuId } from '../../../../../platform/actions/common/actions.js'; import { hasReadableCustomizationContent } from '../../../../../platform/agentHost/common/agentHostCustomizationUri.js'; import { CustomizationMigrationCategoryId } from './customizationMigrationCategories.js'; import { ICustomizationMigrationHint } from '../../common/promptSyntax/service/customizationMigrationService.js'; +import type { IChatWidget } from '../chat.js'; +import { hasKey } from '../../../../../base/common/types.js'; // Re-export for convenience — consumers import from this file export { AICustomizationManagementCommands, AICustomizationManagementSection } from '../../common/aiCustomizationWorkspaceService.js'; @@ -23,6 +25,7 @@ export const DELETE_AI_CUSTOMIZATION_ID = 'aiCustomizationManagement.delete'; export type AICustomizationManagementOpenEditorTarget = | AICustomizationManagementSection + | { readonly widget: IChatWidget } | { readonly section?: AICustomizationManagementSection; readonly sessionType?: string; @@ -42,6 +45,11 @@ export function resolveAICustomizationManagementOpenEditorTarget( chatSessionResource: URI | undefined, getSessionResourceForHarness: (sessionType: string) => URI, ): { readonly section?: AICustomizationManagementSection; readonly revealUri?: URI; readonly sessionResource?: URI; readonly showDiscover?: boolean; readonly searchQuery?: string; readonly migration?: boolean; readonly migrationCategory?: CustomizationMigrationCategoryId; readonly migrationHint?: ICustomizationMigrationHint } { + if (target && typeof target === 'object' && hasKey(target, { widget: true })) { + pendingSessionType = target.widget.input.pendingDelegationTarget; + chatSessionResource = target.widget.viewModel?.sessionResource; + target = undefined; + } if (isChatViewTitleActionContext(target)) { return { sessionResource: target.sessionResource }; } diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts index 0406627eb261..691c115c24d8 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts @@ -10,7 +10,7 @@ import { Button } from '../../../../../base/browser/ui/button/button.js'; import { IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; import { CustomizationMarketplaceIcon, CustomizationMarketplaceMediaType, getCustomizationMarketplaceResourceKey, ICustomizationMarketplaceCursor, ICustomizationMarketplacePage, ICustomizationMarketplaceResource, ICustomizationMarketplaceService } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; import { CustomizationMarketplaceConfiguration, CustomizationMarketplaceSources, getVisibleCustomizationMarketplaceSources } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; -import { normalizeMcpGalleryUrl } from '../../../../../platform/customizationMarketplace/common/mcpGalleryMarketplaceProvider.js'; +import { mcpAccessConfig, McpAccessValue, normalizeMcpGalleryUrl } from '../../../../../platform/mcp/common/mcpManagement.js'; import { getGitHubMcpRegistryIdentity, getGitHubMcpRegistryResourceIdentity } from './githubMcpRegistryIcons.js'; import { dirname as dirnamePath } from '../../../../../base/common/path.js'; @@ -57,7 +57,6 @@ import { IAICustomizationListItem } from './aiCustomizationItemSource.js'; import { IAICustomizationItemsModel, ITEMS_MODEL_SECTIONS } from './aiCustomizationItemsModel.js'; import { renderCustomizationMarketplaceIcon } from './aiCustomizationPresentation.js'; import { createInstalledPluginItem, McpListWidget } from './mcpListWidget.js'; -import { mcpAccessConfig, McpAccessValue } from '../../../../../platform/mcp/common/mcpManagement.js'; import { PluginListWidget } from './pluginListWidget.js'; import { ToolsListWidget } from './toolsListWidget.js'; import { AGENT_HOST_COPILOT_CLI_SESSION_TYPE } from '../agentSessions/agentHost/agentHostToolSetEnablementService.js'; @@ -2475,6 +2474,15 @@ export class AICustomizationManagementEditor extends EditorPane { return; } if (item.extensionId) { + // The Agents window has no Extensions view, so it shows the extension in its Extensions section instead. + const extensionsSection = this.sections.some(section => section.id === AICustomizationManagementSection.Extensions) + ? this.ensureContributedSectionWidget(AICustomizationManagementSection.Extensions) + : undefined; + if (extensionsSection?.showExtension) { + this.selectSection(AICustomizationManagementSection.Extensions); + extensionsSection.showExtension(item.extensionId); + return; + } await this.commandService.executeCommand(showExtensionsWithIdsCommandId, [item.extensionId]); } } @@ -3829,19 +3837,26 @@ export class AICustomizationManagementEditor extends EditorPane { // Move focus to the search input so keyboard users can immediately // filter without extra Tab traversal (parity with mouse-click flow). if (!options?.preserveFocus) { - if (section === AICustomizationManagementSection.McpServers) { - this.mcpListWidget?.focusSearch(); - } else if (section === AICustomizationManagementSection.Plugins) { - this.pluginListWidget?.focusSearch(); - } else if (section === AICustomizationManagementSection.Models) { - this.modelsWidget?.focusSearch(); - } else if (section === AICustomizationManagementSection.Tools) { - this.toolsListWidget?.focusSearch(); - } else if (this.contributedSectionContainers.has(section)) { - this.ensureContributedSectionWidget(section)?.focus?.(); - } else { - this.listWidget?.focusSearch(); - } + this.focusSectionContent(section); + } + } + + /** + * Moves focus to the search input of the given section, or into its widget for contributed sections. + */ + private focusSectionContent(section: AICustomizationManagementSection): void { + if (section === AICustomizationManagementSection.McpServers) { + this.mcpListWidget?.focusSearch(); + } else if (section === AICustomizationManagementSection.Plugins) { + this.pluginListWidget?.focusSearch(); + } else if (section === AICustomizationManagementSection.Models) { + this.modelsWidget?.focusSearch(); + } else if (section === AICustomizationManagementSection.Tools) { + this.toolsListWidget?.focusSearch(); + } else if (this.contributedSectionContainers.has(section)) { + this.ensureContributedSectionWidget(section)?.focus?.(); + } else { + this.listWidget?.focusSearch(); } } @@ -3974,7 +3989,7 @@ export class AICustomizationManagementEditor extends EditorPane { if (!contribution || !container) { return undefined; } - const widget = contribution.create(this.instantiationService, container); + const widget = contribution.create(this.instantiationService, container, this.group); this.contributedSectionWidgets.set(section, widget); widget.setCloseCustomizationEditor?.(() => this.closeCustomizationEditor()); const disposables = new DisposableStore(); @@ -4288,19 +4303,7 @@ export class AICustomizationManagementEditor extends EditorPane { this.welcomePage?.focus(); return; } - if (this.selectedSection === AICustomizationManagementSection.McpServers) { - this.mcpListWidget?.focusSearch(); - } else if (this.selectedSection === AICustomizationManagementSection.Plugins) { - this.pluginListWidget?.focusSearch(); - } else if (this.selectedSection === AICustomizationManagementSection.Models) { - this.modelsWidget?.focusSearch(); - } else if (this.selectedSection === AICustomizationManagementSection.Tools) { - this.toolsListWidget?.focusSearch(); - } else if (this.selectedSection && this.contributedSectionContainers.has(this.selectedSection)) { - this.ensureContributedSectionWidget(this.selectedSection)?.focus?.(); - } else { - this.listWidget?.focusSearch(); - } + this.focusSectionContent(this.selectedSection); } /** @@ -4374,22 +4377,22 @@ export class AICustomizationManagementEditor extends EditorPane { // to handle the case where the editor just opened with a persisted section that // matches the requested one (content might not be loaded yet). if (this.viewMode === 'marketplaceDetail') { - this.goBackFromMarketplaceDetail(); + this.goBackFromMarketplaceDetail(options?.preserveFocus); } if (this.viewMode === 'editor') { - this.goBackToList(); + this.goBackToList(options?.preserveFocus); } if (this.viewMode === 'migration') { this.viewMode = 'list'; } if (this.viewMode === 'mcpDetail') { - this.goBackFromMcpDetail(); + this.goBackFromMcpDetail(options?.preserveFocus); } if (this.viewMode === 'connectorDetail') { - this.goBackFromConnectorDetail(); + this.goBackFromConnectorDetail(options?.preserveFocus); } if (this.viewMode === 'pluginDetail') { - this.goBackFromPluginDetail(); + this.goBackFromPluginDetail(options?.preserveFocus); } this.selectedSection = sectionId; this.sectionContextKey.set(sectionId); @@ -4411,6 +4414,13 @@ export class AICustomizationManagementEditor extends EditorPane { this.pluginListWidget?.showBrowseMarketplace(); } } + + // Showing the section hides whatever had focus before (such as the welcome + // page search), so move focus into the section to keep the modal's Escape + // handling, Tab order, and screen reader context. + if (!options?.preserveFocus) { + this.focusSectionContent(sectionId); + } return true; } return false; diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementSectionRegistry.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementSectionRegistry.ts index dc7595aac8c1..dc010df04456 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementSectionRegistry.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementSectionRegistry.ts @@ -9,6 +9,7 @@ import { IDisposable, toDisposable } from '../../../../../base/common/lifecycle. import { IObservable } from '../../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IEditorGroup } from '../../../../services/editor/common/editorGroupsService.js'; import { AICustomizationManagementSection } from '../../common/aiCustomizationWorkspaceService.js'; export interface IAICustomizationManagementSectionWidget extends IDisposable { @@ -16,6 +17,8 @@ export interface IAICustomizationManagementSectionWidget extends IDisposable { focus?(): void; fireItemCount?(): void; setSearchQuery?(query: string): void; + /** Shows the installed extension with the given identifier, such as its page. */ + showExtension?(extensionId: string): void; setVisible?(visible: boolean): void; setCloseCustomizationEditor?(closeCustomizationEditor: () => Promise): void; getAccessibilityContent?(): string; @@ -40,7 +43,11 @@ export interface IAICustomizationManagementSectionContribution { * accessible name. The editor reads it while it is open. */ readonly getBadge?: (accessor: ServicesAccessor) => IObservable; - create(instantiationService: IInstantiationService, container: HTMLElement): IAICustomizationManagementSectionWidget; + /** + * Creates the section's widget in `container`. `group` is the editor group of the editor that shows the section, + * which editor panes that the section shows need. + */ + create(instantiationService: IInstantiationService, container: HTMLElement, group: IEditorGroup): IAICustomizationManagementSectionWidget; } class AICustomizationManagementSectionRegistry { diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationSectionBadges.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationSectionBadges.ts new file mode 100644 index 000000000000..7e898e76f0db --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationSectionBadges.ts @@ -0,0 +1,93 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { arrayEqualsC } from '../../../../../base/common/equals.js'; +import { IObservable, derived, derivedOpts, observableSignalFromEvent } from '../../../../../base/common/observable.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { ICustomizationHarnessService } from '../../common/customizationHarnessService.js'; +import { aiCustomizationManagementSectionRegistry } from './aiCustomizationManagementSectionRegistry.js'; + +/** + * The services that observing section badges reads. + */ +export interface IAICustomizationSectionBadgeServices { + readonly instantiationService: IInstantiationService; + readonly harnessService: ICustomizationHarnessService; + readonly workspaceService: IAICustomizationWorkspaceService; + readonly configurationService: IConfigurationService; +} + +/** + * A section that the active harness shows, and the description of its badge. + */ +export interface IAICustomizationVisibleSectionBadge { + readonly section: AICustomizationManagementSection; + readonly badge: string; +} + +/** + * Observes the badge of `section` while the active harness shows it in the editor, otherwise `undefined`. + */ +export function observeVisibleSectionBadge(accessor: ServicesAccessor, section: AICustomizationManagementSection): IObservable { + const badges = observeVisibleSectionBadges(getSectionBadgeServices(accessor), sections => sections.includes(section) ? [section] : []); + return derived(reader => badges.read(reader)[0]?.badge); +} + +/** + * Observes the badge of the first section with a badge, of `sections` if given, that the active harness shows in the + * editor, otherwise `undefined`. Entry points to the editor show it as a single badge. + */ +export function observeVisibleSectionsBadge(accessor: ServicesAccessor, sections?: ReadonlySet): IObservable { + const badges = observeVisibleSectionBadges(getSectionBadgeServices(accessor), sections && (managementSections => managementSections.filter(section => sections.has(section)))); + return derived(reader => badges.read(reader)[0]?.badge); +} + +/** + * Observes the badges of the management sections, or of those that `selectSections` selects, that the active harness + * shows in the editor, in the order of the management sections. Only reads the badges of visible sections, as reading + * a badge may log an experiment trigger. + */ +export function observeVisibleSectionBadges( + { instantiationService, harnessService, workspaceService, configurationService }: IAICustomizationSectionBadgeServices, + selectSections: (managementSections: readonly AICustomizationManagementSection[]) => readonly AICustomizationManagementSection[] = sections => sections, +): IObservable { + const configurationChanged = observableSignalFromEvent('aiCustomizationSectionBadges.configuration', configurationService.onDidChangeConfiguration); + + // Resolve the badge observables once per harness so that badge changes only re-read them. + const sectionBadges = derived(reader => { + const harnessId = harnessService.activeHarness.read(reader); + return selectSections(workspaceService.managementSections).flatMap(section => { + const getBadge = aiCustomizationManagementSectionRegistry.getBadge(section, harnessId); + return getBadge ? [{ section, badge: instantiationService.invokeFunction(getBadge) }] : []; + }); + }); + + return derivedOpts({ equalsFn: arrayEqualsC((a, b) => a.section === b.section && a.badge === b.badge) }, reader => { + configurationChanged.read(reader); + harnessService.availableHarnesses.read(reader); + const harnessId = harnessService.activeHarness.read(reader); + const visibleBadges: IAICustomizationVisibleSectionBadge[] = []; + for (const { section, badge } of sectionBadges.read(reader)) { + if (aiCustomizationManagementSectionRegistry.isVisible(section, harnessId, harnessService, configurationService)) { + const description = badge.read(reader); + if (description !== undefined) { + visibleBadges.push({ section, badge: description }); + } + } + } + return visibleBadges; + }); +} + +function getSectionBadgeServices(accessor: ServicesAccessor): IAICustomizationSectionBadgeServices { + return { + instantiationService: accessor.get(IInstantiationService), + harnessService: accessor.get(ICustomizationHarnessService), + workspaceService: accessor.get(IAICustomizationWorkspaceService), + configurationService: accessor.get(IConfigurationService), + }; +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizations.contribution.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizations.contribution.ts new file mode 100644 index 000000000000..c01b6e9ca0a9 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizations.contribution.ts @@ -0,0 +1,70 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { localize } from '../../../../../nls.js'; +import { MenuId, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ContextKeyExpr, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../common/contributions.js'; +import { IsSessionsWindowContext } from '../../../../common/contextkeys.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; +import { AICustomizationManagementCommands, IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { ChatAgentLocation, ChatConfiguration } from '../../common/constants.js'; +import { ChatCustomizationsLocation, ChatCustomizationsLocationContext, resolveChatCustomizationsLocation } from '../../common/customizationsLocation.js'; +import { ChatCustomizationsTelemetry } from './chatCustomizationsTelemetry.js'; + +const command = { + id: AICustomizationManagementCommands.OpenEditor, + title: localize('openChatCustomizations', "Open Customizations"), + icon: Codicon.extensions, +}; + +MenuRegistry.appendMenuItem(MenuId.ChatExecute, { + command, + group: 'navigation', + order: -12, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + IsSessionsWindowContext.negate(), + ChatContextKeys.location.isEqualTo(ChatAgentLocation.Chat), + ChatContextKeys.inQuickChat.negate(), + ChatContextKeys.currentlyEditing.negate(), + ChatCustomizationsLocationContext.isEqualTo('chatInput'), + ), +}); + +class ChatCustomizationsEntryPointContribution extends Disposable implements IWorkbenchContribution { + static readonly ID = 'workbench.contrib.chatCustomizationsEntryPoint'; + + constructor( + @IConfigurationService configurationService: IConfigurationService, + @IContextKeyService contextKeyService: IContextKeyService, + @IAICustomizationWorkspaceService workspaceService: IAICustomizationWorkspaceService, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + this._register(instantiationService.createInstance(ChatCustomizationsTelemetry).observeLocationChanges()); + if (workspaceService.isSessionsWindow) { + return; + } + const location = ChatCustomizationsLocationContext.bindTo(contextKeyService); + const update = () => location.set(resolveChatCustomizationsLocation( + configurationService.getValue(ChatConfiguration.ChatCustomizationsLocation), + false, + false, + )); + update(); + this._register(configurationService.onDidChangeConfiguration(event => { + if (event.affectsConfiguration(ChatConfiguration.ChatCustomizationsLocation)) { + update(); + } + })); + } +} + +registerWorkbenchContribution2(ChatCustomizationsEntryPointContribution.ID, ChatCustomizationsEntryPointContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsHover.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsHover.ts new file mode 100644 index 000000000000..d9808e2b8b97 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsHover.ts @@ -0,0 +1,351 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/chatCustomizations.css'; +import { IManagedHoverContent, IManagedHoverOptions, IManagedHoverTooltipMarkdownString } from '../../../../../base/browser/ui/hover/hover.js'; +import { reset } from '../../../../../base/browser/dom.js'; +import { renderLabelWithIcons } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { raceCancellation } from '../../../../../base/common/async.js'; +import { MarkdownString } from '../../../../../base/common/htmlContent.js'; +import { basename, isEqual } from '../../../../../base/common/resources.js'; +import { IObservable, IReader, autorun, constObservable, derived, observableSignal } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { isObject } from '../../../../../base/common/types.js'; +import { localize } from '../../../../../nls.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from '../../../../../platform/actions/browser/menuEntryActionViewItem.js'; +import { MenuItemAction } from '../../../../../platform/actions/common/actions.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { IStorageService } from '../../../../../platform/storage/common/storage.js'; +import { AICustomizationManagementCommands, AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { ChatConfiguration } from '../../common/constants.js'; +import { ICustomizationHarnessService } from '../../common/customizationHarnessService.js'; +import { getMcpServerDisplayLabel, IAgentHostCustomizationService } from '../agentSessions/agentHost/agentHostCustomizationService.js'; +import { IMcpService } from '../../../mcp/common/mcpTypes.js'; +import { McpCommandIds } from '../../../mcp/common/mcpCommandIds.js'; +import { IAICustomizationItemsModel } from './aiCustomizationItemsModel.js'; +import { AgentHostMcpServer, getEffectiveMcpServerCounts } from './mcpServerCount.js'; +import { IChatWidgetService } from '../chat.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { CustomizationMigrationState } from './customizationMigrationState.js'; +import { hookIcon, instructionsIcon, mcpServerIcon, pluginIcon, skillIcon } from './aiCustomizationIcons.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { ICustomizationMigrationService } from '../../common/promptSyntax/service/customizationMigrationService.js'; +import { getIgnoredCustomizationMigrationGroups } from './customizationMigrationIgnoredGroups.js'; +import { getChatSessionType } from '../../common/model/chatUri.js'; +import { ChatCustomizationsLocation } from '../../common/customizationsLocation.js'; +import { ChatCustomizationsTelemetry, CustomizationsHoverTarget } from './chatCustomizationsTelemetry.js'; +import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { openLinkFromMarkdown } from '../../../../../platform/markdown/browser/markdownRenderer.js'; + +const hoverCommands = [AICustomizationManagementCommands.OpenEditor, McpCommandIds.AuthenticateAgentHostServer, 'workbench.action.openSettings']; + +export class ChatCustomizationsHover { + private readonly telemetry: ChatCustomizationsTelemetry; + private readonly linkTargets = new Map(); + private hoverToken: CancellationToken | undefined; + private shownToken: CancellationToken | undefined; + + constructor( + @IAICustomizationItemsModel private readonly itemsModel: IAICustomizationItemsModel, + @ICustomizationHarnessService private readonly harnessService: ICustomizationHarnessService, + @IAICustomizationWorkspaceService private readonly workspaceService: IAICustomizationWorkspaceService, + @IMcpService private readonly mcpService: IMcpService, + @IAgentHostCustomizationService private readonly agentHostCustomizationService: IAgentHostCustomizationService, + @IChatWidgetService private readonly chatWidgetService: IChatWidgetService, + @ICustomizationMigrationService private readonly migrationService: ICustomizationMigrationService, + @IStorageService private readonly storageService: IStorageService, + @IInstantiationService instantiationService: IInstantiationService, + @IOpenerService private readonly openerService: IOpenerService, + ) { + this.telemetry = instantiationService.createInstance(ChatCustomizationsTelemetry); + } + + logButtonClicked(location: Exclude): void { + this.telemetry.logInteraction('buttonClicked', location); + } + + getHoverOptions(location: Exclude): IManagedHoverOptions { + return { + trapFocus: true, + additionalClasses: ['chat-customizations-hover'], + onDidShow: () => { + // Loading and its resolved content are one managed hover request. + if (this.hoverToken && !this.hoverToken.isCancellationRequested && this.shownToken !== this.hoverToken) { + this.shownToken = this.hoverToken; + this.telemetry.logInteraction('hoverShown', location); + } + }, + linkHandler: url => { + const target = this.linkTargets.get(url); + if (target) { + this.telemetry.logInteraction('hoverInteracted', location, target); + } + void openLinkFromMarkdown(this.openerService, url, { enabledCommands: hoverCommands }); + }, + }; + } + + getSessionResource(context?: unknown, reader?: IReader): URI { + const active = this.harnessService.activeSessionResource.read(reader); + if (isObject(context)) { + const widgetContext: unknown = Reflect.get(context, 'widget'); + if (widgetContext) { + const widget = this.chatWidgetService.getAllWidgets().find(widget => widget === widgetContext); + if (widget?.input.pendingDelegationTarget) { + return this.harnessService.getSessionResourceForHarness(widget.input.pendingDelegationTarget); + } + if (widget?.viewModel) { + return widget.viewModel.sessionResource; + } + } + const sessionResource: unknown = Reflect.get(context, 'sessionResource'); + if (URI.isUri(sessionResource)) { + return sessionResource; + } + const resource: unknown = Reflect.get(context, 'resource'); + if (URI.isUri(resource)) { + return resource; + } + } + return active; + } + + getProjectRoot(sessionResource: URI, reader?: IReader): URI | undefined { + return isEqual(sessionResource, this.harnessService.activeSessionResource.read(reader)) + ? this.workspaceService.activeProjectRoot.read(reader) + : this.agentHostCustomizationService.getClientWorkingDirectoryUris(sessionResource)[0]; + } + + getManagedContent(note?: string, context?: () => unknown): IManagedHoverTooltipMarkdownString { + return { + markdown: token => { + this.hoverToken = token; + return this.getContent(token, context?.(), note); + }, + markdownNotSupportedFallback: note ?? localize('customizationsHover.title', "Session Customizations"), + }; + } + + async getContent(token: CancellationToken, context?: unknown, note?: string): Promise { + const sessionResource = this.getSessionResource(context); + const active = isEqual(sessionResource, this.harnessService.activeSessionResource.get()); + const descriptor = active ? this.harnessService.getActiveDescriptor() : this.harnessService.getDescriptorForSession(sessionResource); + if (!descriptor) { + return new MarkdownString().appendText(localize('customizationsHover.loading', "Customizations are still loading.")); + } + const scope = active ? undefined : this.itemsModel.createSessionModel(sessionResource); + try { + const itemsModel = scope?.model ?? this.itemsModel; + const hidden = new Set(descriptor.hiddenSections); + const sections = [AICustomizationManagementSection.Plugins, AICustomizationManagementSection.Skills, AICustomizationManagementSection.Instructions, AICustomizationManagementSection.Hooks] + .filter(section => !hidden.has(section)); + const ignoredGroups = getIgnoredCustomizationMigrationGroups(this.storageService, getChatSessionType(sessionResource), this.getProjectRoot(sessionResource)); + const discovery = await raceCancellation(Promise.all([ + this.migrationService.computeMigrationHint(sessionResource, token, ignoredGroups), + Promise.all(sections.map(section => itemsModel.whenSectionLoaded(section))), + ]), token); + if (!discovery || token.isCancellationRequested) { + return undefined; + } + if (!isEqual(sessionResource, this.getSessionResource(context))) { + return this.getContent(token, context, note); + } + const [migrationHint] = discovery; + const migrationCount = migrationHint?.counts.reduce((total, entry) => total + entry.count, 0) ?? 0; + const linkTargets = new Map(); + const commandLink = (target: { readonly section?: AICustomizationManagementSection; readonly migration?: boolean; readonly showDiscover?: boolean }, telemetryTarget: CustomizationsHoverTarget) => { + const link = `command:${AICustomizationManagementCommands.OpenEditor}?${encodeURIComponent(JSON.stringify([{ ...target, sessionResource, ...(target.migration ? { migrationHint } : {}) }]))}`; + linkTargets.set(link, telemetryTarget); + return link; + }; + const content = new MarkdownString('', { supportThemeIcons: true, supportHtml: true, isTrusted: { enabledCommands: hoverCommands } }); + content.appendMarkdown(`**${localize('customizationsHover.title', "Session Customizations")}**\n\n`); + const projectRoot = this.getProjectRoot(sessionResource); + const projectLabel = active ? this.workspaceService.activeProjectLabel.get() : projectRoot ? basename(projectRoot) : undefined; + content.appendText(projectLabel + ? localize('customizationsHover.context', "{0} \u00b7 {1}", descriptor.label, projectLabel) + : descriptor.label); + content.appendMarkdown('\n\n'); + let hasSections = false; + const appendSection = (section: AICustomizationManagementSection & CustomizationsHoverTarget, icon: ThemeIcon, label: string, count: () => number) => { + if (!hidden.has(section)) { + if (!hasSections) { + content.appendMarkdown(`| ${localize('customizationsHover.type', "Type")} | ${localize('customizationsHover.available', "Available")} |\n| :--- | ---: |\n`); + hasSections = true; + } + content.appendMarkdown('| '); + content.appendLink(commandLink({ section }, section), `$(${icon.id})${label}`); + content.appendMarkdown(` | ${count()} |\n`); + } + }; + appendSection(AICustomizationManagementSection.Plugins, pluginIcon, localize('customizationsHover.plugins', "Plugins"), () => itemsModel.getPluginCount().get()); + let authRequiredServers: readonly AgentHostMcpServer[] = []; + if (!hidden.has(AICustomizationManagementSection.McpServers)) { + const counts = getEffectiveMcpServerCounts( + this.mcpService.servers.get(), + this.agentHostCustomizationService.getMcpServers(sessionResource), + undefined, + descriptor.hiddenMcpServerCollectionIds, + ); + authRequiredServers = counts.authRequiredServers; + appendSection(AICustomizationManagementSection.McpServers, mcpServerIcon, localize('customizationsHover.mcp', "MCP Servers"), () => counts.total); + } + appendSection(AICustomizationManagementSection.Skills, skillIcon, localize('customizationsHover.skills', "Skills"), () => itemsModel.getCount(AICustomizationManagementSection.Skills).get()); + appendSection(AICustomizationManagementSection.Instructions, instructionsIcon, localize('customizationsHover.instructions', "Instructions"), () => itemsModel.getCount(AICustomizationManagementSection.Instructions).get()); + appendSection(AICustomizationManagementSection.Hooks, hookIcon, localize('customizationsHover.hooks', "Hooks"), () => itemsModel.getCount(AICustomizationManagementSection.Hooks).get()); + if (migrationCount || authRequiredServers.length) { + content.appendMarkdown(`\n\n**${localize('customizationsHover.attention', "Needs attention")}**\n\n`); + if (migrationCount) { + content.appendMarkdown(`- $(${Codicon.warning.id}) `); + content.appendLink(commandLink({ migration: true }, 'migrations'), migrationCount === 1 + ? localize('customizationsHover.migrationSingle', "1 customization needs migration") + : localize('customizationsHover.migrationsCount', "{0} customizations need migration", migrationCount), + localize('customizationsHover.reviewMigrations', "Review Migrations")); + content.appendMarkdown('\n'); + } + if (authRequiredServers.length) { + content.appendMarkdown(`- $(${Codicon.key.id}) `); + const names = authRequiredServers.slice(0, 2).map(getMcpServerDisplayLabel).join(', '); + const serverNames = authRequiredServers.length > 2 + ? localize('customizationsHover.moreServers', "{0}, +{1} more", names, authRequiredServers.length - 2) + : names; + content.appendLink(commandLink({ section: AICustomizationManagementSection.McpServers }, 'mcpServers'), authRequiredServers.length === 1 + ? localize('customizationsHover.authenticationSingle', "1 MCP server requires sign-in") + : localize('customizationsHover.authentication', "{0} MCP servers require sign-in", authRequiredServers.length), + localize('customizationsHover.manageMcp', "Manage MCP Servers: {0}", serverNames)); + content.appendMarkdown(' *'); + for (const [index, server] of authRequiredServers.slice(0, 2).entries()) { + if (index > 0) { + content.appendMarkdown(', '); + } + const label = getMcpServerDisplayLabel(server); + const link = `command:${McpCommandIds.AuthenticateAgentHostServer}?${encodeURIComponent(JSON.stringify([sessionResource, server.id]))}`; + linkTargets.set(link, 'mcpAuthentication'); + content.appendLink( + link, + new MarkdownString().appendText(label).value, + localize('customizationsHover.signInToServer', "Sign In to {0}", label), + ); + } + if (authRequiredServers.length > 2) { + content.appendText(localize('customizationsHover.remainingServers', ", +{0} more", authRequiredServers.length - 2)); + } + content.appendMarkdown('*\n'); + } + } + if (note && !migrationCount) { + content.appendMarkdown('\n\n'); + content.appendText(note); + } + content.appendMarkdown('\n\n---\n\n'); + content.appendLink(commandLink({ showDiscover: true }, 'browseAdditional'), `$(${Codicon.add.id})${localize('customizationsHover.browseAdditional', "Browse Additional")}`); + content.appendMarkdown(' '); + const locationLabel = localize('customizationsHover.location', "Change Button Location..."); + const gearLabel = new MarkdownString(); + gearLabel.appendMarkdown(`$(${Codicon.settingsGear.id})`); + gearLabel.appendText(locationLabel); + gearLabel.appendMarkdown(''); + const settingsLink = `command:workbench.action.openSettings?${encodeURIComponent(JSON.stringify([ChatConfiguration.ChatCustomizationsLocation]))}`; + linkTargets.set(settingsLink, 'locationSetting'); + content.appendLink(settingsLink, gearLabel.value, locationLabel); + this.linkTargets.clear(); + for (const [link, target] of linkTargets) { + this.linkTargets.set(link, target); + } + return content; + } finally { + scope?.dispose(); + } + } +} + +export class ChatCustomizationsActionViewItem extends MenuEntryActionViewItem { + private readonly contextChanged = observableSignal(this); + private readonly migrationAvailable: IObservable; + + constructor( + action: MenuItemAction, + options: IMenuEntryActionViewItemOptions | undefined, + private readonly hover: ChatCustomizationsHover, + private readonly location: Exclude, + migrationAvailable: IObservable | undefined, + private readonly showLabel = false, + private readonly extensionSuggestions: IObservable = constObservable(false), + @IKeybindingService keybindingService: IKeybindingService, + @INotificationService notificationService: INotificationService, + @IContextKeyService contextKeyService: IContextKeyService, + @IThemeService themeService: IThemeService, + @IContextMenuService contextMenuService: IContextMenuService, + @IAccessibilityService accessibilityService: IAccessibilityService, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(action, options, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, accessibilityService); + this.options.label = showLabel; + this.migrationAvailable = migrationAvailable ?? this._register(instantiationService.createInstance(CustomizationMigrationState, derived(this, reader => { + this.contextChanged.read(reader); + const sessionResource = this.hover.getSessionResource(this._context, reader); + return { sessionResource, projectRoot: this.hover.getProjectRoot(sessionResource, reader) }; + }))).available; + } + + override setActionContext(context: unknown): void { + super.setActionContext(context); + this.contextChanged.trigger(undefined); + } + + override render(container: HTMLElement): void { + super.render(container); + this._register(this.actionRunner.onWillRun(event => { + if (event.action === this.action) { + this.hover.logButtonClicked(this.location); + } + })); + container.classList.add('chat-customizations-action-item'); + if (this.showLabel) { + container.classList.add('customization-link-widget'); + this.label?.classList.add('monaco-button', 'monaco-text-button', 'sidebar-action-button'); + } + this._register(autorun(reader => { + container.classList.toggle('migration-available', this.migrationAvailable.read(reader) || this.extensionSuggestions.read(reader)); + this.updateTooltip(); + })); + } + + protected override updateLabel(): void { + if (this.showLabel && this.label) { + reset(this.label, ...renderLabelWithIcons(`$(${Codicon.extensions.id}) ${this._commandAction.label}`)); + } else { + super.updateLabel(); + } + } + + protected override getTooltip(): string { + return this.migrationAvailable.get() + ? localize('customizationsHover.migrationsLabel', "{0} (Migrations Available)", super.getTooltip()) + : this.extensionSuggestions.get() + ? localize('customizationsHover.extensionsLabel', "{0} (Extension Suggestions Available)", super.getTooltip()) + : super.getTooltip(); + } + + protected override getHoverContents(): IManagedHoverContent { + return this.hover.getManagedContent(this.migrationAvailable.get() + ? localize('customizationsHover.migrations', "Some customizations need an update to keep working.") + : this.extensionSuggestions.get() + ? localize('customizationsHover.extensions', "Some installed extensions can be enabled in the Agents window.") + : undefined, () => this._context); + } + + protected override getHoverOptions(): IManagedHoverOptions { + return this.hover.getHoverOptions(this.location); + } + +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsTelemetry.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsTelemetry.ts new file mode 100644 index 000000000000..1e15557a57f2 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/chatCustomizationsTelemetry.ts @@ -0,0 +1,101 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IDisposable } from '../../../../../base/common/lifecycle.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { ChatConfiguration } from '../../common/constants.js'; +import { ChatCustomizationsLocation } from '../../common/customizationsLocation.js'; + +type CustomizationsLocation = ChatCustomizationsLocation | 'unknown'; +type CustomizationsInteraction = 'buttonClicked' | 'hoverShown' | 'hoverInteracted'; +export type CustomizationsHoverTarget = 'plugins' | 'mcpServers' | 'skills' | 'instructions' | 'hooks' | 'migrations' | 'mcpAuthentication' | 'browseAdditional' | 'locationSetting'; + +type CustomizationsInteractionEvent = { + action: CustomizationsInteraction; + location: Exclude; + configuredLocation: CustomizationsLocation; + windowKind: 'agents' | 'editor'; + target: CustomizationsHoverTarget | 'none'; +}; + +type CustomizationsInteractionClassification = { + owner: 'aeschli'; + comment: 'Tracks Customizations entry-point activations, visible hovers, and hover link activations without collecting link arguments or customization content.'; + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the entry point was activated, its hover shown, or a hover link activated.' }; + location: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The code-defined placement of the invoking entry point.' }; + configuredLocation: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The bounded effective value of the Customizations location setting, including auto or unknown.' }; + windowKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the entry point belongs to the Agents window or editor window.' }; + target: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The code-defined hover action category, or none for button activation and hover display.' }; +}; + +type CustomizationsLocationChangedEvent = { + previousLocation: CustomizationsLocation; + location: CustomizationsLocation; + windowKind: 'agents' | 'editor'; +}; + +type CustomizationsLocationChangedClassification = { + owner: 'aeschli'; + comment: 'Tracks changes to the Customizations location setting in user or application configuration, excluding default and experiment assignment changes.'; + previousLocation: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The previous bounded value of the Customizations location setting.' }; + location: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The new bounded value of the Customizations location setting.' }; + windowKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the change was observed in the Agents window or editor window.' }; +}; + +export class ChatCustomizationsTelemetry { + constructor( + @IConfigurationService private readonly configurationService: IConfigurationService, + @ITelemetryService private readonly telemetryService: ITelemetryService, + @IAICustomizationWorkspaceService private readonly workspaceService: IAICustomizationWorkspaceService, + ) { } + + logInteraction(action: CustomizationsInteraction, location: Exclude, target: CustomizationsHoverTarget | 'none' = 'none'): void { + this.telemetryService.publicLog2('chatCustomizationEntryPoint.interaction', { + action, + location, + configuredLocation: this.getConfiguredLocation(), + windowKind: this.workspaceService.isSessionsWindow ? 'agents' : 'editor', + target, + }); + } + + observeLocationChanges(): IDisposable { + let previousLocation = this.getConfiguredLocation(); + return this.configurationService.onDidChangeConfiguration(event => { + if (!event.affectsConfiguration(ChatConfiguration.ChatCustomizationsLocation)) { + return; + } + const location = this.getConfiguredLocation(); + const previous = previousLocation; + previousLocation = location; + if (previous === location || ![ + ConfigurationTarget.APPLICATION, ConfigurationTarget.USER, ConfigurationTarget.USER_LOCAL, ConfigurationTarget.USER_REMOTE, + ].includes(event.source)) { + return; + } + this.telemetryService.publicLog2('chatCustomizationEntryPoint.locationChanged', { + previousLocation: previous, + location, + windowKind: this.workspaceService.isSessionsWindow ? 'agents' : 'editor', + }); + }); + } + + private getConfiguredLocation(): CustomizationsLocation { + const location = this.configurationService.getValue(ChatConfiguration.ChatCustomizationsLocation); + switch (location) { + case 'auto': + case 'sidebar': + case 'sessionsHeader': + case 'chatToolbar': + case 'chatInput': + return location; + default: + return 'unknown'; + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationCardList.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationCardList.ts index d9f2861468d5..e766a595ade3 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationCardList.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationCardList.ts @@ -22,13 +22,18 @@ export interface ICustomizationCardListItem { readonly contextMenuAction?: HTMLElement; } +/** + * Focuses the first visible item unless a visible entry is already focused, + * for example when focus was kept on an entry inside a collapsed group. + */ export function focusFirstCustomizationTreeItem( list: { getFocus(): readonly (T | null)[]; setFocus(elements: T[]): void }, entries: readonly T[], isItem: (entry: T) => boolean, + isVisible: (entry: T) => boolean = () => true, ): void { - if (list.getFocus().length === 0) { - const firstItem = entries.find(isItem) ?? entries[0]; + if (!list.getFocus().some(entry => entry !== null && isVisible(entry))) { + const firstItem = entries.find(entry => isItem(entry) && isVisible(entry)) ?? entries[0]; if (firstItem) { list.setFocus([firstItem]); } diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceInstallService.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceInstallService.ts index 06044c30005e..037b72c35b65 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceInstallService.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceInstallService.ts @@ -15,12 +15,11 @@ import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { normalizePluginPath, PLUGIN_MANIFEST_PATHS } from '../../../../../platform/agentPlugins/common/pluginParsers.js'; import { CustomizationMarketplaceInstallation, CustomizationMarketplaceMediaType, getCustomizationMarketplaceResourceKey, ICustomizationMarketplaceResource, ICustomizationMarketplaceService, isCustomizationMarketplaceIconEqual } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; -import { normalizeMcpGalleryUrl } from '../../../../../platform/customizationMarketplace/common/mcpGalleryMarketplaceProvider.js'; import { affectsCustomizationMarketplaceSources, CustomizationMarketplaceConfiguration, CustomizationMarketplaceSources, getVisibleCustomizationMarketplaceSources } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../platform/files/common/files.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; -import { mcpGalleryServiceUrlConfig } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { mcpGalleryServiceUrlConfig, normalizeMcpGalleryUrl } from '../../../../../platform/mcp/common/mcpManagement.js'; import { IMcpGalleryManifest, IMcpGalleryManifestService } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { IStorageService } from '../../../../../platform/storage/common/storage.js'; diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceWorkbenchService.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceWorkbenchService.ts index 559e8d75d6ed..b2e5cf563c0f 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceWorkbenchService.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMarketplaceWorkbenchService.ts @@ -22,6 +22,7 @@ import { createMcpGalleryMarketplaceProviders, getAllMcpGalleryMarketplaceSource import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { IMcpGalleryManifestService } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; import { ChatConfiguration } from '../../common/constants.js'; @@ -141,13 +142,14 @@ export class PlatformCustomizationMarketplaceWorkbenchService implements ICustom declare readonly _serviceBrand: undefined; readonly allSources = getAllMcpGalleryMarketplaceSourceInfos(); readonly onDidChangeSources: Event; - get sources() { return getCustomizationMarketplaceSourceInfos(this.mcpGalleryManifestService.mcpGalleryManifestStatus); } + get sources() { return getCustomizationMarketplaceSourceInfos(this.mcpGalleryManifestService.mcpGalleryManifestStatus, this.configurationService, this.productService); } private readonly service: Lazy; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IMcpGalleryManifestService private readonly mcpGalleryManifestService: IMcpGalleryManifestService, + @IProductService private readonly productService: IProductService, ) { this.onDidChangeSources = Event.map(mcpGalleryManifestService.onDidChangeMcpGalleryManifestStatus, () => ({ sourceIds: this.allSources.map(source => source.id) })); void mcpGalleryManifestService.getMcpGalleryManifest(); diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationState.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationState.ts new file mode 100644 index 000000000000..9667a425f2d9 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationState.ts @@ -0,0 +1,70 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { cancelOnDispose } from '../../../../../base/common/cancellation.js'; +import { Event } from '../../../../../base/common/event.js'; +import { isCancellationError } from '../../../../../base/common/errors.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, IObservable, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { IStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; +import { getChatSessionType } from '../../common/model/chatUri.js'; +import { ICustomizationMigrationService } from '../../common/promptSyntax/service/customizationMigrationService.js'; +import { getCustomizationMigrationCategory, homepageMigrationCategories } from './customizationMigrationCategories.js'; +import { CUSTOMIZATION_MIGRATION_IGNORED_GROUPS_STORAGE_KEY, getIgnoredCustomizationMigrationGroups } from './customizationMigrationIgnoredGroups.js'; + +interface ICustomizationMigrationContext { + readonly sessionResource: URI; + readonly projectRoot: URI | undefined; +} + +export class CustomizationMigrationState extends Disposable { + private readonly availableValue = observableValue(this, false); + readonly available: IObservable = this.availableValue; + + constructor( + context: IObservable, + @ICustomizationMigrationService migrationService: ICustomizationMigrationService, + @IConfigurationService configurationService: IConfigurationService, + @IStorageService storageService: IStorageService, + @ILogService logService: ILogService, + ) { + super(); + const categories = homepageMigrationCategories.map(getCustomizationMigrationCategory); + const configurationChanged = observableSignalFromEvent(this, Event.filter(configurationService.onDidChangeConfiguration, event => + categories.some(category => event.affectsConfiguration(category.enablementSetting)))); + const customizationsChanged = observableSignalFromEvent(this, migrationService.onDidChangeCustomizations); + const ignoredGroupsChanged = observableSignalFromEvent(this, Event.filter( + storageService.onDidChangeValue(StorageScope.PROFILE, undefined, this._store), + event => event.key === CUSTOMIZATION_MIGRATION_IGNORED_GROUPS_STORAGE_KEY, + )); + this._register(autorun(reader => { + const current = context.read(reader); + configurationChanged.read(reader); + customizationsChanged.read(reader); + ignoredGroupsChanged.read(reader); + if (!current) { + this.availableValue.set(false, undefined); + return; + } + const ignored = getIgnoredCustomizationMigrationGroups(storageService, getChatSessionType(current.sessionResource), current.projectRoot); + const token = cancelOnDispose(reader.store); + void migrationService.computeMigrationHint(current.sessionResource, token, ignored).then(hint => { + if (!token.isCancellationRequested) { + this.availableValue.set(hint !== undefined, undefined); + } + }, error => { + if (!isCancellationError(error)) { + logService.error('Failed to check customization migrations', error); + } + if (!token.isCancellationRequested) { + this.availableValue.set(false, undefined); + } + }); + })); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationOrganizationPolicy.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationOrganizationPolicy.ts new file mode 100644 index 000000000000..2cbfbe699da7 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationOrganizationPolicy.ts @@ -0,0 +1,186 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as DOM from '../../../../../base/browser/dom.js'; +import { IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; +import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Disposable, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize } from '../../../../../nls.js'; +import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { mcpAllowedServersConfig } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG, COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG, COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG, getManagedSupportUrl, IManagedSettingsService } from '../../../../../platform/policy/common/copilotManagedSettings.js'; +import { appendContactAdministratorLink } from '../../../../services/policies/browser/organizationSupportLink.js'; +import { AICustomizationManagementSection } from '../../common/aiCustomizationWorkspaceService.js'; +import { ICustomizationOrganizationControl } from '../../common/customizationHarnessService.js'; + +const $ = DOM.$; + +/** + * How an organization restricts the customizations of one section. + * - `pluginOnly`: only customizations supplied by plugins load. + * - `organizationOnly`: only customizations the organization supplies or approves load. + * - `allowlist`: only customizations the organization approved by name load. + */ +export type CustomizationOrganizationRestriction = 'pluginOnly' | 'organizationOnly' | 'allowlist'; + +const organizationRestrictionSettings = [ + COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG, + COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG, + COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG, + mcpAllowedServersConfig, +]; + +function affectsOrganizationRestriction(event: IConfigurationChangeEvent): boolean { + return organizationRestrictionSettings.some(setting => event.affectsConfiguration(setting)); +} + +/** + * The restriction an organization's managed policy places on `section`. + * Reads only policy values, so a user's own settings never claim to come from their organization. + * Customizations excluded by these settings are not listed, so the section explains their absence. + */ +export function getCustomizationOrganizationRestriction(configurationService: Pick, section: string): CustomizationOrganizationRestriction | undefined { + const policy = (key: string) => configurationService.inspect(key).policyValue; + const strictPluginOnly = policy(COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG) === true; + switch (section) { + case AICustomizationManagementSection.Skills: + case AICustomizationManagementSection.Agents: + case AICustomizationManagementSection.Instructions: + return strictPluginOnly ? 'pluginOnly' : undefined; + case AICustomizationManagementSection.Hooks: + if (policy(COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG) === true) { + return 'organizationOnly'; + } + return strictPluginOnly ? 'pluginOnly' : undefined; + case AICustomizationManagementSection.McpServers: + if (strictPluginOnly) { + return 'pluginOnly'; + } + if (policy(COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG) === true) { + return 'organizationOnly'; + } + return Array.isArray(policy(mcpAllowedServersConfig)) ? 'allowlist' : undefined; + } + return undefined; +} + +/** Explains an organization-managed customization, including any enablement it requires. */ +export function getOrganizationManagedTooltip(control: ICustomizationOrganizationControl): string { + switch (control.requiredEnabled) { + case true: + return localize('organizationManagedEnabled', "Managed by your organization. It is always enabled and can't be disabled."); + case false: + return localize('organizationManagedDisabled', "Managed by your organization. It is disabled and can't be enabled."); + default: + return localize('organizationManaged', "Managed by your organization."); + } +} + +/** Appends the organization-managed explanation to a row's accessible label, so screen readers hear what the tag shows. */ +export function withOrganizationManagedAriaLabel(label: string, control: ICustomizationOrganizationControl | undefined): string { + return control ? localize('organizationManagedAriaLabel', "{0}. {1}", label, getOrganizationManagedTooltip(control)) : label; +} + +/** The "Managed by your organization" tag shown next to the name of an organization-managed customization. */ +export class OrganizationManagedTag extends Disposable { + + private readonly element: HTMLElement; + private readonly hover: IManagedHover; + + constructor(container: HTMLElement, hoverService: IHoverService) { + super(); + this.element = DOM.append(container, $('.inline-badge.organization-managed-tag')); + DOM.append(this.element, $(`span${ThemeIcon.asCSSSelector(Codicon.shield)}`, { 'aria-hidden': 'true' })); + DOM.append(this.element, $('span')).textContent = localize('organizationManagedTag', "Managed by your organization"); + this.hover = this._register(hoverService.setupManagedHover(getDefaultHoverDelegate('mouse'), this.element, '')); + this.update(undefined); + } + + /** Shows the tag for `control`, or hides it when the customization isn't organization managed. */ + update(control: ICustomizationOrganizationControl | undefined): void { + const tooltip = control ? getOrganizationManagedTooltip(control) : ''; + this.element.style.display = control ? '' : 'none'; + this.element.setAttribute('aria-label', tooltip); + this.hover.update(tooltip); + } +} + +function getRestrictionMessage(section: string, restriction: CustomizationOrganizationRestriction): string | undefined { + switch (section) { + case AICustomizationManagementSection.Skills: + return localize('organizationSkillsPluginOnly', "Your organization only allows skills from plugins. Other skills are hidden."); + case AICustomizationManagementSection.Agents: + return localize('organizationAgentsPluginOnly', "Your organization only allows agents from plugins. Other agents are hidden."); + case AICustomizationManagementSection.Instructions: + return localize('organizationInstructionsPluginOnly', "Your organization only allows instructions from plugins. Other instructions are hidden."); + case AICustomizationManagementSection.Hooks: + return restriction === 'organizationOnly' + ? localize('organizationHooksOrganizationOnly', "Your organization only allows hooks it provides. Other hooks are hidden.") + : localize('organizationHooksPluginOnly', "Your organization only allows hooks from plugins. Other hooks are hidden."); + case AICustomizationManagementSection.McpServers: + switch (restriction) { + case 'pluginOnly': return localize('organizationMcpPluginOnly', "Your organization only allows MCP servers from plugins to run."); + case 'organizationOnly': return localize('organizationMcpOrganizationOnly', "Your organization only allows MCP servers it provides or approves to run."); + case 'allowlist': return localize('organizationMcpAllowlist', "Your organization only allows approved MCP servers to run."); + } + } + return undefined; +} + +/** A notice explaining that the user's organization restricts which customizations of a section load. */ +export class CustomizationOrganizationPolicyNotice extends Disposable { + + readonly element: HTMLElement; + private readonly message: HTMLElement; + private readonly supportLink = this._register(new MutableDisposable()); + private section: string | undefined; + + constructor( + @IConfigurationService private readonly configurationService: IConfigurationService, + @IHoverService private readonly hoverService: IHoverService, + @IOpenerService private readonly openerService: IOpenerService, + @IManagedSettingsService private readonly managedSettingsService: IManagedSettingsService, + ) { + super(); + this.element = $('.organization-policy-notice', { role: 'note' }); + DOM.append(this.element, $(`.organization-policy-notice-icon${ThemeIcon.asCSSSelector(Codicon.shield)}`, { 'aria-hidden': 'true' })); + this.message = DOM.append(this.element, $('.organization-policy-notice-message')); + this.element.style.display = 'none'; + this._register(this.configurationService.onDidChangeConfiguration(e => { + if (affectsOrganizationRestriction(e)) { + this.render(); + } + })); + this._register(this.managedSettingsService.onDidChangeManagedSettings(() => this.render())); + } + + /** Shows the notice for `section`, or hides it when the organization doesn't restrict it. */ + setSection(section: string): void { + this.section = section; + this.render(); + } + + private render(): void { + const restriction = this.section ? getCustomizationOrganizationRestriction(this.configurationService, this.section) : undefined; + const text = this.section && restriction ? getRestrictionMessage(this.section, restriction) : undefined; + this.supportLink.clear(); + DOM.clearNode(this.message); + if (!text) { + this.element.style.display = 'none'; + return; + } + this.element.style.display = ''; + this.message.appendChild(document.createTextNode(text)); + const supportUrl = getManagedSupportUrl(this.managedSettingsService); + if (supportUrl) { + this.message.appendChild(document.createTextNode(' ')); + this.supportLink.value = appendContactAdministratorLink(this.message, 'section-title-link', supportUrl, this.openerService, this.hoverService); + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationTree.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationTree.ts index 86012d187362..81d479514ab1 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationTree.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationTree.ts @@ -42,6 +42,22 @@ export function getTreeNodeElement(node: ITreeNode): T { return node.element; } +/** + * Whether the entry has a row in the tree, that is, it is not inside a + * collapsed group. + */ +export function isCustomizationTreeEntryVisible(tree: { hasElement(element: T): boolean; getParentElement(element: T): T | null; isCollapsed(element: T): boolean }, entry: T): boolean { + if (!tree.hasElement(entry)) { + return false; + } + for (let parent = tree.getParentElement(entry); parent; parent = tree.getParentElement(parent)) { + if (tree.isCollapsed(parent)) { + return false; + } + } + return true; +} + export function getCustomizationTreeAriaLabel(label: string, count: number, collapsed: boolean): string { return localize( 'customizationTreeGroupAriaLabel', diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts index 79a5595ef965..b3d202855635 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts @@ -15,7 +15,7 @@ import { localize } from '../../../../../nls.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { IListRenderer, IListVirtualDelegate } from '../../../../../base/browser/ui/list/list.js'; import { RenderIndentGuides } from '../../../../../base/browser/ui/tree/abstractTree.js'; -import { IObjectTreeElement, ObjectTreeElementCollapseState } from '../../../../../base/browser/ui/tree/tree.js'; +import { IObjectTreeElement } from '../../../../../base/browser/ui/tree/tree.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Button } from '../../../../../base/browser/ui/button/button.js'; @@ -26,8 +26,8 @@ import { CustomizationMarketplaceIcon, ICustomizationMarketplaceService } from ' import { CustomizationMarketplaceConfiguration } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; -import { IQueryOptions, mcpAccessConfig, McpAccessValue } from '../../../../../platform/mcp/common/mcpManagement.js'; -import { IMcpGalleryManifestService } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; +import { getConfiguredCustomMcpGalleryUrl, IQueryOptions, isProductMcpGalleryEnabled, mcpAccessConfig, McpAccessValue, normalizeMcpGalleryUrl } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { IMcpGalleryManifest, IMcpGalleryManifestService } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; import { IMcpWorkbenchService, IWorkbenchMcpServer, McpCollectionDefinition, McpCollectionProvenance, McpConnectionState, McpServerDefinition, McpServerInstallState, IMcpService, IMcpServer, McpServerTransportType } from '../../../../contrib/mcp/common/mcpTypes.js'; import { IMcpRegistry } from '../../../mcp/common/mcpRegistryTypes.js'; import { MCP_PLUGIN_COLLECTION_ID_PREFIX } from '../../../mcp/common/discovery/pluginMcpDiscovery.js'; @@ -59,7 +59,8 @@ import { createInstantHoverDelegate, getDefaultHoverDelegate } from '../../../.. import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; -import { IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../common/aiCustomizationWorkspaceService.js'; +import { CustomizationOrganizationPolicyNotice } from './customizationOrganizationPolicy.js'; import { AgentPluginItemKind, IAgentPluginItem } from '../agentPluginEditor/agentPluginItems.js'; import { CustomizationMcpServerCompatibilityKind, getCustomizationDisabledLabel, ICustomizationHarnessService } from '../../common/customizationHarnessService.js'; import { getMcpServerDisplayLabel, IAgentHostCustomizationService } from '../agentSessions/agentHost/agentHostCustomizationService.js'; @@ -87,13 +88,14 @@ import { ActiveSessionMcpServerMatcher, type AgentHostMcpServer, getRuntimeServe import { getConnectorActionLabel } from './connectorPresentation.js'; import { ICopilotConnector, ICopilotConnectorsService, IConnectedCopilotConnectorMcpServer } from './copilotConnectorsService.js'; import { CustomizationGroupHeaderRenderer, CUSTOMIZATION_GROUP_HEADER_HEIGHT, CUSTOMIZATION_GROUP_HEADER_HEIGHT_WITH_SEPARATOR, getCustomizationGroupAriaLabel, ICustomizationGroupHeaderEntry } from './customizationGroupHeaderRenderer.js'; -import { asTreeRenderer, customizationTreeStyles, getCustomizationTreeContentHeight, ICustomizationTreeGroup } from './customizationTree.js'; +import { asTreeRenderer, customizationTreeStyles, getCustomizationTreeContentHeight, ICustomizationTreeGroup, isCustomizationTreeEntryVisible } from './customizationTree.js'; import { getCustomizationContributionSourceLabel } from './customizationContributionSource.js'; import { CustomizationToggle } from './customizationToggle.js'; import { affectsCustomizationDiscoveryAvailability, isCustomizationDiscoveryAvailable } from './customizationMarketplaceConfiguration.js'; import { renderCustomizationMarketplaceIcon } from './aiCustomizationPresentation.js'; import { findAICustomizationWorkspaceGroupContaining, getAICustomizationWorkspaceGroups, isAICustomizationWorkspaceGroupKey, isInAICustomizationWorkspaceFolder } from './aiCustomizationWorkspaceGroups.js'; import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; export type { AgentHostMcpServer } from './mcpServerCount.js'; @@ -1609,8 +1611,14 @@ export function shouldLoadMcpGallerySnapshot(visible: boolean, query: string, it return accessEnabled && visible && !query.trim() && itemCount === 0 && !failed && !loading; } -export function shouldShowLegacyMcpGallery(configurationService: IConfigurationService): boolean { - return configurationService.getValue(CustomizationMarketplaceConfiguration.MarketplaceEnabled) !== true; +export function shouldShowLegacyMcpGallery(configurationService: IConfigurationService, productService: IProductService): boolean { + return configurationService.getValue(CustomizationMarketplaceConfiguration.MarketplaceEnabled) !== true + && (isProductMcpGalleryEnabled(configurationService, productService) + || getConfiguredCustomMcpGalleryUrl(configurationService, productService) !== undefined); +} + +export function shouldRestartLegacyMcpGallerySearch(query: string, showLegacyGallery: boolean): boolean { + return showLegacyGallery && !!query.trim(); } export function hasSameMcpMembership(previous: string, current: string): boolean { @@ -1932,8 +1940,8 @@ function createConnectorMcpEntry(connector: IConnectedCopilotConnectorMcpServer, return { type: 'connector-item', id: `copilot-connector:${connector.id}`, - label: connector.serverName, - description: localize('mcpServerFromConnector', "Connector: {0}", connector.connector.displayName), + label: connector.connector.displayName, + description: localize('mcpServerFromConnector', "Connector"), activeSessionServer, connector, }; @@ -2092,6 +2100,8 @@ export class McpListWidget extends Disposable { private galleryServers: IWorkbenchMcpServer[] = []; private searchQuery: string = ''; private currentTreeGroups: readonly ICustomizationTreeGroup[] = []; + /** Groups the user collapsed, restored whenever the tree is re-rendered without a search. */ + private readonly collapsedGroups = new Set(); private gallerySnapshotFailed = false; private gallerySnapshotLoading = false; private gallerySearchLoading = false; @@ -2149,6 +2159,7 @@ export class McpListWidget extends Disposable { @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @IManagedSettingsService private readonly managedSettingsService: IManagedSettingsService, + @IProductService private readonly productService: IProductService, ) { super(); this.agentHostCustomizationsChanged = observableSignalFromEvent(this, this.agentHostCustomizationService.onDidChangeCustomizations); @@ -2182,7 +2193,7 @@ export class McpListWidget extends Disposable { void this.refresh(); } })); - if (!this.isGalleryDiscoveryEnabled()) { + if (this.shouldShowLegacyGallery()) { void mcpGalleryManifestService.getMcpGalleryManifest(); } void this.refresh(); @@ -2199,7 +2210,11 @@ export class McpListWidget extends Disposable { this.gallerySnapshotFailed = false; this.gallerySnapshotLoading = false; this.gallerySearchLoading = false; - void this.refresh(); + if (shouldRestartLegacyMcpGallerySearch(this.searchQuery, this.shouldShowLegacyGallery())) { + void this.queryMcpSearch(); + } else { + void this.refresh(); + } } if (e.affectsConfiguration(mcpAccessConfig)) { this.updateAccessState(); @@ -2282,6 +2297,9 @@ export class McpListWidget extends Disposable { })); this.discoveryMessage = DOM.append(this.sectionTitleHeader, $('p.section-title-description.mcp-discovery-message', { role: 'status' })); this.discoveryMessage.style.display = 'none'; + const organizationPolicyNotice = this._register(this.instantiationService.createInstance(CustomizationOrganizationPolicyNotice)); + this.sectionTitleHeader.appendChild(organizationPolicyNotice.element); + organizationPolicyNotice.setSection(AICustomizationManagementSection.McpServers); // Re-layout when the header height changes so the list's allotted // height stays in sync with the actual on-screen header size. Only @@ -2325,7 +2343,7 @@ export class McpListWidget extends Disposable { ? this.gallerySnapshotServers.filter(server => this.matchesGalleryServerQuery(server, query)) : [...this.gallerySnapshotServers]; this.delayedFilter.trigger(() => this.filterServers()); - if (!this.mcpAccessEnabled || this.isGalleryDiscoveryEnabled()) { + if (!this.mcpAccessEnabled || !this.shouldShowLegacyGallery()) { this.gallerySearchLoading = false; this.delayedGallerySearch.cancel(); return; @@ -2417,7 +2435,7 @@ export class McpListWidget extends Disposable { return getCustomizationGroupAriaLabel(entry.label, entry.count, entry.description); } return entry.type === 'connector-item' - ? localize('connectorMcpServerAriaLabel', "{0}. Connector: {1}.", entry.connector.serverName, entry.connector.connector.displayName) + ? localize('connectorMcpServerAriaLabel', "{0}. Connector.", entry.label) : entry.type === 'marketplace-item' ? localize('marketplaceMcpServerRowAriaLabel', "{0}. Available to install from the MCP marketplace.", entry.server.label) : this.getMcpEntryAriaLabel(entry); @@ -2452,8 +2470,18 @@ export class McpListWidget extends Disposable { itemRenderer.setFocusedRowKey(entry && entry.type !== 'group-header' && entry.type !== 'marketplace-item' ? getMcpRowKey(entry) : undefined); marketplaceRenderer.setFocusedServerId(entry?.type === 'marketplace-item' ? entry.server.id : undefined); })); + this._register(this.list.onDidChangeCollapseState(event => { + const entry = event.node.element; + if (entry?.type === 'group-header' && !this.searchQuery.trim()) { + if (event.node.collapsed) { + this.collapsedGroups.add(entry.group); + } else { + this.collapsedGroups.delete(entry.group); + } + } + })); this._register(this.list.onDidFocus(() => { - focusFirstCustomizationTreeItem(this.list, this.getVisibleMcpEntries(), entry => entry.type !== 'group-header'); + focusFirstCustomizationTreeItem(this.list, this.getVisibleMcpEntries(), entry => entry.type !== 'group-header', entry => isCustomizationTreeEntryVisible(this.list, entry)); })); // Listen to MCP service changes @@ -2489,7 +2517,7 @@ export class McpListWidget extends Disposable { private async refresh(): Promise { this.updateDiscoveryMessage(); this.filterServers(); - if (!this.isGalleryDiscoveryEnabled() && shouldLoadMcpGallerySnapshot(this.visible, this.searchQuery, this.gallerySnapshotServers.length, this.gallerySnapshotFailed, this.gallerySnapshotLoading, this.mcpAccessEnabled)) { + if (this.shouldShowLegacyGallery() && shouldLoadMcpGallerySnapshot(this.visible, this.searchQuery, this.gallerySnapshotServers.length, this.gallerySnapshotFailed, this.gallerySnapshotLoading, this.mcpAccessEnabled)) { await this.queryGallerySnapshot(); } } @@ -2548,7 +2576,11 @@ export class McpListWidget extends Disposable { } private isGalleryDiscoveryEnabled(): boolean { - return !shouldShowLegacyMcpGallery(this.configurationService); + return this.configurationService.getValue(CustomizationMarketplaceConfiguration.MarketplaceEnabled) === true; + } + + private shouldShowLegacyGallery(): boolean { + return shouldShowLegacyMcpGallery(this.configurationService, this.productService); } setVisible(visible: boolean): void { @@ -2668,7 +2700,7 @@ export class McpListWidget extends Disposable { } } } else if (accessChanged && this.visible) { - if (this.searchQuery.trim() && !this.isGalleryDiscoveryEnabled()) { + if (this.searchQuery.trim() && this.shouldShowLegacyGallery()) { void this.queryMcpSearch(); } else { void this.refresh(); @@ -2680,7 +2712,7 @@ export class McpListWidget extends Disposable { } public showBrowseMarketplace(): void { - if (this.isGalleryDiscoveryEnabled()) { + if (!this.shouldShowLegacyGallery()) { return; } if (!this.mcpAccessEnabled) { @@ -2692,12 +2724,18 @@ export class McpListWidget extends Disposable { } private async queryLegacyGallery(options: IQueryOptions | undefined, token: CancellationToken): Promise { + const customGalleryUrl = getConfiguredCustomMcpGalleryUrl(this.configurationService, this.productService); + const defaultGalleryEnabled = isProductMcpGalleryEnabled(this.configurationService, this.productService); const [active, fallback] = await Promise.all([ - this.mcpGalleryManifestService.getMcpGalleryManifest(), - this.mcpGalleryManifestService.getDefaultMcpGalleryManifest(), + customGalleryUrl ? this.mcpGalleryManifestService.getMcpGalleryManifest() : Promise.resolve(null), + defaultGalleryEnabled ? this.mcpGalleryManifestService.getDefaultMcpGalleryManifest() : Promise.resolve(null), ]); - const manifests = active && fallback && active.url !== fallback.url ? [active, fallback] : [active ?? fallback ?? undefined]; - const pages = await Promise.allSettled((manifests[0] ? manifests : [undefined]).map(async manifest => + const manifests = [ + active && normalizeMcpGalleryUrl(active.url) === customGalleryUrl ? active : null, + fallback, + ].filter((manifest): manifest is IMcpGalleryManifest => manifest !== null) + .filter((manifest, index, manifests) => manifests.findIndex(candidate => candidate.url === manifest.url) === index); + const pages = await Promise.allSettled(manifests.map(async manifest => (await this.mcpWorkbenchService.queryGallery(options, token, manifest)).firstPage.items)); if (pages.length && pages.every(page => page.status === 'rejected')) { throw pages[0].reason; @@ -2706,7 +2744,7 @@ export class McpListWidget extends Disposable { } private async queryGallerySnapshot(revealMarketplace = false): Promise { - if (!this.mcpAccessEnabled || this.isGalleryDiscoveryEnabled()) { + if (!this.mcpAccessEnabled || !this.shouldShowLegacyGallery()) { return; } this.galleryCts?.dispose(true); @@ -2750,7 +2788,7 @@ export class McpListWidget extends Disposable { private async queryMcpSearch(): Promise { const query = this.searchQuery.trim(); - if (!query || !this.mcpAccessEnabled || this.isGalleryDiscoveryEnabled()) { + if (!query || !this.mcpAccessEnabled || !this.shouldShowLegacyGallery()) { return; } @@ -3002,7 +3040,7 @@ export class McpListWidget extends Disposable { installedKeys.add(key.toLowerCase()); } } else if (entry.type === 'builtin-item' || entry.type === 'connector-item') { - installedKeys.add(entry.label.toLowerCase()); + installedKeys.add((entry.type === 'connector-item' ? entry.connector.serverName : entry.label).toLowerCase()); if (entry.localServer) { for (const key of getRuntimeServerMatchKeys(entry.localServer)) { installedKeys.add(key.toLowerCase()); @@ -3030,7 +3068,7 @@ export class McpListWidget extends Disposable { return; } - const showGallery = !this.isGalleryDiscoveryEnabled(); + const showGallery = this.shouldShowLegacyGallery(); const allInstalledEntries = this.installedEntries.map(presentation => presentation.entry); const workspaceGroups = getAICustomizationWorkspaceGroups(this.workspaceContextService); const grouped = new Map([ @@ -3091,13 +3129,13 @@ export class McpListWidget extends Disposable { this.cardScrollableNode.style.display = 'none'; this.cardDisposables.clear(); + const isFiltering = !!this.searchQuery.trim(); const children: IObjectTreeElement[] = this.currentTreeGroups.map(group => ({ element: group.element, collapsible: true, - collapsed: ObjectTreeElementCollapseState.PreserveOrExpanded, + collapsed: !isFiltering && this.collapsedGroups.has(group.id), children: group.children.map(element => ({ element })), })); - this.list.setChildren(null); this.list.setChildren(null, children); this.updateMcpTreeEmptyState(this.currentTreeGroups.reduce((count, group) => count + group.count, 0)); } @@ -3777,7 +3815,7 @@ export class McpListWidget extends Disposable { case 'builtin-item': return entry.label === serverName; case 'connector-item': - return entry.label === serverName || entry.connector.connector.displayName === serverName; + return entry.connector.serverName === serverName || entry.connector.connector.displayName === serverName; case 'provider-item': return entry.name === serverName || entry.label === serverName; case 'group-header': @@ -3802,7 +3840,8 @@ export class McpListWidget extends Disposable { * Focuses the list. */ focus(): void { - const firstItem = this.getVisibleMcpEntries().find(entry => entry.type !== 'group-header'); + const entries = this.getVisibleMcpEntries(); + const firstItem = entries.find(entry => entry.type !== 'group-header' && isCustomizationTreeEntryVisible(this.list, entry)) ?? entries[0]; if (firstItem) { this.list.setFocus([firstItem]); this.list.domFocus(); diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpServerCount.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpServerCount.ts index f8d38445fb3d..301a39de11ad 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpServerCount.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpServerCount.ts @@ -6,6 +6,7 @@ import { IReader } from '../../../../../base/common/observable.js'; import { getCustomizationScopeEnablement, type CustomizationDisabledReason } from '../../../../../platform/agentHost/common/customizationEnablement.js'; import { isContributionEnabled } from '../../common/enablement.js'; +import { McpServerStatus } from '../../../../../platform/agentHost/common/state/protocol/state.js'; import { customizationSearchMatchesAny } from '../../common/aiCustomizationSearch.js'; import { IAgentHostCustomizationService } from '../agentSessions/agentHost/agentHostCustomizationService.js'; import { IMcpServer } from '../../../mcp/common/mcpTypes.js'; @@ -84,18 +85,30 @@ export function isMcpServerInUse(primaryEnabled: boolean, activeSessionServer: A export function getEffectiveMcpServerCount( localServers: readonly IMcpServer[], activeSessionServers: readonly AgentHostMcpServer[], - reader: IReader, + reader: IReader | undefined, hiddenCollectionIds: readonly string[] | undefined, ): number { + return getEffectiveMcpServerCounts(localServers, activeSessionServers, reader, hiddenCollectionIds).total; +} + +export function getEffectiveMcpServerCounts( + localServers: readonly IMcpServer[], + activeSessionServers: readonly AgentHostMcpServer[], + reader: IReader | undefined, + hiddenCollectionIds: readonly string[] | undefined, +): { total: number; authRequired: number; authRequiredServers: readonly AgentHostMcpServer[] } { if (activeSessionServers.length === 0) { - return localServers.filter(server => - !hiddenCollectionIds?.includes(server.collection.id) - && isContributionEnabled(server.enablement.read(reader)) - ).length; + return { + total: localServers.filter(server => + !hiddenCollectionIds?.includes(server.collection.id) + && isContributionEnabled(server.enablement.read(reader)) + ).length, authRequired: 0, authRequiredServers: [] + }; } const activeSessionMatcher = new ActiveSessionMcpServerMatcher(activeSessionServers); let count = 0; + const authRequiredServers: AgentHostMcpServer[] = []; for (const localServer of localServers) { if (hiddenCollectionIds?.includes(localServer.collection.id)) { continue; @@ -106,14 +119,20 @@ export function getEffectiveMcpServerCount( : isContributionEnabled(localServer.enablement.read(reader)); if (isMcpServerInUse(primaryEnabled, activeSessionServer)) { count++; + if (activeSessionServer?.status === McpServerStatus.AuthRequired && !activeSessionServer.authenticating) { + authRequiredServers.push(activeSessionServer); + } } } for (const activeSessionServer of activeSessionMatcher.unmatched('')) { if (isMcpServerInUse(getCustomizationScopeEnablement(activeSessionServer).global, activeSessionServer)) { count++; + if (activeSessionServer.status === McpServerStatus.AuthRequired && !activeSessionServer.authenticating) { + authRequiredServers.push(activeSessionServer); + } } } - return count; + return { total: count, authRequired: authRequiredServers.length, authRequiredServers }; } function isHostOwnedPluginMcpServer(server: { diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/media/aiCustomizationManagement.css b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/aiCustomizationManagement.css index 88583bbe989e..26357f135478 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/media/aiCustomizationManagement.css +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/aiCustomizationManagement.css @@ -828,6 +828,43 @@ per-word capitalization does not survive translation. */ line-height: 16px; } +/* "Managed by your organization" tag for customizations controlled by the user's organization */ +.inline-badge.organization-managed-tag { + display: inline-flex; + align-items: center; + gap: var(--vscode-spacing-size20); +} + +.inline-badge.organization-managed-tag .codicon { + font-size: var(--vscode-codiconFontSize-compact); +} + +/* Notice explaining an organization restriction on a whole section */ +.organization-policy-notice { + display: flex; + align-items: flex-start; + gap: var(--vscode-spacing-size80); + margin: 0 0 var(--vscode-spacing-size80) 0; + padding: var(--vscode-spacing-size60) var(--vscode-spacing-size80); + border-radius: var(--vscode-cornerRadius-medium); + border: 1px solid var(--vscode-widget-border, transparent); + background: var(--vscode-textBlockQuote-background); + font-size: var(--vscode-fontSize-body1); + line-height: 1.45; + color: var(--vscode-foreground); +} + +.organization-policy-notice .organization-policy-notice-icon { + flex-shrink: 0; + font-size: var(--vscode-codiconFontSize); + line-height: 1.45; + color: var(--vscode-descriptionForeground); +} + +.organization-policy-notice .organization-policy-notice-message { + min-width: 0; +} + /* Status icon for remote customization items (loading/loaded/degraded/error) */ .ai-customization-list-item .item-status-icon { flex-shrink: 0; @@ -976,6 +1013,7 @@ per-word capitalization does not survive translation. */ .ai-customization-list-item:hover .item-right, .ai-customization-list-item:focus-within .item-right, +.ai-customization-list-item.menu-open .item-right, .monaco-list-row.focused .ai-customization-list-item .item-right { opacity: 1; } @@ -987,7 +1025,7 @@ per-word capitalization does not survive translation. */ padding: 0; align-items: center; justify-content: center; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* Highlighted matches */ @@ -1038,7 +1076,7 @@ per-word capitalization does not survive translation. */ width: var(--vscode-spacing-size240); min-width: var(--vscode-spacing-size240); padding: var(--vscode-spacing-sizeNone); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .ai-customization-list-widget .section-title-header .section-title-back-slot, @@ -1982,7 +2020,7 @@ per-word capitalization does not survive translation. */ gap: var(--vscode-spacing-size120); width: 100%; padding: var(--vscode-spacing-size40) var(--vscode-spacing-size60); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); text-align: left; } @@ -2197,7 +2235,7 @@ per-word capitalization does not survive translation. */ .ai-customization-management-editor .ai-customization-embedded-detail .embedded-detail-title-actions .monaco-button-dropdown:focus-within { outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); outline-offset: -1px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .ai-customization-management-editor .ai-customization-embedded-detail .embedded-detail-title-actions .monaco-button-dropdown > .monaco-button:focus { @@ -3017,7 +3055,7 @@ per-word capitalization does not survive translation. */ min-height: var(--vscode-spacing-size240); padding: 0 var(--vscode-spacing-size80); font-size: var(--vscode-fontSize-label1); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .mcp-server-item .mcp-server-sign-in.monaco-button:hover, @@ -3291,25 +3329,31 @@ per-word capitalization does not survive translation. */ color: var(--vscode-textPreformat-foreground, var(--vscode-descriptionForeground)); } -.plugin-list-widget .plugin-list-item-status { +.plugin-list-widget .plugin-list-item-status-icon { flex-shrink: 0; - font-size: var(--vscode-agents-fontSize-label2); - font-weight: var(--vscode-agents-fontWeight-semiBold); - line-height: 18px; - padding: 0 var(--vscode-spacing-size80); - border-radius: var(--vscode-cornerRadius-circle); - color: var(--vscode-badge-foreground); - background-color: var(--vscode-badge-background); + width: var(--vscode-spacing-size160); + height: var(--vscode-spacing-size160); + display: flex; + align-items: center; + justify-content: center; + font-size: var(--vscode-codiconFontSize); + color: var(--vscode-descriptionForeground); } -.plugin-list-widget .plugin-list-item-status.running { - color: var(--vscode-editor-background); - background-color: color-mix(in srgb, var(--vscode-terminal-ansiGreen) 50%, transparent); +.plugin-list-widget .plugin-list-item-status-icon.loading { + color: var(--vscode-progressBar-background, var(--vscode-icon-foreground)); } -.plugin-list-widget .plugin-list-item-status.disabled { - color: var(--vscode-badge-foreground); - background-color: color-mix(in srgb, var(--vscode-badge-background) 50%, transparent); +.monaco-reduce-motion .plugin-list-widget .plugin-list-item-status-icon.loading { + animation: none; +} + +.plugin-list-widget .plugin-list-item-status-icon.warning { + color: var(--vscode-list-warningForeground, var(--vscode-editorWarning-foreground)); +} + +.plugin-list-widget .plugin-list-item-status-icon.error { + color: var(--vscode-errorForeground); } .plugin-list-widget .plugin-list-item-action { @@ -3329,7 +3373,7 @@ per-word capitalization does not survive translation. */ min-width: var(--vscode-spacing-size240); height: var(--vscode-spacing-size240); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); border-color: transparent; background: transparent; color: var(--vscode-foreground); @@ -3349,7 +3393,7 @@ per-word capitalization does not survive translation. */ min-width: var(--vscode-spacing-size240); height: var(--vscode-spacing-size240); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); border-color: transparent; background: transparent; color: var(--vscode-foreground); @@ -3711,7 +3755,7 @@ per-word capitalization does not survive translation. */ min-width: var(--vscode-spacing-size240); height: var(--vscode-spacing-size240); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); border-color: transparent; background: transparent; color: var(--vscode-foreground); @@ -3738,7 +3782,7 @@ per-word capitalization does not survive translation. */ min-width: var(--vscode-spacing-size240); height: var(--vscode-spacing-size240); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); background: transparent; color: var(--vscode-foreground); border-color: transparent; diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/media/chatCustomizations.css b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/chatCustomizations.css new file mode 100644 index 000000000000..9f36af0ff5d4 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/chatCustomizations.css @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.chat-customizations-action-item { + position: relative; +} + +.chat-customizations-action-item.migration-available::after { + content: ''; + position: absolute; + top: var(--vscode-spacing-size20); + right: var(--vscode-spacing-size20); + width: var(--vscode-spacing-size60); + height: var(--vscode-spacing-size60); + border-radius: var(--vscode-cornerRadius-circle); + background-color: var(--vscode-activityWarningBadge-background, var(--vscode-editorWarning-foreground)); + pointer-events: none; +} + +.monaco-hover.chat-customizations-hover .hover-contents { + width: 280px; + max-width: calc(100vw - 32px); +} + +.monaco-hover.workbench-hover.chat-customizations-hover .markdown-hover .hover-contents { + padding-top: var(--vscode-spacing-size80); +} + +.chat-customizations-hover .hover-contents p:first-child { + margin-bottom: var(--vscode-spacing-size40); +} + +.chat-customizations-hover .hover-contents p:nth-of-type(2) { + margin-top: 0; + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-label1); + overflow-wrap: anywhere; +} + +.chat-customizations-hover table { + width: 100%; + border-collapse: collapse; +} + +/* Keep column headers and the icon-only settings label available to screen readers. */ +.chat-customizations-hover thead, +.chat-customizations-hover .hover-contents hr + p > a:last-child > span:not(.codicon) { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.chat-customizations-hover td { + padding: var(--vscode-spacing-size40) 0; +} + +.chat-customizations-hover td:last-child { + padding-left: var(--vscode-spacing-size160); + font-variant-numeric: tabular-nums; +} + +.monaco-hover.chat-customizations-hover a { + text-decoration: var(--text-link-decoration, none); +} + +.hc-black .monaco-hover.chat-customizations-hover a, +.hc-light .monaco-hover.chat-customizations-hover a { + text-decoration: underline; +} + +.monaco-hover.chat-customizations-hover td a { + display: inline-block; + color: var(--vscode-foreground); +} + +.chat-customizations-hover td a > .codicon, +.chat-customizations-hover .hover-contents hr + p > a:first-child > .codicon { + margin-right: var(--vscode-spacing-size80); +} + +.monaco-hover.chat-customizations-hover td a:hover { + color: var(--vscode-textLink-activeForeground); +} + +.monaco-hover.chat-customizations-hover .hover-contents ul { + list-style: none; + padding-left: 0; +} + +.chat-customizations-hover li { + padding: var(--vscode-spacing-size40) 0; +} + +.chat-customizations-hover li > .codicon { + margin-right: var(--vscode-spacing-size60); + color: var(--vscode-editorWarning-foreground); +} + +.chat-customizations-hover li em { + display: flex; + padding-left: var(--vscode-spacing-size240); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-label2); + font-style: normal; + white-space: nowrap; +} + +.chat-customizations-hover li em a { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.monaco-hover.chat-customizations-hover .markdown-hover .hover-contents .codicon { + font-size: var(--vscode-codiconFontSize); + margin-bottom: 0; +} + +.monaco-hover.chat-customizations-hover .hover-contents hr { + margin: var(--vscode-spacing-size80) 0; + border: none; + border-top: var(--vscode-strokeThickness) solid var(--vscode-editorHoverWidget-border); + height: 0; +} + +.chat-customizations-hover .hover-contents hr + p { + font-size: var(--vscode-fontSize-label1); + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--vscode-spacing-size80); +} + +.chat-customizations-hover .hover-contents hr + p > a { + display: inline-flex; + align-items: center; +} + +.monaco-hover.workbench-hover.chat-customizations-hover .markdown-hover .hover-contents hr + p > a > .codicon { + margin-bottom: 0; +} + +.chat-customizations-hover .hover-contents hr + p > a:last-child { + flex-shrink: 0; + padding: var(--vscode-spacing-size40); + /* Align the glyph with the counts while preserving its padded hit target. */ + margin-right: calc(-1 * var(--vscode-spacing-size40)); + color: var(--vscode-descriptionForeground); +} + +.chat-customizations-hover .hover-contents hr + p > a:last-child:hover { + color: var(--vscode-textLink-activeForeground); +} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/media/customizationMigrationDashboard.css b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/customizationMigrationDashboard.css index a144c30cc135..2c06286d46d7 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/media/customizationMigrationDashboard.css +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/media/customizationMigrationDashboard.css @@ -114,7 +114,7 @@ width: auto; flex-shrink: 0; font-size: var(--vscode-fontSize-label1); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .customization-migration-dashboard .migration-secondary-button { diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginCustomizationMarketplaceProvider.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginCustomizationMarketplaceProvider.ts index 9d40d0b68e95..9f66899d2973 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginCustomizationMarketplaceProvider.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginCustomizationMarketplaceProvider.ts @@ -55,11 +55,15 @@ export function getPluginCustomizationMarketplaceSourceIdFromIdentifier(identifi } export function isPluginMarketplaceAvailableInDiscover(configurationService: IConfigurationService, marketplace: IMarketplaceReference | string, githubFeedAvailable: boolean): boolean { - const reference = typeof marketplace === 'string' ? parseProviderMarketplaceReference(marketplace) : marketplace; return !githubFeedAvailable || configurationService.getValue(CustomizationMarketplaceConfiguration.MarketplaceEnabled) !== true || configurationService.getValue(CustomizationMarketplaceConfiguration.AgentFinderPublicFeedEnabled) !== true || - reference?.githubRepo?.toLowerCase() !== defaultMarketplaceReference.githubRepo; + !isDefaultPluginMarketplace(marketplace); +} + +export function isDefaultPluginMarketplace(marketplace: IMarketplaceReference | string): boolean { + const reference = typeof marketplace === 'string' ? parseProviderMarketplaceReference(marketplace) : marketplace; + return reference?.githubRepo?.toLowerCase() === defaultMarketplaceReference.githubRepo; } export function getPluginCustomizationMarketplaceSourceInfos( diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginListWidget.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginListWidget.ts index 5e9f5b6ec106..d5321d8e6a33 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/pluginListWidget.ts @@ -12,7 +12,7 @@ import { IInstantiationService } from '../../../../../platform/instantiation/com import { WorkbenchList, WorkbenchObjectTree } from '../../../../../platform/list/browser/listService.js'; import { IListVirtualDelegate, IListRenderer, IListContextMenuEvent } from '../../../../../base/browser/ui/list/list.js'; import { RenderIndentGuides } from '../../../../../base/browser/ui/tree/abstractTree.js'; -import { IObjectTreeElement, ITreeContextMenuEvent, ObjectTreeElementCollapseState } from '../../../../../base/browser/ui/tree/tree.js'; +import { IObjectTreeElement, ITreeContextMenuEvent } from '../../../../../base/browser/ui/tree/tree.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Button, ButtonWithDropdown } from '../../../../../base/browser/ui/button/button.js'; @@ -36,6 +36,7 @@ import { ContributionEnablementState, IEnablementModel, isContributionEnabled } import { ICustomizationMarketplaceInstallService } from '../../common/customizationMarketplaceInstallService.js'; import { customizationSearchMatchesAny } from '../../common/aiCustomizationSearch.js'; import { getInstalledPluginContextMenuActions, getPluginManagedByOrganizationMessage, getPluginPolicyEnablement, removePluginWithMarketplaceOwnership } from '../agentPluginActions.js'; +import { OrganizationManagedTag, withOrganizationManagedAriaLabel } from './customizationOrganizationPolicy.js'; import { IMarketplacePlugin, IPluginMarketplaceService } from '../../common/plugins/pluginMarketplaceService.js'; import { IPluginInstallService } from '../../common/plugins/pluginInstallService.js'; import { AgentPluginItemKind, IAgentPluginItem, IInstalledPluginItem, IMarketplacePluginItem } from '../agentPluginEditor/agentPluginItems.js'; @@ -60,13 +61,14 @@ import { createCustomizationCardPrimaryAction, CustomizationCardListController, import { DomScrollableElement } from '../../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { ScrollbarVisibility } from '../../../../../base/common/scrollable.js'; import { getCustomizationContributionSourceLabel } from './customizationContributionSource.js'; -import { asTreeRenderer, customizationTreeStyles, getCustomizationTreeContentHeight, ICustomizationTreeGroup } from './customizationTree.js'; +import { asTreeRenderer, customizationTreeStyles, getCustomizationTreeContentHeight, ICustomizationTreeGroup, isCustomizationTreeEntryVisible } from './customizationTree.js'; import { CustomizationToggle } from './customizationToggle.js'; import { affectsCustomizationDiscoveryAvailability, isCustomizationDiscoveryAvailable } from './customizationMarketplaceConfiguration.js'; import { getAvailableCustomizationMarketplaceInstallTelemetryContext, runCustomizationMarketplaceInstallWithTelemetry } from '../../common/customizationMarketplaceInstallTelemetry.js'; import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; import { getAICustomizationWorkspaceGroupForResource, getAICustomizationWorkspaceGroups, isAICustomizationWorkspaceGroupKey } from './aiCustomizationWorkspaceGroups.js'; import { MANAGE_PLUGIN_MARKETPLACES_COMMAND_ID } from '../actions/chatPluginActions.js'; +import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; const $ = DOM.$; @@ -262,6 +264,7 @@ interface IPluginInstalledItemTemplateData { readonly container: HTMLElement; readonly syncToggleContainer: HTMLElement; readonly name: HTMLElement; + readonly managedTag: OrganizationManagedTag; readonly location: MiddleEllipsisPathLabel; readonly metadata: HTMLElement; readonly actions: HTMLElement; @@ -277,6 +280,7 @@ class PluginInstalledItemRenderer implements IListRenderer void, private readonly _showSyncToggle = true, ) { } @@ -289,13 +293,14 @@ class PluginInstalledItemRenderer implements IListRenderer { + const policyEnablement = getPluginPolicyEnablement(element.item.plugin, reader); + templateData.managedTag.update(policyEnablement === undefined ? undefined : { requiredEnabled: policyEnablement }); + })); templateData.location.set(element.item.location ?? ''); templateData.metadata.textContent = getInstalledPluginMetadata(element.item); @@ -363,9 +372,10 @@ interface IPluginRemoteItemTemplateData { readonly container: HTMLElement; readonly name: HTMLElement; readonly badge: HTMLElement; + readonly managedTag: OrganizationManagedTag; readonly description: HTMLElement; readonly metadata: HTMLElement; - readonly status: HTMLElement; + readonly statusIcon: HTMLElement; readonly actions: HTMLElement; readonly templateDisposables: DisposableStore; readonly disposables: DisposableStore; @@ -387,6 +397,7 @@ class PluginRemoteItemRenderer implements IListRenderer void, + private readonly _hoverService: IHoverService, ) { } renderTemplate(container: HTMLElement): IPluginRemoteItemTemplateData { @@ -396,14 +407,15 @@ class PluginRemoteItemRenderer implements IListRenderer entry.label).slice(0, 2).join(' • '); } @@ -819,6 +849,8 @@ export class PluginListWidget extends Disposable { private searchQuery: string = ''; private currentTreeGroups: readonly ICustomizationTreeGroup[] = []; private browseMode: boolean = false; + /** Groups the user collapsed, restored whenever the tree is re-rendered without a search or browsing the marketplace. */ + private readonly collapsedGroups = new Set(); private visible = false; private firstCardFocusElement: HTMLElement | undefined; private narrowLayout = false; @@ -1066,8 +1098,8 @@ export class PluginListWidget extends Disposable { (entry, container, disposables) => this.renderPluginTreeGroupActions(entry, container, disposables), ); const searchHeaderRenderer = new PluginSearchHeaderRenderer(); - const installedRenderer = new PluginInstalledItemRenderer(this.harnessService, (item, container, actions, disposables) => this.renderInstalledListActions(item, container, actions, disposables), false); - const remoteRenderer = new PluginRemoteItemRenderer((item, actions, disposables) => this.renderRemoteListActions(item, actions, disposables)); + const installedRenderer = new PluginInstalledItemRenderer(this.harnessService, this.hoverService, (item, container, actions, disposables) => this.renderInstalledListActions(item, container, actions, disposables), false); + const remoteRenderer = new PluginRemoteItemRenderer((item, actions, disposables) => this.renderRemoteListActions(item, actions, disposables), this.hoverService); const marketplaceRenderer = new PluginMarketplaceItemRenderer(this.pluginInstallService, this.agentPluginService, this.pluginMarketplaceService, this.notificationService); this.list = this._register(this.instantiationService.createInstance( @@ -1123,8 +1155,18 @@ export class PluginListWidget extends Disposable { remoteRenderer.setFocusedItemId(entry?.type === 'remote-item' ? getRemotePluginEntryId(entry) : undefined); marketplaceRenderer.setFocusedItemId(entry?.type === 'marketplace-item' ? getMarketplacePluginEntryId(entry) : undefined); })); + this._register(this.list.onDidChangeCollapseState(event => { + const entry = event.node.element; + if (entry?.type === 'group-header' && !this.isFilteringPluginTree()) { + if (event.node.collapsed) { + this.collapsedGroups.add(entry.group); + } else { + this.collapsedGroups.delete(entry.group); + } + } + })); this._register(this.list.onDidFocus(() => { - focusFirstCustomizationTreeItem(this.list, this.getVisiblePluginEntries(), entry => entry.type !== 'group-header'); + focusFirstCustomizationTreeItem(this.list, this.getVisiblePluginEntries(), entry => entry.type !== 'group-header', entry => isCustomizationTreeEntryVisible(this.list, entry)); })); // Handle context menu @@ -1351,19 +1393,19 @@ export class PluginListWidget extends Disposable { if (element.type === 'plugin-item') { const details = [element.item.location, getInstalledPluginMetadata(element.item)].filter(detail => !!detail); const withDetails = details.reduce((label, detail) => localize('pluginInstalledItemAriaLabelWithDetail', "{0}. {1}", label, detail), name); - return derived(this, reader => isContributionEnabled(element.item.plugin.enablement.read(reader)) - ? localize('pluginInstalledItemAriaLabelEnabled', "{0}. Enabled", withDetails) - : localize('pluginInstalledItemAriaLabelDisabled', "{0}. Disabled", withDetails)); + return derived(this, reader => { + const label = isContributionEnabled(element.item.plugin.enablement.read(reader)) + ? localize('pluginInstalledItemAriaLabelEnabled', "{0}. Enabled", withDetails) + : localize('pluginInstalledItemAriaLabelDisabled', "{0}. Disabled", withDetails); + const policyEnablement = getPluginPolicyEnablement(element.item.plugin, reader); + return withOrganizationManagedAriaLabel(label, policyEnablement === undefined ? undefined : { requiredEnabled: policyEnablement }); + }); } - const itemDescription = element.type === 'remote-item' ? getRemotePluginDescription(element.item) : element.item.description; - const description = itemDescription ? truncateToFirstLine(itemDescription) : undefined; - const nameAndDescription = description ? localize('pluginItemAriaLabel', "{0}. {1}", name, description) : name; if (element.type === 'remote-item') { - const statusLabel = getRemotePluginStatusLabel(element.item); - return statusLabel - ? localize('pluginSessionItemAriaLabelWithStatus', "{0}. Agent host. Status: {1}", nameAndDescription, statusLabel) - : localize('pluginSessionItemAriaLabel', "{0}. Agent host", nameAndDescription); + return getRemotePluginAriaLabel(element.item); } + const description = element.item.description ? truncateToFirstLine(element.item.description) : undefined; + const nameAndDescription = description ? localize('pluginItemAriaLabel', "{0}. {1}", name, description) : name; const marketplaceLabel = localize('pluginMarketplaceItemAriaLabel', "{0}. From {1}", nameAndDescription, element.item.marketplace); return this.pluginMarketplaceService.recommendedPlugins.get().has(getMarketplaceRecommendationKey(element.item)) ? localize('pluginMarketplaceItemAriaLabelRecommended', "{0}. Recommended for this workspace", marketplaceLabel) @@ -1588,18 +1630,26 @@ export class PluginListWidget extends Disposable { }); this.cardScrollableNode.style.display = 'none'; + const isFiltering = this.isFilteringPluginTree(); const children: IObjectTreeElement[] = this.currentTreeGroups.map(group => ({ element: group.element, collapsible: true, - collapsed: ObjectTreeElementCollapseState.PreserveOrExpanded, + collapsed: !isFiltering && this.collapsedGroups.has(group.id), children: group.children.map(element => ({ element })), })); - this.list.setChildren(null); this.list.setChildren(null, children); this.updateToolbarActions(); this.updatePluginTreeEmptyState(this.currentTreeGroups.reduce((count, group) => count + group.children.length, 0)); } + /** + * Whether the tree shows search or marketplace results, which are shown + * with every group expanded. + */ + private isFilteringPluginTree(): boolean { + return this.browseMode || !!this.searchQuery.trim(); + } + private renderPluginTreeGroupActions(entry: IPluginGroupHeaderEntry, container: HTMLElement, disposables: DisposableStore): void { const actions = DOM.append(container, $('.plugin-card-section-actions')); const isMultiRootWorkspaceFallback = entry.group === 'workspace' && getAICustomizationWorkspaceGroups(this.workspaceContextService).length > 0; @@ -1856,7 +1906,7 @@ export class PluginListWidget extends Disposable { protected appendRemotePluginRow(parent: HTMLElement, item: ICustomizationItem): void { const row = DOM.append(parent, $('.plugin-list-item.plugin-home-row.plugin-remote-item')); row.setAttribute('role', 'listitem'); - row.setAttribute('aria-label', localize('pluginSessionCardAria', "{0}. Session plugin", item.name)); + row.setAttribute('aria-label', getRemotePluginAriaLabel(item)); row.classList.toggle('disabled', item.enabled === false); const details = DOM.append(row, $('.plugin-list-item-details')); @@ -1868,14 +1918,8 @@ export class PluginListWidget extends Disposable { const metadata = DOM.append(details, $('.plugin-list-item-metadata')); metadata.textContent = localize('sessionPluginConfigurationSource', "Configured on the active agent host"); - const status = DOM.append(row, $('.plugin-list-item-status')); - const statusLabel = getRemotePluginStatusLabel(item); - if (statusLabel) { - status.textContent = statusLabel; - status.classList.toggle('disabled', item.enabled === false || item.status === 'degraded' || item.status === 'error'); - } else { - status.style.display = 'none'; - } + const statusIcon = DOM.append(row, $('.plugin-list-item-status-icon', { 'aria-hidden': 'true' })); + renderRemotePluginStatusIcon(statusIcon, item, this.hoverService, this.cardDisposables); let more: Button | undefined; if (item.actions?.length) { const actions = DOM.append(row, $('.plugin-list-item-action')); @@ -2396,7 +2440,7 @@ export class PluginListWidget extends Disposable { return; } this.list.domFocus(); - const firstItem = entries.find(entry => entry.type !== 'group-header'); + const firstItem = entries.find(entry => entry.type !== 'group-header' && isCustomizationTreeEntryVisible(this.list, entry)) ?? entries[0]; if (firstItem) { this.list.setFocus([firstItem]); } diff --git a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentResolveService.ts b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentResolveService.ts index 30d41f7d0308..c322cda7845e 100644 --- a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentResolveService.ts +++ b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentResolveService.ts @@ -75,7 +75,7 @@ export class ChatAttachmentResolveService implements IChatAttachmentResolveServi } // untitled editor - if (isUntitledResourceEditorInput(editor)) { + if (!(editor instanceof EditorInput) && isUntitledResourceEditorInput(editor)) { return await this.resolveUntitledEditorAttachContext(editor); } diff --git a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgetRegistry.ts b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgetRegistry.ts index 886e595ebbcc..a4a2b2d8a8dc 100644 --- a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgetRegistry.ts +++ b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgetRegistry.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as event from '../../../../../base/common/event.js'; +import { IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; import { IDisposable } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; @@ -18,6 +19,19 @@ export interface IChatAttachmentWidgetInstance extends IDisposable { readonly onDidOpen: event.Event; /** Optional label element, used for applying warning styles on omitted attachments. */ readonly label?: { readonly element: HTMLElement }; + /** Creates the detail preview used by the input editor's keyboard hover. */ + getPreviewHoverContent?(): HTMLElement | undefined; + /** Whether the attachment provides a delayed reference preview. Activation still navigates. */ + readonly supportsPreview?: boolean; + /** Shared pointer hover, also revealed when the editor gives the reference keyboard focus. */ + readonly previewHover?: IManagedHover; + /** Fires when account changes or widget disposal invalidate displayed preview details. */ + readonly onDidChangePreview?: event.Event; + /** + * The name that the widget shows for the attachment, when it differs from + * the attachment's name and can change, as the title of a linked session does. + */ + readonly displayName?: string; } /** @@ -42,6 +56,11 @@ export interface IChatAttachmentWidgetRegistry { */ registerFactory(kind: string, factory: ChatAttachmentWidgetFactory): IDisposable; + /** + * Whether a widget factory is registered for an attachment kind. + */ + hasFactory(kind: string): boolean; + /** * Try to create a widget for the given attachment using a registered factory. * Returns undefined if no factory is registered for the attachment's kind. @@ -72,6 +91,10 @@ export class ChatAttachmentWidgetRegistry implements IChatAttachmentWidgetRegist }; } + hasFactory(kind: string): boolean { + return this._factories.has(kind); + } + createWidget( attachment: IChatRequestVariableEntry, options: { shouldFocusClearButton: boolean; supportsDeletion: boolean }, diff --git a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts index 9c58ac99a6a3..9f029808b07d 100644 --- a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts +++ b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts @@ -11,8 +11,9 @@ import { StandardMouseEvent } from '../../../../../base/browser/mouseEvent.js'; import { Button } from '../../../../../base/browser/ui/button/button.js'; import { decodeBase64, VSBuffer } from '../../../../../base/common/buffer.js'; import { IAction, Separator } from '../../../../../base/common/actions.js'; -import { HoverStyle, IDelayedHoverOptions, type IHoverLifecycleOptions, type IHoverOptions } from '../../../../../base/browser/ui/hover/hover.js'; -import { createInstantHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { HoverStyle, IDelayedHoverOptions, type IHoverLifecycleOptions, type IHoverOptions, type IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; +import { IHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegate.js'; +import { createInstantHoverDelegate, getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; import { DomScrollableElement } from '../../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { Codicon } from '../../../../../base/common/codicons.js'; @@ -89,6 +90,10 @@ import { IChatImageCarouselService } from '../chatImageCarouselService.js'; import { createChatImageCopyActions } from '../chatImageActions.js'; import { createChatImageHoverContent } from '../../../../browser/chatImagePreview.js'; import { ChatImageReveal, IChatImageRevealOrigin } from './chatImageReveal.js'; +import { GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX } from '../../common/attachments/chatInlineAttachments.js'; +import { GitHubResourceDetailsResolver, IGitHubResourceDetailsHover, parseGitHubReferenceTarget } from '../../../github/browser/githubResourceDetails.js'; +import { IClipboardService } from '../../../../../platform/clipboard/common/clipboardService.js'; +import { IWorkbenchGitHubService } from '../../../../services/github/common/githubService.js'; const commonHoverOptions: Partial = { style: HoverStyle.Pointer, @@ -779,8 +784,13 @@ function createImageElements(resource: URI | undefined, name: string, fullName: return dom.$('div.chat-attached-context-pill', {}, iconElement); }; const supportsVision = modelSupportsVision(currentLanguageModel); + const isUnsupported = (!supportsVision && !!currentLanguageModel) || omittedState === OmittedState.Full; + const isLimitExceeded = omittedState === OmittedState.ImageLimitExceeded; + // The icon is the placeholder until the thumbnail is ready, so it only warns when no preview + // follows. Without a known model, as for a tool result, nothing is wrong with the image. + const showsPreview = !isUnsupported && !isLimitExceeded; const warningIcon = useCompactWarningIcon ? Codicon.warningCompact : Codicon.warning; - const pillIcon = createPillIcon(supportsVision ? Codicon.fileMediaCompact : warningIcon); + const pillIcon = createPillIcon(supportsVision || showsPreview ? Codicon.fileMediaCompact : warningIcon); const textLabel = dom.$('span.chat-attached-context-custom-text', {}, name); element.appendChild(pillIcon); element.appendChild(textLabel); @@ -795,14 +805,14 @@ function createImageElements(resource: URI | undefined, name: string, fullName: const hoverElement = dom.$('div.chat-attached-context-hover'); hoverElement.setAttribute('aria-label', ariaLabel); - if ((!supportsVision && currentLanguageModel) || omittedState === OmittedState.Full) { + if (isUnsupported) { element.classList.add('warning'); hoverElement.textContent = localize('chat.imageAttachmentHover', "{0} does not support images.", currentLanguageModelName ?? 'This model'); disposable.add(hoverService.setupDelayedHover(element, { content: hoverElement, style: HoverStyle.Pointer, })); - } else if (omittedState === OmittedState.ImageLimitExceeded) { + } else if (isLimitExceeded) { element.classList.add('warning'); const maxImagesPerRequest = getImageAttachmentLimit(currentLanguageModel?.metadata); hoverElement.textContent = maxImagesPerRequest !== undefined @@ -954,7 +964,14 @@ export class PasteAttachmentWidget extends AbstractChatAttachmentWidget { export class DefaultChatAttachmentWidget extends AbstractChatAttachmentWidget { + readonly previewHover: IManagedHover | undefined; private readonly _tooltipHover: MutableDisposable = this._register(new MutableDisposable()); + private _referenceHover: (() => IGitHubResourceDetailsHover) | undefined; + get supportsPreview(): boolean { + return !!this._referenceHover; + } + private readonly _onDidChangePreview = this._register(new event.Emitter()); + readonly onDidChangePreview = this._onDidChangePreview.event; constructor( resource: URI | undefined, @@ -962,7 +979,7 @@ export class DefaultChatAttachmentWidget extends AbstractChatAttachmentWidget { attachment: IChatRequestVariableEntry, correspondingContentReference: IChatContentReference | undefined, currentLanguageModel: ILanguageModelChatMetadataAndIdentifier | undefined, - options: { shouldFocusClearButton: boolean; supportsDeletion: boolean }, + options: { shouldFocusClearButton: boolean; supportsDeletion: boolean; supportsReferencePreview?: boolean; gitHubResourceDetailsResolver?: GitHubResourceDetailsResolver; hoverDelegate?: IHoverDelegate }, container: HTMLElement, contextResourceLabels: ResourceLabels, @ICommandService commandService: ICommandService, @@ -974,6 +991,8 @@ export class DefaultChatAttachmentWidget extends AbstractChatAttachmentWidget { @IModelService private readonly modelService: IModelService, @ILanguageService private readonly languageService: ILanguageService, @IThemeService private readonly themeService: IThemeService, + @IClipboardService private readonly clipboardService: IClipboardService, + @IWorkbenchGitHubService private readonly gitHubService: IWorkbenchGitHubService, ) { super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService, configurationService); @@ -1033,11 +1052,59 @@ export class DefaultChatAttachmentWidget extends AbstractChatAttachmentWidget { this._setupTooltipHover(attachment.tooltip); } + // A pill in the text of the input always previews and opens its GitHub issue or pull request; other pills do when asked to. + if (attachment.kind === 'generic' && attachment.id.startsWith(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX) && (options.supportsReferencePreview || this.element.closest('.chat-inline-attachment'))) { + const link = URI.parse(attachment.id.substring(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX.length)); + const issue = parseGitHubReferenceTarget(link, 'issue'); + const target = issue ?? parseGitHubReferenceTarget(link, 'pullRequest'); + if (target) { + resource = link; + const resolver = options.gitHubResourceDetailsResolver ?? this._register(this.instantiationService.createInstance(GitHubResourceDetailsResolver)); + const repository = URI.parse(`https://github.com/${target.owner}/${target.repo}`); + const open = (uri: URI) => { void this.openerService.open(uri, { openExternal: true }); }; + const createHover = () => resolver.createHover(attachment, { + kind: issue ? 'issue' : 'pullRequest', + target, + resource: link, + onDidClickRepository: () => open(repository), + onDidClickReference: () => open(link), + onDidClickBaseBranch: branch => { void this.clipboardService.writeText(branch); }, + onDidClickHeadBranch: branch => { void this.clipboardService.writeText(branch); }, + }); + this._referenceHover = createHover; + // Keep the external pill's lazy content and spacing contract intact. + const hover = this.hoverService.setupManagedHover(options.hoverDelegate ?? getDefaultHoverDelegate('element'), this.element, () => createHover().pillHover); + this.previewHover = hover; + this._tooltipHover.value = hover; + this._register(this.gitHubService.onDidChangeDefaultClient(() => { + hover.hide(); + this._onDidChangePreview.fire(); + })); + this.element.ariaLabel = this.appendDeletionHint(localize('chat.attachment.openReferenceLabel', "Open reference, {0}", attachment.name)); + } + } + if (resource) { this.addResourceOpenHandlers(resource, range); } } + getPreviewHoverContent(): HTMLElement | undefined { + if (!this._referenceHover) { + return undefined; + } + const content = this._referenceHover().hover.content; + if (typeof content !== 'function') { + throw new Error('Expected GitHub reference hover content factory'); + } + return content(); + } + + override dispose(): void { + this._onDidChangePreview.fire(); + super.dispose(); + } + private _applyLabel(attachment: IChatRequestVariableEntry, attachmentLabel: string, description: string | undefined, iconPath: ChatContextIconPath | undefined): void { if (isStringVariableEntry(attachment) && iconPath && ThemeIcon.isThemeIcon(iconPath) && (ThemeIcon.isFile(iconPath) || ThemeIcon.isFolder(iconPath)) && attachment.resourceUri) { // Derive icon classes from resourceUri for file/folder theme icons diff --git a/src/vs/workbench/contrib/chat/browser/attachments/chatUserImageAttachments.ts b/src/vs/workbench/contrib/chat/browser/attachments/chatUserImageAttachments.ts new file mode 100644 index 000000000000..ff8b853c0786 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/attachments/chatUserImageAttachments.ts @@ -0,0 +1,59 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { InstantiationType, registerSingleton } from '../../../../../platform/instantiation/common/extensions.js'; +import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IChatRequestVariableEntry, isImageVariableEntry } from '../../common/attachments/chatVariableEntries.js'; + +/** How the user attached images to a chat input. */ +export type ChatImageAttachGesture = 'paste' | 'drop'; + +export interface IChatUserImageAttachmentEvent { + /** The chat input that the images were attached to. */ + readonly inputUri: URI; + /** The images that the gesture attached, none of which were attached before. */ + readonly attachmentIds: readonly string[]; + readonly gesture: ChatImageAttachGesture; +} + +export const IChatUserImageAttachmentService = createDecorator('chatUserImageAttachmentService'); + +/** + * Reports the images that the user attaches to a chat input by hand, by pasting or dropping them. Images that come back + * with a draft, the history, an undo or a redo are not reported, nor are images that other features attach. + */ +export interface IChatUserImageAttachmentService { + readonly _serviceBrand: undefined; + + readonly onDidAttachImages: Event; + + /** Called by the paste and drop handlers once the images are attached. */ + didAttachImages(event: IChatUserImageAttachmentEvent): void; +} + +/** Returns the ids of the images in `after` that are not in `before`. */ +export function getAddedImageIds(before: readonly IChatRequestVariableEntry[], after: readonly IChatRequestVariableEntry[]): string[] { + const beforeIds = new Set(before.map(entry => entry.id)); + return after.filter(entry => isImageVariableEntry(entry) && !beforeIds.has(entry.id)).map(entry => entry.id); +} + +class ChatUserImageAttachmentService extends Disposable implements IChatUserImageAttachmentService { + + declare readonly _serviceBrand: undefined; + + private readonly _onDidAttachImages = this._register(new Emitter()); + readonly onDidAttachImages = this._onDidAttachImages.event; + + didAttachImages(event: IChatUserImageAttachmentEvent): void { + if (event.attachmentIds.length) { + this._onDidAttachImages.fire(event); + } + } +} + +registerSingleton(IChatUserImageAttachmentService, ChatUserImageAttachmentService, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/chat/browser/attachments/defaultChatAttachmentWidgetRegistry.ts b/src/vs/workbench/contrib/chat/browser/attachments/defaultChatAttachmentWidgetRegistry.ts new file mode 100644 index 000000000000..26b47d67fc75 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/attachments/defaultChatAttachmentWidgetRegistry.ts @@ -0,0 +1,80 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { createScreenshotToolImage, getScreenshotToolImageData, IScreenshotToolEdit, IScreenshotToolEditable, IScreenshotToolService, ScreenshotToolSurface, toImageCarouselMarkUp } from '../../../screenshotTool/browser/screenshotTool.js'; +import { IChatRequestVariableEntry, isImageVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import { extractImagesFromChatVariables } from '../../common/chatImageExtraction.js'; +import { ChatAttachmentModel } from './chatAttachmentModel.js'; +import { ChatAttachmentWidgetRegistry, IChatImageAttachmentEditor } from './chatAttachmentWidgetRegistry.js'; + +/** Supplies image editing before restored attachments first render, without a late contribution. */ +export class DefaultChatAttachmentWidgetRegistry extends ChatAttachmentWidgetRegistry { + readonly imageEditor: IChatImageAttachmentEditor | undefined; + + constructor( + @IScreenshotToolService screenshotToolService: IScreenshotToolService, + @IFileService fileService: IFileService, + @ILogService logService: ILogService, + ) { + super(); + if (screenshotToolService.isSupported) { + const readFile = async (uri: URI) => (await fileService.readFile(uri)).value.buffer; + this.imageEditor = { + edit: async (attachmentModel, attachment) => { + try { + const screenshot = await getEditableImageAttachment(attachment, screenshotToolService, readFile); + const edit = await screenshotToolService.edit(screenshot, ScreenshotToolSurface.Chat); + if (edit) { + applyScreenshotToolEdit(attachmentModel, attachment, edit, screenshotToolService); + } + } catch (error) { + logService.error('[ChatInputPart] Marking up an attached image failed:', error); + } + }, + createMarkUp: (container, attachmentModel, attachmentId) => { + // An earlier markup may have replaced the attachment since the carousel opened. + const attachment = attachmentModel.attachments.find(candidate => candidate.id === attachmentId); + const screenshot = getEditableImageAttachment(attachment, screenshotToolService, readFile); + const markUp = screenshotToolService.markUp(container, screenshot, ScreenshotToolSurface.Chat); + void markUp.result.then(edit => { + if (edit && attachment) { + applyScreenshotToolEdit(attachmentModel, attachment, edit, screenshotToolService); + } + }, error => logService.error('[ChatImageCarouselService] Marking up an attached image failed:', error)); + return toImageCarouselMarkUp(markUp); + }, + }; + } + } +} + +function applyScreenshotToolEdit(attachmentModel: ChatAttachmentModel, attachment: IChatRequestVariableEntry, edit: IScreenshotToolEdit, screenshotToolService: IScreenshotToolService): void { + if (!isImageVariableEntry(attachment) || !attachmentModel.attachments.includes(attachment)) { + return; + } + const { data, mimeType } = getScreenshotToolImageData(edit.image); + // Downloads and recalled input must use the marked-up image, not its original file. + const marked: IChatRequestVariableEntry = { ...attachment, value: data.buffer, mimeType, references: [] }; + // Updating the model immediately re-renders its attachments, so register their annotations first. + screenshotToolService.registerEditableAttachment(marked, { original: edit.original, annotationState: edit.annotationState }); + attachmentModel.updateContext([], [marked]); +} + +function getEditableImageAttachment(attachment: IChatRequestVariableEntry | undefined, screenshotToolService: IScreenshotToolService, readFile: (uri: URI) => Promise): IScreenshotToolEditable | Promise { + return (attachment && screenshotToolService.getEditableAttachment(attachment)) ?? loadEditableImageAttachment(attachment, readFile); +} + +async function loadEditableImageAttachment(attachment: IChatRequestVariableEntry | undefined, readFile: (uri: URI) => Promise): Promise { + const [image] = attachment ? extractImagesFromChatVariables([attachment]) : []; + if (!image) { + throw new Error('The image is no longer attached.'); + } + const data = image.data ?? VSBuffer.wrap(await readFile(image.uri)); + return { original: await createScreenshotToolImage(data, image.mimeType), annotationState: undefined }; +} 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 7989bdde615b..dc540ce58cdb 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts @@ -6,6 +6,7 @@ import './agentSessions/agentHost/codexContinuation.contribution.js'; import './agentSessions/agentHost/computerUseSetup.contribution.js'; import './agentSessions/agentHost/localModel.contribution.js'; +import './agentSessions/agentHost/agentHostToolApprovals.js'; import { getDefaultModelPolicyDescription } from '../common/modelSelection.js'; import { CODEX_CONTINUATION_DEFAULT_THRESHOLD } from '../../../services/agentHost/browser/codexContinuation.js'; import { CODEX_CONTINUATION_SETTING, CODEX_CONTINUATION_THRESHOLD_SETTING } from '../../../services/agentHost/browser/codexContinuationService.js'; @@ -145,6 +146,8 @@ import { registerChatToolActions } from './actions/chatToolActions.js'; import { ChatTransferContribution } from './actions/chatTransfer.js'; import { CONFIGURE_DICTATION_INSTRUCTIONS_ACTION_ID, registerConfigureSpeechInstructionsActions } from './actions/configureVoiceInstructionsAction.js'; import './agentSessions/agentSessions.contribution.js'; +// Registers the chatDockedViews contribution point before extensions are read. +import './chatDockedViews/chatDockedViews.js'; import { AgentHostChatDebugContribution } from './chatDebug/agentHostChatDebugProvider.js'; import { ChatDebugEditor } from './chatDebug/chatDebugEditor.js'; import { ChatDebugEditorInput, ChatDebugEditorInputSerializer } from './chatDebug/chatDebugEditorInput.js'; @@ -231,6 +234,8 @@ import { ChatPasteTargetService } from './attachments/chatPasteTargetService.js' import { ChatVariablesService } from './attachments/chatVariables.js'; import { ChatImageCarouselService, IChatImageCarouselService } from './chatImageCarouselService.js'; import { EditorChatUsageContribution } from './editorChatUsage.contribution.js'; +import { CustomAgentUsageContribution } from './customAgentUsage.contribution.js'; +import { ChatDailyUsageContribution } from './chatDailyUsage.contribution.js'; import { ChatOutputRendererService, IChatOutputRendererService } from './chatOutputItemRenderer.js'; import { ChatCompatibilityNotifier, ChatExtensionPointHandler } from './chatParticipant.contribution.js'; import { ChatPetAchievementsAccessibilityHelp, ChatPetContextContribution, ChatPetCustomizationAchievementContribution, ChatPetEditingAchievementContribution } from './chatPetAchievements.contribution.js'; @@ -241,6 +246,7 @@ import { ChatExpNotificationContribution } from './expNotification/chatExpNotifi import { ChatQuotaNotificationContribution } from './chatQuotaNotification.js'; import { ChatRepoInfoContribution } from './chatRepoInfo.js'; import { ChatSetupContribution, ChatTeardownContribution } from './chatSetup/chatSetupContributions.js'; +import { ChatEntitlementSimulationContribution, SimulateChatEntitlementAction } from './chatSetup/chatEntitlementSimulation.js'; import { ChatMicrosoftSignInProbeContribution, ChatMicrosoftSignInProbeService, IChatMicrosoftSignInProbeService } from './chatSetup/chatSetupMicrosoftProbe.js'; import { ChatSessionOptionSlashCommandsContribution, ChatSlashCommandsContribution } from './chatSlashCommands.js'; import { BtwSlashCommandContribution } from './btwSlashCommand.js'; @@ -277,6 +283,8 @@ import './widget/chatContentParts/chatSubagentOpenChat.js'; import { ChatFindAccessibilityHelp } from './widget/chatFind/chatFindAccessibilityHelp.js'; import { ChatWidget } from './widget/chatWidget.js'; import { ChatWidgetService } from './widget/chatWidgetService.js'; +import { IChatViewHostService } from './chatViewHost.js'; +import { ChatViewHostService } from './widgetHosts/viewPane/chatViewHostService.js'; import { ChatQueuePickerRendering } from './widget/input/chatQueuePickerActionItem.js'; import './widget/input/editor/agentHostInputCompletions.js'; import './widget/input/editor/agentHostQuestionAnswerCompletions.js'; @@ -521,7 +529,7 @@ configurationRegistry.registerConfiguration({ enum: [AgentHostExternalSessionsMode.None, AgentHostExternalSessionsMode.Recent, AgentHostExternalSessionsMode.Last24Hours, AgentHostExternalSessionsMode.Last7Days, AgentHostExternalSessionsMode.Last30Days], enumDescriptions: [ nls.localize('chat.agentSessions.showExternal.none', "Do not show external sessions."), - nls.localize('chat.agentSessions.showExternal.recent', "Show up to the 2 most recent external sessions updated in the last 7 days. At startup, external sessions older than the second-most-recently updated local session are hidden."), + nls.localize('chat.agentSessions.showExternal.recent', "Show the 2 most recently updated external sessions from the last 7 days, hiding any that are older than your 2 newest local sessions."), nls.localize('chat.agentSessions.showExternal.last24Hours', "Show external sessions updated in the last 24 hours."), nls.localize('chat.agentSessions.showExternal.last7Days', "Show external sessions updated in the last 7 days."), nls.localize('chat.agentSessions.showExternal.last30Days', "Show external sessions updated in the last 30 days."), @@ -1097,6 +1105,13 @@ configurationRegistry.registerConfiguration({ experiment: { mode: 'startup' }, markdownDescription: nls.localize('chat.btwTip.enabled', "Controls whether the Agents Window shows a tip about using `/btw` to ask side questions."), }, + [ChatConfiguration.AutomateTipEnabled]: { + type: 'boolean', + default: false, + tags: ['experimental'], + experiment: { mode: 'auto' }, + markdownDescription: nls.localize('chat.automateTip.enabled', "Controls whether the Agents Window shows a tip about using `/automate` to create recurring automations."), + }, [ChatConfiguration.SendInBackgroundTipEnabled]: { type: 'boolean', default: false, @@ -1418,7 +1433,7 @@ configurationRegistry.registerConfiguration({ }, [ChatConfiguration.ExtensionToolsEnabled]: { type: 'boolean', - description: nls.localize('chat.extensionToolsEnabled', "Enable using tools contributed by third-party extensions."), + description: nls.localize('chat.extensionToolsEnabled', "Enable using tools contributed by third-party extensions. These tools are also disabled when your organization disables MCP."), default: true, policy: { name: 'ChatAgentExtensionTools', @@ -1427,7 +1442,7 @@ configurationRegistry.registerConfiguration({ localization: { description: { key: 'chat.extensionToolsEnabled', - value: nls.localize('chat.extensionToolsEnabled', "Enable using tools contributed by third-party extensions.") + value: nls.localize('chat.extensionToolsEnabled', "Enable using tools contributed by third-party extensions. These tools are also disabled when your organization disables MCP.") } }, } @@ -1969,6 +1984,11 @@ configurationRegistry.registerConfiguration({ description: nls.localize('chat.mathEnabled.description', "Enable math rendering in chat responses using KaTeX."), default: true, }, + [ChatConfiguration.HtmlPreviewEnabled]: { + type: 'boolean', + description: nls.localize('chat.htmlPreview.enabled.description', "Render explicit html-preview code blocks as inline HTML previews in the Agents window. When disabled, these blocks are shown as source code."), + default: false, + }, [ChatConfiguration.ShowCodeBlockProgressAnimation]: { type: 'boolean', description: nls.localize('chat.codeBlock.showProgressAnimation.description', "When applying edits, show a progress animation in the code block pill. If disabled, shows the progress percentage instead."), @@ -2577,6 +2597,22 @@ configurationRegistry.registerConfiguration({ default: false, tags: ['experimental'], }, + [ChatConfiguration.ChatCustomizationsLocation]: { + type: 'string', + enum: ['auto', 'sidebar', 'sessionsHeader', 'chatToolbar', 'chatInput'], + enumDescriptions: [ + nls.localize('chat.customizations.location.auto', "Use the default location for the window and sidebar layout."), + nls.localize('chat.customizations.location.sidebar', "Below the Sessions view in the Agents window. Uses the Chat toolbar in editor windows."), + nls.localize('chat.customizations.location.sessionsHeader', "At the top left of the Sessions view in the Agents window. Uses the Chat toolbar in editor windows."), + nls.localize('chat.customizations.location.chatToolbar', "In the Chat toolbar."), + nls.localize('chat.customizations.location.chatInput', "Inside the chat input, after the model pickers and before the voice controls."), + ], + description: nls.localize('chat.customizations.location', "Controls where the Customizations button appears. Explicit choices override the default location."), + default: 'auto', + scope: ConfigurationScope.APPLICATION, + tags: ['experimental'], + experiment: { mode: 'startup' }, + }, [ChatConfiguration.ChatCustomizationsStructuredPreviewEnabled]: { type: 'boolean', tags: ['preview'], @@ -3312,6 +3348,8 @@ Registry.as(EditorExtensions.EditorFactory).registerEdit registerWorkbenchContribution2(CopilotTelemetryContribution.ID, CopilotTelemetryContribution, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(EditorChatUsageContribution.ID, EditorChatUsageContribution, WorkbenchPhase.BlockRestore); +registerWorkbenchContribution2(CustomAgentUsageContribution.ID, CustomAgentUsageContribution, WorkbenchPhase.BlockRestore); +registerWorkbenchContribution2(ChatDailyUsageContribution.ID, ChatDailyUsageContribution, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(ChatSpeechToTextInitContribution.ID, ChatSpeechToTextInitContribution, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(ChatResolverContribution.ID, ChatResolverContribution, WorkbenchPhase.BlockStartup); registerWorkbenchContribution2(ChatDebugResolverContribution.ID, ChatDebugResolverContribution, WorkbenchPhase.BlockStartup); @@ -3336,6 +3374,8 @@ registerWorkbenchContribution2(ChatImplicitContextContribution.ID, ChatImplicitC registerWorkbenchContribution2(ChatViewsWelcomeHandler.ID, ChatViewsWelcomeHandler, WorkbenchPhase.BlockStartup); registerWorkbenchContribution2(ChatGettingStartedContribution.ID, ChatGettingStartedContribution, WorkbenchPhase.Eventually); registerWorkbenchContribution2(ChatSetupContribution.ID, ChatSetupContribution, WorkbenchPhase.BlockRestore); +registerWorkbenchContribution2(ChatEntitlementSimulationContribution.ID, ChatEntitlementSimulationContribution, WorkbenchPhase.AfterRestored); +registerAction2(SimulateChatEntitlementAction); registerWorkbenchContribution2(ChatMicrosoftSignInProbeContribution.ID, ChatMicrosoftSignInProbeContribution, WorkbenchPhase.Eventually); registerWorkbenchContribution2(ChatQuotaNotificationContribution.ID, ChatQuotaNotificationContribution, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(ChatPromoNotificationContribution.ID, ChatPromoNotificationContribution, WorkbenchPhase.AfterRestored); @@ -3424,6 +3464,7 @@ registerSingleton(IVoiceCodeTranscriptionClient, VoiceCodeTranscriptionClient, I registerSingleton(IChatTransferService, ChatTransferService, InstantiationType.Delayed); registerSingleton(IChatService, ChatService, InstantiationType.Delayed); registerSingleton(IChatWidgetService, ChatWidgetService, InstantiationType.Delayed); +registerSingleton(IChatViewHostService, ChatViewHostService, InstantiationType.Delayed); registerSingleton(ISessionChatPillVisibilityService, SessionChatPillVisibility, InstantiationType.Delayed); registerSingleton(IChatSessionReviewPreferencesService, ChatSessionReviewPreferencesService, InstantiationType.Delayed); registerSingleton(IChatPasteTargetService, ChatPasteTargetService, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/chat/browser/chat.ts b/src/vs/workbench/contrib/chat/browser/chat.ts index 043aa7959850..25fd49ac10ee 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.ts @@ -5,6 +5,7 @@ import { IMouseWheelEvent } from '../../../../base/browser/mouseEvent.js'; import { Event } from '../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; import { IDisposable } from '../../../../base/common/lifecycle.js'; import { IObservable } from '../../../../base/common/observable.js'; import { isMobile, isWeb } from '../../../../base/common/platform.js'; @@ -18,6 +19,7 @@ import { EditDeltaInfo } from '../../../../editor/common/textModelEditSource.js' import { MenuId } from '../../../../platform/actions/common/actions.js'; import { IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { IKeybindings } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; import { PreferredGroup } from '../../../services/editor/common/editorService.js'; import type { IChatPillSection } from '../../../browser/chatPills.js'; import { IChatRequestVariableEntry } from '../common/attachments/chatVariableEntries.js'; @@ -125,6 +127,12 @@ export interface IChatWidgetService { */ revealWidget(preserveFocus?: boolean): Promise; + /** + * Shows the host of the Chat view's chats ({@link IChatViewHostService}): the Chat view, or what replaces it. Resolves to the + * widget of the chat it shows. + */ + revealChatView(preserveFocus?: boolean): Promise; + getAllWidgets(): ReadonlyArray; getWidgetByInputUri(uri: URI): IChatWidget | undefined; /** Opens or reveals a session, retaining its model while moving it between widgets. */ @@ -191,6 +199,9 @@ export interface IChatCodeBlockInfo { codemapperUri: URI | undefined; readonly chatSessionResource: URI | undefined; focus(): void; + readonly isFocused?: boolean; + /** Reveals hidden code without taking focus; returns whether its layout changed. */ + reveal?(): boolean; readonly languageId?: string | undefined; readonly editDeltaInfo?: EditDeltaInfo | undefined; } @@ -255,6 +266,8 @@ export interface IChatListItemRendererOptions { readonly progressMessageAction?: IObservable<{ readonly label: string; readonly run: () => void } | undefined>; readonly backgroundActivityPillSections?: IChatBackgroundActivityPillSections; readonly contentHorizontalPadding?: number; + /** Whether the list shows a session chat, which behaves as in the Agents window, in whatever window. */ + readonly isSessionsChat?: boolean; /** Collapses the first request under this label without changing its message or attachments. */ readonly firstRequestSummary?: string; /** @@ -262,6 +275,8 @@ export interface IChatListItemRendererOptions { * so command/tool output pasted by the model wraps instead of overflowing). */ readonly codeBlockRenderOptions?: ICodeBlockRenderOptions; + /** Enables isolated previews for explicit html-preview fences in responses. */ + readonly renderHtmlPreviews?: boolean; /** Presents responses as coming from this identity instead of the responding agent's own. */ readonly responseIdentity?: IChatResponseIdentity; } @@ -668,6 +683,14 @@ export interface IChatCodeBlockContextProviderService { export const ChatViewId = `workbench.panel.chat.view.${CHAT_PROVIDER_ID}`; export const ChatViewContainerId = 'workbench.panel.chat'; +/** The default keybindings of {@link ChatViewContainerId}, which toggles the Chat view. */ +export const ChatViewOpenKeybindings: IKeybindings = { + primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyI, + mac: { + primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KeyI + } +}; + export const HasInstalledAgentPluginsContext = new RawContextKey('hasInstalledAgentPlugins', false); export const InstalledAgentPluginsViewId = 'workbench.views.agentPlugins.installed'; diff --git a/src/vs/workbench/contrib/chat/browser/chatDailyUsage.contribution.ts b/src/vs/workbench/contrib/chat/browser/chatDailyUsage.contribution.ts new file mode 100644 index 000000000000..45152718517e --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatDailyUsage.contribution.ts @@ -0,0 +1,94 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IntervalTimer } from '../../../../base/common/async.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { MessageKind } from '../../../../platform/agentHost/common/state/protocol/state.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { ChatEntitlement, IChatEntitlementService, isProUser } from '../../../services/chat/common/chatEntitlementService.js'; +import { IHostService } from '../../../services/host/browser/host.js'; +import { ILifecycleService, LifecyclePhase } from '../../../services/lifecycle/common/lifecycle.js'; +import { IChatService } from '../common/chatService/chatService.js'; +import { ChatDailyUsage, IChatDailyUsageTelemetry } from '../common/chatDailyUsage.js'; + +type ChatDailyUsageEvent = IChatDailyUsageTelemetry & { + readonly plan: string; +}; + +type ChatDailyUsageClassification = { + plan: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Copilot plan of the signed-in user as a ChatEntitlement name, e.g. Free, Pro or Business.' }; + messagesLast7Days: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chat messages the user sent on this machine during the current and previous 6 UTC days.' }; + messagesLast30Days: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chat messages the user sent on this machine during the current and previous 29 UTC days.' }; + messagesTotal: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chat messages the user sent on this machine. Starts from editor chat messages and Agents Window session starts recorded before tracking began, so it is a lower bound.' }; + sessionsLast7Days: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chats and sessions the user started on this machine, by sending their first message, during the current and previous 6 UTC days.' }; + sessionsLast30Days: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chats and sessions the user started on this machine, by sending their first message, during the current and previous 29 UTC days.' }; + sessionsTotal: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Chats and sessions the user started on this machine. Starts from editor chat and Agents Window sessions recorded before tracking began.' }; + minutesSinceLastMessage: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Minutes since the user last sent a chat message on this machine. Includes editor chat messages and Agents Window session starts recorded before this event existed. Absent when no usage was recorded.' }; + trackedDays: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'UTC days since this machine started recording daily chat usage, capped at 30. The 7 and 30 day counts cover all of their days once this reaches 7 and 30.' }; + owner: 'benibenj'; + comment: 'Daily summary of chat messages and new chats or sessions across all windows on this machine, sent at most once per UTC day for users with a Copilot plan.'; +}; + +const reportCheckInterval = 60 * 60 * 1000; + +function hasCopilotPlan(entitlement: ChatEntitlement): boolean { + return entitlement === ChatEntitlement.Free || isProUser(entitlement); +} + +/** Records the user's chat messages and reports recent usage once per UTC day for users with a Copilot plan. */ +export class ChatDailyUsageContribution extends Disposable implements IWorkbenchContribution { + static readonly ID = 'workbench.contrib.chatDailyUsage'; + + constructor( + @IChatService chatService: IChatService, + @IStorageService storageService: IStorageService, + @ITelemetryService telemetryService: ITelemetryService, + @IHostService hostService: IHostService, + @ILifecycleService lifecycleService: ILifecycleService, + @IChatEntitlementService chatEntitlementService: IChatEntitlementService, + ) { + super(); + const usage = new ChatDailyUsage(storageService); + usage.startTracking(); + this._register(chatService.onDidAcceptRequest(event => { + // Messages an agent, tool or automation produced are not the user's own activity. + if (!event.agentHostMessageOrigin || event.agentHostMessageOrigin.kind === MessageKind.User) { + usage.recordMessage(event.isNewSession); + } + })); + + let startupCompleted = false; + const report = async () => { + const entitlement = chatEntitlementService.entitlement; + // Only a focused window tries to claim the day's report, and the atomic claim lets at most one window send it. + if (!startupCompleted || !hostService.hasFocus || !hasCopilotPlan(entitlement)) { + return; + } + const telemetry = await usage.takeDailyReport(); + if (telemetry) { + telemetryService.publicLog2('chatDailyUsage', { plan: ChatEntitlement[entitlement], ...telemetry }); + } + }; + const reportIfDue = () => { + report().catch(onUnexpectedError); + }; + this._register(hostService.onDidChangeFocus(focused => { + if (focused) { + reportIfDue(); + } + })); + this._register(chatEntitlementService.onDidChangeEntitlement(reportIfDue)); + this._register(new IntervalTimer()).cancelAndSet(reportIfDue, reportCheckInterval); + lifecycleService.when(LifecyclePhase.Eventually).then(() => { + if (!this._store.isDisposed) { + startupCompleted = true; + reportIfDue(); + } + }); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatDebug/media/chatDebug.css b/src/vs/workbench/contrib/chat/browser/chatDebug/media/chatDebug.css index e85f50cb89fa..d61b06e5d790 100644 --- a/src/vs/workbench/contrib/chat/browser/chatDebug/media/chatDebug.css +++ b/src/vs/workbench/contrib/chat/browser/chatDebug/media/chatDebug.css @@ -281,7 +281,7 @@ border: none; background: transparent; color: var(--vscode-foreground); - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); cursor: pointer; opacity: 0.7; flex-shrink: 0; @@ -482,7 +482,7 @@ font-size: 16px; line-height: 1; padding: 2px 6px; - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); opacity: 0.7; } .chat-debug-detail-button.monaco-button:hover { @@ -692,7 +692,7 @@ .chat-debug-section-copy-btn.monaco-button { flex-shrink: 0; opacity: 0.7; - border-radius: 3px; + border-radius: var(--workbench-custom-buttons-corner-radius, 3px); padding: 2px; background: none; border: none; diff --git a/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewSizing.ts b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewSizing.ts new file mode 100644 index 000000000000..fb1788dcdf4b --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewSizing.ts @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const CHAT_DOCKED_VIEW_MIN_HEIGHT = 40; +/** The height of a view whose webview has not reported its content height yet. */ +const DEFAULT_CONTENT_HEIGHT = 120; +const DEFAULT_MAX_AUTOMATIC_HEIGHT = 320; +const MAX_HEIGHT = 1000; +/** Dropping the resize edge within this distance of the content height (or the automatic height) follows the content. */ +const SNAP_DISTANCE = 10; + +/** + * How the user sized a docked view. + * + * A view follows its content height up to {@link maxAutomaticHeight}, unless the user dragged it to a + * {@link fixedHeight}. Dragging it back to its content height follows the content again and makes that + * height the new maximum, so content the user chose to see in full stays fully visible as it changes. + */ +export interface IChatDockedViewSize { + /** The height the user dragged the view to, or `undefined` to follow its content. */ + readonly fixedHeight: number | undefined; + readonly maxAutomaticHeight: number; +} + +export const defaultChatDockedViewSize: IChatDockedViewSize = { + fixedHeight: undefined, + maxAutomaticHeight: DEFAULT_MAX_AUTOMATIC_HEIGHT, +}; + +/** The height a view follows its content at. */ +export function getChatDockedViewAutomaticHeight(size: IChatDockedViewSize, contentHeight: number | undefined): number { + return Math.min(contentHeight ?? DEFAULT_CONTENT_HEIGHT, size.maxAutomaticHeight); +} + +/** The height a view is shown at. The space the chat has limits how much of the view shows, but does not change its size. */ +export function getChatDockedViewHeight(size: IChatDockedViewSize, contentHeight: number | undefined, availableHeight: number): number { + const height = size.fixedHeight ?? getChatDockedViewAutomaticHeight(size, contentHeight); + return Math.max(CHAT_DOCKED_VIEW_MIN_HEIGHT, Math.min(height, availableHeight)); +} + +/** + * The size after dragging the resize edge so that the view would be `requestedHeight` tall. + * @param start The size when the drag started. Each move derives the size from it, so moving back undoes a snap. + * @param startAutomaticHeight The automatic height when the drag started. + */ +export function resizeChatDockedView(start: IChatDockedViewSize, startAutomaticHeight: number, requestedHeight: number, contentHeight: number | undefined): IChatDockedViewSize { + const height = Math.min(MAX_HEIGHT, Math.max(CHAT_DOCKED_VIEW_MIN_HEIGHT, requestedHeight)); + if (contentHeight !== undefined && Math.abs(height - contentHeight) <= SNAP_DISTANCE) { + return { fixedHeight: undefined, maxAutomaticHeight: Math.max(DEFAULT_MAX_AUTOMATIC_HEIGHT, Math.min(MAX_HEIGHT, contentHeight)) }; + } + if (Math.abs(height - startAutomaticHeight) <= SNAP_DISTANCE) { + return { fixedHeight: undefined, maxAutomaticHeight: start.maxAutomaticHeight }; + } + return { fixedHeight: height, maxAutomaticHeight: start.maxAutomaticHeight }; +} diff --git a/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViews.ts b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViews.ts new file mode 100644 index 000000000000..fe23095706b8 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViews.ts @@ -0,0 +1,128 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { basename } from '../../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IJSONSchema, TypeFromJsonSchema } from '../../../../../base/common/jsonSchema.js'; +import * as nls from '../../../../../nls.js'; +import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { isProposedApiEnabled } from '../../../../services/extensions/common/extensions.js'; +import { ExtensionsRegistry } from '../../../../services/extensions/common/extensionsRegistry.js'; + +/** + * A view that an extension docks above the chat input of every chat whose + * resource exists. The resource is rendered by its custom editor, readonly. + */ +export interface IChatDockedViewContribution { + readonly extensionId: ExtensionIdentifier; + readonly id: string; + readonly label: string; + readonly icon: ThemeIcon | undefined; + /** A URI template; `${chatSessionId}` is replaced with {@link getChatDockedViewSessionId}. */ + readonly resource: string; +} + +/** The identifier substituted for `${chatSessionId}`: the last path segment of the chat session resource. */ +export function getChatDockedViewSessionId(sessionResource: URI): string { + return basename(sessionResource); +} + +export function resolveChatDockedViewResource(contribution: IChatDockedViewContribution, sessionResource: URI): URI | undefined { + try { + return URI.parse(contribution.resource.replaceAll('${chatSessionId}', encodeURIComponent(getChatDockedViewSessionId(sessionResource)))); + } catch { + return undefined; + } +} + +const chatDockedViewSchema = { + type: 'object', + additionalProperties: false, + required: ['id', 'label', 'resource'], + properties: { + id: { + type: 'string', + description: nls.localize('chatDockedViews.id', "Identifier of the docked view, unique within the extension."), + }, + label: { + type: 'string', + description: nls.localize('chatDockedViews.label', "Label of the pill that toggles the docked view."), + }, + icon: { + type: 'string', + description: nls.localize('chatDockedViews.icon', "Codicon of the pill, such as {0}.", '`$(checklist)`'), + }, + resource: { + type: 'string', + description: nls.localize('chatDockedViews.resource', "URI of the resource to show for a chat, such as `chat-todos:/${chatSessionId}.todo.json`. The view is offered while the resource exists and is rendered by the resource's custom editor."), + }, + }, +} as const satisfies IJSONSchema; + +type IRawChatDockedViewContribution = TypeFromJsonSchema; + +const chatDockedViewsExtensionPoint = ExtensionsRegistry.registerExtensionPoint({ + extensionPoint: 'chatDockedViews', + jsonSchema: { + description: nls.localize('vscode.extension.contributes.chatDockedViews', "Contributes views docked above the chat input, rendered from a per-chat resource by its custom editor."), + type: 'array', + items: chatDockedViewSchema, + }, +}); + +const contributions = observableValue('chatDockedViews', []); + +chatDockedViewsExtensionPoint.setHandler(extensions => { + const result: IChatDockedViewContribution[] = []; + for (const extension of extensions) { + if (!isProposedApiEnabled(extension.description, 'contribChatDockedViews')) { + extension.collector.error(`The 'chatDockedViews' contribution point requires the 'contribChatDockedViews' API proposal.`); + continue; + } + for (const raw of extension.value) { + if (typeof raw.id !== 'string' || typeof raw.label !== 'string' || typeof raw.resource !== 'string') { + extension.collector.error(`A chat docked view needs an 'id', a 'label', and a 'resource'.`); + continue; + } + result.push({ + extensionId: extension.description.identifier, + id: raw.id, + label: raw.label, + icon: raw.icon ? ThemeIcon.fromString(raw.icon) : undefined, + resource: raw.resource, + }); + } + } + contributions.set(result, undefined); +}); + +/** The docked views contributed by installed extensions. */ +export const chatDockedViewContributions: IObservable = contributions; + +export type ChatDockedViewsLayout = 'stack' | 'tabs'; +export const ChatDockedViewsLayoutSettingId = 'chat.dockedViews.layout'; + +Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ + id: 'chatDockedViews', + title: nls.localize('chatDockedViews.configurationTitle', "Chat Docked Views"), + type: 'object', + properties: { + [ChatDockedViewsLayoutSettingId]: { + type: 'string', + enum: ['stack', 'tabs'] satisfies ChatDockedViewsLayout[], + enumDescriptions: [ + nls.localize('chatDockedViews.layout.stack', "Each pill toggles its own view; open views stack above the pills."), + nls.localize('chatDockedViews.layout.tabs', "Pills act as tabs: one view is shown at a time, and clicking the selected pill collapses it."), + ], + default: 'stack', + tags: ['experimental'], + description: nls.localize('chatDockedViews.layout', "How views that extensions dock above the chat input share the space."), + }, + }, +}); diff --git a/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewsControl.ts b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewsControl.ts new file mode 100644 index 000000000000..2049e9a8dbfa --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatDockedViews/chatDockedViewsControl.ts @@ -0,0 +1,406 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/chatDockedViews.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { IActionViewItemOptions } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { Action } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, constObservable, derived, IObservable, ISettableObservable, mapObservableArrayCached, observableValue } from '../../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { localize } from '../../../../../nls.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { observableConfigValue } from '../../../../../platform/observable/common/platformObservableUtils.js'; +import { ChatPillActionViewItem, IChatPill } from '../../../../browser/chatPills.js'; +import { DEFAULT_EDITOR_ASSOCIATION } from '../../../../common/editor.js'; +import { IEditorResolverService } from '../../../../services/editor/common/editorResolverService.js'; +import { IExtensionService } from '../../../../services/extensions/common/extensions.js'; +import { CustomEditorInput } from '../../../customEditor/browser/customEditorInput.js'; +import { IChatInputPillSource } from '../chatInputPills.js'; +import { chatDockedViewContributions, ChatDockedViewsLayout, ChatDockedViewsLayoutSettingId, IChatDockedViewContribution, resolveChatDockedViewResource } from './chatDockedViews.js'; +import { defaultChatDockedViewSize, getChatDockedViewAutomaticHeight, getChatDockedViewHeight, IChatDockedViewSize, resizeChatDockedView } from './chatDockedViewSizing.js'; + +/** A contributed docked view resolved for one chat. */ +interface IChatDockedView { + /** Identifies the view across chats; stable across re-renders. */ + readonly key: string; + readonly contribution: IChatDockedViewContribution; + readonly resource: URI; +} + +/** The transcript height that docked views leave visible above them. */ +const MIN_TRANSCRIPT_HEIGHT = 80; +/** The height a docked view takes up besides its body: its resize edge, its border, and the gap to the next view. */ +const VIEW_CHROME_HEIGHT = 12; + +/** + * Docks extension-contributed views above a chat input and supplies the pills + * that toggle them. A view is offered while its per-chat resource exists and is + * rendered, readonly, by the resource's custom editor. + */ +export class ChatDockedViewsControl extends Disposable { + + readonly pillSources: IObservable; + /** The height the docked views take up, including their spacing. */ + readonly height: IObservable; + + /** In the stack layout: keys of views the user closed; views open when their resource appears. */ + private readonly _closed = observableValue>(this, new Set()); + /** In the tabs layout: the selected view key per chat, or `null` when the user collapsed the views; absent selects the first view. */ + private readonly _tabSelection = observableValue>(this, new Map()); + /** Sizes by view key, kept while the control lives so that hiding and showing a view keeps its size. */ + private readonly _sizes = new Map>(); + private readonly _shown: IObservable; + private readonly _sessionKey: IObservable; + private readonly _layout: IObservable; + + /** + * @param container Receives the docked views as its first child, so they appear above the pills that the container also hosts. + * @param chatElement The chat widget. The views never grow past the top of the element that clips it, and are clipped to that element. + */ + constructor( + container: HTMLElement, + chatElement: HTMLElement, + sessionResource: IObservable, + @IFileService private readonly _fileService: IFileService, + @IInstantiationService instantiationService: IInstantiationService, + @IConfigurationService configurationService: IConfigurationService, + ) { + super(); + const element = dom.$('.chat-docked-views'); + container.prepend(element); + this._register(toDisposable(() => element.remove())); + + this._layout = observableConfigValue(ChatDockedViewsLayoutSettingId, 'stack', configurationService); + this._sessionKey = derived(this, reader => sessionResource.read(reader)?.toString()); + const candidates = derived(this, reader => { + const session = sessionResource.read(reader); + if (!session) { + return []; + } + return chatDockedViewContributions.read(reader).flatMap(contribution => { + const resource = resolveChatDockedViewResource(contribution, session); + return resource ? [{ key: `${session.toString()}\u0000${contribution.extensionId.value}\u0000${contribution.id}`, contribution, resource }] : []; + }); + }); + const withExistence = mapObservableArrayCached(this, candidates, (view, store) => ({ + view, + exists: this._observeExists(view.resource, store), + }), view => view.key); + const available = derived(this, reader => withExistence.read(reader).filter(entry => entry.exists.read(reader)).map(entry => entry.view)); + this._shown = derived(this, reader => { + const views = available.read(reader); + if (this._layout.read(reader) === 'tabs') { + const session = this._sessionKey.read(reader); + const selected = session === undefined ? undefined : this._tabSelection.read(reader).get(session); + if (selected === null) { + return []; + } + const view = views.find(view => view.key === selected) ?? views[0]; + return view ? [view] : []; + } + const closed = this._closed.read(reader); + return views.filter(view => !closed.has(view.key)); + }); + + // The views float upwards from the pills, over the transcript and whatever else the chat's container shows above the input + // (such as the sessions list of an empty chat), so that container's top bounds them. It is looked up when measuring, because + // the chat widget may not be attached yet when this control is created. + const getBoundary = () => findClippingAncestor(chatElement); + const availableSpace = observableValue(this, Number.POSITIVE_INFINITY); + const height = observableValue(this, 0); + const layoutObserver = new (dom.getWindow(container).ResizeObserver)(() => { + height.set(element.offsetHeight, undefined); + // While no view shows, the element is not laid out; it is measured once it shows a view. + if (element.offsetHeight > 0) { + // The bottom edge stays put when the views resize, and moves with the chat input, which resizes then. + availableSpace.set(Math.max(0, element.getBoundingClientRect().bottom - getBoundary().getBoundingClientRect().top - MIN_TRANSCRIPT_HEIGHT), undefined); + } + }); + for (const observed of [element, chatElement, container.parentElement]) { + if (observed) { + layoutObserver.observe(observed); + } + } + this._register(toDisposable(() => layoutObserver.disconnect())); + this.height = height; + const availableHeightPerView = derived(this, reader => { + const shown = this._shown.read(reader).length; + return shown === 0 ? 0 : availableSpace.read(reader) / shown - VIEW_CHROME_HEIGHT; + }); + + const frames = mapObservableArrayCached(this, this._shown, (view, store) => + store.add(instantiationService.createInstance(ChatDockedViewFrame, view, this._getSize(view.key), availableHeightPerView, getBoundary)), view => view.key); + this._register(autorun(reader => { + dom.reset(element, ...frames.read(reader).map(frame => frame.element)); + })); + + this.pillSources = mapObservableArrayCached(this, available, (view, store) => this._createPillSource(view, store), view => view.key); + } + + private _getSize(key: string): ISettableObservable { + let size = this._sizes.get(key); + if (!size) { + size = observableValue(this, defaultChatDockedViewSize); + this._sizes.set(key, size); + } + return size; + } + + private _toggle(key: string): void { + const isShown = this._shown.get().some(view => view.key === key); + if (this._layout.get() === 'tabs') { + const session = this._sessionKey.get(); + if (session !== undefined) { + const selection = new Map(this._tabSelection.get()); + selection.set(session, isShown ? null : key); + this._tabSelection.set(selection, undefined); + } + return; + } + const closed = new Set(this._closed.get()); + if (isShown) { + closed.add(key); + } else { + closed.delete(key); + } + this._closed.set(closed, undefined); + } + + private _createPillSource(view: IChatDockedView, store: DisposableStore): IChatInputPillSource { + const isShown = derived(reader => this._shown.read(reader).some(shown => shown.key === view.key)); + const label = view.contribution.label; + const action = store.add(new Action( + `chatDockedViews.toggle.${view.contribution.extensionId.value}.${view.contribution.id}`, + label, + ThemeIcon.asClassName(view.contribution.icon ?? Codicon.layoutPanel), + true, + async () => this._toggle(view.key), + )); + store.add(autorun(reader => { + const shown = isShown.read(reader); + action.checked = shown; + action.tooltip = shown + ? localize('chatDockedViews.hide', "Hide {0}", label) + : localize('chatDockedViews.show', "Show {0}", label); + })); + const pill: IChatPill = { + action, + createActionViewItem: (options: IActionViewItemOptions) => new ChatDockedViewPillViewItem(undefined, action, options), + }; + return { hasData: constObservable(true), pills: constObservable([pill]) }; + } + + private _observeExists(resource: URI, store: DisposableStore): IObservable { + const exists = observableValue(this, false); + let version = 0; + const refresh = async () => { + const current = ++version; + let result = false; + try { + await this._fileService.activateProvider(resource.scheme); + result = await this._fileService.exists(resource); + } catch { + result = false; + } + if (current === version && !store.isDisposed) { + exists.set(result, undefined); + } + }; + store.add(this._fileService.onDidFilesChange(e => { + if (e.affects(resource)) { + void refresh(); + } + })); + store.add(this._fileService.onDidChangeFileSystemProviderRegistrations(e => { + if (e.scheme === resource.scheme) { + void refresh(); + } + })); + store.add(this._fileService.watch(resource)); + store.add(toDisposable(() => version++)); + void refresh(); + return exists; + } +} + +/** The element itself or its nearest ancestor that clips its content, which bounds what floats inside it. */ +function findClippingAncestor(element: HTMLElement): HTMLElement { + for (let current: HTMLElement | null = element; current; current = current.parentElement) { + if (dom.getComputedStyle(current).overflow !== 'visible') { + return current; + } + } + return element; +} + +/** Shows on its pill whether a docked view is shown. */ +class ChatDockedViewPillViewItem extends ChatPillActionViewItem { + override render(container: HTMLElement): void { + super.render(container); + this.updateChecked(); + } + + protected override updateChecked(): void { + this.element?.classList.toggle('chat-docked-view-pill-open', !!this.action.checked); + this.buttonElement?.setAttribute('aria-pressed', String(!!this.action.checked)); + } +} + +/** + * One docked view: the resource's custom editor in an overlay webview, sized + * as {@link IChatDockedViewSize} describes, with a resize edge on top. + */ +class ChatDockedViewFrame extends Disposable { + + readonly element: HTMLElement; + private readonly _body: HTMLElement; + private readonly _contentHeight = observableValue(this, undefined); + + constructor( + private readonly _view: IChatDockedView, + private readonly _size: ISettableObservable, + availableHeight: IObservable, + private readonly _getClippingContainer: () => HTMLElement, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IEditorResolverService private readonly _editorResolverService: IEditorResolverService, + @IExtensionService private readonly _extensionService: IExtensionService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + // The view is anchored to the pills below it, so its top edge is the one that moves. + const elements = dom.h('.chat-docked-view@root', [ + dom.h('.chat-docked-view-sash@sash', { role: 'separator', 'aria-orientation': 'horizontal' }), + dom.h('.chat-docked-view-body@body'), + ]); + this.element = elements.root; + this._body = elements.body; + this.element.setAttribute('aria-label', _view.contribution.label); + + const height = derived(this, reader => getChatDockedViewHeight(this._size.read(reader), this._contentHeight.read(reader), availableHeight.read(reader))); + this._register(autorun(reader => { + const size = this._size.read(reader); + this._body.style.height = `${height.read(reader)}px`; + this.element.classList.toggle('automatic-height', size.fixedHeight === undefined); + elements.sash.title = size.fixedHeight === undefined + ? localize('chatDockedViews.resizeAutomatic', "Follows its content up to {0}px. Drag to resize, double-click to reset.", size.maxAutomaticHeight) + : localize('chatDockedViews.resizeFixed', "Fixed at {0}px. Drag to its content height to follow the content again, double-click to reset.", Math.round(size.fixedHeight)); + })); + this._register(this._registerSash(elements.sash, height)); + void this._render(); + } + + private _registerSash(sash: HTMLElement, height: IObservable): DisposableStore { + const store = new DisposableStore(); + store.add(dom.addDisposableListener(sash, dom.EventType.POINTER_DOWN, (e: PointerEvent) => { + if (e.button !== 0) { + return; + } + e.preventDefault(); + sash.setPointerCapture(e.pointerId); + sash.classList.add('active'); + const drag = new DisposableStore(); + // Like the workbench sash: webview iframes would otherwise swallow the pointer while it passes over them. + // eslint-disable-next-line no-restricted-syntax + const iframes = [...sash.ownerDocument.getElementsByTagName('iframe')]; + for (const iframe of iframes) { + iframe.classList.add('pointer-events-disabled'); + } + drag.add(toDisposable(() => { + sash.classList.remove('active'); + for (const iframe of iframes) { + iframe.classList.remove('pointer-events-disabled'); + } + })); + const startY = e.clientY; + const startHeight = height.get(); + const startSize = this._size.get(); + const startAutomaticHeight = getChatDockedViewAutomaticHeight(startSize, this._contentHeight.get()); + drag.add(dom.addDisposableListener(sash, dom.EventType.POINTER_MOVE, (move: PointerEvent) => { + this._size.set(resizeChatDockedView(startSize, startAutomaticHeight, startHeight + startY - move.clientY, this._contentHeight.get()), undefined); + })); + drag.add(dom.addDisposableListener(sash, dom.EventType.POINTER_UP, () => drag.dispose())); + drag.add(dom.addDisposableListener(sash, 'lostpointercapture', () => drag.dispose())); + store.add(drag); + })); + store.add(dom.addDisposableListener(sash, dom.EventType.DBLCLICK, () => this._size.set(defaultChatDockedViewSize, undefined))); + return store; + } + + private async _render(): Promise { + const { resource, contribution } = this._view; + try { + const viewType = this._editorResolverService.getEditors(resource).find(editor => editor.id !== DEFAULT_EDITOR_ASSOCIATION.id)?.id; + if (!viewType) { + throw new Error(localize('chatDockedViews.noEditor', "No custom editor is registered for {0}.", resource.toString())); + } + await this._extensionService.activateByEvent(`onCustomEditor:${viewType}`); + if (this._store.isDisposed) { + return; + } + const input = CustomEditorInput.create(this._instantiationService, { + resource, + viewType, + webviewTitle: contribution.label, + preferredName: contribution.label, + iconPath: undefined, + }, undefined); + if (!(input instanceof CustomEditorInput)) { + input.dispose(); + return; + } + this._register(input); + await input.resolve(); + if (this._store.isDisposed) { + return; + } + this._attach(input); + } catch (error) { + this._logService.error(`[ChatDockedViews] Could not render ${resource.toString()}`, error); + dom.reset(this._body, dom.$('.chat-docked-view-error', undefined, toErrorMessage(error))); + } + } + + private _attach(input: CustomEditorInput): void { + const webview = input.webview; + const targetWindow = dom.getWindow(this.element); + // Webviews report the height of their document, which is the content height. + this._register(autorun(reader => { + const size = webview.intrinsicContentSize.read(reader); + if (size) { + this._contentHeight.set(size.height, undefined); + } + })); + + // Like MCP apps in chat, claim the overlay only while its anchor is visible. + let claimed = false; + const release = () => { + if (claimed) { + claimed = false; + webview.release(this); + } + }; + const observer = new targetWindow.IntersectionObserver(entries => { + if (entries.some(entry => entry.isIntersecting) && this._body.isConnected) { + webview.claim(this, targetWindow, undefined); + claimed = true; + webview.setAnchorElement(this._body, this._getClippingContainer()); + } else { + release(); + } + }); + observer.observe(this._body); + this._register(toDisposable(() => { + observer.disconnect(); + release(); + })); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatDockedViews/media/chatDockedViews.css b/src/vs/workbench/contrib/chat/browser/chatDockedViews/media/chatDockedViews.css new file mode 100644 index 000000000000..f90204e3acf9 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatDockedViews/media/chatDockedViews.css @@ -0,0 +1,64 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Docked views float above the pills, whose container lets clicks fall through to the transcript. */ +.chat-docked-views { + position: relative; + z-index: 1; + display: flex; + flex-direction: column; + gap: 4px; + pointer-events: auto; +} + +/* Padding rather than margin, so the measured height that the transcript reserves includes it. */ +.chat-docked-views:empty { + display: none; +} + +.chat-docked-views:not(:empty) { + padding-bottom: 4px; +} + +.chat-docked-view { + position: relative; + border: 1px solid var(--vscode-input-border, var(--vscode-widget-border, transparent)); + border-radius: 4px; + overflow: hidden; + background: var(--vscode-chat-list-background, var(--vscode-sideBar-background)); +} + +.chat-docked-view-body { + position: relative; +} + +.chat-docked-view-error { + padding: 6px 8px; + color: var(--vscode-errorForeground); +} + +.chat-docked-view-sash { + height: 6px; + cursor: ns-resize; + background: transparent; + border-bottom: 1px solid var(--vscode-widget-border, transparent); +} + +.chat-docked-view-sash:hover, +.chat-docked-view-sash.active { + background: var(--vscode-sash-hoverBorder); +} + +.chat-docked-view.automatic-height .chat-docked-view-sash { + border-bottom-style: dashed; +} + +.chat-pill-item.chat-docked-view-pill-open .chat-pill-button { + /* The pill button sets its colors inline. */ + background: var(--vscode-inputOption-activeBackground) !important; + color: var(--vscode-inputOption-activeForeground) !important; + outline: 1px solid var(--vscode-inputOption-activeBorder); + outline-offset: -1px; +} diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingActions.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingActions.ts index b950fd700bd7..63c20d460907 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingActions.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingActions.ts @@ -695,7 +695,7 @@ registerAction2(class EditAction extends Action2 { icon: Codicon.edit, keybinding: { primary: KeyCode.Enter, - when: ContextKeyExpr.and(ChatContextKeys.inChatSession, EditorContextKeys.textInputFocus.negate(), ChatContextKeys.readOnly.negate()), + when: ContextKeyExpr.and(ChatContextKeys.inChatSession, EditorContextKeys.textInputFocus.negate(), EditorContextKeys.hoverFocused.negate(), ChatContextKeys.readOnly.negate()), weight: KeybindingWeight.WorkbenchContrib, }, menu: [ diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingCodeEditorIntegration.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingCodeEditorIntegration.ts index d35f2a71cf3c..c9a61be5464a 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingCodeEditorIntegration.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingCodeEditorIntegration.ts @@ -46,7 +46,6 @@ import { LinkedList } from '../../../../../base/common/linkedList.js'; import { ChatEditingExplanationWidgetManager } from './chatEditingExplanationWidget.js'; import { IChatEditingExplanationModelManager } from './chatEditingExplanationModelManager.js'; import { IChatWidgetService } from '../chat.js'; -import { IViewsService } from '../../../../services/views/common/viewsService.js'; export interface IDocumentDiff2 extends IDocumentDiff { @@ -109,7 +108,6 @@ export class ChatEditingCodeEditorIntegration implements IModifiedFileEntryEdito @IChatEditingService _chatEditingService: IChatEditingService, @IChatEditingExplanationModelManager private readonly _explanationModelManager: IChatEditingExplanationModelManager, @IChatWidgetService private readonly _chatWidgetService: IChatWidgetService, - @IViewsService private readonly _viewsService: IViewsService, ) { this._diffLineDecorations = _editor.createDecorationsCollection(); const codeEditorObs = observableCodeEditor(_editor); @@ -121,7 +119,6 @@ export class ChatEditingCodeEditorIntegration implements IModifiedFileEntryEdito this._store.add(new ChatEditingExplanationWidgetManager( this._editor, this._chatWidgetService, - this._viewsService, this._explanationModelManager, this._entry.modifiedURI, )); diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorActions.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorActions.ts index db30fb2a7d12..f94069220ee3 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorActions.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorActions.ts @@ -36,7 +36,6 @@ import { ChatEditingExplanationWidgetManager } from './chatEditingExplanationWid import { IChatEditingExplanationModelManager, IExplanationDiffInfo } from './chatEditingExplanationModelManager.js'; import { DiffEditorViewModel } from '../../../../../editor/browser/widget/diffEditor/diffEditorViewModel.js'; import { IChatWidgetService } from '../chat.js'; -import { IViewsService } from '../../../../services/views/common/viewsService.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; import { Event } from '../../../../../base/common/event.js'; @@ -487,7 +486,6 @@ class ExplainMultiDiffAction extends Action2 { const editorService = accessor.get(IEditorService); const explanationModelManager = accessor.get(IChatEditingExplanationModelManager); const chatWidgetService = accessor.get(IChatWidgetService); - const viewsService = accessor.get(IViewsService); const chatEditingService = accessor.get(IChatEditingService); const activePane = editorService.activeEditorPane; @@ -610,7 +608,6 @@ class ExplainMultiDiffAction extends Action2 { const manager = new ChatEditingExplanationWidgetManager( fileData.editor, chatWidgetService, - viewsService, explanationModelManager, diffInfo.modifiedModel.uri, ); diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorOverlay.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorOverlay.ts index 92d515561a7b..101fbfc12bc7 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorOverlay.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingEditorOverlay.ts @@ -110,7 +110,7 @@ class ChatEditorOverlayWidget extends Disposable { private readonly _session = observableValue(this, undefined); private readonly _entry = observableValue(this, undefined); - private readonly _isBusy: IObservable; + readonly isBusy: IObservable; private readonly _navigationBearings = observableValue<{ changeCount: number; activeIdx: number; entriesCount: number }>(this, { changeCount: -1, activeIdx: -1, entriesCount: -1 }); @@ -123,7 +123,7 @@ class ChatEditorOverlayWidget extends Disposable { this._domNode = document.createElement('div'); this._domNode.classList.add('chat-editor-overlay-widget'); - this._isBusy = derived(r => { + this.isBusy = derived(r => { const entry = this._entry.read(r); return entry?.waitsForLastEdits.read(r); }); @@ -136,7 +136,7 @@ class ChatEditorOverlayWidget extends Disposable { this._domNode.appendChild(progressNode); this._store.add(autorun(r => { - const busy = this._isBusy.read(r); + const busy = this.isBusy.read(r); this._domNode.classList.toggle('busy', busy); textProgress.innerText = ''; @@ -248,7 +248,7 @@ class ChatEditorOverlayWidget extends Disposable { } else { result = localize('tooltip_nm', "{0} changes in {1} files", changeCount, entriesCount); } - if (!that._isBusy.get()) { + if (!that.isBusy.get()) { return result; } return localize('tooltip_busy', "{0} - Working...", result); @@ -300,6 +300,11 @@ class ChatEditingOverlayController { this._store.add(toDisposable(() => this._domNode.remove())); this._store.add(widget); + // The busy pulse is drawn on this unclipped host because the widget clips its overflow + this._store.add(autorun(r => { + this._domNode.classList.toggle('busy', !!widget.isBusy.read(r)); + })); + const show = () => { if (!container.contains(this._domNode)) { container.appendChild(this._domNode); diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingExplanationWidget.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingExplanationWidget.ts index 2edef286585f..82ca84c9a6ed 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingExplanationWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingExplanationWidget.ts @@ -20,8 +20,7 @@ import { overviewRulerRangeHighlight } from '../../../../../editor/common/core/e import { IEditorDecorationsCollection } from '../../../../../editor/common/editorCommon.js'; import { OverviewRulerLane } from '../../../../../editor/common/model.js'; import { themeColorFromId } from '../../../../../platform/theme/common/themeService.js'; -import { ChatViewId, IChatWidget, IChatWidgetService } from '../chat.js'; -import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { IChatWidget, IChatWidgetService } from '../chat.js'; import * as nls from '../../../../../nls.js'; import { IExplanationDiffInfo, IChangeExplanation as IChangeExplanationModel, IChatEditingExplanationModelManager } from './chatEditingExplanationModelManager.js'; import { autorun } from '../../../../../base/common/observable.js'; @@ -134,7 +133,6 @@ export class ChatEditingExplanationWidget extends Disposable implements IOverlay private _changes: readonly (LineRangeMapping | DetailedLineRangeMapping)[], diffInfo: IExplanationDiffInfo, private readonly _chatWidgetService: IChatWidgetService, - private readonly _viewsService: IViewsService, private readonly _chatSessionResource?: URI, ) { super(); @@ -355,8 +353,7 @@ export class ChatEditingExplanationWidget extends Disposable implements IOverlay if (this._chatSessionResource) { chatWidget = await this._chatWidgetService.openSession(this._chatSessionResource); } else { - await this._viewsService.openView(ChatViewId, true); - chatWidget = this._chatWidgetService.lastFocusedWidget; + chatWidget = await this._chatWidgetService.revealChatView(false); } if (chatWidget) { chatWidget.attachmentModel.addContext( @@ -550,7 +547,6 @@ export class ChatEditingExplanationWidgetManager extends Disposable { constructor( private readonly _editor: ICodeEditor, private readonly _chatWidgetService: IChatWidgetService, - private readonly _viewsService: IViewsService, modelManager: IChatEditingExplanationModelManager, private readonly _modelUri: URI, ) { @@ -615,7 +611,6 @@ export class ChatEditingExplanationWidgetManager extends Disposable { group, diffInfo, this._chatWidgetService, - this._viewsService, chatSessionResource, ); this._widgets.push(widget); diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedDocumentEntry.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedDocumentEntry.ts index 81c83d8cf3a6..3822d049719c 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedDocumentEntry.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingModifiedDocumentEntry.ts @@ -167,7 +167,7 @@ export class ChatEditingModifiedDocumentEntry extends AbstractChatEditingModifie this._register(this._textModelChangeService.onDidUserEditModel(() => { this._userEditScheduler.schedule(); const didResetToOriginalContent = this.modifiedModel.getValue() === this.initialContent; - if (this._stateObs.get() === ModifiedFileEntryState.Modified && didResetToOriginalContent) { + if (this._stateObs.get() === ModifiedFileEntryState.Modified && didResetToOriginalContent && this._rejectsWhenResetToInitialContent()) { this._stateObs.set(ModifiedFileEntryState.Rejected, undefined); } })); @@ -237,6 +237,11 @@ export class ChatEditingModifiedDocumentEntry extends AbstractChatEditingModifie this._textModelChangeService.setOriginalToModifiedEdit(edit); } + /** Whether the entry is rejected once the user's edits return the document to its initial content. */ + protected _rejectsWhenResetToInitialContent(): boolean { + return true; + } + protected override async _areOriginalAndModifiedIdentical(): Promise { return this._textModelChangeService.areOriginalAndModifiedIdentical(); } diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingSessionStorage.ts b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingSessionStorage.ts index ce9472fa96b4..8fd4dad8bf56 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingSessionStorage.ts +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/chatEditingSessionStorage.ts @@ -28,6 +28,22 @@ export interface StoredSessionState { readonly timeline: IChatEditingTimelineState | undefined; } +/** + * Whether the state holds nothing beyond what a new editing session starts + * with: no file contents, no entries, and a timeline with only its initial + * checkpoint. + */ +function isEmptySessionState(state: StoredSessionState): boolean { + const timeline = state.timeline; + return state.initialFileContents.size === 0 + && state.recentSnapshot.entries.size === 0 + && (!timeline || ( + timeline.operations.length === 0 + && timeline.fileBaselines.length === 0 + && timeline.checkpoints.every(checkpoint => checkpoint.requestId === undefined) + )); +} + export class ChatEditingSessionStorage { private readonly storageKey: string; constructor( @@ -122,6 +138,11 @@ export class ChatEditingSessionStorage { } public async storeState(state: StoredSessionState): Promise { + if (isEmptySessionState(state)) { + // Nothing to restore: don't leave a folder behind for every session that never edited. + return this.clearState(); + } + const storageFolder = this._getStorageLocation(); const contentsFolder = URI.joinPath(storageFolder, STORAGE_CONTENTS_FOLDER); diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditingEditorOverlay.css b/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditingEditorOverlay.css index 29210950e00a..3f10df278b27 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditingEditorOverlay.css +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditingEditorOverlay.css @@ -18,20 +18,63 @@ overflow: hidden; } -@keyframes pulse { +@keyframes chat-editor-overlay-busy-pulse-in { 0% { - box-shadow: var(--vscode-shadow-md); + opacity: 0; } 50% { - box-shadow: var(--vscode-shadow-lg); + opacity: 1; } 100% { - box-shadow: var(--vscode-shadow-md); + opacity: 0; + } +} + +@keyframes chat-editor-overlay-busy-pulse-out { + 0% { + opacity: 1; + } + 50% { + opacity: 0; + } + 100% { + opacity: 1; } } -.chat-editor-overlay-widget.busy { - animation: pulse ease-in 2.3s infinite; +/* + * Crossfade static shadow layers instead of animating box-shadow, which repaints every frame. + * The layers live on the host because the widget clips its overflow. + */ +.chat-editing-editor-overlay.busy > .chat-editor-overlay-widget { + box-shadow: none; +} + +.chat-editing-editor-overlay.busy::before, +.chat-editing-editor-overlay.busy::after { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: 6px; /* same as overlay widget */ + pointer-events: none; + animation: ease-in 2.3s infinite; +} + +.chat-editing-editor-overlay.busy::before { + box-shadow: var(--vscode-shadow-md); + animation-name: chat-editor-overlay-busy-pulse-out; +} + +.chat-editing-editor-overlay.busy::after { + box-shadow: var(--vscode-shadow-lg); + opacity: 0; + animation-name: chat-editor-overlay-busy-pulse-in; +} + +.monaco-reduce-motion .chat-editing-editor-overlay.busy::before, +.monaco-reduce-motion .chat-editing-editor-overlay.busy::after { + animation: none; } .chat-editor-overlay-widget .chat-editor-overlay-progress { @@ -63,7 +106,7 @@ padding: 4px 6px; font-size: 11px; line-height: 14px; - border-radius: 4px; /* same as overlay widget */ + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); /* same as overlay widget */ } .chat-editor-overlay-widget .monaco-action-bar .actions-container { diff --git a/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditorController.css b/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditorController.css index 5e5b64f1fcdc..a25e8c93a6e9 100644 --- a/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditorController.css +++ b/src/vs/workbench/contrib/chat/browser/chatEditing/media/chatEditorController.css @@ -30,7 +30,7 @@ } .chat-diff-change-content-widget .monaco-action-bar .action-item .action-label { - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); font-size: 11px; line-height: 14px; padding: 4px 6px; diff --git a/src/vs/workbench/contrib/chat/browser/chatImageActions.ts b/src/vs/workbench/contrib/chat/browser/chatImageActions.ts index 11bc5e434d22..b071ee9c2a19 100644 --- a/src/vs/workbench/contrib/chat/browser/chatImageActions.ts +++ b/src/vs/workbench/contrib/chat/browser/chatImageActions.ts @@ -32,7 +32,7 @@ export function createChatImageCopyActions(accessor: ServicesAccessor, widget: H const labelService = accessor.get(ILabelService); const webContentExtractorService = accessor.get(ISharedWebContentExtractorService); return () => { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const image = widget instanceof HTMLImageElement || widget instanceof getWindow(widget).HTMLImageElement ? widget : widget.querySelector('img'); const canCopy = !!readData || !!image?.complete && image.naturalWidth > 0; diff --git a/src/vs/workbench/contrib/chat/browser/chatInputPills.ts b/src/vs/workbench/contrib/chat/browser/chatInputPills.ts index 0dbea06845ad..557a937ef09c 100644 --- a/src/vs/workbench/contrib/chat/browser/chatInputPills.ts +++ b/src/vs/workbench/contrib/chat/browser/chatInputPills.ts @@ -488,12 +488,16 @@ export class ChatInputPills extends Disposable { })); this._register(this._row.onDidRequestContextMenu(anchor => showContextMenu(anchor, this._getTarget(anchor)))); - derived(this, reader => { + const rowState = derived(this, reader => { const anyVisible = this._pills.isVisible.read(reader); // The empty row only restores pills the user hid or filtered; default-hidden kinds never claimed room in the row. const anyRestorable = [...kindsWithData.read(reader)].some(kind => this._visibility.isVisible(kind, reader) || !isSessionChatPillHiddenByDefault(kind)); return anyVisible ? 'visible' : anyRestorable ? 'empty' : 'hidden'; - }).recomputeInitiallyAndOnChange(this._store, state => { + }); + // Only touch the DOM when the row state changes: the sources update often (e.g. while a response streams), + // and pill size changes are already rescanned by the row's resize observer. + this._register(autorun(reader => { + const state = rowState.read(reader); const activeElement = getWindow(this._row.content).document.activeElement; const restoreInputFocus = state === 'hidden' && !!activeElement && this._row.content.contains(activeElement); const visible = state !== 'hidden'; @@ -507,7 +511,7 @@ export class ChatInputPills extends Disposable { if (restoreInputFocus) { this._row.restoreFocus(() => this._pills.getPillElements(), _options.focusFallback); } - }); + })); } get visible(): boolean { @@ -518,6 +522,11 @@ export class ChatInputPills extends Disposable { return this._pills.getPillElements(); } + /** Surfaces for the chat pet: each pill together with any segments joined to it, such as integration status. */ + getPillItemElements(): readonly HTMLElement[] { + return this._pills.getPillItemElements(); + } + focusFirst(): boolean { return this._pills.focusFirst(); } diff --git a/src/vs/workbench/contrib/chat/browser/chatOutputItemRenderer.ts b/src/vs/workbench/contrib/chat/browser/chatOutputItemRenderer.ts index 95cf50544a75..3096ff109a00 100644 --- a/src/vs/workbench/contrib/chat/browser/chatOutputItemRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/chatOutputItemRenderer.ts @@ -164,7 +164,7 @@ export class ChatOutputRendererService extends Disposable implements IChatOutput })); webview.setContextKeyService(store.add(this._contextKeyService.createScoped(parent))); if (webviewOptions.chatSessionResource) { - store.add(this.delegateScrollToChatWidget(webview, webviewOptions.chatSessionResource)); + store.add(delegateWebviewScrollToChatWidget(webview, webviewOptions.chatSessionResource, this._chatWidgetService)); } const onDidChangeHeight = store.add(new Emitter()); @@ -195,16 +195,6 @@ export class ChatOutputRendererService extends Disposable implements IChatOutput }; } - private delegateScrollToChatWidget(webview: IWebview, chatSessionResource: URI): IDisposable { - return webview.onDidWheel(e => { - this._chatWidgetService.getWidgetBySessionResource(chatSessionResource)?.delegateScrollFromMouseWheelEvent({ - ...e, - preventDefault: () => { }, - stopPropagation: () => { } - }); - }); - } - private getOrigin(rendererData: RendererEntry): string | undefined { return rendererData.options.extension ? this._originStore.getOrigin(rendererData.viewType, rendererData.options.extension.id) : undefined; } @@ -261,6 +251,16 @@ export class ChatOutputRendererService extends Disposable implements IChatOutput } } +export function delegateWebviewScrollToChatWidget(webview: IWebview, chatSessionResource: URI, chatWidgetService: IChatWidgetService): IDisposable { + return webview.onDidWheel(e => { + chatWidgetService.getWidgetBySessionResource(chatSessionResource)?.delegateScrollFromMouseWheelEvent({ + ...e, + preventDefault: () => { }, + stopPropagation: () => { } + }); + }); +} + const chatOutputRendererContributionSchema = { type: 'object', additionalProperties: false, diff --git a/src/vs/workbench/contrib/chat/browser/chatParticipant.contribution.ts b/src/vs/workbench/contrib/chat/browser/chatParticipant.contribution.ts index 892008422327..51b9d6b799d5 100644 --- a/src/vs/workbench/contrib/chat/browser/chatParticipant.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chatParticipant.contribution.ts @@ -30,7 +30,7 @@ import { IChatAgentData, IChatAgentService } from '../common/participants/chatAg import { ChatContextKeys } from '../common/actions/chatContextKeys.js'; import { IRawChatParticipantContribution } from '../common/participants/chatParticipantContribTypes.js'; import { ChatAgentLocation, ChatModeKind } from '../common/constants.js'; -import { ChatViewId, ChatViewContainerId } from './chat.js'; +import { ChatViewId, ChatViewContainerId, ChatViewOpenKeybindings } from './chat.js'; import { ChatViewPane } from './widgetHosts/viewPane/chatViewPane.js'; import { ChatUpdateRequiredView } from './viewsWelcome/chatUpdateRequiredView.js'; import { MANAGED_SETTINGS_UPDATE_VIEW_ID, ManagedSettingsUpdateRequiredContext } from '../../../services/policies/common/managedSettingsUpdate.js'; @@ -61,16 +61,13 @@ const chatViewDescriptor: IViewDescriptor = { id: ChatViewContainerId, title: chatViewContainer.title, mnemonicTitle: localize({ key: 'miToggleChat', comment: ['&& denotes a mnemonic'] }, "&&Chat"), - keybindings: { - primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyI, - mac: { - primary: KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KeyI - } - }, + keybindings: ChatViewOpenKeybindings, order: 1 }, ctorDescriptor: new SyncDescriptor(ChatViewPane), when: ContextKeyExpr.and( + // The chat part of an editor window with the Agents view replaces it + ChatContextKeys.agentsViewActive.negate(), ChatContextKeys.accountPolicyGateActive.negate(), ContextKeyExpr.or( ContextKeyExpr.and( @@ -92,7 +89,7 @@ Registry.as(ViewExtensions.ViewsRegistry).registerViews([{ canToggleVisibility: false, canMoveView: false, ctorDescriptor: new SyncDescriptor(ChatUpdateRequiredView), - when: ManagedSettingsUpdateRequiredContext, + when: ContextKeyExpr.and(ChatContextKeys.agentsViewActive.negate(), ManagedSettingsUpdateRequiredContext), openCommandActionDescriptor: { id: 'workbench.action.chat.showUpdateRequired', title: localize2('chat.updateRequiredView', "Chat Update Requirement"), diff --git a/src/vs/workbench/contrib/chat/browser/chatProgressConfiguration.ts b/src/vs/workbench/contrib/chat/browser/chatProgressConfiguration.ts index c864961f47b1..7d3c26782146 100644 --- a/src/vs/workbench/contrib/chat/browser/chatProgressConfiguration.ts +++ b/src/vs/workbench/contrib/chat/browser/chatProgressConfiguration.ts @@ -50,9 +50,9 @@ export const chatProgressConfigurationProperties = { enumDescriptions: [ localize('chat.progressVerbosity.verbose', "Keep tool calls in expanded, headerless chains without an internal scrolling limit."), localize('chat.progressVerbosity.compact', "Preview tool calls while they run, then collapse each group to a single expandable summary row when the response moves on."), - localize('chat.progressVerbosity.conversation', "Collapse reasoning and tool calls together into a single section that names the current tool call or reasoning heading while it runs, then shows a generated summary or Finished thinking once it finishes."), + localize('chat.progressVerbosity.conversation', "Collapse reasoning and tool calls together into a single section that names the current tool call or reasoning heading while it runs. Once it finishes, it shows what its tool calls did, followed by the time it took when known, or how long it thought when it has no tool calls."), ], - markdownDescription: localize('chat.experimental.persistentProgressVerbosity', "Control tool call details when {0} is enabled. Compact is the default and collapses tool groups in place when thinking or response text resumes, or the response finishes. When Agent Host activity data is available, headers summarize up to three activity groups, prioritizing edits and commands, without language model requests. Remaining activity is counted as other steps. Failed, skipped, denied, and unfinished tool invocations remain explicit, including in the other-steps count. Completed shell invocations count as commands without tracking later background process status. Groups with no recognized activity or outcome use a step count. Expand a summary to inspect all its tool calls. Conversation collapses reasoning and tool calls between response text into one section that starts collapsed, names the current tool call, or the heading of the current reasoning summary (Thinking when the reasoning has no heading), while it runs, and shows a generated summary or Finished thinking once it finishes. Has no effect when persistent progress is Off. Changes apply immediately.", `\`#${ChatConfiguration.PersistentProgress}#\``), + markdownDescription: localize('chat.experimental.persistentProgressVerbosity', "Control tool call details when {0} is enabled. Compact is the default and collapses tool groups in place when thinking or response text resumes, or the response finishes. When Agent Host activity data is available, headers summarize up to three activity groups, prioritizing edits and commands, without language model requests. Remaining activity is counted as other steps. Failed, skipped, denied, and unfinished tool invocations remain explicit, including in the other-steps count. Completed shell invocations count as commands without tracking later background process status. Groups with no recognized activity or outcome use a step count. Expand a summary to inspect all its tool calls. Conversation collapses reasoning and tool calls between response text into one section that starts collapsed, names the current tool call, or the heading of the current reasoning summary (Thinking, followed by the first line of the reasoning on a single row, when the reasoning has no heading), while it runs. Once it finishes, its header shows what its tool calls did, such as how many commands ran and which files were read or edited, followed by the time its reasoning and tool calls took when all of it was recorded. A section without tool calls shows how long it thought instead. A finished section never uses a reasoning heading or a generated summary as its header. Inside a section with tool calls, each reasoning run is a collapsible row naming how long it thought. Has no effect when persistent progress is Off. Changes apply immediately.", `\`#${ChatConfiguration.PersistentProgress}#\``), tags: ['experimental'], experiment: { mode: 'auto', name: `config.${legacyPersistentProgressVerbositySetting}` }, }, @@ -77,7 +77,7 @@ export const legacyChatThinkingConfigurationProperties = { [ChatConfiguration.ThinkingGenerateTitles]: { type: 'boolean', default: true, - description: localize('chat.agent.thinking.generateTitles', "Generate a summary only when a live thinking section finishes with its header in view. A single extracted reasoning heading is used directly without a model request; multiple headings are used as summary input. Opening a chat, returning to it, scrolling or expanding existing sections never generates titles. Sections that finish off-screen or in background chats keep their existing title or Finished thinking."), + description: localize('chat.agent.thinking.generateTitles', "Generate a summary only when a live thinking section finishes with its header in view. A single extracted reasoning heading is used directly without a model request; multiple headings are used as summary input. Opening a chat, returning to it, scrolling or expanding existing sections never generates titles. Sections that finish off-screen or in background chats keep their existing title or Finished thinking. Conversation sections never use a reasoning heading or a generated summary as their title."), tags: ['experimental'], }, 'chat.agent.thinking.collapsedTools': { diff --git a/src/vs/workbench/contrib/chat/browser/chatQuotaNotification.ts b/src/vs/workbench/contrib/chat/browser/chatQuotaNotification.ts index 58eb58d6aaba..4b080d84d3b9 100644 --- a/src/vs/workbench/contrib/chat/browser/chatQuotaNotification.ts +++ b/src/vs/workbench/contrib/chat/browser/chatQuotaNotification.ts @@ -342,12 +342,20 @@ export class ChatQuotaNotificationContribution extends Disposable implements IWo description: localize('quota.approaching.switchToAuto', "Switch to Auto to reduce credit usage."), actions: [{ kind: ChatInputNotificationActionKind.SwitchToModel, label: localize('switchToAuto', "Switch to Auto"), matchesModel: isAutoLanguageModel }], }; + const fusionBody: IChatInputNotificationBody = { + description: localize('quota.approaching.switchToFusion', "Switch to Copilot Fusion to reduce credit usage."), + actions: [{ kind: ChatInputNotificationActionKind.SwitchToModel, label: localize('switchToFusion', "Switch to Copilot Fusion"), matchesModel: isAutoLanguageModel }], + }; const resolveBody: IChatInputNotification['resolveBody'] = context => { if (!isAutoEligible(context)) { return defaultBody; } this._requestSwitchToAutoTreatment(); - return this._switchToAutoTreatment === true ? autoBody : defaultBody; + if (this._switchToAutoTreatment !== true) { + return defaultBody; + } + // Agent hosts present their Auto as Copilot Fusion when the catalog advertises it. + return context.modelState.models.some(model => isAutoLanguageModel(model) && model.metadata.autoModelFusion) ? fusionBody : autoBody; }; this._setQuotaApproachingNotification(warning, description, actions, resolveBody); diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContent.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContent.ts new file mode 100644 index 000000000000..948a8f7dd100 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContent.ts @@ -0,0 +1,243 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../base/browser/dom.js'; +import { CancellationError } from '../../../../../base/common/errors.js'; +import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { autorun, IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IEditorConstructionOptions } from '../../../../../editor/browser/config/editorConfiguration.js'; +import { EditorExtensionsRegistry } from '../../../../../editor/browser/editorExtensions.js'; +import { CodeEditorWidget, ICodeEditorWidgetOptions } from '../../../../../editor/browser/widget/codeEditor/codeEditorWidget.js'; +import { ITextModelService } from '../../../../../editor/common/services/resolverService.js'; +import { ContextMenuController } from '../../../../../editor/contrib/contextmenu/browser/contextmenu.js'; +import { ContentHoverController } from '../../../../../editor/contrib/hover/browser/contentHoverController.js'; +import { localize } from '../../../../../nls.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { DEFAULT_EDITOR_ASSOCIATION } from '../../../../common/editor.js'; +import { MenuPreventer } from '../../../codeEditor/browser/menuPreventer.js'; +import { SelectionClipboardContributionID } from '../../../codeEditor/browser/selectionClipboard.js'; +import { CustomEditorInput } from '../../../customEditor/browser/customEditorInput.js'; +import { ICustomEditorService } from '../../../customEditor/common/customEditor.js'; +import { IEditorResolverService } from '../../../../services/editor/common/editorResolverService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IExtensionService } from '../../../../services/extensions/common/extensions.js'; + +/** What a embedded resource shows. */ +export interface IChatResourceTarget { + readonly resource: URI; + readonly label: string; +} + +/** The content of a embedded resource, rendered into the view's body. */ +export interface IChatResourceContent extends Disposable { + /** The height the content needs, or `undefined` until it is known. */ + readonly contentHeight: IObservable; + layout(width: number, height: number): void; +} + +/** + * Renders a resource with the editor that opens it by default: its custom editor when that is the default (such as an + * extension's view or an image preview), and a readonly text editor otherwise. + * @param owner Owns the content from its creation on, so that disposing it while the content loads disposes the content. + */ +export async function createChatResourceContent( + target: IChatResourceTarget, + body: HTMLElement, + getClippingContainer: () => HTMLElement, + instantiationService: IInstantiationService, + owner: DisposableStore, +): Promise { + return instantiationService.invokeFunction(async accessor => { + const defaultEditor = accessor.get(IEditorResolverService).getEditorMatches(target.resource).defaultRule.editor.id; + if (defaultEditor !== DEFAULT_EDITOR_ASSOCIATION.id) { + const customEditorService = accessor.get(ICustomEditorService); + await accessor.get(IExtensionService).activateByEvent(`onCustomEditor:${defaultEditor}`); + if (owner.isDisposed) { + throw new CancellationError(); + } + // Only custom editors that an extension provides render in a webview here; other editors, such as notebooks, show + // the resource as text. + const capabilities = customEditorService.getCustomEditorCapabilities(defaultEditor); + if (capabilities) { + return whenReady(owner.add(instantiationService.createInstance(ChatResourceWebviewContent, target, defaultEditor, !capabilities.supportsMultipleEditorsPerDocument, body, getClippingContainer))); + } + } + return whenReady(owner.add(instantiationService.createInstance(ChatResourceTextContent, target.resource, body))); + }); +} + +/** The content once it is ready; content that fails to get ready is disposed. */ +async function whenReady }>(content: T): Promise { + try { + return await content.ready(); + } catch (error) { + content.dispose(); + throw error; + } +} + + +const editorContributions = () => EditorExtensionsRegistry.getSomeEditorContributions([ + MenuPreventer.ID, + SelectionClipboardContributionID, + ContextMenuController.ID, + ContentHoverController.ID, +]); + +const embeddedEditorOptions: IEditorConstructionOptions = { + // The resource is a document, so it looks like it does in an editor, rather than like the input boxes of the part around the chat. + extraEditorClassName: 'keep-editor-background', + readOnly: true, + scrollBeyondLastLine: false, + // The chat is narrow: wrapping keeps whole lines in view, especially prose such as Markdown. + wordWrap: 'on', + minimap: { enabled: false }, + stickyScroll: { enabled: false }, + lineNumbersMinChars: 3, + glyphMargin: false, + folding: false, + renderLineHighlight: 'none', + overviewRulerLanes: 0, + scrollbar: { alwaysConsumeMouseWheel: false, useShadows: false }, + automaticLayout: false, +}; + +/** A text resource in a readonly code editor, showing the document an editor of the resource edits, including unsaved changes. */ +class ChatResourceTextContent extends Disposable implements IChatResourceContent { + private readonly _contentHeight = observableValue(this, undefined); + readonly contentHeight: IObservable = this._contentHeight; + private readonly _editor: CodeEditorWidget; + + constructor( + private readonly _resource: URI, + body: HTMLElement, + @IInstantiationService instantiationService: IInstantiationService, + @ITextModelService private readonly _textModelService: ITextModelService, + ) { + super(); + const options: ICodeEditorWidgetOptions = { isSimpleWidget: false, contributions: editorContributions() }; + this._editor = this._register(instantiationService.createInstance(CodeEditorWidget, body, embeddedEditorOptions, options)); + this._register(this._editor.onDidContentSizeChange(() => this._contentHeight.set(this._editor.getContentHeight(), undefined))); + } + + async ready(): Promise { + const reference = await this._textModelService.createModelReference(this._resource); + if (this._store.isDisposed) { + reference.dispose(); + return this; + } + this._register(reference); + this._editor.setModel(reference.object.textEditorModel); + this._contentHeight.set(this._editor.getContentHeight(), undefined); + return this; + } + + layout(width: number, height: number): void { + this._editor.layout({ width, height }); + } +} + +/** + * A resource rendered by its custom editor in an overlay webview anchored to the view's body. A custom editor that supports + * only one editor per document is not rendered while an editor shows the resource, so that it gets no second instance. + */ +class ChatResourceWebviewContent extends Disposable implements IChatResourceContent { + private readonly _contentHeight = observableValue(this, undefined); + readonly contentHeight: IObservable = this._contentHeight; + /** The custom editor input and its webview while the chat shows them. */ + private readonly _presentation = this._register(new MutableDisposable()); + + constructor( + private readonly _target: IChatResourceTarget, + private readonly _viewType: string, + private readonly _singlePerResource: boolean, + private readonly _body: HTMLElement, + private readonly _getClippingContainer: () => HTMLElement, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IEditorService private readonly _editorService: IEditorService, + ) { + super(); + } + + async ready(): Promise { + if (this._singlePerResource) { + this._register(this._editorService.onDidEditorsChange(() => { + if (this._presentation.value && this._isOpenInEditor()) { + this._showOpenInEditor(); + } + })); + if (this._isOpenInEditor()) { + this._showOpenInEditor(); + return this; + } + } + const presentation = this._presentation.value = new DisposableStore(); + const input = presentation.add(CustomEditorInput.create(this._instantiationService, { + resource: this._target.resource, + viewType: this._viewType, + webviewTitle: this._target.label, + preferredName: this._target.label, + iconPath: undefined, + }, undefined)); + if (!(input instanceof CustomEditorInput)) { + return this; + } + await input.resolve(); + if (!presentation.isDisposed) { + this._attach(input, presentation); + } + return this; + } + + private _isOpenInEditor(): boolean { + return this._editorService.editors.some(editor => editor instanceof CustomEditorInput && editor.viewType === this._viewType && isEqual(editor.resource, this._target.resource)); + } + + private _showOpenInEditor(): void { + this._presentation.clear(); + dom.reset(this._body, dom.$('.chat-embedded-resource-message', undefined, localize('chatResources.openInEditorElsewhere', "{0} is open in an editor.", this._target.label))); + } + + private _attach(input: CustomEditorInput, presentation: DisposableStore): void { + const webview = input.webview; + const targetWindow = dom.getWindow(this._body); + // Webviews report the height of their document, which is the content height. + presentation.add(autorun(reader => { + const size = webview.intrinsicContentSize.read(reader); + if (size) { + this._contentHeight.set(size.height, undefined); + } + })); + + // Like MCP apps in chat, claim the overlay only while its anchor is visible. + let claimed = false; + const release = () => { + if (claimed) { + claimed = false; + webview.release(this); + } + }; + const observer = new targetWindow.IntersectionObserver(entries => { + if (entries.some(entry => entry.isIntersecting) && this._body.isConnected) { + webview.claim(this, targetWindow, undefined); + claimed = true; + webview.setAnchorElement(this._body, this._getClippingContainer()); + } else { + release(); + } + }); + observer.observe(this._body); + presentation.add(toDisposable(() => { + observer.disconnect(); + release(); + })); + } + + layout(): void { + // The overlay follows its anchor element. + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContributions.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContributions.ts new file mode 100644 index 000000000000..2e64f40770c9 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceContributions.ts @@ -0,0 +1,183 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IJSONSchema, TypeFromJsonSchema } from '../../../../../base/common/jsonSchema.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { derived, IObservable, mapObservableArrayCached, observableValue } from '../../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import * as nls from '../../../../../nls.js'; +import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; +import { IChatPillEntry, IChatPillSection } from '../../../../browser/chatPills.js'; +import { isProposedApiEnabled } from '../../../../services/extensions/common/extensions.js'; +import { ExtensionsRegistry } from '../../../../services/extensions/common/extensionsRegistry.js'; +import { observeChatResourceExists } from './chatResourceExistence.js'; + +/** + * A resource an extension adds to every chat whose resource exists, contributed with the proposed `chatResources` + * contribution point. Whatever makes the resource exist for a chat, such as the extension's file system provider or a tool + * that writes a file, makes it appear in the chat's Artifacts pill, where it can be pinned and shown like a recorded file. + */ +export interface IChatResourceContribution { + readonly extensionId: ExtensionIdentifier; + readonly id: string; + readonly label: string; + readonly icon: ThemeIcon | undefined; + /** A URI template; see {@link resolveChatResourceTemplate}. */ + readonly resource: string; +} + +/** The identifiers of a chat that a {@link IChatResourceContribution.resource} template can use. */ +export interface IChatResourceSessionIds { + /** `${chatSessionId}`: the agent host's identifier of the chat, distinct for each chat of a session, such as a side chat. */ + readonly chatSessionId: string; + /** + * `${agentSessionId}`: the agent host's identifier of the session, the `` of `ahp-session:/`, shared by all its + * chats. Agents get it from the `get_current_session` tool. It differs from a provider's own ID, such as the Copilot CLI's. + * Only native agent hosts have it. + */ + readonly agentSessionId: string | undefined; +} + +/** + * The resource of a contribution for a chat: its template with `${chatSessionId}` and `${agentSessionId}` replaced. A chat + * without an agent session has no resource for templates that use `${agentSessionId}`. + */ +export function resolveChatResourceTemplate(template: string, ids: IChatResourceSessionIds): URI | undefined { + if (template.includes('${agentSessionId}') && ids.agentSessionId === undefined) { + return undefined; + } + try { + return URI.parse(template + .replaceAll('${chatSessionId}', encodeURIComponent(ids.chatSessionId)) + .replaceAll('${agentSessionId}', encodeURIComponent(ids.agentSessionId ?? '')), true); + } catch { + return undefined; + } +} + +const chatResourceSchema = { + type: 'object', + additionalProperties: false, + required: ['id', 'label', 'resource'], + properties: { + id: { + type: 'string', + description: nls.localize('chatResources.id', "Identifier of the chat resource, unique within the extension."), + }, + label: { + type: 'string', + description: nls.localize('chatResources.label', "Label of the resource in the chat's Artifacts pill."), + }, + icon: { + type: 'string', + description: nls.localize('chatResources.icon', "Codicon of the resource, such as {0}.", '`$(checklist)`'), + }, + resource: { + type: 'string', + description: nls.localize('chatResources.resource', "URI of the resource for a chat, such as `chat-todos:/${agentSessionId}.todo.json`. `${chatSessionId}` is the agent host's identifier of the chat, `${agentSessionId}` the agent host's identifier of the session, which agents get from the `get_current_session` tool. The chat lists the resource while it exists."), + }, + }, +} as const satisfies IJSONSchema; + +type IRawChatResourceContribution = TypeFromJsonSchema; + +const chatResourcesExtensionPoint = ExtensionsRegistry.registerExtensionPoint({ + extensionPoint: 'chatResources', + jsonSchema: { + description: nls.localize('vscode.extension.contributes.chatResources', "Contributes resources that every chat lists while they exist, for example a per-chat todo list rendered by a custom editor."), + type: 'array', + items: chatResourceSchema, + }, +}); + +function isRawChatResourceContribution(value: unknown): value is IRawChatResourceContribution { + if (!value || typeof value !== 'object') { + return false; + } + const raw = value as { readonly id?: unknown; readonly label?: unknown; readonly resource?: unknown; readonly icon?: unknown }; + return typeof raw.id === 'string' && typeof raw.label === 'string' && typeof raw.resource === 'string' + && (raw.icon === undefined || typeof raw.icon === 'string'); +} + +const contributions = observableValue('chatResourceContributions', []); + +chatResourcesExtensionPoint.setHandler(extensions => { + const result: IChatResourceContribution[] = []; + for (const extension of extensions) { + if (!isProposedApiEnabled(extension.description, 'contribChatResources')) { + extension.collector.error(`The 'chatResources' contribution point requires the 'contribChatResources' API proposal.`); + continue; + } + if (!Array.isArray(extension.value)) { + extension.collector.error(`The 'chatResources' contribution must be an array.`); + continue; + } + for (const raw of extension.value as unknown[]) { + if (!isRawChatResourceContribution(raw)) { + extension.collector.error(`A chat resource needs an 'id', a 'label', and a 'resource', and its 'icon' must be a string.`); + continue; + } + result.push({ + extensionId: extension.description.identifier, + id: raw.id, + label: raw.label, + icon: raw.icon !== undefined ? ThemeIcon.fromString(raw.icon) : undefined, + resource: raw.resource, + }); + } + } + contributions.set(result, undefined); +}); + +/** The chat resources contributed by installed extensions. */ +export const chatResourceContributions: IObservable = contributions; + +/** The ID of the pill entry of a contributed resource, stable across the chat's lifetime so that pinning it sticks. */ +export function getContributedChatResourceEntryId(contribution: IChatResourceContribution): string { + return `contributed:${contribution.extensionId.value}/${contribution.id}`; +} + +/** The contributed resources of a chat that exist, as a section of its Artifacts pill. */ +export class ChatResourceContributionEntries extends Disposable { + + readonly sections: IObservable; + + /** + * @param ids The identifiers of the chat, or `undefined` while it has none, such as in a subagent chat. + * @param open Opens a resource in an editor. + */ + constructor( + contributionList: IObservable, + ids: IObservable, + open: (resource: URI) => void, + @IFileService fileService: IFileService, + ) { + super(); + const candidates = derived(this, reader => { + const current = ids.read(reader); + return current ? contributionList.read(reader).flatMap(contribution => { + const resource = resolveChatResourceTemplate(contribution.resource, current); + return resource ? [{ contribution, resource }] : []; + }) : []; + }); + // A resource of a scheme that no file system provides does not exist: its extension has not made it exist. + const withExistence = mapObservableArrayCached(this, candidates, (candidate, store) => ({ + ...candidate, + exists: observeChatResourceExists(fileService, candidate.resource, store, false), + }), candidate => `${getContributedChatResourceEntryId(candidate.contribution)}\u0000${candidate.resource.toString()}`); + this.sections = derived(this, reader => { + const entries = withExistence.read(reader).filter(candidate => candidate.exists.read(reader)).map(({ contribution, resource }): IChatPillEntry => ({ + id: getContributedChatResourceEntryId(contribution), + label: contribution.label, + icon: contribution.icon, + resource, + open: () => open(resource), + })); + return entries.length ? [{ title: nls.localize('chatResources.contributedSection', "Extensions"), entries }] : []; + }); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceExistence.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceExistence.ts new file mode 100644 index 000000000000..875abfe50270 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceExistence.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; + +/** + * Whether a resource exists, following changes to it until `store` is disposed. + * @param existsWithoutProvider Whether a resource that no file system provides counts as existing, because nothing can tell + * whether it exists. + */ +export function observeChatResourceExists(fileService: IFileService, resource: URI, store: DisposableStore, existsWithoutProvider: boolean): IObservable { + const exists = observableValue('chatResourceExists', false); + let version = 0; + const refresh = async () => { + const current = ++version; + let result = false; + try { + await fileService.activateProvider(resource.scheme); + result = fileService.hasProvider(resource) ? await fileService.exists(resource) : existsWithoutProvider; + } catch { + result = false; + } + if (current === version && !store.isDisposed) { + exists.set(result, undefined); + } + }; + const watcher = store.add(new MutableDisposable()); + const watch = () => watcher.value = fileService.hasProvider(resource) ? fileService.watch(resource) : undefined; + store.add(fileService.onDidFilesChange(e => { + if (e.affects(resource)) { + void refresh(); + } + })); + // A provider that registers late, such as an extension's, only reports changes to resources watched through it. + store.add(fileService.onDidChangeFileSystemProviderRegistrations(e => { + if (e.scheme === resource.scheme) { + watch(); + void refresh(); + } + })); + watch(); + store.add(toDisposable(() => version++)); + void refresh(); + return exists; +} diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceSizing.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceSizing.ts new file mode 100644 index 000000000000..295db0764aa1 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourceSizing.ts @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const CHAT_EMBEDDED_RESOURCE_MIN_HEIGHT = 40; +/** The height of a view whose webview has not reported its content height yet. */ +const DEFAULT_CONTENT_HEIGHT = 120; +const DEFAULT_MAX_AUTOMATIC_HEIGHT = 320; +const MAX_HEIGHT = 1000; +/** Dropping the resize edge within this distance of the content height (or the automatic height) follows the content. */ +const SNAP_DISTANCE = 10; + +/** + * How the user sized a embedded resource. + * + * A view follows its content height up to {@link maxAutomaticHeight}, unless the user dragged it to a + * {@link fixedHeight}. Dragging it back to its content height follows the content again and makes that + * height the new maximum, so content the user chose to see in full stays fully visible as it changes. + */ +export interface IChatEmbeddedResourceSize { + /** The height the user dragged the view to, or `undefined` to follow its content. */ + readonly fixedHeight: number | undefined; + readonly maxAutomaticHeight: number; +} + +export const defaultChatEmbeddedResourceSize: IChatEmbeddedResourceSize = { + fixedHeight: undefined, + maxAutomaticHeight: DEFAULT_MAX_AUTOMATIC_HEIGHT, +}; + +/** The height a view follows its content at. */ +export function getChatEmbeddedResourceAutomaticHeight(size: IChatEmbeddedResourceSize, contentHeight: number | undefined): number { + return Math.min(contentHeight ?? DEFAULT_CONTENT_HEIGHT, size.maxAutomaticHeight); +} + +/** + * The height a view is shown at: at least the minimum height, but never more than the space the chat has, so that the + * transcript keeps its room. The space limits how much of the view shows, but does not change the size the user chose. + */ +export function getChatEmbeddedResourceHeight(size: IChatEmbeddedResourceSize, contentHeight: number | undefined, availableHeight: number): number { + const height = size.fixedHeight ?? getChatEmbeddedResourceAutomaticHeight(size, contentHeight); + return Math.max(0, Math.min(Math.max(CHAT_EMBEDDED_RESOURCE_MIN_HEIGHT, height), availableHeight)); +} + +/** + * The size after dragging the resize edge so that the view would be `requestedHeight` tall. + * @param start The size when the drag started. Each move derives the size from it, so moving back undoes a snap. + * @param startAutomaticHeight The automatic height when the drag started. + */ +export function resizeChatEmbeddedResource(start: IChatEmbeddedResourceSize, startAutomaticHeight: number, requestedHeight: number, contentHeight: number | undefined): IChatEmbeddedResourceSize { + const height = Math.min(MAX_HEIGHT, Math.max(CHAT_EMBEDDED_RESOURCE_MIN_HEIGHT, requestedHeight)); + if (contentHeight !== undefined && Math.abs(height - contentHeight) <= SNAP_DISTANCE) { + return { fixedHeight: undefined, maxAutomaticHeight: Math.max(DEFAULT_MAX_AUTOMATIC_HEIGHT, Math.min(MAX_HEIGHT, contentHeight)) }; + } + if (Math.abs(height - startAutomaticHeight) <= SNAP_DISTANCE) { + return { fixedHeight: undefined, maxAutomaticHeight: start.maxAutomaticHeight }; + } + return { fixedHeight: height, maxAutomaticHeight: start.maxAutomaticHeight }; +} diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResources.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResources.ts new file mode 100644 index 000000000000..a4758e0c0a0d --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResources.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as nls from '../../../../../nls.js'; +import { AgentHostChatResourcesConfigKey } from '../../../../../platform/agentHost/common/agentHostSchema.js'; +import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; + +export const ChatResourcesEnabledSettingId = 'chat.resources.enabled'; + +Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ + id: 'chatResources', + title: nls.localize('chatResources.configurationTitle', "Chat Resources"), + type: 'object', + properties: { + [ChatResourcesEnabledSettingId]: { + type: 'boolean', + default: false, + scope: ConfigurationScope.APPLICATION, + // Agents can then ask to pin the files they record or show them above the chat input. + agentHost: { key: AgentHostChatResourcesConfigKey }, + markdownDescription: nls.localize('chatResources.enabled', "Whether the pinned pills of files the chat recorded, such as its agent's artifacts, can show them above the chat input instead of opening them in an editor."), + tags: ['experimental'], + }, + }, +}); diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/chatResourcesControl.ts b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourcesControl.ts new file mode 100644 index 000000000000..0d22d8fe1ef8 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/chatResourcesControl.ts @@ -0,0 +1,552 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/chatResources.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { toAction } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; +import { isCancellationError } from '../../../../../base/common/errors.js'; +import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, derived, IObservable, IReader, ISettableObservable, mapObservableArrayCached, observableFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { localize } from '../../../../../nls.js'; +import { SessionArtifactMode } from '../../../../../platform/agentHost/common/sessionArtifacts.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { IChatPillEntry, withChatPillHoverLabel } from '../../../../browser/chatPills.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IChatInputOwnPillContext } from '../chatInputPills.js'; +import { createChatResourceContent, IChatResourceTarget } from './chatResourceContent.js'; +import { observeChatResourceExists } from './chatResourceExistence.js'; +import { defaultChatEmbeddedResourceSize, getChatEmbeddedResourceAutomaticHeight, getChatEmbeddedResourceHeight, IChatEmbeddedResourceSize, resizeChatEmbeddedResource } from './chatResourceSizing.js'; + +/** A file the chat can show above its input, such as one its agent recorded as an artifact. */ +export interface IChatResource extends IChatResourceTarget { + /** The ID of the pill entry that stands for the resource. */ + readonly id: string; + /** + * How whoever recorded the file asked the chat to show it, and how often that request changed; see + * {@link ChatResourcesControl}. + */ + readonly requested?: { readonly mode: SessionArtifactMode; readonly revision: number }; +} + +/** The transcript height that shown resources leave visible. */ +const MIN_TRANSCRIPT_HEIGHT = 80; +/** The height a shown resource takes up besides its body: its header, its resize edge, its border, and spacing. */ +const SHOWN_RESOURCE_CHROME_HEIGHT = 36; +const OPENS_IN_CHAT_STORAGE_KEY = 'chat.resources.opensInChat'; +const APPLIED_REQUESTS_STORAGE_KEY = 'chat.resources.appliedRequests'; + +/** + * Lets the pinned pills of a chat's files open them above the chat input instead of in an editor. + * + * Pinning is the pills' own: any entry can be pinned into a pill of its own. On top of that, the user chooses for each + * pinned file where its pill opens it (see {@link presentOwnPill}). The pills of the files that open in the chat act as + * tabs: one of them is shown at a time, and clicking the shown one hides it. + * + * Whoever recorded a file can ask for it to be pinned or shown above the input ({@link IChatResource.requested}). The + * control does that once per request, as the user would, and remembers it: the user's later changes stick until the file + * is recorded with another request. + */ +export class ChatResourcesControl extends Disposable { + + /** The height the resource above the chat input takes up, including its spacing. */ + readonly height: IObservable; + + /** The chat's files that exist, by the ID of their pill entry. */ + private readonly _resources: IObservable>; + /** The IDs of the entries that open in the chat rather than in an editor, by chat. */ + private readonly _opensInChat: IObservable>>; + /** The ID of the shown resource by chat; `null` when the user hid it, absent before the user chose; see {@link getShownChatResource}. */ + private readonly _selection = observableValue>(this, new Map()); + /** Sizes by chat and resource ID, kept while the control lives so that switching resources keeps their sizes. */ + private readonly _sizes = new Map>(); + /** The content height each resource last reported, so that showing it again starts at that height rather than jumping to it. */ + private readonly _contentHeights = new Map>(); + private readonly _chatKey: IObservable; + private readonly _shown: IObservable; + + /** + * @param container Receives the resource shown above the chat input as its first child, so it appears above the pills that the container also hosts. + * @param chatElement The chat widget. Shown resources never grow past the top of the element that clips it, and are clipped to it. + * @param recorded Files recorded for the chat, such as files its agent added as artifacts. + * @param isPinned Whether the user pinned the entry of a resource into a pill of its own; only pinned resources open in the chat. + * @param pin Pins the entry of a resource, as its pin action does. Returns whether it could. + */ + constructor( + container: HTMLElement, + chatElement: HTMLElement, + sessionResource: IObservable, + recorded: IObservable, + isPinned: (id: string, reader: IReader) => boolean, + private readonly _pin: (resource: IChatResource) => boolean, + @IFileService private readonly _fileService: IFileService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IStorageService private readonly _storageService: IStorageService, + @IEditorService private readonly _editorService: IEditorService, + @INotificationService private readonly _notificationService: INotificationService, + ) { + super(); + const element = dom.$('.chat-embedded-resources'); + container.prepend(element); + this._register(toDisposable(() => element.remove())); + + // Every chat widget stores its choices under the same key, so each follows the stored value rather than its own copy. + this._opensInChat = observableFromEvent(this, this._storageService.onDidChangeValue(StorageScope.WORKSPACE, OPENS_IN_CHAT_STORAGE_KEY, this._store), () => this._readOpensInChat()); + this._chatKey = derived(this, reader => sessionResource.read(reader)?.toString()); + // A recorded file can be missing: the agent can record it before writing it, or delete it later. + const recordedTargets = derived(this, reader => [...new Set(recorded.read(reader).map(resource => resource.resource.toString()))]); + const recordedExistence = mapObservableArrayCached(this, recordedTargets, (target, store) => [target, /* Resources that no file system provides, such as settings, count as existing: nothing can tell. */ observeChatResourceExists(this._fileService, URI.parse(target), store, true)] as const); + this._resources = derived(this, reader => { + if (this._chatKey.read(reader) === undefined) { + return new Map(); + } + const existence = new Map(recordedExistence.read(reader)); + return new Map(recorded.read(reader) + .filter(resource => existence.get(resource.resource.toString())?.read(reader) ?? false) + .map(resource => [resource.id, resource])); + }); + this._shown = derived(this, reader => { + const chat = this._chatKey.read(reader); + const inChat = [...this._resources.read(reader).values()].filter(resource => isPinned(resource.id, reader) && this._opensInChatFor(resource.id, reader)); + return getShownChatResource(inChat, chat === undefined ? undefined : this._selection.read(reader).get(chat)); + }); + this._register(autorun(reader => { + const chat = this._chatKey.read(reader); + if (chat === undefined) { + return; + } + const resources = [...this._resources.read(reader).values()]; + // Pinning can become possible only later, such as once the chat's pills exist: reading the pins runs this again then. + resources.forEach(resource => resource.requested && isPinned(resource.id, reader)); + this._applyRequests(chat, resources); + })); + + // The resource floats upwards from the pills, over the transcript and whatever else the chat's container shows above the + // input (such as the sessions list of an empty chat), so that container's top bounds it. It is looked up when measuring, + // because the chat widget may not be attached yet when this control is created. + const getBoundary = () => findClippingAncestor(chatElement); + const availableSpace = observableValue(this, Number.POSITIVE_INFINITY); + const height = observableValue(this, 0); + const measure = () => { + height.set(element.offsetHeight, undefined); + // While nothing is shown, the element is not laid out; it is measured once it shows a resource. + if (element.offsetHeight > 0) { + // The bottom edge stays put when the resource resizes, and moves with the chat input, which resizes then. + availableSpace.set(Math.max(0, element.getBoundingClientRect().bottom - getBoundary().getBoundingClientRect().top - MIN_TRANSCRIPT_HEIGHT), undefined); + } + }; + // The measured height resizes the chat, which resizes the observed elements: measuring in the next frame keeps + // that from looping within one frame. + const scheduledMeasure = this._register(new MutableDisposable()); + const layoutObserver = new (dom.getWindow(container).ResizeObserver)(() => { + scheduledMeasure.value ??= dom.scheduleAtNextAnimationFrame(dom.getWindow(container), () => { + scheduledMeasure.clear(); + measure(); + }); + }); + for (const observed of [element, chatElement, container.parentElement]) { + if (observed) { + layoutObserver.observe(observed); + } + } + this._register(toDisposable(() => layoutObserver.disconnect())); + this.height = height; + + const availableHeight = derived(this, reader => availableSpace.read(reader) - SHOWN_RESOURCE_CHROME_HEIGHT); + const shownList = derived(this, reader => { + const shown = this._shown.read(reader); + return shown ? [shown] : []; + }); + const frames = mapObservableArrayCached(this, shownList, (resource, store) => + store.add(this._instantiationService.createInstance(ChatShownResourceFrame, resource, this._getSize(resource), this._getContentHeight(resource), availableHeight, getBoundary, { + openInEditor: () => this._openInEditor(resource), + // Closing hides the resource; its pill shows it again, like a tab. + close: () => this._select(null), + })), resource => `${resource.id}\u0000${resource.resource.toString()}`); + this._register(autorun(reader => { + dom.reset(element, ...frames.read(reader).map(frame => frame.element)); + })); + } + + /** + * Decorates the entry of a pill of its own (see {@link IStandardChatInputPillSections.presentOwnPill}) that stands for one + * of the chat's files: its context menu offers whether the pill shows the file in the chat rather than in an editor; a pill that shows it there shows + * and hides it there. + */ + presentOwnPill(entry: IChatPillEntry, context: IChatInputOwnPillContext, reader: IReader): IChatPillEntry { + const resource = this._resources.read(reader).get(entry.id); + if (!resource) { + return entry; + } + const inChat = context.pinned && this._opensInChatFor(entry.id, reader); + const shown = inChat && this._shown.read(reader)?.id === entry.id; + const actions = [ + withChatPillHoverLabel(toAction({ + id: 'chatResources.showAboveInput', + label: localize('chatResources.showAboveInput', "Show Above Chat Input"), + class: ThemeIcon.asClassName(Codicon.layoutPanel), + checked: inChat, + run: () => { + if (inChat) { + // Unchecking it lets the pill open the file in an editor again. + this._setOpensInChat(entry.id, false); + return; + } + // Only pinned entries open in the chat, so that the file keeps its pill when the chat records more. + context.pin(); + this._setOpensInChat(entry.id, true); + this._select(entry.id); + }, + }), localize('chatResources.showAboveInputHoverLabel', "Chat")), + ]; + return { + ...entry, + hoverActions: [...entry.hoverActions ?? [], ...actions], + ...(inChat ? { + checked: shown, + tooltip: shown ? localize('chatResources.hide', "Hide {0}", resource.label) : localize('chatResources.show', "Show {0}", resource.label), + open: () => this._select(this._shown.get()?.id === entry.id ? null : entry.id), + } : {}), + }; + } + + private _opensInChatFor(id: string, reader: IReader | undefined): boolean { + const chat = this._chatKey.read(reader); + return chat !== undefined && (this._opensInChat.read(reader)[chat]?.includes(id) ?? false); + } + + private _setOpensInChat(id: string, opensInChat: boolean): void { + const chat = this._chatKey.get(); + if (chat === undefined) { + return; + } + const all = this._readOpensInChat(); + const ids = (all[chat] ?? []).filter(candidate => candidate !== id); + const next: Record = { ...all, [chat]: opensInChat ? [...ids, id] : ids }; + if (next[chat].length === 0) { + delete next[chat]; + } + if (Object.keys(next).length > 0) { + this._storageService.store(OPENS_IN_CHAT_STORAGE_KEY, JSON.stringify(next), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } else { + this._storageService.remove(OPENS_IN_CHAT_STORAGE_KEY, StorageScope.WORKSPACE); + } + } + + private _readOpensInChat(): Record { + try { + const value: unknown = JSON.parse(this._storageService.get(OPENS_IN_CHAT_STORAGE_KEY, StorageScope.WORKSPACE, '{}')); + const result: Record = {}; + for (const [chat, ids] of Object.entries(value && typeof value === 'object' ? value : {})) { + if (Array.isArray(ids)) { + result[chat] = ids.filter((id): id is string => typeof id === 'string'); + } + } + return result; + } catch { + return {}; + } + } + + private _select(id: string | null): void { + const chat = this._chatKey.get(); + if (chat !== undefined) { + this._selection.set(new Map(this._selection.get()).set(chat, id), undefined); + } + } + + /** Does what each resource's request asks once, as the user would; see {@link IChatResource.requested}. */ + private _applyRequests(chat: string, resources: readonly IChatResource[]): void { + const all = this._readAppliedRequests(); + const applied = { ...all[chat] }; + let changed = false; + for (const resource of resources) { + if (!resource.requested) { + continue; + } + // The revision tells a new request from the applied one even if the chat missed the requests in between. + const request = `${resource.requested.mode}#${resource.requested.revision}`; + if (applied[resource.id] === request || !this._pin(resource)) { + continue; + } + // A pinned file opens in an editor; one shown above the input opens there. + this._setOpensInChat(resource.id, resource.requested.mode === 'aboveInput'); + if (resource.requested.mode === 'aboveInput') { + this._select(resource.id); + } + applied[resource.id] = request; + changed = true; + } + if (changed) { + this._storageService.store(APPLIED_REQUESTS_STORAGE_KEY, JSON.stringify({ ...all, [chat]: applied }), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } + } + + private _readAppliedRequests(): Record> { + try { + const value: unknown = JSON.parse(this._storageService.get(APPLIED_REQUESTS_STORAGE_KEY, StorageScope.WORKSPACE, '{}')); + const result: Record> = {}; + for (const [chat, requests] of Object.entries(value && typeof value === 'object' ? value : {})) { + result[chat] = Object.fromEntries(Object.entries(requests && typeof requests === 'object' ? requests : {}).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); + } + return result; + } catch { + return {}; + } + } + + /** Opens the resource in an editor, or reveals the editor that shows it, and hides it in the chat. */ + private _openInEditor(resource: IChatResource): void { + if (this._shown.get()?.id === resource.id) { + this._select(null); + } + this._editorService.openEditor({ resource: resource.resource, options: { pinned: true } }).catch(error => this._notificationService.error(error)); + } + + private _getSize(resource: IChatResource): ISettableObservable { + const key = `${this._chatKey.get()}\u0000${resource.id}`; + let size = this._sizes.get(key); + if (!size) { + size = observableValue(this, defaultChatEmbeddedResourceSize); + this._sizes.set(key, size); + } + return size; + } + + private _getContentHeight(resource: IChatResource): ISettableObservable { + const key = `${this._chatKey.get()}\u0000${resource.id}`; + let contentHeight = this._contentHeights.get(key); + if (!contentHeight) { + contentHeight = observableValue(this, undefined); + this._contentHeights.set(key, contentHeight); + } + return contentHeight; + } + +} + +/** + * The resource the chat shows, of the resources that open in the chat. Until the user chooses one, the chat shows the first + * one; afterwards only the chosen one, so the chat does not show another one when the chosen one stops opening in the chat. + * @param selected The ID of the chosen resource, `null` when the user hid it, `undefined` before the user chose. + */ +export function getShownChatResource(resources: readonly T[], selected: string | null | undefined): T | undefined { + if (selected === undefined) { + return resources[0]; + } + return selected === null ? undefined : resources.find(resource => resource.id === selected); +} + +/** The element itself or its nearest ancestor that clips its content, which bounds what floats inside it. */ +function findClippingAncestor(element: HTMLElement): HTMLElement { + for (let current: HTMLElement | null = element; current; current = current.parentElement) { + if (dom.getComputedStyle(current).overflow !== 'visible') { + return current; + } + } + return element; +} + +/** How far the arrow keys move the resize edge. */ +const KEYBOARD_RESIZE_STEP = 20; +/** How long the content height must stay unchanged after the content is shown before the view follows it. */ +const CONTENT_HEIGHT_SETTLE_DELAY = 150; +/** The view follows the content height at the latest this long after the content is shown. */ +const CONTENT_HEIGHT_SETTLE_DEADLINE = 600; + +interface IChatShownResourceFrameActions { + openInEditor(): void; + close(): void; +} + +/** + * A resource shown in an area of the chat: a header that offers to open it in an editor, its content as + * {@link createChatResourceContent} renders it, sized as {@link IChatEmbeddedResourceSize} describes, and a resize edge. + * The resource is anchored to the pills below it, so its top edge resizes it. + */ +class ChatShownResourceFrame extends Disposable { + + readonly element: HTMLElement; + private readonly _body: HTMLElement; + constructor( + private readonly _resource: IChatResource, + private readonly _size: ISettableObservable, + private readonly _contentHeight: ISettableObservable, + availableHeight: IObservable, + private readonly _getClippingContainer: () => HTMLElement, + actions: IChatShownResourceFrameActions, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + const elements = dom.h('.chat-embedded-resource@root', [ + dom.h('.chat-embedded-resource-header@header', [ + dom.h('span.chat-embedded-resource-title@title'), + dom.h('.chat-embedded-resource-actions@actions'), + ]), + dom.h('.chat-embedded-resource-body@body'), + ]); + // The resize edge is the edge that moves: the top one. + const resizeHandle = dom.$('.chat-embedded-resource-sash', { + role: 'separator', + tabindex: '0', + 'aria-orientation': 'horizontal', + 'aria-label': localize('chatResources.resizeLabel', "Resize {0}", _resource.label), + }); + elements.root.prepend(resizeHandle); + this.element = elements.root; + this._body = elements.body; + elements.title.textContent = _resource.label; + this.element.setAttribute('aria-label', _resource.label); + const addButton = (label: string, icon: ThemeIcon, run: () => void) => { + const button = dom.append(elements.actions, dom.$(`a.action-label${ThemeIcon.asCSSSelector(icon)}`, { role: 'button', tabindex: '0', title: label, 'aria-label': label })); + this._register(dom.addDisposableListener(button, dom.EventType.POINTER_DOWN, e => e.stopPropagation())); + this._register(dom.addDisposableListener(button, dom.EventType.CLICK, () => run())); + this._register(dom.addDisposableListener(button, dom.EventType.KEY_DOWN, e => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + run(); + } + })); + return button; + }; + addButton(localize('chatResources.openInEditorButton', "Open in Editor"), Codicon.goToFile, actions.openInEditor); + addButton(localize('chatResources.close', "Close"), Codicon.close, actions.close); + + + const height = derived(this, reader => getChatEmbeddedResourceHeight(this._size.read(reader), this._contentHeight.read(reader), availableHeight.read(reader))); + this._register(autorun(reader => { + const size = this._size.read(reader); + this._body.style.height = `${height.read(reader)}px`; + this.element.classList.toggle('automatic-height', size.fixedHeight === undefined); + resizeHandle.setAttribute('aria-valuenow', String(Math.round(height.read(reader)))); + resizeHandle.setAttribute('aria-valuetext', size.fixedHeight === undefined + ? localize('chatResources.resizeValueAutomatic', "Follows its content, {0} pixels", Math.round(height.read(reader))) + : localize('chatResources.resizeValueFixed', "{0} pixels", Math.round(height.read(reader)))); + resizeHandle.title = size.fixedHeight === undefined + ? localize('chatResources.resizeAutomatic', "Follows its content up to {0}px. Drag or use the Up and Down Arrow keys to resize, double-click or press Home to reset.", size.maxAutomaticHeight) + : localize('chatResources.resizeFixed', "Fixed at {0}px. Resize to its content height to follow the content again; double-click or press Home to reset.", Math.round(size.fixedHeight)); + })); + // Dragging the top edge up grows the resource. + this._register(this._registerResizing(resizeHandle, height, -1)); + void this._render(); + } + + private _registerResizing(handle: HTMLElement, height: IObservable, direction: 1 | -1): DisposableStore { + const store = new DisposableStore(); + store.add(dom.addDisposableListener(handle, dom.EventType.POINTER_DOWN, (e: PointerEvent) => { + if (e.button !== 0) { + return; + } + e.preventDefault(); + handle.setPointerCapture(e.pointerId); + handle.classList.add('active'); + const drag = new DisposableStore(); + // Like the workbench sash: webview iframes would otherwise swallow the pointer while it passes over them. + // eslint-disable-next-line eslint-js/no-restricted-syntax + const iframes = [...handle.ownerDocument.getElementsByTagName('iframe')]; + for (const iframe of iframes) { + iframe.classList.add('pointer-events-disabled'); + } + drag.add(toDisposable(() => { + handle.classList.remove('active'); + for (const iframe of iframes) { + iframe.classList.remove('pointer-events-disabled'); + } + })); + const startY = e.clientY; + const startHeight = height.get(); + const startSize = this._size.get(); + const startAutomaticHeight = getChatEmbeddedResourceAutomaticHeight(startSize, this._contentHeight.get()); + drag.add(dom.addDisposableListener(handle, dom.EventType.POINTER_MOVE, (move: PointerEvent) => { + this._size.set(resizeChatEmbeddedResource(startSize, startAutomaticHeight, startHeight + direction * (move.clientY - startY), this._contentHeight.get()), undefined); + })); + drag.add(dom.addDisposableListener(handle, dom.EventType.POINTER_UP, () => drag.dispose())); + drag.add(dom.addDisposableListener(handle, 'lostpointercapture', () => drag.dispose())); + store.add(drag); + })); + store.add(dom.addDisposableListener(handle, dom.EventType.DBLCLICK, () => this._size.set(defaultChatEmbeddedResourceSize, undefined))); + store.add(dom.addDisposableListener(handle, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { + if (e.key === 'Home') { + e.preventDefault(); + this._size.set(defaultChatEmbeddedResourceSize, undefined); + return; + } + // The arrow moves the handle, like dragging it. + const movement = e.key === 'ArrowUp' ? -KEYBOARD_RESIZE_STEP : e.key === 'ArrowDown' ? KEYBOARD_RESIZE_STEP : 0; + if (movement) { + e.preventDefault(); + const size = this._size.get(); + const contentHeight = this._contentHeight.get(); + this._size.set(resizeChatEmbeddedResource(size, getChatEmbeddedResourceAutomaticHeight(size, contentHeight), height.get() + direction * movement, contentHeight), undefined); + } + })); + return store; + } + + /** + * Applies the content height as it changes. Content reports several heights while it renders (for example a webview + * its empty document first), so until the reports settle the view keeps the height the resource last had. + */ + private _followContentHeight(contentHeight: IObservable): DisposableStore { + const store = new DisposableStore(); + let settled = false; + const settle = () => { + settled = true; + const height = contentHeight.get(); + if (height !== undefined) { + this._contentHeight.set(height, undefined); + } + }; + const settleTimer = store.add(new MutableDisposable()); + const deadline = setTimeout(settle, CONTENT_HEIGHT_SETTLE_DEADLINE); + store.add(toDisposable(() => clearTimeout(deadline))); + store.add(autorun(reader => { + const height = contentHeight.read(reader); + if (height === undefined) { + return; + } + if (settled) { + this._contentHeight.set(height, undefined); + return; + } + const timer = setTimeout(() => { + clearTimeout(deadline); + settle(); + }, CONTENT_HEIGHT_SETTLE_DELAY); + settleTimer.value = toDisposable(() => clearTimeout(timer)); + })); + return store; + } + + private async _render(): Promise { + try { + // The frame owns the content while it loads, so closing the frame disposes content that is still loading. + const content = await createChatResourceContent(this._resource, this._body, this._getClippingContainer, this._instantiationService, this._store); + if (this._store.isDisposed) { + return; + } + this._register(this._followContentHeight(content.contentHeight)); + const layout = () => content.layout(this._body.clientWidth, this._body.clientHeight); + const resizeObserver = new (dom.getWindow(this._body).ResizeObserver)(layout); + resizeObserver.observe(this._body); + this._register(toDisposable(() => resizeObserver.disconnect())); + layout(); + } catch (error) { + if (this._store.isDisposed || isCancellationError(error)) { + return; + } + this._logService.error(`[ChatResources] Could not render ${this._resource.resource.toString()}`, error); + dom.reset(this._body, dom.$('.chat-embedded-resource-error', undefined, toErrorMessage(error))); + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatResources/media/chatResources.css b/src/vs/workbench/contrib/chat/browser/chatResources/media/chatResources.css new file mode 100644 index 000000000000..a1a2731f3395 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatResources/media/chatResources.css @@ -0,0 +1,101 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* The embedded resource floats above the pills, whose container lets clicks fall through to the transcript. */ +.chat-embedded-resources { + position: relative; + z-index: 1; + pointer-events: auto; +} + +.chat-embedded-resources:empty { + display: none; +} + +/* Padding rather than margin, so the measured height that the transcript reserves includes it. */ +.chat-embedded-resources:not(:empty) { + padding-bottom: 4px; +} + +.chat-embedded-resource { + position: relative; + border: 1px solid var(--vscode-input-border, var(--vscode-widget-border, transparent)); + border-radius: 4px; + overflow: hidden; + background: var(--vscode-chat-list-background, var(--vscode-sideBar-background)); +} + +.chat-embedded-resource-header { + display: flex; + align-items: center; + gap: 4px; + height: 22px; + padding: 0 4px 0 8px; + user-select: none; + border-bottom: 1px solid var(--vscode-widget-border, transparent); + color: var(--vscode-descriptionForeground); + font-size: 11px; +} + +/* The resize edge is the edge that moves: the top one. */ +.chat-embedded-resource-sash { + height: 4px; + cursor: ns-resize; + transition: background-color 0.1s ease-out; +} + +.chat-embedded-resource-sash:hover, +.chat-embedded-resource-sash.active { + background: var(--vscode-sash-hoverBorder); + transition-delay: 0.2s; +} + +.chat-embedded-resource-sash.active { + transition-delay: 0s; +} + +.chat-embedded-resource-title { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-embedded-resource-actions { + display: flex; + gap: 2px; +} + +.chat-embedded-resource-actions .action-label { + display: flex; + align-items: center; + justify-content: center; + width: 18px; + height: 18px; + border-radius: 3px; + cursor: pointer; + color: var(--vscode-icon-foreground); +} + +.chat-embedded-resource-actions .action-label:hover { + background: var(--vscode-toolbar-hoverBackground); +} + +.chat-embedded-resource-body { + position: relative; +} + +.chat-embedded-resource-error, +.chat-embedded-resource-message { + padding: 6px 8px; +} + +.chat-embedded-resource-error { + color: var(--vscode-errorForeground); +} + +.chat-embedded-resource-message { + color: var(--vscode-descriptionForeground); +} diff --git a/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.ts b/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.ts index 9cfaf4efc63a..a71fc32037d7 100644 --- a/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { sep } from '../../../../../base/common/path.js'; -import { AsyncIterableProducer, DeferredPromise, raceCancellation, raceCancellationError } from '../../../../../base/common/async.js'; +import { AsyncIterableProducer, raceCancellation, raceCancellationError } from '../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; @@ -22,7 +22,6 @@ import { InstantiationType, registerSingleton } from '../../../../../platform/in import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { ILabelService } from '../../../../../platform/label/common/label.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; -import { IProgressService } from '../../../../../platform/progress/common/progress.js'; import { Registry } from '../../../../../platform/registry/common/platform.js'; import { isDark } from '../../../../../platform/theme/common/theme.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; @@ -40,9 +39,8 @@ import { IChatEditorOptions } from '../widgetHosts/editor/chatEditor.js'; import { IChatService, ResponseModelState } from '../../common/chatService/chatService.js'; import { autorun, derived, IObservable, observableFromEvent, observableSignal, observableValue } from '../../../../../base/common/observable.js'; import { IChatRequestVariableEntry, PromptFileVariableKind, toPromptFileVariableEntry } from '../../common/attachments/chatVariableEntries.js'; -import { IViewsService } from '../../../../services/views/common/viewsService.js'; -import { ChatViewId } from '../chat.js'; -import { ChatViewPane } from '../widgetHosts/viewPane/chatViewPane.js'; +import { IChatViewHostService, IChatViewHostSessionStart } from '../chatViewHost.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; import { AgentSessionProviders, getAgentSessionProvider, getAgentSessionProviderName } from '../agentSessions/agentSessions.js'; import { IAgentHostImportConversationStore, type IAgentHostImportConversation } from '../agentSessions/agentHost/agentHostImportConversationStore.js'; import { IAgentHostActiveClientService } from '../agentSessions/agentHost/agentHostActiveClientService.js'; @@ -1912,7 +1910,6 @@ export type NewChatSessionSendOutcome = 'none' | 'sent' | 'queued' | 'rejected' * session stays open (and its resource is returned) when that request is rejected or fails. */ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOptions: NewChatSessionOpenOptions, chatSendOptions?: NewChatSessionSendOptions): Promise<{ readonly resource: URI; readonly sendOutcome: NewChatSessionSendOutcome } | undefined> { - const viewsService = accessor.get(IViewsService); const chatService = accessor.get(IChatService); const chatSessionService = accessor.get(IChatSessionsService); const logService = accessor.get(ILogService); @@ -1922,7 +1919,8 @@ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOpt const toolsService = accessor.get(ILanguageModelToolsService); const importConversationStore = accessor.get(IAgentHostImportConversationStore); const activeClientService = chatSendOptions?.sessionToolIds?.length ? accessor.get(IAgentHostActiveClientService) : undefined; - const progressService = accessor.get(IProgressService); + const chatViewHostService = accessor.get(IChatViewHostService); + const notificationService = accessor.get(INotificationService); // Determine resource to open const sessionResource = openOptions.sessionResource ?? getResourceForNewChatSession(openOptions); @@ -1939,32 +1937,19 @@ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOpt importConversationStore.set(sessionResource, chatSendOptions.importConversation); } - // Open chat session. For a sidebar "Continue in…" migration the transition - // spans multiple async phases (load → materializing send → untitled→real - // rebind), during which the chat widget is transiently empty. Hold the - // sessions list suppressed across the whole transition so it never flashes. - let sessionsListSuppression: IDisposable | undefined; - let transitionProgress: DeferredPromise | undefined; + // Open chat session. In the host of the Chat view's chats, the start spans the + // whole transition (load → materializing send → untitled→real rebind) until + // it completes below. + let hostSessionStart: IChatViewHostSessionStart | undefined; try { openOptions.beforeOpen?.(); switch (openOptions.position) { case ChatSessionPosition.Sidebar: { - const view = await viewsService.openView(ChatViewId) as ChatViewPane; - openOptions.beforeOpen?.(); - if (chatSendOptions?.importConversation) { - sessionsListSuppression = view.beginSessionsListSuppression(); - // Show the chat view's working indicator for the whole transition (the - // widget is blank while the backend session materializes) so it does not - // look hung. Completed once the migration finishes below. - transitionProgress = new DeferredPromise(); - progressService.withProgress({ location: ChatViewId }, () => transitionProgress!.p); - } - if (openOptions.type === AgentSessionProviders.Local) { - await view.startNewLocalSession(); - } else { - await view.loadSession(sessionResource, 'explicitOverride'); - } - view.focus(); + hostSessionStart = await chatViewHostService.startSession(sessionResource, { + local: openOptions.type === AgentSessionProviders.Local, + importingConversation: !!chatSendOptions?.importConversation, + beforeOpen: openOptions.beforeOpen, + }); break; } case ChatSessionPosition.Editor: { @@ -2008,8 +1993,7 @@ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOpt } } catch (e) { activeClientService?.clearSessionTools(sessionResource); - sessionsListSuppression?.dispose(); - transitionProgress?.complete(); + hostSessionStart?.dispose(); if (openOptions.beforeOpen && isCancellationError(e)) { throw e; } @@ -2039,8 +2023,7 @@ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOpt openedSessionResource = newSessionResource; switch (openOptions.position) { case ChatSessionPosition.Sidebar: { - const view = await viewsService.openView(ChatViewId) as ChatViewPane; - await view.loadSession(newSessionResource); + await hostSessionStart?.moved(newSessionResource); break; } case ChatSessionPosition.Editor: { @@ -2066,11 +2049,33 @@ export async function openChatSessionAndSend(accessor: ServicesAccessor, openOpt } } - // The migration transition is complete (session loaded, request sent and any - // untitled→real rebind done); allow the sessions list again and stop the - // working indicator. - sessionsListSuppression?.dispose(); - transitionProgress?.complete(); + // The start is complete (session loaded, request sent and any untitled→real + // rebind done). A request that did not run, in a session the host does not + // show, is put back into a new session's composer when it can be sent again. + if (hostSessionStart) { + try { + const sent = sendOutcome === 'sent' || sendOutcome === 'queued'; + const shown = await hostSessionStart.complete(openedSessionResource, sent); + if (!sent && !shown && chatSendOptions) { + importConversationStore.take(sessionResource); + // Only a request of a prompt and attachments can be sent again from a composer: one with a copied + // conversation, session options or tools would start a different session, so its caller reports it instead + const restorable = !chatSendOptions.importConversation && !chatSendOptions.initialSessionOptions && !chatSendOptions.sessionToolIds?.length; + const composer = restorable ? await hostSessionStart.createComposer() : undefined; + if (composer) { + composer.setInput(chatSendOptions.prompt); + if (chatSendOptions.attachedContext?.length) { + composer.attachmentModel.addContext(...chatSendOptions.attachedContext); + } + notificationService.warn(localize('chatSessions.requestRestored', "The request could not be sent. It was restored in a new session so you can send it again.")); + } else { + notificationService.error(localize('chatSessions.requestNotSent', "The request could not be sent.")); + } + } + } finally { + hostSessionStart.dispose(); + } + } return { resource: openedSessionResource, sendOutcome }; } diff --git a/src/vs/workbench/contrib/chat/browser/chatSetup/chatEntitlementSimulation.ts b/src/vs/workbench/contrib/chat/browser/chatSetup/chatEntitlementSimulation.ts new file mode 100644 index 000000000000..6b5225888018 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatSetup/chatEntitlementSimulation.ts @@ -0,0 +1,166 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * 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 { Disposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { localize, localize2 } from '../../../../../nls.js'; +import { Categories } from '../../../../../platform/action/common/actionCommonCategories.js'; +import { Action2 } from '../../../../../platform/actions/common/actions.js'; +import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IWorkbenchContribution } from '../../../../common/contributions.js'; +import { ChatEntitlement, ChatEntitlementService, getChatPlanName, IChatEntitlementService, SimulatedChatEntitlement } from '../../../../services/chat/common/chatEntitlementService.js'; +import { IStatusbarEntry, IStatusbarEntryAccessor, IStatusbarService, StatusbarAlignment } from '../../../../services/statusbar/browser/statusbar.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; + +const SIMULATE_ENTITLEMENT_COMMAND_ID = 'workbench.action.chat.simulateEntitlement'; + +function getSimulatedEntitlementLabel(entitlement: SimulatedChatEntitlement): string { + switch (entitlement) { + case ChatEntitlement.Available: + return localize('simulatedEntitlement.available', "Can Claim Copilot Free"); + case ChatEntitlement.Unavailable: + return localize('simulatedEntitlement.unavailable', "No Copilot Access"); + default: + return getChatPlanName(entitlement); + } +} + +function getChatEntitlementRequests(chatEntitlementService: IChatEntitlementService) { + return chatEntitlementService instanceof ChatEntitlementService ? chatEntitlementService.requests?.value : undefined; +} + +interface ISimulatedEntitlementPickItem extends IQuickPickItem { + readonly entitlement: SimulatedChatEntitlement | undefined; +} + +/** + * Lets developers try the product as a user with a different Copilot plan, + * for example a user who can claim Copilot Free but has not signed up yet. + */ +export class SimulateChatEntitlementAction extends Action2 { + + constructor() { + super({ + id: SIMULATE_ENTITLEMENT_COMMAND_ID, + title: localize2('simulateEntitlement', "Simulate Copilot Plan..."), + category: Categories.Developer, + f1: true, + precondition: ChatContextKeys.enabled + }); + } + + override async run(accessor: ServicesAccessor): Promise { + const chatEntitlementService = accessor.get(IChatEntitlementService); + const quickInputService = accessor.get(IQuickInputService); + const notificationService = accessor.get(INotificationService); + + const requests = getChatEntitlementRequests(chatEntitlementService); + if (!requests) { + notificationService.info(localize('simulateEntitlement.unsupported', "Simulating a Copilot plan is not supported in this environment.")); + return; + } + + const current = requests.simulatedEntitlement; + const currentDescription = localize('simulateEntitlement.current', "Current"); + const toItem = (entitlement: SimulatedChatEntitlement, detail?: string): ISimulatedEntitlementPickItem => ({ + entitlement, + label: getSimulatedEntitlementLabel(entitlement), + description: entitlement === current ? currentDescription : undefined, + detail + }); + + const items: (ISimulatedEntitlementPickItem | IQuickPickSeparator)[] = [ + { + entitlement: undefined, + label: current === undefined ? localize('simulateEntitlement.actual', "Actual Plan") : localize('simulateEntitlement.stop', "Stop Simulating"), + description: current === undefined ? currentDescription : undefined, + detail: localize('simulateEntitlement.actualDetail', "Use the Copilot plan of your signed-in account") + }, + { type: 'separator', label: localize('simulateEntitlement.notSubscribed', "Not Subscribed") }, + toItem(ChatEntitlement.Available, localize('simulateEntitlement.availableDetail', "Signed in and eligible for Copilot Free, but not signed up yet")), + toItem(ChatEntitlement.Unavailable, localize('simulateEntitlement.unavailableDetail', "Signed in but not eligible for any Copilot plan")), + { type: 'separator', label: localize('simulateEntitlement.individual', "Individual Plans") }, + toItem(ChatEntitlement.Free), + toItem(ChatEntitlement.EDU), + toItem(ChatEntitlement.Pro), + toItem(ChatEntitlement.ProPlus), + toItem(ChatEntitlement.Max), + { type: 'separator', label: localize('simulateEntitlement.organization', "Organization Plans") }, + toItem(ChatEntitlement.Business), + toItem(ChatEntitlement.Enterprise), + ]; + + const pick = await quickInputService.pick(items, { + title: localize('simulateEntitlement.title', "Simulate Copilot Plan"), + placeHolder: localize('simulateEntitlement.placeholder', "Select the Copilot plan to experience the product with"), + activeItem: items.find((item): item is ISimulatedEntitlementPickItem => item.type !== 'separator' && item.entitlement === current) + }); + if (!pick || pick.entitlement === current) { + return; + } + + await requests.setSimulatedEntitlement(pick.entitlement); + + if (pick.entitlement === undefined) { + status(localize('simulateEntitlement.stopped', "Stopped simulating a Copilot plan")); + } else { + status(localize('simulateEntitlement.started', "Simulating {0}", getSimulatedEntitlementLabel(pick.entitlement))); + if (chatEntitlementService.entitlement === ChatEntitlement.Unknown) { + notificationService.info(localize('simulateEntitlement.signIn', "Sign in with GitHub to experience the simulated Copilot plan.")); + } + } + } +} + +/** + * Shows a status bar entry while a Copilot plan is simulated. + */ +export class ChatEntitlementSimulationContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.chatEntitlementSimulation'; + + private readonly entry = this._register(new MutableDisposable()); + + constructor( + @IChatEntitlementService chatEntitlementService: IChatEntitlementService, + @IStatusbarService private readonly statusbarService: IStatusbarService, + ) { + super(); + + const requests = getChatEntitlementRequests(chatEntitlementService); + if (!requests) { + return; + } + + this.update(requests.simulatedEntitlement); + this._register(requests.onDidChangeSimulatedEntitlement(() => this.update(requests.simulatedEntitlement))); + } + + private update(simulatedEntitlement: SimulatedChatEntitlement | undefined): void { + if (simulatedEntitlement === undefined) { + this.entry.clear(); + return; + } + + const label = getSimulatedEntitlementLabel(simulatedEntitlement); + const props: IStatusbarEntry = { + name: localize('simulateEntitlement.statusName', "Simulated Copilot Plan"), + text: `$(beaker) ${localize('simulateEntitlement.statusText', "Simulating: {0}", label)}`, + ariaLabel: localize('simulateEntitlement.statusAria', "Simulating the Copilot plan {0}. Select to change or stop the simulation.", label), + tooltip: localize('simulateEntitlement.statusTooltip', "Simulating the Copilot plan \"{0}\". Click to change or stop the simulation.", label), + command: SIMULATE_ENTITLEMENT_COMMAND_ID, + kind: 'warning' + }; + + if (this.entry.value) { + this.entry.value.update(props); + } else { + // Far right, just before the notifications bell, independent of whether the Copilot entry is shown + this.entry.value = this.statusbarService.addEntry(props, 'chat.entitlementSimulation', StatusbarAlignment.RIGHT, -Number.MAX_SAFE_INTEGER); + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusPromo.ts b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusPromo.ts index f785f8748c35..1e9e39f6e290 100644 --- a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusPromo.ts +++ b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusPromo.ts @@ -3,6 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; import * as dom from '../../../../../base/browser/dom.js'; import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; @@ -91,9 +93,17 @@ export class ChatStatusPromo extends Disposable { @IAgentHostEnablementService private readonly agentHostEnablementService: IAgentHostEnablementService, @IManagedSettingsService private readonly managedSettingsService: IManagedSettingsService, @IAccountPolicyGateService private readonly accountPolicyGateService: IAccountPolicyGateService, + @IContextKeyService private readonly contextKeyService: IContextKeyService, ) { super(); this._register(this.languageModelsService.onDidChangeLanguageModels(() => this._onDidChange.fire())); + // Offered only while the Chat view can show, as the views are + const agentsViewActiveKeys = new Set([ChatContextKeys.agentsViewActive.key]); + this._register(this.contextKeyService.onDidChangeContext(e => { + if (e.affectsSome(agentsViewActiveKeys)) { + this._onDidChange.fire(); + } + })); for (const key of [DISMISSED_PROMOS_STORAGE_KEY, SEEN_PROMOS_STORAGE_KEY]) { this._register(this.storageService.onDidChangeValue(StorageScope.APPLICATION, key, this._store)(() => this._onDidChange.fire())); } @@ -215,6 +225,10 @@ export class ChatStatusPromo extends Disposable { } private getOpportunity(): IPromo | undefined { + // Trying a model opens it in the Chat view, which does not show while the Agents view replaces it + if (this.contextKeyService.getContextKeyValue(ChatContextKeys.agentsViewActive.key)) { + return undefined; + } const sessionType = this.resolveDefaultSessionType().sessionType; if (this.viewsService.isViewVisible(ChatViewId)) { const resource = this.viewsService.getViewWithId(ChatViewId)?.widget?.viewModel?.sessionResource; diff --git a/src/vs/workbench/contrib/chat/browser/chatTipCatalog.ts b/src/vs/workbench/contrib/chat/browser/chatTipCatalog.ts index 0aeb23677a68..fb155dc92e06 100644 --- a/src/vs/workbench/contrib/chat/browser/chatTipCatalog.ts +++ b/src/vs/workbench/contrib/chat/browser/chatTipCatalog.ts @@ -15,8 +15,10 @@ import { IsSessionsWindowContext } from '../../../common/contextkeys.js'; import { localChatSessionType } from '../common/chatSessionsService.js'; import { ITipExclusionConfig } from './chatTipEligibilityTracker.js'; import { TipTrackingCommands } from './chatTipStorageKeys.js'; -import { SessionIsCreatedContext } from '../../sessions/common/contextkeys.js'; +import { ChatInputCanScheduleContext, SessionIsCreatedContext } from '../../sessions/common/contextkeys.js'; import { SEND_IN_BACKGROUND_COMMAND_ID } from '../../sessions/common/sessionCommands.js'; +import { SESSIONS_SEND_LATER_ENABLED_SETTING } from '../../sessions/common/sessionConfig.js'; +import { ChatAutomationsEnabledContext } from '../common/automations/automationsEnabled.js'; import { GENERATE_AGENT_COMMAND_ID, GENERATE_AGENT_INSTRUCTIONS_COMMAND_ID, @@ -360,6 +362,38 @@ export const TIP_CATALOG: readonly ITipDefinition[] = [ ), excludeWhenCommandsExecuted: [TipTrackingCommands.BtwUsed], }, + { + id: 'tip.automate', + tier: ChatTipTier.Qol, + buildMessage() { + return new MarkdownString( + localize('tip.automate', "Use `/automate` to have the agent walk you through turning a task into a recurring automation.") + ); + }, + when: ContextKeyExpr.and( + ContextKeyExpr.equals(`config.${ChatConfiguration.AutomateTipEnabled}`, true), + IsSessionsWindowContext, + ChatContextKeys.enabled, + ChatAutomationsEnabledContext, + ), + excludeWhenToolsInvoked: ['vscode_configureAutomation'], + }, + { + id: 'tip.sendLater', + tier: ChatTipTier.Qol, + buildMessage() { + return new MarkdownString( + localize('tip.sendLater', "Ask the agent to send a request later using natural language, like \"check the build in 10 minutes\".") + ); + }, + when: ContextKeyExpr.and( + ContextKeyExpr.equals(`config.${SESSIONS_SEND_LATER_ENABLED_SETTING}`, true), + IsSessionsWindowContext, + ChatContextKeys.enabled, + ChatAutomationsEnabledContext, + ChatInputCanScheduleContext, + ), + }, { id: 'tip.forkConversation', tier: ChatTipTier.Qol, diff --git a/src/vs/workbench/contrib/chat/browser/chatTipService.ts b/src/vs/workbench/contrib/chat/browser/chatTipService.ts index 1fb65b0d53d8..4af8e1dc65d5 100644 --- a/src/vs/workbench/contrib/chat/browser/chatTipService.ts +++ b/src/vs/workbench/contrib/chat/browser/chatTipService.ts @@ -76,9 +76,14 @@ export interface IChatTipProvider { resetSession?(): void; clearDismissedTips?(): void; hasMultipleTips?(): boolean; + /** Overrides navigation with a provider-owned tip collection. Otherwise the tip joins catalog navigation. */ navigateTip?(direction: 1 | -1): IChatTip | undefined; } +type ChatTipNavigationTarget = + | { readonly kind: 'catalog'; readonly id: string; readonly definition: ITipDefinition } + | { readonly kind: 'provider'; readonly id: string; readonly tip: IChatTip; readonly provider: IChatTipProvider }; + export interface IChatTipService { readonly _serviceBrand: undefined; @@ -200,6 +205,7 @@ export class ChatTipService extends Disposable implements IChatTipService { private readonly _tipProviders = new Set(); private _activeTipProvider: IChatTipProvider | undefined; private _activeProvidedTip: IChatTip | undefined; + private _isNavigatingTips = false; /** * The request ID that was assigned a tip (for stable rerenders). @@ -361,7 +367,10 @@ export class ChatTipService extends Disposable implements IChatTipService { registerTipProvider(provider: IChatTipProvider): IDisposable { const store = new DisposableStore(); this._tipProviders.add(provider); - store.add(provider.onDidChange(() => this._onDidChangeTip.fire())); + store.add(provider.onDidChange(() => { + this._isNavigatingTips = false; + this._onDidChangeTip.fire(); + })); store.add(toDisposable(() => { this._tipProviders.delete(provider); if (this._activeTipProvider === provider) { @@ -374,6 +383,7 @@ export class ChatTipService extends Disposable implements IChatTipService { } resetSession(): void { + this._isNavigatingTips = false; for (const provider of this._tipProviders) { provider.resetSession?.(); } @@ -412,6 +422,7 @@ export class ChatTipService extends Disposable implements IChatTipService { } clearDismissedTips(): void { + this._isNavigatingTips = false; this._storageService.remove(ChatTipStorageKeys.DismissedTips, StorageScope.APPLICATION); this._storageService.remove(ChatTipStorageKeys.DismissedTips, StorageScope.PROFILE); this._shownTip = undefined; @@ -533,6 +544,12 @@ export class ChatTipService extends Disposable implements IChatTipService { } for (const provider of this._tipProviders) { + if (this._isNavigatingTips && this._shownTip) { + break; + } + if (this._isNavigatingTips && this._activeTipProvider && this._activeTipProvider !== provider) { + continue; + } const tip = provider.provideTip(); if (tip) { const isNewTip = this._activeTipProvider !== provider || this._activeProvidedTip?.id !== tip.id; @@ -751,7 +768,7 @@ export class ChatTipService extends Disposable implements IChatTipService { } hasMultipleTips(): boolean { - if (this._activeProvidedTip) { + if (this._activeProvidedTip && this._activeTipProvider?.navigateTip) { return this._activeTipProvider?.hasMultipleTips?.() ?? false; } if (!this._contextKeyService) { @@ -763,7 +780,7 @@ export class ChatTipService extends Disposable implements IChatTipService { } private _navigateTip(direction: 1 | -1, contextKeyService: IContextKeyService): IChatTip | undefined { - if (this._activeTipProvider && this._activeProvidedTip) { + if (this._activeTipProvider?.navigateTip && this._activeProvidedTip) { const previousTip = this._activeProvidedTip; const tip = this._activeTipProvider.navigateTip?.(direction); if (tip) { @@ -776,15 +793,16 @@ export class ChatTipService extends Disposable implements IChatTipService { return tip; } this._createSlashCommandsUsageTracker.syncContextKey(contextKeyService); - if (!this._shownTip) { + const previousTip = this._activeProvidedTip ?? this._shownTip; + if (!previousTip) { return undefined; } - const orderedTips = this._getOrderedEligibleTips(contextKeyService); + const orderedTips = this._getOrderedNavigationTips(contextKeyService); if (!orderedTips.length) { return undefined; } - const currentIndex = orderedTips.findIndex(tip => tip.id === this._shownTip!.id); + const currentIndex = orderedTips.findIndex(tip => tip.id === previousTip.id); if (orderedTips.length === 1 && currentIndex !== -1) { return undefined; } @@ -795,11 +813,17 @@ export class ChatTipService extends Disposable implements IChatTipService { : (currentIndex + direction + orderedTips.length) % orderedTips.length; const candidate = orderedTips[nextIndex]; if (candidate) { - this._logTipTelemetry(this._shownTip.id, direction === 1 ? 'navigateNext' : 'navigatePrevious'); - this._shownTip = candidate; + this._logTipTelemetry(previousTip.id, direction === 1 ? 'navigateNext' : 'navigatePrevious'); + const provided = candidate.kind === 'provider'; + this._isNavigatingTips = true; + this._activeTipProvider = provided ? candidate.provider : undefined; + this._activeProvidedTip = provided ? candidate.tip : undefined; + this._shownTip = provided ? undefined : candidate.definition; this._tipRequestId = 'welcome'; - this._storageService.store(ChatTipStorageKeys.LastTipId, candidate.id, StorageScope.APPLICATION, StorageTarget.USER); - const tip = this._createTip(candidate); + if (!provided) { + this._storageService.store(ChatTipStorageKeys.LastTipId, candidate.id, StorageScope.APPLICATION, StorageTarget.USER); + } + const tip = provided ? candidate.tip : this._createTip(candidate.definition); this._logTipTelemetry(candidate.id, 'shown'); this._trackTipCommandClicks(tip); this._onDidNavigateTip.fire(tip); @@ -810,12 +834,13 @@ export class ChatTipService extends Disposable implements IChatTipService { } private _hasNavigableTip(contextKeyService: IContextKeyService): boolean { - const orderedTips = this._getOrderedEligibleTips(contextKeyService); + const orderedTips = this._getOrderedNavigationTips(contextKeyService); if (!orderedTips.length) { return false; } - if (!this._shownTip) { + const currentTip = this._activeProvidedTip ?? this._shownTip; + if (!currentTip) { return orderedTips.length > 1; } @@ -823,7 +848,23 @@ export class ChatTipService extends Disposable implements IChatTipService { return true; } - return orderedTips[0].id !== this._shownTip.id; + return orderedTips[0].id !== currentTip.id; + } + + private _getOrderedNavigationTips(contextKeyService: IContextKeyService): ChatTipNavigationTarget[] { + const tips: ChatTipNavigationTarget[] = []; + for (const provider of this._tipProviders) { + if (!provider.navigateTip) { + const tip = provider.provideTip(); + if (tip) { + tips.push({ kind: 'provider', id: tip.id, tip, provider }); + } + } + } + for (const definition of this._getOrderedEligibleTips(contextKeyService)) { + tips.push({ kind: 'catalog', id: definition.id, definition }); + } + return tips; } private _getOrderedEligibleTips(contextKeyService: IContextKeyService, options?: { excludeShownTip?: boolean; includeTipId?: string }): ITipDefinition[] { diff --git a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts new file mode 100644 index 000000000000..fc6589af2b94 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/chatViewHost.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 { IDisposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { SessionTypeSelectionReason } from '../common/constants.js'; +import { IChatWidget } from './chat.js'; + +export const IChatViewHostService = createDecorator('chatViewHostService'); + +/** How {@link IChatViewHost.reveal} shows the host. */ +export interface IChatViewHostRevealOptions { + /** + * Waits for the widget of the chat it shows while the host has none yet, such as the Chat view before its body first + * renders, rather than resolving to `undefined`. + */ + readonly waitForWidget?: boolean; +} + +/** How {@link IChatViewHost.openSession} shows a session. */ +export interface IChatViewHostOpenOptions { + readonly preserveFocus?: boolean; + readonly sessionTypeSelectionReason?: SessionTypeSelectionReason; +} + +/** How {@link IChatViewHost.startSession} starts a session that its caller may send a first request to. */ +export interface IChatViewHostSessionStartOptions { + /** Whether the session is a new local chat, rather than the session of the given resource. */ + readonly local: boolean; + /** Whether its first request copies another conversation, which can take a while to show. */ + readonly importingConversation: boolean; + /** Called once the host shows, before the session loads. */ + readonly beforeOpen?: () => void; +} + +/** A session that {@link IChatViewHost.startSession} started; disposing it ends the start without completing it. */ +export interface IChatViewHostSessionStart extends IDisposable { + /** The session moved to `sessionResource`, such as an untitled session that its first request made real. */ + moved(sessionResource: URI): Promise; + /** + * The start is done: its first request, if any, was sent (`sent`) or not, and the session is `sessionResource`. Resolves + * to whether the host shows the session, such as not a new session whose request did not run. + */ + complete(sessionResource: URI, sent: boolean): Promise; + /** + * A new-session composer of the session's type, to put back a first request that was not sent and that the host does not + * show; `undefined` when the host has none. + */ + createComposer(): Promise; +} + +/** + * What shows the chats of the Chat view: the Chat view itself, unless something replaces it, such as the Agents view of an + * editor window. + */ +export interface IChatViewHost { + /** Shows the host and resolves to the widget of the chat it shows. */ + reveal(preserveFocus?: boolean, options?: IChatViewHostRevealOptions): Promise; + /** + * Shows the host and resolves to the widget of the chat of `sessionResource` when the host already holds that chat, without + * loading it again; to `undefined` when it does not. A host that does not implement it holds no chat to reveal this way. + */ + revealIfShowing?(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise; + /** Shows the chat of `sessionResource` in the host and resolves to its widget; to `undefined` when it cannot show it. */ + openSession(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise; + /** Shows the host, or hides it while it shows. Resolves to whether it shows afterwards. */ + toggle(): Promise; + /** Starts showing the session of `sessionResource`, which its caller may send a first request to. */ + startSession(sessionResource: URI, options: IChatViewHostSessionStartOptions): Promise; +} + +/** + * The host of the Chat view's chats. Everything that would show the Chat view goes through it. By default the host is the + * Chat view; a host registered with {@link registerHost} replaces it while registered. + */ +export interface IChatViewHostService extends IChatViewHost { + readonly _serviceBrand: undefined; + + revealIfShowing(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise; + + /** + * Replaces the Chat view with `host` until the returned disposable is disposed. The host registered last is the one in + * use; disposing it gives the use back to the one before. + */ + registerHost(host: IChatViewHost): IDisposable; +} diff --git a/src/vs/workbench/contrib/chat/browser/claudePluginRecommendations.ts b/src/vs/workbench/contrib/chat/browser/claudePluginRecommendations.ts index fdee276812b1..601a2ba5d88a 100644 --- a/src/vs/workbench/contrib/chat/browser/claudePluginRecommendations.ts +++ b/src/vs/workbench/contrib/chat/browser/claudePluginRecommendations.ts @@ -55,7 +55,7 @@ export class AgentPluginRecommendations extends Disposable implements IWorkbench let fetched: readonly IMarketplacePlugin[] = this._pluginMarketplaceService.lastFetchedPlugins.get(); if (fetched.length === 0) { try { - fetched = await this._pluginMarketplaceService.fetchMarketplacePlugins(CancellationToken.None); + fetched = await this._pluginMarketplaceService.fetchMarketplacePlugins(CancellationToken.None, undefined, { priority: 'background' }); } catch { return; } diff --git a/src/vs/workbench/contrib/chat/browser/customAgentUsage.contribution.ts b/src/vs/workbench/contrib/chat/browser/customAgentUsage.contribution.ts new file mode 100644 index 000000000000..97fc5a4d51b7 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/customAgentUsage.contribution.ts @@ -0,0 +1,66 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Disposable } from '../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../platform/product/common/productService.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { IChatRequestAcceptedEvent, IChatService } from '../common/chatService/chatService.js'; +import { CustomAgentUsage } from '../common/customAgentUsage.js'; +import { ICustomizationHarnessService } from '../common/customizationHarnessService.js'; +import { IChatRequestModeInfo } from '../common/model/chatModel.js'; +import { PromptsStorage } from '../common/promptSyntax/service/promptsService.js'; +import { isBuiltinAgent } from '../common/promptSyntax/utils/promptsServiceUtils.js'; + +/** + * Whether a request ran a custom agent rather than an agent built into the product, such as Agent, Ask, or an + * agent of the built-in chat extension. Matches the custom agents the agent picker spotlight points to. + */ +async function isCustomAgentRequest(modeInfo: IChatRequestModeInfo | undefined, sessionResource: URI, customizationHarnessService: ICustomizationHarnessService, productService: IProductService): Promise { + if (!modeInfo || modeInfo.isBuiltin) { + return false; + } + const uri = modeInfo.modeInstructions?.uri; + if (!uri) { + return true; + } + const agents = await customizationHarnessService.getCustomAgents(sessionResource, CancellationToken.None); + const agent = agents.find(agent => agent.id === uri.toString() || isEqual(agent.uri, uri)); + return !agent || (agent.source.storage !== PromptsStorage.builtIn && !isBuiltinAgent(agent.source, agent.sourceUri ?? agent.uri, productService)); +} + +/** Records each request the user submits with a custom agent in any window. */ +export class CustomAgentUsageContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.customAgentUsage'; + + private readonly usage: CustomAgentUsage; + + constructor( + @IChatService chatService: IChatService, + @ICustomizationHarnessService private readonly customizationHarnessService: ICustomizationHarnessService, + @IProductService private readonly productService: IProductService, + @IStorageService storageService: IStorageService, + @ILogService private readonly logService: ILogService, + ) { + super(); + this.usage = new CustomAgentUsage(storageService); + this._register(chatService.onDidAcceptRequest(event => void this.recordRequest(event, Date.now()))); + } + + private async recordRequest({ chatSessionResource, modeInfo }: IChatRequestAcceptedEvent, timestamp: number): Promise { + try { + if (await isCustomAgentRequest(modeInfo, chatSessionResource, this.customizationHarnessService, this.productService)) { + this.usage.recordUse(timestamp); + } + } catch (error) { + this.logService.error('[CustomAgentUsage] Failed to record custom agent usage', error); + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.contribution.ts b/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.contribution.ts new file mode 100644 index 000000000000..6b51329ea38a --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.contribution.ts @@ -0,0 +1,9 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../../common/contributions.js'; +import { AgentPickerSpotlight } from './agentPickerSpotlight.js'; + +registerWorkbenchContribution2(AgentPickerSpotlight.ID, AgentPickerSpotlight, WorkbenchPhase.AfterRestored); diff --git a/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.ts b/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.ts new file mode 100644 index 000000000000..33e0492062e4 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/onboarding/agentPickerSpotlight.ts @@ -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 { AnimationFrameScheduler, DisposableResizeObserver } from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Event } from '../../../../../base/common/event.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, derived, IObservable, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { observableConfigValue } from '../../../../../platform/observable/common/platformObservableUtils.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { EditorPartModalVisibleContext } from '../../../../common/contextkeys.js'; +import { isVisibleOnboardingTarget, registerOnboardingTargetProvider, resolveOnboardingTarget } from '../../../onboarding/browser/spotlight/onboardingTarget.js'; +import { ISpotlightPayload, SPOTLIGHT_PRESENTATION_KIND } from '../../../onboarding/browser/spotlight/spotlightTypes.js'; +import { onboardingScenarioRegistry } from '../../../onboarding/common/onboardingRegistry.js'; +import { IOnboardingScenario } from '../../../onboarding/common/onboardingScenario.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; +import { ChatAgentLocation, ChatConfiguration } from '../../common/constants.js'; +import { IChatWidget, IChatWidgetService } from '../chat.js'; +import { isModeConsideredBuiltIn } from '../widget/input/modePickerActionItem.js'; + +export const AGENT_PICKER_SPOTLIGHT_ID = 'chat.onboarding.agentPickerInAttachContext'; + +export class AgentPickerSpotlight extends Disposable { + static readonly ID = 'workbench.contrib.agentPickerSpotlight'; + + constructor( + @IConfigurationService configurationService: IConfigurationService, + @IChatWidgetService chatWidgetService: IChatWidgetService, + @IProductService productService: IProductService, + ) { + super(); + const enabled = observableConfigValue(ChatConfiguration.AgentsPickerInAttachContextMenu, false, configurationService); + const widgetsChanged = observableSignalFromEvent(this, Event.any( + chatWidgetService.onDidAddWidget, + chatWidgetService.onDidRemoveWidget, + chatWidgetService.onDidChangeWidgetVisibility, + chatWidgetService.onDidChangeFocusedWidget, + )); + const inputChanged = derived(this, reader => { + widgetsChanged.read(reader); + return observableSignalFromEvent(this, Event.any(...chatWidgetService.getWidgetsByLocations(ChatAgentLocation.Chat) + .map(widget => widget.inputPart.onDidChangeAttachContextButton))); + }); + const eligibleChats = derived(this, reader => { + widgetsChanged.read(reader); + if (!enabled.read(reader)) { + return []; + } + inputChanged.read(reader).read(reader); + return chatWidgetService.getWidgetsByLocations(ChatAgentLocation.Chat).filter(widget => { + widget.inputPart.currentModeObs.read(reader); + return widget.domNode.ownerDocument === mainWindow.document && widget.visible && widget.inputPart.isAgentPickerInAttachContextMenu; + }); + }); + this._register(registerAgentPickerSpotlight(eligibleChats, productService)); + } +} + +/** Shares the tip and shown-once state for composers with custom agents in either window. */ +export function registerAgentPickerSpotlight(chats: IObservable, productService: IProductService): IDisposable { + const store = new DisposableStore(); + const modesChanged = derived(store, reader => observableSignalFromEvent(store, Event.any( + ...chats.read(reader).map(widget => widget.inputPart.currentChatModesObs.read(reader).onDidChange), + ))); + const eligibleChats = derived(store, reader => { + modesChanged.read(reader).read(reader); + return chats.read(reader).filter(widget => widget.inputPart.currentChatModesObs.read(reader).custom + .some(mode => !isModeConsideredBuiltIn(mode, productService))); + }); + const targetReady = observableValue(store, false); + store.add(registerOnboardingTargetProvider(AGENT_PICKER_SPOTLIGHT_ID, scope => { + const widget = eligibleChats.get().find(widget => { + const element = widget.inputPart.attachContextButtonElement; + return widget.visible && element && isVisibleOnboardingTarget(mainWindow, element); + }); + const element = widget?.inputPart.attachContextButtonElement; + return scope === undefined && widget?.visible && element ? { element, onDidActivate: widget.inputPart.onDidActivateAttachContext } : undefined; + })); + store.add(autorun(reader => { + targetReady.set(false, undefined); + const scheduler = reader.store.add(new AnimationFrameScheduler(mainWindow.document.body, () => { + targetReady.set(!!resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID), undefined); + })); + const observer = reader.store.add(new DisposableResizeObserver('AgentPickerSpotlight.target', () => scheduler.schedule())); + for (const widget of eligibleChats.read(reader)) { + if (widget.domNode.ownerDocument !== mainWindow.document) { + continue; + } + const observation = reader.store.add(new MutableDisposable()); + const updateTarget = () => { + targetReady.set(false, undefined); + const element = widget.inputPart.attachContextButtonElement; + observation.value = element ? observer.observe(element) : undefined; + scheduler.schedule(); + }; + reader.store.add(widget.inputPart.onDidChangeAttachContextButton(updateTarget)); + updateTarget(); + } + })); + const scenario: IOnboardingScenario = { + id: AGENT_PICKER_SPOTLIGHT_ID, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + ContextKeyExpr.equals(`config.${ChatConfiguration.AgentsPickerInAttachContextMenu}`, true), + EditorPartModalVisibleContext.toNegated(), + ), + trigger: { kind: 'observable', signal: targetReady }, + presentation: { + kind: SPOTLIGHT_PRESENTATION_KIND, + payload: { + steps: [{ + id: 'agentPicker', + targetId: AGENT_PICKER_SPOTLIGHT_ID, + title: localize('agentPickerSpotlight.title', "Find your custom agents"), + description: localize('agentPickerSpotlight.description', "We default to Agent, find your custom agents in the + menu"), + nextButtonLabel: localize('agentPickerSpotlight.understood', "Understood"), + placement: 'above', + allowTargetInteraction: true, + advanceOnTargetClick: true, + hideNext: false, + missingTarget: { kind: 'wait', timeoutMs: 1000 }, + }], + }, + }, + }; + store.add(onboardingScenarioRegistry.register(scenario)); + return store; +} diff --git a/src/vs/workbench/contrib/chat/browser/planReviewFeedback/media/planReviewFeedback.css b/src/vs/workbench/contrib/chat/browser/planReviewFeedback/media/planReviewFeedback.css index a00c20cdca30..7c931bd43711 100644 --- a/src/vs/workbench/contrib/chat/browser/planReviewFeedback/media/planReviewFeedback.css +++ b/src/vs/workbench/contrib/chat/browser/planReviewFeedback/media/planReviewFeedback.css @@ -105,7 +105,7 @@ padding: 4px 6px; font-size: 11px; line-height: 14px; - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); } .plan-review-feedback-overlay-widget .monaco-action-bar .actions-container { diff --git a/src/vs/workbench/contrib/chat/browser/pluginInstallService.ts b/src/vs/workbench/contrib/chat/browser/pluginInstallService.ts index ca57f941bd8c..96f0b93f99c4 100644 --- a/src/vs/workbench/contrib/chat/browser/pluginInstallService.ts +++ b/src/vs/workbench/contrib/chat/browser/pluginInstallService.ts @@ -127,8 +127,8 @@ export class PluginInstallService implements IPluginInstallService { private async _doInstallFromSource(reference: IMarketplaceReference, options?: IInstallPluginFromSourceOptions): Promise { // Build a source descriptor for the git clone. const sourceDescriptor = reference.kind === MarketplaceReferenceKind.GitHubShorthand - ? { kind: PluginSourceKind.GitHub as const, repo: reference.githubRepo!, ...(options?.path !== undefined && reference.ref ? { ref: reference.ref } : {}) } - : { kind: PluginSourceKind.GitUrl as const, url: reference.cloneUrl, ...(options?.path !== undefined && reference.ref ? { ref: reference.ref } : {}) }; + ? { kind: PluginSourceKind.GitHub as const, repo: reference.githubRepo!, ...(reference.ref ? { ref: reference.ref } : {}) } + : { kind: PluginSourceKind.GitUrl as const, url: reference.cloneUrl, ...(reference.ref ? { ref: reference.ref } : {}) }; // Build a temporary plugin object for the trust gate and clone step. const tempPlugin: IMarketplacePlugin = { @@ -549,7 +549,7 @@ export class PluginInstallService implements IPluginInstallService { // 2. Re-fetch marketplace data *after* pulling so we see any // updated plugin descriptors (new versions, refs, etc.). const marketplaceIds = new Set(installed.map(entry => entry.plugin.marketplaceReference.canonicalId)); - const marketplacePlugins = await this._pluginMarketplaceService.fetchMarketplacePlugins(token, marketplaceIds, { refresh: true }); + const marketplacePlugins = await this._pluginMarketplaceService.fetchMarketplacePlugins(token, marketplaceIds, { refresh: true, priority: options.automatic ? 'background' : undefined }); const marketplaceByKey = new Map(); for (const mp of marketplacePlugins) { marketplaceByKey.set(`${mp.marketplaceReference.canonicalId}::${mp.name}`, mp); diff --git a/src/vs/workbench/contrib/chat/browser/pluginUrlHandler.ts b/src/vs/workbench/contrib/chat/browser/pluginUrlHandler.ts index 9adef360f5b6..e0111fc5faec 100644 --- a/src/vs/workbench/contrib/chat/browser/pluginUrlHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/pluginUrlHandler.ts @@ -9,47 +9,55 @@ import { CancellationToken } from '../../../../base/common/cancellation.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { isCancellationError } from '../../../../base/common/errors.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; +import { isWeb } from '../../../../base/common/platform.js'; import { URI } from '../../../../base/common/uri.js'; import { localize } from '../../../../nls.js'; import { COPILOT_CLI_AGENT_PROVIDER_ID } from '../../../../platform/agentHost/common/agent.js'; +import { IAgentHostService } from '../../../../platform/agentHost/common/agentService.js'; import { ICommandService } from '../../../../platform/commands/common/commands.js'; -import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { CustomizationMarketplaceMediaType, getCustomizationMarketplaceResourceKey, ICustomizationMarketplaceCursor, ICustomizationMarketplaceResource, ICustomizationMarketplaceService } from '../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; +import { CustomizationMarketplaceSources, getEnabledCustomizationMarketplaceSources } from '../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js'; import { IURLHandler, IURLService } from '../../../../platform/url/common/url.js'; import { IChatEntitlementService } from '../../../services/chat/common/chatEntitlementService.js'; import { IHostService } from '../../../services/host/browser/host.js'; import { IWorkbenchEnvironmentService } from '../../../services/environment/common/environmentService.js'; import { IWorkbenchContribution } from '../../../common/contributions.js'; import { AICustomizationManagementCommands } from '../common/aiCustomizationWorkspaceService.js'; -import { IChatSessionsService, INewSessionInAgentsWindowOptions, NEW_SESSION_IN_AGENTS_WINDOW_COMMAND_ID, SessionType } from '../common/chatSessionsService.js'; +import { SessionType } from '../common/chatSessionsService.js'; import { ChatConfiguration } from '../common/constants.js'; import { ICustomizationHarnessService } from '../common/customizationHarnessService.js'; -import { isUntitledChatSession } from '../common/model/chatUri.js'; -import { MarketplaceReferenceKind, parseMarketplaceReference, parseProviderMarketplaceReference } from '../common/plugins/marketplaceReference.js'; -import { IAgentSessionsService } from './agentSessions/agentSessionsService.js'; -import { IAgentHostNewSessionFolderService } from './agentSessions/agentHost/agentHostNewSessionFolderService.js'; -import { IAgentHostUntitledProvisionalSessionService } from './agentSessions/agentHost/agentHostUntitledProvisionalSessionService.js'; -import { getProviderMarketplaceSourceId } from './aiCustomization/customizationMarketplaceWorkbenchService.js'; - -/** - * Handles confirmed Copilot Agent Host marketplace links: `/add-marketplace?ref=owner/repo` - * and `/install?source=owner/repo&plugin=name` under `vscode://chat-plugin`. - */ +import { IPluginInstallService } from '../common/plugins/pluginInstallService.js'; +import { DEFAULT_PLUGIN_MARKETPLACE, IMarketplaceReference, MarketplaceReferenceKind, parseMarketplaceReferences, parseProviderMarketplaceReference, readConfiguredMarketplaces } from '../common/plugins/marketplaceReference.js'; +import { isDefaultPluginMarketplace } from './aiCustomization/pluginCustomizationMarketplaceProvider.js'; + +const awesomeCopilotCatalogIdentityPrefix = 'urn:air:github.com:github:awesome-copilot:'; +const defaultPluginMarketplaceReference = parseProviderMarketplaceReference(DEFAULT_PLUGIN_MARKETPLACE)!; + +type PluginLinkHarness = 'copilot' | 'vscode'; + +interface IPluginLinkHarnessPick extends IQuickPickItem { + readonly harness: PluginLinkHarness; +} + +/** Handles external marketplace and plugin installation links after explicit owner selection and consent. */ export class PluginUrlHandler extends Disposable implements IWorkbenchContribution, IURLHandler { static readonly ID = 'workbench.contrib.pluginUrlHandler'; constructor( @IURLService urlService: IURLService, + @IAgentHostService private readonly agentHostService: IAgentHostService, @ICustomizationHarnessService private readonly harnessService: ICustomizationHarnessService, - @IAgentSessionsService private readonly sessionsService: IAgentSessionsService, - @IChatSessionsService private readonly chatSessionsService: IChatSessionsService, - @IAgentHostUntitledProvisionalSessionService private readonly provisionalSessionService: IAgentHostUntitledProvisionalSessionService, - @IAgentHostNewSessionFolderService private readonly newSessionFolderService: IAgentHostNewSessionFolderService, + @IPluginInstallService private readonly pluginInstallService: IPluginInstallService, + @IQuickInputService private readonly quickInputService: IQuickInputService, @IDialogService private readonly dialogService: IDialogService, @IConfigurationService private readonly configurationService: IConfigurationService, + @ICustomizationMarketplaceService private readonly marketplaceService: ICustomizationMarketplaceService, @IChatEntitlementService private readonly entitlementService: IChatEntitlementService, @ICommandService private readonly commandService: ICommandService, @IHostService private readonly hostService: IHostService, @@ -67,10 +75,7 @@ export class PluginUrlHandler extends Disposable implements IWorkbenchContributi } try { - if (this.entitlementService.sentiment.hidden || this.entitlementService.sentiment.disabledInWorkspace || - this.configurationService.getValue(ChatConfiguration.PluginsEnabled) !== true) { - throw new Error(localize('pluginLinksDisabled', "Plugin links are unavailable because chat or plugins are disabled.")); - } + this.ensureLinksEnabled(); const params = new URLSearchParams(uri.query); const sourceKey = uri.path === '/install' ? 'source' : 'ref'; @@ -83,63 +88,49 @@ export class PluginUrlHandler extends Disposable implements IWorkbenchContributi if (uri.path === '/install' && (!pluginName || params.getAll('plugin').length !== 1 || /[@\u0000-\u001f\u007f]/.test(pluginName))) { throw new Error(localize('invalidPluginLinkName', "The plugin link must specify a plugin name.")); } + const hint = params.get('harness'); + if (params.getAll('harness').length > 1 || (hint !== null && hint !== 'copilot' && hint !== 'vscode')) { + throw new Error(localize('invalidPluginLinkHarness', "The plugin link must specify at most one harness: 'copilot' or 'vscode'.")); + } + if (isWeb || this.environmentService.remoteAuthority) { + throw new Error(localize('pluginLinkLocalWindowRequired', "Open this plugin link in a local VS Code desktop window. Plugin links do not install into a remote workspace or web environment.")); + } await this.hostService.focus(mainWindow); + const harness = hint ?? await this.selectHarness(); + if (!harness) { + return true; + } + const owner = harness === 'copilot' + ? localize('copilotPluginLinkOwner', "Copilot's user installation on this machine") + : localize('vscodePluginLinkOwner', "VS Code's shared plugin installation on this machine"); const { confirmed } = await this.dialogService.confirm({ type: 'warning', message: pluginName - ? localize('confirmAddMarketplaceAndPlugin', "Add Marketplace '{0}' and Install Plugin '{1}'?", ref.displayLabel, pluginName) + ? localize('confirmInstallPluginFromSource', "Install Plugin '{1}' from '{0}'?", ref.displayLabel, pluginName) : localize('confirmAddMarketplace', "Add Plugin Marketplace '{0}'?", ref.displayLabel), detail: pluginName - ? localize('confirmMarketplacePluginLinkDetail', "An external application wants to add this marketplace and install a plugin. Plugins can run code on your machine. Continue only if you initiated this request and trust this source.\n\nSource: {0}", ref.rawValue) - : localize('confirmMarketplaceLinkDetail', "An external application wants to add this plugin marketplace. Continue only if you initiated this request and trust this source.\n\nSource: {0}", ref.rawValue), + ? localize('confirmPluginLinkDetail', "An external application wants to install a plugin from this source into {0}. Plugins can run code on your machine. Continue only if you initiated this request and trust this source. This does not trust or run code from your workspace.\n\nSource: {1}", owner, ref.rawValue) + : localize('confirmMarketplaceLinkDetail', "An external application wants to add this plugin marketplace to {0}. Continue only if you initiated this request and trust this source.\n\nSource: {1}", owner, ref.rawValue), primaryButton: pluginName - ? localize('addMarketplaceAndInstallButton', "&&Add Marketplace and Install") + ? localize('installPluginButton', "&&Install") : localize('addMarketplaceButton', "&&Add Marketplace"), custom: { icon: Codicon.shield }, }); if (!confirmed) { return true; } + this.ensureLinksEnabled(); - const session = await this.resolveSession(); - if (!session) { + if (harness === 'copilot') { + await this.installForCopilot(ref, pluginName ?? undefined); + } else if (!await this.installForVSCode(ref, pluginName ?? undefined)) { return true; } - const descriptor = this.harnessService.getDescriptorForSession(session.resource); - const managementProvider = descriptor?.marketplaceManagementProvider; - const installProvider = descriptor?.marketplaceInstallProvider; - if (!managementProvider || (pluginName && !installProvider)) { - throw new Error(localize('pluginLinkHarnessUnavailable', "The selected Copilot Agent Host session does not support marketplace management or plugin installation.")); - } - - const marketplaces = await managementProvider.list(session.backendResource); - const existingMarketplace = marketplaces.find(marketplace => parseProviderMarketplaceReference(marketplace.source)?.canonicalId === ref.canonicalId); - const marketplace = existingMarketplace ?? await managementProvider.add(session.backendResource, ref.rawValue); - if (pluginName && installProvider) { - let cursor: string | undefined; - const seenCursors = new Set(); - while (true) { - const page = await managementProvider.queryMarketplace(session.backendResource, marketplace, { query: pluginName, cursor }, CancellationToken.None); - const plugin = page.items.find(item => item.installation?.kind === 'providerPlugin' && item.installation.name === pluginName); - if (plugin) { - await installProvider.install(session.backendResource, { - ...plugin, - sourceId: getProviderMarketplaceSourceId(marketplace.name), - }, CancellationToken.None); - break; - } - if (!page.nextCursor || seenCursors.has(page.nextCursor)) { - throw new Error(localize('pluginLinkPluginNotFound', "Marketplace '{0}' was added, but plugin '{1}' was not found. No plugin was installed.", marketplace.name, pluginName)); - } - cursor = page.nextCursor; - seenCursors.add(cursor); - } - } await this.commandService.executeCommand(AICustomizationManagementCommands.OpenEditor, { showDiscover: true, - sessionResource: session.resource, + sessionType: harness === 'copilot' ? SessionType.AgentHostCopilot : SessionType.Local, searchQuery: pluginName ?? '', }); } catch (error) { @@ -151,53 +142,184 @@ export class PluginUrlHandler extends Disposable implements IWorkbenchContributi return true; } - private async resolveSession(): Promise<{ resource: URI; backendResource: URI } | undefined> { - let resource = this.harnessService.activeSessionResource.get(); - if (resource.scheme === SessionType.AgentHostCopilot) { - const provisional = this.provisionalSessionService.get(resource); - if (provisional) { - return { resource, backendResource: provisional }; - } - if (!isUntitledChatSession(resource)) { - return { resource, backendResource: resource }; - } + private async resolveAgentFinderPlugin(pluginName: string): Promise { + const sourceId = CustomizationMarketplaceSources.AgentFinderPublicFeed.id; + if (!getEnabledCustomizationMarketplaceSources(this.configurationService, this.marketplaceService.sources).some(source => source.id === sourceId)) { + return undefined; + } + + const requestedIdentity = pluginName.toLowerCase(); + const matches = await this.queryAgentFinderPlugins(pluginName, item => { + const installation = item.installation; + const catalogIdentity = installation?.kind === 'providerCatalog' + ? installation.catalogIdentity?.toLowerCase() + : undefined; + const expectedIdentity = requestedIdentity.startsWith(awesomeCopilotCatalogIdentityPrefix) + ? requestedIdentity + : `${awesomeCopilotCatalogIdentityPrefix}${requestedIdentity}`; + return installation?.kind === 'providerCatalog' && + installation.resourceKind === 'plugin' && + catalogIdentity?.startsWith(awesomeCopilotCatalogIdentityPrefix) === true && + catalogIdentity === expectedIdentity; + }); + if (matches.length === 0 && !requestedIdentity.startsWith('urn:')) { + matches.push(...await this.getAgentFinderBrowsePlugins(item => { + const installation = item.installation; + const reference = installation?.kind === 'providerPlugin' && installation.marketplaceSource + ? parseProviderMarketplaceReference(installation.marketplaceSource) + : undefined; + return installation?.kind === 'providerPlugin' && + installation.name.toLowerCase() === requestedIdentity && + !!reference && + isDefaultPluginMarketplace(reference); + })); } - if (!await this.chatSessionsService.canResolveChatSession(SessionType.AgentHostCopilot)) { - throw new Error(localize('pluginLinkCopilotUnavailable', "Plugin links require Copilot on the Agent Host.")); + if (matches.length === 0) { + throw new Error(localize('pluginLinkAgentFinderPluginNotFound', "The plugin '{0}' was not found in the GitHub Feed.", pluginName)); } - await this.sessionsService.model.resolve(SessionType.AgentHostCopilot, error => { throw error; }); - const existing = this.sessionsService.model.sessions.find(session => session.providerType === SessionType.AgentHostCopilot && !session.isArchived()); - if (existing) { - return { resource: existing.resource, backendResource: existing.resource }; + if (matches.length > 1) { + throw new Error(localize('pluginLinkAgentFinderPluginAmbiguous', "Multiple GitHub Feed plugins matched '{0}'.", pluginName)); + } + return matches[0]; + } + + private async getAgentFinderBrowsePlugins( + predicate: (item: ICustomizationMarketplaceResource) => boolean, + ): Promise { + const result = await this.marketplaceService.getBrowseSections?.({ + sourceIds: [CustomizationMarketplaceSources.AgentFinderPublicFeed.id], + }, CancellationToken.None); + if (result?.error) { + throw new Error(result.error); } - const { confirmed } = await this.dialogService.confirm({ - type: 'question', - message: localize('createPluginLinkSession', "Create a Copilot Agent Host Session for This Link?"), - detail: localize('createPluginLinkSessionDetail', "Adding a marketplace requires a Copilot Agent Host session. No existing session is available."), - primaryButton: localize('createPluginLinkSessionButton', "&&Create Session"), + const matches = new Map(); + for (const section of result?.sections ?? []) { + for (const item of section.items) { + if (predicate(item)) { + matches.set(getCustomizationMarketplaceResourceKey(item), item); + } + } + } + return [...matches.values()]; + } + + private async queryAgentFinderPlugins( + query: string, + predicate: (item: ICustomizationMarketplaceResource) => boolean, + ): Promise { + const matches: ICustomizationMarketplaceResource[] = []; + let cursor: ICustomizationMarketplaceCursor | undefined; + do { + const page = await this.marketplaceService.query({ + sourceIds: [CustomizationMarketplaceSources.AgentFinderPublicFeed.id], + mediaType: CustomizationMarketplaceMediaType.CopilotPlugin, + query, + pageSize: 50, + cursor, + }, CancellationToken.None); + if (page.sourceErrors?.length) { + throw new Error(page.sourceErrors.map(error => error.message).join('\n')); + } + matches.push(...page.items.filter(predicate)); + cursor = page.nextCursor; + } while (matches.length < 2 && cursor); + return matches; + } + + private ensureLinksEnabled(): void { + if (this.entitlementService.sentiment.hidden || this.entitlementService.sentiment.disabledInWorkspace || + this.configurationService.getValue(ChatConfiguration.PluginsEnabled) !== true) { + throw new Error(localize('pluginLinksDisabled', "Plugin links are unavailable because chat or plugins are disabled.")); + } + } + + private async selectHarness(): Promise { + const picks: IPluginLinkHarnessPick[] = [{ + harness: 'copilot', + label: localize('pluginLinkCopilot', "Copilot"), + description: localize('pluginLinkCopilotDescription', "Native Copilot plugins on this machine"), + detail: localize('pluginLinkCopilotDetail', "No chat session is required. Does not install for Claude or Codex."), + }, { + harness: 'vscode', + label: localize('pluginLinkVSCode', "VS Code"), + description: localize('pluginLinkVSCodeDescription', "VS Code-managed shared plugins on this machine"), + detail: localize('pluginLinkVSCodeDetail', "Available to compatible harnesses through VS Code. Does not install into native Claude or Codex inventories."), + }]; + const picked = await this.quickInputService.pick(picks, { + title: localize('pluginLinkSelectHarness', "Choose Where to Install Plugins"), + placeHolder: localize('pluginLinkSelectHarnessPlaceholder', "Select the owner of this marketplace and plugin installation"), + activeItem: picks[0], + matchOnDescription: true, + matchOnDetail: true, }); - if (!confirmed) { - return undefined; + return picked?.harness; + } + + private async installForCopilot(ref: IMarketplaceReference, pluginName: string | undefined): Promise { + const agentFinderPlugin = pluginName && !ref.ref && isDefaultPluginMarketplace(ref) + ? await this.resolveAgentFinderPlugin(pluginName) + : undefined; + if (agentFinderPlugin) { + const sessionResource = this.harnessService.getSessionResourceForHarness(SessionType.AgentHostCopilot); + const installProvider = this.harnessService.getDescriptorForSession(sessionResource)?.marketplaceInstallProvider; + if (!installProvider) { + throw new Error(localize('pluginLinkHarnessUnavailable', "Copilot plugin installation is unavailable in this window.")); + } + await installProvider.install(sessionResource, agentFinderPlugin, CancellationToken.None); + return; } - const options: INewSessionInAgentsWindowOptions = { noWorkspace: true, agentHostProvider: COPILOT_CLI_AGENT_PROVIDER_ID }; - const created = this.environmentService.isSessionsWindow - ? await this.commandService.executeCommand(NEW_SESSION_IN_AGENTS_WINDOW_COMMAND_ID, options) - : await this.commandService.executeCommand(`workbench.action.chat.openNewSessionEditor.${SessionType.AgentHostCopilot}`); - if (!URI.isUri(created) || created.scheme !== SessionType.AgentHostCopilot) { - throw new Error(localize('pluginLinkSessionCreationFailed', "Could not create a Copilot Agent Host session for this link.")); + if (!this.agentHostService.listPluginMarketplaces || !this.agentHostService.addPluginMarketplace || + (pluginName && (!this.agentHostService.browsePluginMarketplace || !this.agentHostService.installPlugin))) { + throw new Error(localize('pluginLinkCopilotUnavailable', "Copilot plugin installation is unavailable in this window. Select VS Code explicitly to use its shared plugin installer.")); } - resource = created; - if (this.environmentService.isSessionsWindow) { - // Agents-window drafts already own their backend session; do not create a second provisional one. - return { resource, backendResource: resource }; + const provider = COPILOT_CLI_AGENT_PROVIDER_ID; + const marketplaces = await this.agentHostService.listPluginMarketplaces(provider); + let marketplace = marketplaces.find(marketplace => { + const source = parseProviderMarketplaceReference(marketplace.source); + // The built-in source description omits the standard published marketplace branch. + return source?.canonicalId === ref.canonicalId || + marketplace.isDefault && !marketplace.managed && !!source && !source.ref && isDefaultPluginMarketplace(source) && + ref.canonicalId === defaultPluginMarketplaceReference.canonicalId; + }); + if (!marketplace) { + const managementProvider = this.harnessService.getDescriptorForSession( + this.harnessService.getSessionResourceForHarness(SessionType.AgentHostCopilot), + )?.marketplaceManagementProvider; + if (!managementProvider) { + throw new Error(localize('pluginLinkMarketplaceManagementUnavailable', "Copilot marketplace management is unavailable in this window.")); + } + marketplace = await managementProvider.add(undefined, ref.rawValue); } - const backendResource = await this.provisionalSessionService.getOrCreate(resource, COPILOT_CLI_AGENT_PROVIDER_ID, this.newSessionFolderService.resolveNewSessionPrimary(resource)); - if (!backendResource) { - throw new Error(localize('pluginLinkSessionCreationFailed', "Could not create a Copilot Agent Host session for this link.")); + if (pluginName) { + const plugins = await this.agentHostService.browsePluginMarketplace!(provider, undefined, marketplace.name); + if (!plugins.some(plugin => plugin.name === pluginName)) { + throw new Error(localize('pluginLinkPluginNotFound', "Marketplace '{0}' was added, but plugin '{1}' was not found. No plugin was installed.", marketplace.name, pluginName)); + } + await this.agentHostService.installPlugin!(provider, { source: `${pluginName}@${marketplace.name}` }); } - return { resource, backendResource }; + } + + private async installForVSCode(ref: IMarketplaceReference, pluginName: string | undefined): Promise { + if (pluginName) { + const result = await this.pluginInstallService.installPluginFromSource(ref.rawValue, { plugin: pluginName }); + if (!result.success) { + if (result.message) { + throw new Error(result.message); + } + return false; + } + } else { + if (!await this.pluginInstallService.ensureMarketplaceTrusted(ref)) { + return false; + } + const { userValues, effectiveValues } = readConfiguredMarketplaces(this.configurationService); + if (!parseMarketplaceReferences(effectiveValues).some(existing => existing.canonicalId === ref.canonicalId)) { + await this.configurationService.updateValue(ChatConfiguration.PluginMarketplaces, [...userValues, ref.rawValue], ConfigurationTarget.USER); + } + } + return true; } private parseReference(raw: string) { @@ -207,6 +329,6 @@ export class PluginUrlHandler extends Disposable implements IWorkbenchContributi } catch { // Marketplace references also support plain-text owner/repo and Git URLs. } - return (decoded && parseMarketplaceReference(decoded)) || parseMarketplaceReference(raw); + return (decoded && parseProviderMarketplaceReference(decoded)) || parseProviderMarketplaceReference(raw); } } diff --git a/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts b/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts index 35fcadb8ca48..e24dd51fef91 100644 --- a/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts +++ b/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts @@ -3,11 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { VSBuffer } from '../../../../../base/common/buffer.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { isEqual } from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { getCodeEditor, ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; import { SnippetController2 } from '../../../../../editor/contrib/snippet/browser/snippetController2.js'; +import { SnippetParser } from '../../../../../editor/contrib/snippet/browser/snippetParser.js'; import { localize, localize2 } from '../../../../../nls.js'; import { Action2, MenuId, registerAction2 } from '../../../../../platform/actions/common/actions.js'; import { ICommandService } from '../../../../../platform/commands/common/commands.js'; @@ -352,7 +354,8 @@ class NewSkillFileAction extends Action2 { await fileService.createFolder(skillFolder); const skillFileUri = URI.joinPath(skillFolder, SKILL_FILENAME); - await fileService.createFile(skillFileUri); + const template = getDefaultContentSnippet(PromptsType.skill, trimmedName, Target.Undefined); + await fileService.createFile(skillFileUri, VSBuffer.fromString(SnippetParser.asInsertText(template))); let editor: ICodeEditor | null | undefined; if (options?.openFile) { @@ -364,7 +367,7 @@ class NewSkillFileAction extends Action2 { if (editor && editor.hasModel() && isEqual(editor.getModel().uri, skillFileUri)) { SnippetController2.get(editor)?.apply([{ range: editor.getModel().getFullModelRange(), - template: getDefaultContentSnippet(PromptsType.skill, trimmedName, Target.Undefined), + template, }]); } } diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css index 1d6903ca3023..7cbfea631932 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css @@ -36,7 +36,9 @@ * gutter the rail is offset by, but only while the rail surface is mounted (`.prompt-timeline-with-rail`); * header-only keeps the base layout. */ .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .prompt-timeline-host.prompt-timeline-with-rail.interactive-session .interactive-item-container, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .prompt-timeline-host.prompt-timeline-with-rail.interactive-session .interactive-item-container, .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .prompt-timeline-host.prompt-timeline-with-rail.interactive-session > .chat-suggest-next-widget, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .prompt-timeline-host.prompt-timeline-with-rail.interactive-session > .chat-suggest-next-widget, .agent-sessions-workbench .chat-editor-relative .prompt-timeline-host.prompt-timeline-with-rail.interactive-session .interactive-item-container, .agent-sessions-workbench .chat-editor-relative .prompt-timeline-host.prompt-timeline-with-rail.interactive-session > .chat-suggest-next-widget { padding-right: calc(var(--prompt-timeline-rail-width) + var(--prompt-timeline-content-gap) + var(--prompt-timeline-scrollbar-gutter)); @@ -127,12 +129,14 @@ * card's hairline side and bottom border. The top is left open so it reads as anchored to the top of the * transcript. The left inset matches the header's status-icon column (codicon size + 6px gap) so the * prompt text aligns with the title and the prompts below. */ -.agent-sessions-workbench .prompt-timeline-sticky-content { +.agent-sessions-workbench .prompt-timeline-sticky-content, +.sessions-chat .prompt-timeline-sticky-content { max-width: var(--session-view-centered-content-max-width, 950px); padding: 0 10px; } -.agent-sessions-workbench .prompt-timeline-sticky-band { +.agent-sessions-workbench .prompt-timeline-sticky-band, +.sessions-chat .prompt-timeline-sticky-band { padding-left: calc(var(--vscode-codiconFontSize, 16px) + 6px); /* The centered host already insets this side by 10px, so the band itself sits flush with it. */ padding-right: 0; @@ -750,8 +754,8 @@ /* Hovering tints only the half under the pointer — that, and nothing else, is what tells the two * targets apart. No divider: at rest there is no boundary to draw (nothing is being interacted with), * and on hover the tinted half's own edge already is the boundary. */ -.prompt-timeline-gutter-row-jump:hover, -.prompt-timeline-gutter-row-diff:hover { +.prompt-timeline-gutter-row-jump:is(:hover, .hovered), +.prompt-timeline-gutter-row-diff:is(:hover, .hovered) { background-color: var(--vscode-list-hoverBackground); } @@ -788,10 +792,16 @@ border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; } -.prompt-timeline-gutter-row-jump:focus-visible, -.prompt-timeline-gutter-row-diff:focus-visible { - outline: 1px solid var(--vscode-focusBorder); - outline-offset: -1px; +.prompt-timeline-gutter-row-jump:is(:focus-visible, .focus-visible), +.prompt-timeline-gutter-row-diff:is(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness, 1px) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + +.monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-row-jump:is(:hover, .hovered):not(:focus-visible, .focus-visible), +.monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-row-diff:is(:hover, .hovered):not(:focus-visible, .focus-visible) { + outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); } .prompt-timeline-gutter-row-label { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts index 4fe7fc4ca46d..d741e10adc59 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts @@ -12,7 +12,7 @@ import { disposableTimeout, raceCancellationError, timeout } from '../../../../. 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 { AgentHostProtocolClient, InitialAuthenticationError, RetryableAuthenticationError } 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'; @@ -27,10 +27,10 @@ import { cloudSandboxEnvironmentId, CloudSandboxEnabledSettingId, CloudSandboxNetworkError, + CloudSandboxAuthenticationRequiredError, ICloudSandboxAgentHostService, ICloudSandboxConnectOptions, ICloudSandboxApiService, - isCloudSandboxSealedToken, isRetryableCloudSandboxError, CloudSandboxRequestError, type CloudSandboxConnectResult, @@ -44,6 +44,7 @@ import { IWorkbenchEnvironmentService } from '../../../../services/environment/c import { IPowerService } from '../../../../services/power/common/powerService.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; +import { isSealedEnvironmentToken } from '../../../../../platform/github/common/missionControl/environments.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'; @@ -279,6 +280,8 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo staged.refreshState, )); staged.refresher = refresher; + store.add(this._powerService.onDidSuspend(() => refresher.suspend())); + store.add(this._powerService.onDidResume(() => refresher.resume())); store.add(toDisposable(() => { if (staged.refresher === refresher) { staged.refresher = undefined; @@ -351,7 +354,12 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo throw new CancellationError(); } if (!isMissionControlRecipientTrusted(request, staged.trustedEncryptionKeys)) { - const environment = await this._apiService.getEnvironment(staged.options.environmentId, lifetime.token); + const environment = await this._apiService.getEnvironment(staged.options.environmentId, lifetime.token).catch(error => { + if (!isCancellationError(error) && isRetryableCloudSandboxError(error)) { + throw new RetryableAuthenticationError(error); + } + throw error; + }); if (environment.id !== staged.options.environmentId) { throw new Error('Mission Control returned a different environment for credential encryption.'); } @@ -384,19 +392,22 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo throw new CancellationError(); } if (staged.options.environmentKind === 'user-local') { - return this.resolveUserLocalAuthentication(staged.options.environmentId, GITHUB_COPILOT_PROTECTED_RESOURCE.resource); + try { + return await this.resolveUserLocalAuthentication(staged.options.environmentId, GITHUB_COPILOT_PROTECTED_RESOURCE.resource); + } catch (error) { + if (error instanceof CloudSandboxAuthenticationRequiredError || !isRetryableCloudSandboxError(error)) { + throw new InitialAuthenticationError(error); + } + throw error; + } } - // 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 - // initial-authentication failure and surfaces it as incompatible. const address = getEntryAddress(staged.entry); const sealedToken = staged.creds.token.encrypted_github_token; if (!sealedToken) { - throw new Error(`Mission Control returned no sealed token for ${address}; the session cannot make authenticated requests.`); + throw new InitialAuthenticationError(new Error(`Mission Control returned no sealed token for ${address}; the session cannot make authenticated requests.`)); } - if (!isCloudSandboxSealedToken(sealedToken)) { - throw new Error(`Refusing to forward a non-sealed token to ${address}; Mission Control did not return a copilot-sealed envelope.`); + if (!isSealedEnvironmentToken(sealedToken)) { + throw new InitialAuthenticationError(new Error(`Refusing to forward a non-sealed token to ${address}; Mission Control did not return a copilot-sealed envelope.`)); } staged.lastAuthenticationToken = sealedToken; return { resource: GITHUB_COPILOT_PROTECTED_RESOURCE.resource, token: sealedToken }; @@ -642,7 +653,7 @@ export class CloudSandboxAgentHostService extends Disposable implements ICloudSa let rateLimitFailures = 0; let rateLimitedAt: number | undefined; // Match what `_establish` accepts: an unsealed value would wrongly end the loop. - for (let attempt = 0; attempt < MAX_SEALED_TOKEN_RETRIES && !isCloudSandboxSealedToken(clientToken.encrypted_github_token); attempt++) { + for (let attempt = 0; attempt < MAX_SEALED_TOKEN_RETRIES && !isSealedEnvironmentToken(clientToken.encrypted_github_token); attempt++) { if (token.isCancellationRequested) { throw new CancellationError(); } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts index 1e9f5ef60985..d8b052f1739b 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts @@ -3,14 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Limiter, MAX_TIMEOUT_DELAY, raceCancellationError, timeout } from '../../../../../base/common/async.js'; -import { decodeBase64, encodeBase64, VSBuffer } from '../../../../../base/common/buffer.js'; +import { MAX_TIMEOUT_DELAY, raceCancellationError } from '../../../../../base/common/async.js'; +import { CachedFunction } from '../../../../../base/common/cache.js'; import { cancelOnDispose, CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; import { CancellationError, isCancellationError } from '../../../../../base/common/errors.js'; -import { Emitter } from '../../../../../base/common/event.js'; -import { isObject } from '../../../../../base/common/types.js'; -import { Disposable, DisposableMap, DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable, DisposableMap, DisposableStore, IReference, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { equals } from '../../../../../base/common/objects.js'; import { localize } from '../../../../../nls.js'; import { StopWatch } from '../../../../../base/common/stopwatch.js'; @@ -20,12 +19,10 @@ import { generateUuid } from '../../../../../base/common/uuid.js'; import { CLOUD_SANDBOX_AGENT_SLUG, CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, - CLOUD_SANDBOX_SEALED_TOKEN_PREFIX, CloudSandboxAuthenticationRequiredError, CloudSandboxConnectResult, CloudSandboxNetworkError, CloudSandboxRequestError, - ICloudSandboxClientToken, ICloudSandboxConnectionRequest, ICloudSandboxApiService, ICloudSandboxCreatedSession, @@ -42,7 +39,6 @@ import { ICloudSandboxPreparedAuthentication, ICloudSandboxSealedToken, ICloudSandboxSealTokenRequest, - IHostEncryptionKey, IMissionControlEnvironment, ICloudSandboxModelCatalog, ICloudSandboxSessionFeedConnection, @@ -52,14 +48,15 @@ import { SessionStatus } from '../../../../../platform/agentHost/common/state/se import { SessionModelInfo } from '../../../../../platform/agentHost/common/state/protocol/state.js'; import { createPricingMetaFromBilling, normalizeCAPIBilling } from '../../../../../platform/agentHost/common/meta/agentModelMeta.js'; import { COPILOT_INTEGRATION_ID } from '../../../../../platform/endpoint/common/licenseAgreement.js'; -import { GITHUB_DOT_COM_COPILOT_API_BASE_URI, deriveGitHubEndpoints } from '../../../../../platform/github/common/githubEndpoints.js'; -import { nextLink } from '../../../../../platform/github/common/githubResponse.js'; -import { GitHubRequestTimeoutError } from '../../../../../platform/github/common/githubTypes.js'; +import { GITHUB_DOT_COM_COPILOT_API_BASE_URI } from '../../../../../platform/github/common/githubEndpoints.js'; +import { GitHubAuthorizationContext, GitHubRequestError, GitHubRequestTimeoutError, isEqualAuthorization } from '../../../../../platform/github/common/githubTypes.js'; +import { IGitHubAccountClient } from '../../../../../platform/github/common/account/account.js'; +import { ApiRequestOptions, ApiResponse } from '../../../../../platform/github/common/client/request.js'; import { RequestError } from '../../../../../platform/github/common/types.js'; -import { isRetryableMissionControlError, parseMissionControlError } from '../../../../../platform/github/common/missionControl/missionControlError.js'; +import { isRetryableMissionControlError, parseMissionControlError, type MissionControlErrorMetadata } from '../../../../../platform/github/common/missionControl/missionControlError.js'; import { ApiRequestError, MutationUncertainError } from '../../../../../platform/github/common/missionControl/missionControlClient.js'; import { SchemaError } from '../../../../../platform/github/common/client/schema.js'; -import type { TaskClient } from '../../../../../platform/github/common/missionControl/tasks.js'; +import { MAX_TASK_BATCH_SIZE, type GetTaskResponse, type ListTasksOptions, type Task } from '../../../../../platform/github/common/missionControl/tasks.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IRequestContext } from '../../../../../base/parts/request/common/request.js'; @@ -71,52 +68,10 @@ import { type CloudSandboxLifecycleFailurePoint, type CloudSandboxLifecycleOpera import { CloudSandboxHistoryCache } from './cloudSandboxHistoryCache.js'; import { createCloudSandboxContextTierSchema } from './cloudSandboxSessionConfig.js'; import { CloudSandboxIdentityTokenProvider, ICloudSandboxIdentityTokenResponse } from './cloudSandboxIdentityTokenProvider.js'; -import { RATE_LIMIT_MAX_RETRIES, RATE_LIMIT_WAIT_BUDGET_MS, rateLimitDelay, retryAfterSeconds } from './cloudSandboxRateLimit.js'; +import { retryAfterSeconds } from './cloudSandboxRateLimit.js'; import { IWorkbenchGitHubService } from '../../../../services/github/common/githubService.js'; -/** The agent-environment endpoints Mission Control exposes. */ -type CloudSandboxEnvironmentAction = 'get' | 'connect' | 'reconnect'; - -interface ISealedTokenResponse { - readonly encrypted_github_token?: unknown; - readonly host_encryption_key?: Partial; -} - -/** The subset of a Mission Control task the sandbox discovery path reads. */ -interface ITaskSummary { - readonly id: string; - readonly event_type?: string; - readonly clients?: readonly TaskClient[]; - readonly name?: string; - readonly archived_at?: string | null; - readonly updated_at?: string; - readonly state?: string; - readonly agent_collaborators?: readonly { readonly slug?: string }[]; - readonly compute?: { readonly provider?: string } | null; - readonly current_environment?: { readonly kind?: string }; - /** - * The owning repository, identified by numeric id only — the payload carries no name. See - * {@link CloudSandboxApiService._resolveRepositoryName}. - */ - readonly repository?: { readonly id?: number }; -} - -/** A full task, which additionally carries the sessions bound to sandbox environments. */ -interface ITaskDetail extends ITaskSummary { - readonly reserved?: boolean; - readonly claimed?: boolean; - readonly reservation_expires_at?: string; - readonly sessions?: readonly { - readonly id: string; - readonly environment_id?: string; - readonly state?: string; - readonly created_at?: string; - readonly updated_at?: string; - readonly ahp_resource_uri?: string | null; - }[]; -} - -interface IScannedTask extends ITaskSummary { +interface IScannedTask extends Task { readonly hasRepository: boolean; } @@ -135,21 +90,7 @@ interface ISessionResolution { const LOG_PREFIX = '[CloudSandboxApi]'; -interface ICloudModel { - readonly id: string; - readonly name: string; - readonly model_picker_enabled?: boolean; - readonly policy?: { readonly state?: string }; - readonly billing?: unknown; - readonly model_picker_category?: string; - readonly model_picker_price_category?: string; - readonly capabilities?: { - readonly limits?: { readonly max_context_window_tokens?: number; readonly max_prompt_tokens?: number; readonly max_output_tokens?: number }; - readonly supports?: { readonly vision?: boolean; readonly reasoning_effort?: readonly string[] }; - }; -} - -function taskSessionStatus(state: string | undefined, logService: ILogService): SessionStatus | undefined { +function taskSessionStatus(state: Task['state']): SessionStatus { switch (state) { case 'queued': case 'in_progress': @@ -163,32 +104,11 @@ function taskSessionStatus(state: string | undefined, logService: ILogService): case 'timed_out': case 'cancelled': return SessionStatus.Error; - case undefined: - return undefined; - default: - logService.warn(`${LOG_PREFIX} Unrecognized session activity state; leaving its status unknown.`); - return undefined; } } -/** - * The github.com REST API base, used for the repository-name lookup discovery needs. The CORS - * caveat on {@link CloudSandboxApiService._tasksBaseUrl} is specific to `api.github.com/agents/*`; - * the general REST API is CORS-enabled and already called from the renderer elsewhere. - */ -const GITHUB_DOT_COM_API_BASE_URI = deriveGitHubEndpoints(undefined).apiBaseUri; - -/** Default per-request timeout (ms) for environment reads and task updates. */ -const REQUEST_TIMEOUT_MS = 10_000; - -/** Connection requests can wait for an environment to wake before returning. */ -const CONNECTION_REQUEST_TIMEOUT_MS = 30_000; - -/** Per-request timeout (ms) for discovery, whose task list is far larger than a credential mint. */ -const DISCOVERY_TIMEOUT_MS = 30_000; - -/** Per-request timeout (ms) for allocating sandbox compute, with or without a task. */ -const CREATE_TIMEOUT_MS = 60_000; +/** Timeout (ms) for history requests still using the legacy request service. */ +const LEGACY_READ_TIMEOUT_MS = 30_000; /** Default Retry-After (seconds) when a 202 "waking" response omits the header. */ const DEFAULT_WAKING_RETRY_AFTER_SECONDS = 5; @@ -199,47 +119,26 @@ const DISCOVERY_TASK_SCAN_LIMIT = 100; /** Maximum pages to read per repository/archive task scope during discovery. */ const DISCOVERY_TASK_SCAN_MAX_PAGES = 3; -/** - * Max concurrent task-detail fetches during discovery. - * - * Discovery used to resolve every sandbox task at once, which meant a user with a few dozen - * sandbox tasks issued that many simultaneous requests and tripped GitHub's rate limit. Each - * rejected fetch drops its session from the pass, and the burst also starves the `listTasks` call - * of whichever pass runs next — including the one a freshly reloaded window depends on. - */ -const DISCOVERY_TASK_FETCH_CONCURRENCY = 5; - const DISCOVERY_OVERLAP_MS = 60_000; -/** Minimum automatic inventory retry interval after a first-page authorization refusal. */ +/** Minimum automatic inventory retry interval after an authorization refusal. */ const DISCOVERY_AUTHORIZATION_RETRY_INTERVAL_MS = 15 * 60_000; -/** HTTP status GitHub answers a rate-limited request with. */ -const HTTP_TOO_MANY_REQUESTS = 429; - /** Fallback scopes when the product does not configure `defaultChatAgent.providerScopes`. */ const FALLBACK_SCOPES = ['read:user', 'user:email', 'repo', 'workflow']; -/** - * Mission Control client for cloud sandbox sessions: mints (`connect`) and refreshes (`reconnect`) - * Web PubSub credentials, reads environment and task records, discovers sandbox-backed sessions, - * and replays a task's persisted AHP history. - * - * Runs in the renderer so the sandbox path works in VS Code Web, where no Copilot extension host is - * available. - */ +/** Coordinates sandbox lifecycle, discovery, and recorded history. Supported operations use typed GitHub clients with host-owned execution. */ export class CloudSandboxApiService extends Disposable implements ICloudSandboxApiService { declare readonly _serviceBrand: undefined; private readonly _identityTokenProvider: CloudSandboxIdentityTokenProvider; private readonly _lifetimeToken = cancelOnDispose(this._store); - /** Resolved (or in-flight) repository names, keyed by numeric repository id. */ - private readonly _repositoryNames = new Map>(); + private readonly _apiClient = this._register(new MutableDisposable>()); + private readonly _repositoryNames = new Map(); private readonly _discoveredTasks = new Map(); private readonly _sessionResolutions = new Map(); private readonly _sessionResolutionSources = this._register(new DisposableMap()); - private readonly _sessionResolutionLimiter = this._register(new Limiter(DISCOVERY_TASK_FETCH_CONCURRENCY)); private readonly _activeDiscoveryReads = new Set>(); private _discoverySince: string | undefined; private _archivedDiscoverySince: string | undefined; @@ -322,7 +221,8 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA const session = await this._resolveStableGitHubSession(); // Token rotation preserves the declared listing scope; unannounced access changes need full reconciliation. this._updateDiscoveryAuthorization(session ? JSON.stringify([ - this._authenticationProviderId, session.account.id, this._tasksBaseUrl(), this._userDataProfileService.currentProfile.id, [...new Set(session.scopes)].sort(), + this._authenticationProviderId, session.account.id, session.id, session.authorizationServer?.toString(), + this._tasksBaseUrl(), this._userDataProfileService.currentProfile.id, [...new Set(session.scopes)].sort(), ]) : undefined); return session; } @@ -335,6 +235,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA this._discoveryGeneration++; } this._discoveryAuthorization = authorization; + this._apiClient.clear(); this._discoveryAuthorizationFailure = undefined; this._discoverySince = undefined; this._archivedDiscoverySince = undefined; @@ -353,6 +254,97 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA this._sessionResolutions.clear(); } + private async _getApiClient(session: AuthenticationSession, signal: AbortSignal): Promise { + const authorization: GitHubAuthorizationContext = { + providerId: this._authenticationProviderId, sessionId: session.id, accountId: session.account.id, + scopes: session.scopes, authorizationServer: session.authorizationServer?.toString(), + }; + const current = this._apiClient.value?.object; + if (current && isEqualAuthorization(current.authorization, authorization)) { + return current; + } + const generation = this._accountGeneration; + const lifetime = new DisposableStore(); + try { + const acquired = lifetime.add(await this._githubService.acquireAccountApiClient(authorization, signal)); + signal.throwIfAborted(); + if (generation !== this._accountGeneration || this._store.isDisposed) { + throw new CancellationError(); + } + const existing = this._apiClient.value?.object; + if (existing && isEqualAuthorization(existing.authorization, authorization)) { + lifetime.dispose(); + return existing; + } + lifetime.add(Event.once(acquired.onDidInvalidate)(() => { + if (this._apiClient.value?.object === acquired) { + this._updateDiscoveryAuthorization(undefined); + } + })); + this._apiClient.value = { object: acquired, dispose: () => lifetime.dispose() }; + return acquired; + } catch (error) { + lifetime.dispose(); + throw error; + } + } + + private async _withApiClient( + token: CancellationToken, + options: ApiRequestOptions, + execute: (client: IGitHubAccountClient, signal: AbortSignal, options: ApiRequestOptions, authentication: AuthenticationSession) => Promise, + context?: { + readonly authentication?: AuthenticationSession; + readonly expectedAccountKey?: string; + readonly action?: string; + }, + ): Promise { + const lifetime = new DisposableStore(); + try { + const signal = AbortSignal.any([ + CancellationToken.toAbortSignal(token, lifetime), + CancellationToken.toAbortSignal(this._lifetimeToken, lifetime), + ]); + signal.throwIfAborted(); + const session = context?.authentication ?? await raceCancellationError(this._resolveDiscoveryAuthorization(), CancellationToken.fromAbortSignal(signal, lifetime)); + if (!session) { + throw new CloudSandboxAuthenticationRequiredError(); + } + if (context?.expectedAccountKey !== undefined && context.expectedAccountKey !== this._accountKeyForSession(session)) { + throw new CancellationError(); + } + const client = await this._getApiClient(session, signal); + signal.throwIfAborted(); + const result = await execute(client, signal, options, session); + signal.throwIfAborted(); + return result; + } catch (error) { + if (token.isCancellationRequested || this._store.isDisposed || isCancellationError(error)) { + throw new CancellationError(); + } + if (error instanceof MutationUncertainError) { + throw error; + } + if (error instanceof ApiRequestError && error.statusCode >= 400) { + const metadata = { + code: error.code, limitedResource: error.limitedResource, requestId: error.requestId, + }; + throw context?.action + ? this._createRequestError(context.action, error.statusCode, error.retryAfterSeconds, metadata, error.outcome) + : new CloudSandboxRequestError(error.statusCode, error.message, error.retryAfterSeconds, metadata, error.outcome); + } + if (error instanceof GitHubRequestError && error.statusCode !== undefined && error.statusCode >= 400) { + const metadata = parseMissionControlError(error.responseBody, error.responseMetadata?.requestId); + throw context?.action + ? this._createRequestError(context.action, error.statusCode, error.responseMetadata?.retryAfterSeconds, metadata) + : new CloudSandboxRequestError(error.statusCode, error.message, error.responseMetadata?.retryAfterSeconds, metadata); + } + throw error; + } finally { + lifetime.dispose(); + } + } + private _accountKeyForSession(session: AuthenticationSession): string { return JSON.stringify([this._authenticationProviderId, session.account.id]); } @@ -406,29 +398,33 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA throw new Error(localize('cloudSandbox.invalidSealingResource', "The sandbox token-sealing resource must be a valid URL.")); } } - const response = await raceCancellationError(this._requestCredential( - 'sealToken', `${encodeURIComponent(request.environmentId)}/seal-token`, - { token: request.token, ...(request.resource === undefined ? {} : { resource: request.resource }) }, token, session, - ), token); + const response = await this._withApiClient(token, { caller: 'mc.environmentClient.sealToken', priority: 'mutation' }, + (client, signal, options) => client.environments.sealToken(request.environmentId, { + token: request.token, ...(request.resource === undefined ? {} : { resource: request.resource }), + }, signal, options), + { authentication: session, action: 'token sealing' }); if (this._store.isDisposed || token.isCancellationRequested) { throw new CancellationError(); } - return parseSealedTokenResponse(response); + return response; } private async _requestIdentityToken(session: AuthenticationSession, token: CancellationToken): Promise { const store = new DisposableStore(); try { - const signal = AbortSignal.any([CancellationToken.toAbortSignal(token, store), AbortSignal.timeout(REQUEST_TIMEOUT_MS)]); + const signal = AbortSignal.any([ + CancellationToken.toAbortSignal(token, store), + CancellationToken.toAbortSignal(this._lifetimeToken, store), + ]); 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 }); + const result = await client.environments.mintIdentityToken(signal, { caller: 'mc.tokens.create' }); this._telemetry.reportRequest('mintIdentityToken', 'succeeded'); return result; } catch (error) { - if (token.isCancellationRequested || isCancellationError(error)) { + if (this._store.isDisposed || token.isCancellationRequested || isCancellationError(error)) { throw new CancellationError(); } if (error instanceof ApiRequestError) { @@ -438,53 +434,26 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA }); } this._telemetry.reportRequest('mintIdentityToken', 'networkError'); + if (error instanceof GitHubRequestError && error.kind === 'network') { + throw new CloudSandboxNetworkError(localize('cloudSandbox.identityNetworkFailed', "The sandbox identity-token request failed because of a network error.")); + } throw new Error(localize('cloudSandbox.identityClientFailed', "The sandbox identity-token request failed or returned an invalid response.")); } finally { store.dispose(); } } - private async _requestCredential(action: 'mintIdentityToken' | 'sealToken', path: string, body: Record, token: CancellationToken, session?: AuthenticationSession): Promise { - const context = await this._request( - `${GITHUB_DOT_COM_API_BASE_URI}/cmc_internal/api/agents/environments/${path}`, - action === 'mintIdentityToken' ? 'mc.tokens.create' : 'mc.environmentClient.sealToken', action, { Accept: 'application/json' }, - token, REQUEST_TIMEOUT_MS, body, 'POST', undefined, session ? { authentication: session } : undefined, - ); - if (token.isCancellationRequested) { - context.stream.destroy(); - throw new CancellationError(); - } - if (!isSuccess(context)) { - context.stream.destroy(); - const status = context.res.statusCode; - const retryAfter = retryAfterSeconds(context.res.headers?.['retry-after']); - const requestId = getGitHubRequestId(context.res.headers?.['x-github-request-id']); - throw new CloudSandboxRequestError(status, - action === 'mintIdentityToken' - ? localize('cloudSandbox.identityRequestFailed', "Sandbox identity-token acquisition failed: HTTP {0} (request {1}).", status ?? 'unknown', requestId ?? 'unknown') - : localize('cloudSandbox.sealingRequestFailed', "Sandbox token sealing failed: HTTP {0} (request {1}).", status ?? 'unknown', requestId ?? 'unknown'), - retryAfter); - } - try { - return await raceCancellationError(this._readJson(context), token); - } catch (error) { - context.stream.destroy(); - if (isCancellationError(error)) { - throw error; - } - throw new Error(action === 'mintIdentityToken' - ? localize('cloudSandbox.identityResponseFailed', "Could not read the sandbox identity-token response.") - : localize('cloudSandbox.sealingResponseFailed', "Could not read the sandbox token-sealing response.")); - } - } - async connectSessionFeed(token: CancellationToken): Promise { const store = new DisposableStore(); let connection: ICloudSandboxSessionFeedConnection; let requested = false; try { - const signal = AbortSignal.any([CancellationToken.toAbortSignal(token, store), AbortSignal.timeout(REQUEST_TIMEOUT_MS)]); - const authentication = await raceCancellationError(this._resolveGitHubSession(), token); + const signal = AbortSignal.any([ + CancellationToken.toAbortSignal(token, store), + CancellationToken.toAbortSignal(this._lifetimeToken, store), + ]); + const requestToken = CancellationToken.fromAbortSignal(signal, store); + const authentication = await raceCancellationError(this._resolveGitHubSession(), requestToken); if (!authentication) { throw new CloudSandboxAuthenticationRequiredError(); } @@ -494,19 +463,19 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA authorizationServer: authentication.authorizationServer?.toString(), }, signal)); requested = true; - connection = await client.tasks.connectFeed(signal, { caller: 'mc.sessionFeed.connect', deadline: Date.now() + REQUEST_TIMEOUT_MS }); - const current = await raceCancellationError(this._resolveGitHubSession(), token); + connection = await client.tasks.connectFeed(signal, { caller: 'mc.sessionFeed.connect' }); + const current = await raceCancellationError(this._resolveGitHubSession(), requestToken); if (!current || current.account.id !== authentication.account.id) { throw new CancellationError(); } this._telemetry.reportRequest('connectSessionFeed', 'succeeded'); } catch (error) { - if (token.isCancellationRequested || isCancellationError(error)) { + if (this._store.isDisposed || token.isCancellationRequested || isCancellationError(error)) { throw new CancellationError(); } if (error instanceof ApiRequestError) { this._telemetry.reportRequest('connectSessionFeed', requestOutcomeForStatus(error.statusCode)); - if (error.statusCode === 403 || error.statusCode === 404) { + if (RequestError.isNotFound(error) || RequestError.isForbidden(error)) { this._logService.debug(`${LOG_PREFIX} Session feed unavailable (HTTP ${error.statusCode}); retaining discovery polling.`); return undefined; } @@ -538,7 +507,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA || reconnectIn <= 0 || reconnectIn >= expiresIn || reconnectIn > MAX_TIMEOUT_DELAY) { throw new SchemaError('Mission Control returned invalid session feed connection metadata'); } - if (token.isCancellationRequested) { + if (this._store.isDisposed || token.isCancellationRequested) { throw new CancellationError(); } return connection; @@ -570,27 +539,17 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } async connect(request: ICloudSandboxConnectionRequest, token: CancellationToken): Promise { - return this._connectRequest('connect', request, token, { - ...(request.sessionId && { session_id: request.sessionId }), - }); + return this._connectRequest(request, token); } async reconnect(request: ICloudSandboxConnectionRequest, clientId: string, token: CancellationToken): Promise { - return this._connectRequest('reconnect', request, token, { - client_id: clientId, - ...(request.sessionId && { session_id: request.sessionId }), - }); + return this._connectRequest(request, token, clientId); } async getEnvironment(environmentId: string, token: CancellationToken): Promise { - const context = await this._sendEnvironment('get', environmentId, token); - if (!isSuccess(context)) { - await this._throwForStatus('get', context); - } - const environment = await this._readJson(context); - if (!environment?.status) { - throw new Error('Mission Control get returned an incomplete environment response'); - } + const environment = await this._withApiClient(token, { caller: 'mc.environmentClient.get', priority: 'interactive' }, + (client, signal, options) => client.environments.get(environmentId, signal, options), + { action: 'get' }); // `status` comes from heartbeat age: a stale one means `/connect` will attempt a resume and // can block for its whole budget. this._logService.trace(`${LOG_PREFIX} Environment ${environmentId}: status=${environment.status}, ahp=${environment.capabilities?.ahp_version ?? 'unknown'}`); @@ -608,31 +567,10 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA if (!options?.refresh && cached) { return cached; } - const context = await this._request(`${GITHUB_DOT_COM_COPILOT_API_BASE_URI}/agents/environments`, 'mc.environmentClient.list', 'listEnvironments', { - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token); - if (!isSuccess(context)) { - await this._throwForStatus('list environments', context); - } - const response = await this._readJson(context); - if (!Array.isArray(response)) { - throw new Error('Mission Control returned invalid environment discovery metadata'); - } - const values: IMissionControlEnvironment[] = []; - for (const value of response as readonly unknown[]) { - if (!isObject(value)) { - this._logService.warn('Ignoring malformed Mission Control environment metadata'); - continue; - } - const environment = value as Partial; - if (typeof environment.id !== 'string' || !/^[A-Za-z0-9_-]+$/.test(environment.id) - || typeof environment.name !== 'string' || !environment.name.trim() || typeof environment.kind !== 'string' - || typeof environment.status !== 'string' || !environment.status) { - this._logService.warn('Ignoring incomplete Mission Control environment metadata'); - continue; - } - values.push({ id: environment.id, name: environment.name, kind: environment.kind, status: environment.status }); - } + const environments = await this._withApiClient(token, { caller: 'mc.environmentClient.list', priority: 'interactive' }, + (client, signal, options) => client.environments.list(signal, options), + { action: 'list environments' }); + const values = environments.map(({ id, name, kind, status }) => ({ id, name, kind, status })); if (generation !== this._discoveryGeneration) { throw new CancellationError(); } @@ -641,26 +579,29 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } async deleteEnvironment(environmentId: string, token: CancellationToken, expectedAccountKey: string): Promise { - const context = await this._request(`${GITHUB_DOT_COM_COPILOT_API_BASE_URI}/agents/environments/${encodeURIComponent(environmentId)}`, 'mc.environmentClient.delete', 'deleteEnvironment', { - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, REQUEST_TIMEOUT_MS, undefined, 'DELETE', undefined, { expectedAccountKey }); - if (!isSuccess(context) && context.res.statusCode !== 404) { - await this._throwForStatus('environment delete', context); + try { + await this._withApiClient(token, { caller: 'mc.environmentClient.delete', priority: 'mutation' }, + (client, signal, options) => client.environments.delete(environmentId, signal, options), + { expectedAccountKey, action: 'environment delete' }); + } catch (error) { + if (!(error instanceof CloudSandboxRequestError) || error.statusCode !== 404) { + throw error; + } } this._environments = undefined; this._discoveryGeneration++; } - /** Full scans replace recent inventory; automatic retries of first-page authorization refusals are paced without blocking manual or targeted reads. */ + /** Full scans replace recent inventory; automatic retries of authorization refusals are paced without blocking manual or targeted reads. */ async listSessions(token: CancellationToken, options?: ICloudSandboxDiscoveryOptions): Promise { const stopwatch = StopWatch.create(); const requestedMode = options?.taskIds !== undefined ? 'targeted' : options?.incremental ? 'incremental' : 'full'; const telemetry: ICloudSandboxDiscoveryTelemetryData = { trigger: options?.trigger ?? 'unknown', requestedMode, mode: requestedMode, outcome: 'failed', - durationMs: 0, pageCount: 0, listRequestCount: 0, taskCount: 0, + durationMs: 0, listOperationCount: 0, taskBatchOperationCount: 0, taskBatchOperationFailureCount: 0, taskCount: 0, sandboxTaskCount: 0, changedSandboxTaskCount: 0, checkpointAdvanced: false, checkpointAvailable: false, checkpointSource: 'unavailable', - listPageFailureCount: 0, taskDetailFailureCount: 0, repositoryEnrichmentMissCount: 0, + listOperationFailureCount: 0, taskDetailFailureCount: 0, repositoryEnrichmentMissCount: 0, unresolvedTaskCount: 0, unreadPageScopeCount: 0, generationInvalidated: false, }; const updates = new Map(); @@ -705,7 +646,6 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA return { kind: 'failed', reason: toErrorMessage(error) }; } const generation = this._discoveryGeneration; - let requestSession = session; const targeted = options?.taskIds !== undefined; const includeArchived = options?.includeArchived !== false; const checkpointSince = includeArchived @@ -725,7 +665,6 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA return { kind: 'failed', reason: authorizationFailure.error.message }; } const tasks = new Map(); - const details = new Map(); const cache = new Map(this._discoveredTasks); const returnedSandboxTasks = new Set(); const changedSandboxTasks = new Set(); @@ -753,35 +692,36 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA let checkpoint: number | undefined; let latestUpdate: number | undefined; if (targeted) { - const limiter = new Limiter(DISCOVERY_TASK_FETCH_CONCURRENCY); - try { - await Promise.all([...new Set(options.taskIds)].map(id => limiter.queue(async () => { - try { - const context = await this._sendTask(`${this._tasksBaseUrl()}/tasks/${encodeURIComponent(id)}`, 'get', token); - const task = await this._readJson(context); - if (!task || task.id !== id) { - throw new Error('getTask returned an invalid task'); - } + const ids = [...new Set(options.taskIds)]; + for (let offset = 0; offset < ids.length; offset += MAX_TASK_BATCH_SIZE) { + const batch = ids.slice(offset, offset + MAX_TASK_BATCH_SIZE); + telemetry.taskBatchOperationCount = (telemetry.taskBatchOperationCount ?? 0) + 1; + try { + const returned = await this._withApiClient(token, { caller: 'mc.taskClient.getBatch', priority: 'background' }, + (client, signal, options) => client.tasks.getBatch(batch, signal, options), { authentication: session }); + const returnedIds = new Set(returned.map(task => task.id)); + for (const task of returned) { recordTask({ ...task, hasRepository: (task.repository?.id ?? 0) > 0 }); - details.set(id, task); - } catch (error) { - if (isCancellationError(error) || token.isCancellationRequested) { - throw new CancellationError(); - } - if (error instanceof CloudSandboxRequestError && (error.statusCode === 403 || error.statusCode === 404)) { + } + // Successful omissions end discoverability, not the remote task or its running session. + for (const id of batch) { + if (!returnedIds.has(id)) { cache.delete(id); removedTaskIds.push(id); - } else { - telemetry.taskDetailFailureCount = (telemetry.taskDetailFailureCount ?? 0) + 1; - telemetry.unresolvedTaskCount = (telemetry.unresolvedTaskCount ?? 0) + 1; - truncated = true; - failedTaskIds.add(id); - this._logService.warn(`${LOG_PREFIX} Feed task refresh failed: ${toErrorMessage(error)}`); } } - }))); - } finally { - limiter.dispose(); + } catch (error) { + if (isCancellationError(error) || token.isCancellationRequested) { + throw new CancellationError(); + } + telemetry.taskBatchOperationFailureCount = (telemetry.taskBatchOperationFailureCount ?? 0) + 1; + telemetry.unresolvedTaskCount = (telemetry.unresolvedTaskCount ?? 0) + batch.length; + truncated = true; + for (const id of batch) { + failedTaskIds.add(id); + } + this._logService.warn(`${LOG_PREFIX} Feed task batch refresh failed: ${toErrorMessage(error)}`); + } } } // Separate repository scopes include workspace-less sandboxes as well as repository sessions. @@ -789,75 +729,63 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA { withRepository: true, archived: false }, { withRepository: false, archived: false }, ...(includeArchived ? [{ withRepository: true, archived: true }, { withRepository: false, archived: true }] : []), ]) { - const query: Record = { - per_page: String(DISCOVERY_TASK_SCAN_LIMIT), + const query: NonNullable = { + per_page: DISCOVERY_TASK_SCAN_LIMIT, + page: 1, sort: 'updated_at', direction: 'desc', - with_repo: String(withRepository), - is_archived: String(archived), + with_repo: withRepository, + is_archived: archived, + include_counts: false, ...(since ? { since, include_environment_kinds: 'managed-sandbox' } : {}), }; - const requestedUrls = new Set(); - let url: string | undefined = `${this._tasksBaseUrl()}/tasks${toQuery({ ...query, page: '1' })}`; - for (let page = 1; url && page <= DISCOVERY_TASK_SCAN_MAX_PAGES; page++) { + try { + telemetry.listOperationCount = (telemetry.listOperationCount ?? 0) + 1; + const response = await this._withApiClient(token, { + caller: 'mc.taskClient.list', priority: options?.trigger === 'manual' ? 'interactive' : 'background', + }, (client, signal, requestOptions) => client.tasks.list(signal, { + ...requestOptions, query, maxPages: DISCOVERY_TASK_SCAN_MAX_PAGES, pageLimitBehavior: 'returnPartial', + }), { authentication: session }); if (token.isCancellationRequested) { throw new CancellationError(); } - try { - if (requestedUrls.has(url)) { - throw new Error('Task list repeated a pagination URL'); - } - requestedUrls.add(url); - const context = await this._sendTask(url, 'list', token, () => telemetry.listRequestCount++, responseSession => requestSession = responseSession); - const response = await this._readJson<{ tasks?: readonly ITaskSummary[] }>(context); - if (!Array.isArray(response?.tasks)) { - throw new Error('listTasks returned no tasks array'); - } - telemetry.pageCount++; - if (generation === this._discoveryGeneration) { - this._discoveryAuthorizationFailure = undefined; - } - const date = context.res.headers?.date; - const serverTime = typeof date === 'string' ? Date.parse(date) : Number.NaN; - if (!Number.isNaN(serverTime)) { - checkpoint = Math.min(checkpoint ?? serverTime, serverTime); - telemetry.checkpointSource = 'serverDate'; - } - for (const task of response.tasks) { - recordTask({ ...task, hasRepository: withRepository }); - const updatedAt = task.updated_at ? Date.parse(task.updated_at) : Number.NaN; - if (!Number.isNaN(updatedAt)) { - latestUpdate = Math.max(latestUpdate ?? updatedAt, updatedAt); - if (checkpoint === undefined) { - telemetry.checkpointSource = 'taskUpdate'; - } + if (generation === this._discoveryGeneration) { + this._discoveryAuthorizationFailure = undefined; + } + if (response.serverDate !== undefined) { + const serverTime = Date.parse(response.serverDate); + checkpoint = Math.min(checkpoint ?? serverTime, serverTime); + telemetry.checkpointSource = 'serverDate'; + } + for (const task of response.data.tasks) { + recordTask({ ...task, hasRepository: withRepository }); + if (task.updated_at !== undefined) { + const updatedAt = Date.parse(task.updated_at); + latestUpdate = Math.max(latestUpdate ?? updatedAt, updatedAt); + if (checkpoint === undefined) { + telemetry.checkpointSource = 'taskUpdate'; } } - url = nextTaskPageUrl(context.res.headers?.link, url, query); - if (page === DISCOVERY_TASK_SCAN_MAX_PAGES && url) { - hasUnreadPages = true; - telemetry.unreadPageScopeCount = (telemetry.unreadPageScopeCount ?? 0) + 1; - } - } catch (error) { - if (isCancellationError(error) || token.isCancellationRequested) { - throw new CancellationError(); - } - telemetry.listPageFailureCount = (telemetry.listPageFailureCount ?? 0) + 1; - if (telemetry.pageCount === 0 && generation === this._discoveryGeneration && error instanceof CloudSandboxRequestError - && (error.statusCode === 401 || error.statusCode === 403) && !isRetryableMissionControlError(error.statusCode, error.code)) { - this._discoveryAuthorizationFailure = { - session: requestSession, - retryAt: Date.now() + Math.max(DISCOVERY_AUTHORIZATION_RETRY_INTERVAL_MS, (error.retryAfterSeconds ?? 0) * 1000), - error, - }; - } - if (tasks.size === 0) { - return { kind: 'failed', reason: `listTasks failed: ${toErrorMessage(error)}` }; - } - this._logService.warn(`${LOG_PREFIX} Discovery page ${page} (with_repo=${withRepository}) failed: ${toErrorMessage(error)}`); - truncated = true; - break; } + if (response.nextLink) { + hasUnreadPages = true; + telemetry.unreadPageScopeCount = (telemetry.unreadPageScopeCount ?? 0) + 1; + } + } catch (error) { + if (isCancellationError(error) || token.isCancellationRequested) { + throw new CancellationError(); + } + telemetry.listOperationFailureCount = (telemetry.listOperationFailureCount ?? 0) + 1; + if (telemetry.listOperationCount === 1 && generation === this._discoveryGeneration && error instanceof CloudSandboxRequestError + && (error.statusCode === 401 || error.statusCode === 403) && !isRetryableMissionControlError(error.statusCode, error.code)) { + this._discoveryAuthorizationFailure = { + session, + retryAt: Date.now() + Math.max(DISCOVERY_AUTHORIZATION_RETRY_INTERVAL_MS, (error.retryAfterSeconds ?? 0) * 1000), + error, + }; + } + this._logService.warn(`${LOG_PREFIX} Discovery task list failed: ${toErrorMessage(error)}`); + return { kind: 'failed', reason: `listTasks failed: ${toErrorMessage(error)}` }; } } @@ -892,51 +820,39 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } } let unresolved = 0; - const limiter = new Limiter(DISCOVERY_TASK_FETCH_CONCURRENCY); - let discovered: (ICloudSandboxTask | undefined)[]; - try { - discovered = await Promise.all(sandboxTasks.map(task => limiter.queue(async (): Promise => { - try { - if (token.isCancellationRequested) { - throw new CancellationError(); - } - const previous = cache.get(task.id); - const full = details.get(task.id); - const binding = full ? getTaskEnvironmentBinding(full) : previous?.session; - const { repositoryId, session: summary } = await this._taskSummary(task, previous, token); - const session: ICloudSandboxTask = { - ...summary, - ...(binding?.environmentId && binding.sessionId ? { environmentId: binding.environmentId, sessionId: binding.sessionId } : {}), - }; - const cached: ICachedSandboxTask = { summary: task, repositoryId, session }; - if (repositoryId !== undefined && !session.repoName) { - telemetry.repositoryEnrichmentMissCount = (telemetry.repositoryEnrichmentMissCount ?? 0) + 1; - } - cache.set(task.id, cached); - if (binding?.environmentId && binding.sessionId - && (binding.environmentId !== previous?.session?.environmentId || binding.sessionId !== previous?.session?.sessionId)) { - this._telemetry.lifecycle.record({ - phase: 'binding', outcome: 'observed', operationId: generateUuid(), - environmentId: binding.environmentId, agentSessionId: binding.sessionId, taskId: task.id, - }); - } - return session; - } catch (error) { - if (isCancellationError(error) || token.isCancellationRequested) { - throw new CancellationError(); - } - this._logService.warn(`${LOG_PREFIX} Discovery getTask ${task.id} failed: ${toErrorMessage(error)}`); - logExcludedTask(task.id, 'detailFetchFailed'); - telemetry.taskDetailFailureCount = (telemetry.taskDetailFailureCount ?? 0) + 1; - cache.set(task.id, { ...cache.get(task.id), summary: task, needsRefresh: true }); - unresolved++; - failedTaskIds.add(task.id); - return undefined; + // A large repository group must occupy only one transport waiter per discovery pass. + const repositoryLookups = new CachedFunction((repositoryId: number) => this._resolveRepositoryName(repositoryId, token)); + const discovered = await Promise.all(sandboxTasks.map(async (task): Promise => { + try { + if (token.isCancellationRequested) { + throw new CancellationError(); } - }))); - } finally { - limiter.dispose(); - } + const previous = cache.get(task.id); + const binding = previous?.session; + const { repositoryId, session: summary } = await this._taskSummary(task, previous, repositoryId => repositoryLookups.get(repositoryId)); + const session: ICloudSandboxTask = { + ...summary, + ...(binding?.environmentId && binding.sessionId ? { environmentId: binding.environmentId, sessionId: binding.sessionId } : {}), + }; + const cached: ICachedSandboxTask = { summary: task, repositoryId, session }; + if (repositoryId !== undefined && !session.repoName) { + telemetry.repositoryEnrichmentMissCount = (telemetry.repositoryEnrichmentMissCount ?? 0) + 1; + } + cache.set(task.id, cached); + return session; + } catch (error) { + if (isCancellationError(error) || token.isCancellationRequested) { + throw new CancellationError(); + } + this._logService.warn(`${LOG_PREFIX} Discovery task ${task.id} processing failed: ${toErrorMessage(error)}`); + logExcludedTask(task.id, 'detailFetchFailed'); + telemetry.taskDetailFailureCount = (telemetry.taskDetailFailureCount ?? 0) + 1; + cache.set(task.id, { ...cache.get(task.id), summary: task, needsRefresh: true }); + unresolved++; + failedTaskIds.add(task.id); + return undefined; + } + })); if (token.isCancellationRequested) { throw new CancellationError(); @@ -1012,7 +928,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA removed.add(id); } } - const observed = scannedTaskIds.has(id) || details.has(id) || updates.has(id); + const observed = scannedTaskIds.has(id) || updates.has(id); // Window eviction and unobserved cached state cannot invalidate an overlapping read. if (!removed.has(id) && (!cached || !observed)) { continue; @@ -1043,14 +959,15 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA : { kind: 'scoped', sessions, removedTaskIds: [...removed] }; } - private async _taskSummary(task: IScannedTask, previous: ICachedSandboxTask | undefined, token: CancellationToken): Promise<{ repositoryId: number | undefined; session: ICloudSandboxTask }> { + private async _taskSummary(task: IScannedTask, previous: ICachedSandboxTask | undefined, resolveRepositoryName: (repositoryId: number) => Promise): Promise<{ repositoryId: number | undefined; session: ICloudSandboxTask }> { const application = task.clients?.find(client => client.creator === true)?.slug; const repositoryId = [task.repository?.id, previous?.repositoryId].find(id => id !== undefined && id > 0); - const status = taskSessionStatus(task.state, this._logService); + const status = taskSessionStatus(task.state); const eventType = task.event_type || previous?.session?.eventType; const creatingApplication = application ?? previous?.session?.application; const repoName = previous?.repositoryId === repositoryId ? previous?.session?.repoName : undefined; - const repositoryName = repoName ?? (repositoryId !== undefined ? await this._resolveRepositoryName(repositoryId, token) : undefined); + const repositoryName = task.repository?.full_name || repoName + || (repositoryId !== undefined ? await resolveRepositoryName(repositoryId) : undefined); return { repositoryId, session: { @@ -1062,16 +979,31 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA ...(repositoryName !== undefined ? { repoName: repositoryName } : {}), updatedAt: task.updated_at, ...(task.state === 'queued' ? { isQueued: true } : {}), - ...(status !== undefined ? { status } : {}), + status, ...(task.archived_at ? { isArchived: true } : {}), }, }; } async resolveSession(taskId: string, token: CancellationToken): Promise { - if (token.isCancellationRequested) { + if (token.isCancellationRequested || this._store.isDisposed) { + throw new CancellationError(); + } + let authentication: AuthenticationSession | undefined; + const authorizationLifetime = new DisposableStore(); + try { + const source = authorizationLifetime.add(new CancellationTokenSource(this._lifetimeToken)); + authorizationLifetime.add(token.onCancellationRequested(() => source.cancel())); + authentication = await raceCancellationError(this._resolveDiscoveryAuthorization(), source.token); + } finally { + authorizationLifetime.dispose(); + } + if (token.isCancellationRequested || this._store.isDisposed) { throw new CancellationError(); } + if (!authentication) { + throw new CloudSandboxAuthenticationRequiredError(); + } const cached = this._discoveredTasks.get(taskId)?.session; if (cached?.environmentId && cached.sessionId) { return { ...cached, environmentId: cached.environmentId, sessionId: cached.sessionId }; @@ -1081,12 +1013,13 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA const generation = this._accountGeneration; const source = new CancellationTokenSource(this._lifetimeToken); this._sessionResolutionSources.set(taskId, source); - const pending = raceCancellationError(this._sessionResolutionLimiter.queue(async () => { - const full = await this._readJson(await this._sendTask(`${this._tasksBaseUrl()}/tasks/${encodeURIComponent(taskId)}`, 'get', source.token)); + const pending = raceCancellationError((async () => { + const full = await this._withApiClient(source.token, { caller: 'mc.taskClient.get', priority: 'interactive' }, + (client, signal, options) => client.tasks.get(taskId, signal, options), { authentication }); if (source.token.isCancellationRequested || generation !== this._accountGeneration || this._store.isDisposed) { throw new CancellationError(); } - if (!full || full.id !== taskId || !isCloudSandboxTask(full)) { + if (!isCloudSandboxTask(full)) { throw new Error(localize('cloudSandbox.invalidTask', "The cloud task is no longer available.")); } const binding = getTaskEnvironmentBinding(full); @@ -1095,7 +1028,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } const previous = this._discoveredTasks.get(taskId); const summary = previous?.summary ?? { ...full, hasRepository: (full.repository?.id ?? 0) > 0 }; - const fallback = previous?.session ? undefined : await this._taskSummary(summary, previous, source.token); + const fallback = previous?.session ? undefined : await this._taskSummary(summary, previous, repositoryId => this._resolveRepositoryName(repositoryId, source.token)); if (source.token.isCancellationRequested || generation !== this._accountGeneration || this._store.isDisposed) { throw new CancellationError(); } @@ -1122,7 +1055,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA environmentId: binding.environmentId, agentSessionId: binding.sessionId, taskId, }); return session; - }), source.token).finally(() => { + })(), source.token).finally(() => { if (this._sessionResolutionSources.get(taskId) === source) { this._sessionResolutionSources.deleteAndDispose(taskId); } else { @@ -1159,26 +1092,25 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } private async _reserveSession(request: ICloudSandboxReserveSessionRequest, token: CancellationToken, operation: CloudSandboxLifecycleOperation): Promise { - const context = await this._requestTaskCreation({ + const response = await this._requestTaskCreation({ repoNwo: request.repoNwo, expectedAccountKey: request.expectedAccountKey, prompt: '', }, token, undefined, { taskId: request.reservedTaskId }); - operation.bind({ serverRequestId: getGitHubRequestId(context.res.headers?.['x-github-request-id']) }); - const task = await this._readJson(context); - const taskId = typeof task?.id === 'string' && task.id.trim().length > 0 ? task.id : undefined; - const binding = task && getTaskEnvironmentBinding(task); - const reservationExpiresAt = typeof task?.reservation_expires_at === 'string' ? Date.parse(task.reservation_expires_at) : NaN; - if (!taskId || !binding || task?.reserved !== true || !Number.isFinite(reservationExpiresAt)) { - if (taskId && taskId !== request.reservedTaskId?.trim()) { - await this._deleteTaskBestEffort(taskId, request.expectedAccountKey); - } else if (taskId) { + operation.bind({ serverRequestId: response.metadata?.requestId }); + const task = response.data; + const taskId = task.id; + const binding = getTaskEnvironmentBinding(task); + if (!binding || task.reserved !== true || task.reservation_expires_at === undefined) { + if (taskId !== request.reservedTaskId?.trim()) { + await this._deleteTaskBestEffort(taskId, response.accountKey); + } else { this._logService.warn(`${LOG_PREFIX} Retaining task ${taskId} after an unusable renewal response; it may already have been claimed.`); } - throw new CloudSandboxRequestError(context.res.statusCode, localize('cloudSandbox.invalidTaskReservation', "The cloud service did not return a usable task reservation.")); + throw new CloudSandboxRequestError(response.status, localize('cloudSandbox.invalidTaskReservation', "The cloud service did not return a usable task reservation.")); } this._logService.info(`${LOG_PREFIX} Reserved sandbox task ${taskId} (session ${binding.sessionId}) on environment ${binding.environmentId}.`); - return { taskId, sessionId: binding.sessionId, environmentId: binding.environmentId, reservationExpiresAt }; + return { taskId, sessionId: binding.sessionId, environmentId: binding.environmentId, reservationExpiresAt: Date.parse(task.reservation_expires_at) }; } /** @@ -1206,40 +1138,36 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } private async _createSession(request: ICloudSandboxCreateSessionRequest, token: CancellationToken, onRequest: (() => void) | undefined, operation: CloudSandboxLifecycleOperation): Promise { - const context = await this._requestTaskCreation(request, token, onRequest); - operation.bind({ serverRequestId: getGitHubRequestId(context.res.headers?.['x-github-request-id']) }); - const task = await this._readJson(context); - const taskId = typeof task?.id === 'string' && task.id.trim().length > 0 ? task.id : undefined; - if (!taskId) { - throw new CloudSandboxRequestError(context.res.statusCode, 'Mission Control task create returned no task id'); - } + const response = await this._requestTaskCreation(request, token, onRequest); + operation.bind({ serverRequestId: response.metadata?.requestId }); + const task = response.data; + const taskId = task.id; let claimed: boolean | undefined; if (request.reservedTaskId !== undefined) { - const serverClaimed = task?.claimed; - const reserved = task?.reserved; - if (typeof serverClaimed !== 'boolean' || (reserved !== undefined && reserved !== false) || (serverClaimed && taskId !== request.reservedTaskId.trim())) { - throw new CloudSandboxRequestError(context.res.statusCode, localize('cloudSandbox.invalidReservationSubmission', "The cloud service did not confirm the task reservation outcome.")); + const serverClaimed = task.claimed; + if (serverClaimed === undefined || task.reserved === true || (serverClaimed && taskId !== request.reservedTaskId.trim())) { + throw new CloudSandboxRequestError(response.status, localize('cloudSandbox.invalidReservationSubmission', "The cloud service did not confirm the task reservation outcome.")); } claimed = serverClaimed; } - const binding = task && getTaskEnvironmentBinding(task); + const binding = getTaskEnvironmentBinding(task); if (!binding) { if (request.reservedTaskId === undefined) { // An unusable task must not remain in the session list. - await this._deleteTaskBestEffort(taskId, request.expectedAccountKey); + await this._deleteTaskBestEffort(taskId, response.accountKey); } else { this._logService.warn(`${LOG_PREFIX} Retaining task ${taskId} after an incomplete reservation submission response; its outcome must be reconciled.`); } - throw new CloudSandboxRequestError(context.res.statusCode, `Mission Control bound no sandbox session to task ${taskId}`); + throw new CloudSandboxRequestError(response.status, `Mission Control bound no sandbox session to task ${taskId}`); } if (request.environmentId !== undefined && binding.environmentId !== request.environmentId) { - throw new CloudSandboxRequestError(context.res.statusCode, `Mission Control bound sandbox task ${taskId} to a different environment`); + throw new CloudSandboxRequestError(response.status, `Mission Control bound sandbox task ${taskId} to a different environment`); } this._logService.info(`${LOG_PREFIX} Provisioned sandbox task ${taskId} (session ${binding.sessionId}) on environment ${binding.environmentId}.`); return { taskId, sessionId: binding.sessionId, environmentId: binding.environmentId, ...(claimed !== undefined ? { claimed } : {}) }; } - private async _requestTaskCreation(request: ICloudSandboxCreateSessionRequest, token: CancellationToken, onRequest?: () => void, reservation?: { readonly taskId?: string }): Promise { + private async _requestTaskCreation(request: ICloudSandboxCreateSessionRequest, token: CancellationToken, onRequest?: () => void, reservation?: { readonly taskId?: string }): Promise & { readonly accountKey: string }> { const repository = parseNwo(request.repoNwo); if (request.repoNwo !== undefined && !repository) { throw new CloudSandboxRequestError(undefined, localize('cloudSandbox.invalidRepository', "The sandbox repository must be specified as owner/name."), undefined, { code: 'invalid_request' }); @@ -1260,36 +1188,51 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA throw new Error(localize('cloudSandbox.reservationAccountRequired', "The account that reserved the task is required to submit it.")); } } - const context = await this._request(`${this._tasksBaseUrl()}/tasks`, 'mc.taskClient.create', reservation ? 'reserveTask' : 'createTask', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, CREATE_TIMEOUT_MS, session => ({ - environment_id: request.environmentId ?? CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, - // Persisted for display, so replayed history shows the prompt no run was started for. - prompt: request.prompt, - ...(repository ? { repositories: [repository] } : {}), - // New repo-less compute uses the account authorizing this request. - ...(!repository && request.environmentId === undefined ? { compute: { scope: session.account.label } } : {}), - ...(reservation ? { reserve: true } : {}), - ...(reservedTaskId ? { reserved_task_id: reservedTaskId } : {}), - }), undefined, onRequest, { expectedAccountKey: request.expectedAccountKey }); - if (!isSuccess(context)) { - // Read once: the body carries both the id to clean up and the failure message. - const failureBody = await asText(context).catch(() => '') ?? ''; - - const orphanedTaskId = this._taskIdFromFailure(failureBody); + let submitted = false; + let createdTaskId: string | undefined; + let accountKey = request.expectedAccountKey; + try { + return await this._withApiClient(token, { caller: 'mc.taskClient.create', priority: 'mutation' }, + async (client, signal, options, authentication) => { + const currentAccountKey = this._accountKeyForSession(authentication); + accountKey = currentAccountKey; + onRequest?.(); + signal.throwIfAborted(); + submitted = true; + try { + const response = await client.tasks.create({ + environment_id: request.environmentId ?? CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, + // Persisted for display before the caller sends the first turn over the relay. + prompt: request.prompt, + ...(repository ? { repositories: [{ owner: repository.owner, repo: repository.name }] } : {}), + ...(!repository && request.environmentId === undefined ? { compute: { scope: authentication.account.label } } : {}), + ...(reservation ? { reserve: true } : {}), + ...(reservedTaskId ? { reserved_task_id: reservedTaskId } : {}), + }, signal, options); + createdTaskId = response.data.id; + return { ...response, accountKey: currentAccountKey }; + } catch (error) { + if (error instanceof ApiRequestError) { + createdTaskId = error.createdTaskId; + } + throw error; + } + }, { expectedAccountKey: request.expectedAccountKey, action: reservation ? 'task reservation' : 'task create' }); + } catch (error) { + if (!submitted) { + throw error; + } if (!reservation && reservedTaskId) { this._logService.warn(`${LOG_PREFIX} Retaining reservation ${reservedTaskId} and any created task after a failed submission; its outcome must be reconciled.`); - } else if (orphanedTaskId && reservation && orphanedTaskId === reservedTaskId) { - this._logService.warn(`${LOG_PREFIX} Retaining task ${orphanedTaskId} after a failed renewal request; it may already have been claimed.`); - } else if (orphanedTaskId) { - await this._deleteTaskBestEffort(orphanedTaskId, request.expectedAccountKey); + } else if (createdTaskId && reservation && createdTaskId === reservedTaskId) { + this._logService.warn(`${LOG_PREFIX} Retaining task ${createdTaskId} after a failed renewal request; it may already have been claimed.`); + } else if (createdTaskId) { + await this._deleteTaskBestEffort(createdTaskId, accountKey); } else { - this._logService.warn(`${LOG_PREFIX} Task create failed (HTTP ${context.res.statusCode ?? 'unknown'}) without reporting a task id. Mission Control may have recorded a task before failing; such a task is orphaned and can only be removed server-side.`); + this._logService.warn(`${LOG_PREFIX} Task creation failed without reporting a task id; the service may have accepted the operation and its outcome must be reconciled.`); } - await this._throwForStatus(reservation ? 'task reservation' : 'task create', context, failureBody); + throw error; } - return context; } async deleteTask(taskId: string, token: CancellationToken, expectedAccountKey?: string): Promise { @@ -1307,12 +1250,14 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } private async _deleteTask(taskId: string, token: CancellationToken, expectedAccountKey?: string): Promise { - const context = await this._request(`${this._tasksBaseUrl()}/tasks/${encodeURIComponent(taskId)}`, 'mc.taskClient.delete', 'deleteTask', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, REQUEST_TIMEOUT_MS, undefined, 'DELETE', undefined, { expectedAccountKey }); - if (!isSuccess(context) && context.res.statusCode !== 404) { - await this._throwForStatus('task delete', context); + try { + await this._withApiClient(token, { caller: 'mc.taskClient.delete', priority: 'mutation' }, + (client, signal, options) => client.tasks.delete(taskId, signal, options), + { expectedAccountKey, action: 'task delete' }); + } catch (error) { + if (!(error instanceof CloudSandboxRequestError) || error.statusCode !== 404) { + throw error; + } } this._discoveredTasks.delete(taskId); this.clearSessionHistory(taskId); @@ -1321,13 +1266,9 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } async renameTask(taskId: string, title: string, token: CancellationToken): Promise { - const context = await this._request(`${this._tasksBaseUrl()}/tasks/${encodeURIComponent(taskId)}`, 'mc.taskClient.update', 'renameTask', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, REQUEST_TIMEOUT_MS, { name: title }, 'PATCH'); - if (!isSuccess(context)) { - await this._throwForStatus('task rename', context); - } + await this._withApiClient(token, { caller: 'mc.taskClient.update', priority: 'mutation' }, + (client, signal, options) => client.tasks.update(taskId, { name: title }, signal, options), + { action: 'task rename' }); this.invalidateSessionHistory(taskId); const cached = this._discoveredTasks.get(taskId); if (cached) { @@ -1343,13 +1284,9 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA async setTaskArchived(taskId: string, archived: boolean, token: CancellationToken): Promise { const action = archived ? 'archive' : 'unarchive'; - const context = await this._request(`${this._tasksBaseUrl()}/tasks/${encodeURIComponent(taskId)}/${action}`, `mc.taskClient.${action}`, archived ? 'archiveTask' : 'unarchiveTask', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, REQUEST_TIMEOUT_MS, undefined, 'POST'); - if (!isSuccess(context)) { - await this._throwForStatus(`task ${action}`, context); - } + await this._withApiClient(token, { caller: `mc.taskClient.${action}`, priority: 'mutation' }, + (client, signal, options) => client.tasks.setArchived(taskId, archived, signal, options), + { action: `task ${action}` }); this._discoveredTasks.delete(taskId); this.invalidateSessionHistory(taskId); this._discoveryGeneration++; @@ -1444,7 +1381,7 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA const context = await this._request(url, 'mc.taskClient.events', 'getTaskEvents', { 'Accept': 'application/vnd.github.ahp+json', 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, DISCOVERY_TIMEOUT_MS, undefined, undefined, () => { + }, token, () => { phaseStarted = watch.elapsed(); logTiming('requestIssued', `authenticationMs=${phaseStarted}`); phase = 'request'; @@ -1490,161 +1427,89 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } } - /** - * Resolve a numeric repository id to its `owner/name`, memoized for the life of the service. - * A task names its repository nowhere — `repository` carries an id, and the session's - * `event_url` / `base_ref` are empty for tasks created through the tasks API. - * - * The cached promise must never reject: every task in a pass shares it, and a rejection would - * count each one as unresolved (forcing the scan `partial`) and drop those sessions from the - * listing entirely. A miss is evicted so the next pass retries. - */ - private _resolveRepositoryName(repositoryId: number, token: CancellationToken): Promise { + private async _resolveRepositoryName(repositoryId: number, token: CancellationToken): Promise { const cached = this._repositoryNames.get(repositoryId); if (cached) { return cached; } - const pending = (async () => { - try { - const url = `${GITHUB_DOT_COM_API_BASE_URI}/repositories/${repositoryId}`; - const context = await this._retryWhileRateLimited('repository get', token, () => this._request(url, 'mc.repositoryClient.get', 'getRepository', { - 'Accept': 'application/vnd.github.v3+json', - }, token, DISCOVERY_TIMEOUT_MS)); - if (!isSuccess(context)) { - throw new CloudSandboxRequestError(context.res.statusCode, `HTTP ${context.res.statusCode ?? 'none'}`); - } - const body = await this._readJson<{ full_name?: string }>(context); - return body?.full_name; - } catch (error) { - this._logService.warn(`${LOG_PREFIX} Repository ${repositoryId} lookup failed: ${toErrorMessage(error)}`); - return undefined; + const generation = this._discoveryGeneration; + try { + const repository = await this._withApiClient(token, { caller: 'mc.repositoryClient.get', priority: 'enrichment' }, + (client, signal, options) => client.repositories.getById(repositoryId, signal, options)); + if (generation === this._discoveryGeneration) { + this._repositoryNames.set(repositoryId, repository.full_name); } - })(); - this._repositoryNames.set(repositoryId, pending); - pending.then(name => { - if (!name && this._repositoryNames.get(repositoryId) === pending) { - this._repositoryNames.delete(repositoryId); + return repository.full_name; + } catch (error) { + if (isCancellationError(error) || token.isCancellationRequested) { + throw new CancellationError(); } - }); - return pending; + this._logService.warn(`${LOG_PREFIX} Repository ${repositoryId} lookup failed: ${toErrorMessage(error)}`); + return undefined; + } } /** Shared handler for the `connect`/`reconnect` endpoints (200 token or 202 waking). */ private async _connectRequest( - action: CloudSandboxEnvironmentAction, request: ICloudSandboxConnectionRequest, token: CancellationToken, - searchParams: Record, + clientId?: string, ): Promise { const { environmentId, environmentKind, onRequest } = request; + const action = clientId === undefined ? 'connect' : 'reconnect'; const operation = this._telemetry.lifecycle.start(action === 'connect' ? 'credentials.connect' : 'credentials.refresh', { - environmentKind, environmentId, agentSessionId: searchParams.session_id, connectionId: searchParams.client_id, + environmentKind, environmentId, agentSessionId: request.sessionId, connectionId: clientId, }); let failurePoint: CloudSandboxLifecycleFailurePoint = 'credentials.request'; + let requestingCredentials = false; try { - const context = await this._sendEnvironment(action, environmentId, token, searchParams, onRequest); - operation.bind({ serverRequestId: getGitHubRequestId(context.res.headers?.['x-github-request-id']) }); - if (context.res.statusCode === 202) { + const result = await this._withApiClient(token, { caller: `mc.environmentClient.${action}`, priority: 'mutation' }, + (client, signal, options) => { + onRequest?.('issued'); + requestingCredentials = true; + const connectionOptions = { ...options, query: request.sessionId ? { session_id: request.sessionId } : undefined }; + return clientId === undefined + ? client.environments.connect(environmentId, signal, connectionOptions) + : client.environments.reconnect(environmentId, clientId, signal, connectionOptions); + }, { action }); + requestingCredentials = false; + operation.bind({ serverRequestId: result.requestId }); + this._logService.trace(`${LOG_PREFIX} ${action} -> HTTP ${result.status}`); + if (result.status === 202) { onRequest?.('waking'); - const retryAfterSeconds = parseRetryAfter(context.res.headers?.['retry-after']); + const retryAfterSeconds = result.retryAfterSeconds ?? DEFAULT_WAKING_RETRY_AFTER_SECONDS; this._logService.debug(`${LOG_PREFIX} ${action}: environment waking, retry after ${retryAfterSeconds}s`); operation.complete('waking', {}, undefined, 202); return { kind: 'waking', waking: { retryAfterSeconds } }; } - if (!isSuccess(context)) { - await this._throwForStatus(action, context); - } - failurePoint = 'credentials.invalidResponse'; - const clientToken = await this._readJson(context); - if (!clientToken?.access_token || !clientToken?.wps_endpoint || !clientToken?.client_id || !clientToken?.groups) { - failurePoint = 'credentials.incompleteResponse'; - throw new Error(`Mission Control ${action} returned an incomplete token response`); - } - if (action === 'reconnect' && clientToken.client_id !== searchParams.client_id) { - failurePoint = 'credentials.clientMismatch'; - throw new Error('Cloud sandbox reconnect returned credentials for a different client'); - } - operation.complete('succeeded', { connectionId: clientToken.client_id }, undefined, context.res.statusCode); - return { kind: 'token', token: clientToken }; + operation.complete('succeeded', { connectionId: result.data.client_id }, undefined, result.status); + return { kind: 'token', token: result.data }; } catch (error) { - operation.complete(isCancellationError(error) || token.isCancellationRequested ? 'cancelled' : 'failed', { failurePoint }, error); - throw error; - } - } - - /** - * Issue an agent-environment request and return the raw response. The caller owns status - * handling, since the meaning of a status is endpoint-specific (notably HTTP 202 = "waking", - * which is neither an error nor a result). - */ - private async _sendEnvironment( - action: CloudSandboxEnvironmentAction, - environmentId: string, - token: CancellationToken, - searchParams?: Record, - onRequest?: ICloudSandboxConnectionRequest['onRequest'], - ): Promise { - const path = action === 'get' ? '' : `/${action}`; - const url = `${GITHUB_DOT_COM_COPILOT_API_BASE_URI}/agents/environments/${encodeURIComponent(environmentId)}${path}${toQuery(searchParams)}`; - return this._request(url, `mc.environmentClient.${action}`, action === 'get' ? 'getEnvironment' : action, { - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, action === 'get' ? REQUEST_TIMEOUT_MS : CONNECTION_REQUEST_TIMEOUT_MS, undefined, undefined, onRequest); - } - - /** Issue a task API request, throwing on a non-success status. */ - private async _sendTask(url: string, action: 'list' | 'get', token: CancellationToken, onRequest?: () => void, onResponse?: (session: AuthenticationSession) => void): Promise { - const context = await this._retryWhileRateLimited(`task ${action}`, token, () => this._request(url, `mc.taskClient.${action}`, action === 'list' ? 'listTasks' : 'getTask', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - }, token, DISCOVERY_TIMEOUT_MS, undefined, undefined, onRequest, { onResponse })); - if (!isSuccess(context)) { - await this._throwForStatus(`task ${action}`, context); - } - return context; - } - - /** - * Re-issue a discovery read that came back rate-limited, waiting for `Retry-After` when the - * response names one and backing off exponentially when it does not. - * - * Discovery reads the API far harder than any other sandbox call, so it is the one path that - * routinely trips the limit. Reporting a 429 rather than retrying it loses the session being - * resolved for the rest of the window, because nothing re-runs a pass that otherwise succeeded. - */ - private async _retryWhileRateLimited(action: string, token: CancellationToken, send: () => Promise): Promise { - let waited = 0; - for (let attempt = 0; ; attempt++) { - const context = await send(); - if (context.res.statusCode !== HTTP_TOO_MANY_REQUESTS || attempt >= RATE_LIMIT_MAX_RETRIES || token.isCancellationRequested) { - return context; + if (error instanceof MutationUncertainError && (error.kind === 'schema' || error.kind === 'malformedResponse')) { + failurePoint = 'credentials.invalidResponse'; } - const delay = rateLimitDelay(retryAfterSeconds(context.res.headers?.['retry-after']), attempt); - // Waiting less than asked would re-issue inside the server's window, so a delay that - // does not fit ends the retries rather than being trimmed to fit. - if (waited + delay > RATE_LIMIT_WAIT_BUDGET_MS) { - this._logService.warn(`${LOG_PREFIX} ${action} was rate limited and asks for another ${delay}ms, beyond what is left of its ${RATE_LIMIT_WAIT_BUDGET_MS}ms budget; giving up so the pass stays bounded. A later pass retries it.`); - return context; + if (error instanceof CloudSandboxRequestError) { + operation.bind({ serverRequestId: error.requestId }); + this._logService.error(`${LOG_PREFIX} ${error.message}${error.limitedResource ? ` limitedResource=${error.limitedResource}` : ''}`); } - // Nothing reads the body on this path, and an unconsumed stream holds its connection. - await asText(context).catch(() => undefined); - this._logService.warn(`${LOG_PREFIX} ${action} was rate limited; retrying in ${delay}ms (attempt ${attempt + 1} of ${RATE_LIMIT_MAX_RETRIES}).`); - await timeout(delay, token); - waited += delay; + const cancelled = isCancellationError(error) || token.isCancellationRequested; + const unanswered = requestingCredentials && error instanceof RequestError && (error.kind === 'network' + || error.kind === 'timeout' && (error instanceof MutationUncertainError || error instanceof GitHubRequestTimeoutError && error.requestDispatched)); + const failure = !cancelled && unanswered ? new CloudSandboxNetworkError('Mission Control connection request failed', { cause: error }) : error; + operation.complete(cancelled ? 'cancelled' : 'failed', { failurePoint }, failure); + throw failure; } } - private async _request(url: string, callSite: string, action: CloudSandboxRequestAction, headers: Record, token: CancellationToken, timeoutMs: number = REQUEST_TIMEOUT_MS, body?: Record | ((session: AuthenticationSession) => Record), method?: 'GET' | 'POST' | 'DELETE' | 'PATCH', onRequest?: ICloudSandboxConnectionRequest['onRequest'], requestContext?: { readonly diagnosticId?: string; readonly authentication?: AuthenticationSession; readonly expectedAccountKey?: string; readonly onResponse?: (session: AuthenticationSession) => void }): Promise { + private async _request(url: string, callSite: string, action: CloudSandboxRequestAction, headers: Record, token: CancellationToken, onRequest?: () => void, requestContext?: { readonly diagnosticId?: string; readonly authentication?: AuthenticationSession }): Promise { let session = requestContext?.authentication ?? await this._resolveGitHubSession(); if (!session?.accessToken) { // No request is issued, so there is no request outcome to count. throw new CloudSandboxAuthenticationRequiredError(); } - if (requestContext?.expectedAccountKey !== undefined && requestContext.expectedAccountKey !== this._accountKeyForSession(session)) { - throw new CancellationError(); - } let accessToken = session.accessToken; const started = Date.now(); - const requestMethod = method ?? (body === undefined ? 'GET' : 'POST'); + const timeoutMs = LEGACY_READ_TIMEOUT_MS; try { if (token.isCancellationRequested) { throw new CancellationError(); @@ -1653,31 +1518,21 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA if (token.isCancellationRequested) { throw new CancellationError(); } - onRequest?.('issued'); + onRequest?.(); const context = await this._requestService.request({ - type: requestMethod, + type: 'GET', url, headers: { ...headers, - // `fetch` labels a string body `text/plain` unless told otherwise. - ...(body === undefined ? undefined : { ['Content-Type']: 'application/json' }), ['Authorization']: `Bearer ${accessToken}` }, - ...(body === undefined ? undefined : { data: JSON.stringify(typeof body === 'function' ? body(session) : body) }), timeout: timeoutMs, callSite, ...(requestContext?.diagnosticId !== undefined ? { diagnosticId: requestContext.diagnosticId } : {}), - }, token).catch((error: unknown) => { - if ((action === 'connect' || action === 'reconnect') && !isCancellationError(error) && !token.isCancellationRequested) { - throw new CloudSandboxNetworkError('Mission Control connection request failed'); - } - throw error; - }); + }, token); this._telemetry.reportRequest(action, requestOutcomeForStatus(context.res.statusCode)); - // Latency against its budget: `/connect` blocks on a compute resume, so how close a reply - // came to being cut off separates "Mission Control is silent" from "we stopped listening". this._logService.trace(`${LOG_PREFIX} ${action} -> HTTP ${context.res.statusCode ?? 'none'} in ${Date.now() - started}ms (budget ${timeoutMs}ms)${context.res.headers?.['retry-after'] ? `, Retry-After: ${context.res.headers['retry-after']}` : ''}`); - if (requestMethod === 'GET' && context.res.statusCode === 401 && attempt === 0) { + if (context.res.statusCode === 401 && attempt === 0) { const replacement = await raceCancellationError(this._resolveGitHubSession(), token).catch(error => { if (!(error instanceof CloudSandboxAuthenticationRequiredError)) { throw error; @@ -1692,7 +1547,6 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA continue; } } - requestContext?.onResponse?.(session); return context; } } catch (error) { @@ -1700,20 +1554,15 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA const cancellationError = isCancellationError(error) ? error : token.isCancellationRequested ? new CancellationError() : undefined; - const requestError = action === 'mintIdentityToken' - ? new CloudSandboxNetworkError(localize('cloudSandbox.identityNetworkError', "The sandbox identity-token request failed before a response was received.")) - : action === 'sealToken' - ? new CloudSandboxNetworkError(localize('cloudSandbox.sealingNetworkError', "The sandbox token-sealing request failed before a response was received.")) - : error; if (cancellationError) { this._logService.trace(`${LOG_PREFIX} ${action} -> cancelled after ${Date.now() - started}ms (budget ${timeoutMs}ms)`); } else { this._telemetry.reportRequest(action, 'networkError'); // Elapsed at the budget means our own timeout fired; shorter means something else did. this._logService.trace(`${LOG_PREFIX} ${action} -> failed after ${Date.now() - started}ms (budget ${timeoutMs}ms)`); - this._logService.error(`${LOG_PREFIX} ${requestMethod} ${action} failed before a response was available.`); + this._logService.error(`${LOG_PREFIX} GET ${action} failed before a response was available.`); } - throw cancellationError ?? requestError; + throw cancellationError ?? error; } } @@ -1726,25 +1575,12 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } async listModels(token: CancellationToken): Promise { - const context = await this._request(`${this._tasksBaseUrl()}/swe/models`, 'mc.models.list', 'listModels', { - 'Accept': 'application/json', - 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, - 'X-GitHub-Api-Version': '2026-06-01', - }, token, DISCOVERY_TIMEOUT_MS); - if (!isSuccess(context)) { - await this._throwForStatus('model catalog', context); - } - const catalog = await this._readJson<{ data?: ICloudModel[]; default_model?: string }>(context); - if (!catalog || !Array.isArray(catalog.data) || (catalog.default_model !== undefined && typeof catalog.default_model !== 'string')) { - throw new Error('Mission Control returned an invalid model catalog.'); - } + const catalog = await this._withApiClient(token, { caller: 'mc.models.list', priority: 'interactive' }, + (client, signal, options) => client.missionControlModels.list(signal, options), + { action: 'model catalog' }); const models: SessionModelInfo[] = []; for (const model of catalog.data) { - const efforts = model?.capabilities?.supports?.reasoning_effort; - if (!model || typeof model.id !== 'string' || !model.id || typeof model.name !== 'string' - || (efforts !== undefined && (!Array.isArray(efforts) || !efforts.every(value => typeof value === 'string')))) { - throw new Error('Mission Control returned invalid model metadata.'); - } + const efforts = model.capabilities?.supports?.reasoning_effort; if (model.model_picker_enabled === false || model.policy?.state === 'disabled') { continue; } @@ -1791,41 +1627,26 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } } - /** - * Throw a diagnosable error for a non-success response. Pass `prereadBody` when the caller has - * already consumed the stream, since reading it twice yields nothing. - */ - private async _throwForStatus(action: string, context: IRequestContext, prereadBody?: string): Promise { - const body = prereadBody ?? await asText(context).catch(() => ''); + /** Surface credential-free diagnostics from a failed raw read. */ + private async _throwForStatus(action: string, context: IRequestContext): Promise { + const body = await asText(context).catch(() => ''); const status = context.res.statusCode; const metadata = parseMissionControlError(body, context.res.headers?.['x-github-request-id']); - const error = new CloudSandboxRequestError( + const error = this._createRequestError(action, status, retryAfterSeconds(context.res.headers?.['retry-after']), metadata); + this._logService.error(`${LOG_PREFIX} ${error.message}${metadata.limitedResource ? ` limitedResource=${metadata.limitedResource}` : ''}`); + throw error; + } + + private _createRequestError(action: string, status: number | undefined, retryAfter: number | undefined, metadata: MissionControlErrorMetadata, outcome?: 'indeterminate'): CloudSandboxRequestError { + return new CloudSandboxRequestError( status, `Mission Control ${action} failed: HTTP ${status ?? 'unknown'}${metadata.code ? ` code=${metadata.code}` : ''}${metadata.requestId ? ` (requestId=${metadata.requestId})` : ''}`, - retryAfterSeconds(context.res.headers?.['retry-after']), + retryAfter, metadata, + outcome, ); - this._logService.error(`${LOG_PREFIX} ${error.message}${metadata.limitedResource ? ` limitedResource=${metadata.limitedResource}` : ''}`); - throw error; } - /** The task id from a failed create, when the response names the task it already recorded. */ - private _taskIdFromFailure(body: string): string | undefined { - if (!body) { - return undefined; - } - try { - const parsed = JSON.parse(body) as { id?: unknown; task_id?: unknown }; - for (const candidate of [parsed?.id, parsed?.task_id]) { - if (typeof candidate === 'string' && candidate.length > 0) { - return candidate; - } - } - } catch { - // A non-JSON error body names no task. - } - return undefined; - } /** A GitHub session carrying at least the configured chat provider scopes. */ private async _resolveGitHubSession(): Promise { const providerId = this._authenticationProviderId; @@ -1863,91 +1684,17 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA } } -function parseSealedTokenResponse(response: ISealedTokenResponse | undefined): ICloudSandboxSealedToken { - const key = response?.host_encryption_key; - const sealed = response?.encrypted_github_token; - const invalidResponse = () => new Error(localize('cloudSandbox.invalidSealedToken', "The sandbox token-sealing response is invalid.")); - if (typeof sealed !== 'string' || sealed.length > 64 * 1024 || !isObject(key) - || typeof key.key_id !== 'string' || !/^[A-Za-z0-9_-]{11}$/.test(key.key_id) - || key.use !== 'auth-token' || typeof key.public_key !== 'string' - || (key.algorithm !== 'x25519-sealedbox' && key.algorithm !== 'hpke-x25519-hkdf-sha256-aes256gcm')) { - throw invalidResponse(); - } - const prefix = `${CLOUD_SANDBOX_SEALED_TOKEN_PREFIX}${key.key_id}.`; - const payload = sealed.slice(prefix.length); - if (!sealed.startsWith(prefix) || !/^[A-Za-z0-9_-]+$/.test(payload)) { - throw invalidResponse(); - } - let publicKey: VSBuffer; - let ciphertext: VSBuffer; - try { - publicKey = decodeBase64(key.public_key); - ciphertext = decodeBase64(payload); - } catch { - throw invalidResponse(); - } - if (publicKey.byteLength !== 32 || encodeBase64(publicKey) !== key.public_key - || ciphertext.byteLength < 48 || encodeBase64(ciphertext, false, true) !== payload) { - throw invalidResponse(); - } - return { - encrypted_github_token: sealed, - host_encryption_key: { key_id: key.key_id, use: key.use, algorithm: key.algorithm, public_key: key.public_key }, - }; -} - function isSuccess(context: IRequestContext): boolean { const status = context.res.statusCode ?? 0; return status >= 200 && status < 300; } -function toQuery(searchParams: Record | undefined): string { - if (!searchParams) { - return ''; - } - const search = new URLSearchParams(searchParams).toString(); - return search ? `?${search}` : ''; -} - -/** Parse a `Retry-After` header; fall back to a small default. */ -function parseRetryAfter(value: string | string[] | undefined): number { - return retryAfterSeconds(value) ?? DEFAULT_WAKING_RETRY_AFTER_SECONDS; -} - /** Provisioning tasks can advertise an empty provider before their runtime is ready. */ -function isCloudSandboxTask(task: ITaskSummary): boolean { +function isCloudSandboxTask(task: Task): boolean { const provider = task.compute?.provider; return provider === 'sandboxes' || ((provider === undefined || provider === '') && task.current_environment?.kind === 'managed-sandbox'); } -/** - * The next task-list page advertised by a `Link` header, or `undefined` on the last page. - * Only the query is adopted: discovery stays on the CORS-enabled endpoint and keeps the - * scope filters a numbered link may omit. - */ -function nextTaskPageUrl(value: string | string[] | undefined, requestUrl: string, query: Record): string | undefined { - const raw = Array.isArray(value) ? value.join(',') : value; - const link = nextLink(raw); - if (!link) { - if (raw && /\brel\s*=\s*["']?[^;,]*\bnext\b/i.test(raw)) { - throw new Error('Task list returned an unsupported pagination link'); - } - return undefined; - } - const current = new URL(requestUrl); - const next = new URL(link, current); - if ((next.origin !== current.origin && next.origin !== GITHUB_DOT_COM_API_BASE_URI) || next.pathname !== current.pathname) { - throw new Error('Task list returned an invalid pagination URL'); - } - for (const [key, value] of Object.entries(query)) { - if (!next.searchParams.has(key)) { - next.searchParams.set(key, value); - } - } - current.search = next.search; - return current.href; -} - function isConcreteEnvironmentId(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0 && value !== CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID; } @@ -1961,16 +1708,10 @@ function parseNwo(nwo: string | undefined): { owner: string; name: string } | un return { owner: nwo.slice(0, separator), name: nwo.slice(separator + 1) }; } -/** - * The Mission Control environment a sandbox task runs in, read from the full task's nested - * `sessions[]`. Undefined when no session is bound to an environment yet. - */ -function getTaskEnvironmentBinding(task: ITaskDetail): { environmentId: string; sessionId: string } | undefined { - if (!Array.isArray(task.sessions)) { - return undefined; - } - for (const session of task.sessions) { - if (isConcreteEnvironmentId(session?.environment_id) && typeof session.id === 'string' && session.id.trim().length > 0) { +/** Finds a session bound to a concrete environment rather than the provisioning placeholder. */ +function getTaskEnvironmentBinding(task: GetTaskResponse): { environmentId: string; sessionId: string } | undefined { + for (const session of task.sessions ?? []) { + if (isConcreteEnvironmentId(session.environment_id)) { return { environmentId: session.environment_id, sessionId: session.id }; } } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts index 361381e493e9..69a85b0055d4 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts @@ -15,8 +15,8 @@ import { CLOUD_SANDBOX_SESSION_SCHEME, cloudSandboxEnvironmentId, ICloudSandboxAgentHostService, - isCloudSandboxSealedToken, } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; +import { isSealedEnvironmentToken } from '../../../../../platform/github/common/missionControl/environments.js'; import { IAgentHostAuthenticateRequest } from '../agentSessions/agentHost/agentHostAuth.js'; import { IRemoteAgentHostConnectionCustomization } from './remoteAgentHostConnectionCustomization.js'; import { createCloudSandboxSessionPreparation } from './cloudSandboxLegacySessionPreparation.js'; @@ -69,7 +69,7 @@ export function createCloudSandboxConnectionCustomization( const sealed = renew ? await sandboxService.refreshSealedGitHubToken(environmentId) : sandboxService.getSealedGitHubToken(environmentId); - if (!sealed || !isCloudSandboxSealedToken(sealed)) { + if (!sealed || !isSealedEnvironmentToken(sealed)) { throw new Error(`No sealed GitHub token is available for cloud sandbox ${address}; refusing to forward a plaintext bearer.`); } return { resource, scopes, token: sealed }; @@ -78,7 +78,7 @@ export function createCloudSandboxConnectionCustomization( requiresWorkspaceTrust: false, inputPlaceholder: provider => !userLocal && provider === CLOUD_SANDBOX_AGENT_PROVIDER ? CLOUD_SANDBOX_INPUT_PLACEHOLDER : undefined, authenticate: async (request: IAgentHostAuthenticateRequest, reason?: AuthRequiredReason): Promise => { - if (reason !== AuthRequiredReason.Expired && isCloudSandboxSealedToken(request.token)) { + if (reason !== AuthRequiredReason.Expired && isSealedEnvironmentToken(request.token)) { return request; } if (userLocal && (request.target || !isGitHubResource(request.resource))) { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxCredentialRefresh.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxCredentialRefresh.ts index c29205aee27f..c73f4bf92c5d 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxCredentialRefresh.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxCredentialRefresh.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { raceCancellationError, timeout } from '../../../../../base/common/async.js'; +import { DeferredPromise, raceCancellationError, timeout } from '../../../../../base/common/async.js'; import { CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; import { CancellationError, isCancellationError } from '../../../../../base/common/errors.js'; @@ -11,16 +11,15 @@ import { Disposable, toDisposable } from '../../../../../base/common/lifecycle.j import { equals } from '../../../../../base/common/objects.js'; import { generateUuid } from '../../../../../base/common/uuid.js'; import { - CLOUD_SANDBOX_SEALED_TOKEN_PREFIX, CloudSandboxRequestError, ICloudSandboxApiService, - isCloudSandboxSealedToken, isRetryableCloudSandboxError, type CloudSandboxConnectResult, type ICloudSandboxClientToken, type ICloudSandboxConnectionRequest, } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; +import { isSealedEnvironmentToken, SEALED_ENVIRONMENT_TOKEN_PREFIX } from '../../../../../platform/github/common/missionControl/environments.js'; import { MISSION_CONTROL_RETRY_BUDGET_MS, missionControlMaxRetries, missionControlRetryDelay } from '../../../../../platform/github/common/missionControl/missionControlError.js'; import { ICloudSandboxTelemetryService, type CloudSandboxRefreshStopReason } from './cloudSandboxTelemetry.js'; import { type CloudSandboxLifecycleFailurePoint, type CloudSandboxLifecycleOperation, type ICloudSandboxLifecycleContext } from './cloudSandboxLifecycleTelemetry.js'; @@ -35,7 +34,7 @@ export function mergeCloudSandboxConnectionToken(previous: ICloudSandboxClientTo if (hostKey) { const matchesKey = typeof sealedToken === 'string' && typeof hostKey.key_id === 'string' && hostKey.key_id.length > 0 - && sealedToken.startsWith(`${CLOUD_SANDBOX_SEALED_TOKEN_PREFIX}${hostKey.key_id}.`); + && sealedToken.startsWith(`${SEALED_ENVIRONMENT_TOKEN_PREFIX}${hostKey.key_id}.`); const reusedKeyChanged = reusesSealedToken && previous.host_encryption_key !== undefined && !equals(previous.host_encryption_key, hostKey); if (!matchesKey || reusedKeyChanged) { @@ -80,6 +79,7 @@ export class CloudSandboxCredentialRefresher extends Disposable { private readonly _cts = new CancellationTokenSource(); private _refreshInFlight: Promise | undefined; + private _resume: { readonly ready: DeferredPromise; readonly suspendedAt: number } | undefined; constructor( private readonly _address: string, @@ -95,6 +95,22 @@ export class CloudSandboxCredentialRefresher extends Disposable { this._register(toDisposable(() => this._cts.dispose(true))); } + suspend(): void { + this._resume ??= { ready: new DeferredPromise(), suspendedAt: Date.now() }; + } + + resume(): void { + const suspended = this._resume; + if (!suspended) { + return; + } + this._resume = undefined; + if (this._refreshState.requestFailureStartedAt !== undefined) { + this._refreshState.requestFailureStartedAt += Math.max(0, Date.now() - suspended.suspendedAt); + } + suspended.ready.complete(); + } + /** Share an in-flight refresh or refresh expired credentials before opening a replacement transport. */ ensureUnexpiredCredentials(): Promise { return this._ensureCredentials(false); @@ -112,7 +128,7 @@ export class CloudSandboxCredentialRefresher extends Disposable { const previousToken = this._creds.token.encrypted_github_token; await this.refreshConnectionCredentials(); const sealedToken = this._creds.token.encrypted_github_token; - if (!sealedToken || !isCloudSandboxSealedToken(sealedToken) || sealedToken === previousToken) { + if (!sealedToken || !isSealedEnvironmentToken(sealedToken) || sealedToken === previousToken) { const error = new Error('Sandbox authentication refresh did not provide a new sealed token.'); operation.complete('failed', { failurePoint: 'credentialRefresh.authenticationTokenUnchanged' }, error); throw error; @@ -143,6 +159,10 @@ export class CloudSandboxCredentialRefresher extends Disposable { const previousToken = this._creds.token; let waited = false; while (!this._refreshInFlight) { + if (this._resume) { + await raceCancellationError(this._resume.ready.p, this._cts.token); + continue; + } if (!this._refreshState.stopped && this._refreshState.requestFailureStartedAt !== undefined && Date.now() - this._refreshState.requestFailureStartedAt >= MISSION_CONTROL_RETRY_BUDGET_MS) { this._stop('consecutiveFailures', 'Mission Control request retry budget exhausted', undefined, { failurePoint: 'credentialRefresh.retryBudget' }); @@ -243,6 +263,10 @@ export class CloudSandboxCredentialRefresher extends Disposable { operation.complete('cancelled', { recoveryAction: 'cancelled' }); return false; } + if (this._resume && isRetryableCloudSandboxError(err)) { + operation.complete('cancelled', { recoveryAction: 'deferred' }); + return false; + } // A rejected request (deleted environment, revoked token) fails identically however // often it is repeated, so retrying only adds load without any prospect of recovery. if (!isRetryableCloudSandboxError(err)) { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxTelemetry.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxTelemetry.ts index c81da5c60a1f..0c5c61d08581 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxTelemetry.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxTelemetry.ts @@ -9,7 +9,7 @@ import { LRUCache } from '../../../../../base/common/map.js'; import { Mutable } from '../../../../../base/common/types.js'; import { generateUuid, isUUID } from '../../../../../base/common/uuid.js'; import { CloudSandboxRequestError, cloudSandboxDiscoveryTriggers, cloudSandboxFullScanReasons, cloudSandboxTaskCreationPaths, type CloudSandboxDiscoveryTrigger, type CloudSandboxFullScanReason, type CloudSandboxTaskCreationPath, type ICloudSandboxConnectOptions, type ICloudSandboxCreatedSession, type ICloudSandboxCreateSessionRequest, type ICloudSandboxDiscoveryDiagnostics, type ICloudSandboxDiscoveryResult } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; -import { type ConnectionDiagnosticRequestKind, IConnectionDiagnosticEvent, type IConnectionDiagnosticState } from '../../../../../platform/agentHost/common/connectionDiagnostics.js'; +import { connectionCloseReasons, type ConnectionCloseReason, type ConnectionDiagnosticRequestKind, IConnectionDiagnosticEvent, type IConnectionDiagnosticState } from '../../../../../platform/agentHost/common/connectionDiagnostics.js'; import { getConnectionTelemetryError, type ConnectionTelemetryErrorClassification, type IConnectionTelemetryError } from '../../../../../platform/agentHost/common/connectionTelemetry.js'; import { RemoteAgentHostConnectionObserver } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; @@ -68,6 +68,7 @@ type CloudSandboxTaskCreationClassification = { }; type CloudSandboxConnectionPhase = Exclude; type CloudSandboxEnvironmentOperation = 'provision' | 'resume' | 'recover' | 'attach'; +type RecoveryStopReason = 'attemptsExhausted' | 'timeout' | 'authentication' | 'protocol' | 'nonReconnectable'; type CloudSandboxConnectionContext = Pick & Partial>; export function getCloudSandboxConnectionSurface(isSessionsWindow: boolean, isWeb: boolean): CloudSandboxConnectionSurface { @@ -309,6 +310,10 @@ export class CloudSandboxTelemetryService extends Disposable implements ICloudSa durationMs: data.durationMs, pageCount: data.pageCount, listRequestCount: data.listRequestCount, + listOperationCount: data.listOperationCount, + listOperationFailureCount: data.listOperationFailureCount, + taskBatchOperationCount: data.taskBatchOperationCount, + taskBatchOperationFailureCount: data.taskBatchOperationFailureCount, taskCount: data.taskCount, sandboxTaskCount: data.sandboxTaskCount, changedSandboxTaskCount: data.changedSandboxTaskCount, @@ -399,9 +404,14 @@ interface IConnectionOperation { stage: CloudSandboxConnectionStage; preparationStartedAt: number | undefined; preparationMs: number; - credentialRequests: number; + credentialOperations: number; wakingResponses: number; transportAttempts: number; + suspendCount: number; + suspendedAt: number | undefined; + suspendedMs: number; + recoveryStopReason?: RecoveryStopReason; + closeReason?: ConnectionCloseReason; firstFailure?: { readonly phase: string; readonly code: number | undefined; readonly error: IConnectionTelemetryError }; readonly failures: Record; readonly durations: Record; @@ -423,6 +433,8 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo private readonly _observedRequests = new Set(); private _connectedSince: number | undefined; private _restoring = false; + private _suspendedAt: number | undefined; + private _closeReason: ConnectionCloseReason | undefined; private _counts = { connectedMs: 0, unexpectedDisconnects: 0, receivedFrames: 0 }; constructor( @@ -457,7 +469,10 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo const measuredReservationWait = typeof reservationWaitMs === 'number' && Number.isFinite(reservationWaitMs) ? Math.max(0, reservationWaitMs) : undefined; return { - operation, stage, startedAt, credentialRequests: 0, wakingResponses: 0, transportAttempts: 0, + operation, stage, startedAt, credentialOperations: 0, wakingResponses: 0, transportAttempts: 0, + suspendCount: this._suspendedAt === undefined ? 0 : 1, + suspendedAt: this._suspendedAt === undefined ? undefined : startedAt, + suspendedMs: 0, provisioningMs, reservationWaitMs: operation === 'connect' && this._initialEnvironmentOperation === 'provision' ? measuredReservationWait === undefined ? undefined : Math.min(measuredReservationWait, provisioningMs ?? measuredReservationWait) @@ -509,15 +524,19 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo } this._connectedSince ??= Date.now(); this._complete('success'); + this._closeReason = undefined; break; case 'reconnecting': this._completeRequests('failure', { errorCategory: 'connectionClosed' }); this._restoring = true; if (this._connectedSince !== undefined) { this._pauseConnectedTime(); - this._counts.unexpectedDisconnects++; + if (this._suspendedAt === undefined) { + this._counts.unexpectedDisconnects++; + } this._lifecycle?.record({ ...this._lifecycleContext, phase: 'connection.closed', operationId: generateUuid(), outcome: 'observed' }); this._operation = this._newOperation('recover', 'connection'); + this._operation.closeReason = this._closeReason; this._lifecycleOperation = this._lifecycle?.start('connection.recover', this._lifecycleContext); } break; @@ -547,7 +566,7 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo if (event === 'issued') { operation = this._operation; if (operation) { - operation.credentialRequests++; + operation.credentialOperations++; } } else if (operation && operation === this._operation) { operation.wakingResponses++; @@ -559,6 +578,39 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo if (this._store.isDisposed) { return; } + if (this._environmentKind === 'user-local' && (event.phase === 'transport.closed' + || ((event.phase === 'transport.connect' || event.phase === 'transport.reconnect') && event.outcome === 'failed'))) { + const reason = event.closeReason && connectionCloseReasons.includes(event.closeReason) ? event.closeReason : 'unknown'; + this._closeReason ??= reason; + if (this._operation) { + this._operation.closeReason ??= reason; + } + } + if (event.phase === 'power.suspend') { + this._suspendedAt ??= Date.now(); + if (this._operation && this._operation.suspendedAt === undefined) { + this._operation.suspendCount++; + this._operation.suspendedAt = Date.now(); + } + return; + } + if (event.phase === 'power.resume') { + this._suspendedAt = undefined; + if (this._operation?.suspendedAt !== undefined) { + this._operation.suspendedMs += Math.max(0, Date.now() - this._operation.suspendedAt); + this._operation.suspendedAt = undefined; + } + return; + } + if (this._operation) { + switch (event.phase) { + case 'reconnect.exhausted': this._operation.recoveryStopReason = 'attemptsExhausted'; break; + case 'reconnect.timedOut': this._operation.recoveryStopReason = 'timeout'; break; + case 'authentication.failed': this._operation.recoveryStopReason = 'authentication'; break; + case 'protocol.incompatible': this._operation.recoveryStopReason = 'protocol'; break; + case 'reconnect.nonReconnectable': this._operation.recoveryStopReason = 'nonReconnectable'; break; + } + } if (event.phase === 'chat.binding' && event.sessionResource && event.chatResource) { this._chatSessions.set(event.chatResource, event.sessionResource); } @@ -712,6 +764,7 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo const { id, startedAt, ...context } = request; const event: CloudSandboxFirstSessionRequestEvent = { ...context, ...error, + ...(outcome === 'failure' && error?.errorCategory === 'connectionClosed' && this._closeReason ? { closeReason: this._closeReason } : {}), surface: this._surface, source: this._source, environmentKind: this._environmentKind, outcome, taskCreationPath: this._taskCreationPath, durationMs: Math.max(0, Date.now() - startedAt), @@ -755,6 +808,10 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo const durationMs = Math.max(0, Date.now() - operation.startedAt); const preparationMs = Math.min(durationMs, operation.preparationMs); this._reportOutcome({ + ...(operation.closeReason ? { closeReason: operation.closeReason } : {}), + suspendCount: operation.suspendCount, + suspendedMs: operation.suspendedMs + (operation.suspendedAt === undefined ? 0 : Math.max(0, Date.now() - operation.suspendedAt)), + ...(operation.recoveryStopReason === undefined ? {} : { recoveryStopReason: operation.recoveryStopReason }), ...(operation.firstFailure?.error.errorCategory ? { firstFailureCategory: operation.firstFailure.error.errorCategory } : {}), ...(operation.firstFailure?.error.statusCode === undefined ? {} : { firstFailureStatusCode: operation.firstFailure.error.statusCode }), operation: operation.operation, outcome, stage: operation.stage, durationMs, @@ -765,7 +822,8 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo preparationMs, connectionMs: durationMs - preparationMs, surface: this._surface, source: this._source, environmentKind: this._environmentKind, taskCreationPath: this._taskCreationPath, - credentialRequests: operation.credentialRequests, wakingResponses: operation.wakingResponses, transportAttempts: operation.transportAttempts, + credentialRequests: undefined, credentialOperations: operation.credentialOperations, + wakingResponses: operation.wakingResponses, transportAttempts: operation.transportAttempts, credentialsMs: operation.durations.credentials, relayMs: operation.durations.relay, protocolMs: operation.durations.protocol, authenticationMs: operation.durations.authentication, restorationMs: operation.durations.restoration, firstFailurePhase: operation.firstFailure?.phase, firstFailureCode: operation.firstFailure?.code, @@ -790,6 +848,10 @@ class CloudSandboxConnectionTelemetry extends Disposable implements ICloudSandbo } type CloudSandboxConnectionOutcomeEvent = { + closeReason?: ConnectionCloseReason; + suspendCount: number; + suspendedMs: number; + recoveryStopReason?: RecoveryStopReason; environmentKind: CloudSandboxEnvironmentKind; taskCreationPath: CloudSandboxTaskCreationPath; operation: 'connect' | 'recover'; @@ -804,7 +866,8 @@ type CloudSandboxConnectionOutcomeEvent = { connectionMs: number; surface: CloudSandboxConnectionSurface; source: CloudSandboxConnectionSource; - credentialRequests: number; + credentialRequests: number | undefined; + credentialOperations: number; wakingResponses: number; transportAttempts: number; credentialsMs: number; @@ -824,6 +887,10 @@ type CloudSandboxConnectionOutcomeEvent = { }; export type CloudSandboxConnectionOutcomeClassification = CloudSandboxEnvironmentClassification & CloudSandboxTaskCreationClassification & { + closeReason?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'User-local only: first source-owned close boundary initiating this connect/recovery operation, preserved across retries. Allowlisted socket, relay/host handshake, publish acknowledgement/rejection, send, offline/lane/generation/limit, watchdog, protocol reinitialize, OS suspend, external close or unknown; not a server-side root cause.' }; + suspendCount: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'OS suspend intervals observed during this operation, including an interval already active when recovery began. Zero when no suspension was reported.' }; + suspendedMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Milliseconds of this operation spent in reported OS suspension, included in durationMs. Zero when no suspension was reported.' }; + recoveryStopReason?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Bounded source-owned reason automatic recovery stopped: attemptsExhausted, timeout, authentication, protocol, or nonReconnectable. Absent without an observed stop decision.' }; operation: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Logical connect or recovery, including all retries.' }; environmentOperation: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Provision follows task submission, including prepared-environment or reservation reuse; resume opens an existing sandbox; recover follows loss of a ready connection; attach connects a user-local Mission Control host. Client workflow, not confirmed VM lifecycle state.' }; outcome: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Success, failure, or cancellation; cancellations are not failures.' }; @@ -836,7 +903,8 @@ export type CloudSandboxConnectionOutcomeClassification = CloudSandboxEnvironmen connectionMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Elapsed milliseconds outside credential preparation, including relay, protocol, authentication, restoration and connection retry backoff. Together with preparationMs equals durationMs, without nested phase overlap.' }; surface: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Editor or Agents window, on desktop or web; unknown when not supplied.' }; source: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Created or existing environment from the caller; does not imply warm or cold compute.' }; - credentialRequests: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Credential requests handed to the request service during this operation, including failed and cancelled in-flight requests.' }; + credentialRequests: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Legacy credential request-service submissions; omitted for typed-client operations, whose wire attempts use shared GitHub transport telemetry.' }; + credentialOperations: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Credential operations submitted to the typed client, including failures and cancellations; not an HTTP attempt count.' }; wakingResponses: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Credential requests answered with a pending response during this operation.' }; transportAttempts: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Relay connection attempts begun during this operation.' }; credentialsMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Cumulative credential acquisition and waiting time, including partial spans; may overlap authentication.' }; @@ -871,6 +939,7 @@ export type CloudSandboxProvisioningOutcomeClassification = CloudSandboxTaskCrea }; type CloudSandboxFirstSessionRequestEvent = IConnectionTelemetryError & { + closeReason?: ConnectionCloseReason; environmentKind: CloudSandboxEnvironmentKind; taskCreationPath: CloudSandboxTaskCreationPath; surface: CloudSandboxConnectionSurface; @@ -883,6 +952,7 @@ type CloudSandboxFirstSessionRequestEvent = IConnectionTelemetryError & { }; export type CloudSandboxFirstSessionRequestClassification = CloudSandboxEnvironmentClassification & CloudSandboxTaskCreationClassification & ConnectionTelemetryErrorClassification & { + closeReason?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'User-local only: allowlisted source-owned close boundary interrupting this request. Unknown when uninstrumented; absent for success, cancellation and non-close failures. No socket reason text or remote identities.' }; surface: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Editor or Agents window, on desktop or web; unknown when not supplied.' }; source: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Created or existing environment from the caller; does not imply warm or cold compute.' }; outcome: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Outcome of the first session create, list, or subscribe request issued while ready; not turn completion.' }; @@ -919,8 +989,12 @@ export interface ICloudSandboxDiscoveryTelemetryData extends Mutable boolean): Promise { + const { providerId, scopes } = getGitHubEnvironmentAuthentication(product); + let account: AuthenticationSessionAccount | undefined; + if (defaultAccount) { + if (defaultAccount.authenticationProvider.id !== providerId) { + throw new GitHubEnvironmentAccountUnavailableError(localize('missionControlSharing.githubAccountRequired', "GitHub environment sharing requires a GitHub.com Copilot account."), 'nonGitHubAccount'); + } + const allSessions = await authentication.getSessions(providerId, undefined, undefined, true); + account = allSessions.find(session => session.id === defaultAccount.sessionId)?.account; + if (!account) { + throw new GitHubEnvironmentSharingError(localize('missionControlSharing.accountUnavailable', "The selected Copilot account is unavailable. Sign in to GitHub again to enable environment sharing."), 'accountUnavailable'); + } + } + const sessionOptions = account ? { account } : undefined; + let sessions = await authentication.getSessions(providerId, [...scopes], sessionOptions, true); + if (account) { + const accountId = account.id; + sessions = sessions.filter(session => session.account.id === accountId); + } + if (!sessions.length && canPrompt()) { + const session = await authentication.createSession(providerId, [...scopes], sessionOptions).catch(error => { + if (isCancellationError(error) || error === 'Cancelled' || (error instanceof Error && error.message === 'Cancelled')) { + throw new CancellationError(); + } + throw new GitHubEnvironmentSharingError(getErrorMessage(error), 'signInFailed', { cause: error, diagnostic: getConnectionDiagnosticError(error) }); + }); + if (account && session.account.id !== account.id) { + throw new GitHubEnvironmentSharingError(localize('missionControlSharing.accountMismatch', "Sign in with the selected Copilot account to enable GitHub environment sharing."), 'accountMismatch'); + } + sessions = [session]; + } + return sessions; +} diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts index 247190e2741a..049fcf317a4d 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts @@ -54,6 +54,7 @@ function isHost(value: unknown): value is IMissionControlHost { export class MissionControlEnvironmentService extends Disposable implements IMissionControlEnvironmentService { declare readonly _serviceBrand: undefined; readonly hosts = observableValue(this, []); + readonly discoveredOnlineHostIds = observableValue>(this, new Set()); readonly ownEnvironmentId = observableValue(this, undefined); private _accountKey: string | undefined; private _generation = 0; @@ -247,6 +248,8 @@ export class MissionControlEnvironmentService extends Disposable implements IMis } this._replaceHosts([...next.values()]); this._persist(); + // Publish last so automatic attachment cannot observe fresh admission with cached availability. + this.discoveredOnlineHostIds.set(new Set([...next.values()].filter(host => host.status === 'online').map(host => host.id)), undefined); } async connect(id: string, token: CancellationToken): Promise { @@ -475,6 +478,7 @@ export class MissionControlEnvironmentService extends Disposable implements IMis private _withdraw(): void { this._generation++; + this.discoveredOnlineHostIds.set(new Set(), undefined); this._discoveryCancellation.value?.cancel(); this._discoveryCancellation.clear(); this._initializing = undefined; diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlSharingService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlSharingService.ts index 56344f59970e..420ae675bb63 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlSharingService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlSharingService.ts @@ -3,11 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { RunOnceScheduler, Throttler } from '../../../../../base/common/async.js'; +import { RunOnceScheduler, Throttler, timeout } from '../../../../../base/common/async.js'; import { equals } from '../../../../../base/common/arrays.js'; +import { CancellationToken, cancelOnDispose } from '../../../../../base/common/cancellation.js'; import { IDefaultAccount } from '../../../../../base/common/defaultAccount.js'; -import { CancellationError } from '../../../../../base/common/errors.js'; -import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { getErrorMessage, isCancellationError } from '../../../../../base/common/errors.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { ResourceSet } from '../../../../../base/common/map.js'; import { Schemas } from '../../../../../base/common/network.js'; import { autorun, observableValue } from '../../../../../base/common/observable.js'; @@ -16,17 +17,20 @@ import { extUriBiasedIgnorePathCase } from '../../../../../base/common/resources import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; -import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService, isGitHubEnvironmentBackend, MissionControlUseLocalCredentialsSettingId } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { getConnectionDiagnosticError } from '../../../../../platform/agentHost/common/connectionDiagnostics.js'; +import { getConnectionTelemetryError } from '../../../../../platform/agentHost/common/connectionTelemetry.js'; +import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentSharingError, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService, isGitHubEnvironmentBackend, MissionControlOwnerMismatchErrorCode, MissionControlUseLocalCredentialsSettingId } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; -import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../platform/files/common/files.js'; +import { FileOperationResult, FileSystemProviderErrorCode, IFileService, toFileOperationResult, toFileSystemProviderErrorCode } from '../../../../../platform/files/common/files.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IPathService } from '../../../../../platform/path/common/pathService.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; -import { AuthenticationSessionAccount, IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; +import { IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { getGitHubEnvironmentAuthentication, getGitHubEnvironmentSessions } from './gitHubEnvironmentAccount.js'; const sharingStorageKey = 'agentHost.missionControl.sharing'; const gitDefaultCloneDirectorySetting = 'git.defaultCloneDirectory'; @@ -34,6 +38,14 @@ const environmentNameStorageKey = 'agentHost.missionControl.environmentName'; const missionControlIgnoreRemoteControlPolicy = 'chat.agentHost.experimentalMissionControl.ignoreRemoteControlPolicy'; const missionControlDisableRepositoryMetadata = 'chat.agentHost.experimentalMissionControl.disableRepositoryMetadata'; +/** Keeps the original message, so the notification is unchanged, and adds the file system error code. */ +function toFileSharingError(error: unknown, reason: 'fileSystemRoot' | 'projectFolder'): GitHubEnvironmentSharingError { + return new GitHubEnvironmentSharingError(getErrorMessage(error), reason, { + cause: error, + fileErrorCode: error instanceof Error ? toFileSystemProviderErrorCode(error) : FileSystemProviderErrorCode.Unknown, + }); +} + export class MissionControlSharingService extends Disposable implements IMissionControlSharingService { declare readonly _serviceBrand: undefined; readonly state = observableValue<'disabled' | 'connecting' | 'enabled'>(this, 'disabled'); @@ -46,8 +58,12 @@ export class MissionControlSharingService extends Disposable implements IMission private _accountSessionIds = new Set(); private _projectFolders: readonly URI[] | undefined; protected get isWindowsPlatform(): boolean { return isWindows; } + private readonly _enablement = this._register(new MutableDisposable()); private readonly _updates = this._register(new Throttler()); private readonly _update = this._register(new RunOnceScheduler(() => { + if (this._enablement.value) { + return; + } void this._updates.queue(() => this._configure()).catch(error => { this._logService.error('Mission Control configuration failed', error); }); @@ -178,19 +194,28 @@ export class MissionControlSharingService extends Disposable implements IMission } async setEnabled(enabled: boolean): Promise { - if (enabled && (!this._availabilityService.available.get() || !this._agentHost.configureMissionControl || !this._usesMissionControl() || !this._configuration.getValue(GitHubEnvironmentsEnabledSettingId) || this._entitlement.sentiment.hidden)) { - throw new Error(localize('missionControlSharing.unavailable', "GitHub environment sharing is unavailable.")); + if (enabled && !this._canShare()) { + throw new GitHubEnvironmentSharingError(localize('missionControlSharing.unavailable', "GitHub environment sharing is unavailable."), 'unavailable'); } this._enabled = enabled; this._generation++; this._update.cancel(); + this._enablement.clear(); if (!enabled) { this._storage.store(sharingStorageKey, false, StorageScope.APPLICATION, StorageTarget.MACHINE); await this._withdraw(); return; } this.state.set('connecting', undefined); - await this._updates.queue(() => this._configure(true)); + const enablement = new DisposableStore(); + this._enablement.value = enablement; + try { + await this._updates.queue(() => this._configure(enablement)); + } finally { + if (this._enablement.value === enablement) { + this._enablement.clear(); + } + } } async setEnvironmentName(name: string): Promise { @@ -215,10 +240,17 @@ export class MissionControlSharingService extends Disposable implements IMission await this._withdraw(); if (this._enabled) { this.state.set('connecting', undefined); - await this._updates.queue(() => this._configure()); + if (!this._enablement.value) { + await this._updates.queue(() => this._configure()); + } } } + private _canShare(): boolean { + return !!this._availabilityService.available.get() && !!this._agentHost.configureMissionControl && this._usesMissionControl() + && this._configuration.getValue(GitHubEnvironmentsEnabledSettingId) && !this._entitlement.sentiment.hidden; + } + private _usesMissionControl(): boolean { return isGitHubEnvironmentBackend(this._configuration.getValue(AgentHostRemoteConnectionsSettingId)); } @@ -250,7 +282,7 @@ export class MissionControlSharingService extends Disposable implements IMission } private _getScopes(): readonly string[] { - return this._product.defaultChatAgent?.providerScopes?.[0] ?? ['read:user', 'user:email', 'repo', 'workflow']; + return getGitHubEnvironmentAuthentication(this._product).scopes; } private async _getFileSystemRoots(): Promise { @@ -258,158 +290,201 @@ export class MissionControlSharingService extends Disposable implements IMission return [URI.file('/')]; } const drives = Array.from({ length: 26 }, (_, index) => URI.from({ scheme: Schemas.file, path: `/${String.fromCharCode(65 + index)}:/` })); - const roots = await Promise.all(drives.map(async drive => { + const checks = await Promise.all(drives.map(async (drive): Promise<{ readonly root?: URI; readonly failure?: { readonly drive: URI; readonly error: unknown } }> => { try { if (!(await this._fileService.stat(drive)).isDirectory) { - return undefined; + return {}; } const canonical = await this._fileService.realpath(drive); if (canonical?.fsPath.replace(/\\/g, '/').startsWith('//')) { this._logService.info('[Mission Control] Excluding a network-backed drive from local filesystem sharing', drive.toString()); - return undefined; + return {}; } - return drive; + return { root: drive }; } catch (error) { - if (!(error instanceof Error) || toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) { - throw error; - } - return undefined; + return error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND ? {} : { failure: { drive, error } }; } })); - return roots.filter(root => root !== undefined); + const roots = checks.flatMap(check => check.root ? [check.root] : []); + const failures = checks.flatMap(check => check.failure ? [check.failure] : []); + // A drive that cannot be read (e.g. an empty card reader or a locked volume) cannot be verified as local, so it is not + // shared. When no drive can be read, report the failure instead of granting little more than the home folder. + if (failures.length && !roots.length) { + throw toFileSharingError(failures[0].error, 'fileSystemRoot'); + } + for (const { drive, error } of failures) { + this._logService.warn('[Mission Control] Excluding a drive that cannot be read from local filesystem sharing', drive.toString(), getErrorMessage(error)); + } + return roots; } - private async _configure(interactive = false): Promise { + private async _configure(enablement?: DisposableStore): Promise { + let retries = 0; + let retryDelay = 0; + const token = enablement ? cancelOnDispose(enablement) : CancellationToken.None; + while (!this._store.isDisposed && !token.isCancellationRequested && enablement === this._enablement.value) { + const available = this._availabilityService.available.get(); + if (available === false || available !== undefined && !this._configuration.getValue(GitHubEnvironmentsEnabledSettingId)) { + await this._withdraw(); + return; + } + const generation = this._generation; + try { + if (retryDelay) { + await timeout(retryDelay, token); + } + if (generation !== this._generation) { + retryDelay = 0; + continue; + } + await this._configureOnce(!!enablement); + } catch (error) { + if (this._store.isDisposed || token.isCancellationRequested || !this._enabled || enablement !== this._enablement.value) { + this._logService.debug('Mission Control configuration cancelled', error); + return; + } + if (generation !== this._generation) { + this._logService.warn('Mission Control configuration superseded', error); + retryDelay = 0; + continue; + } + const diagnostic = error instanceof GitHubEnvironmentSharingError ? error.diagnostic ?? getConnectionDiagnosticError(error.cause) : getConnectionDiagnosticError(error); + const { errorCategory } = getConnectionTelemetryError(diagnostic); + if (enablement && retries < 2 && (errorCategory === 'timeout' || errorCategory === 'network' || errorCategory === 'dns')) { + this._logService.warn('Retrying GitHub environment connection', error); + retryDelay = 500 * 2 ** retries++; + continue; + } + if (enablement) { + this._enabled = false; + this._storage.store(sharingStorageKey, false, StorageScope.APPLICATION, StorageTarget.MACHINE); + } + await this._withdraw().catch(withdrawalError => this._reportWithdrawalError(withdrawalError)); + throw error; + } + if (generation === this._generation || !this._enabled || !this._canShare()) { + return; + } + retryDelay = 0; + } + } + + private async _configureOnce(interactive: boolean): Promise { const generation = this._generation; const available = this._availabilityService.available.get(); - if (available === false || available !== undefined && !this._configuration.getValue(GitHubEnvironmentsEnabledSettingId)) { - await this._withdraw(); - return; - } if (!available || !this._enabled || !this._usesMissionControl() || this._entitlement.sentiment.hidden) { return; } if (!this._configured) { this.state.set('connecting', undefined); } - try { - const providerId = this._product.defaultChatAgent?.provider?.default?.id ?? 'github'; - const scopes = this._getScopes(); - const defaultAccount = await this._defaultAccountService.getDefaultAccount(); - if (generation !== this._generation || this._store.isDisposed) { - return; - } - this._defaultAccount = defaultAccount; - let account: AuthenticationSessionAccount | undefined; - if (defaultAccount) { - if (defaultAccount.authenticationProvider.id !== providerId) { - throw new Error(localize('missionControlSharing.githubAccountRequired', "GitHub environment sharing requires a GitHub.com Copilot account.")); - } - const allSessions = await this._authentication.getSessions(providerId, undefined, undefined, true); - account = allSessions.find(session => session.id === defaultAccount.sessionId)?.account; - if (!account) { - throw new Error(localize('missionControlSharing.accountUnavailable', "The selected Copilot account is unavailable. Sign in to GitHub again to enable environment sharing.")); - } - } - const sessionOptions = account ? { account } : undefined; - let sessions = await this._authentication.getSessions(providerId, [...scopes], sessionOptions, true); - if (account) { - const accountId = account.id; - sessions = sessions.filter(session => session.account.id === accountId); - } - if (!sessions.length && interactive && generation === this._generation && !this._store.isDisposed) { - const session = await this._authentication.createSession(providerId, [...scopes], sessionOptions).catch(error => { - if (error === 'Cancelled' || (error instanceof Error && error.message === 'Cancelled')) { - throw new CancellationError(); - } - throw error; - }); - if (account && session.account.id !== account.id) { - throw new Error(localize('missionControlSharing.accountMismatch', "Sign in with the selected Copilot account to enable GitHub environment sharing.")); + const defaultAccount = await this._defaultAccountService.getDefaultAccount(); + if (generation !== this._generation || this._store.isDisposed) { + return; + } + this._defaultAccount = defaultAccount; + const sessions = await getGitHubEnvironmentSessions(this._authentication, this._product, defaultAccount, () => interactive && generation === this._generation && !this._store.isDisposed); + if (generation !== this._generation || this._store.isDisposed) { + return; + } + const accountCount = new Set(sessions.map(session => session.account.id)).size; + if (accountCount !== 1) { + throw new GitHubEnvironmentSharingError(localize('missionControlSharing.accountRequired', "Select a GitHub account for Copilot and sign in with the required permissions to enable environment sharing."), accountCount ? 'multipleAccounts' : 'signInRequired'); + } + const home = this._pathService.userHome({ preferLocal: true }); + const fileSystemRoots = await this._getFileSystemRoots(); + const folders = this._projectFolders ?? this._workspace.getWorkspace().folders.map(folder => folder.uri); + const projects = (await Promise.all(folders.filter(folder => folder.scheme === Schemas.file).map(async folder => { + try { + if ((await this._fileService.stat(folder)).isDirectory) { + return folder.fsPath; } - sessions = [session]; - } - if (generation !== this._generation || this._store.isDisposed) { - return; - } - if (new Set(sessions.map(session => session.account.id)).size !== 1) { - throw new Error(localize('missionControlSharing.accountRequired', "Select a GitHub account for Copilot and sign in with the required permissions to enable environment sharing.")); - } - const home = this._pathService.userHome({ preferLocal: true }); - const fileSystemRoots = await this._getFileSystemRoots(); - const folders = this._projectFolders ?? this._workspace.getWorkspace().folders.map(folder => folder.uri); - const projects = (await Promise.all(folders.filter(folder => folder.scheme === Schemas.file).map(async folder => { - try { - if ((await this._fileService.stat(folder)).isDirectory) { - return folder.fsPath; - } - this._logService.warn('[Mission Control] Ignoring a recent project path that is not a directory', folder.toString()); - } catch (error) { - const result = error instanceof Error ? toFileOperationResult(error) : undefined; - if (result !== FileOperationResult.FILE_NOT_FOUND && result !== FileOperationResult.FILE_NOT_DIRECTORY) { - throw error; - } - this._logService.warn('[Mission Control] Ignoring a missing or invalid recent project directory', folder.toString()); + this._logService.warn('[Mission Control] Ignoring a recent project path that is not a directory', folder.toString()); + } catch (error) { + const result = error instanceof Error ? toFileOperationResult(error) : undefined; + if (result !== FileOperationResult.FILE_NOT_FOUND && result !== FileOperationResult.FILE_NOT_DIRECTORY) { + throw toFileSharingError(error, 'projectFolder'); } - return undefined; - }))).filter(project => project !== undefined); - if (generation !== this._generation || this._store.isDisposed) { - return; + this._logService.warn('[Mission Control] Ignoring a missing or invalid recent project directory', folder.toString()); } - this._agentHost.startAgentHost(); - if (generation !== this._generation) { - return; + return undefined; + }))).filter(project => project !== undefined); + if (generation !== this._generation || this._store.isDisposed) { + return; + } + this._agentHost.startAgentHost(); + if (generation !== this._generation) { + return; + } + this._accountId = sessions[0].account.id; + this._accountSessionIds = new Set(sessions.map(session => session.id)); + const useLocalCredentials = this._configuration.getValue(MissionControlUseLocalCredentialsSettingId) === true; + if (useLocalCredentials) { + this._logService.warn('[Mission Control] Local credential delegation enabled: same-owner remote clients will run GitHub and Copilot work with the desktop credentials and their permissions'); + } + const remoteControlPolicySetting = this._configuration.inspect(missionControlIgnoreRemoteControlPolicy); + const ignoreRemoteControlPolicy = (remoteControlPolicySetting.userLocalValue ?? remoteControlPolicySetting.applicationValue) === true; + if (ignoreRemoteControlPolicy) { + this._logService.warn('[Mission Control] Device remote-control policy override enabled: registration will omit enterprise remote-control restrictions'); + } + let cloneRoot: string | undefined; + for (const settingId of [AgentHostDefaultCloneDirectorySettingId, gitDefaultCloneDirectorySetting]) { + const setting = this._configuration.inspect(settingId); + const value = setting.userLocalValue !== undefined ? setting.userLocalValue : setting.applicationValue; + if (value) { + cloneRoot = value; + break; } - this._accountId = sessions[0].account.id; - this._accountSessionIds = new Set(sessions.map(session => session.id)); - const useLocalCredentials = this._configuration.getValue(MissionControlUseLocalCredentialsSettingId) === true; - if (useLocalCredentials) { - this._logService.warn('[Mission Control] Local credential delegation enabled: same-owner remote clients will run GitHub and Copilot work with the desktop credentials and their permissions'); + } + const repositoryMetadataSetting = this._configuration.inspect(missionControlDisableRepositoryMetadata); + const disableRepositoryMetadata = (repositoryMetadataSetting.userLocalValue ?? repositoryMetadataSetting.applicationValue) === true; + await this._agentHost.configureMissionControl?.({ + baseUrl: 'https://api.github.com', + accountId: sessions[0].account.id, + credential: sessions[0].accessToken, + roots: [...new Set([...fileSystemRoots.map(root => root.fsPath), home.fsPath, ...projects])], + projects, + defaultDirectory: home.fsPath, + ...(cloneRoot ? { cloneRoot } : {}), + live: true, + ...(this.environmentName.get() ? { name: this.environmentName.get() } : {}), + ...(useLocalCredentials ? { useLocalCredentials: true } : {}), + ...(ignoreRemoteControlPolicy ? { ignoreRemoteControlPolicy: true } : {}), + ...(disableRepositoryMetadata ? { disableRepositoryMetadata: true } : {}), + }).catch(error => { + if (!interactive || isCancellationError(error)) { + throw error; } - const remoteControlPolicySetting = this._configuration.inspect(missionControlIgnoreRemoteControlPolicy); - const ignoreRemoteControlPolicy = (remoteControlPolicySetting.userLocalValue ?? remoteControlPolicySetting.applicationValue) === true; - if (ignoreRemoteControlPolicy) { - this._logService.warn('[Mission Control] Device remote-control policy override enabled: registration will omit enterprise remote-control restrictions'); + this._logService.warn('GitHub environment connection failed', error); + const diagnostic = getConnectionDiagnosticError(error); + if (diagnostic.code === MissionControlOwnerMismatchErrorCode) { + throw new GitHubEnvironmentSharingError(localize('missionControlSharing.ownerMismatch', "This Agent Host belongs to a different GitHub account. Restart VS Code to share it with another account."), 'ownerMismatch', { cause: error, diagnostic }); } - let cloneRoot: string | undefined; - for (const settingId of [AgentHostDefaultCloneDirectorySettingId, gitDefaultCloneDirectorySetting]) { - const setting = this._configuration.inspect(settingId); - const value = setting.userLocalValue !== undefined ? setting.userLocalValue : setting.applicationValue; - if (value) { - cloneRoot = value; + const { errorCategory } = getConnectionTelemetryError(diagnostic); + let message: string; + switch (errorCategory) { + case 'timeout': + message = localize('missionControlSharing.connectionTimeout', "The connection timed out. Please try again."); break; - } - } - const repositoryMetadataSetting = this._configuration.inspect(missionControlDisableRepositoryMetadata); - const disableRepositoryMetadata = (repositoryMetadataSetting.userLocalValue ?? repositoryMetadataSetting.applicationValue) === true; - await this._agentHost.configureMissionControl?.({ - baseUrl: 'https://api.github.com', - accountId: sessions[0].account.id, - credential: sessions[0].accessToken, - roots: [...new Set([...fileSystemRoots.map(root => root.fsPath), home.fsPath, ...projects])], - projects, - defaultDirectory: home.fsPath, - ...(cloneRoot ? { cloneRoot } : {}), - live: true, - ...(this.environmentName.get() ? { name: this.environmentName.get() } : {}), - ...(useLocalCredentials ? { useLocalCredentials: true } : {}), - ...(ignoreRemoteControlPolicy ? { ignoreRemoteControlPolicy: true } : {}), - ...(disableRepositoryMetadata ? { disableRepositoryMetadata: true } : {}), - }); - if (generation === this._generation && !this._store.isDisposed) { - this._configured = true; - this._storage.store(sharingStorageKey, true, StorageScope.APPLICATION, StorageTarget.MACHINE); - this.state.set('enabled', undefined); - } - } catch (error) { - if (generation === this._generation && !this._store.isDisposed) { - if (interactive) { - this._enabled = false; - this._storage.store(sharingStorageKey, false, StorageScope.APPLICATION, StorageTarget.MACHINE); - } - await this._withdraw().catch(withdrawalError => this._reportWithdrawalError(withdrawalError)); + case 'authentication': + message = localize('missionControlSharing.connectionAuthentication', "Sign in to GitHub again and try enabling remote connections."); + break; + case 'authorization': + message = localize('missionControlSharing.connectionAuthorization', "GitHub did not allow this connection. Check your account and organization settings."); + break; + case 'network': + case 'dns': + message = localize('missionControlSharing.connectionFailed', "Could not connect to GitHub. Please try again. See the Agent Host log for details."); + break; + default: + message = localize('missionControlSharing.configurationFailed', "Could not set up GitHub environment sharing. See the Agent Host log for details."); } - throw error; + throw new GitHubEnvironmentSharingError(message, 'connection', { cause: error, diagnostic }); + }); + if (generation === this._generation && !this._store.isDisposed) { + this._configured = true; + this._storage.store(sharingStorageKey, true, StorageScope.APPLICATION, StorageTarget.MACHINE); + this.state.set('enabled', undefined); } } } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHost.contribution.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHost.contribution.ts index 4a5d7b8dbe24..29d5f7855056 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHost.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHost.contribution.ts @@ -19,13 +19,14 @@ import { CloudSandboxTelemetryService, ICloudSandboxTelemetryService } from './c import { EditorCloudSandboxContribution } from './editorCloudSandboxContribution.js'; import { RemoteAgentHostContribution } from './remoteAgentHostChatContribution.js'; import './missionControlEnvironmentActions.js'; -import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlSharingService, MissionControlUseLocalCredentialsConfigKey, MissionControlUseLocalCredentialsSettingId } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlSharingService, IRemoteGitHubEnvironmentSharingService, MissionControlUseLocalCredentialsConfigKey, MissionControlUseLocalCredentialsSettingId } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { MissionControlEnvironmentService } from './missionControlEnvironmentService.js'; import { MissionControlSharingService } from './missionControlSharingService.js'; import { IRemoteAgentHostConnectionCustomizationService, RemoteAgentHostConnectionCustomizationService } from './remoteAgentHostConnectionCustomization.js'; import { IAgentHostAdvertisedAuthenticationResolver } from '../../../../../platform/agentHost/common/agentHostAdvertisedAuthentication.js'; import { RemoteAgentHostAuthenticationResolver } from './remoteAgentHostAuthenticationResolver.js'; import { MissionControlAvailabilityService } from './missionControlAvailabilityService.js'; +import { RemoteGitHubEnvironmentSharingService } from './remoteGitHubEnvironmentSharingService.js'; class MissionControlContribution { static readonly ID = 'workbench.contrib.missionControl'; @@ -41,6 +42,7 @@ registerSingleton(ICloudSandboxModelCatalogService, CloudSandboxModelCatalogServ registerSingleton(ICloudSandboxAgentHostService, CloudSandboxAgentHostService, InstantiationType.Delayed); registerSingleton(IMissionControlEnvironmentService, MissionControlEnvironmentService, InstantiationType.Delayed); registerSingleton(IMissionControlSharingService, MissionControlSharingService, InstantiationType.Delayed); +registerSingleton(IRemoteGitHubEnvironmentSharingService, RemoteGitHubEnvironmentSharingService, InstantiationType.Delayed); registerSingleton(IMissionControlAvailabilityService, MissionControlAvailabilityService, InstantiationType.Delayed); registerSingleton(IRemoteAgentHostConnectionCustomizationService, RemoteAgentHostConnectionCustomizationService, InstantiationType.Delayed); registerSingleton(IAgentHostAdvertisedAuthenticationResolver, RemoteAgentHostAuthenticationResolver, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.ts index ede6e6521ed3..45e9997c557b 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.ts @@ -7,7 +7,7 @@ import { DisposableStore, toDisposable } from '../../../../../base/common/lifecy import { getExpirationTime, getRemainingTimeInSeconds } from '../../../../../base/common/date.js'; import { IAgentHostAdvertisedAuthenticationResolver, type IAgentHostAdvertisedAuthentication, type IAgentHostAuthenticationSessionRemoval } from '../../../../../platform/agentHost/common/agentHostAdvertisedAuthentication.js'; import type { AuthenticateParams } from '../../../../../platform/agentHost/common/agent.js'; -import type { AgentInfo } from '../../../../../platform/agentHost/common/state/sessionState.js'; +import type { AgentInfo, RootState } from '../../../../../platform/agentHost/common/state/sessionState.js'; import type { ProtectedResourceMetadata } from '../../../../../platform/agentHost/common/state/protocol/state.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; @@ -60,7 +60,7 @@ export class RemoteAgentHostAuthenticationResolver implements IAgentHostAdvertis } })); } - return { resolve: agents => this._resolve(address, agents), dispose: () => store.dispose() }; + return { resolve: (agents, root) => this._resolve(address, agents, root), dispose: () => store.dispose() }; } takePendingSessionRemovals(address: string): readonly IAgentHostAuthenticationSessionRemoval[] { @@ -73,7 +73,7 @@ export class RemoteAgentHostAuthenticationResolver implements IAgentHostAdvertis return removals; } - private async _resolve(address: string, agents: readonly AgentInfo[]): Promise { + private async _resolve(address: string, agents: readonly AgentInfo[], root?: RootState): Promise { if (!this._environmentService.isSessionsWindow || this._customizations.get(address)?.authenticate) { return []; } @@ -97,7 +97,7 @@ export class RemoteAgentHostAuthenticationResolver implements IAgentHostAdvertis await this._extensionService.whenInstalledExtensionsRegistered(); const requests: { readonly request: AuthenticateParams; readonly expiresAt: number | undefined }[] = []; for (const resource of resources.values()) { - const request = await this._instantiationService.invokeFunction(resolveProtectedResourceAuthentication, resource, '[RemoteAgentHost]'); + const request = await this._instantiationService.invokeFunction(resolveProtectedResourceAuthentication, resource, '[RemoteAgentHost]', root); if (request) { requests.push({ request, expiresAt: getExpirationTime(request.expiresIn) }); } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostChatContribution.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostChatContribution.ts index 6a09861bb26b..8fedb7f8c294 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostChatContribution.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteAgentHostChatContribution.ts @@ -647,6 +647,7 @@ export class RemoteAgentHostContribution extends Disposable implements IWorkbenc : undefined; this._instantiationService.invokeFunction(accessor => connState.authRecovery.recover(accessor, protectedResource, { authTokenCache: connState.authTokenCache, + challengeReason: reason, logPrefix: '[RemoteAgentHost]', isCurrent: () => this._connections.get(address) === connState, renewAuthentication: renewAuthentication ? async resource => { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.ts new file mode 100644 index 000000000000..f73df1e3b0a5 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.ts @@ -0,0 +1,561 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RunOnceScheduler, Sequencer } from '../../../../../base/common/async.js'; +import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { mapsStrictEqualIgnoreOrder } from '../../../../../base/common/map.js'; +import { autorun, derived, derivedOpts, IObservable, observableSignal, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.js'; +import { IAgentConnection } from '../../../../../platform/agentHost/common/agentService.js'; +import type { IAgentHostGitHubEnvironmentStatus } from '../../../../../platform/agentHost/common/meta/agentHostGitHubEnvironmentMeta.js'; +import { GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService, IRemoteGitHubEnvironmentShare, IRemoteGitHubEnvironmentSharingService } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import type { InitializeResult } from '../../../../../platform/agentHost/common/state/protocol/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { AuthenticationSession, IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; +import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { getGitHubEnvironmentAuthentication, getGitHubEnvironmentSessions, GitHubEnvironmentAccountUnavailableError } from './gitHubEnvironmentAccount.js'; + +const sharesStorageKey = 'agentHost.remoteGitHubEnvironments.shared'; +const pendingUnregistrationsStorageKey = 'agentHost.remoteGitHubEnvironments.pendingUnregister'; +const shareableEntryTypes: ReadonlySet = new Set([RemoteAgentHostEntryType.SSH, RemoteAgentHostEntryType.WSL, RemoteAgentHostEntryType.Tunnel]); + +interface IStoredShare { + readonly accountId: string; + readonly environmentId?: string; + /** The agent host process holding the registration; without it, a missing registration was lost rather than removed by another client. */ + readonly instanceId?: string; +} + +interface IShareStatus { + readonly state: 'connecting' | 'error'; + readonly error?: string; +} + +/** This window's GitHub account, or why it is missing; `signedOut` distinguishes a removed account from a failed lookup. */ +type IAccountResult = { readonly session: AuthenticationSession } | { readonly session?: undefined; readonly error: unknown; readonly signedOut: boolean }; + +type IGitHubEnvironmentConnection = IAgentConnection & Required>; + +function isGitHubEnvironmentConnection(connection: IAgentConnection): connection is IGitHubEnvironmentConnection { + return !!connection.registerGitHubEnvironment && !!connection.unregisterGitHubEnvironment && !!connection.gitHubEnvironment; +} + +function setEquals(a: ReadonlySet, b: ReadonlySet): boolean { + return a.size === b.size && [...a].every(value => b.has(value)); +} + +function createStoredShare(accountId: string, environmentId: string | undefined, instanceId: string | undefined): IStoredShare { + return { accountId, ...(environmentId !== undefined ? { environmentId } : {}), ...(instanceId !== undefined ? { instanceId } : {}) }; +} + +/** + * Describes a connected remote's share from the registration its agent host reports, or `undefined` if it is not shared. + */ +function getHostShare(host: IAgentHostGitHubEnvironmentStatus, stored: IStoredShare | undefined, accountId: string | undefined): IRemoteGitHubEnvironmentShare | undefined { + if (host.registration) { + return host.registration.accountId === stored?.accountId || host.registration.accountId === accountId + ? { state: 'enabled', environmentId: host.registration.environmentId } + : { state: 'unavailable', unavailableReason: 'account' }; + } + if (host.registeredByHost) { + return { state: 'unavailable', unavailableReason: 'host' }; + } + // Another client stopped sharing if the registration is missing from the process that held it; otherwise it is registered again. + return stored && stored.instanceId !== host.instanceId ? { state: 'enabled', environmentId: stored.environmentId } : undefined; +} + +/** + * Registers remote agent hosts as GitHub environments with this window's + * GitHub account. A registration lives in the remote agent host process, so + * the remote stays shared while this window is disconnected; this service + * registers again with a fresh credential after each (re)connection. The + * status each agent host reports shows registrations made or removed by other + * clients, and reveals a restart that lost the registration. + */ +export class RemoteGitHubEnvironmentSharingService extends Disposable implements IRemoteGitHubEnvironmentSharingService { + declare readonly _serviceBrand: undefined; + + private readonly _stored = observableValue>(this, new Map()); + private readonly _status = observableValue>(this, new Map()); + /** This window's GitHub account, which identifies registrations made from other computers as its own. */ + private readonly _accountId = observableValue(this, undefined); + /** Whether this window resolved a GitHub account before, so that a missing account means it signed out rather than that authentication is still starting. */ + private _hadAccount = false; + private readonly _pendingUnregistrations = new Map(); + /** The handshake each address was last synchronized for; a new handshake means a restarted host. */ + private readonly _synced = new Map(); + /** Incremented when the gate or account changes, so that work started before does not mark remotes synchronized. */ + private _generation = 0; + /** Shares another window added whose registration this window's connection has not reported yet. */ + private readonly _adopted = new Set(); + private readonly _queue = new Sequencer(); + private readonly _sync = this._register(new RunOnceScheduler(() => { + void this._queue.queue(() => this._doSync()).catch(error => this._logService.error('[RemoteGitHubEnvironments] Synchronization failed', error)); + }, 0)); + private readonly _gate = observableSignal(this); + private readonly _enabled: IObservable; + private readonly _connections: IObservable>; + + readonly shareable: IObservable>; + readonly shares: IObservable>; + readonly environmentIds: IObservable>; + + constructor( + @IRemoteAgentHostService private readonly _remoteAgentHostService: IRemoteAgentHostService, + @IMissionControlEnvironmentService private readonly _environmentService: IMissionControlEnvironmentService, + @IMissionControlAvailabilityService availabilityService: IMissionControlAvailabilityService, + @IConfigurationService configurationService: IConfigurationService, + @IChatEntitlementService entitlementService: IChatEntitlementService, + @IAuthenticationService private readonly _authenticationService: IAuthenticationService, + @IDefaultAccountService private readonly _defaultAccountService: IDefaultAccountService, + @IProductService private readonly _productService: IProductService, + @IStorageService private readonly _storageService: IStorageService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + this._stored.set(this._readStored(), undefined); + this._readPendingUnregistrations(); + + this._enabled = derived(this, reader => { + this._gate.read(reader); + availabilityService.available.read(reader); + return this._environmentService.enabled; + }); + const connectionsChanged = observableSignalFromEvent(this, this._remoteAgentHostService.onDidChangeConnections); + const entriesChanged = observableSignalFromEvent(this, this._remoteAgentHostService.onDidChangeConfiguredEntries); + this._connections = derivedOpts>({ owner: this, equalsFn: mapsStrictEqualIgnoreOrder }, reader => { + connectionsChanged.read(reader); + entriesChanged.read(reader); + const result = new Map(); + for (const { address, status } of this._remoteAgentHostService.connections) { + const type = this._remoteAgentHostService.getEntryByAddress(address)?.connection.type; + const connection = this._remoteAgentHostService.getConnection(address); + if (RemoteAgentHostConnectionStatus.isConnected(status) && type !== undefined && shareableEntryTypes.has(type) + && connection && isGitHubEnvironmentConnection(connection) && connection.gitHubEnvironment.read(reader) !== undefined) { + result.set(address, connection); + } + } + return result; + }); + this.shareable = derivedOpts>({ owner: this, equalsFn: setEquals }, reader => this._enabled.read(reader) ? new Set(this._connections.read(reader).keys()) : new Set()); + this.shares = derived(this, reader => { + const stored = this._stored.read(reader); + const accountId = this._accountId.read(reader); + const result = new Map(); + for (const [address, share] of stored) { + result.set(address, { state: 'enabled', environmentId: share.environmentId }); + } + for (const [address, connection] of this._connections.read(reader)) { + const host = connection.gitHubEnvironment.read(reader); + const share = host && getHostShare(host, stored.get(address), accountId); + if (share) { + result.set(address, share); + } else if (host) { + result.delete(address); + } + } + for (const [address, status] of this._status.read(reader)) { + const environmentId = result.get(address)?.environmentId; + result.set(address, environmentId !== undefined ? { ...status, environmentId } : status); + } + return result; + }); + // Only remotes that are still configured hide their environment, so removing one elsewhere keeps the environment reachable. + this.environmentIds = derivedOpts>({ owner: this, equalsFn: setEquals }, reader => { + entriesChanged.read(reader); + const result = new Set(); + for (const [address, share] of this.shares.read(reader)) { + if (share.environmentId !== undefined && this._remoteAgentHostService.getEntryByAddress(address)) { + result.add(share.environmentId); + } + } + return result; + }); + + this._register(configurationService.onDidChangeConfiguration(e => { + if (e.affectsConfiguration(RemoteAgentHostsEnabledSettingId) || e.affectsConfiguration(GitHubEnvironmentsEnabledSettingId) || e.affectsConfiguration('chat.disableAIFeatures')) { + this._gate.trigger(undefined); + } + })); + this._register(entitlementService.onDidChangeSentiment(() => this._gate.trigger(undefined))); + let wasEnabled: boolean | undefined; + this._register(autorun(reader => { + const enabled = this._enabled.read(reader); + const connections = this._connections.read(reader); + for (const connection of connections.values()) { + connection.initializeResult.read(reader); + connection.gitHubEnvironment.read(reader); + } + // A protocol reconnect keeps the handshake, so a remote synchronizes again whenever it returns to the connected set. + for (const address of [...this._synced.keys()]) { + if (!connections.has(address)) { + this._synced.delete(address); + } + } + if (enabled !== wasEnabled) { + wasEnabled = enabled; + this._invalidate(); + } + this._sync.schedule(); + })); + this._register(this._storageService.onDidChangeValue(StorageScope.APPLICATION, sharesStorageKey, this._store)(e => { + if (e.external) { + this._reloadStored(); + } + })); + this._register(this._storageService.onDidChangeValue(StorageScope.APPLICATION, pendingUnregistrationsStorageKey, this._store)(e => { + if (e.external) { + this._readPendingUnregistrations(); + this._sync.schedule(); + } + })); + const { providerId } = getGitHubEnvironmentAuthentication(this._productService); + this._register(this._authenticationService.onDidChangeSessions(e => { + if (e.providerId === providerId) { + this._resync(); + } + })); + this._register(this._defaultAccountService.onDidChangeDefaultAccount(() => this._resync())); + } + + setShared(address: string, shared: boolean): Promise { + return this._queue.queue(() => shared ? this._share(address) : this._unshare(address)); + } + + private async _share(address: string): Promise { + if (!this._enabled.get() || !this._connections.get().has(address)) { + throw this._unavailableError(); + } + this._setStatus(address, { state: 'connecting' }); + try { + const session = await this._getSession(true); + // Signing in can take long enough for the remote or the gate to change. + const connection = this._connections.get().get(address); + if (!this._enabled.get() || !connection) { + throw this._unavailableError(); + } + const generation = this._generation; + this._accountId.set(session.account.id, undefined); + const previousAccountId = this._stored.get().get(address)?.accountId ?? this._pendingUnregistrations.get(address); + if (previousAccountId !== undefined && previousAccountId !== session.account.id) { + await connection.unregisterGitHubEnvironment(previousAccountId); + } + this._setPendingUnregistration(address, undefined); + await this._registerConnection(address, connection, session, generation, false); + } finally { + this._setStatus(address, undefined); + } + } + + private _unavailableError(): Error { + return new Error(localize('remoteGitHubEnvironment.unavailable', "Connect to this remote to share it as a GitHub environment.")); + } + + private async _unshare(address: string): Promise { + const share = this._stored.get().get(address); + this._setStatus(address, undefined); + if (share) { + this._setStored(address, undefined); + this._synced.delete(address); + await this._unregister(address, share.accountId); + return; + } + // Shared with this window's GitHub account from another computer. + const connection = this._connections.get().get(address); + const accountId = this._accountId.get(); + if (connection && accountId !== undefined && connection.gitHubEnvironment.get()?.registration?.accountId === accountId) { + await this._unregister(address, accountId); + } + } + + private _resync(): void { + this._invalidate(); + this._sync.schedule(); + } + + private _invalidate(): void { + this._generation++; + this._synced.clear(); + } + + private async _doSync(): Promise { + const generation = this._generation; + const enabled = this._enabled.get(); + const account = enabled && (this._connections.get().size || this._stored.get().size) ? await this._resolveAccount() : undefined; + if (generation !== this._generation) { + // Superseded by the synchronization scheduled with the change. + return; + } + this._accountId.set(account?.session?.account.id, undefined); + if (account?.session || account?.signedOut) { + for (const [address, share] of [...this._stored.get()]) { + if (share.accountId === account.session?.account.id) { + continue; + } + this._logService.info('[RemoteGitHubEnvironments] Stopped sharing a remote agent host because the GitHub account changed or signed out', address); + this._forget(address); + await this._unregister(address, share.accountId); + } + } + for (const [address, pendingAccountId] of [...this._pendingUnregistrations]) { + const connection = this._connections.get().get(address); + const host = connection?.gitHubEnvironment.get(); + if (!connection || !host || this._stored.get().has(address)) { + continue; + } + // A restart or another client may already have removed the registration. + if (host.registration?.accountId === pendingAccountId) { + try { + await connection.unregisterGitHubEnvironment(pendingAccountId); + } catch (error) { + this._logService.warn('[RemoteGitHubEnvironments] Failed to unregister a remote agent host', address, error); + continue; + } + } + this._setPendingUnregistration(address, undefined); + } + for (const address of [...this._stored.get().keys()]) { + if (generation !== this._generation) { + return; + } + // Earlier iterations await requests, during which other windows and connections can change. + let share = this._stored.get().get(address); + const connection = this._connections.get().get(address); + const host = connection?.gitHubEnvironment.get(); + const initializeResult = connection?.initializeResult.get(); + if (!share || !connection || !host || !initializeResult) { + continue; + } + if (host.registration) { + this._adopted.delete(address); + } + if (host.registration ? host.registration.accountId !== share.accountId : host.registeredByHost) { + this._logService.info('[RemoteGitHubEnvironments] Stopped sharing a remote agent host because another account or the host registered it', address); + this._forget(address); + continue; + } + if (!host.registration && share.instanceId === host.instanceId) { + if (this._adopted.has(address)) { + // Another window's registration may be reported after its storage change. + continue; + } + this._logService.info('[RemoteGitHubEnvironments] Stopped sharing a remote agent host because another client stopped sharing it', address); + this._forget(address); + continue; + } + if (host.registration && (host.registration.environmentId !== share.environmentId || host.instanceId !== share.instanceId)) { + share = createStoredShare(share.accountId, host.registration.environmentId, host.instanceId); + this._setStored(address, share); + } + if (this._synced.get(address) === initializeResult) { + continue; + } + this._synced.set(address, initializeResult); + if (!enabled) { + // Keep the user's choice, but withdraw the registration while GitHub environments are unavailable. + if (share.instanceId !== undefined) { + this._setStored(address, createStoredShare(share.accountId, share.environmentId, undefined)); + } + await connection.unregisterGitHubEnvironment(share.accountId).catch(error => this._logService.warn('[RemoteGitHubEnvironments] Failed to withdraw a remote agent host', address, error)); + continue; + } + if (!account?.session) { + this._logService.warn('[RemoteGitHubEnvironments] Failed to register a remote agent host', address, account?.error); + this._setStatus(address, { state: 'error', error: toErrorMessage(account?.error) }); + continue; + } + try { + await this._registerConnection(address, connection, account.session, generation, true); + this._setStatus(address, undefined); + } catch (error) { + this._logService.warn('[RemoteGitHubEnvironments] Failed to register a remote agent host', address, error); + this._setStatus(address, { state: 'error', error: toErrorMessage(error) }); + } + } + } + + /** Forgets a share that is no longer this window's to manage, without unregistering it. */ + private _forget(address: string): void { + this._setStored(address, undefined); + this._setStatus(address, undefined); + this._synced.delete(address); + } + + /** + * Registers a remote with a fresh credential. A `background` registration + * renews an existing share, which another window may stop meanwhile. + */ + private async _registerConnection(address: string, connection: IGitHubEnvironmentConnection, session: AuthenticationSession, generation: number, background: boolean): Promise { + const initializeResult = connection.initializeResult.get(); + // Marked before the request: an invalidation while it runs must leave the remote to the next synchronization. + if (initializeResult && generation === this._generation) { + this._synced.set(address, initializeResult); + } + let registration; + try { + registration = await connection.registerGitHubEnvironment(session.account.id, session.accessToken); + } catch (error) { + // The host withdraws a failed registration, which must not look like another client stopped sharing. + const share = this._stored.get().get(address); + if (share?.instanceId !== undefined) { + this._setStored(address, createStoredShare(share.accountId, share.environmentId, undefined)); + } + throw error; + } + if (background && !this._stored.get().has(address)) { + this._logService.info('[RemoteGitHubEnvironments] Withdrawing a registration that another window stopped sharing meanwhile', address); + await this._unregister(address, session.account.id); + return; + } + // The host reports its new status before it responds. + this._setStored(address, createStoredShare(session.account.id, registration.environmentId, connection.gitHubEnvironment.get()?.instanceId)); + } + + private async _unregister(address: string, accountId: string): Promise { + const connection = this._connections.get().get(address); + if (connection) { + try { + await connection.unregisterGitHubEnvironment(accountId); + return; + } catch (error) { + this._logService.warn('[RemoteGitHubEnvironments] Failed to unregister a remote agent host; retrying after the next connection', address, error); + } + } + this._setPendingUnregistration(address, accountId); + } + + private async _resolveAccount(): Promise { + try { + return { session: await this._getSession(false) }; + } catch (error) { + return { error, signedOut: this._hadAccount && error instanceof GitHubEnvironmentAccountUnavailableError }; + } + } + + private async _getSession(interactive: boolean): Promise { + const defaultAccount = await this._defaultAccountService.getDefaultAccount(); + const sessions = await getGitHubEnvironmentSessions(this._authenticationService, this._productService, defaultAccount, () => interactive && !this._store.isDisposed); + const accountIds = new Set(sessions.map(session => session.account.id)); + if (accountIds.size !== 1) { + const message = localize('remoteGitHubEnvironment.accountRequired', "Select a GitHub account for Copilot and sign in with the required permissions to share this remote as a GitHub environment."); + throw accountIds.size ? new Error(message) : new GitHubEnvironmentAccountUnavailableError(message, 'signInRequired'); + } + this._hadAccount = true; + return sessions[0]; + } + + private _setStatus(address: string, status: IShareStatus | undefined): void { + const current = this._status.get(); + if (current.get(address) === status) { + return; + } + const next = new Map(current); + if (status) { + next.set(address, status); + } else { + next.delete(address); + } + this._status.set(next, undefined); + } + + private _setStored(address: string, share: IStoredShare | undefined): void { + this._adopted.delete(address); + const next = new Map(this._stored.get()); + if (share) { + next.set(address, share); + } else if (!next.delete(address)) { + return; + } + this._stored.set(next, undefined); + this._updateRecord(sharesStorageKey, address, share); + } + + private _setPendingUnregistration(address: string, accountId: string | undefined): void { + if (accountId === undefined ? !this._pendingUnregistrations.delete(address) : this._pendingUnregistrations.get(address) === accountId) { + return; + } + if (accountId !== undefined) { + this._pendingUnregistrations.set(address, accountId); + } + this._updateRecord(pendingUnregistrationsStorageKey, address, accountId); + } + + private _readPendingUnregistrations(): void { + this._pendingUnregistrations.clear(); + for (const [address, accountId] of Object.entries(this._readRecord(pendingUnregistrationsStorageKey))) { + if (typeof accountId === 'string') { + this._pendingUnregistrations.set(address, accountId); + } + } + } + + private _readStored(): Map { + const result = new Map(); + for (const [address, value] of Object.entries(this._readRecord(sharesStorageKey))) { + if (value && typeof value === 'object' && typeof (value as IStoredShare).accountId === 'string') { + const { accountId, environmentId, instanceId } = value as IStoredShare; + result.set(address, createStoredShare(accountId, typeof environmentId === 'string' ? environmentId : undefined, typeof instanceId === 'string' ? instanceId : undefined)); + } + } + return result; + } + + /** Adopts shares changed by another window, which registers the shares it adds itself. */ + private _reloadStored(): void { + const previous = this._stored.get(); + const stored = this._readStored(); + for (const address of previous.keys()) { + if (!stored.has(address)) { + // Another window stopped sharing, which a background registration in flight must respect. + this._adopted.delete(address); + this._synced.delete(address); + this._setStatus(address, undefined); + } + } + for (const address of stored.keys()) { + if (previous.has(address)) { + continue; + } + this._adopted.add(address); + // The other window registers the share, which a disabled window must still withdraw. + const initializeResult = this._enabled.get() ? this._connections.get().get(address)?.initializeResult.get() : undefined; + if (initializeResult) { + this._synced.set(address, initializeResult); + } + } + this._stored.set(stored, undefined); + this._sync.schedule(); + } + + private _readRecord(key: string): Record { + try { + const value: unknown = JSON.parse(this._storageService.get(key, StorageScope.APPLICATION, '{}')); + return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; + } catch { + return {}; + } + } + + /** Updates one address, keeping the entries other windows wrote. */ + private _updateRecord(key: string, address: string, value: unknown): void { + const record = new Map(Object.entries(this._readRecord(key))); + if (value === undefined) { + record.delete(address); + } else { + record.set(address, value); + } + if (record.size) { + this._storageService.store(key, JSON.stringify(Object.fromEntries(record)), StorageScope.APPLICATION, StorageTarget.MACHINE); + } else { + this._storageService.remove(key, StorageScope.APPLICATION); + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/responseSelectionResolver.ts b/src/vs/workbench/contrib/chat/browser/responseSelectionResolver.ts index 6b3c152c28cc..66a88769862f 100644 --- a/src/vs/workbench/contrib/chat/browser/responseSelectionResolver.ts +++ b/src/vs/workbench/contrib/chat/browser/responseSelectionResolver.ts @@ -38,6 +38,18 @@ function isAssistantMarkdownEndpoint(node: Node, widgetDomNode: HTMLElement): bo return !excludedAncestorSelectors.some(selector => element.closest(selector)); } +function isSelectableText(text: Text): boolean { + const targetWindow = dom.getWindow(text); + for (let element = text.parentElement; element; element = element.parentElement) { + const style = targetWindow.getComputedStyle(element); + const userSelect = style.userSelect || style.webkitUserSelect; + if (userSelect !== 'auto') { + return userSelect !== 'none'; + } + } + return true; +} + interface IContributingTextEndpoint { readonly node: Text; readonly startOffset: number; @@ -122,6 +134,10 @@ function contributingTextEndpoints(range: Range, widgetDomNode?: HTMLElement): { if (firstOffset === end) { continue; } + // Native selections omit unselectable text even when their DOM range spans it. + if (!isSelectableText(text)) { + continue; + } const firstEndOffset = nextCodePointOffset(text.data, firstOffset); let trimmedEndOffset = end; let lastOffset = previousCodePointOffset(text.data, trimmedEndOffset); diff --git a/src/vs/workbench/contrib/chat/browser/responseSelectionSideChatController.ts b/src/vs/workbench/contrib/chat/browser/responseSelectionSideChatController.ts index a60604ea5f49..236b399be93d 100644 --- a/src/vs/workbench/contrib/chat/browser/responseSelectionSideChatController.ts +++ b/src/vs/workbench/contrib/chat/browser/responseSelectionSideChatController.ts @@ -126,6 +126,7 @@ export class ResponseSelectionSideChatController extends Disposable { private readonly _autoScrollHold = this._register(new MutableDisposable()); private _chatResource: URI | undefined; private _isReadOnly: IObservable = constObservable(true); + private _showOnSelection: boolean; /** Bumped on a genuine chat navigation/force-dismiss so a stale submission's completion/error handler can no-op. */ private _generation = 0; @@ -141,6 +142,7 @@ export class ResponseSelectionSideChatController extends Disposable { ) { super(); + this._showOnSelection = this._options.showOnSelection ?? true; this._selectionChangeScheduler = this._register(new dom.AnimationFrameScheduler(this._widget.domNode, () => this._applySelectionChange())); this._input = this._register(new FeedbackInputWidget({ placeholder: localize('sessions.selectionSideChat.placeholder', "Ask Question"), @@ -267,6 +269,18 @@ export class ResponseSelectionSideChatController extends Disposable { } } + setShowOnSelection(showOnSelection: boolean): void { + if (this._showOnSelection === showOnSelection) { + return; + } + this._showOnSelection = showOnSelection; + if (showOnSelection) { + this._onSelectionChange(); + } else { + this._dismiss(); + } + } + private _bindWindow(): void { const window = dom.getWindow(this._widget.domNode); if (this._boundWindow === window) { @@ -338,7 +352,7 @@ export class ResponseSelectionSideChatController extends Disposable { this._syncHighlight(); return; } - if (this._options.showOnSelection === false) { + if (!this._showOnSelection) { this._dismiss(); return; } diff --git a/src/vs/workbench/contrib/chat/browser/speechToText/dictationOnboarding.ts b/src/vs/workbench/contrib/chat/browser/speechToText/dictationOnboarding.ts index 3d3bfcbd6e55..7795ccf3c42b 100644 --- a/src/vs/workbench/contrib/chat/browser/speechToText/dictationOnboarding.ts +++ b/src/vs/workbench/contrib/chat/browser/speechToText/dictationOnboarding.ts @@ -678,7 +678,7 @@ export class DictationOnboardingBanner extends ChatInputNoticeWidget implements // else, so make them real controls: reachable by Tab and operable by // Enter or Space like any other button. The renderer owns this DOM, so a // selector is the only handle on it. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const link of description.querySelectorAll('a')) { link.tabIndex = 0; link.setAttribute('role', 'button'); diff --git a/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsConfirmationService.ts b/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsConfirmationService.ts index 680b687c564d..c41d82b7572e 100644 --- a/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsConfirmationService.ts +++ b/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsConfirmationService.ts @@ -3,11 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { Sequencer } from '../../../../../base/common/async.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Lazy } from '../../../../../base/common/lazy.js'; import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js'; import { LRUCache } from '../../../../../base/common/map.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; +import { autorun } from '../../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { localize } from '../../../../../nls.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; @@ -17,7 +19,7 @@ import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.j import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { ConfirmedReason, ToolConfirmKind } from '../../common/chatService/chatService.js'; import { isAutoApprovePolicyRestricted } from '../../common/agentHostConfigPolicy.js'; -import { ILanguageModelToolConfirmationActions, ILanguageModelToolConfirmationContribution, ILanguageModelToolConfirmationContributionQuickTreeItem, ILanguageModelToolConfirmationRef, ILanguageModelToolsConfirmationService } from '../../common/tools/languageModelToolsConfirmationService.js'; +import { ILanguageModelToolConfirmationActions, ILanguageModelToolConfirmationContribution, ILanguageModelToolConfirmationContributionQuickTreeItem, ILanguageModelToolConfirmationRef, ILanguageModelToolsConfirmationService, IToolPreApprovalStore } from '../../common/tools/languageModelToolsConfirmationService.js'; import { IToolData, ToolDataSource } from '../../common/tools/languageModelToolsService.js'; const RUN_WITHOUT_APPROVAL = localize('runWithoutApproval', "without approval"); @@ -576,7 +578,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements return results; } - manageConfirmationPreferences(tools: readonly IToolData[], options?: { defaultScope?: 'workspace' | 'profile' | 'session'; focusToolId?: string }): void { + manageConfirmationPreferences(tools: readonly IToolData[], options?: { defaultScope?: 'workspace' | 'profile' | 'session'; focusToolId?: string; preApprovalStore?: IToolPreApprovalStore }): void { interface IToolTreeItem extends IQuickTreeItem { type: 'tool' | 'server' | 'tool-pre' | 'tool-post' | 'server-pre' | 'server-post' | 'manage' | 'combination'; toolId?: string; @@ -584,8 +586,13 @@ export class LanguageModelToolsConfirmationService extends Disposable implements scope?: 'workspace' | 'profile'; combinationKey?: string; combinationArgs?: string; + manageActionIndex?: number; } + const manageActionSequencer = new Sequencer(); + const uncheckedManageActions = new Map(); + const preApprovalStore = options?.preApprovalStore; + const viewArgsButton: IQuickInputButton = { iconClass: ThemeIcon.asClassName(Codicon.info), tooltip: localize('viewCombinationArguments', "View Arguments"), @@ -603,59 +610,77 @@ export class LanguageModelToolsConfirmationService extends Disposable implements const addServerToolFromSource = (source: ToolDataSource, toolId: string, serversWithTools: Map }>) => { if (source.type === 'mcp') { trackServerTool(source.definitionId, source.serverLabel || source.label, toolId, serversWithTools); - } else if (source.type === 'extension') { + } else if (!preApprovalStore && source.type === 'extension') { trackServerTool(source.extensionId.value, source.label, toolId, serversWithTools); } }; // Determine which tools should be shown + let allTools = tools; const relevantTools = new Set(); const serversWithTools = new Map }>(); - - // Add tools that request approval - for (const tool of tools) { - if (tool.canRequestPreApproval || tool.canRequestPostApproval || this._contributions.has(tool.id)) { - relevantTools.add(tool.id); - addServerToolFromSource(tool.source, tool.id, serversWithTools); + const updateTools = (discoveredTools: readonly IToolData[]) => { + allTools = preApprovalStore ? [...new Map([...tools, ...discoveredTools].map(tool => [tool.id, tool])).values()] : tools; + relevantTools.clear(); + serversWithTools.clear(); + for (const server of preApprovalStore?.servers ?? []) { + serversWithTools.set(server.id, { label: server.label, tools: new Set() }); } - } - - // Add tools that have stored approvals (but we can't display them without metadata) - for (const id of this._preExecutionToolConfirmStore.getAllConfirmed()) { - if (!relevantTools.has(id)) { - // Only add if we have the tool data - const tool = tools.find(t => t.id === id); - if (tool) { - relevantTools.add(id); - addServerToolFromSource(tool.source, id, serversWithTools); + for (const tool of allTools) { + if (preApprovalStore + ? (tool.source.type === 'mcp' && tool.canRequestPreApproval) || this._contributions.has(tool.id) + : tool.canRequestPreApproval || tool.canRequestPostApproval || this._contributions.has(tool.id)) { + relevantTools.add(tool.id); + addServerToolFromSource(tool.source, tool.id, serversWithTools); } } - } - for (const id of this._postExecutionToolConfirmStore.getAllConfirmed()) { - if (!relevantTools.has(id)) { - // Only add if we have the tool data - const tool = tools.find(t => t.id === id); - if (tool) { - relevantTools.add(id); - addServerToolFromSource(tool.source, id, serversWithTools); + }; + updateTools(preApprovalStore?.discoveredTools?.get() ?? []); + + if (!preApprovalStore) { + // Add tools that have stored approvals (but we can't display them without metadata) + for (const id of this._preExecutionToolConfirmStore.getAllConfirmed()) { + if (!relevantTools.has(id)) { + // Only add if we have the tool data + const tool = tools.find(t => t.id === id); + if (tool) { + relevantTools.add(id); + addServerToolFromSource(tool.source, id, serversWithTools); + } + } + } + for (const id of this._postExecutionToolConfirmStore.getAllConfirmed()) { + if (!relevantTools.has(id)) { + // Only add if we have the tool data + const tool = tools.find(t => t.id === id); + if (tool) { + relevantTools.add(id); + addServerToolFromSource(tool.source, id, serversWithTools); + } } } - } - // Add tools that have combination approvals - for (const tool of tools) { - if (!relevantTools.has(tool.id) && this._hasCombinationApprovalsForTool(tool.id)) { - relevantTools.add(tool.id); - addServerToolFromSource(tool.source, tool.id, serversWithTools); + // Add tools that have combination approvals + for (const tool of tools) { + if (!relevantTools.has(tool.id) && this._hasCombinationApprovalsForTool(tool.id)) { + relevantTools.add(tool.id); + addServerToolFromSource(tool.source, tool.id, serversWithTools); + } } } - if (relevantTools.size === 0) { + if (relevantTools.size === 0 && serversWithTools.size === 0 && !preApprovalStore?.isDiscovering?.get()) { return; // Nothing to show } // Determine initial scope from options let currentScope = options?.defaultScope ?? 'workspace'; + const isServerPreApproved = (serverId: string) => preApprovalStore + ? preApprovalStore.isServerApproved(serverId) + : this._preExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); + const isToolPreApproved = (tool: IToolData) => preApprovalStore + ? preApprovalStore.isToolApproved(tool) + : this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); // Helper function to build tree items based on current scope const buildTreeItems = (): IToolTreeItem[] => { @@ -667,39 +692,41 @@ export class LanguageModelToolsConfirmationService extends Disposable implements const serverChildren: IToolTreeItem[] = []; // Add server-level controls as first children - const hasAnyPre = Array.from(serverInfo.tools).some(toolId => { - const tool = tools.find(t => t.id === toolId); + const hasAnyPre = !!preApprovalStore || Array.from(serverInfo.tools).some(toolId => { + const tool = allTools.find(t => t.id === toolId); return tool?.canRequestPreApproval; }); - const hasAnyPost = Array.from(serverInfo.tools).some(toolId => { - const tool = tools.find(t => t.id === toolId); + const hasAnyPost = !preApprovalStore && Array.from(serverInfo.tools).some(toolId => { + const tool = allTools.find(t => t.id === toolId); return tool?.canRequestPostApproval; }); - const serverPreConfirmed = this._preExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); - const serverPostConfirmed = this._postExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); + const serverPreConfirmed = isServerPreApproved(serverId); + const serverPostConfirmed = !preApprovalStore && this._postExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); // Add individual tools from this server as children for (const toolId of serverInfo.tools) { - const tool = tools.find(t => t.id === toolId); + const tool = allTools.find(t => t.id === toolId); if (!tool) { continue; } const toolChildren: IToolTreeItem[] = []; - const hasPre = !serverPreConfirmed && (tool.canRequestPreApproval || this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope)); - const hasPost = !serverPostConfirmed && (tool.canRequestPostApproval || this._postExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope)); + const hasPre = !serverPreConfirmed && (tool.canRequestPreApproval || isToolPreApproved(tool)); + const hasPost = !preApprovalStore && !serverPostConfirmed && (tool.canRequestPostApproval || this._postExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope)); // Add child items for granular control when both approval types exist if (hasPre && hasPost) { toolChildren.push({ + id: `tool-pre/${tool.id}`, type: 'tool-pre', toolId: tool.id, label: RUN_WITHOUT_APPROVAL, disabled: defaultApprovalsDisabled, - checked: this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope) + checked: isToolPreApproved(tool) }); toolChildren.push({ + id: `tool-post/${tool.id}`, type: 'tool-post', toolId: tool.id, label: CONTINUE_WITHOUT_REVIEWING_RESULTS, @@ -709,9 +736,10 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } // Add combination approval children - const combinationApprovals = this._getCombinationApprovalsForTool(tool.id, currentScope); + const combinationApprovals = preApprovalStore ? [] : this._getCombinationApprovalsForTool(tool.id, currentScope); for (const { key, label, arguments: args } of combinationApprovals) { toolChildren.push({ + id: `combination/${key}`, type: 'combination', toolId: tool.id, combinationKey: key, @@ -724,8 +752,8 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } // Tool item always has a checkbox - const preApproval = this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); - const postApproval = this._postExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); + const preApproval = isToolPreApproved(tool); + const postApproval = !preApprovalStore && this._postExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); let checked: boolean | 'mixed'; let description: string | undefined; @@ -752,6 +780,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } serverChildren.push({ + id: `tool/${tool.id}`, type: 'tool', toolId: tool.id, label: tool.displayName || tool.id, @@ -767,6 +796,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements if (hasAnyPost) { serverChildren.unshift({ + id: `server-post/${serverId}`, type: 'server-post', serverId, iconClass: ThemeIcon.asClassName(Codicon.play), @@ -777,6 +807,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } if (hasAnyPre) { serverChildren.unshift({ + id: `server-pre/${serverId}`, type: 'server-pre', serverId, iconClass: ThemeIcon.asClassName(Codicon.play), @@ -787,8 +818,8 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } // Server node has checkbox to control both pre and post - const serverHasPre = this._preExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); - const serverHasPost = this._postExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); + const serverHasPre = isServerPreApproved(serverId); + const serverHasPost = !preApprovalStore && this._postExecutionServerConfirmStore.getAutoConfirmationIn(serverId, currentScope); let serverChecked: boolean | 'mixed'; if (hasAnyPre && hasAnyPost) { serverChecked = serverHasPre && serverHasPost ? true : (!serverHasPre && !serverHasPost ? false : 'mixed'); @@ -800,48 +831,62 @@ export class LanguageModelToolsConfirmationService extends Disposable implements serverChecked = false; } - const existingItem = quickTree.itemTree.find(i => i.serverId === serverId); treeItems.push({ + id: `server/${serverId}`, type: 'server', serverId, label: serverInfo.label, disabled: defaultApprovalsDisabled, checked: serverChecked, children: serverChildren, - collapsed: existingItem ? quickTree.isCollapsed(existingItem) : true, + collapsed: true, pickable: false }); } // Add individual tool nodes (only for non-MCP/extension tools) - const sortedTools = tools.slice().sort((a, b) => a.displayName.localeCompare(b.displayName)); + const sortedTools = allTools.slice().sort((a, b) => a.displayName.localeCompare(b.displayName)); for (const tool of sortedTools) { if (!relevantTools.has(tool.id)) { continue; } // Skip tools that belong to MCP/extension servers (they're shown under server nodes) - if (tool.source.type === 'mcp' || tool.source.type === 'extension') { + if (tool.source.type === 'mcp' || (!preApprovalStore && tool.source.type === 'extension')) { continue; } const contributed = this._contributions.get(tool.id); const toolChildren: IToolTreeItem[] = []; - const manageActions = contributed?.getManageActions?.(); - if (manageActions) { - toolChildren.push(...manageActions.map(action => ({ - type: 'manage' as const, - ...action, - }))); + const manageActions: IToolTreeItem[] = (contributed?.getManageActions?.() ?? []).map(action => ({ + type: 'manage', + ...action, + id: `manage/${tool.id}/${action.id ?? action.label}`, + toolId: tool.id, + })); + for (const [id, retained] of [...uncheckedManageActions].sort((a, b) => a[1].index - b[1].index)) { + if (retained.item.toolId !== tool.id) { + continue; + } + const freshAction = manageActions.find(action => action.id === id); + if (freshAction?.checked) { + uncheckedManageActions.delete(id); + } else if (!freshAction) { + manageActions.splice(Math.min(retained.index, manageActions.length), 0, { ...retained.item, checked: false }); + } } + toolChildren.push(...manageActions.map((action, index) => ({ ...action, manageActionIndex: index }))); + if (preApprovalStore && toolChildren.length === 0) { + continue; + } let checked: boolean | 'mixed' = false; let description: string | undefined; let pickable = false; - if (contributed?.canUseDefaultApprovals !== false) { + if (!preApprovalStore && contributed?.canUseDefaultApprovals !== false) { pickable = true; const hasPre = tool.canRequestPreApproval || this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); const hasPost = tool.canRequestPostApproval || this._postExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope); @@ -849,6 +894,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements // Add child items for granular control when both approval types exist if (hasPre && hasPost) { toolChildren.push({ + id: `tool-pre/${tool.id}`, type: 'tool-pre', toolId: tool.id, label: RUN_WITHOUT_APPROVAL, @@ -856,6 +902,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements checked: this._preExecutionToolConfirmStore.getAutoConfirmationIn(tool.id, currentScope) }); toolChildren.push({ + id: `tool-post/${tool.id}`, type: 'tool-post', toolId: tool.id, label: CONTINUE_WITHOUT_REVIEWING_RESULTS, @@ -868,6 +915,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements const combinationApprovals = this._getCombinationApprovalsForTool(tool.id, currentScope); for (const { key, label, arguments: args } of combinationApprovals) { toolChildren.push({ + id: `combination/${key}`, type: 'combination', toolId: tool.id, combinationKey: key, @@ -905,6 +953,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } treeItems.push({ + id: `tool/${tool.id}`, type: 'tool', toolId: tool.id, label: tool.displayName || tool.id, @@ -912,7 +961,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements disabled: defaultApprovalsDisabled && contributed?.canUseDefaultApprovals !== false, checked, pickable, - collapsed: tools.length > 1, + collapsed: preApprovalStore ? true : allTools.length > 1, children: toolChildren.length > 0 ? toolChildren : undefined }); } @@ -926,7 +975,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements quickTree.sortByLabel = false; // Only show toggle if not in session scope - if (currentScope !== 'session') { + if (!preApprovalStore && currentScope !== 'session') { const scopeButton: IQuickInputButtonWithToggle = { iconClass: ThemeIcon.asClassName(Codicon.folder), tooltip: localize('workspaceScope', "Configure for this workspace only"), @@ -944,7 +993,9 @@ export class LanguageModelToolsConfirmationService extends Disposable implements } const updatePlaceholder = () => { - if (currentScope === 'session') { + if (preApprovalStore) { + quickTree.placeholder = preApprovalStore.placeholder; + } else if (currentScope === 'session') { quickTree.placeholder = localize('configureSessionToolApprovals', "Configure session tool approvals"); } else { quickTree.placeholder = currentScope === 'workspace' @@ -955,6 +1006,17 @@ export class LanguageModelToolsConfirmationService extends Disposable implements updatePlaceholder(); quickTree.setItemTree(buildTreeItems()); + if (preApprovalStore) { + quickTree.busy = preApprovalStore.isDiscovering?.get() ?? false; + } + + // Serialize contributed edits, including their settings reads, before rebuilding. + const runManageAction = (action: () => void | Promise) => manageActionSequencer.queue(async () => { + await action(); + if (!disposables.isDisposed) { + quickTree.setItemTree(buildTreeItems()); + } + }); disposables.add(quickTree.onDidChangeCheckboxState(item => { if (isAutoApprovePolicyRestricted(this._configurationService) && item.type !== 'manage') { @@ -962,6 +1024,19 @@ export class LanguageModelToolsConfirmationService extends Disposable implements return; } + if (preApprovalStore && item.type !== 'manage') { + if ((item.type === 'server' || item.type === 'server-pre') && item.serverId) { + preApprovalStore.setServerApproved(item.serverId, !!item.checked); + } else if ((item.type === 'tool' || item.type === 'tool-pre') && item.toolId) { + const tool = allTools.find(t => t.id === item.toolId); + if (tool?.source.type === 'mcp') { + preApprovalStore.setToolApproved(tool, !!item.checked); + } + } + quickTree.setItemTree(buildTreeItems()); + return; + } + const newState = item.checked ? currentScope : 'never'; if (item.type === 'server' && item.serverId) { @@ -972,7 +1047,7 @@ export class LanguageModelToolsConfirmationService extends Disposable implements this._postExecutionServerConfirmStore.setAutoConfirmation(item.serverId, newState); } } else if (item.type === 'tool' && item.toolId) { - const tool = tools.find(t => t.id === item.toolId); + const tool = allTools.find(t => t.id === item.toolId); if (tool?.canRequestPostApproval || newState === 'never') { this._postExecutionToolConfirmStore.setAutoConfirmation(item.toolId, newState); } @@ -999,7 +1074,11 @@ export class LanguageModelToolsConfirmationService extends Disposable implements this._postExecutionServerConfirmStore.setAutoConfirmation(item.serverId, newState); quickTree.setItemTree(buildTreeItems()); } else if (item.type === 'manage') { - (item as ILanguageModelToolConfirmationContributionQuickTreeItem).onDidChangeChecked?.(!!item.checked); + const checked = !!item.checked; + if (!checked && item.id && item.manageActionIndex !== undefined) { + uncheckedManageActions.set(item.id, { item, index: item.manageActionIndex }); + } + void runManageAction(() => (item as ILanguageModelToolConfirmationContributionQuickTreeItem).onDidChangeChecked?.(checked)); } else if (item.type === 'combination' && item.combinationKey) { this._combinationConfirmStore.setAutoConfirmation(item.combinationKey, newState, item.label, item.combinationArgs); quickTree.setItemTree(buildTreeItems()); @@ -1008,7 +1087,10 @@ export class LanguageModelToolsConfirmationService extends Disposable implements disposables.add(quickTree.onDidTriggerItemButton(i => { if (i.item.type === 'manage') { - (i.item as ILanguageModelToolConfirmationContributionQuickTreeItem).onDidTriggerItemButton?.(i.button); + if (i.item.id) { + uncheckedManageActions.delete(i.item.id); + } + void runManageAction(() => (i.item as ILanguageModelToolConfirmationContributionQuickTreeItem).onDidTriggerItemButton?.(i.button)); } else if (i.item.type === 'combination' && i.button === viewArgsButton && i.item.combinationArgs) { this._dialogService.prompt({ message: localize('combinationArguments', "Arguments"), @@ -1023,11 +1105,13 @@ export class LanguageModelToolsConfirmationService extends Disposable implements })); disposables.add(quickTree.onDidAccept(async () => { - const manageItem = quickTree.activeItems.find(i => i.type === 'manage'); + const manageItem = quickTree.activeItems.find(i => i.type === 'manage') as ILanguageModelToolConfirmationContributionQuickTreeItem | undefined; if (manageItem) { quickTree.hide(); - await (manageItem as ILanguageModelToolConfirmationContributionQuickTreeItem).onDidOpen?.(); - this.manageConfirmationPreferences(tools, options); + await manageItem.onDidOpen?.(); + if (!manageItem.closesPicker) { + this.manageConfirmationPreferences(tools, options); + } } else { quickTree.hide(); } @@ -1037,23 +1121,32 @@ export class LanguageModelToolsConfirmationService extends Disposable implements disposables.dispose(); })); - quickTree.show(); - - // If a focus tool was specified, expand its parent and set it as active. - // Must happen after show() since the tree data is applied via autorun on visibility. - if (options?.focusToolId) { - const focusToolId = options.focusToolId; + let focusToolId = options?.focusToolId; + const focusTool = () => { + if (!focusToolId) { + return; + } for (const serverItem of quickTree.itemTree) { - const serverItemTyped = serverItem as IToolTreeItem; - if (serverItemTyped.children) { - const toolItem = (serverItemTyped.children as IToolTreeItem[]).find(c => c.type === 'tool' && c.toolId === focusToolId); - if (toolItem) { - quickTree.expand(serverItem); - quickTree.reveal(toolItem); - break; - } + const toolItem = (serverItem.children as readonly IToolTreeItem[] | undefined)?.find(child => child.type === 'tool' && child.toolId === focusToolId); + if (toolItem) { + quickTree.expand(serverItem); + quickTree.reveal(toolItem); + focusToolId = undefined; + break; } } + }; + + quickTree.show(); + if (preApprovalStore) { + disposables.add(autorun(reader => { + updateTools(preApprovalStore.discoveredTools?.read(reader) ?? []); + quickTree.busy = preApprovalStore.isDiscovering?.read(reader) ?? false; + quickTree.setItemTree(buildTreeItems()); + focusTool(); + })); + } else { + focusTool(); } } diff --git a/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsService.ts b/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsService.ts index 848847957455..c6a45ac17db2 100644 --- a/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsService.ts +++ b/src/vs/workbench/contrib/chat/browser/tools/languageModelToolsService.ts @@ -17,7 +17,7 @@ import { createMarkdownCommandLink, MarkdownString } from '../../../../../base/c import { Iterable } from '../../../../../base/common/iterator.js'; import { combinedDisposable, Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { getMediaMime } from '../../../../../base/common/mime.js'; -import { derived, derivedOpts, IObservable, IReader, observableFromEventOpts, ObservableSet, observableSignal, transaction } from '../../../../../base/common/observable.js'; +import { derived, derivedOpts, IObservable, IReader, observableFromEvent, observableFromEventOpts, ObservableSet, observableSignal, transaction } from '../../../../../base/common/observable.js'; import { isEqual } from '../../../../../base/common/resources.js'; import Severity from '../../../../../base/common/severity.js'; import { StopWatch } from '../../../../../base/common/stopwatch.js'; @@ -34,6 +34,7 @@ import type { LanguageModelToolApprovalClassification, LanguageModelToolInvokedC import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import * as JSONContributionRegistry from '../../../../../platform/jsonschemas/common/jsonContributionRegistry.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; +import { mcpAccessConfig, McpAccessValue } from '../../../../../platform/mcp/common/mcpManagement.js'; import { observableConfigValue } from '../../../../../platform/observable/common/platformObservableUtils.js'; import { Registry } from '../../../../../platform/registry/common/platform.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; @@ -140,12 +141,13 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo private readonly _callsByRequestId = new Map(); /** Pending tool calls in the streaming phase, keyed by toolCallId */ - private readonly _pendingToolCalls = new Map(); + private readonly _pendingToolCalls = new Map(); /** Deduplicates _checkGlobalAutoApprove calls within this window */ private _pendingGlobalAutoApproveCheck: Promise | undefined; private readonly _isAgentModeEnabled: IObservable; + private readonly _isMcpDisabledByPolicy: IObservable; constructor( @IInstantiationService private readonly _instantiationService: IInstantiationService, @@ -168,6 +170,9 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo super(); this._isAgentModeEnabled = observableConfigValue(ChatConfiguration.AgentEnabled, true, this._configurationService); + this._isMcpDisabledByPolicy = observableFromEvent(this, + Event.filter(this._configurationService.onDidChangeConfiguration, e => e.affectsConfiguration(mcpAccessConfig)), + () => this._configurationService.inspect(mcpAccessConfig).policyValue === McpAccessValue.None); this._register(this._contextKeyService.onDidChangeContext(e => { if (e.affectsSome(this._toolContextKeys)) { @@ -177,7 +182,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo })); this._register(this._configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(ChatConfiguration.ExtensionToolsEnabled) || e.affectsConfiguration(ChatConfiguration.AgentEnabled) || e.affectsConfiguration(CopilotChatSettingId.Gpt55ReadFileToolEnabled)) { + if (e.affectsConfiguration(ChatConfiguration.ExtensionToolsEnabled) || e.affectsConfiguration(ChatConfiguration.AgentEnabled) || e.affectsConfiguration(CopilotChatSettingId.Gpt55ReadFileToolEnabled) || e.affectsConfiguration(mcpAccessConfig)) { this._onDidChangeToolsScheduler.schedule(); } })); @@ -254,12 +259,18 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo return true; } - /** - * Returns if the given tool or toolset is permitted in the current context. - * When agent mode is enabled, all tools are permitted (no restriction) - * When agent mode is disabled only a subset of read-only tools are permitted in agentic-loop contexts. - */ + private isAllowedByPolicy(toolOrToolSet: IToolData | IToolSet, reader?: IReader): boolean { + return toolOrToolSet.source.type !== 'extension' || !(reader + ? this._isMcpDisabledByPolicy.read(reader) + : this._configurationService.inspect(mcpAccessConfig).policyValue === McpAccessValue.None); + } + + /** Applies enterprise policy and restricts agentic-loop tools to a read-only subset when agent mode is disabled. */ private isPermitted(toolOrToolSet: IToolData | ToolSet, reader?: IReader): boolean { + if (!this.isAllowedByPolicy(toolOrToolSet, reader)) { + return false; + } + const agentModeEnabled = this._isAgentModeEnabled.read(reader); if (agentModeEnabled !== false) { return true; @@ -491,15 +502,30 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo return undefined; } - private _validateToolSession(toolData: IToolData | undefined, toolSessionResource: URI | undefined): void { + private _validateToolAccess(toolData: IToolData | undefined, toolSessionResource: URI | undefined, dto?: IToolInvocation): void { if (toolData?.sessionResource && !isEqual(toolData.sessionResource, toolSessionResource)) { throw new Error(localize('toolSessionMismatch', "Tool \"{0}\" is not available in this session.", toolData.id)); } + + if (toolData && !this.isAllowedByPolicy(toolData)) { + const reason = localize('extensionToolDisabledByPolicy', "Tool \"{0}\" is disabled because your organization has disabled MCP and third-party extension tools.", toolData.id); + if (dto) { + const key = this._pendingToolCalls.has(dto.callId) ? dto.callId : dto.chatStreamToolCallId; + const pending = key !== undefined ? this._pendingToolCalls.get(key) : undefined; + if (key !== undefined && pending && pending.invocation.toolId === dto.toolId + && isEqual(pending.toolSessionResource, dto.toolSessionResource) + && isEqual(pending.sessionResource, dto.context?.sessionResource)) { + this._pendingToolCalls.delete(key); + pending.invocation.cancelFromStreaming({ type: ToolConfirmKind.Denied }, reason); + } + } + throw new Error(reason); + } } async invokeTool(dto: IToolInvocation, countTokens: CountTokensCallback, token: CancellationToken): Promise { const toolData = this._tools.get(dto.toolId)?.data; - this._validateToolSession(toolData, dto.toolSessionResource); + this._validateToolAccess(toolData, dto.toolSessionResource, dto); this._logService.trace(`[LanguageModelToolsService#invokeTool] Invoking tool ${dto.toolId} with parameters ${JSON.stringify(dto.parameters)}`); let model: IChatModel | undefined; let request: IChatRequestModel | undefined; @@ -576,7 +602,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo let tool = this._tools.get(dto.toolId); try { - this._validateToolSession(tool?.data, dto.toolSessionResource); + this._validateToolAccess(tool?.data, dto.toolSessionResource, dto); // Fire the event to notify listeners that a tool is being invoked this._onDidInvokeTool.fire({ @@ -591,14 +617,14 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo if (!tool) { throw new Error(`Tool ${dto.toolId} was not contributed`); } - this._validateToolSession(tool.data, dto.toolSessionResource); + this._validateToolAccess(tool.data, dto.toolSessionResource, dto); if (!tool.impl) { await this._extensionService.activateByEvent(`onLanguageModelTool:${dto.toolId}`); // Extension should activate and register the tool implementation tool = this._tools.get(dto.toolId); - this._validateToolSession(tool?.data, dto.toolSessionResource); + this._validateToolAccess(tool?.data, dto.toolSessionResource, dto); if (!tool?.impl) { throw new Error(`Tool ${dto.toolId} does not have an implementation registered.`); } @@ -752,7 +778,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo if (!currentTool) { throw new Error(`Tool ${dto.toolId} was not contributed`); } - this._validateToolSession(currentTool.data, dto.toolSessionResource); + this._validateToolAccess(currentTool.data, dto.toolSessionResource, dto); if (!currentTool.impl) { throw new Error(`Tool ${dto.toolId} does not have an implementation registered.`); } @@ -1138,7 +1164,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo if (!toolEntry) { return undefined; } - this._validateToolSession(toolEntry.data, options.toolSessionResource); + this._validateToolAccess(toolEntry.data, options.toolSessionResource); // Don't create a streaming invocation for tools that don't implement handleToolStream. // These tools will have their invocation created directly in invokeToolInternal. @@ -1157,7 +1183,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo }); // Track the pending tool call - this._pendingToolCalls.set(options.toolCallId, { invocation, toolSessionResource: options.toolSessionResource }); + this._pendingToolCalls.set(options.toolCallId, { invocation, toolSessionResource: options.toolSessionResource, sessionResource: options.sessionResource }); // If we have a session, append the invocation to the chat as progress if (options.sessionResource) { @@ -1206,7 +1232,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo const { invocation, toolSessionResource } = pendingToolCall; const toolEntry = this._tools.get(invocation.toolId); - this._validateToolSession(toolEntry?.data, toolSessionResource); + this._validateToolAccess(toolEntry?.data, toolSessionResource); // Update the partial input on the invocation invocation.updatePartialInput(partialInput); @@ -1799,6 +1825,10 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo referenceName = this.getSpecedToolSetName(referenceName); const result = new class extends ToolSet implements IDisposable { + override getTools(reader?: IReader): Iterable { + return Iterable.filter(super.getTools(reader), tool => that.isAllowedByPolicy(tool, reader)); + } + dispose(): void { if (that._toolSets.has(result)) { this._tools.clear(); @@ -1824,7 +1854,7 @@ export class LanguageModelToolsService extends Disposable implements ILanguageMo for (const toolSet of this.toolSets.read(reader)) { if (toolSet.source.type !== 'user') { result.push([toolSet, getToolSetFullReferenceName(toolSet)]); - for (const tool of toolSet.getTools()) { + for (const tool of toolSet.getTools(reader)) { result.push([tool, getToolFullReferenceName(tool, toolSet)]); coveredByToolSets.add(tool); } diff --git a/src/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewWelcomeController.ts b/src/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewWelcomeController.ts index 752a93fd0299..334c6d817ff7 100644 --- a/src/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewWelcomeController.ts +++ b/src/vs/workbench/contrib/chat/browser/viewsWelcome/chatViewWelcomeController.ts @@ -229,7 +229,7 @@ export class ChatViewWelcomePart extends Disposable { private renderMarkdownMessageContent(content: IMarkdownString, options: IChatViewWelcomeRenderOptions | undefined): IRenderedMarkdown { const messageResult = this._register(this.markdownRendererService.render(content)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const firstLink = options?.firstLinkToButton ? messageResult.element.querySelector('a') : undefined; if (firstLink) { const target = firstLink.getAttribute('data-href'); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatClipboard.ts b/src/vs/workbench/contrib/chat/browser/widget/chatClipboard.ts index bee37569a529..ecb1938cf629 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatClipboard.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatClipboard.ts @@ -37,7 +37,7 @@ export function cloneVisibleSelection(range: Range, root: Node): DocumentFragmen try { const fragment = cloneWithAncestors(range, root); - // eslint-disable-next-line no-restricted-syntax -- operating on a detached fragment + // eslint-disable-next-line eslint-js/no-restricted-syntax -- operating on a detached fragment for (const element of Array.from(fragment.querySelectorAll(`[${hiddenElementAttribute}], ${controlSelector}`))) { element.remove(); } @@ -132,7 +132,7 @@ function replaceWithLabel(element: Element, label: string): void { export function sanitizeChatClipboardFragment(fragment: DocumentFragment): boolean { let changed = false; - // eslint-disable-next-line no-restricted-syntax -- operating on a detached fragment + // eslint-disable-next-line eslint-js/no-restricted-syntax -- operating on a detached fragment for (const anchor of Array.from(fragment.querySelectorAll('a'))) { const target = getLinkTarget(anchor); if (isPortableLinkTarget(target)) { @@ -145,7 +145,7 @@ export function sanitizeChatClipboardFragment(fragment: DocumentFragment): boole changed = true; } - // eslint-disable-next-line no-restricted-syntax -- operating on a detached fragment + // eslint-disable-next-line eslint-js/no-restricted-syntax -- operating on a detached fragment for (const image of Array.from(fragment.querySelectorAll('img'))) { if (!isPortableLinkTarget(image.getAttribute('src') ?? '')) { replaceWithLabel(image, image.getAttribute('alt') ?? ''); @@ -153,7 +153,7 @@ export function sanitizeChatClipboardFragment(fragment: DocumentFragment): boole } } - // eslint-disable-next-line no-restricted-syntax -- operating on a detached fragment + // eslint-disable-next-line eslint-js/no-restricted-syntax -- operating on a detached fragment for (const element of Array.from(fragment.querySelectorAll('[data-href]'))) { element.removeAttribute('data-href'); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts index a73c287c4167..6cd3f9ccab5d 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentMarkdownRenderer.ts @@ -224,7 +224,7 @@ export class ChatContentMarkdownRenderer implements IMarkdownRenderer { private attachCustomHover(result: IRenderedMarkdown): IRenderedMarkdown { const store = new DisposableStore(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax result.element.querySelectorAll('a').forEach((element) => { if (element.title) { let title = element.title; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAttachmentsContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAttachmentsContentPart.ts index bf93c36e2140..4a3321ab5061 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAttachmentsContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAttachmentsContentPart.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import * as dom from '../../../../../../base/browser/dom.js'; +import { IHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate.js'; import { Emitter } from '../../../../../../base/common/event.js'; import { Disposable, DisposableStore } from '../../../../../../base/common/lifecycle.js'; import { ResourceMap } from '../../../../../../base/common/map.js'; @@ -34,6 +35,8 @@ export interface IChatAttachmentsContentPartOptions { readonly imageReveal?: IChatImageRevealOrigin; readonly imageDimensions?: ResourceMap; readonly imageBase64Data?: ReadonlyMap; + /** Shared by related pills that preview a GitHub issue or pull request, so that moving between them shows the next preview right away. */ + readonly hoverDelegate?: IHoverDelegate; } export class ChatAttachmentsContentPart extends Disposable { @@ -54,6 +57,7 @@ export class ChatAttachmentsContentPart extends Disposable { private readonly imageReveal: IChatImageRevealOrigin | undefined; private readonly imageDimensions: ResourceMap | undefined; private readonly imageBase64Data: ReadonlyMap | undefined; + private readonly hoverDelegate: IHoverDelegate | undefined; public readonly domNode: HTMLElement | undefined; public contextMenuHandler?: (attachment: IChatRequestVariableEntry, event: MouseEvent) => void; @@ -76,6 +80,7 @@ export class ChatAttachmentsContentPart extends Disposable { this.imageReveal = options.imageReveal; this.imageDimensions = options.imageDimensions; this.imageBase64Data = options.imageBase64Data; + this.hoverDelegate = options.hoverDelegate; this.domNode = options.domNode ?? dom.$('.chat-attached-context'); this._contextResourceLabels = this._register(this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this._onDidChangeVisibility.event })); @@ -280,8 +285,9 @@ export class ChatAttachmentsContentPart extends Disposable { // skip workspace attachments return; } else { + // These attachments are shown rather than edited, so a GitHub issue or pull request previews its details and opens when activated. widget = this.chatAttachmentWidgetRegistry.createWidget(attachment, { shouldFocusClearButton: false, supportsDeletion: false }, container, this.sessionResource) - ?? this.instantiationService.createInstance(DefaultChatAttachmentWidget, resource, range, attachment, correspondingContentReference, undefined, { shouldFocusClearButton: false, supportsDeletion: false }, container, this._contextResourceLabels); + ?? this.instantiationService.createInstance(DefaultChatAttachmentWidget, resource, range, attachment, correspondingContentReference, undefined, { shouldFocusClearButton: false, supportsDeletion: false, supportsReferencePreview: true, hoverDelegate: this.hoverDelegate }, container, this._contextResourceLabels); } let ariaLabel: string | null = null; @@ -293,7 +299,7 @@ export class ChatAttachmentsContentPart extends Disposable { if (isAttachmentPartialOrOmitted) { ariaLabel = `${ariaLabel}${description ? ` ${description}` : ''}`; for (const selector of ['.monaco-icon-suffix-container', '.monaco-icon-name-container']) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = widget.label?.element.querySelector(selector); if (element) { element.classList.add('warning'); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAutoModeResolutionContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAutoModeResolutionContentPart.ts index 0338c016277e..59381de86c97 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAutoModeResolutionContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatAutoModeResolutionContentPart.ts @@ -79,6 +79,7 @@ export class ChatAutoModeResolutionContentPart extends ChatThinkingStyleContentP && other.resolved?.reason === this.content.resolved?.reason && other.preference === this.content.preference && other.effort === this.content.effort + && other.contextSize === this.content.contextSize && other.switchedFrom === this.content.switchedFrom; } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConversationReasoningPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConversationReasoningPart.ts new file mode 100644 index 000000000000..4372dd40f026 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConversationReasoningPart.ts @@ -0,0 +1,62 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $ } from '../../../../../../base/browser/dom.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { IChatRendererContent } from '../../../common/model/chatViewModel.js'; +import { ChatTreeItem } from '../../chat.js'; +import { ChatCollapsibleContentPart } from './chatCollapsibleContentPart.js'; +import { IChatContentPartRenderContext } from './chatContentParts.js'; + +/** + * A reasoning run listed among the tool calls of a Conversation section. It names how long + * the run thought and shows its text once expanded. + */ +export class ChatConversationReasoningPart extends ChatCollapsibleContentPart { + + /** Holds the run's reasoning text, whether or not the row has been expanded yet. */ + readonly content = $('.chat-used-context-list.chat-thinking-reasoning-content'); + + constructor( + private rowTitle: string, + context: IChatContentPartRenderContext, + @IHoverService hoverService: IHoverService, + @IConfigurationService configurationService: IConfigurationService, + @ITelemetryService telemetryService: ITelemetryService, + ) { + super(rowTitle, context, undefined, hoverService, configurationService, telemetryService); + this.domNode.classList.add('chat-thinking-reasoning'); + } + + protected override get collapsibleKind(): string { + return 'reasoning'; + } + + protected override get collapsibleInThinking(): boolean { + return true; + } + + protected override initContent(): HTMLElement { + return this.content; + } + + updateTitle(title: string): void { + if (title !== this.rowTitle) { + this.rowTitle = title; + this.setTitle(title); + } + } + + /** Opens the row, which attaches and shows its reasoning text. */ + expand(): void { + this.setExpanded(true); + } + + hasSameContent(_other: IChatRendererContent, _followingContent: IChatRendererContent[], _element: ChatTreeItem): boolean { + return false; + } +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewDocument.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewDocument.ts new file mode 100644 index 000000000000..11c0d6960ae1 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewDocument.ts @@ -0,0 +1,163 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../../base/browser/dom.js'; +import { basicMarkupHtmlTags, safeSetInnerHtml } from '../../../../../../base/browser/domSanitize.js'; +import { escapeDoubleQuotes } from '../../../../../../base/common/htmlContent.js'; +import { Schemas } from '../../../../../../base/common/network.js'; +import { escape } from '../../../../../../base/common/strings.js'; +import { localize } from '../../../../../../nls.js'; +import { WebviewInitInfo, WebviewStyles } from '../../../../webview/browser/webview.js'; + +const htmlPreviewIdPrefix = 'vscode-html-preview-'; + +function sanitizeFragmentLink(node: Element, value: string, namespaceId: (id: string) => string): string | false { + if (node.namespaceURI !== 'http://www.w3.org/1999/xhtml' || node.localName !== 'a' || !value.startsWith('#')) { + return false; + } + try { + const id = decodeURIComponent(value.slice(1)); + return id ? '#' + encodeURIComponent(namespaceId(id)) : '#'; + } catch { + return false; + } +} + +function namespaceCssReferences(css: string, namespaceId: (id: string) => string): string { + // Consume comments and quoted literals without interpreting their text as ID selectors. + const tokens = /\/\*[\s\S]*?(?:\*\/|$)|(?url\(\s*["']?#)(?(?:\\(?:[\da-f]{1,6}\s?|[^\r\n])|[\w%\u0080-\uFFFF-])+)(?["']?\s*\))|(?\[\s*href\s*=\s*["']?#)(?[\w%\u0080-\uFFFF-]+)(?["']?\s*(?:[is]\s*)?\])|(?\[\s*id\s*=\s*["']?)(?[\w\u0080-\uFFFF-]+)(?["']?\s*(?:[is]\s*)?\])|"(?:\\[\s\S]|[^"\\])*"?|'(?:\\[\s\S]|[^'\\])*'?|#(?(?:\\(?:[\da-f]{1,6}\s?|[^\r\n])|[\w\u0080-\uFFFF-])+)/gi; + let result = ''; + let offset = 0; + for (const match of css.matchAll(tokens)) { + const groups = match.groups!; + const id = groups.id ?? groups.urlId ?? groups.hrefId ?? groups.attributeId; + if (!id) { + continue; + } + let decodedId = id.replace(/\\(?[\da-f]{1,6})\s?|\\(?.)/gi, (escaped: string, hex: string | undefined, character: string | undefined) => { + const codePoint = hex ? parseInt(hex, 16) : undefined; + return codePoint !== undefined ? (codePoint > 0 && codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : '\uFFFD') : character ?? escaped; + }); + if (groups.urlId || groups.hrefId) { + try { + decodedId = decodeURIComponent(decodedId); + } catch { + continue; + } + } + const namespacedId = namespaceId(decodedId); + if (namespacedId !== decodedId) { + const prefix = groups.urlPrefix ?? groups.hrefPrefix ?? groups.attributePrefix ?? '#'; + const suffix = groups.urlSuffix ?? groups.hrefSuffix ?? groups.attributeSuffix ?? ''; + const rewritten = prefix + (groups.hrefId ? encodeURIComponent(namespacedId) : htmlPreviewIdPrefix + id) + suffix; + const replacement = /i\s*\]$/i.test(suffix) ? `:is(${match[0]},${rewritten})` : rewritten; + result += css.slice(offset, match.index) + replacement; + offset = match.index + match[0].length; + } + } + return result + css.slice(offset); +} + +/** Builds script-free, offline previews, with a transparent, unpadded surface when inline. */ +export function createHtmlPreviewDocument(html: string, theme?: { readonly styles: Readonly; readonly activeTheme: string }, presentation: 'document' | 'inline' = 'document'): string { + const form = dom.$('form'); + const namespaceId = (id: string) => id.startsWith(htmlPreviewIdPrefix) || Reflect.has(form.ownerDocument, id) || Reflect.has(form, id) ? htmlPreviewIdPrefix + id : id; + const contentRoot = dom.$('div'); + safeSetInnerHtml(contentRoot, `${html}`, { + allowedTags: { + override: [ + ...basicMarkupHtmlTags.filter(tag => tag !== 'source' && tag !== 'video'), + 'style', 'section', 'article', 'header', 'footer', 'main', 'nav', 'aside', 'address', + 'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', + 'defs', 'marker', 'linearGradient', 'radialGradient', 'stop', 'title', 'desc', + ], + }, + allowedAttributes: { + override: [ + 'class', 'title', 'lang', 'dir', 'role', 'alt', 'width', 'height', 'aria-label', 'aria-hidden', + { attributeName: 'id', shouldKeep: (_node, attribute) => namespaceId(attribute.attrValue) }, + { attributeName: 'style', shouldKeep: (_node, attribute) => namespaceCssReferences(attribute.attrValue, namespaceId) }, + ...['aria-labelledby', 'aria-describedby'].map(attributeName => ({ + attributeName, + shouldKeep: (_node: Element, attribute: { readonly attrValue: string }) => attribute.attrValue.replace(/\S+/g, namespaceId), + })), + { + attributeName: 'src', + shouldKeep: (node, attribute) => node.nodeName.toLowerCase() === 'img' && /^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(attribute.attrValue), + }, + { + attributeName: 'href', + shouldKeep: (node, attribute) => sanitizeFragmentLink(node, attribute.attrValue, namespaceId), + }, + 'open', 'colspan', 'rowspan', 'scope', 'start', 'reversed', + 'viewBox', 'preserveAspectRatio', 'd', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', + 'points', 'transform', 'fill-opacity', 'fill-rule', 'stroke-width', 'stroke-opacity', + 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'opacity', 'text-anchor', 'dominant-baseline', + 'dx', 'dy', 'offset', 'stop-color', 'stop-opacity', 'gradientUnits', 'gradientTransform', + 'markerWidth', 'markerHeight', 'refX', 'refY', 'orient', + ...['fill', 'stroke', 'marker-start', 'marker-mid', 'marker-end'].map(attributeName => ({ + attributeName, + shouldKeep: (_node: Element, attribute: { readonly attrValue: string }) => namespaceCssReferences(attribute.attrValue, namespaceId), + })), + ], + }, + allowedLinkProtocols: { override: [] }, + allowedMediaProtocols: { override: [Schemas.data] }, + }); + const walker = contentRoot.ownerDocument.createTreeWalker(contentRoot, NodeFilter.SHOW_ELEMENT); + for (let element = walker.nextNode(); element; element = walker.nextNode()) { + if (element.nodeName.toLowerCase() === 'style') { + element.textContent = namespaceCssReferences(element.textContent ?? '', namespaceId); + } + } + const content = contentRoot.innerHTML; + + const styles = ` + body { display: flow-root; box-sizing: border-box; margin: 0; padding: ${presentation === 'inline' ? '0' : '12px'}; overflow-wrap: anywhere; color: var(--vscode-${presentation === 'inline' ? 'foreground' : 'editor-foreground'}, CanvasText); background: ${presentation === 'inline' ? 'transparent' : 'var(--vscode-editor-background, Canvas)'}; font-family: var(--vscode-font-family, system-ui); font-size: var(--vscode-font-size, 13px); ${presentation === 'inline' ? 'line-height: 1.5;' : ''} } + img, svg { max-width: 100%; } + a[href] { color: var(--vscode-textLink-foreground, LinkText); } + :focus-visible { outline: 1px solid var(--vscode-focusBorder, Highlight); outline-offset: 2px; } + `; + const documentStyle = dom.$('div').style; + if (theme) { + const variables = new Set([...`${styles}${content}`.matchAll(/var\(\s*--(?[\w-]+)/g)].map(match => match.groups!.name)); + for (const [name, value] of Object.entries(theme.styles)) { + if (variables.has(name)) { + documentStyle.setProperty(`--${name}`, String(value)); + } + } + } + + return ` + + + + + + ${escape(localize('chat.htmlPreview.documentTitle', "HTML Preview"))} + + +${content} +`; +} + +export function getHtmlPreviewWebviewOptions(title: string): WebviewInitInfo { + return { + title, + providedViewType: 'vscode.chat.htmlPreview', + options: { + disableServiceWorker: true, + includeHorizontalScrollbarInContentHeight: true, + tryRestoreScrollPosition: false, + }, + contentOptions: { + allowScripts: false, + allowForms: false, + enableCommandUris: false, + localResourceRoots: [], + }, + extension: undefined, + }; +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewEditorInput.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewEditorInput.ts new file mode 100644 index 000000000000..6c0d6f0385c2 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewEditorInput.ts @@ -0,0 +1,85 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { convertHtmlToMarkdown } from '../../../../../../base/browser/htmlToMarkdown.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { localize } from '../../../../../../nls.js'; +import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType } from '../../../../../../platform/accessibility/browser/accessibleView.js'; +import { IAccessibleViewImplementation } from '../../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { ContextKeyExpr } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../../platform/log/common/log.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IThemeService } from '../../../../../../platform/theme/common/themeService.js'; +import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { AccessibilityVerbositySettingId } from '../../../../accessibility/browser/accessibilityConfiguration.js'; +import { IWebviewService, KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED, WebviewContentPurpose } from '../../../../webview/browser/webview.js'; +import { CONTEXT_ACTIVE_WEBVIEW_PANEL_ID } from '../../../../webviewPanel/browser/webviewEditor.js'; +import { WebviewInput } from '../../../../webviewPanel/browser/webviewEditorInput.js'; +import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { createHtmlPreviewDocument, getHtmlPreviewWebviewOptions } from './chatHtmlPreviewDocument.js'; + +export class ChatHtmlPreviewEditorInput extends WebviewInput { + static readonly viewType = 'vscode.chat.htmlPreview'; + readonly html: string; + + constructor( + readonly source: string, + readonly sourceId: string, + @IWebviewService webviewService: IWebviewService, + @IThemeService themeService: IThemeService, + @ILogService logService: ILogService, + @INotificationService notificationService: INotificationService, + ) { + const title = localize('chat.htmlPreview.editorTitle', "HTML Preview"); + const options = getHtmlPreviewWebviewOptions(title); + const html = createHtmlPreviewDocument(source); + super({ + viewType: ChatHtmlPreviewEditorInput.viewType, + providedId: ChatHtmlPreviewEditorInput.viewType, + name: title, + iconPath: Codicon.preview, + }, webviewService.createWebviewOverlay({ + ...options, + options: { ...options.options, purpose: WebviewContentPurpose.CustomEditor, enableFindWidget: true, tryRestoreScrollPosition: true }, + }), themeService); + this.html = html; + this._register(this.webview.onFatalError(error => { + logService.error('Error loading expanded chat HTML preview', error.message); + notificationService.error(localize('chat.htmlPreview.editorError', "Unable to load HTML preview. The original source is still available in the chat.")); + })); + this.webview.setHtml(html); + } +} + +export class ChatHtmlPreviewAccessibleView implements IAccessibleViewImplementation { + readonly priority = 125; + readonly name = 'chatHtmlPreview'; + readonly when = ContextKeyExpr.and(ChatContextKeys.enabled, CONTEXT_ACTIVE_WEBVIEW_PANEL_ID.isEqualTo(ChatHtmlPreviewEditorInput.viewType), KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED.toNegated()); + + constructor(readonly type: AccessibleViewType) { } + + getProvider(accessor: ServicesAccessor): AccessibleContentProvider | undefined { + const editorService = accessor.get(IEditorService); + const input = editorService.activeEditor; + if (!(input instanceof ChatHtmlPreviewEditorInput) || !input.webview.isFocused) { + return undefined; + } + const content = this.type === AccessibleViewType.Help + ? localize('chat.htmlPreview.editorHelp', "This is an expanded HTML response preview. Use Tab and Shift+Tab to reach links to sections and expandable disclosures. External links, scripts, and forms are disabled. Use Find{0} to search the document, or Accessible View{1} to read its text. Close the editor{2} to return to chat, where the preview context menu offers Show Source and Save HTML. Focus the HTML preview and press Shift+F10 to open its context menu. Save HTML exports a sanitized, self-contained document, not the original source.", '', '', '') + : convertHtmlToMarkdown(input.html); + return new AccessibleContentProvider( + AccessibleViewProviderId.ChatHtmlPreview, + { type: this.type }, + () => content, + () => { + if (!input.isDisposed() && editorService.activeEditor === input) { + input.webview.focus(); + } + }, + AccessibilityVerbositySettingId.Chat, + ); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewPart.ts new file mode 100644 index 000000000000..9bc13755473a --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatHtmlPreviewPart.ts @@ -0,0 +1,360 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../../../base/browser/keyboardEvent.js'; +import { StandardMouseEvent } from '../../../../../../base/browser/mouseEvent.js'; +import { status } from '../../../../../../base/browser/ui/aria/aria.js'; +import { Action, IAction, Separator } from '../../../../../../base/common/actions.js'; +import { VSBuffer } from '../../../../../../base/common/buffer.js'; +import { KeyCode, KeyMod } from '../../../../../../base/common/keyCodes.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../../../base/common/observable.js'; +import { joinPath } from '../../../../../../base/common/resources.js'; +import { localize } from '../../../../../../nls.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { IContextMenuService } from '../../../../../../platform/contextview/browser/contextView.js'; +import { IFileDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; +import { IFileService } from '../../../../../../platform/files/common/files.js'; +import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../../platform/log/common/log.js'; +import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; +import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { WebviewThemeDataProvider } from '../../../../webview/browser/themeing.js'; +import { IWebviewElement, IWebviewService, WebviewContentPurpose } from '../../../../webview/browser/webview.js'; +import { IChatWidgetService } from '../../chat.js'; +import { IChatLayoutService } from '../../../common/widget/chatLayoutService.js'; +import { delegateWebviewScrollToChatWidget } from '../../chatOutputItemRenderer.js'; +import { openChatTurnFile, previewKind } from '../chatTurnPills.js'; +import { IDisposableReference } from './chatCollections.js'; +import { EditorPool } from './chatContentCodePools.js'; +import { IChatContentPartRenderContext } from './chatContentParts.js'; +import { createHtmlPreviewDocument, getHtmlPreviewWebviewOptions } from './chatHtmlPreviewDocument.js'; +import { ChatHtmlPreviewEditorInput } from './chatHtmlPreviewEditorInput.js'; +import { IChatOutputPartStateCache, IOutputPartState } from './chatOutputPartStateCache.js'; +import { CodeBlockPart, ICodeBlockData } from './codeBlockPart.js'; +import './media/chatHtmlPreviewPart.css'; + +export function isHtmlPreviewCodeBlock(languageId: string, raw: string | undefined): boolean { + if (languageId.toLowerCase() !== 'html-preview' || !raw) { + return false; + } + + const opening = /^ {0,3}(?`{3,}|~{3,})/.exec(raw)?.groups?.fence; + const closing = /\n {0,3}(?`{3,}|~{3,}) *(?:\r?\n)*$/.exec(raw)?.groups?.fence; + return !!opening && !!closing + && closing.length >= opening.length + && [...closing].every(character => character === opening[0]); +} + +export class ChatHtmlPreviewPart extends Disposable { + static readonly maxPreviewLength = 64_000; + + readonly element = dom.$('.chat-html-preview'); + readonly reuseKey: string; + + private readonly source: IDisposableReference; + private readonly webviewDisposables = this._register(new DisposableStore()); + private webview: IWebviewElement | undefined; + private readonly renderPreview: (() => void) | undefined; + private readonly previewContainer = dom.$('.chat-html-preview-content'); + private readonly sourceContainer = dom.$('.chat-html-preview-source'); + private readonly sourceAction: Action; + private readonly openAction: Action; + private readonly saveAction: Action; + private expandedPreview: ChatHtmlPreviewEditorInput | undefined; + private readonly stateCacheKey: string; + private readonly partState: IOutputPartState; + + constructor( + private readonly data: ICodeBlockData, + context: IChatContentPartRenderContext, + editorPool: EditorPool, + private readonly onDidChangeHeight: () => void, + @IWebviewService webviewService: IWebviewService, + @IContextKeyService contextKeyService: IContextKeyService, + @IChatWidgetService chatWidgetService: IChatWidgetService, + @ILogService logService: ILogService, + @IInstantiationService private readonly instantiationService: IInstantiationService, + @IEditorService private readonly editorService: IEditorService, + @IFileDialogService private readonly fileDialogService: IFileDialogService, + @IFileService private readonly fileService: IFileService, + @IOpenerService private readonly openerService: IOpenerService, + @IConfigurationService private readonly configurationService: IConfigurationService, + @IContextMenuService private readonly contextMenuService: IContextMenuService, + @IChatLayoutService chatLayoutService: IChatLayoutService, + @IChatOutputPartStateCache stateCache: IChatOutputPartStateCache, + ) { + super(); + this.element.setAttribute('data-chat-find-ignore', ''); + this.element.tabIndex = 0; + this.element.setAttribute('role', 'group'); + this.element.setAttribute('aria-label', localize('chat.htmlPreview.label', "HTML preview for code block {0}", data.codeBlockIndex + 1)); + this.reuseKey = CodeBlockPart.poolKey(data.element.id, data.codeBlockIndex); + this.stateCacheKey = `htmlPreview/${data.chatSessionResource.toString()}/${data.element.id}/${data.codeBlockIndex}`; + this.partState = stateCache.get(this.stateCacheKey) ?? { height: 0 }; + stateCache.set(this.stateCacheKey, this.partState); + this.source = this._register(editorPool.get(this.reuseKey)); + this.source.object.render({ ...data, languageId: 'html' }, context.currentWidth.get()); + + this.sourceAction = this._register(new Action('chat.htmlPreview.source', localize('chat.htmlPreview.source', "Show Source"), undefined, true, async () => { + this.showSource(!this.sourceAction.checked); + this.focus(); + })); + this.sourceAction.checked = !!this.partState.showingSource; + this.openAction = this._register(new Action('chat.htmlPreview.open', localize('chat.htmlPreview.open', "Open Preview"), undefined, true, () => this.openPreview())); + this.saveAction = this._register(new Action('chat.htmlPreview.save', localize('chat.htmlPreview.save', "Save HTML..."), undefined, true, () => this.savePreview())); + this._register(dom.addDisposableListener(this.element, dom.EventType.CONTEXT_MENU, event => { + event.preventDefault(); + event.stopPropagation(); + this.showContextMenu(new StandardMouseEvent(dom.getWindow(this.element), event)); + }, true)); + this._register(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, event => { + const keyboardEvent = new StandardKeyboardEvent(event); + if (keyboardEvent.equals(KeyMod.Shift | KeyCode.F10) || keyboardEvent.equals(KeyCode.ContextMenu)) { + keyboardEvent.preventDefault(); + keyboardEvent.stopPropagation(); + this.showContextMenu(); + } + }, true)); + + const notice = dom.append(this.element, dom.$('.chat-html-preview-notice')); + notice.hidden = true; + this.element.append(this.previewContainer, this.sourceContainer); + this.sourceContainer.appendChild(this.source.object.element); + const showingSource = this.updateViewState(); + + if (data.text.length > ChatHtmlPreviewPart.maxPreviewLength) { + notice.textContent = localize('chat.htmlPreview.tooLarge', "HTML preview is too large. Showing source instead."); + notice.hidden = false; + this.showSource(true); + this.sourceAction.enabled = this.openAction.enabled = this.saveAction.enabled = false; + return; + } + + const webviewOptions = getHtmlPreviewWebviewOptions(localize('chat.htmlPreview.label', "HTML preview for code block {0}", data.codeBlockIndex + 1)); + const html = createHtmlPreviewDocument(data.text, undefined, 'inline'); + this.renderPreview = () => { + const webview = this.webview = this.webviewDisposables.add(webviewService.createWebviewElement({ + ...webviewOptions, + options: { + ...webviewOptions.options, + purpose: WebviewContentPurpose.ChatOutputItem, + getContextMenuActions: () => this.getContextMenuActions(), + transformCssVariables: styles => ({ + ...styles, + 'vscode-font-family': chatLayoutService.fontFamily.get() ?? styles['vscode-font-family'], + 'vscode-font-size': `${chatLayoutService.fontSize.get()}px`, + }), + }, + })); + webview.setContextKeyService(this.webviewDisposables.add(contextKeyService.createScoped(this.previewContainer))); + this.webviewDisposables.add(delegateWebviewScrollToChatWidget(webview, data.chatSessionResource, chatWidgetService)); + this.webviewDisposables.add(autorun(reader => { + const size = webview.intrinsicContentSize.read(reader); + if (size && Number.isFinite(size.height) && size.height > 0) { + const height = size.height; + this.partState.height = height; + this.previewContainer.style.height = `${height}px`; + this.onDidChangeHeight(); + } + })); + this.webviewDisposables.add(webview.onFatalError(error => { + logService.error('Error loading chat HTML preview', error.message); + notice.textContent = localize('chat.htmlPreview.error', "Unable to load HTML preview. Showing source instead."); + notice.setAttribute('role', 'alert'); + notice.hidden = false; + const restoreFocus = webview.isFocused; + this.showSource(true); + this.sourceAction.enabled = false; + if (restoreFocus) { + this.source.object.focus(); + } + })); + webview.setHtml(html); + webview.mountTo(this.previewContainer, dom.getWindow(context.container)); + }; + const connectionObserver = dom.append(this.element, dom.$('connection-observer')); + connectionObserver.hidden = true; + this._register(toDisposable(() => { + connectionObserver.onDidConnect = undefined; + connectionObserver.onDidDisconnect = undefined; + connectionObserver.remove(); + })); + connectionObserver.onDidDisconnect = () => this.clearWebview(); + connectionObserver.onDidConnect = () => { + if (!this.webview) { + this.onDidRemount(); + } + }; + this._register(context.onDidChangeVisibility(visible => { + if (visible) { + this.onDidRemount(); + } else { + this.clearWebview(); + } + })); + this._register(configurationService.onDidChangeConfiguration(event => { + if (event.affectsConfiguration('chat.fontFamily') || event.affectsConfiguration('chat.fontSize')) { + this.onDidRemount(); + } + })); + if (!showingSource) { + this.renderPreview(); + } + } + + get uri() { + return this.source.object.uri; + } + + get isFocused(): boolean { + return this.element.contains(dom.getWindow(this.element).document.activeElement); + } + + hasSameContent(text: string): boolean { + return this.data.text === text; + } + + layout(width: number): void { + this.source.object.layout(width); + } + + onDidRemount(): void { + const previousSource = this.sourceAction.checked; + const previousHeight = this.previewContainer.style.height; + const showingSource = this.updateViewState(); + const viewStateChanged = previousSource !== showingSource || previousHeight !== this.previewContainer.style.height; + this.source.object.onDidRemount(); + // A detached iframe can retain an unpainted document even after reinitialization. + this.clearWebview(); + if (!showingSource && !this._store.isDisposed) { + this.renderPreview?.(); + } + if (viewStateChanged) { + this.onDidChangeHeight(); + } + } + + private clearWebview(): void { + this.webviewDisposables.clear(); + this.webview = undefined; + } + + private getContextMenuActions(): IAction[] { + return Separator.join([this.openAction], [this.sourceAction], [this.saveAction]); + } + + private showContextMenu(anchor?: StandardMouseEvent): void { + const editor = this.sourceContainer.hidden ? undefined : this.source.object.editor; + this.contextMenuService.showContextMenu({ + getAnchor: () => anchor ?? this.element, + getActions: () => this.getContextMenuActions(), + menuId: editor?.contextMenuId, + contextKeyService: editor?.contextKeyService, + menuActionOptions: { arg: editor?.getModel()?.uri }, + onHide: cancelled => { + if (cancelled) { + this.focus(); + } + }, + }); + } + + focus(): void { + if (this.sourceContainer.hidden) { + this.element.focus(); + } else { + this.source.object.focus(); + } + } + + reveal(): boolean { + if (!this.sourceContainer.hidden) { + return false; + } + this.showSource(true); + return true; + } + + private showSource(show: boolean): void { + this.partState.showingSource = show; + const showingSource = this.updateViewState(); + if (showingSource) { + this.source.object.onDidRemount(); + } else if (!this.webview) { + this.renderPreview?.(); + } + this.onDidChangeHeight(); + } + + private updateViewState(): boolean { + const showingSource = !!this.partState.showingSource || !this.sourceAction.enabled; + this.sourceContainer.hidden = !showingSource; + this.previewContainer.hidden = showingSource; + this.sourceAction.checked = showingSource; + if (Number.isFinite(this.partState.height) && this.partState.height > 0) { + this.previewContainer.style.height = `${this.partState.height}px`; + } + return showingSource; + } + + private async openPreview(): Promise { + this.openAction.enabled = false; + let created: ChatHtmlPreviewEditorInput | undefined; + try { + if (!this.expandedPreview || this.expandedPreview.isDisposed()) { + this.expandedPreview = this.editorService.editors.find((input): input is ChatHtmlPreviewEditorInput => + input instanceof ChatHtmlPreviewEditorInput && input.sourceId === this.stateCacheKey && input.source === this.data.text); + if (!this.expandedPreview) { + created = this.instantiationService.createInstance(ChatHtmlPreviewEditorInput, this.data.text, this.stateCacheKey); + this.expandedPreview = created; + } + } + if (!await this.editorService.openEditor(this.expandedPreview, { pinned: true })) { + created?.dispose(); + } + } catch (error) { + created?.dispose(); + throw error; + } finally { + this.openAction.enabled = true; + } + } + + private async savePreview(): Promise { + this.saveAction.enabled = false; + try { + const store = new DisposableStore(); + let html: string; + try { + const theme = store.add(this.instantiationService.createInstance(WebviewThemeDataProvider)).getWebviewThemeData(); + html = createHtmlPreviewDocument(this.data.text, theme); + } finally { + store.dispose(); + } + const target = await this.fileDialogService.showSaveDialog({ + defaultUri: joinPath(await this.fileDialogService.defaultFilePath(), 'html-preview.html'), + title: localize('chat.htmlPreview.saveTitle', "Save Sanitized HTML Preview"), + filters: [{ name: localize('chat.htmlPreview.htmlFiles', "HTML"), extensions: ['html'] }], + }); + if (!target) { + return; + } + + await this.fileService.writeFile(target, VSBuffer.fromString(html)); + status(localize('chat.htmlPreview.saved', "Sanitized HTML preview saved.")); + const kind = previewKind(target); + if (kind) { + await openChatTurnFile({ uri: target, kind, created: true }, this.openerService, this.configurationService); + } else { + await this.editorService.openEditor({ resource: target, options: { pinned: true } }); + } + } finally { + this.saveAction.enabled = true; + } + } +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatInlineAnchorWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatInlineAnchorWidget.ts index 9247033f8c00..8665f461c951 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatInlineAnchorWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatInlineAnchorWidget.ts @@ -83,7 +83,7 @@ export interface IRenderFileWidgetsOptions { } export function renderFileWidgets(element: HTMLElement, instantiationService: IInstantiationService, chatMarkdownAnchorService: IChatMarkdownAnchorService, disposables: DisposableStore, options?: IRenderFileWidgetsOptions) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const links = element.querySelectorAll('a'); links.forEach(a => { renderFileAnchor(a, instantiationService, chatMarkdownAnchorService, disposables, options); @@ -119,9 +119,10 @@ export function renderFileAnchor(anchor: HTMLAnchorElement, instantiationService if (vscodeLinkType) { metadata = { vscodeLinkType, linkText }; - // Presentation metadata must not reach the filesystem provider. - searchParams.delete('vscodeLinkType'); - uri = uri.with({ query: searchParams.toString() }); + // Strip the presentation field without reserializing the resource's own query. + const queryParts = uri.query.split('&'); + queryParts.splice(queryParts.findIndex(part => new URLSearchParams(part).has('vscodeLinkType')), 1); + uri = uri.with({ query: queryParts.join('&') }); } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownContentPart.ts index 538798e15556..1473bd638c3f 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownContentPart.ts @@ -72,6 +72,7 @@ import { EditorPool } from './chatContentCodePools.js'; import { IChatContentPart, IChatContentPartDiffData, IChatContentPartRenderContext } from './chatContentParts.js'; import { ChatEditPillElement, isResourceContentEmpty } from './chatEditPillElement.js'; import { ChatExtensionsContentPart } from './chatExtensionsContentPart.js'; +import { ChatHtmlPreviewPart, isHtmlPreviewCodeBlock } from './chatHtmlPreviewPart.js'; import { ChatProgressSubPart } from './chatProgressContentPart.js'; import { IncrementalDOMMorpher } from './chatIncrementalRendering/chatIncrementalRendering.js'; import { IChatOutputPartStateCache, IOutputPartState } from './chatOutputPartStateCache.js'; @@ -81,6 +82,7 @@ const $ = dom.$; export interface IChatMarkdownContentPartOptions { readonly codeBlockRenderOptions?: ICodeBlockRenderOptions; + readonly renderHtmlPreviews?: boolean; readonly allowInlineDiffs?: boolean; readonly horizontalPadding?: number; readonly accessibilityOptions?: { @@ -130,7 +132,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP private readonly _onDidChangeCodeblocks = this._register(new Emitter()); readonly onDidChangeCodeblocks: Event = this._onDidChangeCodeblocks.event; - private readonly allRefs: IDisposableReference[] = []; + private readonly allRefs: IDisposableReference[] = []; private readonly _codeblocks: IMarkdownPartCodeBlockInfo[] = []; public get codeblocks(): IChatCodeBlockInfo[] { @@ -223,11 +225,16 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP const previousRenderStore = renderStore.clearAndLeak(); const reusableOutputCodeBlockRefs = new Map>(); + const reusableHtmlPreviewRefs = new Map>(); for (const ref of this.allRefs) { if (ref.object instanceof ChatOutputCodeBlockPart) { const outputRef = ref as IDisposableReference; previousRenderStore?.deleteAndLeak(outputRef); reusableOutputCodeBlockRefs.set(outputRef.object.reuseKey, outputRef); + } else if (ref.object instanceof ChatHtmlPreviewPart) { + const previewRef = ref as IDisposableReference; + previousRenderStore?.deleteAndLeak(previewRef); + reusableHtmlPreviewRefs.set(previewRef.object.reuseKey, previewRef); } } previousRenderStore?.dispose(); @@ -349,6 +356,31 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP }; if (element.isCompleteAddedRequest || !codemapperUri || !isEdit) { + if (this.rendererOptions.renderHtmlPreviews && isResponseVM(element) && !hideToolbar + && !codemapperUri && isHtmlPreviewCodeBlock(languageId, raw)) { + const reuseKey = CodeBlockPart.poolKey(element.id, globalIndex); + let ref = reusableHtmlPreviewRefs.get(reuseKey); + if (ref?.object.hasSameContent(codeBlockText)) { + reusableHtmlPreviewRefs.delete(reuseKey); + } else { + const preview = this.instantiationService.createInstance(ChatHtmlPreviewPart, codeBlockInfo, context, this.editorPool, () => this._onDidChangeHeight.fire()); + ref = { object: preview, isStale: () => false, dispose: () => preview.dispose() }; + } + this.allRefs.push(ref); + store.add(ref); + const preview = ref.object; + this._codeblocks.push({ + ...baseCodeBlockInfo, + codemapperUri: undefined, + isStreamingEdit: false, + get uri() { return preview.uri; }, + get isFocused() { return preview.isFocused; }, + focus() { preview.focus(); }, + reveal() { return preview.reveal(); }, + }); + return preview.element; + } + if (hasChatOutputRenderer) { const ref = this.renderChatOutputCodeBlock(languageId, codeBlockText, globalIndex, context, isCodeBlockComplete, reusableOutputCodeBlockRefs); this._codeblocks.push({ @@ -447,7 +479,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP }); // Make katex blocks horizontally scrollable - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const katexBlock of this.domNode.querySelectorAll('.katex-display')) { if (!dom.isHTMLElement(katexBlock)) { continue; @@ -466,6 +498,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP store.add(wrapTablesWithScrollable(this.domNode, layoutParticipants)); dispose(reusableOutputCodeBlockRefs.values()); + dispose(reusableHtmlPreviewRefs.values()); this._onDidChangeCodeblocks.fire(); }; @@ -503,7 +536,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP */ private hookUpImages(element: HTMLElement, fileImages: ResourceSet, sessionResource: URI, responseId: string): IDisposable { const store = new DisposableStore(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const image of element.querySelectorAll('img')) { const source = image.dataset.src; const resource = source ? URI.parse(source) : undefined; @@ -656,7 +689,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP } if (!this._incrementalMorpher) { - if (this.allRefs.some(ref => ref.object instanceof ChatOutputCodeBlockPart) + if (this.allRefs.some(ref => ref.object instanceof ChatOutputCodeBlockPart || ref.object instanceof ChatHtmlPreviewPart) && newMarkdown.content.value.startsWith(this.markdown.content.value)) { const previousMarkdown = this.markdown; this.markdown = newMarkdown; @@ -695,7 +728,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP this.allRefs.forEach((ref, index) => { if (ref.object instanceof CodeBlockPart) { ref.object.layout(width); - } else if (ref.object instanceof ChatOutputCodeBlockPart) { + } else if (ref.object instanceof ChatOutputCodeBlockPart || ref.object instanceof ChatHtmlPreviewPart) { ref.object.layout(width); } else if (ref.object instanceof MarkdownDiffBlockPart) { ref.object.layout(width); @@ -712,7 +745,7 @@ export class ChatMarkdownContentPart extends Disposable implements IChatContentP onDidRemount(): void { for (const ref of this.allRefs) { - if (ref.object instanceof CodeBlockPart || ref.object instanceof ChatOutputCodeBlockPart) { + if (ref.object instanceof CodeBlockPart || ref.object instanceof ChatOutputCodeBlockPart || ref.object instanceof ChatHtmlPreviewPart) { ref.object.onDidRemount(); } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownDecorationsRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownDecorationsRenderer.ts index 7d6e67d98ab1..f01a4aa974f7 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownDecorationsRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownDecorationsRenderer.ts @@ -7,11 +7,12 @@ import * as dom from '../../../../../../base/browser/dom.js'; import { Button } from '../../../../../../base/browser/ui/button/button.js'; import { getDefaultHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { toErrorMessage } from '../../../../../../base/common/errorMessage.js'; -import { escapeMarkdownSyntaxTokens } from '../../../../../../base/common/htmlContent.js'; +import { escapeMarkdownSyntaxTokens, MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { Lazy } from '../../../../../../base/common/lazy.js'; import { Disposable, DisposableStore, IDisposable } from '../../../../../../base/common/lifecycle.js'; import { escape } from '../../../../../../base/common/strings.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { isUUID } from '../../../../../../base/common/uuid.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { ILinkPresentationService } from '../../../../../../platform/dataChannel/common/dataChannel.js'; @@ -35,6 +36,7 @@ import { ChatAgentHover, getChatAgentHoverOptions } from '../chatAgentHover.js'; import { IChatMarkdownAnchorService } from './chatMarkdownAnchorService.js'; import { InlineAnchorWidget, renderFileAnchor } from './chatInlineAnchorWidget.js'; import { ChatRichLinkDecorator } from './chatRichLink.js'; +import { AgentHostCompletionReferenceKind, getAgentHostCompletionReferenceKindFromValue } from '../../../common/attachments/chatVariableEntries.js'; /** For rendering slash commands, variables */ const decorationRefUrl = `http://_vscodedecoration_`; @@ -119,7 +121,8 @@ export class ChatMarkdownDecorationsRenderer extends Disposable { * @param inlineAttachmentParts The indices of the parts whose attachments are * shown as pills inline with the text, by a {@link ChatInlineAttachmentRenderer}. */ - convertParsedRequestToMarkdown(sessionResource: URI, parsedRequest: IParsedChatRequest, inlineAttachmentParts?: ReadonlySet): string { + convertParsedRequestToMarkdown(sessionResource: URI, parsedRequest: IParsedChatRequest, inlineAttachmentParts?: ReadonlySet): MarkdownString { + const markdown = new MarkdownString(); let result = ''; parsedRequest.parts.forEach((part, index) => { if (part instanceof ChatRequestTextPart) { @@ -127,14 +130,24 @@ export class ChatMarkdownDecorationsRenderer extends Disposable { } else if (part instanceof ChatRequestAgentPart) { result += this.instantiationService.invokeFunction(accessor => agentToMarkdown(part.agent, sessionResource, false, accessor)); } else { - result += this.genericDecorationToMarkdown(part, inlineAttachmentParts?.has(index) ? index : undefined); + result += this.genericDecorationToMarkdown(part, inlineAttachmentParts?.has(index) ? index : undefined, markdown); } }); - return result; + markdown.value = result; + return markdown; } - private genericDecorationToMarkdown(part: IParsedChatRequestPart, inlineAttachment: number | undefined): string { + private genericDecorationToMarkdown(part: IParsedChatRequestPart, inlineAttachment: number | undefined, markdown: MarkdownString): string { + const text = escapeMarkdownSyntaxTokens(escape(part.text)); + if (part instanceof ChatRequestDynamicVariablePart && getAgentHostCompletionReferenceKindFromValue(part.data) === AgentHostCompletionReferenceKind.Skill && !isUUID(part.id)) { + const uri = URI.parse(part.id, true); + const query = `vscodeLinkType=skill${uri.query ? `&${uri.query}` : ''}`; + const href = `${contentRefUrl}/skill-${encodeURIComponent(uri.toString()).replace(/\(/g, '%28').replace(/\)/g, '%29')}`; + // Use markdown's resource map so custom schemes retain the normal sanitization path. + (markdown.uris ??= {})[href] = uri.with({ query }); + return `[${text}](${href})`; + } const uri = part instanceof ChatRequestDynamicVariablePart && part.data instanceof URI ? part.data : undefined; @@ -146,7 +159,6 @@ export class ChatMarkdownDecorationsRenderer extends Disposable { ''; const args: IDecorationWidgetArgs = inlineAttachment === undefined ? { title } : { title, inlineAttachment }; - const text = escapeMarkdownSyntaxTokens(escape(part.text)); const encodedArgs = encodeURIComponent(JSON.stringify(args)).replace(/\(/g, '%28').replace(/\)/g, '%29'); return `[${text}](${decorationRefUrl}?${encodedArgs})`; } @@ -158,13 +170,17 @@ export class ChatMarkdownDecorationsRenderer extends Disposable { walkTreeAndAnnotateReferenceLinks(content: IChatMarkdownContent, element: HTMLElement, renderInlineAttachment?: ChatInlineAttachmentRenderer): IDisposable { const store = new DisposableStore(); const fileWidgetOptions = { linkTypes: ['markdown-preview'] }; + const skillWidgetOptions = { linkTypes: ['skill'] }; + const skillLinks = new Set(Object.entries(content.content.uris ?? {}) + .filter(([key]) => key.startsWith(`${contentRefUrl}/skill-`)) + .map(([, uri]) => URI.revive(uri).toString())); const richLinksEnabled = this.configurationService.getValue(ChatConfiguration.RichLinks); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax element.querySelectorAll('a').forEach(a => { - if (renderFileAnchor(a, this.instantiationService, this.chatMarkdownAnchorService, store, fileWidgetOptions)) { + const href = a.getAttribute('data-href'); + if (renderFileAnchor(a, this.instantiationService, this.chatMarkdownAnchorService, store, href && skillLinks.has(href) ? skillWidgetOptions : fileWidgetOptions)) { return; } - const href = a.getAttribute('data-href'); if (href) { if (href.startsWith(agentRefUrl)) { let args: IAgentWidgetArgs | undefined; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownTableScrolling.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownTableScrolling.ts index 8deecd4e1fc8..c8138c31edd4 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownTableScrolling.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMarkdownTableScrolling.ts @@ -92,7 +92,7 @@ function measureTable(table: ITableScrollable): ITableMeasurement { */ export function wrapTablesWithScrollable(domNode: HTMLElement, layoutParticipants: Lazy void>>): DisposableStore { const store = new DisposableStore(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const table of domNode.querySelectorAll('table')) { if (!dom.isHTMLElement(table)) { continue; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpAuthenticationContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpAuthenticationContentPart.ts index 6631b69d1b40..53b05dc73a68 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpAuthenticationContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpAuthenticationContentPart.ts @@ -138,7 +138,7 @@ export class ChatMcpAuthenticationContentPart extends Disposable implements ICha })); store.add(widget.onDidClick(() => void this.authenticate())); this.domNode.appendChild(widget.domNode); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.authenticateAction = widget.domNode.querySelector('.monaco-button') ?? undefined; if (!this._renderedAuthenticatingServerId && this.configurationService.getValue(AccessibilityWorkbenchSettingId.VerboseChatProgressUpdates)) { alert(localize('mcp.auth.announcement', "{0} Use the Authenticate button to continue.", renderAsPlaintext(new MarkdownString(content)))); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersInteractionContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersInteractionContentPart.ts index e623e3b260d3..dfe8c09b5800 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersInteractionContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersInteractionContentPart.ts @@ -187,7 +187,7 @@ export class ChatMcpServersInteractionContentPart extends Disposable implements } }); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const startLink = [...messageMd.element.querySelectorAll('a')].find(a => !a.getAttribute('data-href')?.startsWith('command:')); if (!startLink) { // Should not happen diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersStartingContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersStartingContentPart.ts index 48133f1668b7..97cb63e632da 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersStartingContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatMcpServersStartingContentPart.ts @@ -140,7 +140,7 @@ export class ChatMcpServersStartingContentPart extends Disposable implements ICh messageContainer.appendChild(rendered.element); container.appendChild(messageContainer); this.domNode.appendChild(container); - // eslint-disable-next-line no-restricted-syntax -- The markdown renderer owns the Skip anchor. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- The markdown renderer owns the Skip anchor. return rendered.element.querySelector('a[data-href="#skip"]') ?? undefined; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponents.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponents.ts new file mode 100644 index 000000000000..f2d699d7f8d8 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponents.ts @@ -0,0 +1,75 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * The seam between shared chat code and the renderer of native components. + * + * This module is part of every bundle that renders chat, including the size-constrained phone + * bundle, so it only holds the contract and the registration point. The parser, the components + * and their styles are contributed by the entries that render them. Do not import them here. + */ + +import { IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { ChatAIDisabledSettingId } from '../../../../../../platform/chat/common/chatSettings.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ChatConfiguration } from '../../../common/constants.js'; +import { NATIVE_COMPONENTS_LANGUAGE_ID } from '../../../common/nativeComponents/nativeComponents.js'; +import { getClosedCodeFenceInfo } from '../../../common/widget/codeFence.js'; +import { EditorPool } from './chatContentCodePools.js'; +import { IChatContentPartRenderContext } from './chatContentParts.js'; +import { ICodeBlockData } from './codeBlockPart.js'; + +/** A native components block in a response, which shows either its visual or its source. */ +export interface IChatNativeComponentsPart extends IDisposable { + readonly element: HTMLElement; + /** The resource of the source editor, by which Find and code block navigation address the block. */ + readonly uri: URI | undefined; + readonly isFocused: boolean; + hasSameContent(text: string, fenceInfo: string): boolean; + layout(width: number): void; + onDidRemount(): void; + focus(): void; + /** Shows the source without taking focus. Returns whether that changed the layout. */ + reveal(): boolean; +} + +export interface IChatNativeComponentsRenderer { + /** + * Creates the part of a block whose closing fence has arrived. + * @param fenceInfo The info string of the opening fence, which may declare a schema version. + */ + createPart(instantiationService: IInstantiationService, data: ICodeBlockData, fenceInfo: string, context: IChatContentPartRenderContext, editorPool: EditorPool, onDidChangeHeight: () => void): IChatNativeComponentsPart; + /** Returns the text alternative of a block that renders as a visual, or `undefined` for one that shows its source. */ + describe(source: string, fenceInfo: string): string | undefined; +} + +let registeredRenderer: IChatNativeComponentsRenderer | undefined; + +/** Contributes the renderer. Entries that do not, such as the phone bundle, show these blocks as source. */ +export function registerChatNativeComponentsRenderer(renderer: IChatNativeComponentsRenderer): IDisposable { + registeredRenderer = renderer; + return toDisposable(() => { + if (registeredRenderer === renderer) { + registeredRenderer = undefined; + } + }); +} + +/** + * Returns the renderer when native components are available and enabled. A chat surface must also + * opt in with its `renderNativeComponents` renderer option before it uses one. + */ +export function getChatNativeComponentsRenderer(configurationService: IConfigurationService): IChatNativeComponentsRenderer | undefined { + const isEnabled = configurationService.getValue(ChatConfiguration.NativeComponentsEnabled) === true + && configurationService.getValue(ChatAIDisabledSettingId) !== true; + return isEnabled ? registeredRenderer : undefined; +} + +/** Returns the fence info string of a native components block whose closing fence has arrived, or `undefined` for any other code block. */ +export function getNativeComponentsFenceInfo(languageId: string, raw: string | undefined): string | undefined { + return languageId.toLowerCase() === NATIVE_COMPONENTS_LANGUAGE_ID ? getClosedCodeFenceInfo(raw) : undefined; +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsPart.ts new file mode 100644 index 000000000000..6dc983e231d7 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsPart.ts @@ -0,0 +1,241 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../../../base/browser/keyboardEvent.js'; +import { StandardMouseEvent } from '../../../../../../base/browser/mouseEvent.js'; +import { Action } from '../../../../../../base/common/actions.js'; +import { KeyCode, KeyMod } from '../../../../../../base/common/keyCodes.js'; +import { Disposable } from '../../../../../../base/common/lifecycle.js'; +import { localize } from '../../../../../../nls.js'; +import { IContextMenuService } from '../../../../../../platform/contextview/browser/contextView.js'; +import { parseNativeComponents } from '../../../common/nativeComponents/nativeComponentsParser.js'; +import { describeNativeComponents } from '../../../common/nativeComponents/nativeComponentsText.js'; +import { IDisposableReference } from './chatCollections.js'; +import { EditorPool } from './chatContentCodePools.js'; +import { IChatContentPartRenderContext } from './chatContentParts.js'; +import { IChatNativeComponentsPart, IChatNativeComponentsRenderer } from './chatNativeComponents.js'; +import { renderNativeComponents } from './chatNativeComponentsRenderer.js'; +import { IChatOutputPartStateCache, IOutputPartState } from './chatOutputPartStateCache.js'; +import { CodeBlockPart, ICodeBlockData } from './codeBlockPart.js'; + +/** + * The disclosures that the user expanded in a block, by the block's cached view state. They are + * kept in memory only: they outlive the part when its row is recycled, but not a reload, and are + * dropped together with the view state. + */ +const expandedDisclosures = new WeakMap }>(); +const noDisclosures: ReadonlySet = new Set(); + +/** + * Shows a native components block of a response as a visual, with its source one context menu + * action away. A block that does not validate shows its source and the reason instead. + */ +export class ChatNativeComponentsPart extends Disposable implements IChatNativeComponentsPart { + + readonly element = dom.$('.chat-native-components'); + + private readonly source: IDisposableReference; + private readonly visualContainer = dom.$('.chat-native-components-visual'); + private readonly sourceContainer = dom.$('.chat-native-components-source'); + private readonly sourceAction: Action; + private readonly disclosures: readonly HTMLDetailsElement[]; + private readonly stateKey: string; + + constructor( + private readonly data: ICodeBlockData, + private readonly fenceInfo: string, + context: IChatContentPartRenderContext, + editorPool: EditorPool, + private readonly onDidChangeHeight: () => void, + @IContextMenuService private readonly contextMenuService: IContextMenuService, + @IChatOutputPartStateCache private readonly stateCache: IChatOutputPartStateCache, + ) { + super(); + // Find searches the source, as it does for any code block, and reveals it on a match. + this.element.setAttribute('data-chat-find-ignore', ''); + this.stateKey = `nativeComponents/${data.chatSessionResource.toString()}/${data.element.id}/${data.codeBlockIndex}`; + this.source = this._register(editorPool.get(CodeBlockPart.poolKey(data.element.id, data.codeBlockIndex))); + this.source.object.render({ ...data, languageId: 'xml' }, context.currentWidth.get()); + this.sourceAction = this._register(new Action('chat.nativeComponents.source', localize('chat.nativeComponents.source', "Show Source"), undefined, true, async () => { + this.showSource(!this.sourceAction.checked); + this.focus(); + })); + + const result = parseNativeComponents(data.text, fenceInfo); + if (result.error) { + this.disclosures = []; + this.sourceAction.enabled = false; + dom.append(this.element, dom.$('.chat-native-components-notice')).textContent = result.error.line === undefined + ? localize('chat.nativeComponents.invalid', "This block could not be shown as a visual, so its source is shown instead. {0}", result.error.message) + : localize('chat.nativeComponents.invalidLine', "This block could not be shown as a visual, so its source is shown instead. Line {0}: {1}", result.error.line, result.error.message); + } else { + const visual = renderNativeComponents(result.document); + this.disclosures = visual.disclosures; + this.visualContainer.appendChild(visual.element); + this.registerVisualListeners(); + } + + this.element.append(this.visualContainer, this.sourceContainer); + this.sourceContainer.appendChild(this.source.object.element); + this.applyViewState(); + } + + get uri() { + return this.source.object.uri; + } + + get isFocused(): boolean { + return dom.isAncestorOfActiveElement(this.element); + } + + hasSameContent(text: string, fenceInfo: string): boolean { + return this.data.text === text && this.fenceInfo === fenceInfo; + } + + layout(width: number): void { + this.source.object.layout(width); + } + + onDidRemount(): void { + // Another part of the same block may have changed the view state in the meantime. + const changed = this.applyViewState(); + this.source.object.onDidRemount(); + if (changed) { + this.onDidChangeHeight(); + } + } + + focus(): void { + if (this.sourceContainer.hidden) { + this.element.focus(); + } else { + this.source.object.focus(); + } + } + + reveal(): boolean { + if (!this.sourceContainer.hidden) { + return false; + } + this.showSource(true); + return true; + } + + /** Makes the visual a labelled tab stop that offers its context menu and remembers its disclosures. */ + private registerVisualListeners(): void { + this.element.tabIndex = 0; + this.element.setAttribute('role', 'group'); + this.element.setAttribute('aria-label', localize('chat.nativeComponents.label', "Visual for code block {0}", this.data.codeBlockIndex + 1)); + this._register(dom.addDisposableListener(this.element, dom.EventType.CONTEXT_MENU, event => { + event.preventDefault(); + event.stopPropagation(); + this.showContextMenu(new StandardMouseEvent(dom.getWindow(this.element), event)); + }, true)); + this._register(dom.addDisposableListener(this.element, dom.EventType.KEY_DOWN, event => { + const keyboardEvent = new StandardKeyboardEvent(event); + if (keyboardEvent.equals(KeyMod.Shift | KeyCode.F10) || keyboardEvent.equals(KeyCode.ContextMenu)) { + keyboardEvent.preventDefault(); + keyboardEvent.stopPropagation(); + this.showContextMenu(); + } + }, true)); + this.disclosures.forEach((details, index) => { + // Chat binds Enter to Edit Request wherever no text input has focus, which takes the key before + // the browser toggles a native disclosure. The summary therefore handles Enter itself, like a + // button. Nothing is bound to Space inside a response, so the browser toggles it on Space. + this._register(dom.addDisposableListener(details, dom.EventType.KEY_DOWN, event => { + if (event.target === details.firstElementChild && new StandardKeyboardEvent(event).equals(KeyCode.Enter)) { + dom.EventHelper.stop(event, true); + details.open = !details.open; + } + })); + this._register(dom.addDisposableListener(details, 'toggle', () => { + if (details.open !== this.readViewState().expanded.has(index)) { + this.writeViewState((_state, expanded) => { + if (details.open) { + expanded.add(index); + } else { + expanded.delete(index); + } + }); + this.onDidChangeHeight(); + } + })); + }); + } + + private showContextMenu(anchor?: StandardMouseEvent): void { + // While the source is shown, its editor's own menu is offered along with the action. + const editor = this.sourceContainer.hidden ? undefined : this.source.object.editor; + this.contextMenuService.showContextMenu({ + getAnchor: () => anchor ?? this.element, + getActions: () => [this.sourceAction], + menuId: editor?.contextMenuId, + contextKeyService: editor?.contextKeyService, + menuActionOptions: { arg: editor?.getModel()?.uri }, + onHide: cancelled => { + if (cancelled) { + this.focus(); + } + }, + }); + } + + private showSource(show: boolean): void { + this.writeViewState(state => { state.showingSource = show; }); + this.applyViewState(); + if (show) { + this.source.object.onDidRemount(); + } + this.onDidChangeHeight(); + } + + /** Shows what the remembered view state asks for. Returns whether that changed anything. */ + private applyViewState(): boolean { + const state = this.readViewState(); + const showSource = state.showingSource || !this.sourceAction.enabled; + let changed = this.sourceContainer.hidden === showSource; + this.sourceContainer.hidden = !showSource; + this.visualContainer.hidden = showSource; + this.sourceAction.checked = showSource; + this.disclosures.forEach((details, index) => { + const open = state.expanded.has(index); + changed ||= details.open !== open; + details.open = open; + }); + return changed; + } + + private readViewState(): { readonly showingSource: boolean; readonly expanded: ReadonlySet } { + const state = this.stateCache.get(this.stateKey); + const expanded = state && expandedDisclosures.get(state); + return { + showingSource: !!state?.showingSource, + expanded: expanded?.source === this.data.text ? expanded.indexes : noDisclosures, + }; + } + + /** Remembers a change of the view state. A block only occupies the cache once the user has changed how it is shown. */ + private writeViewState(update: (state: IOutputPartState, expanded: Set) => void): void { + const state = this.stateCache.get(this.stateKey) ?? { height: 0 }; + let expanded = expandedDisclosures.get(state); + if (expanded?.source !== this.data.text) { + expanded = { source: this.data.text, indexes: new Set() }; + expandedDisclosures.set(state, expanded); + } + update(state, expanded.indexes); + this.stateCache.set(this.stateKey, state); + } +} + +/** Renders native components blocks. Contributed by the entries whose chat surfaces show them. */ +export const chatNativeComponentsRenderer: IChatNativeComponentsRenderer = { + createPart: (instantiationService, data, fenceInfo, context, editorPool, onDidChangeHeight) => instantiationService.createInstance(ChatNativeComponentsPart, data, fenceInfo, context, editorPool, onDidChangeHeight), + describe: (source, fenceInfo) => { + const { document } = parseNativeComponents(source, fenceInfo); + return document && describeNativeComponents(document); + }, +}; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsRenderer.ts new file mode 100644 index 000000000000..57d2ed7f6417 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatNativeComponentsRenderer.ts @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../../base/browser/dom.js'; +import { renderIcon } from '../../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { IdGenerator } from '../../../../../../base/common/idGenerator.js'; +import { ThemeIcon } from '../../../../../../base/common/themables.js'; +import { INativeBadge, INativeBarChart, INativeComponentsDocument, INativeMetric, INativeTable, INativeText, NativeComponent, NativeComponentTone } from '../../../common/nativeComponents/nativeComponents.js'; +import { formatNativeBarValue, getNativeComponentToneLabel } from '../../../common/nativeComponents/nativeComponentsText.js'; +import './media/chatNativeComponents.css'; + +const $ = dom.$; + +const idGenerator = new IdGenerator('chat-native-components-'); + +export interface IRenderedNativeComponents { + readonly element: HTMLElement; + /** The disclosures of the document, in document order. */ + readonly disclosures: readonly HTMLDetailsElement[]; +} + +/** + * Renders a validated document with the components of the catalogue. + * + * The document only selects components and their semantic variants. Every string that it carries + * is untrusted and set as text, never as markup, and it has no influence on class names or styles + * beyond those variants: the appearance is defined by the stylesheet with theme and size tokens. + */ +export function renderNativeComponents(document: INativeComponentsDocument): IRenderedNativeComponents { + const disclosures: HTMLDetailsElement[] = []; + const element = appendComponents($('.chat-native-components-content'), document.children, disclosures); + return { element, disclosures }; +} + +function appendComponents(container: HTMLElement, components: readonly NativeComponent[], disclosures: HTMLDetailsElement[]): HTMLElement { + let badges: HTMLElement | undefined; + for (const component of components) { + if (component.type === 'badge') { + // Adjacent badges share a line instead of each taking a row or a column. + badges ??= dom.append(container, $('.chat-native-badges')); + badges.appendChild(renderBadge(component)); + } else { + badges = undefined; + container.appendChild(renderComponent(component, disclosures)); + } + } + return container; +} + +function renderComponent(component: Exclude, disclosures: HTMLDetailsElement[]): HTMLElement { + switch (component.type) { + case 'stack': return appendComponents($('.chat-native-stack'), component.children, disclosures); + case 'columns': return appendComponents($('.chat-native-columns'), component.children, disclosures); + case 'text': return renderText(component); + case 'metric': return renderMetric(component); + case 'table': return renderTable(component); + case 'barChart': return renderBarChart(component); + case 'disclosure': { + const details = $('details.chat-native-disclosure'); + disclosures.push(details); + const summary = dom.append(details, $('summary.chat-native-disclosure-summary')); + appendIcon(summary, Codicon.chevronRightCompact).setAttribute('aria-hidden', 'true'); + dom.append(summary, $('span')).textContent = component.summary; + appendComponents(dom.append(details, $('.chat-native-disclosure-content')), component.children, disclosures); + return details; + } + } +} + +function renderText(component: INativeText): HTMLElement { + const element = $(`.chat-native-text.${component.variant}`); + if (component.variant === 'heading') { + element.setAttribute('role', 'heading'); + element.setAttribute('aria-level', '3'); + } + element.textContent = component.text; + return element; +} + +function renderMetric(component: INativeMetric): HTMLElement { + const element = $('.chat-native-metric', { role: 'group' }); + const label = dom.append(element, $('.chat-native-metric-label')); + label.id = idGenerator.nextId(); + label.textContent = component.label; + element.setAttribute('aria-labelledby', label.id); + const value = dom.append(element, $('.chat-native-metric-value')); + dom.append(value, $('span')).textContent = component.value; + if (component.delta) { + const detail = dom.append(element, $('.chat-native-metric-detail')); + appendToneIcon(detail, component.tone); + dom.append(detail, $('span')).textContent = component.delta; + } else { + // Without a delta to qualify, the tone qualifies the value itself. + appendToneIcon(value, component.tone); + } + return element; +} + +function renderBadge(component: INativeBadge): HTMLElement { + const element = $('.chat-native-badge'); + appendToneIcon(element, component.tone); + dom.append(element, $('span')).textContent = component.text; + return element; +} + +function renderTable(component: INativeTable): HTMLElement { + // Wide tables scroll inside their own box instead of widening the response. + const element = $('.chat-native-table-scroll'); + const table = dom.append(element, $('table.chat-native-table')); + if (component.caption) { + dom.append(table, $('caption')).textContent = component.caption; + } + const header = dom.append(dom.append(table, $('thead')), $('tr')); + for (const column of component.columns) { + const cell = dom.append(header, $('th', { scope: 'col' })); + cell.classList.toggle('align-end', column.align === 'end'); + cell.textContent = column.header; + } + const body = dom.append(table, $('tbody')); + for (const row of component.rows) { + const tableRow = dom.append(body, $('tr')); + row.forEach((text, index) => { + const cell = dom.append(tableRow, $('td')); + cell.classList.toggle('align-end', component.columns[index].align === 'end'); + cell.textContent = text; + }); + } + return element; +} + +/** + * Draws the chart as a table of labels and values, so that assistive technology reads the same + * data that the bars show. The bars themselves are decoration and hidden from it. + */ +function renderBarChart(component: INativeBarChart): HTMLElement { + const element = $('.chat-native-chart'); + const title = dom.append(element, $('.chat-native-chart-title')); + title.id = idGenerator.nextId(); + title.textContent = component.title; + const plot = dom.append(element, $('.chat-native-chart-plot', { role: 'table', 'aria-labelledby': title.id })); + const maximum = Math.max(...component.bars.map(bar => bar.value)); + for (const bar of component.bars) { + const row = dom.append(plot, $('.chat-native-chart-row', { role: 'row' })); + dom.append(row, $('.chat-native-chart-label', { role: 'rowheader' })).textContent = bar.label; + const track = dom.append(row, $('.chat-native-chart-track', { 'aria-hidden': 'true' })); + dom.append(track, $('.chat-native-chart-bar')).style.width = `${maximum > 0 ? bar.value / maximum * 100 : 0}%`; + dom.append(row, $('.chat-native-chart-value', { role: 'cell' })).textContent = formatNativeBarValue(bar, component.unit); + } + return element; +} + +const toneIcons = { + positive: Codicon.passCompact, + negative: Codicon.errorCompact, + warning: Codicon.warningCompact, +}; + +/** Shows a tone as an icon whose shape and accessible name carry the meaning, with color as reinforcement. */ +function appendToneIcon(container: HTMLElement, tone: NativeComponentTone): void { + const label = getNativeComponentToneLabel(tone); + if (tone === 'neutral' || !label) { + return; + } + const icon = appendIcon(container, toneIcons[tone]); + icon.classList.add(tone); + icon.setAttribute('role', 'img'); + icon.setAttribute('aria-label', label); +} + +function appendIcon(container: HTMLElement, icon: ThemeIcon): HTMLElement { + const element = dom.append(container, renderIcon(icon)); + element.classList.add('chat-native-icon'); + return element; +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatOutputPartStateCache.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatOutputPartStateCache.ts index 6dc5d0f2bf5b..07ebbaf4dbbd 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatOutputPartStateCache.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatOutputPartStateCache.ts @@ -12,6 +12,7 @@ import { InstantiationType, registerSingleton } from '../../../../../../platform export interface IOutputPartState { height: number; webviewState?: string; + showingSource?: boolean; } export const IChatOutputPartStateCache = createDecorator('IChatOutputPartStateCache'); @@ -65,7 +66,11 @@ export class ChatOutputPartStateCache implements IChatOutputPartStateCache { for (const key in data) { const state = data[key]; if (typeof state.height === 'number') { - this._cache.set(key, { height: state.height, webviewState: typeof state.webviewState === 'string' ? state.webviewState : undefined }); + this._cache.set(key, { + height: state.height, + webviewState: typeof state.webviewState === 'string' ? state.webviewState : undefined, + showingSource: typeof state.showingSource === 'boolean' ? state.showingSource : undefined, + }); } } } catch { diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts index 24282524ceec..83571b4eff0d 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatProgressContentPart.ts @@ -38,6 +38,7 @@ import { ChatWorkingProgressLogo } from '../chatWorkingLogo.js'; import { autorun, constObservable, derived, observableValue, transaction } from '../../../../../../base/common/observable.js'; import { Link } from '../../../../../../platform/opener/browser/link.js'; import { animateChatProgress } from '../chatProgressAnimation.js'; +import { ChatActivityLabelTransition } from './chatActivityLabelTransition.js'; import { ChatDropdownPillActionViewItem } from '../../../../../browser/chatDropdownPill.js'; import { ChatPillsWidget, type IChatPill } from '../../../../../browser/chatPills.js'; import { sessionBackgroundShellsPillOptions, sessionSubagentsPillOptions } from '../../sessionChatPillOptions.js'; @@ -220,6 +221,11 @@ export class ChatProgressContentPart extends Disposable implements IChatContentP } } + /** The element showing the message, which is replaced when the message changes. */ + protected get messageElement(): HTMLElement | undefined { + return this.renderedMessage.value?.element; + } + updateMessage(content: IMarkdownString): void { if (this.isHidden) { return; @@ -350,6 +356,7 @@ export class ChatProgressSubPart extends Disposable { } const WORKING_LABEL_MIN_DWELL_MS = 1200; +const WORKING_LABEL_ROTATION_MS = 10_000; const DELAYED_PROGRESS_MESSAGE_TIMEOUT_MS = 90_000; const lastPickedWorkingLabelByElement = new WeakMap(); const lastPickedLegacyWorkingLabelByElement = new Map(); @@ -375,6 +382,26 @@ function pickLegacyWorkingLabel(elementId: string, configurationService: IConfig return label; } +function pickNextWorkingLabel(configurationService: IConfigurationService, current: string | undefined): string { + const fun = maybePickFunWorkingMessage(configurationService); + if (fun && fun !== current) { + return fun; + } + const pool = buildPhrasePool(defaultThinkingMessages, configurationService); + const alternatives = pool.filter(label => label !== current); + const candidates = alternatives.length ? alternatives : pool; + return candidates[Math.floor(Math.random() * candidates.length)]; +} + +/** Replaces the phrase {@link pickWorkingLabel} keeps for the running activity, so a long one does not look stalled. */ +function replaceWorkingLabel(element: ChatTreeItem, configurationService: IConfigurationService): void { + const existing = lastPickedWorkingLabelByElement.get(element); + if (existing) { + existing.label = pickNextWorkingLabel(configurationService, existing.label); + existing.pickedAt = Date.now(); + } +} + /** Keeps labels stable within an activity and gives new phrases a minimum dwell time. */ export function pickWorkingLabel(element: ChatTreeItem, configurationService: IConfigurationService, progressStep?: number): string { if (progressStep === undefined) { @@ -390,13 +417,7 @@ export function pickWorkingLabel(element: ChatTreeItem, configurationService: IC } } - const fun = maybePickFunWorkingMessage(configurationService); - const label = fun && fun !== existing?.label ? fun : (() => { - const pool = buildPhrasePool(defaultThinkingMessages, configurationService); - const alternatives = pool.filter(label => label !== existing?.label); - const candidates = alternatives.length ? alternatives : pool; - return candidates[Math.floor(Math.random() * candidates.length)]; - })(); + const label = pickNextWorkingLabel(configurationService, existing?.label); lastPickedWorkingLabelByElement.set(element, { label, pickedAt: now, progressStep }); return label; } @@ -415,6 +436,8 @@ const imageGenerationMessageIntervalMs = 4000; export class ChatWorkingProgressContentPart extends ChatProgressContentPart implements IChatContentPart { private explicitContent: IMarkdownString | undefined; + /** The latest requested label, which the persistent footer may still be wiping to. */ + private targetContent: IMarkdownString; private isActive: boolean; private progressStep: number | undefined; private showDelayedProgressMessage: boolean; @@ -423,8 +446,10 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl private responseComplete = false; private readonly contextElement: ChatTreeItem; private readonly workingLogo: ChatWorkingProgressLogo | undefined; + private readonly labelTransition: ChatActivityLabelTransition | undefined; private readonly delayedProgressMessageScheduler: RunOnceScheduler | undefined; private readonly imageGenerationMessageScheduler: RunOnceScheduler | undefined; + private readonly workingLabelRotationScheduler: RunOnceScheduler | undefined; private imageGeneration: boolean; private imageGenerationMessageIndex = 0; private readonly backgroundActivity = observableValue(this, undefined); @@ -471,8 +496,18 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl this.workingLogo.domNode.classList.add('chat-working-logo-compact'); this.workingLogo.setActive(isActive); this.progressIconElement.appendChild(this.workingLogo.domNode); + this.labelTransition = this._register(instantiationService.createInstance(ChatActivityLabelTransition, { + getElement: () => this.messageElement, + shouldAnimate: () => this.targetContent.value !== this.currentContent.value, + showTarget: () => { + if (this.targetContent.value !== this.currentContent.value) { + this.updateMessage(this.targetContent); + } + }, + })); } this.explicitContent = explicitContent; + this.targetContent = this.currentContent; this.isActive = isActive; this.imageGeneration = imageGeneration; this.progressStep = workingProgress.progressStep; @@ -555,11 +590,15 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl this.imageGenerationMessageScheduler = this.workingLogo ? this._register(new RunOnceScheduler(() => this.rotateImageGenerationMessage(), imageGenerationMessageIntervalMs)) : undefined; + this.workingLabelRotationScheduler = this.workingLogo + ? this._register(new RunOnceScheduler(() => this.rotateWorkingLabel(), WORKING_LABEL_ROTATION_MS)) + : undefined; if (this.workingLogo && isResponseVM(context.element)) { this._register(context.element.model.onDidChange(() => this.onResponseActivity())); } this.updateDelayedProgressMessageScheduler(); this.updateImageGenerationMessageScheduler(); + this.updateWorkingLabelRotationScheduler(); // Keep the replacement anchor, but never leave disposed progress visible. this._register(toDisposable(() => hide(this.domNode))); @@ -576,6 +615,7 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl } this.updateActiveState(); this.updateImageGenerationMessageScheduler(); + this.updateWorkingLabelRotationScheduler(); this.onResponseActivity(); })); } @@ -589,7 +629,7 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl } get workingLabel(): string { - return renderAsPlaintext(this.currentContent); + return renderAsPlaintext(this.targetContent); } /** Returns whether the rendered progress changed. */ @@ -617,8 +657,9 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl } this.updateDelayedProgressMessageScheduler(shouldResetDelayedProgress); this.updateImageGenerationMessageScheduler(); + this.updateWorkingLabelRotationScheduler(previousProgressStep !== progressStep); const resolvedContent = this.resolveWorkingContent(); - if (this.workingLogo && content?.value === previousExplicitContent?.value && resolvedContent.value === this.currentContent.value && isActive === previousIsActive && !backgroundActivityChanged) { + if (this.workingLogo && content?.value === previousExplicitContent?.value && resolvedContent.value === this.targetContent.value && isActive === previousIsActive && !backgroundActivityChanged) { return false; } const shouldAnnounce = announce && !!this.workingLogo @@ -627,7 +668,7 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl if (this.workingLogo) { this.updateActiveState(); } - this.updateMessage(resolvedContent); + this.showWorkingContent(resolvedContent); transaction(tx => { if (backgroundActivityChanged) { this.backgroundActivity.set(backgroundActivity, tx); @@ -655,6 +696,18 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl this.setShimmerActive(active); } + /** Shows a label, which the persistent footer wipes to, and restarts the phrase rotation when it is a new one. */ + private showWorkingContent(content: IMarkdownString): void { + const changed = content.value !== this.targetContent.value; + this.targetContent = content; + if (this.labelTransition) { + this.labelTransition.update(); + } else { + this.updateMessage(content); + } + this.updateWorkingLabelRotationScheduler(changed); + } + private resolveWorkingContent(): IMarkdownString { if (this.imageGeneration) { return new MarkdownString().appendText(imageGenerationMessages[this.imageGenerationMessageIndex]); @@ -696,10 +749,35 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl return; } this.imageGenerationMessageIndex = (this.imageGenerationMessageIndex + 1) % imageGenerationMessages.length; - this.updateMessage(this.resolveWorkingContent()); + this.showWorkingContent(this.resolveWorkingContent()); this.updateImageGenerationMessageScheduler(); } + /** Only generic phrases rotate, once one has been shown for a while without new activity. Other labels name a state that still holds. */ + private shouldRotateWorkingLabel(): boolean { + return !this.explicitContent && !this.imageGeneration && !this.showingDelayedProgressMessage + && this.progressStep !== undefined && this.isActive && !this.responseComplete; + } + + private updateWorkingLabelRotationScheduler(reset = false): void { + if (!this.workingLabelRotationScheduler) { + return; + } + if (!this.shouldRotateWorkingLabel()) { + this.workingLabelRotationScheduler.cancel(); + } else if (reset || !this.workingLabelRotationScheduler.isScheduled()) { + this.workingLabelRotationScheduler.schedule(); + } + } + + private rotateWorkingLabel(): void { + if (!this.shouldRotateWorkingLabel()) { + return; + } + replaceWorkingLabel(this.contextElement, this.workingConfigurationService); + this.showWorkingContent(this.resolveWorkingContent()); + } + private onResponseActivity(): void { if (!this.showDelayedProgressMessage || !this.isActive) { return; @@ -707,7 +785,7 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl const wasShowingDelayedProgress = this.showingDelayedProgressMessage; this.showingDelayedProgressMessage = false; if (wasShowingDelayedProgress) { - this.updateMessage(this.resolveWorkingContent()); + this.showWorkingContent(this.resolveWorkingContent()); } this.updateDelayedProgressMessageScheduler(true); } @@ -723,7 +801,7 @@ export class ChatWorkingProgressContentPart extends ChatProgressContentPart impl } this.showingDelayedProgressMessage = true; const content = this.resolveWorkingContent(); - this.updateMessage(content); + this.showWorkingContent(content); if (this.workingConfigurationService.getValue(AccessibilityWorkbenchSettingId.VerboseChatProgressUpdates)) { status(stripIcons(renderAsPlaintext(content))); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionAnswerEditor.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionAnswerEditor.ts index 4e20a9a9183e..48f37e9392d9 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionAnswerEditor.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionAnswerEditor.ts @@ -48,11 +48,6 @@ export function getChatQuestionAnswerSessionResource(uri: URI): URI | undefined export interface IChatQuestionAnswerEditorOptions { readonly placeholder: string; - /** - * Placeholder shown while the editor is idle, i.e. unfocused and empty. Opts the editor into an idle style - * (see the `ghost` class on {@link ChatQuestionAnswerEditor.domNode}) until it gains focus or content. - */ - readonly idlePlaceholder?: string; readonly ariaLabel: string; readonly initialValue?: string; /** Chat session the answer belongs to. Used to route completions to the session's agent host. */ @@ -78,11 +73,9 @@ export class ChatQuestionAnswerEditor extends Disposable { private readonly _onDidPressEnter = this._register(new Emitter()); readonly onDidPressEnter: Event = this._onDidPressEnter.event; - private readonly _onDidFocus = this._register(new Emitter()); - readonly onDidFocus: Event = this._onDidFocus.event; - - private readonly _onDidBlur = this._register(new Emitter()); - readonly onDidBlur: Event = this._onDidBlur.event; + private readonly _onDidPressUpAtStart = this._register(new Emitter()); + /** Fires when Up is pressed with the cursor at the start of the answer, so focus can move to the content above. */ + readonly onDidPressUpAtStart: Event = this._onDidPressUpAtStart.event; /** Root element carrying the input-box styling. */ readonly domNode: HTMLElement; @@ -91,8 +84,6 @@ export class ChatQuestionAnswerEditor extends Disposable { private readonly _editor: CodeEditorWidget; private readonly _model: ITextModel; private readonly _maxHeight: number; - private readonly _placeholder: string; - private readonly _idlePlaceholder: string | undefined; private _width = 0; private _height = 0; @@ -128,8 +119,6 @@ export class ChatQuestionAnswerEditor extends Disposable { super(); this._maxHeight = options.maxHeight ?? DEFAULT_MAX_HEIGHT; - this._placeholder = options.placeholder; - this._idlePlaceholder = options.idlePlaceholder; this.domNode = dom.append(container, dom.$('.chat-question-answer-editor')); this._editorElement = dom.append(this.domNode, dom.$('.chat-question-answer-editor-input')); @@ -145,7 +134,7 @@ export class ChatQuestionAnswerEditor extends Disposable { const editorOptions: IEditorConstructionOptions = { ...getSimpleEditorOptions(configurationService), ariaLabel: options.ariaLabel, - placeholder: options.idlePlaceholder !== undefined && !options.initialValue ? options.idlePlaceholder : options.placeholder, + placeholder: options.placeholder, wordWrap: 'on', wrappingStrategy: 'advanced', overflowWidgetsDomNode: options.overflowWidgetsDomNode, @@ -175,30 +164,22 @@ export class ChatQuestionAnswerEditor extends Disposable { this._register(this._model.onDidChangeContent(() => { this._value = this._model.getValue(); - this._updateIdle(); this._onDidChangeValue.fire(this._value); })); - this._register(this._editor.onDidFocusEditorText(() => { - this._updateIdle(); - this._onDidFocus.fire(); - })); - this._register(this._editor.onDidBlurEditorText(() => { - this._updateIdle(); - this._onDidBlur.fire(); - })); - this._updateIdle(); - this._register(this._editor.onKeyDown(e => { - if (e.keyCode !== KeyCode.Enter || e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) { + if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || this.isSuggestWidgetVisible()) { return; } - if (this.isSuggestWidgetVisible()) { - return; + if (e.keyCode === KeyCode.Enter) { + e.preventDefault(); + e.stopPropagation(); + this._onDidPressEnter.fire(); + } else if (e.keyCode === KeyCode.UpArrow && this._isCursorAtStart()) { + e.preventDefault(); + e.stopPropagation(); + this._onDidPressUpAtStart.fire(); } - e.preventDefault(); - e.stopPropagation(); - this._onDidPressEnter.fire(); })); this._register(this._editor.onDidContentSizeChange(e => { @@ -236,17 +217,9 @@ export class ChatQuestionAnswerEditor extends Disposable { return !!SuggestContext.Visible.getValue(this._editor.contextKeyService); } - /** Toggles the ghost style and idle placeholder while the editor is unfocused and empty. */ - private _updateIdle(): void { - if (this._idlePlaceholder === undefined) { - return; - } - const idle = !this._value && !this._editor.hasTextFocus(); - if (idle === this.domNode.classList.contains('ghost')) { - return; - } - this.domNode.classList.toggle('ghost', idle); - this._editor.updateOptions({ placeholder: idle ? this._idlePlaceholder : this._placeholder }); + private _isCursorAtStart(): boolean { + const selections = this._editor.getSelections(); + return selections?.length === 1 && selections[0].isEmpty() && selections[0].startLineNumber === 1 && selections[0].startColumn === 1; } private _layout(): void { diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionCarouselPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionCarouselPart.ts index 632a967c5a0e..358c8c48928e 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionCarouselPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatQuestionCarouselPart.ts @@ -22,7 +22,7 @@ import { Button } from '../../../../../../base/browser/ui/button/button.js'; import { DomScrollableElement } from '../../../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { Checkbox } from '../../../../../../base/browser/ui/toggle/toggle.js'; import { IChatQuestion, IChatQuestionCarousel, IChatQuestionAnswerValue, IChatQuestionValidation, IChatSingleSelectAnswer, IChatMultiSelectAnswer } from '../../../common/chatService/chatService.js'; -import { findQuestionValidationFailure, getDisplayedQuestionText, getOptionsWithDefaultsFirst } from '../../../common/chatService/chatQuestionCarouselHelpers.js'; +import { findQuestionValidationFailure, getDisplayedQuestionText, getOptionsWithDefaultsFirst, isBooleanQuestion } from '../../../common/chatService/chatQuestionCarouselHelpers.js'; import { ChatQuestionCarouselData } from '../../../common/model/chatProgressTypes/chatQuestionCarouselData.js'; import { IChatContentPart, IChatContentPartRenderContext } from './chatContentParts.js'; import { IChatRendererContent, isResponseVM } from '../../../common/model/chatViewModel.js'; @@ -59,17 +59,6 @@ const ANSWERS_REVEAL_CONTEXT = 32; /** How far the scroll body moves for one arrow key press. */ const BODY_SCROLL_LINE_HEIGHT = 20; -/** - * Whether the question is a yes/no choice, the shape MCP elicitation and the agent host emit for boolean fields. - */ -function isBooleanQuestion(question: IChatQuestion): boolean { - const options = question.options; - return question.type === 'singleSelect' - && options?.length === 2 - && options.some(opt => opt.value === 'true') - && options.some(opt => opt.value === 'false'); -} - /** * The title renders as one line of inline markdown, so a leading block marker must not start a block: * "6. Timeframe" would otherwise render as an indented ordered list starting at 6. @@ -79,7 +68,8 @@ function escapeLeadingMarkdownBlockSyntax(value: string): string { } export interface IChatQuestionCarouselOptions { - onSubmit: (answers: Map | undefined) => void; + /** `byUser` is `true` only when the person submitted or dismissed the carousel themselves. */ + onSubmit: (answers: Map | undefined, byUser?: boolean) => void; onDidDismiss?: (answers: ReadonlyMap) => void; dismissLabel?: string; submissionAcknowledgement?: { @@ -173,12 +163,10 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent private _headerActionsContainer: HTMLElement | undefined; private _closeButtonContainer: HTMLElement | undefined; private _footerRow: HTMLElement | undefined; - private _footerRightContainer: HTMLElement | undefined; private _stepIndicator: HTMLElement | undefined; private _primaryButton: Button | undefined; private _primaryState: 'nav' | 'action' | undefined; private _primaryAnimations: Animation[] = []; - private _showingBooleanButtons = false; private _collapseButton: Button | undefined; private _maximizeButton: Button | undefined; private _bodyScrollable: DomScrollableElement | undefined; @@ -195,9 +183,10 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent private readonly _singleSelectItems: Map = new Map(); private readonly _multiSelectCheckboxes: Map = new Map(); private readonly _freeformAnswerEditors: Map = new Map(); + /** Custom answer text that a selected option overrides, kept so it survives navigating between questions. */ + private readonly _ignoredFreeformValues = new Map(); private readonly _inputBoxes: DisposableStore = this._register(new DisposableStore()); private readonly _questionRenderStore = this._register(new MutableDisposable()); - private readonly _footerPrimaryStore = this._register(new DisposableStore()); /** * Disposable store for interactive UI components (header, nav buttons, etc.) @@ -357,7 +346,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent interactiveStore.add(maximizeButton.onDidClick(() => this.toggleMaximized())); if (this._skipAllButton) { - interactiveStore.add(this._skipAllButton.onDidClick(() => this.ignore())); + interactiveStore.add(this._skipAllButton.onDidClick(() => this.ignore(true))); } // Capture phase, because buttons consume Escape themselves and would otherwise leave the card maximized. @@ -370,10 +359,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent // Escape closes the suggest widget; leave it to the editor. return; } - if (answerEditor && isBooleanQuestion(this.carousel.questions[this._currentIndex])) { - // Handled below by leaving the custom answer first. - return; - } e.preventDefault(); e.stopPropagation(); this.toggleMaximized(); @@ -390,15 +375,10 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent // Escape closes the suggest widget; leave it to the editor. return; } - if (event.keyCode === KeyCode.Escape && answerEditor && isBooleanQuestion(this.carousel.questions[this._currentIndex])) { - // Leaves the custom answer of a boolean question without dismissing the carousel or discarding the text. + if (event.keyCode === KeyCode.Escape && this.carousel.allowSkip) { e.preventDefault(); e.stopPropagation(); - this.domNode.focus(); - } else if (event.keyCode === KeyCode.Escape && this.carousel.allowSkip) { - e.preventDefault(); - e.stopPropagation(); - this.ignore(); + this.ignore(true); } else if (event.keyCode === KeyCode.Enter && (event.metaKey || event.ctrlKey)) { // Cmd/Ctrl+Enter submits immediately from anywhere e.preventDefault(); @@ -578,7 +558,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent if (!this.validateRequiredFields()) { return; } - this._options.onSubmit(this._answers); + this._options.onSubmit(this._answers, true); this.hideAndShowSummary(); } } @@ -594,7 +574,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent if (!this.validateRequiredFields()) { return; } - this._options.onSubmit(this._answers); + this._options.onSubmit(this._answers, true); this.hideAndShowSummary(); } @@ -690,7 +670,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this._singleSelectItems.clear(); this._multiSelectCheckboxes.clear(); this._freeformAnswerEditors.clear(); - this._footerPrimaryStore.clear(); this._focusAnswer = undefined; // Clear references to disposed elements @@ -708,7 +687,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this._bodyScrollable = undefined; this._answersContainer = undefined; this._footerRow = undefined; - this._footerRightContainer = undefined; this._stepIndicator = undefined; } @@ -743,8 +721,10 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent * Returns undefined to signal the carousel was ignored. * * Guarded on `carousel.isUsed` for the same reason as {@link skip}. + * + * @param byUser Whether the person dismissed the carousel themselves, rather than it being dismissed for them. */ - public ignore(): boolean { + public ignore(byUser = false): boolean { if (this._isSkipped || this.carousel.isUsed || !this.carousel.allowSkip) { return false; } @@ -752,7 +732,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this._options.onDidDismiss?.(new Map(this._answers)); this._isSkipped = true; - this._options.onSubmit(undefined); + this._options.onSubmit(undefined, byUser); // Dispose interactive UI and clear DOM this.clearInteractiveResources(); @@ -1055,7 +1035,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this._questionContainer.appendChild(this._validationMessageElement); // Render footer before observing so the scroll body is measured against its final available height. - this.renderFooter(question); + this.renderFooter(); // Track whether the body is pinned to the bottom so it stays there when an answer editor grows. let wasAtBottom = false; const isAtBottom = () => { @@ -1117,9 +1097,9 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent /** * Renders or updates the persistent footer: navigation arrows and step indicator on the left, - * the primary action (arrow/Next/Submit or Yes/No) on the right. + * the primary action (arrow/Next/Submit) on the right. */ - private renderFooter(question: IChatQuestion): void { + private renderFooter(): void { if (!this._footerRow) { const interactiveStore = this._interactiveUIStore.value; if (!interactiveStore) { @@ -1162,91 +1142,14 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this._footerRow.appendChild(leftControls); - this._footerRightContainer = dom.append(this._footerRow, dom.$('.chat-question-footer-right')); + const rightControls = dom.append(this._footerRow, dom.$('.chat-question-footer-right')); + this.renderPrimaryButton(rightControls, interactiveStore); this.domNode.append(this._footerRow); } - this.renderFooterPrimary(question); - this.updateFooterState(); - } - - /** - * Whether the footer answers the question with Yes/No buttons, which a boolean - * question stops doing once the user types a custom answer. - */ - private shouldShowBooleanButtons(question: IChatQuestion): boolean { - return isBooleanQuestion(question) && !this._freeformAnswerEditors.get(question.id)?.value; - } - - /** - * Renders the primary footer controls for the given question: Yes/No buttons for - * boolean questions, otherwise a single button that scrolls to the answers, or - * advances to the next question or submits once they are in view. - */ - private renderFooterPrimary(question: IChatQuestion, animate = false): void { - const container = this._footerRightContainer; - if (!container) { - return; - } - - // Re-rendering drops the focused control, so remember where focus was to restore it. - const focusedIndex = dom.isAncestorOfActiveElement(container) - ? Array.from(container.children).findIndex(child => dom.isAncestorOfActiveElement(child)) - : -1; - - this.cancelPrimaryAnimations(); - this._footerPrimaryStore.clear(); - dom.clearNode(container); - this._primaryButton = undefined; this._primaryState = undefined; - this._showingBooleanButtons = this.shouldShowBooleanButtons(question); - - if (this._showingBooleanButtons) { - this.renderBooleanButtons(container, question, this._footerPrimaryStore); - } else { - this.renderPrimaryButton(container, this._footerPrimaryStore); - } - - if (focusedIndex >= 0) { - const focusTarget = container.children[Math.min(focusedIndex, container.children.length - 1)]; - if (dom.isHTMLElement(focusTarget)) { - focusTarget.focus(); - } else { - this.domNode.focus(); - } - } - - if (animate && !this._accessibilityService.isMotionReduced()) { - for (const child of container.children) { - this._primaryAnimations.push(child.animate( - [{ transform: 'translateY(4px)', opacity: 0 }, { transform: 'none', opacity: 1 }], - { duration: 160, easing: 'ease-out' } - )); - } - } - } - - private renderBooleanButtons(container: HTMLElement, question: IChatQuestion, store: DisposableStore): void { - const recorded = this._answers.get(question.id); - const recordedValue = typeof recorded === 'object' ? (recorded as IChatSingleSelectAnswer).selectedValue : recorded; - const defaultOption = typeof question.defaultValue === 'string' - ? question.options?.find(opt => opt.id === question.defaultValue || opt.value === question.defaultValue) - : undefined; - const primaryValue = recordedValue ?? defaultOption?.value ?? 'true'; - - const entries = [ - { value: 'false', label: localize('chat.questionCarousel.no', "No") }, - { value: 'true', label: localize('chat.questionCarousel.yes', "Yes") }, - ]; - for (const { value, label } of entries) { - const button = store.add(new Button(container, { ...defaultButtonStyles, small: true, secondary: value !== primaryValue })); - button.label = label; - store.add(button.onDidClick(() => { - this._answers.set(question.id, { selectedValue: value, freeformValue: undefined } satisfies IChatSingleSelectAnswer); - this.persistDraftState(); - this.handleNextOrSubmit(); - })); - } + this.updatePrimaryState(); + this.updateFooterState(); } private renderPrimaryButton(container: HTMLElement, store: DisposableStore): void { @@ -1261,7 +1164,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent })); store.add(toDisposable(() => this.cancelPrimaryAnimations())); this._primaryButton = button; - this.updatePrimaryState(); } private getPrimaryActionLabel(): string { @@ -1390,9 +1292,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent this.carousel.questions.length ); } - if (question && this._footerRightContainer && this.shouldShowBooleanButtons(question) !== this._showingBooleanButtons) { - this.renderFooterPrimary(question, true); - } } private getLabelWithKeybinding(label: string, actionId: string): string { @@ -1403,13 +1302,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent } private renderInput(container: HTMLElement, question: IChatQuestion): void { - if (isBooleanQuestion(question)) { - // Answered with the footer Yes/No buttons, with an optional custom answer unless free-form input is disallowed. - if (question.allowFreeformInput !== false) { - this.renderBooleanFreeform(container, question); - } - return; - } switch (question.type) { case 'text': this.renderTextInput(container, question); @@ -1426,11 +1318,10 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent /** * Creates an answer editor in the container, tied to the lifetime of the rendered question. */ - private createAnswerEditor(container: HTMLElement, placeholder: string, initialValue: string | undefined, overrides?: { readonly idlePlaceholder: string; readonly ariaLabel: string }): ChatQuestionAnswerEditor { + private createAnswerEditor(container: HTMLElement, placeholder: string, initialValue: string | undefined): ChatQuestionAnswerEditor { const editor = this._inputBoxes.add(this._instantiationService.createInstance(ChatQuestionAnswerEditor, container, { placeholder, - idlePlaceholder: overrides?.idlePlaceholder, - ariaLabel: overrides?.ariaLabel ?? placeholder, + ariaLabel: placeholder, initialValue, sessionResource: this._options.sessionResource ?? this._context?.element?.sessionResource, overflowWidgetsDomNode: this._options.editorOverflowWidgetsDomNode, @@ -1440,29 +1331,6 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent return editor; } - /** - * Renders the custom answer editor of a boolean question. While idle it is a borderless "Something else…" row - * that takes on the input style once focused or filled in, so nothing shifts when the user starts typing. - */ - private renderBooleanFreeform(container: HTMLElement, question: IChatQuestion): void { - const previousAnswer = this._answers.get(question.id); - const previousFreeform = typeof previousAnswer === 'object' && previousAnswer !== null && hasKey(previousAnswer, { selectedValue: true }) - ? (previousAnswer as IChatSingleSelectAnswer).freeformValue - : undefined; - - const freeformEditor = this.createAnswerEditor(container, localize('chat.questionCarousel.describeAnswer', "Describe your answer"), previousFreeform, { - idlePlaceholder: localize('chat.questionCarousel.somethingElse', "Something else…"), - ariaLabel: localize('chat.questionCarousel.somethingElseLabel', "Something else"), - }); - this._inputBoxes.add(freeformEditor.onDidChangeValue(() => this.saveCurrentAnswer())); - this._freeformAnswerEditors.set(question.id, freeformEditor); - this._focusAnswer = () => freeformEditor.focus(); - - if (previousFreeform && this._shouldAutoFocus()) { - this._inputBoxes.add(dom.runAtThisOrScheduleAtNextAnimationFrame(dom.getWindow(container), () => freeformEditor.focus())); - } - } - private renderTextInput(container: HTMLElement, question: IChatQuestion): void { // Restore previous answer if exists const previousAnswer = this._answers.get(question.id); @@ -1483,6 +1351,7 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent } private renderSingleSelect(container: HTMLElement, question: IChatQuestion): void { + const booleanQuestion = isBooleanQuestion(question); const orderedOptions = getOptionsWithDefaultsFirst(question); const selectContainer = dom.$('.chat-question-list'); container.appendChild(selectContainer); @@ -1531,9 +1400,12 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent const listItems: HTMLElement[] = []; orderedOptions.forEach(({ option }, index) => { + const optionLabel = booleanQuestion + ? (option.value === 'true' ? localize('chat.questionCarousel.yes', "Yes") : localize('chat.questionCarousel.no', "No")) + : option.label; const listItem = dom.$('.chat-question-list-item'); listbox.addOption(listItem, `option-${question.id}`); - listItem.setAttribute('aria-label', localize('chat.questionCarousel.optionLabel', "Option {0}: {1}", index + 1, option.label)); + listItem.setAttribute('aria-label', localize('chat.questionCarousel.optionLabel', "Option {0}: {1}", index + 1, optionLabel)); const number = dom.$('.chat-question-list-number'); number.textContent = `${index + 1}`; @@ -1544,36 +1416,32 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent // Label with optional description (format: "Title - Description") const label = dom.$('.chat-question-list-label'); - const separatorIndex = option.label.indexOf(' - '); + const separatorIndex = optionLabel.indexOf(' - '); if (separatorIndex !== -1) { listItem.classList.add('has-description'); const titleSpan = dom.$('span.chat-question-list-label-title'); - titleSpan.textContent = option.label.substring(0, separatorIndex); + titleSpan.textContent = optionLabel.substring(0, separatorIndex); label.appendChild(titleSpan); const descSpan = dom.$('span.chat-question-list-label-desc'); - descSpan.textContent = option.label.substring(separatorIndex + 3); + descSpan.textContent = optionLabel.substring(separatorIndex + 3); label.appendChild(descSpan); } else { - label.textContent = option.label; + label.textContent = optionLabel; } listItem.appendChild(label); listItem.appendChild(indicator); - // if we select an option, clear text and go to next question + // Selecting an option answers with it, ignoring any custom answer, and goes to the next question this._inputBoxes.add(dom.addDisposableListener(listItem, dom.EventType.CLICK, (e: MouseEvent) => { e.preventDefault(); e.stopPropagation(); updateSelection(index); - const freeform = this._freeformAnswerEditors.get(question.id); - if (freeform) { - freeform.value = ''; - } this.handleNextOrSubmit(); })); this._inputBoxes.add(this._hoverService.setupDelayedHover(listItem, { - content: option.label, + content: optionLabel, position: { hoverPosition: HoverPosition.BELOW }, appearance: { showPointer: true } })); @@ -1582,7 +1450,8 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent listItems.push(listItem); }); - this._singleSelectItems.set(question.id, { items: listItems, selectedIndex, optionIndices: orderedOptions.map(o => o.originalIndex) }); + const selectionData = { items: listItems, selectedIndex, optionIndices: orderedOptions.map(o => o.originalIndex) }; + this._singleSelectItems.set(question.id, selectionData); // Paints the initial row and points `aria-activedescendant` at it. Deliberately not // `updateSelection`, which would commit an answer the user has not given yet. @@ -1598,8 +1467,16 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent freeformContainer.appendChild(freeformNumber); container.appendChild(freeformContainer); - const capturedFreeform = this.createAnswerEditor(freeformContainer, localize('chat.questionCarousel.enterCustomAnswer', 'Enter custom answer'), previousFreeform); + const capturedFreeform = this.createAnswerEditor(freeformContainer, localize('chat.questionCarousel.enterCustomAnswer', 'Enter custom answer'), previousFreeform ?? this._ignoredFreeformValues.get(question.id)); freeformEditor = capturedFreeform; + // The saved answer leaves out text that a selected option overrides, so keep it here when the question is unrendered. + this._inputBoxes.add(toDisposable(() => { + if (selectionData.selectedIndex >= 0 && capturedFreeform.value) { + this._ignoredFreeformValues.set(question.id, capturedFreeform.value); + } else { + this._ignoredFreeformValues.delete(question.id); + } + })); // clear when we start typing in freeform this._inputBoxes.add(capturedFreeform.onDidChangeValue(value => { @@ -1610,6 +1487,14 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent } })); + // Up from the start of the custom answer selects the last option instead, keeping the text + this._inputBoxes.add(capturedFreeform.onDidPressUpAtStart(() => { + if (listItems.length) { + updateSelection(listItems.length - 1); + listbox.focus(); + } + })); + this._freeformAnswerEditors.set(question.id, capturedFreeform); } @@ -1622,7 +1507,13 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent } let newIndex = data.selectedIndex; - if (event.keyCode === KeyCode.DownArrow) { + if (event.keyCode === KeyCode.DownArrow && freeformEditor && data.selectedIndex === listItems.length - 1) { + // Down from the last option moves on to the custom answer + e.preventDefault(); + updateSelection(-1); + freeformEditor.focus(); + return; + } else if (event.keyCode === KeyCode.DownArrow) { e.preventDefault(); newIndex = listbox.clampedIndex(data.selectedIndex + 1); } else if (event.keyCode === KeyCode.UpArrow) { @@ -1794,6 +1685,13 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent const capturedFreeform = this.createAnswerEditor(freeformContainer, localize('chat.questionCarousel.enterCustomAnswer', 'Enter custom answer'), previousFreeform); freeformEditor = capturedFreeform; this._inputBoxes.add(capturedFreeform.onDidChangeValue(() => this.saveCurrentAnswer())); + // Up from the start of the custom answer moves to the last option, keeping the custom answer + this._inputBoxes.add(capturedFreeform.onDidPressUpAtStart(() => { + if (listItems.length) { + focusedIndex = listItems.length - 1; + listItems[focusedIndex].focus(); + } + })); this._freeformAnswerEditors.set(question.id, capturedFreeform); } @@ -1807,7 +1705,11 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent return; } - if (event.keyCode === KeyCode.DownArrow) { + if (event.keyCode === KeyCode.DownArrow && freeformEditor && focusedIndex === listItems.length - 1) { + // Down from the last option moves on to the custom answer + e.preventDefault(); + freeformEditor.focus(); + } else if (event.keyCode === KeyCode.DownArrow) { e.preventDefault(); focusedIndex = Math.min(focusedIndex + 1, listItems.length - 1); listItems[focusedIndex].focus(); @@ -1868,40 +1770,23 @@ export class ChatQuestionCarouselPart extends Disposable implements IChatContent } case 'singleSelect': { - if (isBooleanQuestion(question)) { - // Yes/No is recorded by the footer buttons; only a custom answer is read from the editor. - const customAnswer = this._freeformAnswerEditors.get(question.id)?.value; - if (customAnswer) { - return { selectedValue: undefined, freeformValue: customAnswer } satisfies IChatSingleSelectAnswer; - } - const recorded = this._answers.get(question.id); - if (recorded === undefined) { - // The footer highlights the default, so it counts as the answer until the user picks. - return this.getDefaultAnswerForQuestion(question); - } - // A custom answer that was cleared is no longer an answer. - return typeof recorded === 'object' && recorded !== null && hasKey(recorded, { selectedValue: true }) && (recorded as IChatSingleSelectAnswer).freeformValue - ? undefined - : recorded; - } + // A selected option wins over the custom answer, which typing in it deselects; the text is kept but ignored. const data = this._singleSelectItems.get(question.id); let selectedValue: string | undefined = undefined; if (data && data.selectedIndex >= 0) { const originalIndex = data.optionIndices[data.selectedIndex]; selectedValue = originalIndex !== undefined ? question.options?.[originalIndex]?.value : undefined; } + + const freeformValue = this._freeformAnswerEditors.get(question.id)?.value || undefined; + if (selectedValue === undefined && freeformValue) { + return { selectedValue: undefined, freeformValue } satisfies IChatSingleSelectAnswer; + } // Find default option if nothing selected (defaultValue is the option id) if (selectedValue === undefined && typeof question.defaultValue === 'string') { const defaultOption = question.options?.find(opt => opt.id === question.defaultValue); selectedValue = defaultOption?.value; } - - // For single-select: if freeform is provided, use ONLY freeform (ignore selection) - const freeformValue = this._freeformAnswerEditors.get(question.id)?.value || undefined; - if (freeformValue) { - // Freeform takes priority - ignore selectedValue - return { selectedValue: undefined, freeformValue } satisfies IChatSingleSelectAnswer; - } if (selectedValue !== undefined) { return { selectedValue, freeformValue: undefined } satisfies IChatSingleSelectAnswer; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatReferencesContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatReferencesContentPart.ts index 48945e53439c..72136b330fd2 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatReferencesContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatReferencesContentPart.ts @@ -431,7 +431,7 @@ class CollapsibleListRenderer implements IListRenderer isPhase ? this.instantiationService.createInstance(FusionPhasePillActionViewItem, undefined, action, { ...options, showElapsedOnly: true }, false) : this.actionViewItemService.lookUp(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID)?.(action, options, this.instantiationService, dom.getWindow(container).vscodeWindowId) - ?? this.instantiationService.createInstance(OpenSubagentChatActionViewItem, undefined, action, options, !this.environmentService.isSessionsWindow), + ?? this.instantiationService.createInstance(OpenSubagentChatActionViewItem, undefined, action, options, !this.environmentService.isSessionsWindow && !ChatContextKeys.inSessionsChat.getValue(this.contextKeyService)), })); this._openChatToolbar.setActions([menuAction]); this._updateOpenChatOnlyMode(); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts index 0f47c0bcb530..f83d7d564627 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatSubagentOpenChat.ts @@ -3,6 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; import './media/chatSubagentOpenChat.css'; import { $, addDisposableListener, EventHelper, EventLike, EventType, isHTMLElement, WindowIntervalTimer } from '../../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../../base/browser/keyboardEvent.js'; @@ -879,6 +881,15 @@ export class OpenSubagentChatActionViewItem extends BaseActionViewItem { } } +/** Reads the session chat flag of the widget whose scoped instantiation service creates it. */ +class SessionsChatScope { + readonly isSessionsChat: boolean; + + constructor(@IContextKeyService contextKeyService: IContextKeyService) { + this.isSessionsChat = !!ChatContextKeys.inSessionsChat.getValue(contextKeyService); + } +} + class EditorOpenSubagentChatActionViewItemContribution extends Disposable implements IWorkbenchContribution { static readonly ID = 'workbench.contrib.editorOpenSubagentChatActionViewItem'; @@ -892,7 +903,8 @@ class EditorOpenSubagentChatActionViewItemContribution extends Disposable implem } const onDidRegister = this._register(new Emitter()); this._register(actionViewItemService.register(MenuId.ChatSubagentContent, CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, (action, options, instantiationService) => { - if (!(action instanceof MenuItemAction)) { + // A session chat opens its subagents' chats as the Agents window does, whatever window shows it + if (!(action instanceof MenuItemAction) || instantiationService.createInstance(SessionsChatScope).isSessionsChat) { return undefined; } return instantiationService.createInstance(OpenSubagentChatActionViewItem, undefined, action, options, true); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatThinkingContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatThinkingContentPart.ts index c88886f97e5e..2bf4f835e9bc 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatThinkingContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatThinkingContentPart.ts @@ -5,6 +5,7 @@ import { $, addDisposableListener, clearNode, DisposableResizeObserver, EventHelper, EventType, getActiveElement, getWindow, hide, isAncestorOfActiveElement, isHTMLElement, scheduleAtNextAnimationFrame, setVisibility } from '../../../../../../base/browser/dom.js'; import { alert } from '../../../../../../base/browser/ui/aria/aria.js'; +import { HoverStyle } from '../../../../../../base/browser/ui/hover/hover.js'; import { DomScrollableElement } from '../../../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { ScrollbarVisibility } from '../../../../../../base/common/scrollable.js'; import { IChatExternalEdit, IChatMarkdownContent, IChatTerminalToolInvocationData, IChatThinkingPart, IChatToolInvocation, IChatToolInvocationSerialized } from '../../../common/chatService/chatService.js'; @@ -33,7 +34,7 @@ import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { Lazy } from '../../../../../../base/common/lazy.js'; import { Emitter } from '../../../../../../base/common/event.js'; import { DisposableMap, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; -import { autorun, IObservable, IReader, observableValue } from '../../../../../../base/common/observable.js'; +import { autorun, IObservable, IReader, observableValue, runOnChange } from '../../../../../../base/common/observable.js'; import { IChatMarkdownAnchorService } from './chatMarkdownAnchorService.js'; import './media/chatThinkingContent.css'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; @@ -48,6 +49,7 @@ import { URI } from '../../../../../../base/common/uri.js'; import { IUriIdentityService } from '../../../../../../platform/uriIdentity/common/uriIdentity.js'; import { getToolGroupSummary } from './chatToolGroupSummary.js'; import { ChatActivityLabelTransition } from './chatActivityLabelTransition.js'; +import { ChatConversationReasoningPart } from './chatConversationReasoningPart.js'; import { formatElapsedTime } from '../../../common/chatProgressFormatting.js'; @@ -214,8 +216,12 @@ interface IConversationTitle { */ readonly key?: string; readonly finished?: boolean; + /** The time a finished title was requested with, so it is requested again once more of that time is recorded. */ + readonly duration?: number; /** Shows the title as text instead of rendering it as markdown, for titles that are already plain text. */ readonly plainText?: boolean; + /** Keeps a plain text title on one row, ending what does not fit with an ellipsis. */ + readonly singleRow?: boolean; } /** The latest reasoning or item in a conversation section, which its collapsed header names while running. */ @@ -230,6 +236,23 @@ const conversationReasoningKey = 'reasoning'; const conversationDefaultKey = 'default'; const conversationFinishedKey = 'finished'; +/** + * The first line of reasoning as plain text, for a header to preview. It is the whole line: + * the header shows as much of it as fits its row. There is none while that line is still + * streaming a bold span, which may yet be the heading that names the reasoning. + */ +function getReasoningPreview(text: string): string | undefined { + // Whitespace before the line is dropped, as it is from a line a heading is extracted from, so that + // an unfinished heading is recognized however the text starts. + const firstLine = text.trimStart().split(/\r?\n/, 1)[0]; + if (firstLine.startsWith('**') && !firstLine.includes('**', 2)) { + return undefined; + } + const preview = renderAsPlaintext(new MarkdownString(firstLine), { omitMarkdownSyntax: true }).replace(/\s+/g, ' ').trim(); + // Markdown syntax that has not been followed by any text yet, like a list marker, previews nothing. + return /[\p{L}\p{N}]/u.test(preview) ? preview : undefined; +} + /** * Metadata passed to {@link ChatThinkingContentPart.appendItem} to drive * title / icon extraction. The `kind` discriminates which payload is @@ -259,6 +282,14 @@ interface ILazyThinkingItem { } type ILazyItem = ILazyToolItem | ILazyThinkingItem; + +/** A row that lists reasoning among a conversation section's tool calls. */ +interface IConversationReasoningRow { + readonly element: HTMLElement; + readonly part: ChatConversationReasoningPart; + readonly store: DisposableStore; +} + const THINKING_SCROLL_MAX_HEIGHT = 200; const enum WorkingMessageCategory { @@ -268,7 +299,6 @@ const enum WorkingMessageCategory { } export const defaultThinkingMessages = [ - localize('chat.thinking.thinking.1', 'Thinking'), localize('chat.thinking.thinking.2', 'Reasoning'), localize('chat.thinking.thinking.3', 'Considering'), localize('chat.thinking.thinking.4', 'Analyzing'), @@ -358,12 +388,23 @@ export function buildPhrasePool(defaults: string[], configurationService: IConfi return [...defaults]; } -function getFinishedThinkingTitle(parts: readonly IChatThinkingPart[]): string { +/** The recorded time of the reasoning in `parts`, which is only known when it ran once. */ +function getReasoningDuration(parts: readonly IChatThinkingPart[]): number | undefined { const runs = parts.filter(part => extractTextFromPart(part).trim()); const duration = runs.length === 1 ? runs[0].reasoningDurationMs : undefined; - return duration !== undefined && Number.isFinite(duration) && duration >= 0 - ? getReasoningDurationLabel(duration) - : localize('chat.thinking.finishedThinking', "Finished thinking"); + return duration !== undefined && Number.isFinite(duration) && duration >= 0 ? duration : undefined; +} + +function getFinishedThinkingTitle(duration: number | undefined): string { + return duration === undefined + ? localize('chat.thinking.finishedThinking', "Finished thinking") + : getReasoningDurationLabel(duration); +} + +/** A section's title names what happened rather than ending a sentence, so it drops any closing period. */ +function withoutClosingPeriod(title: string): string { + // Covers the ideographic full stop (U+3002) and the ellipsis character (U+2026) as well. + return title.replace(/[\s.\u3002\u2026]+$/, '') || title; } /** @@ -429,6 +470,12 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem private lastExtractedTitle: string | undefined; private toolInvocationCount: number = 0; private appendedItemCount: number = 0; + /** How many of the appended items are reasoning rather than tool activity. */ + private reasoningItemCount: number = 0; + /** Which of {@link allThinkingParts} each reasoning container shows. */ + private readonly thinkingPartIndexByContainer = new WeakMap(); + private readonly reasoningRows = new Map(); + private readonly reasoningRowStore = this._register(new DisposableStore()); private isActive: boolean = true; private toolInvocations: (IChatToolInvocation | IChatToolInvocationSerialized)[] = []; private allThinkingParts: IChatThinkingPart[] = []; @@ -463,6 +510,8 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem private readonly _externalResourceWidget: ChatThinkingExternalResourceWidget; private readonly _pendingExternalResources = new Map(); private readonly _titleDetailRendered = this._register(new MutableDisposable()); + /** A title on a single row. Its hover shows the whole of it, as the row may end it early. */ + private readonly singleRowTitle = this._register(new MutableDisposable()); private readonly _pendingAppendRefresh = this._register(new MutableDisposable()); private readonly diffDataByPartId = new Map(); private readonly editResourcesByPartId = new Map(); @@ -523,7 +572,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem const extractedTitle = extractTitleFromThinkingContent(initialText) ?? localize('chat.thinking.header.initial', 'Thinking'); const initialTitle = streamingCompleted && !context.isToolChain - ? getFinishedThinkingTitle([content]) + ? getFinishedThinkingTitle(getReasoningDuration([content])) : context.suppressProgressShimmer && !context.isToolChain ? localize('chat.thinking.header.initial', 'Thinking') : extractedTitle; @@ -561,12 +610,13 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem if (this.isConversation && containsReasoning) { // Queue the first reasoning like later sections so it stays ahead of the tool calls that follow it. - this.textContainer = $('.chat-thinking-item.markdown-content'); + this.textContainer = this.createReasoningContainer(content); this.lazyItems.push({ kind: 'thinking', textContainer: this.textContainer, content }); } if (initialText.trim()) { this.appendedItemCount++; + this.reasoningItemCount++; } // Alert screen reader users that thinking has started. Conversation sections announce @@ -753,13 +803,19 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem } } - /** Names reasoning by its latest summary heading, which changes as the summary streams, or says Thinking without one. */ + /** + * Names reasoning by its latest summary heading, which changes as the summary streams. + * Without one it says Thinking, followed by the reasoning's first line as that streams. + */ private getReasoningActivity(content: IChatThinkingPart): IConversationActivity { - const heading = getThinkingHeaders(extractTextFromPart(content)).at(-1)?.title; + const text = extractTextFromPart(content); + const heading = getThinkingHeaders(text).at(-1)?.title; + const preview = heading === undefined ? getReasoningPreview(text) : undefined; return { - title: heading ?? this.thinkingTitle, + title: heading ?? (preview === undefined ? this.thinkingTitle : localize('chat.thinking.label', "{0}: {1}", this.thinkingTitle, preview)), key: heading === undefined ? conversationReasoningKey : `${conversationReasoningKey}:${heading}`, plainText: true, + singleRow: preview !== undefined, reasoning: { partId: content.id }, }; } @@ -773,7 +829,8 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem } this.pendingConversationReasoningId = undefined; const activity = this.getReasoningActivity(content); - if (activity.key !== current?.key || partId !== current.reasoning?.partId) { + // A preview keeps its key as its line streams, so the header follows it without wiping. + if (activity.key !== current?.key || partId !== current.reasoning?.partId || !thinkingTitleEqual(activity.title, current.title)) { this.setConversationActivity(activity); } } @@ -825,7 +882,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem if (target.finished) { this.setFinalizedTitle(getThinkingTitleValue(target.title)); } else { - this.setTitle(target.title, !target.key || target.plainText); + this.setTitle(target.title, !target.key || target.plainText, target.singleRow); } } finally { this.isShowingConversationTitle = false; @@ -916,8 +973,8 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem // with the latest streaming content. const hasLazyThinkingItems = this.lazyItems.some(item => item.kind === 'thinking'); if (this.currentThinkingValue && !hasLazyThinkingItems) { - this.textContainer = $('.chat-thinking-item.markdown-content'); - this.wrapper.appendChild(this.textContainer); + this.textContainer = this.createReasoningContainer(this.content); + this.appendReasoningContainer(this.textContainer); this.renderMarkdown(this.currentThinkingValue); } @@ -1344,7 +1401,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem } this.interruptConversationTitle(); - const duration = this.getGeneratedTitleDuration(); + const duration = this.getTitleDuration(); const displayTitle = duration === undefined ? title : localize('chat.thinking.titleWithDuration', "{0} - {1}", title, formatReasoningDuration(duration)); @@ -1499,6 +1556,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem } private updateDropdownClickability(knownContentHeight?: number): void { + this.syncReasoningRows(); if (this.fallbackTitle !== undefined && this.currentTitle === this.fallbackTitle) { const title = this.getFallbackTitle(); if (title !== this.currentTitle) { @@ -1506,6 +1564,11 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this.showFinalizedTitle(title); } } + // A finished conversation section's time can be recorded after its title was shown. + const finishedTitle = this.conversationTitleTarget; + if (finishedTitle?.finished && finishedTitle.duration !== this.getTitleDuration()) { + this.showFinalizedTitle(this.currentTitle); + } this.updateToolChainVisibility(); if (this.isVerboseToolChain) { return; @@ -1551,6 +1614,122 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this.updateToolChainVisibility(); } + /** Creates the element that shows the text of one of {@link allThinkingParts}. */ + private createReasoningContainer(content: IChatThinkingPart): HTMLElement { + const container = $('.chat-thinking-item.markdown-content'); + this.thinkingPartIndexByContainer.set(container, this.allThinkingParts.indexOf(content)); + return container; + } + + /** The reasoning runs with text, counting a run split into several parts once. */ + private getReasoningRuns(): IChatThinkingPart[] { + return [...new Set(this.allThinkingParts.map(part => this.thinkingPartSources?.get(part) ?? part))].filter(part => extractTextFromPart(part)); + } + + private getVisibleToolItemCount(): number { + return this.appendedItemCount - this.hiddenToolCallIds.size - this.reasoningItemCount; + } + + /** + * Whether a conversation section lists its reasoning as rows among its other items. + * A section that only reasoned once shows that reasoning directly instead. + */ + private listsReasoningAsRows(): boolean { + return this.isConversation && (this.getVisibleToolItemCount() > 0 || this.getReasoningRuns().length > 1); + } + + /** Adds a reasoning container to the body, in a row when the section lists its reasoning as rows. */ + private appendReasoningContainer(container: HTMLElement): void { + this.appendToWrapper(container); + this.syncReasoningRows(); + } + + private createReasoningRow(): IConversationReasoningRow { + const store = this.reasoningRowStore.add(new DisposableStore()); + const part = store.add(this.instantiationService.createInstance(ChatConversationReasoningPart, this.thinkingTitle, this.context)); + store.add(runOnChange(part.expanded, () => this._onDidChangeHeight.fire())); + const icon = createThinkingIcon(Codicon.thinking); + icon.setAttribute('aria-hidden', 'true'); + const row: IConversationReasoningRow = { element: $('.chat-thinking-tool-wrapper.chat-thinking-reasoning-row', undefined, icon, part.domNode), part, store }; + this.reasoningRows.set(row.element, row); + return row; + } + + /** The reasoning run a container starts. Containers that continue a run, like its later summary rows, have none. */ + private getContainerRun(container: Element): IChatThinkingPart | undefined { + const part = this.allThinkingParts[this.thinkingPartIndexByContainer.get(container) ?? -1]; + return part && (this.thinkingPartSources?.get(part) ?? part); + } + + private getReasoningRowRuns(row: IConversationReasoningRow): IChatThinkingPart[] { + const runs = new Set(); + for (const container of row.part.content.children) { + const run = this.getContainerRun(container); + if (run) { + runs.add(run); + } + } + return [...runs]; + } + + /** Whether a container belongs in a row, which holds one reasoning run however many parts it was split into. */ + private continuesReasoningRow(row: IConversationReasoningRow, container: Element): boolean { + const run = this.getContainerRun(container); + return !run || this.getReasoningRowRuns(row).every(rowRun => rowRun === run); + } + + /** Names how long a row's reasoning thought, or that it is still thinking. */ + private getReasoningRowTitle(row: IConversationReasoningRow): string { + const duration = getReasoningDuration(this.getReasoningRowRuns(row)); + const isCurrentActivity = !this.streamingCompleted && !!this.conversationActivity?.reasoning && this.textContainer?.parentElement === row.part.content; + return isCurrentActivity && duration === undefined ? this.thinkingTitle : getFinishedThinkingTitle(duration); + } + + /** + * Lists a conversation section's reasoning as rows once it has other items, shows it + * directly while it is all the section has, and keeps the rows' titles current. + */ + private syncReasoningRows(): void { + if (!this.isConversation || !this.wrapper) { + return; + } + // Moving reasoning takes keyboard focus from an element inside it, such as a link the user tabbed to. + const activeElement = getActiveElement(); + const focused = isHTMLElement(activeElement) && this.wrapper.contains(activeElement) ? activeElement : undefined; + if (this.listsReasoningAsRows()) { + let row: IConversationReasoningRow | undefined; + for (const child of Array.from(this.wrapper.children)) { + const existingRow = this.reasoningRows.get(child); + if (existingRow || !child.matches('.chat-thinking-item.markdown-content')) { + row = existingRow; + continue; + } + if (!row || !this.continuesReasoningRow(row, child)) { + row = this.createReasoningRow(); + child.before(row.element); + } + if (focused && child.contains(focused)) { + // A collapsed row keeps its text out of the document, so the row the user is in opens. + row.part.expand(); + } + row.part.content.appendChild(child); + } + } else { + for (const row of [...this.reasoningRows.values()]) { + row.element.replaceWith(...row.part.content.children); + this.reasoningRows.delete(row.element); + this.reasoningRowStore.delete(row.store); + } + } + if (focused && getActiveElement() !== focused) { + // A removed row's header cannot take focus back, so the section's header does. + (focused.isConnected ? focused : this._collapseButton?.element)?.focus({ preventScroll: true }); + } + for (const row of this.reasoningRows.values()) { + row.part.updateTitle(this.getReasoningRowTitle(row)); + } + } + private updateWorkingSpinnerVisibility(reader?: IReader): void { if (!this.wrapper || !this.workingSpinnerElement) { return; @@ -1829,6 +2008,11 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem if (!this.containsReasoning && this.restoreSingleItemToOriginalPosition()) { return; } + if (this.isConversation) { + // A conversation section is named by what it did, never by a reasoning heading or a generated title. + this.setFallbackTitle(); + return; + } const headers = this.getTitleHeaders(); if (headers.length === 1) { this.acceptGeneratedTitle(headers[0]); @@ -1901,6 +2085,8 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem if (this._store.isDisposed) { return; } + // Titles generated or saved as a sentence are corrected here, the one place they become the section's title. + title = withoutClosingPeriod(title); for (const part of this.allThinkingParts) { part.generatedTitle = title; const source = this.thinkingPartSources?.get(part); @@ -1998,26 +2184,81 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem } } + /** Names a finished section without a generated title: by its tool calls, or else by how long it reasoned. */ private getFallbackTitle(): string { - if (!this.isToolChain) { - return getFinishedThinkingTitle([...new Set(this.allThinkingParts.map(part => this.thinkingPartSources?.get(part) ?? part))]); + const toolItemCount = this.isConversation ? this.getVisibleToolItemCount() : this.appendedItemCount - this.hiddenToolCallIds.size; + if (!this.isToolChain && !(this.isConversation && toolItemCount > 0)) { + // Several runs only have a total in a conversation section, where a provider recorded each of them. + const duration = getReasoningDuration(this.getReasoningRuns()) ?? (this.isConversation ? this.getSectionDuration() : undefined); + return getFinishedThinkingTitle(duration); } - const visibleItemCount = this.appendedItemCount - this.hiddenToolCallIds.size; - if (this.isToolChain) { - const tools = this.toolInvocations.filter(tool => !this.hiddenToolCallIds.has(tool.toolCallId) && !IChatToolInvocation.isEffectivelyHidden(tool)); - const summary = getToolGroupSummary(tools, [...this.editResourcesByPartId.values()], visibleItemCount, this.uriIdentityService.extUri); - if (summary) { - return summary; - } + const summary = this.getToolSummary(toolItemCount); + if (summary) { + return summary; } - return visibleItemCount > 0 - ? visibleItemCount === 1 + return toolItemCount > 0 + ? toolItemCount === 1 ? localize('chat.thinking.finished.withStepsSingular', 'Finished with 1 step') - : localize('chat.thinking.finished.withStepsPlural', 'Finished with {0} steps', visibleItemCount) + : localize('chat.thinking.finished.withStepsPlural', 'Finished with {0} steps', toolItemCount) : localize('chat.thinking.finished', 'Finished Working'); } + private getVisibleTools(): (IChatToolInvocation | IChatToolInvocationSerialized)[] { + return this.toolInvocations.filter(tool => !this.hiddenToolCallIds.has(tool.toolCallId) && !IChatToolInvocation.isEffectivelyHidden(tool)); + } + + /** Summarizes the recognized activity among the section's visible tool items. */ + private getToolSummary(visibleToolItemCount: number): string | undefined { + return getToolGroupSummary(this.getVisibleTools(), [...this.editResourcesByPartId.values()], visibleToolItemCount, this.uriIdentityService.extUri); + } + + /** The time to show after a finished section's title. */ + private getTitleDuration(): number | undefined { + if (!this.isConversation) { + return this.getGeneratedTitleDuration(); + } + // A section that only reasoned names its time in its fallback title. + const namesOwnTime = this.fallbackTitle !== undefined && this.getVisibleToolItemCount() <= 0; + return namesOwnTime ? undefined : this.getSectionDuration(); + } + + /** + * The time a finished section spent on its reasoning and tool calls, counting tool calls + * that ran together once. It is unknown unless every one of them recorded its time. + */ + private getSectionDuration(): number | undefined { + if (!this.streamingCompleted) { + return undefined; + } + const runs = this.getReasoningRuns(); + const tools = this.getVisibleTools(); + let total = 0; + for (const run of runs) { + // Only a provider tells runs apart, so only its times can be added up. + const duration = run.reasoningTimingSource === 'provider' ? getReasoningDuration([run]) : undefined; + if (duration === undefined) { + return undefined; + } + total += duration; + } + const spans: [start: number, end: number][] = []; + for (const { startedAt, completedAt } of tools) { + if (startedAt === undefined || completedAt === undefined || !(completedAt >= startedAt)) { + return undefined; + } + spans.push([startedAt, completedAt]); + } + let coveredUntil = -Infinity; + for (const [start, end] of spans.sort((a, b) => a[0] - b[0])) { + if (end > coveredUntil) { + total += end - Math.max(start, coveredUntil); + coveredUntil = end; + } + } + return runs.length || tools.length ? total : undefined; + } + /** Counts each provider-recorded reasoning run once, excluding tool time and incomplete timing. */ private getGeneratedTitleDuration(): number | undefined { if (!this.streamingCompleted || this.fallbackTitle !== undefined) { @@ -2064,7 +2305,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem /** Shows a finished section's title, which a conversation section wipes in after its last activity. */ private showFinalizedTitle(title: string): void { if (this.isConversation) { - this.showConversationTitle({ title, key: conversationFinishedKey, finished: true }, true); + this.showConversationTitle({ title, key: conversationFinishedKey, finished: true, duration: this.getTitleDuration() }, true); } else { this.setFinalizedTitle(title); } @@ -2695,7 +2936,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem private materializeLazyItem(item: ILazyItem): void { if (item.kind === 'thinking') { // Materialize thinking container - this.appendToWrapper(item.textContainer); + this.appendReasoningContainer(item.textContainer); // Store reference to textContainer for updateThinking calls this.textContainer = item.textContainer; this.id = item.content.id; @@ -2748,16 +2989,17 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem return; } if (!this.textContainer && this.currentThinkingValue) { - this.lazyItems.push({ kind: 'thinking', textContainer: $('.chat-thinking-item.markdown-content'), content: this.content }); + this.lazyItems.push({ kind: 'thinking', textContainer: this.createReasoningContainer(this.content), content: this.content }); } if (source) { this.setThinkingPartSource(content, source); } this.appendedItemCount++; + this.reasoningItemCount++; this.allThinkingParts.push(content); const contentText = extractTextFromPart(content); this.recordReasoningContent(contentText); - this.textContainer = $('.chat-thinking-item.markdown-content'); + this.textContainer = this.createReasoningContainer(content); // Observe the new textContainer for child resizes in fixed scrolling mode if (this.childResizeObserver && this.fixedScrollingMode && !this.streamingCompleted) { this._register(this.childResizeObserver.observe(this.textContainer)); @@ -2766,7 +3008,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem // Use lazy rendering when collapsed to preserve order with tool items if (this.isExpanded() || this.hasExpandedOnce || (this.fixedScrollingMode && !this.streamingCompleted)) { // Render immediately when expanded - this.appendToWrapper(this.textContainer); + this.appendReasoningContainer(this.textContainer); this.id = content.id; this.updateThinking(content); } else { @@ -2798,7 +3040,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this.updateDropdownClickability(); } - protected override setTitle(title: ChatThinkingTitle, omitPrefix?: boolean): void { + protected override setTitle(title: ChatThinkingTitle, omitPrefix?: boolean, singleRow?: boolean): void { if (this.isVerboseToolChain || this.streamingCompleted || this.element.isComplete) { return; } @@ -2816,14 +3058,29 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this.interruptConversationTitle(); if (omitPrefix) { - this.clearTitleDetail(); - if (this._collapseButton) { - const labelElement = this._collapseButton.labelElement; - labelElement.textContent = ''; - const plainSpan = $('span'); - plainSpan.textContent = titleValue; - labelElement.appendChild(plainSpan); + const labelElement = this._collapseButton?.labelElement; + const shownSingleRow = singleRow ? this.singleRowTitle.value : undefined; + if (labelElement && shownSingleRow?.element.parentElement === labelElement) { + // Text streams into the title that is there and into its hover, which may be open. + shownSingleRow.element.textContent = titleValue; + shownSingleRow.hoverContent.textContent = titleValue; this.setAriaLabel(titleValue); + } else { + this.clearTitleDetail(); + if (labelElement) { + labelElement.textContent = ''; + const plainSpan = $(singleRow ? 'span.chat-thinking-title-single-row' : 'span'); + plainSpan.textContent = titleValue; + labelElement.appendChild(plainSpan); + if (singleRow) { + // The hover's content is an element, which the hover follows as its text changes. + const hoverContent = $('span'); + hoverContent.textContent = titleValue; + const hover = this.hoverService.setupDelayedHover(plainSpan, { content: hoverContent, style: HoverStyle.Pointer, persistence: { hideOnHover: true } }); + this.singleRowTitle.value = { element: plainSpan, hoverContent, dispose: () => hover.dispose() }; + } + this.setAriaLabel(titleValue); + } } this.forgetShimmerTitle(); this.currentTitle = titleValue; @@ -2856,6 +3113,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem // Dispose previous detail rendering this._titleDetailRendered.clear(); this._titleFileWidgetStore.clear(); + this.singleRowTitle.clear(); const markdownTitle = typeof title === 'string' ? new MarkdownString(title) : title; const result = this.chatContentMarkdownRenderer.render(markdownTitle); @@ -2871,7 +3129,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this._titleDetailRendered.value = result; const previousTitleDetail = this.titleDetailContainer; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const hasTitleLinks = result.element.querySelector('a') !== null; // Titles with links sit beside the button so the links stay interactive. this._collapseButton.element.parentElement?.classList.toggle('chat-thinking-title-beside-button', hasTitleLinks); @@ -2908,6 +3166,7 @@ export class ChatThinkingContentPart extends ChatThinkingStyleContentPart implem this._collapseButton?.element.parentElement?.classList.remove('chat-thinking-title-beside-button'); this._titleDetailRendered.clear(); this._titleFileWidgetStore.clear(); + this.singleRowTitle.clear(); } hasSameContent(other: IChatRendererContent, _followingContent: IChatRendererContent[], _element: ChatTreeItem): boolean { diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatTipContentPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatTipContentPart.ts index 989ffa2a1fdd..f2c26a578fc5 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatTipContentPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatTipContentPart.ts @@ -20,6 +20,7 @@ import { IContextKey, IContextKeyService } from '../../../../../../platform/cont import { IContextMenuService } from '../../../../../../platform/contextview/browser/contextView.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; import { IInstantiationService, ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../../../../platform/instantiation/common/serviceCollection.js'; import { IMarkdownRenderer, openLinkFromMarkdown } from '../../../../../../platform/markdown/browser/markdownRenderer.js'; import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; @@ -46,6 +47,8 @@ export class ChatTipContentPart extends Disposable { private readonly _inChatTipContextKey: IContextKey; private readonly _multipleChatTipsContextKey: IContextKey; + private readonly _contextKeyService: IContextKeyService; + private readonly _instantiationService: IInstantiationService; constructor( tip: IChatTip, @@ -53,8 +56,8 @@ export class ChatTipContentPart extends Disposable { @IChatTipService private readonly _chatTipService: IChatTipService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IMenuService private readonly _menuService: IMenuService, - @IContextKeyService private readonly _contextKeyService: IContextKeyService, - @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IContextKeyService contextKeyService: IContextKeyService, + @IInstantiationService instantiationService: IInstantiationService, @IOpenerService private readonly _openerService: IOpenerService, @ICommandService private readonly _commandService: ICommandService, @IChatEntitlementService private readonly _chatEntitlementService: IChatEntitlementService, @@ -69,6 +72,8 @@ export class ChatTipContentPart extends Disposable { ariaRoleDescription: localize('chatTipRoleDescription', "tip"), })); + this._contextKeyService = this._register(contextKeyService.createScoped(this.domNode)); + this._instantiationService = this._register(instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]))); this._inChatTipContextKey = ChatContextKeys.inChatTip.bindTo(this._contextKeyService); this._multipleChatTipsContextKey = ChatContextKeys.multipleChatTips.bindTo(this._contextKeyService); const focusTracker = this._register(dom.trackFocus(this.domNode)); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatConfirmationWidget.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatConfirmationWidget.css index 6ec7a1d0f2ac..f5990bae8876 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatConfirmationWidget.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatConfirmationWidget.css @@ -442,7 +442,7 @@ max-width: 100%; padding: 4px 6px 4px 0; border: none; - border-radius: 2px; + border-radius: var(--workbench-custom-buttons-corner-radius, 2px); background-color: unset; color: var(--vscode-descriptionForeground); } @@ -498,7 +498,7 @@ .chat-editing-session-actions .monaco-button.secondary.monaco-text-button.codicon { cursor: pointer; padding: 2px; - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); display: inline-flex; } @@ -549,6 +549,7 @@ border: none !important; } +.chat-confirmation-message-terminal-target, .chat-confirmation-message-terminal-reason { padding: var(--vscode-spacing-size40) var(--vscode-spacing-size80); @@ -561,6 +562,10 @@ } } +.chat-confirmation-message-terminal-target { + overflow-wrap: anywhere; +} + .chat-confirmation-message-terminal .chat-confirmation-message-terminal-disclaimer p:last-child { margin-bottom: 0 !important; padding: 4px 8px 0 8px; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatEditStatsButton.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatEditStatsButton.css index 23ec74c05403..feb54a7a6903 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatEditStatsButton.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatEditStatsButton.css @@ -10,7 +10,7 @@ padding: var(--vscode-spacing-size20) var(--vscode-spacing-size40); margin-block: calc(-1 * var(--vscode-spacing-size20)); margin-left: var(--vscode-spacing-sizeNone); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); gap: var(--vscode-spacing-size40); background: transparent; color: inherit; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatHtmlPreviewPart.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatHtmlPreviewPart.css new file mode 100644 index 000000000000..3fa6ed6378a8 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatHtmlPreviewPart.css @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.chat-html-preview:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: -1px; +} + +.chat-html-preview-notice { + padding-bottom: var(--vscode-spacing-size80); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-body2); +} + +.chat-html-preview-content { + height: 1.5em; + overflow: hidden; +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatNativeComponents.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatNativeComponents.css new file mode 100644 index 000000000000..b417f4e09ae0 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatNativeComponents.css @@ -0,0 +1,269 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* + * Native components in a chat response. The agent chooses components and semantic variants; this + * stylesheet owns how they look. Text follows the chat type scale, so it tracks the chat font + * settings, and every color is a theme token, so visuals follow the active theme. + */ + +/* + * The visual has no frame of its own, so its focus ring stands clear of the content instead of crossing + * it. The second selector outranks the workbench's inset ring for focusable elements. + */ +.chat-native-components:focus-visible, +.monaco-workbench .chat-native-components[tabindex="0"]:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: var(--vscode-spacing-size40); + border-radius: var(--vscode-cornerRadius-small); +} + +/* A click inside the visual focuses it as well. That needs no ring, and the workbench's inset one would cross the content. */ +.monaco-workbench .chat-native-components[tabindex="0"]:focus:not(:focus-visible) { + outline: none; +} + +.chat-native-components-notice { + padding-bottom: var(--vscode-spacing-size80); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-chat-font-size-body-s); +} + +/* Layout */ + +.chat-native-components-content, +.chat-native-stack, +.chat-native-disclosure-content { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size120); +} + +.chat-native-components-content { + color: var(--vscode-foreground); + user-select: text; +} + +/* Columns share the width equally and wrap to fewer columns, down to one, as the chat narrows. */ +.chat-native-columns { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 10em), 1fr)); + gap: var(--vscode-spacing-size120) var(--vscode-spacing-size160); + align-items: start; +} + +.chat-native-components-content > *, +.chat-native-stack > *, +.chat-native-columns > *, +.chat-native-disclosure-content > * { + min-width: 0; +} + +/* Text: a long unbroken string wraps rather than widening the chat. A table scrolls instead. */ + +.chat-native-components-content { + overflow-wrap: anywhere; +} + +.chat-native-table { + overflow-wrap: normal; +} + +/* A heading sits closer to what it introduces than to what precedes it. */ +.chat-native-text.heading { + margin-bottom: calc(var(--vscode-spacing-size60) * -1); + font-size: var(--vscode-chat-font-size-body-l); + font-weight: var(--vscode-fontWeight-semiBold); +} + +.chat-native-text.caption { + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-chat-font-size-body-s); +} + +/* Icons: outrank the workbench's base codicon size and the chat Markdown rules for inline icons. */ + +.chat-native-components .chat-native-components-content .chat-native-icon.codicon, +.interactive-item-container .value .rendered-markdown .chat-native-components .chat-native-icon.codicon { + position: static; + flex-shrink: 0; + font-size: var(--vscode-codiconFontSize-compact); +} + +/* A tone colors its icon only. Text keeps the foreground color, so its contrast never depends on the tone. */ + +.chat-native-icon.positive { + color: var(--vscode-charts-green); +} + +.chat-native-icon.negative { + color: var(--vscode-charts-red); +} + +.chat-native-icon.warning { + color: var(--vscode-charts-yellow); +} + +/* Metric: the value leads; its label and detail stay quiet. */ + +.chat-native-metric { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size20); +} + +.chat-native-metric-label, +.chat-native-metric-detail { + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-chat-font-size-body-s); +} + +.chat-native-metric-value { + font-size: var(--vscode-chat-font-size-body-xxl); + font-weight: var(--vscode-fontWeight-semiBold); + line-height: 1.2; +} + +.chat-native-metric-value, +.chat-native-metric-detail { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); +} + +/* Badge */ + +.chat-native-badges { + display: flex; + flex-wrap: wrap; + gap: var(--vscode-spacing-size60); +} + +.chat-native-badge { + display: inline-flex; + align-items: center; + gap: var(--vscode-spacing-size40); + box-sizing: border-box; + max-width: 100%; + padding: var(--vscode-spacing-size20) var(--vscode-spacing-size80); + border: var(--vscode-strokeThickness) solid var(--vscode-chat-requestBorder); + border-radius: var(--vscode-cornerRadius-circle); + font-size: var(--vscode-chat-font-size-body-s); + line-height: 1.4; +} + +/* Table: the same treatment as a Markdown table in a response. */ + +.chat-native-table-scroll { + overflow-x: auto; +} + +.chat-native-table { + border: var(--vscode-strokeThickness) solid var(--vscode-chat-requestBorder); + border-radius: var(--vscode-cornerRadius-medium); + border-collapse: separate; + border-spacing: 0; + text-align: start; +} + +.chat-native-table caption { + padding-bottom: var(--vscode-spacing-size40); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-chat-font-size-body-s); + text-align: start; +} + +.chat-native-table th, +.chat-native-table td { + padding: var(--vscode-spacing-size40) var(--vscode-spacing-size60); + border: var(--vscode-strokeThickness) solid var(--vscode-chat-requestBorder); + border-top: none; + border-left: none; + vertical-align: top; +} + +.chat-native-table th { + font-weight: var(--vscode-fontWeight-semiBold); +} + +.chat-native-table th:last-child, +.chat-native-table td:last-child { + border-right: none; +} + +.chat-native-table tbody tr:last-child td { + border-bottom: none; +} + +.chat-native-table .align-end, +.chat-native-chart-value { + font-variant-numeric: tabular-nums; + text-align: end; +} + +/* Bar chart: one row per bar, with the labels, bars and values aligned in shared columns. */ + +.chat-native-chart { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size60); +} + +.chat-native-chart-title { + font-weight: var(--vscode-fontWeight-semiBold); +} + +/* The values keep their width as long as the bars keep theirs, then wrap. */ +.chat-native-chart-plot { + display: grid; + grid-template-columns: fit-content(40%) minmax(40px, 1fr) minmax(0, max-content); + gap: var(--vscode-spacing-size60) var(--vscode-spacing-size80); + color: var(--vscode-charts-foreground); +} + +.chat-native-chart-row { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + align-items: center; +} + +.chat-native-chart-bar { + height: var(--vscode-spacing-size80); + border-radius: var(--vscode-cornerRadius-xSmall); + background-color: var(--vscode-charts-blue); +} + +/* Disclosure */ + +.chat-native-disclosure-summary { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); + width: fit-content; + max-width: 100%; + border-radius: var(--vscode-cornerRadius-small); + cursor: pointer; + list-style: none; +} + +.chat-native-disclosure-summary::-webkit-details-marker { + display: none; +} + +.chat-native-disclosure-summary:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: var(--vscode-spacing-size20); +} + +.chat-native-disclosure[open] > .chat-native-disclosure-summary > .chat-native-icon { + transform: rotate(90deg); +} + +/* Aligns the content with the summary text, past the chevron. */ +.chat-native-disclosure-content { + padding-block-start: var(--vscode-spacing-size80); + padding-inline-start: var(--vscode-spacing-size160); +} diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatPlanReview.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatPlanReview.css index 9c7d4eeed8ec..4e29c517075a 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatPlanReview.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatPlanReview.css @@ -42,6 +42,7 @@ /* In the Agents window / editor the surface is the editor background. */ .agent-sessions-workbench .interactive-session .chat-plan-review-container > .chat-confirmation-widget2.chat-plan-review, +.sessions-chat .interactive-session .chat-plan-review-container > .chat-confirmation-widget2.chat-plan-review, .editor-instance .interactive-session .chat-plan-review-container > .chat-confirmation-widget2.chat-plan-review { background-color: var(--vscode-editor-background); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionAnswerEditor.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionAnswerEditor.css index d205d64adfc2..faa8e38e3139 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionAnswerEditor.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionAnswerEditor.css @@ -21,28 +21,16 @@ width: 100%; } -/* Blend the editor into the input; the background layer must stay opaque, so paint it with the input color. */ -.chat-question-answer-editor .monaco-editor { +/* Outrank session-surface editor colors while keeping Monaco's background layers opaque. */ +.monaco-workbench .interactive-session .chat-question-carousel-container .chat-question-answer-editor .chat-question-answer-editor-input .monaco-editor { background-color: transparent; } -.chat-question-answer-editor .monaco-editor .monaco-editor-background { +.monaco-workbench .interactive-session .chat-question-carousel-container .chat-question-answer-editor .chat-question-answer-editor-input .monaco-editor .margin, +.monaco-workbench .interactive-session .chat-question-carousel-container .chat-question-answer-editor .chat-question-answer-editor-input .monaco-editor .monaco-editor-background { background-color: var(--vscode-input-background); } -/* Idle (unfocused and empty): same frame as any input; only the placeholder reads as an action. */ -.chat-question-answer-editor.ghost { - cursor: text; -} - -.chat-question-answer-editor.ghost .monaco-editor .editorPlaceholder { - color: var(--vscode-textLink-foreground); -} - .monaco-workbench:not(.monaco-reduce-motion) .chat-question-answer-editor { transition: border-color 150ms ease-out; - - .monaco-editor .editorPlaceholder { - transition: color 150ms ease-out; - } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionCarousel.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionCarousel.css index a8fae046b4cb..27862be4e377 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionCarousel.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatQuestionCarousel.css @@ -141,11 +141,6 @@ padding-top: 0; } - /* boolean questions are answered from the footer */ - .chat-question-answers:empty { - display: none; - } - /* some hackiness to get the focus looking right */ .chat-question-list-item:focus, .chat-question-list:focus { @@ -283,13 +278,21 @@ } } + /* The input frame wraps the whole row so the custom answer lines up with the options above it. */ .chat-question-freeform { - margin: 0; + margin: 4px 0 0; display: flex; flex-direction: row; align-items: center; - padding: 4px 8px; + padding: 0 calc(var(--vscode-spacing-size80) - var(--vscode-strokeThickness)); gap: 8px; + border: var(--vscode-strokeThickness) solid var(--vscode-input-border, var(--vscode-widget-border, transparent)); + border-radius: var(--vscode-cornerRadius-medium); + background-color: var(--vscode-input-background); + + &:focus-within { + border-color: var(--vscode-focusBorder); + } .chat-question-freeform-number { height: fit-content; @@ -299,6 +302,9 @@ flex: 1 1 0; width: auto; min-width: 0; + padding: 0; + border: none; + border-radius: 0; } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSystemNotificationContentPart.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSystemNotificationContentPart.css index 1251b00daf89..29d840800d94 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSystemNotificationContentPart.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatSystemNotificationContentPart.css @@ -49,11 +49,22 @@ padding: 0; } +/* Pointer focus stays quiet; keyboard focus keeps the workbench focus outline. */ +.chat-system-notification-disclosure-header.monaco-button:focus:not(:focus-visible) { + outline: none; +} + .chat-system-notification-disclosure-header > .codicon { flex-shrink: 0; line-height: inherit; } +/* Name the disclosure as well to outrank `.monaco-workbench .codicon[class*='codicon-']`, which otherwise + resets the chevron to the base codicon size. */ +.chat-system-notification-disclosure > .chat-system-notification-disclosure-header > .chat-collapsible-hover-chevron.codicon { + font-size: var(--vscode-codiconFontSize-compact); +} + .chat-system-notification-disclosure-header:hover { color: var(--vscode-foreground); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatThinkingContent.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatThinkingContent.css index 0942f4d04194..cf9b7750b2b7 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatThinkingContent.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatThinkingContent.css @@ -184,6 +184,28 @@ } } +/* A conversation lists each reasoning run as a row naming its time. The run's text opens + under the row in the same text column, like the details of a tool call. */ +.interactive-session .interactive-response.chat-persistent-progress .value .chat-thinking-box.chat-thinking-conversation .chat-thinking-tool-wrapper > .chat-used-context.chat-thinking-reasoning { + margin-left: 0; + padding-left: var(--vscode-spacing-size240); + + .chat-used-context-list.chat-thinking-reasoning-content { + margin: 0; + padding: 0; + border: none; + + > .chat-thinking-item.markdown-content { + padding: var(--chat-persistent-nested-gap) var(--vscode-spacing-size120) 0 0; + + &::before, + > .chat-thinking-icon { + display: none; + } + } + } +} + .interactive-session .interactive-response.chat-persistent-progress .value .chat-thinking-box:is(.chat-persistent-reasoning, .chat-thinking-conversation, .chat-tool-chain-collapsible:not(.chat-tool-chain-preview)) { &:not(.chat-used-context-collapsed) > .chat-used-context-label::after { box-sizing: border-box; @@ -205,6 +227,12 @@ } } + /* A conversation section's hook starts under its chevron, which sits on the text's edge, and still reaches the first row. */ + &.chat-thinking-conversation:not(.chat-used-context-collapsed) > .chat-used-context-label::after { + left: var(--chat-conversation-rail-left); + width: calc(var(--chat-persistent-hook-width) + var(--chat-persistent-rail-left) - var(--chat-conversation-rail-left)); + } + .chat-used-context-list.chat-thinking-collapsible { margin-left: var(--chat-persistent-nested-indent); padding-inline: 0; @@ -254,7 +282,12 @@ /* A conversation title with links sits beside its button; keep it in the button's text column and type size. */ .interactive-session .interactive-response .value .chat-thinking-box.chat-thinking-conversation > .chat-used-context-label.chat-thinking-title-beside-button { + /* The title gets its own text column, so its line matches a title inside the button and the header keeps its height. */ + display: flex; + align-items: flex-start; + > .monaco-button.monaco-icon-button { + flex-shrink: 0; padding-right: 0; /* The emptied label still spans the title's line, so the chevron centers on it. */ @@ -264,6 +297,7 @@ } > .rendered-markdown.chat-thinking-title-detail { + min-width: 0; font-size: var(--vscode-chat-font-size-body-s); } } @@ -276,6 +310,14 @@ --chat-persistent-icon-top: calc((var(--vscode-chat-font-size-body-m) * 1.5 - var(--vscode-codiconFontSize-compact)) / 2); --chat-persistent-rail-left: calc(var(--chat-persistent-icon-left) + var(--vscode-codiconFontSize-compact) / 2 - var(--vscode-strokeThickness) / 2); --chat-persistent-hook-width: calc(var(--chat-persistent-nested-indent) - var(--vscode-codiconFontSize-compact) / 2 - var(--vscode-spacing-size40) + var(--vscode-strokeThickness) / 2); + /* The compact chevron is drawn narrower than its box: where its ink starts in the box, and how long it is. */ + --chat-conversation-chevron-bearing: calc(var(--vscode-codiconFontSize-compact) / 3); + --chat-conversation-chevron-length: calc(var(--vscode-codiconFontSize-compact) * 2 / 3); + /* An open chevron's ink is wider, so it moves to start on the same edge, and its rail hangs from its middle. */ + --chat-conversation-chevron-open-shift: calc(var(--chat-conversation-chevron-bearing) - (var(--vscode-codiconFontSize-compact) - var(--chat-conversation-chevron-length)) / 2); + --chat-conversation-rail-left: calc(var(--chat-conversation-chevron-length) / 2 - var(--vscode-strokeThickness) / 2); + /* Where a conversation header's label starts, and so where the steps it discloses line up. */ + --chat-conversation-label-left: var(--vscode-spacing-size160); } /* Anchor the footer to the list's integer-sized row, not the fractional streaming content height. */ @@ -327,6 +369,7 @@ > .chat-thinking-conversation, > .chat-tool-chain-collapsible, .chat-tool-chain .chat-thinking-tool-wrapper > .chat-used-context, + .chat-thinking-conversation .chat-thinking-tool-wrapper > .chat-thinking-reasoning, .chat-tool-call-with-icon :is(.chat-terminal-thinking-collapsible, .chat-confirmation-widget-collapsible) { gap: 0; @@ -398,13 +441,35 @@ margin-right: calc(var(--vscode-spacing-size240) - var(--vscode-codiconFontSize-compact) - 0.2em); } -/* A conversation section's chevron turns to point down at its rows while open, like a collapsible's hover chevron. */ +/* A chevron centered in the icon gutter looks indented beside the response's text, because its glyph is + narrow. Conversation chevrons start on the text's edge instead, and their labels follow them. */ +.interactive-session .interactive-response .value > .completed-response-conversation > .completed-response-summary .chat-collapsible-hover-chevron.codicon, .interactive-session .interactive-response .value .chat-thinking-box.chat-thinking-conversation > .chat-used-context-label .monaco-button.monaco-icon-button > .codicon-chevron-right-compact { - transition: transform 180ms cubic-bezier(0.2, 0, 0, 1); + margin-left: calc(-1 * var(--chat-conversation-chevron-bearing)); + margin-right: calc(var(--chat-conversation-label-left) - var(--vscode-codiconFontSize-compact) + var(--chat-conversation-chevron-bearing)); } +.interactive-session .interactive-response .value > .completed-response-conversation > .completed-response-summary .chat-collapsible-hover-chevron.codicon.expanded, .interactive-session .interactive-response .value .chat-thinking-box.chat-thinking-conversation:not(.chat-used-context-collapsed) > .chat-used-context-label .monaco-button.monaco-icon-button > .codicon-chevron-right-compact { - transform: rotate(90deg); + transform: translateX(var(--chat-conversation-chevron-open-shift)) rotate(90deg); +} + +/* In Conversation progress a completed response's steps disclose like a conversation section: the chevron + leads the label and stays visible, and the steps open under it in the label's text column. */ +.interactive-session .interactive-response.chat-persistent-progress > .value > .completed-response-conversation { + &::details-content { + margin-inline-start: var(--chat-conversation-rail-left); + padding-inline-start: calc(var(--chat-conversation-label-left) - var(--chat-conversation-rail-left) - var(--vscode-strokeThickness)); + } + + > .completed-response-summary .chat-collapsible-hover-chevron.codicon { + opacity: 1; + } +} + +/* A conversation section's chevron turns to point down at its rows while open, like a collapsible's hover chevron. */ +.interactive-session .interactive-response .value .chat-thinking-box.chat-thinking-conversation > .chat-used-context-label .monaco-button.monaco-icon-button > .codicon-chevron-right-compact { + transition: transform 180ms cubic-bezier(0.2, 0, 0, 1); } .monaco-reduce-motion .interactive-response .value .chat-thinking-box.chat-thinking-conversation > .chat-used-context-label .monaco-button.monaco-icon-button > .codicon-chevron-right-compact { @@ -464,6 +529,14 @@ .chat-thinking-title-detail-text { opacity: 0.7; } + + /* A title kept to one row ends in an ellipsis where that row does. */ + .chat-thinking-title-single-row { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } } > .chat-used-context-label .rendered-markdown.collapsible-title-content { @@ -479,6 +552,11 @@ display: inline; margin: 0; } + + /* The title's own text sets the header's line; smaller links, file pills, and code must not stretch it. */ + :is(a, code) { + line-height: 1; + } } > .chat-used-context-label > .rendered-markdown.chat-thinking-title-detail { diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatOtherClientToolProgressPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatOtherClientToolProgressPart.ts index df364e4ed3b1..30306d50416c 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatOtherClientToolProgressPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatOtherClientToolProgressPart.ts @@ -49,7 +49,7 @@ export class ChatOtherClientToolProgressPart extends BaseChatToolInvocationSubPa } }, })); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const skipLink = rendered.element.querySelector(`a[data-href="${skipHref}"]`); if (skipLink) { skipLink.setAttribute('role', 'button'); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolConfirmationSubPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolConfirmationSubPart.ts index c39659720cc6..4b7cf8b8d567 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolConfirmationSubPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolConfirmationSubPart.ts @@ -12,7 +12,7 @@ import { ErrorNoTelemetry } from '../../../../../../../base/common/errors.js'; import { createCommandUri, escapeMarkdownSyntaxTokens, MarkdownString, type IMarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { toDisposable } from '../../../../../../../base/common/lifecycle.js'; import Severity from '../../../../../../../base/common/severity.js'; -import { isObject } from '../../../../../../../base/common/types.js'; +import { isObject, isDefined } from '../../../../../../../base/common/types.js'; import { ILanguageService } from '../../../../../../../editor/common/languages/language.js'; import { localize } from '../../../../../../../nls.js'; import { ConfirmationOption } from '../../../../../../../platform/agentHost/common/state/protocol/state.js'; @@ -27,7 +27,7 @@ import { IPreferencesService } from '../../../../../../services/preferences/comm import { ITerminalChatService } from '../../../../../terminal/browser/terminal.js'; import { TerminalContribCommandId, TerminalContribSettingId } from '../../../../../terminal/terminalContribExports.js'; import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; -import { migrateLegacyTerminalToolSpecificData } from '../../../../common/chat.js'; +import { getTerminalExecutionTargetDescription, getTerminalExecutionTargetMessage, migrateLegacyTerminalToolSpecificData } from '../../../../common/chat.js'; import { isResponseVM } from '../../../../common/model/chatViewModel.js'; import { IChatToolInvocation, ToolConfirmKind, type IChatTerminalToolInvocationData, type ILegacyChatTerminalToolInvocationData } from '../../../../common/chatService/chatService.js'; import { ILanguageModelToolsService } from '../../../../common/tools/languageModelToolsService.js'; @@ -167,7 +167,10 @@ export class ChatTerminalToolConfirmationSubPart extends BaseChatToolInvocationS wordWrap: 'on', readOnly: isReadOnly, tabFocusMode: true, - ariaLabel: hasDistinctMessage ? localize('chat.terminal.confirmation.ariaLabel', "{0}\n{1}", titleText, messageText) : titleText + ariaLabel: [ + hasDistinctMessage ? localize('chat.terminal.confirmation.ariaLabel', "{0}\n{1}", titleText, messageText) : titleText, + getTerminalExecutionTargetDescription(terminalData), + ].filter(isDefined).join('\n') } }; const languageId = this.languageService.getLanguageIdByLanguageName(terminalData.presentationOverrides?.language ?? terminalData.language ?? 'sh') ?? 'shellscript'; @@ -204,10 +207,18 @@ export class ChatTerminalToolConfirmationSubPart extends BaseChatToolInvocationS } const elements = h('.chat-confirmation-message-terminal', [ h('.chat-confirmation-message-terminal-editor@editor'), + h('.chat-confirmation-message-terminal-target@target'), h('.chat-confirmation-message-terminal-reason@reason'), h('.chat-confirmation-message-terminal-disclaimer@disclaimer'), ]); append(elements.editor, editor.object.element); + // Always visible, unlike the details below that can fold into the risk badge's hover. + const executionTarget = getTerminalExecutionTargetMessage(terminalData); + if (executionTarget) { + this._appendMarkdownPart(elements.target, executionTarget, codeBlockRenderOptions); + } else { + elements.target.remove(); + } if (message && hasDistinctMessage) { this._appendMarkdownPart(elements.reason, typeof message === 'string' ? new MarkdownString().appendText(message) : message, codeBlockRenderOptions); } else { diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolProgressPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolProgressPart.ts index cbcd30ec4d55..2925ac9b3a75 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolProgressPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatTerminalToolProgressPart.ts @@ -110,6 +110,11 @@ function getTerminalFullOutputLabel(runId: string): string { */ const expandedStateByInvocation = new WeakMap(); +/** + * Invocations whose expanded state the user chose. Only these keep that state once the command is done. + */ +const userToggledInvocations = new WeakSet(); + // --- Command registrations for terminal tool progress toolbar --- CommandsRegistry.registerCommand(TerminalContribCommandId.FocusChatInstanceAction, async (_accessor: unknown, progressPart?: IChatTerminalToolProgressPart) => { @@ -293,7 +298,7 @@ class TerminalCommandDecoration extends Disposable { * - Long-running commands with output auto-expand after a short delay * - Fast commands that complete quickly don't auto-expand (prevents flickering) * - Failed commands can be configured to auto-expand via settings - * - Successful commands auto-collapse if output was auto-expanded + * - Finished commands collapse unless the user toggled them or their failure is configured to stay expanded */ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart implements IChatTerminalToolProgressPart { public readonly domNode: HTMLElement; @@ -326,7 +331,10 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart private readonly _outputSourceListener = this._register(new MutableDisposable()); private readonly _pendingOutputRestore = this._register(new MutableDisposable()); private readonly _decoration: TerminalCommandDecoration; - private _userToggledOutput: boolean = false; + /** Whether the command was running when this part was created, so its completion collapses the part once. */ + private _awaitsCompletion: boolean; + /** The wait for focus to leave the card before a finished command collapses. */ + private readonly _pendingFocusCollapse = this._register(new MutableDisposable()); private _isInThinkingContainer: boolean = false; private _usesCollapsibleWrapper: boolean = false; private _thinkingCollapsibleWrapper: ChatTerminalThinkingCollapsibleWrapper | undefined; @@ -380,6 +388,10 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart this._terminalData = terminalData; this._terminalCommandUri = terminalData.terminalCommandUri ? URI.revive(terminalData.terminalCommandUri) : undefined; this._isSerializedInvocation = (toolInvocation.kind === 'toolInvocationSerialized'); + this._awaitsCompletion = this._isInvocationRunning(); + if (!this._awaitsCompletion && !userToggledInvocations.has(toolInvocation)) { + expandedStateByInvocation.delete(toolInvocation); + } const elements = h('.chat-terminal-content-part@container', [ h('.chat-terminal-content-title@title', [ @@ -626,6 +638,11 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart this._isInThinkingContainer, )); this._thinkingCollapsibleWrapper = wrapper; + this._register(dom.addDisposableListener(wrapper.domNode, ChatCollapsibleContentPart.userToggleEvent, e => { + if (e.target === wrapper.domNode) { + userToggledInvocations.add(toolInvocation); + } + })); // Sync terminal output expansion with the collapsible wrapper. // Skip the initial run — initial state is handled separately. @@ -905,14 +922,16 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart /** * Determines whether the terminal output should auto-expand. * Returns false if already expanded, user has manually toggled, component is disposed, - * or if the invocation was previously expanded (to preserve state across re-renders). + * the command is no longer running, or if the invocation was previously expanded + * (to preserve state across re-renders). */ private _shouldAutoExpand(): boolean { return !this._outputView.isExpanded && - !this._userToggledOutput && + !userToggledInvocations.has(this.toolInvocation) && !this._store.isDisposed && (!this._forceExpandTerminalOutput || !expandedStateByInvocation.has(this.toolInvocation)) && - !expandedStateByInvocation.get(this.toolInvocation); + !expandedStateByInvocation.get(this.toolInvocation) && + this._isInvocationRunning(); } /** @@ -1002,7 +1021,7 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart this._updateToolbarContextKeys(terminalInstance, this._terminalData.terminalToolSessionId); const resolvedCommand = this._getResolvedCommand(terminalInstance); - this._handleCommandCompletion(resolvedCommand); + this._handleCommandCompletion(resolvedCommand?.exitCode); if (resolvedCommand?.endMarker) { commandDetectionListener.clear(); @@ -1013,7 +1032,7 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart const resolvedImmediately = await tryResolveCommand(); if (resolvedImmediately?.endMarker) { commandDetectionListener.clear(); - this._handleCommandCompletion(resolvedImmediately); + this._handleCommandCompletion(resolvedImmediately.exitCode); return; } }; @@ -1083,7 +1102,7 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart if (this._terminalData.terminalCommandId === cmd.id) { this._updateToolbarContextKeys(terminalInstance, this._terminalData.terminalToolSessionId); const resolvedCommand = this._getResolvedCommand(terminalInstance); - this._handleCommandCompletion(resolvedCommand); + this._handleCommandCompletion(resolvedCommand?.exitCode); } })); @@ -1092,31 +1111,55 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart // Check if the command was already resolved (e.g. during content replay) const resolvedCommand = this._resolveCommand(terminalInstance); if (resolvedCommand?.endMarker) { - this._handleCommandCompletion(resolvedCommand); + this._handleCommandCompletion(resolvedCommand.exitCode); } } /** - * Handles the completion of a terminal command by updating the UI state. - * This includes marking the collapsible wrapper as complete, auto-collapsing - * successful commands, and keeping failed commands expanded. - * - * @param resolvedCommand The completed terminal command with exit code information. + * Marks the collapsible wrapper complete and, once the command is done, collapses it + * unless the user chose its expanded state or its failure is configured to stay expanded. */ - private _handleCommandCompletion(resolvedCommand: ITerminalCommand | undefined): void { - // Update title to show completion state + private _handleCommandCompletion(exitCode: number | undefined): void { this.markCollapsibleWrapperComplete(); - // Auto-collapse on success (exit code 0) - if (resolvedCommand?.exitCode === 0 && this._outputView.isExpanded && !this._userToggledOutput && !this._forceExpandTerminalOutput) { - this._toggleOutput(false); + // The event can belong to another command in the same terminal + if (this._isInvocationRunning() || userToggledInvocations.has(this.toolInvocation) || this._forceExpandTerminalOutput) { + return; } - // Keep outer wrapper expanded on error for visibility const autoExpandFailures = this._configurationService.getValue(ChatConfiguration.AutoExpandToolFailures); - if (autoExpandFailures && resolvedCommand?.exitCode !== undefined && resolvedCommand.exitCode !== 0 && this._thinkingCollapsibleWrapper) { + if (autoExpandFailures && exitCode !== undefined && exitCode !== 0) { this.expandCollapsibleWrapper(); + } else if (this._awaitsCompletion) { + this._collapseWhenUnfocused(); + } + this._awaitsCompletion = false; + } + + /** + * Collapses the finished command once keyboard focus is outside its card, so the collapse + * never hides the output or control a user is on. + */ + private _collapseWhenUnfocused(): void { + const collapse = () => { + this._pendingFocusCollapse.clear(); + // The user may have chosen the card's state while the collapse waited. + if (!userToggledInvocations.has(this.toolInvocation)) { + this._thinkingCollapsibleWrapper?.collapse(); + void this._toggleOutput(false).catch(onUnexpectedError); + } + }; + if (!dom.isAncestorOfActiveElement(this.domNode)) { + collapse(); + return; } + this._pendingFocusCollapse.value = dom.addDisposableListener(this.domNode, dom.EventType.FOCUS_OUT, (event: FocusEvent) => { + // Focus that moves within the card, or stays in it while the window is inactive, has not left. + const movesWithinCard = dom.isHTMLElement(event.relatedTarget) && this.domNode.contains(event.relatedTarget); + if (!movesWithinCard && !dom.isAncestorOfActiveElement(this.domNode)) { + collapse(); + } + }); } private async _toggleOutput(expanded: boolean): Promise { @@ -1220,14 +1263,14 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart void this._outputView.refresh(); if (source.hasExited) { onCommandFinished.fire(); - this.markCollapsibleWrapperComplete(); + this._handleCommandCompletion(source.exitCode); } })); this._outputSourceListener.value = store; onCommandExecuted.fire(); if (source.hasExited) { onCommandFinished.fire(); - this.markCollapsibleWrapperComplete(); + this._handleCommandCompletion(source.exitCode); } this._decoration.update(); this._updateToolbarContextKeys(undefined, this._terminalData.terminalToolSessionId); @@ -1330,7 +1373,7 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart } public async toggleOutputFromAction(): Promise { - this._userToggledOutput = true; + userToggledInvocations.add(this.toolInvocation); type ToggleChatTerminalOutputTelemetryEvent = { previousExpanded: boolean; @@ -1352,7 +1395,7 @@ export class ChatTerminalToolProgressPart extends BaseChatToolInvocationSubPart } public async toggleOutputFromKeyboard(): Promise { - this._userToggledOutput = true; + userToggledInvocations.add(this.toolInvocation); if (!this._outputView.isExpanded) { await this._toggleOutput(true); this.focusOutput(); @@ -1444,6 +1487,8 @@ export class ChatTerminalToolOutputSection extends Disposable { private readonly _fullOutputLink = this._register(new MutableDisposable()); private _lastRenderedLineCount: number | undefined; private readonly _outputRelayout = this._register(new MutableDisposable()); + /** The latest requested state, so a collapse requested while the output still loads is not undone. */ + private _expandRequested = false; private readonly _onDidFocusEmitter = this._register(new Emitter()); public get onDidFocus() { return this._onDidFocusEmitter.event; } @@ -1506,6 +1551,7 @@ export class ChatTerminalToolOutputSection extends Disposable { } public async toggle(expanded: boolean): Promise { + this._expandRequested = expanded; const currentlyExpanded = this.isExpanded; if (expanded === currentlyExpanded) { if (expanded) { @@ -1524,6 +1570,9 @@ export class ChatTerminalToolOutputSection extends Disposable { await this._createScrollableContainer(); } await this._updateTerminalContent(); + if (!this._expandRequested) { + return false; + } // Only now show the expanded state (after content is ready) this._setExpanded(true); @@ -2251,6 +2300,10 @@ export class ChatTerminalThinkingCollapsibleWrapper extends ChatCollapsibleConte this.setExpanded(true); } + public collapse(): void { + this.setExpanded(false); + } + override hasSameContent(_other: IChatRendererContent, _followingContent: IChatRendererContent[], _element: ChatTreeItem): boolean { return false; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatToolConfirmationSubPart.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatToolConfirmationSubPart.ts index 1fd01c6608f7..1a3ddca8b388 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatToolConfirmationSubPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatToolConfirmationSubPart.ts @@ -162,7 +162,8 @@ export class ToolConfirmationSubPart extends AbstractToolConfirmationSubPart { ? toolInvocation.toolSpecificData : undefined; if (typeof message === 'string' && !disclaimer && !inputData) { - return dom.$('.message-wrapper', undefined, message); + // A paragraph, so that literal text is spaced like a Markdown message. + return dom.$('.message-wrapper', undefined, dom.$('p', undefined, message)); } else { const codeBlockRenderOptions: ICodeBlockRenderOptions = { hideToolbar: true, diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatDragAndDrop.ts b/src/vs/workbench/contrib/chat/browser/widget/chatDragAndDrop.ts index 18a6003c5fd6..60b1393368ac 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatDragAndDrop.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatDragAndDrop.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { DataTransfers } from '../../../../../base/browser/dnd.js'; -import { $, DragAndDropObserver } from '../../../../../base/browser/dom.js'; +import { $, DragAndDropObserver, getWindow } from '../../../../../base/browser/dom.js'; import { renderLabelWithIcons } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { coalesce } from '../../../../../base/common/arrays.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; @@ -15,7 +15,7 @@ import { Mimes } from '../../../../../base/common/mime.js'; import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { DraggedChatReferenceIdentifier, CodeDataTransfers, containsDragType, extractChatReferenceDropData, extractEditorsDropData, extractMarkerDropData, extractNotebookCellOutputDropData, extractSymbolDropData, LocalSelectionTransfer } from '../../../../../platform/dnd/browser/dnd.js'; +import { CodeDataTransfers, containsDragType, extractChatReferenceDropData, extractEditorsDropData, extractMarkerDropData, extractNotebookCellOutputDropData, extractSymbolDropData } from '../../../../../platform/dnd/browser/dnd.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IThemeService, Themable } from '../../../../../platform/theme/common/themeService.js'; import { ISharedWebContentExtractorService } from '../../../../../platform/webContentExtractor/common/webContentExtractor.js'; @@ -29,7 +29,7 @@ import { IChatAttachmentResolveService, ImageTransferData } from '../attachments import { isCrossAgentHostChatReferenceDrop, isSelfChatReferenceDrop, resolveChatReferenceDropEntry } from './chatReferenceDrop.js'; import { IChatInputStyles } from './input/chatInputPart.js'; import { convertStringToUInt8Array } from '../chatImageUtils.js'; -import { registerInputDropTarget } from '../../../../browser/dnd.js'; +import { isPassThroughDrag, registerInputDropTarget } from '../../../../browser/dnd.js'; enum ChatDragAndDropType { CHAT_REFERENCE, @@ -54,13 +54,6 @@ export class ChatDragAndDrop extends Themable { private overlayTextBackground: string = ''; private disableOverlay: boolean = false; - /** - * In-process transfer for a dragged chat reference. Readable during - * `dragover` (unlike the `dataTransfer` mime payload), so the self-reference - * guard can suppress the overlay when a chat is dragged onto its own input. - */ - private readonly chatReferenceTransfer = LocalSelectionTransfer.getInstance(); - constructor( private readonly widgetRef: () => IChatWidget | undefined, private readonly attachmentTarget: IChatAttachmentTarget, @@ -131,7 +124,18 @@ export class ChatDragAndDrop extends Themable { overlayContainer.appendChild(overlay); const disposable = new DisposableStore(); - disposable.add(registerInputDropTarget(inputTarget)); + // The pane around the input, such as a grid that opens what is dropped on it, leaves the input the drags it takes. + disposable.add(registerInputDropTarget(inputTarget, { + accepts: e => !this.disableOverlay && this.isDragEventSupported(e), + area: target, + getHint: passThroughModifier => passThroughModifier + ? localize({ key: 'chatInputDropHintWithModifier', comment: ['{0} is a key, such as Shift. Keep the underscores around it: they show it as a key.'] }, "Drag here or hold __{0}__ to attach to chat", passThroughModifier) + : localize('chatInputDropHint', "Drag here to attach to chat"), + })); + // Whether a pane around the target lets the drag through to it, such as the editor area of a chat editor while the key + // to drop into the editor is held. The input takes it then, as with the drag over it, until the drag leaves: also + // once the key is released, as the drop still attaches until the pane takes the drag again. + let letThrough = false; const observer = disposable.add(new DragAndDropObserver(target, { onDragOver: (e) => { if (this.disableOverlay) { @@ -141,7 +145,11 @@ export class ChatDragAndDrop extends Themable { e.stopPropagation(); e.preventDefault(); - if (target === this.currentActiveTarget) { + const entering = target !== this.currentActiveTarget; + letThrough = (letThrough && !entering) || isPassThroughDrag(target, e); + this.layoutOverlay(overlay, overlayContainer, target, inputTarget, e, letThrough); + + if (!entering) { return; } @@ -183,6 +191,37 @@ export class ChatDragAndDrop extends Themable { return { overlay, disposable, observer }; } + /** + * Fits the overlay to what takes the drop: the input while the drag is over it, as the pane around the input, such as + * a grid that opens what is dropped on it, can take the drag elsewhere, and while that pane lets the drag through to + * the target (`letThrough`); else the whole target, whose drags outside the input reach it only where nothing around + * it takes them. + */ + private layoutOverlay(overlay: HTMLElement, overlayContainer: HTMLElement, target: HTMLElement, inputTarget: HTMLElement, e: DragEvent, letThrough: boolean): void { + if (inputTarget === target) { + return; + } + + const input = inputTarget.getBoundingClientRect(); + const overInput = e.clientX >= input.left && e.clientX <= input.right && e.clientY >= input.top && e.clientY <= input.bottom; + if (input.width <= 0 || input.height <= 0 || !(overInput || letThrough)) { + overlay.style.top = overlay.style.left = overlay.style.width = overlay.style.height = overlay.style.borderRadius = ''; + return; + } + + // Measures before it writes, as this runs on every `dragover` + const container = overlayContainer.getBoundingClientRect(); + const top = input.top - container.top - overlayContainer.clientTop; + const left = input.left - container.left - overlayContainer.clientLeft; + // Shaped as the input is, whose corners depend on where it shows and on what is docked on it. + const borderRadius = getWindow(inputTarget).getComputedStyle(inputTarget).borderRadius; + overlay.style.top = `${top}px`; + overlay.style.left = `${left}px`; + overlay.style.width = `${input.width}px`; + overlay.style.height = `${input.height}px`; + overlay.style.borderRadius = borderRadius; + } + private onDragEnter(e: DragEvent, target: HTMLElement): void { const estimatedDropType = this.guessDropType(e); this.updateDropFeedback(e, target, estimatedDropType); @@ -255,18 +294,17 @@ export class ChatDragAndDrop extends Themable { * - a self-reference (a chat dropped onto its *own* input), and * - a cross-agent-host reference, which the owning host could never resolve. * - * The dragged chat's client resource is read from the in-process - * {@link LocalSelectionTransfer} (readable during `dragover`) with the - * `dataTransfer` mime payload as a fallback (readable on `drop`), and compared - * against this input's own client session resource. Both are opaque client - * URIs, so the workbench never touches an AHP chat URI. + * The dragged chat's client resource is read with {@link extractChatReferenceDropData} + * (from the drag in progress during `dragover`, from the `dataTransfer` payload + * on `drop`), and compared against this input's own client session resource. + * Both are opaque client URIs, so the workbench never touches an AHP chat URI. */ private guessChatReferenceDropType(e: DragEvent): ChatDragAndDropType | undefined { const sessionResource = this.widgetRef()?.viewModel?.model.sessionResource; if (!sessionResource || !isAgentHostTarget(getChatSessionType(sessionResource))) { return undefined; } - const droppedClientResource = this.getDraggedClientResource(e); + const droppedClientResource = extractChatReferenceDropData(e)?.clientResource; if (droppedClientResource !== undefined && (isSelfChatReferenceDrop(droppedClientResource, sessionResource.toString()) || isCrossAgentHostChatReferenceDrop(droppedClientResource, sessionResource.toString(), this.agentHostConnectionsService))) { @@ -275,21 +313,6 @@ export class ChatDragAndDrop extends Themable { return ChatDragAndDropType.CHAT_REFERENCE; } - /** - * The client resource of the dragged chat reference (used only for - * self-reference identity comparison). Prefers the in-process local transfer - * (available during `dragover`), falling back to the `dataTransfer` mime - * payload (only readable on `drop`). Returns `undefined` when neither source - * carries a chat reference. - */ - private getDraggedClientResource(e: DragEvent): string | undefined { - const local = this.chatReferenceTransfer.getData(DraggedChatReferenceIdentifier.prototype); - if (local && local.length > 0) { - return local[0].clientResource; - } - return extractChatReferenceDropData(e)?.clientResource; - } - private isDragEventSupported(e: DragEvent): boolean { // if guessed drop type is undefined, it means the drop is not supported const dropType = this.guessDropType(e); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts index abe776b7a9bd..d18be0335932 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts @@ -9,6 +9,7 @@ import { DeferredPromise, Delayer } from '../../../../../../base/common/async.js import { createRegExp } from '../../../../../../base/common/strings.js'; import { isDefined } from '../../../../../../base/common/types.js'; import { Event } from '../../../../../../base/common/event.js'; +import { URI } from '../../../../../../base/common/uri.js'; import { MutableDisposable } from '../../../../../../base/common/lifecycle.js'; import { Range as EditorRange } from '../../../../../../editor/common/core/range.js'; import { EditorOption } from '../../../../../../editor/common/config/editorOptions.js'; @@ -21,7 +22,7 @@ import { IHoverService } from '../../../../../../platform/hover/browser/hover.js import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; import { SimpleFindWidget } from '../../../../codeEditor/browser/find/simpleFindWidget.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; -import { ChatTreeItem, IChatFindController } from '../../chat.js'; +import { ChatTreeItem, IChatCodeBlockInfo, IChatFindController } from '../../chat.js'; import { IChatListItemTemplate } from '../chatListRenderer.js'; import { CodeBlockPart } from '../chatContentParts/codeBlockPart.js'; import { ChatFindCommandId } from './chatFindCommandIds.js'; @@ -36,6 +37,7 @@ export interface IChatFindHost { getTemplateDataForRequestId(requestId: string | undefined): IChatListItemTemplate | undefined; readonly onDidRerenderRow: Event; editorsInUse(): Iterable; + getCodeBlockInfoForEditor(uri: URI): IChatCodeBlockInfo | undefined; /** Scroll offset of the transcript, in list content space. */ getScrollTop(): number; setScrollTop(scrollTop: number): void; @@ -81,6 +83,10 @@ function nearestBlock(node: Node, root: HTMLElement): Element { } export function findMatchRangesInDom(root: HTMLElement, regex: RegExp, limit: number, excludedRoots: readonly HTMLElement[] = []): Range[] { + if (root.hasAttribute('data-chat-find-ignore')) { + return []; + } + const ignoredRoots: Element[] = [...excludedRoots]; const ownerDocument = root.ownerDocument; const nodes: { node: Text; start: number; end: number }[] = []; let buffer = ''; @@ -89,12 +95,18 @@ export function findMatchRangesInDom(root: HTMLElement, regex: RegExp, limit: nu const walker = ownerDocument.createTreeWalker(root, 5 /* NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT */); let current: Node | null; while ((current = walker.nextNode())) { - if (excludedRoots.some(candidate => candidate.contains(current))) { + if (ignoredRoots.some(candidate => candidate.contains(current))) { separatorPending = true; continue; } if (current.nodeType !== 3 /* Node.TEXT_NODE */) { - separatorPending ||= (current as Element).tagName === 'BR'; + const element = current as Element; + if (element.hasAttribute('data-chat-find-ignore')) { + ignoredRoots.push(element); + separatorPending = true; + } else { + separatorPending ||= element.tagName === 'BR'; + } continue; } const text = current.textContent; @@ -574,13 +586,16 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl return; } if (isCodeMatch(locatedMatch)) { + const uri = locatedMatch.codeBlock.uri; + const sourceRevealed = uri ? this.host.getCodeBlockInfoForEditor(uri)?.reveal?.() : false; const revealCodeMatch = () => { locatedMatch.codeBlock.editor.revealRangeInCenter(locatedMatch.range); this._repaintVisibleHighlights(); this._revealRect(this._codeMatchRect(locatedMatch)); this._completeSettle(); }; - if (openAncestorDisclosures(this.host.transcriptDomNode, locatedMatch.codeBlock.element)) { + const disclosureOpened = openAncestorDisclosures(this.host.transcriptDomNode, locatedMatch.codeBlock.element); + if (sourceRevealed || disclosureOpened) { this._revealScheduler.value = dom.scheduleAtNextAnimationFrame(this._targetWindow, revealCodeMatch); } else { revealCodeMatch(); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts b/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts index c894de1202a6..825e6c774617 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatListRenderer.ts @@ -8,7 +8,7 @@ import { renderFormattedText } from '../../../../../base/browser/formattedTextRe import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { IActionViewItemOptions } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; import { alert } from '../../../../../base/browser/ui/aria/aria.js'; -import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { createInstantHoverDelegate, getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { IManagedHover } from '../../../../../base/browser/ui/hover/hover.js'; import { CachedListVirtualDelegate, IListElementRenderDetails } from '../../../../../base/browser/ui/list/list.js'; import { IStickyScrollNodeSourceRange } from '../../../../../base/browser/ui/tree/abstractTree.js'; @@ -27,6 +27,7 @@ import { KeyCode } from '../../../../../base/common/keyCodes.js'; import { Disposable, DisposableMap, DisposableStore, IDisposable, MutableDisposable, dispose, toDisposable } from '../../../../../base/common/lifecycle.js'; import { ResourceMap } from '../../../../../base/common/map.js'; import { rewriteMarkdownLinks } from '../../../../../base/common/markdownLinks.js'; +import { marked } from '../../../../../base/common/marked/marked.js'; import { ScrollEvent } from '../../../../../base/common/scrollable.js'; import { FileAccess, Schemas } from '../../../../../base/common/network.js'; import { clamp, formatTokenCount } from '../../../../../base/common/numbers.js'; @@ -130,8 +131,9 @@ import { ChatImageGenerationBatchPart } from './chatContentParts/chatImageGenera import { ChatInlineAttachmentRenderer, ChatMarkdownDecorationsRenderer } from './chatContentParts/chatMarkdownDecorationsRenderer.js'; import { getInlineRequestAttachments, recoverAttachmentMentions } from '../../common/attachments/chatInlineAttachments.js'; import { ChatEditorOptions } from './chatOptions.js'; +import { ChatInputNotificationWidget } from './input/chatInputNotificationWidget.js'; import { ChatCodeBlockContentProvider, CodeBlockPart } from './chatContentParts/codeBlockPart.js'; -import { autorun, autorunPerKeyedItem, autorunSelfDisposable, derived, IObservable, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { autorun, autorunPerKeyedItem, autorunSelfDisposable, constObservable, derived, IObservable, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; import { basename, isEqual } from '../../../../../base/common/resources.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; @@ -151,9 +153,11 @@ const WORKING_CAUGHT_UP_DEBOUNCE_MS = 750; const DEFAULT_CHAT_ITEM_HORIZONTAL_PADDING = 40; export interface IChatListItemTemplate { + transcriptNotice?: ChatInputNotificationWidget; currentElement?: ChatTreeItem; renderedReadOnly?: boolean; renderedInputRequests?: boolean; + renderedHtmlPreviews?: boolean; renderedPersistentProgress?: boolean; renderedStickyProgress?: boolean; /** The persistent progress verbosity the template was rendered with, if persistent progress was on. */ @@ -292,22 +296,50 @@ export function getFinalResponseStartIndex(content: ReadonlyArray 0) { - const previous = content[index - 1]; - if (previous.kind === 'markdownContent') { - index--; - } else if (canCrossTool && (previous.kind === 'toolInvocation' || previous.kind === 'toolInvocationSerialized') && content[index - 2]?.kind === 'markdownContent') { - // A final tool can separate a detailed answer from its closing summary. - index -= 2; - canCrossTool = false; - } else { + index = getMarkdownRunStartIndex(content, index); + if (!allowSingleToolGap) { + return index; + } + + // A final tool call, and the reasoning around it, can separate a detailed answer from its closing summary. + let gapStartIndex = index; + let toolCount = 0; + while (gapStartIndex > 0) { + const previous = content[gapStartIndex - 1]; + if (previous.kind === 'toolInvocation' || previous.kind === 'toolInvocationSerialized') { + toolCount++; + } else if (previous.kind !== 'thinking') { break; } + gapStartIndex--; + } + if (toolCount !== 1) { + return index; + } + const answerStartIndex = getMarkdownRunStartIndex(content, gapStartIndex); + // Edit code blocks render as pills among the tool calls, so on their own they are work rather than an answer. + return content.slice(answerStartIndex, gapStartIndex).some(part => !isEditOnlyMarkdown(part)) ? answerStartIndex : index; +} + +function getMarkdownRunStartIndex(content: ReadonlyArray, index: number): number { + while (index > 0 && content[index - 1].kind === 'markdownContent') { + index--; } return index; } +/** Whether the Markdown holds edit code blocks and no other content. */ +function isEditOnlyMarkdown(part: IChatRendererContent): boolean { + if (part.kind !== 'markdownContent') { + return false; + } + if (part.codeblockUri?.isEdit) { + return true; + } + return hasEditCodeblockUriTag(part.content.value) + && marked.lexer(part.content.value).every(token => token.type === 'space' || (token.type === 'code' && hasEditCodeblockUriTag(token.text))); +} + function isKeptVisiblePart(part: IChatContentPart | undefined): boolean { return (part instanceof ChatAutoModeResolutionContentPart || part instanceof ChatSystemNotificationContentPart) && part.keepVisible; } @@ -943,6 +975,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer()); private readonly stickyProgressPart = this._register(new MutableDisposable()); + private readonly pendingStickyProgressUpdate = this._register(new MutableDisposable()); private stickyProgressContainer: HTMLElement | undefined; private stickyProgressResponse: IChatResponseViewModel | undefined; private stickyProgressAnchor: ChatWorkingProgressAnchor | undefined; @@ -979,6 +1012,9 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer()); + /** Shared by the attachment pills of requests, so that moving between them shows the next preview right away. */ + private readonly _requestAttachmentHoverDelegate = this._register(createInstantHoverDelegate()); + private readonly _editorPool: EditorPool; private readonly _toolEditorPool: EditorPool; private readonly _diffEditorPool: DiffEditorPool; @@ -1089,6 +1125,11 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer { + this.pendingStickyProgressUpdate.clear(); + this.updateStickyProgress(); + }); + } + updateStickyProgress(): void { + this.pendingStickyProgressUpdate.clear(); const container = this.stickyProgressContainer; const response = this.stickyProgressResponse; const part = this.stickyProgressPart.value; @@ -1489,13 +1547,13 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer { - if (this.environmentService.isSessionsWindow && subagentData?.chatResource) { + if (this.isSessionsChat && subagentData?.chatResource) { void this.commandService.executeCommand(CHAT_OPEN_AGENT_HOST_CHAT_COMMAND_ID, { chatResource: subagentData.chatResource }); } else { widget.reveal(response); } }; - const revealSubagentLabel = this.environmentService.isSessionsWindow && subagentTitle + const revealSubagentLabel = this.isSessionsChat && subagentTitle ? localize('openSubagentChat', "Open {0} Chat", subagentTitle) : undefined; const context: IChatContentPartRenderContext = { @@ -1886,6 +1944,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer(ChatConfiguration.HtmlPreviewEnabled) === true; const persistentProgress = this.rendererOptions.renderStyle !== 'minimal' && this.isPersistentProgressEnabled(); const stickyProgress = this.isStickyProgressEnabled(); const progressVerbosity = persistentProgress ? this.getPersistentProgressVerbosity() : undefined; - if (templateData.currentElement && (templateData.currentElement.id !== element.id || templateData.renderedReadOnly !== readOnly || templateData.renderedInputRequests !== renderInputRequests || templateData.renderedPersistentProgress !== persistentProgress || templateData.renderedStickyProgress !== stickyProgress || templateData.renderedProgressVerbosity !== progressVerbosity)) { + if (templateData.currentElement && (templateData.currentElement.id !== element.id || templateData.renderedReadOnly !== readOnly || templateData.renderedInputRequests !== renderInputRequests || templateData.renderedHtmlPreviews !== renderHtmlPreviews || templateData.renderedPersistentProgress !== persistentProgress || templateData.renderedStickyProgress !== stickyProgress || templateData.renderedProgressVerbosity !== progressVerbosity)) { this.traceLayout('renderChatTreeItem', () => `Rendering a different element or presentation state into the template, index=${index}`, index); const mappedTemplateData = this.templateDataByRequestId.get(templateData.currentElement.id); if (mappedTemplateData && (mappedTemplateData.currentElement?.id !== templateData.currentElement.id)) { @@ -1918,6 +1978,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer widget.focusInput(), + })); + templateData.transcriptNotice = notice; + templateData.elementDisposables.add(toDisposable(() => { templateData.transcriptNotice = undefined; })); + templateData.rowContainer.insertBefore(notice.domNode, templateData.footerToolbarContainer); + } + } } else { ChatContextKeys.responseVote.bindTo(templateData.contextKeyService).set(''); templateData.feedbackSurveyWidget.render(undefined); @@ -2087,8 +2160,8 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer !isExplicitFileOrImageVariableEntry(variable) && !isPasteVariableEntry(variable)); const isStickyAndEditing = !element.confirmation && isStickyScrollRow && element.id === this.viewModel?.editing?.id; if (!element.confirmation && !isStickyAndEditing) { - const requestMarkdown = isStickyScrollRow && requestSummary ? requestSummary : this.getRequestMarkdown(element, explicitFileOrImageVariables, new Set(inlineAttachments.keys())); + const requestMarkdown = isStickyScrollRow && requestSummary ? new MarkdownString(requestSummary) : this.getRequestMarkdown(element, explicitFileOrImageVariables, new Set(inlineAttachments.keys())); if (requestMarkdown) { - content = [{ content: new MarkdownString(requestMarkdown), kind: 'markdownContent' }]; + content = [{ content: requestMarkdown, kind: 'markdownContent' }]; } if (this.rendererOptions.renderStyle === 'minimal' && !element.isComplete) { @@ -3185,14 +3258,14 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer): string | undefined { + private getRequestMarkdown(element: IChatRequestViewModel, explicitFileOrImageVariables = element.variables.filter(isExplicitFileOrImageVariableEntry), inlineAttachmentParts?: ReadonlySet): MarkdownString | undefined { const markdown = isChatFollowup(element.message) - ? element.message.message + ? new MarkdownString(element.message.message) : this.markdownDecorationsRenderer.convertParsedRequestToMarkdown(element.sessionResource, this.getRenderedRequestMessage(element.message, element.variables), inlineAttachmentParts); const attachmentSummary = !element.messageText.trim() && !explicitFileOrImageVariables.length ? getExplicitFileOrImageAttachmentSummary(element.variables) : undefined; - return markdown.trim() ? markdown : attachmentSummary; + return markdown.value.trim() ? markdown : attachmentSummary ? new MarkdownString(attachmentSummary) : undefined; } /** @@ -3234,6 +3307,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer part instanceof ChatMarkdownContentPart && !part.isRenderComplete); + if (!(finalResponsePart instanceof ChatMarkdownContentPart) || revealingPart) { this.removeCompletedResponseDisclosure(templateData); - if (finalResponsePart instanceof ChatMarkdownContentPart) { - templateData.completedResponseDisclosureDisposables.add(Event.once(finalResponsePart.onDidFinishRendering)(() => { + if (revealingPart) { + templateData.completedResponseDisclosureDisposables.add(Event.once(revealingPart.onDidFinishRendering)(() => { this.updateCompletedResponseDisclosure(element, content, templateData, false); })); } @@ -4204,12 +4281,16 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer | undefined, part: ChatQuestionCarouselPart) => { + const handleSubmit = async (answers: Map | undefined, part: ChatQuestionCarouselPart, byUser?: boolean) => { if (carousel.isUsed) { // Voice can answer the same form, so a queued click may land after it // has been submitted. Applying it would replace the spoken answer and @@ -5694,6 +5779,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer handleSubmit(answers, part) + onSubmit: async (answers, byUser) => handleSubmit(answers, part, byUser) }); return part; } @@ -5749,14 +5835,14 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer handleSubmit(answers, part!) + onSubmit: async (answers, byUser) => handleSubmit(answers, part!, byUser) }); // If we couldn't render in the input part, fall back to inline rendering if (!part) { const fallbackPart = this.instantiationService.createInstance(ChatQuestionCarouselPart, carousel, context, { shouldAutoFocus, - onSubmit: async (answers) => handleSubmit(answers, fallbackPart) + onSubmit: async (answers, byUser) => handleSubmit(answers, fallbackPart, byUser) }); return fallbackPart; } @@ -5851,6 +5937,7 @@ export class ChatListItemRenderer extends Disposable implements ITreeRenderer this._currentLayoutWidth.get(), { codeBlockRenderOptions: this.rendererOptions.codeBlockRenderOptions, + renderHtmlPreviews: templateData.renderedHtmlPreviews, renderInlineAttachment: isRequestVM(element) ? this.createInlineRequestAttachmentRenderer(element) : undefined, }); markdownPart.addDisposable(markdownPart.onDidChangeHeight(() => this.fireItemHeightChange(templateData))); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts index bc80b3b2a154..e00df2a7a134 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts @@ -428,6 +428,12 @@ export class ChatListWidget extends Disposable { private _effectivePaddingBottom: number; private _scrollHeightReservation: { response: IChatResponseViewModel; height: number } | undefined; private readonly _pendingScrollHeightRelease = this._register(new MutableDisposable()); + /** + * Positions the scroll-down button once before the next paint. While a response streams, the + * button can be shown and hidden many times per frame as the content grows past the bottom and + * is revealed again, and each positioning reads layout. + */ + private readonly _scrollDownButtonPositionScheduler: dom.AnimationFrameScheduler; //#endregion @@ -533,6 +539,7 @@ export class ChatListWidget extends Disposable { this._effectivePaddingBottom = this._paddingBottom; this._lastItemIdContextKey = ChatContextKeys.lastItemId.bindTo(this.contextKeyService); this._container = container; + this._scrollDownButtonPositionScheduler = this._register(new dom.AnimationFrameScheduler(this._container, () => this.updateScrollDownButtonPosition())); // Toggle link-style for inline reference widgets based on configuration (single listener for all widgets) const updateInlineReferencesStyle = () => { @@ -770,7 +777,7 @@ export class ChatListWidget extends Disposable { // Handle scroll events (fire public event and manage scroll-down button) this._register(this._tree.onDidScroll((e) => { - this._renderer.updateStickyProgress(); + this._renderer.scheduleStickyProgressUpdate(); this._onDidScroll.fire(e); this.updateScrollDownButtonVisibility(); })); @@ -817,6 +824,7 @@ export class ChatListWidget extends Disposable { if (e.affectsConfiguration(ChatConfiguration.EditRequests) || e.affectsConfiguration(ChatConfiguration.CheckpointsEnabled) || e.affectsConfiguration(ChatConfiguration.RichLinks) + || e.affectsConfiguration(ChatConfiguration.HtmlPreviewEnabled) || e.affectsConfiguration(ChatConfiguration.ProgressBorder) || e.affectsConfiguration(ChatConfiguration.PersistentProgress) || e.affectsConfiguration(ChatConfiguration.PersistentProgressVerbosity)) { @@ -861,7 +869,7 @@ export class ChatListWidget extends Disposable { // Cloning a range never yields the anchors around it, so ask the selection what it // touches: otherwise a selection inside a link looks clean while the browser still // copies the enclosing anchor. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const touched = Array.from(this._container.querySelectorAll('a, img')) .filter(element => selection.containsNode(element, true)); if (!touched.length) { @@ -908,7 +916,7 @@ export class ChatListWidget extends Disposable { this._container.classList.toggle('chat-list-scrolled-to-bottom', isScrolledToBottom); // Scrolling cannot move the progress row; layout and its resize observer reposition a shown button. if (showButton !== wasShown) { - this.updateScrollDownButtonPosition(); + this._scrollDownButtonPositionScheduler.schedule(); } } @@ -922,6 +930,7 @@ export class ChatListWidget extends Disposable { * input even while no progress is shown. */ private updateScrollDownButtonPosition(): void { + this._scrollDownButtonPositionScheduler.cancel(); const button = this._scrollDownButton.element; const progress = this._workingProgressContainer; let bottom = ''; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatPetJumpGame.ts b/src/vs/workbench/contrib/chat/browser/widget/chatPetJumpGame.ts index 5ec6c5d44201..0882d6f41c0c 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatPetJumpGame.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatPetJumpGame.ts @@ -408,7 +408,7 @@ export class ChatPetJumpGame extends Disposable { getHelp(): string { return [ localize('chatPet.jump.help.overview', "Blobby's jump game starts when you activate the pet while it is sitting on the new-session welcome text. You can also choose Play Jump Game from the pet's context menu to move to that perch and start, including with reduced motion enabled. The randomly generated platforms belong only to the game. Your session, draft, and workspace are not changed."), - localize('chatPet.jump.help.controls', "Hold Space to charge a jump, then release it to launch. Blobby crouches as the charge builds. A longer charge jumps higher and farther. Left and Right Arrow make short hops; while holding Space, they choose the jump direction and turn Blobby's crouched pose. The direction is locked during flight. Walls bounce Blobby back. Missing a platform can drop Blobby onto a lower one. Falling past the starting platform ends the run and lets Blobby finish falling onto the input or another surface. If no surface catches Blobby, the normal respawn plays. Once Blobby has landed and recovered, Retry and Reset appear above the pet. Retry or R teleports Blobby to the last safe spot before the fall in the same game, restoring the platforms and progress from that point with no jump charge. A crumbling launch platform gets a fresh timer. Reset or Z teleports Blobby to the start of a new game with new platforms and zero hops. The shortcuts work only while Blobby or a recovery button is focused. Tab or the arrow keys move between the buttons; Enter or Space activates the focused button. Your high score is kept. The recovery prompt and its shortcuts disappear after five idle seconds. Hovering or focusing a recovery button pauses this timeout, and leaving the buttons starts a new five-second timeout. With screen reader optimization enabled, the prompt stays until you dismiss it or choose an action. Press Escape to dismiss the prompt."), + localize('chatPet.jump.help.controls', "Hold Space to charge a jump, then release it to launch. Blobby crouches as the charge builds. A longer charge jumps higher and farther. Left and Right Arrow make short hops; while holding Space, they choose the jump direction and turn Blobby's crouched pose. The direction is locked during flight. Walls bounce Blobby back. Missing a platform can drop Blobby onto a lower one. Falling past the starting platform ends the run and lets Blobby finish falling onto the input or another surface. If no surface catches Blobby, the normal respawn plays. Once Blobby has landed and recovered, Retry and Reset appear above the pet. Retry or R teleports Blobby to the last safe spot before the fall in the same game, restoring the platforms and progress from that point with no jump charge. All crumbling platforms are restored, including ones that fell earlier in the run. A crumbling launch platform gets a fresh timer. Reset or Z teleports Blobby to the start of a new game with new platforms and zero hops. The shortcuts work only while Blobby or a recovery button is focused. Tab or the arrow keys move between the buttons; Enter or Space activates the focused button. Your high score is kept. The recovery prompt and its shortcuts disappear after five idle seconds. Hovering or focusing a recovery button pauses this timeout, and leaving the buttons starts a new five-second timeout. With screen reader optimization enabled, the prompt stays until you dismiss it or choose an action. Press Escape to dismiss the prompt."), localize('chatPet.jump.help.camera', "The camera follows Blobby up and down. The platforms scroll, but the workbench does not. The charge bar is visible only while holding Space on a platform. Landings and a full charge are announced."), localize('chatPet.jump.help.difficulty', "As you climb, ledges become narrower. Moving ledges have arrow markings and carry Blobby while charging. Broken-line ledges crumble shortly after landing, then fall away; charge and leave before their remaining solid line disappears. Later sections add solid walls. Aim toward a wall to reflect your jump onto a nearby narrow ledge; hitting a side reverses horizontal travel without changing the vertical speed. The platforms and crumble timers pause with accessibility help and the accessible view."), localize('chatPet.jump.help.score', "The top-right counter shows Hops, with High score underneath. Landing on a platform higher than any you have reached in this run adds one hop. Returning to old platforms or hopping in place does not add points. Only the high score is saved on this device; every run starts at zero."), diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts index 95d5bd72fe05..d4f6688e6ad1 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatPetWidget.ts @@ -2763,8 +2763,20 @@ export class ChatPetWidget extends Disposable { } }, )) : undefined; + const hide = actions.add(new Action( + 'chat.pet.hide', + localize('chatPet.hide.action', "Hide Pet"), + undefined, + true, + () => { + if (this.chatPetService.enabled.get()) { + this.chatPetService.toggle(); + } + }, + )); const interactionSeparator = new Separator(); const appearanceSeparator = new Separator(); + const hideSeparator = new Separator(); this.contextMenuService.showContextMenu({ getAnchor: () => event ? new StandardMouseEvent(dom.getWindow(this._button.element), event) : this._button.element, autoSelectItem: !event, @@ -2777,6 +2789,8 @@ export class ChatPetWidget extends Disposable { resetSize, appearanceSeparator, changeColor, + hideSeparator, + hide, ], onHide: () => { this._contextMenuVisible = false; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts index 71a23a0a1f0b..2a1f869e6822 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts @@ -34,6 +34,7 @@ import { ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; import { ICodeEditorService } from '../../../../../editor/browser/services/codeEditorService.js'; import { OffsetRange } from '../../../../../editor/common/core/ranges/offsetRange.js'; import { Range } from '../../../../../editor/common/core/range.js'; +import { CopyPasteController } from '../../../../../editor/contrib/dropOrPasteInto/browser/copyPasteController.js'; import { localize } from '../../../../../nls.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; @@ -490,6 +491,11 @@ export class ChatWidget extends Disposable implements IChatWidget { private _inputVisible = true; private _readOnly = false; + /** The `editable` and `readOnly` renderer options last applied to the list. */ + private _rendererEditable: boolean | undefined; + private _rendererReadOnly: boolean | undefined; + /** Whether renderer options changed since the list rows were last rerendered. */ + private _listRowsStale = false; private readonly _draftOnly = observableValue(this, false); private _instructionFilesCheckPromise: Promise | undefined; @@ -701,6 +707,7 @@ export class ChatWidget extends Disposable implements IChatWidget { this._lockedCodingAgentIdContextKey = ChatContextKeys.lockedCodingAgentId.bindTo(this.contextKeyService); this._readOnlyContextKey = ChatContextKeys.readOnly.bindTo(this.contextKeyService); this._chatIsAgentHostSessionContextKey = ChatContextKeys.chatIsAgentHostSession.bindTo(this.contextKeyService); + ChatContextKeys.inSessionsChat.bindTo(this.contextKeyService).set(!!viewOptions.isSessionsWindow); this._chatAgentHostProviderIdContextKey = ChatContextKeys.chatAgentHostProviderId.bindTo(this.contextKeyService); this._chatAgentHostHasImmutablePrimaryWorkingDirectoryContextKey = ChatContextKeys.chatAgentHostHasImmutablePrimaryWorkingDirectory.bindTo(this.contextKeyService); this._chatAgentHostFolderPickerVisibleContextKey = ChatContextKeys.chatAgentHostFolderPickerVisible.bindTo(this.contextKeyService); @@ -1263,6 +1270,7 @@ export class ChatWidget extends Disposable implements IChatWidget { this.createList(this.listContainer, { editable: !isInlineChat(this) && !isQuickChat(this), contentHorizontalPadding: this.viewOptions.isSessionsWindow ? SESSIONS_CHAT_CONTENT_HORIZONTAL_PADDING : undefined, + isSessionsChat: this.viewOptions.isSessionsWindow, ...this.viewOptions.rendererOptions, renderStyle }); @@ -1276,6 +1284,7 @@ export class ChatWidget extends Disposable implements IChatWidget { getTemplateDataForRequestId: (requestId) => this.getTemplateDataForRequestId(requestId), onDidRerenderRow: this.onDidRerenderRow, editorsInUse: () => this.listWidget.editorsInUse(), + getCodeBlockInfoForEditor: uri => this.listWidget.getCodeBlockInfoForEditor(uri), getScrollTop: () => this.listWidget.scrollTop, setScrollTop: (scrollTop) => { this.listWidget.scrollTop = scrollTop; }, getRenderHeight: () => this.listWidget.renderHeight, @@ -2140,7 +2149,7 @@ export class ChatWidget extends Disposable implements IChatWidget { private async archiveLocalParentSession(sessionResource: URI): Promise { // In the regular workbench, only archive local chat sessions. // In the sessions window, allow archiving any session type after delegation. - if (getChatSessionType(sessionResource) !== localChatSessionType && !IsSessionsWindowContext.getValue(this.contextKeyService)) { + if (getChatSessionType(sessionResource) !== localChatSessionType && !IsSessionsWindowContext.getValue(this.contextKeyService) && !this.viewOptions.isSessionsWindow) { return; } @@ -2209,7 +2218,10 @@ export class ChatWidget extends Disposable implements IChatWidget { this.setInputVisible(inputVisible); // Authoritative over the lock/unlock `editable` toggles below. this._applyRendererEditable(!readOnly); - this.rerenderListIfConnected(); + // Rows only need a rerender when they were rendered with other options. + if (this._listRowsStale) { + this.rerenderListIfConnected(); + } } private _listRerenderPending = false; @@ -2225,6 +2237,7 @@ export class ChatWidget extends Disposable implements IChatWidget { const listDomNode = this.listWidget.domNode; if (listDomNode.isConnected && listDomNode.offsetHeight > 0) { this._listRerenderPending = false; + this._listRowsStale = false; this.listWidget.rerender(); } else { this._listRerenderPending = true; @@ -2369,7 +2382,13 @@ export class ChatWidget extends Disposable implements IChatWidget { */ private _applyRendererEditable(editable: boolean): void { const readOnly = this._readOnly || this.isTranscriptProgressActive; - this.listWidget?.updateRendererOptions({ editable: editable && !readOnly, readOnly }); + editable = editable && !readOnly; + if (editable !== this._rendererEditable || readOnly !== this._rendererReadOnly) { + this._rendererEditable = editable; + this._rendererReadOnly = readOnly; + this._listRowsStale = true; + } + this.listWidget?.updateRendererOptions({ editable, readOnly }); } /** @@ -3531,7 +3550,9 @@ export class ChatWidget extends Disposable implements IChatWidget { const agent = this.chatAgentService.getAgent(agentId); this._updateAgentCapabilitiesContextKeys(agent); const supportsCheckpoints = this._attachmentCapabilities.supportsCheckpoints ?? false; - this.listWidget?.updateRendererOptions({ restorable: supportsCheckpoints, editable: supportsCheckpoints && !this._readOnly, noFooter: false, progressMessageAtBottomOfResponse: true }); + this._rendererEditable = supportsCheckpoints && !this._readOnly; + this._listRowsStale = true; + this.listWidget?.updateRendererOptions({ restorable: supportsCheckpoints, editable: this._rendererEditable, noFooter: false, progressMessageAtBottomOfResponse: true }); this.rerenderListIfConnected(); } @@ -3562,7 +3583,9 @@ export class ChatWidget extends Disposable implements IChatWidget { this.viewModel.resetInputPlaceholder(); } this._updateInputPlaceholder(undefined); - this.listWidget?.updateRendererOptions({ restorable: true, editable: !this._readOnly, progressMessageAtBottomOfResponse: mode => mode !== ChatModeKind.Ask }); + this._rendererEditable = !this._readOnly; + this._listRowsStale = true; + this.listWidget?.updateRendererOptions({ restorable: true, editable: this._rendererEditable, progressMessageAtBottomOfResponse: mode => mode !== ChatModeKind.Ask }); this.rerenderListIfConnected(); } @@ -3584,7 +3607,7 @@ export class ChatWidget extends Disposable implements IChatWidget { return undefined; } const inputValue = query ?? this.getInput(); - if (!inputValue.trimStart().startsWith(chatAgentLeader) || IsSessionsWindowContext.getValue(this.contextKeyService)) { + if (!inputValue.trimStart().startsWith(chatAgentLeader) || IsSessionsWindowContext.getValue(this.contextKeyService) || this.viewOptions.isSessionsWindow) { return undefined; } const parsed = this.instantiationService.createInstance(ChatRequestParser).parseChatRequest(sessionResource, inputValue, this.location, { selectedAgent: this._lastSelectedAgent }); @@ -3654,11 +3677,28 @@ export class ChatWidget extends Disposable implements IChatWidget { return captureForkPromptSourceInput(this, this.chatService); } - async acceptInput(query?: string, options?: IChatAcceptInputOptions): Promise { + private isInputSubmissionBlocked(): boolean { const modelInputBlocked = this.viewModel?.model.isInputBlocked.get() && !this.viewOptions.hostSubmit; - if (this._readOnly || modelInputBlocked || this.isTranscriptProgressActive || this.input.hasPendingProgrammaticModelSelection || this.isSubmissionBlockedByManagedSettingsRefresh()) { + return !!(this._readOnly || modelInputBlocked || this.isTranscriptProgressActive || this.input.hasPendingProgrammaticModelSelection || this.isSubmissionBlockedByManagedSettingsRefresh()); + } + + async acceptInput(query?: string, options?: IChatAcceptInputOptions): Promise { + if (this.isInputSubmissionBlocked()) { return undefined; } + if (!options?.preserveInput) { + const input = this.input; + const viewModel = this.viewModel; + if (await CopyPasteController.get(input.inputEditor)?.finishedPaste() === false) { + throw new CancellationError(); + } + if (this._store.isDisposed || this.input !== input || this.viewModel !== viewModel) { + throw new CancellationError(); + } + if (this.isInputSubmissionBlocked()) { + return undefined; + } + } const participant = this.getParticipantForLocalChat(query); if (participant) { return this.acceptParticipantInputInLocalChat(participant, query, options); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatWidgetService.ts b/src/vs/workbench/contrib/chat/browser/widget/chatWidgetService.ts index 63f0591f40af..b9fbf30958d5 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatWidgetService.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatWidgetService.ts @@ -16,10 +16,10 @@ import { IEditorGroup, IEditorGroupsService, isEditorGroup } from '../../../../s import { IViewsService } from '../../../../services/views/common/viewsService.js'; import { IChatService } from '../../common/chatService/chatService.js'; import { ChatAgentLocation } from '../../common/constants.js'; -import { ChatViewId, ChatViewPaneTarget, IChatWidget, IChatWidgetService, IQuickChatService, isIChatViewViewContext } from '../chat.js'; +import { ChatViewId, ChatViewPaneTarget, IChatWidget, IChatWidgetService, IQuickChatService, isIChatResourceViewContext, isIChatViewViewContext } from '../chat.js'; +import { IChatViewHostService } from '../chatViewHost.js'; import { ChatEditor, IChatEditorOptions } from '../widgetHosts/editor/chatEditor.js'; import { ChatEditorInput } from '../widgetHosts/editor/chatEditorInput.js'; -import { ChatViewPane } from '../widgetHosts/viewPane/chatViewPane.js'; export class ChatWidgetService extends Disposable implements IChatWidgetService { @@ -54,6 +54,7 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService @IEditorService private readonly editorService: IEditorService, @IChatService private readonly chatService: IChatService, @ILogService private readonly logService: ILogService, + @IChatViewHostService private readonly chatViewHostService: IChatViewHostService, ) { super(); } @@ -87,11 +88,16 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService async revealWidget(preserveFocus?: boolean): Promise { const last = this.lastFocusedWidget; - if (last && await this.reveal(last, preserveFocus)) { + // The Chat view's widgets are shown by the host of its chats, which may have replaced the Chat view: what it shows is the result + if (last && !(isIChatViewViewContext(last.viewContext) && last.viewContext.viewId === ChatViewId) && await this.reveal(last, preserveFocus)) { return last; } - return (await this.viewsService.openView(ChatViewId, !preserveFocus))?.widget; + return this.revealChatView(preserveFocus); + } + + revealChatView(preserveFocus?: boolean): Promise { + return this.chatViewHostService.reveal(preserveFocus); } async reveal(widget: IChatWidget, preserveFocus?: boolean): Promise { @@ -103,6 +109,9 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService } if (isIChatViewViewContext(widget.viewContext)) { + if (widget.viewContext.viewId === ChatViewId) { + return !!await this.chatViewHostService.reveal(preserveFocus); + } const view = await this.viewsService.openView(widget.viewContext.viewId, !preserveFocus); if (!preserveFocus) { view?.focus(); @@ -110,6 +119,16 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService return !!view; } + // A chat widget that is hosted outside of the chat view and chat editors, + // such as the session chat of the Agents window, has nothing to open when + // it is already showing. + if (widget.visible && widget.location === ChatAgentLocation.Chat && isIChatResourceViewContext(widget.viewContext) && !widget.viewContext.isQuickChat && !widget.viewContext.isInlineChat) { + if (!preserveFocus) { + widget.focusInput(); + } + return true; + } + return false; } @@ -138,17 +157,11 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService return undefined; } - // Load this session in chat view (preferred) + // Load this session in the host of the Chat view's chats (preferred) if (target === ChatViewPaneTarget || typeof target === 'undefined') { - const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); - if (chatView) { - await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason); - if (!options?.preserveFocus) { - chatView.focusInput(); - } - } + const widget = await this.chatViewHostService.openSession(sessionResource, { preserveFocus: options?.preserveFocus, sessionTypeSelectionReason: options?.sessionTypeSelectionReason }); this.logService.trace(`[ChatWidgetService] openSession done total=${Date.now() - t0}ms uri=${sessionResource.toString()} path=view`); - return chatView?.widget; + return widget; } // Open in chat editor @@ -167,14 +180,10 @@ export class ChatWidgetService extends Disposable implements IChatWidgetService } private async revealSessionIfAlreadyOpen(sessionResource: URI, options?: IChatEditorOptions): Promise { - // Already open in chat view? - const chatView = this.viewsService.getViewWithId(ChatViewId); - if (chatView?.widget.viewModel?.sessionResource && isEqual(chatView.widget.viewModel.sessionResource, sessionResource)) { - const view = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); - if (!options?.preserveFocus) { - view?.focus(); - } - return chatView.widget; + // Already open in the host of the Chat view's chats? + const hostWidget = await this.chatViewHostService.revealIfShowing(sessionResource, options); + if (hostWidget) { + return hostWidget; } // Already open in an editor? diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationService.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationService.ts index 2b4cdb7442cf..6766fe8d50f5 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationService.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationService.ts @@ -126,6 +126,8 @@ export interface IChatInputNotificationSetOptions { export interface IChatInputNotification { readonly id: string; + /** Optional setup guidance appears once in the transcript, beside the first response, rather than in the composer. */ + readonly placement?: 'transcript'; /** Targets one input instance, including when several inputs show the same session. */ readonly inputUri?: URI; readonly telemetryId?: string; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationWidget.ts index 0de53f600f9d..1e9e963a5e88 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputNotificationWidget.ts @@ -102,6 +102,7 @@ export interface IChatInputNotificationModelSelection { /** Input-local capabilities used to filter and execute semantic notification actions. */ export interface IChatInputNotificationDelegate { + readonly placement?: 'transcript'; readonly hostVisible?: IObservable; readonly inputUri?: URI; readonly modelTargetChatSessionType?: IObservable; @@ -203,6 +204,9 @@ export class ChatInputNotificationWidget extends Disposable implements IChatInpu dismissible: false, autoDismissOnMessage: false, } : this._notificationService.getActiveNotification(candidate => { + if (candidate.placement !== this._delegate?.placement) { + return false; + } const body = this._resolveBody(candidate); if (body) { bodies.set(candidate.id, body); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputPart.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputPart.ts index 586f8aadee7c..3eb89a7b886b 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputPart.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputPart.ts @@ -14,6 +14,7 @@ import { ActionViewItem, BaseActionViewItem, IActionViewItemOptions } from '../. import * as aria from '../../../../../../base/browser/ui/aria/aria.js'; import { ButtonWithIcon } from '../../../../../../base/browser/ui/button/button.js'; import { createInstantHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { IHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate.js'; import { IAction } from '../../../../../../base/common/actions.js'; import { equals as arraysEqual } from '../../../../../../base/common/arrays.js'; import { DeferredPromise, RunOnceScheduler } from '../../../../../../base/common/async.js'; @@ -124,6 +125,8 @@ import { IChatLayoutService } from '../../../common/widget/chatLayoutService.js' import { ChatHistoryNavigator } from '../../../common/widget/chatWidgetHistoryService.js'; import { ChatEditingSessionSubmitAction, ChatSessionPrimaryPickerAction, ChatSubmitAction, IChatExecuteActionContext, OpenDelegationPickerAction, OpenModelPickerAction, OpenModePickerAction, OpenPermissionPickerAction, OpenSessionTargetPickerAction } from '../../actions/chatExecuteActions.js'; import { ChatVoiceInputModeAction, VoiceInputModeActionViewItem } from '../../voiceInputMode/voiceInputModeActionViewItem.js'; +import { ChatCustomizationsActionViewItem, ChatCustomizationsHover } from '../../aiCustomization/chatCustomizationsHover.js'; +import { AICustomizationManagementCommands } from '../../../common/aiCustomizationWorkspaceService.js'; import { ChatSpeechToTextConnectingAction, ChatSpeechToTextPreparingAction, ToggleChatSpeechToTextAction } from '../../actions/chatSpeechToTextActions.js'; import { DictationActionViewItem } from '../../speechToText/dictationActionViewItem.js'; import { DictationDownloadActionViewItem } from '../../speechToText/dictationDownloadActionViewItem.js'; @@ -137,6 +140,7 @@ import { getAgentSessionPullRequestContextValue } from '../../agentSessions/agen import { IAgentSessionsService } from '../../agentSessions/agentSessionsService.js'; import { ChatAttachmentModel } from '../../attachments/chatAttachmentModel.js'; import { IChatAttachmentWidgetInstance, IChatAttachmentWidgetRegistry } from '../../attachments/chatAttachmentWidgetRegistry.js'; +import { GitHubResourceDetailsResolver } from '../../../../github/browser/githubResourceDetails.js'; import { DefaultChatAttachmentWidget, ElementChatAttachmentWidget, FileAttachmentWidget, ImageAttachmentWidget, BrowserViewAttachmentWidget, NotebookCellOutputChatAttachmentWidget, PasteAttachmentWidget, PromptFileAttachmentWidget, PromptTextAttachmentWidget, SCMHistoryItemAttachmentWidget, SCMHistoryItemChangeAttachmentWidget, SCMHistoryItemChangeRangeAttachmentWidget, TerminalCommandAttachmentWidget, ToolSetOrToolItemAttachmentWidget } from '../../attachments/chatAttachmentWidgets.js'; import { ChatImplicitContexts } from '../../attachments/chatImplicitContext.js'; import { ImplicitContextAttachmentWidget, isImplicitContextAlreadyAttached } from '../../attachments/implicitContextAttachment.js'; @@ -682,6 +686,15 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge return element?.isConnected ? element : undefined; } + private readonly _onDidChangeAttachContextButton = this._register(new Emitter()); + readonly onDidChangeAttachContextButton = this._onDidChangeAttachContextButton.event; + get onDidActivateAttachContext(): Event { + return Event.map(Event.filter(Event.any( + this.inputActionsToolbar.actionRunner.onWillRun, + this.executeToolbar.actionRunner.onWillRun, + ), event => event.action.id === CHAT_ATTACH_CONTEXT_ACTION_ID), () => undefined); + } + setInputToolbarAriaLabel(label: string): void { this.inputActionsToolbar.setAriaLabel(label); } @@ -949,6 +962,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge private readonly _modelSelectionDiagnostics: ChatModelSelectionDiagnostics; private readonly _modelSelectionController: ChatInputModelSelectionController; private readonly _currentLanguageModel: IObservable; + private _lastAnnouncedModelId: string | undefined; private readonly _modelSelectionRuntime: IChatInputModelSelectionRuntime; /** @@ -1495,13 +1509,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge this.setImplicitContextEnablement(); })); this._register(autorun(reader => { - const lm = this._currentLanguageModel.read(reader); - this.chatModelIdKey.set(lm?.metadata.id.toLowerCase() ?? ''); - this.contextUsageWidget?.setSelectedModel(lm?.identifier); - if (lm?.metadata.name) { - this.accessibilityService.alert(lm.metadata.name); - } - this._inputEditor?.updateOptions({ ariaLabel: this._getAriaLabel() }); + this._updateSelectedModel(this._currentLanguageModel.read(reader)); })); this._register(autorun(r => { const mode = this._currentModeObservable.read(r); @@ -2238,6 +2246,16 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge } } + private _updateSelectedModel(model: ILanguageModelChatMetadataAndIdentifier | undefined): void { + this.chatModelIdKey.set(model?.metadata.id.toLowerCase() ?? ''); + this.contextUsageWidget?.setSelectedModel(model?.identifier); + if (model?.metadata.name && model.identifier !== this._lastAnnouncedModelId) { + this._lastAnnouncedModelId = model.identifier; + this.accessibilityService.alert(model.metadata.name); + } + this._inputEditor?.updateOptions({ ariaLabel: this._getAriaLabel() }); + } + public setCurrentLanguageModel(model: ILanguageModelChatMetadataAndIdentifier, isUserAction = false, storeSelection: boolean = isUserAction) { const policyError = getAgentModelPolicyError(this.getAgentModelPreferences(), model.identifier, this.getModels()); if (isUserAction && policyError) { @@ -3647,9 +3665,9 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge } private updateChatSessionPickerContainer(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.chatSessionPickerContainer = this.inputActionsToolbar?.getElement().querySelector('.chat-sessionPicker-container') - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax ?? this.secondaryToolbar?.getElement().querySelector('.chat-sessionPicker-container') ?? undefined; } @@ -3678,7 +3696,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge } private updateDeferredNotificationsEligibility(e?: IChatWidgetViewModelChangeEvent): void { - if (this.environmentService.isSessionsWindow) { + if (this.environmentService.isSessionsWindow || this.options.isSessionsWindow) { this._deferredNotificationsEnabled.set(true, undefined); return; } @@ -3974,7 +3992,8 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge this.renderChatEditingSessionState(null); - this.dnd.addOverlay(this.options.dndContainer ?? container, this.options.dndContainer ?? container, this.container); + // Only the input itself takes drags ahead of the pane around it, not the widgets stacked on it, such as notices. + this.dnd.addOverlay(this.options.dndContainer ?? container, this.options.dndContainer ?? container, this.inputContainer); const inputScopedContextKeyService = this._register(this.contextKeyService.createScoped(inputContainer)); ChatContextKeys.inChatInput.bindTo(inputScopedContextKeyService).set(true); @@ -4028,10 +4047,13 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge this.updateInputEditorFontFamily(); this._register(addDisposableListener(this._inputEditorElement, dom.EventType.PASTE, e => this.handleTerminalCommandPaste(e), true)); + const hoverDelegate = this._register(createInstantHoverDelegate()); const getWidget = () => this._widget; + const getSessionResource = () => this._inputModelSessionResource ?? this._widget?.viewModel?.sessionResource; this._inlineAttachments = this._register(this.instantiationService.createInstance(ChatInlineAttachments, this._inputEditor, this._attachmentModel, { get widget() { return getWidget(); }, - createAttachmentWidget: (attachment, container, attachmentOptions) => this.createAttachmentWidget(attachment, container, attachmentOptions), + get sessionResource() { return getSessionResource(); }, + createAttachmentWidget: (attachment, container, attachmentOptions) => this.createAttachmentWidget(attachment, container, { ...attachmentOptions, hoverDelegate }), removeAttachments: (attachments, explicit) => this.removeInlineAttachments(attachments, explicit), resetDragState: () => this.dnd.resetDragState(), })); @@ -4157,8 +4179,6 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge DropIntoEditorController.get(this._inputEditor)?.clearWidgets(); })); - const hoverDelegate = this._register(createInstantHoverDelegate()); - const { location } = this.getWidgetLocationInfo(widget); const focusedWidget = observableFromEvent(this, this.chatWidgetService.onDidChangeFocusedSession, () => this.chatWidgetService.lastFocusedWidget); const voiceSessionResource = observableFromEvent(this, widget.onDidChangeViewModel, () => widget.viewModel?.sessionResource); @@ -4363,6 +4383,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge this.inputActionsToolbar.getElement().classList.add('chat-input-toolbar'); this.inputActionsToolbar.context = { widget } satisfies IChatExecuteActionContext; this._register(this.inputActionsToolbar.onDidChangeMenuItems(() => { + this._onDidChangeAttachContextButton.fire(); this.updateChatSessionPickerContainer(); if (this.cachedWidth && typeof this.cachedInputToolbarWidth === 'number' && this.cachedInputToolbarWidth !== this.inputActionsToolbar.getItemsWidth()) { this._toolbarRelayoutScheduler.schedule(); @@ -4389,6 +4410,9 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge hoverDelegate, hiddenItemStrategy: HiddenItemStrategy.NoHide, actionViewItemProvider: (action, options) => { + if (action.id === AICustomizationManagementCommands.OpenEditor && action instanceof MenuItemAction) { + return this.instantiationService.createInstance(ChatCustomizationsActionViewItem, action, options, this.instantiationService.createInstance(ChatCustomizationsHover), 'chatInput', undefined, false, undefined); + } if (action.id === CHAT_ATTACH_CONTEXT_ACTION_ID && action instanceof MenuItemAction) { return this.attachContextActionViewItem = this.instantiationService.createInstance(MenuEntryActionViewItem, action, options); } @@ -4468,6 +4492,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge }; updateVoiceInputActionBorder(); this._register(this.executeToolbar.onDidChangeMenuItems(() => { + this._onDidChangeAttachContextButton.fire(); updateVoiceInputActionBorder(); if (this.cachedWidth && typeof this.cachedExecuteToolbarWidth === 'number' && this.cachedExecuteToolbarWidth !== this.executeToolbar.getItemsWidth()) { this._toolbarRelayoutScheduler.schedule(); @@ -4938,7 +4963,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge * Creates the pill for an attachment, using the widget that matches its kind. * Used for the attachments above the input and for inline attachment pills. */ - createAttachmentWidget(attachment: IChatRequestVariableEntry, container: HTMLElement, options: { shouldFocusClearButton: boolean; supportsDeletion: boolean }): IChatAttachmentWidgetInstance { + createAttachmentWidget(attachment: IChatRequestVariableEntry, container: HTMLElement, options: { shouldFocusClearButton: boolean; supportsDeletion: boolean; gitHubResourceDetailsResolver?: GitHubResourceDetailsResolver; hoverDelegate?: IHoverDelegate }): IChatAttachmentWidgetInstance { const resource = URI.isUri(attachment.value) ? attachment.value : isLocation(attachment.value) ? attachment.value.uri : undefined; const range = isLocation(attachment.value) ? attachment.value.range : undefined; const widgetOptions = { ...options, isCurrentInput: true }; @@ -5081,7 +5106,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge return; } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const attachments = Array.from(this.attachedContextContainer.querySelectorAll('.chat-attached-context-attachment')); if (!attachments.length) { return; @@ -5667,19 +5692,19 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge sessionEntriesObs: IObservable ) { // Summary of number of files changed - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const innerContainer = this.chatEditingSessionWidgetContainer.querySelector('.chat-editing-session-container.show-file-icons') as HTMLElement ?? dom.append(this.chatEditingSessionWidgetContainer, $('.chat-editing-session-container.show-file-icons')); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const overviewRegion = innerContainer.querySelector('.chat-editing-session-overview') as HTMLElement ?? dom.append(innerContainer, $('.chat-editing-session-overview')); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const overviewTitle = overviewRegion.querySelector('.working-set-title') as HTMLElement ?? dom.append(overviewRegion, $('.working-set-title')); // Clear out the previous actions (if any) this._chatEditsActionsDisposables.clear(); // Chat editing session actions - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const actionsContainer = overviewRegion.querySelector('.chat-editing-session-actions') as HTMLElement ?? dom.append(overviewRegion, $('.chat-editing-session-actions')); const sessionResource = chatEditingSession?.chatSessionResource || this._widget?.viewModel?.model.sessionResource; @@ -5705,7 +5730,7 @@ export class ChatInputPart extends Disposable implements IHistoryNavigationWidge const scopedInstantiationService = this._chatEditsActionsDisposables.add(this.instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); // Working set - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const workingSetContainer = innerContainer.querySelector('.chat-editing-session-list') as HTMLElement ?? dom.append(innerContainer, $('.chat-editing-session-list')); const button = this._chatEditsActionsDisposables.add(new ButtonWithIcon(overviewTitle, { diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputTipPresenter.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputTipPresenter.ts index ba5cbeea532c..d54e4d6b213c 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatInputTipPresenter.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatInputTipPresenter.ts @@ -7,12 +7,15 @@ import * as dom from '../../../../../../base/browser/dom.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { TIP_CATALOG } from '../../chatTipCatalog.js'; import { IChatTipService } from '../../chatTipService.js'; import { ChatContentMarkdownRenderer } from '../chatContentMarkdownRenderer.js'; import { ChatTipContentPart } from '../chatContentParts/chatTipContentPart.js'; import { ChatInputNoticeHost, ChatInputNoticeLane } from './chatInputNoticeHost.js'; import { ChatInputStackSlot, setChatInputStackSlot } from './chatInputStack.js'; +const tipConfigurationContextKeys = new Set(TIP_CATALOG.flatMap(tip => tip.when?.keys().filter(key => key.startsWith('config.')) ?? [])); + export interface IChatInputTipPresenterOptions { /** The element the tip is rendered into. Hidden while no tip is showing. */ readonly container: HTMLElement; @@ -53,22 +56,29 @@ export class ChatInputTipPresenter extends Disposable { // Takes the tip out of the container even if the notice host is already // gone, so disposal never depends on a stand-down that will not arrive. this._register(toDisposable(() => this._clearContent())); - this._register(this._chatTipService.onDidChangeTip(() => { - const hadFocus = this._partRef?.hasFocus() ?? false; - this._clearContent(); - this.update(); - if (hadFocus) { - if (this._partRef) { - this._partRef.focus(); - } else { - this._options.focusInput(); - } + this._register(this._chatTipService.onDidChangeTip(() => this._refreshTip())); + this._register(this._contextKeyService.onDidChangeContext(e => { + if (e.affectsSome(tipConfigurationContextKeys)) { + this._refreshTip(); } })); this.update(); } + private _refreshTip(): void { + const hadFocus = this._partRef?.hasFocus() ?? false; + this._clearContent(); + this.update(); + if (hadFocus) { + if (this._partRef) { + this._partRef.focus(); + } else { + this._options.focusInput(); + } + } + } + /** * Re-evaluate whether this surface wants a tip at all. Claiming the tip lane is * all this does: whether the tip is actually on screen is the notice host's diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatModelConfigurationStore.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatModelConfigurationStore.ts index fb8d9d1c6da8..fac600b81679 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatModelConfigurationStore.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatModelConfigurationStore.ts @@ -336,8 +336,10 @@ export class ChatModelConfigurationStore extends Disposable implements IModelCon } const applied = filterConfigurationToSchema(current.config, this.getModelConfigurationSchema(modelId)); const result = { ...configuration }; + // A conversation with turns runs with the runtime's values, which also win over preferences it inherited but never set. + const ownKeys = this.isEmpty() ? undefined : this._ownKeys.get(modelId) ?? new Set(); for (const key of this._defaultKeys(modelId) ?? []) { - if (!Object.hasOwn(applied, key) || !isModelConfigurationDefault(configuration, key)) { + if (!Object.hasOwn(applied, key) || (!isModelConfigurationDefault(configuration, key) && (!ownKeys || ownKeys.has(key)))) { continue; } result[key] = applied[key]; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.ts index 37f7583e117d..9436872a700a 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatPhoneInputPresenter.ts @@ -18,8 +18,10 @@ import { localize } from '../../../../../../nls.js'; import { InstantiationType, registerSingleton } from '../../../../../../platform/instantiation/common/extensions.js'; import { createDecorator } from '../../../../../../platform/instantiation/common/instantiation.js'; import { IModePickerDelegate } from './modePickerActionItem.js'; +import { ILanguageModelsService, isAutoLanguageModel } from '../../../common/languageModels.js'; import { IModelPickerDelegate } from './modelPicker/modelPickerActionItem.js'; import { getModelProviderIcon } from './modelPicker/modelProviderIcons.js'; +import { isPendingLegacyAutoModel } from './modelPicker/modelPickerPresentation.js'; export interface IChatPhoneInputSessionContext { readonly providerId: string; @@ -201,6 +203,7 @@ export class MobileChatInputCombinedPickerActionItem extends BaseActionViewItem private readonly _modeDelegate: IModePickerDelegate, private readonly _modelDelegate: IModelPickerDelegate, @IChatPhoneInputPresenter private readonly _presenter: IChatPhoneInputPresenter, + @ILanguageModelsService private readonly _languageModelsService: ILanguageModelsService, ) { super(undefined, action); } @@ -260,8 +263,10 @@ export class MobileChatInputCombinedPickerActionItem extends BaseActionViewItem if (currentModel && this._modelDelegate.getPresentationOptions().showModelIcon) { dom.append(trigger, renderIcon(getModelProviderIcon(currentModel))); } - const labelText = currentModel?.metadata.name - ?? localize('chatPhoneInput.autoLabel', "Auto"); + // An Auto offered as Copilot Fusion stands for Auto under its own name. + const labelText = (isPendingLegacyAutoModel(currentModel, this._languageModelsService) ? undefined : currentModel?.metadata.name) + ?? this._modelDelegate.getModels().find(model => isAutoLanguageModel(model) && model.metadata.autoModelFusion)?.metadata.name + ?? localize('chatPhoneInput.fusionLabel', "Copilot Fusion"); const labelSpan = dom.append(trigger, dom.$('span.chat-input-picker-label')); labelSpan.textContent = labelText; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/chatSessionArchiveNudge.ts b/src/vs/workbench/contrib/chat/browser/widget/input/chatSessionArchiveNudge.ts index de9ab5bf1f35..b1b98e24d7f3 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/chatSessionArchiveNudge.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/chatSessionArchiveNudge.ts @@ -38,6 +38,8 @@ export const CHAT_SESSION_ARCHIVE_NUDGE_ICON_TREATMENT = 'chatSessionArchiveNudg export interface IChatSessionArchiveNudgeOptions { readonly hasWorktree: boolean; readonly pullRequestCount: number; + /** Whether the suggestion archives only the chat showing it rather than the whole session. */ + readonly archivesChat?: boolean; readonly compact?: boolean; readonly onArchive: () => Promise; readonly onDismiss: () => void; @@ -79,7 +81,7 @@ export class ChatSessionArchiveNudge extends Disposable { super(); // Every arm of the copy experiments renders the suggestion; they only change its title and icon. - logExperimentTrigger(this.telemetryService, CHAT_SESSION_ARCHIVE_NUDGE_TITLE_TREATMENT); + this.reportTitleExperimentTrigger(options); logExperimentTrigger(this.telemetryService, CHAT_SESSION_ARCHIVE_NUDGE_ICON_TREATMENT); const id = generateUuid(); @@ -134,7 +136,6 @@ export class ChatSessionArchiveNudge extends Disposable { }, true)); this.setOptions(options); - this.updateContent(); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(ChatSessionArchiveActionWordingSettingId)) { this.updateContent(); @@ -146,7 +147,8 @@ export class ChatSessionArchiveNudge extends Disposable { setOptions(options: IChatSessionArchiveNudgeOptions): void { this.options = options; - this.updateTitle(); + this.reportTitleExperimentTrigger(options); + this.updateContent(); this.worktreeElement.hidden = !options.hasWorktree; const compact = !!options.compact; this.domNode.classList.toggle('compact', compact); @@ -165,14 +167,30 @@ export class ChatSessionArchiveNudge extends Disposable { } } + /** The title experiment's copy describes the session, so a suggestion that archives only its chat never shows it. */ + private reportTitleExperimentTrigger(options: IChatSessionArchiveNudgeOptions): void { + if (!options.archivesChat) { + logExperimentTrigger(this.telemetryService, CHAT_SESSION_ARCHIVE_NUDGE_TITLE_TREATMENT); + } + } + private updateTitle(): void { - const title = this.titleTreatment ?? (this.markAsDone - ? this.options.pullRequestCount > 1 - ? localize('chat.sessionArchiveNudge.doneQuestionAll', "All PRs merged. Mark this session as done?") - : localize('chat.sessionArchiveNudge.doneQuestion', "PR merged. Mark this session as done?") - : this.options.pullRequestCount > 1 - ? localize('chat.sessionArchiveNudge.archiveQuestionAll', "All PRs merged. Archive this session?") - : localize('chat.sessionArchiveNudge.archiveQuestion', "PR merged. Archive this session?")); + const multiple = this.options.pullRequestCount > 1; + const title = (this.options.archivesChat ? undefined : this.titleTreatment) ?? (this.options.archivesChat + ? this.markAsDone + ? multiple + ? localize('chat.sessionArchiveNudge.chatDoneQuestionAll', "All PRs merged. Mark this chat as done?") + : localize('chat.sessionArchiveNudge.chatDoneQuestion', "PR merged. Mark this chat as done?") + : multiple + ? localize('chat.sessionArchiveNudge.chatArchiveQuestionAll', "All PRs merged. Archive this chat?") + : localize('chat.sessionArchiveNudge.chatArchiveQuestion', "PR merged. Archive this chat?") + : this.markAsDone + ? multiple + ? localize('chat.sessionArchiveNudge.doneQuestionAll', "All PRs merged. Mark this session as done?") + : localize('chat.sessionArchiveNudge.doneQuestion', "PR merged. Mark this session as done?") + : multiple + ? localize('chat.sessionArchiveNudge.archiveQuestionAll', "All PRs merged. Archive this session?") + : localize('chat.sessionArchiveNudge.archiveQuestion', "PR merged. Archive this session?")); if (this.titleElement.textContent !== title) { this.titleElement.textContent = title; } @@ -187,13 +205,22 @@ export class ChatSessionArchiveNudge extends Disposable { const actionLabel = getChatSessionArchiveActionPresentation(wording).archive.title.value; const sectionLabel = getChatSessionArchivedSectionLabel(wording); this.updateTitle(); - this.descriptionElement.textContent = this.markAsDone - ? localize('chat.sessionArchiveNudge.doneOverview', "Mark this session as done to hide it from the sessions list and focus on your remaining tasks.") - : localize('chat.sessionArchiveNudge.overview', "Archive this session to hide it from the sessions list and focus on your remaining tasks."); + if (this.options.archivesChat) { + this.descriptionElement.textContent = this.markAsDone + ? localize('chat.sessionArchiveNudge.chatDoneOverview', "Mark this chat as done to set it aside and focus on the rest of this session.") + : localize('chat.sessionArchiveNudge.chatOverview', "Archive this chat to set it aside and focus on the rest of this session."); + this.recoveryElement.textContent = this.markAsDone + ? localize('chat.sessionArchiveNudge.chatDoneRecovery', "Other chats in this session are not affected. This chat is not deleted. Look in the \"{0}\" section of the sessions list. You can restore it anytime.", sectionLabel) + : localize('chat.sessionArchiveNudge.chatRecovery', "Other chats in this session are not affected. This chat is not deleted. Look in the \"{0}\" section of the sessions list. You can unarchive it anytime.", sectionLabel); + } else { + this.descriptionElement.textContent = this.markAsDone + ? localize('chat.sessionArchiveNudge.doneOverview', "Mark this session as done to set it aside and focus on your remaining tasks.") + : localize('chat.sessionArchiveNudge.overview', "Archive this session to set it aside and focus on your remaining tasks."); + this.recoveryElement.textContent = this.markAsDone + ? localize('chat.sessionArchiveNudge.doneRecovery', "The session is not deleted. Ask your agent to find it, or look in the \"{0}\" section of the sessions list. You can restore it anytime.", sectionLabel) + : localize('chat.sessionArchiveNudge.recovery', "The session is not deleted. Ask your agent to find it, or look in the \"{0}\" section of the sessions list. You can unarchive it anytime.", sectionLabel); + } this.detailsLabelElement.textContent = localize('chat.sessionArchiveNudge.actionDetails', "What Does \"{0}\" Do?", actionLabel); - this.recoveryElement.textContent = this.markAsDone - ? localize('chat.sessionArchiveNudge.doneRecovery', "The session is not deleted. Ask your agent to find it, or look in the \"{0}\" section of the sessions list. You can restore it anytime.", sectionLabel) - : localize('chat.sessionArchiveNudge.recovery', "The session is not deleted. Ask your agent to find it, or look in the \"{0}\" section of the sessions list. You can unarchive it anytime.", sectionLabel); this.worktreeElement.textContent = this.markAsDone ? localize('chat.sessionArchiveNudge.doneWorktree', "The worktree created for this session will be deleted. You can recreate it by restoring the session.") : localize('chat.sessionArchiveNudge.worktree', "The worktree created for this session will be deleted. You can recreate it by unarchiving the session."); @@ -263,9 +290,13 @@ export class ChatSessionArchiveNudge extends Disposable { this.accessibilitySignalService.playSignal(AccessibilitySignal.confetti); } } catch (error) { - this.notificationService.error(this.markAsDone - ? localize('chat.sessionArchiveNudge.doneError', "Unable to mark the session as done: {0}", toErrorMessage(error)) - : localize('chat.sessionArchiveNudge.archiveError', "Unable to archive the session: {0}", toErrorMessage(error))); + this.notificationService.error(this.options.archivesChat + ? this.markAsDone + ? localize('chat.sessionArchiveNudge.chatDoneError', "Unable to mark the chat as done: {0}", toErrorMessage(error)) + : localize('chat.sessionArchiveNudge.chatArchiveError', "Unable to archive the chat: {0}", toErrorMessage(error)) + : this.markAsDone + ? localize('chat.sessionArchiveNudge.doneError', "Unable to mark the session as done: {0}", toErrorMessage(error)) + : localize('chat.sessionArchiveNudge.archiveError', "Unable to archive the session: {0}", toErrorMessage(error))); } finally { if (!this._store.isDisposed) { this.setArchiving(false); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInlineAttachments.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInlineAttachments.ts index 23ef93353c2a..a7a0d055659a 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInlineAttachments.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInlineAttachments.ts @@ -8,11 +8,14 @@ import { createStyleSheet } from '../../../../../../../base/browser/domStyleshee import { status } from '../../../../../../../base/browser/ui/aria/aria.js'; import { StandardKeyboardEvent } from '../../../../../../../base/browser/keyboardEvent.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; -import { Emitter } from '../../../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../../../base/common/event.js'; +import { Lazy } from '../../../../../../../base/common/lazy.js'; +import { URI } from '../../../../../../../base/common/uri.js'; import { IMarkdownString, MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { KeyCode, KeyMod } from '../../../../../../../base/common/keyCodes.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition, MouseTargetType } from '../../../../../../../editor/browser/editorBrowser.js'; +import { EditorContextKeys } from '../../../../../../../editor/common/editorContextKeys.js'; import { IClipboardCopyEvent } from '../../../../../../../editor/browser/controller/editContext/clipboardUtils.js'; import { ICodeEditorService } from '../../../../../../../editor/browser/services/codeEditorService.js'; import { EditorOption } from '../../../../../../../editor/common/config/editorOptions.js'; @@ -24,27 +27,32 @@ import { PositionOffsetTransformer } from '../../../../../../../editor/common/co import { CursorChangeReason } from '../../../../../../../editor/common/cursorEvents.js'; import { IEditorDecorationsCollection, ScrollType } from '../../../../../../../editor/common/editorCommon.js'; import { IIdentifiedSingleEditOperation, IModelDecorationOptions, ITextModel, TrackedRangeStickiness } from '../../../../../../../editor/common/model.js'; +import { ILinkComputerTarget } from '../../../../../../../editor/common/languages/linkComputer.js'; import { IModelContentChange } from '../../../../../../../editor/common/model/mirrorTextModel.js'; import { localize, localize2 } from '../../../../../../../nls.js'; import { IAccessibilityService } from '../../../../../../../platform/accessibility/common/accessibility.js'; import { Action2, registerAction2 } from '../../../../../../../platform/actions/common/actions.js'; import { IConfigurationService } from '../../../../../../../platform/configuration/common/configuration.js'; import { ContextKeyExpr, IContextKey, IContextKeyService } from '../../../../../../../platform/contextkey/common/contextkey.js'; -import { ServicesAccessor } from '../../../../../../../platform/instantiation/common/instantiation.js'; +import { IInstantiationService, ServicesAccessor } from '../../../../../../../platform/instantiation/common/instantiation.js'; import { KeybindingWeight } from '../../../../../../../platform/keybinding/common/keybindingsRegistry.js'; import { ILabelService } from '../../../../../../../platform/label/common/label.js'; +import { ILogService } from '../../../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../../../platform/product/common/productService.js'; import { AccessibilityVerbositySettingId } from '../../../../../accessibility/browser/accessibilityConfiguration.js'; import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; import { canOpenAttachment, canShowAttachmentInline, getAttachmentLabel, getAttachmentMention, getAttachmentPromptText, GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX, IInlineAttachmentAnchor, IInlineAttachmentProjection, INLINE_ATTACHMENT_ANCHOR, isInlineAttachmentCandidate, projectInlineAttachments, toRelativeRange } from '../../../../common/attachments/chatInlineAttachments.js'; -import { IChatRequestVariableEntry } from '../../../../common/attachments/chatVariableEntries.js'; +import { IChatRequestSessionLinkVariableEntry, IChatRequestVariableEntry, isSessionLinkVariableEntry } from '../../../../common/attachments/chatVariableEntries.js'; import { IDynamicVariable, toAttachedContextDynamicVariable } from '../../../../common/attachments/chatVariables.js'; import { ChatConfiguration } from '../../../../common/constants.js'; import { ChatRequestDynamicVariablePart, ChatRequestToolPart, ChatRequestToolSetPart, IParsedChatRequest, IParsedChatRequestPart, chatAgentLeader, chatSubcommandLeader, chatVariableLeader } from '../../../../common/requestParser/chatParserTypes.js'; import { IChatWidget } from '../../../chat.js'; import { ChatAttachmentModel } from '../../../attachments/chatAttachmentModel.js'; -import { IChatAttachmentWidgetInstance } from '../../../attachments/chatAttachmentWidgetRegistry.js'; +import { IChatAttachmentWidgetInstance, IChatAttachmentWidgetRegistry } from '../../../attachments/chatAttachmentWidgetRegistry.js'; import { ChatDynamicVariableModel } from '../../../attachments/chatDynamicVariables.js'; import { getGitHubIssueOrPullRequestAttachments } from './chatPasteProviders.js'; +import { GitHubResourceDetailsResolver, parseGitHubReferenceTarget } from '../../../../../github/browser/githubResourceDetails.js'; +import { ChatInputSessionLinkDetector } from './chatInputSessionLinkProvider.js'; import './media/chatInlineAttachments.css'; /** What an inline attachment pill stands for. */ @@ -57,6 +65,8 @@ interface IInlineAttachmentPillData { readonly reference: IDynamicVariable | undefined; /** What the pill shows while its attachment is not in the attachment model, such as an attachment derived from a reference. */ readonly entry: IChatRequestVariableEntry; + /** Whether the prompt says {@link text} exactly where the pill is, see {@link IInlineAttachmentAnchor.verbatim}. */ + readonly verbatim?: boolean; } /** A pill that was removed by editing the input, kept so that undo and redo can restore it. */ @@ -101,8 +111,9 @@ interface IInputChange { export interface IChatInlineAttachmentsHost { /** The widget whose input contains the pills, once it is rendered. */ readonly widget: IChatWidget | undefined; + readonly sessionResource?: URI; /** Creates a pill with the widget that the attachments above the input use for the attachment. */ - createAttachmentWidget(attachment: IChatRequestVariableEntry, container: HTMLElement, options: { shouldFocusClearButton: boolean; supportsDeletion: boolean }): IChatAttachmentWidgetInstance; + createAttachmentWidget(attachment: IChatRequestVariableEntry, container: HTMLElement, options: { shouldFocusClearButton: boolean; supportsDeletion: boolean; gitHubResourceDetailsResolver?: GitHubResourceDetailsResolver }): IChatAttachmentWidgetInstance; /** * Removes the attachments of pills that were removed from the input, as * removing them from above the input does. @@ -116,8 +127,11 @@ export interface IChatInlineAttachmentsHost { /** The smallest width that keeps the spacer after an anchor, which must exist to place the cursor after a pill at the end of a line. */ const minWrapWidthInEm = 0.001; +/** The horizontal padding of a pill, see `.chat-inline-attachment` in chatInlineAttachments.css. */ +const pillPaddingWidth = 4; const gitHubLinkPattern = /https?:\/\/github\.com\/[^\s/]+\/[^\s/]+\/(?:issues|pull)\/\d+[^\s]*/gi; const inlineAttachmentDragType = 'application/vnd.code.chat-inline-attachment'; +const sessionLinkKind: IChatRequestSessionLinkVariableEntry['kind'] = 'sessionLink'; /** * Shows the attachments of a chat input as pills inline with the prompt text, @@ -128,10 +142,10 @@ const inlineAttachmentDragType = 'application/vnd.code.chat-inline-attachment'; * other character. The anchor is widened to the pill's width, and the pill * itself is a content widget laid out over it. * - * Attachments, references such as `#file:index.ts`, and tool references in the - * input all become pills. Removing a pill removes its attachment. The prompt - * that is submitted and persisted is the input with every pill expanded back to - * the text it stands for, see {@link project}. + * Attachments, references such as `#file:index.ts`, tool references, and links + * to agent sessions in the input all become pills. Removing a pill removes its + * attachment. The prompt that is submitted and persisted is the input with + * every pill expanded back to the text it stands for, see {@link project}. */ export class ChatInlineAttachments extends Disposable { @@ -196,6 +210,7 @@ export class ChatInlineAttachments extends Disposable { * see {@link ChatContextKeys.inputInlineAttachmentActive}. */ private _activePill: InlineAttachmentPill | undefined; + private readonly _gitHubResourceDetailsResolver = new Lazy(() => this._register(this._instantiationService.createInstance(GitHubResourceDetailsResolver))); /** * Whether the cursor was placed by an edit rather than by the user, as when a * prompt is pasted or restored, in which case the pill before it is not @@ -207,6 +222,7 @@ export class ChatInlineAttachments extends Disposable { private readonly _activePillContextKey: IContextKey; private _draggedPill: InlineAttachmentPill | undefined; private readonly _dropTarget: IEditorDecorationsCollection; + private readonly _sessionLinkDetector: ChatInputSessionLinkDetector; constructor( private readonly _editor: ICodeEditor, @@ -215,9 +231,14 @@ export class ChatInlineAttachments extends Disposable { @IConfigurationService private readonly _configurationService: IConfigurationService, @IAccessibilityService private readonly _accessibilityService: IAccessibilityService, @ILabelService private readonly _labelService: ILabelService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IChatAttachmentWidgetRegistry private readonly _attachmentWidgetRegistry: IChatAttachmentWidgetRegistry, + @IProductService productService: IProductService, + @ILogService logService: ILogService, ) { super(); + this._sessionLinkDetector = new ChatInputSessionLinkDetector(productService.urlProtocol, logService); ChatInlineAttachments._byEditor.set(this._editor, this); this._register(toDisposable(() => { if (ChatInlineAttachments._byEditor.get(this._editor) === this) { @@ -299,6 +320,9 @@ export class ChatInlineAttachments extends Disposable { this._updateSelectedPills(); const previousActive = this._activePill; this._updateActivePill(); + if (e.source === 'keyboard' && previousActive !== this._activePill && this._editor.hasTextFocus()) { + this._activePill?.widget?.previewHover?.show(false); + } // The cursor crosses a pill when it is moved, rather than when an edit, such as deleting the pill, moves it. this._announcePillAtCursor(e.reason === CursorChangeReason.Explicit, previousActive); // Typed text that stands for an attachment becomes a pill once the cursor leaves it. @@ -423,7 +447,7 @@ export class ChatInlineAttachments extends Disposable { const range = pill.range; if (range && isAnchorRange(model, range)) { const promptText = options?.forModel && pill.data.reference ? getAttachmentPromptText(this._resolveEntry(pill.data)) : undefined; - anchors.push({ offset: model.getOffsetAt(range.getStartPosition()), text: pill.data.text, reference: pill.data.reference, promptText }); + anchors.push(toAnchor(pill.data, model.getOffsetAt(range.getStartPosition()), promptText)); } } // Pills that this controller's edit adds exist only while it edits, when no request is sent. @@ -525,6 +549,25 @@ export class ChatInlineAttachments extends Disposable { return true; } + /** Returns a lazy, independent presentation for the editor's standard keyboard hover. */ + getReferenceHover(range: Range): { range: Range; createContent: () => HTMLElement | undefined; onDidChange: Event } | undefined { + for (const pill of this._pills) { + const pillRange = pill.range; + if (pillRange && Range.containsRange(pillRange, range) && pill.widget?.supportsPreview) { + const widget = pill.widget; + return { + range: pillRange, + createContent: () => { + widget.previewHover?.hide(); + return widget.getPreviewHoverContent?.(); + }, + onDidChange: widget.onDidChangePreview ?? Event.None, + }; + } + } + return undefined; + } + /** Shows the context menu of the pill right before the cursor for Shift+F10 and the Context Menu key, when the pill has one. */ private _showActivePillContextMenu(e: KeyboardEvent): void { const event = new StandardKeyboardEvent(e); @@ -641,15 +684,13 @@ export class ChatInlineAttachments extends Disposable { this._applyEdits([ { range, text: '' }, { range: Range.fromPositions(position), text: INLINE_ATTACHMENT_ANCHOR }, - ], () => [Selection.fromPositions(model.getPositionAt(offset + 1))], [ - { offset, text: pill.data.text, reference: pill.data.reference }, - ]); + ], () => [Selection.fromPositions(model.getPositionAt(offset + 1))], [toAnchor(pill.data, offset)]); this._editor.pushUndoStop(); const start = model.getPositionAt(offset); pill.moveTo(Range.fromPositions(start, model.getPositionAt(offset + 1)), offset, model.getLineContent(start.lineNumber)); this._scheduleReconcile(); if (this._accessibilityService.isScreenReaderOptimized()) { - status(localize('chat.inlineAttachment.moved', "Moved {0}", getAttachmentLabel(pill.data.entry))); + status(localize('chat.inlineAttachment.moved', "Moved {0}", this._getPillLabel(pill))); } } @@ -898,7 +939,7 @@ export class ChatInlineAttachments extends Disposable { this._host.removeAttachments([...attachmentsToDelete.values()], !change.undoRedo); } if (removed.length === 1 && this._accessibilityService.isScreenReaderOptimized()) { - status(localize('chat.inlineAttachment.removed', "Removed {0}", getAttachmentLabel(removed[0].data.entry))); + status(localize('chat.inlineAttachment.removed', "Removed {0}", this._getPillLabel(removed[0]))); } } @@ -962,6 +1003,25 @@ export class ChatInlineAttachments extends Disposable { pending.push({ data: { id: entry.id, text: part.text, reference: undefined, entry: { ...entry, range: undefined } }, range }); } + // Links to agent sessions, which are recognized from their text where a widget can show the session that they + // link to. The prompt keeps the link exactly where it is, such as within parentheses, so the pill has no reference. + if (this._attachmentWidgetRegistry.hasFactory(sessionLinkKind)) { + // A pill right after a link ends the link, rather than being read as part of it. + const text: ILinkComputerTarget = { + getLineCount: () => model.getLineCount(), + getLineContent: lineNumber => model.getLineContent(lineNumber).replaceAll(INLINE_ATTACHMENT_ANCHOR, ' '), + }; + for (const { range, link } of this._sessionLinkDetector.detect(text)) { + const id = `${sessionLinkKind}:${link.toString()}`; + if (this._expandedByUndoRedo.has(id) || this._isBeingTyped(range) || !claim(range)) { + continue; + } + // The widget names the pill after the session that it finds for the link. + const entry: IChatRequestSessionLinkVariableEntry = { kind: sessionLinkKind, id, name: localize('chat.inlineAttachment.sessionLink', "Session"), value: link }; + pending.push({ data: { id, text: model.getValueInRange(range), reference: undefined, entry, verbatim: true }, range }); + } + } + // Anchors without a pill, which undo and redo did not bring back the pills of, are removed along with the edit that left them behind. const orphans: Range[] = []; if (change && !change.flush && !change.undoRedo) { @@ -1091,7 +1151,7 @@ export class ChatInlineAttachments extends Disposable { .filter(edit => model.getValueInRange(edit.range) !== edit.text) .map(edit => ({ range: edit.range, text: edit.text })), undefined, - pending.map(item => ({ offset: anchorOffsets.get(item)!, text: item.data.text, reference: item.data.reference })), + pending.map(item => toAnchor(item.data, anchorOffsets.get(item)!)), undoable); for (const item of pending) { this._addPill(model, item.data, anchorOffsets.get(item)!); @@ -1124,7 +1184,7 @@ export class ChatInlineAttachments extends Disposable { this._applyEdits( [{ range: Range.fromPositions(position), text }], () => [Selection.fromPositions(model.getPositionAt(offset + text.length))], - pills.map((pill, i) => ({ offset: anchorOffsets[i], text: pill.text, reference: pill.reference }))); + pills.map((pill, i) => toAnchor(pill, anchorOffsets[i]))); this._editor.pushUndoStop(); for (let i = 0; i < pills.length; i++) { this._addPill(model, pills[i], anchorOffsets[i]); @@ -1190,6 +1250,15 @@ export class ChatInlineAttachments extends Disposable { } private _renderPills(): void { + const references = [...this._pills].flatMap(pill => { + const entry = this._resolveEntry(pill.data); + return entry.kind === 'generic' && entry.id.startsWith(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX) + ? [{ identity: entry, resource: URI.parse(entry.id.substring(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX.length)) }] + : []; + }); + if (references.length || this._gitHubResourceDetailsResolver.hasValue) { + this._gitHubResourceDetailsResolver.value.retain(references, this._host.sessionResource?.toString() ?? this._editor.getModel()?.uri.toString()); + } if (!this._needsRender && ![...this._pills].some(pill => pill.needsRender(this._resolveEntry(pill.data)))) { return; } @@ -1201,11 +1270,15 @@ export class ChatInlineAttachments extends Disposable { const anchorWidth = measureAnchorWidth(`${fontInfo.fontWeight} ${fontInfo.fontSize}px ${fontInfo.fontFamily}`); for (const pill of this._pills) { const entry = this._resolveEntry(pill.data); - pill.render(entry, lineHeight, container => this._host.createAttachmentWidget(entry, container, { shouldFocusClearButton: false, supportsDeletion: true }), { + pill.render(entry, lineHeight, container => this._host.createAttachmentWidget(entry, container, { + shouldFocusClearButton: false, + supportsDeletion: true, + gitHubResourceDetailsResolver: references.length ? this._gitHubResourceDetailsResolver.value : undefined, + }), { getClassName: width => this._widthStyles.getClassName(width), // Line wrapping measures the anchor in the editor font rather than at its widened width. getWrapWidthInEm: width => Math.max(0, width - anchorWidth) / fontInfo.fontSize, - hoverMessage: this._getHoverMessage(entry), + hoverMessage: this._getHoverMessage(pill.data, entry), }); } this._updateSelectedPills(); @@ -1218,6 +1291,11 @@ export class ChatInlineAttachments extends Disposable { return entry.range ? { ...entry, range: undefined } : entry; } + /** The name of a pill, as screen readers announce it: what its widget shows, such as the current title of a session, or its attachment's name. */ + private _getPillLabel(pill: InlineAttachmentPill): string { + return pill.displayName ?? getAttachmentLabel(this._resolveEntry(pill.data)); + } + /** The attachment that the input holds because of the pill, which goes when the pill goes. */ private _getAttachmentOwnedByPill(data: IInlineAttachmentPillData): IChatRequestVariableEntry | undefined { if (!data.reference?.isAttachmentReference) { @@ -1368,6 +1446,7 @@ export class ChatInlineAttachments extends Disposable { } } if (active !== this._activePill) { + this._activePill?.widget?.previewHover?.hide(); this._activePill?.setActive(false); this._activePill = active; active?.setActive(true); @@ -1407,7 +1486,7 @@ export class ChatInlineAttachments extends Disposable { if (!pill) { return; } - const label = getAttachmentLabel(this._resolveEntry(pill.data)); + const label = this._getPillLabel(pill); if (!selection.isEmpty()) { status(localize('chat.inlineAttachment.selected', "{0}, attachment, selected", label)); } else if (pill === active) { @@ -1428,11 +1507,21 @@ export class ChatInlineAttachments extends Disposable { private _announceActivatedPill(previousActive: InlineAttachmentPill | undefined): void { const pill = this._activePill; if (pill && pill !== previousActive && this._shouldAnnounceActivePill()) { - status(localize('chat.inlineAttachment.open', "{0}, attachment, press Enter to open", getAttachmentLabel(this._resolveEntry(pill.data)))); + status(localize('chat.inlineAttachment.open', "{0}, attachment, press Enter to open", this._getPillLabel(pill))); } } - private _getHoverMessage(entry: IChatRequestVariableEntry): IMarkdownString { + private _getHoverMessage(data: IInlineAttachmentPillData, entry: IChatRequestVariableEntry): IMarkdownString | undefined { + if (entry.kind === 'generic' && entry.id.startsWith(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX)) { + const resource = URI.parse(entry.id.substring(GITHUB_CONTEXT_ATTACHMENT_ID_PREFIX.length)); + if (parseGitHubReferenceTarget(resource, 'issue') || parseGitHubReferenceTarget(resource, 'pullRequest')) { + return undefined; + } + } + if (isSessionLinkVariableEntry(entry)) { + // The pill shows the session, while the link that it stands for is what the prompt says. + return new MarkdownString().appendText(data.text); + } const resource = IChatRequestVariableEntry.toUri(entry); // The full name of a dropped image is its path, as the path of a file is. const label = resource ? this._labelService.getUriLabel(resource, { relative: true }) : entry.fullName ?? entry.name; @@ -1477,6 +1566,9 @@ export class ChatInlineAttachments extends Disposable { private _clearPills(): void { this._endDrag(); + if (this._gitHubResourceDetailsResolver.hasValue) { + this._gitHubResourceDetailsResolver.value.retain([]); + } for (const pill of this._pills) { pill.dispose(); } @@ -1510,6 +1602,8 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { private _decorationKey: string | undefined; private _width = 0; private _widget: IChatAttachmentWidgetInstance | undefined; + get widget(): IChatAttachmentWidgetInstance | undefined { return this._widget; } + private _displayName: string | undefined; /** The position that the pill was last laid out at. */ private _layoutPosition: Position | undefined; @@ -1533,6 +1627,8 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { // The attachment widgets are styled for attachments in this container. this._container = dom.append(this._domNode, dom.$('.chat-attached-context')); this._decorations = this._editor.createDecorationsCollection([{ range, options: getAnchorDecorationOptions(undefined, 0, undefined) }]); + this._updateMaxWidth(); + this._register(this._editor.onDidLayoutChange(() => this._updateMaxWidth())); this._editor.addContentWidget(this); this._register(toDisposable(() => { this._editor.removeContentWidget(this); @@ -1590,7 +1686,11 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { const widget = store.add(createWidget(this._container)); this._widget = widget; - store.add(toDisposable(() => this._widget = undefined)); + store.add(toDisposable(() => { + // The pill's removal is announced once the pill is gone. + this._displayName = widget.displayName; + this._widget = undefined; + })); // The cursor reaches the pill as a character, so the pill itself is not a tab stop. widget.element.tabIndex = -1; widget.element.draggable = true; @@ -1629,6 +1729,11 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { this._domNode.classList.toggle('active', active); } + /** The name that the pill's widget shows, when it differs from its attachment's, see {@link IChatAttachmentWidgetInstance.displayName}. */ + get displayName(): string | undefined { + return this._widget ? this._widget.displayName : this._displayName; + } + /** Whether the request would not use what the pill stands for, as for a tool that is turned off. */ get isUnavailable(): boolean { return this._domNode.classList.contains('unavailable'); @@ -1645,7 +1750,7 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { /** Whether opening the pill's attachment does something, see {@link canOpenAttachment}. */ get canOpen(): boolean { - return !!this._widget && !!this._renderedEntry && canOpenAttachment(this._renderedEntry); + return !!this._widget?.supportsPreview || (!!this._widget && !!this._renderedEntry && canOpenAttachment(this._renderedEntry)); } /** @@ -1669,6 +1774,23 @@ class InlineAttachmentPill extends Disposable implements IContentWidget { return Math.ceil(this._domNode.getBoundingClientRect().width); } + /** + * Keeps the pill within a row of the input, so that a pill wider than the input + * shortens its label rather than making the input scroll horizontally. + */ + private _updateMaxWidth(): void { + const { contentWidth, verticalScrollbarWidth } = this._editor.getOption(EditorOption.layoutInfo); + const { typicalHalfwidthCharacterWidth } = this._editor.getOption(EditorOption.fontInfo); + // The pill's padding is part of its width. Lines wrap at a whole character, which loses up to a character's + // width, and the anchor needs another character's width to spare to stay on its row. + const maxWidth = Math.floor(contentWidth - verticalScrollbarWidth - pillPaddingWidth - 2 * typicalHalfwidthCharacterWidth); + if (maxWidth > 0) { + this._domNode.style.setProperty('--chat-inline-attachment-max-width', `${maxWidth}px`); + } else { + this._domNode.style.removeProperty('--chat-inline-attachment-max-width'); + } + } + private _updateDecoration(): void { const range = this.range; const options = this._decorationOptions; @@ -1865,6 +1987,11 @@ function isTokenBoundary(value: string, start: number, end: number): boolean { return (!before || isWhitespace(before) || before === INLINE_ATTACHMENT_ANCHOR) && (!after || isWhitespace(after) || after === INLINE_ATTACHMENT_ANCHOR); } +/** The anchor of a pill at an offset of the input, which the prompt replaces with what the pill stands for. */ +function toAnchor(data: IInlineAttachmentPillData, offset: number, promptText?: string): IInlineAttachmentAnchor { + return { offset, text: data.text, reference: data.reference, promptText, verbatim: data.verbatim }; +} + function toAttachmentPillData(attachment: IChatRequestVariableEntry): IInlineAttachmentPillData { const text = getAttachmentMention(attachment.name); return { id: attachment.id, text, reference: toAttachedContextDynamicVariable(attachment, new Range(1, 1, 1, 1 + text.length)), entry: attachment }; @@ -1925,7 +2052,7 @@ class OpenInlineAttachmentAction extends Action2 { title: localize2('chat.openInlineAttachment', "Open Inline Attachment"), precondition: ChatContextKeys.enabled, keybinding: { - when: ContextKeyExpr.and(ChatContextKeys.inChatInput, ChatContextKeys.inputInlineAttachmentActive), + when: ContextKeyExpr.and(ChatContextKeys.inChatInput, ChatContextKeys.inputInlineAttachmentActive, EditorContextKeys.hoverFocused.negate()), primary: KeyCode.Enter, // Above sending the request, below accepting a suggestion. weight: KeybindingWeight.EditorContrib + 10, diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts index b87e3567842b..26d7c262da61 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; import { coalesce } from '../../../../../../../base/common/arrays.js'; import { decodeBase64 } from '../../../../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../../../base/common/cancellation.js'; @@ -414,7 +415,7 @@ export class AgentCompletions extends Disposable { } const agentHostSession = isAgentHostBackedWidget(widget); - if (agentHostSession && (widget.location !== ChatAgentLocation.Chat || IsSessionsWindowContext.getValue(widget.scopedContextKeyService))) { + if (agentHostSession && (widget.location !== ChatAgentLocation.Chat || IsSessionsWindowContext.getValue(widget.scopedContextKeyService) || ChatContextKeys.inSessionsChat.getValue(widget.scopedContextKeyService))) { return; } @@ -456,7 +457,7 @@ export class AgentCompletions extends Disposable { } const agentHostSession = isAgentHostBackedWidget(widget); - if (agentHostSession && (widget.location !== ChatAgentLocation.Chat || IsSessionsWindowContext.getValue(widget.scopedContextKeyService))) { + if (agentHostSession && (widget.location !== ChatAgentLocation.Chat || IsSessionsWindowContext.getValue(widget.scopedContextKeyService) || ChatContextKeys.inSessionsChat.getValue(widget.scopedContextKeyService))) { return; } if (widget.lockedAgentId && !agentHostSession) { diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorContrib.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorContrib.ts index a771e3d79228..82fb68f7c7ac 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorContrib.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorContrib.ts @@ -4,26 +4,32 @@ *--------------------------------------------------------------------------------------------*/ import { MarkdownString } from '../../../../../../../base/common/htmlContent.js'; -import { Disposable, MutableDisposable } from '../../../../../../../base/common/lifecycle.js'; -import { autorun, observableSignalFromEvent } from '../../../../../../../base/common/observable.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../../../../base/common/observable.js'; import { themeColorFromId } from '../../../../../../../base/common/themables.js'; import { URI } from '../../../../../../../base/common/uri.js'; +import { isUUID } from '../../../../../../../base/common/uuid.js'; import { MouseTargetType } from '../../../../../../../editor/browser/editorBrowser.js'; import { ICodeEditorService } from '../../../../../../../editor/browser/services/codeEditorService.js'; import { EditorOption } from '../../../../../../../editor/common/config/editorOptions.js'; import { Position } from '../../../../../../../editor/common/core/position.js'; import { IRange, Range } from '../../../../../../../editor/common/core/range.js'; import { IDecorationOptions } from '../../../../../../../editor/common/editorCommon.js'; +import { Action2, registerAction2 } from '../../../../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../../../../platform/contextkey/common/contextkey.js'; +import { ServicesAccessor } from '../../../../../../../platform/instantiation/common/instantiation.js'; import { ILabelService } from '../../../../../../../platform/label/common/label.js'; import { IThemeService } from '../../../../../../../platform/theme/common/themeService.js'; import { getInputPlaceholderColor, getRangeForPlaceholder } from './chatInputPlaceholderDecoration.js'; import { IChatAgentCommand, IChatAgentData, IChatAgentService } from '../../../../common/participants/chatAgents.js'; import { INLINE_ATTACHMENT_ANCHOR } from '../../../../common/attachments/chatInlineAttachments.js'; -import { localize } from '../../../../../../../nls.js'; +import { localize, localize2 } from '../../../../../../../nls.js'; +import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; import { chatSlashCommandBackground, chatSlashCommandForeground } from '../../../../common/widget/chatColors.js'; import { ChatRequestAgentPart, ChatRequestAgentSubcommandPart, ChatRequestDynamicVariablePart, ChatRequestSlashCommandPart, ChatRequestSlashPromptPart, ChatRequestTextPart, ChatRequestToolPart, ChatRequestToolSetPart, IParsedChatRequestPart, chatAgentLeader, chatSubcommandLeader } from '../../../../common/requestParser/chatParserTypes.js'; import { agentReg, slashReg, variableReg } from '../../../../common/requestParser/chatRequestParser.js'; -import { IChatWidget } from '../../../chat.js'; +import { IChatWidget, IChatWidgetService } from '../../../chat.js'; +import { CHAT_CATEGORY } from '../../../actions/chatActions.js'; import { ChatWidget } from '../../chatWidget.js'; import { registerChatInputReferenceDecorationType } from './chatInputReferenceDecorations.js'; import { NativeEditContextRegistry } from '../../../../../../../editor/browser/controller/editContext/native/nativeEditContextRegistry.js'; @@ -35,6 +41,7 @@ import { IEditorService } from '../../../../../../services/editor/common/editorS import { getChatSessionType } from '../../../../common/model/chatUri.js'; import { ICustomizationHarnessService } from '../../../../common/customizationHarnessService.js'; import { getSandboxPlaceholder } from './chatInputSandboxContribution.js'; +import { AgentHostCompletionReferenceKind, getAgentHostCompletionReferenceKindFromValue } from '../../../../common/attachments/chatVariableEntries.js'; const decorationDescription = 'chat'; const placeholderDecorationType = 'chat-session-detail'; @@ -60,18 +67,26 @@ function exactlyOneSpaceAfterPart(parsedRequest: readonly IParsedChatRequestPart return nextPart && nextPart instanceof ChatRequestTextPart && nextPart.text === ' '; } +function getSkillResource(variable: ChatRequestDynamicVariablePart): URI | undefined { + if (getAgentHostCompletionReferenceKindFromValue(variable.data) !== AgentHostCompletionReferenceKind.Skill || isUUID(variable.id)) { + return undefined; + } + return URI.parse(variable.id, true); +} + class InputEditorDecorations extends Disposable { private static readonly UPDATE_DELAY = 200; - public readonly id = 'inputEditorDecorations'; + static readonly ID = 'inputEditorDecorations'; + public readonly id = InputEditorDecorations.ID; private readonly previouslyUsedAgents = new Set(); - private clickablePromptSlashCommand: { range: Range; uri: URI } | undefined; - private mouseDownPromptSlashCommand: { position: Position; uri: URI; range: Range } | undefined; + private clickableReferences: { range: Range; uri: URI }[] = []; + private mouseDownReference: { position: Position; uri: URI; range: Range } | undefined; private readonly viewModelDisposables = this._register(new MutableDisposable()); - + private readonly inputEditorDisposables = this._register(new MutableDisposable()); private readonly updateThrottle = this._register(new ThrottledDelayer(InputEditorDecorations.UPDATE_DELAY)); @@ -87,16 +102,11 @@ class InputEditorDecorations extends Disposable { super(); this.registeredDecorationTypes(); + this.registerInputEditorListeners(); this.triggerInputEditorDecorationsUpdate(); - this._register(this.widget.inputEditor.onDidChangeModelContent(() => this.triggerInputEditorDecorationsUpdate())); - this._register(this.widget.inputEditor.onDidChangeConfiguration(e => { - // The editor's placeholder option is set/cleared by features such as - // dictation ("Listening…"). When it is set, PlaceholderTextContribution - // renders it, so the decoration placeholder must yield to avoid two - // overlapping placeholders; re-run when the option changes. - if (e.hasChanged(EditorOption.placeholder)) { - this.triggerInputEditorDecorationsUpdate(); - } + this._register(this.widget.onDidChangeActiveInputEditor(() => { + this.registerInputEditorListeners(); + this.triggerInputEditorDecorationsUpdate(); })); this._register(this.widget.onDidChangeParsedInput(() => this.triggerInputEditorDecorationsUpdate())); this._register(this.widget.onDidChangeViewModel(() => { @@ -107,38 +117,6 @@ class InputEditorDecorations extends Disposable { this._register(this.widget.onDidSubmitAgent((e) => { this.previouslyUsedAgents.add(agentAndCommandToKey(e.agent, e.slashCommand?.name)); })); - this._register(this.widget.inputEditor.onMouseDown(e => { - this.mouseDownPromptSlashCommand = undefined; - - if (!e.event.leftButton || e.target.type !== MouseTargetType.CONTENT_TEXT || !e.target.position) { - return; - } - - const clickablePromptSlashCommand = this.clickablePromptSlashCommand; - if (!clickablePromptSlashCommand || !clickablePromptSlashCommand.range.containsPosition(e.target.position)) { - return; - } - - this.mouseDownPromptSlashCommand = { - position: Position.lift(e.target.position), - uri: clickablePromptSlashCommand.uri, - range: clickablePromptSlashCommand.range, - }; - })); - this._register(this.widget.inputEditor.onMouseUp(e => { - const mouseDownPromptSlashCommand = this.mouseDownPromptSlashCommand; - this.mouseDownPromptSlashCommand = undefined; - - if (!mouseDownPromptSlashCommand || e.target.type !== MouseTargetType.CONTENT_TEXT || !e.target.position) { - return; - } - - if (!mouseDownPromptSlashCommand.range.containsPosition(e.target.position) || !Position.equals(mouseDownPromptSlashCommand.position, e.target.position)) { - return; - } - - void this.editorService.openEditor({ resource: mouseDownPromptSlashCommand.uri }); - })); this._register(this.chatAgentService.onDidChangeAgents(() => this.triggerInputEditorDecorationsUpdate())); this._register(this.customizationHarnessService.onDidChangeSlashCommands((e) => { const sessionResource = this.widget.viewModel?.sessionResource; @@ -146,9 +124,7 @@ class InputEditorDecorations extends Disposable { this.triggerInputEditorDecorationsUpdate(); } })); - const activeInputChanged = observableSignalFromEvent(this, this.widget.onDidChangeActiveInputEditor); this._register(autorun(reader => { - activeInputChanged.read(reader); this.widget.input.sandboxToggleChecked.read(reader); const currentMode = this.widget.input.currentModeObs.read(reader); if (currentMode) { @@ -162,6 +138,70 @@ class InputEditorDecorations extends Disposable { this.registerViewModelListeners(); } + async openSkillAtCursor(): Promise { + const editor = this.widget.inputEditor; + const position = editor.getPosition(); + if (!position || !editor.getSelection()?.isEmpty()) { + return; + } + + const variable = this.widget.parsedInput.parts.find((part): part is ChatRequestDynamicVariablePart => + part instanceof ChatRequestDynamicVariablePart + && Range.containsPosition(part.editorRange, position) + && !Position.equals(Range.getEndPosition(part.editorRange), position)); + const resource = variable && getSkillResource(variable); + if (resource) { + await this.editorService.openEditor({ resource }); + } + } + + private registerInputEditorListeners(): void { + const store = new DisposableStore(); + this.inputEditorDisposables.value = store; + this.mouseDownReference = undefined; + this.clickableReferences = []; + const editor = this.widget.inputEditor; + store.add(editor.onDidChangeModelContent(() => this.triggerInputEditorDecorationsUpdate())); + store.add(editor.onDidChangeConfiguration(e => { + if (e.hasChanged(EditorOption.placeholder)) { + this.triggerInputEditorDecorationsUpdate(); + } + })); + store.add(editor.onMouseDown(e => { + this.mouseDownReference = undefined; + + if (!e.event.leftButton || e.target.type !== MouseTargetType.CONTENT_TEXT || !e.target.position) { + return; + } + + const position = e.target.position; + const reference = this.clickableReferences.find(reference => reference.range.containsPosition(position) && !Position.equals(reference.range.getEndPosition(), position)); + if (!reference) { + return; + } + + this.mouseDownReference = { + position: Position.lift(position), + uri: reference.uri, + range: reference.range, + }; + })); + store.add(editor.onMouseUp(e => { + const mouseDownReference = this.mouseDownReference; + this.mouseDownReference = undefined; + + if (!mouseDownReference || !e.event.leftButton || e.target.type !== MouseTargetType.CONTENT_TEXT || !e.target.position) { + return; + } + + if (!mouseDownReference.range.containsPosition(e.target.position) || !Position.equals(mouseDownReference.position, e.target.position)) { + return; + } + + void this.editorService.openEditor({ resource: mouseDownReference.uri }); + })); + } + private registerViewModelListeners(): void { this.viewModelDisposables.value = this.widget.viewModel?.onDidChange(e => { if (e?.kind === 'changePlaceholder' || e?.kind === 'initialize') { @@ -321,7 +361,8 @@ class InputEditorDecorations extends Disposable { } private async updateAsyncInputEditorDecorations(token: CancellationToken): Promise { - this.clickablePromptSlashCommand = undefined; + const editor = this.widget.inputEditor; + this.clickableReferences = []; this.widget.inputEditor.setDecorationsByType(decorationDescription, clickableSlashPromptTextDecorationType, []); const parsedRequest = this.widget.parsedInput.parts; @@ -330,6 +371,16 @@ class InputEditorDecorations extends Disposable { return; } + const dynamicVariableParts = parsedRequest.filter((p): p is ChatRequestDynamicVariablePart => p instanceof ChatRequestDynamicVariablePart); + const clickableDecorations: IDecorationOptions[] = []; + for (const variable of dynamicVariableParts) { + const uri = getSkillResource(variable); + if (uri) { + clickableDecorations.push(this.createClickableReferenceDecoration(variable.editorRange, uri, variable.modelDescription)); + } + } + this.widget.inputEditor.setDecorationsByType(decorationDescription, clickableSlashPromptTextDecorationType, clickableDecorations); + const agentPart = parsedRequest.find((p): p is ChatRequestAgentPart => p instanceof ChatRequestAgentPart); const agentSubcommandPart = parsedRequest.find((p): p is ChatRequestAgentSubcommandPart => p instanceof ChatRequestAgentSubcommandPart); const slashCommandPart = parsedRequest.find((p): p is ChatRequestSlashCommandPart => p instanceof ChatRequestSlashCommandPart); @@ -337,7 +388,7 @@ class InputEditorDecorations extends Disposable { // first, fetch all async context const promptSlashCommand = slashPromptPart ? await this.customizationHarnessService.resolvePromptSlashCommand(slashPromptPart.name, viewModel.sessionResource, token) : undefined; - if (token.isCancellationRequested) { + if (token.isCancellationRequested || editor !== this.widget.inputEditor) { // a new update came in while we were waiting return; } @@ -373,25 +424,8 @@ class InputEditorDecorations extends Disposable { } if (slashPromptPart && promptSlashCommand) { - this.clickablePromptSlashCommand = { - range: Range.lift(slashPromptPart.editorRange), - uri: promptSlashCommand.uri, - }; - const promptHoverMessage = new MarkdownString(); - if (promptSlashCommand.description) { - promptHoverMessage.appendText(promptSlashCommand.description); - promptHoverMessage.appendText('\n'); - } - promptHoverMessage.appendText(localize( - 'chatInput.promptSlashCommand.open', - "Click to open {0}", - this.labelService.getUriLabel(promptSlashCommand.uri, { relative: true }) - )); - const promptDecoration = { - range: slashPromptPart.editorRange, - hoverMessage: promptHoverMessage, - }; - this.widget.inputEditor.setDecorationsByType(decorationDescription, clickableSlashPromptTextDecorationType, [promptDecoration]); + clickableDecorations.push(this.createClickableReferenceDecoration(slashPromptPart.editorRange, promptSlashCommand.uri, promptSlashCommand.description)); + this.widget.inputEditor.setDecorationsByType(decorationDescription, clickableSlashPromptTextDecorationType, clickableDecorations); } this.widget.inputEditor.setDecorationsByType(decorationDescription, slashCommandTextDecorationType, textDecorations); @@ -407,8 +441,6 @@ class InputEditorDecorations extends Disposable { } } - const dynamicVariableParts = parsedRequest.filter((p): p is ChatRequestDynamicVariablePart => p instanceof ChatRequestDynamicVariablePart); - const isEditingPreviousRequest = !!viewModel.editing; if (isEditingPreviousRequest) { for (const variable of dynamicVariableParts) { @@ -421,6 +453,21 @@ class InputEditorDecorations extends Disposable { this.widget.inputEditor.setDecorationsByType(decorationDescription, variableTextDecorationType, varDecorations); } + private createClickableReferenceDecoration(range: IRange, uri: URI, description?: string): IDecorationOptions { + this.clickableReferences.push({ range: Range.lift(range), uri }); + const hoverMessage = new MarkdownString(); + if (description) { + hoverMessage.appendText(description); + hoverMessage.appendText('\n'); + } + hoverMessage.appendText(localize( + 'chatInput.promptSlashCommand.open', + "Click to open {0}", + this.labelService.getUriLabel(uri, { relative: true }) + )); + return { range, hoverMessage }; + } + private updateAriaPlaceholder(value: string | undefined): void { const nativeEditContext = NativeEditContextRegistry.get(this.widget.inputEditor.getId()); if (nativeEditContext) { @@ -483,6 +530,23 @@ class InputEditorSlashCommandMode extends Disposable { ChatWidget.CONTRIBS.push(InputEditorDecorations, InputEditorSlashCommandMode); +registerAction2(class OpenSkillAtCursorAction extends Action2 { + constructor() { + super({ + id: 'workbench.action.chat.openSkillAtCursor', + title: localize2('chat.openSkillAtCursor', "Open Skill at Cursor"), + category: CHAT_CATEGORY, + f1: true, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.inChatInput), + }); + } + + async run(accessor: ServicesAccessor): Promise { + const widget = accessor.get(IChatWidgetService).lastFocusedWidget; + await widget?.getContrib(InputEditorDecorations.ID)?.openSkillAtCursor(); + } +}); + class ChatTokenDeleter extends Disposable { public readonly id = 'chatTokenDeleter'; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorHover.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorHover.ts index 99f32c0fea55..665574c48bab 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorHover.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputEditorHover.ts @@ -3,7 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { DisposableStore } from '../../../../../../../base/common/lifecycle.js'; +import { DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.js'; +import { Event } from '../../../../../../../base/common/event.js'; import { ICodeEditor } from '../../../../../../../editor/browser/editorBrowser.js'; import { Range } from '../../../../../../../editor/common/core/range.js'; import { IModelDecoration } from '../../../../../../../editor/common/model.js'; @@ -20,6 +21,21 @@ import { isImageVariableEntry, type IImageVariableEntry } from '../../../../comm import { coerceImageBuffer } from '../../../../common/chatImageExtraction.js'; import { createChatImageHoverContent } from '../../../../../../browser/chatImagePreview.js'; import { URI } from '../../../../../../../base/common/uri.js'; +import { ChatInlineAttachments } from './chatInlineAttachments.js'; +import { HoverStartSource } from '../../../../../../../editor/contrib/hover/browser/hoverOperation.js'; +import { KeyChord, KeyCode, KeyMod } from '../../../../../../../base/common/keyCodes.js'; +import { SHOW_OR_FOCUS_HOVER_ACTION_ID } from '../../../../../../../editor/contrib/hover/browser/hoverActionIds.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; +import { ContextKeyExpr } from '../../../../../../../platform/contextkey/common/contextkey.js'; +import { EditorContextKeys } from '../../../../../../../editor/common/editorContextKeys.js'; + +KeybindingsRegistry.registerKeybindingRule({ + id: SHOW_OR_FOCUS_HOVER_ACTION_ID, + weight: KeybindingWeight.WorkbenchContrib, + when: ContextKeyExpr.and(ChatContextKeys.inChatInput, EditorContextKeys.textInputFocus), + primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyCode.KeyI), +}); export class ChatAgentHoverParticipant implements IEditorHoverParticipant { @@ -176,3 +192,56 @@ export class ChatAttachmentReferenceHoverPart implements IHoverPart { } HoverParticipantRegistry.register(ChatAttachmentReferenceHoverParticipant); + +class ChatInlineReferenceHoverParticipant implements IEditorHoverParticipant { + + readonly hoverOrdinal = 3; + + constructor(private readonly editor: ICodeEditor) { } + + computeSync(anchor: HoverAnchor, _lineDecorations: IModelDecoration[], source: HoverStartSource): ChatInlineReferenceHoverPart[] { + if (source !== HoverStartSource.Keyboard || anchor.type !== HoverAnchorType.Range) { + return []; + } + const reference = ChatInlineAttachments.get(this.editor)?.getReferenceHover(anchor.range); + return reference ? [new ChatInlineReferenceHoverPart(this, reference.range, reference.createContent, reference.onDidChange)] : []; + } + + renderHoverParts(context: IEditorHoverRenderContext, hoverParts: ChatInlineReferenceHoverPart[]): IRenderedHoverParts { + const hoverPart = hoverParts[0]; + const content = hoverPart?.createContent(); + if (!content) { + return new RenderedHoverParts([]); + } + const store = new DisposableStore(); + hoverPart.element = content; + context.fragment.appendChild(content); + const observer = new MutationObserver(() => context.onContentsChanged()); + observer.observe(content, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['aria-busy'] }); + store.add(toDisposable(() => observer.disconnect())); + store.add(hoverPart.onDidChange(() => context.hide())); + return new RenderedHoverParts([{ hoverPart, hoverElement: content, dispose: () => store.dispose() }]); + } + + getAccessibleContent(hoverPart: ChatInlineReferenceHoverPart): string { + return hoverPart.element?.innerText || hoverPart.element?.textContent || ''; + } +} + +class ChatInlineReferenceHoverPart implements IHoverPart { + + element: HTMLElement | undefined; + + constructor( + readonly owner: ChatInlineReferenceHoverParticipant, + readonly range: Range, + readonly createContent: () => HTMLElement | undefined, + readonly onDidChange: Event, + ) { } + + isValidForHoverAnchor(anchor: HoverAnchor): boolean { + return anchor.type === HoverAnchorType.Range && Range.containsRange(this.range, anchor.range); + } +} + +HoverParticipantRegistry.register(ChatInlineReferenceHoverParticipant); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputSessionLinkProvider.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputSessionLinkProvider.ts index cf3f3b803554..f5e1bd5afa08 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputSessionLinkProvider.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputSessionLinkProvider.ts @@ -7,8 +7,8 @@ import { Disposable } from '../../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../../base/common/network.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { Range } from '../../../../../../../editor/common/core/range.js'; -import { ILink, ILinksList, LinkProvider } from '../../../../../../../editor/common/languages.js'; -import { Edge, LinkComputer, State, StateMachine } from '../../../../../../../editor/common/languages/linkComputer.js'; +import { ILinksList, LinkProvider } from '../../../../../../../editor/common/languages.js'; +import { Edge, ILinkComputerTarget, LinkComputer, State, StateMachine } from '../../../../../../../editor/common/languages/linkComputer.js'; import { ITextModel } from '../../../../../../../editor/common/model.js'; import { ILanguageFeaturesService } from '../../../../../../../editor/common/services/languageFeatures.js'; import { localize2 } from '../../../../../../../nls.js'; @@ -19,17 +19,27 @@ import { IProductService } from '../../../../../../../platform/product/common/pr import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; import { chatInputSchemes } from '../../../../common/constants.js'; -export class ChatInputSessionLinkProvider extends Disposable implements LinkProvider { - private readonly stateMachines: readonly StateMachine[]; +/** A link to an agent session in a chat input. */ +export interface IChatInputSessionLink { + readonly range: Range; + /** The `agent-host-session://` link that opens the session, which the link in the input carries. */ + readonly link: URI; +} + +/** + * Finds the links to agent sessions in a chat input: `agent-host-session://` + * links, and product protocol URLs that carry one, such as those that Copy Link + * copies. Ordinary links that contain a session link are left alone. + */ +export class ChatInputSessionLinkDetector { + private readonly _stateMachines: readonly StateMachine[]; constructor( - @ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService, - @IProductService productService: IProductService, - @ILogService private readonly logService: ILogService, + productUrlProtocol: string, + private readonly _logService: ILogService, ) { - super(); - const schemes = new Set([AGENT_HOST_SESSION_LINK_SCHEME, Schemas.vscode, `${Schemas.vscode}-insiders`, productService.urlProtocol]); - this.stateMachines = [...schemes].map(scheme => { + const schemes = new Set([AGENT_HOST_SESSION_LINK_SCHEME, Schemas.vscode, `${Schemas.vscode}-insiders`, productUrlProtocol]); + this._stateMachines = [...schemes].map(scheme => { const prefix = `${scheme}://`; const edges: Edge[] = []; for (let i = 0; i < prefix.length; i++) { @@ -39,17 +49,17 @@ export class ChatInputSessionLinkProvider extends Disposable implements LinkProv } return new StateMachine(edges); }); - this._register(languageFeaturesService.linkProvider.register(chatInputSchemes.map(scheme => ({ scheme, hasAccessToAllModels: true })), this)); - this._register(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { - command: { id: 'editor.action.openLink', title: localize2('openLink', "Open Link") }, - when: ChatContextKeys.enabled, - })); } - provideLinks(model: ITextModel): ILinksList { - const links: ILink[] = []; + /** The session links in `model`, in the order they appear. */ + detect(model: ILinkComputerTarget): IChatInputSessionLink[] { + // Every session link, including a product protocol URL that carries one, names the scheme. + if (!hasLineIncluding(model, AGENT_HOST_SESSION_LINK_SCHEME)) { + return []; + } + const links: IChatInputSessionLink[] = []; const ordinaryLinks = LinkComputer.computeLinks(model); - for (const stateMachine of this.stateMachines) { + for (const stateMachine of this._stateMachines) { for (const link of LinkComputer.computeLinks(model, stateMachine)) { if (typeof link.url !== 'string' || ordinaryLinks.some(ordinaryLink => Range.containsRange(ordinaryLink.range, link.range))) { continue; @@ -61,14 +71,45 @@ export class ChatInputSessionLinkProvider extends Disposable implements LinkProv ? parseOpenSessionLinkUri(uri) ? uri : undefined : parseExternalOpenSessionLinkUri(uri, uri.scheme); } catch (error) { - this.logService.warn('Failed to parse session link in chat input', error); + this._logService.warn('Failed to parse session link in chat input', error); continue; } if (sessionLink) { - links.push({ range: link.range, url: sessionLink }); + links.push({ range: Range.lift(link.range), link: sessionLink }); } } } - return { links: links.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range)) }; + return links.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range)); + } +} + +function hasLineIncluding(model: ILinkComputerTarget, text: string): boolean { + for (let lineNumber = 1; lineNumber <= model.getLineCount(); lineNumber++) { + if (model.getLineContent(lineNumber).includes(text)) { + return true; + } + } + return false; +} + +export class ChatInputSessionLinkProvider extends Disposable implements LinkProvider { + private readonly _detector: ChatInputSessionLinkDetector; + + constructor( + @ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService, + @IProductService productService: IProductService, + @ILogService logService: ILogService, + ) { + super(); + this._detector = new ChatInputSessionLinkDetector(productService.urlProtocol, logService); + this._register(languageFeaturesService.linkProvider.register(chatInputSchemes.map(scheme => ({ scheme, hasAccessToAllModels: true })), this)); + this._register(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { + command: { id: 'editor.action.openLink', title: localize2('openLink', "Open Link") }, + when: ChatContextKeys.enabled, + })); + } + + provideLinks(model: ITextModel): ILinksList { + return { links: this._detector.detect(model).map(({ range, link }) => ({ range, url: link })) }; } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatPasteProviders.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatPasteProviders.ts index f87420c8178f..6fe0cbbecc6a 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatPasteProviders.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatPasteProviders.ts @@ -5,13 +5,14 @@ import { alert, status } from '../../../../../../../base/browser/ui/aria/aria.js'; import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../../base/common/codicons.js'; -import { createStringDataTransferItem, IDataTransferItem, IReadonlyVSDataTransfer, VSDataTransfer } from '../../../../../../../base/common/dataTransfer.js'; +import { createStringDataTransferItem, IDataTransferFile, IDataTransferItem, IReadonlyVSDataTransfer, VSDataTransfer } from '../../../../../../../base/common/dataTransfer.js'; import { convertHtmlToMarkdown } from '../../../../../../../base/browser/htmlToMarkdown.js'; import { HierarchicalKind } from '../../../../../../../base/common/hierarchicalKind.js'; import { Disposable } from '../../../../../../../base/common/lifecycle.js'; import { revive } from '../../../../../../../base/common/marshalling.js'; import { Mimes } from '../../../../../../../base/common/mime.js'; import { Schemas } from '../../../../../../../base/common/network.js'; +import { extname } from '../../../../../../../base/common/path.js'; import { basename, joinPath } from '../../../../../../../base/common/resources.js'; import { URI, UriComponents } from '../../../../../../../base/common/uri.js'; import { Position } from '../../../../../../../editor/common/core/position.js'; @@ -105,7 +106,8 @@ export class PasteImageProvider implements DocumentPasteEditProvider { if (!imageItem || !mimeType) { return; } - const currClipboard = await imageItem.asFile()?.data(); + const imageFile = imageItem.asFile(); + const currClipboard = await imageFile?.data(); if (token.isCancellationRequested || !currClipboard) { return; } @@ -115,13 +117,7 @@ export class PasteImageProvider implements DocumentPasteEditProvider { return; } - const attachedVariables = target.attachments; - const displayName = localize('pastedImageName', 'Pasted Image'); - let tempDisplayName = displayName; - - for (let appendValue = 2; attachedVariables.some(attachment => attachment.name === tempDisplayName); appendValue++) { - tempDisplayName = `${displayName} ${appendValue}`; - } + const tempDisplayName = getPastedImageName(imageFile, target.attachments.map(attachment => attachment.name)); const fileReference = await createFileForMedia(this.fileService, this.imagesFolder, currClipboard, mimeType); if (token.isCancellationRequested || !fileReference) { @@ -149,6 +145,26 @@ export class PasteImageProvider implements DocumentPasteEditProvider { } } +/** + * Names a pasted image after the file it was pasted from (e.g. a file copied in the OS file + * manager or a screenshot tool that saves to disk), or "Pasted Image" for raw clipboard data. + * A counter before the extension keeps the name unique among the existing attachments. + */ +export function getPastedImageName(file: IDataTransferFile | undefined, existingNames: readonly string[]): string { + // Raw clipboard images have a generic name such as "image.png" and no uri. Use the name rather than + // the uri's basename: the uri is parsed from a native path, so it breaks on Windows paths and on '#'. + const fileName = file?.uri ? file.name : ''; + const baseName = fileName || localize('pastedImageName', 'Pasted Image'); + const extension = extname(fileName); + const stem = baseName.slice(0, baseName.length - extension.length); + + let candidate = baseName; + for (let counter = 2; existingNames.includes(candidate); counter++) { + candidate = `${stem} ${counter}${extension}`; + } + return candidate; +} + async function getImageAttachContext(data: Uint8Array, mimeType: string, token: CancellationToken, displayName: string, resource: URI): Promise { const imageHash = await imageToHash(data); if (token.isCancellationRequested) { diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/media/chatInlineAttachments.css b/src/vs/workbench/contrib/chat/browser/widget/input/editor/media/chatInlineAttachments.css index 62a1497467bd..111d78c790ff 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/media/chatInlineAttachments.css +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/media/chatInlineAttachments.css @@ -50,8 +50,9 @@ pointer-events: auto; } +/* The pill fits in a row of the input, which sets the variable from its width, and shortens its label to fit. */ .interactive-session .monaco-editor .chat-inline-attachment .chat-attached-context-attachment { - max-width: 240px; + max-width: min(240px, var(--chat-inline-attachment-max-width, 240px)); } /* diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotice.css b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotice.css index 92df580f555f..045efb00126d 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotice.css +++ b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotice.css @@ -189,7 +189,7 @@ height: 100%; padding: 0; border: none; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); background-color: transparent; color: var(--vscode-dropdown-foreground, var(--vscode-foreground)); font-family: inherit; @@ -219,7 +219,7 @@ width: var(--vscode-spacing-size200); height: var(--vscode-spacing-size200); padding: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-descriptionForeground); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotificationWidget.css b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotificationWidget.css index bc55112e839a..4edf15fb9b69 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotificationWidget.css +++ b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputNotificationWidget.css @@ -221,4 +221,22 @@ animation-timing-function: steps(10, end); } +/* A transcript notice belongs to the response, not the framed composer stack. */ +.interactive-item-container > .chat-input-notice.chat-input-notification-widget { + margin-block: var(--vscode-spacing-size120) var(--vscode-spacing-size80); + padding: 0; + border: 0; + border-radius: 0; + background: transparent; +} + +.interactive-item-container > .chat-input-notification-widget .chat-input-notification-body { + flex-direction: column; +} + +.interactive-item-container > .chat-input-notification-widget .chat-input-notification-actions { + margin-inline-start: 0; + justify-content: flex-start; +} + /* Dismiss + mute icon buttons are styled by `.chat-input-notice-action`. */ diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputPicker.css b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputPicker.css index f95d02a7b119..793af3e8a768 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputPicker.css +++ b/src/vs/workbench/contrib/chat/browser/widget/input/media/chatInputPicker.css @@ -39,12 +39,16 @@ background-color: var(--vscode-toolbar-hoverBackground); } +.monaco-workbench .monaco-action-bar:not(.vertical) .action-item .action-label.chat-input-picker-split:hover:not(.disabled) { + outline: none; +} + .chat-input-picker-split:not(.disabled, [aria-disabled='true']) > .chat-input-picker-split-button:not([aria-disabled='true']):is(:hover, .hovered, [aria-expanded='true']) { background-color: var(--vscode-toolbar-activeBackground, var(--vscode-toolbar-hoverBackground)); color: var(--vscode-foreground); } -.monaco-workbench .chat-input-picker-split-button:focus-visible, +.monaco-workbench .chat-input-picker-split-button:is(:focus-visible, .focus-visible), .monaco-workbench .chat-input-picker-focus-scope :is(.action-label, .monaco-button):focus-visible { outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); outline-offset: calc(-1 * var(--vscode-strokeThickness)); @@ -55,3 +59,13 @@ .monaco-workbench .chat-input-picker-focus-scope.pointer-focus :is(.action-label, .chat-input-picker-split-button, .monaco-button):focus { outline: none; } + +.monaco-workbench:is(.hc-black, .hc-light) .chat-input-picker-split:not(.disabled, [aria-disabled='true']) > .chat-input-picker-split-button:not([aria-disabled='true'], [aria-expanded='true'], :focus-visible, .focus-visible):is(:hover, .hovered) { + outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + +.monaco-workbench:is(.hc-black, .hc-light) .chat-input-picker-split:not(.disabled, [aria-disabled='true']) > .chat-input-picker-split-button:not([aria-disabled='true'])[aria-expanded='true'] { + outline: var(--vscode-strokeThickness, 1px) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} 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 b5e2481aeac4..7ebd980b5e2b 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 @@ -652,7 +652,7 @@ width: auto; height: var(--vscode-spacing-size200); padding: var(--vscode-spacing-sizeNone) var(--vscode-spacing-size160) var(--vscode-spacing-sizeNone) var(--vscode-spacing-size40); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-descriptionForeground); background: transparent; font-size: var(--vscode-fontSize-label2); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelCard.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelCard.ts index 1f269191fa30..59324a4cecc8 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelCard.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelCard.ts @@ -50,7 +50,7 @@ function getThinkingSignature(directModel: ILocalModelDirectModelConfig | undefi } /** Everything the page shows except progress: a change re-renders it, progress alone updates it in place. */ -function getCardSignature({ status, family, readiness, directModel, pendingStops }: ILocalModelDetails): string { +function getCardSignature({ status, family, readiness, directModel, pendingStops, autoModelFusion }: ILocalModelDetails): string { const { usage: _usage, operation, ...rest } = family; return JSON.stringify([ readiness, @@ -59,6 +59,7 @@ function getCardSignature({ status, family, readiness, directModel, pendingStops status.runtime, status.active && { ...status.active, drain: !!status.active.drain }, status.useInAuto, + !!autoModelFusion, status.device, getThinkingSignature(directModel), [operation?.id, getLocalModelServerStopId(family.familyId)].map(id => !!id && !!pendingStops?.has(id)), @@ -794,10 +795,16 @@ export class LocalModelCard extends DisposableStore { const { status, family } = details; const active = status.active?.familyId === family.familyId ? status.active : undefined; const tooSlow = active?.autoEligible === false; - const label = localize('localModel.useInAuto', "Use in Auto"); - const description = tooSlow - ? localize('localModel.useInAuto.tooSlow', "{0} runs on this device but is too slow for Auto. You can still select it directly.", family.displayName) - : localize('localModel.useInAuto.description', "Let Auto route turns to this on-device model, with cloud fallback."); + const label = details.autoModelFusion + ? localize('localModel.useInFusion', "Use in Copilot Fusion") + : localize('localModel.useInAuto', "Use in Auto"); + const description = details.autoModelFusion + ? tooSlow + ? localize('localModel.useInFusion.tooSlow', "{0} runs on this device but is too slow for Copilot Fusion. You can still select it directly.", family.displayName) + : localize('localModel.useInFusion.description', "Let Copilot Fusion route turns to this on-device model, with cloud fallback.") + : tooSlow + ? localize('localModel.useInAuto.tooSlow', "{0} runs on this device but is too slow for Auto. You can still select it directly.", family.displayName) + : localize('localModel.useInAuto.description', "Let Auto route turns to this on-device model, with cloud fallback."); const section = this._section(); const row = dom.append(section, dom.$('.chat-local-model-card-setting')); const labelId = `chat-local-model-card-auto-${generateUuid()}`; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelItems.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelItems.ts index 14bfc80f70c1..ce21ec7e71ec 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelItems.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerLocalModelItems.ts @@ -114,6 +114,8 @@ export interface ILocalModelPickerHost { readonly selectedModelId: string | undefined; /** The chat's model configuration, for the thinking level of a direct model. */ readonly configurationAccess?: IModelConfigurationAccess; + /** Whether the chat's Auto model, which is not among `models`, is presented as Copilot Fusion. */ + readonly autoModelFusion?: boolean; select(model: ILanguageModelChatMetadataAndIdentifier): void; showDetails(familyId: string): void; } @@ -136,6 +138,8 @@ export interface ILocalModelDetails { readonly directModel?: ILocalModelDirectModelConfig; /** Operations whose stop was sent and hasn't taken effect yet, shown as in progress. */ readonly pendingStops?: ReadonlySet; + /** Whether the chat's Auto model is presented as Copilot Fusion. */ + readonly autoModelFusion?: boolean; } /** The on-device model content of one picker showing, listed in the picker's "On This Device" tab. */ @@ -375,7 +379,7 @@ interface ILocalModelRowState { } /** The short state (only while not ready) and notes of one family's row; a `selectable` row also says what using its model costs. */ -function getFamilyRowState(family: ILocalModelFamilyV1, readiness: LocalModelReadiness, status: ILocalModelStatusV1, selectable: boolean): ILocalModelRowState { +function getFamilyRowState(family: ILocalModelFamilyV1, readiness: LocalModelReadiness, status: ILocalModelStatusV1, selectable: boolean, autoModelFusion = false): ILocalModelRowState { const active = status.active?.familyId === family.familyId ? status.active : undefined; const notes: string[] = []; let state: string | undefined; @@ -425,7 +429,9 @@ function getFamilyRowState(family: ILocalModelFamilyV1, readiness: LocalModelRea } case 'ready': { if (active?.autoEligible === false) { - notes.push(localize('localModel.tooSlowForAuto', "Too slow for Auto")); + notes.push(autoModelFusion + ? localize('localModel.tooSlowForFusion', "Too slow for Copilot Fusion") + : localize('localModel.tooSlowForAuto', "Too slow for Auto")); } else if (selectable) { notes.push(localize('localModel.noUsageLimit', "No usage limit")); } @@ -437,7 +443,9 @@ function getFamilyRowState(family: ILocalModelFamilyV1, readiness: LocalModelRea notes.push(localize('localModel.memoryWarning.short', "Needs more GPU memory than this device has")); } if (!family.autoCapable) { - notes.push(localize('localModel.notAutoCapable', "Not available for Auto yet")); + notes.push(autoModelFusion + ? localize('localModel.notFusionCapable', "Not available for Copilot Fusion yet") + : localize('localModel.notAutoCapable', "Not available for Auto yet")); } const update = family.install?.update; if (update && readiness !== 'preparing') { @@ -578,7 +586,7 @@ function isLocalModelNotDownloaded(family: ILocalModelFamilyV1): boolean { */ function buildFamilyRow(family: ILocalModelFamilyV1, readiness: LocalModelReadiness, status: ILocalModelStatusV1, host: ILocalModelPickerHost | undefined): IActionListItem { const model = family.install ? host?.models.find(candidate => isDirectModelOf(candidate, family)) : undefined; - const row = getFamilyRowState(family, readiness, status, !!model); + const row = getFamilyRowState(family, readiness, status, !!model, host?.autoModelFusion); const summary = getLocalModelConfigSummary(family, status, model, host?.configurationAccess); const slot = getLocalModelDownloadSlot(family, readiness, status); const showDetails = () => host?.showDetails(family.familyId); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerPresentation.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerPresentation.ts index 42031fcc6034..05f680d16d91 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerPresentation.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerPresentation.ts @@ -15,6 +15,12 @@ export function isAutoModel(model: ILanguageModelChatMetadataAndIdentifier): boo return isAutoLanguageModel(model); } +export function isPendingLegacyAutoModel(model: ILanguageModelChatMetadataAndIdentifier | undefined, languageModelsService: ILanguageModelsService): boolean { + return !!model && isAutoModel(model) && !model.metadata.autoModelFusion + && !isUserProvidedModel(model, languageModelsService) + && !languageModelsService.getLanguageModelIds().includes(model.identifier); +} + /** * Whether the model is a Copilot CLI HydraFusion research preview (HydraFusion or HydraFusion Max). * Fusion offers them among its tiers; otherwise HydraFusion is a model of its own, with 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 6bd7897dec16..c6dbae00eeea 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 @@ -677,6 +677,11 @@ export class TabbedModelPicker extends Disposable { return derived.autoModel.model; } + /** Whether the picker's Auto model is presented as Copilot Fusion, which the on-device rows and pages then name. */ + private _isAutoModelFusion(context: ITabbedModelPickerContext): boolean { + return !!this._autoModel(context)?.metadata.autoModelFusion; + } + /** * The HydraFusion routing models this build can run, HydraFusion before HydraFusion Max. * The host only offers HydraFusion Max with HydraFusion v2, and Fusion only offers @@ -783,7 +788,7 @@ export class TabbedModelPicker extends Disposable { selectedModelId: context.selectedModelId, organizationDefaultModelId: this._getOrganizationDefaultModel(context)?.identifier, pinnedModelIds: context.pinnedModelIds, - controlModels: context.controlModels, + controlModels: isBuiltIn ? context.controlModels : {}, preferredSpeedVariants: this._preferredSpeedVariants, // Only the built-in provider curates a shortlist. A provider the user added // gets a tab of its own, which is already the whole of what it offers. @@ -848,6 +853,7 @@ export class TabbedModelPicker extends Disposable { alignEnd: true, useManagedHover: true, checked: !!comparison.state.get(), + preserveFocus: true, render: !comparison.state.get() && !comparison.summary.get() && comparison.renderToggle ? button => comparison.renderToggle!(button) : undefined, @@ -1098,6 +1104,7 @@ export class TabbedModelPicker extends Disposable { models: this._localDirectModels(context), selectedModelId: context.selectedModelId, configurationAccess: context.configurationAccess, + autoModelFusion: this._isAutoModelFusion(context), select: model => { this._selectionVersion++; this._applyModelSelection(model, this._context ?? context); @@ -1117,7 +1124,8 @@ export class TabbedModelPicker extends Disposable { /** The detail page content of an on-device family, with its direct model and the chat's configuration of it. */ private _getLocalModelDetails(familyId: string, context: ITabbedModelPickerContext): ILocalModelDetails | undefined { - const details = context.localModels?.getDetails(familyId); + const localDetails = context.localModels?.getDetails(familyId); + const details = localDetails && { ...localDetails, autoModelFusion: this._isAutoModelFusion(context) }; const model = details && this._getLocalDirectModel(familyId, context); if (!details || !model) { return details; diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabs.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabs.ts index 417a8a3a98b0..e0619b91561c 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabs.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabs.ts @@ -273,10 +273,11 @@ function buildUnavailableEntries(options: IModelPickerSectionsOptions): IModelPi const present = new Set(options.models.flatMap(model => [model.identifier, model.metadata.id])); const entries: IModelPickerUnavailableEntry[] = []; for (const [id, entry] of Object.entries(options.controlModels)) { - if (!entry.featured || (!options.showUnavailable && !options.alwaysShowUnavailableModelIds?.has(id))) { + const outOfDate = isOutOfDate(entry, options.currentVSCodeVersion); + const showUpdate = present.has(id) && outOfDate; + if (!entry.featured || !(options.showUnavailable || options.alwaysShowUnavailableModelIds?.has(id) || showUpdate)) { continue; } - const outOfDate = isOutOfDate(entry, options.currentVSCodeVersion); // A model that is here but gated needs an update; one that is missing entirely // needs whatever its account is short of. if (present.has(id) ? outOfDate : !entry.exists) { 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 107ec4c98d38..f2b429e76d8f 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 @@ -57,7 +57,7 @@ import { getModelConfigProperty, MODEL_CONFIG_GROUP_EFFORT, whenModelConfigValue import { IModelPickerProviderPlaceholder } from './modelPickerTabs.js'; import { getOrganizationDefaultDescription, getOrganizationDefaultModel } from './modelPickerBadges.js'; import { formatLocalModelOnDeviceName, ILocalModelPickerActionEvent, isLocalModelDirectRow, ModelPickerLocalModels } from './modelPickerLocalModelItems.js'; -import { getFusionTierLabel, getHydraFusionTierLabel, getModelPickerUnavailableReason, isAutoModel, isHydraFusionModel, isHydraFusionUpgradeOnly, ModelPickerUnavailableReason, modelPickerRequiresSetup, shouldShowCacheBreakHint as computeShouldShowCacheBreakHint } from './modelPickerPresentation.js'; +import { getFusionTierLabel, getHydraFusionTierLabel, getModelPickerUnavailableReason, isAutoModel, isHydraFusionModel, isHydraFusionUpgradeOnly, isPendingLegacyAutoModel, ModelPickerUnavailableReason, modelPickerRequiresSetup, shouldShowCacheBreakHint as computeShouldShowCacheBreakHint } from './modelPickerPresentation.js'; /** Trusted caller options for opening a searchable picker without toggling it closed. */ export interface IModelPickerOpenOptions { @@ -385,6 +385,16 @@ export class ModelPickerWidget extends Disposable { return fusion; } + /** The name of the Auto model the picker offers as Copilot Fusion, which then stands for Auto while no model is selected. */ + private _getFusionAutoName(models: readonly ILanguageModelChatMetadataAndIdentifier[]): string | undefined { + const fusionModels = models.filter(candidate => candidate.metadata.autoModelFusion); + if (!fusionModels.length) { + return undefined; + } + const runnable = this._getRunnablePredicate(models); + return fusionModels.find(runnable)?.metadata.name; + } + /** * The model a HydraFusion tier is shown as, with that tier: Fusion for one of * Fusion's tiers, or HydraFusion for HydraFusion's own Default or Max. @@ -892,10 +902,13 @@ export class ModelPickerWidget extends Disposable { const comparisonBusy = !!comparisonSummary && (this._delegate.comparisonBusy?.get() ?? false); const routingTier = !comparisonSummary && this._selectedModel ? this._getRoutingTier(this._selectedModel, models) : undefined; const shownModel = routingTier?.shownModel ?? this._selectedModel; - const displayName = shownModel ? getLanguageModelDisplayNameWithSubscriptionSource(shownModel) : undefined; + const pendingAutoModel = isPendingLegacyAutoModel(shownModel, this._languageModelsService); + const displayName = shownModel && !pendingAutoModel ? getLanguageModelDisplayNameWithSubscriptionSource(shownModel) : undefined; const configurationAccess = this._delegate.modelConfiguration ?? this._languageModelsService; // A HydraFusion model shown as one of Fusion's tiers is named by that tier, even where the label shows only Fusion. - this._fusionDisplayName = !comparisonSummary && routingTier && shownModel?.metadata.autoModelFusion ? localize('chat.modelPicker.fusionTier', "Copilot Fusion {0}", routingTier.label) : undefined; + this._fusionDisplayName = !comparisonSummary && routingTier && shownModel?.metadata.autoModelFusion + ? localize('chat.modelPicker.fusionTier', "Copilot Fusion {0}", routingTier.label) + : !comparisonSummary && pendingAutoModel ? (this._getFusionAutoName(models) ?? localize('chat.modelPicker.fusion', "Copilot Fusion")) : undefined; // A directly selected on-device model reads " · On-device", like the Copilot CLI and app. const name = comparisonSummary ?? (shownModel && displayName !== undefined && isLocalModelDirectRow(shownModel) ? formatLocalModelOnDeviceName(displayName) : displayName); @@ -922,13 +935,14 @@ export class ModelPickerWidget extends Disposable { // dropdown carry the Restricted Mode explanation and the Trust Workspace / Sign In action. // "Activating..." is transient while models load after a Trust grant; "No models available" // is the genuinely empty state (e.g. an agent-host session with no Auto fallback). + // Before the catalog arrives, name the Copilot fallback without inventing an effort level. const modelLabel = unavailable ? localize('chat.modelPicker.modelsLabel', "Models") : activating ? localize('chat.modelPicker.activating', "Activating...") : genericNoModels ? localize('chat.modelPicker.noModels', "No models available") - : (name ?? localize('chat.modelPicker.auto', "Auto")); + : (name ?? this._getFusionAutoName(models) ?? localize('chat.modelPicker.fusion', "Copilot Fusion")); const showModelLabel = (!comparisonSummary || noModelsAvailable) && (!compact || !modelIcon || noModelsAvailable); if (showModelLabel) { nameChildren.push(dom.$('span.chat-input-picker-label', undefined, modelLabel)); @@ -944,7 +958,7 @@ export class ModelPickerWidget extends Disposable { const localModelReadout = this._selectedModel && isLocalModelDirectRow(this._selectedModel) ? this._getLocalModels()?.getPresentation()?.getDirectModel(this._selectedModel, configurationAccess)?.readout : undefined; - renderModelConfigurationButton(this._configButton, shownModel, configurationAccess, !!comparisonSummary || minimal || compact || noModelsAvailable, routingTier?.label, localModelReadout); + renderModelConfigurationButton(this._configButton, shownModel, configurationAccess, !!comparisonSummary || minimal || compact || noModelsAvailable || pendingAutoModel, routingTier?.label, localModelReadout); } const configVisible = !!this._configButton && this._configButton.style.display !== 'none'; this._domNode.classList.toggle('has-config', configVisible); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/sessionTargetPickerActionItem.ts b/src/vs/workbench/contrib/chat/browser/widget/input/sessionTargetPickerActionItem.ts index 2e8cf7ecc549..75b1892aa757 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/sessionTargetPickerActionItem.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/sessionTargetPickerActionItem.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; import * as dom from '../../../../../../base/browser/dom.js'; import { renderAsPlaintext } from '../../../../../../base/browser/markdownRenderer.js'; import { renderLabelWithIcons } from '../../../../../../base/browser/ui/iconLabel/iconLabels.js'; @@ -243,7 +244,7 @@ export class SessionTypePickerActionItem extends ChatInputPickerActionViewItem { super(action, sessionTargetPickerOptions, pickerOptions, actionWidgetService, keybindingService, contextKeyService, telemetryService); - this._isSessionsWindow = IsSessionsWindowContext.getValue(contextKeyService) === true; + this._isSessionsWindow = IsSessionsWindowContext.getValue(contextKeyService) === true || ChatContextKeys.inSessionsChat.getValue(contextKeyService) === true; if (this.delegate.onDidChangeActiveSessionProvider) { this._register(this.delegate.onDidChangeActiveSessionProvider(() => { diff --git a/src/vs/workbench/contrib/chat/browser/widget/media/chat.css b/src/vs/workbench/contrib/chat/browser/widget/media/chat.css index e5e180dd73f3..4883c1ef5077 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/media/chat.css +++ b/src/vs/workbench/contrib/chat/browser/widget/media/chat.css @@ -596,7 +596,8 @@ pointer-events: auto; } -.monaco-workbench:not(.agent-sessions-workbench) .interactive-item-container.interactive-request.editing .chat-request-timestamp-container { +/* Not in session chats, which pad it themselves, whatever window shows them. */ +.monaco-workbench:not(.agent-sessions-workbench) .interactive-item-container.interactive-request.editing .chat-request-timestamp-container:where(:not(.sessions-chat *)) { box-sizing: border-box; padding-inline-end: var(--vscode-spacing-size160); } @@ -1683,7 +1684,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .monaco-button { padding: 2px 6px 2px 0px; - border-radius: var(--vscode-cornerRadius-xSmall); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-xSmall)); border: none; background-color: unset; color: var(--vscode-descriptionForeground); @@ -1723,7 +1724,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .interactive-session .chat-editing-session .chat-editing-session-actions .monaco-button.secondary.monaco-text-button.codicon { cursor: pointer; padding: 2px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); display: inline-flex; } @@ -1824,7 +1825,7 @@ have to be updated for changes to the rules above, or to support more deeply nes height: 22px; min-width: 22px; padding: 0; - border-radius: var(--vscode-cornerRadius-xSmall); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-xSmall)); display: inline-flex; align-items: center; justify-content: center; @@ -2100,7 +2101,7 @@ have to be updated for changes to the rules above, or to support more deeply nes box-sizing: border-box; height: var(--chat-input-control-height); padding: 0 var(--vscode-spacing-size60); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); display: flex; align-items: center; color: var(--vscode-icon-foreground); @@ -2211,7 +2212,7 @@ have to be updated for changes to the rules above, or to support more deeply nes box-sizing: border-box; height: var(--chat-input-control-height); padding: 0 var(--vscode-spacing-size60); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); display: flex; align-items: center; color: var(--vscode-icon-foreground); @@ -2221,7 +2222,7 @@ have to be updated for changes to the rules above, or to support more deeply nes box-sizing: border-box; height: var(--chat-input-control-height); padding: 0 var(--vscode-spacing-size60); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); display: flex; align-items: center; color: var(--vscode-icon-foreground); @@ -2661,8 +2662,9 @@ have to be updated for changes to the rules above, or to support more deeply nes font-size: var(--vscode-codiconFontSize-compact); } +/* A theme icon is centered in its box, so the box takes the height of the pill rather than the taller height of a list row. */ .interactive-session .chat-attached-context .chat-attached-context-attachment .monaco-icon-label .monaco-icon-label-iconpath.codicon { - padding-top: 2px; + height: auto; } .interactive-session .chat-input-container .chat-attached-context { @@ -2730,13 +2732,20 @@ have to be updated for changes to the rules above, or to support more deeply nes /* An attachment shown as a pill inline with the text of a request, see `chat.inlineAttachments.enabled`. */ .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown .chat-attached-context.chat-request-inline-attachment { display: inline-flex; - vertical-align: middle; max-width: 100%; width: auto; margin: 0; padding: 0; } +/* + * The label of the pill sits on the baseline of the text of the request. The pill takes its baseline from its + * first box, which would be its icon, so a box without text that is laid out as the line of its label comes first. + */ +.interactive-session .interactive-item-container.interactive-request .value .rendered-markdown .chat-request-inline-attachment .chat-attached-context-attachment::before { + content: '\200b'; +} + /* Codicons in the text of a request are moved down to its baseline, while those of a pill are centered in it. */ .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown .chat-request-inline-attachment .codicon { top: 0; @@ -2873,6 +2882,22 @@ have to be updated for changes to the rules above, or to support more deeply nes color: var(--vscode-chat-slashCommandForeground); } +/* + * A reference in the text of a request that is not an attachment pill, such as a slash command, is level with the + * pills beside it, and its text stays on the baseline of the text of the request. Its box is a line that also holds + * the label of a pill, without text: 18px high, in the smaller font of a pill and inside the width of its border. + */ +.interactive-item-container.interactive-request .chat-resource-widget { + display: inline-block; + padding-block: var(--vscode-strokeThickness); + line-height: normal; +} + +.interactive-item-container.interactive-request .chat-resource-widget::before { + content: '\200b'; + font-size: var(--vscode-chat-font-size-body-xs); + line-height: 18px; +} .interactive-item-container .chat-resource-widget, .interactive-item-container .chat-agent-widget .monaco-button { @@ -3030,7 +3055,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .chat-artifacts-widget .chat-artifacts-list-actions .action-item .action-label { padding: 2px; - border-radius: var(--vscode-cornerRadius-xSmall); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-xSmall)); cursor: pointer; } @@ -3533,7 +3558,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .interactive-session .chat-used-context-label .monaco-button { width: fit-content; border: none; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); gap: 0; text-align: initial; justify-content: initial; diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/editor/chatEditor.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/editor/chatEditor.ts index 4c4a06bac0b6..7f2be0e3f847 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/editor/chatEditor.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/editor/chatEditor.ts @@ -298,7 +298,7 @@ export class ChatEditor extends AbstractEditorWithViewState { + const view = await this.viewsService.openView(ChatViewId, !preserveFocus); + if (view && !view.widget && options?.waitForWidget) { + return raceTimeout(view.whenWidget, ChatViewPaneHost.WIDGET_TIMEOUT); + } + return view?.widget; + } + + async revealIfShowing(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { + const chatView = this.viewsService.getViewWithId(ChatViewId); + if (!isEqual(chatView?.widget.viewModel?.sessionResource, sessionResource)) { + return undefined; + } + const view = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); + if (view && !options?.preserveFocus) { + view.focus(); + } + return view?.widget; + } + + async openSession(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { + const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); + if (chatView) { + await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason); + if (!options?.preserveFocus) { + chatView.focusInput(); + } + } + return chatView?.widget; + } + + async toggle(): Promise { + const visible = !this.viewsService.isViewVisible(ChatViewId); + this.updatePartVisibility(this.viewDescriptorService.getViewLocationById(ChatViewId), visible); + return visible; + } + + private updatePartVisibility(location: ViewContainerLocation | null, visible: boolean): void { + let part: Parts.PANEL_PART | Parts.SIDEBAR_PART | Parts.AUXILIARYBAR_PART | undefined; + switch (location) { + case ViewContainerLocation.Panel: + part = Parts.PANEL_PART; + break; + case ViewContainerLocation.Sidebar: + part = Parts.SIDEBAR_PART; + break; + case ViewContainerLocation.AuxiliaryBar: + part = Parts.AUXILIARYBAR_PART; + break; + } + + if (part) { + this.layoutService.setPartHidden(!visible, part); + } + } + + async startSession(sessionResource: URI, options: IChatViewHostSessionStartOptions): Promise { + const view = await this.viewsService.openView(ChatViewId) as ChatViewPane; + options.beforeOpen?.(); + const transition = new DisposableStore(); + if (options.importingConversation) { + // The transition spans loading, sending and moving to the real session, during which the chat widget is + // transiently empty: the sessions list stays suppressed so it never flashes, and the view shows that it works. + transition.add(view.beginSessionsListSuppression()); + const progress = new DeferredPromise(); + transition.add(toDisposable(() => progress.complete())); + this.progressService.withProgress({ location: ChatViewId }, () => progress.p); + } + try { + if (options.local) { + await view.startNewLocalSession(); + } else { + await view.loadSession(sessionResource, 'explicitOverride'); + } + view.focus(); + } catch (error) { + transition.dispose(); + throw error; + } + return { + moved: async movedSessionResource => { + const movedView = await this.viewsService.openView(ChatViewId) as ChatViewPane; + await movedView.loadSession(movedSessionResource); + }, + complete: async () => { + transition.dispose(); + return true; + }, + createComposer: async () => undefined, + dispose: () => transition.dispose(), + }; + } +} + +export class ChatViewHostService implements IChatViewHostService { + + declare readonly _serviceBrand: undefined; + + private readonly chatViewHost: IChatViewHost; + /** The registrations of the hosts that replace the Chat view, the one in use last: one each, also of the same host. */ + private readonly registrations: { readonly host: IChatViewHost }[] = []; + + constructor( + @IInstantiationService instantiationService: IInstantiationService, + ) { + this.chatViewHost = instantiationService.createInstance(ChatViewPaneHost); + } + + private get host(): IChatViewHost { + return this.registrations.at(-1)?.host ?? this.chatViewHost; + } + + registerHost(host: IChatViewHost): IDisposable { + const registration = { host }; + this.registrations.push(registration); + return toDisposable(() => { + const index = this.registrations.indexOf(registration); + if (index >= 0) { + this.registrations.splice(index, 1); + } + }); + } + + reveal(preserveFocus?: boolean, options?: IChatViewHostRevealOptions): Promise { + return this.host.reveal(preserveFocus, options); + } + + async revealIfShowing(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { + return this.host.revealIfShowing?.(sessionResource, options); + } + + openSession(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { + return this.host.openSession(sessionResource, options); + } + + toggle(): Promise { + return this.host.toggle(); + } + + startSession(sessionResource: URI, options: IChatViewHostSessionStartOptions): Promise { + return this.host.startSession(sessionResource, options); + } +} diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index 983626cc70b2..ff50f904ca98 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -23,7 +23,7 @@ import { getComparisonKey, isEqual } from '../../../../../../base/common/resourc import { ScrollbarVisibility } from '../../../../../../base/common/scrollable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { localize } from '../../../../../../nls.js'; -import { MenuEntryActionViewItem } from '../../../../../../platform/actions/browser/menuEntryActionViewItem.js'; +import { ChatCustomizationsActionViewItem, ChatCustomizationsHover } from '../../aiCustomization/chatCustomizationsHover.js'; import { MenuWorkbenchToolBar } from '../../../../../../platform/actions/browser/toolbar.js'; import { MenuId, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; import { CommandsRegistry, ICommandService } from '../../../../../../platform/commands/common/commands.js'; @@ -72,7 +72,7 @@ import { AgentSessionsViewerOrientation, AgentSessionsViewerPosition } from '../ import { IProgressService } from '../../../../../../platform/progress/common/progress.js'; import { CHAT_WIDGET_VIEW_STATE_CACHE_LIMIT, ChatViewId, IChatWidgetService, IChatWidgetViewState, setModelPreservingInputTypedWhileLoading } from '../../chat.js'; import { IActivityService, ProgressBadge } from '../../../../../services/activity/common/activity.js'; -import { disposableTimeout, raceCancellation } from '../../../../../../base/common/async.js'; +import { DeferredPromise, disposableTimeout, raceCancellation, RunOnceScheduler } from '../../../../../../base/common/async.js'; import { AgentSessionsFilter, AgentSessionsGrouping } from '../../agentSessions/agentSessionsFilter.js'; import { IAgentSessionsService } from '../../agentSessions/agentSessionsService.js'; import { IAgentHostEnablementService } from '../../../../../../platform/agentHost/common/agentHostEnablementService.js'; @@ -118,6 +118,33 @@ type ChatViewPaneOpenedClassification = { comment: 'Event fired when the chat view pane is opened'; }; +type ChatViewSessionsLayout = { + configuredOrientation: 'stacked' | 'sideBySide'; + effectiveOrientation: 'stacked' | 'sideBySide'; + sessionsVisible: boolean; + sessionsEnabled: boolean; + position: 'left' | 'right'; + chatViewLocation: 'auxiliaryBar' | 'sidebar' | 'panel'; + chatViewMaximized: boolean; +}; + +type ChatViewSessionsLayoutEvent = ChatViewSessionsLayout & { + reason: 'initial' | 'orientationChanged' | 'visibilityChanged'; +}; + +type ChatViewSessionsLayoutClassification = { + configuredOrientation: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The configured orientation of the sessions list (`chat.viewSessions.orientation`): stacked or sideBySide.' }; + effectiveOrientation: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The orientation of the sessions list actually in use, which falls back to stacked when the chat view is too narrow for side by side.' }; + sessionsVisible: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the sessions list is shown in the chat view.' }; + sessionsEnabled: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the sessions list is enabled in the chat view (`chat.viewSessions.enabled`).' }; + position: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Which side of the chat the side by side sessions list is on: left or right.' }; + chatViewLocation: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Where the chat view is located: auxiliaryBar, sidebar or panel.' }; + chatViewMaximized: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the chat view is in the secondary side bar and the secondary side bar is maximized.' }; + reason: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Why the layout is reported: initial (first time the chat view is shown in the window), orientationChanged or visibilityChanged.' }; + owner: 'sandy081'; + comment: 'Reports the layout of the sessions list in the chat view, to measure how the sessions list in the chat view is used.'; +}; + export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private readonly memento: Memento; @@ -365,6 +392,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { restoringSession.finally(() => { if (this.restoringSession === restoringSession) { this.restoringSession = undefined; + this.sessionsLayoutScheduler?.schedule(); } }); } @@ -860,6 +888,12 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private sessionsViewerSash: Sash | undefined; private readonly sessionsViewerSashDisposables = this._register(new MutableDisposable()); + /** Reports the sessions list layout once it settled, so a resize reports at most one change. Accessed with `?.` because tests invoke pane methods on partial hosts. */ + private readonly sessionsLayoutScheduler = this._register(new RunOnceScheduler(() => this.reportSessionsLayout(), 1000)); + private lastReportedSessionsLayout: ChatViewSessionsLayout | undefined; + /** Number of in-flight {@link loadSession} calls, during which the reported sessions layout is not settled. */ + private _loadingSessionCount = 0; + private createSessionsControl(parent: HTMLElement): AgentSessionsControl { const sessionsContainer = this.sessionsContainer = parent.appendChild($('.agent-sessions-container')); @@ -875,7 +909,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { // Sessions Toolbar const sessionsToolbarContainer = append(sessionsTitleContainer, $('.agent-sessions-toolbar')); const sessionsToolbar = this._register(this.instantiationService.createInstance(MenuWorkbenchToolBar, sessionsToolbarContainer, MenuId.AgentSessionsToolbar, { - menuOptions: { shouldForwardArgs: true } + menuOptions: { shouldForwardArgs: true }, + telemetrySource: 'agentSessionsToolbar' })); // Sessions Filter @@ -913,7 +948,10 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { return openEvent; }, })); - this._register(this.onDidChangeBodyVisibility(() => sessionsControl.setVisible(this.isBodyVisible() && this.sessionsViewerVisible))); + this._register(this.onDidChangeBodyVisibility(() => { + sessionsControl.setVisible(this.isBodyVisible() && this.sessionsViewerVisible); + this.sessionsLayoutScheduler?.schedule(); + })); sessionsToolbar.context = sessionsControl; @@ -1001,6 +1039,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { this.sessionsViewerVisible = newSessionsContainerVisible; this.sessionsControl?.setVisible(this.isBodyVisible() && newSessionsContainerVisible); this.sessionsViewerVisibilityContext.set(newSessionsContainerVisible); + this.sessionsLayoutScheduler?.schedule(); return { changed: sessionsContainerVisible !== newSessionsContainerVisible, @@ -1008,6 +1047,49 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { }; } + private reportSessionsLayout(): void { + if (!this.sessionsContainer || !this.lastDimensions || !this.isBodyVisible()) { + return; // not rendered, laid out or shown yet + } + + if (this.restoringSession || this._loadingSessionCount > 0 || this._sessionsListSuppressionCount > 0) { + return; // session is restoring, loading or transitioning, sessions visibility is not settled + } + + const { position, location } = this.getViewPositionAndLocation(); + + let chatViewLocation: ChatViewSessionsLayout['chatViewLocation']; + switch (location) { + case ViewContainerLocation.Sidebar: chatViewLocation = 'sidebar'; break; + case ViewContainerLocation.Panel: chatViewLocation = 'panel'; break; + default: chatViewLocation = 'auxiliaryBar'; break; + } + + const layout: ChatViewSessionsLayout = { + configuredOrientation: this.sessionsViewerOrientationConfiguration, + effectiveOrientation: this.sessionsViewerOrientation === AgentSessionsViewerOrientation.SideBySide ? 'sideBySide' : 'stacked', + sessionsVisible: this.sessionsViewerVisible, + sessionsEnabled: !!this.configurationService.getValue(ChatConfiguration.ChatViewSessionsEnabled), + position: position === Position.RIGHT ? 'right' : 'left', + chatViewLocation, + chatViewMaximized: chatViewLocation === 'auxiliaryBar' && this.layoutService.isAuxiliaryBarMaximized(), + }; + + let reason: ChatViewSessionsLayoutEvent['reason']; + if (!this.lastReportedSessionsLayout) { + reason = 'initial'; + } else if (this.lastReportedSessionsLayout.effectiveOrientation !== layout.effectiveOrientation) { + reason = 'orientationChanged'; + } else if (this.lastReportedSessionsLayout.sessionsVisible !== layout.sessionsVisible) { + reason = 'visibilityChanged'; + } else { + return; // no change since last report + } + + this.lastReportedSessionsLayout = layout; + this.telemetryService.publicLog2('chatViewSessionsLayout', { ...layout, reason }); + } + private refreshSessionsControlVisibility(): void { const { changed } = this.updateSessionsControlVisibility(); if (changed) { @@ -1043,6 +1125,10 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private _widget!: ChatWidget; get widget(): ChatWidget { return this._widget; } + private readonly _widgetCreated = new DeferredPromise(); + /** Resolves to {@link widget} once the view creates it, as its body first renders. */ + get whenWidget(): Promise { return this._widgetCreated.p; } + private titleControl: ChatViewTitleControl | undefined; private createChatControl(parent: HTMLElement): ChatWidget { @@ -1058,7 +1144,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { // Chat Widget const scopedInstantiationService = this._register(this.instantiationService.createChild(new ServiceCollection([IContextKeyService, this.scopedContextKeyService]))); - this._widget = this._register(scopedInstantiationService.createInstance( + const widget = this._register(scopedInstantiationService.createInstance( ChatWidget, ChatAgentLocation.Chat, { viewId: this.id }, @@ -1095,7 +1181,10 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { inputEditorBackground: locationBasedColors.background, resultEditorBackground: editorBackground, })); - this._widget.render(chatControlsContainer, parent); + this._widget = widget; + widget.render(chatControlsContainer, parent); + // What waits for the widget gets it once it is rendered, as the body renders, once + this._widgetCreated.complete(widget); this._register(scopedInstantiationService.createInstance(AgentHostSessionInputPills, this._widget, 'auto')); const updateWidgetVisibility = (reader?: IReader) => this._widget.setVisible(this.isBodyVisible() && !this.welcomeController?.isShowingWelcome.read(reader)); @@ -1107,7 +1196,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { override createActionViewItem(action: IAction, options?: IDropdownMenuActionViewItemOptions): IActionViewItem | undefined { if (action.id === AICustomizationManagementCommands.OpenEditor && action instanceof MenuItemAction) { - return this.instantiationService.createInstance(ChatCustomizationsActionViewItem, action, options, this.customizationMigrationsAvailable); + return this.instantiationService.createInstance(ChatCustomizationsActionViewItem, action, options, this.instantiationService.createInstance(ChatCustomizationsHover), 'chatToolbar', this.customizationMigrationsAvailable, false, undefined); } return super.createActionViewItem(action, options); } @@ -1289,6 +1378,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { restoringSession.finally(() => { if (this.restoringSession === restoringSession) { this.restoringSession = undefined; + this.sessionsLayoutScheduler?.schedule(); } }); } @@ -1365,7 +1455,16 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { return { modelRef: undefined }; } - const modelRef = await this.chatService.acquireOrLoadSession(sessionResource, ChatAgentLocation.Chat, token, debugOwner); + let modelRef: IChatModelReference | undefined; + try { + modelRef = await this.chatService.acquireOrLoadSession(sessionResource, ChatAgentLocation.Chat, token, debugOwner); + } catch (error) { + if (isCancellationError(error)) { + throw error; + } + // The persisted session may be gone, for example when its agent host was replaced; start a new one instead. + this.logService.warn(`ChatViewPane: failed to restore ${sessionResource.toString()}, starting a new session`, error); + } if (!modelRef) { return { modelRef: undefined, @@ -1554,6 +1653,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { const open = this._openDiagnostics.value = !isUntitledChatSession(sessionResource) && this.layoutService.isRestored() ? this.chatOpenDiagnosticsService.startOpen('panel', sessionResource, token, alreadyShown) : undefined; + this._loadingSessionCount++; try { // Capture the input draft up front: the load window (clear + acquire below) // opens before `showModel` binds, so text typed during loading must be @@ -1636,6 +1736,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { throw error; } finally { open?.end(); + this._loadingSessionCount--; + this.sessionsLayoutScheduler?.schedule(); } } @@ -1951,35 +2053,3 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } } - -class ChatCustomizationsActionViewItem extends MenuEntryActionViewItem { - constructor( - action: MenuItemAction, - options: IDropdownMenuActionViewItemOptions | undefined, - private readonly migrationAvailable: IObservable, - @IKeybindingService keybindingService: IKeybindingService, - @INotificationService notificationService: INotificationService, - @IContextKeyService contextKeyService: IContextKeyService, - @IThemeService themeService: IThemeService, - @IContextMenuService contextMenuService: IContextMenuService, - @IAccessibilityService accessibilityService: IAccessibilityService, - ) { - super(action, options, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, accessibilityService); - } - - override render(container: HTMLElement): void { - super.render(container); - container.classList.add('chat-customizations-action-item'); - this._register(autorun(reader => { - container.classList.toggle('migration-available', this.migrationAvailable.read(reader)); - this.updateTooltip(); - })); - } - - protected override getTooltip(): string { - const tooltip = super.getTooltip(); - return this.migrationAvailable.get() - ? localize('openCustomizationsMigrationsAvailable', "{0} (Migrations Available)", tooltip) - : tooltip; - } -} diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/media/chatViewPane.css b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/media/chatViewPane.css index 017e97243343..b0f2fa5e108d 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/media/chatViewPane.css +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/media/chatViewPane.css @@ -69,22 +69,6 @@ overflow: hidden; } - .chat-viewpane-container .chat-customizations-action-item { - position: relative; - } - - .chat-viewpane-container .chat-customizations-action-item.migration-available::after { - content: ''; - position: absolute; - top: var(--vscode-spacing-size20); - right: var(--vscode-spacing-size20); - width: var(--vscode-spacing-size60); - height: var(--vscode-spacing-size60); - border-radius: var(--vscode-cornerRadius-circle); - background-color: var(--vscode-activityWarningBadge-background, var(--vscode-editorWarning-foreground)); - pointer-events: none; - } - .chat-controls-container { display: flex; flex-direction: column; diff --git a/src/vs/workbench/contrib/chat/common/actions/chatContextKeys.ts b/src/vs/workbench/contrib/chat/common/actions/chatContextKeys.ts index 97e570c3e27c..1e32ed7f2610 100644 --- a/src/vs/workbench/contrib/chat/common/actions/chatContextKeys.ts +++ b/src/vs/workbench/contrib/chat/common/actions/chatContextKeys.ts @@ -178,6 +178,10 @@ export namespace ChatContextKeys { export const agentSessionsViewerOrientation = new RawContextKey('agentSessionsViewerOrientation', undefined, { type: 'number', description: localize('agentSessionsViewerOrientation', "Orientation of the agent sessions view in the chat view.") }); export const agentSessionsViewerPosition = new RawContextKey('agentSessionsViewerPosition', undefined, { type: 'number', description: localize('agentSessionsViewerPosition', "Position of the agent sessions view in the chat view.") }); export const agentSessionsViewerVisible = new RawContextKey('agentSessionsViewerVisible', undefined, { type: 'boolean', description: localize('agentSessionsViewerVisible', "Visibility of the agent sessions view in the chat view.") }); + /** Whether a chat widget shows a session chat, as the Agents window does, in whatever window: it then behaves as there. */ + export const inSessionsChat = new RawContextKey('chatInSessionsChat', false, { type: 'boolean', description: localize('chatInSessionsChat', "True when the chat widget shows a session chat, as the Agents Window does.") }); + /** Whether an editor window shows the Sessions view, whose chat part replaces the Chat view: it is set as the window starts. */ + export const agentsViewActive = new RawContextKey('chatAgentsViewActive', false, { type: 'boolean', description: localize('chatAgentsViewActive', "True when the window shows the Agents view, whose chat part replaces the Chat view.") }); export const hasCreatedSessionInAgentsWindow = new RawContextKey('chatHasCreatedSessionInAgentsWindow', false, { type: 'boolean', description: localize('chatHasCreatedSessionInAgentsWindow', "True when the user has created at least one session in the Agents Window.") }); export const agentSessionType = new RawContextKey('chatSessionType', '', { type: 'string', description: localize('agentSessionType', "The type of the current agent session item.") }); export const isAgentSessionChild = new RawContextKey('agentSessionIsChild', false, { type: 'boolean', description: localize('agentSessionIsChild', "True when the current agent session item is a child chat.") }); diff --git a/src/vs/workbench/contrib/chat/common/agentsWindowUsage.ts b/src/vs/workbench/contrib/chat/common/agentsWindowUsage.ts index 5c1581fbd988..7d0b6bf11e14 100644 --- a/src/vs/workbench/contrib/chat/common/agentsWindowUsage.ts +++ b/src/vs/workbench/contrib/chat/common/agentsWindowUsage.ts @@ -12,10 +12,16 @@ import { IStorageService, StorageScope, StorageTarget } from '../../../../platfo export class AgentsWindowUsage { constructor(private readonly storageService: IStorageService) { } + /** Requests the user sent from the Agents Window that started a session. Onboarding uses it to recognize new users. */ get createdSessionCount(): number { return this.storageService.getNumber(AGENTS_WINDOW_TOTAL_SESSIONS_STORAGE_KEY, StorageScope.APPLICATION, 0); } + /** When the user last created an Agents Window session, or `undefined` if no creation was recorded. */ + get lastSessionCreated(): number | undefined { + return this.storageService.getNumber(AGENTS_WINDOW_LAST_SESSION_CREATED_STORAGE_KEY, StorageScope.APPLICATION); + } + isActiveUser(now = Date.now()): boolean { return isActiveAgentsWindowUser(this.storageService, now); } diff --git a/src/vs/workbench/contrib/chat/common/attachments/chatInlineAttachments.ts b/src/vs/workbench/contrib/chat/common/attachments/chatInlineAttachments.ts index adeada6d4304..b380d7537c35 100644 --- a/src/vs/workbench/contrib/chat/common/attachments/chatInlineAttachments.ts +++ b/src/vs/workbench/contrib/chat/common/attachments/chatInlineAttachments.ts @@ -55,6 +55,12 @@ export interface IInlineAttachmentAnchor { * of the pill's reference, and is unset for the prompt that is persisted. */ readonly promptText?: string; + /** + * Whether the prompt says the pill's text exactly where the pill is, rather + * than separated from adjacent text by spaces, as for a link, which needs no + * parsing as a token of its own and may be enclosed in other text. + */ + readonly verbatim?: boolean; } /** @@ -93,8 +99,9 @@ interface IProjectedAnchor { /** * Projects a chat input with inline attachment pills onto the prompt it * represents. A pill's text is separated from adjacent text with a space so it - * parses as its own token. An {@link INLINE_ATTACHMENT_ANCHOR} without a pill - * is dropped from the prompt. + * parses as its own token, unless the pill is {@link IInlineAttachmentAnchor.verbatim verbatim}, + * while adjacent pills are always separated from each other. An + * {@link INLINE_ATTACHMENT_ANCHOR} without a pill is dropped from the prompt. * * @returns `undefined` when the input contains no anchor, in which case the * input already is the prompt. @@ -114,6 +121,8 @@ export function projectInlineAttachments(input: string, anchors: readonly IInlin const projected: IProjectedAnchor[] = []; let text = ''; let copiedUntil = 0; + // Where the text of the previous pill ends in the prompt. + let previousEnd = -1; for (let offset = input.indexOf(INLINE_ATTACHMENT_ANCHOR); offset !== -1; offset = input.indexOf(INLINE_ATTACHMENT_ANCHOR, offset + 1)) { text += input.slice(copiedUntil, offset); copiedUntil = offset + 1; @@ -125,11 +134,13 @@ export function projectInlineAttachments(input: string, anchors: readonly IInlin continue; } - const leading = text.length > 0 && !isWhitespace(text.charAt(text.length - 1)) ? ' ' : ''; + // A pill right after another one is separated from it, whose trailing space a pill leaves to the next one. + const leading = text.length > 0 && !isWhitespace(text.charAt(text.length - 1)) && (!anchor.verbatim || promptOffset === previousEnd) ? ' ' : ''; const next = nextPromptCharacter(input, offset + 1, anchorsByOffset); - const trailing = next !== undefined && next !== INLINE_ATTACHMENT_ANCHOR && !isWhitespace(next) ? ' ' : ''; + const trailing = !anchor.verbatim && next !== undefined && next !== INLINE_ATTACHMENT_ANCHOR && !isWhitespace(next) ? ' ' : ''; const replacement = leading + anchor.text + trailing; text += replacement; + previousEnd = text.length; projected.push({ inputOffset: offset, promptOffset, replacement, textStart: promptOffset + leading.length, anchor }); } text += input.slice(copiedUntil); diff --git a/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts b/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts index f7c4578635e2..65261948eecd 100644 --- a/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts +++ b/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts @@ -149,15 +149,6 @@ export function toAgentHostCompletionVariableEntry(kind: AgentHostCompletionRefe }; } -export function toAgentHostCompletionVariableEntryFromMetadata(kind: AgentHostCompletionReferenceKind, name: string, _meta: Record | undefined): IGenericChatRequestVariableEntry & { value: IAgentHostCompletionVariableValue } { - switch (kind) { - case AgentHostCompletionReferenceKind.Skill: - return toAgentHostCompletionVariableEntry(kind, name, typeof _meta?.uri === 'string' ? _meta.uri : undefined, _meta); - case AgentHostCompletionReferenceKind.Command: - return toAgentHostCompletionVariableEntry(kind, name, typeof _meta?.command === 'string' ? _meta.command : undefined, _meta); - } -} - export function getAgentHostCompletionReferenceKind(entry: IChatRequestVariableEntry): AgentHostCompletionReferenceKind | undefined { if (entry.kind !== 'generic') { return undefined; @@ -731,6 +722,21 @@ export function chatReferenceVariableEntryFromDynamicValue(value: IChatReference }; } +/** + * A link to an agent session in the chat input, which its inline attachment + * pill shows as the session's title and status. The pill is derived from the + * link's text and is not attached to the request: the prompt keeps the link. + */ +export interface IChatRequestSessionLinkVariableEntry extends IBaseChatRequestVariableEntry { + readonly kind: 'sessionLink'; + /** The `agent-host-session://` link that opens the session, which the link in the input carries. */ + readonly value: URI; +} + +export function isSessionLinkVariableEntry(entry: IChatRequestVariableEntry): entry is IChatRequestSessionLinkVariableEntry { + return entry.kind === 'sessionLink'; +} + export type IChatRequestVariableEntry = IGenericChatRequestVariableEntry | IChatRequestImplicitVariableEntry | IChatRequestPasteVariableEntry | ISymbolVariableEntry | ICommandResultVariableEntry | IDiagnosticVariableEntry | IImageVariableEntry | IChatRequestToolEntry | IChatRequestToolSetEntry @@ -739,7 +745,7 @@ export type IChatRequestVariableEntry = IGenericChatRequestVariableEntry | IChat | ISCMHistoryItemVariableEntry | ISCMHistoryItemChangeVariableEntry | ISCMHistoryItemChangeRangeVariableEntry | ITerminalVariableEntry | IChatRequestStringVariableEntry | IChatRequestWorkspaceVariableEntry | IDebugVariableEntry | IAgentFeedbackVariableEntry | IChatRequestDebugEventsVariableEntry | IChatRequestSessionReferenceVariableEntry | IBrowserViewVariableEntry | IChatRequestChatReferenceVariableEntry - | IChatRequestTranscriptContextVariableEntry; + | IChatRequestTranscriptContextVariableEntry | IChatRequestSessionLinkVariableEntry; export namespace IChatRequestVariableEntry { diff --git a/src/vs/workbench/contrib/chat/common/chat.ts b/src/vs/workbench/contrib/chat/common/chat.ts index 233cd275aed7..23fef3e14c9e 100644 --- a/src/vs/workbench/contrib/chat/common/chat.ts +++ b/src/vs/workbench/contrib/chat/common/chat.ts @@ -3,7 +3,10 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { appendEscapedMarkdownInlineCode, MarkdownString, type IMarkdownString } from '../../../../base/common/htmlContent.js'; import { ResourceSet } from '../../../../base/common/map.js'; +import { escapeControlAndFormatCharacters } from '../../../../base/common/strings.js'; +import { localize } from '../../../../nls.js'; import { chatEditingSessionIsReady } from './editing/chatEditingService.js'; import { IChatModel } from './model/chatModel.js'; import { isLegacyChatTerminalToolInvocationData, type IChatSessionStats, type IChatTerminalToolInvocationData, type ILegacyChatTerminalToolInvocationData } from './chatService/chatService.js'; @@ -38,6 +41,34 @@ export function migrateLegacyTerminalToolSpecificData(data: IChatTerminalToolInv return data; } +/** + * Describes where a terminal command runs, for display before it is approved. + * Control and format characters are shown as escapes so a directory name + * containing them cannot break the line or reorder how it reads. + */ +export function getTerminalExecutionTargetMessage(data: Pick): IMarkdownString | undefined { + const lines = describeTerminalExecutionTarget(data, appendEscapedMarkdownInlineCode); + return lines.length ? new MarkdownString(lines.join(' \n')) : undefined; +} + +/** Plain-text form of {@link getTerminalExecutionTargetMessage} for screen readers. */ +export function getTerminalExecutionTargetDescription(data: Pick): string | undefined { + const lines = describeTerminalExecutionTarget(data, value => value); + return lines.length ? lines.join(', ') : undefined; +} + +function describeTerminalExecutionTarget(data: Pick, formatValue: (value: string) => string): string[] { + const target = data.executionTarget; + const lines: string[] = []; + if (target?.workingDirectory) { + lines.push(localize('chat.terminal.workingDirectory', "Working directory: {0}", formatValue(escapeControlAndFormatCharacters(target.workingDirectory)))); + } + if (target?.environment) { + lines.push(localize('chat.terminal.environment', "Environment: {0}", formatValue(escapeControlAndFormatCharacters(target.environment)))); + } + return lines; +} + export async function awaitStatsForSession(model: IChatModel): Promise { if (!model.editingSession) { return undefined; diff --git a/src/vs/workbench/contrib/chat/common/chatAutoModeExplainability.ts b/src/vs/workbench/contrib/chat/common/chatAutoModeExplainability.ts index 98fcb0f3cf6e..e9169d6d113a 100644 --- a/src/vs/workbench/contrib/chat/common/chatAutoModeExplainability.ts +++ b/src/vs/workbench/contrib/chat/common/chatAutoModeExplainability.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { formatTokenCount } from '../../../../base/common/numbers.js'; import { localize } from '../../../../nls.js'; import { getReasoningEffortLabel } from '../../../../platform/agentHost/common/reasoningEffort.js'; import { IChatAutoModeResolutionPart } from './chatService/chatService.js'; @@ -24,21 +25,42 @@ export function autoModeRoutingTitle(part: IChatAutoModeResolutionPart): string if (!part.resolved) { return localize('modelRouter.routing', "{0} picking a model", part.router); } - const title = part.switchedFrom - ? localize('modelRouter.switched', "{0} switched from {1} to {2}", part.router, part.switchedFrom, part.resolved.name) - : part.kept - ? localize('modelRouter.kept', "{0} stayed on {1}", part.router, part.resolved.name) - : part.defaulted - ? localize('modelRouter.defaulted', "{0} used {1}, its first route", part.router, part.resolved.name) - : localize('modelRouter.routed', "{0} picked {1}", part.router, part.resolved.name); - return part.effort + const title = part.playbook + ? modelRouterPlaybookTitle(part.router, part.playbook, part.resolved.name, part) + : part.switchedFrom + ? localize('modelRouter.switched', "{0} switched from {1} to {2}", part.router, part.switchedFrom, part.resolved.name) + : part.kept + ? localize('modelRouter.kept', "{0} stayed on {1}", part.router, part.resolved.name) + : part.defaulted + ? localize('modelRouter.defaulted', "{0} used {1}, its first route", part.router, part.resolved.name) + : localize('modelRouter.routed', "{0} picked {1}", part.router, part.resolved.name); + const withEffort = part.effort ? localize('modelRouter.withEffort', "{0} \u00b7 {1} effort", title, getReasoningEffortLabel(part.effort)) : title; + return part.contextSize + ? localize({ key: 'modelRouter.withContextSize', comment: ['{0} is a sentence about the model a router picked, {1} is a context window size such as 1M or 200K'] }, "{0} \u00b7 {1}", withEffort, formatTokenCount(part.contextSize)) + : withEffort; } if (!part.resolved) { return localize('autoMode.routing', "Auto routing task"); } - return part.resolved.reason ?? localize('autoMode.routedTo', "Auto routed task to {0}", part.resolved.name); + return part.resolved.reason ?? (part.fusion + ? localize('autoMode.fusionRoutedTo', "Copilot Fusion routed task to {0}", part.resolved.name) + : localize('autoMode.routedTo', "Auto routed task to {0}", part.resolved.name)); +} + +/** The routing line for a router written as playbooks: it names the playbook as well as the model it runs on. */ +function modelRouterPlaybookTitle(router: string, playbook: string, model: string, part: Pick): string { + // A chat that moves to the router gets one routing line, so it has to name the playbook too. + if (part.switchedFrom) { + return localize('modelRouter.playbookSwitched', "{0} switched from {1} to its {2} playbook on {3}", router, part.switchedFrom, playbook, model); + } + if (part.kept) { + return localize('modelRouter.playbookKept', "{0} stayed on its {1} playbook on {2}", router, playbook, model); + } + return part.defaulted + ? localize('modelRouter.playbookDefaulted', "{0} used its {1} playbook on {2}, its fallback", router, playbook, model) + : localize('modelRouter.playbookRouted', "{0} picked its {1} playbook on {2}", router, playbook, model); } /** Why a host-side router made its pick, for the routing line's hover. Auto explains itself in its title. */ diff --git a/src/vs/workbench/contrib/chat/common/chatDailyUsage.ts b/src/vs/workbench/contrib/chat/common/chatDailyUsage.ts new file mode 100644 index 000000000000..97b1b9ac8366 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/chatDailyUsage.ts @@ -0,0 +1,174 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { coalesce } from '../../../../base/common/arrays.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { AgentsWindowUsage } from './agentsWindowUsage.js'; +import { EditorChatUsage } from './editorChatUsage.js'; + +const usageStorageKey = 'chat.dailyUsage'; +const lastReportedDayStorageKey = 'chat.dailyUsage.lastReportedDay'; +const trackingStartDayStorageKey = 'chat.dailyUsage.trackingStartDay'; +const dayMs = 24 * 60 * 60 * 1000; +const minuteMs = 60 * 1000; +const retainedDays = 30; + +/** + * Chat usage on this machine. Windows span the current UTC day and the + * preceding UTC days, e.g. the last 7 days are today and the 6 days before. + * A window of N days covers all of its days once {@link trackedDays} reaches N. + * Totals include usage recorded by older counters before tracking started. + */ +export interface IChatDailyUsageTelemetry { + readonly messagesLast7Days: number; + readonly messagesLast30Days: number; + readonly messagesTotal: number; + readonly sessionsLast7Days: number; + readonly sessionsLast30Days: number; + readonly sessionsTotal: number; + readonly minutesSinceLastMessage: number | undefined; + readonly trackedDays: number; +} + +type DailyCount = [day: number, messages: number, sessions: number]; + +interface IStoredChatDailyUsage { + /** Counts per UTC day (days since the Unix epoch) within the retained window. */ + readonly days: DailyCount[]; + /** Time of the most recent message in milliseconds since the Unix epoch. */ + readonly lastMessage?: number; + readonly messagesTotal: number; + readonly sessionsTotal: number; +} + +function getUtcDay(time: number): number { + return Math.floor(time / dayMs); +} + +function isCount(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) && value >= 0; +} + +function isDailyCount(value: unknown): value is DailyCount { + return Array.isArray(value) && value.length === 3 && value.every(isCount); +} + +/** + * Best-effort chat usage shared by all windows and profiles on this machine. + * Overlapping writes from different windows can lose increments. + */ +export class ChatDailyUsage { + constructor(private readonly storageService: IStorageService) { } + + /** + * Records the UTC day this machine started tracking usage and seeds the + * totals from older lifetime counters, unless tracking already started. + */ + startTracking(now = Date.now()): void { + if (this.storageService.getNumber(trackingStartDayStorageKey, StorageScope.APPLICATION_SHARED) !== undefined) { + return; + } + // Each Agents Window session started with a message, but its follow-up messages were never counted, so the message total is a lower bound. + const editor = new EditorChatUsage(this.storageService); + const agentsWindowSessions = new AgentsWindowUsage(this.storageService).createdSessionCount; + const usage = this.read(); + const seeded: IStoredChatDailyUsage = { + ...usage, + messagesTotal: usage.messagesTotal + editor.messageCount + agentsWindowSessions, + sessionsTotal: usage.sessionsTotal + editor.sessionCount + agentsWindowSessions, + }; + this.storageService.storeAll([ + { key: usageStorageKey, value: JSON.stringify(seeded), scope: StorageScope.APPLICATION_SHARED, target: StorageTarget.MACHINE }, + { key: trackingStartDayStorageKey, value: getUtcDay(now), scope: StorageScope.APPLICATION_SHARED, target: StorageTarget.MACHINE }, + ], false); + } + + recordMessage(isNewSession: boolean, now = Date.now()): void { + const today = getUtcDay(now); + const usage = this.read(); + const days = usage.days.filter(([day]) => day <= today && today - day < retainedDays); + let entry = days.find(([day]) => day === today); + if (!entry) { + entry = [today, 0, 0]; + days.push(entry); + } + entry[1]++; + if (isNewSession) { + entry[2]++; + } + const updated: IStoredChatDailyUsage = { + days, + lastMessage: now, + messagesTotal: usage.messagesTotal + 1, + sessionsTotal: usage.sessionsTotal + (isNewSession ? 1 : 0), + }; + this.storageService.store(usageStorageKey, JSON.stringify(updated), StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE); + } + + getTelemetry(now = Date.now()): IChatDailyUsageTelemetry { + const today = getUtcDay(now); + const { days, lastMessage, messagesTotal, sessionsTotal } = this.read(); + let messagesLast7Days = 0, messagesLast30Days = 0, sessionsLast7Days = 0, sessionsLast30Days = 0; + for (const [day, messages, sessions] of days) { + const age = today - day; + if (age < 0 || age >= retainedDays) { + continue; + } + messagesLast30Days += messages; + sessionsLast30Days += sessions; + if (age < 7) { + messagesLast7Days += messages; + sessionsLast7Days += sessions; + } + } + // Usage recorded before daily tracking existed only has last-use times, so they seed the last message time. + const lastUsageTimes = coalesce([lastMessage, new EditorChatUsage(this.storageService).lastMessageDate, new AgentsWindowUsage(this.storageService).lastSessionCreated]); + const trackingStartDay = this.storageService.getNumber(trackingStartDayStorageKey, StorageScope.APPLICATION_SHARED, today); + return { + messagesLast7Days, + messagesLast30Days, + messagesTotal, + sessionsLast7Days, + sessionsLast30Days, + sessionsTotal, + minutesSinceLastMessage: lastUsageTimes.length ? Math.max(0, Math.floor((now - Math.max(...lastUsageTimes)) / minuteMs)) : undefined, + trackedDays: Math.min(retainedDays, Math.max(0, today - trackingStartDay)), + }; + } + + /** Claims the current UTC day's report across windows. Resolves to `undefined` when another window already claimed it. */ + async takeDailyReport(now = Date.now()): Promise { + const today = String(getUtcDay(now)); + // The local cache lags behind other windows, so it can only rule a report out without a round trip. + if (this.storageService.get(lastReportedDayStorageKey, StorageScope.APPLICATION_SHARED) === today) { + return undefined; + } + const lastReportedDay = await this.storageService.readApplicationSharedValue(lastReportedDayStorageKey); + if (lastReportedDay === today) { + return undefined; + } + const { swapped } = await this.storageService.compareAndSwapApplicationSharedValue(lastReportedDayStorageKey, lastReportedDay, today); + return swapped ? this.getTelemetry(now) : undefined; + } + + private read(): IStoredChatDailyUsage { + const empty: IStoredChatDailyUsage = { days: [], messagesTotal: 0, sessionsTotal: 0 }; + const raw = this.storageService.get(usageStorageKey, StorageScope.APPLICATION_SHARED); + if (!raw) { + return empty; + } + try { + const parsed: Partial> | null = JSON.parse(raw); + return { + days: Array.isArray(parsed?.days) ? parsed.days.filter(isDailyCount) : [], + lastMessage: isCount(parsed?.lastMessage) ? parsed.lastMessage : undefined, + messagesTotal: isCount(parsed?.messagesTotal) ? parsed.messagesTotal : 0, + sessionsTotal: isCount(parsed?.sessionsTotal) ? parsed.sessionsTotal : 0, + }; + } catch { + return empty; + } + } +} diff --git a/src/vs/workbench/contrib/chat/common/chatErrorMessages.ts b/src/vs/workbench/contrib/chat/common/chatErrorMessages.ts index 1f8cc382b4b7..d92aa195c83d 100644 --- a/src/vs/workbench/contrib/chat/common/chatErrorMessages.ts +++ b/src/vs/workbench/contrib/chat/common/chatErrorMessages.ts @@ -117,7 +117,10 @@ function secondsToHumanReadableTime(seconds: number): string { return localize('chatError.duration.hours', "{0} hours", hours); } -function getRateLimitMessage(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined): string { +/** + * @param autoModelFusion Whether the chat's Auto model is presented as Copilot Fusion, so suggestions to switch to it name it that way. + */ +function getRateLimitMessage(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined, autoModelFusion: boolean | undefined): string { const retryAfterString = fetchError.retryAfter ? secondsToHumanReadableTime(fetchError.retryAfter) : localize('chatError.aMoment', "a moment"); const code = fetchError.capiError?.code; if (code?.startsWith('agent_mode_limit_exceeded')) { // Rate limited in agent mode @@ -127,6 +130,9 @@ function getRateLimitMessage(fetchError: IChatFetchErrorPayload, copilotPlan: st if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.overloadedAuto', comment: [`{Locked=']({'}`] }, "Sorry, the upstream model provider is currently experiencing high demand. Please try again in {0}. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.overloadedFusion', comment: [`{Locked=']({'}`] }, "Sorry, the upstream model provider is currently experiencing high demand. Please try again in {0} or consider switching to Copilot Fusion. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); + } return localize({ key: 'chatError.rateLimit.overloaded', comment: [`{Locked=']({'}`] }, "Sorry, the upstream model provider is currently experiencing high demand. Please try again in {0} or consider switching to Auto. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } if (code?.startsWith('user_global_rate_limited')) { @@ -142,17 +148,26 @@ function getRateLimitMessage(fetchError: IChatFetchErrorPayload, copilotPlan: st if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.weeklyDateAuto', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please wait for your limit to reset on {0}. [Learn More]({1})", resetDateString, RATE_LIMIT_LEARN_MORE_URL); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.weeklyDateFusion', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please switch to Copilot Fusion to continue working or wait for your limit to reset on {0}. [Learn More]({1})", resetDateString, RATE_LIMIT_LEARN_MORE_URL); + } return localize({ key: 'chatError.rateLimit.weeklyDate', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please switch to the Auto model to continue working or wait for your limit to reset on {0}. [Learn More]({1})", resetDateString, RATE_LIMIT_LEARN_MORE_URL); } if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.weeklyAuto', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please wait {0} for your limit to reset. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.weeklyFusion', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please switch to Copilot Fusion to continue working or wait {0} for your limit to reset. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); + } return localize({ key: 'chatError.rateLimit.weekly', comment: [`{Locked=']({'}`] }, "You've reached your weekly rate limit. Please switch to the Auto model to continue working or wait {0} for your limit to reset. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } if (code?.startsWith('user_model_rate_limited')) { if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.modelAuto', comment: [`{Locked=']({'}`] }, "You've hit the rate limit for this model. Please try again in {0}. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.modelFusion', comment: [`{Locked=']({'}`] }, "You've hit the rate limit for this model. Please try switching to Copilot Fusion or try again in {0}. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); + } return localize({ key: 'chatError.rateLimit.model', comment: [`{Locked=']({'}`] }, "You've hit the rate limit for this model. Please try switching to Auto or try again in {0}. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } if (code?.startsWith('integration_rate_limited')) { @@ -163,12 +178,18 @@ function getRateLimitMessage(fetchError: IChatFetchErrorPayload, copilotPlan: st if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.serverAuto', comment: [`{Locked=']({'}`] }, "Sorry, you have been rate-limited. Please wait {0} before trying again. [Learn More]({1})\n\nServer Error: {2}\nError Code: {3}", retryAfterString, RATE_LIMIT_LEARN_MORE_URL, fetchError.capiError.message, fetchError.capiError.code); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.serverFusion', comment: [`{Locked=']({'}`] }, "Sorry, you have been rate-limited. Please wait {0} before trying again or consider switching to Copilot Fusion. [Learn More]({1})\n\nServer Error: {2}\nError Code: {3}", retryAfterString, RATE_LIMIT_LEARN_MORE_URL, fetchError.capiError.message, fetchError.capiError.code); + } return localize({ key: 'chatError.rateLimit.server', comment: [`{Locked=']({'}`] }, "Sorry, you have been rate-limited. Please wait {0} before trying again or consider switching to Auto. [Learn More]({1})\n\nServer Error: {2}\nError Code: {3}", retryAfterString, RATE_LIMIT_LEARN_MORE_URL, fetchError.capiError.message, fetchError.capiError.code); } if (fetchError.isAuto) { return localize({ key: 'chatError.rateLimit.genericAuto', comment: [`{Locked=']({'}`] }, "Sorry, your request was rate-limited. Please wait {0} before trying again. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } + if (autoModelFusion) { + return localize({ key: 'chatError.rateLimit.genericFusion', comment: [`{Locked=']({'}`] }, "Sorry, your request was rate-limited. Please wait {0} before trying again or consider switching to Copilot Fusion. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); + } return localize({ key: 'chatError.rateLimit.generic', comment: [`{Locked=']({'}`] }, "Sorry, your request was rate-limited. Please wait {0} before trying again or consider switching to Auto. [Learn More]({1})", retryAfterString, RATE_LIMIT_LEARN_MORE_URL); } @@ -273,11 +294,11 @@ export function getFilteredMessage(category: FilterReason | string, supportsMark * access to the GitHub outage status, so the outage note is never appended * (assume no outage). */ -export function getChatErrorDetailsFromFetchError(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined, isUsageBasedBilling?: boolean, quotaResetDate?: string): IChatResponseErrorDetails { - return { code: fetchError.type, ...getChatErrorDetailsInner(fetchError, copilotPlan, isUsageBasedBilling, quotaResetDate) }; +export function getChatErrorDetailsFromFetchError(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined, isUsageBasedBilling?: boolean, quotaResetDate?: string, autoModelFusion?: boolean): IChatResponseErrorDetails { + return { code: fetchError.type, ...getChatErrorDetailsInner(fetchError, copilotPlan, isUsageBasedBilling, quotaResetDate, autoModelFusion) }; } -function getChatErrorDetailsInner(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined, isUsageBasedBilling?: boolean, quotaResetDate?: string): IChatResponseErrorDetails { +function getChatErrorDetailsInner(fetchError: IChatFetchErrorPayload, copilotPlan: string | undefined, isUsageBasedBilling?: boolean, quotaResetDate?: string, autoModelFusion?: boolean): IChatResponseErrorDetails { const requestId = fetchError.requestId ?? ''; const reason = fetchError.reason ?? ''; switch (fetchError.type) { @@ -287,7 +308,7 @@ function getChatErrorDetailsInner(fetchError: IChatFetchErrorPayload, copilotPla return CanceledMessage; case ChatFetchResponseType.RateLimited: return { - message: getRateLimitMessage(fetchError, copilotPlan), + message: getRateLimitMessage(fetchError, copilotPlan, autoModelFusion), level: ChatErrorLevel.Info, isRateLimited: true }; @@ -381,6 +402,7 @@ export function getChatErrorDetailsFromMeta(error: ErrorInfo | undefined, contex context?.copilotPlan ?? chatError.copilotPlan, context?.isUsageBasedBilling ?? chatError.isUsageBasedBilling, context?.quotaResetDate ?? chatError.quotaResetDate, + context?.autoModelFusion, ); } @@ -393,6 +415,8 @@ export interface IChatErrorContext { readonly copilotPlan?: string; readonly isUsageBasedBilling?: boolean; readonly quotaResetDate?: string; + /** Whether the chat's Auto model is presented as Copilot Fusion. */ + readonly autoModelFusion?: boolean; } /** diff --git a/src/vs/workbench/contrib/chat/common/chatPetJumpGame.ts b/src/vs/workbench/contrib/chat/common/chatPetJumpGame.ts index 9a6ed097868c..eaab2e5bb6c9 100644 --- a/src/vs/workbench/contrib/chat/common/chatPetJumpGame.ts +++ b/src/vs/workbench/contrib/chat/common/chatPetJumpGame.ts @@ -167,11 +167,16 @@ export class ChatPetJumpGameModel { this._hops = checkpoint.hops; this.accumulator = 0; this.cancelCharge(); - const platform = this._platforms.find(platform => platform.id === this._player.platform); - if (platform?.kind === 'crumbling') { - platform.collapseStep = this.steps; - platform.collapseProgress = 0; - platform.fallDistance = 0; + for (const platform of this._platforms) { + if (platform.kind === 'crumbling') { + if (platform.id === this._player.platform) { + platform.collapseStep = this.steps; + } else { + delete platform.collapseStep; + } + platform.collapseProgress = 0; + platform.fallDistance = 0; + } } this.resize(width); } diff --git a/src/vs/workbench/contrib/chat/common/chatService/chatQuestionCarouselHelpers.ts b/src/vs/workbench/contrib/chat/common/chatService/chatQuestionCarouselHelpers.ts index 61d7c150e612..1ae3ac2b91c0 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/chatQuestionCarouselHelpers.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/chatQuestionCarouselHelpers.ts @@ -12,9 +12,21 @@ export interface IOrderedQuestionOption { readonly originalIndex: number; } +/** + * Whether the question is a yes/no choice, the shape MCP elicitation and the agent host emit for boolean fields. + */ +export function isBooleanQuestion(question: IChatQuestion): boolean { + const options = question.options; + return question.type === 'singleSelect' + && options?.length === 2 + && options.some(opt => opt.value === 'true') + && options.some(opt => opt.value === 'false'); +} + /** * Order a question's options as they are displayed: defaults first, then the * rest, each group keeping declared order. Defaults are named by option *id*. + * Yes/no questions always list Yes before No. * * The voice path numbers options from this list, so the widget must render from * the same function or the number the user hears stops matching the one they see. @@ -22,6 +34,9 @@ export interface IOrderedQuestionOption { export function getOptionsWithDefaultsFirst(question: IChatQuestion): IOrderedQuestionOption[] { const options = question.options ?? []; const orderedOptions = options.map((option, index) => ({ option, originalIndex: index })); + if (isBooleanQuestion(question)) { + return orderedOptions.sort((a, b) => Number(b.option.value === 'true') - Number(a.option.value === 'true')); + } const defaultOptionIds = Array.isArray(question.defaultValue) ? question.defaultValue : (typeof question.defaultValue === 'string' ? [question.defaultValue] : []); diff --git a/src/vs/workbench/contrib/chat/common/chatService/chatService.ts b/src/vs/workbench/contrib/chat/common/chatService/chatService.ts index de7a024724d9..c7686873f21c 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/chatService.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/chatService.ts @@ -686,16 +686,22 @@ export interface IChatAutoModeResolutionPart { resolved?: { readonly id: string; readonly name: string; readonly reason?: string }; /** A router other than Auto, such as a host-side model router. */ router?: string; + /** The playbook a host-side model router chose, when it is written as playbooks. */ + playbook?: string; /** The chosen route's `when`, when it decided the pick. */ preference?: string; /** The thinking effort the router chose for this turn. */ effort?: string; + /** The context window a host-side model router asked for, in tokens. */ + contextSize?: number; /** Display name of the model the router moved off on this turn. */ switchedFrom?: string; /** The router had no confident pick and used its first route. */ defaulted?: boolean; /** The chat stayed on the model it was already running. */ kept?: boolean; + /** Auto is presented as Copilot Fusion, so the row names it that way. */ + fusion?: boolean; } /** @@ -756,6 +762,18 @@ export interface IChatTerminalToolInvocationData { intention?: string; /** The working directory URI for the terminal */ cwd?: UriComponents; + /** + * Where an Agent Host command runs, shown before approval because the same + * relative command line runs a different program in another directory or + * environment. The built-in terminal tool leaves this unset and names a + * changed directory in its confirmation title instead. + */ + executionTarget?: { + /** The working directory, verbatim in its execution environment's path syntax. */ + readonly workingDirectory?: string; + /** The execution environment, when it is not the agent host's own machine. */ + readonly environment?: string; + }; /** * Pre-computed confirmation display data (localization must happen at source). * Contains the command line to show in confirmation (potentially without cd prefix) @@ -2177,6 +2195,10 @@ export interface IChatRequestSubmittedEvent { export interface IChatRequestAcceptedEvent { readonly chatSessionResource: URI; readonly isNewSession: boolean; + /** The mode (agent) the submission was sent with, if the sender chose one. */ + readonly modeInfo?: IChatRequestModeInfo; + /** Actor that produced an Agent Host message, e.g. an agent delegating to another session. Absent for direct sends. */ + readonly agentHostMessageOrigin?: MessageOrigin; } export const IChatService = createDecorator('IChatService'); diff --git a/src/vs/workbench/contrib/chat/common/chatService/chatServiceImpl.ts b/src/vs/workbench/contrib/chat/common/chatService/chatServiceImpl.ts index 31f72cf8481c..4aeff9644b2e 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/chatServiceImpl.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/chatServiceImpl.ts @@ -88,6 +88,7 @@ interface IRemoteSessionLoad { /** Input state of a restored remote session that is applied and logged once its model is published. */ interface IRemoteSessionInputRestore { readonly modelId: string | undefined; + readonly modelConfiguration: IStringDictionary | undefined; readonly agentUri: URI | undefined; readonly historySelectedModel: string | undefined; readonly storedInputState: ISerializableChatModelInputState | undefined; @@ -223,6 +224,11 @@ export function backfillTransferredModel( return { ...transferredState, selectedModel: historyModel }; } +/** A restored model the input reclaims once its metadata publishes, with the configuration to restore it with. */ +function restoredIntendedModel(modelId: string, configuration: IStringDictionary | undefined): IIntendedModelSelection { + return { modelId, reason: ModelSelectionReason.SessionRestore, ...(configuration ? { configuration } : {}) }; +} + /** * Carry a draft's intended model onto the session it materialized into when that session has a * different type. Session types that own a model pool key their identifiers by the type, so a @@ -1056,23 +1062,26 @@ export class ChatService extends Disposable implements IChatService { const storedMetadata = this._chatSessionStore.getMetadataForSessionSync(sessionResource); const storedPermissionLevel = storedMetadata?.permissionLevel; const storedInputState = storedMetadata?.inputState; + // The session request history only tells us which model id was last used, not the + // user's per-model configuration (e.g. thinking effort, context window). Take that + // configuration from the transferred draft, which carries the session's current one, else + // from the persisted draft when it refers to the same model, so reopening the session + // restores the full model config and not just the bare model id. Older drafts stored the + // configuration as a sibling of `selectedModel` (legacy top-level field) rather than nested + // within it, so fall back to that for backwards compatibility. + const transferredModelConfiguration = providedSession.transferredState?.selectedModelId === modelId + ? providedSession.transferredState?.selectedModelConfiguration + : undefined; + const storedModelConfiguration = storedInputState?.selectedModel?.modelConfiguration + ?? (storedInputState as { modelConfiguration?: IStringDictionary } | undefined)?.modelConfiguration; + const modelConfiguration = transferredModelConfiguration + ?? (storedInputState?.selectedModel?.identifier === modelId ? storedModelConfiguration : undefined); let initialData: ISerializedChatDataReference | undefined = undefined; let historySelectedModel: string | undefined = undefined; let historyDerivedModel: ISerializableChatModelInputState['selectedModel'] = undefined; if ((modelId || agentUri)) { const mode: ISerializableChatModelInputState['mode'] = agentUri ? { kind: ChatModeKind.Agent, id: agentUri.toString() } : { kind: ChatModeKind.Agent, id: ChatMode.Agent.id }; const modelMetadata = modelId ? this.languageModelsService.lookupLanguageModel(modelId) : undefined; - // The session request history only tells us which model id was last used, not the - // user's per-model configuration (e.g. thinking effort, context window). Preserve that - // configuration from the persisted draft when it refers to the same model, so reopening - // the session restores the full model config and not just the bare model id. Older drafts - // stored the configuration as a sibling of `selectedModel` (legacy top-level field) rather - // than nested within it, so fall back to that for backwards compatibility. - const storedModelConfiguration = storedInputState?.selectedModel?.modelConfiguration - ?? (storedInputState as { modelConfiguration?: IStringDictionary } | undefined)?.modelConfiguration; - const modelConfiguration = storedInputState?.selectedModel?.identifier === modelId - ? storedModelConfiguration - : undefined; // When the live model list has not loaded yet (cold restore) `lookupLanguageModel` // returns undefined. Don't discard the known model: fall back to the session's saved // draft model, which carries the full serialized metadata (including @@ -1155,7 +1164,7 @@ export class ChatService extends Disposable implements IChatService { // The id is known but no metadata was found for it. Record it anyway so the input reclaims // the model once it publishes, rather than settling on the default. if (modelId && !historySelectedModel) { - model.inputModel.setIntendedModel({ modelId, reason: ModelSelectionReason.SessionRestore }); + model.inputModel.setIntendedModel(restoredIntendedModel(modelId, modelConfiguration)); } // Restore permission level from metadata even when initialData was not constructed @@ -1170,7 +1179,7 @@ export class ChatService extends Disposable implements IChatService { return { model, - inputRestore: { modelId, agentUri, historySelectedModel, storedInputState, hasInitialData: !!initialData }, + inputRestore: { modelId, modelConfiguration, agentUri, historySelectedModel, storedInputState, hasInitialData: !!initialData }, }; } @@ -1178,9 +1187,9 @@ export class ChatService extends Disposable implements IChatService { * Applies the history-derived model again after the restored model is * published, and logs where the input state came from. */ - private finishRemoteSessionInputState(model: ChatModel, providedSession: IChatSession, { modelId, agentUri, historySelectedModel, storedInputState, hasInitialData }: IRemoteSessionInputRestore): void { + private finishRemoteSessionInputState(model: ChatModel, providedSession: IChatSession, { modelId, modelConfiguration, agentUri, historySelectedModel, storedInputState, hasInitialData }: IRemoteSessionInputRestore): void { if (modelId && !historySelectedModel) { - model.inputModel.setIntendedModel({ modelId, reason: ModelSelectionReason.SessionRestore }); + model.inputModel.setIntendedModel(restoredIntendedModel(modelId, modelConfiguration)); } logChangesToStateModel(model.inputModel, `loadRemoteSession inputState source: session=${model.sessionResource.toString()}, chatSessionType=${getChatSessionType(model.sessionResource)}, historyModelId=${modelId}, agentUri=${agentUri?.toString()}, historySelectedModel=${historySelectedModel}, transferredSelectedModel=${providedSession.transferredState?.inputState?.selectedModel?.identifier}, storedSelectedModel=${storedInputState?.selectedModel?.identifier}, finalSelectedModel=${model.inputModel.state.get()?.selectedModel?.identifier}, hasTransferredInputState=${!!providedSession.transferredState?.inputState}, hasStoredInputState=${!!storedInputState}, hasInitialData=${hasInitialData}`, model.inputModel.state.get(), undefined, this.logService); } @@ -1676,7 +1685,7 @@ export class ChatService extends Disposable implements IChatService { const notifyAccepted = () => { if (isSubmission && !options?.isSystemInitiated && !options?.hideFromTranscript) { this._modelsWithAcceptedRequests.add(model); - this._onDidAcceptRequest.fire({ chatSessionResource: sessionResource, isNewSession }); + this._onDidAcceptRequest.fire({ chatSessionResource: sessionResource, isNewSession, modeInfo: options?.modeInfo, agentHostMessageOrigin: options?.agentHostMessageOrigin }); const provider = this.chatSessionService.getChatSessionContribution(getChatSessionType(sessionResource))?.agentHostProviderId; if (isCopilotAgentHostProvider(provider)) { // Copilot harness submissions bypass the extension's legacy usage signal, including queued sends in either window. diff --git a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts index 1bcd46a3acdf..8eea56f54818 100644 --- a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts +++ b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts @@ -628,6 +628,11 @@ export interface IChatSession extends IDisposable { * model instead of falling back to the request history's. */ readonly selectedModelId?: string; + /** + * The configuration (e.g. thinking effort) that the transferred draft + * gives {@link selectedModelId}, kept for the same cold restore. + */ + readonly selectedModelConfiguration?: IStringDictionary; }; requestHandler?: ( diff --git a/src/vs/workbench/contrib/chat/common/constants.ts b/src/vs/workbench/contrib/chat/common/constants.ts index 2dd89c522ea3..7d10f6817556 100644 --- a/src/vs/workbench/contrib/chat/common/constants.ts +++ b/src/vs/workbench/contrib/chat/common/constants.ts @@ -79,6 +79,7 @@ export enum ChatConfiguration { AutoApprovedUrls = 'chat.tools.urls.autoApprove', EligibleForAutoApproval = 'chat.tools.eligibleForAutoApproval', EnableMath = 'chat.math.enabled', + HtmlPreviewEnabled = 'chat.htmlPreview.enabled', CheckpointsEnabled = 'chat.checkpoints.enabled', ThinkingStyle = 'chat.agent.thinkingStyle', ThinkingGenerateTitles = 'chat.agent.thinking.generateTitles', @@ -134,6 +135,7 @@ export enum ChatConfiguration { HarnessSwitchFeedbackSurveyEnabled = 'chat.harnessSwitchFeedbackSurvey.enabled', ChatCustomizationsStructuredPreviewEnabled = 'chat.customizations.structuredPreview.enabled', + ChatCustomizationsLocation = 'chat.customizations.location', ChatCustomizationsToggleStyle = 'chat.experimental.customizations.toggleStyle', ChatCustomizationsPromptMigrationEnabled = 'chat.customizations.promptMigration.enabled', ChatCustomizationsUserDataMigrationEnabled = 'chat.customizations.userDataMigration.enabled', @@ -162,6 +164,7 @@ export enum ChatConfiguration { AgentsHandoffTipMode = 'chat.agentsHandoffTip.mode', AgentsHandoffTipDelaySeconds = 'chat.agentsHandoffTip.delaySeconds', BtwTipEnabled = 'chat.btwTip.enabled', + AutomateTipEnabled = 'chat.automateTip.enabled', SendInBackgroundTipEnabled = 'chat.sendInBackgroundTip.enabled', CopilotCliCommandEnabled = 'chat.copilotCliCommand.enabled', diff --git a/src/vs/workbench/contrib/chat/common/customAgentUsage.ts b/src/vs/workbench/contrib/chat/common/customAgentUsage.ts new file mode 100644 index 000000000000..ca029ce8c6a6 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/customAgentUsage.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 { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; + +const CUSTOM_AGENT_USE_COUNT_STORAGE_KEY = 'chat.customAgentUsage.count'; +const CUSTOM_AGENT_LAST_USED_STORAGE_KEY = 'chat.customAgentUsage.lastUsed'; + +/** + * Best-effort, machine-local use of custom agents, i.e. agents not built into the product, shared by all + * windows, profiles and applications. Overlapping window writes can lose increments. + */ +export class CustomAgentUsage { + constructor(private readonly storageService: IStorageService) { } + + /** How many requests were submitted with a custom agent. */ + get useCount(): number { + return this.storageService.getNumber(CUSTOM_AGENT_USE_COUNT_STORAGE_KEY, StorageScope.APPLICATION_SHARED, 0); + } + + /** When a request was last submitted with a custom agent, in milliseconds since the epoch. */ + get lastUsed(): number | undefined { + return this.storageService.getNumber(CUSTOM_AGENT_LAST_USED_STORAGE_KEY, StorageScope.APPLICATION_SHARED); + } + + recordUse(timestamp = Date.now()): void { + this.storageService.storeAll([ + { key: CUSTOM_AGENT_USE_COUNT_STORAGE_KEY, value: this.useCount + 1, scope: StorageScope.APPLICATION_SHARED, target: StorageTarget.MACHINE }, + { key: CUSTOM_AGENT_LAST_USED_STORAGE_KEY, value: Math.max(this.lastUsed ?? 0, timestamp), scope: StorageScope.APPLICATION_SHARED, target: StorageTarget.MACHINE }, + ], false); + } +} diff --git a/src/vs/workbench/contrib/chat/common/customizationHarnessService.ts b/src/vs/workbench/contrib/chat/common/customizationHarnessService.ts index cfd381e79f3d..e3260fcbc616 100644 --- a/src/vs/workbench/contrib/chat/common/customizationHarnessService.ts +++ b/src/vs/workbench/contrib/chat/common/customizationHarnessService.ts @@ -144,7 +144,8 @@ export interface ICustomizationMarketplaceManagementProvider { */ readonly onDidChangeMarketplaces: Event; list(sessionResource: URI): Promise; - add(sessionResource: URI, source: string): Promise; + /** Omit the session for a global mutation through the local provider. */ + add(sessionResource: URI | undefined, source: string): Promise; queryMarketplace(sessionResource: URI, marketplace: ICustomizationMarketplaceInfo, options: ICustomizationMarketplaceSourceQuery, token: CancellationToken): Promise; remove(sessionResource: URI, name: string, force?: boolean): Promise; refresh(sessionResource: URI, name?: string): Promise; @@ -258,6 +259,15 @@ export interface IHarnessDescriptor { readonly marketplaceManagementProvider?: ICustomizationMarketplaceManagementProvider; } +/** Organization control over a single customization. */ +export interface ICustomizationOrganizationControl { + /** + * Enabled state the organization requires. Undefined when the organization + * supplies the customization without locking its enablement. + */ + readonly requiredEnabled?: boolean; +} + /** * Identifies who supplied a built-in or account customization. * `label` is optional for `harness`, which defaults to the active harness name. @@ -293,6 +303,8 @@ export interface ICustomizationItem { readonly enabled?: boolean; /** Host-published reason for a disabled customization. */ readonly disabledReason?: CustomizationDisabledReason; + /** Set when the user's organization manages this customization. */ + readonly organizationControl?: ICustomizationOrganizationControl; /** When set, items with the same groupKey are displayed under a shared collapsible header. */ readonly groupKey?: string; /** diff --git a/src/vs/workbench/contrib/chat/common/customizationsLocation.ts b/src/vs/workbench/contrib/chat/common/customizationsLocation.ts new file mode 100644 index 000000000000..08654395cc01 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/customizationsLocation.ts @@ -0,0 +1,20 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; + +export type ChatCustomizationsLocation = 'auto' | 'sidebar' | 'sessionsHeader' | 'chatToolbar' | 'chatInput'; + +export const ChatCustomizationsLocationContext = new RawContextKey>('chatCustomizationsLocation', 'chatToolbar'); + +export function resolveChatCustomizationsLocation(location: ChatCustomizationsLocation, isSessionsWindow: boolean, separateNavigation: boolean): Exclude { + if (!isSessionsWindow) { + return location === 'chatInput' ? 'chatInput' : 'chatToolbar'; + } + if (location === 'auto') { + return separateNavigation ? 'sessionsHeader' : 'sidebar'; + } + return location; +} diff --git a/src/vs/workbench/contrib/chat/common/editorChatUsage.ts b/src/vs/workbench/contrib/chat/common/editorChatUsage.ts index e4f471fff1b5..72d269639685 100644 --- a/src/vs/workbench/contrib/chat/common/editorChatUsage.ts +++ b/src/vs/workbench/contrib/chat/common/editorChatUsage.ts @@ -50,6 +50,19 @@ export class EditorChatUsage { ?? ['copilot', 'claude', 'codex', 'remoteCopilot', 'remoteClaude', 'remoteCodex'].reduce((total, provider) => total + this.getNumber(`sessions.${provider}`), 0); } + /** When the user last sent an editor chat message, or `undefined` if no message was recorded. */ + get lastMessageDate(): number | undefined { + return this.getNumber('messages') > 0 ? this.getNumber('lastMessageDate') : undefined; + } + + get messageCount(): number { + return this.getNumber('messages'); + } + + get sessionCount(): number { + return providers.reduce((total, provider) => total + this.getNumber(`sessions.${provider}`), 0); + } + recordSubmission(sessionType: string, isNewSession: boolean, otherSessionInProgress: boolean, otherWindowSessionInProgress: boolean, timestamp: number): void { if (isNewSession) { this.increment(`sessions.${getProvider(sessionType)}`); @@ -81,12 +94,13 @@ export class EditorChatUsage { } } const messages = this.getNumber('messages'); + const lastMessageDate = this.lastMessageDate; return { editorSessionsByProvider: JSON.stringify(sessionsByProvider), editorMessages: messages, editorMessagesWithOtherSessionInProgress: this.getNumber('messagesWithOtherSessionInProgress'), editorMessagesWithOtherSessionInProgressAcrossWindows: this.getNumber('messagesWithOtherSessionInProgressAcrossWindows'), - editorLastMessageSecondsAgo: messages > 0 ? Math.max(0, Math.floor((now - this.getNumber('lastMessageDate')) / 1000)) : undefined, + editorLastMessageSecondsAgo: lastMessageDate !== undefined ? Math.max(0, Math.floor((now - lastMessageDate) / 1000)) : undefined, }; } } diff --git a/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatPlanReviewData.ts b/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatPlanReviewData.ts index f19521d1501e..10276fc8e0cf 100644 --- a/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatPlanReviewData.ts +++ b/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatPlanReviewData.ts @@ -23,6 +23,12 @@ export class ChatPlanReviewData implements IChatPlanReview { public draftFeedback: string | undefined; public draftCollapsed: boolean | undefined; + /** + * Set to `true` only when a person settled the review through its own UI. A voice answer and a dismissal + * caused by cancellation or disposal leave it unset. Not persisted. + */ + public submittedByUser?: boolean; + constructor( public title: string, public content: string, diff --git a/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatQuestionCarouselData.ts b/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatQuestionCarouselData.ts index 2745c87c71a5..10486fa353f4 100644 --- a/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatQuestionCarouselData.ts +++ b/src/vs/workbench/contrib/chat/common/model/chatProgressTypes/chatQuestionCarouselData.ts @@ -32,6 +32,13 @@ export class ChatQuestionCarouselData implements IChatQuestionCarousel { public answeredExternally?: boolean; public autoReply?: boolean; + /** + * Set to `true` only when a person settled the carousel through its own UI, whether by submitting or + * dismissing it. Answers submitted on their behalf (defaults, automatic replies, voice) and dismissals caused + * by cancellation or disposal leave it unset. Not persisted. + */ + public submittedByUser?: boolean; + /** * Marks the carousel as dismissed with the given answers and clears draft * state. Safe to call multiple times — subsequent calls are no-ops. diff --git a/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponents.ts b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponents.ts new file mode 100644 index 000000000000..58fb22a33c09 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponents.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * The schema of a native components block: a composition that an agent authors in a fenced code + * block and that VS Code renders with its own components. The agent supplies content, data and + * composition only; every component's implementation and appearance belongs to the renderer. + */ + +/** The language of the fenced code block that holds a native components block. */ +export const NATIVE_COMPONENTS_LANGUAGE_ID = 'vscode-ui'; + +/** The schema version. A fence that declares no version is version 1. */ +export const NATIVE_COMPONENTS_SCHEMA_VERSION = 1; + +/** Bounds of a block. A block that exceeds one is rejected as a whole rather than truncated. */ +export const NativeComponentsLimits = { + /** UTF-16 code units of the block's source. */ + sourceLength: 32_000, + /** Nesting depth of components; a top-level component has depth 1. */ + depth: 8, + /** Components in the block, counting every tag. */ + components: 2_000, + tableColumns: 12, + tableRows: 100, + bars: 24, +} as const; + +/** + * The meaning of a value, chosen by the agent. The renderer maps it to theme colors and pairs it + * with an icon and a label, so that it is never conveyed by color alone. + */ +export type NativeComponentTone = 'neutral' | 'positive' | 'negative' | 'warning'; + +export type NativeTextVariant = 'body' | 'heading' | 'caption'; + +export type NativeColumnAlignment = 'start' | 'end'; + +/** Lays its children out from top to bottom. */ +export interface INativeStack { + readonly type: 'stack'; + readonly children: readonly NativeComponent[]; +} + +/** Lays its children out side by side in equal columns, which wrap when space runs out. */ +export interface INativeColumns { + readonly type: 'columns'; + readonly children: readonly NativeComponent[]; +} + +export interface INativeText { + readonly type: 'text'; + readonly variant: NativeTextVariant; + readonly text: string; +} + +export interface INativeMetric { + readonly type: 'metric'; + readonly label: string; + readonly value: string; + /** A change or comparison shown beside the value, such as `-85%`. */ + readonly delta: string | undefined; + readonly tone: NativeComponentTone; +} + +export interface INativeBadge { + readonly type: 'badge'; + readonly text: string; + readonly tone: NativeComponentTone; +} + +export interface INativeTableColumn { + readonly header: string; + readonly align: NativeColumnAlignment; +} + +export interface INativeTable { + readonly type: 'table'; + readonly caption: string | undefined; + readonly columns: readonly INativeTableColumn[]; + /** Every row has one cell per column. */ + readonly rows: readonly (readonly string[])[]; +} + +export interface INativeBar { + readonly label: string; + /** A finite number that is not negative. */ + readonly value: number; + /** The value as it was authored, which is what the chart displays. */ + readonly valueText: string; +} + +export interface INativeBarChart { + readonly type: 'barChart'; + readonly title: string; + /** The unit of every value, such as `s`. */ + readonly unit: string | undefined; + readonly bars: readonly INativeBar[]; +} + +/** Content that is hidden until the user expands its summary. */ +export interface INativeDisclosure { + readonly type: 'disclosure'; + readonly summary: string; + readonly children: readonly NativeComponent[]; +} + +export type NativeComponent = INativeStack | INativeColumns | INativeText | INativeMetric | INativeBadge | INativeTable | INativeBarChart | INativeDisclosure; + +export interface INativeComponentsDocument { + readonly version: typeof NATIVE_COMPONENTS_SCHEMA_VERSION; + readonly children: readonly NativeComponent[]; +} diff --git a/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsParser.ts b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsParser.ts new file mode 100644 index 000000000000..8367a66c37e4 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsParser.ts @@ -0,0 +1,458 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../../nls.js'; +import { INativeBar, INativeComponentsDocument, INativeTableColumn, NATIVE_COMPONENTS_LANGUAGE_ID, NATIVE_COMPONENTS_SCHEMA_VERSION, NativeColumnAlignment, NativeComponent, NativeComponentsLimits, NativeComponentTone, NativeTextVariant } from './nativeComponents.js'; + +export interface INativeComponentsError { + /** A localized reason that an author can act on. */ + readonly message: string; + /** The 1-based line of the block's source that the error refers to, when it has one. */ + readonly line: number | undefined; +} + +export type NativeComponentsParseResult = + | { readonly document: INativeComponentsDocument; readonly error?: undefined } + | { readonly document?: undefined; readonly error: INativeComponentsError }; + +/** + * Parses and validates the markup of a native components block. + * + * The markup looks like JSX, but nothing in it is evaluated: it consists of the tags of the + * component catalogue with quoted literal attributes. Anything else is rejected, including + * unknown components and attributes, expressions, and text where no text is expected, so that a + * block either renders exactly as specified or not at all. + * + * @param source The text between the fences. + * @param fenceInfo The info string of the opening fence, such as `vscode-ui` or `vscode-ui v1`. + */ +export function parseNativeComponents(source: string, fenceInfo: string = NATIVE_COMPONENTS_LANGUAGE_ID): NativeComponentsParseResult { + try { + checkVersion(fenceInfo); + if (source.length > NativeComponentsLimits.sourceLength) { + throw new MarkupError(localize('nativeComponents.tooLarge', "The block is longer than {0} characters.", NativeComponentsLimits.sourceLength)); + } + const children = toComponents(new MarkupReader(source).readDocument(), undefined); + if (children.length === 0) { + throw new MarkupError(localize('nativeComponents.empty', "The block has no components.")); + } + return { document: { version: NATIVE_COMPONENTS_SCHEMA_VERSION, children } }; + } catch (error) { + if (error instanceof MarkupError) { + return { error: { message: error.message, line: error.line } }; + } + throw error; + } +} + +class MarkupError extends Error { + constructor(message: string, readonly line?: number) { + super(message); + } +} + +function checkVersion(fenceInfo: string): void { + const [language, ...options] = fenceInfo.trim().split(/\s+/); + if (language.toLowerCase() === NATIVE_COMPONENTS_LANGUAGE_ID) { + if (options.length === 0) { + return; + } + const version = options.length === 1 ? /^v(?\d+)$/.exec(options[0])?.groups?.version : undefined; + if (version !== undefined) { + if (Number(version) === NATIVE_COMPONENTS_SCHEMA_VERSION) { + return; + } + throw new MarkupError(localize('nativeComponents.unsupportedVersion', "The block uses schema version {0}, but this version of VS Code supports version {1}.", version, NATIVE_COMPONENTS_SCHEMA_VERSION)); + } + } + throw new MarkupError(localize('nativeComponents.fenceInfo', "The fence can only name the language {0}, optionally followed by a schema version such as v{1}.", NATIVE_COMPONENTS_LANGUAGE_ID, NATIVE_COMPONENTS_SCHEMA_VERSION)); +} + +//#region Markup + +interface IMarkupElement { + readonly name: string; + readonly line: number; + readonly attributes: ReadonlyMap; + readonly children: readonly IMarkupElement[]; + /** The text directly inside the element, with entities decoded and whitespace collapsed. */ + readonly text: string; + /** The line on which {@link text} starts, when there is any. */ + readonly textLine: number | undefined; +} + +type MarkupContent = Pick; + +const namedEntities: { readonly [name: string]: string } = { amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'' }; + +/** Decodes the entities that let a literal contain markup characters. Any other `&` is kept as written. */ +function decodeEntities(text: string): string { + return text.replace(/&(?:#x(?[0-9a-fA-F]{1,6})|#(?[0-9]{1,7})|(?amp|lt|gt|quot|apos));/g, (match, hex: string | undefined, decimal: string | undefined, name: string | undefined) => { + if (name) { + return namedEntities[name]; + } + const codePoint = hex ? parseInt(hex, 16) : parseInt(decimal!, 10); + const isScalarValue = codePoint <= 0x10FFFF && (codePoint < 0xD800 || codePoint > 0xDFFF); + return isScalarValue ? String.fromCodePoint(codePoint) : match; + }); +} + +/** + * Collapses whitespace as HTML does: only the ASCII kinds, so that a non-breaking space keeps + * holding its words together. Text that is nothing but spaces of any kind is empty. + */ +function collapseWhitespace(text: string): string { + return /\S/.test(text) ? text.replace(/[ \t\n\r\f]+/g, ' ').replace(/^ | $/g, '') : ''; +} + +/** Reads the tag structure of a block without interpreting component names or attributes. */ +class MarkupReader { + + private offset = 0; + private line = 1; + private components = 0; + + constructor(private readonly source: string) { } + + readDocument(): readonly IMarkupElement[] { + const content = this.readContent(undefined, 0); + if (content.text) { + throw new MarkupError(localize('nativeComponents.topLevelText', "Text must be inside a component, such as \"Text\"."), content.textLine); + } + return content.children; + } + + private readContent(parent: string | undefined, depth: number): MarkupContent { + const children: IMarkupElement[] = []; + let text = ''; + let textLine: number | undefined; + while (true) { + const tagStart = this.source.indexOf('<', this.offset); + const textEnd = tagStart === -1 ? this.source.length : tagStart; + const run = this.source.substring(this.offset, textEnd); + const brace = /[{}]/.exec(run); + if (brace) { + this.advance(this.offset + brace.index); + throw this.expressionError(); + } + const textStart = textLine === undefined ? /\S/.exec(run) : null; + if (textStart) { + this.advance(this.offset + textStart.index); + textLine = this.line; + } + text += run; + this.advance(textEnd); + + if (tagStart === -1) { + if (parent !== undefined) { + throw new MarkupError(localize('nativeComponents.unclosed', "\"{0}\" is not closed. Expected {1}.", parent, ``), this.line); + } + break; + } + if (this.source.startsWith('') { + throw new MarkupError(parent === undefined + ? localize('nativeComponents.unexpectedClosingTag', "Unexpected closing tag {0}.", ``) + : localize('nativeComponents.mismatchedClosingTag', "Expected {0} to close \"{1}\".", ``, parent), line); + } + this.advance(this.offset + 1); + } + + private readElement(depth: number): IMarkupElement { + const line = this.line; + this.advance(this.offset + 1); + const name = this.readName(); + if (!name) { + throw new MarkupError(localize('nativeComponents.unexpectedTagStart', "Expected a component name after \"<\". Write a literal \"<\" in text as {0}.", '<'), line); + } + if (++this.components > NativeComponentsLimits.components) { + throw new MarkupError(localize('nativeComponents.tooManyComponents', "The block has more than {0} components.", NativeComponentsLimits.components), line); + } + if (depth > NativeComponentsLimits.depth) { + throw new MarkupError(localize('nativeComponents.tooDeep', "Components are nested more than {0} levels deep.", NativeComponentsLimits.depth), line); + } + + const attributes = new Map(); + while (true) { + this.skipWhitespace(); + if (this.source.startsWith('/>', this.offset)) { + this.advance(this.offset + 2); + return { name, line, attributes, children: [], text: '', textLine: undefined }; + } + const character = this.source[this.offset]; + if (character === '>') { + this.advance(this.offset + 1); + return { name, line, attributes, ...this.readContent(name, depth) }; + } + if (character === undefined) { + throw new MarkupError(localize('nativeComponents.unclosedTag', "The \"{0}\" tag is not closed.", name), line); + } + if (character === '{') { + throw this.expressionError(); + } + this.readAttribute(name, attributes); + } + } + + private readAttribute(element: string, attributes: Map): void { + const line = this.line; + const name = this.readName(); + if (!name) { + throw new MarkupError(localize('nativeComponents.unexpectedCharacter', "Unexpected \"{0}\" in the \"{1}\" tag.", this.source[this.offset], element), line); + } + this.skipWhitespace(); + let quote: string | undefined; + if (this.source[this.offset] === '=') { + this.advance(this.offset + 1); + this.skipWhitespace(); + quote = this.source[this.offset]; + } + if (quote === '{') { + throw this.expressionError(); + } + const valueEnd = quote === '"' || quote === '\'' ? this.source.indexOf(quote, this.offset + 1) : -1; + if (valueEnd === -1) { + throw new MarkupError(localize('nativeComponents.unquotedAttribute', "The \"{0}\" attribute of \"{1}\" needs a value in quotes.", name, element), line); + } + if (attributes.has(name)) { + throw new MarkupError(localize('nativeComponents.duplicateAttribute', "The \"{0}\" attribute of \"{1}\" is set more than once.", name, element), line); + } + attributes.set(name, collapseWhitespace(decodeEntities(this.source.substring(this.offset + 1, valueEnd)))); + this.advance(valueEnd + 1); + } + + private expressionError(): MarkupError { + return new MarkupError(localize('nativeComponents.expression', "Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as {0} or {1}.", '{', '}'), this.line); + } + + private readName(): string { + const pattern = /[A-Za-z_][\w.:-]*/y; + pattern.lastIndex = this.offset; + const name = pattern.exec(this.source)?.[0] ?? ''; + this.offset += name.length; + return name; + } + + private skipWhitespace(): void { + let end = this.offset; + while (end < this.source.length && /\s/.test(this.source[end])) { + end++; + } + this.advance(end); + } + + /** Moves to `offset`, counting the lines that are passed. */ + private advance(offset: number): void { + for (let index = this.offset; index < offset; index++) { + if (this.source.charCodeAt(index) === 10 /* \n */) { + this.line++; + } + } + this.offset = offset; + } +} + +//#endregion + +//#region Catalogue + +const tones: readonly NativeComponentTone[] = ['neutral', 'positive', 'negative', 'warning']; +const textVariants: readonly NativeTextVariant[] = ['body', 'heading', 'caption']; +const columnAlignments: readonly NativeColumnAlignment[] = ['start', 'end']; + +/** Converts the components that may appear at the top level and inside layout components. */ +const componentConverters = new Map NativeComponent>([ + ['Stack', element => { + checkAttributes(element, []); + return { type: 'stack', children: toChildComponents(element) }; + }], + ['Columns', element => { + checkAttributes(element, []); + return { type: 'columns', children: toChildComponents(element) }; + }], + ['Text', element => { + checkAttributes(element, ['variant']); + return { type: 'text', variant: oneOf(element, 'variant', textVariants), text: requiredText(element) }; + }], + ['Metric', element => { + checkAttributes(element, ['label', 'value', 'delta', 'tone']); + checkEmpty(element); + return { type: 'metric', label: required(element, 'label'), value: required(element, 'value'), delta: element.attributes.get('delta') || undefined, tone: oneOf(element, 'tone', tones) }; + }], + ['Badge', element => { + checkAttributes(element, ['tone']); + return { type: 'badge', text: requiredText(element), tone: oneOf(element, 'tone', tones) }; + }], + ['Table', element => { + checkAttributes(element, ['caption']); + const columns: INativeTableColumn[] = []; + const rows: string[][] = []; + for (const child of childElements(element, ['Column', 'Row'])) { + if (child.name === 'Column') { + if (rows.length > 0) { + throw new MarkupError(localize('nativeComponents.columnAfterRow', "Every \"Column\" of a \"Table\" must come before its first \"Row\"."), child.line); + } + checkAttributes(child, ['align']); + checkNoChildren(child); + columns.push({ header: child.text, align: oneOf(child, 'align', columnAlignments) }); + } else { + checkAttributes(child, []); + const cells = childElements(child, ['Cell']).map(cell => { + checkAttributes(cell, []); + checkNoChildren(cell); + return cell.text; + }); + if (cells.length !== columns.length) { + throw new MarkupError(localize('nativeComponents.cellCount', "The number of cells in this row ({0}) does not match the number of columns ({1}).", cells.length, columns.length), child.line); + } + rows.push(cells); + } + } + checkCount(element, 'Column', columns.length, NativeComponentsLimits.tableColumns); + checkCount(element, 'Row', rows.length, NativeComponentsLimits.tableRows); + return { type: 'table', caption: element.attributes.get('caption') || undefined, columns, rows }; + }], + ['BarChart', element => { + checkAttributes(element, ['title', 'unit']); + const bars = childElements(element, ['Bar']).map((bar): INativeBar => { + checkAttributes(bar, ['label', 'value']); + checkEmpty(bar); + const valueText = required(bar, 'value'); + if (!/^\d+(?:\.\d+)?$/.test(valueText) || !Number.isFinite(Number(valueText))) { + throw new MarkupError(localize('nativeComponents.barValue', "The \"value\" of a \"Bar\" must be a number that is not negative, such as 12.5, without a unit or separators. Found \"{0}\".", valueText), bar.line); + } + return { label: required(bar, 'label'), value: Number(valueText), valueText }; + }); + checkCount(element, 'Bar', bars.length, NativeComponentsLimits.bars); + return { type: 'barChart', title: required(element, 'title'), unit: element.attributes.get('unit') || undefined, bars }; + }], + ['Disclosure', element => { + checkAttributes(element, ['summary']); + return { type: 'disclosure', summary: required(element, 'summary'), children: toChildComponents(element) }; + }], +]); + +/** The components that only have a meaning inside another one. */ +const nestedComponentParents = new Map([['Column', 'Table'], ['Row', 'Table'], ['Cell', 'Row'], ['Bar', 'BarChart']]); + +function toComponents(elements: readonly IMarkupElement[], parent: IMarkupElement | undefined): NativeComponent[] { + return elements.map(element => { + const convert = componentConverters.get(element.name); + if (!convert) { + throw unexpectedElementError(element, parent?.name, [...componentConverters.keys()]); + } + return convert(element); + }); +} + +function toChildComponents(element: IMarkupElement): NativeComponent[] { + checkNoText(element); + if (element.children.length === 0) { + throw new MarkupError(localize('nativeComponents.noChildren', "\"{0}\" needs at least one component inside it.", element.name), element.line); + } + return toComponents(element.children, element); +} + +function childElements(element: IMarkupElement, allowed: readonly string[]): readonly IMarkupElement[] { + checkNoText(element); + for (const child of element.children) { + if (!allowed.includes(child.name)) { + throw unexpectedElementError(child, element.name, allowed); + } + } + return element.children; +} + +function unexpectedElementError(element: IMarkupElement, parent: string | undefined, allowed: readonly string[]): MarkupError { + const expectedParent = nestedComponentParents.get(element.name); + if (expectedParent) { + return new MarkupError(localize('nativeComponents.misplaced', "\"{0}\" is only allowed directly inside \"{1}\".", element.name, expectedParent), element.line); + } + if (componentConverters.has(element.name) && parent) { + return new MarkupError(localize('nativeComponents.notAllowedInside', "\"{0}\" is not allowed inside \"{1}\". Allowed: {2}.", element.name, parent, allowed.join(', ')), element.line); + } + return new MarkupError(localize('nativeComponents.unknownComponent', "Unknown component \"{0}\". Available here: {1}.", element.name, allowed.join(', ')), element.line); +} + +function checkAttributes(element: IMarkupElement, allowed: readonly string[]): void { + for (const name of element.attributes.keys()) { + if (!allowed.includes(name)) { + throw new MarkupError(allowed.length > 0 + ? localize('nativeComponents.unknownAttribute', "Unknown attribute \"{0}\" on \"{1}\". Allowed: {2}.", name, element.name, allowed.join(', ')) + : localize('nativeComponents.noAttributes', "Unknown attribute \"{0}\" on \"{1}\", which has no attributes.", name, element.name), element.line); + } + } +} + +function required(element: IMarkupElement, name: string): string { + const value = element.attributes.get(name); + if (!value) { + throw new MarkupError(localize('nativeComponents.missingAttribute', "\"{0}\" needs a \"{1}\" attribute.", element.name, name), element.line); + } + return value; +} + +/** Reads an attribute that selects one of `values`, the first of which is the default. */ +function oneOf(element: IMarkupElement, name: string, values: readonly T[]): T { + const value = element.attributes.get(name); + if (value === undefined) { + return values[0]; + } + const match = values.find(candidate => candidate === value); + if (match === undefined) { + throw new MarkupError(localize('nativeComponents.invalidValue', "\"{0}\" is not a valid \"{1}\" for \"{2}\". Allowed: {3}.", value, name, element.name, values.join(', ')), element.line); + } + return match; +} + +function requiredText(element: IMarkupElement): string { + checkNoChildren(element); + if (!element.text) { + throw new MarkupError(localize('nativeComponents.missingText', "\"{0}\" needs text between its tags.", element.name), element.line); + } + return element.text; +} + +function checkNoChildren(element: IMarkupElement): void { + if (element.children.length > 0) { + throw new MarkupError(localize('nativeComponents.textOnly', "\"{0}\" can only contain text, but contains \"{1}\".", element.name, element.children[0].name), element.children[0].line); + } +} + +function checkNoText(element: IMarkupElement): void { + if (element.text) { + throw new MarkupError(localize('nativeComponents.unexpectedText', "\"{0}\" cannot contain text. Put text in a \"Text\" component.", element.name), element.textLine); + } +} + +function checkEmpty(element: IMarkupElement): void { + if (element.text || element.children.length > 0) { + throw new MarkupError(localize('nativeComponents.notEmpty', "\"{0}\" cannot have content. Set its attributes instead.", element.name), element.textLine ?? element.children[0].line); + } +} + +function checkCount(element: IMarkupElement, child: string, count: number, limit: number): void { + if (count === 0) { + throw new MarkupError(localize('nativeComponents.missingChild', "\"{0}\" needs at least one \"{1}\".", element.name, child), element.line); + } + if (count > limit) { + throw new MarkupError(localize('nativeComponents.tooManyChildren', "\"{0}\" has {1} \"{2}\" components, which is more than the limit of {3}.", element.name, count, child, limit), element.line); + } +} + +//#endregion diff --git a/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsText.ts b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsText.ts new file mode 100644 index 000000000000..48c75f4b54cf --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/nativeComponents/nativeComponentsText.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../../nls.js'; +import { INativeBar, INativeComponentsDocument, NativeComponent, NativeComponentTone } from './nativeComponents.js'; + +/** The words that convey a tone without color, or `undefined` for the neutral tone. */ +export function getNativeComponentToneLabel(tone: NativeComponentTone): string | undefined { + switch (tone) { + case 'positive': return localize('nativeComponents.tone.positive', "Positive"); + case 'negative': return localize('nativeComponents.tone.negative', "Negative"); + case 'warning': return localize('nativeComponents.tone.warning', "Warning"); + case 'neutral': return undefined; + } +} + +/** The value of a bar as the chart displays it. */ +export function formatNativeBarValue(bar: INativeBar, unit: string | undefined): string { + return unit ? localize('nativeComponents.valueWithUnit', "{0} {1}", bar.valueText, unit) : bar.valueText; +} + +/** + * Describes a block as lines of plain text, in reading order. This is the text alternative of the + * visual, so it states everything that the rendered components show, including what they convey + * through position, icons or color. + */ +export function describeNativeComponents(document: INativeComponentsDocument): string { + const lines: string[] = []; + describeComponents(document.children, lines); + return lines.join('\n'); +} + +function describeComponents(components: readonly NativeComponent[], lines: string[]): void { + for (const component of components) { + switch (component.type) { + case 'stack': + case 'columns': + describeComponents(component.children, lines); + break; + case 'text': + lines.push(component.text); + break; + case 'metric': { + const tone = getNativeComponentToneLabel(component.tone); + const detail = component.delta && tone ? localize('nativeComponents.deltaAndTone', "{0}, {1}", component.delta, tone) : component.delta ?? tone; + lines.push(detail + ? localize('nativeComponents.metricWithDetail', "{0}: {1} ({2})", component.label, component.value, detail) + : localize('nativeComponents.labelAndValue', "{0}: {1}", component.label, component.value)); + break; + } + case 'badge': { + const tone = getNativeComponentToneLabel(component.tone); + lines.push(tone ? localize('nativeComponents.badgeWithTone', "{0} ({1})", component.text, tone) : component.text); + break; + } + case 'table': + lines.push(component.caption ? localize('nativeComponents.tableWithCaption', "Table: {0}", component.caption) : localize('nativeComponents.table', "Table")); + lines.push(component.columns.map(column => column.header).join(' | ')); + for (const row of component.rows) { + lines.push(row.join(' | ')); + } + break; + case 'barChart': + lines.push(localize('nativeComponents.barChart', "Bar chart: {0}", component.title)); + for (const bar of component.bars) { + lines.push(localize('nativeComponents.labelAndValue', "{0}: {1}", bar.label, formatNativeBarValue(bar, component.unit))); + } + break; + case 'disclosure': + lines.push(localize('nativeComponents.disclosure', "Details: {0}", component.summary)); + describeComponents(component.children, lines); + break; + } + } +} diff --git a/src/vs/workbench/contrib/chat/common/plugins/AGENTS_PLUGINS.md b/src/vs/workbench/contrib/chat/common/plugins/AGENTS_PLUGINS.md index 0f75c01a317f..b463c3082a28 100644 --- a/src/vs/workbench/contrib/chat/common/plugins/AGENTS_PLUGINS.md +++ b/src/vs/workbench/contrib/chat/common/plugins/AGENTS_PLUGINS.md @@ -141,7 +141,8 @@ Manages the catalog of available and installed plugins: - **Installed storage** — persists `{ pluginUri, relativePath?, enablementUri?, marketplace, name? }` entries in `agent-plugins/installed.json`. Managed plugins resolve `relativePath` against the current plugin home so moving a portable installation does not invalidate them; external plugins retain absolute URIs. Escaping relative paths fall back to `pluginUri` and are removed or replaced with a valid managed path during migration. Descendant paths preserve plugin-directory casing and use the same casing policy as containment, including on macOS. Legacy entries under the current home and relocated absolute URIs are migrated at startup and after external edits. The store serializes its own file operations and preserves pending local changes instead of publishing stale migration results. Migration uses the file service's existing modification-time and etag checks; detected conflicts are reloaded and rescheduled. This is best-effort protection, not a cross-process transaction: same-size edits, unchanged timestamps, and changes after validation can still be overwritten. A stable `enablementUri` preserves each profile's enablement decisions through `IAgentPluginEnablementService`, including in-window profile switches and after another profile rewrites the shared manifest. Updates that move an installation transfer this identity from its previous recorded URI; a stale update whose source was already removed retains the target's established identity. - **Trust** — marketplace canonical IDs must be explicitly trusted before install proceeds (`chat.plugins.trustedMarketplaces.v1`). - **Auto-update** — checks eligible installed marketplaces approximately every 24 hours and reports their canonical IDs through `marketplacesWithUpdates`. Managed `extraKnownMarketplaces..autoUpdate` values override `extensions.autoUpdate` for that marketplace; undefined entries inherit the global setting. Checks and updates are restricted to enabled marketplaces and still enforce `strictKnownMarketplaces`. -- **GitHub caching** — caches raw GitHub API responses with an 8-hour TTL to avoid repeated fetches. +- **GitHub discovery and caching** — uses the shared anonymous GitHub client, resolving the configured ref (or `main` when omitted) once per discovery and reading definition candidates at that immutable commit. Parsed catalogs retain their 8-hour persisted cache. On a cache miss, ref resolution can revalidate a shared ETag with GitHub; forced refresh bypasses both the catalog cache and ref ETag caching. Raw definition downloads are uncached. Private repositories retain clone-based discovery. +- **GitHub request priority** — user-requested discovery uses the interactive lane. Metadata hydration, recommendation checks, and automatic updates use the background lane for both ref resolution and definition downloads, independently of whether the catalog cache is bypassed. ### Marketplace Definition Files @@ -151,6 +152,8 @@ Checked in order per repository: 3. `.github/plugin/marketplace.json` → `MarketplaceType.Copilot` 4. `.claude-plugin/marketplace.json` → `MarketplaceType.Claude` +The first definition containing a plugins array wins; catalogs from different configured marketplaces are combined. GitHub raw definitions use the shared client's 1 MiB text limit. An oversized response reports a marketplace error rather than selecting a lower-priority definition or falling back to cloning. + ### IPluginInstallService Orchestrates install and update workflows: diff --git a/src/vs/workbench/contrib/chat/common/plugins/agentPluginServiceImpl.ts b/src/vs/workbench/contrib/chat/common/plugins/agentPluginServiceImpl.ts index c970cf401dec..703b321422d0 100644 --- a/src/vs/workbench/contrib/chat/common/plugins/agentPluginServiceImpl.ts +++ b/src/vs/workbench/contrib/chat/common/plugins/agentPluginServiceImpl.ts @@ -1207,7 +1207,7 @@ export class CopilotCliAgentPluginDiscovery extends AbstractAgentPluginDiscovery throw new Error(localize('pluginRuntimeEnablementUnavailable', "Runtime plugin enablement is unavailable.")); } const target = installedPlugin.directSourceId ?? `${installedPlugin.name}@${installedPlugin.marketplace}`; - await this._agentHostService.setPluginEnabled(COPILOT_CLI_AGENT_PROVIDER_ID, target, enabled); + await this._agentHostService.setPluginEnabled(COPILOT_CLI_AGENT_PROVIDER_ID, target, enabled, 'global'); } : undefined, remove: this._agentHostService.uninstallPlugin && canUninstall ? async () => { await this._agentHostService.uninstallPlugin!(COPILOT_CLI_AGENT_PROVIDER_ID, { diff --git a/src/vs/workbench/contrib/chat/common/plugins/marketplaceReference.ts b/src/vs/workbench/contrib/chat/common/plugins/marketplaceReference.ts index e72e18f220c1..cf122b98790e 100644 --- a/src/vs/workbench/contrib/chat/common/plugins/marketplaceReference.ts +++ b/src/vs/workbench/contrib/chat/common/plugins/marketplaceReference.ts @@ -200,7 +200,7 @@ export function deduplicateMarketplaceReferences(primary: readonly IMarketplaceR } export function parseProviderMarketplaceReference(source: string): IMarketplaceReference | undefined { - const labeledSource = /^(?:GitHub|URL):\s+(?.+)$/.exec(source)?.groups?.source; + const labeledSource = /^(?:GitHub|URL):\s*(?.+)$/.exec(source)?.groups?.source; return parseMarketplaceReference(labeledSource ?? source); } diff --git a/src/vs/workbench/contrib/chat/common/plugins/pluginMarketplaceService.ts b/src/vs/workbench/contrib/chat/common/plugins/pluginMarketplaceService.ts index 299dd3382d0b..d79e56703a49 100644 --- a/src/vs/workbench/contrib/chat/common/plugins/pluginMarketplaceService.ts +++ b/src/vs/workbench/contrib/chat/common/plugins/pluginMarketplaceService.ts @@ -10,7 +10,7 @@ import { CancellationError, getErrorMessage, isCancellationError, onUnexpectedEr import { Event } from '../../../../../base/common/event.js'; import { parse as parseJSONC } from '../../../../../base/common/json.js'; import { Lazy } from '../../../../../base/common/lazy.js'; -import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore } from '../../../../../base/common/lifecycle.js'; import { LRUCache } from '../../../../../base/common/map.js'; import { revive } from '../../../../../base/common/marshalling.js'; import { Schemas } from '../../../../../base/common/network.js'; @@ -22,14 +22,17 @@ import { localize } from '../../../../../nls.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IEnvironmentService } from '../../../../../platform/environment/common/environment.js'; import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../platform/files/common/files.js'; +import { toRepositoryRef } from '../../../../../platform/github/common/client/routing.js'; +import { GitHubRequestError } from '../../../../../platform/github/common/githubTypes.js'; +import { RequestError, RequestPriority } from '../../../../../platform/github/common/types.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IMeteredConnectionService } from '../../../../../platform/meteredConnection/common/meteredConnection.js'; import { ObservableMemento, observableMemento } from '../../../../../platform/observable/common/observableMemento.js'; import { COPILOT_STRICT_MARKETPLACES_KEY, IManagedSettingsService } from '../../../../../platform/policy/common/copilotManagedSettings.js'; -import { asJson, IRequestService } from '../../../../../platform/request/common/request.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import type { Dto } from '../../../../services/extensions/common/proxyIdentifier.js'; +import { IWorkbenchGitHubService } from '../../../../services/github/common/githubService.js'; import { AutoUpdateConfigurationKey, IExtensionsWorkbenchService } from '../../../extensions/common/extensions.js'; import { ChatConfiguration } from '../constants.js'; import { customizationSearchMatchesAny } from '../aiCustomizationSearch.js'; @@ -231,6 +234,8 @@ export interface IMarketplaceInstalledPlugin { export interface IFetchMarketplacePluginsOptions { /** Bypass the marketplace caches (HTTP TTL cache and cloned-repository TTL) and re-read from the remote. */ readonly refresh?: boolean; + /** GitHub request priority; omit to use the client's interactive default. */ + readonly priority?: RequestPriority; /** * Called for each marketplace that could not be read. Individual failures * are otherwise swallowed so that one bad marketplace cannot fail the @@ -450,7 +455,7 @@ export class PluginMarketplaceService extends Disposable implements IPluginMarke constructor( @IConfigurationService private readonly _configurationService: IConfigurationService, - @IRequestService private readonly _requestService: IRequestService, + @IWorkbenchGitHubService private readonly _gitHubService: IWorkbenchGitHubService, @IEnvironmentService environmentService: IEnvironmentService, @IFileService private readonly _fileService: IFileService, @IAgentPluginRepositoryService private readonly _pluginRepositoryService: IAgentPluginRepositoryService, @@ -724,31 +729,56 @@ export class PluginMarketplaceService extends Disposable implements IPluginMarke let repoMayBePrivate = true; let readError: Error | undefined; - - const plugins = await this._readPluginsFromDefinitions(reference, async (defPath) => { - if (token.isCancellationRequested) { - return undefined; + const recordReadError = (error: unknown) => { + if (RequestError.isResponseTooLarge(error)) { + repoMayBePrivate = false; + readError = new Error(localize('pluginMarketplace.responseTooLarge', "Unable to read marketplace '{0}': the GitHub response exceeds the size limit.", reference.displayLabel)); + } else if (error instanceof GitHubRequestError && error.statusCode !== undefined) { + const statusCode = error.statusCode; + repoMayBePrivate &&= statusCode >= 400 && statusCode < 500; + if (statusCode >= 500 || RequestError.isRateLimited(error)) { + readError = new Error(localize('pluginMarketplace.httpReadFailed', "Unable to read marketplace '{0}' (HTTP {1}).", reference.displayLabel, statusCode)); + } + } else { + readError = new Error(localize('pluginMarketplace.readFailed', "Unable to read marketplace '{0}'.", reference.displayLabel)); } - const ref = encodeURIComponent(reference.ref ?? 'main'); - const url = `https://raw.githubusercontent.com/${repo}/${ref}/${defPath}`; - try { - const context = await this._requestService.request({ type: 'GET', url, callSite: 'pluginMarketplaceService.fetchPluginList' }, token); - const statusCode = context.res.statusCode; - if (statusCode !== 200) { - repoMayBePrivate &&= statusCode !== undefined && statusCode >= 400 && statusCode < 500; - if (statusCode === undefined || statusCode >= 500 || statusCode === 429) { - readError = new Error(localize('pluginMarketplace.httpReadFailed', "Unable to read marketplace '{0}' (HTTP {1}).", reference.displayLabel, statusCode ?? 'unknown')); + this._logService.debug(`[PluginMarketplaceService] Failed to read marketplace ${reference.rawValue}:`, error); + }; + + let plugins: IMarketplacePlugin[]; + const lifetime = new DisposableStore(); + const signal = CancellationToken.toAbortSignal(token, lifetime); + try { + const client = lifetime.add(await this._gitHubService.acquireAnonymousApiClient(signal)); + const repository = toRepositoryRef(repo); + const commit = await client.content.resolveRef(repository, reference.ref ?? 'main', signal, { caller: 'pluginMarketplaceService.resolveRef', noCache: options?.refresh, priority: options?.priority }); + plugins = await this._readPluginsFromDefinitions(reference, async defPath => { + signal.throwIfAborted(); + try { + const text = await client.content.getRawFile(repository, commit, defPath, signal, { caller: 'pluginMarketplaceService.fetchPluginList', priority: options?.priority }); + const json: IMarketplaceJson | null = JSON.parse(text); + return json ?? undefined; + } catch (error) { + if (signal.aborted || isCancellationError(error) || RequestError.isResponseTooLarge(error)) { + throw error; } - this._logService.debug(`[PluginMarketplaceService] ${url} returned status ${statusCode}, skipping`); + recordReadError(error); return undefined; } - return await asJson(context) ?? undefined; - } catch (err) { - readError = new Error(localize('pluginMarketplace.readFailed', "Unable to read marketplace '{0}'.", reference.displayLabel)); - this._logService.debug(`[PluginMarketplaceService] Failed to fetch marketplace.json from ${url}:`, err); - return undefined; + }); + } catch (error) { + if (signal.aborted || isCancellationError(error)) { + return []; } - }); + recordReadError(error); + plugins = []; + } finally { + lifetime.dispose(); + } + + if (token.isCancellationRequested) { + return []; + } if (plugins.length > 0) { cache.set(reference.canonicalId, { @@ -1002,7 +1032,7 @@ export class PluginMarketplaceService extends Disposable implements IPluginMarke private async _readPluginsForInstalledEntry(reference: IMarketplaceReference, token: CancellationToken): Promise { if (reference.kind === MarketplaceReferenceKind.GitHubShorthand && reference.githubRepo) { - return this._fetchFromGitHubRepo(reference, reference.githubRepo, token); + return this._fetchFromGitHubRepo(reference, reference.githubRepo, token, { priority: 'background' }); } return this._readPluginsFromDirectory(this._pluginRepositoryService.getRepositoryUri(reference), reference, token); @@ -1177,8 +1207,8 @@ export class PluginMarketplaceService extends Disposable implements IPluginMarke } const sourceDescriptor: IPluginSourceDescriptor = reference.kind === MarketplaceReferenceKind.GitHubShorthand - ? { kind: PluginSourceKind.GitHub, repo: reference.githubRepo! } - : { kind: PluginSourceKind.GitUrl, url: reference.cloneUrl }; + ? { kind: PluginSourceKind.GitHub, repo: reference.githubRepo!, ...(reference.ref ? { ref: reference.ref } : {}) } + : { kind: PluginSourceKind.GitUrl, url: reference.cloneUrl, ...(reference.ref ? { ref: reference.ref } : {}) }; const agentManifest = await readAgentPluginManifest(repoDir, this._fileService); if (agentManifest) { return { diff --git a/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptToolResolver.ts b/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptToolResolver.ts index f2e96c8038ca..c5bbb2d61a83 100644 --- a/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptToolResolver.ts +++ b/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptToolResolver.ts @@ -40,16 +40,13 @@ export async function resolveAgentFileTools(target: Target, harnessService: ICus const tools: IAgentFileTool[] = [ ...knownGithubCopilotTools.map(tool => ({ ...tool, availability: 'available' as const, harnessId: 'github-copilot' })), { name: '*', availability: 'available', harnessId: 'github-copilot' }, + ...knownGithubCopilotToolNamespaces.map(tool => ({ ...tool, availability: 'available' as const, harnessId: 'github-copilot' })), ]; - tools.push(...inventories.flatMap((inventory, index) => inventory?.map(tool => ({ + const staticToolNames = new Set(tools.map(tool => tool.name)); + tools.push(...inventories.flatMap((inventory, index) => inventory?.filter(tool => !staticToolNames.has(tool.name)).map(tool => ({ ...tool, harnessId: descriptors[index].id, })) ?? [])); - for (const namespace of knownGithubCopilotToolNamespaces) { - if (!tools.some(tool => tool.name === namespace.name)) { - tools.push({ ...namespace, availability: 'available', harnessId: 'github-copilot' }); - } - } return { tools, isResolved: descriptors.length > 0 && inventories.every(inventory => inventory !== undefined), diff --git a/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptValidator.ts b/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptValidator.ts index 1f141e7da106..64949fb2e293 100644 --- a/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptValidator.ts +++ b/src/vs/workbench/contrib/chat/common/promptSyntax/languageProviders/promptValidator.ts @@ -1049,6 +1049,10 @@ export class PromptValidator { report(toMarker(localize('promptValidator.unknownMatcherProperty', "Unknown property '{0}' in hook matcher.", prop.key.value), prop.key.range, MarkerSeverity.Warning)); } } + const matcherProperty = item.properties.find(p => p.key.value === 'matcher'); + if (matcherProperty) { + this.validateHookMatcher(matcherProperty.value, target, eventName, report); + } if (hooksProperty.value.type !== 'sequence') { report(toMarker(localize('promptValidator.nestedHooksMustBeArray', "The 'hooks' property in a matcher must be an array of command objects."), hooksProperty.value.range, MarkerSeverity.Error)); return; @@ -1122,10 +1126,10 @@ export class PromptValidator { const actionType = typeProperty?.value.type === 'scalar' ? typeProperty.value.value : 'command'; switch (actionType) { case 'command': - this.validateCopilotCommandHook(item, report); + this.validateCopilotCommandHook(item, eventName, report); break; case 'http': - this.validateCopilotHttpHook(item, report); + this.validateCopilotHttpHook(item, eventName, report); break; case 'prompt': this.validateCopilotPromptHook(item, eventName, report); @@ -1135,7 +1139,7 @@ export class PromptValidator { } } - private validateCopilotCommandHook(item: IMapValue, report: (markers: IMarkerData) => void): void { + private validateCopilotCommandHook(item: IMapValue, eventName: string, report: (markers: IMarkerData) => void): void { const shellFields = new Set(['bash', 'powershell', 'command', 'windows', 'linux', 'osx']); const validProperties = new Set(['type', ...shellFields, 'exec', 'args', 'cwd', 'env', 'timeoutSec', 'timeout', 'matcher']); let hasShellCommand = false; @@ -1154,8 +1158,10 @@ export class PromptValidator { this.validateNonEmptyHookString(name, property.value, report); } else if (name === 'args') { this.validateHookStringArray(name, property.value, report); - } else if (name === 'cwd' || name === 'matcher') { + } else if (name === 'cwd') { this.validateHookString(name, property.value, report); + } else if (name === 'matcher') { + this.validateHookMatcher(property.value, Target.GitHubCopilot, eventName, report); } else if (name === 'env') { this.validateHookStringMap(name, property.value, report); } else if (name === 'timeout' || name === 'timeoutSec') { @@ -1170,7 +1176,7 @@ export class PromptValidator { } } - private validateCopilotHttpHook(item: IMapValue, report: (markers: IMarkerData) => void): void { + private validateCopilotHttpHook(item: IMapValue, eventName: string, report: (markers: IMarkerData) => void): void { const validProperties = new Set(['type', 'url', 'headers', 'allowedEnvVars', 'timeoutSec', 'timeout', 'matcher']); const url = item.properties.find(property => property.key.value === 'url'); if (!url) { @@ -1183,7 +1189,7 @@ export class PromptValidator { continue; } if (name === 'url') { - if (property.value.type !== 'scalar' || !/^https?:\/\//i.test(property.value.value)) { + if (property.value.type !== 'scalar' || !isHttpUrl(property.value.value)) { report(toMarker(localize('promptValidator.httpHookUrlInvalid', "The 'url' property in an HTTP hook action must be an HTTP or HTTPS URL."), property.value.range, MarkerSeverity.Error)); } } else if (name === 'headers') { @@ -1191,7 +1197,7 @@ export class PromptValidator { } else if (name === 'allowedEnvVars') { this.validateHookStringArray(name, property.value, report); } else if (name === 'matcher') { - this.validateHookString(name, property.value, report); + this.validateHookMatcher(property.value, Target.GitHubCopilot, eventName, report); } else if (name === 'timeout' || name === 'timeoutSec') { this.validateHookTimeout(name, property.value, report); } @@ -1228,6 +1234,32 @@ export class PromptValidator { } } + private validateHookMatcher(value: IValue, target: Target, eventName: string, report: (markers: IMarkerData) => void): void { + const canonicalEventName = getCanonicalAgentHookName(Target.GitHubCopilot, eventName); + if (target === Target.GitHubCopilot && !['preToolUse', 'postToolUse', 'preMcpToolCall', 'permissionRequest', 'subagentStart', 'preCompact', 'notification'].includes(canonicalEventName ?? '')) { + return; + } + if (value.type !== 'scalar') { + report(toMarker(localize('promptValidator.hookMatcherMustBeString', "The 'matcher' property in a hook must be a string."), value.range, MarkerSeverity.Error)); + return; + } + if (target === Target.GitHubCopilot && value.value.length === 0) { + report(toMarker(localize('promptValidator.hookMatcherMustNotBeEmpty', "The 'matcher' property in a hook must not be empty."), value.range, MarkerSeverity.Error)); + return; + } + // PascalCase aliases use Claude-compatible matchers, including trimmed match-all patterns. + const isCompatibleMatcher = canonicalEventName !== undefined && canonicalEventName !== eventName; + const matcher = isCompatibleMatcher ? value.value.trim() : value.value; + if (isCompatibleMatcher && (matcher.length === 0 || matcher === '*' || matcher === '**')) { + return; + } + try { + new RegExp(`^(?:${matcher})$`); + } catch { + report(toMarker(localize('promptValidator.hookMatcherMustBeValidRegex', "The 'matcher' property in a hook must be a valid regular expression."), value.range, MarkerSeverity.Error)); + } + } + private validateHookStringArray(name: string, value: IValue, report: (markers: IMarkerData) => void): void { if (value.type !== 'sequence') { report(toMarker(localize('promptValidator.hookPropertyMustBeStringArray', "The '{0}' property in a hook action must be an array of strings.", name), value.range, MarkerSeverity.Error)); @@ -1516,9 +1548,15 @@ export class PromptValidator { } case 'command': case 'cwd': + if (property.value.type !== 'scalar') { + report(toMarker(localize('promptValidator.mcpServerPropertyMustBeString', "The '{0}' property for MCP server '{1}' must be a string.", propertyName, name), property.value.range, MarkerSeverity.Error)); + } + break; case 'url': if (property.value.type !== 'scalar') { report(toMarker(localize('promptValidator.mcpServerPropertyMustBeString', "The '{0}' property for MCP server '{1}' must be a string.", propertyName, name), property.value.range, MarkerSeverity.Error)); + } else if (!isHttpUrl(property.value.value)) { + report(toMarker(localize('promptValidator.mcpServerUrlInvalid', "The 'url' property for MCP server '{0}' must be an HTTP or HTTPS URL.", name), property.value.range, MarkerSeverity.Error)); } break; case 'args': @@ -1591,6 +1629,14 @@ function isNullScalar(value: IValue): boolean { return value.type === 'scalar' && value.value === 'null' && value.format === 'none'; } +function isHttpUrl(value: string): boolean { + if (!URL.canParse(value)) { + return false; + } + const url = new URL(value); + return (url.protocol === 'http:' || url.protocol === 'https:') && !!url.hostname; +} + function formatAttributeTypes(types: readonly IValue['type'][], allowNull = false): string { const labels: string[] = types.map(type => { switch (type) { diff --git a/src/vs/workbench/contrib/chat/common/promptSyntax/service/promptsService.ts b/src/vs/workbench/contrib/chat/common/promptSyntax/service/promptsService.ts index cf522ba81fb0..88eaa9803bf0 100644 --- a/src/vs/workbench/contrib/chat/common/promptSyntax/service/promptsService.ts +++ b/src/vs/workbench/contrib/chat/common/promptSyntax/service/promptsService.ts @@ -290,6 +290,12 @@ export interface ICustomAgent { */ readonly uri: URI; + /** + * Original location of an agent that was copied for another host, such as a VS Code agent synced to an Agent Host. + * Provenance checks, like whether an agent is organization-provided, need it because {@link uri} is the copy. + */ + readonly sourceUri?: URI; + /** * Name of the custom agent as used in prompt files or contexts */ diff --git a/src/vs/workbench/contrib/chat/common/tools/builtinTools/chatUrlFetchingConfirmation.ts b/src/vs/workbench/contrib/chat/common/tools/builtinTools/chatUrlFetchingConfirmation.ts index 65123eec0a1c..bf0fc6ce1237 100644 --- a/src/vs/workbench/contrib/chat/common/tools/builtinTools/chatUrlFetchingConfirmation.ts +++ b/src/vs/workbench/contrib/chat/common/tools/builtinTools/chatUrlFetchingConfirmation.ts @@ -9,7 +9,7 @@ import { ResourceMap } from '../../../../../../base/common/map.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { URI } from '../../../../../../base/common/uri.js'; import { localize } from '../../../../../../nls.js'; -import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { IQuickInputButton, IQuickInputService, IQuickTreeItem } from '../../../../../../platform/quickinput/common/quickInput.js'; import { extractUrlPatterns, getPatternLabel, isUrlApproved, IUrlApprovalSettings } from '../../../../../../platform/url/common/urlApprovalPatterns.js'; import { IPreferencesService } from '../../../../../services/preferences/common/preferences.js'; @@ -293,28 +293,68 @@ export class ChatUrlFetchingConfirmationContribution implements ILanguageModelTo } const item: ILanguageModelToolConfirmationContributionQuickTreeItem = { + id: `url/${pattern}`, label, description, buttons: [trashButton], - checked: true, - onDidChangeChecked: (checked) => { - if (checked) { - approvedUrls[pattern] = settings; + // The checkbox controls fetching without asking; response approval is kept as is. + checked: getUrlApproval(settings).request, + onDidChangeChecked: checked => this._updateApprovals((approvals, target) => { + const defaultSettings = this._getDefaultApprovedUrls()[pattern]; + const next = { request: checked, response: getUrlApproval(this._getApprovedUrls()[pattern] ?? settings).response }; + const matchesDefault = target === ConfigurationTarget.USER && (defaultSettings !== undefined + ? getUrlApproval(defaultSettings).request === next.request && getUrlApproval(defaultSettings).response === next.response + : !next.request && !next.response); + if (matchesDefault) { + delete approvals[pattern]; } else { - delete approvedUrls[pattern]; + approvals[pattern] = next.request === next.response ? next.request : { approveRequest: next.request, approveResponse: next.response }; } - - this._configurationService.updateValue(ChatConfiguration.AutoApprovedUrls, approvedUrls); + }, pattern), + onDidTriggerItemButton: button => { + if (button !== trashButton) { + return; + } + return this._updateApprovals(approvals => { + if (this._getDefaultApprovedUrls()[pattern] !== undefined) { + // Default patterns cannot be deleted, so override them instead. + approvals[pattern] = false; + } else { + delete approvals[pattern]; + } + }, pattern); } }; items.push(item); } + items.push({ + pickable: false, + label: localize('addUrlPattern', "Add URL Pattern..."), + onDidOpen: async () => { + const pattern = (await this._quickInputService.input({ + prompt: localize('addUrlPatternPrompt', "Enter a domain or URL pattern to fetch without approval, e.g. example.com or https://example.com/docs/*"), + validateInput: async value => value.trim() ? undefined : localize('urlPatternRequired', "Enter a domain or URL pattern.") + }))?.trim(); + if (!pattern) { + return; + } + await this._updateUserApprovals(approvals => { + const existing = approvals[pattern] ?? this._getDefaultApprovedUrls()[pattern]; + approvals[pattern] = { + approveRequest: true, + approveResponse: typeof existing === 'boolean' ? existing : existing?.approveResponse === true + }; + }); + } + }); + items.push({ pickable: false, label: localize('moreOptionsManage', "More Options..."), description: localize('openSettings', "Open settings"), + closesPicker: true, onDidOpen: () => { this._preferencesService.openUserSettings({ query: ChatConfiguration.AutoApprovedUrls }); } @@ -335,4 +375,35 @@ export class ChatUrlFetchingConfirmationContribution implements ILanguageModelTo ChatConfiguration.AutoApprovedUrls ) || {}; } + + private _getDefaultApprovedUrls(): Readonly> { + return this._configurationService.inspect>(ChatConfiguration.AutoApprovedUrls).defaultValue ?? {}; + } + + /** Edits only the user value, so default patterns are not copied into user settings. */ + private _updateUserApprovals(update: (approvals: Record) => void): Promise { + return this._updateApprovals(update); + } + + private _updateApprovals(update: (approvals: Record, target: ConfigurationTarget) => void, pattern?: string): Promise { + const inspected = this._configurationService.inspect>(ChatConfiguration.AutoApprovedUrls); + let target = ConfigurationTarget.USER; + let value = inspected.userValue; + if (pattern !== undefined && inspected.workspaceFolderValue?.[pattern] !== undefined) { + target = ConfigurationTarget.WORKSPACE_FOLDER; + value = inspected.workspaceFolderValue; + } else if (pattern !== undefined && inspected.workspaceValue?.[pattern] !== undefined) { + target = ConfigurationTarget.WORKSPACE; + value = inspected.workspaceValue; + } + const approvals = { ...value }; + update(approvals, target); + return this._configurationService.updateValue(ChatConfiguration.AutoApprovedUrls, approvals, target); + } +} + +function getUrlApproval(settings: boolean | IUrlApprovalSettings): { readonly request: boolean; readonly response: boolean } { + return typeof settings === 'boolean' + ? { request: settings, response: settings } + : { request: !!settings.approveRequest, response: !!settings.approveResponse }; } diff --git a/src/vs/workbench/contrib/chat/common/tools/builtinTools/tools.ts b/src/vs/workbench/contrib/chat/common/tools/builtinTools/tools.ts index 4a711c404fa5..bddc2e7bb817 100644 --- a/src/vs/workbench/contrib/chat/common/tools/builtinTools/tools.ts +++ b/src/vs/workbench/contrib/chat/common/tools/builtinTools/tools.ts @@ -8,8 +8,10 @@ import { IConfigurationService } from '../../../../../../platform/configuration/ import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { IWorkbenchContribution } from '../../../../../common/contributions.js'; import { ChatConfiguration } from '../../constants.js'; +import { ILanguageModelToolsConfirmationService } from '../languageModelToolsConfirmationService.js'; import { ILanguageModelToolsService } from '../languageModelToolsService.js'; import { AskQuestionsTool, AskQuestionsToolData } from './askQuestionsTool.js'; +import { ChatUrlFetchingConfirmationContribution } from './chatUrlFetchingConfirmation.js'; import { ConfirmationTool, ConfirmationToolData, ConfirmationToolWithOptionsData, ModifiedFilesConfirmationTool, ModifiedFilesConfirmationToolData } from './confirmationTool.js'; import { EditTool, EditToolData } from './editFileTool.js'; import { createManageTodoListToolData, ManageTodoListTool } from './manageTodoListTool.js'; @@ -25,11 +27,20 @@ export class BuiltinToolsContribution extends Disposable implements IWorkbenchCo constructor( @ILanguageModelToolsService toolsService: ILanguageModelToolsService, + @ILanguageModelToolsConfirmationService confirmationService: ILanguageModelToolsConfirmationService, @IInstantiationService instantiationService: IInstantiationService, @IConfigurationService configurationService: IConfigurationService, ) { super(); + this._register(confirmationService.registerConfirmationContribution( + InternalFetchWebPageToolId, + instantiationService.createInstance( + ChatUrlFetchingConfirmationContribution, + params => (params as { urls?: string[] }).urls + ) + )); + const editTool = instantiationService.createInstance(EditTool); this._register(toolsService.registerTool(EditToolData, editTool)); diff --git a/src/vs/workbench/contrib/chat/common/tools/languageModelToolsConfirmationService.ts b/src/vs/workbench/contrib/chat/common/tools/languageModelToolsConfirmationService.ts index c0925fa3129b..1ba82f2a7c66 100644 --- a/src/vs/workbench/contrib/chat/common/tools/languageModelToolsConfirmationService.ts +++ b/src/vs/workbench/contrib/chat/common/tools/languageModelToolsConfirmationService.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { IDisposable } from '../../../../../base/common/lifecycle.js'; +import { IObservable } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; import { IQuickInputButton, IQuickTreeItem } from '../../../../../platform/quickinput/common/quickInput.js'; @@ -68,9 +69,11 @@ export interface ILanguageModelToolConfirmationActionProducer { } export interface ILanguageModelToolConfirmationContributionQuickTreeItem extends IQuickTreeItem { - onDidTriggerItemButton?(button: IQuickInputButton): void; - onDidChangeChecked?(checked: boolean): void; + onDidTriggerItemButton?(button: IQuickInputButton): void | Promise; + onDidChangeChecked?(checked: boolean): void | Promise; onDidOpen?(): void | Promise; + /** Leaves the picker closed after {@link onDidOpen} instead of reopening it, e.g. when opening another editor. */ + closesPicker?: boolean; } /** @@ -80,7 +83,7 @@ export interface ILanguageModelToolConfirmationContributionQuickTreeItem extends export type ILanguageModelToolConfirmationContribution = Partial & { /** * Gets items to be shown in the `manageConfirmationPreferences` quick tree. - * These are added under the tool's category. + * These are added under the tool's category; unchecked items remain visible until the picker closes so they can be rechecked. */ getManageActions?(): ILanguageModelToolConfirmationContributionQuickTreeItem[]; @@ -96,6 +99,22 @@ export type ILanguageModelToolConfirmationContribution = Partial; + /** Whether tool discovery is running, shown as a busy state in the manage quick tree. */ + readonly isDiscovering?: IObservable; + isServerApproved(serverId: string): boolean; + setServerApproved(serverId: string, approved: boolean): void; + isToolApproved(tool: IToolData): boolean; + setToolApproved(tool: IToolData, approved: boolean): void; +} + /** * Handles language model tool confirmation. * @@ -113,7 +132,7 @@ export interface ILanguageModelToolsConfirmationService extends ILanguageModelTo readonly _serviceBrand: undefined; /** Opens an IQuickTree to let the user manage their preferences. */ - manageConfirmationPreferences(tools: readonly IToolData[], options?: { defaultScope?: 'workspace' | 'profile' | 'session'; focusToolId?: string }): void; + manageConfirmationPreferences(tools: readonly IToolData[], options?: { defaultScope?: 'workspace' | 'profile' | 'session'; focusToolId?: string; preApprovalStore?: IToolPreApprovalStore }): void; /** * Registers a contribution that provides more specific confirmation logic diff --git a/src/vs/workbench/contrib/chat/common/tools/toolInvocationSummary.ts b/src/vs/workbench/contrib/chat/common/tools/toolInvocationSummary.ts index c623cc5de972..627175acf707 100644 --- a/src/vs/workbench/contrib/chat/common/tools/toolInvocationSummary.ts +++ b/src/vs/workbench/contrib/chat/common/tools/toolInvocationSummary.ts @@ -27,8 +27,11 @@ export function getToolInvocationSummary(invocation: IChatToolInvocation | IChat return invocation.summary; } -/** Called at the agent-host boundary after validating native tool provenance and successful completion. */ -export function getToolInvocationSummaryFromInput(toolId: string, input: unknown, mapResource: (uri: URI) => URI = uri => uri): ChatToolInvocationSummary | undefined { +/** + * Called at the agent-host boundary after validating native tool provenance and successful completion. + * `viewedResourceType` is what the host reports the path of a `view` call named, when it knows. + */ +export function getToolInvocationSummaryFromInput(toolId: string, input: unknown, mapResource: (uri: URI) => URI = uri => uri, viewedResourceType?: 'file' | 'directory'): ChatToolInvocationSummary | undefined { const resource = (value: unknown): IChatToolSummaryResource | undefined => { if (typeof value !== 'string' || !value) { return undefined; @@ -58,10 +61,17 @@ export function getToolInvocationSummaryFromInput(toolId: string, input: unknown } case 'view': { const target = file(); + if (!target) { + return undefined; + } + // The tool also lists directories. A host that does not say which the path named leaves a line range as the only sign of a file. + if (viewedResourceType === 'directory') { + return { kind: 'list', resources: [target] }; + } const viewRange = getProperty(input, 'view_range'); - return target && Array.isArray(viewRange) && viewRange.length === 2 && Number.isSafeInteger(viewRange[0]) && viewRange[0] > 0 - && Number.isSafeInteger(viewRange[1]) && (viewRange[1] === -1 || viewRange[1] >= viewRange[0]) - ? { kind: 'read', resources: [target] } : undefined; + const hasLineRange = Array.isArray(viewRange) && viewRange.length === 2 && Number.isSafeInteger(viewRange[0]) && viewRange[0] > 0 + && Number.isSafeInteger(viewRange[1]) && (viewRange[1] === -1 || viewRange[1] >= viewRange[0]); + return viewedResourceType === 'file' || hasLineRange ? { kind: 'read', resources: [target] } : undefined; } case 'copilot_findTextInFiles': case 'grep_search': diff --git a/src/vs/workbench/contrib/chat/common/widget/codeFence.ts b/src/vs/workbench/contrib/chat/common/widget/codeFence.ts new file mode 100644 index 000000000000..2f03bd083272 --- /dev/null +++ b/src/vs/workbench/contrib/chat/common/widget/codeFence.ts @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Returns the info string of a fenced code block whose closing fence has arrived, or `undefined` + * while the block is still open. `raw` is the Markdown source of the block, including its fences. + */ +export function getClosedCodeFenceInfo(raw: string | undefined): string | undefined { + if (!raw) { + return undefined; + } + + const opening = /^ {0,3}(?`{3,}|~{3,})(?[^\n]*)/.exec(raw)?.groups; + const closing = /\n {0,3}(?`{3,}|~{3,}) *(?:\r?\n)*$/.exec(raw)?.groups?.fence; + if (!opening || !closing || closing.length < opening.fence.length || closing[0] !== opening.fence[0]) { + return undefined; + } + return opening.info.trim(); +} diff --git a/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotActions.ts b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotActions.ts new file mode 100644 index 000000000000..83c395b965c9 --- /dev/null +++ b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotActions.ts @@ -0,0 +1,445 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getWindow } from '../../../../../base/browser/dom.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { raceTimeout } from '../../../../../base/common/async.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Event } from '../../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { autorun } from '../../../../../base/common/observable.js'; +import { StopWatch } from '../../../../../base/common/stopwatch.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { generateUuid } from '../../../../../base/common/uuid.js'; +import { localize, localize2 } from '../../../../../nls.js'; +import { Action2, registerAction2 } from '../../../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { ContextKeyExpr, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { FocusMode } from '../../../../../platform/native/common/native.js'; +import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; +import { observableConfigValue } from '../../../../../platform/observable/common/platformObservableUtils.js'; +import product from '../../../../../platform/product/common/product.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../common/contributions.js'; +import { IHostService } from '../../../../services/host/browser/host.js'; +import { getScreenshotToolImageData, IScreenshotToolImage, IScreenshotToolService, ScreenshotToolEntryPoint, ScreenshotToolOutcome } from '../../../screenshotTool/browser/screenshotTool.js'; +import { AppWindowScreenshotPermission, AppWindowScreenshotResult, getAppWindowLabel, IAppWindowScreenshotService } from '../../../screenshotTool/electron-browser/appWindowScreenshot.js'; +import { CHAT_CATEGORY } from '../../browser/actions/chatActions.js'; +import { IChatContextPickService, IChatContextValueItem } from '../../browser/attachments/chatContextPickService.js'; +import { IChatWidget, IChatWidgetService, IQuickChatService } from '../../browser/chat.js'; +import { ChatWidget, IChatWidgetContrib, isQuickChat } from '../../browser/widget/chatWidget.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; +import { IChatRequestVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import { ATTACH_APP_WINDOW_SCREENSHOT_COMMAND_ID, ChatAgentLocation, ChatConfiguration } from '../../common/constants.js'; +import { isAutoLanguageModel } from '../../common/languageModels.js'; +import { AppWindowScreenshotHint } from './chatAppWindowScreenshotHint.js'; +import { AppWindowScreenshotSetupDialog } from './chatAppWindowScreenshotSetup.js'; + +const ATTACH_APP_WINDOW_SCREENSHOT_TITLE = localize2('chat.attachAppWindowScreenshot', "Attach Screenshot of App Window"); +const PICK_APP_WINDOW_SCREENSHOT_COMMAND_ID = 'workbench.action.chat.pickAppWindowScreenshot'; + +/** How long a capture waits for the chat input to load its session before it gives up attaching the screenshot. */ +const VIEW_MODEL_TIMEOUT = 10000; + +const AppWindowScreenshotsEnabled = ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.equals(`config.${ChatConfiguration.AppWindowScreenshotsEnabled}`, true)); + +Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ + id: 'chatSidebar', + title: localize('chatConfigurationTitle', "Chat"), + type: 'object', + properties: { + [ChatConfiguration.AppWindowScreenshotsEnabled]: { + type: 'boolean', + default: product.quality !== 'stable', + tags: ['experimental'], + experiment: { mode: 'auto' }, + markdownDescription: localize('chat.appWindowScreenshots.enabled', "Controls whether chat can attach a screenshot of the window of another app, such as the browser or simulator that runs the app that you are building. **Attach Screenshot of App Window** captures the window that you are using or just left, and you can mark up the screenshot before you send it. Its keybinding also works while the other app is in front."), + }, + }, +}); + +/** What started a capture, as reported in telemetry. */ +type AppWindowScreenshotSource = 'command' | 'addContext'; + +type AppWindowScreenshotEvent = { + source: AppWindowScreenshotSource; + target: string; + result: string; + permission: string; + inBackground: boolean; +}; + +type AppWindowScreenshotClassification = { + owner: 'Giuspepe'; + comment: 'Reports how attaching a screenshot of the window of another app to chat ended, to learn how the window is found and why captures fail.'; + source: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'What started the capture: a command, such as from its keybinding, or the Add Context item.' }; + target: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'How the window was found: the frontmost window of another app, picked by the user in a list or in the system picker, or none when the setup showed instead.' }; + result: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'How it ended: captured, cancelled, no window of another app, missing Screen Recording permission (the setup showed), or failed.' }; + permission: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether capturing had the permission that it needs when it started: granted, not granted or restricted on macOS, or not required on other platforms.' }; + inBackground: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether VS Code was in the background when the capture started, as with a system-wide keybinding.' }; +}; + +interface IAppWindowScreenshotRequest { + readonly source: AppWindowScreenshotSource; + /** Lets the user pick the window in a list. */ + readonly pick?: boolean; + /** The session of the chat to attach the screenshot to, instead of the chat that had focus last. */ + readonly sessionResource?: URI; +} + +/** The arguments of Attach Screenshot of App Window, for callers that know which chat to attach the screenshot to. */ +interface IAttachAppWindowScreenshotArgs { + readonly sessionResource: URI; +} + +function isAttachAppWindowScreenshotArgs(args: unknown): args is IAttachAppWindowScreenshotArgs { + return typeof args === 'object' && args !== null && URI.isUri((args as Partial).sessionResource); +} + +/** A screenshot of the window of another app, as an attachment that the user can mark up. */ +interface IAppWindowScreenshot { + readonly entry: IChatRequestVariableEntry; + readonly image: IScreenshotToolImage; +} + +/** + * Captures the window of another app for chat. When macOS doesn't allow Screen Recording, it shows the setup instead. + * Explains why a capture failed. When it captured, the caller ends the feedback of the capture, see + * {@link IAppWindowScreenshotService.endCaptureFeedback}. + */ +async function captureAppWindowScreenshot(accessor: ServicesAccessor, request: IAppWindowScreenshotRequest): Promise { + const appWindowScreenshotService = accessor.get(IAppWindowScreenshotService); + const screenshotToolService = accessor.get(IScreenshotToolService); + const hostService = accessor.get(IHostService); + const notificationService = accessor.get(INotificationService); + const commandService = accessor.get(ICommandService); + const telemetryService = accessor.get(ITelemetryService); + const instantiationService = accessor.get(IInstantiationService); + const contextKeyService = accessor.get(IContextKeyService); + + // A system-wide keybinding runs the command without checking its precondition. + if (!contextKeyService.contextMatchesRules(AppWindowScreenshotsEnabled)) { + return undefined; + } + + const stopWatch = StopWatch.create(false); + // A system-wide keybinding runs the command while another app is in front. + const inBackground = !hostService.hasFocus; + const permission = await appWindowScreenshotService.getPermission(); + const log = (target: string, result: string, outcome: ScreenshotToolOutcome) => { + screenshotToolService.logCapture({ entryPoint: ScreenshotToolEntryPoint.ChatAppWindow, outcome, mode: outcome === 'attached' ? 'appWindow' : 'none', durationMs: stopWatch.elapsed() }); + telemetryService.publicLog2('screenshotTool.appWindow', { source: request.source, target, result, permission, inBackground }); + }; + + if (permission === 'notGranted' || permission === 'restricted') { + log('none', 'permissionRequired', 'cancelled'); + await instantiationService.invokeFunction(showAppWindowScreenshotSetup, permission, inBackground); + return undefined; + } + + const result: AppWindowScreenshotResult = await appWindowScreenshotService.capture({ pick: request.pick }); + if (result.kind === 'captured') { + const label = getAppWindowLabel(result.window); + const { data, mimeType } = getScreenshotToolImageData(result.image); + const entry: IChatRequestVariableEntry = { + id: generateUuid(), + kind: 'image', + name: label, + fullName: localize('appWindowScreenshot.fullName', "Screenshot of {0}", label), + value: data.buffer, + mimeType, + }; + screenshotToolService.registerEditableAttachment(entry, { original: result.image, annotationState: undefined }); + log(result.target, result.kind, 'attached'); + return { entry, image: result.image }; + } + + void appWindowScreenshotService.endCaptureFeedback(); + log(result.target, result.kind, result.kind === 'cancelled' ? 'cancelled' : 'failed'); + if (result.kind === 'noWindow') { + notificationService.info(localize('appWindowScreenshot.noWindow', "No other app shows a window to capture. Open the app, then try again.")); + } else if (result.kind === 'permissionRequired') { + // macOS revoked the permission after it was checked. + const current = await appWindowScreenshotService.getPermission(); + await instantiationService.invokeFunction(showAppWindowScreenshotSetup, current === 'restricted' ? 'restricted' : 'notGranted', inBackground); + } else if (result.kind === 'failed') { + notificationService.prompt( + Severity.Error, + result.window + ? localize('appWindowScreenshot.failedWindow', "The window \"{0}\" could not be captured.", getAppWindowLabel(result.window)) + : localize('appWindowScreenshot.failed', "The windows of other apps could not be listed."), + [{ + label: localize('appWindowScreenshot.pickWindow', "Pick a Window..."), + run: () => { void commandService.executeCommand(PICK_APP_WINDOW_SCREENSHOT_COMMAND_ID); }, + }], + ); + } + return undefined; +} + +/** The setup that shows in this window, so that pressing the keybinding again doesn't open another one. */ +let shownSetup: Promise | undefined; + +/** Shows the setup, while macOS doesn't allow Screen Recording, which lets the user allow it. Resolves once the setup closed. */ +async function showAppWindowScreenshotSetup(accessor: ServicesAccessor, permission: AppWindowScreenshotPermission, inBackground: boolean): Promise { + const hostService = accessor.get(IHostService); + const instantiationService = accessor.get(IInstantiationService); + + if (inBackground) { + // The setup shows in VS Code, which a system-wide keybinding leaves in the background. + await hostService.focus(mainWindow, { mode: FocusMode.Force }); + } + if (shownSetup) { + return shownSetup; + } + + const dialog = instantiationService.createInstance(AppWindowScreenshotSetupDialog, permission); + shownSetup = (async () => { + try { + await dialog.show(); + } finally { + dialog.dispose(); + shownSetup = undefined; + } + })(); + return shownSetup; +} + +/** + * Captures the window of another app and attaches it to the chat that the request names, or else the chat input that + * was in use, or to the one that comes to the front when that chat isn't shown anymore. + */ +async function attachAppWindowScreenshot(accessor: ServicesAccessor, request: IAppWindowScreenshotRequest): Promise { + const chatWidgetService = accessor.get(IChatWidgetService); + const hostService = accessor.get(IHostService); + const notificationService = accessor.get(INotificationService); + const instantiationService = accessor.get(IInstantiationService); + const contextKeyService = accessor.get(IContextKeyService); + const appWindowScreenshotService = accessor.get(IAppWindowScreenshotService); + const quickChatService = accessor.get(IQuickChatService); + + // A system-wide keybinding runs the command without checking its precondition. + if (!contextKeyService.contextMatchesRules(AppWindowScreenshotsEnabled)) { + return; + } + const inBackground = !hostService.hasFocus; + const chatInUse = request.sessionResource ? chatWidgetService.getWidgetBySessionResource(request.sessionResource) : chatWidgetService.lastFocusedWidget; + if (chatInUse && !chatInUse.attachmentCapabilities.supportsImageAttachments) { + notificationService.info(localize('appWindowScreenshot.noImages', "This chat does not accept images.")); + return; + } + const sessionInUse = request.sessionResource ?? chatInUse?.viewModel?.sessionResource; + + // Captures before VS Code comes to the front, which would change which window is in front. + const screenshot = await instantiationService.invokeFunction(captureAppWindowScreenshot, request); + // Quick Chat can't be revealed like other chats, and the list of windows to pick from takes its place, so it opens + // again, also when the user cancelled picking a window. + if (chatInUse && isQuickChat(chatInUse) && (screenshot || request.pick)) { + quickChatService.open(); + } + if (!screenshot) { + return; + } + + try { + // The user can switch chats while picking the window. + let widget = sessionInUse ? chatWidgetService.getWidgetBySessionResource(sessionInUse) : undefined; + let focused: Promise | undefined; + if (widget?.visible && widget.viewModel && isEqual(widget.viewModel.sessionResource, sessionInUse)) { + // The chat shows already, so the screenshot flies into it at once, while VS Code comes to the front under the screenshot. + if (inBackground) { + focused = hostService.focus(getWindow(widget.domNode), { mode: FocusMode.Force }); + } + } else { + // VS Code comes to the front first, as a window behind other apps doesn't render the chat that it reveals. + if (inBackground) { + await hostService.focus(chatInUse ? getWindow(chatInUse.domNode) : mainWindow, { mode: FocusMode.Force }); + } + if (widget && isEqual(widget.viewModel?.sessionResource, sessionInUse)) { + await chatWidgetService.reveal(widget); + } else { + widget = await chatWidgetService.revealWidget() ?? chatWidgetService.lastFocusedWidget; + } + // The chat input drops the attachments that it got before its session loaded. + if (widget && !widget.viewModel) { + const viewModelChange = Event.toPromise(widget.onDidChangeViewModel); + await raceTimeout(viewModelChange, VIEW_MODEL_TIMEOUT); + viewModelChange.cancel(); + } + if (!widget?.viewModel) { + return; + } + // The chat can be in another window, which also comes to the front, so that the screenshot flies into it. + if (inBackground) { + await hostService.focus(getWindow(widget.domNode), { mode: FocusMode.Force }); + } + } + widget.attachmentModel.addContext(screenshot.entry); + // The input renders the attachment at once, which shows once the screenshot covers it. + const attachment = widget.inputPart.getAttachmentElement(screenshot.entry.id); + attachment?.style.setProperty('visibility', 'hidden'); + try { + await appWindowScreenshotService.endCaptureFeedback({ element: attachment ?? widget.inputPart.inputContainerElement ?? widget.inputPart.element, image: screenshot.image }); + } finally { + attachment?.style.removeProperty('visibility'); + } + await focused; + widget.focusInput(); + status(localize('appWindowScreenshot.attached', "Attached a screenshot of {0}.", screenshot.entry.name)); + } finally { + void appWindowScreenshotService.endCaptureFeedback(); + } +} + +class AttachAppWindowScreenshotAction extends Action2 { + + constructor() { + super({ + id: ATTACH_APP_WINDOW_SCREENSHOT_COMMAND_ID, + title: ATTACH_APP_WINDOW_SCREENSHOT_TITLE, + metadata: { + description: localize2('chat.attachAppWindowScreenshot.description', "Attaches a screenshot of the window of another app to chat: the window that you are using, or the one that you just left."), + }, + category: CHAT_CATEGORY, + f1: true, + precondition: AppWindowScreenshotsEnabled, + keybinding: { + weight: KeybindingWeight.WorkbenchContrib, + primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.KeyS, + mac: { primary: KeyMod.WinCtrl | KeyMod.CtrlCmd | KeyCode.KeyS }, + // Captures the window of the app that is in front, which is the point of the keybinding. + systemWide: true, + }, + }); + } + + run(accessor: ServicesAccessor, args?: unknown): Promise { + return attachAppWindowScreenshot(accessor, { source: 'command', sessionResource: isAttachAppWindowScreenshotArgs(args) ? args.sessionResource : undefined }); + } +} + +class PickAppWindowScreenshotAction extends Action2 { + + constructor() { + super({ + id: PICK_APP_WINDOW_SCREENSHOT_COMMAND_ID, + title: localize2('chat.pickAppWindowScreenshot', "Pick App Window to Screenshot..."), + category: CHAT_CATEGORY, + f1: true, + precondition: AppWindowScreenshotsEnabled, + }); + } + + run(accessor: ServicesAccessor): Promise { + return attachAppWindowScreenshot(accessor, { source: 'command', pick: true }); + } +} + +/** The Add Context item, which lets the user pick the window to capture, as Pick App Window to Screenshot does. */ +class AppWindowScreenshotContextValuePick implements IChatContextValueItem { + + readonly type = 'valuePick'; + readonly icon = Codicon.deviceCamera; + readonly label = localize('chatContext.appWindowScreenshot', "Screenshot App Window..."); + readonly commandId = PICK_APP_WINDOW_SCREENSHOT_COMMAND_ID; + + constructor( + @IInstantiationService private readonly instantiationService: IInstantiationService, + ) { } + + async isEnabled(widget: IChatWidget): Promise { + const model = widget.input.selectedLanguageModel.get(); + // An automatically selected model can pick one that sees images, as the image pills assume. + return !!widget.attachmentCapabilities.supportsImageAttachments && (isAutoLanguageModel(model) || !!model?.metadata.capabilities?.vision); + } + + /** Attaches the screenshot to this chat itself, so that it shrinks into its attachment, and returns nothing to attach. */ + async asAttachment(widget: IChatWidget): Promise { + await this.instantiationService.invokeFunction(attachAppWindowScreenshot, { source: 'addContext', pick: true, sessionResource: widget.viewModel?.sessionResource }); + return undefined; + } +} + +/** Offers the Add Context item while the feature is on. */ +class AppWindowScreenshotContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.chat.appWindowScreenshot'; + + constructor( + @IChatContextPickService contextPickService: IChatContextPickService, + @IInstantiationService instantiationService: IInstantiationService, + @IConfigurationService configurationService: IConfigurationService, + ) { + super(); + const enabled = observableConfigValue(ChatConfiguration.AppWindowScreenshotsEnabled, false, configurationService); + this._register(autorun(reader => { + if (enabled.read(reader)) { + reader.store.add(contextPickService.registerChatContextItem(instantiationService.createInstance(AppWindowScreenshotContextValuePick))); + } + })); + } +} + +/** Shows {@link AppWindowScreenshotHint} above the main input of a chat widget, while the feature is on. */ +class AppWindowScreenshotHintContribution extends Disposable implements IChatWidgetContrib { + + static readonly ID = 'chatAppWindowScreenshotHint'; + + readonly id = AppWindowScreenshotHintContribution.ID; + + constructor( + widget: IChatWidget, + @IInstantiationService instantiationService: IInstantiationService, + @IContextKeyService contextKeyService: IContextKeyService, + @ICommandService commandService: ICommandService, + @IConfigurationService configurationService: IConfigurationService, + ) { + super(); + + const input = widget.inputPart; + const enabled = observableConfigValue(ChatConfiguration.AppWindowScreenshotsEnabled, false, configurationService); + this._register(autorun(reader => { + if (!enabled.read(reader)) { + return; + } + reader.store.add(instantiationService.createInstance(AppWindowScreenshotHint, { + inputUri: input.inputUri, + noticeHost: input.noticeHost, + container: input.attachmentHintContainerElement, + getAttachmentIds: () => input.attachmentModel.attachments.map(attachment => attachment.id), + onDidChangeAttachments: input.attachmentModel.onDidChange, + onDidChangeDraft: Event.any(widget.onDidAcceptInput, widget.onDidChangeViewModel), + canAttachScreenshots: () => { + const model = input.selectedLanguageModel.read(undefined); + return widget.location === ChatAgentLocation.Chat + && !!widget.attachmentCapabilities.supportsImageAttachments + && (isAutoLanguageModel(model) || !!model?.metadata.capabilities?.vision) + && contextKeyService.contextMatchesRules(ChatContextKeys.enabled); + }, + }, { + id: ATTACH_APP_WINDOW_SCREENSHOT_COMMAND_ID, + title: ATTACH_APP_WINDOW_SCREENSHOT_TITLE.value, + // Attaches to the chat that shows the hint, which need not be the chat that had focus last. + run: () => { + const sessionResource = widget.viewModel?.sessionResource; + void commandService.executeCommand(ATTACH_APP_WINDOW_SCREENSHOT_COMMAND_ID, sessionResource ? { sessionResource } satisfies IAttachAppWindowScreenshotArgs : undefined); + }, + })); + })); + } +} + +registerAction2(AttachAppWindowScreenshotAction); +registerAction2(PickAppWindowScreenshotAction); +registerWorkbenchContribution2(AppWindowScreenshotContribution.ID, AppWindowScreenshotContribution, WorkbenchPhase.AfterRestored); +ChatWidget.CONTRIBS.push(AppWindowScreenshotHintContribution); diff --git a/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotHint.ts b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotHint.ts new file mode 100644 index 000000000000..3864dce60f01 --- /dev/null +++ b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotHint.ts @@ -0,0 +1,363 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../media/chatAppWindowScreenshotHint.css'; +import { $, append, clearNode } from '../../../../../base/browser/dom.js'; +import { renderAsPlaintext } from '../../../../../base/browser/markdownRenderer.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Event } from '../../../../../base/common/event.js'; +import { escapeMarkdownSyntaxTokens, MarkdownString } from '../../../../../base/common/htmlContent.js'; +import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { generateUuid } from '../../../../../base/common/uuid.js'; +import { localize } from '../../../../../nls.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { IMarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js'; +import { IStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; +import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/accessibilityConfiguration.js'; +import { selectSystemWideKeybindings } from '../../../keybindings/electron-browser/systemWideKeybindings.js'; +import { IAppWindowScreenshotService } from '../../../screenshotTool/electron-browser/appWindowScreenshot.js'; +import { ChatImageAttachGesture, IChatUserImageAttachmentEvent, IChatUserImageAttachmentService } from '../../browser/attachments/chatUserImageAttachments.js'; +import { ChatInputNoticeHost, ChatInputNoticeLane } from '../../browser/widget/input/chatInputNoticeHost.js'; +import { ChatInputNoticeVariant, ChatInputNoticeWidget } from '../../browser/widget/input/chatInputNoticeWidget.js'; +import { ChatInputStackSlot, setChatInputStackSlot } from '../../browser/widget/input/chatInputStack.js'; +import { ChatConfiguration } from '../../common/constants.js'; + +/** Remembers that the hint showed, in VS Code or in the Agents window, as it only shows once. */ +const HINT_SHOWN_STORAGE_KEY = 'chat.appWindowScreenshots.hintShown'; + +/** Turns off chat tips, which the hint is one of. */ +const TIPS_ENABLED_SETTING = 'chat.tips.enabled'; + +/** Which instructions the hint gives: press the keybinding in chat, press it in the other app, or run the command. */ +type AppWindowScreenshotHintCopy = 'inApp' | 'systemWide' | 'palette' | 'none'; + +type AppWindowScreenshotHintAction = 'opportunity' | 'shown' | 'clicked' | 'dismissed' | 'expired' | 'used'; + +type AppWindowScreenshotHintEvent = { + action: AppWindowScreenshotHintAction; + gesture: ChatImageAttachGesture; + copy: AppWindowScreenshotHintCopy; + imageCount: number; + durationMs: number; +}; + +type AppWindowScreenshotHintClassification = { + owner: 'Giuspepe'; + comment: 'Reports the hint that suggests attaching a screenshot of an app window when the user pastes or drops an image into chat, to learn whether it teaches the keybinding.'; + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'What happened: the user pasted or dropped an image where the hint could show, logged once per chat input while the feature and tips are on; the hint showed; the user clicked its link, which runs the command; the user dismissed it; it went away with its images or the draft; or the user captured an app window while it showed.' }; + gesture: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the user pasted or dropped the image.' }; + copy: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Which instructions the hint gave: press the keybinding in chat, press it while the other app is in front, run the command from the Command Palette, or none when it did not show.' }; + imageCount: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'How many images the paste or drop attached, or the hint is about.' }; + durationMs: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'How long ago the hint first showed, in milliseconds, or -1 when it did not show.' }; +}; + +/** The chat input that the hint shows above. */ +export interface IAppWindowScreenshotHintTarget { + /** Names the input in the events of {@link IChatUserImageAttachmentService}. */ + readonly inputUri: URI; + readonly noticeHost: ChatInputNoticeHost; + /** The slot that the hint renders into. */ + readonly container: HTMLElement; + getAttachmentIds(): readonly string[]; + readonly onDidChangeAttachments: Event; + /** Fires when the draft goes away, as the user sends it or the input moves to another session. */ + readonly onDidChangeDraft: Event; + /** Whether the input could take a screenshot of an app window, whether or not the feature is on. */ + canAttachScreenshots(): boolean; +} + +/** The command that the hint suggests, which attaches a screenshot of an app window. */ +export interface IAppWindowScreenshotHintCommand { + readonly id: string; + /** The title that the Command Palette shows. */ + readonly title: string; + /** Runs the command for the chat that shows the hint, as the hint's link does. */ + run(): void; +} + +/** + * Suggests the keybinding of Attach Screenshot of App Window once, right after the user pastes or drops an image into + * the chat input, which is how they attach a screenshot by hand. It shows as a tip above the input, which yields to + * every other notice, and goes away with its images or with the draft. The keybinding in it is a link that runs the + * command, which captures the window, or opens the setup while macOS doesn't allow Screen Recording. + */ +export class AppWindowScreenshotHint extends Disposable { + + /** Holds the tip lane from the paste or drop until the hint goes away. */ + private readonly _claim = this._register(new MutableDisposable()); + private readonly _content = this._register(new MutableDisposable()); + private _notice: ChatInputNoticeWidget | undefined; + /** The images that the hint is about, while it waits for the lane or shows. */ + private readonly _imageIds = new Set(); + private _gesture: ChatImageAttachGesture = 'paste'; + private _copy: AppWindowScreenshotHintCopy = 'none'; + private _shownAt: number | undefined; + private _loggedOpportunity = false; + private _leading = false; + private _claiming = false; + /** The claim that this window gave back last, which its cached value can hold for a moment longer. */ + private _releasedClaim: string | undefined; + + constructor( + private readonly _target: IAppWindowScreenshotHintTarget, + private readonly _command: IAppWindowScreenshotHintCommand, + @IChatUserImageAttachmentService userImageAttachmentService: IChatUserImageAttachmentService, + @IAppWindowScreenshotService private readonly _appWindowScreenshotService: IAppWindowScreenshotService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IContextKeyService private readonly _contextKeyService: IContextKeyService, + @IKeybindingService private readonly _keybindingService: IKeybindingService, + @IMarkdownRendererService private readonly _markdownRendererService: IMarkdownRendererService, + @IStorageService private readonly _storageService: IStorageService, + @ITelemetryService private readonly _telemetryService: ITelemetryService, + @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, + ) { + super(); + + this._register(userImageAttachmentService.onDidAttachImages(e => { + if (isEqual(e.inputUri, this._target.inputUri)) { + this._onDidAttachImages(e); + } + })); + this._register(this._target.onDidChangeAttachments(() => { + if (this._imageIds.size && !this._hasImagesAttached()) { + this._end('expired'); + } + })); + this._register(this._target.onDidChangeDraft(() => this._end('expired'))); + this._register(this._appWindowScreenshotService.onDidChangeHasCaptured(() => { + if (this._appWindowScreenshotService.hasCaptured) { + this._end('used'); + } + })); + this._register(this._configurationService.onDidChangeConfiguration(e => { + if ((e.affectsConfiguration(ChatConfiguration.AppWindowScreenshotsEnabled) || e.affectsConfiguration(TIPS_ENABLED_SETTING)) && !this._isTurnedOn()) { + this._end('expired'); + } + })); + // Takes the hint off screen even when the notice host is gone and won't stand it down. + this._register(toDisposable(() => this._clearContent())); + } + + private _onDidAttachImages(e: IChatUserImageAttachmentEvent): void { + if (!this._target.canAttachScreenshots() || !this._isTurnedOn()) { + return; + } + if (!this._loggedOpportunity) { + this._loggedOpportunity = true; + this._log('opportunity', e.gesture, 'none', e.attachmentIds.length, -1); + } + // A hint that waits or shows already is about these images too. + if (!this._imageIds.size && (this._appWindowScreenshotService.hasCaptured || this._wasShown())) { + return; + } + for (const id of e.attachmentIds) { + this._imageIds.add(id); + } + if (this._claim.value) { + return; + } + + this._gesture = e.gesture; + const claim = this._target.noticeHost.occupy(ChatInputNoticeLane.Tip, { + focusTarget: { + hasFocus: () => this._notice?.hasFocus() ?? false, + focus: () => this._notice?.focus(), + // The lane is held from the paste or drop, but there is only something to focus once the hint renders. + canFocus: () => !!this._notice, + }, + onDidChangeLeading: leading => this._setLeading(leading), + }); + // The host can hand over the lane while claiming it, and the hint may have ended already then. + if (this._imageIds.size) { + this._claim.value = claim; + } else { + claim.dispose(); + } + } + + /** Whether the feature and tips are on. */ + private _isTurnedOn(): boolean { + return !!this._configurationService.getValue(ChatConfiguration.AppWindowScreenshotsEnabled) && this._configurationService.getValue(TIPS_ENABLED_SETTING) !== false; + } + + /** Whether the hint still applies: it is turned on, the input can take the screenshot, and the user hasn't captured one yet. */ + private _isEligible(): boolean { + return this._isTurnedOn() && this._target.canAttachScreenshots() && !this._appWindowScreenshotService.hasCaptured && this._hasImagesAttached(); + } + + /** Whether the hint showed, as far as this window knows: another window may have shown it a moment ago. */ + private _wasShown(): boolean { + return this._isClaimed(this._storageService.get(HINT_SHOWN_STORAGE_KEY, StorageScope.APPLICATION_SHARED)); + } + + /** Whether a stored value claims the hint's showing, which neither an empty value nor a claim that this window gave back does. */ + private _isClaimed(value: string | undefined): boolean { + return !!value && value !== this._releasedClaim; + } + + /** Whether the hint can show now, which a claim of its one showing needs before and after it. */ + private _isReadyToShow(): boolean { + return !this._store.isDisposed && this._leading && this._isEligible(); + } + + private _hasImagesAttached(): boolean { + return this._target.getAttachmentIds().some(id => this._imageIds.has(id)); + } + + private _setLeading(leading: boolean): void { + this._leading = leading; + if (!leading) { + this._clearContent(); + return; + } + if (this._shownAt !== undefined) { + this._render(); + return; + } + // Things may have changed while the hint waited for other notices. + if (!this._isEligible() || this._wasShown()) { + this._end('expired'); + return; + } + void this._claimShowing(); + } + + /** + * Claims the hint's one showing, which only one window can do, and shows it. The claim is the stored value, so the + * hint only claims while it can show, and gives the claim back when it went away or stood down meanwhile. + */ + private async _claimShowing(): Promise { + if (this._claiming) { + return; + } + this._claiming = true; + let claim: string | undefined; + let shownElsewhere = false; + try { + // The cached value can lag behind other windows, so the claim reads and swaps the value that they share. + const shown = await this._storageService.readApplicationSharedValue(HINT_SHOWN_STORAGE_KEY); + if (this._isClaimed(shown)) { + shownElsewhere = true; + } else if (this._isReadyToShow()) { + const id = generateUuid(); + if ((await this._storageService.compareAndSwapApplicationSharedValue(HINT_SHOWN_STORAGE_KEY, shown, id)).swapped) { + claim = id; + } else { + shownElsewhere = true; + } + } + } finally { + this._claiming = false; + } + + if (claim && this._isReadyToShow()) { + this._show(); + } else if (claim) { + // An empty value lets the next paste or drop claim the showing, unless another window claimed it since. + this._releasedClaim = claim; + void this._storageService.compareAndSwapApplicationSharedValue(HINT_SHOWN_STORAGE_KEY, claim, ''); + } else if (shownElsewhere && !this._store.isDisposed) { + this._end('expired'); + } + // Otherwise the hint went away, or stood down and claims again once it leads. + } + + private _show(): void { + this._render(); + this._shownAt = Date.now(); + this._log('shown', this._gesture, this._copy, this._imageIds.size, 0); + if (this._configurationService.getValue(this._environmentService.isSessionsWindow ? AccessibilityVerbositySettingId.SessionsChat : AccessibilityVerbositySettingId.Chat)) { + this._notice?.announce(); + } + } + + private _render(): void { + this._clearContent(); + const { copy, message, ariaLabel } = this._getCopy(); + this._copy = copy; + + const store = new DisposableStore(); + const notice = store.add(new ChatInputNoticeWidget({ + variant: ChatInputNoticeVariant.Tip, + className: 'chat-app-window-screenshot-hint', + ariaLabel, + ariaRoleDescription: localize('appWindowScreenshotHint.roleDescription', "tip"), + onEscape: () => this._end('dismissed'), + })); + append(notice.domNode, $(`span.chat-app-window-screenshot-hint-icon${ThemeIcon.asCSSSelector(Codicon.deviceCamera)}`, { 'aria-hidden': 'true' })); + const rendered = store.add(this._markdownRendererService.render(message, { actionHandler: () => this._runCommand() })); + append(notice.domNode, $('.chat-app-window-screenshot-hint-message')).appendChild(rendered.element); + notice.addDismissAction({ onActivate: () => this._end('dismissed') }); + + this._content.value = store; + this._notice = notice; + this._target.container.appendChild(notice.domNode); + setChatInputStackSlot(this._target.container, ChatInputStackSlot.Docked); + } + + /** + * Words the hint for the user's keybinding, which can work while the app is in front, or for the command when it has + * none. Either is a link that runs the command. + */ + private _getCopy(): { readonly copy: AppWindowScreenshotHintCopy; readonly message: MarkdownString; readonly ariaLabel: string } { + const link = `command:${this._command.id}`; + const markdown = (value: string) => new MarkdownString(value, { isTrusted: { enabledCommands: [this._command.id] } }); + const keybinding = this._keybindingService.lookupKeybinding(this._command.id); + const label = keybinding?.getLabel(); + if (!keybinding || !label) { + const message = markdown(localize('appWindowScreenshotHint.palette', "Showing the agent your app? Next time, switch from your app to chat and run [{0}]({1}) from the Command Palette to attach a screenshot of its window.", escapeMarkdownSyntaxTokens(this._command.title), link)); + return { copy: 'palette', message, ariaLabel: renderAsPlaintext(message) }; + } + + const accelerator = keybinding.getElectronAccelerator(); + const systemWide = !!accelerator && selectSystemWideKeybindings(this._keybindingService.getKeybindings(), this._contextKeyService).candidates.some(candidate => candidate.commandId === this._command.id && candidate.accelerator === accelerator); + const format = (key: string) => markdown(systemWide + ? localize('appWindowScreenshotHint.systemWide', "Showing the agent your app? Next time, press [{0}]({1}) while your app is in front to attach a screenshot of its window.", escapeMarkdownSyntaxTokens(key), link) + : localize('appWindowScreenshotHint.inApp', "Showing the agent your app? Next time, switch from your app to chat and press [{0}]({1}) to attach a screenshot of its window.", escapeMarkdownSyntaxTokens(key), link)); + return { copy: systemWide ? 'systemWide' : 'inApp', message: format(label), ariaLabel: renderAsPlaintext(format(keybinding.getAriaLabel() ?? label)) }; + } + + /** Runs the command from the hint's link: it captures the window, or opens the setup while macOS doesn't allow Screen Recording. */ + private _runCommand(): void { + if (this._shownAt !== undefined) { + this._log('clicked', this._gesture, this._copy, this._imageIds.size, Date.now() - this._shownAt); + } + this._command.run(); + } + + /** Takes the hint away. When it never showed, the next paste or drop can show it. */ + private _end(action: 'dismissed' | 'expired' | 'used'): void { + if (!this._imageIds.size) { + return; + } + if (this._shownAt !== undefined) { + this._log(action, this._gesture, this._copy, this._imageIds.size, Date.now() - this._shownAt); + } + this._imageIds.clear(); + this._shownAt = undefined; + this._copy = 'none'; + // Released before the content goes, so the notice host moves focus back to the input only when it was in the hint. + this._claim.clear(); + this._clearContent(); + } + + private _clearContent(): void { + this._notice = undefined; + this._content.clear(); + clearNode(this._target.container); + setChatInputStackSlot(this._target.container, ChatInputStackSlot.Empty); + } + + private _log(action: AppWindowScreenshotHintAction, gesture: ChatImageAttachGesture, copy: AppWindowScreenshotHintCopy, imageCount: number, durationMs: number): void { + this._telemetryService.publicLog2('screenshotTool.appWindowHint', { action, gesture, copy, imageCount, durationMs }); + } +} diff --git a/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotSetup.ts b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotSetup.ts new file mode 100644 index 000000000000..4f7c3d0239be --- /dev/null +++ b/src/vs/workbench/contrib/chat/electron-browser/actions/chatAppWindowScreenshotSetup.ts @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../media/chatAppWindowScreenshotSetup.css'; +import { $, append, clearNode, getWindow, isHTMLElement } from '../../../../../base/browser/dom.js'; +import { ActionBar } from '../../../../../base/browser/ui/actionbar/actionbar.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { Button } from '../../../../../base/browser/ui/button/button.js'; +import { Dialog, DialogContentsAlignment } from '../../../../../base/browser/ui/dialog/dialog.js'; +import { Action } from '../../../../../base/common/actions.js'; +import { equals } from '../../../../../base/common/arrays.js'; +import { RunOnceScheduler } from '../../../../../base/common/async.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize } from '../../../../../nls.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; +import { IProductService } from '../../../../../platform/product/common/productService.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'; +import { AppWindowScreenshotPermission, IAppWindowScreenshotService } from '../../../screenshotTool/electron-browser/appWindowScreenshot.js'; + +interface IStepElements { + readonly row: HTMLElement; + readonly description: HTMLElement; + readonly status: HTMLElement; + readonly controls: HTMLElement; +} + +interface IScreenRecordingStep extends IStepElements { + readonly recheck: HTMLElement; + readonly allow: Button; + /** Opens System Settings again, beside Restart, which is the next thing to do once the user came back. */ + readonly openSettings: Button; + readonly restart: Button; +} + +/** How long the modal shows Screen Recording allowed before it closes on its own. */ +const ALLOWED_CLOSE_DELAY = 1000; + +/** + * The modal that sets up attaching screenshots of other apps while macOS doesn't allow Screen Recording, which it lets + * the user allow. After the user goes to System Settings, it checks Screen Recording again once the window regains focus. macOS only applies the permission once + * VS Code restarts, so when the user comes back without it, the step offers to restart. Once Screen Recording is + * allowed, the modal closes on its own, and the keybinding attaches screenshots. + */ +export class AppWindowScreenshotSetupDialog extends Disposable { + + private readonly _dialog: Dialog; + private readonly _element: HTMLElement; + private readonly _screenRecording: IScreenRecordingStep; + private readonly _closeWhenAllowed = this._register(new RunOnceScheduler(() => this._dialog.dispose(), ALLOWED_CLOSE_DELAY)); + + private _permission: AppWindowScreenshotPermission; + /** Set when the user went to System Settings: once the window lost and regained focus, check again. */ + private _settingsVisit: { blurred: boolean } | undefined; + /** Whether the user came back from System Settings while macOS still didn't allow Screen Recording. */ + private _returnedWithoutPermission = false; + + constructor( + permission: AppWindowScreenshotPermission, + @ILayoutService layoutService: ILayoutService, + @IKeybindingService keybindingService: IKeybindingService, + @IHostService private readonly _hostService: IHostService, + @IAppWindowScreenshotService private readonly _appWindowScreenshotService: IAppWindowScreenshotService, + @IProductService private readonly _productService: IProductService, + ) { + super(); + this._permission = permission; + + // The dialog renders its icon and body when it is created, so it comes first and takes the elements after. + const slots: { icon?: HTMLElement; body?: HTMLElement } = {}; + this._dialog = this._register(new Dialog( + layoutService.activeContainer, + localize('appWindowScreenshotSetup.title', "Attach Screenshots of Other Apps"), + [], + createWorkbenchDialogOptions({ + type: 'none', + alignment: DialogContentsAlignment.Vertical, + renderIcon: container => { slots.icon = container; }, + renderBody: container => { slots.body = container; }, + extraClasses: ['app-window-screenshot-setup-dialog'], + disableDefaultAction: true, + // The body has no links, so the dialog mustn't style the Check Again action's label like one. + dialogStyles: { ...defaultDialogStyles, textLinkForeground: undefined }, + }, keybindingService, layoutService, _hostService), + )); + + this._element = $('.app-window-screenshot-setup'); + append(this._element, $('p.app-window-screenshot-setup-description', undefined, localize('appWindowScreenshotSetup.description', "Let the agent see the app that you are building, whether it runs in a browser, a simulator, or its own window. {0} captures a window only when you ask it to.", _productService.nameShort))); + const steps = append(this._element, $('.app-window-screenshot-setup-steps', { role: 'list', 'aria-label': localize('appWindowScreenshotSetup.steps', "Setup steps") })); + this._screenRecording = this._createScreenRecordingStep(steps); + + this._register(_hostService.onDidChangeFocus(focused => this._onWindowFocus(focused))); + + slots.icon?.appendChild($('.app-window-screenshot-setup-icon', { 'aria-hidden': 'true' })); + slots.body?.appendChild(this._element); + this._render(); + } + + /** Shows the modal, and resolves once it closed. */ + async show(): Promise { + const closed = this._dialog.show(); + this._focus(); + await closed; + } + + private _createStep(list: HTMLElement, icon: ThemeIcon, name: string): IStepElements { + const row = append(list, $('.app-window-screenshot-setup-step', { role: 'listitem' })); + append(row, $(`span.app-window-screenshot-setup-step-icon${ThemeIcon.asCSSSelector(icon)}`, { 'aria-hidden': 'true' })); + const text = append(row, $('.app-window-screenshot-setup-step-text', { 'aria-hidden': 'true' })); + append(text, $('span.app-window-screenshot-setup-step-name', undefined, name)); + const description = append(text, $('span.app-window-screenshot-setup-step-description')); + const status = append(row, $('span.app-window-screenshot-setup-step-status', { 'aria-hidden': 'true' })); + const controls = append(row, $('.app-window-screenshot-setup-step-controls')); + return { row, description, status, controls }; + } + + private _createScreenRecordingStep(list: HTMLElement): IScreenRecordingStep { + const step = this._createStep(list, Codicon.eye, localize('appWindowScreenshotSetup.screenRecording', "Screen Recording")); + + const recheck = $('.app-window-screenshot-setup-recheck'); + const recheckAction = this._register(new Action('appWindowScreenshotSetup.recheck', localize('appWindowScreenshotSetup.recheck', "Check Again"), ThemeIcon.asClassName(Codicon.refresh), true, () => this._checkPermission(false))); + recheckAction.tooltip = localize('appWindowScreenshotSetup.recheck.tooltip', "Check Screen Recording Again"); + // The modal stops every key release, so the action runs as the key goes down. + const actionBar = this._register(new ActionBar(recheck, { triggerKeys: { keys: [KeyCode.Enter, KeyCode.Space], keyDown: true } })); + actionBar.push(recheckAction, { icon: true, label: false }); + + const allow = this._register(new Button(step.controls, { ...defaultButtonStyles, small: true })); + allow.label = localize('appWindowScreenshotSetup.allow', "Allow in Settings"); + allow.setAriaLabel(localize('appWindowScreenshotSetup.allow.aria', "Allow Screen Recording in System Settings")); + this._register(allow.onDidClick(() => this._allowInSettings())); + + const openSettings = this._register(new Button(step.controls, { ...defaultButtonStyles, secondary: true, small: true })); + openSettings.label = localize('appWindowScreenshotSetup.openSettings', "Open Settings"); + openSettings.setAriaLabel(localize('appWindowScreenshotSetup.openSettings.aria', "Open Screen Recording in System Settings")); + this._register(openSettings.onDidClick(() => this._allowInSettings())); + + const restart = this._register(new Button(step.controls, { ...defaultButtonStyles, small: true })); + restart.label = localize('appWindowScreenshotSetup.restart', "Restart"); + restart.setAriaLabel(localize('appWindowScreenshotSetup.restart.aria', "Restart {0} to Apply Screen Recording", this._productService.nameShort)); + this._register(restart.onDidClick(() => { void this._hostService.restart(); })); + + return { ...step, recheck, allow, openSettings, restart }; + } + + private _render(): void { + const targetDocument = getWindow(this._element).document; + const focused = targetDocument.activeElement; + const hadFocus = focused !== targetDocument.body && this._element.contains(focused); + const product = this._productService.nameShort; + + const screenRecording = this._screenRecording; + const granted = this._permission === 'granted' || this._permission === 'notRequired'; + const restricted = this._permission === 'restricted'; + this._renderStep( + screenRecording, + localize('appWindowScreenshotSetup.screenRecording', "Screen Recording"), + granted ? localize('appWindowScreenshotSetup.allowed.state', "Allowed") : restricted ? localize('appWindowScreenshotSetup.restricted.state', "Restricted") : localize('appWindowScreenshotSetup.notAllowed.state', "Not allowed"), + granted ? localize('appWindowScreenshotSetup.allowed.description', "{0} can see the windows of other apps.", product) + : restricted ? localize('appWindowScreenshotSetup.restricted.description', "This Mac doesn't let {0} record the screen.", product) + : this._returnedWithoutPermission ? localize('appWindowScreenshotSetup.restart.description', "If you turned it on, restart {0} to apply it.", product) + : localize('appWindowScreenshotSetup.notAllowed.description', "Lets {0} see the windows of other apps.", product), + granted, + granted || restricted ? [] + : this._returnedWithoutPermission ? [screenRecording.recheck, screenRecording.openSettings.element, screenRecording.restart.element] + : [screenRecording.recheck, screenRecording.allow.element], + ); + + if (granted && !this._closeWhenAllowed.isScheduled()) { + this._closeWhenAllowed.schedule(); + } + // A control that the steps kept gets focus back, and when they removed it, focus moves to the next thing to do. + if (hadFocus && targetDocument.activeElement !== focused) { + if (isHTMLElement(focused) && this._element.contains(focused)) { + focused.focus(); + } else { + this._focus(); + } + } + } + + private _renderStep(step: IStepElements, name: string, state: string, description: string, done: boolean, controls: readonly HTMLElement[]): void { + step.description.textContent = description; + step.status.className = 'app-window-screenshot-setup-step-status'; + if (done) { + step.status.classList.add('done', ...ThemeIcon.asClassNameArray(Codicon.passFilled)); + } + // Removed, not hidden: the modal moves focus itself across every control in its body, hidden ones too. + if (!equals(Array.from(step.controls.children), controls)) { + clearNode(step.controls); + step.controls.append(...controls); + } + step.row.setAttribute('aria-label', localize('appWindowScreenshotSetup.step', "{0}, {1}. {2}", name, state, description)); + } + + /** Moves focus to the next thing to do: restarting, or allowing Screen Recording. */ + private _focus(): void { + const screenRecording = this._screenRecording; + if (screenRecording.restart.element.isConnected) { + screenRecording.restart.focus(); + } else if (screenRecording.allow.element.isConnected) { + screenRecording.allow.focus(); + } + } + + private async _allowInSettings(): Promise { + this._settingsVisit = { blurred: false }; + await this._appWindowScreenshotService.requestPermission(); + } + + private _onWindowFocus(focused: boolean): void { + const visit = this._settingsVisit; + if (!visit) { + return; + } + if (!focused) { + visit.blurred = true; + } else if (visit.blurred) { + this._settingsVisit = undefined; + void this._checkPermission(true); + } + } + + private async _checkPermission(returned: boolean): Promise { + const previous = this._permission; + const permission = await this._appWindowScreenshotService.getPermission(); + if (this._store.isDisposed) { + return; + } + this._permission = permission; + if (returned && permission === 'notGranted') { + this._returnedWithoutPermission = true; + } + this._render(); + if (permission === 'granted') { + if (previous !== 'granted') { + status(localize('appWindowScreenshotSetup.allowed', "Screen Recording is allowed.")); + } + } else if (permission === 'notGranted') { + status(localize('appWindowScreenshotSetup.notAllowed', "Screen Recording is not allowed yet. If you turned it on in System Settings, restart {0}.", this._productService.nameShort)); + } + } +} diff --git a/src/vs/workbench/contrib/chat/electron-browser/builtInTools/tools.ts b/src/vs/workbench/contrib/chat/electron-browser/builtInTools/tools.ts index 1d1d822cc305..fafb9b1e7a4e 100644 --- a/src/vs/workbench/contrib/chat/electron-browser/builtInTools/tools.ts +++ b/src/vs/workbench/contrib/chat/electron-browser/builtInTools/tools.ts @@ -13,11 +13,9 @@ import { ILabelService } from '../../../../../platform/label/common/label.js'; import { IStorageService } from '../../../../../platform/storage/common/storage.js'; import { IWorkbenchContribution } from '../../../../common/contributions.js'; import { ChatExternalPathConfirmationContribution } from '../../common/tools/builtinTools/chatExternalPathConfirmation.js'; -import { ChatUrlFetchingConfirmationContribution } from '../../common/tools/builtinTools/chatUrlFetchingConfirmation.js'; import { ILanguageModelToolsConfirmationService } from '../../common/tools/languageModelToolsConfirmationService.js'; import { ILanguageModelToolsService } from '../../common/tools/languageModelToolsService.js'; -import { InternalFetchWebPageToolId } from '../../common/tools/builtinTools/tools.js'; -import { FetchWebPageTool, FetchWebPageToolData, IFetchWebPageToolParams } from './fetchPageTool.js'; +import { FetchWebPageTool, FetchWebPageToolData } from './fetchPageTool.js'; export class NativeBuiltinToolsContribution extends Disposable implements IWorkbenchContribution { @@ -37,14 +35,6 @@ export class NativeBuiltinToolsContribution extends Disposable implements IWorkb const editTool = instantiationService.createInstance(FetchWebPageTool); this._register(toolsService.registerTool(FetchWebPageToolData, editTool)); - this._register(confirmationService.registerConfirmationContribution( - InternalFetchWebPageToolId, - instantiationService.createInstance( - ChatUrlFetchingConfirmationContribution, - params => (params as IFetchWebPageToolParams).urls - ) - )); - // Register external path confirmation contribution for read_file and list_dir // They share the same allowlist so approving a folder for reading files also allows listing that directory const externalPathConfirmation = new ChatExternalPathConfirmationContribution( diff --git a/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotHint.css b/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotHint.css new file mode 100644 index 000000000000..c352bdc60211 --- /dev/null +++ b/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotHint.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. + *--------------------------------------------------------------------------------------------*/ + +.chat-attachment-hint-container { + width: 100%; +} + +/* + * The frame, row layout and type come from `.chat-input-notice`. Like the + * getting-started tip, this is one row of text, so it centres rather than taking + * the variant's top alignment. Prefixed with the base class so it out-ranks it. + */ +.chat-attachment-hint-container .chat-input-notice.chat-app-window-screenshot-hint { + align-items: center; +} + +.chat-app-window-screenshot-hint .chat-app-window-screenshot-hint-icon { + flex: 0 0 auto; +} + +.chat-app-window-screenshot-hint .chat-app-window-screenshot-hint-message { + flex: 1 1 auto; + min-width: 0; +} + +.chat-app-window-screenshot-hint .chat-app-window-screenshot-hint-message .rendered-markdown p { + margin: 0; +} diff --git a/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotSetup.css b/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotSetup.css new file mode 100644 index 000000000000..2a150a53fdbe --- /dev/null +++ b/src/vs/workbench/contrib/chat/electron-browser/media/chatAppWindowScreenshotSetup.css @@ -0,0 +1,96 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-icon { + width: 64px; + height: 64px; + background: url('../../../../browser/media/code-icon.svg') center / contain no-repeat; +} + +/* The body holds every control, so the modal has no buttons of its own. */ +.monaco-dialog-box.app-window-screenshot-setup-dialog > .dialog-buttons-row { + display: none; +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup { + display: flex; + flex-direction: column; + align-self: stretch; + gap: var(--vscode-spacing-size160); + width: 420px; + max-width: 100%; + margin-top: var(--vscode-spacing-size40); + margin-bottom: var(--vscode-spacing-size120); + text-align: start; +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-description { + margin: 0; + text-align: center; + text-wrap: balance; + color: var(--vscode-descriptionForeground); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-steps { + display: flex; + flex-direction: column; + /* The dialog's surface is translucent, so the stroke tints the foreground rather than use an opaque color. */ + border: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, color-mix(in srgb, var(--vscode-foreground) 14%, transparent)); + border-radius: var(--vscode-cornerRadius-medium); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: var(--vscode-spacing-size80) var(--vscode-spacing-size120); + min-height: 32px; + padding: var(--vscode-spacing-size100) var(--vscode-spacing-size120); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step + .app-window-screenshot-setup-step { + border-top: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, color-mix(in srgb, var(--vscode-foreground) 14%, transparent)); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-icon { + color: var(--vscode-icon-foreground); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-text { + display: flex; + flex-direction: column; + min-width: 0; +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-name { + font-weight: var(--vscode-fontWeight-semiBold); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-description { + font-size: var(--vscode-fontSize-body2); + color: var(--vscode-descriptionForeground); +} + +/* A step shows either its done check or its controls. */ +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-status, +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-controls { + grid-row: 1; + grid-column: 3; +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-status.done { + color: var(--vscode-testing-iconPassed); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-controls { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); +} + +.app-window-screenshot-setup-dialog .app-window-screenshot-setup-step-controls > .monaco-button { + width: fit-content; + white-space: nowrap; +} diff --git a/src/vs/workbench/contrib/chat/electron-browser/remoteConnectionsSharing.ts b/src/vs/workbench/contrib/chat/electron-browser/remoteConnectionsSharing.ts index 2540d579ecea..3cb41a1bc131 100644 --- a/src/vs/workbench/contrib/chat/electron-browser/remoteConnectionsSharing.ts +++ b/src/vs/workbench/contrib/chat/electron-browser/remoteConnectionsSharing.ts @@ -3,14 +3,18 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { Sequencer } from '../../../../base/common/async.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; -import { autorun } from '../../../../base/common/observable.js'; +import { autorun, IObservable, observableValue } from '../../../../base/common/observable.js'; import { localize } from '../../../../nls.js'; import { IAgentHostService } from '../../../../platform/agentHost/common/agentService.js'; -import { AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService, isGitHubEnvironmentBackend } from '../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { getConnectionDiagnosticError } from '../../../../platform/agentHost/common/connectionDiagnostics.js'; +import { ConnectionTelemetryErrorClassification, getConnectionTelemetryError, IConnectionTelemetryError, toConnectionTelemetryError } from '../../../../platform/agentHost/common/connectionTelemetry.js'; +import { AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentSharingError, GitHubEnvironmentSharingFailureReason, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService, isGitHubEnvironmentBackend } from '../../../../platform/agentHost/common/missionControlEnvironment.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { FileSystemProviderErrorCode } from '../../../../platform/files/common/files.js'; +import { INotificationService, NotificationMessage } from '../../../../platform/notification/common/notification.js'; import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; import { CONFIGURATION_KEY_HOST_NAME, INACTIVE_TUNNEL_MODE, IRemoteTunnelService, TunnelMode, TunnelStatus } from '../../../../platform/remoteTunnel/common/remoteTunnel.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; @@ -41,43 +45,105 @@ export type GitHubEnvironmentsAvailability = 'enabled' | 'policyDisabled' | 'una /** Where the connection method is chosen: the Agents window title bar, the chat input, or the Remote Environments editor. */ export type RemoteConnectionsSource = 'titleBar' | 'chatInput' | 'remotesEditor'; -/** The outcome of toggling sharing: `failed` when an error was reported, otherwise `completed`, even when sharing stays off, e.g. because sign-in was canceled. */ -export type RemoteConnectionsToggleResult = 'completed' | 'failed'; +/** + * Why a choice did not change sharing as requested: `canceled` when sign-in was canceled, the failed step + * (`settingsUpdate`, `stopDevTunnel`, `devTunnel`), why GitHub environment sharing could not be enabled, or `unknown`. + */ +export type RemoteConnectionsFailureReason = GitHubEnvironmentSharingFailureReason | 'canceled' | 'settingsUpdate' | 'stopDevTunnel' | 'devTunnel' | 'unknown'; + +/** Describes a reported failure with structured error metadata only, never with error messages. */ +export interface IRemoteConnectionsToggleFailure extends IConnectionTelemetryError { + readonly failureReason: RemoteConnectionsFailureReason; + readonly fileErrorCode?: FileSystemProviderErrorCode; +} + +/** The outcome of toggling sharing: `canceled` when sign-in was canceled, a failure when an error was reported, otherwise `completed`. */ +export type RemoteConnectionsToggleResult = 'completed' | 'canceled' | IRemoteConnectionsToggleFailure; + +export function getRemoteConnectionsToggleFailure(error: unknown, fallbackReason: RemoteConnectionsFailureReason): IRemoteConnectionsToggleFailure { + if (error instanceof GitHubEnvironmentSharingError) { + return { + failureReason: error.reason, + ...getConnectionTelemetryError(error.diagnostic), + ...(error.fileErrorCode === undefined ? {} : { fileErrorCode: error.fileErrorCode }), + }; + } + return { failureReason: fallbackReason, ...getConnectionTelemetryError(getConnectionDiagnosticError(error)) }; +} + +const remoteConnectionsFailureReasons: Record = { + unavailable: true, nonGitHubAccount: true, accountUnavailable: true, signInRequired: true, multipleAccounts: true, accountMismatch: true, signInFailed: true, + fileSystemRoot: true, projectFolder: true, ownerMismatch: true, connection: true, canceled: true, settingsUpdate: true, stopDevTunnel: true, devTunnel: true, unknown: true, +}; +const fileSystemProviderErrorCodes = new Set(Object.values(FileSystemProviderErrorCode)); + +function isRemoteConnectionsFailureReason(value: unknown): value is RemoteConnectionsFailureReason { + return typeof value === 'string' && Object.hasOwn(remoteConnectionsFailureReasons, value); +} + +function isFileSystemProviderErrorCode(value: unknown): value is FileSystemProviderErrorCode { + return fileSystemProviderErrorCodes.has(value); +} + +/** Copies only allowlisted values from a failed toggle result, so telemetry never receives anything else the command returned. */ +function toRemoteConnectionsToggleFailure(result: unknown): IRemoteConnectionsToggleFailure | undefined { + if (typeof result !== 'object' || result === null) { + return undefined; + } + const failure: { readonly failureReason?: unknown; readonly fileErrorCode?: unknown; readonly errorCategory?: unknown; readonly errorCode?: unknown; readonly statusCode?: unknown } = result; + if (failure.failureReason === undefined) { + return undefined; + } + return { + failureReason: isRemoteConnectionsFailureReason(failure.failureReason) ? failure.failureReason : 'unknown', + ...toConnectionTelemetryError(failure), + ...(isFileSystemProviderErrorCode(failure.fileErrorCode) ? { fileErrorCode: failure.fileErrorCode } : {}), + }; +} type RemoteConnectionsSelectionResult = 'applied' | 'unchanged' | 'unavailable' | 'disabled' | 'failed'; -type RemoteConnectionsSelectMethodEvent = { +interface IRemoteConnectionsSelectionOutcome { + readonly result: RemoteConnectionsSelectionResult; + readonly failure?: IRemoteConnectionsToggleFailure; +} + +type RemoteConnectionsSelectMethodEvent = IConnectionTelemetryError & { source: RemoteConnectionsSource; method: RemoteConnectionsMethod; previousMethod: RemoteConnectionsMethod; activeMethod: RemoteConnectionsMethod; result: RemoteConnectionsSelectionResult; gitHubEnvironments: GitHubEnvironmentsAvailability; + failureReason?: RemoteConnectionsFailureReason; + fileErrorCode?: FileSystemProviderErrorCode; }; -type RemoteConnectionsSelectMethodClassification = { +type RemoteConnectionsSelectMethodClassification = ConnectionTelemetryErrorClassification & { source: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Where the method was chosen: titleBar (Agents window), chatInput, or remotesEditor (This Computer section).' }; method: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The chosen connection method: off, devTunnel, or githubEnvironment.' }; previousMethod: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The connection method sharing or starting to share this computer before the choice, or off.' }; activeMethod: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The connection method sharing or starting to share this computer after the choice was applied, or off, e.g. when sign-in was canceled or failed.' }; result: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the choice was applied, already in effect, unavailable, disabled by settings or policy, or failed with an error.' }; gitHubEnvironments: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether GitHub Environments could be chosen when the method was chosen: enabled, policyDisabled, or unavailable.' }; + failureReason?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Allowlisted reason when the choice failed, e.g. signInRequired, fileSystemRoot, connection, settingsUpdate, or unknown; canceled when sign-in was canceled. Never error text.' }; + fileErrorCode?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Allowlisted file system error code, e.g. NoPermissions or Unknown, when a file system root or project folder to share could not be read.' }; owner: 'chrmarti'; - comment: 'Tracks how users choose how this computer is shared for remote connections and whether sharing is on afterwards, to compare the entry points.'; + comment: 'Tracks how users choose how this computer is shared for remote connections, whether sharing is on afterwards, and why choices failed, to compare the entry points.'; }; export function getOffDetail(): string { - return localize('remoteConnections.off.detail', "Only accessible from this machine."); + return localize('remoteConnections.off.detail', "Don't allow connections from other devices through this app."); } export function getDevTunnelsDetail(): string { - return localize('remoteConnections.devTunnel.detail', "Access workspaces and agents on this machine from VS Code or vscode.dev/agents."); + return localize('remoteConnections.devTunnel.detail', "Use agents and folders on this computer from VS Code or vscode.dev/agents. For full-editor access, use Remote Tunnels."); } export function getGitHubEnvironmentsDetail(availability: GitHubEnvironmentsAvailability): string { return availability === 'policyDisabled' ? localize('remoteConnections.githubEnvironment.policyDisabled', "Disabled by your organization. Contact your administrator to enable GitHub Environments.") - : localize('remoteConnections.githubEnvironment.detail', "Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot."); + : localize('remoteConnections.githubEnvironment.detail', "Continue agent sessions across supported Copilot apps, VS Code, and vscode.dev/agents. Agents use folders and tools on this computer; features vary by app."); } export interface IRemoteConnectionsStateSource { @@ -156,6 +222,50 @@ export class RemoteConnectionsState extends Disposable implements IRemoteConnect } } +/** + * Applies the connection methods chosen in a window one at a time, so each choice acts on the state the + * previous one left rather than a transitional one, and skips choices superseded while they waited, so + * the last choice wins. + */ +class RemoteConnectionsSelections { + + private readonly _sequencer = new Sequencer(); + private _latest = 0; + private _unresolved = 0; + private readonly _pendingMethod = observableValue(this, undefined); + /** The method chosen last while choices are being applied, otherwise `undefined`. */ + readonly pendingMethod: IObservable = this._pendingMethod; + + async select(method: RemoteConnectionsMethod, apply: () => Promise): Promise { + const selection = ++this._latest; + this._unresolved++; + this._pendingMethod.set(method, undefined); + try { + await this._sequencer.queue(async () => { + if (selection === this._latest) { + await apply(); + } + }); + } finally { + if (--this._unresolved === 0) { + this._pendingMethod.set(undefined, undefined); + } + } + } +} + +// Keyed by a window-scoped service, so the Remote Connections menus and the Remote Environments editor of a window share one. +const selectionsByWindow = new WeakMap(); + +function getSelections(remoteTunnelService: IRemoteTunnelService): RemoteConnectionsSelections { + let selections = selectionsByWindow.get(remoteTunnelService); + if (!selections) { + selections = new RemoteConnectionsSelections(); + selectionsByWindow.set(remoteTunnelService, selections); + } + return selections; +} + /** * Chooses how this computer is shared and names it for other clients. Shared by the * Remote Connections menu and the Remote Environments editor. @@ -169,6 +279,7 @@ export class RemoteConnectionsSharing extends Disposable { private _tunnelName: string | undefined; private _namesLoaded = false; private _nameRequest = 0; + private readonly _selections: RemoteConnectionsSelections; /** * @param _toggle Toggles sharing with the configured connection method and resolves to its {@link RemoteConnectionsToggleResult}. @@ -188,6 +299,11 @@ export class RemoteConnectionsSharing extends Disposable { ) { super(); + this._selections = getSelections(this._remoteTunnelService); + this._register(autorun(reader => { + this._selections.pendingMethod.read(reader); + this._onDidChange.fire(); + })); this._register(this._state.onDidChangeState(() => this._onDidChange.fire())); this._register(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(CONFIGURATION_KEY_HOST_NAME)) { @@ -220,6 +336,11 @@ export class RemoteConnectionsSharing extends Disposable { return !state.isSharing && !state.isConnecting ? 'off' : this.usesGitHubEnvironment ? 'githubEnvironment' : 'devTunnel'; } + /** The method chosen last in this window while choices are being applied, so it can be shown instead of the transitional {@link activeMethod}. */ + get pendingMethod(): RemoteConnectionsMethod | undefined { + return this._selections.pendingMethod.get(); + } + /** The name other clients see for this computer with the configured connection method. */ get name(): string | undefined { return this.usesGitHubEnvironment ? this._environmentName : this.getState().tunnelName ?? this._tunnelName; @@ -239,74 +360,104 @@ export class RemoteConnectionsSharing extends Disposable { return this._configurationService.getValue(GitHubEnvironmentsEnabledSettingId) === true ? 'enabled' : 'unavailable'; } - async selectMethod(method: RemoteConnectionsMethod): Promise { - const previousMethod = this.activeMethod; + /** + * Applies the chosen method once the choices made before it in this window have been applied, unless a later choice + * supersedes it while it waits. A superseded choice is not applied and not logged. + */ + selectMethod(method: RemoteConnectionsMethod): Promise { + return this._selections.select(method, () => this._applySelection(method)); + } + + private async _applySelection(method: RemoteConnectionsMethod): Promise { + const previousMethod = await this._readActiveMethod(); const gitHubEnvironments = this.gitHubEnvironmentsAvailability; - let result: RemoteConnectionsSelectionResult; + let outcome: IRemoteConnectionsSelectionOutcome; try { - result = await this._applyMethod(method); + outcome = await this._applyMethod(method, previousMethod !== 'off'); } catch (error) { - result = 'failed'; + outcome = { result: 'failed', failure: getRemoteConnectionsToggleFailure(error, 'unknown') }; this._notificationService.error(error); } - let activeMethod: RemoteConnectionsMethod; - try { - activeMethod = await this._readActiveMethod(); - } catch { - activeMethod = this.activeMethod; - } + const activeMethod = await this._readActiveMethod(); // Logged in every arm of the This Computer experiment, so sharing changes can be compared across them. this._telemetryService.publicLog2('remoteConnections.selectMethod', { source: this._source, method, previousMethod, activeMethod, - result, + result: outcome.result, gitHubEnvironments, + ...outcome.failure, }); } /** - * Reads the {@link activeMethod} from the sharing services: a toolbar can replace its view item, and with it - * the state source, while a selection is applied, which leaves the state source with the state before the change. + * Reads the {@link activeMethod} from the sharing services: the state source can lag behind a choice applied just + * before, and a toolbar can replace its view item, and with it the state source, while a choice waits or is applied. */ private async _readActiveMethod(): Promise { if (this.usesGitHubEnvironment) { return this._missionControlSharingService.state.get() === 'disabled' ? 'off' : 'githubEnvironment'; } - const [mode, status] = await Promise.all([ - this._remoteTunnelService.getMode(), - this._remoteTunnelService.getTunnelStatus(), - ]); - const state = getRemoteTunnelAccessState(mode, status); - return state.isSharing || state.isConnecting ? 'devTunnel' : 'off'; + try { + const [mode, status] = await Promise.all([ + this._remoteTunnelService.getMode(), + this._remoteTunnelService.getTunnelStatus(), + ]); + const state = getRemoteTunnelAccessState(mode, status); + return state.isSharing || state.isConnecting ? 'devTunnel' : 'off'; + } catch { + return this.activeMethod; + } } - private async _applyMethod(method: RemoteConnectionsMethod): Promise { + private async _applyMethod(method: RemoteConnectionsMethod, enabled: boolean): Promise { if (method === 'githubEnvironment' && !this._availabilityService.available.get()) { this._notificationService.error(new Error(localize('remoteConnections.githubEnvironment.unavailable', "GitHub Environments are currently unavailable."))); - return 'unavailable'; + return { result: 'unavailable' }; } if (method === 'githubEnvironment' && this._configurationService.getValue(GitHubEnvironmentsEnabledSettingId) !== true) { this._notificationService.error(new Error(localize('remoteConnections.githubEnvironment.disabled', "GitHub Environments are disabled by your settings or your organization."))); - return 'disabled'; + return { result: 'disabled' }; } - const state = this.getState(); - const enabled = state.isSharing || state.isConnecting; if (method === 'off') { - return enabled ? this._toggleSharing() : 'unchanged'; + return enabled ? this._toggleSharing() : { result: 'unchanged' }; } if (this.usesGitHubEnvironment !== isGitHubEnvironmentBackend(method)) { - await this._configurationService.updateValue(AgentHostRemoteConnectionsSettingId, method, ConfigurationTarget.USER); - await this._remoteTunnelService.stopTunnel(); + try { + await this._configurationService.updateValue(AgentHostRemoteConnectionsSettingId, method, ConfigurationTarget.USER); + } catch (error) { + return this._fail(error, 'settingsUpdate'); + } + try { + await this._remoteTunnelService.stopTunnel(); + } catch (error) { + return this._fail(error, 'stopDevTunnel'); + } } else if (enabled) { - return 'unchanged'; + return { result: 'unchanged' }; } return this._toggleSharing(); } - private async _toggleSharing(): Promise { - return (await this._toggle()) === 'failed' ? 'failed' : 'applied'; + private async _toggleSharing(): Promise { + const usesGitHubEnvironment = this.usesGitHubEnvironment; + let toggleResult: unknown; + try { + toggleResult = await this._toggle(); + } catch (error) { + return this._fail(error, usesGitHubEnvironment ? 'unknown' : 'devTunnel'); + } + if (toggleResult === 'canceled') { + return { result: 'applied', failure: { failureReason: 'canceled' } }; + } + const failure = toRemoteConnectionsToggleFailure(toggleResult); + return failure ? { result: 'failed', failure } : { result: 'applied' }; + } + + private _fail(error: NotificationMessage, reason: RemoteConnectionsFailureReason): IRemoteConnectionsSelectionOutcome { + this._notificationService.error(error); + return { result: 'failed', failure: getRemoteConnectionsToggleFailure(error, reason) }; } async rename(): Promise { diff --git a/src/vs/workbench/contrib/chat/electron-browser/toggleRemoteConnectionsActionViewItem.ts b/src/vs/workbench/contrib/chat/electron-browser/toggleRemoteConnectionsActionViewItem.ts index 5ea54b248b83..d97f7dddaa8a 100644 --- a/src/vs/workbench/contrib/chat/electron-browser/toggleRemoteConnectionsActionViewItem.ts +++ b/src/vs/workbench/contrib/chat/electron-browser/toggleRemoteConnectionsActionViewItem.ts @@ -232,7 +232,8 @@ export class RemoteConnectionsActionViewItem extends BaseActionViewItem { private _getConnectionMethods(): IActionWidgetDropdownAction[] { const environments = this._sharing.gitHubEnvironmentsAvailability; - const active = this._sharing.activeMethod; + // Checks the method chosen last, also in another surface, while choices are being applied. + const active = this._sharing.pendingMethod ?? this._sharing.activeMethod; const methods: IActionWidgetDropdownAction[] = [ { ...toAction({ diff --git a/src/vs/workbench/contrib/chat/electron-browser/tunnelHost.contribution.ts b/src/vs/workbench/contrib/chat/electron-browser/tunnelHost.contribution.ts index 4d658e067857..ab46170389b2 100644 --- a/src/vs/workbench/contrib/chat/electron-browser/tunnelHost.contribution.ts +++ b/src/vs/workbench/contrib/chat/electron-browser/tunnelHost.contribution.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import { Codicon } from '../../../../base/common/codicons.js'; -import { isCancellationError } from '../../../../base/common/errors.js'; +import { getErrorMessage, isCancellationError } from '../../../../base/common/errors.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; import { autorun } from '../../../../base/common/observable.js'; -import { localize2 } from '../../../../nls.js'; +import { localize, localize2 } from '../../../../nls.js'; import { IActionViewItemService, type IActionViewItemFactory } from '../../../../platform/actions/browser/actionViewItemService.js'; import { Action2, MenuId, registerAction2 } from '../../../../platform/actions/common/actions.js'; import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; @@ -23,7 +23,7 @@ import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase import { ChatContextKeyExprs, ChatContextKeys } from '../common/actions/chatContextKeys.js'; import { IRemoteTunnelStartOptions, RemoteTunnelCommandIds } from '../../remoteTunnel/electron-browser/remoteTunnel.contribution.js'; import { RemoteConnectionsActionViewItem } from './toggleRemoteConnectionsActionViewItem.js'; -import { getRemoteTunnelAccessState, RemoteConnectionsToggleResult } from './remoteConnectionsSharing.js'; +import { getRemoteConnectionsToggleFailure, getRemoteTunnelAccessState, RemoteConnectionsFailureReason, RemoteConnectionsToggleResult } from './remoteConnectionsSharing.js'; export const TUNNEL_HOST_SHARING_KEY = 'tunnelHostSharing'; export const TUNNEL_HOST_SHARING_CONTEXT = new RawContextKey(TUNNEL_HOST_SHARING_KEY, false); @@ -39,17 +39,24 @@ export async function executeToggleRemoteConnections(accessor: ServicesAccessor, const logService = accessor.get(ILogService); const notificationService = accessor.get(INotificationService); const enabled = sharingService.state.get() !== 'disabled'; - try { - if (!enabled) { + const fail = (error: unknown, reason: RemoteConnectionsFailureReason) => { + logService.error('Failed to toggle GitHub environment sharing', error); + notificationService.error(enabled + ? localize('tunnelHost.disableSharingFailed', "Failed to disable GitHub environment sharing: {0}", getErrorMessage(error)) + : localize('tunnelHost.enableSharingFailed', "Failed to enable GitHub environment sharing: {0}", getErrorMessage(error))); + return getRemoteConnectionsToggleFailure(error, reason); + }; + if (!enabled) { + try { await remoteTunnelService.stopTunnel(); + } catch (error) { + return isCancellationError(error) ? 'canceled' : fail(error, 'stopDevTunnel'); } + } + try { await sharingService.setEnabled(!enabled); } catch (error) { - if (!isCancellationError(error)) { - logService.error('Failed to toggle GitHub environment sharing', error); - notificationService.error(error); - return 'failed'; - } + return isCancellationError(error) ? 'canceled' : fail(error, 'unknown'); } return 'completed'; } diff --git a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityHelp.test.ts b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityHelp.test.ts index d4dc2be9b12f..0697929c7965 100644 --- a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityHelp.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityHelp.test.ts @@ -38,6 +38,18 @@ suite('Chat Accessibility Help', () => { && help.includes('leaves Refresh available to try again')), [true, true, false, true]); }); + test('explains sandbox scope storage and keyboard approval in both windows', () => { + assert.deepStrictEqual([false, true].map(sessionsWindow => { + const help = getAccessibilityHelpText('agentView', new MockKeybindingService(), true, sessionsWindow); + return { + sessionDefault: help.includes('Allow for This Session is the default'), + workspace: help.includes('Allow for This Workspace') && help.includes('privately on the agent host'), + noWorkspaceSettings: help.includes('without changing workspace settings'), + keyboard: help.includes('Enter or Space to open the approval dropdown') && help.includes('Escape closes the dropdown without approving'), + }; + }), Array.from({ length: 2 }, () => ({ sessionDefault: true, workspace: true, noWorkspaceSettings: true, keyboard: true }))); + }); + test('documents the file chooser on chat surfaces with Add Context', () => { assert.deepStrictEqual([ getAccessibilityHelpText('panelChat', new MockKeybindingService(), true), @@ -643,7 +655,7 @@ suite('Chat Accessibility Help', () => { disclosure: shown.includes('What Does "Archive" Do? is collapsed by default'), disclosureKeyboard: shown.includes('Enter or Space to expand or collapse it'), focus: shown.includes('Escape while it is focused, returns to the chat input'), - focusRemainingTasks: shown.includes('hides it from the sessions list so you can focus on your remaining tasks'), + focusRemainingTasks: shown.includes('Archiving the session sets it aside so you can focus on your remaining tasks'), retained: shown.includes('The session is not deleted'), agentRecovery: shown.includes('Ask your agent to find it'), recovery: shown.includes('"Archived" section of the sessions list. You can unarchive it anytime'), @@ -679,13 +691,14 @@ suite('Chat Accessibility Help', () => { fallback: help.includes('Completed thinking headers show Finished thinking until a summary is available'), singleHeader: help.includes('A single extracted reasoning heading is used directly without a model request'), multipleHeaders: help.includes('Multiple headings remain in the details and are used as the input for a generated summary'), - allStyles: help.includes('in every thinking style and progress layout'), + allStyles: help.includes('in every thinking style, and in every progress layout except Conversation'), + conversation: help.includes('A Conversation section never uses a reasoning heading or a generated summary as its header'), visibleOnly: help.includes('only when a live section finishes with its header in view'), background: help.includes('Sections that finish off-screen or in background chats do not request titles'), noBackfill: help.includes('Opening a chat, returning to it, scrolling or expanding existing sections never generates titles'), details: help.includes('All reasoning headings and content remain available in the expandable details'), setting: help.includes('chat.agent.thinking.generateTitles'), - }, { fallback: true, singleHeader: true, multipleHeaders: true, allStyles: true, visibleOnly: true, background: true, noBackfill: true, details: true, setting: true }); + }, { fallback: true, singleHeader: true, multipleHeaders: true, allStyles: true, conversation: true, visibleOnly: true, background: true, noBackfill: true, details: true, setting: true }); }); test('uses the configured Mark as Done wording for nudge help', () => { @@ -694,7 +707,7 @@ suite('Chat Accessibility Help', () => { keyboard: help.includes('Tab or Shift+Tab to reach Mark as Done, Configure Automatic Cleanup, or Dismiss Mark as Done Suggestion'), cleanupSettings: help.includes('Configure Automatic Cleanup opens the settings for automatically archiving inactive merged sessions and permanently deleting automatically archived merged sessions'), disclosure: help.includes('What Does "Mark as Done" Do? is collapsed by default'), - focusRemainingTasks: help.includes('hides it from the sessions list so you can focus on your remaining tasks'), + focusRemainingTasks: help.includes('Marking the session as done sets it aside so you can focus on your remaining tasks'), retained: help.includes('The session is not deleted'), agentRecovery: help.includes('Ask your agent to find it'), recovery: help.includes('"Done" section of the sessions list. You can restore it anytime'), diff --git a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityProvider.test.ts index 9f0940595ec8..65dd032d9e5b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatAccessibilityProvider.test.ts @@ -10,8 +10,10 @@ import { marked } from '../../../../../../base/common/marked/marked.js'; import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAccessibleViewService } from '../../../../../../platform/accessibility/browser/accessibleView.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; -import { ChatAccessibilityProvider } from '../../../browser/accessibility/chatAccessibilityProvider.js'; +import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { ChatAccessibilityProvider, getToolConfirmationAlert } from '../../../browser/accessibility/chatAccessibilityProvider.js'; import { Response } from '../../../common/model/chatModel.js'; import { IChatResponseIdentity } from '../../../browser/chat.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; @@ -107,6 +109,23 @@ suite('ChatAccessibilityProvider', () => { } } + test('announces where a terminal command awaiting confirmation runs', () => { + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IKeybindingService, { lookupKeybinding: () => undefined }); + instantiationService.stub(IContextKeyService, {}); + const confirmation = (workingDirectory: string) => new ChatToolInvocation({ + confirmationMessages: { title: 'Run the tests', message: './test.sh' }, + toolSpecificData: { kind: 'terminal', commandLine: { original: './test.sh' }, language: 'sh', executionTarget: { workingDirectory } }, + }, { + id: 'shell', displayName: 'Run shell command', modelDescription: 'Run a shell command', source: ToolDataSource.Internal, + }, 'shell', undefined, {}); + + assert.deepStrictEqual(['/work/web', '/work/api'].map(directory => instantiationService.invokeFunction(accessor => getToolConfirmationAlert(accessor, [confirmation(directory)]))), [ + 'Chat confirmation required: Run the tests: ./test.sh (Working directory: /work/web)', + 'Chat confirmation required: Run the tests: ./test.sh (Working directory: /work/api)', + ]); + }); + test('updates labels when the response content and accessibility hint change', () => { const response = store.add(new Response(new MarkdownString(table))); const element = createViewModel(response); diff --git a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatResponseAccessibleView.test.ts b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatResponseAccessibleView.test.ts index bda7587fc3ed..782ba5491294 100644 --- a/src/vs/workbench/contrib/chat/test/browser/accessibility/chatResponseAccessibleView.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/accessibility/chatResponseAccessibleView.test.ts @@ -252,7 +252,7 @@ suite('ChatResponseAccessibleView', () => { ]); }); - test('reads an Auto routing row as its selection reason when the router supplies one', () => { + test('reads an Auto routing row as its selection reason when the router supplies one, naming Copilot Fusion when Auto is presented that way', () => { const reason = 'Auto selected gpt-5.4-mini to prioritize cost efficiency, alongside model fit for this task.'; const item = upcastPartial({ isComplete: true, @@ -260,6 +260,7 @@ suite('ChatResponseAccessibleView', () => { value: [ { kind: 'autoModeResolution', resolved: { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', reason } }, { kind: 'autoModeResolution', resolved: { id: 'gpt-5.5', name: 'GPT-5.5' } }, + { kind: 'autoModeResolution', resolved: { id: 'gpt-5.5', name: 'GPT-5.5' }, fusion: true }, ], }), }); @@ -267,6 +268,43 @@ suite('ChatResponseAccessibleView', () => { assert.deepStrictEqual(getChatResponsePlaintextParts(item, true), [ { partIndex: 0, text: reason }, { partIndex: 1, text: 'Auto routed task to GPT-5.5' }, + { partIndex: 2, text: 'Copilot Fusion routed task to GPT-5.5' }, + ]); + }); + + test('reads a model router row with the effort and context size its router set, and neither when it set none', () => { + const resolved = { id: 'opus', name: 'Claude Opus 5.5' }; + const item = upcastPartial({ + isComplete: true, + response: upcastPartial({ + value: [ + { kind: 'autoModeResolution', router: 'Daily Driver', resolved, effort: 'medium', contextSize: 1_000_000 }, + { kind: 'autoModeResolution', router: 'Daily Driver', resolved, contextSize: 200_000 }, + { kind: 'autoModeResolution', router: 'Daily Driver', resolved }, + ], + }), + }); + + assert.deepStrictEqual(getChatResponsePlaintextParts(item, true).map(part => part.text), [ + 'Daily Driver picked Claude Opus 5.5 \u00b7 Medium effort \u00b7 1M', + 'Daily Driver picked Claude Opus 5.5 \u00b7 200K', + 'Daily Driver picked Claude Opus 5.5', + ]); + }); + + test('reads a model router row for a playbook with the playbook\'s name', () => { + const playbook = { kind: 'autoModeResolution' as const, router: 'Workday', playbook: 'bug-fix', resolved: { id: 'opus', name: 'Claude Opus 5.5' } }; + const item = upcastPartial({ + isComplete: true, + response: upcastPartial({ value: [{ ...playbook, effort: 'medium' }, { ...playbook, defaulted: true }, { ...playbook, kept: true }, { ...playbook, switchedFrom: 'GPT-5.5' }] }), + }); + + assert.deepStrictEqual(getChatResponsePlaintextParts(item, true).map(part => part.text), [ + 'Workday picked its bug-fix playbook on Claude Opus 5.5 \u00b7 Medium effort', + 'Workday used its bug-fix playbook on Claude Opus 5.5, its fallback', + 'Workday stayed on its bug-fix playbook on Claude Opus 5.5', + // A chat that moved to the router from another model has only this line to name the playbook. + 'Workday switched from GPT-5.5 to its bug-fix playbook on Claude Opus 5.5', ]); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts index 9ea9974d61b1..613643b9fbf2 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatCodeblockActions.test.ts @@ -4,12 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { mainWindow } from '../../../../../../base/browser/window.js'; import { DeferredPromise } from '../../../../../../base/common/async.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { isEqual } from '../../../../../../base/common/resources.js'; import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; -import { IDisposable } from '../../../../../../base/common/lifecycle.js'; +import { IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { IActiveCodeEditor } from '../../../../../../editor/browser/editorBrowser.js'; +import { IActiveCodeEditor, ICodeEditor } from '../../../../../../editor/browser/editorBrowser.js'; import { IBulkEditService } from '../../../../../../editor/browser/services/bulkEditService.js'; import { ICodeEditorService } from '../../../../../../editor/browser/services/codeEditorService.js'; import { Selection } from '../../../../../../editor/common/core/selection.js'; @@ -33,7 +35,7 @@ import { CellKind, NOTEBOOK_EDITOR_ID } from '../../../../notebook/common/notebo import { withTestNotebook } from '../../../../notebook/test/browser/testNotebookEditor.js'; import { registerChatCodeBlockActions } from '../../../browser/actions/chatCodeblockActions.js'; import { InsertCodeBlockOperation } from '../../../browser/actions/codeBlockOperations.js'; -import { IChatCodeBlockContextProviderService, IChatWidgetService } from '../../../browser/chat.js'; +import { IChatCodeBlockContextProviderService, IChatCodeBlockInfo, IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; import { ICodeBlockActionContext } from '../../../browser/widget/chatContentParts/codeBlockPart.js'; import { IChatService, IChatUserActionEvent } from '../../../common/chatService/chatService.js'; import { IChatResponseModel } from '../../../common/model/chatModel.js'; @@ -321,3 +323,63 @@ suite('Chat code-block action telemetry', () => { assert.deepStrictEqual({ accepted, userActions }, { accepted: [], userActions: [] }); }); }); + +suite('Chat code-block navigation', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let actions: IDisposable; + suiteSetup(() => actions = registerChatCodeBlockActions()); + suiteTeardown(() => actions.dispose()); + + for (const reverse of [false, true]) { + test(`continues ${reverse ? 'backward' : 'forward'} from preview controls through mixed blocks`, async () => { + const instantiation = store.add(new TestInstantiationService()); + const container = mainWindow.document.createElement('div'); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + const controls = [0, 1, 2].map(() => container.appendChild(mainWindow.document.createElement('button'))); + const model = store.add(createTextModel('const value = 1;')); + const editor = upcastPartial({ getModel: () => model }); + let focusedEditor: ICodeEditor | undefined; + const response = upcastPartial({ id: 'preview-response', setVote: () => { } }); + const otherResponse = upcastPartial({ id: 'other-response', setVote: () => { } }); + const visited: number[] = []; + const revealed: string[] = []; + const blocks: IChatCodeBlockInfo[] = controls.map((control, index) => ({ + ownerMarkdownPartId: 'mixed-blocks', + codeBlockIndex: index, + elementId: response.id, + chatSessionResource: URI.parse('chat-session:/navigation'), + codemapperUri: undefined, + uri: index === 1 ? model.uri : undefined, + get isFocused() { return index !== 1 && mainWindow.document.activeElement === control; }, + focus: () => { + control.focus(); + focusedEditor = index === 1 ? editor : undefined; + visited.push(index); + }, + })); + instantiation.stub(ICodeEditorService, { getFocusedCodeEditor: () => focusedEditor ?? null }); + instantiation.stub(IChatWidgetService, { + lastFocusedWidget: upcastPartial({ + inputEditor: upcastPartial({ hasWidgetFocus: () => false }), + viewModel: upcastPartial({ getItems: () => [response, otherResponse] }), + getFocus: () => otherResponse, + getElementFromNode: node => container.contains(node) ? response : undefined, + getCodeBlockInfoForEditor: uri => isEqual(uri, model.uri) ? blocks[1] : undefined, + getCodeBlockInfosForResponse: item => item === response ? blocks : [], + reveal: item => revealed.push(item.id), + }), + }); + controls[reverse ? 2 : 0].focus(); + const command = CommandsRegistry.getCommand(`workbench.action.chat.${reverse ? 'previous' : 'next'}CodeBlock`); + assert.ok(command); + for (let step = 0; step < 3; step++) { + await command.handler(instantiation); + } + assert.deepStrictEqual({ visited, revealed }, { + visited: reverse ? [1, 0, 2] : [1, 2, 0], + revealed: [response.id, response.id, response.id], + }); + }); + } +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts index f686e1e1d155..028b80506338 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts @@ -29,6 +29,10 @@ import { registerMoveActions } from '../../../browser/actions/chatMoveActions.js import { ChatViewId, ChatViewPaneTarget, IChatWidgetService, IChatWidgetViewContext, IQuickChatService } from '../../../browser/chat.js'; import { ChatWidget } from '../../../browser/widget/chatWidget.js'; import { ChatWidgetService } from '../../../browser/widget/chatWidgetService.js'; +import { IChatViewHostService } from '../../../browser/chatViewHost.js'; +import { IViewDescriptorService } from '../../../../../common/views.js'; +import { IWorkbenchLayoutService } from '../../../../../services/layout/browser/layoutService.js'; +import { ChatViewPaneHost } from '../../../browser/widgetHosts/viewPane/chatViewHostService.js'; import { ChatEditorInput } from '../../../browser/widgetHosts/editor/chatEditorInput.js'; import { ChatViewPane } from '../../../browser/widgetHosts/viewPane/chatViewPane.js'; import { IChatService } from '../../../common/chatService/chatService.js'; @@ -142,6 +146,8 @@ suite('Chat move actions', () => { }), chatService, new NullLogService(), + // The Chat view, as the host of its chats + upcastPartial(new ChatViewPaneHost(viewsService, upcastPartial({}), upcastPartial({}), upcastPartial({}))), )); store.add(widgetService.register(widget)); instantiationService.set(IChatWidgetService, widgetService); diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatOpenActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatOpenActions.test.ts new file mode 100644 index 000000000000..60bce108f8a3 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatOpenActions.test.ts @@ -0,0 +1,215 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { IAgentHostActiveClientService } from '../../../browser/agentSessions/agentHost/agentHostActiveClientService.js'; +import { ServiceIdentifier } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INotificationHandle, INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IChatViewOpenOptions, ModeOpenChatGlobalAction } from '../../../browser/actions/chatActions.js'; +import { IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; +import { IChatRequestVariableEntry } from '../../../common/attachments/chatVariableEntries.js'; +import { IChatViewHostService, IChatViewHostSessionStart } from '../../../browser/chatViewHost.js'; +import { ILogService } from '../../../../../../platform/log/common/log.js'; +import { IEditorGroupsService } from '../../../../../services/editor/common/editorGroupsService.js'; +import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { AgentSessionProviders, AgentSessionsViewerOrientation, IAgentSessionsControl } from '../../../browser/agentSessions/agentSessions.js'; +import { ChatSessionPosition, openChatSessionAndSend } from '../../../browser/chatSessions/chatSessions.contribution.js'; +import { IChatSessionsService } from '../../../common/chatSessionsService.js'; +import { ICustomizationHarnessService } from '../../../common/customizationHarnessService.js'; +import { IAgentHostImportConversationStore } from '../../../browser/agentSessions/agentHost/agentHostImportConversationStore.js'; +import { ILanguageModelToolsService } from '../../../common/tools/languageModelToolsService.js'; +import { ChatMode, IChatMode } from '../../../common/chatModes.js'; +import { ChatConfiguration, ChatModeKind } from '../../../common/constants.js'; +import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { FindAgentSessionInViewerAction, FocusAgentSessionsAction, HideAgentSessionsSidebar, RefreshAgentSessionsViewerAction, SetAgentSessionsOrientationSideBySideAction, SetAgentSessionsOrientationStackedAction, ShowAgentSessionsSidebar, ToggleAgentSessionsSidebar, ToggleShowAgentSessionsAction } from '../../../browser/agentSessions/agentSessionsActions.js'; +import { ContinueInlineChatInChatViewAction } from '../../../../inlineChat/browser/inlineChatActions.js'; +import { CTX_INLINE_CHAT_HAS_AGENT, CTX_INLINE_CHAT_TERMINATED, CTX_INLINE_CHAT_VISIBLE } from '../../../../inlineChat/common/inlineChat.js'; + +import { IChatAgentData, IChatAgentService } from '../../../common/participants/chatAgents.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { IFileService } from '../../../../../../platform/files/common/files.js'; +import { ISCMService } from '../../../../scm/common/scm.js'; +import { IHostService } from '../../../../../services/host/browser/host.js'; +import { ILanguageModelsService } from '../../../common/languageModels.js'; +import { ChatSendResult, IChatService } from '../../../common/chatService/chatService.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; + +suite('Open Chat', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('while the Agents view replaces the Chat view, Open Chat asked for what only local chat serves shows that it is not available, and opens nothing', async () => { + const calls: string[] = []; + const instantiationService = disposables.add(new TestInstantiationService()); + const contextKeyService = new MockContextKeyService(); + contextKeyService.createKey(ChatContextKeys.agentsViewActive.key, true); + instantiationService.stub(IContextKeyService, contextKeyService); + instantiationService.stub(IChatWidgetService, upcastPartial({ + revealWidget: async () => { calls.push('revealWidget'); return undefined; }, + })); + instantiationService.stub(INotificationService, upcastPartial({ info: () => { calls.push('notification'); return upcastPartial({}); } })); + instantiationService.stub(IChatAgentService, upcastPartial({ + getAgentsByName: name => name === 'workspace' ? [upcastPartial({ name })] : [], + getAgentByFullyQualifiedId: () => undefined, + })); + const unrelatedServices: ServiceIdentifier[] = [IChatService, ILanguageModelToolsService, IHostService, ICommandService, IFileService, ILanguageModelsService, ISCMService, IConfigurationService]; + for (const service of unrelatedServices) { + instantiationService.stub(service, {}); + } + const openChat = (mode: IChatMode, opts?: IChatViewOpenOptions) => instantiationService.invokeFunction(accessor => new class extends ModeOpenChatGlobalAction { + constructor() { super(mode); } + }().run(accessor, opts)); + + // A precondition cannot see the arguments, such as the mode or the chat participant a caller asks for + await openChat(ChatMode.Agent, { query: 'refactor this', mode: ChatModeKind.Edit }); + await openChat(ChatMode.Agent, { query: ' @workspace where is the layout?' }); + + // Leading `@` text that names no participant, such as a decorator, is a plain query + await openChat(ChatMode.Agent, { query: '@dataclass\nclass Point: ...' }); + + assert.deepStrictEqual(calls, ['notification', 'notification', 'revealWidget']); + }); + + test('a session opened in the Chat view starts, moves and completes in the host of the Chat view\'s chats, which holds what it needs until the start ends, and gets back a request it does not show', async () => { + const calls: unknown[] = []; + const instantiationService = disposables.add(new TestInstantiationService()); + let sendKind: 'sent' | 'failed' = 'sent'; + let startFails = false; + let composerAvailable = true; + const prepared = URI.from({ scheme: AgentSessionProviders.AgentHostCopilot, path: '/untitled-prepared' }); + const materialized = URI.from({ scheme: AgentSessionProviders.AgentHostCopilot, path: '/session-1' }); + const composer = upcastPartial({ + setInput: (query?: string) => { calls.push({ composerInput: query }); }, + attachmentModel: upcastPartial({ addContext: (...entries: IChatRequestVariableEntry[]) => { calls.push({ composerContext: entries.map(entry => entry.id) }); } }), + }); + // A host that shows only sessions whose request ran, such as the Agents view, and holds the session's model meanwhile + instantiationService.stub(IChatViewHostService, upcastPartial({ + startSession: async (resource, options) => { + calls.push({ start: resource.toString(), local: options.local }); + if (startFails) { + throw new Error('cannot show'); + } + calls.push('hold'); + return upcastPartial({ + moved: async moved => { calls.push({ moved: moved.toString() }); }, + complete: async (completed, sent) => { calls.push({ complete: completed.toString(), sent }); return sent; }, + createComposer: async () => { calls.push('composer'); return composerAvailable ? composer : undefined; }, + dispose: () => { calls.push('release'); }, + }); + }, + })); + instantiationService.stub(IChatService, upcastPartial({ + sendRequest: async (resource, prompt) => { + calls.push({ send: prompt, to: resource.toString() }); + if (sendKind === 'failed') { + throw new Error('send failed'); + } + return upcastPartial({ kind: 'sent', newSessionResource: materialized }); + }, + })); + instantiationService.stub(INotificationService, upcastPartial({ + warn: () => { calls.push('requestRestoredNotice'); return upcastPartial({}); }, + error: () => { calls.push('requestNotSentError'); return upcastPartial({}); }, + })); + instantiationService.stub(IAgentHostImportConversationStore, upcastPartial({ take: () => { calls.push('importDropped'); return undefined; } })); + instantiationService.stub(IAgentHostActiveClientService, upcastPartial({ + setSessionTools: () => { }, moveSessionTools: () => { }, clearSessionTools: () => { }, + })); + instantiationService.stub(ILogService, upcastPartial({ error: () => { } })); + const services: ServiceIdentifier[] = [IChatSessionsService, IEditorGroupsService, IEditorService, ICustomizationHarnessService, ILanguageModelToolsService]; + for (const service of services) { + instantiationService.stub(service, {}); + } + const open = (type: string, sessionResource?: URI, chatSendOptions?: Parameters[2]) => instantiationService.invokeFunction(accessor => openChatSessionAndSend(accessor, { type, displayName: type, position: ChatSessionPosition.Sidebar, sessionResource }, chatSendOptions)); + const plain = { prompt: 'review this', attachedContext: [upcastPartial({ id: 'file' })] }; + const start = { start: prepared.toString(), local: false }; + const send = { send: 'review this', to: prepared.toString() }; + const steps: Record = {}; + const run = async (name: string, ...args: Parameters) => { const result = await open(...args); steps[name] = { result, calls: calls.splice(0) }; }; + + await run('sent', AgentSessionProviders.AgentHostCopilot, prepared, plain); + sendKind = 'failed'; + await run('restored', AgentSessionProviders.AgentHostCopilot, prepared, plain); + await run('withTools', AgentSessionProviders.AgentHostCopilot, prepared, { ...plain, sessionToolIds: ['report'] }); + composerAvailable = false; + await run('noComposer', AgentSessionProviders.AgentHostCopilot, prepared, plain); + await run('opened', AgentSessionProviders.AgentHostCopilot, prepared); + startFails = true; + await run('notShown', AgentSessionProviders.AgentHostCopilot, prepared, plain); + + assert.deepStrictEqual(steps, { + sent: { result: { resource: materialized, sendOutcome: 'sent' }, calls: [start, 'hold', send, { moved: materialized.toString() }, { complete: materialized.toString(), sent: true }, 'release'] }, + // A request of only a prompt and attachments that did not run stays in the input of a new session, to send again + restored: { + result: { resource: prepared, sendOutcome: 'failed' }, + calls: [start, 'hold', send, { complete: prepared.toString(), sent: false }, 'importDropped', 'composer', { composerInput: 'review this' }, { composerContext: ['file'] }, 'requestRestoredNotice', 'release'], + }, + // One with tools would start a different session from a composer: it only says it was not sent + withTools: { result: { resource: prepared, sendOutcome: 'failed' }, calls: [start, 'hold', send, { complete: prepared.toString(), sent: false }, 'importDropped', 'requestNotSentError', 'release'] }, + noComposer: { result: { resource: prepared, sendOutcome: 'failed' }, calls: [start, 'hold', send, { complete: prepared.toString(), sent: false }, 'importDropped', 'composer', 'requestNotSentError', 'release'] }, + opened: { result: { resource: prepared, sendOutcome: 'none' }, calls: [start, 'hold', { complete: prepared.toString(), sent: false }, 'release'] }, + // A host that cannot show it opens nothing and sends nothing + notShown: { result: undefined, calls: [start] }, + }); + }); + + test('Refresh and Find act on the sessions control they are given, also while the Agents view replaces the Chat view', async () => { + const calls: string[] = []; + const instantiationService = disposables.add(new TestInstantiationService()); + const control = upcastPartial({ refresh: () => { calls.push('refresh'); }, openFind: () => { calls.push('find'); } }); + const actions = [new RefreshAgentSessionsViewerAction(), new FindAgentSessionInViewerAction()]; + + for (const action of actions) { + await instantiationService.invokeFunction(accessor => action.run(accessor, control)); + } + + // Only the Chat view's sessions toolbar offers them, with its control: they are not gated on the Chat view showing + assert.deepStrictEqual({ calls, preconditions: actions.map(action => action.desc.precondition) }, { calls: ['refresh', 'find'], preconditions: [undefined, undefined] }); + }); + + test('while the Agents view replaces the Chat view, what needs local chat or the Chat view\'s sessions is not enabled', () => { + const modeAction = (mode: IChatMode) => new class extends ModeOpenChatGlobalAction { + constructor() { super(mode); } + }(); + const preconditions = { + openAsk: modeAction(ChatMode.Ask).desc.precondition, + openEdit: modeAction(ChatMode.Edit).desc.precondition, + openAgent: modeAction(ChatMode.Agent).desc.precondition, + askInChat: new ContinueInlineChatInChatViewAction().desc.precondition, + showSessions: new ToggleShowAgentSessionsAction().desc.precondition, + orientationStacked: new SetAgentSessionsOrientationStackedAction().desc.precondition, + orientationSideBySide: new SetAgentSessionsOrientationSideBySideAction().desc.precondition, + showSidebar: new ShowAgentSessionsSidebar().desc.precondition, + hideSidebar: new HideAgentSessionsSidebar().desc.precondition, + toggleSidebar: new ToggleAgentSessionsSidebar().desc.precondition, + focusSessions: new FocusAgentSessionsAction().desc.precondition, + }; + const enabled = (agentsViewActive: boolean, orientation: number) => { + const values: Record = { + [ChatContextKeys.enabled.key]: true, + [CTX_INLINE_CHAT_HAS_AGENT.key]: true, + [CTX_INLINE_CHAT_VISIBLE.key]: true, + [CTX_INLINE_CHAT_TERMINATED.key]: true, + [`config.${ChatConfiguration.ChatViewSessionsEnabled}`]: true, + [ChatContextKeys.agentSessionsViewerOrientation.key]: orientation, + [ChatContextKeys.agentsViewActive.key]: agentsViewActive, + }; + const context = { getValue: (key: string) => values[key] as T }; + return Object.fromEntries(Object.entries(preconditions).map(([name, precondition]) => [name, precondition?.evaluate(context) ?? true])); + }; + const all = (value: boolean) => Object.fromEntries(Object.keys(preconditions).map(name => [name, value])); + + // Show and Hide Agent Sessions Sidebar are each enabled in one orientation: both are checked in the one they need + const chatView = { ...enabled(false, AgentSessionsViewerOrientation.Stacked), hideSidebar: enabled(false, AgentSessionsViewerOrientation.SideBySide).hideSidebar }; + const agentsView = { ...enabled(true, AgentSessionsViewerOrientation.Stacked), hideSidebar: enabled(true, AgentSessionsViewerOrientation.SideBySide).hideSidebar }; + assert.deepStrictEqual({ chatView, agentsView }, { chatView: all(true), agentsView: { ...all(false), openAgent: true } }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatPluginActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatPluginActions.test.ts index 401998717160..71af49084ed6 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatPluginActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatPluginActions.test.ts @@ -18,6 +18,7 @@ import { CustomizationMarketplaceConfiguration } from '../../../../../../platfor import { IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; import { IFileService } from '../../../../../../platform/files/common/files.js'; import { INotification, INotificationHandle, INotificationService, Severity } from '../../../../../../platform/notification/common/notification.js'; +import { IProgress, IProgressService, IProgressStep, ProgressLocation } from '../../../../../../platform/progress/common/progress.js'; import { IInputBox, IPickOptions, IQuickInputButton, IQuickInputHideEvent, IQuickInputService, IQuickPick, IQuickPickDidAcceptEvent, IQuickPickItem, QuickInputHideReason, QuickPickInput } from '../../../../../../platform/quickinput/common/quickInput.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; import { AddPluginMarketplaceAction, InstallFromSourceAction, ManagePluginMarketplacesAction } from '../../../browser/actions/chatPluginActions.js'; @@ -66,7 +67,19 @@ suite('InstallFromSourceAction', () => { const localInstalls: string[] = []; const validations: string[] = []; const notifications: Parameters[0][] = []; + const progress: { options: Parameters[0]; active: boolean }[] = []; const commands: { id: string; args: unknown[] }[] = []; + instantiationService.stub(IProgressService, new class extends mock() { + override async withProgress(options: Parameters[0], task: (progress: IProgress) => Promise): Promise { + const entry = { options, active: true }; + progress.push(entry); + try { + return await task({ report() { } }); + } finally { + entry.active = false; + } + } + }()); instantiationService.stub(ICommandService, new class extends mock() { override async executeCommand(id: string, ...args: unknown[]): Promise { commands.push({ id, args }); @@ -106,9 +119,67 @@ suite('InstallFromSourceAction', () => { } }()); const result = instantiationService.invokeFunction(accessor => new InstallFromSourceAction().run(accessor, { skipReveal: options.skipReveal ?? true })); - return { inputBox, acceptEmitter, showEmitter, result, localInstalls, validations, notifications, commands, session, activeSessionResource, harnesses }; + return { inputBox, acceptEmitter, showEmitter, result, localInstalls, validations, notifications, progress, commands, session, activeSessionResource, harnesses }; } + test('shows progress throughout a provider-owned source installation before revealing the plugin', async () => { + const installation = new DeferredPromise(); + const fixture = createFixture({ installFromSource: () => installation.p }, undefined, { skipReveal: false }); + fixture.inputBox.value = 'owner/repo'; + fixture.acceptEmitter.fire(); + + assert.deepStrictEqual({ progress: fixture.progress, commands: fixture.commands }, { + progress: [{ + options: { location: ProgressLocation.Notification, title: 'Installing plugin from source...', cancellable: false }, + active: true, + }], + commands: [], + }); + + await installation.complete(); + assert.deepStrictEqual({ installed: await fixture.result, active: fixture.progress.map(entry => entry.active), commands: fixture.commands.map(command => command.id) }, { + installed: true, + active: [false], + commands: [AICustomizationManagementCommands.OpenEditor], + }); + }); + + test('closes provider installation progress on failure and allows retrying', async () => { + const installation = new DeferredPromise(); + let attempts = 0; + const fixture = createFixture({ + installFromSource: async () => { + if (++attempts === 1) { + await installation.p; + } + }, + }); + const shown = Event.toPromise(fixture.showEmitter.event); + fixture.inputBox.value = 'owner/repo'; + fixture.acceptEmitter.fire(); + await installation.error(new Error('Cannot install plugin')); + await shown; + const failureState = { + active: fixture.progress.map(entry => entry.active), + notifications: [...fixture.notifications], + enabled: fixture.inputBox.enabled, + busy: fixture.inputBox.busy, + }; + fixture.acceptEmitter.fire(); + + assert.deepStrictEqual({ failureState, installed: await fixture.result, attempts, active: fixture.progress.map(entry => entry.active) }, { + failureState: { + active: [false], + notifications: ['Failed to install plugin: Cannot install plugin'], + enabled: true, + busy: false, + }, + installed: true, + attempts: 2, + active: [false, false], + }); + }); + test('reveals the installed plugin in Chat Customizations for the installing session', async () => { const installedUri = URI.file('/plugins/example'); const fixture = createFixture(undefined, { success: true, installedUri }, { skipReveal: false }); @@ -969,7 +1040,7 @@ suite('ManagePluginMarketplacesAction', () => { test('keeps the provider input busy and shows errors inline for correction and retry', async () => { const pending = new DeferredPromise(); - const addCalls: { session: URI; source: string }[] = []; + const addCalls: { session: URI | undefined; source: string }[] = []; const provider: ICustomizationMarketplaceManagementProvider = { onDidChange: Event.None, onDidChangeMarketplaces: Event.None, diff --git a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostEditReview.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostEditReview.test.ts index 3fda8453d250..67459c600dcc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostEditReview.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostEditReview.test.ts @@ -17,6 +17,7 @@ import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js' import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { EditOperation } from '../../../../../../editor/common/core/editOperation.js'; import { Position } from '../../../../../../editor/common/core/position.js'; +import { Range } from '../../../../../../editor/common/core/range.js'; import { IDocumentDiff, IDocumentDiffProviderOptions } from '../../../../../../editor/common/diff/documentDiffProvider.js'; import { ITextModel } from '../../../../../../editor/common/model.js'; import { DiffAlgorithmName, IEditorWorkerService } from '../../../../../../editor/common/services/editorWorker.js'; @@ -170,7 +171,7 @@ suite('AgentHostEditReview', () => { /** How long diffs take. */ let diffDelay: number; let diffGate: { started: DeferredPromise; release: DeferredPromise } | undefined; - let stringDiffGate: { started: DeferredPromise; release: DeferredPromise } | undefined; + let stringDiffGate: { started: DeferredPromise; release: DeferredPromise; when?: (original: string, modified: string) => boolean } | undefined; let stringDiffCoarse: boolean; let version: number; /** The diff editors that are open. */ @@ -290,6 +291,27 @@ suite('AgentHostEditReview', () => { diffEditors.push({ editor: store.add(new DiffEditorInput(undefined, undefined, original, modified, undefined, editorService)), groupId: 1 }); } + class TestDelayedWorkerService extends TestWorkerService { + override async computeStringEditFromDiffWithMetadata(...args: Parameters) { + const result = await computeStringDiffWithMetadata(...args); + if (stringDiffGate && (!stringDiffGate.when || stringDiffGate.when(args[0], args[1]))) { + stringDiffGate.started.complete(); + await stringDiffGate.release.p; + } + return { ...result, isCoarse: stringDiffCoarse || result.isCoarse }; + } + override async computeDiff(original: URI, modified: URI, options: IDocumentDiffProviderOptions, algorithm: DiffAlgorithmName): Promise { + if (diffGate) { + diffGate.started.complete(); + await diffGate.release.p; + } + if (diffDelay) { + await timeout(diffDelay); + } + return super.computeDiff(original, modified, options, algorithm); + } + } + async function useRealTextFiles(content: string) { review.dispose(); const files = store.add(new class extends FileService { @@ -325,11 +347,7 @@ suite('AgentHostEditReview', () => { override warn(message: string) { errors.push(message); warning.fire(message); } override error(message: string) { errors.push(message); } }()); - instantiation.stub(IEditorWorkerService, store.add(instantiation.createInstance(class extends TestWorkerService { - override computeStringEditFromDiffWithMetadata(...args: Parameters) { - return computeStringDiffWithMetadata(...args); - } - }))); + instantiation.stub(IEditorWorkerService, store.add(instantiation.createInstance(TestDelayedWorkerService))); const service = instantiation.get(ITextFileService); store.add(service.files.retainResolvedContent()); await files.writeFile(URI.file('/dirty.ts'), VSBuffer.fromString(content)); @@ -373,27 +391,6 @@ suite('AgentHostEditReview', () => { store.add(host.onDidChangeWorkingSet); store.add(host.onDidErrorWorkingSet); - class TestDelayedWorkerService extends TestWorkerService { - override async computeStringEditFromDiffWithMetadata(...args: Parameters) { - const result = await computeStringDiffWithMetadata(...args); - if (stringDiffGate) { - stringDiffGate.started.complete(); - await stringDiffGate.release.p; - } - return { ...result, isCoarse: stringDiffCoarse || result.isCoarse }; - } - override async computeDiff(original: URI, modified: URI, options: IDocumentDiffProviderOptions, algorithm: DiffAlgorithmName): Promise { - if (diffGate) { - diffGate.started.complete(); - await diffGate.release.p; - } - if (diffDelay) { - await timeout(diffDelay); - } - return super.computeDiff(original, modified, options, algorithm); - } - } - const collection = new ServiceCollection(); collection.set(IAgentHostConnectionsService, new class extends mock() { override readonly onDidChangeSessionResolution = Event.None; @@ -1246,6 +1243,480 @@ suite('AgentHostEditReview', () => { assert.deepStrictEqual({ original: entry.originalModel.getValue(), changes: await getChanges(entry) }, { original: 'one\ntwo\nXthree\nfour\n', changes: ['[4,5)'] }); }); + for (const eol of ['\n', '\r\n']) { + test(`a disk reload and editor undo/redo keep pulled changes outside the agent edit out of review (${JSON.stringify(eol)})`, async () => { + const baseline = ['first', 'unchanged before', 'middle', 'unchanged after', 'last', ''].join(eol); + const current = ['first', 'unchanged before', 'MIDDLE', 'unchanged after', 'last', ''].join(eol); + const pulled = ['FIRST', 'unchanged before', 'MIDDLE', 'unchanged after', 'LAST', ''].join(eol); + const pulledOriginal = ['FIRST', 'unchanged before', 'middle', 'unchanged after', 'LAST', ''].join(eol); + const { model, files } = await useRealTextFiles(current); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const entry = getEntry('/dirty.ts'); + await getChanges(entry); + const describe = async () => ({ + changes: await getChanges(entry), + original: entry.originalModel.getValue(), + text: model.textEditorModel.getValue(), + dirty: model.isDirty(), + }); + + await files.writeFile(model.resource, VSBuffer.fromString(pulled)); + await model.resolve({ forceReadFromFile: true }); + await review.resolveEntry(model.resource); + const afterPull = await describe(); + + await model.textEditorModel.undo(); + await review.resolveEntry(model.resource); + const afterUndo = await describe(); + + await model.textEditorModel.redo(); + await review.resolveEntry(model.resource); + const afterRedo = await describe(); + + assert.deepStrictEqual({ afterPull, afterUndo, afterRedo, invoked: host.invoked, errors }, { + afterPull: { changes: ['[3,4)'], original: pulledOriginal, text: pulled, dirty: false }, + afterUndo: { changes: ['[3,4)'], original: baseline, text: current, dirty: true }, + afterRedo: { changes: ['[3,4)'], original: pulledOriginal, text: pulled, dirty: false }, + invoked: [], + errors: [], + }); + }); + } + + test('keeps reviewing a file whose changes are stashed and restored outside the session', async () => { + hostWrites('/a.ts', 'A\nb\n'); + host.setWorkingSet([workingSetFile('/a.ts', 'a\nb\n', 'A\nb\n', 'tc1')]); + await waitForEntries('/a.ts'); + const entry = getEntry('/a.ts'); + const describe = async () => { + await review.resolveEntry(entry.modifiedURI); + return { state: entry.state.get(), changes: await getChanges(entry), reviewing: getEntry('/a.ts') === entry }; + }; + const shown = await describe(); + + // Like `git stash`, which the session doesn't record. + hostWrites('/a.ts', 'a\nb\n'); + const stashed = await describe(); + + // Like `git stash pop`. + hostWrites('/a.ts', 'A\nb\n'); + const restored = await describe(); + + assert.deepStrictEqual({ shown, stashed, restored, invoked: host.invoked, errors }, { + shown: { state: ModifiedFileEntryState.Modified, changes: ['[1,2)'], reviewing: true }, + stashed: { state: ModifiedFileEntryState.Modified, changes: [], reviewing: true }, + restored: { state: ModifiedFileEntryState.Modified, changes: ['[1,2)'], reviewing: true }, + invoked: [], + errors: [], + }); + }); + + test('keeps reviewing changes after the user undoes and redoes the reload of the agent edit', async () => { + const baseline = 'first\nmiddle\nlast\n'; + const current = 'first\nMIDDLE\nlast\n'; + const { model, files } = await useRealTextFiles(baseline); + // The document is open when the agent writes the file, and reloads it. + await files.writeFile(model.resource, VSBuffer.fromString(current)); + await model.resolve({ forceReadFromFile: true }); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const entry = getEntry('/dirty.ts'); + const describe = async () => { + await review.resolveEntry(model.resource); + return { state: entry.state.get(), changes: await getChanges(entry), text: model.textEditorModel.getValue() }; + }; + const shown = await describe(); + + await model.textEditorModel.undo(); + const afterUndo = await describe(); + + await model.textEditorModel.redo(); + const afterRedo = await describe(); + + assert.deepStrictEqual({ shown, afterUndo, afterRedo, invoked: host.invoked, errors }, { + shown: { state: ModifiedFileEntryState.Modified, changes: ['[2,3)'], text: current }, + afterUndo: { state: ModifiedFileEntryState.Modified, changes: [], text: baseline }, + afterRedo: { state: ModifiedFileEntryState.Modified, changes: ['[2,3)'], text: current }, + invoked: [], + errors: [], + }); + }); + + for (const otherAgentEdit of [false, true]) { + test(`undo/redo preserves user text adjacent to a removed agent edit (other agent edit: ${otherAgentEdit})`, async () => { + const suffix = otherAgentEdit ? 'unchanged\nlast\n' : ''; + const modifiedSuffix = otherAgentEdit ? 'unchanged\nLAST\n' : ''; + const baseline = `start\nend\n${suffix}`; + const current = `start\nAAA\nend\n${modifiedSuffix}`; + const { model } = await useRealTextFiles(current); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const entry = getEntry('/dirty.ts'); + await getChanges(entry); + + model.textEditorModel.pushEditOperations(null, [EditOperation.insert(new Position(3, 1), 'ZZZ\n')], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(entry); + const originalWithUserText = entry.originalModel.getValue(); + + model.textEditorModel.pushEditOperations(null, [EditOperation.delete(new Range(2, 1, 3, 1))], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(entry); + await model.textEditorModel.undo(); + await review.resolveEntry(model.resource); + await getChanges(entry); + await model.textEditorModel.redo(); + await review.resolveEntry(model.resource); + + assert.deepStrictEqual({ + originalWithUserText, + original: entry.originalModel.getValue(), + text: model.textEditorModel.getValue(), + changes: await getChanges(entry), + dirty: model.isDirty(), + invoked: host.invoked, + errors, + }, { + originalWithUserText: `start\nZZZ\nend\n${suffix}`, + original: `start\nZZZ\nend\n${suffix}`, + text: `start\nZZZ\nend\n${modifiedSuffix}`, + changes: otherAgentEdit ? ['[5,6)'] : [], + dirty: true, + invoked: [], + errors: [], + }); + }); + } + + test('a broad disk reload preserves adjacent user text already tracked in the review baseline', async () => { + const baseline = 'first\nstart\nend\nunchanged\nmiddle\nunchanged after\nlast\n'; + const current = 'first\nstart\nAAA\nend\nunchanged\nMIDDLE\nunchanged after\nlast\n'; + const { model, files } = await useRealTextFiles(current); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const entry = getEntry('/dirty.ts'); + await getChanges(entry); + + model.textEditorModel.pushEditOperations(null, [EditOperation.insert(new Position(4, 1), 'ZZZ\n')], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(entry); + model.textEditorModel.pushEditOperations(null, [EditOperation.delete(new Range(3, 1, 4, 1))], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(entry); + await model.save({ skipSaveParticipants: true, ignoreErrorHandler: true }); + + const pulled = 'FIRST\nstart\nZZZ\nend\nunchanged\nMIDDLE\nunchanged after\nLAST\n'; + await files.writeFile(model.resource, VSBuffer.fromString(pulled)); + await model.resolve({ forceReadFromFile: true }); + await review.resolveEntry(model.resource); + const afterPull = { original: entry.originalModel.getValue(), changes: await getChanges(entry) }; + await model.textEditorModel.undo(); + await review.resolveEntry(model.resource); + const afterUndo = { original: entry.originalModel.getValue(), changes: await getChanges(entry) }; + await model.textEditorModel.redo(); + await review.resolveEntry(model.resource); + const afterRedo = { original: entry.originalModel.getValue(), changes: await getChanges(entry) }; + + assert.deepStrictEqual({ afterPull, afterUndo, afterRedo, text: model.textEditorModel.getValue(), dirty: model.isDirty(), errors }, { + afterPull: { original: 'FIRST\nstart\nZZZ\nend\nunchanged\nmiddle\nunchanged after\nLAST\n', changes: ['[6,7)'] }, + afterUndo: { original: 'first\nstart\nZZZ\nend\nunchanged\nmiddle\nunchanged after\nlast\n', changes: ['[6,7)'] }, + afterRedo: { original: 'FIRST\nstart\nZZZ\nend\nunchanged\nmiddle\nunchanged after\nLAST\n', changes: ['[6,7)'] }, + text: pulled, + dirty: false, + errors: [], + }); + }); + + for (const retainedText of ['z', '']) { + test(`reload refinement preserves inline user text and deleted separators (${JSON.stringify(retainedText)})`, async () => { + const separator = retainedText ? '' : '-'; + const baseline = `before${separator}after\nunchanged\nlast\nunchanged after\ntail\n`; + const current = `beforeXXX${separator}after\nunchanged\nLAST\nunchanged after\ntail\n`; + const { model, files } = await useRealTextFiles(current); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const entry = getEntry('/dirty.ts'); + await getChanges(entry); + + model.textEditorModel.pushEditOperations(null, [EditOperation.replace(new Range(1, 10, 1, 10 + separator.length), retainedText)], () => null); + await getChanges(entry); + model.textEditorModel.pushEditOperations(null, [EditOperation.delete(new Range(1, 7, 1, 10))], () => null); + await getChanges(entry); + await model.save({ skipSaveParticipants: true, ignoreErrorHandler: true }); + const tracked = entry.originalModel.getValue(); + + const pulled = retainedText ? 'BEFOREzAFTER\nunchanged\nLAST\nunchanged after\nTAIL\n' : 'beforeYafter\nunchanged\nLAST\nunchanged after\nTAIL\n'; + await files.writeFile(model.resource, VSBuffer.fromString(pulled)); + await model.resolve({ forceReadFromFile: true }); + await review.resolveEntry(model.resource); + + assert.deepStrictEqual({ + tracked, + original: entry.originalModel.getValue(), + text: model.textEditorModel.getValue(), + dirty: model.isDirty(), + errors, + }, { + tracked: `before${retainedText}after\nunchanged\nlast\nunchanged after\ntail\n`, + original: `before${retainedText}after\nunchanged\nlast\nunchanged after\nTAIL\n`, + text: pulled, + dirty: false, + errors: [], + }); + }); + } + + test('a suspended review retains adjacent user text through save recovery', async () => { + const baseline = 'start\nend\nunchanged\nlast\n'; + const current = 'start\nAAA\nend\nunchanged\nLAST\n'; + const { model, files, type } = await useRealTextFiles(current); + const file = workingSetFile('/dirty.ts', baseline, current, 'tc1'); + host.setWorkingSet([file]); + await waitForEntries('/dirty.ts'); + const previousEntry = getEntry('/dirty.ts'); + await getChanges(previousEntry); + + model.textEditorModel.pushEditOperations(null, [EditOperation.insert(new Position(3, 1), 'ZZZ\n')], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(previousEntry); + model.textEditorModel.pushEditOperations(null, [EditOperation.delete(new Range(2, 1, 3, 1))], () => null); + model.textEditorModel.pushStackElement(); + await getChanges(previousEntry); + await model.textEditorModel.undo(); + await review.resolveEntry(model.resource); + await getChanges(previousEntry); + + stringDiffCoarse = true; + const gate = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise() }; + await model.textEditorModel.redo(); + await gate.started.p; + await getChanges(previousEntry); + stringDiffGate = undefined; + gate.release.complete(); + await review.resolveEntry(model.resource); + const suspended = { entries: review.entries.get().length, text: model.textEditorModel.getValue() }; + + type(); + stringDiffCoarse = false; + await model.save({ skipSaveParticipants: true, ignoreErrorHandler: true }); + await review.resolveEntry(model.resource); + const recovered = getEntry('/dirty.ts'); + const afterRecovery = { original: recovered.originalModel.getValue(), changes: await getChanges(recovered) }; + host.setWorkingSet([]); + await review.resolveEntry(model.resource); + + assert.deepStrictEqual({ + suspended, + afterRecovery, + disk: (await files.readFile(model.resource)).value.toString(), + released: recovered.originalModel.isDisposed(), + warnings: errors.length, + }, { + suspended: { entries: 0, text: 'start\nZZZ\nend\nunchanged\nLAST\n' }, + afterRecovery: { original: 'start\nuser ZZZ\nend\nunchanged\nlast\n', changes: ['[5,6)'] }, + disk: 'start\nuser ZZZ\nend\nunchanged\nLAST\n', + released: true, + warnings: 1, + }); + }); + + for (const replacement of [false, true]) { + test(`a suspended review follows removal or replacement of its Working Set file (replacement: ${replacement})`, async () => { + hostWrites('/a.ts', 'ONE\nmiddle\nlast\n'); + const file = workingSetFile('/a.ts', 'one\nmiddle\nlast\n', 'ONE\nmiddle\nlast\n', 'tc1'); + host.setWorkingSet([file]); + await review.resolveEntry(URI.file('/a.ts')); + const entry = getEntry('/a.ts'); + await getChanges(entry); + stringDiffCoarse = true; + const gate = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise() }; + hostWrites('/a.ts', 'ONE\nmiddle\nLAST\n'); + await gate.started.p; + await getChanges(entry); + stringDiffGate = undefined; + gate.release.complete(); + await review.resolveEntry(entry.modifiedURI); + const suspendedEntries = review.entries.get().length; + + stringDiffCoarse = false; + if (replacement) { + host.setWorkingSet([{ ...file, isEditing: true }]); + hostWrites('/a.ts', 'ONE\nMIDDLE\nLAST\n'); + host.setWorkingSet([workingSetFile('/a.ts', 'ONE\nmiddle\nLAST\n', 'ONE\nMIDDLE\nLAST\n', 'tc2')]); + } else { + host.setWorkingSet([]); + } + await review.resolveEntry(entry.modifiedURI); + const recovered = getEntry('/a.ts'); + const afterUpdate = recovered ? { original: recovered.originalModel.getValue(), changes: await getChanges(recovered) } : undefined; + if (recovered) { + await review.accept(); + } + review.dispose(); + + assert.deepStrictEqual({ suspendedEntries, afterUpdate, released: entry.originalModel.isDisposed(), invoked: host.invoked, warnings: errors.length }, { + suspendedEntries: 0, + afterUpdate: replacement ? { original: 'ONE\nmiddle\nLAST\n', changes: ['[2,3)'] } : undefined, + released: true, + invoked: replacement ? ['keep /a.ts @tc2'] : [], + warnings: 1, + }); + }); + } + + for (const spansAgentEdit of [false, true]) { + test(`an imprecise disk reload comparison suspends review and recovers after saving (spans agent edit: ${spansAgentEdit})`, async () => { + const baseline = 'first\nunchanged before\nmiddle\nunchanged after\nlast\n'; + const current = 'first\nunchanged before\nMIDDLE\nunchanged after\nlast\n'; + const last = spansAgentEdit ? 'LAST' : 'last'; + const pulled = `FIRST\nunchanged before\nMIDDLE\nunchanged after\n${last}\n`; + const { model, files, type } = await useRealTextFiles(current); + host.setWorkingSet([workingSetFile('/dirty.ts', baseline, current, 'tc1')]); + await waitForEntries('/dirty.ts'); + const previousEntry = getEntry('/dirty.ts'); + await getChanges(previousEntry); + + stringDiffCoarse = true; + const gate = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise() }; + await files.writeFile(model.resource, VSBuffer.fromString(pulled)); + await model.resolve({ forceReadFromFile: true }); + await gate.started.p; + await getChanges(previousEntry); + stringDiffGate = undefined; + gate.release.complete(); + await review.resolveEntry(model.resource); + const suspended = { entries: review.entries.get().length, text: model.textEditorModel.getValue(), dirty: model.isDirty() }; + await review.reject(); + + stringDiffCoarse = false; + type(); + await model.save({ skipSaveParticipants: true, ignoreErrorHandler: true }); + await review.resolveEntry(model.resource); + const entry = getEntry('/dirty.ts'); + + assert.deepStrictEqual({ + suspended, + recovered: { changes: await getChanges(entry), original: entry.originalModel.getValue(), text: model.textEditorModel.getValue(), dirty: model.isDirty() }, + disk: (await files.readFile(model.resource)).value.toString(), + invoked: host.invoked, + errors, + }, { + suspended: { entries: 0, text: pulled, dirty: false }, + recovered: { + changes: ['[3,4)'], + original: `FIRST\nuser unchanged before\nmiddle\nunchanged after\n${last}\n`, + text: `FIRST\nuser unchanged before\nMIDDLE\nunchanged after\n${last}\n`, + dirty: false, + }, + disk: `FIRST\nuser unchanged before\nMIDDLE\nunchanged after\n${last}\n`, + invoked: [], + errors: ['Could not update editor review for \'dirty.ts\': The file\'s changes could not be compared precisely. Your text has been preserved. Resolve the file\'s changes and save or revert it to resume editor review.'], + }); + }); + } + + test('a disk reload refresh preserves subsequent reloads and typing while its diff is pending', async () => { + const baseline = 'first\nunchanged before\nmiddle\nunchanged after\nlast\n'; + const current = 'first\nunchanged before\nMIDDLE\nunchanged after\nlast\n'; + hostWrites('/a.ts', current); + host.setWorkingSet([workingSetFile('/a.ts', baseline, current, 'tc1')]); + await settle(); + const entry = getEntry('/a.ts'); + await getChanges(entry); + const gate = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise() }; + + modelService.updateModel(entry.modifiedModel, 'FIRST\nunchanged before\nMIDDLE\nunchanged after\nlast\n', EditSources.reloadFromDisk()); + await gate.started.p; + modelService.updateModel(entry.modifiedModel, 'FIRST\nunchanged before\nMIDDLE\nunchanged after\nLAST\n', EditSources.reloadFromDisk()); + userTypes('/a.ts', 2, 1, 'user '); + stringDiffGate = undefined; + gate.release.complete(); + await review.resolveEntry(entry.modifiedURI); + + assert.deepStrictEqual({ + changes: await getChanges(entry), + original: entry.originalModel.getValue(), + text: entry.modifiedModel.getValue(), + invoked: host.invoked, + errors, + }, { + changes: ['[3,4)'], + original: 'FIRST\nuser unchanged before\nmiddle\nunchanged after\nLAST\n', + text: 'FIRST\nuser unchanged before\nMIDDLE\nunchanged after\nLAST\n', + invoked: [], + errors: [], + }); + }); + + test('a superseded reload comparison retries without suspending review', async () => { + const baseline = 'first\nunchanged before\nmiddle\nunchanged after\nlast\n'; + const current = 'first\nunchanged before\nMIDDLE\nunchanged after\nlast\n'; + hostWrites('/a.ts', current); + host.setWorkingSet([workingSetFile('/a.ts', baseline, current, 'tc1')]); + await review.resolveEntry(URI.file('/a.ts')); + const entry = getEntry('/a.ts'); + await getChanges(entry); + + const when = (original: string, modified: string) => original === baseline && modified === current; + const first = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise(), when }; + modelService.updateModel(entry.modifiedModel, 'FIRST\nunchanged before\nMIDDLE\nunchanged after\nLAST\n', EditSources.reloadFromDisk()); + await first.started.p; + await getChanges(entry); + userTypes('/a.ts', 2, 1, 'one '); + const second = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise(), when }; + first.release.complete(); + await second.started.p; + await getChanges(entry); + userTypes('/a.ts', 2, 1, 'two '); + await getChanges(entry); + stringDiffGate = undefined; + second.release.complete(); + await review.resolveEntry(entry.modifiedURI); + await review.resolveEntry(entry.modifiedURI); + + assert.deepStrictEqual({ + sameEntry: getEntry('/a.ts') === entry, + original: entry.originalModel.isDisposed() ? undefined : entry.originalModel.getValue(), + changes: entry.originalModel.isDisposed() ? undefined : await getChanges(entry), + errors, + }, { + sameEntry: true, + original: 'FIRST\ntwo one unchanged before\nmiddle\nunchanged after\nLAST\n', + changes: ['[3,4)'], + errors: [], + }); + }); + + test('a disk reload refresh cannot overwrite newer agent edits published while its diff is pending', async () => { + const baseline = 'first\nunchanged before\nmiddle\nunchanged after\nlast\n'; + const current = 'first\nunchanged before\nMIDDLE\nunchanged after\nlast\n'; + hostWrites('/a.ts', current); + host.setWorkingSet([workingSetFile('/a.ts', baseline, current, 'tc1')]); + await settle(); + const entry = getEntry('/a.ts'); + await getChanges(entry); + const gate = stringDiffGate = { started: new DeferredPromise(), release: new DeferredPromise() }; + + hostWrites('/a.ts', 'FIRST\nunchanged before\nMIDDLE\nunchanged after\nLAST\n'); + await gate.started.p; + hostWritesWithoutReload('/a.ts', 'FIRST\nunchanged before\nMIDDLE\nAGENT\nLAST\n'); + host.setWorkingSet([workingSetFile('/a.ts', 'FIRST\nunchanged before\nmiddle\nunchanged after\nLAST\n', 'FIRST\nunchanged before\nMIDDLE\nAGENT\nLAST\n', 'tc2')]); + stringDiffGate = undefined; + gate.release.complete(); + await review.resolveEntry(entry.modifiedURI); + const changes = await getChanges(entry); + const original = entry.originalModel.getValue(); + await review.accept(); + + assert.deepStrictEqual({ changes, original, invoked: host.invoked, errors }, { + changes: ['[3,5)'], + original: 'FIRST\nunchanged before\nmiddle\nunchanged after\nLAST\n', + invoked: ['keep /a.ts @tc2'], + errors: [], + }); + }); + test('typing before the first diff is computed does not change the baseline', async () => { diffDelay = 30; hostWrites('/a.ts', 'added\nbase\n'); 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 c4de5ca0726d..5fbbfae387ee 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 @@ -1531,7 +1531,7 @@ suite('AgentHostSessionInputPills', () => { }))), }), undefined, createRichGitHubService([])); const icon = () => harness.persistentContent.querySelector('.chat-pill-icon'); - const pending = { open: icon()?.classList.contains('codicon-issue-opened'), color: icon()?.style.color }; + const pending = { open: icon()?.classList.contains('codicon-issues'), color: icon()?.style.color }; await timeout(0); assert.deepStrictEqual({ diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentCustomizationItemProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentCustomizationItemProvider.test.ts index 6e9ab850a090..2b0987259ffc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentCustomizationItemProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentCustomizationItemProvider.test.ts @@ -34,6 +34,7 @@ import { ChatMode, CustomChatMode } from '../../../common/chatModes.js'; import { IExtensionPromptPath, IPromptPath, IPromptsService, PromptsStorage } from '../../../common/promptSyntax/service/promptsService.js'; import { SYNCED_CUSTOMIZATION_SCHEME } from '../../../../../../workbench/services/agentHost/common/agentHostFileSystemService.js'; import { withCustomizationDiscoveryMeta } from '../../../../../../platform/agentHost/common/meta/customizationDiscoveryMeta.js'; +import { withCustomizationOrganizationMeta } from '../../../../../../platform/agentHost/common/meta/customizationOrganizationMeta.js'; import { AGENT_BUILTIN_CUSTOMIZATION_SCHEME, hasReadableCustomizationContent } from '../../../../../../platform/agentHost/common/agentHostCustomizationUri.js'; import { AICustomizationItemNormalizer, expandHookFileItems, ICustomizationSkillItem, ItemProviderItemSource } from '../../../browser/aiCustomization/aiCustomizationItemSource.js'; import { buildMcpResourceUri } from '../../../../../../platform/agentHost/common/mcpResourceUri.js'; @@ -249,6 +250,41 @@ suite('AgentCustomizationItemProvider', () => { }); }); + test('marks managed-policy hooks and organization-managed plugins as organization controlled', async () => { + class TestCustomizationService extends NullAgentHostCustomizationService { + override getCustomizations(): readonly Customization[] { + return [ + { + type: CustomizationType.Directory, id: 'hooks', uri: 'agent-discovery://copilot/hooks', + name: 'Hooks', contents: CustomizationType.Hook, enabled: true, writable: false, + children: ([['policy', true], ['policy', false], ['user', true]] as const).map(([source, enabled], index) => ({ + type: CustomizationType.Hook, id: `hook-${index}`, uri: `agent-discovery://copilot/hooks#${index}`, + name: 'sessionStart', enabled, + _meta: withCustomizationDiscoveryMeta(undefined, { source, hookType: 'sessionStart' }), + })), + }, + ...([['required', { requiredEnabled: true }], ['supplied', {}], ['unmanaged', undefined]] as const).map(([name, organization]): PluginCustomization => ({ + type: CustomizationType.Plugin, id: name, uri: `file:///plugins/${name}`, name, + ...(organization ? { _meta: withCustomizationOrganizationMeta(undefined, organization) } : {}), + })), + ]; + } + } + const provider = disposables.add(new AgentCustomizationItemProvider( + { clientId: 'vscode', resourceUris: createAgentHostResourceUriMapper('remote') }, undefined, undefined, upcastPartial({}), + new NullLogService(), new TestCustomizationService(), makePromptsService(), labelService, + )); + const items = await provider.provideChatSessionCustomizations(URI.parse('other-host:/opaque/session'), CancellationToken.None); + assert.deepStrictEqual(items.map(item => ({ key: item.itemKey ?? item.name, organizationControl: item.organizationControl })), [ + { key: 'required', organizationControl: { requiredEnabled: true } }, + { key: 'supplied', organizationControl: {} }, + { key: 'unmanaged', organizationControl: undefined }, + { key: 'hook-0', organizationControl: { requiredEnabled: true } }, + { key: 'hook-1', organizationControl: {} }, + { key: 'hook-2', organizationControl: undefined }, + ]); + }); + for (const kind of agentHostConnectionKinds) { for (const origin of ['repository', 'user'] as const) { test(`keeps readable SDK ${origin} hook actions distinct while expanding hook-file records (${kind.name})`, async () => { @@ -473,10 +509,10 @@ suite('AgentCustomizationItemProvider', () => { const result = await provider.provideCustomAgents(URI.parse('other-session:/opaque'), CancellationToken.None); assert.deepStrictEqual(result.map(agent => { const mode = new CustomChatMode(agent); - return { id: mode.id, name: mode.name.get(), source: mode.source?.label, storage: mode.source?.storage }; + return { id: mode.id, name: mode.name.get(), source: mode.source?.label, storage: mode.source?.storage, sourceUri: agent.sourceUri?.toString() }; }), [ - { id: createAgentHostResourceUriMapper('remote').fromAgentHost(URI.parse(agents[0].uri)).toString(), name: 'Reviewer', source: 'Extension: First Extension', storage: PromptsStorage.extension }, - { id: createAgentHostResourceUriMapper('remote').fromAgentHost(URI.parse(agents[1].uri)).toString(), name: 'Reviewer', source: 'Extension: second', storage: PromptsStorage.extension }, + { id: createAgentHostResourceUriMapper('remote').fromAgentHost(URI.parse(agents[0].uri)).toString(), name: 'Reviewer', source: 'Extension: First Extension', storage: PromptsStorage.extension, sourceUri: files[0].uri.toString() }, + { id: createAgentHostResourceUriMapper('remote').fromAgentHost(URI.parse(agents[1].uri)).toString(), name: 'Reviewer', source: 'Extension: second', storage: PromptsStorage.extension, sourceUri: files[1].uri.toString() }, ]); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.test.ts index d609163c943d..4c49f166f4f9 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostCustomizationMarketplaceInstallProvider.test.ts @@ -136,6 +136,45 @@ suite('AgentHostCustomizationMarketplaceInstallProvider', () => { }); }); + test('session-free marketplace additions notify source consumers without resolving a session or chat', async () => { + const calls: unknown[] = []; + const provider = store.add(createTestProvider( + 'copilotcli', + async () => true, + new class extends mock() { + override readonly onAgentHostStart = Event.None; + override readonly onAgentHostExit = Event.None; + override async addPluginMarketplace(provider: string, session: URI | undefined, source: string, chat?: URI) { + calls.push([provider, session, source, chat]); + if (source === 'invalid') { + throw new Error('SDK rejected source'); + } + return { name: 'catalog', source, isDefault: false, managed: false, available: true }; + } + }(), + new class extends mock() { }(), + new class extends mock() { + override readonly onDidChangeCustomizations = Event.None; + }(), + new class extends mock() { }(), + new NullLogService(), + pluginService, + )); + const changes: string[] = []; + store.add(provider.onDidChangeMarketplaces(() => changes.push('marketplaces'))); + store.add(provider.onDidChange(() => changes.push('customizations'))); + + await provider.add(undefined, 'owner/repo#feature/beta'); + await assert.rejects(provider.add(undefined, 'invalid'), /SDK rejected source/); + assert.deepStrictEqual({ calls, changes }, { + calls: [ + ['copilotcli', undefined, 'owner/repo#feature/beta', undefined], + ['copilotcli', undefined, 'invalid', undefined], + ], + changes: ['marketplaces', 'customizations'], + }); + }); + test('routes saved feeds through the owning session and preserves SDK identities and authentication recovery', async () => { const requests: { session: string; request: IAgentCustomizationMarketplaceSearchRequest }[] = []; const provider = store.add(createTestProvider( @@ -429,6 +468,50 @@ suite('AgentHostCustomizationMarketplaceInstallProvider', () => { }); }); + test('matches marketplace plugin separators consistently', async () => { + const frontendSession = URI.parse('agent-host-copilotcli:/frontend-session'); + const backendSession = URI.parse('agent-host-copilotcli:/backend-session'); + const provider = store.add(createTestProvider( + 'copilotcli', + async () => true, + new class extends mock() { + override readonly onAgentHostStart = Event.None; + override readonly onAgentHostExit = Event.None; + override async browsePluginMarketplace() { + return [ + { name: 'handy-commands', description: 'Useful commands' }, + { name: 'other-plugin', description: 'Something else' }, + ]; + } + }(), + new class extends mock() { + override resolveSessionResourceIdentity() { + return { connectionAuthority: AMBIENT_AGENT_HOST_AUTHORITY, backendSession }; + } + }(), + new class extends mock() { + override readonly onDidChangeCustomizations = Event.None; + }(), + new class extends mock() { }(), + new NullLogService(), + pluginService, + )); + const marketplace = { + name: 'marketplace', + source: 'GitHub: owner/repository', + isDefault: false, + managed: false, + available: true, + }; + const queries = ['handy-commands', 'handy commands', 'handy_commands', 'handy.commands', 'handy/commands']; + const results = await Promise.all(queries.map(async query => { + const page = await provider.queryMarketplace(frontendSession, marketplace, { query }, CancellationToken.None); + return page.items.map(item => item.displayName); + })); + + assert.deepStrictEqual(results, queries.map(() => ['handy-commands'])); + }); + test('projects SDK catalog searches and featured plugin browse results', async () => { const frontendSession = URI.parse('agent-host-copilotcli:/frontend-session'); const backendSession = URI.parse('ahp-session:/backend-session'); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts index d4cd48f3c0b1..42b6d8458077 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostByokLmHandler.test.ts @@ -11,7 +11,7 @@ import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; import { NullLogService } from '../../../../../../platform/log/common/log.js'; -import type { IByokLmChatRequest } from '../../../../../../platform/agentHost/common/agentHostByokLm.js'; +import type { IByokLmChatRequest, IByokLmStreamDelta } from '../../../../../../platform/agentHost/common/agentHostByokLm.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextKeyService } from '../../../../../../platform/contextkey/browser/contextKeyService.js'; import { IContextKey, IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; @@ -374,6 +374,79 @@ suite('AgentHostByokLmHandler', () => { }); }); + test('streams a delta for every part it folds into the result, in fold order', async () => { + const service = new TestLanguageModelsService( + new Map([['id-acme-claude', byokModel('acme', 'claude')]]), + () => responseOf([ + { type: 'thinking', value: 'considered ', id: 'rs_1' }, + { type: 'thinking', value: ['options'], id: 'rs_1', metadata: { encrypted_content: 'opaque' } }, + { type: 'thinking', value: '', id: 'thinking_2', metadata: { signature: 'sig', _completeThinking: 'full thought' } }, + { type: 'text', value: 'hello ' }, + { type: 'text', value: 'world' }, + { type: 'tool_use', name: 'getWeather', toolCallId: 't1', parameters: { city: 'NYC' } }, + { type: 'tool_use', name: 'apply_patch', toolCallId: 't2', parameters: { input: 'patch' } }, + { type: 'data', mimeType: 'stateful_marker', data: VSBuffer.fromString('claude\\resp_provider') }, + ]), + ); + const handler = createHandler(service); + const deltas: IByokLmStreamDelta[] = []; + store.add(handler.onDidDelta(delta => deltas.push(delta))); + + const result = await handler.chat( + { + requestId: 'req-1', + vendor: 'acme', + modelId: 'claude', + input: [{ type: 'message', role: 'user', content: [{ type: 'text', text: 'hi' }] }], + tools: [ + { type: 'function', name: 'getWeather' }, + { type: 'custom', name: 'apply_patch' }, + ], + }, + CancellationToken.None, + ); + + assert.deepStrictEqual({ + deltas, + output: result.output, + }, { + deltas: [ + { requestId: 'req-1', kind: 'reasoning', id: 'rs_1', delta: 'considered ', newSummaryPart: true }, + { requestId: 'req-1', kind: 'reasoning', id: 'rs_1', delta: 'options', newSummaryPart: true, encryptedContent: 'opaque' }, + { requestId: 'req-1', kind: 'reasoning', id: 'thinking_2', delta: '', newSummaryPart: true, encryptedContent: 'vscode-reasoning-metadata:{"signature":"sig","_completeThinking":"full thought"}' }, + { requestId: 'req-1', kind: 'text', delta: 'hello ' }, + { requestId: 'req-1', kind: 'text', delta: 'world' }, + { requestId: 'req-1', kind: 'toolCall', callId: 't1', name: 'getWeather', isCustom: false, value: '{"city":"NYC"}' }, + { requestId: 'req-1', kind: 'toolCall', callId: 't2', name: 'apply_patch', isCustom: true, value: 'patch' }, + ], + // The deltas above describe exactly these items, in this order. + output: [ + { type: 'reasoning', id: 'rs_1', summary: ['considered ', 'options'], encryptedContent: 'opaque', metadata: { encrypted_content: 'opaque' } }, + { type: 'reasoning', id: 'thinking_2', summary: [''], encryptedContent: 'vscode-reasoning-metadata:{"signature":"sig","_completeThinking":"full thought"}', metadata: { signature: 'sig', _completeThinking: 'full thought' } }, + { type: 'message', content: [{ type: 'text', text: 'hello world' }] }, + { type: 'function_call', callId: 't1', name: 'getWeather', argumentsJson: '{"city":"NYC"}' }, + { type: 'custom_tool_call', callId: 't2', name: 'apply_patch', input: 'patch' }, + ], + }); + }); + + test('emits no deltas for a request that does not ask to be streamed', async () => { + const service = new TestLanguageModelsService( + new Map([['id-acme-claude', byokModel('acme', 'claude')]]), + () => responseOf([{ type: 'text', value: 'ok' }]), + ); + const handler = createHandler(service); + const deltas: IByokLmStreamDelta[] = []; + store.add(handler.onDidDelta(delta => deltas.push(delta))); + + const result = await handler.chat({ vendor: 'acme', modelId: 'claude', input: [] }, CancellationToken.None); + + assert.deepStrictEqual({ deltas, output: result.output }, { + deltas: [], + output: [{ type: 'message', content: [{ type: 'text', text: 'ok' }] }], + }); + }); + test('combines streamed thinking chunks into one summary entry', async () => { const service = new TestLanguageModelsService( new Map([['id-deepseek', byokModel('customendpoint', 'deepseek')]]), 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 d21919d30394..e83f8d6bef6b 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 @@ -32,6 +32,9 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/ import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { DeferredPromise, raceTimeout, timeout } from '../../../../../../base/common/async.js'; import { Range } from '../../../../../../editor/common/core/range.js'; +import { Position } from '../../../../../../editor/common/core/position.js'; +import { ILanguageFeaturesService } from '../../../../../../editor/common/services/languageFeatures.js'; +import { LanguageFeaturesService } from '../../../../../../editor/common/services/languageFeaturesService.js'; import { OffsetRange } from '../../../../../../editor/common/core/ranges/offsetRange.js'; import { isLocation } from '../../../../../../editor/common/languages.js'; import { ITextModel, TrackedRangeStickiness } from '../../../../../../editor/common/model.js'; @@ -45,6 +48,7 @@ import { ChatAttachmentModel } from '../../../browser/attachments/chatAttachment import { IChatAttachmentResolveService } from '../../../browser/attachments/chatAttachmentResolveService.js'; import { ChatInputPart } from '../../../browser/widget/input/chatInputPart.js'; import { ChatWidget } from '../../../browser/widget/chatWidget.js'; +import { AgentHostInputCompletions } from '../../../browser/widget/input/editor/agentHostInputCompletions.js'; import { IChatVariablesService, type IDynamicVariable } from '../../../common/attachments/chatVariables.js'; import { ChatRequestParser } from '../../../common/requestParser/chatRequestParser.js'; import { ChatRequestDynamicVariablePart } from '../../../common/requestParser/chatParserTypes.js'; @@ -61,7 +65,7 @@ import { ContextKeyExpr, type ContextKeyValue } from '../../../../../../platform import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TERMINAL_AUTO_APPROVE_SETTING_ID, URL_AUTO_APPROVE_SETTING_ID } from '../../../../../../platform/agentHost/common/agentHostSchema.js'; import { permissionGrantOptionId, PermissionGrantScope } from '../../../../../../platform/agentHost/common/permissionRules.js'; -import { SAVE_SANDBOX_PATH } from '../../../../../../platform/agentHost/common/sandboxPathGrant.js'; +import { SAVE_SANDBOX_PATH, SAVE_SESSION_SANDBOX_PATH, SAVE_WORKSPACE_SANDBOX_PATH } from '../../../../../../platform/agentHost/common/sandboxPathGrant.js'; import { readAgentPermissionResponseMeta } from '../../../../../../platform/agentHost/common/meta/agentPermissionResponseMeta.js'; import { withMcpServerConnectorNameMeta } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; import { AgentSandboxSettingId } from '../../../../../../platform/sandbox/common/settings.js'; @@ -95,7 +99,7 @@ import { ActionType, AuthRequiredReason, isSessionAction, isChatAction, Notifica import { chatToolCallComplete, chatToolCallReady, chatToolCallStart, chatTurnComplete, chatTurnStarted } from '../../../../../../platform/agentHost/test/common/chatActionBuilders.js'; import { AhpErrorCodes, AHP_AUTH_REQUIRED, AHP_NOT_FOUND, JsonRpcErrorCodes, ProtocolError, type DispatchActionParams, type IStateSnapshot, type JsonRpcRequest, type ProtocolMessage } from '../../../../../../platform/agentHost/common/state/sessionProtocol.js'; import { BackgroundWorkKind, ChatInteractivity, ConfirmationOptionKind, CustomizationEnablementKind, CustomizationType, McpAuthRequiredReason, McpServerStatus, SessionOriginKind, type AgentCustomization, type ChatInputAnswer, type ChatInputRequest, type ClientPluginCustomization, type ProtectedResourceMetadata, type SessionActiveClient, type ToolDefinition, type Turn, type UsageInfo } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; -import { ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, ChatOriginKind, SessionLifecycle, SessionStatus, TurnState, ToolCallStatus, ToolCallConfirmationReason, ToolCallContributorKind, ToolCallRiskAssessmentKind, ToolCallRiskAssessmentStatus, createSessionState, createChatState, createDefaultChatSummary, createErrorResponsePart, buildChatUri, buildDefaultChatUri, parseChatUri, isAhpChatChannel, createActiveTurn, isAhpRootChannel, PolicyState, ResponsePartKind, ROOT_STATE_URI, StateComponents, buildSubagentChatUri, buildSubagentSessionUri, ToolResultContentType, MessageAttachmentKind, MessageKind, PendingMessageKind, withMessageRequestHiddenFromTranscript, withSessionMultiRootMetadata, SESSION_META_EHCLI_ADOPTABLE_KEY, SESSION_META_EHCLI_ADOPTED_KEY, type SessionState, type SessionSummary, type ChatState, type ISessionWithDefaultChat, RootState, type ToolCallState, type AgentInfo, type Message, type MessageAttachment, type MessageChatAttachment } from '../../../../../../platform/agentHost/common/state/sessionState.js'; +import { ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, ChatOriginKind, SessionLifecycle, SessionStatus, TurnState, ToolCallStatus, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributorKind, ToolCallRiskAssessmentKind, ToolCallRiskAssessmentStatus, createSessionState, createChatState, createDefaultChatSummary, createErrorResponsePart, buildChatUri, buildDefaultChatUri, parseChatUri, isAhpChatChannel, createActiveTurn, isAhpRootChannel, PolicyState, ResponsePartKind, ROOT_STATE_URI, StateComponents, buildSubagentChatUri, buildSubagentSessionUri, ToolResultContentType, MessageAttachmentKind, MessageKind, PendingMessageKind, withMessageRequestHiddenFromTranscript, withSessionMultiRootMetadata, SESSION_META_EHCLI_ADOPTABLE_KEY, SESSION_META_EHCLI_ADOPTED_KEY, type SessionState, type SessionSummary, type ChatState, type ISessionWithDefaultChat, RootState, type ToolCallState, type AgentInfo, type Message, type MessageAttachment, type MessageChatAttachment } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { CompletionItemKind as AhpCompletionItemKind, type CompletionsParams, type CompletionsResult, type CreateChatParams, type InitializeResult } from '../../../../../../platform/agentHost/common/state/protocol/commands.js'; import { sessionReducer, chatReducer } from '../../../../../../platform/agentHost/common/state/sessionReducers.js'; import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; @@ -121,7 +125,7 @@ import { IChatEditingService, IChatEditingSession, IChatEditingSessionProvider } import { ITextFileEditorModelManager, ITextFileService } from '../../../../../services/textfile/common/textfiles.js'; import { IChatResponseFileChangesService } from '../../../browser/chatResponseFileChangesService.js'; import { IMarkdownString, MarkdownString } from '../../../../../../base/common/htmlContent.js'; -import { ChatSessionForkError, ChatSessionStatus, IChatSessionsService, type IChatSession, type IChatSessionForkOptions, type IChatSessionHistoryItem, type IChatSessionContentProvider, type IChatSessionItem, type IChatSessionItemController, type IChatSessionRequestHistoryItem, type IChatSessionServerRequest, type IChatSessionsExtensionPoint } from '../../../common/chatSessionsService.js'; +import { ChatSessionForkError, ChatSessionStatus, IChatSessionsService, type IChatInputCompletionItem, type IChatSession, type IChatSessionForkOptions, type IChatSessionHistoryItem, type IChatSessionContentProvider, type IChatSessionItem, type IChatSessionItemController, type IChatSessionRequestHistoryItem, type IChatSessionServerRequest, type IChatSessionsExtensionPoint } from '../../../common/chatSessionsService.js'; import { IChatSideChatOrigin } from '../../../common/chatSideChatService.js'; import { ILanguageModelsService, type ILanguageModelChatMetadata } from '../../../common/languageModels.js'; import { IProductService } from '../../../../../../platform/product/common/productService.js'; @@ -190,7 +194,7 @@ import { IAgentHostMcpAppToolsService } from '../../../browser/agentSessions/age import { IAgentHostCustomizationService, NullAgentHostCustomizationService } from '../../../browser/agentSessions/agentHost/agentHostCustomizationService.js'; import { ILanguageModelToolsService, ToolAndToolSetEnablementMap, ToolDataSource } from '../../../common/tools/languageModelToolsService.js'; import { IPromptsService } from '../../../common/promptSyntax/service/promptsService.js'; -import { IChatWidgetService } from '../../../browser/chat.js'; +import { IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; import { ChatQuestionCarouselData } from '../../../common/model/chatProgressTypes/chatQuestionCarouselData.js'; import { ChatPlanReviewData } from '../../../common/model/chatProgressTypes/chatPlanReviewData.js'; import { ChatElicitationRequestPart } from '../../../common/model/chatProgressTypes/chatElicitationRequestPart.js'; @@ -985,7 +989,7 @@ function createTestServices(disposables: DisposableStore, workingDirectoryResolv agentHostService, new NullRemoteAgentHostService(), upcastPartial({ registerPathProvider: () => Disposable.None }), - new NullLogService(), + upcastPartial({ registerFormatter: () => Disposable.None }), ))); instantiationService.stub(ILogService, new NullLogService()); instantiationService.stub(IProductService, { quality: 'insider' }); @@ -2001,7 +2005,7 @@ suite('AgentHostChatContribution', () => { }, }; }; - return { startRequest, fire, echo, peer, client, handler, chatSession, sessionResource, backendSession, chatUri, modelService, quotaUpdates, implicitReadGrants, instantiationService, chatService }; + return { startRequest, fire, echo, peer, client, handler, chatSession, sessionResource, backendSession, chatUri, modelService, quotaUpdates, implicitReadGrants, instantiationService, chatService, chatAgentService }; } for (const active of [false, true]) { @@ -2083,6 +2087,174 @@ suite('AgentHostChatContribution', () => { }); } + suite('checkpoint truncation', () => { + async function openRestoredSession(keepFirstTurn: boolean) { + const turns = ['turn-1', 'turn-2', 'turn-3'].map(id => ({ + id, message: { text: id, origin: { kind: MessageKind.User } }, + responseParts: [], usage: undefined, state: TurnState.Complete, + })); + const context = await openWireSession({ chat: { turns } }); + const controller = disposables.add(new AgentHostSnapshotController(context.sessionResource, context.client, 'local', undefined, new NullLogService(), disposables.add(new TestFileService()), new MockWorkingCopyService())); + for (const turn of turns) { + controller.ensureRequestCheckpoint(turn.id); + } + await controller.restoreSnapshot(turns[keepFirstTurn ? 1 : 0].id, undefined); + const disabled = new Set(controller.requestDisablement.get().map(request => request.requestId)); + // ChatService removes disabled requests before invoking the agent with the new request. + const requests = [...turns.filter(turn => !disabled.has(turn.id)), { id: 'replacement' }] + .map(request => upcastPartial({ id: request.id })); + context.chatService.setSession(context.sessionResource, upcastPartial({ + sessionResource: context.sessionResource, editingSession: controller, + getRequests: () => requests, getPendingRequests: () => [], onDidChangePendingRequests: Event.None, + })); + const registered = context.chatAgentService.registeredAgents.get('agent-host-copilot'); + assert.ok(registered); + const dispatched: DispatchActionParams[] = []; + disposables.add(context.peer.onDispatch(action => { + if (action.action.type === ActionType.ChatTruncated || action.action.type === ActionType.ChatTurnStarted) { + dispatched.push(action); + } + })); + return { + ...context, dispatched, requests, + invoke: (token = CancellationToken.None, requestId = 'replacement') => registered.impl.invoke(makeRequest({ + sessionResource: context.sessionResource, requestId, + }), () => { }, [], token), + turnIds: () => { + const state = context.client.getSubscriptionUnmanaged(StateComponents.Chat, URI.parse(context.chatUri))?.verifiedValue; + assert.ok(state && !(state instanceof Error)); + return state.turns.map(turn => turn.id); + }, + }; + } + + for (const keepFirstTurn of [false, true]) { + for (const synchronous of [false, true]) { + test(`waits for authoritative history truncation before sending the replacement (keep first: ${keepFirstTurn}, synchronous: ${synchronous})`, async () => { + const context = await openRestoredSession(keepFirstTurn); + if (synchronous) { + disposables.add(context.peer.onDispatch(sent => { + if (sent.action.type === ActionType.ChatTruncated) { + context.echo(sent); + } + })); + } + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const starting = context.peer.nextDispatch(ActionType.ChatTurnStarted); + const result = context.invoke(); + const truncated = await truncating; + if (!synchronous) { + await timeout(0); + assert.deepStrictEqual(context.dispatched.map(({ channel, action }) => ({ channel, action })), [{ + channel: context.chatUri, + action: { type: ActionType.ChatTruncated, ...(keepFirstTurn ? { turnId: 'turn-1' } : {}) }, + }]); + context.echo({ ...truncated, clientSeq: truncated.clientSeq + 100 }, 'Unrelated rejection'); + await timeout(0); + assert.strictEqual(context.dispatched.length, 1); + context.echo(truncated); + } + const started = await starting; + context.echo(started); + context.fire(chatTurnComplete('replacement', 1)); + await result; + assert.deepStrictEqual(context.turnIds(), [...(keepFirstTurn ? ['turn-1'] : []), 'replacement']); + }); + } + + for (const synchronous of [false, true]) { + test(`a refused truncation surfaces the reason without sending against stale history (keep first: ${keepFirstTurn}, synchronous: ${synchronous})`, async () => { + const context = await openRestoredSession(keepFirstTurn); + const reason = 'The runtime could not truncate its history.'; + if (synchronous) { + disposables.add(context.peer.onDispatch(sent => { + if (sent.action.type === ActionType.ChatTruncated) { + context.echo(sent, reason); + } + })); + } + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const rejected = assert.rejects(context.invoke(), { message: `Chat history could not be restored: ${reason}` }); + const truncated = await truncating; + if (!synchronous) { + context.echo(truncated, reason); + } + await rejected; + assert.deepStrictEqual({ + actions: context.dispatched.map(sent => sent.action.type), + turns: context.turnIds(), + }, { + actions: [ActionType.ChatTruncated], + turns: ['turn-1', 'turn-2', 'turn-3'], + }); + }); + } + + test(`retries a refused truncation before sending another request (keep first: ${keepFirstTurn})`, async () => { + const context = await openRestoredSession(keepFirstTurn); + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const rejected = assert.rejects(context.invoke(), /Chat history could not be restored/); + context.echo(await truncating, 'Retry the history operation'); + await rejected; + context.requests.push(upcastPartial({ id: 'retry' })); + const result = context.invoke(CancellationToken.None, 'retry'); + await timeout(0); + assert.deepStrictEqual(context.dispatched.map(sent => sent.action), [ + { type: ActionType.ChatTruncated, ...(keepFirstTurn ? { turnId: 'turn-1' } : {}) }, + { type: ActionType.ChatTruncated, ...(keepFirstTurn ? { turnId: 'turn-1' } : {}) }, + ]); + const starting = context.peer.nextDispatch(ActionType.ChatTurnStarted); + context.echo(context.dispatched[1]); + context.echo(await starting); + context.fire(chatTurnComplete('retry', 1)); + await result; + assert.deepStrictEqual(context.turnIds(), [...(keepFirstTurn ? ['turn-1'] : []), 'retry']); + }); + } + + test('a cancelled wait cannot let a retry use optimistically truncated history', async () => { + const context = await openRestoredSession(true); + const cancellation = disposables.add(new CancellationTokenSource()); + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const cancelled = assert.rejects(context.invoke(cancellation.token), isCancellationError); + const original = await truncating; + cancellation.cancel(); + await cancelled; + context.requests.push(upcastPartial({ id: 'retry' })); + const retryTruncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const starting = context.peer.nextDispatch(ActionType.ChatTurnStarted); + const result = context.invoke(CancellationToken.None, 'retry'); + const retry = await retryTruncating; + context.echo(original); + await timeout(0); + assert.deepStrictEqual(context.dispatched.map(sent => sent.action.type), [ActionType.ChatTruncated, ActionType.ChatTruncated]); + context.echo(retry); + context.echo(await starting); + context.fire(chatTurnComplete('retry', 1)); + await result; + assert.deepStrictEqual(context.turnIds(), ['turn-1', 'retry']); + }); + + for (const interruption of ['cancel', 'dispose', 'disconnect'] as const) { + test(`does not send a replacement after ${interruption} while truncation is pending`, async () => { + const context = await openRestoredSession(true); + const cancellation = disposables.add(new CancellationTokenSource()); + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const rejected = assert.rejects(context.invoke(cancellation.token), interruption === 'disconnect' ? /connection|transport/i : isCancellationError); + await truncating; + if (interruption === 'cancel') { + cancellation.cancel(); + } else if (interruption === 'dispose') { + context.handler.dispose(); + } else { + context.client.dispose(); + } + await rejected; + assert.deepStrictEqual(context.dispatched.map(sent => sent.action.type), [ActionType.ChatTruncated]); + }); + } + }); + for (const synchronous of [false, true]) { test(`rejected turn starts surface the reason and settle without a host turn (synchronous: ${synchronous})`, async () => { const { startRequest, echo, peer, client, chatUri, chatSession } = await openWireSession(); @@ -2410,6 +2582,55 @@ suite('AgentHostChatContribution', () => { }); } + test('a running command asked for approval again shows where it runs, and the answer is sent back as before', async () => { + const { startRequest, fire, peer, echo } = await openWireSession(); + const { turnId, progress, finish } = await startRequest(); + const terminal = { toolKind: 'terminal' }; + const observed = []; + for (const [toolCallId, workingDirectory, approved] of [['web', '/work/web', true], ['api', '/work/api', false]] as const) { + // The same relative command, started and then asked for approval as Codex does. + fire(chatToolCallStart(turnId, toolCallId, 'shell', 'Run shell command', { _meta: terminal })); + fire(chatToolCallReady(turnId, toolCallId, './test.sh', { toolInput: './test.sh', confirmed: ToolCallConfirmationReason.NotNeeded, _meta: terminal })); + fire(chatToolCallReady(turnId, toolCallId, './test.sh', { + toolInput: './test.sh', confirmationTitle: 'Run the tests', + _meta: { ...terminal, 'vscode.terminalWorkingDirectory': workingDirectory }, + })); + const invocation = progress.find((part): part is IChatToolInvocation => part.kind === 'toolInvocation' && part.toolCallId === toolCallId); + assert.ok(invocation); + const data = invocation.toolSpecificData; + const state = invocation.state.get().type; + const confirmation = peer.nextDispatch(ActionType.ChatToolCallConfirmed); + IChatToolInvocation.confirmWith(invocation, approved ? { type: ToolConfirmKind.UserAction } : { type: ToolConfirmKind.Denied, source: 'user' }); + const sent = await confirmation; + echo(sent); + fire(chatToolCallComplete(turnId, toolCallId, { success: approved, pastTenseMessage: 'Ran ./test.sh', content: [] })); + observed.push({ + state, + executionTarget: data?.kind === 'terminal' && hasKey(data, { commandLine: true }) ? data.executionTarget : undefined, + sent: sent.action, + }); + } + await finish(); + assert.deepStrictEqual(observed, [ + { + state: IChatToolInvocation.StateKind.WaitingForConfirmation, + executionTarget: { workingDirectory: '/work/web' }, + sent: { + type: ActionType.ChatToolCallConfirmed, turnId, toolCallId: 'web', approved: true, confirmed: ToolCallConfirmationReason.UserAction, + _meta: { ...terminal, 'vscode.terminalWorkingDirectory': '/work/web', 'agentHost.permissionDecisionSource': 'human_response' }, + }, + }, + { + state: IChatToolInvocation.StateKind.WaitingForConfirmation, + executionTarget: { workingDirectory: '/work/api' }, + sent: { + type: ActionType.ChatToolCallConfirmed, turnId, toolCallId: 'api', approved: false, reason: ToolCallCancellationReason.Denied, + _meta: { ...terminal, 'vscode.terminalWorkingDirectory': '/work/api', 'agentHost.permissionDecisionSource': 'human_response' }, + }, + }, + ]); + }); + const appToolCases = [ { name: 'grep', args: { pattern: 'auth' }, kind: 'search', running: 'Searching `auth`', completed: 'Searched `auth`' }, { name: 'glob', args: { pattern: '*.ts' }, kind: 'search', running: 'Searching `*.ts`', completed: 'Searched `*.ts`' }, @@ -2524,7 +2745,8 @@ suite('AgentHostChatContribution', () => { }); const usageCases = [ - { name: 'VS Code zero turn cost', meta: { cost: 0 }, credits: 0, sessionCredits: undefined, latest: undefined, attribution: undefined }, + { name: 'VS Code zero turn cost', meta: { copilotUsage: { totalNanoAiu: 0 } }, credits: 0, sessionCredits: undefined, latest: undefined, attribution: undefined }, + { name: 'VS Code model multiplier is not measured credits', meta: { cost: 2 }, credits: undefined, sessionCredits: undefined, latest: undefined, attribution: undefined }, { name: 'VS Code credits, quota and context attribution', meta: { copilotUsage: { totalNanoAiu: 2_000_000_000, sessionTotalNanoAiu: 4_000_000_000 }, @@ -2536,7 +2758,7 @@ suite('AgentHostChatContribution', () => { ] }, { name: 'Copilot D latest-call diagnostics', meta: { 'copilot.usageDetail': { cost: 0.5, duration: 12 } }, credits: undefined, sessionCredits: undefined, latest: { cost: 0.5, duration: 12 }, attribution: undefined }, - { name: 'mixed usage preserves VS Code turn cost', meta: { cost: 0, 'copilot.usageDetail': { cost: 0.5, duration: 12 } }, credits: 0, sessionCredits: undefined, latest: undefined, attribution: undefined }, + { name: 'mixed usage does not promote model multipliers to credits', meta: { cost: 0, 'copilot.usageDetail': { cost: 0.5, duration: 12 } }, credits: undefined, sessionCredits: undefined, latest: undefined, attribution: undefined }, ]; for (const entry of usageCases) { test(`${entry.name} reaches Chat usage through the live handler`, async () => { @@ -3135,14 +3357,85 @@ suite('AgentHostChatContribution', () => { suite('request attachments', () => { - test('sends accepted agent-host skill and command completions as ranged simple attachments', async () => { + for (const kind of agentHostConnectionKinds) { + test(`accepts, sends, and restores native skill resource completions without metadata (${kind.name})`, async () => { + const { sessionHandler, agentHostService, chatAgentService, instantiationService } = createContribution(disposables, { + chatSessionsServiceOverride: { getContentProviderSchemes: () => [], onDidChangeContentProviderSchemes: Event.None }, + }); + agentHostService.resourceUris = kind.resourceUris; + const hostResource = URI.file('/workspace/skills/review/SKILL.md'); + agentHostService.completions = async () => ({ + items: [{ + insertText: '/tools:review ', rangeStart: 0, rangeEnd: 1, + attachment: { type: MessageAttachmentKind.Resource, uri: hostResource.toString(), label: '/tools:review', displayKind: 'skill' }, + }], + }); + const item = (await sessionHandler.provideChatInputCompletions(URI.parse('agent-host-copilot:/abc'), { text: '/', offset: 1 }, CancellationToken.None))!.items[0]; + instantiationService.stub(ILanguageFeaturesService, new LanguageFeaturesService()); + const completions = disposables.add(instantiationService.createInstance(class extends AgentHostInputCompletions { + build(item: IChatInputCompletionItem, widget: IChatWidget) { + return this._buildItem(new Position(1, 2), item, widget); + } + })); + const codeEditorService = disposables.add(new TestCodeEditorService(new TestThemeService())); + disposables.add(codeEditorService.registerDecorationType('test', dynamicVariableDecorationType, { + rangeBehavior: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, + })); + const editor = disposables.add(createTestCodeEditor(disposables.add(createTextModel('/')), { + serviceCollection: new ServiceCollection([ICodeEditorService, codeEditorService]), + })); + const attachmentModel = disposables.add(new ChatAttachmentModel( + upcastPartial({}), upcastPartial({}), upcastPartial({}), + )); + const widget = upcastPartial({ + inputEditor: editor, input: upcastPartial({ attachmentModel }), + onDidChangeActiveInputEditor: Event.None, refreshParsedInput: () => { }, getContrib: () => undefined, + }); + const references = disposables.add(new ChatDynamicVariableModel(widget, new MockLabelService())); + const getContrib = sinon.stub(widget, 'getContrib'); + disposables.add(toDisposable(() => getContrib.restore())); + getContrib.withArgs(ChatDynamicVariableModel.ID).returns(references); + const completion = completions.build(item, widget)!; + editor.executeEdits('suggest', [{ range: Range.isIRange(completion.range) ? completion.range : completion.range.replace, text: completion.insertText }]); + const command = completion.command!; + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand(command.id)!.handler(accessor, ...(command.arguments ?? []))); + const parser = new ChatRequestParser( + upcastPartial({ getDefaultAgent: () => undefined }), upcastPartial({}), + upcastPartial({ getCommands: () => [] }), upcastPartial({ hasPromptSlashCommand: () => false, isValidSlashCommandName: () => false }), + ); + const parsed = parser.parseChatRequestWithReferences(references.variables, ToolAndToolSetEnablementMap.fromEntries([]), editor.getValue()); + const variables = parsed.parts.flatMap(part => part instanceof ChatRequestDynamicVariablePart ? [part.toVariableEntry()] : []); + const { turnPromise, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { + message: parsed.text, variables: { variables }, + }); + const sent = (agentHostService.turnActions[0].action as ITurnStartedAction).message.attachments; + const restored = messageAttachmentsToVariableData(sent, 'test', parsed.text, kind.resourceUris)!.variables; + fire(chatTurnComplete(turnId!, 1000)); + await turnPromise; + assert.deepStrictEqual({ + clientResource: item.attachment?.kind === 'skill' ? item.attachment.uri.toString() : undefined, + text: parsed.text, sent, restored: restored.map(variable => ({ id: variable.id, value: variable.value, range: variable.range })), + attachments: attachmentModel.attachments.length, + }, { + clientResource: kind.toClient(hostResource).toString(), + text: '/tools:review ', + sent: [{ + type: MessageAttachmentKind.Resource, uri: hostResource.toString(), label: '/tools:review', displayKind: 'skill', + range: { start: { line: 0, character: 0 }, end: { line: 0, character: 13 } }, + }], + restored: [{ id: kind.toClient(hostResource).toString(), value: { $mid: 'agentHostCompletion', kind: 'skill' }, range: { start: 0, endExclusive: 13 } }], + attachments: 0, + }); + }); + } + + test('sends accepted agent-host skill resources and command completions with ranges', async () => { const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); const message = 'use /author-contributions\n/rename Title'; const skillStart = message.indexOf('/author-contributions'); const commandStart = message.indexOf('/rename'); const skillMeta = { providerPayload: 'skill-metadata', - displayName: 'author-contributions', description: 'Summarize author contributions', }; const commandMeta = { @@ -3169,7 +3462,8 @@ suite('AgentHostChatContribution', () => { const turnStarted = agentHostService.turnActions[0].action as ITurnStartedAction; assert.deepStrictEqual(turnStarted.message.attachments, [ { - type: MessageAttachmentKind.Simple, + type: MessageAttachmentKind.Resource, + uri: 'file:///skills/author-contributions/SKILL.md', label: '/author-contributions', displayKind: 'skill', range: { @@ -3194,6 +3488,18 @@ suite('AgentHostChatContribution', () => { await turnPromise; }); + test('keeps a legacy skill invocation without a resource as text rather than emitting a new Simple skill', async () => { + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); + const { turnPromise, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { + message: '/review', + variables: { variables: [toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', undefined, undefined)] }, + }); + const action = agentHostService.turnActions[0].action as ITurnStartedAction; + fire(chatTurnComplete(turnId!, 1000)); + await turnPromise; + assert.deepStrictEqual({ text: action.message.text, attachments: action.message.attachments }, { text: '/review', attachments: undefined }); + }); + test('sends paste variables as embedded text attachments', async () => { const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { @@ -4587,9 +4893,10 @@ suite('AgentHostChatContribution', () => { const sessionResource = URI.parse('agent-host-copilot:/inline-draft-sync'); const text = '/review #file.ts\n/compact now'; const file = URI.file('/workspace/file.ts'); - const skillMetadata = { uri: 'host-skill:/review', name: 'review', opaque: false }; + const skillUri = URI.file('/workspace/review/SKILL.md'); + const skillMetadata = { uri: 'host-skill:/wrong', opaque: false }; const commandMetadata = { command: 'compact', opaque: 0 }; - const skill = toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', skillMetadata.uri, skillMetadata); + const skill = toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', kind.toClient(skillUri), skillMetadata); const command = toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Command, '/compact', 'compact', commandMetadata); const references: IDynamicVariable[] = [ { id: skill.id, range: new Range(1, 1, 1, 8), data: skill.value, _meta: skillMetadata }, @@ -4687,7 +4994,7 @@ suite('AgentHostChatContribution', () => { { range: [2, 1, 2, 9], data: command.value, metadata: commandMetadata }, ]; const expectedAttachments = [ - { type: MessageAttachmentKind.Simple, label: '/review', displayKind: 'skill', range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } }, _meta: skillMetadata }, + { type: MessageAttachmentKind.Resource, uri: skillUri.toString(), label: '/review', displayKind: 'skill', range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } }, _meta: skillMetadata }, { type: MessageAttachmentKind.Resource, label: 'file.ts', uri: file.toString(), displayKind: 'document', range: { start: { line: 0, character: 8 }, end: { line: 0, character: 16 } } }, { type: MessageAttachmentKind.Simple, label: '/compact', displayKind: 'command', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 8 } }, _meta: commandMetadata }, ]; @@ -4734,7 +5041,7 @@ suite('AgentHostChatContribution', () => { const sessionResource = URI.parse('agent-host-copilot:/widget-draft-clear'); const text = 'explain /commit and /compact please'; const completions = [ - toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/commit', 'host-skill:/commit', { uri: 'host-skill:/commit', opaque: false }), + toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/commit', 'host-skill:/commit', { opaque: false }), toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Command, '/compact', 'compact', { command: 'compact', opaque: 0 }), ]; const sender = createContribution(disposables); @@ -4865,7 +5172,7 @@ suite('AgentHostChatContribution', () => { source: summarizeInput(source), peer: summarizeInput(peer), editedPeer: summarizeInput(editedPeer), peerDrafts: peer.agentHostService.dispatchedActions.filter(entry => entry.action.type === ActionType.ChatDraftChanged), }, { - draftAttachments: completions.map(completion => ({ type: MessageAttachmentKind.Simple, label: completion.name, metadata: completion._meta })), + draftAttachments: completions.map(completion => ({ type: completion.value.kind === AgentHostCompletionReferenceKind.Skill ? MessageAttachmentKind.Resource : MessageAttachmentKind.Simple, label: completion.name, metadata: completion._meta })), afterRestore: { references: 2, viewAttachments: 2, modelAttachments: 0 }, beforeSend: { references: 2, attachments: 2, origin: undefined }, source: { editor: '', model: '', references: 0, attachments: 0 }, @@ -4888,9 +5195,9 @@ suite('AgentHostChatContribution', () => { seedDraftSession(agentHostService, backendSession, 'Pill Projection', { text, origin: { kind: MessageKind.User }, attachments: [{ - type: MessageAttachmentKind.Simple, label: '/review', displayKind: 'skill', + type: MessageAttachmentKind.Resource, uri: 'host-skill:/review', label: '/review', displayKind: 'skill', range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } }, - _meta: { uri: 'host-skill:/review', opaque: false }, + _meta: { opaque: false }, }, { type: MessageAttachmentKind.Simple, label: '/compact', displayKind: 'command', range: { start: { line: 0, character: 12 }, end: { line: 0, character: 20 } }, @@ -4997,7 +5304,7 @@ suite('AgentHostChatContribution', () => { const file = URI.file('/workspace/file.ts'); for (const reference of [ { name: 'file', text: 'please #file\nabc', attachment: { type: MessageAttachmentKind.Resource, uri: file.toString(), label: 'file.ts', displayKind: 'document' } }, - { name: 'skill', text: 'please /skill\nabc', attachment: { type: MessageAttachmentKind.Simple, label: '/skill', displayKind: 'skill', _meta: { uri: 'host-skill:/skill' } } }, + { name: 'skill', text: 'please /skill\nabc', attachment: { type: MessageAttachmentKind.Resource, uri: 'host-skill:/skill', label: '/skill', displayKind: 'skill' } }, { name: 'command', text: 'please /compact\nabc', attachment: { type: MessageAttachmentKind.Simple, label: '/compact', displayKind: 'command', _meta: { command: 'compact' } } }, ] as const) { test(`keeps multiline ${reference.name} draft mentions as attachments (${kind.name})`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { @@ -9670,22 +9977,23 @@ suite('AgentHostChatContribution', () => { assert.deepStrictEqual(records.map(record => ({ outcome: record.outcome, hasResponseText: record.hasResponseText })), [{ outcome: 'cancelled', hasResponseText: false }]); }); - test('first response timing excludes reasoning and error messages', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('first response timing counts root reasoning only toward the combined timing and ignores error messages', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService, instantiationService } = createContribution(disposables); - const records: { outcome: string; hasResponseText: boolean }[] = []; + const records: { outcome: string; hasResponseText: boolean; firstResponseOrReasoningMs?: number }[] = []; instantiationService.get(ILogService).info = message => { if (message?.startsWith('[AgentHostFirstResponse] ')) { records.push(JSON.parse(message.substring('[AgentHostFirstResponse] '.length))); } }; const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/responsePart', session, turnId, part: { kind: ResponsePartKind.Reasoning, id: 'thought', content: 'thinking' } } as ChatAction); + fire({ type: 'chat/responsePart', session, turnId, part: { kind: ResponsePartKind.Reasoning, id: 'thought', content: ' ' } } as ChatAction); + fire({ type: ActionType.ChatReasoning, turnId, partId: 'thought', content: 'thinking' } as ChatAction); fire({ type: 'chat/error', endedAt: '2025-01-01T00:00:00.000Z', turnId, part: { kind: ResponsePartKind.Error, error: { errorType: 'connection_error', message: 'connection lost' } }, } as ChatAction); await turnPromise; - assert.deepStrictEqual(records.map(record => ({ outcome: record.outcome, hasResponseText: record.hasResponseText })), [{ outcome: 'error', hasResponseText: false }]); + assert.deepStrictEqual(records.map(record => ({ outcome: record.outcome, hasResponseText: record.hasResponseText, timedReasoning: typeof record.firstResponseOrReasoningMs === 'number' })), [{ outcome: 'error', hasResponseText: false, timedReasoning: true }]); })); test('delta events become markdownContent progress', () => runWithFakedTimers({ useFakeTimers: true }, async () => { @@ -9854,6 +10162,32 @@ suite('AgentHostChatContribution', () => { ]); })); + test('a model router row that is picking a model settles when its router keeps the chat\'s pick', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const languageModels = new Map([ + ['agent-host-copilot:model-router:daily', upcastPartial({ name: 'Daily Driver' })], + ['agent-host-copilot:gpt-5.4-mini', upcastPartial({ name: 'GPT-5.4 mini' })], + ]); + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables, { languageModels }); + const { turnPromise, collected, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { + userSelectedModelId: 'agent-host-copilot:model-router:daily', + }); + + // No earlier turn says this router picks once per chat, so the row is already showing when the kept pick arrives. + fire({ + type: 'chat/usage', + session, + turnId, + usage: { _meta: { modelRouted: { router: 'daily', chosenModel: 'gpt-5.4-mini', kept: true, firstTurnOnly: true } } }, + } as ChatAction); + fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); + await turnPromise; + + assert.deepStrictEqual(collected.flat().flatMap(part => part.kind === 'autoModeResolution' ? [[part.router, part.resolved?.name, part.kept]] : []), [ + ['Daily Driver', undefined, undefined], + ['daily', 'GPT-5.4 mini', true], + ]); + })); + test('Copilot Fusion routing shows only the resolved part', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const languageModels = new Map([ ['agent-host-copilot:auto', upcastPartial({ name: 'Copilot Fusion', autoModelFusion: true })], @@ -9879,7 +10213,7 @@ suite('AgentHostChatContribution', () => { }; 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 } }], + standard: [{ kind: 'autoModeResolution', resolved: { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', reason }, fusion: true }], highOrMax: [], }); })); @@ -10063,7 +10397,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { cost: 1.5 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10111,7 +10445,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire, collected } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { userSelectedModelId: 'agent-host-copilot:hydrafusion', cancellationToken: cts.token, }); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { cost: 15.5 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { copilotUsage: { totalNanoAiu: 15_500_000_000 } } } } as ChatAction); if (cancelled) { cts.cancel(); } else { @@ -10135,7 +10469,7 @@ suite('AgentHostChatContribution', () => { ]); const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables, { languageModels, provider: 'copilotcli' }); const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { userSelectedModelId: 'agent-host-copilot:hydrafusion' }); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'gpt-5.6-sol', inputTokens: 100, _meta: cost === undefined ? {} : { cost } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'gpt-5.6-sol', inputTokens: 100, _meta: cost === undefined ? {} : { copilotUsage: { totalNanoAiu: cost * 1_000_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); assert.strictEqual((await turnPromise).details, cost === undefined ? 'HydraFusion Preview · 2x' : 'HydraFusion Preview • 2 credits'); })); @@ -10147,7 +10481,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'openrouter/amazon/nova-micro-v1', _meta: { cost: 1.5 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'openrouter/amazon/nova-micro-v1', _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10161,7 +10495,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'customendpoint/custom-model', _meta: { cost: 1 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'customendpoint/custom-model', _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10179,7 +10513,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { cancellationToken: cts.token }); // Usage (credits) accumulated before the user interrupts the turn. - fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { cost: 1.5 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } } } as ChatAction); // User cancels mid-flight before the turn reaches a terminal state. cts.cancel(); @@ -10197,7 +10531,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { cost: 0 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'opus-4.7', _meta: { copilotUsage: { totalNanoAiu: 0 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10215,8 +10549,8 @@ suite('AgentHostChatContribution', () => { const { turnPromise, collected, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); - fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 100, _meta: { cost: 1 } } } as ChatAction); - fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 100, model: 'claude-sonnet-4-6', _meta: { cost: 1 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 100, _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 100, model: 'claude-sonnet-4-6', _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10241,7 +10575,7 @@ suite('AgentHostChatContribution', () => { const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { userSelectedModelId: 'agent-host-copilot:auto' }); - fire({ type: 'chat/usage', session, turnId, usage: { model: 'raptor-mini', _meta: { cost: 1 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { model: 'raptor-mini', _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } } } as ChatAction); fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); const result = await turnPromise; @@ -10275,7 +10609,7 @@ suite('AgentHostChatContribution', () => { // Parent turn reports its own usage. For hosts that fold subagent usage // into the parent turn aggregate, this value already includes the subagent; // the client emits it as-is and never re-adds subagent credits itself. - fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 500, outputTokens: 100, model: 'gpt-5', _meta: { cost: 2.0 } } } as ChatAction); + fire({ type: 'chat/usage', session, turnId, usage: { inputTokens: 500, outputTokens: 100, model: 'gpt-5', _meta: { copilotUsage: { totalNanoAiu: 2_000_000_000 } } } } as ChatAction); // Spawn a subagent tool call. const parentToolCallId = 'tc-sub-cost'; @@ -10316,7 +10650,7 @@ suite('AgentHostChatContribution', () => { } as ChatAction); fireChild({ type: 'chat/usage', session: childSessionUri, turnId: childTurnId, - usage: { inputTokens: 800, outputTokens: 200, model: 'openrouter/amazon/nova-micro-v1', _meta: { cost: 5.0 } }, + usage: { inputTokens: 800, outputTokens: 200, model: 'openrouter/amazon/nova-micro-v1', _meta: { copilotUsage: { totalNanoAiu: 5_000_000_000 } } }, } as ChatAction); await timeout(50); @@ -10869,6 +11203,45 @@ suite('AgentHostChatContribution', () => { await turnPromise; })); + test('marks a completion as a person\'s only when they settled the request in its UI', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); + const { turnPromise, collected, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); + const question = { kind: ChatInputQuestionKind.Text, id: 'q', message: 'Delete the file?', required: true }; + const plan: ChatInputRequestWithPlanReview = { + id: 'plan', + planReview: { title: 'Review Plan', content: 'Plan', canProvideFeedback: true, answerQuestionId: 'action', actions: [{ id: 'interactive', label: 'Implement Plan', default: true }] }, + }; + for (const request of [{ id: 'answered', questions: [question] }, { id: 'dismissed', questions: [question] }, { id: 'defaults', questions: [question] }, plan]) { + fire({ type: ActionType.ChatInputRequested, request } as ChatAction); + } + await timeout(10); + const [answered, dismissed, defaults] = collected.flat().filter((part): part is ChatQuestionCarouselData => part instanceof ChatQuestionCarouselData); + const review = collected.flat().find((part): part is ChatPlanReviewData => part instanceof ChatPlanReviewData)!; + agentHostService.dispatchedActions.length = 0; + + answered.submittedByUser = true; + answered.completion.complete({ answers: { q: 'Yes' } }); + dismissed.submittedByUser = true; + dismissed.completion.complete({ answers: undefined }); + // Defaults submitted for the person when they send another message. + defaults.submittedByUser = false; + defaults.completion.complete({ answers: { q: 'Yes' } }); + review.submittedByUser = true; + review.completion.complete({ rejected: true }); + await timeout(10); + + const answer = { q: { state: ChatInputAnswerState.Submitted, value: { kind: ChatInputAnswerValueKind.Text, value: 'Yes' } } }; + const human = { 'agentHost.inputResponseSource': 'human_response' }; + assert.deepStrictEqual(agentHostService.dispatchedActions.filter(d => d.action.type === ActionType.ChatInputCompleted).map(d => d.action), [ + { type: ActionType.ChatInputCompleted, requestId: 'answered', response: ChatInputResponseKind.Accept, answers: answer, _meta: human }, + { type: ActionType.ChatInputCompleted, requestId: 'dismissed', response: ChatInputResponseKind.Cancel, _meta: human }, + { type: ActionType.ChatInputCompleted, requestId: 'defaults', response: ChatInputResponseKind.Accept, answers: answer }, + { type: ActionType.ChatInputCompleted, requestId: 'plan', response: ChatInputResponseKind.Decline, _meta: human }, + ]); + fire({ type: ActionType.ChatTurnComplete, turnId, endedAt: '2025-01-01T00:00:00.000Z' } as ChatAction); + await turnPromise; + })); + test('plan-review rejection dispatches a decline without selecting an implementation action', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); const { turnPromise, collected, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); @@ -11055,6 +11428,47 @@ suite('AgentHostChatContribution', () => { await turnPromise; })); + test('freeform input request submission preserves the advertised single-select kind', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); + const { turnPromise, collected, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); + + fire({ + type: ActionType.ChatInputRequested, + request: { + id: 'input-1', + questions: [{ + kind: ChatInputQuestionKind.SingleSelect, + id: 'answer', + message: 'Which release?', + required: true, + options: [{ id: 'preview', label: 'Preview' }], + allowFreeformInput: true, + }], + }, + } as ChatAction); + await timeout(10); + + const carousel = collected.flat().find(part => part.kind === 'questionCarousel'); + assert.ok(carousel instanceof ChatQuestionCarouselData); + carousel.dismiss({ answer: { freeformValue: 'latest' } }); + await timeout(10); + + assert.deepStrictEqual(agentHostService.dispatchedActions.find(dispatched => dispatched.action.type === ActionType.ChatInputCompleted)?.action, { + type: ActionType.ChatInputCompleted, + requestId: 'input-1', + response: ChatInputResponseKind.Accept, + answers: { + answer: { + state: ChatInputAnswerState.Submitted, + value: { kind: ChatInputAnswerValueKind.Selected, value: '', freeformValues: ['latest'] }, + }, + }, + }); + + fire({ type: ActionType.ChatTurnComplete, turnId, endedAt: '2025-01-01T00:00:00.000Z' } as ChatAction); + await turnPromise; + })); + test('input request completion from another client clears local question carousel', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService, chatWidgetService } = createContribution(disposables); const sessionResource = URI.from({ scheme: 'agent-host-copilot', path: '/new-input-request-test' }); @@ -11373,7 +11787,7 @@ suite('AgentHostChatContribution', () => { completionsBeforeClick: [], completions: [{ channel: session, - action: { type: ActionType.ChatInputCompleted, requestId: 'empty-form', response, ...(response === ChatInputResponseKind.Accept ? { answers: {} } : {}) }, + action: { type: ActionType.ChatInputCompleted, requestId: 'empty-form', response, ...(response === ChatInputResponseKind.Accept ? { answers: {} } : {}), _meta: { 'agentHost.inputResponseSource': 'human_response' } }, }], state: response === ChatInputResponseKind.Accept ? ElicitationState.Accepted : ElicitationState.Rejected, openedUrls: [], @@ -12804,6 +13218,47 @@ suite('AgentHostChatContribution', () => { await turnPromise; })); + for (const scope of [SAVE_SESSION_SANDBOX_PATH, SAVE_WORKSPACE_SANDBOX_PATH]) { + test(`sandbox path grant ${scope} dispatches without writing settings or claiming a saved receipt`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { sessionHandler, agentHostService, chatAgentService, instantiationService } = createContribution(disposables); + const config = instantiationService.invokeFunction(accessor => accessor.get(IConfigurationService)); + const update = sinon.stub(config, 'updateValue'); + try { + const { turnPromise, collected, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); + fire({ type: 'chat/toolCallStart', session, turnId, toolCallId: 'tc-session-grant', toolName: 'read_file', displayName: 'Read File' } as ChatAction); + fire({ + type: 'chat/toolCallReady', session, turnId, toolCallId: 'tc-session-grant', + invocationMessage: 'Read /outside', confirmationTitle: 'Allow sandbox path access and retry?', + _meta: { 'vscode.sandboxPathGrant': { path: '/outside', access: 'read' } }, + options: [ + { id: SAVE_SESSION_SANDBOX_PATH, label: 'Allow for This Session', kind: ConfirmationOptionKind.Approve }, + { id: SAVE_WORKSPACE_SANDBOX_PATH, label: 'Allow for This Workspace', kind: ConfirmationOptionKind.Approve }, + { id: SAVE_SANDBOX_PATH, label: 'Allow for This User', kind: ConfirmationOptionKind.Approve }, + { id: 'skip', label: 'Skip', kind: ConfirmationOptionKind.Deny }, + ], + } as ChatAction); + await timeout(10); + const invocation = collected.flat().find(p => p.kind === 'toolInvocation'); + assert.ok(invocation?.kind === 'toolInvocation'); + IChatToolInvocation.confirmWith(invocation, { type: ToolConfirmKind.UserAction, selectedButton: scope }); + await timeout(10); + const confirmations = agentHostService.dispatchedActions.filter(a => a.action.type === 'chat/toolCallConfirmed'); + assert.deepStrictEqual({ + settingsWrites: update.callCount, + confirmations: confirmations.map(item => ({ + option: (item.action as IToolCallConfirmedAction).selectedOptionId, + receipt: readAgentPermissionResponseMeta(item.action as IToolCallConfirmedAction).sandboxPathGrantSaved, + source: readAgentPermissionResponseMeta(item.action as IToolCallConfirmedAction).decisionSource, + })), + }, { settingsWrites: 0, confirmations: [{ option: scope, receipt: undefined, source: 'human_response' }] }); + fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); + await turnPromise; + } finally { + update.restore(); + } + })); + } + for (const failSave of [false, true]) { test(`sandbox path grant ${failSave ? 'keeps confirmation open when saving fails' : 'saves before dispatching the grant'}`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService, instantiationService } = createContribution(disposables); @@ -13906,9 +14361,8 @@ suite('AgentHostChatContribution', () => { const { sessionHandler, agentHostService } = createContribution(disposables); const sessionResource = URI.from({ scheme: 'agent-host-copilot', path: '/completion-history' }); const sessionUri = AgentSession.uri('copilot', 'completion-history'); + const skillUri = 'file:///skills/agent-host-docs/SKILL.md'; const skillMeta = { - uri: 'file:///skills/agent-host-docs/SKILL.md', - displayName: 'agent-host-docs', description: 'Use this skill when working on Agent Host code', }; const commandMeta = { @@ -13926,7 +14380,8 @@ suite('AgentHostChatContribution', () => { origin: { kind: MessageKind.User }, attachments: [ { - type: MessageAttachmentKind.Simple, + type: MessageAttachmentKind.Resource, + uri: skillUri, label: '/agent-host-docs', displayKind: 'skill', _meta: skillMeta, @@ -13958,7 +14413,7 @@ suite('AgentHostChatContribution', () => { value: variable.value, _meta: variable._meta, })), [ - toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/agent-host-docs', skillMeta.uri, skillMeta), + toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/agent-host-docs', skillUri, skillMeta), toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Command, '/rename', 'rename', commandMeta), ]); } @@ -14143,7 +14598,7 @@ suite('AgentHostChatContribution', () => { ]); const { sessionHandler, agentHostService } = createContribution(disposables, { languageModels, provider }); const sessionUri = AgentSession.uri(provider, 'sess-fusion-footers'); - const usage = { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { cost: 15.5 } }; + const usage = { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { copilotUsage: { totalNanoAiu: 15_500_000_000 } } }; const fusionMessage = { text: 'Fusion request', origin: { kind: MessageKind.User }, model: { id: 'hydrafusion' } } as const; agentHostService.sessionStates.set(sessionUri.toString(), { ...createSessionState({ @@ -14192,7 +14647,7 @@ suite('AgentHostChatContribution', () => { ]); const { sessionHandler, agentHostService } = createContribution(disposables, { languageModels, provider: 'copilotcli' }); const sessionUri = AgentSession.uri('copilotcli', 'sess-fusion-footers'); - const usage = { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { cost: 15.5 } }; + const usage = { model: 'gpt-5.6-sol', inputTokens: 100, outputTokens: 20, _meta: { copilotUsage: { totalNanoAiu: 15_500_000_000 } } }; const message = (model: string) => ({ text: 'Fusion request', origin: { kind: MessageKind.User }, model: { id: model } } as const); agentHostService.sessionStates.set(sessionUri.toString(), { ...createSessionState({ @@ -14231,7 +14686,7 @@ suite('AgentHostChatContribution', () => { id: 'turn-1', message: { text: 'Q1', origin: { kind: MessageKind.User } }, responseParts: [{ kind: ResponsePartKind.Markdown, id: 'md-1', content: 'A1' }], - usage: { model: 'opus-4.7', _meta: { cost: 1.5 } }, + usage: { model: 'opus-4.7', _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } }, state: TurnState.Complete, }, { @@ -14247,7 +14702,7 @@ suite('AgentHostChatContribution', () => { startedAt: '2025-01-01T00:00:00.000Z', message: { text: 'Q3', origin: { kind: MessageKind.User }, model: { id: 'sonnet-4.6', config: { reasoningEffort: 'max' } } }, responseParts: [], - usage: { _meta: { cost: 1 } }, + usage: { _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } }, }, }); @@ -14961,12 +15416,12 @@ suite('AgentHostChatContribution', () => { childState.turns[0] = { ...childState.turns[0], startedAt: new Date(startedAt).toISOString(), duration: 40_000, - usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 0.5 } }, + usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 500_000_000 } } }, }; childState.turns.push({ ...childState.turns[0], id: 'followup', startedAt: new Date(startedAt + 60_000).toISOString(), duration: 23_000, - usage: { inputTokens: 20, outputTokens: 10, _meta: { cost: 0.25 } }, + usage: { inputTokens: 20, outputTokens: 10, _meta: { copilotUsage: { totalNanoAiu: 250_000_000 } } }, }); const { session, pills } = await scenario.open(); const pill = pills.find(part => part.toolCallId === 'launch-1'); @@ -14993,7 +15448,7 @@ suite('AgentHostChatContribution', () => { turns: [{ ...childState.turns[0], id: 'earlier', startedAt: new Date(startedAt - 10_000).toISOString(), duration: 10_000, - usage: { inputTokens: 30, outputTokens: 15, _meta: { cost: 1.25 } }, + usage: { inputTokens: 30, outputTokens: 15, _meta: { copilotUsage: { totalNanoAiu: 1_250_000_000 } } }, }], }, serverSeq: 100, origin: undefined, @@ -15028,7 +15483,7 @@ suite('AgentHostChatContribution', () => { childState.turns[0] = { ...childState.turns[0], ...(duration !== undefined ? { startedAt: children[0].modifiedAt, duration } : {}), - usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 2.5 } }, + usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 2_500_000_000 } } }, }; const childResource = getSubagentEditorResource({ chatResource: child, parentSessionResource: resource.toString() }); assert.ok(childResource); @@ -15057,7 +15512,7 @@ suite('AgentHostChatContribution', () => { const startedAt = Date.parse(children[0].modifiedAt); const latestTurn: Turn = { ...childState.turns[0], startedAt: new Date(startedAt).toISOString(), duration: 20_000, - usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 0.5 } }, + usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 500_000_000 } } }, }; const tail = { ...childState, turns: [latestTurn], turnsNextCursor: 'older' }; agentHostService.chatStates.set(child, tail); @@ -15076,7 +15531,7 @@ suite('AgentHostChatContribution', () => { type: ActionType.ChatTurnsLoaded, turns: [{ ...latestTurn, id: 'earlier', startedAt: new Date(startedAt - 60_000).toISOString(), duration: 30_000, - usage: { inputTokens: 20, outputTokens: 10, _meta: { cost: 1.5 } }, + usage: { inputTokens: 20, outputTokens: 10, _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } }, }], turnsNextCursor: hasMoreHistory ? 'oldest' : undefined, }, @@ -15113,7 +15568,7 @@ suite('AgentHostChatContribution', () => { assert.ok(childState); childState.turns[0] = { ...childState.turns[0], startedAt: children[0].modifiedAt, duration: 40_000, - usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 2.5 } }, + usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 2_500_000_000 } } }, }; const { pills } = await scenario.open(); const presentation = () => { @@ -15129,7 +15584,7 @@ suite('AgentHostChatContribution', () => { ...childState, turns: childState.turns.map(turn => ({ ...turn, - usage: restoredCredits === undefined ? undefined : { inputTokens: 10, outputTokens: 5, _meta: { cost: restoredCredits } }, + usage: restoredCredits === undefined ? undefined : { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: restoredCredits * 1_000_000_000 } } }, })), }); const reopened = disposables.add(await sessionHandler.provideChatSessionContent(childResource, CancellationToken.None)); @@ -15439,8 +15894,8 @@ suite('AgentHostChatContribution', () => { for (const [index, child] of children.entries()) { const state = agentHostService.chatStates.get(child.resource); assert.ok(state?.activeTurn); - state.turns[0].usage = { inputTokens: 10, outputTokens: 5, _meta: { cost: index === 0 ? 0.5 : 0.75 } }; - state.activeTurn.usage = { inputTokens: 10, outputTokens: 5, _meta: { cost: 0.25 } }; + state.turns[0].usage = { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: index === 0 ? 500_000_000 : 750_000_000 } } }; + state.activeTurn.usage = { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 250_000_000 } } }; } const { pills } = await scenario.open(); const credits = () => pills.filter(part => part.toolSpecificData?.kind === 'subagent') @@ -15449,7 +15904,7 @@ suite('AgentHostChatContribution', () => { let sequence = 100; const fireChild = (chat: string, action: AgentHostChatAction) => agentHostService.fireAction({ channel: chat, action, serverSeq: sequence++, origin: undefined }); for (const [index, child] of children.entries()) { - fireChild(child.resource, { type: ActionType.ChatUsage, turnId: 'child-turn', usage: { inputTokens: 20, outputTokens: 10, _meta: { cost: index + 2 } } }); + fireChild(child.resource, { type: ActionType.ChatUsage, turnId: 'child-turn', usage: { inputTokens: 20, outputTokens: 10, _meta: { copilotUsage: { totalNanoAiu: (index + 2) * 1_000_000_000 } } } }); fire({ type: ActionType.SessionChatUpdated, chat: child.resource, changes: { status: SessionStatus.Idle } }); fireChild(child.resource, chatTurnComplete('child-turn', 40000)); } @@ -15471,7 +15926,7 @@ suite('AgentHostChatContribution', () => { assert.ok(previous); agentHostService.chatStates.set(child, { ...previous, activeTurn: createActiveTurn('followup', { text: 'Continue', origin: { kind: MessageKind.User } }, '2026-10-19T00:01:00.000Z') }); fire({ type: ActionType.SessionChatUpdated, chat: child, changes: { status: SessionStatus.InProgress, modifiedAt: '2026-10-19T00:01:00.000Z' } }); - fireChild(child, { type: ActionType.ChatUsage, turnId: 'followup', usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 0.5 } } }); + fireChild(child, { type: ActionType.ChatUsage, turnId: 'followup', usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 500_000_000 } } } }); fire({ type: ActionType.SessionChatUpdated, chat: child, changes: { status: SessionStatus.Idle, modifiedAt: '2026-10-19T00:01:10.000Z' } }); fireChild(child, chatTurnComplete('followup', 10000)); await timeout(0); @@ -15494,7 +15949,7 @@ suite('AgentHostChatContribution', () => { const state = agentHostService.chatStates.get(child); assert.ok(state); state.activeTurn = undefined; - state.turns[0].usage = { inputTokens: 10, outputTokens: 5, _meta: { cost: 2.5 } }; + state.turns[0].usage = { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 2_500_000_000 } } }; await scenario.open(); fire({ type: ActionType.SessionChatUpdated, chat: child, changes: { status: SessionStatus.Idle } }); await timeout(0); @@ -15519,7 +15974,7 @@ suite('AgentHostChatContribution', () => { const child = children[0].resource; agentHostService.fireAction({ channel: child, - action: { type: ActionType.ChatUsage, turnId: 'child-turn', usage: { inputTokens: 10, outputTokens: 5, _meta: { cost: 2.5 } } }, + action: { type: ActionType.ChatUsage, turnId: 'child-turn', usage: { inputTokens: 10, outputTokens: 5, _meta: { copilotUsage: { totalNanoAiu: 2_500_000_000 } } } }, serverSeq: 99, origin: undefined, }); fire({ type: ActionType.SessionChatUpdated, chat: child, changes: { status: SessionStatus.Idle } }); @@ -17028,6 +17483,38 @@ suite('AgentHostChatContribution', () => { ]); })); + for (const metadata of [undefined, { 'copilot.attachmentDetail': { type: 'terminal_selection' } }]) { + test(`terminal selection becomes a model-readable attachment ${metadata ? 'with' : 'without'} metadata`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); + const selection = '$ echo hello\nhello'; + + const { turnPromise, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { + message: 'Explain this terminal output.', + variables: { + variables: [{ + kind: 'generic', + id: 'terminal-selection-1', + name: 'Terminal Selection', + fullName: 'Terminal Selection', + value: selection, + icon: Codicon.terminal, + ...(metadata ? { _meta: metadata } : {}), + }], + }, + }); + fire(chatTurnComplete(turnId, 0)); + await turnPromise; + + const turnAction = agentHostService.turnActions[0].action as ITurnStartedAction; + assert.deepStrictEqual(turnAction.message.attachments, [{ + type: MessageAttachmentKind.Simple, + label: 'Terminal Selection', + modelRepresentation: selection, + ...(metadata ? { displayKind: 'terminal-selection', _meta: metadata } : {}), + }]); + })); + } + test('generic web references become model-readable attachments without treating them as files', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); const urls = ['https://aka.ms/vscode-agent-skills', 'http://example.com/documentation']; @@ -19599,7 +20086,7 @@ suite('AgentHostChatContribution', () => { message: 'Proceed after reconnect?', completions: [{ channel: chatUri, - action: { type: ActionType.ChatInputCompleted, requestId: 'empty-form', response: ChatInputResponseKind.Accept, answers: {} }, + action: { type: ActionType.ChatInputCompleted, requestId: 'empty-form', response: ChatInputResponseKind.Accept, answers: {}, _meta: { 'agentHost.inputResponseSource': 'human_response' } }, }], }); }); @@ -24463,6 +24950,43 @@ suite('AgentHostChatContribution', () => { assert.deepStrictEqual(records.map(record => record.rootToolCallsBeforeFirstText), [1]); })); + test('first response timing ignores subagent reasoning and text', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { sessionHandler, agentHostService, chatAgentService, instantiationService } = createContribution(disposables); + const records = captureFirstResponseTimings(instantiationService); + const { turnPromise, collected, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables); + const parentToolCallId = 'tc-parent-task'; + const parentSession = mintedTestChatOwner(session); + assert.ok(parentSession); + const childSessionUri = buildSubagentChatUri(parentSession, parentToolCallId); + const childState = makeChildState(childSessionUri, 'tc-child-1'); + childState.activeTurn!.responseParts.unshift( + { kind: ResponsePartKind.Reasoning, id: 'child-thought', content: 'Child reasoning' }, + { kind: ResponsePartKind.Markdown, id: 'child-answer', content: 'Child answer' }, + ); + agentHostService.sessionStates.set(childSessionUri, childState); + fire({ + type: 'chat/toolCallStart', session, turnId, + toolCallId: parentToolCallId, toolName: 'task', displayName: 'Task', + _meta: { toolKind: 'subagent', subagentDescription: 'do some work', subagentAgentName: 'helper' }, + } as ChatAction); + fire({ type: 'chat/toolCallReady', session, turnId, toolCallId: parentToolCallId, invocationMessage: 'Spawning subagent', confirmed: 'not-needed' } as ChatAction); + fire({ + type: 'chat/toolCallContentChanged', session, turnId, toolCallId: parentToolCallId, + content: [{ type: ToolResultContentType.Subagent, resource: childSessionUri, title: 'Subagent' }], + } as ChatAction); + await timeout(50); + fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); + await turnPromise; + + assert.deepStrictEqual({ + childToolObserved: collected.flat().some(part => part.kind === 'toolInvocation' && part.subAgentInvocationId === parentToolCallId), + timings: records.map(record => ({ hasResponseText: record.hasResponseText, firstResponseOrReasoningMs: record.firstResponseOrReasoningMs })), + }, { + childToolObserved: true, + timings: [{ hasResponseText: false, firstResponseOrReasoningMs: undefined }], + }); + })); + for (const alreadyFailed of [false, true]) { test(`subagent failures stay out of parent markdown (alreadyFailed=${alreadyFailed})`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables); @@ -26201,11 +26725,11 @@ suite('AgentHostChatContribution', () => { rangeStart: 0, rangeEnd: 1, attachment: { - type: MessageAttachmentKind.Simple, + type: MessageAttachmentKind.Resource, + uri: 'file:///skills/agent-host-docs/SKILL.md', label: '/agent-host-docs', + displayKind: 'skill', _meta: { - uri: 'file:///skills/agent-host-docs/SKILL.md', - displayName: 'Agent Host Docs', description: 'Use this skill when working on Agent Host code', }, }, @@ -26229,11 +26753,9 @@ suite('AgentHostChatContribution', () => { attachment: { kind: 'skill', uri: URI.parse('file:///skills/agent-host-docs/SKILL.md'), - displayName: 'Agent Host Docs', + displayName: 'agent-host-docs', description: 'Use this skill when working on Agent Host code', _meta: { - uri: 'file:///skills/agent-host-docs/SKILL.md', - displayName: 'Agent Host Docs', description: 'Use this skill when working on Agent Host code', }, }, @@ -26243,15 +26765,15 @@ suite('AgentHostChatContribution', () => { }); for (const authority of ['local', 'sandbox']) { - test(`maps MCP skill completion resources and preserves friendly display names (${authority})`, async () => { + test(`maps MCP skill completion resources and preserves namespaced invocation labels (${authority})`, async () => { const { sessionHandler, agentHostService } = createContribution(disposables); agentHostService.resourceUris = createAgentHostResourceUriMapper(authority); const resource = URI.parse(buildMcpResourceUri('opaque-mcp-channel:skills', 'skill://server/friendly/SKILL.md', 'Friendly')); - const meta = { uri: resource.toString(), name: 'Friendly', displayName: 'Friendly', description: 'MCP skill (MCP: Server)' }; + const meta = { description: 'MCP skill (MCP: Server)' }; agentHostService.completions = async () => ({ items: [{ insertText: '/mcp1:server:friendly ', rangeStart: 0, rangeEnd: 1, - attachment: { type: MessageAttachmentKind.Simple, label: '/Friendly', _meta: meta }, + attachment: { type: MessageAttachmentKind.Resource, uri: resource.toString(), label: '/mcp1:server:friendly', displayKind: 'skill', _meta: meta }, }] }); @@ -26261,7 +26783,7 @@ suite('AgentHostChatContribution', () => { items: [{ insertText: '/mcp1:server:friendly ', start: { lineNumber: 1, column: 1 }, end: { lineNumber: 1, column: 2 }, - attachment: { kind: 'skill', uri: toAgentHostUri(resource, authority), displayName: 'Friendly', description: meta.description, _meta: meta }, + attachment: { kind: 'skill', uri: toAgentHostUri(resource, authority), displayName: 'mcp1:server:friendly', description: meta.description, _meta: meta }, }] }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatInputPicker.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatInputPicker.test.ts index 853888c7ba94..5ae4715dbe04 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatInputPicker.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatInputPicker.test.ts @@ -46,13 +46,14 @@ import { NullOpenerService } from '../../../../../../platform/opener/test/common import { IStorageService } from '../../../../../../platform/storage/common/storage.js'; import { COPILOT_SANDBOX_ALLOW_BYPASS_KEY, IManagedSettingsService, ManagedSettingsData, NullManagedSettingsService } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import { IAgentHostNewSessionFolderService } from '../../../browser/agentSessions/agentHost/agentHostNewSessionFolderService.js'; import { IAgentHostSessionWorkingDirectoryResolver } from '../../../browser/agentSessions/agentHost/agentHostSessionWorkingDirectoryResolver.js'; import { IAgentHostUntitledProvisionalSessionService } from '../../../browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.js'; import { IChatAcceptInputOptions, IChatWidget } from '../../../browser/chat.js'; import { IChatRequestModel } from '../../../common/model/chatModel.js'; import { IChatViewModel } from '../../../common/model/chatViewModel.js'; -import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; +import { TestStorageService, TestWorkspaceTrustManagementService } from '../../../../../test/common/workbenchTestServices.js'; import { IsSessionsWindowContext } from '../../../../../common/contextkeys.js'; import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; import * as dom from '../../../../../../base/browser/dom.js'; @@ -294,6 +295,7 @@ suite('AgentHostChatInputPicker - combined mode and permissions', () => { }); instantiationService.stub(IAgentHostSessionWorkingDirectoryResolver, { resolve: () => undefined }); instantiationService.stub(IWorkspaceContextService, { getWorkspace: () => ({ id: 'test', folders: [] }) }); + instantiationService.set(IWorkspaceTrustManagementService, store.add(new TestWorkspaceTrustManagementService())); instantiationService.stub(IAgentHostNewSessionFolderService, { getFolder: () => undefined, getDefaultFolder: () => undefined }); const resolvedRefreshes: Record[] = []; instantiationService.stub(IAgentHostUntitledProvisionalSessionService, { onDidChange: Event.None, get: () => undefined, getResolvedConfig: () => undefined, refreshResolvedConfig: async (_resource, _provider, _directory, values) => { resolvedRefreshes.push(values ?? {}); } }); @@ -1094,12 +1096,16 @@ suite('AgentHostChatInputPicker - combined mode and permissions', () => { const withoutMetadata = permissionPicker['_getSandboxStandaloneToggle']()!.disabled; await sandboxReady(); await permissionPicker['_showPicker'](dom.$('div')); - const staleToggle = actionWidget.items.find(item => item.standaloneToggle)!.standaloneToggle!; + const initialRow = actionWidget.items.find(item => item.standaloneToggle)!; + const staleToggle = initialRow.standaloneToggle!; + assert.strictEqual(initialRow.hover?.content, staleToggle.title); state._meta = withSessionSandboxPolicy(undefined, { enabled: true, allowBypass: false }); permissionPicker['_sandboxConfigChanged'].trigger(undefined); staleToggle.onChange(true); - const required = actionWidget.items.find(item => item.standaloneToggle)!.standaloneToggle!; + const requiredRow = actionWidget.items.find(item => item.standaloneToggle)!; + const required = requiredRow.standaloneToggle!; const enforced = { checked: required.checked, disabled: required.disabled, title: required.title }; + assert.strictEqual(requiredRow.hover?.content, required.title); state._meta = withSessionSandboxPolicy(undefined, { enabled: false }); permissionPicker['_sandboxConfigChanged'].trigger(undefined); const removed = actionWidget.items.find(item => item.standaloneToggle)!.standaloneToggle!; @@ -2073,6 +2079,7 @@ suite('AgentHostChatInputPicker - sandbox toggle', () => { new class extends mock() { }(), managedSettingsService, new class extends mock() { }(), + store.add(new TestWorkspaceTrustManagementService()), )); widget.viewModel = new class extends mock() { override readonly sessionResource = URI.from({ scheme: SessionType.AgentHostCopilot, path: '/test-session' }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostClientTools.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostClientTools.test.ts index 6039d48dfbde..0e0c8592b091 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostClientTools.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostClientTools.test.ts @@ -1116,6 +1116,7 @@ suite('AgentHostClientTools', () => { onDidChangeLanguageModels: Event.None, deltaLanguageModelChatProviderDescriptors: () => { }, registerLanguageModelProvider: () => toDisposable(() => { }), + lookupLanguageModel: () => undefined, }); instantiationService.stub(IConfigurationService, configService); instantiationService.stub(IOutputService, { getChannel: () => undefined }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts index 133d4c1d46d1..4558ec18f31b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts @@ -17,6 +17,7 @@ import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { remoteAgentHostSessionTypeId } from '../../../../../../platform/agentHost/common/agentHostSessionType.js'; +import { SessionConfigKey } from '../../../../../../platform/agentHost/common/sessionConfigKeys.js'; import { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; import { IAgentHostMcpOAuthMetadataService } from '../../../../../../platform/agentHost/common/agentHostMcpOAuthMetadataService.js'; import { withMcpServerConnectorNameMeta, withMcpServerControllingSettingMeta, withMcpServerDisplayNameMeta, withMcpServerSourceMeta, withMcpServerSourcePluginMeta } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; @@ -585,6 +586,27 @@ suite('AbstractAgentHostCustomizationService', () => { ]); }); + test('exposes host permissions only when their schema is writable', () => { + const sut = createSut(); + const session = URI.parse('vscode-agent-session:///session-1'); + const permissions = { allow: ['Mcp(server)'], deny: ['Write'], ask: ['Read'] }; + const configs: IAgentHostCustomizationTarget['rootConfig'][] = [ + undefined, + { schema: { type: 'object', properties: {} }, values: { permissions } }, + { schema: { type: 'object', properties: { [SessionConfigKey.Permissions]: { type: 'object', title: 'Permissions', readOnly: true } } }, values: { permissions } }, + { schema: { type: 'object', properties: { [SessionConfigKey.Permissions]: { type: 'object', title: 'Permissions', readOnly: false } } }, values: { permissions } }, + { schema: { type: 'object', properties: { [SessionConfigKey.Permissions]: { type: 'object', title: 'Permissions' } } }, values: {} }, + ]; + const results = configs.map(config => { + sut.setTarget(session, new class extends FakeTarget { + readonly rootConfig = config; + }([])); + return sut.getHostPermissions(session); + }); + + assert.deepStrictEqual(results, [undefined, undefined, undefined, permissions, { allow: [], deny: [] }]); + }); + test('preserves global and session decisions when re-enabling workspace enablement', () => { const sut = createSut(); const session = URI.parse('vscode-agent-session:///session-1'); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostFirstResponseTelemetry.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostFirstResponseTelemetry.test.ts index 5021e12789c4..64756ef41866 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostFirstResponseTelemetry.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostFirstResponseTelemetry.test.ts @@ -22,10 +22,36 @@ suite('AgentHostFirstResponseTiming', () => { timing.observeText('duplicate'); assert.deepStrictEqual(timing.finish({ requestId: 'turn', provider: 'copilot', connectionKind: AgentHostClientConnectionKind.WebPubSub, agentSessionId: 'session', chatId: 'chat', outcome: 'success', sessionTurnKind: 'first', invocationKind: 'newTurn', trustInteractionRequired: false }), { schemaVersion: 1, requestId: 'turn', provider: 'copilot', connectionKind: AgentHostClientConnectionKind.WebPubSub, agentSessionId: 'session', chatId: 'chat', outcome: 'success', sessionTurnKind: 'first', invocationKind: 'newTurn', trustInteractionRequired: false, - firstResponseTextMs: 250, rootToolCallsBeforeFirstText: 0, totalElapsedMs: 900, hasResponseText: true, + firstResponseTextMs: 250, firstResponseOrReasoningMs: 250, rootToolCallsBeforeFirstText: 0, totalElapsedMs: 900, hasResponseText: true, }); }); + test('times the first nonwhitespace reasoning or text without moving the text timing', () => { + const time = (outputs: readonly (readonly ['text' | 'reasoning', string])[]) => { + let elapsed = 0; + const timing = new AgentHostFirstResponseTiming({ elapsed: () => elapsed }); + for (const [kind, text] of outputs) { + elapsed += 100; + if (kind === 'text') { + timing.observeText(text); + } else { + timing.observeReasoning(text); + } + } + const { firstResponseTextMs, firstResponseOrReasoningMs, hasResponseText } = timing.finish({ requestId: 'turn', provider: 'copilot', connectionKind: AgentHostClientConnectionKind.Local, outcome: 'success', sessionTurnKind: 'first', invocationKind: 'newTurn', trustInteractionRequired: false }); + return { firstResponseTextMs, firstResponseOrReasoningMs, hasResponseText }; + }; + assert.deepStrictEqual([ + time([['reasoning', ' \n'], ['reasoning', 'thinking'], ['reasoning', 'more'], ['text', 'answer']]), + time([['text', 'answer'], ['reasoning', 'thinking']]), + time([['reasoning', 'thinking']]), + ], [ + { firstResponseTextMs: 400, firstResponseOrReasoningMs: 200, hasResponseText: true }, + { firstResponseTextMs: 100, firstResponseOrReasoningMs: 100, hasResponseText: true }, + { firstResponseTextMs: undefined, firstResponseOrReasoningMs: 100, hasResponseText: false }, + ]); + }); + test('counts distinct root tools only until first nonwhitespace text', () => { const timing = new AgentHostFirstResponseTiming({ elapsed: () => 42 }); timing.observeToolCall('rename'); @@ -54,7 +80,7 @@ suite('AgentHostFirstResponseTiming', () => { timing.observeToolCall('no-answer'); assert.deepStrictEqual(timing.finish({ requestId: 'turn', provider: 'copilot', connectionKind: AgentHostClientConnectionKind.Unknown, outcome, sessionTurnKind: 'unknown', invocationKind: 'unknown', trustInteractionRequired: false }), { schemaVersion: 1, requestId: 'turn', provider: 'copilot', connectionKind: AgentHostClientConnectionKind.Unknown, outcome, sessionTurnKind: 'unknown', invocationKind: 'unknown', trustInteractionRequired: false, - firstResponseTextMs: undefined, rootToolCallsBeforeFirstText: undefined, totalElapsedMs: 42, hasResponseText: false, + firstResponseTextMs: undefined, firstResponseOrReasoningMs: undefined, rootToolCallsBeforeFirstText: undefined, totalElapsedMs: 42, hasResponseText: false, }); }); } diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostGenericConfigChips.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostGenericConfigChips.test.ts index cde05db7014d..ed69dc839e4a 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostGenericConfigChips.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostGenericConfigChips.test.ts @@ -8,10 +8,11 @@ import * as dom from '../../../../../../base/browser/dom.js'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; -import { IReference } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, IReference } from '../../../../../../base/common/lifecycle.js'; +import { ResourceSet } from '../../../../../../base/common/map.js'; import { constObservable } 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 { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAgentConnection, IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; @@ -36,15 +37,17 @@ import { TestDialogService } from '../../../../../../platform/dialogs/test/commo import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../../platform/hover/test/browser/nullHoverService.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../../platform/label/common/label.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { NullOpenerService } from '../../../../../../platform/opener/test/common/nullOpenerService.js'; import { IStorageService } from '../../../../../../platform/storage/common/storage.js'; import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import { IChatWidget, IChatWidgetViewModelChangeEvent } from '../../../browser/chat.js'; import { IChatViewModel } from '../../../common/model/chatViewModel.js'; import { IChatPhoneInputPresenter } from '../../../browser/widget/input/chatPhoneInputPresenter.js'; -import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; +import { TestStorageService, TestWorkspaceTrustManagementService } from '../../../../../test/common/workbenchTestServices.js'; import { TestPathService } from '../../../../../test/browser/workbenchTestServices.js'; import { IPreferencesService } from '../../../../../services/preferences/common/preferences.js'; import { AgentHostGenericConfigChips } from '../../../browser/agentSessions/agentHost/agentHostGenericConfigChips.js'; @@ -67,8 +70,9 @@ function createSubscription(): IAgentSubscription { suite('AgentHostGenericConfigChips', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); - function createChips(generic: boolean, { sessionResource = URI.parse('agent-host-copilotcli:/untitled-restoration'), configuration = new TestConfigurationService(), initialConfig, preparedConfig }: { sessionResource?: URI; configuration?: TestConfigurationService; initialConfig?: Record; preparedConfig?: ResolveSessionConfigResult } = {}) { + function createChips(generic: boolean, { sessionResource = URI.parse('agent-host-copilotcli:/untitled-restoration'), configuration = new TestConfigurationService(), initialConfig, preparedConfig, trustService, property = 'mode' }: { sessionResource?: URI; configuration?: TestConfigurationService; initialConfig?: Record; preparedConfig?: ResolveSessionConfigResult; trustService?: IWorkspaceTrustManagementService; property?: string } = {}) { const requests: Parameters[0][] = []; + const completionRequests: Parameters[0][] = []; const answers: DeferredPromise[] = []; const acquired: string[] = []; const released: string[] = []; @@ -76,6 +80,8 @@ suite('AgentHostGenericConfigChips', () => { const provisionalChanged = disposables.add(new Emitter()); const sessionChanged = disposables.add(new Emitter()); const sessionErrored = disposables.add(new Emitter()); + const folderChanged = disposables.add(new Emitter()); + let folder: URI | undefined; let provisionalBackend: URI | undefined; let sessionState: SessionState | Error | undefined; const subscriptions: { [K in StateComponents]?: IAgentSubscription } = { @@ -103,12 +109,16 @@ suite('AgentHostGenericConfigChips', () => { answers.push(answer); return answer.p; } + override async sessionConfigCompletions(request: Parameters[0]): Promise { + completionRequests.push(request); + return { items: [] }; + } }(); const remoteService = new class extends mock() { override readonly onDidChangeConnections = Event.None; override readonly connections: readonly IRemoteAgentHostConnectionInfo[] = []; }(); - const connections = disposables.add(new AgentHostConnectionsService(agentHost, remoteService, new TestPathService(), new NullLogService())); + const connections = disposables.add(new AgentHostConnectionsService(agentHost, remoteService, new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); const changed = disposables.add(new Emitter()); const widget = new class extends mock() { override readonly onDidChangeViewModel = changed.event; @@ -128,11 +138,26 @@ suite('AgentHostGenericConfigChips', () => { getOrCreate: async (...args) => { provisionalRequests.push(args); return undefined; }, }); instantiation.stub(IAgentHostSessionWorkingDirectoryResolver, { resolve: () => URI.file('/workspace') }); - instantiation.stub(IAgentHostNewSessionFolderService, { getFolder: () => undefined }); - instantiation.stub(IWorkspaceContextService, {}); + instantiation.stub(IAgentHostNewSessionFolderService, { getFolder: () => folder, onDidChangeFolder: folderChanged.event }); + instantiation.stub(IWorkspaceContextService, { onDidChangeWorkspaceFolders: Event.None }); + instantiation.set(IWorkspaceTrustManagementService, trustService ?? disposables.add(new TestWorkspaceTrustManagementService(true, new ResourceSet([URI.file('/workspace')])))); disposables.add(configuration.onDidChangeConfigurationEmitter); instantiation.set(IConfigurationService, configuration); - instantiation.stub(IActionWidgetService, { isVisible: false, hide: () => { } }); + const actionWidget = new class extends mock() { + override isVisible = false; + private _onHide: (() => void) | undefined; + override show(_id: string, _supportsPreview: boolean, _items: readonly IActionListItem[], delegate: IActionListDelegate): void { + this.isVisible = true; + this._onHide = delegate.onHide; + } + override hide(): void { + this.isVisible = false; + const onHide = this._onHide; + this._onHide = undefined; + onHide?.(); + } + }(); + instantiation.set(IActionWidgetService, actionWidget); instantiation.set(IHoverService, NullHoverService); instantiation.stub(IOpenerService, {}); instantiation.stub(IDialogService, {}); @@ -147,9 +172,13 @@ suite('AgentHostGenericConfigChips', () => { instantiation.stub(IWorkbenchEnvironmentService, { remoteAuthority: undefined }); const chips = disposables.add(generic ? instantiation.createInstance(AgentHostGenericConfigChips, widget) - : instantiation.createInstance(AgentHostChatInputPicker, widget, 'mode')); + : instantiation.createInstance(AgentHostChatInputPicker, widget, property)); return { - chips, connections, requests, answers, acquired, released, provisionalRequests, sessionResource, restarted, exited, changed, + chips, connections, requests, completionRequests, answers, acquired, released, provisionalRequests, sessionResource, restarted, exited, changed, actionWidget, + setFolder: (target: URI) => { + folder = target; + folderChanged.fire(sessionResource); + }, setProvisional: (backend: URI) => { provisionalBackend = backend; provisionalChanged.fire(sessionResource); @@ -166,6 +195,86 @@ suite('AgentHostGenericConfigChips', () => { } for (const generic of [false, true]) { + for (const pending of [false, true]) { + test(`${generic ? 'generic' : 'dedicated'} chips discard ${pending ? 'pending' : 'resolved'} configuration when selecting an untrusted folder`, async () => { + const property = generic ? 'choice' : 'branch'; + const result: ResolveSessionConfigResult = { + schema: { type: 'object', properties: { [property]: { type: 'string', title: 'Branch', enum: ['main'], enumDynamic: true } } }, + values: { [property]: 'main' }, + }; + const rig = createChips(generic, { property }); + const container = dom.$('div'); + rig.chips.render(container); + await timeout(0); + if (!pending) { + for (const answer of rig.answers) { + await answer.complete(result); + await timeout(0); + } + } + const trigger = container.querySelector('[role="button"]'); + rig.setFolder(URI.file('/untrusted')); + if (pending) { + await rig.answers[0].complete(result); + } + await timeout(0); + trigger?.dispatchEvent(new MouseEvent('click', { bubbles: true })); + await timeout(0); + + assert.deepStrictEqual({ + controls: container.querySelectorAll('[role="button"]').length, + slots: container.querySelectorAll('.agent-host-generic-chip-slot').length, + untrustedRequests: rig.requests.filter(request => request.workingDirectory?.path === '/untrusted'), + completions: rig.completionRequests, + }, { controls: 0, slots: 0, untrustedRequests: [], completions: [] }); + }); + } + + test(`${generic ? 'generic' : 'dedicated'} started-session pickers keep their menu open on unrelated trust changes`, async () => { + const foldersChanged = disposables.add(new Emitter()); + const trustService = disposables.add(new class extends TestWorkspaceTrustManagementService { + override readonly onDidChangeTrustedFolders = foldersChanged.event; + }()); + const rig = createChips(generic, { sessionResource: URI.parse('agent-host-copilotcli:/started'), trustService }); + const property = generic ? 'choice' : 'mode'; + rig.setSessionState(new class extends mock() { + override readonly provider = 'copilotcli'; + override readonly config = { + schema: { type: 'object' as const, properties: { [property]: { type: 'string' as const, title: 'Mode', enum: ['interactive', 'plan'], sessionMutable: true } } }, + values: { [property]: 'interactive' }, + }; + override readonly chats = []; + }()); + const container = dom.$('div'); + rig.chips.render(container); + const trigger = container.querySelector('[role="button"]'); + assert.ok(trigger); + trigger.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })); + await timeout(0); + const before = rig.actionWidget.isVisible; + foldersChanged.fire(); + await trustService.setWorkspaceTrust(false); + assert.deepStrictEqual({ before, after: rig.actionWidget.isVisible }, { before: true, after: true }); + }); + + test(`${generic ? 'generic' : 'dedicated'} chips defer initial configuration until the target folder is trusted`, async () => { + const trustedFoldersChanged = disposables.add(new Emitter()); + const trustService = disposables.add(new class extends TestWorkspaceTrustManagementService { + override readonly onDidChangeTrustedFolders = trustedFoldersChanged.event; + }()); + const rig = createChips(generic, { trustService }); + await timeout(0); + const blocked = rig.requests.length; + await trustService.setTrustedUris([URI.file('/workspace')]); + trustedFoldersChanged.fire(); + await timeout(0); + const resumed = rig.requests.length; + for (const answer of rig.answers) { + await answer.complete({ schema: { type: 'object', properties: {} }, values: {} }); + } + assert.deepStrictEqual({ blocked, resumed }, { blocked: 0, resumed: 1 }); + }); + test(`${generic ? 'generic' : 'dedicated'} chips clear prepared controls when the first snapshot fails`, () => { const property = generic ? 'choice' : 'mode'; const preparedConfig: ResolveSessionConfigResult = { @@ -225,9 +334,9 @@ suite('AgentHostGenericConfigChips', () => { const initialConfig = { mode: 'autopilot', autoApprove: 'autoApprove', isolation: 'folder' }; const rig = createChips(generic, { initialConfig }); await timeout(0); - assert.deepStrictEqual(rig.requests, [{ + assert.deepStrictEqual(rig.requests.map(request => ({ ...request, workingDirectory: request.workingDirectory?.toString() })), [{ provider: 'copilotcli', - workingDirectory: URI.file('/workspace'), + workingDirectory: URI.file('/workspace').toString(), config: initialConfig, }]); await rig.answers[0].complete({ schema: { type: 'object', properties: {} }, values: initialConfig }); @@ -357,6 +466,28 @@ suite('AgentHostGenericConfigChips', () => { }); } + test('initial pickers coalesce trust-source notifications during the target trust check', async () => { + const foldersChanged = disposables.add(new Emitter()); + let trustChecks = 0; + const trustService = disposables.add(new class extends TestWorkspaceTrustManagementService { + override readonly onDidChangeTrustedFolders = foldersChanged.event; + override async getUriTrustInfo(uri: URI) { + if (++trustChecks <= 3) { + foldersChanged.fire(); + } + return { uri, trusted: true }; + } + }()); + const rigs = [createChips(false, { trustService }), createChips(true, { trustService })]; + await timeout(0); + for (const rig of rigs) { + for (const answer of rig.answers) { + await answer.complete({ schema: { type: 'object', properties: {} }, values: {} }); + } + } + assert.deepStrictEqual({ trustChecks, requests: rigs.map(rig => rig.requests.length) }, { trustChecks: 1, requests: [1, 1] }); + }); + for (const generic of [false, true]) { for (const provider of ['claude', 'codex']) { for (const untitled of [false, true]) { @@ -435,7 +566,7 @@ suite('AgentHostGenericConfigChips', () => { override getConnection() { return agentHost; } override getConnectionByAuthority() { return agentHost; } }(); - const connections = disposables.add(new AgentHostConnectionsService(agentHost, remoteService, new TestPathService(), new NullLogService())); + const connections = disposables.add(new AgentHostConnectionsService(agentHost, remoteService, new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); const backend = URI.parse(`${provider}:/parent`); const resource = connections.getSessionResource(backend, remote ? 'host' : AMBIENT_AGENT_HOST_AUTHORITY)!; for (const fragment of ['', 'first-peer', 'second-peer']) { @@ -457,6 +588,7 @@ suite('AgentHostGenericConfigChips', () => { new NullLogService(), agentHost, configuration, + disposables.add(new TestWorkspaceTrustManagementService()), )); chips.dispose(); } @@ -520,6 +652,7 @@ suite('AgentHostGenericConfigChips', () => { new NullLogService(), agentHostService, configuration, + disposables.add(new TestWorkspaceTrustManagementService()), )); currentBackend = secondBackend; @@ -540,6 +673,30 @@ suite('AgentHostGenericConfigChips', () => { suite('AgentHostInitialSessionConfig', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('retries skipped configuration reads rather than caching denied trust', async () => { + const folder = URI.file('/workspace'); + const trustService = store.add(new TestWorkspaceTrustManagementService()); + const requests: Parameters[0][] = []; + const result: ResolveSessionConfigResult = { schema: { type: 'object', properties: {} }, values: { mode: 'interactive' } }; + const connection = new class extends mock() { + override async resolveSessionConfig(request: Parameters[0]): Promise { + requests.push(request); + return result; + } + }(); + const resolver = store.add(new AgentHostInitialSessionConfig(error => { throw error; }, trustService)); + const resource = URI.parse('agent-host-copilotcli:/untitled-trust'); + const resolution = { connection, connectionAuthority: AMBIENT_AGENT_HOST_AUTHORITY, backendSession: URI.parse('ahp-session:/opaque') }; + const blocked = { result: await resolver.resolve(resource, 'copilotcli', resolution, folder), requests: [...requests] }; + await trustService.setTrustedUris([folder]); + const retried = await resolver.resolve(resource, 'copilotcli', resolution, folder); + assert.deepStrictEqual({ blocked, retried, requests }, { + blocked: { result: undefined, requests: [] }, + retried: result, + requests: [{ provider: 'copilotcli', workingDirectory: folder }], + }); + }); + test('shares equal defaults and discards results for superseded defaults', async () => { const configs: (Record | undefined)[] = []; const answers: DeferredPromise[] = []; @@ -553,7 +710,7 @@ suite('AgentHostInitialSessionConfig', () => { }(); const resource = URI.parse('agent-host-copilotcli:/untitled-test'); const resolution = { connection, connectionAuthority: AMBIENT_AGENT_HOST_AUTHORITY, backendSession: URI.parse('ahp-session:/opaque') }; - const resolver = store.add(new AgentHostInitialSessionConfig(error => { throw error; })); + const resolver = store.add(new AgentHostInitialSessionConfig(error => { throw error; }, store.add(new TestWorkspaceTrustManagementService()))); const initial = resolver.resolve(resource, 'copilotcli', resolution, undefined, { mode: 'interactive' }); const shared = resolver.resolve(resource, 'copilotcli', resolution, undefined, { mode: 'interactive' }); await timeout(0); @@ -583,7 +740,7 @@ suite('AgentHostInitialSessionConfig', () => { const second = { ...first, connection: makeConnection('second') }; const resource = URI.parse('remote-opaque-host-test-agent:/untitled-test'); const folder = URI.file('/folder'); - const resolver = store.add(new AgentHostInitialSessionConfig(error => errors.push(error))); + const resolver = store.add(new AgentHostInitialSessionConfig(error => errors.push(error), store.add(new TestWorkspaceTrustManagementService(true, new ResourceSet([folder, URI.file('/new-folder')]))))); const failing = resolver.resolve(resource, 'test-agent', first, folder); const shared = resolver.resolve(resource, 'test-agent', first, folder); await timeout(0); @@ -611,6 +768,28 @@ suite('AgentHostInitialSessionConfig', () => { staleResult: undefined, currentResult: { current: true }, clearedResult: undefined, currentValue: undefined, }); }); + + test('does not dispatch after disposal during target trust resolution', async () => { + const trustCheck = new DeferredPromise(); + const trustService = store.add(new class extends TestWorkspaceTrustManagementService { + override async getUriTrustInfo(uri: URI) { return { uri, trusted: await trustCheck.p }; } + }()); + const requests: Parameters[0][] = []; + const connection = new class extends mock() { + override async resolveSessionConfig(request: Parameters[0]): Promise { + requests.push(request); + return { schema: { type: 'object', properties: {} }, values: {} }; + } + }(); + const resolver = store.add(new AgentHostInitialSessionConfig(error => { throw error; }, trustService)); + const pending = resolver.resolve(URI.parse('agent-host-copilotcli:/untitled-trust'), 'copilotcli', { + connection, connectionAuthority: AMBIENT_AGENT_HOST_AUTHORITY, backendSession: URI.parse('ahp-session:/opaque'), + }, URI.file('/workspace')); + await timeout(0); + resolver.dispose(); + await trustCheck.complete(true); + assert.deepStrictEqual({ result: await pending, requests }, { result: undefined, requests: [] }); + }); }); suite('AgentHostGenericConfigChips - remote sessions', () => { @@ -713,7 +892,7 @@ suite('AgentHostGenericConfigChips - remote sessions', () => { return [...remoteConnections].find(([address]) => agentHostAuthority(address) === authority)?.[1]; } }(); - const connectionsService = store.add(new AgentHostConnectionsService(ambient, remoteService, new TestPathService(), new NullLogService())); + const connectionsService = store.add(new AgentHostConnectionsService(ambient, remoteService, new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); const registerPolicy = (address: string) => store.add(connectionsService.registerSessionResolutionPolicy(agentHostAuthority(address), { sessionSchemeAlias: { ui: 'test-agent', backend: 'ahp-session' }, })); @@ -770,6 +949,7 @@ suite('AgentHostGenericConfigChips - remote sessions', () => { instantiationService.stub(IPreferencesService, {}); instantiationService.stub(IAgentHostSessionWorkingDirectoryResolver, { resolve: () => undefined }); instantiationService.stub(IWorkspaceContextService, { getWorkspace: () => ({ id: 'test', folders: [] }) }); + instantiationService.set(IWorkspaceTrustManagementService, store.add(new TestWorkspaceTrustManagementService())); instantiationService.stub(IAgentHostNewSessionFolderService, { getFolder: () => undefined, getDefaultFolder: () => undefined }); instantiationService.stub(IAgentHostUntitledProvisionalSessionService, { onDidChange: Event.None, get: () => undefined, getResolvedConfig: () => undefined, diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLocalModelSupport.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLocalModelSupport.test.ts index ba48c74b4dd4..745fcf8cf32f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLocalModelSupport.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLocalModelSupport.test.ts @@ -104,6 +104,11 @@ suite('AgentHostLocalModelSupport', () => { fallbackExplainabilityHidden: getLocalModelTurnPresentation({ execution: 'fallback', fallbackModel: 'gpt-5-mini' }, { ...context, hideCloudModelName: true })?.name, direct: getLocalModelTurnPresentation({ execution: 'local' }, { ...context, isAuto: false }), unnamed: [getLocalModelTurnPresentation({ execution: 'local' }, { ...context, localName: undefined })?.name, getLocalModelTurnPresentation({ execution: 'local' }, { ...context, isAuto: false, localName: undefined })?.name], + fusion: [ + getLocalModelTurnPresentation({ execution: 'local', familyId: mai.familyId }, { ...context, fusion: true })?.name, + getLocalModelTurnPresentation({ execution: 'fallback', fallbackModel: 'gpt-5-mini' }, { ...context, fusion: true })?.routed?.reason, + getLocalModelTurnPresentation({ execution: 'mixed', fallbackModel: 'gpt-5-mini' }, { ...context, fusion: true })?.name, + ], }, { local: { name: 'Auto (Example Flash 1.0 \u00b7 On-device)', @@ -126,6 +131,11 @@ suite('AgentHostLocalModelSupport', () => { fallbackExplainabilityHidden: 'Auto (a cloud model)', direct: { name: 'Example Flash 1.0 \u00b7 On-device', pricing: 'No usage limit' }, unnamed: ['Auto (On-device model)', 'On-device model'], + fusion: [ + 'Copilot Fusion (Example Flash 1.0 \u00b7 On-device)', + 'Copilot Fusion routed task to GPT-5 mini. The on-device model was unavailable, so a cloud model was used.', + 'Copilot Fusion (On-device + GPT-5 mini)', + ], }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostPolicyContinuationEditor.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostPolicyContinuationEditor.test.ts index 7ee8de87e94e..ebc4865bbec3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostPolicyContinuationEditor.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostPolicyContinuationEditor.test.ts @@ -18,6 +18,10 @@ import { IViewsService } from '../../../../../services/views/common/viewsService import { AgentHostImportConversationStore, IAgentHostImportConversationStore } from '../../../browser/agentSessions/agentHost/agentHostImportConversationStore.js'; import { EditorAgentHostPolicyContinuationPresenter } from '../../../browser/agentSessions/agentHost/agentHostPolicyContinuationEditor.js'; import { ChatViewId, IChatWidget } from '../../../browser/chat.js'; +import { IChatViewHostService } from '../../../browser/chatViewHost.js'; +import { ChatViewHostService } from '../../../browser/widgetHosts/viewPane/chatViewHostService.js'; +import { IViewDescriptorService } from '../../../../../common/views.js'; +import { IWorkbenchLayoutService } from '../../../../../services/layout/browser/layoutService.js'; import { ChatEditorInput } from '../../../browser/widgetHosts/editor/chatEditorInput.js'; import { ChatViewPane } from '../../../browser/widgetHosts/viewPane/chatViewPane.js'; import { IChatService } from '../../../common/chatService/chatService.js'; @@ -72,6 +76,10 @@ suite('Editor Agent Host policy continuation presenter', () => { services.stub(IAgentHostImportConversationStore, new AgentHostImportConversationStore()); services.stub(IProgressService, {}); services.stub(ILogService, new NullLogService()); + // The sidebar is the Chat view, as in the workbench + services.stub(IViewDescriptorService, {}); + services.stub(IWorkbenchLayoutService, {}); + services.stub(IChatViewHostService, services.createInstance(ChatViewHostService)); const presenter = services.createInstance(EditorAgentHostPolicyContinuationPresenter); return { state, navigation, diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSandboxNotification.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSandboxNotification.test.ts index 9676a7bca936..8c83d481e0de 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSandboxNotification.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSandboxNotification.test.ts @@ -939,6 +939,31 @@ suite('AgentHostSandboxNotification', () => { assert.deepStrictEqual({ hasInstallButton: hasInstallButton(service), actions: service.notifications.get(id)?.actions }, { hasInstallButton: false, actions: [] }); }); + test('transcript guidance wraps below the reply with the action aligned to the description', () => { + const subscription = store.add(new TestSubscription()); + subscription.setValue(); + subscription.setCertificate(certificate); + const service = new NotificationService(); + enableRefresh(async () => { }); + focus(resource); + createNotification(resource, subscription, service); + const widget = renderWarning(service, [], inputUri, 'transcript'); + const row = document.createElement('div'); + row.className = 'interactive-item-container'; + row.append(widget.domNode); + document.body.append(row); + try { + for (const width of [680, 300, 680]) { + row.style.width = `${width}px`; + const text = row.querySelector('.chat-input-notification-description')!.getBoundingClientRect(); + const action = row.querySelector('.monaco-button')!.getBoundingClientRect(); + assert.ok(text.height > 0 && action.top >= text.bottom && action.left === text.left && action.right <= row.getBoundingClientRect().right); + } + } finally { + row.remove(); + } + }); + const remoteGuidance = 'Install the sandbox certificate authority (CA) on the remote agent host so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. On the host, run code agent sandbox ca create, then code agent sandbox ca trust. Learn more.'; function enableRefresh(refresh: (chat: string, scopeId: string) => Promise) { @@ -1060,7 +1085,9 @@ suite('AgentHostSandboxNotification', () => { focus(resource); createNotification(resource, subscription, service); const commands: Parameters[] = []; - const widget = renderWarning(service, commands, inputUri); + const composer = renderWarning(service, commands, inputUri); + assert.strictEqual(composer.domNode.querySelector('.chat-input-notification-actions'), null); + const widget = renderWarning(service, commands, inputUri, 'transcript'); const button = widget.domNode.querySelector('.chat-input-notification-actions .monaco-button'); assert.ok(button); const description = widget.domNode.querySelector('.chat-input-notification-description'); @@ -1231,6 +1258,7 @@ suite('AgentHostSandboxNotification', () => { hostVisible: constObservable(true), modelTargetChatSessionType: constObservable('agent-host-copilot'), sessionResource: constObservable(resource), + placement: 'transcript', })); const descriptionElement = widget.domNode.querySelector('.chat-input-notification-description'); assert.ok(descriptionElement); @@ -1263,7 +1291,7 @@ suite('AgentHostSandboxNotification', () => { }, { renderedButton: { label: 'Install', role: 'button', tabIndex: 0, ariaLabel: 'Sandbox trusted CA is not installed (optional) Install' }, calls: outcome === 'cancelled' ? 0 : 1, confirmations: 1, - description: 'Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. Learn more.', + description: 'Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. You can install it later from the Command Palette with Sandbox: Manage Trusted CA. Learn more.', descriptionLinks: ['Learn more'], descriptionEnding: true, untrustedContent: false, keepOpen: true, actions: 1, pending: id, @@ -1519,10 +1547,10 @@ suite('AgentHostSandboxNotification', () => { assert.deepStrictEqual({ before, body: { ...body, description: rendered.element.textContent }, links: links.map(link => link.textContent), openedLinks, dismissible: typeof onDismiss, dispatched }, { before: 0, body: { - id, inputUri, + id, inputUri, placement: 'transcript', severity: ChatInputNotificationSeverity.Info, message: 'Sandbox trusted CA is not installed (optional)', - description: isWeb ? remoteGuidance : 'Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. Learn more.', + description: isWeb ? remoteGuidance : 'Install the sandbox certificate authority (CA) so developer tools can connect securely through a proxy that adds credentials to outgoing requests without exposing them to agent tools. You can install it later from the Command Palette with Sandbox: Manage Trusted CA. Learn more.', actions: [], dismissible: true, autoDismissOnMessage: false, sessionResources: [resource], }, links: ['Learn more'], @@ -1626,8 +1654,12 @@ suite('AgentHostSandboxNotification', () => { service.dismissNotification(warning.id); const info = service.getActiveNotification(); assert.ok(info); - const certificateRendered = widget.domNode.textContent?.includes('Sandbox trusted CA is not installed (optional)'); - const installButton = widget.domNode.querySelector('.chat-input-notification-actions .monaco-button'); + assert.strictEqual(widget.domNode.textContent?.includes('Sandbox trusted CA is not installed (optional)'), false); + const transcriptWidget = store.add(widgetInstantiationService.createInstance(ChatInputNotificationWidget, { + placement: 'transcript', inputUri, sessionResource: constObservable(resource), + })); + const certificateRendered = transcriptWidget.domNode.textContent?.includes('Sandbox trusted CA is not installed (optional)'); + const installButton = transcriptWidget.domNode.querySelector('.chat-input-notification-actions .monaco-button'); const renderedButton = { label: installButton?.textContent, tabIndex: installButton?.tabIndex }; service.dismissNotification(info.id); subscription.setCertificate(certificate); @@ -1831,7 +1863,7 @@ suite('AgentHostSandboxNotification', () => { }); }); - function renderWarning(service: NotificationService, commands: Parameters[] = [], inputUri?: URI): ChatInputNotificationWidget { + function renderWarning(service: NotificationService, commands: Parameters[] = [], inputUri?: URI, placement?: 'transcript'): ChatInputNotificationWidget { const widgetInstantiationService = store.add(workbenchInstantiationService(undefined, store)); widgetInstantiationService.stub(IChatInputNotificationService, { onDidChange: Event.None, @@ -1846,7 +1878,7 @@ suite('AgentHostSandboxNotification', () => { }, }); return store.add(widgetInstantiationService.createInstance(ChatInputNotificationWidget, { - inputUri, + placement, inputUri, hostVisible: constObservable(true), modelTargetChatSessionType: constObservable('agent-host-copilot'), sessionResource: constObservable(resource), diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSettingsFileSystemProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSettingsFileSystemProvider.test.ts index 2a0c9cfa3acd..5d50f0365351 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSettingsFileSystemProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostSettingsFileSystemProvider.test.ts @@ -227,6 +227,22 @@ suite('AgentHostSettingsFileSystemProvider (ambient editor-window adapter)', () assert.strictEqual(events[0].toString(), uri.toString()); }); + test('stat changes modification time for same-size content changes', async () => { + const schema = { mode: { type: 'string', title: 'Mode', enum: ['ab', 'ba'] } } satisfies Record; + const { fs, uri, agentHostService } = createHarness(makeRootState(schema, { mode: 'ab' })); + + const first = await fs.stat(uri); + const unchanged = await fs.stat(uri); + agentHostService.setRootState(makeRootState(schema, { mode: 'ba' })); + const changed = await fs.stat(uri); + + assert.deepStrictEqual({ + sameSize: changed.size === first.size, + unchangedMtime: unchanged.mtime === first.mtime, + changedMtime: changed.mtime > first.mtime, + }, { sameSize: true, unchangedMtime: true, changedMtime: true }); + }); + test('root state hydrates after construction (readFile reflects late-arriving config)', async () => { const { fs, uri, agentHostService } = createHarness(); // no initial state diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostToolApprovals.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostToolApprovals.test.ts new file mode 100644 index 000000000000..2d2fd68a0840 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostToolApprovals.test.ts @@ -0,0 +1,317 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { waitForState } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IPermissionsValue } from '../../../../../../platform/agentHost/common/agentHostSchema.js'; +import { CommandsRegistry, ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { CLOUD_SANDBOX_TASK_SCHEME } from '../../../../../../platform/agentHost/common/agentHostSessionType.js'; +import { MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID } from '../../../browser/actions/chatActions.js'; +import { IAgentHostCustomizationService, NullAgentHostCustomizationService } from '../../../browser/agentSessions/agentHost/agentHostCustomizationService.js'; +import { manageAgentHostToolApprovals } from '../../../browser/agentSessions/agentHost/agentHostToolApprovals.js'; +import { IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; +import { IChatViewModel } from '../../../common/model/chatViewModel.js'; +import { InternalFetchWebPageToolId } from '../../../common/tools/builtinTools/tools.js'; +import { ILanguageModelToolsConfirmationService, IToolPreApprovalStore } from '../../../common/tools/languageModelToolsConfirmationService.js'; +import { ILanguageModelToolsService, IToolData, ToolDataSource } from '../../../common/tools/languageModelToolsService.js'; +import { TerminalToolId } from '../../../common/tools/terminalToolIds.js'; + +type IAgentHostMcpServer = ReturnType[number]; + +suite('AgentHostToolApprovals', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + test('discovers tools and updates exact host grants while preserving other rules', async () => { + const sessionResource = URI.parse('remote-peer-claude:/opaque-session'); + const runningTools = new DeferredPromise>>>(); + const stoppedTools = new DeferredPromise>>>(); + const initialPermissions: IPermissionsValue = { + allow: ['Shell(git *)', 'Mcp(stopped/old)', 'Mcp(stopped/old)', 'Mcp(failed)'], + deny: ['Mcp(running/denied)'], + ask: ['Read'], + }; + let hostPermissions = initialPermissions; + const writes: { resource: string; permissions: IPermissionsValue }[] = []; + const customizationService = new class extends NullAgentHostCustomizationService { + override getHostPermissions(): IPermissionsValue { return hostPermissions; } + override getMcpServers(): readonly IAgentHostMcpServer[] { + return [ + upcastPartial({ name: 'running', enabled: true, listTools: () => runningTools.p }), + upcastPartial({ name: 'stopped', enabled: false, listTools: () => stoppedTools.p }), + upcastPartial({ name: 'failed', enabled: false, listTools: async () => { throw new Error('Unavailable'); } }), + upcastPartial({ name: 'disabled', enabled: false }), + ]; + } + override setHostPermissions(resource: URI, permissions: IPermissionsValue): void { + hostPermissions = permissions; + writes.push({ resource: resource.toString(), permissions }); + } + }; + const shown: { tools: readonly IToolData[]; store?: IToolPreApprovalStore } = { tools: [] }; + const confirmationService = new class extends mock() { + override manageConfirmationPreferences(tools: readonly IToolData[], options?: Parameters[1]): void { + shown.tools = tools; + shown.store = options?.preApprovalStore; + } + }; + const fetchTool: IToolData = { id: InternalFetchWebPageToolId, source: ToolDataSource.Internal, displayName: 'Fetch', modelDescription: '' }; + const toolsService = new class extends mock() { + override getTool(id: string): IToolData | undefined { return id === fetchTool.id ? fetchTool : undefined; } + }; + const handled = manageAgentHostToolApprovals(sessionResource, customizationService, confirmationService, toolsService, true); + const preApprovalStore = shown.store!; + const initial = { + tools: shown.tools.map(tool => [tool.id, tool.displayName]), + discoveredTools: preApprovalStore.discoveredTools!.get(), + isDiscovering: preApprovalStore.isDiscovering!.get(), + }; + await runningTools.complete([ + { name: 'raw', title: 'Display Name', annotations: { title: 'Ignored Title' } }, + { name: 'annotated', annotations: { title: 'Annotated Title' } }, + ]); + await waitForState(preApprovalStore.discoveredTools!, tools => tools.length > 0); + const partial = { + tools: preApprovalStore.discoveredTools!.get().map(tool => [tool.id, tool.displayName]), + isDiscovering: preApprovalStore.isDiscovering!.get(), + }; + await stoppedTools.complete([{ name: 'old', title: 'Old Tool' }, { name: 'old', title: 'Old Tool' }]); + await waitForState(preApprovalStore.isDiscovering!, discovering => !discovering); + const oldTool = shown.tools.find(tool => tool.id === 'agentHostMcp:stopped/old')!; + const states = [preApprovalStore.isToolApproved(oldTool), preApprovalStore.isServerApproved('running')]; + preApprovalStore.setServerApproved('running', true); + states.push(preApprovalStore.isServerApproved('running')); + preApprovalStore.setToolApproved(oldTool, false); + states.push(preApprovalStore.isToolApproved(oldTool)); + preApprovalStore.setToolApproved(oldTool, true); + preApprovalStore.setToolApproved(oldTool, true); + preApprovalStore.setServerApproved('running', false); + preApprovalStore.setServerApproved('', true); + preApprovalStore.setToolApproved(fetchTool, true); + const discoveredTool = preApprovalStore.discoveredTools!.get().find(tool => tool.id === 'agentHostMcp:running/raw')!; + preApprovalStore.setToolApproved(discoveredTool, true); + states.push(preApprovalStore.isToolApproved(discoveredTool)); + preApprovalStore.setToolApproved(discoveredTool, false); + states.push(preApprovalStore.isToolApproved(discoveredTool)); + + assert.deepStrictEqual({ + handled, + initial, + partial, + discoveredTools: preApprovalStore.discoveredTools!.get().map(tool => [tool.id, tool.displayName]), + isDiscovering: preApprovalStore.isDiscovering!.get(), + servers: preApprovalStore.servers, + states, + allowWrites: writes.map(write => write.permissions.allow), + preserved: writes.every(write => write.permissions.deny === initialPermissions.deny && write.permissions.ask === initialPermissions.ask && write.resource === sessionResource.toString()), + originalAllow: initialPermissions.allow, + }, { + handled: true, + initial: { + tools: [['agentHostMcp:stopped/old', 'old']], + discoveredTools: [], + isDiscovering: true, + }, + partial: { + tools: [['agentHostMcp:running/raw', 'Display Name'], ['agentHostMcp:running/annotated', 'Annotated Title']], + isDiscovering: true, + }, + discoveredTools: [['agentHostMcp:running/raw', 'Display Name'], ['agentHostMcp:running/annotated', 'Annotated Title'], ['agentHostMcp:stopped/old', 'Old Tool']], + isDiscovering: false, + servers: [{ id: 'running', label: 'running' }, { id: 'stopped', label: 'stopped' }, { id: 'failed', label: 'failed' }], + states: [true, false, true, false, true, false], + allowWrites: [ + ['Shell(git *)', 'Mcp(stopped/old)', 'Mcp(failed)', 'Mcp(running)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(running)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(running)', 'Mcp(stopped/old)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(running)', 'Mcp(stopped/old)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(stopped/old)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(stopped/old)', 'Mcp(running/raw)'], + ['Shell(git *)', 'Mcp(failed)', 'Mcp(stopped/old)'], + ], + preserved: true, + originalAllow: ['Shell(git *)', 'Mcp(stopped/old)', 'Mcp(stopped/old)', 'Mcp(failed)'], + }); + }); + + test('merges picker overrides with external host changes before writes are acknowledged', () => { + const sessionResource = URI.parse('remote-peer-claude:/opaque-session'); + let hostPermissions: IPermissionsValue = { allow: ['Mcp(server/tool)'], deny: [] }; + const writes: IPermissionsValue[] = []; + const customizationService = new class extends NullAgentHostCustomizationService { + override getHostPermissions(): IPermissionsValue { return hostPermissions; } + override getMcpServers(): readonly IAgentHostMcpServer[] { + return [upcastPartial({ name: 'server', enabled: true })]; + } + override setHostPermissions(_resource: URI, permissions: IPermissionsValue): void { + writes.push(permissions); + } + }; + const shown: { tools: readonly IToolData[]; store?: IToolPreApprovalStore } = { tools: [] }; + const confirmationService = new class extends mock() { + override manageConfirmationPreferences(tools: readonly IToolData[], options?: Parameters[1]): void { + shown.tools = tools; + shown.store = options?.preApprovalStore; + } + }; + const toolsService = new class extends mock() { }; + manageAgentHostToolApprovals(sessionResource, customizationService, confirmationService, toolsService, true); + const preApprovalStore = shown.store!; + const tool = shown.tools[0]; + preApprovalStore.setServerApproved('server', true); + + hostPermissions = { allow: ['WebFetch(example.com)', 'Mcp(other)'], deny: ['Write'], ask: ['Read'] }; + const states = [preApprovalStore.isServerApproved('server'), preApprovalStore.isServerApproved('other'), preApprovalStore.isToolApproved(tool)]; + preApprovalStore.setToolApproved(tool, true); + states.push(preApprovalStore.isToolApproved(tool)); + hostPermissions = { ...hostPermissions, allow: [...hostPermissions.allow, 'Mcp(server)'] }; + preApprovalStore.setServerApproved('server', false); + states.push(preApprovalStore.isServerApproved('server')); + + assert.deepStrictEqual({ states, writes }, { + states: [true, true, false, true, false], + writes: [ + { allow: ['Mcp(server/tool)', 'Mcp(server)'], deny: [] }, + { allow: ['WebFetch(example.com)', 'Mcp(other)', 'Mcp(server)', 'Mcp(server/tool)'], deny: ['Write'], ask: ['Read'] }, + { allow: ['WebFetch(example.com)', 'Mcp(other)', 'Mcp(server/tool)'], deny: ['Write'], ask: ['Read'] }, + ], + }); + }); + + for (const acknowledgement of ['read', 'write']) { + test(`drops acknowledged overrides on ${acknowledgement} before external revocations`, () => { + const sessionResource = URI.parse('remote-peer-claude:/opaque-session'); + let hostPermissions: IPermissionsValue = { allow: [], deny: [] }; + const writes: string[][] = []; + const customizationService = new class extends NullAgentHostCustomizationService { + override getHostPermissions(): IPermissionsValue { return hostPermissions; } + override getMcpServers(): readonly IAgentHostMcpServer[] { + return ['a', 'b'].map(name => upcastPartial({ name, enabled: true })); + } + override setHostPermissions(_resource: URI, permissions: IPermissionsValue): void { + writes.push([...permissions.allow]); + } + }; + let preApprovalStore: IToolPreApprovalStore | undefined; + const confirmationService = new class extends mock() { + override manageConfirmationPreferences(_tools: readonly IToolData[], options?: Parameters[1]): void { + preApprovalStore = options?.preApprovalStore; + } + }; + const toolsService = new class extends mock() { }; + manageAgentHostToolApprovals(sessionResource, customizationService, confirmationService, toolsService, false); + preApprovalStore!.setServerApproved('a', true); + hostPermissions = { allow: ['Mcp(a)'], deny: [] }; + if (acknowledgement === 'read') { + preApprovalStore!.isServerApproved('a'); + } else { + preApprovalStore!.setServerApproved('b', true); + } + hostPermissions = { allow: [], deny: [] }; + preApprovalStore!.setServerApproved('b', true); + + assert.deepStrictEqual({ writes, approved: preApprovalStore!.isServerApproved('a') }, { + writes: [ + ['Mcp(a)'], + ...(acknowledgement === 'write' ? [['Mcp(a)', 'Mcp(b)']] : []), + ['Mcp(b)'], + ], + approved: false, + }); + }); + } + + test('includes settings-backed URL and terminal tools only when local settings are mirrored', () => { + const customizationService = new class extends NullAgentHostCustomizationService { + override getHostPermissions(): IPermissionsValue { return { allow: [], deny: [] }; } + }; + const shown: (readonly IToolData[])[] = []; + const confirmationService = new class extends mock() { + override manageConfirmationPreferences(tools: readonly IToolData[]): void { + shown.push(tools); + } + }; + const fetchTool: IToolData = { id: InternalFetchWebPageToolId, source: ToolDataSource.Internal, displayName: 'Fetch', modelDescription: '' }; + const terminalTool: IToolData = { id: TerminalToolId.RunInTerminal, source: ToolDataSource.Internal, displayName: 'Terminal', modelDescription: '' }; + const availableTools = new Map([fetchTool, terminalTool].map(tool => [tool.id, tool])); + const toolsService = new class extends mock() { + override getTool(id: string): IToolData | undefined { return availableTools.get(id); } + }; + for (const mirrorsLocalSettings of [true, false]) { + for (const resource of ['agent-host-copilotcli:/session', 'agent-host-claude:/session', 'remote-peer-claude:/opaque-session', `${CLOUD_SANDBOX_TASK_SCHEME}:/session`]) { + manageAgentHostToolApprovals(URI.parse(resource), customizationService, confirmationService, toolsService, mirrorsLocalSettings); + } + } + availableTools.delete(terminalTool.id); + manageAgentHostToolApprovals(URI.parse('agent-host-copilotcli:/session'), customizationService, confirmationService, toolsService, true); + availableTools.delete(fetchTool.id); + manageAgentHostToolApprovals(URI.parse('agent-host-copilotcli:/session'), customizationService, confirmationService, toolsService, true); + assert.deepStrictEqual(shown, [ + [fetchTool, terminalTool], + [fetchTool, terminalTool], + [], + [], + [], + [], + [], + [], + [fetchTool], + [{ id: InternalFetchWebPageToolId, displayName: 'Fetch Web Page', modelDescription: '', source: ToolDataSource.Internal }], + ]); + }); + + test('returns unhandled for non-host sessions or unavailable host root config', () => { + const customizationService = new NullAgentHostCustomizationService(); + const confirmationService = new class extends mock() { }; + const toolsService = new class extends mock() { }; + assert.deepStrictEqual([ + manageAgentHostToolApprovals(URI.parse('vscode-chat-session:/session'), customizationService, confirmationService, toolsService, true), + manageAgentHostToolApprovals(URI.parse('agent-host-claude:/session'), customizationService, confirmationService, toolsService, true), + ], [false, false]); + }); + + for (const registered of [true, false]) { + test(`reports unavailable host approvals when the command is ${registered ? 'unhandled' : 'missing'}`, async () => { + const instantiationService = store.add(new TestInstantiationService()); + let localPickers = 0; + let commandCalls = 0; + const notifications: string[] = []; + const sessionResource = URI.parse('agent-host-claude:/session'); + instantiationService.stub(ILanguageModelToolsConfirmationService, { + manageConfirmationPreferences: () => { localPickers++; }, + }); + instantiationService.stub(ILanguageModelToolsService, { getAllToolsIncludingDisabled: () => [] }); + instantiationService.stub(IChatWidgetService, { + lastFocusedWidget: upcastPartial({ viewModel: upcastPartial({ sessionResource }) }), + }); + instantiationService.stub(ICommandService, new class extends mock() { + override async executeCommand(): Promise { + commandCalls++; + await Promise.resolve(); + return false as T; + } + }()); + instantiationService.stub(INotificationService, { info: message => { notifications.push(String(message)); } }); + const command = CommandsRegistry.getCommand('workbench.action.chat.editToolApproval')!; + if (!registered) { + sinon.stub(CommandsRegistry, 'getCommand').withArgs(MANAGE_AGENT_HOST_TOOL_APPROVALS_COMMAND_ID).returns(undefined); + } + await command.handler(instantiationService); + + assert.deepStrictEqual({ localPickers, commandCalls, notifications }, { + localPickers: 0, + commandCalls: registered ? 1 : 0, + notifications: ['Tool approvals for this agent host are not available yet. Try again once it has connected.'], + }); + }); + } +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostUntitledProvisionalSessionService.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostUntitledProvisionalSessionService.test.ts index 7be72473bd18..086cb94791f3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostUntitledProvisionalSessionService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostUntitledProvisionalSessionService.test.ts @@ -262,6 +262,9 @@ suite('AgentHostUntitledProvisionalSessionService', () => { let cleanup: DisposableStore; let workspaceTrusted: boolean; let untrustedFolders: Set; + let trustCheck: DeferredPromise | undefined; + let onDidChangeTrust: Emitter; + let onDidChangeTrustedFolders: Emitter; let workspaceFolders: URI[]; let workspaceConfiguration: URI | null; let workspaceName: string | undefined; @@ -285,6 +288,9 @@ suite('AgentHostUntitledProvisionalSessionService', () => { warnings = []; workspaceTrusted = true; untrustedFolders = new Set(); + trustCheck = undefined; + onDidChangeTrust = ds.add(new Emitter()); + onDidChangeTrustedFolders = ds.add(new Emitter()); workspaceFolders = []; workspaceConfiguration = null; workspaceName = undefined; @@ -349,8 +355,10 @@ suite('AgentHostUntitledProvisionalSessionService', () => { override getWorkbenchState(): WorkbenchState { return workbenchState; } }); insta.stub(IWorkspaceTrustManagementService, new class extends mock() { + override readonly onDidChangeTrust = onDidChangeTrust.event; + override readonly onDidChangeTrustedFolders = onDidChangeTrustedFolders.event; override isWorkspaceTrusted(): boolean { return workspaceTrusted; } - override async getUriTrustInfo(uri: URI) { return { uri, trusted: !untrustedFolders.has(uri.toString()) }; } + override async getUriTrustInfo(uri: URI) { return { uri, trusted: trustCheck ? await trustCheck.p : !untrustedFolders.has(uri.toString()) }; } }); insta.stub(IUriIdentityService, { extUri: new ExtUri(() => false) } as Partial as IUriIdentityService); folderService = ds.add(insta.createInstance(AgentHostNewSessionFolderService)); @@ -1813,6 +1821,66 @@ suite('AgentHostUntitledProvisionalSessionService', () => { }); }); + for (const selectedFolder of [false, true]) { + test(`preparation defers untrusted ${selectedFolder ? 'selected folders in a trusted workspace' : 'workspaces without a folder'} until trust is granted`, async () => { + const ui = untitledChatUri('untrusted-config'); + const folder = URI.file('/untrusted-target'); + if (selectedFolder) { + workspaceFolders = [URI.file('/trusted-workspace'), folder]; + folderService.setFolder(ui, folder); + untrustedFolders.add(folder.toString()); + } else { + workspaceTrusted = false; + } + const resolved: ResolveSessionConfigResult = { schema: makeSchema(true), values: { isolation: 'folder' } }; + agentHost.resolveQueue = [resolved, resolved]; + + await provisional.prepareSessionConfig(ui); + const blocked = { requests: [...agentHost.resolveCalls], prepared: provisional.getPreparedSessionConfig(ui) }; + workspaceTrusted = true; + untrustedFolders.clear(); + await provisional.prepareSessionConfig(ui); + + assert.deepStrictEqual({ + blocked, + requests: agentHost.resolveCalls, + prepared: provisional.getPreparedSessionConfig(ui), + created: agentHost.createCalls, + }, { + blocked: { requests: [], prepared: undefined }, + requests: [{ provider: 'copilot', workingDirectory: selectedFolder ? folder : undefined, config: { isolation: 'folder' } }], + prepared: resolved, + created: [], + }); + }); + } + + for (const change of ['folder', 'cancellation', 'disposal', 'connection'] as const) { + test(`preparation does not dispatch after ${change} during target trust resolution`, async () => { + const ui = untitledChatUri('pending-trust'); + workspaceFolders = [URI.file('/workspace')]; + trustCheck = new DeferredPromise(); + agentHost.resolveQueue = [{ schema: makeSchema(true), values: { isolation: 'folder' } }]; + const cts = ds.add(new CancellationTokenSource()); + const preparation = provisional.prepareSessionConfig(ui, cts.token); + if (change === 'folder') { + const folder = URI.file('/other-folder'); + workspaceFolders.push(folder); + folderService.setFolder(ui, folder); + } else if (change === 'cancellation') { + cts.cancel(); + } else if (change === 'disposal') { + onDidDisposeChatSession.fire({ sessionResources: [ui], reason: 'disposed' }); + } else { + sessionResolutions.set(ui, undefined); + onDidChangeSessionResolution.fire(); + } + await trustCheck.complete(true); + await preparation; + assert.deepStrictEqual({ requests: agentHost.resolveCalls, prepared: provisional.getPreparedSessionConfig(ui) }, { requests: [], prepared: undefined }); + }); + } + test('prepared defaults remain editable while provisional creation is pending', async () => { const ui = URI.parse('agent-host-copilotcli:/untitled-prepared-edit'); agentHost.resolveQueue = [{ schema: makeSchema(true), values: { isolation: 'folder', mode: 'autopilot' } }]; @@ -1917,8 +1985,23 @@ suite('AgentHostUntitledProvisionalSessionService', () => { assert.deepStrictEqual({ prepared: provisional.getPreparedSessionConfig(ui), warnings }, { prepared: undefined, warnings: [] }); }); + test('preparation timeout prevents dispatch after a delayed trust check', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const ui = untitledChatUri('trust-timeout'); + workspaceFolders = [URI.file('/workspace')]; + trustCheck = new DeferredPromise(); + agentHost.resolveQueue = [{ schema: makeSchema(true), values: {} }]; + const preparation = provisional.prepareSessionConfig(ui); + await timeout(1000); + await preparation; + await trustCheck.complete(true); + await timeout(0); + assert.deepStrictEqual({ requests: agentHost.resolveCalls, prepared: provisional.getPreparedSessionConfig(ui), warnings: warnings.length }, { + requests: [], prepared: undefined, warnings: 1, + }); + })); + for (const changeWhilePending of [true, false]) { - for (const change of ['restart', 'disposal', 'connection'] as const) { + for (const change of ['restart', 'disposal', 'connection', 'workspace trust', 'folder trust'] as const) { test(`invalidates prepared configuration on ${change} ${changeWhilePending ? 'during' : 'after'} resolution`, async () => { const ui = URI.parse('agent-host-copilotcli:/untitled-invalidated'); const answer = new DeferredPromise(); @@ -1929,6 +2012,11 @@ suite('AgentHostUntitledProvisionalSessionService', () => { agentHost.fireAgentHostStart(); } else if (change === 'disposal') { onDidDisposeChatSession.fire({ sessionResources: [ui], reason: 'disposed' }); + } else if (change === 'workspace trust') { + workspaceTrusted = false; + onDidChangeTrust.fire(false); + } else if (change === 'folder trust') { + onDidChangeTrustedFolders.fire(); } else { sessionResolutions.set(ui, undefined); onDidChangeSessionResolution.fire(); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionApprovalModel.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionApprovalModel.test.ts index e7d349b0512f..7c84c1627aa8 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionApprovalModel.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionApprovalModel.test.ts @@ -434,6 +434,30 @@ suite('AgentSessionApprovalModel', () => { assert.strictEqual(getApproval(approvalModel, chatModel), undefined); }); + test('carries where a terminal command runs, and updates when only that changes', () => { + const approvalModel = createModel(); + const chatModel = addChatModel(); + + const stateObs = observableValue('toolState', makeWaitingState()); + let toolSpecificData = makeTerminalToolData({ executionTarget: { workingDirectory: '/work/web' } }); + const part: IChatToolInvocation = { + ...makeToolInvocationPart({ state: makeWaitingState(), toolSpecificData }), + state: stateObs, + get toolSpecificData() { return toolSpecificData; }, + }; + mockModelWithResponse(chatModel, [part]); + chatModel.requestNeedsInput.set({ title: 'Test' }, undefined); + const first = getApproval(approvalModel, chatModel)?.executionTarget; + + toolSpecificData = makeTerminalToolData({ executionTarget: { workingDirectory: '/work/api' } }); + stateObs.set(makeWaitingState(), undefined); + + assert.deepStrictEqual({ first, second: getApproval(approvalModel, chatModel)?.executionTarget }, { + first: { workingDirectory: '/work/web' }, + second: { workingDirectory: '/work/api' }, + }); + }); + test('tracks multiple models independently', () => { const approvalModel = createModel(); const chatModel1 = addChatModel(URI.parse('test://session/1')); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionSettingsFileSystemProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionSettingsFileSystemProvider.test.ts index 499083727db6..711daa102e87 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionSettingsFileSystemProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionSettingsFileSystemProvider.test.ts @@ -6,8 +6,8 @@ import assert from 'assert'; import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; -import { DisposableStore, IReference } from '../../../../../../base/common/lifecycle.js'; -import { mock } from '../../../../../../base/test/common/mock.js'; +import { Disposable, DisposableStore, IReference } from '../../../../../../base/common/lifecycle.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { URI } from '../../../../../../base/common/uri.js'; import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; @@ -18,6 +18,7 @@ import { Registry } from '../../../../../../platform/registry/common/platform.js import { NullLogService, ILogService } from '../../../../../../platform/log/common/log.js'; import { ServiceCollection } from '../../../../../../platform/instantiation/common/serviceCollection.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../../platform/label/common/label.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { FileSystemProviderErrorCode, toFileSystemProviderErrorCode } from '../../../../../../platform/files/common/files.js'; @@ -195,7 +196,7 @@ suite('AgentSessionSettingsFileSystemProvider (editor-window per-session adapter const store = ensureNoDisposablesAreLeakedInTestSuite(); function createConnectionsService(agentHostService: IAgentHostService): AgentHostConnectionsService { - return store.add(new AgentHostConnectionsService(agentHostService, new NullRemoteAgentHostService(), new TestPathService(), new NullLogService())); + return store.add(new AgentHostConnectionsService(agentHostService, new NullRemoteAgentHostService(), new TestPathService(), upcastPartial({ registerFormatter: () => Disposable.None }))); } function createHarness(initialState?: SessionState | Error, configurationService: IConfigurationService = new TestConfigurationService(), backendSession = BACKEND_SESSION) { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsBanner.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsBanner.test.ts index f6ef61133622..89e05fb95f12 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsBanner.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsBanner.test.ts @@ -17,11 +17,11 @@ import { TestConfigurationService } from '../../../../../../platform/configurati import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { TestExperimentTriggerTelemetryService } from '../../../../../../platform/telemetry/test/common/experimentTriggerTestUtils.js'; -import { AgentsWindowOpenSource, isAgentsWindowOpenSource } from '../../../../../../platform/window/common/window.js'; +import { AgentsWindowOpenSource, IOpenedMainWindow, isAgentsWindowOpenSource } from '../../../../../../platform/window/common/window.js'; import { IChatEntitlementService, IChatSentiment } from '../../../../../services/chat/common/chatEntitlementService.js'; import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; import { IHostService } from '../../../../../services/host/browser/host.js'; -import { canShowAgentsBanner, createAgentsBanner } from '../../../browser/agentSessions/agentSessionsBanner.js'; +import { createAgentsBanner, isAgentsWindowAvailable } from '../../../browser/agentSessions/agentSessionsBanner.js'; import { AgentsWindowGraphic } from '../../../browser/agentSessions/agentsWindowGraphic.js'; import { AgentsWindowGraphicVariant, ChatConfiguration, OPEN_WORKSPACE_IN_AGENTS_WINDOW_COMMAND_ID } from '../../../common/constants.js'; @@ -94,7 +94,7 @@ suite('AgentsBanner', () => { } }, visibility: () => ({ - canShow: canShowAgentsBanner(chatEntitlementService, configurationService), + agentsWindowAvailable: isAgentsWindowAvailable(chatEntitlementService, configurationService), display: banner.element.style.display, ariaHidden: banner.element.getAttribute('aria-hidden'), disabled: button.disabled, @@ -119,7 +119,7 @@ suite('AgentsBanner', () => { ...banner.visibility(), commands: banner.state().commands.length, }, { - canShow: enabled, + agentsWindowAvailable: enabled, display: enabled ? '' : 'none', ariaHidden: enabled ? null : 'true', disabled: !enabled, @@ -137,8 +137,8 @@ suite('AgentsBanner', () => { banner.button.click(); } - const visible = { canShow: true, display: '', ariaHidden: null, disabled: false }; - const hidden = { canShow: false, display: 'none', ariaHidden: 'true', disabled: true }; + const visible = { agentsWindowAvailable: true, display: '', ariaHidden: null, disabled: false }; + const hidden = { agentsWindowAvailable: false, display: 'none', ariaHidden: 'true', disabled: true }; assert.deepStrictEqual({ states, sameButton: banner.button === banner.banner.element.querySelector('button'), @@ -150,8 +150,8 @@ suite('AgentsBanner', () => { }); }); - for (const sentiment of [{ hidden: true }, { disabled: true }]) { - test(`keeps the banner hidden when chat is ${sentiment.hidden ? 'hidden' : 'disabled'}`, async () => { + for (const sentiment of [{ hidden: true }, { disabled: true, disabledInWorkspace: true }]) { + test(`keeps the banner hidden when chat is ${sentiment.hidden ? 'hidden' : 'disabled in the workspace'}`, async () => { const banner = createBanner(account, { sentiment }); const states = [banner.visibility().display]; await banner.setAgentEnabled(false); @@ -166,6 +166,22 @@ suite('AgentsBanner', () => { }); } + test('shows the sign-in action when the chat extension is disabled until setup completes', async () => { + const banner = createBanner(null, { sentiment: { installed: true, disabled: true } }); + await Promise.resolve(); + banner.button.click(); + + assert.deepStrictEqual({ + display: banner.visibility().display, + label: banner.state().label, + signInCalls: banner.state().signInCalls, + }, { + display: '', + label: 'Sign in to GitHub', + signInCalls: 1, + }); + }); + test('does not offer sign-in when agent mode is disabled', async () => { const banner = createBanner(null, { configuration: new TestConfigurationService({ @@ -360,6 +376,10 @@ suite('AgentsBanner graphic', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); const graphicTreatment = `config.${ChatConfiguration.WelcomePageAgentsWindowGraphic}`; const sectionStyleTreatment = `config.${ChatConfiguration.WelcomePageAgentsWindowSectionStyle}`; + const multipleEditorWindowsTreatment = `config.${ChatConfiguration.WelcomePageAgentsWindowGraphic}.multipleEditorWindows`; + const agentSessionsWorkspace = URI.file('/agent-sessions.code-workspace'); + const editorWindow = (id: number): IOpenedMainWindow => ({ id, title: '', dirty: false }); + const agentsWindow: IOpenedMainWindow = { id: 99, title: '', dirty: false, workspace: { id: 'agents', configPath: agentSessionsWorkspace } }; const defaultAccountService = new class extends mock() { override currentDefaultAccount = null; override onDidChangeDefaultAccount = Event.None; @@ -369,7 +389,7 @@ suite('AgentsBanner graphic', () => { }(); /** Creates the banner with the graphic, like the Welcome page does. */ - function createBannerWithGraphic(variant: string, telemetryService: TestExperimentTriggerTelemetryService, options: { agentEnabled?: boolean; exposed?: boolean } = {}) { + function createBannerWithGraphic(variant: string, telemetryService: TestExperimentTriggerTelemetryService, options: { agentEnabled?: boolean; exposed?: boolean; windows?: IOpenedMainWindow[] | Promise } = {}) { const configurationService = new TestConfigurationService({ [ChatConfiguration.WelcomePageAgentsWindowGraphic]: variant, [ChatConfiguration.AgentEnabled]: options.agentEnabled ?? true, @@ -381,15 +401,15 @@ suite('AgentsBanner graphic', () => { override onDidChangeSentiment = Event.None; }(); const hostService = new class extends mock() { - override async getWindows() { return [{ id: 1, title: '', dirty: false }]; } + override async getWindows() { return options.windows ?? [editorWindow(1)]; } }(); const environmentService = new class extends mock() { - override agentSessionsWorkspace = URI.file('/agent-sessions.code-workspace'); + override agentSessionsWorkspace = agentSessionsWorkspace; }(); const graphic = store.add(new AgentsWindowGraphic(configurationService, hostService, environmentService)); const exposed = observableValue('exposed', options.exposed ?? true); const banner = createAgentsBanner( - { cssClass: 'agents-banner', graphic: { element: graphic.element, shownDesign: graphic.shownDesign, isExposed: exposed } }, + { cssClass: 'agents-banner', graphic: { element: graphic.element, shownDesign: graphic.shownDesign, isExposed: exposed, hasMultipleEditorWindows: graphic.hasMultipleEditorWindows } }, new class extends mock() { }(), telemetryService, configurationService, @@ -430,30 +450,58 @@ suite('AgentsBanner graphic', () => { ]); }); + const windowSetups: [label: string, windows: IOpenedMainWindow[], multiple: boolean][] = [ + ['1 editor window', [editorWindow(1)], false], + ['2 editor windows', [editorWindow(1), editorWindow(2)], true], + ['1 editor window and the Agents window', [editorWindow(1), agentsWindow], false], + ]; for (const variant of [AgentsWindowGraphicVariant.None, AgentsWindowGraphicVariant.WindowComparison, AgentsWindowGraphicVariant.ManyWindowsToOne, AgentsWindowGraphicVariant.Auto]) { - test(`logs the experiment triggers once the banner is visible and exposed (${variant})`, async () => { - const telemetryService = new TestExperimentTriggerTelemetryService(); - const banner = createBannerWithGraphic(variant, telemetryService, { agentEnabled: false, exposed: false }); - const triggers = async () => { - await timeout(0); - return [...telemetryService.triggers]; - }; - const steps = [await triggers()]; - banner.setExposed(true); - steps.push(await triggers()); - await banner.setAgentEnabled(true); - steps.push(await triggers()); - banner.setExposed(false); - banner.setExposed(true); - createBannerWithGraphic(variant, telemetryService); - steps.push(await triggers()); - - // The section style only applies while a graphic is shown, so its trigger waits for one - const shown = variant === AgentsWindowGraphicVariant.None ? [graphicTreatment] : [graphicTreatment, sectionStyleTreatment]; - assert.deepStrictEqual(steps, [[], [], shown, shown]); - }); + for (const [label, windows, multiple] of windowSetups) { + test(`logs the experiment triggers once the banner is visible and exposed (${variant}, ${label})`, async () => { + const telemetryService = new TestExperimentTriggerTelemetryService(); + const banner = createBannerWithGraphic(variant, telemetryService, { agentEnabled: false, exposed: false, windows }); + const triggers = async () => { + await timeout(0); + return [...telemetryService.triggers]; + }; + const steps = [await triggers()]; + banner.setExposed(true); + steps.push(await triggers()); + await banner.setAgentEnabled(true); + steps.push(await triggers()); + banner.setExposed(false); + banner.setExposed(true); + createBannerWithGraphic(variant, telemetryService, { windows }); + steps.push(await triggers()); + + // The section style only applies while a graphic is shown, so its trigger waits for one. + // The multiple editor windows trigger depends only on the windows, so every arm logs it alike. + const shown = [ + graphicTreatment, + ...(variant === AgentsWindowGraphicVariant.None ? [] : [sectionStyleTreatment]), + ...(multiple ? [multipleEditorWindowsTreatment] : []), + ]; + assert.deepStrictEqual(steps, [[], [], shown, shown]); + }); + } } + test('logs the multiple editor windows trigger once the windows have been counted', async () => { + const telemetryService = new TestExperimentTriggerTelemetryService(); + const windows = new DeferredPromise(); + createBannerWithGraphic(AgentsWindowGraphicVariant.WindowComparison, telemetryService, { windows: windows.p }); + await timeout(0); + const steps = [[...telemetryService.triggers]]; + await windows.complete([editorWindow(1), editorWindow(2)]); + await timeout(0); + steps.push([...telemetryService.triggers]); + + assert.deepStrictEqual(steps, [ + [graphicTreatment, sectionStyleTreatment], + [graphicTreatment, sectionStyleTreatment, multipleEditorWindowsTreatment], + ]); + }); + test('logs the section style trigger when a graphic is shown later', async () => { const telemetryService = new TestExperimentTriggerTelemetryService(); const banner = createBannerWithGraphic(AgentsWindowGraphicVariant.None, telemetryService); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsDataSource.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsDataSource.test.ts index 19587ea01373..7cea8e318a49 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsDataSource.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsDataSource.test.ts @@ -145,7 +145,7 @@ suite('AgentSessionsDataSource', () => { ['unread', { ...Codicon.circleFilled, color: themeColorFromId('textLink.foreground') }], ['archived', { ...Codicon.passFilled, color: themeColorFromId('agentSessionReadIndicator.foreground') }], ['in-progress', { ...Codicon.sessionInProgress, color: themeColorFromId('textLink.foreground') }], - ['needs-input', { ...Codicon.reportQuestion, color: themeColorFromId('list.warningForeground') }], + ['needs-input', { ...Codicon.reportQuestion, color: themeColorFromId('agentSessionNeedsInput.foreground') }], ['failed', { ...Codicon.error, color: themeColorFromId('errorForeground') }], ]); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsRenderer.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsRenderer.test.ts index cf376cafcf87..02472183fb81 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsRenderer.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsRenderer.test.ts @@ -77,11 +77,16 @@ suite('AgentSessionsRenderer', () => { const template = renderer.renderTemplate(contents); store.add({ dispose: () => renderer.disposeTemplate(template) }); - assert.deepStrictEqual([...row.classList], [ - 'monaco-list-row', - 'agent-session-list-row', - 'agent-session-item-row', - ]); + const marker = contents.querySelector('.agent-session-attention-indicator'); + assert.deepStrictEqual({ + rowClasses: [...row.classList], + markerTag: marker?.tagName, + markerAriaHidden: marker?.getAttribute('aria-hidden'), + }, { + rowClasses: ['monaco-list-row', 'agent-session-list-row', 'agent-session-item-row'], + markerTag: 'SPAN', + markerAriaHidden: 'true', + }); }); test('adds section classes when the container is a sticky row', () => { @@ -182,6 +187,8 @@ suite('AgentSessionsRenderer', () => { hasChatIcon: !!template.element.querySelector('.agent-session-chat-icon'), hasNeutralChatIcon: !!template.element.querySelector('.codicon-circle-small-filled'), hasDetails: !!template.element.querySelector('.agent-session-details-row'), + markerTag: template.element.querySelector('.agent-session-attention-indicator')?.tagName, + markerAriaHidden: template.element.querySelector('.agent-session-attention-indicator')?.getAttribute('aria-hidden'), completion, restore, unsupported: actionLabels(), @@ -192,6 +199,8 @@ suite('AgentSessionsRenderer', () => { hasChatIcon: true, hasNeutralChatIcon: true, hasDetails: false, + markerTag: 'SPAN', + markerAriaHidden: 'true', completion: ['Mark as Done'], restore: ['Restore'], unsupported: [], diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsViewer.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsViewer.test.ts index 7baa182ae45c..b853dd2cf623 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsViewer.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentSessionsViewer.test.ts @@ -12,51 +12,85 @@ import { mainWindow } from '../../../../../../base/browser/window.js'; suite('AgentSessionsViewer styles', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - test('input-needed session and chat rows use static icons and warning backgrounds', () => { - const container = mainWindow.document.createElement('div'); - container.className = 'agent-sessions-viewer'; - container.style.setProperty('--vscode-list-warningForeground', 'rgb(255, 0, 0)'); + for (const themeClass of ['', 'hc-black', 'hc-light']) { + test(`input-needed rows use static icons and ${themeClass ? `left-edge markers in ${themeClass}` : 'warning backgrounds'}`, () => { + const container = mainWindow.document.createElement('div'); + container.className = 'agent-sessions-viewer'; + container.style.setProperty('--vscode-spacing-size20', '2px'); + container.style.setProperty('--vscode-spacing-size40', '4px'); + container.style.setProperty('--vscode-list-warningForeground', 'rgb(0, 0, 255)'); + container.style.setProperty('--vscode-agentSessionNeedsInput-foreground', 'rgb(255, 0, 0)'); - const sessionRow = mainWindow.document.createElement('div'); - sessionRow.className = 'monaco-list-row'; - const sessionItem = mainWindow.document.createElement('div'); - sessionItem.className = 'agent-session-item'; - const sessionIcon = mainWindow.document.createElement('div'); - sessionIcon.className = 'agent-session-icon needs-input'; - sessionItem.appendChild(sessionIcon); - sessionRow.appendChild(sessionItem); - container.appendChild(sessionRow); + const sessionRow = mainWindow.document.createElement('div'); + sessionRow.className = 'monaco-list-row'; + const sessionItem = mainWindow.document.createElement('div'); + sessionItem.className = 'agent-session-item'; + const sessionMarker = mainWindow.document.createElement('span'); + sessionMarker.className = 'agent-session-attention-indicator'; + sessionMarker.setAttribute('aria-hidden', 'true'); + sessionItem.appendChild(sessionMarker); + const sessionIcon = mainWindow.document.createElement('div'); + sessionIcon.className = 'agent-session-icon needs-input'; + sessionItem.appendChild(sessionIcon); + sessionRow.appendChild(sessionItem); + container.appendChild(sessionRow); - const chatRow = mainWindow.document.createElement('div'); - chatRow.className = 'monaco-list-row'; - const chatItem = mainWindow.document.createElement('div'); - chatItem.className = 'agent-session-chat-item needs-input'; - const chatIcon = mainWindow.document.createElement('div'); - chatIcon.className = 'agent-session-chat-icon needs-input'; - chatItem.appendChild(chatIcon); - chatRow.appendChild(chatItem); - container.appendChild(chatRow); + const chatRow = mainWindow.document.createElement('div'); + chatRow.className = 'monaco-list-row'; + const chatItem = mainWindow.document.createElement('div'); + chatItem.className = 'agent-session-chat-item needs-input'; + const chatMarker = mainWindow.document.createElement('span'); + chatMarker.className = 'agent-session-attention-indicator'; + chatMarker.setAttribute('aria-hidden', 'true'); + chatItem.appendChild(chatMarker); + const chatIcon = mainWindow.document.createElement('div'); + chatIcon.className = 'agent-session-chat-icon needs-input'; + chatItem.appendChild(chatIcon); + chatRow.appendChild(chatItem); + container.appendChild(chatRow); - mainWindow.document.body.appendChild(container); - store.add(toDisposable(() => container.remove())); - assert.deepStrictEqual([ - { background: sessionRow, icon: sessionIcon }, - { background: chatItem, icon: chatIcon }, - ].map(({ background, icon }) => ({ - hasWarningBackground: ['color(srgb 1 0 0 / 0.08)', 'rgba(255, 0, 0, 0.08)'].includes(mainWindow.getComputedStyle(background).backgroundColor), - backgroundAnimation: mainWindow.getComputedStyle(background).animationName, - iconAnimation: mainWindow.getComputedStyle(icon).animationName, - })), [ - { - hasWarningBackground: true, - backgroundAnimation: 'none', - iconAnimation: 'none', - }, - { - hasWarningBackground: true, - backgroundAnimation: 'none', - iconAnimation: 'none', - }, - ]); - }); + const wrapper = mainWindow.document.createElement('div'); + wrapper.className = themeClass; + wrapper.appendChild(container); + mainWindow.document.body.appendChild(wrapper); + store.add(toDisposable(() => wrapper.remove())); + assert.deepStrictEqual([ + { background: sessionRow, icon: sessionIcon, marker: sessionMarker }, + { background: chatItem, icon: chatIcon, marker: chatMarker }, + ].map(({ background, icon, marker }) => ({ + hasWarningBackground: ['color(srgb 1 0 0 / 0.08)', 'rgba(255, 0, 0, 0.08)'].includes(mainWindow.getComputedStyle(background).backgroundColor), + borderWidth: mainWindow.getComputedStyle(background).borderLeftWidth, + markerDisplay: mainWindow.getComputedStyle(marker).display, + markerCornerRadius: mainWindow.getComputedStyle(marker).borderRadius, + markerWidth: mainWindow.getComputedStyle(marker).width, + markerInsets: [mainWindow.getComputedStyle(marker).top, mainWindow.getComputedStyle(marker).bottom], + markerAriaHidden: marker.getAttribute('aria-hidden'), + backgroundAnimation: mainWindow.getComputedStyle(background).animationName, + iconAnimation: mainWindow.getComputedStyle(icon).animationName, + })), [ + { + hasWarningBackground: !themeClass, + borderWidth: '0px', + markerDisplay: themeClass ? 'block' : 'none', + markerCornerRadius: '0px', + markerWidth: '2px', + markerInsets: ['4px', '4px'], + markerAriaHidden: 'true', + backgroundAnimation: 'none', + iconAnimation: 'none', + }, + { + hasWarningBackground: !themeClass, + borderWidth: '0px', + markerDisplay: themeClass ? 'block' : 'none', + markerCornerRadius: '0px', + markerWidth: '2px', + markerInsets: ['4px', '4px'], + markerAriaHidden: 'true', + backgroundAnimation: 'none', + iconAnimation: 'none', + }, + ]); + }); + } }); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentTitleBarStatusWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentTitleBarStatusWidget.test.ts new file mode 100644 index 000000000000..612bc8b3fc95 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentTitleBarStatusWidget.test.ts @@ -0,0 +1,108 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mainWindow } from '../../../../../../base/browser/window.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { DisposableStore } from '../../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IAction } from '../../../../../../base/common/actions.js'; +import { IFolderLocation } from '../../../../../../platform/workspace/common/folderLocations.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js'; +import { IMenuService } from '../../../../../../platform/actions/common/actions.js'; +import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { IStorageService } from '../../../../../../platform/storage/common/storage.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { IEditorGroupsService } from '../../../../../services/editor/common/editorGroupsService.js'; +import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { IChatEntitlementService } from '../../../../../services/chat/common/chatEntitlementService.js'; +import { IChatWidgetService } from '../../../browser/chat.js'; +import { IAgentSessionsService } from '../../../browser/agentSessions/agentSessionsService.js'; +import { IAgentTitleBarStatusService } from '../../../browser/agentSessions/experiments/agentTitleBarStatusService.js'; +import { AgentTitleBarStatusWidget } from '../../../browser/agentSessions/experiments/agentTitleBarStatusWidget.js'; +import { WindowTitle } from '../../../../../browser/parts/titlebar/windowTitle.js'; + +suite('AgentTitleBarStatusWidget', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** A service whose events never fire and whose methods do nothing, for the parts the widget does not use here. */ + function inert(overrides: Partial> = {}): T { + return new Proxy(overrides, { + get: (target, key) => { + if (Object.prototype.hasOwnProperty.call(target, key)) { + return (target as Record)[key]; + } + if (typeof key === 'string' && key.startsWith('onDid')) { + return Event.None; + } + return () => undefined; + } + }) as T; + } + + function renderWidget(location: { current: IFolderLocation | undefined }, store: DisposableStore) { + const instantiationService = store.add(new TestInstantiationService()); + const windowTitle = inert({ + workspaceName: 'repo-tasks', + getCommandCenterLabel: () => 'repo-tasks', + get folderLocationInfo() { return location.current; }, + getTitleDecorations: () => ({ prefix: undefined, suffix: undefined }), + isCustomTitleFormat: () => false, + onDidChange: new Emitter().event + }); + + instantiationService.stub(IAgentTitleBarStatusService, inert({ mode: 'default', sessionInfo: undefined })); + instantiationService.stub(IHoverService, inert()); + instantiationService.stub(ICommandService, inert()); + instantiationService.stub(IKeybindingService, inert()); + instantiationService.stub(IAgentSessionsService, inert({ model: inert({ sessions: [] }) })); + instantiationService.stub(IWorkspaceContextService, inert()); + instantiationService.stub(IEditorGroupsService, inert({ partOptions: { showTabs: 'multiple' } })); + instantiationService.stub(IEditorService, inert()); + instantiationService.stub(IMenuService, inert({ createMenu: () => inert({ getActions: () => [] }) })); + instantiationService.stub(IContextKeyService, inert()); + instantiationService.stub(IStorageService, inert({ onDidChangeValue: () => Event.None, get: () => undefined, getBoolean: () => false, getNumber: () => 0 })); + instantiationService.stub(IConfigurationService, inert({ getValue: () => undefined })); + instantiationService.stub(IChatEntitlementService, inert()); + instantiationService.stub(IChatWidgetService, inert()); + instantiationService.stub(ITelemetryService, inert()); + + const container = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + store.add({ dispose: () => container.remove() }); + const widget = store.add(instantiationService.invokeFunction(accessor => accessor.get(IInstantiationService)).createInstance(AgentTitleBarStatusWidget, { id: 'test' } as IAction, windowTitle, undefined)); + widget.render(container); + return { container, widget }; + } + + test('the focusable button keeps its Quick Access name and adds the folder location while switched', () => { + const location = { current: undefined as IFolderLocation | undefined }; + const { container, widget } = renderWidget(location, disposables.add(new DisposableStore())); + const name = () => container.querySelector('.agent-status-input-area')?.getAttribute('aria-label'); + + const atPrimary = name(); + location.current = { uri: URI.file('/wt-1'), label: 'wt-1', description: 'feature-x', icon: Codicon.folder }; + (widget as unknown as { _lastRenderState: undefined; _render(): void })._lastRenderState = undefined; + (widget as unknown as { _render(): void })._render(); + const atAlternate = name(); + location.current = undefined; + (widget as unknown as { _lastRenderState: undefined })._lastRenderState = undefined; + (widget as unknown as { _render(): void })._render(); + + assert.deepStrictEqual({ atPrimary, atAlternate, afterReturn: name() }, { + atPrimary: 'Open Quick Access', + atAlternate: 'Open Quick Access, repo-tasks, branch feature-x', + afterReturn: 'Open Quick Access' + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentsWindowGraphic.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentsWindowGraphic.test.ts index 55364bb0409f..ddc97e5bf0db 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentsWindowGraphic.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentsWindowGraphic.test.ts @@ -59,6 +59,7 @@ suite('AgentsWindowGraphic', () => { rendered: graphic.element.querySelector('.agents-window-graphic')?.classList[1], captions: [...graphic.element.querySelectorAll('figcaption')].map(caption => caption.textContent), windowRequests, + hasMultipleEditorWindows: graphic.hasMultipleEditorWindows.get(), }), }; } @@ -76,7 +77,7 @@ suite('AgentsWindowGraphic', () => { ); }); - test('shows the configured graphic and counts the open editor windows when the automatic one is shown', async () => { + test('shows the configured graphic and counts the open editor windows for every variant', async () => { const graphic = createGraphic(AgentsWindowGraphicVariant.None); const states = [graphic.state()]; for (const variant of [AgentsWindowGraphicVariant.WindowComparison, AgentsWindowGraphicVariant.ManyWindowsToOne, AgentsWindowGraphicVariant.Auto]) { @@ -101,13 +102,13 @@ suite('AgentsWindowGraphic', () => { }; const manyWindowsToOne = { shown: 'manyWindowsToOne', display: '', rendered: 'many-windows-to-one', captions: ['All your projects and agents, in one window.'] }; assert.deepStrictEqual(states, [ - { ...none, windowRequests: 0 }, - { ...windowComparison, windowRequests: 0 }, - { ...manyWindowsToOne, windowRequests: 0 }, - { ...windowComparison, windowRequests: 1 }, - { ...manyWindowsToOne, windowRequests: 2 }, - { ...windowComparison, windowRequests: 3 }, - { ...none, windowRequests: 3 }, + { ...none, windowRequests: 1, hasMultipleEditorWindows: undefined }, + { ...windowComparison, windowRequests: 2, hasMultipleEditorWindows: false }, + { ...manyWindowsToOne, windowRequests: 3, hasMultipleEditorWindows: false }, + { ...windowComparison, windowRequests: 4, hasMultipleEditorWindows: false }, + { ...manyWindowsToOne, windowRequests: 6, hasMultipleEditorWindows: true }, + { ...windowComparison, windowRequests: 8, hasMultipleEditorWindows: false }, + { ...none, windowRequests: 9, hasMultipleEditorWindows: false }, ]); }); @@ -123,16 +124,18 @@ suite('AgentsWindowGraphic', () => { }); test('ignores a window count that arrives after the setting changed', async () => { - const requests = [new DeferredPromise(), new DeferredPromise()]; + const requests = [new DeferredPromise(), new DeferredPromise(), new DeferredPromise()]; let next = 0; const graphic = createGraphic(AgentsWindowGraphicVariant.Auto, () => requests[next++].p); await graphic.setVariant(AgentsWindowGraphicVariant.None); await graphic.setVariant(AgentsWindowGraphicVariant.Auto); - await requests[1].complete([editorWindow(1)]); + await requests[2].complete([editorWindow(1)]); await requests[0].complete([editorWindow(1), editorWindow(2)]); + await requests[1].complete([editorWindow(1), editorWindow(2)]); await timeout(0); - assert.deepStrictEqual(graphic.state().shown, AgentsWindowGraphicVariant.WindowComparison); + const { shown, hasMultipleEditorWindows } = graphic.state(); + assert.deepStrictEqual({ shown, hasMultipleEditorWindows }, { shown: AgentsWindowGraphicVariant.WindowComparison, hasMultipleEditorWindows: false }); }); test('hides the drawings from screen readers and gives every clip path a unique id', () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/convertCarouselAnswers.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/convertCarouselAnswers.test.ts index c508eac7e29d..c45e73697970 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/convertCarouselAnswers.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/convertCarouselAnswers.test.ts @@ -42,6 +42,29 @@ suite('convertCarouselAnswers', () => { }); }); + test('preserves the single-select kind for freeform-only answers', () => { + const result = convertCarouselAnswers({ + q1: { freeformValue: 'latest' }, + q2: { selectedValue: '', freeformValue: 'custom' }, + }, ['q1', 'q2'].map(id => ({ + kind: ChatInputQuestionKind.SingleSelect, + id, + message: 'Which release?', + options: [{ id: 'preview', label: 'Preview' }], + allowFreeformInput: true, + }))); + assert.deepStrictEqual(result, { + q1: { + state: ChatInputAnswerState.Submitted, + value: { kind: ChatInputAnswerValueKind.Selected, value: '', freeformValues: ['latest'] } + }, + q2: { + state: ChatInputAnswerState.Submitted, + value: { kind: ChatInputAnswerValueKind.Selected, value: '', freeformValues: ['custom'] } + } + }); + }); + test('converts boolean single-select answer', () => { const result = convertCarouselAnswers({ 'q1': { selectedValue: 'false' } }, [{ kind: ChatInputQuestionKind.Boolean, diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts new file mode 100644 index 000000000000..d3763cc962d6 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/copilotEntraAuthentication.test.ts @@ -0,0 +1,434 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; +import type { IDefaultAccount } from '../../../../../../base/common/defaultAccount.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { mock } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { copilotEntraAuthorizationServer, copilotEntraClientId, copilotEntraDiscoveryResource } from '../../../../../../platform/agentHost/common/copilotEntraAuthentication.js'; +import { authenticationAccountMeta } from '../../../../../../platform/agentHost/common/meta/agentAuthenticationAccount.js'; +import { AuthRequiredReason } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; +import type { ProtectedResourceMetadata } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IAuthenticationService, type AuthenticationSession } from '../../../../../services/authentication/common/authentication.js'; +import { AgentHostAuthenticationRecovery, AgentHostAuthTokenCache, AgentHostInteractiveAuthentication, authenticateProtectedResources, resolveAuthenticationInteractively, resolveProtectedResourceAuthentication, revokeAuthenticationForRemovedSessions, type IAgentHostAuthenticateRequest } from '../../../browser/agentSessions/agentHost/agentHostAuth.js'; + +class MicrosoftAuthentication extends mock() { + readonly calls: Parameters[] = []; + readonly created: Parameters[] = []; + sessions: readonly AuthenticationSession[] = []; + interactiveResult: AuthenticationSession | Promise | undefined; + readonly interactiveStarted = new DeferredPromise(); + pending: DeferredPromise | undefined; + pendingStarted: DeferredPromise | undefined; + + override async getOrActivateProviderIdForServer(): Promise { + return 'microsoft'; + } + + override async getSessions(...args: Parameters): Promise { + this.calls.push(args); + if (args[1] === undefined) { + return this.sessions.map(session => ({ ...session, scopes: [], accessToken: 'account-list-placeholder' })); + } + this.pendingStarted?.complete(); + return this.pending ? this.pending.p : this.sessions; + } + + override async createSession(...args: Parameters): Promise { + this.created.push(args); + this.interactiveStarted.complete(); + assert.ok(this.interactiveResult); + return this.interactiveResult; + } +} + +suite('Agent Host Microsoft credential acquisition', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const resource: ProtectedResourceMetadata = { + resource: copilotEntraDiscoveryResource, + authorization_servers: [copilotEntraAuthorizationServer], + scopes_supported: ['User.Read'], + }; + const selected: AuthenticationSession = { + id: 'selected', + account: { id: 'selected', label: 'Selected' }, + scopes: ['User.Read'], + accessToken: 'synthetic-selected-token', + }; + const other: AuthenticationSession = { + ...selected, id: 'other', account: { id: 'other', label: 'Other' }, accessToken: 'synthetic-other-token', + }; + + function fixture() { + const authentication = new MicrosoftAuthentication(); + authentication.sessions = [other, selected]; + const defaults = new class extends mock() { + override currentDefaultAccount: IDefaultAccount | null = { + authenticationProvider: { id: 'microsoft', name: 'Microsoft', enterprise: false }, + sessionId: selected.id, accountName: selected.account.label, enterprise: false, + }; + }(); + const instantiation = store.add(new TestInstantiationService()); + instantiation.stub(IAuthenticationService, authentication); + instantiation.stub(IDefaultAccountService, defaults); + instantiation.stub(ILogService, new NullLogService()); + instantiation.stub(IConfigurationService, new TestConfigurationService()); + instantiation.stub(ICommandService, new class extends mock() { }()); + instantiation.stub(ITelemetryService, NullTelemetryService); + const resolve = () => instantiation.invokeFunction(resolveProtectedResourceAuthentication, resource, '[test]'); + return { authentication, defaults, resolve, instantiation }; + } + + test('acquires real scoped credentials silently for the default account and fixed client registration', async () => { + const f = fixture(); + const credential = await f.resolve(); + assert.deepStrictEqual({ calls: f.authentication.calls, credential }, { + calls: [ + ['microsoft', undefined, { silent: true, clientId: copilotEntraClientId }, true], + ['microsoft', ['User.Read'], { account: selected.account, authorizationServer: URI.parse(copilotEntraAuthorizationServer), clientId: copilotEntraClientId, silent: true }, true], + ], + credential: { resource: resource.resource, scopes: ['User.Read'], token: selected.accessToken, _meta: authenticationAccountMeta({ providerId: 'microsoft', accountId: selected.account.id, label: selected.account.label }) }, + }); + }); + + test('does not use a sole different account when the default account is absent', async () => { + const f = fixture(); + f.authentication.sessions = [other]; + assert.strictEqual(await f.resolve(), undefined); + }); + + test('does not treat a GitHub default account as a Microsoft identity', async () => { + const f = fixture(); + f.defaults.currentDefaultAccount = { + authenticationProvider: { id: 'github', name: 'GitHub', enterprise: false }, + sessionId: selected.id, accountName: selected.account.label, enterprise: false, + }; + assert.deepStrictEqual({ credential: await f.resolve(), calls: f.authentication.calls }, { credential: undefined, calls: [] }); + }); + + test('rejects a returned session for the wrong resource scopes', async () => { + const f = fixture(); + f.authentication.sessions = [{ ...selected, scopes: ['different'] }]; + assert.strictEqual(await f.resolve(), undefined); + }); + + test('rejects a late credential after the default account signs out', async () => { + const f = fixture(); + f.authentication.pending = new DeferredPromise(); + const resolved = f.resolve(); + await Promise.resolve(); + f.defaults.currentDefaultAccount = null; + f.authentication.pending.complete([selected]); + assert.strictEqual(await resolved, undefined); + }); + + test('surfaces provider errors instead of treating them as successful authentication', async () => { + const f = fixture(); + f.authentication.pending = new DeferredPromise(); + const resolved = f.resolve(); + f.authentication.pending.error(new Error('authentication provider unavailable')); + await assert.rejects(resolved, /authentication provider unavailable/); + }); + + test('revokes only the forwarded Microsoft account, including scope-less account-removal events', async () => { + const f = fixture(); + const cache = new AgentHostAuthTokenCache(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + await cache.authenticate(resource.resource, resource.scopes_supported, selected.accessToken, async () => { }, selected.account.id, undefined, undefined, { sessionId: selected.id, accountId: selected.account.id }); + for (const session of [other, selected]) { + await f.instantiation.invokeFunction(revokeAuthenticationForRemovedSessions, + [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }], + 'microsoft', [{ id: session.id, scopes: [] }], + { logPrefix: '[test]', authTokenCache: cache, authenticate: async request => { forwarded.push(request); } }); + } + assert.deepStrictEqual(forwarded, [{ resource: resource.resource, scopes: ['User.Read'], token: '' }]); + }); + + test('uses the existing Microsoft interactive flow for the same default account after silent acquisition fails', async () => { + const f = fixture(); + f.authentication.sessions = [{ ...selected, scopes: ['unrelated'] }]; + f.authentication.interactiveResult = selected; + const forwarded: IAgentHostAuthenticateRequest[] = []; + const signedIn = await f.instantiation.invokeFunction(resolveAuthenticationInteractively, [resource], { + logPrefix: '[test]', authenticate: async request => { forwarded.push(request); }, + }); + assert.deepStrictEqual({ + signedIn, + created: f.authentication.created, + forwarded, + }, { + signedIn: true, + created: [['microsoft', ['User.Read'], { account: selected.account, authorizationServer: URI.parse(copilotEntraAuthorizationServer), clientId: copilotEntraClientId }]], + forwarded: [{ resource: resource.resource, scopes: ['User.Read'], token: selected.accessToken, _meta: authenticationAccountMeta({ providerId: 'microsoft', accountId: selected.account.id, label: selected.account.label }) }], + }); + }); + + test('a missing silent credential neither prompts nor revokes the signed-in account', async () => { + const f = fixture(); + f.authentication.sessions = [{ ...selected, scopes: [] }]; + f.authentication.interactiveResult = selected; + const forwarded: IAgentHostAuthenticateRequest[] = []; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { + logPrefix: '[test]', authenticate: async request => { forwarded.push(request); }, + })); + assert.deepStrictEqual({ + interactiveAccounts: f.authentication.created.map(([, , options]) => options?.account), + tokens: forwarded.map(request => request.token), + }, { interactiveAccounts: [], tokens: [] }); + }); + + test('a second window without the Microsoft account cannot revoke another window through discovery or recovery', async () => { + const f = fixture(); + f.defaults.currentDefaultAccount = null; + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + await f.instantiation.invokeFunction(authenticateProtectedResources, + [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }], options); + assert.deepStrictEqual({ forwarded, interactive: f.authentication.created }, { forwarded: [], interactive: [] }); + }); + + test('distinguishes the default session id from its account id', async () => { + const f = fixture(); + f.authentication.sessions = [{ ...selected, account: { ...selected.account, id: 'opaque-account' } }]; + const result = await f.resolve(); + assert.deepStrictEqual(result?._meta, authenticationAccountMeta({ providerId: 'microsoft', accountId: 'opaque-account', label: selected.account.label })); + }); + + test('same-token deduplication retains the replacement session identity for sign-out', async () => { + const cache = new AgentHostAuthTokenCache(); + const calls: string[] = []; + for (const id of ['old-session', 'new-session']) { + await cache.authenticate(resource.resource, resource.scopes_supported, selected.accessToken, async () => { calls.push(id); }, selected.account.id, undefined, undefined, { sessionId: id, accountId: selected.account.id }); + } + assert.deepStrictEqual({ calls, session: cache.getSessionId(resource.resource, resource.scopes_supported) }, { calls: ['old-session'], session: 'new-session' }); + }); + + test('sign-out during interactive Graph recovery still withdraws the forwarded identity', async () => { + const f = fixture(); + const cache = new AgentHostAuthTokenCache(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: cache, authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const agents = [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }]; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + const interactive = new DeferredPromise(); + f.authentication.interactiveResult = interactive.p; + const recovering = f.instantiation.createInstance(AgentHostInteractiveAuthentication).request(resource, options); + await f.authentication.interactiveStarted.p; + const duringRecovery = cache.getSessionId(resource.resource, resource.scopes_supported); + + f.defaults.currentDefaultAccount = null; + f.authentication.sessions = []; + await f.instantiation.invokeFunction(revokeAuthenticationForRemovedSessions, agents, 'microsoft', [{ id: selected.id, scopes: [] }], options); + interactive.complete(selected); + await assert.rejects(recovering, /account changed/); + assert.deepStrictEqual({ duringRecovery, tokens: forwarded.map(request => request.token) }, { duringRecovery: selected.id, tokens: [selected.accessToken, ''] }); + }); + + for (const hasScopedCredential of [true, false]) { + test(`switching to another signed-in default withdraws the old account before acquiring credentials (scoped=${hasScopedCredential})`, async () => { + const f = fixture(); + f.authentication.sessions = [selected, { ...other, scopes: hasScopedCredential ? ['User.Read'] : [] }]; + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const agents = [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }]; + await f.instantiation.invokeFunction(authenticateProtectedResources, agents, options); + f.authentication.calls.length = 0; + f.defaults.currentDefaultAccount = { + authenticationProvider: { id: 'microsoft', name: 'Microsoft', enterprise: false }, + sessionId: other.id, accountName: other.account.label, enterprise: false, + }; + await f.instantiation.invokeFunction(authenticateProtectedResources, agents, options); + assert.deepStrictEqual({ + tokens: forwarded.map(request => request.token), + scopedAcquisitions: f.authentication.calls.filter(([, scopes]) => scopes !== undefined).length, + remaining: options.authTokenCache.getAccountId(resource.resource, resource.scopes_supported), + accounts: f.authentication.sessions.map(session => session.account.id), + }, { tokens: [selected.accessToken, ''], scopedAcquisitions: 0, remaining: undefined, accounts: [selected.account.id, other.account.id] }); + }); + } + + test('a superseded default-account lookup does not revoke the current account', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const agents = [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }]; + await f.instantiation.invokeFunction(authenticateProtectedResources, agents, options); + const originalDefault = f.defaults.currentDefaultAccount; + f.defaults.currentDefaultAccount = { + authenticationProvider: { id: 'microsoft', name: 'Microsoft', enterprise: false }, + sessionId: other.id, accountName: other.account.label, enterprise: false, + }; + const forwarding = f.instantiation.invokeFunction(authenticateProtectedResources, agents, options); + f.defaults.currentDefaultAccount = originalDefault; + await assert.rejects(forwarding, isCancellationError); + assert.deepStrictEqual(forwarded.map(request => request.token), [selected.accessToken]); + }); + + test('repeated recovery notifications remain silent even for an unchanged available token', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + assert.deepStrictEqual({ tokens: forwarded.map(request => request.token), prompts: f.authentication.created }, { tokens: [selected.accessToken, selected.accessToken], prompts: [] }); + }); + + test('expired recovery never replays the challenged token or prompts and accepts a later silent replacement', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + const expired = { ...options, challengeReason: AuthRequiredReason.Expired }; + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, expired)); + assert.ok(f.defaults.currentDefaultAccount); + f.defaults.currentDefaultAccount = { ...f.defaults.currentDefaultAccount, sessionId: 'rotated-session' }; + f.authentication.sessions = [{ ...selected, id: 'rotated-session' }]; + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, expired)); + f.authentication.sessions = [{ ...selected, id: 'rotated-session', accessToken: 'replacement-token' }]; + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, expired)); + assert.deepStrictEqual({ + tokens: forwarded.map(request => request.token), prompts: f.authentication.created, + account: options.authTokenCache.getAccountId(resource.resource, resource.scopes_supported), + }, { tokens: [selected.accessToken, 'replacement-token'], prompts: [], account: selected.account.id }); + }); + + test('expired recovery without a known challenged credential defers to explicit recovery', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { + logPrefix: '[test]', challengeReason: AuthRequiredReason.Expired, + authenticate: async request => { forwarded.push(request); }, + })); + assert.deepStrictEqual({ forwarded, prompts: f.authentication.created }, { forwarded: [], prompts: [] }); + }); + + test('an expired challenge cannot join an earlier required recovery and replay its token', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const options = { logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request); } }; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + f.authentication.pending = new DeferredPromise(); + const required = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + const expired = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { ...options, challengeReason: AuthRequiredReason.Expired })); + const finished = Promise.allSettled([required, expired]); + f.authentication.pending.complete([selected]); + await finished; + assert.deepStrictEqual({ tokens: forwarded.map(request => request.token), prompts: f.authentication.created }, { tokens: [selected.accessToken], prompts: [] }); + }); + + test('expired recovery retains sign-out ownership while the first credential push is pending', async () => { + const f = fixture(); + const forwarded: string[] = []; + const accepted = new DeferredPromise(); + const started = new DeferredPromise(); + const options = { + logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), + authenticate: async (request: IAgentHostAuthenticateRequest) => { + forwarded.push(request.token); + if (request.token) { + started.complete(); + await accepted.p; + } + }, + }; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + const initial = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + const finished = assert.rejects(initial, isCancellationError); + await started.p; + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { ...options, challengeReason: AuthRequiredReason.Expired })); + f.defaults.currentDefaultAccount = null; + f.authentication.sessions = []; + await f.instantiation.invokeFunction(revokeAuthenticationForRemovedSessions, + [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }], + 'microsoft', [{ id: selected.id, scopes: [] }], options); + accepted.complete(); + await finished; + assert.deepStrictEqual(forwarded, [selected.accessToken, '']); + }); + + test('a rotated session from an earlier silent lookup cannot replay an expired token', async () => { + const f = fixture(); + const forwarded: string[] = []; + const options = { + logPrefix: '[test]', authTokenCache: new AgentHostAuthTokenCache(), + authenticate: async (request: IAgentHostAuthenticateRequest) => { forwarded.push(request.token); }, + }; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + await f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, options)); + f.authentication.pending = new DeferredPromise(); + f.authentication.pendingStarted = new DeferredPromise(); + const lookup = f.instantiation.invokeFunction(authenticateProtectedResources, + [{ provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], protectedResources: [resource] }], options); + await f.authentication.pendingStarted.p; + const expired = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { ...options, challengeReason: AuthRequiredReason.Expired })); + f.authentication.pending.complete([{ ...selected, id: 'rotated-scoped-session' }]); + const results = await Promise.allSettled([lookup, expired]); + assert.deepStrictEqual({ + forwarded, prompts: f.authentication.created, + results: results.map(result => result.status === 'fulfilled' ? 'completed' : isCancellationError(result.reason) ? 'cancelled' : 'error'), + }, { forwarded: [selected.accessToken], prompts: [], results: ['cancelled', 'completed'] }); + }); + + test('a silent provider failure is surfaced without revocation or interactive fallback', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + f.authentication.pending = new DeferredPromise(); + const result = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { + logPrefix: '[test]', authenticate: async request => { forwarded.push(request); }, + })); + f.authentication.pending.error(new Error('provider unavailable')); + await assert.rejects(result, /provider unavailable/); + assert.deepStrictEqual({ forwarded, prompts: f.authentication.created }, { forwarded: [], prompts: [] }); + }); + + test('cancelling explicit interactive recovery does not send a revocation', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const interactive = new DeferredPromise(); + f.authentication.interactiveResult = interactive.p; + const result = f.instantiation.createInstance(AgentHostInteractiveAuthentication).request(resource, { + logPrefix: '[test]', authenticate: async request => { forwarded.push(request); }, + }); + await f.authentication.interactiveStarted.p; + interactive.error(new CancellationError()); + await assert.rejects(result, isCancellationError); + assert.deepStrictEqual({ forwarded, account: f.defaults.currentDefaultAccount?.sessionId }, { forwarded: [], account: selected.id }); + }); + + test('a superseded silent recovery never forwards its late credential', async () => { + const f = fixture(); + const forwarded: IAgentHostAuthenticateRequest[] = []; + const recovery = f.instantiation.createInstance(AgentHostAuthenticationRecovery); + let current = true; + f.authentication.pending = new DeferredPromise(); + const result = f.instantiation.invokeFunction(accessor => recovery.recover(accessor, resource, { + logPrefix: '[test]', isCurrent: () => current, authenticate: async request => { forwarded.push(request); }, + })); + current = false; + f.authentication.pending.complete([selected]); + await assert.rejects(result, isCancellationError); + assert.deepStrictEqual({ forwarded, prompts: f.authentication.created }, { forwarded: [], prompts: [] }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/localModelReadyNotification.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/localModelReadyNotification.test.ts index c2d3d2a6aa5c..5e19f7222256 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/localModelReadyNotification.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/localModelReadyNotification.test.ts @@ -52,9 +52,9 @@ function describeActions(actions: readonly IChatInputNotificationAction[]): stri }); } -function body(status: ILocalModelStatusV1, family: ILocalModelFamilyV1, currentModel: ILanguageModelChatMetadataAndIdentifier | undefined) { +function body(status: ILocalModelStatusV1, family: ILocalModelFamilyV1, currentModel: ILanguageModelChatMetadataAndIdentifier | undefined, autoModelFusion?: boolean) { const flavor = getLocalModelReadyOfferFlavor(status, family, false); - const resolved = flavor ? resolveLocalModelReadyOfferBody({ status, family, flavor, currentModel }) : undefined; + const resolved = flavor ? resolveLocalModelReadyOfferBody({ status, family, flavor, currentModel, autoModelFusion }) : undefined; return resolved && { flavor, description: resolved.description, actions: describeActions(resolved.actions) }; } @@ -114,6 +114,27 @@ suite('LocalModelReadyNotification', () => { }); }); + test('names Auto as Copilot Fusion when the host presents it that way', () => { + const status = createStatus([installedFamily], { active: readyActive }); + assert.deepStrictEqual({ + auto: body(status, installedFamily, autoModel, true), + server: body(status, installedFamily, serverModel, true)?.description, + tooSlow: body(createStatus([installedFamily], { active: { ...readyActive, autoEligible: false } }), installedFamily, autoModel, true)?.description, + }, { + auto: { + flavor: 'ready', + description: 'Copilot Fusion can now run some requests on this device, with cloud fallback. New Copilot Fusion chats will use it.', + actions: [ + `Switch to Example Flash 1.0 -> ${VENDOR}:MAI-Code-1.1-Flash (unique)`, + 'Not Now -> _workbench.action.chat.localModel.readyOfferNotNow', + 'New Copilot Fusion Chat [primary] -> workbench.action.chat.localModel.newAutoChat', + ], + }, + server: 'Run this chat on your device, or let Copilot Fusion choose between local and cloud.', + tooSlow: 'It\'s too slow on this device for Copilot Fusion, but you can select it directly.', + }); + }); + test('a second install while another model is active: Load through the confirmed swap', () => { const status = createStatus([installedFamily, otherFamily], { active: { ...readyActive, familyId: otherFamily.familyId, contentId: 'q1' } }); assert.deepStrictEqual(body(status, installedFamily, serverModel), { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/resolveCustomizationRefs.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/resolveCustomizationRefs.test.ts index acc7d91419c1..a0023883878b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/resolveCustomizationRefs.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/resolveCustomizationRefs.test.ts @@ -541,6 +541,25 @@ suite('resolveCustomizationRefs - built-in skills', () => { ]); }); + test('includes plugins without contributions VS Code parses, such as Copilot extensions with canvases', async () => { + const pluginUri = URI.file('/plugins/canvas-only'); + const refs = await resolveCustomizationRefs( + makeFileService(), + makePromptsService(new Map()), + new FakeSyncProvider(), + makeAgentPluginService([makePlugin(pluginUri, { label: 'Canvas Only' })]), + makeMcpService(), + makeConfigurationResolverService(), + toBundlers(new FakeBundler()), + SessionType.CopilotCLI, + undefined, + ); + + assert.deepStrictEqual(refs.map(ref => ({ uri: ref.uri, name: ref.name })), [ + { uri: pluginUri.toString(), name: 'Canvas Only' }, + ]); + }); + test('forwards a userPromptTransformed-only plugin without prompt files', async () => { const pluginUri = URI.file('/plugins/prompt-transform'); const groups = parseHooksJson(URI.joinPath(pluginUri, 'com.github.copilot/hooks/hooks.json'), { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/stateToProgressAdapter.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/stateToProgressAdapter.test.ts index f14e260a809f..ac98827c4b6e 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/stateToProgressAdapter.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/stateToProgressAdapter.test.ts @@ -9,6 +9,7 @@ import { Codicon } from '../../../../../../base/common/codicons.js'; import { autorun } from '../../../../../../base/common/observable.js'; import { hasKey } from '../../../../../../base/common/types.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { isUUID } from '../../../../../../base/common/uuid.js'; import { extUri } from '../../../../../../base/common/resources.js'; import { renderAsPlaintext, renderMarkdown } from '../../../../../../base/browser/markdownRenderer.js'; import { getChatMarkdownRenderOptions } from '../../../browser/widget/chatContentMarkdownRenderer.js'; @@ -31,14 +32,17 @@ import { toAgentWorkspaceContinuationMessageMeta } from '../../../../../../platf import { getComputerUseActivationAnswers, withComputerUseActivationCard, withComputerUseSetupCard } from '../../../../../../platform/agentHost/common/meta/computerUse.js'; import { ConfirmationOptionKind, McpAuthRequiredReason } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; import { createAgentHostResourceUriMapper, fromAgentHostUri, identityAgentHostResourceUriMapper, toAgentHostContentUri } from '../../../../../../platform/agentHost/common/agentHostUri.js'; +import { agentHostConnectionKinds } from '../../../../../../platform/agentHost/test/common/testAgentHostResourceUriMappers.js'; import { buildSubagentChatUri, ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, createErrorResponsePart, MessageAttachmentKind, MessageKind, ToolCallContributorKind, ToolCallRiskAssessmentKind, ToolCallRiskAssessmentStatus, ToolCallStatus, ToolCallConfirmationReason, ToolResultContentType, TurnState, ResponsePartKind, readUsageInfoMeta, withMessageHiddenFromTranscript, withMessageRequestHiddenFromTranscript, withMessageSystemInitiatedLabel, type ActiveTurn, type ChatInputAnswer, type ICompletedToolCall, type ToolCallPendingConfirmationState, type ToolCallRunningState, type Turn, type ToolCallResponsePart, ToolCallCancellationReason, type Message, type ToolResultContent } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { ChatTranscriptContextAttachmentDisplayKind, IChatRequestTranscriptContextVariableEntry, toChatTranscriptContextAttachmentMeta } from '../../../common/attachments/chatVariableEntries.js'; import { ChatRequestOriginKind } from '../../../common/chatRequestOrigin.js'; import { ElicitationState, IChatToolInvocation, IChatToolInvocationSerialized, ToolConfirmKind, type IChatMarkdownContent, type IChatPlanReviewResult, type IChatProgress, type IChatTerminalToolInvocationData, type IChatThinkingPart, type IChatToolInputInvocationData, type IChatUsage } from '../../../common/chatService/chatService.js'; import { isToolResultInputOutputDetails, type IToolResultInputOutputDetails, ToolDataSource, ToolInvocationPresentation } from '../../../common/tools/languageModelToolsService.js'; -import { appendToolOutput, turnsToHistory as rawTurnsToHistory, activeTurnToProgress as rawActiveTurnToProgress, completedToolCallToEditParts, completedToolCallToSerialized, containsAutomaticReplyAnswer, createInputRequestCarousel, getAgentHostActivityProgressId, systemNotificationToChatPart, messageAttachmentsToVariableData, shouldObserveSubagentChat, toolCallStateToInvocation as rawToolCallStateToInvocation, toolCallStateToPreparedInvocation as rawToolCallStateToPreparedInvocation, toolCallStateToStreamingInvocation, finalizeToolInvocation as rawFinalizeToolInvocation, updateRunningToolSpecificData as rawUpdateRunningToolSpecificData, updateStreamingToolInvocation, usageInfoToAutoModeResolution, usageInfoToChatUsage, usageInfoToQuotas, formatTurnResponseDetails, rewriteAgentHostLinkTarget, rewriteMarkdownLinks, turnToResultMetadata, type TurnModelLookup } from '../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { appendToolOutput, turnsToHistory as rawTurnsToHistory, activeTurnToProgress as rawActiveTurnToProgress, completedToolCallToEditParts, completedToolCallToSerialized, containsAutomaticReplyAnswer, createInputRequestCarousel, getAgentHostActivityProgressId, systemNotificationToChatPart, messageAttachmentsToVariableData, shouldObserveSubagentChat, toolCallStateToInvocation as rawToolCallStateToInvocation, toolCallStateToPreparedInvocation as rawToolCallStateToPreparedInvocation, toolCallStateToStreamingInvocation, finalizeToolInvocation as rawFinalizeToolInvocation, isModelRouterPickSettled, updateRunningToolSpecificData as rawUpdateRunningToolSpecificData, updateStreamingToolInvocation, usageInfoToAutoModeResolution, usageInfoToChatUsage, usageInfoToQuotas, formatTurnResponseDetails, rewriteAgentHostLinkTarget, rewriteMarkdownLinks, turnToResultMetadata, type TurnModelLookup } from '../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; import { getQuotaReset } from '../../../../../services/chat/common/chatEntitlementService.js'; import { AGENT_HOST_RETRY_MANAGED_PLUGINS_COMMAND_ID } from '../../../browser/agentSessions/agentHost/agentHostManagedPluginRetry.js'; +import { getGitHubIssueOrPullRequestAttachments } from '../../../browser/widget/input/editor/chatPasteProviders.js'; +import { OPEN_SESSION_COMPARISON_COMMAND_ID } from '../../../../../common/sessionComparisonConstants.js'; // ---- Helper factories ------------------------------------------------------- @@ -430,14 +434,28 @@ suite('stateToProgressAdapter', () => { }); }); + test('restores GitHub issue and pull request attachments from what they say', () => { + const sent = getGitHubIssueOrPullRequestAttachments('https://github.com/microsoft/vscode/pull/345729 and https://github.com/microsoft/vscode/issues/347977'); + const restored = messageAttachmentsToVariableData([ + ...sent.map(attachment => ({ type: MessageAttachmentKind.Simple as const, label: attachment.name, modelRepresentation: String(attachment.value) })), + { type: MessageAttachmentKind.Simple as const, label: 'Notes', modelRepresentation: `${sent[0].value} was merged` }, + ], 'local')?.variables; + + assert.deepStrictEqual(restored?.map(({ kind, id, icon, name, value }) => ({ kind, id: id.startsWith('github-context:') ? id : undefined, icon: icon?.id, name, value })), [ + { kind: 'generic', id: 'github-context:https://github.com/microsoft/vscode/pull/345729', icon: 'git-pull-request', name: 'microsoft/vscode#345729', value: 'GitHub context: https://github.com/microsoft/vscode/pull/345729' }, + { kind: 'generic', id: 'github-context:https://github.com/microsoft/vscode/issues/347977', icon: 'issues', name: 'microsoft/vscode#347977', value: 'GitHub context: https://github.com/microsoft/vscode/issues/347977' }, + { kind: 'generic', id: undefined, icon: undefined, name: 'Notes', value: 'GitHub context: https://github.com/microsoft/vscode/pull/345729 was merged' }, + ]); + }); + test('preserves completion and resource mention ranges when restoring attachments', () => { const text = '/skill first\r\nthen /command and #file'; const attachments = [{ - type: MessageAttachmentKind.Simple as const, + type: MessageAttachmentKind.Resource as const, label: 'Skill', displayKind: 'skill', range: { start: { line: 0, character: 0 }, end: { line: 0, character: 6 } }, - _meta: { uri: 'custom-skill:/selected' }, + uri: 'custom-skill:/selected', }, { type: MessageAttachmentKind.Simple as const, label: 'Command', @@ -466,6 +484,79 @@ suite('stateToProgressAdapter', () => { ]); }); + for (const kind of agentHostConnectionKinds) { + test(`restores skill identity in client space without changing host metadata (${kind.name})`, () => { + const uri = URI.file('/workspace/review/SKILL.md'); + const metadata = { uri: 'file:///wrong/SKILL.md', opaque: { value: false } }; + const variables = messageAttachmentsToVariableData([{ + type: MessageAttachmentKind.Resource, + uri: uri.toString(), + label: '/review', + displayKind: 'skill', + range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } }, + _meta: metadata, + }, { + type: MessageAttachmentKind.Simple, + label: '/compact', + displayKind: 'command', + _meta: { command: 'compact', uri: uri.toString() }, + }], 'test', '/review', kind.resourceUris)?.variables; + + assert.deepStrictEqual(variables, [{ + kind: 'generic', + id: kind.toClient(uri).toString(), + name: '/review', + value: { $mid: 'agentHostCompletion', kind: 'skill' }, + _meta: metadata, + range: { start: 0, endExclusive: 7 }, + }, { + kind: 'generic', + id: 'agent-host-command:compact', + name: '/compact', + value: { $mid: 'agentHostCompletion', kind: 'command' }, + _meta: { command: 'compact', uri: uri.toString() }, + }]); + }); + } + + test('restores legacy persisted Simple skills as bound resources', () => { + const uri = URI.file('/workspace/review/SKILL.md'); + const metadata = { uri: uri.toString(), description: 'Review changes' }; + const variable = messageAttachmentsToVariableData([{ + type: MessageAttachmentKind.Simple, label: '/review', displayKind: 'skill', _meta: metadata, + }], 'local')?.variables[0]; + assert.deepStrictEqual(variable, { + kind: 'generic', id: uri.toString(), name: '/review', value: { $mid: 'agentHostCompletion', kind: 'skill' }, + modelDescription: 'Review changes', _meta: metadata, + }); + }); + + test('restores skills without resource URIs as non-resource references', () => { + const metadata = [undefined, { uri: 42 }]; + const variables = messageAttachmentsToVariableData(metadata.map(_meta => ({ + type: MessageAttachmentKind.Simple, + label: '/review', + displayKind: 'skill', + _meta, + })), 'local')?.variables; + assert.deepStrictEqual(variables?.map(variable => ({ ...variable, id: isUUID(variable.id) })), metadata.map(_meta => ({ + kind: 'generic', + id: true, + name: '/review', + value: { $mid: 'agentHostCompletion', kind: 'skill' }, + _meta, + }))); + }); + + test('rejects malformed skill resource URIs instead of treating them as file paths', () => { + assert.throws(() => messageAttachmentsToVariableData([{ + type: MessageAttachmentKind.Resource, + label: '/review', + displayKind: 'skill', + uri: 'not-a-uri', + }], 'local'), /Scheme is missing/); + }); + test('restores embedded resources with invalid base64 data without throwing', () => { const restored = messageAttachmentsToVariableData([{ type: MessageAttachmentKind.EmbeddedResource, @@ -1476,7 +1567,7 @@ suite('stateToProgressAdapter', () => { }); test('Fusion footer identification is per-turn, including restored events without a selected model', () => { - const usage = { model: 'gpt-5', _meta: { cost: 0 } }; + const usage = { model: 'gpt-5', _meta: { copilotUsage: { totalNanoAiu: 0 } } }; const turns = [ createTurn({ message: { ...message('Before usage'), model: { id: 'hydrafusion' } } }), createTurn({ @@ -1564,6 +1655,26 @@ suite('stateToProgressAdapter', () => { assert.deepStrictEqual(response.parts.filter(part => part.kind === 'autoModeResolution'), []); }); + test('a model router that picks once per chat is settled after its first pick', () => { + const routedTurn = (id: string, router: string, firstTurnOnly?: boolean) => createTurn({ id, usage: { _meta: { modelRouted: { router, chosenModel: 'opus', ...(firstTurnOnly ? { firstTurnOnly } : {}) } } } }); + const picked = routedTurn('turn-1', 'daily', true); + const selecting = (model: string) => createTurn({ id: 'turn-2', message: { text: 'Hello', origin: { kind: MessageKind.User }, model: { id: model } } }); + // After a restart a turn's selection is the model it ran on; its usage says which router it asked for, if any. + const restoredUnrouted = (router: string) => createTurn({ id: 'turn-2', message: { text: 'Hello', origin: { kind: MessageKind.User }, model: { id: 'opus' } }, usage: { inputTokens: 5, outputTokens: 1, _meta: { modelRouterUnrouted: router } } }); + assert.deepStrictEqual({ + firstTurn: isModelRouterPickSettled([picked], 'turn-1', 'daily'), + laterTurn: isModelRouterPickSettled([picked, createTurn({ id: 'turn-2' })], 'turn-3', 'daily'), + afterItsOwnUnroutedTurn: isModelRouterPickSettled([picked, selecting('model-router:daily')], 'turn-3', 'daily'), + afterItsOwnRestoredUnroutedTurn: isModelRouterPickSettled([picked, restoredUnrouted('daily')], 'turn-3', 'daily'), + afterAnotherRoutersRestoredUnroutedTurn: isModelRouterPickSettled([picked, restoredUnrouted('other')], 'turn-3', 'daily'), + afterAHandPickedModel: isModelRouterPickSettled([picked, selecting('opus')], 'turn-3', 'daily'), + afterAnotherRouterWasSelected: isModelRouterPickSettled([picked, selecting('model-router:other')], 'turn-3', 'daily'), + reroutesEveryTurn: isModelRouterPickSettled([routedTurn('turn-1', 'daily')], 'turn-2', 'daily'), + anotherRouter: isModelRouterPickSettled([picked], 'turn-2', 'other'), + notARouter: isModelRouterPickSettled([picked], 'turn-2', undefined), + }, { firstTurn: false, laterTurn: true, afterItsOwnUnroutedTurn: true, afterItsOwnRestoredUnroutedTurn: true, afterAnotherRoutersRestoredUnroutedTurn: false, afterAHandPickedModel: false, afterAnotherRouterWasSelected: false, reroutesEveryTurn: false, anotherRouter: false, notARouter: false }); + }); + test('falls back to session-level model when turn has no usage.model', () => { const turn = createTurn({ message: message('first') }); const lookup = makeLookup('agent-host-copilot:', { 'gpt-5': 'GPT-5' }, 'gpt-5'); @@ -2498,6 +2609,22 @@ suite('stateToProgressAdapter', () => { }); }); + test('summarizes a view call without a line range by what the host reports its path named', () => { + const resourceUris = createAgentHostResourceUriMapper('remote-test'); + const session = URI.parse('ahp-session:/opaque-session'); + const fields = { toolName: 'view', toolInput: JSON.stringify({ path: '/workspace/src' }) }; + const summaries = ['file', 'directory', 'image', undefined].map(viewedResourceType => { + const completed = createCompletedToolCall({ ...fields, _meta: { ...nativeToolMeta, 'vscode.viewedResourceType': viewedResourceType } }); + const live = rawToolCallStateToInvocation(createToolCallState({ ...fields, _meta: nativeToolMeta }), undefined, session, 'remote-test', undefined, undefined, resourceUris); + rawFinalizeToolInvocation(live, completed, session, 'remote-test', resourceUris); + return { live: live.summary, restored: completedToolCallToSerialized(completed, undefined, session, 'remote-test', resourceUris).summary }; + }); + const resources = [{ uri: resourceUris.fromAgentHost(URI.file('/workspace/src')) }]; + assert.deepStrictEqual(summaries, [ + { kind: 'read', resources }, { kind: 'list', resources }, { kind: 'unknown' }, { kind: 'unknown' }, + ].map(summary => ({ live: summary, restored: summary }))); + }); + test('requires an explicit native input contract and excludes client and MCP implementations', () => { const resourceUris = createAgentHostResourceUriMapper('remote-test'); const session = URI.parse('ahp-session:/unrelated-peer/session-id'); @@ -3379,6 +3506,41 @@ suite('stateToProgressAdapter', () => { }); }); + suite('model comparison reference', () => { + test('reconstructs the same narrowly trusted link for live completion and restored history', () => { + const comparisonId = 'comparison-(one)'; + const tc = createCompletedToolCall({ + toolName: 'createModelComparison', + pastTenseMessage: { markdown: '[untrusted](command:unrelated.command)' }, + content: [{ type: ToolResultContentType.Text, text: JSON.stringify({ comparisonId }) }], + }); + const invocation = toolCallStateToInvocation(createToolCallState({ toolName: tc.toolName })); + finalizeToolInvocation(invocation, tc); + const expected = { + value: `Started model comparison. [Open Comparison](command:${OPEN_SESSION_COMPARISON_COMMAND_ID}?%5B%22comparison-%28one%29%22%5D)`, + isTrusted: { enabledCommands: [OPEN_SESSION_COMPARISON_COMMAND_ID] }, + }; + const messages = [invocation.pastTenseMessage, completedToolCallToSerialized(tc, undefined, URI.file('/'), 'remote-test').pastTenseMessage]; + assert.deepStrictEqual(messages.map(message => { + assert.ok(message && typeof message !== 'string'); + return { value: message.value, isTrusted: message.isTrusted }; + }), [expected, expected]); + }); + + test('does not trust unrelated, failed or malformed tool output', () => { + const messages = [ + { toolName: 'otherTool', success: true, text: '{"comparisonId":"comparison"}' }, + { toolName: 'createModelComparison', success: false, text: '{"comparisonId":"comparison"}' }, + { toolName: 'createModelComparison', success: true, text: 'not JSON' }, + { toolName: 'createModelComparison', success: true, text: 'null' }, + { toolName: 'createModelComparison', success: true, text: '{"comparisonId":17}' }, + ].map(({ toolName, success, text }) => completedToolCallToSerialized(createCompletedToolCall({ + toolName, success, content: [{ type: ToolResultContentType.Text, text }], + }), undefined, URI.file('/'), 'local').pastTenseMessage); + assert.deepStrictEqual(messages, ['Ran test tool', 'Running test tool...', 'Ran test tool', 'Ran test tool', 'Ran test tool']); + }); + }); + suite('addComment reference', () => { const commentRange = { startLineNumber: 3, startColumn: 1, endLineNumber: 3, endColumn: 5 }; @@ -3750,6 +3912,36 @@ suite('stateToProgressAdapter', () => { }); }); + test('a call the user approves stays visible once it completes, and one they decline is hidden', () => { + const running = createToolCallState({ toolCallId: 'tc-grep', toolName: 'grep', displayName: 'Search', invocationMessage: 'Search for `thinkingStyle`', _meta: { toolKind: 'search' } }); + const pending: AnyToolCallState = { ...running, status: ToolCallStatus.PendingConfirmation, confirmationTitle: 'Allow search?' }; + const settle = (asksFirst: boolean, approved: boolean) => { + // Copilot starts a call running and asks for approval later; other hosts can ask first. + const invocation = toolCallStateToInvocation(asksFirst ? pending : running); + if (!asksFirst) { + invocation.requestConfirmation(toolCallStateToPreparedInvocation(pending)); + } + const hiddenWhilePending = IChatToolInvocation.isEffectivelyHidden(invocation); + IChatToolInvocation.confirmWith(invocation, { type: approved ? ToolConfirmKind.UserAction : ToolConfirmKind.Denied }); + finalizeToolInvocation(invocation, approved + ? createCompletedToolCall({ ...running, status: ToolCallStatus.Completed, pastTenseMessage: 'Searched for `thinkingStyle`' }) + : { ...running, status: ToolCallStatus.Cancelled, reason: ToolCallCancellationReason.Denied }); + return { hiddenWhilePending, hidden: IChatToolInvocation.isEffectivelyHidden(invocation) }; + }; + + assert.deepStrictEqual({ + approvedAfterRunning: settle(false, true), + approvedBeforeRunning: settle(true, true), + declinedAfterRunning: settle(false, false), + declinedBeforeRunning: settle(true, false), + }, { + approvedAfterRunning: { hiddenWhilePending: false, hidden: false }, + approvedBeforeRunning: { hiddenWhilePending: false, hidden: false }, + declinedAfterRunning: { hiddenWhilePending: false, hidden: true }, + declinedBeforeRunning: { hiddenWhilePending: false, hidden: true }, + }); + }); + test('requestConfirmation no-ops on a completed invocation', () => { const streaming = toolCallStateToStreamingInvocation({ toolCallId: 'tc-done', toolName: 'bash', displayName: 'Bash', status: ToolCallStatus.Streaming }, undefined); streaming.transitionFromStreaming(toolCallStateToPreparedInvocation({ toolCallId: 'tc-done', toolName: 'bash', displayName: 'Bash', invocationMessage: 'run', status: ToolCallStatus.Running, confirmed: ToolCallConfirmationReason.NotNeeded }), undefined, undefined); @@ -5891,13 +6083,21 @@ suite('stateToProgressAdapter', () => { const auto = { name: 'Auto' }; + test('does not present a model multiplier as measured credits', () => { + assert.deepStrictEqual([ + formatTurnResponseDetails({ name: 'Model' }, undefined, { _meta: { cost: 2 } }), + formatTurnResponseDetails({ name: 'Model', pricing: '2x' }, undefined, { _meta: { cost: 2 } }), + formatTurnResponseDetails({ name: 'Model' }, undefined, { _meta: { cost: 2, copilotUsage: { totalNanoAiu: 0 } } }), + ], ['Model', 'Model · 2x', 'Model • 0 credits']); + }); + test('appends the billed model id when one is supplied', () => { // A pick whose billed model is unregistered (e.g. "Auto" billed as "raptor-mini") shows "Auto (raptor-mini)". const result = { resolvedModel: formatTurnResponseDetails(auto, 'raptor-mini', undefined), withPricing: formatTurnResponseDetails({ ...auto, pricing: '0x' }, 'raptor-mini', undefined), - withCredits: formatTurnResponseDetails(auto, 'raptor-mini', { _meta: { cost: 2 } }), - oneCredit: formatTurnResponseDetails(auto, 'raptor-mini', { _meta: { cost: 1 } }), + withCredits: formatTurnResponseDetails(auto, 'raptor-mini', { _meta: { copilotUsage: { totalNanoAiu: 2_000_000_000 } } }), + oneCredit: formatTurnResponseDetails(auto, 'raptor-mini', { _meta: { copilotUsage: { totalNanoAiu: 1_000_000_000 } } }), noBilledModel: formatTurnResponseDetails(auto, undefined, undefined), }; @@ -5914,7 +6114,7 @@ suite('stateToProgressAdapter', () => { const sonnet = { name: 'Claude Sonnet 4.5', pricing: '1x' }; const result = { concrete: formatTurnResponseDetails(sonnet, undefined, undefined), - concreteWithCredits: formatTurnResponseDetails(sonnet, undefined, { _meta: { cost: 2 } }), + concreteWithCredits: formatTurnResponseDetails(sonnet, undefined, { _meta: { copilotUsage: { totalNanoAiu: 2_000_000_000 } } }), unknown: formatTurnResponseDetails(undefined, 'raptor-mini', { _meta: { cost: 2 } }), }; @@ -5943,6 +6143,16 @@ suite('stateToProgressAdapter', () => { }); suite('usageInfoToChatUsage', () => { + test('reports measured credits without model multipliers', () => { + assert.deepStrictEqual([ + usageInfoToChatUsage({ _meta: { cost: 0 } })?.copilotCredits, + usageInfoToChatUsage({ _meta: { cost: 2 } })?.copilotCredits, + usageInfoToChatUsage({ _meta: { cost: 2, copilotUsage: { totalNanoAiu: 0 } } })?.copilotCredits, + usageInfoToChatUsage({ _meta: { cost: 2, copilotUsage: { totalNanoAiu: 1_500_000_000 } } })?.copilotCredits, + usageInfoToChatUsage({ _meta: { copilotUsage: { totalNanoAiu: 1_500_000_000 } } })?.copilotCredits, + ], [undefined, undefined, 0, 1.5, 1.5]); + }); + test('carries whole-turn per-model token totals and resolves display names', () => { const turnTokenTotals = [{ model: 'claude-opus-4.8', inputTokens: 110, cachedTokens: 4, outputTokens: 220 }]; diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationItemsModel.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationItemsModel.test.ts index 1b578dc3993c..37c875335391 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationItemsModel.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationItemsModel.test.ts @@ -25,9 +25,9 @@ import { ICustomizationHarnessService, ICustomizationItem, ICustomizationItemPro import { ContributionEnablementState } from '../../../common/enablement.js'; import { createCustomizationMarketplaceInstallationSnapshot, CustomizationMarketplaceInstallState, emptyCustomizationMarketplaceInstallationSnapshot, ICustomizationMarketplaceInstallationSnapshot, ICustomizationMarketplaceInstallService, RecordedCustomizationMarketplaceInstallState } from '../../../common/customizationMarketplaceInstallService.js'; import { IAgentPluginService, type IAgentPlugin } from '../../../common/plugins/agentPluginService.js'; -import { PromptsType, Target } from '../../../common/promptSyntax/promptTypes.js'; +import { PromptFileSource, PromptsType, Target } from '../../../common/promptSyntax/promptTypes.js'; import { IAgentSource, ICustomAgent, IPromptPath, IPromptsService, PromptsStorage } from '../../../common/promptSyntax/service/promptsService.js'; -import { getChatSessionType } from '../../../common/model/chatUri.js'; +import { getChatSessionType, LocalChatSessionUri } from '../../../common/model/chatUri.js'; import { basename } from '../../../../../../base/common/resources.js'; suite('AICustomizationItemsModel', () => { @@ -51,6 +51,7 @@ suite('AICustomizationItemsModel', () => { let descriptorA: IHarnessDescriptor; let descriptorB: IHarnessDescriptor; let providerA_didChange: Emitter; + let hooksDidChange: Emitter; let providerA_callCount: number; let providerA_items: ICustomizationItem[]; let plugins: ISettableObservable; @@ -73,6 +74,7 @@ suite('AICustomizationItemsModel', () => { setup(() => { disposables = new DisposableStore(); providerA_didChange = disposables.add(new Emitter()); + hooksDidChange = disposables.add(new Emitter()); providerA_callCount = 0; providerA_items = []; listPromptFilesResult = []; @@ -128,7 +130,7 @@ suite('AICustomizationItemsModel', () => { onDidChangeCustomAgents: Event.None, onDidChangeSlashCommands: Event.None, onDidChangeSkills: Event.None, - onDidChangeHooks: Event.None, + onDidChangeHooks: hooksDidChange.event, onDidChangeInstructions: Event.None, onDidChangeAgentInstructions: Event.None, listPromptFiles: async (type: PromptsType) => listPromptFilesResult.filter(f => f.type === type), @@ -281,6 +283,24 @@ suite('AICustomizationItemsModel', () => { assert.strictEqual(providerA_callCount, 2); }); + test('session-scoped models keep discovery and counts separate from the active harness', async () => { + providerA_items = [{ + uri: URI.file('/active/SKILL.md'), type: PromptsType.skill, name: 'Active Skill', + source: AICustomizationSources.plugin, extensionId: undefined, pluginUri: undefined, userInvocable: true, + }]; + const model = disposables.add(instaService.createInstance(AICustomizationItemsModel)); + await model.whenSectionLoaded(AICustomizationManagementSection.Skills); + const resource = URI.parse('B:///other-session'); + const scope = disposables.add(model.createSessionModel(resource)); + await scope.model.whenSectionLoaded(AICustomizationManagementSection.Skills); + assert.deepStrictEqual({ + activeSession: activeSessionResource.get().toString(), + activeCount: model.getCount(AICustomizationManagementSection.Skills).get(), + scopedSession: scope.model.getActiveItemSource().sessionResource.toString(), + scopedCount: scope.model.getCount(AICustomizationManagementSection.Skills).get(), + }, { activeSession: 'A:/session', activeCount: 1, scopedSession: resource.toString(), scopedCount: 0 }); + }); + test('source.onDidChange refetches only previously-observed sections', async () => { const model = disposables.add(instaService.createInstance(AICustomizationItemsModel)); model.getItems(AICustomizationManagementSection.Agents); @@ -462,6 +482,38 @@ suite('AICustomizationItemsModel', () => { }]); }); + test('refreshes Local hook inventory without another plugin contribution changing', async () => { + availableHarnesses.set([createDescriptor('local', undefined)], undefined); + activeSessionResource.set(LocalChatSessionUri.forSession('hooks-only'), undefined); + const model = disposables.add(instaService.createInstance(AICustomizationItemsModel)); + const section = AICustomizationManagementSection.Hooks; + const items = model.getItems(section); + const count = model.getCount(section); + await timeout(0); + await model.whenSectionLoaded(section); + const snapshots = [items.get().map(item => item.name)]; + + const plugin = createLocalPlugin('hooks-only'); + plugins.set([plugin], undefined); + listPromptFilesResult = ['sessionStart', 'userPromptSubmitted'].map(name => ({ + uri: URI.parse('file:///plugins/hooks-only/hooks.json'), + name, + type: PromptsType.hook, + storage: PromptsStorage.plugin, + pluginUri: plugin.uri, + source: PromptFileSource.Plugin, + })); + hooksDidChange.fire(); + await timeout(0); + await model.whenSectionLoaded(section); + snapshots.push(items.get().map(item => item.name)); + + assert.deepStrictEqual({ snapshots, count: count.get() }, { + snapshots: [[], ['sessionStart', 'userPromptSubmitted']], + count: 2, + }); + }); + test('plugin count includes provider-supplied plugin items', async () => { providerA_items = [ { @@ -908,7 +960,7 @@ suite('AICustomizationItemsModel', () => { const model = disposables.add(instaService.createInstance(AICustomizationItemsModel)); const count = model.getPluginCount(); - await timeout(0); + await model.whenSectionLoaded(AICustomizationManagementSection.Plugins); assert.strictEqual(count.get(), 2, 'remote-client harness rows are excluded; both internal "plugin" and API "plugins" types are recognised'); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationListWidget.test.ts index ef0bdd23d267..ab4226734478 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationListWidget.test.ts @@ -11,9 +11,11 @@ import { Emitter, Event } from '../../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { derived, observableValue } from '../../../../../../base/common/observable.js'; import { setARIAContainer } from '../../../../../../base/browser/ui/aria/aria.js'; +import { IContextMenuDelegate } from '../../../../../../base/browser/contextmenu.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { CommandsRegistry, ICommandService } from '../../../../../../platform/commands/common/commands.js'; +import { IContextMenuService } from '../../../../../../platform/contextview/browser/contextView.js'; import { CustomizationMarketplaceMediaType, ICustomizationMarketplaceService } from '../../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; import { IListService, ListService } from '../../../../../../platform/list/browser/listService.js'; import { ColorScheme } from '../../../../../../platform/theme/common/theme.js'; @@ -105,6 +107,29 @@ suite('aiCustomizationListWidget', () => { assert.deepStrictEqual(focusChanges, [[firstItem], [group]]); }); + test('moves focus that is kept inside a collapsed group to the first visible item', () => { + type Entry = { type: 'group-header'; id: string } | { type: 'item'; id: string }; + const collapsedGroup: Entry = { type: 'group-header', id: 'user' }; + const hiddenItem: Entry = { type: 'item', id: 'hidden' }; + const expandedGroup: Entry = { type: 'group-header', id: 'workspace' }; + const visibleItem: Entry = { type: 'item', id: 'visible' }; + let focus: Entry[] = [hiddenItem]; + const focusChanges: Entry[][] = []; + const list = { + getFocus: () => focus, + setFocus: (entries: Entry[]) => { + focus = entries; + focusChanges.push(entries); + }, + }; + const isVisible = (entry: Entry) => entry !== hiddenItem; + + focusFirstCustomizationTreeItem(list, [collapsedGroup, hiddenItem, expandedGroup, visibleItem], entry => entry.type === 'item', isVisible); + focusFirstCustomizationTreeItem(list, [collapsedGroup, hiddenItem, expandedGroup, visibleItem], entry => entry.type === 'item', isVisible); + + assert.deepStrictEqual(focusChanges, [[visibleItem]]); + }); + test('keeps editable source sections visible until search filtering starts', () => { assert.deepStrictEqual({ agents: getAlwaysVisibleCustomizationGroupKeys(AICustomizationManagementSection.Agents, false), @@ -1096,6 +1121,96 @@ suite('aiCustomizationListWidget', () => { }); }); + test('keeps the overflow action visible while its context menu is open without moving tree focus', async () => { + const item: IAICustomizationListItem = { + id: 'skill', + uri: URI.file('/workspace/.github/skills/review/SKILL.md'), + name: 'Review', + filename: '.github/skills/review/SKILL.md', + description: 'Review changes', + source: PromptsStorage.local, + promptType: PromptsType.skill, + disabled: false, + }; + const items = observableValue('test', [item]); + let contextMenuDelegate: IContextMenuDelegate | undefined; + instaService.stub(IContextMenuService, { + onDidShowContextMenu: Event.None, + onDidHideContextMenu: Event.None, + showContextMenu: delegate => contextMenuDelegate = delegate as IContextMenuDelegate, + }); + instaService.stub(IAICustomizationItemsModel, { + getItems: () => items, + getCount: () => observableValue('test', 1), + getPluginCount: () => observableValue('test', 0), + whenSectionLoaded: async () => { }, + getActiveItemSource: () => ({ onDidAICustomizationItemsChange: Event.None, fetchProviderItems: async () => [], fetchAICustomizationItems: async () => [], fetchSourceFolders: async () => [], sessionResource: URI.parse('test:///session'), dispose() { } }), + }); + const widget = disposables.add(instaService.createInstance(AICustomizationListWidget)); + document.body.appendChild(widget.element); + disposables.add(toDisposable(() => widget.element.remove())); + const selections: string[] = []; + disposables.add(widget.onDidSelectItem(selected => selections.push(selected.id))); + setLayoutHeights(widget, 500); + + await widget.setSection(AICustomizationManagementSection.Skills); + widget.layout(800, 500); + const getRow = () => widget.element.querySelector('.ai-customization-list-item')!; + const initialAction = getRow().querySelector('.item-right .action-label')!; + const initialFocusedRows = widget.element.querySelectorAll('.monaco-list-row.focused').length; + initialAction.click(); + assert.ok(contextMenuDelegate); + const openRow = getRow(); + const openAction = openRow.querySelector('.item-right .action-label')!; + const openState = { + menuOpen: openRow.classList.contains('menu-open'), + hasPopup: openAction.getAttribute('aria-haspopup'), + expanded: openAction.getAttribute('aria-expanded'), + autoSelectItem: contextMenuDelegate.autoSelectItem, + focusedRows: widget.element.querySelectorAll('.monaco-list-row.focused').length, + }; + + items.set([{ ...item, description: 'Updated review instructions' }], undefined); + const refreshedRow = getRow(); + const refreshedAction = refreshedRow.querySelector('.item-right .action-label')!; + const refreshedState = { + menuOpen: refreshedRow.classList.contains('menu-open'), + expanded: refreshedAction.getAttribute('aria-expanded'), + }; + + contextMenuDelegate.onHide?.(false); + const closedRow = getRow(); + const closedAction = closedRow.querySelector('.item-right .action-label')!; + assert.deepStrictEqual({ + initialFocusedRows, + openState, + refreshedState, + closedState: { + menuOpen: closedRow.classList.contains('menu-open'), + expanded: closedAction.getAttribute('aria-expanded'), + }, + selections, + }, { + initialFocusedRows: 0, + openState: { + menuOpen: true, + hasPopup: 'menu', + expanded: 'true', + autoSelectItem: true, + focusedRows: 0, + }, + refreshedState: { + menuOpen: true, + expanded: 'true', + }, + closedState: { + menuOpen: false, + expanded: 'false', + }, + selections: [], + }); + }); + test('shows one aligned icon per item when a marketplace skill has an icon', async () => { const marketplaceUri = URI.file('/workspace/.github/skills/marketplace/SKILL.md'); const plainUri = URI.file('/workspace/.github/skills/plain/SKILL.md'); @@ -1355,6 +1470,186 @@ suite('aiCustomizationListWidget', () => { }); }); + test('toggles scope groups with a single click on the header', async () => { + const agents = observableValue('agents', [{ + id: 'agent-one', + uri: URI.file('/workspace/.github/agents/agent-one.agent.md'), + name: 'Agent One', + filename: 'agent-one.agent.md', + source: PromptsStorage.local, + promptType: PromptsType.agent, + disabled: false, + }]); + instaService.stub(IAICustomizationItemsModel, { + getItems: () => agents, + getCount: () => observableValue('test', 1), + getPluginCount: () => observableValue('test', 0), + whenSectionLoaded: async () => { }, + getActiveItemSource: () => ({ onDidAICustomizationItemsChange: Event.None, fetchProviderItems: async () => [], fetchAICustomizationItems: async () => [], fetchSourceFolders: async () => [], sessionResource: URI.parse('test:///session'), dispose() { } }), + }); + const widget = disposables.add(instaService.createInstance(AICustomizationListWidget)); + document.body.appendChild(widget.element); + disposables.add(toDisposable(() => widget.element.remove())); + setLayoutHeights(widget, 500); + await widget.setSection(AICustomizationManagementSection.Agents); + widget.layout(800, 500); + const labels = () => Array.from(widget.element.querySelectorAll('.item-name'), element => element.textContent); + const clickWorkspaceHeader = () => [...widget.element.querySelectorAll('.group-label')] + .find(element => element.textContent === 'Workspace')! + .dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 })); + + const initial = labels(); + clickWorkspaceHeader(); + const afterCollapse = labels(); + clickWorkspaceHeader(); + + assert.deepStrictEqual({ initial, afterCollapse, afterExpand: labels() }, { + initial: ['Agent One'], + afterCollapse: [], + afterExpand: ['Agent One'], + }); + }); + + test('keeps collapsed groups and focus when the items refresh', async () => { + const createAgent = (name: string, source: PromptsStorage): IAICustomizationListItem => ({ + id: name, + uri: URI.file(`/${source}/.github/agents/${name}.agent.md`), + name, + filename: `${name}.agent.md`, + source, + promptType: PromptsType.agent, + disabled: false, + }); + const agents = observableValue('agents', [createAgent('local-one', PromptsStorage.local), createAgent('user-one', PromptsStorage.user)]); + instaService.stub(IAICustomizationItemsModel, { + getItems: () => agents, + getCount: () => observableValue('test', agents.get().length), + getPluginCount: () => observableValue('test', 0), + whenSectionLoaded: async () => { }, + getActiveItemSource: () => ({ onDidAICustomizationItemsChange: Event.None, fetchProviderItems: async () => [], fetchAICustomizationItems: async () => [], fetchSourceFolders: async () => [], sessionResource: URI.parse('test:///session'), dispose() { } }), + }); + const widget = disposables.add(instaService.createInstance(AICustomizationListWidget)); + document.body.appendChild(widget.element); + disposables.add(toDisposable(() => widget.element.remove())); + setLayoutHeights(widget, 500); + await widget.setSection(AICustomizationManagementSection.Agents); + widget.layout(800, 500); + const labels = () => Array.from(widget.element.querySelectorAll('.item-name'), element => element.textContent); + const list = widget.element.querySelector('.monaco-list')!; + const focused = () => document.getElementById(list.getAttribute('aria-activedescendant')!)?.querySelector('.item-name')?.textContent; + [...widget.element.querySelectorAll('.group-label')] + .find(element => element.textContent === 'User')! + .dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 })); + widget.focusList(); + const collapsed = { labels: labels(), focused: focused() }; + + agents.set([...agents.get(), createAgent('local-two', PromptsStorage.local), createAgent('user-two', PromptsStorage.user)], undefined); + const afterItemsChange = { labels: labels(), focused: focused() }; + widget.setSearchQuery('one'); + const whileSearching = labels(); + widget.clearSearch(); + + assert.deepStrictEqual({ collapsed, afterItemsChange, whileSearching, afterClearingSearch: labels() }, { + collapsed: { labels: ['local-one'], focused: 'local-one' }, + afterItemsChange: { labels: ['local-one', 'local-two'], focused: 'local-one' }, + whileSearching: ['local-one', 'user-one'], + afterClearingSearch: ['local-one', 'local-two'], + }); + }); + + test('focuses a visible item when entering a tree whose first group is collapsed', async () => { + const createAgent = (name: string, source: PromptsStorage): IAICustomizationListItem => ({ + id: name, + uri: URI.file(`/${source}/.github/agents/${name}.agent.md`), + name, + filename: `${name}.agent.md`, + source, + promptType: PromptsType.agent, + disabled: false, + }); + const agents = observableValue('agents', [createAgent('local-one', PromptsStorage.local), createAgent('user-one', PromptsStorage.user)]); + instaService.stub(IAICustomizationItemsModel, { + getItems: () => agents, + getCount: () => observableValue('test', agents.get().length), + getPluginCount: () => observableValue('test', 0), + whenSectionLoaded: async () => { }, + getActiveItemSource: () => ({ onDidAICustomizationItemsChange: Event.None, fetchProviderItems: async () => [], fetchAICustomizationItems: async () => [], fetchSourceFolders: async () => [], sessionResource: URI.parse('test:///session'), dispose() { } }), + }); + const widget = disposables.add(instaService.createInstance(AICustomizationListWidget)); + document.body.appendChild(widget.element); + disposables.add(toDisposable(() => widget.element.remove())); + setLayoutHeights(widget, 500); + await widget.setSection(AICustomizationManagementSection.Agents); + widget.layout(800, 500); + const list = widget.element.querySelector('.monaco-list')!; + const focused = () => document.getElementById(list.getAttribute('aria-activedescendant') ?? '')?.querySelector('.item-name, .group-label')?.textContent; + const clickGroup = (label: string) => [...widget.element.querySelectorAll('.group-label')] + .find(element => element.textContent === label)! + .dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 })); + clickGroup('Workspace'); + await widget.setSection(AICustomizationManagementSection.Skills); + await widget.setSection(AICustomizationManagementSection.Agents); + list.focus(); + list.dispatchEvent(new FocusEvent('focus')); + const onTab = focused(); + widget.focusList(); + const onFocusList = focused(); + clickGroup('User'); + await widget.setSection(AICustomizationManagementSection.Skills); + await widget.setSection(AICustomizationManagementSection.Agents); + widget.focusList(); + const allCollapsed = focused(); + + assert.deepStrictEqual({ onTab, onFocusList, allCollapsed }, { + onTab: 'user-one', + onFocusList: 'user-one', + allCollapsed: 'Workspace', + }); + }); + + test('moves focus to the group header when clearing the search hides the focused item', async () => { + const createAgent = (name: string, source: PromptsStorage): IAICustomizationListItem => ({ + id: name, + uri: URI.file(`/${source}/.github/agents/${name}.agent.md`), + name, + filename: `${name}.agent.md`, + source, + promptType: PromptsType.agent, + disabled: false, + }); + const agents = observableValue('agents', [createAgent('local-one', PromptsStorage.local), createAgent('user-one', PromptsStorage.user)]); + instaService.stub(IAICustomizationItemsModel, { + getItems: () => agents, + getCount: () => observableValue('test', agents.get().length), + getPluginCount: () => observableValue('test', 0), + whenSectionLoaded: async () => { }, + getActiveItemSource: () => ({ onDidAICustomizationItemsChange: Event.None, fetchProviderItems: async () => [], fetchAICustomizationItems: async () => [], fetchSourceFolders: async () => [], sessionResource: URI.parse('test:///session'), dispose() { } }), + }); + const widget = disposables.add(instaService.createInstance(AICustomizationListWidget)); + document.body.appendChild(widget.element); + disposables.add(toDisposable(() => widget.element.remove())); + setLayoutHeights(widget, 500); + await widget.setSection(AICustomizationManagementSection.Agents); + widget.layout(800, 500); + const list = widget.element.querySelector('.monaco-list')!; + const focused = () => document.getElementById(list.getAttribute('aria-activedescendant') ?? '')?.querySelector('.item-name, .group-label')?.textContent; + [...widget.element.querySelectorAll('.group-label')] + .find(element => element.textContent === 'User')! + .dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 })); + widget.setSearchQuery('user-one'); + widget.focusList(); + const whileSearching = focused(); + widget.clearSearch(); + const afterClearingSearch = focused(); + list.dispatchEvent(new FocusEvent('focus')); + + assert.deepStrictEqual({ whileSearching, afterClearingSearch, onTab: focused() }, { + whileSearching: 'user-one', + afterClearingSearch: 'User', + onTab: 'User', + }); + }); + test('announces updated item count when the model changes after section load', async () => { const ariaHost = document.createElement('div'); document.body.appendChild(ariaHost); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagement.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagement.test.ts index 312d7eb2583c..3abe2bdb27bb 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagement.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagement.test.ts @@ -10,10 +10,26 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/ import { AICustomizationManagementSection, resolveAICustomizationManagementOpenEditorTarget } from '../../../browser/aiCustomization/aiCustomizationManagement.js'; import { CustomizationMigrationCategoryId } from '../../../browser/aiCustomization/customizationMigrationCategories.js'; import { CustomizationMigrationType } from '../../../common/promptSyntax/service/customizationMigrationService.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { IChatWidget } from '../../../browser/chat.js'; suite('aiCustomizationManagement', () => { ensureNoDisposablesAreLeakedInTestSuite(); + test('input actions target their own widget for pointer and keyboard invocation', () => { + const origin = URI.parse('agent-host-copilot:/origin'); + const fallback = URI.parse('local:/other-widget'); + const results = [undefined, 'agent-host-claude'].map(pendingDelegationTarget => + resolveAICustomizationManagementOpenEditorTarget({ + widget: upcastPartial({ + input: upcastPartial({ pendingDelegationTarget }), + viewModel: upcastPartial>({ sessionResource: origin }), + }), + }, 'unrelated-harness', fallback, sessionType => URI.from({ scheme: sessionType, path: '/draft' })).sessionResource?.toString(), + ); + assert.deepStrictEqual(results, [origin.toString(), 'agent-host-claude:/draft']); + }); + test('resolves the originating chat title context before fallback session state', () => { const titleSessionResource = URI.parse('agent-host-copilot:/title-session'); const fallbackSessionResource = URI.parse('local:/fallback-session'); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagementEditor.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagementEditor.test.ts index 21ef0fd0a2b3..e21200b58fd7 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagementEditor.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationManagementEditor.test.ts @@ -2074,6 +2074,27 @@ suite('aiCustomizationManagementEditor', () => { }); }); + test('selecting a section by id moves focus into it unless focus is preserved', () => { + const editor = createTestEditor(); + store.add(editor.editorPreviewDisposables); + const focused: AICustomizationManagementSection[] = []; + Object.assign(editor, { + sections: [{ id: AICustomizationManagementSection.Instructions }, { id: AICustomizationManagementSection.McpServers }], + sectionContextKey: { set() { } }, + listWidget: { setSection: async () => { }, focusSearch: () => focused.push(AICustomizationManagementSection.Instructions) }, + mcpListWidget: { setVisible() { }, focusSearch: () => focused.push(AICustomizationManagementSection.McpServers) }, + }); + + editor.selectSectionById(AICustomizationManagementSection.Instructions); + editor.selectSectionById(AICustomizationManagementSection.McpServers); + editor.selectSectionById(AICustomizationManagementSection.Instructions, { preserveFocus: true }); + + assert.deepStrictEqual({ focused, selected: editor.selectedSection }, { + focused: [AICustomizationManagementSection.Instructions, AICustomizationManagementSection.McpServers], + selected: AICustomizationManagementSection.Instructions, + }); + }); + test('opens a plugin skill when section counts change while it loads', async () => { type SectionItem = { readonly id: AICustomizationManagementSection; readonly label: string; readonly description: string; count: number }; type NavigationEditor = TestableEditor & { diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationSectionBadges.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationSectionBadges.test.ts new file mode 100644 index 000000000000..0f0f582a88b7 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/aiCustomizationSectionBadges.test.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Codicon } from '../../../../../../base/common/codicons.js'; +import { autorun, constObservable, derived, observableValue } from '../../../../../../base/common/observable.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { aiCustomizationManagementSectionRegistry } from '../../../browser/aiCustomization/aiCustomizationManagementSectionRegistry.js'; +import { observeVisibleSectionsBadge } from '../../../browser/aiCustomization/aiCustomizationSectionBadges.js'; +import { AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../../common/aiCustomizationWorkspaceService.js'; +import { ICustomizationHarnessService, IHarnessDescriptor } from '../../../common/customizationHarnessService.js'; + +suite('aiCustomizationSectionBadges', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('shows the badge of the first visible section and does not read the badges of other sections', () => { + const harnessId = 'test-harness'; + const enablementSetting = 'test.sectionBadges.enabled'; + const configurationService = new TestConfigurationService({ [enablementSetting]: false }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(ICustomizationHarnessService, new class extends mock() { + override readonly activeHarness = constObservable(harnessId); + override readonly availableHarnesses = constObservable([upcastPartial({ id: harnessId, hiddenSections: [AICustomizationManagementSection.Agents] })]); + override findHarnessById(id: string) { + return this.availableHarnesses.get().find(harness => harness.id === id); + } + }); + instantiationService.stub(IAICustomizationWorkspaceService, new class extends mock() { + override readonly managementSections = [ + AICustomizationManagementSection.Agents, + AICustomizationManagementSection.Skills, + AICustomizationManagementSection.HarnessSettings, + AICustomizationManagementSection.Instructions, + ]; + }); + store.add(aiCustomizationManagementSectionRegistry.register({ + id: AICustomizationManagementSection.HarnessSettings, + label: 'Settings', + description: '', + icon: Codicon.settingsGear, + enablementSettings: [enablementSetting], + supportsHarness: id => id === harnessId, + create: () => ({ dispose() { } }), + })); + + const readBadges = new Set(); + const trackedBadge = (badge: string) => derived(() => { + readBadges.add(badge); + return badge; + }); + const skillsBadge = observableValue('skills', undefined); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.Agents, () => trackedBadge('hidden by harness'))); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.Prompts, () => trackedBadge('not a management section'))); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.Skills, () => skillsBadge)); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.HarnessSettings, () => trackedBadge('settings'))); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.Instructions, () => constObservable('instructions'), id => id === harnessId)); + store.add(aiCustomizationManagementSectionRegistry.registerBadge(AICustomizationManagementSection.Instructions, () => constObservable('other harness'), () => true)); + + const badges: (string | undefined)[] = []; + const badge = instantiationService.invokeFunction(observeVisibleSectionsBadge); + store.add(autorun(reader => { badges.push(badge.read(reader)); })); + const readWhileDisabled = [...readBadges]; + + configurationService.setUserConfiguration(enablementSetting, true); + configurationService.onDidChangeConfigurationEmitter.fire(upcastPartial({ affectsConfiguration: key => key === enablementSetting })); + skillsBadge.set('skills', undefined); + skillsBadge.set(undefined, undefined); + + assert.deepStrictEqual({ badges, readWhileDisabled, readBadges: [...readBadges] }, { + badges: ['instructions', 'settings', 'skills', 'settings'], + readWhileDisabled: [], + readBadges: ['settings'], + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/chatCustomizationsHover.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/chatCustomizationsHover.test.ts new file mode 100644 index 000000000000..3bd5ccc163bd --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/chatCustomizationsHover.test.ts @@ -0,0 +1,512 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; +import { constObservable, observableValue } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { McpServerStatus } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { IAICustomizationItemsModel } from '../../../browser/aiCustomization/aiCustomizationItemsModel.js'; +import { ChatCustomizationsActionViewItem, ChatCustomizationsHover } from '../../../browser/aiCustomization/chatCustomizationsHover.js'; +import { IAgentHostCustomizationService } from '../../../browser/agentSessions/agentHost/agentHostCustomizationService.js'; +import { AICustomizationManagementCommands, AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../../common/aiCustomizationWorkspaceService.js'; +import { ICustomizationHarnessService, IHarnessDescriptor } from '../../../common/customizationHarnessService.js'; +import { IMcpService } from '../../../../mcp/common/mcpTypes.js'; +import { McpCommandIds } from '../../../../mcp/common/mcpCommandIds.js'; +import { AgentHostMcpServer } from '../../../browser/aiCustomization/mcpServerCount.js'; +import { IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; +import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; +import { CustomizationMigrationState } from '../../../browser/aiCustomization/customizationMigrationState.js'; +import { MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { mainWindow } from '../../../../../../base/browser/window.js'; +import { renderMarkdown } from '../../../../../../base/browser/markdownRenderer.js'; +import { InMemoryStorageService } from '../../../../../../platform/storage/common/storage.js'; +import { CustomizationMigrationType, ICustomizationMigrationHint, ICustomizationMigrationService } from '../../../common/promptSyntax/service/customizationMigrationService.js'; +import { ChatCustomizationsTelemetry } from '../../../browser/aiCustomization/chatCustomizationsTelemetry.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ITelemetryData, ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryServiceShape } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IOpenerService, OpenOptions } from '../../../../../../platform/opener/common/opener.js'; +import { ChatConfiguration } from '../../../common/constants.js'; +import { ActionBar } from '../../../../../../base/browser/ui/actionbar/actionbar.js'; + +suite('Chat customizations hover', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const sessionResource = URI.parse('agent-host-copilotcli:/session'); + + function createHover(hiddenSections: string[] = [], loaded: Promise = Promise.resolve(), widgets: readonly IChatWidget[] = [], hasWorkspace = true, attention: { servers?: readonly AgentHostMcpServer[]; migration?: ICustomizationMigrationHint; isSessionsWindow?: boolean } = {}) { + const observed: string[] = []; + const scoped: string[] = []; + const events: { name: string; data?: ITelemetryData }[] = []; + const opened: { link: URI | string; options?: OpenOptions }[] = []; + const projectLabel = observableValue(store, hasWorkspace ? 'Project' : undefined); + const configurationService = new TestConfigurationService({ [ChatConfiguration.ChatCustomizationsLocation]: 'chatInput' }); + const telemetryService = new class extends NullTelemetryServiceShape { + override publicLog2(name?: string, data?: ITelemetryData): void { + if (name) { + events.push({ name, data }); + } + } + }(); + const instantiationService = workbenchInstantiationService({}, store); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(ITelemetryService, telemetryService); + instantiationService.stub(IAICustomizationWorkspaceService, new class extends mock() { + override readonly isSessionsWindow = attention.isSessionsWindow ?? false; + }()); + const openerService = new class extends mock() { + override async open(link: URI | string, options?: OpenOptions): Promise { + opened.push({ link, options }); + return true; + } + }(); + let scopeDisposed = false; + const hover = new ChatCustomizationsHover( + new class extends mock() { + override whenSectionLoaded(section: AICustomizationManagementSection) { + observed.push(section); + return loaded; + } + override getPluginCount() { return constObservable(4); } + override getCount(section: AICustomizationManagementSection) { return constObservable(section === AICustomizationManagementSection.Skills ? 12 : section === AICustomizationManagementSection.Hooks ? 2 : 3); } + override createSessionModel(resource: URI) { + scoped.push(resource.toString()); + return { + model: new class extends mock() { + override whenSectionLoaded() { return Promise.resolve(); } + override getPluginCount() { return constObservable(2); } + override getCount() { return constObservable(1); } + }, + dispose: () => { scopeDisposed = true; }, + }; + } + }, + new class extends mock() { + override readonly activeSessionResource = constObservable(sessionResource); + override getActiveDescriptor() { return upcastPartial({ label: 'Copilot', hiddenSections }); } + override getDescriptorForSession() { return upcastPartial({ label: 'Claude', hiddenSections }); } + }, + new class extends mock() { + override readonly activeProjectLabel = projectLabel; + override readonly activeProjectRoot = constObservable(hasWorkspace ? URI.file('/workspace') : undefined); + }, + new class extends mock() { + override readonly servers = constObservable([]); + }, + new class extends mock() { + override getClientWorkingDirectoryUris() { return [URI.file('/other-project')]; } + override getMcpServers() { + return attention.servers ?? [upcastPartial({ + id: 'session/server', name: 'Server', enabled: true, status: McpServerStatus.Ready, + })]; + } + }, + new class extends mock() { + override getAllWidgets() { return widgets; } + }, + new class extends mock() { + override async computeMigrationHint() { return attention.migration; } + }, + store.add(new InMemoryStorageService()), + instantiationService, + openerService, + ); + return { hover, observed, scoped, events, opened, projectLabel, configurationService, instantiationService, scopeDisposed: () => scopeDisposed }; + } + + test('unfocused widget counts and deep links use that widget without retargeting the active model', async () => { + const resource = URI.parse('agent-host-claude:/other-session'); + const widget = upcastPartial({ + input: upcastPartial({ pendingDelegationTarget: undefined }), + viewModel: upcastPartial>({ sessionResource: resource }), + }); + const { hover, observed, scoped, scopeDisposed } = createHover([], Promise.resolve(), [widget]); + const content = (await hover.getContent(CancellationToken.None, { widget }))!; + const rendered = store.add(renderMarkdown(content)).element; + const links = Array.from(rendered.querySelectorAll('a'), link => + JSON.parse(decodeURIComponent(link.dataset.href!.split('?')[1]))[0], + ).filter(target => typeof target === 'object'); + assert.deepStrictEqual({ + observed, scoped, disposed: scopeDisposed(), + context: rendered.querySelector('p:nth-of-type(2)')?.textContent?.replace(/\u00a0/g, ' '), + counts: [...rendered.querySelectorAll('tbody tr')].map(row => row.querySelector('td:last-child')?.textContent?.trim()), + targets: links.map(target => target.sessionResource), + }, { + observed: [], scoped: [resource.toString()], disposed: true, + context: 'Claude \u00b7 other-project', + counts: ['2', '1', '1', '1', '1'], + targets: Array(6).fill(resource.toJSON()), + }); + }); + + test('shows compact harness and workspace context as plain text, or only the harness without a workspace', async () => { + const summaries = []; + for (const label of ['Project', 'Project [Open](command:untrusted)', undefined]) { + const { hover, projectLabel } = createHover([], Promise.resolve(), [], label !== undefined); + projectLabel.set(label, undefined); + const content = (await hover.getContent(CancellationToken.None))!; + const rendered = store.add(renderMarkdown(content)).element; + const context = rendered.querySelector('p:nth-of-type(2)'); + summaries.push({ + title: rendered.querySelector('strong')?.textContent, + context: context?.textContent?.replace(/\u00a0/g, ' '), + nestedMarkup: context?.querySelectorAll('b, a').length, + order: [...rendered.children].map(element => element.tagName), + }); + } + assert.deepStrictEqual(summaries, [ + { title: 'Session Customizations', context: 'Copilot \u00b7 Project', nestedMarkup: 0, order: ['P', 'P', 'TABLE', 'HR', 'P'] }, + { title: 'Session Customizations', context: 'Copilot \u00b7 Project [Open](command:untrusted)', nestedMarkup: 0, order: ['P', 'P', 'TABLE', 'HR', 'P'] }, + { title: 'Session Customizations', context: 'Copilot', nestedMarkup: 0, order: ['P', 'P', 'TABLE', 'HR', 'P'] }, + ]); + }); + + test('new entry points retain migration and extension-suggestion indicators and accessible hints', () => { + const instantiationService = workbenchInstantiationService({}, store); + const migrations = observableValue(store, false); + const suggestions = observableValue(store, false); + instantiationService.stubInstance(CustomizationMigrationState, new class extends mock() { + override readonly available = migrations; + override dispose() { } + }); + const action = instantiationService.createInstance(MenuItemAction, { + id: 'test.customizations', title: 'Customizations', icon: Codicon.extensions, + }, undefined, undefined, undefined, undefined); + const item = store.add(instantiationService.createInstance(ChatCustomizationsActionViewItem, action, undefined, createHover().hover, 'chatInput', undefined, false, suggestions)); + const container = mainWindow.document.createElement('li'); + item.render(container); + const read = () => ({ badge: container.classList.contains('migration-available'), label: container.querySelector('.action-label')?.getAttribute('aria-label') }); + const initial = read(); + migrations.set(true, undefined); + const migration = read(); + migrations.set(false, undefined); + suggestions.set(true, undefined); + assert.deepStrictEqual({ initial, migration, suggestion: read() }, { + initial: { badge: false, label: 'Customizations' }, + migration: { badge: true, label: 'Customizations (Migrations Available)' }, + suggestion: { badge: true, label: 'Customizations (Extension Suggestions Available)' }, + }); + }); + + test('waits for discovery and links every count to its session-scoped page', async () => { + const loaded = new DeferredPromise(); + const { hover, observed } = createHover([], loaded.p); + let settled = false; + const pending = hover.getContent(CancellationToken.None).then(value => { + settled = true; + return value; + }); + await Promise.resolve(); + const beforeDiscovery = settled; + await loaded.complete(); + const content = (await pending)!; + const rendered = store.add(renderMarkdown(content)).element; + const links = Array.from(rendered.querySelectorAll('a'), link => { + const [command, argumentsString] = link.dataset.href!.slice('command:'.length).split('?'); + return { command, arguments: JSON.parse(decodeURIComponent(argumentsString)) }; + }); + assert.deepStrictEqual({ + beforeDiscovery, + observed, + rows: [...rendered.querySelectorAll('tbody tr')].map(row => ({ + label: row.querySelector('a')?.textContent?.trim(), + count: row.querySelector('td:last-child')?.textContent?.trim(), + detail: row.querySelector('em')?.textContent?.replace(/\u00a0/g, ' '), + hasIcon: !!row.querySelector('a .codicon'), + })), + links, + }, { + beforeDiscovery: false, + observed: ['plugins', 'skills', 'instructions', 'hooks'], + rows: [ + { label: 'Plugins', count: '4', detail: undefined, hasIcon: true }, + { label: 'MCP Servers', count: '1', detail: undefined, hasIcon: true }, + { label: 'Skills', count: '12', detail: undefined, hasIcon: true }, + { label: 'Instructions', count: '3', detail: undefined, hasIcon: true }, + { label: 'Hooks', count: '2', detail: undefined, hasIcon: true }, + ], + links: [ + ...['plugins', 'mcpServers', 'skills', 'instructions', 'hooks'].map(section => ({ + command: AICustomizationManagementCommands.OpenEditor, + arguments: [{ section, sessionResource: sessionResource.toJSON() }], + })), + { command: AICustomizationManagementCommands.OpenEditor, arguments: [{ showDiscover: true, sessionResource: sessionResource.toJSON() }] }, + { command: 'workbench.action.openSettings', arguments: ['chat.customizations.location'] }, + ], + }); + }); + + test('does not request counts until the managed hover is opened', async () => { + const { hover, observed } = createHover(); + const content = hover.getManagedContent(); + const beforeOpening = [...observed]; + assert.ok(typeof content.markdown === 'function'); + await content.markdown(CancellationToken.None); + assert.deepStrictEqual({ beforeOpening, afterOpening: observed }, { + beforeOpening: [], + afterOpening: ['plugins', 'skills', 'instructions', 'hooks'], + }); + }); + + test('logs visibility only after showing and deduplicates loading and resolved content', async () => { + const loaded = new DeferredPromise(); + const { hover, events } = createHover([], loaded.p); + const options = hover.getHoverOptions('chatInput'); + const content = hover.getManagedContent(); + assert.ok(typeof content.markdown === 'function'); + const firstToken = store.add(new CancellationTokenSource()); + const first = content.markdown(firstToken.token); + const beforeShown = [...events]; + options.onDidShow?.(); + await loaded.complete(); + await first; + options.onDidShow?.(); + firstToken.cancel(); + const secondToken = store.add(new CancellationTokenSource()); + await content.markdown(secondToken.token); + options.onDidShow?.(); + const dismissedToken = store.add(new CancellationTokenSource()); + await content.markdown(dismissedToken.token); + dismissedToken.cancel(); + options.onDidShow?.(); + assert.deepStrictEqual({ beforeShown, events }, { + beforeShown: [], + events: Array(2).fill({ + name: 'chatCustomizationEntryPoint.interaction', + data: { action: 'hoverShown', location: 'chatInput', configuredLocation: 'chatInput', windowKind: 'editor', target: 'none' }, + }), + }); + }); + + test('records one button activation for mouse and keyboard without counting other toolbar actions', async () => { + const { hover, events, instantiationService } = createHover(); + const action = instantiationService.createInstance(MenuItemAction, { + id: 'test.customizations', title: 'Customizations', + }, undefined, undefined, undefined, undefined); + const other = instantiationService.createInstance(MenuItemAction, { + id: 'test.other', title: 'Other', + }, undefined, undefined, undefined, undefined); + const container = mainWindow.document.createElement('div'); + const actionBar = store.add(new ActionBar(container, { + actionViewItemProvider: candidate => candidate === action + ? instantiationService.createInstance(ChatCustomizationsActionViewItem, action, undefined, hover, 'chatInput', constObservable(false), false, undefined) + : undefined, + })); + actionBar.push([action, other]); + container.querySelector('.action-label')!.click(); + await actionBar.run(other); + actionBar.focus(0); + actionBar.domNode.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + actionBar.domNode.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', keyCode: 13, bubbles: true })); + assert.deepStrictEqual(events, Array(2).fill({ + name: 'chatCustomizationEntryPoint.interaction', + data: { action: 'buttonClicked', location: 'chatInput', configuredLocation: 'chatInput', windowKind: 'editor', target: 'none' }, + })); + }); + + test('logs bounded hover action categories and preserves command trust and opener routing', async () => { + const { hover, events, opened } = createHover([], Promise.resolve(), [], true, { + isSessionsWindow: true, + servers: [upcastPartial({ id: 'secret-id', name: 'Private Server', enabled: true, status: McpServerStatus.AuthRequired })], + migration: { migrationFlowId: 'private-flow', message: '', counts: [{ type: CustomizationMigrationType.UserData, count: 1 }] }, + }); + const content = (await hover.getContent(CancellationToken.None))!; + const options = hover.getHoverOptions('sessionsHeader'); + const rendered = store.add(renderMarkdown(content, { actionHandler: link => options.linkHandler?.(link) })).element; + const links = [...rendered.querySelectorAll('a')]; + for (const link of links) { + link.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + } + const beforeUnknownLink = events.length; + options.linkHandler?.('command:notTrusted?private-data'); + assert.deepStrictEqual({ + events, + knownLinks: opened.slice(0, -1).map(entry => entry.link), + openerOptions: opened.at(-1)?.options, + unknownLinkLogged: events.length !== beforeUnknownLink, + }, { + events: ['plugins', 'mcpServers', 'skills', 'instructions', 'hooks', 'migrations', 'mcpServers', 'mcpAuthentication', 'browseAdditional', 'locationSetting'].map(target => ({ + name: 'chatCustomizationEntryPoint.interaction', + data: { action: 'hoverInteracted', location: 'sessionsHeader', configuredLocation: 'chatInput', windowKind: 'agents', target }, + })), + knownLinks: links.map(link => link.dataset.href), + openerOptions: { + fromUserGesture: true, allowContributedOpeners: true, + allowCommands: [AICustomizationManagementCommands.OpenEditor, McpCommandIds.AuthenticateAgentHostServer, 'workbench.action.openSettings'], + skipValidation: undefined, + }, + unknownLinkLogged: false, + }); + }); + + test('observes location updates without logging initialization, unchanged values, or experiment defaults', async () => { + const { configurationService, instantiationService, events } = createHover(); + const telemetry = instantiationService.createInstance(ChatCustomizationsTelemetry); + const observer = store.add(telemetry.observeLocationChanges()); + const update = async (value: string, source: ConfigurationTarget, key: string = ChatConfiguration.ChatCustomizationsLocation) => { + await configurationService.setUserConfiguration(key, value); + configurationService.onDidChangeConfigurationEmitter.fire({ + source, affectedKeys: new Set([key]), change: { keys: [key], overrides: [] }, + affectsConfiguration: candidate => candidate === key, + }); + }; + await update('chatInput', ConfigurationTarget.USER); + await update('sidebar', ConfigurationTarget.DEFAULT); + await update('chatToolbar', ConfigurationTarget.USER); + await update('auto', ConfigurationTarget.APPLICATION); + await update('private-value', ConfigurationTarget.USER); + await update('another-private-value', ConfigurationTarget.USER); + await update('private-other', ConfigurationTarget.USER, 'unrelated.setting'); + observer.dispose(); + await update('chatInput', ConfigurationTarget.USER); + assert.deepStrictEqual(events, [ + { previousLocation: 'sidebar', location: 'chatToolbar', windowKind: 'editor' }, + { previousLocation: 'chatToolbar', location: 'auto', windowKind: 'editor' }, + { previousLocation: 'auto', location: 'unknown', windowKind: 'editor' }, + ].map(data => ({ name: 'chatCustomizationEntryPoint.locationChanged', data }))); + }); + + test('category and footer links remain keyboard operable in the compact layout', async () => { + const { hover } = createHover(); + const content = (await hover.getContent(CancellationToken.None))!; + const opened: string[] = []; + const rendered = store.add(renderMarkdown(content, { actionHandler: href => opened.push(href) })).element; + const links = [...rendered.querySelectorAll('a')]; + for (const link of links) { + link.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + } + assert.deepStrictEqual({ + headers: [...rendered.querySelectorAll('th')].map(header => header.textContent), + footerLinks: [...rendered.querySelectorAll('hr + p a')].map(link => link.textContent?.trim().replace(/\u00a0/g, ' ')), + gearTooltip: links.at(-1)?.getAttribute('title'), + opened: opened.map(href => href.split('?')[0]), + }, { + headers: ['Type', 'Available'], + footerLinks: ['Browse Additional', 'Change Button Location...'], + gearTooltip: 'Change Button Location...', + opened: [ + ...Array(6).fill(`command:${AICustomizationManagementCommands.OpenEditor}`), + 'command:workbench.action.openSettings', + ], + }); + }); + + test('does not fetch or advertise sections hidden by the harness', async () => { + const { hover, observed } = createHover(['plugins', 'mcpServers', 'skills', 'hooks']); + const content = (await hover.getContent(CancellationToken.None))!; + assert.deepStrictEqual({ + observed, + hasPlugins: content.value.includes('Plugins'), + hasMcp: content.value.includes('MCP Servers'), + hasSkills: content.value.includes('Skills'), + hasInstructions: content.value.includes('Instructions') && content.value.includes('| 3 |'), + }, { observed: ['instructions'], hasPlugins: false, hasMcp: false, hasSkills: false, hasInstructions: true }); + }); + + test('puts actionable migration and authentication details below the inventory and above the footer', async () => { + const servers = ['GitHub', 'Figma', 'Third', 'Fourth'].map(name => upcastPartial({ + id: `session/${name}`, name, enabled: true, status: McpServerStatus.AuthRequired, + })); + const migration: ICustomizationMigrationHint = { + migrationFlowId: 'flow', + message: 'Migrations available', + counts: [{ type: CustomizationMigrationType.UserData, count: 2 }, { type: CustomizationMigrationType.PromptFiles, count: 1 }], + }; + const { hover } = createHover([], Promise.resolve(), [], true, { servers, migration }); + const content = (await hover.getContent(CancellationToken.None))!; + const rendered = store.add(renderMarkdown(content)).element; + const attentionLinks = [...rendered.querySelectorAll('ul a')]; + const targets = attentionLinks.map(link => JSON.parse(decodeURIComponent(link.getAttribute('data-href')!.split('?')[1]))); + assert.deepStrictEqual({ + order: [...rendered.children].map(element => element.tagName), + attentionHeading: [...rendered.querySelectorAll('strong')].at(-1)?.textContent, + entries: attentionLinks.map(link => link.textContent?.trim().replace(/\u00a0/g, ' ')), + targets, + inventoryDetails: rendered.querySelectorAll('td em').length, + }, { + order: ['P', 'P', 'TABLE', 'P', 'UL', 'HR', 'P'], + attentionHeading: 'Needs attention', + entries: ['3 customizations need migration', '4 MCP servers require sign-in', 'GitHub', 'Figma'], + targets: [ + [{ migration: true, sessionResource: sessionResource.toJSON(), migrationHint: migration }], + [{ section: AICustomizationManagementSection.McpServers, sessionResource: sessionResource.toJSON() }], + [sessionResource.toJSON(), 'session/GitHub'], + [sessionResource.toJSON(), 'session/Figma'], + ], + inventoryDetails: 0, + }); + }); + + test('omits attention when nothing needs action and does not advertise hidden MCP authentication', async () => { + const states = []; + for (const hidden of [[], [AICustomizationManagementSection.McpServers]]) { + const { hover } = createHover(hidden, Promise.resolve(), [], true, hidden.length ? { + servers: [upcastPartial({ id: 'auth', name: 'Hidden', enabled: true, status: McpServerStatus.AuthRequired })], + } : {}); + const content = (await hover.getContent(CancellationToken.None))!; + const rendered = store.add(renderMarkdown(content)).element; + states.push({ attention: rendered.querySelectorAll('ul').length, hasFooter: !!rendered.querySelector('hr + p') }); + } + assert.deepStrictEqual(states, [{ attention: 0, hasFooter: true }, { attention: 0, hasFooter: true }]); + }); + + test('formats a single authentication request without interpreting server names as markup', async () => { + const name = 'GitHub [Sign In](command:untrusted)'; + const { hover } = createHover([], Promise.resolve(), [], true, { + servers: [upcastPartial({ id: 'auth', name, enabled: true, status: McpServerStatus.AuthRequired })], + }); + const content = (await hover.getContent(CancellationToken.None))!; + const rendered = store.add(renderMarkdown(content)).element; + assert.deepStrictEqual({ + text: rendered.querySelector('li')?.textContent?.replace(/\u00a0/g, ' ').trim(), + serverName: rendered.querySelector('li em a')?.textContent?.replace(/\u00a0/g, ' '), + links: rendered.querySelectorAll('li a').length, + nestedMarkup: rendered.querySelectorAll('li b').length, + }, { text: `1 MCP server requires sign-in ${name}`, serverName: name, links: 2, nestedMarkup: 0 }); + }); + + test('server-name links support keyboard sign-in for the originating, unfocused session', async () => { + const resource = URI.parse('agent-host-copilotcli://remote-host/other-session'); + const serverId = 'plugin/server?&"]'; + const { hover } = createHover([], Promise.resolve(), [], true, { + servers: [upcastPartial({ + id: serverId, name: 'internal-name', displayName: 'GitHub', enabled: true, status: McpServerStatus.AuthRequired, + })], + }); + const content = (await hover.getContent(CancellationToken.None, { sessionResource: resource }))!; + const opened: string[] = []; + const rendered = store.add(renderMarkdown(content, { actionHandler: href => opened.push(href) })).element; + const link = rendered.querySelector('li em a')!; + link.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + assert.deepStrictEqual({ + label: link.textContent?.replace(/\u00a0/g, ' '), + tooltip: link.title, + commands: opened.map(href => href.split('?')[0]), + arguments: opened.map(href => JSON.parse(decodeURIComponent(href.split('?')[1]))), + trusted: typeof content.isTrusted === 'object' && content.isTrusted.enabledCommands?.includes(McpCommandIds.AuthenticateAgentHostServer), + }, { + label: 'GitHub (Connector)', + tooltip: 'Sign In to GitHub (Connector)', + commands: [`command:${McpCommandIds.AuthenticateAgentHostServer}`], + arguments: [[resource.toJSON(), serverId]], + trusted: true, + }); + }); + + test('does not publish a dismissed hover after discovery finishes', async () => { + const loaded = new DeferredPromise(); + const token = store.add(new CancellationTokenSource()); + const { hover } = createHover([], loaded.p); + const pending = hover.getContent(token.token); + token.cancel(); + await loaded.complete(); + assert.strictEqual(await pending, undefined); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationOrganizationPolicy.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationOrganizationPolicy.test.ts new file mode 100644 index 000000000000..3acd4febd4d6 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationOrganizationPolicy.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 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IConfigurationService, IConfigurationValue } from '../../../../../../platform/configuration/common/configuration.js'; +import { mcpAllowedServersConfig } from '../../../../../../platform/mcp/common/mcpManagement.js'; +import { COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG, COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG, COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; +import { getCustomizationOrganizationRestriction } from '../../../browser/aiCustomization/customizationOrganizationPolicy.js'; +import { AICustomizationManagementSection } from '../../../common/aiCustomizationWorkspaceService.js'; + +suite('customizationOrganizationPolicy', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + function restrictions(values: { readonly policy?: Record; readonly user?: Record }) { + const configurationService: Pick = { + inspect: (key: string) => ({ policyValue: values.policy?.[key], userValue: values.user?.[key], value: values.policy?.[key] ?? values.user?.[key] }) as IConfigurationValue, + }; + return Object.fromEntries([ + AICustomizationManagementSection.Skills, + AICustomizationManagementSection.Agents, + AICustomizationManagementSection.Instructions, + AICustomizationManagementSection.Hooks, + AICustomizationManagementSection.McpServers, + AICustomizationManagementSection.Plugins, + ].map(section => [section, getCustomizationOrganizationRestriction(configurationService, section)])); + } + + test('derives section restrictions from organization policy only', () => { + const allowlist = [{ serverName: 'approved' }]; + assert.deepStrictEqual({ + none: restrictions({}), + userSettingsOnly: restrictions({ user: { [COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG]: true, [COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG]: true, [mcpAllowedServersConfig]: allowlist } }), + pluginOnly: restrictions({ policy: { [COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG]: true, [COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG]: true } }), + managedHooksOverPluginOnly: restrictions({ policy: { [COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG]: true, [COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG]: true } }), + managedMcpOverAllowlist: restrictions({ policy: { [COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG]: true, [mcpAllowedServersConfig]: allowlist } }), + emptyAllowlist: restrictions({ policy: { [mcpAllowedServersConfig]: [] } }), + }, { + none: { skills: undefined, agents: undefined, instructions: undefined, hooks: undefined, mcpServers: undefined, plugins: undefined }, + userSettingsOnly: { skills: undefined, agents: undefined, instructions: undefined, hooks: undefined, mcpServers: undefined, plugins: undefined }, + pluginOnly: { skills: 'pluginOnly', agents: 'pluginOnly', instructions: 'pluginOnly', hooks: 'pluginOnly', mcpServers: 'pluginOnly', plugins: undefined }, + managedHooksOverPluginOnly: { skills: 'pluginOnly', agents: 'pluginOnly', instructions: 'pluginOnly', hooks: 'organizationOnly', mcpServers: 'pluginOnly', plugins: undefined }, + managedMcpOverAllowlist: { skills: undefined, agents: undefined, instructions: undefined, hooks: undefined, mcpServers: 'organizationOnly', plugins: undefined }, + emptyAllowlist: { skills: undefined, agents: undefined, instructions: undefined, hooks: undefined, mcpServers: 'allowlist', plugins: undefined }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts index 391b8e190984..98ba9108bc53 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts @@ -7,7 +7,7 @@ import assert from 'assert'; import * as DOM from '../../../../../../base/browser/dom.js'; import { Button, unthemedButtonStyles } from '../../../../../../base/browser/ui/button/button.js'; import { DeferredPromise } from '../../../../../../base/common/async.js'; -import { CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; import { URI } from '../../../../../../base/common/uri.js'; import { Action, IAction, Separator } from '../../../../../../base/common/actions.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; @@ -33,8 +33,9 @@ import { IThemeService } from '../../../../../../platform/theme/common/themeServ import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; -import { mcpAccessConfig, McpAccessValue } from '../../../../../../platform/mcp/common/mcpManagement.js'; +import { mcpAccessConfig, McpAccessValue, mcpGalleryServiceEnablementConfig, mcpGalleryServiceUrlConfig } from '../../../../../../platform/mcp/common/mcpManagement.js'; import { McpServerType } from '../../../../../../platform/mcp/common/mcpPlatformTypes.js'; +import { IProductService } from '../../../../../../platform/product/common/productService.js'; import { IExtensionsWorkbenchService } from '../../../../extensions/common/extensions.js'; import { IAuthenticationQueryService } from '../../../../../services/authentication/common/authenticationQuery.js'; import { IAuthenticationService } from '../../../../../services/authentication/common/authentication.js'; @@ -83,11 +84,12 @@ import { hasSameMcpMembership, preserveMcpEntryOrder, shouldLoadMcpGallerySnapshot, + shouldRestartLegacyMcpGallerySearch, shouldShowLegacyMcpGallery, setPrimaryMcpServerEnablement, } from '../../../browser/aiCustomization/mcpListWidget.js'; import { registerMcpInlineButtonAction, registerMcpSignInButtonAction, renderMcpServerSignInButton } from '../../../browser/aiCustomization/mcpServerSignInButton.js'; -import { ActiveSessionMcpServerMatcher, getEffectiveMcpServerCount, getRuntimeServerMatchKeys } from '../../../browser/aiCustomization/mcpServerCount.js'; +import { ActiveSessionMcpServerMatcher, getEffectiveMcpServerCount, getEffectiveMcpServerCounts, getRuntimeServerMatchKeys } from '../../../browser/aiCustomization/mcpServerCount.js'; import { ICopilotConnector, ICopilotConnectorsService } from '../../../browser/aiCustomization/copilotConnectorsService.js'; import { CustomizationCardListController } from '../../../browser/aiCustomization/customizationCardList.js'; import { IWorkspaceContextService, IWorkspaceFolder } from '../../../../../../platform/workspace/common/workspace.js'; @@ -190,6 +192,7 @@ type McpAccessTestWidget = { access: McpAccessValue; policyAccess: McpAccessValue | undefined; configurationService: IConfigurationService; + productService: IProductService; connectorsCancellation: MutableDisposable<{ cancel(): void; dispose(): void }>; connectorActionCancellation: MutableDisposable; connectorsCancelCount: number; @@ -227,15 +230,18 @@ function createMcpAccessTestWidget(access: McpAccessValue, policyAccess: McpAcce widget.configurationService = { getValue: (key: string) => key === CustomizationMarketplaceConfiguration.MarketplaceEnabled ? galleryDiscoveryEnabled - : key === CustomizationMarketplaceConfiguration.CopilotConnectorsEnabled - ? connectorsEnabled - : undefined, + : key === mcpGalleryServiceEnablementConfig + ? true + : key === CustomizationMarketplaceConfiguration.CopilotConnectorsEnabled + ? connectorsEnabled + : undefined, inspect: (key: string) => key === mcpAccessConfig ? { value: widget.access, defaultValue: McpAccessValue.All, policyValue: widget.policyAccess, } : undefined, } as unknown as IConfigurationService; + widget.productService = {} as IProductService; widget.connectorsCancelCount = 0; widget.connectorsCancellation = store.add(new MutableDisposable()); widget.connectorActionCancellation = store.add(new MutableDisposable()); @@ -363,6 +369,50 @@ suite('mcpListWidget', () => { }); }); + test('identifies a Connector row by its server name rather than its display label', () => { + const connectorEntry = { + type: 'connector-item' as const, + id: 'copilot-connector:mail:mail-mcp', + label: 'Mail', + description: 'Connector', + connector: { + id: 'mail:mail-mcp', + connector: { name: 'mail', displayName: 'Mail' }, + serverName: 'mail-mcp', + }, + }; + const calls: string[] = []; + const widget = Object.assign(Object.create(McpListWidget.prototype), { + searchQuery: '', + installedEntries: [{ entry: connectorEntry }], + galleryServers: [ + { id: 'mail-mcp', name: 'mail-mcp', label: 'mail-mcp', installState: McpServerInstallState.Uninstalled }, + { id: 'other-mcp', name: 'other-mcp', label: 'Other', installState: McpServerInstallState.Uninstalled }, + ], + currentTreeGroups: [{ + element: { type: 'group-header' }, + children: [connectorEntry], + }], + list: { + getParentElement: () => null, + reveal: () => calls.push('reveal'), + setFocus: () => calls.push('focus'), + setSelection: () => calls.push('select'), + domFocus: () => calls.push('dom-focus'), + }, + }) as Pick & { getAvailableGalleryServers(): IWorkbenchMcpServer[] }; + + assert.deepStrictEqual({ + available: widget.getAvailableGalleryServers().map(server => server.id), + revealed: widget.revealAndSelectServer(undefined, 'mail-mcp'), + calls, + }, { + available: ['other-mcp'], + revealed: true, + calls: ['reveal', 'focus', 'select', 'dom-focus'], + }); + }); + test('routes only an exactly recorded MCP uninstall through the marketplace', async () => { const resource: ICustomizationMarketplaceResource = { sourceId: 'testSource', @@ -633,7 +683,10 @@ suite('mcpListWidget', () => { }, }, installedEntries: entries.map(entry => ({ entry })), + collapsedGroups: new Set(), + searchQuery: '', isGalleryDiscoveryEnabled: () => true, + shouldShowLegacyGallery: () => false, getAvailableGalleryServers: () => [], cardScrollableNode: document.createElement('div'), cardDisposables: { clear() { } }, @@ -663,6 +716,49 @@ suite('mcpListWidget', () => { }); }); + test('keeps collapsed groups collapsed when the server list changes', () => { + const localEntry = (id: string, scope: LocalMcpServerScope): IMcpInstalledEntry => ({ + type: 'server-item', + server: { id, local: { scope } as IWorkbenchLocalMcpServer } as IWorkbenchMcpServer, + }); + type TreeNode = { readonly element: { readonly type: string; readonly label?: string }; readonly collapsed?: unknown; readonly children?: readonly unknown[] }; + const renders: (readonly TreeNode[] | undefined)[] = []; + const widget = Object.assign(Object.create(McpListWidget.prototype), { + list: { setChildren: (_input: null, children?: readonly TreeNode[]) => renders.push(children) }, + installedEntries: [localEntry('workspace-one', LocalMcpServerScope.Workspace), localEntry('user-one', LocalMcpServerScope.User)].map(entry => ({ entry })), + collapsedGroups: new Set(['user']), + searchQuery: '', + isGalleryDiscoveryEnabled: () => true, + shouldShowLegacyGallery: () => false, + getAvailableGalleryServers: () => [], + cardScrollableNode: document.createElement('div'), + cardDisposables: { clear() { } }, + updateMcpTreeEmptyState: () => { }, + workspaceContextService: new class extends mock() { + override getWorkspace() { + return testIWorkspace({ id: 'test', folders: [] }); + } + }(), + }); + const renderMcpTree = Reflect.get(McpListWidget.prototype, 'renderMcpTree') as (this: object) => void; + const describeRenders = () => renders.splice(0).map(children => children?.map(child => `${child.element.label} (${child.children?.length}) ${child.collapsed ? 'collapsed' : 'expanded'}`)); + + renderMcpTree.call(widget); + const initial = describeRenders(); + widget.installedEntries = [...widget.installedEntries, { entry: localEntry('user-two', LocalMcpServerScope.User) }]; + renderMcpTree.call(widget); + const afterServerAdded = describeRenders(); + widget.searchQuery = 'one'; + renderMcpTree.call(widget); + const whileSearching = describeRenders(); + + assert.deepStrictEqual({ initial, afterServerAdded, whileSearching }, { + initial: [['Workspace (1) expanded', 'User (1) collapsed']], + afterServerAdded: [['Workspace (1) expanded', 'User (2) collapsed']], + whileSearching: [['Workspace (1) expanded', 'User (2) expanded']], + }); + }); + test('splits workspace MCP sections in multi-root workspaces', () => { const firstUri = URI.file('/workspace/first'); const secondUri = URI.file('/workspace/second'); @@ -688,7 +784,10 @@ suite('mcpListWidget', () => { const widget = Object.assign(Object.create(McpListWidget.prototype), { list: { setChildren: (_input: null, children?: readonly TreeNode[]) => renderedChildren = children ?? [] }, installedEntries: [createEntry('first', folders[0]), createEntry('second', folders[1])].map(entry => ({ entry })), + collapsedGroups: new Set(), + searchQuery: '', isGalleryDiscoveryEnabled: () => true, + shouldShowLegacyGallery: () => false, getAvailableGalleryServers: () => [], cardScrollableNode: document.createElement('div'), cardDisposables: { clear() { } }, @@ -868,6 +967,20 @@ suite('mcpListWidget', () => { assert.strictEqual(count.get(), 1); }); + test('authentication count excludes disabled and silently authenticating MCP servers', () => { + const servers = [ + createAgentHostServer({ id: 'auth', name: 'auth', status: McpServerStatus.AuthRequired }), + createAgentHostServer({ id: 'ready', name: 'ready' }), + createAgentHostServer({ id: 'silent', name: 'silent', status: McpServerStatus.AuthRequired, authenticating: true }), + createAgentHostServer({ id: 'disabled', name: 'disabled', status: McpServerStatus.AuthRequired, enabled: false }), + createAgentHostServer({ id: 'plugin-disabled', name: 'plugin-disabled', status: McpServerStatus.AuthRequired, disabledReason: { source: 'plugin', plugin: { id: 'p', name: 'p', uri: 'file:///p', enablement: [{ kind: CustomizationEnablementKind.Global, enabled: false }] } } }), + ]; + const counts = getEffectiveMcpServerCounts([], servers, undefined, undefined); + assert.deepStrictEqual({ ...counts, authRequiredServers: counts.authRequiredServers.map(server => server.id) }, { + total: 3, authRequired: 1, authRequiredServers: ['auth'], + }); + }); + test('one native publication per source matches local rows and preserves disabled counts', () => { const names = ['automation', 'explorer']; const localServers = names.map(name => new class extends mock() { @@ -1070,6 +1183,7 @@ suite('mcpListWidget', () => { searchQuery: 'shared', mcpAccessEnabled: true, isGalleryDiscoveryEnabled: () => false, + shouldShowLegacyGallery: () => true, queryLegacyGallery: () => result.p, renderFilteredServers: () => { }, }); @@ -1391,16 +1505,95 @@ suite('mcpListWidget', () => { ], [false, true, false, false, false]); }); - test('legacy Available retains the MCP Gallery until Marketplace visibility is enabled', () => { - const configuration = (enabled: boolean | undefined) => ({ - getValue: () => enabled, + test('legacy Available respects MCP gallery configuration until Marketplace visibility is enabled', () => { + const productService = { + mcpGallery: { serviceUrl: 'https://default.test' }, + } as IProductService; + const configuration = (marketplaceEnabled: boolean | undefined, galleryEnabled: boolean | undefined, serviceUrl?: string) => ({ + getValue: (key: string) => key === CustomizationMarketplaceConfiguration.MarketplaceEnabled + ? marketplaceEnabled + : key === mcpGalleryServiceEnablementConfig + ? galleryEnabled + : key === mcpGalleryServiceUrlConfig + ? serviceUrl + : undefined, }) as unknown as IConfigurationService; assert.deepStrictEqual( - [undefined, false, true].map(enabled => shouldShowLegacyMcpGallery(configuration(enabled))), - [true, true, false], + [ + shouldShowLegacyMcpGallery(configuration(undefined, false), productService), + shouldShowLegacyMcpGallery(configuration(undefined, undefined), productService), + shouldShowLegacyMcpGallery(configuration(false, true), productService), + shouldShowLegacyMcpGallery(configuration(false, false, 'https://custom.test'), productService), + shouldShowLegacyMcpGallery(configuration(false, false, 'https://default.test/'), productService), + shouldShowLegacyMcpGallery(configuration(true, true), productService), + ], + [false, true, true, true, false, false], ); }); + test('restarts active legacy gallery searches after configuration changes', () => { + assert.deepStrictEqual([ + shouldRestartLegacyMcpGallerySearch('', true), + shouldRestartLegacyMcpGallerySearch(' ', true), + shouldRestartLegacyMcpGallerySearch('enterprise', false), + shouldRestartLegacyMcpGallerySearch('enterprise', true), + ], [false, false, false, true]); + }); + + test('legacy gallery queries enabled default and configured custom registries independently', async () => { + const productService = { + mcpGallery: { serviceUrl: 'https://default.test' }, + } as IProductService; + const queryLegacyGallery = Reflect.get(McpListWidget.prototype, 'queryLegacyGallery') as (this: object, options: undefined, token: CancellationToken) => Promise; + const run = async (galleryEnabled: boolean, serviceUrl?: string) => { + const manifestCalls: string[] = []; + const queryCalls: string[] = []; + const widget = Object.assign(Object.create(McpListWidget.prototype), { + productService, + configurationService: { + getValue: (key: string) => key === mcpGalleryServiceEnablementConfig + ? galleryEnabled + : key === mcpGalleryServiceUrlConfig + ? serviceUrl + : undefined, + }, + mcpGalleryManifestService: { + getMcpGalleryManifest: async () => { + manifestCalls.push('custom'); + return { url: 'https://custom.test' }; + }, + getDefaultMcpGalleryManifest: async () => { + manifestCalls.push('default'); + return { url: 'https://default.test' }; + }, + }, + mcpWorkbenchService: { + queryGallery: async (_options: undefined, _token: CancellationToken, manifest: { url: string }) => { + queryCalls.push(manifest.url); + return { firstPage: { items: [] } }; + }, + }, + }); + const cancellation = disposables.add(new CancellationTokenSource()); + await queryLegacyGallery.call(widget, undefined, cancellation.token); + return { manifestCalls, queryCalls }; + }; + + assert.deepStrictEqual({ + disabled: await run(false), + default: await run(true), + custom: await run(false, 'https://custom.test'), + both: await run(true, 'https://custom.test'), + defaultConfigured: await run(false, 'https://default.test/'), + }, { + disabled: { manifestCalls: [], queryCalls: [] }, + default: { manifestCalls: ['default'], queryCalls: ['https://default.test'] }, + custom: { manifestCalls: ['custom'], queryCalls: ['https://custom.test'] }, + both: { manifestCalls: ['custom', 'default'], queryCalls: ['https://custom.test', 'https://default.test'] }, + defaultConfigured: { manifestCalls: [], queryCalls: [] }, + }); + }); + test('does not restart management gallery search when Discover owns MCP discovery', () => { const widget = createMcpAccessTestWidget(McpAccessValue.None, undefined, disposables, true); widget.searchQuery = 'server'; diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/pluginListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/pluginListWidget.test.ts index 3fa5de11b3f4..f611ef105f2a 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/pluginListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/pluginListWidget.test.ts @@ -90,6 +90,58 @@ suite('pluginListWidget', () => { }); }); + test('keeps collapsed groups collapsed when the plugin list changes', () => { + const createItem = (name: string, state: ContributionEnablementState): IInstalledPluginItem => { + const plugin = new class extends mock() { + override readonly uri = URI.file(`/plugins/${name}`); + override readonly label = name; + override readonly enablement = constObservable(state); + }(); + return { kind: AgentPluginItemKind.Installed, name, description: '', plugin }; + }; + type TreeNode = { readonly element: { readonly type: string; readonly label?: string }; readonly collapsed?: unknown; readonly children?: readonly unknown[] }; + const renders: (readonly TreeNode[] | undefined)[] = []; + const widget = Object.assign(Object.create(PluginListWidget.prototype), { + list: { setChildren: (_input: null, children?: readonly TreeNode[]) => renders.push(children) }, + installedItems: [createItem('workspace-one', ContributionEnablementState.EnabledWorkspace), createItem('user-one', ContributionEnablementState.EnabledProfile)], + remoteItems: [], + marketplaceItems: [], + marketplaceSnapshot: new PluginMarketplaceSnapshotModel(), + searchQuery: '', + browseMode: false, + collapsedGroups: new Set(['user']), + configurationService: new TestConfigurationService({ [CustomizationMarketplaceConfiguration.MarketplaceEnabled]: true }), + cardScrollableNode: document.createElement('div'), + updateToolbarActions: () => { }, + updatePluginTreeEmptyState: () => { }, + workspaceContextService: new class extends mock() { + override getWorkspace() { return testIWorkspace({ id: 'test', folders: [] }); } + }(), + }); + const renderPluginTree = Reflect.get(PluginListWidget.prototype, 'renderPluginTree') as (this: object) => void; + const describeRenders = () => renders.splice(0).map(children => children?.map(child => `${child.element.label} (${child.children?.length}) ${child.collapsed ? 'collapsed' : 'expanded'}`)); + + renderPluginTree.call(widget); + const initial = describeRenders(); + widget.installedItems = [...widget.installedItems, createItem('user-two', ContributionEnablementState.EnabledProfile)]; + renderPluginTree.call(widget); + const afterPluginAdded = describeRenders(); + widget.searchQuery = 'one'; + renderPluginTree.call(widget); + const whileSearching = describeRenders(); + widget.searchQuery = ''; + widget.browseMode = true; + renderPluginTree.call(widget); + const whileBrowsing = describeRenders(); + + assert.deepStrictEqual({ initial, afterPluginAdded, whileSearching, whileBrowsing }, { + initial: [['Workspace (1) expanded', 'User (1) collapsed']], + afterPluginAdded: [['Workspace (1) expanded', 'User (2) collapsed']], + whileSearching: [['Workspace (1) expanded', 'User (2) expanded']], + whileBrowsing: [['Workspace (1) expanded', 'User (2) expanded']], + }); + }); + test('renders Workspace before User even when User has no plugins', () => { const createItem = (name: string, state: ContributionEnablementState): IInstalledPluginItem => { const plugin = new class extends mock() { @@ -114,6 +166,7 @@ suite('pluginListWidget', () => { marketplaceSnapshot: new PluginMarketplaceSnapshotModel(), searchQuery: '', browseMode: false, + collapsedGroups: new Set(), configurationService: new TestConfigurationService({ [CustomizationMarketplaceConfiguration.MarketplaceEnabled]: true, }), @@ -169,10 +222,12 @@ suite('pluginListWidget', () => { assert.deepStrictEqual([ widget.getPluginEntryAriaLabel({ type: 'remote-item', item }), widget.getPluginEntryAriaLabel({ type: 'remote-item', item: { ...item, status: 'loaded' } }), + widget.getPluginEntryAriaLabel({ type: 'remote-item', item: { ...item, status: 'error', statusMessage: 'Invalid plugin manifest' } }), widget.getPluginEntryAriaLabel({ type: 'remote-item', item: { ...item, origin: { kind: 'account', label: 'contoso' } } }), ], [ 'host-plugin. Agent host', 'host-plugin. Agent host. Status: Loaded', + 'host-plugin. Agent host. Status: Error: Invalid plugin manifest', 'host-plugin. Organization: contoso. Agent host', ]); }); @@ -205,6 +260,7 @@ suite('pluginListWidget', () => { marketplaceSnapshot: new PluginMarketplaceSnapshotModel(), searchQuery: '', browseMode: false, + collapsedGroups: new Set(), configurationService: new TestConfigurationService({ [CustomizationMarketplaceConfiguration.MarketplaceEnabled]: true }), cardScrollableNode: document.createElement('div'), updateToolbarActions: () => { }, diff --git a/src/vs/workbench/contrib/chat/test/browser/chatConfiguration.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatConfiguration.test.ts index 130485ccbbdb..ab5d4d6f1492 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatConfiguration.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatConfiguration.test.ts @@ -15,6 +15,9 @@ import { IConfigurationService, IConfigurationValue } from '../../../../../platf import { chatProgressConfigurationProperties, legacyChatThinkingConfigurationProperties } from '../../browser/chatProgressConfiguration.js'; import { customizationMarketplaceConfigurationProperties, isAgentFinderPublicFeedAvailable, isCustomizationMarketplaceValueFromDefault } from '../../browser/aiCustomization/customizationMarketplaceConfiguration.js'; import { AgentHostCopilotPolicyHelperSettingId, CopilotCliConfigKey, CopilotImageGenerationEnabledSettingId, CopilotImageGenerationModelSettingId } from '../../../../../platform/agentHost/common/copilotCliConfig.js'; +import { AgentHostConfigurationSyncTarget, resolveAgentHostConfigurationSyncPatch } from '../../../../../platform/agentHost/common/agentHostConfigurationSync.js'; +import { AgentHostCopilotM365EnabledSettingId } from '../../../../../platform/chat/common/chatSettings.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import '../../browser/agentSessionsConfiguration.js'; import { copilotPolicyHelperConfigurationProperties } from '../../browser/copilotPolicyHelperConfiguration.js'; import { IPluginMarketplaceService } from '../../common/plugins/pluginMarketplaceService.js'; @@ -25,6 +28,7 @@ const registeredAgentSessionsSettings = [ ChatConfiguration.AutoDeleteMarkedAsDoneMergedSessionsAfterDays, ].map(key => configurationProperties[key] !== undefined); const agentsPickerSetting = configurationProperties[ChatConfiguration.AgentsPickerInAttachContextMenu]; +const copilotM365Setting = configurationProperties[AgentHostCopilotM365EnabledSettingId]; const migrations = Registry.as(WorkbenchConfigurationExtensions.ConfigurationMigration).migrations; const legacyAutoArchiveMigration = migrations.find(migration => migration.key === 'chat.agentSessions.autoArchiveMergedSessionsAfterDays'); const legacyAutoDeleteArchivedMigration = migrations.find(migration => migration.key === 'chat.agentSessions.autoDeleteArchivedMergedSessionsAfterDays'); @@ -86,6 +90,49 @@ suite('Chat configuration', () => { assert.deepStrictEqual(registeredAgentSessionsSettings, [true, true]); }); + test('registers one default-off, restart-required Copilot M365 rollout setting', () => { + assert.deepStrictEqual({ + keys: Object.keys(configurationProperties).filter(key => key.startsWith('chat.agentHost.copilot.m365.')), + type: copilotM365Setting.type, + default: copilotM365Setting.default, + scope: copilotM365Setting.scope, + tags: copilotM365Setting.tags?.filter(tag => tag !== 'onExP'), + experiment: copilotM365Setting.experiment, + treatment: getConfigurationExperimentName(AgentHostCopilotM365EnabledSettingId, copilotM365Setting.experiment!), + restartRequired: copilotM365Setting.markdownDescription?.includes('requires restarting VS Code'), + agentHost: copilotM365Setting.agentHost, + policy: copilotM365Setting.policy, + }, { + keys: ['chat.agentHost.copilot.m365.enabled'], + type: 'boolean', + default: false, + scope: ConfigurationScope.APPLICATION, + tags: ['experimental', 'advanced'], + experiment: { mode: 'startup' }, + treatment: 'config.chat.agentHost.copilot.m365.enabled', + restartRequired: true, + agentHost: { key: CopilotCliConfigKey.M365Enabled }, + policy: undefined, + }); + }); + + test('mirrors the configured Copilot M365 flag to Agent Host root configuration', () => { + const targets = [ + AgentHostConfigurationSyncTarget.Local, + AgentHostConfigurationSyncTarget.RemoteExtensionHost, + AgentHostConfigurationSyncTarget.Remote, + ]; + assert.deepStrictEqual([undefined, true, false, 'invalid'].map(value => { + const configurationService = new TestConfigurationService({ [AgentHostCopilotM365EnabledSettingId]: value }); + return targets.map(target => resolveAgentHostConfigurationSyncPatch(configurationService, target)[CopilotCliConfigKey.M365Enabled]); + }), [ + [false, false, false], + [true, true, true], + [false, false, false], + [false, false, false], + ]); + }); + test('registers the existing Agent picker setting for both editor and Agents windows', () => { assert.deepStrictEqual({ key: ChatConfiguration.AgentsPickerInAttachContextMenu, diff --git a/src/vs/workbench/contrib/chat/test/browser/chatContinueInCopilotAction.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatContinueInCopilotAction.test.ts index ae144461fb9c..885567c19296 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatContinueInCopilotAction.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatContinueInCopilotAction.test.ts @@ -23,6 +23,10 @@ import { IManagedSettingsService } from '../../../../../platform/policy/common/c import { IEditorService } from '../../../../services/editor/common/editorService.js'; import { IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { IViewDescriptorService } from '../../../../common/views.js'; +import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; +import { IChatViewHostService } from '../../browser/chatViewHost.js'; +import { ChatViewHostService } from '../../browser/widgetHosts/viewPane/chatViewHostService.js'; import { ContinueChatInCopilotAction } from '../../browser/actions/chatContinueInAction.js'; import { AgentHostImportConversationStore, IAgentHostImportConversation, IAgentHostImportConversationStore } from '../../browser/agentSessions/agentHost/agentHostImportConversationStore.js'; import { ChatViewId, IChatWidget, IChatWidgetService } from '../../browser/chat.js'; @@ -292,6 +296,10 @@ suite('Continue in Copilot policy recovery', () => { beginSessionsListSuppression: () => Disposable.None, })); services.stub(IViewsService, { openView: views.openView }); + // The panel is the Chat view, as in the workbench + services.stub(IViewDescriptorService, {}); + services.stub(IWorkbenchLayoutService, {}); + services.stub(IChatViewHostService, services.createInstance(ChatViewHostService)); const action = new ContinueChatInCopilotAction(); // The policy move runs on its own when the panel opens a chat, and when the user chooses it in an editor. const execute = () => services.invokeFunction(accessor => action.run(accessor, { $mid: MarshalledId.ChatViewContext, sessionResource: source, inputUri, ...(sidebar ? { trigger: 'automatic' } : {}) })); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatDailyUsage.contribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatDailyUsage.contribution.test.ts new file mode 100644 index 000000000000..3113105ad4fd --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/chatDailyUsage.contribution.test.ts @@ -0,0 +1,96 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { MessageKind } from '../../../../../platform/agentHost/common/state/protocol/state.js'; +import { InMemoryStorageService } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { ChatEntitlement, IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { IHostService } from '../../../../services/host/browser/host.js'; +import { LifecyclePhase } from '../../../../services/lifecycle/common/lifecycle.js'; +import { TestLifecycleService } from '../../../../test/common/workbenchTestServices.js'; +import { ChatDailyUsageContribution } from '../../browser/chatDailyUsage.contribution.js'; +import { ChatDailyUsage } from '../../common/chatDailyUsage.js'; +import { IChatRequestAcceptedEvent, IChatService } from '../../common/chatService/chatService.js'; + +suite('ChatDailyUsageContribution', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const hour = 60 * 60 * 1000; + const day = 24 * hour; + + function createContribution() { + const storage = disposables.add(new InMemoryStorageService()); + const requests = disposables.add(new Emitter()); + const focus = disposables.add(new Emitter()); + const entitlementChanged = disposables.add(new Emitter()); + const lifecycle = disposables.add(new TestLifecycleService()); + lifecycle.usePhases = true; + const state = { hasFocus: true, entitlement: ChatEntitlement.Pro }; + const events: object[] = []; + const contribution = disposables.add(new ChatDailyUsageContribution( + upcastPartial({ onDidAcceptRequest: requests.event }), + storage, + upcastPartial({ publicLog2: (eventName: string, data?: object) => { events.push({ eventName, ...data }); } }), + upcastPartial({ get hasFocus() { return state.hasFocus; }, onDidChangeFocus: focus.event }), + lifecycle, + upcastPartial({ get entitlement() { return state.entitlement; }, onDidChangeEntitlement: entitlementChanged.event }), + )); + return { contribution, storage, requests, focus, entitlementChanged, lifecycle, state, events }; + } + + test('reports once per UTC day after startup from a focused window of a user with a Copilot plan', () => runWithFakedTimers({ useFakeTimers: true, startTime: 10 * day + 22 * hour }, async () => { + const { contribution, requests, focus, entitlementChanged, lifecycle, state, events } = createContribution(); + const chatSessionResource = URI.parse('local:/session'); + requests.fire({ chatSessionResource, isNewSession: true }); + requests.fire({ chatSessionResource, isNewSession: false }); + focus.fire(true); + const beforeStartup = events.length; + state.hasFocus = false; + lifecycle.phase = LifecyclePhase.Eventually; + await timeout(0); + const unfocused = events.length; + state.hasFocus = true; + state.entitlement = ChatEntitlement.Available; + focus.fire(true); + await timeout(0); + const withoutPlan = events.length; + // Concurrent attempts from the same window still claim the day once. + state.entitlement = ChatEntitlement.Pro; + entitlementChanged.fire(); + focus.fire(true); + state.entitlement = ChatEntitlement.Free; + entitlementChanged.fire(); + // Hourly checks at 23:00 and 00:00 UTC; only the new day reports. + await timeout(2.5 * hour); + contribution.dispose(); + assert.deepStrictEqual({ beforeStartup, unfocused, withoutPlan, events }, { + beforeStartup: 0, + unfocused: 0, + withoutPlan: 0, + events: [ + { eventName: 'chatDailyUsage', plan: 'Pro', messagesLast7Days: 2, messagesLast30Days: 2, messagesTotal: 2, sessionsLast7Days: 1, sessionsLast30Days: 1, sessionsTotal: 1, minutesSinceLastMessage: 0, trackedDays: 0 }, + { eventName: 'chatDailyUsage', plan: 'Free', messagesLast7Days: 2, messagesLast30Days: 2, messagesTotal: 2, sessionsLast7Days: 1, sessionsLast30Days: 1, sessionsTotal: 1, minutesSinceLastMessage: 120, trackedDays: 1 }, + ], + }); + })); + + test('does not count messages that an agent, tool or automation sent on the user\'s behalf', () => { + const { storage, requests } = createContribution(); + const chatSessionResource = URI.parse('local:/session'); + requests.fire({ chatSessionResource, isNewSession: true }); + requests.fire({ chatSessionResource, isNewSession: false, agentHostMessageOrigin: { kind: MessageKind.User } }); + for (const kind of [MessageKind.Agent, MessageKind.Tool, MessageKind.Automation, MessageKind.SystemNotification]) { + requests.fire({ chatSessionResource: URI.parse(`local:/${kind}`), isNewSession: true, agentHostMessageOrigin: { kind } }); + } + const { messagesTotal, sessionsTotal } = new ChatDailyUsage(storage).getTelemetry(); + assert.deepStrictEqual({ messagesTotal, sessionsTotal }, { messagesTotal: 2, sessionsTotal: 1 }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatDockedViews.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatDockedViews.test.ts new file mode 100644 index 000000000000..028c4b64c329 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/chatDockedViews.test.ts @@ -0,0 +1,72 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { IChatDockedViewContribution, resolveChatDockedViewResource } from '../../browser/chatDockedViews/chatDockedViews.js'; +import { defaultChatDockedViewSize, getChatDockedViewHeight, IChatDockedViewSize, resizeChatDockedView } from '../../browser/chatDockedViews/chatDockedViewSizing.js'; + +suite('ChatDockedViews', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + function contribution(resource: string): IChatDockedViewContribution { + return { extensionId: new ExtensionIdentifier('pub.ext'), id: 'todos', label: 'Todos', icon: undefined, resource }; + } + + test('resolves the resource template with the chat session id', () => { + const session = URI.parse('vscode-chat-session://local/c2Vzc2lvbi8x'); + assert.strictEqual( + resolveChatDockedViewResource(contribution('chat-todos:/${chatSessionId}.todo.json'), session)?.toString(), + 'chat-todos:/c2Vzc2lvbi8x.todo.json', + ); + }); + + test('keeps characters of the chat session id that are special in URIs within the path', () => { + const session = URI.parse('agent-host://host/session%20one%23two%3F'); + assert.strictEqual( + resolveChatDockedViewResource(contribution('chat-todos:/${chatSessionId}.todo.json'), session)?.path, + '/session one#two?.todo.json', + ); + }); + + suite('sizing', () => { + const automatic = (maxAutomaticHeight: number): IChatDockedViewSize => ({ fixedHeight: undefined, maxAutomaticHeight }); + + test('follows the content height up to the maximum, within the available space', () => { + assert.deepStrictEqual([ + getChatDockedViewHeight(defaultChatDockedViewSize, 200, 1000), + getChatDockedViewHeight(defaultChatDockedViewSize, 600, 1000), + getChatDockedViewHeight(defaultChatDockedViewSize, 600, 250), + getChatDockedViewHeight(defaultChatDockedViewSize, 10, 1000), + getChatDockedViewHeight({ fixedHeight: 500, maxAutomaticHeight: 320 }, 100, 1000), + ], [200, 320, 250, 40, 500]); + }); + + test('dragging to another height fixes it', () => { + assert.deepStrictEqual(resizeChatDockedView(defaultChatDockedViewSize, 200, 260, 200), { fixedHeight: 260, maxAutomaticHeight: 320 }); + }); + + test('dragging back to the automatic height follows the content again', () => { + assert.deepStrictEqual(resizeChatDockedView({ fixedHeight: 100, maxAutomaticHeight: 320 }, 320, 315, 600), automatic(320)); + }); + + test('dragging to the content height follows it and remembers it as the maximum', () => { + assert.deepStrictEqual(resizeChatDockedView(defaultChatDockedViewSize, 320, 605, 600), automatic(600)); + }); + + test('the remembered maximum is never below the default', () => { + assert.deepStrictEqual(resizeChatDockedView(automatic(600), 200, 205, 200), automatic(320)); + }); + + test('heights are clamped', () => { + assert.deepStrictEqual([ + resizeChatDockedView(defaultChatDockedViewSize, 200, 5, undefined), + resizeChatDockedView(defaultChatDockedViewSize, 200, 5000, undefined), + ], [{ fixedHeight: 40, maxAutomaticHeight: 320 }, { fixedHeight: 1000, maxAutomaticHeight: 320 }]); + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingActions.test.ts index e7c938f7066f..1b6a21ed120f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingActions.test.ts @@ -12,6 +12,7 @@ import { URI } from '../../../../../../base/common/uri.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { CodeEditorWidget } from '../../../../../../editor/browser/widget/codeEditor/codeEditorWidget.js'; +import { EditorContextKeys } from '../../../../../../editor/common/editorContextKeys.js'; import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -37,6 +38,25 @@ import { MockChatWidgetService } from '../widget/mockChatWidget.js'; suite('Chat editing actions', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('Enter edits a focused transcript request but not controls in an editor hover', () => { + const enterHash = decodeKeybinding(KeyCode.Enter, OperatingSystem.Windows)!.getHashCode(); + const rule = KeybindingsRegistry.getDefaultKeybindingsForOS(OperatingSystem.Windows) + .find(rule => rule.keybinding?.getHashCode() === enterHash && rule.command === 'workbench.action.chat.editRequests'); + assert.ok(rule?.when); + const context = (hoverFocused: boolean): IContext => ({ + getValue: (key: string) => ({ + [ChatContextKeys.inChatSession.key]: true, + [EditorContextKeys.textInputFocus.key]: false, + [EditorContextKeys.hoverFocused.key]: hoverFocused, + [ChatContextKeys.readOnly.key]: false, + })[key] as T | undefined + }); + assert.deepStrictEqual({ + transcript: rule.when.evaluate(context(false)), + hover: rule.when.evaluate(context(true)), + }, { transcript: true, hover: false }); + }); + test('Delete actions do not run while a native input is focused', () => { const deleteHash = decodeKeybinding(KeyCode.Delete, OperatingSystem.Windows)!.getHashCode(); const rules = KeybindingsRegistry.getDefaultKeybindingsForOS(OperatingSystem.Windows) diff --git a/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingSessionStorage.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingSessionStorage.test.ts index 4c4a8f19f373..f5f4cbd65ffd 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingSessionStorage.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatEditing/chatEditingSessionStorage.test.ts @@ -107,4 +107,27 @@ suite('ChatEditingSessionStorage', () => { const s = await storage.restoreState(); assert.strictEqual(s, undefined); }); + + test('does not write a folder for an empty state', async () => { + const emptyState: StoredSessionState = { + initialFileContents: new ResourceMap(), + recentSnapshot: { stopId: undefined, entries: new ResourceMap() }, + timeline: { + checkpoints: [{ checkpointId: generateUuid(), requestId: undefined, undoStopId: undefined, epoch: 0, label: 'Initial State' }], + currentEpoch: 1, + fileBaselines: [], + operations: [], + epochCounter: 1, + }, + }; + + await storage.storeState(emptyState); + const writtenWhenEmpty = await fs.exists(storage.storageLocation); + + await storage.storeState(generateState()); + await storage.storeState(emptyState); + const keptAfterEmptied = await fs.exists(storage.storageLocation); + + assert.deepStrictEqual({ writtenWhenEmpty, keptAfterEmptied }, { writtenWhenEmpty: false, keptAfterEmptied: false }); + }); }); 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 88eb03bd61d6..f80fa5bf2268 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import sinon from 'sinon'; 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'; @@ -16,7 +17,7 @@ import { IActionListItem } from '../../../../../platform/actionWidget/browser/ac 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 { IChatPillEntry, IChatPillSection } from '../../../../browser/chatPills.js'; +import { ChatPillsRow, type IChatPillEntry, type 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'; @@ -929,6 +930,26 @@ suite('StandardChatInputPillSources', () => { }); }); + test('does not rescan the row when pill data updates without changing the row state', () => { + const scanDomNode = sinon.spy(ChatPillsRow.prototype, 'scanDomNode'); + store.add(toDisposable(() => scanDomNode.restore())); + const sections = observableValue('artifacts', [{ title: 'Artifacts', entries: [{ id: 'plan', label: 'Plan 0', open: () => { } }] }]); + const pills = createPills({ artifacts: { sections } }); + const initialScans = scanDomNode.callCount; + + for (let index = 1; index <= 5; index++) { + sections.set([{ title: 'Artifacts', entries: [{ id: 'plan', label: `Plan ${index}`, open: () => { } }] }], undefined); + } + const afterUpdates = { visible: pills.inputPills.visible, scans: scanDomNode.callCount - initialScans }; + sections.set([], undefined); + + assert.deepStrictEqual({ initialScans, afterUpdates, afterRemoved: { visible: pills.inputPills.visible, scans: scanDomNode.callCount - initialScans } }, { + initialScans: 2, + afterUpdates: { visible: true, scans: 0 }, + afterRemoved: { visible: false, scans: 1 }, + }); + }); + test('keeps the row available for restoring a hidden pill', async () => { const instantiationService = workbenchInstantiationService(undefined, store); const hidden = observableValue('hiddenPills', false); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatResources.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatResources.test.ts new file mode 100644 index 000000000000..f9d51ddcc0dc --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/chatResources.test.ts @@ -0,0 +1,130 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { autorun, observableValue, waitForState } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { FileService } from '../../../../../platform/files/common/fileService.js'; +import { InMemoryFileSystemProvider } from '../../../../../platform/files/common/inMemoryFilesystemProvider.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { ChatResourceContributionEntries, IChatResourceContribution, IChatResourceSessionIds, resolveChatResourceTemplate } from '../../browser/chatResources/chatResourceContributions.js'; +import { getShownChatResource } from '../../browser/chatResources/chatResourcesControl.js'; +import { defaultChatEmbeddedResourceSize, getChatEmbeddedResourceHeight, IChatEmbeddedResourceSize, resizeChatEmbeddedResource } from '../../browser/chatResources/chatResourceSizing.js'; + +suite('ChatResources', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('resolves resource templates with the chat\'s and the agent\'s session id', () => { + const ids: IChatResourceSessionIds = { chatSessionId: 'chat 1', agentSessionId: 'cli-42' }; + assert.deepStrictEqual([ + resolveChatResourceTemplate('chat-todos:/${chatSessionId}.todo.json', ids)?.toString(true), + resolveChatResourceTemplate('chat-todos:/${agentSessionId}.todo.json', ids)?.toString(true), + resolveChatResourceTemplate('chat-todos:/${agentSessionId}.todo.json', { chatSessionId: 'chat 1', agentSessionId: undefined }), + resolveChatResourceTemplate('chat-todos:/${chatSessionId}.todo.json', { chatSessionId: 'a#b?c', agentSessionId: undefined })?.path, + ], ['chat-todos:/chat 1.todo.json', 'chat-todos:/cli-42.todo.json', undefined, '/a#b?c.todo.json']); + }); + + test('lists a contributed resource while its file exists for the chat', async () => { + const fileService = store.add(new FileService(new NullLogService())); + store.add(fileService.registerProvider('chat-status', store.add(new InMemoryFileSystemProvider()))); + const contribution: IChatResourceContribution = { extensionId: new ExtensionIdentifier('pub.ext'), id: 'status', label: 'Status', icon: undefined, resource: 'chat-status:/${agentSessionId}.md' }; + const ids = observableValue('ids', { chatSessionId: 'chat-1', agentSessionId: 'cli-42' }); + const entries = store.add(new ChatResourceContributionEntries(observableValue('contributions', [contribution]), ids, () => { }, fileService)); + const listed = () => entries.sections.get().flatMap(section => section.entries.map(entry => `${entry.id} ${entry.label} ${entry.resource?.toString()}`)); + // Like the pill that reads them, an observer keeps the entries and their file watchers alive. + store.add(autorun(reader => entries.sections.read(reader))); + + const before = listed(); + await fileService.writeFile(URI.parse('chat-status:/cli-42.md'), VSBuffer.fromString('# Status')); + await waitForState(entries.sections, sections => sections.length > 0); + const created = listed(); + await fileService.del(URI.parse('chat-status:/cli-42.md')); + await waitForState(entries.sections, sections => sections.length === 0); + + assert.deepStrictEqual({ before, created, deleted: listed() }, { + before: [], + created: ['contributed:pub.ext/status Status chat-status:/cli-42.md'], + deleted: [], + }); + }); + + test('watches a resource whose file system provider registers later', async () => { + const fileService = store.add(new FileService(new NullLogService())); + const contribution: IChatResourceContribution = { extensionId: new ExtensionIdentifier('pub.ext'), id: 'status', label: 'Status', icon: undefined, resource: 'chat-status:/${chatSessionId}.md' }; + const entries = store.add(new ChatResourceContributionEntries(observableValue('contributions', [contribution]), observableValue('ids', { chatSessionId: 'chat-1', agentSessionId: undefined }), () => { }, fileService)); + store.add(autorun(reader => entries.sections.read(reader))); + const provider = store.add(new InMemoryFileSystemProvider()); + const watched: string[] = []; + const watch = provider.watch.bind(provider); + provider.watch = (resource, options) => { + watched.push(resource.toString()); + return watch(resource, options); + }; + + store.add(fileService.registerProvider('chat-status', provider)); + await fileService.writeFile(URI.parse('chat-status:/chat-1.md'), VSBuffer.fromString('# Status')); + await waitForState(entries.sections, sections => sections.length > 0); + + assert.deepStrictEqual(watched, ['chat-status:/chat-1.md']); + }); + + suite('embedded size', () => { + const automatic = (maxAutomaticHeight: number): IChatEmbeddedResourceSize => ({ fixedHeight: undefined, maxAutomaticHeight }); + + test('follows the content height up to the maximum, within the available space', () => { + assert.deepStrictEqual([ + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 200, 1000), + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 600, 1000), + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 600, 250), + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 10, 1000), + getChatEmbeddedResourceHeight({ fixedHeight: 500, maxAutomaticHeight: 320 }, 100, 1000), + ], [200, 320, 250, 40, 500]); + }); + + test('leaves the transcript its room even below the minimum height', () => { + assert.deepStrictEqual([ + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 10, 24), + getChatEmbeddedResourceHeight(defaultChatEmbeddedResourceSize, 200, -5), + ], [24, 0]); + }); + + test('dragging to another height fixes it', () => { + assert.deepStrictEqual(resizeChatEmbeddedResource(defaultChatEmbeddedResourceSize, 200, 260, 200), { fixedHeight: 260, maxAutomaticHeight: 320 }); + }); + + test('dragging back to the automatic height follows the content again', () => { + assert.deepStrictEqual(resizeChatEmbeddedResource({ fixedHeight: 100, maxAutomaticHeight: 320 }, 320, 315, 600), automatic(320)); + }); + + test('dragging to the content height follows it and remembers it as the maximum', () => { + assert.deepStrictEqual(resizeChatEmbeddedResource(defaultChatEmbeddedResourceSize, 320, 605, 600), automatic(600)); + }); + + test('the remembered maximum is never below the default', () => { + assert.deepStrictEqual(resizeChatEmbeddedResource(automatic(600), 200, 205, 200), automatic(320)); + }); + + test('heights are clamped', () => { + assert.deepStrictEqual([ + resizeChatEmbeddedResource(defaultChatEmbeddedResourceSize, 200, 5, undefined), + resizeChatEmbeddedResource(defaultChatEmbeddedResourceSize, 200, 5000, undefined), + ], [{ fixedHeight: 40, maxAutomaticHeight: 320 }, { fixedHeight: 1000, maxAutomaticHeight: 320 }]); + }); + }); + + test('an area shows its first resource until the user chooses, then only the chosen one', () => { + const resources = [{ id: 'todos' }, { id: 'plan' }]; + assert.deepStrictEqual([ + getShownChatResource(resources, undefined)?.id, + getShownChatResource(resources, 'plan')?.id, + getShownChatResource(resources, null)?.id, + // The chosen resource left the area, for example because the user showed it at the top: no other one takes its place. + getShownChatResource(resources, 'notes')?.id, + ], ['todos', 'plan', undefined, undefined]); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatSetup/chatSetupCopilotAccount.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatSetup/chatSetupCopilotAccount.test.ts new file mode 100644 index 000000000000..d0905996ccde --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/chatSetup/chatSetupCopilotAccount.test.ts @@ -0,0 +1,737 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, raceTimeout, Sequencer } from '../../../../../../base/common/async.js'; +import { CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; +import { CancellationError } from '../../../../../../base/common/errors.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { Lazy } from '../../../../../../base/common/lazy.js'; +import { Disposable } from '../../../../../../base/common/lifecycle.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IDefaultAccount } from '../../../../../../base/common/defaultAccount.js'; +import { IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; +import { AuthenticateParams } from '../../../../../../platform/agentHost/common/agent.js'; +import { copilotEntraClientId, copilotEntraDiscoveryResource, copilotEntraM365Audience, copilotEntraEmuAudience, copilotEntraResources } from '../../../../../../platform/agentHost/common/copilotEntraAuthentication.js'; +import { ProtectedResourceMetadata } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { AuthRequiredReason, INotification, NotificationType } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; +import { ROOT_STATE_URI, RootState } from '../../../../../../platform/agentHost/common/state/sessionState.js'; +import { AgentHostCopilotM365EnabledSettingId } from '../../../../../../platform/chat/common/chatSettings.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../../platform/product/common/productService.js'; +import { IProgressOptions, IProgressService } from '../../../../../../platform/progress/common/progress.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../../../platform/quickinput/common/quickInput.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; +import { IActivityService } from '../../../../../services/activity/common/activity.js'; +import { AuthenticationSession, IAuthenticationService } from '../../../../../services/authentication/common/authentication.js'; +import { ChatEntitlement, ChatEntitlementContext, ChatEntitlementRequests } from '../../../../../services/chat/common/chatEntitlementService.js'; +import { ILifecycleService } from '../../../../../services/lifecycle/common/lifecycle.js'; +import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; +import { IExtensionsWorkbenchService } from '../../../../extensions/common/extensions.js'; +import { gitHubEnterpriseUrisSetting } from '../../../../../services/accounts/common/githubEnterprise.js'; +import { ChatSetupController } from '../../../browser/chatSetup/chatSetupController.js'; +import { ChatSetupStep, ChatSetupStrategy } from '../../../browser/chatSetup/chatSetup.js'; +import { ChatSetup } from '../../../browser/chatSetup/chatSetupRunner.js'; + +suite('Microsoft Copilot resource setup UI', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const discovery: ProtectedResourceMetadata = { + resource: copilotEntraDiscoveryResource, authorization_servers: ['https://login.microsoftonline.com/organizations'], + scopes_supported: ['User.Read'], required: false, + }; + const services: readonly ProtectedResourceMetadata[] = [ + { resource: copilotEntraResources.get(copilotEntraEmuAudience)!, resource_name: 'GitHub Copilot', authorization_servers: discovery.authorization_servers, scopes_supported: [`${copilotEntraEmuAudience}/user_impersonation`], required: false }, + { resource: copilotEntraResources.get(copilotEntraM365Audience)!, resource_name: 'Microsoft 365 Copilot', authorization_servers: discovery.authorization_servers, scopes_supported: [`${copilotEntraM365Audience}/.default`], required: false }, + ]; + const unrelated: ProtectedResourceMetadata = { resource: 'https://other.example', scopes_supported: ['unrelated'] }; + /** A credential the host asks for, which unlike a service it offers carries no name. */ + const requirement: ProtectedResourceMetadata = { resource: services[0].resource, authorization_servers: services[0].authorization_servers, scopes_supported: services[0].scopes_supported, required: false }; + + function fixture() { + const changed = store.add(new Emitter()); + const exited = store.add(new Emitter()); + const notifications = store.add(new Emitter()); + const available = observableValue('connectionAvailable', true); + let root: RootState | Error = { agents: [] }; + const calls: string[] = []; + const deliveries: AuthenticateParams[] = []; + const account = { id: 'opaque-account', label: 'Microsoft Account' }; + const state = { + offered: services, pick: undefined as number | undefined, sessions: [] as AuthenticationSession[], + credentialAccount: account, credentialScopes: undefined as readonly string[] | undefined, + silentCredential: true, needsServiceConsent: false, rejectResource: undefined as string | undefined, + signIn: undefined as Promise | undefined, publication: undefined as Promise | undefined, + activation: undefined as Promise | undefined, retry: false, + discovery: undefined as DeferredPromise | undefined, + challenge: undefined as ProtectedResourceMetadata | undefined, challengeBeforePublication: false, challengeSatisfiedElsewhere: false, + leftover: undefined as ProtectedResourceMetadata | undefined, + refused: undefined as ProtectedResourceMetadata | undefined, + consentError: undefined as Error | undefined, finishDiscoveryOnCredential: false, progress: false, + cancelProgress: undefined as (() => void) | undefined, + picks: [] as (readonly IQuickPickItem[])[], + }; + const publish = (resources: readonly ProtectedResourceMetadata[]) => { + root = { agents: [{ provider: 'different-advertised-copilot-id', displayName: 'Agent', description: '', models: [], protectedResources: [...resources] }] }; + changed.fire(root); + }; + publish([unrelated, discovery]); + const subscription = { get value() { return root; }, get verifiedValue() { return root instanceof Error ? undefined : root; }, onDidChange: changed.event, onDidError: Event.None, onWillApplyAction: Event.None, onDidApplyAction: Event.None }; + const signInStarted = new DeferredPromise(); + const discoveryDelivered = new DeferredPromise(); + const activationStarted = new DeferredPromise(); + const retryShown = new DeferredPromise(); + const challengeAnswered = new DeferredPromise(); + const consentFailed = new DeferredPromise(); + const isRefused = (scopes: readonly string[]) => !!state.refused?.scopes_supported?.every(scope => scopes.includes(scope)); + const host = upcastPartial({ + connectionAvailable: available, rootState: subscription, onAgentHostExit: exited.event, onDidNotification: notifications.event, + startAgentHost() { }, + authenticate: async request => { + deliveries.push(request); + if (!request.token) { + publish([unrelated, discovery]); + return { authenticated: true }; + } + if (state.rejectResource === request.resource) { + return { authenticated: false }; + } + if (request.resource === discovery.resource) { + const pending = state.discovery; + if (state.challenge) { + const challenge: INotification = { type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: state.challenge, reason: AuthRequiredReason.Required }; + if (state.challengeBeforePublication) { + notifications.fire(challenge); + } + publish([discovery, state.challenge]); + if (!state.challengeBeforePublication) { + notifications.fire(challenge); + } + if (state.challengeSatisfiedElsewhere) { + publish([discovery]); + } + } + void discoveryDelivered.complete(); + await pending?.p; + // Like the real host, keep advertising a requirement that was never given a credential. + const challenged = state.challenge; + const outstanding = [ + ...(state.leftover ? [state.leftover] : []), + ...(challenged && !state.challengeSatisfiedElsewhere && !state.offered.some(offered => offered.resource === challenged.resource) + && !deliveries.some(delivery => delivery.resource === challenged.resource) ? [challenged] : []), + ]; + if (state.publication) { + publish([discovery, ...outstanding]); + void state.publication.then(() => publish([discovery, ...outstanding, ...state.offered])); + } else { + publish([discovery, ...outstanding, ...state.offered]); + } + } else { + if (request.resource === state.challenge?.resource) { + void challengeAnswered.complete(); + if (state.finishDiscoveryOnCredential) { + void state.discovery?.complete(); + } + } + void activationStarted.complete(); + await state.activation; + } + return { authenticated: true }; + }, + }); + const configuration = new TestConfigurationService({ [AgentHostCopilotM365EnabledSettingId]: true }); + const context = store.add(new ChatEntitlementContext(store.add(new MockContextKeyService()), store.add(new TestStorageService()), new NullLogService(), configuration, NullTelemetryService)); + const instantiation = store.add(new TestInstantiationService()); + instantiation.stub(IAgentHostService, host); + instantiation.stub(IConfigurationService, configuration); + instantiation.stub(ITelemetryService, NullTelemetryService); + instantiation.stub(ILogService, new NullLogService()); + instantiation.stub(IProductService, { quality: 'stable' }); + instantiation.stub(IActivityService, { showViewContainerActivity: () => Disposable.None }); + instantiation.stub(IProgressService, { + withProgress: async (options: IProgressOptions & { readonly command?: string }, task, onDidCancel) => { + state.progress = true; + state.cancelProgress = options.cancellable && !options.command ? onDidCancel : undefined; + try { + return await task({ report() { } }); + } finally { + state.progress = false; + state.cancelProgress = undefined; + } + } + }); + instantiation.stub(IExtensionsWorkbenchService, { local: [], install: async () => { calls.push('install'); return undefined!; } }); + instantiation.stub(ILifecycleService, { willShutdown: false }); + instantiation.stub(IDefaultAccountService, { getDefaultAccountAuthenticationProvider: () => ({ id: 'github', name: 'GitHub', enterprise: false }) }); + instantiation.stub(IWorkspaceTrustManagementService, { isWorkspaceTrusted: () => true }); + instantiation.stub(IWorkspaceTrustRequestService, { requestWorkspaceTrust: async () => true }); + instantiation.stub(IDialogService, { + confirm: async () => { + calls.push('retry'); + void retryShown.complete(); + const confirmed = state.retry; + state.retry = false; + state.rejectResource = undefined; + return { confirmed }; + } + }); + instantiation.stub(IQuickInputService, { + pick: async items => { + const choices = (await items).filter((item): item is typeof item & IQuickPickItem => item.type !== 'separator'); + state.picks.push(choices); + return state.pick === undefined ? undefined : choices[state.pick]; + } + }); + const credential = (scopes: readonly string[]): AuthenticationSession => ({ id: 'microsoft-session', account: state.credentialAccount, scopes: state.credentialScopes ?? scopes, accessToken: 'synthetic', expiresAfter: 120000 }); + instantiation.stub(IAuthenticationService, { + getSessions: async (provider, scopes, options) => { + assert.strictEqual(provider, 'microsoft'); + if (!scopes) { + return state.sessions; + } + assert.deepStrictEqual([options?.clientId, options?.authorizationServer?.toString(), options?.account?.id], [copilotEntraClientId, discovery.authorization_servers![0], account.id]); + assert.ok(Array.isArray(scopes)); + const granted = state.sessions.some(session => scopes.every(scope => session.scopes.includes(scope))); + return state.silentCredential && !isRefused(scopes) && (!state.needsServiceConsent || scopes.includes('User.Read') || granted) ? [credential(scopes)] : []; + }, + createSession: async (_provider, scopes, options) => { + calls.push('signIn'); + assert.deepStrictEqual([options?.clientId, options?.authorizationServer?.toString()], [copilotEntraClientId, discovery.authorization_servers![0]]); + void signInStarted.complete(); + await state.signIn; + assert.ok(Array.isArray(scopes)); + if (state.consentError && (!state.refused || isRefused(scopes))) { + void consentFailed.complete(); + throw state.consentError; + } + const session = credential(scopes); + state.sessions = [session]; + return session; + }, + }); + const requests = upcastPartial({ signIn: async () => { calls.push('legacy'); return {}; } }); + const controller = store.add(instantiation.createInstance(ChatSetupController, context, requests)); + const runner = instantiation.createInstance(ChatSetup, context, new Lazy(() => controller)); + const run = (cancellationToken?: CancellationTokenSource['token']) => runner.run({ setupStrategy: ChatSetupStrategy.SetupWithMicrosoftProvider, disableChatViewReveal: true, cancellationToken }); + return { + host, publish, available, state, calls, deliveries, context, configuration, controller, requests, instantiation, run, account, credential, signInStarted, discoveryDelivered, activationStarted, notifications, retryShown, challengeAnswered, consentFailed, + disconnect: () => { available.set(false, undefined); exited.fire(0); } + }; + } + + for (const beforePublication of [false, true]) { + test(`answers nested consent while discovery is still pending${beforePublication ? ' when the challenge precedes its resource' : ''}`, async () => { + const f = fixture(); + const discovery = new DeferredPromise(); + f.state.discovery = discovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[0]]; + f.state.challenge = services[0]; + f.state.challengeBeforePublication = beforePublication; + f.state.needsServiceConsent = true; + f.state.finishDiscoveryOnCredential = true; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ success: result?.success, answered: f.challengeAnswered.isResolved, calls: f.calls, resources: f.deliveries.map(request => request.resource), scopes: f.state.sessions.map(session => session.scopes) }, { + success: true, answered: true, calls: ['signIn', 'install'], resources: [copilotEntraDiscoveryResource, services[0].resource, services[0].resource], scopes: [services[0].scopes_supported], + }); + } finally { + cancellation.cancel(); + await discovery.complete(); + await pending; + } + }); + } + + test('a requirement satisfied elsewhere before its prompt starts does not fail choosing that service', async () => { + const f = fixture(); + const pendingDiscovery = new DeferredPromise(); + f.state.discovery = pendingDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[0]]; + f.state.challenge = services[0]; + f.state.challengeSatisfiedElsewhere = true; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await f.discoveryDelivered.p; + const returnedBeforeHostResult = await raceTimeout(pending, 50) !== undefined; + await pendingDiscovery.complete(); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ returnedBeforeHostResult, success: result?.success, calls: f.calls, delivered: f.deliveries.map(request => request.resource) }, { + returnedBeforeHostResult: false, success: true, calls: ['install'], delivered: [discovery.resource, services[0].resource], + }); + } finally { + cancellation.cancel(); + await pendingDiscovery.complete(); + await pending; + } + }); + + test('a queued requirement satisfied elsewhere does not fail the service already chosen', async () => { + const f = fixture(); + const pendingDiscovery = new DeferredPromise(); + const prompt = new DeferredPromise(); + f.state.discovery = pendingDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[1]]; + f.state.challenge = requirement; + f.state.refused = services[0]; + f.state.consentError = new CancellationError(); + f.state.signIn = prompt.p; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.signInStarted.p, 500); + const requirement: ProtectedResourceMetadata = { resource: services[1].resource, authorization_servers: services[1].authorization_servers, scopes_supported: services[1].scopes_supported, required: false }; + f.publish([discovery, services[0], requirement]); + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: requirement, reason: AuthRequiredReason.Required }); + await pendingDiscovery.complete(); + const returnedBehindOpenPrompt = await raceTimeout(pending, 50) !== undefined; + await prompt.complete(); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ returnedBehindOpenPrompt, success: result?.success, calls: f.calls, delivered: f.deliveries.map(request => request.resource) }, { + returnedBehindOpenPrompt: false, success: true, calls: ['signIn', 'install'], delivered: [discovery.resource, services[1].resource], + }); + } finally { + cancellation.cancel(); + await prompt.complete(); + await pendingDiscovery.complete(); + await pending; + } + }); + + for (const [kind, consentError] of [['refused', new Error('access_denied')], ['declined', new CancellationError()]] as const) { + test(`a ${kind} permission for one service does not fail setup when the host offers another`, async () => { + const f = fixture(); + const pendingDiscovery = new DeferredPromise(); + f.state.discovery = pendingDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[1]]; + f.state.challenge = requirement; + f.state.refused = services[0]; + f.state.consentError = consentError; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.consentFailed.p, 500); + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: requirement, reason: AuthRequiredReason.Required }); + const beforeHostResult = { returned: await raceTimeout(pending, 50) !== undefined, failureShown: f.retryShown.isSettled }; + await pendingDiscovery.complete(); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ beforeHostResult, success: result?.success, choices: f.state.picks.length, calls: f.calls, delivered: f.deliveries.map(request => request.resource) }, { + beforeHostResult: { returned: false, failureShown: false }, success: true, choices: 0, calls: ['signIn', 'install'], delivered: [discovery.resource, services[1].resource], + }); + } finally { + cancellation.cancel(); + await pendingDiscovery.complete(); + await pending; + } + }); + } + + test('a requirement left advertised by an earlier attempt is not offered as a service', async () => { + const f = fixture(); + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[1]]; + f.state.leftover = requirement; + f.publish([discovery, requirement, services[1]]); + const result = await raceTimeout(f.run(), 500); + assert.deepStrictEqual({ success: result?.success, choices: f.state.picks.length, delivered: f.deliveries.map(request => request.resource) }, { + success: true, choices: 0, delivered: [discovery.resource, services[1].resource], + }); + }); + + test('a requirement the host is still asking for is not mistaken for a published service', async () => { + const f = fixture(); + const publication = new DeferredPromise(); + f.state.publication = publication.p; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[1]]; + f.state.challenge = requirement; + f.state.refused = services[0]; + f.state.consentError = new Error('access_denied'); + const pending = f.run(); + await raceTimeout(f.consentFailed.p, 500); + const beforePublication = { returned: await raceTimeout(pending, 50) !== undefined, failureShown: f.retryShown.isSettled, choices: f.state.picks.length }; + await publication.complete(); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ beforePublication, success: result?.success, choices: f.state.picks.length, delivered: f.deliveries.map(request => request.resource) }, { + beforePublication: { returned: false, failureShown: false, choices: 0 }, success: true, choices: 0, delivered: [discovery.resource, services[1].resource], + }); + }); + + test('a declined permission leaves the outcome to the host, and Cancel after its failure retains sign-in', async () => { + const f = fixture(); + const pendingDiscovery = new DeferredPromise(); + f.state.discovery = pendingDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.challenge = services[0]; + f.state.refused = services[0]; + f.state.consentError = new CancellationError(); + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.consentFailed.p, 500); + const failureShownBeforeHostResult = await raceTimeout(pending, 50) !== undefined || f.retryShown.isSettled; + await pendingDiscovery.error(new Error('No usable service')); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ + failureShownBeforeHostResult, success: result?.success, handled: result?.errorAlreadyHandled, + calls: f.calls, revoked: f.deliveries.filter(request => !request.token).map(request => request.resource), + signedIn: f.state.sessions.length, + }, { + failureShownBeforeHostResult: false, success: false, handled: true, calls: ['signIn', 'retry'], + revoked: [discovery.resource], signedIn: 1, + }); + } finally { + cancellation.cancel(); + await pendingDiscovery.complete(); + await pending; + } + }); + + test('a provider sign-in failure does not revoke a binding setup never started', async () => { + const f = fixture(); + f.state.consentError = new Error('Provider sign-in failed'); + const result = await f.run(); + assert.deepStrictEqual({ success: result.success, calls: f.calls, deliveries: f.deliveries }, { + success: false, calls: ['signIn', 'retry'], deliveries: [], + }); + }); + + test('a repeated answered challenge fails without prompting again', async () => { + const f = fixture(); + const pendingDiscovery = new DeferredPromise(); + f.state.discovery = pendingDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.challenge = services[0]; + f.state.needsServiceConsent = true; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.challengeAnswered.p, 500); + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: services[0], reason: AuthRequiredReason.Required }); + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ answered: f.challengeAnswered.isResolved, success: result?.success, calls: f.calls, revoked: f.deliveries.filter(request => !request.token).length }, { + answered: true, success: false, calls: ['signIn', 'retry'], revoked: 1, + }); + } finally { + cancellation.cancel(); + await pendingDiscovery.complete(); + await pending; + } + }); + + for (const cancelRetry of [false, true]) { + test(`Retry after an early failure stays in progress behind the old request${cancelRetry ? ' and can be cancelled' : ''}`, async () => { + const f = fixture(); + const oldDiscovery = new DeferredPromise(); + const newDiscovery = new DeferredPromise(); + const queued = new DeferredPromise(); + const requests: AuthenticateParams[] = []; + const sequence = new Sequencer(); + const authenticate = f.host.authenticate; + f.host.authenticate = request => { + if (request.resource !== discovery.resource || !request.token) { + return authenticate(request); + } + requests.push(request); + if (requests.length === 2) { + void queued.complete(); + } + return sequence.queue(() => authenticate(request)); + }; + f.state.discovery = oldDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[0]]; + f.state.challenge = services[0]; + f.state.needsServiceConsent = true; + f.state.retry = true; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.challengeAnswered.p, 500); + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: services[0], reason: AuthRequiredReason.Required }); + await raceTimeout(f.retryShown.p, 500); + f.state.discovery = newDiscovery; + f.state.finishDiscoveryOnCredential = true; + await raceTimeout(queued.p, 500); + const waiting = { queued: queued.isResolved, step: f.controller.step, progress: f.state.progress, oldPending: !oldDiscovery.isSettled }; + if (cancelRetry) { + f.state.cancelProgress?.(); + } else { + await oldDiscovery.error(new Error('Old discovery timed out')); + } + const result = await raceTimeout(pending, 500); + assert.deepStrictEqual({ + waiting, returned: result !== undefined, success: result?.success, + retries: f.calls.filter(call => call === 'retry').length, installed: f.calls.includes('install'), + revoked: f.deliveries.filter(request => !request.token).length, + }, { + waiting: { queued: true, step: ChatSetupStep.SigningIn, progress: true, oldPending: true }, + returned: true, success: cancelRetry ? undefined : true, retries: 1, installed: !cancelRetry, revoked: cancelRetry ? 1 : 0, + }); + } finally { + cancellation.cancel(); + await oldDiscovery.complete(); + await newDiscovery.complete(); + await pending; + } + }); + } + + for (const lateError of [false, true]) { + test(`a late discovery ${lateError ? 'error' : 'result'} after Cancel cannot overwrite a newer setup or reopen failure UI`, async () => { + const f = fixture(); + const oldDiscovery = new DeferredPromise(); + f.state.discovery = oldDiscovery; + f.state.sessions = [f.credential(['User.Read'])]; + f.state.challenge = services[0]; + f.state.needsServiceConsent = true; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + try { + await raceTimeout(f.challengeAnswered.p, 500); + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: services[0], reason: AuthRequiredReason.Required }); + const failed = await raceTimeout(pending, 500); + f.state.discovery = undefined; + f.state.challenge = undefined; + f.state.offered = [services[1]]; + const fresh = await f.run(); + if (lateError) { + await oldDiscovery.error(new Error('Late native failure')); + } else { + await oldDiscovery.complete(); + } + f.notifications.fire({ type: NotificationType.AuthRequired, channel: ROOT_STATE_URI, resource: services[0], reason: AuthRequiredReason.Required }); + await pending; + assert.deepStrictEqual({ + failed: failed?.success, fresh: fresh.success, completed: f.context.state.completed, step: f.controller.step, + retries: f.calls.filter(call => call === 'retry').length, installs: f.calls.filter(call => call === 'install').length, + }, { failed: false, fresh: true, completed: true, step: ChatSetupStep.Initial, retries: 1, installs: 1 }); + } finally { + cancellation.cancel(); + await oldDiscovery.complete(); + await pending; + } + }); + } + + for (const pick of [0, 1]) { + test(`ordinary discovery authentication offers two resources and authenticates only choice ${pick}`, async () => { + const f = fixture(); + f.state.pick = pick; + const result = await f.run(); + assert.deepStrictEqual({ + success: result.success, completed: f.context.state.completed, calls: f.calls, + choices: f.state.picks.map(items => items.map(item => item.label)), delivered: f.deliveries, + }, { + success: true, completed: true, calls: ['signIn', 'install'], choices: [['GitHub Copilot', 'Microsoft 365 Copilot']], + delivered: [discovery, services[pick]].map(resource => ({ + resource: resource.resource, scopes: resource.scopes_supported, token: 'synthetic', expiresIn: 120, + _meta: { 'vscode.authentication.account': { providerId: 'microsoft', accountId: f.account.id } }, + })), + }); + }); + } + + test('waits for resource publication after the accepted discovery response', async () => { + const f = fixture(); + const publication = new DeferredPromise(); + f.state.publication = publication.p; + f.state.offered = [services[1]]; + const pending = f.run(); + await f.discoveryDelivered.p; + const before = { choices: f.state.picks.length, delivered: f.deliveries.length, completed: f.context.state.completed }; + await publication.complete(); + const result = await pending; + assert.deepStrictEqual({ before, success: result.success, choices: f.state.picks.length, resources: f.deliveries.map(request => request.resource) }, { + before: { choices: 0, delivered: 1, completed: undefined }, success: true, choices: 0, resources: [discovery.resource, services[1].resource], + }); + }); + + test('chooser cancellation retains sign-in and resume offers both services again', async () => { + const f = fixture(); + const first = await f.run(); + const canceled = { result: first.success, resources: f.deliveries.map(request => request.resource), completed: f.context.state.completed }; + f.state.pick = 1; + const second = await f.run(); + assert.deepStrictEqual({ canceled, resumed: second.success, choices: f.state.picks.length, signIns: f.calls.filter(call => call === 'signIn').length }, { + canceled: { result: undefined, resources: [discovery.resource], completed: undefined }, resumed: true, choices: 2, signIns: 1, + }); + }); + + for (const rejected of [discovery, services[1]]) { + test(`rejected authentication for ${rejected.resource} cannot complete setup`, async () => { + const f = fixture(); + f.state.offered = [services[1]]; + f.state.rejectResource = rejected.resource; + const result = await f.run(); + assert.deepStrictEqual({ success: result.success, handled: result.errorAlreadyHandled, calls: f.calls, completed: f.context.state.completed }, { + success: false, handled: true, calls: ['signIn', 'retry'], completed: undefined, + }); + }); + } + + test('retry reuses Microsoft sign-in after a discovery failure', async () => { + const f = fixture(); + f.state.offered = [services[1]]; + f.state.rejectResource = discovery.resource; + f.state.retry = true; + assert.deepStrictEqual({ result: (await f.run()).success, calls: f.calls }, { result: true, calls: ['signIn', 'retry', 'install'] }); + }); + + test('concurrent callers share the same handled authentication failure', async () => { + const f = fixture(); + f.state.rejectResource = discovery.resource; + const results = await Promise.all([f.run(), f.run()]); + assert.deepStrictEqual({ sameResult: results[0] === results[1], success: results[0].success, handled: results[0].errorAlreadyHandled, calls: f.calls, delivered: f.deliveries.length }, { + sameResult: true, success: false, handled: true, calls: ['signIn', 'retry'], delivered: 2, + }); + }); + + test('a cold host is started before waiting for connection availability', async () => { + const f = fixture(); + f.state.offered = [services[1]]; + f.available.set(false, undefined); + f.host.startAgentHost = () => { + f.calls.push('start'); + f.available.set(true, undefined); + }; + assert.deepStrictEqual({ success: (await f.run()).success, calls: f.calls }, { success: true, calls: ['start', 'signIn', 'install'] }); + }); + + test('cancelling native sign-in releases the shared runner and ignores late credentials', async () => { + const f = fixture(); + const signIn = new DeferredPromise(); + f.state.signIn = signIn.p; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + await f.signInStarted.p; + cancellation.cancel(); + const canceled = await raceTimeout(pending, 100); + await signIn.complete(); + await pending; + const deliveredBeforeResume = f.deliveries.length; + f.state.offered = [services[1]]; + assert.deepStrictEqual({ canceled: canceled?.success, returned: canceled !== undefined, deliveredBeforeResume, resumed: (await f.run()).success, signIns: f.calls.filter(call => call === 'signIn').length }, { + canceled: undefined, returned: true, deliveredBeforeResume: 0, resumed: true, signIns: 1, + }); + }); + + test('cancelled publication wait cannot continue from a later resource update', async () => { + const f = fixture(); + const publication = new DeferredPromise(); + f.state.publication = publication.p; + const cancellation = store.add(new CancellationTokenSource()); + const pending = f.run(cancellation.token); + await f.discoveryDelivered.p; + cancellation.cancel(); + const result = await pending; + await publication.complete(); + assert.deepStrictEqual({ result: result.success, choices: f.state.picks.length, resources: f.deliveries.map(request => request.resource), installed: f.calls.includes('install') }, { + result: undefined, choices: 0, resources: [discovery.resource, discovery.resource], installed: false, + }); + }); + + test('a target withdrawn during consent is not authenticated', async () => { + const f = fixture(); + f.state.sessions = [f.credential(['User.Read'])]; + f.state.offered = [services[1]]; + const consent = new DeferredPromise(); + f.state.needsServiceConsent = true; + f.state.signIn = consent.p; + const pending = f.run(); + await f.signInStarted.p; + f.publish([discovery]); + await consent.complete(); + const result = await pending; + assert.deepStrictEqual({ success: result.success, deliveredTargets: f.deliveries.filter(request => request.resource !== discovery.resource).length, installed: f.calls.includes('install') }, { + success: false, deliveredTargets: 0, installed: false, + }); + }); + + test('disconnection with a retained resource snapshot cannot install or complete setup', async () => { + const f = fixture(); + f.state.offered = [services[1]]; + const activation = new DeferredPromise(); + f.state.activation = activation.p; + const pending = f.run(); + await f.activationStarted.p; + f.disconnect(); + await activation.complete(); + const result = await pending; + assert.deepStrictEqual({ success: result.success, installed: f.calls.includes('install'), completed: f.context.state.completed }, { + success: false, installed: false, completed: undefined, + }); + }); + + test('Microsoft credentials must match the selected identity', async () => { + const f = fixture(); + f.state.sessions = [f.credential(['User.Read'])]; + f.state.credentialAccount = { ...f.account, id: 'different-account' }; + f.state.silentCredential = false; + const result = await f.run(); + assert.deepStrictEqual({ success: result.success, calls: f.calls, delivered: f.deliveries }, { success: false, calls: ['signIn', 'retry'], delivered: [] }); + }); + + test('an account-only session cannot substitute for Copilot-client consent', async () => { + const f = fixture(); + f.state.sessions = [f.credential([])]; + f.state.silentCredential = false; + f.state.credentialScopes = []; + const result = await f.run(); + assert.deepStrictEqual({ success: result.success, calls: f.calls, delivered: f.deliveries }, { success: false, calls: ['signIn', 'retry'], delivered: [] }); + }); + + test('Microsoft setup fails on a host that does not offer it and, like GitHub, is not refused when AI features are off', async () => { + const outcomes = []; + for (const condition of ['unsupported', 'hidden', 'admin'] as const) { + const f = fixture(); + f.state.offered = [services[1]]; + if (condition === 'unsupported') { + f.publish([]); + } else { + await f.configuration.setUserConfiguration(condition === 'hidden' ? 'chat.disableAIFeatures' : 'chat.agent.enabled', condition === 'hidden'); + } + const result = await f.run(); + outcomes.push({ condition, success: result.success, calls: f.calls, delivered: f.deliveries.length }); + } + assert.deepStrictEqual(outcomes, [ + { condition: 'unsupported', success: false, calls: ['retry'], delivered: 0 }, + ...['hidden', 'admin'].map(condition => ({ condition, success: true, calls: ['signIn', 'install'], delivered: 2 })), + ]); + }); + + test('GitHub and GHE follow the ordinary sign-in path with the gate on or off', async () => { + const observed = []; + for (const enabled of [false, true]) { + for (const provider of ['github', 'github-enterprise', 'google', 'apple', ...(!enabled ? ['microsoft'] : [])]) { + const f = fixture(); + await f.configuration.setUserConfiguration(AgentHostCopilotM365EnabledSettingId, enabled); + await f.configuration.setUserConfiguration(gitHubEnterpriseUrisSetting, ['https://contoso.ghe.com']); + const account: IDefaultAccount = { sessionId: 'chosen', accountName: 'GitHub', authenticationProvider: { id: 'github', name: 'GitHub', enterprise: false }, enterprise: false }; + f.requests.signIn = async () => { f.calls.push(provider); return { defaultAccount: account, entitlements: { entitlement: ChatEntitlement.Pro } }; }; + const result = await f.controller.setupWithProvider({ useEnterpriseProvider: provider === 'github-enterprise', useSocialProvider: ['github', 'github-enterprise'].includes(provider) ? undefined : provider }); + observed.push({ enabled, provider, result, calls: f.calls, delivered: f.deliveries }); + } + } + assert.deepStrictEqual(observed, [false, true].flatMap(enabled => ['github', 'github-enterprise', 'google', 'apple', ...(!enabled ? ['microsoft'] : [])].map(provider => ({ + enabled, provider, result: true, calls: [provider, 'install'], delivered: [], + })))); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatStatusPromo.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatStatusPromo.test.ts index df3cef827c47..aa3c158fc912 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatStatusPromo.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatStatusPromo.test.ts @@ -40,6 +40,9 @@ import { IViewsService } from '../../../../services/views/common/viewsService.js import { TestChatWidgetService, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; import { TestContextService } from '../../../../test/common/workbenchTestServices.js'; import { ChatViewId, IChatWidget, IChatWidgetService, IChatWidgetViewModelChangeEvent } from '../../browser/chat.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; import { ChatStatusPromo } from '../../browser/chatStatus/chatStatusPromo.js'; import type { ChatWidget } from '../../browser/widget/chatWidget.js'; import type { ChatInputPart } from '../../browser/widget/input/chatInputPart.js'; @@ -124,12 +127,14 @@ suite('ChatStatusPromo', () => { sinon.stub(widgets, 'getAllWidgets').callsFake(() => state.widgets); instantiation.stub(IChatWidgetService, widgets); instantiation.stub(IHoverService, options.hoverService ?? new class extends mock() { override hideHover() { } }()); + const contextKeys = store.add(new ContextKeyService(configuration)); + instantiation.stub(IContextKeyService, contextKeys); const promo = store.add(instantiation.createInstance(ChatStatusPromo)); let entry: ReturnType; const update = () => { entry = promo.getEntryProps(state.visible); }; store.add(promo.onDidChange(update)); update(); - return { promo, state, models, modelChanged, storage, configuration, treatment, refetch, warn, telemetry, widgets, widgetAdded, viewVisibility, update, get entry() { return entry; } }; + return { promo, state, models, modelChanged, storage, configuration, treatment, refetch, warn, telemetry, widgets, widgetAdded, contextKeys, viewVisibility, update, get entry() { return entry; } }; } function chatView(f: ReturnType, sessionType?: string, restored: Promise = Promise.resolve()) { @@ -268,6 +273,13 @@ suite('ChatStatusPromo', () => { }, { pip: false, sameTooltip: true, seen: '["sale"]', dismissed: undefined, events: ['chatPromoWidgetArmed', 'chatPromoWidgetShown'] }); }); + test('withdraws its offer as the Agents view replaces the Chat view, in which trying the model would open, as the Chat view hides', () => { + const f = fixture({ configured: ChatClosedPromoNotification.CopilotIconPopup }); + const offered = !!f.entry; + ChatContextKeys.agentsViewActive.bindTo(f.contextKeys).set(true); + assert.deepStrictEqual({ offered, replaced: f.entry }, { offered: true, replaced: undefined }); + }); + test('withdraws a displayed offer without dismissing it', () => { const f = fixture({ configured: ChatClosedPromoNotification.CopilotIconPopup }); f.entry!.tooltip.onDidShow?.(); diff --git a/src/vs/workbench/contrib/chat/test/browser/chatTipService.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatTipService.test.ts index e3fb740a5d57..e96e974f9287 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatTipService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatTipService.test.ts @@ -49,6 +49,9 @@ import { GENERATE_AGENT_INSTRUCTIONS_COMMAND_ID, GENERATE_PROMPT_COMMAND_ID } fr import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ResolvedKeybinding } from '../../../../../base/common/keybindings.js'; import { SEND_IN_BACKGROUND_COMMAND_ID } from '../../../sessions/common/sessionCommands.js'; +import { SESSIONS_SEND_LATER_ENABLED_SETTING } from '../../../sessions/common/sessionConfig.js'; +import { ChatInputCanScheduleContext } from '../../../sessions/common/contextkeys.js'; +import { ChatAutomationsEnabledContext } from '../../common/automations/automationsEnabled.js'; class MockContextKeyServiceWithRulesMatching extends MockContextKeyService { override contextMatchesRules(rules: ContextKeyExpression): boolean { @@ -436,6 +439,101 @@ suite('ChatTipService', () => { }); }); + test('navigates between a standalone provider tip and catalog tips without losing the selection on rerender', () => { + const service = createService(); + const contextualTip: IChatTip = { id: 'contextual.shortcut', content: new MarkdownString('Enable shortcut') }; + testDisposables.add(service.registerTipProvider({ + onDidChange: Event.None, + provideTip: () => contextualTip, + dismissTip: () => { }, + })); + service.getWelcomeTip(contextKeyService); + const enabled = service.hasMultipleTips(); + const next = service.navigateToNextTip(); + const rerendered = service.getWelcomeTip(contextKeyService); + const previous = service.navigateToPreviousTip(); + const wrapped = service.navigateToPreviousTip(); + const wrappedRerender = service.getWelcomeTip(contextKeyService); + const returned = service.navigateToNextTip(); + + assert.deepStrictEqual({ + enabled, + nextIsCatalog: next?.id.startsWith('tip.'), + rerenderKeepsSelection: rerendered?.id === next?.id, + previous: previous?.id, + wrappedIsCatalog: wrapped?.id.startsWith('tip.'), + wrappedRerenderKeepsSelection: wrappedRerender?.id === wrapped?.id, + returned: returned?.id, + }, { + enabled: true, + nextIsCatalog: true, + rerenderKeepsSelection: true, + previous: contextualTip.id, + wrappedIsCatalog: true, + wrappedRerenderKeepsSelection: true, + returned: contextualTip.id, + }); + }); + + test('disables navigation when a standalone provider tip is the only eligible tip', () => { + const service = createService(); + const contextualTip: IChatTip = { id: 'contextual.only', content: new MarkdownString('Only tip') }; + storageService.store('chat.tip.dismissed', JSON.stringify(TIP_CATALOG.map(tip => tip.id)), StorageScope.APPLICATION, StorageTarget.MACHINE); + testDisposables.add(service.registerTipProvider({ + onDidChange: Event.None, + provideTip: () => contextualTip, + dismissTip: () => { }, + })); + service.getWelcomeTip(contextKeyService); + + assert.deepStrictEqual({ + enabled: service.hasMultipleTips(), + next: service.navigateToNextTip(), + previous: service.navigateToPreviousTip(), + }, { enabled: false, next: undefined, previous: undefined }); + }); + + test('preserves navigation to a second standalone provider on rerender', () => { + const service = createService(); + for (const id of ['contextual.first', 'contextual.second']) { + testDisposables.add(service.registerTipProvider({ + onDidChange: Event.None, + provideTip: () => ({ id, content: new MarkdownString(id) }), + dismissTip: () => { }, + })); + } + service.getWelcomeTip(contextKeyService); + + assert.deepStrictEqual([ + service.navigateToNextTip()?.id, + service.getWelcomeTip(contextKeyService)?.id, + service.navigateToPreviousTip()?.id, + ], ['contextual.second', 'contextual.second', 'contextual.first']); + }); + + test('restores contextual tip priority when the provider changes or the session resets', () => { + const service = createService(); + const onDidChange = testDisposables.add(new Emitter()); + const contextualTip: IChatTip = { id: 'contextual.shortcut', content: new MarkdownString('Enable shortcut') }; + testDisposables.add(service.registerTipProvider({ + onDidChange: onDidChange.event, + provideTip: () => contextualTip, + dismissTip: () => { }, + })); + service.getWelcomeTip(contextKeyService); + service.navigateToNextTip(); + onDidChange.fire(); + const afterChange = service.getWelcomeTip(contextKeyService); + service.navigateToNextTip(); + service.resetSession(); + const afterReset = service.getWelcomeTip(contextKeyService); + + assert.deepStrictEqual({ afterChange: afterChange?.id, afterReset: afterReset?.id }, { + afterChange: contextualTip.id, + afterReset: contextualTip.id, + }); + }); + test('uses descriptive titles for tip command links', () => { for (const tip of TIP_CATALOG) { const markdown = tip.buildMessage({ @@ -542,6 +640,67 @@ suite('ChatTipService', () => { ); }); + test('automate tip is controlled by its experiment setting and limited to the Agents window with chat and automations enabled', () => { + const tip = TIP_CATALOG.find(tip => tip.id === 'tip.automate'); + assert.ok(tip?.when); + + const isEnabled = contextKeyService.createKey(`config.${ChatConfiguration.AutomateTipEnabled}`, true); + const isSessionsWindow = contextKeyService.createKey(IsSessionsWindowContext.key, false); + const isChatEnabled = contextKeyService.createKey(ChatContextKeys.enabled.key, false); + const isAutomationsEnabled = contextKeyService.createKey('chatAutomationsEnabled', false); + const eligibility = [contextKeyService.contextMatchesRules(tip.when)]; + + isSessionsWindow.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isChatEnabled.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isAutomationsEnabled.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isEnabled.set(false); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isEnabled.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isSessionsWindow.set(false); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isSessionsWindow.set(true); + isChatEnabled.set(false); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + + assert.deepStrictEqual(eligibility, [false, false, false, true, false, true, false, false]); + assert.strictEqual( + tip.buildMessage({ + keybindingService: { lookupKeybinding: () => undefined } as Partial as IKeybindingService, + experimentalTipMessages: new Map(), + }).value, + 'Use `/automate` to have the agent walk you through turning a task into a recurring automation.', + ); + }); + + test('send later tip requires the setting and a supported Agents window chat with AI and automations enabled', () => { + const tip = TIP_CATALOG.find(tip => tip.id === 'tip.sendLater'); + assert.ok(tip?.when); + + const isEnabled = contextKeyService.createKey(`config.${SESSIONS_SEND_LATER_ENABLED_SETTING}`, undefined); + const isSessionsWindow = contextKeyService.createKey(IsSessionsWindowContext.key, true); + const isChatEnabled = contextKeyService.createKey(ChatContextKeys.enabled.key, true); + const isAutomationsEnabled = contextKeyService.createKey(ChatAutomationsEnabledContext.key, true); + const canSchedule = contextKeyService.createKey(ChatInputCanScheduleContext.key, true); + const eligibility = [contextKeyService.contextMatchesRules(tip.when)]; + + isEnabled.set(false); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + isEnabled.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + for (const key of [isSessionsWindow, isChatEnabled, isAutomationsEnabled, canSchedule]) { + key.set(false); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + key.set(true); + eligibility.push(contextKeyService.contextMatchesRules(tip.when)); + } + + assert.deepStrictEqual(eligibility, [false, false, true, false, true, false, true, false, true, false, true]); + }); + test('records # file reference usage for attach files tip eligibility', () => { const submitRequestEmitter = testDisposables.add(new Emitter<{ readonly chatSessionResource: URI; readonly message?: IParsedChatRequest }>()); instantiationService.stub(IChatService, { diff --git a/src/vs/workbench/contrib/chat/test/browser/customAgentUsage.test.ts b/src/vs/workbench/contrib/chat/test/browser/customAgentUsage.test.ts new file mode 100644 index 000000000000..ce0455a99dc3 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/customAgentUsage.test.ts @@ -0,0 +1,82 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { InMemoryStorageService } from '../../../../../platform/storage/common/storage.js'; +import { TestProductService } from '../../../../test/common/workbenchTestServices.js'; +import { CustomAgentUsageContribution } from '../../browser/customAgentUsage.contribution.js'; +import { IChatRequestAcceptedEvent, IChatService } from '../../common/chatService/chatService.js'; +import { ChatModeKind } from '../../common/constants.js'; +import { CustomAgentUsage } from '../../common/customAgentUsage.js'; +import { ICustomizationHarnessService } from '../../common/customizationHarnessService.js'; +import { IChatRequestModeInfo } from '../../common/model/chatModel.js'; +import { IAgentSource, ICustomAgent, PromptsStorage } from '../../common/promptSyntax/service/promptsService.js'; + +suite('CustomAgentUsageContribution', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const chatExtensionId = 'github.copilot-chat'; + const sessionResource = URI.parse('vscode-chat-session://local/session'); + const chatExtensionSource: IAgentSource = { storage: PromptsStorage.extension, extensionId: new ExtensionIdentifier(chatExtensionId) }; + const agents: { uri: string; source: IAgentSource; sourceUri?: string }[] = [ + { uri: 'file:///workspace/.github/agents/reviewer.agent.md', source: { storage: PromptsStorage.local } }, + { uri: `file:///extensions/${chatExtensionId}/agents/plan.agent.md`, source: chatExtensionSource }, + { uri: 'file:///host/builtin/ask.agent.md', source: { storage: PromptsStorage.builtIn } }, + // An organization agent synced to an Agent Host is only recognizable by its original location. + { uri: 'agent-host:/synced/agents/security.agent.md', source: chatExtensionSource, sourceUri: `file:///user/globalStorage/${chatExtensionId}/github/contoso/agents/security.agent.md` }, + ]; + + const defaultMode: IChatRequestModeInfo = { kind: ChatModeKind.Agent, isBuiltin: true, modeInstructions: undefined, telemetryModeId: 'agent', applyCodeBlockSuggestionId: undefined }; + function customMode(uri: string): IChatRequestModeInfo { + return { kind: ChatModeKind.Agent, isBuiltin: false, modeInstructions: { uri: URI.parse(uri), name: '', content: '', toolReferences: [] }, telemetryModeId: 'custom', applyCodeBlockSuggestionId: undefined }; + } + + test('records the count and last use of agents not built into the product', async () => { + const storage = disposables.add(new InMemoryStorageService()); + const accepted = disposables.add(new Emitter()); + disposables.add(new CustomAgentUsageContribution( + upcastPartial({ onDidAcceptRequest: accepted.event }), + upcastPartial({ + getCustomAgents: async () => agents.map(({ uri, source, sourceUri }) => upcastPartial({ id: uri, uri: URI.parse(uri), source, sourceUri: sourceUri ? URI.parse(sourceUri) : undefined })), + }), + upcastPartial({ ...TestProductService, defaultChatAgent: upcastPartial>({ chatExtensionId }) }), + storage, + new NullLogService(), + )); + const usage = new CustomAgentUsage(storage); + const record = async (modeInfo: IChatRequestModeInfo | undefined) => { + const before = Date.now(); + accepted.fire({ chatSessionResource: sessionResource, isNewSession: false, modeInfo }); + await timeout(0); + return { count: usage.useCount, recordedNow: (usage.lastUsed ?? 0) >= before }; + }; + + assert.deepStrictEqual({ + noMode: await record(undefined), + defaultAgent: await record(defaultMode), + builtInExtensionAgent: await record(customMode(`file:///extensions/${chatExtensionId}/agents/plan.agent.md`)), + builtInHostAgent: await record(customMode('file:///host/builtin/ask.agent.md')), + workspaceAgent: await record(customMode('file:///workspace/.github/agents/reviewer.agent.md')), + syncedOrganizationAgent: await record(customMode('agent-host:/synced/agents/security.agent.md')), + unlistedAgent: await record(customMode('file:///removed.agent.md')), + }, { + noMode: { count: 0, recordedNow: false }, + defaultAgent: { count: 0, recordedNow: false }, + builtInExtensionAgent: { count: 0, recordedNow: false }, + builtInHostAgent: { count: 0, recordedNow: false }, + workspaceAgent: { count: 1, recordedNow: true }, + syncedOrganizationAgent: { count: 2, recordedNow: true }, + unlistedAgent: { count: 3, recordedNow: true }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/onboarding/agentPickerSpotlight.test.ts b/src/vs/workbench/contrib/chat/test/browser/onboarding/agentPickerSpotlight.test.ts new file mode 100644 index 000000000000..e335ee4549a7 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/onboarding/agentPickerSpotlight.test.ts @@ -0,0 +1,338 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { getWindow, scheduleAtNextAnimationFrame } from '../../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../../base/browser/window.js'; +import { ActionViewItem } from '../../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { ToolBar } from '../../../../../../base/browser/ui/toolbar/toolbar.js'; +import { Action } from '../../../../../../base/common/actions.js'; +import { DeferredPromise, retry, timeout } from '../../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { ConfigurationTarget } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IContextMenuProvider } from '../../../../../../base/browser/contextmenu.js'; +import { NullLogService } from '../../../../../../platform/log/common/log.js'; +import { InMemoryStorageService, StorageScope } from '../../../../../../platform/storage/common/storage.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { Memento } from '../../../../../common/memento.js'; +import { NullWorkbenchAssignmentService } from '../../../../../services/assignment/test/common/nullAssignmentService.js'; +import { DialogService } from '../../../../../services/dialogs/common/dialogService.js'; +import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; +import { TestHostService, TestLayoutService } from '../../../../../test/browser/workbenchTestServices.js'; +import { TestLifecycleService, TestProductService } from '../../../../../test/common/workbenchTestServices.js'; +import { OnboardingScenarioService } from '../../../../onboarding/browser/onboardingService.js'; +import { runWithOnboardingPresentation } from '../../../../onboarding/browser/onboardingPresentationQueue.js'; +import { resolveOnboardingTarget } from '../../../../onboarding/browser/spotlight/onboardingTarget.js'; +import { SpotlightPresentation } from '../../../../onboarding/browser/spotlight/spotlightPresentation.js'; +import { ISpotlightPayload, SPOTLIGHT_PRESENTATION_KIND } from '../../../../onboarding/browser/spotlight/spotlightTypes.js'; +import { onboardingPresentationRegistry } from '../../../../onboarding/common/onboardingPresentation.js'; +import { onboardingScenarioRegistry } from '../../../../onboarding/common/onboardingRegistry.js'; +import { IOnboardingScenario, OnboardingDismissReason, OnboardingOutcome } from '../../../../onboarding/common/onboardingScenario.js'; +import { ONBOARDING_ENABLED_CONFIG } from '../../../../onboarding/common/onboardingScenarioService.js'; +import { IChatWidget, IChatWidgetService } from '../../../browser/chat.js'; +import { AgentPickerSpotlight, AGENT_PICKER_SPOTLIGHT_ID } from '../../../browser/onboarding/agentPickerSpotlight.js'; +import { ChatInputPart } from '../../../browser/widget/input/chatInputPart.js'; +import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { ChatMode, IChatMode, IChatModes } from '../../../common/chatModes.js'; +import { CHAT_ATTACH_CONTEXT_ACTION_ID, ChatConfiguration } from '../../../common/constants.js'; +import { PromptsStorage } from '../../../common/promptSyntax/service/promptsService.js'; + +suite('AgentPickerSpotlight', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + teardown(() => Memento.clear(StorageScope.APPLICATION)); + + const custom: IChatMode = { ...ChatMode.Agent, id: 'custom-agent', isBuiltin: false }; + + function createHarness(enabled = true, initialCustomModes: readonly IChatMode[] = [custom]) { + const configuration = new TestConfigurationService({ [ChatConfiguration.AgentsPickerInAttachContextMenu]: enabled }); + store.add(configuration.onDidChangeConfigurationEmitter); + const root = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + store.add(toDisposable(() => root.remove())); + let button: HTMLElement; + let activations = 0; + const action = store.add(new Action(CHAT_ATTACH_CONTEXT_ACTION_ID, 'Add Context', undefined, true, async () => { activations++; })); + const toolbar = store.add(new ToolBar(root, upcastPartial({}), { + actionViewItemProvider: action => new class extends ActionViewItem { + override render(container: HTMLElement) { + super.render(container); + button = container; + button.style.cssText = 'width: 28px; height: 28px;'; + } + }(undefined, action, { label: true }), + })); + const executeToolbar = store.add(new ToolBar(root, upcastPartial({}))); + toolbar.setActions([action]); + const mode = observableValue('mode', ChatMode.Agent); + let visible = true; + let supported = true; + const changed = store.add(new Emitter()); + const buttonChanged = store.add(new Emitter()); + const modesChanged = store.add(new Emitter()); + let customModes = initialCustomModes; + const modes = observableValue('modes', upcastPartial({ + onDidChange: modesChanged.event, + get custom() { return customModes; }, + })); + const inputPart: ChatInputPart = Object.create(ChatInputPart.prototype, { + inputActionsToolbar: { value: toolbar }, + executeToolbar: { value: executeToolbar }, + currentModeObs: { get: () => mode }, + currentChatModesObs: { get: () => modes }, + isAgentPickerInAttachContextMenu: { get: () => supported && mode.get() === ChatMode.Agent }, + attachContextButtonElement: { get: () => button.isConnected ? button : undefined }, + onDidChangeAttachContextButton: { value: buttonChanged.event }, + }); + const widget = new class extends mock() { + override readonly domNode = root; + override get visible() { return visible; } + override readonly inputPart = inputPart; + }(); + const widgets = [widget]; + const widgetService = new class extends mock() { + override readonly onDidAddWidget = changed.event; + override readonly onDidRemoveWidget = changed.event; + override readonly onDidChangeWidgetVisibility = changed.event; + override readonly onDidChangeFocusedWidget = Event.None; + override getWidgetsByLocations() { return widgets; } + }(); + const spotlight = store.add(new AgentPickerSpotlight(configuration, widgetService, TestProductService)); + const scenario = onboardingScenarioRegistry.getScenario(AGENT_PICKER_SPOTLIGHT_ID) as IOnboardingScenario; + const signal = scenario.trigger.kind === 'observable' ? scenario.trigger.signal : undefined; + const frame = () => new Promise(resolve => store.add(scheduleAtNextAnimationFrame(getWindow(button), resolve))); + const setEnabled = async (value: boolean) => { + await configuration.setUserConfiguration(ChatConfiguration.AgentsPickerInAttachContextMenu, value); + configuration.onDidChangeConfigurationEmitter.fire({ + source: ConfigurationTarget.USER, + change: { keys: [ChatConfiguration.AgentsPickerInAttachContextMenu], overrides: [] }, + affectedKeys: new Set([ChatConfiguration.AgentsPickerInAttachContextMenu]), + affectsConfiguration: key => key === ChatConfiguration.AgentsPickerInAttachContextMenu, + }); + }; + return { + configuration, button: button!, mode, scenario, signal, frame, setEnabled, spotlight, root, toolbar, + modes, + setCustomModes: (value: readonly IChatMode[]) => { customModes = value; modesChanged.fire(); }, + activations: () => activations, + setVisible: (value: boolean) => { visible = value; changed.fire(widget); }, + setSupported: (value: boolean) => { supported = value; buttonChanged.fire(); }, + removeWidget: () => { widgets.length = 0; changed.fire(widget); }, + replaceButton: () => { + toolbar.setActions([action]); + buttonChanged.fire(); + return button; + }, + }; + } + + test('requires a custom agent and follows discovery, removal, and session modes', async () => { + const { signal, frame, modes, setCustomModes } = createHarness(true, []); + await frame(); + const empty = signal?.get(); + setCustomModes([{ ...custom, source: { storage: PromptsStorage.builtIn } }]); + await frame(); + const builtInOnly = signal?.get(); + setCustomModes([custom]); + await frame(); + const discovered = signal?.get(); + setCustomModes([]); + await frame(); + const removed = signal?.get(); + modes.set(upcastPartial({ custom: [custom], onDidChange: Event.None }), undefined); + await frame(); + const newSession = signal?.get(); + modes.set(upcastPartial({ custom: [], onDidChange: Event.None }), undefined); + await frame(); + assert.deepStrictEqual({ empty, builtInOnly, discovered, removed, newSession, emptySession: signal?.get() }, { + empty: false, builtInOnly: false, discovered: true, removed: false, newSession: true, emptySession: false, + }); + }); + + test('waits for layout and follows setting, mode, visibility, and placement support', async () => { + const { button, signal, frame, setEnabled, mode, setVisible, setSupported, removeWidget } = createHarness(false); + const states: boolean[] = []; + const record = () => states.push(!!signal?.get()); + await frame(); + record(); + await setEnabled(true); + record(); + await frame(); + record(); + assert.strictEqual(resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID)?.element, button); + mode.set(ChatMode.Ask, undefined); + record(); + mode.set(ChatMode.Agent, undefined); + await frame(); + record(); + setVisible(false); + record(); + setVisible(true); + await frame(); + record(); + setSupported(false); + record(); + setSupported(true); + await frame(); + await setEnabled(false); + record(); + await setEnabled(true); + await frame(); + removeWidget(); + record(); + assert.deepStrictEqual(states, [false, false, true, false, true, false, true, false, false, false]); + }); + + test('resolves the current + button when the toolbar rerenders after readiness', async () => { + const { frame, replaceButton, signal } = createHarness(); + await frame(); + const replacement = replaceButton(); + await frame(); + assert.deepStrictEqual({ + ready: signal?.get(), + currentTarget: resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID)?.element === replacement, + }, { ready: true, currentTarget: true }); + }); + + test('waits for a hidden composer to become visibly resolvable', async () => { + const { root, signal, frame } = createHarness(); + root.style.display = 'none'; + await frame(); + const hidden = { ready: signal?.get(), resolved: !!resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID) }; + root.style.display = ''; + await retry(async () => assert.strictEqual(signal?.get(), true), 20, 10); + assert.deepStrictEqual({ hidden, visible: !!resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID) }, { + hidden: { ready: false, resolved: false }, visible: true, + }); + }); + + test('does not consume readiness for a composer in another document', async () => { + const { root, signal, frame, setEnabled } = createHarness(false); + const auxiliaryDocument = mainWindow.document.implementation.createHTMLDocument(); + auxiliaryDocument.body.appendChild(root); + await setEnabled(true); + await frame(); + const auxiliary = signal?.get(); + mainWindow.document.body.appendChild(root); + await setEnabled(false); + await setEnabled(true); + await frame(); + assert.deepStrictEqual({ auxiliary, main: signal?.get() }, { auxiliary: false, main: true }); + }); + + test('honors AI and onboarding gates and persists once-only state across engine recreation', async () => { + const { configuration, frame, setEnabled, replaceButton } = createHarness(); + const context = store.add(new ContextKeyService(configuration)); + const aiEnabled = context.createKey(ChatContextKeys.enabled.key, false); + context.createKey(`config.${ChatConfiguration.AgentsPickerInAttachContextMenu}`, true); + const storage = store.add(new InMemoryStorageService()); + const runs: string[] = []; + let resolvedTarget: HTMLElement | undefined; + store.add(onboardingPresentationRegistry.register({ + kind: SPOTLIGHT_PRESENTATION_KIND, + run: async (scenario, runContext) => { + runs.push(scenario.id); + resolvedTarget = resolveOnboardingTarget(mainWindow, AGENT_PICKER_SPOTLIGHT_ID)?.element; + runContext.onDidShow?.(); + return { outcome: OnboardingOutcome.Completed, shown: true, dismissReason: OnboardingDismissReason.Completed, lastStepIndex: 0, stepCount: 1 }; + }, + })); + const createEngine = () => store.add(new OnboardingScenarioService( + storage, context, configuration, store.add(new TestLifecycleService()), + new NullWorkbenchAssignmentService(), NullTelemetryService, + store.add(new DialogService(new class extends mock() { }(), new NullLogService())), + )); + const finish = new DeferredPromise(); + store.add(toDisposable(() => { void finish.complete(); })); + const occupant = runWithOnboardingPresentation(mainWindow, CancellationToken.None, () => finish.p); + const first = createEngine(); + first.start(); + await frame(); + await timeout(0); + const whileAIHidden = runs.length; + await configuration.setUserConfiguration(ONBOARDING_ENABLED_CONFIG, false); + aiEnabled.set(true); + await timeout(0); + const whileOnboardingDisabled = runs.length; + await configuration.setUserConfiguration(ONBOARDING_ENABLED_CONFIG, true); + configuration.onDidChangeConfigurationEmitter.fire({ + source: ConfigurationTarget.USER, + change: { keys: [ONBOARDING_ENABLED_CONFIG], overrides: [] }, + affectedKeys: new Set([ONBOARDING_ENABLED_CONFIG]), + affectsConfiguration: key => key === ONBOARDING_ENABLED_CONFIG, + }); + await timeout(0); + const queued = { runs: runs.length, shown: first.hasBeenShown(AGENT_PICKER_SPOTLIGHT_ID) }; + const replacement = replaceButton(); + await frame(); + await finish.complete(); + await occupant; + await timeout(0); + first.dispose(); + Memento.clear(StorageScope.APPLICATION); + const second = createEngine(); + second.start(); + await setEnabled(false); + await setEnabled(true); + await frame(); + await timeout(0); + assert.deepStrictEqual({ whileAIHidden, whileOnboardingDisabled, queued, runs, replacedWhileQueued: resolvedTarget === replacement, persisted: second.hasBeenShown(AGENT_PICKER_SPOTLIGHT_ID) }, { + whileAIHidden: 0, whileOnboardingDisabled: 0, queued: { runs: 0, shown: false }, runs: [AGENT_PICKER_SPOTLIGHT_ID], replacedWhileQueued: true, persisted: true, + }); + }); + + for (const dismiss of ['understood', 'escape', 'target', 'enter', 'space', 'rerender'] as const) { + test(`shows the accessible tip after toolbar replacement and dismisses via ${dismiss}`, async () => { + const { scenario, frame, replaceButton, toolbar, activations } = createHarness(); + await frame(); + let button = replaceButton(); + await frame(); + toolbar.focus(); + const context = store.add(new ContextKeyService(new TestConfigurationService())); + const layout = new class extends TestLayoutService { + override getContainer() { return mainWindow.document.body; } + }(); + const presentation = store.add(new SpotlightPresentation(layout, new TestHostService(), context)); + const shown = new DeferredPromise(); + const result = presentation.run(scenario, { targetWindow: mainWindow, onAbort: Event.None, onDidShow: () => { void shown.complete(); } }); + await shown.p; + if (dismiss === 'rerender') { + button = replaceButton(); + await retry(async () => assert.notStrictEqual(button.id, ''), 20, 10); + } + const callout = mainWindow.document.querySelector('.spotlight-callout')!; + const description = mainWindow.document.getElementById(callout.getAttribute('aria-describedby')!); + const next = Array.from(callout.querySelectorAll('.monaco-button')).find(element => element.textContent === 'Understood')!; + const before = { role: callout.getAttribute('role'), description: description?.textContent, focused: mainWindow.document.activeElement === next }; + if (dismiss === 'target') { + button.querySelector('.action-label')!.click(); + } else if (dismiss === 'enter' || dismiss === 'space' || dismiss === 'rerender') { + toolbar.focus(); + const key = dismiss === 'space' ? ' ' : 'Enter'; + const keyCode = dismiss === 'space' ? 32 : 13; + for (const type of ['keydown', 'keyup']) { + mainWindow.document.activeElement!.dispatchEvent(new KeyboardEvent(type, { key, keyCode, bubbles: true })); + } + } else if (dismiss === 'understood') { + next.click(); + } else { + next.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + } + const outcome = (await result).outcome; + assert.deepStrictEqual({ before, outcome, restored: button.contains(mainWindow.document.activeElement), activations: activations() }, { + before: { role: 'dialog', description: 'We default to Agent, find your custom agents in the + menu', focused: true }, + outcome: dismiss === 'escape' ? OnboardingOutcome.Skipped : OnboardingOutcome.Completed, + restored: dismiss !== 'target', + activations: dismiss === 'understood' || dismiss === 'escape' ? 0 : 1, + }); + }); + } +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/plugins/pluginInstallService.test.ts b/src/vs/workbench/contrib/chat/test/browser/plugins/pluginInstallService.test.ts index f04df4556348..43a51de81a80 100644 --- a/src/vs/workbench/contrib/chat/test/browser/plugins/pluginInstallService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/plugins/pluginInstallService.test.ts @@ -1178,35 +1178,37 @@ suite('PluginInstallService', () => { }, { result: { updatedNames: [], failedNames: [] }, updated: [plugin], added: [] }); }); - test('uses the refreshed Git descriptor and replaces the old installed URI', async () => { - const plugin = createPlugin({ sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/repo', ref: 'main', path: 'plugins/test' } }); - const livePlugin = createPlugin({ sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/repo', ref: 'main', path: 'plugins/test', sha: 'new-sha' } }); - const oldUri = URI.file('/cache/ref_main/plugins/test'); - const newUri = URI.file('/cache/sha_new-sha/plugins/test'); - const { service, state } = createService({ - installedPlugins: [{ pluginUri: oldUri, plugin }], - fetchedMarketplacePlugins: [livePlugin], - pluginSourceInstallUris: new Map([[PluginSourceKind.GitHub, newUri]]), - ensurePluginSourceResult: newUri, - recordInstalledPlugins: true, - }); + for (const automatic of [false, true]) { + test(`uses the refreshed Git descriptor and replaces the old installed URI (${automatic ? 'automatic' : 'manual'})`, async () => { + const plugin = createPlugin({ sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/repo', ref: 'main', path: 'plugins/test' } }); + const livePlugin = createPlugin({ sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/repo', ref: 'main', path: 'plugins/test', sha: 'new-sha' } }); + const oldUri = URI.file('/cache/ref_main/plugins/test'); + const newUri = URI.file('/cache/sha_new-sha/plugins/test'); + const { service, state } = createService({ + installedPlugins: [{ pluginUri: oldUri, plugin }], + fetchedMarketplacePlugins: [livePlugin], + pluginSourceInstallUris: new Map([[PluginSourceKind.GitHub, newUri]]), + ensurePluginSourceResult: newUri, + recordInstalledPlugins: true, + }); - const result = await service.updateAllPlugins({ silent: true }, CancellationToken.None); + const result = await service.updateAllPlugins({ silent: true, automatic }, CancellationToken.None); - assert.deepStrictEqual({ - result, - ensured: state.ensurePluginSourceDescriptors, - installed: state.installedPlugins, - removed: state.removedPluginUris, - fetchOptions: state.fetchMarketplaceOptions, - }, { - result: { updatedNames: [plugin.name], failedNames: [] }, - ensured: [livePlugin.sourceDescriptor], - installed: [{ pluginUri: newUri, plugin: livePlugin }], - removed: [oldUri.toString()], - fetchOptions: [{ refresh: true }], + assert.deepStrictEqual({ + result, + ensured: state.ensurePluginSourceDescriptors, + installed: state.installedPlugins, + removed: state.removedPluginUris, + fetchOptions: state.fetchMarketplaceOptions, + }, { + result: { updatedNames: [plugin.name], failedNames: [] }, + ensured: [livePlugin.sourceDescriptor], + installed: [{ pluginUri: newUri, plugin: livePlugin }], + removed: [oldUri.toString()], + fetchOptions: [{ refresh: true, priority: automatic ? 'background' : undefined }], + }); }); - }); + } for (const kind of [PluginSourceKind.Npm, PluginSourceKind.Pip] as const) { for (const force of [false, true]) { @@ -1451,6 +1453,17 @@ suite('PluginInstallService', () => { suite('installPluginFromSource', () => { + for (const [source, descriptor] of [ + ['owner/collection#feature/beta', { kind: PluginSourceKind.GitHub, repo: 'owner/collection', ref: 'feature/beta' }], + ['https://example.com/collection.git#release/v1', { kind: PluginSourceKind.GitUrl, url: 'https://example.com/collection.git', ref: 'release/v1' }], + ] as const) { + test(`uses the requested revision for marketplace discovery: ${source}`, async () => { + const { service, state } = createService(); + await service.installPluginFromSource(source, { plugin: 'my-plugin' }); + assert.deepStrictEqual(state.ensurePluginSourceDescriptors, [descriptor]); + }); + } + test('rejects marketplace traversal before cloning a pinned source', async () => { const { service, state } = createService({ strictMarketplaces: [{ source: 'github', repo: 'microsoft/vscode', ref: 'marketplace' }], @@ -1471,9 +1484,9 @@ suite('PluginInstallService', () => { }); }); - test('keeps legacy source handling for repository-root plugins', async () => { + test('keeps the requested revision for repository-root plugins', async () => { const singlePlugin = createPlugin({ - sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/catalog' }, + sourceDescriptor: { kind: PluginSourceKind.GitHub, repo: 'owner/catalog', ref: 'release/v1' }, }); const { service, state } = createService({ singlePluginManifestResult: singlePlugin, @@ -1488,10 +1501,10 @@ suite('PluginInstallService', () => { }, { success: true, sources: [ - { kind: PluginSourceKind.GitHub, repo: 'owner/catalog' }, - { kind: PluginSourceKind.GitHub, repo: 'owner/catalog' }, + { kind: PluginSourceKind.GitHub, repo: 'owner/catalog', ref: 'release/v1' }, + { kind: PluginSourceKind.GitHub, repo: 'owner/catalog', ref: 'release/v1' }, ], - installedSource: { kind: PluginSourceKind.GitHub, repo: 'owner/catalog' }, + installedSource: { kind: PluginSourceKind.GitHub, repo: 'owner/catalog', ref: 'release/v1' }, }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/plugins/pluginUrlHandler.test.ts b/src/vs/workbench/contrib/chat/test/browser/plugins/pluginUrlHandler.test.ts index b2e7e3a66c42..6ae418bcbde5 100644 --- a/src/vs/workbench/contrib/chat/test/browser/plugins/pluginUrlHandler.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/plugins/pluginUrlHandler.test.ts @@ -7,189 +7,255 @@ import assert from 'assert'; import { DeferredPromise } from '../../../../../../base/common/async.js'; import { encodeBase64, VSBuffer } from '../../../../../../base/common/buffer.js'; import { CancellationError } from '../../../../../../base/common/errors.js'; -import { Event } from '../../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; import { observableValue } from '../../../../../../base/common/observable.js'; +import { isWeb } from '../../../../../../base/common/platform.js'; import { URI } from '../../../../../../base/common/uri.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IAgentHostService } from '../../../../../../platform/agentHost/common/agentService.js'; +import { CustomizationMarketplaceMediaType, ICustomizationMarketplaceQuery, ICustomizationMarketplaceService } from '../../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; +import { CustomizationMarketplaceConfiguration, CustomizationMarketplaceSources } from '../../../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; import { ICommandService } from '../../../../../../platform/commands/common/commands.js'; -import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService, IConfigurationUpdateOverrides } from '../../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; -import { CustomizationMarketplaceMediaType } from '../../../../../../platform/customizationMarketplace/common/customizationMarketplaceService.js'; import { IConfirmation, IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IPickOptions, IQuickInputService, IQuickPickItem } from '../../../../../../platform/quickinput/common/quickInput.js'; import { IURLService } from '../../../../../../platform/url/common/url.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import { IChatEntitlementService } from '../../../../../services/chat/common/chatEntitlementService.js'; -import { IHostService } from '../../../../../services/host/browser/host.js'; +import { IAuthenticationService } from '../../../../../services/authentication/common/authentication.js'; import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; -import { IAgentSessionsModel, IAgentSession } from '../../../browser/agentSessions/agentSessionsModel.js'; -import { IAgentSessionsService } from '../../../browser/agentSessions/agentSessionsService.js'; -import { IAgentHostNewSessionFolderService } from '../../../browser/agentSessions/agentHost/agentHostNewSessionFolderService.js'; -import { IAgentHostUntitledProvisionalSessionService } from '../../../browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.js'; +import { IHostService } from '../../../../../services/host/browser/host.js'; import { PluginUrlHandler } from '../../../browser/pluginUrlHandler.js'; +import { ICopilotConnectorsService } from '../../../browser/aiCustomization/copilotConnectorsService.js'; +import { CustomizationMarketplaceWorkbenchService, getProviderMarketplaceSourceId } from '../../../browser/aiCustomization/customizationMarketplaceWorkbenchService.js'; import { AICustomizationManagementCommands } from '../../../common/aiCustomizationWorkspaceService.js'; -import { IChatSessionsService, NEW_SESSION_IN_AGENTS_WINDOW_COMMAND_ID, SessionType } from '../../../common/chatSessionsService.js'; +import { SessionType } from '../../../common/chatSessionsService.js'; import { ChatConfiguration } from '../../../common/constants.js'; import { ICustomizationHarnessService, ICustomizationMarketplaceManagementProvider, IHarnessDescriptor } from '../../../common/customizationHarnessService.js'; import { ICustomizationMarketplaceInstallProvider } from '../../../common/customizationMarketplaceInstallService.js'; +import { IPluginInstallService } from '../../../common/plugins/pluginInstallService.js'; +import { IPluginMarketplaceService } from '../../../common/plugins/pluginMarketplaceService.js'; suite('PluginUrlHandler', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + const desktopTest = isWeb ? test.skip : test; const sessionResource = URI.parse(`${SessionType.AgentHostCopilot}:/existing`); - const draftResource = URI.parse(`${SessionType.AgentHostCopilot}:/untitled-new`); - const backendResource = URI.parse('ahp-session:/opaque-backend'); - const agentsDraftResource = URI.parse(`${SessionType.AgentHostCopilot}:/agents-draft`); function createHandler(options: { - activeResource?: URI; - existingSession?: boolean; - existingMarketplaceSource?: string; - archivedSession?: boolean; - provisional?: URI; - confirmations?: boolean[]; + harness?: 'copilot' | 'vscode'; + cancelPicker?: boolean; + confirmed?: boolean; confirmation?: Promise; + existingMarketplaceSource?: string; + existingMarketplaceIsDefault?: boolean; + existingMarketplaceManaged?: boolean; hidden?: boolean; disabledInWorkspace?: boolean; pluginsEnabled?: boolean; - available?: boolean; managementUnavailable?: boolean; installUnavailable?: boolean; - pluginMissing?: boolean; - paginated?: boolean; - createFailed?: boolean; + marketplaceTrusted?: boolean; + installResult?: { success: boolean; message?: string }; + remoteAuthority?: string; isSessionsWindow?: boolean; - backendFailed?: boolean; - failure?: 'list' | 'add' | 'query' | 'install'; + failure?: 'list' | 'add' | 'browse' | 'agentFinderQuery' | 'install'; + agentFinderAvailable?: boolean; + agentFinderEnabled?: boolean; + agentFinderMatchCount?: number; + agentFinderIdentity?: string | null; + agentFinderProviderPlugin?: boolean; + agentFinderProviderPluginSource?: string; + agentFinderBrowseError?: boolean; + agentFinderBrowseDuplicate?: boolean; + agentFinderPaginated?: boolean; + agentFinderSourceError?: boolean; cancelled?: boolean; } = {}) { const instantiationService = store.add(new TestInstantiationService()); - const calls: string[] = []; + const calls: unknown[] = []; const dialogs: IConfirmation[] = []; const errors: string[] = []; const commands: { id: string; args: unknown[] }[] = []; - const confirmations = [...(options.confirmations ?? [true, true])]; + const picks: { items: readonly IQuickPickItem[]; activeLabel?: string }[] = []; const fail = (phase: typeof options.failure) => { if (phase === options.failure) { throw options.cancelled ? new CancellationError() : new Error(`${phase} failed`); } }; - - const managementProvider: ICustomizationMarketplaceManagementProvider = { - onDidChange: Event.None, - onDidChangeMarketplaces: Event.None, - list: async () => { + let marketplaces = options.existingMarketplaceSource ? [{ + name: 'catalog', source: options.existingMarketplaceSource, isDefault: options.existingMarketplaceIsDefault ?? false, managed: options.existingMarketplaceManaged ?? false, available: true, + }] : []; + instantiationService.stub(IAgentHostService, { + listPluginMarketplaces: options.managementUnavailable ? undefined : async (provider, session, chat) => { + calls.push(['list', provider, session, chat]); fail('list'); - return options.existingMarketplaceSource ? [{ - name: 'catalog', - source: options.existingMarketplaceSource, - isDefault: false, - managed: false, - available: true, - }] : []; + return marketplaces; }, - add: async (session, source) => { - calls.push(`add:${session}:${source}`); + addPluginMarketplace: async (provider, session, source, chat) => { + calls.push(['add', provider, session, source, chat]); fail('add'); - return { name: 'catalog', source, isDefault: false, managed: false, available: true }; + const marketplace = { name: 'catalog', source, isDefault: false, managed: false, available: true }; + marketplaces = [...marketplaces, marketplace]; + return marketplace; }, - queryMarketplace: async (session, marketplace, query) => { - calls.push(`query:${session}:${marketplace.name}:${query.cursor ?? ''}`); - fail('query'); + browsePluginMarketplace: async (provider, session, name, chat) => { + calls.push(['browse', provider, session, name, chat]); + fail('browse'); + return [{ name: 'my-plugin' }, { name: 'other-plugin' }]; + }, + installPlugin: options.installUnavailable ? undefined : async (provider, request, session, chat) => { + calls.push(['install', provider, request, session, chat]); + fail('install'); + }, + }); + const marketplaceSources = options.agentFinderAvailable ? [CustomizationMarketplaceSources.AgentFinderPublicFeed] : []; + const agentFinderProviderPlugin = { + identifier: 'agentFinder/accessibility-agents', + displayName: 'Accessibility Agents', + description: '', + mediaType: CustomizationMarketplaceMediaType.CopilotPlugin, + sourceId: CustomizationMarketplaceSources.AgentFinderPublicFeed.id, + tags: [], + capabilities: [], + representativeQueries: [], + installation: { + kind: 'providerPlugin' as const, + name: 'accessibility-agents', + marketplace: 'awesome-copilot', + marketplaceSource: options.agentFinderProviderPluginSource ?? 'GitHub: github/awesome-copilot', + }, + }; + instantiationService.stub(ICustomizationMarketplaceService, new class extends mock() { + override readonly sources = marketplaceSources; + override async query(query: ICustomizationMarketplaceQuery) { + calls.push(`agentFinderQuery:${query.query ?? ''}:${query.cursor?.token ?? ''}`); + fail('agentFinderQuery'); + const paginatedFirstPage = options.agentFinderPaginated && !query.cursor; return { - items: options.pluginMissing || (options.paginated && !query.cursor) ? [] : [{ - identifier: 'catalog/my-plugin', + items: Array.from({ length: options.agentFinderMatchCount ?? 1 }, (_, index) => ({ + identifier: `agentFinder/my-plugin-${index}`, displayName: 'My Plugin', description: '', mediaType: CustomizationMarketplaceMediaType.CopilotPlugin, + sourceId: CustomizationMarketplaceSources.AgentFinderPublicFeed.id, tags: [], capabilities: [], representativeQueries: [], - installation: { kind: 'providerPlugin', name: 'my-plugin', marketplace: marketplace.name, marketplaceSource: marketplace.source }, - }], - nextCursor: options.paginated && !query.cursor ? 'next' : undefined, + installation: { + kind: 'providerCatalog' as const, + resourceKind: 'plugin' as const, + selectionId: `my-plugin-${index}`, + catalogIdentity: options.agentFinderIdentity === null ? undefined : options.agentFinderIdentity ?? `urn:air:github.com:github:awesome-copilot:${paginatedFirstPage ? 'other-plugin' : 'my-plugin'}`, + }, + })), + ...(paginatedFirstPage ? { nextCursor: { token: 'next' } } : {}), + ...(options.agentFinderSourceError ? { sourceErrors: [{ sourceId: CustomizationMarketplaceSources.AgentFinderPublicFeed.id, message: 'feed failed' }] } : {}), }; - }, - remove: async () => ({ removed: false }), - refresh: async () => [], - }; - const installProvider: ICustomizationMarketplaceInstallProvider = { - onDidChange: Event.None, - getInstallations: async () => [], - install: async (session, resource) => { + } + override async getBrowseSections() { + calls.push('agentFinderBrowse'); + return { + sourceId: CustomizationMarketplaceSources.AgentFinderPublicFeed.id, + sections: options.agentFinderProviderPlugin ? [ + { id: 'featured', title: 'Featured', items: [agentFinderProviderPlugin] }, + ...(options.agentFinderBrowseDuplicate ? [{ id: 'more', title: 'More', items: [agentFinderProviderPlugin] }] : []), + ] : [], + ...(options.agentFinderBrowseError ? { error: 'browse failed' } : {}), + }; + } + }()); + const marketplaceChanges = store.add(new Emitter()); + const managementProvider = new class extends mock() { + override readonly onDidChange = Event.None; + override readonly onDidChangeMarketplaces = marketplaceChanges.event; + override async list(session: URI) { + return instantiationService.get(IAgentHostService).listPluginMarketplaces!('copilotcli', session); + } + override async add(session: URI | undefined, source: string) { + const marketplace = await instantiationService.get(IAgentHostService).addPluginMarketplace!('copilotcli', session, source); + marketplaceChanges.fire(); + return marketplace; + } + }(); + const installProvider = new class extends mock() { + override readonly onDidChange = Event.None; + override async install(session: URI, resource: Parameters[1]) { calls.push(`install:${session}:${resource.identifier}`); fail('install'); - }, - repair: async () => { }, - uninstall: async () => { }, - }; - const harness: IHarnessDescriptor = { - id: SessionType.AgentHostCopilot, - label: 'Copilot', - icon: { id: 'copilot' }, - marketplaceManagementProvider: options.managementUnavailable ? undefined : managementProvider, + } + }(); + const descriptor: IHarnessDescriptor = { + id: SessionType.AgentHostCopilot, label: 'Copilot', icon: { id: 'copilot' }, marketplaceManagementProvider: managementProvider, marketplaceInstallProvider: options.installUnavailable ? undefined : installProvider, }; - instantiationService.stub(ICustomizationHarnessService, { - activeSessionResource: observableValue('activeSession', options.activeResource ?? sessionResource), - getDescriptorForSession: () => harness, - }); - const existing = new class extends mock() { - override readonly resource = sessionResource; - override readonly providerType = SessionType.AgentHostCopilot; - override isArchived() { return options.archivedSession ?? false; } - }(); - instantiationService.stub(IAgentSessionsService, { - model: new class extends mock() { - override readonly sessions = options.existingSession ? [existing] : []; - override async resolve() { calls.push('resolve'); } - }(), + const harnessService = instantiationService.stub(ICustomizationHarnessService, { + activeHarness: observableValue('harness', descriptor.id), + activeSessionResource: observableValue('activeSession', sessionResource), + availableHarnesses: observableValue('harnesses', [descriptor]), + getDescriptorForSession: () => descriptor, + getSessionResourceForHarness: () => sessionResource, }); - instantiationService.stub(IChatSessionsService, { - canResolveChatSession: async type => { - assert.strictEqual(type, SessionType.AgentHostCopilot); - return options.available ?? true; + instantiationService.stub(IPluginInstallService, { + ensureMarketplaceTrusted: async reference => { + calls.push(['trustMarketplace', reference.rawValue]); + return options.marketplaceTrusted ?? true; }, - }); - instantiationService.stub(IAgentHostUntitledProvisionalSessionService, { - get: () => options.provisional, - getOrCreate: async (resource, provider, folder) => { - calls.push(`create:${resource}:${provider}:${folder}`); - return options.backendFailed ? undefined : backendResource; + installPluginFromSource: async (source, installOptions) => { + calls.push(['vscodeInstall', source, installOptions]); + fail('install'); + return options.installResult ?? { success: true }; }, }); - instantiationService.stub(IAgentHostNewSessionFolderService, { - resolveNewSessionPrimary: () => URI.file('/workspace'), + instantiationService.stub(IQuickInputService, new class extends mock() { }()); + instantiationService.stub(IQuickInputService, 'pick', async (items: IQuickPickItem[], pickOptions?: IPickOptions) => { + const activeItem = await pickOptions?.activeItem; + picks.push({ items, activeLabel: activeItem?.label }); + return options.cancelPicker ? undefined : options.harness + ? items.find(item => item.label === (options.harness === 'copilot' ? 'Copilot' : 'VS Code')) + : activeItem; }); instantiationService.stub(IURLService, { registerHandler: () => ({ dispose() { } }) }); instantiationService.stub(IDialogService, { confirm: async confirmation => { dialogs.push(confirmation); - return { confirmed: options.confirmation ? await options.confirmation : confirmations.shift() ?? false }; + return { confirmed: options.confirmation ? await options.confirmation : options.confirmed ?? true }; }, }); - instantiationService.stub(IConfigurationService, new TestConfigurationService({ + const configuration = new class extends TestConfigurationService { + override async updateValue(key: string, value: unknown, overridesOrTarget?: ConfigurationTarget | IConfigurationOverrides | IConfigurationUpdateOverrides): Promise { + assert.strictEqual(overridesOrTarget, ConfigurationTarget.USER); + await this.setUserConfiguration(key, value); + } + }({ [ChatConfiguration.PluginsEnabled]: options.pluginsEnabled ?? true, - })); + [ChatConfiguration.PluginMarketplaces]: options.existingMarketplaceSource ? [options.existingMarketplaceSource] : [], + [CustomizationMarketplaceConfiguration.MarketplaceEnabled]: true, + [CustomizationMarketplaceConfiguration.AgentFinderPublicFeedEnabled]: options.agentFinderEnabled ?? true, + }); + instantiationService.stub(IConfigurationService, configuration); instantiationService.stub(IChatEntitlementService, { sentiment: { hidden: options.hidden, disabledInWorkspace: options.disabledInWorkspace } }); instantiationService.stub(ICommandService, new class extends mock() { }()); instantiationService.stub(ICommandService, 'executeCommand', async (id: string, ...args: unknown[]) => { - commands.push({ id, args }); - if (id === NEW_SESSION_IN_AGENTS_WINDOW_COMMAND_ID) { - return options.createFailed ? undefined : agentsDraftResource; - } - if (id === `workbench.action.chat.openNewSessionEditor.${SessionType.AgentHostCopilot}`) { - return options.createFailed ? undefined : draftResource; - } assert.strictEqual(id, AICustomizationManagementCommands.OpenEditor); - return undefined; + commands.push({ id, args }); + }); + instantiationService.stub(IWorkspaceTrustManagementService, { + isWorkspaceTrusted: () => false, + onDidChangeTrust: Event.None, + setWorkspaceTrust: async () => { throw new Error('Plugin links must not trust the workspace'); }, }); - instantiationService.stub(IWorkbenchEnvironmentService, { isSessionsWindow: options.isSessionsWindow ?? false }); + instantiationService.stub(IWorkbenchEnvironmentService, { remoteAuthority: options.remoteAuthority, isSessionsWindow: options.isSessionsWindow ?? false }); instantiationService.stub(IHostService, { focus: async () => { } }); instantiationService.stub(ILogService, new NullLogService()); instantiationService.stub(INotificationService, { error: message => { errors.push(String(message)); } }); - return { handler: store.add(instantiationService.createInstance(PluginUrlHandler)), calls, dialogs, errors, commands }; + return { handler: store.add(instantiationService.createInstance(PluginUrlHandler)), calls, dialogs, errors, commands, picks, configuration, harnessService, instantiationService }; } function uri(path = '/add-marketplace', query = 'ref=acme/plugins'): URI { @@ -204,6 +270,60 @@ suite('PluginUrlHandler', () => { ], [false, false]); }); + (isWeb ? test : test.skip)('rejects web plugin links before selection, consent, or mutation', async () => { + const fixture = createHandler(); + await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin&harness=copilot')); + assert.deepStrictEqual({ picks: fixture.picks.length, dialogs: fixture.dialogs.length, calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { + picks: 0, + dialogs: 0, + calls: [], + commands: [], + errors: ['Unable to complete the plugin link: Open this plugin link in a local VS Code desktop window. Plugin links do not install into a remote workspace or web environment.'], + }); + }); + + desktopTest('refreshes Discover sources for an add-only link while Copilot is already selected', async () => { + const fixture = createHandler(); + const activeSession = fixture.harnessService.activeSessionResource.get(); + const marketplaceService = store.add(new CustomizationMarketplaceWorkbenchService( + fixture.configuration, + new class extends mock() { + override readonly sources = []; + }(), + new class extends mock() { + override readonly onDidChangeMarketplaces = Event.None; + override isStrictMarketplacePolicyActive() { return false; } + }(), + new class extends mock() { }(), + fixture.harnessService, + fixture.instantiationService, + new class extends mock() { + override readonly onDidChangeDefaultAccount = Event.None; + }(), + new class extends mock() { + override readonly onDidChangeSessions = Event.None; + }(), + NullTelemetryService, + )); + const sourceId = getProviderMarketplaceSourceId('catalog'); + const before = marketplaceService.sources.some(source => source.id === sourceId); + const refreshed = new DeferredPromise(); + store.add(marketplaceService.onDidChangeSources(() => { + if (marketplaceService.sources.some(source => source.id === sourceId)) { + refreshed.complete(); + } + })); + + await fixture.handler.handleURL(uri('/add-marketplace', 'ref=acme/plugins&harness=copilot')); + await refreshed.p; + assert.deepStrictEqual({ + before, + after: marketplaceService.sources.some(source => source.id === sourceId), + sameSession: fixture.harnessService.activeSessionResource.get() === activeSession, + errors: fixture.errors, + }, { before: false, after: true, sameSession: true, errors: [] }); + }); + for (const [source, expectedSource] of [ ['acme/plugins', 'acme/plugins'], [encodeBase64(VSBuffer.fromString('acme/plugins')), 'acme/plugins'], @@ -212,105 +332,405 @@ suite('PluginUrlHandler', () => { [encodeBase64(VSBuffer.fromString('acme/plugins#feature/beta')), 'acme/plugins#feature/beta'], ['https://github.com/acme/plugins.git#v1.2.3', 'https://github.com/acme/plugins.git#v1.2.3'], ]) { - test(`adds marketplace through the active harness: ${source}`, async () => { - const fixture = createHandler(); - assert.strictEqual(await fixture.handler.handleURL(uri('/add-marketplace', `ref=${encodeURIComponent(source)}`)), true); + for (const harness of ['copilot', 'vscode'] as const) { + desktopTest(`adds the exact marketplace for ${harness}: ${source}`, async () => { + const fixture = createHandler({ harness }); + await fixture.handler.handleURL(uri('/add-marketplace', `ref=${encodeURIComponent(source)}`)); + assert.deepStrictEqual({ + calls: fixture.calls, + marketplaces: fixture.configuration.getValue(ChatConfiguration.PluginMarketplaces), + errors: fixture.errors, + commands: fixture.commands, + }, { + calls: harness === 'copilot' + ? [['list', 'copilotcli', undefined, undefined], ['add', 'copilotcli', undefined, expectedSource, undefined]] + : [['trustMarketplace', expectedSource]], + marketplaces: harness === 'copilot' ? [] : [expectedSource], + errors: [], + commands: [{ + id: AICustomizationManagementCommands.OpenEditor, + args: [{ showDiscover: true, sessionType: harness === 'copilot' ? SessionType.AgentHostCopilot : SessionType.Local, searchQuery: '' }], + }], + }); + }); + } + } + + for (const isSessionsWindow of [false, true]) { + desktopTest(`installs the exact Copilot plugin without a session in a restricted workspace (Agents window: ${isSessionsWindow})`, async () => { + const fixture = createHandler({ isSessionsWindow }); + await fixture.handler.handleURL(uri('/install', 'source=acme%2Fplugins%23feature%2Fbeta&plugin=my-plugin&harness=copilot')); + assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs.length, errors: fixture.errors }, { + calls: [ + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, 'acme/plugins#feature/beta', undefined], + ['browse', 'copilotcli', undefined, 'catalog', undefined], + ['install', 'copilotcli', { source: 'my-plugin@catalog' }, undefined, undefined], + ], + dialogs: 1, + errors: [], + }); + assert.ok(typeof fixture.dialogs[0].detail === 'string' && fixture.dialogs[0].detail.includes('Copilot\'s user installation on this machine')); + }); + } + + desktopTest('uses the VS Code source installer with the exact plugin and revision', async () => { + const fixture = createHandler(); + await fixture.handler.handleURL(uri('/install', 'source=acme%2Fplugins%23feature%2Fbeta&plugin=my-plugin&harness=vscode')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { + calls: [['vscodeInstall', 'acme/plugins#feature/beta', { plugin: 'my-plugin' }]], + errors: [], + }); + assert.ok(typeof fixture.dialogs[0].detail === 'string' && fixture.dialogs[0].detail.includes('VS Code\'s shared plugin installation on this machine')); + }); + + for (const source of ['GitHub: acme/plugins', 'GitHub: acme/plugins#other']) { + desktopTest(`does not confuse ${source} with the requested revision`, async () => { + const fixture = createHandler({ existingMarketplaceSource: source }); + await fixture.handler.handleURL(uri('/add-marketplace', 'ref=acme%2Fplugins%23feature%2Fbeta')); + assert.deepStrictEqual(fixture.calls, [ + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, 'acme/plugins#feature/beta', undefined], + ]); + }); + } + + for (const source of ['acme/plugins#feature/beta', 'GitHub: acme/plugins#feature/beta', 'URL: https://github.com/ACME/plugins.git#feature/beta']) { + desktopTest(`reuses an exact Copilot marketplace identity: ${source}`, async () => { + const fixture = createHandler({ existingMarketplaceSource: source }); + await fixture.handler.handleURL(uri('/install', 'source=acme%2Fplugins%23feature%2Fbeta&plugin=my-plugin')); + assert.deepStrictEqual(fixture.calls, [ + ['list', 'copilotcli', undefined, undefined], + ['browse', 'copilotcli', undefined, 'catalog', undefined], + ['install', 'copilotcli', { source: 'my-plugin@catalog' }, undefined, undefined], + ]); + }); + } + + for (const source of [ + 'github/awesome-copilot', + 'GitHub:github/awesome-copilot', + 'GitHub: github/awesome-copilot', + 'URL:https://github.com/GitHub/Awesome-Copilot.git', + 'URL: https://github.com/GitHub/Awesome-Copilot.git', + ]) { + desktopTest(`resolves a legacy Awesome Copilot plugin name through Agent Finder: ${source}`, async () => { + const fixture = createHandler({ agentFinderAvailable: true, managementUnavailable: true, agentFinderIdentity: 'urn:air:github.com:github:awesome-copilot:MY-PLUGIN' }); + await fixture.handler.handleURL(uri('/install', `source=${encodeURIComponent(source)}&plugin=my-plugin`)); assert.deepStrictEqual({ calls: fixture.calls, - dialogs: fixture.dialogs.length, errors: fixture.errors, commands: fixture.commands, }, { - calls: [`add:${sessionResource}:${expectedSource}`], - dialogs: 1, + calls: [ + 'agentFinderQuery:my-plugin:', + `install:${sessionResource}:agentFinder/my-plugin-0`, + ], errors: [], commands: [{ id: AICustomizationManagementCommands.OpenEditor, - args: [{ showDiscover: true, sessionResource, searchQuery: '' }], + args: [{ showDiscover: true, sessionType: SessionType.AgentHostCopilot, searchQuery: 'my-plugin' }], }], }); }); } - test('adds the marketplace before installing the exact catalog plugin', async () => { - const fixture = createHandler({ paginated: true }); - await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); - assert.deepStrictEqual(fixture.calls, [ - `add:${sessionResource}:acme/plugins`, - `query:${sessionResource}:catalog:`, - `query:${sessionResource}:catalog:next`, - `install:${sessionResource}:catalog/my-plugin`, - ]); - assert.ok(fixture.dialogs[0].message.includes('my-plugin')); - assert.deepStrictEqual(fixture.errors, []); + desktopTest('keeps an explicit VS Code target on its source installer when Agent Finder is available', async () => { + const fixture = createHandler({ agentFinderAvailable: true }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin&harness=vscode')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { + calls: [['vscodeInstall', 'github/awesome-copilot', { plugin: 'my-plugin' }]], + errors: [], + }); }); - for (const existingMarketplaceSource of ['GitHub: acme/plugins', 'GitHub: acme/plugins#other']) { - test(`registers the requested revision before installing from ${existingMarketplaceSource}`, async () => { - const fixture = createHandler({ existingMarketplaceSource }); - await fixture.handler.handleURL(uri('/install', 'source=acme%2Fplugins%23feature%2Fbeta&plugin=my-plugin')); + desktopTest('adds an Awesome Copilot marketplace without using Agent Finder or creating a session', async () => { + const fixture = createHandler({ agentFinderAvailable: true }); + await fixture.handler.handleURL(uri('/add-marketplace', 'ref=github%2Fawesome-copilot&harness=copilot')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { + calls: [ + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, 'github/awesome-copilot', undefined], + ], + errors: [], + }); + }); + + desktopTest('resolves a full Awesome Copilot catalog identity through Agent Finder', async () => { + const catalogIdentity = 'urn:air:github.com:github:awesome-copilot:my-plugin'; + const fixture = createHandler({ agentFinderAvailable: true, managementUnavailable: true, agentFinderIdentity: catalogIdentity.toUpperCase() }); + await fixture.handler.handleURL(uri('/install', `source=github%2Fawesome-copilot&plugin=${encodeURIComponent(catalogIdentity)}`)); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors, + }, { + calls: [ + `agentFinderQuery:${catalogIdentity}:`, + `install:${sessionResource}:agentFinder/my-plugin-0`, + ], + errors: [], + }); + }); + + desktopTest('rejects an external listing with the same name from another Agent Finder marketplace', async () => { + const fixture = createHandler({ + agentFinderAvailable: true, + agentFinderMatchCount: 0, + agentFinderProviderPlugin: true, + agentFinderProviderPluginSource: 'GitHub: other/marketplace', + }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=accessibility-agents')); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors.length, + commands: fixture.commands, + }, { + calls: [ + 'agentFinderQuery:accessibility-agents:', + 'agentFinderBrowse', + ], + errors: 1, + commands: [], + }); + }); + + for (const options of [ + { agentFinderAvailable: false }, + { agentFinderAvailable: true, agentFinderEnabled: false }, + ]) { + desktopTest(`falls back to the configured Awesome Copilot marketplace when Agent Finder is unavailable: ${JSON.stringify(options)}`, async () => { + const fixture = createHandler(options); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin')); assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { calls: [ - `add:${sessionResource}:acme/plugins#feature/beta`, - `query:${sessionResource}:catalog:`, - `install:${sessionResource}:catalog/my-plugin`, + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, 'github/awesome-copilot', undefined], + ['browse', 'copilotcli', undefined, 'catalog', undefined], + ['install', 'copilotcli', { source: 'my-plugin@catalog' }, undefined, undefined], ], errors: [], }); }); } - test('reuses an exact registered revision', async () => { - const fixture = createHandler({ existingMarketplaceSource: 'GitHub: acme/plugins#feature/beta' }); - await fixture.handler.handleURL(uri('/install', 'source=acme%2Fplugins%23feature%2Fbeta&plugin=my-plugin')); - assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { - calls: [`query:${sessionResource}:catalog:`, `install:${sessionResource}:catalog/my-plugin`], + desktopTest('resolves an external Awesome Copilot listing through Agent Finder browse metadata', async () => { + const fixture = createHandler({ + agentFinderAvailable: true, + managementUnavailable: true, + agentFinderMatchCount: 0, + agentFinderProviderPlugin: true, + }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=accessibility-agents')); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors, + commands: fixture.commands, + }, { + calls: [ + 'agentFinderQuery:accessibility-agents:', + 'agentFinderBrowse', + `install:${sessionResource}:agentFinder/accessibility-agents`, + ], errors: [], + commands: [{ + id: AICustomizationManagementCommands.OpenEditor, + args: [{ showDiscover: true, sessionType: SessionType.AgentHostCopilot, searchQuery: 'accessibility-agents' }], + }], }); }); - for (const existingMarketplaceSource of ['acme/plugins', 'https://github.com/ACME/plugins.git', 'GitHub: acme/plugins', 'URL: https://github.com/ACME/plugins.git']) { - test(`reuses the registered marketplace and opens customizations in the Agents window: ${existingMarketplaceSource}`, async () => { - const fixture = createHandler({ existingMarketplaceSource, isSessionsWindow: true }); - await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); + for (const options of [ + { agentFinderMatchCount: 0 }, + { agentFinderMatchCount: 2 }, + { agentFinderMatchCount: 1, agentFinderIdentity: 'my-plugin' }, + { agentFinderMatchCount: 1, agentFinderIdentity: 'other-plugin' }, + { agentFinderMatchCount: 1, agentFinderIdentity: 'urn:air:github.com:other:awesome-copilot:my-plugin' }, + { agentFinderMatchCount: 1, agentFinderIdentity: null }, + { agentFinderMatchCount: 1, agentFinderSourceError: true }, + ] as const) { + desktopTest(`rejects invalid Agent Finder resolution without adding the legacy marketplace: ${JSON.stringify(options)}`, async () => { + const fixture = createHandler({ agentFinderAvailable: true, ...options }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin')); assert.deepStrictEqual({ calls: fixture.calls, + errors: fixture.errors.length, commands: fixture.commands, - errors: fixture.errors, }, { - calls: [`query:${sessionResource}:catalog:`, `install:${sessionResource}:catalog/my-plugin`], - commands: [{ - id: AICustomizationManagementCommands.OpenEditor, - args: [{ showDiscover: true, sessionResource, searchQuery: 'my-plugin' }], - }], - errors: [], + calls: options.agentFinderMatchCount === 0 || options.agentFinderIdentity === 'my-plugin' || + options.agentFinderIdentity === 'other-plugin' || + options.agentFinderIdentity === 'urn:air:github.com:other:awesome-copilot:my-plugin' || + options.agentFinderIdentity === null + ? ['agentFinderQuery:my-plugin:', 'agentFinderBrowse'] + : ['agentFinderQuery:my-plugin:'], + errors: 1, + commands: [], }); }); } - test('opens customizations for an already registered add-only marketplace', async () => { - const fixture = createHandler({ existingMarketplaceSource: 'GitHub: acme/plugins', isSessionsWindow: true }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual({ calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { - calls: [], - commands: [{ - id: AICustomizationManagementCommands.OpenEditor, - args: [{ showDiscover: true, sessionResource, searchQuery: '' }], - }], + desktopTest('rejects a full Agent Finder identity from another repository', async () => { + const catalogIdentity = 'urn:air:github.com:other:awesome-copilot:my-plugin'; + const fixture = createHandler({ agentFinderAvailable: true, agentFinderIdentity: catalogIdentity }); + await fixture.handler.handleURL(uri('/install', `source=github%2Fawesome-copilot&plugin=${encodeURIComponent(catalogIdentity)}`)); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors.length, + commands: fixture.commands, + }, { + calls: [`agentFinderQuery:${catalogIdentity}:`], + errors: 1, + commands: [], + }); + }); + + desktopTest('surfaces Agent Finder browse failures without adding the legacy marketplace', async () => { + const fixture = createHandler({ + agentFinderAvailable: true, + agentFinderMatchCount: 0, + agentFinderBrowseError: true, + }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin')); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors.length, + commands: fixture.commands, + }, { + calls: ['agentFinderQuery:my-plugin:', 'agentFinderBrowse'], + errors: 1, + commands: [], + }); + }); + + desktopTest('deduplicates an external Awesome Copilot listing across Agent Finder browse sections', async () => { + const fixture = createHandler({ + agentFinderAvailable: true, + managementUnavailable: true, + agentFinderMatchCount: 0, + agentFinderProviderPlugin: true, + agentFinderBrowseDuplicate: true, + }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=accessibility-agents')); + assert.deepStrictEqual({ + calls: fixture.calls, + errors: fixture.errors, + }, { + calls: [ + 'agentFinderQuery:accessibility-agents:', + 'agentFinderBrowse', + `install:${sessionResource}:agentFinder/accessibility-agents`, + ], errors: [], }); }); - test('does not reuse a registered marketplace at a different revision', async () => { - const fixture = createHandler({ existingMarketplaceSource: 'GitHub: acme/plugins#other' }); - await fixture.handler.handleURL(uri()); + desktopTest('follows Agent Finder pagination to find an exact catalog identity', async () => { + const fixture = createHandler({ agentFinderAvailable: true, agentFinderPaginated: true }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { + calls: [ + 'agentFinderQuery:my-plugin:', + 'agentFinderQuery:my-plugin:next', + `install:${sessionResource}:agentFinder/my-plugin-0`, + ], + errors: [], + }); + }); + + desktopTest('surfaces Agent Finder query failures without adding the legacy marketplace', async () => { + const fixture = createHandler({ agentFinderAvailable: true, failure: 'agentFinderQuery' }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot&plugin=my-plugin')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors.length, commands: fixture.commands }, { + calls: ['agentFinderQuery:my-plugin:'], + errors: 1, + commands: [], + }); + }); + + desktopTest('preserves a pinned Awesome Copilot reference on the configured marketplace path', async () => { + const fixture = createHandler({ agentFinderAvailable: true }); + await fixture.handler.handleURL(uri('/install', 'source=github%2Fawesome-copilot%23v1.2.3&plugin=my-plugin')); assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { - calls: [`add:${sessionResource}:acme/plugins`], + calls: [ + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, 'github/awesome-copilot#v1.2.3', undefined], + ['browse', 'copilotcli', undefined, 'catalog', undefined], + ['install', 'copilotcli', { source: 'my-plugin@catalog' }, undefined, undefined], + ], errors: [], }); }); - test('does not mutate anything while consent is pending', async () => { + for (const source of ['GitHub: github/awesome-copilot', 'URL: https://github.com/GitHub/Awesome-Copilot.git']) { + for (const path of ['/install', '/add-marketplace']) { + desktopTest(`reuses the built-in published Awesome Copilot marketplace for ${path}: ${source}`, async () => { + const fixture = createHandler({ + existingMarketplaceSource: source, + existingMarketplaceIsDefault: true, + agentFinderAvailable: true, + failure: 'add', + }); + await fixture.handler.handleURL(uri(path, 'source=github%2Fawesome-copilot%23marketplace&ref=github%2Fawesome-copilot%23marketplace&plugin=my-plugin&harness=copilot')); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors }, { + calls: [ + ['list', 'copilotcli', undefined, undefined], + ...(path === '/install' ? [ + ['browse', 'copilotcli', undefined, 'catalog', undefined], + ['install', 'copilotcli', { source: 'my-plugin@catalog' }, undefined, undefined], + ] : []), + ], + errors: [], + }); + }); + } + } + + for (const [source, isDefault, revision, managed] of [ + ['GitHub: github/awesome-copilot', true, 'feature/beta', false], + ['GitHub: github/awesome-copilot#other', true, 'marketplace', false], + ['GitHub: github/awesome-copilot', false, 'marketplace', false], + ['GitHub: github/awesome-copilot', true, 'marketplace', true], + ] as const) { + desktopTest(`does not substitute ${source} for revision ${revision} (default: ${isDefault}, managed: ${managed})`, async () => { + const fixture = createHandler({ existingMarketplaceSource: source, existingMarketplaceIsDefault: isDefault, existingMarketplaceManaged: managed, failure: 'add' }); + await fixture.handler.handleURL(uri('/install', `source=${encodeURIComponent(`github/awesome-copilot#${revision}`)}&plugin=my-plugin&harness=copilot`)); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors.length }, { + calls: [ + ['list', 'copilotcli', undefined, undefined], + ['add', 'copilotcli', undefined, `github/awesome-copilot#${revision}`, undefined], + ], + errors: 1, + }); + }); + } + + desktopTest('does not duplicate a configured VS Code marketplace', async () => { + const fixture = createHandler({ harness: 'vscode', existingMarketplaceSource: 'https://github.com/ACME/plugins.git#feature/beta' }); + await fixture.handler.handleURL(uri('/add-marketplace', 'ref=acme%2Fplugins%23feature%2Fbeta')); + assert.deepStrictEqual(fixture.configuration.getValue(ChatConfiguration.PluginMarketplaces), ['https://github.com/ACME/plugins.git#feature/beta']); + }); + + for (const harness of ['copilot', 'vscode'] as const) { + for (const path of ['/install', '/add-marketplace']) { + desktopTest(`an explicit ${harness} target skips the picker but still requires consent for ${path}`, async () => { + const fixture = createHandler({ harness: harness === 'copilot' ? 'vscode' : 'copilot', confirmed: false }); + await fixture.handler.handleURL(uri(path, `source=acme/plugins&ref=acme/plugins&plugin=my-plugin&harness=${harness}`)); + assert.deepStrictEqual({ picks: fixture.picks.length, dialogs: fixture.dialogs.length, calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { + picks: 0, dialogs: 1, calls: [], commands: [], errors: [], + }); + assert.ok(typeof fixture.dialogs[0].detail === 'string' && fixture.dialogs[0].detail.includes(harness === 'copilot' ? 'Copilot\'s user installation' : 'VS Code\'s shared plugin installation')); + }); + } + } + + desktopTest('cancelling owner selection performs no mutations or confirmation', async () => { + const fixture = createHandler({ cancelPicker: true }); + await fixture.handler.handleURL(uri()); + assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs, errors: fixture.errors, commands: fixture.commands }, { + calls: [], dialogs: [], errors: [], commands: [], + }); + }); + + desktopTest('does not mutate anything while consent is pending', async () => { const confirmation = new DeferredPromise(); const fixture = createHandler({ confirmation: confirmation.p }); const handling = fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); @@ -321,19 +741,31 @@ suite('PluginUrlHandler', () => { assert.deepStrictEqual({ calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { calls: [], commands: [], errors: [] }); }); - for (const path of ['/add-marketplace', '/install']) { - test(`declining ${path} does not access the harness or create a session`, async () => { - const fixture = createHandler({ activeResource: URI.parse('local:/session'), confirmations: [false] }); - await fixture.handler.handleURL(uri(path, 'ref=acme/plugins&source=acme/plugins&plugin=my-plugin')); + desktopTest('rechecks plugin availability after consent', async () => { + const confirmation = new DeferredPromise(); + const fixture = createHandler({ confirmation: confirmation.p }); + const handling = fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); + await fixture.configuration.setUserConfiguration(ChatConfiguration.PluginsEnabled, false); + await confirmation.complete(true); + await handling; + assert.deepStrictEqual({ calls: fixture.calls, commands: fixture.commands, errors: fixture.errors.length }, { calls: [], commands: [], errors: 1 }); + }); + + for (const harness of ['copilot', 'vscode'] as const) { + desktopTest(`declining consent does not access the ${harness} installer`, async () => { + const fixture = createHandler({ harness, confirmed: false }); + await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); assert.deepStrictEqual({ calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { calls: [], commands: [], errors: [] }); }); } - for (const query of ['', 'ref=invalid', 'ref=file:///local/repo', 'ref=acme/plugins&ref=evil/plugins']) { - test(`rejects invalid marketplace input: ${query}`, async () => { + for (const query of ['', 'ref=invalid', 'ref=file:///local/repo', 'ref=acme/plugins&ref=evil/plugins', 'ref=acme/plugins&harness=', 'ref=acme/plugins&harness=claude', 'ref=acme/plugins&harness=copilot&harness=vscode']) { + test(`rejects invalid marketplace or harness input: ${query}`, async () => { const fixture = createHandler(); await fixture.handler.handleURL(uri('/add-marketplace', query)); - assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs.length, errors: fixture.errors.length }, { calls: [], dialogs: 0, errors: 1 }); + assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs.length, picks: fixture.picks.length, errors: fixture.errors.length }, { + calls: [], dialogs: 0, picks: 0, errors: 1, + }); }); } @@ -345,118 +777,57 @@ suite('PluginUrlHandler', () => { }); } - test('reuses an existing Copilot session rather than the non-Copilot active harness', async () => { - const fixture = createHandler({ activeResource: URI.parse(`${SessionType.AgentHostClaude}:/session`), existingSession: true }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs.length }, { - calls: ['resolve', `add:${sessionResource}:acme/plugins`], - dialogs: 1, - }); - }); - - test('uses an existing provisional backend identity unchanged', async () => { - const fixture = createHandler({ activeResource: draftResource, provisional: backendResource }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual(fixture.calls, [`add:${backendResource}:acme/plugins`]); - }); - - test('asks before creating a session and uses its backend identity', async () => { - const fixture = createHandler({ activeResource: URI.parse('local:/session') }); - await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); - assert.deepStrictEqual({ - calls: fixture.calls, - dialogs: fixture.dialogs.length, - firstCommand: fixture.commands[0].id, - errors: fixture.errors, - }, { - calls: ['resolve', `create:${draftResource}:copilotcli:file:///workspace`, `add:${backendResource}:acme/plugins`, `query:${backendResource}:catalog:`, `install:${backendResource}:catalog/my-plugin`], - dialogs: 2, - firstCommand: `workbench.action.chat.openNewSessionEditor.${SessionType.AgentHostCopilot}`, - errors: [], - }); - }); - - test('declining session creation does not add a marketplace', async () => { - const fixture = createHandler({ activeResource: draftResource, confirmations: [true, false] }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual({ calls: fixture.calls, commands: fixture.commands, errors: fixture.errors }, { calls: ['resolve'], commands: [], errors: [] }); - }); - - test('uses the Agents-window new session command without creating a second backend', async () => { - const fixture = createHandler({ activeResource: URI.parse('local:/session'), isSessionsWindow: true }); - await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); - assert.deepStrictEqual({ - calls: fixture.calls, - dialogs: fixture.dialogs.length, - commands: fixture.commands, - errors: fixture.errors, - }, { - calls: ['resolve', `add:${agentsDraftResource}:acme/plugins`, `query:${agentsDraftResource}:catalog:`, `install:${agentsDraftResource}:catalog/my-plugin`], - dialogs: 2, - commands: [{ - id: NEW_SESSION_IN_AGENTS_WINDOW_COMMAND_ID, - args: [{ noWorkspace: true, agentHostProvider: 'copilotcli' }], - }, { - id: AICustomizationManagementCommands.OpenEditor, - args: [{ showDiscover: true, sessionResource: agentsDraftResource, searchQuery: 'my-plugin' }], - }], - errors: [], + for (const options of [{ hidden: true }, { disabledInWorkspace: true }, { pluginsEnabled: false }, { remoteAuthority: 'ssh-remote+host' }]) { + test(`rejects disabled or nonlocal flows before owner selection: ${JSON.stringify(options)}`, async () => { + const fixture = createHandler(options); + await fixture.handler.handleURL(uri()); + assert.deepStrictEqual({ calls: fixture.calls, picks: fixture.picks.length, errors: fixture.errors.length }, { calls: [], picks: 0, errors: 1 }); }); - }); - - test('declining session creation in the Agents window does not invoke a command', async () => { - const fixture = createHandler({ activeResource: draftResource, isSessionsWindow: true, confirmations: [true, false] }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual({ commands: fixture.commands, calls: fixture.calls, errors: fixture.errors }, { commands: [], calls: ['resolve'], errors: [] }); - }); - - test('does not reuse archived sessions without asking to create a new one', async () => { - const fixture = createHandler({ activeResource: URI.parse('local:/session'), existingSession: true, archivedSession: true, confirmations: [true, false] }); - await fixture.handler.handleURL(uri()); - assert.deepStrictEqual({ calls: fixture.calls, dialogs: fixture.dialogs.length, commands: fixture.commands }, { calls: ['resolve'], dialogs: 2, commands: [] }); - }); + } - for (const options of [ - { hidden: true }, - { disabledInWorkspace: true }, - { pluginsEnabled: false }, - { activeResource: draftResource, available: false }, - { activeResource: draftResource, createFailed: true }, - { activeResource: draftResource, isSessionsWindow: true, createFailed: true }, - { activeResource: draftResource, backendFailed: true }, - { managementUnavailable: true }, - { installUnavailable: true }, - ]) { - test(`reports unsupported or unavailable flows: ${JSON.stringify(options)}`, async () => { + for (const options of [{ managementUnavailable: true }, { installUnavailable: true }]) { + desktopTest(`reports unavailable Copilot capabilities without switching owners: ${JSON.stringify(options)}`, async () => { const fixture = createHandler(options); await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); - assert.deepStrictEqual({ mutations: fixture.calls.filter(call => /^(add|install):/.test(call)), errors: fixture.errors.length }, { mutations: [], errors: 1 }); + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors.length, commands: fixture.commands }, { calls: [], errors: 1, commands: [] }); }); } - test('reports a missing exact plugin without installing another plugin', async () => { + desktopTest('reports a missing plugin without installing a different one', async () => { const fixture = createHandler(); await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=missing')); - assert.deepStrictEqual({ - calls: fixture.calls, - errors: fixture.errors.length, - commands: fixture.commands, - }, { - calls: [`add:${sessionResource}:acme/plugins`, `query:${sessionResource}:catalog:`], + assert.deepStrictEqual({ calls: fixture.calls, errors: fixture.errors.length, commands: fixture.commands }, { + calls: [['list', 'copilotcli', undefined, undefined], ['add', 'copilotcli', undefined, 'acme/plugins', undefined], ['browse', 'copilotcli', undefined, 'catalog', undefined]], errors: 1, commands: [], }); }); - for (const failure of ['list', 'add', 'query', 'install'] as const) { - test(`surfaces ${failure} failures without a legacy fallback`, async () => { + for (const failure of ['list', 'add', 'browse', 'install'] as const) { + desktopTest(`surfaces ${failure} failures without switching owners`, async () => { const fixture = createHandler({ failure }); await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); - assert.deepStrictEqual({ errors: fixture.errors.length, commands: fixture.commands }, { errors: 1, commands: [] }); + assert.deepStrictEqual({ errors: fixture.errors.length, commands: fixture.commands, usedVSCode: fixture.calls.some(call => Array.isArray(call) && call[0] === 'vscodeInstall') }, { + errors: 1, commands: [], usedVSCode: false, + }); }); } - test('does not report user cancellation as an error', async () => { + desktopTest('reports the VS Code installer error', async () => { + const fixture = createHandler({ harness: 'vscode', installResult: { success: false, message: 'Installation failed' } }); + await fixture.handler.handleURL(uri('/install', 'source=acme/plugins&plugin=my-plugin')); + assert.deepStrictEqual({ errors: fixture.errors, commands: fixture.commands }, { errors: ['Unable to complete the plugin link: Installation failed'], commands: [] }); + }); + + desktopTest('respects marketplace trust refusal for VS Code', async () => { + const fixture = createHandler({ harness: 'vscode', marketplaceTrusted: false }); + await fixture.handler.handleURL(uri()); + assert.deepStrictEqual({ marketplaces: fixture.configuration.getValue(ChatConfiguration.PluginMarketplaces), errors: fixture.errors, commands: fixture.commands }, { + marketplaces: [], errors: [], commands: [], + }); + }); + + desktopTest('does not report user cancellation as an error', async () => { const fixture = createHandler({ failure: 'add', cancelled: true }); await fixture.handler.handleURL(uri()); assert.deepStrictEqual({ errors: fixture.errors, commands: fixture.commands }, { errors: [], commands: [] }); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHeaderAutocompletion.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHeaderAutocompletion.test.ts index de2677a4cae4..a9556fbd0a3c 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHeaderAutocompletion.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHeaderAutocompletion.test.ts @@ -455,7 +455,8 @@ suite('PromptHeaderAutocompletion', () => { test('complete github-copilot tools from all matching harness inventories', async () => { copilotToolInventory = [ { name: 'publisher.extension/clientTool', description: 'Provided by the client', availability: 'available' }, - { name: 'github/*', availability: 'available' }, + { name: 'github/*', availability: 'disabled' }, + { name: 'playwright/*', availability: 'unavailable' }, { name: 'disabled/*', availability: 'disabled' }, ]; otherCopilotToolInventory = [{ name: 'other.extension/remoteClientTool', availability: 'available' }]; @@ -469,7 +470,7 @@ suite('PromptHeaderAutocompletion', () => { const labels = (await getCompletions(content, PromptsType.agent)).map(item => item.label); - assert.deepStrictEqual(labels, ['execute', 'read', 'edit', 'search', 'agent', 'web', 'todo', '*', 'publisher.extension/clientTool', 'github/*', 'disabled/*', 'other.extension/remoteClientTool', 'playwright/*']); + assert.deepStrictEqual(labels, ['execute', 'read', 'edit', 'search', 'agent', 'web', 'todo', '*', 'github/*', 'playwright/*', 'publisher.extension/clientTool', 'disabled/*', 'other.extension/remoteClientTool']); }); test('complete github-copilot skills from all matching harness inventories', async () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHovers.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHovers.test.ts index 75822c4ab432..b2074f385855 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHovers.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptHovers.test.ts @@ -446,19 +446,42 @@ suite('PromptHoverProvider', () => { assert.strictEqual(hoverEdit, 'Read files'); }); - test('hover on unavailable github-copilot tool shows provider availability', async () => { - copilotToolInventory = [{ name: 'github/*', description: 'GitHub tools', availability: 'disabled' }]; + test('hover on spec-defined github-copilot namespaces uses static descriptions', async () => { + copilotToolInventory = [ + { name: 'github/*', description: 'Provider GitHub tools', availability: 'disabled' }, + { name: 'playwright/*', description: 'Provider browser tools', availability: 'unavailable' }, + ]; const content = [ '---', 'description: "Test"', 'target: github-copilot', - `tools: ['github/*']`, + `tools: ['github/*', 'playwright/*']`, '---', ].join('\n'); - const hover = await getHover(content, 4, 10, PromptsType.agent); + const githubHover = await getHover(content, 4, 10, PromptsType.agent); + const playwrightHover = await getHover(content, 4, 23, PromptsType.agent); + + assert.deepStrictEqual({ githubHover, playwrightHover }, { + githubHover: 'Use GitHub tools', + playwrightHover: 'Use browser automation tools', + }); + }); - assert.strictEqual(hover, 'GitHub tools\n\nThis tool is recognized but disabled for the matching GitHub Copilot harness.'); + test('hover on discovered github-copilot namespaces retains provider availability', async () => { + copilotToolInventory = [ + { name: 'disabled/*', description: 'Disabled tools', availability: 'disabled' }, + { name: 'unavailable/*', description: 'Unavailable tools', availability: 'unavailable' }, + ]; + const content = '---\ndescription: Test\ntarget: github-copilot\ntools: [disabled/*, unavailable/*]\n---'; + + assert.deepStrictEqual({ + disabledHover: await getHover(content, 4, 10, PromptsType.agent), + unavailableHover: await getHover(content, 4, 23, PromptsType.agent), + }, { + disabledHover: 'Disabled tools\n\nThis tool is recognized but disabled for the matching GitHub Copilot harness.', + unavailableHover: 'Unavailable tools\n\nThis tool is recognized but currently unavailable for the matching GitHub Copilot harness.', + }); }); test('hover on github-copilot skill shows description, source, and availability', async () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptValidator.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptValidator.test.ts index 1a522685a6e8..d2a482687365 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptValidator.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/languageProviders/promptValidator.test.ts @@ -903,6 +903,7 @@ suite('PromptValidator', () => { ' exec: node', ' args: [script.js]', ' timeout: 2.5', + ' matcher: shell|bash', ' preToolUse:', ' - type: http', ' url: https://example.com/approve', @@ -916,6 +917,95 @@ suite('PromptValidator', () => { assert.deepStrictEqual(await validate(content, PromptsType.agent), []); }); + test('github-copilot agent reports invalid hook matcher regular expressions', async () => { + const content = [ + '---', + 'target: github-copilot', + 'description: Test', + 'hooks:', + ' preToolUse:', + ' - type: command', + ' bash: echo test', + ' matcher: "["', + ' - type: http', + ' url: https://example.com/approve', + ' matcher: "("', + '---', + ].join('\n'); + + assert.deepStrictEqual((await validate(content, PromptsType.agent)).map(marker => marker.message), [ + `The 'matcher' property in a hook must be a valid regular expression.`, + `The 'matcher' property in a hook must be a valid regular expression.`, + ]); + }); + + const hookMatcherCases: [name: string, eventName: string, matcher: string, expected: string[]][] = [ + ['rejects empty matchers', 'preToolUse', '""', [`The 'matcher' property in a hook must not be empty.`]], + ['rejects non-string matchers', 'preToolUse', '[]', [`The 'matcher' property in a hook must be a string.`]], + ['rejects native wildcard matchers', 'preToolUse', '"*"', [`The 'matcher' property in a hook must be a valid regular expression.`]], + ['accepts native regular expressions', 'preToolUse', '"shell|bash"', []], + ['accepts compatible wildcard matchers', 'PreToolUse', '"*"', []], + ['accepts padded compatible wildcard matchers', 'PreToolUse', '" ** "', []], + ['rejects empty compatible matchers', 'PreToolUse', '""', [`The 'matcher' property in a hook must not be empty.`]], + ['accepts whitespace compatible matchers', 'PreToolUse', '" "', []], + ['rejects invalid compatible regexes', 'PreToolUse', '"["', [`The 'matcher' property in a hook must be a valid regular expression.`]], + ['ignores matchers on startup hooks', 'sessionStart', '"["', []], + ['ignores matchers on stop hooks', 'Stop', '[]', []], + ['validates MCP hook matchers', 'preMcpToolCall', '"("', [`The 'matcher' property in a hook must be a valid regular expression.`]], + ['validates notification hook matchers', 'notification', '"("', [`The 'matcher' property in a hook must be a valid regular expression.`]], + ]; + for (const [name, eventName, matcher, expected] of hookMatcherCases) { + test(`github-copilot agent ${name} for command and HTTP hooks`, async () => { + const results: string[][] = []; + for (const action of [['type: command', 'command: echo test'], ['type: http', 'url: https://example.com/hook']]) { + const content = [ + '---', + 'target: github-copilot', + 'description: Test', + 'hooks:', + ` ${eventName}:`, + ` - ${action[0]}`, + ` ${action[1]}`, + ` matcher: ${matcher}`, + '---', + ].join('\n'); + results.push((await validate(content, PromptsType.agent)).map(marker => marker.message)); + } + assert.deepStrictEqual(results, [expected, expected]); + }); + } + + test('github-copilot reports malformed HTTP hook and remote MCP URLs', async () => { + const content = [ + '---', + 'target: github-copilot', + 'description: Test', + 'hooks:', + ' preToolUse:', + ' - type: http', + ' url: "not-a-url"', + ' - type: http', + ' url: "https://"', + 'mcp-servers:', + ' invalid:', + ' type: http', + ' url: "not-a-url"', + ' tools: [fetch]', + ' missingHost:', + ' type: http', + ' url: "https://"', + ' tools: [fetch]', + '---', + ].join('\n'); + + assert.deepStrictEqual((await validate(content, PromptsType.agent)).map(marker => marker.message), [ + `The 'url' property in an HTTP hook action must be an HTTP or HTTPS URL.`, + `The 'url' property in an HTTP hook action must be an HTTP or HTTPS URL.`, + `The 'url' property for MCP server 'invalid' must be an HTTP or HTTPS URL.`, + `The 'url' property for MCP server 'missingHost' must be an HTTP or HTTPS URL.`, + ]); + }); + const githubCopilotSchemaCases: [name: string, header: string[], expected: string[]][] = [ ['github-copilot agent rejects invalid hook action combinations', [ 'description: Test', @@ -1034,6 +1124,16 @@ suite('PromptValidator', () => { assert.deepStrictEqual(await validate(content, PromptsType.agent), []); }); + test('keeps spec-defined github-copilot namespaces recognized when inventories also contain them', async () => { + copilotToolInventory = [ + { name: 'github/*', availability: 'disabled' }, + { name: 'playwright/*', availability: 'unavailable' }, + ]; + otherCopilotToolInventory = []; + const content = '---\ndescription: Test\ntarget: github-copilot\ntools: [github/*, playwright/*]\n---'; + assert.deepStrictEqual(await validate(content, PromptsType.agent), []); + }); + test('github-copilot tool validation remains fail-open until every inventory is ready', async () => { const content = [ '---', @@ -2076,6 +2176,24 @@ suite('PromptValidator', () => { ' - type: script', ' command: "echo foo"', ], [{ severity: MarkerSeverity.Error, message: `The 'type' property in a hook command must be 'command'.` }]], + ['hooks - nested matcher must be a valid regular expression', [ + 'hooks:', + ' PreToolUse:', + ' - matcher: "["', + ' hooks: []', + ], [{ severity: MarkerSeverity.Error, message: `The 'matcher' property in a hook must be a valid regular expression.` }]], + ['hooks - nested wildcard matcher is valid', [ + 'hooks:', + ' PreToolUse:', + ' - matcher: "*"', + ' hooks:', + ' - type: command', + ' command: "echo foo"', + ' - matcher: " ** "', + ' hooks:', + ' - type: command', + ' command: "echo bar"', + ], []], ['hooks - nested hooks must be array', [ 'hooks:', ' PreToolUse:', diff --git a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/newPromptFileActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/newPromptFileActions.test.ts new file mode 100644 index 000000000000..c30c73c0cce1 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/newPromptFileActions.test.ts @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { URI } from '../../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { SnippetController2 } from '../../../../../../editor/contrib/snippet/browser/snippetController2.js'; +import { createTestCodeEditor } from '../../../../../../editor/test/browser/testCodeEditor.js'; +import { createTextModel } from '../../../../../../editor/test/common/testTextModel.js'; +import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; +import { IFileService } from '../../../../../../platform/files/common/files.js'; +import { createInMemoryFileService } from '../../../../../../platform/files/test/common/inMemoryFileService.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; +import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; +import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { INewPromptOptions, NEW_SKILL_COMMAND_ID, registerNewPromptFileActions } from '../../../browser/promptSyntax/newPromptFileActions.js'; + +suite('New skill file', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const targetFolder = URI.file('/workspace/.agents/skills'); + const skillFileUri = URI.joinPath(targetFolder, 'test-skill', 'SKILL.md'); + const expectedContent = [ + '---', + 'name: test-skill', + 'description: Describe what this skill does and when to use it. Include keywords that help agents identify relevant tasks.', + '---', + '', + '', + '', + 'Define the functionality provided by this skill, including detailed instructions and examples', + ].join('\n'); + + function setup() { + const instantiationService = store.add(new TestInstantiationService()); + const fileService = createInMemoryFileService(store, skillFileUri.scheme); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(IQuickInputService, { input: async () => ' test-skill ' }); + instantiationService.stub(IEditorService, { activeTextEditorControl: undefined }); + store.add(registerNewPromptFileActions()); + return { instantiationService, fileService }; + } + + async function createSkill(instantiationService: TestInstantiationService, options?: INewPromptOptions) { + const command = CommandsRegistry.getCommand(NEW_SKILL_COMMAND_ID)!; + await instantiationService.invokeFunction(command.handler, { targetFolder, ...options }); + } + + test('writes the template before opening in a non-text editor', async () => { + const { instantiationService, fileService } = setup(); + let openedContent: string | undefined; + instantiationService.stub(IOpenerService, { + open: async resource => { + assert.strictEqual(resource.toString(), skillFileUri.toString()); + openedContent = (await fileService.readFile(skillFileUri)).value.toString(); + return true; + } + }); + + await createSkill(instantiationService); + + assert.strictEqual(openedContent, expectedContent); + }); + + test('writes the template before calling a custom opener without a code editor', async () => { + const { instantiationService, fileService } = setup(); + instantiationService.stub(IOpenerService, {}); + let openedContent: string | undefined; + + await createSkill(instantiationService, { + openFile: async resource => { + openedContent = (await fileService.readFile(resource)).value.toString(); + return undefined; + } + }); + + assert.strictEqual(openedContent, expectedContent); + }); + + test('preserves snippet navigation in the embedded code editor', async () => { + const { instantiationService, fileService } = setup(); + instantiationService.stub(IOpenerService, {}); + const model = store.add(createTextModel('', undefined, undefined, skillFileUri)); + const editor = store.add(createTestCodeEditor(model)); + editor.registerAndInstantiateContribution(SnippetController2.ID, SnippetController2); + + await createSkill(instantiationService, { + openFile: async resource => { + model.setValue((await fileService.readFile(resource)).value.toString()); + return editor; + } + }); + + assert.deepStrictEqual({ + content: model.getValue(), + selectedText: model.getValueInRange(editor.getSelection()!), + }, { + content: expectedContent, + selectedText: 'Describe what this skill does and when to use it. Include keywords that help agents identify relevant tasks.', + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/promptToolsCodeLensProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/promptToolsCodeLensProvider.test.ts index 3f1d00e440a5..1f64d6f653a6 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptSyntax/promptToolsCodeLensProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptSyntax/promptToolsCodeLensProvider.test.ts @@ -195,7 +195,7 @@ suite('PromptToolsCodeLensProvider', () => { assert.deepStrictEqual(offeredTools.map(tool => [tool.label, tool.checked]), [ ['All Tools', false], ['execute', false], ['read', true], ['edit', false], ['search', false], ['agent', false], ['web', false], ['todo', false], - ['read_file', true], ['*', false], ['*', false], + ['*', false], ['*', false], ['read_file', true], ]); }); @@ -212,13 +212,21 @@ suite('PromptToolsCodeLensProvider', () => { }); }); - test('spec-defined namespaces do not override explicit inventory restrictions', async () => { + test('spec-defined namespaces remain selectable despite conflicting inventory entries', async () => { inventory = [ { name: 'github/*', availability: 'disabled' }, { name: 'playwright/*', availability: 'unavailable' }, ]; - await runLens(createModel('target: github-copilot\ntools: [read]')); - assert.deepStrictEqual(offeredGroups.map(group => group.label), ['All Tools', 'Built-In']); + selectedNames = ['github/*', 'playwright/*']; + const model = createModel('target: github-copilot\ntools: [read]'); + await runLens(model); + assert.deepStrictEqual({ + groups: offeredGroups.map(group => group.label), + content: model.getValue(), + }, { + groups: ['All Tools', 'Built-In', 'github', 'playwright'], + content: '---\ntarget: github-copilot\ntools: [\'github/*\', \'playwright/*\']\n---\n', + }); }); test('groups unqualified tools and namespaced tools without losing reference names', async () => { @@ -240,11 +248,11 @@ suite('PromptToolsCodeLensProvider', () => { allTools: '*', groups: [ ['Built-In', ['execute', 'read', 'edit', 'search', 'agent', 'web', 'todo'].map(name => [name, name])], + ['github', [['github/*', '*']]], + ['playwright', [['playwright/*', '*']]], ['vscode', [['vscode/usages', 'usages'], ['vscode/runTask', 'runTask']]], ['browser', [['browser/openBrowserPage', 'openBrowserPage']]], ['custom', [['custom/nested/tool', 'nested/tool']]], - ['github', [['github/*', '*']]], - ['playwright', [['playwright/*', '*']]], ], content: '---\ntarget: github-copilot\ntools: [vscode/runTask, custom/nested/tool]\n---\n', pickerDisposed: true, @@ -394,7 +402,7 @@ suite('PromptToolsCodeLensProvider', () => { assert.deepStrictEqual(results, [ ['vscode/usages', 'vscode/runTask'], ['vscode/usages'], - ['*', 'execute', 'read', 'edit', 'search', 'agent', 'web', 'todo', 'vscode/usages', 'vscode/runTask', 'browser/openBrowserPage', 'github/*', 'playwright/*'], + ['*', 'execute', 'read', 'edit', 'search', 'agent', 'web', 'todo', 'github/*', 'playwright/*', 'vscode/usages', 'vscode/runTask', 'browser/openBrowserPage'], ]); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index 903d7a816f48..851441ba8a1a 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { getWindow } from '../../../../../../base/browser/dom.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { PromptTimelineGutterRail, restDotCount } from '../../../browser/promptTimeline/promptTimelineGutterRail.js'; @@ -70,6 +71,44 @@ suite('PromptTimelineGutterRail', () => { }); }); + test('keeps an active row hover visible in high contrast', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench hc-black'; + root.style.setProperty('--vscode-contrastActiveBorder', '#f38518'); + root.style.setProperty('--vscode-focusBorder', '#007fd4'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const rail = store.add(new PromptTimelineGutterRail()); + root.appendChild(rail.domNode); + rail.setTicks([tick(0), tick(1)]); + rail.setActive('1'); + const activeJump = rowParts(rail)[1].jump; + activeJump.classList.add('hovered'); + const readOutline = () => { + const style = getWindow(activeJump).getComputedStyle(activeJump); + return { + color: style.outlineColor, + offset: style.outlineOffset, + style: style.outlineStyle, + width: style.outlineWidth, + }; + }; + const hovered = readOutline(); + activeJump.classList.add('focus-visible'); + const focusedAndHovered = readOutline(); + + assert.deepStrictEqual({ + active: activeJump.parentElement?.classList.contains('active'), + hovered, + focusedAndHovered, + }, { + active: true, + hovered: { color: 'rgb(243, 133, 24)', offset: '-1px', style: 'dashed', width: '1px' }, + focusedAndHovered: { color: 'rgb(0, 127, 212)', offset: '-1px', style: 'solid', width: '1px' }, + }); + }); + test('maps row hover to the nearest sampled dot when capped', () => { const rail = store.add(new PromptTimelineGutterRail()); rail.setTicks(Array.from({ length: 51 }, (_, index) => tick(index))); 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 59b1695b6363..b6f9dcfe4aa5 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 @@ -82,11 +82,12 @@ class TestCloudSandboxAgentHostService extends CloudSandboxAgentHostService { type ScriptedConnectResult = CloudSandboxConnectResult | Error | (() => Promise); const connectionDetails = { + suspendCount: 0, suspendedMs: 0, environmentOperation: 'resume', provisioningMs: 0, readinessMs: 0, taskCreationPath: 'unknown', reservationWaitMs: 0, preparationMs: 0, connectionMs: 0, environmentKind: 'cloud', - surface: isWeb ? 'editorWeb' : 'editorDesktop', source: 'existing', credentialRequests: 0, wakingResponses: 0, transportAttempts: 0, + surface: isWeb ? 'editorWeb' : 'editorDesktop', source: 'existing', credentialRequests: undefined, credentialOperations: 0, wakingResponses: 0, transportAttempts: 0, credentialsMs: 0, relayMs: 0, protocolMs: 0, authenticationMs: 0, restorationMs: 0, firstFailurePhase: undefined, firstFailureCode: undefined, credentialFailures: 0, relayFailures: 0, protocolFailures: 0, authenticationFailures: 0, restorationFailures: 0, @@ -345,6 +346,12 @@ suite('CloudSandboxAgentHostService', () => { assert.ok(options.resolveInitialAuthentication && options.sealAuthenticationToken); const identity = await options.resolveInitialAuthentication(); assert.ok(identity); + const unavailable = new Error('network unavailable'); + fixture.setIdentityResult(async () => { throw unavailable; }); + await assert.rejects(options.resolveInitialAuthentication(), error => error === unavailable); + fixture.setIdentityResult(async () => { throw new CloudSandboxRequestError(401, 'sign in required'); }); + await assert.rejects(options.resolveInitialAuthentication(), InitialAuthenticationError); + fixture.setIdentityResult(async () => ({ token: 'identity-only-token' })); 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/); @@ -355,7 +362,10 @@ suite('CloudSandboxAgentHostService', () => { }, { 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 }], + sealed: true, identityRequests: [ + { account: 'account-a', forceRefresh: false }, { account: 'account-a', forceRefresh: false }, + { account: 'account-a', forceRefresh: false }, { account: 'account-a', forceRefresh: true }, + ], controlPlaneRequests: 1, environmentReads: 1, }); }); @@ -618,7 +628,7 @@ suite('CloudSandboxAgentHostService', () => { reservationWaitMs: undefined, connectionMs: 50, surface: isSessionsWindow ? (isWeb ? 'agentsWeb' : 'agentsDesktop') : connectionDetails.surface, source: 'created', - credentialRequests: 1, transportAttempts: 1, relayMs: 20, authenticationMs: 30, + credentialOperations: 1, transportAttempts: 1, relayMs: 20, authenticationMs: 30, }, }], listening: false, @@ -653,7 +663,7 @@ suite('CloudSandboxAgentHostService', () => { outcomes: fixture.events.filter(event => event.eventName === 'cloudSandboxConnectionOutcome').map(event => event.data), }, { entries: [], sealed: undefined, - outcomes: [{ ...connectionDetails, operation: 'connect', outcome: 'failure', stage, durationMs: 600_000, readinessMs: 600_000, preparationMs: stage === 'credentials' ? 600_000 : 0, connectionMs: stage === 'connection' ? 600_000 : 0, credentialRequests: 1, credentialsMs: stage === 'credentials' ? 600_000 : 0 }], + outcomes: [{ ...connectionDetails, operation: 'connect', outcome: 'failure', stage, durationMs: 600_000, readinessMs: 600_000, preparationMs: stage === 'credentials' ? 600_000 : 0, connectionMs: stage === 'connection' ? 600_000 : 0, credentialOperations: 1, credentialsMs: stage === 'credentials' ? 600_000 : 0 }], }); })); } @@ -1575,7 +1585,7 @@ suite('CloudSandboxAgentHostService', () => { ...connectionDetails, operation: 'connect', source: 'created', outcome: 'success', stage: 'connection', environmentOperation: 'provision', provisioningMs: 1000, readinessMs: 1100, taskCreationPath: taskCreationPath ?? 'unknown', reservationWaitMs, - durationMs: 100, connectionMs: 100, credentialRequests: 1, + durationMs: 100, connectionMs: 100, credentialOperations: 1, }, { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', @@ -1601,7 +1611,7 @@ suite('CloudSandboxAgentHostService', () => { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 7000, readinessMs: 7000, - preparationMs: 2000, connectionMs: 5000, credentialRequests: 1, credentialsMs: 2000, + preparationMs: 2000, connectionMs: 5000, credentialOperations: 1, credentialsMs: 2000, }, }]); })); @@ -1630,7 +1640,7 @@ suite('CloudSandboxAgentHostService', () => { fixture.service.dispose(); assert.deepStrictEqual({ calls: fixture.requestCalls(), events: fixture.events, withinExpectedWindow: durationMs >= 9_000 && durationMs < 9_400 }, { calls: 3, - events: [{ eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs, readinessMs: durationMs, preparationMs: durationMs - 5000, connectionMs: 5000, credentialRequests: 3, wakingResponses: 1, credentialsMs: durationMs - 5000 } }], + events: [{ eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs, readinessMs: durationMs, preparationMs: durationMs - 5000, connectionMs: 5000, credentialOperations: 3, wakingResponses: 1, credentialsMs: durationMs - 5000 } }], withinExpectedWindow: true, }); })); @@ -1646,7 +1656,7 @@ suite('CloudSandboxAgentHostService', () => { await Promise.all([first, second]); fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 3000, readinessMs: 3000, connectionMs: 3000, credentialRequests: 2 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 3000, readinessMs: 3000, connectionMs: 3000, credentialOperations: 2 } }, ]); })); @@ -1666,8 +1676,8 @@ suite('CloudSandboxAgentHostService', () => { await timeout(1000); fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialRequests: 1 } }, - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'success', stage: 'credentials', durationMs: 3000, readinessMs: 3000, preparationMs: 2000, connectionMs: 1000, credentialRequests: 1, firstFailurePhase: 'credentials', firstFailureCategory: 'unknown', credentialFailures: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialOperations: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'success', stage: 'credentials', durationMs: 3000, readinessMs: 3000, preparationMs: 2000, connectionMs: 1000, credentialOperations: 1, firstFailurePhase: 'credentials', firstFailureCategory: 'unknown', credentialFailures: 1 } }, { eventName: 'cloudSandboxConnectionHealth', data: { environmentKind: 'cloud', connectedMs: 2000, unexpectedDisconnects: 1, receivedFrames: 0 } }, ]); })); @@ -1688,8 +1698,8 @@ suite('CloudSandboxAgentHostService', () => { await redial; fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialRequests: 1 } }, - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'failure', stage: 'connection', durationMs: 2000, readinessMs: 2000, connectionMs: 2000, credentialRequests: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialOperations: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'failure', stage: 'connection', durationMs: 2000, readinessMs: 2000, connectionMs: 2000, credentialOperations: 1 } }, { eventName: 'cloudSandboxConnectionHealth', data: { environmentKind: 'cloud', connectedMs: 1000, unexpectedDisconnects: 1, receivedFrames: 0 } }, ]); })); @@ -1702,7 +1712,7 @@ suite('CloudSandboxAgentHostService', () => { await assert.rejects(fixture.service.connect(options, CancellationToken.None)); fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'credentials', durationMs: 1700, readinessMs: 1700, preparationMs: 1700, credentialRequests: 1, credentialsMs: 1700, firstFailurePhase: 'credentials', firstFailureCategory: 'unknown', credentialFailures: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'credentials', durationMs: 1700, readinessMs: 1700, preparationMs: 1700, credentialOperations: 1, credentialsMs: 1700, firstFailurePhase: 'credentials', firstFailureCategory: 'unknown', credentialFailures: 1 } }, ]); })); @@ -1716,7 +1726,7 @@ suite('CloudSandboxAgentHostService', () => { await connecting; fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'connection', durationMs: 2400, readinessMs: 2400, connectionMs: 2400, credentialRequests: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'connection', durationMs: 2400, readinessMs: 2400, connectionMs: 2400, credentialOperations: 1 } }, ]); })); @@ -1733,7 +1743,7 @@ suite('CloudSandboxAgentHostService', () => { await connecting; fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'credentials', durationMs: 1100, readinessMs: 1100, preparationMs: 1100, credentialRequests: 1, credentialsMs: 1100 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'credentials', durationMs: 1100, readinessMs: 1100, preparationMs: 1100, credentialOperations: 1, credentialsMs: 1100 } }, ]); })); @@ -1749,7 +1759,7 @@ suite('CloudSandboxAgentHostService', () => { await connecting; fixture.service.dispose(); assert.deepStrictEqual(fixture.events, [ - { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'connection', durationMs: 1200, readinessMs: 1200, connectionMs: 1200, credentialRequests: 1 } }, + { eventName: 'cloudSandboxConnectionOutcome', data: { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'connection', durationMs: 1200, readinessMs: 1200, connectionMs: 1200, credentialOperations: 1 } }, ]); })); }); 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 6e2318f1e4f7..b7a2320c0419 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 @@ -11,23 +11,27 @@ import { CancellationToken, CancellationTokenSource } from '../../../../../../ba import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { isObject } from '../../../../../../base/common/types.js'; import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { runWithFakedTimers } from '../../../../../../base/test/common/virtualScheduling/index.js'; import { IRequestContext, type IHeaders, type IRequestOptions } from '../../../../../../base/parts/request/common/request.js'; -import { CLOUD_SANDBOX_AGENT_SLUG, CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, CloudSandboxAuthenticationRequiredError, CloudSandboxRequestError, type ICloudSandboxAuthenticationTarget, type ICloudSandboxClientToken, type ICloudSandboxConnectionRequest, type ICloudSandboxPreparedAuthentication, type ICloudSandboxSealTokenRequest } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; +import { CLOUD_SANDBOX_AGENT_SLUG, CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, CloudSandboxAuthenticationRequiredError, CloudSandboxRequestError, type ICloudSandboxAuthenticationTarget, type ICloudSandboxConnectionRequest, type ICloudSandboxPreparedAuthentication, type ICloudSandboxSealTokenRequest } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { SessionStatus } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { ActionType } from '../../../../../../platform/agentHost/common/state/protocol/common/actions.js'; import { COPILOT_INTEGRATION_ID } from '../../../../../../platform/endpoint/common/licenseAgreement.js'; import { IGitHubAccountClient } from '../../../../../../platform/github/common/account/account.js'; -import { ApiRequest, ApiResponse, BufferedApiRequestProvider, IApiRequestProvider } from '../../../../../../platform/github/common/client/request.js'; +import { AccountClient } from '../../../../../../platform/github/common/account/accountClient.js'; +import { IApiRequestProvider } from '../../../../../../platform/github/common/client/request.js'; +import { LocalApiRequestProvider } from '../../../../../../platform/github/common/client/localApiRequestProvider.js'; import { LocalMissionControlRequestProvider } from '../../../../../../platform/github/common/client/localMissionControlRequestProvider.js'; import { SchemaError } from '../../../../../../platform/github/common/client/schema.js'; -import { GitHubRestTextRequest, IGitHubTransport } from '../../../../../../platform/github/common/githubTransport.js'; +import { IGitHubCredentials } from '../../../../../../platform/github/common/githubCredentialService.js'; +import { GitHubRestTextRequest, GitHubTransport, IGitHubTransport } from '../../../../../../platform/github/common/githubTransport.js'; import { AccountHandle, RequestError } from '../../../../../../platform/github/common/types.js'; -import { ApiRequestError, MissionControlClient } from '../../../../../../platform/github/common/missionControl/missionControlClient.js'; -import { TasksClient } from '../../../../../../platform/github/common/missionControl/tasksClient.js'; import { GitHubRequestError, GitHubRequestTimeoutError } from '../../../../../../platform/github/common/githubTypes.js'; +import { ClientTokenResponse } from '../../../../../../platform/github/common/missionControl/environments.js'; +import { MutationUncertainError } from '../../../../../../platform/github/common/missionControl/missionControlClient.js'; import type { TaskClient } from '../../../../../../platform/github/common/missionControl/tasks.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; @@ -42,9 +46,7 @@ import { createModelAction } from '../../../browser/widget/input/modelPicker/mod import { getModelConfigSummary } from '../../../browser/widget/input/modelPicker/modelPickerModelConfig.js'; import { ICloudSandboxTelemetryService, type ICloudSandboxDiscoveryTelemetryData } from '../../../browser/remoteAgentHost/cloudSandboxTelemetry.js'; import { IWorkbenchGitHubService } from '../../../../../services/github/common/githubService.js'; -import { EnvironmentsClient } from '../../../../../../platform/github/common/missionControl/environmentsClient.js'; import { ITelemetryService, type ITelemetryData } from '../../../../../../platform/telemetry/common/telemetry.js'; -import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { IUserDataProfile } from '../../../../../../platform/userDataProfile/common/userDataProfile.js'; import { DidChangeUserDataProfileEvent, IUserDataProfileService } from '../../../../../services/userDataProfile/common/userDataProfile.js'; import { CloudSandboxLifecycleTelemetry } from '../../../browser/remoteAgentHost/cloudSandboxLifecycleTelemetry.js'; @@ -56,16 +58,39 @@ function jsonResponse(body: unknown, statusCode = 200, headers: Record = { + ...metadata, + remote_steerable: true, + ...body, + }; + if (Array.isArray(response.sessions)) { + response.sessions = response.sessions.map((session: unknown) => isObject(session) ? { ...metadata, ...session } : session); + } + return response; +} + +function jsonTaskResponse(body: unknown, statusCode = 200, headers: Record = {}): IRequestContext { + return jsonResponse(statusCode >= 200 && statusCode < 300 ? taskResponse(body) : body, statusCode, headers); +} + +/** A task without optional repository-name enrichment. */ function task(id: string, name: string, repositoryId: number | undefined, sessionId: string, environmentId: string) { return { id, name, + state: 'completed', + created_at: '2026-01-01T00:00:00Z', + remote_steerable: true, agent_collaborators: [{ slug: CLOUD_SANDBOX_AGENT_SLUG }], compute: { provider: 'sandboxes' }, current_environment: { id: environmentId, kind: 'managed-sandbox' }, ...(repositoryId !== undefined ? { repository: { id: repositoryId } } : {}), - sessions: [{ id: sessionId, environment_id: environmentId }], + sessions: [{ id: sessionId, environment_id: environmentId, state: 'completed', created_at: '2026-01-01T00:00:00Z' }], }; } @@ -84,10 +109,13 @@ interface ITestSetup { readonly requestOutcomes: RequestOutcome[]; readonly lifecycleEvents: ITelemetryData[]; readonly discoveryEvents: ICloudSandboxDiscoveryTelemetryData[]; + readonly typedRequests: GitHubRestTextRequest[]; + readonly clientLifetimes: { readonly authorization: IGitHubAccountClient['authorization']; disposed: boolean }[]; /** Peak number of task-detail fetches in flight at once during the run. */ readonly concurrency: { max: number; current: number }; changeAuthentication(kind?: 'sessions' | 'register' | 'unregister'): void; changeProfile(id: string): void; + invalidateClients(): void; } type ProvisioningOutcome = Parameters; @@ -148,6 +176,9 @@ function createService(store: Pick<{ add(t: T): T const requestOutcomes: RequestOutcome[] = []; const lifecycleEvents: ITelemetryData[] = []; const discoveryEvents: ICloudSandboxDiscoveryTelemetryData[] = []; + const typedRequests: GitHubRestTextRequest[] = []; + const clientLifetimes: ITestSetup['clientLifetimes'] = []; + const clientInvalidations: Emitter[] = []; const concurrency = { max: 0, current: 0 }; const remainingTaskRateLimits = new Map(options.rateLimitedTaskFetches ?? []); let remainingListRateLimits = options.rateLimitedListPages ?? 0; @@ -180,11 +211,23 @@ function createService(store: Pick<{ add(t: T): T } const repoMatch = url.match(/\/repositories\/(\d+)$/); if (repoMatch) { - const entry = options.repositories.get(Number(repoMatch[1])); + const id = Number(repoMatch[1]); + const entry = options.repositories.get(id); if (entry === 'error') { return jsonResponse({ message: 'Not Found' }, 404); } - return jsonResponse(entry ?? {}); + return jsonResponse({ + id, node_id: `R_${id}`, name: entry?.full_name?.split('/')[1] ?? 'repository', + full_name: entry?.full_name, + owner: { id: 1, node_id: 'U_1', login: 'owner', avatar_url: '', html_url: 'https://github.com/owner', type: 'User' }, + private: true, html_url: `https://github.com/${entry?.full_name}`, url, + description: null, fork: false, default_branch: 'main', clone_url: 'https://github.com/owner/repository.git', + ssh_url: 'git@github.com:owner/repository.git', archived: false, disabled: false, language: null, stargazers_count: 0, + }); + } + if (new URL(url).pathname === '/agents/tasks/batch') { + const ids = new Set(new URL(url).searchParams.get('task_ids')?.split(',')); + return jsonResponse({ tasks: options.tasks.filter(task => ids.has(task.id)) }); } if (/\/tasks\/[^/]+$/.test(url)) { const id = decodeURIComponent(url.split('/').pop()!); @@ -223,19 +266,21 @@ function createService(store: Pick<{ add(t: T): T }); const perPage = Number(url.match(/[?&]per_page=(\d+)/)?.[1] ?? options.tasks.length); const page = Number(url.match(/[?&]page=(\d+)/)?.[1] ?? 1); + const continuation = new URL(url); + continuation.host = 'api.github.com'; if (options.shortFirstPage && tasks.length > 0 && page === 1) { - return jsonResponse({ tasks: [] }, 200, { link: `; rel="next"` }); + continuation.searchParams.set('page', '2'); + return jsonResponse({ tasks: [] }, 200, { link: `<${continuation.href}>; rel="next"` }); } const slice = options.shortFirstPage ? tasks : tasks.slice((page - 1) * perPage, page * perPage); const hasNext = !options.shortFirstPage && page * perPage < tasks.length; - const link = hasNext - ? `; rel="next"` - : `; rel="last"`; + continuation.searchParams.set('page', String(hasNext ? page + 1 : page)); + const link = `<${continuation.href}>; rel="${hasNext ? 'next' : 'last'}"`; return jsonResponse({ tasks: slice }, 200, { link, date: options.discoveryDate?.() ?? new Date().toUTCString() }); } }()); let selectedSessions: readonly AuthenticationSession[] = []; - instantiationService.stub(IAuthenticationService, new class extends mock() { + const authentication = instantiationService.stub(IAuthenticationService, new class extends mock() { override async getSessions(_providerId: string, scopes?: readonly string[]) { selectedSessions = options.authenticationSessions ? await options.authenticationSessions(scopes) : [{ accessToken: 'tok', id: 's', account: { id: 'a', label: 'a' }, scopes: [] }]; return selectedSessions; @@ -264,38 +309,83 @@ function createService(store: Pick<{ add(t: T): T provisioningOutcomes.push(outcome); } }()); + const transport = store.add(new class extends GitHubTransport { + override restText(account: AccountHandle, token: string, request: GitHubRestTextRequest, signal: AbortSignal) { + typedRequests.push(request); + return super.restText(account, token, request, signal); + } + }(async (input, init = {}) => { + const lifetime = new DisposableStore(); + try { + const token = init.signal ? CancellationToken.fromAbortSignal(init.signal, lifetime) : CancellationToken.None; + const headers = new Headers(init.headers); + const headerNames: Record = { + accept: 'Accept', authorization: 'Authorization', 'content-type': 'Content-Type', + 'copilot-integration-id': 'Copilot-Integration-Id', 'x-github-api-version': 'X-GitHub-Api-Version', 'if-none-match': 'If-None-Match', + }; + const url = new URL(String(input)); + const context = await requests.request({ + type: init.method, url: url.href, + headers: Object.fromEntries([...headers].map(([name, value]) => [headerNames[name] ?? name, value])), + callSite: url.pathname === '/agents/tasks' ? 'mc.taskClient.list' + : url.pathname === '/agents/tasks/batch' ? 'mc.taskClient.getBatch' + : url.pathname.startsWith('/agents/tasks/') ? 'mc.taskClient.get' : 'test.typed', + ...(typeof init.body === 'string' ? { data: init.body } : {}), + }, token); + const responseHeaders = new Headers(); + for (const [name, values] of Object.entries(context.res.headers)) { + for (const value of Array.isArray(values) ? values : values === undefined ? [] : [values]) { + responseHeaders.append(name, value); + } + } + const body = await asText(context); + return new Response([204, 205, 304].includes(context.res.statusCode ?? 0) ? null : body, { status: context.res.statusCode, headers: responseHeaders }); + } finally { + lifetime.dispose(); + } + }, undefined, false, options.logService ?? new NullLogService())); instantiationService.stub(IWorkbenchGitHubService, new class extends mock() { override async acquireAccountApiClient(authorization: IGitHubAccountClient['authorization']): Promise { 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, signal: AbortSignal, bodyText?: string): Promise> { - 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: `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!; - const body = await asText(context); - if (status !== 200) { - throw new ApiRequestError(status, 'unknown', undefined, undefined, Number(context.res.headers['retry-after']) || undefined); - } - return { status, data: body ?? undefined }; - } finally { - lifetime.dispose(); + const lifetime = new DisposableStore(); + const invalidation = lifetime.add(new Emitter()); + clientInvalidations.push(invalidation); + const controller = new AbortController(); + const state = { authorization, disposed: false }; + clientLifetimes.push(state); + lifetime.add(toDisposable(() => { + state.disposed = true; + controller.abort(new CancellationError()); + })); + let refresh = false; + const credentials: IGitHubCredentials = { + onDidInvalidate: Event.None, + getCredential: async () => { + const sessions = refresh ? await authentication.getSessions(authorization.providerId, [...authorization.scopes]) : selectedSessions; + refresh = false; + const current = sessions.find(candidate => candidate.id === authorization.sessionId && candidate.account.id === authorization.accountId); + if (!current) { + throw new GitHubRequestError('The selected authentication session is unavailable', 'authentication'); } - } - }(); - return new class extends mock() { - override readonly tasks = new TasksClient(new MissionControlClient(options.missionControlProvider ?? provider)); - override readonly environments = new EnvironmentsClient(new MissionControlClient(provider)); - override dispose(): void { } - }(); + return { account: { host: 'api.github.com', accountId: current.account.id }, token: current.accessToken, generation: 0, signal: controller.signal }; + }, + handleRequestError: (_credential, error) => { + refresh ||= error instanceof GitHubRequestError && error.statusCode === 401; + }, + }; + const provider = new LocalMissionControlRequestProvider({ + 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, + }, credentials, transport, options.logService ?? new NullLogService(), controller.signal); + const rest = new LocalApiRequestProvider('https://api.github.com', transport, credentials, 'rest', controller.signal); + return new AccountClient(authorization, { + rest, graphql: rest, missionControl: options.missionControlProvider ?? provider, + onDidInvalidate: invalidation.event, + }, lifetime); } }()); @@ -311,7 +401,14 @@ function createService(store: Pick<{ add(t: T): T requestOutcomes, lifecycleEvents, discoveryEvents, + typedRequests, + clientLifetimes, concurrency, + invalidateClients: () => { + for (const invalidation of clientInvalidations) { + invalidation.fire(); + } + }, changeAuthentication: (kind = 'sessions') => { if (kind === 'register') { providerRegistered.fire({ id: 'github', label: 'GitHub' }); @@ -324,17 +421,217 @@ function createService(store: Pick<{ add(t: T): T }; } +suite('CloudSandboxApiService typed reads', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('reuses typed clients and repository names returned by the task list', async () => { + const current = { ...task('one', 'One', 42, 'session', 'environment'), repository: { id: 42, full_name: 'owner/from-list' } }; + const h = createService(store, { tasks: [current], repositories: new Map() }); + const result = await h.service.listSessions(CancellationToken.None, { includeArchived: false, trigger: 'poll' }); + await h.service.listSessions(CancellationToken.None, { includeArchived: false, trigger: 'manual' }); + await h.service.resolveSession('one', CancellationToken.None); + assert.deepStrictEqual({ + names: result.kind === 'failed' ? [] : result.sessions.map(session => session.repoName), + clients: h.clientLifetimes.length, + reads: h.typedRequests.map(request => ({ path: new URL(request.url).pathname, priority: request.priority })), + repositories: h.requestedUrls.filter(url => url.includes('/repositories/')), + legacyRequestOutcomes: h.requestOutcomes, + }, { + names: ['owner/from-list'], clients: 1, + reads: [ + { path: '/agents/tasks', priority: 'background' }, { path: '/agents/tasks', priority: 'background' }, + { path: '/agents/tasks', priority: 'interactive' }, { path: '/agents/tasks', priority: 'interactive' }, + { path: '/agents/tasks/one', priority: 'interactive' }, + ], + repositories: [], legacyRequestOutcomes: [], + }); + }); + + test('shares one repository enrichment for more tasks than the transport waiter limit', async () => { + const tasks = Array.from({ length: 65 }, (_, index) => task(`task-${index}`, 'Task', 42, `session-${index}`, 'environment')); + const h = createService(store, { + tasks, repositories: new Map([[42, { full_name: 'owner/repository' }]]), + onRequest: async url => { + if (url.pathname === '/repositories/42') { + await timeout(0); + } + return undefined; + }, + }); + const result = await h.service.listSessions(CancellationToken.None); + assert.deepStrictEqual({ + names: result.kind === 'failed' ? [] : result.sessions.map(session => session.repoName), + lookups: h.typedRequests.filter(request => new URL(request.url).pathname === '/repositories/42').length, + misses: h.discoveryEvents.at(-1)?.repositoryEnrichmentMissCount, + }, { names: Array(65).fill('owner/repository'), lookups: 1, misses: 0 }); + }); + + test('repository enrichment returns an invalidated scan without caching stale names after a task mutation', async () => { + const started = new DeferredPromise(); + const response = new DeferredPromise(); + const current = task('task', 'Task', 42, 'session', 'environment'); + const repositories = new Map([[42, { full_name: 'owner/old-name' }]]); + let lookups = 0; + const h = createService(store, { + tasks: [current], repositories, + onRequest: async url => { + if (url.pathname === '/repositories/42' && ++lookups === 1) { + void started.complete(); + await response.p; + } + if (url.pathname === '/agents/tasks/task/archive') { + return jsonResponse(current); + } + return undefined; + }, + }); + const discovery = h.service.listSessions(CancellationToken.None); + await started.p; + await h.service.setTaskArchived('task', true, CancellationToken.None); + await response.complete(); + const invalidated = await discovery; + repositories.set(42, { full_name: 'owner/new-name' }); + const refreshed = await h.service.listSessions(CancellationToken.None); + assert.deepStrictEqual({ + invalidated: invalidated.kind, + generationInvalidated: h.discoveryEvents[0].generationInvalidated, + names: refreshed.kind === 'failed' ? [] : refreshed.sessions.map(session => session.repoName), + lookups, + }, { invalidated: 'failed', generationInvalidated: true, names: ['owner/new-name'], lookups: 2 }); + }); + + test('a later list-page failure preserves the previous checkpoint instead of publishing partial pages', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const original = task('old', 'Old', undefined, 'session', 'environment'); + const tasks = [original]; + let fail = false; + let date = 'Tue, 22 Sep 2026 10:00:00 GMT'; + const h = createService(store, { + tasks, repositories: new Map(), discoveryDate: () => date, + onRequest: url => fail && url.pathname === '/agents/tasks' && url.searchParams.get('page') === '2' + ? jsonResponse({ message: 'Unavailable' }, 503) : undefined, + }); + await h.service.listSessions(CancellationToken.None, { includeArchived: false }); + tasks.unshift(...Array.from({ length: 101 }, (_, index) => task(`new-${index}`, 'New', undefined, 'session', 'environment'))); + fail = true; + date = 'Tue, 22 Sep 2026 10:05:00 GMT'; + const failed = await h.service.listSessions(CancellationToken.None, { includeArchived: false, incremental: true }); + fail = false; + tasks.splice(0, 101); + h.requestedUrls.length = 0; + await h.service.listSessions(CancellationToken.None, { includeArchived: false, incremental: true }); + assert.deepStrictEqual({ + kind: failed.kind, + since: h.requestedUrls.filter(url => new URL(url).pathname === '/agents/tasks').map(url => new URL(url).searchParams.get('since')), + }, { + kind: 'failed', + since: ['2026-09-22T09:59:00.000Z', '2026-09-22T09:59:00.000Z'], + }); + })); + + test('reacquires invalidated and profile-scoped clients', async () => { + const h = createService(store, { tasks: [], repositories: new Map() }); + await h.service.listSessions(CancellationToken.None, { includeArchived: false }); + h.invalidateClients(); + await h.service.listSessions(CancellationToken.None, { includeArchived: false }); + const changed = Event.toPromise(h.service.onDidChangeAccount); + h.changeProfile('other-profile'); + await changed; + await h.service.listSessions(CancellationToken.None, { includeArchived: false }); + assert.deepStrictEqual(h.clientLifetimes.map(client => client.disposed), [true, true, false]); + }); + + test('splits targeted task batches at 50 IDs without individual GETs or inventory filters', async () => { + const tasks = Array.from({ length: 51 }, (_, index) => ({ + ...task(`task-${index}`, 'Task', undefined, `session-${index}`, 'environment'), + ...(index % 2 ? { archived_at: '2026-10-01T00:00:00Z' } : {}), + })); + const h = createService(store, { tasks, repositories: new Map() }); + const ids = tasks.map(task => task.id); + const result = await h.service.listSessions(CancellationToken.None, { taskIds: [...ids, ids[0]], includeArchived: false, trigger: 'feedChange' }); + assert.deepStrictEqual({ + kind: result.kind, tasks: result.kind === 'failed' ? 0 : result.sessions.length, + archived: result.kind === 'failed' ? 0 : result.sessions.filter(task => task.isArchived).length, + requests: h.typedRequests.map(request => { + const url = new URL(request.url); + return { + path: url.pathname, method: request.method, priority: request.priority, + ids: url.searchParams.get('task_ids')?.split(','), filters: [...url.searchParams.keys()], + }; + }), + }, { + kind: 'incremental', tasks: 51, archived: 25, + requests: [ids.slice(0, 50), ids.slice(50)].map(ids => ({ + path: '/agents/tasks/batch', method: 'GET', priority: 'background', ids, filters: ['task_ids'], + })), + }); + }); + + test('successful task batch omissions leave inventory without fallback GETs or remote deletion', async () => { + const visible = task('visible', 'Visible', undefined, 'visible-session', 'environment'); + const omitted = task('omitted', 'Still directly readable', undefined, 'omitted-session', 'environment'); + const h = createService(store, { + tasks: [visible, omitted], repositories: new Map(), + onRequest: url => url.pathname === '/agents/tasks/batch' ? jsonResponse({ tasks: [visible] }) : undefined, + }); + await h.service.listSessions(CancellationToken.None); + await h.service.resolveSession('omitted', CancellationToken.None); + h.requestedUrls.length = 0; + const result = await h.service.listSessions(CancellationToken.None, { taskIds: ['visible', 'omitted'] }); + const discoveryRequests = h.requestedUrls.map(url => new URL(url).pathname); + h.requestedUrls.length = 0; + const resolved = await h.service.resolveSession('omitted', CancellationToken.None); + assert.deepStrictEqual({ + result: result.kind === 'failed' ? result : { + kind: result.kind, tasks: result.sessions.map(task => task.taskId), removed: result.removedTaskIds, + }, + discoveryRequests, + onDemand: { session: resolved.sessionId, requests: h.requestedUrls.map(url => new URL(url).pathname) }, + }, { + result: { kind: 'incremental', tasks: ['visible'], removed: ['omitted'] }, + discoveryRequests: ['/agents/tasks/batch'], + onDemand: { session: 'omitted-session', requests: ['/agents/tasks/omitted'] }, + }); + }); + + test('failed task batches preserve their cached inventory while successful omissions are reconciled', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const tasks = Array.from({ length: 51 }, (_, index) => task(`task-${index}`, 'Original', undefined, `session-${index}`, 'environment')); + const ids = tasks.map(task => task.id); + const h = createService(store, { + tasks, repositories: new Map(), + onRequest: url => url.pathname === '/agents/tasks/batch' + ? url.searchParams.get('task_ids')?.includes('task-0') ? jsonResponse({}, 503) : jsonResponse({ tasks: [] }) + : undefined, + }); + await h.service.listSessions(CancellationToken.None); + await h.service.resolveSession('task-0', CancellationToken.None); + tasks[0] = { ...tasks[0], name: 'Must not replace the cache' }; + h.requestedUrls.length = 0; + const result = await h.service.listSessions(CancellationToken.None, { taskIds: ids }); + const retained = await h.service.resolveSession('task-0', CancellationToken.None); + assert.deepStrictEqual({ + result, + retained: retained.name, + unexpectedRequests: h.requestedUrls.filter(url => new URL(url).pathname !== '/agents/tasks/batch'), + batches: h.discoveryEvents.at(-1)?.taskBatchOperationCount, + failures: h.discoveryEvents.at(-1)?.taskBatchOperationFailureCount, + }, { + result: { kind: 'partial', sessions: [], removedTaskIds: ['task-50'], failedTaskIds: ids.slice(0, 50) }, + retained: 'Original', unexpectedRequests: [], batches: 2, failures: 1, + }); + })); +}); + suite('CloudSandboxApiService discovery telemetry', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); const date = 'Tue, 22 Sep 2026 10:00:00 GMT'; const emptyScan = { trigger: 'unknown', requestedMode: 'full', mode: 'full', outcome: 'complete', - pageCount: 4, listRequestCount: 4, taskCount: 0, sandboxTaskCount: 0, + pageCount: undefined, listRequestCount: undefined, listOperationCount: 4, taskCount: 0, sandboxTaskCount: 0, changedSandboxTaskCount: 0, checkpointAdvanced: true, validDuration: true, }; const summarize = (event: ICloudSandboxDiscoveryTelemetryData) => ({ trigger: event.trigger, requestedMode: event.requestedMode, mode: event.mode, outcome: event.outcome, - pageCount: event.pageCount, listRequestCount: event.listRequestCount, taskCount: event.taskCount, + pageCount: event.pageCount, listRequestCount: event.listRequestCount, listOperationCount: event.listOperationCount, taskCount: event.taskCount, sandboxTaskCount: event.sandboxTaskCount, changedSandboxTaskCount: event.changedSandboxTaskCount, checkpointAdvanced: event.checkpointAdvanced, validDuration: Number.isFinite(event.durationMs) && event.durationMs >= 0, }); @@ -355,26 +652,29 @@ suite('CloudSandboxApiService discovery telemetry', () => { ]); }); - test('distinguishes list page and label failures from targeted detail failures', async () => { + test('distinguishes list and batch failures from optional label failures', async () => { const h = createService(store, { tasks: [task('bad', 'Bad detail', undefined, 's1', 'e1'), task('label', 'Optional label', 42, 's2', 'e2')], repositories: new Map([[42, 'error']]), - onRequest: url => url.pathname === '/agents/tasks/bad' || url.pathname === '/agents/tasks' && url.searchParams.get('is_archived') === 'true' + onRequest: url => url.pathname === '/agents/tasks/batch' && url.searchParams.get('task_ids') === 'bad' + || url.pathname === '/agents/tasks' && url.searchParams.get('is_archived') === 'true' ? jsonResponse({}, 503) : undefined, }); await h.service.listSessions(CancellationToken.None); const listDetailReads = h.requestedUrls.filter(url => new URL(url).pathname.startsWith('/agents/tasks/')); - await h.service.listSessions(CancellationToken.None, { taskIds: ['bad', 'label'], trigger: 'feedChange' }); + await h.service.listSessions(CancellationToken.None, { taskIds: ['bad'], trigger: 'feedChange' }); + await h.service.listSessions(CancellationToken.None, { taskIds: ['label'], trigger: 'feedChange' }); const summarizeFailures = (event: ICloudSandboxDiscoveryTelemetryData) => ({ - outcome: event.outcome, pages: event.listPageFailureCount, details: event.taskDetailFailureCount, + outcome: event.outcome, lists: event.listOperationFailureCount, batches: event.taskBatchOperationFailureCount, details: event.taskDetailFailureCount, labels: event.repositoryEnrichmentMissCount, unresolved: event.unresolvedTaskCount, advanced: event.checkpointAdvanced, invalidated: event.generationInvalidated, }); assert.deepStrictEqual({ listDetailReads, events: h.discoveryEvents.map(summarizeFailures) }, { listDetailReads: [], events: [ - { outcome: 'partial', pages: 2, details: 0, labels: 1, unresolved: 0, advanced: false, invalidated: false }, - { outcome: 'partial', pages: 0, details: 1, labels: 1, unresolved: 1, advanced: false, invalidated: false }, + { outcome: 'failed', lists: 1, batches: 0, details: 0, labels: 0, unresolved: 0, advanced: false, invalidated: false }, + { outcome: 'partial', lists: 0, batches: 1, details: 0, labels: 0, unresolved: 1, advanced: false, invalidated: false }, + { outcome: 'incremental', lists: 0, batches: 0, details: 0, labels: 1, unresolved: 0, advanced: false, invalidated: false }, ], }); }); @@ -394,7 +694,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { tasks: [], repositories: new Map(), onRequest: async url => { if (url.pathname === '/agents/tasks/removed') { - return jsonResponse({}); + return jsonResponse({}, 204); } if (!entered.isSettled) { await entered.complete(); @@ -409,7 +709,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { await pending.complete(); await scan; assert.deepStrictEqual({ - bounded: { outcome: bounded.outcome, unread: bounded.unreadPageScopeCount, failures: bounded.listPageFailureCount, advanced: bounded.checkpointAdvanced }, + bounded: { outcome: bounded.outcome, unread: bounded.unreadPageScopeCount, failures: bounded.listOperationFailureCount, advanced: bounded.checkpointAdvanced }, invalidated: { outcome: invalidated.discoveryEvents[0].outcome, generation: invalidated.discoveryEvents[0].generationInvalidated, advanced: invalidated.discoveryEvents[0].checkpointAdvanced }, }, { bounded: { outcome: 'complete', unread: 4, failures: 0, advanced: true }, @@ -425,14 +725,14 @@ suite('CloudSandboxApiService discovery telemetry', () => { assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ { ...emptyScan, trigger: 'feedRenewal', requestedMode: 'incremental' }, { ...emptyScan, trigger: 'poll', requestedMode: 'incremental', mode: 'incremental', outcome: 'incremental', checkpointAdvanced: false }, - { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', pageCount: 0, listRequestCount: 0, checkpointAdvanced: false }, + { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', listOperationCount: 0, checkpointAdvanced: false }, ]); }); test('counts returned tasks separately from changed sandbox summaries', async () => { const tasks: ITestTask[] = [ task('sandbox', 'Private task name', undefined, 'session', 'environment'), - { ...task('other', 'Other task', undefined, 'other-session', 'other-environment'), compute: { provider: 'other' } }, + { ...task('other', 'Other task', undefined, 'other-session', 'other-environment'), compute: { provider: 'codespaces' } }, ]; const h = createService(store, { tasks, repositories: new Map(), discoveryDate: () => date }); await h.service.listSessions(CancellationToken.None, { trigger: 'startup' }); @@ -442,11 +742,11 @@ suite('CloudSandboxApiService discovery telemetry', () => { assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ { ...emptyScan, trigger: 'startup', taskCount: 2, sandboxTaskCount: 1, changedSandboxTaskCount: 1 }, { ...emptyScan, trigger: 'manual', taskCount: 2, sandboxTaskCount: 1, checkpointAdvanced: false }, - { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', pageCount: 0, listRequestCount: 0, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1, checkpointAdvanced: false }, + { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', listOperationCount: 0, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1, checkpointAdvanced: false }, ]); }); - test('deduplicates returned tasks while counting each successfully parsed page', async () => { + test('deduplicates returned tasks while counting logical list operations', async () => { const repeated = task('repeated', 'Private task', undefined, 'session', 'environment'); const h = createService(store, { tasks: [], repositories: new Map(), @@ -456,14 +756,14 @@ suite('CloudSandboxApiService discovery telemetry', () => { }); await h.service.listSessions(CancellationToken.None); assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ - { ...emptyScan, pageCount: 5, listRequestCount: 5, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1 }, + { ...emptyScan, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1 }, ]); }); - test('counts rate-limit retries as HTTP attempts, not extra pages', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('counts a refused list once without estimating transport attempts', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const h = createService(store, { tasks: [], repositories: new Map(), rateLimitedListPages: 2, retryAfterSeconds: 1 }); await h.service.listSessions(CancellationToken.None); - assert.deepStrictEqual(h.discoveryEvents.map(summarize), [{ ...emptyScan, listRequestCount: 6 }]); + assert.deepStrictEqual(h.discoveryEvents.map(summarize), [{ ...emptyScan, outcome: 'failed', listOperationCount: 1, checkpointAdvanced: false }]); })); for (const status of [401, 403]) { @@ -482,7 +782,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { refused = false; await timeout(15 * 60_000); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal', incremental: true }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [ + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [ ['failed', 1], ['failed', 0], ['failed', 0], ['failed', 0], ['failed', 1], ['incremental', 0], ['complete', 4], ]); })); @@ -498,7 +798,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { refused = false; await h.service.listSessions(CancellationToken.None, { trigger: 'manual' }); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal', incremental: true }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [ + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [ ['failed', 1], ['complete', 4], ['incremental', 4], ]); }); @@ -515,7 +815,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); await timeout(15 * 60_000); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [ + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [ ['failed', 1], ['failed', 0], ['complete', 4], ]); })); @@ -542,10 +842,10 @@ suite('CloudSandboxApiService discovery telemetry', () => { await pending.complete(); await stale; await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [['failed', 1], ['complete', 4]]); + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [['failed', 1], ['complete', 4]]); }); - test('paces the credential refused after in-request authentication recovery', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('shared cooldown protects the credential refused after in-request authentication recovery', () => runWithFakedTimers({ useFakeTimers: true }, async () => { let accessToken = 'original'; const credentials: (IHeaders[string] | undefined)[] = []; const h = createService(store, { @@ -567,8 +867,8 @@ suite('CloudSandboxApiService discovery telemetry', () => { await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); await timeout(15 * 60_000); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); - assert.deepStrictEqual({ credentials, reads: h.discoveryEvents.map(event => event.listRequestCount) }, { - credentials: ['Bearer original', 'Bearer replacement'], reads: [2, 0, 0], + assert.deepStrictEqual({ credentials, reads: h.discoveryEvents.map(event => event.listOperationCount) }, { + credentials: ['Bearer original', 'Bearer replacement'], reads: [1, 1, 1], }); })); @@ -601,7 +901,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { } refused = false; await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [['failed', 1], ['complete', 4]]); + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [['failed', 1], ['complete', 4]]); }); } @@ -609,15 +909,15 @@ suite('CloudSandboxApiService discovery telemetry', () => { { status: 403, body: { error_code: 'rate_limit_exceeded' } }, { status: 503, body: {} }, ]) { - test(`does not apply authorization pacing to HTTP ${response.status} ${JSON.stringify(response.body)}`, async () => { + test(`does not apply authorization pacing to HTTP ${response.status} ${JSON.stringify(response.body)}`, () => runWithFakedTimers({}, async () => { const h = createService(store, { tasks: [], repositories: new Map(), onRequest: url => url.pathname === '/agents/tasks' ? jsonResponse(response.body, response.status) : undefined, }); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); await h.service.listSessions(CancellationToken.None, { trigger: 'feedRenewal' }); - assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listRequestCount]), [['failed', 1], ['failed', 1]]); - }); + assert.deepStrictEqual(h.discoveryEvents.map(event => [event.outcome, event.listOperationCount]), [['failed', 1], ['failed', 1]]); + })); } test('detail endpoint failures do not block summary discovery or its checkpoint', async () => { @@ -650,9 +950,9 @@ suite('CloudSandboxApiService discovery telemetry', () => { }); await assert.rejects(h.service.listSessions(cancellation.token), CancellationError); assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ - { ...emptyScan, outcome: 'cancelled', pageCount: 1, listRequestCount: 2, checkpointAdvanced: false }, + { ...emptyScan, outcome: 'cancelled', listOperationCount: 1, checkpointAdvanced: false }, ]); - assert.strictEqual(h.discoveryEvents[0].checkpointSource, 'serverDate'); + assert.strictEqual(h.discoveryEvents[0].checkpointSource, 'unavailable'); }); test('retains the observed checkpoint source when an empty partition is followed by a list failure', async () => { @@ -664,23 +964,23 @@ suite('CloudSandboxApiService discovery telemetry', () => { }); await h.service.listSessions(CancellationToken.None); assert.deepStrictEqual(h.discoveryEvents.map(event => ({ - source: event.checkpointSource, outcome: event.outcome, advanced: event.checkpointAdvanced, pages: event.pageCount, - })), [{ source: 'serverDate', outcome: 'failed', advanced: false, pages: 1 }]); + source: event.checkpointSource, outcome: event.outcome, advanced: event.checkpointAdvanced, lists: event.listOperationCount, + })), [{ source: 'serverDate', outcome: 'failed', advanced: false, lists: 2 }]); }); test('reports malformed successful HTTP responses as failed discovery', async () => { const h = createService(store, { tasks: [], repositories: new Map(), onRequest: () => jsonResponse({ privateData: 'not a task list' }) }); await h.service.listSessions(CancellationToken.None); assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ - { ...emptyScan, outcome: 'failed', pageCount: 0, listRequestCount: 1, checkpointAdvanced: false }, + { ...emptyScan, outcome: 'failed', listOperationCount: 1, checkpointAdvanced: false }, ]); }); - test('does not count HTTP attempts when authentication prevents discovery', async () => { + test('does not count list operations when authentication prevents discovery', async () => { const h = createService(store, { tasks: [], repositories: new Map(), authenticationSessions: async () => [] }); await h.service.listSessions(CancellationToken.None); assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ - { ...emptyScan, outcome: 'failed', pageCount: 0, listRequestCount: 0, checkpointAdvanced: false }, + { ...emptyScan, outcome: 'failed', listOperationCount: 0, checkpointAdvanced: false }, ]); }); @@ -703,7 +1003,7 @@ suite('CloudSandboxApiService discovery telemetry', () => { await pending.complete(); await inventory; assert.deepStrictEqual(h.discoveryEvents.map(summarize), [ - { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', pageCount: 0, listRequestCount: 0, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1, checkpointAdvanced: false }, + { ...emptyScan, trigger: 'feedChange', requestedMode: 'targeted', mode: 'targeted', outcome: 'incremental', listOperationCount: 0, taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1, checkpointAdvanced: false }, { ...emptyScan, trigger: 'startup', taskCount: 1, sandboxTaskCount: 1, changedSandboxTaskCount: 1 }, ]); }); @@ -725,7 +1025,7 @@ suite('CloudSandboxApiService identity credentials', () => { await timeout(500); return jsonResponse({ token: 'identity', expires_in: 60, expires_at: new Date(started + 90_000).toISOString() }); } - return jsonResponse({ id: 'env-1', status: 'online' }); + return jsonResponse({ id: 'env-1', name: 'Environment', kind: 'managed-sandbox', status: 'online' }); }, }); const identity = await service.getIdentityToken(accountKey, CancellationToken.None); @@ -738,7 +1038,7 @@ suite('CloudSandboxApiService identity credentials', () => { { url: endpoint, method: 'POST', authorization: 'Bearer tok', contentType: 'application/json', data: '{}' }, { url: 'https://api.githubcopilot.com/agents/environments/env-1', method: 'GET', authorization: 'Bearer tok', contentType: undefined, data: undefined }, ], - requestOutcomes: [['mintIdentityToken', 'succeeded'], ['getEnvironment', 'succeeded']], + requestOutcomes: [['mintIdentityToken', 'succeeded']], }); })); @@ -761,6 +1061,16 @@ suite('CloudSandboxApiService identity credentials', () => { }); }); + test('preserves network failure attribution when acquiring identity credentials', async () => { + const failure = new GitHubRequestError('network unavailable', 'network'); + const { service } = createService(store, { + tasks: [], repositories: new Map(), + missionControlProvider: { request: async () => { throw failure; } }, + }); + await assert.rejects(service.getIdentityToken(accountKey, CancellationToken.None), error => error instanceof Error + && error.name === 'CloudSandboxNetworkError' && error.cause === undefined); + }); + test('refreshes the identity cache after a REST request recovers with a new GitHub credential', async () => { let lookups = 0; let environmentRequests = 0; @@ -777,7 +1087,7 @@ suite('CloudSandboxApiService identity credentials', () => { } return ++environmentRequests === 1 ? jsonResponse({ error_code: 'unauthenticated' }, 401) - : jsonResponse({ id: 'env-1', status: 'online' }); + : jsonResponse({ id: 'env-1', name: 'Environment', kind: 'managed-sandbox', status: 'online' }); }, }); const first = await service.getIdentityToken(accountKey, CancellationToken.None); @@ -1059,7 +1369,7 @@ suite('CloudSandboxApiService token sealing', () => { url: endpoint, method: 'POST', authorization: 'Bearer tok', contentType: 'application/json', body: { token: request.token, ...(resource === undefined ? {} : { resource }) }, }], - requestOutcomes: [['sealToken', 'succeeded']], + requestOutcomes: [], }); }); } @@ -1079,7 +1389,7 @@ suite('CloudSandboxApiService token sealing', () => { seals++; return jsonResponse(response); } - return jsonResponse({ id: 'env-1', status: 'online' }); + return jsonResponse({ id: 'env-1', name: 'Environment', kind: 'managed-sandbox', status: 'online' }); }, }); const identity = await service.getIdentityToken(JSON.stringify(['github', 'a']), CancellationToken.None); @@ -1120,7 +1430,7 @@ suite('CloudSandboxApiService token sealing', () => { }); const error = await readSealingError(service); assert.deepStrictEqual({ message: error.message, requests: requestedUrls.length }, { - message: 'The sandbox token-sealing response is invalid.', requests: 1, + message: 'The API may have accepted the operation; reconcile before trying again', requests: 1, }); }); } @@ -1144,8 +1454,8 @@ suite('CloudSandboxApiService token sealing', () => { exposesToken: [...logService.traces, ...logService.errors].some(message => String(message).includes(request.token)), }, { status, retryAfter: 45, - message: `Sandbox token sealing failed: HTTP ${status} (request ABCD:1234:5678:90AB:CDEF).`, - authentications: 1, requests: 1, requestOutcomes: [['sealToken', status < 500 ? 'clientError' : 'serverError']], exposesToken: false, + message: `Mission Control token sealing failed: HTTP ${status} (requestId=ABCD:1234:5678:90AB:CDEF)`, + authentications: 1, requests: 1, requestOutcomes: [], exposesToken: false, }); }); } @@ -1308,7 +1618,10 @@ suite('CloudSandboxApiService session feed', () => { new GitHubRequestTimeoutError(false), new GitHubRequestError('private-schema-error', 'schema'), ]) { - const h = createService(store, { tasks: [], repositories: new Map(), requestError }); + const h = createService(store, { + tasks: [], repositories: new Map(), + missionControlProvider: { request: async () => { throw requestError; } }, + }); await assert.rejects(h.service.connectSessionFeed(CancellationToken.None)); outcomes.push(h.requestOutcomes); } @@ -1453,7 +1766,7 @@ suite('CloudSandboxApiService session feed', () => { void requested.complete(); return response.p; } - return jsonResponse({}); + return jsonTaskResponse({ id: 'task' }); }, }); const pending = h.service.connectSessionFeed(CancellationToken.None); @@ -1516,7 +1829,7 @@ suite('CloudSandboxApiService feed task refresh', () => { const { service } = createService(store, { tasks, repositories: new Map(), onRequest: url => { - if (hold && url.pathname === '/agents/tasks/task') { + if (hold && url.pathname === '/agents/tasks/batch') { void entered.complete(); return pending.p; } @@ -1529,7 +1842,7 @@ suite('CloudSandboxApiService feed task refresh', () => { await entered.p; tasks.length = 0; await service.listSessions(CancellationToken.None); - await pending.complete(jsonResponse(original)); + await pending.complete(jsonResponse({ tasks: [original] })); assert.deepStrictEqual(await refresh, { kind: 'incremental', sessions: [], removedTaskIds: ['task'] }); }); @@ -1542,7 +1855,7 @@ suite('CloudSandboxApiService feed task refresh', () => { const { service } = createService(store, { tasks, repositories: new Map(), onRequest: url => { - if (hold && url.pathname === '/agents/tasks/task') { + if (hold && url.pathname === '/agents/tasks/batch') { void entered.complete(); return pending.p; } @@ -1554,10 +1867,10 @@ suite('CloudSandboxApiService feed task refresh', () => { const targeted = service.listSessions(CancellationToken.None, { taskIds: ['task'] }); await entered.p; tasks.unshift(...Array.from({ length: 301 }, (_, i) => ({ - ...task(`new-${i}`, 'Other task', undefined, `s-${i}`, `e-${i}`), compute: { provider: 'other' }, + ...task(`new-${i}`, 'Other task', undefined, `s-${i}`, `e-${i}`), compute: { provider: 'codespaces' }, }))); const scan = await service.listSessions(CancellationToken.None); - await pending.complete(jsonResponse(original)); + await pending.complete(jsonResponse({ tasks: [original] })); const refreshed = await targeted; assert.deepStrictEqual({ @@ -1630,8 +1943,8 @@ suite('CloudSandboxApiService feed task refresh', () => { tasks: [known], repositories: new Map([[42, { full_name: 'owner/repo' }]]), onRequest: url => { if (!hold) { return undefined; } - if (url.pathname === '/agents/tasks/removed') { - return jsonResponse({}, 404); + if (url.pathname === '/agents/tasks/batch') { + return jsonResponse({ tasks: [] }); } if (url.pathname === '/agents/tasks') { if (!entered.isSettled) { @@ -1661,7 +1974,7 @@ suite('CloudSandboxApiService feed task refresh', () => { const { service, requestedUrls } = createService(store, { tasks: [first, second], repositories: new Map(), onRequest: url => { - if (url.pathname === '/agents/tasks/first' && !entered.isSettled) { + if (url.pathname === '/agents/tasks/batch' && url.searchParams.get('task_ids') === 'first' && !entered.isSettled) { void entered.complete(); return pending.p; } @@ -1671,7 +1984,7 @@ suite('CloudSandboxApiService feed task refresh', () => { const firstRefresh = service.listSessions(CancellationToken.None, { taskIds: ['first'] }); await entered.p; await service.listSessions(CancellationToken.None, { taskIds: ['second'] }); - await pending.complete(jsonResponse(first)); + await pending.complete(jsonResponse({ tasks: [first] })); await firstRefresh; const beforeScan = requestedUrls.length; const result = await service.listSessions(CancellationToken.None); @@ -1686,7 +1999,6 @@ suite('CloudSandboxApiService feed task refresh', () => { const entered = new DeferredPromise(); const original = { ...task('task', 'Old title', undefined, 'session', 'environment'), updated_at: '2026-10-18T00:00:00Z' }; const newer = { ...original, name: 'New title', updated_at: '2026-10-18T00:01:00Z' }; - let updated = false; const { service } = createService(store, { tasks: [original], repositories: new Map(), onRequest: url => { @@ -1697,13 +2009,12 @@ suite('CloudSandboxApiService feed task refresh', () => { } return jsonResponse({ tasks: [] }); } - return updated && url.pathname === '/agents/tasks/task' ? jsonResponse(newer) : undefined; + return undefined; }, }); const scan = service.listSessions(CancellationToken.None); await entered.p; await service.listSessions(CancellationToken.None, { taskIds: ['task'] }); - updated = true; await pending.complete(jsonResponse({ tasks: [newer] })); const result = await scan; assert.deepStrictEqual(result.kind === 'failed' ? [] : result.sessions.map(session => session.name), ['New title']); @@ -1740,10 +2051,10 @@ suite('CloudSandboxApiService feed task refresh', () => { requests: requestedUrls.map(url => new URL(url).pathname), }, { results: [ - { kind: 'incremental', sessions: [{ taskId: 'provisioning', sessionId: 'session', environmentId: 'environment', name: 'New remote session', status: SessionStatus.InProgress }] }, - { kind: 'incremental', sessions: [{ taskId: 'provisioning', sessionId: 'session', environmentId: 'environment', name: 'Ready sandbox', status: SessionStatus.Idle }] }, + { kind: 'incremental', sessions: [{ taskId: 'provisioning', sessionId: undefined, environmentId: undefined, name: 'New remote session', status: SessionStatus.InProgress }] }, + { kind: 'incremental', sessions: [{ taskId: 'provisioning', sessionId: undefined, environmentId: undefined, name: 'Ready sandbox', status: SessionStatus.Idle }] }, ], - requests: ['/agents/tasks/provisioning', '/agents/tasks/provisioning'], + requests: ['/agents/tasks/batch', '/agents/tasks/batch'], }); }); @@ -1761,12 +2072,12 @@ suite('CloudSandboxApiService feed task refresh', () => { sessions: result.kind === 'failed' ? [] : result.sessions.map(session => [session.taskId, session.name]), urls, other: other.kind === 'failed' ? [] : other.sessions.map(session => [session.taskId, session.name]), - }, { kind: 'incremental', sessions: [['one', 'Renamed']], urls: ['/agents/tasks/one'], other: [['two', 'Second']] }); + }, { kind: 'incremental', sessions: [['one', 'Renamed']], urls: ['/agents/tasks/batch'], other: [['two', 'Second']] }); }); - test('discovers new sandbox tasks without listing and ignores non-sandbox task hints', async () => { + test('discovers new sandbox tasks without inventory scans or detail GETs and ignores non-sandbox hints', async () => { const { service, requestedUrls } = createService(store, { - tasks: [task('sandbox', 'New', undefined, 's1', 'e1'), { ...task('actions', 'Other', undefined, 's2', 'e2'), compute: { provider: 'actions' }, current_environment: { id: 'e2', kind: 'managed-actions' } }], + tasks: [task('sandbox', 'New', undefined, 's1', 'e1'), { ...task('actions', 'Other', undefined, 's2', 'e2'), compute: undefined, current_environment: { id: 'e2', kind: 'managed-actions' } }], repositories: new Map(), }); const result = await service.listSessions(CancellationToken.None, { taskIds: ['sandbox', 'actions'] }); @@ -1774,16 +2085,16 @@ suite('CloudSandboxApiService feed task refresh', () => { kind: result.kind, tasks: result.kind === 'failed' ? [] : result.sessions.map(session => session.taskId), urls: requestedUrls.map(url => new URL(url).pathname).sort(), - }, { kind: 'incremental', tasks: ['sandbox'], urls: ['/agents/tasks/actions', '/agents/tasks/sandbox'] }); + }, { kind: 'incremental', tasks: ['sandbox'], urls: ['/agents/tasks/batch'] }); }); for (const status of [403, 404, 500]) { - test(`handles hinted task HTTP ${status} without erasing unrelated inventory`, async () => { + test(`retains hinted inventory when a task batch returns HTTP ${status}`, async () => { let fail = false; const { service, requestedUrls } = createService(store, { tasks: [task('one', 'First', undefined, 's1', 'e1'), task('two', 'Second', undefined, 's2', 'e2')], repositories: new Map(), - onRequest: url => fail && url.pathname === '/agents/tasks/one' ? jsonResponse({}, status) : undefined, + onRequest: url => fail && url.pathname === '/agents/tasks/batch' ? jsonResponse({}, status) : undefined, }); await service.listSessions(CancellationToken.None); fail = true; @@ -1793,8 +2104,8 @@ suite('CloudSandboxApiService feed task refresh', () => { result, urls: requestedUrls.slice(start).map(url => new URL(url).pathname), }, { - result: { kind: status === 500 ? 'partial' : 'incremental', sessions: [], removedTaskIds: status === 500 ? [] : ['one'], ...(status === 500 ? { failedTaskIds: ['one'] } : {}) }, - urls: ['/agents/tasks/one'], + result: { kind: 'partial', sessions: [], removedTaskIds: [], failedTaskIds: ['one'] }, + urls: Array(status === 500 ? 2 : 1).fill('/agents/tasks/batch'), }); }); } @@ -1830,12 +2141,12 @@ suite('CloudSandboxApiService connection credentials', () => { const otherConnectionId = generateUuid(); const { service, lifecycleEvents } = createService(store, { tasks: [], repositories: new Map(), - onRequest: () => jsonResponse({ access_token: 'private', wps_endpoint: 'https://private.invalid', client_id: otherConnectionId, groups: {} }), + onRequest: () => jsonResponse(clientToken(otherConnectionId)), }); - await assert.rejects(service.reconnect({ environmentId: generateUuid() }, connectionId, CancellationToken.None), /different client/); + await assert.rejects(service.reconnect({ environmentId: generateUuid() }, connectionId, CancellationToken.None), MutationUncertainError); assert.deepStrictEqual(lifecycleEvents.map(event => [event.phase, event.outcome, event.connectionId, event.failurePoint]), [ ['credentials.refresh', 'started', connectionId, undefined], - ['credentials.refresh', 'failed', connectionId, 'credentials.clientMismatch'], + ['credentials.refresh', 'failed', connectionId, 'credentials.invalidResponse'], ]); }); @@ -1844,11 +2155,11 @@ suite('CloudSandboxApiService connection credentials', () => { tasks: [], repositories: new Map(), onRequest: () => jsonResponse({ access_token: 'private response' }), }); - await assert.rejects(service.connect({ environmentId: generateUuid() }, CancellationToken.None), /incomplete token/); + await assert.rejects(service.connect({ environmentId: generateUuid() }, CancellationToken.None), MutationUncertainError); assert.deepStrictEqual({ failurePoint: lifecycleEvents.at(-1)?.failurePoint, privateContent: JSON.stringify(lifecycleEvents).includes('private'), - }, { failurePoint: 'credentials.incompleteResponse', privateContent: false }); + }, { failurePoint: 'credentials.invalidResponse', privateContent: false }); }); for (const failure of ['signed out', 'already cancelled', 'cancelled in flight', 'HTTP error', 'network error'] as const) { @@ -1880,7 +2191,7 @@ suite('CloudSandboxApiService connection credentials', () => { }); } - function clientToken(clientId: string): ICloudSandboxClientToken { + function clientToken(clientId: string): ClientTokenResponse { const groupPrefix = `user.u1.env.env-1.client.${clientId}`; return { access_token: 'relay-token', @@ -1889,10 +2200,12 @@ suite('CloudSandboxApiService connection credentials', () => { hub: 'hub', subprotocol: 'json.reliable.webpubsub.azure.v1', client_id: clientId, + environment_status: 'online', groups: { broadcast: `${groupPrefix}.broadcast`, to_client: `${groupPrefix}.to-client`, to_host: `${groupPrefix}.to-host`, + clients: 'user.u1.env.env-1.clients', }, }; } @@ -1920,7 +2233,7 @@ suite('CloudSandboxApiService connection credentials', () => { throw new CancellationError(); } return response === 'token' ? jsonResponse(clientToken(connectionId)) - : response === 'waking' ? jsonResponse({}, 202, { 'retry-after': '45' }) + : response === 'waking' ? jsonResponse({ environment_status: 'waking' }, 202, { 'retry-after': '45' }) : response === 'httpError' ? jsonResponse({ message: 'private chat content' }, 403) : jsonResponse({ access_token: 'private-token' }); }, @@ -1948,13 +2261,14 @@ suite('CloudSandboxApiService connection credentials', () => { } } - test('allows thirty seconds for connection requests while keeping environment reads at ten seconds', async () => { + test('uses shared default deadlines for connection requests and environment reads', async () => { const requests: { path: string; timeout: number | undefined }[] = []; - const { service } = createService(store, { + const { service, typedRequests } = createService(store, { tasks: [], repositories: new Map(), onRequest: (url, _token, options) => { requests.push({ path: url.pathname, timeout: options.timeout }); - return jsonResponse(url.pathname === '/agents/environments/env-1' ? { status: 'online' } : clientToken('client-1')); + return jsonResponse(url.pathname === '/agents/environments/env-1' + ? { id: 'env-1', name: 'Environment', kind: 'managed-sandbox', status: 'online' } : clientToken('client-1')); }, }); @@ -1962,11 +2276,15 @@ suite('CloudSandboxApiService connection credentials', () => { await service.reconnect(request, 'client-1', CancellationToken.None); await service.getEnvironment(request.environmentId, CancellationToken.None); - assert.deepStrictEqual(requests, [ - { path: '/agents/environments/env-1/connect', timeout: 30_000 }, - { path: '/agents/environments/env-1/reconnect', timeout: 30_000 }, - { path: '/agents/environments/env-1', timeout: 10_000 }, - ]); + assert.deepStrictEqual({ + requests, + explicitDeadlines: typedRequests.map(request => request.deadline), + }, { + requests: ['connect', 'reconnect', ''].map(action => ({ + path: `/agents/environments/env-1${action ? `/${action}` : ''}`, timeout: undefined, + })), + explicitDeadlines: [undefined, undefined, undefined], + }); }); test('loads cloud models and reasoning metadata without creating a task or environment', async () => { @@ -2109,7 +2427,7 @@ suite('CloudSandboxApiService connection credentials', () => { for (const body of [{}, { data: [null] }, { data: [{ id: 'bad', name: 'Bad', capabilities: { supports: { reasoning_effort: [1] } } }] }]) { test(`rejects invalid cloud model metadata: ${JSON.stringify(body)}`, async () => { const { service } = createService(store, { tasks: [], repositories: new Map(), onRequest: () => jsonResponse(body) }); - await assert.rejects(service.listModels(CancellationToken.None), /invalid model/); + await assert.rejects(service.listModels(CancellationToken.None), SchemaError); }); } @@ -2220,7 +2538,7 @@ suite('CloudSandboxApiService connection credentials', () => { const observedRequest = { ...request, onRequest: (event: string) => progress.push(event) }; const { service } = createService(store, { tasks: [], repositories: new Map(), - onRequest: () => jsonResponse({}, 202, { 'retry-after': '5' }), + onRequest: () => jsonResponse({ environment_status: 'waking' }, 202, { 'retry-after': '5' }), }); const result = action === 'connect' @@ -2231,16 +2549,28 @@ suite('CloudSandboxApiService connection credentials', () => { }); } + for (const status of [200, 201]) { + test(`preserves malformed successful read errors without converting HTTP ${status} to a sandbox HTTP failure`, async () => { + const { service } = createService(store, { + tasks: [], repositories: new Map(), + onRequest: () => ({ res: { statusCode: status, headers: {} }, stream: bufferToStream(VSBuffer.fromString('invalid JSON')) }), + }); + await assert.rejects(service.getEnvironment('environment', CancellationToken.None), { + name: 'GitHubRequestError', kind: 'malformedResponse', statusCode: status, + }); + }); + } + test('preserves transport errors from environment reads without classifying them for connection retries', async () => { const failure = new Error('network unavailable'); const { service } = createService(store, { tasks: [], repositories: new Map(), onRequest: () => { throw failure; }, }); - await assert.rejects(service.getEnvironment(request.environmentId, CancellationToken.None), error => error === failure); + await assert.rejects(service.getEnvironment(request.environmentId, CancellationToken.None), GitHubRequestError); }); - for (const header of [undefined, 'ABCD:1234:5678', 'ABCD:1234:5678:90AB:CDEF\ninjected', 'ghp_secret', 'A'.repeat(129), ['ABCD:1234:5678:90AB:CDEF', 'ABCD:1234:5678:90AB:CDEF']]) { + for (const header of [undefined, 'ABCD:1234:5678', 'ABCD:1234:5678:90AB:CDEF\tinjected', 'ghp_secret', 'A'.repeat(129), ['ABCD:1234:5678:90AB:CDEF', 'ABCD:1234:5678:90AB:CDEF']]) { test(`omits unavailable or invalid request IDs: ${JSON.stringify(header)}`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { const logService = new TestLogService(); const { service } = createService(store, { @@ -2269,14 +2599,14 @@ suite('CloudSandboxApiService connection credentials', () => { await assert.rejects( service.reconnect(request, 'client-1', CancellationToken.None), - /Cloud sandbox reconnect returned credentials for a different client/, + MutationUncertainError, ); }); test('parses a pending response with an HTTP-date Retry-After', () => runWithFakedTimers({ useFakeTimers: true, startTime: Date.UTC(2026, 0, 1) }, async () => { const { service } = createService(store, { tasks: [], repositories: new Map(), - onRequest: () => jsonResponse({}, 202, { 'retry-after': new Date(Date.now() + 45_000).toUTCString() }), + onRequest: () => jsonResponse({ environment_status: 'waking' }, 202, { 'retry-after': new Date(Date.now() + 45_000).toUTCString() }), }); assert.deepStrictEqual(await service.connect(request, CancellationToken.None), { kind: 'waking', waking: { retryAfterSeconds: 45 }, @@ -2316,6 +2646,7 @@ suite('CloudSandboxApiService connection credentials', () => { name: 'CloudSandboxRequestError', statusCode: response.status, retryAfterSeconds: 5, code: response.code, limitedResource: response.resource, requestId: 'ABCD:1234:5678:90AB:CDEF', message: `Mission Control connect failed: HTTP ${response.status} code=${response.code} (requestId=ABCD:1234:5678:90AB:CDEF)`, + outcome: undefined, privateContent: false, }); return true; @@ -2349,7 +2680,8 @@ suite('CloudSandboxApiService connection credentials', () => { if (replacement === 'new credential') { await connecting; } else { - await assert.rejects(connecting, replacement === 'cancelled' ? isCancellationError : { statusCode: 401, code: 'unauthenticated' }); + await assert.rejects(connecting, replacement === 'cancelled' ? isCancellationError + : replacement === 'unavailable' ? /provider unavailable/ : { statusCode: 401, code: 'unauthenticated' }); } assert.deepStrictEqual({ lookups, requests: requestedUrls.length }, { lookups: 2, requests: replacement === 'new credential' || replacement === 'rejected again' ? 2 : 1, @@ -2641,7 +2973,8 @@ suite('CloudSandboxApiService history cache', () => { test(`${mutation} invalidates the affected task without evicting other tasks`, async () => { const { service } = createService(store, { tasks: [], repositories: new Map(), - onRequest: url => url.pathname.endsWith('/events') ? historyResponse('Recorded') : jsonResponse({}), + onRequest: url => url.pathname.endsWith('/events') ? historyResponse('Recorded') + : mutation === 'delete' ? jsonResponse({}, 204) : jsonTaskResponse({ id: 'task' }), }); await service.getSessionHistory('task', CancellationToken.None); await service.getSessionHistory('unaffected', CancellationToken.None); @@ -2706,7 +3039,7 @@ suite('Mission Control environment discovery', () => { }, { requests: [{ path: '/agents/environments/host%2Fwith%20spaces', method: 'DELETE', body: undefined }], cached: undefined, - deleteOutcomes: [['deleteEnvironment', statusCode === 204 ? 'succeeded' : 'clientError']], + deleteOutcomes: [], }); }); } @@ -2730,7 +3063,11 @@ suite('Mission Control environment discovery', () => { const { service, requestedUrls, changeAuthentication } = createService(store, { tasks: [], repositories: new Map(), onRequest: url => url.pathname.endsWith('/agents/environments') ? jsonResponse([{ - id: 'host', kind: 'user-local', name: 'Native host', status: 'online', webpubsub: { access_token: 'must-not-be-cached' }, + id: 'host', kind: 'user-local', name: 'Native host', status: 'online', + webpubsub: { + url: 'wss://relay.example.test', hub: 'hub', subprotocol: 'json.reliable.webpubsub.azure.v1', + access_token: 'must-not-be-cached', groups: { control: 'control', ingest_ack: 'ack', events: 'events', lifecycle: 'lifecycle' }, + }, }]) : undefined, }); const first = await service.listEnvironments(CancellationToken.None); @@ -2761,7 +3098,7 @@ suite('Mission Control environment discovery', () => { }); }); - test('skips unusable metadata without hiding other valid environments or rejecting future statuses', async () => { + test('rejects invalid environment metadata without publishing a partial inventory', async () => { const { service } = createService(store, { tasks: [], repositories: new Map(), onRequest: url => url.pathname.endsWith('/agents/environments') ? jsonResponse([ @@ -2770,10 +3107,8 @@ suite('Mission Control environment discovery', () => { { id: 'managed', name: 'Managed host', kind: 'managed-sandbox', status: 'paused' }, ]) : undefined, }); - assert.deepStrictEqual(await service.listEnvironments(CancellationToken.None), [ - { id: 'host', name: 'Native host', kind: 'user-local', status: 'online' }, - { id: 'managed', name: 'Managed host', kind: 'managed-sandbox', status: 'paused' }, - ]); + await assert.rejects(service.listEnvironments(CancellationToken.None), SchemaError); + assert.strictEqual(service.getCachedEnvironments(), undefined); }); test('explicit inventory refresh observes a host started since the cached offline result', async () => { @@ -2868,8 +3203,8 @@ suite('CloudSandboxApiService archived discovery', () => { const tasks: ITestTask[] = [ task('repo', 'Repository', 42, 'repo-session', 'repo-environment'), task('no-repo', 'No repository', undefined, 'no-repo-session', 'no-repo-environment'), - { ...task('archived-repo', 'Archived repository', 42, 'archived-repo-session', 'archived-repo-environment'), archived_at: date }, - { ...task('archived-no-repo', 'Archived without repository', undefined, 'archived-no-repo-session', 'archived-no-repo-environment'), archived_at: date }, + { ...task('archived-repo', 'Archived repository', 42, 'archived-repo-session', 'archived-repo-environment'), archived_at: new Date(date).toISOString() }, + { ...task('archived-no-repo', 'Archived without repository', undefined, 'archived-no-repo-session', 'archived-no-repo-environment'), archived_at: new Date(date).toISOString() }, ].map(task => ({ ...task, updated_at: '2026-09-22T09:00:00Z' })); const { service, requestedUrls } = createService(store, { tasks, repositories: new Map([[42, { full_name: 'owner/repo' }]]), @@ -2878,10 +3213,12 @@ suite('CloudSandboxApiService archived discovery', () => { return undefined; } const archived = url.searchParams.get('is_archived') === 'true'; + const continuation = new URL(url); + continuation.searchParams.set('page', String(Number(url.searchParams.get('page')) + 1)); return jsonResponse({ tasks: tasks.filter(task => (task.repository !== undefined) === (url.searchParams.get('with_repo') === 'true') && !!task.archived_at === archived), - }, 200, { date, link: `; rel="next"` }); + }, 200, { date, link: `<${continuation.search}>; rel="next"` }); }, }); const partitions = () => requestedUrls.map(url => new URL(url)).filter(url => url.pathname === '/agents/tasks') @@ -2921,7 +3258,7 @@ suite('CloudSandboxApiService archived discovery', () => { openedRequests: requestedUrls.map(url => new URL(url).pathname), }, { collapsed: { kind: 'scoped', sessions: [], removedTaskIds: [] }, collapsedDetails: [], - opened: [{ taskId: 'changed', archived: true }], openedRequests: ['/agents/tasks/changed'], + opened: [{ taskId: 'changed', archived: true }], openedRequests: ['/agents/tasks/batch'], }); }); @@ -2985,7 +3322,7 @@ suite('CloudSandboxApiService archived discovery', () => { assert.deepStrictEqual({ archived: result.kind === 'failed' ? [] : result.sessions.map(session => session.isArchived), urls: requestedUrls.map(url => new URL(url).pathname), - }, { archived: [true], urls: ['/agents/tasks/archived'] }); + }, { archived: [true], urls: ['/agents/tasks/batch'] }); }); }); @@ -3122,6 +3459,7 @@ suite('CloudSandboxApiService repository resolution', () => { ], sessions: [{ id: 'session-1', environment_id: 'environment-1', + state: 'completed', created_at: '2026-01-01T00:00:00Z', clients: [{ integration_id: 'vscode-chat', slug: 'copilot-vscode', creator: true }], }], }; @@ -3179,7 +3517,7 @@ suite('CloudSandboxApiService repository resolution', () => { detailReads: requestedUrls.filter(url => url.endsWith('/tasks/task-1')).length, }, { applications: [['copilot-cli'], ['copilot-cli'], ['copilot-cli'], ['copilot-cli']], - detailReads: 1, + detailReads: 0, }); }); } @@ -3190,7 +3528,7 @@ suite('CloudSandboxApiService repository resolution', () => { tasks: states.map(state => ({ ...task(state, state, undefined, `session-${state}`, `environment-${state}`), state, - sessions: [{ id: `session-${state}`, environment_id: `environment-${state}`, state: 'idle' }], + sessions: [{ id: `session-${state}`, environment_id: `environment-${state}`, state: 'idle', created_at: '2026-01-01T00:00:00Z' }], })), repositories: new Map(), }); @@ -3223,6 +3561,7 @@ suite('CloudSandboxApiService repository resolution', () => { repoName: 'osortega/simple-server', hasRepository: true, updatedAt: undefined, + status: SessionStatus.Idle, }], }); }); @@ -3232,7 +3571,7 @@ suite('CloudSandboxApiService repository resolution', () => { ...task('activity-cache', 'Question', undefined, 'original-session', 'original-environment'), updated_at: '2026-07-01T00:01:00.000Z', state: 'waiting_for_user', - sessions: [{ id: 'original-session', environment_id: 'original-environment', state: 'waiting_for_user' }], + sessions: [{ id: 'original-session', environment_id: 'original-environment', state: 'waiting_for_user', created_at: '2026-01-01T00:00:00Z' }], }; const h = createService(store, { tasks: [current], @@ -3257,21 +3596,19 @@ suite('CloudSandboxApiService repository resolution', () => { test('propagates task-list cancellation without error logging', async () => { const logService = new TestLogService(); + const cancellation = store.add(new CancellationTokenSource()); const { service } = createService(store, { tasks: [], repositories: new Map(), - requestError: new CancellationError(), + onRequest: () => { + cancellation.cancel(); + throw new CancellationError(); + }, logService, }); - await assert.rejects(() => service.listSessions(CancellationToken.None), error => isCancellationError(error)); - assert.deepStrictEqual({ - cancelledTraces: logService.traces.filter(message => message.includes(' -> cancelled')).length, - errors: logService.errors, - }, { - cancelledTraces: 1, - errors: [], - }); + await assert.rejects(service.listSessions(cancellation.token), isCancellationError); + assert.deepStrictEqual(logService.errors, []); }); test('does not start discovery reads when already cancelled', async () => { @@ -3321,14 +3658,10 @@ suite('CloudSandboxApiService repository resolution', () => { }); test('a failed lookup leaves every sharing session discoverable and is retried next pass', async () => { - // Two tasks on the same failing repository: they share one memoized promise, and if it - // rejects the callers that receive it drop their sessions from the listing entirely. + const tasks = Array.from({ length: 12 }, (_, index) => task(`task-${index}`, 'Task', 290012776, `session-${index}`, `environment-${index}`)); const repositories = new Map([[290012776, 'error']]); const { service, requestedUrls } = createService(store, { - tasks: [ - task('task-1', 'Change port to 5555', 290012776, 'sess-1', 'env-1'), - task('task-2', 'hi', 290012776, 'sess-2', 'env-2'), - ], + tasks, repositories, }); @@ -3337,7 +3670,6 @@ suite('CloudSandboxApiService repository resolution', () => { const second = await service.listSessions(CancellationToken.None); assert.deepStrictEqual({ - // `complete`, not `partial`: the sessions resolved fine, only their label did not. firstKind: first.kind, firstSessions: first.kind === 'failed' ? [] : first.sessions.map(s => s.taskId), firstNames: first.kind === 'failed' ? [] : first.sessions.map(s => s.repoName), @@ -3345,11 +3677,9 @@ suite('CloudSandboxApiService repository resolution', () => { repoLookups: requestedUrls.filter(u => /\/repositories\//.test(u)).length, }, { firstKind: 'complete', - firstSessions: ['task-1', 'task-2'], - firstNames: [undefined, undefined], - secondNames: ['osortega/simple-server', 'osortega/simple-server'], - // One per pass: the failure is evicted so the second pass retries, but neither pass - // issues a second lookup for the task that shares the repository. + firstSessions: tasks.map(task => task.id), + firstNames: Array(12).fill(undefined), + secondNames: Array(12).fill('osortega/simple-server'), repoLookups: 2, }); }); @@ -3381,7 +3711,7 @@ suite('CloudSandboxApiService repository resolution', () => { { name: 'empty user-local compute provider', compute: { provider: '' }, kind: 'user-local', expected: false }, { name: 'empty compute provider without environment kind', compute: { provider: '' }, kind: undefined, expected: false }, { name: 'compute only', compute: { provider: 'sandboxes' }, kind: undefined, expected: true }, - { name: 'explicit other compute', compute: { provider: 'other' }, kind: 'managed-sandbox', expected: false }, + { name: 'explicit other compute', compute: { provider: 'codespaces' }, kind: 'managed-sandbox', expected: false }, { name: 'user-local environment', compute: undefined, kind: 'user-local', expected: false }, { name: 'unknown environment kind', compute: undefined, kind: 'unknown', expected: false }, { name: 'missing compute and environment', compute: undefined, kind: undefined, expected: false }, @@ -3402,7 +3732,7 @@ suite('CloudSandboxApiService repository resolution', () => { assert.deepStrictEqual({ kind: result.kind, sessions: result.kind === 'failed' ? [] : result.sessions.map(session => session.taskId), - }, { kind: 'complete', sessions: expected ? ['sandbox'] : [] }); + }, { kind: name === 'unknown environment kind' ? 'failed' : 'complete', sessions: expected ? ['sandbox'] : [] }); }); } @@ -3452,7 +3782,7 @@ suite('CloudSandboxApiService repository resolution', () => { const tasks = Array.from({ length: 300 }, (_, i) => ({ ...task(`filler-${i}`, 'Other task', repositoryId, `s-${i}`, `e-${i}`), agent_collaborators: [{ slug: 'other' }], - compute: { provider: 'other' }, + compute: { provider: 'codespaces' }, ...(archived ? { archived_at: '2026-10-01T00:00:00Z' } : {}), })); tasks.push({ @@ -3504,8 +3834,8 @@ suite('CloudSandboxApiService pagination', () => { const tasks: ITestTask[] = [ task('repo', 'Repository', 42, 'repo-session', 'repo-environment'), task('no-repo', 'No repository', undefined, 'no-repo-session', 'no-repo-environment'), - { ...task('archived-repo', 'Archived repository', 42, 'archived-repo-session', 'archived-repo-environment'), archived_at: date }, - { ...task('archived-no-repo', 'Archived without repository', undefined, 'archived-no-repo-session', 'archived-no-repo-environment'), archived_at: date }, + { ...task('archived-repo', 'Archived repository', 42, 'archived-repo-session', 'archived-repo-environment'), archived_at: new Date(date).toISOString() }, + { ...task('archived-no-repo', 'Archived without repository', undefined, 'archived-no-repo-session', 'archived-no-repo-environment'), archived_at: new Date(date).toISOString() }, ]; const { service, requestedUrls } = createService(store, { tasks, repositories: new Map([[42, { full_name: 'owner/repo' }]]), @@ -3515,10 +3845,13 @@ suite('CloudSandboxApiService pagination', () => { } const cursor = url.searchParams.get('cursor'); const next = cursor === null ? 'second+/= opaque' : cursor === 'second+/= opaque' ? 'third' : 'fourth'; + const continuation = new URL(url); + continuation.searchParams.delete('page'); + continuation.searchParams.set('cursor', next); return jsonResponse({ tasks: tasks.filter(task => (task.repository !== undefined) === (url.searchParams.get('with_repo') === 'true') && !!task.archived_at === (url.searchParams.get('is_archived') === 'true')), - }, 200, { date, link: ['; rel="first"', `; rel="next"`] }); + }, 200, { date, link: ['; rel="first"', `<${continuation.search}>; rel="next"`] }); }, }); @@ -3539,7 +3872,7 @@ suite('CloudSandboxApiService pagination', () => { }); }); - test('follows numbered next-page links while retaining the API endpoint and scope filters', async () => { + test('follows numbered next-page links with the service-provided scope filters', async () => { const older = task('older', 'Older task', undefined, 'older-session', 'older-environment'); const { service, requestedUrls } = createService(store, { tasks: [older], repositories: new Map(), @@ -3547,9 +3880,12 @@ suite('CloudSandboxApiService pagination', () => { if (url.pathname !== '/agents/tasks' || url.searchParams.get('with_repo') !== 'false' || url.searchParams.get('is_archived') !== 'false') { return undefined; } + const continuation = new URL(url); + continuation.host = 'api.github.com'; + continuation.searchParams.set('page', '7'); return url.searchParams.get('page') === '7' ? jsonResponse({ tasks: [older] }) - : jsonResponse({ tasks: [] }, 200, { link: '; rel="next"' }); + : jsonResponse({ tasks: [] }, 200, { link: `<${continuation.href}>; rel="next"` }); }, }); @@ -3572,10 +3908,10 @@ suite('CloudSandboxApiService pagination', () => { }); for (const [link, reason, requests] of [ - ['; rel="next"', 'Task list returned an invalid pagination URL', 1], - ['; rel="next"', 'Task list returned an invalid pagination URL', 1], - ['; rel=next', 'Task list returned an unsupported pagination link', 1], - ['; rel="next"', 'Task list repeated a pagination URL', 2], + ['; rel="next"', 'GitHub returned an invalid pagination link', 1], + ['; rel="next"', 'GitHub returned an invalid pagination link', 1], + ['; rel=next', 'GitHub returned an invalid pagination link', 1], + ['; rel="next"', 'GitHub pagination repeated a continuation', 2], ] as const) { test(`fails the scan instead of following ${link}`, async () => { const { service, requestedUrls } = createService(store, { @@ -3603,7 +3939,7 @@ suite('CloudSandboxApiService discovery logs', () => { ...task('bound', 'Work on repository', 42, 'session-1', 'env-1'), updated_at: '2026-09-22T10:00:00Z', state: 'idle', - sessions: [{ id: 'session-1', environment_id: 'env-1', state: 'waiting_for_user', ahp_resource_uri: 'ahp-session:/session-1' }], + sessions: [{ id: 'session-1', environment_id: 'env-1', state: 'waiting_for_user', created_at: '2026-01-01T00:00:00Z', ahp_resource_uri: 'ahp-session:/session-1' }], prompt: 'not-for-logs', }; const { service } = createService(store, { @@ -3611,7 +3947,7 @@ suite('CloudSandboxApiService discovery logs', () => { bound, { ...task('archived', 'Old task', undefined, 'session-2', 'env-2'), archived_at: '2026-09-21T10:00:00Z' }, { ...task('different-agent', 'Other agent', undefined, 'session-3', 'env-3'), agent_collaborators: [{ slug: 'other' }] }, - { ...task('other-compute', 'Other compute', undefined, 'session-5', 'env-5'), compute: { provider: 'other' } }, + { ...task('other-compute', 'Other compute', undefined, 'session-5', 'env-5'), compute: { provider: 'codespaces' } }, { ...task('unbound', 'Not ready', undefined, 'session-4', 'env-4'), sessions: [] }, ], repositories: new Map([[42, { full_name: 'owner/repository' }]]), @@ -3632,11 +3968,11 @@ suite('CloudSandboxApiService discovery logs', () => { name: 'Work on repository', repoName: 'owner/repository', updatedAt: bound.updated_at, status: SessionStatus.Idle, })}`, `[CloudSandboxApi] Discovered sandbox session ${JSON.stringify({ - taskId: 'different-agent', name: 'Other agent', + taskId: 'different-agent', name: 'Other agent', status: SessionStatus.Idle, })}`, `[CloudSandboxApi] Discovered sandbox session ${JSON.stringify({ - taskId: 'unbound', name: 'Not ready', + taskId: 'unbound', name: 'Not ready', status: SessionStatus.Idle, })}`, `[CloudSandboxApi] Discovered sandbox session ${JSON.stringify({ - taskId: 'archived', name: 'Old task', + taskId: 'archived', name: 'Old task', status: SessionStatus.Idle, })}`], filtering: [ '[CloudSandboxApi] Accepted task previously excluded by agent slug {"taskId":"different-agent"}', @@ -3935,7 +4271,7 @@ suite('CloudSandboxApiService discovery without recorded history', () => { event_type: 'unknown', state: 'idle', updated_at: new Date(startTime - 2 * oneHour).toISOString(), - sessions: [{ id: `session-${id}`, environment_id: 'shared-environment', state: 'idle', ahp_resource_uri: `ahp-session:/session-${id}` }], + sessions: [{ id: `session-${id}`, environment_id: 'shared-environment', state: 'idle', created_at: '2026-01-01T00:00:00Z', ahp_resource_uri: `ahp-session:/session-${id}` }], }; } @@ -3962,7 +4298,7 @@ suite('CloudSandboxApiService discovery without recorded history', () => { initial: initial.kind === 'failed' ? initial : { kind: initial.kind, tasks: initial.sessions.map(session => session.taskId).sort() }, renewed, targeted: targeted.kind === 'failed' ? targeted : targeted.sessions.map(session => session.taskId), - unexpectedRequests: requestedUrls.filter(url => !/\/agents\/tasks(?:\?|\/(?:idle|legacy|archived)$)|\/repositories\/42$/.test(url)), + unexpectedRequests: requestedUrls.filter(url => !['/agents/tasks', '/agents/tasks/batch', '/repositories/42'].includes(new URL(url).pathname)), queries: requestedUrls.filter(url => new URL(url).pathname === '/agents/tasks').map(url => { const query = new URL(url).searchParams; return [query.get('with_repo'), query.get('is_archived'), query.get('since'), query.get('include_environment_kinds')]; @@ -4032,6 +4368,44 @@ suite('CloudSandboxApiService discovery without recorded history', () => { suite('CloudSandboxApiService task catalog resolution', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('resolves a cold session without a preceding inventory scan', async () => { + const { service, requestedUrls } = createService(store, { + tasks: [task('task', 'Conversation', undefined, 'session', 'environment')], repositories: new Map(), + }); + const resolved = await service.resolveSession('task', CancellationToken.None); + assert.deepStrictEqual({ + binding: [resolved.taskId, resolved.sessionId, resolved.environmentId], + paths: requestedUrls.map(url => new URL(url).pathname), + }, { binding: ['task', 'session', 'environment'], paths: ['/agents/tasks/task'] }); + }); + + for (const ending of ['cancellation', 'disposal'] as const) { + test(`${ending} stops cold session authorization without dispatching a task read`, async () => { + const started = new DeferredPromise(); + const authorization = new DeferredPromise(); + const source = store.add(new CancellationTokenSource()); + const { service, requestedUrls } = createService(store, { + tasks: [], repositories: new Map(), + authenticationSessions: () => { + void started.complete(); + return authorization.p; + }, + }); + const resolving = service.resolveSession('task', source.token); + const rejected = assert.rejects(resolving, isCancellationError); + await started.p; + if (ending === 'cancellation') { + source.cancel(); + } else { + service.dispose(); + } + await rejected; + await authorization.complete([{ id: 'auth', accessToken: 'token', account: { id: 'a', label: 'Account' }, scopes: [] }]); + await timeout(0); + assert.deepStrictEqual(requestedUrls, []); + }); + } + test('reports queued state from listing metadata without execution reads', async () => { const queued = { ...task('queued', 'New remote session', undefined, 'session', 'environment'), state: 'queued' }; const tasks = [queued]; @@ -4045,24 +4419,27 @@ suite('CloudSandboxApiService task catalog resolution', () => { }, { queued: [true, undefined], details: [] }); }); - test('reuses execution details already read for a targeted feed update', async () => { + test('resolves execution details only when opening a batch-discovered task', async () => { const { service, requestedUrls } = createService(store, { tasks: [task('task', 'Conversation', undefined, 'session', 'environment')], repositories: new Map(), }); await service.listSessions(CancellationToken.None, { taskIds: ['task'] }); + const beforeOpen = requestedUrls.filter(url => new URL(url).pathname.endsWith('/tasks/task')).length; const resolved = await service.resolveSession('task', CancellationToken.None); + await service.resolveSession('task', CancellationToken.None); assert.deepStrictEqual({ + beforeOpen, binding: [resolved.sessionId, resolved.environmentId], detailReads: requestedUrls.filter(url => new URL(url).pathname.endsWith('/tasks/task')).length, - }, { binding: ['session', 'environment'], detailReads: 1 }); + }, { beforeOpen: 0, binding: ['session', 'environment'], detailReads: 1 }); }); - test('bounds concurrent on-demand execution reads independently of enumeration', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + test('uses the shared queue for concurrent on-demand execution reads', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const tasks = Array.from({ length: 30 }, (_, index) => task(`task-${index}`, 'Conversation', undefined, `session-${index}`, `environment-${index}`)); const { service, concurrency } = createService(store, { tasks, repositories: new Map(), taskFetchDelayMs: 10 }); await service.listSessions(CancellationToken.None); const resolved = await Promise.all(tasks.map(task => service.resolveSession(task.id, CancellationToken.None))); - assert.deepStrictEqual({ resolved: resolved.length, peak: concurrency.max, active: concurrency.current }, { resolved: 30, peak: 5, active: 0 }); + assert.deepStrictEqual({ resolved: resolved.length, peak: concurrency.max, active: concurrency.current }, { resolved: 30, peak: 8, active: 0 }); })); }); @@ -4134,10 +4511,10 @@ suite('CloudSandboxApiService incremental discovery', () => { const third = await service.listSessions(CancellationToken.None, { incremental: true, includeArchived: false }); await service.listSessions(CancellationToken.None, { incremental: true, includeArchived: false }); assert.deepStrictEqual({ - progress: [first, second].map(result => result.kind === 'partial' ? result.inventoryComplete : result.kind), + progress: [first.kind, second.kind], recovered: third.kind, queries: requestedUrls.filter(url => new URL(url).pathname === '/agents/tasks').map(url => new URL(url).searchParams.get('since')), - }, { progress: [undefined, undefined], recovered: 'scoped', queries: [...Array(6).fill(null), checkpoint, checkpoint] }); + }, { progress: ['failed', 'failed'], recovered: 'scoped', queries: [...Array(8).fill(null), checkpoint, checkpoint] }); }); test('queries both repository and archive scopes and resolves no task details when nothing changed', async () => { @@ -4157,7 +4534,7 @@ suite('CloudSandboxApiService incremental discovery', () => { }, { result: { kind: 'incremental', sessions: [], removedTaskIds: [] }, queries: [false, true].flatMap(archived => [true, false].map(withRepository => ({ - per_page: '100', page: '1', sort: 'updated_at', direction: 'desc', + per_page: '100', page: '1', sort: 'updated_at', direction: 'desc', include_counts: 'false', with_repo: String(withRepository), is_archived: String(archived), since: checkpoint, include_environment_kinds: 'managed-sandbox', }))), }); @@ -4201,7 +4578,7 @@ suite('CloudSandboxApiService incremental discovery', () => { }, { kind: 'incremental', since: '2026-09-22T09:57:00.000Z', requests: 4 }); }); - test('preserves incremental filters when pagination links omit them', async () => { + test('follows incremental filters supplied in pagination links', async () => { const tasks: ITestTask[] = []; const { service, requestedUrls } = createService(store, { tasks, repositories: new Map(), discoveryDate: () => firstScanDate, @@ -4367,7 +4744,7 @@ suite('CloudSandboxApiService incremental discovery', () => { tasks.length = 0; } tasks.unshift(...Array.from({ length: 301 }, (_, i) => ({ - ...updatedTask(`new-${i}`, checkpoint), compute: { provider: 'other' }, + ...updatedTask(`new-${i}`, checkpoint), compute: { provider: 'codespaces' }, }))); date = 'Tue, 22 Sep 2026 10:05:00 GMT'; const bounded = await service.listSessions(CancellationToken.None); @@ -4587,6 +4964,10 @@ suite('CloudSandboxApiService incremental discovery', () => { tasks.push(updatedTask('new', checkpoint)); paused = true; const inFlight = service.listSessions(CancellationToken.None, { incremental: true }); + const settled = inFlight.then(result => result.kind, error => { + assert.ok(isCancellationError(error)); + return 'cancelled'; + }); await entered.p; authentication = { ...authentication, accessToken: 'rotated', @@ -4597,18 +4978,18 @@ suite('CloudSandboxApiService incremental discovery', () => { changeAuthentication(); await changed; await response.complete(jsonResponse({ tasks })); - const stale = await inFlight; + const staleKind = await settled; paused = false; requestedUrls.length = 0; const refreshed = await service.listSessions(CancellationToken.None, { incremental: true }); assert.deepStrictEqual({ - staleKind: stale.kind, + staleKind, refreshedKind: refreshed.kind, since: new URL(requestedUrls[0]).searchParams.get('since'), details: requestedUrls.filter(url => new URL(url).pathname.startsWith('/agents/tasks/')).length, }, { - staleKind: 'failed', refreshedKind: change === 'token' ? 'incremental' : 'complete', + staleKind: change === 'token' ? 'failed' : 'cancelled', refreshedKind: change === 'token' ? 'incremental' : 'complete', since: change === 'token' ? checkpoint : null, details: 0, }); }); @@ -4639,49 +5020,53 @@ suite('CloudSandboxApiService discovery rate limiting', () => { }); })); - test('retries a rate-limited task fetch instead of dropping its session', () => runWithFakedTimers({ useFakeTimers: true }, async () => { - // A 429 that is merely reported loses the session for the life of the window, because - // nothing re-runs a pass that otherwise succeeded. - const { service } = createService(store, { + test('a later resolution attempt honors the shared cooldown without dropping the listed task', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, requestedUrls } = createService(store, { tasks: [ task('task-1', 'kept', undefined, 'sess-1', 'env-1'), task('task-2', 'also kept', undefined, 'sess-2', 'env-2'), ], repositories: new Map(), - rateLimitedTaskFetches: new Map([['task-1', 2]]), + rateLimitedTaskFetches: new Map([['task-1', 1]]), retryAfterSeconds: 1, }); const result = await service.listSessions(CancellationToken.None); - + await assert.rejects(service.resolveSession('task-1', CancellationToken.None), { statusCode: 429 }); + const afterRefusal = requestedUrls.filter(url => url.endsWith('/tasks/task-1')).length; const resolved = await Promise.all(['task-1', 'task-2'].map(taskId => service.resolveSession(taskId, CancellationToken.None))); assert.deepStrictEqual({ - // `complete`, not `partial`: the retry resolved it, so nothing was left unresolved. kind: result.kind, sessions: resolved.map(s => s.sessionId).sort(), + afterRefusal, }, { kind: 'complete', sessions: ['sess-1', 'sess-2'], + afterRefusal: 1, }); })); - test('retries a rate-limited task list rather than failing the whole pass', () => runWithFakedTimers({ useFakeTimers: true }, async () => { - // Page one failing is fatal — it returns `failed`, which seeds nothing and leaves the - // sessions list empty until something else triggers discovery. - const { service } = createService(store, { + test('a later inventory pass recovers after the shared rate limit without an inline retry loop', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const { service, requestedUrls } = createService(store, { tasks: [task('task-1', 'kept', undefined, 'sess-1', 'env-1')], repositories: new Map(), - rateLimitedListPages: 2, + rateLimitedListPages: 1, }); + const refused = await service.listSessions(CancellationToken.None); + const afterRefusal = requestedUrls.length; const result = await service.listSessions(CancellationToken.None); assert.deepStrictEqual({ kind: result.kind, sessions: result.kind === 'failed' ? [] : result.sessions.map(s => s.taskId), + refused: refused.kind, + afterRefusal, }, { kind: 'complete', sessions: ['task-1'], + refused: 'failed', + afterRefusal: 1, }); })); @@ -4715,9 +5100,7 @@ suite('CloudSandboxApiService discovery rate limiting', () => { }); })); - test('gives up on a persistently rate-limited task, leaving the scan partial', () => runWithFakedTimers({ useFakeTimers: true }, async () => { - // Retrying forever would hold discovery open; the pass must end, but as `partial` so the - // caller does not treat the missing session as one that no longer exists. + test('a persistently rate-limited task is not retried inline or removed from inventory', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const { service, requestedUrls } = createService(store, { tasks: [ task('task-1', 'lost', undefined, 'sess-1', 'env-1'), @@ -4733,12 +5116,11 @@ suite('CloudSandboxApiService discovery rate limiting', () => { assert.deepStrictEqual({ kind: result.kind, sessions: result.kind === 'failed' ? [] : result.sessions.map(s => s.taskId), - // The original attempt plus RATE_LIMIT_MAX_RETRIES retries, then it stops. taskOneAttempts: requestedUrls.filter(u => u.endsWith('/tasks/task-1')).length, }, { kind: 'complete', sessions: ['task-1', 'task-2'], - taskOneAttempts: 4, + taskOneAttempts: 1, }); })); }); @@ -4755,12 +5137,9 @@ function createServiceForCreate(store: Pick<{ add const calls: ICreateCall[] = []; const errors: string[] = []; const warnings: string[] = []; - const instantiationService = store.add(new TestInstantiationService()); - instantiationService.stub(IUserDataProfileService, new class extends mock() { - override readonly onDidChangeCurrentProfile = Event.None; - }()); - instantiationService.stub(IRequestService, new class extends mock() { - override async request(opts: IRequestOptions): Promise { + const { service } = createService(store, { + tasks: [], repositories: new Map(), + onRequest: (url, _token, opts) => { calls.push({ url: opts.url ?? '', type: opts.type ?? '', @@ -4775,32 +5154,21 @@ function createServiceForCreate(store: Pick<{ add // Reusing the create's failure status would fake a cleanup that never happened. return jsonResponse({}, options?.deleteStatusCode ?? 204); } - return jsonResponse(response, statusCode, options?.responseHeaders); - } - }()); - instantiationService.stub(IAuthenticationService, new class extends mock() { - override async getSessions() { return [{ accessToken: 'tok', id: 's', account: { id: 'a', label: 'a' }, scopes: [] }]; } - override readonly onDidChangeSessions = Event.None; - override readonly onDidRegisterAuthenticationProvider = Event.None; - override readonly onDidUnregisterAuthenticationProvider = Event.None; - }()); - instantiationService.stub(IProductService, { defaultChatAgent: undefined } as unknown as IProductService); - instantiationService.stub(ILogService, new class extends NullLogService { - override error(message: string | Error): void { - errors.push(String(message)); - } - override warn(message: string): void { - warnings.push(String(message)); - } - }()); - instantiationService.stub(ICloudSandboxTelemetryService, new class extends mock() { - override readonly lifecycle = new CloudSandboxLifecycleTelemetry(NullTelemetryService); - override reportRequest(): void { } - override reportDiscovery(): void { } - override reportProvisioningOutcome(): void { } - }()); - instantiationService.stub(IWorkbenchGitHubService, new class extends mock() { }()); - return { service: store.add(instantiationService.createInstance(CloudSandboxApiService)), calls, errors, warnings }; + const taskPath = /^\/agents\/tasks\/(?[^/]+)(?:\/(?:archive|unarchive))?$/.exec(url.pathname); + const data = taskPath?.groups && isObject(response) && statusCode >= 200 && statusCode < 300 + ? { id: decodeURIComponent(taskPath.groups.id), ...response } : response; + return jsonTaskResponse(data, statusCode, options?.responseHeaders); + }, + logService: new class extends NullLogService { + override error(message: string | Error): void { + errors.push(String(message)); + } + override warn(message: string): void { + warnings.push(String(message)); + } + }(), + }); + return { service, calls, errors, warnings }; } suite('CloudSandboxApiService task archiving', () => { @@ -4813,7 +5181,7 @@ suite('CloudSandboxApiService task archiving', () => { onRequest: (url, _token, options) => { if (options.type === 'POST') { tasks[0] = { ...tasks[0], archived_at: url.pathname.endsWith('/archive') ? new Date().toISOString() : undefined }; - return jsonResponse({}); + return jsonResponse(tasks[0]); } return undefined; }, @@ -4839,8 +5207,8 @@ suite('CloudSandboxApiService task archiving', () => { path: new URL(call.url).pathname, method: call.type, body: call.body, timeout: call.timeout, integration: call.headers['Copilot-Integration-Id'], })), [ - { path: '/agents/tasks/task%2Fwith%20spaces/archive', method: 'POST', body: undefined, timeout: 10_000, integration: COPILOT_INTEGRATION_ID }, - { path: '/agents/tasks/task%2Fwith%20spaces/unarchive', method: 'POST', body: undefined, timeout: 10_000, integration: COPILOT_INTEGRATION_ID }, + { path: '/agents/tasks/task%2Fwith%20spaces/archive', method: 'POST', body: undefined, timeout: undefined, integration: COPILOT_INTEGRATION_ID }, + { path: '/agents/tasks/task%2Fwith%20spaces/unarchive', method: 'POST', body: undefined, timeout: undefined, integration: COPILOT_INTEGRATION_ID }, ]); }); @@ -4870,7 +5238,7 @@ suite('CloudSandboxApiService task archiving', () => { tasks, repositories: new Map(), onRequest: async (url, _token, options) => { if (options.type === 'POST') { - return jsonResponse({}); + return jsonResponse(tasks[0]); } if (paused && url.pathname.endsWith('/tasks')) { paused = false; @@ -4899,7 +5267,7 @@ suite('CloudSandboxApiService task renaming', () => { url: 'https://api.githubcopilot.com/agents/tasks/task%2Fwith%20spaces', type: 'PATCH', body: { name: 'New title' }, - timeout: 10_000, + timeout: undefined, headers: { Accept: 'application/json', 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, @@ -4928,7 +5296,7 @@ suite('CloudSandboxApiService task renaming', () => { const { service } = createService(store, { tasks: [], repositories: new Map(), requestError: new Error('rename transport failed'), }); - await assert.rejects(service.renameTask('task-1', 'New title', CancellationToken.None), /rename transport failed/); + await assert.rejects(service.renameTask('task-1', 'New title', CancellationToken.None), MutationUncertainError); }); test('refreshes a renamed task even when the incremental list omits it', async () => { @@ -4940,7 +5308,7 @@ suite('CloudSandboxApiService task renaming', () => { if (options.type === 'PATCH') { renamed = true; original.name = 'New title'; - return jsonResponse({}); + return jsonResponse(original); } if (renamed && url.pathname.endsWith('/tasks/task-1')) { return jsonResponse({ ...original, name: 'New title' }); @@ -4963,7 +5331,7 @@ suite('CloudSandboxApiService task renaming', () => { tasks: [original], repositories: new Map(), onRequest: (url, _token, options) => { if (options.type === 'PATCH') { - return jsonResponse({}); + return jsonResponse(original); } if (paused && url.pathname.endsWith('/tasks')) { paused = false; @@ -4984,7 +5352,7 @@ suite('CloudSandboxApiService task renaming', () => { suite('CloudSandboxApiService task deletion', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - for (const statusCode of [200, 204, 404]) { + for (const statusCode of [204, 404]) { test(`deletes the encoded task through Mission Control: HTTP ${statusCode}`, async () => { const { service, calls } = createServiceForCreate(store, undefined, 200, { deleteStatusCode: statusCode }); await service.deleteTask('task/with spaces', CancellationToken.None); @@ -4992,7 +5360,7 @@ suite('CloudSandboxApiService task deletion', () => { url: 'https://api.githubcopilot.com/agents/tasks/task%2Fwith%20spaces', type: 'DELETE', body: undefined, - timeout: 10_000, + timeout: undefined, headers: { Accept: 'application/json', 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, @@ -5011,7 +5379,7 @@ suite('CloudSandboxApiService task deletion', () => { test('surfaces transport errors', async () => { const { service } = createServiceForCreate(store, undefined, 200, { failDelete: true }); - await assert.rejects(service.deleteTask('task-1', CancellationToken.None), /delete failed/); + await assert.rejects(service.deleteTask('task-1', CancellationToken.None), MutationUncertainError); }); test('requires authentication before deleting', async () => { @@ -5128,7 +5496,7 @@ suite('CloudSandboxApiService task ownership', () => { }, onRequest: (_url, _token, options) => { requests.push(options); - return jsonResponse(operation.response, operation.statusCode); + return jsonTaskResponse(operation.response, operation.statusCode); }, }); const accountKey = await service.getAccountKey(); @@ -5174,7 +5542,7 @@ suite('CloudSandboxApiService task reservations', () => { }, { reserved: { taskId: 'reserved-task', sessionId: 'reserved-session', environmentId: 'reserved-env', reservationExpiresAt: Date.parse(expiry) }, requests: [{ - path: '/agents/tasks', type: 'POST', timeout: 60_000, + path: '/agents/tasks', type: 'POST', timeout: undefined, body: { environment_id: CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID, prompt: '', reserve: true, ...(repoNwo ? { repositories: [{ owner: 'owner', name: 'repo' }] } : { compute: { scope: 'a' } }), @@ -5206,25 +5574,25 @@ suite('CloudSandboxApiService task reservations', () => { for (const invalid of [ { name: 'missing reservation acknowledgement', response: { ...receipt, reserved: undefined } }, { name: 'unreserved task', response: { ...receipt, reserved: false } }, - { name: 'invalid reservation acknowledgement', response: { ...receipt, reserved: 'true' } }, + { name: 'invalid reservation acknowledgement', schemaInvalid: true, response: { ...receipt, reserved: 'true' } }, { name: 'missing expiry', response: { ...receipt, reservation_expires_at: undefined } }, - { name: 'invalid expiry', response: { ...receipt, reservation_expires_at: 'not-a-date' } }, - { name: 'numeric expiry', response: { ...receipt, reservation_expires_at: 42 } }, + { name: 'invalid expiry', schemaInvalid: true, response: { ...receipt, reservation_expires_at: 'not-a-date' } }, + { name: 'numeric expiry', schemaInvalid: true, response: { ...receipt, reservation_expires_at: 42 } }, { name: 'missing session', response: { ...receipt, sessions: [] } }, - { name: 'invalid session list', response: { ...receipt, sessions: {} } }, - { name: 'null session', response: { ...receipt, sessions: [null] } }, - { name: 'missing session identity', response: { ...receipt, sessions: [{ environment_id: 'reserved-env' }] } }, + { name: 'invalid session list', schemaInvalid: true, response: { ...receipt, sessions: {} } }, + { name: 'null session', schemaInvalid: true, response: { ...receipt, sessions: [null] } }, + { name: 'missing session identity', schemaInvalid: true, response: { ...receipt, sessions: [{ environment_id: 'reserved-env' }] } }, { name: 'non-concrete environment', response: { ...receipt, sessions: [{ id: 'reserved-session', environment_id: CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID }] } }, - { name: 'invalid environment type', response: { ...receipt, sessions: [{ id: 'reserved-session', environment_id: ['reserved-env'] }] } }, + { name: 'invalid environment type', schemaInvalid: true, response: { ...receipt, sessions: [{ id: 'reserved-session', environment_id: ['reserved-env'] }] } }, ]) { - test(`rejects ${invalid.name} and cleans up only the acknowledged new task`, async () => { + test(`rejects ${invalid.name} and cleans up only a schema-validated new task`, async () => { const { service, calls } = createServiceForCreate(store, invalid.response, 201); - await assert.rejects(service.reserveSession({ expectedAccountKey }, CancellationToken.None), /usable task reservation/); + await assert.rejects(service.reserveSession({ expectedAccountKey }, CancellationToken.None), + invalid.schemaInvalid ? MutationUncertainError : /usable task reservation/); - assert.deepStrictEqual(calls.map(call => [call.type, new URL(call.url).pathname]), [ - ['POST', '/agents/tasks'], ['DELETE', '/agents/tasks/reserved-task'], - ]); + assert.deepStrictEqual(calls.map(call => [call.type, new URL(call.url).pathname]), invalid.schemaInvalid + ? [['POST', '/agents/tasks']] : [['POST', '/agents/tasks'], ['DELETE', '/agents/tasks/reserved-task']]); }); } @@ -5232,7 +5600,7 @@ suite('CloudSandboxApiService task reservations', () => { test(`rejects an unusable reservation task identity ${JSON.stringify(id)} without guessing a cleanup target`, async () => { const { service, calls } = createServiceForCreate(store, { ...receipt, id }, 201); - await assert.rejects(service.reserveSession({ expectedAccountKey }, CancellationToken.None), /usable task reservation/); + await assert.rejects(service.reserveSession({ expectedAccountKey }, CancellationToken.None), MutationUncertainError); assert.deepStrictEqual(calls.map(call => call.type), ['POST']); }); @@ -5290,7 +5658,7 @@ suite('CloudSandboxApiService task reservations', () => { authenticationSessions: async () => [{ accessToken: 'token', id: 's', account: { id: account, label: account }, scopes: [] }], onRequest: () => { account = 'other'; - return jsonResponse({ ...receipt, reserved: false }, 201); + return jsonTaskResponse({ ...receipt, reserved: false }, 201); }, logService: new class extends NullLogService { override warn(message: string): void { warnings.push(message); } @@ -5330,32 +5698,29 @@ suite('CloudSandboxApiService task reservations', () => { }); } - test('retains an acknowledged reservation received after cancellation so the owner can release it', async () => { + test('cancels a reservation without replay or cleanup when its response arrives after cancellation', async () => { const source = store.add(new CancellationTokenSource()); const { service, requestedUrls } = createService(store, { tasks: [], repositories: new Map(), onRequest: () => { source.cancel(); - return jsonResponse(receipt, 201); + return jsonTaskResponse(receipt, 201); }, }); - const reserved = await service.reserveSession({ expectedAccountKey }, source.token); - - assert.deepStrictEqual({ taskId: reserved.taskId, requests: requestedUrls.length, cancelled: source.token.isCancellationRequested }, { - taskId: 'reserved-task', requests: 1, cancelled: true, - }); + await assert.rejects(service.reserveSession({ expectedAccountKey }, source.token), isCancellationError); + assert.deepStrictEqual(requestedUrls.map(url => new URL(url).pathname), ['/agents/tasks']); }); - test('counts reservation requests separately from submitted provisioning', async () => { + test('leaves reservation request telemetry to the shared transport without reporting submitted provisioning', async () => { const { service, requestOutcomes, provisioningOutcomes } = createService(store, { - tasks: [], repositories: new Map(), onRequest: () => jsonResponse(receipt, 201), + tasks: [], repositories: new Map(), onRequest: () => jsonTaskResponse(receipt, 201), }); await service.reserveSession({ expectedAccountKey }, CancellationToken.None); assert.deepStrictEqual({ requestOutcomes, provisioningOutcomes }, { - requestOutcomes: [['reserveTask', 'succeeded']], provisioningOutcomes: [], + requestOutcomes: [], provisioningOutcomes: [], }); }); }); @@ -5422,7 +5787,7 @@ suite('CloudSandboxApiService reservation submission', () => { assert.ok(options.data); const body: Record = JSON.parse(options.data); bodies.push(body); - return jsonResponse({ + return jsonTaskResponse({ id: 'reserved-task', sessions: [{ id: 'reserved-session', environment_id: 'reserved-env' }], ...(body.reserve === true ? { reserved: true, reservation_expires_at: '2030-01-01T00:10:00Z' } : { claimed: true }), }, body.reserve === true ? 201 : 200); @@ -5444,7 +5809,7 @@ suite('CloudSandboxApiService reservation submission', () => { { ...context, prompt: 'final prompt', reserved_task_id: 'reserved-task' }, ], created: { taskId: 'reserved-task', sessionId: 'reserved-session', environmentId: 'reserved-env', claimed: true }, - requestOutcomes: [['reserveTask', 'succeeded'], ['createTask', 'succeeded']], + requestOutcomes: [], provisioningOutcomes: ['success'], }); }); @@ -5455,23 +5820,23 @@ suite('CloudSandboxApiService reservation submission', () => { }; for (const invalid of [ { name: 'missing claim acknowledgement', response: { ...claimedTask, claimed: undefined } }, - { name: 'invalid claim acknowledgement', response: { ...claimedTask, claimed: 'true' } }, + { name: 'invalid claim acknowledgement', schemaInvalid: true, response: { ...claimedTask, claimed: 'true' } }, { name: 'still reserved task', response: { ...claimedTask, reserved: true } }, - { name: 'invalid reservation state', response: { ...claimedTask, reserved: 'false' } }, - { name: 'null reservation state', response: { ...claimedTask, reserved: null } }, + { name: 'invalid reservation state', schemaInvalid: true, response: { ...claimedTask, reserved: 'false' } }, + { name: 'null reservation state', schemaInvalid: true, response: { ...claimedTask, reserved: null } }, { name: 'different claimed task', response: { ...claimedTask, id: 'unexpected-task' } }, - { name: 'missing task identity', response: { ...claimedTask, id: undefined } }, - { name: 'numeric task identity', response: { ...claimedTask, id: 42 } }, - { name: 'blank task identity', response: { ...claimedTask, id: ' ' } }, + { name: 'missing task identity', schemaInvalid: true, response: { ...claimedTask, id: undefined } }, + { name: 'numeric task identity', schemaInvalid: true, response: { ...claimedTask, id: 42 } }, + { name: 'blank task identity', schemaInvalid: true, response: { ...claimedTask, id: ' ' } }, { name: 'missing claimed session', response: { ...claimedTask, sessions: [] } }, { name: 'missing fallback session', response: { ...claimedTask, id: 'fresh-task', claimed: false, sessions: [] } }, - { name: 'invalid session list', response: { ...claimedTask, sessions: {} } }, + { name: 'invalid session list', schemaInvalid: true, response: { ...claimedTask, sessions: {} } }, { name: 'non-concrete environment', response: { ...claimedTask, sessions: [{ id: 'reserved-session', environment_id: CLOUD_SANDBOX_ON_DEMAND_ENVIRONMENT_ID }] } }, ]) { test(`rejects a reservation submission with ${invalid.name} without deleting or replaying it`, async () => { const { service, calls } = createServiceForCreate(store, invalid.response, 200); - await assert.rejects(service.createSession(request, CancellationToken.None), CloudSandboxRequestError); + await assert.rejects(service.createSession(request, CancellationToken.None), invalid.schemaInvalid ? MutationUncertainError : CloudSandboxRequestError); assert.deepStrictEqual(calls.map(call => call.type), ['POST']); }); @@ -5507,37 +5872,43 @@ suite('CloudSandboxApiService reservation submission', () => { }); } - for (const error of [new Error('network interrupted'), new CancellationError()]) { - test(`reservation submission preserves ${error.name} after dispatch without retry or cleanup`, async () => { + for (const cancelled of [false, true]) { + test(`reservation submission reports ${cancelled ? 'cancellation' : 'an uncertain network outcome'} after dispatch without retry or cleanup`, async () => { + const source = store.add(new CancellationTokenSource()); const { service, requestedUrls } = createService(store, { - tasks: [], repositories: new Map(), onRequest: () => { throw error; }, + tasks: [], repositories: new Map(), + onRequest: () => { + if (cancelled) { + source.cancel(); + } + throw new Error('network interrupted'); + }, }); let dispatched = 0; - await assert.rejects(service.createSession(request, CancellationToken.None, () => dispatched++), caught => caught === error); + await assert.rejects(service.createSession(request, source.token, () => dispatched++), cancelled ? isCancellationError : MutationUncertainError); assert.deepStrictEqual({ requests: requestedUrls.length, dispatched }, { requests: 1, dispatched: 1 }); }); } for (const claimed of [false, true]) { - test(`late reservation submission acknowledgement retains claimed ${claimed} after cancellation`, async () => { + test(`late reservation submission with claimed ${claimed} does not override cancellation or trigger cleanup`, async () => { const source = store.add(new CancellationTokenSource()); const taskId = claimed ? 'reserved-task' : 'fresh-task'; const { service, requestedUrls, provisioningOutcomes } = createService(store, { tasks: [], repositories: new Map(), onRequest: () => { source.cancel(); - return jsonResponse({ ...claimedTask, id: taskId, claimed }, 200); + return jsonTaskResponse({ ...claimedTask, id: taskId, claimed }, 200); }, }); - const created = await service.createSession(request, source.token); + await assert.rejects(service.createSession(request, source.token), isCancellationError); assert.deepStrictEqual({ - created, requests: requestedUrls.length, provisioningOutcomes: provisioningOutcomes.map(outcome => outcome[0]), + requests: requestedUrls.length, provisioningOutcomes: provisioningOutcomes.map(outcome => outcome[0]), }, { - created: { taskId, sessionId: 'reserved-session', environmentId: 'reserved-env', claimed }, requests: 1, provisioningOutcomes: ['cancelled'], }); }); @@ -5570,7 +5941,7 @@ suite('CloudSandboxApiService session creation', () => { const serverRequestId = 'ABCD:1234:5678:9ABC:DEF01234'; const { service, lifecycleEvents } = createService(store, { tasks: [], repositories: new Map(), - onRequest: () => jsonResponse({ id: taskId, claimed: false, sessions: [{ id: sessionId, environment_id: environmentId }] }, 201, { 'x-github-request-id': serverRequestId }), + onRequest: () => jsonTaskResponse({ id: taskId, claimed: false, sessions: [{ id: sessionId, environment_id: environmentId }] }, 201, { 'x-github-request-id': serverRequestId }), }); await service.createSession({ reservedTaskId, prompt: 'private prompt', repoNwo: 'private/repository', @@ -5619,7 +5990,7 @@ suite('CloudSandboxApiService session creation', () => { test(`reports the ${scenario.path} startup path without exporting creation inputs`, async () => { const { service, provisioningOutcomes } = createService(store, { tasks: [], repositories: new Map(), - onRequest: () => jsonResponse({ + onRequest: () => jsonTaskResponse({ id: 'private-task', claimed: scenario.claimed, sessions: [{ id: 'private-session', environment_id: 'private-env' }], }, scenario.statusCode ?? 201), @@ -5659,7 +6030,7 @@ suite('CloudSandboxApiService session creation', () => { } return outcome === 'HTTP failure' ? jsonResponse({ message: 'unavailable' }, 503) - : jsonResponse({ id: 'task-1', sessions: [{ id: 'session-1', environment_id: 'env-1' }] }, 201); + : jsonTaskResponse({ id: 'task-1', sessions: [{ id: 'session-1', environment_id: 'env-1' }] }, 201); }, }); const creating = service.createSession({ prompt: 'hello', environmentId: 'env-1' }, CancellationToken.None, () => events.push('dispatch')); @@ -5739,7 +6110,7 @@ suite('CloudSandboxApiService session creation', () => { if (result === 'invalid JSON') { return { res: { headers: {}, statusCode: 200 }, stream: bufferToStream(VSBuffer.fromString('invalid')) }; } - return jsonResponse({ + return jsonTaskResponse({ id: 'private-task', sessions: result === 'invalid binding' ? [] : [{ id: 'private-session', environment_id: 'private-environment' }], }); @@ -5747,10 +6118,11 @@ suite('CloudSandboxApiService session creation', () => { }); await timeout(100); const provisioning = service.createSession({ prompt: 'private prompt' }, source.token); - if (result === 'success' || result === 'late success after cancellation') { + if (result === 'success') { await provisioning; } else { - await assert.rejects(provisioning, caught => result === 'network error' ? caught === error : caught instanceof Error); + await assert.rejects(provisioning, result === 'late success after cancellation' || result === 'cancelled' + ? isCancellationError : result === 'network error' ? MutationUncertainError : Error); } await timeout(100); assert.deepStrictEqual(provisioningOutcomes, [[ @@ -5780,7 +6152,6 @@ suite('CloudSandboxApiService session creation', () => { type: calls[0].type, endsWithTasks: calls[0].url.endsWith('/agents/tasks'), body: calls[0].body, - // Creating a task provisions a VM before replying, so it needs its own budget. timeout: calls[0].timeout, // `fetch` labels a string body `text/plain` unless told otherwise. contentType: calls[0].headers['Content-Type'], @@ -5793,8 +6164,7 @@ suite('CloudSandboxApiService session creation', () => { prompt: 'fix it', repositories: [{ owner: 'osortega', name: 'simple-server' }], }, - // A literal, not the constant: comparing a value to itself would prove nothing. - timeout: 60_000, + timeout: undefined, contentType: 'application/json', }); }); @@ -5877,7 +6247,7 @@ suite('CloudSandboxApiService session creation', () => { onRequest: () => { throw error; }, }); - await assert.rejects(service.createSession({ environmentId: 'env-prepared', prompt: 'hello' }, CancellationToken.None), caught => caught === error); + await assert.rejects(service.createSession({ environmentId: 'env-prepared', prompt: 'hello' }, CancellationToken.None), MutationUncertainError); assert.deepStrictEqual(requestedUrls.map(url => new URL(url).pathname), ['/agents/tasks']); }); @@ -5897,7 +6267,7 @@ suite('CloudSandboxApiService session creation', () => { }, onRequest: (_url, _token, options) => { calls.push({ body: JSON.parse(options.data ?? ''), headers: options.headers ?? {} }); - return jsonResponse({ id: 'task-1', sessions: [{ id: 'sess-1', environment_id: 'env-1' }] }); + return jsonTaskResponse({ id: 'task-1', sessions: [{ id: 'sess-1', environment_id: 'env-1' }] }); }, }); @@ -6023,15 +6393,15 @@ suite('CloudSandboxApiService session creation', () => { assert.deepStrictEqual(calls.map(c => c.type), ['POST']); }); - test('logs safe diagnostics instead of private bodies when creation fails', async () => { - const { service, errors } = createServiceForCreate(store, + test('surfaces safe diagnostics instead of private bodies when creation fails', async () => { + const { service, errors, warnings } = createServiceForCreate(store, { message: 'private credential', access_token: 'private credential', error_code: 'backend_error' }, 500, { responseHeaders: { 'x-github-request-id': 'ABCD:1234:5678:90AB:CDEF', 'x-sweagentd-retry': 'private header' } }); - await assert.rejects(() => service.createSession({ prompt: 'hello' }, CancellationToken.None)); - - assert.deepStrictEqual(errors, [ - '[CloudSandboxApi] Mission Control task create failed: HTTP 500 code=backend_error (requestId=ABCD:1234:5678:90AB:CDEF)', - ]); + await assert.rejects(() => service.createSession({ prompt: 'hello' }, CancellationToken.None), { + message: 'Mission Control task create failed: HTTP 500 code=backend_error (requestId=ABCD:1234:5678:90AB:CDEF)', + statusCode: 500, code: 'backend_error', + }); + assert.strictEqual([...errors, ...warnings].some(message => message.includes('private')), false); }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxCredentialRefresh.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxCredentialRefresh.test.ts index a18ea41c376f..6a643f10c8dc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxCredentialRefresh.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxCredentialRefresh.test.ts @@ -458,6 +458,50 @@ suite('CloudSandboxCredentialRefresher recovery', () => { return { refresher, credentials, creds, telemetry }; } + test('sleep pauses a pending credential retry and does not exhaust its request budget', () => runWithFakedTimers({ useFakeTimers: true, startTime: START_TIME }, async () => { + let attempts = 0; + const state = new CloudSandboxCredentialRefreshState(); + const { refresher, credentials, telemetry } = createRefresher(tokenExpiringIn(0, START_TIME), () => { + if (++attempts === 1) { + throw new CloudSandboxRequestError(503, 'temporarily unavailable', 30); + } + return { kind: 'token', token: tokenExpiringIn(40, Date.now()) }; + }, state); + await assert.rejects(refresher.refreshConnectionCredentials()); + const recovering = refresher.refreshConnectionCredentials(); + refresher.suspend(); + await timeout(600_000); + const whileAsleep = credentials.callCount; + refresher.resume(); + await recovering; + assert.deepStrictEqual({ whileAsleep, calls: credentials.callCount, stopped: state.stopped, stops: telemetry.stops }, { + whileAsleep: 1, calls: 2, stopped: false, stops: [], + }); + })); + + test('a network request interrupted by sleep does not consume the credential failure budget', () => runWithFakedTimers({ useFakeTimers: true, startTime: START_TIME }, async () => { + const response = new DeferredPromise(); + const state = new CloudSandboxCredentialRefreshState(); + const { refresher, telemetry } = createRefresher(tokenExpiringIn(0, START_TIME), () => response.p, state); + const rejected = assert.rejects(refresher.refreshConnectionCredentials()); + refresher.suspend(); + await response.error(new CloudSandboxRequestError(503, 'network interrupted')); + await rejected; + refresher.resume(); + assert.deepStrictEqual({ failures: state.unhealthyCycles, requestFailures: state.requestFailures, stopped: state.stopped, stops: telemetry.stops }, { + failures: 0, requestFailures: 0, stopped: false, stops: [], + }); + })); + + test('disposal cancels credential acquisition waiting for wake', async () => { + const { refresher, credentials } = createRefresher(tokenExpiringIn(0, START_TIME), () => assert.fail('request while suspended')); + refresher.suspend(); + const rejected = assert.rejects(refresher.refreshConnectionCredentials(), isCancellationError); + refresher.dispose(); + await rejected; + assert.strictEqual(credentials.callCount, 0); + }); + for (const scenario of ['authentication', 'retry', 'permanentError', 'wakingLimit', 'invalidExpiry', 'cancelledWait'] as const) { test(`user-local ${scenario} preserves credential behavior and stop aggregates without lifecycle events`, () => runWithFakedTimers({ useFakeTimers: true, startTime: START_TIME }, async () => { const observations = []; diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxTelemetry.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxTelemetry.test.ts index 672f8101f4b2..4db10ba75a73 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxTelemetry.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxTelemetry.test.ts @@ -33,11 +33,12 @@ import { } from '../../../browser/remoteAgentHost/cloudSandboxTelemetry.js'; const connectionDetails = { + suspendCount: 0, suspendedMs: 0, environmentOperation: 'resume', provisioningMs: 0, reservationWaitMs: 0, readinessMs: 0, preparationMs: 0, connectionMs: 0, environmentKind: 'cloud', taskCreationPath: 'unknown', - surface: 'unknown', source: 'existing', credentialRequests: 0, wakingResponses: 0, transportAttempts: 0, + surface: 'unknown', source: 'existing', credentialRequests: undefined, credentialOperations: 0, wakingResponses: 0, transportAttempts: 0, credentialsMs: 0, relayMs: 0, protocolMs: 0, authenticationMs: 0, restorationMs: 0, firstFailurePhase: undefined, firstFailureCode: undefined, credentialFailures: 0, relayFailures: 0, protocolFailures: 0, authenticationFailures: 0, restorationFailures: 0, @@ -68,6 +69,8 @@ suite('cloudSandbox telemetry', () => { const data = { trigger: 'feedRenewal', requestedMode: 'incremental', mode: 'full', outcome: 'partial', durationMs: 150, pageCount: 4, listRequestCount: 5, taskCount: 30, sandboxTaskCount: 2, + listOperationCount: 2, listOperationFailureCount: 1, + taskBatchOperationCount: 2, taskBatchOperationFailureCount: 1, changedSandboxTaskCount: 1, checkpointAdvanced: false, intentMode: 'incremental', fullScanReason: 'reconciliationDue', previousInventoryAgeMs: 480_000, lastFullAgeMs: 960_000, queued: true, coalescedRequestCount: 2, coalescedTrigger: 'feedRenewal', @@ -86,6 +89,8 @@ suite('cloudSandbox telemetry', () => { const data: ICloudSandboxDiscoveryTelemetryData = { trigger: 'manual', requestedMode: 'full', mode: 'full', outcome: 'complete', durationMs: 0, pageCount: 0, listRequestCount: 0, taskCount: 0, sandboxTaskCount: 0, + listOperationCount: undefined, listOperationFailureCount: undefined, + taskBatchOperationCount: undefined, taskBatchOperationFailureCount: undefined, changedSandboxTaskCount: 0, checkpointAdvanced: false, intentMode: 'incremental', fullScanReason: 'noCheckpoint', checkpointSource: 'unavailable', previousInventoryAgeMs: undefined, lastFullAgeMs: undefined, queued: undefined, coalescedRequestCount: undefined, @@ -463,7 +468,7 @@ suite('cloudSandbox telemetry', () => { operation: 'connect', outcome: 'success', stage: 'restoration', durationMs: 255, surface: 'agentsWeb', source: 'created', environmentOperation: 'provision', provisioningMs: 100, reservationWaitMs: undefined, readinessMs: 355, preparationMs: 70, connectionMs: 185, - credentialRequests: 3, wakingResponses: 1, transportAttempts: 2, + credentialOperations: 3, wakingResponses: 1, transportAttempts: 2, credentialsMs: 70, relayMs: 25, protocolMs: 30, authenticationMs: 40, restorationMs: 50, firstFailurePhase: 'transport.connect', firstFailureCategory: 'unknown', relayFailures: 1, }, @@ -473,7 +478,7 @@ suite('cloudSandbox telemetry', () => { ...connectionDetails, operation: 'recover', outcome: 'failure', stage: 'credentials', durationMs: 25, environmentOperation: 'recover', readinessMs: 25, preparationMs: 25, - surface: 'agentsWeb', source: 'created', credentialRequests: 1, credentialsMs: 25, + surface: 'agentsWeb', source: 'created', credentialOperations: 1, credentialsMs: 25, }, }, ]); @@ -689,8 +694,8 @@ suite('cloudSandbox telemetry', () => { second.completeConnect('cancelled'); service.dispose(); assert.deepStrictEqual(telemetry.events.map(event => event.data), [ - { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'credentials', durationMs: 10, readinessMs: 10, preparationMs: 10, credentialsMs: 10, credentialRequests: 2, wakingResponses: 1 }, - { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'credentials', durationMs: 20, readinessMs: 20, preparationMs: 20, credentialsMs: 20, credentialRequests: 1 }, + { ...connectionDetails, operation: 'connect', outcome: 'failure', stage: 'credentials', durationMs: 10, readinessMs: 10, preparationMs: 10, credentialsMs: 10, credentialOperations: 2, wakingResponses: 1 }, + { ...connectionDetails, operation: 'connect', outcome: 'cancelled', stage: 'credentials', durationMs: 20, readinessMs: 20, preparationMs: 20, credentialsMs: 20, credentialOperations: 1 }, ]); })); @@ -730,11 +735,38 @@ suite('cloudSandbox telemetry', () => { connection.onConnectionStateChange('failed'); service.dispose(); assert.deepStrictEqual(telemetry.events.filter(event => event.eventName === 'cloudSandboxConnectionOutcome').map(event => event.data), [ - { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialRequests: 1 }, - { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'failure', stage: 'connection', durationMs: 0, credentialRequests: 1, wakingResponses: 1 }, + { ...connectionDetails, operation: 'connect', outcome: 'success', stage: 'connection', durationMs: 0, credentialOperations: 1 }, + { ...connectionDetails, operation: 'recover', environmentOperation: 'recover', outcome: 'failure', stage: 'connection', durationMs: 0, credentialOperations: 1, wakingResponses: 1 }, ]); })); + test('recovery reports overlapping sleep time and the source-owned stop reason without diagnostic content', () => runWithFakedTimers({}, async () => { + const telemetry = new TestTelemetryService(); + const service = store.add(new CloudSandboxTelemetryService(telemetry)); + const connection = store.add(service.trackConnection('connection', 'agentsDesktop', 'existing', { environmentKind: 'user-local' })); + connection.onConnectionStateChange('connected'); + const diagnostic = (phase: string) => connection.recordConnectionDiagnostic({ + operationId: 'private-id', phase, outcome: 'info', timestamp: Date.now(), detail: 'private diagnostic', + }); + diagnostic('power.suspend'); + await timeout(1000); + connection.onConnectionStateChange('reconnecting'); + await timeout(600_000); + diagnostic('power.resume'); + await timeout(2000); + diagnostic('reconnect.timedOut'); + connection.onConnectionStateChange('failed'); + const event = telemetry.events.find(event => event.eventName === 'userLocalRelayConnectionOutcome' && event.data?.operation === 'recover'); + type ClassifiedSample = { [K in keyof Omit]: NonNullable extends { isMeasurement: true } ? number | undefined : string | undefined }; + const expected: ClassifiedSample = { + ...connectionDetails, environmentKind: 'user-local', environmentOperation: 'recover', + surface: 'agentsDesktop', operation: 'recover', outcome: 'failure', stage: 'connection', + durationMs: 602_000, connectionMs: 602_000, readinessMs: 602_000, + suspendCount: 1, suspendedMs: 600_000, recoveryStopReason: 'timeout', + }; + assert.deepStrictEqual(event, { eventName: 'userLocalRelayConnectionOutcome', data: expected }); + })); + for (const environmentKind of ['cloud', 'user-local'] as const) { for (const outcome of ['success', 'failure', 'cancelled'] as const) { test(`reports ${environmentKind} first session request ${outcome} without counting user idle time`, () => runWithFakedTimers({}, async () => { @@ -821,6 +853,93 @@ suite('cloudSandbox telemetry', () => { }]); })); + test('attributes rapid post-readiness losses to their initiating boundary without multiplying samples or health losses', () => runWithFakedTimers({}, async () => { + const telemetry = new TestTelemetryService(); + const service = store.add(new CloudSandboxTelemetryService(telemetry)); + const connection = store.add(service.trackConnection('connection', 'agentsDesktop', 'existing', { environmentKind: 'user-local' })); + connection.onConnectionStateChange('connected'); + for (const closeReason of ['hostLaneClosed', 'publishAckTimeout'] as const) { + for (const phase of ['protocol.firstSessionRequest', 'protocol.sessionOpen'] as const) { + connection.recordConnectionDiagnostic({ + operationId: `${closeReason}-${phase}`, phase, outcome: 'started', timestamp: Date.now(), + requestKind: phase === 'protocol.firstSessionRequest' ? 'listSessions' : 'subscribeSession', connectionOperation: 'recover', + }); + } + await timeout(10); + connection.recordConnectionDiagnostic({ + operationId: 'private-id', phase: 'transport.closed', outcome: 'info', timestamp: Date.now(), closeReason, + detail: 'private text', error: { name: 'Error', message: 'private error' }, + }); + connection.onConnectionStateChange('reconnecting'); + connection.recordConnectionDiagnostic({ + operationId: 'retry', phase: 'transport.closed', outcome: 'info', timestamp: Date.now(), closeReason: 'socketError', + }); + connection.onConnectionStateChange('reconnecting'); + for (const phase of ['protocol.firstSessionRequest', 'protocol.sessionOpen'] as const) { + connection.recordConnectionDiagnostic({ operationId: `${closeReason}-${phase}`, phase, outcome: 'failed', timestamp: Date.now() }); + } + await timeout(30); + connection.onConnectionStateChange('connected'); + } + connection.recordConnectionDiagnostic({ operationId: 'last', phase: 'protocol.firstSessionRequest', outcome: 'started', timestamp: Date.now() }); + connection.recordConnectionDiagnostic({ operationId: 'last', phase: 'protocol.firstSessionRequest', outcome: 'succeeded', timestamp: Date.now() }); + connection.recordConnectionDiagnostic({ operationId: 'dispose', phase: 'protocol.sessionOpen', outcome: 'started', timestamp: Date.now() }); + connection.dispose(); + service.dispose(); + + assert.deepStrictEqual({ + samples: telemetry.events.filter(event => event.eventName !== 'userLocalRelayConnectionHealth').map(event => ({ + event: event.eventName, outcome: event.data?.outcome, reason: event.data?.closeReason, category: event.data?.errorCategory, + })), + health: telemetry.events.filter(event => event.eventName === 'userLocalRelayConnectionHealth').map(event => event.data), + privateContent: JSON.stringify(telemetry.events).includes('private'), + }, { + samples: [ + { event: 'userLocalRelayConnectionOutcome', outcome: 'success', reason: undefined, category: undefined }, + ...['hostLaneClosed', 'publishAckTimeout'].flatMap(reason => [ + { event: 'userLocalRelayFirstSessionRequest', outcome: 'failure', reason, category: 'connectionClosed' }, + { event: 'userLocalRelaySessionOpen', outcome: 'failure', reason, category: 'connectionClosed' }, + { event: 'userLocalRelayConnectionOutcome', outcome: 'success', reason, category: undefined }, + ]), + { event: 'userLocalRelayFirstSessionRequest', outcome: 'success', reason: undefined, category: undefined }, + { event: 'userLocalRelaySessionOpen', outcome: 'cancelled', reason: undefined, category: undefined }, + ], + health: [{ environmentKind: 'user-local', connectedMs: 20, unexpectedDisconnects: 2, receivedFrames: 0 }], + privateContent: false, + }); + })); + + test('allowlists close attribution only at user-local close boundaries, not from text or unrelated diagnostics', () => { + const results = []; + for (const sample of [ + { environmentKind: 'user-local', phase: 'transport.closed', closeReason: 'private reason' }, + { environmentKind: 'user-local', phase: 'transport.closed', closeReason: undefined }, + { environmentKind: 'user-local', phase: 'unrelated', closeReason: 'socketClose' }, + { environmentKind: 'cloud', phase: 'transport.closed', closeReason: 'socketClose' }, + ] as const) { + const telemetry = new TestTelemetryService(); + const service = store.add(new CloudSandboxTelemetryService(telemetry)); + const connection = store.add(service.trackConnection('connection', 'agentsDesktop', 'existing', { environmentKind: sample.environmentKind === 'user-local' ? sample.environmentKind : undefined })); + connection.onConnectionStateChange('connected'); + connection.recordConnectionDiagnostic({ operationId: 'first', phase: 'protocol.firstSessionRequest', outcome: 'started', timestamp: Date.now() }); + const diagnostic: IConnectionDiagnosticEvent = { operationId: 'close', phase: sample.phase, outcome: 'info', timestamp: Date.now(), detail: 'watchdog private text' }; + connection.recordConnectionDiagnostic(Object.assign(diagnostic, { closeReason: sample.closeReason })); + connection.onConnectionStateChange('reconnecting'); + connection.onConnectionStateChange('connected'); + service.dispose(); + results.push({ + reasons: telemetry.events.filter(event => event.data?.outcome === 'failure' || event.data?.operation === 'recover').map(event => event.data?.closeReason), + privateContent: JSON.stringify(telemetry.events).includes('private'), + }); + } + assert.deepStrictEqual(results, [ + { reasons: ['unknown', 'unknown'], privateContent: false }, + { reasons: ['unknown', 'unknown'], privateContent: false }, + { reasons: [undefined, undefined], privateContent: false }, + { reasons: [undefined, undefined], privateContent: false }, + ]); + }); + for (const state of ['reconnecting', 'failed', 'disposed'] as const) { test(`settles a pending session snapshot once when ${state}, without counting later completion`, () => runWithFakedTimers({}, async () => { const telemetry = new TestTelemetryService(); @@ -1149,7 +1268,7 @@ suite('cloudSandbox telemetry', () => { for (const environmentKind of ['cloud', 'user-local'] as const) { test(`${environmentKind} classification marks every numeric payload field, and no string field, as a measurement`, () => runWithFakedTimers({}, async () => { - type ClassifiedSample = { [K in keyof Omit]: NonNullable extends { isMeasurement: true } ? number : string }; + type ClassifiedSample = { [K in keyof Omit]: NonNullable extends { isMeasurement: true } ? number | undefined : string }; const outcome: ClassifiedSample = { ...connectionDetails, environmentKind, environmentOperation: environmentKind === 'user-local' ? 'attach' : 'resume', operation: 'connect', outcome: 'success', stage: 'protocol', durationMs: 2000, readinessMs: 2000, connectionMs: 2000, diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlContribution.test.ts index 782d0a372935..9d62335d4b86 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlContribution.test.ts @@ -7,7 +7,7 @@ import assert from 'assert'; import { restore, stub } from 'sinon'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { IDefaultAccount } from '../../../../../../base/common/defaultAccount.js'; -import { isCancellationError } from '../../../../../../base/common/errors.js'; +import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; @@ -17,7 +17,7 @@ import { runWithFakedTimers } from '../../../../../../base/test/common/timeTrave import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAgentHostService, IMissionControlOptions } from '../../../../../../platform/agentHost/common/agentService.js'; import { CloudSandboxAutoConnectOnOpenSettingId, CloudSandboxEarlyPreparationSettingId, CloudSandboxEnabledSettingId, ICloudSandboxDraftPreparationService } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; -import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, MissionControlUseLocalCredentialsConfigKey, MissionControlUseLocalCredentialsSettingId } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { AgentHostDefaultCloneDirectorySettingId, AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentSharingError, GitHubEnvironmentSharingFailureReason, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, MissionControlOwnerMismatchError, MissionControlUseLocalCredentialsConfigKey, MissionControlUseLocalCredentialsSettingId } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { AgentHostConfigurationSyncTarget, resolveAgentHostConfigurationSyncPatch } from '../../../../../../platform/agentHost/common/agentHostConfigurationSync.js'; import { IConfigurationChangeEvent, IConfigurationService, IConfigurationValue } from '../../../../../../platform/configuration/common/configuration.js'; import { ConfigurationModelParser } from '../../../../../../platform/configuration/common/configurationModels.js'; @@ -26,7 +26,7 @@ import { TestConfigurationService } from '../../../../../../platform/configurati import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { getSingletonServiceDescriptors } from '../../../../../../platform/instantiation/common/extensions.js'; -import { FileOperationError, FileOperationResult, IFileService, IFileStatWithMetadata, IFileStatWithPartialMetadata } from '../../../../../../platform/files/common/files.js'; +import { createFileSystemProviderError, FileOperationError, FileOperationResult, FileSystemProviderErrorCode, IFileService, IFileStatWithMetadata, IFileStatWithPartialMetadata } from '../../../../../../platform/files/common/files.js'; import { IPathService } from '../../../../../../platform/path/common/pathService.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../../platform/product/common/productService.js'; @@ -106,6 +106,10 @@ suite('Mission Control sharing service', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); teardown(() => restore()); + function sharingFailure(reason: GitHubEnvironmentSharingFailureReason, message: RegExp) { + return (error: unknown) => error instanceof GitHubEnvironmentSharingError && error.reason === reason && message.test(error.message); + } + function fixture(options: { backend?: AgentHostRemoteConnectionsBackend; configuration?: TestConfigurationService; @@ -526,7 +530,7 @@ suite('Mission Control sharing service', () => { override affectsConfiguration(section: string) { return section === GitHubEnvironmentsEnabledSettingId; } }()); await timeout(0); - await assert.rejects(sharing.setEnabled(true), /unavailable/); + await assert.rejects(sharing.setEnabled(true), sharingFailure('unavailable', /unavailable/)); assert.deepStrictEqual({ calls, state: sharing.state.get() }, { calls: [ { options: expectedOptions, withdrawingAccountId: undefined }, @@ -568,6 +572,28 @@ suite('Mission Control sharing service', () => { }); })); + test('reports an availability withdrawal failure once without retrying setup', () => runWithFakedTimers({}, async () => { + const error = new Error('Withdrawal failed'); + const { availability, sharing, calls, logService } = fixture({ + configure: async options => { + if (!options) { + throw error; + } + }, + }); + await sharing.setEnabled(true); + await timeout(0); + const logError = stub(logService, 'error'); + calls.length = 0; + availability.set(false, undefined); + await timeout(2000); + assert.deepStrictEqual({ state: sharing.state.get(), calls, errors: logError.args }, { + state: 'disabled', + calls: [{ options: undefined, withdrawingAccountId: 'account' }], + errors: [['Mission Control configuration failed', error]], + }); + })); + for (const enabled of [false, true]) { test(`ignores removed settings when registration is ${enabled ? 'enabled' : 'disabled'}`, () => runWithFakedTimers({}, async () => { const { calls, starts, sharing } = fixture(); @@ -629,38 +655,52 @@ suite('Mission Control sharing service', () => { assert.deepStrictEqual(calls, [{ options: expectedOptions, withdrawingAccountId: undefined }]); })); - test('shares all available Windows drives but starts at home without creating a directory', () => runWithFakedTimers({}, async () => { + test('shares readable local Windows drives but starts at home without creating a directory', () => runWithFakedTimers({}, async () => { const windowsHome = URI.parse('file:///C:/Users/test'); const statRequests: string[] = []; - const { sharing, calls, createdFolders } = fixture({ + const { sharing, calls, createdFolders, logService } = fixture({ windows: true, emptyWindow: true, userHome: windowsHome, stat: async resource => { statRequests.push(resource.path); - if (!['/C:/', '/D:/', '/Z:/'].includes(resource.path)) { + if (resource.path === '/E:/') { + throw createFileSystemProviderError('Drive not ready', FileSystemProviderErrorCode.Unknown); + } + if (!['/C:/', '/D:/', '/F:/', '/Z:/'].includes(resource.path)) { throw new FileOperationError('Drive not found', FileOperationResult.FILE_NOT_FOUND); } return upcastPartial({ resource, isDirectory: true }); }, - realpath: async resource => resource.path === '/Z:/' ? resource.with({ path: '\\\\server\\share\\' }) : resource, + realpath: async resource => { + if (resource.path === '/F:/') { + throw createFileSystemProviderError('Volume locked', FileSystemProviderErrorCode.Unknown); + } + return resource.path === '/Z:/' ? resource.with({ path: '\\\\server\\share\\' }) : resource; + }, }); + const warn = stub(logService, 'warn'); await sharing.setEnabled(true); - assert.deepStrictEqual({ options: calls[0].options, statRequests, createdFolders }, { + const driveWarnings = warn.getCalls().filter(call => call.args[0] === '[Mission Control] Excluding a drive that cannot be read from local filesystem sharing'); + assert.deepStrictEqual({ options: calls[0].options, statRequests, createdFolders, driveWarnings: driveWarnings.map(call => call.args.slice(1)) }, { options: { ...expectedOptions, roots: [URI.parse('file:///C:/').fsPath, URI.parse('file:///D:/').fsPath, windowsHome.fsPath], projects: [], defaultDirectory: windowsHome.fsPath, }, statRequests: Array.from({ length: 26 }, (_, index) => `/${String.fromCharCode(65 + index)}:/`), createdFolders: [], + driveWarnings: [['file:///e%3A/', 'Drive not ready'], ['file:///f%3A/', 'Volume locked']], }); })); - test('reports unexpected drive enumeration failures instead of granting a partial filesystem', () => runWithFakedTimers({}, async () => { + test('reports drive enumeration failures when no drive can be read instead of granting a partial filesystem', () => runWithFakedTimers({}, async () => { const { sharing, calls } = fixture({ windows: true, - stat: async () => { throw new Error('Filesystem unavailable'); }, + stat: async () => { throw createFileSystemProviderError('Filesystem unavailable', FileSystemProviderErrorCode.NoPermissions); }, + }); + const error = await sharing.setEnabled(true).then(() => undefined, (error: unknown) => error); + assert.ok(error instanceof GitHubEnvironmentSharingError); + assert.deepStrictEqual({ message: error.message, reason: error.reason, fileErrorCode: error.fileErrorCode, state: sharing.state.get(), calls }, { + message: 'Filesystem unavailable', reason: 'fileSystemRoot', fileErrorCode: FileSystemProviderErrorCode.NoPermissions, state: 'disabled', calls: [], }); - await assert.rejects(sharing.setEnabled(true), /Filesystem unavailable/); - assert.deepStrictEqual({ state: sharing.state.get(), calls }, { state: 'disabled', calls: [] }); })); test('does not reconfigure when removed settings change', () => runWithFakedTimers({}, async () => { @@ -816,7 +856,7 @@ suite('Mission Control sharing service', () => { const { sharing, calls, storage } = fixture({ configure: async options => { if (options) { throw new Error('Registration failed'); } }, }); - await assert.rejects(sharing.setEnabled(true), /Registration failed/); + await assert.rejects(sharing.setEnabled(true), /Could not set up GitHub environment sharing/); const restored = fixture({ storage }); await timeout(0); assert.deepStrictEqual({ state: sharing.state.get(), restoredCalls: restored.calls, calls }, { @@ -827,6 +867,281 @@ suite('Mission Control sharing service', () => { }); })); + for (const replacementFails of [false, true]) { + test(`waits for the replacement configuration when the original enable attempt fails (${replacementFails ? 'failure' : 'success'})`, () => runWithFakedTimers({}, async () => { + const first = new DeferredPromise(); + const replacement = new DeferredPromise(); + let attempts = 0; + const { sharing, calls, storage } = fixture({ + configure: options => !options ? Promise.resolve() : ++attempts === 1 ? first.p : replacement.p, + }); + const error = new Error('Replacement rejected'); + let settled = false; + const enabling = sharing.setEnabled(true).finally(() => { settled = true; }); + const outcome = replacementFails + ? assert.rejects(enabling, failure => failure instanceof Error && failure.cause === error) + : enabling; + await timeout(0); + sharing.setProjectFolders([]); + await timeout(0); + first.error(new Error('Superseded connection failed')); + await timeout(0); + const pending = { state: sharing.state.get(), settled }; + if (replacementFails) { + replacement.error(error); + } else { + replacement.complete(); + } + await outcome; + await timeout(0); + const restored = fixture({ storage }); + await timeout(0); + assert.deepStrictEqual({ + pending, state: sharing.state.get(), attempts, + withdrawals: calls.filter(call => !call.options).length, + restored: restored.sharing.state.get(), + }, { + pending: { state: 'connecting', settled: false }, + state: replacementFails ? 'disabled' : 'enabled', + attempts: 2, + withdrawals: replacementFails ? 1 : 0, + restored: replacementFails ? 'disabled' : 'enabled', + }); + })); + } + + test('retries transient enable failures with bounded backoff while staying connecting', () => runWithFakedTimers({}, async () => { + const started = Date.now(); + const attempts: { delay: number; state: string }[] = []; + const { sharing } = fixture({ + configure: async options => { + if (options) { + attempts.push({ delay: Date.now() - started, state: sharing.state.get() }); + if (attempts.length < 3) { + throw new TypeError('fetch failed', { + cause: new Error('Dispatcher failed', { + cause: Object.assign(new Error('Network failure'), { code: 'ETIMEDOUT' }), + }), + }); + } + } + }, + }); + await sharing.setEnabled(true); + assert.deepStrictEqual({ attempts, state: sharing.state.get() }, { + attempts: [{ delay: 0, state: 'connecting' }, { delay: 500, state: 'connecting' }, { delay: 1500, state: 'connecting' }], + state: 'enabled', + }); + })); + + test('rejects once after exhausting enable retries and preserves the original timeout', () => runWithFakedTimers({}, async () => { + const error = Object.assign(new Error('Mission Control WPS socket error'), { code: 'ETIMEDOUT' }); + const { sharing, calls, storage } = fixture({ + configure: async options => { if (options) { throw error; } }, + }); + await assert.rejects(sharing.setEnabled(true), failure => failure instanceof Error + && failure.message === 'The connection timed out. Please try again.' && failure.cause === error); + const restored = fixture({ storage }); + await timeout(0); + assert.deepStrictEqual({ + state: sharing.state.get(), + attempts: calls.filter(call => call.options).length, + withdrawals: calls.filter(call => !call.options).length, + restoredCalls: restored.calls, + }, { state: 'disabled', attempts: 3, withdrawals: 1, restoredCalls: [] }); + })); + + for (const status of [401, 403]) { + test(`does not retry an authentication or policy rejection (${status})`, () => runWithFakedTimers({}, async () => { + const error = Object.assign(new Error('Mission Control WPS socket error'), { status }); + const { sharing, calls } = fixture({ + configure: async options => { if (options) { throw error; } }, + }); + await assert.rejects(sharing.setEnabled(true), sharingFailure('connection', status === 401 ? /Sign in to GitHub again/ : /Check your account and organization settings/)); + assert.deepStrictEqual({ state: sharing.state.get(), attempts: calls.filter(call => call.options).length }, { + state: 'disabled', attempts: 1, + }); + })); + } + + test('explains how to recover from an Agent Host account mismatch without retrying', () => runWithFakedTimers({}, async () => { + const { sharing, calls } = fixture({ + configure: async options => { + if (options) { + throw new MissionControlOwnerMismatchError('Agent Host already belongs to another local account'); + } + }, + }); + await assert.rejects(sharing.setEnabled(true), sharingFailure('ownerMismatch', /Restart VS Code to share it with another account/)); + assert.deepStrictEqual({ state: sharing.state.get(), attempts: calls.filter(call => call.options).length }, { + state: 'disabled', attempts: 1, + }); + })); + + for (const backgroundFails of [false, true]) { + for (const enableFails of [false, true]) { + test(`keeps a new enable operation separate from an in-flight background restore (background ${backgroundFails ? 'fails' : 'succeeds'}, enable ${enableFails ? 'fails' : 'succeeds'})`, () => runWithFakedTimers({}, async () => { + const first = fixture(); + await first.sharing.setEnabled(true); + first.sharing.dispose(); + const background = new DeferredPromise(); + let attempts = 0; + const { sharing, calls } = fixture({ + storage: first.storage, + configure: async options => { + if (options && ++attempts === 1) { + await background.p; + } else if (options && enableFails) { + throw new Error('Enable failed'); + } + }, + }); + await timeout(0); + await sharing.setEnabled(false); + let settled = false; + const enabling = sharing.setEnabled(true).finally(() => { settled = true; }); + const outcome = enableFails ? assert.rejects(enabling, /Could not set up GitHub environment sharing/) : enabling; + sharing.setProjectFolders([]); + await timeout(0); + const pending = { state: sharing.state.get(), settled }; + if (backgroundFails) { + background.error(new Error('Restore failed')); + } else { + background.complete(); + } + await outcome; + await timeout(0); + assert.deepStrictEqual({ + pending, state: sharing.state.get(), attempts, + withdrawals: calls.filter(call => !call.options).length, + }, { + pending: { state: 'connecting', settled: false }, + state: enableFails ? 'disabled' : 'enabled', + attempts: 2, + withdrawals: enableFails ? 2 : 1, + }); + })); + } + } + + for (const setting of [MissionControlUseLocalCredentialsSettingId, remoteControlPolicyOverrideSetting]) { + test(`applies ${setting} changes that withdraw an in-flight enable without dropping the new configuration`, () => runWithFakedTimers({}, async () => { + const configuring = new DeferredPromise(); + let attempts = 0; + const { sharing, calls, configuration } = fixture({ + configure: options => options && ++attempts === 1 ? configuring.p : Promise.resolve(), + }); + const enabling = sharing.setEnabled(true); + await timeout(0); + await configuration.setUserConfiguration(setting, setting === remoteControlPolicyOverrideSetting); + configuration.onDidChangeConfigurationEmitter.fire(new class extends mock() { + override affectsConfiguration(section: string) { return section === setting; } + }()); + await timeout(0); + configuring.complete(); + await enabling; + await timeout(0); + assert.deepStrictEqual({ + state: sharing.state.get(), + calls: calls.map(call => call.options ? { + useLocalCredentials: call.options.useLocalCredentials === true, + ignoreRemoteControlPolicy: call.options.ignoreRemoteControlPolicy === true, + } : { withdrawingAccountId: call.withdrawingAccountId }), + }, { + state: 'enabled', + calls: [ + { useLocalCredentials: true, ignoreRemoteControlPolicy: false }, + { withdrawingAccountId: 'account' }, + { + useLocalCredentials: setting === remoteControlPolicyOverrideSetting, + ignoreRemoteControlPolicy: setting === remoteControlPolicyOverrideSetting, + }, + ], + }); + })); + } + + for (const queuedBehindRestore of [false, true]) { + test(`renaming during enable is handled by that enable operation (${queuedBehindRestore ? 'queued behind restore' : 'active'})`, () => runWithFakedTimers({}, async () => { + const first = fixture(); + if (queuedBehindRestore) { + await first.sharing.setEnabled(true); + } + first.sharing.dispose(); + const configuring = new DeferredPromise(); + let attempts = 0; + const { sharing, calls } = fixture({ + storage: first.storage, + configure: options => options && ++attempts === 1 ? configuring.p : Promise.resolve(), + }); + if (queuedBehindRestore) { + await timeout(0); + await sharing.setEnabled(false); + } + const enabling = sharing.setEnabled(true); + await timeout(0); + const renaming = sharing.setEnvironmentName('New shared name'); + await timeout(0); + configuring.complete(); + await Promise.all([enabling, renaming]); + await timeout(0); + assert.deepStrictEqual({ + state: sharing.state.get(), attempts, + names: calls.filter(call => call.options).map(call => call.options?.name), + }, { state: 'enabled', attempts: 2, names: [undefined, 'New shared name'] }); + })); + } + + test('turning sharing off cancels the retry delay without another attempt or failure', () => runWithFakedTimers({}, async () => { + const { sharing, calls } = fixture({ + configure: async options => { + if (options) { + throw Object.assign(new Error('Connection reset'), { code: 'ECONNRESET' }); + } + }, + }); + const enabling = sharing.setEnabled(true); + await timeout(0); + await sharing.setEnabled(false); + await enabling; + await timeout(2000); + assert.deepStrictEqual({ state: sharing.state.get(), calls }, { + state: 'disabled', + calls: [ + { options: expectedOptions, withdrawingAccountId: undefined }, + { options: undefined, withdrawingAccountId: 'account' }, + ], + }); + })); + + test('ignores a connection failure that arrives after sharing was turned off', () => runWithFakedTimers({}, async () => { + const configuring = new DeferredPromise(); + const { sharing, calls } = fixture({ configure: options => options ? configuring.p : Promise.resolve() }); + const enabling = sharing.setEnabled(true); + await timeout(0); + await sharing.setEnabled(false); + configuring.error(Object.assign(new Error('Connection timed out'), { code: 'ETIMEDOUT' })); + await enabling; + await timeout(2000); + assert.deepStrictEqual({ state: sharing.state.get(), calls }, { + state: 'disabled', + calls: [ + { options: expectedOptions, withdrawingAccountId: undefined }, + { options: undefined, withdrawingAccountId: 'account' }, + ], + }); + })); + + test('preserves host cancellation without retrying or translating it to a connection error', () => runWithFakedTimers({}, async () => { + const { sharing, calls } = fixture({ + configure: async options => { if (options) { throw new CancellationError(); } }, + }); + await assert.rejects(sharing.setEnabled(true), isCancellationError); + assert.deepStrictEqual({ state: sharing.state.get(), attempts: calls.filter(call => call.options).length }, { + state: 'disabled', attempts: 1, + }); + })); + for (const message of ['fetch failed', 'Mission Control WPS connection closed before joining control group']) { for (const trigger of ['window reload', 'host restart'] as const) { test(`logs background configuration failure without notifying after ${trigger}: ${message}`, () => runWithFakedTimers({}, async () => { @@ -916,10 +1231,10 @@ suite('Mission Control sharing service', () => { test('does not register an ambiguous account or bypass disabled AI', () => runWithFakedTimers({}, async () => { const ambiguous = fixture({ getSessions: async () => [session, { ...session, account: { id: 'second', label: 'Second' } }] }); - await assert.rejects(ambiguous.sharing.setEnabled(true), /Select a GitHub account for Copilot/); + await assert.rejects(ambiguous.sharing.setEnabled(true), sharingFailure('multipleAccounts', /Select a GitHub account for Copilot/)); const hidden = fixture(); hidden.disableAI(); - await assert.rejects(hidden.sharing.setEnabled(true), /sharing is unavailable/); + await assert.rejects(hidden.sharing.setEnabled(true), sharingFailure('unavailable', /sharing is unavailable/)); assert.deepStrictEqual({ ambiguous: ambiguous.calls, hidden: hidden.calls }, { ambiguous: [], hidden: [] }); })); @@ -970,12 +1285,12 @@ suite('Mission Control sharing service', () => { getSessions: async (_providerId, scopes) => scopes ? [] : [copilotSession], createSession: async () => otherSession, }); - await assert.rejects(sharing.setEnabled(true), /Sign in with the selected Copilot account/); + await assert.rejects(sharing.setEnabled(true), sharingFailure('accountMismatch', /Sign in with the selected Copilot account/)); assert.deepStrictEqual({ state: sharing.state.get(), calls }, { state: 'disabled', calls: [] }); })); - for (const error of [new Error('Cancelled'), 'Cancelled']) { - test(`normalizes GitHub sign-in cancellation (${typeof error})`, () => runWithFakedTimers({}, async () => { + for (const [error, label] of [[new Error('Cancelled'), 'object'], ['Cancelled', 'string'], [new CancellationError(), 'CancellationError']] as const) { + test(`normalizes GitHub sign-in cancellation (${label})`, () => runWithFakedTimers({}, async () => { const { sharing, calls, storage } = fixture({ defaultAccount: copilotAccount, getSessions: async (_providerId, scopes) => scopes ? [] : [copilotSession], @@ -990,13 +1305,13 @@ suite('Mission Control sharing service', () => { })); } - for (const defaultAccount of [ - { ...copilotAccount, sessionId: 'missing' }, - { ...copilotAccount, authenticationProvider: { id: 'github-enterprise', name: 'GitHub Enterprise', enterprise: true } }, - ]) { + for (const [defaultAccount, reason] of [ + [{ ...copilotAccount, sessionId: 'missing' }, 'accountUnavailable'], + [{ ...copilotAccount, authenticationProvider: { id: 'github-enterprise', name: 'GitHub Enterprise', enterprise: true } }, 'nonGitHubAccount'], + ] as const) { test(`does not fall back to another account when the Copilot account is unavailable (${defaultAccount.authenticationProvider.id}, ${defaultAccount.sessionId})`, () => runWithFakedTimers({}, async () => { const { sharing, calls } = fixture({ defaultAccount }); - await assert.rejects(sharing.setEnabled(true), /Copilot account/); + await assert.rejects(sharing.setEnabled(true), sharingFailure(reason, /Copilot account/)); assert.deepStrictEqual({ state: sharing.state.get(), calls }, { state: 'disabled', calls: [] }); })); } 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 997369a7b4e1..89c78b66a160 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 @@ -366,6 +366,106 @@ suite('Mission Control inventory', () => { }); }); + for (const status of ['online', 'offline']) { + test(`cached online availability is not discovered until a fresh ${status} response`, async () => { + const first = fixture(); + await first.service.refresh(CancellationToken.None); + first.service.dispose(); + const reopened = fixture(first.storage); + await reopened.service.initialize(); + const snapshot = () => ({ + status: reopened.service.hosts.get()[0]?.status, + online: [...reopened.service.discoveredOnlineHostIds.get()], + }); + const cached = snapshot(); + const response = new DeferredPromise(); + const listed = reopened.setList(response.p); + const refresh = reopened.service.refresh(CancellationToken.None); + await listed; + const pending = snapshot(); + await response.complete([host('remote', 'Machine', status)]); + await refresh; + assert.deepStrictEqual({ cached, pending, refreshed: snapshot() }, { + cached: { status: 'online', online: [] }, + pending: { status: 'online', online: [] }, + refreshed: { status, online: status === 'online' ? ['remote'] : [] }, + }); + }); + } + + test('failed startup discovery retains cached UI and manual admission without confirming cached availability', async () => { + const first = fixture(); + await first.service.refresh(CancellationToken.None); + first.service.dispose(); + const reopened = fixture(first.storage); + await reopened.service.initialize(); + reopened.setList(Promise.reject(new Error('Inventory unavailable'))); + await assert.rejects(reopened.service.refresh(CancellationToken.None), /Inventory unavailable/); + await reopened.service.connect('remote', CancellationToken.None); + assert.deepStrictEqual({ + hosts: reopened.service.hosts.get(), + online: [...reopened.service.discoveredOnlineHostIds.get()], + lookups: reopened.calls.lookups, + connects: reopened.calls.connects.length, + }, { hosts: [{ ...host('remote'), displayName: undefined }], online: [], lookups: ['remote'], connects: 1 }); + }); + + test('storage updates cannot turn a freshly offline host into a discovered online host', async () => { + const context = fixture(); + context.setList(Promise.resolve([host('remote', 'Machine', 'offline')])); + await context.service.refresh(CancellationToken.None); + context.storage.store(`missionControl.userLocalHosts.v1.${encodeURIComponent(firstAccount)}.remote.metadata`, + JSON.stringify(host('remote')), StorageScope.PROFILE, StorageTarget.MACHINE); + assert.deepStrictEqual({ + status: context.service.hosts.get()[0].status, + online: [...context.service.discoveredOnlineHostIds.get()], + }, { status: 'online', online: [] }); + }); + + for (const change of ['account', 'disable'] as const) { + test(`${change} invalidates discovered availability and rejects an old in-flight response`, async () => { + const first = fixture(); + await first.service.refresh(CancellationToken.None); + first.service.dispose(); + const context = fixture(first.storage); + await context.service.refresh(CancellationToken.None); + const before = [...context.service.discoveredOnlineHostIds.get()]; + const oldResponse = new DeferredPromise(); + const oldListed = context.setList(oldResponse.p); + const oldRefresh = context.service.refresh(CancellationToken.None); + const rejected = assert.rejects(oldRefresh, CancellationError); + await oldListed; + const newResponse = new DeferredPromise(); + const newListed = context.setList(newResponse.p); + if (change === 'account') { + context.changeAccount(secondAccount); + } else { + context.availability.set(false, undefined); + context.availability.set(true, undefined); + } + await newListed; + const pending = { + hosts: context.service.hosts.get().map(host => host.id), + online: [...context.service.discoveredOnlineHostIds.get()], + }; + await oldResponse.complete([host('remote')]); + await rejected; + const afterOldResponse = [...context.service.discoveredOnlineHostIds.get()]; + const refresh = context.service.refresh(CancellationToken.None); + await newResponse.complete([host('remote', 'Current', 'offline')]); + await refresh; + assert.deepStrictEqual({ + before, pending, afterOldResponse, + online: [...context.service.discoveredOnlineHostIds.get()], + status: context.service.hosts.get()[0].status, + }, { + before: ['remote'], + pending: { hosts: change === 'account' ? [] : ['remote'], online: [] }, + afterOldResponse: [], online: [], status: 'offline', + }); + }); + } + test('previously hidden hosts are restored and connectable without losing local names', async () => { const { service, storage, calls } = fixture(); const prefix = `missionControl.userLocalHosts.v1.${encodeURIComponent(firstAccount)}.remote`; diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.test.ts index 227141437687..6ae73f0a58cc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostAuthenticationResolver.test.ts @@ -12,6 +12,8 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/ import { URI } from '../../../../../../base/common/uri.js'; import { AgentHostAuthenticationPendingError } from '../../../../../../platform/agentHost/common/agentHostAdvertisedAuthentication.js'; import { authenticationAccountMeta } from '../../../../../../platform/agentHost/common/meta/agentAuthenticationAccount.js'; +import { copilotEntraAuthenticationMeta } from '../../../../../../platform/agentHost/common/meta/agentHostCopilotAuthentication.js'; +import { copilotEntraAuthorizationServer, copilotEntraClientId, copilotEntraDiscoveryResource } from '../../../../../../platform/agentHost/common/copilotEntraAuthentication.js'; import { readAgentEntitlementHint } from '../../../../../../platform/agentHost/common/meta/agentEntitlementHintMeta.js'; import type { AgentInfo } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; @@ -35,16 +37,18 @@ suite('RemoteAgentHostAuthenticationResolver', () => { expiresAfter: 1500, authorizationServer: URI.parse('https://example.com'), }; - function fixture(options?: { editor?: boolean; transform?: boolean; smokeTest?: boolean; testToken?: string; lookup?: () => Promise }) { + function fixture(options?: { editor?: boolean; transform?: boolean; smokeTest?: boolean; testToken?: string; providerId?: string; lookup?: () => Promise }) { const instantiationService = store.add(new TestInstantiationService()); const extensions = new DeferredPromise(); const sessionChanges = store.add(new Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }>()); + const queries: Parameters[] = []; const state = { registered: true, sessions: [session], sessionError: false, extensionWaits: 0, lookups: 0, + queries, }; instantiationService.stub(ILogService, NullLogService); instantiationService.stub(IDefaultAccountService, { currentDefaultAccount: null }); @@ -65,9 +69,10 @@ suite('RemoteAgentHostAuthenticationResolver', () => { override isAuthenticationProviderRegistered(): boolean { return state.registered; } override async getOrActivateProviderIdForServer(): Promise { state.lookups++; - return state.registered ? 'test' : undefined; + return state.registered ? options?.providerId ?? 'test' : undefined; } - override async getSessions(): Promise { + override async getSessions(...args: Parameters): Promise { + state.queries.push(args); if (options?.lookup) { return options.lookup(); } @@ -101,6 +106,36 @@ suite('RemoteAgentHostAuthenticationResolver', () => { }); }); + test('preserves the advertised bridge context during initial Microsoft acquisition', async () => { + const { resolver, instantiationService, extensions, state } = fixture({ providerId: 'microsoft' }); + await extensions.complete(true); + const microsoft = { ...session, scopes: ['User.Read'], authorizationServer: URI.parse(copilotEntraAuthorizationServer) }; + state.sessions = [microsoft]; + instantiationService.stub(IDefaultAccountService, { + currentDefaultAccount: { + sessionId: microsoft.id, accountName: microsoft.account.label, enterprise: false, + authenticationProvider: { id: 'microsoft', name: 'Microsoft', enterprise: false }, + }, + }); + const root = { + _meta: copilotEntraAuthenticationMeta(), + agents: [{ + provider: 'copilotcli', displayName: 'Copilot', description: '', models: [], + protectedResources: [{ resource: copilotEntraDiscoveryResource, authorization_servers: [copilotEntraAuthorizationServer], scopes_supported: ['User.Read'] }], + }], + }; + const requests = await resolver.resolve(root.agents, root); + assert.deepStrictEqual({ + tokens: requests.map(request => request.token), + registrations: state.queries.map(([, , options]) => options?.clientId), + accounts: state.queries.map(([, , options]) => options?.account?.id), + }, { + tokens: [microsoft.accessToken], + registrations: [copilotEntraClientId, copilotEntraClientId], + accounts: [undefined, microsoft.account.id], + }); + }); + test('does not mistake a declared provider still starting for a signed-out account', async () => { const { resolver, extensions, state } = fixture(); await extensions.complete(true); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostCustomizationHarness.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostCustomizationHarness.test.ts index bd00a0371887..f5547cd662c2 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostCustomizationHarness.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostCustomizationHarness.test.ts @@ -203,6 +203,8 @@ function createTestCustomAgentsService(connection: MockAgentConnection, rootCust getMcpServers(_sessionResource: URI) { return []; }, + getHostPermissions: () => undefined, + setHostPermissions: () => { }, addMcpServer(_sessionResource: URI, _name: string, _config) { // no-op }, diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.test.ts new file mode 100644 index 000000000000..d6e9800bc3e5 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.test.ts @@ -0,0 +1,431 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; +import { mock } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; +import type { IAgentHostGitHubEnvironmentStatus } from '../../../../../../platform/agentHost/common/meta/agentHostGitHubEnvironmentMeta.js'; +import { GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { IRemoteAgentHostConnectionInfo, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import type { InitializeResult } from '../../../../../../platform/agentHost/common/state/protocol/common/commands.js'; +import { IConfigurationChangeEvent } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { NullLogService } from '../../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../../platform/product/common/productService.js'; +import { InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; +import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticationService } from '../../../../../services/authentication/common/authentication.js'; +import { IChatEntitlementService } from '../../../../../services/chat/common/chatEntitlementService.js'; +import { RemoteGitHubEnvironmentSharingService } from '../../../browser/remoteAgentHost/remoteGitHubEnvironmentSharingService.js'; + +function initializeResult(): InitializeResult { + return { protocolVersion: '1.0.0', serverSeq: 0, snapshots: [] }; +} + +const sharesStorageKey = 'agentHost.remoteGitHubEnvironments.shared'; +const pendingUnregistrationsStorageKey = 'agentHost.remoteGitHubEnvironments.pendingUnregister'; + +suite('RemoteGitHubEnvironmentSharingService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function fixture(storage = store.add(new InMemoryStorageService())) { + const calls: string[] = []; + const connectionsChanged = store.add(new Emitter()); + const entriesChanged = store.add(new Emitter()); + const sessionsChanged = store.add(new Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }>()); + const configuration = new TestConfigurationService(); + store.add(configuration.onDidChangeConfigurationEmitter); + const remotes = new Map(); + let session: AuthenticationSession = { id: 'session', accessToken: 'token-1', account: { id: 'account', label: 'Account' }, scopes: [] }; + let signedIn = true; + let enabled = true; + + const remoteAgentHostService = new class extends mock() { + override readonly onDidChangeConnections = connectionsChanged.event; + override readonly onDidChangeConfiguredEntries = entriesChanged.event; + override get connections(): readonly IRemoteAgentHostConnectionInfo[] { + return [...remotes].map(([address, remote]) => ({ address, name: address, status: remote.connected ? RemoteAgentHostConnectionStatus.connected : RemoteAgentHostConnectionStatus.disconnected })); + } + override getConnection(address: string) { return remotes.get(address)?.connection; } + override getEntryByAddress(address: string): IRemoteAgentHostEntry | undefined { + return remotes.get(address)?.configured ? { name: address, connection: { type: RemoteAgentHostEntryType.WSL, address, distro: address } } : undefined; + } + }(); + const service = store.add(new RemoteGitHubEnvironmentSharingService( + remoteAgentHostService, + new class extends mock() { override get enabled() { return enabled; } }(), + new class extends mock() { override readonly available = observableValue('available', true); }(), + configuration, + new class extends mock() { override readonly onDidChangeSentiment = Event.None; }(), + new class extends mock() { + override readonly onDidChangeSessions = sessionsChanged.event; + override async getSessions() { return signedIn ? [session] : []; } + }(), + new class extends mock() { + override readonly onDidChangeDefaultAccount = Event.None; + override async getDefaultAccount() { return null; } + }(), + new class extends mock() { }(), + storage, + new NullLogService(), + )); + + return { + service, calls, storage, + addRemote(address: string, capable = true) { + let instance = 0; + let unregisterFails = false; + let held: { readonly started: DeferredPromise; readonly released: DeferredPromise } | undefined; + const initialize = observableValue('initializeResult', initializeResult()); + const status = observableValue('gitHubEnvironment', capable ? { instanceId: `${address}#0` } : undefined); + // Mirrors the agent host, which reports its new status before it responds. + const setStatus = (registration?: IAgentHostGitHubEnvironmentStatus['registration'], registeredByHost?: boolean) => status.set({ + instanceId: `${address}#${instance}`, + ...(registration ? { registration } : {}), + ...(registeredByHost ? { registeredByHost } : {}), + }, undefined); + const connection = new class extends mock() { + override readonly initializeResult = initialize; + override readonly gitHubEnvironment = status; + override async registerGitHubEnvironment(accountId: string, credential: string) { + calls.push(`register ${address} ${accountId} ${credential}`); + const current = held; + held = undefined; + if (current) { + current.started.complete(); + await current.released.p; + } + const registration = { accountId, environmentId: `environment-${address}`, name: address }; + setStatus(registration); + return { environmentId: registration.environmentId, name: registration.name }; + } + override async unregisterGitHubEnvironment(accountId: string) { + calls.push(`unregister ${address} ${accountId}${unregisterFails ? ' (failed)' : ''}`); + if (unregisterFails) { + throw new Error('Connection lost'); + } + if (status.get()?.registration?.accountId === accountId) { + setStatus(); + } + } + }(); + remotes.set(address, { configured: true, connected: true, connection }); + connectionsChanged.fire(); + entriesChanged.fire(); + return { + reconnect: () => initialize.set(initializeResult(), undefined), + restart: () => { + instance++; + setStatus(); + initialize.set(initializeResult(), undefined); + }, + /** Simulates another client registering or unregistering the remote. */ + setRegistration: (accountId: string | undefined) => setStatus(accountId ? { accountId, environmentId: `environment-${address}-${accountId}`, name: address } : undefined), + setRegisteredByHost: () => setStatus(undefined, true), + setConnected: (connected: boolean) => { remotes.get(address)!.connected = connected; connectionsChanged.fire(); }, + setConfigured: (configured: boolean) => { remotes.get(address)!.configured = configured; entriesChanged.fire(); }, + /** Holds the next registration request until it is released. */ + holdRegistration: () => { + held = { started: new DeferredPromise(), released: new DeferredPromise() }; + return held; + }, + setUnregisterFails: (fails: boolean) => { unregisterFails = fails; }, + }; + }, + changeAccount(accountId: string) { + session = { ...session, accessToken: `token-${accountId}`, account: { id: accountId, label: accountId } }; + sessionsChanged.fire({ providerId: 'github', label: 'GitHub', event: { added: [session], removed: undefined, changed: undefined } }); + }, + signOut() { + signedIn = false; + sessionsChanged.fire({ providerId: 'github', label: 'GitHub', event: { added: undefined, removed: [session], changed: undefined } }); + }, + setEnabled(value: boolean) { + enabled = value; + configuration.onDidChangeConfigurationEmitter.fire(new class extends mock() { + override affectsConfiguration(section: string) { return section === GitHubEnvironmentsEnabledSettingId; } + }()); + }, + async flush() { + await timeout(0); + // Queued behind any scheduled synchronization. + await service.setShared('flush', false); + }, + snapshot() { + return { + shareable: [...service.shareable.get()], + shares: Object.fromEntries(service.shares.get()), + environmentIds: [...service.environmentIds.get()], + }; + }, + stored(key = sharesStorageKey): unknown { + return JSON.parse(storage.get(key, StorageScope.APPLICATION, '{}')); + }, + }; + } + + test('shares connected remotes that support it, registers again after reconnecting and gating, and stops after an account change', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + context.addRemote('wsl:Debian', false); + await context.flush(); + const initial = context.snapshot(); + + await context.service.setShared('wsl:Ubuntu', true); + const shared = context.snapshot(); + const restored = fixture(context.storage).snapshot(); + + ubuntu.reconnect(); + await context.flush(); + context.setEnabled(false); + await context.flush(); + const gated = context.snapshot(); + context.setEnabled(true); + await context.flush(); + + context.changeAccount('other'); + await context.flush(); + + assert.deepStrictEqual({ initial, shared, restored, gated, final: context.snapshot(), calls: context.calls }, { + initial: { shareable: ['wsl:Ubuntu'], shares: {}, environmentIds: [] }, + shared: { shareable: ['wsl:Ubuntu'], shares: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu' } }, environmentIds: ['environment-wsl:Ubuntu'] }, + restored: { shareable: [], shares: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu' } }, environmentIds: [] }, + gated: { shareable: [], shares: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu' } }, environmentIds: ['environment-wsl:Ubuntu'] }, + final: { shareable: ['wsl:Ubuntu'], shares: {}, environmentIds: [] }, + calls: [ + 'register wsl:Ubuntu account token-1', + 'register wsl:Ubuntu account token-1', + 'unregister wsl:Ubuntu account', + 'register wsl:Ubuntu account token-1', + 'unregister wsl:Ubuntu account', + ], + }); + }); + + test('rejects sharing unavailable remotes and retries unsharing after the next connection', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + await context.flush(); + await context.service.setShared('wsl:Ubuntu', true); + + ubuntu.setConfigured(false); + const removedElsewhere = context.snapshot().environmentIds; + ubuntu.setConfigured(true); + ubuntu.setConnected(false); + const rejected = await context.service.setShared('wsl:Debian', true).then(() => 'shared', error => error.message); + await context.service.setShared('wsl:Ubuntu', false); + const unshared = context.snapshot(); + const callsWhileDisconnected = [...context.calls]; + + ubuntu.setConnected(true); + await context.flush(); + + assert.deepStrictEqual({ removedElsewhere, rejected, unshared, callsWhileDisconnected, calls: context.calls }, { + removedElsewhere: [], + rejected: 'Connect to this remote to share it as a GitHub environment.', + unshared: { shareable: [], shares: {}, environmentIds: [] }, + callsWhileDisconnected: ['register wsl:Ubuntu account token-1'], + calls: ['register wsl:Ubuntu account token-1', 'unregister wsl:Ubuntu account'], + }); + }); + + test('follows the registration the agent host reports', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + await context.flush(); + await context.service.setShared('wsl:Ubuntu', true); + + ubuntu.restart(); + await context.flush(); + const restarted = context.snapshot().shares; + + ubuntu.setRegistration(undefined); + await context.flush(); + const unsharedElsewhere = { shares: context.snapshot().shares, stored: context.stored() }; + + ubuntu.setRegistration('account'); + await context.flush(); + const sharedElsewhere = context.snapshot(); + await context.service.setShared('wsl:Ubuntu', false); + const stopped = context.snapshot().shares; + + await context.service.setShared('wsl:Ubuntu', true); + ubuntu.setRegistration('other'); + await context.flush(); + const otherAccount = { shares: context.snapshot().shares, stored: context.stored() }; + ubuntu.setRegisteredByHost(); + const byHost = context.snapshot().shares; + + assert.deepStrictEqual({ restarted, unsharedElsewhere, sharedElsewhere, stopped, otherAccount, byHost, calls: context.calls }, { + restarted: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu' } }, + unsharedElsewhere: { shares: {}, stored: {} }, + sharedElsewhere: { shareable: ['wsl:Ubuntu'], shares: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu-account' } }, environmentIds: ['environment-wsl:Ubuntu-account'] }, + stopped: {}, + otherAccount: { shares: { 'wsl:Ubuntu': { state: 'unavailable', unavailableReason: 'account' } }, stored: {} }, + byHost: { 'wsl:Ubuntu': { state: 'unavailable', unavailableReason: 'host' } }, + calls: [ + 'register wsl:Ubuntu account token-1', + 'register wsl:Ubuntu account token-1', + 'unregister wsl:Ubuntu account', + 'register wsl:Ubuntu account token-1', + ], + }); + }); + + test('adopts a share another window added before the registration is reported', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + const otherWindow = fixture(); + otherWindow.addRemote('wsl:Ubuntu'); + await context.flush(); + await otherWindow.flush(); + await otherWindow.service.setShared('wsl:Ubuntu', true); + + context.storage.store(sharesStorageKey, otherWindow.storage.get(sharesStorageKey, StorageScope.APPLICATION)!, StorageScope.APPLICATION, StorageTarget.MACHINE, true); + await context.flush(); + ubuntu.setRegistration('account'); + await context.flush(); + + assert.deepStrictEqual({ shares: context.snapshot().shares, stored: context.stored(), calls: context.calls }, { + shares: { 'wsl:Ubuntu': { state: 'enabled', environmentId: 'environment-wsl:Ubuntu-account' } }, + stored: { 'wsl:Ubuntu': { accountId: 'account', environmentId: 'environment-wsl:Ubuntu-account', instanceId: 'wsl:Ubuntu#0' } }, + calls: [], + }); + }); + + test('withdraws a share another window added while this window is disabled', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + context.setEnabled(false); + await context.flush(); + + ubuntu.setRegistration('account'); + context.storage.store(sharesStorageKey, JSON.stringify({ 'wsl:Ubuntu': { accountId: 'account', environmentId: 'environment-wsl:Ubuntu-account', instanceId: 'wsl:Ubuntu#0' } }), StorageScope.APPLICATION, StorageTarget.MACHINE, true); + await context.flush(); + + assert.deepStrictEqual({ stored: context.stored(), calls: context.calls }, { + stored: { 'wsl:Ubuntu': { accountId: 'account', environmentId: 'environment-wsl:Ubuntu-account' } }, + calls: ['unregister wsl:Ubuntu account'], + }); + }); + + test('registers again after a protocol reconnect and withdraws a registration the gate closed meanwhile', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + await context.flush(); + await context.service.setShared('wsl:Ubuntu', true); + + // A protocol reconnect keeps the handshake object. + ubuntu.setConnected(false); + ubuntu.setConnected(true); + await context.flush(); + + const held = ubuntu.holdRegistration(); + ubuntu.reconnect(); + await held.started.p; + context.setEnabled(false); + held.released.complete(); + // The completed registration schedules the withdrawal behind the first flush. + await context.flush(); + await context.flush(); + + assert.deepStrictEqual({ stored: context.stored(), calls: context.calls }, { + stored: { 'wsl:Ubuntu': { accountId: 'account', environmentId: 'environment-wsl:Ubuntu' } }, + calls: [ + 'register wsl:Ubuntu account token-1', + 'register wsl:Ubuntu account token-1', + 'register wsl:Ubuntu account token-1', + 'unregister wsl:Ubuntu account', + ], + }); + }); + + test('stops sharing after signing out and withdraws from disconnected remotes on their next connection', async () => { + const context = fixture(); + context.addRemote('wsl:Ubuntu'); + const debian = context.addRemote('wsl:Debian'); + await context.flush(); + await context.service.setShared('wsl:Ubuntu', true); + await context.service.setShared('wsl:Debian', true); + debian.setConnected(false); + + context.signOut(); + await context.flush(); + const signedOut = { shares: context.snapshot().shares, stored: context.stored(), pending: context.stored(pendingUnregistrationsStorageKey) }; + + debian.setConnected(true); + await context.flush(); + + assert.deepStrictEqual({ signedOut, pending: context.stored(pendingUnregistrationsStorageKey), calls: context.calls }, { + signedOut: { shares: {}, stored: {}, pending: { 'wsl:Debian': 'account' } }, + pending: {}, + calls: [ + 'register wsl:Ubuntu account token-1', + 'register wsl:Debian account token-1', + 'unregister wsl:Ubuntu account', + 'unregister wsl:Debian account', + ], + }); + }); + + test('retries stopping a share from another computer after the next connection', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + await context.flush(); + ubuntu.setRegistration('account'); + await context.flush(); + + ubuntu.setUnregisterFails(true); + await context.service.setShared('wsl:Ubuntu', false); + const failed = context.stored(pendingUnregistrationsStorageKey); + + ubuntu.setUnregisterFails(false); + ubuntu.setConnected(false); + ubuntu.setConnected(true); + await context.flush(); + + assert.deepStrictEqual({ failed, shares: context.snapshot().shares, pending: context.stored(pendingUnregistrationsStorageKey), calls: context.calls }, { + failed: { 'wsl:Ubuntu': 'account' }, + shares: {}, + pending: {}, + calls: ['unregister wsl:Ubuntu account (failed)', 'unregister wsl:Ubuntu account'], + }); + }); + + test('follows sharing changes other windows make during a registration', async () => { + const context = fixture(); + const ubuntu = context.addRemote('wsl:Ubuntu'); + const debian = context.addRemote('wsl:Debian'); + await context.flush(); + await context.service.setShared('wsl:Ubuntu', true); + + const held = ubuntu.holdRegistration(); + ubuntu.reconnect(); + await held.started.p; + // Another window stops sharing Ubuntu and defers withdrawing its Debian registration. + context.storage.remove(sharesStorageKey, StorageScope.APPLICATION, true); + debian.setRegistration('account'); + context.storage.store(pendingUnregistrationsStorageKey, JSON.stringify({ 'wsl:Debian': 'account' }), StorageScope.APPLICATION, StorageTarget.MACHINE, true); + held.released.complete(); + await context.flush(); + await context.flush(); + + assert.deepStrictEqual({ shares: context.snapshot().shares, stored: context.stored(), pending: context.stored(pendingUnregistrationsStorageKey), calls: context.calls }, { + shares: {}, + stored: {}, + pending: {}, + calls: [ + 'register wsl:Ubuntu account token-1', + 'register wsl:Ubuntu account token-1', + 'unregister wsl:Ubuntu account', + 'unregister wsl:Debian account', + ], + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsConfirmationService.test.ts b/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsConfirmationService.test.ts index 17253e0bea13..7c98c93dfb08 100644 --- a/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsConfirmationService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsConfirmationService.test.ts @@ -4,16 +4,21 @@ *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { observableValue, transaction } from '../../../../../../base/common/observable.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IConfigurationOverrides, IConfigurationValue, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IQuickInputHideEvent, IQuickInputService, IQuickTree, IQuickTreeItem, IQuickTreeItemButtonEvent, QuickInputHideReason } from '../../../../../../platform/quickinput/common/quickInput.js'; import { IStorageService, InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; import { LanguageModelToolsConfirmationService } from '../../../browser/tools/languageModelToolsConfirmationService.js'; import { ToolConfirmKind } from '../../../common/chatService/chatService.js'; import { ChatConfiguration } from '../../../common/constants.js'; -import { computeCombinationKey, ILanguageModelToolConfirmationActions, ILanguageModelToolConfirmationContribution, ILanguageModelToolConfirmationRef } from '../../../common/tools/languageModelToolsConfirmationService.js'; -import { ToolDataSource } from '../../../common/tools/languageModelToolsService.js'; +import { computeCombinationKey, ILanguageModelToolConfirmationActions, ILanguageModelToolConfirmationContribution, ILanguageModelToolConfirmationRef, IToolPreApprovalStore } from '../../../common/tools/languageModelToolsConfirmationService.js'; +import { IToolData, ToolDataSource } from '../../../common/tools/languageModelToolsService.js'; class PolicyTestConfigurationService extends TestConfigurationService { policyRestricted = false; @@ -72,6 +77,327 @@ suite('LanguageModelToolsConfirmationService', () => { }; } + test('manage actions that close the picker do not reopen it', async () => { + const onDidAccept = store.add(new Emitter()); + const onDidHide = store.add(new Emitter()); + let items: IQuickTreeItem[] = []; + let shown = 0; + const quickTree = upcastPartial>({ + get itemTree() { return items; }, + get activeItems() { return items[0].children!.filter(item => item.label === 'More Options...'); }, + buttons: [], + onDidChangeCheckboxState: Event.None, + onDidHide: onDidHide.event, + onDidTriggerItemButton: Event.None, + onDidTriggerButton: Event.None, + onDidAccept: onDidAccept.event, + setItemTree: value => { items = value; }, + isCollapsed: () => true, + show: () => { shown++; }, + hide: () => onDidHide.fire({ reason: QuickInputHideReason.Other }), + dispose: () => { }, + }); + instantiationService.stub(IQuickInputService, { createQuickTree: () => quickTree as IQuickTree }); + service = store.add(instantiationService.createInstance(LanguageModelToolsConfirmationService)); + let opened = 0; + store.add(service.registerConfirmationContribution('fetch', { + canUseDefaultApprovals: false, + getManageActions: () => [{ label: 'More Options...', pickable: false, closesPicker: true, onDidOpen: () => { opened++; } }], + })); + service.manageConfirmationPreferences([{ id: 'fetch', source: ToolDataSource.Internal, displayName: 'Fetch', modelDescription: '' }]); + onDidAccept.fire(); + await Promise.resolve(); + + assert.deepStrictEqual({ opened, shown }, { opened: 1, shown: 1 }); + }); + + test('manage external pre-approvals without reading or changing stored approvals', async () => { + const onDidChangeCheckboxState = store.add(new Emitter()); + const onDidHide = store.add(new Emitter()); + let items: IQuickTreeItem[] = []; + const focused: string[] = []; + const quickTree = upcastPartial>({ + get itemTree() { return items; }, + buttons: [], + busy: false, + onDidChangeCheckboxState: onDidChangeCheckboxState.event, + onDidHide: onDidHide.event, + onDidTriggerItemButton: Event.None, + onDidAccept: Event.None, + setItemTree: value => { items = value; }, + isCollapsed: () => true, + expand: item => { focused.push(item.label); }, + reveal: item => { focused.push(item.label); }, + show: () => { }, + dispose: () => { }, + }); + instantiationService.stub(IQuickInputService, { createQuickTree: () => quickTree as IQuickTree }); + service = store.add(instantiationService.createInstance(LanguageModelToolsConfirmationService)); + const ref = createMcpToolRef('mcpTool', 'server', 'Test Server'); + await service.getPreConfirmActions(ref).find(action => action.scope === 'workspace')!.select(); + const combinationRef = await createCombinationRef(ref.toolId, {}, 'Allow this combination'); + await service.getPreConfirmActions(combinationRef).find(action => action.scope === 'workspace')!.select(); + await service.getPostConfirmActions(ref).find(action => action.scope === 'workspace')!.select(); + const tool: IToolData = { id: ref.toolId, source: ref.source, displayName: 'Tool', modelDescription: '', canRequestPreApproval: true, canRequestPostApproval: true }; + let serverApproved = false; + let toolApproved = false; + const writes: [string, boolean][] = []; + const discoveredTools = observableValue('discoveredTools', []); + const isDiscovering = observableValue('isDiscovering', true); + const preApprovalStore: IToolPreApprovalStore = { + discoveredTools, + isDiscovering, + placeholder: 'Host approvals', + servers: [{ id: 'empty', label: 'Empty Server' }, { id: 'server', label: 'Test Server' }], + isServerApproved: () => serverApproved, + setServerApproved: (id, approved) => { serverApproved = approved; writes.push([id, approved]); }, + isToolApproved: () => toolApproved, + setToolApproved: (tool, approved) => { toolApproved = approved; writes.push([tool.id, approved]); }, + }; + store.add(service.registerConfirmationContribution('fetch', { + getManageActions: () => [{ label: 'Configure URLs' }], + })); + service.manageConfirmationPreferences([ + { id: 'fetch', source: ToolDataSource.Internal, displayName: 'Fetch', modelDescription: '', canRequestPreApproval: true }, + ], { preApprovalStore, focusToolId: tool.id }); + + const snapshot = (entries: readonly IQuickTreeItem[]): object[] => entries.map(item => ({ + id: item.id, + label: item.label, + type: (item as IQuickTreeItem & { type?: string }).type, + checked: item.checked, + pickable: item.pickable, + children: item.children ? snapshot(item.children) : [], + })); + const initial = { items: snapshot(items), busy: quickTree.busy, fetchCollapsed: items.find(item => item.id === 'tool/fetch')?.collapsed }; + transaction(tx => { + discoveredTools.set([tool], tx); + isDiscovering.set(false, tx); + }); + const discovered = { items: snapshot(items), busy: quickTree.busy }; + const server = items.find(item => item.label === 'Test Server')!; + const toolItem = server.children!.find(item => item.label === 'Tool')!; + onDidChangeCheckboxState.fire({ ...toolItem, checked: true }); + onDidChangeCheckboxState.fire({ ...toolItem, checked: false }); + const itemsAfterToggle = snapshot(items); + const storedPreApproval = service.getPreConfirmAction(ref); + onDidChangeCheckboxState.fire({ ...server, checked: true }); + onDidChangeCheckboxState.fire({ ...server, checked: false }); + const serverPre = items.find(item => item.label === 'Test Server')!.children![0]; + onDidChangeCheckboxState.fire({ ...serverPre, checked: true }); + configurationService.policyRestricted = true; + onDidChangeCheckboxState.fire({ ...server, checked: false }); + configurationService.policyRestricted = false; + onDidHide.fire({ reason: QuickInputHideReason.Other }); + + assert.deepStrictEqual({ initial, discovered, itemsAfterToggle, focused, writes, storedPreApproval, storedPostApproval: service.getPostConfirmAction(ref), buttons: quickTree.buttons, placeholder: quickTree.placeholder }, { + initial: { + items: [ + { + id: 'server/empty', label: 'Empty Server', type: 'server', checked: false, pickable: false, children: [ + { id: 'server-pre/empty', label: 'Run any tool without approval', type: 'server-pre', checked: false, pickable: undefined, children: [] }, + ] + }, + { + id: 'server/server', label: 'Test Server', type: 'server', checked: false, pickable: false, children: [ + { id: 'server-pre/server', label: 'Run any tool without approval', type: 'server-pre', checked: false, pickable: undefined, children: [] }, + ] + }, + { + id: 'tool/fetch', label: 'Fetch', type: 'tool', checked: false, pickable: false, children: [ + { id: 'manage/fetch/Configure URLs', label: 'Configure URLs', type: 'manage', checked: undefined, pickable: undefined, children: [] }, + ] + }, + ], + busy: true, + fetchCollapsed: true, + }, + discovered: { + items: [ + { + id: 'server/empty', label: 'Empty Server', type: 'server', checked: false, pickable: false, children: [ + { id: 'server-pre/empty', label: 'Run any tool without approval', type: 'server-pre', checked: false, pickable: undefined, children: [] }, + ] + }, + { + id: 'server/server', label: 'Test Server', type: 'server', checked: false, pickable: false, children: [ + { id: 'server-pre/server', label: 'Run any tool without approval', type: 'server-pre', checked: false, pickable: undefined, children: [] }, + { id: 'tool/mcpTool', label: 'Tool', type: 'tool', checked: false, pickable: undefined, children: [] }, + ] + }, + { + id: 'tool/fetch', label: 'Fetch', type: 'tool', checked: false, pickable: false, children: [ + { id: 'manage/fetch/Configure URLs', label: 'Configure URLs', type: 'manage', checked: undefined, pickable: undefined, children: [] }, + ] + }, + ], + busy: false, + }, + itemsAfterToggle: discovered.items, + focused: ['Test Server', 'Tool'], + writes: [['mcpTool', true], ['mcpTool', false], ['server', true], ['server', false], ['server', true]], + storedPreApproval: { type: ToolConfirmKind.LmServicePerTool, scope: 'workspace' }, + storedPostApproval: { type: ToolConfirmKind.LmServicePerTool, scope: 'workspace' }, + buttons: [], + placeholder: 'Host approvals', + }); + }); + + test('retains unchecked contribution rows until rechecked or deleted', async () => { + const onDidChangeCheckboxState = store.add(new Emitter()); + const onDidTriggerItemButton = store.add(new Emitter>()); + const onDidHide = store.add(new Emitter()); + const onDidSetItemTree = store.add(new Emitter()); + let items: IQuickTreeItem[] = []; + const quickTree = upcastPartial>({ + get itemTree() { return items; }, + onDidChangeCheckboxState: onDidChangeCheckboxState.event, + onDidTriggerItemButton: onDidTriggerItemButton.event, + onDidHide: onDidHide.event, + onDidAccept: Event.None, + setItemTree: value => { items = value; onDidSetItemTree.fire(); }, + show: () => { }, + dispose: () => { }, + }); + instantiationService.stub(IQuickInputService, { createQuickTree: () => quickTree as IQuickTree }); + service = store.add(instantiationService.createInstance(LanguageModelToolsConfirmationService)); + const deleteButton = { tooltip: 'Delete' }; + let rows = ['first', 'second']; + store.add(service.registerConfirmationContribution('testTool', { + canUseDefaultApprovals: false, + getManageActions: () => [ + ...rows.map(label => ({ + id: label === 'first' ? 'row/first' : undefined, + label, + checked: true, + buttons: [deleteButton], + onDidChangeChecked: async (checked: boolean) => { + await Promise.resolve(); + rows = checked ? [...rows, label] : rows.filter(row => row !== label); + }, + onDidTriggerItemButton: async () => { + await Promise.resolve(); + rows = rows.filter(row => row !== label); + }, + })), + { label: 'Add Row...', pickable: false }, + ], + })); + const tools: IToolData[] = [{ id: 'testTool', source: ToolDataSource.Internal, displayName: 'Tool', modelDescription: '' }]; + service.manageConfirmationPreferences(tools, { defaultScope: 'session' }); + + const snapshot = () => items[0].children!.map(item => [item.id, item.label, item.checked]); + const changeChecked = async (label: string, checked: boolean) => { + const updated = Event.toPromise(onDidSetItemTree.event); + onDidChangeCheckboxState.fire({ ...items[0].children!.find(item => item.label === label)!, checked }); + await updated; + }; + const remove = async (label: string) => { + const updated = Event.toPromise(onDidSetItemTree.event); + onDidTriggerItemButton.fire({ item: items[0].children!.find(item => item.label === label)!, button: deleteButton }); + await updated; + }; + const initial = snapshot(); + await changeChecked('first', false); + const unchecked = snapshot(); + await changeChecked('second', false); + const bothUnchecked = snapshot(); + await changeChecked('second', true); + await changeChecked('first', true); + const restored = snapshot(); + await remove('second'); + await changeChecked('first', false); + await remove('first'); + const deleted = snapshot(); + onDidHide.fire({ reason: QuickInputHideReason.Other }); + + assert.deepStrictEqual({ initial, unchecked, bothUnchecked, restored, deleted, rows }, { + initial: [ + ['manage/testTool/row/first', 'first', true], + ['manage/testTool/second', 'second', true], + ['manage/testTool/Add Row...', 'Add Row...', undefined], + ], + unchecked: [ + ['manage/testTool/row/first', 'first', false], + ['manage/testTool/second', 'second', true], + ['manage/testTool/Add Row...', 'Add Row...', undefined], + ], + bothUnchecked: [ + ['manage/testTool/row/first', 'first', false], + ['manage/testTool/second', 'second', false], + ['manage/testTool/Add Row...', 'Add Row...', undefined], + ], + restored: [ + ['manage/testTool/second', 'second', true], + ['manage/testTool/row/first', 'first', true], + ['manage/testTool/Add Row...', 'Add Row...', undefined], + ], + deleted: [['manage/testTool/Add Row...', 'Add Row...', undefined]], + rows: [], + }); + }); + + test('serializes contribution checkbox and button handlers before they read settings', async () => { + const onDidChangeCheckboxState = store.add(new Emitter()); + const onDidTriggerItemButton = store.add(new Emitter>()); + const onDidHide = store.add(new Emitter()); + const firstStarted = new DeferredPromise(); + const writeReady = new DeferredPromise(); + const rebuilt = new DeferredPromise(); + let items: IQuickTreeItem[] = []; + let rebuilds = 0; + const quickTree = upcastPartial>({ + get itemTree() { return items; }, + onDidChangeCheckboxState: onDidChangeCheckboxState.event, + onDidTriggerItemButton: onDidTriggerItemButton.event, + onDidHide: onDidHide.event, + onDidAccept: Event.None, + setItemTree: value => { + items = value; + if (++rebuilds === 3) { + void rebuilt.complete(); + } + }, + show: () => { }, + dispose: () => { }, + }); + instantiationService.stub(IQuickInputService, { createQuickTree: () => quickTree as IQuickTree }); + service = store.add(instantiationService.createInstance(LanguageModelToolsConfirmationService)); + let approvals: string[] = []; + const started: string[] = []; + const update = async (label: string) => { + const current = approvals; + started.push(label); + if (label === 'first') { + void firstStarted.complete(); + } + await writeReady.p; + approvals = [...current, label]; + }; + const deleteButton = { tooltip: 'Delete' }; + store.add(service.registerConfirmationContribution('testTool', { + canUseDefaultApprovals: false, + getManageActions: () => [ + { label: 'first', checked: false, onDidChangeChecked: () => update('first') }, + { label: 'second', buttons: [deleteButton], onDidTriggerItemButton: () => update('second') }, + ], + })); + service.manageConfirmationPreferences([{ id: 'testTool', source: ToolDataSource.Internal, displayName: 'Tool', modelDescription: '' }], { defaultScope: 'session' }); + onDidChangeCheckboxState.fire({ ...items[0].children![0], checked: true }); + onDidTriggerItemButton.fire({ item: items[0].children![1], button: deleteButton }); + await firstStarted.p; + const beforeWrite = { started: [...started], approvals }; + await writeReady.complete(); + await rebuilt.p; + onDidHide.fire({ reason: QuickInputHideReason.Other }); + + assert.deepStrictEqual({ beforeWrite, started, approvals }, { + beforeWrite: { started: ['first'], approvals: [] }, + started: ['first', 'second'], + approvals: ['first', 'second'], + }); + }); + test('getPreConfirmAction returns undefined by default', () => { const ref = createToolRef('testTool'); const result = service.getPreConfirmAction(ref); diff --git a/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsService.test.ts b/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsService.test.ts index 657cd451d025..718169b0b9f3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/tools/languageModelToolsService.test.ts @@ -8,6 +8,7 @@ import { Barrier, DeferredPromise } from '../../../../../../base/common/async.js import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; +import { autorun } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAccessibilityService } from '../../../../../../platform/accessibility/common/accessibility.js'; @@ -21,6 +22,7 @@ import { ContextKeyEqualsExpr, ContextKeyExpr, IContextKeyService } from '../../ import { IConfirmation, IConfirmationResult, IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; import { TestDialogService } from '../../../../../../platform/dialogs/test/common/testDialogService.js'; import { ExtensionIdentifier } from '../../../../../../platform/extensions/common/extensions.js'; +import { mcpAccessConfig, McpAccessValue } from '../../../../../../platform/mcp/common/mcpManagement.js'; import { ConfirmationOptionKind } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; @@ -30,7 +32,7 @@ import { IChatToolRiskAssessmentService, IToolRiskAssessment, ToolRiskLevel, Too import { ChatModel, IChatModel } from '../../../common/model/chatModel.js'; import { IChatService, IChatProgress, IChatInfoMessage, IChatToolInputInvocationData, IChatToolInvocation, ToolConfirmKind } from '../../../common/chatService/chatService.js'; import { ChatConfiguration, ChatPermissionLevel } from '../../../common/constants.js'; -import { SpecedToolAliases, isToolResultInputOutputDetails, IToolData, IToolImpl, IToolInvocation, ToolDataSource, IToolResultTextPart, ToolAndToolSetEnablementMap } from '../../../common/tools/languageModelToolsService.js'; +import { SpecedToolAliases, isToolResultInputOutputDetails, isToolSet, IToolData, IToolImpl, IToolInvocation, ToolDataSource, IToolResultTextPart, ToolAndToolSetEnablementMap } from '../../../common/tools/languageModelToolsService.js'; import { MockChatService } from '../../common/chatService/mockChatService.js'; import { ChatToolInvocation } from '../../../common/model/chatProgressTypes/chatToolInvocation.js'; import { LocalChatSessionUri } from '../../../common/model/chatUri.js'; @@ -180,6 +182,27 @@ class AutoApprovePolicyTestConfigurationService extends TestConfigurationService } } +class McpPolicyTestConfigurationService extends TestConfigurationService { + private mcpPolicyValue: McpAccessValue | undefined; + + setMcpPolicyValue(value: McpAccessValue | undefined): void { + this.mcpPolicyValue = value; + this.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === mcpAccessConfig, + affectedKeys: new Set([mcpAccessConfig]), + change: { keys: [mcpAccessConfig], overrides: [] }, + source: ConfigurationTarget.DEFAULT, + }); + } + + override inspect(key: string, overrides?: IConfigurationOverrides): IConfigurationValue { + const result = super.inspect(key, overrides); + return key === mcpAccessConfig + ? { ...result, policyValue: this.mcpPolicyValue as T | undefined } + : result; + } +} + interface TestToolsServiceSetup { configurationService: TestConfigurationService; chatService: MockChatService; @@ -4501,6 +4524,299 @@ suite('LanguageModelToolsService', () => { assert.deepStrictEqual(tool.models[1], { vendor: 'anthropic', family: 'claude-3' }); }); + suite('MCP enterprise policy for extension tools', () => { + const extensionSource: ToolDataSource = { + type: 'extension', label: 'Test Extension', extensionId: new ExtensionIdentifier('test.extension'), + }; + const policyError = /disabled because your organization has disabled MCP and third-party extension tools/; + + test('only policy none filters extension tools and reactively updates tools and toolsets', () => { + const config = new McpPolicyTestConfigurationService({ [mcpAccessConfig]: McpAccessValue.None }); + const { service } = createTestToolsService(store, { configurationService: config }); + for (const [id, source] of [ + ['extensionTool', extensionSource], + ['internalTool', ToolDataSource.Internal], + ['mcpTool', { type: 'mcp', label: 'MCP', serverLabel: 'MCP', instructions: undefined, collectionId: 'collection', definitionId: 'server' }], + ] satisfies [string, ToolDataSource][]) { + store.add(service.registerToolData({ id, source, displayName: id, modelDescription: id })); + } + store.add(service.createToolSet(extensionSource, 'extensionSet', 'extensionSet')); + service.flushToolUpdates(); + const observedTools: string[][] = []; + const observedToolSets: string[][] = []; + const tools = service.observeTools(undefined); + store.add(autorun(reader => { + observedTools.push(tools.read(reader).map(tool => tool.id)); + })); + store.add(autorun(reader => { + observedToolSets.push(Array.from(service.toolSets.read(reader), toolSet => toolSet.id)); + })); + const snapshots = []; + for (const policyValue of [undefined, McpAccessValue.Registry, McpAccessValue.None, undefined]) { + config.setMcpPolicyValue(policyValue); + service.flushToolUpdates(); + snapshots.push(Array.from(service.getAllToolsIncludingDisabled(), tool => tool.id)); + } + + const enabledTools = ['extensionTool', 'internalTool', 'mcpTool']; + const disabledTools = ['internalTool', 'mcpTool']; + const internalToolSets = ['vscode', 'execute', 'read', 'agent']; + const enabledToolSets = [...internalToolSets, 'extensionSet']; + assert.deepStrictEqual({ snapshots, observedTools, observedToolSets }, { + snapshots: [enabledTools, enabledTools, disabledTools, enabledTools], + observedTools: [enabledTools, disabledTools, enabledTools], + observedToolSets: [enabledToolSets, internalToolSets, enabledToolSets], + }); + }); + + test('rejects streaming calls during policy refresh before observable listeners update', () => { + const config = new McpPolicyTestConfigurationService(); + const { service } = createTestToolsService(store, { configurationService: config }); + const effects: string[] = []; + const tool = registerToolForTest(service, store, 'extensionTool', { + handleToolStream: async () => { effects.push('stream'); return undefined; }, + invoke: async () => ({ content: [] }), + }, { source: extensionSource }); + store.add(service.createToolSet(extensionSource, 'extensionSet', 'extensionSet')); + let errorMessage: string | undefined; + let invocationCreated = false; + store.add(config.onDidChangeConfiguration(() => { + try { + invocationCreated = !!service.beginToolCall({ toolCallId: 'stream', toolId: tool.id }); + } catch (error) { + errorMessage = error instanceof Error ? error.message : String(error); + } + })); + store.add(autorun(reader => { + service.toolSets.read(reader); + })); + + config.setMcpPolicyValue(McpAccessValue.None); + + assert.deepStrictEqual({ + blocked: policyError.test(errorMessage ?? ''), + invocationCreated, + effects, + }, { + blocked: true, + invocationCreated: false, + effects: [], + }); + }); + + test('toolsets and references cannot reenable prohibited extension members', () => { + const config = new McpPolicyTestConfigurationService(); + config.setMcpPolicyValue(McpAccessValue.None); + const { service } = createTestToolsService(store, { configurationService: config }); + const extensionTool: IToolData = { + id: 'extensionTool', source: extensionSource, displayName: 'Extension Tool', modelDescription: 'Extension Tool', + toolReferenceName: 'extensionTool', canBeReferencedInPrompt: true, + }; + const internalTool: IToolData = { + id: 'internalTool', source: ToolDataSource.Internal, displayName: 'Internal Tool', modelDescription: 'Internal Tool', + toolReferenceName: 'internalTool', canBeReferencedInPrompt: true, + }; + store.add(service.registerToolData(extensionTool)); + store.add(service.registerToolData(internalTool)); + const extensionSet = store.add(service.createToolSet(extensionSource, 'extensionSet', 'extensionSet')); + const userSet = store.add(service.createToolSet({ + type: 'user', label: 'User Tools', file: URI.file('/tools.json'), + }, 'userSet', 'userSet')); + store.add(extensionSet.addTool(extensionTool)); + store.add(service.readToolSet.addTool(extensionTool)); + store.add(service.readToolSet.addTool(internalTool)); + store.add(userSet.addToolSet(extensionSet)); + store.add(userSet.addTool(internalTool)); + const selection = service.toToolAndToolSetEnablementMap([ + 'read', 'extensionSet', 'read/extensionTool', 'extensionSet/extensionTool', + ], undefined); + const model = { id: 'test-model', vendor: 'test', family: 'test', version: '1' } as ILanguageModelChatMetadata; + const readToolSets = [undefined, model].map(model => + Array.from(service.getToolSetsForModel(model)).find(toolSet => toolSet.id === 'read')); + + assert.deepStrictEqual({ + extensionReferences: ['read/extensionTool', 'extensionSet/extensionTool', 'test.extension/extensionTool'].map(name => service.getToolByFullReferenceName(name)), + enabledTools: Array.from(selection).filter(([tool, enabled]) => !isToolSet(tool) && enabled).map(([tool]) => tool.id), + extensionSetSelected: selection.has(extensionSet), + extensionMembers: Array.from(extensionSet.getTools(), tool => tool.id), + userMembers: Array.from(userSet.getTools(), tool => tool.id), + modelMembers: readToolSets.map(toolSet => Array.from(toolSet?.getTools() ?? [], tool => tool.id)), + }, { + extensionReferences: [undefined, undefined, undefined], + enabledTools: ['internalTool'], + extensionSetSelected: false, + extensionMembers: [], + userMembers: ['internalTool'], + modelMembers: [['internalTool'], ['internalTool']], + }); + }); + + test('rejects direct calls before activation or preparation while preserving internal tools and policy removal', async () => { + const config = new McpPolicyTestConfigurationService({ [mcpAccessConfig]: McpAccessValue.None }); + config.setMcpPolicyValue(McpAccessValue.None); + const effects: string[] = []; + const { service } = createTestToolsService(store, { + configurationService: config, + extensionService: { activateByEvent: async () => { effects.push('activate'); } }, + }); + store.add(service.registerToolData({ + id: 'lazyExtensionTool', source: extensionSource, displayName: 'Lazy Tool', modelDescription: 'Lazy Tool', + })); + const extensionTool = registerToolForTest(service, store, 'extensionTool', { + prepareToolInvocation: async () => { effects.push('prepare'); return undefined; }, + invoke: async () => { effects.push('extensionInvoke'); return { content: [] }; }, + handleToolStream: async () => { effects.push('stream'); return undefined; }, + }, { source: extensionSource }); + const internalTool = registerToolForTest(service, store, 'internalTool', { + invoke: async () => { effects.push('internalInvoke'); return { content: [] }; }, + }); + + for (const toolId of ['lazyExtensionTool', extensionTool.id]) { + await assert.rejects(service.invokeTool({ + callId: toolId, toolId, parameters: {}, context: undefined, + }, async () => 0, CancellationToken.None), policyError); + } + assert.throws(() => service.beginToolCall({ toolCallId: 'stream', toolId: extensionTool.id }), policyError); + await service.invokeTool(internalTool.makeDto({}), async () => 0, CancellationToken.None); + config.setMcpPolicyValue(undefined); + await service.invokeTool(extensionTool.makeDto({}), async () => 0, CancellationToken.None); + service.beginToolCall({ toolCallId: 'stream', toolId: extensionTool.id }); + config.setMcpPolicyValue(McpAccessValue.None); + await assert.rejects(service.updateToolStream('stream', {}, CancellationToken.None), policyError); + assert.deepStrictEqual(effects, ['internalInvoke', 'prepare', 'extensionInvoke', 'stream']); + }); + + for (const useStreamAlias of [false, true]) { + test(`cancels a policy-denied pending invocation matched by ${useStreamAlias ? 'stream alias' : 'call id'}`, async () => { + const config = new McpPolicyTestConfigurationService(); + const { service, chatService } = createTestToolsService(store, { configurationService: config }); + const owner = LocalChatSessionUri.forSession('policy-owner'); + stubGetSession(chatService, 'policy-owner'); + const effects: string[] = []; + const tool = registerToolForTest(service, store, 'extensionTool', { + handleToolStream: async () => { effects.push('stream'); return undefined; }, + invoke: async () => { effects.push('invoke'); return { content: [] }; }, + }, { source: extensionSource, sessionResource: owner }); + const invocation = service.beginToolCall({ + toolId: tool.id, toolCallId: 'stream', toolSessionResource: owner, sessionResource: owner, + }); + config.setMcpPolicyValue(McpAccessValue.None); + + await assert.rejects(service.invokeTool({ + ...tool.makeDto({}, { sessionId: 'policy-owner' }, useStreamAlias ? 'invoke' : 'stream'), + chatStreamToolCallId: useStreamAlias ? 'stream' : undefined, + toolSessionResource: owner, + }, async () => 0, CancellationToken.None), policyError); + config.setMcpPolicyValue(undefined); + await service.updateToolStream('stream', {}, CancellationToken.None); + + const state = invocation?.state.get(); + assert.deepStrictEqual({ + state: state?.type, + reason: state?.type === IChatToolInvocation.StateKind.Cancelled ? state.reason : undefined, + hasPolicyReason: state?.type === IChatToolInvocation.StateKind.Cancelled && typeof state.reasonMessage === 'string' && policyError.test(state.reasonMessage), + effects, + }, { + state: IChatToolInvocation.StateKind.Cancelled, + reason: ToolConfirmKind.Denied, + hasPolicyReason: true, + effects: ['stream'], + }); + }); + } + + test('policy denial cannot cancel a pending call owned by another tool or session', async () => { + const config = new McpPolicyTestConfigurationService(); + const { service } = createTestToolsService(store, { configurationService: config }); + const owner = LocalChatSessionUri.forSession('policy-owner'); + const other = LocalChatSessionUri.forSession('other-session'); + const effects: string[] = []; + const tool = registerToolForTest(service, store, 'extensionTool', { + handleToolStream: async () => { effects.push('stream'); return undefined; }, + invoke: async () => ({ content: [] }), + }, { source: extensionSource, sessionResource: owner }); + registerToolForTest(service, store, 'otherTool', { + invoke: async () => ({ content: [] }), + }, { source: extensionSource, sessionResource: owner }); + const invocation = service.beginToolCall({ + toolId: tool.id, toolCallId: 'stream', toolSessionResource: owner, sessionResource: owner, + }); + config.setMcpPolicyValue(McpAccessValue.None); + const states = []; + for (const scenario of [ + { toolId: 'otherTool', callId: 'stream', scope: owner, presentation: owner, error: policyError }, + { toolId: tool.id, callId: 'stream', scope: other, presentation: owner, error: /not available in this session/ }, + { toolId: tool.id, callId: 'stream', scope: owner, presentation: other, error: policyError }, + { toolId: tool.id, callId: 'other-call', scope: owner, presentation: owner, error: policyError }, + ]) { + await assert.rejects(service.invokeTool({ + callId: scenario.callId, toolId: scenario.toolId, parameters: {}, + toolSessionResource: scenario.scope, context: { sessionResource: scenario.presentation }, + }, async () => 0, CancellationToken.None), scenario.error); + states.push(invocation?.state.get().type); + } + config.setMcpPolicyValue(undefined); + await service.updateToolStream('stream', {}, CancellationToken.None); + assert.deepStrictEqual({ states, effects }, { + states: Array(4).fill(IChatToolInvocation.StateKind.Streaming), + effects: ['stream', 'stream'], + }); + }); + + for (const phase of ['activation', 'preparation']) { + test(`rechecks policy after asynchronous ${phase}`, async () => { + const config = new McpPolicyTestConfigurationService(); + const entered = new DeferredPromise(); + const resume = new DeferredPromise(); + const effects: string[] = []; + const { service } = createTestToolsService(store, { + configurationService: config, + extensionService: { + activateByEvent: async () => { + effects.push('activate'); + entered.complete(); + await resume.p; + }, + }, + }); + const toolData: IToolData = { + id: 'extensionTool', source: extensionSource, displayName: 'Extension Tool', modelDescription: 'Extension Tool', + }; + const implementation: IToolImpl = { + prepareToolInvocation: async () => { + effects.push('prepare'); + entered.complete(); + await resume.p; + return undefined; + }, + invoke: async () => { effects.push('invoke'); return { content: [] }; }, + }; + store.add(service.registerToolData(toolData)); + if (phase === 'preparation') { + store.add(service.registerToolImplementation(toolData.id, implementation)); + } + const pendingInvocation = phase === 'activation' + ? service.beginToolCall({ toolId: toolData.id, toolCallId: 'call', force: true }) + : undefined; + const result = service.invokeTool({ + callId: 'call', toolId: toolData.id, parameters: {}, context: undefined, + }, async () => 0, CancellationToken.None); + const rejected = assert.rejects(result, policyError); + await entered.p; + config.setMcpPolicyValue(McpAccessValue.None); + if (phase === 'activation') { + store.add(service.registerToolImplementation(toolData.id, implementation)); + } + await resume.complete(); + await rejected; + assert.deepStrictEqual({ effects, pendingState: pendingInvocation?.state.get().type }, { + effects: [phase === 'activation' ? 'activate' : 'prepare'], + pendingState: phase === 'activation' ? IChatToolInvocation.StateKind.Cancelled : undefined, + }); + }); + } + }); + test('tools with extension tools disabled setting are filtered', () => { // Create a tool from an extension const extensionTool: IToolData = { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatAttachmentsContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatAttachmentsContentPart.test.ts index c8a7702afb77..8762a1294be6 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatAttachmentsContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatAttachmentsContentPart.test.ts @@ -4,19 +4,38 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import sinon from 'sinon'; +import { timeout } from '../../../../../../../base/common/async.js'; import * as dom from '../../../../../../../base/browser/dom.js'; +import { isManagedHoverTooltipHTMLElement } from '../../../../../../../base/browser/ui/hover/hover.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; +import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../../../../base/common/event.js'; +import { MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { Disposable, DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../../../base/common/uri.js'; +import { observableValue } from '../../../../../../../base/common/observable.js'; import { ExtensionIdentifier } from '../../../../../../../platform/extensions/common/extensions.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { runWithFakedTimers } from '../../../../../../../base/test/common/timeTravelScheduler.js'; +import { IConfigurationService } from '../../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { HoverService } from '../../../../../../../platform/hover/browser/hoverService.js'; +import { ILayoutService } from '../../../../../../../platform/layout/browser/layoutService.js'; import { IFileService } from '../../../../../../../platform/files/common/files.js'; -import { IHoverService } from '../../../../../../../platform/hover/browser/hover.js'; +import { IHoverService, WorkbenchHoverDelegate } from '../../../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../../../platform/hover/test/browser/nullHoverService.js'; import { ILabelService } from '../../../../../../../platform/label/common/label.js'; import { TestFileService, workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../../../../browser/labels.js'; -import { ImageAttachmentWidget } from '../../../../browser/attachments/chatAttachmentWidgets.js'; +import { DefaultChatAttachmentWidget, ImageAttachmentWidget } from '../../../../browser/attachments/chatAttachmentWidgets.js'; +import { getGitHubIssueOrPullRequestAttachments } from '../../../../browser/widget/input/editor/chatPasteProviders.js'; +import { GitHubResourceDetailsResolver, LazyGitHubResourceState } from '../../../../../github/browser/githubResourceDetails.js'; +import { IGitHubIssueHoverModel } from '../../../../../github/browser/githubResourceHover.js'; +import { IWorkbenchGitHubService } from '../../../../../../services/github/common/githubService.js'; +import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; +import { IClipboardService } from '../../../../../../../platform/clipboard/common/clipboardService.js'; +import { IOpenerService } from '../../../../../../../platform/opener/common/opener.js'; import { ChatAttachmentsContentPart } from '../../../../browser/widget/chatContentParts/chatAttachmentsContentPart.js'; import { AgentHostCompletionReferenceKind, IChatRequestVariableEntry, OmittedState, toAgentHostCompletionVariableEntry } from '../../../../common/attachments/chatVariableEntries.js'; import { ILanguageModelChatMetadata, ILanguageModelsService } from '../../../../common/languageModels.js'; @@ -29,12 +48,273 @@ suite('ChatAttachmentsContentPart', () => { setup(() => { disposables = store.add(new DisposableStore()); instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IWorkbenchGitHubService, upcastPartial({ onDidChangeDefaultClient: Event.None })); }); teardown(() => { + sinon.restore(); disposables.dispose(); }); + suite('GitHub attachment previews', () => { + for (const delay of [500, 700]) { + test(`pointer previews use the configured ${delay}ms delay and replace the previous reference`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = dom.append(document.body, dom.$('div')); + disposables.add(toDisposable(() => fixture.remove())); + instantiationService.stub(IConfigurationService, new TestConfigurationService({ 'workbench.hover.delay': delay })); + instantiationService.stub(ILayoutService, { + activeContainer: fixture, + mainContainer: fixture, + getContainer: () => fixture, + onDidLayoutContainer: Event.None, + }); + const hoverService = disposables.add(instantiationService.createInstance(HoverService)); + disposables.add(toDisposable(() => hoverService.hideHover(true))); + instantiationService.stub(IHoverService, hoverService); + // Fake time starts inside the delegate's instant-hover grace period. + await timeout(1000); + const hoverDelegate = disposables.add(instantiationService.createInstance(WorkbenchHoverDelegate, 'element', { instantHover: true }, {})); + const previews = [dom.$('div', undefined, 'First reference'), dom.$('div', undefined, 'Second reference')]; + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover').callsFake((_identity, options) => ({ + hover: { content: () => dom.$('div', undefined, 'Keyboard details') }, + pillHover: { element: () => previews[options.target.number - 1], contentOwnsPadding: true }, + prefetch: () => { }, + })); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const widgets = [1, 2].map(number => disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, getGitHubIssueOrPullRequestAttachments(`https://github.com/microsoft/vscode/issues/${number}`)[0], undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true, hoverDelegate }, dom.append(fixture, dom.$('.chat-inline-attachment')), labels))); + widgets[0].element.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + await timeout(delay - 1); + const beforeDeadline = previews[0].isConnected; + const resolvedBeforeDeadline = createHover.callCount; + await timeout(1); + const firstShown = previews[0].isConnected; + const contentOwnsPadding = !!previews[0].closest('.managed-hover-content-owns-padding'); + widgets[0].element.dispatchEvent(new MouseEvent('mouseleave')); + widgets[1].element.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + await timeout(0); + const secondShownForPointer = previews[1].isConnected; + widgets[1].element.dispatchEvent(new MouseEvent('mouseleave')); + const focusedElement = dom.getActiveElement(); + widgets[0].previewHover?.show(false); + await timeout(0); + const keyboardShown = previews[0].isConnected; + const keyboardPreservedFocus = dom.getActiveElement() === focusedElement; + widgets[1].element.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + await timeout(0); + assert.deepStrictEqual({ + beforeDeadline, + resolvedBeforeDeadline, + firstShown, + contentOwnsPadding, + secondShownForPointer, + keyboardShown, + keyboardPreservedFocus, + firstDismissed: !previews[0].isConnected, + secondShown: previews[1].isConnected, + }, { beforeDeadline: false, resolvedBeforeDeadline: 0, firstShown: true, contentOwnsPadding: true, secondShownForPointer: true, keyboardShown: true, keyboardPreservedFocus: true, firstDismissed: true, secondShown: true }); + })); + } + + test('keeps the shared resolver cache across attachment widget recreation', async () => { + const resolver = disposables.add(instantiationService.createInstance(GitHubResourceDetailsResolver)); + const state = observableValue>(resolver, { status: 'idle' }); + const issue: IGitHubIssueHoverModel = { + title: 'Cached issue', + body: 'Real details', + state: 'open', + author: { login: 'octocat' }, + createdAt: '2026-11-03T00:00:00Z', + }; + sinon.stub(resolver, 'getIssueState').returns(state); + sinon.stub(resolver, 'isFresh').callsFake(() => state.get().status === 'resolved'); + const resolve = sinon.stub(resolver, 'resolveIssue').callsFake(async () => { + state.set({ status: 'resolved', value: issue }, undefined); + return issue; + }); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const attachment = getGitHubIssueOrPullRequestAttachments('https://github.com/microsoft/vscode/issues/123')[0]; + const createWidget = () => disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, attachment, undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true, gitHubResourceDetailsResolver: resolver }, dom.$('.chat-inline-attachment'), labels)); + const first = createWidget(); + const loading = first.getPreviewHoverContent(); + const firstFallback = loading?.textContent; + await timeout(0); + first.dispose(); + const second = createWidget(); + const cached = second.getPreviewHoverContent(); + let pointerContent: Promise | undefined; + instantiationService.stub(IHoverService, { + ...NullHoverService, + setupManagedHover: (delegate, target, content) => { + const resolved = typeof content === 'function' ? content() : content; + assert.ok(isManagedHoverTooltipHTMLElement(resolved)); + pointerContent = Promise.resolve(resolved.element(CancellationToken.None)); + return NullHoverService.setupManagedHover(delegate, target, content); + }, + }); + const pointerWidget = createWidget(); + const pointer = await pointerContent; + assert.deepStrictEqual({ + firstFallback, + resolvedTitle: cached?.querySelector('.sessions-issue-hover-title')?.textContent?.replace(/\s+/g, ' ').trim(), + requests: resolve.callCount, + independentViews: pointer !== cached, + pointerTitle: pointer?.querySelector('.sessions-issue-hover-title')?.textContent?.replace(/\s+/g, ' ').trim(), + }, { firstFallback: 'Issue #123', resolvedTitle: 'Cached issue #123', requests: 1, independentViews: true, pointerTitle: 'Cached issue #123' }); + pointerWidget.dispose(); + }); + + for (const [path, kind] of [['issues', 'issue'], ['pull', 'pullRequest']] as const) { + test(`provides the lazy ${kind} preview only to inline attachments`, async () => { + const preview = dom.$('div', undefined, 'Preview title and status'); + const render = sinon.spy(() => preview); + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover').returns({ + hover: { content: render }, + pillHover: { element: render }, + prefetch: () => assert.fail('Attachments must not prefetch details'), + }); + let pointerRegistrations = 0; + instantiationService.stub(IHoverService, { + ...NullHoverService, + setupManagedHover: (delegate, target, content) => { + pointerRegistrations++; + return NullHoverService.setupManagedHover(delegate, target, content); + }, + }); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const attachment = getGitHubIssueOrPullRequestAttachments(`https://github.com/microsoft/vscode/${path}/123`)[0]; + const copied: string[] = []; + const opened: { resource: string; options: Parameters[1] }[] = []; + instantiationService.stub(IClipboardService, upcastPartial({ writeText: async text => { copied.push(text); } })); + instantiationService.stub(IOpenerService, upcastPartial({ + open: async (resource, options) => { + opened.push({ resource: resource.toString(), options }); + return true; + }, + })); + const widget = disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, attachment, undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true }, dom.$('.chat-inline-attachment'), labels)); + assert.deepStrictEqual({ + createdAtRest: createHover.callCount, + renderedAtRest: render.callCount, + label: widget.label.element.textContent?.trim(), + pointerRegistrations, + }, { + createdAtRest: 0, + renderedAtRest: 0, + label: 'microsoft/vscode#123', + pointerRegistrations: 1, + }); + const keyboardContent = widget.getPreviewHoverContent(); + assert.deepStrictEqual({ + kind: createHover.firstCall.args[1].kind, + target: createHover.firstCall.args[1].target, + keyboardContent, + supportsPreview: widget.supportsPreview, + }, { + kind, + target: { owner: 'microsoft', repo: 'vscode', number: 123 }, + keyboardContent: preview, + supportsPreview: true, + }); + createHover.lastCall.args[1].onDidClickBaseBranch('main'); + createHover.lastCall.args[1].onDidClickHeadBranch('feature/preview'); + createHover.lastCall.args[1].onDidClickReference(); + assert.deepStrictEqual({ copied, opened }, { + copied: ['main', 'feature/preview'], + opened: [{ resource: `https://github.com/microsoft/vscode/${path}/123`, options: { openExternal: true } }], + }); + opened.length = 0; + widget.element.click(); + await timeout(0); + assert.deepStrictEqual(opened.map(item => item.resource), [`https://github.com/microsoft/vscode/${path}/123`]); + widget.dispose(); + }); + + test(`preserves the ordinary non-inline ${kind} attachment tooltip`, () => { + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover'); + let tooltipRegistrations = 0; + instantiationService.stub(IHoverService, { + ...NullHoverService, + setupDelayedHover: () => { + tooltipRegistrations++; + return toDisposable(() => { }); + }, + }); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const attachment = getGitHubIssueOrPullRequestAttachments(`https://github.com/microsoft/vscode/${path}/123`)[0]; + assert.ok(attachment.kind === 'generic'); + const widget = disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, { ...attachment, tooltip: new MarkdownString('Existing reference tooltip') }, undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true }, dom.$('div'), labels)); + assert.deepStrictEqual({ + supportsPreview: widget.supportsPreview, + preview: widget.getPreviewHoverContent(), + enrichmentCalls: createHover.callCount, + tooltipRegistrations, + }, { supportsPreview: false, preview: undefined, enrichmentCalls: 0, tooltipRegistrations: 1 }); + }); + } + + for (const id of [ + 'ordinary', + 'github-context:https://github.com/microsoft/vscode/pull/0', + 'github-context:https://github.com/microsoft/vscode/pull/not-a-number', + 'github-context:https://github.com/microsoft/vscode/discussions/123', + 'github-context:https://example.com/microsoft/vscode/pull/123', + 'github-context:https://example.com/artifact/123', + ]) { + test(`does not preview an unsupported reference: ${id}`, () => { + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover'); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const widget = disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, { kind: 'generic', id, name: 'Reference', value: id }, undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true }, dom.$('.chat-inline-attachment'), labels)); + assert.deepStrictEqual({ + supportsPreview: widget.supportsPreview, + preview: widget.getPreviewHoverContent(), + popup: widget.element.getAttribute('aria-haspopup'), + requested: createHover.callCount, + }, { supportsPreview: false, preview: undefined, popup: null, requested: 0 }); + }); + } + + test('invalidates old-account content and reacquires the preview on reopening', () => { + const changed = disposables.add(new Emitter()); + instantiationService.stub(IWorkbenchGitHubService, upcastPartial({ onDidChangeDefaultClient: changed.event })); + const oldContent = dom.$('div'); + const freshContent = dom.$('div', undefined, 'New account details'); + const hide = sinon.spy(); + instantiationService.stub(IHoverService, { + ...NullHoverService, + setupManagedHover: (delegate, target, content) => ({ ...NullHoverService.setupManagedHover(delegate, target, content), hide }), + }); + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover'); + createHover.onFirstCall().returns({ hover: { content: () => oldContent }, pillHover: { element: () => oldContent }, prefetch: () => { } }); + createHover.onSecondCall().returns({ hover: { content: () => freshContent }, pillHover: { element: () => freshContent }, prefetch: () => { } }); + const labels = disposables.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const widget = disposables.add(instantiationService.createInstance(DefaultChatAttachmentWidget, + undefined, undefined, getGitHubIssueOrPullRequestAttachments('https://github.com/microsoft/vscode/pull/123')[0], undefined, undefined, + { shouldFocusClearButton: false, supportsDeletion: true }, dom.$('.chat-inline-attachment'), labels)); + widget.getPreviewHoverContent(); + let invalidated = 0; + disposables.add(widget.onDidChangePreview(() => { + invalidated++; + })); + changed.fire(); + assert.deepStrictEqual({ + freshContent: widget.getPreviewHoverContent() === freshContent, + invalidated, + hidden: hide.calledOnce, + }, { freshContent: true, invalidated: 1, hidden: true }); + }); + + }); + function createFileEntry(name: string, uri?: URI): IChatRequestVariableEntry { const fileUri = uri ?? URI.file(`/test/${name}`); return { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts index 3e76405058a4..49272c8c0d31 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatMarkdownContentPart.test.ts @@ -6,10 +6,11 @@ import assert from 'assert'; import { spy, stub } from 'sinon'; import { DeferredPromise, timeout } from '../../../../../../../base/common/async.js'; +import { IAction, Separator } from '../../../../../../../base/common/actions.js'; import { decodeBase64, encodeBase64, VSBuffer } from '../../../../../../../base/common/buffer.js'; import { addDisposableListener, scheduleAtNextAnimationFrame } from '../../../../../../../base/browser/dom.js'; import { DomScrollableElement } from '../../../../../../../base/browser/ui/scrollbar/scrollableElement.js'; -import { Event } from '../../../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { observableValue } from '../../../../../../../base/common/observable.js'; @@ -30,14 +31,20 @@ import { IConfigurationService } from '../../../../../../../platform/configurati import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IMarkdownRenderer, MarkdownRendererService } from '../../../../../../../platform/markdown/browser/markdownRenderer.js'; import { BrowserResourceService } from '../../../../../../../platform/files/browser/browserResourceService.js'; -import { IOpenerService } from '../../../../../../../platform/opener/common/opener.js'; +import { IOpenerService, OpenOptions } from '../../../../../../../platform/opener/common/opener.js'; +import { IFileDialogService } from '../../../../../../../platform/dialogs/common/dialogs.js'; +import { IEditorOptions } from '../../../../../../../platform/editor/common/editor.js'; +import { AccessibleViewType } from '../../../../../../../platform/accessibility/browser/accessibleView.js'; +import { ContextKeyService } from '../../../../../../../platform/contextkey/browser/contextKeyService.js'; import { AGENT_HOST_SCHEME, toAgentHostUri } from '../../../../../../../platform/agentHost/common/agentHostUri.js'; import { AgentHostFileSystemProvider, IRemoteFilesystemConnection } from '../../../../../../../platform/agentHost/common/agentHostFileSystemProvider.js'; import { ContentEncoding, ResourceReadResult, ResourceResolveParams, ResourceResolveResult, ResourceType } from '../../../../../../../platform/agentHost/common/state/protocol/commands.js'; import { IFileService } from '../../../../../../../platform/files/common/files.js'; import { FileService } from '../../../../../../../platform/files/common/fileService.js'; import { createInMemoryFileService } from '../../../../../../../platform/files/test/common/inMemoryFileService.js'; -import { NullLogService } from '../../../../../../../platform/log/common/log.js'; +import { ILogService, NullLogService } from '../../../../../../../platform/log/common/log.js'; +import { getSizeRegistry } from '../../../../../../../platform/theme/common/sizeRegistry.js'; +import { ISizeService } from '../../../../../../../platform/theme/common/sizeService.js'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { IChatContentPartRenderContext } from '../../../../browser/widget/chatContentParts/chatContentParts.js'; import { ChatMarkdownContentPart, IChatMarkdownContentPartOptions } from '../../../../browser/widget/chatContentParts/chatMarkdownContentPart.js'; @@ -56,12 +63,38 @@ import { getChatMarkdownImageId } from '../../../../common/chatImageExtraction.j import { IChatSessionsService } from '../../../../common/chatSessionsService.js'; import { ChatRequestSlashPromptPart } from '../../../../common/requestParser/chatParserTypes.js'; import { ChatConfiguration } from '../../../../common/constants.js'; +import { IChatLayoutService } from '../../../../common/widget/chatLayoutService.js'; +import { ChatLayoutService } from '../../../../browser/widget/chatLayoutService.js'; import { MarkedKatexSupport } from '../../../../../markdown/browser/markedKatexSupport.js'; -import { rewriteAgentHostLinkTarget } from '../../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { messageAttachmentsToVariableData, rewriteAgentHostLinkTarget } from '../../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { MessageAttachmentKind, type MessageAttachment } from '../../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { agentHostConnectionKinds } from '../../../../../../../platform/agentHost/test/common/testAgentHostResourceUriMappers.js'; +import { ChatRequestParser } from '../../../../common/requestParser/chatRequestParser.js'; +import { IChatAgentService } from '../../../../common/participants/chatAgents.js'; +import { IChatSlashCommandService } from '../../../../common/participants/chatSlashCommands.js'; +import { IChatVariablesService } from '../../../../common/attachments/chatVariables.js'; +import { IPromptsService } from '../../../../common/promptSyntax/service/promptsService.js'; +import { ToolAndToolSetEnablementMap } from '../../../../common/tools/languageModelToolsService.js'; +import { getInlineRequestAttachments } from '../../../../common/attachments/chatInlineAttachments.js'; import { IAiEditTelemetryService } from '../../../../../editTelemetry/browser/telemetry/aiEditTelemetry/aiEditTelemetryService.js'; import { IViewDescriptorService } from '../../../../../../common/views.js'; import { IDisposableReference } from '../../../../browser/widget/chatContentParts/chatCollections.js'; import { MockChatSessionsService } from '../../../common/mockChatSessionsService.js'; +import { ChatHtmlPreviewPart, isHtmlPreviewCodeBlock } from '../../../../browser/widget/chatContentParts/chatHtmlPreviewPart.js'; +import { createHtmlPreviewDocument } from '../../../../browser/widget/chatContentParts/chatHtmlPreviewDocument.js'; +import { ChatHtmlPreviewAccessibleView, ChatHtmlPreviewEditorInput } from '../../../../browser/widget/chatContentParts/chatHtmlPreviewEditorInput.js'; +import { IOverlayWebview, IWebviewElement, IWebviewService, KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED, WebviewInitInfo } from '../../../../../webview/browser/webview.js'; +import { CONTEXT_ACTIVE_WEBVIEW_PANEL_ID } from '../../../../../webviewPanel/browser/webviewEditor.js'; +import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; +import { IChatWidgetService } from '../../../../browser/chat.js'; +import { IEditorPane } from '../../../../../../common/editor.js'; +import { IEditorService } from '../../../../../../services/editor/common/editorService.js'; +import { IWorkbenchLayoutService } from '../../../../../../services/layout/browser/layoutService.js'; +import { OverlayWebview } from '../../../../../webview/browser/overlayWebview.js'; +import { EditorInput } from '../../../../../../common/editor/editorInput.js'; +import { isWeb } from '../../../../../../../base/common/platform.js'; +import { Schemas } from '../../../../../../../base/common/network.js'; +import { BrowserViewEditorId } from '../../../../../browserView/common/browserView.js'; suite('ChatMarkdownContentPart', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -82,6 +115,7 @@ suite('ChatMarkdownContentPart', () => { return { get(): IDisposableReference { const element = mainWindow.document.createElement('div'); + element.tabIndex = 0; const mockPart = { element, get uri() { return undefined; }, @@ -90,7 +124,7 @@ suite('ChatMarkdownContentPart', () => { renderedCodeBlockWidths.push(width); }, layout() { }, - focus() { }, + focus() { element.focus(); }, reset() { }, onDidRemount() { }, } as unknown as CodeBlockPart; @@ -281,10 +315,10 @@ suite('ChatMarkdownContentPart', () => { const text = `/${name}`; const part = new ChatRequestSlashPromptPart(new OffsetRange(0, text.length), new Range(1, 1, 1, text.length + 1), name); const markdown = decorationsRenderer.convertParsedRequestToMarkdown(URI.parse('chat-session://test/session1'), { text, parts: [part] }); - const rendered = disposables.add(renderer.render(new MarkdownString(markdown))); + const rendered = disposables.add(renderer.render(markdown)); const anchor = rendered.element.querySelector('a'); const href = anchor?.getAttribute('data-href'); - disposables.add(decorationsRenderer.walkTreeAndAnnotateReferenceLinks({ kind: 'markdownContent', content: new MarkdownString(markdown) }, rendered.element)); + disposables.add(decorationsRenderer.walkTreeAndAnnotateReferenceLinks({ kind: 'markdownContent', content: markdown }, rendered.element)); return { text: rendered.element.textContent, decorationCount: rendered.element.querySelectorAll('.chat-resource-widget').length, @@ -294,6 +328,59 @@ suite('ChatMarkdownContentPart', () => { assert.deepStrictEqual(actual, names.map(name => ({ text: `/${name}`, decorationCount: 1, href: `http://_vscodedecoration_?${JSON.stringify({ title: name })}` }))); }); + for (const kind of agentHostConnectionKinds) { + test(`opens sent skill references through resource widgets by click and keyboard (${kind.name})`, async () => { + const text = '/review and /review /compact'; + const hostResources = [URI.file('/workspace/review (one)/SKILL.md'), URI.parse('custom-skill:/review?view=with%20spaces&bare&vscodeLinkType=opaque#details')]; + const attachments: MessageAttachment[] = hostResources.map((uri, index) => ({ + type: MessageAttachmentKind.Resource, uri: uri.toString(), label: '/review', displayKind: 'skill', + range: { start: { line: 0, character: index * 12 }, end: { line: 0, character: index * 12 + 7 } }, + ...(index === 0 ? { _meta: { uri: 'file:///wrong/SKILL.md' } } : {}), + })); + attachments.push({ + type: MessageAttachmentKind.Simple, label: '/compact', displayKind: 'command', _meta: { command: 'compact' }, + range: { start: { line: 0, character: 20 }, end: { line: 0, character: 28 } }, + }); + const variables = messageAttachmentsToVariableData(attachments, 'test', text, kind.resourceUris)!.variables; + const parser = new ChatRequestParser( + upcastPartial({ getDefaultAgent: () => undefined }), + upcastPartial({}), + upcastPartial({ getCommands: () => [] }), + upcastPartial({ hasPromptSlashCommand: () => false, isValidSlashCommandName: () => false }), + ); + const parsed = parser.parseChatRequestWithReferences(variables.map(variable => ({ + id: variable.id, data: variable.value, _meta: variable._meta, + range: new Range(1, variable.range!.start + 1, 1, variable.range!.endExclusive + 1), + })), ToolAndToolSetEnablementMap.fromEntries([]), text); + const inlineAttachments = getInlineRequestAttachments(parsed.parts, variables, text); + const decorations = disposables.add(instantiationService.createInstance(ChatMarkdownDecorationsRenderer)); + const markdown = decorations.convertParsedRequestToMarkdown(URI.parse('chat-session://test/session1'), parsed, new Set(inlineAttachments.keys())); + const opens: string[] = []; + instantiationService.stub(IOpenerService, new class extends mock() { + override async open(resource: URI | string): Promise { + opens.push(resource.toString()); + return true; + } + }()); + renderer = instantiationService.createInstance(ChatContentMarkdownRenderer); + const rendered = disposables.add(renderer.render(markdown)); + disposables.add(decorations.walkTreeAndAnnotateReferenceLinks({ kind: 'markdownContent', content: markdown }, rendered.element)); + const anchors = rendered.element.querySelectorAll('.chat-inline-anchor-widget'); + assert.strictEqual(anchors.length, 2); + anchors[0].click(); + anchors[1].dispatchEvent(new mainWindow.KeyboardEvent('keydown', { keyCode: 13, bubbles: true, cancelable: true })); + anchors[0].dispatchEvent(new mainWindow.KeyboardEvent('keydown', { keyCode: 32, bubbles: true, cancelable: true })); + await timeout(0); + const resources = [kind.toClient(hostResources[0]), kind.resourceUris.fromAgentHost(hostResources[1])].map(uri => uri.toString()); + assert.deepStrictEqual({ + opens, + labels: Array.from(anchors, anchor => anchor.textContent), + commandDecorations: rendered.element.querySelectorAll('.chat-resource-widget').length, + inlineAttachments: inlineAttachments.size, + }, { opens: [resources[0], resources[1], resources[0]], labels: ['/review', '/review'], commandDecorations: 1, inlineAttachments: 0 }); + }); + } + test('decorates a response with 1000 ordinary links and one preview link in a single anchor scan', () => { const configurationService = instantiationService.get(IConfigurationService) as TestConfigurationService; configurationService.setUserConfiguration(ChatConfiguration.RichLinks, false); @@ -1139,6 +1226,788 @@ suite('ChatMarkdownContentPart', () => { assert.ok(part.domNode.textContent?.includes('Rendering code block')); }); + suite('HTML previews', () => { + // WebKit never runs animation frame callbacks in a sandboxed document without allow-scripts, so wait on + // the host window's frame, which also renders these same-origin preview iframes. + function nextHostFrame(): Promise { + return new Promise(resolve => mainWindow.requestAnimationFrame(() => resolve())); + } + + class TestPreviewWebview extends mock() { + html = ''; + disposed = false; + remounts = 0; + override isFocused = false; + readonly fatalError = disposables.add(new Emitter<{ message: string }>()); + override readonly onFatalError = this.fatalError.event; + override readonly onDidWheel = Event.None; + override readonly onDidDispose = Event.None; + override readonly onDidFocus = Event.None; + override readonly onDidBlur = Event.None; + override readonly onDidClickLink = Event.None; + override readonly onMessage = Event.None; + override readonly onMissingCsp = Event.None; + override readonly onDidUpdateState = Event.None; + readonly scroll = disposables.add(new Emitter<{ scrollYPercentage: number }>()); + override readonly onDidScroll = this.scroll.event; + override initialScrollProgress = 0; + override state: string | undefined; + override readonly intrinsicContentSize = observableValue<{ width: number; height: number } | undefined>('preview size', undefined); + override setHtml(html: string): void { this.html = html; } + override setContextKeyService(): void { } + override mountTo(): void { } + override reinitializeAfterDismount(): void { this.remounts++; } + override dispose(): void { this.disposed = true; } + override focus(): void { } + } + + let webviews: { init: WebviewInitInfo; webview: TestPreviewWebview }[]; + let contextMenu: Parameters[0] | undefined; + const html = '

Quarterly report

MoreDetails
'; + const fenced = (text = html, fence = '```') => `${fence}html-preview\n${text}\n${fence}`; + const options = { renderHtmlPreviews: true }; + + function action(part: ChatMarkdownContentPart, label: string): IAction { + part.domNode.querySelector('.chat-html-preview')!.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + const action = contextMenu?.getActions?.().find(action => action.label === label); + assert.ok(action, `Missing preview action: ${label}`); + return action; + } + + setup(() => { + webviews = []; + contextMenu = undefined; + instantiationService.stub(IContextMenuService, { + showContextMenu: delegate => { contextMenu = delegate; }, + onDidHideContextMenu: Event.None, + }); + instantiationService.stub(IChatLayoutService, disposables.add(instantiationService.createInstance(ChatLayoutService))); + instantiationService.stub(ISizeService, { + onDidChangeSizes: Event.None, + getSize: (id, theme) => getSizeRegistry().resolveDefaultSize(id, theme), + }); + instantiationService.stub(IWebviewService, new class extends mock() { + override createWebviewElement(init: WebviewInitInfo): IWebviewElement { + const webview = new TestPreviewWebview(); + webviews.push({ init, webview }); + return webview; + } + override createWebviewOverlay(init: WebviewInitInfo): IOverlayWebview { + const webview = new TestPreviewWebview(); + webviews.push({ init, webview }); + return webview; + } + }()); + instantiationService.stub(IChatWidgetService, new class extends mock() { }()); + }); + + test('renders an explicit response preview in a restricted webview and retains its source', () => { + const part = createMarkdownPart(fenced(), undefined, false, false, options); + const document = new DOMParser().parseFromString(webviews[0].webview.html, 'text/html'); + assert.deepStrictEqual({ + previews: webviews.length, + contentOptions: webviews[0].init.contentOptions, + serviceWorkerDisabled: webviews[0].init.options.disableServiceWorker, + title: webviews[0].init.title, + heading: document.querySelector('h2')?.textContent, + style: document.querySelector('body style')?.textContent, + source: renderedCodeBlocks.map(block => ({ language: block.languageId, text: block.text })), + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')?.hidden, + noticeHidden: part.domNode.querySelector('.chat-html-preview-notice')?.hidden, + chrome: part.domNode.querySelectorAll('.chat-html-preview-header, .chat-html-preview-actions').length, + outputRenderers: renderedCodeBlockOutputs.length, + }, { + previews: 1, + contentOptions: { allowScripts: false, allowForms: false, enableCommandUris: false, localResourceRoots: [] }, + serviceWorkerDisabled: true, + title: 'HTML preview for code block 1', + heading: 'Quarterly report', + style: 'h2 { color: red }', + source: [{ language: 'html', text: html }], + sourceHidden: true, + noticeHidden: true, + chrome: 0, + outputRenderers: 0, + }); + }); + + test('keeps inline chrome transparent and uses short content height without a card minimum', () => { + const part = createMarkdownPart(fenced('

Short report

'), undefined, false, false, options); + mainWindow.document.body.appendChild(part.domNode); + disposables.add(toDisposable(() => part.domNode.remove())); + webviews[0].webview.intrinsicContentSize.set({ width: 500, height: 24 }, undefined); + const preview = part.domNode.querySelector('.chat-html-preview')!; + const style = mainWindow.getComputedStyle(preview); + assert.deepStrictEqual({ + background: style.backgroundColor, + border: style.borderTopWidth, + height: part.domNode.querySelector('.chat-html-preview-content')!.getBoundingClientRect().height, + label: preview.getAttribute('aria-label'), + webviewActions: webviews[0].init.options.getContextMenuActions!().filter(action => !(action instanceof Separator)).map(action => action.label), + }, { background: 'rgba(0, 0, 0, 0)', border: '0px', height: 24, label: 'HTML preview for code block 1', webviewActions: ['Open Preview', 'Show Source', 'Save HTML...'] }); + }); + + test('uses chat typography and refreshes it when chat font settings change', async () => { + const part = createMarkdownPart(fenced(), undefined, false, false, options); + const theme = { 'vscode-font-family': 'system-ui', 'vscode-font-size': '13px', 'vscode-foreground': '#123456' }; + const before = webviews[0].init.options.transformCssVariables!(theme); + const configuration = instantiationService.get(IConfigurationService) as TestConfigurationService; + await configuration.setUserConfiguration('chat.fontFamily', 'serif'); + await configuration.setUserConfiguration('chat.fontSize', 18); + configuration.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === 'chat.fontFamily' || key === 'chat.fontSize', + affectedKeys: new Set(['chat.fontFamily', 'chat.fontSize']), + source: 1, + change: { keys: ['chat.fontFamily', 'chat.fontSize'], overrides: [] }, + }); + assert.deepStrictEqual({ + before, + after: webviews.at(-1)!.init.options.transformCssVariables!(theme), + oldDisposed: webviews[0].webview.disposed, + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')!.hidden, + }, { + before: theme, + after: { ...theme, 'vscode-font-family': 'serif', 'vscode-font-size': '18px' }, + oldDisposed: true, + sourceHidden: true, + }); + }); + + test('does not reinterpret normal code, requests, incomplete fences, filtered responses, or annotated files', () => { + const request = { + ...createRenderContext(), + element: upcastPartial({ + id: 'request', + sessionResource: URI.parse('chat-session://test/session1'), + message: { text: fenced(), parts: [] }, + contentReferences: [], + }), + }; + const filtered = createRenderContext(); + Object.assign(filtered.element, { errorDetails: { responseIsFiltered: true, message: 'Filtered' } }); + const cases = [ + { markdown: fenced().replace('html-preview', 'html'), context: createRenderContext(), options }, + { markdown: fenced(), context: createRenderContext(), options: {} }, + { markdown: fenced(), context: request, options }, + { markdown: '```html-preview\n

Still streaming

', context: createRenderContext(false), options }, + { markdown: '```html-preview\n

Stopped without closing fence

', context: createRenderContext(), options }, + { markdown: fenced(html, '````').slice(0, -1), context: createRenderContext(), options }, + { markdown: fenced(), context: filtered, options }, + { markdown: fenced(`${html}\nfile:///report.html`), context: createRenderContext(), options }, + ]; + const results = cases.map(testCase => { + const part = createMarkdownPart(testCase.markdown, testCase.context, true, false, testCase.options); + return { preview: !!part.domNode.querySelector('.chat-html-preview'), codeblocks: part.codeblocks.length }; + }); + assert.deepStrictEqual({ results, webviews: webviews.length }, { + results: cases.map(() => ({ preview: false, codeblocks: 1 })), + webviews: 0, + }); + }); + + test('accepts closed backtick and tilde fences, not short or mismatched closing fences', () => { + assert.deepStrictEqual([ + ['html-preview', fenced()], + ['HTML-PREVIEW', fenced(html, '~~~~')], + ['html-preview', fenced(html, '````')], + ['html-preview', fenced(html, '````').slice(0, -1)], + ['html-preview', '```html-preview\n

Hi

\n~~~'], + ['html-preview', undefined], + ['html', fenced()], + ].map(([language, raw]) => isHtmlPreviewCodeBlock(language!, raw)), [true, true, true, false, false, false, false]); + createMarkdownPart(fenced(html, '~~~'), createRenderContext(false), true, false, options); + assert.strictEqual(webviews.length, 1); + }); + + test('leaves invalidly indented closing fences as source, including stopped responses', () => { + const results = [false, true].flatMap(complete => [0, 3, 4].map(indentation => { + const count = webviews.length; + const markdown = '```html-preview\n

Report

\n' + ' '.repeat(indentation) + '```'; + const context = createRenderContext(complete); + if (complete) { + Object.assign(context.element, { isCanceled: true }); + } + const part = createMarkdownPart(markdown, context, true, false, options); + return { preview: !!part.domNode.querySelector('.chat-html-preview'), created: webviews.length > count }; + })); + assert.deepStrictEqual(results, [true, true, false, true, true, false].map(preview => ({ preview, created: preview }))); + }); + + test('focuses the preview context menu and source editor without permanent controls', async () => { + const part = createMarkdownPart(fenced(), undefined, false, false, options); + mainWindow.document.body.appendChild(part.domNode); + disposables.add(toDisposable(() => part.domNode.remove())); + part.codeblocks[0].focus(); + const preview = { focused: part.codeblocks[0].isFocused, region: mainWindow.document.activeElement === part.domNode.querySelector('.chat-html-preview') }; + mainWindow.document.activeElement!.dispatchEvent(new KeyboardEvent('keydown', { key: 'F10', keyCode: 121, shiftKey: true, bubbles: true, cancelable: true })); + const menuLabels = contextMenu!.getActions!().filter(action => !(action instanceof Separator)).map(action => action.label); + await action(part, 'Show Source').run(); + part.codeblocks[0].focus(); + const source = { focused: part.codeblocks[0].isFocused, editor: part.domNode.querySelector('.chat-html-preview-source')?.contains(mainWindow.document.activeElement) }; + assert.deepStrictEqual({ preview, source, menuLabels }, { + preview: { focused: true, region: true }, + source: { focused: true, editor: true }, + menuLabels: ['Open Preview', 'Show Source', 'Save HTML...'], + }); + }); + + test('preserves the source toggle and webview while the rest of the response streams', async () => { + const part = createMarkdownPart(fenced(), createRenderContext(false), true, false, options); + const sourceAction = action(part, 'Show Source'); + await sourceAction.run(); + const updated = part.tryIncrementalUpdate({ kind: 'markdownContent', content: new MarkdownString(`${fenced()}\n\nExplanation.`) }); + assert.deepStrictEqual({ + updated, + webviews: webviews.length, + disposed: webviews[0].webview.disposed, + sameAction: sourceAction === action(part, 'Show Source'), + checked: sourceAction.checked, + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')?.hidden, + previewHidden: part.domNode.querySelector('.chat-html-preview-content')?.hidden, + sourceRenders: renderedCodeBlocks.length, + remounts: webviews[0].webview.remounts, + }, { updated: true, webviews: 1, disposed: false, sameAction: true, checked: true, sourceHidden: false, previewHidden: true, sourceRenders: 1, remounts: 0 }); + }); + + test('uses the full content height and replaces its detached webview on remount', () => { + const visibility = disposables.add(new Emitter()); + const part = createMarkdownPart(fenced(), { ...createRenderContext(), onDidChangeVisibility: visibility.event }, false, false, options); + disposables.add(toDisposable(() => part.domNode.remove())); + mainWindow.document.body.appendChild(part.domNode); + const webview = webviews[0].webview; + webview.intrinsicContentSize.set({ width: 500, height: 100_000 }, undefined); + const preview = part.domNode.querySelector('.chat-html-preview-content')!; + const height = preview.style.height; + const measuredHeight = preview.getBoundingClientRect().height; + part.onDidRemount(); + const previousDisposed = webview.disposed; + webviews[1].webview.intrinsicContentSize.set({ width: 0, height: 0 }, undefined); + const loadingHeight = part.domNode.querySelector('.chat-html-preview-content')?.style.height; + visibility.fire(true); + part.dispose(); + assert.deepStrictEqual({ + height, + measuredHeight, + loadingHeight, + previousDisposed, + created: webviews.length, + reusedDetachedFrame: webviews.some(view => view.webview.remounts > 0), + allDisposed: webviews.every(view => view.webview.disposed), + }, { height: '100000px', measuredHeight: 100000, loadingHeight: '100000px', previousDisposed: true, created: 3, reusedDetachedFrame: false, allDisposed: true }); + }); + + test('keeps source mode on remount and creates a fresh webview when returning to preview', async () => { + const part = createMarkdownPart(fenced(), undefined, false, false, options); + await action(part, 'Show Source').run(); + part.onDidRemount(); + const inSource = { + created: webviews.length, + oldDisposed: webviews[0].webview.disposed, + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')?.hidden, + }; + await action(part, 'Show Source').run(); + assert.deepStrictEqual({ + inSource, + createdAfterToggle: webviews.length, + previewHidden: part.domNode.querySelector('.chat-html-preview-content')?.hidden, + sourceChecked: action(part, 'Show Source').checked, + }, { inSource: { created: 1, oldDisposed: true, sourceHidden: false }, createdAfterToggle: 2, previewHidden: false, sourceChecked: false }); + }); + + test('restores source mode and reserved height after rebuilding a recycled HTML part', async () => { + const context = createRenderContext(); + const part = createMarkdownPart(fenced(), context, false, false, options); + webviews[0].webview.intrinsicContentSize.set({ width: 500, height: 480 }, undefined); + await action(part, 'Show Source').run(); + part.dispose(); + + const restored = createMarkdownPart(fenced(), context, false, false, options); + const beforeToggle = { + created: webviews.length, + sourceHidden: restored.domNode.querySelector('.chat-html-preview-source')?.hidden, + checked: action(restored, 'Show Source').checked, + height: restored.domNode.querySelector('.chat-html-preview-content')?.style.height, + }; + await action(restored, 'Show Source').run(); + const other = createRenderContext(); + Object.assign(other.element, { id: 'another-response' }); + const separate = createMarkdownPart(fenced(), other, false, false, options); + assert.deepStrictEqual({ + beforeToggle, + createdAfterToggle: webviews.length, + previewHidden: restored.domNode.querySelector('.chat-html-preview-content')?.hidden, + separateSourceHidden: separate.domNode.querySelector('.chat-html-preview-source')?.hidden, + separateHeight: separate.domNode.querySelector('.chat-html-preview-content')?.style.height, + }, { + beforeToggle: { created: 1, sourceHidden: false, checked: true, height: '480px' }, + createdAfterToggle: 3, previewHidden: false, separateSourceHidden: true, separateHeight: '', + }); + }); + + test('resynchronizes a retained HTML part after another row changes the shared view state', async () => { + const context = createRenderContext(); + const retained = createMarkdownPart(fenced(), context, false, false, options); + const replacement = createMarkdownPart(fenced(), context, false, false, options); + webviews[1].webview.intrinsicContentSize.set({ width: 500, height: 480 }, undefined); + const state = () => ({ + sourceHidden: retained.domNode.querySelector('.chat-html-preview-source')?.hidden, + previewHidden: retained.domNode.querySelector('.chat-html-preview-content')?.hidden, + checked: action(retained, 'Show Source').checked, + height: retained.domNode.querySelector('.chat-html-preview-content')?.style.height, + created: webviews.length, + }); + await action(replacement, 'Show Source').run(); + retained.onDidRemount(); + const inSource = state(); + await action(replacement, 'Show Source').run(); + retained.onDidRemount(); + assert.deepStrictEqual({ inSource, inPreview: state(), oldDisposed: webviews[0].webview.disposed }, { + inSource: { sourceHidden: false, previewHidden: true, checked: true, height: '480px', created: 2 }, + inPreview: { sourceHidden: true, previewHidden: false, checked: false, height: '480px', created: 3 }, + oldDisposed: true, + }); + }); + + test('does not reload a failed retained preview when another row switches back to preview', async () => { + const context = createRenderContext(); + const failed = createMarkdownPart(fenced(), context, false, false, options); + webviews[0].webview.fatalError.fire({ message: 'Webview unavailable' }); + const replacement = createMarkdownPart(fenced(), context, false, false, options); + await action(replacement, 'Show Source').run(); + failed.onDidRemount(); + assert.deepStrictEqual({ + created: webviews.length, + sourceHidden: failed.domNode.querySelector('.chat-html-preview-source')?.hidden, + previewHidden: failed.domNode.querySelector('.chat-html-preview-content')?.hidden, + checked: action(failed, 'Show Source').checked, + enabled: action(failed, 'Show Source').enabled, + }, { created: 2, sourceHidden: false, previewHidden: true, checked: true, enabled: false }); + }); + + test('keeps oversized output as source without allocating a webview', () => { + const atLimit = 'x'.repeat(ChatHtmlPreviewPart.maxPreviewLength); + createMarkdownPart(fenced(atLimit), undefined, false, false, options); + const overLimit = atLimit + 'x'; + const part = createMarkdownPart(fenced(overLimit), undefined, false, false, options); + assert.deepStrictEqual({ + webviews: webviews.length, + sourcePreserved: renderedCodeBlocks.at(-1)?.text === overLimit, + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')?.hidden, + message: part.domNode.querySelector('.chat-html-preview-notice')?.textContent, + noticeHidden: part.domNode.querySelector('.chat-html-preview-notice')?.hidden, + }, { webviews: 1, sourcePreserved: true, sourceHidden: false, message: 'HTML preview is too large. Showing source instead.', noticeHidden: false }); + }); + + test('shows and logs webview failures while preserving the original source', () => { + const logError = stub(instantiationService.get(ILogService), 'error'); + disposables.add(toDisposable(() => logError.restore())); + const part = createMarkdownPart(fenced(), undefined, false, false, options); + webviews[0].webview.fatalError.fire({ message: 'Webview unavailable' }); + assert.deepStrictEqual({ + logged: logError.calledOnce, + sourceHidden: part.domNode.querySelector('.chat-html-preview-source')?.hidden, + message: part.domNode.querySelector('[role="alert"]')?.textContent, + noticeHidden: part.domNode.querySelector('.chat-html-preview-notice')?.hidden, + source: renderedCodeBlocks[0].text, + }, { logged: true, sourceHidden: false, message: 'Unable to load HTML preview. Showing source instead.', noticeHidden: false, source: html }); + }); + + test('opens a restricted larger editor, reuses it, and keeps it alive independently of chat rendering', async () => { + const opened: EditorInput[] = []; + const editors = stub(instantiationService.get(IEditorService), 'editors').get(() => opened); + const open = stub(instantiationService.get(IEditorService), 'openEditor').callsFake(async input => { + opened.push(input); + store.add(input); + return upcastPartial({ input }); + }); + disposables.add(toDisposable(() => open.restore())); + disposables.add(toDisposable(() => editors.restore())); + const markdown = fenced('

Review

Summary

'); + const part = createMarkdownPart(markdown, undefined, false, false, options); + await action(part, 'Open Preview').run(); + await action(part, 'Open Preview').run(); + part.dispose(); + const restored = createMarkdownPart(markdown, undefined, false, false, options); + await action(restored, 'Open Preview').run(); + restored.dispose(); + const document = new DOMParser().parseFromString(webviews[1].webview.html, 'text/html'); + assert.deepStrictEqual({ + count: webviews.length, + reused: opened[0] === opened[1], + reusedAfterRecycling: opened[0] === opened[2], + editor: opened[0] instanceof ChatHtmlPreviewEditorInput, + editorDisposed: opened[0].isDisposed(), + inlineDisposed: webviews[0].webview.disposed, + expandedDisposed: webviews[1].webview.disposed, + contentOptions: webviews[1].init.contentOptions, + find: webviews[1].init.options.enableFindWidget, + heading: document.querySelector('h1')?.textContent, + scripts: document.scripts.length, + }, { + count: 3, reused: true, reusedAfterRecycling: true, editor: true, editorDisposed: false, inlineDisposed: true, expandedDisposed: false, + contentOptions: { allowScripts: false, allowForms: false, enableCommandUris: false, localResourceRoots: [] }, + find: true, heading: 'Review', scripts: 0, + }); + }); + + test('disposes a new expanded preview if opening its editor fails', async () => { + const failure = new Error('Editor unavailable'); + instantiationService.stub(IEditorService, new class extends mock() { + override readonly editors = []; + override async openEditor(): Promise { throw failure; } + }()); + const part = createMarkdownPart(fenced(), undefined, false, false, options); + await assert.rejects(async () => action(part, 'Open Preview').run(), /Editor unavailable/); + assert.deepStrictEqual({ + disposed: webviews[1].webview.disposed, + retryEnabled: action(part, 'Open Preview').enabled, + }, { disposed: true, retryEnabled: true }); + }); + + test('restores expanded preview scroll after releasing and reclaiming its editor', () => { + const service = instantiationService.get(IWebviewService); + const createOverlay = stub(service, 'createWebviewOverlay').callsFake(init => instantiationService.createInstance(OverlayWebview, init)); + disposables.add(toDisposable(() => createOverlay.restore())); + instantiationService.stub(IWorkbenchLayoutService, { getContainer: () => mainWindow.document.body }); + const input = store.add(instantiationService.createInstance(ChatHtmlPreviewEditorInput, '

Long report

', 'scroll-preview')); + const owner = {}; + input.webview.claim(owner, mainWindow, undefined); + webviews[0].webview.scroll.fire({ scrollYPercentage: 0.6 }); + input.webview.release(owner); + input.webview.claim(owner, mainWindow, undefined); + assert.deepStrictEqual({ + created: webviews.length, + oldDisposed: webviews[0].webview.disposed, + restoredScroll: webviews[1].webview.initialScrollProgress, + }, { created: 2, oldDisposed: true, restoredScroll: 0.6 }); + }); + + test('exports a sanitized standalone file and opens it through the existing file preview path', async () => { + const files = createInMemoryFileService(disposables, Schemas.file); + instantiationService.stub(IFileService, files); + const target = URI.file('/html-report.html'); + instantiationService.stub(IFileDialogService, { + defaultFilePath: async () => URI.file('/'), + showSaveDialog: async () => target, + }); + const didOpen = new DeferredPromise(); + let opened: URI | string | undefined; + let override: IEditorOptions['override']; + instantiationService.stub(IOpenerService, { + open: async (resource, options: OpenOptions | undefined) => { + opened = resource; + override = options?.editorOptions?.override; + void didOpen.complete(); + return true; + }, + }); + instantiationService.stub(IEditorService, new class extends mock() { + override async openEditor(): Promise { + opened = target; + void didOpen.complete(); + return undefined; + } + }()); + const part = createMarkdownPart(fenced('

Saved report

Summary
'), undefined, false, false, options); + await action(part, 'Save HTML...').run(); + await didOpen.p; + const saved = (await files.readFile(target)).value.toString(); + const document = new DOMParser().parseFromString(saved, 'text/html'); + const reopened = store.add(instantiationService.createInstance(ChatHtmlPreviewEditorInput, saved, 'saved-preview')); + assert.deepStrictEqual({ + opened: opened?.toString(), + override, + heading: document.querySelector('h1')?.textContent, + activeContent: document.querySelectorAll('script,form,input').length, + csp: document.querySelector('meta[http-equiv="Content-Security-Policy"]')?.getAttribute('content')?.includes(`script-src 'none'`), + navigation: document.querySelector('a')?.getAttribute('href'), + font: document.documentElement.style.getPropertyValue('--vscode-font-family').length > 0, + reopened: new DOMParser().parseFromString(reopened.html, 'text/html').querySelector('h1')?.textContent, + originalSource: renderedCodeBlocks[0].text.includes(''), + }, { + opened: target.toString(), override: isWeb ? undefined : BrowserViewEditorId, heading: 'Saved report', + activeContent: 0, csp: true, navigation: '#summary', font: true, reopened: 'Saved report', originalSource: true, + }); + }); + + test('reports an export failure without opening a successful-looking preview', async () => { + const failure = new Error('Write denied'); + instantiationService.stub(IFileService, { writeFile: async () => { throw failure; } }); + instantiationService.stub(IFileDialogService, { + defaultFilePath: async () => URI.file('/'), + showSaveDialog: async () => URI.file('/report.html'), + }); + const opener = spy(); + instantiationService.stub(IOpenerService, { open: opener }); + const part = createMarkdownPart(fenced(), undefined, false, false, options); + await assert.rejects(async () => action(part, 'Save HTML...').run(), /Write denied/); + assert.deepStrictEqual({ + opened: opener.called, + retryEnabled: action(part, 'Save HTML...').enabled, + }, { opened: false, retryEnabled: true }); + }); + + test('provides readable expanded content and restores focus after accessibility help', () => { + const input = store.add(instantiationService.createInstance(ChatHtmlPreviewEditorInput, '

Plan

Review this change.

Risks

Offline only.

AreaStatus
PreviewReady
', 'accessible-preview')); + webviews[0].webview.isFocused = true; + instantiationService.stub(IEditorService, { activeEditor: input }); + const focus = spy(input.webview, 'focus'); + disposables.add(toDisposable(() => focus.restore())); + const view = store.add(new ChatHtmlPreviewAccessibleView(AccessibleViewType.View).getProvider(instantiationService)!); + const help = store.add(new ChatHtmlPreviewAccessibleView(AccessibleViewType.Help).getProvider(instantiationService)!); + help.onClose(); + assert.deepStrictEqual({ + content: view.provideContent(), + help: help.provideContent().includes('Save HTML exports a sanitized, self-contained document'), + findCommand: help.provideContent().includes(''), + focusRestored: focus.calledOnce, + }, { content: '# Plan\nReview this change.\n\nRisks\n\nOffline only.\n\nArea | Status\n\nPreview | Ready', help: true, findCommand: true, focusRestored: true }); + }); + + test('leaves accessibility commands with chat and Find when the preview content is not focused', () => { + const input = store.add(instantiationService.createInstance(ChatHtmlPreviewEditorInput, '

Report

', 'focused-preview')); + const editorService: { activeEditor: EditorInput | undefined } = { activeEditor: input }; + instantiationService.stub(IEditorService, editorService); + const configuration = new TestConfigurationService(); + disposables.add(configuration.onDidChangeConfigurationEmitter); + const context = disposables.add(new ContextKeyService(configuration)); + ChatContextKeys.enabled.bindTo(context).set(true); + CONTEXT_ACTIVE_WEBVIEW_PANEL_ID.bindTo(context).set(ChatHtmlPreviewEditorInput.viewType); + const findFocused = KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED.bindTo(context); + const focus = spy(input.webview, 'focus'); + disposables.add(toDisposable(() => focus.restore())); + const results = [AccessibleViewType.Help, AccessibleViewType.View].map(type => { + const implementation = new ChatHtmlPreviewAccessibleView(type); + const unfocused = implementation.getProvider(instantiationService); + if (unfocused) { + store.add(unfocused); + } + const matchesPreview = context.contextMatchesRules(implementation.when); + findFocused.set(true); + const matchesFind = context.contextMatchesRules(implementation.when); + findFocused.set(false); + webviews[0].webview.isFocused = true; + const provider = store.add(implementation.getProvider(instantiationService)!); + editorService.activeEditor = undefined; + provider.onClose(); + editorService.activeEditor = input; + webviews[0].webview.isFocused = false; + return { suppliedOutsidePreview: !!unfocused, matchesPreview, matchesFind }; + }); + assert.deepStrictEqual({ results, refocusedAfterEditorChanged: focus.called }, { + results: [{ suppliedOutsidePreview: false, matchesPreview: true, matchesFind: false }, { suppliedOutsidePreview: false, matchesPreview: true, matchesFind: false }], + refocusedAfterEditorChanged: false, + }); + }); + + test('allows only normalized in-document anchor navigation', () => { + const document = new DOMParser().parseFromString(createHtmlPreviewDocument(` + SummaryEncodedSpacesTop + MalformedExternal + Protocol relativeCommandScript + SVG link +

Summary

Code review

+ `), 'text/html'); + assert.deepStrictEqual([...document.querySelectorAll('a')].map(anchor => anchor.getAttribute('href')), + ['#summary', '#code%20review', '#code%20review', '#', null, null, null, null, null, null]); + }); + + test('preserves common section targets and their ARIA and SVG references without DOM collisions', () => { + const ids = ['title', 'timeline', 'implementation', 'style', 'summary', 'vscode-html-preview-title']; + const document = new DOMParser().parseFromString(createHtmlPreviewDocument( + ids.map(id => `${id}

${id}

`).join('') + + '
' + ), 'text/html'); + const markerId = document.querySelector('path')?.getAttribute('marker-end')?.slice(5, -1); + assert.deepStrictEqual({ + targets: [...document.querySelectorAll('a')].map(anchor => document.getElementById(decodeURIComponent(anchor.hash.slice(1)))?.textContent), + ariaTargets: document.querySelector('section')?.getAttribute('aria-labelledby')?.split(' ').map(id => document.getElementById(id)?.textContent), + svgTarget: !!markerId && document.getElementById(decodeURIComponent(markerId)) === document.querySelector('marker'), + noClobberingTitle: document.getElementById('title') === null, + distinctIds: new Set([...document.querySelectorAll('[id]')].map(element => element.id)).size, + }, { targets: ids, ariaTargets: ['title', 'summary'], svgTarget: true, noClobberingTitle: true, distinctIds: ids.length + 1 }); + }); + + test('exports only referenced theme variables without introducing active markup', () => { + const document = new DOMParser().parseFromString(createHtmlPreviewDocument('

Themed

', { + activeTheme: 'vscode-dark', + styles: { 'vscode-foreground': '#123456', 'vscode-font-family': 'font"', 'vscode-unused': 'not exported' }, + }), 'text/html'); + assert.deepStrictEqual({ + color: document.documentElement.style.getPropertyValue('--vscode-foreground'), + unused: document.documentElement.style.getPropertyValue('--vscode-unused'), + scripts: document.scripts.length, + class: document.body.className, + }, { color: '#123456', unused: '', scripts: 0, class: 'vscode-dark' }); + }); + + test('preserves quoted platform fonts and subsequent theme variables in saved HTML', () => { + const fonts = ['"Segoe WPC", "Segoe UI", sans-serif', 'system-ui, "Ubuntu", "Droid Sans", sans-serif', '-apple-system, BlinkMacSystemFont, sans-serif']; + const results = fonts.map(font => { + const document = new DOMParser().parseFromString(createHtmlPreviewDocument('

Report

', { + activeTheme: 'vscode-dark', + styles: { 'vscode-font-family': font, 'vscode-editor-foreground': '#d4d4d4', 'vscode-editor-background': '#1e1e1e' }, + }), 'text/html'); + return { + font: document.documentElement.style.getPropertyValue('--vscode-font-family'), + foreground: document.documentElement.style.getPropertyValue('--vscode-editor-foreground'), + background: document.documentElement.style.getPropertyValue('--vscode-editor-background'), + attributes: document.documentElement.getAttributeNames(), + }; + }); + assert.deepStrictEqual(results, fonts.map(font => ({ + font, foreground: '#d4d4d4', background: '#1e1e1e', attributes: ['style'], + }))); + }); + + test('blends inline documents with chat without removing authored surfaces or standalone styling', async () => { + const frame = mainWindow.document.createElement('iframe'); + frame.setAttribute('sandbox', 'allow-same-origin'); + disposables.add(toDisposable(() => frame.remove())); + mainWindow.document.body.appendChild(frame); + const results = []; + for (const presentation of ['inline', 'document'] as const) { + const loaded = new DeferredPromise(); + const listener = disposables.add(addDisposableListener(frame, 'load', () => loaded.complete())); + frame.srcdoc = createHtmlPreviewDocument('
Report
', { + activeTheme: 'vscode-dark', + styles: { 'vscode-foreground': '#123456', 'vscode-editor-foreground': '#abcdef', 'vscode-editor-background': '#182d50' }, + }, presentation); + await loaded.p; + listener.dispose(); + const body = frame.contentWindow!.getComputedStyle(frame.contentDocument!.body); + results.push({ + presentation, + background: body.backgroundColor, + color: body.color, + padding: body.padding, + authored: frame.contentWindow!.getComputedStyle(frame.contentDocument!.querySelector('section')!).backgroundColor, + }); + } + assert.deepStrictEqual(results, [ + { presentation: 'inline', background: 'rgba(0, 0, 0, 0)', color: 'rgb(18, 52, 86)', padding: '0px', authored: 'rgb(170, 187, 204)' }, + { presentation: 'document', background: 'rgb(24, 45, 80)', color: 'rgb(171, 205, 239)', padding: '12px', authored: 'rgb(170, 187, 204)' }, + ]); + }); + + test('preserves native horizontal scrolling without a layout wrapper', async () => { + const frame = mainWindow.document.createElement('iframe'); + frame.setAttribute('sandbox', 'allow-same-origin'); + frame.style.cssText = 'position: absolute; top: 0; left: 0; width: 440px; height: 300px; border: 0;'; + const loaded = new DeferredPromise(); + disposables.add(addDisposableListener(frame, 'load', () => loaded.complete())); + disposables.add(toDisposable(() => frame.remove())); + frame.srcdoc = createHtmlPreviewDocument('
' + ('Wide content '.repeat(30) + '\n').repeat(4) + '
'); + mainWindow.document.body.appendChild(frame); + await loaded.p; + const document = frame.contentDocument!; + const contentWindow = frame.contentWindow!; + // Headless browsers can hide scrollbars even when their size is specified in CSS. + const scrollbarHeight = contentWindow.innerHeight - document.documentElement.clientHeight; + frame.style.height = `${Math.ceil(document.documentElement.getBoundingClientRect().height + scrollbarHeight)}px`; + contentWindow.scrollTo(100, 100); + assert.deepStrictEqual({ + rootFitsVertically: document.documentElement.scrollHeight === document.documentElement.clientHeight, + contentOverflows: document.documentElement.scrollWidth > document.documentElement.clientWidth, + scrollbarHeight: contentWindow.innerHeight - document.documentElement.clientHeight, + scrollPosition: { x: contentWindow.scrollX, y: contentWindow.scrollY }, + unwrapped: document.querySelector('pre')?.parentElement === document.body, + }, { rootFitsVertically: true, contentOverflows: true, scrollbarHeight, scrollPosition: { x: 100, y: 0 }, unwrapped: true }); + }); + + test('keeps a viewport-height body minimum stable while auto-sizing', async () => { + const frame = mainWindow.document.createElement('iframe'); + frame.setAttribute('sandbox', 'allow-same-origin'); + frame.style.cssText = 'position: absolute; top: 0; left: 0; width: 440px; height: 300px; border: 0;'; + const loaded = new DeferredPromise(); + disposables.add(addDisposableListener(frame, 'load', () => loaded.complete())); + disposables.add(toDisposable(() => frame.remove())); + frame.srcdoc = createHtmlPreviewDocument('

Viewport-height document

'); + mainWindow.document.body.appendChild(frame); + await loaded.p; + const heights: number[] = []; + for (let index = 0; index < 3; index++) { + const root = frame.contentDocument!.documentElement; + const height = Math.ceil(root.getBoundingClientRect().height + frame.contentWindow!.innerHeight - root.clientHeight); + heights.push(height); + frame.style.height = `${height}px`; + await nextHostFrame(); + } + assert.deepStrictEqual(heights, [300, 300, 300]); + }); + + test('preserves body grid layout, ID selectors and sticky navigation', async () => { + const frame = mainWindow.document.createElement('iframe'); + frame.setAttribute('sandbox', 'allow-same-origin'); + frame.style.cssText = 'position: absolute; top: 0; left: 0; width: 800px; height: 300px; border: 0;'; + const loaded = new DeferredPromise(); + disposables.add(addDisposableListener(frame, 'load', () => loaded.complete())); + disposables.add(toDisposable(() => frame.remove())); + frame.srcdoc = createHtmlPreviewDocument('

Report

Timeline

Case variant

Unicode ID

'); + mainWindow.document.body.appendChild(frame); + await loaded.p; + const document = frame.contentDocument!; + const nav = document.querySelector('nav')!; + const main = document.querySelector('main')!; + const before = { sameRow: nav.getBoundingClientRect().top === main.getBoundingClientRect().top, separateColumns: main.getBoundingClientRect().left > nav.getBoundingClientRect().right }; + frame.contentWindow!.scrollTo(0, 200); + await nextHostFrame(); + assert.deepStrictEqual({ + before, + stickyTop: nav.getBoundingClientRect().top, + titleColor: frame.contentWindow!.getComputedStyle(document.querySelector('h1')!).color, + linkColor: frame.contentWindow!.getComputedStyle(document.querySelector('a')!).color, + timelineWeight: frame.contentWindow!.getComputedStyle(document.querySelector('p')!).fontWeight, + variantWeight: frame.contentWindow!.getComputedStyle(document.getElementById('Timeline')!).fontWeight, + unicodeStyle: frame.contentWindow!.getComputedStyle(document.getElementById('title\u00e9')!).fontStyle, + literal: frame.contentWindow!.getComputedStyle(document.querySelector('.literal')!, '::after').content, + children: [...document.body.children].filter(element => element.tagName !== 'STYLE').map(element => element.tagName), + }, { + before: { sameRow: true, separateColumns: true }, stickyTop: 0, titleColor: 'rgb(255, 0, 0)', linkColor: 'rgb(0, 128, 0)', timelineWeight: '600', variantWeight: '600', unicodeStyle: 'italic', literal: '"#title"', children: ['NAV', 'MAIN'], + }); + }); + + test('removes active markup, navigations, resource URLs, and webview context while preserving static visuals', () => { + const document = new DOMParser().parseFromString(createHtmlPreviewDocument(` + + + + +
+ + + + Embedded + + +
+ Link + Chart

Unsafe

+
MoreVisible details
+
+ `), 'text/html'); + assert.deepStrictEqual({ + activeElements: document.querySelectorAll('script, iframe, object, form, input, button, base, link, foreignObject, use').length, + refresh: document.querySelectorAll('meta[http-equiv="refresh"]').length, + cspCount: document.querySelectorAll('meta[http-equiv="Content-Security-Policy"]').length, + csp: document.querySelector('meta[http-equiv="Content-Security-Policy"]')?.getAttribute('content'), + resourceUrls: [...document.querySelectorAll('[src]')].map(element => element.getAttribute('src')), + unsafeAttributes: document.querySelectorAll('[href], [ping], [target], [onerror], [data-vscode-context]').length, + label: document.querySelector('section')?.getAttribute('aria-label'), + style: document.querySelector('section')?.getAttribute('style'), + svg: document.querySelector('svg')?.getAttribute('viewBox'), + rectangle: document.querySelector('rect')?.getAttribute('width'), + details: document.querySelector('details')?.hasAttribute('open'), + authorStyle: document.querySelector('body style')?.textContent, + }, { + activeElements: 0, refresh: 0, cspCount: 1, + csp: `default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none';`, + resourceUrls: ['data:image/png;base64,AAAA'], unsafeAttributes: 0, label: 'Report', + style: 'padding: 12px', svg: '0 0 100 100', rectangle: '50', details: true, authorStyle: '.card { color: red }', + }); + }); + }); + test('renders multiple code blocks with correct indices', () => { const part = createMarkdownPart( 'Some text\n```python\nprint("a")\n```\nMore text\n```typescript\nconst x = 1;\n```' diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatNativeComponentsRenderer.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatNativeComponentsRenderer.test.ts new file mode 100644 index 000000000000..9c782e421a51 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatNativeComponentsRenderer.test.ts @@ -0,0 +1,164 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mainWindow } from '../../../../../../../base/browser/window.js'; +import { toDisposable } from '../../../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { renderNativeComponents } from '../../../../browser/widget/chatContentParts/chatNativeComponentsRenderer.js'; +import { parseNativeComponents } from '../../../../common/nativeComponents/nativeComponentsParser.js'; + +suite('Native components renderer', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function render(source: string): HTMLElement { + const { document, error } = parseNativeComponents(source); + assert.ok(document, error?.message); + const { element } = renderNativeComponents(document); + mainWindow.document.body.appendChild(element); + store.add(toDisposable(() => element.remove())); + return element; + } + + const labelledBy = (element: Element) => mainWindow.document.getElementById(element.getAttribute('aria-labelledby') ?? '')?.textContent; + const texts = (elements: Iterable) => Array.from(elements, element => element.textContent); + + test('gives every component real semantics, and names what a tone or a bar conveys', () => { + const element = render([ + 'Build', + '', + '', + '', + 'Flaky', + 'Draft', + 'TargetSecondsFull12.4
', + '', + 'Median of five runs.', + ].join('\n')); + + const heading = element.querySelector('.chat-native-text.heading')!; + const table = element.querySelector('table')!; + const plot = element.querySelector('.chat-native-chart-plot')!; + const details = element.querySelector('details')!; + assert.deepStrictEqual({ + heading: { role: heading.getAttribute('role'), level: heading.getAttribute('aria-level'), text: heading.textContent }, + metrics: Array.from(element.querySelectorAll('.chat-native-metric'), metric => ({ + role: metric.getAttribute('role'), + label: labelledBy(metric), + value: metric.querySelector('.chat-native-metric-value')!.textContent, + detail: metric.querySelector('.chat-native-metric-detail')?.textContent, + tone: Array.from(metric.querySelectorAll('.chat-native-icon'), icon => `${icon.parentElement!.className} > ${icon.getAttribute('role')}: ${icon.getAttribute('aria-label')}`), + })), + badgesPerLine: Array.from(element.querySelectorAll('.chat-native-badges'), badges => badges.children.length), + badge: { + text: element.querySelector('.chat-native-badge')!.textContent, + tone: Array.from(element.querySelectorAll('.chat-native-badge .chat-native-icon'), icon => `${icon.getAttribute('role')}: ${icon.getAttribute('aria-label')}`), + }, + table: { + caption: table.caption?.textContent, + headers: Array.from(table.tHead!.rows[0].cells, cell => `${cell.tagName} ${cell.getAttribute('scope')} ${cell.textContent}${cell.classList.contains('align-end') ? ' (end)' : ''}`), + rows: Array.from(table.tBodies[0].rows, row => Array.from(row.cells, cell => `${cell.tagName} ${cell.textContent}${cell.classList.contains('align-end') ? ' (end)' : ''}`)), + }, + chart: { + role: plot.getAttribute('role'), + label: labelledBy(plot), + rows: Array.from(plot.children, row => Array.from(row.children, cell => cell.getAttribute('aria-hidden') === 'true' + ? `decorative bar ${cell.querySelector('.chat-native-chart-bar')!.style.width}` + : `${row.getAttribute('role')} > ${cell.getAttribute('role')}: ${cell.textContent}`)), + }, + disclosure: { + summary: details.querySelector('summary')!.textContent, + chevronHidden: details.querySelector('summary .chat-native-icon')!.getAttribute('aria-hidden'), + open: details.open, + content: texts(details.querySelectorAll('.chat-native-disclosure-content > *')), + }, + }, { + heading: { role: 'heading', level: '3', text: 'Build' }, + metrics: [ + { role: 'group', label: 'Incremental build', value: '1.8 s', detail: '-85%', tone: ['chat-native-metric-detail > img: Positive'] }, + { role: 'group', label: 'Full build', value: '12.4 s', detail: undefined, tone: [] }, + { role: 'group', label: 'Flaky tests', value: '7', detail: undefined, tone: ['chat-native-metric-value > img: Warning'] }, + ], + badgesPerLine: [2], + badge: { text: 'Flaky', tone: ['img: Warning'] }, + table: { + caption: 'By target', + headers: ['TH col Target', 'TH col Seconds (end)'], + rows: [['TD Full', 'TD 12.4 (end)']], + }, + chart: { + role: 'table', + label: 'Duration', + rows: [ + ['row > rowheader: Full', 'decorative bar 100%', 'row > cell: 10 s'], + ['row > rowheader: Incremental', 'decorative bar 25%', 'row > cell: 2.5 s'], + ['row > rowheader: Cached', 'decorative bar 0%', 'row > cell: 0 s'], + ], + }, + disclosure: { summary: 'Method', chevronHidden: 'true', open: false, content: ['Median of five runs.'] }, + }); + }); + + test('sets authored strings as text, never as markup, classes or styles', () => { + const markup = 'bold'; + const escaped = markup.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); + const element = render([ + `${escaped}`, + ``, + `${escaped}`, + `${escaped}${escaped}
`, + ``, + `A`, + ].join('\n')); + const authoredText = '.chat-native-text, .chat-native-metric-label, .chat-native-metric-value, .chat-native-metric-detail, .chat-native-badge, caption, th, td, .chat-native-chart-title, .chat-native-chart-label, summary'; + assert.deepStrictEqual({ + activeOrAuthoredElements: element.querySelectorAll('img, script, b, [style*="color"], .x, [onerror]').length, + texts: [...new Set(texts(element.querySelectorAll(authoredText)))], + value: element.querySelector('.chat-native-chart-value')!.textContent, + }, { + activeOrAuthoredElements: 0, + texts: [markup, 'A'], + value: `1 ${markup}`, + }); + }); + + test('lays columns out side by side, and stacks them as the chat narrows', () => { + const element = render(''); + element.style.fontSize = '13px'; + const columnsPerRow = (width: number) => { + element.style.width = `${width}px`; + const tops = Array.from(element.querySelectorAll('.chat-native-metric'), metric => Math.round(metric.getBoundingClientRect().top)); + return tops.filter(top => top === tops[0]).length; + }; + assert.deepStrictEqual([600, 320, 200].map(columnsPerRow), [3, 2, 1]); + }); + + test('scrolls a wide table inside its own box instead of widening the response', () => { + const element = render(`${'Column'.repeat(12)}${'A long value that cannot wrap'.repeat(12)}
`); + element.style.width = '300px'; + const scroller = element.querySelector('.chat-native-table-scroll')!; + assert.deepStrictEqual({ + responseWidth: element.getBoundingClientRect().width, + scrollerWidth: scroller.getBoundingClientRect().width, + scrolls: scroller.scrollWidth > scroller.clientWidth, + }, { responseWidth: 300, scrollerWidth: 300, scrolls: true }); + }); + + test('wraps long unbroken strings instead of widening a narrow chat', () => { + const long = 'W'.repeat(60); + const element = render([ + `${long}`, + ``, + `${long}`, + ``, + `${long}`, + ].join('\n')); + element.style.width = '240px'; + element.style.fontSize = '13px'; + element.querySelector('details')!.open = true; + const overflowing = Array.from(element.querySelectorAll('*')).filter(child => child.scrollWidth > child.clientWidth + 1).map(child => child.className); + assert.deepStrictEqual({ width: element.scrollWidth, overflowing: [...new Set(overflowing)] }, { width: 240, overflowing: [] }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatQuestionCarouselPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatQuestionCarouselPart.test.ts index 589b7cafac39..174431c0c286 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatQuestionCarouselPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatQuestionCarouselPart.test.ts @@ -45,6 +45,7 @@ suite('ChatQuestionCarouselPart', () => { let widget: ChatQuestionCarouselPart; let submittedAnswers: Map | undefined | null = null; + let submittedByUser: boolean | undefined; let codeEditorService: ICodeEditorService; /** Returns the answer editors rendered under the given root, in DOM order. */ @@ -77,8 +78,9 @@ suite('ChatQuestionCarouselPart', () => { codeEditorService = instantiationService.get(ICodeEditorService); const options: IChatQuestionCarouselOptions = { ...optionsOverrides, - onSubmit: (answers) => { + onSubmit: (answers, byUser) => { submittedAnswers = answers; + submittedByUser = byUser; onSubmit?.(); } }; @@ -92,6 +94,7 @@ suite('ChatQuestionCarouselPart', () => { teardown(() => { submittedAnswers = null; + submittedByUser = undefined; }); suite('Basic Rendering', () => { @@ -669,78 +672,59 @@ suite('ChatQuestionCarouselPart', () => { suite('Question Types', () => { const booleanOptions = [ - { id: 'true', label: 'True', value: 'true' }, - { id: 'false', label: 'False', value: 'false' }, + { id: 'no', label: 'false', value: 'false' }, + { id: 'yes', label: 'true', value: 'true' }, ]; const getFooterButtons = () => [...widget.domNode.querySelectorAll('.chat-question-footer-right .monaco-button')]; - test('renders boolean questions as No/Yes footer buttons and submits the chosen answer', () => { - const renderButtons = (defaultValue: string | undefined) => { - createWidget(createMockCarousel([{ id: 'q1', type: 'singleSelect', title: 'Proceed?', options: booleanOptions, defaultValue, allowFreeformInput: false }])); - const buttons = getFooterButtons(); - return { buttons, state: buttons.map(button => ({ label: button.textContent, primary: !button.classList.contains('secondary') })) }; + test('renders boolean questions as Yes/No options and submits No', () => { + createWidget(createMockCarousel([{ id: 'q1', type: 'singleSelect', title: 'Proceed?', options: booleanOptions }])); + const list = widget.domNode.querySelector('.chat-question-list')!; + const listItems = [...list.querySelectorAll('.chat-question-list-item')]; + const rendered = { + role: list.getAttribute('role'), + labels: listItems.map(item => item.querySelector('.chat-question-list-label')?.textContent), + freeformBelow: list.nextElementSibling?.classList.contains('chat-question-freeform'), + footer: getFooterButtons().map(button => button.textContent), }; - - const byDefault = renderButtons(undefined); - const hasList = !!widget.domNode.querySelector('.chat-question-list-item'); - widget.domNode.remove(); - const defaultedToNo = renderButtons('false'); - widget.domNode.remove(); - const rendered = renderButtons(undefined); - rendered.buttons[1].click(); - - assert.deepStrictEqual({ byDefault: byDefault.state, hasList, defaultedToNo: defaultedToNo.state, submitted: submittedAnswers?.get('q1') }, { - byDefault: [{ label: 'No', primary: false }, { label: 'Yes', primary: true }], - hasList: false, - defaultedToNo: [{ label: 'No', primary: true }, { label: 'Yes', primary: false }], - submitted: { selectedValue: 'true', freeformValue: undefined }, + listItems[1].click(); + + assert.deepStrictEqual({ ...rendered, submitted: submittedAnswers?.get('q1') }, { + role: 'listbox', + labels: ['Yes', 'No'], + freeformBelow: true, + footer: ['Submit'], + submitted: { selectedValue: 'false', freeformValue: undefined }, }); }); - test('boolean question with custom answers always shows the answer editor and swaps Yes/No for the primary button once it has text', () => { - createWidget(createMockCarousel([{ id: 'q1', type: 'singleSelect', title: 'Proceed?', options: booleanOptions, allowFreeformInput: true }])); - const editorNode = widget.domNode.querySelector('.chat-question-answer-editor')!; - const getState = () => ({ - ghost: editorNode.classList.contains('ghost'), - footer: getFooterButtons().map(button => button.getAttribute('aria-label') ?? button.textContent), - }); - const initial = getState(); - const hasLink = !!widget.domNode.querySelector('.chat-question-custom-answer-link'); - - getAnswerEditor().focus(); - const focused = getState(); - - setAnswer('Only on staging'); - const typed = getState(); - - setAnswer(''); - const cleared = getState(); - - setAnswer('Only on staging'); + test('boolean default selects No without reordering options or enabling disallowed freeform input', () => { + createWidget(createMockCarousel([{ id: 'q1', type: 'singleSelect', title: 'Proceed?', options: booleanOptions, defaultValue: 'no', allowFreeformInput: false }])); + const options = [...widget.domNode.querySelectorAll('.chat-question-list-item')].map(item => ({ + label: item.querySelector('.chat-question-list-label')?.textContent, + selected: item.classList.contains('selected'), + })); + const hasFreeform = !!widget.domNode.querySelector('.chat-question-freeform'); getFooterButtons()[0].click(); - assert.deepStrictEqual({ hasLink, initial, focused, typed, cleared, submitted: submittedAnswers?.get('q1') }, { - hasLink: false, - initial: { ghost: true, footer: ['No', 'Yes'] }, - focused: { ghost: false, footer: ['No', 'Yes'] }, - typed: { ghost: false, footer: ['Submit'] }, - cleared: { ghost: false, footer: ['No', 'Yes'] }, - submitted: { selectedValue: undefined, freeformValue: 'Only on staging' }, + assert.deepStrictEqual({ options, hasFreeform, submitted: submittedAnswers?.get('q1') }, { + options: [{ label: 'Yes', selected: false }, { label: 'No', selected: true }], + hasFreeform: false, + submitted: { selectedValue: 'false', freeformValue: undefined }, }); }); - test('Escape in the empty custom answer editor of a boolean question blurs it instead of dismissing the carousel', () => { + test('boolean custom answers use the single-select freeform input and normal primary button', () => { createWidget(createMockCarousel([{ id: 'q1', type: 'singleSelect', title: 'Proceed?', options: booleanOptions, allowFreeformInput: true }])); - const editor = getAnswerEditor(); - editor.focus(); - const focusedBefore = editor.hasTextFocus(); - - editor.getDomNode()!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + setAnswer('Only on staging'); + const selectedOptions = widget.domNode.querySelectorAll('.chat-question-list-item.selected').length; + const footer = getFooterButtons().map(button => button.textContent); + getFooterButtons()[0].click(); - assert.deepStrictEqual({ focusedBefore, carouselFocused: mainWindow.document.activeElement === widget.domNode, submittedAnswers }, { - focusedBefore: true, - carouselFocused: true, - submittedAnswers: null, + assert.deepStrictEqual({ selectedOptions, footer, submitted: submittedAnswers?.get('q1') }, { + selectedOptions: 0, + footer: ['Submit'], + submitted: { selectedValue: undefined, freeformValue: 'Only on staging' }, }); }); @@ -1038,6 +1022,30 @@ suite('ChatQuestionCarouselPart', () => { assert.strictEqual(submittedAnswers?.get('q1'), 'default answer', 'Skip should return default values'); }); + test('only the person\'s own submission or dismissal is reported as theirs', () => { + const outcomes: { answers: unknown; byUser: boolean | undefined }[] = []; + const settle = (act: () => void) => { + createWidget(createMockCarousel([{ id: 'q1', type: 'text', title: 'Question 1', defaultValue: 'default answer' }], true)); + act(); + outcomes.push({ answers: submittedAnswers && [...submittedAnswers], byUser: submittedByUser }); + }; + + settle(() => widget.domNode.querySelector('.chat-question-submit-button')!.click()); + settle(() => widget.domNode.querySelector('.chat-question-close')!.click()); + settle(() => widget.domNode.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true }))); + // Defaults submitted when another message is sent, and a dismissal made for the person. + settle(() => widget.skip()); + settle(() => widget.ignore()); + + assert.deepStrictEqual(outcomes, [ + { answers: [['q1', 'default answer']], byUser: true }, + { answers: undefined, byUser: true }, + { answers: undefined, byUser: true }, + { answers: [['q1', 'default answer']], byUser: undefined }, + { answers: undefined, byUser: false }, + ]); + }); + test('skip fails when allowSkip is false', () => { const carousel = createMockCarousel([ { id: 'q1', type: 'text', title: 'Question 1' } @@ -1291,7 +1299,7 @@ suite('ChatQuestionCarouselPart', () => { } test('arrow keys move the selection and clamp at both ends', () => { - const list = createSelectWidget(3); + const list = createSelectWidget(3, false); const start = selectedIndex(); press(list, 40 /* DownArrow */, 'ArrowDown'); @@ -1328,6 +1336,48 @@ suite('ChatQuestionCarouselPart', () => { }); }); + test('down from the last option moves to the custom answer, and up from its start returns to the last option', () => { + const list = createSelectWidget(2); + const freeform = getAnswerEditor(); + const freeformInput = freeform.getDomNode()!.querySelector('.native-edit-context') ?? freeform.getDomNode()!.querySelector('textarea')!; + + press(list, 40 /* DownArrow */, 'ArrowDown'); + press(list, 40 /* DownArrow */, 'ArrowDown'); + const afterDown = { selected: selectedIndex(), freeformFocused: freeform.hasTextFocus() }; + + freeform.getModel()!.setValue('custom'); + freeform.setPosition({ lineNumber: 1, column: 7 }); + press(freeformInput, 38 /* UpArrow */, 'ArrowUp'); + const upWithinText = { selected: selectedIndex(), freeformFocused: freeform.hasTextFocus() }; + + freeform.setPosition({ lineNumber: 1, column: 1 }); + press(freeformInput, 38 /* UpArrow */, 'ArrowUp'); + const upAtStart = { selected: selectedIndex(), listFocused: mainWindow.document.activeElement === list, freeformValue: freeform.getValue() }; + press(list, 13 /* Enter */, 'Enter'); + const answer = submittedAnswers?.get('q1'); + + assert.deepStrictEqual({ afterDown, upWithinText, upAtStart, answer }, { + afterDown: { selected: -1, freeformFocused: true }, + upWithinText: { selected: -1, freeformFocused: true }, + upAtStart: { selected: 1, listFocused: true, freeformValue: 'custom' }, + answer: { selectedValue: 'b', freeformValue: undefined }, + }); + }); + + test('custom answer text that a selected option overrides survives navigating to another question and back', () => { + createWidget(createMockCarousel([ + { id: 'q1', type: 'singleSelect', title: 'Choose one', options: [{ id: 'a', label: 'Option A', value: 'a' }], allowFreeformInput: true }, + { id: 'q2', type: 'text', title: 'Anything else?' }, + ])); + + setAnswer('custom'); + // Selects the option, which goes to the next question + (widget.domNode.querySelector('.chat-question-list-item') as HTMLElement).click(); + (widget.domNode.querySelector('.chat-question-nav-prev') as HTMLElement).click(); + + assert.deepStrictEqual({ selected: selectedIndex(), freeform: getAnswerEditor().getValue() }, { selected: 0, freeform: 'custom' }); + }); + test('aria-activedescendant follows the selection', () => { const list = createSelectWidget(3); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatResourceGroupWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatResourceGroupWidget.test.ts index c0e90bc6d4b9..b015b3b3c0cb 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatResourceGroupWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatResourceGroupWidget.test.ts @@ -561,6 +561,21 @@ suite('ChatResourceGroupWidget', () => { }, { initialFilePills: 1, initialImages: 0, finalImages: 1, decoded: true, hoverImages: 1 }); }); + test('tool result thumbnails show an image placeholder, not a warning, until they are ready', async () => { + const widget = render([{ kind: 'data', uri: resource, mimeType: 'image/png', value: decodeBase64(imageData).buffer }], false); + const state = () => ({ + icons: [...widget.domNode.querySelectorAll('.image-attachment .chat-attached-context-pill .codicon')].map(icon => icon.className), + images: snapshot(widget).images, + }); + const loading = state(); + await waitForElement(widget.domNode, 'img.chat-attached-context-pill-image'); + + assert.deepStrictEqual({ loading, ready: state() }, { + loading: { icons: ['codicon codicon-file-media-compact'], images: 0 }, + ready: { icons: [], images: 1 }, + }); + }); + for (const inline of [false, true]) { test(`${inline ? 'selected generated-image previews' : 'tool result thumbnails'} keep one image copy menu`, async () => { const menus: Parameters[0][] = []; diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts index e121b14f8496..7d202e3b5277 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatSystemNotificationContentPart.test.ts @@ -18,6 +18,7 @@ import { agentMergeEnabledNotice, defaultAgentMergeConfiguration } from '../../. import { IHoverService } from '../../../../../../../platform/hover/browser/hover.js'; import { IMarkdownRenderer } from '../../../../../../../platform/markdown/browser/markdownRenderer.js'; import { getIconsStyleSheet } from '../../../../../../../platform/theme/browser/iconsStyleSheet.js'; +import '../../../../../../browser/media/style.css'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { ChatCollapsibleContentPart } from '../../../../browser/widget/chatContentParts/chatCollapsibleContentPart.js'; import { ChatSystemNotificationContentPart } from '../../../../browser/widget/chatContentParts/chatSystemNotificationContentPart.js'; @@ -292,6 +293,24 @@ suite('ChatSystemNotificationContentPart', () => { }); } + test('keeps the disclosure chevron compact under the workbench codicon size', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + const renderer: IMarkdownRenderer = { render: markdown => renderMarkdown(markdown) }; + const container = $('.monaco-workbench'); + container.style.setProperty('--vscode-codiconFontSize-compact', '12px'); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + const part = store.add(instantiationService.createInstance( + ChatSystemNotificationContentPart, + { kind: 'systemNotification', icon: Codicon.gitPullRequest, collapsible: true, content: new MarkdownString('Autopilot updated\n\n- Automatically Fix CI enabled') }, + renderer, + )); + container.appendChild(part.domNode); + const chevron = part.domNode.querySelector('.chat-collapsible-hover-chevron')!; + + assert.strictEqual(mainWindow.getComputedStyle(chevron).fontSize, '12px'); + }); + test('uses the ordinary compact icon and avoids a disclosure without details', () => { const disposables = store.add(new DisposableStore()); const instantiationService = workbenchInstantiationService(undefined, disposables); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatTerminalToolProgressPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatTerminalToolProgressPart.test.ts index d025957a4387..c70abf165643 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatTerminalToolProgressPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatTerminalToolProgressPart.test.ts @@ -1253,6 +1253,131 @@ suite('ChatTerminalToolProgressPart output scrollback', () => { }); }); +suite('ChatTerminalToolProgressPart completion', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + type Harness = Awaited>; + + /** A non-PTY command that is still running and already produced output. */ + function createRunningSource() { + const onDidChange = store.add(new Emitter()); + let exit: { readonly exitCode: number } | undefined; + const source: IChatTerminalOutputSource = { + onDidChange: onDidChange.event, + output: 'Live command output', + outputPosition: { generation: 1, start: 0 }, + get hasExited() { return !!exit; }, + get exitCode() { return exit?.exitCode; }, + }; + return { + source, + emitOutput: () => onDidChange.fire(), + exit: (exitCode: number) => { + exit = { exitCode }; + onDidChange.fire(); + }, + }; + } + + async function waitForExpandedOutput(part: ChatTerminalToolProgressPart): Promise { + await retry(async () => assert.ok(part.domNode.querySelector('.chat-terminal-output-container.expanded')), 10, 100); + } + + async function createAutoExpandedPart(harness: Harness, running: ReturnType, mode: TerminalFullOutputRenderingMode) { + const entry = harness.createPart({ mode, hasReference: false, runningInBackground: true }); + running.emitOutput(); + await waitForExpandedOutput(entry.part); + return entry; + } + + function expansion(part: ChatTerminalToolProgressPart, mode: TerminalFullOutputRenderingMode) { + return { + output: !!part.domNode.querySelector('.chat-terminal-output-container.expanded'), + wrapper: mode === 'plain' ? undefined : !part.domNode.classList.contains('chat-used-context-collapsed'), + }; + } + + for (const mode of ['plain', 'thinking'] as const) { + const collapsed = { output: false, wrapper: mode === 'plain' ? undefined : false }; + + test(`collapses automatically expanded output once the command exits in ${mode} mode`, async () => { + const running = createRunningSource(); + const harness = await createTerminalFullOutputHarness(store, running.source); + const { part } = await createAutoExpandedPart(harness, running, mode); + const whileRunning = expansion(part, mode); + running.exit(0); + await timeout(0); + assert.deepStrictEqual({ whileRunning, afterExit: expansion(part, mode) }, { + whileRunning: { output: true, wrapper: mode === 'plain' ? undefined : true }, + afterExit: collapsed, + }); + }); + + test(`waits for focus to leave the card before collapsing a finished command in ${mode} mode`, async () => { + const running = createRunningSource(); + const harness = await createTerminalFullOutputHarness(store, running.source); + const { part } = await createAutoExpandedPart(harness, running, mode); + const output = part.domNode.querySelector('.chat-terminal-output-container [tabindex="0"]'); + assert.ok(output); + output.focus(); + running.exit(0); + await timeout(0); + const whileFocused = { ...expansion(part, mode), focused: mainWindow.document.activeElement === output }; + // The window becoming inactive blurs the output without moving focus elsewhere + output.dispatchEvent(new FocusEvent('focusout', { bubbles: true, relatedTarget: null })); + await timeout(0); + const whileWindowInactive = expansion(part, mode); + output.blur(); + output.dispatchEvent(new FocusEvent('focusout', { bubbles: true, relatedTarget: null })); + await timeout(0); + const expanded = { output: true, wrapper: mode === 'plain' ? undefined : true }; + assert.deepStrictEqual({ whileFocused, whileWindowInactive, afterLeaving: expansion(part, mode) }, { + whileFocused: { ...expanded, focused: true }, + whileWindowInactive: expanded, + afterLeaving: collapsed, + }); + }); + + test(`starts collapsed when rebuilt for a completed tool call that expanded automatically in ${mode} mode`, async () => { + const running = createRunningSource(); + const harness = await createTerminalFullOutputHarness(store, running.source); + const original = await createAutoExpandedPart(harness, running, mode); + original.part.domNode.remove(); + original.part.dispose(); + // The tool call completes before its still attached output reports the exit + const data = original.invocation.toolSpecificData; + assert.ok(data?.kind === 'terminal'); + data.terminalCommandState = { exitCode: 0 }; + const rebuilt = harness.createPart({ mode, hasReference: false, invocation: original.invocation }); + running.emitOutput(); + await timeout(TerminalToolAutoExpandTimeout.DataEvent * 2); + assert.deepStrictEqual(expansion(rebuilt.part, mode), collapsed); + }); + } + + test('keeps a command the user expanded from its header once the command exits', async () => { + const running = createRunningSource(); + const harness = await createTerminalFullOutputHarness(store, running.source); + const { part } = await createAutoExpandedPart(harness, running, 'thinking'); + await harness.collapse(part, 'thinking'); + part.domNode.querySelector('.chat-used-context-label .monaco-button')?.click(); + await waitForExpandedOutput(part); + running.exit(0); + await timeout(0); + assert.deepStrictEqual(expansion(part, 'thinking'), { output: true, wrapper: true }); + }); + + test('keeps a failed command expanded when failures expand automatically', async () => { + const running = createRunningSource(); + const harness = await createTerminalFullOutputHarness(store, running.source); + harness.configurationService.setUserConfiguration(ChatConfiguration.AutoExpandToolFailures, true); + const { part } = await createAutoExpandedPart(harness, running, 'thinking'); + running.exit(1); + await timeout(0); + assert.deepStrictEqual(expansion(part, 'thinking'), { output: true, wrapper: true }); + }); +}); + suite('ChatTerminalToolProgressPart Auto-Expand Logic', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -1577,6 +1702,14 @@ suite('ChatTerminalToolOutputSection layout', () => { }); } + test('a collapse requested while the output loads is not undone by the pending expansion', async () => { + const section = createSection({ text: 'output' }); + const expansion = section.toggle(true); + await section.toggle(false); + await expansion; + assert.strictEqual(section.isExpanded, false); + }); + test('only enables Enter and View Full Output activation for completed output with an enabled action', async () => { let running = true; let opens = 0; diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatThinkingContentPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatThinkingContentPart.test.ts index 7b8081f37783..dacaa48827e7 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatThinkingContentPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatThinkingContentPart.test.ts @@ -5,7 +5,7 @@ import assert from 'assert'; import * as sinon from 'sinon'; -import { $, EventType } from '../../../../../../../base/browser/dom.js'; +import { $, EventType, isHTMLElement } from '../../../../../../../base/browser/dom.js'; import { timeout } from '../../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.js'; @@ -1935,8 +1935,8 @@ suite('ChatThinkingContentPart', () => { suite('Conversation sections', () => { const readFile = { id: 'read_file', displayName: 'Read file', modelDescription: 'Read file', source: ToolDataSource.Internal }; - function createConversationSection(content: IChatThinkingPart, complete = false): ChatThinkingContentPart { - const context = { ...createMockRenderContext(complete), suppressProgressShimmer: true, isConversation: true }; + function createConversationSection(content: IChatThinkingPart, complete = false, registerThinkingTitle?: IChatContentPartRenderContext['registerThinkingTitle']): ChatThinkingContentPart { + const context = { ...createMockRenderContext(complete), suppressProgressShimmer: true, isConversation: true, registerThinkingTitle }; const markdownRenderer: IMarkdownRenderer = { render: (markdown, options, target) => renderMarkdown(markdown, options, target) }; const part = createThinkingContentPart(content, context, markdownRenderer, complete); mainWindow.document.body.appendChild(part.domNode); @@ -1953,6 +1953,16 @@ suite('ChatThinkingContentPart', () => { return { title: button.textContent?.trim(), ariaLabel: button.ariaLabel, expanded: part.expanded.get() }; } + function getReasoningRowButtons(part: ChatThinkingContentPart): HTMLElement[] { + return Array.from(part.domNode.querySelectorAll('.chat-thinking-reasoning > .chat-used-context-label .monaco-button')); + } + + /** The open section's rows in order: reasoning rows by their title, everything else by its text. */ + function getRows(part: ChatThinkingContentPart): (string | undefined)[] { + return Array.from(part.domNode.querySelectorAll('.chat-thinking-collapsible > *'), row => + (row.querySelector('.chat-thinking-reasoning > .chat-used-context-label .monaco-button') ?? row).textContent?.trim()); + } + function appendTool(part: ChatThinkingContentPart, tool: IChatToolInvocation | IChatToolInvocationSerialized, label: string): void { part.appendItem(() => ({ domNode: $('div.test-tool', undefined, label) }), tool.toolId, tool); } @@ -1968,7 +1978,7 @@ suite('ChatThinkingContentPart', () => { test('collapses reasoning and tool calls into one section that names the current activity', async () => { const clock = sinon.useFakeTimers({ now: 10_000, toFake: ['Date'] }); store.add(toDisposable(() => clock.restore())); - const first = createThinkingPart('**Planning the fix**\n\nCheck the renderer.', 'first'); + const first: IChatThinkingPart = { ...createThinkingPart('**Planning the fix**\n\nCheck the renderer.', 'first'), reasoningTimingSource: 'provider' }; const part = createConversationSection(first); const thinking = snapshot(part); first.reasoningStartedAt = 10_000; @@ -1979,7 +1989,7 @@ suite('ChatThinkingContentPart', () => { const reading = snapshot(part); clock.tick(800); await tool.didExecuteTool(undefined); - const second = createThinkingPart('Compare the results.', 'second'); + const second: IChatThinkingPart = { ...createThinkingPart('Compare the results.', 'second'), reasoningTimingSource: 'provider' }; part.setupThinkingContainer(second); const thinkingAgain = snapshot(part); second.reasoningStartedAt = 14_000; @@ -1988,6 +1998,8 @@ suite('ChatThinkingContentPart', () => { part.finalizeTitleIfDefault(); const finished = snapshot(part); getButton(part).click(); + const rows = getRows(part); + getReasoningRowButtons(part)[0].click(); assert.deepStrictEqual({ thinking, @@ -1996,15 +2008,17 @@ suite('ChatThinkingContentPart', () => { finished, sectionClasses: ['chat-persistent-reasoning', 'chat-thinking-conversation'].filter(name => part.domNode.classList.contains(name)), headerIcons: Array.from(getButton(part).querySelectorAll('.codicon'), icon => [...icon.classList].filter(name => name !== 'codicon').join(' ')), - body: Array.from(part.domNode.querySelectorAll('.chat-thinking-collapsible p, .chat-thinking-collapsible .test-tool'), element => element.textContent?.trim()), + rows, + expandedReasoning: Array.from(part.domNode.querySelectorAll('.chat-thinking-reasoning p'), element => element.textContent?.trim()), }, { thinking: { title: 'Planning the fix', ariaLabel: 'Planning the fix', expanded: false }, reading: { title: 'Reading renderer.ts', ariaLabel: 'Reading renderer.ts', expanded: false }, - thinkingAgain: { title: 'Thinking', ariaLabel: 'Thinking', expanded: false }, - finished: { title: 'Planning the fix', ariaLabel: 'Planning the fix', expanded: false }, + thinkingAgain: { title: 'Thinking: Compare the results.', ariaLabel: 'Thinking: Compare the results.', expanded: false }, + finished: { title: 'Finished with 1 step - 4s', ariaLabel: 'Finished with 1 step - 4s', expanded: false }, sectionClasses: ['chat-thinking-conversation'], headerIcons: ['codicon-chevron-right-compact'], - body: ['Planning the fix', 'Check the renderer.', 'Read renderer.ts', 'Compare the results.'], + rows: ['Thought for 2s', 'Read renderer.ts', 'Thought for 2s'], + expandedReasoning: ['Planning the fix', 'Check the renderer.'], }); }); @@ -2026,7 +2040,7 @@ suite('ChatThinkingContentPart', () => { assert.deepStrictEqual({ searching, thinking, expanded, appendedWhileExpanded, collapsed: snapshot(part) }, { searching: 'Searching for the renderer', - thinking: 'Thinking', + thinking: 'Thinking: Compare the results.', expanded: { title: 'Working', ariaLabel: 'Working', expanded: true }, appendedWhileExpanded: 'Working', collapsed: { title: 'Reading renderer.ts', ariaLabel: 'Reading renderer.ts', expanded: false }, @@ -2076,8 +2090,8 @@ suite('ChatThinkingContentPart', () => { expanded: { title: 'Working', wipe: undefined }, collapsed: { title: 'Searching the workspace', wipe: undefined }, finishing: { title: 'Searching the workspace', wipe: 'out' }, - summary: { title: 'Finished thinking', wipe: 'in' }, - finished: { title: 'Finished thinking', wipe: undefined }, + summary: { title: '2 unfinished tool calls', wipe: 'in' }, + finished: { title: '2 unfinished tool calls', wipe: undefined }, }); }); @@ -2132,12 +2146,12 @@ suite('ChatThinkingContentPart', () => { visible, title: snapshot(part).title, movedOut: response.querySelectorAll('.test-tool').length, - body: Array.from(part.domNode.querySelectorAll('.chat-thinking-collapsible p, .chat-thinking-collapsible .test-tool'), element => element.textContent?.trim()), + rows: getRows(part), }, { visible: true, - title: 'Finished thinking', + title: 'Finished with 1 step', movedOut: 0, - body: ['Read read', 'Compare the results.'], + rows: ['Read read', 'Finished thinking'], }); }); @@ -2150,7 +2164,35 @@ suite('ChatThinkingContentPart', () => { assert.deepStrictEqual({ whitespace, text: snapshot(part).title }, { whitespace: 'Reading renderer.ts', - text: 'Thinking', + text: 'Thinking: Compare the results.', + }); + }); + + test('previews the whole first line of reasoning without a summary heading, on a single row', () => { + let hoverContent: HTMLElement | undefined; + mockHoverService.setupDelayedHover = (_target, options) => { + const content = typeof options === 'function' ? options().content : options.content; + hoverContent = isHTMLElement(content) ? content : undefined; + return toDisposable(() => { }); + }; + const part = createConversationSection(createThinkingPart('I need', 'preview')); + const getSingleRow = () => getButton(part).querySelector('.chat-thinking-title-single-row'); + const started = snapshot(part); + const startedElement = getSingleRow(); + part.updateThinking(createThinkingPart('I need to read `chatModel.ts` and **compare** it.\n\nThen run the tests.', 'preview')); + // The text streams into one element whose hover follows it, so the hover can be open meanwhile. + const firstLine = { ...snapshot(part), streamedInPlace: !!startedElement && startedElement === getSingleRow(), hover: hoverContent?.textContent }; + // The row ends a line that does not fit; the title itself is not cut short. + const longText = `${'word '.repeat(60)}end`; + part.setupThinkingContainer(createThinkingPart(`${longText}\n\nNext paragraph.`, 'long')); + const longLine = { title: snapshot(part).title, singleRow: !!getSingleRow() }; + appendTool(part, new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'read', undefined, {}), 'Read renderer.ts'); + + assert.deepStrictEqual({ started, firstLine, longLine, tool: { title: snapshot(part).title, singleRow: !!getSingleRow() } }, { + started: { title: 'Thinking: I need', ariaLabel: 'Thinking: I need', expanded: false }, + firstLine: { title: 'Thinking: I need to read chatModel.ts and compare it.', ariaLabel: 'Thinking: I need to read chatModel.ts and compare it.', expanded: false, streamedInPlace: true, hover: 'Thinking: I need to read chatModel.ts and compare it.' }, + longLine: { title: `Thinking: ${longText}`, singleRow: true }, + tool: { title: 'Reading renderer.ts', singleRow: false }, }); }); @@ -2197,24 +2239,28 @@ suite('ChatThinkingContentPart', () => { }); }); - test('finished sections report only recorded reasoning time and not tool time', () => { - type Case = { readonly reasoning: readonly { readonly startedAt?: number; readonly durationMs?: number; readonly text?: string }[]; readonly tools: readonly (readonly [startedAt?: number, completedAt?: number])[] }; + test('finished sections are named by their tool calls, or else their reasoning, with the time only when all of it was recorded', () => { + type Case = { readonly reasoning: readonly { readonly startedAt?: number; readonly durationMs?: number; readonly text?: string; readonly provider?: boolean }[]; readonly tools: readonly (readonly [startedAt?: number, completedAt?: number])[] }; const cases: Record = { shortReasoning: { reasoning: [{ startedAt: 1000, durationMs: 400 }], tools: [] }, reasoningWithoutStart: { reasoning: [{ durationMs: 2600 }], tools: [] }, textlessReasoning: { reasoning: [{ startedAt: 1000, durationMs: 2400, text: '\n' }], tools: [] }, textlessReasoningAndTools: { reasoning: [{ startedAt: 1000, durationMs: 2000, text: ' ' }], tools: [[3000, 4500]] }, toolsOnly: { reasoning: [], tools: [[1000, 2000], [3000, 66_000]] }, - reasoningAndTools: { reasoning: [{ startedAt: 1000, durationMs: 1500 }], tools: [[2500, 4000]] }, - reasoningWithoutStartAndTools: { reasoning: [{ durationMs: 2600 }], tools: [[1000, 2000], [3000]] }, - unfinishedTool: { reasoning: [{ startedAt: 1000, durationMs: 500 }], tools: [[1500]] }, + reasoningAndTools: { reasoning: [{ startedAt: 1000, durationMs: 1500, provider: true }], tools: [[2500, 4000]] }, + unattributedReasoningAndTools: { reasoning: [{ startedAt: 1000, durationMs: 1500 }], tools: [[2500, 4000]] }, + reasoningWithoutStartAndTools: { reasoning: [{ durationMs: 2600, provider: true }], tools: [[1000, 2000], [3000]] }, + unfinishedTool: { reasoning: [{ startedAt: 1000, durationMs: 500, provider: true }], tools: [[1500]] }, restoredReasoning: { reasoning: [{}], tools: [] }, restoredTools: { reasoning: [], tools: [[], []] }, - restoredReasoningThenLiveTool: { reasoning: [{}], tools: [[1000, 2000]] }, - liveReasoningThenRestoredTool: { reasoning: [{ startedAt: 1000, durationMs: 1500 }], tools: [[]] }, + restoredReasoningThenLiveTool: { reasoning: [{ provider: true }], tools: [[1000, 2000]] }, + liveReasoningThenRestoredTool: { reasoning: [{ startedAt: 1000, durationMs: 1500, provider: true }], tools: [[]] }, }; const titles = Object.fromEntries(Object.entries(cases).map(([name, { reasoning, tools }]) => { - const [first, ...rest] = reasoning.length ? reasoning.map(({ startedAt, durationMs, text }, index) => ({ ...createThinkingPart(text ?? `Reasoning ${index}`, `reasoning-${index}`), reasoningStartedAt: startedAt, reasoningDurationMs: durationMs })) : [createThinkingPart()]; + const [first, ...rest] = reasoning.length ? reasoning.map(({ startedAt, durationMs, text, provider }, index): IChatThinkingPart => ({ + ...createThinkingPart(text ?? `Reasoning ${index}`, `reasoning-${index}`), + reasoningTimingSource: provider ? 'provider' : undefined, reasoningStartedAt: startedAt, reasoningDurationMs: durationMs, + })) : [createThinkingPart()]; const part = createConversationSection(first, true); for (const [index, [startedAt, completedAt]] of tools.entries()) { appendTool(part, createSerializedTool(`tool-${index}`, startedAt, completedAt), `Read tool-${index}`); @@ -2230,26 +2276,131 @@ suite('ChatThinkingContentPart', () => { shortReasoning: 'Thought for 1s', reasoningWithoutStart: 'Thought for 3s', textlessReasoning: 'Finished thinking', - textlessReasoningAndTools: 'Finished thinking', - toolsOnly: 'Finished thinking', - reasoningAndTools: 'Thought for 2s', - reasoningWithoutStartAndTools: 'Thought for 3s', - unfinishedTool: 'Thought for 1s', + textlessReasoningAndTools: 'Finished with 1 step - 2s', + toolsOnly: 'Finished with 2 steps - 1m 4s', + reasoningAndTools: 'Finished with 1 step - 3s', + unattributedReasoningAndTools: 'Finished with 1 step', + reasoningWithoutStartAndTools: 'Finished with 2 steps', + unfinishedTool: 'Finished with 1 step', restoredReasoning: 'Finished thinking', - restoredTools: 'Finished thinking', - restoredReasoningThenLiveTool: 'Finished thinking', - liveReasoningThenRestoredTool: 'Thought for 2s', + restoredTools: 'Finished with 2 steps', + restoredReasoningThenLiveTool: 'Finished with 1 step', + liveReasoningThenRestoredTool: 'Finished with 1 step', + }); + }); + + test('finished sections summarize their tool activity and list each reasoning run by its time', () => { + const createReasoning = (text: string, id: string, reasoningDurationMs: number): IChatThinkingPart => ({ ...createThinkingPart(text, id), reasoningTimingSource: 'provider', reasoningDurationMs }); + const part = createConversationSection(createReasoning('Check the terminal.', 'first', 23_000), true); + const tools: [ChatToolInvocationSummary, startedAt: number, completedAt: number][] = [ + [{ kind: 'command' }, 30_000, 32_000], + [{ kind: 'unknown' }, 31_000, 33_000], + [{ kind: 'read', resources: [{ uri: URI.file('/workspace/File.ts') }] }, 40_000, 41_000], + ]; + for (const [index, [summary, startedAt, completedAt]] of tools.entries()) { + appendTool(part, { ...createSerializedTool(`tool-${index}`, startedAt, completedAt), summary }, `Tool ${index}`); + } + part.setupThinkingContainer(createReasoning('Wrap up.', 'second', 4000)); + part.finalizeTitleIfDefault(); + const title = snapshot(part).title; + getButton(part).click(); + + // The first two tool calls overlap, so their time counts once: 23s + 3s + 1s + 4s. + assert.deepStrictEqual({ title, rows: getRows(part) }, { + title: 'Ran 1 command, read File.ts, 1 other step - 31s', + rows: ['Thought for 23s', 'Tool 0', 'Tool 1', 'Tool 2', 'Thought for 4s'], + }); + }); + + test('lists reasoning as rows only while the open section has other items', () => { + const part = createConversationSection(createThinkingPart('Check the renderer.', 'first')); + getButton(part).click(); + const alone = getRows(part); + const tool = new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'read', undefined, {}); + appendTool(part, tool, 'Read renderer.ts'); + const withTool = getRows(part); + // The renderer moves a tool call out of the section the same way, such as one that needs confirmation. + part.domNode.querySelector('.test-tool')?.parentElement?.remove(); + part.removeMaterializedItem(tool.toolCallId); + + assert.deepStrictEqual({ alone, withTool, aloneAgain: getRows(part) }, { + alone: ['Check the renderer.'], + withTool: ['Finished thinking', 'Read renderer.ts'], + aloneAgain: ['Check the renderer.'], + }); + }); + + test('keeps keyboard focus in the section as its reasoning moves into and out of a row', () => { + const part = createConversationSection(createThinkingPart('Check [the renderer](https://example.com/renderer).', 'first')); + getButton(part).click(); + const link = part.domNode.querySelector('.chat-thinking-collapsible a'); + assert.ok(link); + const isFocused = (element: HTMLElement) => mainWindow.document.activeElement === element; + const removeTool = (tool: ChatToolInvocation) => { + part.domNode.querySelector('.test-tool')?.parentElement?.remove(); + part.removeMaterializedItem(tool.toolCallId); + }; + link.focus(); + const focusedAlone = isFocused(link); + const first = new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'first', undefined, {}); + appendTool(part, first, 'Read renderer.ts'); + const inRow = { rows: getRows(part), rowsExpanded: getReasoningRowButtons(part).map(button => button.ariaExpanded), linkFocused: isFocused(link) }; + removeTool(first); + const aloneAgain = { rows: getRows(part), linkFocused: isFocused(link) }; + const second = new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'second', undefined, {}); + appendTool(part, second, 'Read renderer.ts'); + getReasoningRowButtons(part)[0].focus(); + removeTool(second); + + assert.deepStrictEqual({ focusedAlone, inRow, aloneAgain, afterFocusedRowLeft: { rows: getRows(part), sectionHeaderFocused: isFocused(getButton(part)) } }, { + focusedAlone: true, + inRow: { rows: ['Finished thinking', 'Read renderer.ts'], rowsExpanded: ['true'], linkFocused: true }, + aloneAgain: { rows: ['Check the renderer.'], linkFocused: true }, + afterFocusedRowLeft: { rows: ['Check the renderer.'], sectionHeaderFocused: true }, + }); + }); + + test('a reasoning row says Thinking until its run records how long it thought', () => { + const part = createConversationSection(createThinkingPart()); + appendTool(part, new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'read', undefined, {}), 'Read renderer.ts'); + getButton(part).click(); + const reasoning = createThinkingPart('Compare the results.', 'compare'); + part.setupThinkingContainer(reasoning); + const thinking = getRows(part); + part.updateReasoningTiming({ ...reasoning, reasoningDurationMs: 2000 }); + + assert.deepStrictEqual({ thinking, thought: getRows(part) }, { + thinking: ['Read renderer.ts', 'Thinking'], + thought: ['Read renderer.ts', 'Thought for 2s'], + }); + }); + + test('a finished section adds its time once its last tool call records it', async () => { + const clock = sinon.useFakeTimers({ now: 10_000, toFake: ['Date'] }); + store.add(toDisposable(() => clock.restore())); + const part = createConversationSection({ ...createThinkingPart('**Planning the fix**\n\nCheck the renderer.', 'plan'), reasoningTimingSource: 'provider', reasoningDurationMs: 2000 }); + const tool = new ChatToolInvocation({ invocationMessage: 'Reading renderer.ts' }, readFile, 'read', undefined, {}); + appendTool(part, tool, 'Read renderer.ts'); + part.finalizeTitleIfDefault(); + const running = snapshot(part).title; + clock.tick(3000); + await tool.didExecuteTool(undefined); + + assert.deepStrictEqual({ running, completed: snapshot(part).title }, { + running: '1 unfinished tool call', + completed: 'Finished with 1 step - 5s', }); }); - test('split array reasoning does not combine distinct source durations', () => { - const cases: Record = { + test('split array reasoning is one row per source and only combines the durations of provider-recorded runs', () => { + const cases: Record = { equalDurations: { parts: [ { kind: 'thinking', value: ['First', 'Second'], reasoningDurationMs: 1200 }, { kind: 'thinking', value: ['Third', 'Fourth'], reasoningDurationMs: 1200 }, ], title: 'Finished thinking', + rows: ['Thought for 2s', 'Thought for 2s'], }, knownSpan: { parts: [ @@ -2257,6 +2408,7 @@ suite('ChatThinkingContentPart', () => { { kind: 'thinking', value: ['Third', 'Fourth'], reasoningStartedAt: 5000, reasoningDurationMs: 1200 }, ], title: 'Finished thinking', + rows: ['Thought for 2s', 'Thought for 2s'], }, unknownTiming: { parts: [ @@ -2264,9 +2416,18 @@ suite('ChatThinkingContentPart', () => { { kind: 'thinking', value: ['Third', 'Fourth'] }, ], title: 'Finished thinking', + rows: ['Thought for 2s', 'Finished thinking'], + }, + providerRuns: { + parts: [ + { kind: 'thinking', value: ['First', 'Second'], reasoningTimingSource: 'provider', reasoningDurationMs: 1200 }, + { kind: 'thinking', value: ['Third', 'Fourth'], reasoningTimingSource: 'provider', reasoningDurationMs: 1200 }, + ], + title: 'Thought for 3s', + rows: ['Thought for 2s', 'Thought for 2s'], }, }; - const titles = Object.fromEntries(Object.entries(cases).map(([name, { parts }]) => { + const sections = Object.fromEntries(Object.entries(cases).map(([name, { parts }]) => { const [first, ...rest] = parts.flatMap(source => (Array.isArray(source.value) ? source.value : [source.value ?? '']) .map(value => ({ source, rendered: { ...source, value } }))); const part = createConversationSection(first.rendered, true); @@ -2275,10 +2436,12 @@ suite('ChatThinkingContentPart', () => { part.setupThinkingContainer(rendered, source); } part.finalizeTitleIfDefault(); - return [name, snapshot(part).title]; + const title = snapshot(part).title; + getButton(part).click(); + return [name, { title, rows: getRows(part) }]; })); - assert.deepStrictEqual(titles, Object.fromEntries(Object.entries(cases).map(([name, { title }]) => [name, title]))); + assert.deepStrictEqual(sections, Object.fromEntries(Object.entries(cases).map(([name, { title, rows }]) => [name, { title, rows }]))); }); test('replacing a split reasoning fragment updates the recorded duration', () => { @@ -2296,25 +2459,31 @@ suite('ChatThinkingContentPart', () => { }); }); - test('does not request a title without viewport registration or remove reasoning headings', async () => { - let modelSelections = 0; - mockLanguageModelsService.selectLanguageModels = async () => { - modelSelections++; - return []; + test('a finished section is never named by a reasoning heading or a generated title, and keeps its headings in the details', () => { + let registrations = 0; + const registerThinkingTitle = () => { + registrations++; + return toDisposable(() => { }); }; - const part = createConversationSection(createThinkingPart('**Evaluating code**\n\nCheck the renderer.\n\n**Reviewing build processes**\n\nCheck the build.'), true); - part.finalizeTitleIfDefault(); - await timeout(0); - part.expandContent(); + const sections: Record = { + loneHeading: { text: '**Planning the fix**\n\nCheck the renderer.' }, + severalHeadings: { text: '**Evaluating code**\n\nCheck the renderer.\n\n**Reviewing build processes**\n\nCheck the build.' }, + savedTitle: { text: 'Check the renderer.', generatedTitle: 'Reviewed the renderer' }, + }; + const actual = Object.fromEntries(Object.entries(sections).map(([name, { text, generatedTitle }]) => { + const content: IChatThinkingPart = { ...createThinkingPart(text, name), generatedTitle, reasoningTimingSource: 'provider', reasoningDurationMs: 2000 }; + const part = createConversationSection(content, false, registerThinkingTitle); + part.finalizeTitleIfDefault(); + const title = snapshot(part).title; + part.expandContent(); + return [name, { title, savedTitle: content.generatedTitle, body: Array.from(part.domNode.querySelectorAll('.chat-thinking-collapsible p'), paragraph => paragraph.textContent?.trim()) }]; + })); - assert.deepStrictEqual({ - title: snapshot(part).title, - modelSelections, - body: Array.from(part.domNode.querySelectorAll('.chat-thinking-collapsible p'), paragraph => paragraph.textContent?.trim()), - }, { - title: 'Finished thinking', - modelSelections: 0, - body: ['Evaluating code', 'Check the renderer.', 'Reviewing build processes', 'Check the build.'], + assert.deepStrictEqual({ registrations, ...actual }, { + registrations: 0, + loneHeading: { title: 'Thought for 2s', savedTitle: undefined, body: ['Planning the fix', 'Check the renderer.'] }, + severalHeadings: { title: 'Thought for 2s', savedTitle: undefined, body: ['Evaluating code', 'Check the renderer.', 'Reviewing build processes', 'Check the build.'] }, + savedTitle: { title: 'Thought for 2s', savedTitle: 'Reviewed the renderer', body: ['Check the renderer.'] }, }); }); @@ -2325,14 +2494,13 @@ suite('ChatThinkingContentPart', () => { mockConfigurationService.setUserConfiguration('chat.agent.thinkingStyle', ThinkingDisplayMode.Collapsed); }); - for (const layout of ['legacy', 'persistent', 'conversation']) { + for (const layout of ['legacy', 'persistent']) { test(`a single extracted header is the completed title without generation (${layout})`, () => { let registrations = 0; const content = createThinkingPart('**Reviewed implementation details**\n\nThe full reasoning remains here.'); const part = createThinkingContentPart(content, { ...createMockRenderContext(true), suppressProgressShimmer: layout !== 'legacy', - isConversation: layout === 'conversation', registerThinkingTitle: () => { registrations++; return toDisposable(() => { }); }, }, mockMarkdownRenderer, true); part.finalizeTitleIfDefault(); @@ -2354,7 +2522,6 @@ suite('ChatThinkingContentPart', () => { const part = createThinkingContentPart(content, { ...createMockRenderContext(false), suppressProgressShimmer: layout !== 'legacy', - isConversation: layout === 'conversation', registerThinkingTitle: (_header, getRequest, acceptTitle, newlyCompleted) => { prepare = getRequest; eligible = newlyCompleted; @@ -2393,7 +2560,6 @@ suite('ChatThinkingContentPart', () => { const part = createThinkingContentPart(first, { ...createMockRenderContext(false), suppressProgressShimmer: layout !== 'legacy', - isConversation: layout === 'conversation', registerThinkingTitle: (_header, getRequest, accept, newlyCompleted) => { registered++; eligible = newlyCompleted; @@ -2444,7 +2610,7 @@ suite('ChatThinkingContentPart', () => { }); } - test('reuses generated headers in every thinking and progress style without model requests', async () => { + test('reuses generated headers in every thinking style, with and without persistent progress, without model requests', async () => { let modelSelections = 0; mockLanguageModelsService.selectLanguageModels = async () => { modelSelections++; @@ -2455,11 +2621,10 @@ suite('ChatThinkingContentPart', () => { let durationRows = 0; for (const thinkingStyle of Object.values(ThinkingDisplayMode)) { mockConfigurationService.setUserConfiguration(ChatConfiguration.ThinkingStyle, thinkingStyle); - for (const progress of ['legacy', 'persistent', 'conversation']) { + for (const progress of ['legacy', 'persistent']) { const context = { ...createMockRenderContext(true), suppressProgressShimmer: progress !== 'legacy', - isConversation: progress === 'conversation', }; for (const split of [false, true]) { const values = ['**Reviewing code**\n\nDetails.', '**Planning tests**\n\nMore details.']; @@ -2486,12 +2651,42 @@ suite('ChatThinkingContentPart', () => { } await timeout(0); assert.deepStrictEqual({ titles, durationRows, modelSelections }, { - titles: Array.from({ length: Object.values(ThinkingDisplayMode).length * 3 * 2 }, () => 'Previously generated summary - 2s'), + titles: Array.from({ length: Object.values(ThinkingDisplayMode).length * 2 * 2 }, () => 'Previously generated summary - 2s'), durationRows: 0, modelSelections: 0, }); }); + test('generated and saved titles drop their closing period', () => { + let acceptTitle: ((title: string) => void) | undefined; + const createTimedPart = (generatedTitle?: string): IChatThinkingPart => ({ + ...createThinkingPart('Compare both approaches'), generatedTitle, reasoningTimingSource: 'provider', reasoningDurationMs: 2000, + }); + const context = { suppressProgressShimmer: true }; + const generated = createTimedPart(); + const generatedPart = createThinkingContentPart(generated, { + ...createMockRenderContext(false), ...context, + registerThinkingTitle: (_header, _getRequest, accept) => { + acceptTitle = accept; + return toDisposable(() => { }); + }, + }, mockMarkdownRenderer, false); + generatedPart.finalizeTitleIfDefault(); + assert.ok(acceptTitle); + acceptTitle('Reviewed plan for removing old chat settings and renaming.'); + const saved = createTimedPart('Reviewed both approaches...'); + const savedPart = createThinkingContentPart(saved, { ...createMockRenderContext(true), ...context }, mockMarkdownRenderer, true); + savedPart.finalizeTitleIfDefault(); + + assert.deepStrictEqual({ + generated: { header: generatedPart.domNode.querySelector('.monaco-button')?.textContent, title: generated.generatedTitle }, + saved: { header: savedPart.domNode.querySelector('.monaco-button')?.textContent, title: saved.generatedTitle }, + }, { + generated: { header: 'Reviewed plan for removing old chat settings and renaming - 2s', title: 'Reviewed plan for removing old chat settings and renaming' }, + saved: { header: 'Reviewed both approaches - 2s', title: 'Reviewed both approaches' }, + }); + }); + test('generated titles use only complete provider-recorded reasoning durations', () => { const cases = [ { name: 'recorded runs', provider: true, durations: [1200, 1800], title: 'Reviewed results - 3s', labels: [] }, @@ -2510,7 +2705,6 @@ suite('ChatThinkingContentPart', () => { const part = createThinkingContentPart(first, { ...createMockRenderContext(true), suppressProgressShimmer: true, - isConversation: true, }, mockMarkdownRenderer, true); for (const content of rest) { part.setupThinkingContainer(content); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolConfirmationSubPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolConfirmationSubPart.test.ts index 67b49ab548cc..234ffb461b7e 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolConfirmationSubPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatContentParts/chatToolConfirmationSubPart.test.ts @@ -141,9 +141,10 @@ suite('ToolConfirmationSubPart', () => { test(`preserves the compact plain-text display with ${JSON.stringify(input)} input`, () => { const { part, renderedInputs } = renderConfirmation('Review this tool call.', input); assert.deepStrictEqual({ - messageVisible: part.domNode.textContent?.includes('Review this tool call.'), + // The message region takes its bottom spacing from the paragraph. + paragraphs: [...part.domNode.querySelectorAll('.chat-confirmation-widget-message p')].map(paragraph => paragraph.textContent), inputs: renderedInputs.length, - }, { messageVisible: true, inputs: 0 }); + }, { paragraphs: ['Review this tool call.'], inputs: 0 }); }); test(`keeps Markdown-looking reasons literal with ${JSON.stringify(input)} input`, () => { @@ -204,6 +205,28 @@ suite('ToolConfirmationSubPart', () => { }); } + test('shows where a terminal command runs, with control and format characters escaped', () => { + const workingDirectory = '/work/api\n\nWorking directory: /work/web\u202e'; + const { part, renderedInputs } = renderConfirmation('', undefined, undefined, { + kind: 'terminal', + commandLine: { original: './test.sh' }, + language: 'bash', + editable: false, + executionTarget: { workingDirectory, environment: 'remote' }, + }); + const target = part.domNode.querySelector('.chat-confirmation-message-terminal-target'); + const shown = '/work/api\\u{a}\\u{a}Working directory: /work/web\\u{202e}'; + assert.deepStrictEqual({ + values: [...target?.querySelectorAll('code') ?? []].map(code => code.textContent), + paragraphs: target?.querySelectorAll('p').length, + ariaLabel: renderedInputs[0].renderOptions?.editorOptions?.ariaLabel, + }, { + values: [shown, 'remote'], + paragraphs: 1, + ariaLabel: `Run in terminal?\nWorking directory: ${shown}, Environment: remote`, + }); + }); + test('keeps plain-text reasons literal when a disclaimer requires rich content', () => { const reason = '**Review** this tool call.'; const { part } = renderConfirmation(reason, undefined, new MarkdownString('A disclaimer.')); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts index dfb5061ed1ce..e85ae69a805f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts @@ -30,6 +30,7 @@ suite('ChatFindWidget', () => { getTemplateDataForRequestId: () => undefined, onDidRerenderRow: BaseEvent.None, editorsInUse: () => [], + getCodeBlockInfoForEditor: () => undefined, getScrollTop: () => 0, setScrollTop: () => { }, getRenderHeight: () => 0, @@ -179,6 +180,14 @@ suite('ChatFindWidget DOM highlighting', () => { assert.deepStrictEqual(findMatchRangesInDom(root, regex('needle'), 100, [editor]), []); }); + test('excludes marked preview chrome without shifting response matches', () => { + const root = document.createElement('div'); + root.innerHTML = '

Show Source in the response.

'; + assert.deepStrictEqual(findMatchRangesInDom(root, regex('Show Source'), 100).map(range => ({ + text: range.toString(), parent: range.startContainer.parentElement?.tagName, + })), [{ text: 'Show Source', parent: 'P' }]); + }); + test('returns no ranges when there is no text content', () => { const root = document.createElement('div'); assert.deepStrictEqual(findMatchRangesInDom(root, regex('needle'), 100), []); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatListRenderer.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatListRenderer.test.ts index 6d76b9145f91..377ab0c1f340 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatListRenderer.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatListRenderer.test.ts @@ -6,6 +6,9 @@ import assert from 'assert'; import * as sinon from 'sinon'; import * as dom from '../../../../../../base/browser/dom.js'; +import type { IManagedHoverContentOrFactory } from '../../../../../../base/browser/ui/hover/hover.js'; +import type { IHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate.js'; +import { getDefaultHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { mainWindow } from '../../../../../../base/browser/window.js'; import { Action, IAction, Separator } from '../../../../../../base/common/actions.js'; import { DeferredPromise, raceTimeout, retry, timeout } from '../../../../../../base/common/async.js'; @@ -47,6 +50,7 @@ import { IHoverService } from '../../../../../../platform/hover/browser/hover.js import { NullHoverService } from '../../../../../../platform/hover/test/browser/nullHoverService.js'; import { NullLogService } from '../../../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; +import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { ISharedWebContentExtractorService } from '../../../../../../platform/webContentExtractor/common/webContentExtractor.js'; import { IUserInteractionService, MockUserInteractionService } from '../../../../../../platform/userInteraction/browser/userInteractionService.js'; import { URI } from '../../../../../../base/common/uri.js'; @@ -70,8 +74,10 @@ import { AcceptToolConfirmationActionId, registerChatToolActions, SkipToolConfir import { buildPlanReviewProgressContent, ChatListItemRenderer, endsWithActiveSubagentContent, endsWithCompletedQuestionInteraction, formatCompletedResponseDisclosureLabel, formatResponseTokenStats, getCompletedResponseCollapseEndIndex, getFinalResponseStartIndex, getFinalResponseStartIndexAfterMovingResponseOutcomeTools, getPersistentActivityLabel, getPersistentBackgroundActivity, getPersistentProgressState, getTrailingProgressLabel, getVisibleCompletedResponseItemCount, getWorkingProgressRelevantParts, IChatListItemTemplate, isAnchorTarget, isBlockingToolState, isFinalResponseRendered, isWaitingForMcpServers, moveResponseOutcomeToolsAfterFinalResponse, reconcileChatItemHeight, renderChatRequestTimestamp, renderChatResponseDetails, shouldCollapseCompletedResponsePart, shouldCreateGroupedThinkingPart, shouldHideChatUserIdentity, shouldPinToolInvocationToThinking, shouldRenderInitialProgressiveContentImmediately, shouldScheduleInitialHeightChange, shouldShowFileChangesSummaryForSettings, shouldShowTurnPillsSummary, shouldStartNewCollapsedThinkingGroup } from '../../../browser/widget/chatListRenderer.js'; import { ChatWidget } from '../../../browser/widget/chatWidget.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { ChatAttachmentWidgetRegistry, IChatAttachmentWidgetRegistry } from '../../../browser/attachments/chatAttachmentWidgetRegistry.js'; import type { IChatRequestVariableEntry } from '../../../common/attachments/chatVariableEntries.js'; import { ChatInputPart } from '../../../browser/widget/input/chatInputPart.js'; +import { getGitHubIssueOrPullRequestAttachments } from '../../../browser/widget/input/editor/chatPasteProviders.js'; import { ChatToolConfirmationCarouselPart } from '../../../browser/widget/chatContentParts/toolInvocationParts/chatToolConfirmationCarouselPart.js'; import { ChatSubagentContentPart } from '../../../browser/widget/chatContentParts/chatSubagentContentPart.js'; import { getSubagentEditorResource, OpenSubagentChatActionViewItem } from '../../../browser/widget/chatContentParts/chatSubagentOpenChat.js'; @@ -93,10 +99,10 @@ import { ChatModel, ChatResponseResource, ISerializedChatDataReference, isSerial import { ChatSessionOperationLog } from '../../../common/model/chatSessionOperationLog.js'; import { getGeneratedImageResources } from '../../../common/chatImageExtraction.js'; import { ChatResponseResourceFileSystemProvider } from '../../../common/widget/chatResponseResourceFileSystemProvider.js'; -import { ChatViewModel, IChatPendingDividerViewModel, IChatRendererContent, IChatResponseViewModel, IChatViewModel, isRequestVM, isResponseVM } from '../../../common/model/chatViewModel.js'; +import { ChatViewModel, IChatPendingDividerViewModel, IChatRendererContent, IChatResponseViewModel, IChatViewModel, IChatWorkingProgress, isRequestVM, isResponseVM } from '../../../common/model/chatViewModel.js'; import { ChatToolInvocation } from '../../../common/model/chatProgressTypes/chatToolInvocation.js'; import { ChatAgentService, IChatAgentService } from '../../../common/participants/chatAgents.js'; -import { ChatRequestDynamicVariablePart, ChatRequestTextPart } from '../../../common/requestParser/chatParserTypes.js'; +import { ChatRequestDynamicVariablePart, ChatRequestSlashPromptPart, ChatRequestTextPart } from '../../../common/requestParser/chatParserTypes.js'; import { HookType } from '../../../common/promptSyntax/hookTypes.js'; import { ILanguageModelToolsService, IPreparedToolInvocation, IToolData, IToolResult, IToolResultInputOutputDetails, ToolDataSource, ToolInvocationPresentation } from '../../../common/tools/languageModelToolsService.js'; import { ILanguageModelToolsConfirmationService } from '../../../common/tools/languageModelToolsConfirmationService.js'; @@ -126,6 +132,8 @@ import { generateUuid } from '../../../../../../base/common/uuid.js'; import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { IResourceMultiDiffEditorInput, isResourceMultiDiffEditorInput, IUntypedEditorInput } from '../../../../../common/editor.js'; import { IEditorService } from '../../../../../services/editor/common/editorService.js'; +import { IWorkbenchGitHubService } from '../../../../../services/github/common/githubService.js'; +import { GitHubResourceDetailsResolver } from '../../../../github/browser/githubResourceDetails.js'; import { ChatAccessibilityProvider } from '../../../browser/accessibility/chatAccessibilityProvider.js'; import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; import { ChatSideChatService, IChatSideChatOrigin, IChatSideChatSelection, IChatSideChatService } from '../../../common/chatSideChatService.js'; @@ -189,7 +197,7 @@ suite('ChatListRenderer', () => { suite('getFinalResponseStartIndex', () => { for (const serialized of [false, true]) { - test(`completed response folding crosses only one trailing single-tool gap (serialized=${serialized})`, async () => { + test(`completed response folding crosses only one trailing single-tool gap and its reasoning (serialized=${serialized})`, async () => { const invocation = new ChatToolInvocation( { invocationMessage: 'Finish bookkeeping' }, { id: 'test_tool', displayName: 'Test Tool', modelDescription: 'Test tool', source: ToolDataSource.Internal }, @@ -207,6 +215,10 @@ suite('ChatListRenderer', () => { [thinking, markdown, tool, tool, summary], [markdown, tool, markdown, tool, summary], [markdown, tool, thinking, summary], + [tool, markdown, thinking, tool, thinking, summary], + [markdown, tool, thinking, tool, summary], + [markdown, thinking, summary], + [tool, thinking, summary], [tool, summary], [tool], ]; @@ -218,13 +230,39 @@ suite('ChatListRenderer', () => { { contiguous: 4, singleToolGap: 1 }, { contiguous: 4, singleToolGap: 4 }, { contiguous: 4, singleToolGap: 2 }, - { contiguous: 3, singleToolGap: 3 }, + { contiguous: 3, singleToolGap: 0 }, + { contiguous: 5, singleToolGap: 1 }, + { contiguous: 4, singleToolGap: 4 }, + { contiguous: 2, singleToolGap: 2 }, + { contiguous: 2, singleToolGap: 2 }, { contiguous: 1, singleToolGap: 1 }, { contiguous: undefined, singleToolGap: undefined }, ]); }); } + test('completed response folding does not keep an edit code block as the answer', async () => { + const tool = new ChatToolInvocation( + { invocationMessage: 'Verify the edit' }, + { id: 'test_tool', displayName: 'Test Tool', modelDescription: 'Test tool', source: ToolDataSource.Internal }, + 'verify', undefined, {}, + ); + await tool.didExecuteTool(undefined); + const editBlock = '```typescript\nfile:///workspace/progress.ts\nexport const enabled = true;\n```'; + const edit = { kind: 'markdownContent', content: new MarkdownString(`${editBlock}\n\n`) } as const; + const standaloneEdit = { kind: 'markdownContent', content: new MarkdownString('```\n\n```'), codeblockUri: { kind: 'codeblockUri', uri: URI.file('/workspace/progress.ts'), isEdit: true, isStandalone: true } } as const; + const editWithAnswer = { kind: 'markdownContent', content: new MarkdownString(`${editBlock}\n\nDetailed response`) } as const; + const thinking = { kind: 'thinking', value: 'Reasoning' } as const; + const summary = { kind: 'markdownContent', content: new MarkdownString('Task completed.') } as const; + const cases: IChatRendererContent[][] = [ + [tool, edit, thinking, tool, summary], + [tool, edit, tool, summary], + [tool, standaloneEdit, tool, summary], + [tool, editWithAnswer, thinking, tool, summary], + ]; + assert.deepStrictEqual(cases.map(content => getFinalResponseStartIndex(content, true)), [4, 3, 3, 1]); + }); + test('preserves the single-tool answer boundary when session outcomes move', async () => { const outcome = new ChatToolInvocation( { invocationMessage: 'Created session', toolSpecificData: { kind: 'sessionCreated', openLink: 'agent-host-session://local/created', label: 'Created session' } }, @@ -2445,6 +2483,36 @@ suite('ChatListRenderer', () => { }); })); + test('sticky progress measures placement once per frame while streaming renders repeat', async () => { + const { model, request, container, renderer, template, node } = createPersistentProgressRenderer(); + const sticky = dom.append(container, dom.$('.chat-sticky-progress.interactive-item-container.chat-persistent-progress')); + let outsideViewport = false; + let measurements = 0; + renderer.setWorkingProgressContainer(sticky, () => { + measurements++; + return outsideViewport; + }); + renderer.renderElement(node, 0, template); + const nextFrame = () => new Promise(resolve => dom.scheduleAtNextAnimationFrame(dom.getWindow(container), () => resolve())); + await nextFrame(); + const progress = container.querySelector('.chat-working-progress'); + measurements = 0; + + outsideViewport = true; + for (let i = 0; i < 20; i++) { + model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('More progress. ') }); + renderer.renderElement(node, 0, template); + } + const beforeFrame = { measurements, sticky: progress?.parentElement === sticky }; + await nextFrame(); + + assert.deepStrictEqual({ beforeFrame, measurements, sticky: progress?.parentElement === sticky }, { + beforeFrame: { measurements: 0, sticky: false }, + measurements: 1, + sticky: true, + }); + }); + test('sticky progress replaces a stale anchor when a hidden completed turn resumes', async () => { const { request, container, renderer, template, node } = createPersistentProgressRenderer(); const sticky = dom.append(container, dom.$('.chat-sticky-progress.interactive-item-container.chat-persistent-progress')); @@ -2577,8 +2645,8 @@ suite('ChatListRenderer', () => { }); suite('single-tool completed response collapse', () => { - async function addCompletionResponse({ model, request }: ReturnType, serialized: boolean): Promise { - for (const id of ['initial-work', 'follow-up-work', 'final-bookkeeping']) { + async function addCompletionResponse({ model, request }: ReturnType, serialized: boolean, reasonBeforeMarkdown = false, ids = ['initial-work', 'follow-up-work', 'final-bookkeeping']): Promise { + for (const id of ids) { const tool = new ChatToolInvocation( { invocationMessage: id, pastTenseMessage: id }, { id: 'test_tool', displayName: 'Test Tool', modelDescription: 'Test tool', source: ToolDataSource.Internal }, @@ -2587,6 +2655,9 @@ suite('ChatListRenderer', () => { await tool.didExecuteTool(undefined); model.acceptResponseProgress(request, serialized ? tool.toJSON() : tool); if (id !== 'initial-work') { + if (reasonBeforeMarkdown) { + model.acceptResponseProgress(request, { kind: 'thinking', value: `Reasoning after ${id}`, id: `reasoning-after-${id}` }); + } model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString(id === 'final-bookkeeping' ? 'Task completed.' : 'Detailed answer with the full analysis.'), @@ -2627,6 +2698,61 @@ suite('ChatListRenderer', () => { } } + // Conversation folds the earlier work into one section, which needs no disclosure. + for (const [progressVerbosity, collapsedLabel] of [[ChatProgressVerbosity.Verbose, 'Completed 3 steps'], [ChatProgressVerbosity.Compact, 'Completed 2 steps'], [ChatProgressVerbosity.Conversation, undefined]] as const) { + for (const initiallyComplete of [false, true]) { + test(`preserves the detailed answer when reasoning follows the final tool (${progressVerbosity}, restored=${initiallyComplete})`, async () => { + const setup = createPersistentProgressRenderer({ progressVerbosity, chatMode: ChatModeKind.Agent }); + const { disposables, configurationService, request, renderer, template, node } = setup; + configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, true); + await addCompletionResponse(setup, initiallyComplete, true); + if (!initiallyComplete) { + renderer.renderElement(node, 0, template); + } + request.response?.complete(); + renderer.renderElement(node, 0, template); + await new Promise(resolve => mainWindow.requestAnimationFrame(() => resolve())); + await timeout(0); + assert.deepStrictEqual({ + collapsedLabel: template.completedResponseDisclosure?.querySelector('summary')?.textContent, + visibleMarkdown: Array.from(template.value.querySelectorAll(':scope > .chat-markdown-part'), part => part.textContent?.trim()), + }, { + collapsedLabel, + visibleMarkdown: ['Detailed answer with the full analysis.', 'Task completed.'], + }); + disposables.dispose(); + }); + } + } + + test('waits for the closing summary to finish revealing before collapsing', async () => { + const setup = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent }); + const { disposables, configurationService, request, renderer, template, node } = setup; + configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, true); + configurationService.setUserConfiguration(ChatConfiguration.IncrementalRendering, true); + configurationService.setUserConfiguration(ChatConfiguration.IncrementalRenderingBuffering, 'word'); + const markdownParts = () => template.renderedParts?.filter(part => part instanceof ChatMarkdownContentPart) ?? []; + await addCompletionResponse(setup, false, true, ['initial-work', 'follow-up-work']); + renderer.renderElement(node, 0, template); + const answer = markdownParts()[0]; + if (!answer.isRenderComplete) { + await Event.toPromise(answer.onDidFinishRendering); + } + await addCompletionResponse(setup, false, true, ['final-bookkeeping']); + renderer.renderElement(node, 0, template); + const summary = markdownParts()[1]; + const revealing = markdownParts().map(part => !part.isRenderComplete); + request.response?.complete(); + renderer.renderElement(node, 0, template); + const collapsedWhileRevealing = !!template.completedResponseDisclosure; + if (!summary.isRenderComplete) { + await Event.toPromise(summary.onDidFinishRendering); + } + await timeout(0); + assert.deepStrictEqual({ revealing, collapsedWhileRevealing, collapsed: !!template.completedResponseDisclosure }, { revealing: [false, true], collapsedWhileRevealing: false, collapsed: true }); + disposables.dispose(); + }); + for (const permissionLevel of [ChatPermissionLevel.Default, ChatPermissionLevel.Autopilot]) { for (const subagent of [false, true]) { test(`keeps folding after a mode switch and history restoration (${permissionLevel}, subagent=${subagent})`, async () => { @@ -2846,6 +2972,71 @@ suite('ChatListRenderer', () => { }); suite('inline request attachments', () => { + for (const fontSize of [13, 18]) { + test(`aligns attachment pills and slash commands with the text of a request at chat font size ${fontSize}`, () => { + const { container, configurationService, model, request, viewModel, renderer, template, node } = createPersistentProgressRenderer(); + configurePersistentProgressTypography(container, fontSize); + container.style.fontFamily = 'sans-serif'; + // Rows are in the list of a chat widget, where pills take the smaller font of the chat. + template.rowContainer.classList.add('interactive-list'); + configurationService.setUserConfiguration(ChatConfiguration.InlineAttachmentsEnabled, true); + request.response?.complete(); + const file: IChatRequestVariableEntry = { kind: 'file', id: 'file', name: 'a.ts', value: URI.file('/src/a.ts') }; + const text = '#attachment:a.ts /explain short wrapping text.'; + model.addRequest({ + text, + parts: [ + new ChatRequestDynamicVariablePart(new OffsetRange(0, 16), new Range(1, 1, 1, 17), '#attachment:a.ts', file.id, undefined, file.value, undefined, undefined, true, false, undefined, true), + new ChatRequestTextPart(new OffsetRange(16, 17), new Range(1, 17, 1, 18), ' '), + new ChatRequestSlashPromptPart(new OffsetRange(17, 25), new Range(1, 18, 1, 26), 'explain'), + new ChatRequestTextPart(new OffsetRange(25, text.length), new Range(1, 26, 1, text.length + 1), text.slice(25)), + ], + }, { variables: [file] }, 0); + renderer.renderElement({ ...node, element: viewModel.getItems().filter(isRequestVM)[1] }, 2, template); + const attachment = template.value.querySelector('.chat-request-inline-attachment'); + const label = attachment?.querySelector('.label-name'); + const command = template.value.querySelector('.chat-resource-widget'); + const commandText = command?.firstElementChild; + const paragraph = template.value.querySelector('p'); + const bubble = template.value.querySelector('.rendered-markdown'); + assert.ok(attachment && label && command && commandText && paragraph && bubble); + + // An inline block without content sits on the baseline of the text that it is added to. + const baselineOf = (addProbe: (probe: HTMLElement) => void) => { + const probe = dom.$('span'); + probe.style.display = 'inline-block'; + addProbe(probe); + const baseline = probe.getBoundingClientRect().bottom; + probe.remove(); + return baseline; + }; + + const geometry = [720, 240, 720].map(width => { + container.style.width = `${width}px`; + renderer.layout(width); + const attachmentBounds = attachment.getBoundingClientRect(); + const commandBounds = command.getBoundingClientRect(); + const textBaseline = baselineOf(probe => command.after(probe)); + return { + baselineOffsets: [baselineOf(probe => label.append(probe)) - textBaseline, baselineOf(probe => commandText.append(probe)) - textBaseline], + boxOffsets: [attachmentBounds.top - commandBounds.top, attachmentBounds.bottom - commandBounds.bottom], + overflows: bubble.scrollWidth > bubble.clientWidth, + wraps: paragraph.getBoundingClientRect().height > fontSize * 2, + }; + }); + assert.deepStrictEqual(geometry.map(({ baselineOffsets, boxOffsets, ...rest }) => ({ + onBaseline: baselineOffsets.every(offset => Math.abs(offset) < 0.5), + // A pill keeps its height in a larger font, in which a slash command is taller than it. + level: fontSize > 13 || boxOffsets.every(offset => Math.abs(offset) < 1), + ...rest, + })), [ + { onBaseline: true, level: true, overflows: false, wraps: false }, + { onBaseline: true, level: true, overflows: false, wraps: true }, + { onBaseline: true, level: true, overflows: false, wraps: false }, + ], JSON.stringify(geometry)); + }); + } + for (const restored of [false, true]) { test(`shows an image above the request as well as its pill in the text (restored=${restored})`, () => { const { configurationService, model, request, viewModel, renderer, template, node } = createPersistentProgressRenderer(); @@ -2871,6 +3062,69 @@ suite('ChatListRenderer', () => { }, { above: ['image'], inline: ['image', 'file'], links: 0 }); }); } + + for (const [inline, path, kind] of [[true, 'issues', 'issue'], [false, 'pull', 'pullRequest']] as const) { + test(`previews and opens the GitHub ${kind} of a request instead of editing the request (inline=${inline})`, async () => { + const { disposables, instantiationService, configurationService, model, request, viewModel, renderer, template, node } = createPersistentProgressRenderer({ rendererOptions: { editable: true } }); + configurationService.setUserConfiguration(ChatConfiguration.InlineAttachmentsEnabled, inline); + configurationService.setUserConfiguration('chat.editRequests', 'inline'); + instantiationService.stub(IWorkbenchGitHubService, upcastPartial({ onDidChangeDefaultClient: Event.None })); + instantiationService.stub(IChatAttachmentWidgetRegistry, new ChatAttachmentWidgetRegistry()); + const opened: string[] = []; + instantiationService.stub(IOpenerService, upcastPartial({ + open: async resource => { + opened.push(resource.toString()); + return true; + }, + })); + const previews = new Map(); + instantiationService.stub(IHoverService, { + ...NullHoverService, + setupManagedHover: (delegate, target, content) => { + previews.set(target, { delegate, content }); + return NullHoverService.setupManagedHover(delegate, target, content); + }, + }); + const createHover = sinon.stub(GitHubResourceDetailsResolver.prototype, 'createHover').returns({ + hover: { content: () => dom.$('div') }, + pillHover: { element: () => dom.$('div') }, + prefetch: () => { }, + }); + disposables.add(toDisposable(() => createHover.restore())); + let editRequests = 0; + disposables.add(renderer.onDidClickRequest(() => editRequests++)); + request.response?.complete(); + const link = `https://github.com/microsoft/vscode/${path}/346788`; + const text = `Investigate ${link} and https://github.com/microsoft/vscode/${path}/346789`; + model.addRequest({ text, parts: [new ChatRequestTextPart(new OffsetRange(0, text.length), new Range(1, 1, 1, text.length + 1), text)] }, { variables: [...getGitHubIssueOrPullRequestAttachments(text)] }, 0); + renderer.renderElement({ ...node, element: viewModel.getItems().filter(isRequestVM)[1] }, 2, template); + const [pill, otherPill] = template.value.querySelectorAll('.chat-attached-context-attachment'); + assert.ok(pill && otherPill); + + const preview = previews.get(pill); + if (typeof preview?.content === 'function') { + preview.content(); + } + pill.click(); + pill.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + await timeout(0); + const reference = createHover.firstCall?.args[1]; + assert.deepStrictEqual({ + inline: !!pill.closest('.rendered-markdown .chat-request-inline-attachment'), + preview: { kind: reference?.kind, target: reference?.target }, + // Moving between the pills of a request shows the next preview without waiting again. + sharesInstantHover: !!preview && preview.delegate === previews.get(otherPill)?.delegate && preview.delegate !== getDefaultHoverDelegate('element'), + opened, + editRequests, + }, { + inline, + preview: { kind, target: { owner: 'microsoft', repo: 'vscode', number: 346788 } }, + sharesInstantHover: true, + opened: [link, link], + editRequests: 0, + }); + }); + } }); function configureTerminalProgressRenderer({ instantiationService, configurationService }: Pick, 'instantiationService' | 'configurationService'>): void { @@ -7867,6 +8121,105 @@ suite('ChatListRenderer', () => { }); })); + function createPersistentWorkingPart(fixture: ReturnType, working: IChatWorkingProgress): ChatWorkingProgressContentPart { + const context = new class extends mock() { + override readonly element = fixture.response; + override readonly content = [working]; + override readonly contentIndex = 0; + override readonly suppressProgressShimmer = true; + }(); + return fixture.disposables.add(fixture.instantiationService.createInstance(ChatWorkingProgressContentPart, working, fixture.instantiationService.get(IMarkdownRendererService), context)); + } + + test('persistent progress rotates a generic phrase after ten seconds without a new piece', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createPersistentProgressRenderer(); + fixture.configurationService.setUserConfiguration(ChatConfiguration.ThinkingPhrases, { mode: 'replace', phrases: ['Reviewing', 'Considering'] }); + const part = createPersistentWorkingPart(fixture, { kind: 'working', isActive: true, progressStep: 0 }); + const first = part.workingLabel; + const other = first === 'Reviewing' ? 'Considering' : 'Reviewing'; + await timeout(9999); + const beforeRotation = part.workingLabel; + await timeout(1); + const rotated = part.workingLabel; + await timeout(5000); + part.updateWorkingContent(undefined, true, false, 1); + const newPiece = part.workingLabel; + await timeout(9999); + const beforeNewPieceRotation = part.workingLabel; + await timeout(1); + const afterNewPieceRotation = part.workingLabel; + // A piece that arrives within the minimum dwell keeps the phrase, and still restarts the ten seconds. + await timeout(500); + part.updateWorkingContent(undefined, true, false, 2); + await timeout(9999); + const beforeSamePhraseRotation = part.workingLabel; + await timeout(1); + const afterSamePhraseRotation = part.workingLabel; + part.updateWorkingContent(new MarkdownString('Waiting for your response'), true, true, 2); + await timeout(30_000); + const blocked = part.workingLabel; + part.updateWorkingContent(undefined, true, false, 2); + const resumed = part.workingLabel; + fixture.request.response?.complete(); + await timeout(30_000); + + assert.deepStrictEqual({ + beforeRotation, rotated, newPiece, beforeNewPieceRotation, afterNewPieceRotation, + beforeSamePhraseRotation, afterSamePhraseRotation, blocked, resumed, afterCompletion: part.workingLabel, + }, { + beforeRotation: first, rotated: other, newPiece: first, beforeNewPieceRotation: first, afterNewPieceRotation: other, + beforeSamePhraseRotation: other, afterSamePhraseRotation: first, blocked: 'Waiting for your response', resumed: first, afterCompletion: first, + }); + })); + + test('persistent progress keeps rotating generic phrases until it reports prolonged inactivity', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createPersistentProgressRenderer(); + fixture.configurationService.setUserConfiguration(ChatConfiguration.ThinkingPhrases, { mode: 'replace', phrases: ['Reviewing', 'Considering'] }); + const part = createPersistentWorkingPart(fixture, { kind: 'working', isActive: true, progressStep: 0, showDelayedProgressMessage: true }); + const first = part.workingLabel; + const other = first === 'Reviewing' ? 'Considering' : 'Reviewing'; + const delayed = 'This is taking a little longer than usual'; + await timeout(5000); + const labelsEveryTenSeconds: string[] = []; + for (let index = 0; index < 12; index++) { + labelsEveryTenSeconds.push(part.workingLabel); + await timeout(10_000); + } + + assert.deepStrictEqual(labelsEveryTenSeconds, [first, other, first, other, first, other, first, other, first, delayed, delayed, delayed]); + })); + + test('persistent progress wipes to a new label and reports it at once', () => { + const fixture = createPersistentProgressRenderer(); + fixture.instantiationService.stub(IAccessibilityService, new class extends TestAccessibilityService { + override isMotionReduced() { return false; } + }()); + const part = createPersistentWorkingPart(fixture, { kind: 'working', content: new MarkdownString('Working'), isActive: true }); + fixture.container.appendChild(part.domNode); + const getWipe = (label: Element) => label.classList.contains('chat-activity-label-wipe-out') ? 'out' : label.classList.contains('chat-activity-label-wipe-in') ? 'in' : undefined; + const state = () => { + const label = part.domNode.querySelector('.progress-step'); + assert.ok(label); + return { text: label.textContent?.trim(), wipe: getWipe(label), reported: part.workingLabel }; + }; + const endWipe = () => { + const label = part.domNode.querySelector('.progress-step'); + assert.ok(label); + label.dispatchEvent(new AnimationEvent(dom.EventType.ANIMATION_END, { animationName: `chat-activity-label-wipe-${getWipe(label)}` })); + }; + part.updateWorkingContent(new MarkdownString('Waiting for your response')); + const leaving = state(); + endWipe(); + const arriving = state(); + endWipe(); + + assert.deepStrictEqual({ leaving, arriving, settled: state() }, { + leaving: { text: 'Working', wipe: 'out', reported: 'Waiting for your response' }, + arriving: { text: 'Waiting for your response', wipe: 'in', reported: 'Waiting for your response' }, + settled: { text: 'Waiting for your response', wipe: undefined, reported: 'Waiting for your response' }, + }); + }); + for (const incremental of [false, true]) { test(`persistent progress reports provider background shells instead of inactivity (incremental=${incremental})`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { const backgroundShellCount = observableValue('backgroundShellCount', 0); @@ -9163,6 +9516,8 @@ suite('ChatListRenderer', () => { async function addCompletedProgressResponse({ model, request }: ReturnType, finalText = 'Final review.\n\nAll checks passed.'): Promise { model.acceptResponseProgress(request, { kind: 'thinking', id: 'first', value: '**Checking the implementation**\nReview the current changes.' }); + // Several tools follow this text, so it folds with the work instead of being kept as a single-tool tail. + model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('Checking the remaining paths.\n\nComparing the results.') }); for (const id of ['first', 'second']) { const tool = new ChatToolInvocation( { invocationMessage: `Read ${id} file` }, @@ -9172,7 +9527,6 @@ suite('ChatListRenderer', () => { model.acceptResponseProgress(request, tool); await tool.didExecuteTool(undefined); } - model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('Checking the remaining paths.\n\nComparing the results.') }); model.acceptResponseProgress(request, { kind: 'thinking', id: 'second', value: '**Verifying the result**\nCheck the external reference.' }); const externalTool = new ChatToolInvocation( { invocationMessage: 'Read external reference' }, @@ -9287,6 +9641,80 @@ suite('ChatListRenderer', () => { } } + for (const withEdits of [false, true]) { + test(`conversation progress discloses completed steps like its sections (edits=${withEdits})`, async () => { + const describeDisclosure = async (verbosity: ChatProgressVerbosity) => { + const setup = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent, progressVerbosity: verbosity }); + const { container, configurationService, model, request, renderer, template, node } = setup; + configurePersistentProgressTypography(container, 13); + configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, true); + if (withEdits) { + model.acceptResponseProgress(request, { + kind: 'externalEdit', uri: URI.file('/workspace/renderer.ts'), editKind: 'edit', diff: { added: 14, removed: 3 }, + }); + } + await addCompletedProgressResponse(setup); + request.response?.complete(); + renderer.renderElement(node, 0, template); + await timeout(0); + const disclosure = template.completedResponseDisclosure; + const summary = disclosure?.querySelector('summary'); + const chevron = summary?.querySelector('.chat-collapsible-hover-chevron'); + const label = summary?.querySelector('.monaco-button-mdlabel'); + assert.ok(disclosure && summary && chevron && label); + const pointsDown = () => Math.round(new DOMMatrixReadOnly(mainWindow.getComputedStyle(chevron).transform).b) === 1; + const closed = { + order: [...summary.querySelectorAll('.chat-collapsible-hover-chevron, .monaco-button-mdlabel, .chat-edit-stats')] + .map(part => part === chevron ? 'chevron' : part === label ? 'label' : 'edits'), + chevronShownAtRest: mainWindow.getComputedStyle(chevron).opacity === '1', + pointsDown: pointsDown(), + }; + summary.click(); + await timeout(0); + const section = disclosure.querySelector(':scope > .chat-thinking-conversation'); + if (!section) { + return { ...closed, pointsDownWhenOpen: pointsDown() }; + } + const sectionHeader = section.querySelector(':scope > .chat-used-context-label'); + const sectionChevron = sectionHeader?.querySelector('.monaco-button > .codicon'); + const sectionLabel = sectionHeader?.querySelector('.monaco-button-mdlabel'); + assert.ok(sectionHeader && sectionChevron && sectionLabel); + // An open chevron is placed differently from a closed one, so the section opens to compare like with like. + sectionHeader.querySelector('.monaco-button')?.click(); + const offset = (part: Element, from: Element) => part.getBoundingClientRect().left - from.getBoundingClientRect().left; + const center = (part: Element, from: Element) => offset(part, from) + part.getBoundingClientRect().width / 2; + const same = (a: number, b: number) => Math.abs(a - b) < 0.05; + const rail = mainWindow.getComputedStyle(disclosure, '::details-content'); + const hook = mainWindow.getComputedStyle(sectionHeader, '::after'); + const open = { + pointsDownWhenOpen: pointsDown(), + sharesSectionGutter: same(center(chevron, summary), center(sectionChevron, section)) && same(offset(label, summary), offset(sectionLabel, section)), + sharesSectionChevronColor: mainWindow.getComputedStyle(chevron).color === mainWindow.getComputedStyle(sectionChevron).color, + stepsUnderLabel: same(offset(section, summary), offset(label, summary)), + railUnderChevron: same(parseFloat(rail.marginInlineStart) + parseFloat(rail.borderInlineStartWidth) / 2, center(chevron, summary)), + hookUnderSectionChevron: same(parseFloat(hook.left) + parseFloat(hook.borderLeftWidth) / 2, center(sectionChevron, section)), + }; + container.style.width = '140px'; + renderer.layout(140); + return { + ...closed, ...open, + containedWhenNarrow: summary.scrollWidth <= summary.clientWidth + 1 && same(offset(label, summary), offset(sectionLabel, section)), + }; + }; + + assert.deepStrictEqual({ + compact: await describeDisclosure(ChatProgressVerbosity.Compact), + conversation: await describeDisclosure(ChatProgressVerbosity.Conversation), + }, { + compact: { order: ['label', ...(withEdits ? ['edits'] : []), 'chevron'], chevronShownAtRest: false, pointsDown: false, pointsDownWhenOpen: true }, + conversation: { + order: ['chevron', 'label', ...(withEdits ? ['edits'] : [])], chevronShownAtRest: true, pointsDown: false, pointsDownWhenOpen: true, + sharesSectionGutter: true, sharesSectionChevronColor: true, stepsUnderLabel: true, railUnderChevron: true, hookUnderSectionChevron: true, containedWhenNarrow: true, + }, + }); + }); + } + for (const fontSize of [13, 18]) { for (const withEdits of [false, true]) { test(`completed response summaries stay on one line with duration (fontSize=${fontSize}, edits=${withEdits})`, async () => { @@ -10757,7 +11185,7 @@ suite('ChatListRenderer', () => { }); }); - test('late reasoning timing never adds inline durations to a finalized conversation group', async () => { + test('late reasoning timing names its row in a finalized conversation group', async () => { const { model, request, renderer, template, node } = createPersistentProgressRenderer({ progressVerbosity: ChatProgressVerbosity.Conversation }); model.acceptResponseProgress(request, { kind: 'thinking', id: 'first', value: 'First run', reasoningTimingSource: 'provider' }, false, true); const tool = new ChatToolInvocation( @@ -10773,7 +11201,7 @@ suite('ChatListRenderer', () => { const section = template.renderedParts?.find(part => part instanceof ChatThinkingContentPart); assert.ok(section instanceof ChatThinkingContentPart); section.expandContent(); - const labels = () => Array.from(section.domNode.querySelectorAll('.chat-thinking-run-duration'), element => element.textContent); + const labels = () => Array.from(section.domNode.querySelectorAll('.chat-thinking-reasoning > .chat-used-context-label .monaco-button'), element => element.textContent); const before = labels(); model.acceptResponseProgress(request, { kind: 'thinking', id: 'first', value: '', reasoningTimingSource: 'provider', reasoningDurationMs: 5000 }); @@ -10785,12 +11213,12 @@ suite('ChatListRenderer', () => { before, after, durations: request.response?.entireResponse.value.flatMap(part => part.kind === 'thinking' ? [part.reasoningDurationMs] : []), - }, { before: [], after: [], durations: [5000, 12_000] }); + }, { before: ['Finished thinking', 'Thought for 12s'], after: ['Thought for 5s', 'Thought for 12s'], durations: [5000, 12_000] }); }); for (const progressVerbosity of [ChatProgressVerbosity.Compact, ChatProgressVerbosity.Verbose, ChatProgressVerbosity.Conversation]) { for (const boundary of ['markdown', 'tool'] as const) { - test(`reasoning timing survives reload without inline duration rows (${progressVerbosity}, ${boundary})`, async () => { + test(`reasoning timing survives reload (${progressVerbosity}, ${boundary})`, async () => { const setup = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent, progressVerbosity }); setup.configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, false); const diagnostics: string[] = []; @@ -10811,7 +11239,6 @@ suite('ChatListRenderer', () => { return { labels: Array.from(current.template.value.querySelectorAll('.chat-used-context-label .monaco-button'), label => label.textContent?.trim()) .filter(label => label?.startsWith('Thought for ')), - inlineDurationRows: current.template.value.querySelectorAll('.chat-thinking-run-duration').length, runs: current.request.response?.entireResponse.value.flatMap(part => part.kind === 'thinking' && part.value ? [{ value: part.value, duration: part.reasoningDurationMs }] : []), }; @@ -10842,9 +11269,9 @@ suite('ChatListRenderer', () => { const restored = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent, progressVerbosity, initialData: { value, serializer: new ChatSessionOperationLog() } }); restored.configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, false); + // Reasoning names its time in its own header, or in its row of a conversation section with other items. const expected = { - labels: progressVerbosity === ChatProgressVerbosity.Conversation && boundary === 'tool' ? [] : ['Thought for 5s', 'Thought for 12s'], - inlineDurationRows: 0, + labels: ['Thought for 5s', 'Thought for 12s'], runs: [{ value: 'First run', duration: 5000 }, { value: 'Second run', duration: 12_000 }], }; assert.deepStrictEqual({ before, after: await snapshot(restored) }, { before: expected, after: expected }, diagnostics.join('\n')); @@ -10853,7 +11280,7 @@ suite('ChatListRenderer', () => { } } - test('conversation progress collapses reasoning and tool calls into one section with its extracted heading', async () => { + test('conversation progress collapses reasoning and tool calls into one section named by its activity, then by what it did', async () => { const clock = sinon.useFakeTimers({ now: 1_000_000, toFake: ['Date'] }); store.add(toDisposable(() => clock.restore())); const { model, request, renderer, template, node } = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent, progressVerbosity: ChatProgressVerbosity.Conversation }); @@ -10898,13 +11325,13 @@ suite('ChatListRenderer', () => { reading, thinkingAgain, finished, - rows: [...getSection()?.querySelectorAll(':scope .chat-thinking-collapsible > *') ?? []].map(row => row.classList.contains('chat-thinking-tool-wrapper') ? 'tool' : 'reasoning'), + rows: [...getSection()?.querySelectorAll(':scope .chat-thinking-collapsible > *') ?? []].map(row => row.matches('.chat-thinking-tool-wrapper:not(.chat-thinking-reasoning-row)') ? 'tool' : 'reasoning'), toolChains: template.value.querySelectorAll('.chat-tool-chain').length, }, { thinking: { title: 'Planning the fix', expanded: 'false', order: ['section', 'progress'] }, reading: { title: 'Reading renderer.ts', expanded: 'false', order: ['section', 'progress'] }, - thinkingAgain: { title: 'Thinking', expanded: 'false', order: ['section', 'progress'] }, - finished: { title: 'Planning the fix', expanded: 'false', order: ['section', 'markdown', 'progress'] }, + thinkingAgain: { title: 'Thinking: Compare the results.', expanded: 'false', order: ['section', 'progress'] }, + finished: { title: 'Finished with 1 step', expanded: 'false', order: ['section', 'markdown', 'progress'] }, rows: ['reasoning', 'tool', 'reasoning'], toolChains: 0, }); @@ -10961,7 +11388,7 @@ suite('ChatListRenderer', () => { assert.deepStrictEqual({ sectionVisible: !!section && section.getClientRects().length > 0, standaloneTools: template.value.querySelectorAll(':scope > .chat-tool-invocation-part').length, - rows: [...section?.querySelectorAll(':scope .chat-thinking-collapsible > *') ?? []].map(row => row.classList.contains('chat-thinking-tool-wrapper') ? 'tool' : 'reasoning'), + rows: [...section?.querySelectorAll(':scope .chat-thinking-collapsible > *') ?? []].map(row => row.matches('.chat-thinking-tool-wrapper:not(.chat-thinking-reasoning-row)') ? 'tool' : 'reasoning'), }, { sectionVisible: true, standaloneTools: 0, @@ -10988,12 +11415,60 @@ suite('ChatListRenderer', () => { title: sections[0]?.querySelector(':scope > .chat-used-context-label .monaco-button')?.textContent?.trim(), }, { sections: 1, - title: 'Thinking', + title: 'Thinking: the results.', }); request.response?.complete(); renderer.renderElement(node, 0, template); }); + for (const fontSize of [13, 18]) { + test(`conversation headers keep their height and text line as titles gain file pills, code, and links at chat font size ${fontSize}`, () => { + const { instantiationService, container, model, request, renderer, template, node } = createPersistentProgressRenderer({ chatMode: ChatModeKind.Agent, progressVerbosity: ChatProgressVerbosity.Conversation }); + instantiationService.stub(IChatMarkdownAnchorService, new class extends mock() { + override register() { return Disposable.None; } + }()); + configurePersistentProgressTypography(container, fontSize); + renderer.layout(720); + const headers = [ + 'Editing files', + new MarkdownString('Replacing 2 lines with 5 lines in [](file:///workspace/renderer.ts)'), + new MarkdownString('Running `git status --short`'), + new MarkdownString('Fetched [the guide](https://example.com/guide)'), + 'Editing files', + ].map((invocationMessage, index) => { + model.acceptResponseProgress(request, new ChatToolInvocation( + { invocationMessage }, + { id: `tool${index}`, displayName: 'Tool', modelDescription: 'Tool', source: ToolDataSource.Internal }, + `call${index}`, undefined, {}, + )); + renderer.renderElement(node, 0, template); + const header = template.value.querySelector(':scope > .chat-thinking-conversation > .chat-used-context-label'); + const title = header?.querySelector('.chat-thinking-title-detail > p') ?? header?.querySelector('.monaco-button-mdlabel'); + assert.ok(header && title); + const bounds = header.getBoundingClientRect(); + return { + title: header.textContent, + filePills: header.querySelectorAll('.chat-inline-anchor-widget').length, + height: bounds.height, + baseline: getTextBaseline(title) - bounds.top, + }; + }); + request.response?.complete(); + renderer.renderElement(node, 0, template); + + assert.deepStrictEqual(headers.map(({ height, baseline, ...header }) => ({ + ...header, + sameLine: Math.abs(height - headers[0].height) < 0.05 && Math.abs(baseline - headers[0].baseline) < 0.05, + })), [ + { title: 'Editing files', filePills: 0, sameLine: true }, + { title: 'Replacing 2 lines with 5 lines in renderer.ts', filePills: 1, sameLine: true }, + { title: 'Running git status --short', filePills: 0, sameLine: true }, + { title: 'Fetched the guide', filePills: 0, sameLine: true }, + { title: 'Editing files', filePills: 0, sameLine: true }, + ], JSON.stringify(headers)); + }); + } + async function createExpandedPersistentPreview(source: 'thinking' | 'tools', options: { incremental?: boolean; reducedMotion?: boolean } = {}) { const setup = createPersistentProgressRenderer({ progressVerbosity: ChatProgressVerbosity.Compact }); const { configurationService, container, model, request, renderer, template, node } = setup; @@ -15300,20 +15775,29 @@ suite('ChatListRenderer', () => { } for (const carousel of [true, false]) { - for (const selectedOption of ['save-sandbox-path', 'skip']) { - test(`preserves sandbox path file confirmation option ${selectedOption} ${carousel ? 'in the carousel' : 'inline'}`, () => { + for (const selectedOption of ['save-session-sandbox-path', 'save-workspace-sandbox-path', 'save-sandbox-path', 'skip']) { + test(`preserves sandbox path file confirmation option ${selectedOption} ${carousel ? 'in the carousel' : 'inline'}`, async () => { const context = createConfirmationRenderer(); context.configurationService.setUserConfiguration(ChatConfiguration.ToolConfirmationCarousel, carousel); + let menuActions: readonly IAction[] = []; + context.instantiationService.stub(IContextMenuService, new class extends mock() { + override showContextMenu(delegate: Parameters[0]): void { + assert.ok(delegate.getActions); + menuActions = delegate.getActions(); + } + }()); const resource = URI.file('/outside/new.ts').toString(); const tool = toolCallStateToInvocation({ status: ToolCallStatus.PendingConfirmation, toolCallId: 'sandbox-write', toolName: 'apply_patch', displayName: 'Apply Patch', - confirmationTitle: 'Add to user sandbox settings and retry?', + confirmationTitle: 'Allow sandbox path access and retry?', invocationMessage: 'Allow read/write access to the folder.', options: [ - { id: 'save-sandbox-path', label: 'Allow', kind: ConfirmationOptionKind.Approve, group: 1 }, + { id: 'save-session-sandbox-path', label: 'Allow for This Session', kind: ConfirmationOptionKind.Approve, group: 1 }, + { id: 'save-workspace-sandbox-path', label: 'Allow for This Workspace', kind: ConfirmationOptionKind.Approve, group: 1 }, + { id: 'save-sandbox-path', label: 'Allow for This User', kind: ConfirmationOptionKind.Approve, group: 1 }, { id: 'skip', label: 'Skip', kind: ConfirmationOptionKind.Deny, group: 2 }, ], edits: { items: [{ after: { uri: resource, content: { uri: resource } } }] }, @@ -15322,19 +15806,32 @@ suite('ChatListRenderer', () => { context.render(); const container = carousel ? context.confirmationContainer : context.template.value; - const buttons = Array.from(container.querySelectorAll('.chat-confirmation-widget-buttons .monaco-button')); - const labels = buttons.map(button => button.textContent?.replaceAll('\u00a0', ' ')); + const primary = container.querySelector('.chat-confirmation-widget-buttons .monaco-button'); + const dropdown = container.querySelector('.monaco-dropdown-button'); + const skip = container.querySelector('.chat-confirmation-widget-buttons .monaco-button.secondary'); + assert.ok(primary && dropdown && skip); + const labels = [primary, skip].map(button => button.textContent?.replaceAll('\u00a0', ' ')); const hasFilePreview = !!container.querySelector('.chat-modified-files-confirmation-list'); - const button = buttons[selectedOption === 'skip' ? 1 : 0]; - assert.ok(button); - button.click(); + if (selectedOption === 'save-workspace-sandbox-path') { + dropdown.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + } else { + dropdown.click(); + } + const moreActions = menuActions.filter(action => !(action instanceof Separator)); + if (selectedOption === 'save-workspace-sandbox-path' || selectedOption === 'save-sandbox-path') { + await moreActions[selectedOption === 'save-workspace-sandbox-path' ? 0 : 1].run(); + } else { + (selectedOption === 'skip' ? skip : primary).click(); + } assert.deepStrictEqual({ labels, + moreLabels: moreActions.map(action => action.label), hasFilePreview, confirmed: IChatToolInvocation.executionConfirmedOrDenied(tool), }, { - labels: ['Allow', 'Skip'], + labels: ['Allow for This Session', 'Skip'], + moreLabels: ['Allow for This Workspace', 'Allow for This User'], hasFilePreview: true, confirmed: { type: ToolConfirmKind.UserAction, diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts index 9ac75aface04..a636b64ddaca 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts @@ -20,7 +20,7 @@ import { constObservable } from '../../../../../../base/common/observable.js'; import { isMacintosh } from '../../../../../../base/common/platform.js'; import { isEqual } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { Range } from '../../../../../../editor/common/core/range.js'; import { OffsetRange } from '../../../../../../editor/common/core/ranges/offsetRange.js'; @@ -45,8 +45,11 @@ import { IViewDescriptorService } from '../../../../../common/views.js'; import { IEditorResolverService, RegisteredEditorPriority } from '../../../../../services/editor/common/editorResolverService.js'; import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; import { TestFileService, workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; -import { IChatAccessibilityService, isChatContextMenuActionContext } from '../../../browser/chat.js'; +import { IChatAccessibilityService, IChatWidgetService, isChatContextMenuActionContext } from '../../../browser/chat.js'; +import { IWebviewElement, IWebviewService } from '../../../../webview/browser/webview.js'; import { IChatOutputRendererService } from '../../../browser/chatOutputItemRenderer.js'; +import { IChatOutputPartStateCache, IOutputPartState } from '../../../browser/widget/chatContentParts/chatOutputPartStateCache.js'; +import { ChatFindWidget, IChatFindHost } from '../../../browser/widget/chatFind/chatFindWidget.js'; import { IChatResponseFileChangesService } from '../../../browser/chatResponseFileChangesService.js'; import { ChatAttachmentWidgetRegistry, IChatAttachmentWidgetRegistry } from '../../../browser/attachments/chatAttachmentWidgetRegistry.js'; import { computeScrollDownState, getAnchoredScrollTop, AutoScrollHolds, UserToggleResizeState, ChatListWidget, IChatListWidgetOptions, getChatContextMenuTargetContext, isChatBackgroundContextMenuTarget, shouldShowChatLinkOpenWith } from '../../../browser/widget/chatListWidget.js'; @@ -68,6 +71,8 @@ import { MockChatSessionsService } from '../../common/mockChatSessionsService.js import { MockLanguageModelToolsService } from '../../common/tools/mockLanguageModelToolsService.js'; import { IChatModelFeedbackSurveyService } from '../../../browser/feedbackSurvey/chatModelFeedbackSurveyService.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { IChatLayoutService } from '../../../common/widget/chatLayoutService.js'; +import { ChatLayoutService } from '../../../browser/widget/chatLayoutService.js'; import { MockChatModelFeedbackSurveyService } from '../feedbackSurvey/mockChatModelFeedbackSurveyService.js'; import { IChatRequestVariableEntry } from '../../../common/attachments/chatVariableEntries.js'; import { PROMPT_TIMELINE_STICKY_SCROLL_SETTING } from '../../../common/promptTimeline.js'; @@ -376,6 +381,7 @@ suite('ChatListWidget', () => { editor: { fontSize: 13, fontFamily: 'default', fontWeight: 'normal', lineHeight: 0, wordWrap: 'on' }, }); configurationService.setUserConfiguration(ChatConfiguration.IncrementalRendering, false); + configurationService.setUserConfiguration(ChatConfiguration.HtmlPreviewEnabled, true); configurationService.setUserConfiguration(ChatConfiguration.CollapseCompletedResponses, true); configurationService.setUserConfiguration('chat.checkpoints.enabled', false); configurationService.setUserConfiguration('chat.checkpoints.showFileChanges', false); @@ -591,6 +597,213 @@ suite('ChatListWidget', () => { ]); }); + function stubHtmlPreviewWebviews(instantiationService: ReturnType) { + const webviews: { marker: HTMLElement; disposed: boolean }[] = []; + instantiationService.stub(IChatLayoutService, store.add(instantiationService.createInstance(ChatLayoutService))); + const states = new Map(); + instantiationService.stub(IChatOutputPartStateCache, { + get: key => states.get(key), + set: (key, state) => states.set(key, state), + }); + instantiationService.stub(IChatWidgetService, { getWidgetBySessionResource: () => undefined }); + instantiationService.stub(IWebviewService, { + createWebviewElement: () => { + const state = { marker: dom.$('div'), disposed: false }; + webviews.push(state); + return new class extends mock() { + override readonly onFatalError = Event.None; + override readonly onDidWheel = Event.None; + override readonly intrinsicContentSize = constObservable({ width: 500, height: 180 }); + override setHtml(): void { } + override setContextKeyService(): void { } + override mountTo(parent: HTMLElement): void { + parent.appendChild(state.marker); + } + override reinitializeAfterDismount(): void { } + override dispose(): void { + state.disposed = true; + state.marker.remove(); + } + }(); + }, + }); + return webviews; + } + + test('HTML preview Find reveals matching source and ignores preview controls', async () => { + const { disposables, instantiationService, model, viewModel, container, widget } = createWidget({ rendererOptions: { renderHtmlPreviews: true } }, undefined, true); + stubHtmlPreviewWebviews(instantiationService); + const text = 'Report'; + const request = model.addRequest({ + text, + parts: [new ChatRequestTextPart(new OffsetRange(0, text.length), new Range(1, 1, 1, text.length + 1), text)], + }, { variables: [] }, 0); + model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('```html-preview\n

FindNeedle

\n```\n\nShow Source refers to the artifact.') }); + request.response?.complete(); + widget.refresh(); + widget.layout(300, 500); + await waitForStableLayout(widget); + const host: IChatFindHost = { + transcriptDomNode: widget.domNode, + getItems: () => viewModel.getItems(), + onDidChangeContent: Event.None, + reveal: (item, relativeTop) => widget.reveal(item, relativeTop), + getTemplateDataForRequestId: id => widget.getTemplateDataForRequestId(id), + onDidRerenderRow: widget.onDidRerender, + editorsInUse: () => widget.editorsInUse(), + getCodeBlockInfoForEditor: uri => widget.getCodeBlockInfoForEditor(uri), + getScrollTop: () => widget.scrollTop, + setScrollTop: top => { widget.scrollTop = top; }, + getRenderHeight: () => widget.renderHeight, + getViewportAnchorItemId: () => widget.lastVisibleItem?.id, + }; + const find = disposables.add(instantiationService.createInstance(ChatFindWidget, host)); + find.show('Show Source'); + await retry(async () => { + const current = mainWindow.CSS.highlights.get('chat-find-current-match'); + assert.ok(current && current.size > 0); + }, 10, 50); + const ranges = [...mainWindow.CSS.highlights.get('chat-find-current-match')!]; + const sourceStillHidden = container.querySelector('.chat-html-preview-source')?.hidden; + find.show('FindNeedle'); + await retry(async () => { + assert.strictEqual(container.querySelector('.chat-html-preview-source')?.hidden, false); + }, 10, 50); + await waitForStableLayout(widget); + const findKeepsFocus = mainWindow.document.activeElement === find.getDomNode().querySelector('input'); + const sourceVisible = container.querySelector('.chat-html-preview-source')!.getBoundingClientRect().height > 0; + assert.deepStrictEqual({ + sourceStillHidden, + findKeepsFocus, + sourceVisible, + matchParents: ranges.map(range => range.startContainer.parentElement?.tagName), + }, { sourceStillHidden: true, findKeepsFocus: true, sourceVisible: true, matchParents: ['P'] }); + find.hide(); + }); + + for (const supportsHtmlPreviews of [false, true]) { + test(`updates existing responses when HTML previews are enabled or disabled (supported: ${supportsHtmlPreviews})`, async () => { + const { instantiationService, configurationService, model, container, widget } = createWidget( + { rendererOptions: { renderHtmlPreviews: supportsHtmlPreviews } }, + configuration => configuration.setUserConfiguration(ChatConfiguration.HtmlPreviewEnabled, false), + true, + ); + const webviews = stubHtmlPreviewWebviews(instantiationService); + const text = 'Show a report'; + const request = model.addRequest({ + text, + parts: [new ChatRequestTextPart(new OffsetRange(0, text.length), new Range(1, 1, 1, text.length + 1), text)], + }, { variables: [] }, 0); + model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('```html-preview\n

Report

\n```') }); + request.response?.complete(); + widget.refresh(); + widget.layout(300, 500); + await waitForStableLayout(widget); + const state = () => ({ + preview: !!container.querySelector('.chat-html-preview'), + source: [...container.querySelectorAll('.view-line')].some(line => !line.closest('[hidden]') && line.textContent?.includes('

Report

')), + activeWebviews: webviews.filter(webview => !webview.disposed && webview.marker.isConnected).length, + }); + const states = [state()]; + for (const enabled of [true, false, true]) { + await configurationService.setUserConfiguration(ChatConfiguration.HtmlPreviewEnabled, enabled); + configurationService.onDidChangeConfigurationEmitter.fire(upcastPartial({ + affectedKeys: new Set([ChatConfiguration.HtmlPreviewEnabled]), + affectsConfiguration: key => key === ChatConfiguration.HtmlPreviewEnabled, + })); + await waitForStableLayout(widget); + states.push(state()); + } + assert.deepStrictEqual(states, [false, true, false, true].map(enabled => ({ + preview: supportsHtmlPreviews && enabled, + source: !supportsHtmlPreviews || !enabled, + activeWebviews: supportsHtmlPreviews && enabled ? 1 : 0, + }))); + }); + } + + test('recreates detached HTML webviews when scrolling a response back into view', async () => { + const { instantiationService, model, viewModel, container, widget } = createWidget({ rendererOptions: { renderHtmlPreviews: true } }, undefined, true); + const webviews = stubHtmlPreviewWebviews(instantiationService); + const addRequest = (text: string) => model.addRequest({ + text, + parts: [new ChatRequestTextPart(new OffsetRange(0, text.length), new Range(1, 1, 1, text.length + 1), text)], + }, { variables: [] }, 0); + const request = addRequest('Show an HTML report'); + model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString('```html-preview\n

Report

\n```') }); + request.response?.complete(); + widget.refresh(); + widget.layout(300, 500); + await waitForStableLayout(widget); + const initialWebview = webviews.find(webview => webview.marker.isConnected)!; + const parent = container.parentElement!; + widget.setVisible(false); + const disposedWhenHidden = initialWebview.disposed; + container.remove(); + parent.appendChild(container); + widget.setVisible(true); + await waitForStableLayout(widget); + const retainedViewReplaced = initialWebview.disposed && webviews.find(webview => webview.marker.isConnected) !== initialWebview; + const response = viewModel.getItems().find(isResponseVM)!; + for (let index = 0; index < 8; index++) { + const followup = addRequest(`Follow-up ${index}`); + model.acceptResponseProgress(followup, { kind: 'markdownContent', content: new MarkdownString(`Response ${index}.\n\n`.repeat(20)) }); + followup.response?.complete(); + } + widget.refresh(); + widget.reveal(response, 0); + await waitForStableLayout(widget); + + const returnedPreviews: { replaced: boolean; oldDisposed: boolean; disposedWhileOffscreen: boolean }[] = []; + for (let pass = 0; pass < 3; pass++) { + const previous = webviews.find(webview => webview.marker.isConnected)!; + widget.scrollToEnd(); + await waitForStableLayout(widget); + assert.strictEqual(container.querySelector('.chat-html-preview'), null, 'The preview must actually leave the rendered viewport'); + const disposedWhileOffscreen = previous.disposed; + const width = pass % 2 === 0 ? 360 : 500; + container.style.width = `${width}px`; + widget.layout(300, width); + await waitForStableLayout(widget); + widget.reveal(response, 0); + await waitForStableLayout(widget); + const visible = webviews.find(webview => webview.marker.isConnected); + assert.ok(visible); + returnedPreviews.push({ replaced: visible !== previous, oldDisposed: previous.disposed, disposedWhileOffscreen }); + } + const originalPreview = container.querySelector('.chat-html-preview')!; + let previewMenu: Parameters[0] | undefined; + const contextMenu = sinon.stub(instantiationService.get(IContextMenuService), 'showContextMenu').callsFake(delegate => { previewMenu = delegate; }); + originalPreview.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + await previewMenu!.getActions!().find(action => action.id === 'chat.htmlPreview.source')!.run(); + contextMenu.restore(); + for (let index = 0; index < 12; index++) { + const followup = addRequest(`Short follow-up ${index}`); + model.acceptResponseProgress(followup, { kind: 'markdownContent', content: new MarkdownString('Short response.') }); + followup.response?.complete(); + } + widget.refresh(); + widget.scrollToEnd(); + await waitForStableLayout(widget); + assert.strictEqual(container.querySelector('.chat-html-preview'), null); + widget.reveal(response, 0); + await waitForStableLayout(widget); + const restoredPreview = container.querySelector('.chat-html-preview')!; + assert.deepStrictEqual({ + disposedWhenHidden, + retainedViewReplaced, + returnedPreviews, + recycled: restoredPreview !== originalPreview, + sourceHidden: restoredPreview.querySelector('.chat-html-preview-source')?.hidden, + reservedHeight: restoredPreview.querySelector('.chat-html-preview-content')?.style.height, + }, { + disposedWhenHidden: true, + retainedViewReplaced: true, + returnedPreviews: Array.from({ length: 3 }, () => ({ replaced: true, oldDisposed: true, disposedWhileOffscreen: true })), + recycled: true, sourceHidden: false, reservedHeight: '180px', + }); + }); + suite('generated image preview retention', () => { for (const { imageCount, fraction } of [1, 3].flatMap(imageCount => [undefined, 0.25, 0.75].map(fraction => ({ imageCount, fraction })))) { test(`image generation preserves scroll position on every frame before expansion (${imageCount} calls, fraction=${fraction ?? 'natural'})`, async () => { @@ -2960,6 +3173,44 @@ suite('ChatListWidget', () => { }); }); + test('positions the scroll arrow once per frame while scrolling toggles it', async () => { + const { container, widget, sticky } = await createTranscript(); + const button = widget.scrollDownButtonDomNode; + const bottom = widget.scrollTop; + // Render and measure the rows at the top first, so that only the toggles below measure. + widget.scrollTop = 0; + await waitForStableLayout(widget); + widget.scrollTop = bottom; + await waitForStableLayout(widget); + const measure = sinon.spy(container, 'getBoundingClientRect'); + let synchronous: number; + try { + for (let index = 0; index < 5; index++) { + widget.scrollTop = 0; + widget.scrollTop = bottom; + } + widget.scrollTop = 0; + synchronous = measure.callCount; + await nextFrame(); + } finally { + measure.restore(); + } + await waitForStableLayout(widget); + const row = sticky.getBoundingClientRect(); + const arrow = button.getBoundingClientRect(); + assert.deepStrictEqual({ + synchronous, + afterFrame: measure.callCount, + shown: button.style.display, + centered: Math.abs((row.top + row.bottom) / 2 - (arrow.top + arrow.bottom) / 2) < 0.5, + }, { + synchronous: 0, + afterFrame: 1, + shown: 'flex', + centered: true, + }); + }); + test('follows pills appearing and disappearing without moving the pills or input', async () => { const { widget, progress, sticky, pillRow, input, setPillsVisible } = await createTranscript(); widget.scrollTop = 0; diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatMarkdownRenderer.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatMarkdownRenderer.test.ts index c10b51201e02..dcbcbe1f50a1 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatMarkdownRenderer.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatMarkdownRenderer.test.ts @@ -8,7 +8,6 @@ import sinon from 'sinon'; import { allowedMarkdownHtmlAttributes } from '../../../../../../base/browser/markdownRenderer.js'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; -import { OperatingSystem } from '../../../../../../base/common/platform.js'; import { URI } from '../../../../../../base/common/uri.js'; import { assertSnapshot } from '../../../../../../base/test/common/snapshot.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; @@ -21,6 +20,7 @@ import { ILabelService } from '../../../../../../platform/label/common/label.js' import { IMarkdownRendererService, MarkdownRendererService } from '../../../../../../platform/markdown/browser/markdownRenderer.js'; import { ServiceCollection } from '../../../../../../platform/instantiation/common/serviceCollection.js'; import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; +import { PathStyle } from '../../../../../../platform/agentHost/common/state/protocol/common/commands.js'; import { MarkedKatexSupport } from '../../../../markdown/browser/markedKatexSupport.js'; import { allowedChatMarkdownHtmlTags, ChatContentMarkdownRenderer, getChatMarkdownRenderOptions } from '../../../browser/widget/chatContentMarkdownRenderer.js'; import { ChatMarkdownAnchorService, IChatMarkdownAnchorService } from '../../../browser/widget/chatContentParts/chatMarkdownAnchorService.js'; @@ -178,7 +178,7 @@ suite('ChatMarkdownRenderer', () => { test('shows host paths for transformed and already mapped links without changing their targets', () => { const authority = agentHostAuthority('vscode-remote://wsl+Ubuntu'); - store.add(instantiationService.get(ILabelService).registerFormatter(agentHostLabelFormatter(authority, OperatingSystem.Linux))); + store.add(instantiationService.get(ILabelService).registerFormatter(agentHostLabelFormatter(authority, PathStyle.Posix))); const file = URI.file('/home/user/my project/a&b.ts').with({ fragment: 'L42,7' }); const target = toAgentHostUri(file, authority).toString(); const links = [ @@ -205,9 +205,9 @@ suite('ChatMarkdownRenderer', () => { }))); }); - test('uses the remote host operating system for path formatting', () => { + test('uses the remote host path style for formatting', () => { const labelService = instantiationService.get(ILabelService); - store.add(labelService.registerFormatter(agentHostLabelFormatter('windows-host', OperatingSystem.Windows))); + store.add(labelService.registerFormatter(agentHostLabelFormatter('windows-host', PathStyle.Windows))); const target = toAgentHostUri(URI.file('C:/my project/file.ts'), 'windows-host').toString(); store.add(testRenderer.render(new MarkdownString(`[file](${target})`))); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts index 095f6a7a4e3f..dc96cd2b2910 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatPetWidget.test.ts @@ -2122,6 +2122,50 @@ suite('ChatPetWidget', () => { }); }); + test('hides the pet from its context menu', async () => { + const parent = mainWindow.document.createElement('div'); + mainWindow.document.body.append(parent); + disposables.add(toDisposable(() => parent.remove())); + let menu: IContextMenuDelegate | undefined; + const service = disposables.add(new ChatPetService(disposables.add(new TestStorageService()), new TestTelemetryService(), new NullLogService(), editorWindowEnvironment)); + service.toggle(); + disposables.add(new ChatPetWidget( + createPetHost(parent, parent, parent), + undefined, + service, + new TestAccessibilityService(), + new class extends mock() { + override showContextMenu(delegate: IContextMenuDelegate): void { menu = delegate; } + }(), + new class extends mock() { }(), + new NullLogService(), + new class extends mock() { + override readonly hasFocus = true; + override readonly onDidChangeFocus = Event.None; + override readonly onDidChangeActiveWindow = Event.None; + }(), + workbenchInstantiationService(undefined, disposables), + )); + const button = parent.querySelector('.chat-pet-button'); + assert.ok(button); + button.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + const actions = menu?.getActions() ?? []; + const hide = actions.find(action => action.id === 'chat.pet.hide'); + assert.ok(hide); + await hide.run(); + await hide.run(); + + assert.deepStrictEqual({ + label: hide.label, + isLast: actions[actions.length - 1] === hide, + enabled: service.enabled.get(), + }, { + label: 'Hide Pet', + isLast: true, + enabled: false, + }); + }); + test('stacks dragging above sticky scroll and leaves the persistent content fade to the input', () => { const session = mainWindow.document.createElement('div'); session.className = 'interactive-session chat-floating-persistent-content'; diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts index 81edd3d7317c..a722a03c2032 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts @@ -7,6 +7,8 @@ import assert from 'assert'; import * as dom from '../../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../../base/browser/window.js'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { createStringDataTransferItem, VSDataTransfer } from '../../../../../../base/common/dataTransfer.js'; +import { HierarchicalKind } from '../../../../../../base/common/hierarchicalKind.js'; import { CancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; @@ -17,6 +19,11 @@ import { mockObject, upcastPartial } from '../../../../../../base/test/common/mo import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { OffsetRange } from '../../../../../../editor/common/core/ranges/offsetRange.js'; import { Range } from '../../../../../../editor/common/core/range.js'; +import { CopyPasteController } from '../../../../../../editor/contrib/dropOrPasteInto/browser/copyPasteController.js'; +import { IBulkEditService } from '../../../../../../editor/browser/services/bulkEditService.js'; +import { DocumentPasteEditProvider } from '../../../../../../editor/common/languages.js'; +import { withAsyncTestCodeEditor } from '../../../../../../editor/test/browser/testCodeEditor.js'; +import { IActionWidgetService } from '../../../../../../platform/actionWidget/browser/actionWidget.js'; import { AgentHostClientConnectionKind } from '../../../../../../platform/agentHost/common/agentHostTelemetry.js'; import { AgentHostClaudeAgentEnabledSettingId, AgentHostCodexAgentEnabledSettingId } from '../../../../../../platform/agentHost/common/agentService.js'; import { IConfigurationChangeEvent } from '../../../../../../platform/configuration/common/configuration.js'; @@ -24,7 +31,7 @@ import { Codicon } from '../../../../../../base/common/codicons.js'; import { CodeEditorWidget } from '../../../../../../editor/browser/widget/codeEditor/codeEditorWidget.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IDialogService } from '../../../../../../platform/dialogs/common/dialogs.js'; -import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { createDecorator, IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { NullHoverService } from '../../../../../../platform/hover/test/browser/nullHoverService.js'; @@ -34,6 +41,8 @@ import { ILinkDescriptor, ILinkOptions, Link } from '../../../../../../platform/ import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, NullManagedSettingsService, requiresCopilotAgentHost } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IProgressService } from '../../../../../../platform/progress/common/progress.js'; +import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; import { SaveReason } from '../../../../../common/editor.js'; import { IEditorService, ISaveAllEditorsOptions, ISaveEditorsResult } from '../../../../../services/editor/common/editorService.js'; import { TestEditorService } from '../../../../../test/browser/workbenchTestServices.js'; @@ -699,10 +708,11 @@ suite('ChatWidget', () => { const submit = async (hostSubmit: boolean) => { const widget = Object.create(ChatWidget.prototype) as ChatWidget; Object.defineProperties(widget, { + _store: { value: store.add(new DisposableStore()) }, viewOptions: { value: hostSubmit ? { hostSubmit: { canSubmit: constObservable(true) } } : {} }, // A placeholder local chat, as blocked by a policy that requires the agent host. viewModel: { value: { model: { isInputBlocked: constObservable(true) }, sessionResource: LocalChatSessionUri.forSession('placeholder') } }, - input: { value: { hasPendingProgrammaticModelSelection: false, isManagedSettingsRefreshBlocked: false } }, + input: { value: { inputEditor: { getContribution: () => null }, hasPendingProgrammaticModelSelection: false, isManagedSettingsRefreshBlocked: false } }, // The first step past the input checks. getParticipantForLocalChat: { value: () => { reached.push(hostSubmit ? 'hostSubmit' : 'widget'); return undefined; } }, instantiationService: { value: { createInstance: () => { throw new Error('stop after the input checks'); } } }, @@ -1583,10 +1593,11 @@ suite('ChatWidget', () => { let rerenders = 0; const layoutHeights: number[] = []; const discardingSlot = { set value(disposable: IDisposable | undefined) { disposable?.dispose(); } }; + const visible = observableValue('visible', true); const widget: ChatWidget = Object.assign(Object.create(ChatWidget.prototype), { _readOnly: false, _draftOnly: observableValue('draftOnly', false), - _visible: observableValue('visible', true), + _visible: visible, visibleChangeCount: 0, viewOptions: { renderStyle: 'minimal' }, _readOnlyContextKey: { set: () => { } }, @@ -1615,7 +1626,7 @@ suite('ChatWidget', () => { rerender: () => rerenders++, }, }); - return { widget, domNode, layoutHeights, rerenders: () => rerenders }; + return { widget, domNode, layoutHeights, visible, rerenders: () => rerenders }; } test('passes read-only transitions to the renderer independently of request editing', () => { @@ -1644,11 +1655,47 @@ suite('ChatWidget', () => { assert.deepStrictEqual({ rendererOptions, rerenders, inputVisibility }, { rendererOptions: [{ editable: false, readOnly: true }, { editable: false, readOnly: true }, { editable: true, readOnly: false }], - rerenders: 3, + rerenders: 2, inputVisibility: [false, true, true], }); }); + test('only rerenders the list when the read-only state changes what rows render', () => { + const { widget, domNode, rerenders } = createRerenderWidget(); + mainWindow.document.body.appendChild(domNode); + domNode.style.height = '100px'; + store.add(toDisposable(() => domNode.remove())); + const counts: number[] = []; + + for (const readOnly of [false, false, false, true, true, false]) { + widget.setReadOnly(readOnly); + counts.push(rerenders()); + } + + assert.deepStrictEqual(counts, [1, 1, 1, 2, 2, 3]); + }); + + test('rerenders rows left stale by a read-only change while hidden', () => { + const { widget, domNode, visible, rerenders } = createRerenderWidget(); + mainWindow.document.body.appendChild(domNode); + domNode.style.height = '100px'; + store.add(toDisposable(() => domNode.remove())); + const counts: number[] = []; + + widget.setReadOnly(false); + counts.push(rerenders()); + visible.set(false, undefined); + widget.setReadOnly(true); + counts.push(rerenders()); + visible.set(true, undefined); + widget.setReadOnly(true); + counts.push(rerenders()); + widget.setReadOnly(true); + counts.push(rerenders()); + + assert.deepStrictEqual(counts, [1, 1, 2, 2]); + }); + test('keeps the sandbox composer visible while live content is unavailable', () => { const container = dom.append(mainWindow.document.body, dom.$('.interactive-session')); store.add(toDisposable(() => container.remove())); @@ -2510,11 +2557,15 @@ suite('ChatWidget - acceptInput submission', () => { const attachments = new ChatRequestVariableSet(); const contribs: IChatWidget['contribs'][number][] = []; const parts: IParsedChatRequest['parts'][number][] = []; - const parsedInput: IParsedChatRequest = { text: inputText, parts }; + const parsedInput = { text: inputText, parts } satisfies IParsedChatRequest; const policyRequiresAgentHost = observableValue('policyRequiresAgentHost', false); const contextKeyService = store.add(new MockContextKeyService()); + const pasteController = mockObject()(); + pasteController.finishedPaste.resolves(true); + const editor = mockObject()(); + editor.getContribution.returns(pasteController); const input = mockObject()({ - inputEditor: upcastPartial({ getValue: () => parsedInput.text }), + inputEditor: upcastPartial({ getValue: () => parsedInput.text, getContribution: editor.getContribution }), getPromptText: () => parsedInput.text, inlineAttachments: undefined, currentModeKind: ChatModeKind.Ask, @@ -2612,7 +2663,162 @@ suite('ChatWidget - acceptInput submission', () => { _maybeStartGoalSummary: { value: () => { } }, }); const options: IChatAcceptInputOptions = { preserveInput: true }; - return { widget, viewOptions, options, original, input, inputPartDisposable, configurationService, editorService, chatService, chatWidgetService, chatSessionsService, customizationHarnessService, parser, parts, policyRequiresAgentHost, contextKeyService, attachments, contribs, response, sent, acceptedRequests }; + return { widget, widgetStore, viewOptions, options, original, input, inputPartDisposable, configurationService, editorService, chatService, chatWidgetService, chatSessionsService, customizationHarnessService, parser, parts, parsedInput, pasteController, policyRequiresAgentHost, contextKeyService, attachments, contribs, response, sent, acceptedRequests }; + } + + for (const customHandler of [false, true]) { + test(`waits for pasted text and attachments before ${customHandler ? 'calling a custom submit handler' : 'sending the draft'}`, async () => { + const fixture = createSubmissionWidget(undefined, 'Explain '); + const paste = new DeferredPromise(); + fixture.pasteController.finishedPaste.returns(paste.p); + const submissions: { text: string; attachments: readonly string[] }[] = []; + if (customHandler) { + fixture.viewOptions.submitHandler = async (text, _mode, attachments) => { + submissions.push({ text, attachments: attachments?.map(entry => entry.id) ?? [] }); + return true; + }; + } + + const sending = fixture.widget.acceptInput(); + await timeout(0); + const pending = { + waitingForPaste: fixture.pasteController.finishedPaste.calledOnce, + requests: fixture.chatService.sendRequest.callCount, + accepted: fixture.input.acceptInput.callCount, + handled: submissions.length, + }; + fixture.parsedInput.text = 'Explain pasted text'; + fixture.attachments.add({ kind: 'file', id: 'pasted-file', name: 'file.ts', value: URI.file('/workspace/file.ts') }); + await paste.complete(true); + await sending; + for (const call of fixture.chatService.sendRequest.getCalls()) { + const options: IChatSendRequestOptions = call.args[2]; + submissions.push({ text: call.args[1], attachments: options.attachedContext?.map(entry => entry.id) ?? [] }); + } + + assert.deepStrictEqual({ pending, submissions }, { + pending: { waitingForPaste: true, requests: 0, accepted: 0, handled: 0 }, + submissions: [{ text: 'Explain pasted text', attachments: ['pasted-file'] }], + }); + }); + } + + test('preserved-input submissions do not wait for a paste into the unrelated draft', async () => { + const fixture = createSubmissionWidget(); + const paste = new DeferredPromise(); + fixture.pasteController.finishedPaste.returns(paste.p); + try { + await fixture.widget.acceptInput('Background continuation', fixture.options); + assert.deepStrictEqual({ + waited: fixture.pasteController.finishedPaste.called, + message: fixture.chatService.sendRequest.firstCall.args[1], + }, { waited: false, message: 'Background continuation' }); + } finally { + await paste.complete(true); + } + }); + + test('does not send an incomplete draft when paste fails', async () => { + const fixture = createSubmissionWidget(); + fixture.pasteController.finishedPaste.rejects(new Error('Paste failed')); + + await assert.rejects(fixture.widget.acceptInput(), /Paste failed/); + assert.deepStrictEqual({ + requests: fixture.chatService.sendRequest.callCount, + accepted: fixture.input.acceptInput.callCount, + }, { requests: 0, accepted: 0 }); + }); + + for (const phase of ['provide', 'resolve'] as const) { + test(`does not send when editing the same composer cancels paste during ${phase}`, async () => { + const fixture = createSubmissionWidget(); + await withAsyncTestCodeEditor('Explain ', {}, async (editor, _viewModel, instantiationService) => { + instantiationService.stub(createDecorator<{ add(): () => void }>('IEditorCancelService'), { add: () => () => { } }); + instantiationService.stub(IActionWidgetService, {}); + instantiationService.stub(IQuickInputService, {}); + instantiationService.stub(IProgressService, {}); + const bulkEditService = mockObject()(); + bulkEditService.apply.resolves({ isApplied: true, ariaSummary: '' }); + instantiationService.stub(IBulkEditService, { apply: bulkEditService.apply }); + const controller = store.add(editor.registerAndInstantiateContribution(CopyPasteController.ID, CopyPasteController)); + Object.defineProperty(fixture.input, 'inputEditor', { value: editor }); + fixture.input.getPromptText = () => editor.getValue(); + + const entered = new DeferredPromise(); + const finish = new DeferredPromise(); + const kind = new HierarchicalKind('chat.attach.image'); + const provider: DocumentPasteEditProvider = { + copyMimeTypes: [], + pasteMimeTypes: ['image/png'], + providedPasteEditKinds: [kind], + async provideDocumentPasteEdits(_model, _ranges, _dataTransfer, _context, token) { + if (phase === 'provide') { + entered.complete(); + await finish.p; + } + if (token.isCancellationRequested) { + return undefined; + } + return { edits: [{ title: 'Image', insertText: '', kind }], dispose: () => { } }; + }, + async resolveDocumentPasteEdit(edit) { + entered.complete(); + await finish.p; + return edit; + }, + }; + const dataTransfer = new VSDataTransfer(); + dataTransfer.append('image/png', createStringDataTransferItem('image')); + // The test editor has no clipboard view, so start the inline paste directly. + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers + controller['doPasteInline']([provider], editor.getSelections(), dataTransfer, undefined, undefined); + await entered.p; + const sending = assert.rejects(fixture.widget.acceptInput(), CancellationError); + editor.getModel().setValue('Changed draft'); + await finish.complete(); + await sending; + + assert.deepStrictEqual({ + draft: editor.getValue(), + requests: fixture.chatService.sendRequest.callCount, + accepted: fixture.input.acceptInput.callCount, + applied: bulkEditService.apply.callCount, + }, { draft: 'Changed draft', requests: 0, accepted: 0, applied: 0 }); + }); + }); + } + + for (const change of ['session', 'input', 'blocked', 'dispose'] as const) { + test(`does not submit after ${change} changes while waiting for paste`, async () => { + const fixture = createSubmissionWidget(); + const paste = new DeferredPromise(); + fixture.pasteController.finishedPaste.returns(paste.p); + const sending = fixture.widget.acceptInput(); + const settled = change === 'blocked' + ? sending + : assert.rejects(sending, CancellationError); + switch (change) { + case 'session': + Object.defineProperty(fixture.widget, '_viewModel', { value: createSession(URI.parse('test:/other-session')).viewModel }); + break; + case 'input': + Object.defineProperty(fixture.widget, 'input', { value: upcastPartial({}) }); + break; + case 'blocked': + fixture.original.isInputBlocked.set(true, undefined); + break; + case 'dispose': + fixture.widgetStore.dispose(); + break; + } + await paste.complete(true); + await settled; + + assert.deepStrictEqual({ + requests: fixture.chatService.sendRequest.callCount, + accepted: fixture.input.acceptInput.callCount, + }, { requests: 0, accepted: 0 }); + }); } for (const changeModel of [true, false]) { @@ -3024,6 +3230,41 @@ suite('ChatWidget - acceptInput submission', () => { return { widget, input, attachmentModel }; } + test('waits for paste before routing an extension participant to a Local chat', async () => { + const fixture = createSubmissionWidget(undefined, 'Explain '); + const paste = new DeferredPromise(); + fixture.pasteController.finishedPaste.returns(paste.p); + const local = createSession(LocalChatSessionUri.getNewSessionUri()); + fixture.chatService.startNewLocalSession.returns({ object: local.model, dispose: () => { } }); + const destination = createParticipantDestination(local.viewModel, fixture.response); + fixture.chatWidgetService.openSession.resolves(destination.widget); + + const sending = fixture.widget.acceptInput(); + await timeout(0); + const beforePaste = { + created: fixture.chatService.startNewLocalSession.callCount, + sent: fixture.chatService.sendRequest.callCount, + }; + fixture.parsedInput.text = '@participant Explain pasted text'; + const participant = addParticipant(fixture); + await paste.complete(true); + await sending; + + assert.deepStrictEqual({ + beforePaste, + participant: destination.widget.lastSelectedAgent, + draft: local.inputModel.setState.firstCall.args[0].inputText, + sent: fixture.chatService.sendRequest.callCount, + redirected: destination.widget.acceptInput.callCount, + }, { + beforePaste: { created: 0, sent: 0 }, + participant, + draft: '@participant Explain pasted text', + sent: 0, + redirected: 1, + }); + }); + for (const inEditor of [false, true]) { test(`submits an extension participant in a new Local chat without changing the agent-host request (${inEditor ? 'editor' : 'sidebar'})`, async () => { const fixture = createSubmissionWidget(undefined, '@participant Test request'); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts index 16a59c5c3584..b0a653dd42ac 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts @@ -16,18 +16,32 @@ import { ILogService, NullLogService } from '../../../../../../platform/log/comm import { IEditorGroupsService } from '../../../../../services/editor/common/editorGroupsService.js'; import { IEditorService } from '../../../../../services/editor/common/editorService.js'; import { IViewsService } from '../../../../../services/views/common/viewsService.js'; -import { IChatWidget, IQuickChatService } from '../../../browser/chat.js'; +import { ChatViewId, ChatViewPaneTarget, IChatWidget, IChatWidgetViewContext, IQuickChatService } from '../../../browser/chat.js'; +import { IChatViewHost, IChatViewHostService } from '../../../browser/chatViewHost.js'; +import { ChatViewHostService } from '../../../browser/widgetHosts/viewPane/chatViewHostService.js'; +import { IViewDescriptorService } from '../../../../../common/views.js'; +import { IWorkbenchLayoutService } from '../../../../../services/layout/browser/layoutService.js'; +import { IProgressService } from '../../../../../../platform/progress/common/progress.js'; import { ChatDynamicVariableModel } from '../../../browser/attachments/chatDynamicVariables.js'; import { ChatVariablesService } from '../../../browser/attachments/chatVariables.js'; import { ChatWidgetService } from '../../../browser/widget/chatWidgetService.js'; import { IDynamicVariable } from '../../../common/attachments/chatVariables.js'; import { IChatService } from '../../../common/chatService/chatService.js'; +import { ChatAgentLocation } from '../../../common/constants.js'; import { IChatViewModel } from '../../../common/model/chatViewModel.js'; import { ToolAndToolSetEnablementMap } from '../../../common/tools/languageModelToolsService.js'; suite('ChatWidgetService', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + /** The host of the Chat view's chats as in the workbench: the Chat view, through the stubbed views service. */ + function stubChatViewHostService(instantiationService: TestInstantiationService): void { + instantiationService.stub(IViewDescriptorService, {}); + instantiationService.stub(IWorkbenchLayoutService, {}); + instantiationService.stub(IProgressService, {}); + instantiationService.stub(IChatViewHostService, instantiationService.createInstance(ChatViewHostService)); + } + test('only input-request routing prefers the full session over Inbox, preserving the submitting input context', () => { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IEditorGroupsService, {}); @@ -37,6 +51,7 @@ suite('ChatWidgetService', () => { instantiationService.stub(IEditorService, {}); instantiationService.stub(IChatService, {}); instantiationService.stub(ILogService, new NullLogService()); + stubChatViewHostService(instantiationService); const service = store.add(instantiationService.createInstance(ChatWidgetService)); const variablesService = new ChatVariablesService(service); const resource = URI.parse('test:/session'); @@ -90,4 +105,177 @@ suite('ChatWidgetService', () => { unrelatedSession: service.getWidgetBySessionResource(URI.parse('test:/other')), }, { ordinaryRouting: { default: true, inputRequests: true }, inboxOnly: true, withFullSession: true, submittingWidget: true, dynamicVariables: references, selectedTools: true, afterClosingSession: true, unrelatedSession: undefined }); }); + + test('shows what the Chat view would in the host of the Chat view\'s chats', async () => { + const instantiationService = store.add(new TestInstantiationService()); + const calls: string[] = []; + instantiationService.stub(IEditorGroupsService, upcastPartial({ groups: [] })); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async (id: string, focus?: boolean) => { calls.push(`openView ${id} focus=${focus}`); return null; }) as IViewsService['openView'], + getViewWithId: () => null, + })); + instantiationService.stub(IQuickChatService, upcastPartial({ sessionResource: undefined })); + instantiationService.stub(ILayoutService, {}); + instantiationService.stub(IEditorService, {}); + instantiationService.stub(IChatService, upcastPartial({ acquireExistingSession: () => undefined })); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IChatViewHostService, upcastPartial({ + reveal: async preserveFocus => { calls.push(`reveal preserveFocus=${preserveFocus}`); return undefined; }, + revealIfShowing: async () => undefined, + openSession: async (sessionResource, options) => { calls.push(`openSession ${sessionResource.toString()} preserveFocus=${options?.preserveFocus} reason=${options?.sessionTypeSelectionReason}`); return undefined; }, + })); + const service = store.add(instantiationService.createInstance(ChatWidgetService)); + const resource = URI.parse('test:/session'); + + await service.revealWidget(); + await service.revealChatView(true); + await service.openSession(resource); + await service.openSession(resource, ChatViewPaneTarget, { preserveFocus: true, sessionTypeSelectionReason: 'explicitOverride' }); + + assert.deepStrictEqual(calls, [ + 'reveal preserveFocus=undefined', + 'reveal preserveFocus=true', + 'openSession test:/session preserveFocus=undefined reason=undefined', + 'openSession test:/session preserveFocus=true reason=explicitOverride', + ]); + }); + + test('revealWidget reuses a visible chat widget hosted outside of the chat view, such as the Agents window session chat', async () => { + const instantiationService = store.add(new TestInstantiationService()); + const openedViews: string[] = []; + instantiationService.stub(IEditorGroupsService, { groups: [] }); + instantiationService.stub(IViewsService, { + getViewWithId: () => null, + openView: async (id: string) => { openedViews.push(id); return null; }, + }); + instantiationService.stub(IQuickChatService, { sessionResource: undefined }); + instantiationService.stub(ILayoutService, {}); + instantiationService.stub(IEditorService, {}); + instantiationService.stub(IChatService, {}); + instantiationService.stub(ILogService, new NullLogService()); + stubChatViewHostService(instantiationService); + const service = store.add(instantiationService.createInstance(ChatWidgetService)); + const createWidget = (visible: boolean, viewContext: IChatWidgetViewContext) => { + const focusInput = stub(); + const widget = upcastPartial({ + visible, + viewContext, + location: ChatAgentLocation.Chat, + viewModel: upcastPartial({ sessionResource: URI.parse('test:/session') }), + focusInput, + onDidFocus: Event.None, + onDidShow: Event.None, + onDidHide: Event.None, + onDidChangeViewModel: Event.None, + }); + return { widget, focusInput }; + }; + const revealLastFocused = async (visible: boolean, viewContext: IChatWidgetViewContext, preserveFocus?: boolean) => { + const { widget, focusInput } = createWidget(visible, viewContext); + const registration = service.register(widget); + try { + const revealed = await service.revealWidget(preserveFocus); + return { revealed: revealed === widget, focusInput: focusInput.callCount }; + } finally { + registration.dispose(); + } + }; + + const result = { + visible: await revealLastFocused(true, {}), + visiblePreserveFocus: await revealLastFocused(true, {}, true), + hidden: await revealLastFocused(false, {}), + quickChat: await revealLastFocused(true, { isQuickChat: true }), + inlineChat: await revealLastFocused(true, { isInlineChat: true }), + openedViews, + }; + assert.deepStrictEqual(result, { + visible: { revealed: true, focusInput: 1 }, + visiblePreserveFocus: { revealed: true, focusInput: 0 }, + hidden: { revealed: false, focusInput: 0 }, + quickChat: { revealed: false, focusInput: 0 }, + inlineChat: { revealed: false, focusInput: 0 }, + openedViews: [ChatViewId, ChatViewId, ChatViewId], + }); + }); + suite('Chat view widgets with a replacement host', () => { + + const session = URI.parse('test:/session'); + + function setUp() { + const instantiationService = store.add(new TestInstantiationService()); + const calls: string[] = []; + const createWidget = (sessionResource: URI | undefined) => upcastPartial({ + visible: true, + viewContext: { viewId: ChatViewId }, + location: ChatAgentLocation.Chat, + viewModel: sessionResource ? upcastPartial({ sessionResource }) : undefined, + onDidFocus: Event.None, + onDidShow: Event.None, + onDidHide: Event.None, + onDidChangeViewModel: Event.None, + }); + const oldWidget = createWidget(session); + const emptyOldWidget = createWidget(undefined); + const hostWidget = upcastPartial({}); + const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); } }; + instantiationService.stub(IEditorGroupsService, { groups: [] }); + instantiationService.stub(IViewsService, { + getViewWithId: (() => view) as unknown as IViewsService['getViewWithId'], + openView: (async (id: string) => { calls.push(`openView ${id}`); return view; }) as unknown as IViewsService['openView'], + }); + instantiationService.stub(IQuickChatService, { sessionResource: undefined }); + instantiationService.stub(ILayoutService, {}); + instantiationService.stub(IEditorService, {}); + instantiationService.stub(IChatService, { acquireExistingSession: () => undefined }); + instantiationService.stub(ILogService, new NullLogService()); + stubChatViewHostService(instantiationService); + const hostService = instantiationService.get(IChatViewHostService); + const service = store.add(instantiationService.createInstance(ChatWidgetService)); + return { calls, service, hostService, oldWidget, emptyOldWidget, hostWidget }; + } + + test('a Chat view that still holds the session is not shown or returned instead of what the replacement host shows', async () => { + const { calls, service, hostService, oldWidget, hostWidget } = setUp(); + store.add(hostService.registerHost(upcastPartial({ + reveal: async () => { calls.push('host.reveal'); return hostWidget; }, + openSession: async () => { calls.push('host.openSession'); return hostWidget; }, + }))); + const registration = service.register(oldWidget); + store.add(registration); + + const result = { + openSession: (await service.openSession(session)) === hostWidget, + revealOpenSession: (await service.openSession(session, undefined, { revealIfOpened: true })) === hostWidget, + revealWidget: (await service.revealWidget()) === hostWidget, + calls, + }; + + assert.deepStrictEqual(result, { + openSession: true, + revealOpenSession: true, + revealWidget: true, + calls: ['host.openSession', 'host.openSession', 'host.reveal'], + }); + }); + + test('a Chat view widget without a session is revealed by the replacement host, which may show none', async () => { + const { calls, service, hostService, emptyOldWidget } = setUp(); + store.add(hostService.registerHost(upcastPartial({ + reveal: async () => { calls.push('host.reveal'); return undefined; }, + }))); + + const revealed = await service.reveal(emptyOldWidget); + + assert.deepStrictEqual({ revealed, calls }, { revealed: false, calls: ['host.reveal'] }); + }); + + test('without a replacement host, a Chat view that holds the session is shown as it is, without loading the session again', async () => { + const { calls, service, oldWidget } = setUp(); + + const widget = await service.openSession(session); + + assert.deepStrictEqual({ shown: widget === oldWidget, calls }, { shown: true, calls: [`openView ${ChatViewId}`, 'view.focus'] }); + }); + }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputNotificationWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputNotificationWidget.test.ts index 67ddf7e423d3..d6627395f168 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputNotificationWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputNotificationWidget.test.ts @@ -342,6 +342,7 @@ suite('ChatInputNotificationWidget', () => { let hasSessions = false; const harness = { environmentService: { isSessionsWindow: false }, + options: { isSessionsWindow: false }, chatService: { hasSessions: () => hasSessions }, _deferredNotificationsEnabled: deferredNotificationsEnabled, _isFirstWorkbenchSession: undefined as boolean | undefined, @@ -372,22 +373,24 @@ suite('ChatInputNotificationWidget', () => { }); }); - test('Agents window bypasses the workbench first-session gate', () => { - const deferredNotificationsEnabled = observableValue('deferredNotificationsEnabled', false); - const harness = { - environmentService: { isSessionsWindow: true }, - chatService: { hasSessions: () => false }, - _deferredNotificationsEnabled: deferredNotificationsEnabled, - _isFirstWorkbenchSession: undefined as boolean | undefined, - }; + test('session chats bypass the workbench first-session gate, in the Agents window and in other windows', () => { const update = Reflect.get(ChatInputPart.prototype, 'updateDeferredNotificationsEligibility') as ( - this: typeof harness, + this: object, event?: { previousSessionResource: URI | undefined; currentSessionResource: URI | undefined }, ) => void; + const enabledFor = (isSessionsWindow: boolean, isSessionsChat: boolean) => { + const deferredNotificationsEnabled = observableValue('deferredNotificationsEnabled', false); + update.call({ + environmentService: { isSessionsWindow }, + options: { isSessionsWindow: isSessionsChat }, + chatService: { hasSessions: () => false }, + _deferredNotificationsEnabled: deferredNotificationsEnabled, + _isFirstWorkbenchSession: undefined as boolean | undefined, + }); + return deferredNotificationsEnabled.get(); + }; - update.call(harness); - - assert.strictEqual(deferredNotificationsEnabled.get(), true); + assert.deepStrictEqual({ agentsWindow: enabledFor(true, true), sessionChatInEditorWindow: enabledFor(false, true) }, { agentsWindow: true, sessionChatInEditorWindow: true }); }); test('renders markdown descriptions as rich content', () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPart.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPart.test.ts index 7cfeba7c2244..5aa471d1eead 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPart.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPart.test.ts @@ -89,6 +89,27 @@ suite('ChatInputPart', () => { assert.deepStrictEqual(updates, ['input', 'execute', 'secondary', 'layout']); }); + test('announces a model once across metadata refreshes and transient loading states', () => { + const announcements: string[] = []; + const labels: string[] = []; + const input: ChatInputPart = Object.assign(Object.create(ChatInputPart.prototype), { + chatModelIdKey: { set: () => { } }, + accessibilityService: { alert: (message: string) => announcements.push(message) }, + _inputEditor: { updateOptions: ({ ariaLabel }: { ariaLabel: string }) => labels.push(ariaLabel) }, + _getAriaLabel: () => 'Chat input', + }); + const model = (identifier: string) => upcastPartial({ + identifier, metadata: upcastPartial({ id: identifier, name: identifier }), + }); + const update = Reflect.get(ChatInputPart.prototype, '_updateSelectedModel') as (this: ChatInputPart, model: ILanguageModelChatMetadataAndIdentifier | undefined) => void; + for (const selected of [undefined, model('first'), model('first'), undefined, model('first'), model('second'), model('second')]) { + update.call(input, selected); + } + assert.deepStrictEqual({ announcements, labelUpdates: labels.length }, { + announcements: ['first', 'second'], labelUpdates: 7, + }); + }); + for (const placement of ['primary', 'secondary'] as const) { test(`keeps dependent session options in the attached ${placement} toolbar after synchronous refresh`, () => { const root = dom.append(mainWindow.document.body, dom.$('div')); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPickerActionItem.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPickerActionItem.test.ts index 8d1efe7665fc..3d4ca0743975 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPickerActionItem.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputPickerActionItem.test.ts @@ -117,6 +117,40 @@ suite('ChatInputPickerSplit', () => { { tabIndex: -1, disabled: 'true' }, ]); }); + + test('uses dashed high contrast hover and solid focus and open-state outlines per button', () => { + const root = dom.append(document.body, dom.$('.monaco-workbench.hc-black')); + root.style.setProperty('--vscode-contrastActiveBorder', '#f38518'); + root.style.setProperty('--vscode-focusBorder', '#007fd4'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + disposables.add({ dispose: () => root.remove() }); + const container = dom.append(root, dom.$('.action-label')); + const { primaryButton, secondaryButton } = renderChatInputPickerSplit(container); + const readOutline = (element: HTMLElement) => { + const style = dom.getWindow(element).getComputedStyle(element); + return { + color: style.outlineColor, + offset: style.outlineOffset, + style: style.outlineStyle, + width: style.outlineWidth, + }; + }; + + primaryButton.classList.add('hovered'); + const hovered = readOutline(primaryButton); + primaryButton.classList.add('focus-visible'); + const focusedAndHovered = readOutline(primaryButton); + primaryButton.classList.remove('hovered', 'focus-visible'); + secondaryButton.ariaExpanded = 'true'; + secondaryButton.classList.add('hovered'); + const openAndHovered = readOutline(secondaryButton); + + assert.deepStrictEqual({ hovered, focusedAndHovered, openAndHovered }, { + hovered: { color: 'rgb(243, 133, 24)', offset: '-1px', style: 'dashed', width: '1px' }, + focusedAndHovered: { color: 'rgb(0, 127, 212)', offset: '-1px', style: 'solid', width: '1px' }, + openAndHovered: { color: 'rgb(243, 133, 24)', offset: '-1px', style: 'solid', width: '1px' }, + }); + }); }); suite('ChatInputPickerFocus', () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputTipPresenter.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputTipPresenter.test.ts index 8e80ef37621b..f695abc0e509 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputTipPresenter.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatInputTipPresenter.test.ts @@ -5,16 +5,30 @@ import assert from 'assert'; import * as dom from '../../../../../../../base/browser/dom.js'; -import { Emitter } from '../../../../../../../base/common/event.js'; +import { timeout } from '../../../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { DisposableStore, toDisposable } from '../../../../../../../base/common/lifecycle.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 { IMenuService } from '../../../../../../../platform/actions/common/actions.js'; +import { MenuService } from '../../../../../../../platform/actions/common/menuService.js'; +import { ICommandService } from '../../../../../../../platform/commands/common/commands.js'; +import { ConfigurationTarget, IConfigurationChangeEvent } from '../../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IContextKeyService } from '../../../../../../../platform/contextkey/common/contextkey.js'; import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; +import { CommandService } from '../../../../../../services/commands/common/commandService.js'; +import { IsSessionsWindowContext } from '../../../../../../common/contextkeys.js'; +import { TIP_CATALOG } from '../../../../browser/chatTipCatalog.js'; import { IChatTip, IChatTipService } from '../../../../browser/chatTipService.js'; import { ChatInputNoticeHost, ChatInputNoticeLane } from '../../../../browser/widget/input/chatInputNoticeHost.js'; import { ChatInputTipPresenter } from '../../../../browser/widget/input/chatInputTipPresenter.js'; +import { ChatContextKeys } from '../../../../common/actions/chatContextKeys.js'; +import { ChatConfiguration } from '../../../../common/constants.js'; suite('ChatInputTipPresenter', () => { @@ -22,14 +36,17 @@ suite('ChatInputTipPresenter', () => { const TIP: IChatTip = { id: 'tip.test', content: { value: 'A tip' } } as IChatTip; - function createPresenter(store: DisposableStore, noticeHost: ChatInputNoticeHost, options?: { isEligible?: () => boolean; tip?: IChatTip }) { + function createPresenter(store: DisposableStore, noticeHost: ChatInputNoticeHost, options?: { isEligible?: () => boolean; tip?: IChatTip; contextKeyService?: IContextKeyService; getTip?: () => IChatTip | undefined }) { let welcomeTipCalls = 0; let focusInputCalls = 0; let tip = options?.tip ?? TIP; const onDidChangeTip = store.add(new Emitter()); const instantiationService = workbenchInstantiationService(undefined, store) as TestInstantiationService; + if (options?.contextKeyService) { + instantiationService.stub(IContextKeyService, options.contextKeyService); + } instantiationService.stub(IChatTipService, { - getWelcomeTip: () => { welcomeTipCalls++; return tip; }, + getWelcomeTip: () => { welcomeTipCalls++; return options?.getTip ? options.getTip() : tip; }, onDidChangeTip: onDidChangeTip.event, onDidDismissTip: () => toDisposable(() => { }), onDidNavigateTip: () => toDisposable(() => { }), @@ -96,6 +113,123 @@ suite('ChatInputTipPresenter', () => { assert.strictEqual(welcomeTipCalls(), 1); }); + test('keeps replacement tip arrows clickable after disposing the previous presenter', async () => { + const store = disposables.add(new DisposableStore()); + const instantiationService = workbenchInstantiationService(undefined, store); + const contextKeyService = store.add(new ContextKeyService(new TestConfigurationService())); + instantiationService.stub(IContextKeyService, contextKeyService); + instantiationService.stub(ICommandService, store.add(instantiationService.createInstance(CommandService))); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const onDidNavigateTip = store.add(new Emitter()); + const tips = [ + { id: 'tip.first', content: new MarkdownString('First tip') }, + { id: 'tip.second', content: new MarkdownString('Second tip') }, + ]; + let index = 0; + const navigate = () => { + index = 1 - index; + onDidNavigateTip.fire(tips[index]); + return tips[index]; + }; + instantiationService.stub(IChatTipService, { + getWelcomeTip: () => tips[index], + hasMultipleTips: () => true, + navigateToNextTip: navigate, + navigateToPreviousTip: navigate, + onDidNavigateTip: onDidNavigateTip.event, + onDidChangeTip: Event.None, + onDidDismissTip: Event.None, + onDidHideTip: Event.None, + onDidDisableTips: Event.None, + }); + const create = () => { + const container = dom.append(document.body, dom.$('.chat-getting-started-tip-container')); + store.add(toDisposable(() => container.remove())); + const noticeHost = store.add(new ChatInputNoticeHost(() => { })); + const presenter = store.add(instantiationService.createInstance(ChatInputTipPresenter, { + container, + isEligible: () => true, + focusInput: () => { }, + }, noticeHost)); + return { presenter, container }; + }; + const previous = create(); + const replacement = create(); + previous.presenter.dispose(); + await timeout(100); + + const navigation = []; + for (const label of ['Next tip', 'Previous tip']) { + const arrow = replacement.container.querySelector(`[aria-label="${label}"]`); + assert.ok(arrow); + arrow.click(); + await Promise.resolve(); + navigation.push(replacement.container.querySelector('.rendered-markdown')?.textContent); + } + + assert.deepStrictEqual({ + navigation, + visible: !!replacement.presenter.current, + }, { + navigation: ['Second tip', 'First tip'], + visible: true, + }); + }); + + test('refreshes the background send tip when its setting changes without moving focus for unrelated changes', async () => { + const store = disposables.add(new DisposableStore()); + const key = ChatConfiguration.SendInBackgroundTipEnabled; + const configuration = new TestConfigurationService({ [key]: true }); + store.add(configuration.onDidChangeConfigurationEmitter); + const contextKeyService = store.add(new ContextKeyService(configuration)); + contextKeyService.createKey(IsSessionsWindowContext.key, true); + contextKeyService.createKey(ChatContextKeys.enabled.key, true); + contextKeyService.createKey('sessionIsCreated', false); + const definition = TIP_CATALOG.find(tip => tip.id === 'tip.sendInBackground'); + assert.ok(definition?.when); + const when = definition.when; + const noticeHost = store.add(new ChatInputNoticeHost(() => { })); + const fixture = createPresenter(store, noticeHost, { + contextKeyService, + getTip: () => contextKeyService.contextMatchesRules(when) + ? { id: definition.id, content: new MarkdownString('[Customize the shortcut](https://example.com)') } + : undefined, + }); + store.add(fixture.presenter); + + async function updateConfiguration(setting: string, value: boolean): Promise { + await configuration.setUserConfiguration(setting, value); + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial({ + source: ConfigurationTarget.USER, + affectedKeys: new Set([setting]), + })); + } + + const showing = [fixture.showing()]; + fixture.container.querySelector('a')?.focus(); + await updateConfiguration('editor.wordWrap', true); + const callsAfterUnrelatedChange = fixture.welcomeTipCalls(); + const focusedAfterUnrelatedChange = fixture.presenter.current?.hasFocus(); + await updateConfiguration(key, false); + showing.push(fixture.showing()); + await updateConfiguration(key, true); + showing.push(fixture.showing()); + await updateConfiguration(key, false); + showing.push(fixture.showing()); + + assert.deepStrictEqual({ + showing, + callsAfterUnrelatedChange, + focusedAfterUnrelatedChange, + focusInputCalls: fixture.focusInputCalls(), + }, { + showing: [true, false, true, false], + callsAfterUnrelatedChange: 1, + focusedAfterUnrelatedChange: true, + focusInputCalls: 1, + }); + }); + test('replaces the rendered tip when a contextual provider changes', () => { const store = disposables.add(new DisposableStore()); const noticeHost = store.add(new ChatInputNoticeHost(() => { })); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatModelConfigurationStore.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatModelConfigurationStore.test.ts index 348a28ffd727..ee8ae6591aca 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatModelConfigurationStore.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatModelConfigurationStore.test.ts @@ -462,6 +462,35 @@ suite('ChatModelConfigurationStore', () => { } } + test('a started chat shows the values its session runs with over preferences it inherited but never set', async () => { + const storage = store.add(new InMemoryStorageService()); + const control = createControllableService(); + control.setSchema(schemaWithContextSize, ['thinkingEffort', 'contextSize']); + await createStore(storage, control.service).setModelConfiguration(MODEL, { thinkingEffort: 'low', contextSize: 1_000_000 }); + const report = { + models: { [MODEL]: { defaults: { thinkingEffort: 'medium', contextSize: 200_000 }, readOnly: [] } }, + current: { + id: MODEL, config: { + thinkingEffort: 'high', contextSize: 200_000, + [modelConfigurationSourceKey('thinkingEffort')]: 'default', + [modelConfigurationSourceKey('contextSize')]: 'default', + } + }, + }; + const draft = createStore(storage, control.service); + draft.setSessionModelConfiguration(report); + const started = createStore(storage, control.service, () => false); + started.restoreModelConfiguration(MODEL, { thinkingEffort: 'high' }, false); + started.setSessionModelConfiguration(report); + const restored = started.getModelConfiguration(MODEL); + await started.setModelConfiguration(MODEL, { contextSize: 1_000_000 }); + assert.deepStrictEqual({ draft: draft.getModelConfiguration(MODEL), restored, picked: started.getModelConfiguration(MODEL) }, { + draft: { thinkingEffort: 'low', contextSize: 1_000_000, [modelConfigurationSourceKey('thinkingEffort')]: 'explicit', [modelConfigurationSourceKey('contextSize')]: 'explicit' }, + restored: { thinkingEffort: 'high', contextSize: 200_000, [modelConfigurationSourceKey('thinkingEffort')]: 'explicit', [modelConfigurationSourceKey('contextSize')]: 'default' }, + picked: { thinkingEffort: 'high', contextSize: 1_000_000, [modelConfigurationSourceKey('thinkingEffort')]: 'explicit', [modelConfigurationSourceKey('contextSize')]: 'explicit' }, + }); + }); + for (const started of [false, true]) { test(`standard read-only defaults apply without provenance metadata, started=${started}`, async () => { const storage = store.add(new InMemoryStorageService()); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatSessionArchiveNudge.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatSessionArchiveNudge.test.ts index b37eb5a685aa..cdddfc60bdc8 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/chatSessionArchiveNudge.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/chatSessionArchiveNudge.test.ts @@ -163,7 +163,7 @@ suite('ChatSessionArchiveNudge', () => { mergeIcon: true, decorativeIcon: 'true', iconBeforeTitle: true, - overview: 'Archive this session to hide it from the sessions list and focus on your remaining tasks.', + overview: 'Archive this session to set it aside and focus on your remaining tasks.', overviewOutsideDetails: true, detailsExpanded: false, detailsLabel: 'What Does "Archive" Do?', @@ -419,7 +419,7 @@ suite('ChatSessionArchiveNudge', () => { }, { title: 'PR merged. Mark this session as done?', multipleTitle: 'All PRs merged. Mark this session as done?', - description: 'Mark this session as done to hide it from the sessions list and focus on your remaining tasks.', + description: 'Mark this session as done to set it aside and focus on your remaining tasks.', disclosure: 'What Does "Mark as Done" Do?', recovery: 'The session is not deleted. Ask your agent to find it, or look in the "Done" section of the sessions list. You can restore it anytime.', worktree: 'The worktree created for this session will be deleted. You can recreate it by restoring the session.', @@ -607,6 +607,55 @@ suite('ChatSessionArchiveNudge', () => { }); }); + test('uses chat wording when marking only the chat as done, including after updates and for errors', async () => { + const pending = new DeferredPromise(); + const { widget, archive, errors } = createWidget(undefined, undefined, ChatSessionArchiveActionWording.MarkAsDone); + const describe = () => ({ + title: widget.domNode.querySelector('h3')?.textContent, + description: widget.domNode.querySelector('.chat-session-archive-nudge-description')?.textContent, + recovery: widget.domNode.querySelector('details > p')?.textContent, + worktreeHidden: widget.domNode.querySelector('.chat-session-archive-nudge-worktree')?.hidden, + }); + const session = describe(); + widget.setOptions(options({ archivesChat: true, pullRequestCount: 2, onArchive: () => pending.p })); + const chat = describe(); + archive.click(); + await pending.error(new Error('Chat archive failed')); + + assert.deepStrictEqual({ session, chat, errors }, { + session: { + title: 'PR merged. Mark this session as done?', + description: 'Mark this session as done to set it aside and focus on your remaining tasks.', + recovery: 'The session is not deleted. Ask your agent to find it, or look in the "Done" section of the sessions list. You can restore it anytime.', + worktreeHidden: true, + }, + chat: { + title: 'All PRs merged. Mark this chat as done?', + description: 'Mark this chat as done to set it aside and focus on the rest of this session.', + recovery: 'Other chats in this session are not affected. This chat is not deleted. Look in the "Done" section of the sessions list. You can restore it anytime.', + worktreeHidden: true, + }, + errors: ['Unable to mark the chat as done: Chat archive failed'], + }); + }); + + test('keeps the session title treatment and its trigger out of chat suggestions', async () => { + const title = 'Tidy up this session.'; + const { widget, triggers } = createWidget({ archivesChat: true }, createAssignmentService(name => name === CHAT_SESSION_ARCHIVE_NUDGE_TITLE_TREATMENT ? title : undefined)); + await timeout(0); + const describe = () => ({ title: widget.domNode.querySelector('h3')?.textContent, triggers: [...triggers] }); + const chat = describe(); + widget.setOptions(options()); + const session = describe(); + widget.setOptions(options({ archivesChat: true })); + + assert.deepStrictEqual({ chat, session, chatAgain: describe().title }, { + chat: { title: 'PR merged. Archive this chat?', triggers: [CHAT_SESSION_ARCHIVE_NUDGE_ICON_TREATMENT] }, + session: { title, triggers: [CHAT_SESSION_ARCHIVE_NUDGE_ICON_TREATMENT, CHAT_SESSION_ARCHIVE_NUDGE_TITLE_TREATMENT] }, + chatAgain: 'PR merged. Archive this chat?', + }); + }); + test('updates content and callbacks without replacing focused controls', async () => { let oldActions = 0; let archives = 0; diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInlineAttachments.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInlineAttachments.test.ts index 955a0814a99f..b623fa1257dc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInlineAttachments.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInlineAttachments.test.ts @@ -8,6 +8,7 @@ import sinon from 'sinon'; import * as dom from '../../../../../../../../base/browser/dom.js'; import { timeout } from '../../../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../../../base/common/event.js'; +import { OS } from '../../../../../../../../base/common/platform.js'; import { DisposableStore, toDisposable } from '../../../../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../../../../../../base/test/common/mock.js'; @@ -17,7 +18,15 @@ import { CodeEditorWidget } from '../../../../../../../../editor/browser/widget/ import { EditorAutoIndentStrategy } from '../../../../../../../../editor/common/config/editorOptions.js'; import { Position } from '../../../../../../../../editor/common/core/position.js'; import { Range } from '../../../../../../../../editor/common/core/range.js'; +import { HoverStartMode, HoverStartSource } from '../../../../../../../../editor/contrib/hover/browser/hoverOperation.js'; import { Selection } from '../../../../../../../../editor/common/core/selection.js'; +import { IMarkerDecorationsService } from '../../../../../../../../editor/common/services/markerDecorations.js'; +import { EditorContributionCtor, EditorContributionInstantiation, MultiCommand } from '../../../../../../../../editor/browser/editorExtensions.js'; +import { ContentHoverController } from '../../../../../../../../editor/contrib/hover/browser/contentHoverController.js'; +import { ShowOrFocusHoverAction } from '../../../../../../../../editor/contrib/hover/browser/hoverActions.js'; +import { SHOW_OR_FOCUS_HOVER_ACTION_ID } from '../../../../../../../../editor/contrib/hover/browser/hoverActionIds.js'; +import { EditorContextKeys } from '../../../../../../../../editor/common/editorContextKeys.js'; +import { HoverAccessibleView, HoverAccessibilityHelp } from '../../../../../../../../editor/contrib/hover/browser/hoverAccessibleViews.js'; import { MoveLinesCommand } from '../../../../../../../../editor/contrib/linesOperations/browser/moveLinesCommand.js'; import { CopyLinesCommand } from '../../../../../../../../editor/contrib/linesOperations/browser/copyLinesCommand.js'; import { createCodeEditorServices, instantiateTestCodeEditor } from '../../../../../../../../editor/test/browser/testCodeEditor.js'; @@ -25,19 +34,36 @@ import { instantiateTextModel } from '../../../../../../../../editor/test/common import { IAgentHostConnectionsService } from '../../../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { IConfigurationService } from '../../../../../../../../platform/configuration/common/configuration.js'; import { IContextKeyService } from '../../../../../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyService } from '../../../../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IContextMenuService } from '../../../../../../../../platform/contextview/browser/contextView.js'; +import { KeybindingsRegistry } from '../../../../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { KeybindingResolver, ResultKind } from '../../../../../../../../platform/keybinding/common/keybindingResolver.js'; +import { ResolvedKeybindingItem } from '../../../../../../../../platform/keybinding/common/resolvedKeybindingItem.js'; +import { USLayoutResolvedKeybinding } from '../../../../../../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; +import { registerAction2 } from '../../../../../../../../platform/actions/common/actions.js'; +import { CommandsRegistry } from '../../../../../../../../platform/commands/common/commands.js'; import { TestConfigurationService } from '../../../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { CodeDataTransfers } from '../../../../../../../../platform/dnd/browser/dnd.js'; import { IFileService, IFileSystemWatcher } from '../../../../../../../../platform/files/common/files.js'; import { ServiceCollection } from '../../../../../../../../platform/instantiation/common/serviceCollection.js'; import { TestInstantiationService } from '../../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILabelService } from '../../../../../../../../platform/label/common/label.js'; +import { IProductService } from '../../../../../../../../platform/product/common/productService.js'; import { ISharedWebContentExtractorService } from '../../../../../../../../platform/webContentExtractor/common/webContentExtractor.js'; import { IExtensionService } from '../../../../../../../services/extensions/common/extensions.js'; import { ChatAttachmentModel } from '../../../../../browser/attachments/chatAttachmentModel.js'; import { ChatDynamicVariableModel } from '../../../../../browser/attachments/chatDynamicVariables.js'; import { IChatAttachmentResolveService } from '../../../../../browser/attachments/chatAttachmentResolveService.js'; -import { IChatWidget } from '../../../../../browser/chat.js'; +import { IChatWidget, IChatWidgetService } from '../../../../../browser/chat.js'; +import { ChatResponseAccessibleView } from '../../../../../browser/accessibility/chatResponseAccessibleView.js'; +import { ChatSubmitAction } from '../../../../../browser/actions/chatExecuteActions.js'; +import { ChatQueueMessageAction, ChatSteerWithMessageAction } from '../../../../../browser/actions/chatQueueActions.js'; +import { IChatAttachmentWidgetRegistry } from '../../../../../browser/attachments/chatAttachmentWidgetRegistry.js'; import { ChatInlineAttachments } from '../../../../../browser/widget/input/editor/chatInlineAttachments.js'; +import '../../../../../browser/widget/input/editor/chatInputEditorHover.js'; +import { GitHubResourceDetailsResolver } from '../../../../../../github/browser/githubResourceDetails.js'; +import { IManagedHover } from '../../../../../../../../base/browser/ui/hover/hover.js'; +import { IWorkbenchGitHubService } from '../../../../../../../services/github/common/githubService.js'; import { IChatWidgetContrib } from '../../../../../browser/widget/chatWidget.js'; import { ChatDragAndDrop } from '../../../../../browser/widget/chatDragAndDrop.js'; import { ChatContextKeys } from '../../../../../common/actions/chatContextKeys.js'; @@ -56,23 +82,31 @@ suite('ChatInlineAttachments', () => { readonly attachments: ChatAttachmentModel; readonly controller: ChatInlineAttachments; readonly instantiationService: TestInstantiationService; + readonly attachmentResolvers: (GitHubResourceDetailsResolver | undefined)[]; + setSessionResource(resource: URI): void; /** Adds a reference to the input, as accepting a completion does. */ addReference(reference: IDynamicVariable): void; /** Whether the pill right before the cursor is active, which Enter opens. */ isActive(): boolean; /** The prompt that the input stands for, and the ids of its attachments. */ state(): { prompt: string; attachments: string[] }; + /** What the pills that were rendered last show. */ + readonly rendered: IChatRequestVariableEntry[]; } /** * @param showsPills Whether the input's host shows pills, which a host * whose chat widget does not own the input, such as the Automation dialog's, * does not. + * @param showsSessionLinks Whether a widget can show the sessions that links in the input link to, as in the Agents window. */ - function createInput(text: string, showsPills = true, renderEditor = false): ITestInput { + function createInput(text: string, showsPills = true, renderEditor = false, showsSessionLinks = false, preview?: () => HTMLElement, previewHover?: IManagedHover): ITestInput { const disposables = store.add(new DisposableStore()); const configurationService = new TestConfigurationService({ [ChatConfiguration.InlineAttachmentsEnabled]: true }); const instantiationService = createCodeEditorServices(disposables, new ServiceCollection([IConfigurationService, configurationService])); + if (renderEditor && preview) { + instantiationService.stub(IContextKeyService, disposables.add(new ContextKeyService(configurationService))); + } instantiationService.stub(ILabelService, new class extends mock() { override getUriLabel(uri: URI): string { return uri.path; } }); @@ -81,21 +115,40 @@ suite('ChatInlineAttachments', () => { }); instantiationService.stub(ISharedWebContentExtractorService, new class extends mock() { }); instantiationService.stub(IChatAttachmentResolveService, new class extends mock() { }); + instantiationService.stub(IWorkbenchGitHubService, upcastPartial({ onDidChangeDefaultClient: Event.None })); + instantiationService.stub(IMarkerDecorationsService, upcastPartial({ getMarker: () => null })); + instantiationService.stub(IContextMenuService, upcastPartial({ + onDidShowContextMenu: Event.None, + onDidHideContextMenu: Event.None, + })); + instantiationService.stub(IAgentHostConnectionsService, upcastPartial({ resolveSessionResourceIdentity: () => undefined, })); instantiationService.stub(IExtensionService, new class extends mock() { override readonly extensions = []; }); + instantiationService.stub(IProductService, upcastPartial({ urlProtocol: 'code-oss' })); + instantiationService.stub(IChatAttachmentWidgetRegistry, upcastPartial({ + hasFactory: kind => showsSessionLinks && kind === 'sessionLink', + })); const model = disposables.add(instantiateTextModel(instantiationService, text)); let editor: ICodeEditor; if (renderEditor) { const container = dom.append(document.body, dom.$('.interactive-session')); disposables.add(toDisposable(() => container.remove())); + const overflowWidgetsDomNode = preview ? dom.append(document.body, dom.$('div')) : undefined; + if (overflowWidgetsDomNode) { + disposables.add(toDisposable(() => overflowWidgetsDomNode.remove())); + } editor = disposables.add(instantiationService.createInstance(CodeEditorWidget, dom.append(container, dom.$('div')), { dimension: { width: 600, height: 200 }, - }, { contributions: [], isSimpleWidget: true })); + overflowWidgetsDomNode, + }, { + contributions: preview ? [{ id: ContentHoverController.ID, ctor: ContentHoverController as EditorContributionCtor, instantiation: EditorContributionInstantiation.Lazy }] : [], + isSimpleWidget: true, + })); editor.setModel(model); } else { editor = disposables.add(instantiateTestCodeEditor(instantiationService, model)); @@ -121,6 +174,9 @@ suite('ChatInlineAttachments', () => { } override refreshParsedInput(): void { } }; + instantiationService.stub(IChatWidgetService, upcastPartial({ getWidgetByInputUri: () => widget })); + const attachmentResolvers: (GitHubResourceDetailsResolver | undefined)[] = []; + let sessionResource = URI.parse('chat-session:test-1'); const dnd = renderEditor ? disposables.add(instantiationService.createInstance(ChatDragAndDrop, () => widget, { get attachments() { return attachments.attachments; }, addAttachments: entries => attachments.addContext(...entries), @@ -129,11 +185,20 @@ suite('ChatInlineAttachments', () => { const container = editor.getContainerDomNode().parentElement!; dnd.addOverlay(container, container, editor.getContainerDomNode()); } + const rendered: IChatRequestVariableEntry[] = []; const controller = disposables.add(instantiationService.createInstance(ChatInlineAttachments, editor, attachments, { widget: showsPills ? widget : undefined, - createAttachmentWidget: (attachment: IChatRequestVariableEntry, container: HTMLElement) => { + get sessionResource() { return sessionResource; }, + createAttachmentWidget: (attachment, container, options) => { + attachmentResolvers.push(options.gitHubResourceDetailsResolver); + rendered.push(attachment); const element = dom.append(container, dom.$('span.chat-attached-context-attachment', undefined, attachment.name)); - return { element, onDidDelete: Event.None, onDidOpen: Event.None, dispose: () => element.remove() }; + const onDidChangePreview = new Emitter(); + return { + element, supportsPreview: !!preview, getPreviewHoverContent: preview, previewHover, + onDidChangePreview: onDidChangePreview.event, onDidDelete: Event.None, onDidOpen: Event.None, + dispose: () => { onDidChangePreview.fire(); onDidChangePreview.dispose(); element.remove(); }, + }; }, removeAttachments: (removed: readonly IChatRequestVariableEntry[]) => attachments.delete(...removed.map(attachment => attachment.id)), resetDragState: () => dnd?.resetDragState(), @@ -144,12 +209,15 @@ suite('ChatInlineAttachments', () => { attachments, controller, instantiationService, + attachmentResolvers, + setSessionResource: resource => { sessionResource = resource; }, addReference: reference => dynamicVariableModel.addReference(reference), isActive: () => !!editor.invokeWithinContext(accessor => accessor.get(IContextKeyService).getContextKeyValue(ChatContextKeys.inputInlineAttachmentActive.key)), state: () => ({ prompt: controller.project()?.text ?? editor.getValue(), attachments: attachments.attachments.map(attachment => attachment.id), }), + rendered, }; } @@ -162,6 +230,284 @@ suite('ChatInlineAttachments', () => { return timeout(0); } + test('Show or Focus Hover is scoped to the composer text input, not its toolbar or attachments', () => { + const binding = KeybindingsRegistry.getDefaultKeybindings().find(binding => + binding.command === SHOW_OR_FOCUS_HOVER_ACTION_ID && + binding.when?.keys().includes(ChatContextKeys.inChatInput.key)); + assert.ok(binding?.when); + const configuration = new TestConfigurationService(); + const context = store.add(new ContextKeyService(configuration)); + ChatContextKeys.inChatInput.bindTo(context).set(true); + const textInputFocus = EditorContextKeys.textInputFocus.bindTo(context); + const toolbarOrAttachment = context.contextMatchesRules(binding.when); + textInputFocus.set(true); + const composer = context.contextMatchesRules(binding.when); + textInputFocus.set(false); + configuration.setUserConfiguration(ChatConfiguration.InlineAttachmentsEnabled, false); + assert.deepStrictEqual({ + toolbarOrAttachment, + composer, + toolbarOrAttachmentWithInlineDisabled: context.contextMatchesRules(binding.when), + }, { toolbarOrAttachment: false, composer: true, toolbarOrAttachmentWithInlineDisabled: false }); + }); + + test('Enter in the focused reference hover does not open the active pill or submit the draft', async () => { + // Other suites in the same run may have registered these actions already, and the registry rejects duplicates. + for (const action of [ChatSubmitAction, ChatQueueMessageAction, ChatSteerWithMessageAction]) { + if (!CommandsRegistry.getCommand(action.ID)) { + store.add(registerAction2(action)); + } + } + const items = KeybindingsRegistry.getDefaultKeybindingsForOS(OS).flatMap(item => { + if (!item.keybinding || ![ChatSubmitAction.ID, ChatQueueMessageAction.ID, ChatSteerWithMessageAction.ID, 'workbench.action.chat.openInlineAttachment'].includes(item.command ?? '')) { + return []; + } + return [new ResolvedKeybindingItem(USLayoutResolvedKeybinding.resolveKeybinding(item.keybinding, OS)[0], item.command, item.commandArgs, item.when ?? undefined, true, null, false)]; + }); + const resolver = new KeybindingResolver(items, [], () => { }); + const actual: { activePill: boolean; composerCommand: string | null | undefined; enterCommands: (string | null | undefined)[]; enterPrevented: boolean[] }[] = []; + for (const [position, defaultAction] of [ + [new Position(1, 9), 'queue'], + [new Position(1, 8), 'queue'], + [new Position(1, 9), 'steer'], + [new Position(1, 8), 'steer'], + ] as const) { + const content = dom.$('div'); + const link = dom.append(content, dom.$('a', { href: '#reference' }, 'Reference')); + const button = dom.append(content, dom.$('button', { type: 'button' }, 'Branch')); + const input = createInput('review ', true, true, false, () => content); + input.editor.setPosition(new Position(1, 8)); + input.attachments.addContext({ + kind: 'generic', + id: 'github-context:https://github.com/microsoft/vscode/issues/123', + name: 'microsoft/vscode#123', + value: '', + }); + await settle(); + input.editor.invokeWithinContext(accessor => { + const context = accessor.get(IContextKeyService); + ChatContextKeys.enabled.bindTo(context).set(true); + ChatContextKeys.inChatInput.bindTo(context).set(true); + ChatContextKeys.inputHasText.bindTo(context).set(true); + ChatContextKeys.inputHasSendableContent.bindTo(context).set(true); + ChatContextKeys.chatSessionOptionsValid.bindTo(context).set(true); + ChatContextKeys.requestInProgress.bindTo(context).set(true); + context.createKey(`config.${ChatConfiguration.RequestQueueingDefaultAction}`, defaultAction); + }); + const contextService = input.instantiationService.get(IContextKeyService); + const resolveEnter = (target: Element) => { + const result = resolver.resolve(contextService.getContext(target), [], 'Enter'); + return result.kind === ResultKind.KbFound ? result.commandId : undefined; + }; + input.editor.focus(); + input.editor.setPosition(position, 'keyboard'); + const activePill = input.isActive(); + const composerCommand = resolveEnter(input.editor.getDomNode()!); + ContentHoverController.get(input.editor)!.showContentHover(new Range(1, 9, 1, 9), HoverStartMode.Immediate, HoverStartSource.Keyboard, true); + await settle(); + const enterCommands: (string | null | undefined)[] = []; + const enterPrevented: boolean[] = []; + const container = content.closest('.monaco-hover')!; + const keydownListener = store.add(dom.addDisposableListener(dom.getWindow(container).document, 'keydown', event => { + if (event.key === 'Enter' && event.target instanceof Element) { + const command = resolveEnter(event.target); + enterCommands.push(command); + if (command) { + event.preventDefault(); + } + } + })); + for (const target of [container, link, button]) { + target.focus(); + target.dispatchEvent(new FocusEvent('focusin', { bubbles: true })); + enterPrevented.push(!target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true }))); + } + keydownListener.dispose(); + actual.push({ activePill, composerCommand, enterCommands, enterPrevented }); + ContentHoverController.get(input.editor)!.hideContentHover(); + await settle(); + } + assert.deepStrictEqual(actual, [ + { activePill: true, composerCommand: 'workbench.action.chat.openInlineAttachment', enterCommands: [undefined, undefined, undefined], enterPrevented: [false, false, false] }, + { activePill: false, composerCommand: ChatQueueMessageAction.ID, enterCommands: [undefined, undefined, undefined], enterPrevented: [false, false, false] }, + { activePill: true, composerCommand: 'workbench.action.chat.openInlineAttachment', enterCommands: [undefined, undefined, undefined], enterPrevented: [false, false, false] }, + { activePill: false, composerCommand: ChatSteerWithMessageAction.ID, enterCommands: [undefined, undefined, undefined], enterPrevented: [false, false, false] }, + ]); + }); + + test('keyboard activation reveals the shared hover without focusing it or showing it after edits', async () => { + const events: string[] = []; + const previewHover: IManagedHover = { + show: focus => events.push(`show:${focus}`), + hide: () => events.push('hide'), + update: async () => { }, + dispose: () => { }, + }; + const input = createInput('review tail', true, true, false, () => dom.$('div'), previewHover); + input.editor.setPosition(new Position(1, 8)); + input.attachments.addContext({ + kind: 'generic', + id: 'github-context:https://github.com/microsoft/vscode/issues/123', + name: 'microsoft/vscode#123', + value: '', + }); + await settle(); + const afterInsertion = [...events]; + input.editor.focus(); + input.editor.trigger('keyboard', 'cursorLeft', {}); + input.editor.trigger('keyboard', 'cursorRight', {}); + const afterKeyboardActivation = [...events]; + input.editor.trigger('keyboard', 'cursorRight', {}); + input.editor.setPosition(new Position(1, 9)); + assert.deepStrictEqual({ + afterInsertion, + afterKeyboardActivation, + afterLeavingAndProgrammaticReturn: events, + focusInComposer: input.editor.hasTextFocus(), + }, { afterInsertion: [], afterKeyboardActivation: ['show:false'], afterLeavingAndProgrammaticReturn: ['show:false', 'hide'], focusInComposer: true }); + }); + + test('Show or Focus Hover displays reference details and Escape returns to the draft', async () => { + const content = dom.$('div', undefined, 'Issue title and description'); + let rendered = 0; + let sharedPreviewVisible = false; + const previewHover = upcastPartial({ + show: () => { sharedPreviewVisible = true; }, + hide: () => { sharedPreviewVisible = false; }, + }); + const input = createInput('review ', true, true, false, () => { + rendered++; + return content; + }, previewHover); + const hover = ContentHoverController.get(input.editor)!; + input.editor.setPosition(new Position(1, 8)); + input.attachments.addContext({ + kind: 'generic', + id: 'github-context:https://github.com/microsoft/vscode/issues/123', + name: 'microsoft/vscode#123', + value: '', + }); + await settle(); + input.editor.focus(); + input.editor.trigger('keyboard', 'cursorLeft', {}); + input.editor.trigger('keyboard', 'cursorRight', {}); + await settle(); + input.editor.setPosition(new Position(1, 9), 'keyboard'); + hover.showContentHover(Range.fromPositions(input.editor.getPosition()!), HoverStartMode.Immediate, HoverStartSource.Mouse, false); + await settle(); + const shownForMouse = hover.isHoverVisible; + const renderedBeforeCommand = rendered; + const sharedPreviewBeforeCommand = sharedPreviewVisible; + const before = input.state(); + input.editor.focus(); + const context = input.editor.invokeWithinContext(accessor => { + const contextKeyService = accessor.get(IContextKeyService); + ChatContextKeys.inChatInput.bindTo(contextKeyService).set(true); + ChatContextKeys.inChatSession.bindTo(contextKeyService).set(true); + return { getValue: (key: string) => contextKeyService.getContextKeyValue(key) }; + }); + const hoverBinding = KeybindingsRegistry.getDefaultKeybindings().some(binding => + binding.command === SHOW_OR_FOCUS_HOVER_ACTION_ID && + binding.when?.evaluate(context)); + assert.deepStrictEqual({ editorTextFocus: EditorContextKeys.editorTextFocus.evaluate(context), hoverBinding }, { + editorTextFocus: false, hoverBinding: true, + }); + input.editor.invokeWithinContext(accessor => new ShowOrFocusHoverAction().run(accessor, input.editor, { focus: true })); + await settle(); + const shown = hover.isHoverVisible; + const accessibleView = new HoverAccessibleView(); + const accessibilityHelp = new HoverAccessibilityHelp(); + const command = new MultiCommand({ id: 'test.referenceAccessibleView', precondition: undefined }); + let provider: ReturnType; + const chatResponse = new ChatResponseAccessibleView(); + store.add(command.addImplementation(chatResponse.priority, chatResponse.name, () => true, chatResponse.when)); + store.add(command.addImplementation(accessibleView.priority, accessibleView.name, accessor => { + provider = accessibleView.getProvider(accessor); + return !!provider; + }, accessibleView.when)); + // Hidden Electron test windows don't dispatch native focus events. + const focusedElement = dom.getActiveElement(); + focusedElement?.dispatchEvent(new FocusEvent('focusin', { bubbles: true })); + const focusedContext = input.instantiationService.get(IContextKeyService).getContext(focusedElement); + assert.deepStrictEqual({ + outsideEditor: !input.editor.getDomNode()!.contains(focusedElement), + accessibleViewAvailable: accessibleView.when.evaluate(focusedContext), + accessibilityHelpAvailable: accessibilityHelp.when.evaluate(focusedContext), + }, { outsideEditor: true, accessibleViewAvailable: true, accessibilityHelpAvailable: true }); + input.instantiationService.invokeFunction(accessor => command.runCommand(accessor, undefined)); + assert.ok(provider); + store.add(provider); + provider.onOpen?.(); + const accessibleContent = provider.provideContent(); + assert.deepStrictEqual({ shownForMouse, renderedBeforeCommand, renderedAfterCommand: rendered > 0, sharedPreviewBeforeCommand, sharedPreviewAfterCommand: sharedPreviewVisible, shown, accessibleContent }, { + shownForMouse: false, renderedBeforeCommand: 0, renderedAfterCommand: true, sharedPreviewBeforeCommand: true, sharedPreviewAfterCommand: false, shown: true, accessibleContent: 'Issue title and description', + }); + let contentUpdates = 0; + store.add(hover.onHoverContentsChanged(() => contentUpdates++)); + content.textContent = 'Refreshed issue description'; + await settle(); + const refreshedAccessibleContent = provider.provideContent(); + provider.onClose(); + const container = content.closest('.monaco-hover'); + assert.ok(container); + container.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + await settle(); + assert.deepStrictEqual({ + contentUpdated: contentUpdates > 0, + refreshedAccessibleContent, + dismissed: !hover.isHoverVisible, + focusReturned: input.editor.hasTextFocus(), + draft: input.state(), + }, { contentUpdated: true, refreshedAccessibleContent: 'Refreshed issue description', dismissed: true, focusReturned: true, draft: before }); + input.editor.invokeWithinContext(accessor => new ShowOrFocusHoverAction().run(accessor, input.editor, { focus: true })); + await settle(); + input.controller.refresh(); + await settle(); + const reference = input.editor.getDomNode()!.querySelector('.chat-inline-attachment .chat-attached-context-attachment'); + assert.ok(reference); + const sandbox = sinon.createSandbox(); + store.add(toDisposable(() => sandbox.restore())); + const click = sandbox.spy(reference, 'click'); + assert.deepStrictEqual({ + dismissedOnRefresh: !hover.isHoverVisible, + opensActiveReference: input.controller.openActivePill(), + clicks: click.callCount, + draft: input.state(), + }, { dismissedOnRefresh: true, opensActiveReference: true, clicks: 1, draft: before }); + }); + + test('the input owns one GitHub resolver across pill rerenders and warms only new arrivals', async () => { + const sandbox = sinon.createSandbox(); + store.add(toDisposable(() => sandbox.restore())); + const prefetch = sandbox.stub(GitHubResourceDetailsResolver.prototype, 'prefetchIssue').resolves(undefined); + const input = createInput('review '); + input.editor.setPosition(new Position(1, 8)); + const issue = (number: number): IChatRequestVariableEntry => ({ + kind: 'generic', + id: `github-context:https://github.com/microsoft/vscode/issues/${number}`, + name: `microsoft/vscode#${number}`, + value: '', + }); + input.attachments.addContext(issue(123)); + await settle(); + const resolver = input.attachmentResolvers[0]; + input.controller.refresh(); + await settle(); + input.attachments.addContext(issue(456)); + await settle(); + input.setSessionResource(URI.parse('chat-session:test-2')); + input.attachments.delete(issue(123).id, issue(456).id); + input.editor.getModel()!.setValue('review '); + input.editor.setPosition(new Position(1, 8)); + input.attachments.addContext(issue(789)); + await settle(); + assert.deepStrictEqual({ + hasResolver: !!resolver, + sameResolver: input.attachmentResolvers.every(value => value === resolver), + warmed: prefetch.args.map(([target]) => target.number), + }, { hasResolver: true, sameResolver: true, warmed: [456] }); + }); + function dispatchDrag(element: HTMLElement, type: string, dataTransfer: DataTransfer): DragEvent { const event = new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer }); element.dispatchEvent(event); @@ -583,6 +929,71 @@ suite('ChatInlineAttachments', () => { }); }); + test('a session link becomes a pill that shows the session where a widget can, while the prompt keeps the link', async () => { + const link = 'code-oss://agents/agent-host-session/copilotcli/session-1'; + const text = `continue ${link} please`; + const shown = createInput(text, true, false, true); + const hidden = createInput(text); + await settle(); + + assert.deepStrictEqual({ + shown: { + input: shown.editor.getValue(), + ...shown.state(), + forModel: shown.controller.project([], { forModel: true })?.text, + rendered: shown.rendered.map(entry => ({ kind: entry.kind, name: entry.name, value: String(entry.value) })), + }, + hidden: { input: hidden.editor.getValue(), rendered: hidden.rendered.length }, + }, { + shown: { + input: 'continue \uFFFC please', + prompt: text, + attachments: [], + forModel: text, + rendered: [{ kind: 'sessionLink', name: 'Session', value: 'agent-host-session://copilotcli/session-1' }], + }, + hidden: { input: text, rendered: 0 }, + }); + }); + + test('a session link within other text becomes a pill too, which the prompt says exactly where it is', async () => { + const link = 'agent-host-session://copilotcli/session-1'; + const collapse = async (text: string) => { + const input = createInput(text, true, false, true); + await settle(); + return { input: input.editor.getValue(), prompt: input.state().prompt }; + }; + + // A pill right after a link ends the link, which becomes a pill too. + assert.deepStrictEqual(await Promise.all([`check (${link}), then`, `{"session":"${link}"}`, `${link}\uFFFC`].map(collapse)), [ + { input: 'check (\uFFFC), then', prompt: `check (${link}), then` }, + { input: '{"session":"\uFFFC"}', prompt: `{"session":"${link}"}` }, + { input: '\uFFFC\uFFFC', prompt: link }, + ]); + }); + + test('a session link pill dragged into parentheses keeps the link exactly where it is, during and after the move', async () => { + const link = 'agent-host-session://copilotcli/session-1'; + const input = createInput(`see () ${link}`, true, true, true); + await settle(); + const container = input.editor.getContainerDomNode(); + const widget = container.querySelector('.chat-inline-attachment .chat-attached-context-attachment')!; + const dataTransfer = new DataTransfer(); + sinon.stub(input.editor, 'getTargetAtClientPoint').returns(dropTarget(new Position(1, 6))); + const duringMove: (string | undefined)[] = []; + const listener = input.editor.onDidChangeModelContent(() => duringMove.push(input.controller.project()?.text)); + dispatchDrag(widget, dom.EventType.DRAG_START, dataTransfer); + dispatchDrag(container, dom.EventType.DRAG_OVER, dataTransfer); + dispatchDrag(container, dom.EventType.DROP, dataTransfer); + listener.dispose(); + await settle(); + + assert.deepStrictEqual({ duringMove, moved: input.state().prompt }, { + duringMove: [`see (${link}) `], + moved: `see (${link}) `, + }); + }); + test('shows images inline', async () => { const input = createInput('look at '); input.editor.setPosition(new Position(1, 9)); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputCommandArgumentHint.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputCommandArgumentHint.test.ts index 9419128afb4f..9dae871f2190 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputCommandArgumentHint.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputCommandArgumentHint.test.ts @@ -264,7 +264,7 @@ suite('InputEditorCommandArgumentHint', () => { id: 'file:///skills/design-prep/SKILL.md', range: new Range(1, 1, 1, 13), data: { $mid: 'agentHostCompletion', kind: 'skill' }, - _meta: { uri: 'file:///skills/design-prep/SKILL.md', argumentHint: '' }, + _meta: { argumentHint: '' }, }; const other: IDynamicVariable = { ...skill, id: 'other', data: 'file:///other.md' }; assert.deepStrictEqual({ skill: run('/design-prep ', [skill]), other: run('/design-prep ', [other]) }, { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputEditorContrib.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputEditorContrib.test.ts index 9999d22b70a9..5edbe69669e1 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputEditorContrib.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatInputEditorContrib.test.ts @@ -4,13 +4,50 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { DisposableStore } from '../../../../../../../../base/common/lifecycle.js'; +import sinon from 'sinon'; +import { DeferredPromise } from '../../../../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../../../../base/common/event.js'; +import { Disposable, DisposableStore } from '../../../../../../../../base/common/lifecycle.js'; +import { constObservable, observableValue } from '../../../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../../base/test/common/utils.js'; +import { IEditorMouseEvent, MouseTargetType } from '../../../../../../../../editor/browser/editorBrowser.js'; +import { ICodeEditorService } from '../../../../../../../../editor/browser/services/codeEditorService.js'; +import { Position } from '../../../../../../../../editor/common/core/position.js'; import { Range } from '../../../../../../../../editor/common/core/range.js'; +import { OffsetRange } from '../../../../../../../../editor/common/core/ranges/offsetRange.js'; +import { Selection } from '../../../../../../../../editor/common/core/selection.js'; +import { IDecorationOptions } from '../../../../../../../../editor/common/editorCommon.js'; import { withTestCodeEditor } from '../../../../../../../../editor/test/browser/testCodeEditor.js'; -import { IChatWidget } from '../../../../../browser/chat.js'; +import { isIMenuItem, MenuId, MenuRegistry } from '../../../../../../../../platform/actions/common/actions.js'; +import { agentHostConnectionKinds } from '../../../../../../../../platform/agentHost/test/common/testAgentHostResourceUriMappers.js'; +import { CommandsRegistry } from '../../../../../../../../platform/commands/common/commands.js'; +import { TestConfigurationService } from '../../../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IResourceEditorInput } from '../../../../../../../../platform/editor/common/editor.js'; +import { TestInstantiationService } from '../../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../../../../platform/label/common/label.js'; +import { TestThemeService } from '../../../../../../../../platform/theme/test/common/testThemeService.js'; +import { IEditorService } from '../../../../../../../services/editor/common/editorService.js'; +import { IChatWidget, IChatWidgetService } from '../../../../../browser/chat.js'; import { ChatWidget } from '../../../../../browser/widget/chatWidget.js'; import '../../../../../browser/widget/input/editor/chatInputEditorContrib.js'; +import { ChatContextKeys } from '../../../../../common/actions/chatContextKeys.js'; +import { AgentHostCompletionReferenceKind, IChatRequestVariableEntry, toAgentHostCompletionVariableEntry } from '../../../../../common/attachments/chatVariableEntries.js'; +import { IChatMode } from '../../../../../common/chatModes.js'; +import { ICustomizationHarnessService } from '../../../../../common/customizationHarnessService.js'; +import { IChatAgentService } from '../../../../../common/participants/chatAgents.js'; +import { IPromptsService, IResolvedChatPromptSlashCommand } from '../../../../../common/promptSyntax/service/promptsService.js'; +import { ChatRequestDynamicVariablePart, ChatRequestSlashPromptPart, ChatRequestTextPart, IParsedChatRequestPart } from '../../../../../common/requestParser/chatParserTypes.js'; +import { ChatRequestParser } from '../../../../../common/requestParser/chatRequestParser.js'; +import { IChatVariablesService } from '../../../../../common/attachments/chatVariables.js'; +import { IChatSlashCommandService } from '../../../../../common/participants/chatSlashCommands.js'; +import { IChatRequestViewModel } from '../../../../../common/model/chatViewModel.js'; +import { ToolAndToolSetEnablementMap } from '../../../../../common/tools/languageModelToolsService.js'; +import { messageAttachmentsToVariableData } from '../../../../../browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { MessageAttachmentKind } from '../../../../../../../../platform/agentHost/common/state/protocol/state.js'; suite('ChatTokenDeleter', () => { @@ -106,3 +143,372 @@ suite('ChatTokenDeleter', () => { }); }); }); + +suite('InputEditorDecorations', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + teardown(() => sinon.restore()); + + function referencePart(startColumn: number, entry: IChatRequestVariableEntry): ChatRequestDynamicVariablePart { + const endColumn = startColumn + entry.name.length; + return new ChatRequestDynamicVariablePart( + new OffsetRange(startColumn - 1, endColumn - 1), new Range(1, startColumn, 1, endColumn), + entry.name, entry.id, entry.modelDescription, entry.value, undefined, undefined, false, false, entry._meta, + ); + } + + function textPart(startColumn: number, text: string): ChatRequestTextPart { + return new ChatRequestTextPart(new OffsetRange(startColumn - 1, startColumn - 1 + text.length), new Range(1, startColumn, 1, startColumn + text.length), text); + } + + function createDecorations(parts: readonly IParsedChatRequestPart[], prompt?: IResolvedChatPromptSlashCommand) { + const ctor = ChatWidget.CONTRIBS.find(contrib => contrib.name === 'InputEditorDecorations'); + assert.ok(ctor, 'InputEditorDecorations should be registered as a chat widget contribution'); + const activeEditorChanged = store.add(new Emitter()); + const parsedInputChanged = store.add(new Emitter()); + const decorations = new Map(); + const openedResources: string[] = []; + const openEditor = sinon.stub().callsFake(async (input: IResourceEditorInput) => { + openedResources.push(input.resource.toString()); + return undefined; + }); + const resolvePromptSlashCommand = sinon.stub().resolves(prompt); + let updated = new DeferredPromise(); + function createEditor(parts: readonly IParsedChatRequestPart[]) { + let parsedInput = { parts, text: parts.map(part => part.text).join('') }; + let selection = new Selection(1, 1, 1, 1); + const mouseDown = store.add(new Emitter()); + const mouseUp = store.add(new Emitter()); + const inputEditor = upcastPartial({ + getValue: () => parsedInput.text, + getPosition: () => selection.getPosition(), + getSelection: () => selection, + hasTextFocus: () => false, + getModel: () => null, + getId: () => 'test-chat-input', + onDidChangeModelContent: Event.None, + onDidChangeConfiguration: Event.None, + onMouseDown: mouseDown.event, + onMouseUp: mouseUp.event, + setDecorationsByType: (_owner, key, options) => { + decorations.set(key, options); + if (key === 'chat-variable-text') { + updated.complete(); + } + return []; + }, + }); + return { + inputEditor, + get parsedInput() { return parsedInput; }, + setPosition: (column: number) => { selection = new Selection(1, column, 1, column); }, + setSelection: (startColumn: number, endColumn: number) => { selection = new Selection(1, startColumn, 1, endColumn); }, + setInput: (parts: readonly IParsedChatRequestPart[]) => { + updated = new DeferredPromise(); + parsedInput = { parts, text: parts.map(part => part.text).join('') }; + parsedInputChanged.fire(); + return updated.p; + }, + click: (column: number) => { + mouseDown.fire(mouseEvent(column)); + mouseUp.fire(mouseEvent(column)); + }, + drag: (from: number, to: number) => { + mouseDown.fire(mouseEvent(from)); + mouseUp.fire(mouseEvent(to)); + }, + rightClick: (column: number) => { + mouseDown.fire(mouseEvent(column, false)); + mouseUp.fire(mouseEvent(column, false)); + }, + mouseDown: (column: number) => mouseDown.fire(mouseEvent(column)), + mouseUp: (column: number) => mouseUp.fire(mouseEvent(column)), + }; + } + const mainEditor = createEditor(parts); + let activeEditor = mainEditor; + const widget = upcastPartial({ + get inputEditor() { return activeEditor.inputEditor; }, + get parsedInput() { return activeEditor.parsedInput; }, + getContrib: () => undefined, + viewModel: upcastPartial>({ + sessionResource: URI.parse('agent-host-copilot:/test'), + onDidChange: Event.None, + get editing() { return activeEditor === mainEditor ? undefined : upcastPartial({}); }, + }), + input: upcastPartial({ + sandboxToggleChecked: observableValue('sandboxToggleChecked', false), + currentModeObs: constObservable(upcastPartial({ description: constObservable(undefined) })), + }), + onDidChangeParsedInput: parsedInputChanged.event, + onDidChangeViewModel: Event.None, + onDidSubmitAgent: Event.None, + onDidChangeActiveInputEditor: activeEditorChanged.event, + }); + const contribution = store.add(new ctor( + widget, + upcastPartial({ registerDecorationType: () => Disposable.None }), + new TestThemeService(), + upcastPartial({ onDidChangeAgents: Event.None }), + upcastPartial({ getUriLabel: uri => uri.path }), + upcastPartial({ onDidChangeSlashCommands: Event.None, resolvePromptSlashCommand }), + upcastPartial({ openEditor }), + )); + sinon.stub(widget, 'getContrib').withArgs(contribution.id).returns(contribution); + const instantiation = store.add(new TestInstantiationService()); + instantiation.stub(IChatWidgetService, upcastPartial({ lastFocusedWidget: widget })); + + function mouseEvent(column: number, leftButton = true): IEditorMouseEvent { + return { + event: upcastPartial({ leftButton }), + target: { + type: MouseTargetType.CONTENT_TEXT, + position: new Position(1, column), + range: new Range(1, column, 1, column), + element: null, + mouseColumn: column, + detail: { mightBeForeignElement: false, injectedText: null }, + }, + }; + } + + return { + ...mainEditor, + openedResources, + resolvePromptSlashCommand, + decorations, + openSkillAtCursor: async () => { + const command = CommandsRegistry.getCommand('workbench.action.chat.openSkillAtCursor'); + assert.ok(command, 'Open Skill at Cursor should be registered'); + await instantiation.invokeFunction(command.handler); + }, + whenUpdated: () => updated.p, + editSentMessage: (editParts: readonly IParsedChatRequestPart[] = parts) => { + updated = new DeferredPromise(); + activeEditor = createEditor(editParts); + activeEditorChanged.fire(); + return { ...activeEditor, whenUpdated: () => updated.p }; + }, + returnToMainInput: () => { + updated = new DeferredPromise(); + activeEditor = mainEditor; + activeEditorChanged.fire(); + return updated.p; + }, + setInput: (parts: readonly IParsedChatRequestPart[]) => activeEditor.setInput(parts), + }; + } + + test('offers keyboard skill navigation in the Command Palette only for enabled chat inputs', () => { + const configuration = new TestConfigurationService(); + store.add(configuration.onDidChangeConfigurationEmitter); + const context = store.add(new ContextKeyService(configuration)); + const enabled = ChatContextKeys.enabled.bindTo(context); + const inInput = ChatContextKeys.inChatInput.bindTo(context); + const item = MenuRegistry.getMenuItems(MenuId.CommandPalette).filter(isIMenuItem) + .find(item => item.command.id === 'workbench.action.chat.openSkillAtCursor'); + assert.ok(item); + + enabled.set(true); + inInput.set(true); + const inChatInput = context.contextMatchesRules(item.when); + inInput.set(false); + const outsideInput = context.contextMatchesRules(item.when); + inInput.set(true); + enabled.set(false); + + assert.deepStrictEqual({ + inChatInput, + outsideInput, + aiDisabled: context.contextMatchesRules(item.when), + }, { inChatInput: true, outsideInput: false, aiDisabled: false }); + }); + + test('opens a restored sent-message skill from the active edit input and releases old editor listeners', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const text = '/review changes'; + const uri = URI.file('/workspace/review/SKILL.md'); + const variable = messageAttachmentsToVariableData([{ + type: MessageAttachmentKind.Resource, uri: uri.toString(), label: '/review', displayKind: 'skill', + range: { start: { line: 0, character: 0 }, end: { line: 0, character: 7 } }, + }], 'local', text)!.variables[0]; + const parser = new ChatRequestParser( + upcastPartial({ getDefaultAgent: () => undefined }), + upcastPartial({}), + upcastPartial({ getCommands: () => [] }), + upcastPartial({ hasPromptSlashCommand: () => false, isValidSlashCommandName: () => false }), + ); + const parsed = parser.parseChatRequestWithReferences([{ + id: variable.id, data: variable.value, range: new Range(1, 1, 1, 8), + }], ToolAndToolSetEnablementMap.fromEntries([]), text); + const fixture = createDecorations(parsed.parts); + await fixture.whenUpdated(); + fixture.mouseDown(2); + const editing = fixture.editSentMessage(); + await editing.whenUpdated(); + editing.setPosition(2); + await fixture.openSkillAtCursor(); + editing.mouseUp(2); + fixture.click(2); + editing.drag(2, 3); + editing.rightClick(2); + editing.click(10); + editing.click(2); + await fixture.returnToMainInput(); + editing.click(2); + fixture.click(2); + fixture.setPosition(2); + await fixture.openSkillAtCursor(); + const secondEdit = fixture.editSentMessage(); + await secondEdit.whenUpdated(); + editing.click(2); + secondEdit.click(2); + assert.deepStrictEqual(fixture.openedResources, Array(5).fill(uri.toString())); + })); + + test('keyboard navigation uses only the active input and restores the composer after editing', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const mainUri = URI.file('/workspace/main/SKILL.md'); + const editUri = URI.file('/workspace/edit/SKILL.md'); + const skill = (resource: URI) => referencePart(1, toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', resource, undefined)); + const fixture = createDecorations([skill(mainUri), textPart(8, ' more')]); + fixture.setPosition(2); + await fixture.openSkillAtCursor(); + + const editing = fixture.editSentMessage([skill(editUri), textPart(8, ' changes')]); + editing.setPosition(10); + await fixture.openSkillAtCursor(); + editing.setPosition(2); + await fixture.openSkillAtCursor(); + fixture.setPosition(10); + await fixture.openSkillAtCursor(); + + const restored = fixture.returnToMainInput(); + await fixture.openSkillAtCursor(); + editing.setPosition(10); + fixture.setPosition(2); + await fixture.openSkillAtCursor(); + await restored; + + assert.deepStrictEqual(fixture.openedResources, [mainUri, editUri, editUri, mainUri].map(resource => resource.toString())); + })); + + test('keyboard navigation requires a caret inside the current bound skill, without waiting for decorations', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const oldUri = URI.file('/workspace/old/SKILL.md'); + const currentUri = URI.file('/workspace/current/SKILL.md'); + const parts = (resource: URI) => [ + textPart(1, 'changes '), + referencePart(9, toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', resource, undefined)), + textPart(16, ' more'), + ]; + const fixture = createDecorations(parts(oldUri)); + await fixture.whenUpdated(); + void fixture.setInput(parts(currentUri)); + for (const column of [1, 8, 9, 15, 16, 20]) { + fixture.setPosition(column); + await fixture.openSkillAtCursor(); + } + for (const [start, end] of [[9, 16], [10, 19], [19, 10]]) { + fixture.setSelection(start, end); + await fixture.openSkillAtCursor(); + } + const removed = fixture.setInput([textPart(1, 'changes /review more')]); + fixture.setPosition(10); + await fixture.openSkillAtCursor(); + await removed; + + assert.deepStrictEqual(fixture.openedResources, [currentUri.toString(), currentUri.toString()]); + })); + + for (const kind of agentHostConnectionKinds) { + test(`opens each same-name skill's bound resource by mouse and keyboard without a name lookup (${kind.name})`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const resources = [URI.file('/workspace/one/SKILL.md'), URI.file('/workspace/two/SKILL.md')].map(kind.toClient); + const entries = resources.map(resource => toAgentHostCompletionVariableEntry( + AgentHostCompletionReferenceKind.Skill, '/review', resource, { uri: 'file:///host/other/SKILL.md' }, + )); + const fixture = createDecorations([ + referencePart(1, entries[0]), textPart(8, ' '), referencePart(9, entries[1]), textPart(16, ' '), + ], upcastPartial({ name: 'review', uri: URI.file('/wrong/review.prompt.md') })); + fixture.setPosition(2); + await fixture.openSkillAtCursor(); + fixture.setPosition(10); + await fixture.openSkillAtCursor(); + await fixture.whenUpdated(); + fixture.click(2); + fixture.click(10); + + assert.deepStrictEqual({ + opens: fixture.openedResources, + lookups: fixture.resolvePromptSlashCommand.callCount, + ranges: fixture.decorations.get('chat-session-clickable-text')?.map(decoration => decoration.range), + }, { + opens: [...resources, ...resources].map(resource => resource.toString()), + lookups: 0, + ranges: [new Range(1, 1, 1, 8), new Range(1, 9, 1, 16)], + }); + })); + } + + test('ignores missing resources, commands, and ordinary variables', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const uri = URI.file('/workspace/SKILL.md'); + const entries: IChatRequestVariableEntry[] = [ + toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', undefined, { uri: uri.toString() }), + toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Command, '/review', 'review', { uri: uri.toString() }), + { kind: 'generic', name: '/review', id: uri.toString(), value: uri }, + ]; + const fixture = createDecorations(entries.flatMap((entry, index) => [referencePart(1 + index * 8, entry), textPart(8 + index * 8, ' ')])); + await fixture.whenUpdated(); + for (let column = 2; column < 24; column += 8) { + fixture.click(column); + fixture.setPosition(column); + await fixture.openSkillAtCursor(); + } + assert.deepStrictEqual({ + opens: fixture.openedResources, + lookups: fixture.resolvePromptSlashCommand.callCount, + decorations: fixture.decorations.get('chat-session-clickable-text'), + }, { opens: [], lookups: 0, decorations: [] }); + })); + + test('preserves ordinary slash prompt navigation and argument hints alongside bound skills', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const promptUri = URI.file('/workspace/review.prompt.md'); + const skillUri = URI.file('/workspace/review/SKILL.md'); + const prompt = new ChatRequestSlashPromptPart(new OffsetRange(0, 7), new Range(1, 1, 1, 8), 'review'); + const fixture = createDecorations([prompt, textPart(8, ' ')], upcastPartial({ + name: 'review', uri: promptUri, argumentHint: 'Files to review', + })); + await fixture.whenUpdated(); + const argumentHint = fixture.decorations.get('chat-session-detail')?.[0].renderOptions?.after?.contentText; + fixture.setPosition(2); + await fixture.openSkillAtCursor(); + fixture.click(2); + await fixture.setInput([ + prompt, textPart(8, ' '), + referencePart(9, toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', skillUri, undefined)), + ]); + fixture.click(2); + fixture.click(10); + assert.deepStrictEqual({ + opens: fixture.openedResources, + lookups: fixture.resolvePromptSlashCommand.callCount, + argumentHint, + }, { + opens: [promptUri.toString(), promptUri.toString(), skillUri.toString()], + lookups: 2, + argumentHint: 'Files to review', + }); + })); + + test('does not navigate on drags, right clicks, outside clicks, or removed references', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const entry = toAgentHostCompletionVariableEntry(AgentHostCompletionReferenceKind.Skill, '/review', URI.file('/workspace/SKILL.md'), undefined); + const fixture = createDecorations([referencePart(1, entry), textPart(8, ' more')]); + await fixture.whenUpdated(); + fixture.drag(2, 3); + fixture.drag(2, 10); + fixture.rightClick(2); + fixture.click(8); + fixture.click(10); + await fixture.setInput([textPart(1, '/review more')]); + fixture.click(2); + assert.deepStrictEqual(fixture.openedResources, []); + })); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatPasteProviders.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatPasteProviders.test.ts index b489ff6160f2..1e46ca9c7249 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatPasteProviders.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/editor/chatPasteProviders.test.ts @@ -5,7 +5,7 @@ import assert from 'assert'; import { CancellationToken } from '../../../../../../../../base/common/cancellation.js'; -import { createStringDataTransferItem, VSDataTransfer } from '../../../../../../../../base/common/dataTransfer.js'; +import { createStringDataTransferItem, IDataTransferFile, VSDataTransfer } from '../../../../../../../../base/common/dataTransfer.js'; import { Mimes } from '../../../../../../../../base/common/mime.js'; import { Schemas } from '../../../../../../../../base/common/network.js'; import { URI } from '../../../../../../../../base/common/uri.js'; @@ -20,7 +20,7 @@ import { IConfigurationService } from '../../../../../../../../platform/configur import { ILogService } from '../../../../../../../../platform/log/common/log.js'; import { IChatPasteTarget, IChatPasteTargetService } from '../../../../../browser/chat.js'; import { IChatSessionsService } from '../../../../../common/chatSessionsService.js'; -import { CHAT_ATTACHMENT_MIME_TYPE, createPastedTextArtifact, getGitHubIssueOrPullRequestAttachments, pastedTextArtifactDefaultMinLength, PasteTextProvider } from '../../../../../browser/widget/input/editor/chatPasteProviders.js'; +import { CHAT_ATTACHMENT_MIME_TYPE, createPastedTextArtifact, getGitHubIssueOrPullRequestAttachments, getPastedImageName, pastedTextArtifactDefaultMinLength, PasteTextProvider } from '../../../../../browser/widget/input/editor/chatPasteProviders.js'; import { ChatPasteAttachmentMetadata, IChatRequestVariableEntry } from '../../../../../common/attachments/chatVariableEntries.js'; import { isSupportedChatFileScheme } from '../../../../../common/constants.js'; import { ChatResponseResource } from '../../../../../common/model/chatModel.js'; @@ -41,6 +41,23 @@ suite('Chat Paste Providers', () => { false); }); + test('names pasted images after their file and keeps the names unique', () => { + // Mirrors toVSDataTransfer, which parses the native path of a pasted file into the uri + const fromDisk: IDataTransferFile = { id: '1', name: 'diagram #1.png', uri: URI.parse('C:\\Screenshots\\diagram #1.png'), data: async () => new Uint8Array() }; + const rawBitmap: IDataTransferFile = { id: '2', name: 'image.png', uri: undefined, data: async () => new Uint8Array() }; + assert.deepStrictEqual({ + fromFile: getPastedImageName(fromDisk, []), + fromFileTaken: getPastedImageName(fromDisk, ['diagram #1.png', 'diagram #1 2.png']), + rawBitmap: getPastedImageName(rawBitmap, []), + rawBitmapTaken: getPastedImageName(rawBitmap, ['Pasted Image']), + }, { + fromFile: 'diagram #1.png', + fromFileTaken: 'diagram #1 3.png', + rawBitmap: 'Pasted Image', + rawBitmapTaken: 'Pasted Image 2', + }); + }); + test('creates sequential artifacts only for long pasted text', () => { const longText = `${'x'.repeat(10000)}\n`.repeat(10); const first = createPastedTextArtifact(longText, []); 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 42fe5103e25b..cc90456c7e56 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 @@ -516,6 +516,19 @@ suite('ModelPickerActionItem', () => { }); }); + test('a cached Auto that has not loaded yet is named Copilot Fusion in both its label and its hover', () => { + const auto = createModel('auto'); + const { domNode, getHoverContents } = renderPicker({ ...auto, metadata: { ...auto.metadata, name: 'Auto' } }, { models: [] }); + const hover = getHoverContents(); + assert.deepStrictEqual({ + label: domNode.querySelector('.chat-input-picker-label')?.textContent, + hover: isManagedHoverTooltipMarkdownString(hover) ? hover.markdownNotSupportedFallback : hover, + }, { + label: 'Copilot Fusion', + hover: 'Models • Copilot Fusion\n\nCopilot Fusion selects a single model or orchestrates multiple models to complete your task.', + }); + }); + test('a directly selected on-device model reads " · On-device", as in the Copilot CLI and app', () => { const model = createModel('MAI Code 1.1 Flash'); const { domNode } = renderPicker({ ...model, metadata: { ...model.metadata, id: 'vscode-on-device/MAI-Code-1.1-Flash', targetChatSessionType: SessionType.AgentHostCopilot } }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerStartup.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerStartup.test.ts new file mode 100644 index 000000000000..966545ae0ce6 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerStartup.test.ts @@ -0,0 +1,204 @@ +/*--------------------------------------------------------------------------------------------- + * 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 * as dom from '../../../../../../../../base/browser/dom.js'; +import { Action } from '../../../../../../../../base/common/actions.js'; +import { Emitter, Event } from '../../../../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../../../../base/common/lifecycle.js'; +import { autorun, constObservable, observableValue } from '../../../../../../../../base/common/observable.js'; +import { upcastPartial } from '../../../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../../base/test/common/utils.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 { IDefaultAccountService } from '../../../../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { ExtensionIdentifier } from '../../../../../../../../platform/extensions/common/extensions.js'; +import { IInstantiationService } from '../../../../../../../../platform/instantiation/common/instantiation.js'; +import { TestInstantiationService } from '../../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IOpenerService } from '../../../../../../../../platform/opener/common/opener.js'; +import { IManagedSettingsService } from '../../../../../../../../platform/policy/common/copilotManagedSettings.js'; +import { IProductService } from '../../../../../../../../platform/product/common/productService.js'; +import { InMemoryStorageService, IStorageService } from '../../../../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../../../../platform/telemetry/common/telemetry.js'; +import { IUpdateService } from '../../../../../../../../platform/update/common/update.js'; +import { IUriIdentityService } from '../../../../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from '../../../../../../../../platform/workspace/common/workspaceTrust.js'; +import { ChatEntitlement, IChatEntitlementService } from '../../../../../../../services/chat/common/chatEntitlementService.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../../services/environment/common/environmentService.js'; +import { IChatPhoneInputPresenter, MobileChatInputCombinedPickerActionItem } from '../../../../../browser/widget/input/chatPhoneInputPresenter.js'; +import { IModePickerDelegate } from '../../../../../browser/widget/input/modePickerActionItem.js'; +import { IModelPickerDelegate } from '../../../../../browser/widget/input/modelPicker/modelPickerActionItem.js'; +import { ModelPickerWidget } from '../../../../../browser/widget/input/modelPicker/modelPickerWidget.js'; +import { IChatMode } from '../../../../../common/chatModes.js'; +import { ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService } from '../../../../../common/languageModels.js'; + +function autoModel(fusion = false): ILanguageModelChatMetadataAndIdentifier { + return { + identifier: 'agent-host-copilotcli:auto', + metadata: { + extension: new ExtensionIdentifier('test.extension'), + id: 'auto', + name: fusion ? 'Copilot Fusion' : 'Auto', + vendor: 'agent-host-copilotcli', + modelGroup: { id: 'copilotcli' }, + version: '1', + family: 'auto', + maxInputTokens: 0, + maxOutputTokens: 0, + isDefaultForLocation: {}, + autoModelFusion: fusion, + configurationSchema: { + properties: { + tier: { + type: 'string', + group: 'navigation', + title: fusion ? 'Effort Level' : 'Optimize for', + enum: fusion ? ['balance', 'hydrafusion'] : ['efficiency', 'balance'], + enumItemLabels: fusion ? ['Standard', 'High'] : ['Efficiency', 'Balance'], + default: fusion ? 'balance' : 'efficiency', + }, + }, + }, + }, + }; +} + +suite('Model picker startup rendering', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function createPickers(initial?: ILanguageModelChatMetadataAndIdentifier, live = false) { + const instantiationService = disposables.add(new TestInstantiationService()); + const changes = disposables.add(new Emitter()); + const registered = new Map(); + if (initial && live) { + registered.set(initial.identifier, initial.metadata); + } + let models = initial ? [initial] : []; + const selected = observableValue('selected', initial); + instantiationService.stub(ICommandService, {}); + instantiationService.stub(IOpenerService, {}); + instantiationService.stub(ITelemetryService, {}); + instantiationService.stub(ILanguageModelsService, { + onDidChangeLanguageModels: changes.event, + getLanguageModelIds: () => [...registered.keys()], + lookupLanguageModel: identifier => registered.get(identifier), + getVendors: () => [], + getModelsControlManifest: () => ({ free: {}, paid: {} }), + getModelConfiguration: () => undefined, + }); + instantiationService.stub(IProductService, { version: '1.147.0' }); + instantiationService.stub(IChatEntitlementService, { + entitlement: ChatEntitlement.Pro, + anonymous: false, + hasByokModels: false, + onDidChangeUsageBasedBilling: Event.None, + onDidChangeEntitlement: Event.None, + onDidChangeSentiment: Event.None, + onDidChangeAnonymous: Event.None, + }); + instantiationService.stub(IUpdateService, {}); + instantiationService.stub(IUriIdentityService, {}); + instantiationService.stub(IDefaultAccountService, {}); + instantiationService.stub(IWorkspaceTrustManagementService, { + workspaceTrustInitialized: Promise.resolve(), + isWorkspaceTrusted: () => true, + onDidChangeTrust: Event.None, + }); + instantiationService.stub(IWorkspaceTrustRequestService, {}); + instantiationService.stub(IStorageService, disposables.add(new InMemoryStorageService())); + instantiationService.stub(IInstantiationService, instantiationService); + instantiationService.stub(IConfigurationService, new TestConfigurationService()); + instantiationService.stub(IWorkbenchEnvironmentService, {}); + instantiationService.stub(IManagedSettingsService, { onDidChangeManagedSettings: Event.None }); + instantiationService.stub(IChatPhoneInputPresenter, {}); + + const delegate: IModelPickerDelegate = { + currentModel: selected, + getModels: () => models, + setModel: value => selected.set(value, undefined), + getPresentationOptions: () => ({ showAutoModel: true, showManageModelsAction: false, showUnavailableFeatured: false, showModelIcon: false }), + }; + const container = dom.append(document.body, dom.$('div')); + disposables.add(toDisposable(() => container.remove())); + const desktop = disposables.add(instantiationService.createInstance(ModelPickerWidget, delegate)); + disposables.add(autorun(reader => desktop.setSelectedModel(selected.read(reader)))); + desktop.render(dom.append(container, dom.$('div'))); + const mode = upcastPartial({ label: constObservable('Agent'), icon: constObservable(undefined) }); + const modeDelegate = upcastPartial({ currentMode: constObservable(mode) }); + const action = disposables.add(new Action('test.models', 'Models')); + const phone = disposables.add(instantiationService.createInstance(MobileChatInputCombinedPickerActionItem, action, modeDelegate, delegate)); + const phoneContainer = dom.append(container, dom.$('div')); + phone.render(phoneContainer); + + return { + publish(model: ILanguageModelChatMetadataAndIdentifier) { + models = [model]; + registered.set(model.identifier, model.metadata); + selected.set(model, undefined); + changes.fire(model.metadata.vendor); + }, + read() { + const configuration = desktop.domNode?.querySelector('.model-picker-config'); + const phoneTrigger = phoneContainer.querySelector('.chat-phone-input-chip'); + return { + desktop: desktop.nameButton?.textContent, + desktopAria: desktop.nameButton?.ariaLabel, + configuration: configuration?.style.display === 'none' ? undefined : configuration?.textContent, + phone: phoneTrigger?.querySelector('.chat-input-picker-label')?.textContent, + phoneAria: phoneTrigger?.ariaLabel, + }; + }, + }; + } + + const pending = { + desktop: 'Copilot Fusion', + desktopAria: 'Models, Copilot Fusion', + configuration: undefined, + phone: 'Copilot Fusion', + phoneAria: 'Pick Mode and Model, Agent, Copilot Fusion', + }; + + test('empty startup names Copilot Fusion without an effort readout', () => { + assert.deepStrictEqual(createPickers().read(), pending); + }); + + test('cached legacy Auto hides Efficiency until live Fusion metadata arrives', () => { + const pickers = createPickers(autoModel()); + const beforeDiscovery = pickers.read(); + pickers.publish(autoModel(true)); + assert.deepStrictEqual({ beforeDiscovery, afterDiscovery: pickers.read() }, { + beforeDiscovery: pending, + afterDiscovery: { ...pending, configuration: 'Standard' }, + }); + }); + + test('live legacy Auto keeps its provider name and configuration', () => { + assert.deepStrictEqual(createPickers(autoModel(), true).read(), { + desktop: 'Auto', + desktopAria: 'Models, Auto', + configuration: 'Efficiency', + phone: 'Auto', + phoneAria: 'Pick Mode and Model, Agent, Auto', + }); + }); + + test('a cached user-provided model named auto is not presented as Fusion', () => { + const auto = autoModel(); + const custom = { + ...auto, + identifier: 'custom/auto', + metadata: { ...auto.metadata, vendor: 'custom', modelGroup: { id: 'custom' }, name: 'My Auto' }, + }; + assert.deepStrictEqual(createPickers(custom).read(), { + desktop: 'My Auto', + desktopAria: 'Models, My Auto', + configuration: 'Efficiency', + phone: 'My Auto', + phoneAria: 'Pick Mode and Model, Agent, My Auto', + }); + }); +}); 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 6a69d738a2e2..f5ed32325b9d 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 @@ -820,6 +820,8 @@ suite('TabbedModelPicker', () => { : undefined, controlModels: { First: { label: 'First', exists: true, featured: true }, Second: { label: 'Second', exists: true, featured: true } }, }); + anchor.style.left = 'calc(100% - 500px)'; + picker.show(anchor, context); const listHeight = () => element(popup, '.monaco-list').offsetHeight; popup.style.setProperty('--vscode-strokeThickness', '1px'); popup.style.setProperty('--vscode-inputOption-activeBackground', 'rgb(10, 20, 30)'); @@ -860,6 +862,8 @@ suite('TabbedModelPicker', () => { picker.show(anchor, context); const reopened = bounds(); assert.deepStrictEqual({ + initiallyBesideAnchor: first.bottom <= anchor.getBoundingClientRect().top || first.top >= anchor.getBoundingClientRect().bottom, + initiallyAligned: first.left === anchor.getBoundingClientRect().left, sameListViewport: firstRows === initialRows, withinViewportCap: firstRows <= Math.floor(dom.getWindow(popup).innerHeight * 0.6), stableHeight: reopened.height === first.height, @@ -867,10 +871,47 @@ suite('TabbedModelPicker', () => { aligned: reopened.left === anchor.getBoundingClientRect().left, besideAnchor: reopened.bottom <= anchor.getBoundingClientRect().top || reopened.top >= anchor.getBoundingClientRect().bottom, fitsWindow: reopened.top >= 0 && reopened.bottom <= dom.getWindow(popup).innerHeight, - }, { sameListViewport: true, withinViewportCap: true, stableHeight: true, stableRows: true, aligned: true, besideAnchor: true, fitsWindow: true }); + }, { initiallyBesideAnchor: true, initiallyAligned: true, sameListViewport: true, withinViewportCap: true, stableHeight: true, stableRows: true, aligned: true, besideAnchor: true, fitsWindow: true }); }); } + test('comparison stays vertically anchored when its list fills the fractional space above the trigger', () => { + const state = observableValue('comparison', undefined); + const comparison: IModelPickerComparison = { + available: constObservable(true), summary: constObservable(undefined), state, label: 'Compare Models', + start: () => state.set({ + title: 'Attempts', description: 'Select two or more models to compare their responses side by side.', + summary: '', selectedModelIds: [], multiple: true, maxSelections: 10, + canGoBack: false, canGoNext: false, canFinish: true, + }, undefined), + cancel: () => { }, reset: () => { }, select: () => { }, setCount: () => { }, back: () => { }, next: () => { }, finish: () => { }, + getVariants: () => [], addVariant: () => { }, removeVariant: () => { }, + }; + const manyModels = Array.from({ length: 25 }, (_, index) => model(`Model-${index}`)); + const { picker, popup, anchor, context, dismiss } = createPicker({ + comparison, realContextView: true, anchorTop: '400.5px', models: manyModels, + pinnedModelIds: manyModels.map(model => model.identifier), + controlModels: Object.fromEntries(manyModels.map(model => [model.metadata.id, { label: model.metadata.name, exists: true, featured: true }])), + }); + dismiss(); + for (const size of [2, 4, 6, 8, 10, 12, 16, 20, 24, 28, 32, 36]) { + anchor.parentElement!.style.setProperty(`--vscode-spacing-size${size * 10}`, `${size}px`); + } + anchor.parentElement!.style.setProperty('--vscode-strokeThickness', '1px'); + anchor.parentElement!.style.setProperty('--vscode-fontSize-label1', '13px'); + anchor.style.left = 'calc(100% - 500px)'; + picker.show(anchor, context); + element(popup, '[aria-label="Compare Models"]').click(); + const bounds = element(popup, '.chat-model-picker-widget').getBoundingClientRect(); + const trigger = anchor.getBoundingClientRect(); + assert.ok(bounds.height > 300, `Expected a constrained list, got ${bounds.height}`); + assert.deepStrictEqual({ + aligned: bounds.left === trigger.left, + above: bounds.bottom <= trigger.top, + fits: bounds.top >= 0, + }, { aligned: true, above: true, fits: true }); + }); + test('comparison shows every harness tab and selects attempts, judge, and synthesizer across them', () => { const copilot = models[0]; const claude = harnessModel('claude', 'Claude Choice'); @@ -2150,6 +2191,41 @@ suite('TabbedModelPicker', () => { }); }); + for (const showUnavailable of [false, true]) { + test(`version requirements stay scoped to built-in models with unavailable suggestions ${showUnavailable ? 'shown' : 'hidden'}`, () => { + const gated = model('Gated'); + const compatible = model('Compatible'); + const byok = { ...gated, identifier: 'ollama/Gated', metadata: { ...gated.metadata, name: 'BYOK Gated', vendor: 'ollama' } }; + const result = createPicker({ + models: [gated, compatible, byok], + selectedModelId: compatible.identifier, + showUnavailable, + controlModels: { + Gated: { label: 'Gated', exists: true, featured: true, minVSCodeVersion: '99.0.0' }, + Compatible: { label: 'Compatible', exists: true, featured: true }, + }, + }); + const gatedRow = Array.from(result.popup.querySelectorAll('.monaco-list-row')) + .find(row => row.querySelector('.title')?.textContent === 'Gated')!; + const update = gatedRow.textContent?.includes('Update VS Code'); + gatedRow.click(); + const gatedSelections = [...result.selections]; + reopen(result); + selectRow(result.popup, 'Compatible'); + reopen(result); + element(result.popup, '.chat-model-picker-tabbar [aria-label="Ollama"]').click(); + const byokRows = listRows(result.popup); + element(result.popup, '.monaco-list-row:not(.separator)').click(); + + assert.deepStrictEqual({ update, gatedSelections, byokRows, selections: result.selections }, { + update: true, + gatedSelections: [], + byokRows: ['BYOK Gated'], + selections: [compatible.identifier, byok.identifier], + }); + }); + } + for (const entitlement of [ChatEntitlement.Free, ChatEntitlement.EDU]) { test(`${ChatEntitlement[entitlement]} plans show HydraFusion as an unavailable upgrade instead of a tier`, () => { const auto = createAutoModel(); @@ -2519,6 +2595,21 @@ suite('TabbedModelPicker', () => { }); }); + test('an on-device row too slow for Auto names Copilot Fusion when Auto is presented that way', () => { + const status = onDeviceStatus(); + const localModels = onDevicePresentation({ ...status, active: { ...status.active!, autoEligible: false } }); + const label = (auto: ILanguageModelChatMetadataAndIdentifier) => { + const { popup, dismiss } = createPicker({ models: [auto, ...models, exampleFlash, qwen], selectedModelId: exampleFlash.identifier, localModels }); + const row = Array.from(popup.querySelectorAll('.chat-model-picker-tabbed .monaco-list-row.action')).find(candidate => candidate.querySelector('.title')?.textContent === exampleFlash.metadata.name); + dismiss(); + return row?.getAttribute('aria-label'); + }; + assert.deepStrictEqual({ auto: label(createAutoModel()), fusion: label(createFusionModel()) }, { + auto: 'Example Flash 1.0, Active, Effort Level: Medium, Context: 128K, Too slow for Auto', + fusion: 'Example Flash 1.0, Active, Effort Level: Medium, Context: 128K, Too slow for Copilot Fusion', + }); + }); + test('Right Arrow on an on-device row opens its detail page, and Back returns to the row', async () => { const { popup } = createPicker({ models: [...copilotModels, exampleFlash, qwen], selectedModelId: exampleFlash.identifier, localModels: onDevicePresentation() }); const list = element(popup, '.chat-model-picker-tabbed .monaco-list'); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/mockChatWidget.ts b/src/vs/workbench/contrib/chat/test/browser/widget/mockChatWidget.ts index f75eb2ee996a..3a0008899222 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/mockChatWidget.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/mockChatWidget.ts @@ -40,6 +40,10 @@ export class MockChatWidgetService implements IChatWidgetService { return Promise.resolve(undefined); } + revealChatView(preserveFocus?: boolean): Promise { + return Promise.resolve(undefined); + } + reveal(widget: IChatWidget, preserveFocus?: boolean): Promise { return Promise.resolve(true); } diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts new file mode 100644 index 000000000000..25db610ef256 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../../../base/common/lifecycle.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 { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IProgressService } from '../../../../../../../platform/progress/common/progress.js'; +import { IViewDescriptorService, ViewContainerLocation } from '../../../../../../common/views.js'; +import { IWorkbenchLayoutService, Parts } from '../../../../../../services/layout/browser/layoutService.js'; +import { IViewsService } from '../../../../../../services/views/common/viewsService.js'; +import { ChatViewId } from '../../../../browser/chat.js'; +import { ChatWidget } from '../../../../browser/widget/chatWidget.js'; +import { IChatViewHost } from '../../../../browser/chatViewHost.js'; +import { ChatViewHostService } from '../../../../browser/widgetHosts/viewPane/chatViewHostService.js'; +import { ChatViewPane } from '../../../../browser/widgetHosts/viewPane/chatViewPane.js'; + +suite('ChatViewHostService', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** The service over a Chat view that records what is asked of it, of the views service and of the layout. */ + function createService(options: { readonly chatVisible?: boolean; readonly widgetCreatedLater?: boolean } = {}) { + const calls: string[] = []; + const widget = upcastPartial({}); + const created = new DeferredPromise(); + let accesses = 0; + const view = upcastPartial({ + widget: options.widgetCreatedLater ? undefined : widget, + get whenWidget() { accesses++; return created.p; }, + loadSession: async (resource: URI, reason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}`); return undefined; }, + startNewLocalSession: async () => { calls.push('startNewLocalSession'); return undefined; }, + focus: () => { calls.push('focus'); }, + focusInput: () => { calls.push('focusInput'); }, + beginSessionsListSuppression: () => { calls.push('suppress'); return toDisposable(() => calls.push('unsuppress')); }, + }); + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async (id: string, focus?: boolean) => { calls.push(`openView ${id} focus=${focus}`); return view; }) as IViewsService['openView'], + isViewVisible: () => !!options.chatVisible, + })); + instantiationService.stub(IViewDescriptorService, upcastPartial({ getViewLocationById: () => ViewContainerLocation.AuxiliaryBar })); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial({ setPartHidden: (hidden, part) => { calls.push(`setPartHidden ${hidden} ${part}`); } })); + instantiationService.stub(IProgressService, upcastPartial({ + withProgress: (async (_options: unknown, task: () => Promise) => { calls.push('progress'); await task(); calls.push('progress done'); }) as IProgressService['withProgress'], + })); + return { service: instantiationService.createInstance(ChatViewHostService), widget, view, created, calls, accesses: () => accesses }; + } + + test('without a host that replaces it, the Chat view shows the chats as before', async () => { + const { service, widget, calls } = createService(); + const resource = URI.parse('test:/session'); + const results: Record = {}; + + results.reveal = await service.reveal(false) === widget; + results.revealPreservingFocus = await service.reveal(true) === widget; + results.openSession = await service.openSession(resource, { sessionTypeSelectionReason: 'explicitOverride' }) === widget; + results.toggle = await service.toggle(); + const start = await service.startSession(resource, { local: false, importingConversation: true, beforeOpen: () => calls.push('beforeOpen') }); + await start.moved(URI.parse('test:/moved')); + results.shown = await start.complete(URI.parse('test:/moved'), true); + results.composer = await start.createComposer(); + await timeout(0); + const local = await service.startSession(resource, { local: true, importingConversation: false }); + local.dispose(); + + assert.deepStrictEqual({ results, calls }, { + results: { reveal: true, revealPreservingFocus: true, openSession: true, toggle: true, shown: true, composer: undefined }, + calls: [ + `openView ${ChatViewId} focus=true`, + `openView ${ChatViewId} focus=false`, + `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'focusInput', + `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, + `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', + `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', + 'unsuppress', 'progress done', + `openView ${ChatViewId} focus=undefined`, 'startNewLocalSession', 'focus', + ], + }); + }); + + test('toggle hides a visible Chat view', async () => { + const { service, calls } = createService({ chatVisible: true }); + assert.deepStrictEqual({ shows: await service.toggle(), calls }, { shows: false, calls: [`setPartHidden true ${Parts.AUXILIARYBAR_PART}`] }); + }); + + test('the host registered last shows the chats, each registration on its own, also of the same host, until it is disposed, in any order', async () => { + const { service, calls } = createService(); + const reveals: string[] = []; + const host = (name: string) => upcastPartial({ reveal: async () => { reveals.push(name); return undefined; } }); + const active = async () => { + reveals.length = 0; + calls.length = 0; + await service.reveal(); + return reveals[0] ?? (calls.length ? 'chat view' : 'none'); + }; + const a = host('A'); + const b = host('B'); + const steps: string[] = []; + + const firstA = service.registerHost(a); + const registeredB = service.registerHost(b); + const lastA = service.registerHost(a); + steps.push(await active()); + lastA.dispose(); + steps.push(await active()); + const c = service.registerHost(host('C')); + // An earlier registration disposed out of order leaves the one in use + registeredB.dispose(); + steps.push(await active()); + c.dispose(); + steps.push(await active()); + firstA.dispose(); + steps.push(await active()); + + assert.deepStrictEqual(steps, ['A', 'B', 'C', 'A', 'chat view']); + }); + + test('reveal waits for the Chat view\'s widget, which its body creates as it first renders, only when asked to', async () => { + const { service, view, created, accesses } = createService({ widgetCreatedLater: true }); + const unchanged = await service.reveal(false); + let settled = false; + const pending = service.reveal(false, { waitForWidget: true }).then(widget => { settled = true; return widget; }); + await timeout(0); + // It waits for the widget it asked the view for, which the view has not created yet + const waiting = { accesses: accesses(), settled }; + const widget = upcastPartial({}); + Object.assign(view, { widget }); + created.complete(widget); + assert.deepStrictEqual({ unchanged, waiting, revealed: await pending === widget }, { unchanged: undefined, waiting: { accesses: 1, settled: false }, revealed: true }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 421c6c526ae2..17c349b7be14 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -5,7 +5,8 @@ import assert from 'assert'; import { CancellationToken, CancellationTokenSource } from '../../../../../../../base/common/cancellation.js'; -import { DeferredPromise, timeout } from '../../../../../../../base/common/async.js'; +import { CancellationError } from '../../../../../../../base/common/errors.js'; +import { DeferredPromise, RunOnceScheduler, timeout } from '../../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../../base/common/event.js'; import { constObservable } from '../../../../../../../base/common/observable.js'; import { DisposableStore, MutableDisposable, toDisposable } from '../../../../../../../base/common/lifecycle.js'; @@ -19,6 +20,8 @@ import { NullLogService } from '../../../../../../../platform/log/common/log.js' import { AccountPolicyGateState } from '../../../../../../services/policies/common/accountPolicyService.js'; import { TestContextService, TestStorageService } from '../../../../../../test/common/workbenchTestServices.js'; import { ChatViewPane } from '../../../../browser/widgetHosts/viewPane/chatViewPane.js'; +import { ChatWidget } from '../../../../browser/widget/chatWidget.js'; +import { mainWindow } from '../../../../../../../base/browser/window.js'; import { ChatOpenDiagnosticsService } from '../../../../common/chatOpenDiagnosticsService.js'; import { MockChatSessionsService } from '../../../common/mockChatSessionsService.js'; import { IChatModelReference } from '../../../../common/chatService/chatService.js'; @@ -31,6 +34,8 @@ import { AgentSessionsFilter } from '../../../../browser/agentSessions/agentSess import { MenuWorkbenchToolBar } from '../../../../../../../platform/actions/browser/toolbar.js'; import { ChatConfiguration } from '../../../../common/constants.js'; import { AgentSessionsViewerOrientation } from '../../../../browser/agentSessions/agentSessions.js'; +import { Position } from '../../../../../../services/layout/browser/layoutService.js'; +import { ViewContainerLocation } from '../../../../../../common/views.js'; suite('ChatViewPane sessions refresh', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -68,6 +73,50 @@ suite('ChatViewPane sessions refresh', () => { assert.deepStrictEqual(visibility, [false, true, false, true, false, false]); }); + test('sessions layout telemetry reports the settled layout once shown and restored, then only changes', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const events: unknown[] = []; + const host = { + sessionsContainer: document.createElement('div'), + lastDimensions: { width: 1000, height: 600 }, + bodyVisible: false, + isBodyVisible: () => host.bodyVisible, + restoringSession: Promise.resolve() as Promise | undefined, + _loadingSessionCount: 0, + _sessionsListSuppressionCount: 0, + getViewPositionAndLocation: () => ({ position: Position.RIGHT, location: ViewContainerLocation.AuxiliaryBar }), + sessionsViewerOrientationConfiguration: 'sideBySide', + sessionsViewerOrientation: AgentSessionsViewerOrientation.SideBySide, + sessionsViewerVisible: true, + configurationService: new TestConfigurationService({ [ChatConfiguration.ChatViewSessionsEnabled]: true }), + layoutService: { isAuxiliaryBarMaximized: () => false }, + telemetryService: { publicLog2: (eventName: string, data: object) => events.push({ eventName, ...data }) }, + lastReportedSessionsLayout: undefined, + }; + const report = Reflect.get(ChatViewPane.prototype, 'reportSessionsLayout') as (this: typeof host) => void; + const scheduler = store.add(new RunOnceScheduler(() => report.call(host), 1000)); + const settle = async (change: () => void = () => { }) => { change(); scheduler.schedule(); await timeout(1000); }; + const setOrientation = (orientation: AgentSessionsViewerOrientation) => () => host.sessionsViewerOrientation = orientation; + + await settle(); // hidden view: nothing + await settle(() => host.bodyVisible = true); // shown but still restoring: nothing + await settle(() => host.restoringSession = undefined); // restored: initial + + setOrientation(AgentSessionsViewerOrientation.Stacked)(); // resize flips and returns before settling: nothing + scheduler.schedule(); + await settle(setOrientation(AgentSessionsViewerOrientation.SideBySide)); + + await settle(() => { host._loadingSessionCount = 1; host.sessionsViewerVisible = false; }); // transient state while loading: nothing + await settle(() => host._sessionsListSuppressionCount = 1); // transient state while transitioning: nothing + await settle(() => { host._loadingSessionCount = 0; host._sessionsListSuppressionCount = 0; host.sessionsViewerVisible = true; }); // settled unchanged: nothing + await settle(setOrientation(AgentSessionsViewerOrientation.Stacked)); // settled change: orientationChanged + + const layout = { configuredOrientation: 'sideBySide', sessionsVisible: true, sessionsEnabled: true, position: 'right', chatViewLocation: 'auxiliaryBar', chatViewMaximized: false }; + assert.deepStrictEqual(events, [ + { eventName: 'chatViewSessionsLayout', ...layout, effectiveOrientation: 'sideBySide', reason: 'initial' }, + { eventName: 'chatViewSessionsLayout', ...layout, effectiveOrientation: 'stacked', reason: 'orientationChanged' }, + ]); + })); + test('window focus refreshes automatically while the toolbar retains explicit refresh intent', async () => { const focusChanged = store.add(new Emitter()); const reasons: (ChatSessionRefreshReason | undefined)[] = []; @@ -298,6 +347,27 @@ suite('ChatViewPane session transitions', () => { } }); +suite('ChatViewPane persisted session restore', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + function createPane(error: Error): { acquireTransferredOrPersistedSession(token: CancellationToken, debugOwner: string): Promise<{ modelRef?: IChatModelReference }> } { + return Object.assign(Object.create(ChatViewPane.prototype), { + viewState: { sessionResource: URI.parse('agent-host-copilotcli:/missing') }, + logService: new NullLogService(), + chatService: { acquireOrLoadSession: async () => { throw error; } }, + }); + } + + test('starts a new session when the persisted session fails to load', async () => { + const restored = await createPane(new Error('Session identity was not advertised by its agent host')).acquireTransferredOrPersistedSession(CancellationToken.None, 'test'); + assert.strictEqual(restored.modelRef, undefined); + }); + + test('still propagates cancellation', async () => { + await assert.rejects(createPane(new CancellationError()).acquireTransferredOrPersistedSession(CancellationToken.None, 'test'), CancellationError); + }); +}); + suite('ChatViewPane managed permission rules', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -489,3 +559,44 @@ suite('ChatViewPane restored chat with a harness disabled by policy', () => { }); }); }); + +suite('ChatViewPane widget readiness', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('whenWidget resolves to the widget the body creates, once it is rendered, as the body creates its controls', async () => { + const steps: string[] = []; + const store = disposables.add(new DisposableStore()); + const widget = upcastPartial({ + render: () => { steps.push('render'); }, + setVisible: () => { }, + dispose: () => { }, + }); + const instantiationService = { + createInstance: () => ({ onDidChangeHeight: Event.None, dispose: () => { } }), + createChild: () => ({ createInstance: (ctor: unknown) => ctor === ChatWidget ? widget : { dispose: () => { } }, dispose: () => { } }), + }; + // The order of the real Chat view: its title control, then its widget, which it renders + const pane = Object.assign(Object.create(ChatViewPane.prototype), { + _store: store, + _widgetCreated: new DeferredPromise(), + id: 'workbench.panel.chat.view.copilot', + instantiationService, + layoutService: { getContainer: () => mainWindow.document.createElement('div') }, + scopedContextKeyService: {}, + aiCustomizationWorkspaceService: { activeProjectRoot: constObservable(undefined) }, + customizationMigrationsAvailable: { set: () => { } }, + getLocationBasedColors: () => ({ background: '', overlayBackground: '', listOverrideStyles: {} }), + onDidChangeBodyVisibility: Event.None, + isBodyVisible: () => true, + welcomeController: undefined, + relayout: () => { }, + }) as ChatViewPane; + pane.whenWidget.then(created => steps.push(created === widget ? 'resolved to the widget' : `resolved to ${created}`)); + + (Reflect.get(ChatViewPane.prototype, 'createChatControl') as (this: ChatViewPane, parent: HTMLElement) => ChatWidget).call(pane, mainWindow.document.createElement('div')); + await timeout(0); + + assert.deepStrictEqual(steps, ['render', 'resolved to the widget']); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/attachments/chatInlineAttachments.test.ts b/src/vs/workbench/contrib/chat/test/common/attachments/chatInlineAttachments.test.ts index bf18e24ca8a7..951ce883d686 100644 --- a/src/vs/workbench/contrib/chat/test/common/attachments/chatInlineAttachments.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/attachments/chatInlineAttachments.test.ts @@ -76,6 +76,17 @@ suite('Chat inline attachments', () => { }); }); + test('says verbatim pills exactly where they are, while separating adjacent pills', () => { + const project = (input: string, anchors: Parameters[1]) => projectInlineAttachments(input, anchors, [])?.text; + assert.deepStrictEqual([ + project(`see (${A}), "${A}"`, [{ offset: 5, text: 'link-a', verbatim: true }, { offset: 10, text: 'link-b', verbatim: true }]), + project(`${A}${A}${A}.`, [{ offset: 0, text: 'link-a', verbatim: true }, { offset: 1, text: '#x' }, { offset: 2, text: 'link-b', verbatim: true }]), + ], [ + 'see (link-a), "link-b"', + 'link-a #x link-b.', + ]); + }); + test('maps positions across lines', () => { const input = `first\r\n${A} second ${A}`; const projection = projectInlineAttachments(input, [ diff --git a/src/vs/workbench/contrib/chat/test/common/chatDailyUsage.test.ts b/src/vs/workbench/contrib/chat/test/common/chatDailyUsage.test.ts new file mode 100644 index 000000000000..2cbb153b1fe8 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/chatDailyUsage.test.ts @@ -0,0 +1,139 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { AgentsWindowUsage } from '../../common/agentsWindowUsage.js'; +import { ChatDailyUsage } from '../../common/chatDailyUsage.js'; +import { SessionType } from '../../common/chatSessionsService.js'; +import { EditorChatUsage } from '../../common/editorChatUsage.js'; + +/** + * A window whose local cache never sees other windows' writes, while shared values go to + * one authoritative map, as they do through the main process. + */ +class WindowStorageService extends InMemoryStorageService { + constructor(private readonly shared: Map) { + super(); + } + + override async readApplicationSharedValue(key: string): Promise { + return this.shared.get(key); + } + + override async compareAndSwapApplicationSharedValue(key: string, expectedValue: string | undefined, newValue: string): Promise<{ swapped: boolean; currentValue: string | undefined }> { + const currentValue = this.shared.get(key); + if (currentValue !== expectedValue) { + return { swapped: false, currentValue }; + } + this.shared.set(key, newValue); + return { swapped: true, currentValue: newValue }; + } +} + +suite('ChatDailyUsage', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const minute = 60 * 1000; + const hour = 60 * minute; + const day = 24 * hour; + + test('sums messages and new sessions over the current and preceding UTC days and in total', () => { + const storage = disposables.add(new InMemoryStorageService()); + const empty = new ChatDailyUsage(storage).getTelemetry(100 * day); + const usage = new ChatDailyUsage(storage); + usage.startTracking(60 * day); + usage.recordMessage(true, 70 * day); + usage.recordMessage(true, 71 * day); + usage.recordMessage(false, 93 * day + 23 * hour); + usage.recordMessage(true, 94 * day); + usage.recordMessage(false, 100 * day + 2 * hour); + assert.deepStrictEqual({ empty, recorded: new ChatDailyUsage(storage).getTelemetry(100 * day + 12 * hour) }, { + empty: { messagesLast7Days: 0, messagesLast30Days: 0, messagesTotal: 0, sessionsLast7Days: 0, sessionsLast30Days: 0, sessionsTotal: 0, minutesSinceLastMessage: undefined, trackedDays: 0 }, + recorded: { messagesLast7Days: 2, messagesLast30Days: 4, messagesTotal: 5, sessionsLast7Days: 1, sessionsLast30Days: 2, sessionsTotal: 3, minutesSinceLastMessage: 600, trackedDays: 30 }, + }); + }); + + test('claims one report per UTC day across windows sharing storage and keeps the first tracking day', async () => { + const storage = disposables.add(new InMemoryStorageService()); + const first = new ChatDailyUsage(storage); + const second = new ChatDailyUsage(storage); + first.startTracking(10 * day); + second.startTracking(11 * day); + first.recordMessage(true, 10 * day + hour); + assert.deepStrictEqual([ + await first.takeDailyReport(10 * day + 2 * hour), + await second.takeDailyReport(10 * day + 23 * hour), + await second.takeDailyReport(11 * day), + await first.takeDailyReport(11 * day + hour), + ], [ + { messagesLast7Days: 1, messagesLast30Days: 1, messagesTotal: 1, sessionsLast7Days: 1, sessionsLast30Days: 1, sessionsTotal: 1, minutesSinceLastMessage: 60, trackedDays: 0 }, + undefined, + { messagesLast7Days: 1, messagesLast30Days: 1, messagesTotal: 1, sessionsLast7Days: 1, sessionsLast30Days: 1, sessionsTotal: 1, minutesSinceLastMessage: 23 * 60, trackedDays: 1 }, + undefined, + ]); + }); + + test('claims the daily report atomically when windows have stale local caches', async () => { + const shared = new Map(); + const first = new ChatDailyUsage(disposables.add(new WindowStorageService(shared))); + const second = new ChatDailyUsage(disposables.add(new WindowStorageService(shared))); + const concurrent = await Promise.all([first.takeDailyReport(10 * day), second.takeDailyReport(10 * day)]); + const sequential = [ + await second.takeDailyReport(10 * day + 23 * hour), + await second.takeDailyReport(11 * day), + await first.takeDailyReport(11 * day + hour), + ]; + assert.deepStrictEqual({ concurrent: concurrent.map(Boolean), sequential: sequential.map(Boolean) }, { + concurrent: [true, false], + sequential: [false, true, false], + }); + }); + + test('seeds totals once and last usage from editor and Agents Window usage recorded before tracking', () => { + const storage = disposables.add(new InMemoryStorageService()); + const editor = new EditorChatUsage(storage); + const agentsWindow = new AgentsWindowUsage(storage); + editor.recordSubmission(SessionType.Local, true, false, false, 10 * day); + editor.recordSubmission(SessionType.Local, false, false, false, 10 * day); + agentsWindow.recordSessionCreated(9 * day); + const usage = new ChatDailyUsage(storage); + usage.startTracking(10 * day + 30 * minute); + const seeded = usage.getTelemetry(10 * day + hour); + editor.recordSubmission(SessionType.Local, true, false, false, 10 * day + 40 * minute); + agentsWindow.recordSessionCreated(10 * day + 40 * minute); + usage.startTracking(10 * day + 40 * minute); + const restarted = usage.getTelemetry(10 * day + hour); + usage.recordMessage(true, 10 * day + 45 * minute); + assert.deepStrictEqual({ seeded, restarted, recorded: usage.getTelemetry(10 * day + hour) }, { + seeded: { messagesLast7Days: 0, messagesLast30Days: 0, messagesTotal: 3, sessionsLast7Days: 0, sessionsLast30Days: 0, sessionsTotal: 2, minutesSinceLastMessage: 60, trackedDays: 0 }, + restarted: { messagesLast7Days: 0, messagesLast30Days: 0, messagesTotal: 3, sessionsLast7Days: 0, sessionsLast30Days: 0, sessionsTotal: 2, minutesSinceLastMessage: 20, trackedDays: 0 }, + recorded: { messagesLast7Days: 1, messagesLast30Days: 1, messagesTotal: 4, sessionsLast7Days: 1, sessionsLast30Days: 1, sessionsTotal: 3, minutesSinceLastMessage: 15, trackedDays: 0 }, + }); + }); + + test('recovers from malformed state and keeps usage in machine-local shared storage', () => { + const storage = disposables.add(new InMemoryStorageService()); + storage.store('chat.dailyUsage', '{"days":[[5,"x",0],[5,2]],"lastMessage":"y","messagesTotal":-1,"sessionsTotal":"z"}', StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE); + const malformed = new ChatDailyUsage(storage).getTelemetry(5 * day); + storage.store('chat.dailyUsage', 'not json', StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE); + const usage = new ChatDailyUsage(storage); + usage.startTracking(5 * day); + usage.recordMessage(false, 5 * day); + assert.deepStrictEqual({ + malformed, + shared: storage.keys(StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE).sort(), + synced: storage.keys(StorageScope.APPLICATION_SHARED, StorageTarget.USER), + application: storage.keys(StorageScope.APPLICATION, StorageTarget.MACHINE), + recorded: new ChatDailyUsage(storage).getTelemetry(5 * day), + }, { + malformed: { messagesLast7Days: 0, messagesLast30Days: 0, messagesTotal: 0, sessionsLast7Days: 0, sessionsLast30Days: 0, sessionsTotal: 0, minutesSinceLastMessage: undefined, trackedDays: 0 }, + shared: ['chat.dailyUsage', 'chat.dailyUsage.trackingStartDay'], + synced: [], + application: [], + recorded: { messagesLast7Days: 1, messagesLast30Days: 1, messagesTotal: 1, sessionsLast7Days: 0, sessionsLast30Days: 0, sessionsTotal: 0, minutesSinceLastMessage: 0, trackedDays: 0 }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/chatEntitlementService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatEntitlementService.test.ts index 1211a104e10d..5c03b61a1512 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatEntitlementService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatEntitlementService.test.ts @@ -5,15 +5,17 @@ import assert from 'assert'; import { IEntitlementsData } from '../../../../../base/common/defaultAccount.js'; +import { Emitter } from '../../../../../base/common/event.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IContextKeyChangeEvent } from '../../../../../platform/contextkey/common/contextkey.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; -import { ChatEntitlement, ChatEntitlementContext, ChatEntitlementContextKeys, ChatEntitlementService, getQuotaReset, getQuotaUsage, parseQuotas, QuotaUsageKind } from '../../../../services/chat/common/chatEntitlementService.js'; +import { ChatEntitlement, ChatEntitlementContext, ChatEntitlementContextKeys, ChatEntitlementService, getChatEntitlement, getQuotaReset, getQuotaUsage, parseQuotas, QuotaUsageKind, SIMULATABLE_CHAT_ENTITLEMENTS, simulateEntitlementsData } from '../../../../services/chat/common/chatEntitlementService.js'; import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; import { TestStorageService } from '../../../../test/common/workbenchTestServices.js'; @@ -554,15 +556,64 @@ suite('getQuotaReset', () => { }); }); +suite('simulateEntitlementsData', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + test('every simulated entitlement resolves to itself and keeps the account identity', () => { + const actual: IEntitlementsData = { + access_type_sku: 'copilot_enterprise_seat_quota', + chat_enabled: true, + assigned_date: '2026-04-17T12:53:45-07:00', + can_signup_for_limited: false, + copilot_plan: 'enterprise', + organization_login_list: ['microsoft'], + is_staff: true, + analytics_tracking_id: 'tracking-id', + }; + + const simulated = SIMULATABLE_CHAT_ENTITLEMENTS.map(entitlement => { + const data = simulateEntitlementsData(entitlement, actual); + const quotas = parseQuotas(data); + return { entitlement: getChatEntitlement(data), organisations: data.organization_login_list, isStaff: data.is_staff, trackingId: data.analytics_tracking_id, limitedChat: quotas.chat?.unlimited === false, premiumChat: quotas.premiumChat !== undefined }; + }); + + const expected = (entitlement: ChatEntitlement, limitedChat: boolean, premiumChat: boolean) => ({ entitlement, organisations: ['microsoft'], isStaff: true, trackingId: 'tracking-id', limitedChat, premiumChat }); + assert.deepStrictEqual(simulated, [ + expected(ChatEntitlement.Available, false, false), + expected(ChatEntitlement.Unavailable, false, false), + expected(ChatEntitlement.Free, true, false), + expected(ChatEntitlement.EDU, false, true), + expected(ChatEntitlement.Pro, false, true), + expected(ChatEntitlement.ProPlus, false, true), + expected(ChatEntitlement.Max, false, true), + expected(ChatEntitlement.Business, false, true), + expected(ChatEntitlement.Enterprise, false, true), + ]); + }); +}); + suite('ChatEntitlementService', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - function createService(): ChatEntitlementService { + class ChangeEmittingContextKeyService extends MockContextKeyService { + private readonly _onDidChangeContext = store.add(new Emitter()); + override get onDidChangeContext() { return this._onDidChangeContext.event; } + + fireChange(key: string): void { + this._onDidChangeContext.fire({ + affectsSome: keys => keys.has(key), + allKeysContainedIn: keys => keys.has(key), + }); + } + } + + function createService(contextKeyService = store.add(new MockContextKeyService())): ChatEntitlementService { return store.add(new ChatEntitlementService( store.add(new TestInstantiationService()), new class extends mock() { }, new class extends mock() { }, - store.add(new MockContextKeyService()), + contextKeyService, new TestConfigurationService(), NullTelemetryService, new NullLogService(), @@ -570,6 +621,29 @@ suite('ChatEntitlementService', () => { )); } + test('signals sentiment changes for every setup key that sentiment reads', () => { + const contextKeyService = store.add(new ChangeEmittingContextKeyService()); + const service = createService(contextKeyService); + const fired: string[] = []; + const keys = [ + ChatEntitlementContextKeys.Setup.hidden.key, + ChatEntitlementContextKeys.Setup.disabled.key, + ChatEntitlementContextKeys.Setup.disabledInWorkspace.key, + ChatEntitlementContextKeys.chatAnonymous.key, + ]; + for (const key of keys) { + const listener = service.onDidChangeSentiment(() => fired.push(key)); + contextKeyService.fireChange(key); + listener.dispose(); + } + + assert.deepStrictEqual(fired, [ + ChatEntitlementContextKeys.Setup.hidden.key, + ChatEntitlementContextKeys.Setup.disabled.key, + ChatEntitlementContextKeys.Setup.disabledInWorkspace.key, + ]); + }); + test('signals changed usage when only consumed credits move on an unlimited plan', () => { const service = createService(); const fired: string[] = []; diff --git a/src/vs/workbench/contrib/chat/test/common/chatErrorMessages.test.ts b/src/vs/workbench/contrib/chat/test/common/chatErrorMessages.test.ts index 17e50ea0d79f..5c4247a5d76e 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatErrorMessages.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatErrorMessages.test.ts @@ -215,6 +215,15 @@ suite('ChatErrorMessages', () => { ]); }); + test('rate-limit messages suggest Copilot Fusion when Auto is presented as Fusion', () => { + const message = (capiCode: string | undefined) => getChatErrorDetailsFromFetchError({ type: ChatFetchResponseType.RateLimited, retryAfter: 30, capiError: capiCode ? { code: capiCode } : undefined }, undefined, undefined, undefined, true).message; + assert.deepStrictEqual([message('model_overloaded'), message('user_model_rate_limited'), message(undefined)], [ + 'Sorry, the upstream model provider is currently experiencing high demand. Please try again in 30 seconds or consider switching to Copilot Fusion. [Learn More](https://aka.ms/github-copilot-rate-limit-error)', + 'You\'ve hit the rate limit for this model. Please try switching to Copilot Fusion or try again in 30 seconds. [Learn More](https://aka.ms/github-copilot-rate-limit-error)', + 'Sorry, your request was rate-limited. Please wait 30 seconds before trying again or consider switching to Copilot Fusion. [Learn More](https://aka.ms/github-copilot-rate-limit-error)', + ]); + }); + test('quota sub-codes map to specific messages', () => { const messages = [ getChatErrorDetailsFromFetchError({ type: ChatFetchResponseType.QuotaExceeded, capiError: { code: 'overage_limit_reached' } }, undefined).message, diff --git a/src/vs/workbench/contrib/chat/test/common/chatPetJumpGame.test.ts b/src/vs/workbench/contrib/chat/test/common/chatPetJumpGame.test.ts index 3ae4f86f2fcc..3aa88cc9def0 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatPetJumpGame.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatPetJumpGame.test.ts @@ -387,6 +387,47 @@ suite('ChatPetJumpGame', () => { }); }); + test('retry restores all crumbling platforms in the same course across repeated attempts', () => { + const model = climbTo(18); + const snapshot = () => ({ + player: { ...model.player }, + platforms: model.platforms.map(({ id, left, width, height, kind, collapseProgress, fallDistance }) => ({ id, left, width, height, kind, collapseProgress, fallDistance })), + walls: [...model.walls], + hops: model.hops, + bestHeight: model.bestHeight, + }); + const crumblingState = () => model.platforms.filter(platform => platform.kind === 'crumbling') + .map(({ id, collapseProgress, fallDistance }) => ({ id, collapseProgress, fallDistance })); + advance(model, 2000); + assert.deepStrictEqual(crumblingState().filter(platform => platform.fallDistance >= model.petSize * 4).map(platform => platform.id), [9, 17]); + const before = snapshot(); + const restored = { + ...before, + platforms: before.platforms.map(platform => ({ ...platform, collapseProgress: 0, fallDistance: 0 })), + }; + const intact = crumblingState().map(platform => ({ ...platform, collapseProgress: 0, fallDistance: 0 })); + model.hop(0); + advance(model, 100); + for (let attempt = 0; attempt < 3; attempt++) { + model.resetToCheckpoint(); + assert.deepStrictEqual(snapshot(), restored); + advance(model, 2000); + assert.deepStrictEqual(crumblingState(), intact); + } + + const platform = model.platforms[9]; + Object.assign(model.player, { + x: platform.left + platform.width / 2, height: platform.height + model.petSize, + velocityX: 0, velocityY: 0, platform: undefined, + }); + advance(model, 250); + const landed = { platform: model.player.platform, crumbling: platform.collapseProgress > 0, hops: model.hops }; + advance(model, 1600); + assert.deepStrictEqual({ landed, collapsed: platform.collapseProgress, falling: platform.fallDistance > 0 }, { + landed: { platform: 9, crumbling: true, hops: 18 }, collapsed: 1, falling: true, + }); + }); + test('bank shots reflect horizontal speed without an extra vertical kick and land on the narrow ledge', () => { const model = climbTo(11); const wall = model.walls.find(wall => wall.id === 12)!; diff --git a/src/vs/workbench/contrib/chat/test/common/chatQuestionCarouselHelpers.test.ts b/src/vs/workbench/contrib/chat/test/common/chatQuestionCarouselHelpers.test.ts index 6f8dc12811b8..5a0d32717ece 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatQuestionCarouselHelpers.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatQuestionCarouselHelpers.test.ts @@ -80,6 +80,20 @@ suite('ChatQuestionCarouselHelpers', () => { [1, 0], ); }); + + test('lists yes before no for a yes/no question, whatever its declared order or default', () => { + const yesNo: IChatQuestion = { + id: 'q_bool', + type: 'singleSelect', + title: 'Continue?', + options: [ + { id: 'n', label: 'false', value: 'false' }, + { id: 'y', label: 'true', value: 'true' }, + ], + defaultValue: 'n', + }; + assert.deepStrictEqual(getOptionsWithDefaultsFirst(yesNo).map(o => o.originalIndex), [1, 0]); + }); }); suite('getDisplayedQuestionText', () => { diff --git a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts index bcc5a81a5729..c5544d5a2c54 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts @@ -59,7 +59,7 @@ import { AgentHostCompletionReferenceKind, ChatPasteAttachmentMetadata, IChatReq import { IChatVariablesService } from '../../../common/attachments/chatVariables.js'; import { IChatDebugService } from '../../../common/chatDebugService.js'; import { ChatDebugServiceImpl } from '../../../common/chatDebugServiceImpl.js'; -import { ChatRequestQueueKind, ChatSendResult, IChatFollowup, IChatModelReference, IChatProgress, IChatService, IChatUserActionEvent, ResponseModelState, IRemotePendingRequest } from '../../../common/chatService/chatService.js'; +import { ChatRequestQueueKind, ChatSendResult, IChatFollowup, IChatModelReference, IChatProgress, IChatRequestAcceptedEvent, IChatService, IChatUserActionEvent, ResponseModelState, IRemotePendingRequest } from '../../../common/chatService/chatService.js'; import { backfillTransferredModel, backfillRestoredPickerState, ChatService, rekeyIntendedModel } from '../../../common/chatService/chatServiceImpl.js'; import { ChatOpenDiagnosticsService, IChatOpenDiagnosticsService } from '../../../common/chatOpenDiagnosticsService.js'; import { IIntendedModelSelection, ModelSelectionReason } from '../../../common/modelSelection.js'; @@ -69,7 +69,7 @@ import { ChatRequestOriginKind } from '../../../common/chatRequestOrigin.js'; import { ChatAgentLocation, ChatModeKind } from '../../../common/constants.js'; import { ChatEditingSessionState, IChatEditingService, IChatEditingSession, IModifiedFileEntry, ModifiedFileEntryState } from '../../../common/editing/chatEditingService.js'; import { ILanguageModelChatMetadata, ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService } from '../../../common/languageModels.js'; -import { ChatModel, IChatModel, ISerializableChatData, ISerializableChatModelInputState } from '../../../common/model/chatModel.js'; +import { ChatModel, IChatModel, IChatRequestModeInfo, ISerializableChatData, ISerializableChatModelInputState } from '../../../common/model/chatModel.js'; import { ChatToolInvocation } from '../../../common/model/chatProgressTypes/chatToolInvocation.js'; import { ChatSessionOperationLog } from '../../../common/model/chatSessionOperationLog.js'; import { IChatSessionIndex } from '../../../common/model/chatSessionStore.js'; @@ -647,10 +647,11 @@ suite('ChatService', () => { test('acceptance counts submissions once, not rejections, system messages, retries or queue drains', async () => { const service = createChatService(); const model = startSessionModel(service).object; - const accepted: boolean[] = []; - testDisposables.add(service.onDidAcceptRequest(event => accepted.push(event.isNewSession))); + const modeInfo: IChatRequestModeInfo = { kind: undefined, isBuiltin: true, modeInstructions: undefined, telemetryModeId: undefined, applyCodeBlockSuggestionId: undefined }; + const accepted: { isNewSession: boolean; modeInfo?: IChatRequestModeInfo }[] = []; + testDisposables.add(service.onDidAcceptRequest(event => accepted.push({ isNewSession: event.isNewSession, modeInfo: event.modeInfo }))); await service.sendRequest(model.sessionResource, ''); - const first = await service.sendRequest(model.sessionResource, 'first'); + const first = await service.sendRequest(model.sessionResource, 'first', { modeInfo }); ChatSendResult.assertSent(first); await first.data.responseCompletePromise; await service.resendRequest(model.getRequests()[0]); @@ -661,7 +662,25 @@ suite('ChatService', () => { await service.sendRequest(model.sessionResource, 'steering', { queue: ChatRequestQueueKind.Steering, pauseQueue: true }); service.processPendingRequests(model.sessionResource); await timeout(10); - assert.deepStrictEqual(accepted, [true, false, false]); + assert.deepStrictEqual(accepted, [ + { isNewSession: true, modeInfo }, + { isNewSession: false, modeInfo: undefined }, + { isNewSession: false, modeInfo: undefined }, + ]); + }); + + test('acceptance exposes the Agent Host origin of delegated submissions', async () => { + const service = createChatService(); + const model = startSessionModel(service).object; + const accepted: IChatRequestAcceptedEvent['agentHostMessageOrigin'][] = []; + testDisposables.add(service.onDidAcceptRequest(event => accepted.push(event.agentHostMessageOrigin))); + for (const agentHostMessageOrigin of [undefined, { kind: MessageKind.Agent }]) { + const sent = await service.sendRequest(model.sessionResource, 'hello', { agentHostMessageOrigin }); + ChatSendResult.assertSent(sent); + await sent.data.responseCompletePromise; + } + await service.sendRequest(model.sessionResource, 'queued', { queue: ChatRequestQueueKind.Queued, pauseQueue: true, agentHostMessageOrigin: { kind: MessageKind.Tool } }); + assert.deepStrictEqual(accepted, [undefined, { kind: MessageKind.Agent }, { kind: MessageKind.Tool }]); }); async function createSurveySession(sessionType: string, provider?: string) { @@ -6634,12 +6653,13 @@ suite('ChatService', () => { assert.deepStrictEqual({ canceled: response?.isCanceled, completionTimestamp: response?.completionTimestamp }, { canceled: true, completionTimestamp: completedAt }); }); - test('a cold restore waits for the transferred draft\'s model, not the history\'s last one', async () => { + test('a cold restore waits for the transferred draft\'s model and configuration, not the history\'s last model', async () => { const draftModelId = 'agent-host-copilotcli:gpt-5.3-codex'; + const configuration = { thinkingLevel: 'high', contextSize: 200_000 }; const { resource } = setupRemoteProvider({ history: [{ type: 'request', prompt: 'hello', participant: remoteScheme, modelId: 'agent-host-copilotcli:claude-opus-5.5' }], // The live catalog is not loaded, so the draft arrives without its model's metadata. - transferredState: { editingSession: undefined, inputState: { attachments: [], contrib: {}, inputText: '', mode: { id: 'agent', kind: ChatModeKind.Agent }, selectedModel: undefined, selections: [] }, selectedModelId: draftModelId }, + transferredState: { editingSession: undefined, inputState: { attachments: [], contrib: {}, inputText: '', mode: { id: 'agent', kind: ChatModeKind.Agent }, selectedModel: undefined, selections: [] }, selectedModelId: draftModelId, selectedModelConfiguration: configuration }, }); const testService = createChatService(); @@ -6651,7 +6671,7 @@ suite('ChatService', () => { intended: ref.object.inputModel.intendedModel, selected: ref.object.inputModel.state.get()?.selectedModel?.identifier, }, { - intended: { modelId: draftModelId, reason: ModelSelectionReason.SessionRestore }, + intended: { modelId: draftModelId, reason: ModelSelectionReason.SessionRestore, configuration }, selected: undefined, }); }); diff --git a/src/vs/workbench/contrib/chat/test/common/customizationsLocation.test.ts b/src/vs/workbench/contrib/chat/test/common/customizationsLocation.test.ts new file mode 100644 index 000000000000..e35012b95ea4 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/customizationsLocation.test.ts @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { ChatCustomizationsLocation, resolveChatCustomizationsLocation } from '../../common/customizationsLocation.js'; + +suite('Chat customizations location', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('preserves window defaults and applies explicit placements independently of sidebar navigation', () => { + const locations: ChatCustomizationsLocation[] = ['auto', 'sidebar', 'sessionsHeader', 'chatToolbar', 'chatInput']; + assert.deepStrictEqual(locations.map(location => ({ + location, + editor: resolveChatCustomizationsLocation(location, false, false), + agents: resolveChatCustomizationsLocation(location, true, false), + rearrangedAgents: resolveChatCustomizationsLocation(location, true, true), + })), [ + { location: 'auto', editor: 'chatToolbar', agents: 'sidebar', rearrangedAgents: 'sessionsHeader' }, + { location: 'sidebar', editor: 'chatToolbar', agents: 'sidebar', rearrangedAgents: 'sidebar' }, + { location: 'sessionsHeader', editor: 'chatToolbar', agents: 'sessionsHeader', rearrangedAgents: 'sessionsHeader' }, + { location: 'chatToolbar', editor: 'chatToolbar', agents: 'chatToolbar', rearrangedAgents: 'chatToolbar' }, + { location: 'chatInput', editor: 'chatInput', agents: 'chatInput', rearrangedAgents: 'chatInput' }, + ]); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/nativeComponents/nativeComponentsParser.test.ts b/src/vs/workbench/contrib/chat/test/common/nativeComponents/nativeComponentsParser.test.ts new file mode 100644 index 000000000000..856eedea668f --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/nativeComponents/nativeComponentsParser.test.ts @@ -0,0 +1,275 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { INativeComponentsDocument, NativeComponentsLimits } from '../../../common/nativeComponents/nativeComponents.js'; +import { parseNativeComponents } from '../../../common/nativeComponents/nativeComponentsParser.js'; +import { describeNativeComponents } from '../../../common/nativeComponents/nativeComponentsText.js'; + +suite('Native components parser', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + const catalogue = [ + '', + ' ', + ' ', + '', + '', + ' Build & test', + ' ', + ' Most of the improvement', + ' comes from caching.', + ' ', + ' Flaky', + '', + '', + ' Target', + ' Seconds', + ' Full12.4', + ' Incremental', + '
', + '', + ' ', + ' ', + '', + '', + ' Median of five runs.', + '', + ].join('\n'); + + const document: INativeComponentsDocument = { + version: 1, + children: [ + { + type: 'columns', children: [ + { type: 'metric', label: 'Full build', value: '12.4 s', delta: undefined, tone: 'neutral' }, + { type: 'metric', label: 'Incremental build', value: '1.8 s', delta: '-85%', tone: 'positive' }, + ] + }, + { + type: 'stack', children: [ + { type: 'text', variant: 'heading', text: 'Build & test' }, + { type: 'text', variant: 'body', text: 'Most of the improvement comes from caching.' }, + { type: 'badge', text: 'Flaky', tone: 'warning' }, + ] + }, + { + type: 'table', caption: 'Duration by target', + columns: [{ header: 'Target', align: 'start' }, { header: 'Seconds', align: 'end' }], + rows: [['Full', '12.4'], ['Incremental', '']], + }, + { + type: 'barChart', title: 'Build duration', unit: 's', + bars: [{ label: 'Full', value: 12.4, valueText: '12.4' }, { label: 'Incremental', value: 1.8, valueText: '1.80' }], + }, + { type: 'disclosure', summary: 'Method', children: [{ type: 'text', variant: 'caption', text: 'Median of five runs.' }] }, + ], + }; + + /** The outcome of parsing, reduced to what a failing block reports. */ + function failure(source: string, fenceInfo?: string): string { + const { error } = parseNativeComponents(source, fenceInfo); + return error ? `${error.line ?? '-'}: ${error.message}` : 'valid'; + } + + test('parses every component of the catalogue into a typed document', () => { + assert.deepStrictEqual(parseNativeComponents(catalogue), { document }); + }); + + test('describes a document as the text alternative of its visual', () => { + assert.deepStrictEqual(describeNativeComponents(document).split('\n'), [ + 'Full build: 12.4 s', + 'Incremental build: 1.8 s (-85%, Positive)', + 'Build & test', + 'Most of the improvement comes from caching.', + 'Flaky (Warning)', + 'Table: Duration by target', + 'Target | Seconds', + 'Full | 12.4', + 'Incremental | ', + 'Bar chart: Build duration', + 'Full: 12.4 s', + 'Incremental: 1.80 s', + 'Details: Method', + 'Median of five runs.', + ]); + }); + + test('keeps literals as text: decodes the supported entities and leaves everything else as written', () => { + const result = parseNativeComponents('<b> "R&D" 'x' {a}   � �'); + assert.deepStrictEqual(result.document?.children, [ + { type: 'text', variant: 'body', text: ' "R&D" \'x\' {a}   � �' }, + { type: 'metric', label: '{count} > 1', value: 'a b', delta: undefined, tone: 'neutral' }, + ]); + }); + + test('collapses ordinary whitespace and keeps a non-breaking space as written', () => { + const result = parseNativeComponents('\u00a0\n 1.8 s \n\t a\u202fb  '); + assert.deepStrictEqual(result.document?.children, [{ + type: 'stack', children: [ + { type: 'text', variant: 'body', text: '1.8\u00a0s a\u202fb \u00a0' }, + { type: 'metric', label: 'Full build', value: '12.4\u00a0s', delta: undefined, tone: 'neutral' }, + ] + }]); + }); + + test('rejects everything outside the catalogue, with the line and a reason', () => { + assert.deepStrictEqual([ + '', + ' \n ', + '', + '
Hello
', + '', + '\n bold\n', + '', + 'A', + '', + '', + '', + 'Total: {total}', + '\n {/* note */}\n A\n', + '\nA', + 'import { Chart } from "charts";\nA', + 'A\nloose text', + '\n loose text\n A\n', + 'a < b', + '', + '', + '', + '', + '', + '', + 'text', + 'A', + '', + '', + '\n A\n', + '\n A', + '', + '', + 'A', + 'A
', + 'A
', + 'A
', + 'A12
', + 'A1B
', + 'A1
', + '', + '', + '', + '', + '', + '', + ``, + 'A', + '', + ].map(source => failure(source)), [ + '-: The block has no components.', + '-: The block has no components.', + '1: Unknown component "Chart". Available here: Stack, Columns, Text, Metric, Badge, Table, BarChart, Disclosure.', + '1: Unknown component "div". Available here: Stack, Columns, Text, Metric, Badge, Table, BarChart, Disclosure.', + '1: Unknown component "script". Available here: Stack, Columns, Text, Metric, Badge, Table, BarChart, Disclosure.', + '2: "Text" can only contain text, but contains "b".', + '1: Unknown attribute "style" on "Metric". Allowed: label, value, delta, tone.', + '1: Unknown attribute "class" on "Stack", which has no attributes.', + '1: Unknown attribute "onClick" on "Metric". Allowed: label, value, delta, tone.', + '1: Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as { or }.', + '1: Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as { or }.', + '1: Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as { or }.', + '2: Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as { or }.', + '1: Expected a component name after "<". Write a literal "<" in text as <.', + '1: Expressions in braces are not supported. Use quoted literal values, and write a literal brace in text as { or }.', + '2: Text must be inside a component, such as "Text".', + '2: "Stack" cannot contain text. Put text in a "Text" component.', + '1: Expected a component name after "<". Write a literal "<" in text as <.', + '1: The "value" attribute of "Metric" needs a value in quotes.', + '1: The "value" attribute of "Metric" needs a value in quotes.', + '1: The "value" attribute of "Metric" needs a value in quotes.', + '1: The "label" attribute of "Metric" is set more than once.', + '1: "Metric" needs a "value" attribute.', + '1: "Metric" needs a "label" attribute.', + '1: "green" is not a valid "tone" for "Metric". Allowed: neutral, positive, negative, warning.', + '1: "Metric" cannot have content. Set its attributes instead.', + '1: "title" is not a valid "variant" for "Text". Allowed: body, heading, caption.', + '1: "Text" needs text between its tags.', + '1: "Stack" needs at least one component inside it.', + '3: Expected
to close "Stack".', + '2: "Stack" is not closed. Expected .', + '1: Unexpected closing tag .', + '1: "Bar" is only allowed directly inside "BarChart".', + '1: "Row" is only allowed directly inside "Table".', + '1: "Text" is not allowed inside "Table". Allowed: Column, Row.', + '1: The number of cells in this row (1) does not match the number of columns (0).', + '1: "Table" needs at least one "Row".', + '1: The number of cells in this row (2) does not match the number of columns (1).', + '1: Every "Column" of a "Table" must come before its first "Row".', + '1: "Cell" can only contain text, but contains "Badge".', + '1: "BarChart" needs at least one "Bar".', + '1: "BarChart" needs a "title" attribute.', + '1: The "value" of a "Bar" must be a number that is not negative, such as 12.5, without a unit or separators. Found "-1".', + '1: The "value" of a "Bar" must be a number that is not negative, such as 12.5, without a unit or separators. Found "1.5 s".', + '1: The "value" of a "Bar" must be a number that is not negative, such as 12.5, without a unit or separators. Found "1,200".', + '1: The "value" of a "Bar" must be a number that is not negative, such as 12.5, without a unit or separators. Found "1e3".', + `1: The "value" of a "Bar" must be a number that is not negative, such as 12.5, without a unit or separators. Found "${'9'.repeat(400)}".`, + '1: "Disclosure" needs a "summary" attribute.', + '1: Unknown component "constructor". Available here: Stack, Columns, Text, Metric, Badge, Table, BarChart, Disclosure.', + ]); + }); + + test('bounds the size, nesting, component count and datasets of a block', () => { + const nested = (depth: number) => `${''.repeat(depth - 1)}A${''.repeat(depth - 1)}`; + const texts = (count: number) => 'A'.repeat(count); + const table = (columns: number, rows: number) => `${'C'.repeat(columns)}${`${'1'.repeat(columns)}`.repeat(rows)}
`; + const chart = (bars: number) => `${''.repeat(bars)}`; + const padded = (length: number) => `${'a'.repeat(length - ''.length)}`; + assert.deepStrictEqual({ + sourceAtLimit: failure(padded(NativeComponentsLimits.sourceLength)), + sourceOverLimit: failure(padded(NativeComponentsLimits.sourceLength + 1)), + depthAtLimit: failure(nested(NativeComponentsLimits.depth)), + depthOverLimit: failure(nested(NativeComponentsLimits.depth + 1)), + componentsAtLimit: failure(texts(NativeComponentsLimits.components)), + componentsOverLimit: failure(texts(NativeComponentsLimits.components + 1)), + columnsAtLimit: failure(table(NativeComponentsLimits.tableColumns, 1)), + columnsOverLimit: failure(table(NativeComponentsLimits.tableColumns + 1, 1)), + rowsAtLimit: failure(table(1, NativeComponentsLimits.tableRows)), + rowsOverLimit: failure(table(1, NativeComponentsLimits.tableRows + 1)), + barsAtLimit: failure(chart(NativeComponentsLimits.bars)), + barsOverLimit: failure(chart(NativeComponentsLimits.bars + 1)), + }, { + sourceAtLimit: 'valid', + sourceOverLimit: '-: The block is longer than 32000 characters.', + depthAtLimit: 'valid', + depthOverLimit: '1: Components are nested more than 8 levels deep.', + componentsAtLimit: 'valid', + componentsOverLimit: '1: The block has more than 2000 components.', + columnsAtLimit: 'valid', + columnsOverLimit: '1: "Table" has 13 "Column" components, which is more than the limit of 12.', + rowsAtLimit: 'valid', + rowsOverLimit: '1: "Table" has 101 "Row" components, which is more than the limit of 100.', + barsAtLimit: 'valid', + barsOverLimit: '1: "BarChart" has 25 "Bar" components, which is more than the limit of 24.', + }); + }); + + test('accepts only its own schema version on the fence', () => { + const source = 'A'; + assert.deepStrictEqual([undefined, 'vscode-ui', 'VSCODE-UI', ' vscode-ui v1 ', 'vscode-ui v2', 'vscode-ui v0', 'vscode-ui 1', 'vscode-ui v1 wide', 'vscode-ui title="A"', 'vscode-ui:v2', 'html-preview', ''].map(fenceInfo => failure(source, fenceInfo)), [ + 'valid', + 'valid', + 'valid', + 'valid', + '-: The block uses schema version 2, but this version of VS Code supports version 1.', + '-: The block uses schema version 0, but this version of VS Code supports version 1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + '-: The fence can only name the language vscode-ui, optionally followed by a schema version such as v1.', + ]); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/plugins/pluginMarketplaceService.test.ts b/src/vs/workbench/contrib/chat/test/common/plugins/pluginMarketplaceService.test.ts index d3781d94b44d..965af4ec04e8 100644 --- a/src/vs/workbench/contrib/chat/test/common/plugins/pluginMarketplaceService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/plugins/pluginMarketplaceService.test.ts @@ -6,28 +6,32 @@ import assert from 'assert'; import * as sinon from 'sinon'; import { DeferredPromise, installFakeRunWhenIdle, timeout } from '../../../../../../base/common/async.js'; -import { bufferToStream, VSBuffer } from '../../../../../../base/common/buffer.js'; +import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; -import { Disposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../base/common/network.js'; import { observableValue, waitForState } from '../../../../../../base/common/observable.js'; import { isWeb, isWindows } from '../../../../../../base/common/platform.js'; import { basename, joinPath } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { AGENT_PLUGIN_SCHEMA } from '../../../../../../platform/agentPlugins/common/agentPluginParser.js'; import { ConfigurationTarget, IConfigurationChangeEvent, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; -import { IFileService, IFileSystemWatcher } from '../../../../../../platform/files/common/files.js'; +import { FileOperationError, FileOperationResult, IFileService, IFileSystemWatcher } from '../../../../../../platform/files/common/files.js'; +import { GitHubService } from '../../../../../../platform/github/common/githubService.js'; +import { RequestFetch } from '../../../../../../platform/github/common/types.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; import { IMeteredConnectionService } from '../../../../../../platform/meteredConnection/common/meteredConnection.js'; import { COPILOT_STRICT_MARKETPLACES_KEY, IManagedSettingsService, ManagedSettingsData, NullManagedSettingsService } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; -import { IRequestService } from '../../../../../../platform/request/common/request.js'; import { IStorageService, InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { IWorkspaceTrustManagementService } from '../../../../../../platform/workspace/common/workspaceTrust.js'; import { IEnvironmentService } from '../../../../../../platform/environment/common/environment.js'; +import { IWorkbenchGitHubService } from '../../../../../services/github/common/githubService.js'; import { AutoUpdateConfigurationValue, IExtensionsWorkbenchService } from '../../../../extensions/common/extensions.js'; import { ChatConfiguration } from '../../../common/constants.js'; import { ContributionEnablementState } from '../../../common/enablement.js'; @@ -76,6 +80,17 @@ function stubMarketplaceServices(instantiationService: TestInstantiationService, instantiationService.stub(IManagedSettingsService, new NullManagedSettingsService()); } +function stubGitHubService(instantiationService: TestInstantiationService, store: Pick, fetch: RequestFetch): GitHubService { + const service = store.add(new GitHubService({ fetch }, new NullLogService(), NullTelemetryService)); + instantiationService.stub(IWorkbenchGitHubService, { + acquireAnonymousApiClient: async signal => { + signal.throwIfAborted(); + return service.acquireAnonymousClient(); + }, + }); + return service; +} + suite('PluginMarketplaceService', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -206,8 +221,8 @@ suite('PluginMarketplaceService', () => { }, }); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async () => { throw new Error('Unexpected HTTP request'); }, + instantiationService.stub(IWorkbenchGitHubService, { + acquireAnonymousApiClient: async () => { throw new Error('Unexpected GitHub request'); }, }); instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); instantiationService.stub(IWorkspacePluginSettingsService, { @@ -592,90 +607,234 @@ suite('PluginMarketplaceService', () => { suite('PluginMarketplaceService - GitHub marketplace refs', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - - test('fetches GitHub marketplace definitions from the configured ref', async () => { - const requestUrls: string[] = []; + const commit = 'a'.repeat(40); + const definitions = [ + { path: 'marketplace.json', type: MarketplaceType.OpenPlugin }, + { path: '.plugin/marketplace.json', type: MarketplaceType.OpenPlugin }, + { path: '.github/plugin/marketplace.json', type: MarketplaceType.Copilot }, + { path: '.claude-plugin/marketplace.json', type: MarketplaceType.Claude }, + ]; + + teardown(() => sinon.restore()); + + function createService(fetch: RequestFetch, marketplaces = ['microsoft/vscode'], storageService = store.add(new InMemoryStorageService())) { + const repoDir = URI.file('/cache/marketplace'); + const files = new Map(); + const ensureRepository = sinon.stub().resolves(repoDir); const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IConfigurationService, new TestConfigurationService({ - [ChatConfiguration.PluginMarketplaces]: ['microsoft/vscode#marketplace'], + [ChatConfiguration.PluginMarketplaces]: marketplaces, [ChatConfiguration.PluginsEnabled]: true, })); - instantiationService.stub(IEnvironmentService, { cacheHome: URI.file('/cache') } as Partial as IEnvironmentService); - instantiationService.stub(IFileService, {} as unknown as IFileService); + instantiationService.stub(IEnvironmentService, { cacheHome: URI.file('/cache') }); + const fileService = { + readFile: async (resource: URI) => { + const text = files.get(resource.path); + if (text === undefined) { + throw new FileOperationError('File not found', FileOperationResult.FILE_NOT_FOUND); + } + const value = VSBuffer.fromString(text); + return { resource, name: basename(resource), value, size: value.byteLength, mtime: 0, ctime: 0, etag: '', readonly: false, locked: false, executable: false }; + }, + createWatcher: () => ({ onDidChange: Event.None, dispose: () => { } }), + }; + instantiationService.stub(IFileService, fileService); instantiationService.stub(IAgentPluginRepositoryService, { agentPluginsHome: URI.file('/agent-plugins'), - ensureRepository: async () => { - throw new Error('should not clone for 5xx responses'); - }, - } as Partial as IAgentPluginRepositoryService); + ensureRepository, + }); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async (options: { url: string }) => { - requestUrls.push(options.url); - return { res: { headers: {}, statusCode: 500 }, stream: bufferToStream(VSBuffer.fromString('')) }; - }, - } as Partial as IRequestService); - instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); + const gitHubService = stubGitHubService(instantiationService, store, fetch); + instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), enabledPlugins: observableValue('test.enabledPlugins', new Map()), - } as Partial as IWorkspacePluginSettingsService); + }); instantiationService.stub(IWorkspaceTrustManagementService, { isWorkspaceTrusted: () => true, onDidChangeTrust: Event.None, - } as Partial as IWorkspaceTrustManagementService); - instantiationService.stub(IExtensionsWorkbenchService, { - getAutoUpdateValue: () => 'on', - } as Partial as IExtensionsWorkbenchService); + }); + instantiationService.stub(IExtensionsWorkbenchService, { getAutoUpdateValue: () => 'off' }); stubMarketplaceServices(instantiationService); - const service = store.add(instantiationService.createInstance(PluginMarketplaceService)); + return { service, gitHubService, storageService, ensureRepository, fileService, files, repoDir }; + } + + test('resolves each configured ref once and combines the first matching pinned definitions', async () => { + const catalogs = definitions.map((definition, index) => ({ + ...definition, + repo: `owner/catalog${index}`, + ref: index % 2 ? 'release/marketplace' : undefined, + })); + const requests: Request[] = []; + const { service, ensureRepository } = createService(async (input, init) => { + const request = new Request(input, init); + requests.push(request); + const catalog = catalogs.find(catalog => request.url.includes(`/${catalog.repo}/`))!; + if (request.url.includes('/commits/')) { + return new Response(commit); + } + const definitionIndex = definitions.findIndex(definition => request.url.endsWith(`/${commit}/${definition.path}`)); + if (definitionIndex < catalogs.indexOf(catalog)) { + return new Response('', { status: 404 }); + } + return new Response(JSON.stringify({ plugins: [{ name: catalog.repo, source: './plugin' }] })); + }, catalogs.map(catalog => `${catalog.repo}${catalog.ref ? `#${catalog.ref}` : ''}`)); const errors: string[] = []; const plugins = await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { - onMarketplaceError: (reference, error) => errors.push(`${reference.displayLabel}: ${error instanceof Error ? error.message : String(error)}`), + onMarketplaceError: (_reference, error) => errors.push(String(error)), + }); + assert.deepStrictEqual({ + plugins: plugins.map(plugin => [plugin.name, plugin.marketplaceType]), + requests: catalogs.map(catalog => requests.filter(request => request.url.includes(`/${catalog.repo}/`)).map(request => request.url)), + anonymous: requests.every(request => request.headers.get('authorization') === null && request.credentials === 'omit' && request.referrerPolicy === 'no-referrer'), + clones: ensureRepository.callCount, + errors, + }, { + plugins: catalogs.map(catalog => [catalog.repo, catalog.type]), + requests: catalogs.map((catalog, index) => [ + `https://api.github.com/repos/${catalog.repo}/commits/${encodeURIComponent(catalog.ref ?? 'main')}`, + ...definitions.slice(0, index + 1).map(definition => `https://raw.githubusercontent.com/${catalog.repo}/${commit}/${definition.path}`), + ]), + anonymous: true, + clones: 0, + errors: [], + }); + }); + + test('reuses persisted catalogs but resolves again after refresh and cache expiry', async () => { + const clock = sinon.useFakeTimers({ toFake: ['Date'] }); + let revision = 0; + const requests: Request[] = []; + const fetch: RequestFetch = async (input, init) => { + const request = new Request(input, init); + requests.push(request); + return request.url.includes('/commits/') + ? new Response(String(++revision).repeat(40), { headers: { ETag: `"ref${revision}"` } }) + : new Response(JSON.stringify({ plugins: [{ name: `plugin${revision}` }] })); + }; + const first = createService(fetch); + store.add(first.gitHubService.acquireAnonymousClient()); + const results = [await first.service.fetchMarketplacePlugins(CancellationToken.None)]; + results.push(await first.service.fetchMarketplacePlugins(CancellationToken.None)); + const restored = createService(fetch, undefined, first.storageService); + results.push(await restored.service.fetchMarketplacePlugins(CancellationToken.None)); + results.push(await first.service.fetchMarketplacePlugins(CancellationToken.None, undefined, { refresh: true })); + clock.tick(8 * 60 * 60 * 1000); + results.push(await first.service.fetchMarketplacePlugins(CancellationToken.None)); + assert.deepStrictEqual({ + plugins: results.map(plugins => plugins.map(plugin => plugin.name)), + revisions: revision, + rawPaths: requests.filter(request => request.url.startsWith('https://raw.')).map(request => new URL(request.url).pathname), + refValidators: requests.filter(request => request.url.includes('/commits/')).map(request => request.headers.get('if-none-match')), + }, { + plugins: [['plugin1'], ['plugin1'], ['plugin1'], ['plugin2'], ['plugin3']], + revisions: 3, + rawPaths: [1, 2, 3].map(revision => `/microsoft/vscode/${String(revision).repeat(40)}/marketplace.json`), + refValidators: [null, null, '"ref1"'], + }); + }); + + for (const priority of [undefined, 'background'] as const) { + test(`forwards ${priority ?? 'default'} priority for both ref resolution and definitions on refresh`, async () => { + const { service, gitHubService } = createService(async input => + new Response(String(input).includes('/commits/') ? commit : '{"plugins":[{"name":"plugin"}]}')); + const client = store.add(gitHubService.acquireAnonymousClient()); + sinon.stub(gitHubService, 'acquireAnonymousClient').returns(client); + const resolveRef = sinon.spy(client.content, 'resolveRef'); + const getRawFile = sinon.spy(client.content, 'getRawFile'); + + const plugins = await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { refresh: true, priority }); + + assert.deepStrictEqual({ + plugins: plugins.map(plugin => plugin.name), + ref: resolveRef.args.map(([, , , options]) => ({ priority: options?.priority, noCache: options?.noCache })), + definitions: getRawFile.args.map(([, , path, , options]) => ({ path, priority: options?.priority })), + }, { + plugins: ['plugin'], + ref: [{ priority, noCache: true }], + definitions: [{ path: 'marketplace.json', priority }], + }); + }); + } + + for (const phase of ['ref', 'definition']) { + test(`reports ${phase} HTTP failures without cloning`, () => runWithFakedTimers({}, async () => { + const { service, ensureRepository } = createService(async input => + phase === 'definition' && String(input).includes('/commits/') + ? new Response(commit) + : new Response('', { status: 500 })); + const errors: string[] = []; + const plugins = await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { + onMarketplaceError: (_reference, error) => errors.push(error instanceof Error ? error.message : String(error)), + }); + assert.deepStrictEqual({ plugins, clones: ensureRepository.callCount, errors }, { + plugins: [], + clones: 0, + errors: ['Unable to read marketplace \'microsoft/vscode\' (HTTP 500).'], + }); + })); + + test(`cancels ${phase} reads and releases the client without cloning`, async () => { + const started = new DeferredPromise(); + const response = new DeferredPromise(); + const { service, gitHubService, ensureRepository } = createService(async (input, init) => { + if (phase === 'definition' && String(input).includes('/commits/')) { + return new Response(commit); + } + const signal = init?.signal; + assert.ok(signal); + void started.complete(signal); + return response.p; + }); + const acquisitions = sinon.spy(gitHubService, 'acquireAnonymousClient'); + const cts = store.add(new CancellationTokenSource()); + const errors: unknown[] = []; + const pending = service.fetchMarketplacePlugins(cts.token, undefined, { + onMarketplaceError: (_reference, error) => errors.push(error), + }); + const signal = await started.p; + const dispose = sinon.spy(acquisitions.firstCall.returnValue, 'dispose'); + cts.cancel(); + await response.complete(new Response(phase === 'ref' ? commit : '{"plugins":[]}')); + assert.deepStrictEqual({ + plugins: await pending, + aborted: signal.aborted, + disposals: dispose.callCount, + clones: ensureRepository.callCount, + errors, + }, { plugins: [], aborted: true, disposals: 1, clones: 0, errors: [] }); }); + } + test('falls back to cloning a private repository and invalidates its public catalog on refresh', async () => { + let privateRepo = false; + const { service, ensureRepository, files, repoDir } = createService(async input => privateRepo + ? new Response('', { status: 404 }) + : new Response(String(input).includes('/commits/') ? commit : '{"plugins":[{"name":"public"}]}')); + files.set(joinPath(repoDir, 'marketplace.json').path, '{"plugins":[{"name":"private"}]}'); + const errors: unknown[] = []; + const options = { onMarketplaceError: (_reference: IMarketplaceReference, error: unknown) => errors.push(error) }; + const results = [await service.fetchMarketplacePlugins(CancellationToken.None, undefined, options)]; + privateRepo = true; + results.push(await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { ...options, refresh: true })); + results.push(await service.fetchMarketplacePlugins(CancellationToken.None, undefined, options)); assert.deepStrictEqual({ - queriedPinnedRevision: requestUrls.length > 0 && requestUrls.every(url => url.includes('/marketplace/')) && requestUrls.every(url => !url.includes('/main/')), - plugins, + plugins: results.map(plugins => plugins.map(plugin => plugin.name)), + cloneRefresh: ensureRepository.args.map(([, options]) => options.refreshIfOlderThanMs), errors, }, { - queriedPinnedRevision: true, - plugins: [], - errors: ['microsoft/vscode#marketplace: Unable to read marketplace \'microsoft/vscode#marketplace\' (HTTP 500).'], + plugins: [['public'], ['private'], ['private']], + cloneRefresh: [0, 8 * 60 * 60 * 1000], + errors: [], }); }); test('reports an unreadable cloned marketplace rather than a successful empty catalog', async () => { - const instantiationService = store.add(new TestInstantiationService()); - instantiationService.stub(IConfigurationService, new TestConfigurationService({ - [ChatConfiguration.PluginMarketplaces]: ['microsoft/vscode'], - [ChatConfiguration.PluginsEnabled]: true, + const { service, fileService } = createService(async input => new Response(String(input).includes('/commits/') ? commit : '', { + status: String(input).includes('/commits/') ? 200 : 404, })); - instantiationService.stub(IEnvironmentService, { cacheHome: URI.file('/cache') } as Partial as IEnvironmentService); - instantiationService.stub(IFileService, { - readFile: async () => { throw new Error('Permission denied'); }, - } as Partial as IFileService); - instantiationService.stub(IAgentPluginRepositoryService, { - agentPluginsHome: URI.file('/agent-plugins'), - ensureRepository: async () => URI.file('/cache/marketplace'), - } as Partial as IAgentPluginRepositoryService); - instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async () => ({ res: { headers: {}, statusCode: 404 }, stream: bufferToStream(VSBuffer.fromString('')) }), - } as Partial as IRequestService); - instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); - instantiationService.stub(IWorkspacePluginSettingsService, { - extraMarketplaces: observableValue('test.extraMarketplaces', []), - enabledPlugins: observableValue('test.enabledPlugins', new Map()), - } as Partial as IWorkspacePluginSettingsService); - instantiationService.stub(IWorkspaceTrustManagementService, { - isWorkspaceTrusted: () => true, - onDidChangeTrust: Event.None, - } as Partial as IWorkspaceTrustManagementService); - instantiationService.stub(IExtensionsWorkbenchService, { getAutoUpdateValue: () => 'on' } as Partial as IExtensionsWorkbenchService); - stubMarketplaceServices(instantiationService); - const service = store.add(instantiationService.createInstance(PluginMarketplaceService)); + sinon.stub(fileService, 'readFile').rejects(new Error('Permission denied')); const errors: string[] = []; const plugins = await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { onMarketplaceError: (_reference, error) => errors.push(error instanceof Error ? error.message : String(error)), @@ -684,44 +843,45 @@ suite('PluginMarketplaceService - GitHub marketplace refs', () => { }); test('a cancelled fetch does not clear the last fetched plugins', async () => { - const instantiationService = store.add(new TestInstantiationService()); - instantiationService.stub(IConfigurationService, new TestConfigurationService({ - [ChatConfiguration.PluginMarketplaces]: ['microsoft/vscode'], - [ChatConfiguration.PluginsEnabled]: true, - })); - instantiationService.stub(IEnvironmentService, { cacheHome: URI.file('/cache') } as Partial as IEnvironmentService); - instantiationService.stub(IFileService, {} as unknown as IFileService); - instantiationService.stub(IAgentPluginRepositoryService, { - agentPluginsHome: URI.file('/agent-plugins'), - ensureRepository: async () => URI.file('/agent-plugins/github.com/microsoft/vscode'), - } as Partial as IAgentPluginRepositoryService); - instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async () => ({ res: { headers: {}, statusCode: 404 }, stream: bufferToStream(VSBuffer.fromString('')) }), - } as Partial as IRequestService); - instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); - instantiationService.stub(IWorkspacePluginSettingsService, { - extraMarketplaces: observableValue('test.extraMarketplaces', []), - enabledPlugins: observableValue('test.enabledPlugins', new Map()), - } as Partial as IWorkspacePluginSettingsService); - instantiationService.stub(IWorkspaceTrustManagementService, { - isWorkspaceTrusted: () => true, - onDidChangeTrust: Event.None, - } as Partial as IWorkspaceTrustManagementService); - instantiationService.stub(IExtensionsWorkbenchService, { - getAutoUpdateValue: () => 'on', - } as Partial as IExtensionsWorkbenchService); - stubMarketplaceServices(instantiationService); - - const service = store.add(instantiationService.createInstance(PluginMarketplaceService)); + const { service, gitHubService, ensureRepository } = createService(async input => + new Response(String(input).includes('/commits/') ? commit : '{"plugins":[{"name":"cached"}]}')); + await service.fetchMarketplacePlugins(CancellationToken.None); const seeded = service.lastFetchedPlugins.get(); - + const acquisitions = sinon.spy(gitHubService, 'acquireAnonymousClient'); const cts = store.add(new CancellationTokenSource()); cts.cancel(); - await service.fetchMarketplacePlugins(cts.token); - - assert.deepStrictEqual(service.lastFetchedPlugins.get(), seeded); - }); + await service.fetchMarketplacePlugins(cts.token, undefined, { refresh: true }); + assert.deepStrictEqual({ + plugins: service.lastFetchedPlugins.get(), + acquisitions: acquisitions.callCount, + clones: ensureRepository.callCount, + }, { plugins: seeded, acquisitions: 0, clones: 0 }); + }); + + for (const size of [1024 * 1024, 1024 * 1024 + 1]) { + test(`handles a ${size}-byte definition without a lower-priority or clone fallback`, async () => { + const json = '{"plugins":[{"name":"large"}]}'; + const text = json + ' '.repeat(size - json.length); + const paths: string[] = []; + const { service, ensureRepository } = createService(async input => { + if (String(input).includes('/commits/')) { + return new Response(commit); + } + paths.push(new URL(String(input)).pathname); + return new Response(text); + }); + const errors: string[] = []; + const plugins = await service.fetchMarketplacePlugins(CancellationToken.None, undefined, { + onMarketplaceError: (_reference, error) => errors.push(error instanceof Error ? error.message : String(error)), + }); + assert.deepStrictEqual({ plugins: plugins.map(plugin => plugin.name), paths, clones: ensureRepository.callCount, errors }, { + plugins: size === 1024 * 1024 ? ['large'] : [], + paths: [`/microsoft/vscode/${commit}/marketplace.json`], + clones: 0, + errors: size === 1024 * 1024 ? [] : ['Unable to read marketplace \'microsoft/vscode\': the GitHub response exceeds the size limit.'], + }); + }); + } }); suite('PluginMarketplaceService - Agent Plugin direct install probes', () => { @@ -757,7 +917,7 @@ suite('PluginMarketplaceService - Agent Plugin direct install probes', () => { instantiationService.stub(IFileService, fileService as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, { agentPluginsHome: URI.file('/agent-plugins') } as unknown as IAgentPluginRepositoryService); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {} as unknown as IRequestService); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -810,6 +970,20 @@ suite('PluginMarketplaceService - Agent Plugin direct install probes', () => { assert.strictEqual(result?.name, 'compatible-plugin'); }); + for (const [source, descriptor] of [ + ['owner/compatible#feature/beta', { kind: PluginSourceKind.GitHub, repo: 'owner/compatible', ref: 'feature/beta' }], + ['https://example.com/compatible.git#release/v1', { kind: PluginSourceKind.GitUrl, url: 'https://example.com/compatible.git', ref: 'release/v1' }], + ] as const) { + test(`retains the revision in a standalone plugin descriptor: ${source}`, async () => { + const fileService = new ProbeFileService(); + const repoDir = URI.file('/repos/compatible'); + seedCompatibleManifest(fileService, repoDir); + const service = createService(fileService); + const plugin = await service.readSinglePluginManifest(repoDir, parseMarketplaceReference(source)!); + assert.deepStrictEqual(plugin?.sourceDescriptor, descriptor); + }); + } + test('recognizes a local directory with a compatible schema revision', async () => { const fileService = new ProbeFileService(); const repoDir = URI.file('/plugins/compatible'); @@ -839,7 +1013,7 @@ suite('PluginMarketplaceService - getMarketplacePluginMetadata', () => { instantiationService.stub(IFileService, {} as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, { agentPluginsHome: URI.file('/agent-plugins') } as unknown as IAgentPluginRepositoryService); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {} as unknown as IRequestService); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -947,7 +1121,7 @@ suite('PluginMarketplaceService - installed plugins lifecycle', () => { ...options?.pluginRepositoryService, } as IAgentPluginRepositoryService); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {} as unknown as IRequestService); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -1568,7 +1742,7 @@ suite('PluginMarketplaceService - hydration after restart', () => { instantiationService.stub(IFileService, fileService as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, createPluginRepositoryStub(cacheRoot)); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {}); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -1602,19 +1776,17 @@ suite('PluginMarketplaceService - hydration after restart', () => { instantiationService.stub(IFileService, new TestFileService() as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, createPluginRepositoryStub()); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async () => { - requests++; - return { - res: { headers: {}, statusCode: 200 }, - stream: bufferToStream(VSBuffer.fromString(JSON.stringify({ - plugins: [ - { name: 'unsafe', source: { source: 'github', repo: 'owner/..' } }, - { name: 'safe', source: { source: 'github', repo: 'owner/plugin' } }, - ], - }))), - }; - }, + stubGitHubService(instantiationService, store, async input => { + if (String(input).includes('/commits/')) { + return new Response('a'.repeat(40)); + } + requests++; + return new Response(JSON.stringify({ + plugins: [ + { name: 'unsafe', source: { source: 'github', repo: 'owner/..' } }, + { name: 'safe', source: { source: 'github', repo: 'owner/plugin' } }, + ], + })); }); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { @@ -1666,7 +1838,7 @@ suite('PluginMarketplaceService - hydration after restart', () => { instantiationService.stub(IFileService, fileService as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, createPluginRepositoryStub()); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {} as unknown as IRequestService); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -1739,9 +1911,7 @@ suite('PluginMarketplaceService - hydration after restart', () => { ensureRepository: async () => marketplaceUri, } as unknown as IAgentPluginRepositoryService); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, { - request: async () => ({ res: { headers: {}, statusCode: 404 }, stream: bufferToStream(VSBuffer.fromString('')) }), - } as Partial as IRequestService); + stubGitHubService(instantiationService, store, async () => new Response('', { status: 404 })); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), @@ -1801,7 +1971,7 @@ suite('PluginMarketplaceService - hydration after restart', () => { instantiationService.stub(IFileService, fileService as unknown as IFileService); instantiationService.stub(IAgentPluginRepositoryService, createPluginRepositoryStub()); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IRequestService, {} as unknown as IRequestService); + instantiationService.stub(IWorkbenchGitHubService, {}); instantiationService.stub(IStorageService, storageService); instantiationService.stub(IWorkspacePluginSettingsService, { extraMarketplaces: observableValue('test.extraMarketplaces', []), diff --git a/src/vs/workbench/contrib/chat/test/common/promptSyntax/service/promptsService.test.ts b/src/vs/workbench/contrib/chat/test/common/promptSyntax/service/promptsService.test.ts index 92d585903d73..4103a8e107af 100644 --- a/src/vs/workbench/contrib/chat/test/common/promptSyntax/service/promptsService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/promptSyntax/service/promptsService.test.ts @@ -5920,6 +5920,38 @@ suite('PromptsService', () => { assert.deepStrictEqual(after.hooks[HookType.PreToolUse], [{ command: 'echo after', sourceUri: URI.file('/plugins/test-plugin/hooks.json') }]); }); + test('refreshes hook inventory when a hooks-only plugin finishes loading', async () => { + testConfigService.setUserConfiguration(PromptsConfig.USE_CHAT_HOOKS, true); + testConfigService.setUserConfiguration(PromptsConfig.HOOKS_LOCATION_KEY, {}); + await timeout(0); + + assert.deepStrictEqual(await service.listPromptFiles(PromptsType.hook, CancellationToken.None), []); + + const { plugin, hooks } = createTestPlugin('/plugins/hooks-only', []); + const pluginDiscovered = Event.toPromise(service.onDidChangeHooks); + testPluginsObservable.set([plugin], undefined); + await pluginDiscovered; + await service.listPromptFiles(PromptsType.hook, CancellationToken.None); + + const hookUri = URI.file('/plugins/hooks-only/hooks.json'); + const hooksChanged = Event.toPromise(service.onDidChangeHooks); + hooks.set([ + { type: HookType.SessionStart, originalId: 'sessionStart', hooks: [{ command: 'echo start' }], uri: hookUri }, + { type: HookType.UserPromptSubmit, originalId: 'userPromptSubmitted', hooks: [{ command: 'echo prompt' }], uri: hookUri }, + ], undefined); + await hooksChanged; + + const files = await service.listPromptFiles(PromptsType.hook, CancellationToken.None); + assert.deepStrictEqual(files.map(file => ({ + name: file.name, + storage: file.storage, + pluginUri: file.pluginUri, + })), [ + { name: 'hooks-only:sessionstart', storage: PromptsStorage.plugin, pluginUri: plugin.uri }, + { name: 'hooks-only:userpromptsubmitted', storage: PromptsStorage.plugin, pluginUri: plugin.uri }, + ]); + }); + test('returns undefined when workspace is untrusted', async function () { workspaceContextService.setWorkspace(testWorkspace(URI.file('/test-workspace'))); testConfigService.setUserConfiguration(PromptsConfig.USE_CHAT_HOOKS, true); diff --git a/src/vs/workbench/contrib/chat/test/common/tools/builtinTools/chatUrlFetchingConfirmation.test.ts b/src/vs/workbench/contrib/chat/test/common/tools/builtinTools/chatUrlFetchingConfirmation.test.ts new file mode 100644 index 000000000000..bdd166e7d3e1 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/tools/builtinTools/chatUrlFetchingConfirmation.test.ts @@ -0,0 +1,222 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IInputOptions, IQuickInputService } from '../../../../../../../platform/quickinput/common/quickInput.js'; +import { IUrlApprovalSettings } from '../../../../../../../platform/url/common/urlApprovalPatterns.js'; +import { IPreferencesService } from '../../../../../../services/preferences/common/preferences.js'; +import { ChatConfiguration } from '../../../../common/constants.js'; +import { ChatUrlFetchingConfirmationContribution } from '../../../../common/tools/builtinTools/chatUrlFetchingConfirmation.js'; + +suite('ChatUrlFetchingConfirmationContribution', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + test('toggles request approval for retained URL patterns without overwriting newer approvals', async () => { + const setting = ChatConfiguration.AutoApprovedUrls; + const configurationService = new TestConfigurationService({ + [setting]: { + 'first.example': { approveRequest: true, approveResponse: false }, + 'second.example': true, + } + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + sinon.stub(configurationService, 'updateValue').callsFake((key, value) => configurationService.setUserConfiguration(key, value)); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IQuickInputService, {}); + instantiationService.stub(IPreferencesService, {}); + const contribution = instantiationService.createInstance(ChatUrlFetchingConfirmationContribution, () => undefined); + const [first, second] = contribution.getManageActions(); + await first.onDidChangeChecked!(false); + await second.onDidChangeChecked!(false); + const unchecked = configurationService.getValue(setting); + await configurationService.setUserConfiguration(setting, { 'new.example': { approveResponse: true } }); + await first.onDidChangeChecked!(true); + const restored = configurationService.getValue(setting); + await second.onDidTriggerItemButton!(second.buttons![0]); + const afterDelete = configurationService.getValue(setting); + await first.onDidTriggerItemButton!(first.buttons![0]); + + assert.deepStrictEqual({ unchecked, restored, afterDelete, approvals: configurationService.getValue(setting) }, { + unchecked: { 'second.example': { approveRequest: false, approveResponse: true } }, + restored: { + 'new.example': { approveResponse: true }, + 'first.example': { approveRequest: true, approveResponse: false }, + }, + afterDelete: restored, + approvals: { 'new.example': { approveResponse: true } }, + }); + }); + + test('overrides default URL patterns instead of copying or deleting them', async () => { + const setting = ChatConfiguration.AutoApprovedUrls; + const defaultValue = { 'default.example': true }; + let userValue: Record = { 'user.example': true }; + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + sinon.stub(configurationService, 'getValue').callsFake(() => ({ ...defaultValue, ...userValue })); + sinon.stub(configurationService, 'inspect').callsFake(() => ({ value: { ...defaultValue, ...userValue }, defaultValue, userValue })); + sinon.stub(configurationService, 'updateValue').callsFake(async (_key, value) => { userValue = value as Record; }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IQuickInputService, {}); + instantiationService.stub(IPreferencesService, {}); + const contribution = instantiationService.createInstance(ChatUrlFetchingConfirmationContribution, () => undefined); + const defaultItem = () => contribution.getManageActions().find(item => item.label === 'default.example')!; + const states: [boolean | 'mixed' | undefined, Record][] = [[defaultItem().checked, userValue]]; + await defaultItem().onDidChangeChecked!(false); + states.push([defaultItem().checked, userValue]); + await defaultItem().onDidChangeChecked!(true); + states.push([defaultItem().checked, userValue]); + await defaultItem().onDidTriggerItemButton!(defaultItem().buttons![0]); + states.push([defaultItem().checked, userValue]); + + assert.deepStrictEqual({ setting, states }, { + setting, + states: [ + [true, { 'user.example': true }], + [false, { 'user.example': true, 'default.example': { approveRequest: false, approveResponse: true } }], + [true, { 'user.example': true }], + [false, { 'user.example': true, 'default.example': false }], + ], + }); + }); + + for (const target of [ConfigurationTarget.WORKSPACE, ConfigurationTarget.WORKSPACE_FOLDER]) { + test(`edits URL patterns at configuration target ${target} using its latest value`, async () => { + const userValue = { 'user.example': true }; + let workspaceValue: Record = { 'scoped.example': true }; + let workspaceFolderValue: Record | undefined = target === ConfigurationTarget.WORKSPACE_FOLDER + ? { 'scoped.example': { approveRequest: true, approveResponse: false } } + : undefined; + const writes: { target: ConfigurationTarget | undefined; approvals: Record }[] = []; + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + sinon.stub(configurationService, 'updateValue').callsFake(async (_key: string, value: unknown, writeTarget?: unknown) => { + const approvals = value as Record; + writes.push({ target: writeTarget as ConfigurationTarget | undefined, approvals }); + if (writeTarget === ConfigurationTarget.WORKSPACE_FOLDER) { + workspaceFolderValue = approvals; + } else if (writeTarget === ConfigurationTarget.WORKSPACE) { + workspaceValue = approvals; + } + }); + sinon.stub(configurationService, 'getValue').callsFake(() => ({ ...userValue, ...workspaceValue, ...workspaceFolderValue })); + sinon.stub(configurationService, 'inspect').callsFake(() => ({ userValue, workspaceValue, workspaceFolderValue })); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IQuickInputService, {}); + instantiationService.stub(IPreferencesService, {}); + const contribution = instantiationService.createInstance(ChatUrlFetchingConfirmationContribution, () => undefined); + const item = contribution.getManageActions().find(item => item.label === 'scoped.example')!; + if (workspaceFolderValue) { + workspaceFolderValue = { ...workspaceFolderValue, 'new.example': true }; + } else { + workspaceValue = { ...workspaceValue, 'new.example': true }; + } + await item.onDidChangeChecked!(false); + const unchecked = contribution.getManageActions().find(item => item.label === 'scoped.example')!.checked; + await item.onDidTriggerItemButton!(item.buttons![0]); + + assert.deepStrictEqual({ unchecked, writes, userValue }, { + unchecked: false, + writes: [ + { + target, approvals: target === ConfigurationTarget.WORKSPACE + ? { 'scoped.example': { approveRequest: false, approveResponse: true }, 'new.example': true } + : { 'scoped.example': false, 'new.example': true } + }, + { target, approvals: { 'new.example': true } }, + ], + userValue: { 'user.example': true }, + }); + }); + } + + test('adding an existing default URL pattern preserves response approval', async () => { + const defaultValue = { 'default.example': true, 'response.example': { approveResponse: true } }; + let userValue: Record = {}; + const writes: { value: Record; target: ConfigurationTarget | undefined }[] = []; + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + sinon.stub(configurationService, 'updateValue').callsFake(async (_key: string, value: unknown, target?: unknown) => { + userValue = value as Record; + writes.push({ value: userValue, target: target as ConfigurationTarget | undefined }); + }); + sinon.stub(configurationService, 'getValue').callsFake(() => ({ ...defaultValue, ...userValue })); + sinon.stub(configurationService, 'inspect').callsFake(() => ({ defaultValue, userValue })); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + const inputs = Object.keys(defaultValue); + instantiationService.stub(IQuickInputService, { input: async () => inputs.shift() }); + instantiationService.stub(IPreferencesService, {}); + const contribution = instantiationService.createInstance(ChatUrlFetchingConfirmationContribution, () => undefined); + const addItem = contribution.getManageActions().find(item => item.label === 'Add URL Pattern...')!; + await addItem.onDidOpen!(); + await addItem.onDidOpen!(); + + assert.deepStrictEqual(writes, [ + { value: { 'default.example': { approveRequest: true, approveResponse: true } }, target: ConfigurationTarget.USER }, + { value: { 'default.example': { approveRequest: true, approveResponse: true }, 'response.example': { approveRequest: true, approveResponse: true } }, target: ConfigurationTarget.USER }, + ]); + }); + + test('adds request-only URL patterns while preserving existing response approvals', async () => { + const setting = ChatConfiguration.AutoApprovedUrls; + const configurationService = new TestConfigurationService({ + [setting]: { + 'existing.example': { approveRequest: false, approveResponse: true }, + 'boolean.example': true, + 'blocked.example': false, + 'unrelated.example': { approveRequest: true, approveResponse: false }, + } + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const update = sinon.stub(configurationService, 'updateValue').callsFake((key, value) => configurationService.setUserConfiguration(key, value)); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + const inputs = [' example.com ', 'existing.example', 'boolean.example', 'blocked.example', undefined, ' ']; + let inputOptions: IInputOptions | undefined; + instantiationService.stub(IQuickInputService, { + input: async options => { + inputOptions = options; + return inputs.shift(); + } + }); + instantiationService.stub(IPreferencesService, {}); + const contribution = instantiationService.createInstance(ChatUrlFetchingConfirmationContribution, () => undefined); + const items = contribution.getManageActions(); + const addItem = items.find(item => item.label === 'Add URL Pattern...')!; + for (let index = 0; index < 6; index++) { + await addItem.onDidOpen!(); + } + + assert.deepStrictEqual({ + actions: items.slice(-2).map(item => [item.label, item.pickable]), + approvals: configurationService.inspect(setting).userValue, + writeCount: update.callCount, + userSettingsOnly: update.args.every(arguments_ => arguments_.at(-1) === ConfigurationTarget.USER), + validation: await Promise.all(['', ' ', 'example.com'].map(value => inputOptions?.validateInput?.(value))), + }, { + actions: [['Add URL Pattern...', false], ['More Options...', false]], + approvals: { + 'existing.example': { approveRequest: true, approveResponse: true }, + 'boolean.example': { approveRequest: true, approveResponse: true }, + 'blocked.example': { approveRequest: true, approveResponse: false }, + 'unrelated.example': { approveRequest: true, approveResponse: false }, + 'example.com': { approveRequest: true, approveResponse: false }, + }, + writeCount: 4, + userSettingsOnly: true, + validation: ['Enter a domain or URL pattern.', 'Enter a domain or URL pattern.', undefined], + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/tools/toolInvocationSummary.test.ts b/src/vs/workbench/contrib/chat/test/common/tools/toolInvocationSummary.test.ts index 1e706306157f..991d13bc5518 100644 --- a/src/vs/workbench/contrib/chat/test/common/tools/toolInvocationSummary.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/tools/toolInvocationSummary.test.ts @@ -201,4 +201,17 @@ suite('Tool invocation summaries', () => { openEndedView: { kind: 'read', resources: [{ uri: URI.file('/file.ts') }] }, }); }); + + test('a view call is a read or a listing when the host reports what its path named', () => { + const resources = [{ uri: URI.file('/workspace/src') }]; + assert.deepStrictEqual({ + file: getToolInvocationSummaryFromInput('view', { path: '/workspace/src' }, undefined, 'file'), + directory: getToolInvocationSummaryFromInput('view', { path: '/workspace/src' }, undefined, 'directory'), + relativeFile: getToolInvocationSummaryFromInput('view', { path: 'src' }, undefined, 'file'), + }, { + file: { kind: 'read', resources }, + directory: { kind: 'list', resources }, + relativeFile: undefined, + }); + }); }); diff --git a/src/vs/workbench/contrib/chat/test/common/widget/codeFence.test.ts b/src/vs/workbench/contrib/chat/test/common/widget/codeFence.test.ts new file mode 100644 index 000000000000..c950f0dc8a7f --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/widget/codeFence.test.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { getClosedCodeFenceInfo } from '../../../common/widget/codeFence.js'; + +suite('getClosedCodeFenceInfo', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('returns the info string of a closed fence, and nothing for a fence that is still open', () => { + assert.deepStrictEqual([ + '```vscode-ui\nA\n```', + '~~~~ vscode-ui v1 \r\nA\r\n~~~~~\n\n', + ' ```\ncode\n ```', + '```vscode-ui\nA', + '```vscode-ui\nA\n``', + '````vscode-ui\nA\n```', + '```vscode-ui\nA\n~~~', + '```vscode-ui\nA\n ```', + '```vscode-ui\nA\n``` trailing', + '```vscode-ui```', + '', + undefined, + ].map(raw => getClosedCodeFenceInfo(raw)), [ + 'vscode-ui', + 'vscode-ui v1', + '', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + ]); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/electron-browser/actions/chatAppWindowScreenshotHint.test.ts b/src/vs/workbench/contrib/chat/test/electron-browser/actions/chatAppWindowScreenshotHint.test.ts new file mode 100644 index 000000000000..c305f1559e9e --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/electron-browser/actions/chatAppWindowScreenshotHint.test.ts @@ -0,0 +1,274 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../../base/browser/dom.js'; +import { MarkdownRenderOptions, renderMarkdown } from '../../../../../../base/browser/markdownRenderer.js'; +import { timeout } from '../../../../../../base/common/async.js'; +import { Emitter } from '../../../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../../../base/common/keyCodes.js'; +import { DisposableStore } from '../../../../../../base/common/lifecycle.js'; +import { OperatingSystem } from '../../../../../../base/common/platform.js'; +import { IMarkdownString } from '../../../../../../base/common/htmlContent.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { mock } 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 { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { ResolvedKeybindingItem } from '../../../../../../platform/keybinding/common/resolvedKeybindingItem.js'; +import { createUSLayoutResolvedKeybinding } from '../../../../../../platform/keybinding/test/common/keybindingsTestUtils.js'; +import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IMarkdownRendererService } from '../../../../../../platform/markdown/browser/markdownRenderer.js'; +import { IStorageService, StorageScope } from '../../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; +import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; +import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; +import { IAppWindowScreenshotService } from '../../../../screenshotTool/electron-browser/appWindowScreenshot.js'; +import { ChatImageAttachGesture, IChatUserImageAttachmentEvent, IChatUserImageAttachmentService } from '../../../browser/attachments/chatUserImageAttachments.js'; +import { ChatInputNoticeHost, ChatInputNoticeLane } from '../../../browser/widget/input/chatInputNoticeHost.js'; +import { ChatConfiguration } from '../../../common/constants.js'; +import { AppWindowScreenshotHint } from '../../../electron-browser/actions/chatAppWindowScreenshotHint.js'; + +suite('AppWindowScreenshotHint', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const COMMAND = { id: 'test.attachAppWindowScreenshot', title: 'Attach Screenshot of App Window' }; + const INPUT = URI.parse('vscode-chat-input:input-1'); + const KEYBINDING = createUSLayoutResolvedKeybinding(KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.KeyS, OperatingSystem.Linux)!; + const KEY = KEYBINDING.getLabel(); + + function createHint(options: { readonly enabled?: boolean; readonly keybinding?: 'none' | 'inChat' | 'systemWide'; readonly storageService?: TestStorageService } = {}) { + const store = disposables.add(new DisposableStore()); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, new TestConfigurationService({ [ChatConfiguration.AppWindowScreenshotsEnabled]: options.enabled ?? true })); + const storageService = options.storageService ?? store.add(new TestStorageService()); + instantiationService.stub(IStorageService, storageService); + instantiationService.stub(IWorkbenchEnvironmentService, { isSessionsWindow: false }); + instantiationService.stub(IContextKeyService, new MockContextKeyService()); + + const onDidAttachImages = store.add(new Emitter()); + instantiationService.stub(IChatUserImageAttachmentService, { onDidAttachImages: onDidAttachImages.event }); + + let hasCaptured = false; + const onDidChangeHasCaptured = store.add(new Emitter()); + instantiationService.stub(IAppWindowScreenshotService, { + get hasCaptured() { return hasCaptured; }, + onDidChangeHasCaptured: onDidChangeHasCaptured.event, + }); + + instantiationService.stub(IKeybindingService, { + lookupKeybinding: () => options.keybinding === 'none' ? undefined : KEYBINDING, + getKeybindings: () => options.keybinding === 'systemWide' ? [new ResolvedKeybindingItem(KEYBINDING, COMMAND.id, undefined, undefined, false, null, false, true)] : [], + }); + + const executed: string[] = []; + instantiationService.stub(IMarkdownRendererService, { render: (markdown: IMarkdownString, options?: MarkdownRenderOptions) => renderMarkdown(markdown, options) }); + + const events: string[] = []; + instantiationService.stub(ITelemetryService, new class extends mock() { + override publicLog2(eventName: string, data?: unknown): void { + const { action, gesture, copy, imageCount } = data as { action: string; gesture: string; copy: string; imageCount: number }; + events.push(`${eventName} ${action} ${gesture} ${copy} ${imageCount}`); + } + }); + + const noticeHost = store.add(new ChatInputNoticeHost(() => { })); + const container = $('.chat-attachment-hint-container'); + const attachmentIds: string[] = []; + const onDidChangeAttachments = store.add(new Emitter()); + const onDidChangeDraft = store.add(new Emitter()); + store.add(instantiationService.createInstance(AppWindowScreenshotHint, { + inputUri: INPUT, + noticeHost, + container, + getAttachmentIds: () => attachmentIds, + onDidChangeAttachments: onDidChangeAttachments.event, + onDidChangeDraft: onDidChangeDraft.event, + canAttachScreenshots: () => true, + }, { ...COMMAND, run: () => executed.push(COMMAND.id) })); + + return { + events, + executed, + noticeHost, + storageService, + text: () => container.textContent ?? '', + clickLink: () => container.querySelector('a')?.click(), + attach(id: string, gesture: ChatImageAttachGesture = 'paste') { + attachmentIds.push(id); + onDidAttachImages.fire({ inputUri: INPUT, attachmentIds: [id], gesture }); + }, + attachToOtherInput(id: string) { + onDidAttachImages.fire({ inputUri: URI.parse('vscode-chat-input:input-2'), attachmentIds: [id], gesture: 'paste' }); + }, + remove(id: string) { + attachmentIds.splice(attachmentIds.indexOf(id), 1); + onDidChangeAttachments.fire(); + }, + send() { + attachmentIds.length = 0; + onDidChangeDraft.fire(); + }, + capture() { + hasCaptured = true; + onDidChangeHasCaptured.fire(); + }, + }; + } + + /** Lets the hint claim its one showing, which it does asynchronously, across windows. */ + const claimed = () => timeout(0); + + const IN_CHAT = `Showing the agent your app? Next time, switch from your app to chat and press ${KEY} to attach a screenshot of its window.`; + + test('shows once, above its own input, after other notices and until its images go', async () => { + const hint = createHint(); + const text: Record = {}; + + hint.attachToOtherInput('other'); + text.otherInput = hint.text(); + const notification = hint.noticeHost.occupy(ChatInputNoticeLane.Notification); + hint.attach('image1'); + text.behindNotification = hint.text(); + notification.dispose(); + await claimed(); + text.afterNotification = hint.text(); + const onboarding = hint.noticeHost.occupy(ChatInputNoticeLane.Onboarding); + text.behindOnboarding = hint.text(); + onboarding.dispose(); + text.afterOnboarding = hint.text(); + hint.remove('image1'); + text.imageRemoved = hint.text(); + hint.attach('image2'); + await claimed(); + text.nextPaste = hint.text(); + + assert.deepStrictEqual({ + text, + events: hint.events, + shownStored: !!hint.storageService.get('chat.appWindowScreenshots.hintShown', StorageScope.APPLICATION_SHARED), + }, { + text: { + otherInput: '', + behindNotification: '', + afterNotification: IN_CHAT, + behindOnboarding: '', + afterOnboarding: IN_CHAT, + imageRemoved: '', + nextPaste: '', + }, + events: [ + 'screenshotTool.appWindowHint opportunity paste none 1', + 'screenshotTool.appWindowHint shown paste inApp 1', + 'screenshotTool.appWindowHint expired paste inApp 1', + ], + shownStored: true, + }); + }); + + test('does nothing with the feature off, and shows later when it went away unseen', async () => { + const off = createHint({ enabled: false }); + off.attach('image1'); + + const hint = createHint(); + const notification = hint.noticeHost.occupy(ChatInputNoticeLane.Notification); + hint.attach('image1'); + hint.send(); + notification.dispose(); + const afterSend = hint.text(); + hint.attach('image2', 'drop'); + await claimed(); + const afterDrop = hint.text(); + hint.capture(); + + assert.deepStrictEqual({ + off: { text: off.text(), events: off.events }, + afterSend, + afterDrop, + afterCapture: hint.text(), + events: hint.events, + }, { + off: { text: '', events: [] }, + afterSend: '', + afterDrop: IN_CHAT, + afterCapture: '', + events: [ + 'screenshotTool.appWindowHint opportunity paste none 1', + 'screenshotTool.appWindowHint shown drop inApp 1', + 'screenshotTool.appWindowHint used drop inApp 1', + ], + }); + }); + + test('keeps its one showing when the draft goes while it claims it', async () => { + let onWillSwap: (() => void) | undefined; + const storageService = disposables.add(new class extends TestStorageService { + override compareAndSwapApplicationSharedValue(key: string, expectedValue: string | undefined, newValue: string) { + onWillSwap?.(); + return super.compareAndSwapApplicationSharedValue(key, expectedValue, newValue); + } + }); + const hint = createHint({ storageService }); + hint.attach('image1'); + hint.send(); + await claimed(); + onWillSwap = () => { + onWillSwap = undefined; + hint.send(); + }; + hint.attach('image2'); + await claimed(); + const otherWindow = createHint({ storageService }); + otherWindow.attach('image3'); + await claimed(); + + assert.strictEqual(otherWindow.text(), IN_CHAT); + }); + + test('shows in only one window when two get images at once', async () => { + const storageService = disposables.add(new TestStorageService()); + const first = createHint({ storageService }); + const second = createHint({ storageService }); + first.attach('image1'); + second.attach('image1'); + await claimed(); + + assert.deepStrictEqual([first.text(), second.text()], [IN_CHAT, '']); + }); + + test('names the keybinding, where it works, or the command when there is none, and links it to the command', async () => { + const shown = []; + for (const keybinding of ['none', 'inChat', 'systemWide'] as const) { + const hint = createHint({ keybinding }); + hint.attach('image1'); + await claimed(); + const text = hint.text(); + hint.clickLink(); + shown.push({ text, events: hint.events.slice(1), executed: hint.executed }); + } + + assert.deepStrictEqual(shown, [ + { + text: `Showing the agent your app? Next time, switch from your app to chat and run ${COMMAND.title} from the Command Palette to attach a screenshot of its window.`, + events: ['screenshotTool.appWindowHint shown paste palette 1', 'screenshotTool.appWindowHint clicked paste palette 1'], + executed: [COMMAND.id], + }, + { + text: IN_CHAT, + events: ['screenshotTool.appWindowHint shown paste inApp 1', 'screenshotTool.appWindowHint clicked paste inApp 1'], + executed: [COMMAND.id], + }, + { + text: `Showing the agent your app? Next time, press ${KEY} while your app is in front to attach a screenshot of its window.`, + events: ['screenshotTool.appWindowHint shown paste systemWide 1', 'screenshotTool.appWindowHint clicked paste systemWide 1'], + executed: [COMMAND.id], + }, + ]); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/electron-browser/toggleRemoteConnectionsActionViewItem.test.ts b/src/vs/workbench/contrib/chat/test/electron-browser/toggleRemoteConnectionsActionViewItem.test.ts index 54c04b672934..b52b7e74f258 100644 --- a/src/vs/workbench/contrib/chat/test/electron-browser/toggleRemoteConnectionsActionViewItem.test.ts +++ b/src/vs/workbench/contrib/chat/test/electron-browser/toggleRemoteConnectionsActionViewItem.test.ts @@ -28,7 +28,9 @@ import { ILogService, NullLogService } from '../../../../../platform/log/common/ import { INotificationService } from '../../../../../platform/notification/common/notification.js'; import { TestNotificationService } from '../../../../../platform/notification/test/common/testNotificationService.js'; import { TestConfigurationService as TestBackendConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; -import { AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { AgentHostRemoteConnectionsBackend, AgentHostRemoteConnectionsSettingId, GitHubEnvironmentSharingError, GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlSharingService } from '../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { getConnectionDiagnosticError } from '../../../../../platform/agentHost/common/connectionDiagnostics.js'; +import { FileSystemProviderErrorCode } from '../../../../../platform/files/common/files.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; @@ -36,7 +38,7 @@ import { IProductService } from '../../../../../platform/product/common/productS import { IInputOptions, IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.js'; import { CONFIGURATION_KEY_HOST_NAME, INACTIVE_TUNNEL_MODE, IRemoteTunnelService, type ActiveTunnelMode, type TunnelMode, type TunnelStatus } from '../../../../../platform/remoteTunnel/common/remoteTunnel.js'; import { RemoteConnectionsActionViewItem, ToggleRemoteConnectionsActionViewItem } from '../../electron-browser/toggleRemoteConnectionsActionViewItem.js'; -import { getRemoteTunnelAccessState } from '../../electron-browser/remoteConnectionsSharing.js'; +import { getRemoteTunnelAccessState, RemoteConnectionsSharing, RemoteConnectionsState } from '../../electron-browser/remoteConnectionsSharing.js'; import { executeToggleRemoteConnections, TUNNEL_HOST_SHARING_KEY, TunnelHostContribution } from '../../electron-browser/tunnelHost.contribution.js'; import { IRemoteTunnelStartOptions, promptToRenameRemoteTunnel, RemoteTunnelCommandIds } from '../../../remoteTunnel/electron-browser/remoteTunnel.contribution.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; @@ -277,9 +279,9 @@ suite('RemoteConnectionsActionViewItem', () => { const { openMenu, menuItems } = fixture(); openMenu(); assert.deepStrictEqual(menuItems(), [ - { label: 'Off', detail: 'Only accessible from this machine.', badge: undefined, role: 'menuitemcheckbox' }, - { label: 'GitHub Environments', detail: 'Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot.', badge: 'Preview', role: 'menuitemcheckbox' }, - { label: 'Dev Tunnels', detail: 'Access workspaces and agents on this machine from VS Code or vscode.dev/agents.', badge: undefined, role: 'menuitemcheckbox' }, + { label: 'Off', detail: 'Don\'t allow connections from other devices through this app.', badge: undefined, role: 'menuitemcheckbox' }, + { label: 'GitHub Environments', detail: 'Continue agent sessions across supported Copilot apps, VS Code, and vscode.dev/agents. Agents use folders and tools on this computer; features vary by app.', badge: 'Preview', role: 'menuitemcheckbox' }, + { label: 'Dev Tunnels', detail: 'Use agents and folders on this computer from VS Code or vscode.dev/agents. For full-editor access, use Remote Tunnels.', badge: undefined, role: 'menuitemcheckbox' }, ]); }); @@ -626,6 +628,96 @@ suite('RemoteConnectionsActionViewItem', () => { }); }); + test('applies GitHub Environments chosen while Dev Tunnels is still being saved as the connection method', async () => { + const { openMenu, closeMenu, update, configuration, sharing, remoteTunnel, selectMethodEvents } = fixture('githubEnvironment'); + const saved = new DeferredPromise(); + update.onFirstCall().callsFake(async (key: string, value: unknown) => { + await saved.p; + await TestRemoteConnectionsConfigurationService.prototype.updateValue.call(configuration, key, value); + }); + const select = (method: string) => { + const selected = openMenu().find(action => action.id === `remoteConnections.${method}`)!.run(); + closeMenu(); + return selected; + }; + const devTunnel = select('devTunnel'); + await timeout(0); + const selections = [devTunnel, select('githubEnvironment')]; + const pending = openMenu().map(action => action.checked); + closeMenu(); + await saved.complete(); + await Promise.all(selections); + assert.deepStrictEqual({ + pending, + checked: openMenu().map(action => action.checked), + preference: configuration.getValue(AgentHostRemoteConnectionsSettingId), + sharing: sharing.state.get(), + tunnel: remoteTunnel.status.type, + events: selectMethodEvents(), + }, { + pending: [false, true, false], + checked: [false, true, false], + preference: 'githubEnvironment', + sharing: 'enabled', + tunnel: 'disconnected', + events: [ + { source: 'titleBar', method: 'devTunnel', previousMethod: 'off', activeMethod: 'devTunnel', result: 'applied', gitHubEnvironments: 'enabled' }, + { source: 'titleBar', method: 'githubEnvironment', previousMethod: 'devTunnel', activeMethod: 'githubEnvironment', result: 'applied', gitHubEnvironments: 'enabled' }, + ], + }); + }); + + test('skips a choice from another surface that a later choice supersedes while Dev Tunnels starts', async () => { + const { openMenu, closeMenu, executeCommand, instantiation, run, configuration, sharing, remoteTunnel, selectMethodEvents } = fixture(); + const started = new DeferredPromise(); + executeCommand.callsFake(async () => { + remoteTunnel.fireStatus({ type: 'connecting' }); + await started.p; + remoteTunnel.fireStatus({ type: 'connected', info: { tunnelName: 'tunnel', isAttached: false }, serviceInstallFailed: false }); + return undefined; + }); + const state = store.add(instantiation.createInstance(RemoteConnectionsState)); + const editor = store.add(instantiation.createInstance(RemoteConnectionsSharing, state, () => run(), 'remotesEditor')); + const select = (method: string) => { + const selected = openMenu().find(action => action.id === `remoteConnections.${method}`)!.run(); + closeMenu(); + return selected; + }; + const selections = [select('devTunnel')]; + await timeout(0); + selections.push(editor.selectMethod('off')); + await timeout(0); + const pendingOff = openMenu().map(action => action.checked); + closeMenu(); + selections.push(select('githubEnvironment')); + const pending = { checked: openMenu().map(action => action.checked), editor: editor.pendingMethod }; + closeMenu(); + await started.complete(); + await Promise.all(selections); + assert.deepStrictEqual({ + pendingOff, + pending, + final: { + checked: openMenu().map(action => action.checked), + editor: editor.pendingMethod, + preference: configuration.getValue(AgentHostRemoteConnectionsSettingId), + sharing: sharing.state.get(), + tunnel: remoteTunnel.status.type, + }, + commands: executeCommand.args.map(([id]) => id), + events: selectMethodEvents(), + }, { + pendingOff: [true, false, false], + pending: { checked: [false, true, false], editor: 'githubEnvironment' }, + final: { checked: [false, true, false], editor: undefined, preference: 'githubEnvironment', sharing: 'enabled', tunnel: 'disconnected' }, + commands: [RemoteTunnelCommandIds.turnOn], + events: [ + { source: 'titleBar', method: 'devTunnel', previousMethod: 'off', activeMethod: 'devTunnel', result: 'applied', gitHubEnvironments: 'enabled' }, + { source: 'titleBar', method: 'githubEnvironment', previousMethod: 'devTunnel', activeMethod: 'githubEnvironment', result: 'applied', gitHubEnvironments: 'enabled' }, + ], + }); + }); + test('reflects changes made directly to the setting in the toggle and method menu', async () => { const { configuration, primary, openMenu, closeMenu, sharing, run } = fixture(); openMenu(); @@ -673,11 +765,46 @@ suite('RemoteConnectionsActionViewItem', () => { await openMenu().find(action => action.id === 'remoteConnections.githubEnvironment')!.run(); closeMenu(); assert.deepStrictEqual({ errors: notify.args, checked: openMenu().map(action => action.checked), events: selectMethodEvents() }, { - errors: [[error]], checked: [true, false, false], - events: [{ source: 'titleBar', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'failed', gitHubEnvironments: 'enabled' }], + errors: [['Failed to enable GitHub environment sharing: Unable to enable sharing']], checked: [true, false, false], + events: [{ source: 'titleBar', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'failed', gitHubEnvironments: 'enabled', failureReason: 'unknown', errorCategory: 'unknown' }], }); }); + test('logs why GitHub Environments choices did not enable sharing', async () => { + const { openMenu, closeMenu, sharing, notifications, selectMethodEvents } = fixture('githubEnvironment'); + stub(notifications, 'error'); + const setEnabled = stub(sharing, 'setEnabled'); + setEnabled.onCall(0).rejects(new CancellationError()); + setEnabled.onCall(1).rejects(new GitHubEnvironmentSharingError('Service unavailable', 'connection', { diagnostic: getConnectionDiagnosticError(Object.assign(new Error('Service unavailable'), { status: 503 })) })); + setEnabled.onCall(2).rejects(new GitHubEnvironmentSharingError('Access denied', 'fileSystemRoot', { fileErrorCode: FileSystemProviderErrorCode.NoPermissions })); + for (let i = 0; i < 3; i++) { + await openMenu().find(action => action.id === 'remoteConnections.githubEnvironment')!.run(); + closeMenu(); + } + const event = { source: 'titleBar', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', gitHubEnvironments: 'enabled' }; + assert.deepStrictEqual(selectMethodEvents(), [ + { ...event, result: 'applied', failureReason: 'canceled' }, + { ...event, result: 'failed', failureReason: 'connection', errorCategory: 'httpServer', statusCode: 503 }, + { ...event, result: 'failed', failureReason: 'fileSystemRoot', fileErrorCode: 'NoPermissions' }, + ]); + }); + + test('logs only allowlisted values from a failed toggle result', async () => { + const { instantiation, selectMethodEvents } = fixture('githubEnvironment'); + const toggle = stub(); + toggle.onCall(0).resolves({ failureReason: 'connection', errorCategory: 'httpServer', statusCode: 503, fileErrorCode: 'NoPermissions', message: 'C:\\Users\\someone\\project' }); + toggle.onCall(1).resolves({ failureReason: 'C:\\Users\\someone', errorCategory: 'someone@example.com', errorCode: 12345, statusCode: 99999, fileErrorCode: 'Secret' }); + const state = store.add(instantiation.createInstance(RemoteConnectionsState)); + const editor = store.add(instantiation.createInstance(RemoteConnectionsSharing, state, () => toggle(), 'remotesEditor')); + await editor.selectMethod('githubEnvironment'); + await editor.selectMethod('githubEnvironment'); + const event = { source: 'remotesEditor', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'failed', gitHubEnvironments: 'enabled' }; + assert.deepStrictEqual(selectMethodEvents(), [ + { ...event, failureReason: 'connection', errorCategory: 'httpServer', statusCode: 503, fileErrorCode: 'NoPermissions' }, + { ...event, failureReason: 'unknown' }, + ]); + }); + test('canceling Dev Tunnel enablement leaves Off selected and remembers the method', async () => { const { openMenu, closeMenu, executeCommand, configuration } = fixture('githubEnvironment'); executeCommand.resolves(undefined); @@ -718,7 +845,7 @@ suite('RemoteConnectionsActionViewItem', () => { await staleAction.run(); assert.deepStrictEqual(selectMethodEvents(), [ { source: 'chatInput', method: 'devTunnel', previousMethod: 'off', activeMethod: 'off', result: 'applied', gitHubEnvironments: 'enabled' }, - { source: 'chatInput', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'failed', gitHubEnvironments: 'enabled' }, + { source: 'chatInput', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'failed', gitHubEnvironments: 'enabled', failureReason: 'settingsUpdate', errorCategory: 'unknown' }, { source: 'chatInput', method: 'githubEnvironment', previousMethod: 'off', activeMethod: 'off', result: 'unavailable', gitHubEnvironments: 'unavailable' }, ]); }); @@ -940,7 +1067,7 @@ suite('ToggleRemoteConnectionsActionViewItem', () => { _usesMissionControl: () => true, getAriaLabel: () => 'Allow Remote Connections via GitHub environment', }) as { _getHoverContent(): string }; - assert.strictEqual(viewItem._getHoverContent(), 'Allow Remote Connections via GitHub environment\n\nAccess agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot.'); + assert.strictEqual(viewItem._getHoverContent(), 'Allow Remote Connections via GitHub environment\n\nContinue agent sessions across supported Copilot apps, VS Code, and vscode.dev/agents. Agents use folders and tools on this computer; features vary by app.'); }); function backendConfiguration(backend: AgentHostRemoteConnectionsBackend = 'devTunnel') { @@ -1119,7 +1246,7 @@ suite('ToggleRemoteConnectionsActionViewItem', () => { const remoteTunnel = store.add(new TestRemoteTunnelService()); const commands = new TestCommandService(); const sharing = new TestMissionControlSharingService(); - const error = operation === 'cancel sign-in' ? new CancellationError() : new Error('Sharing failed'); + const error = operation === 'cancel sign-in' ? new CancellationError() : new TypeError('fetch failed'); if (operation === 'disable') { sharing.state.set('enabled', undefined); } @@ -1132,13 +1259,17 @@ suite('ToggleRemoteConnectionsActionViewItem', () => { const notify = stub(notificationService, 'error').callThrough(); const logService = store.add(new NullLogService()); const log = stub(logService, 'error'); - await toggle(remoteTunnel, commands, undefined, backend, sharing, notificationService, logService); + const result = await toggle(remoteTunnel, commands, undefined, backend, sharing, notificationService, logService); assert.deepStrictEqual({ + result, notifications: notify.args, logs: log.args, commands: commands.commands, }, { - notifications: operation === 'cancel sign-in' ? [] : [[error]], + result: operation === 'cancel sign-in' ? 'canceled' : { failureReason: operation === 'stop tunnel' ? 'stopDevTunnel' : 'unknown', errorCategory: 'unknown' }, + notifications: operation === 'cancel sign-in' ? [] : [[operation === 'disable' + ? 'Failed to disable GitHub environment sharing: fetch failed' + : 'Failed to enable GitHub environment sharing: fetch failed']], logs: operation === 'cancel sign-in' ? [] : [['Failed to toggle GitHub environment sharing', error]], commands: [], }); diff --git a/src/vs/workbench/contrib/chatWindow/browser/chatWindow.ts b/src/vs/workbench/contrib/chatWindow/browser/chatWindow.ts index b5a4be147160..32b04302e0ce 100644 --- a/src/vs/workbench/contrib/chatWindow/browser/chatWindow.ts +++ b/src/vs/workbench/contrib/chatWindow/browser/chatWindow.ts @@ -158,6 +158,15 @@ export interface IChatWindowChrome { */ export const CHAT_PART_OPTIONS = { tabSizing: 'fixed', tabSizingFixedMinWidth: 80, tabSizingFixedMaxWidth: 160 } satisfies Partial; +/** + * The options of the main part of a chat window: its tabs follow `workbench.editor.showTabs`, live, as the main window's + * editor area does; `none` shows as `single`, so that the part keeps its title with its actions. Double-clicking a tab + * does not maximize or expand a group: the window arranges its parts. + */ +export function getChatWindowMainPartOptions(showTabs: string | undefined): DeepPartial { + return { doubleClickTabToToggleEditorGroupSizes: 'off', ...(showTabs === 'none' ? { showTabs: 'single' } : undefined) }; +} + /** The look facet: how a provider's chat windows look. */ export interface IChatWindowLook { /** The gap between the parts of the window, in pixels. */ diff --git a/src/vs/workbench/contrib/chatWindow/browser/chatWindowGrid.ts b/src/vs/workbench/contrib/chatWindow/browser/chatWindowGrid.ts index 6bab59a34ffe..9a366c20f301 100644 --- a/src/vs/workbench/contrib/chatWindow/browser/chatWindowGrid.ts +++ b/src/vs/workbench/contrib/chatWindow/browser/chatWindowGrid.ts @@ -4,15 +4,15 @@ *--------------------------------------------------------------------------------------------*/ import { $, addDisposableListener, EventType, getWindow, isHTMLElement, scheduleAtNextAnimationFrame } from '../../../../base/browser/dom.js'; -import { Direction, ISerializedGrid, ISerializedNode, IViewSize, Orientation } from '../../../../base/browser/ui/grid/grid.js'; +import { Direction, ISerializedBranchNode, ISerializedGrid, ISerializedNode, IViewSize, Orientation, orthogonal } from '../../../../base/browser/ui/grid/grid.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { combinedDisposable, Disposable, DisposableMap, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { autorun, constObservable, IObservable, observableValue } from '../../../../base/common/observable.js'; import { IPartGridPartFactory, IPartGridPartOptions, IPartGridView, PartGrid, PartGridCellContent, PartGridLocation } from '../../../browser/parts/partGrid/partGrid.js'; import { IGridEdgeInsets, NO_GRID_EDGE_INSETS } from '../../../browser/parts/partGrid/partGridGap.js'; import { IContentPart, IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.js'; -import { ChatWindowLayoutMode, ChatWindowTerminalPosition } from '../common/chatWindowLayout.js'; -import { ChatWindowPartSizes } from '../common/chatWindowState.js'; +import { ChatWindowLayoutMode, ChatWindowSplitLayout, ChatWindowTerminalPosition, isChatWindowSplitLayout } from '../common/chatWindowLayout.js'; +import { ChatWindowArrangementNode, ChatWindowPartSizes, IChatWindowArrangement } from '../common/chatWindowState.js'; import { moveEditorsToChatWindow } from './chatWindowParts.js'; /** The cells of a chat window's grid. */ @@ -58,6 +58,13 @@ export interface IChatWindowGridCells { readonly chatInputOnly?: IObservable; /** Takes the terminal position the user arranged the terminals in, such as by dropping them below the main part. */ readonly setTerminalPosition?: (position: ChatWindowTerminalPosition) => void; + /** + * How the chat and the main part are arranged while both show, or will next show: the one a layout mode hides hides + * in that arrangement. Without it, the arrangement of the last layout mode that showed both. + */ + readonly splitLayout?: IObservable; + /** How the user last arranged the parts, as {@link ChatWindowGrid.exportArrangement} exports it: the grid shows it first, if it can. */ + readonly arrangement?: IChatWindowArrangement; } type TopologyNode = { readonly cell: ChatWindowGridCell } | { readonly orientation: Orientation; readonly children: readonly TopologyNode[] }; @@ -72,30 +79,26 @@ function branch(orientation: Orientation, ...children: TopologyNode[]): Topology return flat.length === 1 ? flat[0] : { orientation, children: flat }; } -/** Where the terminals show in `mode`: without the main part beside the chat, below the chat is across the window. */ -function getEffectiveTerminalPosition(mode: ChatWindowLayoutMode, position: ChatWindowTerminalPosition): ChatWindowTerminalPosition { - return mode === ChatWindowLayoutMode.ChatOnly && position === ChatWindowTerminalPosition.UnderEditor ? ChatWindowTerminalPosition.FullWidth : position; -} - /** - * How a chat window arranges its cells for a layout mode, below the title row, which is across the top of the window - * while it shows, with the strip in a column of its own at the right, as the main window's Session Activity Bar column: - * - side by side (and chat only): the chat beside the main part; the terminals below the chat, below the main part, or - * across the bottom of the chat and the main part, as `cells.terminals` says (below the main part is across in chat - * only), the strip running past them; - * - stacked (and editor only): the main part above the chat; the terminals across the bottom of the chat and the main - * part, the strip running past them. - * The cells a mode hides, the chat or the main part, stay in the grid, so that showing them is not a move. + * How a chat window arranges its cells while the chat and the main part show as `splitLayout`, below the title row, + * which is across the top of the window while it shows, with the strip in a column of its own at the right, as the main + * window's Session Activity Bar column: + * - side by side: the chat beside the main part; the terminals below the chat, below the main part, or across the bottom + * of the chat and the main part, as `cells.terminals` says, the strip running past them; + * - stacked: the main part above the chat; the terminals across the bottom of the chat and the main part, the strip + * running past them. + * A layout mode that shows only the chat or only the main part hides the other in the arrangement, so that showing it + * again is not a move. */ -export function getChatWindowTopology(mode: ChatWindowLayoutMode, cells: { readonly titleRow: boolean; readonly strip: boolean; readonly terminals?: ChatWindowTerminalPosition }): TopologyNode { +export function getChatWindowTopology(splitLayout: ChatWindowSplitLayout, cells: { readonly titleRow: boolean; readonly strip: boolean; readonly terminals?: ChatWindowTerminalPosition }): TopologyNode { const titleRow: TopologyNode[] = cells.titleRow ? [{ cell: ChatWindowGridCell.TitleRow }] : []; const strip: TopologyNode[] = cells.strip ? [{ cell: ChatWindowGridCell.Strip }] : []; const terminals: TopologyNode[] = cells.terminals !== undefined ? [{ cell: ChatWindowGridCell.Terminals }] : []; const chat: TopologyNode = { cell: ChatWindowGridCell.Chat }; const main: TopologyNode = { cell: ChatWindowGridCell.Main }; - if (mode === ChatWindowLayoutMode.SideBySide || mode === ChatWindowLayoutMode.ChatOnly) { + if (splitLayout === ChatWindowLayoutMode.SideBySide) { let parts: TopologyNode; - switch (cells.terminals === undefined ? undefined : getEffectiveTerminalPosition(mode, cells.terminals)) { + switch (cells.terminals) { case undefined: parts = branch(Orientation.HORIZONTAL, chat, main); break; case ChatWindowTerminalPosition.UnderChat: parts = branch(Orientation.HORIZONTAL, branch(Orientation.VERTICAL, chat, ...terminals), main); break; case ChatWindowTerminalPosition.UnderEditor: parts = branch(Orientation.HORIZONTAL, chat, branch(Orientation.VERTICAL, main, ...terminals)); break; @@ -106,16 +109,13 @@ export function getChatWindowTopology(mode: ChatWindowLayoutMode, cells: { reado return branch(Orientation.VERTICAL, ...titleRow, branch(Orientation.HORIZONTAL, branch(Orientation.VERTICAL, main, chat, ...terminals), ...strip)); } -/** Where the terminals go in the grid of `mode`, beside a cell or at the bottom edge, as {@link getChatWindowTopology} places them. */ -function getTerminalsLocation(mode: ChatWindowLayoutMode, position: ChatWindowTerminalPosition): PartGridLocation { - if (mode === ChatWindowLayoutMode.Stacked) { - return { reference: ChatWindowGridCell.Chat, direction: Direction.Down }; - } - if (mode === ChatWindowLayoutMode.EditorOnly) { - // Below the main part and the hidden chat, the strip running past them +/** Where the terminals go in the arrangement of `splitLayout`, beside a cell or at the bottom edge, as {@link getChatWindowTopology} places them. */ +function getTerminalsLocation(splitLayout: ChatWindowSplitLayout, position: ChatWindowTerminalPosition): PartGridLocation { + if (splitLayout === ChatWindowLayoutMode.Stacked) { + // Across the bottom, wherever the user moved the chat and the main part, the strip running past them return { edge: Direction.Down }; } - switch (getEffectiveTerminalPosition(mode, position)) { + switch (position) { case ChatWindowTerminalPosition.UnderChat: return { reference: ChatWindowGridCell.Chat, direction: Direction.Down }; case ChatWindowTerminalPosition.UnderEditor: return { reference: ChatWindowGridCell.Main, direction: Direction.Down }; // Across the chat and the main part, the strip running past them @@ -123,15 +123,12 @@ function getTerminalsLocation(mode: ChatWindowLayoutMode, position: ChatWindowTe } } -/** - * The key the sizes of the cells are remembered under: the arrangement, and which of the chat and the main part it hides. - * Only the chat and side by side share an arrangement, but the chat takes the room of the hidden main part in one of them. - */ -function getSizesKey(topologyKey: string, mode: ChatWindowLayoutMode): string { +/** The cell `mode` hides, the chat or the main part, if it hides one. */ +function getHiddenCell(mode: ChatWindowLayoutMode): ChatWindowGridCell | undefined { switch (mode) { - case ChatWindowLayoutMode.ChatOnly: return `${topologyKey}|${ChatWindowGridCell.Main} hidden`; - case ChatWindowLayoutMode.EditorOnly: return `${topologyKey}|${ChatWindowGridCell.Chat} hidden`; - default: return topologyKey; + case ChatWindowLayoutMode.ChatOnly: return ChatWindowGridCell.Main; + case ChatWindowLayoutMode.EditorOnly: return ChatWindowGridCell.Chat; + default: return undefined; } } @@ -139,6 +136,231 @@ function describeTopology(node: TopologyNode): string { return isBranch(node) ? `${node.orientation === Orientation.HORIZONTAL ? 'row' : 'column'}(${node.children.map(describeTopology).join(',')})` : node.cell; } +/** The cells of `node`, without their sizes, as the part grid serializes them. */ +function serializeTopology(node: TopologyNode): ISerializedNode { + return isBranch(node) ? { type: 'branch', data: node.children.map(serializeTopology), size: 0 } : { type: 'leaf', data: { id: node.cell }, size: 0 }; +} + +/** What {@link PartGrid.describe} says for `cells`, the children of a branch along `orientation`. */ +function describeSerialized(cells: readonly ISerializedNode[], orientation: Orientation): string { + const describe = (node: ISerializedNode, along: Orientation): string => node.type === 'leaf' + ? (node.data as { id: string }).id + : `${along === Orientation.HORIZONTAL ? 'row' : 'column'}(${node.data.map(child => describe(child, orthogonal(along))).join(', ')})`; + return cells.length === 1 ? describe(cells[0], orientation) : describe({ type: 'branch', data: [...cells], size: 0 }, orientation); +} + +/** + * The cells of `node` that `keep` keeps, to put in place of `node` in the branch around it: a branch with one cell left is + * that cell, and one with a single branch left gives that branch's cells, which are along the branch around it. The room + * of the cells dropped goes to the cells beside them, in proportion. + */ +function keepCells(node: ISerializedNode, keep: (id: string) => boolean): ISerializedNode[] { + if (node.type === 'leaf') { + return keep((node.data as { id: string }).id) ? [node] : []; + } + const kept = node.data.flatMap(child => keepCells(child, keep)); + if (!kept.length) { + return []; + } + if (kept.length === 1) { + const [only] = kept; + return only.type === 'branch' ? only.data : [{ ...only, size: node.size }]; + } + // A hidden cell's size is the one it shows at again, not room it takes, and chrome keeps its size: only the other cells + // that show share the room + const sharing = (child: ISerializedNode) => child.visible !== false && !isChrome(child); + const sharedSize = (cells: readonly ISerializedNode[]) => cells.reduce((sum, child) => sharing(child) ? sum + child.size : sum, 0); + const total = sharedSize(node.data); + const left = sharedSize(kept); + return [{ ...node, data: left > 0 ? kept.map(child => sharing(child) ? { ...child, size: Math.round(child.size * total / left) } : child) : kept }]; +} + +/** What {@link PartGrid.describe} says for the cells of `grid` that `persistent` keeps, such as without the terminals. */ +function describeParts(grid: ISerializedGrid | undefined, persistent: (id: string) => boolean): string | undefined { + const parts = grid && withCellsOf(grid, persistent); + return parts && describeSerialized(parts.root.type === 'branch' ? parts.root.data : [parts.root], parts.orientation); +} + +/** `grid` with only the cells `keep` keeps, or undefined without any left. */ +function withCellsOf(grid: ISerializedGrid, keep: (id: string) => boolean): ISerializedGrid | undefined { + const cells = keepCells(grid.root, keep); + if (cells.length > 1) { + // The root kept a single branch: its cells are along the other orientation + const orientation = orthogonal(grid.orientation); + return { ...grid, orientation, root: { type: 'branch', data: cells, size: orientation === Orientation.HORIZONTAL ? grid.height : grid.width } }; + } + const [root] = cells; + if (!root) { + return undefined; + } + return { ...grid, root: root.type === 'branch' ? root : { type: 'branch', data: [root], size: grid.root.size } }; +} + +function collectCellIds(node: ISerializedNode | ChatWindowArrangementNode): string[] { + return node.type === 'leaf' ? [(node.data as { id: string }).id] : (node.data as readonly (ISerializedNode | ChatWindowArrangementNode)[]).flatMap(collectCellIds); +} + +/** + * `shown`, a grid with the cell `id` hidden, with the row or column it hides in as it was in `before`, as both showed: the + * cells beside it took its room meanwhile. It hides in the row or column of its cell, or, where nothing else there shows, + * such as with the terminals while they have nothing to show, in the one around that. The rows and columns elsewhere + * stay as they are now, with the sizes the user gave them, and so do the cells without any cell `persistent` keeps, + * such as the terminals, which may have joined or left meanwhile and keep their size in it. Where those do not fit, + * the cells share the room as they would be, along the dimension `constrained` says: such sizes are not the ones the user + * gave them. So are sizes below the least sizes of the cells, by `minimum`, which the grid holds them to, such as where + * the terminals leave less room than the parts need. + * Undefined where the cell's row or column cannot be told from `before`. Where that row or column is new, such as one the + * terminals joined it in, it stays as it is. + */ +function withLineSharesOf(shown: ISerializedGrid, id: string, before: ISerializedGrid, persistent: (id: string) => boolean, terminalsHeight: number | undefined, minimum: (id: string) => IViewSize): { readonly grid: ISerializedGrid; readonly constrained: 'width' | 'height' | undefined } | undefined { + const path = pathTo(shown.root, id); + if (!path) { + return undefined; + } + let hiddenIndex = path.length - 1; + while (hiddenIndex > 1 && (path[hiddenIndex - 1] as ISerializedBranchNode).data.every(child => child.visible === false)) { + hiddenIndex--; + } + const line = path[hiddenIndex - 1] as ISerializedBranchNode | undefined; + const hiddenNode = path[hiddenIndex]; + if (!line) { + return undefined; + } + const orientation = (hiddenIndex - 1) % 2 === 0 ? shown.orientation : orthogonal(shown.orientation); + // The cells that share the room as both show: the hidden one, and those that show with a cell the arrangement keeps. + // Another hidden cell, chrome, and cells without any such cell, such as the terminals, keep their size. + const partsOf = (node: ISerializedNode) => collectCellIds(node).filter(persistent); + const sharing = (child: ISerializedNode) => child === hiddenNode || (child.visible !== false && !isChrome(child) && partsOf(child).length > 0); + // Alone among them, such as above the terminals, the hidden cell takes all of it: its row or column may be new + const alone = line.data.filter(sharing).length === 1; + const previousLine = alone ? undefined : findLineWith(before.root, before.orientation, orientation, line.data.filter(sharing).map(partsOf).filter(parts => parts.length > 0)); + if (!alone && !previousLine) { + return undefined; + } + // The cells that keep their size, the terminals in a column their height, as they took the hidden cell's room meanwhile + const kept = line.data.map(child => child.visible === false || sharing(child) ? undefined + : orientation === Orientation.VERTICAL && terminalsHeight !== undefined && collectCellIds(child).every(cell => cell === ChatWindowGridCell.Terminals) ? terminalsHeight : child.size); + const extent = line.data.reduce((sum, child) => child.visible === false ? sum : sum + child.size, 0); + let room = extent - kept.reduce((sum, size) => sum + (size ?? 0), 0); + const previous = line.data.map(child => { + if (!sharing(child)) { + return 0; + } + const parts = partsOf(child); + return alone ? (child.size || 1) : previousLine?.find(candidate => collectCellIds(candidate).some(cell => parts.includes(cell)))?.size; + }); + const total = previous.reduce((sum, size) => sum + (size ?? 0), 0); + if (!total || previous.some(size => size === undefined)) { + return undefined; + } + // Where the cells that keep their size do not fit, such as terminals taller than the window now is, they all share it + // as they would be: their sizes stay what they are, and how they show as both show is still known + const dimension = orientation === Orientation.VERTICAL ? 'height' : 'width'; + const scaled = room <= 0; + if (scaled) { + // Chrome keeps its size, which its view holds it to + const chrome = line.data.reduce((sum, child, index) => kept[index] !== undefined && isChrome(child) ? sum + kept[index]! : sum, 0); + const keptTotal = kept.reduce((sum, size, index) => size === undefined || isChrome(line.data[index]) ? sum : sum + size, 0); + const scale = (extent - chrome) / (keptTotal + total); + kept.forEach((size, index) => kept[index] = size === undefined || isChrome(line.data[index]) ? size : Math.round(size * scale)); + room = extent - kept.reduce((sum, size) => sum + (size ?? 0), 0); + if (room <= 0) { + return undefined; + } + } + const showCell = (node: ISerializedNode): ISerializedNode => node.type === 'leaf' + ? ((node.data as { id: string }).id === id ? { ...node, visible: undefined } : node) + : { ...node, data: node.data.map(showCell) }; + const cells = line.data.map((child, index) => sharing(child) ? { ...(child === hiddenNode ? showCell(child) : child), size: Math.round(previous[index]! * room / total), visible: undefined } + : kept[index] !== undefined ? { ...child, size: kept[index]! } : child); + // The least room a cell of the row or column needs along it: of a row or column across it, that of its largest cell + const minimumOf = (node: ISerializedNode, nodeOrientation: Orientation): number => { + if (node.visible === false) { + return 0; + } + if (node.type === 'leaf') { + return minimum((node.data as { id: string }).id)[dimension]; + } + const minimums = node.data.map(child => minimumOf(child, orthogonal(nodeOrientation))); + return nodeOrientation === orientation ? minimums.reduce((sum, size) => sum + size, 0) : Math.max(0, ...minimums); + }; + const constrained = scaled || cells.some((cell, index) => sharing(line.data[index]) && cell.size < minimumOf(cell, orthogonal(orientation))) ? dimension : undefined; + const replaceLine = (node: ISerializedNode): ISerializedNode => node.type === 'leaf' ? node + : node === line ? { ...node, data: cells } + : { ...node, data: node.data.map(replaceLine) }; + return { grid: { ...shown, root: replaceLine(shown.root) }, constrained }; +} + +/** Whether `node` is only chrome, such as the strip, which keeps its size rather than sharing the room of its row. */ +function isChrome(node: ISerializedNode): boolean { + return collectCellIds(node).every(id => id === ChatWindowGridCell.Strip || id === ChatWindowGridCell.TitleRow); +} + +/** The nodes from `node` down to the cell `id`, or undefined without it. */ +function pathTo(node: ISerializedNode, id: string): ISerializedNode[] | undefined { + if (node.type === 'leaf') { + return (node.data as { id: string }).id === id ? [node] : undefined; + } + for (const child of node.data) { + const path = pathTo(child, id); + if (path) { + return [node, ...path]; + } + } + return undefined; +} + +/** + * The cells of the deepest row or column along `orientation` under `node`, a branch along `nodeOrientation`, in which each + * of `parts`, the cells of a row or column, is in a cell of its own. + */ +function findLineWith(node: ISerializedNode, nodeOrientation: Orientation, orientation: Orientation, parts: readonly (readonly string[])[]): readonly ISerializedNode[] | undefined { + if (node.type === 'leaf') { + return undefined; + } + for (const child of node.data) { + const deeper = findLineWith(child, orthogonal(nodeOrientation), orientation, parts); + if (deeper) { + return deeper; + } + } + const holders = parts.map(cells => node.data.findIndex(child => collectCellIds(child).some(cell => cells.includes(cell)))); + return nodeOrientation === orientation && holders.every(holder => holder >= 0) && new Set(holders).size === holders.length ? node.data : undefined; +} + +/** The size of each cell of `grid`, as its rows and columns divide its room. */ +function cellSizesOf(grid: ISerializedGrid): Map { + const sizes = new Map(); + const visit = (node: ISerializedNode, orientation: Orientation, width: number, height: number) => { + if (node.type === 'leaf') { + sizes.set((node.data as { id: string }).id, { width, height }); + return; + } + for (const child of node.data) { + visit(child, orthogonal(orientation), orientation === Orientation.HORIZONTAL ? child.size : width, orientation === Orientation.HORIZONTAL ? height : child.size); + } + }; + visit(grid.root, grid.orientation, grid.width, grid.height); + return sizes; +} + +/** The row or column the cell `id` is in, under `node`, a branch along `orientation`. */ +function findLineOf(node: ISerializedNode, orientation: Orientation, id: string): { readonly children: readonly ISerializedNode[]; readonly orientation: Orientation } | undefined { + if (node.type === 'leaf') { + return undefined; + } + if (node.data.some(child => child.type === 'leaf' && (child.data as { id: string }).id === id)) { + return { children: node.data, orientation }; + } + for (const child of node.data) { + const line = findLineOf(child, orthogonal(orientation), id); + if (line) { + return line; + } + } + return undefined; +} + /** How much of the room of a branch a cell takes until the user sizes it: the main part wider and taller than the chat. */ function getShare(node: TopologyNode, orientation: Orientation): number { if (isBranch(node)) { @@ -230,8 +452,12 @@ class TitleRowView extends ChromeView { /** * The grid of a chat window, on the workbench's part grid: its title row, its chat part, its main part, its strip and the - * part that holds its terminals, arranged for its layout mode. The sizes the user gives its cells are kept per - * arrangement, so that a mode shows with the sizes it had, and can be exported to come back for the chat after a reload. + * part that holds its terminals, arranged for how the chat and the main part show together, side by side or stacked. A + * layout mode that shows only one of them hides the other in that arrangement, so that the parts the user moved, such + * as the main part to the left of the chat, stay where they are as either hides and shows again; only arranging them + * together the other way, or a reset, arranges them anew. The sizes the user gives its cells are kept per arrangement, + * so that an arrangement shows with the sizes it had, and those and the arrangement the user gave the parts can be + * exported to come back for the chat after a reload. * * The terminals' part joins the grid where the terminal position says once it exists, and moves when the position * changes. Like every part, it hides while it has no editors. It keeps its height as the window is resized, and tall @@ -244,28 +470,44 @@ export class ChatWindowGrid extends Disposable { private readonly _userResize = this._register(new MutableDisposable()); private readonly _styleLayout = this._register(new MutableDisposable()); private _topologyKey: string | undefined; - /** The key the sizes of what shows are remembered under; see {@link getSizesKey}. */ + /** + * The key the sizes of the arrangement are remembered under: as the chat and the main part show together, also while + * one of them hides, which leaves the other its room. + */ private _sizesKey: string | undefined; /** The key the sizes of the chat and the main part are also remembered under, without the terminals: they come back to it after a restart, for example, until the terminals are restored. */ private _baseSizesKey: string | undefined; /** The height the terminals take when they first show: they join the grid empty, until their first terminal shows in them. */ private _terminalsFirstShowHeight: number | undefined; + /** + * The grid restored from the arrangement the user gave the parts, as it shows until the terminals first show in it: + * the parts beside them then keep the shares they have in it, rather than the last of them giving the terminals its + * room. Only once: later, the terminals show among the sizes the parts have then. + */ + private _beforeTerminalsShow: ISerializedGrid | undefined; /** The key of the arrangement without the terminals: while it stays, the terminals join or move rather than rebuild. */ private _baseTopologyKey: string | undefined; private _terminalsInGrid = false; private _dimension: IViewSize | undefined; + /** The height the terminals had by default in the window as it was, which they take back as it grows again, if squeezed. */ + private _lastTerminalsHeight: number | undefined; private _outerInsets: IGridEdgeInsets = NO_GRID_EDGE_INSETS; private _sizes: ChatWindowPartSizes = {}; /** The arrangement of the part grid as the window arranged it: sizes are remembered for it only while the grid still shows it. */ private _arranged: string | undefined; /** The layout mode the grid was last arranged for. */ private _arrangedMode: ChatWindowLayoutMode | undefined; + /** How the chat and the main part were arranged together when the grid was last arranged, which they hide in. */ + private _arrangedSplitLayout: ChatWindowSplitLayout | undefined; + /** The arrangement the user gave the parts before, which the grid shows first for its split layout; see {@link exportArrangement}. */ + private _restoredArrangement: IChatWindowArrangement | undefined; + /** The arrangement the grid last exported, or restored: see {@link exportArrangement}. */ + private _exportedArrangement: IChatWindowArrangement | undefined; /** - * The arrangement of the part grid as the layout mode arranged it, with the parts the grid created: unlike - * {@link _arranged}, it does not take in parts the user moved meanwhile, so that a mode change can tell whether they did. + * What the grid showed, and its sizes, before the layout mode hid the chat or the main part, until it shows both again: + * its shape without the terminals, which may join or leave meanwhile, and the height the terminals take as it does. */ - private _modeArrangement: string | undefined; - private _createdPartsChangingModeArrangement = false; + private _beforeHide: { grid: ISerializedGrid | undefined; created: ReadonlySet; terminalsHeight: number | undefined } | undefined; private _createdPartsChanging = false; /** The height the terminals take once the cells of the arrangement they moved in show. */ private _pendingTerminalsHeight: number | undefined; @@ -304,6 +546,8 @@ export class ChatWindowGrid extends Disposable { ) { super(); this._sizes = { ...sizes }; + this._restoredArrangement = _cells.arrangement; + this._exportedArrangement = _cells.arrangement; this._terminalPosition = terminalPosition ?? constObservable(ChatWindowTerminalPosition.FullWidth); this._partFactory = partFactory && { createPart: () => { @@ -323,6 +567,7 @@ export class ChatWindowGrid extends Disposable { this._register(autorun(reader => { this._layoutMode.read(reader); + _cells.splitLayout?.read(reader); _cells.strip?.visible.read(reader); _cells.titleRow?.visible.read(reader); _cells.terminals?.read(reader); @@ -344,6 +589,7 @@ export class ChatWindowGrid extends Disposable { const end = () => { up.dispose(); this._rememberUserSizes(before); + this._updateBeforeTerminalsShow(); }; // Replacing a resize that never ended, such as one whose release went elsewhere, ends that one first const up = this._userResize.value = combinedDisposable( @@ -358,10 +604,17 @@ export class ChatWindowGrid extends Disposable { // the sash drags within this._resizing.set(true, undefined); }, true)); + // A sash reset, by a double click, is remembered as a drag is: the sizes before it are read as the sash takes it + let beforeReset: Map | undefined; + this._register(addDisposableListener(_container, EventType.DBLCLICK, e => { + beforeReset = this._sashOf(e) ? this._cellSizes() : undefined; + }, true)); this._register(addDisposableListener(_container, EventType.DBLCLICK, e => { - if (this._sashOf(e)) { - this._rememberUserSizes(undefined); + if (this._sashOf(e) && beforeReset) { + this._rememberUserSizes(beforeReset); + this._updateBeforeTerminalsShow(); } + beforeReset = undefined; })); this._register(autorun(reader => { _cells.chatInputOnly?.read(reader); @@ -407,6 +660,10 @@ export class ChatWindowGrid extends Disposable { if (this._closing === closing) { return; } + if (closing) { + // What the user arranged, while the parts are still in the grid: they leave it as the window closes + this.exportArrangement(); + } this._closing = closing; if (!closing) { this._update(); @@ -424,14 +681,76 @@ export class ChatWindowGrid extends Disposable { } layout(width: number, height: number): void { - const first = !this._dimension; + const previous = this._dimension; + const first = !previous; + this._rememberTerminalsHeight(previous); this._dimension = { width, height }; if (first) { // Arranged once the window has its size, so that the parts take their shares of it. this._update(); } else { // The parts keep their shares of the window as it is resized, and the terminals their height (see `_contentOf`) - this._grid.value?.layout(width, height); + const grid = this._grid.value; + grid?.layout(width, height); + // Squeezed where the window had too little room, such as as a part showed in a short one: they take the height the + // user gave them, else the one they had in the larger window, back as it grows taller, as far as the others leave + // room. Not otherwise, as a part dropped at an edge of the window shrinks them on purpose, nor mid-drag, which + // saves the height it ends at. + const given = this._sizes[TERMINALS_SIZE_KEY]?.[ChatWindowGridCell.Terminals]?.height; + const preferred = given ?? this._lastTerminalsHeight; + if (grid && preferred !== undefined && !this._resizing.get()) { + if (height > previous.height && grid.isCellVisible(ChatWindowGridCell.Terminals) && grid.getCellSize(ChatWindowGridCell.Terminals).height < preferred && this._isInColumn(grid, ChatWindowGridCell.Terminals)) { + this._recoverTerminalsHeight(grid, preferred); + } + // The height a hidden part restores them to was squeezed too, if the window had too little room when it hid + if (this._beforeHide?.terminalsHeight !== undefined && this._beforeHide.terminalsHeight < preferred) { + this._beforeHide.terminalsHeight = preferred; + } + } + } + } + + /** + * Remembers the height the terminals have by default in the window as it was, as far as they have it: a window too + * short for it squeezes them, and they take it back as the window grows (see `layout`). Forgotten while they are hidden. + */ + private _rememberTerminalsHeight(dimension: IViewSize | undefined): void { + const grid = this._grid.value; + if (!grid || !dimension || !grid.isCellVisible(ChatWindowGridCell.Terminals)) { + this._lastTerminalsHeight = undefined; + } else if (this._sizes[TERMINALS_SIZE_KEY]?.[ChatWindowGridCell.Terminals]?.height === undefined && !this._resizing.get()) { + this._lastTerminalsHeight = Math.max(this._lastTerminalsHeight ?? 0, Math.min(grid.getCellSize(ChatWindowGridCell.Terminals).height, this._defaultTerminalsHeight(dimension))); + } + } + + /** Whether `cell` is in a column, so that its height is its own, not that of a row it is in. */ + private _isInColumn(grid: PartGrid, cell: string): boolean { + const current = grid.serializeGrid(); + return !!current && findLineOf(current.root, current.orientation, cell)?.orientation === Orientation.VERTICAL; + } + + /** Gives the terminals `height`, taking it from the parts above them in proportion to their heights, not from the last. */ + private _recoverTerminalsHeight(grid: PartGrid, height: number): void { + const current = grid.serializeGrid(); + const line = current && findLineOf(current.root, current.orientation, ChatWindowGridCell.Terminals); + // A row of parts beside them is one sibling, sized by any part it has: its height is the row's. Where a sibling + // has deeper rows or columns, no part tells its height, so the room is taken as the grid takes it + const visibleChildren = (line?.children ?? []) + .filter(child => child.visible !== false && !(child.type === 'leaf' && (child.data as { id: string }).id === ChatWindowGridCell.Terminals)); + const isFlat = (child: ISerializedNode) => child.type === 'leaf' || (child.data as readonly ISerializedNode[]).every(part => part.type === 'leaf'); + const representatives = visibleChildren.map(child => isFlat(child) ? collectCellIds(child).find(id => grid.isCellVisible(id)) : undefined); + const siblings = representatives.every(id => id !== undefined) + ? representatives.map(id => ({ id: id!, height: grid.getCellSize(id!).height })) + : []; + const total = siblings.reduce((sum, sibling) => sum + sibling.height, 0); + const taken = height - grid.getCellSize(ChatWindowGridCell.Terminals).height; + this._resizeTerminals(grid, height); + if (total > taken) { + for (const sibling of siblings.slice(0, -1)) { + grid.resizeCell(sibling.id, { height: sibling.height - Math.round(taken * sibling.height / total) }); + } + // Shrinking a part hands its room to the next one, which may be the terminals. + this._resizeTerminals(grid, height); } } @@ -440,6 +759,72 @@ export class ChatWindowGrid extends Disposable { grid.resizeCell(ChatWindowGridCell.Terminals, { height }); } + /** + * Whether `id` is a cell of the arrangement the user gives the parts: not the terminals, nor a part the grid created + * now or as a part hid, which come and go meanwhile. + */ + private _isPersistentCell(id: string): boolean { + return id !== ChatWindowGridCell.Terminals && !this._created.has(id) && !this._beforeHide?.created.has(id); + } + + /** Whether `shown` arranges the cells of the arrangement the user gives the parts as they were before a part hid. */ + private _showsPartsAsBeforeHide(shown: ISerializedGrid | undefined): boolean { + const persistent = (id: string) => this._isPersistentCell(id); + const before = describeParts(this._beforeHide?.grid, persistent); + return before !== undefined && before === describeParts(shown, persistent); + } + + /** + * Gives the cells of the row or column of `cell` the shares they had in `before`, in the room they have now, the + * terminals among them keeping `terminalsHeight` in a column, else their own height: they may have joined since. Each + * cell takes its size from the last of them, so sizing all but the last, in order, gives each its own. + */ + private _restoreLineSizes(grid: PartGrid, cell: string, before: ISerializedGrid, terminalsHeight: number | undefined): void { + const current = grid.serializeGrid(); + const line = current && findLineOf(current.root, current.orientation, cell); + if (!line) { + return; + } + const dimension = line.orientation === Orientation.VERTICAL ? 'height' : 'width'; + const children = line.children.filter(child => child.visible !== false); + const ids = children.map(child => collectCellIds(child).find(id => grid.isCellVisible(id))); + if (ids.some(id => id === undefined)) { + return; + } + const persistent = (id: string) => this._isPersistentCell(id); + const partsOf = (node: ISerializedNode) => collectCellIds(node).filter(persistent); + // The terminals keep their height; a part that came or goes as the grid created it, such as for dropped editors, its size + const fixed = children.map((child, index) => partsOf(child).length && !isChrome(child) ? undefined + : child.type === 'leaf' && ids[index] === ChatWindowGridCell.Terminals && dimension === 'height' ? terminalsHeight ?? this._terminalsHeight() + : grid.getCellSize(ids[index]!)[dimension]); + // Alone beside the terminals, such as the main part with the terminals under it, the cell takes the rest. Else the + // cells share it as they did, also when the terminals joined or left the row or column meanwhile. + const sharesIn = (grid: ISerializedGrid | undefined) => { + const previousLine = grid && findLineOf(grid.root, grid.orientation, cell); + return children.map((child, index) => { + const parts = partsOf(child); + return fixed[index] !== undefined || previousLine?.orientation !== line.orientation ? undefined + : previousLine.children.find(candidate => candidate.visible !== false && collectCellIds(candidate).some(id => parts.includes(id)))?.size; + }); + }; + const isComplete = (shares: (number | undefined)[]) => shares.every((size, index) => size !== undefined || fixed[index] !== undefined); + const previous = fixed.filter(size => size === undefined).length === 1 ? fixed.map(size => size === undefined ? 1 : undefined) + : [sharesIn(before), sharesIn(withCellsOf(before, persistent))].find(isComplete); + if (!previous) { + return; + } + const room = ids.reduce((sum, id) => sum + grid.getCellSize(id!)[dimension], 0); + const fixedTotal = fixed.reduce((sum, size) => sum + (size ?? 0), 0); + const total = previous.reduce((sum, size) => sum + (size ?? 0), 0); + if (!total || fixedTotal >= room) { + return; + } + children.slice(0, -1).forEach((_child, index) => { + const size = fixed[index] ?? Math.round(previous[index]! * (room - fixedTotal) / total); + grid.resizeCell(ids[index]!, dimension === 'height' ? { height: size } : { width: size }); + }); + } + /** * A part the grid creates or closes, such as for an editor dropped on an edge of the window, is part of the window's * arrangement, which the window then still arranged, unless something else changed it, such as a part the user moved. @@ -447,7 +832,6 @@ export class ChatWindowGrid extends Disposable { private _willChangeCreatedParts(): void { const shown = this._grid.value?.describe(); this._createdPartsChanging ||= shown !== undefined && shown === this._arranged; - this._createdPartsChangingModeArrangement ||= shown !== undefined && shown === this._modeArrangement; } private _updateFromGrid(): void { @@ -455,12 +839,24 @@ export class ChatWindowGrid extends Disposable { this._createdPartsChanging = false; this._arranged = this._grid.value?.describe(); } - if (this._createdPartsChangingModeArrangement) { - this._createdPartsChangingModeArrangement = false; - this._modeArrangement = this._grid.value?.describe(); + const terminalsVisible = !!this._grid.value?.isCellVisible(ChatWindowGridCell.Terminals); + this._terminalsVisible.set(terminalsVisible, undefined); + if (!terminalsVisible) { + this._lastTerminalsHeight = undefined; + } else if (this._lastTerminalsHeight === undefined) { + // As they show, at the height they have by default, before a part dropped at an edge of the window shrinks them + this._rememberTerminalsHeight(this._dimension); } - this._terminalsVisible.set(!!this._grid.value?.isCellVisible(ChatWindowGridCell.Terminals), undefined); this._adoptTerminalPosition(); + this._updateBeforeTerminalsShow(); + } + + /** Until the terminals first show, the parts keep the sizes they have, such as those the user gives them meanwhile. */ + private _updateBeforeTerminalsShow(): void { + const grid = this._grid.value; + if (this._beforeTerminalsShow && grid && !grid.isCellVisible(ChatWindowGridCell.Terminals)) { + this._beforeTerminalsShow = grid.serializeGrid(); + } } /** @@ -472,36 +868,36 @@ export class ChatWindowGrid extends Disposable { const grid = this._grid.value; const setTerminalPosition = this._cells.setTerminalPosition; const mode = this._arrangedMode; - if (!grid || !setTerminalPosition || mode === undefined || this._closing || !this._terminalsInGrid) { + const splitLayout = this._arrangedSplitLayout; + if (!grid || !setTerminalPosition || mode === undefined || splitLayout === undefined || this._closing || !this._terminalsInGrid) { return; } const shown = grid.describe(); const current = this._terminalPosition.get(); - if (shown === this._describeArrangement(mode, current)) { + if (shown === this._describeArrangement(splitLayout, current)) { return; } - const adopted = [ChatWindowTerminalPosition.FullWidth, ChatWindowTerminalPosition.UnderChat, ChatWindowTerminalPosition.UnderEditor].find(position => shown === this._describeArrangement(mode, position)); + const adopted = [ChatWindowTerminalPosition.FullWidth, ChatWindowTerminalPosition.UnderChat, ChatWindowTerminalPosition.UnderEditor].find(position => shown === this._describeArrangement(splitLayout, position)); if (adopted === undefined) { return; } - this._topologyKey = this._topology(mode, adopted).key; - this._sizesKey = getSizesKey(this._topologyKey, mode); + this._topologyKey = this._topology(splitLayout, adopted).key; + this._sizesKey = this._topologyKey; this._arranged = shown; - this._modeArrangement = shown; setTerminalPosition(adopted); } - /** What {@link PartGrid.describe} says for the arrangement of `mode` with the terminals at `position`, as {@link _arrange} builds it. */ - private _describeArrangement(mode: ChatWindowLayoutMode, position: ChatWindowTerminalPosition): string { - const { topology } = this._topology(mode, position); + /** What {@link PartGrid.describe} says for the arrangement of `splitLayout` with the terminals at `position`, as {@link _arrange} builds it. */ + private _describeArrangement(splitLayout: ChatWindowSplitLayout, position: ChatWindowTerminalPosition): string { + const { topology } = this._topology(splitLayout, position); const orientation = isBranch(topology) ? topology.orientation : Orientation.HORIZONTAL; - const serialize = (node: TopologyNode): ISerializedNode => isBranch(node) ? { type: 'branch', data: node.children.map(serialize), size: 0 } : { type: 'leaf', data: { id: node.cell }, size: 0 }; - const root = serialize(topology); - const cells = this._withCreatedParts(root.type === 'branch' ? root.data : [root], orientation, 0, 0); - const describe = (node: ISerializedNode, along: Orientation): string => node.type === 'leaf' - ? (node.data as { id: string }).id - : `${along === Orientation.HORIZONTAL ? 'row' : 'column'}(${node.data.map(child => describe(child, along === Orientation.HORIZONTAL ? Orientation.VERTICAL : Orientation.HORIZONTAL)).join(', ')})`; - return cells.length === 1 ? describe(cells[0], orientation) : describe({ type: 'branch', data: cells, size: 0 }, orientation); + const root = serializeTopology(topology); + return describeSerialized(this._withCreatedParts(root.type === 'branch' ? root.data : [root], orientation, 0, 0), orientation); + } + + /** How the chat and the main part show together in `mode`, or, in a mode that hides one, as they last did. */ + private _splitLayoutOf(mode: ChatWindowLayoutMode): ChatWindowSplitLayout { + return this._cells.splitLayout?.get() ?? (isChatWindowSplitLayout(mode) ? mode : this._arrangedSplitLayout ?? ChatWindowLayoutMode.SideBySide); } private _update(): void { @@ -509,52 +905,83 @@ export class ChatWindowGrid extends Disposable { return; } const mode = this._layoutMode.get(); - // A layout mode arranges the parts as it does, from its own arrangement: parts the user moved go back to their - // places, also when the mode arranges them as the one before it, such as Side by Side and Chat Only, and a part - // it hid, such as the main part in Chat Only, shows again at its size rather than where the terminals moved - // beside it while hidden. Between modes that arrange the parts alike, with none moved, the parts only show or hide. - if (mode !== this._arrangedMode && this._arrangedMode !== undefined) { - const moved = this._grid.value?.describe() !== this._modeArrangement; - if (moved || this._topology(mode).key !== this._topologyKey) { - this._topologyKey = undefined; - this._baseTopologyKey = undefined; - } + const splitLayout = this._splitLayoutOf(mode); + // Only arranging the chat and the main part together another way arranges the parts again, from that arrangement. + // Showing or hiding either keeps the arrangement the grid shows, with the parts the user moved where they are. + if (this._arrangedSplitLayout !== undefined && splitLayout !== this._arrangedSplitLayout) { + this._topologyKey = undefined; + this._baseTopologyKey = undefined; + this._restoredArrangement = undefined; + this._beforeHide = undefined; } + const previousMode = this._arrangedMode; this._arrangedMode = mode; - if (this._arrange(mode, this._dimension)) { - this._modeArrangement = this._grid.value!.describe(); - } + this._arrangedSplitLayout = splitLayout; + // Arranged by the user, such as a part they moved: its sizes are not those of the window's arrangement + const userArranged = !!this._grid.value && this._grid.value.describe() !== this._arranged; + const arranged = this._arrange(splitLayout, this._dimension); const grid = this._grid.value!; // The terminals keep the height they have, or move with, as cells show and hide: a hidden cell, such as the title // row, would otherwise give them its room. const terminalsHeight = this._pendingTerminalsHeight ?? (grid.isCellVisible(ChatWindowGridCell.Terminals) ? grid.getCellSize(ChatWindowGridCell.Terminals).height : undefined); + const hidden = getHiddenCell(mode); + // The part that shows again, also as the other one hides instead, such as from Chat Only to Editor Only + const previousHidden = previousMode !== undefined ? getHiddenCell(previousMode) : undefined; + const shown = previousHidden !== hidden ? previousHidden : undefined; this._pendingTerminalsHeight = undefined; - grid.setCellVisible(ChatWindowGridCell.Chat, mode !== ChatWindowLayoutMode.EditorOnly); - grid.setCellVisible(ChatWindowGridCell.Main, mode !== ChatWindowLayoutMode.ChatOnly); + // The chrome first: the room it leaves is the parts', also as both show before one hides if (this._titleRow) { grid.setCellVisible(ChatWindowGridCell.TitleRow, !!this._cells.titleRow?.visible.get()); } if (this._strip) { grid.setCellVisible(ChatWindowGridCell.Strip, !!this._cells.strip?.visible.get()); } + // Before the part hides, as both show: also in the grid arranged anew while it stays hidden, such as stacked. The + // terminals take their height first, which the chrome that showed or hid changed as it gave or took their room. + if (hidden && (!previousHidden || arranged === 'rebuilt')) { + if (terminalsHeight !== undefined && grid.isCellVisible(ChatWindowGridCell.Terminals) && grid.getCellSize(ChatWindowGridCell.Terminals).height !== terminalsHeight) { + this._resizeTerminals(grid, terminalsHeight); + } + const before = grid.serializeGrid(); + this._beforeHide = { grid: before, created: new Set(this._created.keys()), terminalsHeight: grid.isCellVisible(ChatWindowGridCell.Terminals) ? grid.getCellSize(ChatWindowGridCell.Terminals).height : undefined }; + } + grid.setCellVisible(ChatWindowGridCell.Chat, mode !== ChatWindowLayoutMode.EditorOnly); + grid.setCellVisible(ChatWindowGridCell.Main, mode !== ChatWindowLayoutMode.ChatOnly); // Sized once the cells beside them show, which would otherwise take a share of their height. if (terminalsHeight !== undefined && grid.isCellVisible(ChatWindowGridCell.Terminals) && grid.getCellSize(ChatWindowGridCell.Terminals).height !== terminalsHeight) { this._resizeTerminals(grid, terminalsHeight); } - this._arranged = grid.describe(); - this._sizesKey = getSizesKey(this._topologyKey!, mode); - this._baseSizesKey = getSizesKey(this._baseTopologyKey!, mode); + // The part that shows again takes the room it had back from the cells beside it, unless the arrangement changed + // meanwhile: rather than from the last of them, such as the terminals below it, which took its room as it hid. + const beforeHide = this._beforeHide; + if (shown && beforeHide?.grid && this._showsPartsAsBeforeHide(grid.serializeGrid())) { + this._restoreLineSizes(grid, shown, beforeHide.grid, beforeHide.terminalsHeight); + } + if (!hidden) { + this._beforeHide = undefined; + } + if (arranged === 'changed') { + // The terminals joined, moved or left: the window's arrangement is the one with them as they are now, also + // while the user's differs, so that sizes count again once the user arranges the parts as the window does + this._arranged = userArranged ? this._describeArrangement(splitLayout, this._terminalPosition.get()) : grid.describe(); + } + this._sizesKey = this._topologyKey; + this._baseSizesKey = this._baseTopologyKey; this._updateFromGrid(); } /** - * Forgets the sizes the user gave the cells and arranges them again as the mode arranges them, as in a new window: - * parts moved elsewhere go back to their places, the parts it created close, their editors moving into the main part, - * and the cells take their default shares. + * Forgets the sizes the user gave the cells and how they arranged them, and arranges them again as the mode arranges + * them, as in a new window: parts moved elsewhere go back to their places, the parts it created close, their editors + * moving into the main part, and the cells take their default shares. */ reset(): void { this._closeCreatedParts(); this._sizes = {}; + this._restoredArrangement = undefined; + this._exportedArrangement = undefined; + this._beforeHide = undefined; + this._beforeTerminalsShow = undefined; this._topologyKey = undefined; this._baseTopologyKey = undefined; this._sizesKey = undefined; @@ -586,26 +1013,70 @@ export class ChatWindowGrid extends Disposable { } /** - * Remembers the sizes of the cells a sash the user dragged changed, or of all after they reset one (`before` is - * undefined). The height of the terminals is theirs in every arrangement; the sizes of the chat and the main part are - * those of the arrangement, while the grid still shows it as the window arranged it. + * Remembers the sizes of the cells a sash the user dragged or reset changed. The height of the terminals is theirs in + * every arrangement; the sizes of the chat and the main part are those of the arrangement as both show, while the grid + * still shows it as the window arranged it. While one of them hides, the other took its room: the sizes are those both + * take as they show again, as the hidden one hid with, which the grid then also shows them with. */ - private _rememberUserSizes(before: Map | undefined): void { + private _rememberUserSizes(before: Map): void { const grid = this._grid.value; if (!grid || !this._sizesKey) { return; } const changed: Record = {}; for (const [cell, size] of this._cellSizes()) { - const previous = before?.get(cell); + const previous = before.get(cell); if (!previous || previous.width !== size.width || previous.height !== size.height) { changed[cell] = size; } } - if (changed[ChatWindowGridCell.Terminals]) { - this._sizes[TERMINALS_SIZE_KEY] = { [ChatWindowGridCell.Terminals]: changed[ChatWindowGridCell.Terminals] }; + // Only a height the user gives the terminals is theirs: a width they take, such as beside the chat while the main part + // above them hides, leaves the height they fill there, which is not one the user chose. + const terminals = changed[ChatWindowGridCell.Terminals]; + if (terminals && before.get(ChatWindowGridCell.Terminals)?.height !== terminals.height) { + this._sizes[TERMINALS_SIZE_KEY] = { [ChatWindowGridCell.Terminals]: terminals }; + // As it shows again too, while a part hides + if (this._beforeHide) { + this._beforeHide.terminalsHeight = terminals.height; + } + } + const { [ChatWindowGridCell.Terminals]: _terminals, ...changedParts } = changed; + let parts: Record = changedParts; + const hidden = this._arrangedMode !== undefined ? getHiddenCell(this._arrangedMode) : undefined; + if (hidden) { + const shown = grid.serializeGrid(); + const beforeHide = this._beforeHide; + const previousGrid = beforeHide?.grid; + if (!shown || !beforeHide || !previousGrid || !this._showsPartsAsBeforeHide(shown)) { + return; + } + const asBothShow = withLineSharesOf(shown, hidden, previousGrid, id => this._isPersistentCell(id), beforeHide.terminalsHeight ?? this._terminalsHeight(), id => grid.getCellMinimumSize(id)); + if (!asBothShow) { + return; + } + // Sizes the parts only take as they fit the window, such as beside terminals taller than it, are not taken in + if (!asBothShow.constrained) { + // The parts the grid created that it shows now are in it too, also once they close + beforeHide.grid = asBothShow.grid; + beforeHide.created = new Set([...beforeHide.created, ...this._created.keys()]); + } + if (!Object.keys(changed).length) { + return; + } + // The dimension the user did not change stays as it was where the parts only take their sizes in it as they fit, + // such as the heights beside terminals taller than the window as a width changes. Else, as both show, the parts + // take the sizes they have now in it, such as the widths the window gives them as it is resized. + const touched = (dimension: 'width' | 'height') => Object.entries(changed).some(([cell, size]) => before.get(cell)?.[dimension] !== size[dimension]); + const [width, height] = [asBothShow.constrained !== 'width' || touched('width'), asBothShow.constrained !== 'height' || touched('height')]; + const sizes = cellSizesOf(asBothShow.grid); + const previousSizes = cellSizesOf(previousGrid); + const remembered = this._sizes[this._sizesKey]; + parts = Object.fromEntries([ChatWindowGridCell.Chat, ChatWindowGridCell.Main].flatMap(cell => { + const size = sizes.get(cell); + const kept = remembered?.[cell] ?? previousSizes.get(cell) ?? size; + return size && kept ? [[cell, { width: width ? size.width : kept.width, height: height ? size.height : kept.height }]] : []; + })); } - const { [ChatWindowGridCell.Terminals]: _terminals, ...parts } = changed; if (!Object.keys(parts).length || grid.describe() !== this._arranged) { return; } @@ -615,25 +1086,48 @@ export class ChatWindowGrid extends Disposable { } } - /** The arrangement of a layout mode, with the terminals where they show, or at `position`, and its key. */ - private _topology(mode: ChatWindowLayoutMode, position = this._terminalPosition.get()) { + /** The arrangement of `splitLayout`, with the terminals where they show, or at `position`, and its key. */ + private _topology(splitLayout: ChatWindowSplitLayout, position = this._terminalPosition.get()) { const terminals = this._cells.terminals?.get(); const chrome = { titleRow: !!this._titleRow, strip: !!this._strip }; - const topology = getChatWindowTopology(mode, { ...chrome, terminals: terminals ? position : undefined }); + const topology = getChatWindowTopology(splitLayout, { ...chrome, terminals: terminals ? position : undefined }); return { terminals, position, chrome, topology, key: describeTopology(topology) }; } - /** Arranges the parts as the mode does, unless the grid already shows its arrangement. Returns whether it arranged them. */ - private _arrange(mode: ChatWindowLayoutMode, dimension: IViewSize): boolean { - const { terminals, position, chrome, topology, key } = this._topology(mode); + /** + * The arrangement the user gave the parts before, for the grid of `splitLayout` to show first: only one of that split + * layout, of the cells the grid has, such as without a strip, and before the grid created parts of its own. + */ + private _takeRestoredArrangement(splitLayout: ChatWindowSplitLayout): ISerializedGrid | undefined { + const arrangement = this._restoredArrangement; + this._restoredArrangement = undefined; + if (!arrangement || arrangement.splitLayout !== splitLayout || this._created.size) { + return undefined; + } + if (!this._isOfWindowCells(collectCellIds(arrangement.root))) { + return undefined; + } + return { + root: arrangement.root as ISerializedNode, + orientation: arrangement.orientation === 1 ? Orientation.HORIZONTAL : Orientation.VERTICAL, + width: arrangement.width, + height: arrangement.height, + }; + } + + /** + * Arranges the parts as `splitLayout` does, unless the grid already shows its arrangement: anew (`rebuilt`), or only the + * terminals joining, moving or leaving it (`changed`). + */ + private _arrange(splitLayout: ChatWindowSplitLayout, dimension: IViewSize): 'rebuilt' | 'changed' | undefined { + const { terminals, position, chrome, topology, key } = this._topology(splitLayout); if (key === this._topologyKey) { - return false; + return undefined; } this._topologyKey = key; - const sizesKey = getSizesKey(key, mode); // While the rest of the arrangement stays, the terminals join it, move in it or leave it, as the part grid does. - const baseKey = describeTopology(getChatWindowTopology(mode, chrome)); + const baseKey = describeTopology(getChatWindowTopology(splitLayout, chrome)); const grid = this._grid.value; if (grid && baseKey === this._baseTopologyKey) { // The part grid may rebuild its grid for them, such as across the chat and the main part with the strip running past @@ -643,38 +1137,26 @@ export class ChatWindowGrid extends Disposable { grid.removeCell(ChatWindowGridCell.Terminals); this._terminalsInGrid = false; } else if (this._terminalsInGrid) { - grid.moveCell(ChatWindowGridCell.Terminals, getTerminalsLocation(mode, position)); + grid.moveCell(ChatWindowGridCell.Terminals, getTerminalsLocation(splitLayout, position)); this._pendingTerminalsHeight = this._terminalsHeight(); } else { - const height = this._terminalsHeight(); - grid.addPart(ChatWindowGridCell.Terminals, terminals, getTerminalsLocation(mode, position), height, TERMINALS_OPTIONS); - this._terminalsInGrid = true; - this._terminalsFirstShowHeight = grid.isCellVisible(ChatWindowGridCell.Terminals) ? undefined : height; + this._addTerminals(grid, terminals, splitLayout, position); } this._restoreFocus(focused); - return true; + return 'changed'; } this._baseTopologyKey = baseKey; this._terminalsInGrid = !!terminals; - // The sizes of the arrangement, else those of the chat and the main part as they showed without the terminals, else - // as they showed before the strip had a column of its own in every mode, which a version without it still reads. - const withoutStrip = { ...chrome, strip: false }; - const legacyKeys = this._strip ? [getSizesKey(describeTopology(getChatWindowTopology(mode, withoutStrip)), mode), getSizesKey(describeTopology(getChatWindowTopology(mode, { ...withoutStrip, terminals: terminals ? position : undefined })), mode)] : []; - const remembered: ChatWindowPartSizes[string] = {}; - for (const rememberedKey of [...legacyKeys, getSizesKey(baseKey, mode), sizesKey]) { - Object.assign(remembered, this._sizes[rememberedKey]); - } - const orientation = isBranch(topology) ? topology.orientation : Orientation.HORIZONTAL; // The grid keeps the outer insets to the edges of the window: its cells share what is inside them. const insets = this._outerInsets; const width = Math.max(0, dimension.width - insets.left - insets.right); const height = Math.max(0, dimension.height - insets.top - insets.bottom); - const root = this._serialize(topology, orientation === Orientation.HORIZONTAL ? width : height, orientation, remembered, { width, height }); // Applied once the cells of the arrangement show or hide, such as the title row, whose room would otherwise go to them. this._pendingTerminalsHeight = terminals ? Math.min(height, this._terminalsHeight()) : undefined; - const serializedRoot: ISerializedNode = { type: 'branch', data: this._withCreatedParts(root.type === 'branch' ? root.data : [root], orientation, width, height), size: orientation === Orientation.HORIZONTAL ? height : width }; - const serializedGrid: ISerializedGrid = { root: serializedRoot, orientation, width, height }; + // The terminals join the arrangement the user gave the parts, which is without them, where their position says + const restored = this._takeRestoredArrangement(splitLayout); + const serializedGrid = restored ?? this._serializeArrangement(splitLayout, topology, key, baseKey, terminals ? position : undefined, { width, height }); const state = { grid: serializedGrid, hidden: [], parts: {}, created: Array.from(this._created.keys()) }; // The parts move into the cells of the new grid, which takes the focus from what had it in them, such as the chat input const focused = this._container.ownerDocument.activeElement; @@ -696,19 +1178,118 @@ export class ChatWindowGrid extends Disposable { partGrid.setPinnedTopView(ChatWindowGridCell.TitleRow); } this._terminalsFirstShowHeight = undefined; + this._beforeTerminalsShow = undefined; this._gridListener.value = combinedDisposable(partGrid.onDidChangeArrangement(() => this._updateFromGrid()), partGrid.onDidChangePartEmpty(e => { - const height = this._terminalsFirstShowHeight; - if (e.id === ChatWindowGridCell.Terminals && !e.empty && height !== undefined && partGrid.isCellVisible(ChatWindowGridCell.Terminals)) { - this._terminalsFirstShowHeight = undefined; - this._resizeTerminals(partGrid, height); + if (e.id === ChatWindowGridCell.Terminals && !e.empty && partGrid.isCellVisible(ChatWindowGridCell.Terminals)) { + const height = this._terminalsFirstShowHeight; + if (height !== undefined) { + this._terminalsFirstShowHeight = undefined; + this._resizeTerminals(partGrid, height); + } + this._keepSharesBesideTerminals(partGrid); } this._updateFromGrid(); })); partGrid.setGap(this._gap.get()); partGrid.setOuterInsets(insets); partGrid.layout(dimension.width, dimension.height); + // Once laid out: until then, a restored grid does not know the sizes of its rows and columns, such as the width of + // a row of the chat and the main part without the chrome, which the terminals would take their room in. + if (restored) { + this._beforeTerminalsShow = partGrid.serializeGrid(); + if (terminals) { + this._addTerminals(partGrid, terminals, splitLayout, position); + } + } this._restoreFocus(focused); - return true; + // The window's arrangement, which the user's is not: its sizes are not remembered for it + this._arranged = restored ? this._describeArrangement(splitLayout, position) : partGrid.describe(); + return 'rebuilt'; + } + + private _addTerminals(grid: PartGrid, terminals: IContentPart, splitLayout: ChatWindowSplitLayout, position: ChatWindowTerminalPosition): void { + const height = this._terminalsHeight(); + grid.addPart(ChatWindowGridCell.Terminals, terminals, getTerminalsLocation(splitLayout, position), height, TERMINALS_OPTIONS); + this._terminalsInGrid = true; + this._terminalsFirstShowHeight = grid.isCellVisible(ChatWindowGridCell.Terminals) ? undefined : height; + this._keepSharesBesideTerminals(grid); + } + + /** + * As the terminals first show in a grid restored from the arrangement the user gave the parts, also as they join it + * or fill, the parts beside them keep the shares they had, such as the chat and the main part in a column without the + * chrome, rather than the last of them giving the terminals its room. + */ + private _keepSharesBesideTerminals(grid: PartGrid): void { + const before = this._beforeTerminalsShow; + if (!before || !grid.isCellVisible(ChatWindowGridCell.Terminals)) { + return; + } + this._beforeTerminalsShow = undefined; + const current = grid.serializeGrid(); + const line = current && findLineOf(current.root, current.orientation, ChatWindowGridCell.Terminals); + const beside = line?.children.map(child => child.type === 'leaf' && child.visible !== false ? (child.data as { id: string }).id : undefined).find(id => id === ChatWindowGridCell.Chat || id === ChatWindowGridCell.Main); + if (beside) { + this._restoreLineSizes(grid, beside, before, undefined); + } + } + + /** The grid of `topology` in `box`, its cells at the sizes the user gave them, else at their shares, with the parts the grid created. */ + private _serializeArrangement(splitLayout: ChatWindowSplitLayout, topology: TopologyNode, sizesKey: string, baseKey: string, terminals: ChatWindowTerminalPosition | undefined, box: IViewSize): ISerializedGrid { + // The sizes of the arrangement, else those of the chat and the main part as they showed without the terminals, else + // as they showed before the strip had a column of its own in every mode, which a version without it still reads. + const withoutStrip = { titleRow: !!this._titleRow, strip: false }; + const legacyKeys = this._strip ? [describeTopology(getChatWindowTopology(splitLayout, withoutStrip)), describeTopology(getChatWindowTopology(splitLayout, { ...withoutStrip, terminals }))] : []; + const remembered: ChatWindowPartSizes[string] = {}; + for (const rememberedKey of [...legacyKeys, baseKey, sizesKey]) { + Object.assign(remembered, this._sizes[rememberedKey]); + } + const orientation = isBranch(topology) ? topology.orientation : Orientation.HORIZONTAL; + const { width, height } = box; + const root = this._serialize(topology, orientation === Orientation.HORIZONTAL ? width : height, orientation, remembered, box); + const serializedRoot: ISerializedNode = { type: 'branch', data: this._withCreatedParts(root.type === 'branch' ? root.data : [root], orientation, width, height), size: orientation === Orientation.HORIZONTAL ? height : width }; + return { root: serializedRoot, orientation, width, height }; + } + + /** + * How the user arranged the parts, such as the main part moved to the left of the chat, for the grid to show again, + * such as after a reload: undefined while the grid shows the parts as the window arranges them, apart from the + * terminals and the parts it created, which show where they always do. + */ + exportArrangement(): IChatWindowArrangement | undefined { + const shown = this._grid.value?.serializeGrid(); + const hidden = this._arrangedMode !== undefined ? getHiddenCell(this._arrangedMode) : undefined; + const beforeHide = this._beforeHide; + const partGrid = this._grid.value; + const grid = (shown && partGrid && hidden && beforeHide?.grid && this._showsPartsAsBeforeHide(shown) ? withLineSharesOf(shown, hidden, beforeHide.grid, id => this._isPersistentCell(id), beforeHide.terminalsHeight ?? this._terminalsHeight(), id => partGrid.getCellMinimumSize(id))?.grid : undefined) ?? shown; + const splitLayout = this._arrangedSplitLayout; + // While the window closes, its chat and main part leave the grid: what it showed before is what the user arranged + if (this._closing || !grid || splitLayout === undefined) { + return this._exportedArrangement; + } + const arrangement = withCellsOf(grid, id => id !== ChatWindowGridCell.Terminals && !this._created.has(id)); + if (!arrangement || arrangement.root.type !== 'branch' || !this._isOfWindowCells(collectCellIds(arrangement.root))) { + return this._exportedArrangement; + } + const windowTopology = getChatWindowTopology(splitLayout, { titleRow: !!this._titleRow, strip: !!this._strip }); + const windowArrangement = serializeTopology(windowTopology); + if (describeSerialized(arrangement.root.data, arrangement.orientation) === describeSerialized(windowArrangement.type === 'branch' ? windowArrangement.data : [windowArrangement], isBranch(windowTopology) ? windowTopology.orientation : Orientation.HORIZONTAL)) { + return this._exportedArrangement = undefined; + } + return this._exportedArrangement = { + version: 1, + splitLayout, + orientation: arrangement.orientation === Orientation.HORIZONTAL ? 1 : 0, + width: arrangement.width, + height: arrangement.height, + root: arrangement.root as ChatWindowArrangementNode, + }; + } + + /** Whether `ids` are those of the cells an arrangement the user gave the parts is of: the chat, the main part and the window's chrome, each once. */ + private _isOfWindowCells(ids: readonly string[]): boolean { + const expected = [ChatWindowGridCell.Chat, ChatWindowGridCell.Main, ...(this._titleRow ? [ChatWindowGridCell.TitleRow] : []), ...(this._strip ? [ChatWindowGridCell.Strip] : [])]; + return ids.length === expected.length && expected.every(id => ids.includes(id)); } /** Gives the focus back to `focused`, an element of the window that lost it as the grid arranged its cells. */ @@ -773,9 +1354,13 @@ export class ChatWindowGrid extends Disposable { /** The height the terminals take in every arrangement: the height the user last gave them, else their share of the window. */ private _terminalsHeight(): number { + return this._sizes[TERMINALS_SIZE_KEY]?.[ChatWindowGridCell.Terminals]?.height ?? this._defaultTerminalsHeight(this._dimension); + } + + private _defaultTerminalsHeight(dimension: IViewSize | undefined): number { const insets = this._outerInsets; - const total = Math.max(0, (this._dimension?.height ?? 0) - insets.top - insets.bottom); - return this._sizes[TERMINALS_SIZE_KEY]?.[ChatWindowGridCell.Terminals]?.height ?? Math.round(total * TERMINALS_SHARE); + const total = Math.max(0, (dimension?.height ?? 0) - insets.top - insets.bottom); + return Math.round(total * TERMINALS_SHARE); } private _contentOf(id: string): PartGridCellContent { diff --git a/src/vs/workbench/contrib/chatWindow/browser/chatWindowParts.ts b/src/vs/workbench/contrib/chatWindow/browser/chatWindowParts.ts index 6360768042e4..0ca4628d3f71 100644 --- a/src/vs/workbench/contrib/chatWindow/browser/chatWindowParts.ts +++ b/src/vs/workbench/contrib/chatWindow/browser/chatWindowParts.ts @@ -16,7 +16,7 @@ import { ChatWindowLayoutMode } from '../common/chatWindowLayout.js'; * Follows the editors of a chat window's main part: `onDidOpenEditor` when an editor opens in it, and * `onDidCloseLastEditor` once its last editor closed, but not when that editor moved, or while the window closes. */ -export function trackMainPartEditors(part: Pick, handlers: { onDidOpenEditor(): void; onDidCloseLastEditor(): void; isClosing(): boolean }): IDisposable { +export function trackMainPartEditors(part: Pick, handlers: { onDidOpenEditor(editor: EditorInput | undefined): void; onDidCloseLastEditor(): void; isClosing(): boolean }): IDisposable { const store = new DisposableStore(); const groups = store.add(new DisposableStore()); const isEmpty = () => part.groups.every(group => group.isEmpty); @@ -25,7 +25,7 @@ export function trackMainPartEditors(part: Pick { if (e.kind === GroupModelChangeKind.EDITOR_OPEN && !handlers.isClosing()) { - handlers.onDidOpenEditor(); + handlers.onDidOpenEditor(e.editor); } })); groups.add(group.onDidCloseEditor(e => { @@ -43,16 +43,14 @@ export function trackMainPartEditors(part: Pick, window: { readonly layoutMode: IObservable; showChatOnly(): void }, firstOpen: boolean): boolean { - const mode = window.layoutMode.get(); - if (mode === ChatWindowLayoutMode.ChatOnly || (mode !== ChatWindowLayoutMode.EditorOnly && !firstOpen) || part.groups.some(group => !group.isEmpty)) { +export function showChatInsteadOfEmptyMainPart(part: Pick, window: { readonly layoutMode: IObservable; showChatOnly(): void }): boolean { + if (window.layoutMode.get() === ChatWindowLayoutMode.ChatOnly || part.groups.some(group => !group.isEmpty)) { return false; } window.showChatOnly(); diff --git a/src/vs/workbench/contrib/chatWindow/browser/chatWindowService.ts b/src/vs/workbench/contrib/chatWindow/browser/chatWindowService.ts index 0ae431b9f57a..e7f61167aca6 100644 --- a/src/vs/workbench/contrib/chatWindow/browser/chatWindowService.ts +++ b/src/vs/workbench/contrib/chatWindow/browser/chatWindowService.ts @@ -31,7 +31,7 @@ import { GroupDirection, GroupsOrder, IContentPart, IEditorGroup, IEditorGroupsS import { IHostService } from '../../../services/host/browser/host.js'; import { ILifecycleService } from '../../../services/lifecycle/common/lifecycle.js'; import { ChatWindowLayoutMode, ChatWindowSplitLayout, ChatWindowTerminalPosition } from '../common/chatWindowLayout.js'; -import { ChatWindowChatLayouts, ChatWindowChatSizes, ChatWindowDefaults, ChatWindowState } from '../common/chatWindowState.js'; +import { ChatWindowChatArrangements, ChatWindowChatLayouts, ChatWindowChatSizes, ChatWindowDefaults, ChatWindowState } from '../common/chatWindowState.js'; import { CHAT_PART_OPTIONS, IChatWindow, IChatWindowChat, IChatWindowChatPart, IChatWindowContent, IChatWindowEditors, IChatWindowNewChatOptions, IChatWindowOpenOptions, IChatWindowProvider, IChatWindowService } from './chatWindow.js'; import { bindWindowLayoutContext, bindWindowTerminalsContext } from './chatWindowContextKeys.js'; import { captureChatPart, deserializeChatWindowEditors, getRestoredChatGroup, reopenChatWindow, serializeChatWindowEditorsBesideChat } from './chatWindowEditors.js'; @@ -407,7 +407,11 @@ export class ChatWindow extends Disposable implements IChatWindow { const isChatIn = (groups: readonly IEditorGroup[]) => groups.some(group => this.chatInputs.some(input => group.contains(input))); this._register(trackMainPartEditors(mainPart, { - onDidOpenEditor: () => this._showMainPart(), + onDidOpenEditor: editor => { + if (!editor || editor !== this._restoringEditor) { + this._showMainPart(); + } + }, // Only the chat part can show the chat: with the chat moved to another part, the window keeps its layout onDidCloseLastEditor: () => { if (isChatIn(this.chatPart.groups)) { @@ -571,7 +575,7 @@ export class ChatWindow extends Disposable implements IChatWindow { this._returnChat(); this._host.resetLayout(); this.state.reset(); - showChatInsteadOfEmptyMainPart(this.mainPart, this, true); + showChatInsteadOfEmptyMainPart(this.mainPart, this); } showEditor(): void { @@ -579,6 +583,19 @@ export class ChatWindow extends Disposable implements IChatWindow { this._showMainPart(); } + async restoreMainPartEditor(editor: EditorInput, open: () => Promise): Promise { + let opening: Promise; + this._restoringEditor = editor; + try { + opening = open(); + } finally { + this._restoringEditor = undefined; + } + await opening; + } + + private _restoringEditor: EditorInput | undefined; + /** Shows the main part beside the chat, as the window shows it once an editor opens in it. */ private _showMainPart(): void { if (this.state.layoutMode.get() === ChatWindowLayoutMode.ChatOnly) { @@ -788,6 +805,7 @@ export class ChatWindowService extends Disposable implements IChatWindowService private readonly _openByChat = new SequencerByKey(); private readonly _chatLayouts: ChatWindowChatLayouts; private readonly _chatSizes: ChatWindowChatSizes; + private readonly _chatArrangements: ChatWindowChatArrangements; /** The grid of each open window, which arranges its parts. */ private readonly _grids = new Map(); @@ -805,6 +823,7 @@ export class ChatWindowService extends Disposable implements IChatWindowService this.hasProvider = this._provider.map(provider => !!provider); this._chatLayouts = new ChatWindowChatLayouts(_storageService); this._chatSizes = new ChatWindowChatSizes(_storageService); + this._chatArrangements = new ChatWindowChatArrangements(_storageService); this._register(this._instantiationService.createInstance(ChatWindowsRestoration, { provider: this._provider, windows: this._windows, @@ -883,6 +902,8 @@ export class ChatWindowService extends Disposable implements IChatWindowService } if (added !== target) { moveBack(); + } else if (options?.editors?.editors?.length) { + await this._openEditors(options.editors, target.mainPart, target); } return added; } @@ -1120,6 +1141,7 @@ export class ChatWindowService extends Disposable implements IChatWindowService resetLayout: () => { this._chatLayouts.delete(chatWindow.anchor.chat.get()); this._chatSizes.delete(chatWindow.anchor.chat.get()); + this._chatArrangements.delete(chatWindow.anchor.chat.get()); gridRef.get()?.reset(); }, windowGroups: { @@ -1183,14 +1205,26 @@ export class ChatWindowService extends Disposable implements IChatWindowService terminals: chatWindow.terminalsPart, chatInputOnly: derived(reader => state.layoutMode.read(reader) === ChatWindowLayoutMode.Stacked && state.inputOnly.read(reader)), setTerminalPosition: position => state.setTerminalPosition(position), + splitLayout: state.splitLayout, + arrangement: this._chatArrangements.get(chat), }, state.layoutMode, look.gap, this._chatSizes.get(chat), state.terminalPosition, partFactory)); gridRef.set(grid, undefined); // As the window goes away, after its chat part and main part closed and before the part that holds its terminals does disposables.add(chatWindow.onWillClose(() => grid.willClose())); this._grids.set(chatWindow, grid); disposables.add(toDisposable(() => this._grids.delete(chatWindow))); - // What the window shows is what it shows again for its chat: the sizes of its parts per arrangement. - const saveSizes = () => this._chatSizes.set(chatWindow.anchor.chat.get(), grid.exportSizes()); + // What the window shows is what it shows again for its chat: the sizes of its parts per arrangement, and how the user + // arranged them. + const saveSizes = () => { + const chat = chatWindow.anchor.chat.get(); + this._chatSizes.set(chat, grid.exportSizes()); + const arrangement = grid.exportArrangement(); + if (arrangement) { + this._chatArrangements.set(chat, arrangement); + } else { + this._chatArrangements.delete(chat); + } + }; disposables.add(this._storageService.onWillSaveState(saveSizes)); disposables.add(auxiliaryWindow.onBeforeUnload(saveSizes)); if (look.paintChatBackground) { @@ -1235,9 +1269,9 @@ export class ChatWindowService extends Disposable implements IChatWindowService if (anchor) { chatWindow.anchor = anchor; } - await this._openEditors(options?.editors, mainPart); - await this._openCreatedParts(options?.createdParts, mainPart, grid); - showChatInsteadOfEmptyMainPart(mainPart, chatWindow, !rememberedLayout); + await this._openEditors(options?.editors, mainPart, chatWindow); + await this._openCreatedParts(options?.createdParts, mainPart, grid, chatWindow); + showChatInsteadOfEmptyMainPart(mainPart, chatWindow); if (options?.showTerminals) { chatWindow.getOrCreateTerminalsPart(); } @@ -1265,9 +1299,9 @@ export class ChatWindowService extends Disposable implements IChatWindowService * part at the edge of the window, where such parts go as the window's parts are arranged. Where the window creates no * parts, its editors stay in its main part. */ - private async _openCreatedParts(createdParts: readonly IChatWindowEditors[] | undefined, mainPart: IContentPart, grid: ChatWindowGrid): Promise { + private async _openCreatedParts(createdParts: readonly IChatWindowEditors[] | undefined, mainPart: IContentPart, grid: ChatWindowGrid, chatWindow: ChatWindow): Promise { for (const created of createdParts ?? []) { - await this._openEditors(created, mainPart); + await this._openEditors(created, mainPart, chatWindow); const group = mainPart.activeGroup; const editors = (created.editors ?? []).filter(editor => group.contains(editor)).map(editor => ({ editor, groupId: group.id })); if (editors.length) { @@ -1276,10 +1310,17 @@ export class ChatWindowService extends Disposable implements IChatWindowService } } - private async _openEditors(editors: IChatWindowEditors | undefined, part: IContentPart): Promise { + private async _openEditors(editors: IChatWindowEditors | undefined, part: IContentPart, chatWindow: ChatWindow): Promise { const inputs = editors?.editors ?? []; const active = editors?.activeEditor ?? inputs.at(-1); - await part.activeGroup.openEditors(inputs.map(editor => ({ editor, options: { pinned: true, preserveFocus: true, inactive: editor !== active } }))); + const group = part.activeGroup; + for (const editor of inputs) { + await chatWindow.restoreMainPartEditor(editor, () => group.openEditor(editor, { pinned: true, preserveFocus: true, inactive: editor !== active, index: group.count })); + } + const shown = active && group.getEditors(EditorsOrder.SEQUENTIAL).find(editor => editor.matches(active)); + if (shown && group.activeEditor !== shown) { + await chatWindow.restoreMainPartEditor(shown, () => group.openEditor(shown, { pinned: true, preserveFocus: true })); + } } private _findGroup(editor: EditorInput): IEditorGroup | undefined { diff --git a/src/vs/workbench/contrib/chatWindow/common/chatWindowState.ts b/src/vs/workbench/contrib/chatWindow/common/chatWindowState.ts index ef9b01678fd2..fa001b77aecc 100644 --- a/src/vs/workbench/contrib/chatWindow/common/chatWindowState.ts +++ b/src/vs/workbench/contrib/chatWindow/common/chatWindowState.ts @@ -98,7 +98,11 @@ class PerChatMemory { delete(chat: URI): void { const key = chat.toString(); - this._storageService.store(this._key, JSON.stringify(this._read().filter(([candidate]) => candidate !== key)), StorageScope.WORKSPACE, StorageTarget.MACHINE); + const entries = this._read(); + const kept = entries.filter(([candidate]) => candidate !== key); + if (kept.length !== entries.length) { + this._storageService.store(this._key, JSON.stringify(kept), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } } } @@ -172,6 +176,71 @@ export class ChatWindowChatSizes { } } +/** A cell of an arranged chat window, or a row or column of them, as its part grid serializes it. */ +export type ChatWindowArrangementNode = + { readonly type: 'leaf'; readonly data: { readonly id: string }; readonly size: number; readonly visible?: boolean } | + { readonly type: 'branch'; readonly data: readonly ChatWindowArrangementNode[]; readonly size: number; readonly visible?: boolean }; + +/** + * How the user arranged the chat and the main part of a chat window, such as the main part moved to the left of the chat: + * the cells of its part grid with their sizes, without its terminals and the parts it created, which show where they + * always do. It is the arrangement of {@link splitLayout}, which the chat and the main part hide in. + */ +export interface IChatWindowArrangement { + readonly version: 1; + readonly splitLayout: ChatWindowSplitLayout; + /** The orientation of the root, `0` for vertical and `1` for horizontal, as the part grid's. */ + readonly orientation: 0 | 1; + readonly width: number; + readonly height: number; + readonly root: ChatWindowArrangementNode; +} + +/** The deepest rows and columns of an arrangement read from storage: deeper ones are not one a window arranges. */ +const MAX_ARRANGEMENT_DEPTH = 16; + +function isArrangementNode(value: unknown, depth: number): value is ChatWindowArrangementNode { + const node = value as Partial<{ type: unknown; data: unknown; size: unknown; visible: unknown }> | undefined; + if (!node || typeof node !== 'object' || typeof node.size !== 'number' || !Number.isFinite(node.size) || node.size < 0 || (node.visible !== undefined && typeof node.visible !== 'boolean')) { + return false; + } + if (node.type === 'leaf') { + return typeof (node.data as { id?: unknown } | undefined)?.id === 'string'; + } + return node.type === 'branch' && depth < MAX_ARRANGEMENT_DEPTH && Array.isArray(node.data) && node.data.length > 0 && node.data.every(child => isArrangementNode(child, depth + 1)); +} + +function isArrangement(value: unknown): value is IChatWindowArrangement { + const candidate = value as Partial | undefined; + return candidate?.version === 1 && isChatWindowSplitLayout(candidate.splitLayout) && (candidate.orientation === 0 || candidate.orientation === 1) + && typeof candidate.width === 'number' && Number.isFinite(candidate.width) && candidate.width > 0 && typeof candidate.height === 'number' && Number.isFinite(candidate.height) && candidate.height > 0 + && candidate.root?.type === 'branch' && isArrangementNode(candidate.root, 0); +} + +/** Remembers, per chat and in the workspace, how the user arranged the parts of its chat window, so that they show so again after a reload. */ +export class ChatWindowChatArrangements { + + static readonly STORAGE_KEY = 'sessions.chatWindow.chatArrangements'; + + private readonly _memory: PerChatMemory; + + constructor(storageService: IStorageService) { + this._memory = new PerChatMemory(storageService, ChatWindowChatArrangements.STORAGE_KEY, isArrangement); + } + + get(chat: URI): IChatWindowArrangement | undefined { + return this._memory.get(chat); + } + + set(chat: URI, arrangement: IChatWindowArrangement): void { + this._memory.set(chat, arrangement); + } + + delete(chat: URI): void { + this._memory.delete(chat); + } +} + /** How the chat of a chat window is remembered to show, per chat. */ export interface IChatWindowRememberedLayout { /** How the chat last showed in a chat window, if it did. */ diff --git a/src/vs/workbench/contrib/chatWindow/test/browser/chatWindow.test.ts b/src/vs/workbench/contrib/chatWindow/test/browser/chatWindow.test.ts index b74394d0c572..a02aadda7cbd 100644 --- a/src/vs/workbench/contrib/chatWindow/test/browser/chatWindow.test.ts +++ b/src/vs/workbench/contrib/chatWindow/test/browser/chatWindow.test.ts @@ -107,6 +107,12 @@ suite('Chat window', () => { this.onActiveEditorChange.fire({ editor: this._active }); return undefined; } + override async openEditors(editors: { editor: EditorInput; options?: { inactive?: boolean } }[]) { + for (const [index, { editor, options }] of editors.entries()) { + await this.openEditor(editor, index ? { ...options, inactive: true } : options); + } + return undefined; + } readonly immovable = new Set(); /** Opens nothing, as a group whose open is cancelled; and closes nothing, as one whose close is vetoed. */ refuseOpen = false; @@ -347,6 +353,79 @@ suite('Chat window', () => { assert.deepStrictEqual(modes, [ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.ChatOnly]); }); + test('the editors it restores in its main part keep the mode it opens in, such as only its chat, while an editor the user opens after shows its main part', async () => { + const { window, state, main } = createWindow(); + state.setLayoutMode(ChatWindowLayoutMode.ChatOnly); + const restoredEditor = editor(); + await window.restoreMainPartEditor(restoredEditor, async () => main.group.open(restoredEditor)); + const restored = window.layoutMode.get(); + main.group.open(editor()); + + assert.deepStrictEqual({ restored, afterUserOpen: window.layoutMode.get() }, { restored: ChatWindowLayoutMode.ChatOnly, afterUserOpen: ChatWindowLayoutMode.SideBySide }); + }); + + test('an editor the user opens while the window still restores another one shows its main part, even when the window restores that very editor next, and a restore that fails stops treating its editor as restored', async () => { + const { window, state, main } = createWindow(); + state.setLayoutMode(ChatWindowLayoutMode.ChatOnly); + const first = editor(); + const queued = editor(); + let release!: () => void; + const restoring = window.restoreMainPartEditor(first, async () => { + main.group.open(first); + await new Promise(resolve => release = resolve); + }); + const afterRestoredOpen = window.layoutMode.get(); + main.group.open(queued); + const afterUserOpen = window.layoutMode.get(); + release(); + await restoring; + + state.setLayoutMode(ChatWindowLayoutMode.ChatOnly); + const failed = editor(); + await assert.rejects(window.restoreMainPartEditor(failed, async () => { throw new Error('failed'); })); + main.group.open(failed); + + assert.deepStrictEqual({ afterRestoredOpen, afterUserOpen, afterFailedRestore: window.layoutMode.get() }, { afterRestoredOpen: ChatWindowLayoutMode.ChatOnly, afterUserOpen: ChatWindowLayoutMode.SideBySide, afterFailedRestore: ChatWindowLayoutMode.SideBySide }); + }); + + test('as the window restores the editors of its main part, the user opening one of them that the restore did not open yet shows the main part right away, and the restore keeps the order and the active editor', async () => { + const { service, windows: [a] } = createService(['a']); + const group = a.main.group; + const first = editor(); + const queued = editor(); + const last = editor(); + const gate = new DeferredPromise(); + const openEditor = async (input: EditorInput, options?: { inactive?: boolean }) => { + if (!group.contains(input)) { + group.open(input, !options?.inactive); + } + await gate.p; + return undefined; + }; + Reflect.set(group, 'openEditor', openEditor); + Reflect.set(group, 'openEditors', async (inputs: { editor: EditorInput; options?: { inactive?: boolean } }[]) => { + for (const { editor: input, options } of inputs) { + await openEditor(input, options); + } + }); + a.window.setLayoutMode(ChatWindowLayoutMode.ChatOnly); + + const restoring: Promise = Reflect.get(service, '_openEditors').call(service, { editors: [first, queued, last], activeEditor: queued }, a.main.part, a.window); + const whileRestoring = a.window.layoutMode.get(); + group.open(queued); + const afterUserOpen = a.window.layoutMode.get(); + gate.complete(); + await restoring; + + assert.deepStrictEqual({ whileRestoring, afterUserOpen, afterRestore: a.window.layoutMode.get(), order: group.testEditors.map(input => input === first ? 'first' : input === queued ? 'queued' : 'last'), active: group.activeEditor === queued }, { + whileRestoring: ChatWindowLayoutMode.ChatOnly, + afterUserOpen: ChatWindowLayoutMode.SideBySide, + afterRestore: ChatWindowLayoutMode.SideBySide, + order: ['first', 'queued', 'last'], + active: true, + }); + }); + test('an editor of its main part dropped beside the chat splits the chat part and empties the main part, which changes no mode: never Editor Only', () => { const { window, main, chat } = createWindow(); const file = editor(); @@ -360,29 +439,27 @@ suite('Chat window', () => { assert.deepStrictEqual({ modes, chatVisible: window.chatVisible }, { modes: [ChatWindowLayoutMode.SideBySide, ChatWindowLayoutMode.SideBySide], chatVisible: true }); }); - test('it opens showing only its chat while its main part has no editor: the first time its chat shows in a window, as 491817 does, or when it would show only its main part; a mode chosen for the chat shows again', () => { - const opened = (mode: ChatWindowLayoutMode, firstOpen: boolean, hasEditor: boolean) => { + test('it opens showing only its chat while its main part has no editor, whatever mode is remembered for its chat, which stays remembered', () => { + const opened = (mode: ChatWindowLayoutMode, hasEditor: boolean) => { const defaults = new ChatWindowDefaults(disposables.add(new InMemoryStorageService())); const state = new ChatWindowState(defaults); state.setLayoutMode(mode); const remembered = defaults.getLayoutMode(); - showChatInsteadOfEmptyMainPart({ groups: [upcastPartial({ isEmpty: !hasEditor })] }, state, firstOpen); + showChatInsteadOfEmptyMainPart({ groups: [upcastPartial({ isEmpty: !hasEditor })] }, state); return `${state.layoutMode.get()}, default ${defaults.getLayoutMode() === remembered ? 'kept' : 'changed'}`; }; assert.deepStrictEqual({ - firstOpenNoEditor: opened(ChatWindowLayoutMode.SideBySide, true, false), - firstOpenStackedNoEditor: opened(ChatWindowLayoutMode.Stacked, true, false), - firstOpenWithEditor: opened(ChatWindowLayoutMode.SideBySide, true, true), - rememberedSideBySideNoEditor: opened(ChatWindowLayoutMode.SideBySide, false, false), - rememberedEditorOnlyNoEditor: opened(ChatWindowLayoutMode.EditorOnly, false, false), - rememberedEditorOnlyWithEditor: opened(ChatWindowLayoutMode.EditorOnly, false, true), + sideBySideNoEditor: opened(ChatWindowLayoutMode.SideBySide, false), + stackedNoEditor: opened(ChatWindowLayoutMode.Stacked, false), + editorOnlyNoEditor: opened(ChatWindowLayoutMode.EditorOnly, false), + sideBySideWithEditor: opened(ChatWindowLayoutMode.SideBySide, true), + editorOnlyWithEditor: opened(ChatWindowLayoutMode.EditorOnly, true), }, { - firstOpenNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, - firstOpenStackedNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, - firstOpenWithEditor: `${ChatWindowLayoutMode.SideBySide}, default kept`, - rememberedSideBySideNoEditor: `${ChatWindowLayoutMode.SideBySide}, default kept`, - rememberedEditorOnlyNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, - rememberedEditorOnlyWithEditor: `${ChatWindowLayoutMode.EditorOnly}, default kept`, + sideBySideNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, + stackedNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, + editorOnlyNoEditor: `${ChatWindowLayoutMode.ChatOnly}, default kept`, + sideBySideWithEditor: `${ChatWindowLayoutMode.SideBySide}, default kept`, + editorOnlyWithEditor: `${ChatWindowLayoutMode.EditorOnly}, default kept`, }); }); @@ -778,6 +855,65 @@ suite('Chat window', () => { }); }); + test('a chat opened in a window with editors resolved for it, such as those stashed for its session, opens them in the window\'s main part once the window takes the chat, with the active one active and one the window shows already not twice; not when the window does not take the chat', async () => { + const opened = async (when?: 'file in window' | 'not taken' | 'refused' | 'second active') => { + const { service, windows: [target] } = createService(['a']); + const file = editor(); + const notes = editor(); + target.main.group.honorsInactive = true; + if (when === 'file in window') { + target.main.group.open(file); + } + if (when === 'refused') { + target.main.group.refuseOpen = true; + } + if (when === 'not taken') { + Reflect.set(target.window.content, 'resolveChat', async () => undefined); + } + await service.open(URI.parse('test:/c'), { window: target.window, editors: { editors: [file, notes], activeEditor: when === 'second active' ? notes : file } }); + const name = (input: EditorInput) => input === file ? 'file' : 'notes'; + return { editors: target.main.group.testEditors.map(name), active: target.main.group.activeEditor && name(target.main.group.activeEditor) }; + }; + + assert.deepStrictEqual({ + taken: await opened(), + fileInWindow: await opened('file in window'), + notTaken: await opened('not taken'), + refused: await opened('refused'), + secondActive: await opened('second active'), + }, { + taken: { editors: ['file', 'notes'], active: 'file' }, + fileInWindow: { editors: ['file', 'notes'], active: 'file' }, + notTaken: { editors: [], active: null }, + refused: { editors: [], active: null }, + secondActive: { editors: ['file', 'notes'], active: 'notes' }, + }); + }); + + test('the editors a chat brings along into a window, the active one that is not the first included, do not count as an editor the user opens: a window showing only its chat stays so', async () => { + const opened = async (when: 'second active' | 'user opens after') => { + const { service, windows: [target] } = createService(['a']); + target.main.group.honorsInactive = true; + target.window.setLayoutMode(ChatWindowLayoutMode.ChatOnly); + const file = editor(); + const notes = editor(); + await service.open(URI.parse('test:/c'), { window: target.window, editors: { editors: [file, notes], activeEditor: when === 'second active' ? notes : file } }); + const handedOver = target.window.layoutMode.get(); + if (when === 'user opens after') { + target.main.group.open(editor()); + } + return { handedOver, editors: target.main.group.testEditors.length, mode: target.window.layoutMode.get() }; + }; + + assert.deepStrictEqual({ + secondActive: await opened('second active'), + userOpensAfter: await opened('user opens after'), + }, { + secondActive: { handedOver: ChatWindowLayoutMode.ChatOnly, editors: 2, mode: ChatWindowLayoutMode.ChatOnly }, + userOpensAfter: { handedOver: ChatWindowLayoutMode.ChatOnly, editors: 3, mode: ChatWindowLayoutMode.SideBySide }, + }); + }); + test('the editors a chat brings along into a window go back to where they came from when the chat does not open in that window: it does not resolve, or it shows in another window; one the window showed already stays there too, and the window\'s active editor stays active; with the group they came from gone, they go to the main part\'s active group', async () => { const opened = async (resolvesTo: 'nothing' | 'chat of another window', when?: 'file in window' | 'source gone') => { const { service, events, windows: [target, other], parts, setMainPart } = createService(['a', 'b']); diff --git a/src/vs/workbench/contrib/chatWindow/test/browser/chatWindowGrid.test.ts b/src/vs/workbench/contrib/chatWindow/test/browser/chatWindowGrid.test.ts index 21e2bfe42f31..35bf2f32f367 100644 --- a/src/vs/workbench/contrib/chatWindow/test/browser/chatWindowGrid.test.ts +++ b/src/vs/workbench/contrib/chatWindow/test/browser/chatWindowGrid.test.ts @@ -8,21 +8,21 @@ import * as sinon from 'sinon'; import { $ } from '../../../../../base/browser/dom.js'; import { Direction, IViewSize } from '../../../../../base/browser/ui/grid/grid.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; -import { autorun, constObservable, derived, IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { autorun, constObservable, derived, IObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; -import { IPartGridPartFactory, PartGridLocation } from '../../../../browser/parts/partGrid/partGrid.js'; +import { IPartGridPartFactory, PartGrid, PartGridLocation } from '../../../../browser/parts/partGrid/partGrid.js'; import { EditorInput } from '../../../../common/editor/editorInput.js'; import { IContentPart, IEditorGroup, IEditorGroupsService, IEditorPart } from '../../../../services/editor/common/editorGroupsService.js'; import { ChatWindowGrid, ChatWindowGridCell, IChatWindowGridChrome } from '../../browser/chatWindowGrid.js'; import { GroupModelChangeKind } from '../../../../common/editor.js'; import { IGroupModelChangeEvent } from '../../../../common/editor/editorGroupModel.js'; -import { ChatWindowLayoutMode, ChatWindowTerminalPosition } from '../../common/chatWindowLayout.js'; -import { ChatWindowPartSizes } from '../../common/chatWindowState.js'; +import { ChatWindowLayoutMode, ChatWindowSplitLayout, ChatWindowTerminalPosition } from '../../common/chatWindowLayout.js'; +import { ChatWindowPartSizes, IChatWindowArrangement } from '../../common/chatWindowState.js'; suite('Chat window grid', () => { @@ -303,6 +303,7 @@ suite('Chat window grid', () => { override get isEmpty() { return empty; } override readonly onDidModelChange = onDidModelChange.event; override getEditors() { return []; } + override focus(): void { } }(); const part = new class extends mock() { override readonly element = $(`.${name}`); @@ -314,6 +315,7 @@ suite('Chat window grid', () => { override readonly groups = [group]; override getGroups() { return this.groups; } override findGroup() { return undefined; } + override get activeGroup() { return group; } override readonly onDidAddGroup = Event.None; override readonly onDidRemoveGroup = Event.None; override readonly onDidMoveGroup = Event.None; @@ -426,23 +428,156 @@ suite('Chat window grid', () => { }); }); - test('a part moved beside the terminals goes back to its place, with its size, once the layout mode changes, also to a mode that arranges the parts as the one before', () => { + test('the main part moved to the left of the chat stays there as the editor hides and shows again', () => { + const { mode, grid, visible } = setup(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + const swapped = grid.partGrid!.describe(); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + const hidden = { shape: grid.partGrid!.describe(), visible: visible() }; + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + + assert.deepStrictEqual({ swapped, hidden, shown: { shape: grid.partGrid!.describe(), visible: visible() } }, { + swapped: 'column(titleRow, row(main, chat, strip))', + hidden: { shape: 'column(titleRow, row(main, chat, strip))', visible: [ChatWindowGridCell.TitleRow, ChatWindowGridCell.Chat, ChatWindowGridCell.Strip] }, + shown: { shape: 'column(titleRow, row(main, chat, strip))', visible: [ChatWindowGridCell.TitleRow, ChatWindowGridCell.Chat, ChatWindowGridCell.Main, ChatWindowGridCell.Strip] }, + }); + }); + + test('the parts the user moved stay where they are as the chat hides and shows again, in Editor Only, side by side or stacked; arranging them together the other way, or a reset, arranges them anew', () => { + const { mode, grid, visible } = setup(); + const shape = () => grid.partGrid!.describe(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + mode.set(ChatWindowLayoutMode.EditorOnly, undefined); + const chatHidden = { shape: shape(), visible: visible() }; + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const chatShown = shape(); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + const stacked = shape(); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Up }); + mode.set(ChatWindowLayoutMode.EditorOnly, undefined); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + const stackedChatShown = shape(); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const sideBySide = shape(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + grid.reset(); + + assert.deepStrictEqual({ chatHidden, chatShown, stacked, stackedChatShown, sideBySide, reset: shape() }, { + chatHidden: { shape: 'column(titleRow, row(main, chat, strip))', visible: [ChatWindowGridCell.TitleRow, ChatWindowGridCell.Main, ChatWindowGridCell.Strip] }, + chatShown: 'column(titleRow, row(main, chat, strip))', + stacked: 'column(titleRow, row(column(main, chat), strip))', + stackedChatShown: 'column(titleRow, row(column(chat, main), strip))', + sideBySide: 'column(titleRow, row(chat, main, strip))', + reset: 'column(titleRow, row(chat, main, strip))', + }); + }); + + test('the arrangement the user gave the parts, with its sizes, shows first in a new grid, such as after a reload, also exported while a part hides; the window\'s own arrangement exports none', () => { + const { mode, grid } = setup(); + const untouched = grid.exportArrangement(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + const mainWidth = grid.partGrid!.getCellSize(ChatWindowGridCell.Main).width; + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + const arrangement = grid.exportArrangement(); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), arrangement }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), undefined, undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + + assert.deepStrictEqual({ untouched, splitLayout: arrangement?.splitLayout, shape: restored.partGrid!.describe(), mainWidth: restored.partGrid!.getCellSize(ChatWindowGridCell.Main).width, exportedAgain: !!restored.exportArrangement() }, { + untouched: undefined, splitLayout: ChatWindowLayoutMode.SideBySide, shape: 'column(titleRow, row(main, chat, strip))', mainWidth, exportedAgain: true, + }); + }); + + test('a window that closes, its parts leaving the grid, still exports the arrangement the user last gave them, also without an export before', () => { + const exportOnClose = (arrange: (grid: ChatWindowGrid) => void) => { + const { grid } = setup(); + arrange(grid); + // As the window closes: it says so, then its parts leave the grid + grid.setClosing(true); + grid.partGrid!.removeCell(ChatWindowGridCell.Main); + grid.partGrid!.removeCell(ChatWindowGridCell.Chat); + return grid.exportArrangement() && JSON.stringify(collectIds(grid.exportArrangement()!.root)); + }; + const collectIds = (node: IChatWindowArrangement['root']): string[] => node.type === 'leaf' ? [node.data.id] : node.data.flatMap(collectIds); + const swap = (grid: ChatWindowGrid) => grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + + assert.deepStrictEqual({ + swapped: exportOnClose(swap), + swappedBackAfterAnExport: exportOnClose(grid => { + swap(grid); + grid.exportArrangement(); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Left }); + }), + }, { + swapped: JSON.stringify([ChatWindowGridCell.TitleRow, ChatWindowGridCell.Main, ChatWindowGridCell.Chat, ChatWindowGridCell.Strip]), + swappedBackAfterAnExport: undefined, + }); + }); + + test('an arrangement a new grid cannot show falls back to the window\'s: of the other split layout, of other cells, such as with a strip the window no longer has, or of a cell it does not know', () => { + const { grid } = setup(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + const arrangement = grid.exportArrangement()!; + const shapeOf = (cells: { strip?: IChatWindowGridChrome; arrangement: IChatWindowArrangement }, mode = ChatWindowLayoutMode.SideBySide) => { + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), ...cells }, constObservable(mode), constObservable(0), undefined, undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + return restored.partGrid!.describe(); + }; + const renamed = JSON.parse(JSON.stringify(arrangement).replace('"main"', '"other"')); + + assert.deepStrictEqual({ + stacked: shapeOf({ strip: createChrome(34), arrangement }, ChatWindowLayoutMode.Stacked), + withoutStrip: shapeOf({ arrangement }), + unknownCell: shapeOf({ strip: createChrome(34), arrangement: renamed }), + }, { + stacked: 'column(titleRow, row(column(main, chat), strip))', + withoutStrip: 'column(titleRow, row(chat, main))', + unknownCell: 'column(titleRow, row(chat, main, strip))', + }); + }); + + test('the arrangement the user gave the parts is without the terminals, which join it in a new grid where their position says', () => { + const { grid, open } = setupWithTerminals(); + open(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + const arrangement = grid.exportArrangement(); + const terminalsPart = createPartWithEditors('terminals'); + const terminals = observableValue('terminals', undefined); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals, arrangement }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.UnderEditor), undefined, editorGroupsService)); + restored.layout(1000, 800); + const beforeTerminals = restored.partGrid!.describe(); + terminals.set(terminalsPart.part, undefined); + terminalsPart.setEmpty(false); + + assert.deepStrictEqual({ exported: JSON.stringify(arrangement).includes('terminals'), beforeTerminals, withTerminals: restored.partGrid!.describe() }, { + exported: false, + beforeTerminals: 'column(titleRow, row(main, chat, strip))', + withTerminals: 'column(titleRow, row(column(main, terminals), chat, strip))', + }); + }); + + test('a part moved beside the terminals stays there, with its size, as the editor hides and shows again; arranging the parts stacked and side by side again puts it back in its place, with its size', () => { const { mode, grid, open } = setupWithTerminals(); open(); - const sizeOf = (cell: ChatWindowGridCell) => grid.partGrid!.getCellSize(cell).height; - const before = { shape: grid.partGrid!.describe(), main: sizeOf(ChatWindowGridCell.Main) }; + const state = () => ({ shape: grid.partGrid!.describe(), main: grid.partGrid!.getCellSize(ChatWindowGridCell.Main).height }); + const before = state(); grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Terminals, direction: Direction.Up }); - const moved = grid.partGrid!.describe(); + const moved = state(); mode.set(ChatWindowLayoutMode.ChatOnly, undefined); mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const editorShownAgain = state(); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); - assert.deepStrictEqual({ moved, after: { shape: grid.partGrid!.describe(), main: sizeOf(ChatWindowGridCell.Main) } }, { + assert.deepStrictEqual({ moved: moved.shape, editorShownAgain, arrangedAgain: state() }, { moved: 'column(titleRow, row(column(chat, main, terminals), strip))', - after: before + editorShownAgain: moved, + arrangedAgain: before, }); }); - test('each layout mode arranges the parts from its own arrangement: a part moved beside the terminals, adopted as cells showed meanwhile, and the main part hidden in Chat Only come back to their places at their sizes', () => { + test('the main part hidden in Chat Only shows again where it was, at its size: beside the chat with the terminals under it, or where the user moved it, also as cells showed meanwhile', () => { const roundTrip = (position: ChatWindowTerminalPosition, move: boolean) => { const mode = observableValue('mode', ChatWindowLayoutMode.SideBySide); const titleRowVisible = observableValue('titleRowVisible', true); @@ -457,24 +592,24 @@ suite('Chat window grid', () => { const { width, height } = grid.partGrid!.getCellSize(ChatWindowGridCell.Main); return { shape: grid.partGrid!.describe(), main: `${width}x${height}` }; }; - const before = state(); if (move) { // Dropped on the top edge of the terminals; the title row then shows again, as the chat no longer leads grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Terminals, direction: Direction.Up }); titleRowVisible.set(false, undefined); titleRowVisible.set(true, undefined); } + const before = state(); mode.set(ChatWindowLayoutMode.ChatOnly, undefined); mode.set(ChatWindowLayoutMode.SideBySide, undefined); - return { back: JSON.stringify(state()) === JSON.stringify(before) }; + return { back: JSON.stringify(state()) === JSON.stringify(before), shape: before.shape }; }; assert.deepStrictEqual({ movedAboveFullWidthTerminals: roundTrip(ChatWindowTerminalPosition.FullWidth, true), terminalsUnderTheEditor: roundTrip(ChatWindowTerminalPosition.UnderEditor, false), }, { - movedAboveFullWidthTerminals: { back: true }, - terminalsUnderTheEditor: { back: true }, + movedAboveFullWidthTerminals: { back: true, shape: 'column(titleRow, row(column(chat, main, terminals), strip))' }, + terminalsUnderTheEditor: { back: true, shape: 'column(titleRow, row(chat, column(main, terminals), strip))' }, }); }); @@ -496,7 +631,7 @@ suite('Chat window grid', () => { ]); }); - test('a layout mode that arranges the parts again, as a part was moved or its arrangement differs, keeps the focus where it was in them', () => { + test('hiding the editor keeps a part the user moved, and the grid; arranging the parts the other way arranges them again and keeps the focus where it was in them', () => { const { mode, grid, open, container } = setupWithTerminals(); open(); const input = container.querySelector('.chat')!.appendChild($('input')); @@ -511,7 +646,7 @@ suite('Chat window grid', () => { const otherArrangement = { rebuilt: grid.partGrid !== chatOnlyGrid, focused: mainWindow.document.activeElement === input }; assert.deepStrictEqual({ afterMove, otherArrangement }, { - afterMove: { rebuilt: true, shape: 'column(titleRow, row(column(row(chat, main), terminals), strip))', focused: true }, + afterMove: { rebuilt: false, shape: 'column(titleRow, row(column(chat, main, terminals), strip))', focused: true }, otherArrangement: { rebuilt: true, focused: true }, }); }); @@ -670,7 +805,7 @@ suite('Chat window grid', () => { 'sideBySide/underEditor': 'column(titleRow, row(chat, column(main, terminals), strip))', 'chatOnly/fullWidth': 'column(titleRow, row(column(row(chat, main), terminals), strip))', 'chatOnly/underChat': 'column(titleRow, row(column(chat, terminals), main, strip))', - 'chatOnly/underEditor': 'column(titleRow, row(column(row(chat, main), terminals), strip))', + 'chatOnly/underEditor': 'column(titleRow, row(chat, column(main, terminals), strip))', 'stacked/fullWidth': 'column(titleRow, row(column(main, chat, terminals), strip))', 'stacked/underChat': 'column(titleRow, row(column(main, chat, terminals), strip))', 'stacked/underEditor': 'column(titleRow, row(column(main, chat, terminals), strip))', @@ -1186,7 +1321,7 @@ suite('Chat window grid', () => { assert.deepStrictEqual({ user, forced, again: roundTrip() }, { user: '476/682', forced: '505/653', again: '476/682' }); }); - test('closing the editor area, which shows only the chat, with the terminals under the editor keeps the terminals, across the window and as tall, and they go back under the editor as it shows again', () => { + test('closing the editor area, which shows only the chat, with the terminals under the editor keeps the terminals in their place, beside the chat, and they show as tall as they were under the editor as it shows again', () => { const { mode, position, grid, open, height, userResize } = setupWithTerminals(); position.set(ChatWindowTerminalPosition.UnderEditor, undefined); open(); @@ -1203,11 +1338,878 @@ suite('Chat window grid', () => { mode.set(ChatWindowLayoutMode.SideBySide, undefined); assert.deepStrictEqual({ editorAreaClosed, editorShownAgain: { ...read(), height: height() } }, { - editorAreaClosed: { topology: 'column(titleRow, row(column(row(chat, main), terminals), strip))', visible: [ChatWindowGridCell.Chat, ChatWindowGridCell.Terminals], terminalsVisible: true, height: 200, acrossTheWindow: true }, + editorAreaClosed: { topology: 'column(titleRow, row(chat, column(main, terminals), strip))', visible: [ChatWindowGridCell.Chat, ChatWindowGridCell.Terminals], terminalsVisible: true, height: 770, acrossTheWindow: false }, editorShownAgain: { topology: 'column(titleRow, row(chat, column(main, terminals), strip))', visible: [ChatWindowGridCell.Chat, ChatWindowGridCell.Main, ChatWindowGridCell.Terminals], terminalsVisible: true, height: 200 }, }); }); + test('the main part arranged side by side while hidden, as Stacked is switched off in Chat Only, shows again at its share beside the terminals under it, which are as tall as the user made them', () => { + const mode = observableValue('mode', ChatWindowLayoutMode.Stacked); + const splitLayout = observableValue('splitLayout', ChatWindowLayoutMode.Stacked); + const terminalsPart = createPartWithEditors('terminals'); + const terminals = observableValue('terminals', undefined); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals, splitLayout }, mode, constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.UnderEditor), undefined, editorGroupsService)); + grid.layout(1000, 800); + terminals.set(terminalsPart.part, undefined); + terminalsPart.setEmpty(false); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 200); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + // Toggle Arrangement while only the chat shows + splitLayout.set(ChatWindowLayoutMode.SideBySide, undefined); + const hidden = grid.partGrid!.describe(); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const size = (cell: ChatWindowGridCell) => grid.partGrid!.getCellSize(cell).height; + + assert.deepStrictEqual({ hidden, shown: { main: size(ChatWindowGridCell.Main), terminals: size(ChatWindowGridCell.Terminals) } }, { + hidden: 'column(titleRow, row(chat, column(main, terminals), strip))', + shown: { main: 570, terminals: 200 }, + }); + }); + + test('the height the user gives the terminals while the main part is hidden is theirs as it shows again; the others share the rest as they did', () => { + const { mode, grid, open, height, userResize } = setupWithTerminals(ChatWindowLayoutMode.Stacked); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 200); + const size = (cell: ChatWindowGridCell) => grid.partGrid!.getCellSize(cell).height; + const before = { main: size(ChatWindowGridCell.Main), chat: size(ChatWindowGridCell.Chat) }; + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + userResize(ChatWindowGridCell.Terminals, 'top', 300); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + const share = (before.main + before.chat - 100) / (before.main + before.chat); + + assert.deepStrictEqual({ terminals: height(), main: size(ChatWindowGridCell.Main), chat: size(ChatWindowGridCell.Chat) }, { + terminals: 300, main: Math.round(before.main * share), chat: before.chat + before.main - 100 - Math.round(before.main * share), + }); + }); + + test('a part hidden in Stacked, with the parts moved and the terminals below them, shows again in a new grid at the share it had, after a reload', () => { + const { mode, grid, open } = setupWithTerminals(ChatWindowLayoutMode.Stacked); + open(); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Up }); + const size = (target: ChatWindowGrid, cell: ChatWindowGridCell) => target.partGrid!.getCellSize(cell).height; + const share = size(grid, ChatWindowGridCell.Main) / (size(grid, ChatWindowGridCell.Main) + size(grid, ChatWindowGridCell.Chat)); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + const arrangement = grid.exportArrangement(); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const restoredMode = observableValue('mode', ChatWindowLayoutMode.ChatOnly); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(ChatWindowLayoutMode.Stacked), arrangement }, restoredMode, constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.FullWidth), undefined, editorGroupsService)); + restored.layout(1000, 800); + restoredMode.set(ChatWindowLayoutMode.Stacked, undefined); + const restoredShare = size(restored, ChatWindowGridCell.Main) / (size(restored, ChatWindowGridCell.Main) + size(restored, ChatWindowGridCell.Chat)); + + assert.deepStrictEqual({ shape: restored.partGrid!.describe(), share: Math.round(restoredShare * 100) }, { shape: 'column(titleRow, row(column(chat, main, terminals), strip))', share: Math.round(share * 100) }); + }); + + test('the terminals keep the height they had as the main part hid when it shows again in a window resized meanwhile; the others share the rest', () => { + const { mode, grid, open, height } = setupWithTerminals(ChatWindowLayoutMode.Stacked); + open(); + const before = height(); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + grid.layout(1000, 900); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + + assert.deepStrictEqual({ before, after: height() }, { before, after: before }); + }); + + test('the terminals squeezed as a part shows in a window too short for their height take it back as the window grows', () => { + const { mode, grid, position, open, userResize, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + grid.layout(1000, 450); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const squeezed = height(); + grid.layout(1000, 800); + + assert.deepStrictEqual({ squeezed: squeezed < 400, grown: height(), saved: grid.exportSizes().terminals?.[ChatWindowGridCell.Terminals]?.height }, { squeezed: true, grown: 400, saved: 400 }); + }); + + test('the terminals at their default height, squeezed as a part shows in a window too short for it, take it back as the window grows', () => { + const { mode, grid, position, open, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + const initial = height(); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + grid.layout(1000, 300); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const squeezed = height(); + grid.layout(1000, 800); + + assert.deepStrictEqual({ squeezed: squeezed < initial, grown: height(), saved: grid.exportSizes().terminals?.[ChatWindowGridCell.Terminals]?.height }, { squeezed: true, grown: initial, saved: undefined }); + }); + + test('the terminals at their default height, not squeezed, keep their height as the window grows', () => { + const { grid, position, open, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + const initial = height(); + const heights = [1000, 1200, 800].map(windowHeight => { + grid.layout(1000, windowHeight); + return height(); + }); + + assert.deepStrictEqual(heights, [initial, initial, initial]); + }); + + test('the terminals a user dragged shorter, or that were never given a height, keep their height as the window grows', () => { + const { grid, position, open, userResize, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + const initial = height(); + grid.layout(1000, 1000); + const untouched = height(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + userResize(ChatWindowGridCell.Terminals, 'top', 250); + grid.layout(1000, 1200); + + assert.deepStrictEqual({ untouched: untouched === initial, dragged: height() }, { untouched: true, dragged: 250 }); + }); + + test('the terminals that take their height back as the window grows while a part is hidden keep it as that part shows', () => { + const { mode, grid, position, open, userResize, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + grid.layout(1000, 450); + const squeezed = height(); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + grid.layout(1000, 800); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + + assert.deepStrictEqual({ squeezed: squeezed < 400, shown: height() }, { squeezed: true, shown: 400 }); + }); + + test('the terminals in a row above a part, as a user arranged them, do not squeeze that part to take their height back', () => { + const { grid, position, open, userResize } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Down }); + grid.partGrid!.moveCell(ChatWindowGridCell.Terminals, { reference: ChatWindowGridCell.Chat, direction: Direction.Right }); + grid.layout(1000, 450); + const main = grid.partGrid!.getCellSize(ChatWindowGridCell.Main).height; + + assert.deepStrictEqual({ mainAtItsMinimum: main <= 50 }, { mainAtItsMinimum: false }); + }); + + test('the terminals that shrank as a part was dropped at an edge of the window, or in a layout that does not grow the window, keep their height', () => { + const { grid, position, open, userResize, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { edge: Direction.Down }); + const arranged = height(); + grid.layout(1000, 800); + const same = height(); + grid.layout(1200, 800); + + assert.deepStrictEqual({ arranged: arranged < 400, same, widthOnly: height() }, { arranged: true, same: arranged, widthOnly: arranged }); + }); + + test('the terminals at their default height, shrunk as a part was dropped at an edge of the window, take it back as the window grows', () => { + const { grid, position, open, height } = setupWithTerminals(); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + const initial = height(); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { edge: Direction.Down }); + const arranged = height(); + grid.layout(1000, 1000); + + assert.deepStrictEqual({ arranged: arranged < initial, grown: height() }, { arranged: true, grown: initial }); + }); + + test('a row among the parts above the terminals gives room to them as a unit, in proportion to the parts beside it', () => { + const { grid, open, userResize, height } = setupWithTerminals(); + open(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { edge: Direction.Up }); + userResize(ChatWindowGridCell.Terminals, 'top', 300); + const heights = () => [ChatWindowGridCell.Main, ChatWindowGridCell.Chat].map(cell => grid.partGrid!.getCellSize(cell).height); + const before = heights(); + grid.layout(1000, 400); + const squeezed = height() < 300; + grid.layout(1000, 800); + + assert.deepStrictEqual({ squeezed, terminals: height(), parts: heights().map(size => Math.round(size / 10)) }, { squeezed: true, terminals: 300, parts: before.map(size => Math.round(size / 10)) }); + }); + + test('with parts nested deeper than a row above them, the terminals take their height back as a plain resize does', () => { + const editor = new class extends mock() { + override readonly typeId = 'testEditor'; + override readonly resource = undefined; + override getName() { return 'file'; } + }(); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part) }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.FullWidth), { createPart: () => ({ id: 'created', part: createPart('created') }) }, editorGroupsService)); + grid.layout(1000, 800); + grid.partGrid!.moveEditorsIntoNewPart([{ editor, groupId: 1 }], { edge: Direction.Up }, { dropped: true }); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: 'created', direction: Direction.Left }); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: 'created', direction: Direction.Down }); + const arrangement = grid.partGrid!.describe(); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 300); + const height = () => grid.partGrid!.getCellSize(ChatWindowGridCell.Terminals).height; + grid.layout(1000, 400); + const squeezed = height() < 300; + grid.layout(1000, 800); + + assert.deepStrictEqual({ arrangement, squeezed, terminals: height() }, { arrangement: 'column(titleRow, row(column(row(main, column(created, chat)), terminals), strip))', squeezed: true, terminals: 300 }); + }); + + test('in Stacked, the chat and the main part keep their shares as the terminals take their height back', () => { + const { mode, grid, position, open, userResize } = setupWithTerminals(ChatWindowLayoutMode.ChatOnly); + position.set(ChatWindowTerminalPosition.FullWidth, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 400); + grid.layout(1000, 450); + mode.set(ChatWindowLayoutMode.Stacked, undefined); + const heights = () => [ChatWindowGridCell.Main, ChatWindowGridCell.Chat, ChatWindowGridCell.Terminals].map(cell => grid.partGrid!.getCellSize(cell).height); + const squeezed = heights(); + grid.layout(1000, 800); + const grown = heights(); + + assert.deepStrictEqual({ squeezedTerminals: squeezed[2] < 400, terminals: grown[2], ratio: Math.round(grown[0] / grown[1] * 10) }, { squeezedTerminals: true, terminals: 400, ratio: Math.round(squeezed[0] / squeezed[1] * 10) }); + }); + + test('a part hidden while the terminals open shows again at its share, beside the terminals at their height: the chat in Stacked, and the main part with the terminals under it', () => { + const roundTrip = (initial: ChatWindowLayoutMode, hiding: ChatWindowLayoutMode, position: ChatWindowTerminalPosition, cell: ChatWindowGridCell) => { + const { mode, position: terminalPosition, grid, open, height } = setupWithTerminals(initial); + terminalPosition.set(position, undefined); + const size = (target: ChatWindowGridCell) => grid.partGrid!.getCellSize(target).height; + mode.set(hiding, undefined); + open(); + mode.set(initial, undefined); + return { minimum: size(cell) <= 50, terminals: height() }; + }; + + assert.deepStrictEqual({ + chatInStacked: roundTrip(ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.EditorOnly, ChatWindowTerminalPosition.FullWidth, ChatWindowGridCell.Chat), + mainWithTerminalsUnderIt: roundTrip(ChatWindowLayoutMode.SideBySide, ChatWindowLayoutMode.ChatOnly, ChatWindowTerminalPosition.UnderEditor, ChatWindowGridCell.Main), + }, { + chatInStacked: { minimum: false, terminals: 240 }, + mainWithTerminalsUnderIt: { minimum: false, terminals: 240 }, + }); + }); + + test('with the terminals joining an arrangement the user moved, moving the parts back as the window arranges them remembers the sizes the user gives them again', () => { + const { grid, open, position, userResize } = setupWithTerminals(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { edge: Direction.Left }); + const shape = grid.partGrid!.describe(); + userResize(ChatWindowGridCell.Chat, 'right', 300); + + assert.deepStrictEqual({ shape, arrangement: grid.exportArrangement(), chat: grid.exportSizes()['column(titleRow,row(chat,column(main,terminals),strip))']?.[ChatWindowGridCell.Chat]?.width }, { + shape: 'column(titleRow, row(chat, column(main, terminals), strip))', arrangement: undefined, chat: 300, + }); + }); + + test('a width the user gives the terminals\' column while the main part above them is hidden is the main part\'s after a reload, and the terminals keep the height the user gave them, not the one they fill meanwhile', () => { + const { mode, grid, open, position, userResize } = setupWithTerminals(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 200); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + userResize(ChatWindowGridCell.Terminals, 'right', 300); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part), arrangement: grid.exportArrangement() }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), grid.exportSizes(), constObservable(ChatWindowTerminalPosition.UnderEditor), undefined, editorGroupsService)); + restored.layout(1000, 800); + const size = (cell: ChatWindowGridCell) => restored.partGrid!.getCellSize(cell); + + assert.deepStrictEqual({ hidden: grid.partGrid!.describe(), shape: restored.partGrid!.describe(), main: size(ChatWindowGridCell.Main).width, terminals: size(ChatWindowGridCell.Terminals).height }, { + hidden: 'column(titleRow, row(column(main, terminals), chat, strip))', shape: 'column(titleRow, row(column(main, terminals), chat, strip))', main: 300, terminals: 200, + }); + }); + + test('while a part is hidden, a width the terminals take or a reset of a sash leaves the height the user gave them, rather than the one they fill there: the main part above them, or the chat', () => { + const run = (hide: ChatWindowLayoutMode, position: ChatWindowTerminalPosition, action: 'width' | 'reset') => { + const { mode, grid, open, position: terminalPosition, userResize, container } = setupWithTerminals(); + terminalPosition.set(position, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 200); + mode.set(hide, undefined); + // The sash between the terminals' column and the chat: at the right of the chat, or of the terminals under it + const leftOfSash = position === ChatWindowTerminalPosition.UnderEditor ? ChatWindowGridCell.Chat : ChatWindowGridCell.Terminals; + if (action === 'width') { + userResize(leftOfSash, 'right', 300); + } else { + const cell = container.querySelector(`[data-part-grid-cell="${leftOfSash}"]`)!.getBoundingClientRect(); + const sash = [...container.querySelectorAll('.monaco-sash.vertical')].find(candidate => Math.abs(candidate.getBoundingClientRect().left + candidate.getBoundingClientRect().width / 2 - cell.right) < 8)!; + sash.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + } + return grid.exportSizes().terminals?.[ChatWindowGridCell.Terminals]?.height; + }; + + assert.deepStrictEqual({ + mainHiddenWidth: run(ChatWindowLayoutMode.ChatOnly, ChatWindowTerminalPosition.UnderEditor, 'width'), + mainHiddenReset: run(ChatWindowLayoutMode.ChatOnly, ChatWindowTerminalPosition.UnderEditor, 'reset'), + chatHiddenWidth: run(ChatWindowLayoutMode.EditorOnly, ChatWindowTerminalPosition.UnderChat, 'width'), + chatHiddenReset: run(ChatWindowLayoutMode.EditorOnly, ChatWindowTerminalPosition.UnderChat, 'reset'), + }, { mainHiddenWidth: 200, mainHiddenReset: 200, chatHiddenWidth: 200, chatHiddenReset: 200 }); + }); + + test('sizes the user gives the parts as the window arranges them, while one of them hides, come back after a reload as both show: a width beside the terminals under the main part, and the terminals\' height stacked', () => { + const reload = (grid: ChatWindowGrid, splitLayout: ChatWindowSplitLayout, position: ChatWindowTerminalPosition) => { + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(splitLayout), arrangement: grid.exportArrangement() }, constObservable(splitLayout), constObservable(0), grid.exportSizes(), constObservable(position), undefined, editorGroupsService)); + restored.layout(1000, 800); + return restored; + }; + const sizes = (grid: ChatWindowGrid) => Object.fromEntries([ChatWindowGridCell.Chat, ChatWindowGridCell.Main, ChatWindowGridCell.Terminals].map(cell => { + const { width, height } = grid.partGrid!.getCellSize(cell); + return [cell, `${width}x${height}`]; + })); + + const sideBySide = setupWithTerminals(); + sideBySide.position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + sideBySide.open(); + sideBySide.userResize(ChatWindowGridCell.Chat, 'right', 400); + sideBySide.userResize(ChatWindowGridCell.Terminals, 'top', 200); + sideBySide.mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + sideBySide.userResize(ChatWindowGridCell.Chat, 'right', 300); + sideBySide.mode.set(ChatWindowLayoutMode.SideBySide, undefined); + const sideBySideShown = sizes(sideBySide.grid); + + const stacked = setupWithTerminals(ChatWindowLayoutMode.Stacked); + stacked.open(); + stacked.userResize(ChatWindowGridCell.Terminals, 'top', 200); + stacked.userResize(ChatWindowGridCell.Chat, 'top', 200); + stacked.mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + stacked.userResize(ChatWindowGridCell.Terminals, 'top', 300); + stacked.mode.set(ChatWindowLayoutMode.Stacked, undefined); + const stackedShown = sizes(stacked.grid); + + assert.deepStrictEqual({ + sideBySide: { shown: sideBySideShown, reloaded: sizes(reload(sideBySide.grid, ChatWindowLayoutMode.SideBySide, ChatWindowTerminalPosition.UnderEditor)) }, + stacked: { shown: stackedShown, reloaded: sizes(reload(stacked.grid, ChatWindowLayoutMode.Stacked, ChatWindowTerminalPosition.FullWidth)) }, + }, { + sideBySide: { shown: sideBySideShown, reloaded: sideBySideShown }, + stacked: { shown: stackedShown, reloaded: stackedShown }, + }); + assert.deepStrictEqual({ chat: sideBySideShown[ChatWindowGridCell.Chat], terminals: stackedShown[ChatWindowGridCell.Terminals] }, { chat: '300x770', terminals: '966x300' }); + }); + + test('sizes an earlier version remembered for a mode that hides a part are not read: a window opening in Chat Only shows the main part again at the split the user gave both', () => { + const mode = observableValue('mode', ChatWindowLayoutMode.ChatOnly); + const sizes: ChatWindowPartSizes = { + 'column(titleRow,row(chat,main,strip))': { [ChatWindowGridCell.Chat]: { width: 300, height: 770 } }, + 'column(titleRow,row(chat,main,strip))|main hidden': { [ChatWindowGridCell.Chat]: { width: 900, height: 770 } }, + }; + const grid = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), splitLayout: constObservable(ChatWindowLayoutMode.SideBySide) }, mode, constObservable(0), sizes, undefined, undefined, editorGroupsService)); + grid.layout(1000, 800); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + + assert.deepStrictEqual({ chat: grid.partGrid!.getCellSize(ChatWindowGridCell.Chat).width, kept: grid.exportSizes()['column(titleRow,row(chat,main,strip))|main hidden'] }, { + chat: 300, kept: { [ChatWindowGridCell.Chat]: { width: 900, height: 770 } }, + }); + }); + + test('a window that opens with a part hidden shows it again at the split the user gave both: the main part stacked, and the chat side by side', () => { + const run = (splitLayout: ChatWindowSplitLayout, hide: ChatWindowLayoutMode, edge: 'top' | 'right', size: number) => { + const { mode, grid, userResize } = setupWithTerminals(splitLayout); + userResize(ChatWindowGridCell.Chat, edge, size); + mode.set(hide, undefined); + const restoredMode = observableValue('mode', hide); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), splitLayout: constObservable(splitLayout), arrangement: grid.exportArrangement() }, restoredMode, constObservable(0), grid.exportSizes(), undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + restoredMode.set(splitLayout, undefined); + return restored.partGrid!.getCellSize(ChatWindowGridCell.Chat)[edge === 'top' ? 'height' : 'width']; + }; + + assert.deepStrictEqual({ + stacked: run(ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.ChatOnly, 'top', 200), + sideBySide: run(ChatWindowLayoutMode.SideBySide, ChatWindowLayoutMode.EditorOnly, 'right', 300), + }, { stacked: 200, sideBySide: 300 }); + }); + + test('a reset of the sash above the terminals while a part is hidden gives them the height they take then, as the part shows again, and remembers it for every arrangement: across the window side by side, and stacked', () => { + const run = (splitLayout: ChatWindowSplitLayout) => { + const { mode, grid, open, height, userResize, container } = setupWithTerminals(splitLayout); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 200); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + const cell = container.querySelector(`[data-part-grid-cell="${ChatWindowGridCell.Terminals}"]`)!.getBoundingClientRect(); + const sash = [...container.querySelectorAll('.monaco-sash.horizontal')].find(candidate => Math.abs(candidate.getBoundingClientRect().top + candidate.getBoundingClientRect().height / 2 - cell.top) < 8)!; + sash.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + const reset = height(); + mode.set(splitLayout, undefined); + return { reset: reset !== 200, shown: height() === reset, remembered: grid.exportSizes().terminals?.[ChatWindowGridCell.Terminals]?.height === reset }; + }; + + assert.deepStrictEqual({ sideBySide: run(ChatWindowLayoutMode.SideBySide), stacked: run(ChatWindowLayoutMode.Stacked) }, { + sideBySide: { reset: true, shown: true, remembered: true }, + stacked: { reset: true, shown: true, remembered: true }, + }); + }); + + test('without a title row, a width the user gives the chat while the main part is hidden, after the terminals joined under it, comes back after a reload', () => { + const mode = observableValue('mode', ChatWindowLayoutMode.SideBySide); + const terminals = observableValue('terminals', undefined); + const terminalsPart = createPartWithEditors('terminals'); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { main: createPart('main'), chat: createPart('chat'), strip: createChrome(34), terminals, splitLayout: constObservable(ChatWindowLayoutMode.SideBySide) }, mode, constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.UnderEditor), undefined, editorGroupsService)); + grid.layout(1000, 800); + drag(container, grid, ChatWindowGridCell.Chat, 'right', 300); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + terminals.set(terminalsPart.part, undefined); + terminalsPart.setEmpty(false); + drag(container, grid, ChatWindowGridCell.Chat, 'right', 400); + const restoredTerminals = createPartWithEditors('terminals'); + restoredTerminals.setEmpty(false); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), strip: createChrome(34), terminals: constObservable(restoredTerminals.part), splitLayout: constObservable(ChatWindowLayoutMode.SideBySide), arrangement: grid.exportArrangement() }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), grid.exportSizes(), constObservable(ChatWindowTerminalPosition.UnderEditor), undefined, editorGroupsService)); + restored.layout(1000, 800); + + assert.deepStrictEqual({ shape: restored.partGrid!.describe(), chat: restored.partGrid!.getCellSize(ChatWindowGridCell.Chat).width }, { shape: 'row(chat, column(main, terminals), strip)', chat: 400 }); + }); + + test('a window that opens with a part hidden and the strip hidden by its setting shows the part again at the split the user gave both', () => { + const mode = observableValue('mode', ChatWindowLayoutMode.ChatOnly); + const sizes: ChatWindowPartSizes = { 'column(titleRow,row(chat,main,strip))': { [ChatWindowGridCell.Chat]: { width: 300, height: 770 } } }; + const grid = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: { ...createChrome(34), visible: constObservable(false) }, splitLayout: constObservable(ChatWindowLayoutMode.SideBySide) }, mode, constObservable(0), sizes, undefined, undefined, editorGroupsService)); + grid.layout(1000, 800); + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + + assert.deepStrictEqual(grid.partGrid!.getCellSize(ChatWindowGridCell.Chat).width, 300); + }); + + test('switching right from Chat Only to Editor Only, or back, shows the hidden part again at its share beside the terminals under it, as tall as the user made them, also as both show then', () => { + const run = (position: ChatWindowTerminalPosition, first: ChatWindowLayoutMode, second: ChatWindowLayoutMode, cell: ChatWindowGridCell) => { + const { mode, grid, open, position: terminalPosition, height, userResize } = setupWithTerminals(); + terminalPosition.set(position, undefined); + open(); + userResize(ChatWindowGridCell.Terminals, 'top', 200); + const before = grid.partGrid!.getCellSize(cell).height; + mode.set(first, undefined); + mode.set(second, undefined); + const switched = { part: grid.partGrid!.getCellSize(cell).height, terminals: height() }; + mode.set(ChatWindowLayoutMode.SideBySide, undefined); + return { before, switched, bothShow: { part: grid.partGrid!.getCellSize(cell).height, terminals: height() } }; + }; + const underEditor = run(ChatWindowTerminalPosition.UnderEditor, ChatWindowLayoutMode.ChatOnly, ChatWindowLayoutMode.EditorOnly, ChatWindowGridCell.Main); + const underChat = run(ChatWindowTerminalPosition.UnderChat, ChatWindowLayoutMode.EditorOnly, ChatWindowLayoutMode.ChatOnly, ChatWindowGridCell.Chat); + + assert.deepStrictEqual({ underEditor, underChat }, { + underEditor: { before: 570, switched: { part: 570, terminals: 200 }, bothShow: { part: 570, terminals: 200 } }, + underChat: { before: 570, switched: { part: 570, terminals: 200 }, bothShow: { part: 570, terminals: 200 } }, + }); + }); + + test('the terminals keep the height the user gave them as a part hidden with the title row shows again: in a window opening so, and as the title row hides with the part', () => { + const run = (opening: boolean) => { + const mode = observableValue('mode', opening ? ChatWindowLayoutMode.ChatOnly : ChatWindowLayoutMode.Stacked); + const titleRowVisible = observableValue('titleRowVisible', !opening); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const sizes: ChatWindowPartSizes = { terminals: { [ChatWindowGridCell.Terminals]: { width: 966, height: 200 } } }; + const grid = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: { ...createChrome(30), visible: titleRowVisible }, strip: createChrome(34), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(ChatWindowLayoutMode.Stacked) }, mode, constObservable(0), sizes, undefined, undefined, editorGroupsService)); + grid.layout(1000, 800); + if (!opening) { + transaction(tx => { + titleRowVisible.set(false, tx); + mode.set(ChatWindowLayoutMode.ChatOnly, tx); + }); + } + mode.set(ChatWindowLayoutMode.Stacked, undefined); + return grid.partGrid!.getCellSize(ChatWindowGridCell.Terminals).height; + }; + + assert.deepStrictEqual({ opening: run(true), hidingWithThePart: run(false) }, { opening: 200, hidingWithThePart: 200 }); + }); + + test('a width the user gives the parts while one is hidden in a window too short for the terminals\' height comes back after a reload, and so does that height: the main part above them, or the chat', () => { + const run = (position: ChatWindowTerminalPosition, hide: ChatWindowLayoutMode, sized: ChatWindowGridCell) => { + const { mode, grid, open, position: terminalPosition, userResize, container } = setupWithTerminals(); + terminalPosition.set(position, undefined); + open(); + userResize(sized, 'right', 300); + userResize(ChatWindowGridCell.Terminals, 'top', 600); + mode.set(hide, undefined); + grid.layout(1000, 500); + drag(container, grid, sized, 'right', 400); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(ChatWindowLayoutMode.SideBySide), arrangement: grid.exportArrangement() }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), grid.exportSizes(), constObservable(position), undefined, editorGroupsService)); + restored.layout(1000, 800); + return { width: restored.partGrid!.getCellSize(sized).width, terminals: restored.partGrid!.getCellSize(ChatWindowGridCell.Terminals).height }; + }; + + assert.deepStrictEqual({ + mainHidden: run(ChatWindowTerminalPosition.UnderEditor, ChatWindowLayoutMode.ChatOnly, ChatWindowGridCell.Chat), + chatHidden: run(ChatWindowTerminalPosition.UnderChat, ChatWindowLayoutMode.EditorOnly, ChatWindowGridCell.Terminals), + }, { mainHidden: { width: 400, terminals: 600 }, chatHidden: { width: 400, terminals: 600 } }); + }); + + test('as the window is too short for the terminals beside a hidden part, or leaves less room than the parts need beside them, a width the user gives the parts leaves their heights as the user gave them, whichever part hides, and the title row keeps its height in the arrangement saved', () => { + const editor = new class extends mock() { + override readonly typeId = 'testEditor'; + override readonly resource = undefined; + override getName() { return 'file'; } + }(); + const stackedWithCreatedPart = (height: number, hide: ChatWindowLayoutMode) => { + const mode = observableValue('mode', ChatWindowLayoutMode.Stacked); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const createdPart = createPartWithEditors('created'); + createdPart.setEmpty(false); + const main = createPart('main'); + sourcePart = main; + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { main, chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(ChatWindowLayoutMode.Stacked) }, mode, constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.FullWidth), { createPart: () => ({ id: 'created', part: createdPart.part }) }, editorGroupsService)); + grid.layout(1000, 800); + grid.partGrid!.moveEditorsIntoNewPart([{ editor, groupId: 1 }], { edge: Direction.Right }); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 500); + drag(container, grid, ChatWindowGridCell.Chat, 'top', 130); + mode.set(hide, undefined); + grid.layout(1000, height); + const shown = hide === ChatWindowLayoutMode.ChatOnly ? ChatWindowGridCell.Chat : ChatWindowGridCell.Main; + const width = grid.partGrid!.getCellSize(shown).width - 40; + drag(container, grid, shown, 'right', width); + sourcePart = undefined; + const restoredTerminals = createPartWithEditors('terminals'); + restoredTerminals.setEmpty(false); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), terminals: constObservable(restoredTerminals.part), splitLayout: constObservable(ChatWindowLayoutMode.Stacked), arrangement: grid.exportArrangement() }, constObservable(ChatWindowLayoutMode.Stacked), constObservable(0), grid.exportSizes(), constObservable(ChatWindowTerminalPosition.FullWidth), undefined, editorGroupsService)); + restored.layout(1000, 800); + const size = (cell: ChatWindowGridCell) => restored.partGrid!.getCellSize(cell).height; + return { chat: size(ChatWindowGridCell.Chat), terminals: size(ChatWindowGridCell.Terminals), widthRemembered: grid.exportSizes()['column(titleRow,row(column(main,chat,terminals),strip))']?.[shown]?.width === width }; + }; + const reorderedWithoutStrip = () => { + const mode = observableValue('mode', ChatWindowLayoutMode.Stacked); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), terminals: constObservable(terminalsPart.part), splitLayout: constObservable(ChatWindowLayoutMode.Stacked) }, mode, constObservable(0), undefined, constObservable(ChatWindowTerminalPosition.FullWidth), undefined, editorGroupsService)); + grid.layout(1000, 800); + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Up }); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 500); + const share = (target: ChatWindowGrid) => { + const [main, chat] = [target.partGrid!.getCellSize(ChatWindowGridCell.Main).height, target.partGrid!.getCellSize(ChatWindowGridCell.Chat).height]; + return Math.round(main * 100 / (main + chat)); + }; + const before = share(grid); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + grid.layout(1000, 300); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), splitLayout: constObservable(ChatWindowLayoutMode.Stacked), arrangement: grid.exportArrangement() }, constObservable(ChatWindowLayoutMode.Stacked), constObservable(0), undefined, undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + return { shape: restored.partGrid!.describe(), withinAPoint: Math.abs(share(restored) - before) <= 1 }; + }; + + const { ChatOnly, EditorOnly } = { ChatOnly: ChatWindowLayoutMode.ChatOnly, EditorOnly: ChatWindowLayoutMode.EditorOnly } as const; + assert.deepStrictEqual({ + stackedWithCreatedPart: stackedWithCreatedPart(500, ChatOnly), + stackedWithCreatedPartChatHidden: stackedWithCreatedPart(500, EditorOnly), + // Room for the parts beside the terminals, 70, less than both need + stackedWithCreatedPartNearFit: stackedWithCreatedPart(600, ChatOnly), + stackedWithCreatedPartNearFitChatHidden: stackedWithCreatedPart(600, EditorOnly), + reorderedWithoutStrip: reorderedWithoutStrip(), + }, { + stackedWithCreatedPart: { chat: 130, terminals: 500, widthRemembered: true }, + stackedWithCreatedPartChatHidden: { chat: 130, terminals: 500, widthRemembered: true }, + stackedWithCreatedPartNearFit: { chat: 130, terminals: 500, widthRemembered: true }, + stackedWithCreatedPartNearFitChatHidden: { chat: 130, terminals: 500, widthRemembered: true }, + reorderedWithoutStrip: { shape: 'column(titleRow, chat, main)', withinAPoint: true }, + }); + }); + + test('in a window shorter and narrower than the sizes kept beside a hidden part, a width, a height or a reset keeps the saved sizes of the other dimension where the terminals do not fit in it, else saves those the parts show in it as both show, as without a hidden part; the chrome keeps its size, and the split shows after a reload as it does as both show again', () => { + // The room beside the terminals, 500 high: none, or some, but less than the chat and the main part both need (50 each) + type Row = { split: ChatWindowSplitLayout; position: ChatWindowTerminalPosition; hide: ChatWindowLayoutMode; move?: 'swap' | 'reorder'; chrome: boolean; gesture: 'width' | 'height' | 'reset'; room: 'none' | 'nearFit' }; + const run = ({ split, position, hide, move, chrome, gesture, room }: Row) => { + const height = room === 'none' ? 400 : (chrome ? 30 : 0) + 500 + 70; + const mode = observableValue('mode', split); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const terminalsCell = observableValue('terminals', undefined); + const cells = (arrangement?: IChatWindowArrangement) => ({ main: createPart('main'), chat: createPart('chat'), ...(chrome ? { titleRow: createChrome(30), strip: createChrome(34) } : {}), terminals: terminalsCell, splitLayout: constObservable(split), arrangement }); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, cells(), mode, constObservable(0), undefined, constObservable(position), undefined, editorGroupsService)); + grid.layout(1000, 800); + if (move === 'swap') { + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + } else if (move === 'reorder') { + grid.partGrid!.moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Up }); + } + // The terminals join where their position says, beside the parts as the user moved them + terminalsCell.set(terminalsPart.part, undefined); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 500); + const along = split === ChatWindowLayoutMode.Stacked ? 'height' : 'width'; + if (along === 'width') { + drag(container, grid, move === 'swap' ? ChatWindowGridCell.Main : ChatWindowGridCell.Chat, 'right', 300); + } else { + drag(container, grid, move === 'reorder' ? ChatWindowGridCell.Main : ChatWindowGridCell.Chat, 'top', 130); + } + const recorded = JSON.parse(JSON.stringify(grid.exportSizes())) as ChatWindowPartSizes; + mode.set(hide, undefined); + grid.layout(700, height); + // The sash of the gesture: between the chat and the main part's sides, or above the terminals + const hiddenCell = hide === ChatWindowLayoutMode.ChatOnly ? ChatWindowGridCell.Main : ChatWindowGridCell.Chat; + const leftSide = move === 'swap' ? ChatWindowGridCell.Main : ChatWindowGridCell.Chat; + const besideSash = leftSide === hiddenCell ? ChatWindowGridCell.Terminals : leftSide; + const vertical = gesture === 'width' || (gesture === 'reset' && along === 'width' && position !== ChatWindowTerminalPosition.FullWidth); + if (gesture === 'width') { + drag(container, grid, besideSash, 'right', grid.partGrid!.getCellSize(besideSash).width - 30); + } else if (gesture === 'height') { + drag(container, grid, ChatWindowGridCell.Terminals, 'top', 200); + } else { + const bounds = container.querySelector(`[data-part-grid-cell="${vertical ? besideSash : ChatWindowGridCell.Terminals}"]`)!.getBoundingClientRect(); + const sash = [...container.querySelectorAll(`.monaco-sash.${vertical ? 'vertical' : 'horizontal'}`)].find(candidate => { + const box = candidate.getBoundingClientRect(); + return vertical ? Math.abs(box.left + box.width / 2 - bounds.right) < 8 : Math.abs(box.top + box.height / 2 - bounds.top) < 8; + }); + if (!sash) { + return 'no sash'; + } + sash.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); + } + const sizes = grid.exportSizes(); + const arrangement = grid.exportArrangement(); + const chromeOf = (node: IChatWindowArrangement['root']): number[] => node.type === 'leaf' ? (node.data.id === ChatWindowGridCell.TitleRow || node.data.id === ChatWindowGridCell.Strip ? [node.size] : []) : node.data.flatMap(chromeOf); + const chromeKept = !arrangement || chromeOf(arrangement.root).every(size => size === 30 || size === 34); + const share = (target: ChatWindowGrid) => { + const [main, chat] = [target.partGrid!.getCellSize(ChatWindowGridCell.Main)[along], target.partGrid!.getCellSize(ChatWindowGridCell.Chat)[along]]; + return Math.round(main * 100 / (main + chat)); + }; + // Reopened as it was saved, the hidden part shows again in both as it does + const restoredMode = observableValue('mode', hide); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { ...cells(arrangement), terminals: constObservable(terminalsPart.part) }, restoredMode, constObservable(0), sizes, constObservable(position), undefined, editorGroupsService)); + restored.layout(700, height); + restoredMode.set(split, undefined); + mode.set(split, undefined); + // Where the terminals, 500 high, do not fit the window's height, the heights stay as saved; so they do where the + // parts beside them have less room than they need. Else the sizes are those the window shows the parts with now, + // as a gesture saves them without a hidden part. + const untouched = vertical ? 'height' : 'width'; + const forced = untouched === 'height' && room === 'none'; + const otherKept = Object.entries(recorded).every(([key, entries]) => key === 'terminals' || key.includes('|') || Object.entries(entries).every(([cell, size]) => { + const saved = sizes[key]?.[cell]?.[untouched]; + return saved !== undefined && (forced ? saved === size[untouched] : Math.abs(saved - grid.partGrid!.getCellSize(cell as ChatWindowGridCell)[untouched]) <= 1); + })); + const splitKept = Math.abs(share(restored) - share(grid)) <= 1; + return otherKept && chromeKept && splitKept ? 'kept' : JSON.stringify({ otherKept, chromeKept, splitKept, shown: share(grid), reloaded: share(restored) }); + }; + const { SideBySide, Stacked, ChatOnly, EditorOnly } = { SideBySide: ChatWindowLayoutMode.SideBySide, Stacked: ChatWindowLayoutMode.Stacked, ChatOnly: ChatWindowLayoutMode.ChatOnly, EditorOnly: ChatWindowLayoutMode.EditorOnly } as const; + const rows: Record = {}; + for (const [room, suffix] of [['none', ''], ['nearFit', ', near fit']] as const) { + for (const chrome of [true, false]) { + const name = (row: string) => `${row}${chrome ? '' : ', no chrome'}${suffix}`; + for (const [hide, position] of [[ChatOnly, ChatWindowTerminalPosition.UnderEditor], [EditorOnly, ChatWindowTerminalPosition.UnderChat]] as const) { + for (const move of [undefined, 'swap'] as const) { + for (const gesture of ['width', 'reset'] as const) { + rows[name(`side by side${move ? ', swapped' : ''}, ${hide === ChatOnly ? 'main' : 'chat'} hidden above the terminals, ${gesture}`)] = { split: SideBySide, position, hide, move, chrome, gesture, room }; + } + } + } + for (const hide of [ChatOnly, EditorOnly]) { + for (const gesture of ['height', 'reset'] as const) { + rows[name(`side by side, ${hide === ChatOnly ? 'main' : 'chat'} hidden, terminals across, ${gesture}`)] = { split: SideBySide, position: ChatWindowTerminalPosition.FullWidth, hide, chrome, gesture, room }; + for (const move of [undefined, 'reorder'] as const) { + rows[name(`stacked${move ? ', reordered' : ''}, ${hide === ChatOnly ? 'main' : 'chat'} hidden, ${gesture}`)] = { split: Stacked, position: ChatWindowTerminalPosition.FullWidth, hide, move, chrome, gesture, room }; + } + } + } + } + } + + const results = Object.fromEntries(Object.entries(rows).map(([name, row]) => { + try { + return [name, run(row)]; + } catch (error) { + return [name, String(error)]; + } + })); + assert.deepStrictEqual(results, Object.fromEntries(Object.keys(rows).map(name => [name, 'kept']))); + }); + + test('the split the user gave the parts, restored without the chrome, stays as the terminals first show beside it: shown from the start, registered empty and then filled, as the terminals service does, or joining empty later and then filled, also at a height that takes all but the least sizes of the parts, and while a part hides; only then, as later the terminals show among the sizes the user gave the parts', () => { + type Case = { split: ChatWindowSplitLayout; order: 'shown' | 'registeredEmpty' | 'joiningEmpty'; terminalsHeight: number; hide?: ChatWindowLayoutMode }; + const run = ({ split, order, terminalsHeight, hide }: Case) => { + const stacked = split === ChatWindowLayoutMode.Stacked; + const position = stacked ? ChatWindowTerminalPosition.FullWidth : ChatWindowTerminalPosition.UnderEditor; + const along = stacked ? 'height' : 'width'; + const edge = stacked ? 'top' : 'right'; + // The room the chat and the main part share along the split, of which the main part takes about half, then more + const room = stacked ? 800 - terminalsHeight : 1000; + const share = (target: ChatWindowGrid) => { + const [main, chat] = [target.partGrid!.getCellSize(ChatWindowGridCell.Main)[along], target.partGrid!.getCellSize(ChatWindowGridCell.Chat)[along]]; + return Math.round(main * 100 / (main + chat)); + }; + const cells = (arrangement?: IChatWindowArrangement) => ({ main: createPart('main'), chat: createPart('chat'), splitLayout: constObservable(split), arrangement }); + const terminalsPart = createPartWithEditors('terminals'); + terminalsPart.setEmpty(false); + const originalTerminals = observableValue('terminals', undefined); + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { ...cells(), terminals: originalTerminals }, constObservable(split), constObservable(0), undefined, constObservable(position), undefined, editorGroupsService)); + grid.layout(1000, 800); + grid.partGrid!.moveCell(stacked ? ChatWindowGridCell.Chat : ChatWindowGridCell.Main, stacked ? { reference: ChatWindowGridCell.Main, direction: Direction.Up } : { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + originalTerminals.set(terminalsPart.part, undefined); + drag(container, grid, ChatWindowGridCell.Terminals, 'top', terminalsHeight); + drag(container, grid, ChatWindowGridCell.Main, edge, Math.round(room * 0.45)); + const saved = share(grid); + + const restoredTerminals = createPartWithEditors('terminals'); + restoredTerminals.setEmpty(order !== 'shown'); + const terminalsCell = observableValue('terminals', order === 'joiningEmpty' ? undefined : restoredTerminals.part); + const restoredMode = observableValue('mode', split); + const restoredContainer = createAttachedContainer(); + const restored = disposables.add(new ChatWindowGrid(restoredContainer, { ...cells(grid.exportArrangement()), terminals: terminalsCell }, restoredMode, constObservable(0), grid.exportSizes(), constObservable(position), undefined, editorGroupsService)); + restored.layout(1000, 800); + terminalsCell.set(restoredTerminals.part, undefined); + // Until the terminals have something to show, the parts keep the split + const whileEmpty = share(restored); + if (hide !== undefined) { + restoredMode.set(hide, undefined); + } + restoredTerminals.setEmpty(false); + restoredMode.set(split, undefined); + const first = share(restored); + // The user gives the parts another split; the terminals then empty and fill again + drag(restoredContainer, restored, ChatWindowGridCell.Main, edge, Math.round(room * 0.6)); + const live = share(restored); + restoredTerminals.setEmpty(true); + restoredTerminals.setEmpty(false); + const kept = (from: number, to: number) => Math.abs(to - from) <= 1 ? 'kept' : `${from} -> ${to}`; + return { whileEmpty: kept(saved, whileEmpty), firstShow: kept(saved, first), laterShow: kept(live, share(restored)), terminals: restored.partGrid!.getCellSize(ChatWindowGridCell.Terminals).height }; + }; + const cases: Record = {}; + for (const split of [ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.SideBySide] as const) { + const name = split === ChatWindowLayoutMode.Stacked ? 'stacked, reordered' : 'side by side, swapped'; + for (const terminalsHeight of [200, 600]) { + for (const order of ['shown', 'registeredEmpty', 'joiningEmpty'] as const) { + cases[`${name}, ${order}, terminals ${terminalsHeight}`] = { split, order, terminalsHeight }; + } + for (const hide of [ChatWindowLayoutMode.ChatOnly, ChatWindowLayoutMode.EditorOnly] as const) { + cases[`${name}, registeredEmpty, filled while ${hide === ChatWindowLayoutMode.ChatOnly ? 'main' : 'chat'} hides, terminals ${terminalsHeight}`] = { split, order: 'registeredEmpty', terminalsHeight, hide }; + } + } + } + const results = Object.fromEntries(Object.entries(cases).map(([name, row]) => { + try { + return [name, run(row)]; + } catch (error) { + return [name, String(error)]; + } + })); + assert.deepStrictEqual(results, Object.fromEntries(Object.entries(cases).map(([name, row]) => [name, { whileEmpty: 'kept', firstShow: 'kept', laterShow: 'kept', terminals: row.terminalsHeight }]))); + }); + + test('the main part hidden with the terminals under it while they have nothing to show is as wide after a reload as the user made it', () => { + const { mode, grid, open, position, terminalsPart, userResize } = setupWithTerminals(); + grid.partGrid!.moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + userResize(ChatWindowGridCell.Main, 'right', 400); + position.set(ChatWindowTerminalPosition.UnderEditor, undefined); + open(); + mode.set(ChatWindowLayoutMode.ChatOnly, undefined); + terminalsPart.setEmpty(true); + const arrangement = grid.exportArrangement(); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), { main: createPart('main'), chat: createPart('chat'), titleRow: createChrome(30), strip: createChrome(34), arrangement }, constObservable(ChatWindowLayoutMode.SideBySide), constObservable(0), undefined, undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + + assert.deepStrictEqual({ shape: restored.partGrid!.describe(), main: restored.partGrid!.getCellSize(ChatWindowGridCell.Main).width }, { shape: 'column(titleRow, row(main, chat, strip))', main: 400 }); + }); + + test('the split the user gave the chat and the main part comes back after a reload, within a point as sizes round, whichever part was hidden as it saved, with the terminals beside it showing, empty or absent, a part the grid created coming or going meanwhile, with or without the chrome', () => { + type Case = { split: ChatWindowSplitLayout; move: 'swap' | 'nested' | 'reorder'; hide: ChatWindowLayoutMode; terminals?: { position: ChatWindowTerminalPosition; empty: boolean }; chrome?: false; created?: 'addedWhileHidden' | 'closedWhileHidden' | 'addedResizedAndClosedWhileHidden' }; + const editor = new class extends mock() { + override readonly typeId = 'testEditor'; + override readonly resource = undefined; + override getName() { return 'file'; } + }(); + const run = ({ split, move, hide, terminals, chrome, created }: Case) => { + const mode = observableValue('mode', split); + const terminalsPart = createPartWithEditors('terminals'); + const terminalsCell = observableValue('terminals', undefined); + const closeCreated = disposables.add(new Emitter()); + const createdPart = createPartWithEditors('created', closeCreated.event); + terminalsPart.setEmpty(false); + createdPart.setEmpty(false); + const cells = (arrangement?: IChatWindowArrangement) => ({ main: createPart('main'), chat: createPart('chat'), ...(chrome === false ? {} : { titleRow: createChrome(30), strip: createChrome(34) }), splitLayout: constObservable(split), arrangement }); + const original = cells(); + sourcePart = original.main; + const container = createAttachedContainer(); + const grid = disposables.add(new ChatWindowGrid(container, { ...original, terminals: terminalsCell }, mode, constObservable(0), undefined, constObservable(terminals?.position ?? ChatWindowTerminalPosition.FullWidth), { createPart: () => ({ id: 'created', part: createdPart.part }) }, editorGroupsService)); + const addCreated = () => grid.partGrid!.moveEditorsIntoNewPart([{ editor, groupId: 1 }], { edge: Direction.Right }); + grid.layout(1000, 800); + const partGrid = () => grid.partGrid!; + if (move === 'swap') { + partGrid().moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Left }); + } else if (move === 'nested') { + partGrid().moveCell(ChatWindowGridCell.Main, { reference: ChatWindowGridCell.Chat, direction: Direction.Up }); + } else { + partGrid().moveCell(ChatWindowGridCell.Chat, { reference: ChatWindowGridCell.Main, direction: Direction.Up }); + } + if (terminals) { + terminalsCell.set(terminalsPart.part, undefined); + } + if (created === 'closedWhileHidden') { + addCreated(); + } + // Beside each other, the chat and the main part split the width; one above the other, the height + const along = split === ChatWindowLayoutMode.Stacked || move === 'nested' ? 'height' : 'width'; + const share = (target: PartGrid) => { + const [main, chat] = [target.getCellSize(ChatWindowGridCell.Main)[along], target.getCellSize(ChatWindowGridCell.Chat)[along]]; + return { share: Math.round(main * 100 / (main + chat)), atMinimum: Math.min(main, chat) <= 100 }; + }; + partGrid().resizeCell(ChatWindowGridCell.Main, along === 'width' ? { width: 300 } : { height: 250 }); + const before = share(partGrid()); + mode.set(hide, undefined); + if (terminals?.empty) { + terminalsPart.setEmpty(true); + } + if (created === 'addedWhileHidden') { + addCreated(); + } else if (created === 'closedWhileHidden') { + closeCreated.fire(); + } else if (created === 'addedResizedAndClosedWhileHidden') { + addCreated(); + // The sash between the part that shows and the created part + const beside = hide === ChatWindowLayoutMode.ChatOnly ? ChatWindowGridCell.Chat : ChatWindowGridCell.Main; + drag(container, grid, beside, 'right', partGrid().getCellSize(beside).width - 40); + closeCreated.fire(); + } + const arrangement = grid.exportArrangement(); + const restored = disposables.add(new ChatWindowGrid(createAttachedContainer(), cells(arrangement), constObservable(split), constObservable(0), undefined, undefined, undefined, editorGroupsService)); + restored.layout(1000, 800); + const after = share(restored.partGrid!); + // Within a point: the sizes round as the room is shared again, and as the parts the grid created leave the arrangement + return !!arrangement && Math.abs(after.share - before.share) <= 1 && !after.atMinimum ? 'kept' : `${JSON.stringify(before)} -> ${JSON.stringify(after)}${arrangement ? '' : ' (not saved)'}`; + }; + const [SideBySide, Stacked, ChatOnly, EditorOnly] = [ChatWindowLayoutMode.SideBySide, ChatWindowLayoutMode.Stacked, ChatWindowLayoutMode.ChatOnly, ChatWindowLayoutMode.EditorOnly] as const; + const [FullWidth, UnderChat, UnderEditor] = [ChatWindowTerminalPosition.FullWidth, ChatWindowTerminalPosition.UnderChat, ChatWindowTerminalPosition.UnderEditor] as const; + const cases: Record = { + 'swapped, main hidden': { split: SideBySide, move: 'swap', hide: ChatOnly }, + 'swapped, chat hidden': { split: SideBySide, move: 'swap', hide: EditorOnly }, + 'swapped, main hidden, without chrome': { split: SideBySide, move: 'swap', hide: ChatOnly, chrome: false }, + 'swapped, main hidden, terminals across': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: FullWidth, empty: false } }, + 'swapped, main hidden, terminals across, empty': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: FullWidth, empty: true } }, + 'swapped, main hidden, terminals under it': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: UnderEditor, empty: false } }, + 'swapped, main hidden, terminals under it, empty': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: UnderEditor, empty: true } }, + 'swapped, chat hidden, terminals under it': { split: SideBySide, move: 'swap', hide: EditorOnly, terminals: { position: UnderChat, empty: false } }, + 'swapped, chat hidden, terminals under it, empty': { split: SideBySide, move: 'swap', hide: EditorOnly, terminals: { position: UnderChat, empty: true } }, + 'nested, main hidden': { split: SideBySide, move: 'nested', hide: ChatOnly }, + 'nested, chat hidden, terminals across, empty': { split: SideBySide, move: 'nested', hide: EditorOnly, terminals: { position: FullWidth, empty: true } }, + 'stacked reordered, main hidden, terminals': { split: Stacked, move: 'reorder', hide: ChatOnly, terminals: { position: FullWidth, empty: false } }, + 'stacked reordered, chat hidden, terminals empty': { split: Stacked, move: 'reorder', hide: EditorOnly, terminals: { position: FullWidth, empty: true } }, + 'stacked reordered, main hidden, without chrome': { split: Stacked, move: 'reorder', hide: ChatOnly, chrome: false }, + 'swapped, main hidden, terminals under it, empty, a part created meanwhile': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: UnderEditor, empty: true }, created: 'addedWhileHidden' }, + 'swapped, chat hidden, terminals under it, empty, a part created meanwhile': { split: SideBySide, move: 'swap', hide: EditorOnly, terminals: { position: UnderChat, empty: true }, created: 'addedWhileHidden' }, + 'swapped, main hidden, terminals under it, empty, a part closed meanwhile': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: UnderEditor, empty: true }, created: 'closedWhileHidden' }, + 'swapped, main hidden, a part created meanwhile': { split: SideBySide, move: 'swap', hide: ChatOnly, created: 'addedWhileHidden' }, + 'stacked reordered, chat hidden, terminals empty, a part closed meanwhile': { split: Stacked, move: 'reorder', hide: EditorOnly, terminals: { position: FullWidth, empty: true }, created: 'closedWhileHidden' }, + 'swapped, main hidden, terminals under it, empty, a part created, resized beside and closed meanwhile': { split: SideBySide, move: 'swap', hide: ChatOnly, terminals: { position: UnderEditor, empty: true }, created: 'addedResizedAndClosedWhileHidden' }, + 'swapped, chat hidden, terminals under it, empty, a part created, resized beside and closed meanwhile': { split: SideBySide, move: 'swap', hide: EditorOnly, terminals: { position: UnderChat, empty: true }, created: 'addedResizedAndClosedWhileHidden' }, + }; + + const results = Object.fromEntries(Object.entries(cases).map(([name, testCase]) => [name, run(testCase)])); + sourcePart = undefined; + assert.deepStrictEqual(results, Object.fromEntries(Object.keys(cases).map(name => [name, 'kept']))); + }); + test('the terminal position moves the terminals\' part in the grid, which keeps its height, and the arrangement it moves to is the one a new grid shows', () => { const { position, grid, open, height, userResize } = setupWithTerminals(); open(); diff --git a/src/vs/workbench/contrib/chatWindow/test/common/chatWindowState.test.ts b/src/vs/workbench/contrib/chatWindow/test/common/chatWindowState.test.ts index a18186719558..d53c25792dab 100644 --- a/src/vs/workbench/contrib/chatWindow/test/common/chatWindowState.test.ts +++ b/src/vs/workbench/contrib/chatWindow/test/common/chatWindowState.test.ts @@ -8,7 +8,7 @@ import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { InMemoryStorageService, IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { ChatWindowLayoutMode, ChatWindowTerminalPosition } from '../../common/chatWindowLayout.js'; -import { ChatWindowChatLayouts, ChatWindowChatSizes, ChatWindowDefaults, ChatWindowState, IRememberedChatLayout } from '../../common/chatWindowState.js'; +import { ChatWindowChatArrangements, ChatWindowChatLayouts, ChatWindowChatSizes, ChatWindowDefaults, ChatWindowState, IChatWindowArrangement, IRememberedChatLayout } from '../../common/chatWindowState.js'; suite('ChatWindowState', () => { @@ -130,4 +130,37 @@ suite('ChatWindowState', () => { assert.deepStrictEqual({ sizes: sizes.get(chat), oldKeyRemoved: storage.get(oldKey, StorageScope.WORKSPACE) === undefined }, { sizes: undefined, oldKeyRemoved: true }); }); + + test('remembers how the user arranged the parts of a chat\'s window apart from its sizes, and ignores an arrangement it cannot read, such as of another version, without throwing', () => { + const storage = disposables.add(new InMemoryStorageService()); + const arrangements = new ChatWindowChatArrangements(storage); + const sizes = new ChatWindowChatSizes(storage); + const leaf = (id: string, size: number) => ({ type: 'leaf' as const, data: { id }, size }); + const arrangement: IChatWindowArrangement = { version: 1, splitLayout: ChatWindowLayoutMode.SideBySide, orientation: 0, width: 1000, height: 800, root: { type: 'branch', size: 1000, data: [leaf('titleRow', 30), { type: 'branch', size: 770, data: [leaf('main', 400), leaf('chat', 566), leaf('strip', 34)] }] } }; + sizes.set(chat, { stacked: { chat: { width: 10, height: 20 } } }); + arrangements.set(chat, arrangement); + const stored = { arrangement: arrangements.get(chat), sizes: sizes.get(chat) }; + const read = (value: string) => { + storage.store(ChatWindowChatArrangements.STORAGE_KEY, value, StorageScope.WORKSPACE, StorageTarget.MACHINE); + return arrangements.get(chat); + }; + + assert.deepStrictEqual({ + stored, + corrupt: read('{['), + otherVersion: read(JSON.stringify([[chat.toString(), { ...arrangement, version: 2 }]])), + leafWithoutId: read(JSON.stringify([[chat.toString(), { ...arrangement, root: { type: 'branch', size: 1000, data: [{ type: 'leaf', data: {}, size: 30 }] } }]])), + emptyBranch: read(JSON.stringify([[chat.toString(), { ...arrangement, root: { type: 'branch', size: 1000, data: [] } }]])), + unknownSplitLayout: read(JSON.stringify([[chat.toString(), { ...arrangement, splitLayout: ChatWindowLayoutMode.ChatOnly }]])), + infiniteWidth: read(JSON.stringify([[chat.toString(), arrangement]]).replace('"width":1000', '"width":1e309')), + }, { + stored: { arrangement, sizes: { stacked: { chat: { width: 10, height: 20 } } } }, + corrupt: undefined, + otherVersion: undefined, + leafWithoutId: undefined, + emptyBranch: undefined, + unknownSplitLayout: undefined, + infiniteWidth: undefined, + }); + }); }); diff --git a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyEditorHintActions.ts b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyEditorHintActions.ts new file mode 100644 index 000000000000..80a921415552 --- /dev/null +++ b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyEditorHintActions.ts @@ -0,0 +1,503 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, addDisposableListener, append, clearNode, EventHelper, EventType } from '../../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { ActionBar, ActionsOrientation } from '../../../../../base/browser/ui/actionbar/actionbar.js'; +import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Action, IAction, Separator, WorkbenchActionExecutedClassification, WorkbenchActionExecutedEvent } from '../../../../../base/common/actions.js'; +import { coalesce } from '../../../../../base/common/arrays.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { isCancellationError } from '../../../../../base/common/errors.js'; +import { Event } from '../../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from '../../../../../editor/browser/editorBrowser.js'; +import { EditorOption } from '../../../../../editor/common/config/editorOptions.js'; +import { localize } from '../../../../../nls.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IContextKeyService, RawContextKey } 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'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { REOPEN_ACTIVE_EDITOR_WITH_COMMAND_ID } from '../../../../browser/parts/editor/editorCommands.js'; +import { WatermarkActionViewItem } from '../../../../browser/parts/editor/editorGroupWatermark.js'; +import { ChangeLanguageAction } from '../../../../browser/parts/editor/editorStatus.js'; +import { DEFAULT_EDITOR_ASSOCIATION, IEditorCommandsContext } from '../../../../common/editor.js'; +import { IEditorResolverService, RegisteredEditorInfo } from '../../../../services/editor/common/editorResolverService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IUntitledDocumentTelemetryService } from '../../../../services/untitled/common/untitledDocumentTelemetry.js'; +import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/accessibilityConfiguration.js'; +import { ACTION_ID_OPEN_CHAT } from '../../../chat/browser/actions/chatActions.js'; +import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; +import { ChatAgentLocation } from '../../../chat/common/constants.js'; +import { IChatAgentService } from '../../../chat/common/participants/chatAgents.js'; +import { EmptyEditorHintAction, logEmptyEditorHintEvent } from './emptyTextEditorHintTelemetry.js'; + +export const emptyEditorHintActionsSetting = 'workbench.editor.experimental.emptyEditorHintActions'; + +/** Set in the editor while the list of actions is shown, so that Escape hides it. */ +export const EmptyEditorHintActionsVisible = new RawContextKey('emptyEditorHintActionsVisible', false, localize('emptyEditorHintActionsVisible', "Whether the empty editor hint shows its list of actions")); + +const markdownEditorId = 'vscode.markdown.editor'; +const inlineChatStartCommandId = 'inlineChat.start'; +const reopenWithEditorCommandId = 'workbench.action.reopenWithEditor'; + +/** The editor that an untitled file was last reopened in from the hint, offered first next time. */ +const lastUntitledEditorStorageKey = 'emptyEditorHint.lastUntitledEditor'; + +interface IEmptyEditorHintActionEntry { + readonly action: EmptyEditorHintAction; + readonly label: string; + readonly icon: ThemeIcon; + /** The command whose keybinding is shown next to the label. */ + readonly keybindingCommandId?: string; + readonly run: () => Promise; + /** Makes the row a split button whose dropdown shows the Reopen Editor With picker. */ + readonly hasEditorPicker?: boolean; +} + +export interface IEmptyEditorHintActionsWidgetOptions { + /** Hides the hint for this editor only. */ + readonly close: () => void; + /** Hides the hint everywhere (sets `workbench.editor.empty.hint` to `hidden`). */ + readonly dontShowAgain: () => void; + /** The list no longer fits into the editor (after a resize or when its rows changed), see `requiredSize`. */ + readonly doesNotFit: () => void; +} + +/** The size of the editor's content area (without the vertical scrollbar), in pixels. */ +export interface IEmptyEditorHintActionsSize { + readonly width: number; + readonly height: number; +} + +/** + * The experimental empty editor hint: a list of actions for a new untitled file, rendered like the + * empty editor group watermark, in the top quarter of the editor. It overlays the editor, so the + * cursor stays on line 1 and typing dismisses the hint. + */ +export class EmptyEditorHintActionsWidget extends Disposable implements IOverlayWidget { + + private static readonly ID = 'editor.widget.emptyHintActions'; + + private readonly _domNode = $('.empty-editor-hint-actions'); + private readonly _rows = append(this._domNode, $('.empty-editor-hint-actions-rows')); + private readonly _rowsDisposables = this._register(new DisposableStore()); + private _ariaLabel = ''; + private _top = 0; + private _requiredSize: IEmptyEditorHintActionsSize | undefined; + + private static readonly _preferredWidth = 336; + /** Narrower than this, the classic hint is shown instead. */ + private static readonly _minWidth = 220; + /** The space kept free on each side of the list. */ + private static readonly _margin = 8; + + constructor( + private readonly _editor: ICodeEditor, + private readonly _options: IEmptyEditorHintActionsWidgetOptions, + @ICommandService private readonly _commandService: ICommandService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IKeybindingService private readonly _keybindingService: IKeybindingService, + @IChatAgentService private readonly _chatAgentService: IChatAgentService, + @IContextKeyService private readonly _contextKeyService: IContextKeyService, + @IEditorResolverService private readonly _editorResolverService: IEditorResolverService, + @IEditorService private readonly _editorService: IEditorService, + @ITelemetryService private readonly _telemetryService: ITelemetryService, + @IUntitledDocumentTelemetryService private readonly _untitledDocumentTelemetryService: IUntitledDocumentTelemetryService, + @INotificationService private readonly _notificationService: INotificationService, + @IHoverService private readonly _hoverService: IHoverService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IStorageService private readonly _storageService: IStorageService, + ) { + super(); + + const visible = EmptyEditorHintActionsVisible.bindTo(this._contextKeyService); + visible.set(true); + this._register(toDisposable(() => visible.reset())); + + this._renderCloseButton(); + this._renderFooter(); + this._renderRows(); + + const chatEnabledKeys = new Set([ChatContextKeys.enabled.key]); + this._register(Event.any( + this._keybindingService.onDidUpdateKeybindings, + this._chatAgentService.onDidChangeAgents, + this._editorResolverService.onDidChangeEditorRegistrations, + // The editors that can open the file depend on its language + this._editor.onDidChangeModelLanguage, + Event.filter(this._contextKeyService.onDidChangeContext, e => e.affectsSome(chatEnabledKeys)), + )(() => { + this._renderRows(); + this._layoutAndNotifyFit(); + })); + + this._register(addDisposableListener(this._domNode, EventType.KEY_DOWN, e => { + if (new StandardKeyboardEvent(e).equals(KeyCode.Escape)) { + e.preventDefault(); + e.stopPropagation(); + this.close('closeEscape'); + } + })); + + const onDidFocusEditorText = Event.debounce(this._editor.onDidFocusEditorText, () => undefined, 500); + this._register(onDidFocusEditorText(() => { + if (this._editor.hasTextFocus() && this._configurationService.getValue(AccessibilityVerbositySettingId.EmptyEditorHint)) { + status(this._ariaLabel); + } + })); + + this._register(this._editor.onDidLayoutChange(() => this._layoutAndNotifyFit())); + this._editor.addOverlayWidget(this); + this.layout(); + if (this.fits) { + this._logEvent('shown'); + } + } + + private _layoutAndNotifyFit(): void { + this.layout(); + if (!this.fits) { + this._options.doesNotFit(); + } + } + + override dispose(): void { + this._editor.removeOverlayWidget(this); + super.dispose(); + } + + /** + * Hides the hint for this editor, with the close button or Escape. + */ + close(action: 'close' | 'closeEscape'): void { + this._logEvent('action', action); + this._editor.focus(); + this._options.close(); + } + + getId(): string { + return EmptyEditorHintActionsWidget.ID; + } + + getDomNode(): HTMLElement { + return this._domNode; + } + + getPosition(): IOverlayWidgetPosition | null { + const layoutInfo = this._editor.getLayoutInfo(); + // `left` is the center: the widget centers itself with a CSS transform + const left = Math.round((layoutInfo.width - layoutInfo.verticalScrollbarWidth) / 2); + return { preference: { top: this._top, left } }; + } + + /** + * Whether the list of actions fits into the editor at its current size. If not, `requiredSize` tells + * how large the editor has to be, so that the classic hint can be shown until it is. + */ + get fits(): boolean { + return this._requiredSize === undefined; + } + + get requiredSize(): IEmptyEditorHintActionsSize | undefined { + return this._requiredSize; + } + + /** + * Fits the list into the editor: it shrinks to the available width and moves up from the top quarter + * when the editor is short, but always keeps line 1 (where the cursor blinks) visible above it. + */ + layout(): void { + const layoutInfo = this._editor.getLayoutInfo(); + const lineHeight = this._editor.getOption(EditorOption.lineHeight); + const availableWidth = layoutInfo.width - layoutInfo.verticalScrollbarWidth - 2 * EmptyEditorHintActionsWidget._margin; + this._domNode.style.width = `${Math.max(EmptyEditorHintActionsWidget._minWidth, Math.min(EmptyEditorHintActionsWidget._preferredWidth, availableWidth))}px`; + + const contentHeight = this._domNode.offsetHeight; + const minTop = 3 * lineHeight; + this._top = Math.max(minTop, Math.min(Math.round(layoutInfo.height / 4), layoutInfo.height - contentHeight)); + const fits = layoutInfo.height === 0 || contentHeight === 0 // not laid out yet + || (availableWidth >= EmptyEditorHintActionsWidget._minWidth && this._top + contentHeight <= layoutInfo.height); + this._requiredSize = fits ? undefined : { + width: EmptyEditorHintActionsWidget._minWidth + 2 * EmptyEditorHintActionsWidget._margin, + height: minTop + contentHeight, + }; + this._editor.layoutOverlayWidget(this); + } + + /** + * The visible entries, in groups that are separated by a divider. + */ + private _getEntryGroups(): IEmptyEditorHintActionEntry[][] { + const resource = this._editor.getModel()?.uri; + const hasInlineChat = this._chatAgentService.getActivatedAgents().some(agent => agent.locations.includes(ChatAgentLocation.EditorInline)); + const chatEnabled = this._contextKeyService.contextMatchesRules(ChatContextKeys.enabled); + const otherEditors = resource ? this._getOtherEditors(resource) : []; + const lastEditorId = this._storageService.get(lastUntitledEditorStorageKey, StorageScope.PROFILE); + const primaryEditor = otherEditors.find(editor => editor.id === lastEditorId) ?? otherEditors.find(editor => editor.id === markdownEditorId); + const openWithAnotherEditor: IEmptyEditorHintActionEntry = { + action: 'openWith', + label: localize('emptyEditorHintActions.openWith', "Open With Another Editor..."), + icon: Codicon.files, + run: () => this._showEditorPicker(), + }; + + const groups: (IEmptyEditorHintActionEntry | undefined)[][] = [[ + hasInlineChat ? { + action: 'generateCode', + label: localize('emptyEditorHintActions.generateCode', "Generate Code"), + icon: Codicon.sparkle, + keybindingCommandId: inlineChatStartCommandId, + run: () => this._runCommand(inlineChatStartCommandId, { from: 'hint' }), + } : undefined, + chatEnabled ? { + action: 'newChatEditor', + label: localize('emptyEditorHintActions.newChatEditor', "New Chat Editor"), + icon: Codicon.chatSparkle, + run: () => this._replaceWithNewChatEditor(), + } : undefined, + { + action: 'selectLanguage', + label: localize('emptyEditorHintActions.selectLanguage', "Select a Language"), + icon: Codicon.json, + keybindingCommandId: ChangeLanguageAction.ID, + run: async () => { + await this._runCommand(ChangeLanguageAction.ID); + this._editor.focus(); + }, + }, + ], [ + primaryEditor ? { + action: primaryEditor.id === markdownEditorId ? 'openMarkdownEditor' : 'openEditor', + label: localize('emptyEditorHintActions.openInEditor', "Open in {0}", primaryEditor.label), + icon: primaryEditor.id === markdownEditorId ? Codicon.markdown : Codicon.files, + run: () => this._reopenWith(primaryEditor.id), + hasEditorPicker: true, + } : openWithAnotherEditor, + ]]; + return groups.map(group => coalesce(group)).filter(group => group.length > 0); + } + + /** + * The editors other than the text editor that can open this file, e.g. the Markdown Editor for an untitled plain text file. + */ + private _getOtherEditors(resource: URI): RegisteredEditorInfo[] { + return this._editorResolverService.getEditors(resource).filter(editor => editor.id !== DEFAULT_EDITOR_ASSOCIATION.id); + } + + /** + * Shows the Reopen Editor With picker, which lists all editors for an untitled file. + */ + private _showEditorPicker(): Promise { + return this._reopenAndRemember(context => this._commandService.executeCommand(reopenWithEditorCommandId, context)); + } + + private _reopenWith(editorId: string): Promise { + return this._reopenAndRemember(context => this._commandService.executeCommand(REOPEN_ACTIVE_EDITOR_WITH_COMMAND_ID, editorId, context)); + } + + /** + * The command context of only this editor. The reopen commands act on all tabs that are selected together + * with this editor, so the tab selection is narrowed to this editor first. + */ + private async _getSingleEditorContext(): Promise { + const pane = this._editorService.visibleEditorPanes.find(pane => pane.getControl() === this._editor); + const input = pane?.input; + if (!pane || !input) { + return undefined; + } + if (pane.group.isSelected(input) && pane.group.selectedEditors.length > 1) { + await pane.group.setSelection(input, []); + } + return { groupId: pane.group.id, editorIndex: pane.group.getIndexOfEditor(input) }; + } + + /** + * Reopens this file in another editor and remembers that editor, so the hint offers it first next time. + */ + private async _reopenAndRemember(reopen: (context: IEditorCommandsContext) => Promise): Promise { + const resource = this._editor.getModel()?.uri; + const context = await this._getSingleEditorContext(); + if (!context) { + return; + } + await reopen(context); + const activeEditor = this._editorService.activeEditor; + if (activeEditor?.editorId && activeEditor.editorId !== DEFAULT_EDITOR_ASSOCIATION.id && isEqual(activeEditor.resource, resource)) { + this._storageService.store(lastUntitledEditorStorageKey, activeEditor.editorId, StorageScope.PROFILE, StorageTarget.USER); + } + } + + private _renderRows(): void { + clearNode(this._rows); + this._rowsDisposables.clear(); + + const groups = this._getEntryGroups(); + + const entriesById = new Map(); + const actionBar = this._rowsDisposables.add(new ActionBar(this._rows, { + orientation: ActionsOrientation.VERTICAL, + ariaLabel: localize('emptyEditorHintActions.ariaLabel', "Empty Editor Actions"), + actionViewItemProvider: action => { + const entry = entriesById.get(action.id); + if (!entry) { + return undefined; + } + if (entry.hasEditorPicker) { + return this._instantiationService.createInstance(EmptyEditorHintSplitActionViewItem, action, entry.icon, () => { + this._logEvent('action', 'openWith'); + this._editor.focus(); + void this._showEditorPicker(); + }); + } + const keybinding = entry.keybindingCommandId ? this._keybindingService.lookupKeybinding(entry.keybindingCommandId) : undefined; + return this._instantiationService.createInstance(WatermarkActionViewItem, action, entry.icon, keybinding); + }, + })); + this._rowsDisposables.add(actionBar.onDidRun(e => { + if (e.error && !isCancellationError(e.error)) { + this._notificationService.error(e.error); + } + })); + + const toAction = (entry: IEmptyEditorHintActionEntry) => { + entriesById.set(entry.action, entry); + return this._rowsDisposables.add(new Action(entry.action, entry.label, undefined, true, async () => { + this._logEvent('action', entry.action); + // The commands work on the active editor, so make this editor the active one first + this._editor.focus(); + await entry.run(); + })); + }; + actionBar.push(Separator.join(...groups.map(group => group.map(toAction)))); + + const labels = groups.flat().map(entry => { + const keybinding = entry.keybindingCommandId ? this._keybindingService.lookupKeybinding(entry.keybindingCommandId)?.getAriaLabel() : undefined; + return keybinding ? localize('emptyEditorHintActions.entryAriaLabel', "{0} ({1})", entry.label, keybinding) : entry.label; + }); + this._ariaLabel = localize( + 'emptyEditorHintActions.hintAriaLabel', + "Empty editor actions: {0}. Start typing to dismiss. Toggle {1} in settings to disable this hint.", + labels.join(', '), + AccessibilityVerbositySettingId.EmptyEditorHint + ); + this._domNode.setAttribute('aria-label', this._ariaLabel); + } + + private _renderCloseButton(): void { + const closeActionBar = this._register(new ActionBar(append(this._domNode, $('.empty-editor-hint-actions-close')))); + closeActionBar.push(this._register(new Action( + 'emptyEditorHintActions.close', + localize('emptyEditorHintActions.close', "Hide for This Editor"), + ThemeIcon.asClassName(Codicon.close), + true, + async () => this.close('close') + )), { icon: true, label: false }); + } + + private _renderFooter(): void { + const footer = append(this._domNode, $('.empty-editor-hint-actions-footer')); + append(footer, $('span')).textContent = localize('emptyEditorHintActions.startTyping', "Start typing to dismiss"); + append(footer, $('span.empty-editor-hint-actions-footer-separator')).textContent = '\u00b7'; + const dontShowAgain = append(footer, $('a.empty-editor-hint-actions-dont-show')); + dontShowAgain.setAttribute('role', 'button'); + dontShowAgain.tabIndex = 0; + dontShowAgain.textContent = localize('emptyEditorHintActions.dontShowAgain', "Don't Show Again"); + this._register(this._hoverService.setupDelayedHover(dontShowAgain, { content: localize('emptyEditorHintActions.dontShowAgainHover', "Disable the empty editor hint") })); + + const run = () => { + this._logEvent('action', 'dontShowAgain'); + this._editor.focus(); + this._options.dontShowAgain(); + }; + this._register(addDisposableListener(dontShowAgain, EventType.CLICK, e => { + e.preventDefault(); + run(); + })); + this._register(addDisposableListener(dontShowAgain, EventType.KEY_DOWN, e => { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { + event.preventDefault(); + run(); + } + })); + } + + private async _runCommand(commandId: string, ...args: unknown[]): Promise { + this._telemetryService.publicLog2('workbenchActionExecuted', { id: commandId, from: 'hint' }); + await this._commandService.executeCommand(commandId, ...args); + } + + /** + * Turns this blank file into a chat: opens a new chat editor in the group of this editor and closes this editor. + */ + private async _replaceWithNewChatEditor(): Promise { + const resource = this._editor.getModel()?.uri; + const untitledEditor = resource ? this._editorService.findEditors(resource).find(({ groupId }) => this._editorService.activeEditorPane?.group.id === groupId) : undefined; + await this._runCommand(ACTION_ID_OPEN_CHAT); + if (untitledEditor && !untitledEditor.editor.isDirty()) { + await this._editorService.closeEditor(untitledEditor, { preserveFocus: true }); + } + } + + private _logEvent(kind: 'shown' | 'action', action?: EmptyEditorHintAction): void { + logEmptyEditorHintEvent(this._telemetryService, this._untitledDocumentTelemetryService, this._editor.getModel()?.uri, 'actions', kind, action); + } +} + +/** + * A watermark row with a dropdown button at its end, e.g. "Open in Markdown Editor" with a picker of all editors. + * Right Arrow or Alt+Down opens the dropdown from the keyboard. + */ +class EmptyEditorHintSplitActionViewItem extends WatermarkActionViewItem { + + constructor( + action: IAction, + icon: ThemeIcon, + private readonly _showPicker: () => void, + @IHoverService private readonly _dropdownHoverService: IHoverService, + ) { + super(action, icon, undefined, _dropdownHoverService); + } + + override render(container: HTMLElement): void { + super.render(container); + container.classList.add('empty-editor-hint-actions-split'); + + const dropdown = append(container, $('a.empty-editor-hint-actions-dropdown')); + dropdown.setAttribute('role', 'button'); + dropdown.setAttribute('aria-haspopup', 'dialog'); + const label = localize('emptyEditorHintActions.otherEditors', "Open With Another Editor..."); + dropdown.setAttribute('aria-label', label); + append(dropdown, renderIcon(Codicon.chevronDown)).setAttribute('aria-hidden', 'true'); + this._register(this._dropdownHoverService.setupDelayedHover(dropdown, { content: label })); + + this._register(addDisposableListener(dropdown, EventType.MOUSE_DOWN, e => EventHelper.stop(e, true))); + this._register(addDisposableListener(dropdown, EventType.CLICK, e => { + EventHelper.stop(e, true); + this._showPicker(); + })); + if (this.element) { + this._register(addDisposableListener(this.element, EventType.KEY_DOWN, e => { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.RightArrow) || event.equals(KeyMod.Alt | KeyCode.DownArrow)) { + event.preventDefault(); + event.stopPropagation(); + this._showPicker(); + } + })); + } + } +} \ No newline at end of file diff --git a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.css b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.css index b3308834e445..799569c143ae 100644 --- a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.css +++ b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.css @@ -14,3 +14,110 @@ color: var(--vscode-textLink-foreground); pointer-events: auto; } + +/* Experimental: workbench.editor.experimental.emptyEditorHintActions */ + +.monaco-editor .overlayWidgets .empty-editor-hint-actions { + box-sizing: border-box; + /* The width is set in `layout()`, to fit narrow editors */ + /* `left` is the center of the editor */ + transform: translateX(-50%); + padding: var(--vscode-spacing-size80); + user-select: none; + -webkit-user-select: none; + /* Clicks between the rows go to the editor */ + pointer-events: none; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-rows .monaco-action-bar.vertical .actions-container { + display: block; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .watermark-entry, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-close, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-footer { + /* Dimmed, so that the hint does not compete with the cursor */ + opacity: 0.6; + transition: opacity 0.1s ease-out; + pointer-events: auto; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .watermark-entry:hover, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .watermark-entry:focus, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-close:hover, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-close:focus-within, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-footer:hover, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-footer:focus-within { + opacity: 1; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .monaco-action-bar.vertical .action-label.separator { + width: auto; + margin: var(--vscode-spacing-size80) var(--vscode-spacing-size80) !important; /* overrides the action bar's separator margin */ + opacity: 0.6; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-close { + position: absolute; + top: calc(-1 * var(--vscode-spacing-size160)); + right: 0; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-footer { + display: flex; + gap: var(--vscode-spacing-size40); + margin-top: var(--vscode-spacing-size120); + padding: 0 var(--vscode-spacing-size80); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-body2); +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-dont-show { + color: var(--vscode-textLink-foreground); + cursor: pointer; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-dont-show:hover { + text-decoration: underline; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-dont-show:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: var(--vscode-strokeThickness); +} +.monaco-editor .overlayWidgets .empty-editor-hint-actions .action-item.empty-editor-hint-actions-split { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-split > .watermark-entry { + flex: 1 1 auto; + min-width: 0; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-dropdown { + display: flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: var(--vscode-spacing-size280); + height: var(--vscode-spacing-size280); + border-radius: var(--vscode-cornerRadius-small); + color: var(--vscode-descriptionForeground); + cursor: pointer; + opacity: 0.6; + transition: opacity 0.1s ease-out; + pointer-events: auto; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-split:hover > .empty-editor-hint-actions-dropdown, +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-split:focus-within > .empty-editor-hint-actions-dropdown { + opacity: 1; +} + +.monaco-editor .overlayWidgets .empty-editor-hint-actions .empty-editor-hint-actions-dropdown:hover { + background-color: var(--vscode-toolbar-hoverBackground); + outline: var(--vscode-strokeThickness) dashed var(--vscode-toolbar-hoverOutline); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} \ No newline at end of file diff --git a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.ts b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.ts index 3d1899f8ec78..1f13c0619c5c 100644 --- a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.ts +++ b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHint.ts @@ -30,15 +30,31 @@ import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/ import { IChatAgentService } from '../../../chat/common/participants/chatAgents.js'; import { ChatAgentLocation } from '../../../chat/common/constants.js'; import { IInlineChatSessionService } from '../../../inlineChat/browser/inlineChatSessionService.js'; +import { IUntitledDocumentTelemetryService } from '../../../../services/untitled/common/untitledDocumentTelemetry.js'; import { EmptyTextEditorHintContributionId, IEmptyTextEditorHintContribution } from './emptyTextEditorHintTypes.js'; +import { EmptyEditorHintActionsVisible, EmptyEditorHintActionsWidget, emptyEditorHintActionsSetting, IEmptyEditorHintActionsSize } from './emptyEditorHintActions.js'; +import { EmptyEditorHintAction, logEmptyEditorHintEvent } from './emptyTextEditorHintTelemetry.js'; +import { ITextModel } from '../../../../../editor/common/model.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; +import { ICodeEditorService } from '../../../../../editor/browser/services/codeEditorService.js'; +import { EditorContextKeys } from '../../../../../editor/common/editorContextKeys.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; import './emptyTextEditorHint.css'; export const emptyTextEditorHintSetting = 'workbench.editor.empty.hint'; + export class EmptyTextEditorHintContribution extends Disposable implements IEmptyTextEditorHintContribution { static readonly ID = EmptyTextEditorHintContributionId; - private textHintContentWidget: EmptyTextEditorHintContentWidget | undefined; + private textHintContentWidget: EmptyTextEditorHintContentWidget | EmptyEditorHintActionsWidget | undefined; + + /** The text models for which the user closed the hint. Untitled URIs are reused, models are not; held weakly so disposed models are dropped. */ + private readonly closedForModels = new WeakSet(); + + /** Set while the editor is too small for the list of actions, so that the classic hint is shown until it grows. */ + private actionsRequiredSize: IEmptyEditorHintActionsSize | undefined; constructor( protected readonly editor: ICodeEditor, @@ -54,13 +70,18 @@ export class EmptyTextEditorHintContribution extends Disposable implements IEmpt this._register(this.editor.onDidChangeModelContent(() => this.update())); this._register(this.chatAgentService.onDidChangeAgents(() => this.update())); this._register(this.editor.onDidChangeModelDecorations(() => this.update())); + this._register(this.editor.onDidLayoutChange(() => { + if (this.actionsRequiredSize) { + this.update(); + } + })); this._register(this.editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => { if (e.hasChanged(EditorOption.readOnly)) { this.update(); } })); this._register(this.configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(emptyTextEditorHintSetting)) { + if (e.affectsConfiguration(emptyTextEditorHintSetting) || e.affectsConfiguration(emptyEditorHintActionsSetting)) { this.update(); } })); @@ -94,6 +115,10 @@ export class EmptyTextEditorHintContribution extends Disposable implements IEmpt return false; } + if (this.closedForModels.has(model)) { + return false; + } + if (this.editor.getModel()?.getValueLength()) { return false; } @@ -113,13 +138,67 @@ export class EmptyTextEditorHintContribution extends Disposable implements IEmpt return hasEditorAgents || shouldRenderDefaultHint; } + /** + * The list of actions is experimental and only offered for new untitled files, not in diff editors. + */ + private shouldRenderActions(): boolean { + return this.editor.getModel()?.uri.scheme === Schemas.untitled + && !this.editor.getOption(EditorOption.inDiffEditor) + && this.configurationService.getValue(emptyEditorHintActionsSetting) === true + && this.actionsFit(); + } + + /** + * Whether the editor is large enough for the list of actions, after it did not fit before. + */ + private actionsFit(): boolean { + if (!this.actionsRequiredSize) { + return true; + } + const layoutInfo = this.editor.getLayoutInfo(); + return layoutInfo.width - layoutInfo.verticalScrollbarWidth >= this.actionsRequiredSize.width && layoutInfo.height >= this.actionsRequiredSize.height; + } + protected update(): void { const shouldRenderHint = this.shouldRenderHint(); - if (shouldRenderHint && !this.textHintContentWidget) { - this.textHintContentWidget = this.instantiationService.createInstance(EmptyTextEditorHintContentWidget, this.editor); - } else if (!shouldRenderHint && this.textHintContentWidget) { + const shouldRenderActions = shouldRenderHint && this.shouldRenderActions(); + if (this.textHintContentWidget && (!shouldRenderHint || shouldRenderActions !== this.textHintContentWidget instanceof EmptyEditorHintActionsWidget)) { this.disposeHint(); } + if (shouldRenderHint && !this.textHintContentWidget) { + const actionsWidget = shouldRenderActions ? this.createActionsWidget() : undefined; + this.textHintContentWidget = actionsWidget ?? this.instantiationService.createInstance(EmptyTextEditorHintContentWidget, this.editor); + } + } + + /** + * Creates the list of actions, or returns `undefined` if it does not fit into the editor. + */ + private createActionsWidget(): EmptyEditorHintActionsWidget | undefined { + const widget: EmptyEditorHintActionsWidget = this.instantiationService.createInstance(EmptyEditorHintActionsWidget, this.editor, { + close: () => { + const model = this.editor.getModel(); + if (model) { + this.closedForModels.add(model); + } + this.disposeHint(); + }, + dontShowAgain: () => { + this.configurationService.updateValue(emptyTextEditorHintSetting, 'hidden'); + this.disposeHint(); + }, + doesNotFit: () => { + this.actionsRequiredSize = widget.requiredSize; + this.update(); + }, + }); + if (!widget.fits) { + this.actionsRequiredSize = widget.requiredSize; + widget.dispose(); + return undefined; + } + this.actionsRequiredSize = undefined; + return widget; } disposeHint(): void { @@ -127,6 +206,15 @@ export class EmptyTextEditorHintContribution extends Disposable implements IEmpt this.textHintContentWidget = undefined; } + /** + * Hides the list of actions for this editor (Escape in the editor). + */ + closeActionsHint(): void { + if (this.textHintContentWidget instanceof EmptyEditorHintActionsWidget) { + this.textHintContentWidget.close('closeEscape'); + } + } + override dispose(): void { super.dispose(); @@ -150,6 +238,7 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid @IChatAgentService private readonly chatAgentService: IChatAgentService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IContextMenuService private readonly contextMenuService: IContextMenuService, + @IUntitledDocumentTelemetryService private readonly untitledDocumentTelemetryService: IUntitledDocumentTelemetryService, ) { super(); @@ -165,6 +254,11 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid } })); this.editor.addContentWidget(this); + this.logHintEvent('shown'); + } + + private logHintEvent(kind: 'shown' | 'action', action?: EmptyEditorHintAction): void { + logEmptyEditorHintEvent(this.telemetryService, this.untitledDocumentTelemetryService, this.editor.getModel()?.uri, 'classic', kind, action); } getId(): string { @@ -173,6 +267,7 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid private disableHint(e?: MouseEvent) { const disableHint = () => { + this.logHintEvent('action', 'dontShowAgain'); this.configurationService.updateValue(emptyTextEditorHintSetting, 'hidden'); this.dispose(); this.editor.focus(); @@ -225,6 +320,7 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid const askSomethingCommandId = 'inlineChat.start'; const askSomething = async (e: UIEvent) => { e.stopPropagation(); + this.logHintEvent('action', 'generateCode'); this.telemetryService.publicLog2('workbenchActionExecuted', { id: askSomethingCommandId, from: 'hint' @@ -233,6 +329,7 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid }; const languageOnClickOrTap = async (e: UIEvent) => { e.stopPropagation(); + this.logHintEvent('action', 'selectLanguage'); // Need to focus editor before so current editor becomes active and the command is properly executed this.editor.focus(); this.telemetryService.publicLog2('workbenchActionExecuted', { @@ -268,7 +365,7 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid const ariaLabel = hasInlineChatProvider ? localize('defaultHintAriaLabelWithInlineChat', 'Execute {0} to ask a question, execute {1} to select a language and get started. Start typing to dismiss.', ...keybindingLabels) : localize('defaultHintAriaLabelWithoutInlineChat', 'Execute {0} to select a language and get started. Start typing to dismiss.', ...keybindingLabels); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const anchor of hintElement.querySelectorAll('a')) { anchor.style.cursor = 'pointer'; } @@ -313,3 +410,14 @@ class EmptyTextEditorHintContentWidget extends Disposable implements IContentWid } registerEditorContribution(EmptyTextEditorHintContribution.ID, EmptyTextEditorHintContribution, EditorContributionInstantiation.Eager); // eager because it needs to render a help message + +KeybindingsRegistry.registerCommandAndKeybindingRule({ + id: 'editor.action.hideEmptyEditorHint', + // Below other editor contributions, so Escape still closes their widgets first + weight: KeybindingWeight.EditorContrib - 50, + primary: KeyCode.Escape, + when: ContextKeyExpr.and(EmptyEditorHintActionsVisible, EditorContextKeys.editorTextFocus, EditorContextKeys.hasNonEmptySelection.toNegated(), EditorContextKeys.hasMultipleSelections.toNegated()), + handler: accessor => { + accessor.get(ICodeEditorService).getFocusedCodeEditor()?.getContribution(EmptyTextEditorHintContribution.ID)?.closeActionsHint(); + } +}); diff --git a/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHintTelemetry.ts b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHintTelemetry.ts new file mode 100644 index 000000000000..4e4fa285e18c --- /dev/null +++ b/src/vs/workbench/contrib/codeEditor/browser/emptyTextEditorHint/emptyTextEditorHintTelemetry.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { URI } from '../../../../../base/common/uri.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { IUntitledDocumentTelemetryService } from '../../../../services/untitled/common/untitledDocumentTelemetry.js'; + +/** + * `classic`: the single line hint. `actions`: the experimental list of actions (`workbench.editor.experimental.emptyEditorHintActions`). + */ +export type EmptyEditorHintVariant = 'classic' | 'actions'; + +export type EmptyEditorHintAction = 'generateCode' | 'newChatEditor' | 'selectLanguage' | 'openMarkdownEditor' | 'openEditor' | 'openWith' | 'close' | 'closeEscape' | 'dontShowAgain'; + +export function logEmptyEditorHintEvent( + telemetryService: ITelemetryService, + untitledDocumentTelemetryService: IUntitledDocumentTelemetryService, + resource: URI | undefined, + variant: EmptyEditorHintVariant, + kind: 'shown' | 'action', + action?: EmptyEditorHintAction, +): void { + type EmptyEditorHintEvent = { kind: 'shown' | 'action'; action: EmptyEditorHintAction | undefined; variant: EmptyEditorHintVariant; scheme: string; untitledDocumentId: string | undefined }; + type EmptyEditorHintClassification = { + owner: 'hediet'; + comment: 'How often the empty editor hint is shown and which of its actions are used.'; + kind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'shown: the hint appeared. action: the user clicked one of its actions.' }; + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The action that was used. openMarkdownEditor/openEditor: the Open in row with the Markdown Editor or the editor last chosen from the hint. openWith: the editor picker was opened, from the dropdown of that row or the Open With Another Editor row (workbenchEditorReopen tells which editor was chosen). close/closeEscape: hidden for the editor with the close button or Escape.' }; + variant: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Which hint was shown: classic (a single line) or actions (a list of actions).' }; + scheme: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The scheme of the document, e.g. untitled or file.' }; + untitledDocumentId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The untitledDocumentId of the untitledDocument events, if the document is untitled.' }; + }; + telemetryService.publicLog2('emptyEditorHint', { + kind, + action, + variant, + scheme: resource?.scheme ?? '', + untitledDocumentId: untitledDocumentTelemetryService.getUntitledDocumentId(resource), + }); +} diff --git a/src/vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput.ts b/src/vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput.ts index 6743d0e3bc4f..484a27367696 100644 --- a/src/vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput.ts +++ b/src/vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput.ts @@ -320,7 +320,7 @@ export class SuggestEnabledInput extends Widget { this.stylingContainer.style.borderStyle = 'solid'; this.stylingContainer.style.borderColor = asCssVariableWithDefault(styleOverrides.inputBorder ?? inputBorder, 'transparent'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const cursor = this.stylingContainer.getElementsByClassName('cursor')[0] as HTMLDivElement; if (cursor) { cursor.style.backgroundColor = asCssVariable(styleOverrides.inputForeground ?? inputForeground); diff --git a/src/vs/workbench/contrib/codeEditor/test/browser/emptyEditorHintActions.test.ts b/src/vs/workbench/contrib/codeEditor/test/browser/emptyEditorHintActions.test.ts new file mode 100644 index 000000000000..5a15f2212be4 --- /dev/null +++ b/src/vs/workbench/contrib/codeEditor/test/browser/emptyEditorHintActions.test.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.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 { createTestCodeEditor } from '../../../../../editor/test/browser/testCodeEditor.js'; +import { createTextModel } from '../../../../../editor/test/common/testTextModel.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IEditorResolverService, RegisteredEditorInfo } from '../../../../services/editor/common/editorResolverService.js'; +import { IEditorGroup } from '../../../../services/editor/common/editorGroupsService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { EditorInput } from '../../../../common/editor/editorInput.js'; +import { IVisibleEditorPane } from '../../../../common/editor.js'; +import { IUntitledDocumentTelemetryService } from '../../../../services/untitled/common/untitledDocumentTelemetry.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; +import { IChatAgentService } from '../../../chat/common/participants/chatAgents.js'; +import { EmptyEditorHintActionsWidget } from '../../browser/emptyTextEditorHint/emptyEditorHintActions.js'; + +suite('EmptyEditorHintActionsWidget', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('lists the available actions, offers the last chosen editor first and logs the actions that are used', async () => { + const events: unknown[] = []; + const commands: unknown[][] = []; + const callbacks: string[] = []; + + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(ITelemetryService, upcastPartial({ + ...NullTelemetryService, + publicLog2: (eventName: string, data?: unknown) => { events.push({ eventName, data }); }, + })); + instantiationService.stub(IUntitledDocumentTelemetryService, upcastPartial({ getUntitledDocumentId: () => 'doc-1' })); + instantiationService.stub(IChatAgentService, upcastPartial({ getActivatedAgents: () => [], onDidChangeAgents: Event.None })); + instantiationService.stub(IEditorResolverService, upcastPartial({ + getEditors: () => [upcastPartial({ id: 'default', label: 'Text Editor' }), upcastPartial({ id: 'vscode.markdown.editor', label: 'Markdown Editor' }), upcastPartial({ id: 'hexEditor.hexedit', label: 'Hex Editor' })], + onDidChangeEditorRegistrations: Event.None, + })); + instantiationService.stub(ICommandService, upcastPartial({ + executeCommand: async (...args: unknown[]) => { commands.push(args); return undefined; }, + onWillExecuteCommand: Event.None, + onDidExecuteCommand: Event.None, + })); + const contextKeyService = store.add(new ContextKeyService(instantiationService.get(IConfigurationService))); + contextKeyService.createKey(ChatContextKeys.enabled.key, true); + instantiationService.stub(IContextKeyService, contextKeyService); + // The editor last chosen from the hint is offered first + instantiationService.get(IStorageService).store('emptyEditorHint.lastUntitledEditor', 'hexEditor.hexedit', StorageScope.PROFILE, StorageTarget.USER); + + const model = store.add(createTextModel('', undefined, undefined, URI.from({ scheme: 'untitled', path: 'Untitled-1' }))); + const editor = store.add(createTestCodeEditor(model)); + + // This editor is selected in its group together with another tab: the reopen commands must only act on this editor + const thisInput = upcastPartial({}); + const otherInput = upcastPartial({}); + let selectedEditors = [thisInput, otherInput]; + const group = upcastPartial({ + id: 1, + get selectedEditors() { return selectedEditors; }, + isSelected: input => selectedEditors.includes(input), + setSelection: async (active, inactive) => { selectedEditors = [active, ...inactive]; }, + getIndexOfEditor: input => input === thisInput ? 0 : 1, + }); + instantiationService.stub(IEditorService, upcastPartial({ + visibleEditorPanes: [upcastPartial({ input: thisInput, group, getControl: () => editor })], + activeEditor: undefined, + })); + + const widget = store.add(instantiationService.createInstance(EmptyEditorHintActionsWidget, editor, { + close: () => callbacks.push('close'), + dontShowAgain: () => callbacks.push('dontShowAgain'), + doesNotFit: () => callbacks.push('doesNotFit'), + })); + + const domNode = widget.getDomNode(); + const rows = [...domNode.querySelectorAll('.watermark-entry, .separator')]; + const rowLabels = rows.map(row => row.classList.contains('separator') ? '---' : row.textContent); + + const click = async (label: string) => { + rows.find(row => row.textContent === label)!.click(); + await timeout(0); + }; + await click('Open in Hex Editor'); + const visibleBeforeClose = contextKeyService.getContextKeyValue('emptyEditorHintActionsVisible'); + domNode.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true })); + await timeout(0); + + assert.deepStrictEqual({ rowLabels, hasDropdown: !!domNode.querySelector('.empty-editor-hint-actions-dropdown'), visibleBeforeClose, commands, selectedEditors: selectedEditors.map(input => input === thisInput ? 'this' : 'other'), callbacks, events }, { + rowLabels: ['New Chat Editor', 'Select a Language', '---', 'Open in Hex Editor'], + hasDropdown: true, + visibleBeforeClose: true, + commands: [['reopenActiveEditorWith', 'hexEditor.hexedit', { groupId: 1, editorIndex: 0 }]], + selectedEditors: ['this'], + callbacks: ['close'], + events: [ + { eventName: 'emptyEditorHint', data: { kind: 'shown', action: undefined, variant: 'actions', scheme: 'untitled', untitledDocumentId: 'doc-1' } }, + { eventName: 'emptyEditorHint', data: { kind: 'action', action: 'openEditor', variant: 'actions', scheme: 'untitled', untitledDocumentId: 'doc-1' } }, + { eventName: 'emptyEditorHint', data: { kind: 'action', action: 'closeEscape', variant: 'actions', scheme: 'untitled', untitledDocumentId: 'doc-1' } }, + ], + }); + }); +}); diff --git a/src/vs/workbench/contrib/codeEditor/test/browser/gotoSymbolQuickAccess.test.ts b/src/vs/workbench/contrib/codeEditor/test/browser/gotoSymbolQuickAccess.test.ts new file mode 100644 index 000000000000..d79c7e3af6c4 --- /dev/null +++ b/src/vs/workbench/contrib/codeEditor/test/browser/gotoSymbolQuickAccess.test.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Event } from '../../../../../base/common/event.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; +import { IRange, Range } from '../../../../../editor/common/core/range.js'; +import { ISelection } from '../../../../../editor/common/core/selection.js'; +import { ILanguageFeaturesService } from '../../../../../editor/common/services/languageFeatures.js'; +import { IOutlineModelService } from '../../../../../editor/contrib/documentSymbols/browser/outlineModel.js'; +import { IGotoSymbolQuickAccessProviderOptions } from '../../../../../editor/contrib/quickAccess/browser/gotoSymbolQuickAccess.js'; +import { IQuickAccessTextEditorContext } from '../../../../../editor/contrib/quickAccess/browser/editorNavigationQuickAccess.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IKeyMods } from '../../../../../platform/quickinput/common/quickInput.js'; +import { EditorInput } from '../../../../common/editor/editorInput.js'; +import { IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; +import { IEditorService, PreferredGroup, SIDE_GROUP } from '../../../../services/editor/common/editorService.js'; +import { IOutlineService } from '../../../../services/outline/browser/outline.js'; +import { IChatWidgetService } from '../../../chat/browser/chat.js'; +import { GotoSymbolQuickAccessProvider } from '../../browser/quickaccess/gotoSymbolQuickAccess.js'; + +class TestGotoSymbolQuickAccessProvider extends GotoSymbolQuickAccessProvider { + + get openSideBySideDirection(): IGotoSymbolQuickAccessProviderOptions['openSideBySideDirection'] { + return this.options.openSideBySideDirection; + } + + gotoSymbol(context: IQuickAccessTextEditorContext, options: { range: IRange; keyMods: IKeyMods; forceSideBySide?: boolean }): void { + this.gotoLocation(context, options); + } +} + +suite('GotoSymbolQuickAccessProvider', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + function createProvider(supportsSplitting: boolean) { + const openedEditorGroups: Array = []; + const selections: Array = []; + + const activeEditor = new class extends mock() { + override readonly typeId = 'testEditorInput'; + override readonly resource = undefined; + }; + const editorService = new class extends mock() { + override readonly onDidActiveEditorChange = Event.None; + override readonly activeEditor = activeEditor; + override async openEditor(_editor: unknown, _options?: unknown, group?: PreferredGroup) { + openedEditorGroups.push(group); + return undefined; + } + }; + const editorGroupService = new class extends mock() { + override readonly supportsSplitting = supportsSplitting; + }; + const configurationService = new TestConfigurationService({ workbench: { editor: { openSideBySideDirection: 'right' } } }); + + const provider = new TestGotoSymbolQuickAccessProvider( + editorService, + configurationService, + new class extends mock() { }, + new class extends mock() { }, + new class extends mock() { }, + new class extends mock() { }, + editorGroupService, + ); + + const editor = new class extends mock() { + override setSelection(selection: IRange | ISelection) { selections.push(selection); } + override revealRangeInCenter() { } + override focus() { } + override getModel() { return null; } + }; + + return { provider, editor, openedEditorGroups, selections }; + } + + test('offers and opens to the side when the editor part supports splitting', () => { + const { provider, editor, openedEditorGroups, selections } = createProvider(true); + const range = new Range(2, 1, 2, 5); + + provider.gotoSymbol({ editor }, { range, keyMods: { ctrlCmd: false, alt: false, shift: false }, forceSideBySide: true }); + + assert.deepStrictEqual({ + openSideBySideDirection: provider.openSideBySideDirection?.(), + openedEditorGroups, + selections + }, { + openSideBySideDirection: 'right', + openedEditorGroups: [SIDE_GROUP], + selections: [] + }); + }); + + test('does not offer or open to the side when the editor part does not support splitting', () => { + const { provider, editor, openedEditorGroups, selections } = createProvider(false); + const range = new Range(2, 1, 2, 5); + + provider.gotoSymbol({ editor }, { range, keyMods: { ctrlCmd: false, alt: true, shift: false }, forceSideBySide: true }); + + assert.deepStrictEqual({ + openSideBySideDirection: provider.openSideBySideDirection?.(), + openedEditorGroups, + selections + }, { + openSideBySideDirection: undefined, + openedEditorGroups: [], + selections: [range] + }); + }); +}); diff --git a/src/vs/workbench/contrib/comments/browser/commentColors.ts b/src/vs/workbench/contrib/comments/browser/commentColors.ts index 6151312d8780..3b4b1445508b 100644 --- a/src/vs/workbench/contrib/comments/browser/commentColors.ts +++ b/src/vs/workbench/contrib/comments/browser/commentColors.ts @@ -18,6 +18,7 @@ const resolvedCommentBorder = registerColor('editorCommentsWidget.resolvedBorder const unresolvedCommentBorder = registerColor('editorCommentsWidget.unresolvedBorder', { dark: unresolvedCommentViewIcon, light: unresolvedCommentViewIcon, hcDark: contrastBorder, hcLight: contrastBorder }, nls.localize('unresolvedCommentBorder', 'Color of borders and arrow for unresolved comments.')); export const commentThreadRangeBackground = registerColor('editorCommentsWidget.rangeBackground', transparent(unresolvedCommentBorder, .1), nls.localize('commentThreadRangeBackground', 'Color of background for comment ranges.')); export const commentThreadRangeActiveBackground = registerColor('editorCommentsWidget.rangeActiveBackground', transparent(unresolvedCommentBorder, .1), nls.localize('commentThreadActiveRangeBackground', 'Color of background for currently selected or hovered comment range.')); +const commentThreadRangeBorder = registerColor('editorCommentsWidget.rangeBorder', unresolvedCommentBorder, nls.localize('commentThreadRangeBorder', 'Color of the outline around the code that a floating comment thread is about, and of the line connecting the thread to that code, when the thread is neither resolved nor unresolved.')); const commentThreadStateBorderColors = new Map([ [languages.CommentThreadState.Unresolved, unresolvedCommentBorder], @@ -42,6 +43,13 @@ export function getCommentThreadStateBorderColor(state: languages.CommentThreadS return getCommentThreadStateColor(state, theme, commentThreadStateBorderColors); } +/** + * The color of the outline around commented code and of the line connecting a floating comment thread to it. + */ +export function getCommentThreadRangeBorderColor(state: languages.CommentThreadState | undefined, theme: IColorTheme): Color | undefined { + return getCommentThreadStateBorderColor(state, theme) ?? theme.getColor(commentThreadRangeBorder); +} + export function getCommentThreadStateIconColor(state: languages.CommentThreadState | undefined, theme: IColorTheme): Color | undefined { return getCommentThreadStateColor(state, theme, commentThreadStateIconColors); } diff --git a/src/vs/workbench/contrib/comments/browser/commentGlyphWidget.ts b/src/vs/workbench/contrib/comments/browser/commentGlyphWidget.ts index 2abd1f6b8532..de1b67ac7f72 100644 --- a/src/vs/workbench/contrib/comments/browser/commentGlyphWidget.ts +++ b/src/vs/workbench/contrib/comments/browser/commentGlyphWidget.ts @@ -71,7 +71,8 @@ export class CommentGlyphWidget extends Disposable { position: OverviewRulerLane.Center }, collapseOnReplaceEdit: true, - linesDecorationsClassName: className + linesDecorationsClassName: 'comment-range-glyph comment-thread-bar', + firstLineDecorationClassName: className }; return ModelDecorationOptions.createDynamic(decorationOptions); diff --git a/src/vs/workbench/contrib/comments/browser/commentReply.ts b/src/vs/workbench/contrib/comments/browser/commentReply.ts index dbcb20e0d4ab..729aa0192d5a 100644 --- a/src/vs/workbench/contrib/comments/browser/commentReply.ts +++ b/src/vs/workbench/contrib/comments/browser/commentReply.ts @@ -156,6 +156,12 @@ export class CommentReply extends Disposable { this.expandReplyArea(); } + // A thread that is created without comments expands its reply area for the first comment. Once its comments + // arrive, an untouched reply area collapses to the reply button, as it does when it loses focus. + if (commentThread.comments?.length && this.isReplyExpanded && !this.commentEditor.hasWidgetFocus() && !this.commentEditor.getModel()?.getValueLength()) { + this._container.classList.remove('expand'); + } + if (isReplying) { this.commentEditor.focus(); } @@ -179,7 +185,29 @@ export class CommentReply extends Disposable { } public layout(widthInPixel: number) { - this.commentEditor.layout({ height: this._editorHeight, width: widthInPixel - 54 /* margin 20px * 10 + scrollbar 14px*/ }); + this.commentEditor.layout({ height: this._editorHeight, width: widthInPixel - 54 /* margin 20px * 10 + scrollbar 14px*/ - this.getAvatarWidth() }); + } + + /** + * The width taken up by the author's avatar, which shares a row with the comment editor. + */ + private getAvatarWidth(): number { + return this.avatar ? dom.getTotalWidth(this.avatar) : 0; + } + + /** + * Sizes the comment editor to the space that the author's avatar leaves in the comment form. + */ + private layoutCommentEditorInForm(): void { + const editorNode = this.commentEditor.getDomNode(); + const formWidth = dom.getContentWidth(this._form); + if (!editorNode || formWidth <= 0) { + // The form isn't rendered, so there is nothing to measure. + this.commentEditor.layout(); + return; + } + const editorFrameWidth = dom.getTotalWidth(editorNode) - dom.getContentWidth(editorNode); + this.commentEditor.layout({ height: this._editorHeight, width: formWidth - this.getAvatarWidth() - editorFrameWidth }); } public focusIfNeeded() { @@ -220,6 +248,10 @@ export class CommentReply extends Disposable { this._container.style.display = 'none'; } else { this._container.style.display = 'block'; + if (this.isReplyExpanded) { + // The avatar may have appeared or disappeared next to the comment editor. + this.layoutCommentEditorInForm(); + } } } @@ -340,17 +372,50 @@ export class CommentReply extends Disposable { return !!this._commentThread.comments?.length; } - private get isReplyExpanded(): boolean { + get isReplyExpanded(): boolean { return this._container.classList.contains('expand'); } + get domNode(): HTMLElement { + return this._container; + } + + /** + * Measures the width the reply needs: room for the author's avatar and the reply button, or for the widest of + * the buttons below a reply that is being written, which wrap. + */ + measureMinimumWidth(): number { + if (this._container.style.display === 'none') { + return 0; + } + const targetWindow = dom.getWindow(this._container); + const avatarWidth = this.avatar && this.avatar.offsetWidth > 0 ? dom.getTotalWidth(this.avatar) : 0; + let buttonWidth = 0; + if (this._reviewThreadReplyButton && this._reviewThreadReplyButton.offsetWidth > 0) { + // The button stretches to fill the form, so measure its text instead. + const range = this._reviewThreadReplyButton.ownerDocument.createRange(); + range.selectNodeContents(this._reviewThreadReplyButton); + const buttonStyle = targetWindow.getComputedStyle(this._reviewThreadReplyButton); + buttonWidth = range.getBoundingClientRect().width + (this._reviewThreadReplyButton.offsetWidth - this._reviewThreadReplyButton.clientWidth) + + (parseFloat(buttonStyle.paddingLeft) || 0) + (parseFloat(buttonStyle.paddingRight) || 0); + } + let actionsWidth = 0; + for (const actions of [this._formActions, this._editorActions]) { + for (const action of actions?.children ?? []) { + actionsWidth = Math.max(actionsWidth, dom.isHTMLElement(action) ? dom.getTotalWidth(action) : 0); + } + } + const style = targetWindow.getComputedStyle(this._container); + return (parseFloat(style.marginLeft) || 0) + Math.max(avatarWidth + buttonWidth, actionsWidth) + (parseFloat(style.marginRight) || 0); + } + private expandReplyArea(focus: boolean = true) { if (!this.isReplyExpanded) { this._container.classList.add('expand'); if (focus) { this.commentEditor.focus(); } - this.commentEditor.layout(); + this.layoutCommentEditorInForm(); } } diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadAdditionalActions.ts b/src/vs/workbench/contrib/comments/browser/commentThreadAdditionalActions.ts index 95ea31479970..502a2105b4ce 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadAdditionalActions.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadAdditionalActions.ts @@ -23,6 +23,10 @@ export class CommentThreadAdditionalActions exten private _buttonBar: HTMLElement | null; private _commentFormActions!: CommentFormActions; + get domNode(): HTMLElement | null { + return this._container; + } + constructor( container: HTMLElement, private _commentThread: languages.CommentThread, @@ -45,6 +49,21 @@ export class CommentThreadAdditionalActions exten this._container?.classList.remove('hidden'); } + /** + * Measures the width the buttons need, which don't wrap. + */ + measureWidth(): number { + if (!this._container || !this._buttonBar || this._container.classList.contains('hidden')) { + return 0; + } + let width = 0; + for (const button of this._buttonBar.children) { + width += dom.isHTMLElement(button) ? dom.getTotalWidth(button) : 0; + } + const style = dom.getWindow(this._container).getComputedStyle(this._container); + return (parseFloat(style.marginLeft) || 0) + width + (parseFloat(style.marginRight) || 0); + } + private _hideMenu() { this._container?.classList.add('hidden'); } diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadBody.ts b/src/vs/workbench/contrib/comments/browser/commentThreadBody.ts index 7f3deff2eda8..ebf4e92da8ec 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadBody.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadBody.ts @@ -5,7 +5,9 @@ import * as dom from '../../../../base/browser/dom.js'; import * as nls from '../../../../nls.js'; +import { DomScrollableElement } from '../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { Disposable, DisposableMap, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { ScrollbarVisibility } from '../../../../base/common/scrollable.js'; import * as languages from '../../../../editor/common/languages.js'; import { Emitter } from '../../../../base/common/event.js'; import { ICommentService } from './commentService.js'; @@ -27,6 +29,11 @@ export class CommentThreadBody extends D private _focusedComment: number | undefined = undefined; private _onDidResize = this._register(new Emitter()); onDidResize = this._onDidResize.event; + private readonly _onDidChangeCommentsSize = this._register(new Emitter()); + /** Fires when scrollable comments change size. */ + readonly onDidChangeCommentsSize = this._onDidChangeCommentsSize.event; + private _commentsScrollable: DomScrollableElement | undefined; + private _naturalWidth: number | undefined; private _commentDisposable = new DisposableMap, DisposableStore>(); @@ -38,6 +45,67 @@ export class CommentThreadBody extends D return this._commentElements.filter(node => node.isEditing)[0]; } + /** + * Measures the width at which the comments don't wrap. Comments that are being edited take the width of their editor. + */ + measureNaturalWidth(): number { + if (this._naturalWidth === undefined) { + // Measure a hidden copy, because unwrapping the comments themselves would shorten them, which resets the + // scroll positions of the comments and of the scrolling parts within them. + const copy = this._commentsElement.cloneNode(true); + if (!dom.isHTMLElement(copy)) { + return 0; + } + copy.setAttribute('aria-hidden', 'true'); + copy.style.position = 'absolute'; + copy.style.visibility = 'hidden'; + copy.style.width = 'max-content'; + this.container.appendChild(copy); + const naturalWidth = copy.offsetWidth; + copy.remove(); + if (naturalWidth === 0) { + // The comments aren't rendered, such as while the editor is hidden. + return 0; + } + this._naturalWidth = naturalWidth; + } + return this._naturalWidth; + } + + /** + * Measures the height of the comments, and the height of the rest of the body, which holds the reply and the + * thread's additional actions. Both are the heights the content needs, even when the body is too short to show it. + */ + measureHeights(): { comments: number; besideComments: number } { + const commentsViewport = this._commentsScrollable?.getDomNode() ?? this._commentsElement; + const frame = this.container.offsetHeight - this.container.clientHeight; + return { + comments: this._commentsElement.offsetHeight, + besideComments: this.container.scrollHeight + frame - commentsViewport.offsetHeight + }; + } + + /** + * Sets the height within which scrollable comments scroll. + */ + layoutCommentsHeight(height: number): void { + if (this._commentsScrollable) { + this._commentsScrollable.getDomNode().style.height = `${height}px`; + } + } + + /** + * Scrolls scrollable comments to the given comment. + */ + revealComment(commentUniqueId: number): void { + const coords = this.getCommentCoords(commentUniqueId); + if (coords && this._commentsScrollable) { + // The comments may have just been shown or resized, before their resize observer updated the scroll range. + this._commentsScrollable.scanDomNode(); + this._commentsScrollable.setScrollPosition({ scrollTop: coords.comment.top - coords.thread.top }); + } + } + constructor( private readonly _parentEditor: LayoutableEditor, readonly owner: string, @@ -48,6 +116,7 @@ export class CommentThreadBody extends D private _pendingEdits: { [key: number]: languages.PendingComment } | undefined, private _scopedInstatiationService: IInstantiationService, private _parentCommentThreadWidget: ICommentThreadWidget, + private readonly _scrollableComments: boolean, @ICommentService private readonly commentService: ICommentService, ) { super(); @@ -80,7 +149,12 @@ export class CommentThreadBody extends D } async display() { - this._commentsElement = dom.append(this.container, dom.$('div.comments-container')); + this._commentsElement = dom.$('div.comments-container'); + if (this._scrollableComments) { + this._createCommentsScrollable(); + } else { + this.container.appendChild(this._commentsElement); + } this._commentsElement.setAttribute('role', 'presentation'); this._commentsElement.tabIndex = 0; this._updateAriaLabel(); @@ -123,6 +197,42 @@ export class CommentThreadBody extends D }); } + /** + * Lets the comments scroll within the height set by {@link layoutCommentsHeight}, so that the reply and the + * thread's additional actions below them stay in view. + */ + private _createCommentsScrollable(): void { + const viewport = dom.$('.comments-scroll-viewport'); + viewport.appendChild(this._commentsElement); + const scrollable = this._commentsScrollable = this._register(new DomScrollableElement(viewport, { + vertical: ScrollbarVisibility.Auto, + horizontal: ScrollbarVisibility.Hidden + })); + this.container.appendChild(scrollable.getDomNode()); + // Focusing a comment that is scrolled out of view scrolls the viewport natively. + this._register(dom.addDisposableListener(viewport, dom.EventType.SCROLL, () => scrollable.scanDomNode())); + + let commentsWidth: number | undefined; + const resizeObserver = this._register(new dom.DisposableResizeObserver('commentThreadBody', entries => { + const commentsEntry = entries.find(entry => entry.target === this._commentsElement); + if (commentsEntry) { + if (commentsEntry.contentRect.width === commentsWidth) { + // The comments changed, rather than wrapped at a new width. + this._naturalWidth = undefined; + } + commentsWidth = commentsEntry.contentRect.width; + // Comments only update their own scrollbars when they are laid out. + this.layout(); + } + scrollable.scanDomNode(); + if (commentsEntry) { + this._onDidChangeCommentsSize.fire(); + } + }, dom.getWindow(this.container))); + this._register(resizeObserver.observe(this._commentsElement)); + this._register(resizeObserver.observe(scrollable.getDomNode())); + } + private _containerClientArea: dom.Dimension | undefined = undefined; private _refresh() { const dimensions = dom.getClientArea(this.container); @@ -231,6 +341,7 @@ export class CommentThreadBody extends D this._commentThread = commentThread; this._commentElements = newCommentNodeList; + this._naturalWidth = undefined; // Start editing *after* updating the thread and elements to avoid a sequencing issue https://github.com/microsoft/vscode/issues/239191 await Promise.all(startEditing); diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadConnector.ts b/src/vs/workbench/contrib/comments/browser/commentThreadConnector.ts new file mode 100644 index 000000000000..4f01f9b5d963 --- /dev/null +++ b/src/vs/workbench/contrib/comments/browser/commentThreadConnector.ts @@ -0,0 +1,364 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from '../../../../editor/browser/editorBrowser.js'; +import { EditorOption } from '../../../../editor/common/config/editorOptions.js'; +import { CursorColumns } from '../../../../editor/common/core/cursorColumns.js'; +import { IRange, Range } from '../../../../editor/common/core/range.js'; +import { commentThreadStateColorVar } from './commentColors.js'; +import { EDGE_MARGIN, getConnectorPoints, getRowsOutlinePath, IPoint, IRect } from './commentThreadFloatingWidgetLayout.js'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +/** Space between the commented code and its outline. */ +const OUTLINE_PADDING = 2; +/** How far the outline and connector may extend to the left of the code area, so that the outline of code at the first column isn't cut off. */ +const CONNECTOR_GUTTER_BLEED = OUTLINE_PADDING + 2; + +interface ILineExtent { + /** Where the commented text of the line starts, relative to the start of the line. */ + readonly start: number; + /** Where the commented text of the line ends, relative to the start of the line. */ + readonly end: number; + /** The text that was injected into the line when it was measured, such as inlay hints, which moves its text. */ + readonly injectedText: string; +} + +/** + * Where the code that a comment thread is about is shown in an editor. + * + * Measuring where the text of a line starts and ends makes the editor render, so each line is measured once, when it + * is first in view, and the measurement is kept until edits, injected text, or the editor's font or layout change it. + * Following the code as the editor scrolls only takes the lines' vertical positions, which don't need rendering. + */ +export class CommentedCodeGeometry extends Disposable { + + private readonly _lineExtents = new Map(); + + constructor( + private readonly _editor: ICodeEditor, + private readonly _getRange: () => IRange | undefined + ) { + super(); + const invalidate = () => this.invalidate(); + this._register(_editor.onDidChangeModelContent(invalidate)); + // Decorations can change the font of lines. + this._register(_editor.onDidChangeFont(invalidate)); + this._register(_editor.onDidChangeModelOptions(invalidate)); + this._register(_editor.onDidLayoutChange(invalidate)); + this._register(_editor.onDidChangeConfiguration(e => { + if (e.hasChanged(EditorOption.fontInfo) || e.hasChanged(EditorOption.wrappingInfo)) { + invalidate(); + } + })); + } + + /** + * Forgets the measured lines, such as when the commented range changes. + */ + invalidate(): void { + this._lineExtents.clear(); + } + + /** + * The commented range, validated against the model, and the lines it covers. A range that continues onto + * a further line only up to that line's start, like a selection of whole lines, doesn't cover that line. + */ + getLines(): { range: Range; startLineNumber: number; endLineNumber: number } | undefined { + const model = this._editor.getModel(); + const commentedRange = this._getRange(); + if (!commentedRange || !model) { + return undefined; + } + const range = model.validateRange(commentedRange); + const endsAtLineStart = range.endLineNumber > range.startLineNumber && range.endColumn === 1; + return { range, startLineNumber: range.startLineNumber, endLineNumber: endsAtLineStart ? range.endLineNumber - 1 : range.endLineNumber }; + } + + /** + * The vertical extent of the commented lines in document coordinates. Comments on the whole file are + * anchored at the top of the document. + */ + getVerticalBounds(): { top: number; bottom: number } { + const lines = this.getLines(); + if (!lines) { + return { top: 0, bottom: 0 }; + } + return { top: this._editor.getTopForLineNumber(lines.startLineNumber), bottom: this._editor.getBottomForLineNumber(lines.endLineNumber) }; + } + + /** + * The bounding box of the commented code, in editor coordinates. + */ + getBoundingRect(): IRect | undefined { + const lines = this.getLineRects(); + if (!lines) { + return undefined; + } + const vertical = this.getVerticalBounds(); + const left = Math.min(...lines.map(line => line.left)); + const right = Math.max(...lines.map(line => line.left + line.width)); + return { top: vertical.top - this._editor.getScrollTop(), left, width: right - left, height: vertical.bottom - vertical.top }; + } + + /** + * The areas of the commented lines that are in view, in editor coordinates, top to bottom and without gaps. + * Like the code's background, each line spans from the start of the code to the end of its text. Code that + * continues out of view extends beyond the edge of the editor. When none of the code is in view, its + * estimated area is returned as a single line. + */ + getLineRects(): IRect[] | undefined { + const code = this.getLines(); + const model = this._editor.getModel(); + if (!code || !model) { + return undefined; + } + const { range, startLineNumber, endLineNumber } = code; + const layoutInfo = this._editor.getLayoutInfo(); + const scrollTop = this._editor.getScrollTop(); + const contentLeft = layoutInfo.contentLeft - this._editor.getScrollLeft(); + const minWidth = this._editor.getOption(EditorOption.fontInfo).typicalHalfwidthCharacterWidth; + + const lines: IRect[] = []; + const visibleRanges = this._editor.getVisibleRanges(); + for (const visibleRange of visibleRanges) { + const from = Math.max(startLineNumber, visibleRange.startLineNumber); + const to = Math.min(endLineNumber, visibleRange.endLineNumber); + for (let lineNumber = from; lineNumber <= to; lineNumber++) { + // An empty range comments on its whole line. + const startColumn = !range.isEmpty() && lineNumber === range.startLineNumber ? range.startColumn : 1; + const endColumn = !range.isEmpty() && lineNumber === range.endLineNumber ? range.endColumn : model.getLineMaxColumn(lineNumber); + const extent = this._getLineExtent(lineNumber, startColumn, endColumn); + const top = this._editor.getTopForLineNumber(lineNumber); + const bottom = this._editor.getBottomForLineNumber(lineNumber); + let end = extent.end; + if (bottom - top > this._editor.getLineHeightForPosition({ lineNumber, column: 1 })) { + // The line wraps, so its text reaches the right of the viewport. + end = Math.max(end, layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth); + } + lines.push({ top: top - scrollTop, left: contentLeft + extent.start, width: Math.max(end - extent.start, minWidth), height: bottom - top }); + } + } + + if (lines.length === 0) { + // None of the code is in view, so estimate its area for the connector to point to. + const vertical = this.getVerticalBounds(); + let width = this._estimateOffset(startLineNumber, model.getLineMaxColumn(startLineNumber)); + if (this._lineExtents.size) { + width = Math.max(...Array.from(this._lineExtents.values(), extent => extent.end)); + } + return [{ top: vertical.top - scrollTop, left: contentLeft, width: Math.max(width, minWidth), height: vertical.bottom - vertical.top }]; + } + + // Close the gaps that view zones leave between lines. + for (let i = 0; i < lines.length - 1; i++) { + lines[i] = { ...lines[i], height: lines[i + 1].top - lines[i].top }; + } + const first = lines[0]; + if (first.top > -EDGE_MARGIN && startLineNumber < visibleRanges[0].startLineNumber) { + lines[0] = { ...first, top: -EDGE_MARGIN, height: first.top + first.height + EDGE_MARGIN }; + } + const last = lines[lines.length - 1]; + const viewportBottom = layoutInfo.height + EDGE_MARGIN; + if (last.top + last.height < viewportBottom && endLineNumber > visibleRanges[visibleRanges.length - 1].endLineNumber) { + lines[lines.length - 1] = { ...last, height: viewportBottom - last.top }; + } + return lines; + } + + /** + * Estimates where the editor's lines between the given vertical positions end, such as the lines next to a widget, + * without rendering them. A line with more characters than fit in the editor reaches its right edge anyway, so its + * text isn't read: the time this takes depends on the number of lines, rather than on their length. + * @param top The top of the area, in document coordinates. + * @param bottom The bottom of the area, in document coordinates. + * @returns The lines, in document coordinates. + */ + estimateLineRects(top: number, bottom: number): IRect[] { + const viewModel = this._editor._getViewModel(); + const model = this._editor.getModel(); + if (!viewModel || !model) { + return []; + } + const viewLayout = viewModel.viewLayout; + const layoutInfo = this._editor.getLayoutInfo(); + const left = layoutInfo.contentLeft - this._editor.getScrollLeft(); + const characterWidth = this._editor.getOption(EditorOption.fontInfo).typicalHalfwidthCharacterWidth; + const maxColumns = Math.ceil(layoutInfo.contentWidth / characterWidth); + const tabSize = model.getOptions().tabSize; + const lines: IRect[] = []; + const lineCount = viewModel.getLineCount(); + for (let lineNumber = viewLayout.getLineNumberAtVerticalOffset(Math.max(0, top)); lineNumber <= lineCount; lineNumber++) { + const lineTop = viewLayout.getVerticalOffsetForLineNumber(lineNumber); + if (lineTop >= bottom) { + break; + } + const length = viewModel.getLineLength(lineNumber); + const columns = length > maxColumns ? length : CursorColumns.visibleColumnFromColumn(viewModel.getLineContent(lineNumber), length + 1, tabSize); + lines.push({ top: lineTop, left, width: columns * characterWidth, height: viewLayout.getLineHeightForLineNumber(lineNumber) }); + } + return lines; + } + + /** + * Where the commented text of a line in view starts and ends. + */ + private _getLineExtent(lineNumber: number, startColumn: number, endColumn: number): ILineExtent { + const injectedText = this._getInjectedText(lineNumber); + const cached = this._lineExtents.get(lineNumber); + if (cached?.injectedText === injectedText) { + return cached; + } + const start = this._editor.getOffsetForColumn(lineNumber, startColumn); + const end = this._editor.getOffsetForColumn(lineNumber, endColumn); + if (start < 0 || end < 0) { + // The line isn't rendered, such as while the editor is hidden. + return { start: this._estimateOffset(lineNumber, startColumn), end: this._estimateOffset(lineNumber, endColumn), injectedText }; + } + const extent = { start, end, injectedText }; + this._lineExtents.set(lineNumber, extent); + return extent; + } + + /** + * Describes the text that decorations inject into a line, which changes far less often than decorations do. + */ + private _getInjectedText(lineNumber: number): string { + return this._editor.getModel()!.getLineInjectedText(lineNumber) + .map(text => `${text.column}:${text.options.content}:${text.options.widthInEm ?? ''}:${text.options.inlineClassName ?? ''}`) + .join('|'); + } + + private _estimateOffset(lineNumber: number, column: number): number { + const model = this._editor.getModel()!; + const visibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, model.getOptions().tabSize); + return visibleColumn * this._editor.getOption(EditorOption.fontInfo).typicalHalfwidthCharacterWidth; + } +} + +function setSvgAttributes(element: SVGElement, attributes: Record): void { + for (const [name, value] of Object.entries(attributes)) { + element.setAttribute(name, String(value)); + } +} + +function setSvgVisibility(visible: boolean, ...elements: SVGElement[]): void { + for (const element of elements) { + element.style.display = visible ? '' : 'none'; + } +} + +/** + * Draws an outline that follows the lines of the code that a floating comment thread is about, and a line from the + * code to the thread's widget. Both are drawn on an overlay that covers the code area of the editor. + */ +export class CommentThreadConnector extends Disposable { + + private readonly _domNode: HTMLElement; + private readonly _outline: SVGPathElement; + private readonly _line: SVGLineElement; + private readonly _anchor: SVGCircleElement; + private readonly _overlay: IOverlayWidget; + private _position: IOverlayWidgetPosition | null = null; + private _renderedBounds: { left: number; width: number; height: number } | undefined; + private _renderedOutline: string | undefined; + /** The radius of the corners of the outline around the code. */ + private _outlineCornerRadius = 0; + + constructor( + private readonly _editor: ICodeEditor, + id: string + ) { + super(); + this._domNode = dom.$('.comment-thread-floating-connector'); + this._domNode.setAttribute('aria-hidden', 'true'); + const svg = document.createElementNS(SVG_NS, 'svg'); + this._outline = document.createElementNS(SVG_NS, 'path'); + this._outline.classList.add('code-outline'); + this._line = document.createElementNS(SVG_NS, 'line'); + this._line.classList.add('connector-line'); + this._anchor = document.createElementNS(SVG_NS, 'circle'); + this._anchor.classList.add('connector-anchor'); + this._anchor.setAttribute('r', '2'); + svg.append(this._outline, this._line, this._anchor); + this._domNode.appendChild(svg); + + this._overlay = { + getId: () => id, + getDomNode: () => this._domNode, + getPosition: () => this._position + }; + } + + attach(): void { + this._editor.addOverlayWidget(this._overlay); + this._outlineCornerRadius = parseFloat(dom.getWindow(this._domNode).getComputedStyle(this._domNode).getPropertyValue('--vscode-cornerRadius-small')) || 0; + } + + detach(): void { + this._editor.removeOverlayWidget(this._overlay); + this._position = null; + this._renderedBounds = undefined; + } + + setColor(color: string): void { + this._domNode.style.setProperty(commentThreadStateColorVar, color); + } + + /** + * The outline and connector are subtle at rest and become prominent while focus is in the widget. + */ + setActive(active: boolean): void { + this._domNode.classList.toggle('active', active); + } + + /** + * Draws the outline around the given lines of code and the connector from the code to the anchor point, all in + * editor coordinates. The connector isn't drawn when the anchor is within the outline. + * @param bounds The horizontal extent of the editor's code area. + */ + render(codeLines: readonly IRect[] | undefined, anchor: IPoint, bounds: { left: number; right: number }): void { + // The outline of code that starts at the first column extends slightly into the gutter. + const originX = bounds.left - CONNECTOR_GUTTER_BLEED; + const width = bounds.right - originX; + const height = this._editor.getLayoutInfo().height; + if (this._renderedBounds?.left !== originX || this._renderedBounds.width !== width || this._renderedBounds.height !== height) { + this._renderedBounds = { left: originX, width, height }; + this._position = { preference: { top: 0, left: originX } }; + this._domNode.style.width = `${width}px`; + this._domNode.style.height = `${height}px`; + this._editor.layoutOverlayWidget(this._overlay); + } + + if (!codeLines) { + setSvgVisibility(false, this._outline, this._line, this._anchor); + return; + } + + const outlineRows = codeLines.map(line => ({ + top: line.top, + left: line.left - OUTLINE_PADDING - originX, + width: line.width + 2 * OUTLINE_PADDING, + height: line.height + })); + const outline = getRowsOutlinePath(outlineRows, this._outlineCornerRadius); + if (outline !== this._renderedOutline) { + this._renderedOutline = outline; + this._outline.setAttribute('d', outline); + } + setSvgVisibility(true, this._outline); + + const points = getConnectorPoints(outlineRows, { x: anchor.x - originX, y: anchor.y }); + if (!points) { + setSvgVisibility(false, this._line, this._anchor); + return; + } + setSvgAttributes(this._line, { x1: points.from.x, y1: points.from.y, x2: points.to.x, y2: points.to.y }); + setSvgAttributes(this._anchor, { cx: points.from.x, cy: points.from.y }); + setSvgVisibility(true, this._line, this._anchor); + } +} diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadEditorWidget.ts b/src/vs/workbench/contrib/comments/browser/commentThreadEditorWidget.ts new file mode 100644 index 000000000000..523c80b32b7b --- /dev/null +++ b/src/vs/workbench/contrib/comments/browser/commentThreadEditorWidget.ts @@ -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 { Color } from '../../../../base/common/color.js'; +import { Event } from '../../../../base/common/event.js'; +import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; +import Severity from '../../../../base/common/severity.js'; +import { ICodeEditor } from '../../../../editor/browser/editorBrowser.js'; +import { IPosition } from '../../../../editor/common/core/position.js'; +import { IRange, Range } from '../../../../editor/common/core/range.js'; +import * as languages from '../../../../editor/common/languages.js'; +import { peekViewBorder } from '../../../../editor/contrib/peekView/browser/peekView.js'; +import * as nls from '../../../../nls.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { IColorTheme } from '../../../../platform/theme/common/themeService.js'; +import { getCommentThreadStateBorderColor } from './commentColors.js'; +import { CommentGlyphWidget } from './commentGlyphWidget.js'; +import { ICommentService } from './commentService.js'; + +export enum CommentWidgetFocus { + None = 0, + Widget = 1, + Editor = 2 +} + +/** + * A comment thread shown in a code editor, independent of how it is presented + * (between the lines of the editor or floating above them). + */ +export interface ICommentThreadEditorWidget extends IDisposable { + readonly editor: ICodeEditor; + readonly uniqueOwner: string; + readonly commentThread: languages.CommentThread; + readonly expanded: boolean | undefined; + readonly onDidChangeExpandedState: Event; + readonly onDidClose: Event; + + display(range: IRange | undefined, shouldReveal: boolean): Promise; + update(commentThread: languages.CommentThread): Promise; + reveal(commentUniqueId?: number, focus?: CommentWidgetFocus): void; + expand(setActive?: boolean): void; + collapse(confirm?: boolean): Promise; + collapseAndFocusRange(): Promise; + getGlyphPosition(): number; + getPendingComments(): { newComment: languages.PendingComment | undefined; edits: { [key: number]: languages.PendingComment } }; + setPendingComment(pending: languages.PendingComment): void; + submitComment(): Promise; +} + +export function getCommentThreadWidgetStateColor(state: languages.CommentThreadState | undefined, theme: IColorTheme): Color | undefined { + return getCommentThreadStateBorderColor(state, theme) ?? theme.getColor(peekViewBorder); +} + +/** + * Check if a comment thread has any draft comments + */ +export function commentThreadHasDraft(commentThread: languages.CommentThread): boolean { + const comments = commentThread.comments; + if (!comments) { + return false; + } + return comments.some(comment => comment.state === languages.CommentState.Draft); +} + +/** + * Creates the gutter glyph for a comment thread. The glyph tracks edits to the document, and the + * thread's range is shifted to follow it. + */ +export function createCommentThreadGlyph(editor: ICodeEditor, range: IRange, getCommentThread: () => languages.CommentThread, store: DisposableStore): CommentGlyphWidget { + const glyph = new CommentGlyphWidget(editor, range.endLineNumber); + const commentThread = getCommentThread(); + glyph.setThreadState(commentThread.state, commentThreadHasDraft(commentThread)); + store.add(glyph.onDidChangeLineNumber(lineNumber => { + const thread = getCommentThread(); + if (!thread.range) { + return; + } + const shift = lineNumber - thread.range.endLineNumber; + thread.range = new Range(thread.range.startLineNumber + shift, thread.range.startColumn, thread.range.endLineNumber + shift, thread.range.endColumn); + })); + return glyph; +} + +/** + * Before a new comment is submitted, update the range of the thread template in case the + * thread moved as a result of editor changes. + */ +export async function updateCommentThreadTemplateRange(commentService: ICommentService, uniqueOwner: string, commentThread: languages.CommentThread, newPosition: IPosition | undefined): Promise { + if ((commentThread.comments && commentThread.comments.length) || !newPosition) { + return; + } + + const originalRange = commentThread.range; + if (!originalRange) { + return; + } + + let range: Range; + if (newPosition.lineNumber !== originalRange.endLineNumber) { + // The widget could have moved as a result of editor changes. + // We need to try to calculate the new, more correct, range for the comment. + const distance = newPosition.lineNumber - originalRange.endLineNumber; + range = new Range(originalRange.startLineNumber + distance, originalRange.startColumn, originalRange.endLineNumber + distance, originalRange.endColumn); + } else { + range = new Range(originalRange.startLineNumber, originalRange.startColumn, originalRange.endLineNumber, originalRange.endColumn); + } + await commentService.updateCommentThreadTemplate(uniqueOwner, commentThread.commentThreadHandle, range); +} + +/** + * Asks the user to confirm collapsing a comment thread that has unsubmitted comments, as + * configured by `comments.thread.confirmOnCollapse`. + */ +export async function confirmCommentThreadCollapse(hasUnsubmittedComments: boolean, configurationService: IConfigurationService, dialogService: IDialogService): Promise { + const confirmSetting = configurationService.getValue<'whenHasUnsubmittedComments' | 'never'>('comments.thread.confirmOnCollapse'); + + if (confirmSetting === 'whenHasUnsubmittedComments' && hasUnsubmittedComments) { + const result = await dialogService.confirm({ + message: nls.localize('confirmCollapse', "Collapsing this comment thread will discard unsubmitted comments. Are you sure you want to discard these comments?"), + primaryButton: nls.localize('discard', "Discard"), + type: Severity.Warning, + checkbox: { label: nls.localize('neverAskAgain', "Never ask me again"), checked: false } + }); + if (result.checkboxChecked) { + await configurationService.updateValue('comments.thread.confirmOnCollapse', 'never'); + } + return result.confirmed; + } + return true; +} diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidget.ts b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidget.ts new file mode 100644 index 000000000000..7f9b4f59dff7 --- /dev/null +++ b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidget.ts @@ -0,0 +1,1031 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/review.css'; +import * as dom from '../../../../base/browser/dom.js'; +import { GlobalPointerMoveMonitor } from '../../../../base/browser/globalPointerMoveMonitor.js'; +import { IMouseWheelEvent } from '../../../../base/browser/mouseEvent.js'; +import { IResizeEvent, ResizableHTMLElement } from '../../../../base/browser/ui/resizable/resizable.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Color } from '../../../../base/common/color.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { clamp } from '../../../../base/common/numbers.js'; +import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition, isCodeEditor } from '../../../../editor/browser/editorBrowser.js'; +import { CodeEditorWidget } from '../../../../editor/browser/widget/codeEditor/codeEditorWidget.js'; +import { EditorOption } from '../../../../editor/common/config/editorOptions.js'; +import { IRange, Range } from '../../../../editor/common/core/range.js'; +import { IEditorDecorationsCollection } from '../../../../editor/common/editorCommon.js'; +import * as languages from '../../../../editor/common/languages.js'; +import { ModelDecorationOptions } from '../../../../editor/common/model/textModel.js'; +import * as nls from '../../../../nls.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; +import { registerIcon } from '../../../../platform/theme/common/iconRegistry.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; +import { commentThreadStateBackgroundColorVar, commentThreadStateColorVar, getCommentThreadRangeBorderColor } from './commentColors.js'; +import { CommentGlyphWidget } from './commentGlyphWidget.js'; +import { ICommentService } from './commentService.js'; +import { CommentedCodeGeometry, CommentThreadConnector } from './commentThreadConnector.js'; +import { commentThreadHasDraft, CommentWidgetFocus, confirmCommentThreadCollapse, createCommentThreadGlyph, getCommentThreadWidgetStateColor, ICommentThreadEditorWidget, updateCommentThreadTemplateRange } from './commentThreadEditorWidget.js'; +import { computeFloatingWidgetPlacement, EDGE_MARGIN, FloatingWidgetSizeModel, getCenteredTop, getDefaultFloatingWidgetWidth, getPlacementBesideLines, getRevealScrollTop, getWidthBesideCode, IBesideLinesPlacement, ICommentThreadFloatingWidgetLayout, IFloatingWidgetContentHeights, IFloatingWidgetContentWidths, IFloatingWidgetObstacle, IFloatingWidgetPlacement, IFloatingWidgetPlacementRequest, IRect, ISize, ISizeRange, isInTheWayOf, MIN_HEIGHT, MIN_WIDTH } from './commentThreadFloatingWidgetLayout.js'; +import { FloatingWidgetRoom } from './commentThreadFloatingWidgetRoom.js'; +import { CommentThreadWidget } from './commentThreadWidget.js'; + +const closeIcon = registerIcon('review-comment-close', Codicon.close, nls.localize('closeIcon', "Icon to close a floating review comment.")); + +const emptyRangeHighlightOptions = ModelDecorationOptions.register({ + description: 'comment-thread-floating-range', + className: 'comment-thread-range', + zIndex: 20, + shouldFillLineOnLineBreak: true +}); + +/** + * Provided by the owner of the floating widgets of an editor. + */ +export interface ICommentThreadFloatingWidgetHost { + getLayout(widget: ReviewFloatingWidget): ICommentThreadFloatingWidgetLayout | undefined; + setLayout(widget: ReviewFloatingWidget, layout: ICommentThreadFloatingWidgetLayout): void; + /** Adds a widget to the floating widgets of the editor, until the returned disposable is disposed. */ + addWidget(widget: ReviewFloatingWidget): IDisposable; + /** The other floating widgets of the editor. */ + getOtherWidgets(widget: ReviewFloatingWidget): readonly ReviewFloatingWidget[]; + /** + * The room that an editor that grows with its content makes for its floating widgets, or `undefined` for an + * editor whose height limits the widgets. + */ + getRoom(): FloatingWidgetRoom | undefined; +} + +interface IResizeSession { + readonly layout: ICommentThreadFloatingWidgetLayout; + /** Document top of the widget when the resize started. */ + readonly top: number; + readonly left: number; + readonly width: number; + readonly height: number; + /** The widths the widget's content allows, which don't depend on the widget's size. */ + readonly widthRange: ISizeRange; + north: boolean; + west: boolean; + vertical: boolean; +} + +/** + * Where a widget is placed, and the width it is placed with. + */ +interface ISizedFloatingWidgetPlacement extends IFloatingWidgetPlacement { + readonly width: number; +} + +/** + * Where a widget may be placed, whatever its size. + */ +type FloatingWidgetPlacementArea = Omit; + +/** + * Shows a comment thread in a window that floats above the editor. The window can be moved by dragging + * its title and resized from its edges. A line connects it to the outlined code that the thread is about, + * and it moves along with that code when the editor scrolls. + */ +export class ReviewFloatingWidget extends Disposable implements ICommentThreadEditorWidget { + + private static _idPool = 0; + private static _frontWidget: ReviewFloatingWidget | undefined; + + private readonly _id = `review.floatingWidget.${ReviewFloatingWidget._idPool++}`; + private readonly _resizable: ResizableHTMLElement; + private readonly _domNode: HTMLElement; + private readonly _container: HTMLElement; + private readonly _boxOverlay: IOverlayWidget; + private _boxPosition: IOverlayWidgetPosition | null = null; + private readonly _codeGeometry: CommentedCodeGeometry; + private readonly _connector: CommentThreadConnector; + private readonly _sizeModel = new FloatingWidgetSizeModel(); + + private readonly _contextKeyService: IContextKeyService; + private readonly _scopedInstantiationService: IInstantiationService; + private readonly _commentThreadWidget: CommentThreadWidget; + private readonly _emptyRangeHighlight: IEditorDecorationsCollection; + private readonly _dragMonitor = this._register(new GlobalPointerMoveMonitor()); + private readonly _scheduledRender = this._register(new MutableDisposable()); + private readonly _attachedDisposables = this._register(new DisposableStore()); + private readonly _commentThreadDisposables = this._register(new DisposableStore()); + private readonly _glyphDisposables = this._register(new DisposableStore()); + + private _commentGlyph: CommentGlyphWidget | undefined; + private _initialCollapsibleState: languages.CommentThreadCollapsibleState | undefined; + private _isExpanded: boolean | undefined; + private _isAttached = false; + private _isDisposed = false; + private _layout: ICommentThreadFloatingWidgetLayout | undefined; + private _renderedLeft = 0; + /** The width of the widget's border, which its content doesn't get. */ + private _frameWidth = 0; + /** The width that the thread's content was last laid out for. */ + private _contentLayoutWidth: number | undefined; + /** The connector ends on the widget's rounded top left corner, which this is the radius of. */ + private _cornerRadius = 0; + private _resizeSession: IResizeSession | undefined; + /** The bottom of the widget, in document coordinates, that the editor last made room for. */ + private _bottomWithRoom: number | undefined; + + private readonly _onDidClose = this._register(new Emitter()); + readonly onDidClose = this._onDidClose.event; + + private readonly _onDidChangeExpandedState = this._register(new Emitter()); + readonly onDidChangeExpandedState = this._onDidChangeExpandedState.event; + + get uniqueOwner(): string { + return this._uniqueOwner; + } + + get commentThread(): languages.CommentThread { + return this._commentThread; + } + + get expanded(): boolean | undefined { + return this._isExpanded; + } + + constructor( + readonly editor: ICodeEditor, + private readonly _uniqueOwner: string, + private _commentThread: languages.CommentThread, + private _pendingComment: languages.PendingComment | undefined, + pendingEdits: { [key: number]: languages.PendingComment } | undefined, + private readonly _host: ICommentThreadFloatingWidgetHost, + @IInstantiationService instantiationService: IInstantiationService, + @IThemeService private readonly _themeService: IThemeService, + @ICommentService private readonly _commentService: ICommentService, + @IContextKeyService contextKeyService: IContextKeyService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IDialogService private readonly _dialogService: IDialogService + ) { + super(); + // Other widgets are placed around this one as soon as it's shown, which can be before its owner has added it. + this._register(_host.addWidget(this)); + + this._resizable = this._register(new ResizableHTMLElement()); + this._domNode = this._resizable.domNode; + this._domNode.classList.add('comment-thread-floating-widget'); + this._resizable.minSize = new dom.Dimension(MIN_WIDTH, MIN_HEIGHT); + this._container = dom.append(this._domNode, dom.$('.review-widget')); + + this._contextKeyService = this._register(contextKeyService.createScoped(this._domNode)); + this._scopedInstantiationService = this._register(instantiationService.createChild(new ServiceCollection( + [IContextKeyService, this._contextKeyService] + ))); + + this._initialCollapsibleState = _pendingComment ? languages.CommentThreadCollapsibleState.Expanded : _commentThread.initialCollapsibleState; + _commentThread.initialCollapsibleState = this._initialCollapsibleState; + + this._commentThreadWidget = this._register(this._scopedInstantiationService.createInstance( + CommentThreadWidget, + this._container, + this.editor, + this._uniqueOwner, + this.editor.getModel()!.uri, + this._contextKeyService, + this._scopedInstantiationService, + this._commentThread, + this._pendingComment, + pendingEdits, + { context: this.editor }, + this._commentService.getCommentController(this._uniqueOwner)?.options, + { + actionRunner: () => updateCommentThreadTemplateRange(this._commentService, this._uniqueOwner, this._commentThread, this._commentGlyph?.getPosition().position ?? undefined), + collapse: () => this.collapse(true) + }, + { + collapseAction: { label: nls.localize('label.close', "Close"), icon: closeIcon }, + // The reply and the thread's additional actions stay in view below the comments. + scrollableComments: true + } + )); + + this._codeGeometry = this._register(new CommentedCodeGeometry(this.editor, () => this._commentThread.range)); + this._connector = this._register(new CommentThreadConnector(this.editor, `${this._id}.connector`)); + this._boxOverlay = { + getId: () => this._id, + getDomNode: () => this._domNode, + getPosition: () => this._boxPosition + }; + + this._emptyRangeHighlight = this.editor.createDecorationsCollection(); + this._register(toDisposable(() => this._emptyRangeHighlight.clear())); + + this._register(this._resizable.onDidWillResize(() => this._onWillResize())); + this._register(this._resizable.onDidResize(e => this._onResize(e))); + this._register(this._commentThreadWidget.onDidChangeContentSize(() => this._onContentSizeChanged())); + + const header = this._commentThreadWidget.headerDomNode; + this._register(dom.addDisposableListener(header, dom.EventType.POINTER_DOWN, e => this._onHeaderPointerDown(e))); + this._register(dom.addDisposableListener(header, dom.EventType.DBLCLICK, e => this._onHeaderDoubleClick(e))); + this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, () => this._bringToFront(), true)); + this._register(dom.addDisposableListener(this._domNode, dom.EventType.MOUSE_WHEEL, (e: IMouseWheelEvent) => this._onMouseWheel(e), { passive: false })); + const focusTracker = this._register(dom.trackFocus(this._domNode)); + this._register(focusTracker.onDidFocus(() => { + this._bringToFront(); + this._connector.setActive(true); + })); + this._register(focusTracker.onDidBlur(() => this._connector.setActive(false))); + + this._register(this._themeService.onDidColorThemeChange(() => this._applyTheme())); + this._register(this.editor.onDidChangeConfiguration(e => { + if (e.hasChanged(EditorOption.fontInfo)) { + this._applyTheme(); + } + })); + this._applyTheme(); + } + + async display(range: IRange | undefined, shouldReveal: boolean): Promise { + if (range) { + this._commentGlyph = this._glyphDisposables.add(createCommentThreadGlyph(this.editor, range, () => this._commentThread, this._glyphDisposables)); + this._glyphDisposables.add(this._commentGlyph.onDidChangeLineNumber(() => this._scheduleRender())); + } + + await this._commentThreadWidget.display(this.editor.getOption(EditorOption.lineHeight), shouldReveal); + if (this._isDisposed) { + return; + } + + if (this._commentThread.collapsibleState === languages.CommentThreadCollapsibleState.Expanded) { + this._show(); + } + + // If this is a new comment thread awaiting user input then we need to reveal it. + if (shouldReveal) { + this._makeVisible(); + } + + this._bindCommentThreadListeners(); + } + + async update(commentThread: languages.CommentThread): Promise { + if (this._commentThread !== commentThread) { + this._commentThreadDisposables.clear(); + this._commentThread = commentThread; + this._bindCommentThreadListeners(); + } + + await this._commentThreadWidget.updateCommentThread(commentThread); + if (this._isDisposed) { + return; + } + // The commented range may have changed. + this._codeGeometry.invalidate(); + + if (this._commentGlyph) { + this._commentGlyph.setThreadState(commentThread.state, commentThreadHasDraft(commentThread)); + const lineNumber = this._commentThread.range?.endLineNumber ?? 1; + if (this._commentGlyph.getPosition().position?.lineNumber !== lineNumber) { + this._commentGlyph.setLineNumber(lineNumber); + } + } + + if (this._commentThread.collapsibleState === languages.CommentThreadCollapsibleState.Expanded) { + this._show(); + } else { + this._hide(); + } + } + + reveal(commentUniqueId?: number, focus: CommentWidgetFocus = CommentWidgetFocus.None): void { + this._makeVisible(commentUniqueId, focus); + const comment = this._commentThread.comments?.find(comment => comment.uniqueIdInThread === commentUniqueId) ?? this._commentThread.comments?.[0]; + this._commentService.setActiveCommentAndThread(this.uniqueOwner, { thread: this._commentThread, comment }); + } + + expand(setActive?: boolean): void { + this._commentThread.collapsibleState = languages.CommentThreadCollapsibleState.Expanded; + if (setActive) { + this._commentService.setActiveCommentAndThread(this.uniqueOwner, { thread: this._commentThread }); + } + } + + async collapse(confirm: boolean = false): Promise { + if (confirm && !(await confirmCommentThreadCollapse(this._commentThreadWidget.hasUnsubmittedComments, this._configurationService, this._dialogService))) { + return false; + } + this._commentThread.collapsibleState = languages.CommentThreadCollapsibleState.Collapsed; + return true; + } + + async collapseAndFocusRange(): Promise { + if (await this.collapse(true) && Range.isIRange(this._commentThread.range) && isCodeEditor(this.editor)) { + this.editor.setSelection(this._commentThread.range); + } + } + + getGlyphPosition(): number { + return this._commentGlyph?.getPosition().position?.lineNumber ?? 0; + } + + getPendingComments(): { newComment: languages.PendingComment | undefined; edits: { [key: number]: languages.PendingComment } } { + return { + newComment: this._commentThreadWidget.getPendingComment(), + edits: this._commentThreadWidget.getPendingEdits() + }; + } + + setPendingComment(pending: languages.PendingComment): void { + this._pendingComment = pending; + this.expand(); + this._commentThreadWidget.setPendingComment(pending); + } + + submitComment(): Promise { + return this._commentThreadWidget.submitComment(); + } + + /** + * The area taken up by the widget in document coordinates, and where its code starts, or `undefined` when it isn't + * shown. + */ + getDocumentRect(): IFloatingWidgetObstacle | undefined { + if (!this._isAttached || !this._layout) { + return undefined; + } + const { width, height } = this._resizable.size; + return { top: this._getDocumentTop(this._layout, height), left: this._renderedLeft, width, height, codeTop: this._codeGeometry.getVerticalBounds().top }; + } + + override dispose(): void { + if (this._isDisposed) { + return; + } + this._isDisposed = true; + this._isExpanded = false; + this._detach(); + if (ReviewFloatingWidget._frontWidget === this) { + ReviewFloatingWidget._frontWidget = undefined; + } + this._onDidClose.fire(); + super.dispose(); + } + + private _bindCommentThreadListeners(): void { + this._commentThreadDisposables.add(this._commentThread.onDidChangeComments(async () => { + await this.update(this._commentThread); + })); + + this._commentThreadDisposables.add(this._commentThread.onDidChangeCollapsibleState(state => { + if (state === languages.CommentThreadCollapsibleState.Expanded && !this._isExpanded) { + this._show(); + this._commentThreadWidget.ensureFocusIntoNewEditingComment(); + } else if (state === languages.CommentThreadCollapsibleState.Collapsed && this._isExpanded) { + this._hide(); + } + })); + + if (this._initialCollapsibleState === undefined) { + const onDidChangeInitialCollapsibleState = this._commentThread.onDidChangeInitialCollapsibleState(state => { + // File comments always start expanded + this._initialCollapsibleState = state; + this._commentThread.collapsibleState = this._initialCollapsibleState; + onDidChangeInitialCollapsibleState.dispose(); + }); + this._commentThreadDisposables.add(onDidChangeInitialCollapsibleState); + } + + this._commentThreadDisposables.add(this._commentThread.onDidChangeState(() => this._applyTheme())); + } + + private _show(): void { + const wasExpanded = this._isExpanded; + const wasAttached = this._isAttached; + this._isExpanded = true; + if (this._commentThread.collapsibleState !== languages.CommentThreadCollapsibleState.Expanded) { + this._commentThread.collapsibleState = languages.CommentThreadCollapsibleState.Expanded; + } + + this._attach(); + if (wasAttached) { + this._applySize(); + this._render(); + } else { + this._sizeModel.resetGrowth(); + // A widget that the user moved or resized goes where the user put it. The others are placed among the + // other widgets, in the order of their code. + const layout = this._layout ?? this._host.getLayout(this); + this._placeAmongOtherWidgets(layout?.isChosenByUser ? layout : undefined); + } + this._updateEmptyRangeHighlight(); + + if (!wasExpanded) { + this._onDidChangeExpandedState.fire(true); + } + } + + private _hide(): void { + if (this._isExpanded) { + this._isExpanded = false; + // Move focus out of the widget before it is removed from the DOM. + if (dom.isAncestorOfActiveElement(this._domNode)) { + this.editor.focus(); + } + + if (!this._commentThread.comments || !this._commentThread.comments.length) { + this.dispose(); + this._commentService.disposeCommentThread(this.uniqueOwner, this._commentThread.threadId); + return; + } + this._onDidChangeExpandedState.fire(false); + } + this._detach(); + this._updateEmptyRangeHighlight(); + } + + private _attach(): void { + if (this._isAttached) { + return; + } + this._isAttached = true; + this._connector.attach(); + this.editor.addOverlayWidget(this._boxOverlay); + this._sizeModel.captureEditorSize(this._measureEditorSize()); + this._cornerRadius = parseFloat(dom.getWindow(this._domNode).getComputedStyle(this._domNode).borderTopLeftRadius) || 0; + + this._attachedDisposables.add(this.editor.onDidScrollChange(e => { + if (e.scrollTopChanged || e.scrollLeftChanged) { + this._render(); + } + })); + this._attachedDisposables.add(this.editor.onDidLayoutChange(() => { + // Resizing the editor doesn't resize the widget, unless the editor had no size when the widget was shown. + const editorSize = this._sizeModel.editorSize; + if (editorSize.width <= 0 || editorSize.height <= 0) { + this._sizeModel.captureEditorSize(this._measureEditorSize()); + this._applySize(); + } + this._render(); + })); + // Edits and folding can move the commented code. Wait for the editor to process them before following it. + this._attachedDisposables.add(this.editor.onDidChangeHiddenAreas(() => this._scheduleRender())); + this._attachedDisposables.add(this.editor.onDidContentSizeChange(() => this._scheduleRender())); + this._attachedDisposables.add(this.editor.onDidChangeModelContent(() => this._scheduleRender())); + this._attachedDisposables.add(this.editor.onDidChangeConfiguration(e => { + if (e.hasChanged(EditorOption.fontInfo) || e.hasChanged(EditorOption.lineHeight)) { + this._scheduleRender(); + } + })); + } + + private _detach(): void { + if (!this._isAttached) { + return; + } + this._isAttached = false; + this._attachedDisposables.clear(); + this._scheduledRender.clear(); + this._dragMonitor.stopMonitoring(false); + this._resizeSession = undefined; + this.editor.removeOverlayWidget(this._boxOverlay); + this._connector.detach(); + if (this._bottomWithRoom !== undefined) { + this._bottomWithRoom = undefined; + this._host.getRoom()?.update(); + } + } + + private _makeVisible(commentUniqueId?: number, focus: CommentWidgetFocus = CommentWidgetFocus.None): void { + if (!this._isExpanded) { + this._show(); + } + this._revealInEditor(); + if (commentUniqueId !== undefined) { + this._commentThreadWidget.revealComment(commentUniqueId); + } + + if (focus === CommentWidgetFocus.Widget) { + this._commentThreadWidget.focus(commentUniqueId); + } else if (focus === CommentWidgetFocus.Editor) { + this._commentThreadWidget.focusCommentEditor(); + } + } + + /** + * Scrolls the editor so that the commented code and the widget are visible, if they aren't already. An editor that + * grows with its content can't scroll the view that it's shown in, so when its code is in that view, the widget is + * placed again within the view instead, if it reaches below it. + */ + private _revealInEditor(): void { + if (!this._layout) { + return; + } + const height = this._resizable.size.height; + const widgetTop = this._getDocumentTop(this._layout, height); + const code = this._codeGeometry.getVerticalBounds(); + const viewport = this._host.getRoom()?.getViewport(); + if (viewport && code.top >= viewport.top && code.bottom <= viewport.top + viewport.height) { + const viewportBottom = viewport.top + viewport.height; + if (!this._layout.isChosenByUser && widgetTop + height > viewportBottom - EDGE_MARGIN) { + this._placeAmongOtherWidgets(undefined, viewportBottom); + } + return; + } + const scrollTop = getRevealScrollTop(code, { top: widgetTop, bottom: widgetTop + height }, this.editor.getScrollTop(), this.editor.getLayoutInfo().height); + if (scrollTop !== undefined) { + this.editor.setScrollTop(scrollTop); + } + } + + private _storeLayout(): void { + if (this._layout) { + this._host.setLayout(this, this._layout); + } + } + + /** + * Where the widget goes and how large it is until the user moves or resizes it. The widget is laid out to measure + * its content, and may be left at another width than the layout's until the layout is applied. + * @param obstacles The areas that other widgets take up, which the widget is placed around. + * @param maxBottom How far down the widget can go, when that's less far than the editor can scroll through. + */ + private _computeDefaultLayout(obstacles: readonly IFloatingWidgetObstacle[], maxBottom?: number): ICommentThreadFloatingWidgetLayout { + this._sizeModel.resetGrowth(); + this._sizeModel.captureEditorSize(this._measureEditorSize()); + const bounds = this._getHorizontalBounds(); + const contentWidths = this._measureContentWidths(); + const widthRange = this._sizeModel.getWidthRange(contentWidths); + const preferredWidth = getDefaultFloatingWidgetWidth(this.editor.getLayoutInfo().contentWidth, bounds.right - bounds.left - 2 * EDGE_MARGIN); + const defaultWidth = this._sizeModel.getDefaultWidth(contentWidths, preferredWidth, this._commentThreadWidget.isEditing); + + const editorCode = this._codeGeometry.getBoundingRect(); + const code = editorCode && { ...editorCode, top: editorCode.top + this.editor.getScrollTop() }; + const area: FloatingWidgetPlacementArea = { + minLeft: bounds.left + EDGE_MARGIN, + maxRight: bounds.right, + code, + obstacles, + scrollableHeight: maxBottom ?? this._getScrollableHeight() + }; + const isNewComment = !this._commentThread.comments?.length; + // Laying the widget out makes the browser lay it out, so its size at the default width is measured at most once. + let defaultSize: ISize | undefined; + const measureDefaultSize = () => defaultSize ??= this._layOutAtWidth(defaultWidth, widthRange); + let placement = code && !isNewComment ? this._placeBesideLines(area, code, defaultWidth, measureDefaultSize, contentWidths.natural, widthRange) : undefined; + if (!placement) { + const request = { ...area, ...measureDefaultSize() }; + placement = (code && isNewComment ? this._placeBesideCode(request, code, widthRange) : undefined) ?? { ...computeFloatingWidgetPlacement(request), width: request.width }; + } + const { top, left, centered, width } = placement; + return { offsetTop: centered ? undefined : top - this._codeGeometry.getVerticalBounds().top, left, width, height: undefined, isChosenByUser: false }; + } + + /** + * Places the widget around the other widgets, or where the user put it, and places the automatically placed widgets + * that it's in the way of again, so that the widgets stay in the order of their code. Those are the ones for later + * code, and, for a widget that the user moved or resized, also the ones for earlier code, which may have been placed + * where it is while it was hidden. Widgets that the user moved or resized stay where they are. Widgets that aren't in + * the way stay where they are as well, so placing a widget only moves the ones that it must. + * @param layoutChosenByUser Where the user put the widget, when the user moved or resized it. + * @param maxBottom How far down the widget can go, when that's less far than the editor can scroll through. + */ + private _placeAmongOtherWidgets(layoutChosenByUser?: ICommentThreadFloatingWidgetLayout, maxBottom?: number): void { + const otherWidgets = this._host.getOtherWidgets(this); + if (layoutChosenByUser) { + this._layout = layoutChosenByUser; + this._applySize(); + this._render(); + } else { + this._placeAutomatically(otherWidgets, maxBottom); + } + const placed = this.getDocumentRect(); + if (!placed) { + return; + } + const widgetsToMove: { widget: ReviewFloatingWidget; rect: IFloatingWidgetObstacle }[] = []; + for (const widget of otherWidgets) { + const rect = widget.getDocumentRect(); + if (rect && !widget._layout?.isChosenByUser && (layoutChosenByUser || rect.codeTop > placed.codeTop)) { + widgetsToMove.push({ widget, rect }); + } + } + widgetsToMove.sort((a, b) => a.rect.codeTop - b.rect.codeTop); + // Each widget that is placed again can be in the way of the widgets for code after its own. + const movedRects = [placed]; + const allWidgets = [this, ...otherWidgets]; + for (const { widget, rect } of widgetsToMove) { + if (movedRects.some(movedRect => isInTheWayOf(rect, movedRect))) { + widget._placeAutomatically(allWidgets.filter(other => other !== widget)); + const movedRect = widget.getDocumentRect(); + if (movedRect) { + movedRects.push(movedRect); + } + } + } + } + + /** + * Places the widget where it goes until the user moves or resizes it, around the given other widgets that the user + * moved or resized, or that are for code that doesn't start after its own. + * @param maxBottom How far down the widget can go, when that's less far than the editor can scroll through. + */ + private _placeAutomatically(otherWidgets: readonly ReviewFloatingWidget[], maxBottom?: number): void { + const codeTop = this._codeGeometry.getVerticalBounds().top; + const obstacles: IFloatingWidgetObstacle[] = []; + for (const widget of otherWidgets) { + const rect = widget.getDocumentRect(); + if (rect && (widget._layout?.isChosenByUser || rect.codeTop <= codeTop)) { + obstacles.push(rect); + } + } + this._layout = this._computeDefaultLayout(obstacles, maxBottom); + this._storeLayout(); + this._applySize(); + this._render(); + } + + /** + * Places a new comment right after the end of its code, level with it, when there is room, so that it's close to + * where it's written. + */ + private _placeBesideCode(request: IFloatingWidgetPlacementRequest, code: IRect, widthRange: ISizeRange): ISizedFloatingWidgetPlacement | undefined { + const width = getWidthBesideCode(code, request.height, request.width, widthRange.min, request.maxRight, request.obstacles); + if (width === undefined) { + return undefined; + } + const size = this._layOutAtWidth(width, widthRange); + return { ...computeFloatingWidgetPlacement({ ...request, ...size, besideCode: true }), width: size.width }; + } + + /** + * Places an existing comment right after the end of the lines next to its code, and as wide as its content fills, + * when there is room, so that it's close to its code. See {@link getPlacementBesideLines} for which lines it may + * hide. Where other widgets move it to, it hides no more of the lines there. + * + * Laying the widget out at a new width takes far longer than estimating where lines end, so it's laid out once, + * unless its height decides how wide it is. Which lines it's next to depends on its height, which is only known once + * it's laid out, but it's at least the minimum height and at most the height that it sizes itself to. A taller widget + * is next to more lines, which leave it no more room, so when both heights leave the same room, so do the heights in + * between. A wider widget is no taller, so it's next to no more lines. + * @param measureDefaultSize Lays the widget out at its default width, the first time only, and returns its size there. + */ + private _placeBesideLines(area: FloatingWidgetPlacementArea, code: IRect, defaultWidth: number, measureDefaultSize: () => ISize, naturalWidth: number, widthRange: ISizeRange): ISizedFloatingWidgetPlacement | undefined { + const maxHeight = this._sizeModel.maxAutoHeight; + const centeredTop = (height: number) => getCenteredTop(code.top, code.top + code.height, height); + const nearbyLines = this._codeGeometry.estimateLineRects(centeredTop(maxHeight), centeredTop(maxHeight) + maxHeight); + const getPlacement = (lines: readonly IRect[], top: number, height: number) => getPlacementBesideLines(lines, top, top + height, code.left + code.width, area.maxRight, defaultWidth, naturalWidth); + const getCenteredPlacement = (height: number) => getPlacement(nearbyLines, centeredTop(height), height); + + const shortest = getCenteredPlacement(MIN_HEIGHT); + if (!shortest) { + return undefined; + } + const tallest = getCenteredPlacement(maxHeight); + let beside: IBesideLinesPlacement | undefined; + let size: ISize | undefined; + if (tallest && tallest.linesRight === shortest.linesRight && tallest.width === shortest.width + && computeFloatingWidgetPlacement({ ...area, width: tallest.width, height: maxHeight, linesRight: tallest.linesRight }).centered) { + beside = tallest; + size = this._layOutAtWidth(beside.width, widthRange); + } else { + const defaultSize = measureDefaultSize(); + beside = defaultSize.height <= maxHeight ? getCenteredPlacement(defaultSize.height) : undefined; + size = beside && (beside.width === defaultSize.width ? defaultSize : this._layOutAtWidth(beside.width, widthRange)); + } + // A widget whose title, reply and actions alone are taller than it sizes itself to is next to unchecked lines. + if (!beside || !size || size.height > maxHeight) { + return undefined; + } + const placement = computeFloatingWidgetPlacement({ ...area, ...size, linesRight: beside.linesRight }); + if (!placement.centered) { + // Other widgets moved the widget away from the code, next to other lines. + const moved = getPlacement(this._codeGeometry.estimateLineRects(placement.top, placement.top + size.height), placement.top, size.height); + if (!moved || moved.linesRight > beside.linesRight || moved.width < size.width) { + return undefined; + } + } + return { ...placement, width: size.width }; + } + + /** + * Lays the widget out at the given width, within the given range, and measures the size that it then takes when it + * sizes itself to its content. + */ + private _layOutAtWidth(width: number, range: ISizeRange): ISize { + const newWidth = this._setWidth(width, range); + return { width: newWidth, height: this._sizeModel.getHeight(this._measureContentHeights(), undefined) }; + } + + /** + * Sizes the widget to its layout, within the sizes that its content allows. The content is measured before the + * widget is changed, so that measuring doesn't make the browser lay out the changes, unless the widget's width + * changes, which changes the height of its content. + */ + private _applySize(): void { + const layout = this._layout; + if (!layout) { + return; + } + let heights = this._measureContentHeights(); + const widthRange = this._sizeModel.getWidthRange(this._measureContentWidths()); + const previousWidth = this._resizable.size.width; + if (this._setWidth(layout.width, widthRange) !== previousWidth) { + heights = this._measureContentHeights(); + } + const growthChanged = this._sizeModel.updateGrowth(heights); + const height = this._setHeight(this._sizeModel.getHeight(heights, layout.height), heights); + if (growthChanged) { + const viewport = this._getViewport(); + this._sizeModel.updateUpwardShift(layout.offsetTop, this._codeGeometry.getVerticalBounds(), height, viewport.top, viewport.height); + } + } + + /** + * Sets the widget's width within the given range, and lays out its content for that width. + */ + private _setWidth(width: number, range: ISizeRange): number { + const newWidth = clamp(width, range.min, range.max); + if (!this._resizeSession) { + this._resizable.minSize = new dom.Dimension(range.min, 0); + this._resizable.maxSize = new dom.Dimension(range.max, Number.MAX_SAFE_INTEGER); + } + this._resizable.layout(this._resizable.size.height, newWidth); + const contentWidth = newWidth - this._frameWidth; + if (contentWidth !== this._contentLayoutWidth) { + this._contentLayoutWidth = contentWidth; + this._commentThreadWidget.layout(contentWidth); + } + return newWidth; + } + + /** + * Sets the widget's height within the heights its content allows at its current width, and gives the comments + * the space that the rest of the thread leaves. + */ + private _setHeight(height: number, content: IFloatingWidgetContentHeights): number { + const range = this._sizeModel.getHeightRange(content); + const newHeight = clamp(height, range.min, range.max); + if (!this._resizeSession) { + this._resizable.minSize = new dom.Dimension(this._resizable.minSize.width, range.min); + this._resizable.maxSize = new dom.Dimension(this._resizable.maxSize.width, range.max); + } + this._resizable.layout(newHeight, this._resizable.size.width); + this._commentThreadWidget.layoutCommentsHeight(this._sizeModel.getCommentsHeight(content, newHeight)); + return newHeight; + } + + private _measureContentWidths(): IFloatingWidgetContentWidths { + this._frameWidth = this._domNode.offsetWidth - this._domNode.clientWidth; + const widths = this._commentThreadWidget.measureWidths(); + return { minimum: this._frameWidth + widths.minimum, natural: this._frameWidth + widths.natural }; + } + + private _measureContentHeights(): IFloatingWidgetContentHeights { + const frame = this._domNode.offsetHeight - this._domNode.clientHeight; + const heights = this._commentThreadWidget.measureHeights(); + return { fixed: frame + heights.fixed, comments: heights.comments }; + } + + private _measureEditorSize(): ISize { + const bounds = this._getHorizontalBounds(); + return { width: Math.max(0, bounds.right - bounds.left), height: this._getViewport().height }; + } + + /** + * The part of the document that is in view, in document coordinates: the editor's viewport or, for an editor that + * grows with its content, the part of the editor that the view it's shown in shows. + */ + private _getViewport(): { top: number; height: number } { + return this._host.getRoom()?.getViewport() ?? { top: this.editor.getScrollTop(), height: this.editor.getLayoutInfo().height }; + } + + /** + * The horizontal range, in editor coordinates, of the area that shows the code. + */ + private _getHorizontalBounds(): { left: number; right: number } { + const layoutInfo = this.editor.getLayoutInfo(); + const left = layoutInfo.contentLeft; + const right = layoutInfo.contentLeft + layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth; + return { left, right: Math.max(left, right) }; + } + + /** + * The top of the widget in document coordinates. + */ + private _getDocumentTop(layout: ICommentThreadFloatingWidgetLayout, height: number): number { + return this._sizeModel.getTop(layout.offsetTop, this._codeGeometry.getVerticalBounds(), height, this._getScrollableHeight()); + } + + /** + * The height of the area that the widget can be in. Overlay widgets don't make the area that the editor can scroll + * through larger, but an editor that grows with its content makes room for them below its content. + */ + private _getScrollableHeight(): number { + return this._host.getRoom()?.getScrollableHeight() ?? Math.max(this.editor.getScrollHeight(), this.editor.getLayoutInfo().height); + } + + private _render(): void { + if (!this._isAttached || !this._layout) { + return; + } + this._scheduledRender.clear(); + const bounds = this._getHorizontalBounds(); + const { width, height } = this._resizable.size; + const left = clamp(this._layout.left, bounds.left, Math.max(bounds.left, bounds.right - width)); + const documentTop = this._getDocumentTop(this._layout, height); + const top = documentTop - this.editor.getScrollTop(); + // Measure the code before moving the widget: measuring code that is newly in view makes the editor render. + const codeLines = this._codeGeometry.getLineRects(); + this._renderedLeft = left; + this._boxPosition = { preference: { top: Math.round(top), left: Math.round(left) } }; + this.editor.layoutOverlayWidget(this._boxOverlay); + // Anchor the connector on the widget's rounded top left corner, where the corner's curve is halfway around. + const cornerInset = this._cornerRadius * (1 - Math.SQRT1_2); + this._connector.render(codeLines, { x: left + cornerInset, y: top + cornerInset }, bounds); + // Scrolling doesn't move the widget within the document, so the editor only makes room again when it moved. + const room = this._host.getRoom(); + if (room && documentTop + height !== this._bottomWithRoom) { + this._bottomWithRoom = documentTop + height; + room.update(); + } + } + + private _scheduleRender(): void { + if (this._isAttached && !this._scheduledRender.value) { + this._scheduledRender.value = dom.scheduleAtNextAnimationFrame(dom.getWindow(this.editor.getContainerDomNode()), () => this._render()); + } + } + + /** + * Highlights the commented line of an empty range. Other ranges are highlighted for all comment threads. + */ + private _updateEmptyRangeHighlight(): void { + const range = this._commentThread.range; + const model = this.editor.getModel(); + if (!this._isExpanded || !range || !model || !Range.isEmpty(range)) { + this._emptyRangeHighlight.clear(); + return; + } + const lineNumber = clamp(range.startLineNumber, 1, model.getLineCount()); + this._emptyRangeHighlight.set([{ + range: new Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber)), + options: emptyRangeHighlightOptions + }]); + } + + private _onContentSizeChanged(): void { + if (this._isAttached && !this._resizeSession) { + this._applySize(); + this._render(); + } + } + + /** + * The whole title bar can be dragged, except for its actions. + */ + private _isInHeaderActions(target: EventTarget | null): boolean { + return dom.isHTMLElement(target) && !!target.closest('.review-actions .action-item'); + } + + private _onHeaderPointerDown(e: PointerEvent): void { + const startLayout = this._layout; + if (e.button !== 0 || !startLayout || !this._isAttached || this._isInHeaderActions(e.target)) { + return; + } + // Prevent the text selection and focus change that a mouse down would cause. + e.preventDefault(); + + const header = this._commentThreadWidget.headerDomNode; + const startTop = this._getDocumentTop(startLayout, this._resizable.size.height); + const startLeft = this._renderedLeft; + const startX = e.clientX; + const startY = e.clientY; + const headerHeight = header.offsetHeight; + this._domNode.classList.add('dragging'); + this._dragMonitor.startMonitoring(header, e.pointerId, e.buttons, moveEvent => { + const bounds = this._getHorizontalBounds(); + const scrollTop = this.editor.getScrollTop(); + // Keep the title within the editor so that the widget can always be dragged back. + const maxTop = Math.max(0, this.editor.getLayoutInfo().height - headerHeight); + const top = clamp(startTop - scrollTop + moveEvent.clientY - startY, 0, maxTop) + scrollTop; + const left = clamp(startLeft + moveEvent.clientX - startX, bounds.left, Math.max(bounds.left, bounds.right - this._resizable.size.width)); + // The widget is now where the user puts it, which includes any upward shift for its expanded reply. + this._sizeModel.clearUpwardShift(); + this._layout = { ...startLayout, left, offsetTop: top - this._codeGeometry.getVerticalBounds().top, isChosenByUser: true }; + this._render(); + }, () => { + this._domNode.classList.remove('dragging'); + this._storeLayout(); + }); + } + + private _onHeaderDoubleClick(e: MouseEvent): void { + if (!this._isAttached || this._isInHeaderActions(e.target)) { + return; + } + // Restore the initial placement and size. + this._placeAmongOtherWidgets(); + } + + private _onWillResize(): void { + if (!this._layout) { + return; + } + // The user can resize the widget to fit the editor's current size, without it first shrinking to fit an editor + // that became smaller after the widget was shown. + this._sizeModel.growEditorSize(this._measureEditorSize()); + const { width, height } = this._resizable.size; + const top = this._getDocumentTop(this._layout, height); + const widthRange = this._sizeModel.getWidthRange(this._measureContentWidths()); + this._resizeSession = { layout: this._layout, top, left: this._renderedLeft, width, height, widthRange, north: false, west: false, vertical: false }; + // The allowed height changes with the width, so the sizes are limited while handling each resize instead. + this._resizable.minSize = new dom.Dimension(0, 0); + this._resizable.maxSize = new dom.Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); + } + + private _onResize(e: IResizeEvent): void { + const session = this._resizeSession; + if (!session) { + return; + } + session.north ||= !!e.north; + session.west ||= !!e.west; + session.vertical ||= !!(e.north || e.south); + + // Keep the widget within the editor horizontally. + const bounds = this._getHorizontalBounds(); + const maxWidthOnSide = session.west ? session.left + session.width - bounds.left : bounds.right - session.left; + const widthRange = { min: session.widthRange.min, max: Math.max(session.widthRange.min, Math.min(session.widthRange.max, maxWidthOnSide)) }; + const width = this._setWidth(e.dimension.width, widthRange); + + // Dragging a corner trades width for height: the allowed height depends on the new width. + const heights = this._measureContentHeights(); + this._sizeModel.updateGrowth(heights); + let requestedHeight = session.vertical ? e.dimension.height : this._sizeModel.getHeight(heights, session.layout.height); + if (session.north) { + // The top edge can't go above the start of the document. + requestedHeight = Math.min(requestedHeight, session.top + session.height); + } else if (session.vertical) { + // The bottom edge can't go below the area that the editor can scroll through. + requestedHeight = Math.min(requestedHeight, this._getScrollableHeight() - EDGE_MARGIN - session.top); + } + const height = this._setHeight(requestedHeight, heights); + + // Resizing vertically pins the edge that isn't being dragged, so the widget stops being centered on the code. + let offsetTop = session.layout.offsetTop; + if (session.vertical) { + const top = session.north ? Math.max(0, session.top + session.height - height) : session.top; + offsetTop = top - this._codeGeometry.getVerticalBounds().top; + // The pinned edge includes any upward shift for the widget's expanded reply. + this._sizeModel.clearUpwardShift(); + } + this._layout = { + offsetTop, + left: session.west ? session.left + session.width - width : session.left, + width, + height: session.vertical ? height : session.layout.height, + isChosenByUser: true + }; + this._render(); + + if (e.done) { + this._resizeSession = undefined; + if (session.vertical) { + // The chosen height includes the reply and additional actions as they are now. + this._sizeModel.resetGrowth(); + } + this._storeLayout(); + this._applySize(); + this._render(); + } + } + + private _onMouseWheel(e: IMouseWheelEvent): void { + // The comment body didn't scroll, so scroll the editor instead. The widget moves along with the code. + if (this.editor instanceof CodeEditorWidget && this.editor.getOption(EditorOption.scrollbar).handleMouseWheel) { + this.editor.delegateScrollFromMouseWheelEvent(e); + e.preventDefault(); + e.stopPropagation(); + } + } + + private _bringToFront(): void { + if (ReviewFloatingWidget._frontWidget === this) { + return; + } + ReviewFloatingWidget._frontWidget?._domNode.classList.remove('front'); + ReviewFloatingWidget._frontWidget = this; + this._domNode.classList.add('front'); + } + + private _applyTheme(): void { + const theme = this._themeService.getColorTheme(); + const color = getCommentThreadWidgetStateColor(this._commentThread.state, theme) ?? Color.transparent; + this._domNode.style.setProperty(commentThreadStateColorVar, `${color}`); + this._domNode.style.setProperty(commentThreadStateBackgroundColorVar, `${color.transparent(.1)}`); + // The outline and connector must stand out from the code even when the widget's frame is subtle. + this._connector.setColor(`${getCommentThreadRangeBorderColor(this._commentThread.state, theme) ?? color}`); + this._commentThreadWidget.applyTheme(this.editor.getOption(EditorOption.fontInfo)); + } +} diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetLayout.ts b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetLayout.ts new file mode 100644 index 000000000000..45b005420798 --- /dev/null +++ b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetLayout.ts @@ -0,0 +1,572 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { clamp } from '../../../../base/common/numbers.js'; + +/** Room kept between an automatically placed widget and the edges of the editor or other widgets. */ +export const EDGE_MARGIN = 8; +/** Room kept between the commented code and a widget that is placed next to it. */ +const CODE_GAP = 24; +export const MIN_WIDTH = 240; +export const MIN_HEIGHT = 64; +/** How much of the comments stays visible when the widget is as short as it can be. */ +const MIN_COMMENTS_HEIGHT = 40; +const DEFAULT_MIN_WIDTH = 320; +const DEFAULT_MAX_WIDTH = 560; +const DEFAULT_WIDTH_RATIO = 0.4; +/** + * How many of the lines next to a widget placed right after them may leave it no room after them, and so run under it, + * so that a couple of long lines don't keep it from its code. + */ +const COVERABLE_LINES = 2; +/** The widest that a widget placed after the ends of the lines next to it is shown, so that its comments stay readable. */ +const MAX_WIDTH_BESIDE_LINES = 640; +/** Portion of the editor height that a widget sizing itself to its content may take up. */ +const AUTO_HEIGHT_RATIO = 0.6; + +export interface IRect { + readonly top: number; + readonly left: number; + readonly width: number; + readonly height: number; +} + +export interface IPoint { + readonly x: number; + readonly y: number; +} + +export interface ISize { + readonly width: number; + readonly height: number; +} + +export interface ISizeRange { + readonly min: number; + readonly max: number; +} + +/** + * Where a floating comment thread widget is placed and how large it is. + */ +export interface ICommentThreadFloatingWidgetLayout { + /** + * Distance from the top of the first commented line to the top of the widget, or `undefined` when the + * widget is vertically centered on the commented code. + */ + readonly offsetTop: number | undefined; + /** Distance from the left edge of the editor to the left edge of the widget. */ + readonly left: number; + readonly width: number; + /** The height chosen by the user, or `undefined` when the widget sizes itself to its content. */ + readonly height: number | undefined; + /** + * Whether the user moved or resized the widget. Other widgets are placed around such a widget, rather than moving + * it to keep the widgets in the order of their code. + */ + readonly isChosenByUser: boolean; +} + +/** + * Computes the line connecting the commented code to the anchor point of a widget. The code is given as the + * areas of its lines. The line starts at the point of the code's outline that is closest to the anchor, and is + * `undefined` when the anchor lies within the outline. + */ +export function getConnectorPoints(codeLines: readonly IRect[], anchor: IPoint): { from: IPoint; to: IPoint } | undefined { + let from: IPoint | undefined; + let fromDistance = Number.POSITIVE_INFINITY; + for (const line of codeLines) { + const point: IPoint = { + x: clamp(anchor.x, line.left, line.left + line.width), + y: clamp(anchor.y, line.top, line.top + line.height) + }; + const distance = Math.hypot(anchor.x - point.x, anchor.y - point.y); + if (distance < fromDistance) { + from = point; + fromDistance = distance; + } + } + if (!from || fromDistance === 0) { + return undefined; + } + return { from, to: anchor }; +} + +function roundCoordinate(value: number): number { + return Math.round(value * 100) / 100; +} + +function pointsEqual(a: IPoint, b: IPoint): boolean { + return a.x === b.x && a.y === b.y; +} + +/** + * Computes an SVG path that outlines a stack of rows, such as the lines of some code, with rounded corners. + * Each row must start where the previous one ends. + */ +export function getRowsOutlinePath(rows: readonly IRect[], cornerRadius: number): string { + if (rows.length === 0) { + return ''; + } + + // Go down the right side of the rows, then back up their left side. + let corners: IPoint[] = []; + for (const row of rows) { + corners.push({ x: row.left + row.width, y: row.top }, { x: row.left + row.width, y: row.top + row.height }); + } + for (let i = rows.length - 1; i >= 0; i--) { + const row = rows[i]; + corners.push({ x: row.left, y: row.top + row.height }, { x: row.left, y: row.top }); + } + corners = corners.map(point => ({ x: roundCoordinate(point.x), y: roundCoordinate(point.y) })); + + // Rows of the same width produce repeated points and points in the middle of straight edges. + let removed = true; + while (removed && corners.length > 2) { + removed = false; + for (let i = 0; i < corners.length && corners.length > 2; i++) { + const previous = corners[(i + corners.length - 1) % corners.length]; + const current = corners[i]; + const next = corners[(i + 1) % corners.length]; + if (pointsEqual(current, next) || (previous.x === current.x && current.x === next.x) || (previous.y === current.y && current.y === next.y)) { + corners.splice(i, 1); + removed = true; + i--; + } + } + } + + const commands: string[] = []; + for (let i = 0; i < corners.length; i++) { + const previous = corners[(i + corners.length - 1) % corners.length]; + const current = corners[i]; + const next = corners[(i + 1) % corners.length]; + const radius = Math.min(cornerRadius, Math.hypot(current.x - previous.x, current.y - previous.y) / 2, Math.hypot(next.x - current.x, next.y - current.y) / 2); + const command = i === 0 ? 'M' : 'L'; + if (radius <= 0) { + commands.push(`${command} ${current.x} ${current.y}`); + continue; + } + const towards = (target: IPoint): IPoint => { + const length = Math.hypot(target.x - current.x, target.y - current.y); + return { + x: roundCoordinate(current.x + (target.x - current.x) / length * radius), + y: roundCoordinate(current.y + (target.y - current.y) / length * radius) + }; + }; + const start = towards(previous); + const end = towards(next); + commands.push(`${command} ${start.x} ${start.y} Q ${current.x} ${current.y} ${end.x} ${end.y}`); + } + commands.push('Z'); + return commands.join(' '); +} + +/** + * The top of a widget of the given height that is vertically centered on the given code, without going + * above the start of the document. + */ +export function getCenteredTop(codeTop: number, codeBottom: number, height: number): number { + return Math.max(0, (codeTop + codeBottom - height) / 2); +} + +/** + * The width a widget starts out with in an editor whose code area has the given width. + */ +export function getDefaultFloatingWidgetWidth(editorContentWidth: number, availableWidth: number): number { + return Math.min(clamp(Math.round(editorContentWidth * DEFAULT_WIDTH_RATIO), DEFAULT_MIN_WIDTH, DEFAULT_MAX_WIDTH), availableWidth); +} + +/** + * The width of a widget that is placed right after the end of the code, level with its top, such as a new comment: the + * preferred width, or as much of it as there is room for before the edge of the editor and the obstacles there. + * `undefined` when there isn't room for a reasonably wide widget, or for the width that its content needs. + * @param code The commented code, in document coordinates. + * @param height The height of the widget. + * @param maxRight The rightmost position the right edge of the widget may take. + * @param obstacles The areas, in document coordinates, that the widget should not cover. + */ +export function getWidthBesideCode(code: IRect, height: number, preferredWidth: number, minWidth: number, maxRight: number, obstacles: readonly IRect[]): number | undefined { + const left = code.left + code.width + CODE_GAP; + let right = maxRight - EDGE_MARGIN; + for (const obstacle of obstacles) { + if (obstacle.left + obstacle.width > left && obstacle.top < code.top + height && code.top < obstacle.top + obstacle.height) { + right = Math.min(right, obstacle.left - EDGE_MARGIN); + } + } + const availableWidth = Math.floor(right - left); + const neededWidth = Math.max(minWidth, Math.min(preferredWidth, DEFAULT_MIN_WIDTH)); + return availableWidth >= neededWidth ? Math.min(preferredWidth, availableWidth) : undefined; +} + +/** + * Where a widget goes right after the end of the lines next to it, and how wide it is. + */ +export interface IBesideLinesPlacement { + /** Where the lines that the widget goes after end. */ + readonly linesRight: number; + readonly width: number; +} + +/** + * Where a widget goes right after the end of the lines next to it, such as an existing comment, and how wide it is: as + * wide as its content fills, up to a readable width and the room there is, and no narrower than its default width. + * The widget goes after every line that leaves it room for its default width, rather than hiding it. It only hides a + * couple of lines that leave it no room after them, and then keeps its default width, so that it hides no more of + * them. `undefined` when more lines leave it no room, or when the code does. + * @param lines Lines of the editor, of which those between `top` and `bottom` are next to the widget. + * @param codeRight Where the commented code ends, which the widget never hides. + * @param maxRight The rightmost position the right edge of the widget may take. + */ +export function getPlacementBesideLines(lines: readonly IRect[], top: number, bottom: number, codeRight: number, maxRight: number, defaultWidth: number, naturalWidth: number): IBesideLinesPlacement | undefined { + // The widget has room for its default width after lines that end up to here. + const maxLinesRight = maxRight - EDGE_MARGIN - CODE_GAP - defaultWidth; + let linesRight = codeRight; + let hiddenLines = 0; + for (const line of lines) { + if (line.top < bottom && top < line.top + line.height) { + const right = line.left + line.width; + if (right > maxLinesRight) { + hiddenLines++; + } else { + linesRight = Math.max(linesRight, right); + } + } + } + if (hiddenLines > COVERABLE_LINES || linesRight > maxLinesRight) { + return undefined; + } + const availableWidth = Math.floor(maxRight - EDGE_MARGIN - (linesRight + CODE_GAP)); + return { linesRight, width: hiddenLines ? defaultWidth : Math.max(defaultWidth, Math.min(naturalWidth, MAX_WIDTH_BESIDE_LINES, availableWidth)) }; +} + +/** + * The scroll position that shows the commented code and the widget, all in document coordinates, or `undefined` when + * no scrolling is needed. When they don't fit in the viewport together, the widget is shown in full, with as much of + * the start of the code as fits. + */ +export function getRevealScrollTop(code: { top: number; bottom: number }, widget: { top: number; bottom: number }, scrollTop: number, viewportHeight: number): number | undefined { + const top = Math.min(code.top, widget.top); + const bottom = Math.max(code.bottom, widget.bottom); + if (bottom - top <= viewportHeight) { + const isInView = top >= scrollTop && bottom <= scrollTop + viewportHeight; + return isInView ? undefined : Math.max(0, (top + bottom - viewportHeight) / 2); + } + if (widget.top >= scrollTop && widget.bottom <= scrollTop + viewportHeight) { + return undefined; + } + // A widget that is taller than the viewport is shown from its top. + return Math.max(0, clamp(code.top - EDGE_MARGIN, widget.bottom + EDGE_MARGIN - viewportHeight, widget.top - EDGE_MARGIN)); +} + +function rectsIntersect(a: IRect, b: IRect): boolean { + return a.left < b.left + b.width && b.left < a.left + a.width && a.top < b.top + b.height && b.top < a.top + a.height; +} + +/** + * An area, in document coordinates, that another widget takes up, and where the code that widget is about starts. + */ +export interface IFloatingWidgetObstacle extends IRect { + /** The top of the code that the other widget is about, in document coordinates, which orders the widgets. */ + readonly codeTop: number; +} + +/** + * Whether two widgets, one above the other, are out of the order of their code: the widget for the later code is above + * the other one. + */ +function areOutOfOrder(a: IFloatingWidgetObstacle, b: IFloatingWidgetObstacle): boolean { + if (a.left >= b.left + b.width || b.left >= a.left + a.width) { + return false; + } + return a.codeTop < b.codeTop ? b.top + b.height <= a.top : b.codeTop < a.codeTop && a.top + a.height <= b.top; +} + +/** + * Whether a widget is in the way of another widget: it covers it, or it's above or below it, out of the order of their + * code. + */ +export function isInTheWayOf(widget: IFloatingWidgetObstacle, other: IFloatingWidgetObstacle): boolean { + return rectsIntersect(widget, other) || areOutOfOrder(widget, other); +} + +export interface IFloatingWidgetPlacementRequest { + /** The leftmost position the widget may take. */ + readonly minLeft: number; + /** The rightmost position the right edge of the widget may take. */ + readonly maxRight: number; + readonly width: number; + readonly height: number; + /** The commented code, in document coordinates, or `undefined` for comments on the whole file. */ + readonly code: IRect | undefined; + /** The areas that other widgets take up, which the widget should not cover, and stays in the order of their code with. */ + readonly obstacles: readonly IFloatingWidgetObstacle[]; + /** The height of the area that the editor can scroll through, which the widget is kept within. */ + readonly scrollableHeight: number; + /** + * Places the widget right after the end of the code, level with its top, when there is room for it there, such as + * for a new comment. See {@link getWidthBesideCode}. + */ + readonly besideCode?: boolean; + /** + * Where the lines next to the code end. The widget is placed right after them, vertically centered on the code, + * when there is room, rather than at the right edge of the editor. See {@link getPlacementBesideLines}. + */ + readonly linesRight?: number; +} + +export interface IFloatingWidgetPlacement { + readonly top: number; + readonly left: number; + /** Whether the widget is vertically centered on the code. */ + readonly centered: boolean; +} + +/** + * Places a widget at the right edge of the editor, vertically centered on the commented code. When requested and there + * is room, the widget goes right after the end of the code, level with its top, or right after the end of the lines + * next to the code instead. When the code leaves no room for the widget at the right edge, the widget goes below the + * code, still at the right edge, so that it covers neither the code nor the start of the lines below it. When the + * widget would cover the code or one of the obstacles, it moves to the closest position above or below them that is + * free, within the area that the editor can scroll through. + * + * Widgets stay in the order of their code: a widget that moves out of the way of another one goes to the side of it + * that its code is on. It only goes to the other side when there's no room on its own side. + */ +export function computeFloatingWidgetPlacement(request: IFloatingWidgetPlacementRequest): IFloatingWidgetPlacement { + const { minLeft, width, height, code } = request; + const maxLeft = Math.max(minLeft, request.maxRight - EDGE_MARGIN - width); + let left = maxLeft; + let preferredTop = code ? getCenteredTop(code.top, code.top + code.height, height) : 0; + let centered = true; + const codeRight = code ? code.left + code.width : 0; + if (code && request.besideCode && codeRight + CODE_GAP <= maxLeft) { + left = Math.max(minLeft, codeRight + CODE_GAP); + preferredTop = code.top; + centered = false; + } else if (code && codeRight + CODE_GAP > maxLeft) { + preferredTop = code.top + code.height + EDGE_MARGIN; + centered = false; + } else if (code && request.linesRight !== undefined) { + left = clamp(Math.max(codeRight, request.linesRight) + CODE_GAP, minLeft, maxLeft); + } + + // The free position closest to the preferred one is the preferred position, an edge of the scrollable area, or + // just next to one of the areas to keep clear of. + const maxTop = Math.max(0, request.scrollableHeight - EDGE_MARGIN - height); + const areas = code ? [...request.obstacles, code] : request.obstacles; + const candidates = [preferredTop, 0, maxTop]; + for (const area of areas) { + candidates.push(area.top + area.height + EDGE_MARGIN, area.top - EDGE_MARGIN - height); + } + const getClosestFreeTop = (isAllowed: (top: number) => boolean) => { + let closest: number | undefined; + for (const candidate of candidates) { + const candidateTop = clamp(candidate, 0, maxTop); + if ((closest === undefined || Math.abs(candidateTop - preferredTop) < Math.abs(closest - preferredTop)) + && isAllowed(candidateTop) && !areas.some(area => rectsIntersect({ top: candidateTop, left, width, height }, area))) { + closest = candidateTop; + } + } + return closest; + }; + + // The widget is out of order with a widget above or below it when it's on the side of it that its code isn't on. + const codeTop = code?.top ?? 0; + const isOutOfOrder = (top: number, obstacle: IFloatingWidgetObstacle) => areOutOfOrder({ top, left, width, height, codeTop }, obstacle); + // Widgets that are out of order with the preferred position anyway don't keep the widget from the others. Those are + // ones that the user moved there, and ones for code that starts earlier but goes on long enough for them to be + // centered below this one, which would otherwise push this one far from its code. + const unmovedTop = clamp(preferredTop, 0, maxTop); + const orderedObstacles = request.obstacles.filter(obstacle => !isOutOfOrder(unmovedTop, obstacle)); + // When no position is free, the widget stays as close to the preferred position as it can. + const top = getClosestFreeTop(top => !orderedObstacles.some(obstacle => isOutOfOrder(top, obstacle))) + ?? getClosestFreeTop(() => true) + ?? unmovedTop; + return { top, left, centered: centered && top === preferredTop }; +} + +/** + * The widths that the content of a widget needs, which don't depend on the widget's width. + */ +export interface IFloatingWidgetContentWidths { + /** The width that shows the thread's title actions, reply and additional actions in full. */ + readonly minimum: number; + /** The width at which none of the content wraps or is cut off. */ + readonly natural: number; +} + +/** + * The heights of the content of a widget at its current width. + */ +export interface IFloatingWidgetContentHeights { + /** The height of everything but the comments: the frame, title, reply and additional actions. */ + readonly fixed: number; + /** The height of all of the comments. */ + readonly comments: number; +} + +/** + * Sizes a floating comment thread widget to its content, the size chosen by the user, and the size of the editor. + * + * The editor size is captured when the widget is shown, reset or resized by the user, so that resizing the editor + * doesn't resize a widget that is shown. When the reply or additional actions below the comments grow, such as when + * a reply is expanded, the widget grows down by as much, so that the reply stays in place. When that would take the + * widget past the bottom of the editor, the widget moves up instead. + */ +export class FloatingWidgetSizeModel { + + private _editorSize: ISize = { width: 0, height: 0 }; + /** The fixed height of the content when the widget's size and placement were chosen. */ + private _fixedHeightBase: number | undefined; + private _growth = 0; + private _upwardShift = 0; + + /** The size of the editor that limits the widget's size. */ + get editorSize(): ISize { + return this._editorSize; + } + + /** How much the reply and additional actions have grown since the widget's size and placement were chosen. */ + get growthBelowComments(): number { + return this._growth; + } + + /** How far the widget is moved up to keep its grown reply and additional actions within the editor. */ + get upwardShift(): number { + return this._upwardShift; + } + + captureEditorSize(editorSize: ISize): void { + this._editorSize = editorSize; + } + + /** + * Lets the widget take up the editor's current size, without first shrinking to an editor that became smaller + * after the size was captured. + */ + growEditorSize(editorSize: ISize): void { + this._editorSize = { width: Math.max(this._editorSize.width, editorSize.width), height: Math.max(this._editorSize.height, editorSize.height) }; + } + + /** + * Takes the reply and additional actions, as they are when the content is next measured, as the ones that the + * widget's size and placement are for. + */ + resetGrowth(): void { + this._fixedHeightBase = undefined; + this._growth = 0; + this._upwardShift = 0; + } + + /** + * Stops moving the widget up, such as when the user moves the widget, which includes the upward shift. + */ + clearUpwardShift(): void { + this._upwardShift = 0; + } + + /** + * Measures how much the reply and additional actions have grown, and returns whether that changed. + */ + updateGrowth(content: IFloatingWidgetContentHeights): boolean { + this._fixedHeightBase ??= content.fixed; + const growth = content.fixed - this._fixedHeightBase; + const changed = growth !== this._growth; + this._growth = growth; + return changed; + } + + /** + * The widths the widget can have: wide enough to show its title actions, reply and additional actions, and no + * wider than the editor. + */ + getWidthRange(content: IFloatingWidgetContentWidths): ISizeRange { + const editorWidth = this._editorSize.width; + return { min: Math.min(Math.max(MIN_WIDTH, content.minimum), editorWidth), max: editorWidth }; + } + + /** + * The width that the widget is shown at: the preferred width, but, unless a reply or comment is being written, no + * wider than its content can fill. The user can still make the widget wider. + */ + getDefaultWidth(content: IFloatingWidgetContentWidths, preferredWidth: number, isEditing: boolean): number { + const range = this.getWidthRange(content); + return clamp(isEditing ? preferredWidth : Math.min(preferredWidth, content.natural), range.min, range.max); + } + + /** + * The heights the widget can have: tall enough to show its title, reply and additional actions with some of the + * comments, and no taller than its content or the editor. + */ + getHeightRange(content: IFloatingWidgetContentHeights): ISizeRange { + const max = Math.min(content.fixed + content.comments, Math.max(MIN_HEIGHT, this._editorSize.height - 2 * EDGE_MARGIN)); + return { min: Math.min(content.fixed + Math.min(content.comments, MIN_COMMENTS_HEIGHT), max), max }; + } + + /** + * The tallest that the widget sizes itself to its content when the user didn't choose a height, unless its title, + * reply and additional actions alone are taller, and before they grow. + */ + get maxAutoHeight(): number { + return Math.max(MIN_HEIGHT, Math.floor(this._editorSize.height * AUTO_HEIGHT_RATIO)); + } + + /** + * The height of the widget for the height chosen by the user, or for its content when the user didn't choose one. + * Growth of the reply and additional actions is added, rather than taken from the comments. + */ + getHeight(content: IFloatingWidgetContentHeights, chosenHeight: number | undefined): number { + const range = this.getHeightRange(content); + const height = chosenHeight !== undefined ? chosenHeight + this._growth : Math.min(range.max, this.maxAutoHeight + this._growth); + return clamp(height, range.min, range.max); + } + + /** + * The height that the comments get in a widget of the given height: the space that the rest of the content leaves. + * A widget that is too short for the rest of its content, such as in a short editor, scrolls as a whole, and still + * shows some of the comments. + */ + getCommentsHeight(content: IFloatingWidgetContentHeights, height: number): number { + return Math.max(Math.min(content.comments, MIN_COMMENTS_HEIGHT), height - content.fixed); + } + + /** + * The top of the widget in document coordinates. A centered widget stays centered as it was before its reply and + * additional actions grew, so that it grows down. The widget is kept within the area that the editor can scroll + * through, which the widget doesn't extend, so that the editor can always scroll to all of it. + * @param offsetTop The widget's distance from the top of the code, or `undefined` when it's centered on the code. + * @param code The vertical extent of the commented code in document coordinates. + * @param scrollableHeight The height of the area that the editor can scroll through. + */ + getTop(offsetTop: number | undefined, code: { top: number; bottom: number }, height: number, scrollableHeight: number): number { + return clamp(this._getUnshiftedTop(offsetTop, code, height) - this._upwardShift, 0, Math.max(0, scrollableHeight - EDGE_MARGIN - height)); + } + + /** + * Moves the widget up as far as needed to show its grown reply and additional actions above the bottom of the + * viewport, without moving its top out of view. The widget isn't moved back down while they are grown, such as + * while a reply is being typed. + * @param scrollTop The document coordinate at the top of the viewport. + */ + updateUpwardShift(offsetTop: number | undefined, code: { top: number; bottom: number }, height: number, scrollTop: number, viewportHeight: number): void { + if (this._growth <= 0) { + this._upwardShift = 0; + return; + } + const top = this._getUnshiftedTop(offsetTop, code, height) - scrollTop; + if (top >= viewportHeight) { + // The widget is out of view, so its reply isn't being shown. + return; + } + const overflow = top + height - (viewportHeight - EDGE_MARGIN); + const roomAbove = Math.max(0, top - EDGE_MARGIN); + this._upwardShift = Math.max(this._upwardShift, clamp(overflow, 0, roomAbove)); + } + + private _getUnshiftedTop(offsetTop: number | undefined, code: { top: number; bottom: number }, height: number): number { + return offsetTop !== undefined ? code.top + offsetTop : getCenteredTop(code.top, code.bottom, height - this._growth); + } +} diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetRoom.ts b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetRoom.ts new file mode 100644 index 000000000000..2b912df609ee --- /dev/null +++ b/src/vs/workbench/contrib/comments/browser/commentThreadFloatingWidgetRoom.ts @@ -0,0 +1,101 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { Disposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { ICodeEditor, IViewZone } from '../../../../editor/browser/editorBrowser.js'; +import { EDGE_MARGIN, IRect } from './commentThreadFloatingWidgetLayout.js'; + +/** + * Space after the content of an editor that grows with its content, like the editors of the multi diff editor, which + * makes the editor tall enough for the floating widgets that reach below its content. + * + * The space is measured from the end of the last line, so that it doesn't depend on itself or on other space after the + * last line, like the space that a diff editor adds to align its sides when the other side makes room for its widgets. + */ +export class FloatingWidgetRoom extends Disposable { + + private readonly _zone: IViewZone = { afterLineNumber: 0, heightInPx: 0, domNode: dom.$('div'), showInHiddenAreas: true }; + private _zoneId: string | undefined; + private readonly _scheduler: dom.AnimationFrameScheduler; + + /** + * @param _getWidgets The areas, in document coordinates, of the widgets that are shown in the editor. + */ + constructor(private readonly _editor: ICodeEditor, private readonly _getWidgets: () => Iterable) { + super(); + this._scheduler = this._register(new dom.AnimationFrameScheduler(_editor.getContainerDomNode(), () => this._update())); + // A new model gets a new view, which doesn't have the space. + this._register(_editor.onDidChangeModel(() => this._zoneId = undefined)); + // Edits and hidden lines move the end of the content. + this._register(_editor.onDidContentSizeChange(() => this.update())); + this._register(toDisposable(() => this._setHeight(0))); + } + + /** + * The part of the document that is in view, in document coordinates. The editor is as tall as its content, so the + * view that it's shown in scrolls instead, and may show only part of the editor, or more than the editor. + */ + getViewport(): { top: number; height: number } { + const editorNode = this._editor.getContainerDomNode(); + const view = dom.findParentWithClass(editorNode, 'multiDiffEditor'); + const viewRect = view?.getBoundingClientRect() ?? { top: 0, height: dom.getWindow(editorNode).innerHeight }; + return { top: this._editor.getScrollTop() + viewRect.top - editorNode.getBoundingClientRect().top, height: viewRect.height }; + } + + /** + * How far down the widgets can go. The editor grows to make room for them, so they can go as far below the content + * as the window is tall, which is taller than any widget. + */ + getScrollableHeight(): number { + return this._getContentBottom() + dom.getWindow(this._editor.getContainerDomNode()).innerHeight; + } + + /** + * Makes room for the widgets at the next animation frame, once for all the widgets that moved or resized until + * then. Widgets also resize while the browser delivers resize notifications, which resizing the editor would delay. + */ + update(): void { + this._scheduler.schedule(); + } + + /** + * The bottom of the last line, without the space after it. + */ + private _getContentBottom(): number { + const model = this._editor.getModel(); + return model ? this._editor.getBottomForLineNumber(model.getLineCount()) : 0; + } + + private _update(): void { + let bottom = 0; + for (const widget of this._getWidgets()) { + if (widget) { + bottom = Math.max(bottom, widget.top + widget.height + EDGE_MARGIN); + } + } + this._setHeight(Math.max(0, Math.ceil(bottom - this._getContentBottom()))); + } + + private _setHeight(height: number): void { + const lineCount = this._editor.getModel()?.getLineCount(); + const isUnchanged = this._zoneId ? height === this._zone.heightInPx && lineCount === this._zone.afterLineNumber : height === 0; + if (lineCount === undefined || isUnchanged) { + return; + } + this._zone.afterLineNumber = lineCount; + this._zone.heightInPx = height; + this._editor.changeViewZones(accessor => { + if (!this._zoneId) { + this._zoneId = accessor.addZone(this._zone); + } else if (height > 0) { + accessor.layoutZone(this._zoneId); + } else { + accessor.removeZone(this._zoneId); + this._zoneId = undefined; + } + }); + } +} diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadHeader.ts b/src/vs/workbench/contrib/comments/browser/commentThreadHeader.ts index 021962b21335..39be1f0115bf 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadHeader.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadHeader.ts @@ -33,16 +33,30 @@ function threadHasComments(comments: ReadonlyArray | undefine return !!comments && comments.length > 0; } +/** + * Overrides how the action that collapses the comment thread is presented. + */ +export interface ICommentThreadCollapseActionPresentation { + readonly label: string; + readonly icon: ThemeIcon; +} + export class CommentThreadHeader extends Disposable { private _headElement: HTMLElement; + private _titleElement!: HTMLElement; private _headingLabel!: HTMLElement; + private _actionsContainer!: HTMLElement; private _actionbarWidget!: ActionBar; private _collapseAction!: Action; private _contextMenuActionRunner: ActionRunner | undefined; + get domNode(): HTMLElement { + return this._headElement; + } + constructor( container: HTMLElement, - private _delegate: { collapse: () => void }, + private _delegate: { collapse: () => void; collapseAction?: ICommentThreadCollapseActionPresentation }, private _commentMenus: CommentMenus, private _commentThread: languages.CommentThread, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @@ -57,25 +71,26 @@ export class CommentThreadHeader extends Disposable { } protected _fillHead(): void { - const titleElement = dom.append(this._headElement, dom.$('.review-title')); + this._titleElement = dom.append(this._headElement, dom.$('.review-title')); - this._headingLabel = dom.append(titleElement, dom.$('span.filename')); + this._headingLabel = dom.append(this._titleElement, dom.$('span.filename')); this.createThreadLabel(); - const actionsContainer = dom.append(this._headElement, dom.$('.review-actions')); - this._actionbarWidget = new ActionBar(actionsContainer, { + this._actionsContainer = dom.append(this._headElement, dom.$('.review-actions')); + this._actionbarWidget = new ActionBar(this._actionsContainer, { actionViewItemProvider: createActionViewItem.bind(undefined, this._instantiationService) }); this._register(this._actionbarWidget); - const collapseClass = threadHasComments(this._commentThread.comments) ? COLLAPSE_ACTION_CLASS : DELETE_ACTION_CLASS; - this._collapseAction = new Action(CommentCommandId.Hide, nls.localize('label.collapse', "Collapse"), collapseClass, true, () => this._delegate.collapse()); + const collapseActionClass = this._delegate.collapseAction ? 'expand-review-action ' + ThemeIcon.asClassName(this._delegate.collapseAction.icon) : COLLAPSE_ACTION_CLASS; + const collapseClass = threadHasComments(this._commentThread.comments) ? collapseActionClass : DELETE_ACTION_CLASS; + this._collapseAction = new Action(CommentCommandId.Hide, this._delegate.collapseAction?.label ?? nls.localize('label.collapse', "Collapse"), collapseClass, true, () => this._delegate.collapse()); if (!threadHasComments(this._commentThread.comments)) { const commentsChanged: MutableDisposable = this._register(new MutableDisposable()); commentsChanged.value = this._commentThread.onDidChangeComments(() => { if (threadHasComments(this._commentThread.comments)) { - this._collapseAction.class = COLLAPSE_ACTION_CLASS; + this._collapseAction.class = collapseActionClass; commentsChanged.clear(); } }); @@ -131,6 +146,19 @@ export class CommentThreadHeader extends Disposable { this._headElement.style.lineHeight = this._headElement.style.height; } + /** + * Measures the width the header needs to show all of its actions, and the width that also shows its whole title. + */ + measureWidths(): { minimum: number; natural: number } { + const targetWindow = dom.getWindow(this._headElement); + const titleStyle = targetWindow.getComputedStyle(this._titleElement); + const actionsStyle = targetWindow.getComputedStyle(this._actionsContainer); + const minimum = (parseFloat(titleStyle.marginLeft) || 0) + (parseFloat(titleStyle.marginRight) || 0) + + (parseFloat(actionsStyle.paddingLeft) || 0) + this._actionbarWidget.domNode.offsetWidth + (parseFloat(actionsStyle.paddingRight) || 0); + // The title is cut off with an ellipsis when it doesn't fit. + return { minimum, natural: minimum + this._titleElement.scrollWidth }; + } + private onContextMenu(e: MouseEvent) { const actions = this._commentMenus.getCommentThreadTitleContextActions(this._contextKeyService); if (!actions.length) { diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadRangeDecorator.ts b/src/vs/workbench/contrib/comments/browser/commentThreadRangeDecorator.ts index 1b083f5b8479..2b8412b8dfbd 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadRangeDecorator.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadRangeDecorator.ts @@ -7,7 +7,7 @@ import { Disposable, dispose, IDisposable } from '../../../../base/common/lifecy import { ICodeEditor } from '../../../../editor/browser/editorBrowser.js'; import { IRange } from '../../../../editor/common/core/range.js'; import { CommentThread, CommentThreadCollapsibleState } from '../../../../editor/common/languages.js'; -import { IModelDecorationOptions, IModelDeltaDecoration } from '../../../../editor/common/model.js'; +import { IModelDeltaDecoration } from '../../../../editor/common/model.js'; import { ModelDecorationOptions } from '../../../../editor/common/model/textModel.js'; import { ICommentInfo, ICommentService } from './commentService.js'; @@ -32,33 +32,33 @@ export class CommentThreadRangeDecorator extends Disposable { private static description = 'comment-thread-range-decorator'; private decorationOptions: ModelDecorationOptions; private activeDecorationOptions: ModelDecorationOptions; + private lineEndDecorationOptions: ModelDecorationOptions; + private activeLineEndDecorationOptions: ModelDecorationOptions; private decorationIds: string[] = []; private activeDecorationIds: string[] = []; private editor: ICodeEditor | undefined; private threadCollapseStateListeners: IDisposable[] = []; private currentThreadCollapseStateListener: IDisposable | undefined; - constructor(commentService: ICommentService) { + /** + * @param fillsEditorWidth Whether the backgrounds of ranges that span several lines extend to the full width + * of the editor, rather than ending with the code on each line. + */ + constructor(commentService: ICommentService, private readonly fillsEditorWidth: () => boolean = () => true) { super(); - const decorationOptions: IModelDecorationOptions = { + const createOptions = (className: string, shouldFillLineOnLineBreak: boolean) => ModelDecorationOptions.createDynamic({ description: CommentThreadRangeDecorator.description, isWholeLine: false, zIndex: 20, - className: 'comment-thread-range', - shouldFillLineOnLineBreak: true - }; - - this.decorationOptions = ModelDecorationOptions.createDynamic(decorationOptions); + className, + shouldFillLineOnLineBreak + }); - const activeDecorationOptions: IModelDecorationOptions = { - description: CommentThreadRangeDecorator.description, - isWholeLine: false, - zIndex: 20, - className: 'comment-thread-range-current', - shouldFillLineOnLineBreak: true - }; + this.decorationOptions = createOptions('comment-thread-range', true); + this.activeDecorationOptions = createOptions('comment-thread-range-current', true); + this.lineEndDecorationOptions = createOptions('comment-thread-range', false); + this.activeLineEndDecorationOptions = createOptions('comment-thread-range-current', false); - this.activeDecorationOptions = ModelDecorationOptions.createDynamic(activeDecorationOptions); this._register(commentService.onDidChangeCurrentCommentThread(thread => { this.updateCurrent(thread); })); @@ -82,7 +82,7 @@ export class CommentThreadRangeDecorator extends Disposable { this.updateCurrent(undefined); } }); - newDecoration.push(new CommentThreadRangeDecoration(range, this.activeDecorationOptions)); + newDecoration.push(new CommentThreadRangeDecoration(range, this.fillsEditorWidth() ? this.activeDecorationOptions : this.activeLineEndDecorationOptions)); } } } @@ -101,6 +101,7 @@ export class CommentThreadRangeDecorator extends Disposable { this.editor = editor; const commentThreadRangeDecorations: CommentThreadRangeDecoration[] = []; + const options = this.fillsEditorWidth() ? this.decorationOptions : this.lineEndDecorationOptions; for (const info of commentInfos) { info.threads.forEach(thread => { if (thread.isDisposed) { @@ -122,7 +123,7 @@ export class CommentThreadRangeDecorator extends Disposable { return; } - commentThreadRangeDecorations.push(new CommentThreadRangeDecoration(range, this.decorationOptions)); + commentThreadRangeDecorations.push(new CommentThreadRangeDecoration(range, options)); }); } diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadWidget.ts b/src/vs/workbench/contrib/comments/browser/commentThreadWidget.ts index 8e31f0b21168..a06c45667983 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadWidget.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadWidget.ts @@ -5,8 +5,10 @@ import './media/review.css'; import * as dom from '../../../../base/browser/dom.js'; +import { DomScrollableElement } from '../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { Emitter } from '../../../../base/common/event.js'; import { Disposable, dispose, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { ScrollbarVisibility } from '../../../../base/common/scrollable.js'; import { URI } from '../../../../base/common/uri.js'; import * as languages from '../../../../editor/common/languages.js'; import { IMarkdownRendererExtraOptions } from '../../../../platform/markdown/browser/markdownRenderer.js'; @@ -16,7 +18,7 @@ import { CommentMenus } from './commentMenus.js'; import { CommentReply } from './commentReply.js'; import { ICommentService } from './commentService.js'; import { CommentThreadBody } from './commentThreadBody.js'; -import { CommentThreadHeader } from './commentThreadHeader.js'; +import { CommentThreadHeader, ICommentThreadCollapseActionPresentation } from './commentThreadHeader.js'; import { CommentThreadAdditionalActions } from './commentThreadAdditionalActions.js'; import { CommentContextKeys } from '../common/commentContextKeys.js'; import { ICommentThreadWidget } from '../common/commentThreadWidget.js'; @@ -35,6 +37,20 @@ import { isCodeEditor } from '../../../../editor/browser/editorBrowser.js'; export const COMMENTEDITOR_DECORATION_KEY = 'commenteditordecoration'; +/** + * Options for how a comment thread widget presents the thread. + */ +export interface ICommentThreadWidgetOptions { + /** Overrides how the action that collapses the thread is presented. */ + readonly collapseAction?: ICommentThreadCollapseActionPresentation; + /** + * Lets only the comments scroll, within the height set by {@link CommentThreadWidget.layoutCommentsHeight}, so that + * the reply and the additional actions below them stay in view. When the thread is too short even for those, such + * as in a short editor, the whole body scrolls. + */ + readonly scrollableComments?: boolean; +} + export class CommentThreadWidget extends Disposable implements ICommentThreadWidget { private _header!: CommentThreadHeader; private _body: CommentThreadBody; @@ -47,12 +63,70 @@ export class CommentThreadWidget extends private _focusedContextKey: IContextKey; private _onDidResize = this._register(new Emitter()); onDidResize = this._onDidResize.event; + private readonly _onDidChangeContentSize = this._register(new Emitter()); + /** Fires when the size that the thread's content needs changes. Only fires when the comments are scrollable. */ + readonly onDidChangeContentSize = this._onDidChangeContentSize.event; + private _contentResizeObserver: dom.DisposableResizeObserver | undefined; + /** Scrolls the whole body when the comments are scrollable. */ + private _bodyScrollable: DomScrollableElement | undefined; private _commentThreadState: languages.CommentThreadState | undefined; get commentThread() { return this._commentThread; } + + get headerDomNode(): HTMLElement { + return this._header.domNode; + } + + /** + * Whether a reply is being written or a comment is being edited. The reply of a thread without comments is a new + * comment, which is being written even before its editor opens. + */ + get isEditing(): boolean { + const isWritingReply = !!this._commentReply && (this._commentReply.isReplyExpanded || !this._commentThread.comments?.length); + return isWritingReply || this._body.hasCommentsInEditMode(); + } + + /** + * Measures the width the thread needs to show its title actions, reply and additional actions in full, and the + * width at which none of its content wraps or is cut off. Neither depends on the thread's width. + */ + measureWidths(): { minimum: number; natural: number } { + const header = this._header.measureWidths(); + const reply = this._commentReply?.measureMinimumWidth() ?? 0; + const additionalActions = this._additionalActions?.measureWidth() ?? 0; + return { + minimum: Math.max(header.minimum, reply, additionalActions), + natural: Math.max(header.natural, reply, additionalActions, this._body.measureNaturalWidth()) + }; + } + + /** + * Measures, at the thread's current width, the height of everything but the comments, and the height of the comments. + */ + measureHeights(): { fixed: number; comments: number } { + const body = this._body.measureHeights(); + const bodyScrollableNode = this._bodyScrollable?.getDomNode(); + const bodyScrollableFrame = bodyScrollableNode ? bodyScrollableNode.offsetHeight - bodyScrollableNode.clientHeight : 0; + return { fixed: this._header.domNode.offsetHeight + bodyScrollableFrame + body.besideComments, comments: body.comments }; + } + + /** + * Sets the height within which scrollable comments scroll. + */ + layoutCommentsHeight(height: number): void { + this._body.layoutCommentsHeight(height); + } + + /** + * Scrolls scrollable comments to the given comment. + */ + revealComment(commentUniqueId: number): void { + this._body.revealComment(commentUniqueId); + } + constructor( readonly container: HTMLElement, readonly _parentEditor: LayoutableEditor, @@ -69,6 +143,7 @@ export class CommentThreadWidget extends actionRunner: (() => void) | null; collapse: () => Promise; }, + private readonly _options: ICommentThreadWidgetOptions | undefined, @ICommentService private readonly commentService: ICommentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IKeybindingService private readonly _keybindingService: IKeybindingService @@ -85,7 +160,8 @@ export class CommentThreadWidget extends CommentThreadHeader, container, { - collapse: this._containerDelegate.collapse.bind(this) + collapse: this._containerDelegate.collapse.bind(this), + collapseAction: this._options?.collapseAction }, this._commentMenus, this._commentThread @@ -94,8 +170,19 @@ export class CommentThreadWidget extends this._header.updateCommentThread(this._commentThread); const bodyElement = dom.$('.body'); - container.appendChild(bodyElement); - this._register(toDisposable(() => bodyElement.remove())); + let bodyDomNode = bodyElement; + if (this._options?.scrollableComments) { + const bodyScrollable = this._bodyScrollable = this._register(new DomScrollableElement(bodyElement, { + className: 'comment-thread-body-scrollable', + vertical: ScrollbarVisibility.Auto, + horizontal: ScrollbarVisibility.Hidden + })); + bodyDomNode = bodyScrollable.getDomNode(); + // Focusing an element that is scrolled out of view scrolls the body natively. + this._register(dom.addDisposableListener(bodyElement, dom.EventType.SCROLL, () => bodyScrollable.scanDomNode())); + } + container.appendChild(bodyDomNode); + this._register(toDisposable(() => bodyDomNode.remove())); const tracker = this._register(dom.trackFocus(bodyElement)); this._register(registerNavigableContainer({ @@ -129,7 +216,8 @@ export class CommentThreadWidget extends this._commentThread, this._pendingEdits, this._scopedInstantiationService, - this + this, + !!this._options?.scrollableComments ) as unknown as CommentThreadBody; this._register(this._body); this._setAriaLabel(); @@ -230,6 +318,25 @@ export class CommentThreadWidget extends await this._body.display(); + const bodyScrollable = this._bodyScrollable; + if (bodyScrollable) { + const onDidChangeContentSize = () => { + this._onDidChangeContentSize.fire(); + // The body scrolls when the space it gets is too short for its content. + bodyScrollable.scanDomNode(); + }; + this._register(this._body.onDidChangeCommentsSize(onDidChangeContentSize)); + // The reply and the additional actions take up the space below the comments. + this._contentResizeObserver = this._register(new dom.DisposableResizeObserver('commentThreadWidget', entries => { + if (entries.some(entry => entry.target !== bodyScrollable.getDomNode())) { + onDidChangeContentSize(); + } else { + bodyScrollable.scanDomNode(); + } + }, dom.getWindow(this.container))); + this._register(this._contentResizeObserver.observe(bodyScrollable.getDomNode())); + } + // create comment thread only when it supports reply if (this._commentThread.canReply) { this._createCommentForm(focus); @@ -277,6 +384,9 @@ export class CommentThreadWidget extends this._commentThreadDisposables.push(this._commentThread.onDidChangeLabel(_ => { this._header.createThreadLabel(); + if (this._options?.scrollableComments) { + this._onDidChangeContentSize.fire(); + } })); } @@ -298,6 +408,9 @@ export class CommentThreadWidget extends ); this._register(this._commentReply); + if (this._contentResizeObserver) { + this._register(this._contentResizeObserver.observe(this._commentReply.domNode)); + } } private _createAdditionalActions() { @@ -311,6 +424,9 @@ export class CommentThreadWidget extends ); this._register(this._additionalActions); + if (this._contentResizeObserver && this._additionalActions.domNode) { + this._register(this._contentResizeObserver.observe(this._additionalActions.domNode)); + } } getCommentCoords(commentUniqueId: number) { diff --git a/src/vs/workbench/contrib/comments/browser/commentThreadZoneWidget.ts b/src/vs/workbench/contrib/comments/browser/commentThreadZoneWidget.ts index 00bc6005901b..b8fd16af43a3 100644 --- a/src/vs/workbench/contrib/comments/browser/commentThreadZoneWidget.ts +++ b/src/vs/workbench/contrib/comments/browser/commentThreadZoneWidget.ts @@ -14,41 +14,17 @@ import * as languages from '../../../../editor/common/languages.js'; import { ZoneWidget } from '../../../../editor/contrib/zoneWidget/browser/zoneWidget.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; -import { IColorTheme, IThemeService } from '../../../../platform/theme/common/themeService.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; import { CommentGlyphWidget } from './commentGlyphWidget.js'; import { ICommentService } from './commentService.js'; -import { ICommentThreadWidget } from '../common/commentThreadWidget.js'; import { EditorOption } from '../../../../editor/common/config/editorOptions.js'; import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; import { CommentThreadWidget } from './commentThreadWidget.js'; -import { commentThreadStateBackgroundColorVar, commentThreadStateColorVar, getCommentThreadStateBorderColor } from './commentColors.js'; -import { peekViewBorder } from '../../../../editor/contrib/peekView/browser/peekView.js'; +import { commentThreadStateBackgroundColorVar, commentThreadStateColorVar } from './commentColors.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { StableEditorScrollState } from '../../../../editor/browser/stableEditorScroll.js'; -import Severity from '../../../../base/common/severity.js'; -import * as nls from '../../../../nls.js'; import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; - -function getCommentThreadWidgetStateColor(thread: languages.CommentThreadState | undefined, theme: IColorTheme): Color | undefined { - return getCommentThreadStateBorderColor(thread, theme) ?? theme.getColor(peekViewBorder); -} - -/** - * Check if a comment thread has any draft comments - */ -function commentThreadHasDraft(commentThread: languages.CommentThread): boolean { - const comments = commentThread.comments; - if (!comments) { - return false; - } - return comments.some(comment => comment.state === languages.CommentState.Draft); -} - -export enum CommentWidgetFocus { - None = 0, - Widget = 1, - Editor = 2 -} +import { commentThreadHasDraft, CommentWidgetFocus, confirmCommentThreadCollapse, createCommentThreadGlyph, getCommentThreadWidgetStateColor, ICommentThreadEditorWidget, updateCommentThreadTemplateRange } from './commentThreadEditorWidget.js'; export function parseMouseDownInfoFromEvent(e: IEditorMouseEvent) { const range = e.target.range; @@ -112,7 +88,7 @@ export function isMouseUpEventMatchMouseDown(mouseDownInfo: { lineNumber: number return lineNumber; } -export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadWidget { +export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadEditorWidget { private _commentThreadWidget!: CommentThreadWidget; private readonly _onDidClose = new Emitter(); private readonly _onDidCreateThread = new Emitter(); @@ -291,32 +267,13 @@ export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadWidget this._commentOptions, { actionRunner: async () => { - if (!this._commentThread.comments || !this._commentThread.comments.length) { - const newPosition = this.getPosition(); - - if (newPosition) { - const originalRange = this._commentThread.range; - if (!originalRange) { - return; - } - let range: Range; - - if (newPosition.lineNumber !== originalRange.endLineNumber) { - // The widget could have moved as a result of editor changes. - // We need to try to calculate the new, more correct, range for the comment. - const distance = newPosition.lineNumber - originalRange.endLineNumber; - range = new Range(originalRange.startLineNumber + distance, originalRange.startColumn, originalRange.endLineNumber + distance, originalRange.endColumn); - } else { - range = new Range(originalRange.startLineNumber, originalRange.startColumn, originalRange.endLineNumber, originalRange.endColumn); - } - await this.commentService.updateCommentThreadTemplate(this.uniqueOwner, this._commentThread.commentThreadHandle, range); - } - } + await updateCommentThreadTemplateRange(this.commentService, this.uniqueOwner, this._commentThread, this.getPosition()); }, collapse: () => { return this.collapse(true); } - } + }, + undefined ); this._disposables.add(this._commentThreadWidget); @@ -340,7 +297,7 @@ export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadWidget } public async collapse(confirm: boolean = false): Promise { - if (!confirm || (await this.confirmCollapse())) { + if (!confirm || (await confirmCommentThreadCollapse(this._commentThreadWidget.hasUnsubmittedComments, this.configurationService, this.dialogService))) { this.doCollapse(); return true; } else { @@ -348,24 +305,6 @@ export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadWidget } } - private async confirmCollapse(): Promise { - const confirmSetting = this.configurationService.getValue<'whenHasUnsubmittedComments' | 'never'>('comments.thread.confirmOnCollapse'); - - if (confirmSetting === 'whenHasUnsubmittedComments' && this._commentThreadWidget.hasUnsubmittedComments) { - const result = await this.dialogService.confirm({ - message: nls.localize('confirmCollapse', "Collapsing this comment thread will discard unsubmitted comments. Are you sure you want to discard these comments?"), - primaryButton: nls.localize('discard', "Discard"), - type: Severity.Warning, - checkbox: { label: nls.localize('neverAskAgain', "Never ask me again"), checked: false } - }); - if (result.checkboxChecked) { - await this.configurationService.updateValue('comments.thread.confirmOnCollapse', 'never'); - } - return result.confirmed; - } - return true; - } - public expand(setActive?: boolean) { this._commentThread.collapsibleState = languages.CommentThreadCollapsibleState.Expanded; if (setActive) { @@ -419,17 +358,7 @@ export class ReviewZoneWidget extends ZoneWidget implements ICommentThreadWidget async display(range: IRange | undefined, shouldReveal: boolean) { if (range) { - this._commentGlyph = new CommentGlyphWidget(this.editor, range?.endLineNumber ?? -1); - const hasDraft = commentThreadHasDraft(this._commentThread); - this._commentGlyph.setThreadState(this._commentThread.state, hasDraft); - this._globalToDispose.add(this._commentGlyph.onDidChangeLineNumber(async e => { - if (!this._commentThread.range) { - return; - } - const shift = e - (this._commentThread.range.endLineNumber); - const newRange = new Range(this._commentThread.range.startLineNumber + shift, this._commentThread.range.startColumn, this._commentThread.range.endLineNumber + shift, this._commentThread.range.endColumn); - this._commentThread.range = newRange; - })); + this._commentGlyph = createCommentThreadGlyph(this.editor, range, () => this._commentThread, this._globalToDispose); } await this._commentThreadWidget.display(this.editor.getOption(EditorOption.lineHeight), shouldReveal); diff --git a/src/vs/workbench/contrib/comments/browser/comments.contribution.ts b/src/vs/workbench/contrib/comments/browser/comments.contribution.ts index ff86200fe569..ec4a070d69fa 100644 --- a/src/vs/workbench/contrib/comments/browser/comments.contribution.ts +++ b/src/vs/workbench/contrib/comments/browser/comments.contribution.ts @@ -30,6 +30,7 @@ import { AccessibleViewProviderId } from '../../../../platform/accessibility/bro import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { CommentsAccessibleView, CommentThreadAccessibleView } from './commentsAccessibleView.js'; import { CommentsAccessibilityHelp } from './commentsAccessibility.js'; +import { COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING, CommentThreadStyle } from '../common/commentsConfiguration.js'; registerAction2(class Collapse extends ViewAction { constructor() { @@ -145,6 +146,17 @@ Registry.as(ConfigurationExtensions.Configuration).regis enumDescriptions: [nls.localize('confirmOnCollapse.whenHasUnsubmittedComments', "Show a confirmation dialog when collapsing a comment thread with unsubmitted comments."), nls.localize('confirmOnCollapse.never', "Never show a confirmation dialog when collapsing a comment thread.")], default: 'whenHasUnsubmittedComments', description: nls.localize('confirmOnCollapse', "Controls whether a confirmation dialog is shown when collapsing a comment thread.") + }, + [COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING]: { + type: 'string', + enum: ['inline', 'floating'] satisfies CommentThreadStyle[], + enumDescriptions: [ + nls.localize('comments.thread.experimental.style.inline', "Show comment threads between the lines of code they are about."), + nls.localize('comments.thread.experimental.style.floating', "Show comment threads in floating windows above the code they are about. The windows can be moved by dragging their title and resized by dragging their edges.") + ], + default: 'inline', + tags: ['experimental'], + description: nls.localize('comments.thread.experimental.style', "Controls how comment threads are shown in the editor.") } } }); diff --git a/src/vs/workbench/contrib/comments/browser/commentsController.ts b/src/vs/workbench/contrib/comments/browser/commentsController.ts index bfb504ac3c67..7982c753817c 100644 --- a/src/vs/workbench/contrib/comments/browser/commentsController.ts +++ b/src/vs/workbench/contrib/comments/browser/commentsController.ts @@ -8,12 +8,14 @@ import { coalesce } from '../../../../base/common/arrays.js'; import { findFirstIdxMonotonousOrArrLen } from '../../../../base/common/arraysFind.js'; import { CancelablePromise, createCancelablePromise, Delayer } from '../../../../base/common/async.js'; import { onUnexpectedError } from '../../../../base/common/errors.js'; -import { Disposable, DisposableStore, dispose, IDisposable } from '../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, dispose, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { LRUCache } from '../../../../base/common/map.js'; import './media/review.css'; import { ICodeEditor, IEditorMouseEvent, isCodeEditor, isDiffEditor } from '../../../../editor/browser/editorBrowser.js'; import { ICodeEditorService } from '../../../../editor/browser/services/codeEditorService.js'; import { IRange, Range } from '../../../../editor/common/core/range.js'; import { EditorType, IDiffEditor, IEditor, IEditorContribution, IModelChangedEvent } from '../../../../editor/common/editorCommon.js'; +import { EditorContextKeys } from '../../../../editor/common/editorContextKeys.js'; import { IModelDecorationOptions, IModelDeltaDecoration } from '../../../../editor/common/model.js'; import { ModelDecorationOptions, TextModel } from '../../../../editor/common/model/textModel.js'; import * as languages from '../../../../editor/common/languages.js'; @@ -23,14 +25,18 @@ import { IInstantiationService } from '../../../../platform/instantiation/common import { IQuickInputService, IQuickPickItem, QuickPickInput } from '../../../../platform/quickinput/common/quickInput.js'; import { CommentGlyphWidget } from './commentGlyphWidget.js'; import { ICommentInfo, ICommentService } from './commentService.js'; -import { CommentWidgetFocus, isMouseUpEventDragFromMouseDown, parseMouseDownInfoFromEvent, ReviewZoneWidget } from './commentThreadZoneWidget.js'; +import { isMouseUpEventDragFromMouseDown, parseMouseDownInfoFromEvent, ReviewZoneWidget } from './commentThreadZoneWidget.js'; +import { CommentWidgetFocus, ICommentThreadEditorWidget } from './commentThreadEditorWidget.js'; +import { ICommentThreadFloatingWidgetHost, ReviewFloatingWidget } from './commentThreadFloatingWidget.js'; +import { FloatingWidgetRoom } from './commentThreadFloatingWidgetRoom.js'; +import { ICommentThreadFloatingWidgetLayout } from './commentThreadFloatingWidgetLayout.js'; import { ACTIVE_GROUP, IEditorService, SIDE_GROUP } from '../../../services/editor/common/editorService.js'; import { EmbeddedCodeEditorWidget } from '../../../../editor/browser/widget/codeEditor/embeddedCodeEditorWidget.js'; import { EditorOption } from '../../../../editor/common/config/editorOptions.js'; import { IViewsService } from '../../../services/views/common/viewsService.js'; import { COMMENTS_VIEW_ID } from './commentsTreeViewer.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { COMMENTS_SECTION, ICommentsConfiguration } from '../common/commentsConfiguration.js'; +import { COMMENTS_SECTION, COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING, CommentThreadStyle, ICommentsConfiguration } from '../common/commentsConfiguration.js'; import { COMMENTEDITOR_DECORATION_KEY } from './commentReply.js'; import { Emitter } from '../../../../base/common/event.js'; import { IContextKey, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; @@ -126,7 +132,8 @@ class CommentingRangeDecorator { const decorationOptions: IModelDecorationOptions = { description: CommentingRangeDecorator.description, isWholeLine: true, - linesDecorationsClassName: 'comment-range-glyph comment-diff-added' + linesDecorationsClassName: 'comment-range-glyph comment-diff-added', + firstLineDecorationClassName: 'comment-range-glyph comment-diff-added-glyph' }; this.decorationOptions = ModelDecorationOptions.createDynamic(decorationOptions); @@ -134,7 +141,8 @@ class CommentingRangeDecorator { const hoverDecorationOptions: IModelDecorationOptions = { description: CommentingRangeDecorator.description, isWholeLine: true, - linesDecorationsClassName: `comment-range-glyph line-hover` + linesDecorationsClassName: 'comment-range-glyph comment-diff-added', + firstLineDecorationClassName: 'comment-range-glyph line-hover' }; this.hoverDecorationOptions = ModelDecorationOptions.createDynamic(hoverDecorationOptions); @@ -451,9 +459,15 @@ export function revealCommentThread(commentService: ICommentService, editorServi } export class CommentController extends Disposable implements IEditorContribution { + /** + * Where floating comment thread widgets were placed, so that they come back at the same place when + * they are recreated during the window session. + */ + private static readonly _floatingWidgetLayouts = new LRUCache(500); + private readonly localToDispose: DisposableStore = this._register(new DisposableStore()); private editor: ICodeEditor | undefined; - private _commentWidgets: ReviewZoneWidget[]; + private _commentWidgets: ICommentThreadEditorWidget[]; private _commentInfos: ICommentInfo[]; private _commentingRangeDecorator!: CommentingRangeDecorator; private _commentThreadRangeDecorator!: CommentThreadRangeDecorator; @@ -474,6 +488,18 @@ export class CommentController extends Disposable implements IEditorContribution private _activeEditorHasCommentingRange: IContextKey; private _commentWidgetVisible: IContextKey; private _hasRespondedToEditorChange: boolean = false; + private readonly _floatingWidgets = new Set(); + private readonly _floatingWidgetRoom: FloatingWidgetRoom | undefined; + private readonly _floatingWidgetHost: ICommentThreadFloatingWidgetHost = { + getLayout: widget => CommentController._floatingWidgetLayouts.get(this._getFloatingWidgetLayoutKey(widget)), + setLayout: (widget, layout) => CommentController._floatingWidgetLayouts.set(this._getFloatingWidgetLayoutKey(widget), layout), + addWidget: widget => { + this._floatingWidgets.add(widget); + return toDisposable(() => this._floatingWidgets.delete(widget)); + }, + getOtherWidgets: widget => Array.from(this._floatingWidgets).filter(other => other !== widget), + getRoom: () => this._floatingWidgetRoom + }; constructor( editor: ICodeEditor, @@ -507,6 +533,10 @@ export class CommentController extends Disposable implements IEditorContribution } this.editor = editor; + if (EditorContextKeys.inMultiDiffEditor.getValue(contextKeyService)) { + // The editors of the multi diff editor are as tall as their content, so they grow to fit the floating widgets. + this._floatingWidgetRoom = this._register(new FloatingWidgetRoom(editor, () => Array.from(this._floatingWidgets, widget => widget.getDocumentRect()))); + } this._commentingRangeDecorator = this._register(new CommentingRangeDecorator()); this._register(this._commentingRangeDecorator.onDidChangeDecorationsCount(count => { @@ -517,7 +547,8 @@ export class CommentController extends Disposable implements IEditorContribution } })); - this._register(this._commentThreadRangeDecorator = new CommentThreadRangeDecorator(this.commentService)); + this._register(this._commentThreadRangeDecorator = new CommentThreadRangeDecorator(this.commentService, + () => this.configurationService.getValue(COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING) !== 'floating')); this._register(this.commentService.onDidDeleteDataProvider(ownerId => { if (ownerId) { @@ -556,7 +587,7 @@ export class CommentController extends Disposable implements IEditorContribution this._register(this.editor.onWillChangeModel(e => this.onWillChangeModel(e))); this._register(this.editor.onDidChangeModel(_ => this.onModelChanged())); this._register(this.configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration('diffEditor.renderSideBySide')) { + if (e.affectsConfiguration('diffEditor.renderSideBySide') || e.affectsConfiguration(COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING)) { this.beginCompute(); } })); @@ -841,7 +872,7 @@ export class CommentController extends Disposable implements IEditorContribution return false; }); - const nextWidget: ReviewZoneWidget | undefined = sortedWidgets[idx]; + const nextWidget: ICommentThreadEditorWidget | undefined = sortedWidgets[idx]; if (nextWidget !== undefined) { this.editor.setSelection(nextWidget.commentThread.range ?? new Range(1, 1, 1, 1)); nextWidget.reveal(undefined, focusThread ? CommentWidgetFocus.Widget : CommentWidgetFocus.None); @@ -1004,6 +1035,7 @@ export class CommentController extends Disposable implements IEditorContribution } } const editorId = this.editor?.getId(); + this.sortThreadsForDisplay(added, thread => thread.range); for (const thread of added) { await this.handleCommentAdded(editorId, e.uniqueOwner, thread); } @@ -1097,14 +1129,33 @@ export class CommentController extends Disposable implements IEditorContribution if (thread.range && !pendingComment) { continueOnCommentReply = this.commentService.removeContinueOnComment({ uniqueOwner, uri: editor.uri, range: thread.range, isReply: true }); } - const zoneWidget = this.instantiationService.createInstance(ReviewZoneWidget, this.editor, uniqueOwner, thread, pendingComment ?? continueOnCommentReply?.comment, pendingEdits); - await zoneWidget.display(thread.range, shouldReveal); - this._commentWidgets.push(zoneWidget); - this.localToDispose.add(zoneWidget.onDidChangeExpandedState(() => this._updateCommentWidgetVisibleContext())); - this.localToDispose.add(zoneWidget.onDidClose(() => this._updateCommentWidgetVisibleContext())); + const threadStyle = this.configurationService.getValue(COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING); + const pending = pendingComment ?? continueOnCommentReply?.comment; + const commentWidget: ICommentThreadEditorWidget = threadStyle === 'floating' + ? this.instantiationService.createInstance(ReviewFloatingWidget, this.editor, uniqueOwner, thread, pending, pendingEdits, this._floatingWidgetHost) + : this.instantiationService.createInstance(ReviewZoneWidget, this.editor, uniqueOwner, thread, pending, pendingEdits); + await commentWidget.display(thread.range, shouldReveal); + this._commentWidgets.push(commentWidget); + this.localToDispose.add(commentWidget.onDidChangeExpandedState(() => this._updateCommentWidgetVisibleContext())); + this.localToDispose.add(commentWidget.onDidClose(() => this._updateCommentWidgetVisibleContext())); this.openCommentsView(thread); } + private _getFloatingWidgetLayoutKey(widget: ReviewFloatingWidget): string { + return JSON.stringify([widget.editor.getModel()?.uri.toString(), widget.uniqueOwner, widget.commentThread.threadId]); + } + + /** + * Sorts threads that are about to be displayed by where their code starts when they are shown in floating widgets. + * A floating widget moves the widgets for later code that are in its way, so showing them in the order of their code + * places each one once. + */ + private sortThreadsForDisplay(threads: T[], getRange: (thread: T) => IRange | undefined): void { + if (this.configurationService.getValue(COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING) === 'floating') { + threads.sort((a, b) => Range.compareRangesUsingStarts(getRange(a), getRange(b))); + } + } + private onEditorMouseDown(e: IEditorMouseEvent): void { this.mouseDownInfo = (e.target.element?.className.indexOf('comment-range-glyph') ?? -1) >= 0 ? parseMouseDownInfoFromEvent(e) : null; } @@ -1145,7 +1196,7 @@ export class CommentController extends Disposable implements IEditorContribution } } - public getCommentsAtLine(commentRange: Range | undefined): ReviewZoneWidget[] { + public getCommentsAtLine(commentRange: Range | undefined): ICommentThreadEditorWidget[] { return this._commentWidgets.filter(widget => widget.getGlyphPosition() === (commentRange ? commentRange.endLineNumber : 0)); } @@ -1380,6 +1431,7 @@ export class CommentController extends Disposable implements IEditorContribution this.removeCommentWidgetsAndStoreCache(); let hasCommentingRanges = false; + const threadsToDisplay: { uniqueOwner: string; thread: languages.CommentThread; pendingComment: languages.PendingComment | undefined; pendingEdits: { [key: number]: languages.PendingComment } | undefined }[] = []; for (const info of this._commentInfos) { if (!hasCommentingRanges && (info.commentingRanges.ranges.length > 0 || info.commentingRanges.fileComments)) { hasCommentingRanges = true; @@ -1389,18 +1441,14 @@ export class CommentController extends Disposable implements IEditorContribution const providerEditsCacheStore = this._pendingEditsCache[info.uniqueOwner]; info.threads = info.threads.filter(thread => !thread.isDisposed); for (const thread of info.threads) { - let pendingComment: languages.PendingComment | undefined = undefined; - if (providerCacheStore) { - pendingComment = providerCacheStore[thread.threadId]; - } - - let pendingEdits: { [key: number]: languages.PendingComment } | undefined = undefined; - if (providerEditsCacheStore) { - pendingEdits = providerEditsCacheStore[thread.threadId]; - } - - await this.displayCommentThread(info.uniqueOwner, thread, false, pendingComment, pendingEdits); + threadsToDisplay.push({ uniqueOwner: info.uniqueOwner, thread, pendingComment: providerCacheStore?.[thread.threadId], pendingEdits: providerEditsCacheStore?.[thread.threadId] }); } + } + this.sortThreadsForDisplay(threadsToDisplay, ({ thread }) => thread.range); + for (const { uniqueOwner, thread, pendingComment, pendingEdits } of threadsToDisplay) { + await this.displayCommentThread(uniqueOwner, thread, false, pendingComment, pendingEdits); + } + for (const info of this._commentInfos) { for (const thread of info.pendingCommentThreads ?? []) { this.resumePendingComment(this.editor.getModel()!.uri, thread); } diff --git a/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts b/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts index aeb70b11d9a8..1f86abcdf5ff 100644 --- a/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts +++ b/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts @@ -27,7 +27,7 @@ import { CommentCommandId } from '../common/commentCommandIds.js'; import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js'; import { CommentsInputContentProvider } from './commentsInputContentProvider.js'; import { AccessibleViewProviderId } from '../../../../platform/accessibility/browser/accessibleView.js'; -import { CommentWidgetFocus } from './commentThreadZoneWidget.js'; +import { CommentWidgetFocus } from './commentThreadEditorWidget.js'; import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; import { CommentThread, CommentThreadCollapsibleState, CommentThreadState } from '../../../../editor/common/languages.js'; diff --git a/src/vs/workbench/contrib/comments/browser/commentsTreeViewer.ts b/src/vs/workbench/contrib/comments/browser/commentsTreeViewer.ts index 5162553b7fc3..eeac9a43b651 100644 --- a/src/vs/workbench/contrib/comments/browser/commentsTreeViewer.ts +++ b/src/vs/workbench/contrib/comments/browser/commentsTreeViewer.ts @@ -246,7 +246,7 @@ export class CommentNodeRenderer implements IListRenderer private getRenderedComment(commentBody: IMarkdownString) { const renderedComment = renderMarkdown(commentBody, {}, document.createElement('span')); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const images = renderedComment.element.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { const image = images[i]; @@ -254,7 +254,7 @@ export class CommentNodeRenderer implements IListRenderer textDescription.textContent = image.alt ? nls.localize('imageWithLabel', "Image: {0}", image.alt) : nls.localize('image', "Image"); image.replaceWith(textDescription); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const headings = [...renderedComment.element.getElementsByTagName('h1'), ...renderedComment.element.getElementsByTagName('h2'), ...renderedComment.element.getElementsByTagName('h3'), ...renderedComment.element.getElementsByTagName('h4'), ...renderedComment.element.getElementsByTagName('h5'), ...renderedComment.element.getElementsByTagName('h6')]; for (const heading of headings) { const textNode = document.createTextNode(heading.textContent || ''); diff --git a/src/vs/workbench/contrib/comments/browser/media/review.css b/src/vs/workbench/contrib/comments/browser/media/review.css index 1d42ac39101f..91a77492190e 100644 --- a/src/vs/workbench/contrib/comments/browser/media/review.css +++ b/src/vs/workbench/contrib/comments/browser/media/review.css @@ -99,7 +99,7 @@ width: 30px; background-color: transparent; border: 1px solid grey; - border-radius: 3px; + border-radius: var(--workbench-custom-buttons-corner-radius, 3px); } .review-widget .body .review-comment .review-comment-contents { @@ -505,17 +505,19 @@ div.preview.inline .monaco-editor .comment-range-glyph { display: none !important; } -.monaco-editor .comment-diff-added { +.monaco-editor .comment-diff-added, +.monaco-editor .comment-thread-bar { border-left-width: 3px; border-left-style: solid; } .monaco-editor .comment-diff-added, +.monaco-editor .comment-thread-bar, .monaco-editor .comment-range-glyph.multiline-add { border-left-color: var(--vscode-editorGutter-commentRangeForeground); } -.monaco-editor .comment-diff-added:before, +.monaco-editor .comment-diff-added-glyph:before, .monaco-editor .comment-range-glyph.line-hover:before { background: var(--vscode-editorGutter-commentRangeForeground); } @@ -541,7 +543,7 @@ div.preview.inline .monaco-editor .comment-range-glyph { margin-left: 13px; } -.monaco-editor .margin-view-overlays > div:hover > .comment-range-glyph.comment-diff-added:before, +.monaco-editor .margin-view-overlays > div:hover > .comment-range-glyph.comment-diff-added-glyph:before, .monaco-editor .margin-view-overlays .comment-range-glyph.line-hover:before, .monaco-editor .comment-range-glyph.comment-thread:before, .monaco-editor .comment-range-glyph.comment-thread-unresolved:before, @@ -574,11 +576,10 @@ div.preview.inline .monaco-editor .comment-range-glyph { margin-top: 2px; } -.monaco-editor .margin-view-overlays > div:hover > .comment-range-glyph.comment-diff-added:before, +.monaco-editor .margin-view-overlays > div:hover > .comment-range-glyph.comment-diff-added-glyph:before, .monaco-editor .margin-view-overlays .comment-range-glyph.line-hover:before { content: var(--vscode-icon-plus-content); font-family: var(--vscode-icon-plus-font-family); - font-family: "codicon"; border-radius: 3px; width: 18px !important; margin-left: -5px; @@ -627,3 +628,102 @@ div.preview.inline .monaco-editor .comment-range-glyph { .monaco-editor.inline-comment .margin-view-overlays .dirty-diff-glyph { margin-left: 25px; } + +/* Floating comment thread widget (`comments.thread.experimental.style: floating`) */ + +.monaco-editor .comment-thread-floating-widget { + z-index: 10; + box-sizing: border-box; + border: var(--vscode-strokeThickness) solid var(--comment-thread-state-color); + border-radius: var(--vscode-cornerRadius-large); + background-color: var(--vscode-peekViewResult-background); + box-shadow: var(--vscode-shadow-lg); +} + +.monaco-editor .comment-thread-floating-widget.front { + z-index: 11; +} + +.monaco-editor .comment-thread-floating-widget > .review-widget { + position: relative; + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; + border-radius: calc(var(--vscode-cornerRadius-large) - var(--vscode-strokeThickness)); +} + +.monaco-editor .comment-thread-floating-widget > .review-widget > .head { + flex-shrink: 0; + cursor: grab; +} + +.monaco-editor .comment-thread-floating-widget > .review-widget > .head .review-title { + cursor: inherit; +} + +.monaco-editor .comment-thread-floating-widget.dragging, +.monaco-editor .comment-thread-floating-widget.dragging > .review-widget > .head { + cursor: grabbing; +} + +/* Scrollable comments (`ICommentThreadWidgetOptions.scrollableComments`) fill the height they are given. */ +.review-widget .body .comments-scroll-viewport { + height: 100%; +} + +/* The body shrinks and scrolls when the widget is too short for the reply and additional actions, such as in a short editor. */ +.monaco-editor .comment-thread-floating-widget > .review-widget > .comment-thread-body-scrollable { + flex: 0 1 auto; + min-height: 0; + border-top: 1px solid var(--comment-thread-state-color); +} + +.monaco-editor .comment-thread-floating-widget > .review-widget > .comment-thread-body-scrollable > .body { + position: relative; + height: 100%; +} + +.monaco-editor .comment-thread-floating-connector { + z-index: 9; + overflow: hidden; + pointer-events: none; +} + +.monaco-editor .comment-thread-floating-connector > svg { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + overflow: visible; +} + +/* The outline and connector are subtle at rest and become prominent while focus is in the widget. */ +.monaco-editor .comment-thread-floating-connector .code-outline, +.monaco-editor .comment-thread-floating-connector .connector-line { + fill: none; + stroke: var(--comment-thread-state-color); + stroke-width: var(--vscode-strokeThickness); + stroke-opacity: 0.5; +} + +.monaco-editor .comment-thread-floating-connector .connector-anchor { + fill: var(--comment-thread-state-color); + fill-opacity: 0.5; +} + +.monaco-editor .comment-thread-floating-connector.active .code-outline, +.monaco-editor .comment-thread-floating-connector.active .connector-line, +.monaco-editor.hc-black .comment-thread-floating-connector .code-outline, +.monaco-editor.hc-black .comment-thread-floating-connector .connector-line, +.monaco-editor.hc-light .comment-thread-floating-connector .code-outline, +.monaco-editor.hc-light .comment-thread-floating-connector .connector-line { + stroke-opacity: 1; +} + +.monaco-editor .comment-thread-floating-connector.active .connector-anchor, +.monaco-editor.hc-black .comment-thread-floating-connector .connector-anchor, +.monaco-editor.hc-light .comment-thread-floating-connector .connector-anchor { + fill-opacity: 1; +} diff --git a/src/vs/workbench/contrib/comments/common/commentsConfiguration.ts b/src/vs/workbench/contrib/comments/common/commentsConfiguration.ts index 44004fe47d79..ea71f0b2536e 100644 --- a/src/vs/workbench/contrib/comments/common/commentsConfiguration.ts +++ b/src/vs/workbench/contrib/comments/common/commentsConfiguration.ts @@ -12,3 +12,10 @@ export interface ICommentsConfiguration { } export const COMMENTS_SECTION = 'comments'; + +export const COMMENTS_THREAD_EXPERIMENTAL_STYLE_SETTING = 'comments.thread.experimental.style'; + +/** + * How comment threads are shown in the editor: between the lines of code, or floating above them. + */ +export type CommentThreadStyle = 'inline' | 'floating'; diff --git a/src/vs/workbench/contrib/comments/test/browser/commentGlyphStyles.test.ts b/src/vs/workbench/contrib/comments/test/browser/commentGlyphStyles.test.ts new file mode 100644 index 000000000000..a2bc20326f24 --- /dev/null +++ b/src/vs/workbench/contrib/comments/test/browser/commentGlyphStyles.test.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import * as dom 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 '../../browser/media/review.css'; + +suite('Comment Glyph Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('gutter glyphs use the product icon theme font and character', () => { + const editor = dom.$('.monaco-editor'); + for (const icon of ['plus', 'comment-add', 'comment-unresolved', 'comment-draft']) { + editor.style.setProperty(`--vscode-icon-${icon}-font-family`, '"product-icon-theme-font"'); + editor.style.setProperty(`--vscode-icon-${icon}-content`, '"\\f13c"'); + } + const line = dom.append(dom.append(editor, dom.$('.margin-view-overlays')), dom.$('div')); + mainWindow.document.body.appendChild(editor); + store.add(toDisposable(() => editor.remove())); + + const actual = ['line-hover', 'comment-thread', 'comment-thread-unresolved', 'comment-thread-draft'].map(className => { + const glyph = dom.append(line, dom.$(`.comment-range-glyph.${className}`)); + const style = mainWindow.getComputedStyle(glyph, '::before'); + return { className, content: style.content, fontFamily: style.fontFamily }; + }); + + assert.deepStrictEqual(actual, [ + { className: 'line-hover', content: '"\uf13c"', fontFamily: 'product-icon-theme-font' }, + { className: 'comment-thread', content: '"\uf13c"', fontFamily: 'product-icon-theme-font' }, + { className: 'comment-thread-unresolved', content: '"\uf13c"', fontFamily: 'product-icon-theme-font' }, + { className: 'comment-thread-draft', content: '"\uf13c"', fontFamily: 'product-icon-theme-font' }, + ]); + }); +}); diff --git a/src/vs/workbench/contrib/comments/test/browser/commentGlyphWidget.test.ts b/src/vs/workbench/contrib/comments/test/browser/commentGlyphWidget.test.ts new file mode 100644 index 000000000000..038de1adad68 --- /dev/null +++ b/src/vs/workbench/contrib/comments/test/browser/commentGlyphWidget.test.ts @@ -0,0 +1,59 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { RenderingContext, IViewLines } from '../../../../../editor/browser/view/renderingContext.js'; +import { LinesDecorationsOverlay } from '../../../../../editor/browser/viewParts/linesDecorations/linesDecorations.js'; +import { CommentThreadState } from '../../../../../editor/common/languages.js'; +import { ViewportData } from '../../../../../editor/common/viewLayout/viewLinesViewportData.js'; +import { ViewContext } from '../../../../../editor/common/viewModel/viewContext.js'; +import { TestConfiguration } from '../../../../../editor/test/browser/config/testConfiguration.js'; +import { withTestCodeEditor } from '../../../../../editor/test/browser/testCodeEditor.js'; +import { TestColorTheme } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { CommentGlyphWidget } from '../../browser/commentGlyphWidget.js'; + +suite('CommentGlyphWidget', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('separates the comment bar from the glyph on wrapped lines', () => { + withTestCodeEditor('012345678901234567890123456789', { + wordWrap: 'wordWrapColumn', + wordWrapColumn: 10 + }, (editor, viewModel) => { + const widget = store.add(new CommentGlyphWidget(editor, 1)); + widget.setThreadState(CommentThreadState.Unresolved); + + const configuration = store.add(new TestConfiguration({ + wordWrap: 'wordWrapColumn', + wordWrapColumn: 10 + })); + const overlay = store.add(new LinesDecorationsOverlay(new ViewContext(configuration, new TestColorTheme(), viewModel))); + const partialViewportData = viewModel.viewLayout.getLinesViewportData(); + viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber); + const viewportData = new ViewportData([], partialViewportData, viewModel.viewLayout.getWhitespaceViewportData(), viewModel); + const viewLines: IViewLines = { + linesVisibleRangesForRange: () => null, + visibleRangeForPosition: () => null + }; + overlay.prepareRender(new RenderingContext(viewModel.viewLayout, viewportData, viewLines)); + + const renderedLines = []; + for (let lineNumber = viewportData.startLineNumber; lineNumber <= viewportData.endLineNumber; lineNumber++) { + renderedLines.push(overlay.render(viewportData.startLineNumber, lineNumber)); + } + + assert.deepStrictEqual({ + isWrapped: renderedLines.length > 1, + linesMissingBar: renderedLines.flatMap((line, index) => line.includes('comment-thread-bar') ? [] : [index + 1]), + linesWithGlyph: renderedLines.flatMap((line, index) => line.includes('comment-thread-unresolved') ? [index + 1] : []) + }, { + isWrapped: true, + linesMissingBar: [], + linesWithGlyph: [1] + }); + }); + }); +}); diff --git a/src/vs/workbench/contrib/comments/test/browser/commentReply.test.ts b/src/vs/workbench/contrib/comments/test/browser/commentReply.test.ts index c93670a15223..09d65f185ba0 100644 --- a/src/vs/workbench/contrib/comments/test/browser/commentReply.test.ts +++ b/src/vs/workbench/contrib/comments/test/browser/commentReply.test.ts @@ -11,7 +11,7 @@ import { mock } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; import { IRange } from '../../../../../editor/common/core/range.js'; -import { CommentInput, CommentThread } from '../../../../../editor/common/languages.js'; +import { Comment, CommentInput, CommentThread } from '../../../../../editor/common/languages.js'; import { IResolvedTextEditorModel, ITextModelService } from '../../../../../editor/common/services/resolverService.js'; import { createCodeEditorServices, instantiateTestCodeEditor } from '../../../../../editor/test/browser/testCodeEditor.js'; import { createTextModel } from '../../../../../editor/test/common/testTextModel.js'; @@ -26,6 +26,7 @@ import { SimpleCommentEditor } from '../../browser/simpleCommentEditor.js'; suite('CommentReply', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + const existingComment: Comment = { body: 'Existing comment', uniqueIdInThread: 1, userName: 'Reviewer' }; teardown(() => sinon.restore()); @@ -54,7 +55,7 @@ suite('CommentReply', () => { instantiationService.stub(IMenuService, new TestMenuService()); instantiationService.stub(IContextMenuService, {}); const thread = new class extends mock>() { - override readonly comments = hasExistingComments ? [{ body: 'Existing comment', uniqueIdInThread: 1, userName: 'Reviewer' }] : []; + override comments: ReadonlyArray | undefined = hasExistingComments ? [existingComment] : []; override readonly canReply = true; override readonly onDidChangeInput = onDidChangeInput.event; }; @@ -127,4 +128,31 @@ suite('CommentReply', () => { value: model.getValue() }, { expanded: [true, true, true], hasReplyButton: true, value: '' }); }); + + test('collapses an untouched reply area when a new thread receives its first comments', async () => { + const { reply, container, model, thread } = await createReply(false); + const formContainer = container.querySelector('.comment-form-container')!; + const expanded = [formContainer.classList.contains('expand')]; + thread.comments = [existingComment]; + reply.updateCommentThread(thread); + expanded.push(formContainer.classList.contains('expand')); + + assert.deepStrictEqual({ + expanded, + hasReplyButton: !!container.querySelector('.review-thread-reply-button'), + value: model.getValue() + }, { expanded: [true, false], hasReplyButton: true, value: '' }); + }); + + test('keeps a draft expanded when a new thread receives its first comments', async () => { + const { reply, container, model, thread } = await createReply(false); + model.setValue('Draft comment'); + thread.comments = [existingComment]; + reply.updateCommentThread(thread); + + assert.deepStrictEqual({ + expanded: container.querySelector('.comment-form-container')!.classList.contains('expand'), + value: model.getValue() + }, { expanded: true, value: 'Draft comment' }); + }); }); diff --git a/src/vs/workbench/contrib/comments/test/browser/commentThreadFloatingWidget.test.ts b/src/vs/workbench/contrib/comments/test/browser/commentThreadFloatingWidget.test.ts new file mode 100644 index 000000000000..d68b2959cf70 --- /dev/null +++ b/src/vs/workbench/contrib/comments/test/browser/commentThreadFloatingWidget.test.ts @@ -0,0 +1,467 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { computeFloatingWidgetPlacement, FloatingWidgetSizeModel, getCenteredTop, getConnectorPoints, getPlacementBesideLines, getRevealScrollTop, getRowsOutlinePath, getWidthBesideCode, IFloatingWidgetPlacementRequest, IRect, isInTheWayOf } from '../../browser/commentThreadFloatingWidgetLayout.js'; + +suite('Comment thread floating widget', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + suite('getConnectorPoints', () => { + const code: IRect[] = [{ top: 100, left: 50, width: 200, height: 20 }]; + + test('connects the closest point of the code to the anchor', () => { + assert.deepStrictEqual({ + aboveRight: getConnectorPoints(code, { x: 400, y: 40 }), + right: getConnectorPoints(code, { x: 400, y: 110 }), + belowRight: getConnectorPoints(code, { x: 400, y: 300 }), + below: getConnectorPoints(code, { x: 120, y: 160 }), + aboveLeft: getConnectorPoints(code, { x: 10, y: 10 }), + }, { + aboveRight: { from: { x: 250, y: 100 }, to: { x: 400, y: 40 } }, + right: { from: { x: 250, y: 110 }, to: { x: 400, y: 110 } }, + belowRight: { from: { x: 250, y: 120 }, to: { x: 400, y: 300 } }, + below: { from: { x: 120, y: 120 }, to: { x: 120, y: 160 } }, + aboveLeft: { from: { x: 50, y: 100 }, to: { x: 10, y: 10 } }, + }); + }); + + test('connects the closest line of code that spans several lines', () => { + const lines: IRect[] = [...code, { top: 120, left: 50, width: 80, height: 20 }]; + assert.deepStrictEqual({ + besideShorterLine: getConnectorPoints(lines, { x: 200, y: 135 }), + belowShorterLine: getConnectorPoints(lines, { x: 100, y: 160 }), + insideShorterLine: getConnectorPoints(lines, { x: 100, y: 130 }), + }, { + besideShorterLine: { from: { x: 200, y: 120 }, to: { x: 200, y: 135 } }, + belowShorterLine: { from: { x: 100, y: 140 }, to: { x: 100, y: 160 } }, + insideShorterLine: undefined, + }); + }); + + test('does not connect an anchor within or on the code', () => { + assert.deepStrictEqual({ + inside: getConnectorPoints(code, { x: 100, y: 110 }), + onEdge: getConnectorPoints(code, { x: 250, y: 105 }), + noCode: getConnectorPoints([], { x: 100, y: 110 }), + }, { + inside: undefined, + onEdge: undefined, + noCode: undefined, + }); + }); + }); + + suite('getRowsOutlinePath', () => { + test('outlines the end of each row', () => { + const rows: IRect[] = [ + { top: 0, left: 0, width: 100, height: 20 }, + { top: 20, left: 0, width: 60, height: 20 }, + { top: 40, left: 0, width: 60, height: 20 }, + ]; + assert.deepStrictEqual({ + noRows: getRowsOutlinePath([], 4), + sharpCorners: getRowsOutlinePath(rows, 0), + roundedCorners: getRowsOutlinePath(rows.slice(0, 1), 4), + }, { + noRows: '', + sharpCorners: 'M 100 0 L 100 20 L 60 20 L 60 60 L 0 60 L 0 0 Z', + roundedCorners: 'M 96 0 Q 100 0 100 4 L 100 16 Q 100 20 96 20 L 4 20 Q 0 20 0 16 L 0 4 Q 0 0 4 0 Z', + }); + }); + }); + + suite('getCenteredTop', () => { + test('centers on the code without going above the document', () => { + assert.deepStrictEqual({ + shorterThanCode: getCenteredTop(500, 700, 100), + tallerThanCode: getCenteredTop(500, 520, 200), + nearDocumentStart: getCenteredTop(20, 40, 200), + }, { + shorterThanCode: 550, + tallerThanCode: 410, + nearDocumentStart: 0, + }); + }); + }); + + suite('computeFloatingWidgetPlacement', () => { + const request: IFloatingWidgetPlacementRequest = { + minLeft: 60, + maxRight: 1000, + width: 400, + height: 200, + code: { top: 500, left: 60, width: 300, height: 40 }, + obstacles: [], + scrollableHeight: 5000 + }; + + test('centers the widget vertically on the code at the right edge of the editor', () => { + assert.deepStrictEqual(computeFloatingWidgetPlacement(request), { top: 420, left: 592, centered: true }); + }); + + test('places the widget below the code, at the right edge of the editor, when there is no room next to it', () => { + assert.deepStrictEqual({ + longCode: computeFloatingWidgetPlacement({ ...request, code: { top: 500, left: 60, width: 560, height: 40 } }), + indentedCode: computeFloatingWidgetPlacement({ ...request, code: { top: 500, left: 700, width: 280, height: 20 } }), + narrowEditor: computeFloatingWidgetPlacement({ ...request, maxRight: 500 }), + }, { + longCode: { top: 548, left: 592, centered: false }, + indentedCode: { top: 528, left: 592, centered: false }, + narrowEditor: { top: 548, left: 92, centered: false }, + }); + }); + + test('places the widget at the top of the document for file comments', () => { + assert.deepStrictEqual(computeFloatingWidgetPlacement({ ...request, code: undefined }), { top: 0, left: 592, centered: true }); + }); + + test('moves the widget below the widgets it would cover', () => { + assert.deepStrictEqual(computeFloatingWidgetPlacement({ + ...request, + obstacles: [ + { top: 300, left: 600, width: 300, height: 150, codeTop: 360 }, + { top: 460, left: 500, width: 300, height: 100, codeTop: 480 }, + { top: 0, left: 600, width: 300, height: 100, codeTop: 20 }, + ] + }), { top: 568, left: 592, centered: false }); + }); + + test('places a new comment right after the end of the code when there is room', () => { + assert.deepStrictEqual({ + room: computeFloatingWidgetPlacement({ ...request, besideCode: true }), + noRoom: computeFloatingWidgetPlacement({ ...request, besideCode: true, code: { top: 500, left: 60, width: 560, height: 40 } }), + besideOtherWidget: computeFloatingWidgetPlacement({ ...request, besideCode: true, obstacles: [{ top: 480, left: 400, width: 300, height: 100, codeTop: 440 }] }), + }, { + room: { top: 500, left: 384, centered: false }, + noRoom: { top: 548, left: 592, centered: false }, + besideOtherWidget: { top: 588, left: 384, centered: false }, + }); + }); + + test('places an existing comment right after the end of the lines next to the code when there is room', () => { + assert.deepStrictEqual({ + afterLines: computeFloatingWidgetPlacement({ ...request, linesRight: 400 }), + linesShorterThanCode: computeFloatingWidgetPlacement({ ...request, linesRight: 200 }), + noRoomAfterLines: computeFloatingWidgetPlacement({ ...request, linesRight: 700 }), + }, { + afterLines: { top: 420, left: 424, centered: true }, + linesShorterThanCode: { top: 420, left: 384, centered: true }, + noRoomAfterLines: { top: 420, left: 592, centered: true }, + }); + }); + + test('moves the widget to the closest free position above or below the widgets it would cover', () => { + assert.deepStrictEqual({ + closerAbove: computeFloatingWidgetPlacement({ ...request, obstacles: [{ top: 380, left: 600, width: 300, height: 300, codeTop: 600 }] }), + // The document ends at 1000 and can't be scrolled further, so there is no room below the other widget. + belowOutOfReach: computeFloatingWidgetPlacement({ + ...request, + height: 360, + code: { top: 940, left: 60, width: 300, height: 20 }, + obstacles: [{ top: 632, left: 592, width: 400, height: 360, codeTop: 960 }], + scrollableHeight: 1000 + }), + noFreePosition: computeFloatingWidgetPlacement({ ...request, obstacles: [{ top: 0, left: 600, width: 300, height: 400, codeTop: 520 }], scrollableHeight: 400 }), + }, { + closerAbove: { top: 172, left: 592, centered: false }, + belowOutOfReach: { top: 264, left: 592, centered: false }, + noFreePosition: { top: 192, left: 592, centered: false }, + }); + }); + + test('keeps the widgets in the order of their code', () => { + assert.deepStrictEqual({ + aboveWidgetForLaterCode: computeFloatingWidgetPlacement({ ...request, obstacles: [{ top: 340, left: 600, width: 300, height: 200, codeTop: 600 }] }), + belowWidgetForEarlierCode: computeFloatingWidgetPlacement({ ...request, obstacles: [{ top: 480, left: 600, width: 300, height: 300, codeTop: 400 }] }), + noRoomOnItsSide: computeFloatingWidgetPlacement({ ...request, obstacles: [{ top: 100, left: 600, width: 300, height: 400, codeTop: 600 }] }), + // A widget that was moved above the code of this one doesn't keep this one from staying above the others. + besideMovedWidget: computeFloatingWidgetPlacement({ + ...request, + obstacles: [{ top: 380, left: 600, width: 300, height: 100, codeTop: 560 }, { top: 0, left: 600, width: 300, height: 100, codeTop: 600 }] + }), + }, { + aboveWidgetForLaterCode: { top: 132, left: 592, centered: false }, + belowWidgetForEarlierCode: { top: 788, left: 592, centered: false }, + noRoomOnItsSide: { top: 508, left: 592, centered: false }, + besideMovedWidget: { top: 172, left: 592, centered: false }, + }); + }); + }); + + suite('isInTheWayOf', () => { + test('is in the way of a widget that it covers, or that it is out of the order of their code with', () => { + const earlier = { top: 400, left: 600, width: 300, height: 200, codeTop: 300 }; + assert.deepStrictEqual({ + covering: isInTheWayOf({ top: 500, left: 650, width: 300, height: 200, codeTop: 600 }, earlier), + aboveForLaterCode: isInTheWayOf({ top: 100, left: 650, width: 300, height: 200, codeTop: 600 }, earlier), + belowForLaterCode: isInTheWayOf({ top: 700, left: 650, width: 300, height: 200, codeTop: 600 }, earlier), + besideForLaterCode: isInTheWayOf({ top: 100, left: 100, width: 300, height: 200, codeTop: 600 }, earlier), + aboveForSameCode: isInTheWayOf({ top: 100, left: 650, width: 300, height: 200, codeTop: 300 }, earlier), + }, { + covering: true, + aboveForLaterCode: true, + belowForLaterCode: false, + besideForLaterCode: false, + aboveForSameCode: false, + }); + }); + }); + + suite('getWidthBesideCode', () => { + test('is as wide as preferred, or as wide as there is room for after the end of the code', () => { + const code = { top: 500, left: 60, width: 300, height: 20 }; + assert.deepStrictEqual({ + room: getWidthBesideCode(code, 200, 400, 240, 1000, []), + lessRoom: getWidthBesideCode({ ...code, width: 500 }, 200, 560, 240, 1000, []), + narrowEditor: getWidthBesideCode({ ...code, width: 100 }, 200, 280, 240, 500, []), + tooLittleRoom: getWidthBesideCode({ ...code, width: 700 }, 200, 400, 240, 1000, []), + narrowerThanContent: getWidthBesideCode({ ...code, width: 500 }, 200, 560, 450, 1000, []), + }, { + room: 400, + lessRoom: 408, + narrowEditor: 280, + tooLittleRoom: undefined, + narrowerThanContent: undefined, + }); + }); + + test('leaves room for the widgets beside the code', () => { + const code = { top: 500, left: 60, width: 300, height: 20 }; + assert.deepStrictEqual({ + besideWidget: getWidthBesideCode(code, 200, 400, 240, 1000, [{ top: 400, left: 750, width: 240, height: 150 }]), + tooCloseToWidget: getWidthBesideCode(code, 200, 400, 240, 1000, [{ top: 650, left: 650, width: 340, height: 100 }]), + aboveAndBelowWidgets: getWidthBesideCode(code, 200, 400, 240, 1000, [{ top: 300, left: 400, width: 300, height: 200 }, { top: 700, left: 400, width: 300, height: 100 }]), + widgetOverCode: getWidthBesideCode(code, 200, 400, 240, 1000, [{ top: 500, left: 300, width: 200, height: 100 }]), + }, { + besideWidget: 358, + tooCloseToWidget: undefined, + aboveAndBelowWidgets: 400, + widgetOverCode: undefined, + }); + }); + }); + + suite('getPlacementBesideLines', () => { + test('goes after the lines that leave it room, and is as wide as its content fills, up to a readable width', () => { + assert.deepStrictEqual({ + shortLines: placeBesideLines([100, 300, 200]), + contentWiderThanRoom: placeBesideLines([100, 400, 200], { naturalWidth: 900 }), + readableWidth: placeBesideLines([100, 300], { maxRight: 1400, naturalWidth: 900 }), + codeEndsAfterLines: placeBesideLines([100, 300], { codeRight: 400 }), + longLineWithRoomAfterIt: placeBesideLines([100, 600, 200]), + lineNotNextToWidget: placeBesideLines([100, 300, 200, 700], { bottom: 60 }), + }, { + shortLines: { linesRight: 300, width: 450 }, + contentWiderThanRoom: { linesRight: 400, width: 568 }, + readableWidth: { linesRight: 300, width: 640 }, + codeEndsAfterLines: { linesRight: 400, width: 450 }, + longLineWithRoomAfterIt: { linesRight: 600, width: 368 }, + lineNotNextToWidget: { linesRight: 300, width: 450 }, + }); + }); + + test('hides a couple of lines that leave it no room after them, at its default width', () => { + assert.deepStrictEqual({ + lineEndingInTheMiddle: placeBesideLines([100, 700, 200]), + twoLongLines: placeBesideLines([100, 700, 300, 1400]), + threeLongLines: placeBesideLines([700, 1400, 300, 800]), + codeLeavesNoRoom: placeBesideLines([100, 300], { codeRight: 700 }), + }, { + lineEndingInTheMiddle: { linesRight: 200, width: 300 }, + twoLongLines: { linesRight: 300, width: 300 }, + threeLongLines: undefined, + codeLeavesNoRoom: undefined, + }); + }); + + function placeBesideLines(rights: number[], { bottom = rights.length * 20, codeRight = 60, maxRight = 1000, naturalWidth = 450 } = {}) { + const lines = rights.map((right, i) => ({ top: i * 20, left: 60, width: right - 60, height: 20 })); + return getPlacementBesideLines(lines, 0, bottom, codeRight, maxRight, 300, naturalWidth); + } + }); + + suite('getRevealScrollTop', () => { + const viewportHeight = 600; + + test('scrolls only when the code or the widget is out of view', () => { + const code = { top: 1000, bottom: 1020 }; + const widget = { top: 830, bottom: 1190 }; + assert.deepStrictEqual({ + inView: getRevealScrollTop(code, widget, 700, viewportHeight), + belowView: getRevealScrollTop(code, widget, 0, viewportHeight), + }, { + inView: undefined, + belowView: 710, + }); + }); + + test('shows the whole widget when it does not fit in the viewport together with the code', () => { + // The widget is centered on code that is taller than the viewport. + const tallCode = { top: 1000, bottom: 3000 }; + const centeredWidget = { top: 1820, bottom: 2180 }; + assert.deepStrictEqual({ + centeredOnTallCode: getRevealScrollTop(tallCode, centeredWidget, 0, viewportHeight), + widgetAlreadyInView: getRevealScrollTop(tallCode, centeredWidget, 1700, viewportHeight), + farBelowCode: getRevealScrollTop({ top: 1000, bottom: 1020 }, { top: 2000, bottom: 2360 }, 0, viewportHeight), + tallerThanViewport: getRevealScrollTop(tallCode, { top: 1500, bottom: 2200 }, 0, viewportHeight), + }, { + centeredOnTallCode: 1588, + widgetAlreadyInView: undefined, + farBelowCode: 1768, + tallerThanViewport: 1492, + }); + }); + }); + + suite('FloatingWidgetSizeModel', () => { + const code = { top: 1000, bottom: 1020 }; + const collapsedReply = { fixed: 100, comments: 2000 }; + const expandedReply = { fixed: 180, comments: 2000 }; + const scrollableHeight = 5000; + + function createModel(): FloatingWidgetSizeModel { + const model = new FloatingWidgetSizeModel(); + model.captureEditorSize({ width: 1000, height: 600 }); + return model; + } + + test('can be as wide as the editor, and is shown as wide as its content fills, unless something is being written', () => { + const model = createModel(); + assert.deepStrictEqual({ + narrowContent: model.getWidthRange({ minimum: 100, natural: 180 }), + wideContent: model.getWidthRange({ minimum: 300, natural: 700 }), + defaultForNarrowContent: model.getDefaultWidth({ minimum: 100, natural: 180 }, 400, false), + defaultForWideContent: model.getDefaultWidth({ minimum: 300, natural: 700 }, 400, false), + defaultWhileEditing: model.getDefaultWidth({ minimum: 100, natural: 180 }, 400, true), + defaultWiderThanEditor: model.getDefaultWidth({ minimum: 300, natural: 1400 }, 1200, false), + }, { + narrowContent: { min: 240, max: 1000 }, + wideContent: { min: 300, max: 1000 }, + defaultForNarrowContent: 240, + defaultForWideContent: 400, + defaultWhileEditing: 400, + defaultWiderThanEditor: 1000, + }); + }); + + test('shows the title, reply and some comments, and is no taller than its content or the editor', () => { + const model = createModel(); + assert.deepStrictEqual({ + fewComments: model.getHeightRange({ fixed: 100, comments: 30 }), + manyComments: model.getHeightRange({ fixed: 100, comments: 300 }), + tallerThanEditor: model.getHeightRange(collapsedReply), + }, { + fewComments: { min: 130, max: 130 }, + manyComments: { min: 140, max: 400 }, + tallerThanEditor: { min: 140, max: 584 }, + }); + }); + + test('sizes itself to its content, up to part of the editor, unless the user chose a height', () => { + const model = createModel(); + model.updateGrowth(collapsedReply); + assert.deepStrictEqual({ + auto: model.getHeight(collapsedReply, undefined), + autoFewComments: model.getHeight({ fixed: 100, comments: 100 }, undefined), + chosen: model.getHeight(collapsedReply, 500), + chosenTallerThanEditor: model.getHeight(collapsedReply, 900), + }, { + auto: 360, + autoFewComments: 200, + chosen: 500, + chosenTallerThanEditor: 584, + }); + }); + + test('keeps some of the comments when the widget is too short for the rest of its content', () => { + const model = createModel(); + assert.deepStrictEqual({ + fits: model.getCommentsHeight(collapsedReply, 360), + tooShortForReply: model.getCommentsHeight({ fixed: 180, comments: 2000 }, 134), + tooShortWithFewComments: model.getCommentsHeight({ fixed: 180, comments: 20 }, 134), + }, { + fits: 260, + tooShortForReply: 40, + tooShortWithFewComments: 20, + }); + }); + + test('grows down by as much as its reply grows', () => { + const model = createModel(); + model.updateGrowth(collapsedReply); + const collapsedHeight = model.getHeight(collapsedReply, undefined); + const collapsed = { height: collapsedHeight, top: model.getTop(undefined, code, collapsedHeight, scrollableHeight) }; + const growthChanged = model.updateGrowth(expandedReply); + const expandedHeight = model.getHeight(expandedReply, undefined); + const expanded = { growthChanged, height: expandedHeight, top: model.getTop(undefined, code, expandedHeight, scrollableHeight), chosenHeight: model.getHeight(expandedReply, 300) }; + // A height chosen while the reply is expanded includes the reply. + model.resetGrowth(); + model.updateGrowth(expandedReply); + assert.deepStrictEqual({ collapsed, expanded, chosenWhileExpanded: model.getHeight(expandedReply, 300) }, { + collapsed: { height: 360, top: 830 }, + expanded: { growthChanged: true, height: 440, top: 830, chosenHeight: 380 }, + chosenWhileExpanded: 300, + }); + }); + + test('moves up to keep its grown reply within the editor until the reply is no longer grown', () => { + const model = createModel(); + model.updateGrowth(collapsedReply); + model.updateGrowth(expandedReply); + const shifts: number[] = []; + // The widget's top is 400px below the top of the editor, so the expanded reply extends past its bottom. + model.updateUpwardShift(0, code, 440, 600, 600); + shifts.push(model.upwardShift); + const shiftedTop = model.getTop(0, code, 440, scrollableHeight); + // The widget doesn't move back down while its reply is grown, such as when the editor scrolls. + model.updateUpwardShift(0, code, 440, 900, 600); + shifts.push(model.upwardShift); + model.updateGrowth(collapsedReply); + model.updateUpwardShift(0, code, 360, 600, 600); + shifts.push(model.upwardShift); + assert.deepStrictEqual({ shifts, shiftedTop }, { shifts: [248, 248, 0], shiftedTop: 752 }); + }); + + test('does not move up past the top of the editor', () => { + const model = createModel(); + model.updateGrowth(collapsedReply); + model.updateGrowth(expandedReply); + // The editor became shorter than the widget after the widget was shown. Its top is 100px below the editor's top. + model.updateUpwardShift(0, code, 440, 900, 400); + assert.strictEqual(model.upwardShift, 92); + }); + + test('stays within the area that the editor can scroll through', () => { + const model = createModel(); + model.updateGrowth(collapsedReply); + // The commented code is the last line of a document that can't be scrolled beyond its last line. + assert.deepStrictEqual({ + belowLastLine: model.getTop(28, code, 360, 1020), + centeredOnLastLine: model.getTop(undefined, code, 360, 1020), + documentShorterThanWidget: model.getTop(28, code, 360, 300), + }, { + belowLastLine: 652, + centeredOnLastLine: 652, + documentShorterThanWidget: 0, + }); + }); + + test('is limited by the editor size it captured, rather than the current one', () => { + const model = createModel(); + const maxSize = () => ({ width: model.getWidthRange({ minimum: 300, natural: 1400 }).max, height: model.getHeightRange(collapsedReply).max }); + const captured = maxSize(); + model.growEditorSize({ width: 800, height: 900 }); + const grown = maxSize(); + model.captureEditorSize({ width: 800, height: 400 }); + assert.deepStrictEqual({ captured, grown, recaptured: maxSize() }, { + captured: { width: 1000, height: 584 }, + grown: { width: 1000, height: 884 }, + recaptured: { width: 800, height: 384 }, + }); + }); + }); +}); diff --git a/src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts b/src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts index fac3f4369701..5cb8b579adeb 100644 --- a/src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts +++ b/src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts @@ -162,7 +162,7 @@ export class ConfigurationManager implements IConfigurationManager { let resolvedType = config.type ?? type; let result: IConfig | null | undefined = config; - for (let seen = new Set(); result && !seen.has(resolvedType);) { + for (const seen = new Set(); result && !seen.has(resolvedType);) { seen.add(resolvedType); result = await resolveDebugConfigurationForType(resolvedType, result); result = await resolveDebugConfigurationForType('*', result); diff --git a/src/vs/workbench/contrib/debug/browser/debugEditorContribution.ts b/src/vs/workbench/contrib/debug/browser/debugEditorContribution.ts index 48e3c89d7cf8..882c6f713047 100644 --- a/src/vs/workbench/contrib/debug/browser/debugEditorContribution.ts +++ b/src/vs/workbench/contrib/debug/browser/debugEditorContribution.ts @@ -891,7 +891,7 @@ export class DebugEditorContribution implements IDebugEditorContribution { const scopes = await stackFrame.getMostSpecificScopes(stackFrame.range); const scopesWithVariables = await Promise.all(scopes.map(async scope => - ({ scope, variables: await scope.getChildren() }))); + ({ scope, variables: await scope.getChildren() }))); // Map of inline values per line that's populated in scope order, from // narrowest to widest. This is done to avoid duplicating values if diff --git a/src/vs/workbench/contrib/debug/browser/media/debugViewlet.css b/src/vs/workbench/contrib/debug/browser/media/debugViewlet.css index 954f0d4b9357..48761d2d95d3 100644 --- a/src/vs/workbench/contrib/debug/browser/media/debugViewlet.css +++ b/src/vs/workbench/contrib/debug/browser/media/debugViewlet.css @@ -76,7 +76,7 @@ gap: 4px; min-width: 0; flex: 1; - border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0; color: var(--vscode-dropdown-foreground); outline-offset: -1px; } diff --git a/src/vs/workbench/contrib/debug/common/debugContentProvider.ts b/src/vs/workbench/contrib/debug/common/debugContentProvider.ts index 5ad05e1cb7db..dcfb8100f870 100644 --- a/src/vs/workbench/contrib/debug/common/debugContentProvider.ts +++ b/src/vs/workbench/contrib/debug/common/debugContentProvider.ts @@ -53,7 +53,8 @@ export class DebugContentProvider extends Disposable implements IWorkbenchContri } override dispose(): void { - this.pendingUpdates.forEach(cancellationSource => cancellationSource.dispose()); + this.pendingUpdates.forEach(cancellationSource => cancellationSource.dispose(true)); + this.pendingUpdates.clear(); super.dispose(); } @@ -104,7 +105,17 @@ export class DebugContentProvider extends Disposable implements IWorkbenchContri return this.modelService.createModel(message, languageSelection, resource); }; + const myToken = new CancellationTokenSource(); + if (model) { + this.pendingUpdates.get(model.id)?.dispose(true); + this.pendingUpdates.set(model.id, myToken); + } + const isCurrent = () => !myToken.token.isCancellationRequested && !model?.isDisposed(); + return session.loadSource(resource).then(response => { + if (model && !isCurrent()) { + return model; + } if (response && response.body) { @@ -112,21 +123,9 @@ export class DebugContentProvider extends Disposable implements IWorkbenchContri const newContent = response.body.content; - // cancel and dispose an existing update - const cancellationSource = this.pendingUpdates.get(model.id); - cancellationSource?.cancel(); - - // create and keep update token - const myToken = new CancellationTokenSource(); - this.pendingUpdates.set(model.id, myToken); - // update text model return this.editorWorkerService.computeMoreMinimalEdits(model.uri, [{ text: newContent, range: model.getFullModelRange() }]).then(edits => { - - // remove token - this.pendingUpdates.delete(model.id); - - if (!myToken.token.isCancellationRequested && edits && edits.length > 0) { + if (isCurrent() && edits && edits.length > 0) { // use the evil-edit as these models show in readonly-editor only model.applyEdits(edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text))); } @@ -142,6 +141,11 @@ export class DebugContentProvider extends Disposable implements IWorkbenchContri return createErrModel(); - }, (err: DebugProtocol.ErrorResponse) => createErrModel(err.message)); + }, (err: DebugProtocol.ErrorResponse) => model && !isCurrent() ? model : createErrModel(err.message)).finally(() => { + if (model && this.pendingUpdates.get(model.id) === myToken) { + this.pendingUpdates.delete(model.id); + } + myToken.dispose(); + }); } } diff --git a/src/vs/workbench/contrib/debug/test/browser/debugSource.test.ts b/src/vs/workbench/contrib/debug/test/browser/debugSource.test.ts index 464be5ba1692..2c2fffd754b2 100644 --- a/src/vs/workbench/contrib/debug/test/browser/debugSource.test.ts +++ b/src/vs/workbench/contrib/debug/test/browser/debugSource.test.ts @@ -4,12 +4,30 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { isWindows } from '../../../../../base/common/platform.js'; import { URI as uri } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { EndOfLinePreference } from '../../../../../editor/common/model.js'; +import { IEditorWorkerService } from '../../../../../editor/common/services/editorWorker.js'; +import { ITextModelService } from '../../../../../editor/common/services/resolverService.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IViewContainerModel, IViewDescriptorService, ViewContainer, ViewContainerLocation } from '../../../../common/views.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { DebugSession } from '../../browser/debugSession.js'; +import { LoadedScriptsView } from '../../browser/loadedScriptsView.js'; +import { RawDebugSession } from '../../browser/rawDebugSession.js'; +import { IDebugService, IViewModel, LOADED_SCRIPTS_VIEW_ID } from '../../common/debug.js'; +import { DebugContentProvider } from '../../common/debugContentProvider.js'; import { Source } from '../../common/debugSource.js'; -import { mockUriIdentityService } from './mockDebugModel.js'; +import { MockDebugAdapter } from '../common/mockDebug.js'; +import { createTestSession } from './callStack.test.js'; +import { createMockDebugModel, mockUriIdentityService } from './mockDebugModel.js'; suite('Debug - Source', () => { @@ -62,3 +80,181 @@ suite('Debug - Source', () => { checkData(uri.from({ scheme: 'debug', path: 'a/b/c/d/foo.txt', query: 'session=100&ref=10' }), 'foo.txt', 'a/b/c/d/foo.txt', 10, '100'); }); }); + +suite('Debug - Source content', () => { + let sessionToDisconnect: DebugSession | undefined; + + teardown(async () => { + await sessionToDisconnect?.disconnect(); + sessionToDisconnect = undefined; + }); + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + async function createSourceView(computeMoreMinimalEdits: IEditorWorkerService['computeMoreMinimalEdits'] = async (_resource, edits) => edits ?? undefined) { + const services = workbenchInstantiationService(undefined, disposables); + const debugModel = createMockDebugModel(disposables); + const session = disposables.add(createTestSession(debugModel)); + sessionToDisconnect = session; + debugModel.addSession(session); + const sourceRequests = disposables.add(new Emitter()); + let initialRequest = true; + const adapter = disposables.add(new class extends MockDebugAdapter { + override sendMessage(message: DebugProtocol.ProtocolMessage): void { + if (message.type === 'request') { + const request = message as DebugProtocol.Request; + if (request.command === 'source') { + if (initialRequest) { + initialRequest = false; + this.sendResponseBody(request, { content: 'initial' }); + } else { + sourceRequests.fire(request); + } + return; + } + } + super.sendMessage(message); + } + }); + const raw = disposables.add(new RawDebugSession(adapter, undefined!, '', '', undefined!, undefined!, undefined!, undefined!)); + session.initializeForTest(raw); + const unavailableSources: uri[] = []; + services.stub(IDebugService, { + getModel: () => debugModel, + getViewModel: () => upcastPartial({ focusedSession: session }), + onDidNewSession: Event.None, + onDidEndSession: Event.None, + sourceIsNotAvailable: resource => unavailableSources.push(resource) + }); + services.stub(IEditorWorkerService, { computeMoreMinimalEdits }); + services.stub(IHoverService, NullHoverService); + const provider = disposables.add(services.createInstance(DebugContentProvider)); + + const source = session.getSource({ name: 'synthetic.js', path: 'synthetic.js', sourceReference: 1 }); + const reference = disposables.add(await services.get(ITextModelService).createModelReference(source.uri)); + disposables.add(reference.object); + const model = reference.object.textEditorModel; + const container = upcastPartial({ id: LOADED_SCRIPTS_VIEW_ID }); + services.stub(IViewDescriptorService, { + onDidChangeLocation: Event.None, + getViewLocationById: () => ViewContainerLocation.Sidebar, + getViewDescriptorById: () => null, + getViewContainerByViewId: () => container, + getDefaultContainerById: () => container, + getViewContainerModel: () => upcastPartial({ onDidChangeContainerInfo: Event.None }) + }); + const view = disposables.add(services.createInstance(LoadedScriptsView, { id: LOADED_SCRIPTS_VIEW_ID, title: 'Loaded Scripts' })); + disposables.add(toDisposable(() => view.element.remove())); + document.body.appendChild(view.element); + view.render(); + + const settle = async () => { + const settled = Event.toPromise(session.onDidCustomEvent); + // The adapter dispatches the event after the response's microtasks settle. + adapter.sendEventBody('sourceRefreshComplete', {}); + await settled; + }; + + return { + adapter, + model, + provider, + settle, + unavailableSources, + requestSourceChange: async () => { + const requested = Event.toPromise(sourceRequests.event); + adapter.sendEventBody('loadedSource', { reason: 'changed', source: source.raw }); + return requested; + }, + respond: async (request: DebugProtocol.Request, content: string) => { + adapter.sendResponseBody(request, { content }); + await settle(); + } + }; + } + + test('keeps the latest loaded source when an earlier source response arrives last', async () => { + const { model, requestSourceChange, respond } = await createSourceView(); + const first = await requestSourceChange(); + const second = await requestSourceChange(); + + await respond(second, 'newer source'); + await respond(first, 'older source'); + + assert.strictEqual(model.getValue(), 'newer source'); + }); + + test('does not let a cancelled edit clear a newer source update', async () => { + const firstEdits = new DeferredPromise(); + const secondEdits = new DeferredPromise(); + const { model, requestSourceChange, respond, settle } = await createSourceView(async (_resource, edits) => { + if (edits?.[0].text === 'first') { + await firstEdits.p; + } else if (edits?.[0].text === 'second') { + await secondEdits.p; + } + return edits ?? undefined; + }); + + await respond(await requestSourceChange(), 'first'); + await respond(await requestSourceChange(), 'second'); + await firstEdits.complete(); + await settle(); + await respond(await requestSourceChange(), 'third'); + await secondEdits.complete(); + await settle(); + + assert.strictEqual(model.getValue(), 'third'); + }); + + test('ignores an earlier source error after a newer source has loaded', async () => { + const { adapter, model, requestSourceChange, respond, settle, unavailableSources } = await createSourceView(); + const first = await requestSourceChange(); + const second = await requestSourceChange(); + await respond(second, 'newer source'); + + const response: DebugProtocol.Response = { + type: 'response', + seq: 0, + request_seq: first.seq, + command: first.command, + success: false, + message: 'source replaced' + }; + adapter.acceptMessage(response); + await settle(); + + assert.deepStrictEqual({ content: model.getValue(), unavailableSources }, { content: 'newer source', unavailableSources: [] }); + }); + + test('ignores a source response after the source model is disposed', async () => { + const { model, requestSourceChange, respond } = await createSourceView(); + const request = await requestSourceChange(); + model.dispose(); + + await respond(request, 'late source'); + + assert.strictEqual(model.isDisposed(), true); + }); + + test('ignores a source response after the provider is disposed', async () => { + const { model, provider, requestSourceChange, respond } = await createSourceView(); + const request = await requestSourceChange(); + provider.dispose(); + + await respond(request, 'late source'); + + assert.strictEqual(model.getValue(), 'initial'); + }); + + test('applies sequential loaded source changes including empty content', async () => { + const { model, requestSourceChange, respond } = await createSourceView(); + const contents: string[] = []; + for (const content of ['first\nline', '', '', 'last']) { + await respond(await requestSourceChange(), content); + contents.push(model.getValue(EndOfLinePreference.LF)); + } + + assert.deepStrictEqual(contents, ['first\nline', '', '', 'last']); + }); +}); diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsChart.ts b/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsChart.ts deleted file mode 100644 index b02f21ebd853..000000000000 --- a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsChart.ts +++ /dev/null @@ -1,285 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { $ } from '../../../../../base/browser/dom.js'; -import { localize } from '../../../../../nls.js'; -import { asCssVariable } from '../../../../../platform/theme/common/colorUtils.js'; -import { chartsBlue, chartsForeground, chartsLines } from '../../../../../platform/theme/common/colorRegistry.js'; - -export interface ISessionData { - startTime: number; - typedCharacters: number; - aiCharacters: number; - acceptedInlineSuggestions: number | undefined; - chatEditCount: number | undefined; -} - -export interface IDailyAggregate { - date: string; // ISO date string (YYYY-MM-DD) - displayDate: string; // Formatted for display - aiRate: number; - totalAiChars: number; - totalTypedChars: number; - inlineSuggestions: number; - chatEdits: number; - sessionCount: number; -} - -export type ChartViewMode = 'days' | 'sessions'; - -export function aggregateSessionsByDay(sessions: readonly ISessionData[]): IDailyAggregate[] { - const dayMap = new Map(); - - for (const session of sessions) { - const date = new Date(session.startTime); - const isoDate = date.toISOString().split('T')[0]; - const displayDate = date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); - - let aggregate = dayMap.get(isoDate); - if (!aggregate) { - aggregate = { - date: isoDate, - displayDate, - aiRate: 0, - totalAiChars: 0, - totalTypedChars: 0, - inlineSuggestions: 0, - chatEdits: 0, - sessionCount: 0, - }; - dayMap.set(isoDate, aggregate); - } - - aggregate.totalAiChars += session.aiCharacters; - aggregate.totalTypedChars += session.typedCharacters; - aggregate.inlineSuggestions += session.acceptedInlineSuggestions ?? 0; - aggregate.chatEdits += session.chatEditCount ?? 0; - aggregate.sessionCount += 1; - } - - // Calculate AI rate for each day - for (const aggregate of dayMap.values()) { - const total = aggregate.totalAiChars + aggregate.totalTypedChars; - aggregate.aiRate = total > 0 ? aggregate.totalAiChars / total : 0; - } - - // Sort by date - return Array.from(dayMap.values()).sort((a, b) => a.date.localeCompare(b.date)); -} - -export interface IAiStatsChartOptions { - sessions: readonly ISessionData[]; - viewMode: ChartViewMode; -} - -export function createAiStatsChart( - options: IAiStatsChartOptions -): HTMLElement { - const { sessions: sessionsData, viewMode: mode } = options; - - const width = 280; - const height = 100; - const margin = { top: 10, right: 10, bottom: 25, left: 30 }; - const innerWidth = width - margin.left - margin.right; - const innerHeight = height - margin.top - margin.bottom; - - const container = $('.ai-stats-chart-container'); - container.style.position = 'relative'; - container.style.marginTop = '8px'; - - const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttribute('width', `${width}px`); - svg.setAttribute('height', `${height}px`); - svg.setAttribute('viewBox', `0 0 ${width} ${height}`); - svg.style.display = 'block'; - container.appendChild(svg); - - const g = document.createElementNS('http://www.w3.org/2000/svg', 'g'); - g.setAttribute('transform', `translate(${margin.left},${margin.top})`); - svg.appendChild(g); - - if (sessionsData.length === 0) { - const text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - text.setAttribute('x', `${innerWidth / 2}`); - text.setAttribute('y', `${innerHeight / 2}`); - text.setAttribute('text-anchor', 'middle'); - text.setAttribute('fill', asCssVariable(chartsForeground)); - text.setAttribute('font-size', '11px'); - text.textContent = localize('noData', "No data yet"); - g.appendChild(text); - return container; - } - - // Draw axes - const xAxisLine = document.createElementNS('http://www.w3.org/2000/svg', 'line'); - xAxisLine.setAttribute('x1', '0'); - xAxisLine.setAttribute('y1', `${innerHeight}`); - xAxisLine.setAttribute('x2', `${innerWidth}`); - xAxisLine.setAttribute('y2', `${innerHeight}`); - xAxisLine.setAttribute('stroke', asCssVariable(chartsLines)); - xAxisLine.setAttribute('stroke-width', '1px'); - g.appendChild(xAxisLine); - - const yAxisLine = document.createElementNS('http://www.w3.org/2000/svg', 'line'); - yAxisLine.setAttribute('x1', '0'); - yAxisLine.setAttribute('y1', '0'); - yAxisLine.setAttribute('x2', '0'); - yAxisLine.setAttribute('y2', `${innerHeight}`); - yAxisLine.setAttribute('stroke', asCssVariable(chartsLines)); - yAxisLine.setAttribute('stroke-width', '1px'); - g.appendChild(yAxisLine); - - // Y-axis labels (0%, 50%, 100%) - for (const pct of [0, 50, 100]) { - const y = innerHeight - (pct / 100) * innerHeight; - const label = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - label.setAttribute('x', '-4'); - label.setAttribute('y', `${y + 3}`); - label.setAttribute('text-anchor', 'end'); - label.setAttribute('fill', asCssVariable(chartsForeground)); - label.setAttribute('font-size', '9px'); - label.textContent = `${pct}%`; - g.appendChild(label); - - if (pct > 0) { - const gridLine = document.createElementNS('http://www.w3.org/2000/svg', 'line'); - gridLine.setAttribute('x1', '0'); - gridLine.setAttribute('y1', `${y}`); - gridLine.setAttribute('x2', `${innerWidth}`); - gridLine.setAttribute('y2', `${y}`); - gridLine.setAttribute('stroke', asCssVariable(chartsLines)); - gridLine.setAttribute('stroke-width', '0.5px'); - gridLine.setAttribute('stroke-dasharray', '2,2'); - g.appendChild(gridLine); - } - } - - if (mode === 'days') { - renderDaysView(); - } else { - renderSessionsView(); - } - - function renderDaysView() { - const dailyData = aggregateSessionsByDay(sessionsData); - const barCount = dailyData.length; - const barWidth = Math.min(20, (innerWidth - (barCount - 1) * 2) / barCount); - const gap = 2; - const totalBarSpace = barCount * barWidth + (barCount - 1) * gap; - const startX = (innerWidth - totalBarSpace) / 2; - - // Calculate which labels to show based on available space - // Each label needs roughly 40px of space to not overlap - const minLabelSpacing = 40; - const totalWidth = totalBarSpace; - const maxLabels = Math.max(2, Math.floor(totalWidth / minLabelSpacing)); - const labelStep = Math.max(1, Math.ceil(barCount / maxLabels)); - - dailyData.forEach((day, i) => { - const x = startX + i * (barWidth + gap); - const barHeight = day.aiRate * innerHeight; - const y = innerHeight - barHeight; - - // Bar for AI rate - const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); - rect.setAttribute('x', `${x}`); - rect.setAttribute('y', `${y}`); - rect.setAttribute('width', `${barWidth}`); - rect.setAttribute('height', `${Math.max(1, barHeight)}`); - rect.setAttribute('fill', asCssVariable(chartsBlue)); - rect.setAttribute('rx', '2'); - g.appendChild(rect); - - // X-axis label - only show at calculated intervals to avoid overlap - const isFirst = i === 0; - const isLast = i === barCount - 1; - const isAtInterval = i % labelStep === 0; - - if (isFirst || isLast || (isAtInterval && barCount > 2)) { - // Skip middle labels if they would be too close to first/last - if (!isFirst && !isLast) { - const distFromFirst = i * (barWidth + gap); - const distFromLast = (barCount - 1 - i) * (barWidth + gap); - if (distFromFirst < minLabelSpacing || distFromLast < minLabelSpacing) { - return; // Skip this label - } - } - - const label = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - label.setAttribute('x', `${x + barWidth / 2}`); - label.setAttribute('y', `${innerHeight + 12}`); - label.setAttribute('text-anchor', 'middle'); - label.setAttribute('fill', asCssVariable(chartsForeground)); - label.setAttribute('font-size', '8px'); - label.textContent = day.displayDate; - g.appendChild(label); - } - }); - } - - function renderSessionsView() { - const sessionCount = sessionsData.length; - const barWidth = Math.min(8, (innerWidth - (sessionCount - 1) * 1) / sessionCount); - const gap = 1; - const totalBarSpace = sessionCount * barWidth + (sessionCount - 1) * gap; - const startX = (innerWidth - totalBarSpace) / 2; - - sessionsData.forEach((session, i) => { - const total = session.aiCharacters + session.typedCharacters; - const aiRate = total > 0 ? session.aiCharacters / total : 0; - const x = startX + i * (barWidth + gap); - const barHeight = aiRate * innerHeight; - const y = innerHeight - barHeight; - - // Bar for AI rate - const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); - rect.setAttribute('x', `${x}`); - rect.setAttribute('y', `${y}`); - rect.setAttribute('width', `${barWidth}`); - rect.setAttribute('height', `${Math.max(1, barHeight)}`); - rect.setAttribute('fill', asCssVariable(chartsBlue)); - rect.setAttribute('rx', '1'); - g.appendChild(rect); - }); - - // X-axis labels: only show first and last to avoid overlap - // Each label is roughly 40px wide (e.g., "Jan 15") - const minLabelSpacing = 40; - - if (sessionCount === 0) { - return; - } - - // Always show first label - const firstSession = sessionsData[0]; - const firstX = startX; - const firstDate = new Date(firstSession.startTime); - const firstLabel = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - firstLabel.setAttribute('x', `${firstX + barWidth / 2}`); - firstLabel.setAttribute('y', `${innerHeight + 12}`); - firstLabel.setAttribute('text-anchor', 'start'); - firstLabel.setAttribute('fill', asCssVariable(chartsForeground)); - firstLabel.setAttribute('font-size', '8px'); - firstLabel.textContent = firstDate.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); - g.appendChild(firstLabel); - - // Show last label if there's enough space and more than 1 session - if (sessionCount > 1 && totalBarSpace >= minLabelSpacing) { - const lastSession = sessionsData[sessionCount - 1]; - const lastX = startX + (sessionCount - 1) * (barWidth + gap); - const lastDate = new Date(lastSession.startTime); - const lastLabel = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - lastLabel.setAttribute('x', `${lastX + barWidth / 2}`); - lastLabel.setAttribute('y', `${innerHeight + 12}`); - lastLabel.setAttribute('text-anchor', 'end'); - lastLabel.setAttribute('fill', asCssVariable(chartsForeground)); - lastLabel.setAttribute('font-size', '8px'); - lastLabel.textContent = lastDate.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); - g.appendChild(lastLabel); - } - } - - return container; -} diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsFeature.ts b/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsFeature.ts deleted file mode 100644 index 922e0ac5acdb..000000000000 --- a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsFeature.ts +++ /dev/null @@ -1,249 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { sumBy } from '../../../../../base/common/arrays.js'; -import { TaskQueue, timeout } from '../../../../../base/common/async.js'; -import { Lazy } from '../../../../../base/common/lazy.js'; -import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { autorun, derived, mapObservableArrayCached, observableValue, runOnChange } from '../../../../../base/common/observable.js'; -import { AnnotatedStringEdit } from '../../../../../editor/common/core/edits/stringEdit.js'; -import { isAiEdit, isUserEdit } from '../../../../../editor/common/textModelEditSource.js'; -import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; -import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; -import { AnnotatedDocuments } from '../helpers/annotatedDocuments.js'; -import { AiStatsStatusBar } from './aiStatsStatusBar.js'; - -export class AiStatsFeature extends Disposable { - private readonly _data: IValue; - private readonly _dataVersion = observableValue(this, 0); - - constructor( - annotatedDocuments: AnnotatedDocuments, - @IStorageService private readonly _storageService: IStorageService, - @IInstantiationService private readonly _instantiationService: IInstantiationService, - ) { - super(); - - const storedValue = getStoredValue(this._storageService, 'aiStats', StorageScope.WORKSPACE, StorageTarget.USER); - this._data = rateLimitWrite(storedValue, 1 / 60, this._store); - - this.aiRate.recomputeInitiallyAndOnChange(this._store); - - this._register(autorun(reader => { - reader.store.add(this._instantiationService.createInstance(AiStatsStatusBar.hot.read(reader), this)); - })); - - - const lastRequestIds: string[] = []; - - const obs = mapObservableArrayCached(this, annotatedDocuments.documents, (doc, store) => { - store.add(runOnChange(doc.documentWithAnnotations.value, (_val, _prev, edit) => { - const e = AnnotatedStringEdit.compose(edit.map(e => e.edit)); - - const curSession = new Lazy(() => this._getDataAndSession()); - - for (const r of e.replacements) { - if (isAiEdit(r.data.editSource)) { - curSession.value.currentSession.aiCharacters += r.newText.length; - } else if (isUserEdit(r.data.editSource)) { - curSession.value.currentSession.typedCharacters += r.newText.length; - } - } - - if (e.replacements.length > 0) { - const sessionToUpdate = curSession.value.currentSession; - const s = e.replacements[0].data.editSource; - if (s.metadata.source === 'inlineCompletionAccept') { - if (sessionToUpdate.acceptedInlineSuggestions === undefined) { - sessionToUpdate.acceptedInlineSuggestions = 0; - } - sessionToUpdate.acceptedInlineSuggestions += 1; - } - - if (s.metadata.source === 'Chat.applyEdits' && s.metadata.$$requestId !== undefined) { - const didSeeRequestId = lastRequestIds.includes(s.metadata.$$requestId); - if (!didSeeRequestId) { - lastRequestIds.push(s.metadata.$$requestId); - if (lastRequestIds.length > 10) { - lastRequestIds.shift(); - } - if (sessionToUpdate.chatEditCount === undefined) { - sessionToUpdate.chatEditCount = 0; - } - sessionToUpdate.chatEditCount += 1; - } - } - } - - if (curSession.hasValue) { - this._data.writeValue(curSession.value.data); - this._dataVersion.set(this._dataVersion.get() + 1, undefined); - } - })); - }); - - obs.recomputeInitiallyAndOnChange(this._store); - } - - public readonly aiRate = this._dataVersion.map(() => { - const val = this._data.getValue(); - if (!val) { - return 0; - } - - const r = average(val.sessions, session => { - const sum = session.typedCharacters + session.aiCharacters; - if (sum === 0) { - return 0; - } - return session.aiCharacters / sum; - }); - - return r; - }); - - public readonly sessionCount = derived(this, r => { - this._dataVersion.read(r); - const val = this._data.getValue(); - if (!val) { - return 0; - } - return val.sessions.length; - }); - - public readonly sessions = derived(this, r => { - this._dataVersion.read(r); - const val = this._data.getValue(); - if (!val) { - return []; - } - return val.sessions; - }); - - public readonly acceptedInlineSuggestionsToday = derived(this, r => { - this._dataVersion.read(r); - const val = this._data.getValue(); - if (!val) { - return 0; - } - const startOfToday = new Date(); - startOfToday.setHours(0, 0, 0, 0); - - const sessionsToday = val.sessions.filter(s => s.startTime > startOfToday.getTime()); - return sumBy(sessionsToday, s => s.acceptedInlineSuggestions ?? 0); - }); - - private _getDataAndSession(): { data: IData; currentSession: ISession } { - const state = this._data.getValue() ?? { sessions: [] }; - - const sessionLengthMs = 5 * 60 * 1000; // 5 minutes - - let lastSession = state.sessions.at(-1); - const nowTime = Date.now(); - if (!lastSession || nowTime - lastSession.startTime > sessionLengthMs) { - state.sessions.push({ - startTime: nowTime, - typedCharacters: 0, - aiCharacters: 0, - acceptedInlineSuggestions: 0, - chatEditCount: 0, - }); - lastSession = state.sessions.at(-1)!; - - const dayMs = 24 * 60 * 60 * 1000; // 24h - // Clean up old sessions, keep only the last 24h worth of sessions - while (state.sessions.length > dayMs / sessionLengthMs) { - state.sessions.shift(); - } - } - return { data: state, currentSession: lastSession }; - } -} - -interface IData { - sessions: ISession[]; -} - -// 5 min window -interface ISession { - startTime: number; - typedCharacters: number; - aiCharacters: number; - acceptedInlineSuggestions: number | undefined; - chatEditCount: number | undefined; -} - - -function average(arr: T[], selector: (item: T) => number): number { - if (arr.length === 0) { - return 0; - } - const s = sumBy(arr, selector); - return s / arr.length; -} - - -interface IValue { - writeValue(value: T | undefined): void; - getValue(): T | undefined; -} - -function rateLimitWrite(targetValue: IValue, maxWritesPerSecond: number, store: DisposableStore): IValue { - const queue = new TaskQueue(); - let _value: T | undefined = undefined; - let valueVersion = 0; - let savedVersion = 0; - store.add(toDisposable(() => { - if (valueVersion !== savedVersion) { - targetValue.writeValue(_value); - savedVersion = valueVersion; - } - })); - - return { - writeValue(value: T | undefined): void { - valueVersion++; - const v = valueVersion; - _value = value; - - queue.clearPending(); - queue.schedule(async () => { - targetValue.writeValue(value); - savedVersion = v; - await timeout(5000); - }); - }, - getValue(): T | undefined { - if (valueVersion > 0) { - return _value; - } - return targetValue.getValue(); - } - }; -} - -function getStoredValue(service: IStorageService, key: string, scope: StorageScope, target: StorageTarget): IValue { - let lastValue: T | undefined = undefined; - let hasLastValue = false; - return { - writeValue(value: T | undefined): void { - if (value === undefined) { - service.remove(key, scope); - } else { - service.store(key, JSON.stringify(value), scope, target); - } - lastValue = value; - }, - getValue(): T | undefined { - if (hasLastValue) { - return lastValue; - } - const strVal = service.get(key, scope); - lastValue = strVal === undefined ? undefined : JSON.parse(strVal) as T | undefined; - hasLastValue = true; - return lastValue; - } - }; -} diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsStatusBar.ts b/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsStatusBar.ts deleted file mode 100644 index 3253963e84ae..000000000000 --- a/src/vs/workbench/contrib/editTelemetry/browser/editStats/aiStatsStatusBar.ts +++ /dev/null @@ -1,289 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { n } from '../../../../../base/browser/dom.js'; -import { ActionBar, IActionBarOptions, IActionOptions } from '../../../../../base/browser/ui/actionbar/actionbar.js'; -import { IAction } from '../../../../../base/common/actions.js'; -import { Codicon } from '../../../../../base/common/codicons.js'; -import { createHotClass } from '../../../../../base/common/hotReloadHelpers.js'; -import { Disposable, DisposableStore } from '../../../../../base/common/lifecycle.js'; -import { autorun, derived, IObservable, observableValue } from '../../../../../base/common/observable.js'; -import { ThemeIcon } from '../../../../../base/common/themables.js'; -import { localize } from '../../../../../nls.js'; -import { ICommandService } from '../../../../../platform/commands/common/commands.js'; -import { nativeHoverDelegate } from '../../../../../platform/hover/browser/hover.js'; -import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; -import { IStatusbarService, StatusbarAlignment } from '../../../../services/statusbar/browser/statusbar.js'; -import { AI_STATS_SETTING_ID } from '../settingIds.js'; -import type { AiStatsFeature } from './aiStatsFeature.js'; -import { ChartViewMode, createAiStatsChart, ISessionData } from './aiStatsChart.js'; -import './media.css'; - -export class AiStatsStatusBar extends Disposable { - public static readonly hot = createHotClass(this); - - constructor( - private readonly _aiStatsFeature: AiStatsFeature, - @IStatusbarService private readonly _statusbarService: IStatusbarService, - @ICommandService private readonly _commandService: ICommandService, - @ITelemetryService private readonly _telemetryService: ITelemetryService, - ) { - super(); - - this._register(autorun((reader) => { - const statusBarItem = this._createStatusBar().keepUpdated(reader.store); - - const store = this._register(new DisposableStore()); - - reader.store.add(this._statusbarService.addEntry({ - name: localize('inlineSuggestions', "Inline Suggestions"), - ariaLabel: localize('inlineSuggestionsStatusBar', "Inline suggestions status bar"), - text: '', - tooltip: { - element: async (_token) => { - this._sendHoverTelemetry(); - store.clear(); - const elem = createAiStatsHover({ - data: this._aiStatsFeature, - onOpenSettings: () => openSettingsCommand({ ids: [AI_STATS_SETTING_ID] }).run(this._commandService), - }); - return elem.keepUpdated(store).element; - }, - markdownNotSupportedFallback: undefined, - }, - content: statusBarItem.element, - }, 'aiStatsStatusBar', StatusbarAlignment.RIGHT, 100)); - })); - } - - private _sendHoverTelemetry(): void { - this._telemetryService.publicLog2<{ - aiRate: number; - }, { - owner: 'hediet'; - comment: 'Fired when the AI stats status bar hover tooltip is shown'; - aiRate: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The current AI rate percentage' }; - }>( - 'aiStatsStatusBar.hover', - { - aiRate: this._aiStatsFeature.aiRate.get(), - } - ); - } - - - private _createStatusBar() { - return n.div({ - style: { - height: '100%', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - marginLeft: '3px', - marginRight: '3px', - } - }, [ - n.div( - { - class: 'ai-stats-status-bar', - style: { - display: 'flex', - flexDirection: 'column', - - width: 50, - height: 6, - - borderRadius: 6, - borderWidth: '1px', - borderStyle: 'solid', - } - }, - [ - n.div({ - style: { - flex: 1, - - display: 'flex', - overflow: 'hidden', - - borderRadius: 6, - border: '1px solid transparent', - } - }, [ - n.div({ - style: { - width: this._aiStatsFeature.aiRate.map(v => `${v * 100}%`), - backgroundColor: 'currentColor', - } - }) - ]) - ] - ) - ]); - } -} - -export interface IAiStatsHoverData { - readonly aiRate: IObservable; - readonly acceptedInlineSuggestionsToday: IObservable; - readonly sessions: IObservable; -} - -export interface IAiStatsHoverOptions { - readonly data: IAiStatsHoverData; - readonly onOpenSettings?: () => void; -} - -export function createAiStatsHover(options: IAiStatsHoverOptions) { - const chartViewMode = observableValue('chartViewMode', 'days'); - const aiRatePercent = options.data.aiRate.map(r => `${Math.round(r * 100)}%`); - - const createToggleButton = (mode: ChartViewMode, tooltip: string, icon: ThemeIcon) => { - return derived(reader => { - const currentMode = chartViewMode.read(reader); - const isActive = currentMode === mode; - - return n.div({ - class: ['chart-toggle-button', isActive ? 'active' : ''], - style: { - padding: '2px 4px', - borderRadius: '3px', - cursor: 'pointer', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - }, - onclick: () => { - chartViewMode.set(mode, undefined); - }, - title: tooltip, - }, [ - n.div({ - class: ThemeIcon.asClassName(icon), - style: { fontSize: '14px' } - }) - ]); - }); - }; - - return n.div({ - class: 'ai-stats-status-bar', - }, [ - n.div({ - class: 'header', - style: { - minWidth: '280px', - } - }, - [ - n.div({ style: { flex: 1 } }, [localize('aiStatsStatusBarHeader', "AI Usage Statistics")]), - n.div({ style: { marginLeft: 'auto' } }, options.onOpenSettings - ? actionBar([ - { - action: { - id: 'aiStats.statusBar.settings', - label: '', - enabled: true, - run: options.onOpenSettings, - class: ThemeIcon.asClassName(Codicon.gear), - tooltip: localize('aiStats.statusBar.configure', "Configure") - }, - options: { icon: true, label: false, hoverDelegate: nativeHoverDelegate } - } - ]) - : []) - ] - ), - - n.div({ style: { display: 'flex' } }, [ - n.div({ style: { flex: 1, paddingRight: '4px' } }, [ - localize('text1', "AI vs Typing Average: {0}", aiRatePercent.get()), - ]), - ]), - n.div({ style: { flex: 1, paddingRight: '4px' } }, [ - localize('text2', "Accepted inline suggestions today: {0}", options.data.acceptedInlineSuggestionsToday.get()), - ]), - - // Chart section - n.div({ - style: { - marginTop: '8px', - borderTop: '1px solid var(--vscode-widget-border)', - paddingTop: '8px', - } - }, [ - // Chart header with toggle - n.div({ - class: 'header', - style: { - display: 'flex', - alignItems: 'center', - marginBottom: '4px', - } - }, [ - n.div({ style: { flex: 1 } }, [ - chartViewMode.map(mode => - mode === 'days' - ? localize('chartHeaderDays', "AI Rate by Day") - : localize('chartHeaderSessions', "AI Rate by Session") - ) - ]), - n.div({ - class: 'chart-view-toggle', - style: { marginLeft: 'auto', display: 'flex', gap: '2px' } - }, [ - createToggleButton('days', localize('viewByDays', "Days"), Codicon.calendar), - createToggleButton('sessions', localize('viewBySessions', "Sessions"), Codicon.listFlat), - ]) - ]), - - // Chart container - derived(reader => { - const sessions = options.data.sessions.read(reader); - const viewMode = chartViewMode.read(reader); - return n.div({ - ref: (container) => { - const chart = createAiStatsChart({ - sessions, - viewMode, - }); - container.appendChild(chart); - } - }); - }), - ]), - ]); -} - -function actionBar(actions: { action: IAction; options: IActionOptions }[], options?: IActionBarOptions) { - return derived((_reader) => n.div({ - class: [], - style: { - }, - ref: elem => { - const actionBar = _reader.store.add(new ActionBar(elem, options)); - for (const { action, options } of actions) { - actionBar.push(action, options); - } - } - })); -} - -class CommandWithArgs { - constructor( - public readonly commandId: string, - public readonly args: unknown[] = [], - ) { } - - public run(commandService: ICommandService): void { - commandService.executeCommand(this.commandId, ...this.args); - } -} - -function openSettingsCommand(options: { ids?: string[] } = {}) { - return new CommandWithArgs('workbench.action.openSettings', [{ - query: options.ids ? options.ids.map(id => `@id:${id}`).join(' ') : undefined, - }]); -} diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editStats/media.css b/src/vs/workbench/contrib/editTelemetry/browser/editStats/media.css deleted file mode 100644 index 3668b5565fde..000000000000 --- a/src/vs/workbench/contrib/editTelemetry/browser/editStats/media.css +++ /dev/null @@ -1,127 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -/* Overall */ - -.ai-stats-status-bar { - margin-top: 4px; - margin-bottom: 4px; - - hr { - margin-top: 8px; - margin-bottom: 8px; - } - - div.header { - display: flex; - align-items: center; - color: var(--vscode-descriptionForeground); - margin-bottom: 4px; - font-size: 12px; - font-weight: 600; - } - - div.description { - font-size: 11px; - color: var(--vscode-descriptionForeground); - } - - .monaco-button { - margin-top: 5px; - margin-bottom: 5px; - } - - /* Chart toggle buttons */ - .chart-view-toggle { - display: flex; - gap: 2px; - } - - .chart-toggle-button { - padding: 2px 6px; - border-radius: 3px; - cursor: pointer; - opacity: 0.6; - transition: opacity 0.15s, background-color 0.15s; - } - - .chart-toggle-button:hover { - opacity: 1; - background-color: var(--vscode-toolbar-hoverBackground); - } - - .chart-toggle-button.active { - opacity: 1; - background-color: var(--vscode-toolbar-activeBackground); - } - - /* Chart container */ - .ai-stats-chart-container { - margin-top: 4px; - } - - .ai-stats-chart-container svg { - overflow: visible; - } - - /* Setup for New User */ - - .setup .chat-feature-container { - display: flex; - align-items: center; - gap: 5px; - padding: 4px; - } - - /* Settings */ - - .settings { - display: flex; - flex-direction: column; - gap: 5px; - } - - .settings .setting { - display: flex; - align-items: center; - } - - .settings .setting .monaco-checkbox { - height: 14px; - width: 14px; - margin-right: 5px; - } - - .settings .setting .setting-label { - cursor: pointer; - } - - .settings .setting.disabled .setting-label { - color: var(--vscode-disabledForeground); - } - - - /* Contributions */ - - .contribution .body { - display: flex; - flex-direction: row; - align-items: center; - gap: 5px; - - .description, - .detail-item { - display: flex; - align-items: center; - gap: 3px; - } - - .detail-item, - .detail-item a { - margin-left: auto; - color: var(--vscode-descriptionForeground); - } - } -} diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editTelemetry.contribution.ts b/src/vs/workbench/contrib/editTelemetry/browser/editTelemetry.contribution.ts index d97a096cb3eb..bf66e75c522f 100644 --- a/src/vs/workbench/contrib/editTelemetry/browser/editTelemetry.contribution.ts +++ b/src/vs/workbench/contrib/editTelemetry/browser/editTelemetry.contribution.ts @@ -5,7 +5,7 @@ import { Registry } from '../../../../platform/registry/common/platform.js'; import { EditTelemetryContribution } from './editTelemetryContribution.js'; -import { EDIT_TELEMETRY_SETTING_ID, AI_STATS_SETTING_ID } from './settingIds.js'; +import { EDIT_TELEMETRY_SETTING_ID } from './settingIds.js'; import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { localize } from '../../../../nls.js'; import { EDIT_TELEMETRY_DETAILS_SETTING_ID, EDIT_TELEMETRY_SHOW_DECORATIONS, EDIT_TELEMETRY_SHOW_STATUS_BAR } from './settings.js'; @@ -35,15 +35,6 @@ configurationRegistry.registerConfiguration({ }, agentHost: { key: AgentHostEditTelemetryEnabledConfigKey }, }, - [AI_STATS_SETTING_ID]: { - markdownDescription: localize('editor.aiStats.enabled', "Controls whether to enable AI statistics in the editor. The gauge shows the average AI rate across 5-minute sessions, where each session's rate is calculated as AI-inserted characters divided by total inserted characters."), - type: 'boolean', - default: false, - tags: ['experimental'], - experiment: { - mode: 'auto' - } - }, [EDIT_TELEMETRY_DETAILS_SETTING_ID]: { markdownDescription: localize('telemetry.editStats.detailed.enabled', "Controls whether to enable telemetry for detailed edit statistics (only sends statistics if general telemetry is enabled)."), type: 'boolean', diff --git a/src/vs/workbench/contrib/editTelemetry/browser/editTelemetryContribution.ts b/src/vs/workbench/contrib/editTelemetry/browser/editTelemetryContribution.ts index a630fcef6438..b5bc8359d745 100644 --- a/src/vs/workbench/contrib/editTelemetry/browser/editTelemetryContribution.ts +++ b/src/vs/workbench/contrib/editTelemetry/browser/editTelemetryContribution.ts @@ -13,8 +13,7 @@ import { ITelemetryService, TelemetryLevel, telemetryLevelEnabled } from '../../ import { AnnotatedDocuments } from './helpers/annotatedDocuments.js'; import { EditTrackingFeature } from './telemetry/editSourceTrackingFeature.js'; import { VSCodeWorkspace } from './helpers/vscodeObservableWorkspace.js'; -import { AiStatsFeature } from './editStats/aiStatsFeature.js'; -import { AI_STATS_SETTING_ID, EDIT_TELEMETRY_SETTING_ID } from './settingIds.js'; +import { EDIT_TELEMETRY_SETTING_ID } from './settingIds.js'; import { IChatEntitlementService } from '../../../services/chat/common/chatEntitlementService.js'; import { AiContributionFeature } from './aiContributionFeature.js'; @@ -39,17 +38,6 @@ export class EditTelemetryContribution extends Disposable { r.store.add(instantiationService.createInstance(EditTrackingFeature, workspace.read(r), annotatedDocuments.read(r))); })); - const aiStatsEnabled = observableConfigValue(AI_STATS_SETTING_ID, true, configurationService); - this._register(autorun(r => { - const enabled = aiStatsEnabled.read(r); - const aiDisabled = chatEntitlementService.sentimentObs.read(r).hidden; - if (!enabled || aiDisabled) { - return; - } - - r.store.add(instantiationService.createInstance(AiStatsFeature, annotatedDocuments.read(r))); - })); - // Register no-op fallbacks so that extensions can always call these // commands even when AiContributionFeature is not active. // AiContributionFeature overrides these with real implementations diff --git a/src/vs/workbench/contrib/editTelemetry/browser/settingIds.ts b/src/vs/workbench/contrib/editTelemetry/browser/settingIds.ts index fcb9c14be927..7b82281246b1 100644 --- a/src/vs/workbench/contrib/editTelemetry/browser/settingIds.ts +++ b/src/vs/workbench/contrib/editTelemetry/browser/settingIds.ts @@ -1,7 +1,6 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -export { EDIT_TELEMETRY_SETTING_ID } from '../../../../platform/telemetry/common/editArcTelemetry.js'; -export const AI_STATS_SETTING_ID = 'editor.aiStats.enabled'; +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export { EDIT_TELEMETRY_SETTING_ID } from '../../../../platform/telemetry/common/editArcTelemetry.js'; diff --git a/src/vs/workbench/contrib/extensions/browser/extensionEditor.ts b/src/vs/workbench/contrib/extensions/browser/extensionEditor.ts index fb7d19ea673e..afa2211af861 100644 --- a/src/vs/workbench/contrib/extensions/browser/extensionEditor.ts +++ b/src/vs/workbench/contrib/extensions/browser/extensionEditor.ts @@ -533,9 +533,13 @@ export class ExtensionEditor extends EditorPane { this.transientDisposables.clear(); const token = this.transientDisposables.add(new CancellationTokenSource()).token; + // Rendering another extension, or clearing the editor, stops rendering this one, which would otherwise show it once its + // manifest arrives. + let isDisposed = false; + this.transientDisposables.add(toDisposable(() => { isDisposed = true; })); const gallery = await this.getGalleryVersionToShow(extension, (this.options as IExtensionEditorOptions)?.showPreReleaseVersion); - if (token.isCancellationRequested) { + if (isDisposed) { return; } @@ -560,7 +564,7 @@ export class ExtensionEditor extends EditorPane { } const manifest = await this.extensionManifest.get().promise; - if (token.isCancellationRequested) { + if (isDisposed) { return; } diff --git a/src/vs/workbench/contrib/extensions/browser/extensions.contribution.ts b/src/vs/workbench/contrib/extensions/browser/extensions.contribution.ts index ddc9d0000a26..8206b35253e9 100644 --- a/src/vs/workbench/contrib/extensions/browser/extensions.contribution.ts +++ b/src/vs/workbench/contrib/extensions/browser/extensions.contribution.ts @@ -30,7 +30,7 @@ import { EXTENSION_INSTALL_SOURCE_CONTEXT, ExtensionInstallSource, ExtensionRequ import { areSameExtensions, getIdAndVersion } from '../../../../platform/extensionManagement/common/extensionManagementUtil.js'; import { ExtensionStorageService } from '../../../../platform/extensionManagement/common/extensionStorage.js'; import { IExtensionRecommendationNotificationService } from '../../../../platform/extensionRecommendations/common/extensionRecommendations.js'; -import { EXTENSION_CATEGORIES, ExtensionType } from '../../../../platform/extensions/common/extensions.js'; +import { EXTENSION_CATEGORIES, ExtensionType, MANAGE_EXTENSION_COMMAND_ID } from '../../../../platform/extensions/common/extensions.js'; import { SyncDescriptor } from '../../../../platform/instantiation/common/descriptors.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import { IInstantiationService, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; @@ -393,7 +393,7 @@ const jsonRegistry = Registr jsonRegistry.registerSchema(ExtensionsConfigurationSchemaId, ExtensionsConfigurationSchema); // Register Commands -CommandsRegistry.registerCommand('_extensions.manage', (accessor: ServicesAccessor, extensionId: string, tab?: ExtensionEditorTab, preserveFocus?: boolean, feature?: string) => { +CommandsRegistry.registerCommand(MANAGE_EXTENSION_COMMAND_ID, (accessor: ServicesAccessor, extensionId: string, tab?: ExtensionEditorTab, preserveFocus?: boolean, feature?: string) => { const extensionService = accessor.get(IExtensionsWorkbenchService); const extension = extensionService.local.find(e => areSameExtensions(e.identifier, { id: extensionId })); if (extension) { @@ -412,7 +412,7 @@ CommandsRegistry.registerCommand('extension.open', async (accessor: ServicesAcce return extensionService.open(extension, { tab, preserveFocus, feature, sideByside }); } - return commandService.executeCommand('_extensions.manage', extensionId, tab, preserveFocus, feature); + return commandService.executeCommand(MANAGE_EXTENSION_COMMAND_ID, extensionId, tab, preserveFocus, feature); }); CommandsRegistry.registerCommand({ diff --git a/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts b/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts index 26a2aa641293..ac17af626870 100644 --- a/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts +++ b/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts @@ -1925,6 +1925,10 @@ export class EnableAIFeaturesInWorkspaceAction extends ExtensionAction { if (!this.extensionEnablementService.canChangeWorkspaceEnablement(this.extension.local)) { return; } + if (this.extension.enablementState === EnablementState.DisabledWorkspace) { + this.enabled = true; + return; + } const inspect = this.configurationService.inspect(ChatAIDisabledSettingId); if (inspect.value === false) { return; diff --git a/src/vs/workbench/contrib/extensions/browser/media/extension.css b/src/vs/workbench/contrib/extensions/browser/media/extension.css index 50d413df961d..e2e3e1ba5e86 100644 --- a/src/vs/workbench/contrib/extensions/browser/media/extension.css +++ b/src/vs/workbench/contrib/extensions/browser/media/extension.css @@ -220,7 +220,7 @@ } .extension-list-item > .details > .footer > .monaco-action-bar > .actions-container .action-label:not(.icon) { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .extension-list-item > .details > .footer > .monaco-action-bar > .actions-container .extension-action.label { @@ -282,13 +282,13 @@ /* single install */ .extension-list-item .monaco-action-bar > .actions-container > .action-item.action-dropdown-item.empty > .extension-action { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* split install */ .extension-list-item .monaco-action-bar > .actions-container > .action-item.action-dropdown-item:not(.empty) > .extension-action.label:not(.dropdown) { - border-radius: var(--vscode-cornerRadius-small) 0 0 var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .extension-list-item .monaco-action-bar > .actions-container > .action-item.action-dropdown-item > .monaco-dropdown .extension-action { - border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0; } diff --git a/src/vs/workbench/contrib/extensions/browser/media/extensionEditor.css b/src/vs/workbench/contrib/extensions/browser/media/extensionEditor.css index 7b5cb760b3a5..5bd402cbcd85 100644 --- a/src/vs/workbench/contrib/extensions/browser/media/extensionEditor.css +++ b/src/vs/workbench/contrib/extensions/browser/media/extensionEditor.css @@ -268,17 +268,17 @@ /* single install */ .extension-editor > .header > .details > .actions-status-container > .monaco-action-bar > .actions-container > .action-item > .extension-action.label, .extension-editor > .header > .details > .actions-status-container > .monaco-action-bar > .actions-container > .action-item.action-dropdown-item.empty > .extension-action.label { - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); } /* split install */ .extension-editor > .header > .details > .actions-status-container > .monaco-action-bar > .actions-container > .action-item.action-dropdown-item:not(.empty) > .extension-action.label { - border-radius: 4px 0 0 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px) 0 0 var(--workbench-custom-buttons-corner-radius, 4px); } .extension-editor > .header > .details > .actions-status-container > .monaco-action-bar > .actions-container > .action-item.action-dropdown-item:not(.empty) > .monaco-dropdown .extension-action.label { border-left-width: 0; - border-radius: 0 4px 4px 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, 4px) var(--workbench-custom-buttons-corner-radius, 4px) 0; padding: 0 2px; } diff --git a/src/vs/workbench/contrib/extensions/test/browser/extensionEditor.test.ts b/src/vs/workbench/contrib/extensions/test/browser/extensionEditor.test.ts new file mode 100644 index 000000000000..6f3c87919e0e --- /dev/null +++ b/src/vs/workbench/contrib/extensions/test/browser/extensionEditor.test.ts @@ -0,0 +1,124 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { Event } from '../../../../../base/common/event.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 { IExtensionGalleryManifestService } from '../../../../../platform/extensionManagement/common/extensionGalleryManifest.js'; +import { IAllowedExtensionsService } from '../../../../../platform/extensionManagement/common/extensionManagement.js'; +import { IExtensionManifest } from '../../../../../platform/extensions/common/extensions.js'; +import { IEditorGroup } from '../../../../services/editor/common/editorGroupsService.js'; +import { IExtensionFeaturesManagementService } from '../../../../services/extensionManagement/common/extensionFeatures.js'; +import { IExtensionManagementServerService, IWorkbenchExtensionEnablementService, IWorkbenchExtensionManagementService } from '../../../../services/extensionManagement/common/extensionManagement.js'; +import { IExtensionIgnoredRecommendationsService, IExtensionRecommendationsService } from '../../../../services/extensionRecommendations/common/extensionRecommendations.js'; +import { IWorkbenchThemeService } from '../../../../services/themes/common/workbenchThemeService.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { ExtensionEditor } from '../../browser/extensionEditor.js'; +import { ExtensionState, IExtension, IExtensionsWorkbenchService } from '../../common/extensions.js'; +import { ExtensionsInput } from '../../common/extensionsInput.js'; + +suite('ExtensionEditor', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('shows the extension that it shows last, and stops showing extensions once cleared, when the manifest of an extension that it showed before arrives later', async () => { + const instantiationService = workbenchInstantiationService(undefined, disposables); + // What the editor's actions and widgets use to show extensions that aren't installed. + instantiationService.stub(IExtensionsWorkbenchService, new class extends mock() { + override readonly onChange = Event.None; + override readonly local = []; + override canSetLanguage() { return false; } + override async canInstall() { return true as const; } + override isAutoUpdateEnabledFor() { return false; } + override getAutoUpdateValue() { return 'off' as const; } + }); + instantiationService.stub(IExtensionRecommendationsService, new class extends mock() { + override readonly onDidChangeRecommendations = Event.None; + override getAllRecommendationsWithReason() { return {}; } + }); + instantiationService.stub(IExtensionIgnoredRecommendationsService, new class extends mock() { + override readonly globalIgnoredRecommendations = []; + }); + instantiationService.stub(IExtensionGalleryManifestService, new class extends mock() { + override async getExtensionGalleryManifest() { return null; } + }); + instantiationService.stub(IExtensionManagementServerService, new class extends mock() { + override readonly localExtensionManagementServer = null; + override readonly remoteExtensionManagementServer = null; + override readonly webExtensionManagementServer = null; + }); + instantiationService.stub(IWorkbenchExtensionManagementService, new class extends mock() { }); + instantiationService.stub(IWorkbenchExtensionEnablementService, new class extends mock() { }); + instantiationService.stub(IAllowedExtensionsService, new class extends mock() { + override readonly onDidChangeAllowedExtensionsConfigValue = Event.None; + }); + instantiationService.stub(IExtensionFeaturesManagementService, new class extends mock() { + override readonly onDidChangeAccessData = Event.None; + }); + instantiationService.stub(IWorkbenchThemeService, 'getColorThemes', async () => []); + instantiationService.stub(IWorkbenchThemeService, 'getFileIconThemes', async () => []); + instantiationService.stub(IWorkbenchThemeService, 'getProductIconThemes', async () => []); + const container = mainWindow.document.body.appendChild($('div')); + disposables.add(toDisposable(() => container.remove())); + const editor = disposables.add(instantiationService.createInstance(ExtensionEditor, new class extends mock() { + override readonly windowId = mainWindow.vscodeWindowId; + }())); + editor.create(container); + + // The extensions whose READMEs the editor requested, which it does once it shows their details. + const readmes: string[] = []; + // The editor shows a Changelog tab for extensions that have a changelog, which shows the extension whose tabs it shows. + const anExtension = (id: string, displayName: string, manifest: Promise, changelog: boolean) => new class extends mock() { + override readonly identifier = { id }; + override readonly displayName = displayName; + override readonly description = ''; + override readonly state = ExtensionState.Uninstalled; + override readonly dependencies: string[] = []; + override readonly categories: string[] = []; + override readonly telemetryData = {}; + override getManifest() { return manifest; } + override getReadme() { + readmes.push(id); + return Promise.reject(new Error('No README')); + } + override hasChangelog() { return changelog; } + }(); + const show = (extension: IExtension) => editor.setInput(disposables.add(new ExtensionsInput(extension)), { preserveFocus: true }, {}, CancellationToken.None); + const shown = () => ({ + name: container.querySelector('.extension-editor .header .name')?.textContent, + tabs: [...container.querySelectorAll('.extension-editor .navbar .action-label')].map(tab => tab.textContent), + readmes: readmes.splice(0), + }); + const manifest: IExtensionManifest = { name: 'extension', publisher: 'pub', version: '1.0.0', engines: { vscode: '*' } }; + + const slowManifest = new DeferredPromise(); + const showingSlow = show(anExtension('pub.slow', 'Slow', slowManifest.p, true)); + // While the editor waits for the manifest. + await timeout(0); + await show(anExtension('pub.fast', 'Fast', Promise.resolve(manifest), false)); + await slowManifest.complete(manifest); + await showingSlow; + const superseded = shown(); + + const clearedManifest = new DeferredPromise(); + const showingCleared = show(anExtension('pub.cleared', 'Cleared', clearedManifest.p, true)); + await timeout(0); + editor.clearInput(); + await clearedManifest.complete(manifest); + await showingCleared; + const cleared = { readmes: readmes.splice(0) }; + + assert.deepStrictEqual({ superseded, cleared }, { + superseded: { name: 'Fast', tabs: ['Details', 'Features'], readmes: ['pub.fast'] }, + cleared: { readmes: [] }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/extensions/test/electron-browser/extensionsActions.test.ts b/src/vs/workbench/contrib/extensions/test/electron-browser/extensionsActions.test.ts index c8c87687a88d..c76ebad192b1 100644 --- a/src/vs/workbench/contrib/extensions/test/electron-browser/extensionsActions.test.ts +++ b/src/vs/workbench/contrib/extensions/test/electron-browser/extensionsActions.test.ts @@ -2665,6 +2665,26 @@ suite('EnableAIFeaturesInWorkspaceAction', () => { assert.strictEqual(updatedValue.value, false, 'workspace setting should be set to false'); }); + test('test enable AI in workspace is enabled after disabling AI in workspace', async () => { + const configurationService = instantiationService.get(IConfigurationService) as TestConfigurationService; + configurationService.setUserConfiguration(ChatAIDisabledSettingId, false); + + const chatExtension = aLocalExtension('copilot-chat', { publisher: 'GitHub' }, { type: ExtensionType.System }); + await instantiationService.get(IWorkbenchExtensionEnablementService).setEnablement([chatExtension], EnablementState.DisabledWorkspace); + instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', [chatExtension]); + + const workbenchService = instantiationService.get(IExtensionsWorkbenchService); + await workbenchService.queryLocal(); + const copilotChat = workbenchService.local.find(e => e.identifier.id === 'github.copilot-chat'); + assert.ok(copilotChat); + assert.strictEqual(copilotChat.enablementState, EnablementState.DisabledWorkspace); + + const testObject: ExtensionsActions.EnableAIFeaturesInWorkspaceAction = disposables.add(instantiationService.createInstance(ExtensionsActions.EnableAIFeaturesInWorkspaceAction)); + disposables.add(instantiationService.createInstance(ExtensionContainers, [testObject])); + testObject.extension = copilotChat; + assert.ok(testObject.enabled); + }); + }); function aWorkbenchExtension(state: ExtensionState, origin: ExtensionBlockingOrigin, galleryProperties: Partial = {}): Extension { diff --git a/src/vs/workbench/contrib/externalUriOpener/common/configuration.ts b/src/vs/workbench/contrib/externalUriOpener/common/configuration.ts index 3672c4bb33c6..bd33c1de2c4d 100644 --- a/src/vs/workbench/contrib/externalUriOpener/common/configuration.ts +++ b/src/vs/workbench/contrib/externalUriOpener/common/configuration.ts @@ -7,6 +7,7 @@ import { IConfigurationNode, IConfigurationRegistry, Extensions } from '../../.. import { workbenchConfigurationNodeBase } from '../../../common/configuration.js'; import * as nls from '../../../../nls.js'; import { IJSONSchema } from '../../../../base/common/jsonSchema.js'; +import { IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { defaultExternalUriOpenerId } from '../../../../platform/opener/common/opener.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; @@ -65,10 +66,40 @@ export const externalUriOpenersConfigurationNode: IConfigurationNode = { } }; -export function updateContributedOpeners(enumValues: string[], enumDescriptions: string[]): void { - externalUriOpenerIdSchemaAddition.enum = enumValues; - externalUriOpenerIdSchemaAddition.enumDescriptions = enumDescriptions; +interface IBuiltInOpener { + readonly description: string; + readonly alternateIds: readonly string[]; +} + +const builtInOpeners = new Map(); +let contributedOpenerIds: string[] = []; +let contributedOpenerDescriptions: string[] = []; + +function refreshOpenerSchema(): void { + const alternateIds = new Set([...builtInOpeners.values()].flatMap(opener => opener.alternateIds)); + const contributed = contributedOpenerIds.map((id, i) => ({ id, description: contributedOpenerDescriptions[i] })).filter(opener => !alternateIds.has(opener.id)); + externalUriOpenerIdSchemaAddition.enum = [...builtInOpeners.keys(), ...contributed.map(opener => opener.id)]; + externalUriOpenerIdSchemaAddition.enumDescriptions = [...[...builtInOpeners.values()].map(opener => opener.description), ...contributed.map(opener => opener.description)]; Registry.as(Extensions.Configuration) .notifyConfigurationSchemaUpdated(externalUriOpenersConfigurationNode); } + +export function updateContributedOpeners(enumValues: string[], enumDescriptions: string[]): void { + contributedOpenerIds = enumValues; + contributedOpenerDescriptions = enumDescriptions; + refreshOpenerSchema(); +} + +/** + * Lists a workbench opener, which is not contributed by an extension, as a value of the opener setting. + * Contributed openers in `alternateIds` stay usable in settings but are no longer offered, because this opener replaces them. + */ +export function registerBuiltInExternalUriOpener(id: string, description: string, alternateIds: readonly string[] = []): IDisposable { + builtInOpeners.set(id, { description, alternateIds }); + refreshOpenerSchema(); + return toDisposable(() => { + builtInOpeners.delete(id); + refreshOpenerSchema(); + }); +} diff --git a/src/vs/workbench/contrib/externalUriOpener/common/externalUriOpenerService.ts b/src/vs/workbench/contrib/externalUriOpener/common/externalUriOpenerService.ts index e8e63a4ca6d9..cd9d5bdb1dc9 100644 --- a/src/vs/workbench/contrib/externalUriOpener/common/externalUriOpenerService.ts +++ b/src/vs/workbench/contrib/externalUriOpener/common/externalUriOpenerService.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { isCancellationError } from '../../../../base/common/errors.js'; import { Iterable } from '../../../../base/common/iterator.js'; import { Disposable, IDisposable } from '../../../../base/common/lifecycle.js'; import { LinkedList } from '../../../../base/common/linkedList.js'; @@ -207,7 +208,9 @@ export class ExternalUriOpenerService extends Disposable implements IExternalUri try { return { opener, priority: await opener.canOpen(sourceUri, token) }; } catch (e) { - this.logService.error(e); + if (!isCancellationError(e)) { + this.logService.error(e); + } return undefined; } })); diff --git a/src/vs/workbench/contrib/externalUriOpener/test/common/configuration.test.ts b/src/vs/workbench/contrib/externalUriOpener/test/common/configuration.test.ts new file mode 100644 index 000000000000..0454283c508e --- /dev/null +++ b/src/vs/workbench/contrib/externalUriOpener/test/common/configuration.test.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { externalUriOpenersConfigurationNode, externalUriOpenersSettingId, registerBuiltInExternalUriOpener, updateContributedOpeners } from '../../common/configuration.js'; + +suite('External URI opener configuration', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + function getListedOpeners(): ReadonlyArray<{ id: string; description: string | undefined }> { + const schema = externalUriOpenersConfigurationNode.properties![externalUriOpenersSettingId].additionalProperties as { anyOf: Array<{ enum?: string[]; enumDescriptions?: string[] }> }; + const addition = schema.anyOf[schema.anyOf.length - 1]; + return (addition.enum ?? []).map((id, i) => ({ id, description: addition.enumDescriptions?.[i] })); + } + + test('lists built-in openers before contributed ones, hides replaced ones and keeps them when contributed openers change', () => { + const store = new DisposableStore(); + try { + store.add(registerBuiltInExternalUriOpener('builtIn', 'Built-in', ['replaced'])); + updateContributedOpeners(['contributed', 'replaced'], ['ext.id', 'other.ext']); + assert.deepStrictEqual(getListedOpeners(), [ + { id: 'builtIn', description: 'Built-in' }, + { id: 'contributed', description: 'ext.id' }, + ]); + + updateContributedOpeners([], []); + assert.deepStrictEqual(getListedOpeners(), [{ id: 'builtIn', description: 'Built-in' }]); + } finally { + store.dispose(); + updateContributedOpeners([], []); + } + assert.deepStrictEqual(getListedOpeners(), []); + }); +}); diff --git a/src/vs/workbench/contrib/externalUriOpener/test/common/externalUriOpenerService.test.ts b/src/vs/workbench/contrib/externalUriOpener/test/common/externalUriOpenerService.test.ts index 4b1154615405..b90fd54c80bd 100644 --- a/src/vs/workbench/contrib/externalUriOpener/test/common/externalUriOpenerService.test.ts +++ b/src/vs/workbench/contrib/externalUriOpener/test/common/externalUriOpenerService.test.ts @@ -5,6 +5,7 @@ import assert from 'assert'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { CancellationError } from '../../../../../base/common/errors.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; @@ -13,6 +14,7 @@ import { IConfigurationService } from '../../../../../platform/configuration/com import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ViewColumn } from '../../../../../platform/editor/common/editor.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; import { IOpenerService, OpenOptions } from '../../../../../platform/opener/common/opener.js'; import { IPickOptions, IQuickInputService, IQuickPickItem, QuickPickInput } from '../../../../../platform/quickinput/common/quickInput.js'; import { ExternalUriOpenerService, IExternalOpenerProvider, IExternalUriOpener, ILinkHandler } from '../../common/externalUriOpenerService.js'; @@ -199,6 +201,23 @@ suite('ExternalUriOpenerService', () => { assert.strictEqual(opener?.id, 'enabled'); }); + test('Should log failing openers but not cancelled ones', async () => { + const errors: unknown[] = []; + instantiationService.stub(ILogService, new class extends NullLogService { override error(error: unknown) { errors.push(error); } }); + const failure = new Error('failed'); + const externalUriOpenerService = disposables.add(instantiationService.createInstance(ExternalUriOpenerService)); + disposables.add(externalUriOpenerService.registerExternalOpenerProvider(new class implements IExternalOpenerProvider { + async *getOpeners(_targetUri: URI): AsyncGenerator { + yield { id: 'cancelled', label: 'cancelled', canOpen: async () => { throw new CancellationError(); }, openExternalUri: async () => true }; + yield { id: 'failing', label: 'failing', canOpen: async () => { throw failure; }, openExternalUri: async () => true }; + } + })); + + const uri = URI.parse('http://contoso.com'); + const opener = await externalUriOpenerService.getOpener(uri, { sourceUri: uri }, CancellationToken.None); + assert.deepStrictEqual({ opener, errors }, { opener: undefined, errors: [failure] }); + }); + test('Should list link handlers with the one opening the link by default first', async () => { const configurationService = new TestConfigurationService(); instantiationService.stub(IConfigurationService, configurationService); diff --git a/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts b/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts index f3578109f857..c3e6564dde46 100644 --- a/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts +++ b/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts @@ -27,6 +27,7 @@ import { ThemeIcon } from '../../../../base/common/themables.js'; import { IExplorerService } from './files.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { Categories } from '../../../../platform/action/common/actionCommonCategories.js'; +import { NewMarkdownDocumentFromNewTabButtonAction, NewUntitledFileFromNewTabButtonAction } from './newTabButtonActions.js'; // Contribute Global Actions @@ -41,6 +42,8 @@ registerAction2(SetActiveEditorReadonlyInSession); registerAction2(SetActiveEditorWriteableInSession); registerAction2(ToggleActiveEditorReadonlyInSession); registerAction2(ResetActiveEditorReadonlyInSession); +registerAction2(NewUntitledFileFromNewTabButtonAction); +registerAction2(NewMarkdownDocumentFromNewTabButtonAction); // Commands CommandsRegistry.registerCommand('_files.windowOpen', openWindowCommand); diff --git a/src/vs/workbench/contrib/files/browser/fileCommands.ts b/src/vs/workbench/contrib/files/browser/fileCommands.ts index d124ce22ef14..33f6e8a94bff 100644 --- a/src/vs/workbench/contrib/files/browser/fileCommands.ts +++ b/src/vs/workbench/contrib/files/browser/fileCommands.ts @@ -733,6 +733,7 @@ KeybindingsRegistry.registerCommandAndKeybindingRule({ pinned: true }, languageId: args?.languageId, + untitledOrigin: 'newFileCommand', }); } }); diff --git a/src/vs/workbench/contrib/files/browser/files.contribution.ts b/src/vs/workbench/contrib/files/browser/files.contribution.ts index 72f331d5163c..aaba0ae8a184 100644 --- a/src/vs/workbench/contrib/files/browser/files.contribution.ts +++ b/src/vs/workbench/contrib/files/browser/files.contribution.ts @@ -36,6 +36,8 @@ import { FileEditorInputSerializer, FileEditorWorkingCopyEditorHandler } from '. import { ModesRegistry } from '../../../../editor/common/languages/modesRegistry.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { TextFileEditor } from './editors/textFileEditor.js'; +import { IUntitledDocumentTelemetryService } from '../../../services/untitled/common/untitledDocumentTelemetry.js'; +import { UntitledDocumentTelemetry } from './untitledDocumentTelemetry.js'; class FileUriLabelContribution implements IWorkbenchContribution { @@ -106,6 +108,14 @@ registerWorkbenchContribution2(ExplorerViewletViewsContribution.ID, ExplorerView // Register Text File Editor Tracker registerWorkbenchContribution2(TextFileEditorTracker.ID, TextFileEditorTracker, WorkbenchPhase.BlockStartup); +// Untitled document telemetry: created eagerly so that it sees the untitled documents restored on startup +registerSingleton(IUntitledDocumentTelemetryService, UntitledDocumentTelemetry, InstantiationType.Eager); +class UntitledDocumentTelemetryContribution implements IWorkbenchContribution { + static readonly ID = 'workbench.contrib.untitledDocumentTelemetry'; + constructor(@IUntitledDocumentTelemetryService _untitledDocumentTelemetryService: IUntitledDocumentTelemetryService) { } +} +registerWorkbenchContribution2(UntitledDocumentTelemetryContribution.ID, UntitledDocumentTelemetryContribution, WorkbenchPhase.BlockStartup); + // Register Text File Save Error Handler registerWorkbenchContribution2(TextFileSaveErrorHandler.ID, TextFileSaveErrorHandler, WorkbenchPhase.BlockStartup); diff --git a/src/vs/workbench/contrib/files/browser/newTabButtonActions.ts b/src/vs/workbench/contrib/files/browser/newTabButtonActions.ts new file mode 100644 index 000000000000..9dfa369edee1 --- /dev/null +++ b/src/vs/workbench/contrib/files/browser/newTabButtonActions.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 { Codicon } from '../../../../base/common/codicons.js'; +import { localize2 } from '../../../../nls.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { NewTabButtonEntryAction } from '../../../browser/parts/editor/newTabButton.js'; +import { DEFAULT_EDITOR_ASSOCIATION } from '../../../common/editor.js'; +import { IEditorGroup } from '../../../services/editor/common/editorGroupsService.js'; +import { IEditorResolverService } from '../../../services/editor/common/editorResolverService.js'; +import { IEditorService } from '../../../services/editor/common/editorService.js'; +import { IUntitledTextEditorService } from '../../../services/untitled/common/untitledTextEditorService.js'; + +const MARKDOWN_EDITOR_ID = 'vscode.markdown.editor'; + +export class NewUntitledFileFromNewTabButtonAction extends NewTabButtonEntryAction { + + constructor() { + super({ + id: 'workbench.action.files.newUntitledFileFromNewTabButton', + title: localize2('newTabButton.untitledFile', "New Untitled Text File"), + icon: Codicon.newFile, + order: 1, + }); + } + + protected override openTab(accessor: ServicesAccessor, group: IEditorGroup): Promise { + return accessor.get(IEditorService).openEditor({ + resource: undefined, + untitledOrigin: 'newTabButton', + options: { pinned: true, override: DEFAULT_EDITOR_ASSOCIATION.id } + }, group); + } +} + +export class NewMarkdownDocumentFromNewTabButtonAction extends NewTabButtonEntryAction { + + constructor() { + super({ + id: 'workbench.action.files.newMarkdownDocumentFromNewTabButton', + title: localize2('newTabButton.markdown', "New Markdown Document"), + icon: Codicon.markdown, + order: 2, + }); + } + + protected override async openTab(accessor: ServicesAccessor, group: IEditorGroup): Promise { + const editorService = accessor.get(IEditorService); + const editorResolverService = accessor.get(IEditorResolverService); + const untitled = accessor.get(IUntitledTextEditorService).create({ languageId: 'markdown', origin: 'newTabButton' }); + + // Once resolved, its text model has the Markdown language, so that it matches the editors of `*.md` files. + await untitled.resolve(); + const markdownEditorAvailable = editorResolverService.getEditors(untitled.resource).some(editor => editor.id === MARKDOWN_EDITOR_ID); + + return editorService.openEditor({ + resource: untitled.resource, + options: { pinned: true, override: markdownEditorAvailable ? MARKDOWN_EDITOR_ID : DEFAULT_EDITOR_ASSOCIATION.id } + }, group); + } +} diff --git a/src/vs/workbench/contrib/files/browser/untitledDocumentTelemetry.ts b/src/vs/workbench/contrib/files/browser/untitledDocumentTelemetry.ts new file mode 100644 index 000000000000..07a78a60b901 --- /dev/null +++ b/src/vs/workbench/contrib/files/browser/untitledDocumentTelemetry.ts @@ -0,0 +1,386 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable, DisposableMap, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { disposableTimeout } from '../../../../base/common/async.js'; +import { ResourceMap } from '../../../../base/common/map.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { extname } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { ITextModel } from '../../../../editor/common/model.js'; +import { IModelService } from '../../../../editor/common/services/model.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { ChangeLanguageAction } from '../../../browser/parts/editor/editorStatus.js'; +import { UntitledTextEditorOrigin } from '../../../common/editor.js'; +import { IEditorService } from '../../../services/editor/common/editorService.js'; +import { IFilesConfigurationService } from '../../../services/filesConfiguration/common/filesConfigurationService.js'; +import { LanguageDetectionLanguageEventSource } from '../../../services/languageDetection/common/languageDetectionWorkerService.js'; +import { ILifecycleService } from '../../../services/lifecycle/common/lifecycle.js'; +import { IUntitledDocumentTelemetryService } from '../../../services/untitled/common/untitledDocumentTelemetry.js'; +import { IUntitledTextEditorModel } from '../../../services/untitled/common/untitledTextEditorModel.js'; +import { IUntitledTextEditorService } from '../../../services/untitled/common/untitledTextEditorService.js'; +import { IWorkingCopyService } from '../../../services/workingCopy/common/workingCopyService.js'; + +type UntitledDocumentKind = 'created' | 'firstEdit' | 'ended'; +type UntitledDocumentOutcome = 'saved' | 'closedEmpty' | 'closedDiscarded' | 'other'; +type SizeBucket = '0' | '<100' | '<1k' | '<10k' | '>=10k'; + +type UntitledDocumentEvent = { + kind: UntitledDocumentKind; + untitledDocumentId: string; + origin: UntitledTextEditorOrigin | 'other' | undefined; + restored: boolean | undefined; + language: string | undefined; + editorId: string | undefined; + msSinceCreated: number | undefined; + outcome: UntitledDocumentOutcome | undefined; + atShutdown: boolean | undefined; + savedExt: string | undefined; + sizeBucket: SizeBucket | undefined; +}; + +type UntitledDocumentClassification = { + owner: 'hediet'; + comment: 'Follows untitled text documents from creation to their end, to understand what new files are used for (e.g. scratchpads, Markdown, code) and how the empty editor hint is used.'; + kind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The lifecycle step: created, firstEdit or ended.' }; + untitledDocumentId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'A random id per untitled document, to correlate the events of one document. It is kept across window reloads through hot exit.' }; + origin: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'created: where the document was created from (e.g. newFileCommand, tabBarDoubleClick, extensionApi).' }; + restored: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'created: whether the document was restored after a window reload (hot exit) instead of newly created.' }; + language: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'created: the initial language id. ended: the final language id.' }; + editorId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'ended: the id of the editor the document was last active in (e.g. default for the text editor, or a custom editor view type).' }; + msSinceCreated: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'firstEdit, ended: milliseconds since the document was created.' }; + outcome: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'ended: saved, closedEmpty, closedDiscarded or other.' }; + atShutdown: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'ended: whether the document ended because the window closed.' }; + savedExt: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'ended: the file extension the document was saved with.' }; + sizeBucket: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'ended: the number of characters as a coarse bucket.' }; +}; + +type DocumentLanguageChangedEvent = { + from: string; + to: string; + source: 'picker' | 'autoDetect' | 'other'; + scheme: string; + untitledDocumentId: string | undefined; +}; + +type DocumentLanguageChangedClassification = { + owner: 'hediet'; + comment: 'Language changes of untitled documents (any source) and of other documents (only through the language picker), to understand which languages documents end up in.'; + from: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The previous language id.' }; + to: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The new language id.' }; + source: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'What changed the language: the language picker, automatic language detection, or something else (e.g. an extension).' }; + scheme: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The scheme of the document, e.g. untitled or file.' }; + untitledDocumentId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The untitledDocumentId of the untitledDocument events, if the document is untitled.' }; +}; + +const STORAGE_KEY = 'untitledDocumentTelemetry.documents'; + +interface IPersistedDocument { + readonly id: string; + readonly createdAt: number; + /** Hot exit also keeps empty documents, so a kept document has not necessarily been edited. */ + edited: boolean; +} + +interface ITrackedDocument extends IPersistedDocument { + readonly model: IUntitledTextEditorModel; + readonly disposables: DisposableStore; + reverted: boolean; + length: number; + /** The text model version and the length before the last content change, to tell what a revert emptied. */ + lastChange: { readonly versionId: number; readonly previousLength: number } | undefined; + /** The length right before the last revert, e.g. the one Save As does before reporting the save, or Don't Save. */ + lengthBeforeRevert: number | undefined; + language: string; + editorId: string | undefined; +} + +export function getSizeBucket(length: number): SizeBucket { + if (length === 0) { + return '0'; + } + if (length < 100) { + return '<100'; + } + if (length < 1000) { + return '<1k'; + } + if (length < 10000) { + return '<10k'; + } + return '>=10k'; +} + +export class UntitledDocumentTelemetry extends Disposable implements IUntitledDocumentTelemetryService { + + declare readonly _serviceBrand: undefined; + + private readonly documents = new ResourceMap(); + private readonly textModelListeners = this._register(new DisposableMap()); + private readonly persisted: Map; + private shuttingDown = false; + + constructor( + @IUntitledTextEditorService untitledTextEditorService: IUntitledTextEditorService, + @IWorkingCopyService workingCopyService: IWorkingCopyService, + @IModelService modelService: IModelService, + @IEditorService private readonly editorService: IEditorService, + @ILifecycleService lifecycleService: ILifecycleService, + @IStorageService private readonly storageService: IStorageService, + @ITelemetryService private readonly telemetryService: ITelemetryService, + @IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService, + ) { + super(); + + this.persisted = this.readPersisted(); + + this._register(untitledTextEditorService.onDidCreate(model => this.track(model))); + for (const workingCopy of workingCopyService.workingCopies) { + const model = workingCopy.resource.scheme === Schemas.untitled ? untitledTextEditorService.get(workingCopy.resource) : undefined; + if (model) { + this.track(model); + } + } + + this._register(untitledTextEditorService.onDidSave(e => this.end(e.source, 'saved', extname(e.target)))); + this._register(untitledTextEditorService.onWillDispose(model => this.onWillDispose(model))); + + this._register(modelService.onModelAdded(model => this.watchTextModel(model))); + for (const model of modelService.getModels()) { + this.watchTextModel(model); + } + + this._register(editorService.onDidActiveEditorChange(() => this.onDidActiveEditorChange())); + this._register(lifecycleService.onWillShutdown(() => this.onWillShutdown())); + this._register(storageService.onWillSaveState(() => this.persist())); + } + + getUntitledDocumentId(resource: URI | undefined): string | undefined { + return resource ? this.documents.get(resource)?.id : undefined; + } + + private track(model: IUntitledTextEditorModel): void { + if (this.documents.has(model.resource)) { + return; + } + + const key = model.resource.toString(); + const persisted = this.persisted.get(key); + this.persisted.delete(key); + + const document: ITrackedDocument = { + id: persisted?.id ?? generateUuid(), + createdAt: persisted?.createdAt ?? Date.now(), + edited: persisted?.edited ?? false, + model, + disposables: new DisposableStore(), + reverted: false, + length: 0, + lastChange: undefined, + lengthBeforeRevert: undefined, + language: model.getLanguageId() ?? 'plaintext', + editorId: undefined, + }; + this.documents.set(model.resource, document); + document.disposables.add(model.onDidRevert(() => { + document.reverted = true; + const changedByRevert = document.lastChange !== undefined && document.lastChange.versionId === model.textEditorModel?.getVersionId(); + document.lengthBeforeRevert = changedByRevert ? document.lastChange!.previousLength : document.length; + })); + + this.log({ + kind: 'created', + untitledDocumentId: document.id, + origin: model.origin ?? 'other', + restored: !!persisted, + language: document.language, + }); + + if (model.textEditorModel) { + this.onDidChangeLength(document, model.textEditorModel); + } + } + + /** + * Content can arrive without an edit, e.g. the initial value of chat's Insert into New File or of + * `openTextDocument({ content })`, so it goes through the same bookkeeping as edits. + */ + private onDidChangeLength(document: ITrackedDocument, textModel: ITextModel): void { + const previousLength = document.length; + document.length = textModel.getValueLength(); + document.lastChange = { versionId: textModel.getVersionId(), previousLength }; + if (!document.edited && document.length > 0) { + document.edited = true; + this.log({ kind: 'firstEdit', untitledDocumentId: document.id, msSinceCreated: Date.now() - document.createdAt }); + } + } + + private watchTextModel(model: ITextModel): void { + const disposables = new DisposableStore(); + this.textModelListeners.set(model, disposables); + disposables.add(model.onWillDispose(() => this.textModelListeners.deleteAndDispose(model))); + + disposables.add(model.onDidChangeLanguage(e => { + const document = this.documents.get(model.uri); + if (document) { + document.language = e.newLanguage; + } + + const source = e.source === ChangeLanguageAction.ID ? 'picker' : e.source === LanguageDetectionLanguageEventSource ? 'autoDetect' : 'other'; + if (model.uri.scheme !== Schemas.untitled && source !== 'picker') { + return; // only user choices for other documents, to avoid noise from extensions and configuration + } + + this.telemetryService.publicLog2('documentLanguageChanged', { + from: e.oldLanguage, + to: e.newLanguage, + source, + scheme: model.uri.scheme, + untitledDocumentId: document?.id, + }); + })); + + if (model.uri.scheme === Schemas.untitled) { + disposables.add(model.onDidChangeContent(() => { + const document = this.documents.get(model.uri); + if (document) { + this.onDidChangeLength(document, model); + } + })); + + const document = this.documents.get(model.uri); + if (document) { + document.language = model.getLanguageId(); + this.onDidChangeLength(document, model); + } + } + } + + private onDidActiveEditorChange(): void { + const editor = this.editorService.activeEditor; + const document = editor?.resource ? this.documents.get(editor.resource) : undefined; + if (document) { + document.editorId = editor?.editorId; + } + } + + private onWillDispose(model: IUntitledTextEditorModel): void { + if (this.shuttingDown) { + return; // documents that survive the shutdown continue after the reload, the others ended in onWillShutdown + } + + const document = this.documents.get(model.resource); + if (!document) { + return; + } + if (document.reverted) { + // Save As reverts the source before it reports the save, so the save gets a chance to end the document first + document.disposables.add(disposableTimeout(() => this.end(model.resource, this.getClosedOutcome(document)))); + } else { + this.end(model.resource, this.getClosedOutcome(document)); + } + } + + private onWillShutdown(): void { + this.persist(); + this.shuttingDown = true; + + for (const document of [...this.documents.values()]) { + if (!this.survivesShutdown(document)) { + this.end(document.model.resource, this.getClosedOutcome(document), undefined, true); + } + } + } + + /** + * Hot exit keeps dirty documents and, when enabled, also restores the editors of empty ones. + * Documents that were restored but never resolved still have their backup. + */ + private survivesShutdown(document: ITrackedDocument): boolean { + const resource = document.model.resource; + return document.model.isDirty() + || !document.model.isResolved() + || (this.filesConfigurationService.isHotExitEnabled && this.editorService.findEditors(resource).length > 0); + } + + private getClosedOutcome(document: ITrackedDocument): UntitledDocumentOutcome { + if (document.reverted) { + return 'closedDiscarded'; + } + return document.length === 0 ? 'closedEmpty' : 'other'; + } + + private end(resource: URI, outcome: UntitledDocumentOutcome, savedExt?: string, atShutdown?: boolean): void { + const document = this.documents.get(resource); + if (!document) { + return; + } + + this.documents.delete(resource); + document.disposables.dispose(); + + this.log({ + kind: 'ended', + untitledDocumentId: document.id, + outcome, + atShutdown: !!atShutdown, + savedExt, + language: document.language, + editorId: document.editorId, + msSinceCreated: Date.now() - document.createdAt, + sizeBucket: getSizeBucket(document.reverted ? document.lengthBeforeRevert ?? document.length : document.length), + }); + } + + private readPersisted(): Map { + const result = new Map(); + try { + const raw = JSON.parse(this.storageService.get(STORAGE_KEY, StorageScope.WORKSPACE, '{}')) as Record; + for (const [key, value] of Object.entries(raw)) { + if (typeof value?.id === 'string' && typeof value.createdAt === 'number') { + result.set(key, { id: value.id, createdAt: value.createdAt, edited: value.edited === true }); + } + } + } catch { + // ignore corrupt state + } + return result; + } + + /** + * Remembers the ids of documents that hot exit keeps across the reload. + */ + private persist(): void { + const value: Record = {}; + for (const document of this.documents.values()) { + if (this.survivesShutdown(document)) { + value[document.model.resource.toString()] = { id: document.id, createdAt: document.createdAt, edited: document.edited }; + } + } + if (Object.keys(value).length > 0) { + this.storageService.store(STORAGE_KEY, JSON.stringify(value), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } else { + this.storageService.remove(STORAGE_KEY, StorageScope.WORKSPACE); + } + } + + private log(event: Partial & Pick): void { + this.telemetryService.publicLog2('untitledDocument', { + origin: undefined, restored: undefined, language: undefined, editorId: undefined, msSinceCreated: undefined, + outcome: undefined, atShutdown: undefined, savedExt: undefined, sizeBucket: undefined, + ...event, + }); + } + + override dispose(): void { + for (const document of this.documents.values()) { + document.disposables.dispose(); + } + this.documents.clear(); + super.dispose(); + } +} diff --git a/src/vs/workbench/contrib/files/browser/views/explorerView.ts b/src/vs/workbench/contrib/files/browser/views/explorerView.ts index cf95db6aa79c..c527b89b472c 100644 --- a/src/vs/workbench/contrib/files/browser/views/explorerView.ts +++ b/src/vs/workbench/contrib/files/browser/views/explorerView.ts @@ -320,7 +320,7 @@ export class ExplorerView extends ViewPane implements IExplorerView { // Expand on drag over this.dragHandler = new DelayedDragHandler(container, () => this.setExpanded(true)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const titleElement = container.querySelector('.title') as HTMLElement; const setHeader = () => { titleElement.textContent = this.name; @@ -827,7 +827,7 @@ export class ExplorerView extends ViewPane implements IExplorerView { override getOptimalWidth(): number { const parentNode = this.tree.getHTMLElement(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const childNodes = ([] as HTMLElement[]).slice.call(parentNode.querySelectorAll('.explorer-item .label-name')); // select all file labels return DOM.getLargestChildWidth(parentNode, childNodes); diff --git a/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts b/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts index 6850bc08fead..7d006c35f08f 100644 --- a/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts +++ b/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts @@ -737,7 +737,7 @@ export class CompressedNavigationController implements ICompressedNavigationCont } private updateLabels(templateData: IFileTemplateData): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this._labels = Array.from(templateData.container.querySelectorAll('.label-name')); let parents = ''; for (let i = 0; i < this.labels.length; i++) { @@ -996,7 +996,7 @@ export class FilesRenderer implements ICompressibleTreeRenderer a')); return dom.getLargestChildWidth(parentNode, childNodes); diff --git a/src/vs/workbench/contrib/files/test/browser/newTabButtonActions.test.ts b/src/vs/workbench/contrib/files/test/browser/newTabButtonActions.test.ts new file mode 100644 index 000000000000..2b0a1071c77d --- /dev/null +++ b/src/vs/workbench/contrib/files/test/browser/newTabButtonActions.test.ts @@ -0,0 +1,90 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { Action2 } from '../../../../../platform/actions/common/actions.js'; +import { ContextKeyExpression, ContextKeyValue, IContext } from '../../../../../platform/contextkey/common/contextkey.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { NEW_TAB_BUTTON_SETTING } from '../../../../browser/parts/editor/newTabButton.js'; +import { IEditorCommandsContext } from '../../../../common/editor.js'; +import { IEditorGroup, IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; +import { IEditorResolverService, RegisteredEditorInfo } from '../../../../services/editor/common/editorResolverService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { INewUntitledTextEditorOptions, IUntitledTextEditorService } from '../../../../services/untitled/common/untitledTextEditorService.js'; +import { IUntitledTextEditorModel } from '../../../../services/untitled/common/untitledTextEditorModel.js'; +import { NewMarkdownDocumentFromNewTabButtonAction, NewUntitledFileFromNewTabButtonAction } from '../../browser/newTabButtonActions.js'; + +suite('New tab button entries', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const untitledResource = URI.from({ scheme: 'untitled', path: 'Untitled-1' }); + + /** Runs an entry as the new tab button of the second group does. */ + async function run(action: Action2, markdownEditorAvailable = false) { + const groups = [{ id: 1 }, { id: 2 }] as IEditorGroup[]; + let activeGroup = groups[0]; + const opened: { editor: unknown; group: number | undefined }[] = []; + const created: INewUntitledTextEditorOptions[] = []; + + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IEditorGroupsService, { + getGroup: (id: number) => groups.find(group => group.id === id), + get activeGroup() { return activeGroup; }, + activateGroup: (group: IEditorGroup | number) => activeGroup = group as IEditorGroup, + }); + instantiationService.stub(IEditorService, { + openEditor: async (editor: unknown, group?: unknown) => { + opened.push({ editor, group: (group as IEditorGroup | undefined)?.id }); + return undefined; + } + }); + instantiationService.stub(IUntitledTextEditorService, { + create: (options?: INewUntitledTextEditorOptions) => { + created.push(options ?? {}); + return { resource: untitledResource, resolve: async () => { } } as IUntitledTextEditorModel; + } + }); + instantiationService.stub(IEditorResolverService, { + getEditors: () => (markdownEditorAvailable ? [{ id: 'vscode.markdown.editor' }] : []) as RegisteredEditorInfo[] + }); + + await instantiationService.invokeFunction(accessor => action.run(accessor, { groupId: 2 } satisfies IEditorCommandsContext)); + + return { opened, created, activeGroup: activeGroup.id }; + } + + test('are shown only while the setting is on', () => { + const shown = (on: boolean) => [new NewUntitledFileFromNewTabButtonAction(), new NewMarkdownDocumentFromNewTabButtonAction()] + .filter(action => (action.desc.menu as { readonly when?: ContextKeyExpression }).when?.evaluate({ getValue: (key: string) => (key === `config.${NEW_TAB_BUTTON_SETTING}` ? on : undefined) as T | undefined } satisfies IContext)) + .map(action => action.desc.id); + + assert.deepStrictEqual({ off: shown(false), on: shown(true) }, { + off: [], + on: ['workbench.action.files.newUntitledFileFromNewTabButton', 'workbench.action.files.newMarkdownDocumentFromNewTabButton'], + }); + }); + + test('New Untitled Text File opens in the group of the button, with its origin', async () => { + assert.deepStrictEqual(await run(new NewUntitledFileFromNewTabButtonAction()), { + opened: [{ editor: { resource: undefined, untitledOrigin: 'newTabButton', options: { pinned: true, override: 'default' } }, group: 2 }], + created: [], + activeGroup: 2, + }); + }); + + test('New Markdown Document opens in the Markdown Editor when available, otherwise in the text editor', async () => { + const expected = (override: string) => ({ + opened: [{ editor: { resource: untitledResource, options: { pinned: true, override } }, group: 2 }], + created: [{ languageId: 'markdown', origin: 'newTabButton' }], + activeGroup: 2, + }); + + assert.deepStrictEqual(await run(new NewMarkdownDocumentFromNewTabButtonAction(), true), expected('vscode.markdown.editor')); + assert.deepStrictEqual(await run(new NewMarkdownDocumentFromNewTabButtonAction(), false), expected('default')); + }); +}); diff --git a/src/vs/workbench/contrib/files/test/browser/untitledDocumentTelemetry.test.ts b/src/vs/workbench/contrib/files/test/browser/untitledDocumentTelemetry.test.ts new file mode 100644 index 000000000000..ca6cfa38bff1 --- /dev/null +++ b/src/vs/workbench/contrib/files/test/browser/untitledDocumentTelemetry.test.ts @@ -0,0 +1,161 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { ChangeLanguageAction } from '../../../../browser/parts/editor/editorStatus.js'; +import { LanguageDetectionLanguageEventSource } from '../../../../services/languageDetection/common/languageDetectionWorkerService.js'; +import { UntitledTextEditorService } from '../../../../services/untitled/common/untitledTextEditorService.js'; +import { TestServiceAccessor, TestTextFileService, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { UntitledDocumentTelemetry } from '../../browser/untitledDocumentTelemetry.js'; + +suite('UntitledDocumentTelemetry', () => { + + const disposables = new DisposableStore(); + let instantiationService: TestInstantiationService; + let accessor: TestServiceAccessor; + let events: { name: string; data: Record }[]; + + setup(() => { + events = []; + instantiationService = workbenchInstantiationService(undefined, disposables); + instantiationService.stub(ITelemetryService, { ...NullTelemetryService, publicLog2: (name: string, data: Record) => events.push({ name, data }) } as unknown as ITelemetryService); + accessor = instantiationService.createInstance(TestServiceAccessor); + disposables.add(accessor.untitledTextEditorService as UntitledTextEditorService); + disposables.add(accessor.languageService.registerLanguage({ id: 'markdown' })); + }); + + teardown(() => disposables.clear()); + + function untitledEvents(kind?: string) { + return events.filter(e => e.name === 'untitledDocument' && (!kind || e.data.kind === kind)).map(e => e.data); + } + + test('created, first edit and saved share one id', async () => { + disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const model = disposables.add(accessor.untitledTextEditorService.create({ origin: 'newFileCommand' })); + await model.resolve(); + + model.textEditorModel!.setValue('# Notes'); + model.textEditorModel!.setValue('# Notes!'); + accessor.untitledTextEditorService.notifyDidSave(model.resource, URI.file('/notes.md')); + model.dispose(); + + const [created, firstEdit, ended, ...rest] = untitledEvents(); + assert.deepStrictEqual(rest, []); + assert.deepStrictEqual([created.kind, created.origin, created.restored, created.language], ['created', 'newFileCommand', false, 'plaintext']); + assert.strictEqual(firstEdit.kind, 'firstEdit'); + assert.deepStrictEqual([ended.kind, ended.outcome, ended.savedExt, ended.sizeBucket, ended.atShutdown], ['ended', 'saved', '.md', '<100', false]); + assert.ok(typeof created.untitledDocumentId === 'string'); + assert.strictEqual(firstEdit.untitledDocumentId, created.untitledDocumentId); + assert.strictEqual(ended.untitledDocumentId, created.untitledDocumentId); + }); + + test('closed documents end as empty or discarded', async () => { + disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const untouched = disposables.add(accessor.untitledTextEditorService.create()); + await untouched.resolve(); + const discarded = disposables.add(accessor.untitledTextEditorService.create()); + await discarded.resolve(); + + discarded.textEditorModel!.setValue('scratch'); + await discarded.revert(); + discarded.dispose(); + untouched.dispose(); + await timeout(0); + + assert.deepStrictEqual(untitledEvents('ended').map(e => [e.outcome, e.sizeBucket]), [['closedEmpty', '0'], ['closedDiscarded', '<100']]); + assert.strictEqual(untitledEvents('created')[0].origin, 'other'); + }); + + test('dirty documents keep their id across a shutdown, the others end', async () => { + const telemetry = instantiationService.createInstance(UntitledDocumentTelemetry); + const kept = accessor.untitledTextEditorService.create(); + await kept.resolve(); + kept.textEditorModel!.setValue('keep me'); + const empty = disposables.add(accessor.untitledTextEditorService.create()); + await empty.resolve(); + const keptId = telemetry.getUntitledDocumentId(kept.resource); + + accessor.lifecycleService.fireShutdown(); + kept.dispose(); + telemetry.dispose(); + + assert.deepStrictEqual(untitledEvents('ended').map(e => [e.outcome, e.atShutdown]), [['closedEmpty', true]]); + + const telemetryAfterReload = disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const restored = disposables.add(accessor.untitledTextEditorService.create({ untitledResource: kept.resource })); + + assert.strictEqual(telemetryAfterReload.getUntitledDocumentId(restored.resource), keptId); + assert.deepStrictEqual(untitledEvents('created').at(-1), { kind: 'created', untitledDocumentId: keptId, origin: 'other', restored: true, language: 'plaintext', editorId: undefined, msSinceCreated: undefined, outcome: undefined, atShutdown: undefined, savedExt: undefined, sizeBucket: undefined }); + }); + + test('Save As reports the saved size, although it empties the document before reporting the save', async () => { + disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const model = disposables.add(accessor.untitledTextEditorService.create()); + await model.resolve(); + model.textEditorModel!.setValue('x'.repeat(150)); + + // The shared test text file service is created before the code editor service that Save As needs + const textFileService = disposables.add(instantiationService.createInstance(TestTextFileService)); + await textFileService.saveAs(model.resource, URI.file('/test/notes.md')); + textFileService.files.get(URI.file('/test/notes.md'))?.dispose(); + model.dispose(); + await timeout(0); + + assert.deepStrictEqual(untitledEvents('ended').map(e => [e.outcome, e.savedExt, e.sizeBucket]), [['saved', '.md', '<1k']]); + }); + + test('initial content counts as the first edit', async () => { + disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const model = disposables.add(accessor.untitledTextEditorService.create({ initialValue: 'inserted from chat', origin: 'chat' })); + await model.resolve(); + await model.revert(); + model.dispose(); + await timeout(0); + + assert.deepStrictEqual(untitledEvents().map(e => e.kind), ['created', 'firstEdit', 'ended']); + assert.deepStrictEqual([untitledEvents('ended')[0].outcome, untitledEvents('ended')[0].sizeBucket], ['closedDiscarded', '<100']); + }); + + test('a document kept empty across a reload still reports its first edit', async () => { + const resource = URI.from({ scheme: 'untitled', path: 'Untitled-7' }); + instantiationService.invokeFunction(a => a.get(IStorageService)).store('untitledDocumentTelemetry.documents', JSON.stringify({ [resource.toString()]: { id: 'kept', createdAt: Date.now(), edited: false } }), StorageScope.WORKSPACE, StorageTarget.MACHINE); + disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + + const kept = disposables.add(accessor.untitledTextEditorService.create({ untitledResource: resource })); + await kept.resolve(); + kept.textEditorModel!.setValue('typed after the reload'); + + assert.deepStrictEqual(untitledEvents().map(e => [e.kind, e.untitledDocumentId, e.restored]), [['created', 'kept', true], ['firstEdit', 'kept', undefined]]); + }); + + test('language changes: any source for untitled documents, only the picker for other documents', async () => { + const telemetry = disposables.add(instantiationService.createInstance(UntitledDocumentTelemetry)); + const untitled = disposables.add(accessor.untitledTextEditorService.create()); + await untitled.resolve(); + const file = disposables.add(accessor.modelService.createModel('', null, URI.file('/notes.txt'))); + + untitled.textEditorModel!.setLanguage('markdown', LanguageDetectionLanguageEventSource); + file.setLanguage('markdown'); + file.setLanguage('plaintext', ChangeLanguageAction.ID); + + assert.deepStrictEqual(events.filter(e => e.name === 'documentLanguageChanged').map(e => e.data), [ + { from: 'plaintext', to: 'markdown', source: 'autoDetect', scheme: 'untitled', untitledDocumentId: telemetry.getUntitledDocumentId(untitled.resource) }, + { from: 'markdown', to: 'plaintext', source: 'picker', scheme: 'file', untitledDocumentId: undefined }, + ]); + untitled.dispose(); + assert.strictEqual(untitledEvents('ended')[0].language, 'markdown'); + }); + + ensureNoDisposablesAreLeakedInTestSuite(); +}); diff --git a/src/vs/workbench/contrib/format/test/browser/formatActionsMultiple.test.ts b/src/vs/workbench/contrib/format/test/browser/formatActionsMultiple.test.ts index c829fd675dc5..b217c4348ad1 100644 --- a/src/vs/workbench/contrib/format/test/browser/formatActionsMultiple.test.ts +++ b/src/vs/workbench/contrib/format/test/browser/formatActionsMultiple.test.ts @@ -4,11 +4,21 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { DocumentFormattingEditProvider } from '../../../../../editor/common/languages.js'; +import { Range } from '../../../../../editor/common/core/range.js'; +import { Handler } from '../../../../../editor/common/editorCommon.js'; +import { DocumentFormattingEditProvider, TextEdit } from '../../../../../editor/common/languages.js'; +import { ITextModel } from '../../../../../editor/common/model.js'; +import { IEditorWorkerService } from '../../../../../editor/common/services/editorWorker.js'; import { ILanguageFeaturesService } from '../../../../../editor/common/services/languageFeatures.js'; -import { withAsyncTestCodeEditor } from '../../../../../editor/test/browser/testCodeEditor.js'; +import { FormatOnType } from '../../../../../editor/contrib/format/browser/formatActions.js'; +import { createTestCodeEditor, ITestCodeEditor, withAsyncTestCodeEditor } from '../../../../../editor/test/browser/testCodeEditor.js'; +import { TestEditorWorkerService } from '../../../../../editor/test/common/services/testEditorWorkerService.js'; +import { createTextModel } from '../../../../../editor/test/common/testTextModel.js'; import { IAccessibilitySignalService } from '../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.js'; import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; @@ -57,3 +67,114 @@ suite('Format Actions Multiple', () => { assert.deepStrictEqual(invokedFormatters, ['publisher.requested']); }); }); + +suite('Format On Type', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let editor: ITestCodeEditor; + let originalModel: ITextModel; + let nextModel: ITextModel; + let response: DeferredPromise; + let token: CancellationToken; + + setup(() => { + response = new DeferredPromise(); + token = CancellationToken.None; + const serviceCollection = new ServiceCollection( + [IEditorWorkerService, new class extends TestEditorWorkerService { + override async computeMoreMinimalEdits(_resource: URI, edits: TextEdit[] | null | undefined) { + return edits ?? undefined; + } + }], + [IAccessibilitySignalService, new class extends mock() { + override async playSignal(): Promise { } + }], + ); + originalModel = store.add(createTextModel('const x=1\nnext')); + nextModel = store.add(createTextModel('const value=2;')); + editor = store.add(createTestCodeEditor(originalModel, { formatOnType: true, serviceCollection })); + editor.registerDisposable(editor.invokeWithinContext(accessor => accessor.get(ILanguageFeaturesService).onTypeFormattingEditProvider.register('*', { + autoFormatTriggerCharacters: [';'], + provideOnTypeFormattingEdits: (_model, _position, _ch, _options, requestToken) => { + token = requestToken; + return response.p; + }, + }))); + editor.registerAndInstantiateContribution(FormatOnType.ID, FormatOnType); + editor.setPosition({ lineNumber: 1, column: 10 }); + editor.trigger('keyboard', Handler.Type, { text: ';' }); + }); + + async function completeFormatting() { + const cancelled = token.isCancellationRequested; + await response.complete([ + { range: new Range(1, 8, 1, 8), text: ' ' }, + { range: new Range(1, 9, 1, 9), text: ' ' }, + ]); + await timeout(0); + return { original: originalModel.getValue(), next: nextModel.getValue(), cancelled }; + } + + test('applies pending edits when the model is unchanged', async () => { + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x = 1;\nnext', + next: 'const value=2;', + cancelled: false, + }); + }); + + test('does not apply pending edits to a different model', async () => { + editor.setModel(nextModel); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x=1;\nnext', + next: 'const value=2;', + cancelled: true, + }); + }); + + test('does not apply pending edits after switching back to the original model', async () => { + editor.setModel(nextModel); + originalModel.applyEdits([{ range: new Range(1, 7, 1, 8), text: 'value' }]); + editor.setModel(originalModel); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const value=1;\nnext', + next: 'const value=2;', + cancelled: true, + }); + }); + + test('cancels pending edits when the editor is disposed', async () => { + editor.dispose(); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x=1;\nnext', + next: 'const value=2;', + cancelled: true, + }); + }); + + test('cancels pending edits when format on type is disabled', async () => { + editor.updateOptions({ formatOnType: false }); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x=1;\nnext', + next: 'const value=2;', + cancelled: true, + }); + }); + + test('cancels pending edits after typing on the trigger line', async () => { + editor.trigger('keyboard', Handler.Type, { text: ' ' }); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x=1; \nnext', + next: 'const value=2;', + cancelled: true, + }); + }); + + test('preserves pending edits after changes below the trigger line', async () => { + editor.executeEdits('test', [{ range: new Range(2, 1, 2, 5), text: 'changed' }]); + assert.deepStrictEqual(await completeFormatting(), { + original: 'const x = 1;\nchanged', + next: 'const value=2;', + cancelled: false, + }); + }); +}); diff --git a/src/vs/workbench/contrib/github/test/browser/githubResourceDetails.test.ts b/src/vs/workbench/contrib/github/test/browser/githubResourceDetails.test.ts index 74f0ea67b8f0..70e08f87a510 100644 --- a/src/vs/workbench/contrib/github/test/browser/githubResourceDetails.test.ts +++ b/src/vs/workbench/contrib/github/test/browser/githubResourceDetails.test.ts @@ -195,7 +195,7 @@ suite('GitHubResourceDetails', () => { const target = { owner: 'microsoft', repo: 'vscode', number: 1 }; const issue: IGitHubIssueHoverModel = { title: 'Live title', body: '', state: 'open', author: { login: 'author' } }; const cases = [ - { state: 'open', stateReason: undefined, icon: 'issue-opened', color: 'charts.green' }, + { state: 'open', stateReason: undefined, icon: 'issues', color: 'charts.green' }, { state: 'closed', stateReason: 'completed', icon: 'issue-closed', color: 'charts.purple' }, { state: 'closed', stateReason: 'not_planned', icon: 'issue-closed', color: 'descriptionForeground' }, { state: 'closed', stateReason: 'duplicate', icon: 'issue-closed', color: 'descriptionForeground' }, diff --git a/src/vs/workbench/contrib/inlineChat/browser/inlineChatActions.ts b/src/vs/workbench/contrib/inlineChat/browser/inlineChatActions.ts index 7e5d8f63136e..3b3ba9be48a3 100644 --- a/src/vs/workbench/contrib/inlineChat/browser/inlineChatActions.ts +++ b/src/vs/workbench/contrib/inlineChat/browser/inlineChatActions.ts @@ -362,12 +362,13 @@ export class ContinueInlineChatInChatViewAction extends AbstractInlineChatAction id: 'inlineChat2.continueInChat', title: localize2('continueInChat', "Ask in Chat"), icon: Codicon.chatSparkle, - precondition: ContextKeyExpr.and(CTX_INLINE_CHAT_VISIBLE, CTX_INLINE_CHAT_TERMINATED), + // It continues in local chat, which the Agents view does not show + precondition: ContextKeyExpr.and(CTX_INLINE_CHAT_VISIBLE, CTX_INLINE_CHAT_TERMINATED, ChatContextKeys.agentsViewActive.negate()), menu: [{ id: MenuId.ChatEditorInlineExecute, group: 'navigation', order: 2, - when: CTX_INLINE_CHAT_TERMINATED + when: ContextKeyExpr.and(CTX_INLINE_CHAT_TERMINATED, ChatContextKeys.agentsViewActive.negate()) }] }); } diff --git a/src/vs/workbench/contrib/issue/browser/baseIssueReporterService.ts b/src/vs/workbench/contrib/issue/browser/baseIssueReporterService.ts index b7734ab78769..d3c6e8fa46b9 100644 --- a/src/vs/workbench/contrib/issue/browser/baseIssueReporterService.ts +++ b/src/vs/workbench/contrib/issue/browser/baseIssueReporterService.ts @@ -8,10 +8,11 @@ import { Button, ButtonWithDropdown, unthemedButtonStyles } from '../../../../ba import { renderIcon } from '../../../../base/browser/ui/iconLabel/iconLabels.js'; import { Delayer, RunOnceScheduler } from '../../../../base/common/async.js'; import { VSBuffer } from '../../../../base/common/buffer.js'; +import { abortOnDispose } from '../../../../base/common/cancellation.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { groupBy } from '../../../../base/common/collections.js'; import { debounce } from '../../../../base/common/decorators.js'; -import { CancellationError } from '../../../../base/common/errors.js'; +import { CancellationError, isCancellationError } from '../../../../base/common/errors.js'; import { Disposable, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../base/common/network.js'; import { isLinuxSnap, isMacintosh } from '../../../../base/common/platform.js'; @@ -24,13 +25,15 @@ import { Action } from '../../../../base/common/actions.js'; import { localize } from '../../../../nls.js'; import { IFileDialogService } from '../../../../platform/dialogs/common/dialogs.js'; import { IFileService } from '../../../../platform/files/common/files.js'; +import { withGitHubCredentialDeadline } from '../../../../platform/github/common/githubCredentialService.js'; +import { GitHubRequestError, isEqualAuthorization } from '../../../../platform/github/common/githubTypes.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { getIconsStyleSheet } from '../../../../platform/theme/browser/iconsStyleSheet.js'; import { IThemeService } from '../../../../platform/theme/common/themeService.js'; import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; import { IIssueFormService, ISimilarIssue, IssueReporterData, IssueReporterExtensionData, IssueType } from '../common/issue.js'; -import { normalizeGitHubUrl } from '../common/issueReporterUtil.js'; +import { getGitHubAuthorization, normalizeGitHubUrl } from '../common/issueReporterUtil.js'; import { IssueReporterModel, IssueReporterData as IssueReporterModelData } from './issueReporterModel.js'; import { IAuthenticationService } from '../../../services/authentication/common/authentication.js'; @@ -71,6 +74,7 @@ export class BaseIssueReporterService extends Disposable { private privateAction: Action; private readonly similarIssueSearch = this._register(new MutableDisposable()); private similarIssueSearchGeneration = 0; + private readonly disposeSignal = abortOnDispose(this._store); constructor( public disableExtensions: boolean, @@ -108,13 +112,23 @@ export class BaseIssueReporterService extends Disposable { })); this._register(this.authenticationService.onDidChangeSessions(async () => { + const authorization = this.data.githubAuthorization; + // A caller-supplied token without a known session must not switch to another account. + if (!authorization && this.data.githubAccessToken) { + return; + } const previousAuthState = !!this.data.githubAccessToken; let githubAccessToken = ''; try { const githubSessions = await this.authenticationService.getSessions('github'); - const potentialSessions = githubSessions.filter(session => session.scopes.includes('repo')); - githubAccessToken = potentialSessions[0]?.accessToken; + const session = githubSessions.find(session => authorization + ? isEqualAuthorization(authorization, getGitHubAuthorization(session)) + : session.scopes.includes('repo')); + githubAccessToken = session?.accessToken ?? ''; + if (session) { + this.data.githubAuthorization ??= getGitHubAuthorization(session); + } } catch (e) { // Ignore } @@ -164,7 +178,7 @@ export class BaseIssueReporterService extends Disposable { const issueTitle = data.issueTitle; if (issueTitle) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueTitleElement = this.getElementById('issue-title'); if (issueTitleElement) { issueTitleElement.value = issueTitle; @@ -173,7 +187,7 @@ export class BaseIssueReporterService extends Disposable { const issueBody = data.issueBody; if (issueBody) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const description = this.getElementById('description'); if (description) { description.value = issueBody; @@ -182,7 +196,7 @@ export class BaseIssueReporterService extends Disposable { } if (this.window.document.documentElement.lang !== 'en') { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax show(this.getElementById('english')); } @@ -207,7 +221,7 @@ export class BaseIssueReporterService extends Disposable { } // initialize the reporting button(s) - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueReporterElement = this.getElementById('issue-reporter'); if (issueReporterElement) { this.updateButtonStates(); @@ -221,18 +235,18 @@ export class BaseIssueReporterService extends Disposable { setInitialFocus() { const { fileOnExtension } = this.issueReporterModel.getData(); if (fileOnExtension) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueTitle = this.window.document.getElementById('issue-title'); issueTitle?.focus(); } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueType = this.window.document.getElementById('issue-type'); issueType?.focus(); } } public updateButtonStates() { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueReporterElement = this.getElementById('issue-reporter'); if (!issueReporterElement) { // shouldn't occur -- throw? @@ -241,7 +255,7 @@ export class BaseIssueReporterService extends Disposable { // public elements section - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let publicElements = this.getElementById('public-elements'); if (!publicElements) { publicElements = document.createElement('div'); @@ -254,7 +268,7 @@ export class BaseIssueReporterService extends Disposable { // private filing section - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let internalElements = this.getElementById('internal-elements'); if (!internalElements) { internalElements = document.createElement('div'); @@ -263,7 +277,7 @@ export class BaseIssueReporterService extends Disposable { internalElements.classList.add('hidden'); issueReporterElement.appendChild(internalElements); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let filingRow = this.getElementById('internal-top-row'); if (!filingRow) { filingRow = document.createElement('div'); @@ -277,7 +291,7 @@ export class BaseIssueReporterService extends Disposable { } private updateInternalFilingNote(container: HTMLElement) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let filingNote = this.getElementById('internal-preview-message'); if (!filingNote) { filingNote = document.createElement('span'); @@ -290,7 +304,7 @@ export class BaseIssueReporterService extends Disposable { } private updatePublicGithubButton(container: HTMLElement): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueReporterElement = this.getElementById('issue-reporter'); if (!issueReporterElement) { return; @@ -335,7 +349,7 @@ export class BaseIssueReporterService extends Disposable { } // make sure that the repo link is after the button - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const repoLink = this.getElementById('show-repo-name'); if (repoLink) { container.insertBefore(this.publicGithubButton.element, repoLink); @@ -343,7 +357,7 @@ export class BaseIssueReporterService extends Disposable { } private updatePublicRepoLink(container: HTMLElement): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let issueRepoName = this.getElementById('show-repo-name') as HTMLAnchorElement; if (!issueRepoName) { issueRepoName = document.createElement('a'); @@ -378,7 +392,7 @@ export class BaseIssueReporterService extends Disposable { } private updateInternalGithubButton(container: HTMLElement): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueReporterElement = this.getElementById('issue-reporter'); if (!issueReporterElement) { return; @@ -404,7 +418,7 @@ export class BaseIssueReporterService extends Disposable { } private updateInternalElementsVisibility(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const container = this.getElementById('internal-elements'); if (!container) { // shouldn't happen @@ -448,7 +462,7 @@ export class BaseIssueReporterService extends Disposable { const spinnerIcon = renderIcon(ThemeIcon.modify(Codicon.loading, 'spin')); buttonEl.prepend(spinnerIcon); } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const spinnerEl = buttonEl.querySelector('.codicon-loading'); spinnerEl?.remove(); if (this.preSubmitButtonLabel !== undefined) { @@ -479,7 +493,7 @@ export class BaseIssueReporterService extends Disposable { this.issueReporterModel.update({ numberOfThemeExtesions, enabledNonThemeExtesions: nonThemes, allExtensions: installedExtensions }); this.updateExtensionTable(nonThemes ?? [], numberOfThemeExtesions); if (this.disableExtensions || installedExtensions.length === 0) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax (this.getElementById('disableExtensions')).disabled = true; } @@ -522,7 +536,7 @@ export class BaseIssueReporterService extends Disposable { }, extension.name); }; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionsSelector = this.getElementById('extension-selector'); if (extensionsSelector) { const { selectedExtension } = this.issueReporterModel.getData(); @@ -606,7 +620,7 @@ export class BaseIssueReporterService extends Disposable { } private updateAcknowledgementState() { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const acknowledgementCheckbox = this.getElementById('includeAcknowledgement'); if (acknowledgementCheckbox) { this.acknowledged = acknowledgementCheckbox.checked; @@ -627,7 +641,7 @@ export class BaseIssueReporterService extends Disposable { this.updateAcknowledgementState(); }); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const showInfoElements = this.window.document.getElementsByClassName('showInfo'); for (let i = 0; i < showInfoElements.length; i++) { const showInfo = showInfoElements.item(i)!; @@ -650,7 +664,7 @@ export class BaseIssueReporterService extends Disposable { this.addEventListener('issue-source', 'change', (e: Event) => { const value = (e.target).value; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const problemSourceHelpText = this.getElementById('problem-source-help-text')!; if (value === '') { this.issueReporterModel.update({ fileOnExtension: undefined }); @@ -662,7 +676,7 @@ export class BaseIssueReporterService extends Disposable { hide(problemSourceHelpText); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTextArea = this.getElementById('issue-title'); if (value === IssueSource.VSCode) { descriptionTextArea.placeholder = localize('vscodePlaceholder', "E.g Workbench is missing problems panel"); @@ -686,7 +700,7 @@ export class BaseIssueReporterService extends Disposable { this.issueReporterModel.update({ fileOnExtension, fileOnMarketplace, fileOnProduct }); this.render(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const title = (this.getElementById('issue-title')).value; this.searchIssues(title, fileOnExtension, fileOnMarketplace); }); @@ -696,14 +710,14 @@ export class BaseIssueReporterService extends Disposable { this.issueReporterModel.update({ issueDescription }); if (this.issueReporterModel.fileOnExtension() === false && !this.issueReporterModel.getData().fileOnMarketplace) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const title = (this.getElementById('issue-title')).value; this.searchVSCodeIssues(title, issueDescription); } }); this.addEventListener('issue-title', 'input', _ => { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const titleElement = this.getElementById('issue-title') as HTMLInputElement; if (titleElement) { const title = titleElement.value; @@ -713,7 +727,7 @@ export class BaseIssueReporterService extends Disposable { this.addEventListener('issue-title', 'input', (e: Event) => { const title = (e.target).value; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const lengthValidationMessage = this.getElementById('issue-title-length-validation-error'); const issueUrl = this.getIssueUrl(); if (title && this.getIssueUrlWithTitle(title, issueUrl).length > MAX_URL_LENGTH) { @@ -721,7 +735,7 @@ export class BaseIssueReporterService extends Disposable { } else { hide(lengthValidationMessage); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueSource = this.getElementById('issue-source'); if (!issueSource || issueSource.value === '') { return; @@ -770,7 +784,7 @@ export class BaseIssueReporterService extends Disposable { e.stopPropagation(); e.preventDefault(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueTitle = (this.getElementById('issue-title'))!.value; const { issueDescription } = this.issueReporterModel.getData(); if (!this.hasBeenSubmitted && (issueTitle || issueDescription)) { @@ -909,7 +923,7 @@ export class BaseIssueReporterService extends Disposable { public clearSearchResults(): void { this.similarIssueSearchGeneration++; this.similarIssueSearch.clear(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const similarIssues = this.getElementById('similar-issues')!; similarIssues.innerText = ''; this.numberOfSearchResultsDisplayed = 0; @@ -922,7 +936,7 @@ export class BaseIssueReporterService extends Disposable { } const controller = new AbortController(); this.similarIssueSearch.value = toDisposable(() => controller.abort()); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const similarIssues = this.getElementById('similar-issues')!; void this.issueFormService.searchGitHubIssues(repo, title, controller.signal).then(results => { @@ -974,7 +988,7 @@ export class BaseIssueReporterService extends Disposable { } private displaySearchResults(results: readonly ISimilarIssue[]) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const similarIssues = this.getElementById('similar-issues')!; if (results.length) { const issues = $('div.issues-container'); @@ -1021,7 +1035,7 @@ export class BaseIssueReporterService extends Disposable { private setUpTypes(): void { const makeOption = (issueType: IssueType, description: string) => $('option', { 'value': issueType.valueOf() }, escape(description)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const typeSelect = this.getElementById('issue-type')! as HTMLSelectElement; const { issueType } = this.issueReporterModel.getData(); reset(typeSelect, @@ -1045,7 +1059,7 @@ export class BaseIssueReporterService extends Disposable { } public setSourceOptions(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const sourceSelect = this.getElementById('issue-source')! as HTMLSelectElement; const { issueType, fileOnExtension, selectedExtension, fileOnMarketplace, fileOnProduct } = this.issueReporterModel.getData(); let selected = sourceSelect.selectedIndex; @@ -1077,7 +1091,7 @@ export class BaseIssueReporterService extends Disposable { sourceSelect.selectedIndex = selected; } else { sourceSelect.selectedIndex = 0; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax hide(this.getElementById('problem-source-help-text')); } } @@ -1085,37 +1099,37 @@ export class BaseIssueReporterService extends Disposable { public async renderBlocks(): Promise { // Depending on Issue Type, we render different blocks and text const { issueType, fileOnExtension, fileOnMarketplace, selectedExtension } = this.issueReporterModel.getData(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const blockContainer = this.getElementById('block-container'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const systemBlock = this.window.document.querySelector('.block-system'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const processBlock = this.window.document.querySelector('.block-process'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const workspaceBlock = this.window.document.querySelector('.block-workspace'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionsBlock = this.window.document.querySelector('.block-extensions'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const experimentsBlock = this.window.document.querySelector('.block-experiments'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataBlock = this.window.document.querySelector('.block-extension-data'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const problemSource = this.getElementById('problem-source')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTitle = this.getElementById('issue-description-label')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionSubtitle = this.getElementById('issue-description-subtitle')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionSelector = this.getElementById('extension-selection')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const downloadExtensionDataLink = this.getElementById('extension-data-download')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const titleTextArea = this.getElementById('issue-title-container')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTextArea = this.getElementById('description')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataTextArea = this.getElementById('extension-data')!; // Hide all by default @@ -1228,11 +1242,11 @@ export class BaseIssueReporterService extends Disposable { } public validateInput(inputId: string): boolean { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const inputElement = (this.getElementById(inputId)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const inputValidationMessage = this.getElementById(`${inputId}-empty-error`); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionShortMessage = this.getElementById(`description-short-error`); if (inputId === 'description' && this.nonGitHubIssueUrl && this.data.extensionId) { return true; @@ -1270,27 +1284,26 @@ export class BaseIssueReporterService extends Disposable { } public async submitToGitHub(issueTitle: string, issueBody: string, gitHubDetails: { owner: string; repositoryName: string }): Promise { - const url = `https://api.github.com/repos/${gitHubDetails.owner}/${gitHubDetails.repositoryName}/issues`; - const init = { - method: 'POST', - body: JSON.stringify({ - title: issueTitle, - body: issueBody - }), - headers: new Headers({ - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.data.githubAccessToken}`, - 'User-Agent': 'request' - }) - }; - - const response = await fetch(url, init); - if (!response.ok) { - console.error('Invalid GitHub URL provided.'); - return false; + const authorization = this.data.githubAuthorization; + let issueUrl: string; + try { + const sessions = await withGitHubCredentialDeadline(this.disposeSignal, () => this.authenticationService.getSessions('github', [], { silent: true }, true)); + if (!authorization || !sessions.some(session => isEqualAuthorization(authorization, getGitHubAuthorization(session)))) { + throw new GitHubRequestError(localize('issueReporter.githubSessionUnavailable', "The GitHub session selected for this issue report is no longer available. Sign in again or preview the report on GitHub."), 'authentication'); + } + issueUrl = await this.issueFormService.createGitHubIssue(authorization, { owner: gitHubDetails.owner, repo: gitHubDetails.repositoryName }, { title: issueTitle, body: issueBody }, this.disposeSignal); + this.disposeSignal.throwIfAborted(); + } catch (error) { + this.disposeSignal.throwIfAborted(); + if (!isCancellationError(error)) { + this.logService.error('[IssueReporter] Failed to create GitHub issue', error); + } + if (error instanceof GitHubRequestError && error.statusCode !== undefined && error.statusCode >= 400) { + return false; + } + throw error; } - const result = await response.json(); - await this.openLink(result.html_url); + await this.openLink(issueUrl); this.close(); return true; } @@ -1309,7 +1322,7 @@ export class BaseIssueReporterService extends Disposable { if (!this.validateInputs()) { // If inputs are invalid, set focus to the first one and add listeners on them // to detect further changes - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const invalidInput = this.window.document.getElementsByClassName('invalid-input'); if (invalidInput.length) { (invalidInput[0]).focus(); @@ -1338,7 +1351,7 @@ export class BaseIssueReporterService extends Disposable { this.hasBeenSubmitted = true; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueTitle = (this.getElementById('issue-title')).value; const issueBody = this.issueReporterModel.serialize(); @@ -1357,7 +1370,7 @@ export class BaseIssueReporterService extends Disposable { return this.submitToGitHub(issueTitle, issueBody, gitHubDetails); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const baseUrl = this.getIssueUrlWithTitle((this.getElementById('issue-title')).value, issueUrl); let url = baseUrl + `&body=${encodeURIComponent(issueBody)}`; @@ -1478,7 +1491,7 @@ export class BaseIssueReporterService extends Disposable { // uses this.configuuration.data to ensure that data is coming from `openReporter` command. const template = this.data.issueBody; if (template) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTextArea = this.getElementById('description')!; const descriptionText = (descriptionTextArea as HTMLTextAreaElement).value; if (descriptionText === '' || !descriptionText.includes(template.toString())) { @@ -1492,7 +1505,7 @@ export class BaseIssueReporterService extends Disposable { if (data) { this.issueReporterModel.update({ extensionData: data }); extension.data = data; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataBlock = this.window.document.querySelector('.block-extension-data')!; show(extensionDataBlock); this.renderBlocks(); @@ -1505,7 +1518,7 @@ export class BaseIssueReporterService extends Disposable { } this.validateSelectedExtension(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const title = (this.getElementById('issue-title')).value; this.searchExtensionIssues(title); @@ -1514,9 +1527,9 @@ export class BaseIssueReporterService extends Disposable { } public validateSelectedExtension(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionValidationMessage = this.getElementById('extension-selection-validation-error')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionValidationNoUrlsMessage = this.getElementById('extension-selection-validation-error-no-url')!; hide(extensionValidationMessage); hide(extensionValidationNoUrlsMessage); @@ -1546,15 +1559,15 @@ export class BaseIssueReporterService extends Disposable { this.loadingExtensionData = true; this.updateButtonStates(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataCaption = this.getElementById('extension-id')!; hide(extensionDataCaption); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataCaption2 = Array.from(this.window.document.querySelectorAll('.ext-parens')); extensionDataCaption2.forEach(extensionDataCaption2 => hide(extensionDataCaption2)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const showLoading = this.getElementById('ext-loading')!; show(showLoading); while (showLoading.firstChild) { @@ -1570,15 +1583,15 @@ export class BaseIssueReporterService extends Disposable { this.loadingExtensionData = false; this.updateButtonStates(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataCaption = this.getElementById('extension-id')!; show(extensionDataCaption); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionDataCaption2 = Array.from(this.window.document.querySelectorAll('.ext-parens')); extensionDataCaption2.forEach(extensionDataCaption2 => show(extensionDataCaption2)); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const hideLoading = this.getElementById('ext-loading')!; hide(hideLoading); if (hideLoading.firstChild) { @@ -1588,14 +1601,14 @@ export class BaseIssueReporterService extends Disposable { } private setExtensionValidationMessage(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionValidationMessage = this.getElementById('extension-selection-validation-error')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const extensionValidationNoUrlsMessage = this.getElementById('extension-selection-validation-error-no-url')!; const bugsUrl = this.getExtensionBugsUrl(); if (bugsUrl) { show(extensionValidationMessage); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const link = this.getElementById('extensionBugsLink')!; link.textContent = bugsUrl; return; @@ -1604,7 +1617,7 @@ export class BaseIssueReporterService extends Disposable { const extensionUrl = this.getExtensionRepositoryUrl(); if (extensionUrl) { show(extensionValidationMessage); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const link = this.getElementById('extensionBugsLink'); link!.textContent = extensionUrl; return; @@ -1614,7 +1627,7 @@ export class BaseIssueReporterService extends Disposable { } private updateProcessInfo(state: IssueReporterModelData) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const target = this.window.document.querySelector('.block-process .block-info') as HTMLElement; if (target) { reset(target, $('code', undefined, state.processInfo ?? '')); @@ -1622,12 +1635,12 @@ export class BaseIssueReporterService extends Disposable { } private updateWorkspaceInfo(state: IssueReporterModelData) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.window.document.querySelector('.block-workspace .block-info code')!.textContent = '\n' + state.workspaceInfo; } public updateExtensionTable(extensions: IssueReporterExtensionData[], numThemeExtensions: number): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const target = this.window.document.querySelector('.block-extensions .block-info'); if (target) { if (this.disableExtensions) { @@ -1679,7 +1692,7 @@ export class BaseIssueReporterService extends Disposable { } public getElementById(elementId: string): T | undefined { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = this.window.document.getElementById(elementId) as T | undefined; if (element) { return element; @@ -1689,7 +1702,7 @@ export class BaseIssueReporterService extends Disposable { } public addEventListener(elementId: string, eventType: string, handler: (event: Event) => void): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = this.getElementById(elementId); element?.addEventListener(eventType, handler); } diff --git a/src/vs/workbench/contrib/issue/browser/issueFormService.ts b/src/vs/workbench/contrib/issue/browser/issueFormService.ts index 0a8e27971d0b..86378c3d0c59 100644 --- a/src/vs/workbench/contrib/issue/browser/issueFormService.ts +++ b/src/vs/workbench/contrib/issue/browser/issueFormService.ts @@ -14,6 +14,9 @@ import { IClipboardService } from '../../../../platform/clipboard/common/clipboa import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; import { ExtensionIdentifier, ExtensionIdentifierSet } from '../../../../platform/extensions/common/extensions.js'; +import { RepositoryRef } from '../../../../platform/github/common/client/types.js'; +import { CreateIssueRequest } from '../../../../platform/github/common/core/issues.js'; +import { GitHubAuthorizationContext } from '../../../../platform/github/common/githubTypes.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; @@ -143,6 +146,21 @@ export class IssueFormService extends Disposable implements IIssueFormService { } } + async createGitHubIssue(authorization: GitHubAuthorizationContext, repository: RepositoryRef, request: CreateIssueRequest, signal: AbortSignal): Promise { + signal = AbortSignal.any([signal, this.disposeSignal]); + signal.throwIfAborted(); + const lifetime = new DisposableStore(); + try { + const client = lifetime.add(await this.gitHubService.acquireAccountApiClient(authorization, signal)); + signal.throwIfAborted(); + const issue = await client.issues.create(repository, request, signal, { caller: 'issueReporter', priority: 'mutation' }); + signal.throwIfAborted(); + return issue.html_url; + } finally { + lifetime.dispose(); + } + } + async openReporter(data: IssueReporterData): Promise { if (this.hasToReload(data)) { return; diff --git a/src/vs/workbench/contrib/issue/browser/issueReporterOverlay.ts b/src/vs/workbench/contrib/issue/browser/issueReporterOverlay.ts index 6d17d74cce6f..b11e0469d848 100644 --- a/src/vs/workbench/contrib/issue/browser/issueReporterOverlay.ts +++ b/src/vs/workbench/contrib/issue/browser/issueReporterOverlay.ts @@ -326,7 +326,7 @@ export class IssueReporterOverlay { // Mount inside .monaco-workbench so VS Code's color theme CSS vars // (--vscode-debugToolBar-background, etc.) cascade and the bar matches the // active theme. body is outside that scope and the vars wouldn't resolve. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const workbench = targetWindow.document.querySelector('.monaco-workbench') as HTMLElement | null; const mountTarget = workbench ?? targetWindow.document.body; @@ -1589,7 +1589,7 @@ export class IssueReporterOverlay { if (state) { card.classList.add(`upload-${state}`); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const overlay = card.querySelector('.review-progress-overlay') as HTMLElement | null; if (!overlay) { return; @@ -2342,7 +2342,7 @@ ${rows.map(row => row.map(value => this.escapeMarkdownTableCell(value ?? '')).jo // Mount inside .monaco-workbench so theme CSS vars cascade. Fall back to // document.body when no workbench root is present (shouldn't happen in // practice but keeps the bar visible regardless). - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const workbench = targetWindow.document.querySelector('.monaco-workbench') as HTMLElement | null; const mountTarget = workbench ?? targetWindow.document.body; if (this.floatingBar.parentElement !== mountTarget) { @@ -2438,7 +2438,7 @@ ${rows.map(row => row.map(value => this.escapeMarkdownTableCell(value ?? '')).jo showCloseButton(): void { // Add close button next to the existing preview button const nav = this.previewButton.element.parentElement; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax if (nav && !nav.querySelector('.wizard-close-btn')) { this.closeButton = this.disposables.add(new Button(nav, { ...defaultButtonStyles, secondary: true })); this.closeButton.label = localize('closeTab', "Close"); diff --git a/src/vs/workbench/contrib/issue/browser/issueReporterRepositoryPicker.ts b/src/vs/workbench/contrib/issue/browser/issueReporterRepositoryPicker.ts index 362a7284d06b..e54e05fd2225 100644 --- a/src/vs/workbench/contrib/issue/browser/issueReporterRepositoryPicker.ts +++ b/src/vs/workbench/contrib/issue/browser/issueReporterRepositoryPicker.ts @@ -70,7 +70,7 @@ export function renderIssueReporterRepositoryPicker( const action = store.add(new Action(`issueReporter.repository.${index}`, name, undefined, true, () => { if (!store.isDisposed) { onDidSelect(name); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax container.querySelector('.issue-reporter-repository-picker')?.focus(); } })); diff --git a/src/vs/workbench/contrib/issue/browser/issueReporterService.ts b/src/vs/workbench/contrib/issue/browser/issueReporterService.ts index 9f14e20b5ce8..8f6f126fef26 100644 --- a/src/vs/workbench/contrib/issue/browser/issueReporterService.ts +++ b/src/vs/workbench/contrib/issue/browser/issueReporterService.ts @@ -39,7 +39,7 @@ export class IssueWebReporter extends BaseIssueReporterService { ) { super(disableExtensions, data, os, product, window, true, undefined, issueFormService, themeService, fileService, fileDialogService, contextMenuService, authenticationService, openerService, logService); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const target = this.window.document.querySelector('.block-system .block-info'); const webInfo = this.window.navigator.userAgent; @@ -60,7 +60,7 @@ export class IssueWebReporter extends BaseIssueReporterService { this.issueReporterModel.update({ issueType: issueType }); // Resets placeholder - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTextArea = this.getElementById('issue-title'); if (descriptionTextArea) { descriptionTextArea.placeholder = localize('undefinedPlaceholder', "Please enter a title"); diff --git a/src/vs/workbench/contrib/issue/browser/issueService.ts b/src/vs/workbench/contrib/issue/browser/issueService.ts index 1304430ebca1..2c7c61cb0edb 100644 --- a/src/vs/workbench/contrib/issue/browser/issueService.ts +++ b/src/vs/workbench/contrib/issue/browser/issueService.ts @@ -9,8 +9,9 @@ import { userAgent } from '../../../../base/common/platform.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IExtensionManagementService } from '../../../../platform/extensionManagement/common/extensionManagement.js'; import { ExtensionType, IExtensionDescription } from '../../../../platform/extensions/common/extensions.js'; +import { GitHubAuthorizationContext } from '../../../../platform/github/common/githubTypes.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; -import { normalizeGitHubUrl } from '../common/issueReporterUtil.js'; +import { getGitHubAuthorization, normalizeGitHubUrl } from '../common/issueReporterUtil.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IProductService } from '../../../../platform/product/common/productService.js'; import { buttonBackground, buttonForeground, buttonHoverBackground, foreground, inputActiveOptionBorder, inputBackground, inputBorder, inputForeground, inputValidationErrorBackground, inputValidationErrorBorder, inputValidationErrorForeground, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, textLinkActiveForeground, textLinkForeground } from '../../../../platform/theme/common/colorRegistry.js'; @@ -73,10 +74,14 @@ export class BrowserIssueService implements IWorkbenchIssueService { const experiments = await this.experimentService.getCurrentExperiments(); let githubAccessToken = ''; + let githubAuthorization: GitHubAuthorizationContext | undefined; try { const githubSessions = await this.authenticationService.getSessions('github'); - const potentialSessions = githubSessions.filter(session => session.scopes.includes('repo')); - githubAccessToken = potentialSessions[0]?.accessToken; + const session = githubSessions.find(session => options.githubAccessToken === undefined + ? session.scopes.includes('repo') + : session.accessToken === options.githubAccessToken); + githubAccessToken = session?.accessToken ?? ''; + githubAuthorization = session && getGitHubAuthorization(session); } catch (e) { // Ignore } @@ -137,7 +142,8 @@ export class BrowserIssueService implements IWorkbenchIssueService { restrictedMode: !this.workspaceTrustManagementService.isWorkspaceTrusted(), isInstallationPure, isSessionsWindow: this.environmentService.isSessionsWindow, - githubAccessToken + githubAccessToken, + githubAuthorization, }, options); return this.issueFormService.openReporter(issueReporterData); diff --git a/src/vs/workbench/contrib/issue/browser/media/issueReporterOverlay.css b/src/vs/workbench/contrib/issue/browser/media/issueReporterOverlay.css index b6c2375dfcb3..b562bc3b8804 100644 --- a/src/vs/workbench/contrib/issue/browser/media/issueReporterOverlay.css +++ b/src/vs/workbench/contrib/issue/browser/media/issueReporterOverlay.css @@ -214,7 +214,7 @@ flex: 0 0 auto; padding: 4px 10px; height: 26px; - border-radius: 4px 0 0 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px) 0 0 var(--workbench-custom-buttons-corner-radius, 4px); border-right: none !important; font-size: 12px; line-height: 18px; @@ -266,7 +266,7 @@ flex: 0 0 auto; padding: 4px 6px; height: 26px; - border-radius: 0 4px 4px 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, 4px) var(--workbench-custom-buttons-corner-radius, 4px) 0; border-left: none !important; min-width: 0; } @@ -440,7 +440,7 @@ label/control gap, so the buttons must not add their own margin. */ background: transparent !important; color: var(--vscode-foreground, #ccc) !important; border: 1px solid transparent; - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); font-size: 13px; line-height: normal; transition: border-color 0.15s ease, background 0.15s ease; @@ -1116,7 +1116,7 @@ extension field is hidden (no fixed-width placeholder needed). */ /* Annotation Editor Buttons */ .issue-reporter-annotation-overlay .monaco-button { - border-radius: 4px; + border-radius: var(--workbench-custom-buttons-corner-radius, 4px); height: 28px; font-size: 13px; min-width: 80px; diff --git a/src/vs/workbench/contrib/issue/common/issue.ts b/src/vs/workbench/contrib/issue/common/issue.ts index 8a6fd0312e41..08ca45ad735f 100644 --- a/src/vs/workbench/contrib/issue/common/issue.ts +++ b/src/vs/workbench/contrib/issue/common/issue.ts @@ -4,6 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import { UriComponents } from '../../../../base/common/uri.js'; +import { RepositoryRef } from '../../../../platform/github/common/client/types.js'; +import { CreateIssueRequest } from '../../../../platform/github/common/core/issues.js'; +import { GitHubAuthorizationContext } from '../../../../platform/github/common/githubTypes.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; // Since data sent through the service is serialized to JSON, functions will be lost, so Color objects @@ -90,6 +93,8 @@ export interface IssueReporterData extends WindowData { isInstallationPure: boolean; isSessionsWindow: boolean; githubAccessToken: string; + /** The selected grant for classic issue creation, independent of token renewal. */ + githubAuthorization?: GitHubAuthorizationContext; /** Refreshes an automatically selected GitHub session before a new reporter preview. */ getGitHubAccessToken?: () => Promise; issueTitle?: string; @@ -158,6 +163,7 @@ export interface IIssueFormService { closeReporter(): Promise; submitIssue(host: IIssueSubmissionHost, data: IssueReporterData, title: string, body: string, signal?: AbortSignal): Promise; searchGitHubIssues(repo: string, title: string, signal: AbortSignal): Promise; + createGitHubIssue(authorization: GitHubAuthorizationContext, repository: RepositoryRef, request: CreateIssueRequest, signal: AbortSignal): Promise; } export interface ISimilarIssue { diff --git a/src/vs/workbench/contrib/issue/common/issueReporterUtil.ts b/src/vs/workbench/contrib/issue/common/issueReporterUtil.ts index 9378ffdf5db0..a86bbe2223bc 100644 --- a/src/vs/workbench/contrib/issue/common/issueReporterUtil.ts +++ b/src/vs/workbench/contrib/issue/common/issueReporterUtil.ts @@ -4,6 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { rtrim } from '../../../../base/common/strings.js'; +import { GitHubAuthorizationContext } from '../../../../platform/github/common/githubTypes.js'; +import { AuthenticationSession } from '../../../services/authentication/common/authentication.js'; export function normalizeGitHubUrl(url: string): string { // If the url has a .git suffix, remove it @@ -24,3 +26,13 @@ export function normalizeGitHubUrl(url: string): string { return url; } + +export function getGitHubAuthorization(session: AuthenticationSession): GitHubAuthorizationContext { + return { + providerId: 'github', + sessionId: session.id, + accountId: session.account.id, + scopes: [...session.scopes], + authorizationServer: session.authorizationServer?.toString(), + }; +} diff --git a/src/vs/workbench/contrib/issue/electron-browser/issueReporterService.ts b/src/vs/workbench/contrib/issue/electron-browser/issueReporterService.ts index 58fc1a8b75b5..9398790b123f 100644 --- a/src/vs/workbench/contrib/issue/electron-browser/issueReporterService.ts +++ b/src/vs/workbench/contrib/issue/electron-browser/issueReporterService.ts @@ -88,9 +88,9 @@ export class IssueReporter extends BaseIssueReporterService { const updateState = this.updateService.state; if (updateState.type === StateType.Ready || updateState.type === StateType.Downloaded) { this.needsUpdate = true; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const includeAcknowledgement = this.getElementById('version-acknowledgements'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const updateBanner = this.getElementById('update-banner'); if (updateBanner && includeAcknowledgement) { includeAcknowledgement.classList.remove('hidden'); @@ -113,7 +113,7 @@ export class IssueReporter extends BaseIssueReporterService { } // Resets placeholder - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionTextArea = this.getElementById('issue-title'); if (descriptionTextArea) { descriptionTextArea.placeholder = localize('undefinedPlaceholder', "Please enter a title"); @@ -153,28 +153,7 @@ export class IssueReporter extends BaseIssueReporterService { return false; } } - const url = `https://api.github.com/repos/${gitHubDetails.owner}/${gitHubDetails.repositoryName}/issues`; - const init = { - method: 'POST', - body: JSON.stringify({ - title: issueTitle, - body: issueBody - }), - headers: new Headers({ - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${this.data.githubAccessToken}` - }) - }; - - const response = await fetch(url, init); - if (!response.ok) { - console.error('Invalid GitHub URL provided.'); - return false; - } - const result = await response.json(); - await this.openerService.open(result.html_url, { openExternal: true }); - this.close(); - return true; + return super.submitToGitHub(issueTitle, issueBody, gitHubDetails); } public override async createIssue(shouldCreate?: boolean, privateUri?: boolean): Promise { @@ -192,7 +171,7 @@ export class IssueReporter extends BaseIssueReporterService { if (!this.validateInputs()) { // If inputs are invalid, set focus to the first one and add listeners on them // to detect further changes - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const invalidInput = this.window.document.getElementsByClassName('invalid-input'); if (invalidInput.length) { (invalidInput[0]).focus(); @@ -222,7 +201,7 @@ export class IssueReporter extends BaseIssueReporterService { this.hasBeenSubmitted = true; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const issueTitle = (this.getElementById('issue-title')).value; const issueBody = this.issueReporterModel.serialize(); @@ -237,7 +216,7 @@ export class IssueReporter extends BaseIssueReporterService { const gitHubDetails = this.parseGitHubUrl(issueUrl); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const baseUrl = this.getIssueUrlWithTitle((this.getElementById('issue-title')).value, issueUrl); let url = baseUrl + `&body=${encodeURIComponent(issueBody)}`; @@ -275,7 +254,7 @@ export class IssueReporter extends BaseIssueReporterService { } private updateSystemInfo(state: IssueReporterModelData) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const target = this.window.document.querySelector('.block-system .block-info'); if (target) { @@ -365,7 +344,7 @@ export class IssueReporter extends BaseIssueReporterService { private updateExperimentsInfo(experimentInfo: string | undefined) { this.issueReporterModel.update({ experimentInfo }); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const target = this.window.document.querySelector('.block-experiments .block-info'); if (target) { target.textContent = experimentInfo ? experimentInfo : localize('noCurrentExperiments', "No current experiments."); diff --git a/src/vs/workbench/contrib/issue/electron-browser/issueService.ts b/src/vs/workbench/contrib/issue/electron-browser/issueService.ts index 94db0c3a6442..d5b8fb498841 100644 --- a/src/vs/workbench/contrib/issue/electron-browser/issueService.ts +++ b/src/vs/workbench/contrib/issue/electron-browser/issueService.ts @@ -11,6 +11,7 @@ import { localize } from '../../../../nls.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IExtensionManagementService } from '../../../../platform/extensionManagement/common/extensionManagement.js'; import { ExtensionType } from '../../../../platform/extensions/common/extensions.js'; +import { GitHubAuthorizationContext } from '../../../../platform/github/common/githubTypes.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; @@ -23,6 +24,7 @@ import { IWorkspaceTrustManagementService } from '../../../../platform/workspace import { SIDE_BAR_BACKGROUND } from '../../../common/theme.js'; import { IIssueFormService, IssueReporterData, IssueReporterExtensionData, IssueReporterStyles, IssueSource, IWorkbenchIssueService } from '../common/issue.js'; import { isPublicVSCodeIssueUrl, issueReporterAdditionalRepositoriesSettingId, parseIssueReporterRepositories } from '../common/issueReporterTarget.js'; +import { getGitHubAuthorization } from '../common/issueReporterUtil.js'; import { IWorkbenchAssignmentService } from '../../../services/assignment/common/assignmentService.js'; import { IAuthenticationService } from '../../../services/authentication/common/authentication.js'; import { IWorkbenchExtensionEnablementService } from '../../../services/extensionManagement/common/extensionManagement.js'; @@ -142,10 +144,14 @@ export class NativeIssueService implements IWorkbenchIssueService { const experiments = await this.experimentService.getCurrentExperiments(); let githubAccessToken = ''; + let githubAuthorization: GitHubAuthorizationContext | undefined; try { const githubSessions = await this.authenticationService.getSessions('github'); - const repoSession = githubSessions.find(session => session.scopes.includes('repo')); - githubAccessToken = repoSession?.accessToken ?? ''; + const session = githubSessions.find(session => dataOverrides.githubAccessToken === undefined + ? session.scopes.includes('repo') + : session.accessToken === dataOverrides.githubAccessToken); + githubAccessToken = session?.accessToken ?? ''; + githubAuthorization = session && getGitHubAuthorization(session); } catch (e) { // Ignore } @@ -167,6 +173,7 @@ export class NativeIssueService implements IWorkbenchIssueService { isInstallationPure, isSessionsWindow: this.environmentService.isSessionsWindow, githubAccessToken, + githubAuthorization, }, dataOverrides); return this.issueFormService.openReporter(issueReporterData); diff --git a/src/vs/workbench/contrib/issue/test/browser/baseIssueReporterService.test.ts b/src/vs/workbench/contrib/issue/test/browser/baseIssueReporterService.test.ts index 59ee295c2d59..c9ffc0e88387 100644 --- a/src/vs/workbench/contrib/issue/test/browser/baseIssueReporterService.test.ts +++ b/src/vs/workbench/contrib/issue/test/browser/baseIssueReporterService.test.ts @@ -6,20 +6,23 @@ import assert from 'assert'; import { $ } from '../../../../../base/browser/dom.js'; import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; -import { Event as VSCodeEvent } from '../../../../../base/common/event.js'; +import { isCancellationError } from '../../../../../base/common/errors.js'; +import { Emitter, Event as VSCodeEvent } from '../../../../../base/common/event.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { IProductConfiguration } from '../../../../../base/common/product.js'; +import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; import { IFileDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; +import { GitHubAuthorizationContext, GitHubRequestError } from '../../../../../platform/github/common/githubTypes.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; -import { IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; +import { AuthenticationSession, IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; import { BaseIssueReporterService } from '../../browser/baseIssueReporterService.js'; import { IIssueFormService, ISimilarIssue } from '../../common/issue.js'; @@ -37,6 +40,13 @@ suite('BaseIssueReporterService', () => { function createReporter( searchGitHubIssues: IIssueFormService['searchGitHubIssues'] = async () => [currentIssue], fetcher: typeof fetch = async () => { throw new Error('Unexpected duplicate search'); }, + submission: { + accessToken?: string; + authorization?: GitHubAuthorizationContext; + getSessions?: IAuthenticationService['getSessions']; + onDidChangeSessions?: IAuthenticationService['onDidChangeSessions']; + createGitHubIssue?: IIssueFormService['createGitHubIssue']; + } = {}, ) { const iframe = document.createElement('iframe'); document.body.appendChild(iframe); @@ -59,7 +69,12 @@ suite('BaseIssueReporterService', () => { } })); const instantiationService = store.add(new TestInstantiationService()); - instantiationService.stub(IIssueFormService, { searchGitHubIssues }); + const events: string[] = []; + instantiationService.stub(IIssueFormService, { + searchGitHubIssues, + createGitHubIssue: submission.createGitHubIssue, + closeReporter: async () => { events.push('close'); }, + }); instantiationService.stub(IThemeService, { onDidProductIconThemeChange: VSCodeEvent.None, getProductIconTheme: () => ({ getIcon: () => undefined }), @@ -67,13 +82,27 @@ suite('BaseIssueReporterService', () => { instantiationService.stub(IFileService, {}); instantiationService.stub(IFileDialogService, {}); instantiationService.stub(IContextMenuService, {}); - instantiationService.stub(IAuthenticationService, { onDidChangeSessions: VSCodeEvent.None }); - instantiationService.stub(IOpenerService, {}); + instantiationService.stub(IAuthenticationService, { + onDidChangeSessions: submission.onDidChangeSessions ?? VSCodeEvent.None, + getSessions: submission.getSessions ?? (async () => []), + }); + instantiationService.stub(IOpenerService, { + open: async (uri, options) => { + assert.deepStrictEqual(options, { openExternal: true }); + events.push(uri.toString()); + return true; + }, + }); const warnings: string[] = []; - instantiationService.stub(ILogService, { warn: message => { warnings.push(message); } }); + const errors: string[] = []; + instantiationService.stub(ILogService, { + warn: message => { warnings.push(message); }, + error: message => { errors.push(String(message)); }, + }); const reporter = store.add(instantiationService.createInstance(BaseIssueReporterService, false, { styles: {}, zoomLevel: 0, enabledExtensions: [], restrictedMode: false, - isInstallationPure: true, isSessionsWindow: false, githubAccessToken: '', + isInstallationPure: true, isSessionsWindow: false, githubAccessToken: submission.accessToken ?? '', + githubAuthorization: submission.authorization, }, { type: 'test', arch: 'test', release: 'test' }, new class extends mock() { override readonly nameShort = 'Test'; override readonly version = '1.0.0'; @@ -86,9 +115,108 @@ suite('BaseIssueReporterService', () => { repositoryUrl: 'https://github.com/owner/extension', bugsUrl: undefined, }, }); - return { reporter, title, description, results, warnings }; + return { reporter, title, description, results, warnings, errors, events }; } + suite('GitHub submission', () => { + const selected: AuthenticationSession = { + id: 'selected-session', accessToken: 'selected-token', + account: { id: 'selected-account', label: 'Selected' }, scopes: ['public_repo'], + authorizationServer: URI.parse('https://github.com'), + }; + const other: AuthenticationSession = { + id: 'other-session', accessToken: 'other-token', + account: { id: 'other-account', label: 'Other' }, scopes: ['repo', 'user:email'], + }; + const authorization: GitHubAuthorizationContext = { + providerId: 'github', sessionId: selected.id, accountId: selected.account.id, + scopes: selected.scopes, authorizationServer: selected.authorizationServer?.toString(), + }; + + test('submits with the selected grant after its token is renewed', async () => { + const requests: Parameters[] = []; + const changes = store.add(new Emitter()); + const renewedSession = { ...selected, accessToken: 'renewed-token' }; + let renewed = false; + const { reporter, events } = createReporter(undefined, undefined, { + accessToken: selected.accessToken, authorization, + getSessions: async () => { + if (!renewed) { + renewed = true; + changes.fire(); + } + return [other, renewedSession]; + }, + onDidChangeSessions: VSCodeEvent.map(changes.event, () => ({ + providerId: 'github', label: 'GitHub', event: { added: [], removed: [], changed: [renewedSession] }, + })), + createGitHubIssue: async (...args) => { requests.push(args); return currentIssue.html_url; }, + }); + const result = await reporter.submitToGitHub('Report title', 'Report body', { owner: 'publisher', repositoryName: 'extension' }); + assert.deepStrictEqual({ result, requests: requests.map(([authorization, repository, request]) => [authorization, repository, request]), events, token: reporter.data.githubAccessToken }, { + result: true, + requests: [[authorization, { owner: 'publisher', repo: 'extension' }, { title: 'Report title', body: 'Report body' }]], + events: [currentIssue.html_url, 'close'], token: renewedSession.accessToken, + }); + }); + + test('does not broaden the selected grant or substitute another account', async () => { + let calls = 0; + const { reporter, events, errors } = createReporter(undefined, undefined, { + accessToken: selected.accessToken, authorization, + getSessions: async () => [other, { ...selected, scopes: ['repo'] }], + createGitHubIssue: async () => { calls++; return currentIssue.html_url; }, + }); + await assert.rejects(reporter.submitToGitHub('Title', 'Body', { owner: 'owner', repositoryName: 'repo' }), { kind: 'authentication' }); + assert.deepStrictEqual({ calls, events, errors }, { calls: 0, events: [], errors: ['[IssueReporter] Failed to create GitHub issue'] }); + }); + + for (const error of [ + new GitHubRequestError('Forbidden', 'authorization', 403), + new GitHubRequestError('Connection lost', 'network'), + ]) { + test(`does not retry or open an issue after ${error.message}`, async () => { + let calls = 0; + const { reporter, events, errors } = createReporter(undefined, undefined, { + accessToken: selected.accessToken, authorization, + getSessions: async () => [selected], + createGitHubIssue: async () => { calls++; throw error; }, + }); + const submission = reporter.submitToGitHub('Title', 'Body', { owner: 'owner', repositoryName: 'repo' }); + if (error.statusCode !== undefined) { + assert.strictEqual(await submission, false); + } else { + await assert.rejects(submission, candidate => candidate === error); + } + assert.deepStrictEqual({ calls, events, errors }, { + calls: 1, events: [], errors: ['[IssueReporter] Failed to create GitHub issue'], + }); + }); + } + + test('closing the reporter cancels creation without late navigation', async () => { + const started = new DeferredPromise(); + const pending = new DeferredPromise(); + let signal: AbortSignal | undefined; + const { reporter, events, errors } = createReporter(undefined, undefined, { + accessToken: selected.accessToken, authorization, + getSessions: async () => [selected], + createGitHubIssue: async (_authorization, _repository, _request, requestSignal) => { + signal = requestSignal; + void started.complete(); + await pending.p; + return currentIssue.html_url; + }, + }); + const rejected = assert.rejects(reporter.submitToGitHub('Title', 'Body', { owner: 'owner', repositoryName: 'repo' }), isCancellationError); + await started.p; + reporter.dispose(); + await pending.complete(); + await rejected; + assert.deepStrictEqual({ aborted: signal?.aborted, events, errors }, { aborted: true, events: [], errors: [] }); + }); + }); + for (const source of ['marketplace', 'extension'] as const) { for (const timing of ['debounce', 'active'] as const) { test(`stale duplicate results do not cancel a ${source} search during ${timing}`, () => runWithFakedTimers({}, async () => { diff --git a/src/vs/workbench/contrib/issue/test/browser/issueFormService.test.ts b/src/vs/workbench/contrib/issue/test/browser/issueFormService.test.ts index efb6a872c615..604cec2258da 100644 --- a/src/vs/workbench/contrib/issue/test/browser/issueFormService.test.ts +++ b/src/vs/workbench/contrib/issue/test/browser/issueFormService.test.ts @@ -21,9 +21,11 @@ import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.j import { IFileContent, IFileService } from '../../../../../platform/files/common/files.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { IGitHubAccountClient } from '../../../../../platform/github/common/account/account.js'; import { IGitHubAnonymousClient } from '../../../../../platform/github/common/anonymous/anonymous.js'; import { ApiRequestOptions } from '../../../../../platform/github/common/client/request.js'; -import { GitHubRequestError } from '../../../../../platform/github/common/githubTypes.js'; +import { Issue } from '../../../../../platform/github/common/core/issues.js'; +import { GitHubAuthorizationContext, GitHubRequestError } from '../../../../../platform/github/common/githubTypes.js'; import { SchemaError } from '../../../../../platform/github/common/client/schema.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import product from '../../../../../platform/product/common/product.js'; @@ -838,6 +840,72 @@ suite('IssueFormService', () => { assert.deepStrictEqual(leases, { acquired: 0, released: 0 }); }); + suite('GitHub creation', () => { + const authorization: GitHubAuthorizationContext = { + providerId: 'github', sessionId: 'selected-session', accountId: 'selected-account', scopes: ['public_repo'], + }; + const repository = { owner: 'publisher', repo: 'extension' }; + const request = { title: 'Title', body: 'Body' }; + const issueUrl = 'https://github.com/publisher/extension/issues/42'; + + function createService(create: IGitHubAccountClient['issues']['create'], acquire?: () => Promise) { + const instantiationService = createInstantiationService(); + const grants: GitHubAuthorizationContext[] = []; + const signals: AbortSignal[] = []; + const leases = { released: 0 }; + instantiationService.stub(IWorkbenchGitHubService, new class extends mock() { + override async acquireAccountApiClient(authorization: GitHubAuthorizationContext, signal: AbortSignal) { + grants.push(authorization); + signals.push(signal); + await acquire?.(); + return upcastPartial({ + issues: upcastPartial({ create }), + dispose: () => { leases.released++; }, + }); + } + }()); + return { service: store.add(instantiationService.createInstance(IssueFormService)), grants, signals, leases }; + } + + test('uses a disposable typed account client and preserves the destination and payload', async () => { + const calls: Parameters[] = []; + const { service, grants, signals, leases } = createService(async (...args) => { + calls.push(args); + return upcastPartial({ html_url: issueUrl }); + }); + const result = await service.createGitHubIssue(authorization, repository, request, new AbortController().signal); + assert.deepStrictEqual({ result, grants, calls: calls.map(([repository, request, , options]) => ({ repository, request, options })), sameSignal: calls[0][2] === signals[0], leases }, { + result: issueUrl, grants: [authorization], + calls: [{ repository, request, options: { caller: 'issueReporter', priority: 'mutation' } }], + sameSignal: true, leases: { released: 1 }, + }); + }); + + test('releases the client and propagates a failed write without retrying', async () => { + let calls = 0; + const error = new GitHubRequestError('Connection lost', 'network'); + const { service, grants, leases } = createService(async () => { calls++; throw error; }); + await assert.rejects(service.createGitHubIssue(authorization, repository, request, new AbortController().signal), candidate => candidate === error); + assert.deepStrictEqual({ calls, grants, leases }, { calls: 1, grants: [authorization], leases: { released: 1 } }); + }); + + test('cancellation during acquisition releases the late client without creating an issue', async () => { + const started = new DeferredPromise(); + const pending = new DeferredPromise(); + const { service, signals, leases } = createService( + async () => assert.fail('Unexpected issue creation'), + () => { void started.complete(); return pending.p; }, + ); + const controller = new AbortController(); + const rejected = assert.rejects(service.createGitHubIssue(authorization, repository, request, controller.signal), isCancellationError); + await started.p; + controller.abort(new CancellationError()); + await pending.complete(); + await rejected; + assert.deepStrictEqual({ aborted: signals[0].aborted, leases }, { aborted: true, leases: { released: 1 } }); + }); + }); + test('disposes the legacy web reporter when its auxiliary window closes', async () => { const instantiationService = createInstantiationService(); const iframe = document.createElement('iframe'); diff --git a/src/vs/workbench/contrib/issue/test/electron-browser/issueService.test.ts b/src/vs/workbench/contrib/issue/test/electron-browser/issueService.test.ts index 6e3053fe2bb5..837ff61d553d 100644 --- a/src/vs/workbench/contrib/issue/test/electron-browser/issueService.test.ts +++ b/src/vs/workbench/contrib/issue/test/electron-browser/issueService.test.ts @@ -100,6 +100,22 @@ suite('NativeIssueService additional repositories', () => { }); } + test('classic reporter captures the exact grant for an explicit caller token', async () => { + const { service, opened, authenticationSessions } = createService(false, []); + const authorizationServer = URI.parse('https://github.com'); + authenticationSessions.push( + { id: 'other', account: { id: 'other', label: 'Other' }, scopes: ['repo'], accessToken: 'other-token' }, + { id: 'selected', account: { id: 'selected', label: 'Selected' }, scopes: ['public_repo'], accessToken: 'selected-token', authorizationServer }, + ); + await service.openReporter({ githubAccessToken: 'selected-token' }); + assert.deepStrictEqual({ token: opened[0].githubAccessToken, authorization: opened[0].githubAuthorization }, { + token: 'selected-token', + authorization: { + providerId: 'github', sessionId: 'selected', accountId: 'selected', scopes: ['public_repo'], authorizationServer: authorizationServer.toString(), + }, + }); + }); + test('repository schema is application-scoped, empty by default and experiment-enabled without an authorization policy', () => { const schema = Registry.as(Extensions.Configuration).getConfigurationProperties()[issueReporterAdditionalRepositoriesSettingId]; assert.deepStrictEqual({ diff --git a/src/vs/workbench/contrib/languageStatus/browser/languageStatus.ts b/src/vs/workbench/contrib/languageStatus/browser/languageStatus.ts index c46b6db7dcb4..12d294767dce 100644 --- a/src/vs/workbench/contrib/languageStatus/browser/languageStatus.ts +++ b/src/vs/workbench/contrib/languageStatus/browser/languageStatus.ts @@ -232,9 +232,9 @@ class LanguageStatus { // when severity is warning or error, don't show animation when showing progress/busy const userHasInteractedWithStatus = this._interactionCounter.value >= 3; const targetWindow = dom.getWindow(editor?.getContainerDomNode()); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const node = targetWindow.document.querySelector('.monaco-workbench .statusbar DIV#status\\.languageStatus A>SPAN.codicon'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const container = targetWindow.document.querySelector('.monaco-workbench .statusbar DIV#status\\.languageStatus'); if (dom.isHTMLElement(node) && container) { const _wiggle = 'wiggle'; @@ -255,7 +255,7 @@ class LanguageStatus { // track when the hover shows (this is automagic and DOM mutation spying is needed...) // use that as signal that the user has interacted/learned language status items work if (!userHasInteractedWithStatus) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const hoverTarget = targetWindow.document.querySelector('.monaco-workbench .context-view'); if (dom.isHTMLElement(hoverTarget)) { const observer = new MutationObserver(() => { diff --git a/src/vs/workbench/contrib/markdown/browser/markedKatexSupport.ts b/src/vs/workbench/contrib/markdown/browser/markedKatexSupport.ts index c52989b6d739..476acdb62086 100644 --- a/src/vs/workbench/contrib/markdown/browser/markedKatexSupport.ts +++ b/src/vs/workbench/contrib/markdown/browser/markedKatexSupport.ts @@ -156,7 +156,7 @@ export class MarkedKatexSupport { public static ensureKatexStyles(window: CodeWindow) { const doc = window.document; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax if (!doc.querySelector('link.katex')) { const katexStyle = document.createElement('link'); katexStyle.classList.add('katex'); diff --git a/src/vs/workbench/contrib/markers/browser/markersTable.ts b/src/vs/workbench/contrib/markers/browser/markersTable.ts index d0be59eed893..0dd7fbd51dec 100644 --- a/src/vs/workbench/contrib/markers/browser/markersTable.ts +++ b/src/vs/workbench/contrib/markers/browser/markersTable.ts @@ -354,7 +354,7 @@ export class MarkersTable extends Disposable implements IProblemsWidget { options ) as WorkbenchTable); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const list = this.table.domNode.querySelector('.monaco-list-rows')! as HTMLElement; // mouseover/mouseleave event handlers diff --git a/src/vs/workbench/contrib/markers/browser/markersView.ts b/src/vs/workbench/contrib/markers/browser/markersView.ts index 74c84ed105ba..301dffd08750 100644 --- a/src/vs/workbench/contrib/markers/browser/markersView.ts +++ b/src/vs/workbench/contrib/markers/browser/markersView.ts @@ -486,14 +486,14 @@ export class MarkersView extends FilterViewPane implements IMarkersView { return table; } - private createTree(parent: HTMLElement): IProblemsWidget { - const onDidChangeRenderNodeCount = new Relay>(); + private createTree(parent: HTMLElement,): IProblemsWidget { + const onDidChangeRenderNodeCount = this.widgetDisposables.add(new Relay>()); - const treeLabels = this.instantiationService.createInstance(ResourceLabels, this); + const treeLabels = this.widgetDisposables.add(this.instantiationService.createInstance(ResourceLabels, this)); const virtualDelegate = new VirtualDelegate(this.markersViewModel); const renderers = [ - this.instantiationService.createInstance(ResourceMarkersRenderer, treeLabels, onDidChangeRenderNodeCount.event), + this.widgetDisposables.add(this.instantiationService.createInstance(ResourceMarkersRenderer, treeLabels, onDidChangeRenderNodeCount.event)), this.instantiationService.createInstance(MarkerRenderer, this.markersViewModel), this.instantiationService.createInstance(RelatedInformationRenderer) ]; @@ -611,7 +611,11 @@ export class MarkersView extends FilterViewPane implements IMarkersView { } private onDidChangeViewMode(): void { - // Save selection + if (!this.widgetContainer || !this.widget) { + return; + } + + // Save selection and focus BEFORE disposing the widget const selection = new Set(); for (const marker of this.widget.getSelection()) { if (marker instanceof ResourceMarkers) { @@ -621,7 +625,6 @@ export class MarkersView extends FilterViewPane implements IMarkersView { } } - // Save focus const focus = new Set(); for (const marker of this.widget.getFocus()) { if (marker instanceof Marker || marker instanceof MarkerTableItem) { @@ -629,10 +632,9 @@ export class MarkersView extends FilterViewPane implements IMarkersView { } } - if (this.widgetContainer && this.widget) { - this.widgetContainer.textContent = ''; - this.widgetDisposables.clear(); - } + // Now dispose the widget and clear the container + this.widgetContainer.textContent = ''; + this.widgetDisposables.clear(); // Create new widget this.createWidget(this.widgetContainer); diff --git a/src/vs/workbench/contrib/markers/test/browser/markersView.test.ts b/src/vs/workbench/contrib/markers/test/browser/markersView.test.ts index 608d79c08065..ece2a4d292eb 100644 --- a/src/vs/workbench/contrib/markers/test/browser/markersView.test.ts +++ b/src/vs/workbench/contrib/markers/test/browser/markersView.test.ts @@ -4,11 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { Event } from '../../../../../base/common/event.js'; +import { spy } from 'sinon'; +import { Event, Relay } from '../../../../../base/common/event.js'; import { toDisposable } from '../../../../../base/common/lifecycle.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 { ILanguageService } from '../../../../../editor/common/languages/language.js'; +import { LanguageService } from '../../../../../editor/common/services/languageService.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; import { IMarkerData, IMarkerService, MarkerSeverity } from '../../../../../platform/markers/common/markers.js'; @@ -46,16 +49,15 @@ suite('MarkersView', () => { const markerService = disposables.add(new MarkerService()); instantiationService.stub(IMarkerService, markerService); const view = disposables.add(instantiationService.createInstance(MarkersView, { id: Markers.MARKERS_VIEW_ID, title: 'Problems' })); - const labels = disposables.add(instantiationService.createInstance(ResourceLabels, view)); - instantiationService.stubInstance(ResourceLabels, labels); - instantiationService.stubInstance(ResourceMarkersRenderer, disposables.add(new ResourceMarkersRenderer(labels, Event.None))); + const createInstance = spy(view['instantiationService'], 'createInstance'); + disposables.add(toDisposable(() => createInstance.restore())); disposables.add(toDisposable(() => view.element.remove())); document.body.appendChild(view.element); view.render(); view.setVisible(true); view.orthogonalSize = 400; view.layout(800); - return { view, markerService }; + return { view, markerService, createInstance, languageService: instantiationService.get(ILanguageService) as LanguageService }; } async function update(view: MarkersView, markerService: MarkerService, resource: URI, message: string): Promise { @@ -68,6 +70,49 @@ suite('MarkersView', () => { return resources.flatMap(resource => view['markersModel'].getResourceMarkers(resource)?.markers ?? []); } + test('releases tree labels, renderers and relay subscriptions on repeated switches and disposal', async () => { + const relayInput = spy(Relay.prototype, 'input', ['set']); + disposables.add(toDisposable(() => relayInput.set.restore())); + const { view, markerService, createInstance, languageService } = createView(MarkersViewMode.Table); + await update(view, markerService, resources[0], 'first'); + const listeners = () => languageService['_onDidChange']['_size']; + const initialListeners = listeners(); + const labels: ResourceLabels[] = []; + const renderers: ResourceMarkersRenderer[] = []; + + for (let iteration = 0; iteration < 3; iteration++) { + view.setViewMode(MarkersViewMode.Tree); + const treeLabels = createInstance.returnValues.findLast((instance): instance is ResourceLabels => instance instanceof ResourceLabels)!; + labels.push(treeLabels); + const renderer = createInstance.returnValues.findLast((instance): instance is ResourceMarkersRenderer => instance instanceof ResourceMarkersRenderer)!; + renderers.push(renderer); + const relay: Relay = relayInput.set.lastCall.thisValue; + assert.deepStrictEqual({ + freshLabels: new Set(labels).size, + freshRenderers: new Set(renderers).size, + disposed: treeLabels['_store'].isDisposed, + rendererDisposed: renderer['disposables'].isDisposed, + relayListening: relay['listening'], + relayListeners: relay['emitter'].hasListeners(), + listeners: listeners() + }, { freshLabels: iteration + 1, freshRenderers: iteration + 1, disposed: false, rendererDisposed: false, relayListening: true, relayListeners: true, listeners: initialListeners + 1 }); + + if (iteration < 2) { + view.setViewMode(MarkersViewMode.Table); + } else { + view.dispose(); + } + + assert.deepStrictEqual({ + disposed: labels.map(labels => labels['_store'].isDisposed), + renderersDisposed: renderers.map(renderer => renderer['disposables'].isDisposed), + relayListening: relay['listening'], + relayListeners: relay['emitter'].hasListeners(), + listeners: listeners() + }, { disposed: labels.map(() => true), renderersDisposed: renderers.map(() => true), relayListening: false, relayListeners: false, listeners: initialListeners }); + } + }); + for (const viewMode of [MarkersViewMode.Tree, MarkersViewMode.Table]) { suite(viewMode, () => { for (const populateCache of [false, true]) { diff --git a/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts b/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts index 68df323b1aef..dd13f6f42f66 100644 --- a/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts +++ b/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts @@ -41,7 +41,7 @@ import { IWorkbenchMcpGatewayService } from '../common/mcpGatewayService.js'; import { BrowserMcpGatewayService } from './mcpGatewayService.js'; import { McpGatewayToolBrokerContribution } from './mcpGatewayToolBrokerContribution.js'; import { McpAddContextContribution } from './mcpAddContextContribution.js'; -import { AddConfigurationAction, EditStoredInput, InstallFromManifestAction, ListMcpServerCommand, McpAgentHostServerOptionsCommand, McpBrowseCommand, McpBrowsePageCommand, McpBrowseResourcesCommand, McpConfigureSamplingModels, McpConfirmationServerOptionsCommand, MCPServerActionRendering, McpServerOptionsCommand, McpSkipCurrentAutostartCommand, McpStartPromptingServerCommand, OpenRemoteUserMcpResourceCommand, OpenUserMcpResourceCommand, OpenWorkspaceFolderMcpResourceCommand, OpenWorkspaceMcpResourceCommand, RemoveStoredInput, ResetMcpCachedTools, ResetMcpTrustCommand, RestartServer, SetOAuthClientSecret, ShowConfiguration, ShowInstalledMcpServersCommand, ShowOutput, StartServer, StopServer } from './mcpCommands.js'; +import { AddConfigurationAction, EditStoredInput, InstallFromManifestAction, ListMcpServerCommand, McpAgentHostServerOptionsCommand, McpAuthenticateAgentHostServerCommand, McpBrowseCommand, McpBrowsePageCommand, McpBrowseResourcesCommand, McpConfigureSamplingModels, McpConfirmationServerOptionsCommand, MCPServerActionRendering, McpServerOptionsCommand, McpSkipCurrentAutostartCommand, McpStartPromptingServerCommand, OpenRemoteUserMcpResourceCommand, OpenUserMcpResourceCommand, OpenWorkspaceFolderMcpResourceCommand, OpenWorkspaceMcpResourceCommand, RemoveStoredInput, ResetMcpCachedTools, ResetMcpTrustCommand, RestartServer, SetOAuthClientSecret, ShowConfiguration, ShowInstalledMcpServersCommand, ShowOutput, StartServer, StopServer } from './mcpCommands.js'; import { McpDiscovery } from './mcpDiscovery.js'; import { McpElicitationService } from './mcpElicitationService.js'; import { McpLanguageFeatures } from './mcpLanguageFeatures.js'; @@ -81,6 +81,7 @@ registerWorkbenchContribution2('mcpGatewayToolBrokerRemote', McpGatewayToolBroke registerAction2(ListMcpServerCommand); registerAction2(McpServerOptionsCommand); registerAction2(McpAgentHostServerOptionsCommand); +registerAction2(McpAuthenticateAgentHostServerCommand); registerAction2(McpConfirmationServerOptionsCommand); registerAction2(ResetMcpTrustCommand); registerAction2(ResetMcpCachedTools); diff --git a/src/vs/workbench/contrib/mcp/browser/mcpCommands.ts b/src/vs/workbench/contrib/mcp/browser/mcpCommands.ts index 4438e831a690..b4625039cbd0 100644 --- a/src/vs/workbench/contrib/mcp/browser/mcpCommands.ts +++ b/src/vs/workbench/contrib/mcp/browser/mcpCommands.ts @@ -21,7 +21,7 @@ import { autorun, derived, derivedObservableWithCache, observableValue } from '. import { ThemeIcon } from '../../../../base/common/themables.js'; import { basename } from '../../../../base/common/resources.js'; import { hasKey, isDefined } from '../../../../base/common/types.js'; -import { URI } from '../../../../base/common/uri.js'; +import { URI, UriComponents } from '../../../../base/common/uri.js'; import { Range } from '../../../../editor/common/core/range.js'; import { SuggestController } from '../../../../editor/contrib/suggest/browser/suggestController.js'; import { ILocalizedString, localize, localize2 } from '../../../../nls.js'; @@ -55,6 +55,7 @@ import { IRemoteUserDataProfilesService } from '../../../services/userDataProfil import { IUserDataProfileService } from '../../../services/userDataProfile/common/userDataProfile.js'; import { IViewsService } from '../../../services/views/common/viewsService.js'; import { IChatWidgetService } from '../../chat/browser/chat.js'; +import { IChatViewHostService } from '../../chat/browser/chatViewHost.js'; import { getMcpServerDisplayLabel, IAgentHostCustomizationService } from '../../chat/browser/agentSessions/agentHost/agentHostCustomizationService.js'; import { setAgentHostPluginEnablement } from '../../chat/browser/agentPluginActions.js'; import { AICustomizationManagementCommands, AICustomizationManagementSection, IAICustomizationWorkspaceService } from '../../chat/common/aiCustomizationWorkspaceService.js'; @@ -471,6 +472,21 @@ export function findLocalMcpServer(mcpService: IMcpService, server: IAgentHostMc return nameMatches.length === 1 ? nameMatches[0] : undefined; } +export class McpAuthenticateAgentHostServerCommand extends Action2 { + constructor() { + super({ + id: McpCommandIds.AuthenticateAgentHostServer, + title: localize2('mcp.authenticateAgentHostServer', "Sign In to MCP Server"), + category, + f1: false, + }); + } + + override run(accessor: ServicesAccessor, agentHostSession: UriComponents, customizationId: string): Promise { + return accessor.get(IAgentHostCustomizationService).authenticateMcpServer(URI.revive(agentHostSession), customizationId); + } +} + export class McpAgentHostServerOptionsCommand extends Action2 { constructor() { super({ @@ -1810,7 +1826,7 @@ export class McpStartPromptingServerCommand extends Action2 { } async run(accessor: ServicesAccessor, server: IMcpServer): Promise { - const widget = await openPanelChatAndGetWidget(accessor.get(IViewsService), accessor.get(IChatWidgetService)); + const widget = await openPanelChatAndGetWidget(accessor.get(IChatViewHostService)); if (!widget) { return; } diff --git a/src/vs/workbench/contrib/mcp/browser/mcpResourceQuickAccess.ts b/src/vs/workbench/contrib/mcp/browser/mcpResourceQuickAccess.ts index f07c001e1ac6..885107624cb8 100644 --- a/src/vs/workbench/contrib/mcp/browser/mcpResourceQuickAccess.ts +++ b/src/vs/workbench/contrib/mcp/browser/mcpResourceQuickAccess.ts @@ -19,7 +19,7 @@ import { INotificationService } from '../../../../platform/notification/common/n import { DefaultQuickAccessFilterValue, IQuickAccessProvider, IQuickAccessProviderRunOptions } from '../../../../platform/quickinput/common/quickAccess.js'; import { IQuickInputService, IQuickPick, IQuickPickItem, IQuickPickSeparator } from '../../../../platform/quickinput/common/quickInput.js'; import { IEditorService } from '../../../services/editor/common/editorService.js'; -import { IViewsService } from '../../../services/views/common/viewsService.js'; +import { IChatViewHostService } from '../../chat/browser/chatViewHost.js'; import { IChatWidgetService } from '../../chat/browser/chat.js'; import { IChatAttachmentResolveService } from '../../chat/browser/attachments/chatAttachmentResolveService.js'; import { IChatRequestVariableEntry } from '../../chat/common/attachments/chatVariableEntries.js'; @@ -462,7 +462,7 @@ export abstract class AbstractMcpResourceAccessPick { @IInstantiationService private readonly _instantiationService: IInstantiationService, @IEditorService private readonly _editorService: IEditorService, @IChatWidgetService protected readonly _chatWidgetService: IChatWidgetService, - @IViewsService private readonly _viewsService: IViewsService, + @IChatViewHostService private readonly _chatViewHostService: IChatViewHostService, ) { } @@ -515,7 +515,7 @@ export abstract class AbstractMcpResourceAccessPick { if (attachment instanceof Promise) { attachment.then(async a => { if (a !== 'noop') { - const widget = await openPanelChatAndGetWidget(this._viewsService, this._chatWidgetService); + const widget = await openPanelChatAndGetWidget(this._chatViewHostService); widget?.attachmentModel.addContext(...asArray(a)); } picker.hide(); @@ -565,10 +565,10 @@ export class McpResourceQuickPick extends AbstractMcpResourceAccessPick { @IInstantiationService instantiationService: IInstantiationService, @IEditorService editorService: IEditorService, @IChatWidgetService chatWidgetService: IChatWidgetService, - @IViewsService viewsService: IViewsService, + @IChatViewHostService chatViewHostService: IChatViewHostService, @IQuickInputService private readonly _quickInputService: IQuickInputService, ) { - super(scopeTo, instantiationService, editorService, chatWidgetService, viewsService); + super(scopeTo, instantiationService, editorService, chatWidgetService, chatViewHostService); } public async pick(token = CancellationToken.None) { @@ -591,9 +591,9 @@ export class McpResourceQuickAccess extends AbstractMcpResourceAccessPick implem @IInstantiationService instantiationService: IInstantiationService, @IEditorService editorService: IEditorService, @IChatWidgetService chatWidgetService: IChatWidgetService, - @IViewsService viewsService: IViewsService + @IChatViewHostService chatViewHostService: IChatViewHostService ) { - super(undefined, instantiationService, editorService, chatWidgetService, viewsService); + super(undefined, instantiationService, editorService, chatWidgetService, chatViewHostService); } provide(picker: IQuickPick, token: CancellationToken, runOptions?: IQuickAccessProviderRunOptions): IDisposable { diff --git a/src/vs/workbench/contrib/mcp/browser/mcpServersView.ts b/src/vs/workbench/contrib/mcp/browser/mcpServersView.ts index 895fe809bf60..f5d1e7e85aef 100644 --- a/src/vs/workbench/contrib/mcp/browser/mcpServersView.ts +++ b/src/vs/workbench/contrib/mcp/browser/mcpServersView.ts @@ -47,6 +47,7 @@ import { IPagedRenderer } from '../../../../base/browser/ui/list/listPaging.js'; import { SeverityIcon } from '../../../../base/browser/ui/severityIcon/severityIcon.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { buildModalNavigationForPagedList } from '../../extensions/browser/extensionsViewer.js'; +import { IMcpGalleryManifestService } from '../../../../platform/mcp/common/mcpGalleryManifest.js'; export interface McpServerListViewOptions { showMarketplaceWelcome?: boolean; @@ -79,6 +80,7 @@ export class McpServersListView extends AbstractExtensionsListView { - if (event.affectsConfiguration(CustomizationMarketplaceConfiguration.MarketplaceEnabled) && this.isBodyVisible()) { - void this.show(this.currentQuery); + if (event.affectsConfiguration(CustomizationMarketplaceConfiguration.MarketplaceEnabled)) { + this.refreshCurrentQuery(); } })); + this._register(mcpGalleryManifestService.onDidChangeMcpGalleryManifest(() => this.refreshCurrentQuery())); } protected override renderBody(container: HTMLElement): void { @@ -214,33 +218,50 @@ export class McpServersListView extends AbstractExtensionsListView> { this.currentQuery = query; - if (this.input) { - this.input.disposables.dispose(); - this.input = undefined; - } + const queryGeneration = ++this.queryGeneration; if (this.mpcViewOptions.showMarketplaceWelcome && this.marketplaceConfigurationService.getValue(CustomizationMarketplaceConfiguration.MarketplaceEnabled) === true) { - this.input = { model: new PagedModel([]), disposables: new DisposableStore(), showWelcomeContent: true }; + const input = { model: new PagedModel([]), disposables: new DisposableStore(), showWelcomeContent: true }; + this.setInput(input); + return input.model; + } + + this.setInput({ model: new PagedModel([]), disposables: new DisposableStore() }, false); + const input = await this.query(query.trim()); + if (queryGeneration !== this.queryGeneration) { + input.disposables.dispose(); + return this.input?.model ?? new PagedModel([]); + } + this.setInput(input); + return input.model; + } + + private refreshCurrentQuery(): void { + if (this.isBodyVisible()) { + void this.show(this.currentQuery); } else { - this.input = await this.query(query.trim()); + ++this.queryGeneration; + this.setInput({ model: new PagedModel([]), disposables: new DisposableStore() }, false); } + } - this.renderInput(); + private setInput(input: IQueryResult, announce = true): void { + this.input?.disposables.dispose(); + this.input = input; + this.renderInput(announce); - if (this.input.onDidChangeModel) { - this.input.disposables.add(this.input.onDidChangeModel(model => { - if (!this.input) { + if (input.onDidChangeModel) { + input.disposables.add(input.onDidChangeModel(model => { + if (this.input !== input) { return; } - this.input.model = model; + input.model = model; this.renderInput(); })); } - - return this.input.model; } - private renderInput() { + private renderInput(announce = true) { if (!this.input) { return; } @@ -249,7 +270,7 @@ export class McpServersListView extends AbstractExtensionsListView()); readonly onNotification: Event<{ readonly method: string; readonly params?: unknown }> = this._onNotification.event; private readonly _connectionListener = this._register(new MutableDisposable()); + private readonly _disposeToken = cancelOnDispose(this._store); private _connection: IAgentConnection | undefined; constructor( @@ -182,8 +184,8 @@ class AhpMcpAppCallTransport extends Disposable implements IMcpAppCallTransport @IAgentHostConnectionsService private readonly _agentHostConnectionsService: IAgentHostConnectionsService, ) { super(); - this._updateConnection(); this._register(this._agentHostConnectionsService.onDidChangeConnections(() => this._updateConnection())); + this._updateConnection(); } private _updateConnection(): void { @@ -220,9 +222,33 @@ class AhpMcpAppCallTransport extends Disposable implements IMcpAppCallTransport } } - async loadResource(_token: CancellationToken): Promise { - const result = await this._getConnection().handleMcpRequest(this._channel, 'resources/read', { uri: this._uiData.resourceUri }) as MCP.ReadResourceResult; - return readResourceContentToHtml(result.contents); + async loadResource(token: CancellationToken): Promise { + const disposables = new DisposableStore(); + const cancellation = disposables.add(new CancellationTokenSource(token)); + disposables.add(this._disposeToken.onCancellationRequested(() => cancellation.cancel())); + try { + if (token.isCancellationRequested || this._disposeToken.isCancellationRequested) { + throw new CancellationError(); + } + const availableConnection = observableFromEvent(this, this._agentHostConnectionsService.onDidChangeConnections, () => { + this._updateConnection(); + return this._connection; + }); + let connection: IAgentConnection | undefined; + do { + await waitForState(availableConnection, connection => !!connection, undefined, cancellation.token); + if (cancellation.token.isCancellationRequested) { + throw new CancellationError(); + } + this._updateConnection(); + connection = this._connection; + } while (!connection); + const result = await connection.handleMcpRequest(this._channel, 'resources/read', { uri: this._uiData.resourceUri }) as MCP.ReadResourceResult; + return readResourceContentToHtml(result.contents); + } finally { + cancellation.cancel(); + disposables.dispose(); + } } async callTool(params: MCP.CallToolRequestParams, _token: CancellationToken): Promise { diff --git a/src/vs/workbench/contrib/mcp/browser/openPanelChatAndGetWidget.ts b/src/vs/workbench/contrib/mcp/browser/openPanelChatAndGetWidget.ts index 7b6dad43a4e4..82d080644e5e 100644 --- a/src/vs/workbench/contrib/mcp/browser/openPanelChatAndGetWidget.ts +++ b/src/vs/workbench/contrib/mcp/browser/openPanelChatAndGetWidget.ts @@ -3,25 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { raceTimeout } from '../../../../base/common/async.js'; -import { Event } from '../../../../base/common/event.js'; -import { IViewsService } from '../../../services/views/common/viewsService.js'; -import { ChatViewId, IChatWidget, IChatWidgetService } from '../../chat/browser/chat.js'; -import { ChatAgentLocation } from '../../chat/common/constants.js'; - - -export async function openPanelChatAndGetWidget(viewsService: IViewsService, chatService: IChatWidgetService): Promise { - await viewsService.openView(ChatViewId, true); - const widgets = chatService.getWidgetsByLocations(ChatAgentLocation.Chat); - if (widgets.length) { - return widgets[0]; - } - - const eventPromise = Event.toPromise(Event.filter(chatService.onDidAddWidget, e => e.location === ChatAgentLocation.Chat)); - - return await raceTimeout( - eventPromise, - 10000, // should be enough time for chat to initialize... - () => eventPromise.cancel() - ); +import { IChatWidget } from '../../chat/browser/chat.js'; +import { IChatViewHostService } from '../../chat/browser/chatViewHost.js'; + +/** + * Shows the host of the Chat view's chats, the Chat view or what replaces it, and resolves to the widget of the chat it + * shows, once it has one: not just any chat widget, such as one of a chat editor. + */ +export function openPanelChatAndGetWidget(chatViewHostService: IChatViewHostService): Promise { + return chatViewHostService.reveal(false, { waitForWidget: true }); } diff --git a/src/vs/workbench/contrib/mcp/common/mcpCommandIds.ts b/src/vs/workbench/contrib/mcp/common/mcpCommandIds.ts index a2b9a5f675a5..1dc60b41367f 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpCommandIds.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpCommandIds.ts @@ -17,6 +17,7 @@ export const enum McpCommandIds { InstallFromActivation = 'workbench.mcp.installFromActivation', ListServer = 'workbench.mcp.listServer', AgentHostServerOptions = 'workbench.mcp.agentHostServerOptions', + AuthenticateAgentHostServer = 'workbench.mcp.authenticateAgentHostServer', OpenRemoteUserMcp = 'workbench.mcp.openRemoteUserMcpJson', OpenUserMcp = 'workbench.mcp.openUserMcpJson', OpenWorkspaceFolderMcp = 'workbench.mcp.openWorkspaceFolderMcpJson', diff --git a/src/vs/workbench/contrib/mcp/test/browser/mcpCommands.test.ts b/src/vs/workbench/contrib/mcp/test/browser/mcpCommands.test.ts index ba3aa52f88e8..6d795f644042 100644 --- a/src/vs/workbench/contrib/mcp/test/browser/mcpCommands.test.ts +++ b/src/vs/workbench/contrib/mcp/test/browser/mcpCommands.test.ts @@ -5,6 +5,7 @@ import assert from 'assert'; import { constObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { McpServerStatus } from '../../../../../platform/agentHost/common/state/protocol/state.js'; @@ -15,7 +16,7 @@ import { AICustomizationManagementCommands, AICustomizationManagementSection } f import { ContributionEnablementState } from '../../../chat/common/enablement.js'; import { IExtensionsWorkbenchService } from '../../../extensions/common/extensions.js'; import { IViewsService } from '../../../../services/views/common/viewsService.js'; -import { findLocalMcpServer, McpBrowseCommand, McpBrowsePageCommand, ShowInstalledMcpServersCommand } from '../../browser/mcpCommands.js'; +import { findLocalMcpServer, McpAuthenticateAgentHostServerCommand, McpBrowseCommand, McpBrowsePageCommand, ShowInstalledMcpServersCommand } from '../../browser/mcpCommands.js'; import { IMcpServer, IMcpService, IMcpWorkbenchService, InstalledMcpServersViewId } from '../../common/mcpTypes.js'; type AgentHostMcpServer = ReturnType[number]; @@ -55,6 +56,25 @@ function agentHostServer(id: string, name: string): AgentHostMcpServer { suite('MCP commands', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('sign-in revives the linked session and authenticates its exact server directly', async () => { + const instantiationService = store.add(new TestInstantiationService()); + const sessionResource = URI.parse('agent-host-copilotcli://remote-host/other-session'); + const calls: { resource: URI; serverId: string }[] = []; + instantiationService.stub(IAgentHostCustomizationService, new class extends mock() { + override async authenticateMcpServer(resource: URI, serverId: string): Promise { + calls.push({ resource, serverId }); + return false; + } + }()); + const result = await instantiationService.invokeFunction(accessor => + new McpAuthenticateAgentHostServerCommand().run(accessor, sessionResource.toJSON(), 'session/opaque-server-id')); + + assert.deepStrictEqual({ result, calls }, { + result: false, + calls: [{ resource: sessionResource, serverId: 'session/opaque-server-id' }], + }); + }); + test('findLocalMcpServer matches exact, unambiguous definition IDs and labels', () => { const byId = new TestMcpServer('extension.server', 'Extension Server'); const byLabel = new TestMcpServer('other.server', 'Other Server'); diff --git a/src/vs/workbench/contrib/mcp/test/browser/mcpServersView.test.ts b/src/vs/workbench/contrib/mcp/test/browser/mcpServersView.test.ts new file mode 100644 index 000000000000..b3d699883a17 --- /dev/null +++ b/src/vs/workbench/contrib/mcp/test/browser/mcpServersView.test.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. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { IPagedModel, PagedModel } from '../../../../../base/common/paging.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IWorkbenchMcpServer } from '../../common/mcpTypes.js'; +import { McpServersListView } from '../../browser/mcpServersView.js'; + +interface ITestQueryResult { + model: IPagedModel; + disposables: DisposableStore; +} + +interface ITestMcpServersListView { + mpcViewOptions: { showMarketplaceWelcome?: boolean }; + marketplaceConfigurationService: Pick; + input: ITestQueryResult | undefined; + currentQuery: string; + queryGeneration: number; + query(query: string): Promise; + renderInput(announce?: boolean): void; + show(query: string): Promise>; +} + +suite('MCP Servers View', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('clears stale rows and ignores an older pending query', async () => { + const previous = createQueryResult(); + const first = createPendingQueryResult(); + const second = createPendingQueryResult(); + const renderLengths: number[] = []; + let queryCount = 0; + const view = Object.assign(Object.create(McpServersListView.prototype) as ITestMcpServersListView, { + mpcViewOptions: {}, + marketplaceConfigurationService: { getValue: () => false }, + input: previous.result, + currentQuery: '@mcp', + queryGeneration: 0, + query: () => ++queryCount === 1 ? first.promise : second.promise, + renderInput: function (this: ITestMcpServersListView) { + renderLengths.push(this.input?.model.length ?? -1); + }, + }); + + const firstShow = view.show('@mcp first'); + const clearedImmediately = view.input?.model.length; + const secondShow = view.show('@mcp second'); + second.resolve(); + await secondShow; + first.resolve(); + await firstShow; + + assert.deepStrictEqual({ + clearedImmediately, + renderLengths, + currentModel: view.input?.model, + previousDisposed: previous.disposed, + firstDisposed: first.disposed, + secondDisposed: second.disposed, + }, { + clearedImmediately: 0, + renderLengths: [0, 0, 0], + currentModel: second.result.model, + previousDisposed: true, + firstDisposed: true, + secondDisposed: false, + }); + + view.input?.disposables.dispose(); + }); + + function createQueryResult(): { result: ITestQueryResult; readonly disposed: boolean } { + let disposed = false; + const store = disposables.add(new DisposableStore()); + store.add(toDisposable(() => disposed = true)); + return { + result: { + model: new PagedModel([]), + disposables: store, + }, + get disposed() { return disposed; }, + }; + } + + function createPendingQueryResult(): { result: ITestQueryResult; promise: Promise; resolve(): void; readonly disposed: boolean } { + const queryResult = createQueryResult(); + let resolve!: (result: ITestQueryResult) => void; + const promise = new Promise(complete => resolve = complete); + return { + result: queryResult.result, + promise, + resolve: () => resolve(queryResult.result), + get disposed() { return queryResult.disposed; }, + }; + } +}); diff --git a/src/vs/workbench/contrib/mcp/test/browser/mcpToolCallUI.test.ts b/src/vs/workbench/contrib/mcp/test/browser/mcpToolCallUI.test.ts index 945c9b0d4efd..3c1e499d046b 100644 --- a/src/vs/workbench/contrib/mcp/test/browser/mcpToolCallUI.test.ts +++ b/src/vs/workbench/contrib/mcp/test/browser/mcpToolCallUI.test.ts @@ -4,15 +4,22 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; +import { isCancellationError } from '../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; import { constObservable } from '../../../../../base/common/observable.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { IAgentConnection } from '../../../../../platform/agentHost/common/agentService.js'; +import { AgentHostConnectionsService } from '../../../../../platform/agentHost/browser/agentHostConnectionsService.js'; +import { IAgentConnection, IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { agentHostAuthority, createEditorRemoteAgentHostResourceUriMapper } from '../../../../../platform/agentHost/common/agentHostUri.js'; +import { IRemoteAgentHostService } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { ServiceCollection } from '../../../../../platform/instantiation/common/serviceCollection.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; +import { IPathService } from '../../../../../platform/path/common/pathService.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; import { TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; import { McpToolCallUI } from '../../browser/mcpToolCallUI.js'; @@ -97,7 +104,123 @@ suite('McpToolCallUI', () => { }))); }); - test('routes Agent Host requests through the connection authority', async () => { + test('waits for the owning Agent Host connection before loading an app resource', async () => { + const calls: { channel: string; method: string; params: Record | undefined }[] = []; + const connection = upcastPartial({ + onMcpNotification: Event.None, + handleMcpRequest: async (channel, method, params) => { + calls.push({ channel, method, params }); + return { contents: [{ uri: 'ui://probe/app', text: 'App' }] }; + }, + }); + let remote: IAgentConnection | undefined = undefined; + const onDidChangeConnections = store.add(new Emitter()); + const instantiationService = store.add(new TestInstantiationService(new ServiceCollection( + [IAgentHostConnectionsService, upcastPartial({ + onDidChangeConnections: onDidChangeConnections.event, + getConnectionByAuthority: authority => authority === 'remote-host' ? remote : connection, + })], + [IThemeService, new TestThemeService()], + ))); + const channel = 'mcp://opaque-host-defined-channel/probe'; + const ui = store.add(instantiationService.createInstance(McpToolCallUI, { + kind: 'agentHost', resourceUri: 'ui://probe/app', connectionAuthority: 'remote-host', channel, serverId: 'probe', + })); + const pending = ui.loadResource(CancellationToken.None); + onDidChangeConnections.fire(); + assert.deepStrictEqual(calls, []); + remote = connection; + onDidChangeConnections.fire(); + onDidChangeConnections.fire(); + const loaded = await pending; + assert.deepStrictEqual({ loaded, calls }, { + loaded: { html: 'App', mimeType: 'text/html' }, + calls: [{ channel, method: 'resources/read', params: { uri: 'ui://probe/app' } }], + }); + }); + + test('loads an app through the ambient editor-remote connection', async () => { + const calls: { channel: string; method: string; params: Record | undefined }[] = []; + const remoteAuthority = 'dev-container+test'; + const authority = agentHostAuthority(`vscode-remote://${remoteAuthority}`); + const connection = upcastPartial({ + resourceUris: createEditorRemoteAgentHostResourceUriMapper(remoteAuthority, authority), + onAgentHostStart: Event.None, + onAgentHostExit: Event.None, + onMcpNotification: Event.None, + handleMcpRequest: async (channel, method, params) => { + calls.push({ channel, method, params }); + return { contents: [{ uri: 'ui://probe/app', text: 'Remote App' }] }; + }, + }); + const connectionsService = store.add(new AgentHostConnectionsService( + connection, + upcastPartial({ + connections: [], + onDidChangeConnections: Event.None, + getConnectionByAuthority: () => undefined, + }), + upcastPartial({ registerPathProvider: () => Disposable.None }), + upcastPartial({ registerFormatter: () => Disposable.None }), + )); + const instantiationService = store.add(new TestInstantiationService(new ServiceCollection( + [IAgentHostConnectionsService, connectionsService], + [IThemeService, new TestThemeService()], + ))); + const channel = 'mcp://opaque-host-defined-channel/probe'; + const ui = store.add(instantiationService.createInstance(McpToolCallUI, { + kind: 'agentHost', resourceUri: 'ui://probe/app', connectionAuthority: authority, channel, serverId: 'probe', + })); + const loaded = await ui.loadResource(CancellationToken.None); + + assert.deepStrictEqual({ loaded, calls }, { + loaded: { html: 'Remote App', mimeType: 'text/html' }, + calls: [{ channel, method: 'resources/read', params: { uri: 'ui://probe/app' } }], + }); + }); + + test('rechecks the owning Agent Host connection before dispatching a resource load', async () => { + const calls: { connection: string; channel: string; method: string; params: Record | undefined }[] = []; + const connection = (name: string) => upcastPartial({ + onMcpNotification: Event.None, + handleMcpRequest: async (channel, method, params) => { + calls.push({ connection: name, channel, method, params }); + return { contents: [{ uri: 'ui://probe/app', text: `${name}` }] }; + }, + }); + const original = connection('original'); + let remote: IAgentConnection | undefined = undefined; + const onDidChangeConnections = store.add(new Emitter()); + const instantiationService = store.add(new TestInstantiationService(new ServiceCollection( + [IAgentHostConnectionsService, upcastPartial({ + onDidChangeConnections: onDidChangeConnections.event, + getConnectionByAuthority: authority => authority === 'remote-host' ? remote : undefined, + })], + [IThemeService, new TestThemeService()], + ))); + const channel = 'mcp://opaque-host-defined-channel/probe'; + const ui = store.add(instantiationService.createInstance(McpToolCallUI, { + kind: 'agentHost', resourceUri: 'ui://probe/app', connectionAuthority: 'remote-host', channel, serverId: 'probe', + })); + const pending = ui.loadResource(CancellationToken.None); + remote = original; + onDidChangeConnections.fire(); + remote = undefined; + onDidChangeConnections.fire(); + await Promise.resolve(); + assert.deepStrictEqual(calls, []); + remote = original; + onDidChangeConnections.fire(); + remote = connection('latest'); + onDidChangeConnections.fire(); + const loaded = await pending; + assert.deepStrictEqual({ loaded, calls }, { + loaded: { html: 'latest', mimeType: 'text/html' }, + calls: [{ connection: 'latest', channel, method: 'resources/read', params: { uri: 'ui://probe/app' } }], + }); + }); + + test('routes Agent Host requests and notifications through the reconnected authority', async () => { const calls: Array<{ connection: string; channel: string; method: string; params: Record | undefined }> = []; const connection = (name: string) => { const onMcpNotification = store.add(new Emitter<{ channel: string; method: string; params?: Record }>()); @@ -120,11 +243,11 @@ suite('McpToolCallUI', () => { }; const ambient = connection('ambient'); const originalRemote = connection('remote-1'); - let remote = originalRemote; + let remote: ReturnType | undefined = originalRemote; const onDidChangeConnections = store.add(new Emitter()); const connectionsService = upcastPartial({ onDidChangeConnections: onDidChangeConnections.event, - getConnectionByAuthority: authority => authority === 'remote-host' ? remote.value : authority === 'local' ? ambient.value : undefined, + getConnectionByAuthority: authority => authority === 'remote-host' ? remote?.value : authority === 'local' ? ambient.value : undefined, }); const instantiationService = store.add(new TestInstantiationService(new ServiceCollection( [IAgentHostConnectionsService, connectionsService], @@ -143,20 +266,27 @@ suite('McpToolCallUI', () => { const first = await ui.loadResource(CancellationToken.None); originalRemote.notify(channel, 'notifications/first'); + remote = undefined; + onDidChangeConnections.fire(); + const pending = ui.loadResource(CancellationToken.None); + originalRemote.notify(channel, 'notifications/disconnected'); remote = connection('remote-2'); onDidChangeConnections.fire(); originalRemote.notify(channel, 'notifications/stale'); remote.notify('mcp://other', 'notifications/wrong-channel'); remote.notify(channel, 'notifications/second'); + const reconnected = await pending; const second = await ui.readResource('ui://github-mcp-server/details', CancellationToken.None); assert.deepStrictEqual({ first: first.html, + reconnected: reconnected.html, second: second.contents[0], calls, notifications, }, { first: 'remote-1', + reconnected: 'remote-2', second: { uri: 'ui://github-mcp-server/get-me', mimeType: 'text/html', @@ -169,6 +299,12 @@ suite('McpToolCallUI', () => { method: 'resources/read', params: { uri: 'ui://github-mcp-server/get-me' }, }, + { + connection: 'remote-2', + channel, + method: 'resources/read', + params: { uri: 'ui://github-mcp-server/get-me' }, + }, { connection: 'remote-2', channel, @@ -183,6 +319,49 @@ suite('McpToolCallUI', () => { }); }); + for (const cancel of ['caller', 'disposal'] as const) { + for (const connected of [false, true]) { + test(`cancels Agent Host app resource loading on ${cancel}${connected ? ' just after connecting' : ' while disconnected'}`, async () => { + const calls: string[] = []; + const connection = upcastPartial({ + onMcpNotification: Event.None, + handleMcpRequest: async (_channel, method) => { + calls.push(method); + return { contents: [{ uri: 'ui://probe/app', text: 'App' }] }; + }, + }); + let remote: IAgentConnection | undefined; + const onDidChangeConnections = store.add(new Emitter()); + const instantiationService = store.add(new TestInstantiationService(new ServiceCollection( + [IAgentHostConnectionsService, upcastPartial({ + onDidChangeConnections: onDidChangeConnections.event, + getConnectionByAuthority: authority => authority === 'remote-host' ? remote : undefined, + })], + [IThemeService, new TestThemeService()], + ))); + const ui = store.add(instantiationService.createInstance(McpToolCallUI, { + kind: 'agentHost', resourceUri: 'ui://probe/app', connectionAuthority: 'remote-host', channel: 'mcp://opaque-host-defined-channel/probe', serverId: 'probe', + })); + const cancellation = store.add(new CancellationTokenSource()); + const rejected = assert.rejects(ui.loadResource(cancellation.token), isCancellationError); + if (connected) { + remote = connection; + onDidChangeConnections.fire(); + } + if (cancel === 'caller') { + cancellation.cancel(); + } else { + ui.dispose(); + } + remote = connection; + onDidChangeConnections.fire(); + await rejected; + await assert.rejects(ui.loadResource(cancellation.token), isCancellationError); + assert.deepStrictEqual(calls, []); + }); + } + } + test('preserves remote MCP resource provenance across denied loads, retry and restored render data', async () => { const channel = 'mcp://opaque-host-defined-channel/github'; const resourceUri = 'ui://github-mcp-server/get-me'; @@ -217,6 +396,8 @@ suite('McpToolCallUI', () => { const ui = store.add(instantiationService.createInstance(McpToolCallUI, uiData)); await assert.rejects(ui.loadResource(CancellationToken.None), /MCP app resource is not allowed/); denied = false; + onDidChangeConnections.fire(); + onDidChangeConnections.fire(); const retried = await ui.loadResource(CancellationToken.None); ui.dispose(); const restored = store.add(instantiationService.createInstance(McpToolCallUI, { ...uiData })); diff --git a/src/vs/workbench/contrib/mcp/test/browser/openPanelChatAndGetWidget.test.ts b/src/vs/workbench/contrib/mcp/test/browser/openPanelChatAndGetWidget.test.ts new file mode 100644 index 000000000000..016fc285bc75 --- /dev/null +++ b/src/vs/workbench/contrib/mcp/test/browser/openPanelChatAndGetWidget.test.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 assert from 'assert'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ChatViewId } from '../../../chat/browser/chat.js'; +import { ChatWidget } from '../../../chat/browser/widget/chatWidget.js'; +import { IChatViewHost, IChatViewHostService } from '../../../chat/browser/chatViewHost.js'; +import { ChatViewHostService } from '../../../chat/browser/widgetHosts/viewPane/chatViewHostService.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { IViewDescriptorService } from '../../../../common/views.js'; +import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; +import { IProgressService } from '../../../../../platform/progress/common/progress.js'; +import { ChatViewPane } from '../../../chat/browser/widgetHosts/viewPane/chatViewPane.js'; +import { openPanelChatAndGetWidget } from '../../browser/openPanelChatAndGetWidget.js'; + +suite('openPanelChatAndGetWidget', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** The host service of a workbench whose Chat view shows `chatViewWidget`, where a chat editor opened before it exists. */ + function createService(chatViewWidget: ChatWidget) { + const calls: string[] = []; + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async (id: string, focus?: boolean) => { calls.push(`openView ${id} focus=${focus}`); return upcastPartial({ widget: chatViewWidget }); }) as IViewsService['openView'], + })); + instantiationService.stub(IViewDescriptorService, {}); + instantiationService.stub(IWorkbenchLayoutService, {}); + instantiationService.stub(IProgressService, {}); + return { service: instantiationService.createInstance(ChatViewHostService) as IChatViewHostService, calls }; + } + + test('returns the Chat view\'s widget, not a chat editor opened before it', async () => { + const chatViewWidget = upcastPartial({ viewContext: { viewId: ChatViewId } }); + const { service, calls } = createService(chatViewWidget); + assert.deepStrictEqual({ widget: await openPanelChatAndGetWidget(service) === chatViewWidget, calls }, { widget: true, calls: [`openView ${ChatViewId} focus=true`] }); + }); + + test('returns what a host that replaces the Chat view shows, also none, asking it to wait for its widget', async () => { + const { service, calls } = createService(upcastPartial({})); + const registration = service.registerHost(upcastPartial({ + reveal: async (preserveFocus, options) => { calls.push(`reveal preserveFocus=${preserveFocus} waitForWidget=${options?.waitForWidget}`); return undefined; }, + })); + const widget = await openPanelChatAndGetWidget(service); + registration.dispose(); + assert.deepStrictEqual({ widget, calls }, { widget: undefined, calls: ['reveal preserveFocus=false waitForWidget=true'] }); + }); +}); diff --git a/src/vs/workbench/contrib/mediaPreview/browser/mediaPlayerEditorInput.ts b/src/vs/workbench/contrib/mediaPreview/browser/mediaPlayerEditorInput.ts index f0b1e3ec9c97..a4d0cfc212b6 100644 --- a/src/vs/workbench/contrib/mediaPreview/browser/mediaPlayerEditorInput.ts +++ b/src/vs/workbench/contrib/mediaPreview/browser/mediaPlayerEditorInput.ts @@ -6,6 +6,9 @@ import { RunOnceScheduler } from '../../../../base/common/async.js'; import { Emitter } from '../../../../base/common/event.js'; import { escapeDoubleQuotes } from '../../../../base/common/htmlContent.js'; +import { getMediaMime } from '../../../../base/common/mime.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { isNative } from '../../../../base/common/platform.js'; import { basename, dirname, isEqual } from '../../../../base/common/resources.js'; import { escape } from '../../../../base/common/strings.js'; import { URI } from '../../../../base/common/uri.js'; @@ -16,6 +19,7 @@ import { IFileDialogService } from '../../../../platform/dialogs/common/dialogs. import { FileChangesEvent, FileChangeType, IFileService } from '../../../../platform/files/common/files.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ILabelService } from '../../../../platform/label/common/label.js'; +import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IThemeService } from '../../../../platform/theme/common/themeService.js'; import { EditorInputCapabilities, GroupIdentifier, IMoveResult, ISaveOptions, IUntypedEditorInput, Verbosity } from '../../../common/editor.js'; import { IResourceEditorInput } from '../../../../platform/editor/common/editor.js'; @@ -36,6 +40,18 @@ export type MediaPlayerKind = 'audio' | 'video'; // happens after normal playback failed const maxMediaSourceSize = 200 * 1024 * 1024; +/** + * Button below a codec warning, which sends a message of the given type to the editor input when clicked. + */ +interface ICodecWarningAction { + readonly label: string; + readonly message: 'open-externally' | 'reopen-as-text'; +} + +function getOpenInTextEditorLabel(): string { + return localize('mediaPreview.openInTextEditor', "Open in Text Editor"); +} + export function isMediaPlayerKind(value: unknown): value is MediaPlayerKind { return value === 'audio' || value === 'video'; } @@ -92,14 +108,17 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito @IEditorService private readonly _editorService: IEditorService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IFileDialogService private readonly _fileDialogService: IFileDialogService, + @IOpenerService private readonly _openerService: IOpenerService, ) { super({ viewType: getMediaPlayerEditorId(kind), providedId: undefined, name: basename(_resource), iconPath: undefined }, webview, themeService); this._register(webview.onMessage(e => { if (e.message?.type === 'reopen-as-text') { void reopenInTextEditor(this, this._editorService); - } else if (e.message?.type === 'get-audio-codecs') { - void this._postAudioCodecs(); + } else if (e.message?.type === 'open-externally') { + this._openExternally(); + } else if (e.message?.type === 'get-codecs') { + void this._postCodecs(); } else if (e.message?.type === 'get-webm-type') { void this._postWebmType(); } @@ -224,24 +243,34 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito } /** - * Sends the audio codecs of the file to the webview, which warns if it can't play any of them. - * The webview requests them whenever its content loads, so the warning survives the webview - * being recreated, such as when the editor moves to another window. + * Sends the video and audio codecs of the file to the webview, which warns if it can't play any + * codec of a kind. The webview requests them whenever its content loads, so the warning survives + * the webview being recreated, such as when the editor moves to another window. */ - private async _postAudioCodecs(): Promise { + private async _postCodecs(): Promise { const mediaInfo = this._mediaInfo; const info = await mediaInfo; - const audioTracks = info?.tracks.filter(track => track.kind === 'audio') ?? []; // The webview of a newer render requests its own codecs - if (!info || !audioTracks.length || this.isDisposed() || mediaInfo !== this._mediaInfo) { + if (!info || this.isDisposed() || mediaInfo !== this._mediaInfo) { return; } - void this.webview.postMessage({ - type: 'audio-codecs', - mimeTypes: audioTracks.map(track => `audio/${info.container}; codecs="${track.codec}"`), - warning: this._getUnsupportedCodecWarning(audioTracks[0]), - }); + const openExternally: ICodecWarningAction[] = this._canOpenExternally() ? [{ label: localize('mediaPreview.openExternally', "Open File"), message: 'open-externally' }] : []; + const openInTextEditor: ICodecWarningAction = { label: getOpenInTextEditorLabel(), message: 'reopen-as-text' }; + const getCodecs = (kind: IMediaTrack['kind']) => { + const tracks = info.tracks.filter(track => track.kind === kind); + return tracks.length ? { + mimeTypes: tracks.map(track => `${kind}/${info.container}; codecs="${track.codec}"`), + warning: this._getUnsupportedCodecWarning(tracks[0]), + // Only a file whose own kind of track can't be played fails to load + actions: kind === this.kind ? [...openExternally, openInTextEditor] : openExternally, + } : undefined; + }; + const video = this.kind === 'video' ? getCodecs('video') : undefined; + const audio = getCodecs('audio'); + if (video || audio) { + void this.webview.postMessage({ type: 'codecs', video, audio }); + } } /** @@ -265,14 +294,35 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito } private _getUnsupportedCodecWarning(track: IMediaTrack): string { + if (track.kind === 'video') { + return track.name + ? localize('videoPreview.unsupportedVideoCodec', "This video uses the {0} codec, which can't be played in the video preview.", track.name) + : localize('videoPreview.unsupportedUnknownVideoCodec', "This video uses a codec that can't be played in the video preview."); + } if (this.kind === 'audio') { return track.name - ? localize('audioPreview.unsupportedCodec', "This audio file uses the {0} codec, which can't be played in the audio preview. Open the file in an external application to listen to it.", track.name) - : localize('audioPreview.unsupportedUnknownCodec', "This audio file uses a codec that can't be played in the audio preview. Open the file in an external application to listen to it."); + ? localize('audioPreview.unsupportedCodec', "This audio file uses the {0} codec, which can't be played in the audio preview.", track.name) + : localize('audioPreview.unsupportedUnknownCodec', "This audio file uses a codec that can't be played in the audio preview."); } return track.name - ? localize('videoPreview.unsupportedAudioCodec', "This video's audio uses the {0} codec, which can't be played in the video preview. Open the file in an external application to hear its audio.", track.name) - : localize('videoPreview.unsupportedUnknownAudioCodec', "This video's audio uses a codec that can't be played in the video preview. Open the file in an external application to hear its audio."); + ? localize('videoPreview.unsupportedAudioCodec', "This video's audio uses the {0} codec, which can't be played in the video preview.", track.name) + : localize('videoPreview.unsupportedUnknownAudioCodec', "This video's audio uses a codec that can't be played in the video preview."); + } + + /** + * Whether the file can be opened in the application the OS associates with it. The OS picks that + * application by the file's extension and the preview can show any file, so only files with a + * media extension are opened, never ones that the OS would run. + */ + private _canOpenExternally(): boolean { + const mimeType = getMediaMime(this._resource.path); + return isNative && this._resource.scheme === Schemas.file && !!mimeType && /^(audio|video)\//.test(mimeType); + } + + private _openExternally(): void { + if (this._canOpenExternally()) { + void this._openerService.open(this._resource, { openExternal: true }); + } } private async _updateFileSize(): Promise { @@ -313,7 +363,7 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito // The file only contains a pointer to the media, so don't try to play it media = ''; } - const openInTextEditor = localize('mediaPreview.openInTextEditor', "Open in Text Editor"); + const openInTextEditor = getOpenInTextEditorLabel(); return /* html */` @@ -343,15 +393,52 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito max-height: 100%; min-height: 0; } - .codec-warning:not(:empty) { + .codec-warning { flex-shrink: 0; max-width: 600px; - margin-bottom: var(--vscode-spacing-size80); + display: flex; + flex-direction: column; + align-items: center; + gap: var(--vscode-spacing-size120); + } + /* Separates the warning from media that still plays, such as a video whose audio can't be played */ + body:not(.error) .codec-warning:has(.codec-warning-message:not(:empty)) { + margin-bottom: var(--vscode-spacing-size120); + } + .codec-warning-actions { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: var(--vscode-spacing-size80); + } + .codec-warning-actions:empty { + display: none; + } + .codec-warning-actions button { padding: var(--vscode-spacing-size40) var(--vscode-spacing-size80); - border: var(--vscode-strokeThickness) solid var(--vscode-inputValidation-warningBorder); + border: var(--vscode-strokeThickness) solid var(--vscode-button-border, transparent); border-radius: var(--vscode-cornerRadius-small); - color: var(--vscode-inputValidation-warningForeground); - background-color: var(--vscode-inputValidation-warningBackground); + color: var(--vscode-button-foreground); + background-color: var(--vscode-button-background); + font-family: inherit; + font-size: var(--vscode-fontSize-label1); + line-height: 16px; + cursor: pointer; + } + .codec-warning-actions button:hover { + background-color: var(--vscode-button-hoverBackground); + } + .codec-warning-actions button.secondary { + border-color: var(--vscode-button-secondaryBorder, var(--vscode-button-border, transparent)); + color: var(--vscode-button-secondaryForeground); + background-color: var(--vscode-button-secondaryBackground); + } + .codec-warning-actions button.secondary:hover { + background-color: var(--vscode-button-secondaryHoverBackground); + } + .codec-warning-actions button:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: 2px; } .load-error { display: none; @@ -363,14 +450,17 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito body.error .load-error { display: block; } - /* An audio file without a playable codec fails to load, which the codec warning already explains */ - body.error.unsupported-codec:has(audio) .load-error-message { + /* Media whose own kind of track can't be played fails to load, which the codec warning already explains */ + body.error.unsupported-codec .load-error { display: none; } -
+
+
+
+
${media}

${escape(errorMessage)}

@@ -382,16 +472,30 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito const media = document.querySelector('audio, video'); const showError = () => document.body.classList.add('error'); - // Browsers silently drop audio tracks they can't decode, so warn about them instead of - // letting the file seem broken - const checkAudioCodecs = ({ mimeTypes, warning }) => { + // Browsers don't explain why a file fails to load and silently drop audio tracks they can't + // decode, so warn about codecs that can't be played instead of letting the file seem broken + const showCodecWarning = ({ warning, actions }) => { + document.querySelector('.codec-warning-message').textContent = warning; + document.querySelector('.codec-warning-actions').replaceChildren(...actions.map(({ label, message }, index) => { + const button = document.createElement('button'); + button.textContent = label; + // The first action is the main one + button.classList.toggle('secondary', index > 0); + button.addEventListener('click', () => vscode.postMessage({ type: message })); + return button; + })); + }; + const checkCodecs = ({ video, audio }) => { if (!media) { return; } const canPlay = type => media.canPlayType(type) !== '' || (typeof MediaSource !== 'undefined' && MediaSource.isTypeSupported(type)); - if (!mimeTypes.some(canPlay)) { - document.querySelector('.codec-warning').textContent = warning; - document.body.classList.add('unsupported-codec'); + const isUnsupported = codecs => codecs && !codecs.mimeTypes.some(canPlay); + // The audio of a video that can't be played doesn't matter + const unsupported = isUnsupported(video) ? video : isUnsupported(audio) ? audio : undefined; + if (unsupported) { + showCodecWarning(unsupported); + document.body.classList.toggle('unsupported-codec', unsupported === (media instanceof HTMLVideoElement ? video : audio)); } }; @@ -466,13 +570,13 @@ export class MediaPlayerEditorInput extends WebviewInput implements ICustomEdito }; window.addEventListener('message', e => { - if (e.data?.type === 'audio-codecs') { - checkAudioCodecs(e.data); + if (e.data?.type === 'codecs') { + checkCodecs(e.data); } else if (e.data?.type === 'webm-type') { resolveWebmType?.(e.data.mimeType); } }); - vscode.postMessage({ type: 'get-audio-codecs' }); + vscode.postMessage({ type: 'get-codecs' }); let triedMediaSource = false; media?.addEventListener('error', () => { diff --git a/src/vs/workbench/contrib/mediaPreview/test/browser/mediaPreviewEditorInputs.test.ts b/src/vs/workbench/contrib/mediaPreview/test/browser/mediaPreviewEditorInputs.test.ts index 734274e37020..da294099362d 100644 --- a/src/vs/workbench/contrib/mediaPreview/test/browser/mediaPreviewEditorInputs.test.ts +++ b/src/vs/workbench/contrib/mediaPreview/test/browser/mediaPreviewEditorInputs.test.ts @@ -9,6 +9,7 @@ import { VSBuffer } from '../../../../../base/common/buffer.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../base/common/network.js'; +import { isNative } from '../../../../../base/common/platform.js'; import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; @@ -21,6 +22,7 @@ import { IFileDialogService } from '../../../../../platform/dialogs/common/dialo import { FileChangesEvent, FileChangeType, IFileContent, IFileService, IFileStatWithMetadata } from '../../../../../platform/files/common/files.js'; import { EditorInput } from '../../../../common/editor/editorInput.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IOpenerService, OpenOptions } from '../../../../../platform/opener/common/opener.js'; import { IOverlayWebview, WebviewMessageReceivedEvent } from '../../../webview/browser/webview.js'; import { isCustomEditorCompatibleInput } from '../../../customEditor/common/customEditor.js'; import { AUDIO_PREVIEW_EDITOR_ID, IMAGE_PREVIEW_EDITOR_ID, VIDEO_PREVIEW_EDITOR_ID } from '../../common/mediaPreview.js'; @@ -178,7 +180,15 @@ suite('Media Preview - MediaPlayerEditorInput', () => { fileService.stat = async resource => ({ resource, size: reportedSize } as IFileStatWithMetadata); fileService.readFile = async resource => ({ resource, value: buffer, size: buffer.byteLength } as IFileContent); - const webview = { html: '', onMessage: disposables.add(new Emitter()), message: new DeferredPromise() }; + const webview = { html: '', onMessage: disposables.add(new Emitter()), message: new DeferredPromise(), openedExternally: [] as string[] }; + instantiationService.stub(IOpenerService, new class extends mock() { + override async open(target: URI | string, options?: OpenOptions) { + if (options?.openExternal) { + webview.openedExternally.push(target.toString()); + } + return true; + } + }); const input = disposables.add(instantiationService.createInstance(MediaPlayerEditorInput, kind, resource, new class extends mock() { override readonly onMessage = webview.onMessage.event; override setHtml(value: string) { webview.html = value; } @@ -192,22 +202,70 @@ suite('Media Preview - MediaPlayerEditorInput', () => { return webview; } + // Files can only be opened in an external application on desktop + const openFile = isNative ? [{ label: 'Open File', message: 'open-externally' }] : []; + const openInTextEditor = { label: 'Open in Text Editor', message: 'reopen-as-text' }; + test('sends the audio codecs to the webview on request, which warns if it cannot play them', async () => { const disposables = store.add(new DisposableStore()); // A WAV file with GSM 6.10 audio const webview = await createMediaPlayer(disposables, 'audio', URI.file('/media/voice.wav'), wav(uint16LE(0x0031))); - webview.onMessage.fire({ message: { type: 'get-audio-codecs' } }); + webview.onMessage.fire({ message: { type: 'get-codecs' } }); assert.deepStrictEqual({ - hasWarningRegion: webview.html.includes('
'), + hasWarningRegion: webview.html.includes('
'), message: await webview.message.p, }, { hasWarningRegion: true, message: { - type: 'audio-codecs', - mimeTypes: ['audio/wav; codecs="49"'], - warning: 'This audio file uses the GSM 6.10 codec, which can\'t be played in the audio preview. Open the file in an external application to listen to it.', + type: 'codecs', + video: undefined, + audio: { + mimeTypes: ['audio/wav; codecs="49"'], + warning: 'This audio file uses the GSM 6.10 codec, which can\'t be played in the audio preview.', + actions: [...openFile, openInTextEditor], + }, + }, + }); + }); + + test('sends the video codecs of a WebM file to the webview on request, which warns if it cannot play them', async () => { + const disposables = store.add(new DisposableStore()); + const webview = await createMediaPlayer(disposables, 'video', URI.file('/media/clip.webm'), webm([1, 'V_VP9'], [2, 'A_OPUS'])); + webview.onMessage.fire({ message: { type: 'get-codecs' } }); + + // Only a video that can't be played fails to load, so only its warning offers the text editor + assert.deepStrictEqual(await webview.message.p, { + type: 'codecs', + video: { + mimeTypes: ['video/webm; codecs="vp9"'], + warning: 'This video uses the VP9 codec, which can\'t be played in the video preview.', + actions: [...openFile, openInTextEditor], }, + audio: { + mimeTypes: ['audio/webm; codecs="opus"'], + warning: 'This video\'s audio uses the Opus codec, which can\'t be played in the video preview.', + actions: openFile, + }, + }); + }); + + test('opens only local media files in an external application from the codec warning', async () => { + const disposables = store.add(new DisposableStore()); + const result: Record = {}; + // The preview can show any file, such as a script disguised as a video, which the OS would run + for (const resource of [URI.file('/media/clip.webm'), URI.file('/media/clip.command'), URI.from({ scheme: Schemas.vscodeRemote, authority: 'host', path: '/media/clip.webm' })]) { + const webview = await createMediaPlayer(disposables, 'video', resource, webm([1, 'V_VP9'])); + webview.onMessage.fire({ message: { type: 'get-codecs' } }); + const message = await webview.message.p as { video: { actions: { message: string }[] } }; + webview.onMessage.fire({ message: { type: 'open-externally' } }); + result[resource.toString()] = { offersOpenFile: message.video.actions.some(action => action.message === 'open-externally'), openedExternally: webview.openedExternally }; + } + + assert.deepStrictEqual(result, { + 'file:///media/clip.webm': { offersOpenFile: isNative, openedExternally: isNative ? ['file:///media/clip.webm'] : [] }, + 'file:///media/clip.command': { offersOpenFile: false, openedExternally: [] }, + 'vscode-remote://host/media/clip.webm': { offersOpenFile: false, openedExternally: [] }, }); }); diff --git a/src/vs/workbench/contrib/mergeEditor/browser/view/media/mergeEditor.css b/src/vs/workbench/contrib/mergeEditor/browser/view/media/mergeEditor.css index 6ed544a06c04..0ab9f6f1f8c6 100644 --- a/src/vs/workbench/contrib/mergeEditor/browser/view/media/mergeEditor.css +++ b/src/vs/workbench/contrib/mergeEditor/browser/view/media/mergeEditor.css @@ -188,7 +188,7 @@ .accept-conflict-group.monaco-custom-toggle { height: 18px; width: 18px; - border-radius: 3px; + border-radius: var(--workbench-custom-controls-corner-radius, 3px); margin-right: 0px; margin-left: 0px; padding: 0px; diff --git a/src/vs/workbench/contrib/modernUI/README.md b/src/vs/workbench/contrib/modernUI/README.md index 9be58e964f3f..12ff38ab3233 100644 --- a/src/vs/workbench/contrib/modernUI/README.md +++ b/src/vs/workbench/contrib/modernUI/README.md @@ -24,6 +24,18 @@ Editor and workbench suggestion menus use the Outer radius on their first item's - `connected` (default): the bottom row's active tab joins the editor surface with an outside stroke and curved shoulders. Active caps touching the left frame omit their own left stroke and outside shoulder; the editor frame paints that edge once. Inactive tabs, upper wrapped rows, and a separate pinned row retain symmetric rounded pills. Active caps own their rounded top outline independently of the editor frame. - `pill`: separate rounded tabs, without the connected stroke or shoulders. +In the editor window, this selection also applies to the Panel, Primary Side Bar, and Secondary Side Bar tab strips, for both text and icon labels, including the top and bottom Activity Bar positions. Connected headers continue the recessed tab-strip background through their toolbar actions, while the selected tab opens into its panel's own background. Selected caps fill the header height, with generous internal padding for text and icon labels; overflow controls retain their compact sizing. The first tab meets the frame without a second leading stroke or shoulder, and floating caps share the card's snapped perimeter stroke rather than drawing a second inset line. Bottom-positioned strips connect upward. Accounts, Settings, inactive tabs, and overflow actions remain separate controls. High-contrast themes retain explicit connected borders and keyboard-focus indicators. These panel and horizontal Activity Bar styles do not change the Agents window. + +Connected pane and horizontal Activity Bar caps use the same convex corner radius as editor tabs. Concave shoulder radii remain independent and stable through focus changes. Floating caps can paint beyond their header or footer to the card's rounded outer edge. At a rounded frame-touching corner, the first cap's fill follows the frame and leaves its curved stroke visible; the cap retains its own straight perimeter stroke. Square compact and Activity Bar joins retain their existing treatment. If a compact menu precedes the tab strip, the first tab retains its own leading stroke, rounded cap, and shoulder until the menu is removed. + +The default vertical Activity Bar retains its existing selection, hover, background colors, sizing, and overflow behavior independently of the editor tab style. + +Horizontal connected pane tabs use the editor's `tab.divider` color for subtle inset separators between adjacent inactive tabs. The default vertical Activity Bar remains separator-free. Dividers are omitted next to the selected tab, before overflow controls, and during drag-and-drop. + +Appearance changes made while a pane is hidden defer tab remeasurement until its next visible layout, so reopening a narrow pane retains correct overflow. + +Icon hover fills stay square and centered within their wider hit targets; text hover fills follow the label width. Cap outlines stop at the shoulder tangents so straight side strokes cannot cross the curved connection; footer tabs mirror this join upward. Their separator belongs to the top edge, while the card frame alone owns the bottom boundary. Legacy active-tab underline colors and resets do not paint connected strokes. Keyboard focus uses a separate outline without recoloring a structural shoulder. + In high-contrast themes, the Pill tab fill owns the entire outer hover or focus stroke, including behind the Close action. The outer focus stroke remains visible when focus moves to Close. The action overlay does not redraw that stroke; the Close button retains its own hover and keyboard-focus outline. Changes apply immediately, including in auxiliary editor windows. The Agents window follows the same setting for chat and side-panel tabs, independently of the broader Modern UI setting. Connected tabs are the default in both windows; select `pill` to restore the separate rounded tabs. diff --git a/src/vs/workbench/contrib/modernUI/browser/media/activityBar.css b/src/vs/workbench/contrib/modernUI/browser/media/activityBar.css index 2cf85c558a39..c13e3969349e 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/activityBar.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/activityBar.css @@ -150,7 +150,7 @@ } /* Active item: inset, rounded background box behind the icon. */ -.modern-ui .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar .action-item.icon.checked:not(:active) .active-item-indicator { +.modern-ui:where(:not(.modern-ui-connected-editor-tabs), .agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar .action-item.icon.checked:not(:active) .active-item-indicator { z-index: 0; top: 50%; left: var(--vscode-spacing-size20); @@ -165,7 +165,7 @@ * shows the box) and while dragging (the action-item `::before`/`::after` are * reused for the drop-line indicators). */ -.modern-ui .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar .action-item.icon:not(.checked):not(:active):hover .active-item-indicator { +.modern-ui:where(:not(.modern-ui-connected-editor-tabs), .agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar .action-item.icon:not(.checked):not(:active):hover .active-item-indicator { z-index: 0; top: 50%; left: var(--vscode-spacing-size20); @@ -271,21 +271,21 @@ overflow: visible; } -.modern-ui.monaco-workbench .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { bottom: 8px; border-radius: var(--vscode-cornerRadius-small); } -.modern-ui.monaco-workbench .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:focus .active-item-indicator:before { +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.header > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:focus .active-item-indicator:before { bottom: 0; } -.modern-ui.monaco-workbench .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:focus .active-item-indicator:before { border-radius: var(--vscode-cornerRadius-small); top: 3px; } -.modern-ui.monaco-workbench .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:focus .active-item-indicator:before { +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer.footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:focus .active-item-indicator:before { top: 0; } .modern-ui.monaco-workbench .activitybar > .content :not(.monaco-menu) > .monaco-action-bar .profile-badge .profile-text-overlay { diff --git a/src/vs/workbench/contrib/modernUI/browser/media/connectedEditorTabs.css b/src/vs/workbench/contrib/modernUI/browser/media/connectedEditorTabs.css index 15ab844450c5..b50b5ad3e1a4 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/connectedEditorTabs.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/connectedEditorTabs.css @@ -578,9 +578,9 @@ outline-offset: calc(-1 * var(--vscode-strokeThickness)); } -/* Let the complete filename ellipsize before the action column. */ -.modern-ui-tabs.modern-ui-connected-editor-tabs.monaco-workbench .part.editor > .content .editor-group-container > .title.tabs .tabs-container > .tab:is(.sizing-fixed, .sizing-shrink):not(.sticky-compact) { - min-width: max(80px, var(--tab-sizing-fixed-min-width, 0px)); +/* Honor fixed sizing instead of the legacy leading-action minimum. */ +.modern-ui-tabs.modern-ui-connected-editor-tabs.monaco-workbench .part.editor > .content .editor-group-container > .title.tabs .tabs-container > .tab.sizing-fixed.tab-actions-left:not(.sticky-compact):not(.sticky-shrink) { + min-width: var(--tab-sizing-current-width, var(--tab-sizing-fixed-min-width, 50px)); } .modern-ui-tabs.modern-ui-connected-editor-tabs.monaco-workbench .part.editor > .content .editor-group-container > .title.tabs .tabs-container > .tab:not(.active):not(.dirty):not(:hover):not(.sticky):not(:focus-within) > .tab-actions .action-label { diff --git a/src/vs/workbench/contrib/modernUI/browser/media/connectedPaneTabs.css b/src/vs/workbench/contrib/modernUI/browser/media/connectedPaneTabs.css new file mode 100644 index 000000000000..b1fa0ebefa4d --- /dev/null +++ b/src/vs/workbench/contrib/modernUI/browser/media/connectedPaneTabs.css @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) { + --modern-ui-connected-tab-cap-radius: calc(var(--vscode-cornerRadius-medium, var(--vscode-cornerRadius-small)) + var(--vscode-strokeThickness)); + --modern-ui-connected-tab-shoulder-radius: calc(var(--vscode-cornerRadius-medium) + var(--vscode-strokeThickness)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part { + overflow: clip; + overflow-clip-margin: border-box; +} + +/* The inset clip also keeps hit testing within the card in browsers without overflow-clip-margin. */ +@supports (clip-path: inset(0 round 0)) and (not (overflow-clip-margin: border-box)) { + .modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part { + overflow: visible; + clip-path: inset(0 round + var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius, var(--vscode-cornerRadius-large))) + var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius, var(--vscode-cornerRadius-large))) + var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius, var(--vscode-cornerRadius-large)))) + var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius, var(--vscode-cornerRadius-large))))); + } + + .modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels.modern-ui-compact:not(.agent-sessions-workbench) .pane-composite-part { + clip-path: inset(0); + } + +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part { + --modern-ui-connected-pane-radius: var(--vscode-cornerRadius-large); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part.panel { + --modern-ui-connected-pane-radius: var(--vscode-toolsPanel-cornerRadius, var(--vscode-cornerRadius-large)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part.sidebar { + --modern-ui-connected-pane-radius: var(--vscode-primarySideBar-cornerRadius, var(--vscode-cornerRadius-large)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part.auxiliarybar { + --modern-ui-connected-pane-radius: var(--vscode-secondarySideBar-cornerRadius, var(--vscode-cornerRadius-large)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact):not(.noactivitybar) .pane-composite-part.sidebar.left { + --modern-ui-connected-pane-frame-radius: 0px; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.noactivitybar) .pane-composite-part.sidebar.right { + --modern-ui-connected-pane-right-radius: 0px; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.mac.floating-panels.nostatusbar:not(.web):not(.fullscreen):not(.modern-ui-compact):not(.agent-sessions-workbench) .pane-composite-part.floating-part-outer-left.floating-part-outer-bottom { + --modern-ui-connected-pane-bottom-left-radius: var(--modern-ui-window-corner-radius); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.mac.floating-panels.nostatusbar:not(.web):not(.fullscreen):not(.modern-ui-compact):not(.agent-sessions-workbench) .pane-composite-part.floating-part-outer-right.floating-part-outer-bottom { + --modern-ui-connected-pane-bottom-right-radius: var(--modern-ui-window-corner-radius); +} + +/* Content-box offsets and border-box translations align the repaint with the native frame at any scale. */ +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part:not(.has-footer) { + position: relative; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part:not(.has-footer)::before, +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part:not(.has-footer)::after { + content: ''; + position: absolute; + z-index: 4; + box-sizing: content-box; + border: inherit; + border-top: 0; + pointer-events: none; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part:not(.has-footer)::before { + left: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)))); + bottom: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)))); + width: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)))); + height: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)))); + border-right: 0; + border-radius: 0 0 0 var(--modern-ui-connected-pane-bottom-left-radius, var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius))); + translate: -100% 100%; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part:not(.has-footer)::after { + right: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius)))); + bottom: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius)))); + width: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius)))); + height: max(var(--modern-ui-floating-card-stroke-width), var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius)))); + border-left: 0; + border-radius: 0 0 var(--modern-ui-connected-pane-bottom-right-radius, var(--modern-ui-connected-pane-right-radius, var(--modern-ui-connected-pane-radius))); + translate: 100% 100%; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.mac.floating-panels.nostatusbar:not(.web):not(.fullscreen):not(.modern-ui-compact):not(.agent-sessions-workbench) .pane-composite-part.floating-part-outer-left.floating-part-outer-bottom > .footer { + --modern-ui-connected-pane-frame-radius: var(--modern-ui-window-corner-radius); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part > :is(.title:first-child, .header) { + border-top-left-radius: inherit; + border-top-right-radius: inherit; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part > .footer { + border-bottom-left-radius: inherit; + border-bottom-right-radius: inherit; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .composite-bar-container > .composite-bar > .monaco-action-bar > .actions-container > .action-item > .tab-divider { + top: 50%; + left: 0; + z-index: 9; + width: var(--vscode-strokeThickness); + height: var(--vscode-spacing-size160); + background-color: var(--vscode-tab-divider, transparent); + transform: translateY(-50%); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar > .actions-container > .action-item:not(.checked):not([aria-haspopup]) + .action-item:not(.checked):not([aria-haspopup]) > .tab-divider { + display: block; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) :is(.part.sidebar, .part.auxiliarybar) { + --modern-ui-connected-tab-surface: var(--vscode-sideBar-background); + --modern-ui-connected-tab-border: var(--vscode-modernPanel-border, var(--vscode-sideBar-border, transparent)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .part.panel { + --modern-ui-connected-tab-surface: var(--vscode-panel-background); + --modern-ui-connected-tab-border: var(--vscode-modernPanel-border, var(--vscode-panel-border, transparent)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench):is(.hc-black, .hc-light) :is(.part.sidebar, .part.auxiliarybar, .part.panel) { + --modern-ui-connected-tab-border: var(--vscode-contrastBorder); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title.has-composite-bar, .header-or-footer) { + padding-left: 0; + background-image: linear-gradient(var(--modern-ui-connected-tab-strip-background), var(--modern-ui-connected-tab-strip-background)); + box-shadow: inset 0 calc(-1 * var(--vscode-strokeThickness)) var(--modern-ui-connected-tab-border); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > .header-or-footer.footer { + overflow: visible; + box-shadow: inset 0 var(--vscode-strokeThickness) var(--modern-ui-connected-tab-border); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > :is(.title-actions, .global-actions, .global-actions-left) { + background-color: transparent; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item { + border-block-width: 0; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:not(.icon) { + padding-inline: var(--vscode-spacing-size160); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.icon:not([aria-haspopup]) { + flex-basis: var(--vscode-spacing-size360); + width: var(--vscode-spacing-size360); + min-width: var(--vscode-spacing-size360); + max-width: var(--vscode-spacing-size360); + padding-inline: var(--vscode-spacing-size100); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.icon:not(.checked) > .active-item-indicator { + top: 50%; + bottom: auto; + left: 50%; + right: auto; + width: var(--vscode-spacing-size240); + height: var(--vscode-spacing-size240); + transform: translate(-50%, -50%); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked { + --modern-ui-tab-active-background: var(--modern-ui-connected-tab-surface); + z-index: 1; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator { + top: 0; + bottom: 0; + left: 0; + right: 0; + height: auto; + box-sizing: border-box; + background-color: var(--modern-ui-connected-tab-surface); + border: var(--vscode-strokeThickness) solid transparent; + border-bottom: 0; + border-radius: var(--modern-ui-connected-tab-cap-radius) var(--modern-ui-connected-tab-cap-radius) 0 0; + transform: none; + overflow: visible; + pointer-events: none; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator { + top: calc(-1 * var(--modern-ui-floating-card-stroke-width)); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar:first-child > .monaco-action-bar .action-item.checked:first-child > .active-item-indicator { + border-left-width: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} + +/* Keep the frame's curved corner visible without clipping the cap's straight perimeter. */ +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar:first-child > .monaco-action-bar .action-item.checked:first-child > .active-item-indicator { + background-clip: padding-box; + border-top-left-radius: max(0px, calc(var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)) - var(--modern-ui-floating-card-stroke-width))) var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)); +} + +/* Straight cap strokes stop at the tangents; the shoulders own the curved join. */ +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator > .tab-connected-edge { + display: block; + position: absolute; + inset: calc(-1 * var(--modern-ui-floating-card-stroke-width, var(--vscode-strokeThickness))) calc(-1 * var(--modern-ui-floating-card-stroke-width, var(--vscode-strokeThickness))) 0; + box-sizing: border-box; + border: var(--vscode-strokeThickness) solid var(--modern-ui-connected-tab-border); + border-bottom: 0; + border-radius: inherit; + clip-path: inset(0 0 var(--modern-ui-connected-tab-shoulder-radius)); + pointer-events: none; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar:first-child > .monaco-action-bar .action-item.checked:first-child > .active-item-indicator > .tab-connected-edge { + left: 0; + border-left-width: 0; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench):not(.modern-ui-compact) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar:first-child > .monaco-action-bar .action-item.checked:first-child > .active-item-indicator > .tab-connected-edge { + clip-path: inset(0 0 var(--modern-ui-connected-tab-shoulder-radius) max(0px, calc(var(--modern-ui-connected-pane-frame-radius, var(--modern-ui-connected-pane-radius)) - var(--modern-ui-floating-card-stroke-width)))); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator::before, +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator::after { + content: ''; + display: block; + position: absolute; + top: auto; + bottom: 0; + width: var(--modern-ui-connected-tab-shoulder-radius); + height: var(--modern-ui-connected-tab-shoulder-radius); + box-sizing: border-box; + border: 0; + border-radius: 0; + border-bottom: var(--vscode-strokeThickness) solid var(--modern-ui-connected-tab-border); + clip-path: inset(0); + pointer-events: none; +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator::before { + right: 100%; + left: auto; + border-right: var(--vscode-strokeThickness) solid var(--modern-ui-connected-tab-border); + border-bottom-right-radius: var(--modern-ui-connected-tab-shoulder-radius); + box-shadow: calc(var(--modern-ui-connected-tab-shoulder-radius) / 2) calc(var(--modern-ui-connected-tab-shoulder-radius) / 2) 0 calc(var(--modern-ui-connected-tab-shoulder-radius) / 2) var(--modern-ui-connected-tab-surface); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator::after { + left: 100%; + border-left: var(--vscode-strokeThickness) solid var(--modern-ui-connected-tab-border); + border-bottom-left-radius: var(--modern-ui-connected-tab-shoulder-radius); + box-shadow: calc(var(--modern-ui-connected-tab-shoulder-radius) / -2) calc(var(--modern-ui-connected-tab-shoulder-radius) / 2) 0 calc(var(--modern-ui-connected-tab-shoulder-radius) / 2) var(--modern-ui-connected-tab-surface); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar:first-child > .monaco-action-bar .action-item.checked:first-child > .active-item-indicator::before { + content: none; +} + +/* Footer tabs open upward; their labels and badges keep their normal orientation. */ +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench:not(.agent-sessions-workbench) .pane-composite-part > .footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator { + top: 0; + bottom: 0; + transform: scaleY(-1); +} + +.modern-ui.modern-ui-connected-editor-tabs.monaco-workbench.floating-panels:not(.agent-sessions-workbench) .pane-composite-part > .footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked > .active-item-indicator { + top: 0; + bottom: calc(-1 * var(--modern-ui-floating-card-stroke-width)); +} diff --git a/src/vs/workbench/contrib/modernUI/browser/media/editorBorder.css b/src/vs/workbench/contrib/modernUI/browser/media/editorBorder.css index 4b64c5d3333e..c288aa9493a4 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/editorBorder.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/editorBorder.css @@ -26,7 +26,7 @@ .modern-ui .monaco-grid-view .part.editor:not(.modal-editor-part) { border: var(--vscode-strokeThickness) solid var(--vscode-editorGroup-border, color-mix(in srgb, var(--vscode-foreground) 12%, transparent)); - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--vscode-editorArea-cornerRadius, var(--vscode-cornerRadius-large)); box-sizing: border-box; overflow: hidden; background-color: var(--vscode-editor-background); diff --git a/src/vs/workbench/contrib/modernUI/browser/media/fontRamp.css b/src/vs/workbench/contrib/modernUI/browser/media/fontRamp.css index 858174a2940c..0e5f54e0ccf9 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/fontRamp.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/fontRamp.css @@ -171,10 +171,10 @@ * those exact selectors (including the `:not(:focus)` / `.clicked:focus` states) * and rely on the extra `.modern-ui` class to win on specificity. */ -.modern-ui.monaco-workbench .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.modern-ui.monaco-workbench .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before, -.modern-ui.monaco-workbench .part.auxiliarybar > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.modern-ui.monaco-workbench .part.auxiliarybar > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before, +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.modern-ui.monaco-workbench:where(:not(.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .part.auxiliarybar > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked.clicked:focus .active-item-indicator:before { border-top-color: transparent !important; border-bottom-color: transparent !important; } diff --git a/src/vs/workbench/contrib/modernUI/browser/media/frostedGlass.css b/src/vs/workbench/contrib/modernUI/browser/media/frostedGlass.css index 50d04978ae6a..6d4cb603752d 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/frostedGlass.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/frostedGlass.css @@ -86,7 +86,8 @@ & .quick-input-widget:not(.quick-input-widget-overlay), & .action-widget, - & .monaco-hover, + & .monaco-resizable-hover, + & .monaco-hover:not(.monaco-resizable-hover > .monaco-hover), & .agent-feedback-widget-item, & .monaco-dialog-box, & .notifications-center, @@ -98,11 +99,21 @@ &::before { content: ''; position: absolute; - inset: 0; + /* Centering a content-box copy with the inherited border recreates the host border box. */ + box-sizing: content-box; + left: 50%; + top: 50%; + width: 100%; + height: 100%; z-index: -1; + transform: translate(-50%, -50%); + border: inherit; + border-color: transparent; border-radius: inherit; + clip-path: padding-box; pointer-events: none; background-color: var(--modern-ui-glass-background); + background-clip: padding-box; backdrop-filter: blur(12px); } } diff --git a/src/vs/workbench/contrib/modernUI/browser/media/padding.css b/src/vs/workbench/contrib/modernUI/browser/media/padding.css index 8eaa4a733528..412b1664d54c 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/padding.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/padding.css @@ -357,7 +357,8 @@ gap: var(--vscode-spacing-size20); } -.modern-ui.monaco-workbench .scm-view .monaco-list-row .resource > .name > .monaco-icon-label::after { +.modern-ui.monaco-workbench .scm-view .monaco-list-row .resource > .name > .monaco-icon-label::after, +.modern-ui.monaco-workbench .scm-view .scm-structural-change-status { margin-right: var(--vscode-spacing-size40); } diff --git a/src/vs/workbench/contrib/modernUI/browser/media/roundedCorners.css b/src/vs/workbench/contrib/modernUI/browser/media/roundedCorners.css index 180cccda2061..e6e1d0fd5a86 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/roundedCorners.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/roundedCorners.css @@ -31,17 +31,20 @@ .modern-ui .monaco-inputbox, .modern-ui .monaco-findInput, .modern-ui .monaco-findInput .monaco-inputbox { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); } .modern-ui .browser-root .browser-url-container { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); } /* Select / dropdown controls */ -.modern-ui .monaco-select-box, +.modern-ui .monaco-select-box { + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); +} + .modern-ui .monaco-select-box-dropdown-container { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-menus-corner-radius, var(--vscode-cornerRadius-small)); } /* List / tree rows (including the notification center list rows) */ @@ -55,6 +58,10 @@ border-radius: var(--vscode-cornerRadius-small); } +.modern-ui .monaco-action-bar:not(.vertical) .action-label { + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); +} + /* * Split buttons (dropdown action items — e.g. the extension list/editor * "Install"/"Disable" buttons). These connect a primary action label to a @@ -64,21 +71,21 @@ * on the primary label, right corners on the chevron — so the seam stays flat. */ .modern-ui .monaco-action-bar .action-item.action-dropdown-item > .action-label { - border-radius: var(--vscode-cornerRadius-small) 0 0 var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .modern-ui .monaco-action-bar .action-item.action-dropdown-item > .monaco-dropdown .action-label { - border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0; } .modern-ui .monaco-action-bar .action-item.action-dropdown-item.empty > .action-label { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* Update indicator (title-bar "Update" button — base CSS uses medium, but as a * control it belongs to the controls tier). */ .modern-ui .monaco-action-bar .update-indicator { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } /* @@ -190,42 +197,46 @@ /* Quick input (command palette, quick open) */ .modern-ui .quick-input-widget { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } /* Editor / workbench hover and parameter hints. Suggestion widgets use suggestWidget.css. */ -.modern-ui .monaco-hover, +.modern-ui .monaco-hover { + border-radius: var(--workbench-custom-hovers-corner-radius, var(--vscode-cornerRadius-large)); + overflow: hidden; +} + .modern-ui .monaco-editor .parameter-hints-widget { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } /* Context menus and general menu surfaces */ .modern-ui .monaco-menu .monaco-action-bar.vertical { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-menus-corner-radius, var(--vscode-cornerRadius-large)); } /* Modal dialogs */ .modern-ui .monaco-dialog-box { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-dialogs-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } /* Editor find / replace widget */ .modern-ui .monaco-editor .find-widget { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); } /* Rename input widget */ .modern-ui .monaco-editor .rename-box { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } /* Color picker widget */ .modern-ui .colorpicker-widget { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } diff --git a/src/vs/workbench/contrib/modernUI/browser/media/suggestWidget.css b/src/vs/workbench/contrib/modernUI/browser/media/suggestWidget.css index 4e56730034cc..94f0980e89cc 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/suggestWidget.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/suggestWidget.css @@ -4,13 +4,13 @@ *--------------------------------------------------------------------------------------------*/ :is(.modern-ui, .agent-sessions-workbench) .editor-widget.suggest-widget { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); overflow: hidden; } :is(.modern-ui, .agent-sessions-workbench) .workbench-suggest-widget, :is(.modern-ui, .agent-sessions-workbench) .workbench-suggest-widget .monaco-list { - border-radius: var(--vscode-cornerRadius-large); + border-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); } :is(.modern-ui, .agent-sessions-workbench) :is(.editor-widget.suggest-widget, .workbench-suggest-widget) .monaco-list .monaco-list-row:not(.separator) { @@ -19,13 +19,13 @@ /* Virtualized rows use logical boundaries, not their recycled DOM order. */ :is(.modern-ui, .agent-sessions-workbench) :is(.editor-widget.suggest-widget, .workbench-suggest-widget) .monaco-list .monaco-list-row:not(.separator)[data-index="0"] { - border-top-left-radius: var(--vscode-cornerRadius-large); - border-top-right-radius: var(--vscode-cornerRadius-large); + border-top-left-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); + border-top-right-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); } :is(.modern-ui, .agent-sessions-workbench) :is(.editor-widget.suggest-widget, .workbench-suggest-widget):not(.with-status-bar) .monaco-list .monaco-list-row:not(.separator)[data-last-element="true"] { - border-bottom-left-radius: var(--vscode-cornerRadius-large); - border-bottom-right-radius: var(--vscode-cornerRadius-large); + border-bottom-left-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); + border-bottom-right-radius: var(--workbench-custom-popups-corner-radius, var(--vscode-cornerRadius-large)); } :is(.modern-ui, .agent-sessions-workbench) :is(.editor-widget.suggest-widget, .workbench-suggest-widget).with-status-bar .monaco-list { diff --git a/src/vs/workbench/contrib/modernUI/browser/media/tabs.css b/src/vs/workbench/contrib/modernUI/browser/media/tabs.css index 4314318bb25a..c46249efdddc 100644 --- a/src/vs/workbench/contrib/modernUI/browser/media/tabs.css +++ b/src/vs/workbench/contrib/modernUI/browser/media/tabs.css @@ -892,7 +892,7 @@ } .modern-ui-tabs.monaco-workbench:not(.hc-black):not(.hc-light) .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container:not(.dragged-over):not(.dragged-over-head):not(.dragged-over-tail) > .composite-bar > .monaco-action-bar .action-item.icon.checked:not(:active) > .active-item-indicator { - background-color: var(--vscode-modernTab-activeBackground) !important; + background-color: var(--modern-ui-tab-active-background) !important; } .modern-ui-tabs .pane-composite-part > :is(.title, .header-or-footer) > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.icon.checked > .action-label.codicon { @@ -1017,8 +1017,10 @@ :is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item, :is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item, -:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator, -:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator { +:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:not(.checked) .active-item-indicator, +:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item:not(.checked) .active-item-indicator, +:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator, +:is(.hc-black, .hc-light).modern-ui-tabs.monaco-workbench:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator { background-color: transparent !important; } @@ -1029,8 +1031,8 @@ outline: none !important; } -:is(.hc-black, .hc-light).modern-ui-tabs .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator:before, -:is(.hc-black, .hc-light).modern-ui-tabs .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator:before { +:is(.hc-black, .hc-light).modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator:before, +:is(.hc-black, .hc-light).modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item .active-item-indicator:before { display: none !important; } @@ -1039,8 +1041,8 @@ outline: none !important; } -:is(.hc-black, .hc-light).modern-ui-tabs .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) > .active-item-indicator, -:is(.hc-black, .hc-light).modern-ui-tabs .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) > .active-item-indicator { +:is(.hc-black, .hc-light).modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) > .active-item-indicator, +:is(.hc-black, .hc-light).modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) > .active-item-indicator { outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); outline-offset: calc(-1 * var(--vscode-strokeThickness)); } @@ -1061,8 +1063,8 @@ * Drop the checked underline in favour of the rounded background while retaining * the base keyboard-focus indicator. */ -.modern-ui-tabs .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, -.modern-ui-tabs .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before { +.modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .title > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before, +.modern-ui-tabs:where(:not(.modern-ui.modern-ui-connected-editor-tabs:not(.agent-sessions-workbench))) .pane-composite-part > .header-or-footer > .composite-bar-container > .composite-bar > .monaco-action-bar .action-item.checked:not(:focus) .active-item-indicator:before { border-top-color: transparent !important; border-top-width: 0 !important; border-bottom-color: transparent !important; diff --git a/src/vs/workbench/contrib/modernUI/browser/modernUI.contribution.ts b/src/vs/workbench/contrib/modernUI/browser/modernUI.contribution.ts index 60dbe92d9479..1fe87184e771 100644 --- a/src/vs/workbench/contrib/modernUI/browser/modernUI.contribution.ts +++ b/src/vs/workbench/contrib/modernUI/browser/modernUI.contribution.ts @@ -41,6 +41,7 @@ import './media/statusBar.css'; import './media/suggestWidget.css'; import './media/tabs.css'; import './connectedEditorTabs.js'; +import './media/connectedPaneTabs.css'; import './media/titlebar.css'; import '../../../services/themes/browser/modernTabColorCustomizations.js'; diff --git a/src/vs/workbench/contrib/modernUI/test/browser/frostedGlass.test.ts b/src/vs/workbench/contrib/modernUI/test/browser/frostedGlass.test.ts index 142f0f3da5da..994192317131 100644 --- a/src/vs/workbench/contrib/modernUI/test/browser/frostedGlass.test.ts +++ b/src/vs/workbench/contrib/modernUI/test/browser/frostedGlass.test.ts @@ -399,6 +399,70 @@ suite('Frosted glass styles', () => { }); }); + (supportsGlass(document.body) ? test : test.skip)('aligns bordered and borderless frosted surfaces to their host curves', () => { + const overlays = createOverlays(); + for (const { surface } of overlays.geometrySurfaces) { + surface.style.width = '120px'; + surface.style.height = '60px'; + } + overlays.root.classList.add('modern-ui-frosted-glass'); + + const readGeometry = ({ name, surface }: (typeof overlays.geometrySurfaces)[number]) => { + const targetWindow = getWindow(surface); + const host = targetWindow.getComputedStyle(surface); + const paint = targetWindow.getComputedStyle(surface, '::before'); + const bounds = surface.getBoundingClientRect(); + const paintWidth = parseFloat(paint.width) + parseFloat(paint.borderLeftWidth) + parseFloat(paint.borderRightWidth); + const paintHeight = parseFloat(paint.height) + parseFloat(paint.borderTopWidth) + parseFloat(paint.borderBottomWidth); + return { + name, + hostRadius: host.borderTopLeftRadius, + hostBorder: `${host.borderTopStyle} ${host.borderTopWidth}`, + hostBorderColor: host.borderTopStyle === 'none' ? undefined : host.borderTopColor, + paintRadius: paint.borderTopLeftRadius, + paintBorder: `${paint.borderTopStyle} ${paint.borderTopWidth}`, + paintBorderColor: paint.borderTopColor, + paintBoxSizing: paint.boxSizing, + paintClip: paint.clipPath, + paintBackgroundClip: paint.backgroundClip, + paintFilter: paint.backdropFilter, + sharesBorderBox: Math.abs(paintWidth - bounds.width) < 0.01 && Math.abs(paintHeight - bounds.height) < 0.01, + }; + }; + const radii = ['8px', '8px', '5px', '8px', '8px', '4px', '4px']; + const expected = (bordered: boolean) => overlays.geometrySurfaces.map(({ name }, index) => ({ + name, + hostRadius: radii[index], + hostBorder: bordered ? 'solid 1px' : 'none 0px', + hostBorderColor: bordered ? 'rgb(90, 123, 157)' : undefined, + paintRadius: radii[index], + paintBorder: bordered ? 'solid 1px' : 'none 0px', + paintBorderColor: 'rgba(0, 0, 0, 0)', + paintBoxSizing: 'content-box', + paintClip: 'padding-box', + paintBackgroundClip: 'padding-box', + paintFilter: 'blur(12px)', + sharesBorderBox: true, + })); + const bordered = overlays.geometrySurfaces.map(readGeometry); + for (const token of ['widget-border', 'editorWidget-border', 'editorHoverWidget-border']) { + overlays.root.style.setProperty(`--vscode-${token}`, 'initial'); + } + + assert.deepStrictEqual({ + bordered, + borderless: overlays.geometrySurfaces.map(readGeometry), + resizableInnerPaint: { + content: getWindow(overlays.resizableHoverContent).getComputedStyle(overlays.resizableHoverContent, '::before').content, + filter: getWindow(overlays.resizableHoverContent).getComputedStyle(overlays.resizableHoverContent, '::before').backdropFilter, + }, + }, { + bordered: expected(true), + borderless: expected(false), + resizableInnerPaint: { content: 'none', filter: 'none' }, + }); + }); + test('keeps picker and nested picker tint steady while opening and uses a solid closing fallback', () => { const { root, picker } = createOverlays(); root.classList.add('modern-ui-frosted-glass', 'monaco-enable-motion'); @@ -559,7 +623,12 @@ suite('Frosted glass styles', () => { test('does not move fixed-position children when glass is enabled', () => { const overlays = createOverlays(); - const children = [overlays.quickInput, overlays.menuContainer, overlays.shadowMenuContainer, overlays.picker].map(container => { + const containers = [ + overlays.menuContainer, + overlays.shadowMenuContainer, + ...overlays.geometrySurfaces.map(({ surface }) => surface), + ]; + const children = containers.map(container => { const fixed = append(container, 'fixed-child'); fixed.style.cssText = 'position: fixed; top: 17px; left: 19px; width: 10px; height: 10px;'; return fixed; @@ -570,8 +639,9 @@ suite('Frosted glass styles', () => { }); const before = positions(); overlays.root.classList.add('modern-ui-frosted-glass'); - assert.deepStrictEqual({ before, after: positions() }, { - before: children.map(() => [17, 19]), after: children.map(() => [17, 19]), + assert.deepStrictEqual({ viewportAnchored: before.slice(0, 4), after: positions() }, { + viewportAnchored: before.slice(0, 4).map(() => [17, 19]), + after: before, }); }); diff --git a/src/vs/workbench/contrib/modernUI/test/browser/frostedGlassTestUtils.ts b/src/vs/workbench/contrib/modernUI/test/browser/frostedGlassTestUtils.ts index a99bd243f8b2..45ca7c2ebe75 100644 --- a/src/vs/workbench/contrib/modernUI/test/browser/frostedGlassTestUtils.ts +++ b/src/vs/workbench/contrib/modernUI/test/browser/frostedGlassTestUtils.ts @@ -13,6 +13,7 @@ import { ACTION_WIDGET_ANIMATED_CLASS } from '../../../../../platform/actionWidg import '../../../../../base/browser/ui/contextview/contextview.css'; import '../../../../../base/browser/ui/dialog/dialog.css'; import '../../../../../base/browser/ui/hover/hoverWidget.css'; +import '../../../../../editor/contrib/hover/browser/hover.css'; import '../../../../../platform/actionWidget/browser/actionWidget.css'; import '../../../../../platform/hover/browser/hover.css'; import '../../../../../platform/quickinput/browser/media/quickInput.css'; @@ -35,11 +36,17 @@ export function createFrostedGlassOverlays(store: Pick, for (const token of ['quickInput-background', 'menu-background', 'editorHoverWidget-background', 'editorWidget-background', 'notifications-background', 'editor-background', 'input-background']) { root.style.setProperty(`--vscode-${token}`, background); } + for (const token of ['widget-border', 'editorWidget-border', 'editorHoverWidget-border']) { + root.style.setProperty(`--vscode-${token}`, '#5a7b9d'); + } + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); root.style.setProperty('--vscode-cornerRadius-large', '8px'); root.style.setProperty('--vscode-cornerRadius-xLarge', '12px'); root.style.setProperty('--vscode-list-hoverBackground', '#456789'); const quickInput = append(root, 'quick-input-widget'); quickInput.style.backgroundColor = 'var(--vscode-quickInput-background)'; + quickInput.style.border = '1px solid var(--vscode-widget-border)'; quickInput.style.top = '100px'; const menuContainer = append(root, 'context-view'); menuContainer.style.left = '120px'; @@ -60,18 +67,33 @@ export function createFrostedGlassOverlays(store: Pick, pickerRows.style.backgroundColor = 'var(--vscode-menu-background)'; const pickerFooter = append(picker, 'action-widget-action-bar'); const hover = append(root, 'monaco-hover workbench-hover'); + const editor = append(root, 'monaco-editor'); + const resizableHover = append(editor, 'monaco-resizable-hover'); + resizableHover.style.position = 'absolute'; + const resizableHoverContent = append(resizableHover, 'monaco-hover'); const dialog = append(root, 'monaco-dialog-box'); dialog.style.backgroundColor = 'var(--vscode-editorWidget-background)'; + dialog.style.border = '1px solid var(--vscode-widget-border)'; const center = append(root, 'notifications-center visible'); const centerBackground = append(center, 'notifications-list-container'); const toasts = append(root, 'notifications-toasts visible'); const toast = append(append(toasts, 'notification-toast-container'), 'notification-toast notification-fade-in-done'); toast.style.background = 'var(--vscode-notifications-background)'; + toast.style.border = '1px solid var(--vscode-widget-border)'; const toastList = append(toast, 'notifications-list-container'); return { - root, quickInput, menu, menuContainer, menubarMenuContainer, shadowMenuContainer, picker, pickerFilter, pickerRows, pickerFooter, hover, dialog, toast, toastList, - surfaces: [quickInput, menuContainer, shadowMenuContainer, picker, hover, dialog, center, toast], - backgrounds: [quickInput, menuBackground, shadowMenuBackground, picker, pickerRows, hover, dialog, centerBackground, toast, toastList], + root, quickInput, menu, menuContainer, menubarMenuContainer, shadowMenuContainer, picker, pickerFilter, pickerRows, pickerFooter, hover, resizableHover, resizableHoverContent, dialog, center, toast, toastList, + geometrySurfaces: [ + { name: 'quick input', surface: quickInput }, + { name: 'action widget', surface: picker }, + { name: 'hover', surface: hover }, + { name: 'resizable hover', surface: resizableHover }, + { name: 'dialog', surface: dialog }, + { name: 'notification center', surface: center }, + { name: 'notification toast', surface: toast }, + ], + surfaces: [quickInput, menuContainer, shadowMenuContainer, picker, hover, resizableHover, dialog, center, toast], + backgrounds: [quickInput, menuBackground, shadowMenuBackground, picker, pickerRows, hover, resizableHover, resizableHoverContent, dialog, centerBackground, toast, toastList], }; } diff --git a/src/vs/workbench/contrib/modernUI/test/browser/modernUI.contribution.test.ts b/src/vs/workbench/contrib/modernUI/test/browser/modernUI.contribution.test.ts index 4fe6f557bd3b..1b0482b5128f 100644 --- a/src/vs/workbench/contrib/modernUI/test/browser/modernUI.contribution.test.ts +++ b/src/vs/workbench/contrib/modernUI/test/browser/modernUI.contribution.test.ts @@ -38,12 +38,15 @@ import { WorkbenchState } from '../../../../../platform/workspace/common/workspa import { ColorThemeData } from '../../../../services/themes/common/colorThemeData.js'; import { generateColorThemeCSS } from '../../../../services/themes/browser/colorThemeCss.js'; import '../../../../browser/media/style.css'; +import '../../../../browser/media/part.css'; import '../../../../browser/media/floatingPanels.css'; import '../../../../../base/browser/ui/menu/menubar.css'; import '../../../../browser/parts/activitybar/media/activityaction.css'; import '../../../../browser/parts/editor/media/multieditortabscontrol.css'; import '../../../../browser/parts/editor/media/modalEditorPart.css'; import '../../../../browser/parts/media/paneCompositePart.css'; +import '../../../../browser/parts/sidebar/media/sidebarpart.css'; +import '../../../../browser/parts/auxiliarybar/media/auxiliaryBarPart.css'; import '../../../../browser/parts/statusbar/media/statusbarpart.css'; import '../../../../browser/parts/titlebar/media/menubarControl.css'; import { ModernUIContribution } from '../../browser/modernUI.contribution.js'; @@ -123,12 +126,17 @@ function createEditorTabLabel(parent: HTMLElement, extraClasses?: string): { lab function createCompositeAction(root: HTMLElement, titleHeight: number, checked: boolean, icon = false): { actionItem: HTMLElement; actionLabel: HTMLElement; indicator: HTMLElement } { root.style.setProperty('--vscode-spacing-size20', '2px'); root.style.setProperty('--vscode-spacing-size40', '4px'); + root.style.setProperty('--vscode-spacing-size60', '6px'); + root.style.setProperty('--vscode-spacing-size100', '10px'); + root.style.setProperty('--vscode-spacing-size160', '16px'); root.style.setProperty('--vscode-spacing-size240', '24px'); + root.style.setProperty('--vscode-spacing-size280', '28px'); root.style.setProperty('--vscode-spacing-size320', '32px'); + root.style.setProperty('--vscode-spacing-size360', '36px'); root.style.setProperty('--vscode-fontWeight-regular', '400'); root.style.setProperty('--vscode-fontWeight-semiBold', '600'); const part = appendElement(root, 'part pane-composite-part'); - const title = appendElement(part, 'title'); + const title = appendElement(part, 'title has-composite-bar'); title.style.height = `${titleHeight}px`; const compositeBarContainer = appendElement(title, 'composite-bar-container'); const compositeBar = appendElement(compositeBarContainer, 'composite-bar'); @@ -138,6 +146,8 @@ function createCompositeAction(root: HTMLElement, titleHeight: number, checked: actionItem.tabIndex = 0; const actionLabel = appendElement(actionItem, 'action-label'); const indicator = appendElement(actionItem, 'active-item-indicator'); + appendElement(indicator, 'tab-connected-edge'); + appendElement(actionItem, 'tab-divider'); return { actionItem, actionLabel, indicator }; } @@ -1002,6 +1012,967 @@ suite('ModernUIContribution', () => { }); }); + for (const theme of ['', 'vs', 'hc-black', 'hc-light']) { + test(`connects text and icon pane tabs to their own surfaces (${theme || 'vs-dark'})`, () => { + const root = document.createElement('div'); + root.className = `monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs ${theme}`; + for (const [name, value] of Object.entries({ + '--vscode-strokeThickness': '1px', + '--vscode-cornerRadius-small': '4px', + '--vscode-cornerRadius-medium': '6px', + '--vscode-sideBar-background': '#123456', + '--vscode-panel-background': '#654321', + '--vscode-modernPanel-border': '#778899', + '--vscode-activityBarTop-activeBorder': '#ffffff', + '--vscode-contrastBorder': '#abcdef', + '--modern-ui-connected-tab-strip-background': '#223344', + })) { + root.style.setProperty(name, value); + } + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const actual = []; + const expected = []; + for (const partClass of ['sidebar', 'panel', 'auxiliarybar']) { + for (const headerClass of ['title', 'header-or-footer header', 'header-or-footer footer']) { + for (const icon of [false, true]) { + const { actionItem, actionLabel, indicator } = createCompositeAction(root, 32, true, icon); + const part = actionItem.closest('.part')!; + part.classList.add(partClass); + const title = actionItem.closest('.title')!; + title.className = headerClass === 'title' ? 'title has-composite-bar' : headerClass; + actionLabel.classList.toggle('codicon', icon); + const targetWindow = getWindow(root); + const style = targetWindow.getComputedStyle(indicator); + const edgeStyle = targetWindow.getComputedStyle(indicator.querySelector('.tab-connected-edge')!); + const shoulder = targetWindow.getComputedStyle(indicator, '::before'); + const footer = headerClass.endsWith('footer'); + const toolbar = appendElement(title, 'title-actions'); + actual.push({ + partClass, headerClass, icon, + targetHeight: actionItem.getBoundingClientRect().height, + capHeight: indicator.getBoundingClientRect().height, + padding: [targetWindow.getComputedStyle(actionItem).paddingLeft, targetWindow.getComputedStyle(actionItem).paddingRight], + capInlineInset: [style.left, style.right], + iconWidth: icon ? actionItem.getBoundingClientRect().width : undefined, + background: style.backgroundColor, + borderColor: edgeStyle.borderTopColor, + strokeClip: edgeStyle.clipPath, + shoulderColor: shoulder.borderBottomColor, + borderBottom: style.borderBottomWidth, + firstEdge: [style.borderLeftWidth, style.borderTopLeftRadius, shoulder.content], + transform: style.transform, + shoulder: [shoulder.display, shoulder.width, shoulder.borderBottomRightRadius, shoulder.borderBottomWidth], + strip: targetWindow.getComputedStyle(title).backgroundImage, + bodySeam: targetWindow.getComputedStyle(title).boxShadow, + toolbar: targetWindow.getComputedStyle(toolbar).backgroundColor, + pointerEvents: style.pointerEvents, + }); + expected.push({ + partClass, headerClass, icon, + targetHeight: 32, + capHeight: 32, + padding: icon ? ['10px', '10px'] : ['16px', '16px'], + capInlineInset: ['0px', '0px'], + iconWidth: icon ? 36 : undefined, + background: partClass === 'panel' ? 'rgb(101, 67, 33)' : 'rgb(18, 52, 86)', + borderColor: theme.startsWith('hc-') ? 'rgb(171, 205, 239)' : 'rgb(119, 136, 153)', + strokeClip: 'inset(0px 0px 7px)', + shoulderColor: theme.startsWith('hc-') ? 'rgb(171, 205, 239)' : 'rgb(119, 136, 153)', + borderBottom: '0px', + firstEdge: ['0px', '0px', 'none'], + transform: footer ? 'matrix(1, 0, 0, -1, 0, 0)' : 'none', + shoulder: ['block', '7px', '7px', '1px'], + strip: 'linear-gradient(rgb(34, 51, 68), rgb(34, 51, 68))', + bodySeam: `${theme.startsWith('hc-') ? 'rgb(171, 205, 239)' : 'rgb(119, 136, 153)'} 0px ${footer ? '1px' : '-1px'} 0px 0px inset`, + toolbar: 'rgba(0, 0, 0, 0)', + pointerEvents: 'none', + }); + } + } + } + assert.deepStrictEqual(actual, expected); + }); + } + + test('connected pane geometry switches with the option without changing inactive tabs or Agents headers', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs'; + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + root.style.setProperty('--vscode-cornerRadius-medium', '6px'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const active = createCompositeAction(root, 32, true); + const inactive = createCompositeAction(root, 32, false, true); + const targetWindow = getWindow(root); + const state = () => [active, inactive].map(({ indicator }) => { + const style = targetWindow.getComputedStyle(indicator); + return { height: style.height, radius: style.borderRadius, transform: style.transform }; + }); + const pill = state(); + root.classList.add('modern-ui-connected-editor-tabs'); + const connected = state(); + root.classList.add('agent-sessions-workbench'); + const agents = state(); + root.classList.remove('agent-sessions-workbench', 'modern-ui'); + const disabled = state(); + root.classList.add('modern-ui'); + root.classList.remove('modern-ui-connected-editor-tabs'); + assert.deepStrictEqual({ pill, connected, agents, disabled, restored: state() }, { + pill: [{ height: '24px', radius: '4px', transform: 'matrix(1, 0, 0, 1, 0, -12)' }, { height: '24px', radius: '4px', transform: 'matrix(1, 0, 0, 1, 0, -12)' }], + connected: [{ height: '32px', radius: '0px 7px 0px 0px', transform: 'none' }, { height: '24px', radius: '4px', transform: 'matrix(1, 0, 0, 1, -12, -12)' }], + agents: pill, + disabled: pill, + restored: pill, + }); + }); + + test('legacy and Agents underline colors are retained while Pill underlines stay hidden', () => { + const actual = []; + for (const classes of [ + 'monaco-workbench', + 'monaco-workbench modern-ui modern-ui-tabs', + 'monaco-workbench modern-ui-tabs modern-ui-connected-editor-tabs agent-sessions-workbench', + ]) { + const root = document.createElement('div'); + root.className = classes; + root.style.setProperty('--vscode-activityBarTop-activeBorder', '#ffffff'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + for (const partClass of ['sidebar', 'auxiliarybar']) { + const { actionItem, indicator } = createCompositeAction(root, 32, true, true); + actionItem.closest('.part')!.classList.add(partClass); + actionItem.closest('.title')!.className = 'header-or-footer footer'; + const style = getWindow(root).getComputedStyle(indicator, '::before'); + actual.push(root.classList.contains('modern-ui') ? style.display : style.borderBottomColor); + } + } + assert.deepStrictEqual(actual, [ + 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', + 'none', 'none', + 'rgb(255, 255, 255)', 'rgb(255, 255, 255)', + ]); + }); + + test('connected pane styling leaves standalone view titles untinted', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs hc-black'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + root.style.setProperty('--vscode-cornerRadius-medium', '6px'); + root.style.setProperty('--modern-ui-connected-tab-strip-background', '#223344'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const { actionItem, indicator } = createCompositeAction(root, 32, true, true); + const targetWindow = getWindow(root); + const actual = { + strip: targetWindow.getComputedStyle(actionItem.closest('.title')!).backgroundImage, + shoulder: targetWindow.getComputedStyle(indicator, '::before').display, + height: targetWindow.getComputedStyle(indicator).height, + }; + actionItem.closest('.title')!.classList.remove('has-composite-bar'); + assert.deepStrictEqual({ ...actual, standaloneBackground: targetWindow.getComputedStyle(actionItem.closest('.title')!).backgroundImage }, { + strip: 'linear-gradient(rgb(34, 51, 68), rgb(34, 51, 68))', + shoulder: 'block', + height: '32px', + standaloneBackground: 'none', + }); + }); + + test('connected pane overflow controls retain their original width', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const { actionItem } = createCompositeAction(root, 32, false, true); + actionItem.setAttribute('aria-haspopup', 'true'); + assert.strictEqual(actionItem.getBoundingClientRect().width, 28); + }); + + test('connected pane dividers match editor colors and only separate inactive tabs', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-tab-divider', '#223344'); + root.style.setProperty('--activity-bar-action-gap', '8px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const first = createCompositeAction(root, 32, false); + const actions = first.actionItem.parentElement!; + const items = [first.actionItem]; + for (let index = 0; index < 4; index++) { + const item = appendElement(actions, 'action-item'); + appendElement(item, 'tab-divider'); + items.push(item); + } + items[4].setAttribute('aria-haspopup', 'true'); + const targetWindow = getWindow(root); + const displays = () => items.map(item => targetWindow.getComputedStyle(item.querySelector('.tab-divider')!).display); + const allInactive = displays(); + items[0].classList.add('checked'); + const firstSelected = displays(); + items[0].classList.remove('checked'); + items[2].classList.add('checked'); + const middleSelected = displays(); + const divider = items[1].querySelector('.tab-divider')!; + const horizontal = targetWindow.getComputedStyle(divider); + const horizontalStyle = { width: horizontal.width, height: horizontal.height, color: horizontal.backgroundColor, pointerEvents: horizontal.pointerEvents }; + const container = first.actionItem.closest('.composite-bar-container')!; + container.classList.add('dragged-over'); + const dragging = displays(); + container.classList.remove('dragged-over'); + root.classList.remove('modern-ui-connected-editor-tabs'); + const pill = displays(); + root.classList.add('modern-ui-connected-editor-tabs', 'agent-sessions-workbench'); + const agents = displays(); + root.classList.remove('agent-sessions-workbench'); + + const bar = first.actionItem.closest('.composite-bar')!; + const part = first.actionItem.closest('.part')!; + part.className = 'part activitybar left'; + const content = appendElement(part, 'content'); + content.appendChild(bar); + assert.deepStrictEqual({ + allInactive, firstSelected, middleSelected, dragging, pill, agents, + horizontal: horizontalStyle, + verticalDisplays: displays(), + }, { + allInactive: ['none', 'block', 'block', 'block', 'none'], + firstSelected: ['none', 'none', 'block', 'block', 'none'], + middleSelected: ['none', 'block', 'none', 'none', 'none'], + dragging: ['none', 'none', 'none', 'none', 'none'], + pill: ['none', 'none', 'none', 'none', 'none'], + agents: ['none', 'none', 'none', 'none', 'none'], + horizontal: { width: '1px', height: '16px', color: 'rgb(34, 51, 68)', pointerEvents: 'none' }, + verticalDisplays: ['none', 'none', 'none', 'none', 'none'], + }); + }); + + test('connected pane caps share the card stroke and only the first tab omits its leading edge', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs floating-panels'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-spacing-sizeNone', '0px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + root.style.setProperty('--vscode-cornerRadius-medium', '6px'); + root.style.setProperty('--vscode-cornerRadius-large', '8px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const actual = []; + const expected = []; + for (const footer of [false, true]) { + const { actionItem, indicator } = createCompositeAction(root, 32, true); + const part = actionItem.closest('.part')!; + part.classList.add('panel'); + part.style.width = '200px'; + const header = actionItem.closest('.title')!; + if (footer) { + header.className = 'header-or-footer footer'; + } + const targetWindow = getWindow(root); + const capture = () => { + const style = targetWindow.getComputedStyle(indicator.querySelector('.tab-connected-edge')!); + const shoulder = targetWindow.getComputedStyle(indicator, '::before'); + const frame = part.getBoundingClientRect(); + const cap = indicator.getBoundingClientRect(); + return { + frameEdge: footer ? cap.bottom - frame.bottom : cap.top - frame.top, + leftInset: cap.left - frame.left, + height: cap.height, + leadingStroke: style.borderLeftWidth, + leadingRadius: style.borderTopLeftRadius, + leadingShoulder: shoulder.content, + }; + }; + actual.push(capture()); + expected.push({ frameEdge: 0, leftInset: 1, height: 33, leadingStroke: '0px', leadingRadius: '7px 8px', leadingShoulder: 'none' }); + + const previous = document.createElement('div'); + previous.className = 'action-item'; + actionItem.before(previous); + const middle = capture(); + actual.push({ leadingStroke: middle.leadingStroke, leadingRadius: middle.leadingRadius, leadingShoulder: middle.leadingShoulder }); + expected.push({ leadingStroke: '1px', leadingRadius: '7px', leadingShoulder: '""' }); + } + assert.deepStrictEqual(actual, expected); + }); + + test('floating connected headers follow the card frame across layout changes', () => { + const actual = []; + const expected = []; + for (const partClass of ['sidebar', 'auxiliarybar', 'panel']) { + for (const stripClass of ['composite title has-composite-bar', 'header-or-footer header']) { + if (partClass === 'sidebar' && stripClass.startsWith('composite')) { + continue; + } + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs floating-panels noactivitybar hc-black'; + root.style.cssText = 'position: absolute; left: 20px; top: 20px; width: 240px; height: 120px; --vscode-strokeThickness: 1px; --vscode-cornerRadius-small: 4px; --vscode-cornerRadius-medium: 6px; --vscode-cornerRadius-large: 8px; --vscode-surface-border: #778899; --vscode-modernPanel-border: #778899; --vscode-contrastBorder: #abcdef; --vscode-focusBorder: #13579b;'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const { actionItem, indicator } = createCompositeAction(appendElement(root, 'monaco-grid-view'), 32, true, stripClass.startsWith('header')); + const part = actionItem.closest('.part')!; + part.classList.add(partClass); + if (partClass !== 'sidebar') { + part.classList.add('basepanel', partClass === 'panel' ? 'bottom' : 'right'); + } + part.style.cssText = 'position: relative; width: 200px; height: 96px;'; + const strip = actionItem.closest('.title')!; + strip.className = stripClass; + const edge = indicator.querySelector('.tab-connected-edge')!; + edge.style.pointerEvents = 'auto'; + const targetWindow = getWindow(root); + const geometry = () => { + const partStyle = targetWindow.getComputedStyle(part); + const capStyle = targetWindow.getComputedStyle(indicator); + const edgeStyle = targetWindow.getComputedStyle(edge); + const frame = part.getBoundingClientRect(); + return { + borderBoxClip: partStyle.overflow === 'clip' && partStyle.getPropertyValue('overflow-clip-margin') === 'border-box' + || partStyle.overflow === 'visible' && partStyle.clipPath.startsWith('inset('), + stripRadius: targetWindow.getComputedStyle(strip).borderTopLeftRadius, + capRadius: capStyle.borderTopLeftRadius, + capBackgroundClip: capStyle.backgroundClip, + edgeClip: edgeStyle.clipPath, + edgeColor: edgeStyle.borderTopColor, + perimeterVisible: targetWindow.document.elementFromPoint(frame.left + 16.5, frame.top + 0.5) === edge, + }; + }; + const rounded = geometry(); + actionItem.focus(); + // Electron can retain document.activeElement while its window is inactive, so CSS :focus does not match. + const hasCssFocus = actionItem.matches(':focus'); + const focusedStyle = targetWindow.getComputedStyle(indicator); + const focused = { + active: targetWindow.document.activeElement === actionItem, + outline: hasCssFocus ? [focusedStyle.outlineStyle, focusedStyle.outlineWidth, focusedStyle.outlineColor] : undefined, + capRadius: focusedStyle.borderTopLeftRadius, + }; + actionItem.blur(); + root.classList.add('modern-ui-compact'); + const compact = geometry(); + root.classList.remove('modern-ui-compact', 'modern-ui-connected-editor-tabs'); + const pill = targetWindow.getComputedStyle(part).overflow; + root.classList.add('modern-ui-connected-editor-tabs', 'agent-sessions-workbench'); + const agents = targetWindow.getComputedStyle(part).overflow; + actual.push({ partClass, stripClass, rounded, focused, compact, pill, agents }); + expected.push({ + partClass, stripClass, + rounded: { borderBoxClip: true, stripRadius: '8px', capRadius: '7px 8px', capBackgroundClip: 'padding-box', edgeClip: 'inset(0px 0px 7px 7px)', edgeColor: 'rgb(171, 205, 239)', perimeterVisible: true }, + focused: { active: true, outline: hasCssFocus ? ['solid', '1px', 'rgb(19, 87, 155)'] : undefined, capRadius: '7px 8px' }, + compact: { borderBoxClip: true, stripRadius: '0px', capRadius: '0px', capBackgroundClip: 'border-box', edgeClip: 'inset(0px 0px 7px)', edgeColor: 'rgb(171, 205, 239)', perimeterVisible: true }, + pill: 'hidden', + agents: 'hidden', + }); + } + } + assert.deepStrictEqual(actual, expected); + }); + + test('plain floating titles follow the sidebar card frame', () => { + const root = appendElement(document.body, 'monaco-workbench modern-ui modern-ui-connected-editor-tabs floating-panels'); + root.style.cssText = '--vscode-strokeThickness: 1px; --vscode-cornerRadius-large: 8px; --vscode-spacing-size40: 4px; --vscode-spacing-sizeNone: 0px;'; + store.add(toDisposable(() => root.remove())); + const part = appendElement(appendElement(root, 'monaco-grid-view'), 'part pane-composite-part sidebar left'); + const title = appendElement(part, 'title'); + const targetWindow = getWindow(root); + const capture = (strip: HTMLElement) => { + const partStyle = targetWindow.getComputedStyle(part); + const stripStyle = targetWindow.getComputedStyle(strip); + return { + part: [partStyle.borderTopLeftRadius, partStyle.borderTopRightRadius], + strip: [stripStyle.borderTopLeftRadius, stripStyle.borderTopRightRadius], + }; + }; + + const withActivityBar = capture(title); + root.classList.add('noactivitybar'); + const withoutActivityBar = capture(title); + root.classList.add('modern-ui-compact'); + const compact = capture(title); + root.classList.remove('modern-ui-compact'); + const header = appendElement(part, 'header-or-footer header'); + part.prepend(header); + const withTopHeader = { header: capture(header), title: capture(title) }; + + assert.deepStrictEqual({ withActivityBar, withoutActivityBar, compact, withTopHeader }, { + withActivityBar: { part: ['0px', '8px'], strip: ['0px', '8px'] }, + withoutActivityBar: { part: ['8px', '8px'], strip: ['8px', '8px'] }, + compact: { part: ['0px', '0px'], strip: ['0px', '0px'] }, + withTopHeader: { + header: { part: ['8px', '8px'], strip: ['8px', '8px'] }, + title: { part: ['8px', '8px'], strip: ['0px', '0px'] }, + }, + }); + }); + + test('frame-touching caps follow Activity Bar and native window corners', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs floating-panels noactivitybar'; + root.style.cssText = '--vscode-strokeThickness: 1px; --vscode-cornerRadius-small: 4px; --vscode-cornerRadius-medium: 6px; --vscode-cornerRadius-large: 8px; --modern-ui-window-corner-radius: 16px;'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const header = createCompositeAction(root, 32, true); + const footer = createCompositeAction(root, 32, true); + const part = header.actionItem.closest('.part')!; + part.className = 'part pane-composite-part sidebar left floating-part-outer-left floating-part-outer-bottom'; + header.actionItem.closest('.title')!.className = 'header-or-footer header'; + const footerStrip = appendElement(part, 'header-or-footer footer'); + footerStrip.appendChild(footer.actionItem.closest('.composite-bar-container')!); + const targetWindow = getWindow(root); + const fallback = targetWindow.getComputedStyle(part).overflow === 'visible'; + const capture = () => ({ + radii: [ + targetWindow.getComputedStyle(header.indicator).borderTopLeftRadius, + targetWindow.getComputedStyle(footer.indicator).borderTopLeftRadius, + ], + clip: targetWindow.getComputedStyle(part).clipPath, + }); + const actual = [capture()]; + root.classList.remove('noactivitybar'); + actual.push(capture()); + root.classList.add('mac', 'nostatusbar'); + actual.push(capture()); + root.classList.add('fullscreen'); + actual.push(capture()); + root.classList.remove('fullscreen'); + part.classList.replace('left', 'right'); + part.classList.replace('floating-part-outer-left', 'floating-part-outer-right'); + actual.push(capture()); + root.classList.add('web'); + actual.push(capture()); + root.classList.add('modern-ui-compact'); + actual.push(capture()); + const clip = (value: string) => fallback ? value : 'none'; + assert.deepStrictEqual(actual, [ + { radii: ['7px 8px', '7px 8px'], clip: clip('inset(0px round 8px)') }, + { radii: ['0px', '0px'], clip: clip('inset(0px round 0px 8px 8px 0px)') }, + { radii: ['0px', '15px 16px'], clip: clip('inset(0px round 0px 8px 8px 16px)') }, + { radii: ['0px', '0px'], clip: clip('inset(0px round 0px 8px 8px 0px)') }, + { radii: ['7px 8px', '7px 8px'], clip: clip('inset(0px round 8px 0px 16px 8px)') }, + { radii: ['7px 8px', '7px 8px'], clip: clip('inset(0px round 8px 0px 0px 8px)') }, + { radii: ['0px', '0px'], clip: clip('inset(0px)') }, + ]); + }); + + test('repaints the connected pane frame without clipping content overlays', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs floating-panels noactivitybar'; + root.style.cssText = 'position: absolute; top: 20px; left: 20px; width: 600px; height: 200px; --vscode-strokeThickness: 1px; --vscode-cornerRadius-medium: 6px; --vscode-cornerRadius-large: 8px; --vscode-toolsPanel-cornerRadius: 8px; --vscode-primarySideBar-cornerRadius: 8px; --modern-ui-floating-card-stroke-width: 1px; --vscode-modernPanel-border: #778899; --vscode-surface-border: #778899;'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const targetWindow = getWindow(root); + const createPart = (className: string, left: number) => { + const part = appendElement(root, `part pane-composite-part ${className}`); + part.style.cssText = `position: absolute; top: 0; left: ${left}px; width: 240px; height: 120px; margin: 0;`; + const content = appendElement(part, 'content'); + content.style.cssText = 'position: absolute; top: 32px; left: 1px; width: 238px; height: 87px;'; + return { part, content }; + }; + const panel = createPart('panel', 0); + const completion = appendElement(panel.content, 'workbench-suggest-widget'); + const panelBounds = panel.part.getBoundingClientRect(); + completion.style.cssText = `display: block; position: fixed; z-index: 40; top: ${panelBounds.top + 8}px; left: ${panelBounds.left + 80}px; width: 60px; height: 12px;`; + const sidebar = createPart('sidebar left', 300); + const progress = appendElement(sidebar.content, 'monaco-progress-container'); + const sidebarBounds = sidebar.part.getBoundingClientRect(); + progress.style.cssText = `position: fixed; z-index: 5; top: ${sidebarBounds.top + 8}px; left: ${sidebarBounds.left + 80}px; width: 60px; height: 12px;`; + const frame = () => { + const corner = (pseudo: '::before' | '::after') => { + const style = targetWindow.getComputedStyle(panel.part, pseudo); + return { + borderBottomWidth: style.borderBottomWidth, + borderBottomLeftRadius: style.borderBottomLeftRadius, + borderBottomRightRadius: style.borderBottomRightRadius, + height: style.height, + width: style.width, + zIndex: style.zIndex, + }; + }; + return { + left: corner('::before'), + right: corner('::after'), + }; + }; + const overlays = { + completion: targetWindow.document.elementFromPoint(panelBounds.left + 100, panelBounds.top + 14) === completion, + progress: targetWindow.document.elementFromPoint(sidebarBounds.left + 100, sidebarBounds.top + 14) === progress, + panelContentClip: targetWindow.getComputedStyle(panel.content).clipPath, + sidebarContentClip: targetWindow.getComputedStyle(sidebar.content).clipPath, + }; + const rounded = frame(); + appendElement(panel.part, 'workbench-suggest-widget').style.display = 'none'; + const withTrailingOverlay = frame(); + root.style.setProperty('--vscode-toolsPanel-cornerRadius', '2px'); + const customized = frame(); + panel.part.classList.add('has-footer'); + const footer = appendElement(panel.part, 'header-or-footer footer'); + const withFooter = { + frame: frame(), + footerRadii: [ + targetWindow.getComputedStyle(footer).borderBottomLeftRadius, + targetWindow.getComputedStyle(footer).borderBottomRightRadius, + ], + }; + root.classList.add('modern-ui-compact'); + panel.part.classList.remove('has-footer'); + const compact = frame(); + const visibleFrame = (radius: string) => ({ + left: { + borderBottomWidth: '1px', + borderBottomLeftRadius: radius, + borderBottomRightRadius: '0px', + height: radius, + width: radius, + zIndex: '4', + }, + right: { + borderBottomWidth: '1px', + borderBottomLeftRadius: '0px', + borderBottomRightRadius: radius, + height: radius, + width: radius, + zIndex: '4', + }, + }); + const hiddenFrame = { + left: { + borderBottomWidth: '0px', + borderBottomLeftRadius: '0px', + borderBottomRightRadius: '0px', + height: 'auto', + width: 'auto', + zIndex: 'auto', + }, + right: { + borderBottomWidth: '0px', + borderBottomLeftRadius: '0px', + borderBottomRightRadius: '0px', + height: 'auto', + width: 'auto', + zIndex: 'auto', + }, + }; + + assert.deepStrictEqual({ overlays, rounded, withTrailingOverlay, customized, withFooter, compact }, { + overlays: { + completion: true, + progress: true, + panelContentClip: 'none', + sidebarContentClip: 'none', + }, + rounded: visibleFrame('8px'), + withTrailingOverlay: visibleFrame('8px'), + customized: visibleFrame('2px'), + withFooter: { + frame: hiddenFrame, + footerRadii: ['2px', '2px'], + }, + compact: hiddenFrame, + }); + }); + + test('lower frame repaints align with the card border rather than its padding edge', () => { + const root = appendElement(document.body, 'monaco-workbench modern-ui modern-ui-connected-editor-tabs floating-panels'); + root.style.cssText = '--vscode-strokeThickness: 1px; --vscode-cornerRadius-large: 8px; --vscode-modernPanel-border: #778899; --vscode-surface-border: #778899; --window-corner-radius: 20px; --vscode-spacing-size40: 4px;'; + store.add(toDisposable(() => root.remove())); + const targetWindow = getWindow(root); + root.style.setProperty('--window-device-pixel-ratio', String(targetWindow.devicePixelRatio)); + const actual = []; + const expected = []; + + for (const theme of ['vs', 'vs-dark', 'hc-black', 'hc-light']) { + root.classList.add(theme); + for (const className of ['panel bottom', 'sidebar left', 'sidebar right', 'auxiliarybar']) { + const part = appendElement(root, `part pane-composite-part ${className} floating-part-outer-left floating-part-outer-right floating-part-outer-bottom`); + part.style.cssText = 'position: relative; width: 240px; height: 120px;'; + for (const radius of ['0px', '2px', '8px', '16px']) { + for (const token of ['toolsPanel', 'primarySideBar', 'secondarySideBar']) { + root.style.setProperty(`--vscode-${token}-cornerRadius`, radius); + } + for (const zoom of [1, 1.25, 1.5, 2]) { + root.style.zoom = String(zoom); + root.style.setProperty('--window-device-pixel-ratio', String(targetWindow.devicePixelRatio * zoom)); + for (const nativeWindow of [false, true]) { + root.classList.toggle('mac', nativeWindow); + root.classList.toggle('nostatusbar', nativeWindow); + const frame = targetWindow.getComputedStyle(part); + const left = targetWindow.getComputedStyle(part, '::before'); + const right = targetWindow.getComputedStyle(part, '::after'); + const aligned = (offset: number) => Math.abs(offset) < 1 / 64; + const state = { theme, className, radius, zoom, nativeWindow }; + actual.push({ + ...state, + left: aligned(parseFloat(frame.borderLeftWidth) + parseFloat(left.left) - parseFloat(left.width) - parseFloat(left.borderLeftWidth)), + right: aligned(parseFloat(frame.borderRightWidth) + parseFloat(right.right) - parseFloat(right.width) - parseFloat(right.borderRightWidth)), + bottom: [left, right].map(corner => aligned(parseFloat(frame.borderBottomWidth) + parseFloat(corner.bottom) - parseFloat(corner.height) - parseFloat(corner.borderBottomWidth))), + boxSizing: [left.boxSizing, right.boxSizing], + translate: [left.translate, right.translate], + radii: [left.borderBottomLeftRadius, right.borderBottomRightRadius], + }); + expected.push({ + ...state, + left: true, + right: true, + bottom: [true, true], + boxSizing: ['content-box', 'content-box'], + translate: ['-100% 100%', '100% 100%'], + radii: [frame.borderBottomLeftRadius, frame.borderBottomRightRadius], + }); + } + } + } + part.remove(); + } + root.classList.remove(theme, 'mac', 'nostatusbar'); + } + + assert.deepStrictEqual(actual, expected); + }); + + test('floating connected caps follow their semantic corner-radius customizations', () => { + const actual = []; + const expected = []; + for (const { partClass, token, radius, capRadius } of [ + { partClass: 'panel', token: '--vscode-toolsPanel-cornerRadius', radius: '0px', capRadius: '0px' }, + { partClass: 'sidebar', token: '--vscode-primarySideBar-cornerRadius', radius: '2px', capRadius: '1px 2px' }, + { partClass: 'auxiliarybar', token: '--vscode-secondarySideBar-cornerRadius', radius: '4px', capRadius: '3px 4px' }, + ]) { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-connected-editor-tabs floating-panels noactivitybar'; + root.style.cssText = `--vscode-strokeThickness: 1px; --vscode-cornerRadius-large: 8px; ${token}: ${radius};`; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const { actionItem, indicator } = createCompositeAction(root, 32, true); + const part = actionItem.closest('.part')!; + part.classList.add(partClass); + const targetWindow = getWindow(root); + const partStyle = targetWindow.getComputedStyle(part); + const frameRadius = partStyle.borderTopLeftRadius; + const clipPath = partStyle.overflow === 'visible' ? partStyle.clipPath : 'not-applicable'; + actual.push({ + frameRadius, + capRadius: targetWindow.getComputedStyle(indicator).borderTopLeftRadius, + clipPath, + }); + expected.push({ + frameRadius: radius, + capRadius, + clipPath: partStyle.overflow === 'visible' ? (radius === '0px' ? 'inset(0px)' : `inset(0px round ${radius})`) : 'not-applicable', + }); + } + assert.deepStrictEqual(actual, expected); + }); + + test('floating connected footers paint through the strip without covering the card perimeter', () => { + const actual = []; + const expected = []; + for (const partClass of ['sidebar', 'auxiliarybar']) { + for (const compact of [false, true]) { + for (const theme of ['', 'hc-black', 'hc-light']) { + const root = document.createElement('div'); + root.className = `monaco-workbench modern-ui modern-ui-tabs floating-panels noactivitybar ${theme}${compact ? ' modern-ui-compact' : ''}`; + root.style.cssText = 'position: absolute; left: 20px; top: 20px; width: 240px; height: 100px;'; + for (const [name, value] of Object.entries({ + '--vscode-strokeThickness': '1px', + '--vscode-spacing-sizeNone': '0px', + '--vscode-spacing-size40': '4px', + '--vscode-cornerRadius-small': '4px', + '--vscode-cornerRadius-medium': '6px', + '--vscode-cornerRadius-large': '8px', + '--vscode-sideBar-background': '#123456', + '--vscode-surface-background': '#123456', + '--vscode-surface-border': '#778899', + '--vscode-modernPanel-border': '#778899', + '--vscode-contrastBorder': '#abcdef', + '--modern-ui-connected-tab-strip-background': '#223344', + })) { + root.style.setProperty(name, value); + } + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const { actionItem, indicator } = createCompositeAction(appendElement(root, 'monaco-grid-view'), 32, true, true); + const part = actionItem.closest('.part')!; + part.classList.add(partClass); + part.style.cssText = 'position: relative; width: 200px;'; + const footer = actionItem.closest('.title')!; + footer.className = 'header-or-footer footer'; + const content = appendElement(part, 'content'); + content.style.height = '32px'; + footer.before(content); + const joinProbe = appendElement(indicator, 'join-probe'); + joinProbe.style.cssText = 'position: absolute; top: calc(100% - 1px); left: 16px; width: 1px; height: 1px; pointer-events: auto;'; + const outsideProbe = appendElement(part, 'outside-probe'); + outsideProbe.style.cssText = 'position: absolute; top: 16px; left: calc(100% + 1px); width: 1px; height: 1px;'; + const targetWindow = getWindow(root); + const edge = indicator.querySelector('.tab-connected-edge')!; + const clips = () => ({ + card: targetWindow.getComputedStyle(part).overflow, + footer: targetWindow.getComputedStyle(footer).overflow, + }); + const isVisible = (element: HTMLElement) => { + const bounds = element.getBoundingClientRect(); + return targetWindow.document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2) === element; + }; + const pill = clips(); + root.classList.add('modern-ui-connected-editor-tabs'); + const edgeStyle = targetWindow.getComputedStyle(edge); + const edgeColor = edgeStyle.borderTopColor; + const edgePointerEvents = edgeStyle.pointerEvents; + edge.style.pointerEvents = 'auto'; + const frame = part.getBoundingClientRect(); + const footerBounds = footer.getBoundingClientRect(); + const joinBounds = joinProbe.getBoundingClientRect(); + const edgeAt = (x: number) => targetWindow.document.elementFromPoint(x, frame.bottom - 0.5) === edge; + const connected = { + perimeterVisible: edgeAt(frame.left + 16.5), + cornerStrokeVisible: edgeAt(frame.left + 4.5), + edgeColor, + edgePointerEvents, + joinVisible: isVisible(joinProbe), + joinAtContentEdge: joinBounds.top === footerBounds.top, + spillClipped: !isVisible(outsideProbe), + cardRadius: targetWindow.getComputedStyle(part).borderRadius, + }; + indicator.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + const scroll = [part.scrollLeft, part.scrollTop]; + const previous = appendElement(actionItem.parentElement!, 'action-item icon'); + actionItem.before(previous); + const middle = { + edgeColor: targetWindow.getComputedStyle(edge).borderTopColor, + edgeClip: targetWindow.getComputedStyle(edge).clipPath, + perimeterVisible: edgeAt(edge.getBoundingClientRect().left + 16.5), + }; + root.classList.add('agent-sessions-workbench'); + const agents = clips(); + root.classList.remove('agent-sessions-workbench', 'modern-ui-connected-editor-tabs'); + actual.push({ partClass, compact, theme, pill, connected, scroll, middle, agents, restored: clips() }); + const legacyClips = { card: 'hidden', footer: 'hidden' }; + const expectedEdgeColor = theme ? 'rgb(171, 205, 239)' : 'rgb(119, 136, 153)'; + expected.push({ + partClass, compact, theme, + pill: legacyClips, + connected: { + perimeterVisible: true, + cornerStrokeVisible: compact, + edgeColor: expectedEdgeColor, + edgePointerEvents: 'none', + joinVisible: true, + joinAtContentEdge: true, + spillClipped: true, + cardRadius: compact ? '0px' : '8px', + }, + scroll: [0, 0], + middle: { edgeColor: expectedEdgeColor, edgeClip: 'inset(0px 0px 7px)', perimeterVisible: true }, + agents: legacyClips, + restored: legacyClips, + }); + } + } + } + assert.deepStrictEqual(actual, expected); + }); + + test('selected horizontal tab shoulders retain their shape through focus and blur', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + root.style.setProperty('--vscode-cornerRadius-medium', '6px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const actual = []; + for (const position of ['header', 'footer']) { + const { actionItem, indicator } = createCompositeAction(root, 32, true, true); + actionItem.closest('.part')!.classList.add('sidebar'); + actionItem.closest('.title')!.className = `header-or-footer ${position}`; + const previous = appendElement(actionItem.parentElement!, 'action-item icon'); + actionItem.before(previous); + const targetWindow = getWindow(root); + const capture = () => ['::before', '::after'].map(pseudo => { + const style = targetWindow.getComputedStyle(indicator, pseudo); + return { radius: style.borderRadius, top: style.top, bottom: style.bottom }; + }); + const initial = capture(); + actionItem.focus(); + assert.strictEqual(document.activeElement, actionItem); + const focused = capture(); + actionItem.blur(); + actual.push({ initial, focused, blurred: capture() }); + } + const shoulders = [ + { radius: '0px 0px 7px', top: '24px', bottom: '0px' }, + { radius: '0px 0px 0px 7px', top: '24px', bottom: '0px' }, + ]; + assert.deepStrictEqual(actual, [ + { initial: shoulders, focused: shoulders, blurred: shoulders }, + { initial: shoulders, focused: shoulders, blurred: shoulders }, + ]); + }); + + test('the first horizontal tab retains its leading edge while a compact menu precedes it', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + root.style.setProperty('--vscode-cornerRadius-medium', '6px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const actual = []; + for (const position of ['header', 'footer']) { + const { actionItem, indicator } = createCompositeAction(root, 32, true, true); + actionItem.closest('.part')!.classList.add('sidebar'); + actionItem.closest('.title')!.className = `header-or-footer ${position}`; + const bar = actionItem.closest('.composite-bar')!; + const targetWindow = getWindow(root); + const capture = () => ({ + radius: targetWindow.getComputedStyle(indicator).borderTopLeftRadius, + stroke: targetWindow.getComputedStyle(indicator.querySelector('.tab-connected-edge')!).borderLeftWidth, + shoulder: targetWindow.getComputedStyle(indicator, '::before').content, + }); + const initial = capture(); + const menu = document.createElement('div'); + menu.className = 'menubar compact'; + menu.style.width = '38px'; + menu.style.flexShrink = '0'; + bar.before(menu); + const menuVisible = capture(); + menu.remove(); + actual.push({ initial, menuVisible, menuRemoved: capture() }); + } + const frameEdge = { radius: '0px', stroke: '0px', shoulder: 'none' }; + const freestanding = { radius: '7px', stroke: '1px', shoulder: '""' }; + assert.deepStrictEqual(actual, [ + { initial: frameEdge, menuVisible: freestanding, menuRemoved: frameEdge }, + { initial: frameEdge, menuVisible: freestanding, menuRemoved: frameEdge }, + ]); + }); + + test('pane caps use the same convex radius as editor tabs', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs floating-panels'; + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-cornerRadius-small', '4px'); + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + + const editor = appendElement(root, 'part editor'); + const content = appendElement(editor, 'content'); + const group = appendElement(content, 'editor-group-container active'); + const title = appendElement(group, 'title tabs'); + const strip = appendElement(title, 'tabs-and-actions-container'); + const tabs = appendElement(strip, 'tabs-container'); + const editorFill = appendElement(appendElement(tabs, 'tab active'), 'tab-fill'); + const paneFill = createCompositeAction(root, 32, true).indicator; + const targetWindow = getWindow(root); + const actual = ['6px', '8px'].map(radius => { + root.style.setProperty('--vscode-cornerRadius-medium', radius); + return [ + targetWindow.getComputedStyle(editorFill).borderTopRightRadius, + targetWindow.getComputedStyle(paneFill).borderTopRightRadius, + ]; + }); + assert.deepStrictEqual(actual, [['7px', '7px'], ['9px', '9px']]); + }); + + test('connected tabs leave the default Activity Bar selection unchanged', () => { + for (const { compact, baseWidth } of [ + { compact: false, baseWidth: 36 }, + { compact: false, baseWidth: 28 }, + { compact: true, baseWidth: 36 }, + { compact: true, baseWidth: 28 }, + ]) { + for (const side of ['left', 'right']) { + for (const theme of ['', 'hc-black', 'hc-light']) { + const root = document.createElement('div'); + root.className = `monaco-workbench modern-ui modern-ui-tabs floating-panels ${theme}${compact ? ' modern-ui-compact' : ''}`; + root.style.display = 'inline-flex'; + for (const [name, value] of Object.entries({ + '--vscode-spacing-sizeNone': '0px', + '--vscode-spacing-size20': '2px', + '--vscode-spacing-size40': '4px', + '--vscode-spacing-size80': '8px', + '--vscode-strokeThickness': '1px', + '--vscode-cornerRadius-small': '4px', + '--vscode-cornerRadius-medium': '6px', + '--activity-bar-width': `${baseWidth}px`, + '--activity-bar-action-height': `${baseWidth}px`, + '--vscode-sideBar-background': '#123456', + '--vscode-modernActivityBarItem-activeBackground': '#234567', + '--vscode-modernPanel-border': '#778899', + '--vscode-contrastBorder': '#abcdef', + })) { + root.style.setProperty(name, value); + } + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const activityBar = appendElement(root, `part activitybar ${side}`); + activityBar.classList.toggle('compact', baseWidth === 28); + const content = appendElement(activityBar, 'content'); + const actionBar = appendElement(appendElement(content, 'composite-bar'), 'monaco-action-bar vertical'); + const actions = appendElement(actionBar, 'actions-container'); + const item = appendElement(actions, 'action-item checked'); + appendElement(item, 'action-label codicon'); + const indicator = appendElement(item, 'active-item-indicator'); + appendElement(indicator, 'tab-connected-edge'); + const targetWindow = getWindow(root); + const capture = () => { + const style = targetWindow.getComputedStyle(indicator); + const bounds = indicator.getBoundingClientRect(); + return { + size: [bounds.width, bounds.height], + radius: style.borderRadius, + background: style.backgroundColor, + outline: style.outline, + overflow: targetWindow.getComputedStyle(activityBar).overflow, + frameOverlay: targetWindow.getComputedStyle(activityBar, '::after').content, + shoulder: targetWindow.getComputedStyle(indicator, '::after').content, + }; + }; + const pill = capture(); + root.classList.add('modern-ui-connected-editor-tabs'); + const connected = capture(); + root.classList.remove('modern-ui-connected-editor-tabs'); + assert.deepStrictEqual({ connected, restored: capture() }, { connected: pill, restored: pill }); + } + } + } + }); + + test('connected icon hover fills remain square and centered in top and bottom strips', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench modern-ui modern-ui-tabs modern-ui-connected-editor-tabs'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const actual = ['title', 'header-or-footer header', 'header-or-footer footer'].map(headerClass => { + const { actionItem, actionLabel, indicator } = createCompositeAction(root, 32, false, true); + actionItem.closest('.title')!.className = headerClass; + actionLabel.style.width = '16px'; + actionLabel.style.height = '16px'; + const fill = indicator.getBoundingClientRect(); + const label = actionLabel.getBoundingClientRect(); + return { + size: [fill.width, fill.height], + centerOffset: [fill.left + fill.width / 2 - label.left - label.width / 2, fill.top + fill.height / 2 - label.top - label.height / 2], + }; + }); + assert.deepStrictEqual(actual, [ + { size: [24, 24], centerOffset: [0, 0] }, + { size: [24, 24], centerOffset: [0, 0] }, + { size: [24, 24], centerOffset: [0, 0] }, + ]); + }); + test('pane composite overflow uses the icon foreground', () => { const root = document.createElement('div'); root.className = 'monaco-workbench modern-ui modern-ui-tabs'; diff --git a/src/vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout.ts b/src/vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout.ts index 923522d9aa11..4e6e2d75358e 100644 --- a/src/vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout.ts +++ b/src/vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout.ts @@ -147,7 +147,7 @@ export class TroubleshootController extends Disposable implements INotebookEdito if (this._notebookOverlayDomNode) { // Update label - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const labelElement = this._notebookOverlayDomNode.querySelector('div:nth-child(2)') as HTMLElement; if (labelElement) { labelElement.textContent = `ScrollTop: ${scrollTop}px`; @@ -155,7 +155,7 @@ export class TroubleshootController extends Disposable implements INotebookEdito } // Update top line - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const topLineElement = this._notebookOverlayDomNode.querySelector('div:first-child') as HTMLElement; if (topLineElement) { topLineElement.style.top = `${listViewTop}px`; diff --git a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellComments.ts b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellComments.ts index ebc8c15a436f..df5ce9d33608 100644 --- a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellComments.ts +++ b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellComments.ts @@ -67,7 +67,8 @@ export class CellComments extends CellContentPart { actionRunner: () => { }, collapse: async () => { return true; } - } + }, + undefined ) as unknown as CommentThreadWidget; widgetDisposables.add(widget); this._commentThreadWidgets.set(commentThread.threadId, { widget, dispose: () => widgetDisposables.dispose() }); diff --git a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.ts b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.ts index 1f39fbaff7f5..9508443549a4 100644 --- a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.ts +++ b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellDragRenderer.ts @@ -111,7 +111,7 @@ export class CodeCellDragImageRenderer { dragImageContainer.classList.forEach(c => dragImageContainer.classList.remove(c)); dragImageContainer.classList.add('cell-drag-image', 'monaco-list-row', 'focused', `${type}-cell-row`); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const editorContainer: HTMLElement | null = dragImageContainer.querySelector('.cell-editor-container'); if (!editorContainer) { return null; diff --git a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellExecution.ts b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellExecution.ts index b8e9d472870d..4dac7fbed438 100644 --- a/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellExecution.ts +++ b/src/vs/workbench/contrib/notebook/browser/view/cellParts/cellExecution.ts @@ -172,7 +172,7 @@ export class CellExecutionPart extends CellContentPart { this._executionOrderLabel.classList.remove('sticky'); top = this.currentCell.layoutInfo.editorHeight - lineHeight; // Place at the bottom of the editor // Only update content if we were previously sticky or content is not correct - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const iconIsPresent = this._executionOrderContent.querySelector('.codicon') !== null; if (wasStickyHere || iconIsPresent) { const executionOrder = this.currentCell.internalMetadata.executionOrder; diff --git a/src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts b/src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts index a33ef06b46ea..223b3bbf9cff 100644 --- a/src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts +++ b/src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts @@ -91,7 +91,7 @@ declare function __import(path: string): Promise; async function webviewPreloads(ctx: PreloadContext) { - /* eslint-disable no-restricted-globals, no-restricted-syntax */ + /* eslint-disable no-restricted-globals, eslint-js/no-restricted-syntax */ // The use of global `window` should be fine in this context, even // with aux windows. This code is running from within an `iframe` diff --git a/src/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelQuickPickStrategy.ts b/src/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelQuickPickStrategy.ts index 3867369b0f51..ac96387f0510 100644 --- a/src/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelQuickPickStrategy.ts +++ b/src/vs/workbench/contrib/notebook/browser/viewParts/notebookKernelQuickPickStrategy.ts @@ -540,56 +540,69 @@ export class KernelPickerMRUStrategy extends KernelPickerStrategyBase { const notebook: NotebookTextModel = editor.textModel; const disposables = new DisposableStore(); const quickPick = disposables.add(this._quickInputService.createQuickPick({ useSeparators: true })); - const quickPickItem = await new Promise(resolve => { - // select from kernel sources - quickPick.title = kernelListEmpty ? localize('select', "Select Kernel") : localize('selectAnotherKernel', "Select Another Kernel"); - quickPick.placeholder = localize('selectKernel.placeholder', "Type to choose a kernel source"); + const { promise, resolve } = Promise.withResolvers(); + let requestId = 0; + let isClosed = false; + const finish = (item: KernelQuickPickItem | IQuickInputButton | undefined) => { + isClosed = true; + resolve(item); + }; + const updateItems = async (isInitial = false) => { + if (isClosed) { + return; + } + const currentRequest = ++requestId; quickPick.busy = true; - quickPick.buttons = [this._quickInputService.backButton]; - quickPick.show(); + const items = await this._calculdateKernelSources(editor); + if (isClosed || disposables.isDisposed || currentRequest !== requestId) { + return; + } + quickPick.items = items; + if (!isInitial || items.length > 0) { + quickPick.busy = false; + } + }; - disposables.add(quickPick.onDidTriggerButton(button => { - if (button === this._quickInputService.backButton) { - resolve(button); - } - })); - disposables.add(quickPick.onDidTriggerItemButton(async (e) => { - if (isKernelSourceQuickPickItem(e.item) && e.item.documentation !== undefined) { - const uri = URI.isUri(e.item.documentation) ? URI.parse(e.item.documentation) : await this._commandService.executeCommand(e.item.documentation); - if (uri) { - void this._openerService.open(uri, { openExternal: true }); - } - } - })); - disposables.add(quickPick.onDidAccept(async () => { - resolve(quickPick.selectedItems[0]); - })); - disposables.add(quickPick.onDidHide(() => { - resolve(undefined); - })); + // select from kernel sources + quickPick.title = kernelListEmpty ? localize('select', "Select Kernel") : localize('selectAnotherKernel', "Select Another Kernel"); + quickPick.placeholder = localize('selectKernel.placeholder', "Type to choose a kernel source"); + quickPick.busy = true; + quickPick.buttons = [this._quickInputService.backButton]; + quickPick.show(); - this._calculdateKernelSources(editor).then(quickPickItems => { - quickPick.items = quickPickItems; - if (quickPick.items.length > 0) { - quickPick.busy = false; + disposables.add(quickPick.onDidTriggerButton(button => { + if (button === this._quickInputService.backButton) { + finish(button); + } + })); + disposables.add(quickPick.onDidTriggerItemButton(async (e) => { + if (isKernelSourceQuickPickItem(e.item) && e.item.documentation !== undefined) { + const uri = URI.isUri(e.item.documentation) ? URI.parse(e.item.documentation) : await this._commandService.executeCommand(e.item.documentation); + if (uri) { + void this._openerService.open(uri, { openExternal: true }); } - }); + } + })); + disposables.add(quickPick.onDidAccept(async () => { + finish(quickPick.selectedItems[0]); + })); + disposables.add(quickPick.onDidHide(() => { + finish(undefined); + })); - disposables.add(Event.debounce( - Event.any( - this._notebookKernelService.onDidChangeSourceActions, - this._notebookKernelService.onDidAddKernel, - this._notebookKernelService.onDidRemoveKernel - ), - (last, _current) => last, - KERNEL_PICKER_UPDATE_DEBOUNCE - )(async () => { - quickPick.busy = true; - const quickPickItems = await this._calculdateKernelSources(editor); - quickPick.items = quickPickItems; - quickPick.busy = false; - })); - }); + void updateItems(true); + + disposables.add(Event.debounce( + Event.any( + this._notebookKernelService.onDidChangeSourceActions, + this._notebookKernelService.onDidAddKernel, + this._notebookKernelService.onDidRemoveKernel + ), + (last, _current) => last, + KERNEL_PICKER_UPDATE_DEBOUNCE + )(() => updateItems())); + + const quickPickItem = await promise; quickPick.hide(); disposables.dispose(); diff --git a/src/vs/workbench/contrib/notebook/common/model/notebookCellTextModel.ts b/src/vs/workbench/contrib/notebook/common/model/notebookCellTextModel.ts index fd9b856ab824..392d5a52a3b3 100644 --- a/src/vs/workbench/contrib/notebook/common/model/notebookCellTextModel.ts +++ b/src/vs/workbench/contrib/notebook/common/model/notebookCellTextModel.ts @@ -515,7 +515,7 @@ export function cloneNotebookCellTextModel(cell: NotebookCellTextModel) { mime: cell.mime, cellKind: cell.cellKind, outputs: cell.outputs.map(output => ({ - outputs: output.outputs, + outputs: output.outputs.slice(), /* paste should generate new outputId */ outputId: UUID.generateUuid() })), metadata: {} diff --git a/src/vs/workbench/contrib/notebook/test/browser/cellOperations.test.ts b/src/vs/workbench/contrib/notebook/test/browser/cellOperations.test.ts index ba4a760c42f7..ace4af0c6c7b 100644 --- a/src/vs/workbench/contrib/notebook/test/browser/cellOperations.test.ts +++ b/src/vs/workbench/contrib/notebook/test/browser/cellOperations.test.ts @@ -14,6 +14,7 @@ import { ResourceNotebookCellEdit } from '../../../bulkEdit/browser/bulkCellEdit import { ILanguageService } from '../../../../../editor/common/languages/language.js'; import { ITextBuffer, ValidAnnotatedEditOperation } from '../../../../../editor/common/model.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; suite('CellOperations', () => { ensureNoDisposablesAreLeakedInTestSuite(); @@ -190,6 +191,33 @@ suite('CellOperations', () => { }); }); + for (const targetIndex of [0, 1]) { + test(`Copy/duplicate cells - appending to ${targetIndex === 0 ? 'source' : 'copy'} does not change the other output`, async function () { + await withTestNotebook( + [ + ['test', 'javascript', CellKind.Code, [{ + outputId: 'original-output', + outputs: [{ mime: 'application/vnd.code.notebook.stdout', data: VSBuffer.fromString('before\n') }] + }], {}] + ], + async (editor, viewModel) => { + viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 0, end: 1 }, selections: [{ start: 0, end: 1 }] }); + await copyCellRange({ notebookEditor: editor, cell: viewModel.cellAt(0)! }, 'down'); + editor.textModel.applyEdits([{ + editType: CellEditType.OutputItems, + outputId: editor.textModel.cells[targetIndex].outputs[0].outputId, + append: true, + items: [{ mime: 'application/vnd.code.notebook.stdout', data: VSBuffer.fromString('after\n') }] + }], true, undefined, () => undefined, undefined, false); + + assert.deepStrictEqual( + editor.textModel.cells.map(cell => cell.outputs[0].outputs.map(item => item.data.toString())), + targetIndex === 0 ? [['before\nafter\n'], ['before\n']] : [['before\n'], ['before\nafter\n']] + ); + }); + }); + } + test('Join cell with below - single cell', async function () { await withTestNotebook( [ diff --git a/src/vs/workbench/contrib/notebook/test/browser/notebookKernelQuickPickStrategy.test.ts b/src/vs/workbench/contrib/notebook/test/browser/notebookKernelQuickPickStrategy.test.ts new file mode 100644 index 000000000000..83e284e32e12 --- /dev/null +++ b/src/vs/workbench/contrib/notebook/test/browser/notebookKernelQuickPickStrategy.test.ts @@ -0,0 +1,214 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IMenu, IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IQuickInputHideEvent, IQuickInputService, IQuickPick, IQuickPickDidAcceptEvent, IQuickPickItem, QuickInputHideReason, QuickPickInput } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IExtensionService } from '../../../../services/extensions/common/extensions.js'; +import { IExtensionManagementServerService } from '../../../../services/extensionManagement/common/extensionManagement.js'; +import { TestStorageService } from '../../../../test/common/workbenchTestServices.js'; +import { IExtensionsWorkbenchService } from '../../../extensions/common/extensions.js'; +import { IActiveNotebookEditor } from '../../browser/notebookBrowser.js'; +import { NotebookKernelService } from '../../browser/services/notebookKernelServiceImpl.js'; +import { KernelPickerMRUStrategy } from '../../browser/viewParts/notebookKernelQuickPickStrategy.js'; +import { NotebookTextModel } from '../../common/model/notebookTextModel.js'; +import { INotebookKernelSourceAction } from '../../common/notebookCommon.js'; +import { INotebookKernelHistoryService } from '../../common/notebookKernelService.js'; +import { INotebookService } from '../../common/notebookService.js'; + +class RecordingQuickPick extends Disposable { + private readonly hideEvent = this._register(new Emitter()); + private readonly acceptEvent = this._register(new Emitter()); + readonly onDidHide = this.hideEvent.event; + readonly onDidAccept = this.acceptEvent.event; + readonly onDidTriggerButton = Event.None; + readonly onDidTriggerItemButton = Event.None; + selectedItems: readonly T[] = []; + busy = false; + updates = 0; + private visible = false; + private _items: readonly QuickPickInput[] = []; + + get items(): readonly QuickPickInput[] { return this._items; } + set items(items: readonly QuickPickInput[]) { + this.updates++; + this._items = items; + } + + show(): void { this.visible = true; } + hide(): void { + if (this.visible) { + this.visible = false; + this.hideEvent.fire({ reason: QuickInputHideReason.Gesture }); + } + } + + acceptFirst(): void { + this.selectedItems = this.items.filter((item): item is T => item.type !== 'separator').slice(0, 1); + this.acceptEvent.fire({ inBackground: false }); + } +} + +suite('Notebook kernel source picker', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createPicker() { + const changes = store.add(new Emitter()); + const requests: DeferredPromise[] = []; + const requested = store.add(new Emitter()); + const contextKeyService = upcastPartial({}); + const kernelService = store.add(new NotebookKernelService( + upcastPartial({ onDidAddNotebookDocument: Event.None, onWillRemoveNotebookDocument: Event.None }), + store.add(new TestStorageService()), + upcastPartial({ createMenu: () => upcastPartial({ onDidChange: Event.None, getActions: () => [], dispose: () => { } }) }), + contextKeyService, + )); + store.add(kernelService.registerKernelSourceActionProvider('test', { + viewType: 'test', + onDidChangeSourceActions: changes.event, + provideKernelSourceActions: () => { + const request = new DeferredPromise(); + requests.push(request); + requested.fire(); + return request.p; + }, + })); + const picks: RecordingQuickPick[] = []; + const quickInput = new class extends mock() { + override readonly backButton = { iconClass: 'test-back' }; + override createQuickPick(options: { useSeparators: true }): IQuickPick; + override createQuickPick(options?: { useSeparators: boolean }): IQuickPick; + override createQuickPick(): IQuickPick | IQuickPick { + const pick = store.add(new RecordingQuickPick()); + picks.push(pick); + return upcastPartial>(pick); + } + }; + const executed: { id: string; args: unknown[] }[] = []; + const strategy = new KernelPickerMRUStrategy( + kernelService, upcastPartial({}), quickInput, upcastPartial({}), new NullLogService(), + upcastPartial({}), upcastPartial({ extensions: [] }), + upcastPartial({}), + upcastPartial({ executeCommand: async (id: string, ...args: unknown[]) => { executed.push({ id, args }); return 'selected-kernel' as T; } }), + upcastPartial({ getKernels: () => ({ selected: undefined, all: [] }) }), upcastPartial({}), + ); + const editor = upcastPartial({ + textModel: upcastPartial({ uri: URI.parse('test:///notebook'), notebookType: 'test', viewType: 'test', metadata: {}, cells: [] }), + scopedContextKeyService: contextKeyService, + }); + const action: INotebookKernelSourceAction = { label: 'Current source', command: { title: 'Select', id: 'test.kernel', arguments: [{ label: 'current' }] } }; + const oldAction: INotebookKernelSourceAction = { label: 'Old source', command: 'test.oldKernel' }; + return { + strategy, editor, picks, changes, executed, action, oldAction, + async request(index: number) { + while (requests.length <= index) { + await Event.toPromise(requested.event); + } + return requests[index]; + }, + async complete(index: number, actions: INotebookKernelSourceAction[]) { + await requests[index].complete(actions); + await timeout(0); + }, + }; + } + + for (const initialPending of [true, false]) { + test(`keeps newer source actions when an older ${initialPending ? 'initial calculation' : 'refresh'} finishes last`, async () => { + const fixture = createPicker(); + const result = fixture.strategy.showQuickPick(fixture.editor); + await fixture.request(0); + const pick = fixture.picks[1]; + try { + let older = 0; + if (!initialPending) { + await fixture.complete(0, [fixture.action]); + fixture.changes.fire(); + await fixture.request(1); + older = 1; + } + fixture.changes.fire(); + await fixture.request(older + 1); + await fixture.complete(older + 1, [fixture.action]); + const items = pick.items; + await fixture.complete(older, [fixture.oldAction]); + assert.deepStrictEqual({ preserved: pick.items === items, labels: pick.items.map(item => item.label), busy: pick.busy }, { + preserved: true, labels: [fixture.action.label], busy: false, + }); + pick.acceptFirst(); + assert.deepStrictEqual({ selected: await result, executed: fixture.executed }, { selected: true, executed: [{ id: 'test.kernel', args: [{ label: 'current' }] }] }); + } finally { + pick.hide(); + await result; + } + }); + } + + test('does not clear current actions or loading state when an obsolete refresh finishes before the latest', async () => { + const fixture = createPicker(); + const result = fixture.strategy.showQuickPick(fixture.editor); + await fixture.request(0); + const pick = fixture.picks[1]; + try { + await fixture.complete(0, [fixture.action]); + const items = pick.items; + fixture.changes.fire(); + await fixture.request(1); + fixture.changes.fire(); + await fixture.request(2); + await fixture.complete(1, [fixture.oldAction]); + assert.deepStrictEqual({ preserved: pick.items === items, busy: pick.busy }, { preserved: true, busy: true }); + await fixture.complete(2, [fixture.action]); + assert.deepStrictEqual({ labels: pick.items.map(item => item.label), busy: pick.busy }, { labels: [fixture.action.label], busy: false }); + } finally { + pick.hide(); + await result; + } + }); + + test('accepts a genuinely empty latest response without allowing an older response to replace it', async () => { + const fixture = createPicker(); + const result = fixture.strategy.showQuickPick(fixture.editor); + await fixture.request(0); + const pick = fixture.picks[1]; + try { + fixture.changes.fire(); + await fixture.request(1); + await fixture.complete(1, []); + const items = pick.items; + await fixture.complete(0, [fixture.oldAction]); + assert.deepStrictEqual({ preserved: pick.items === items, ids: pick.items.map(item => item.type === 'separator' ? undefined : item.id), busy: pick.busy }, { + preserved: true, ids: ['install'], busy: false, + }); + } finally { + pick.hide(); + await result; + } + }); + + test('ignores source calculations that complete after the picker closes', async () => { + const fixture = createPicker(); + const result = fixture.strategy.showQuickPick(fixture.editor); + await fixture.request(0); + const pick = fixture.picks[1]; + pick.hide(); + await result; + const updates = pick.updates; + await fixture.complete(0, [fixture.action]); + assert.strictEqual(pick.updates, updates); + }); +}); diff --git a/src/vs/workbench/contrib/onboarding/browser/spotlight/onboardingTarget.ts b/src/vs/workbench/contrib/onboarding/browser/spotlight/onboardingTarget.ts index c37323546cbf..12c9b8c5fc3d 100644 --- a/src/vs/workbench/contrib/onboarding/browser/spotlight/onboardingTarget.ts +++ b/src/vs/workbench/contrib/onboarding/browser/spotlight/onboardingTarget.ts @@ -162,7 +162,7 @@ export function pulseOnboardingTarget(element: HTMLElement): IDisposable { */ export function findOnboardingTarget(targetWindow: Window, id: string, scope?: string): HTMLElement | undefined { const selector = `[${ONBOARDING_TARGET_ATTR}="${CSS.escape(id)}"]`; - // eslint-disable-next-line no-restricted-syntax -- matching only our own onboarding attribute (never foreign classes/structure) is the whole point of this helper + // eslint-disable-next-line eslint-js/no-restricted-syntax -- matching only our own onboarding attribute (never foreign classes/structure) is the whole point of this helper const targets = Array.from(targetWindow.document.querySelectorAll(selector)); return targets.find(target => isVisibleOnboardingTarget(targetWindow, target) && matchesScope(target, scope)); } @@ -172,7 +172,8 @@ function matchesScope(target: HTMLElement, scope: string | undefined): boolean { return (typeof registeredScope === 'function' ? registeredScope() : registeredScope) === scope; } -function isVisibleOnboardingTarget(targetWindow: Window, target: HTMLElement): boolean { +/** Whether a target can be presented in the given window. */ +export function isVisibleOnboardingTarget(targetWindow: Window, target: HTMLElement): boolean { if (!target.isConnected || target.ownerDocument !== targetWindow.document) { return false; } diff --git a/src/vs/workbench/contrib/onboarding/browser/spotlight/spotlightOverlay.ts b/src/vs/workbench/contrib/onboarding/browser/spotlight/spotlightOverlay.ts index 3d65224e24d1..bee8613dcd2c 100644 --- a/src/vs/workbench/contrib/onboarding/browser/spotlight/spotlightOverlay.ts +++ b/src/vs/workbench/contrib/onboarding/browser/spotlight/spotlightOverlay.ts @@ -292,7 +292,7 @@ export class SpotlightOverlay extends Disposable { this._stepListeners.add(addDisposableListener(focusElement, EventType.KEY_DOWN, onTargetKey, true)); this._stepListeners.add(addDisposableListener(focusElement, EventType.KEY_UP, onTargetKey, true)); } else if (options.allowTargetInteraction || advanceOnTargetClick || options.hideNext) { - this._stepListeners.add(addDisposableListener(focusElement, EventType.KEY_DOWN, e => this._onKeyDown(e))); + this._stepListeners.add(addDisposableListener(focusElement, EventType.KEY_DOWN, e => this._onKeyDown(e), true)); } this.layout(); @@ -560,11 +560,11 @@ export class SpotlightOverlay extends Disposable { private _collectFocusable(): HTMLElement[] { const targetFocusables = (this._options.allowTargetInteraction || this._options.advanceOnTargetClick || this._options.hideNext) && this._target ? this._options.focusTarget ? [this._options.focusTarget.element] - // eslint-disable-next-line no-restricted-syntax -- querying the spotlight target subtree for focusable controls + // eslint-disable-next-line eslint-js/no-restricted-syntax -- querying the spotlight target subtree for focusable controls : [this._target, ...this._target.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])')] : []; const descriptionFocusables = Array.from( - // eslint-disable-next-line no-restricted-syntax -- querying our own callout description subtree for focusable markdown content (e.g. links) + // eslint-disable-next-line eslint-js/no-restricted-syntax -- querying our own callout description subtree for focusable markdown content (e.g. links) this._description.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])') ); const buttons = [this._skipButton, this._backButton, this._nextButton] diff --git a/src/vs/workbench/contrib/onboarding/test/browser/spotlightOverlay.test.ts b/src/vs/workbench/contrib/onboarding/test/browser/spotlightOverlay.test.ts index db0b68f907e9..2c58e0b34fb9 100644 --- a/src/vs/workbench/contrib/onboarding/test/browser/spotlightOverlay.test.ts +++ b/src/vs/workbench/contrib/onboarding/test/browser/spotlightOverlay.test.ts @@ -5,7 +5,7 @@ import assert from 'assert'; import { $, addDisposableListener, EventType, scheduleAtNextAnimationFrame } from '../../../../../base/browser/dom.js'; -import { Button } from '../../../../../base/browser/ui/button/button.js'; +import { Button, ButtonWithDropdown } from '../../../../../base/browser/ui/button/button.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { timeout } from '../../../../../base/common/async.js'; import { Event } from '../../../../../base/common/event.js'; @@ -403,6 +403,28 @@ suite('SpotlightOverlay', () => { }); }); + for (const half of ['primary', 'dropdown'] as const) { + test(`Escape from a split button's ${half} half dismisses its wrapper spotlight`, () => { + const container = createContainer(); + const target = disposables.add(new ButtonWithDropdown(container, { + ...defaultButtonStyles, + contextMenuProvider: { showContextMenu: () => { } }, + actions: [], + })); + target.label = 'Create with Agent'; + const overlay = disposables.add(new SpotlightOverlay(container, FakeResizeObserver)); + const reasons: OnboardingDismissReason[] = []; + disposables.add(overlay.onDidSkip(reason => reasons.push(reason))); + overlay.show(target.element, content(), { allowTargetInteraction: true }); + + const button = half === 'primary' ? target.primaryButton : target.dropdownButton; + button.focus(); + button.element.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + + assert.deepStrictEqual(reasons, [OnboardingDismissReason.EscapeKey]); + }); + } + test('Escape in external target UI skips without consuming the native dismissal', () => { const container = createContainer(); const overlay = disposables.add(new SpotlightOverlay(container, FakeResizeObserver)); diff --git a/src/vs/workbench/contrib/preferences/browser/media/settingsEditor2.css b/src/vs/workbench/contrib/preferences/browser/media/settingsEditor2.css index 067ca61be161..ddff4eda8f33 100644 --- a/src/vs/workbench/contrib/preferences/browser/media/settingsEditor2.css +++ b/src/vs/workbench/contrib/preferences/browser/media/settingsEditor2.css @@ -663,7 +663,7 @@ height: 18px; width: 18px; border: 1px solid transparent; - border-radius: 3px; + border-radius: var(--workbench-custom-controls-corner-radius, 3px); margin-right: 9px; margin-left: 0px; padding: 0px; diff --git a/src/vs/workbench/contrib/preferences/browser/settingsEditor2.ts b/src/vs/workbench/contrib/preferences/browser/settingsEditor2.ts index d9c338df77cc..9698347e91d5 100644 --- a/src/vs/workbench/contrib/preferences/browser/settingsEditor2.ts +++ b/src/vs/workbench/contrib/preferences/browser/settingsEditor2.ts @@ -664,7 +664,7 @@ export class SettingsEditor2 extends EditorPane { } else if (this._currentFocusContext === SettingsFocusContext.SettingControl) { const element = this.focusedSettingDOMElement; if (element) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const control = element.querySelector(AbstractSettingRenderer.CONTROL_SELECTOR); if (control) { (control).focus(); @@ -699,7 +699,7 @@ export class SettingsEditor2 extends EditorPane { this.settingsTree.domFocus(); if (focusSettingInput) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const controlInFocusedRow = this.settingsTree.getHTMLElement().querySelector(`.focused ${AbstractSettingRenderer.CONTROL_SELECTOR}`); if (controlInFocusedRow) { (controlInFocusedRow).focus(); @@ -969,7 +969,7 @@ export class SettingsEditor2 extends EditorPane { } private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const targetElement = this.currentSettingsModel?.getElementsByName(evt.targetKey)?.[0]; let revealFailed = false; if (targetElement) { @@ -1010,7 +1010,7 @@ export class SettingsEditor2 extends EditorPane { const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey); if (domElements && domElements[0]) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR); if (control) { (control).focus(); @@ -1656,7 +1656,7 @@ export class SettingsEditor2 extends EditorPane { const newModel = this.settingsTreeModel.value; let newElement: SettingsTreeElement | undefined; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const settings = newModel.getElementsByName(anchorId); if (settings && settings.length > 0) { newElement = settings[0]; @@ -1788,7 +1788,7 @@ export class SettingsEditor2 extends EditorPane { this.renderResultCountMessages(false); if (key) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const elements = this.currentSettingsModel?.getElementsByName(key); if (elements?.length) { if (elements.length >= 2) { @@ -1831,7 +1831,7 @@ export class SettingsEditor2 extends EditorPane { if (!this.currentSettingsModel) { return; } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const dataElements = this.currentSettingsModel.getElementsByName(key); const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key); diff --git a/src/vs/workbench/contrib/preferences/browser/settingsTree.ts b/src/vs/workbench/contrib/preferences/browser/settingsTree.ts index 09a11f3625e2..3c8cd52a1a0e 100644 --- a/src/vs/workbench/contrib/preferences/browser/settingsTree.ts +++ b/src/vs/workbench/contrib/preferences/browser/settingsTree.ts @@ -819,7 +819,7 @@ export interface ISettingLinkClickEvent { } function removeChildrenFromTabOrder(node: Element): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const focusableElements = node.querySelectorAll(` [tabindex="0"], input:not([tabindex="-1"]), @@ -837,7 +837,7 @@ function removeChildrenFromTabOrder(node: Element): void { } function addChildrenToTabOrder(node: Element): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const focusableElements = node.querySelectorAll( `[${AbstractSettingRenderer.ELEMENT_FOCUSABLE_ATTR}="true"]` ); @@ -1330,7 +1330,7 @@ class SettingArrayRenderer extends AbstractSettingRenderer implements ITreeRende renderTemplate(container: HTMLElement): ISettingListItemTemplate { const common = this.renderCommonTemplate(null, container, 'list'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionElement = common.containerElement.querySelector('.setting-item-description')!; const validationErrorMessageElement = $('.setting-item-validation-message'); descriptionElement.after(validationErrorMessageElement); @@ -1446,7 +1446,7 @@ abstract class AbstractSettingObjectRenderer extends AbstractSettingRenderer imp widget.domNode.classList.add(AbstractSettingRenderer.CONTROL_CLASS); common.toDispose.add(widget); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const descriptionElement = common.containerElement.querySelector('.setting-item-description')!; const validationErrorMessageElement = $('.setting-item-validation-message'); descriptionElement.after(validationErrorMessageElement); @@ -1896,7 +1896,7 @@ class SettingEnumRenderer extends AbstractSettingRenderer implements ITreeRender common.toDispose.add(selectBox); selectBox.render(common.controlElement); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const selectElement = common.controlElement.querySelector('select'); if (selectElement) { selectElement.classList.add(AbstractSettingRenderer.CONTROL_CLASS); @@ -2312,7 +2312,7 @@ export class SettingTreeRenderers extends Disposable { } showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const toolbarElement = settingDOMElement.querySelector('.monaco-toolbar'); if (toolbarElement) { this._contextMenuService.showContextMenu({ @@ -2333,7 +2333,7 @@ export class SettingTreeRenderers extends Disposable { } getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax return treeContainer.querySelectorAll(`[${AbstractSettingRenderer.SETTING_KEY_ATTR}="${key}"]`); } diff --git a/src/vs/workbench/contrib/processExplorer/browser/processExplorerControl.ts b/src/vs/workbench/contrib/processExplorer/browser/processExplorerControl.ts index b54812a080aa..24f09d89d491 100644 --- a/src/vs/workbench/contrib/processExplorer/browser/processExplorerControl.ts +++ b/src/vs/workbench/contrib/processExplorer/browser/processExplorerControl.ts @@ -425,7 +425,7 @@ export abstract class ProcessExplorerControl extends Disposable { selectionPids.push(pid); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const rows = selectionPids?.map(e => getDocument(container).getElementById(`pid-${e}`)).filter(e => !!e); if (rows) { const text = rows.map(e => e.innerText).filter(e => !!e); @@ -438,7 +438,7 @@ export abstract class ProcessExplorerControl extends Disposable { id: 'copyAll', label: localize('copyAll', "Copy All"), run: () => { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const processList = getDocument(container).getElementById('process-explorer'); if (processList) { this.clipboardService.writeText(processList.innerText); diff --git a/src/vs/workbench/contrib/scm/browser/media/scm.css b/src/vs/workbench/contrib/scm/browser/media/scm.css index 94bfe2c4f061..b014f09c8b2a 100644 --- a/src/vs/workbench/contrib/scm/browser/media/scm.css +++ b/src/vs/workbench/contrib/scm/browser/media/scm.css @@ -290,12 +290,67 @@ overflow: hidden; } +.scm-view .scm-structural-change > .scm-structural-change-icon { + display: flex; + align-items: center; + flex-shrink: 0; + width: var(--vscode-spacing-size160); + margin-right: var(--vscode-spacing-size60); +} + +.scm-view .scm-structural-change > .name { + min-width: 0; +} + +.scm-view .scm-structural-change > .scm-structural-change-metadata { + display: flex; + align-items: center; + flex-shrink: 0; + gap: var(--vscode-spacing-size60); + margin-left: var(--vscode-spacing-size60); +} + +.scm-view .scm-structural-change-annotation { + font-size: var(--vscode-fontSize-label1); + white-space: nowrap; + opacity: 0.7; +} + +.scm-view .scm-structural-change-status.added { + color: var(--vscode-gitDecoration-addedResourceForeground); +} + +.scm-view .scm-structural-change-status.deleted { + color: var(--vscode-gitDecoration-deletedResourceForeground); +} + +.scm-view .scm-structural-change-status.modified, +.scm-view .scm-structural-change-status.renamed { + color: var(--vscode-gitDecoration-modifiedResourceForeground); +} + +/* Like the file badges in iconlabel.css, status letters are dimmed and use the selection foreground in a focused list. */ +.scm-view .scm-structural-change-status { + opacity: 0.75; +} + +.scm-view .monaco-list:focus .monaco-list-row.selected .scm-structural-change-status { + color: inherit; +} + +/* + * Structural status letters share the file badge box and right margin, so single letters line up with file badges. + * Wider badges, such as a problem count followed by a status letter, extend to the left. + * See https://github.com/microsoft/vscode/issues/346073 + */ .scm-view .monaco-list-row .resource > .name > .monaco-icon-label::after, -.scm-view .monaco-list-row .history-item-change > .label-container > .monaco-icon-label::after { +.scm-view .monaco-list-row .history-item-change > .label-container > .monaco-icon-label::after, +.scm-view .scm-structural-change-status { margin-right: 3px; } -.scm-view .monaco-list-row .resource > .name > .monaco-icon-label.monaco-decoration-text-badge::after { +.scm-view .monaco-list-row .resource > .name > .monaco-icon-label.monaco-decoration-text-badge::after, +.scm-view .scm-structural-change-status { display: inline-flex; align-items: center; justify-content: center; @@ -653,12 +708,19 @@ margin: 4px 0; } -.monaco-hover.history-item-hover .history-item-hover-container div:nth-of-type(3):nth-last-of-type(2) > p { +.monaco-hover.history-item-hover .history-item-hover-container > .history-item-hover-references > p { display: flex; flex-wrap: wrap; gap: 4px; } +.monaco-hover.history-item-hover .history-item-hover-container > .history-item-hover-references > p > span { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + .monaco-hover.history-item-hover .history-item-hover-container span:not(.codicon) { margin-bottom: 0 !important; } diff --git a/src/vs/workbench/contrib/scm/browser/scm.contribution.ts b/src/vs/workbench/contrib/scm/browser/scm.contribution.ts index 22920b5f2d15..dbd145159a10 100644 --- a/src/vs/workbench/contrib/scm/browser/scm.contribution.ts +++ b/src/vs/workbench/contrib/scm/browser/scm.contribution.ts @@ -382,6 +382,12 @@ Registry.as(ConfigurationExtensions.Configuration).regis description: localize('scm.compactFolders', "Controls whether the Source Control view should render folders in a compact form. In such a form, single child folders will be compressed in a combined tree element."), default: true }, + 'scm.structuralDiff.enabled': { + type: 'boolean', + description: localize('scm.structuralDiff.enabled', "Controls whether the Source Control view can show the symbols that changed in a file. When enabled and an extension provides structural diffs for the file, use \"Show Structural Diff\" in the \"View & Sort\" menu to show or hide them."), + default: false, + tags: ['experimental'] + }, 'scm.graph.pageOnScroll': { type: 'boolean', description: localize('scm.graph.pageOnScroll', "Controls whether the Source Control Graph view will load the next page of items when you scroll to the end of the list."), diff --git a/src/vs/workbench/contrib/scm/browser/scmAccessibilityHelp.ts b/src/vs/workbench/contrib/scm/browser/scmAccessibilityHelp.ts index 18908231a3cf..a07667856a2a 100644 --- a/src/vs/workbench/contrib/scm/browser/scmAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/scm/browser/scmAccessibilityHelp.ts @@ -4,16 +4,19 @@ *--------------------------------------------------------------------------------------------*/ import { Disposable } from '../../../../base/common/lifecycle.js'; +import { ILanguageFeaturesService } from '../../../../editor/common/services/languageFeatures.js'; import { localize } from '../../../../nls.js'; import { AccessibleViewType, AccessibleContentProvider, IAccessibleViewContentProvider, AccessibleViewProviderId } from '../../../../platform/accessibility/browser/accessibleView.js'; import { IAccessibleViewImplementation } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { ICommandService } from '../../../../platform/commands/common/commands.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 { FocusedViewContext, SidebarFocusContext } from '../../../common/contextkeys.js'; import { IViewsService } from '../../../services/views/common/viewsService.js'; import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js'; import { HISTORY_VIEW_PANE_ID, ISCMViewService, REPOSITORIES_VIEW_PANE_ID, VIEW_PANE_ID } from '../common/scm.js'; +import { hasSCMStructuralDiffProvider } from '../common/scmStructuralDiff.js'; export class SCMAccessibilityHelp implements IAccessibleViewImplementation { readonly name = 'scm'; @@ -30,8 +33,10 @@ export class SCMAccessibilityHelp implements IAccessibleViewImplementation { const commandService = accessor.get(ICommandService); const scmViewService = accessor.get(ISCMViewService); const viewsService = accessor.get(IViewsService); + const languageFeaturesService = accessor.get(ILanguageFeaturesService); + const configurationService = accessor.get(IConfigurationService); - return new SCMAccessibilityHelpContentProvider(commandService, scmViewService, viewsService); + return new SCMAccessibilityHelpContentProvider(commandService, scmViewService, viewsService, languageFeaturesService, configurationService); } } @@ -45,7 +50,9 @@ class SCMAccessibilityHelpContentProvider extends Disposable implements IAccessi constructor( @ICommandService private readonly _commandService: ICommandService, @ISCMViewService private readonly _scmViewService: ISCMViewService, - @IViewsService private readonly _viewsService: IViewsService + @IViewsService private readonly _viewsService: IViewsService, + @ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService, + @IConfigurationService private readonly _configurationService: IConfigurationService ) { super(); this._focusedView = this._viewsService.getFocusedViewName(); @@ -123,6 +130,15 @@ class SCMAccessibilityHelpContentProvider extends Disposable implements IAccessi content.push(localize('scm-msg3', "Once the Source Control view is opened you can:")); content.push(localize('scm-msg4', " - Use the up/down arrow keys to navigate the list of repositories, resource groups and resources.")); content.push(localize('scm-msg5', " - Use the Space key to expand or collapse a resource group.")); + if (this._configurationService.getValue('scm.structuralDiff.enabled') === true && hasSCMStructuralDiffProvider(this._languageFeaturesService)) { + content.push(localize('scm-structural-toggle', " - Toggle \"Show Structural Diff\" in the \"View & Sort\" menu to show or hide changed symbols below files.")); + content.push(localize('scm-structural-msg1', " - When \"Show Structural Diff\" is enabled, files with a structural diff provider can be expanded with the right arrow key to show changed symbols. Structural descendants expand automatically to reveal changed leaves. Use the left arrow key to collapse them.")); + content.push(localize('scm-structural-staged', " - For Git, staged structural changes compare HEAD with the index, while unstaged structural changes compare the index with the working file. Both versions of the file and a provider that supports their document types are required.")); + content.push(localize('scm-structural-msg2', " - Press Enter on a changed symbol to open its file diff at that symbol. Deleted symbols open on the original side, or where they were deleted when the diff is shown inline. File-level actions continue to apply to file rows.")); + content.push(localize('scm-structural-status', " - Changed symbols use A for additions, D for deletions, M for modifications, and R for renames. Their status is included in the accessible label. Unchanged containers have no status marker.")); + content.push(localize('scm-structural-annotations', " - Modified symbols indicate whether their declaration, implementation, or both changed. These details are included in accessible labels.")); + content.push(localize('scm-structural-rename', " - Detected renames appear with the new symbol name and an R status marker, without a change annotation. The original and new names are included in the hover and accessible label.")); + } // Source Control Graph content.push(localize('scm-graph-msg1', "Use the \"Source Control: Focus on Source Control Graph View\" command to open the Source Control Graph view.")); diff --git a/src/vs/workbench/contrib/scm/browser/scmHistory.ts b/src/vs/workbench/contrib/scm/browser/scmHistory.ts index b7443247c73b..c572bbbefae6 100644 --- a/src/vs/workbench/contrib/scm/browser/scmHistory.ts +++ b/src/vs/workbench/contrib/scm/browser/scmHistory.ts @@ -16,6 +16,7 @@ import { IMarkdownString, isEmptyMarkdownString, isMarkdownString, MarkdownStrin import { ThemeIcon } from '../../../../base/common/themables.js'; import { IMarkdownRendererService } from '../../../../platform/markdown/browser/markdownRenderer.js'; import { findLastIdx } from '../../../../base/common/arraysFind.js'; +import { htmlAttributeEncodeValue } from '../../../../base/common/strings.js'; export const SWIMLANE_HEIGHT = 22; export const SWIMLANE_WIDTH = 11; @@ -573,16 +574,20 @@ export function toHistoryItemHoverContent(markdownRendererService: IMarkdownRend // the reference is pointing to. They are being added before the last element // of the array which is assumed to contain the hover commands. const tooltipSections = historyItem.tooltip.slice(); + let referencesMarkdownString: MarkdownString | undefined; if (includeReferences && historyItem.references?.length) { - const markdownString = new MarkdownString('', { supportHtml: true, supportThemeIcons: true }); + const markdownString = referencesMarkdownString = new MarkdownString('', { supportHtml: true, supportThemeIcons: true }); for (const reference of historyItem.references) { const labelIconId = ThemeIcon.isThemeIcon(reference.icon) ? reference.icon.id : ''; const labelBackgroundColor = reference.color ? asCssVariable(reference.color) : asCssVariable(historyItemHoverDefaultLabelBackground); const labelForegroundColor = reference.color ? asCssVariable(historyItemHoverLabelForeground) : asCssVariable(historyItemHoverDefaultLabelForeground); - markdownString.appendMarkdown(` $(${labelIconId}) `); + // Long names are truncated (see scm.css), so expose the full name as a title. `$` is + // encoded so that theme icon rendering does not rewrite `$(...)` inside the attribute + const labelTitle = htmlAttributeEncodeValue(reference.name).replace(/\$/g, '$'); + markdownString.appendMarkdown(` $(${labelIconId}) `); markdownString.appendText(reference.name); markdownString.appendMarkdown('  '); } @@ -599,6 +604,7 @@ export function toHistoryItemHoverContent(markdownRendererService: IMarkdownRend } const renderedContent = markdownRendererService.render(markdownString); + renderedContent.element.classList.toggle('history-item-hover-references', markdownString === referencesMarkdownString); hoverContainer.appendChild(renderedContent.element); disposables.add(renderedContent); } diff --git a/src/vs/workbench/contrib/scm/browser/scmStructuralDiffRenderer.ts b/src/vs/workbench/contrib/scm/browser/scmStructuralDiffRenderer.ts new file mode 100644 index 000000000000..cab6db1c1b87 --- /dev/null +++ b/src/vs/workbench/contrib/scm/browser/scmStructuralDiffRenderer.ts @@ -0,0 +1,139 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { IconLabel } from '../../../../base/browser/ui/iconLabel/iconLabel.js'; +import { HoverStyle } from '../../../../base/browser/ui/hover/hover.js'; +import { ITreeNode } from '../../../../base/browser/ui/tree/tree.js'; +import { ICompressibleTreeRenderer } from '../../../../base/browser/ui/tree/objectTree.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { FuzzyScore, createMatches } from '../../../../base/common/filters.js'; +import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { SymbolKinds } from '../../../../editor/common/languages.js'; +import { SCMStructuralDiffElement, SCMStructuralDiffNode, getSCMStructuralDiffAriaLabel, getSCMStructuralDiffChange, getSCMStructuralDiffChangeAnnotation, getSCMStructuralDiffLabel } from '../common/scmStructuralDiff.js'; +import { ICodeEditor, isDiffEditor } from '../../../../editor/browser/editorBrowser.js'; +import { IRange, Range } from '../../../../editor/common/core/range.js'; +import { ScrollType } from '../../../../editor/common/editorCommon.js'; +import { IEditorOptions, TextEditorSelectionSource } from '../../../../platform/editor/common/editor.js'; +import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { localize } from '../../../../nls.js'; +import { DEFAULT_EDITOR_ASSOCIATION } from '../../../common/editor.js'; +import { IEditorService, SIDE_GROUP } from '../../../services/editor/common/editorService.js'; +import '../../../../editor/contrib/symbolIcons/browser/symbolIcons.js'; + +interface StructuralDiffTemplate extends IDisposable { + readonly icon: HTMLElement; + readonly label: IconLabel; + readonly metadata: HTMLElement; + readonly annotation: HTMLElement; + readonly status: HTMLElement; + readonly elementDisposables: DisposableStore; +} + +export class SCMStructuralDiffRenderer implements ICompressibleTreeRenderer { + static readonly TEMPLATE_ID = 'scmStructuralDiff'; + readonly templateId = SCMStructuralDiffRenderer.TEMPLATE_ID; + private readonly hoverGroupId = generateUuid(); + + constructor(@IHoverService private readonly hoverService: IHoverService) { } + + renderTemplate(container: HTMLElement): StructuralDiffTemplate { + const disposables = new DisposableStore(); + const row = append(container, $('.resource.scm-structural-change')); + const icon = append(row, $('.scm-structural-change-icon')); + icon.setAttribute('aria-hidden', 'true'); + const label = disposables.add(new IconLabel(append(row, $('.name')), { supportHighlights: true })); + const metadata = append(row, $('.scm-structural-change-metadata')); + metadata.setAttribute('aria-hidden', 'true'); + const annotation = append(metadata, $('span.scm-structural-change-annotation')); + const status = append(metadata, $('.scm-structural-change-status')); + status.setAttribute('aria-hidden', 'true'); + const elementDisposables = disposables.add(new DisposableStore()); + return { icon, label, metadata, annotation, status, elementDisposables, dispose: () => disposables.dispose() }; + } + + renderElement(node: ITreeNode, _index: number, template: StructuralDiffTemplate): void { + const element = node.element; + const item = element.type === 'structuralDiff' ? element.node.modifiedItem ?? element.node.originalItem : undefined; + const change = getSCMStructuralDiffChange(element); + const annotation = getSCMStructuralDiffChangeAnnotation(element); + template.elementDisposables.clear(); + template.icon.className = 'scm-structural-change-icon'; + template.icon.classList.add(...ThemeIcon.asClassNameArray(item ? SymbolKinds.toIcon(item.kind) : Codicon.warning)); + template.icon.classList.toggle('codicon-colored', !!item); + template.label.setLabel(getSCMStructuralDiffLabel(element), item?.detail, { + title: getSCMStructuralDiffAriaLabel(element), + matches: createMatches(node.filterData), + labelEscapeNewLines: true, + }); + template.annotation.textContent = annotation?.label ?? ''; + template.annotation.style.display = annotation ? '' : 'none'; + template.status.className = 'scm-structural-change-status'; + template.status.textContent = ''; + template.metadata.style.display = change ? '' : 'none'; + if (change) { + template.status.textContent = change.type === 'added' + ? localize('structuralDiff.addedMarker', "A") + : change.type === 'deleted' + ? localize('structuralDiff.deletedMarker', "D") + : change.type === 'renamed' + ? localize('structuralDiff.renamedMarker', "R") + : localize('structuralDiff.modifiedMarker', "M"); + template.status.classList.add(change.type); + template.elementDisposables.add(this.hoverService.setupDelayedHoverAtMouse(template.metadata, { + content: annotation?.description ?? change.label, + style: HoverStyle.Mouse, + }, { groupId: this.hoverGroupId })); + } + } + + disposeElement(_node: ITreeNode, _index: number, template: StructuralDiffTemplate): void { + template.elementDisposables.clear(); + } + + renderCompressedElements(): void { + throw new Error('Structural change nodes cannot be compressed'); + } + + disposeTemplate(template: StructuralDiffTemplate): void { + template.dispose(); + } +} + +export async function openSCMStructuralDiff(element: SCMStructuralDiffNode, options: IEditorOptions, editorService: IEditorService, isCurrent: () => boolean, sideBySide = false): Promise { + if (!isCurrent()) { + return; + } + const pane = await editorService.openEditor({ + original: { resource: element.resource.multiDiffEditorOriginalUri! }, + modified: { resource: element.resource.multiDiffEditorModifiedUri! }, + options: { ...options, override: DEFAULT_EDITOR_ASSOCIATION.id }, + }, sideBySide ? SIDE_GROUP : undefined); + const control = pane?.getControl(); + if (!isDiffEditor(control) || !isCurrent()) { + return; + } + const { originalItem, modifiedItem } = element.node; + let target: ICodeEditor; + let range: IRange; + if (modifiedItem) { + target = control.getModifiedEditor(); + range = modifiedItem.selectionRange ?? modifiedItem.range; + } else if (control.renderSideBySide || !element.deletedAt) { + target = control.getOriginalEditor(); + range = originalItem!.selectionRange ?? originalItem!.range; + } else { + // An inline diff hides the original editor and shows deleted text where it was deleted from the modified document. + target = control.getModifiedEditor(); + range = Range.fromPositions(element.deletedAt); + } + target.setSelection(range, TextEditorSelectionSource.NAVIGATION); + target.revealRangeInCenterIfOutsideViewport(range, ScrollType.Smooth); + if (!options.preserveFocus) { + target.focus(); + } +} diff --git a/src/vs/workbench/contrib/scm/browser/scmViewPane.ts b/src/vs/workbench/contrib/scm/browser/scmViewPane.ts index 25a505469d94..8309d3b11d86 100644 --- a/src/vs/workbench/contrib/scm/browser/scmViewPane.ts +++ b/src/vs/workbench/contrib/scm/browser/scmViewPane.ts @@ -70,13 +70,34 @@ import { rot } from '../../../../base/common/numbers.js'; import { IHoverService } from '../../../../platform/hover/browser/hover.js'; import { OpenScmGroupAction } from '../../multiDiffEditor/browser/scmMultiDiffSourceResolver.js'; import { autorun } from '../../../../base/common/observable.js'; -import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; +import { bindContextKey, observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js'; import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; import { AccessibilityCommandId } from '../../accessibility/common/accessibilityCommands.js'; import { SCMInputWidget } from './scmInput.js'; +import { SCM_STRUCTURAL_DIFF_ID_PREFIX, SCMStructuralDiffElement, SCMStructuralDiffModel, getSCMStructuralDiffAriaLabel, getSCMStructuralDiffLabel, isSCMStructuralDiffElement } from '../common/scmStructuralDiff.js'; +import { SCMStructuralDiffRenderer, openSCMStructuralDiff } from './scmStructuralDiffRenderer.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; -type TreeElement = ISCMRepository | ISCMInput | ISCMActionButton | ISCMResourceGroup | ISCMResource | IResourceNode; +type TreeElement = ISCMRepository | ISCMInput | ISCMActionButton | ISCMResourceGroup | ISCMResource | IResourceNode | SCMStructuralDiffElement; + +export function isSCMTreeElementCollapsedByDefault(element: unknown): boolean { + return !(isSCMRepository(element) || isSCMResourceGroup(element) || isSCMResourceNode(element) || isSCMStructuralDiffElement(element)); +} + +/** + * Returns an additional class for the twistie of an element. Files and symbols open when clicked, so they expand only + * through their twistie, and expandable ones keep it when the file icon theme hides arrows, like file nests in the Explorer. + */ +export function getSCMTreeTwistieCssClass(element: unknown, dataSource: SCMTreeDataSource): string | undefined { + if (isSCMActionButton(element) || isSCMInput(element)) { + return 'force-no-twistie'; + } + if ((isSCMResource(element) || isSCMStructuralDiffElement(element)) && dataSource.hasChildren(element)) { + return 'force-twistie'; + } + return undefined; +} function processResourceFilterData(uri: URI, filterData: FuzzyScore | LabelFuzzyScore | undefined): [IMatch[] | undefined, IMatch[] | undefined] { if (!filterData) { @@ -692,6 +713,8 @@ class ListDelegate implements IListVirtualDelegate { return ActionButtonRenderer.TEMPLATE_ID; } else if (isSCMResourceGroup(element)) { return ResourceGroupRenderer.TEMPLATE_ID; + } else if (isSCMStructuralDiffElement(element)) { + return SCMStructuralDiffRenderer.TEMPLATE_ID; } else if (isSCMResource(element) || isSCMResourceNode(element)) { return ResourceRenderer.TEMPLATE_ID; } else { @@ -754,6 +777,12 @@ export class SCMTreeSorter implements ITreeSorter { return isSCMResourceGroup(other) ? 0 : -1; } + if (isSCMStructuralDiffElement(one) || isSCMStructuralDiffElement(other)) { + return isSCMStructuralDiffElement(one) && isSCMStructuralDiffElement(other) + ? one.order - other.order + : isSCMStructuralDiffElement(one) ? 1 : -1; + } + // Resource (List) if (this.viewMode() === ViewMode.List) { // FileName @@ -804,7 +833,9 @@ export class SCMTreeKeyboardNavigationLabelProvider implements ICompressibleKeyb ) { } getKeyboardNavigationLabel(element: TreeElement): { toString(): string } | { toString(): string }[] | undefined { - if (ResourceTree.isResourceNode(element)) { + if (isSCMStructuralDiffElement(element)) { + return getSCMStructuralDiffLabel(element); + } else if (ResourceTree.isResourceNode(element)) { return element.name; } else if (isSCMRepository(element) || isSCMInput(element) || isSCMActionButton(element)) { return undefined; @@ -834,7 +865,9 @@ export class SCMTreeKeyboardNavigationLabelProvider implements ICompressibleKeyb } function getSCMResourceId(element: TreeElement): string { - if (isSCMRepository(element)) { + if (isSCMStructuralDiffElement(element)) { + return element.id; + } else if (isSCMRepository(element)) { const provider = element.provider; return `repo:${provider.id}`; } else if (isSCMInput(element)) { @@ -879,7 +912,9 @@ export class SCMAccessibilityProvider implements IListAccessibilityProvider('scmViewMode', ViewMode.List), SCMViewSortKey: new RawContextKey('scmViewSortKey', ViewSortKey.Path), + SCMViewShowStructuralDiff: new RawContextKey('scmViewShowStructuralDiff', false), + SCMViewHasStructuralDiffProvider: new RawContextKey('scmViewHasStructuralDiffProvider', false), SCMViewAreAllRepositoriesCollapsed: new RawContextKey('scmViewAreAllRepositoriesCollapsed', false), SCMViewIsAnyRepositoryCollapsible: new RawContextKey('scmViewIsAnyRepositoryCollapsible', false), SCMProvider: new RawContextKey('scmProvider', undefined), @@ -946,7 +983,8 @@ export const ContextKeys = { RepositoryCount: new RawContextKey('scmRepositoryCount', 0), RepositoryVisibilityCount: new RawContextKey('scmRepositoryVisibleCount', 0), RepositoryVisibility(repository: ISCMRepository) { - return new RawContextKey(`scmRepositoryVisible:${repository.provider.id}`, false); + // Omit global metadata and let reset remove the repository-specific key. + return new RawContextKey(`scmRepositoryVisible:${repository.provider.id}`, undefined, true); } }; @@ -1285,6 +1323,28 @@ registerAction2(SetSortByNameAction); registerAction2(SetSortByPathAction); registerAction2(SetSortByStatusAction); +class ToggleShowStructuralDiffAction extends ViewAction { + constructor() { + super({ + id: 'workbench.scm.action.toggleShowStructuralDiff', + title: localize('showStructuralDiff', "Show Structural Diff"), + viewId: VIEW_PANE_ID, + f1: false, + toggled: ContextKeys.SCMViewShowStructuralDiff, + menu: { + id: Menus.ViewSort, group: '3_structuralDiff', order: 1, + when: ContextKeyExpr.and(ContextKeyExpr.equals('config.scm.structuralDiff.enabled', true), ContextKeys.SCMViewHasStructuralDiffProvider), + }, + }); + } + + runInView(_: ServicesAccessor, view: SCMViewPane): void { + view.showStructuralDiff = !view.showStructuralDiff; + } +} + +registerAction2(ToggleShowStructuralDiffAction); + class CollapseAllRepositoriesAction extends ViewAction { constructor() { @@ -1415,6 +1475,31 @@ export class SCMViewPane extends ViewPane { private readonly _onDidChangeViewSortKey = this._register(new Emitter()); readonly onDidChangeViewSortKey = this._onDidChangeViewSortKey.event; + /** The user's choice from the View & Sort menu. Structural diffs are only shown while `scm.structuralDiff.enabled` is also set. */ + get showStructuralDiff(): boolean { return this._showStructuralDiff; } + set showStructuralDiff(show: boolean) { + if (this._showStructuralDiff === show) { + return; + } + this._showStructuralDiff = show; + this.storageService.store('scm.showStructuralDiff', show, StorageScope.WORKSPACE, StorageTarget.USER); + this.updateStructuralDiffEnablement(); + } + + private updateStructuralDiffEnablement(): void { + const enabled = this._showStructuralDiff && this.configurationService.getValue('scm.structuralDiff.enabled') === true; + if (this.structuralDiff.enabled === enabled) { + return; + } + if (!enabled && this.tree) { + const toResource = (element: TreeElement) => isSCMStructuralDiffElement(element) ? element.resource : element; + this.tree.setFocus([...new Set(this.tree.getFocus().map(toResource))]); + this.tree.setSelection([...new Set(this.tree.getSelection().map(toResource))]); + } + this.showStructuralDiffContextKey.set(enabled); + this.structuralDiff.setEnabled(enabled); + } + private readonly items = new DisposableMap(); private readonly visibilityDisposables = new DisposableStore(); @@ -1424,6 +1509,8 @@ export class SCMViewPane extends ViewPane { private viewModeContextKey: IContextKey; private viewSortKeyContextKey: IContextKey; + private _showStructuralDiff: boolean; + private showStructuralDiffContextKey: IContextKey; private areAllRepositoriesCollapsedContextKey: IContextKey; private isAnyRepositoryCollapsibleContextKey: IContextKey; @@ -1432,6 +1519,7 @@ export class SCMViewPane extends ViewPane { private scmProviderHasRootUriContextKey: IContextKey; private readonly disposables = new DisposableStore(); + private readonly structuralDiff: SCMStructuralDiffModel; constructor( options: IViewPaneOptions, @@ -1454,6 +1542,9 @@ export class SCMViewPane extends ViewPane { ) { super({ ...options, titleMenuId: MenuId.SCMTitle }, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, hoverService); + this.structuralDiff = this.disposables.add(instantiationService.createInstance(SCMStructuralDiffModel)); + this._showStructuralDiff = this.storageService.getBoolean('scm.showStructuralDiff', StorageScope.WORKSPACE, false); + // View mode and sort key this._viewMode = this.getViewMode(); this._viewSortKey = this.getViewSortKey(); @@ -1463,6 +1554,10 @@ export class SCMViewPane extends ViewPane { this.viewModeContextKey.set(this._viewMode); this.viewSortKeyContextKey = ContextKeys.SCMViewSortKey.bindTo(contextKeyService); this.viewSortKeyContextKey.set(this.viewSortKey); + this.showStructuralDiffContextKey = ContextKeys.SCMViewShowStructuralDiff.bindTo(contextKeyService); + this.updateStructuralDiffEnablement(); + Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('scm.structuralDiff.enabled'), this.disposables)(() => this.updateStructuralDiffEnablement(), this, this.disposables); + this.disposables.add(bindContextKey(ContextKeys.SCMViewHasStructuralDiffProvider, contextKeyService, reader => this.structuralDiff.hasProvider.read(reader))); this.areAllRepositoriesCollapsedContextKey = ContextKeys.SCMViewAreAllRepositoriesCollapsed.bindTo(contextKeyService); this.isAnyRepositoryCollapsibleContextKey = ContextKeys.SCMViewIsAnyRepositoryCollapsible.bindTo(contextKeyService); this.scmProviderContextKey = ContextKeys.SCMProvider.bindTo(contextKeyService); @@ -1480,6 +1575,9 @@ export class SCMViewPane extends ViewPane { case 'scm.viewSortKey': this.viewSortKey = this.getViewSortKey(); break; + case 'scm.showStructuralDiff': + this.showStructuralDiff = this.storageService.getBoolean('scm.showStructuralDiff', StorageScope.WORKSPACE, false); + break; } }, this, this.disposables); @@ -1537,6 +1635,7 @@ export class SCMViewPane extends ViewPane { this.createTree(this.treeContainer, viewState); this.onDidChangeBodyVisibility(async visible => { + this.structuralDiff.setVisible(visible); if (visible) { this.treeOperationSequencer.queue(async () => { await this.tree.setInput(this.scmViewService, viewState); @@ -1607,7 +1706,7 @@ export class SCMViewPane extends ViewPane { resourceActionRunner.onWillRun(() => this.tree.domFocus(), this, this.disposables); this.disposables.add(resourceActionRunner); - const treeDataSource = this.instantiationService.createInstance(SCMTreeDataSource, () => this.viewMode); + const treeDataSource = this.instantiationService.createInstance(SCMTreeDataSource, () => this.viewMode, this.structuralDiff); this.disposables.add(treeDataSource); const compressionEnabled = observableConfigValue('scm.compactFolders', true, this.configurationService); @@ -1623,7 +1722,8 @@ export class SCMViewPane extends ViewPane { this.actionButtonRenderer, this.instantiationService.createInstance(RepositoryRenderer, MenuId.SCMTitle, getActionViewItemProvider(this.instantiationService)), this.instantiationService.createInstance(ResourceGroupRenderer, getActionViewItemProvider(this.instantiationService), resourceActionRunner), - this.disposables.add(this.instantiationService.createInstance(ResourceRenderer, () => this.viewMode, this.listLabels, getActionViewItemProvider(this.instantiationService), resourceActionRunner)) + this.disposables.add(this.instantiationService.createInstance(ResourceRenderer, () => this.viewMode, this.listLabels, getActionViewItemProvider(this.instantiationService), resourceActionRunner)), + this.instantiationService.createInstance(SCMStructuralDiffRenderer), ], treeDataSource, { @@ -1637,23 +1737,23 @@ export class SCMViewPane extends ViewPane { keyboardNavigationLabelProvider: this.instantiationService.createInstance(SCMTreeKeyboardNavigationLabelProvider, () => this.viewMode), overrideStyles: this.getLocationBasedColors().listOverrideStyles, compressionEnabled: compressionEnabled.get(), - collapseByDefault: (e: unknown) => { - // Repository, Resource Group, Resource Folder (Tree) are not collapsed by default - return !(isSCMRepository(e) || isSCMResourceGroup(e) || isSCMResourceNode(e)); - }, + collapseByDefault: isSCMTreeElementCollapsedByDefault, accessibilityProvider: this.instantiationService.createInstance(SCMAccessibilityProvider), - twistieAdditionalCssClass: (e: unknown) => { - if (isSCMActionButton(e) || isSCMInput(e)) { - return 'force-no-twistie'; - } - - return undefined; - }, + expandOnlyOnTwistieClick: element => isSCMResource(element) || isSCMStructuralDiffElement(element) + || this.configurationService.getValue('workbench.tree.expandMode') === 'doubleClick', + twistieAdditionalCssClass: (element: unknown) => getSCMTreeTwistieCssClass(element, treeDataSource), }) as WorkbenchCompressibleAsyncDataTree; this.disposables.add(this.tree); this.tree.onDidOpen(this.open, this, this.disposables); + this.structuralDiff.onDidChange(resource => this.updateStructuralChildren(resource), this, this.disposables); + this.tree.onDidChangeCollapseState(e => { + const element = e.node.element?.element; + if (e.node.collapsed && isSCMResource(element)) { + this.structuralDiff.release(element); + } + }, this, this.disposables); this.tree.onContextMenu(this.onListContextMenu, this, this.disposables); this.tree.onDidScroll(this.inputRenderer.clearValidation, this.inputRenderer, this.disposables); Event.filter(this.tree.onDidChangeCollapseState, e => isSCMRepository(e.node.element?.element), this.disposables)(this.updateRepositoryCollapseAllContextKeys, this, this.disposables); @@ -1705,6 +1805,18 @@ export class SCMViewPane extends ViewPane { this.scmViewService.focus(repository); } return; + } else if (isSCMStructuralDiffElement(e.element)) { + const element = e.element; + if (element.type === 'structuralDiffStatus' || !this.structuralDiff.isCurrent(element)) { + return; + } + const resource = element.resource; + await openSCMStructuralDiff(element, e.editorOptions, this.editorService, () => this.structuralDiff.isCurrent(element), e.sideBySide); + const repository = Iterable.find(this.scmService.repositories, repository => repository.provider === resource.resourceGroup.provider); + if (repository) { + this.scmViewService.focus(repository); + } + return; } else if (isSCMResource(e.element)) { if (e.element.command?.id === API_OPEN_EDITOR_COMMAND_ID || e.element.command?.id === API_OPEN_DIFF_EDITOR_COMMAND_ID) { if (isPointerEvent(e.browserEvent) && e.browserEvent.button === 1) { @@ -1763,8 +1875,11 @@ export class SCMViewPane extends ViewPane { } // Do not set focus/selection when the resource is already focused and selected - if (this.tree.getFocus().some(e => isSCMResource(e) && this.uriIdentityService.extUri.isEqual(e.sourceUri, uri)) && - this.tree.getSelection().some(e => isSCMResource(e) && this.uriIdentityService.extUri.isEqual(e.sourceUri, uri))) { + const representsResource = (element: TreeElement) => { + const resource = isSCMResource(element) ? element : isSCMStructuralDiffElement(element) ? element.resource : undefined; + return resource !== undefined && this.uriIdentityService.extUri.isEqual(resource.sourceUri, uri); + }; + if (this.tree.getFocus().some(representsResource) && this.tree.getSelection().some(representsResource)) { return; } @@ -1817,6 +1932,7 @@ export class SCMViewPane extends ViewPane { const onDidChangeResourceGroups = () => { for (const [resourceGroup] of resourceGroupDisposables) { if (!repository.provider.groups.includes(resourceGroup)) { + this.structuralDiff.invalidateGroup(resourceGroup); resourceGroupDisposables.deleteAndDispose(resourceGroup); } } @@ -1826,7 +1942,10 @@ export class SCMViewPane extends ViewPane { const disposableStore = new DisposableStore(); disposableStore.add(resourceGroup.onDidChange(() => this.updateChildren(repository))); - disposableStore.add(resourceGroup.onDidChangeResources(() => this.updateChildren(repository))); + disposableStore.add(resourceGroup.onDidChangeResources(() => { + this.structuralDiff.releaseRemovedResources(resourceGroup); + this.updateChildren(repository); + })); resourceGroupDisposables.set(resourceGroup, disposableStore); } } @@ -1840,6 +1959,7 @@ export class SCMViewPane extends ViewPane { // Removed repositories for (const repository of removed) { + this.structuralDiff.invalidateProvider(repository.provider); this.items.deleteAndDispose(repository); } @@ -1860,6 +1980,9 @@ export class SCMViewPane extends ViewPane { } const element = e.element; + if (isSCMStructuralDiffElement(element)) { + return; + } let context: unknown = element; let actions: IAction[] = []; @@ -1973,8 +2096,30 @@ export class SCMViewPane extends ViewPane { private storeTreeViewState() { if (this.tree) { - this.storageService.store('scm.viewState2', JSON.stringify(this.tree.getViewState()), StorageScope.WORKSPACE, StorageTarget.MACHINE); + const state = this.tree.getViewState(); + const isPersistent = (id: string) => !id.startsWith(SCM_STRUCTURAL_DIFF_ID_PREFIX); + this.storageService.store('scm.viewState2', JSON.stringify({ + ...state, + focus: state.focus?.filter(isPersistent), + selection: state.selection?.filter(isPersistent), + expanded: state.expanded?.filter(isPersistent), + }), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } + } + + private updateStructuralChildren(resource: ISCMResource | undefined): void { + if (!this.isBodyVisible()) { + return; + } + if (!resource) { + this.updateChildren(); + return; } + this.treeOperationSequencer.queue(async () => { + if (this.tree.hasNode(resource)) { + await this.tree.updateChildren(resource, true, true); + } + }).catch(onUnexpectedError); } private updateChildren(element?: ISCMRepository) { @@ -2186,9 +2331,10 @@ export class SCMViewPane extends ViewPane { } } -class SCMTreeDataSource extends Disposable implements IAsyncDataSource { +export class SCMTreeDataSource extends Disposable implements IAsyncDataSource { constructor( private readonly viewMode: () => ViewMode, + private readonly structuralDiff: SCMStructuralDiffModel, @IConfigurationService private readonly configurationService: IConfigurationService, @ISCMViewService private readonly scmViewService: ISCMViewService ) { @@ -2252,13 +2398,19 @@ class SCMTreeDataSource extends Disposable implements IAsyncDataSource 0; } else if (ResourceTree.isResourceNode(inputOrElement)) { return inputOrElement.childrenCount > 0; } else { diff --git a/src/vs/workbench/contrib/scm/browser/scmViewService.ts b/src/vs/workbench/contrib/scm/browser/scmViewService.ts index d7b3583901c7..9d347b6d8b05 100644 --- a/src/vs/workbench/contrib/scm/browser/scmViewService.ts +++ b/src/vs/workbench/contrib/scm/browser/scmViewService.ts @@ -273,10 +273,17 @@ export class SCMViewService implements ISCMViewService { equalsFn: () => false }, this.onDidFocusRepository, () => this.focusedRepository); + // Editors can be restored before their repository is opened (ex: window reload), so we + // also have to re-evaluate the active editor when the repository containing it is added + const onDidAddActiveEditorRepository = Event.filter(this.scmService.onDidAddRepository, repository => { + const activeResource = EditorResourceAccessor.getOriginalUri(this.editorService.activeEditor); + return !!activeResource && this.scmService.getRepository(activeResource) === repository; + }); + this._activeEditorObs = observableFromEventOpts({ owner: this, equalsFn: () => false - }, this.editorService.onDidActiveEditorChange, () => this.editorService.activeEditor); + }, Event.any(this.editorService.onDidActiveEditorChange, onDidAddActiveEditorRepository), () => this.editorService.activeEditor); this._activeEditorRepositoryObs = derivedObservableWithCache(this, (reader, lastValue) => { diff --git a/src/vs/workbench/contrib/scm/common/scmStructuralDiff.ts b/src/vs/workbench/contrib/scm/common/scmStructuralDiff.ts new file mode 100644 index 000000000000..7253ba574a9f --- /dev/null +++ b/src/vs/workbench/contrib/scm/common/scmStructuralDiff.ts @@ -0,0 +1,522 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { DeferredPromise, Limiter, Promises, RunOnceScheduler, raceCancellation, raceTimeout } from '../../../../base/common/async.js'; +import { CancellationError, isCancellationError } from '../../../../base/common/errors.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable, DisposableMap, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { IObservable, observableFromEvent } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IPosition } from '../../../../editor/common/core/position.js'; +import { Range } from '../../../../editor/common/core/range.js'; +import { PositionOrRange, RangeMapping, SingleRangeMapping } from '../../../../editor/common/core/ranges/rangeMapping.js'; +import { StructuralDiffClassification, StructuralDiffNode, StructuralDiffResult, SymbolKind, symbolKindNames } from '../../../../editor/common/languages.js'; +import { ILanguageService } from '../../../../editor/common/languages/language.js'; +import { ITextModel } from '../../../../editor/common/model.js'; +import { IEditorWorkerService } from '../../../../editor/common/services/editorWorker.js'; +import { ILanguageFeaturesService } from '../../../../editor/common/services/languageFeatures.js'; +import { IModelService } from '../../../../editor/common/services/model.js'; +import { ITextModelService } from '../../../../editor/common/services/resolverService.js'; +import { ITextResourceConfigurationService } from '../../../../editor/common/services/textResourceConfiguration.js'; +import { StructuralDiffs } from '../../../../editor/contrib/structuralDiff/common/structuralDiff.js'; +import { localize } from '../../../../nls.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { ISCMProvider, ISCMResource, ISCMResourceGroup } from './scm.js'; + +export const SCM_STRUCTURAL_DIFF_ID_PREFIX = 'scmStructuralDiff:'; + +/** Structural changes load when a file is expanded, for example many at once when a view with expanded files is restored. Only a few are analyzed at a time. */ +const MAX_CONCURRENT_LOADS = 3; + +/** A load that takes longer is abandoned, so one hung provider cannot occupy a load slot forever. */ +const MAX_LOAD_TIME_MS = 30_000; + +interface SCMStructuralDiffElementBase { + /** + * Identifies the item or status that the element shows. It stays the same when the structural + * changes of a file are reloaded, so the tree keeps focus, selection and collapse state. + */ + readonly id: string; + /** Identifies the result that contains the element, see {@link SCMStructuralDiffModel.isCurrent}. */ + readonly generation: number; + readonly resource: ISCMResource; + readonly order: number; +} + +export interface SCMStructuralDiffNode extends SCMStructuralDiffElementBase { + readonly type: 'structuralDiff'; + readonly node: StructuralDiffNode; + readonly parent: ISCMResource | SCMStructuralDiffNode; + readonly children: readonly SCMStructuralDiffNode[]; + /** + * For an item that only exists in the original document, the position in the modified document where it was + * deleted. An inline diff only shows the modified document, so it shows a deleted item there. + */ + readonly deletedAt?: IPosition; +} + +export interface SCMStructuralDiffStatus extends SCMStructuralDiffElementBase { + readonly type: 'structuralDiffStatus'; + readonly status: 'incomplete' | 'error' | 'timedOut'; + readonly parent: ISCMResource; +} + +export type SCMStructuralDiffElement = SCMStructuralDiffNode | SCMStructuralDiffStatus; + +/** + * A step from a parent to a structural item: its kind and name, whether it was added, where it starts in the original + * document, and its position among siblings that have all of these in common. + */ +type ItemKey = readonly [kind: SymbolKind, name: string, added: boolean, line: number, column: number, ordinal: number]; + +function createElementId(resource: ISCMResource, path: readonly (ItemKey | string)[]): string { + const group = resource.resourceGroup; + return SCM_STRUCTURAL_DIFF_ID_PREFIX + JSON.stringify([group.provider.id, group.id, resource.sourceUri.toString(), ...path]); +} + +export function isSCMStructuralDiffElement(element: unknown): element is SCMStructuralDiffElement { + return typeof element === 'object' && element !== null && 'type' in element + && (element.type === 'structuralDiff' || element.type === 'structuralDiffStatus'); +} + +export function getSCMStructuralDiffLabel(element: SCMStructuralDiffElement): string { + if (element.type === 'structuralDiffStatus') { + return element.status === 'incomplete' + ? localize('structuralDiff.incomplete', "Partial structural changes") + : element.status === 'timedOut' + ? localize('structuralDiff.timedOut', "Structural changes took too long to load") + : localize('structuralDiff.error', "Unable to load structural changes"); + } + return (element.node.modifiedItem ?? element.node.originalItem)!.name; +} + +export function getSCMStructuralDiffChange(element: SCMStructuralDiffElement): { readonly type: 'added' | 'deleted' | 'modified' | 'renamed'; readonly label: string } | undefined { + if (element.type === 'structuralDiffStatus') { + return undefined; + } + if (!element.node.originalItem) { + return { type: 'added', label: localize('structuralDiff.added', "Added") }; + } + if (!element.node.modifiedItem) { + return { type: 'deleted', label: localize('structuralDiff.deleted', "Deleted") }; + } + if (element.node.originalItem.name !== element.node.modifiedItem.name) { + return { + type: 'renamed', + label: localize('structuralDiff.renamed', "Renamed from {0} to {1}", element.node.originalItem.name, element.node.modifiedItem.name), + }; + } + if (element.node.originalChanges.length > 0 || element.node.modifiedChanges.length > 0) { + return { type: 'modified', label: localize('structuralDiff.changed', "Changed") }; + } + return undefined; +} + +export function getSCMStructuralDiffChangeAnnotation(element: SCMStructuralDiffElement): { readonly label: string; readonly description: string } | undefined { + if (element.type === 'structuralDiffStatus' || !element.node.originalItem || !element.node.modifiedItem + || element.node.originalItem.name !== element.node.modifiedItem.name) { + return undefined; + } + const changes = [...element.node.originalChanges, ...element.node.modifiedChanges]; + const declarationChanged = changes.some(change => change.classification === StructuralDiffClassification.Header); + const implementationChanged = changes.some(change => change.classification === StructuralDiffClassification.Implementation); + if (declarationChanged && implementationChanged) { + return { + label: localize({ key: 'structuralDiff.declImplAnnotation', comment: ['Short annotation: declaration and implementation both changed.'] }, "decl+impl"), + description: localize('structuralDiff.declImplChanged', "Declaration and implementation changed"), + }; + } + if (declarationChanged) { + return { + label: localize({ key: 'structuralDiff.declAnnotation', comment: ['Short annotation: decl abbreviates declaration.'] }, "decl"), + description: localize('structuralDiff.declChanged', "Declaration changed"), + }; + } + if (implementationChanged) { + return { + label: localize({ key: 'structuralDiff.implAnnotation', comment: ['Short annotation: impl abbreviates implementation.'] }, "impl"), + description: localize('structuralDiff.implChanged', "Implementation changed"), + }; + } + return undefined; +} + +export function getSCMStructuralDiffDescription(element: SCMStructuralDiffElement): string | undefined { + if (element.type === 'structuralDiffStatus') { + return undefined; + } + const details = (element.node.modifiedItem ?? element.node.originalItem)!.detail; + const status = getSCMStructuralDiffChangeAnnotation(element)?.description ?? getSCMStructuralDiffChange(element)?.label; + return [status, details].filter(value => !!value).join(', ') || undefined; +} + +export function getSCMStructuralDiffAriaLabel(element: SCMStructuralDiffElement): string { + if (element.type === 'structuralDiffStatus') { + return getSCMStructuralDiffLabel(element); + } + const item = (element.node.modifiedItem ?? element.node.originalItem)!; + const description = getSCMStructuralDiffDescription(element); + return description + ? localize('structuralDiff.ariaLabelWithDescription', "{0}, {1}, {2}", item.name, symbolKindNames[item.kind], description) + : localize('structuralDiff.ariaLabel', "{0}, {1}", item.name, symbolKindNames[item.kind]); +} + +class StructuralDiffEntry extends Disposable { + readonly cancellation = this._register(new CancellationTokenSource()); + readonly listeners = this._register(new DisposableStore()); + readonly references = this._register(new DisposableStore()); + private readonly disposal = new DeferredPromise(); + /** Settles when the entry is disposed, for example because its file was collapsed or the view was hidden. */ + readonly whenDisposed = this.disposal.p; + pending?: Promise; + children?: readonly SCMStructuralDiffElement[]; + disposed = false; + timedOut = false; + + constructor(readonly resource: ISCMResource, readonly generation: number) { + super(); + } + + override dispose(): void { + if (!this.disposed) { + this.disposed = true; + this.cancellation.cancel(); + this.disposal.complete(); + super.dispose(); + } + } +} + +/** + * Whether any structural diff provider is registered, regardless of the languages it supports. + * This decides whether the feature is offered at all. Whether a file can show structural + * changes is decided per resource by {@link SCMStructuralDiffModel.hasChildren}, so changes + * that span many languages need no special handling. + */ +export function hasSCMStructuralDiffProvider(languageFeaturesService: ILanguageFeaturesService): boolean { + return languageFeaturesService.structuralDiffProvider.allNoModel().length > 0; +} + +export class SCMStructuralDiffModel extends Disposable { + private _enabled = false; + get enabled(): boolean { return this._enabled; } + private visible = true; + + /** Whether any structural diff provider is registered, see {@link hasSCMStructuralDiffProvider}. */ + readonly hasProvider: IObservable; + + private readonly entries = this._register(new DisposableMap()); + private readonly loadLimiter = this._register(new Limiter(MAX_CONCURRENT_LOADS)); + private readonly _onDidChange = this._register(new Emitter()); + readonly onDidChange = this._onDidChange.event; + private generation = 0; + private readonly pendingChanges = new Set(); + private readonly changeScheduler = this._register(new RunOnceScheduler(() => { + const resources = [...this.pendingChanges]; + this.pendingChanges.clear(); + for (const resource of resources) { + this._onDidChange.fire(resource); + } + }, 150)); + + constructor( + @ITextModelService private readonly textModelService: ITextModelService, + @IModelService private readonly modelService: IModelService, + @ILanguageService private readonly languageService: ILanguageService, + @ILanguageFeaturesService private readonly languageFeaturesService: ILanguageFeaturesService, + @IEditorWorkerService private readonly editorWorkerService: IEditorWorkerService, + @ITextResourceConfigurationService private readonly configurationService: ITextResourceConfigurationService, + @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, + @ILogService private readonly logService: ILogService, + ) { + super(); + this.hasProvider = observableFromEvent(this, this.languageFeaturesService.structuralDiffProvider.onDidChange, () => hasSCMStructuralDiffProvider(this.languageFeaturesService)); + this._register(this.languageFeaturesService.structuralDiffProvider.onDidChange(() => { + if (!this._enabled) { + return; + } + this.clear(); + this._onDidChange.fire(undefined); + })); + this._register(this.modelService.onModelLanguageChanged(({ model }) => { + if (!this.isActive) { + return; + } + for (const [resource] of this.entries) { + if (this.uriIdentityService.extUri.isEqual(resource.multiDiffEditorModifiedUri, model.uri) + || this.uriIdentityService.extUri.isEqual(resource.multiDiffEditorOriginalUri, model.uri)) { + this.entries.deleteAndDispose(resource); + } + } + this._onDidChange.fire(undefined); + })); + this._register(this.languageService.onDidChange(() => { + if (this.isActive) { + this._onDidChange.fire(undefined); + } + })); + } + + setEnabled(enabled: boolean): void { + if (this._enabled === enabled) { + return; + } + this._enabled = enabled; + if (!enabled) { + this.clear(); + } + this._onDidChange.fire(undefined); + } + + /** + * Called when the view is shown or hidden. A hidden view keeps no results and analyzes no files, even when a refresh + * of its tree asks for the children of an expanded file, because refreshes can still run after the view was hidden. + * Files remain expandable, so the tree keeps them expanded and loads their children when it is shown again. + */ + setVisible(visible: boolean): void { + this.visible = visible; + if (!visible) { + this.clear(); + } + } + + hasChildren(resource: ISCMResource): boolean { + if (!this.enabled) { + return false; + } + const entry = this.entries.get(resource); + if (entry?.children !== undefined) { + return entry.children.length > 0; + } + return this.canProvide(resource); + } + + getChildren(resource: ISCMResource): Promise { + if (this._store.isDisposed || !this.visible || !this.canProvide(resource)) { + return Promise.resolve([]); + } + let entry = this.entries.get(resource); + if (entry === undefined) { + entry = new StructuralDiffEntry(resource, ++this.generation); + this.entries.set(resource, entry); + } + if (entry.children !== undefined) { + return Promise.resolve(entry.children); + } + // The tree makes refreshes of the group and the root wait for this request, so it settles as soon as the entry is + // disposed, even while the file still waits for a load slot. A timeout does not dispose the entry and shows its status. + entry.pending ??= Promise.race([this.loadLimiter.queue(() => this.loadWithinBudget(entry)), entry.whenDisposed.then(() => [])]); + return entry.pending; + } + + isCurrent(element: SCMStructuralDiffElement): boolean { + const entry = this.entries.get(element.resource); + return entry !== undefined && !entry.disposed && entry.generation === element.generation; + } + + release(resource: ISCMResource): void { + this.entries.deleteAndDispose(resource); + this._onDidChange.fire(resource); + } + + /** Releases the cached results of all resources in the group, for example because the group was removed. */ + invalidateGroup(group: ISCMResourceGroup): void { + for (const [resource] of this.entries) { + if (resource.resourceGroup === group) { + this.entries.deleteAndDispose(resource); + } + } + } + + /** + * Releases the cached results of resources that are no longer in the group, for example because + * their status changed. Results of the remaining resources are kept, because content changes + * already invalidate them. + */ + releaseRemovedResources(group: ISCMResourceGroup): void { + let resources: Set | undefined; + for (const [resource] of this.entries) { + if (resource.resourceGroup === group) { + resources ??= new Set(group.resources); + if (!resources.has(resource)) { + this.entries.deleteAndDispose(resource); + } + } + } + } + + invalidateProvider(provider: ISCMProvider): void { + for (const [resource] of this.entries) { + if (resource.resourceGroup.provider === provider) { + this.entries.deleteAndDispose(resource); + } + } + } + + private clear(): void { + this.changeScheduler.cancel(); + this.pendingChanges.clear(); + this.entries.clearAndDisposeAll(); + } + + /** Language changes cannot affect the tree unless structural children are enabled and a provider can supply them. */ + private get isActive(): boolean { + return this._enabled && hasSCMStructuralDiffProvider(this.languageFeaturesService); + } + + private canProvide(resource: ISCMResource): boolean { + if (!this.enabled) { + return false; + } + const modified = resource.multiDiffEditorModifiedUri; + if (!resource.multiDiffEditorOriginalUri || !modified) { + return false; + } + const model = this.modelService.getModel(modified); + const registry = this.languageFeaturesService.structuralDiffProvider; + return model ? registry.has(model) + : registry.hasForResource(modified, this.languageService.guessLanguageIdByFilepathOrFirstLine(modified) ?? 'plaintext'); + } + + private invalidate(entry: StructuralDiffEntry): void { + if (!entry.disposed && this.entries.get(entry.resource) === entry) { + this.entries.deleteAndDispose(entry.resource); + this.pendingChanges.add(entry.resource); + this.changeScheduler.schedule(); + } + } + + private checkCancellation(entry: StructuralDiffEntry): void { + if (entry.disposed || entry.cancellation.token.isCancellationRequested) { + throw new CancellationError(); + } + } + + /** Keeps the document loaded while the entry exists and invalidates the entry when the document changes, also after a failure. */ + private async resolveModel(entry: StructuralDiffEntry, resource: URI): Promise { + this.checkCancellation(entry); + const reference = await this.textModelService.createModelReference(resource); + if (entry.disposed || entry.cancellation.token.isCancellationRequested) { + reference.dispose(); + throw new CancellationError(); + } + entry.references.add(reference); + const model = reference.object.textEditorModel; + entry.listeners.add(model.onDidChangeContent(() => this.invalidate(entry))); + entry.listeners.add(model.onWillDispose(() => this.invalidate(entry))); + return model; + } + + /** + * Loads within the time budget, so a load that never completes cannot occupy one of the limited load slots forever. + * Cancelling an entry does not interrupt loading its documents, so a cancelled load stops waiting for them and frees + * its slot right away. Documents that are loaded later are released when they arrive. + */ + private async loadWithinBudget(entry: StructuralDiffEntry): Promise { + const children = await raceTimeout(raceCancellation(this.load(entry), entry.cancellation.token, []), MAX_LOAD_TIME_MS, () => { + entry.timedOut = true; + entry.cancellation.cancel(); + }); + return children && !entry.timedOut ? children : this.fail(entry, 'timedOut'); + } + + private async load(entry: StructuralDiffEntry): Promise { + const resource = entry.resource; + try { + // Both documents are loaded even when one of them cannot be, so that every document that can be loaded is watched. + const [original, modified] = await Promises.settled([ + this.resolveModel(entry, resource.multiDiffEditorOriginalUri!), + this.resolveModel(entry, resource.multiDiffEditorModifiedUri!), + ]); + const result = await this.computeStructuralDiff(entry, original, modified); + this.checkCancellation(entry); + const toModified = new RangeMapping((result?.context.changes ?? []).map(change => new SingleRangeMapping(Range.lift(change.originalRange), Range.lift(change.modifiedRange)))); + const toOriginal = toModified.reverse(); + // A position in changed text maps to the start of the change in the other document. + const startOf = (mapped: PositionOrRange) => mapped.range?.getStartPosition() ?? mapped.position!; + const wrap = (nodes: readonly StructuralDiffNode[], parent: ISCMResource | SCMStructuralDiffNode, path: readonly ItemKey[]): SCMStructuralDiffNode[] => { + const ordinals = new Map(); + return nodes.map((node, order) => { + const item = (node.originalItem ?? node.modifiedItem)!; + // Edits of the working file do not change the original document, so a position in it identifies an item, + // even when siblings with the same name start or stop changing. An added item is located through the text changes. + const start = node.originalItem ? Range.getStartPosition(node.originalItem.range) : startOf(toOriginal.mapPosition(Range.getStartPosition(node.modifiedItem!.range))); + const identity = [item.kind, item.name, !node.originalItem, start.lineNumber, start.column] as const; + const key = JSON.stringify(identity); + const ordinal = ordinals.get(key) ?? 0; + ordinals.set(key, ordinal + 1); + const nodePath: ItemKey[] = [...path, [...identity, ordinal]]; + const children: SCMStructuralDiffNode[] = []; + const element: SCMStructuralDiffNode = { + type: 'structuralDiff', id: createElementId(resource, nodePath), + generation: entry.generation, resource, node, parent, order, children, + ...(node.modifiedItem ? {} : { deletedAt: startOf(toModified.mapPosition(start)) }), + }; + children.push(...wrap(node.children, element, nodePath)); + return element; + }); + }; + const children: SCMStructuralDiffElement[] = result ? wrap(result.root.children, resource, []) : []; + if (result?.isIncomplete) { + children.push(this.createStatus(entry, 'incomplete', children.length)); + } + entry.children = children; + if (children.length === 0) { + this._onDidChange.fire(resource); + } + return children; + } catch (error) { + // A load that timed out already shows its status, and the view disposes an entry when it cancels loading it. Any + // other error, even a cancellation error, is a failure. + if (entry.timedOut || entry.disposed) { + return []; + } + if (error instanceof StructuralDiffs.TimeoutError) { + this.logService.info('[SCM] Structural changes took too long to compute', resource.sourceUri, error.message); + return this.fail(entry, 'timedOut'); + } + this.logService.error('[SCM] Error loading structural changes', resource.sourceUri, error); + return this.fail(entry, 'error'); + } + } + + /** + * Computes the structural diff of the documents. A provider can reject with a cancellation error of its own, for example + * when its language server restarts. Like a provider that fails, it then supplies no result, and the documents remain + * watched, so an edit analyzes the file again. + */ + private async computeStructuralDiff(entry: StructuralDiffEntry, original: ITextModel, modified: ITextModel): Promise { + try { + return await StructuralDiffs.compute(this.editorWorkerService, this.configurationService, this.languageFeaturesService.structuralDiffProvider, original, modified, entry.cancellation.token); + } catch (error) { + if (isCancellationError(error) && !entry.disposed && !entry.cancellation.token.isCancellationRequested) { + return undefined; + } + throw error; + } + } + + /** + * Shows a status row instead of structural changes until the entry is invalidated. Like a result, a failure keeps the + * documents that could be loaded, so editing one of them analyzes the file again. + */ + private fail(entry: StructuralDiffEntry, status: 'error' | 'timedOut'): readonly SCMStructuralDiffElement[] { + if (entry.disposed) { + return []; + } + const children = [this.createStatus(entry, status, 0)]; + entry.children = children; + return children; + } + + private createStatus(entry: StructuralDiffEntry, status: SCMStructuralDiffStatus['status'], order: number): SCMStructuralDiffStatus { + return { + type: 'structuralDiffStatus', id: createElementId(entry.resource, ['status', status]), + generation: entry.generation, resource: entry.resource, parent: entry.resource, order, status, + }; + } +} diff --git a/src/vs/workbench/contrib/scm/test/browser/scmRepositoryVisibility.test.ts b/src/vs/workbench/contrib/scm/test/browser/scmRepositoryVisibility.test.ts new file mode 100644 index 000000000000..4541be167d67 --- /dev/null +++ b/src/vs/workbench/contrib/scm/test/browser/scmRepositoryVisibility.test.ts @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { RawContextKey } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeys } from '../../browser/scmViewPane.js'; +import { ISCMProvider, ISCMRepository } from '../../common/scm.js'; + +suite('SCM repository visibility context keys', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function repository(providerId: string): ISCMRepository { + const provider = new class extends mock() { + override readonly id = providerId; + }(); + return new class extends mock() { + override readonly provider = provider; + }(); + } + + test('does not register metadata for per-repository context keys', () => { + const key = ContextKeys.RepositoryVisibility(repository('visibility-metadata-test')); + + assert.strictEqual([...RawContextKey.all()].some(info => info.key === key.key), false); + }); + + test('removes a repository visibility key when its owner resets it', () => { + const service = disposables.add(new ContextKeyService(new TestConfigurationService())); + const context = service.getContextValuesContainer(service.contextId); + const rawKey = ContextKeys.RepositoryVisibility(repository('visibility-reset-test')); + const key = rawKey.bindTo(service); + key.set(true); + assert.strictEqual(Object.hasOwn(context.value, rawKey.key), true); + + key.reset(); + + assert.strictEqual(Object.hasOwn(context.value, rawKey.key), false); + }); + + test('preserves visible and hidden expressions while a repository is active', () => { + const service = disposables.add(new ContextKeyService(new TestConfigurationService())); + const rawKey = ContextKeys.RepositoryVisibility(repository('visibility-expression-test')); + const key = rawKey.bindTo(service); + + key.set(false); + assert.strictEqual(service.contextMatchesRules(rawKey.isEqualTo(false)), true); + assert.strictEqual(service.contextMatchesRules(rawKey.isEqualTo(true)), false); + key.set(true); + assert.strictEqual(service.contextMatchesRules(rawKey.isEqualTo(false)), false); + assert.strictEqual(service.contextMatchesRules(rawKey.isEqualTo(true)), true); + }); +}); diff --git a/src/vs/workbench/contrib/scm/test/browser/scmStructuralDiff.test.ts b/src/vs/workbench/contrib/scm/test/browser/scmStructuralDiff.test.ts new file mode 100644 index 000000000000..e369a8bcec6f --- /dev/null +++ b/src/vs/workbench/contrib/scm/test/browser/scmStructuralDiff.test.ts @@ -0,0 +1,770 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { ITreeNode } from '../../../../../base/browser/ui/tree/tree.js'; +import { AsyncDataTree } from '../../../../../base/browser/ui/tree/asyncDataTree.js'; +import { IDelayedHoverAtMouseOptions } from '../../../../../base/browser/ui/hover/hover.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { Event } from '../../../../../base/common/event.js'; +import { FuzzyScore } from '../../../../../base/common/filters.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { ResourceTree } from '../../../../../base/common/resourceTree.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ICodeEditor, IDiffEditor } from '../../../../../editor/browser/editorBrowser.js'; +import { IRange, Range } from '../../../../../editor/common/core/range.js'; +import { ISelection, Selection } from '../../../../../editor/common/core/selection.js'; +import { EditorType, ScrollType } from '../../../../../editor/common/editorCommon.js'; +import { StructuralDiffClassification, StructuralDiffProvider, SymbolKind } from '../../../../../editor/common/languages.js'; +import { ILanguageFeaturesService } from '../../../../../editor/common/services/languageFeatures.js'; +import { LanguageFeaturesService } from '../../../../../editor/common/services/languageFeaturesService.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { isICommandActionToggleInfo } from '../../../../../platform/action/common/action.js'; +import { MenuId, MenuRegistry, isIMenuItem } from '../../../../../platform/actions/common/actions.js'; +import { CommandsRegistry, 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 { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { IEditorOptions } from '../../../../../platform/editor/common/editor.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { NullHoverService } from '../../../../../platform/hover/test/browser/nullHoverService.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../../browser/labels.js'; +import { DEFAULT_EDITOR_ASSOCIATION, ITextDiffEditorPane, IUntypedEditorInput } from '../../../../common/editor.js'; +import { DecorationsService } from '../../../../services/decorations/browser/decorationsService.js'; +import { IDecorationsService } from '../../../../services/decorations/common/decorations.js'; +import { IEditorService, PreferredGroup, SIDE_GROUP } from '../../../../services/editor/common/editorService.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { SCMAccessibilityHelp } from '../../browser/scmAccessibilityHelp.js'; +import { ContextKeys, SCMAccessibilityProvider, SCMTreeDataSource, SCMTreeKeyboardNavigationLabelProvider, SCMTreeSorter, SCMViewPane, getSCMTreeTwistieCssClass, isSCMTreeElementCollapsedByDefault } from '../../browser/scmViewPane.js'; +import { SCMStructuralDiffRenderer, openSCMStructuralDiff } from '../../browser/scmStructuralDiffRenderer.js'; +import { ISCMProvider, ISCMResource, ISCMResourceGroup, ISCMViewService, ViewMode } from '../../common/scm.js'; +import { SCMStructuralDiffElement, SCMStructuralDiffModel, SCMStructuralDiffNode } from '../../common/scmStructuralDiff.js'; +import '../../../modernUI/browser/media/padding.css'; + +class TestCodeEditor extends mock() { + readonly selections: IRange[] = []; + readonly reveals: IRange[] = []; + focused = false; + override setSelection(selection: IRange | ISelection): void { this.selections.push(Range.isIRange(selection) ? selection : Selection.liftSelection(selection)); } + override revealRangeInCenterIfOutsideViewport(range: IRange, _scrollType?: ScrollType): void { this.reveals.push(range); } + override focus(): void { this.focused = true; } +} + +class TestStatusHoverService extends mock() { + readonly labels: string[] = []; + active = 0; + + override setupDelayedHoverAtMouse(_target: HTMLElement, options: IDelayedHoverAtMouseOptions | (() => IDelayedHoverAtMouseOptions)) { + const content = (typeof options === 'function' ? options() : options).content; + assert.ok(typeof content === 'string'); + this.labels.push(content); + this.active++; + return toDisposable(() => this.active--); + } +} + +suite('SCM structural diff tree', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let resource: ISCMResource; + let group: ISCMResourceGroup; + let parent: SCMStructuralDiffNode; + let child: SCMStructuralDiffNode; + + setup(() => { + const provider = new class extends mock() { + override readonly id = 'test'; + }; + const resources: ISCMResource[] = []; + group = new class extends mock() { + override readonly id = 'workingTree'; + override readonly provider = provider; + override readonly resources = resources; + override readonly resourceTree: ResourceTree = new ResourceTree(this, URI.file('/repo')); + }; + resource = new class extends mock() { + override readonly sourceUri = URI.file('/repo/folder/file.ts'); + override readonly resourceGroup = group; + override readonly multiDiffEditorOriginalUri = URI.parse('git:/repo/folder/file.ts'); + override readonly multiDiffEditorModifiedUri = this.sourceUri; + }; + resources.push(resource); + group.resourceTree.add(resource.sourceUri, resource); + const range = new Range(1, 1, 10, 1); + const children: SCMStructuralDiffNode[] = []; + parent = { + type: 'structuralDiff', id: 'class', generation: 1, resource, parent: resource, order: 0, children, + node: { + id: 'class', originalItem: { name: 'Calculator', kind: SymbolKind.Class, range }, modifiedItem: { name: 'Calculator', kind: SymbolKind.Class, range }, + originalChanges: [], modifiedChanges: [], children: [], + }, + }; + child = { + type: 'structuralDiff', id: 'method', generation: 1, resource, parent, order: 0, children: [], + node: { + id: 'method', + originalItem: { name: 'run', kind: SymbolKind.Method, range: new Range(2, 1, 4, 1), selectionRange: new Range(2, 2, 2, 5) }, + modifiedItem: { name: 'run', kind: SymbolKind.Method, range: new Range(3, 1, 5, 1), selectionRange: new Range(3, 2, 3, 5) }, + originalChanges: [], modifiedChanges: [], children: [], + }, + }; + children.push(child); + }); + + for (const mode of [ViewMode.List, ViewMode.Tree]) { + test(`exposes structural children and correct parents in ${mode} mode`, async () => { + const structuralDiff = new class extends mock() { + override get enabled(): boolean { return true; } + override hasChildren(candidate: ISCMResource): boolean { return candidate === resource; } + override async getChildren(): Promise { return [parent]; } + }; + const viewService = new class extends mock() { + override readonly visibleRepositories = []; + }; + const dataSource = store.add(new SCMTreeDataSource(() => mode, structuralDiff, new TestConfigurationService(), viewService)); + const top = [...await dataSource.getChildren(group)]; + const files = mode === ViewMode.Tree ? [...await dataSource.getChildren(top[0])] : top; + assert.deepStrictEqual({ + files, + expandable: [dataSource.hasChildren(resource), dataSource.hasChildren(parent), dataSource.hasChildren(child)], + children: [...await dataSource.getChildren(resource)], + nested: [...await dataSource.getChildren(parent)], + parents: [dataSource.getParent(parent), dataSource.getParent(child)], + }, { files: [resource], expandable: [true, true, false], children: [parent], nested: [child], parents: [resource, parent] }); + }); + + test(`hides structural children in ${mode} mode while disabled`, async () => { + let enabled = true; + const structuralDiff = new class extends mock() { + override get enabled(): boolean { return enabled; } + override hasChildren(): boolean { return enabled; } + override async getChildren(): Promise { return enabled ? [parent] : []; } + }; + const viewService = new class extends mock() { + override readonly visibleRepositories = []; + }; + const dataSource = store.add(new SCMTreeDataSource(() => mode, structuralDiff, new TestConfigurationService(), viewService)); + await dataSource.getChildren(resource); + enabled = false; + assert.deepStrictEqual({ + fileChildren: [...await dataSource.getChildren(resource)], + nestedChildren: [...await dataSource.getChildren(parent)], + expandable: [dataSource.hasChildren(resource), dataSource.hasChildren(parent)], + filesRemain: [...await dataSource.getChildren(group)].length, + }, { fileChildren: [], nestedChildren: [], expandable: [false, false], filesRemain: 1 }); + }); + + test(`expands all structural descendants when a file is expanded in ${mode} mode`, async () => { + const classChildren: SCMStructuralDiffNode[] = []; + const classNode = { ...parent, children: classChildren }; + const methodChildren: SCMStructuralDiffNode[] = []; + const methodNode = { ...child, parent: classNode, children: methodChildren }; + const leaf = { ...child, id: 'nested-function', parent: methodNode, children: [] }; + classChildren.push(methodNode); + methodChildren.push(leaf); + let requests = 0; + const structuralDiff = new class extends mock() { + override get enabled(): boolean { return true; } + override hasChildren(candidate: ISCMResource): boolean { return candidate === resource; } + override async getChildren(): Promise { + requests++; + return [classNode]; + } + }; + const viewService = new class extends mock() { + override readonly visibleRepositories = []; + }; + const dataSource = store.add(new SCMTreeDataSource(() => mode, structuralDiff, new TestConfigurationService(), viewService)); + type Element = Parameters[0]; + const tree = store.add(new AsyncDataTree('SCM structural expansion', $('.scm-view'), { + getHeight: () => 22, + getTemplateId: () => 'element', + }, [{ + templateId: 'element', + renderTemplate: container => container, + renderElement: () => { }, + disposeTemplate: () => { }, + }], { + hasChildren: element => dataSource.hasChildren(element), + getChildren: element => dataSource.getChildren(element), + }, { collapseByDefault: isSCMTreeElementCollapsedByDefault })); + await tree.setInput(group); + const before = { collapsed: tree.isCollapsed(resource), requests }; + await tree.expand(resource); + const expanded = [resource, classNode, methodNode].map(element => tree.isCollapsed(element)); + const leafLoaded = tree.hasNode(leaf); + tree.collapse(classNode); + assert.deepStrictEqual({ + before, expanded, leafLoaded, requests, canCollapseManually: tree.isCollapsed(classNode), + }, { + before: { collapsed: true, requests: 0 }, expanded: [false, false, false], + leafLoaded: true, requests: 1, canCollapseManually: true, + }); + }); + + test(`preserves provider order instead of applying file sorting in ${mode} mode`, () => { + const sorter = new SCMTreeSorter(() => mode, () => { throw new Error('Must not sort structural children as files'); }); + const first = { ...child, order: 0, node: { ...child.node, modifiedItem: { ...child.node.modifiedItem!, name: 'zeta' } } }; + const second = { ...child, id: 'second', order: 1, node: { ...child.node, modifiedItem: { ...child.node.modifiedItem!, name: 'alpha' } } }; + assert.strictEqual(sorter.compare(first, second), -1); + }); + } + + test('forces the twistie of expandable files and symbols, which expand only through it, so that file icon themes cannot hide it', async () => { + const other = new class extends mock() { + override readonly sourceUri = URI.file('/repo/folder/notes.md'); + override readonly resourceGroup = group; + }; + const files = new class extends mock() { + override readonly provider = group.provider; + override readonly resources = [resource, other]; + }; + const structuralDiff = new class extends mock() { + override get enabled(): boolean { return true; } + override hasChildren(candidate: ISCMResource): boolean { return candidate === resource; } + override async getChildren(): Promise { return [parent]; } + }; + const viewService = new class extends mock() { + override readonly visibleRepositories = []; + }; + const dataSource = store.add(new SCMTreeDataSource(() => ViewMode.List, structuralDiff, new TestConfigurationService(), viewService)); + const names = new Map([[resource, 'file.ts'], [parent, 'Calculator'], [child, 'run'], [other, 'notes.md']]); + const container = $('.scm-view'); + type Element = Parameters[0]; + const tree = store.add(new AsyncDataTree('SCM twisties', container, { + getHeight: () => 22, + getTemplateId: () => 'element', + }, [{ + templateId: 'element', + renderTemplate: (template: HTMLElement) => template, + renderElement: (node: ITreeNode, _index: number, template: HTMLElement) => { template.textContent = names.get(node.element) ?? ''; }, + disposeTemplate: () => { }, + }], { + hasChildren: element => dataSource.hasChildren(element), + getChildren: element => dataSource.getChildren(element), + }, { collapseByDefault: isSCMTreeElementCollapsedByDefault, twistieAdditionalCssClass: element => getSCMTreeTwistieCssClass(element, dataSource) })); + tree.layout(200); + await tree.setInput(files); + await tree.expand(resource); + const rows = [...container.querySelectorAll('.monaco-list-row')]; + assert.deepStrictEqual(Object.fromEntries(rows.map(row => [row.textContent, row.querySelector('.monaco-tl-twistie')?.classList.contains('force-twistie')])), { + 'file.ts': true, Calculator: true, run: false, 'notes.md': false, + }); + }); + + test('adds Show Structural Diff as a checkable action in a separate View & Sort group while enabled and a provider is registered', () => { + const item = MenuRegistry.getMenuItems(MenuId.for('SCMViewSort')) + .find(item => isIMenuItem(item) && item.command.id === 'workbench.scm.action.toggleShowStructuralDiff'); + assert.ok(item && isIMenuItem(item)); + const toggled = isICommandActionToggleInfo(item.command.toggled) ? item.command.toggled.condition : item.command.toggled; + const isShown = (enabled: boolean, hasProvider: boolean) => { + const contextKeyService = store.add(new ContextKeyService(new TestConfigurationService({ 'scm.structuralDiff.enabled': enabled }))); + ContextKeys.SCMViewHasStructuralDiffProvider.bindTo(contextKeyService).set(hasProvider); + return contextKeyService.contextMatchesRules(item.when); + }; + assert.deepStrictEqual({ + title: item.command.title, group: item.group, order: item.order, toggled: toggled?.serialize(), + shown: { disabled: isShown(false, true), withoutProvider: isShown(true, false), enabled: isShown(true, true) }, + }, { + title: 'Show Structural Diff', group: '3_structuralDiff', order: 1, + toggled: ContextKeys.SCMViewShowStructuralDiff.serialize(), + shown: { disabled: false, withoutProvider: false, enabled: true }, + }); + }); + + test('describes structural diff in the accessibility help only while enabled and a provider is registered', async () => { + const features = new LanguageFeaturesService(); + const configurationService = new TestConfigurationService({ 'scm.structuralDiff.enabled': true }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ICommandService, {}); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(ISCMViewService, { visibleRepositories: [] }); + instantiationService.stub(IViewsService, { getFocusedViewName: () => '' }); + instantiationService.set(ILanguageFeaturesService, features); + const mentionsStructuralDiff = () => { + const provider = store.add(instantiationService.invokeFunction(accessor => new SCMAccessibilityHelp().getProvider(accessor))); + return provider.provideContent().includes('Show Structural Diff'); + }; + const withoutProvider = mentionsStructuralDiff(); + const registration = features.structuralDiffProvider.register('*', new class extends mock() { }); + const enabled = mentionsStructuralDiff(); + await configurationService.setUserConfiguration('scm.structuralDiff.enabled', false); + const disabled = mentionsStructuralDiff(); + registration.dispose(); + assert.deepStrictEqual({ withoutProvider, enabled, disabled }, { withoutProvider: false, enabled: true, disabled: false }); + }); + + test('the menu command toggles the active Source Control view', async () => { + const view = new class extends mock() { + private show = true; + override get showStructuralDiff(): boolean { return this.show; } + override set showStructuralDiff(value: boolean) { this.show = value; } + }; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, {}, 'getActiveViewWithId', () => view); + const command = CommandsRegistry.getCommand('workbench.scm.action.toggleShowStructuralDiff'); + assert.ok(command); + await instantiationService.invokeFunction(command.handler); + const unchecked = view.showStructuralDiff; + await instantiationService.invokeFunction(command.handler); + assert.deepStrictEqual([unchecked, view.showStructuralDiff], [false, true]); + }); + + test('supports symbol-name keyboard navigation and meaningful screen-reader labels', () => { + const labelService = new class extends mock() { }; + const keyboard = new SCMTreeKeyboardNavigationLabelProvider(() => ViewMode.List, labelService); + const accessibility = new SCMAccessibilityProvider( + new class extends mock() { }, + new TestConfigurationService(), + new class extends mock() { }, + labelService, + ); + assert.deepStrictEqual({ + keyboard: keyboard.getKeyboardNavigationLabel(child), + aria: accessibility.getAriaLabel(child), + }, { keyboard: 'run', aria: 'run, method' }); + }); + + test('renders symbol icons and a textual deletion marker without file actions', () => { + const renderer = new SCMStructuralDiffRenderer(NullHoverService); + const container = $('.scm-view'); + const template = store.add(renderer.renderTemplate(container)); + const render = (element: SCMStructuralDiffElement) => renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + render(parent); + const classIcon = !!container.querySelector('.codicon-colored.codicon-symbol-class'); + render({ ...child, node: { ...child.node, modifiedItem: undefined } }); + const methodIcon = !!container.querySelector('.codicon-colored.codicon-symbol-method'); + const deletedText = template.label.element.textContent; + const deletedMarker = template.status.textContent; + render({ type: 'structuralDiffStatus', id: 'partial', status: 'incomplete', parent: resource, resource, generation: 1, order: 1 }); + assert.deepStrictEqual({ + classIcon, methodIcon, deletedText, deletedMarker, status: template.label.element.textContent, + marker: template.status.textContent, + warning: !!container.querySelector('.codicon-warning'), + warningColored: template.icon.classList.contains('codicon-colored'), + actions: container.querySelectorAll('.actions').length, + }, { classIcon: true, methodIcon: true, deletedText: 'run', deletedMarker: 'D', status: 'Partial structural changes', marker: '', warning: true, warningColored: false, actions: 0 }); + }); + + test('applies the same symbol theme colors as Outline when reusing a row', () => { + const container = $('.monaco-workbench.scm-view'); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + container.style.setProperty('--vscode-symbolIcon-classForeground', 'rgb(200, 120, 10)'); + container.style.setProperty('--vscode-symbolIcon-methodForeground', 'rgb(150, 100, 200)'); + const renderer = new SCMStructuralDiffRenderer(NullHoverService); + const template = store.add(renderer.renderTemplate(container)); + const render = (element: SCMStructuralDiffElement) => renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + render(parent); + const classColor = getWindow(container).getComputedStyle(template.icon).color; + render(child); + const methodColor = getWindow(container).getComputedStyle(template.icon).color; + container.style.setProperty('--vscode-symbolIcon-methodForeground', 'rgb(100, 50, 180)'); + assert.deepStrictEqual({ + classColor, methodColor, + updatedMethodColor: getWindow(container).getComputedStyle(template.icon).color, + oldClassIcon: template.icon.classList.contains('codicon-symbol-class'), + iconHiddenFromScreenReaders: template.icon.getAttribute('aria-hidden'), + }, { + classColor: 'rgb(200, 120, 10)', methodColor: 'rgb(150, 100, 200)', + updatedMethodColor: 'rgb(100, 50, 180)', oldClassIcon: false, iconHiddenFromScreenReaders: 'true', + }); + }); + + test('renders themed textual status markers with accessible descriptions and disposes hovers on row reuse', () => { + const container = $('.monaco-workbench.scm-view'); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + container.style.setProperty('--vscode-gitDecoration-addedResourceForeground', 'rgb(10, 110, 30)'); + container.style.setProperty('--vscode-gitDecoration-deletedResourceForeground', 'rgb(160, 20, 40)'); + container.style.setProperty('--vscode-gitDecoration-modifiedResourceForeground', 'rgb(30, 80, 170)'); + const hoverService = new TestStatusHoverService(); + const renderer = new SCMStructuralDiffRenderer(hoverService); + const template = store.add(renderer.renderTemplate(container)); + const makeNode = (element: SCMStructuralDiffElement) => new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }; + const added = { ...child, node: { ...child.node, originalItem: undefined, modifiedItem: { ...child.node.modifiedItem!, detail: '(value: number)' } } }; + const deleted = { ...child, node: { ...child.node, modifiedItem: undefined } }; + const modified = { + ...child, + node: { + ...child.node, + modifiedChanges: [{ textChangeIndex: 0, range: new Range(3, 2, 3, 5), classification: StructuralDiffClassification.Implementation }], + }, + }; + const renamed = { ...modified, node: { ...modified.node, modifiedItem: { ...modified.node.modifiedItem!, name: 'runNext' } } }; + const rows = [added, deleted, modified, renamed, modified].map(element => { + renderer.renderElement(makeNode(element), 0, template); + const color = getWindow(container).getComputedStyle(template.status).color; + return { + marker: template.status.textContent, + iconClasses: [...template.status.classList].filter(value => value.startsWith('codicon')), + color, + text: template.label.element.textContent, + annotation: template.annotation.textContent, + activeHovers: hoverService.active, + aria: template.label.element.getAttribute('aria-label'), + }; + }); + renderer.renderElement(makeNode(parent), 0, template); + const containerState = { hidden: template.metadata.style.display === 'none', marker: template.status.textContent, activeHovers: hoverService.active }; + renderer.renderElement(makeNode(modified), 0, template); + renderer.disposeElement(makeNode(modified), 0, template); + assert.deepStrictEqual({ + rows, containerState, hovers: hoverService.labels, activeAfterUnrender: hoverService.active, + decorative: template.status.getAttribute('aria-hidden'), + }, { + rows: [ + { marker: 'A', iconClasses: [], color: 'rgb(10, 110, 30)', text: 'run(value: number)', annotation: '', activeHovers: 1, aria: 'run, method, Added, (value: number)' }, + { marker: 'D', iconClasses: [], color: 'rgb(160, 20, 40)', text: 'run', annotation: '', activeHovers: 1, aria: 'run, method, Deleted' }, + { marker: 'M', iconClasses: [], color: 'rgb(30, 80, 170)', text: 'run', annotation: 'impl', activeHovers: 1, aria: 'run, method, Implementation changed' }, + { marker: 'R', iconClasses: [], color: 'rgb(30, 80, 170)', text: 'runNext', annotation: '', activeHovers: 1, aria: 'runNext, method, Renamed from run to runNext' }, + { marker: 'M', iconClasses: [], color: 'rgb(30, 80, 170)', text: 'run', annotation: 'impl', activeHovers: 1, aria: 'run, method, Implementation changed' }, + ], + containerState: { hidden: true, marker: '', activeHovers: 0 }, hovers: ['Added', 'Deleted', 'Implementation changed', 'Renamed from run to runNext', 'Implementation changed', 'Implementation changed'], + activeAfterUnrender: 0, decorative: 'true', + }); + }); + + test('renders change-part annotations without losing signatures or retaining stale row descriptions', () => { + const hoverService = new TestStatusHoverService(); + const renderer = new SCMStructuralDiffRenderer(hoverService); + const template = store.add(renderer.renderTemplate($('.scm-view'))); + const withChanges = (original: StructuralDiffClassification[], modified: StructuralDiffClassification[]) => ({ + ...child, + node: { + ...child.node, + modifiedItem: { ...child.node.modifiedItem!, detail: '(value: number)' }, + originalChanges: original.map(classification => ({ textChangeIndex: 0, range: new Range(2, 2, 2, 5), classification })), + modifiedChanges: modified.map(classification => ({ textChangeIndex: 0, range: new Range(3, 2, 3, 5), classification })), + }, + }); + const render = (element: SCMStructuralDiffElement) => { + renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + return { + text: template.label.element.textContent, + annotation: template.annotation.textContent, + aria: template.label.element.getAttribute('aria-label'), + marker: template.status.textContent, + }; + }; + const rows = [ + withChanges([StructuralDiffClassification.Header], []), + withChanges([], [StructuralDiffClassification.Implementation]), + withChanges([StructuralDiffClassification.Header], [StructuralDiffClassification.Implementation]), + ].map(render); + const ancestor = render(parent); + const added = render({ ...child, node: { ...withChanges([], [StructuralDiffClassification.Header]).node, originalItem: undefined } }); + assert.deepStrictEqual({ rows, ancestor, added, hovers: hoverService.labels }, { + rows: [ + { text: 'run(value: number)', annotation: 'decl', aria: 'run, method, Declaration changed, (value: number)', marker: 'M' }, + { text: 'run(value: number)', annotation: 'impl', aria: 'run, method, Implementation changed, (value: number)', marker: 'M' }, + { text: 'run(value: number)', annotation: 'decl+impl', aria: 'run, method, Declaration and implementation changed, (value: number)', marker: 'M' }, + ], + ancestor: { text: 'Calculator', annotation: '', aria: 'Calculator, class', marker: '' }, + added: { text: 'run(value: number)', annotation: '', aria: 'run, method, Added, (value: number)', marker: 'A' }, + hovers: ['Declaration changed', 'Implementation changed', 'Declaration and implementation changed', 'Added'], + }); + }); + + test('renders renames with R and no annotation, preserving both names in hovers and accessible labels', () => { + const hoverService = new TestStatusHoverService(); + const renderer = new SCMStructuralDiffRenderer(hoverService); + const template = store.add(renderer.renderTemplate($('.scm-view'))); + const element = { + ...child, + node: { + ...child.node, + originalItem: { ...child.node.originalItem!, name: 'runNext' }, + modifiedItem: { ...child.node.modifiedItem!, name: 'runNext2' }, + modifiedChanges: [{ textChangeIndex: 0, range: new Range(3, 9, 3, 10), classification: StructuralDiffClassification.Header }], + }, + }; + renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + assert.deepStrictEqual({ + text: template.label.element.textContent, + annotation: template.annotation.textContent, + annotationHidden: template.annotation.style.display === 'none', + marker: template.status.textContent, + renamed: template.status.classList.contains('renamed'), + modified: template.status.classList.contains('modified'), + added: template.status.classList.contains('added'), + hovers: hoverService.labels, + aria: template.label.element.getAttribute('aria-label'), + }, { + text: 'runNext2', annotation: '', annotationHidden: true, marker: 'R', renamed: true, modified: false, added: false, + hovers: ['Renamed from runNext to runNext2'], + aria: 'runNext2, method, Renamed from runNext to runNext2', + }); + }); + + test('right-aligns unbracketed annotations before textual status markers without squeezing them for long names', () => { + const container = $('.monaco-workbench.scm-view'); + container.style.width = '240px'; + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + const renderer = new SCMStructuralDiffRenderer(NullHoverService); + const cases = [ + { name: 'aVeryLongMethodNameThatMustBeTruncatedBeforeTheAnnotation', classifications: [StructuralDiffClassification.Header], change: 'modified' }, + { name: 'run', classifications: [StructuralDiffClassification.Implementation], change: 'modified' }, + { name: 'calculate', classifications: [StructuralDiffClassification.Header, StructuralDiffClassification.Implementation], change: 'modified' }, + { name: 'newMethod', classifications: [], change: 'added' }, + { name: 'oldMethod', classifications: [], change: 'deleted' }, + { name: 'renamedMethod', classifications: [StructuralDiffClassification.Header], change: 'renamed' }, + ]; + const templates = cases.map(({ name, classifications, change }) => { + const row = $('.monaco-list-row'); + row.style.position = 'relative'; + row.style.width = '100%'; + row.style.height = '22px'; + container.appendChild(row); + const template = store.add(renderer.renderTemplate(row)); + const element = { + ...child, + node: { + ...child.node, + originalItem: change === 'added' ? undefined : { ...child.node.originalItem!, name: change === 'renamed' ? 'previousName' : name }, + modifiedItem: change === 'deleted' ? undefined : { ...child.node.modifiedItem!, name }, + modifiedChanges: classifications.map(classification => ({ textChangeIndex: 0, range: new Range(3, 2, 3, 5), classification })), + }, + }; + renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + return template; + }); + const firstAnnotationRight = templates[0].annotation.getBoundingClientRect().right; + const firstStatusRight = templates[0].status.getBoundingClientRect().right; + const annotatedTemplates = templates.filter(template => template.annotation.style.display !== 'none'); + const nameContainer = templates[0].label.element.querySelector('.monaco-icon-label-container'); + assert.ok(nameContainer); + assert.deepStrictEqual({ + annotations: templates.map(template => template.annotation.textContent), + markers: templates.map(template => template.status.textContent), + annotationEdgesAligned: annotatedTemplates.every(template => Math.abs(template.annotation.getBoundingClientRect().right - firstAnnotationRight) < 1), + statusEdgesAligned: templates.every(template => Math.abs(template.status.getBoundingClientRect().right - firstStatusRight) < 1), + noOverlap: templates.every(template => template.label.element.getBoundingClientRect().right <= template.metadata.getBoundingClientRect().left), + annotationsNotClipped: annotatedTemplates.every(template => template.annotation.scrollWidth <= template.annotation.clientWidth), + markersNotClipped: templates.every(template => template.status.scrollWidth <= template.status.clientWidth), + longNameTruncated: nameContainer.scrollWidth > nameContainer.clientWidth, + metadataHiddenFromScreenReaders: templates.every(template => template.metadata.getAttribute('aria-hidden') === 'true'), + }, { + annotations: ['decl', 'impl', 'decl+impl', '', '', ''], + markers: ['M', 'M', 'M', 'A', 'D', 'R'], + annotationEdgesAligned: true, statusEdgesAligned: true, noOverlap: true, + annotationsNotClipped: true, markersNotClipped: true, longNameTruncated: true, metadataHiddenFromScreenReaders: true, + }); + }); + + for (const [width, modernUI] of [[220, false], [420, false], [220, true], [420, true]] as const) { + test(`aligns and dims structural status boxes like file badge boxes at ${width}px${modernUI ? ' in the Modern UI' : ''}, including diagnostic counts`, () => { + const root = $('.monaco-workbench'); + root.classList.toggle('modern-ui', modernUI); + const container = append(root, $('.scm-view.monaco-list')); + container.style.width = `${width}px`; + container.style.setProperty('--vscode-spacing-size40', '4px'); + container.style.setProperty('--vscode-spacing-size160', '16px'); + container.style.setProperty('--vscode-fontSize-label2', '11px'); + container.style.setProperty('--vscode-fontWeight-semiBold', '600'); + mainWindow.document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const instantiationService = workbenchInstantiationService(undefined, store); + const decorations = store.add(instantiationService.createInstance(DecorationsService)); + instantiationService.stub(IDecorationsService, decorations); + const labels = store.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const renderer = new SCMStructuralDiffRenderer(NullHoverService); + const cases = ['M', 'D', 'A', 'R'].flatMap(letter => [undefined, '5', '123'].map(count => ({ + letter, count, uri: URI.file(`/repo/${letter}-${count ?? 'none'}.ts`), + }))); + store.add(decorations.registerDecorationsProvider({ + label: 'SCM status', + onDidChange: Event.None, + provideDecorations: uri => ({ letter: cases.find(candidate => candidate.uri.toString() === uri.toString())?.letter, weight: 1 }), + })); + store.add(decorations.registerDecorationsProvider({ + label: 'Problems', + onDidChange: Event.None, + provideDecorations: uri => { + const count = cases.find(candidate => candidate.uri.toString() === uri.toString())?.count; + return count ? { letter: count, weight: 10 } : undefined; + }, + })); + const createRow = (indent: number) => { + const row = append(container, $('.monaco-list-row')); + row.style.position = 'relative'; + row.style.height = '22px'; + const contents = append(row, $('.monaco-tl-contents')); + contents.style.paddingLeft = `${indent}px`; + return contents; + }; + // The tree contents' right padding plus the badges' right margin: 12px and 3px, or 4px each in the Modern UI. + const expectedRight = container.getBoundingClientRect().right - (modernUI ? 8 : 15); + const results = cases.map(({ letter, count, uri }) => { + const fileRow = append(createRow(0), $('.resource')); + const fileLabel = labels.create(append(fileRow, $('.name'))); + fileLabel.setFile(uri, { hidePath: true, fileDecorations: { colors: false, badges: true } }); + const template = store.add(renderer.renderTemplate(createRow(32))); + const name = 'aVeryLongMethodNameThatMustLeaveRoomForTheStatus'; + const element = { + ...child, + node: { + ...child.node, + originalItem: letter === 'A' ? undefined : { ...child.node.originalItem!, name: letter === 'R' ? 'previousName' : name }, + modifiedItem: letter === 'D' ? undefined : { ...child.node.modifiedItem!, name }, + modifiedChanges: [{ textChangeIndex: 0, range: new Range(3, 2, 3, 5), classification: StructuralDiffClassification.Implementation }], + }, + }; + renderer.renderElement(new class extends mock>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + const fileStyle = getWindow(container).getComputedStyle(fileLabel.element, '::after'); + const structuralStyle = getWindow(container).getComputedStyle(template.status); + const fileRight = fileLabel.element.getBoundingClientRect().right - parseFloat(fileStyle.marginRight); + const structuralRight = template.status.getBoundingClientRect().right; + return { + fileText: fileStyle.content, + structuralText: template.status.textContent, + rightEdgesAligned: Math.abs(fileRight - structuralRight) < 1 && Math.abs(fileRight - expectedRight) < 1, + justifyContent: [fileStyle.justifyContent, structuralStyle.justifyContent], + minWidth: [fileStyle.minWidth, structuralStyle.minWidth], + opacity: [fileStyle.opacity, structuralStyle.opacity], + sameTypography: fileStyle.fontSize === structuralStyle.fontSize && fileStyle.fontWeight === structuralStyle.fontWeight, + badgeFits: template.status.scrollWidth <= template.status.clientWidth, + }; + }); + assert.deepStrictEqual(results, cases.map(({ letter, count }) => ({ + fileText: JSON.stringify(count ? `${count}, ${letter}` : letter), + structuralText: letter, + rightEdgesAligned: true, justifyContent: ['center', 'center'], minWidth: ['16px', '16px'], opacity: ['0.75', '0.75'], sameTypography: true, badgeFits: true, + }))); + }); + } + + for (const [side, staged] of [['original', false], ['modified', false], ['original', true], ['modified', true]] as const) { + for (const preserveFocus of [false, true]) { + test(`opens the ${side} side of ${staged ? 'staged' : 'working-tree'} changes and respects preserveFocus=${preserveFocus}`, async () => { + const comparisonResource = staged ? new class extends mock() { + override readonly sourceUri = resource.sourceUri; + override readonly multiDiffEditorOriginalUri = this.sourceUri.with({ scheme: 'git', query: JSON.stringify({ path: this.sourceUri.fsPath, ref: 'HEAD' }) }); + override readonly multiDiffEditorModifiedUri = this.sourceUri.with({ scheme: 'git', query: JSON.stringify({ path: this.sourceUri.fsPath, ref: '' }) }); + } : resource; + const originalEditor = new TestCodeEditor(); + const modifiedEditor = new TestCodeEditor(); + const diffEditor = new class extends mock() { + override readonly renderSideBySide = true; + override getEditorType(): string { return EditorType.IDiffEditor; } + override getOriginalEditor(): ICodeEditor { return originalEditor; } + override getModifiedEditor(): ICodeEditor { return modifiedEditor; } + }; + const pane = new class extends mock() { + override getControl(): IDiffEditor { return diffEditor; } + }; + const inputs: (IUntypedEditorInput | undefined)[] = []; + const editorService = new class extends mock() { + override async openEditor(input: IUntypedEditorInput): Promise { inputs.push(input); return pane; } + }; + const element = { ...child, resource: comparisonResource, node: side === 'modified' ? child.node : { ...child.node, modifiedItem: undefined } }; + await openSCMStructuralDiff(element, { preserveFocus, pinned: true }, editorService, () => true); + const range = (side === 'original' ? element.node.originalItem : element.node.modifiedItem)!.selectionRange!; + assert.deepStrictEqual({ + inputs, + original: { selections: originalEditor.selections, reveals: originalEditor.reveals, focused: originalEditor.focused }, + modified: { selections: modifiedEditor.selections, reveals: modifiedEditor.reveals, focused: modifiedEditor.focused }, + }, { + inputs: [{ + original: { resource: comparisonResource.multiDiffEditorOriginalUri }, + modified: { resource: comparisonResource.multiDiffEditorModifiedUri }, + options: { preserveFocus, pinned: true, override: DEFAULT_EDITOR_ASSOCIATION.id }, + }], + original: { selections: side === 'original' ? [range] : [], reveals: side === 'original' ? [range] : [], focused: side === 'original' && !preserveFocus }, + modified: { selections: side === 'modified' ? [range] : [], reveals: side === 'modified' ? [range] : [], focused: side === 'modified' && !preserveFocus }, + }); + }); + } + } + + test('opens deleted symbols in the modified editor where they were deleted when the diff is inline', async () => { + const originalEditor = new TestCodeEditor(); + const modifiedEditor = new TestCodeEditor(); + const diffEditor = new class extends mock() { + override readonly renderSideBySide = false; + override getEditorType(): string { return EditorType.IDiffEditor; } + override getOriginalEditor(): ICodeEditor { return originalEditor; } + override getModifiedEditor(): ICodeEditor { return modifiedEditor; } + }; + const pane = new class extends mock() { + override getControl(): IDiffEditor { return diffEditor; } + }; + const editorService = new class extends mock() { + override async openEditor(): Promise { return pane; } + }; + await openSCMStructuralDiff({ ...child, node: { ...child.node, modifiedItem: undefined }, deletedAt: { lineNumber: 2, column: 1 } }, {}, editorService, () => true); + const range = new Range(2, 1, 2, 1); + assert.deepStrictEqual({ + original: { selections: originalEditor.selections, reveals: originalEditor.reveals, focused: originalEditor.focused }, + modified: { selections: modifiedEditor.selections, reveals: modifiedEditor.reveals, focused: modifiedEditor.focused }, + }, { + original: { selections: [], reveals: [], focused: false }, + modified: { selections: [range], reveals: [range], focused: true }, + }); + }); + + test('does not navigate a stale result after asynchronous editor opening', async () => { + const pending = new DeferredPromise(); + const target = new TestCodeEditor(); + const control = new class extends mock() { + override getEditorType(): string { return EditorType.IDiffEditor; } + override getOriginalEditor(): ICodeEditor { return target; } + override getModifiedEditor(): ICodeEditor { return target; } + }; + const pane = new class extends mock() { + override getControl(): IDiffEditor { return control; } + }; + let current = true; + const editorService = new class extends mock() { + override openEditor(_input: IUntypedEditorInput): Promise { return pending.p; } + }; + const opened = openSCMStructuralDiff(child, {}, editorService, () => current); + current = false; + await pending.complete(pane); + await opened; + assert.deepStrictEqual({ selections: target.selections, reveals: target.reveals, focused: target.focused }, { selections: [], reveals: [], focused: false }); + }); + + test('supports side-by-side opening', async () => { + const groups: (PreferredGroup | IEditorOptions | undefined)[] = []; + const editorService = new class extends mock() { + override async openEditor(_input: IUntypedEditorInput, group?: PreferredGroup | IEditorOptions): Promise { + groups.push(group); + return undefined; + } + }; + await openSCMStructuralDiff(child, {}, editorService, () => true, true); + assert.deepStrictEqual(groups, [SIDE_GROUP]); + }); +}); diff --git a/src/vs/workbench/contrib/scm/test/browser/scmViewService.test.ts b/src/vs/workbench/contrib/scm/test/browser/scmViewService.test.ts new file mode 100644 index 000000000000..140df90a6f26 --- /dev/null +++ b/src/vs/workbench/contrib/scm/test/browser/scmViewService.test.ts @@ -0,0 +1,75 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Emitter, Event } from '../../../../../base/common/event.js'; +import { autorun } from '../../../../../base/common/observable.js'; +import { isEqualOrParent } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { TestFileEditorInput, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { SCMMenus } from '../../browser/menus.js'; +import { SCMViewService } from '../../browser/scmViewService.js'; +import { ISCMProvider, ISCMRepository, ISCMService } from '../../common/scm.js'; + +suite('SCMViewService', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('active repository follows the active editor when its repository is opened after the editor', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const instantiationService = workbenchInstantiationService(undefined, disposables); + + const repositories: ISCMRepository[] = []; + const onDidAddRepository = disposables.add(new Emitter()); + instantiationService.stub(ISCMService, new class extends mock() { + override readonly repositories = repositories; + override readonly onDidAddRepository = onDidAddRepository.event; + override readonly onDidRemoveRepository = Event.None; + override getRepository(idOrResource: string | URI): ISCMRepository | undefined { + return repositories.find(r => URI.isUri(idOrResource) && isEqualOrParent(idOrResource, r.provider.rootUri!)); + } + }()); + + const activeEditor = disposables.add(new TestFileEditorInput(URI.file('/repositoryB/file.txt'), 'testEditor')); + instantiationService.stub(IEditorService, new class extends mock() { + override readonly activeEditor = activeEditor; + override readonly onDidActiveEditorChange = Event.None; + }()); + + const scmViewService = disposables.add(instantiationService.createInstance(SCMViewService)); + + // The menus are not disposed by the view service since it is a singleton + const menus = disposables.add(scmViewService.menus as SCMMenus); + disposables.add(menus.titleMenu); + + const activeRepositories: (string | undefined)[] = []; + disposables.add(autorun(reader => { + activeRepositories.push(scmViewService.activeRepository.read(reader)?.repository.id); + })); + + const addRepository = (id: string) => { + const provider = new class extends mock() { + override readonly id = id; + override readonly providerId = 'test'; + override readonly label = id; + override readonly rootUri = URI.file(`/${id}`); + }(); + const repository = new class extends mock() { + override readonly id = id; + override readonly provider = provider; + }(); + + repositories.push(repository); + onDidAddRepository.fire(repository); + }; + + addRepository('repositoryA'); + addRepository('repositoryB'); + + assert.deepStrictEqual(activeRepositories, [undefined, 'repositoryA', 'repositoryB']); + })); +}); diff --git a/src/vs/workbench/contrib/scm/test/common/scmStructuralDiff.test.ts b/src/vs/workbench/contrib/scm/test/common/scmStructuralDiff.test.ts new file mode 100644 index 000000000000..5f654b4dc2ad --- /dev/null +++ b/src/vs/workbench/contrib/scm/test/common/scmStructuralDiff.test.ts @@ -0,0 +1,947 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, raceTimeout, timeout } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { CancellationError, errorHandler, isCancellationError, setUnexpectedErrorHandler } from '../../../../../base/common/errors.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { IReference } from '../../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../../base/common/observable.js'; +import { extUri } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/virtualScheduling/index.js'; +import { Position } from '../../../../../editor/common/core/position.js'; +import { Range } from '../../../../../editor/common/core/range.js'; +import { IDocumentDiff, IDocumentDiffProviderOptions } from '../../../../../editor/common/diff/documentDiffProvider.js'; +import { linesDiffComputers } from '../../../../../editor/common/diff/linesDiffComputers.js'; +import { StructuralDiff, StructuralDiffClassification, StructuralDiffContext, StructuralDiffNode, StructuralDiffProvider, SymbolKind } from '../../../../../editor/common/languages.js'; +import { ILanguageService } from '../../../../../editor/common/languages/language.js'; +import { ITextModel } from '../../../../../editor/common/model.js'; +import { IEditorWorkerService } from '../../../../../editor/common/services/editorWorker.js'; +import { ILanguageFeaturesService } from '../../../../../editor/common/services/languageFeatures.js'; +import { LanguageFeaturesService } from '../../../../../editor/common/services/languageFeaturesService.js'; +import { IModelService } from '../../../../../editor/common/services/model.js'; +import { IResolvedTextEditorModel, ITextModelService } from '../../../../../editor/common/services/resolverService.js'; +import { ITextResourceConfigurationService } from '../../../../../editor/common/services/textResourceConfiguration.js'; +import { createTextModel } from '../../../../../editor/test/common/testTextModel.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; +import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { ISCMProvider, ISCMResource, ISCMResourceGroup } from '../../common/scm.js'; +import { SCMStructuralDiffElement, SCMStructuralDiffModel, getSCMStructuralDiffAriaLabel, getSCMStructuralDiffChange, getSCMStructuralDiffChangeAnnotation, getSCMStructuralDiffDescription, getSCMStructuralDiffLabel } from '../../common/scmStructuralDiff.js'; + +class TestResource extends mock() { + constructor( + override readonly resourceGroup: ISCMResourceGroup, + override readonly sourceUri: URI, + override readonly multiDiffEditorOriginalUri: URI | undefined, + override readonly multiDiffEditorModifiedUri: URI | undefined, + ) { super(); } +} + +class TestResolver extends mock() { + readonly requested: URI[] = []; + readonly released: URI[] = []; + readonly additionalModels: ITextModel[] = []; + blockOriginal?: DeferredPromise; + originalError?: Error; + modifiedError?: Error; + + constructor(readonly original: ITextModel, readonly modified: ITextModel) { super(); } + + getModel(resource: URI): ITextModel { + const model = [this.original, this.modified, ...this.additionalModels].find(model => extUri.isEqual(resource, model.uri)); + assert.ok(model, `Unexpected model reference: ${resource}`); + return model; + } + + override async createModelReference(resource: URI): Promise> { + this.requested.push(resource); + const isOriginal = extUri.isEqual(resource, this.original.uri); + if (isOriginal && this.blockOriginal) { + await this.blockOriginal.p; + } + const error = isOriginal ? this.originalError : this.modifiedError; + if (error) { + throw error; + } + const model = this.getModel(resource); + return { + object: new class extends mock() { + override readonly textEditorModel = model; + }, + dispose: () => this.released.push(resource), + }; + } +} + +class TestProvider implements StructuralDiffProvider { + result: StructuralDiff | undefined; + pending?: DeferredPromise; + started?: DeferredPromise; + calls = 0; + original?: ITextModel; + modified?: ITextModel; + context?: StructuralDiffContext; + + async provideStructuralDiff(original: ITextModel, modified: ITextModel, context: StructuralDiffContext, token: CancellationToken): Promise { + this.calls++; + this.original = original; + this.modified = modified; + this.context = context; + this.started?.complete(token); + return this.pending?.p ?? this.result; + } +} + +suite('SCM structural diff model', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let original: ITextModel; + let modified: ITextModel; + let resource: ISCMResource; + let group: ISCMResourceGroup; + let groupResources: ISCMResource[]; + let resolver: TestResolver; + let provider: TestProvider; + let features: LanguageFeaturesService; + let model: SCMStructuralDiffModel; + let instantiationService: TestInstantiationService; + let registration: { dispose(): void }; + let errors: number; + let maxComputationTimeSetting: unknown; + let textDiffTimedOut: boolean; + let textDiffTimeBudgets: number[]; + let languageChanges: Emitter<{ model: ITextModel; oldLanguageId: string }>; + let languageRegistryChanges: Emitter; + + setup(() => { + const fileUri = URI.file('file.ts'); + original = store.add(createTextModel('class Calculator {\n\trun() { return 1; }\n}', undefined, undefined, fileUri.with({ scheme: 'git', query: JSON.stringify({ path: fileUri.fsPath, ref: '' }) }))); + modified = store.add(createTextModel('class Calculator {\n\trun() { return 2; }\n}', undefined, undefined, fileUri)); + const scmProvider = new class extends mock() { + override readonly id = 'test'; + }; + groupResources = []; + group = new class extends mock() { + override readonly provider = scmProvider; + override readonly id = 'workingTree'; + override readonly resources = groupResources; + }; + resource = new TestResource(group, modified.uri, original.uri, modified.uri); + groupResources.push(resource); + resolver = new TestResolver(original, modified); + features = new LanguageFeaturesService(); + provider = new TestProvider(); + provider.result = createResult(); + registration = store.add(features.structuralDiffProvider.register([ + { scheme: 'file', language: 'plaintext', pattern: '**/*.ts' }, + { scheme: 'git', language: 'plaintext', pattern: '**/*.ts' }, + ], provider)); + languageChanges = store.add(new Emitter<{ model: ITextModel; oldLanguageId: string }>()); + languageRegistryChanges = store.add(new Emitter()); + errors = 0; + maxComputationTimeSetting = undefined; + textDiffTimedOut = false; + textDiffTimeBudgets = []; + instantiationService = store.add(new TestInstantiationService()); + instantiationService.set(ITextModelService, resolver); + instantiationService.set(ILanguageFeaturesService, features); + instantiationService.set(IModelService, new class extends mock() { + override readonly onModelLanguageChanged = languageChanges.event; + override getModel(): ITextModel | null { return null; } + }); + instantiationService.set(ILanguageService, new class extends mock() { + override readonly onDidChange = languageRegistryChanges.event; + override guessLanguageIdByFilepathOrFirstLine(): string { return 'plaintext'; } + }); + instantiationService.set(IUriIdentityService, new class extends mock() { + override readonly extUri = extUri; + }); + instantiationService.set(ILogService, new class extends NullLogService { + override error(): void { errors++; } + }); + instantiationService.set(ITextResourceConfigurationService, new class extends mock() { + override getValue(): T { return maxComputationTimeSetting as T; } + }); + instantiationService.set(IEditorWorkerService, new class extends mock() { + override async computeDiff(originalUri: URI, modifiedUri: URI, options: IDocumentDiffProviderOptions): Promise { + textDiffTimeBudgets.push(options.maxComputationTimeMs); + const result = linesDiffComputers.getDefault().computeDiff(resolver.getModel(originalUri).getLinesContent(), resolver.getModel(modifiedUri).getLinesContent(), options); + return { identical: false, quitEarly: textDiffTimedOut || result.hitTimeout, changes: result.changes, moves: result.moves }; + } + }); + model = store.add(instantiationService.createInstance(SCMStructuralDiffModel)); + model.setEnabled(true); + }); + + function createResult(): StructuralDiff { + const originalItem = { name: 'Calculator', kind: SymbolKind.Class, range: original.getFullModelRange() }; + const modifiedItem = { name: 'Calculator', kind: SymbolKind.Class, range: modified.getFullModelRange() }; + // All compared versions differ only in the returned digit. Covering it on the file keeps the result complete + // without annotating the symbols. + const change = { textChangeIndex: 0, range: new Range(2, 17, 2, 18), classification: StructuralDiffClassification.Implementation }; + return { + root: { + id: 'file', originalItem: { ...originalItem, kind: SymbolKind.File }, modifiedItem: { ...modifiedItem, kind: SymbolKind.File }, + originalChanges: [change], modifiedChanges: [change], + children: [{ + id: 'class', originalItem, modifiedItem, originalChanges: [], modifiedChanges: [], + children: [{ + id: 'method', + originalItem: { name: 'run', kind: SymbolKind.Method, range: new Range(2, 1, 2, original.getLineMaxColumn(2)), selectionRange: new Range(2, 2, 2, 5) }, + modifiedItem: { name: 'run', kind: SymbolKind.Method, range: new Range(2, 1, 2, modified.getLineMaxColumn(2)), selectionRange: new Range(2, 2, 2, 5) }, + originalChanges: [], modifiedChanges: [], children: [], + }], + }], + }, + isIncomplete: false, + }; + } + + function createStagedResource(): { staged: ISCMResource; head: ITextModel } { + const head = store.add(createTextModel('class Calculator {\n\trun() { return 0; }\n}', undefined, undefined, original.uri.with({ query: JSON.stringify({ path: modified.uri.fsPath, ref: 'HEAD' }) }))); + resolver.additionalModels.push(head); + const stagedGroup = new class extends mock() { + override readonly provider = group.provider; + override readonly id = 'index'; + }; + return { staged: new TestResource(stagedGroup, modified.uri, head.uri, original.uri), head }; + } + + function createWorkingTreeResource(name: string): ISCMResource { + const fileUri = URI.file(name); + const index = store.add(createTextModel(original.getValue(), undefined, undefined, fileUri.with({ scheme: 'git', query: JSON.stringify({ path: fileUri.fsPath, ref: '' }) }))); + const working = store.add(createTextModel(modified.getValue(), undefined, undefined, fileUri)); + resolver.additionalModels.push(index, working); + return new TestResource(group, fileUri, index.uri, working.uri); + } + + function flatten(elements: readonly SCMStructuralDiffElement[]): SCMStructuralDiffElement[] { + return elements.flatMap(element => [element, ...(element.type === 'structuralDiff' ? flatten(element.children) : [])]); + } + + /** A result for the current documents in which the class contains the given methods. Changes are not covered. */ + function createResultWithMethods(...methods: StructuralDiffNode[]): StructuralDiff { + const item = (name: string, kind: SymbolKind, document: ITextModel) => ({ name, kind, range: document.getFullModelRange() }); + return { + root: { + id: 'file', originalItem: item('file.ts', SymbolKind.File, original), modifiedItem: item('file.ts', SymbolKind.File, modified), + originalChanges: [], modifiedChanges: [], + children: [{ + id: 'class', originalItem: item('Calculator', SymbolKind.Class, original), modifiedItem: item('Calculator', SymbolKind.Class, modified), + originalChanges: [], modifiedChanges: [], children: methods, + }], + }, + isIncomplete: true, + }; + } + + /** A method that spans the given line of each document in which it exists. */ + function createMethod(id: string, name: string, originalLine: number | undefined, modifiedLine: number | undefined): StructuralDiffNode { + const item = (document: ITextModel, line: number) => ({ name, kind: SymbolKind.Method, range: new Range(line, 2, line, document.getLineMaxColumn(line)) }); + return { + id, + originalItem: originalLine === undefined ? undefined : item(original, originalLine), + modifiedItem: modifiedLine === undefined ? undefined : item(modified, modifiedLine), + originalChanges: [], modifiedChanges: [], children: [], + }; + } + + function getMethodIds(children: readonly SCMStructuralDiffElement[]): Record { + const [calculator] = children; + assert.ok(calculator.type === 'structuralDiff'); + return Object.fromEntries(calculator.children.map(method => [method.node.id, method.id])); + } + + test('checks eligibility without loading models or invoking providers', () => { + assert.deepStrictEqual({ + supported: model.hasChildren(resource), + unsupported: model.hasChildren(new TestResource(group, URI.file('notes.md'), original.uri, URI.file('notes.md'))), + staged: model.hasChildren(new TestResource(group, modified.uri, original.uri, URI.parse('git:/index.ts'))), + added: model.hasChildren(new TestResource(group, modified.uri, undefined, modified.uri)), + deleted: model.hasChildren(new TestResource(group, modified.uri, original.uri, undefined)), + requests: resolver.requested, calls: provider.calls, + }, { supported: true, unsupported: false, staged: true, added: false, deleted: false, requests: [], calls: 0 }); + }); + + test('does not offer staged structural changes when the provider only supports working files', () => { + const { staged } = createStagedResource(); + registration.dispose(); + store.add(features.structuralDiffProvider.register({ scheme: 'file', language: 'plaintext' }, provider)); + assert.deepStrictEqual({ + staged: model.hasChildren(staged), workingTree: model.hasChildren(resource), + requests: resolver.requested, calls: provider.calls, + }, { staged: false, workingTree: true, requests: [], calls: 0 }); + }); + + test('keeps partially staged and working-tree comparisons separate for the same file', async () => { + const { staged, head } = createStagedResource(); + const stagedChildren = await model.getChildren(staged); + const stagedInputs = [provider.original?.uri, provider.modified?.uri]; + const stagedChanges = provider.context?.changes.map(change => [head.getValueInRange(change.originalRange), original.getValueInRange(change.modifiedRange)]); + const workingChildren = await model.getChildren(resource); + const workingInputs = [provider.original?.uri, provider.modified?.uri]; + const workingChanges = provider.context?.changes.map(change => [original.getValueInRange(change.originalRange), modified.getValueInRange(change.modifiedRange)]); + modified.setValue('class Calculator {\n\trun() { return 3; }\n}'); + assert.deepStrictEqual({ + stagedInputs, workingInputs, stagedChanges, workingChanges, + requests: resolver.requested, calls: provider.calls, + distinctIds: stagedChildren[0].id !== workingChildren[0].id, + stagedStillCurrent: model.isCurrent(stagedChildren[0]), + workingStillCurrent: model.isCurrent(workingChildren[0]), + stagedStillCached: await model.getChildren(staged) === stagedChildren, + }, { + stagedInputs: [head.uri, original.uri], workingInputs: [original.uri, modified.uri], + stagedChanges: [['0', '1']], workingChanges: [['1', '2']], + requests: [head.uri, original.uri, original.uri, modified.uri], calls: 2, + distinctIds: true, stagedStillCurrent: true, workingStillCurrent: false, stagedStillCached: true, + }); + }); + + for (const changed of ['HEAD', 'index', 'group'] as const) { + test(`invalidates staged results when ${changed} changes`, async () => { + const { staged, head } = createStagedResource(); + const stagedChildren = await model.getChildren(staged); + const workingChildren = await model.getChildren(resource); + if (changed === 'HEAD') { + head.setValue('class Calculator {\n\trun() { return 4; }\n}'); + } else if (changed === 'index') { + original.setValue('class Calculator {\n\trun() { return 3; }\n}'); + } else { + model.invalidateGroup(staged.resourceGroup); + } + const current = { staged: model.isCurrent(stagedChildren[0]), workingTree: model.isCurrent(workingChildren[0]) }; + const refreshed = await model.getChildren(staged); + assert.deepStrictEqual({ + current, calls: provider.calls, + sameId: refreshed[0].id === stagedChildren[0].id, + refreshedCurrent: model.isCurrent(refreshed[0]), + inputs: [provider.original?.getValue(), provider.modified?.getValue()], + }, { + current: { staged: false, workingTree: changed !== 'index' }, calls: 3, + sameId: true, refreshedCurrent: true, + inputs: [head.getValue(), original.getValue()], + }); + }); + } + + test('loads lazily, coalesces requests and wraps the returned hierarchy beneath the file', async () => { + const first = model.getChildren(resource); + const second = model.getChildren(resource); + assert.strictEqual(first, second); + const children = await first; + const child = children[0]; + assert.ok(child.type === 'structuralDiff'); + assert.deepStrictEqual({ + labels: [getSCMStructuralDiffLabel(child), getSCMStructuralDiffLabel(child.children[0])], + parentIsFile: child.parent === resource, + nestedParent: child.children[0].parent === child, + current: children.every(child => model.isCurrent(child)), + requests: resolver.requested, calls: provider.calls, + original: provider.original, modified: provider.modified, + cached: await model.getChildren(resource) === children, + }, { + labels: ['Calculator', 'run'], parentIsFile: true, nestedParent: true, current: true, + requests: [original.uri, modified.uri], calls: 1, original, modified, cached: true, + }); + }); + + test('does not resolve unsupported resources', async () => { + registration.dispose(); + assert.deepStrictEqual({ children: await model.getChildren(resource), requests: resolver.requested }, { children: [], requests: [] }); + }); + + test('starts disabled without resolving models or calling providers', async () => { + const disabledModel = store.add(instantiationService.createInstance(SCMStructuralDiffModel)); + assert.deepStrictEqual({ + enabled: disabledModel.enabled, + expandable: disabledModel.hasChildren(resource), + children: await disabledModel.getChildren(resource), + requests: resolver.requested, + calls: provider.calls, + }, { enabled: false, expandable: false, children: [], requests: [], calls: 0 }); + }); + + test('disabling clears cached children and re-enabling loads a fresh result', async () => { + const previous = await model.getChildren(resource); + const changes: (ISCMResource | undefined)[] = []; + store.add(model.onDidChange(resource => changes.push(resource))); + model.setEnabled(false); + const disabled = { + expandable: model.hasChildren(resource), + children: await model.getChildren(resource), + current: model.isCurrent(previous[0]), + released: resolver.released.slice(), + calls: provider.calls, + }; + model.setEnabled(true); + const next = await model.getChildren(resource); + assert.deepStrictEqual({ + disabled, + enabled: model.enabled, + sameId: next[0].id === previous[0].id, + current: model.isCurrent(next[0]), + calls: provider.calls, + changes, + }, { + disabled: { expandable: false, children: [], current: false, released: [original.uri, modified.uri], calls: 1 }, + enabled: true, sameId: true, current: true, calls: 2, changes: [undefined, undefined], + }); + }); + + test('disabling cancels an in-flight provider and discards its late result', async () => { + provider.pending = new DeferredPromise(); + provider.started = new DeferredPromise(); + const pending = model.getChildren(resource); + const token = await provider.started.p; + model.setEnabled(false); + const children = await pending; + await provider.pending.complete(provider.result); + assert.deepStrictEqual({ + cancelled: token.isCancellationRequested, + children, + expandable: model.hasChildren(resource), + released: resolver.released, + calls: provider.calls, + }, { cancelled: true, children: [], expandable: false, released: [original.uri, modified.uri], calls: 1 }); + }); + + test('setting the current enabled state does not clear results or refresh the tree', async () => { + const children = await model.getChildren(resource); + const changes: (ISCMResource | undefined)[] = []; + store.add(model.onDidChange(resource => changes.push(resource))); + model.setEnabled(true); + assert.deepStrictEqual({ + current: model.isCurrent(children[0]), released: resolver.released, changes, + }, { current: true, released: [], changes: [] }); + }); + + for (const invalidate of ['release', 'group', 'provider', 'hide'] as const) { + test(`disposes model references and invalidates previous results on ${invalidate}`, async () => { + const children = await model.getChildren(resource); + switch (invalidate) { + case 'release': model.release(resource); break; + case 'group': model.invalidateGroup(group); break; + case 'provider': model.invalidateProvider(group.provider); break; + case 'hide': model.setVisible(false); model.setVisible(true); break; + } + const previousIsCurrent = model.isCurrent(children[0]); + const next = await model.getChildren(resource); + assert.deepStrictEqual({ + previousIsCurrent, + sameId: next[0].id === children[0].id, + current: model.isCurrent(next[0]), + released: resolver.released, + calls: provider.calls, + }, { previousIsCurrent: false, sameId: true, current: true, released: [original.uri, modified.uri], calls: 2 }); + }); + } + + test('keeps the ids of items and status rows when a file is reloaded', async () => { + provider.result = { ...createResult(), isIncomplete: true }; + const before = await model.getChildren(resource); + modified.setValue('class Calculator {\n\trun() { return 3; }\n}'); + const after = await model.getChildren(resource); + assert.deepStrictEqual({ + labels: flatten(after).map(getSCMStructuralDiffLabel), + ids: flatten(after).map(element => element.id), + previousCurrent: model.isCurrent(before[0]), + current: flatten(after).every(element => model.isCurrent(element)), + calls: provider.calls, + }, { + labels: ['Calculator', 'run', 'Partial structural changes'], + ids: flatten(before).map(element => element.id), + previousCurrent: false, current: true, calls: 2, + }); + }); + + test('derives distinct ids for same-name siblings and keeps the id of a renamed item', async () => { + const result = createResult(); + const method = result.root.children[0].children[0]; + const withMethods = (renamedTo: string, idSuffix: string): StructuralDiff => ({ + ...result, + root: { + ...result.root, + children: [{ + ...result.root.children[0], + children: [ + { ...method, id: `first${idSuffix}` }, + { ...method, id: `second${idSuffix}` }, + { ...method, id: `renamed${idSuffix}`, originalItem: { ...method.originalItem!, name: 'compute' }, modifiedItem: { ...method.modifiedItem!, name: renamedTo } }, + { ...method, id: `added${idSuffix}`, originalItem: undefined, modifiedItem: { ...method.modifiedItem!, name: 'helper' } }, + ], + }], + }, + }); + provider.result = withMethods('calculate', ''); + const [before] = await model.getChildren(resource); + model.release(resource); + provider.result = withMethods('compute', '-reloaded'); + const [after] = await model.getChildren(resource); + assert.ok(before.type === 'structuralDiff' && after.type === 'structuralDiff'); + const childIds = before.children.map(child => child.id); + assert.deepStrictEqual({ + distinct: new Set(childIds).size, + reloaded: after.children.map(child => child.id), + }, { distinct: 4, reloaded: childIds }); + }); + + test('keeps the ids of same-name siblings when other siblings start or stop changing', async () => { + original.setValue('class Calculator {\n\trun(a: string) { return 1; }\n\trun(a: number) { return 1; }\n\tstop() { }\n}'); + modified.setValue('class Calculator {\n\trun(a: string) { return 1; }\n\trun(a: number) { return 2; }\n\tstop() { }\n\trun(a: boolean) { return 0; }\n}'); + provider.result = createResultWithMethods(createMethod('second', 'run', 3, 3), createMethod('added', 'run', undefined, 5)); + const before = getMethodIds(await model.getChildren(resource)); + modified.setValue('class Calculator {\n\trun(a: string) { return 2; }\n\trun(a: number) { return 2; }\n\tstop() { }\n\trun(a: boolean) { return 0; }\n}'); + provider.result = createResultWithMethods(createMethod('first', 'run', 2, 2), createMethod('second', 'run', 3, 3), createMethod('added', 'run', undefined, 5)); + const after = getMethodIds(await model.getChildren(resource)); + assert.deepStrictEqual({ + kept: { second: after.second === before.second, added: after.added === before.added }, + distinct: new Set(Object.values(after)).size, + }, { kept: { second: true, added: true }, distinct: 3 }); + }); + + test('locates deleted items in the modified document', async () => { + original.setValue('class Calculator {\n\trun() { return 1; }\n\t// Stops.\n\tstop() { return 2; }\n}'); + modified.setValue('class Calculator {\n\t// Stops.\n}'); + // The range of stop starts at its comment, which is unchanged. + const stop = createMethod('stop', 'stop', 4, undefined); + provider.result = createResultWithMethods(createMethod('run', 'run', 2, undefined), { ...stop, originalItem: { ...stop.originalItem!, range: new Range(3, 2, 4, original.getLineMaxColumn(4)) } }); + const [calculator] = await model.getChildren(resource); + assert.ok(calculator.type === 'structuralDiff' && provider.context); + // Deleted text is located where it was deleted, unchanged text where it is in the modified document. + assert.deepStrictEqual(calculator.children.map(method => method.deletedAt), [ + Range.getStartPosition(provider.context.changes[0].modifiedRange), + new Position(2, 2), + ]); + }); + + test('keeps the results of resources that remain in a changed group and releases the others', async () => { + const other = createWorkingTreeResource('other.ts'); + groupResources.push(other); + const { staged } = createStagedResource(); + const kept = await model.getChildren(resource); + const removed = await model.getChildren(other); + const stagedChildren = await model.getChildren(staged); + groupResources.splice(groupResources.indexOf(other), 1); + model.releaseRemovedResources(group); + assert.deepStrictEqual({ + kept: model.isCurrent(kept[0]), + cached: await model.getChildren(resource) === kept, + removed: model.isCurrent(removed[0]), + otherGroup: model.isCurrent(stagedChildren[0]), + released: resolver.released, + calls: provider.calls, + }, { + kept: true, cached: true, removed: false, otherGroup: true, + released: [other.multiDiffEditorOriginalUri, other.multiDiffEditorModifiedUri], calls: 3, + }); + }); + + test('releases a resource that its group replaced with a new object for the same file', async () => { + const previous = await model.getChildren(resource); + const replacement = new TestResource(group, resource.sourceUri, resource.multiDiffEditorOriginalUri, resource.multiDiffEditorModifiedUri); + groupResources.splice(groupResources.indexOf(resource), 1, replacement); + model.releaseRemovedResources(group); + const next = await model.getChildren(replacement); + assert.deepStrictEqual({ + previous: model.isCurrent(previous[0]), next: model.isCurrent(next[0]), released: resolver.released, calls: provider.calls, + }, { previous: false, next: true, released: [original.uri, modified.uri], calls: 2 }); + }); + + test('updates availability when providers are removed and registered', async () => { + const children = await model.getChildren(resource); + registration.dispose(); + const removed = { expandable: model.hasChildren(resource), current: model.isCurrent(children[0]) }; + store.add(features.structuralDiffProvider.register({ scheme: 'file' }, provider)); + assert.deepStrictEqual({ removed, added: model.hasChildren(resource), released: resolver.released }, { + removed: { expandable: false, current: false }, added: true, released: [original.uri, modified.uri], + }); + }); + + test('watches empty results so later edits can introduce structural children', async () => { + provider.result = { ...createResult(), root: { ...createResult().root, children: [] } }; + const children = await model.getChildren(resource); + const empty = { children, expandable: model.hasChildren(resource) }; + modified.setValue('class Changed {}'); + assert.deepStrictEqual({ empty, expandableAfterEdit: model.hasChildren(resource), released: resolver.released }, { + empty: { children: [], expandable: false }, expandableAfterEdit: true, released: [original.uri, modified.uri], + }); + }); + + test('treats a provider that cancels on its own like a provider that fails and watches the documents', async () => { + provider.pending = new DeferredPromise(); + provider.started = new DeferredPromise(); + const pending = model.getChildren(resource); + await provider.started.p; + // TypeScript, for example, answers all pending requests as cancelled when its server restarts. + await provider.pending.error(new CancellationError()); + const cancelled = { children: await pending, expandable: model.hasChildren(resource), released: [...resolver.released], errors }; + modified.setValue('class Changed {}'); + assert.deepStrictEqual({ cancelled, expandableAfterEdit: model.hasChildren(resource), released: resolver.released }, { + cancelled: { children: [], expandable: false, released: [], errors: 0 }, expandableAfterEdit: true, released: [original.uri, modified.uri], + }); + }); + + test('cancels stale requests and never publishes their result', async () => { + provider.pending = new DeferredPromise(); + provider.started = new DeferredPromise(); + const pending = model.getChildren(resource); + const token = await provider.started.p; + modified.setValue('class Changed {}'); + const children = await pending; + await provider.pending.complete(provider.result); + assert.deepStrictEqual({ children, cancelled: token.isCancellationRequested, released: resolver.released }, { + children: [], cancelled: true, released: [original.uri, modified.uri], + }); + }); + + test('disposes late model references after the view is hidden', async () => { + resolver.blockOriginal = new DeferredPromise(); + const pending = model.getChildren(resource); + model.setVisible(false); + await resolver.blockOriginal.complete(); + await timeout(0); + assert.deepStrictEqual({ + children: await pending, requested: resolver.requested, released: resolver.released, calls: provider.calls, + }, { children: [], requested: [original.uri, modified.uri], released: [modified.uri, original.uri], calls: 0 }); + }); + + test('analyzes no files while the view is hidden, even when its tree asks for children, and keeps them expandable', async () => { + await model.getChildren(resource); + model.setVisible(false); + const hidden = { + children: await model.getChildren(resource), expandable: model.hasChildren(resource), + requested: resolver.requested.length, released: [...resolver.released], calls: provider.calls, + }; + model.setVisible(true); + const shown = await model.getChildren(resource); + assert.deepStrictEqual({ hidden, shown: shown.map(getSCMStructuralDiffLabel), requested: resolver.requested.length, calls: provider.calls }, { + hidden: { children: [], expandable: true, requested: 2, released: [original.uri, modified.uri], calls: 1 }, + shown: ['Calculator'], requested: 4, calls: 2, + }); + }); + + for (const error of [new Error('Cannot resolve modified model'), new CancellationError()]) { + test(`surfaces ${isCancellationError(error) ? 'a cancelled' : 'a failed'} resolution as a status row and keeps the documents that could be loaded`, async () => { + resolver.modifiedError = error; + const children = await model.getChildren(resource); + assert.deepStrictEqual({ + labels: children.map(getSCMStructuralDiffLabel), errors, released: resolver.released, expandable: model.hasChildren(resource), + }, { labels: ['Unable to load structural changes'], errors: 1, released: [], expandable: true }); + }); + } + + for (const failure of ['original', 'modified', 'timedOut'] as const) { + test(`analyzes a file again when a document that could be loaded changes after ${failure === 'timedOut' ? 'the text diff took too long' : `the ${failure} document could not be loaded`}`, async () => { + resolver.originalError = failure === 'original' ? new Error('Cannot resolve original model') : undefined; + resolver.modifiedError = failure === 'modified' ? new Error('Cannot resolve modified model') : undefined; + textDiffTimedOut = failure === 'timedOut'; + const failed = await model.getChildren(resource); + const releasedAfterFailure = [...resolver.released]; + resolver.originalError = undefined; + resolver.modifiedError = undefined; + textDiffTimedOut = false; + // A document that cannot be loaded cannot be watched, so the other document reports the edit. + const edited = failure === 'modified' ? original : modified; + edited.setValue(edited.getValue().replace(/return \d/, 'return 3')); + const recovered = await model.getChildren(resource); + assert.deepStrictEqual({ + failed: failed.map(getSCMStructuralDiffLabel), releasedAfterFailure, recovered: recovered.map(getSCMStructuralDiffLabel), + }, { + failed: [failure === 'timedOut' ? 'Structural changes took too long to load' : 'Unable to load structural changes'], + releasedAfterFailure: [], recovered: ['Calculator'], + }); + }); + } + + test('preserves partial results and shows their incomplete status', async () => { + provider.result = { ...createResult(), isIncomplete: true }; + const children = await model.getChildren(resource); + assert.deepStrictEqual(children.map(child => [getSCMStructuralDiffLabel(child), child.order]), [ + ['Calculator', 0], ['Partial structural changes', 1], + ]); + }); + + test('rejects duplicate node identities rather than corrupting the tree', async () => { + const result = createResult(); + provider.result = { ...result, root: { ...result.root, children: [...result.root.children, ...result.root.children] } }; + const reported: string[] = []; + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + setUnexpectedErrorHandler(error => reported.push(error.message)); + try { + const children = await model.getChildren(resource); + assert.deepStrictEqual({ labels: children.map(getSCMStructuralDiffLabel), reported, errors }, { + labels: [], reported: [`Invalid structural diff: node 'class' must have an identifier that is unique within the result`], errors: 0, + }); + } finally { + setUnexpectedErrorHandler(previousHandler); + } + }); + + test('describes deleted items without relying on color', async () => { + const result = createResult(); + const node = result.root.children[0]; + provider.result = { ...result, root: { ...result.root, children: [{ ...node, modifiedItem: undefined, children: [] }] } }; + const child = (await model.getChildren(resource))[0]; + assert.deepStrictEqual({ + label: getSCMStructuralDiffLabel(child), description: getSCMStructuralDiffDescription(child), aria: getSCMStructuralDiffAriaLabel(child), + }, { label: 'Calculator', description: 'Deleted', aria: 'Calculator, class, Deleted' }); + }); + + test('distinguishes direct changes from unchanged ancestor containers', async () => { + const element = (await model.getChildren(resource))[0]; + assert.ok(element.type === 'structuralDiff'); + const change = { textChangeIndex: 0, range: new Range(2, 2, 2, 5), classification: StructuralDiffClassification.Implementation }; + const candidates = [ + element, + { ...element, node: { ...element.node, originalItem: undefined } }, + { ...element, node: { ...element.node, modifiedItem: undefined } }, + { ...element, node: { ...element.node, originalChanges: [change] } }, + { ...element, node: { ...element.node, modifiedChanges: [change] } }, + ]; + assert.deepStrictEqual(candidates.map(candidate => ({ + change: getSCMStructuralDiffChange(candidate), + description: getSCMStructuralDiffDescription(candidate), + aria: getSCMStructuralDiffAriaLabel(candidate), + })), [ + { change: undefined, description: undefined, aria: 'Calculator, class' }, + { change: { type: 'added', label: 'Added' }, description: 'Added', aria: 'Calculator, class, Added' }, + { change: { type: 'deleted', label: 'Deleted' }, description: 'Deleted', aria: 'Calculator, class, Deleted' }, + { change: { type: 'modified', label: 'Changed' }, description: 'Implementation changed', aria: 'Calculator, class, Implementation changed' }, + { change: { type: 'modified', label: 'Changed' }, description: 'Implementation changed', aria: 'Calculator, class, Implementation changed' }, + ]); + }); + + test('summarizes declaration and implementation changes from both snapshots', async () => { + const element = (await model.getChildren(resource))[0]; + assert.ok(element.type === 'structuralDiff'); + const withChanges = (original: StructuralDiffClassification[], modified: StructuralDiffClassification[]) => ({ + ...element, + node: { + ...element.node, + originalChanges: original.map(classification => ({ textChangeIndex: 0, range: new Range(2, 2, 2, 5), classification })), + modifiedChanges: modified.map(classification => ({ textChangeIndex: 0, range: new Range(2, 2, 2, 5), classification })), + }, + }); + const candidates = [ + withChanges([StructuralDiffClassification.Header], []), + withChanges([], [StructuralDiffClassification.Header]), + withChanges([StructuralDiffClassification.Implementation], []), + withChanges([], [StructuralDiffClassification.Implementation]), + withChanges([StructuralDiffClassification.Header], [StructuralDiffClassification.Implementation]), + withChanges([StructuralDiffClassification.Implementation], [StructuralDiffClassification.Header]), + withChanges([StructuralDiffClassification.Dependency], [StructuralDiffClassification.Other]), + element, + { ...element, node: { ...withChanges([], [StructuralDiffClassification.Header]).node, originalItem: undefined } }, + { ...element, node: { ...withChanges([StructuralDiffClassification.Implementation], []).node, modifiedItem: undefined } }, + ]; + assert.deepStrictEqual(candidates.map(getSCMStructuralDiffChangeAnnotation), [ + { label: 'decl', description: 'Declaration changed' }, + { label: 'decl', description: 'Declaration changed' }, + { label: 'impl', description: 'Implementation changed' }, + { label: 'impl', description: 'Implementation changed' }, + { label: 'decl+impl', description: 'Declaration and implementation changed' }, + { label: 'decl+impl', description: 'Declaration and implementation changed' }, + undefined, undefined, undefined, undefined, + ]); + }); + + test('represents paired items with different names as renames without annotations', async () => { + const element = (await model.getChildren(resource))[0]; + assert.ok(element.type === 'structuralDiff'); + const renamed = { + ...element, + node: { ...element.node, modifiedItem: { ...element.node.modifiedItem!, name: 'RenamedCalculator' } }, + }; + const candidates = [ + [], + [StructuralDiffClassification.Header], + [StructuralDiffClassification.Header, StructuralDiffClassification.Implementation], + ].map(classifications => ({ + ...renamed, + node: { + ...renamed.node, + modifiedChanges: classifications.map(classification => ({ textChangeIndex: 0, range: new Range(1, 7, 1, 24), classification })), + }, + })); + assert.deepStrictEqual(candidates.map(candidate => ({ + name: getSCMStructuralDiffLabel(candidate), + change: getSCMStructuralDiffChange(candidate), + annotation: getSCMStructuralDiffChangeAnnotation(candidate), + description: getSCMStructuralDiffDescription(candidate), + aria: getSCMStructuralDiffAriaLabel(candidate), + })), candidates.map(() => ({ + name: 'RenamedCalculator', + change: { type: 'renamed', label: 'Renamed from Calculator to RenamedCalculator' }, + annotation: undefined, + description: 'Renamed from Calculator to RenamedCalculator', + aria: 'RenamedCalculator, class, Renamed from Calculator to RenamedCalculator', + }))); + }); + + test('invalidates results when the model language changes', async () => { + const children = await model.getChildren(resource); + languageChanges.fire({ model: modified, oldLanguageId: 'plaintext' }); + assert.deepStrictEqual({ current: model.isCurrent(children[0]), released: resolver.released }, { current: false, released: [original.uri, modified.uri] }); + }); + + test('keeps cached results when an unrelated model changes language', async () => { + const children = await model.getChildren(resource); + const unrelated = store.add(createTextModel('', undefined, undefined, URI.file('unrelated.txt'))); + languageChanges.fire({ model: unrelated, oldLanguageId: 'plaintext' }); + await model.getChildren(resource); + assert.deepStrictEqual({ current: model.isCurrent(children[0]), released: resolver.released, calls: provider.calls }, { current: true, released: [], calls: 1 }); + }); + + test('reports provider availability regardless of the languages providers support', () => { + const available: boolean[] = []; + store.add(autorun(reader => available.push(model.hasProvider.read(reader)))); + registration.dispose(); + const python = features.structuralDiffProvider.register({ language: 'python' }, provider); + const expandableForOtherLanguage = model.hasChildren(resource); + const rust = features.structuralDiffProvider.register({ pattern: '**/*.rs' }, provider); + python.dispose(); + rust.dispose(); + assert.deepStrictEqual({ available, expandableForOtherLanguage }, { available: [true, false, true, false], expandableForOtherLanguage: false }); + }); + + test('ignores provider and language changes while disabled', () => { + model.setEnabled(false); + const changes: (ISCMResource | undefined)[] = []; + store.add(model.onDidChange(resource => changes.push(resource))); + registration.dispose(); + store.add(features.structuralDiffProvider.register({ scheme: 'file' }, provider)); + languageChanges.fire({ model: modified, oldLanguageId: 'plaintext' }); + languageRegistryChanges.fire(); + assert.deepStrictEqual(changes, []); + }); + + test('refreshes for language changes only while a provider is registered', () => { + const changes: (ISCMResource | undefined)[] = []; + store.add(model.onDidChange(resource => changes.push(resource))); + const refreshes: number[] = []; + const step = (action: () => void) => { + action(); + refreshes.push(changes.length); + }; + step(() => languageChanges.fire({ model: modified, oldLanguageId: 'plaintext' })); + step(() => languageRegistryChanges.fire()); + step(() => registration.dispose()); + step(() => languageChanges.fire({ model: modified, oldLanguageId: 'plaintext' })); + step(() => languageRegistryChanges.fire()); + // Cumulative tree refreshes: both language events with a provider, its removal, then both language events again without one. + assert.deepStrictEqual(refreshes, [1, 2, 3, 3, 3]); + }); + + function createResources(count: number): ISCMResource[] { + return Array.from({ length: count }, (_, index) => { + const uri = URI.file(`file${index}.ts`); + resolver.additionalModels.push(store.add(createTextModel(modified.getValue(), undefined, undefined, uri))); + return new TestResource(group, uri, original.uri, uri); + }); + } + + test('analyzes only a few files at a time and queues the rest', async () => { + provider.pending = new DeferredPromise(); + const loads = createResources(5).map(file => model.getChildren(file)); + await timeout(0); + const started = provider.calls; + await provider.pending.complete(provider.result); + const loaded = (await Promise.all(loads)).map(children => children.length); + assert.deepStrictEqual({ started, calls: provider.calls, loaded }, { started: 3, calls: 5, loaded: [1, 1, 1, 1, 1] }); + }); + + test('skips queued files that were collapsed before their turn', async () => { + provider.pending = new DeferredPromise(); + const files = createResources(4); + const loads = files.map(file => model.getChildren(file)); + await timeout(0); + model.release(files[3]); + await provider.pending.complete(provider.result); + const loaded = (await Promise.all(loads)).map(children => children.length); + assert.deepStrictEqual({ calls: provider.calls, loaded }, { calls: 3, loaded: [1, 1, 1, 0] }); + }); + + for (const cancel of ['collapse', 'hide'] as const) { + test(`frees the load slots of files whose documents are still loading when ${cancel === 'collapse' ? 'they are collapsed' : 'the view is hidden'}`, () => runWithFakedTimers({ useFakeTimers: true }, async () => { + resolver.blockOriginal = new DeferredPromise(); + const loading = createResources(3); + const loads = loading.map(file => model.getChildren(file)); + if (cancel === 'collapse') { + for (const file of loading) { + model.release(file); + } + } else { + model.setVisible(false); + model.setVisible(true); + } + const start = Date.now(); + const other = await model.getChildren(createWorkingTreeResource('other.ts')); + const elapsed = Date.now() - start; + await resolver.blockOriginal.complete(); + await timeout(0); + assert.deepStrictEqual({ + elapsed, other: other.map(getSCMStructuralDiffLabel), loads: (await Promise.all(loads)).map(children => children.length), + lateReleases: resolver.released.filter(uri => extUri.isEqual(uri, original.uri)).length, + }, { elapsed: 0, other: ['Calculator'], loads: [0, 0, 0], lateReleases: 3 }); + })); + } + + for (const cancel of ['collapse', 'dispose'] as const) { + test(`settles the requests of files waiting for a load slot right away when ${cancel === 'collapse' ? 'they are collapsed' : 'the model is disposed'}`, async () => { + provider.pending = new DeferredPromise(); + const files = createResources(5); + const loads = files.map(file => model.getChildren(file)); + await timeout(0); + if (cancel === 'collapse') { + model.release(files[3]); + model.release(files[4]); + } else { + model.dispose(); + } + // The load slots stay busy until the provider completes, so the waiting requests must settle before any timer fires. + const waiting = await raceTimeout(Promise.all(loads.slice(3)).then(all => all.map(children => children.length)), 0); + await provider.pending.complete(provider.result); + const running = (await Promise.all(loads.slice(0, 3))).map(children => children.length); + assert.deepStrictEqual({ waiting, running, calls: provider.calls }, { + waiting: [0, 0], running: cancel === 'collapse' ? [1, 1, 1] : [0, 0, 0], calls: 3, + }); + }); + } + + test('shows a status row and stops the provider when loading takes too long', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + provider.pending = new DeferredPromise(); + provider.started = new DeferredPromise(); + const start = Date.now(); + const children = await model.getChildren(resource); + const token = await provider.started.p; + assert.deepStrictEqual({ + labels: children.map(getSCMStructuralDiffLabel), + elapsed: Date.now() - start, + providerCancelled: token.isCancellationRequested, + released: resolver.released, + cached: await model.getChildren(resource) === children, + calls: provider.calls, + errors, + }, { + labels: ['Structural changes took too long to load'], elapsed: 30000, providerCancelled: true, + released: [], cached: true, calls: 1, errors: 0, + }); + })); + + test('shows a status row, not an error, when the text diff exceeds its time budget', async () => { + textDiffTimedOut = true; + maxComputationTimeSetting = 1234; + const children = await model.getChildren(resource); + assert.deepStrictEqual({ + labels: children.map(getSCMStructuralDiffLabel), errors, calls: provider.calls, budgets: textDiffTimeBudgets, released: resolver.released, + }, { + labels: ['Structural changes took too long to load'], errors: 0, calls: 0, budgets: [1234], released: [], + }); + }); +}); diff --git a/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotAnnotation.css b/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotAnnotation.css new file mode 100644 index 000000000000..c55293bbf296 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotAnnotation.css @@ -0,0 +1,302 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Annotation Editor Buttons */ +.screenshot-annotation-editor .monaco-button { + border-radius: var(--vscode-cornerRadius-small); + height: 28px; + font-size: var(--vscode-fontSize-body1); + min-width: 80px; + padding: var(--vscode-spacing-sizeNone) var(--vscode-spacing-size160); + cursor: pointer; +} + +/* Annotation Editor */ +.screenshot-annotation-editor { + position: absolute; + inset: 0; + background: var(--vscode-editor-background, #1e1e1e); + display: flex; + flex-direction: column; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe WPC', 'Segoe UI', system-ui, sans-serif; + font-size: var(--vscode-fontSize-body1); + color: var(--vscode-foreground, #ccc); + outline: none !important; +} + +.screenshot-annotation-editor:focus, +.screenshot-annotation-editor:focus-visible, +.screenshot-annotation-editor:focus-within { + outline: none !important; + box-shadow: none !important; +} + +.screenshot-annotation-editor .annotation-mark-up-header { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size80); + padding: var(--vscode-spacing-size40) var(--vscode-spacing-size80); + border-bottom: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border, var(--vscode-panel-border)); +} + +/* The tools stay centered between two equal sides, the second of which ends with Done. */ +.screenshot-annotation-editor .annotation-mark-up-header-start, +.screenshot-annotation-editor .annotation-mark-up-header-end { + flex: 1 1 0; + display: flex; + justify-content: flex-end; +} + +/* The tools sit in the header, between its two sides. */ +.screenshot-annotation-editor .annotation-toolbar { + flex: 0 1 auto; + min-width: 0; + display: flex; + align-items: center; + justify-content: center; + flex-wrap: wrap; + gap: var(--vscode-spacing-size40); +} + +.screenshot-annotation-editor .annotation-crop-toolbar { + gap: var(--vscode-spacing-size80); +} + +.screenshot-annotation-editor .tool-btn { + width: 28px; + height: 28px; + min-width: 28px; + padding: var(--vscode-spacing-sizeNone); + border-radius: var(--vscode-cornerRadius-small); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + border: var(--vscode-strokeThickness) solid transparent; + background: transparent; + color: var(--vscode-foreground, #ccc); + font-size: var(--vscode-codiconFontSize); + flex-shrink: 0; +} + +.screenshot-annotation-editor .tool-btn:hover { + background: rgba(255, 255, 255, .1); +} + +.screenshot-annotation-editor .tool-btn:focus { + outline: none; +} + +.screenshot-annotation-editor .tool-btn:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder, #007acc); + outline-offset: -1px; +} + +.screenshot-annotation-editor .tool-btn:disabled { + opacity: 0.4; + cursor: default; + pointer-events: none; +} + +.screenshot-annotation-editor .tool-btn:disabled:hover { + background: transparent; +} + +.screenshot-annotation-editor .annotation-toolbar .tool-btn.active { + background: var(--vscode-button-background, #0e639c); + color: var(--vscode-button-foreground, #fff); + border-color: var(--vscode-button-background, #0e639c); +} + +.screenshot-annotation-editor .annotation-toolbar .tool-btn.active, +.screenshot-annotation-editor .annotation-toolbar .tool-btn.active .codicon { + color: var(--vscode-button-foreground, #fff) !important; +} + +.screenshot-annotation-editor .annotation-toolbar .toolbar-separator { + width: var(--vscode-strokeThickness); + height: 20px; + background: var(--vscode-panel-border, #555); + margin: var(--vscode-spacing-sizeNone) var(--vscode-spacing-size40); +} + +.screenshot-annotation-editor .annotation-toolbar .toolbar-spacer { + flex: 1; +} + +.screenshot-annotation-editor .annotation-toolbar .monaco-button, +.screenshot-annotation-editor .annotation-mark-up-header-end .monaco-button { + height: 26px; + min-width: 70px; + padding: var(--vscode-spacing-sizeNone) var(--vscode-spacing-size120); + font-size: var(--vscode-fontSize-label1); + width: auto; + flex: none; +} + +.screenshot-annotation-editor .annotation-toolbar .color-btn { + position: relative; +} + +.screenshot-annotation-editor .annotation-tool-options-popover { + position: absolute; + transform: translateX(-50%); + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size80); + padding: var(--vscode-spacing-size100); + background: var(--vscode-editorWidget-background, #2d2d2d); + border: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border, #555); + border-radius: var(--vscode-cornerRadius-medium); + box-shadow: var(--vscode-shadow-lg); + z-index: 4; + min-width: 220px; +} + +.screenshot-annotation-editor .annotation-tool-options-popover::before { + content: ''; + position: absolute; + top: -6px; + left: 50%; + transform: translateX(-50%) rotate(45deg); + width: 10px; + height: 10px; + background: var(--vscode-editorWidget-background, #2d2d2d); + border-left: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border, #555); + border-top: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border, #555); +} + +.screenshot-annotation-editor .annotation-tool-options-group { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--vscode-spacing-size100); +} + +.screenshot-annotation-editor .annotation-tool-options-label { + color: var(--vscode-descriptionForeground, #999); + font-size: var(--vscode-fontSize-label2); + min-width: 76px; +} + +.screenshot-annotation-editor .annotation-color-swatches, +.screenshot-annotation-editor .annotation-size-buttons { + display: flex; + gap: var(--vscode-spacing-size40); + flex-wrap: wrap; + justify-content: flex-end; +} + +.screenshot-annotation-editor .annotation-color-swatch { + position: relative; + width: 22px; + height: 22px; + border-radius: 50%; + cursor: pointer; + border: 2px solid transparent; + flex-shrink: 0; + padding: var(--vscode-spacing-sizeNone); + background-clip: padding-box; +} + +.screenshot-annotation-editor .annotation-color-swatch.transparent { + background: + linear-gradient(45deg, transparent 46%, #d04b4b 48%, #d04b4b 52%, transparent 54%), + linear-gradient(45deg, #858585 25%, transparent 25%, transparent 75%, #858585 75%), + linear-gradient(45deg, #858585 25%, transparent 25%, transparent 75%, #858585 75%); + background-color: #fff; + background-position: 0 0, 0 0, 5px 5px; + background-size: 100% 100%, 10px 10px, 10px 10px; +} + +.screenshot-annotation-editor .annotation-color-swatch:hover, +.screenshot-annotation-editor .annotation-size-button:hover { + border-color: var(--vscode-focusBorder, rgba(255, 255, 255, .5)); +} + +.screenshot-annotation-editor .annotation-color-swatch:focus-visible, +.screenshot-annotation-editor .annotation-size-button:focus-visible, +.screenshot-annotation-editor .annotation-opacity-slider:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder, #007acc); + outline-offset: 2px; +} + +.screenshot-annotation-editor .annotation-color-swatch.active::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 10px; + height: 6px; + border-left: 2px solid #fff; + border-bottom: 2px solid #fff; + transform: translate(-50%, -65%) rotate(-45deg); + pointer-events: none; +} + +.screenshot-annotation-editor .annotation-color-swatch.active.light-swatch::after { + border-color: #000; +} + +.screenshot-annotation-editor .annotation-size-button.active { + background: var(--vscode-list-activeSelectionBackground, rgba(0, 122, 204, 0.25)); + color: var(--vscode-list-activeSelectionForeground, var(--vscode-foreground, #fff)); + border-color: transparent; +} + +.screenshot-annotation-editor .annotation-size-button { + min-width: 28px; + height: 24px; + border-radius: var(--vscode-cornerRadius-small); + border: var(--vscode-strokeThickness) solid transparent; + background: var(--vscode-button-secondaryBackground, rgba(255, 255, 255, 0.08)); + color: var(--vscode-button-secondaryForeground, var(--vscode-foreground, #ccc)); + cursor: pointer; + font-size: var(--vscode-fontSize-label2); + padding: var(--vscode-spacing-sizeNone) var(--vscode-spacing-size60); +} + +.screenshot-annotation-editor .annotation-opacity-options { + align-items: center; +} + +.screenshot-annotation-editor .annotation-opacity-slider { + flex: 1; + min-width: 92px; + accent-color: var(--vscode-focusBorder, #007acc); +} + +.screenshot-annotation-editor .annotation-opacity-value { + color: var(--vscode-descriptionForeground, #999); + font-size: var(--vscode-fontSize-label2); + width: 34px; + text-align: right; +} + +.screenshot-annotation-editor .annotation-hint { + text-align: center; + padding: var(--vscode-spacing-size60) var(--vscode-spacing-sizeNone); + font-size: var(--vscode-fontSize-label1); + color: var(--vscode-descriptionForeground, #999); +} + +.screenshot-annotation-editor .annotation-canvas-container { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + position: relative; + background: var(--vscode-editorWidget-background, var(--vscode-editor-background, #1e1e1e)); +} + +.screenshot-annotation-editor .annotation-canvas-container canvas { + cursor: crosshair; +} + +.screenshot-annotation-editor .annotation-toolbar .crop-btn { + font-size: var(--vscode-codiconFontSize); + line-height: 1; +} diff --git a/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotTool.css b/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotTool.css new file mode 100644 index 000000000000..f2cd3df7205e --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/media/screenshotTool.css @@ -0,0 +1,70 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Above notifications and quick input; below context views and dialogs so accessibility help can open above it. */ +.screenshot-tool-overlay { + position: fixed; + inset: 0; + z-index: 2560; + user-select: none; + -webkit-user-select: none; + -webkit-app-region: no-drag; + outline: none; + box-shadow: inset 0 0 0 var(--vscode-strokeThickness) var(--vscode-focusBorder); +} + +/* A camera for a click that captures the window, with its hotspot at the lens. */ +.screenshot-tool-overlay { + cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M8.6 5.5 9.9 3.8h4.2l1.3 1.7h3.6a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-10a2 2 0 0 1 2-2z' fill='%23fff' stroke='%23000' stroke-width='1.5' stroke-linejoin='round'/%3E%3Ccircle cx='12' cy='12.5' r='3.6' fill='%23fff' stroke='%23000' stroke-width='1.5'/%3E%3Ccircle cx='12' cy='12.5' r='1' fill='%23000'/%3E%3C/svg%3E") 12 12, crosshair; +} + +/* Dragging selects an area. */ +.screenshot-tool-overlay.selecting { + cursor: crosshair; +} + +.screenshot-tool-overlay .screenshot-tool-hint { + position: absolute; + bottom: var(--vscode-spacing-size400); + left: 0; + right: 0; + width: fit-content; + max-width: calc(100% - 2 * var(--vscode-spacing-size400)); + margin-inline: auto; + box-sizing: border-box; + padding: var(--vscode-spacing-size60) var(--vscode-spacing-size120); + border: var(--vscode-strokeThickness) solid var(--vscode-editorWidget-border); + border-radius: var(--vscode-cornerRadius-large); + background-color: var(--vscode-editorWidget-background); + color: var(--vscode-editorWidget-foreground); + box-shadow: var(--vscode-shadow-lg); + font-size: var(--vscode-fontSize-body1); + font-weight: var(--vscode-fontWeight-regular); + text-align: center; + pointer-events: none; +} + +.screenshot-tool-overlay.selecting .screenshot-tool-hint { + display: none; +} + +.screenshot-tool-overlay .screenshot-tool-selection { + position: absolute; + display: none; + box-sizing: border-box; + pointer-events: none; + border: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + box-shadow: 0 0 0 100vmax color-mix(in srgb, var(--vscode-editor-background) 40%, transparent); +} + +.screenshot-tool-overlay .screenshot-tool-selection.visible { + display: block; +} + +.hc-black .screenshot-tool-overlay .screenshot-tool-hint, +.hc-light .screenshot-tool-overlay .screenshot-tool-hint { + border-color: var(--vscode-contrastBorder); + box-shadow: none; +} diff --git a/src/vs/workbench/contrib/screenshotTool/browser/screenshotAnnotation.ts b/src/vs/workbench/contrib/screenshotTool/browser/screenshotAnnotation.ts new file mode 100644 index 000000000000..abe0187429e8 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/screenshotAnnotation.ts @@ -0,0 +1,2483 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, addDisposableListener, append, DisposableResizeObserver, EventType, getWindow } from '../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../base/browser/window.js'; +import { Button } from '../../../../base/browser/ui/button/button.js'; +import { renderIcon } from '../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { DisposableStore } from '../../../../base/common/lifecycle.js'; +import { localize } from '../../../../nls.js'; +import { defaultButtonStyles } from '../../../../platform/theme/browser/defaultStyles.js'; +import './media/screenshotAnnotation.css'; + +const enum AnnotationTool { + Select = 'select', + Freehand = 'freehand', + Rectangle = 'rectangle', + Ellipse = 'ellipse', + Arrow = 'arrow', + Text = 'text', + Eraser = 'eraser', + Pan = 'pan', + Crop = 'crop', + Move = 'move', +} + +const COLORS = [ + '#ff3b30', // red + '#007aff', // blue + '#34c759', // green + '#ffcc00', // yellow + '#000000', // black + '#ffffff', // white +]; + +const LIGHT_SWATCH_COLORS = new Set(['#34c759', '#ffcc00', '#ffffff', 'transparent']); + +const FONT_FAMILIES = [ + { label: 'Sans-serif', value: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' }, + { label: 'Monospace', value: '"Cascadia Code", "Fira Code", Consolas, monospace' }, + { label: 'Serif', value: 'Georgia, "Times New Roman", serif' }, +]; + +const DEFAULT_TEXT_BOX_WIDTH = 240; +const MIN_TEXT_BOX_WIDTH = 48; +const TEXT_DRAG_THRESHOLD = 4; +/** + * Padding on each side of the displayed image inside the canvas container at fit-to-window scale. The image fills most + * of the markup's host, such as a modal editor, which already has a margin around it. + */ +const CANVAS_BREATHING_ROOM = 24; +const FILL_COLORS = ['transparent', ...COLORS]; +const STROKE_WIDTHS = [2, 4, 8, 12]; +const TEXT_SIZES = [14, 18, 24, 32, 48]; + +export interface IAnnotationDrawAction { + readonly type: AnnotationTool; + strokeColor: string; + fillColor?: string; + opacity: number; + lineWidth: number; + fontSize?: number; + fontFamily?: string; + points?: { x: number; y: number }[]; + rect?: { x: number; y: number; width: number; height: number }; + ellipseRect?: { x: number; y: number; width: number; height: number }; + arrowStart?: { x: number; y: number }; + arrowEnd?: { x: number; y: number }; + text?: string; + textPos?: { x: number; y: number }; + textWidth?: number; + /** Only set for type === AnnotationTool.Eraser: the batch of actions removed in one stroke. */ + erasedActions?: IAnnotationDrawAction[]; + /** Only set for type === AnnotationTool.Eraser: the original index (in `actions[]`) of each erased action at the moment it was removed. */ + erasedIndices?: number[]; + /** Only set for type === AnnotationTool.Crop: the crop active before this action. null means no crop (full original image). */ + cropFrom?: { x: number; y: number; width: number; height: number } | null; + /** Only set for type === AnnotationTool.Crop: the crop active after this action. null means no crop (full original image). */ + cropTo?: { x: number; y: number; width: number; height: number } | null; + /** Only set for type === AnnotationTool.Move: the action that was moved or resized. */ + moveTarget?: IAnnotationDrawAction; + /** Only set for type === AnnotationTool.Move: snapshot of geometric fields before the change. */ + moveBefore?: IAnnotationMoveSnapshot; + /** Only set for type === AnnotationTool.Move: snapshot of geometric fields after the change. */ + moveAfter?: IAnnotationMoveSnapshot; +} + +interface IAnnotationMoveSnapshot { + points?: { x: number; y: number }[]; + rect?: { x: number; y: number; width: number; height: number }; + ellipseRect?: { x: number; y: number; width: number; height: number }; + arrowStart?: { x: number; y: number }; + arrowEnd?: { x: number; y: number }; + textPos?: { x: number; y: number }; + textWidth?: number; +} + +type DrawAction = IAnnotationDrawAction; + +export interface IAnnotationEditorState { + readonly actions: readonly IAnnotationDrawAction[]; + readonly undoneActions: readonly IAnnotationDrawAction[]; + readonly crop: { readonly x: number; readonly y: number; readonly width: number; readonly height: number } | null; +} + +export interface IAnnotationSaveResult { + readonly dataUrl: string; + readonly width: number; + readonly height: number; + readonly state: IAnnotationEditorState; + /** Whether the image was drawn on or cropped. */ + readonly annotated: boolean; +} + +function cloneDrawAction(action: IAnnotationDrawAction, identityMap: Map = new Map()): IAnnotationDrawAction { + const existing = identityMap.get(action); + if (existing) { + return existing; + } + const clone: IAnnotationDrawAction = { + type: action.type, + strokeColor: action.strokeColor, + fillColor: action.fillColor, + opacity: action.opacity, + lineWidth: action.lineWidth, + fontSize: action.fontSize, + fontFamily: action.fontFamily, + points: action.points ? action.points.map(p => ({ x: p.x, y: p.y })) : undefined, + rect: action.rect ? { ...action.rect } : undefined, + ellipseRect: action.ellipseRect ? { ...action.ellipseRect } : undefined, + arrowStart: action.arrowStart ? { ...action.arrowStart } : undefined, + arrowEnd: action.arrowEnd ? { ...action.arrowEnd } : undefined, + text: action.text, + textPos: action.textPos ? { ...action.textPos } : undefined, + textWidth: action.textWidth, + cropFrom: action.cropFrom === undefined ? undefined : action.cropFrom === null ? null : { ...action.cropFrom }, + cropTo: action.cropTo === undefined ? undefined : action.cropTo === null ? null : { ...action.cropTo }, + moveBefore: action.moveBefore ? cloneMoveSnapshot(action.moveBefore) : undefined, + moveAfter: action.moveAfter ? cloneMoveSnapshot(action.moveAfter) : undefined, + }; + identityMap.set(action, clone); + // Resolve references after registering self so cyclic structures don't recurse forever. + clone.erasedActions = action.erasedActions ? action.erasedActions.map(a => cloneDrawAction(a, identityMap)) : undefined; + clone.erasedIndices = action.erasedIndices ? action.erasedIndices.slice() : undefined; + clone.moveTarget = action.moveTarget ? cloneDrawAction(action.moveTarget, identityMap) : undefined; + return clone; +} + +function cloneMoveSnapshot(s: IAnnotationMoveSnapshot): IAnnotationMoveSnapshot { + return { + points: s.points ? s.points.map(p => ({ x: p.x, y: p.y })) : undefined, + rect: s.rect ? { ...s.rect } : undefined, + ellipseRect: s.ellipseRect ? { ...s.ellipseRect } : undefined, + arrowStart: s.arrowStart ? { ...s.arrowStart } : undefined, + arrowEnd: s.arrowEnd ? { ...s.arrowEnd } : undefined, + textPos: s.textPos ? { ...s.textPos } : undefined, + textWidth: s.textWidth, + }; +} + +function captureMoveSnapshot(action: IAnnotationDrawAction): IAnnotationMoveSnapshot { + return cloneMoveSnapshot({ + points: action.points, + rect: action.rect, + ellipseRect: action.ellipseRect, + arrowStart: action.arrowStart, + arrowEnd: action.arrowEnd, + textPos: action.textPos, + textWidth: action.textWidth, + }); +} + +function applyMoveSnapshot(action: IAnnotationDrawAction, snapshot: IAnnotationMoveSnapshot): void { + const fresh = cloneMoveSnapshot(snapshot); + action.points = fresh.points; + action.rect = fresh.rect; + action.ellipseRect = fresh.ellipseRect; + action.arrowStart = fresh.arrowStart; + action.arrowEnd = fresh.arrowEnd; + action.textPos = fresh.textPos; + action.textWidth = fresh.textWidth; +} + +function moveSnapshotsEqual(a: IAnnotationMoveSnapshot, b: IAnnotationMoveSnapshot): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +export class ScreenshotAnnotationEditor { + + private static hintIds = 0; + + private readonly disposables = new DisposableStore(); + private readonly toolOptionsDisposables = new DisposableStore(); + private readonly _onDidSave = new Emitter(); + readonly onDidSave: Event = this._onDidSave.event; + private readonly _onDidCancel = new Emitter(); + readonly onDidCancel: Event = this._onDidCancel.event; + + private container!: HTMLElement; + private canvas!: HTMLCanvasElement; + private ctx!: CanvasRenderingContext2D; + + private activeTool: AnnotationTool = AnnotationTool.Freehand; + private activeStrokeColor = COLORS[0]; + private activeFillColor = 'transparent'; + private activeLineWidth = 4; + private activeOpacity = 1; + private readonly actions: DrawAction[] = []; + private readonly undoneActions: DrawAction[] = []; + /** Counts changes to the actions, so that finishing a markup knows whether it changed the image. */ + private revision = 0; + private savedRevision = 0; + private disposed = false; + private currentAction: DrawAction | null = null; + private isDrawing = false; + private isErasing = false; + /** Actions erased during the current pointer drag; committed to undo stack on pointer-up. */ + private pendingEraseActions: DrawAction[] = []; + /** Original index (in `actions[]`) of each entry in `pendingEraseActions`, captured at the moment it was removed. */ + private pendingEraseIndices: number[] = []; + + private imageElement: HTMLImageElement | null = null; + private imageWidth = 0; + private imageHeight = 0; + private scale = 1; + + // Pan & zoom + private panX = 0; + private panY = 0; + private isPanning = false; + private lastPanPoint = { x: 0, y: 0 }; + + // Crop with handles + private cropMode = false; + private cropRegion: { x: number; y: number; width: number; height: number } | null = null; + private cropDragHandle: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move' | null = null; + private cropDragStart = { x: 0, y: 0 }; + private cropRegionStart: { x: number; y: number; width: number; height: number } | null = null; + private hasUserZoomed = false; + /** Pending wheel-zoom delta accumulated across rapid wheel events; flushed on rAF. */ + private pendingZoom: { factor: number; cx: number; cy: number } | null = null; + private pendingZoomRaf = 0; + + // Original image preserved so crops can be expanded back + private originalImage: { element: HTMLImageElement; width: number; height: number } | null = null; + // Current crop region in original-image coords (null = no crop applied) + private currentCrop: { x: number; y: number; width: number; height: number } | null = null; + // Pre-crop state restored on Cancel + private preCropState: { element: HTMLImageElement; width: number; height: number; currentCrop: { x: number; y: number; width: number; height: number } | null } | null = null; + private mainToolbar: HTMLElement | null = null; + private cropToolbar: HTMLElement | null = null; + /** Holds Done while marking up, which hides with the main toolbar while cropping. */ + private doneContainer: HTMLElement | null = null; + + /** Annotations are stored in original-image coords. While in crop mode the canvas already shows the original image, so the offset is 0. */ + private get cropOffsetX(): number { return this.cropMode ? 0 : (this.currentCrop?.x ?? 0); } + private get cropOffsetY(): number { return this.cropMode ? 0 : (this.currentCrop?.y ?? 0); } + + // Selection (Select tool) + private selectedActionIndex = -1; + private isDraggingSelected = false; + private isResizingSelectedText = false; + private dragStart = { x: 0, y: 0 }; + private selectedTextResizeStartWidth = DEFAULT_TEXT_BOX_WIDTH; + /** Captured at the start of a Select-tool drag/resize so a Move sentinel can be committed on pointer-up. */ + private pendingMove: { target: DrawAction; before: IAnnotationMoveSnapshot } | null = null; + + // Text configuration + private activeFontSize = 18; + private activeFontFamily = FONT_FAMILIES[0].value; + private textPlacementState: { + start: { x: number; y: number }; + current: { x: number; y: number }; + pointerId: number; + } | null = null; + private textEditState: { + pos: { x: number; y: number }; + text: string; + caretIndex: number; + strokeColor: string; + fillColor: string; + opacity: number; + fontSize: number; + fontFamily: string; + width: number; + showBoxOutline: boolean; + } | null = null; + private textEditor: HTMLTextAreaElement | null = null; + private textCaretVisible = true; + private textCaretInterval: number | null = null; + + // Tool buttons (for active state management) + private readonly toolButtons: { element: HTMLElement; tool: AnnotationTool }[] = []; + private undoBtn: HTMLButtonElement | null = null; + private redoBtn: HTMLButtonElement | null = null; + private toolOptionsPopover: HTMLElement | null = null; + + + constructor( + private readonly screenshot: { readonly dataUrl: string }, + private readonly parentElement: HTMLElement, + private readonly initialState?: IAnnotationEditorState, + ) { + this.createUI(); + this.savedRevision = this.revision; + this.loadImage(); + } + + get element(): HTMLElement { + return this.container; + } + + focus(): void { + this.container.focus(); + } + + private createUI(): void { + this.container = append(this.parentElement, $('div.screenshot-annotation-editor')); + this.container.tabIndex = -1; + // The markup is part of whatever hosts it, such as a modal editor that already is a dialog. + this.container.setAttribute('role', 'group'); + this.container.setAttribute('aria-label', localize('markUpImage', "Mark Up Image")); + + // The tools are centered in a header row that ends with Done. + const toolbarParent = append(this.container, $('div.annotation-mark-up-header')); + append(toolbarParent, $('div.annotation-mark-up-header-start')); + + // Main toolbar (hidden during crop mode) + const toolbar = append(toolbarParent, $('div.annotation-toolbar')); + this.mainToolbar = toolbar; + + // 1. Drawing tools: Select, Pan, Crop, Draw, Rectangle, Ellipse, Arrow + const drawingTools: { tool: AnnotationTool; label: string; icon: HTMLSpanElement }[] = [ + { tool: AnnotationTool.Select, label: localize('select', "Select / Move"), icon: renderIcon(Codicon.inspect) }, + { tool: AnnotationTool.Pan, label: localize('pan', "Pan"), icon: renderIcon(Codicon.move) }, + ]; + for (const { tool, label, icon } of drawingTools) { + this.addToolButton(toolbar, tool, label, icon); + } + + // 2. Crop tool + const cropBtn = append(toolbar, $('button.tool-btn.crop-btn')); + cropBtn.appendChild(renderIcon(Codicon.screenCut)); + cropBtn.title = localize('crop', "Crop"); + cropBtn.setAttribute('aria-label', localize('crop', "Crop")); + this.toolButtons.push({ element: cropBtn, tool: AnnotationTool.Crop }); + this.disposables.add(addDisposableListener(cropBtn, EventType.CLICK, () => { + this.setActiveTool(AnnotationTool.Crop); + })); + + // 3. More drawing tools + const moreDrawingTools: { tool: AnnotationTool; label: string; icon: HTMLSpanElement }[] = [ + { tool: AnnotationTool.Freehand, label: localize('freehand', "Draw"), icon: renderIcon(Codicon.edit) }, + { tool: AnnotationTool.Rectangle, label: localize('rectangle', "Rectangle"), icon: renderIcon(Codicon.primitiveSquare) }, + { tool: AnnotationTool.Ellipse, label: localize('ellipse', "Ellipse"), icon: renderIcon(Codicon.circle) }, + { tool: AnnotationTool.Arrow, label: localize('arrow', "Arrow"), icon: renderIcon(Codicon.arrowRight) }, + { tool: AnnotationTool.Eraser, label: localize('eraser', "Eraser"), icon: renderIcon(Codicon.eraser) }, + ]; + for (const { tool, label, icon } of moreDrawingTools) { + this.addToolButton(toolbar, tool, label, icon); + } + + // 4. Text tool + this.addToolButton(toolbar, AnnotationTool.Text, localize('text', "Text"), renderIcon(Codicon.symbolString)); + + this.toolOptionsPopover = append(this.container, $('div.annotation-tool-options-popover')); + this.toolOptionsPopover.style.display = 'none'; + this.disposables.add(addDisposableListener(this.container, EventType.CLICK, e => { + if (!this.toolOptionsPopover || this.toolOptionsPopover.style.display === 'none') { + return; + } + const target = e.target as Node; + if (!this.toolOptionsPopover.contains(target) && !this.toolButtons.some(button => button.element.contains(target))) { + this.hideToolOptions(); + } + })); + this.renderToolOptions(); + + // 5. Separator + append(toolbar, $('div.toolbar-separator')); + + // 6. Undo button + const undoBtn = append(toolbar, $('button.tool-btn')) as HTMLButtonElement; + undoBtn.appendChild(renderIcon(Codicon.discard)); + undoBtn.title = localize('undo', "Undo"); + undoBtn.setAttribute('aria-label', localize('undo', "Undo")); + this.disposables.add(addDisposableListener(undoBtn, EventType.CLICK, () => this.undo())); + this.undoBtn = undoBtn; + + // 7. Redo button + const redoBtn = append(toolbar, $('button.tool-btn')) as HTMLButtonElement; + redoBtn.appendChild(renderIcon(Codicon.redo)); + redoBtn.title = localize('redo', "Redo"); + redoBtn.setAttribute('aria-label', localize('redo', "Redo")); + this.disposables.add(addDisposableListener(redoBtn, EventType.CLICK, () => this.redo())); + this.redoBtn = redoBtn; + this.updateUndoRedoState(); + + // Crop toolbar (shown only during crop mode, hidden by default) + const cropToolbar = append(toolbarParent, $('div.annotation-toolbar.annotation-crop-toolbar')); + cropToolbar.style.display = 'none'; + this.cropToolbar = cropToolbar; + + const cropCancelBtn = this.disposables.add(new Button(cropToolbar, { ...defaultButtonStyles, secondary: true })); + cropCancelBtn.label = localize('cancel', "Cancel"); + this.disposables.add(cropCancelBtn.onDidClick(() => { + this.cancelCrop(); + })); + + const cropApplyBtn = this.disposables.add(new Button(cropToolbar, defaultButtonStyles)); + cropApplyBtn.label = localize('apply', "Apply"); + this.disposables.add(cropApplyBtn.onDidClick(() => { + this.commitCrop(); + })); + + this.doneContainer = append(toolbarParent, $('div.annotation-mark-up-header-end')); + const doneBtn = this.disposables.add(new Button(this.doneContainer, defaultButtonStyles)); + doneBtn.label = localize('done', "Done"); + this.disposables.add(doneBtn.onDidClick(() => this.finish())); + + // Hint label + const hint = append(this.container, $('div.annotation-hint')); + hint.textContent = localize('markUpHint', "Draw on the image or crop it, then select Done to apply your changes."); + hint.id = `screenshot-annotation-hint-${ScreenshotAnnotationEditor.hintIds++}`; + this.container.setAttribute('aria-describedby', hint.id); + + // Canvas container + const canvasContainer = append(this.container, $('div.annotation-canvas-container')); + this.canvas = append(canvasContainer, $('canvas')) as HTMLCanvasElement; + const ctx = this.canvas.getContext('2d'); + if (!ctx) { + throw new Error('Failed to get 2D canvas context'); + } + this.ctx = ctx; + + // Canvas pointer events + this.disposables.add(addDisposableListener(this.canvas, EventType.POINTER_DOWN, e => this.onPointerDown(e))); + this.disposables.add(addDisposableListener(this.canvas, EventType.POINTER_MOVE, e => this.onPointerMove(e))); + this.disposables.add(addDisposableListener(this.canvas, EventType.POINTER_UP, e => this.onPointerUp(e))); + + // Double-click to apply crop + this.disposables.add(addDisposableListener(this.canvas, EventType.DBLCLICK, () => { + this.commitCrop(); + })); + + // Wheel: touchpad two-finger scroll → pan; Ctrl+wheel or pinch → zoom around cursor + this.disposables.add(addDisposableListener(canvasContainer, EventType.WHEEL, (e: WheelEvent) => { + e.preventDefault(); + if (e.ctrlKey) { + // Pinch-to-zoom on touchpad (browser synthesises ctrlKey) or Ctrl+scroll. + // Wheel events can fire faster than we can redraw at high zoom levels, + // so we coalesce the deltas and flush once per animation frame. This keeps + // the canvas reallocation/redraw cost bounded and lets other input (like + // drawing) interleave responsively. + const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX; + const factor = delta < 0 ? 1.1 : 0.9; + const containerRect = canvasContainer.getBoundingClientRect(); + const cx = e.clientX - (containerRect.left + containerRect.width / 2); + const cy = e.clientY - (containerRect.top + containerRect.height / 2); + if (this.pendingZoom) { + this.pendingZoom.factor *= factor; + this.pendingZoom.cx = cx; + this.pendingZoom.cy = cy; + } else { + this.pendingZoom = { factor, cx, cy }; + } + if (!this.pendingZoomRaf) { + const targetWindow = getWindow(this.canvas); + this.pendingZoomRaf = targetWindow.requestAnimationFrame(() => { + this.pendingZoomRaf = 0; + this.flushPendingZoom(); + }); + } + } else { + // Two-finger scroll on touchpad (or plain scroll wheel) → pan + this.panX -= e.deltaX; + this.panY -= e.deltaY; + this.clampPan(); + this.canvas.style.transform = `translate(${this.panX}px, ${this.panY}px)`; + } + }, { passive: false })); + + // Keyboard shortcuts + this.disposables.add(addDisposableListener(this.container, EventType.KEY_DOWN, (e: KeyboardEvent) => { + if (this.textEditState) { + return; + } + if (this.textPlacementState && e.key === 'Escape') { + e.preventDefault(); + e.stopPropagation(); + this.cancelTextPlacement(); + return; + } + if (e.key === 'Escape') { + if (this.cropMode) { + e.preventDefault(); + e.stopPropagation(); + this.cancelCrop(); + return; + } + if (this.selectedActionIndex >= 0) { + // Whoever hosts the markup ends it on Escape, which must only clear the selection here. + e.preventDefault(); + e.stopPropagation(); + this.selectedActionIndex = -1; + this.redraw(); + return; + } + e.preventDefault(); + e.stopPropagation(); + this.finish(); + } else if (e.key === 'Enter' && this.cropMode) { + e.preventDefault(); + this.commitCrop(); + } else if ((e.key === 'Delete' || e.key === 'Backspace') && this.selectedActionIndex >= 0) { + e.preventDefault(); + const removedIndex = this.selectedActionIndex; + const [removed] = this.actions.splice(removedIndex, 1); + this.selectedActionIndex = -1; + // Record the deletion as an Eraser sentinel so undo/redo works just + // like the eraser tool. + this.actions.push({ + type: AnnotationTool.Eraser, + strokeColor: '', + opacity: 1, + lineWidth: 0, + erasedActions: [removed], + erasedIndices: [removedIndex], + }); + this.undoneActions.length = 0; + this.updateUndoRedoState(); + this.redraw(); + } + })); + + // Re-fit canvas when container resizes. The editor can be in any window, so observe with that window's observer. + const resizeObserver = this.disposables.add(new DisposableResizeObserver('screenshotAnnotationEditor', () => { + if (this.imageElement) { + // On resize, ensure the user's current zoom is still at least the new fit-to-window + // scale. Without this, growing the window after zooming out could leave the image + // orphaned in the centre with empty space around it that can't be filled. + if (this.hasUserZoomed) { + const minScale = this.getFitScale(); + if (this.scale < minScale) { + this.scale = minScale; + } + } + this.sizeCanvas(); + this.clampPan(); + this.canvas.style.transform = `translate(${this.panX}px, ${this.panY}px)`; + this.redraw(); + } + }, getWindow(this.parentElement))); + this.disposables.add(resizeObserver.observe(canvasContainer)); + } + + private addToolButton(toolbar: HTMLElement, tool: AnnotationTool, label: string, icon: HTMLSpanElement): void { + const btn = append(toolbar, $('button.tool-btn')); + btn.appendChild(icon); + btn.title = label; + btn.setAttribute('aria-label', label); + btn.setAttribute('aria-pressed', String(tool === this.activeTool)); + if (tool === this.activeTool) { + btn.classList.add('active'); + } + this.toolButtons.push({ element: btn, tool }); + this.disposables.add(addDisposableListener(btn, EventType.CLICK, e => { + e.stopPropagation(); + this.setActiveTool(tool); + })); + } + + private renderToolOptions(): void { + if (!this.toolOptionsPopover) { + return; + } + this.toolOptionsDisposables.clear(); + this.toolOptionsPopover.textContent = ''; + this.toolOptionsPopover.setAttribute('role', 'group'); + this.toolOptionsPopover.setAttribute('aria-label', localize('toolOptions', "Tool Options")); + + this.appendColorOptions( + this.toolOptionsPopover, + this.activeTool === AnnotationTool.Text ? localize('textColor', "Text Color") : localize('strokeColor', "Stroke Color"), + COLORS, + this.activeStrokeColor, + localize('setStrokeColor', "Set Stroke Color"), + color => { + this.activeStrokeColor = color; + this.applyToolOptionsToTextEdit(); + } + ); + + if (this.activeTool !== AnnotationTool.Freehand && this.activeTool !== AnnotationTool.Arrow) { + this.appendColorOptions( + this.toolOptionsPopover, + this.activeTool === AnnotationTool.Text ? localize('textBackgroundColor', "Background Color") : localize('fillColor', "Fill Color"), + FILL_COLORS, + this.activeFillColor, + localize('setFillColor', "Set Fill Color"), + color => { + this.activeFillColor = color; + this.applyToolOptionsToTextEdit(); + } + ); + } + + this.appendSizeOptions(this.toolOptionsPopover); + this.appendOpacityOptions(this.toolOptionsPopover); + } + + private appendColorOptions(container: HTMLElement, label: string, colors: string[], selectedColor: string, ariaLabelPrefix: string, onSelect: (color: string) => void): void { + const group = append(container, $('div.annotation-tool-options-group')); + append(group, $('span.annotation-tool-options-label')).textContent = label; + const swatches = append(group, $('div.annotation-color-swatches')); + for (const color of colors) { + const swatch = append(swatches, $('button.annotation-color-swatch')) as HTMLButtonElement; + const isTransparent = color === 'transparent'; + swatch.classList.toggle('transparent', isTransparent); + swatch.classList.toggle('light-swatch', LIGHT_SWATCH_COLORS.has(color)); + swatch.style.backgroundColor = isTransparent ? 'transparent' : color; + swatch.setAttribute('aria-label', isTransparent ? localize('transparentColor', "{0}: Transparent", ariaLabelPrefix) : localize('colorValue', "{0}: {1}", ariaLabelPrefix, color)); + swatch.setAttribute('aria-pressed', String(color === selectedColor)); + swatch.classList.toggle('active', color === selectedColor); + this.toolOptionsDisposables.add(addDisposableListener(swatch, EventType.CLICK, e => { + e.stopPropagation(); + onSelect(color); + this.renderToolOptions(); + this.redraw(); + })); + } + } + + private appendSizeOptions(container: HTMLElement): void { + const isText = this.activeTool === AnnotationTool.Text; + const values = isText ? TEXT_SIZES : STROKE_WIDTHS; + const selectedValue = isText ? this.activeFontSize : this.activeLineWidth; + const group = append(container, $('div.annotation-tool-options-group')); + append(group, $('span.annotation-tool-options-label')).textContent = isText ? localize('textSize', "Text Size") : localize('strokeWidth', "Stroke Width"); + const buttons = append(group, $('div.annotation-size-buttons')); + for (const value of values) { + const button = append(buttons, $('button.annotation-size-button')) as HTMLButtonElement; + button.textContent = `${value}`; + button.setAttribute('aria-label', isText ? localize('setTextSize', "Set Text Size to {0}px", value) : localize('setStrokeWidth', "Set Stroke Width to {0}px", value)); + button.setAttribute('aria-pressed', String(value === selectedValue)); + button.classList.toggle('active', value === selectedValue); + this.toolOptionsDisposables.add(addDisposableListener(button, EventType.CLICK, e => { + e.stopPropagation(); + if (isText) { + this.activeFontSize = value; + } else { + this.activeLineWidth = value; + } + this.applyToolOptionsToTextEdit(); + this.renderToolOptions(); + this.redraw(); + })); + } + } + + private appendOpacityOptions(container: HTMLElement): void { + const group = append(container, $('div.annotation-tool-options-group.annotation-opacity-options')); + const label = append(group, $('label.annotation-tool-options-label')); + label.textContent = localize('opacity', "Opacity"); + const input = append(group, $('input.annotation-opacity-slider')) as HTMLInputElement; + input.type = 'range'; + input.min = '20'; + input.max = '100'; + input.step = '10'; + input.value = `${Math.round(this.activeOpacity * 100)}`; + input.setAttribute('aria-label', localize('setOpacity', "Set Opacity")); + const value = append(group, $('span.annotation-opacity-value')); + value.textContent = `${input.value}%`; + this.toolOptionsDisposables.add(addDisposableListener(input, EventType.INPUT, e => { + e.stopPropagation(); + this.activeOpacity = Number(input.value) / 100; + value.textContent = `${input.value}%`; + this.applyToolOptionsToTextEdit(); + this.redraw(); + })); + } + + private applyToolOptionsToTextEdit(): void { + if (!this.textEditState) { + return; + } + this.textEditState.strokeColor = this.activeStrokeColor; + this.textEditState.fillColor = this.activeFillColor; + this.textEditState.opacity = this.activeOpacity; + this.textEditState.fontSize = this.activeFontSize; + } + + private showToolOptions(anchor: HTMLElement): void { + if (!this.toolOptionsPopover || !this.hasToolOptions(this.activeTool)) { + this.hideToolOptions(); + return; + } + this.renderToolOptions(); + const containerRect = this.container.getBoundingClientRect(); + const anchorRect = anchor.getBoundingClientRect(); + this.toolOptionsPopover.style.top = `${anchorRect.bottom - containerRect.top + 6}px`; + this.toolOptionsPopover.style.display = 'flex'; + const halfWidth = this.toolOptionsPopover.offsetWidth / 2; + const desiredLeft = anchorRect.left + anchorRect.width / 2 - containerRect.left; + const minLeft = halfWidth + 8; + const maxLeft = Math.max(minLeft, containerRect.width - halfWidth - 8); + this.toolOptionsPopover.style.left = `${Math.min(Math.max(desiredLeft, minLeft), maxLeft)}px`; + } + + private hideToolOptions(): void { + if (this.toolOptionsPopover) { + this.toolOptionsPopover.style.display = 'none'; + } + } + + private hasToolOptions(tool: AnnotationTool): boolean { + return tool === AnnotationTool.Freehand + || tool === AnnotationTool.Rectangle + || tool === AnnotationTool.Ellipse + || tool === AnnotationTool.Arrow + || tool === AnnotationTool.Text; + } + + private setActiveTool(tool: AnnotationTool): void { + if (this.textEditState && tool !== AnnotationTool.Text) { + this.commitTextEdit(); + } + if (this.textPlacementState && tool !== AnnotationTool.Text) { + this.cancelTextPlacement(); + } + + // Special handling for Crop: enter crop mode (don't change activeTool to Crop persistently) + if (tool === AnnotationTool.Crop) { + this.hideToolOptions(); + this.enterCropMode(); + return; + } + + this.activeTool = tool; + this.selectedActionIndex = -1; + for (const tb of this.toolButtons) { + tb.element.classList.toggle('active', tb.tool === tool); + tb.element.setAttribute('aria-pressed', String(tb.tool === tool)); + } + const activeToolButton = this.toolButtons.find(tb => tb.tool === tool)?.element; + if (activeToolButton && this.hasToolOptions(tool)) { + this.showToolOptions(activeToolButton); + } else { + this.hideToolOptions(); + } + this.canvas.style.cursor = tool === AnnotationTool.Select ? 'default' : + tool === AnnotationTool.Pan ? 'grab' : + tool === AnnotationTool.Eraser ? 'url("data:image/svg+xml,") 12 12, cell' : 'crosshair'; + this.redraw(); + } + + private enterCropMode(): void { + if (this.cropMode || !this.originalImage) { + return; + } + // Save current state for cancel + this.preCropState = { + element: this.imageElement!, + width: this.imageWidth, + height: this.imageHeight, + currentCrop: this.currentCrop, + }; + // Switch to original image so user can expand crop region + this.imageElement = this.originalImage.element; + this.imageWidth = this.originalImage.width; + this.imageHeight = this.originalImage.height; + // Initial crop region = current crop (or full original) + this.cropRegion = this.currentCrop + ? { ...this.currentCrop } + : { x: 0, y: 0, width: this.originalImage.width, height: this.originalImage.height }; + this.cropMode = true; + // Mark crop tool button active + for (const tb of this.toolButtons) { + tb.element.classList.toggle('active', tb.tool === AnnotationTool.Crop); + } + // Toggle toolbars + if (this.mainToolbar) { this.mainToolbar.style.display = 'none'; } + if (this.doneContainer) { this.doneContainer.style.visibility = 'hidden'; } + if (this.cropToolbar) { this.cropToolbar.style.display = ''; } + // Reset zoom/pan to fit original + this.hasUserZoomed = false; + this.panX = 0; + this.panY = 0; + this.canvas.style.transform = ''; + this.canvas.style.cursor = 'default'; + this.sizeCanvas(); + this.redraw(); + } + + private exitCropMode(): void { + this.cropMode = false; + this.cropRegion = null; + this.cropDragHandle = null; + this.cropRegionStart = null; + this.preCropState = null; + // Restore main toolbar + if (this.mainToolbar) { this.mainToolbar.style.display = ''; } + if (this.doneContainer) { this.doneContainer.style.visibility = ''; } + if (this.cropToolbar) { this.cropToolbar.style.display = 'none'; } + // Reactivate previous tool + this.setActiveTool(this.activeTool); + } + + private commitCrop(): void { + if (!this.cropMode || !this.cropRegion || !this.originalImage) { + return; + } + const cr = this.normalizeCropRect(this.cropRegion); + if (cr.width < 10 || cr.height < 10) { + return; + } + const cropFrom = this.preCropState?.currentCrop ?? null; + // Push a Crop sentinel into the linear undo stack so undo/redo treats it + // like any other action. + const cropAction: DrawAction = { + type: AnnotationTool.Crop, + strokeColor: '', + opacity: 1, + lineWidth: 0, + cropFrom, + cropTo: cr, + }; + this.actions.push(cropAction); + this.undoneActions.length = 0; + this.updateUndoRedoState(); + this.hasUserZoomed = false; + this.panX = 0; + this.panY = 0; + this.canvas.style.transform = ''; + this.exitCropMode(); + this.applyDisplayedCrop(cr); + } + + private cancelCrop(): void { + if (!this.cropMode || !this.preCropState) { + this.exitCropMode(); + return; + } + // Restore the pre-crop displayed state. Annotations live in original coords + // and don't need to be touched. + this.imageElement = this.preCropState.element; + this.imageWidth = this.preCropState.width; + this.imageHeight = this.preCropState.height; + this.currentCrop = this.preCropState.currentCrop; + this.hasUserZoomed = false; + this.panX = 0; + this.panY = 0; + this.canvas.style.transform = ''; + this.exitCropMode(); + this.sizeCanvas(); + this.redraw(); + } + + private loadImage(): void { + const img = mainWindow.document.createElement('img'); + img.onload = () => { + this.imageElement = img; + this.imageWidth = img.naturalWidth; + this.imageHeight = img.naturalHeight; + // Preserve the original image so crops can be re-expanded + this.originalImage = { element: img, width: img.naturalWidth, height: img.naturalHeight }; + this.currentCrop = null; + + // Restore prior actions (clone so undo/redo state survives reopens). + // Use a shared identity map so Move/Eraser sentinels keep pointing at + // the correct cloned action references, both in actions[] and + // undoneActions[]. + if (this.initialState && (this.initialState.actions.length || this.initialState.undoneActions.length)) { + const identityMap = new Map(); + this.actions.push(...this.initialState.actions.map(a => cloneDrawAction(a, identityMap))); + this.undoneActions.push(...this.initialState.undoneActions.map(a => cloneDrawAction(a, identityMap))); + this.updateUndoRedoState(); + } + + // Restore prior crop, if any. + this.applyDisplayedCrop(this.initialState?.crop ?? null); + this.savedRevision = this.revision; + }; + // Use original screenshot (not annotated) so we can re-crop from full original + img.src = this.screenshot.dataUrl; + } + + /** + * Update the displayed image to reflect the given crop (or the full original + * when null). Cropped images are re-rasterized from the preserved original so + * undo/redo of crop actions is fully reversible without keeping intermediate + * image elements around. + */ + private applyDisplayedCrop(crop: { x: number; y: number; width: number; height: number } | null): void { + if (!this.originalImage) { + return; + } + if (!crop) { + this.imageElement = this.originalImage.element; + this.imageWidth = this.originalImage.width; + this.imageHeight = this.originalImage.height; + this.currentCrop = null; + this.sizeCanvas(); + this.redraw(); + return; + } + const cr = { + x: Math.max(0, Math.min(this.originalImage.width, crop.x)), + y: Math.max(0, Math.min(this.originalImage.height, crop.y)), + width: Math.max(1, Math.min(this.originalImage.width - Math.max(0, crop.x), crop.width)), + height: Math.max(1, Math.min(this.originalImage.height - Math.max(0, crop.y), crop.height)), + }; + const cropCanvas = mainWindow.document.createElement('canvas'); + cropCanvas.width = cr.width; + cropCanvas.height = cr.height; + const cropCtx = cropCanvas.getContext('2d')!; + cropCtx.drawImage(this.originalImage.element, cr.x, cr.y, cr.width, cr.height, 0, 0, cr.width, cr.height); + + const croppedImg = mainWindow.document.createElement('img'); + croppedImg.onload = () => { + this.imageElement = croppedImg; + this.imageWidth = croppedImg.naturalWidth; + this.imageHeight = croppedImg.naturalHeight; + this.currentCrop = cr; + this.sizeCanvas(); + this.redraw(); + }; + croppedImg.src = cropCanvas.toDataURL('image/png'); + } + + private captureState(): IAnnotationEditorState { + const identityMap = new Map(); + return { + actions: this.actions.map(a => cloneDrawAction(a, identityMap)), + undoneActions: this.undoneActions.map(a => cloneDrawAction(a, identityMap)), + crop: this.currentCrop ? { ...this.currentCrop } : null, + }; + } + + private sizeCanvas(): void { + const container = this.canvas.parentElement; + if (!container) { + return; + } + + const targetWindow = getWindow(this.canvas); + const dpr = targetWindow.devicePixelRatio || 1; + const maxWidth = container.clientWidth - CANVAS_BREATHING_ROOM * 2; + const maxHeight = container.clientHeight - CANVAS_BREATHING_ROOM * 2; + + // Only auto-fit on initial load; respect user zoom after that + if (!this.hasUserZoomed) { + const scaleX = maxWidth / this.imageWidth; + const scaleY = maxHeight / this.imageHeight; + this.scale = Math.min(scaleX, scaleY, 1); + } + + const displayWidth = Math.floor(this.imageWidth * this.scale); + const displayHeight = Math.floor(this.imageHeight * this.scale); + + this.canvas.style.width = `${displayWidth}px`; + this.canvas.style.height = `${displayHeight}px`; + + // Cap the backing buffer so a 1920×1080 image at 8× zoom + dpr 2 doesn't try to + // allocate a 30k×17k canvas (~2GB GPU memory) per wheel tick. When the natural + // backing size exceeds the cap, the browser CSS-stretches the canvas (slight + // pixelation at extreme zoom) but allocation and drawing stay cheap. + const MAX_BACKING_DIM = 4096; + const naturalW = displayWidth * dpr; + const naturalH = displayHeight * dpr; + const overage = Math.max(1, naturalW / MAX_BACKING_DIM, naturalH / MAX_BACKING_DIM); + const effectiveDpr = dpr / overage; + this.canvas.width = Math.max(1, Math.floor(displayWidth * effectiveDpr)); + this.canvas.height = Math.max(1, Math.floor(displayHeight * effectiveDpr)); + + this.ctx.setTransform(effectiveDpr, 0, 0, effectiveDpr, 0, 0); + } + + private canvasCoords(e: PointerEvent): { x: number; y: number } { + const rect = this.canvas.getBoundingClientRect(); + return { + x: (e.clientX - rect.left) / this.scale + this.cropOffsetX, + y: (e.clientY - rect.top) / this.scale + this.cropOffsetY, + }; + } + + private onPointerDown(e: PointerEvent): void { + const pos = this.canvasCoords(e); + + // Crop mode: hit test handles or interior + if (this.cropMode && this.cropRegion) { + const handle = this.cropHandleHitTest(pos); + if (handle) { + this.cropDragHandle = handle; + this.cropDragStart = pos; + this.cropRegionStart = { ...this.cropRegion }; + this.canvas.setPointerCapture(e.pointerId); + } + return; + } + + // Select tool: hit test and start drag + if (this.activeTool === AnnotationTool.Select) { + const hitIndex = this.hitTest(pos); + this.selectedActionIndex = hitIndex; + if (hitIndex >= 0) { + const hitAction = this.actions[hitIndex]; + this.pendingMove = { target: hitAction, before: captureMoveSnapshot(hitAction) }; + if (hitAction.type === AnnotationTool.Text && this.isNearTextResizeHandle(pos, hitAction)) { + this.isResizingSelectedText = true; + this.dragStart = { x: pos.x, y: pos.y }; + this.selectedTextResizeStartWidth = hitAction.textWidth ?? DEFAULT_TEXT_BOX_WIDTH; + this.canvas.setPointerCapture(e.pointerId); + this.canvas.style.cursor = 'ew-resize'; + } else { + this.isDraggingSelected = true; + this.dragStart = { x: pos.x, y: pos.y }; + this.canvas.setPointerCapture(e.pointerId); + this.canvas.style.cursor = 'move'; + } + } + this.redraw(); + return; + } + + // Deselect when using other tools + this.selectedActionIndex = -1; + + // Text tool: drag to define width, then enter text editing. + if (this.activeTool === AnnotationTool.Text) { + this.commitTextEdit(); + this.textPlacementState = { + start: pos, + current: pos, + pointerId: e.pointerId, + }; + this.canvas.setPointerCapture(e.pointerId); + this.redraw(); + return; + } + + // Eraser removes annotations that intersect the pointer path. + if (this.activeTool === AnnotationTool.Eraser) { + this.isErasing = true; + this.canvas.setPointerCapture(e.pointerId); + this.eraseAt(pos); + return; + } + + // Pan tool + if (this.activeTool === AnnotationTool.Pan) { + this.isPanning = true; + this.lastPanPoint = { x: e.clientX, y: e.clientY }; + this.canvas.setPointerCapture(e.pointerId); + this.canvas.style.cursor = 'grabbing'; + return; + } + + this.isDrawing = true; + this.canvas.setPointerCapture(e.pointerId); + + switch (this.activeTool) { + case AnnotationTool.Freehand: + this.currentAction = { + type: AnnotationTool.Freehand, + strokeColor: this.activeStrokeColor, + opacity: this.activeOpacity, + lineWidth: this.activeLineWidth, + points: [pos], + }; + break; + case AnnotationTool.Rectangle: + this.currentAction = { + type: AnnotationTool.Rectangle, + strokeColor: this.activeStrokeColor, + fillColor: this.activeFillColor, + opacity: this.activeOpacity, + lineWidth: this.activeLineWidth, + rect: { x: pos.x, y: pos.y, width: 0, height: 0 }, + }; + break; + case AnnotationTool.Ellipse: + this.currentAction = { + type: AnnotationTool.Ellipse, + strokeColor: this.activeStrokeColor, + fillColor: this.activeFillColor, + opacity: this.activeOpacity, + lineWidth: this.activeLineWidth, + ellipseRect: { x: pos.x, y: pos.y, width: 0, height: 0 }, + }; + break; + case AnnotationTool.Arrow: + this.currentAction = { + type: AnnotationTool.Arrow, + strokeColor: this.activeStrokeColor, + opacity: this.activeOpacity, + lineWidth: this.activeLineWidth, + arrowStart: pos, + arrowEnd: pos, + }; + break; + } + } + + private onPointerMove(e: PointerEvent): void { + // Crop mode: drag handle or move region; also update cursor + if (this.cropMode) { + const pos = this.canvasCoords(e); + if (this.cropDragHandle && this.cropRegionStart) { + this.updateCropRegion(pos); + this.redraw(); + return; + } + // Update cursor based on hover + const handle = this.cropHandleHitTest(pos); + this.canvas.style.cursor = this.cropCursorFor(handle); + return; + } + + // Select tool: resize selected text + if (this.isResizingSelectedText && this.selectedActionIndex >= 0) { + const pos = this.canvasCoords(e); + const action = this.actions[this.selectedActionIndex]; + if (action.type === AnnotationTool.Text) { + action.textWidth = Math.max(MIN_TEXT_BOX_WIDTH, this.selectedTextResizeStartWidth + (pos.x - this.dragStart.x)); + this.redraw(); + } + return; + } + + // Select tool: move selected element + if (this.isDraggingSelected && this.selectedActionIndex >= 0) { + const pos = this.canvasCoords(e); + const dx = pos.x - this.dragStart.x; + const dy = pos.y - this.dragStart.y; + this.moveAction(this.actions[this.selectedActionIndex], dx, dy); + this.dragStart = { x: pos.x, y: pos.y }; + this.redraw(); + return; + } + + // Pan + if (this.isPanning) { + const dx = e.clientX - this.lastPanPoint.x; + const dy = e.clientY - this.lastPanPoint.y; + this.panX += dx; + this.panY += dy; + this.lastPanPoint = { x: e.clientX, y: e.clientY }; + this.clampPan(); + this.canvas.style.transform = `translate(${this.panX}px, ${this.panY}px)`; + return; + } + + if (this.textPlacementState) { + const pos = this.canvasCoords(e); + this.textPlacementState.current = pos; + this.redraw(); + return; + } + + if (this.isErasing) { + const pos = this.canvasCoords(e); + this.eraseAt(pos); + return; + } + + if (this.activeTool === AnnotationTool.Select && this.selectedActionIndex >= 0) { + const pos = this.canvasCoords(e); + const action = this.actions[this.selectedActionIndex]; + if (action.type === AnnotationTool.Text && this.isNearTextResizeHandle(pos, action)) { + this.canvas.style.cursor = 'ew-resize'; + } else if (this.selectedActionIndex >= 0) { + this.canvas.style.cursor = 'default'; + } + } + + if (!this.isDrawing) { + return; + } + + const pos = this.canvasCoords(e); + + if (!this.currentAction) { + return; + } + + switch (this.currentAction.type) { + case AnnotationTool.Freehand: + this.currentAction.points!.push(pos); + break; + case AnnotationTool.Rectangle: { + const rect = this.currentAction.rect!; + // Mutate the rect on the current action (this is the in-progress drawing) + (this.currentAction as { rect: { x: number; y: number; width: number; height: number } }).rect = { + ...rect, + width: pos.x - rect.x, + height: pos.y - rect.y, + }; + break; + } + case AnnotationTool.Ellipse: { + const er = this.currentAction.ellipseRect!; + let w = pos.x - er.x; + let h = pos.y - er.y; + if (e.shiftKey) { + const size = Math.max(Math.abs(w), Math.abs(h)); + w = Math.sign(w) * size; + h = Math.sign(h) * size; + } + (this.currentAction as { ellipseRect: { x: number; y: number; width: number; height: number } }).ellipseRect = { ...er, width: w, height: h }; + break; + } + case AnnotationTool.Arrow: + (this.currentAction as { arrowEnd: { x: number; y: number } }).arrowEnd = pos; + break; + } + + this.redraw(); + } + + private onPointerUp(e: PointerEvent): void { + // Crop mode: end handle drag + if (this.cropMode && this.cropDragHandle) { + this.cropDragHandle = null; + this.cropRegionStart = null; + this.canvas.releasePointerCapture(e.pointerId); + return; + } + + // Select tool: end drag + if (this.isResizingSelectedText) { + this.isResizingSelectedText = false; + this.canvas.releasePointerCapture(e.pointerId); + this.canvas.style.cursor = 'default'; + this.commitPendingMove(); + return; + } + + // Select tool: end drag + if (this.isDraggingSelected) { + this.isDraggingSelected = false; + this.canvas.releasePointerCapture(e.pointerId); + this.canvas.style.cursor = 'default'; + this.commitPendingMove(); + return; + } + + // Pan + if (this.isPanning) { + this.isPanning = false; + this.canvas.releasePointerCapture(e.pointerId); + this.canvas.style.cursor = this.activeTool === AnnotationTool.Pan ? 'grab' : 'crosshair'; + return; + } + + if (this.isErasing) { + this.isErasing = false; + this.canvas.releasePointerCapture(e.pointerId); + if (this.pendingEraseActions.length > 0) { + this.actions.push({ + type: AnnotationTool.Eraser, + strokeColor: '', + opacity: 1, + lineWidth: 0, + erasedActions: this.pendingEraseActions.slice(), + erasedIndices: this.pendingEraseIndices.slice(), + }); + this.pendingEraseActions = []; + this.pendingEraseIndices = []; + this.undoneActions.length = 0; + this.updateUndoRedoState(); + } + return; + } + + if (this.textPlacementState) { + const { start, current, pointerId } = this.textPlacementState; + if (pointerId === e.pointerId) { + this.canvas.releasePointerCapture(e.pointerId); + } + const dx = current.x - start.x; + const didDrag = Math.abs(dx) >= TEXT_DRAG_THRESHOLD; + const x = didDrag ? Math.min(start.x, current.x) : start.x; + const rawWidth = didDrag ? Math.abs(dx) : this.getMaxTextWidthFrom(start.x); + const width = didDrag + ? Math.max(1, Math.min(rawWidth, this.getTextImageRight() - x)) + : rawWidth; + const y = start.y; + this.textPlacementState = null; + this.startTextEdit({ x, y }, width, didDrag); + return; + } + + if (!this.isDrawing) { + return; + } + this.canvas.releasePointerCapture(e.pointerId); + this.isDrawing = false; + + if (this.currentAction) { + this.actions.push(this.currentAction); + this.undoneActions.length = 0; + this.updateUndoRedoState(); + this.currentAction = null; + } + + this.redraw(); + } + + private eraseAt(pos: { x: number; y: number }): void { + const hitIndex = this.hitTest(pos); + if (hitIndex < 0) { + return; + } + const [erased] = this.actions.splice(hitIndex, 1); + this.pendingEraseActions.push(erased); + this.pendingEraseIndices.push(hitIndex); + this.selectedActionIndex = -1; + this.redraw(); + } + + private commitPendingMove(): void { + const pending = this.pendingMove; + this.pendingMove = null; + if (!pending) { + return; + } + const after = captureMoveSnapshot(pending.target); + if (moveSnapshotsEqual(pending.before, after)) { + return; + } + this.actions.push({ + type: AnnotationTool.Move, + strokeColor: '', + opacity: 1, + lineWidth: 0, + moveTarget: pending.target, + moveBefore: pending.before, + moveAfter: after, + }); + this.undoneActions.length = 0; + this.updateUndoRedoState(); + } + + private updateUndoRedoState(): void { + this.revision++; + if (this.undoBtn) { + this.undoBtn.disabled = this.actions.length === 0; + } + if (this.redoBtn) { + this.redoBtn.disabled = this.undoneActions.length === 0; + } + } + + private undo(): void { + if (this.textPlacementState) { + this.cancelTextPlacement(); + return; + } + if (this.textEditState) { + this.cancelTextEdit(); + return; + } + const action = this.actions.pop(); + if (!action) { + return; + } + if (action.type === AnnotationTool.Eraser && action.erasedActions) { + // Re-insert each erased action at the index it occupied at the moment it was removed. + // Iterate in reverse because each erase splice was relative to the array state after + // the previous one, so unwinding must happen in reverse order to restore positions. + const erased = action.erasedActions; + const indices = action.erasedIndices ?? erased.map(() => this.actions.length); + for (let i = erased.length - 1; i >= 0; i--) { + const idx = Math.min(indices[i], this.actions.length); + this.actions.splice(idx, 0, erased[i]); + } + } + this.undoneActions.push(action); + this.updateUndoRedoState(); + this.selectedActionIndex = -1; + if (action.type === AnnotationTool.Crop) { + this.applyDisplayedCrop(action.cropFrom ?? null); + } else if (action.type === AnnotationTool.Move && action.moveTarget && action.moveBefore) { + applyMoveSnapshot(action.moveTarget, action.moveBefore); + this.redraw(); + } else { + this.redraw(); + } + } + + private redo(): void { + if (this.textPlacementState) { + return; + } + if (this.textEditState) { + return; + } + const action = this.undoneActions.pop(); + if (!action) { + return; + } + if (action.type === AnnotationTool.Eraser && action.erasedActions) { + // Re-apply the erase: remove the re-inserted actions by reference. + for (const erased of action.erasedActions) { + const idx = this.actions.indexOf(erased); + if (idx >= 0) { + this.actions.splice(idx, 1); + } + } + } + this.actions.push(action); + this.selectedActionIndex = -1; + this.updateUndoRedoState(); + if (action.type === AnnotationTool.Crop) { + this.applyDisplayedCrop(action.cropTo ?? null); + } else if (action.type === AnnotationTool.Move && action.moveTarget && action.moveAfter) { + applyMoveSnapshot(action.moveTarget, action.moveAfter); + this.redraw(); + } else { + this.redraw(); + } + } + + private cropHandleHitTest(pos: { x: number; y: number }): 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move' | null { + if (!this.cropRegion) { + return null; + } + const r = this.normalizeCropRect(this.cropRegion); + // Convert handle pixel size to image coords + const handlePx = 12; + const tol = handlePx / this.scale; + const cx = r.x + r.width / 2; + const cy = r.y + r.height / 2; + const handles: { name: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; x: number; y: number }[] = [ + { name: 'nw', x: r.x, y: r.y }, + { name: 'n', x: cx, y: r.y }, + { name: 'ne', x: r.x + r.width, y: r.y }, + { name: 'e', x: r.x + r.width, y: cy }, + { name: 'se', x: r.x + r.width, y: r.y + r.height }, + { name: 's', x: cx, y: r.y + r.height }, + { name: 'sw', x: r.x, y: r.y + r.height }, + { name: 'w', x: r.x, y: cy }, + ]; + for (const h of handles) { + if (Math.abs(pos.x - h.x) <= tol && Math.abs(pos.y - h.y) <= tol) { + return h.name; + } + } + // Inside region → move + if (pos.x >= r.x && pos.x <= r.x + r.width && pos.y >= r.y && pos.y <= r.y + r.height) { + return 'move'; + } + return null; + } + + private cropCursorFor(handle: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move' | null): string { + switch (handle) { + case 'nw': + case 'se': return 'nwse-resize'; + case 'ne': + case 'sw': return 'nesw-resize'; + case 'n': + case 's': return 'ns-resize'; + case 'e': + case 'w': return 'ew-resize'; + case 'move': return 'move'; + default: return 'default'; + } + } + + private updateCropRegion(pos: { x: number; y: number }): void { + if (!this.cropRegionStart || !this.cropDragHandle) { + return; + } + const dx = pos.x - this.cropDragStart.x; + const dy = pos.y - this.cropDragStart.y; + const start = this.cropRegionStart; + + // Translating the entire box: keep dimensions fixed and clamp only the position. + if (this.cropDragHandle === 'move') { + const x = Math.max(0, Math.min(this.imageWidth - start.width, start.x + dx)); + const y = Math.max(0, Math.min(this.imageHeight - start.height, start.y + dy)); + this.cropRegion = { x, y, width: start.width, height: start.height }; + return; + } + + let { x, y, width, height } = start; + switch (this.cropDragHandle) { + case 'nw': + x += dx; y += dy; width -= dx; height -= dy; + break; + case 'n': + y += dy; height -= dy; + break; + case 'ne': + y += dy; width += dx; height -= dy; + break; + case 'e': + width += dx; + break; + case 'se': + width += dx; height += dy; + break; + case 's': + height += dy; + break; + case 'sw': + x += dx; width -= dx; height += dy; + break; + case 'w': + x += dx; width -= dx; + break; + } + // Clamp to image bounds + x = Math.max(0, Math.min(this.imageWidth, x)); + y = Math.max(0, Math.min(this.imageHeight, y)); + width = Math.max(10, Math.min(this.imageWidth - x, width)); + height = Math.max(10, Math.min(this.imageHeight - y, height)); + this.cropRegion = { x, y, width, height }; + } + + private normalizeCropRect(r: { x: number; y: number; width: number; height: number }): { x: number; y: number; width: number; height: number } { + return { + x: r.width < 0 ? r.x + r.width : r.x, + y: r.height < 0 ? r.y + r.height : r.y, + width: Math.abs(r.width), + height: Math.abs(r.height), + }; + } + + private startTextEdit(pos: { x: number; y: number }, width: number, showBoxOutline: boolean): void { + this.commitTextEdit(); + + const editor = mainWindow.document.createElement('textarea'); + editor.setAttribute('aria-label', localize('typeText', "Type text")); + editor.setAttribute('wrap', 'off'); + editor.style.position = 'fixed'; + editor.style.left = '-10000px'; + editor.style.top = '0'; + editor.style.width = '1px'; + editor.style.height = '1px'; + editor.style.opacity = '0'; + editor.style.pointerEvents = 'none'; + editor.style.padding = '0'; + editor.style.border = '0'; + editor.style.margin = '0'; + editor.style.resize = 'none'; + editor.style.overflow = 'hidden'; + this.container.appendChild(editor); + + this.textEditState = { + pos, + text: '', + caretIndex: 0, + strokeColor: this.activeStrokeColor, + fillColor: this.activeFillColor, + opacity: this.activeOpacity, + fontSize: this.activeFontSize, + fontFamily: this.activeFontFamily, + width, + showBoxOutline, + }; + this.textEditor = editor; + this.startTextCaretBlink(); + + const sync = () => { + if (!this.textEditState || this.textEditor !== editor) { + return; + } + this.textEditState.text = editor.value; + this.textEditState.caretIndex = editor.selectionStart ?? editor.value.length; + this.textCaretVisible = true; + this.redraw(); + }; + + editor.addEventListener('input', sync); + editor.addEventListener('keyup', sync); + editor.addEventListener('click', sync); + editor.addEventListener('select', sync); + editor.addEventListener('keydown', e => { + e.stopPropagation(); + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + this.commitTextEdit(); + } else if (e.key === 'Escape') { + e.preventDefault(); + this.cancelTextEdit(); + } + }); + editor.addEventListener('blur', () => { + if (this.textEditor === editor) { + this.commitTextEdit(); + } + }); + + setTimeout(() => { + if (this.textEditor === editor) { + editor.focus(); + editor.setSelectionRange(editor.value.length, editor.value.length); + } + }, 0); + + this.redraw(); + } + + private startTextCaretBlink(): void { + if (this.textCaretInterval !== null) { + getWindow(this.container).clearInterval(this.textCaretInterval); + } + this.textCaretVisible = true; + this.textCaretInterval = getWindow(this.container).setInterval(() => { + if (!this.textEditState) { + return; + } + this.textCaretVisible = !this.textCaretVisible; + this.redraw(); + }, 500); + } + + private stopTextCaretBlink(): void { + if (this.textCaretInterval !== null) { + getWindow(this.container).clearInterval(this.textCaretInterval); + this.textCaretInterval = null; + } + this.textCaretVisible = true; + } + + private commitTextEdit(): void { + if (!this.textEditState) { + return; + } + + const { text, pos, strokeColor, fillColor, opacity, fontFamily, fontSize, width } = this.textEditState; + this.cleanupTextEditor(); + if (text.trim()) { + this.actions.push({ + type: AnnotationTool.Text, + strokeColor, + fillColor, + opacity, + lineWidth: 1, + fontSize, + fontFamily, + text, + textPos: pos, + textWidth: width, + }); + this.undoneActions.length = 0; + this.updateUndoRedoState(); + } + this.redraw(); + } + + private cancelTextEdit(): void { + if (!this.textEditState) { + return; + } + this.cleanupTextEditor(); + this.redraw(); + } + + private cancelTextPlacement(): void { + if (!this.textPlacementState) { + return; + } + if (this.canvas.hasPointerCapture(this.textPlacementState.pointerId)) { + this.canvas.releasePointerCapture(this.textPlacementState.pointerId); + } + this.textPlacementState = null; + this.redraw(); + } + + private getTextImageRight(): number { + return this.cropOffsetX + this.imageWidth; + } + + private getMaxTextWidthFrom(startX: number): number { + return Math.max(1, this.getTextImageRight() - startX); + } + + private cleanupTextEditor(focusEditor = true): void { + this.stopTextCaretBlink(); + this.textEditor?.remove(); + this.textEditor = null; + this.textEditState = null; + if (focusEditor) { + this.container.focus(); + } + } + + private redraw(): void { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + + // Draw background image + if (this.imageElement) { + this.ctx.drawImage(this.imageElement, 0, 0, this.imageWidth * this.scale, this.imageHeight * this.scale); + } + + // Annotations are stored in original-image coords; translate so they appear correctly + // over the (possibly cropped) displayed image. + this.ctx.save(); + this.ctx.translate(-this.cropOffsetX * this.scale, -this.cropOffsetY * this.scale); + + // Draw all completed annotations + for (const action of this.actions) { + this.drawAction(action); + } + + // Draw selection highlight + if (this.selectedActionIndex >= 0 && this.selectedActionIndex < this.actions.length) { + this.drawSelectionHighlight(this.actions[this.selectedActionIndex]); + } + + // Draw current in-progress annotation + if (this.currentAction) { + this.drawAction(this.currentAction); + } + + if (this.textEditState) { + this.drawTextEditState(); + } + + if (this.textPlacementState) { + this.drawTextPlacementState(); + } + + this.ctx.restore(); + + // Draw crop overlay with handles + if (this.cropMode && this.cropRegion) { + const r = this.normalizeCropRect(this.cropRegion); + const dpr = getWindow(this.canvas).devicePixelRatio || 1; + const cw = this.canvas.width / dpr; + const ch = this.canvas.height / dpr; + const rx = r.x * this.scale; + const ry = r.y * this.scale; + const rw = r.width * this.scale; + const rh = r.height * this.scale; + + this.ctx.save(); + // Dim area outside crop + this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; + this.ctx.fillRect(0, 0, cw, ry); // top + this.ctx.fillRect(0, ry + rh, cw, ch - (ry + rh)); // bottom + this.ctx.fillRect(0, ry, rx, rh); // left + this.ctx.fillRect(rx + rw, ry, cw - (rx + rw), rh); // right + + // Draw crop border + this.ctx.strokeStyle = '#ffffff'; + this.ctx.lineWidth = 1; + this.ctx.strokeRect(rx, ry, rw, rh); + + // Draw 8 handles (corner squares) + const handleSize = 10; + const half = handleSize / 2; + const handles: { x: number; y: number }[] = [ + { x: rx, y: ry }, // nw + { x: rx + rw / 2, y: ry }, // n + { x: rx + rw, y: ry }, // ne + { x: rx + rw, y: ry + rh / 2 }, // e + { x: rx + rw, y: ry + rh }, // se + { x: rx + rw / 2, y: ry + rh }, // s + { x: rx, y: ry + rh }, // sw + { x: rx, y: ry + rh / 2 }, // w + ]; + this.ctx.fillStyle = '#ffffff'; + this.ctx.strokeStyle = '#000000'; + this.ctx.lineWidth = 1; + for (const h of handles) { + this.ctx.fillRect(h.x - half, h.y - half, handleSize, handleSize); + this.ctx.strokeRect(h.x - half, h.y - half, handleSize, handleSize); + } + this.ctx.restore(); + } + } + + private drawAction(action: DrawAction): void { + // Erase, crop and move records are undo sentinels; nothing to draw. + if (action.type === AnnotationTool.Eraser || action.type === AnnotationTool.Crop || action.type === AnnotationTool.Move) { + return; + } + this.ctx.save(); + const fillColor = action.fillColor ?? 'transparent'; + this.ctx.globalAlpha = action.opacity; + this.ctx.strokeStyle = action.strokeColor; + this.ctx.fillStyle = this.isTransparent(fillColor) ? action.strokeColor : fillColor; + this.ctx.lineWidth = action.lineWidth * this.scale; + this.ctx.lineCap = 'round'; + this.ctx.lineJoin = 'round'; + + switch (action.type) { + case AnnotationTool.Freehand: + if (action.points && action.points.length > 0) { + this.ctx.beginPath(); + this.ctx.moveTo(action.points[0].x * this.scale, action.points[0].y * this.scale); + for (let i = 1; i < action.points.length; i++) { + this.ctx.lineTo(action.points[i].x * this.scale, action.points[i].y * this.scale); + } + this.ctx.stroke(); + } + break; + + case AnnotationTool.Rectangle: + if (action.rect) { + if (!this.isTransparent(fillColor)) { + this.ctx.fillRect( + action.rect.x * this.scale, + action.rect.y * this.scale, + action.rect.width * this.scale, + action.rect.height * this.scale, + ); + } + this.ctx.strokeRect( + action.rect.x * this.scale, + action.rect.y * this.scale, + action.rect.width * this.scale, + action.rect.height * this.scale, + ); + } + break; + + case AnnotationTool.Ellipse: + if (action.ellipseRect) { + const r = action.ellipseRect; + const cx = (r.x + r.width / 2) * this.scale; + const cy = (r.y + r.height / 2) * this.scale; + const rx = Math.abs(r.width / 2) * this.scale; + const ry = Math.abs(r.height / 2) * this.scale; + this.ctx.beginPath(); + this.ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2); + if (!this.isTransparent(fillColor)) { + this.ctx.fill(); + } + this.ctx.stroke(); + } + break; + + case AnnotationTool.Arrow: + if (action.arrowStart && action.arrowEnd) { + this.drawArrow( + action.arrowStart.x * this.scale, + action.arrowStart.y * this.scale, + action.arrowEnd.x * this.scale, + action.arrowEnd.y * this.scale, + ); + } + break; + + case AnnotationTool.Text: + if (action.text && action.textPos) { + const fontSize = (action.fontSize || 16) * this.scale; + const fontFamily = action.fontFamily || 'sans-serif'; + const width = (action.textWidth ?? DEFAULT_TEXT_BOX_WIDTH) * this.scale; + this.ctx.font = `${fontSize}px ${fontFamily}`; + this.ctx.textBaseline = 'alphabetic'; + if (!this.isTransparent(fillColor)) { + const layout = this.measureWrappedText(action.text, width, fontSize, fontFamily); + this.ctx.fillRect( + action.textPos.x * this.scale, + action.textPos.y * this.scale - fontSize, + width, + Math.max(layout.height, fontSize * 1.2), + ); + } + this.ctx.fillStyle = action.strokeColor; + this.drawWrappedText(action.text, action.textPos.x * this.scale, action.textPos.y * this.scale, width, fontSize, fontFamily); + } + break; + } + + this.ctx.restore(); + } + + private drawTextEditState(): void { + if (!this.textEditState) { + return; + } + + const { pos, text, strokeColor, fillColor, opacity, fontFamily, fontSize, caretIndex, width, showBoxOutline } = this.textEditState; + const scaledFontSize = fontSize * this.scale; + const scaledWidth = width * this.scale; + this.ctx.save(); + this.ctx.globalAlpha = opacity; + this.ctx.fillStyle = strokeColor; + this.ctx.strokeStyle = strokeColor; + this.ctx.lineWidth = Math.max(1, this.scale); + this.ctx.font = `${scaledFontSize}px ${fontFamily}`; + this.ctx.textBaseline = 'alphabetic'; + if (!this.isTransparent(fillColor)) { + const layout = this.measureWrappedText(text, scaledWidth, scaledFontSize, fontFamily); + this.ctx.fillStyle = fillColor; + this.ctx.fillRect( + pos.x * this.scale, + pos.y * this.scale - scaledFontSize, + scaledWidth, + Math.max(layout.height, scaledFontSize * 1.2), + ); + this.ctx.fillStyle = strokeColor; + } + const layout = this.drawWrappedText(text, pos.x * this.scale, pos.y * this.scale, scaledWidth, scaledFontSize, fontFamily); + + if (showBoxOutline) { + this.ctx.setLineDash([4, 4]); + this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)'; + this.ctx.strokeRect( + pos.x * this.scale, + pos.y * this.scale - scaledFontSize, + scaledWidth, + Math.max(layout.height, scaledFontSize * 1.2), + ); + this.ctx.setLineDash([]); + } + + if (this.textCaretVisible) { + const caret = this.getTextCaretMetrics(text, caretIndex, scaledWidth, scaledFontSize, fontFamily); + const caretX = pos.x * this.scale + caret.x; + const baselineY = pos.y * this.scale + caret.baselineOffsetY; + this.ctx.beginPath(); + this.ctx.moveTo(caretX, baselineY - scaledFontSize); + this.ctx.lineTo(caretX, baselineY + Math.max(2, this.scale)); + this.ctx.stroke(); + } + this.ctx.restore(); + } + + private isTransparent(color: string): boolean { + return color === 'transparent'; + } + + private drawTextPlacementState(): void { + if (!this.textPlacementState) { + return; + } + const { start, current } = this.textPlacementState; + const dx = current.x - start.x; + const didDrag = Math.abs(dx) >= TEXT_DRAG_THRESHOLD; + if (!didDrag) { + return; + } + const x = Math.min(start.x, current.x); + const width = Math.max(1, Math.min(Math.abs(dx), this.getTextImageRight() - x)); + const y = (start.y - this.activeFontSize) * this.scale; + const height = this.activeFontSize * this.scale * 1.2; + this.ctx.save(); + this.ctx.setLineDash([4, 4]); + this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.7)'; + this.ctx.lineWidth = Math.max(1, this.scale); + this.ctx.strokeRect(x * this.scale, y, width * this.scale, height); + this.ctx.setLineDash([]); + this.ctx.restore(); + } + + private drawWrappedText(text: string, x: number, baselineY: number, maxWidth: number, fontSize: number, fontFamily: string): { width: number; height: number; lineHeight: number } { + const layout = this.measureWrappedText(text, maxWidth, fontSize, fontFamily); + const lineHeight = layout.lineHeight; + for (let i = 0; i < layout.lines.length; i++) { + const line = layout.lines[i]; + this.ctx.fillText(line.text, x, baselineY + i * lineHeight); + } + return { + width: layout.width, + height: layout.height, + lineHeight, + }; + } + + private getTextCaretMetrics(text: string, caretIndex: number, maxWidth: number, fontSize: number, fontFamily: string): { x: number; baselineOffsetY: number } { + const layout = this.measureWrappedText(text, maxWidth, fontSize, fontFamily); + const line = [...layout.lines].reverse().find(candidate => candidate.startIndex <= caretIndex) ?? layout.lines[0]; + const safeCaretIndex = Math.min(Math.max(caretIndex, line.startIndex), line.endIndex); + const beforeCaret = line.text.slice(0, safeCaretIndex - line.startIndex); + this.ctx.save(); + this.ctx.font = `${fontSize}px ${fontFamily}`; + const x = this.ctx.measureText(beforeCaret).width; + this.ctx.restore(); + return { + x, + baselineOffsetY: line.lineIndex * layout.lineHeight, + }; + } + + private measureWrappedText(text: string, maxWidth: number, fontSize: number, fontFamily: string): { lines: { text: string; startIndex: number; endIndex: number; lineIndex: number }[]; width: number; height: number; lineHeight: number } { + this.ctx.save(); + this.ctx.font = `${fontSize}px ${fontFamily}`; + const lineHeight = fontSize * 1.2; + const lines: { text: string; startIndex: number; endIndex: number; lineIndex: number }[] = []; + const paragraphs = text.split('\n'); + let globalIndex = 0; + let lineIndex = 0; + let maxLineWidth = 0; + + for (let p = 0; p < paragraphs.length; p++) { + const paragraph = paragraphs[p]; + const paragraphStart = globalIndex; + const paragraphEnd = paragraphStart + paragraph.length; + + if (paragraph.length === 0) { + lines.push({ text: '', startIndex: paragraphStart, endIndex: paragraphStart, lineIndex }); + lineIndex++; + } else { + let lineStart = paragraphStart; + while (lineStart < paragraphEnd) { + let bestEnd = lineStart + 1; + let lastWhitespaceBreak = -1; + for (let i = lineStart + 1; i <= paragraphEnd; i++) { + const candidate = text.slice(lineStart, i); + if (this.ctx.measureText(candidate).width <= maxWidth) { + bestEnd = i; + if (/\s/.test(text[i - 1])) { + lastWhitespaceBreak = i; + } + } else { + break; + } + } + + let lineEnd = bestEnd; + if (bestEnd < paragraphEnd && lastWhitespaceBreak > lineStart) { + lineEnd = lastWhitespaceBreak; + } + if (lineEnd <= lineStart) { + lineEnd = lineStart + 1; + } + + const rawLineText = text.slice(lineStart, lineEnd); + const lineText = rawLineText.replace(/\s+$/u, ''); + lines.push({ text: lineText, startIndex: lineStart, endIndex: lineEnd, lineIndex }); + maxLineWidth = Math.max(maxLineWidth, this.ctx.measureText(lineText).width); + lineIndex++; + + lineStart = lineEnd; + while (lineStart < paragraphEnd && /\s/u.test(text[lineStart])) { + lineStart++; + } + } + } + + globalIndex = paragraphEnd + 1; + } + + if (lines.length === 0) { + lines.push({ text: '', startIndex: 0, endIndex: 0, lineIndex: 0 }); + } + + if (maxLineWidth === 0) { + for (const line of lines) { + maxLineWidth = Math.max(maxLineWidth, this.ctx.measureText(line.text).width); + } + } + this.ctx.restore(); + return { + lines, + width: Math.max(maxLineWidth, maxWidth), + height: lines.length * lineHeight, + lineHeight, + }; + } + + private hitTest(pos: { x: number; y: number }): number { + for (let i = this.actions.length - 1; i >= 0; i--) { + if (this.isPointOnAction(pos, this.actions[i])) { + return i; + } + } + return -1; + } + + private isPointOnAction(pos: { x: number; y: number }, action: DrawAction): boolean { + const threshold = 8; + switch (action.type) { + case AnnotationTool.Freehand: + if (action.points) { + for (let i = 1; i < action.points.length; i++) { + if (this.pointToSegmentDist(pos, action.points[i - 1], action.points[i]) < threshold) { + return true; + } + } + } + return false; + case AnnotationTool.Rectangle: + if (action.rect) { + const r = action.rect; + const nx = Math.min(r.x, r.x + r.width); + const ny = Math.min(r.y, r.y + r.height); + const nw = Math.abs(r.width); + const nh = Math.abs(r.height); + return pos.x >= nx - threshold && pos.x <= nx + nw + threshold && + pos.y >= ny - threshold && pos.y <= ny + nh + threshold; + } + return false; + case AnnotationTool.Ellipse: + if (action.ellipseRect) { + const er = action.ellipseRect; + const cx = er.x + er.width / 2; + const cy = er.y + er.height / 2; + const rx = Math.abs(er.width / 2); + const ry = Math.abs(er.height / 2); + if (rx < 1 || ry < 1) { + return false; + } + // Normalized distance from center + const dx = (pos.x - cx) / rx; + const dy = (pos.y - cy) / ry; + const dist = Math.sqrt(dx * dx + dy * dy); + if (!this.isTransparent(action.fillColor ?? 'transparent')) { + return dist <= 1 + threshold / Math.min(rx, ry); + } + // Check if point is near the ellipse border (dist around 1) + const normalizedThreshold = threshold / Math.min(rx, ry); + return Math.abs(dist - 1) < normalizedThreshold; + } + return false; + case AnnotationTool.Arrow: + if (action.arrowStart && action.arrowEnd) { + return this.pointToSegmentDist(pos, action.arrowStart, action.arrowEnd) < threshold; + } + return false; + case AnnotationTool.Text: + if (action.text && action.textPos) { + const bounds = this.getActionBounds(action); + if (!bounds) { + return false; + } + return pos.x >= action.textPos.x - threshold && + pos.x <= bounds.x + bounds.width + threshold && + pos.y >= bounds.y - threshold && + pos.y <= bounds.y + bounds.height + threshold; + } + return false; + } + return false; + } + + private pointToSegmentDist(p: { x: number; y: number }, a: { x: number; y: number }, b: { x: number; y: number }): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const lengthSq = dx * dx + dy * dy; + if (lengthSq === 0) { + return Math.hypot(p.x - a.x, p.y - a.y); + } + let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq; + t = Math.max(0, Math.min(1, t)); + const projX = a.x + t * dx; + const projY = a.y + t * dy; + return Math.hypot(p.x - projX, p.y - projY); + } + + private moveAction(action: DrawAction, dx: number, dy: number): void { + switch (action.type) { + case AnnotationTool.Freehand: + if (action.points) { + for (const pt of action.points) { + pt.x += dx; + pt.y += dy; + } + } + break; + case AnnotationTool.Rectangle: + if (action.rect) { + action.rect.x += dx; + action.rect.y += dy; + } + break; + case AnnotationTool.Ellipse: + if (action.ellipseRect) { + action.ellipseRect.x += dx; + action.ellipseRect.y += dy; + } + break; + case AnnotationTool.Arrow: + if (action.arrowStart) { + action.arrowStart.x += dx; + action.arrowStart.y += dy; + } + if (action.arrowEnd) { + action.arrowEnd.x += dx; + action.arrowEnd.y += dy; + } + break; + case AnnotationTool.Text: + if (action.textPos) { + action.textPos.x += dx; + action.textPos.y += dy; + } + break; + } + } + + private drawSelectionHighlight(action: DrawAction): void { + this.ctx.save(); + this.ctx.strokeStyle = '#007acc'; + this.ctx.lineWidth = 1; + this.ctx.setLineDash([4, 4]); + const pad = 6; + const bounds = this.getActionBounds(action); + if (bounds) { + this.ctx.strokeRect( + (bounds.x - pad) * this.scale, + (bounds.y - pad) * this.scale, + (bounds.width + pad * 2) * this.scale, + (bounds.height + pad * 2) * this.scale, + ); + if (action.type === AnnotationTool.Text) { + const handleSize = 8; + const handleX = (bounds.x + bounds.width + pad) * this.scale; + const handleY = (bounds.y + bounds.height / 2) * this.scale; + this.ctx.fillStyle = '#007acc'; + this.ctx.fillRect(handleX - handleSize / 2, handleY - handleSize / 2, handleSize, handleSize); + } + } + this.ctx.setLineDash([]); + this.ctx.restore(); + } + + private isNearTextResizeHandle(pos: { x: number; y: number }, action: DrawAction): boolean { + if (action.type !== AnnotationTool.Text) { + return false; + } + const bounds = this.getActionBounds(action); + if (!bounds) { + return false; + } + const threshold = 8; + const handleX = bounds.x + bounds.width; + const handleY = bounds.y + bounds.height / 2; + return Math.abs(pos.x - handleX) <= threshold && Math.abs(pos.y - handleY) <= threshold * 2; + } + + private getActionBounds(action: DrawAction): { x: number; y: number; width: number; height: number } | null { + switch (action.type) { + case AnnotationTool.Freehand: + if (action.points && action.points.length > 0) { + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (const pt of action.points) { + minX = Math.min(minX, pt.x); + minY = Math.min(minY, pt.y); + maxX = Math.max(maxX, pt.x); + maxY = Math.max(maxY, pt.y); + } + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; + } + return null; + case AnnotationTool.Rectangle: + if (action.rect) { + const r = action.rect; + return { + x: Math.min(r.x, r.x + r.width), + y: Math.min(r.y, r.y + r.height), + width: Math.abs(r.width), + height: Math.abs(r.height), + }; + } + return null; + case AnnotationTool.Ellipse: + if (action.ellipseRect) { + const er = action.ellipseRect; + return { + x: Math.min(er.x, er.x + er.width), + y: Math.min(er.y, er.y + er.height), + width: Math.abs(er.width), + height: Math.abs(er.height), + }; + } + return null; + case AnnotationTool.Arrow: + if (action.arrowStart && action.arrowEnd) { + const minX = Math.min(action.arrowStart.x, action.arrowEnd.x); + const minY = Math.min(action.arrowStart.y, action.arrowEnd.y); + const maxX = Math.max(action.arrowStart.x, action.arrowEnd.x); + const maxY = Math.max(action.arrowStart.y, action.arrowEnd.y); + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; + } + return null; + case AnnotationTool.Text: + if (action.text && action.textPos) { + const fontSize = action.fontSize || 16; + const fontFamily = action.fontFamily || 'sans-serif'; + const textWidth = action.textWidth ?? DEFAULT_TEXT_BOX_WIDTH; + const layout = this.measureWrappedText(action.text, textWidth, fontSize, fontFamily); + return { + x: action.textPos.x, + y: action.textPos.y - fontSize, + width: textWidth, + height: layout.height, + }; + } + return null; + } + return null; + } + + private drawArrow(fromX: number, fromY: number, toX: number, toY: number): void { + const dx = toX - fromX; + const dy = toY - fromY; + const length = Math.hypot(dx, dy); + if (length === 0) { + return; + } + + const unitX = dx / length; + const unitY = dy / length; + const normalX = -unitY; + const normalY = unitX; + const lineWidth = this.ctx.lineWidth; + const headLength = Math.min(Math.max(12 * this.scale, lineWidth * 3), length); + const headWidth = Math.max(10 * this.scale, lineWidth * 2.5); + const baseX = toX - unitX * headLength; + const baseY = toY - unitY * headLength; + + this.ctx.beginPath(); + this.ctx.moveTo(fromX, fromY); + this.ctx.lineTo(baseX, baseY); + this.ctx.stroke(); + + this.ctx.beginPath(); + this.ctx.moveTo(toX, toY); + this.ctx.lineTo(baseX + normalX * headWidth / 2, baseY + normalY * headWidth / 2); + this.ctx.lineTo(baseX - normalX * headWidth / 2, baseY - normalY * headWidth / 2); + this.ctx.closePath(); + this.ctx.fillStyle = this.ctx.strokeStyle; + this.ctx.fill(); + } + + private flushPendingZoom(): void { + const pending = this.pendingZoom; + this.pendingZoom = null; + if (!pending) { + return; + } + const minScale = this.getFitScale(); + const maxScale = 8; + const desiredScale = this.scale * pending.factor; + const newScale = Math.max(minScale, Math.min(maxScale, desiredScale)); + if (newScale === this.scale) { + return; + } + // Cursor-anchored zoom: keep the image pixel under the cursor under the + // cursor after zoom. Clamp the cursor's image-space coord to the actual + // image extent so an off-image cursor (in breathing-room padding) still + // pivots on the nearest real image pixel. + const halfImgW = (this.imageWidth * this.scale) / 2; + const halfImgH = (this.imageHeight * this.scale) / 2; + const anchorCx = this.panX + Math.max(-halfImgW, Math.min(halfImgW, pending.cx - this.panX)); + const anchorCy = this.panY + Math.max(-halfImgH, Math.min(halfImgH, pending.cy - this.panY)); + const r = newScale / this.scale; + this.panX = anchorCx * (1 - r) + this.panX * r; + this.panY = anchorCy * (1 - r) + this.panY * r; + this.scale = newScale; + this.hasUserZoomed = true; + // Deliberately do NOT call clampPan() here. With rAF-coalesced wheel events + // a single flush can produce a large zoom factor (e.g. trackpad pinch firing + // 10+ events in one frame -> r ~= 2-3); the cursor-anchored pan that needs to + // be applied at large r can exceed the strict clamp, and clamping then + // drifts the cursor away from the anchor pixel. The cursor anchor itself + // ensures at least one image pixel stays visible (the one under the cursor), + // so unbounded zoom pan is safe. + // When zooming back out to fit, snap pan to centered so the breathing-room + // layout looks symmetric instead of carrying over any accumulated offset. + if (newScale === minScale) { + this.panX = 0; + this.panY = 0; + } + this.sizeCanvas(); + this.canvas.style.transform = `translate(${this.panX}px, ${this.panY}px)`; + this.redraw(); + } + + private getFitScale(): number { + const container = this.canvas.parentElement; + if (!container || !this.imageWidth || !this.imageHeight) { + return 1; + } + const maxWidth = Math.max(1, container.clientWidth - CANVAS_BREATHING_ROOM * 2); + const maxHeight = Math.max(1, container.clientHeight - CANVAS_BREATHING_ROOM * 2); + return Math.min(maxWidth / this.imageWidth, maxHeight / this.imageHeight, 1); + } + + private clampPan(): void { + const container = this.canvas.parentElement; + if (!container) { + return; + } + const imgW = this.imageWidth * this.scale; + const imgH = this.imageHeight * this.scale; + const cW = container.clientWidth; + const cH = container.clientHeight; + // Manual-pan clamp: image edge can't travel past container edge in either + // direction. When image is smaller than container (fit / zoomed-out), the + // bound shrinks symmetrically toward 0 so pan can shift the image around + // inside the container without sliding off either edge. When zoomed in, + // allows full pan within the zoomed content. + const maxPanX = Math.abs(cW - imgW) / 2; + const maxPanY = Math.abs(cH - imgH) / 2; + this.panX = Math.max(-maxPanX, Math.min(maxPanX, this.panX)); + this.panY = Math.max(-maxPanY, Math.min(maxPanY, this.panY)); + } + + private compositeToDataUrl(): string { + // Create a final canvas at full resolution + const finalCanvas = mainWindow.document.createElement('canvas'); + finalCanvas.width = this.imageWidth; + finalCanvas.height = this.imageHeight; + const ctx = finalCanvas.getContext('2d')!; + + // Draw background image + if (this.imageElement) { + ctx.drawImage(this.imageElement, 0, 0, this.imageWidth, this.imageHeight); + } + + // Replay annotations at full resolution. Actions are in original-image coords; + // translate by -currentCrop offset so they land correctly on the cropped output. + const savedScale = this.scale; + this.scale = 1; + const savedCtx = this.ctx; + this.ctx = ctx; + + const offX = this.currentCrop?.x ?? 0; + const offY = this.currentCrop?.y ?? 0; + ctx.save(); + ctx.translate(-offX, -offY); + for (const action of this.actions) { + this.drawAction(action); + } + ctx.restore(); + + this.ctx = savedCtx; + this.scale = savedScale; + + return finalCanvas.toDataURL('image/png'); + } + + /** + * Ends a markup and keeps what changed: fires `onDidSave` when something changed, and `onDidCancel` when nothing + * did. Done and Escape end it as well. + */ + finish(): void { + if (this.disposed) { + return; + } + this.cancelTextPlacement(); + this.commitTextEdit(); + if (this.cropMode) { + this.cancelCrop(); + } + if (this.revision === this.savedRevision) { + this._onDidCancel.fire(); + } else { + const annotated = this.actions.length > 0 || this.currentCrop !== null; + this._onDidSave.fire({ + dataUrl: annotated ? this.compositeToDataUrl() : this.screenshot.dataUrl, + width: this.imageWidth, + height: this.imageHeight, + state: this.captureState(), + annotated, + }); + } + this.dispose(); + } + + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + if (this.pendingZoomRaf) { + getWindow(this.canvas).cancelAnimationFrame(this.pendingZoomRaf); + this.pendingZoomRaf = 0; + this.pendingZoom = null; + } + this.cancelTextPlacement(); + // Whoever opened the editor restores focus, so closing it must not move focus itself. + this.cleanupTextEditor(false); + this.container.remove(); + this.toolOptionsDisposables.dispose(); + this.disposables.dispose(); + this._onDidSave.dispose(); + this._onDidCancel.dispose(); + } +} diff --git a/src/vs/workbench/contrib/screenshotTool/browser/screenshotSelection.ts b/src/vs/workbench/contrib/screenshotTool/browser/screenshotSelection.ts new file mode 100644 index 000000000000..54f88bd51db3 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/screenshotSelection.ts @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, addDisposableListener, append, EventType, getWindow } from '../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js'; +import { DeferredPromise } from '../../../../base/common/async.js'; +import { KeyCode } from '../../../../base/common/keyCodes.js'; +import { Disposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { clamp } from '../../../../base/common/numbers.js'; +import { localize } from '../../../../nls.js'; +import './media/screenshotTool.css'; + +export interface IScreenshotRect { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +/** What the user selected, in CSS pixels relative to the window. */ +export type ScreenshotSelection = + /** All of the window. */ + | { readonly kind: 'all' } + | { readonly kind: 'area'; readonly rect: IScreenshotRect }; + +/** Pointer travel, in CSS pixels, below which a press counts as a click rather than a drag. */ +export const SCREENSHOT_DRAG_THRESHOLD = 4; + +/** Resolves a press and release into a click, which selects all of `bounds`, or an area clamped to `bounds`. */ +export function resolveScreenshotSelection(start: { x: number; y: number }, end: { x: number; y: number }, bounds: IScreenshotRect): ScreenshotSelection { + if (Math.abs(end.x - start.x) < SCREENSHOT_DRAG_THRESHOLD && Math.abs(end.y - start.y) < SCREENSHOT_DRAG_THRESHOLD) { + return { kind: 'all' }; + } + const rect = getSelectionRect(start, end, bounds); + return rect.width < 1 || rect.height < 1 ? { kind: 'all' } : { kind: 'area', rect }; +} + +function getSelectionRect(start: { x: number; y: number }, end: { x: number; y: number }, bounds: IScreenshotRect): IScreenshotRect { + const left = clamp(Math.min(start.x, end.x), bounds.x, bounds.x + bounds.width); + const top = clamp(Math.min(start.y, end.y), bounds.y, bounds.y + bounds.height); + const right = clamp(Math.max(start.x, end.x), bounds.x, bounds.x + bounds.width); + const bottom = clamp(Math.max(start.y, end.y), bounds.y, bounds.y + bounds.height); + return { x: left, y: top, width: right - left, height: bottom - top }; +} + +export interface IScreenshotSelectionOverlayOptions { + /** Whether a key press should reach the workbench, such as the one that opens accessibility help. */ + readonly shouldForwardKey: (event: StandardKeyboardEvent) => boolean; +} + +/** + * A layer above the window that lets the user select a capture: a click or Enter selects all of the window, a drag + * selects an area, and Escape cancels. The window keeps running underneath. + */ +export class ScreenshotSelectionOverlay extends Disposable { + + static readonly CLASS_NAME = 'screenshot-tool-overlay'; + + private readonly element: HTMLElement; + private readonly selectionElement: HTMLElement; + private readonly result = new DeferredPromise(); + private drag: { readonly pointerId: number; readonly start: { x: number; y: number }; dragging: boolean } | undefined; + + constructor(container: HTMLElement, private readonly options: IScreenshotSelectionOverlayOptions) { + super(); + this.element = append(container, $(`.${ScreenshotSelectionOverlay.CLASS_NAME}`)); + this.element.tabIndex = -1; + this.element.setAttribute('role', 'dialog'); + this.element.setAttribute('aria-modal', 'true'); + this.element.setAttribute('aria-label', localize('screenshotTool', "Screenshot")); + this._register(toDisposable(() => this.element.remove())); + + const hint = append(this.element, $('.screenshot-tool-hint')); + hint.textContent = getScreenshotSelectionHint(); + hint.setAttribute('aria-hidden', 'true'); + this.selectionElement = append(this.element, $('.screenshot-tool-selection')); + + this._register(addDisposableListener(this.element, EventType.POINTER_DOWN, e => this.onPointerDown(e))); + this._register(addDisposableListener(this.element, EventType.POINTER_MOVE, e => this.onPointerMove(e))); + this._register(addDisposableListener(this.element, EventType.POINTER_UP, e => this.onPointerUp(e))); + this._register(addDisposableListener(this.element, 'pointercancel', () => this.resetDrag())); + this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, e => e.preventDefault())); + this._register(addDisposableListener(this.element, EventType.KEY_DOWN, e => this.onKeyDown(e))); + this._register(addDisposableListener(this.element, EventType.KEY_UP, e => this.onKeyUp(e))); + this._register(toDisposable(() => this.complete(undefined))); + } + + /** Resolves with the selection, or `undefined` when the user cancels. */ + get selection(): Promise { + return this.result.p; + } + + focus(): void { + this.element.focus(); + } + + cancel(): void { + this.complete(undefined); + } + + private complete(selection: ScreenshotSelection | undefined): void { + if (!this.result.isSettled) { + void this.result.complete(selection); + } + } + + private get bounds(): IScreenshotRect { + const targetWindow = getWindow(this.element); + return { x: 0, y: 0, width: targetWindow.innerWidth, height: targetWindow.innerHeight }; + } + + private onPointerDown(e: PointerEvent): void { + e.preventDefault(); + if (e.button !== 0 || this.drag) { + return; + } + this.drag = { pointerId: e.pointerId, start: { x: e.clientX, y: e.clientY }, dragging: false }; + try { + // The capturing element's cursor shows while the pointer is down. + this.element.setPointerCapture(e.pointerId); + } catch { + // Only pointers that are down can be captured, so synthetic events cannot. + } + } + + private onPointerMove(e: PointerEvent): void { + if (!this.drag || e.pointerId !== this.drag.pointerId) { + return; + } + const end = { x: e.clientX, y: e.clientY }; + const selection = resolveScreenshotSelection(this.drag.start, end, this.bounds); + this.drag.dragging ||= selection.kind === 'area'; + if (this.drag.dragging) { + this.showSelection(getSelectionRect(this.drag.start, end, this.bounds)); + } + } + + private onPointerUp(e: PointerEvent): void { + if (!this.drag || e.pointerId !== this.drag.pointerId) { + return; + } + e.preventDefault(); + const { start } = this.drag; + this.resetDrag(); + this.complete(resolveScreenshotSelection(start, { x: e.clientX, y: e.clientY }, this.bounds)); + } + + private resetDrag(): void { + this.drag = undefined; + this.showSelection(undefined); + } + + private onKeyDown(e: KeyboardEvent): void { + const event = new StandardKeyboardEvent(e); + if (event.equals(KeyCode.Escape)) { + event.preventDefault(); + event.stopPropagation(); + this.complete(undefined); + } else if (event.equals(KeyCode.Enter)) { + event.preventDefault(); + event.stopPropagation(); + this.complete({ kind: 'all' }); + } else if (!this.options.shouldForwardKey(event)) { + // Workbench shortcuts would open UI underneath the overlay and take focus from it. + event.preventDefault(); + event.stopPropagation(); + } + } + + private onKeyUp(e: KeyboardEvent): void { + if (!this.options.shouldForwardKey(new StandardKeyboardEvent(e))) { + e.stopPropagation(); + } + } + + private showSelection(rect: IScreenshotRect | undefined): void { + setBounds(this.selectionElement, rect); + this.element.classList.toggle('selecting', !!rect); + } +} + +/** The instructions of the selection overlay, shown at its bottom and announced when it opens. */ +export function getScreenshotSelectionHint(): string { + return localize('screenshotSelectionHint', "Click to capture the window, or drag to capture an area. Press Enter to capture the window or Escape to cancel."); +} + +function setBounds(element: HTMLElement, rect: IScreenshotRect | undefined): void { + element.classList.toggle('visible', !!rect); + if (rect) { + element.style.left = `${rect.x}px`; + element.style.top = `${rect.y}px`; + element.style.width = `${rect.width}px`; + element.style.height = `${rect.height}px`; + } +} diff --git a/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.contribution.ts b/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.contribution.ts new file mode 100644 index 000000000000..cc94d15aa453 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.contribution.ts @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../nls.js'; +import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType } from '../../../../platform/accessibility/browser/accessibleView.js'; +import { AccessibleViewRegistry, IAccessibleViewImplementation } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js'; +import { IScreenshotToolService, ScreenshotToolActiveContext } from './screenshotTool.js'; +import { ScreenshotToolService } from './screenshotToolService.js'; + +registerSingleton(IScreenshotToolService, ScreenshotToolService, InstantiationType.Delayed); + +class ScreenshotToolAccessibilityHelp implements IAccessibleViewImplementation { + readonly type = AccessibleViewType.Help; + readonly priority = 110; + readonly name = 'screenshotTool'; + readonly when = ScreenshotToolActiveContext; + + getProvider(accessor: ServicesAccessor): AccessibleContentProvider { + const screenshotToolService = accessor.get(IScreenshotToolService); + return new AccessibleContentProvider( + AccessibleViewProviderId.ScreenshotTool, + { type: AccessibleViewType.Help }, + () => [ + localize('screenshotTool.accessibilityHelp.overview', "You are in the screenshot tool."), + localize('screenshotTool.accessibilityHelp.capture', "Press Enter to capture the whole window, or Escape to cancel. With a pointer, click to capture the window, or drag to capture an area."), + localize('screenshotTool.accessibilityHelp.attach', "The screenshot is attached right away. To mark up an attached screenshot, focus it and press Enter. In chat, this opens the Images Preview, where Mark Up starts the markup of an image in the input."), + localize('screenshotTool.accessibilityHelp.markUp', "While marking up, use Tab and Shift+Tab to move between the drawing tools, Undo, Redo, and Done. Select Done or press Escape to apply your changes."), + ].join('\n'), + () => screenshotToolService.focus(), + AccessibilityVerbositySettingId.ScreenshotTool, + ); + } +} + +AccessibleViewRegistry.register(new ScreenshotToolAccessibilityHelp()); diff --git a/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.ts b/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.ts new file mode 100644 index 000000000000..65a6c97a141f --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/screenshotTool.ts @@ -0,0 +1,168 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $ } from '../../../../base/browser/dom.js'; +import { CodeWindow } from '../../../../base/browser/window.js'; +import { decodeBase64, encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Event } from '../../../../base/common/event.js'; +import { IDisposable } from '../../../../base/common/lifecycle.js'; +import { localize } from '../../../../nls.js'; +import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { IImageCarouselMarkUp } from '../../imageCarousel/browser/imageCarouselTypes.js'; +import { IAnnotationEditorState } from './screenshotAnnotation.js'; + +/** True while the screenshot tool lets the user select a capture or mark up a screenshot. */ +export const ScreenshotToolActiveContext = new RawContextKey('screenshotToolActive', false, localize('screenshotToolActive', "Whether the screenshot tool is capturing or marking up a screenshot")); + +export const IScreenshotToolService = createDecorator('screenshotToolService'); + +/** A screenshot entry point, as reported in telemetry. */ +export const enum ScreenshotToolEntryPoint { + ChatAddContext = 'chatAddContext', + IssueReporter = 'issueReporter', + BrowserScreenshot = 'browserScreenshot', + BrowserAreaScreenshot = 'browserAreaScreenshot', + BrowserFullPageScreenshot = 'browserFullPageScreenshot', + /** A command or the Add Context item of chat that attach a screenshot of the window of another app. */ + ChatAppWindow = 'chatAppWindow', +} + +/** What a screenshot shows; `none` when it was cancelled or failed before anything was captured. */ +export type ScreenshotToolMode = 'window' | 'area' | 'page' | 'fullPage' | 'appWindow' | 'none'; + +export type ScreenshotToolOutcome = 'attached' | 'cancelled' | 'failed'; + +/** Where an attached screenshot was edited, as reported in telemetry. */ +export const enum ScreenshotToolSurface { + Chat = 'chat', + IssueReporter = 'issueReporter', +} + +export interface IScreenshotToolImage { + /** A `data:` URL of an image, such as a PNG or JPEG. */ + readonly dataUrl: string; + readonly width: number; + readonly height: number; +} + +/** A capture, which entry points attach right away. */ +export interface IScreenshotToolCapture { + readonly kind: 'captured'; + readonly mode: ScreenshotToolMode; + readonly image: IScreenshotToolImage; +} + +export type ScreenshotToolResult = IScreenshotToolCapture | { readonly kind: 'cancelled' | 'failed'; readonly mode: ScreenshotToolMode }; + +/** An attached screenshot that can be edited. */ +export interface IScreenshotToolEditable { + /** The capture without annotations. */ + readonly original: IScreenshotToolImage; + /** The annotations of earlier edits, which the edit dialog restores with their undo history. */ + readonly annotationState: IAnnotationEditorState | undefined; +} + +/** An attached screenshot after an edit. */ +export interface IScreenshotToolEdit extends IScreenshotToolEditable { + /** The screenshot to attach: the original with its annotations, or the original alone when it has none. */ + readonly image: IScreenshotToolImage; + readonly annotated: boolean; +} + +/** The markup of a screenshot, see {@link IScreenshotToolService.markUp}. */ +export interface IScreenshotToolMarkUp extends IDisposable { + /** Resolves once the markup ends, with the edited screenshot, or `undefined` when nothing changed. */ + readonly result: Promise; + focus(): void; + /** Ends the markup and keeps its changes, like its Done button does. */ + finish(): void; +} + +export interface IScreenshotToolService { + readonly _serviceBrand: undefined; + + /** Fires when the tool starts or stops letting the user capture in a window, or mark up a screenshot there. */ + readonly onDidChangeActive: Event<{ readonly targetWindow: CodeWindow; readonly active: boolean }>; + + /** + * Whether the tool can capture here: desktop windows can capture themselves, while the web would ask the user to pick + * a screen, so entry points there keep their own capture. + */ + readonly isSupported: boolean; + + /** Lets the user click or press Enter to capture the window, or drag to capture an area. */ + capture(targetWindow: CodeWindow, token?: CancellationToken): Promise; + + /** + * Captures the whole window, as the user sees it, without letting the user select. With `afterRepaint`, it first + * lets the window repaint, so UI that just closed is not captured. + */ + captureWindow(targetWindow: CodeWindow, options?: { readonly afterRepaint?: boolean }): Promise; + + /** + * Opens an attached screenshot in the Images Preview to mark it up, where Done applies the changes and closes it. + * Resolves with the edited screenshot once it closes, or `undefined` when nothing changed. `name` names an image + * that is not a screenshot, such as an image file. + */ + edit(screenshot: IScreenshotToolEditable, surface: ScreenshotToolSurface, name?: string): Promise; + + /** + * Shows the markup of a screenshot in `container`, such as the Images Preview's. Escape and Done end it, as does + * `finish`, which keeps its changes. A screenshot that is still loading shows once it has loaded. + */ + markUp(container: HTMLElement, screenshot: IScreenshotToolEditable | Promise, surface: ScreenshotToolSurface): IScreenshotToolMarkUp; + + /** + * Remembers a screenshot attached to chat, so that it can be edited while it is attached. It is remembered for that + * attachment only, not for others with the same id, such as the same image attached elsewhere or attached again. + */ + registerEditableAttachment(attachment: object, screenshot: IScreenshotToolEditable): void; + + /** Returns a screenshot attached to chat that can be edited, see {@link registerEditableAttachment}. */ + getEditableAttachment(attachment: object): IScreenshotToolEditable | undefined; + + /** Moves focus back to the screenshot tool while it is active, or to the latest markup. */ + focus(): void; + + /** Reports how an entry point ended, where the tool is supported. */ + logCapture(event: IScreenshotToolCaptureEvent): void; +} + +/** Creates a captured image from its bytes. */ +export async function createScreenshotToolImage(data: VSBuffer, mimeType: string): Promise { + const dataUrl = `data:${mimeType};base64,${encodeBase64(data)}`; + const image = $('img'); + image.src = dataUrl; + await image.decode(); + return { dataUrl, width: image.naturalWidth, height: image.naturalHeight }; +} + +/** Returns the bytes and MIME type of a captured image. */ +export function getScreenshotToolImageData(image: IScreenshotToolImage): { readonly data: VSBuffer; readonly mimeType: string } { + const match = /^data:(?[^;,]+)[^,]*,(?.*)$/.exec(image.dataUrl); + return { + data: decodeBase64(match?.groups?.data ?? ''), + mimeType: match?.groups?.mimeType ?? 'image/png', + }; +} + +/** Lets the Images Preview show a markup, and the image that it changed. */ +export function toImageCarouselMarkUp(markUp: IScreenshotToolMarkUp): IImageCarouselMarkUp { + return { + result: markUp.result.then(edit => edit && getScreenshotToolImageData(edit.image)), + focus: () => markUp.focus(), + finish: () => markUp.finish(), + dispose: () => markUp.dispose(), + }; +} + +export interface IScreenshotToolCaptureEvent { + readonly entryPoint: ScreenshotToolEntryPoint; + readonly outcome: ScreenshotToolOutcome; + readonly mode: ScreenshotToolMode; + readonly durationMs: number; +} diff --git a/src/vs/workbench/contrib/screenshotTool/browser/screenshotToolService.ts b/src/vs/workbench/contrib/screenshotTool/browser/screenshotToolService.ts new file mode 100644 index 000000000000..77a50b4000fe --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/browser/screenshotToolService.ts @@ -0,0 +1,437 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, addDisposableListener, EventType, getActiveWindow, getWindow, isHTMLElement, onDidUnregisterWindow, onWillUnregisterWindow } from '../../../../base/browser/dom.js'; +import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js'; +import { CodeWindow, mainWindow } from '../../../../base/browser/window.js'; +import { DeferredPromise, isThenable, timeout } from '../../../../base/common/async.js'; +import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { LRUCache } from '../../../../base/common/map.js'; +import { isNative } from '../../../../base/common/platform.js'; +import { StopWatch } from '../../../../base/common/stopwatch.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { localize } from '../../../../nls.js'; +import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IContextKey, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { ResultKind } from '../../../../platform/keybinding/common/keybindingResolver.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; +import { IEditorService } from '../../../services/editor/common/editorService.js'; +import { IHostService } from '../../../services/host/browser/host.js'; +import { IWorkbenchLayoutService } from '../../../services/layout/browser/layoutService.js'; +import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js'; +import { AccessibilityCommandId } from '../../accessibility/common/accessibilityCommands.js'; +import { ImageCarouselEditorInput } from '../../imageCarousel/browser/imageCarouselEditorInput.js'; +import { ScreenshotAnnotationEditor } from './screenshotAnnotation.js'; +import { getScreenshotSelectionHint, IScreenshotRect, ScreenshotSelection, ScreenshotSelectionOverlay } from './screenshotSelection.js'; +import { getScreenshotToolImageData, IScreenshotToolCaptureEvent, IScreenshotToolEdit, IScreenshotToolEditable, IScreenshotToolImage, IScreenshotToolMarkUp, IScreenshotToolService, ScreenshotToolActiveContext, ScreenshotToolMode, ScreenshotToolResult, ScreenshotToolSurface, toImageCarouselMarkUp } from './screenshotTool.js'; + +/** How long the window gets to repaint, without the overlay or UI that just closed, before it is captured. */ +const REPAINT_DELAY = 100; + +/** How many screenshots attached to chat stay editable, which bounds the memory their originals take. */ +const MAX_EDITABLE_ATTACHMENTS = 10; + +interface ISession extends IDisposable { + surface: { focus(): void } | undefined; +} + +type ScreenshotToolCaptureClassification = { + owner: 'Giuspepe'; + comment: 'Reports how a screenshot entry point ended.'; + entryPoint: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The entry point that started the screenshot: chat Add Context, the issue reporter, an Integrated Browser screenshot action, or a chat command or Add Context item that captures the window of another app.' }; + outcome: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the screenshot was attached, cancelled, or failed.' }; + mode: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'What was captured: the window, an area, a browser page, a full browser page, or the window of another app, or none when nothing was captured.' }; + durationMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Milliseconds from running the entry point to its outcome, including the time the user spent selecting.' }; +}; + +type ScreenshotToolEditEvent = { + surface: ScreenshotToolSurface; + changed: boolean; + annotated: boolean; + durationMs: number; +}; + +type ScreenshotToolEditClassification = { + owner: 'Giuspepe'; + comment: 'Reports how marking up an attached image with the screenshot tool ended.'; + surface: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Where the marked up image was attached: chat or the issue reporter.' }; + changed: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the image changed during the markup.' }; + annotated: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the image has annotations or a crop when the markup ends.' }; + durationMs: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Milliseconds the markup was shown.' }; +}; + +export class ScreenshotToolService extends Disposable implements IScreenshotToolService { + + declare readonly _serviceBrand: undefined; + + private readonly sessions = new Map(); + private readonly markUps = new Set(); + /** How many captures and markups each window shows, which overlap when a markup's host lets the user capture. */ + private readonly activeSurfaces = new Map(); + private readonly editableAttachments = new LRUCache(MAX_EDITABLE_ATTACHMENTS); + private readonly activeContext: IContextKey; + + private readonly _onDidChangeActive = this._register(new Emitter<{ readonly targetWindow: CodeWindow; readonly active: boolean }>()); + readonly onDidChangeActive = this._onDidChangeActive.event; + + constructor( + @IConfigurationService private readonly configurationService: IConfigurationService, + @ITelemetryService private readonly telemetryService: ITelemetryService, + @IHostService private readonly hostService: IHostService, + @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, + @IAccessibilityService private readonly accessibilityService: IAccessibilityService, + @IKeybindingService private readonly keybindingService: IKeybindingService, + @IContextKeyService contextKeyService: IContextKeyService, + @ILogService private readonly logService: ILogService, + @IEditorService private readonly editorService: IEditorService, + ) { + super(); + this.activeContext = ScreenshotToolActiveContext.bindTo(contextKeyService); + } + + /** Desktop windows can capture themselves, while the web would ask the user to pick a screen. */ + get isSupported(): boolean { + return isNative; + } + + logCapture(event: IScreenshotToolCaptureEvent): void { + if (!this.isSupported) { + return; + } + this.telemetryService.publicLog2('screenshotTool.capture', { + entryPoint: event.entryPoint, + outcome: event.outcome, + mode: event.mode, + durationMs: Math.round(event.durationMs), + }); + } + + registerEditableAttachment(attachment: object, screenshot: IScreenshotToolEditable): void { + this.editableAttachments.set(attachment, screenshot); + } + + getEditableAttachment(attachment: object): IScreenshotToolEditable | undefined { + return this.editableAttachments.get(attachment); + } + + focus(): void { + const sessions = [...this.sessions]; + const [, session] = sessions.find(([targetWindow]) => targetWindow.document.hasFocus()) ?? sessions.at(-1) ?? []; + if (session?.surface) { + session.surface.focus(); + } else { + [...this.markUps].at(-1)?.focus(); + } + } + + async capture(targetWindow: CodeWindow, token = CancellationToken.None): Promise { + const session = this.startSession(targetWindow); + if (!session) { + return { kind: 'cancelled', mode: 'none' }; + } + let mode: ScreenshotToolMode = 'none'; + try { + const selection = await this.select(targetWindow, session, token); + if (!selection || token.isCancellationRequested) { + this.accessibilityService.status(localize('screenshotCancelled', "Screenshot cancelled.")); + return { kind: 'cancelled', mode }; + } + let image: IScreenshotToolImage | undefined; + if (selection.kind === 'area') { + mode = 'area'; + image = await this.captureWindowArea(targetWindow, selection.rect, true); + } else { + mode = 'window'; + image = await this.captureWindowArea(targetWindow, undefined, true); + } + if (!image) { + this.accessibilityService.alert(localize('screenshotFailed', "The screenshot could not be captured.")); + return { kind: 'failed', mode }; + } + if (token.isCancellationRequested) { + return { kind: 'cancelled', mode }; + } + this.accessibilityService.status(localize('screenshotCaptured', "Screenshot captured.")); + return { kind: 'captured', mode, image }; + } catch (error) { + this.logService.error('[ScreenshotTool] Capturing a screenshot failed:', error); + this.accessibilityService.alert(localize('screenshotFailed', "The screenshot could not be captured.")); + return { kind: 'failed', mode }; + } finally { + session.dispose(); + } + } + + async captureWindow(targetWindow: CodeWindow, options?: { readonly afterRepaint?: boolean }): Promise { + try { + return await this.captureWindowArea(targetWindow, undefined, !!options?.afterRepaint); + } catch (error) { + this.logService.error('[ScreenshotTool] Capturing the window failed:', error); + return undefined; + } + } + + async edit(screenshot: IScreenshotToolEditable, surface: ScreenshotToolSurface, name?: string): Promise { + // The Images Preview opens as a modal editor in the main window, which comes to the front, and focus goes back to a reporter in its own window afterwards. + const previousWindow = getActiveWindow(); + const previousFocus = previousWindow.document.activeElement; + const outcome = new DeferredPromise(); + const { data, mimeType } = getScreenshotToolImageData(screenshot.original); + const input = new ImageCarouselEditorInput({ + id: generateUuid(), + title: name ? localize('editImage', "Edit Image") : localize('editScreenshot', "Edit Screenshot"), + sections: [{ + title: '', + images: [{ + id: generateUuid(), + name: name ?? localize('screenshot', "Screenshot"), + mimeType, + data, + markUp: container => { + const markUp = this.markUp(container, screenshot, surface); + void markUp.result.then(edit => outcome.complete(edit)); + return toImageCarouselMarkUp(markUp); + }, + }], + }], + }, 0, true); + const closed = Event.toPromise(input.onWillDispose); + try { + if (previousWindow !== mainWindow) { + await this.hostService.focus(mainWindow); + } + if (!await this.editorService.openEditor(input, { pinned: true })) { + input.dispose(); + return undefined; + } + // The markup ends when the editor closes, unless the editor closed before it began. + void closed.then(() => outcome.complete(undefined)); + const edit = await outcome.p; + await closed; + return edit; + } catch (error) { + this.logService.error('[ScreenshotTool] Editing a screenshot failed:', error); + input.dispose(); + return undefined; + } finally { + if (previousWindow !== mainWindow && !previousWindow.closed) { + await this.hostService.focus(previousWindow); + if (isHTMLElement(previousFocus) && previousFocus.isConnected) { + previousFocus.focus(); + } + } + } + } + + markUp(container: HTMLElement, screenshot: IScreenshotToolEditable | Promise, surface: ScreenshotToolSurface): IScreenshotToolMarkUp { + const store = new DisposableStore(); + const result = new DeferredPromise(); + const stopWatch = StopWatch.create(false); + let editor: ScreenshotAnnotationEditor | undefined; + let editable: IScreenshotToolEditable | undefined; + let focusRequested = false; + const markUp: IScreenshotToolMarkUp = { + result: result.p, + focus: () => { + focusRequested = true; + editor?.focus(); + }, + finish: () => { + if (editor) { + editor.finish(); + } else { + void result.complete(undefined); + } + }, + dispose: () => { + void result.complete(undefined); + store.dispose(); + }, + }; + const targetWindow = getWindow(container); + this.markUps.add(markUp); + this.setActive(targetWindow, true); + store.add(toDisposable(() => { + this.markUps.delete(markUp); + this.setActive(targetWindow, false); + })); + + const show = (loaded: IScreenshotToolEditable) => { + if (result.isSettled) { + return; + } + editable = loaded; + const annotationEditor = editor = new ScreenshotAnnotationEditor(loaded.original, container, loaded.annotationState); + store.add(toDisposable(() => annotationEditor.dispose())); + for (const type of [EventType.KEY_DOWN, EventType.KEY_UP]) { + // Workbench shortcuts would act on what is underneath the markup and take focus from it. + store.add(addDisposableListener(annotationEditor.element, type, (e: KeyboardEvent) => { + if (!this.isAccessibilityHelpKey(new StandardKeyboardEvent(e))) { + e.stopPropagation(); + } + })); + } + store.add(annotationEditor.onDidSave(saved => void result.complete({ + original: loaded.original, + annotationState: saved.state, + image: saved.annotated ? { dataUrl: saved.dataUrl, width: saved.width, height: saved.height } : loaded.original, + annotated: saved.annotated, + }))); + store.add(annotationEditor.onDidCancel(() => void result.complete(undefined))); + if (focusRequested) { + annotationEditor.focus(); + } + }; + if (isThenable(screenshot)) { + screenshot.then(show, error => { + this.logService.error('[ScreenshotTool] Loading a screenshot to mark up failed:', error); + void result.complete(undefined); + }); + } else { + show(screenshot); + } + + void result.p.then(edit => { + store.dispose(); + this.telemetryService.publicLog2('screenshotTool.edit', { + surface, + changed: !!edit, + annotated: edit ? edit.annotated : !!editable?.annotationState?.actions.length || !!editable?.annotationState?.crop, + durationMs: Math.round(stopWatch.elapsed()), + }); + }); + return markUp; + } + + private setActive(targetWindow: CodeWindow, active: boolean): void { + const count = (this.activeSurfaces.get(targetWindow) ?? 0) + (active ? 1 : -1); + if (count > 0) { + this.activeSurfaces.set(targetWindow, count); + } else { + this.activeSurfaces.delete(targetWindow); + } + this.activeContext.set(this.activeSurfaces.size > 0); + if (count === (active ? 1 : 0)) { + this._onDidChangeActive.fire({ targetWindow, active }); + } + } + + private startSession(targetWindow: CodeWindow): ISession | undefined { + if (this.sessions.has(targetWindow)) { + return undefined; + } + // Keyboard input, such as Escape to cancel, only reaches the focused window. + const previousWindow = getActiveWindow(); + const previousFocus = new Set([targetWindow.document.activeElement, previousWindow.document.activeElement]); + if (previousWindow !== targetWindow) { + void this.hostService.focus(targetWindow); + } + const session: ISession = { + surface: undefined, + dispose: () => { + if (this.sessions.get(targetWindow) !== session) { + return; + } + this.sessions.delete(targetWindow); + this.setActive(targetWindow, false); + if (previousWindow !== targetWindow && !previousWindow.closed) { + void this.hostService.focus(previousWindow); + } + for (const element of previousFocus) { + if (isHTMLElement(element) && element.isConnected) { + element.focus(); + } + } + } + }; + this.sessions.set(targetWindow, session); + this.setActive(targetWindow, true); + return session; + } + + private async select(targetWindow: CodeWindow, session: ISession, token: CancellationToken): Promise { + const store = new DisposableStore(); + try { + const overlay = store.add(new ScreenshotSelectionOverlay(this.layoutService.getContainer(targetWindow), { + shouldForwardKey: event => this.isAccessibilityHelpKey(event), + })); + store.add(token.onCancellationRequested(() => overlay.cancel())); + // A window that closes takes the overlay with it, so the selection ends with the window. + store.add(Event.filter(Event.any(onWillUnregisterWindow, onDidUnregisterWindow), window => window === targetWindow)(() => overlay.cancel())); + session.surface = overlay; + store.add(toDisposable(() => session.surface = undefined)); + overlay.focus(); + this.accessibilityService.status(this.getSelectionAnnouncement()); + return await overlay.selection; + } finally { + store.dispose(); + } + } + + private isAccessibilityHelpKey(event: StandardKeyboardEvent): boolean { + const result = this.keybindingService.softDispatch(event, event.target); + return result.kind === ResultKind.KbFound && result.commandId === AccessibilityCommandId.OpenAccessibilityHelp; + } + + private getSelectionAnnouncement(): string { + const message = localize('screenshotModeAnnouncement', "Screenshot mode. {0}", getScreenshotSelectionHint()); + if (!this.configurationService.getValue(AccessibilityVerbositySettingId.ScreenshotTool)) { + return message; + } + const keybinding = this.keybindingService.lookupKeybinding(AccessibilityCommandId.OpenAccessibilityHelp)?.getAriaLabel(); + return keybinding + ? localize('screenshotModeAnnouncementWithHelp', "{0} Use {1} for accessibility help.", message, keybinding) + : message; + } + + /** + * Captures the window or an area of it, as the user sees it. Native content, such as a browser page, shows as the + * placeholder that the window shows for it. + */ + private async captureWindowArea(targetWindow: CodeWindow, area: IScreenshotRect | undefined, afterRepaint: boolean): Promise { + if (afterRepaint) { + await timeout(REPAINT_DELAY); + } + const screenshot = await this.hostService.getScreenshot(undefined, targetWindow); + if (!screenshot?.byteLength) { + return undefined; + } + const windowDataUrl = toDataUrl(screenshot, 'image/jpeg'); + const windowImage = await decodeImage(windowDataUrl); + if (!area) { + return { dataUrl: windowDataUrl, width: windowImage.naturalWidth, height: windowImage.naturalHeight }; + } + + // The capture has device pixels, which can differ from CSS pixels by the zoom level and display scale. + const scaleX = windowImage.naturalWidth / targetWindow.innerWidth; + const scaleY = windowImage.naturalHeight / targetWindow.innerHeight; + const canvas = $('canvas'); + canvas.width = Math.max(1, Math.round(area.width * scaleX)); + canvas.height = Math.max(1, Math.round(area.height * scaleY)); + const context = canvas.getContext('2d'); + if (!context) { + return undefined; + } + context.drawImage(windowImage, area.x * scaleX, area.y * scaleY, area.width * scaleX, area.height * scaleY, 0, 0, canvas.width, canvas.height); + return { dataUrl: canvas.toDataURL('image/png'), width: canvas.width, height: canvas.height }; + } +} + +function toDataUrl(data: VSBuffer, mimeType: string): string { + return `data:${mimeType};base64,${encodeBase64(data)}`; +} + +async function decodeImage(dataUrl: string): Promise { + const image = $('img'); + image.src = dataUrl; + await image.decode(); + return image; +} diff --git a/src/vs/workbench/contrib/screenshotTool/electron-browser/appWindowScreenshot.ts b/src/vs/workbench/contrib/screenshotTool/electron-browser/appWindowScreenshot.ts new file mode 100644 index 000000000000..b2b83b0e3818 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/electron-browser/appWindowScreenshot.ts @@ -0,0 +1,356 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getZoomFactor } from '../../../../base/browser/browser.js'; +import { $, getComputedStyle, getWindow, scheduleAtNextAnimationFrame } from '../../../../base/browser/dom.js'; +import { raceTimeout } from '../../../../base/common/async.js'; +import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { readImageDimensions } from '../../../../base/common/image.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { isMacintosh } from '../../../../base/common/platform.js'; +import { URI } from '../../../../base/common/uri.js'; +import { localize } from '../../../../nls.js'; +import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { INativeAppWindow, INativeAppWindows, INativeHostService } from '../../../../platform/native/common/native.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { IScreenshotToolImage } from '../browser/screenshotTool.js'; + +export const IAppWindowScreenshotService = createDecorator('appWindowScreenshotService'); + +/** How a capture found the window of another app: the frontmost one, or one that the user picked in a list or in the system's picker. */ +export type AppWindowScreenshotTarget = 'frontmost' | 'picked' | 'systemPicked'; + +export type AppWindowScreenshotResult = + | { readonly kind: 'captured'; readonly target: AppWindowScreenshotTarget; readonly window: INativeAppWindow; readonly image: IScreenshotToolImage } + /** The user cancelled picking the window. */ + | { readonly kind: 'cancelled'; readonly target: AppWindowScreenshotTarget } + /** No other app shows a window. */ + | { readonly kind: 'noWindow'; readonly target: AppWindowScreenshotTarget } + /** macOS needs the Screen Recording permission, see {@link IAppWindowScreenshotService.requestPermission}. */ + | { readonly kind: 'permissionRequired'; readonly target: AppWindowScreenshotTarget } + | { readonly kind: 'failed'; readonly target: AppWindowScreenshotTarget; readonly window: INativeAppWindow | undefined }; + +export interface IAppWindowScreenshotOptions { + /** Lets the user pick the window in a list, instead of capturing the frontmost window of another app. */ + readonly pick?: boolean; +} + +/** Whether capturing the windows of other apps has the permission that it needs. */ +export type AppWindowScreenshotPermission = + | 'granted' + /** macOS needs the Screen Recording permission, which the user can turn on in System Settings. */ + | 'notGranted' + /** The Screen Recording permission is restricted, such as by parental controls or by the organization that manages the Mac. */ + | 'restricted' + /** The platform needs no permission. */ + | 'notRequired'; + +/** + * Captures the windows of other apps, such as a browser or a simulator that runs the app that the user builds. + */ +export interface IAppWindowScreenshotService { + readonly _serviceBrand: undefined; + + /** Whether the user has captured the window of another app, in any window of VS Code or of the Agents window. */ + readonly hasCaptured: boolean; + + /** Fires when {@link hasCaptured} changes, including when another window captured. */ + readonly onDidChangeHasCaptured: Event; + + /** Returns whether capturing has the permission that it needs, without asking for it. */ + getPermission(): Promise; + + /** + * Asks for the Screen Recording permission on macOS, which lists VS Code under Screen Recording in System Settings, + * and opens System Settings there, where the user turns it on. macOS also prompts the first time. + */ + requestPermission(): Promise; + + /** + * Captures the window of another app as it is shown. Only call it when the user asked for it, as it asks for the + * Screen Recording permission on macOS the first time, and shows the system's window picker in Wayland sessions. + * + * Where the platform tells where the window is, the window flashes on screen, then turns into its screenshot, which + * stays above it, so that VS Code can come to the front without covering it. That stays until + * {@link endCaptureFeedback}, which the caller must call however the capture ended. + */ + capture(options?: IAppWindowScreenshotOptions): Promise; + + /** + * Ends the feedback of {@link capture}. Given the screenshot and the element that it goes to, the screenshot flies + * into the element, when it is small, like its attachment in the chat input, or else into a thumbnail at the top left + * of the element, then fades as the element shows. Without them, the flash just fades. Resolves once the screenshot + * covers the element, so that the element can show, or once the feedback is gone, at once when there is none. + */ + endCaptureFeedback(destination?: { readonly element: HTMLElement; readonly image: IScreenshotToolImage }): Promise; +} + +/** Names a window of another app by its title. */ +export function getAppWindowLabel(window: INativeAppWindow): string { + return window.title.trim() || localize('untitledAppWindow', "Untitled Window"); +} + +/** Lets a capture keep the resolution of windows on large displays, which Chromium would otherwise scale down to 2880×1800. */ +const MAX_CAPTURE_SIZE = 8192; + +/** How long a capture waits for the first frame of the window. */ +const FRAME_TIMEOUT = 5000; + +/** The height of an element that the screenshot flies into whole. A bigger one takes a thumbnail this high, wider by half. */ +const FEEDBACK_THUMBNAIL_HEIGHT = 32; + +/** The space between a big element and the thumbnail that the screenshot flies into, and the corner radius of the thumbnail. */ +const FEEDBACK_THUMBNAIL_INSET = 6; +const FEEDBACK_THUMBNAIL_RADIUS = 4; + +/** How long the feedback waits for the window to lay out the element that the screenshot flies into. */ +const FEEDBACK_LAYOUT_TIMEOUT = 250; + +const MAC_SCREEN_RECORDING_SETTINGS_URL = 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'; + +/** Remembers that the user captured the window of another app, for VS Code and the Agents window alike. */ +const CAPTURED_STORAGE_KEY = 'chat.appWindowScreenshots.captured'; + +/** Electron's constraints to capture a desktop media source, which the DOM typings don't describe. */ +type DesktopMediaTrackConstraints = MediaTrackConstraints & { + readonly mandatory: { + readonly chromeMediaSource: 'desktop'; + readonly chromeMediaSourceId: string; + readonly maxWidth: number; + readonly maxHeight: number; + }; +}; + +interface IAppWindowPickItem extends IQuickPickItem { + readonly window: INativeAppWindow; +} + +export class AppWindowScreenshotService extends Disposable implements IAppWindowScreenshotService { + + declare readonly _serviceBrand: undefined; + + private readonly _onDidChangeHasCaptured = this._register(new Emitter()); + readonly onDidChangeHasCaptured = this._onDidChangeHasCaptured.event; + + get hasCaptured(): boolean { + return this.storageService.getBoolean(CAPTURED_STORAGE_KEY, StorageScope.APPLICATION_SHARED, false); + } + + /** The feedback of a capture, until the caller ends it, and whether it shows the screenshot. */ + private feedback: { revealed: boolean } | undefined; + + constructor( + @INativeHostService private readonly nativeHostService: INativeHostService, + @IQuickInputService private readonly quickInputService: IQuickInputService, + @ILogService private readonly logService: ILogService, + @IStorageService private readonly storageService: IStorageService, + @IAccessibilityService private readonly accessibilityService: IAccessibilityService, + ) { + super(); + this._register(this.storageService.onDidChangeValue(StorageScope.APPLICATION_SHARED, CAPTURED_STORAGE_KEY, this._store)(() => this._onDidChangeHasCaptured.fire())); + } + + async getPermission(): Promise { + if (!isMacintosh) { + return 'notRequired'; + } + switch (await this.nativeHostService.getMediaAccessStatus('screen')) { + case 'granted': return 'granted'; + case 'restricted': return 'restricted'; + default: return 'notGranted'; + } + } + + async requestPermission(): Promise { + if (!isMacintosh) { + return; + } + try { + await this.nativeHostService.requestScreenCaptureAccess(); + } catch (error) { + // Without the permission, the request rejects after macOS listed VS Code, and prompted the first time. + this.logService.trace('[AppWindowScreenshot] The Screen Recording request was rejected:', error); + } + await this.nativeHostService.openExternal(MAC_SCREEN_RECORDING_SETTINGS_URL); + } + + async capture(options: IAppWindowScreenshotOptions = {}): Promise { + let target: AppWindowScreenshotTarget = options.pick ? 'picked' : 'frontmost'; + let windows: INativeAppWindows; + try { + windows = await this.nativeHostService.getAppWindows(); + if (windows.kind === 'systemPicker') { + target = 'systemPicked'; + } + if (windows.kind !== 'windows') { + windows = await this.nativeHostService.getAppWindows({ interactive: true }); + } + } catch (error) { + if (target === 'systemPicked') { + // Electron rejects when the user dismisses the system's picker, which it doesn't tell apart from a failure. + this.logService.trace('[AppWindowScreenshot] The system picker returned no window:', error); + return { kind: 'cancelled', target }; + } + this.logService.error('[AppWindowScreenshot] Listing the windows of other apps failed:', error); + return { kind: 'failed', target, window: undefined }; + } + if (windows.kind === 'permissionRequired') { + return { kind: 'permissionRequired', target }; + } + if (windows.kind !== 'windows') { + return { kind: 'failed', target, window: undefined }; + } + let window: INativeAppWindow | undefined; + if (target === 'systemPicked') { + // The system's picker lists the window that the user picked, or none when they cancelled. + window = windows.windows[0]; + if (!window) { + return { kind: 'cancelled', target }; + } + } else if (!windows.windows.length) { + return { kind: 'noWindow', target }; + } else if (options.pick) { + window = await this.pick(windows.windows); + if (!window) { + return { kind: 'cancelled', target }; + } + } else { + window = windows.windows[0]; + } + + const feedback = window.bounds ? { revealed: false } : undefined; + this.feedback = feedback; + + try { + let image = await this.captureScreenshot(window, !!feedback); + if (image && feedback) { + feedback.revealed = true; + } + image ??= await this.captureWindow(window); + if (!image) { + return { kind: 'failed', target, window }; + } + if (!this.hasCaptured) { + this.storageService.store(CAPTURED_STORAGE_KEY, true, StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE); + } + return { kind: 'captured', target, window, image }; + } catch (error) { + // macOS can revoke Screen Recording while the user picks the window. + const permission = await this.getPermission(); + if (permission === 'notGranted' || permission === 'restricted') { + return { kind: 'permissionRequired', target }; + } + this.logService.error('[AppWindowScreenshot] Capturing a window failed:', error); + return { kind: 'failed', target, window }; + } + } + + async endCaptureFeedback(destination?: { readonly element: HTMLElement; readonly image: IScreenshotToolImage }): Promise { + const feedback = this.feedback; + if (!feedback) { + return; + } + this.feedback = undefined; + if (!destination) { + return this.nativeHostService.endAppWindowCaptureFeedback(); + } + // What changed lays out in the frames that follow, like the chat input, which grows with an attachment. A window + // behind other windows may not render, hence the timeout. + const targetWindow = getWindow(destination.element); + await raceTimeout(new Promise(resolve => scheduleAtNextAnimationFrame(targetWindow, () => scheduleAtNextAnimationFrame(targetWindow, resolve))), FEEDBACK_LAYOUT_TIMEOUT); + const rect = destination.element.getBoundingClientRect(); + if (!rect.width || !rect.height) { + return this.nativeHostService.endAppWindowCaptureFeedback(); + } + const whole = rect.height <= FEEDBACK_THUMBNAIL_HEIGHT; + const height = Math.max(Math.min(FEEDBACK_THUMBNAIL_HEIGHT, rect.height - 2 * FEEDBACK_THUMBNAIL_INSET), 1); + const box = whole + ? { x: rect.left, y: rect.top, width: rect.width, height: rect.height } + : { x: rect.left + FEEDBACK_THUMBNAIL_INSET, y: rect.top + FEEDBACK_THUMBNAIL_INSET, width: Math.max(Math.min(height * 1.5, rect.width - 2 * FEEDBACK_THUMBNAIL_INSET), 1), height }; + const radius = whole ? parseFloat(getComputedStyle(destination.element).borderTopLeftRadius) || 0 : FEEDBACK_THUMBNAIL_RADIUS; + // The overlay that shows the feedback measures in device-independent pixels, which zoom in the window scales. + const zoom = getZoomFactor(targetWindow); + return this.nativeHostService.endAppWindowCaptureFeedback({ + image: feedback.revealed ? undefined : destination.image.dataUrl, + destination: { x: box.x * zoom, y: box.y * zoom, width: box.width * zoom, height: box.height * zoom }, + radius: radius * zoom, + }, { targetWindowId: targetWindow.vscodeWindowId }); + } + + private async pick(windows: readonly INativeAppWindow[]): Promise { + const picked = await this.quickInputService.pick(windows.map(window => ({ + label: getAppWindowLabel(window), + iconPath: window.iconDataUrl ? { dark: URI.parse(window.iconDataUrl) } : undefined, + window, + })), { + placeHolder: localize('pickAppWindow', "Select the window of the app to capture"), + }); + return picked?.window; + } + + /** + * Captures the window in a single screenshot, where the platform can, which the feedback then shows above the window. + * Returns `undefined` where it can't. + */ + private async captureScreenshot(window: INativeAppWindow, feedback: boolean): Promise { + let data: VSBuffer | undefined; + try { + data = await this.nativeHostService.captureAppWindow(window, feedback ? { feedback: { reduceMotion: this.accessibilityService.isMotionReduced() } } : undefined); + } catch (error) { + this.logService.error('[AppWindowScreenshot] Capturing a screenshot of a window failed:', error); + return undefined; + } + const size = data && readImageDimensions(data); + return data && size ? { dataUrl: `data:image/png;base64,${encodeBase64(data)}`, width: size.width, height: size.height } : undefined; + } + + /** Captures one frame of the window, at its full resolution. */ + private async captureWindow(window: INativeAppWindow): Promise { + const video: DesktopMediaTrackConstraints = { + mandatory: { + chromeMediaSource: 'desktop', + chromeMediaSourceId: window.sourceId, + maxWidth: MAX_CAPTURE_SIZE, + maxHeight: MAX_CAPTURE_SIZE, + }, + }; + const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video }); + try { + const [track] = stream.getVideoTracks(); + if (!track) { + return undefined; + } + const grab = new ImageCapture(track).grabFrame(); + // A frame that arrives after the timeout holds the full image until it is closed. + const frame = await raceTimeout(grab, FRAME_TIMEOUT, () => { + void grab.then(late => late.close(), () => { }); + }); + if (!frame) { + return undefined; + } + try { + const canvas = $('canvas'); + canvas.width = frame.width; + canvas.height = frame.height; + const context = canvas.getContext('2d'); + if (!context) { + return undefined; + } + context.drawImage(frame, 0, 0); + return { dataUrl: canvas.toDataURL('image/png'), width: frame.width, height: frame.height }; + } finally { + frame.close(); + } + } finally { + for (const track of stream.getTracks()) { + track.stop(); + } + } + } +} diff --git a/src/vs/workbench/contrib/screenshotTool/electron-browser/screenshotTool.contribution.ts b/src/vs/workbench/contrib/screenshotTool/electron-browser/screenshotTool.contribution.ts new file mode 100644 index 000000000000..c2a6d5d99f9b --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/electron-browser/screenshotTool.contribution.ts @@ -0,0 +1,9 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { AppWindowScreenshotService, IAppWindowScreenshotService } from './appWindowScreenshot.js'; + +registerSingleton(IAppWindowScreenshotService, AppWindowScreenshotService, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolService.test.ts b/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolService.test.ts new file mode 100644 index 000000000000..55120b32ae25 --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolService.test.ts @@ -0,0 +1,330 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $, registerWindow } from '../../../../../base/browser/dom.js'; +import { CodeWindow, mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { decodeBase64, VSBuffer } from '../../../../../base/common/buffer.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IEditorPane } from '../../../../common/editor.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IHostService } from '../../../../services/host/browser/host.js'; +import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; +import { ImageCarouselEditorInput } from '../../../imageCarousel/browser/imageCarouselEditorInput.js'; +import { createScreenshotToolImage, getScreenshotToolImageData, ScreenshotToolEntryPoint, ScreenshotToolResult, ScreenshotToolSurface } from '../../browser/screenshotTool.js'; +import { resolveScreenshotSelection } from '../../browser/screenshotSelection.js'; +import { ScreenshotToolService } from '../../browser/screenshotToolService.js'; +import { TestScreenshotToolTelemetryService } from './screenshotToolTestUtils.js'; + +suite('ScreenshotTool', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('a press without travel selects everything and a drag selects an area clamped to the bounds', () => { + const windowBounds = { x: 0, y: 0, width: 800, height: 600 }; + const offsetBounds = { x: 100, y: 100, width: 400, height: 300 }; + assert.deepStrictEqual([ + resolveScreenshotSelection({ x: 100, y: 100 }, { x: 103, y: 97 }, windowBounds), + resolveScreenshotSelection({ x: 300, y: 200 }, { x: 100, y: 120 }, windowBounds), + resolveScreenshotSelection({ x: 700, y: 500 }, { x: 900, y: 700 }, windowBounds), + resolveScreenshotSelection({ x: 790, y: 590 }, { x: 900, y: 700 }, windowBounds), + resolveScreenshotSelection({ x: 450, y: 350 }, { x: 20, y: 700 }, offsetBounds), + ], [ + { kind: 'all' }, + { kind: 'area', rect: { x: 100, y: 120, width: 200, height: 80 } }, + { kind: 'area', rect: { x: 700, y: 500, width: 100, height: 100 } }, + { kind: 'area', rect: { x: 790, y: 590, width: 10, height: 10 } }, + { kind: 'area', rect: { x: 100, y: 350, width: 350, height: 50 } }, + ]); + }); + + suite('service', () => { + + class TestAccessibility extends TestAccessibilityService { + readonly messages: string[] = []; + override status(message: string): void { this.messages.push(message); } + override alert(message: string): void { this.messages.push(message); } + } + + function createImage(width: number, height: number, color: string): VSBuffer { + const canvas = $('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d')!; + context.fillStyle = color; + context.fillRect(0, 0, width, height); + return decodeBase64(canvas.toDataURL('image/png').split(',')[1]); + } + + function createService(options: { supported?: boolean; editorService?: Partial } = {}) { + const container = $('div'); + mainWindow.document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + const telemetry = new TestScreenshotToolTelemetryService(); + const accessibility = new TestAccessibility(); + const captures: (Window | undefined)[] = []; + const focusedWindows: Window[] = []; + const windowImage = createImage(mainWindow.innerWidth, mainWindow.innerHeight, '#0000ff'); + const service = store.add(new class extends ScreenshotToolService { + override get isSupported(): boolean { return options.supported ?? true; } + }( + new TestConfigurationService(), + telemetry, + new class extends mock() { + override async getScreenshot(_rect?: unknown, targetWindow?: Window) { + captures.push(targetWindow); + return windowImage; + } + override async focus(targetWindow: Window) { + focusedWindows.push(targetWindow); + } + }(), + new class extends mock() { + override getContainer() { return container; } + }(), + accessibility, + new MockKeybindingService(), + new MockContextKeyService(), + new NullLogService(), + upcastPartial(options.editorService ?? {}), + )); + return { service, telemetry, accessibility, container, captures, focusedWindows }; + } + + function getOverlay(container: HTMLElement): HTMLElement { + return container.querySelector('.screenshot-tool-overlay')!; + } + + function pointer(element: HTMLElement, type: string, x: number, y: number): void { + element.dispatchEvent(new PointerEvent(type, { clientX: x, clientY: y, button: 0, pointerId: 1, bubbles: true, cancelable: true })); + } + + function key(element: HTMLElement, keyName: string, keyCode: number): void { + element.dispatchEvent(new KeyboardEvent('keydown', { key: keyName, keyCode, bubbles: true, cancelable: true })); + } + + function summarize(result: ScreenshotToolResult) { + return result.kind === 'captured' + ? { kind: result.kind, mode: result.mode, size: `${result.image.width}x${result.image.height}` } + : result; + } + + /** Waits until a markup has loaded its screenshot, which sizes its canvas. */ + async function waitForMarkUp(container: HTMLElement): Promise { + const loaded = new DeferredPromise(); + const check = () => { + const markUp = container.querySelector('.screenshot-annotation-editor'); + if (markUp?.querySelector('canvas')?.style.width) { + void loaded.complete(markUp); + } + }; + const observer = new MutationObserver(check); + observer.observe(container, { attributes: true, attributeFilter: ['style'], childList: true, subtree: true }); + check(); + try { + return await loaded.p; + } finally { + observer.disconnect(); + } + } + + test('reports how an entry point ended only where the tool is supported', () => { + const reports = [true, false].map(supported => { + const { service, telemetry } = createService({ supported }); + service.logCapture({ entryPoint: ScreenshotToolEntryPoint.ChatAddContext, outcome: 'attached', mode: 'window', durationMs: 5 }); + return { supported: service.isSupported, captures: telemetry.captures }; + }); + assert.deepStrictEqual(reports, [ + { supported: true, captures: [{ entryPoint: 'chatAddContext', outcome: 'attached', mode: 'window' }] }, + { supported: false, captures: [] }, + ]); + }); + + test('a click captures the target window, which is attached without another step', async () => { + const { service, container, captures, accessibility } = createService(); + const result = service.capture(mainWindow); + const overlay = getOverlay(container); + pointer(overlay, 'pointerdown', 20, 20); + pointer(overlay, 'pointerup', 22, 21); + assert.deepStrictEqual({ result: summarize(await result), captures, overlay: overlay.isConnected, editors: container.querySelectorAll('.screenshot-annotation-editor').length, announced: accessibility.messages.at(-1) }, { + result: { kind: 'captured', mode: 'window', size: `${mainWindow.innerWidth}x${mainWindow.innerHeight}` }, + captures: [mainWindow], + overlay: false, + editors: 0, + announced: 'Screenshot captured.', + }); + }); + + test('a drag captures that area of the window', async () => { + const { service, container, captures } = createService(); + const result = service.capture(mainWindow); + const overlay = getOverlay(container); + pointer(overlay, 'pointerdown', 50, 50); + pointer(overlay, 'pointermove', 150, 120); + pointer(overlay, 'pointerup', 150, 120); + assert.deepStrictEqual({ result: summarize(await result), captures }, { + result: { kind: 'captured', mode: 'area', size: '100x70' }, + captures: [mainWindow], + }); + }); + + test('Enter captures the window and focus returns', async () => { + const { service, container } = createService(); + const button = $('button'); + container.appendChild(button); + button.focus(); + const result = service.capture(mainWindow); + key(getOverlay(container), 'Enter', 13); + assert.deepStrictEqual({ result: summarize(await result), focused: mainWindow.document.activeElement === button }, { + result: { kind: 'captured', mode: 'window', size: `${mainWindow.innerWidth}x${mainWindow.innerHeight}` }, + focused: true, + }); + }); + + test('Escape cancels before capturing and announces it', async () => { + const { service, container, accessibility, captures } = createService(); + const result = service.capture(mainWindow); + const overlay = getOverlay(container); + const focusedOverlay = mainWindow.document.activeElement === overlay; + key(overlay, 'Escape', 27); + assert.deepStrictEqual({ result: await result, focusedOverlay, captures, overlay: overlay.isConnected, messages: accessibility.messages }, { + result: { kind: 'cancelled', mode: 'none' }, + focusedOverlay: true, + captures: [], + overlay: false, + messages: ['Screenshot mode. Click to capture the window, or drag to capture an area. Press Enter to capture the window or Escape to cancel.', 'Screenshot cancelled.'], + }); + }); + + test('started from another window, the tool focuses its target window and then returns focus', async () => { + const { service, container, focusedWindows } = createService(); + const button = $('button'); + container.appendChild(button); + button.focus(); + const targetWindow = upcastPartial({ document: mainWindow.document.implementation.createHTMLDocument() }); + const result = service.capture(targetWindow); + const focusedDuringSession = [...focusedWindows]; + key(getOverlay(container), 'Escape', 27); + assert.deepStrictEqual({ result: await result, focusedDuringSession, focusedWindows, focused: mainWindow.document.activeElement === button }, { + result: { kind: 'cancelled', mode: 'none' }, + focusedDuringSession: [targetWindow], + focusedWindows: [targetWindow, mainWindow], + focused: true, + }); + }); + + test('cancels when its target window closes, which ends its session', async () => { + const { service, container } = createService(); + const targetWindow = upcastPartial({ + vscodeWindowId: 1000, + document: mainWindow.document.implementation.createHTMLDocument(), + addEventListener: () => { }, + removeEventListener: () => { }, + }); + const registration = registerWindow(targetWindow); + const active: boolean[] = []; + store.add(service.onDidChangeActive(event => active.push(event.active))); + const result = service.capture(targetWindow); + const overlay = getOverlay(container); + registration.dispose(); + assert.deepStrictEqual({ result: await result, overlay: overlay.isConnected, active }, { + result: { kind: 'cancelled', mode: 'none' }, + overlay: false, + active: [true, false], + }); + }); + + test('a markup keeps its changes when it ends, and the next one restores them', async () => { + const { service, container, telemetry } = createService(); + const active: boolean[] = []; + store.add(service.onDidChangeActive(event => active.push(event.active))); + const original = await createScreenshotToolImage(createImage(40, 30, '#00ff00'), 'image/png'); + const first = store.add(service.markUp(container, { original, annotationState: undefined }, ScreenshotToolSurface.Chat)); + const markUp = await waitForMarkUp(container); + const hint = mainWindow.document.getElementById(markUp.getAttribute('aria-describedby')!)?.textContent; + const labels = [...markUp.querySelectorAll('.tool-btn, .monaco-button')].map(element => element.getAttribute('aria-label') ?? element.textContent); + markUp.querySelector('.crop-btn')!.click(); + [...markUp.querySelectorAll('.monaco-button')].find(element => element.textContent === 'Apply')!.click(); + key(markUp, 'Escape', 27); + const edit = await first.result; + + // Done without changes keeps the screenshot as it is. + const second = store.add(service.markUp(container, Promise.resolve(edit!), ScreenshotToolSurface.Chat)); + [...(await waitForMarkUp(container)).querySelectorAll('.monaco-button')].find(element => element.textContent === 'Done')!.click(); + assert.deepStrictEqual({ + label: markUp.getAttribute('aria-label'), + hint, + labels, + edit: edit && { annotated: edit.annotated, size: `${edit.image.width}x${edit.image.height}`, actions: edit.annotationState?.actions.length, original: edit.original === original }, + unchanged: await second.result, + open: container.querySelectorAll('.screenshot-annotation-editor').length, + // Like captures, markups let the issue reporter hide its floating bar. + active, + edits: telemetry.edits, + }, { + label: 'Mark Up Image', + hint: 'Draw on the image or crop it, then select Done to apply your changes.', + labels: ['Select / Move', 'Pan', 'Crop', 'Draw', 'Rectangle', 'Ellipse', 'Arrow', 'Eraser', 'Text', 'Undo', 'Redo', 'Cancel', 'Apply', 'Done'], + edit: { annotated: true, size: '40x30', actions: 1, original: true }, + unchanged: undefined, + open: 0, + active: [true, false, true, false], + edits: [ + { surface: 'chat', changed: true, annotated: true }, + { surface: 'chat', changed: false, annotated: true }, + ], + }); + }); + + test('edits a screenshot in the Images Preview, which resolves once the preview closes', async () => { + const opened: ImageCarouselEditorInput[] = []; + const { service, container, telemetry } = createService({ + editorService: { + openEditor: async (input: unknown) => { + opened.push(input as ImageCarouselEditorInput); + return upcastPartial({}); + }, + } as Partial, + }); + const original = await createScreenshotToolImage(createImage(40, 30, '#00ff00'), 'image/png'); + let resolved = false; + const edited = service.edit({ original, annotationState: undefined }, ScreenshotToolSurface.IssueReporter).then(edit => { + resolved = true; + return edit; + }); + const [input] = opened; + const [image] = input.collection.sections[0].images; + const preview = image.markUp!(container); + const markUp = await waitForMarkUp(container); + markUp.querySelector('.crop-btn')!.click(); + [...markUp.querySelectorAll('.monaco-button')].find(element => element.textContent === 'Apply')!.click(); + [...markUp.querySelectorAll('.monaco-button')].find(element => element.textContent === 'Done')!.click(); + const shown = await preview.result; + const resolvedBeforeClose = resolved; + input.dispose(); + const edit = await edited; + preview.dispose(); + assert.deepStrictEqual({ + input: { title: input.getName(), markUpOnly: input.markUpOnly, image: { name: image.name, mimeType: image.mimeType, size: image.data?.byteLength === getScreenshotToolImageData(original).data.byteLength } }, + shown: shown && { mimeType: shown.mimeType, matchesEdit: shown.data.byteLength === getScreenshotToolImageData(edit!.image).data.byteLength }, + resolvedBeforeClose, + edit: edit && { annotated: edit.annotated, original: edit.original === original }, + edits: telemetry.edits, + }, { + input: { title: 'Edit Screenshot', markUpOnly: true, image: { name: 'Screenshot', mimeType: 'image/png', size: true } }, + shown: { mimeType: 'image/png', matchesEdit: true }, + resolvedBeforeClose: false, + edit: { annotated: true, original: true }, + edits: [{ surface: 'issueReporter', changed: true, annotated: true }], + }); + }); + }); +}); diff --git a/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolTestUtils.ts b/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolTestUtils.ts new file mode 100644 index 000000000000..4340f109c7db --- /dev/null +++ b/src/vs/workbench/contrib/screenshotTool/test/browser/screenshotToolTestUtils.ts @@ -0,0 +1,108 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CodeWindow } from '../../../../../base/browser/window.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { NullTelemetryServiceShape } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IHostService } from '../../../../services/host/browser/host.js'; +import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; +import { IScreenshotToolCaptureEvent, IScreenshotToolEdit, IScreenshotToolEditable, IScreenshotToolImage, ScreenshotToolResult, ScreenshotToolSurface } from '../../browser/screenshotTool.js'; +import { ScreenshotToolService } from '../../browser/screenshotToolService.js'; + +/** Records screenshot tool events. */ +export class TestScreenshotToolTelemetryService extends NullTelemetryServiceShape { + readonly captures: Omit[] = []; + readonly edits: object[] = []; + private readonly _onDidLogCapture = new Emitter(); + /** Fires after an entry point reported its outcome, which is the last thing it does. */ + readonly onDidLogCapture = this._onDidLogCapture.event; + + override publicLog2(eventName?: string, data?: object): void { + if (eventName === 'screenshotTool.capture' && data) { + const { durationMs, ...capture } = data as IScreenshotToolCaptureEvent; + if (typeof durationMs === 'number' && durationMs >= 0) { + this.captures.push(capture); + } + this._onDidLogCapture.fire(); + } else if (eventName === 'screenshotTool.edit' && data) { + const { durationMs, ...edit } = data as { durationMs: number }; + if (typeof durationMs === 'number' && durationMs >= 0) { + this.edits.push(edit); + } + } + } +} + +/** Keeps the telemetry logic of the screenshot tool, and returns scripted captures and edits. */ +export class TestScreenshotToolService extends ScreenshotToolService { + /** Whether the tool can capture, as on desktop, or not, as on the web. */ + supported = true; + readonly requests: string[] = []; + /** What a capture returns. A pending promise holds the capture until it settles. */ + result: ScreenshotToolResult | Promise = { kind: 'cancelled', mode: 'none' }; + windowImage: IScreenshotToolImage | undefined; + editResult: IScreenshotToolEdit | undefined; + /** Runs while a scripted capture is active. */ + duringSession: (() => void) | undefined; + + private readonly _onDidChangeScriptedActive = this._register(new Emitter<{ readonly targetWindow: CodeWindow; readonly active: boolean }>()); + override readonly onDidChangeActive = this._onDidChangeScriptedActive.event; + + private readonly _onDidRequestEdit = this._register(new Emitter()); + /** Fires when an edit starts, which then resolves with `editResult`. */ + readonly onDidRequestEdit = this._onDidRequestEdit.event; + + override get isSupported(): boolean { + return this.supported; + } + + override async capture(targetWindow: CodeWindow, _token?: CancellationToken): Promise { + this.requests.push('capture'); + this.runSession(targetWindow); + return this.result; + } + + override async captureWindow(): Promise { + this.requests.push('captureWindow'); + return this.windowImage; + } + + override async edit(screenshot: IScreenshotToolEditable, _surface: ScreenshotToolSurface, name?: string): Promise { + this.requests.push(`edit ${screenshot.original.width}x${screenshot.original.height}${screenshot.annotationState ? ' with annotations' : ''}${name ? ` named ${name}` : ''}`); + this._onDidRequestEdit.fire(); + return this.editResult; + } + + private runSession(targetWindow: CodeWindow): void { + this._onDidChangeScriptedActive.fire({ targetWindow, active: true }); + this.duringSession?.(); + this._onDidChangeScriptedActive.fire({ targetWindow, active: false }); + } +} + +export function createTestScreenshotToolService(store: Pick, supported = true): { readonly service: TestScreenshotToolService; readonly telemetry: TestScreenshotToolTelemetryService } { + const telemetry = new TestScreenshotToolTelemetryService(); + const service = store.add(new TestScreenshotToolService( + new TestConfigurationService(), + telemetry, + new class extends mock() { }(), + new class extends mock() { }(), + new TestAccessibilityService(), + new MockKeybindingService(), + new MockContextKeyService(), + new NullLogService(), + new class extends mock() { }(), + )); + service.supported = supported; + return { service, telemetry }; +} diff --git a/src/vs/workbench/contrib/search/browser/searchResultsView.ts b/src/vs/workbench/contrib/search/browser/searchResultsView.ts index 994769dc62c5..89540f6e2b73 100644 --- a/src/vs/workbench/contrib/search/browser/searchResultsView.ts +++ b/src/vs/workbench/contrib/search/browser/searchResultsView.ts @@ -369,7 +369,7 @@ export class FileMatchRenderer extends Disposable implements ICompressibleTreeRe // when hidesExplorerArrows: true, then the file nodes should still have a twistie because it would otherwise // be hard to tell whether the node is collapsed or expanded. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const twistieContainer = templateData.el.parentElement?.parentElement?.querySelector('.monaco-tl-twistie'); twistieContainer?.classList.add('force-twistie'); } diff --git a/src/vs/workbench/contrib/search/browser/searchTreeModel/searchModel.ts b/src/vs/workbench/contrib/search/browser/searchTreeModel/searchModel.ts index b14e2732a1de..9eda694de838 100644 --- a/src/vs/workbench/contrib/search/browser/searchTreeModel/searchModel.ts +++ b/src/vs/workbench/contrib/search/browser/searchTreeModel/searchModel.ts @@ -217,6 +217,7 @@ export class SearchModelImpl extends Disposable implements ISearchModel { syncResults: IFileMatch[]; } { this.cancelSearch(true); + this._resultQueue.length = 0; this._searchQuery = query; if (!this.searchConfig.searchOnType) { diff --git a/src/vs/workbench/contrib/search/browser/searchWidget.ts b/src/vs/workbench/contrib/search/browser/searchWidget.ts index 8c6b39875db8..d81c95bafbb7 100644 --- a/src/vs/workbench/contrib/search/browser/searchWidget.ts +++ b/src/vs/workbench/contrib/search/browser/searchWidget.ts @@ -716,12 +716,12 @@ export class SearchWidget extends Widget { } else if (keyboardEvent.equals(KeyCode.UpArrow)) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stopPropagationForMultiLineUpwards(keyboardEvent, this.searchInput?.getValue() ?? '', this.searchInput?.domNode.querySelector('textarea') ?? null); } else if (keyboardEvent.equals(KeyCode.DownArrow)) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stopPropagationForMultiLineDownwards(keyboardEvent, this.searchInput?.getValue() ?? '', this.searchInput?.domNode.querySelector('textarea') ?? null); } @@ -800,12 +800,12 @@ export class SearchWidget extends Widget { } else if (keyboardEvent.equals(KeyCode.UpArrow)) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stopPropagationForMultiLineUpwards(keyboardEvent, this.replaceInput?.getValue() ?? '', this.replaceInput?.domNode.querySelector('textarea') ?? null); } else if (keyboardEvent.equals(KeyCode.DownArrow)) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stopPropagationForMultiLineDownwards(keyboardEvent, this.replaceInput?.getValue() ?? '', this.replaceInput?.domNode.querySelector('textarea') ?? null); } } diff --git a/src/vs/workbench/contrib/search/test/browser/searchModel.test.ts b/src/vs/workbench/contrib/search/test/browser/searchModel.test.ts index f56401635a66..ff698270d8c9 100644 --- a/src/vs/workbench/contrib/search/test/browser/searchModel.test.ts +++ b/src/vs/workbench/contrib/search/test/browser/searchModel.test.ts @@ -5,8 +5,9 @@ import assert from 'assert'; import * as sinon from 'sinon'; import * as arrays from '../../../../../base/common/arrays.js'; -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 { isCancellationError } from '../../../../../base/common/errors.js'; import { URI } from '../../../../../base/common/uri.js'; import { Range } from '../../../../../editor/common/core/range.js'; import { IModelService } from '../../../../../editor/common/services/model.js'; @@ -676,6 +677,51 @@ suite('SearchModel', () => { assert.ok(tokenSource.token.isCancellationRequested); }); + for (const hasSyncResults of [false, true]) { + test(`Search Model: a new search discards buffered results with ${hasSyncResults ? 'matching' : 'no matching'} open editors`, async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const previousCompletion = new DeferredPromise(); + const previousProgress = new DeferredPromise(); + const previousMatch = aRawMatch('/old.txt', new TextSearchMatch('old', new OneLineRange(0, 0, 3))); + const currentMatch = aRawMatch('/new.txt', new TextSearchMatch('new', new OneLineRange(0, 0, 3))); + instantiationService.stub(ISearchService, 'textSearchSplitSyncAsync', (query: ITextQuery, token: CancellationToken = CancellationToken.None, onProgress?: (result: ISearchProgressItem) => void) => { + if (query.contentPattern.pattern === 'old') { + queueMicrotask(() => { + onProgress?.(previousMatch); + previousProgress.complete(); + }); + return { + syncResults: { results: [], messages: [] }, + asyncResults: raceCancellationError(previousCompletion.p, token) + }; + } + return { + syncResults: { results: hasSyncResults ? [currentMatch] : [], messages: [] }, + asyncResults: Promise.resolve({ results: [], messages: [] }) + }; + }); + instantiationService.stub(INotebookSearchService, notebookSearchServiceWithInfo([], undefined)); + const model = store.add(instantiationService.createInstance(SearchModelImpl)); + const previousSearch = model.search({ contentPattern: { pattern: 'old' }, type: QueryType.Text, folderQueries }); + await previousProgress.p; + const cancelled = previousSearch.asyncResults.then(() => false, isCancellationError); + + await model.search({ contentPattern: { pattern: 'new' }, type: QueryType.Text, folderQueries }).asyncResults; + assert.ok(await cancelled, 'Expected the previous search to be cancelled'); + previousCompletion.complete({ results: [], messages: [] }); + await clock.runAllAsync(); + + assert.deepStrictEqual( + model.searchResult.matches().map(match => match.resource.toString()), + hasSyncResults ? [currentMatch.resource.toString()] : [] + ); + } finally { + clock.restore(); + } + }); + } + test('getReplaceString returns proper replace string for regExpressions', async () => { const results = [ aRawMatch('/1', diff --git a/src/vs/workbench/contrib/search/test/browser/textSearchQuickAccess.test.ts b/src/vs/workbench/contrib/search/test/browser/textSearchQuickAccess.test.ts new file mode 100644 index 000000000000..6a13588e7d03 --- /dev/null +++ b/src/vs/workbench/contrib/search/test/browser/textSearchQuickAccess.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 * as sinon from 'sinon'; +import { DeferredPromise, raceCancellationError } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { ResourceSet } from '../../../../../base/common/map.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IPickerQuickAccessItem } from '../../../../../platform/quickinput/browser/pickerQuickAccess.js'; +import { IQuickPick, IQuickPickSeparator } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { ISearchComplete, ISearchService, OneLineRange, TextSearchMatch } from '../../../../services/search/common/search.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { INotebookEditorService } from '../../../notebook/browser/services/notebookEditorService.js'; +import { INotebookService } from '../../../notebook/common/notebookService.js'; +import { TextSearchQuickAccess } from '../../browser/quickTextSearch/textSearchQuickAccess.js'; +import { INotebookSearchService } from '../../common/notebookSearch.js'; + +suite('TextSearchQuickAccess', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('changing the query does not show buffered matches from the previous query', async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const instantiationService = workbenchInstantiationService({ + configurationService: () => new TestConfigurationService({ + search: { searchOnType: true, quickAccess: { preserveInput: false } }, + editor: { wordSeparators: '' } + }) + }, store); + instantiationService.stub(IViewsService, {}); + instantiationService.stub(INotebookService, { getNotebookTextModels: () => [] }); + instantiationService.stub(INotebookEditorService, { + onDidAddNotebookEditor: Event.None, + retrieveExistingWidgetFromURI: () => undefined + }); + instantiationService.stub(INotebookSearchService, { + notebookSearch: () => ({ + openFilesToScan: new ResourceSet(), + allScannedFiles: Promise.resolve(new ResourceSet()), + completeData: Promise.resolve({ results: [], messages: [] }) + }) + }); + const folder = instantiationService.get(IWorkspaceContextService).getWorkspace().folders[0].uri; + const previousCompletion = new DeferredPromise(); + const previousProgress = new DeferredPromise(); + instantiationService.stub(ISearchService, { + textSearchSplitSyncAsync: (query, token = CancellationToken.None, onProgress) => { + if (query.contentPattern.pattern === 'old') { + queueMicrotask(() => { + onProgress?.({ + resource: URI.joinPath(folder, 'old.txt'), + results: [new TextSearchMatch('old', new OneLineRange(0, 0, 3))] + }); + previousProgress.complete(); + }); + return { + syncResults: { results: [], messages: [] }, + asyncResults: raceCancellationError(previousCompletion.p, token) + }; + } + return { + syncResults: { results: [], messages: [] }, + asyncResults: Promise.resolve({ results: [], messages: [] }) + }; + } + }); + const changedValue = store.add(new Emitter()); + const currentResults = new DeferredPromise(); + let items: readonly (IPickerQuickAccessItem | IQuickPickSeparator)[] = []; + const picker = new class extends mock>() { + override value = '%old'; + override activeItems: IPickerQuickAccessItem[] = []; + override readonly onDidChangeValue = changedValue.event; + override readonly onDidChangeActive = Event.None; + override readonly onDidTriggerButton = Event.None; + override readonly onDidTriggerItemButton = Event.None; + override readonly onDidTriggerSeparatorButton = Event.None; + override readonly onDidAccept = Event.None; + override readonly onWillHide = Event.None; + override readonly onDidHide = Event.None; + override get items() { return items; } + override set items(value: readonly (IPickerQuickAccessItem | IQuickPickSeparator)[]) { + items = value; + if (this.value === '%new' && value.length) { + currentResults.complete(); + } + } + }; + const provider = store.add(instantiationService.createInstance(TextSearchQuickAccess)); + store.add(provider.provide(picker, CancellationToken.None)); + await previousProgress.p; + + picker.value = '%new'; + changedValue.fire(picker.value); + await currentResults.p; + previousCompletion.complete({ results: [], messages: [] }); + await clock.runAllAsync(); + + assert.deepStrictEqual(picker.items.map(item => item.label), ['No matching results']); + } finally { + clock.restore(); + } + }); +}); diff --git a/src/vs/workbench/contrib/searchEditor/browser/searchEditorInput.ts b/src/vs/workbench/contrib/searchEditor/browser/searchEditorInput.ts index 08e692d36e08..1a756858bcd8 100644 --- a/src/vs/workbench/contrib/searchEditor/browser/searchEditorInput.ts +++ b/src/vs/workbench/contrib/searchEditor/browser/searchEditorInput.ts @@ -267,7 +267,7 @@ export class SearchEditorInput extends EditorInput { async setMatchRanges(ranges: Range[]) { this.oldDecorationsIDs = (await this.resolveModels()).resultsModel.deltaDecorations(this.oldDecorationsIDs, ranges.map(range => - ({ range, options: { description: 'search-editor-find-match', className: SearchEditorFindMatchClass, stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges } }))); + ({ range, options: { description: 'search-editor-find-match', className: SearchEditorFindMatchClass, stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges } }))); } override async revert(group: GroupIdentifier, options?: IRevertOptions) { diff --git a/src/vs/workbench/contrib/sessionChanges/browser/changesView.ts b/src/vs/workbench/contrib/sessionChanges/browser/changesView.ts index 947bcbcb9125..d632064c50bd 100644 --- a/src/vs/workbench/contrib/sessionChanges/browser/changesView.ts +++ b/src/vs/workbench/contrib/sessionChanges/browser/changesView.ts @@ -45,7 +45,7 @@ import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IStorageService } from '../../../../platform/storage/common/storage.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { IThemeService } from '../../../../platform/theme/common/themeService.js'; -import { SessionAgentMergeEnabledContext, SessionIsActiveContext, DesktopChangesEditorTransitionContext, DesktopLayoutContext } from '../../sessions/common/contextkeys.js'; +import { SessionAgentMergeEnabledContext, SessionArtifactIntegrationsEnabledContext, SessionIsActiveContext, DesktopChangesEditorTransitionContext, DesktopLayoutContext } from '../../sessions/common/contextkeys.js'; import { SessionChangesEditorInput } from './sessionChangesEditorInput.js'; import { defaultCountBadgeStyles, defaultProgressBarStyles } from '../../../../platform/theme/browser/defaultStyles.js'; import { IWorkspaceContextService, IWorkspaceFolder, WorkspaceFolder } from '../../../../platform/workspace/common/workspace.js'; @@ -85,7 +85,7 @@ import { ChecksViewModel } from './checksViewModel.js'; import { REVEAL_CI_CHECKS_COMMAND_ID } from '../../sessions/browser/fixCIChecks.js'; // eslint-disable-next-line local/code-import-patterns -- TODO: move skill button constants out of providers import { AGENT_HOST_SKILL_BUTTON_UPDATE_PR_ID, isAgentHostSkillButtonId } from '../../sessions/providers/agentHost/browser/agentHostSkillButtons.js'; -import { AGENT_HOST_AUTO_MERGE_OPERATION_IDS, AGENT_HOST_COMMIT_CHANGESET_OPERATION_ID } from '../../../../platform/agentHost/common/agentHostChangesetOperationService.js'; +import { AGENT_HOST_AUTO_MERGE_OPERATION_IDS, AGENT_HOST_COMMIT_CHANGESET_OPERATION_ID, AGENT_HOST_PULL_REQUEST_OPERATION_IDS } from '../../../../platform/agentHost/common/agentHostChangesetOperationService.js'; import { ActiveSessionContextKeys, CHANGES_VIEW_CONTAINER_ID, CHANGES_VIEW_ID, ChangesContextKeys, ChangesViewMode, IsolationMode, SESSIONS_CHANGES_OPEN_SINGLE_FILE_DIFF_SETTING } from '../../sessions/common/changes.js'; import { buildTreeChildren, ChangesTreeElement, ChangesTreeRenderer, IChangesFileItem, IChangesTreeRootInfo, isChangesFileItem, isChangesFileResource, toIChangesFileItem } from './changesViewRenderer.js'; import { ResourceTree } from '../../../../base/common/resourceTree.js'; @@ -349,6 +349,10 @@ export function isChangesActionsWorkspaceReady(session: ISession | undefined, ch && workspace.folders.every((folder, index) => isEqual(folder.workingDirectory, mountedFolders[index].uri)); } +const AGENT_MERGE_ENABLED_CONTEXT_KEYS: ReadonlySet = new Set([SessionAgentMergeEnabledContext.key]); +const ARTIFACT_INTEGRATIONS_ENABLED_CONTEXT_KEYS: ReadonlySet = new Set([SessionArtifactIntegrationsEnabledContext.key]); +const CHANGES_EDITOR_TRANSITION_CONTEXT_KEYS: ReadonlySet = new Set([DesktopChangesEditorTransitionContext.key]); + class ChangesWorkbenchButtonBarWidget extends Disposable implements IChangesButtonBarWidget { private readonly _buttonBar: WorkbenchButtonBar; @@ -423,9 +427,11 @@ class ChangesWorkbenchButtonBarWidget extends Disposable implements IChangesButt )); }); - const agentMergeEnabledObs = observableFromEvent(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(new Set([SessionAgentMergeEnabledContext.key]))), () => + const agentMergeEnabledObs = observableFromEvent(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(AGENT_MERGE_ENABLED_CONTEXT_KEYS)), () => contextKeyService.getContextKeyValue(SessionAgentMergeEnabledContext.key) === true); - const changesEditorTransitionObs = observableFromEvent(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(new Set([DesktopChangesEditorTransitionContext.key]))), () => + const artifactIntegrationsEnabledObs = observableFromEvent(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(ARTIFACT_INTEGRATIONS_ENABLED_CONTEXT_KEYS)), () => + SessionArtifactIntegrationsEnabledContext.getValue(contextKeyService) === true); + const changesEditorTransitionObs = observableFromEvent(Event.filter(contextKeyService.onDidChangeContext, e => e.affectsSome(CHANGES_EDITOR_TRANSITION_CONTEXT_KEYS)), () => DesktopChangesEditorTransitionContext.getValue(contextKeyService) === true); const workspaceFoldersObs = observableFromEvent(workspaceContextService.onDidChangeWorkspaceFolders, () => workspaceContextService.getWorkspace().folders); @@ -475,10 +481,15 @@ class ChangesWorkbenchButtonBarWidget extends Disposable implements IChangesButt // by the host because the Agent Merge menu keys off them to know it // should stand in (see `agentMergeOwnsPrimaryButton`); where Agent // Merge is unavailable this state simply offers no button. + // + // With artifact integrations, the pull request artifact offers the + // pull request operations, such as Mark Ready and Merge, instead. + const hidesPullRequestOperations = artifactIntegrationsEnabledObs.read(reader); const operations = changes.changesetOperationsObs.read(reader); const changesetOperations = operations .filter(op => op.scopes.includes(SessionChangesetOperationScope.Changeset)) .filter(op => !AGENT_HOST_AUTO_MERGE_OPERATION_IDS.has(op.id)) + .filter(op => !hidesPullRequestOperations || !AGENT_HOST_PULL_REQUEST_OPERATION_IDS.has(op.id)) .filter(op => !excludedOperationIds.has(op.id)); const toOperationAction = (op: ISessionChangesetOperation) => toAction({ @@ -575,11 +586,16 @@ class ChangesWorkbenchButtonBarWidget extends Disposable implements IChangesButt const usesContributedPrimary = !operations.hasRunning && dropdownMenuActions.primary !== undefined; const primaryAction = usesContributedPrimary ? dropdownMenuActions.primary : operations.groups[0]?.[0]; + // The bar renders a single button, so while an operation owns it the + // actions of the toolbar's submenus, such as Submit Feedback, join + // its dropdown rather than being dropped behind it. + const toolbarActions = primaryAction ? getChangesToolbarDropdownActions(menuActions.primary) : []; + // The button bar treats the first entry of a submenu as the button // itself and the remainder as the dropdown, so the primary has to // lead. A contributed primary only names its own actions, so the // menu entry it came from is dropped rather than repeated below it. - const groups = [...operations.groups, ...dropdownMenuActions.groups] + const groups = [...operations.groups, ...dropdownMenuActions.groups, toolbarActions] .map(group => group.filter(action => action !== dropdownMenuActions.contributed)) .filter(group => group.length > 0); const entryCount = groups.reduce((count, group) => count + group.length, 0); @@ -730,6 +746,17 @@ export function actionsNamingSession [group, actions.map((action, index) => action instanceof MenuItemAction && action.item.source ? withResource[groupIndex]?.[1][index] ?? action : action)]); } +/** + * The actions of the submenus of the Changes toolbar, such as Apply Actions with Submit Feedback, as entries of the + * dropdown of the operation that owns the button, such as Merge Changes: the button bar renders only its first action, + * so the submenu itself would never show, and the dropdown is a flat list. + */ +export function getChangesToolbarDropdownActions(actions: readonly IAction[]): IAction[] { + return actions.flatMap(action => action instanceof SubmenuAction + ? action.actions.filter(child => !(child instanceof Separator)) + : []); +} + export class ChangesActionsBarActionViewItem extends BaseActionViewItem { constructor( action: IAction, diff --git a/src/vs/workbench/contrib/sessionChanges/browser/changesViewRenderer.ts b/src/vs/workbench/contrib/sessionChanges/browser/changesViewRenderer.ts index 78c34e6275df..941d8833d65e 100644 --- a/src/vs/workbench/contrib/sessionChanges/browser/changesViewRenderer.ts +++ b/src/vs/workbench/contrib/sessionChanges/browser/changesViewRenderer.ts @@ -359,11 +359,11 @@ export class ChangesTreeRenderer implements ICompressibleTreeRenderer .monaco-button.secondary.monaco-text-button { - border-radius: var(--vscode-cornerRadius-small) 0px 0px var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0px 0px var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .changes-view-body .chat-editing-session-actions .monaco-button.secondary:hover { diff --git a/src/vs/workbench/contrib/sessionChanges/browser/media/createPullRequest.css b/src/vs/workbench/contrib/sessionChanges/browser/media/createPullRequest.css index d2cffd195b61..0c62cfbe4271 100644 --- a/src/vs/workbench/contrib/sessionChanges/browser/media/createPullRequest.css +++ b/src/vs/workbench/contrib/sessionChanges/browser/media/createPullRequest.css @@ -141,7 +141,7 @@ .create-pull-request-widget .monaco-inputbox { width: 100%; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-inputs-corner-radius, var(--vscode-cornerRadius-small)); } .create-pull-request-widget .monaco-inputbox > .ibwrapper > .input { diff --git a/src/vs/workbench/contrib/sessionChanges/browser/media/sessionChangesEditor.css b/src/vs/workbench/contrib/sessionChanges/browser/media/sessionChangesEditor.css index d8318edc9850..709a3785b44d 100644 --- a/src/vs/workbench/contrib/sessionChanges/browser/media/sessionChangesEditor.css +++ b/src/vs/workbench/contrib/sessionChanges/browser/media/sessionChangesEditor.css @@ -192,7 +192,7 @@ padding: var(--vscode-spacing-size20) var(--vscode-spacing-size60); background-color: var(--vscode-commandCenter-background); color: var(--vscode-commandCenter-foreground); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .changes-picker-action-with-summary .action-label > .codicon { @@ -312,7 +312,7 @@ flex: 0 0 auto; padding: var(--vscode-spacing-size40); min-width: 0; - border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; + border-radius: 0 var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)) 0; } .session-changes-editor-header-right .monaco-button.secondary.monaco-text-button.codicon { diff --git a/src/vs/workbench/contrib/sessionChanges/browser/sessionActionContextKeys.ts b/src/vs/workbench/contrib/sessionChanges/browser/sessionActionContextKeys.ts index 666854815a23..36deaa0c6b5a 100644 --- a/src/vs/workbench/contrib/sessionChanges/browser/sessionActionContextKeys.ts +++ b/src/vs/workbench/contrib/sessionChanges/browser/sessionActionContextKeys.ts @@ -6,12 +6,14 @@ import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js'; import { Event } from '../../../../base/common/event.js'; import { autorun, IObservable, observableFromEvent, observableValue, transaction } from '../../../../base/common/observable.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../platform/log/common/log.js'; -import { bindContextKey } from '../../../../platform/observable/common/platformObservableUtils.js'; +import { bindContextKey, observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; import { AGENT_HOST_PULL_REQUEST_OPERATION_IDS } from '../../../../platform/agentHost/common/agentHostChangesetOperationService.js'; -import { DesktopChangesEditorTransitionContext, SessionHasOpenPullRequestContext, SessionPrimaryPullRequestOperationContext } from '../../sessions/common/contextkeys.js'; +import { ArtifactIntegrationsSettingId } from '../../../../platform/artifactIntegrations/common/artifactIntegration.js'; +import { DesktopChangesEditorTransitionContext, SessionArtifactIntegrationsEnabledContext, SessionHasOpenPullRequestContext, SessionPrimaryPullRequestOperationContext } from '../../sessions/common/contextkeys.js'; import { IChat, ISession } from '../../../services/sessions/common/session.js'; import { IGitHubSessionPullRequestObservables } from '../../sessions/browser/github/githubService.js'; import { IChangesSessionObservables } from '../../sessions/common/changesViewService.js'; @@ -56,6 +58,7 @@ export function registerSessionActionContextKeyBinder(binder: SessionActionConte export function bindSessionActionContextKeys(instantiationService: IInstantiationService, source: ISessionActionContextKeysSource, contextKeyService: IContextKeyService): IDisposable { const store = new DisposableStore(); store.add(instantiationService.invokeFunction(accessor => bindChangesetOperationContextKeys(source, contextKeyService, accessor.get(ILogService)))); + store.add(instantiationService.invokeFunction(accessor => bindArtifactIntegrationsContextKey(source, contextKeyService, accessor.get(IConfigurationService)))); store.add(bindSessionCIChecksContextKeys(source.pullRequest, contextKeyService)); for (const binder of sessionActionContextKeyBinders) { store.add(instantiationService.invokeFunction(accessor => binder(accessor, source, contextKeyService))); @@ -63,6 +66,12 @@ export function bindSessionActionContextKeys(instantiationService: IInstantiatio return store; } +function bindArtifactIntegrationsContextKey(source: ISessionActionContextKeysSource, contextKeyService: IContextKeyService, configurationService: IConfigurationService): IDisposable { + const enabled = observableConfigValue(ArtifactIntegrationsSettingId, false, configurationService); + return bindContextKey(SessionArtifactIntegrationsEnabledContext, contextKeyService, reader => + enabled.read(reader) === true && source.session.read(reader)?.capabilities.read(reader).supportsArtifactIntegrations === true); +} + function bindChangesetOperationContextKeys(source: ISessionActionContextKeysSource, contextKeyService: IContextKeyService, logService: ILogService): IDisposable { const store = new DisposableStore(); const { changes } = source; diff --git a/src/vs/workbench/contrib/sessions/browser/agentFeedback.ts b/src/vs/workbench/contrib/sessions/browser/agentFeedback.ts index f488126baef8..93731d7521f5 100644 --- a/src/vs/workbench/contrib/sessions/browser/agentFeedback.ts +++ b/src/vs/workbench/contrib/sessions/browser/agentFeedback.ts @@ -47,6 +47,14 @@ export interface IAgentFeedbackChangeEvent { export interface IAgentFeedbackNavigationBearing { readonly activeIdx: number; readonly totalCount: number; + /** Whether editors should reveal and focus the anchored item. `false` when the anchor was set without revealing it; a missing value means `true`. */ + readonly reveal?: boolean; +} + +export interface IAgentFeedbackNavigationChangeEvent { + readonly sessionResource: URI; + /** Whether editors should reveal and focus the comment the navigation is now anchored at. */ + readonly reveal: boolean; } export interface IAgentFeedbackCommentRevealEvent { @@ -98,7 +106,7 @@ export interface ISubmitFeedbackOptions { * request goes to this chat. */ readonly targetChat?: URI; - /** Sends to the explicit target chat without opening a widget; rejects on failure. */ + /** Sends to the explicit target chat without a widget; accepts selected Created comments only on success and rejects on failure. */ readonly background?: boolean; /** Submit Agent Host feedback without requiring or focusing a chat widget. */ readonly backgroundSubmit?: (query: string, attachment: IAgentFeedbackVariableEntry) => Promise; @@ -114,7 +122,7 @@ export interface IAgentFeedbackService { readonly onDidChangeFeedback: Event; readonly onDidChangeFeedbackVisibility: Event; - readonly onDidChangeNavigation: Event; + readonly onDidChangeNavigation: Event; readonly onDidRevealSessionComment: Event; /** Fired when {@link getFeedbackSessionResource} may resolve differently. */ readonly onDidChangeFeedbackScope: Event; @@ -254,7 +262,10 @@ export interface IAgentFeedbackService { */ getNextFeedback(sessionResource: URI, next: boolean): IAgentFeedback | undefined; getNextNavigableItem(sessionResource: URI, items: readonly T[], next: boolean): T | undefined; - setNavigationAnchor(sessionResource: URI, itemId: string | undefined): void; + /** + * Anchor the navigation of a session at an item. Unless `reveal` is `false`, editors reveal and focus the item. + */ + setNavigationAnchor(sessionResource: URI, itemId: string | undefined, options?: { readonly reveal?: boolean }): void; /** * Get the current navigation bearings for a session. diff --git a/src/vs/workbench/contrib/sessions/browser/aiCustomizationShortcutsWidget.ts b/src/vs/workbench/contrib/sessions/browser/aiCustomizationShortcutsWidget.ts index 597cb87c5887..341710437729 100644 --- a/src/vs/workbench/contrib/sessions/browser/aiCustomizationShortcutsWidget.ts +++ b/src/vs/workbench/contrib/sessions/browser/aiCustomizationShortcutsWidget.ts @@ -5,6 +5,7 @@ import './media/sidebarActionButton.css'; import './media/customizationsToolbar.css'; +import './media/disclosure.css'; import * as DOM from '../../../../base/browser/dom.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { Emitter } from '../../../../base/common/event.js'; @@ -32,6 +33,7 @@ const CUSTOMIZATIONS_COLLAPSED_STORAGE_KEY = 'agentSessions.customizationsShortc export interface IAICustomizationShortcutsWidgetOptions { readonly onDidChangeLayout?: () => void; + readonly compact?: boolean; } export class AICustomizationShortcutsWidget extends Disposable { @@ -60,7 +62,11 @@ export class AICustomizationShortcutsWidget extends Disposable { readonly onDidToggleCollapsed = this._onDidToggleCollapsed.event; get collapsed(): boolean { - return this._collapsed; + return this._options?.compact === true || this._collapsed; + } + + get compact(): boolean { + return this._options?.compact === true; } get collapsedHeight(): number { @@ -112,6 +118,16 @@ export class AICustomizationShortcutsWidget extends Disposable { this._rootVerticalPadding = 0; this._headerTotalCount = 0; DOM.clearNode(this._wrapper); + if (this._options?.compact) { + const container = DOM.append(this._wrapper, $('.ai-customization-toolbar')); + const toolbarContainer = DOM.append(container, $('.ai-customization-toolbar-content')); + this._toolbar = this._renderDisposables.add(this.instantiationService.createInstance(MenuWorkbenchToolBar, toolbarContainer, Menus.SidebarCustomizationsEntryPoint, { + hiddenItemStrategy: HiddenItemStrategy.NoHide, + toolbarOptions: { primaryGroup: () => true }, + telemetrySource: 'sidebarCustomizations', + })); + return; + } this._render(this._wrapper, this._options); this._setCollapsed(this._collapsed); } @@ -132,7 +148,7 @@ export class AICustomizationShortcutsWidget extends Disposable { this._setRootPadding(container, CUSTOMIZATIONS_VERTICAL_PADDING, CUSTOMIZATIONS_VERTICAL_PADDING); // Header - const header = DOM.append(container, $('.ai-customization-header')); + const header = DOM.append(container, $('.ai-customization-header.sessions-disclosure')); this._headerElement = header; header.setAttribute('role', 'button'); header.setAttribute('aria-expanded', 'true'); @@ -195,6 +211,9 @@ export class AICustomizationShortcutsWidget extends Disposable { } get desiredHeight(): number { + if (this._options?.compact) { + return this.collapsedHeight; + } const content = this._toolbarContentElement; if (!content) { return 0; @@ -274,6 +293,10 @@ export class AICustomizationShortcutsWidget extends Disposable { } focus(): void { + if (this._options?.compact) { + this._toolbar?.focus(); + return; + } if (this._collapsed) { this._headerElement?.focus(); return; diff --git a/src/vs/workbench/contrib/sessions/browser/automationsConstants.ts b/src/vs/workbench/contrib/sessions/browser/automationsConstants.ts index dc72cc480646..439ffb16771f 100644 --- a/src/vs/workbench/contrib/sessions/browser/automationsConstants.ts +++ b/src/vs/workbench/contrib/sessions/browser/automationsConstants.ts @@ -4,3 +4,4 @@ *--------------------------------------------------------------------------------------------*/ export const AUTOMATIONS_CUSTOM_VIEW_ID = 'sessions.customView.automations'; +export const AUTOMATIONS_TOUR_SEEN_KEY = 'sessions.getStarted.showMe.automation'; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactActivitiesModel.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactActivitiesModel.ts index 7b0e49114b69..1b1067bbc882 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactActivitiesModel.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactActivitiesModel.ts @@ -13,7 +13,7 @@ import { isEqual } from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { getArtifactThemeIcon } from '../../../../../platform/artifactIntegrations/browser/artifactDetailsList.js'; -import { ArtifactRun, ArtifactRunState, ArtifactSnapshot, IArtifactModel, isArtifactRunSettled } from '../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; +import { ArtifactRun, ArtifactRunState, ArtifactSnapshot, getArtifactRunInitiator, IArtifactModel, isArtifactRunSettled } from '../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; import { IChatWidget, IChatWidgetService } from '../../../chat/browser/chat.js'; import { IChatRequestViewModel, IChatResponseViewModel, isRequestVM, isResponseVM } from '../../../chat/common/model/chatViewModel.js'; import { ISessionsService } from '../sessionsService.js'; @@ -85,7 +85,7 @@ export class ArtifactActivitiesModel extends Disposable { this.changed.trigger(undefined); } else if (!this.pages.length && !this.loading && !this.error && (state.activitiesExpanded || !snapshot.runs.some(isVisibleActivity))) { - // Recent runs that were all skipped would hide the card, so discover older visible history first. + // Recent runs that were all hidden would hide the card, so discover older visible history first. void this.loadPage(0); } })); @@ -135,7 +135,7 @@ export class ArtifactActivitiesModel extends Disposable { this.error = ''; this.changed.trigger(undefined); try { - // Skipped runs are not shown, so keep paging until a page adds a visible run or history ends. + // Hidden runs are not shown, so keep paging until a page adds a visible run or history ends. for (let page: IActivityPage | undefined; !page || (page.next && !page.runs.some(isVisibleActivity)); index++) { const before = index === 0 ? undefined : this.pages[index - 1]?.next; this.retryPage = index; @@ -252,9 +252,12 @@ export class ArtifactActivitiesModel extends Disposable { } } -/** A skipped run did nothing, so it is not shown as activity. */ +/** + * A skipped run did nothing, so it is not shown as activity. Neither is a user's click on a general (footer) action, + * unless its outcome is unknown and must be reconciled from the activity row. + */ function isVisibleActivity(run: ArtifactRun): boolean { - return run.state !== 'skipped'; + return run.state !== 'skipped' && (!run.generalAction || run.indeterminate === true || getArtifactRunInitiator(run) !== 'user'); } export function artifactRunStateLabel(state: ArtifactRunState): string { diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactAutopilotModel.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactAutopilotModel.ts index 6da4ce61775f..7fc9b832ec3a 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactAutopilotModel.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactAutopilotModel.ts @@ -43,13 +43,13 @@ export class ArtifactAutopilotModel extends Disposable { id: contribution.integrationId, title: groups.length > 1 ? localize('artifactAutopilot.providerTitle', "{0} Autopilot", contribution.label) : localize('artifactAutopilot.title', "Autopilot"), expanded: state.expandedAutopilot.has(contribution.integrationId), - checked: enabled > 0 && enabled === eligible.length, + checked: enabled > 0, disabled: this.pendingGroups.has(contribution.integrationId) || !eligible.length, summary: unavailable ? localize('artifactAutopilot.unavailable', "{0} on, {1} unavailable", enabled, unavailable) : localize('artifactAutopilot.enabled', "{0} of {1} on", enabled, eligible.length), toggleLabel: groups.length > 1 ? localize('artifactAutopilot.providerRules', "All Available Autopilot Rules: {0}", contribution.label) : localize('artifactAutopilot.allRules', "All Available Autopilot Rules"), - description: localize('artifactAutopilot.masterHelp', "Enable all available rules for this provider using the policies shown in their dropdowns, or turn off all enabled rules. Unavailable rules are not enabled."), + description: localize('artifactAutopilot.masterHelp', "On while any rule is on. Turn on to enable all available rules for this provider using the policies shown in their dropdowns, or turn off to disable all enabled rules. Unavailable rules are not enabled."), rules: options.map(option => this.rule(contribution, option, snapshot)), setExpanded: expanded => { if (expanded) { @@ -100,6 +100,7 @@ export class ArtifactAutopilotModel extends Disposable { const pending = this.pendingRules.has(id); const disabled = pending || (!checked && !canEnableArtifactAutomationOption(contribution, option)); const available = contribution.view.automationAvailability.find(available => available.id === option.id); + const grant = contribution.configuration.grants?.[option.id]; const reason = contribution.configuration.disablements[option.id]?.reason ?? available?.unavailableReason ?? (!checked ? available?.enablement?.disabledReason : undefined) ?? (contribution.view.availability.kind !== 'available' && contribution.view.availability.kind !== 'loading' ? contribution.view.availability.reason : undefined) @@ -109,7 +110,11 @@ export class ArtifactAutopilotModel extends Disposable { description: [ ...describeArtifactAutomationConsent(contribution, option, { location: this.location(contribution, snapshot) }), option.kind === 'enum' ? localize('artifactPolicyPreparation', "Choosing a policy while this rule is off does not enable it. Turning it on uses the displayed policy.") : '', - checked && contribution.configuration.grants?.[option.id]?.kind === 'agent' ? localize('artifactAutopilot.agentGrant', "Turned on at the agent's request after you confirmed.") : '', + checked && grant?.kind === 'agent' + ? grant.autoApproved + ? localize('artifactAutopilot.agentAutoApprovedGrant', "Turned on by the agent (auto-approved).") + : localize('artifactAutopilot.agentGrant', "Turned on at the agent's request after you confirmed.") + : '', reason, ].filter(Boolean).join(' '), policy: option.kind === 'enum' ? { diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactDetailsContextView.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactDetailsContextView.ts index b2bb9cd43aff..092f46baee37 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactDetailsContextView.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactDetailsContextView.ts @@ -296,9 +296,9 @@ function artifactDetailsHelp(): string { localize('artifactDetailsHelp.description', "Descriptions show at most three lines. The Accessible View includes the full description. When a provider supplies more information about a list, use Tab to reach its information icon and Enter or Space to read the hover."), localize('artifactDetailsHelp.controls', "Use Tab and Shift+Tab to move between controls. Buttons below the state lists run actions once. Enabled actions come first in provider order, and the first action is primary. List rows show a single line; their full text and state remain available to screen readers and in hovers. Use Space to change an Autopilot switch. Enabling a rule grants permission for future automatic runs; it can run immediately if its condition already holds. Turning it off prevents new runs, but does not cancel work already started."), localize('artifactDetailsHelp.focus', "A temporarily unavailable switch moves focus to its explanation, then back when available, unless you move focus elsewhere. Enabled automation remains available to turn off."), - localize('artifactDetailsHelp.dismiss', "Escape or Close returns focus to the invoking pill. Clicking outside, including in the chat input, dismisses details without moving focus back. Clicking another artifact switches this panel; clicking its status section selects and focuses the corresponding list, or focuses its action."), + localize('artifactDetailsHelp.dismiss', "Escape or Close returns focus to the invoking pill. Clicking outside, including in the chat input, dismisses details without moving focus back. A pill's main part opens its resource. Clicking another artifact's status section switches this panel and selects and focuses the corresponding list, or focuses its action; an artifact without status sections offers a Details section instead."), localize('artifactDetailsHelp.view', "Open the Accessible View{0} to read the full description and current lists as text. The chat accessibility verbosity setting controls the help hint.", ''), - localize('artifactDetailsHelp.autopilot', "All Available Autopilot Rules applies only to its provider's currently available rules. The enabled count describes partial enablement. Enabling a group saves immediately and uses the policies shown in the dropdowns. Disabling a group revokes enabled rules without enabling unavailable ones."), + localize('artifactDetailsHelp.autopilot', "All Available Autopilot Rules applies only to its provider's currently available rules. Its switch is on while at least one rule is on, and the enabled count describes partial enablement. Enabling a group saves immediately and uses the policies shown in the dropdowns. Disabling a group revokes all enabled rules without enabling unavailable ones."), localize('artifactDetailsHelp.tabs', "State lists start collapsed. Clicking a state-list tab, or pressing Enter or Space on it, expands its list; activating the expanded tab again collapses all lists. While a list is expanded, Left and Right Arrow, Home, and End select another state-list tab and keep keyboard focus on the full tab; while all lists are collapsed, they only move focus between tabs. Clicking a tab moves focus to the first item in its list. Tab moves through the information buttons beside each tab label and into the expanded list. Enter or Space on an information button shows that list's details without selecting its tab. The list area keeps its height when you change tabs. Use arrow keys in a list and Enter to open its selected item. A pill's status section expands and focuses its list. Autopilot is collapsed by default; its heading expands or collapses its rules, and its separate switch enables all available rules or turns them off. Policy dropdowns remain visible while rules are off. Selecting a policy while off does not enable the rule; turning the switch on uses the displayed policy without asking again. Policy selections, expanded tabs, and Autopilot expansion choices are remembered when reopening the artifact."), localize('artifactDetailsHelp.itemActions', "Some list rows offer actions for that item, such as rerunning a failed check or resolving a review comment. They appear at the end of a row when it is hovered or focused. From the list, press Tab to reach the focused row's actions, Left and Right Arrow to move between them, and Enter or Space to run one. Shift+Tab returns to the list. Item actions run immediately and keep the details open; their row shows progress until they finish, and failures are reported. The Accessible View names each item's actions."), localize('artifactDetailsHelp.automationPill', "Artifacts with enabled Autopilot rules have a trailing pill section with an Autopilot icon and the number of enabled rules. Select it to open and focus Autopilot. This count includes saved enabled rules even when new enablement is temporarily unavailable."), diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationGroup.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationGroup.ts index ab4623336da1..77b170bdf386 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationGroup.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationGroup.ts @@ -29,7 +29,7 @@ import { ILayoutService } from '../../../../../platform/layout/browser/layoutSer import { ChatPillActionViewItem, getChatPillEntryToolbarActions, IChatPill, IChatPillAction, IChatPillEntry } from '../../../../browser/chatPills.js'; import { ArtifactButtons, IArtifactButton } from './artifactButtons.js'; import { ArtifactDetailsSelection } from './artifactDetailsView.js'; -import { ArtifactIntegrationPresentation, countEnabledArtifactAutomations, createArtifactOpenAction, getArtifactStatusButtons, IArtifactDetailsHost } from './artifactIntegrationPresentation.js'; +import { ArtifactIntegrationPresentation, countEnabledArtifactAutomations, getArtifactOpenAriaLabel, getArtifactStatusButtons, IArtifactDetailsHost } from './artifactIntegrationPresentation.js'; /** One artifact listed by an {@link ArtifactIntegrationGroup}. */ export interface IArtifactIntegrationGroupMember { @@ -253,22 +253,22 @@ export interface IArtifactGroupRowAction { } /** - * The actions a group dropdown row offers for its artifact: Open, then the entry's own actions in the order the other - * pill dropdowns show them, with Pin before the entry's promoted action, such as Remove. + * The actions a group dropdown row offers for its artifact, whose main part opens it: the entry's own actions in the + * order the other pill dropdowns show them, with Pin before the entry's promoted action, such as Remove. */ export function getArtifactGroupRowActions(member: Pick): readonly IArtifactGroupRowAction[] { const { entry, pinAction } = member; - const open = createArtifactOpenAction(entry); const entryActions = getChatPillEntryToolbarActions({ ...entry, toolbarActions: [...entry.toolbarActions ?? [], ...pinAction ? [pinAction] : []] }); - return [open, ...entryActions].map(action => ({ action, keepOpen: action === pinAction || action === entry.promotedAction })); + return entryActions.map(action => ({ action, keepOpen: action === pinAction || action === entry.promotedAction })); } /** Marks the focusable controls of a dropdown row, in their visual order. */ const controlAttribute = 'data-artifact-group-control'; /** - * Lists a group's artifacts above its pill. Each row is a toolbar: the artifact's main part opens its details, - * each status section opens the matching list, and the trailing actions open, copy, pin or remove the artifact. + * Lists a group's artifacts above its pill. Each row is a toolbar: the artifact's main part opens its resource, each + * status section opens the matching list in its details, or a Details section opens them when it has no status + * sections, and the trailing actions copy, pin or remove the artifact. */ class ArtifactIntegrationGroupDropdown extends Disposable { private readonly element: HTMLElement; @@ -319,6 +319,7 @@ class ArtifactIntegrationGroupDropdown extends Disposable { let row = this.rows.get(member.entry.id); if (!row) { row = new ArtifactIntegrationGroupRow(this.hoverService, this.hoverLifecycleOptions, { + open: entry => this.openResource(entry), openDetails: (presentation, selection) => this.openDetails(presentation, selection), run: (action, keepOpen) => this.runAction(action, keepOpen), }); @@ -394,6 +395,11 @@ class ArtifactIntegrationGroupDropdown extends Disposable { this.view?.close(); } + private openResource(entry: IChatPillEntry): void { + this.hide(true); + entry.open(); + } + private openDetails(presentation: ArtifactIntegrationPresentation, selection: ArtifactDetailsSelection | undefined): void { const button = this.button; const host = this.group.detailsHost; @@ -465,6 +471,7 @@ class ArtifactIntegrationGroupDropdown extends Disposable { } interface IArtifactIntegrationGroupRowDelegate { + open(entry: IChatPillEntry): void; openDetails(presentation: ArtifactIntegrationPresentation, selection: ArtifactDetailsSelection | undefined): void; run(action: IChatPillAction, keepOpen: boolean): void; } @@ -489,7 +496,7 @@ class ArtifactIntegrationGroupRow extends Disposable { ) { super(); this.element = $('.artifact-group-row', { role: 'toolbar', 'aria-orientation': 'horizontal' }); - this.main = append(this.element, $('.artifact-group-row-main', { role: 'button', tabindex: '-1', [controlAttribute]: '', 'aria-haspopup': 'dialog' })); + this.main = append(this.element, $('.artifact-group-row-main', { role: 'button', tabindex: '-1', [controlAttribute]: '' })); this.icon = append(this.main, $('span.artifact-group-row-icon')); this.label = append(this.main, $('span.artifact-group-row-label')); this.statuses = append(this.element, $('.artifact-group-row-statuses')); @@ -498,7 +505,7 @@ class ArtifactIntegrationGroupRow extends Disposable { this._register(toDisposable(() => this.element.remove())); this._register(this.hoverService.setupDelayedHover(this.main, () => ({ content: this.mainDescription(), style: HoverStyle.Pointer }), this.hoverLifecycleOptions)); this._register(this.hoverService.setupDelayedHover(this.title, () => ({ content: this.member?.entry.label ?? '', style: HoverStyle.Pointer }), this.hoverLifecycleOptions)); - // The row's free space, such as its title, opens the artifact's details like its main part. + // The row's free space, such as its title, opens the artifact's resource like its main part. this._register(addDisposableListener(this.element, EventType.CLICK, event => { const target = event.target; if (isHTMLElement(target) && (target.closest('.artifact-group-row-statuses') || target.closest('.artifact-group-row-actions'))) { @@ -506,7 +513,7 @@ class ArtifactIntegrationGroupRow extends Disposable { } EventHelper.stop(event, true); if (this.member) { - this.delegate.openDetails(this.member.presentation, undefined); + this.delegate.open(this.member.entry); } })); } @@ -527,9 +534,7 @@ class ArtifactIntegrationGroupRow extends Disposable { this.element.setAttribute('aria-label', localize('artifactGroup.row', "{0}, {1} of {2}", description, index + 1, count)); reset(this.icon, renderArtifactIcon(main ? getArtifactThemeIcon(main.icon) : member.entry.icon ?? Codicon.link)); this.label.textContent = label; - this.main.setAttribute('aria-label', localize('artifactGroup.showDetails', "Show artifact details: {0}", description)); - this.main.setAttribute('aria-expanded', String(selected)); - this.main.setAttribute('aria-controls', member.presentation.detailsHost.id); + this.main.setAttribute('aria-label', getArtifactOpenAriaLabel(label)); const title = member.entry.label !== label ? member.entry.label : ''; this.title.textContent = title; this.title.hidden = !title; @@ -585,7 +590,9 @@ class ArtifactIntegrationGroupRow extends Disposable { if (status.icon) { append(element, renderArtifactIcon(status.icon)); } - append(element, $('span.artifact-group-row-status-label', undefined, status.label)); + if (!status.iconOnly) { + append(element, $('span.artifact-group-row-status-label', undefined, status.label)); + } element.setAttribute('aria-label', status.ariaLabel ?? status.description ?? status.label); if (status.controls) { element.setAttribute('aria-controls', status.controls); diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPillSources.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPillSources.ts index 6e985f9f65ec..62fc706905fd 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPillSources.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPillSources.ts @@ -27,8 +27,9 @@ export interface IArtifactIntegrationPillItem { } /** - * The group ID the main integration assigns an integrated record, which gives the record a pill of its own instead of - * listing it in the pill for its kind. Records without a main integration have none. + * The group ID the main integration assigns an integrated record, which gives an artifact a pill of its own instead of + * listing it in the pill for its kind. References stay in the References pill regardless. Records without a main + * integration have none. */ export function getArtifactIntegrationGroupId(snapshot: ArtifactSnapshot): string | undefined { return getArtifactMainContribution(snapshot)?.view.groupId; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPresentation.ts b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPresentation.ts index 04e66432bd13..047eac2c2910 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPresentation.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/artifactIntegrationPresentation.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import './media/artifactIntegrations.css'; -import { $, append, isAncestorOfActiveElement, isHTMLElement } from '../../../../../base/browser/dom.js'; +import { $, append, isAncestorOfActiveElement } from '../../../../../base/browser/dom.js'; import { status } from '../../../../../base/browser/ui/aria/aria.js'; import { HoverStyle } from '../../../../../base/browser/ui/hover/hover.js'; import { Action, toAction } from '../../../../../base/common/actions.js'; @@ -53,12 +53,18 @@ export function createArtifactOpenAction(entry: IChatPillEntry): IChatPillAction }); } +/** The accessible name of an artifact's main part, which opens its resource. */ +export function getArtifactOpenAriaLabel(label: string): string { + return localize('artifactOpenMain', "Open {0}", label); +} + /** - * The status sections an artifact shows beside its main part: each integration section, a Sign In section while - * authentication is required, and the number of enabled Autopilot rules. Activating one opens the artifact's - * details on the matching list, action or Autopilot. + * The status sections an artifact shows beside its main part, which opens its resource: each integration section, a + * Sign In section while authentication is required, and the number of enabled Autopilot rules. Activating one opens + * the artifact's details on the matching list, action or Autopilot. Without any, a Details section toggles the + * artifact's details, so they stay reachable. */ -export function getArtifactStatusButtons(presentation: ArtifactIntegrationPresentation, snapshot: ArtifactSnapshot, expanded: boolean, open: (target: HTMLElement, selection: ArtifactDetailsSelection) => void): IArtifactButton[] { +export function getArtifactStatusButtons(presentation: ArtifactIntegrationPresentation, snapshot: ArtifactSnapshot, expanded: boolean, open: (target: HTMLElement, selection: ArtifactDetailsSelection | undefined) => void): IArtifactButton[] { const controls = presentation.detailsHost.id; const buttons: IArtifactButton[] = snapshot.contributions.flatMap(contribution => contribution.view.sections.map(section => ({ id: JSON.stringify([contribution.integrationId, section.id]), label: section.label, icon: icon(section.icon), @@ -88,6 +94,16 @@ export function getArtifactStatusButtons(presentation: ArtifactIntegrationPresen run: target => open(target, 'autopilot'), }); } + if (buttons.length === 0) { + const main = getArtifactMainContribution(snapshot)?.view.main; + buttons.push({ + id: 'artifact-details', label: localize('artifactDetails', "Details"), icon: Codicon.info, iconOnly: true, + description: localize('artifactDetailsDescription', "Show Details"), + ariaLabel: localize('artifactShowDetails', "Show artifact details: {0}", main?.description ?? main?.label ?? snapshot.artifact.label), + expanded, controls, + run: target => open(target, undefined), + }); + } return buttons; } @@ -119,13 +135,7 @@ export class ArtifactIntegrationPresentation extends Disposable { })), }; }); - this.action = this._register(new Action(`artifactIntegration.${model.snapshot.get().artifact.id}`, model.snapshot.get().artifact.label, undefined, true, - async target => { - if (!isHTMLElement(target)) { - throw new Error(localize('artifactDetailsTargetUnavailable', "The artifact details button is no longer available.")); - } - detailsHost.toggle(this, target); - })); + this.action = this._register(new Action(`artifactIntegration.${model.snapshot.get().artifact.id}`, model.snapshot.get().artifact.label, undefined, true, async () => this.open())); this.inlinePill = this.createPill(constObservable(undefined)); this._register(toDisposable(() => detailsHost.release(this))); } @@ -170,6 +180,22 @@ export class ArtifactIntegrationPresentation extends Disposable { return this.entry; } + /** + * Opens the artifact's resource through its undecorated entry, which records the open; before an entry is known, + * opens the recorded resource directly. + */ + open(): void { + const entry = this.entry; + if (entry) { + entry.open(); + return; + } + const resource = this.model.snapshot.get().artifact.resource; + void this.run(async () => { + await this.openerService.open(resource, { openExternal: true, allowContributedOpeners: true, fromUserGesture: true }); + }); + } + /** `input` is passed to the action, for example the details item it runs for. */ async invoke(integrationId: string, actionId: string, input?: ArtifactJsonValue): Promise { const chat = this.invokingChat(); @@ -243,13 +269,16 @@ class ArtifactIntegrationPill extends ChatPillActionViewItem { const selected = host.selected.read(reader) === this.presentation; this.updateLabel(); this.updateAriaLabel(); + const description = this.mainDescription(); + if (description !== this.getLabelText()) { + this.button!.element.setAttribute('aria-description', description); + } else { + this.button!.element.removeAttribute('aria-description'); + } this.element!.classList.toggle('artifact-pill-selected', selected); - this.button!.element.setAttribute('aria-haspopup', 'dialog'); - this.button!.element.setAttribute('aria-expanded', String(selected)); - this.button!.element.setAttribute('aria-controls', host.id); - this.button!.element.dataset.artifactDetailsOwner = host.id; + // Autopilot and Details can disappear while the details they opened are shown, so those return focus to the main part. const sections = getArtifactStatusButtons(this.presentation, snapshot, selected, (target, selection) => - host.toggle(this.presentation, selection === 'autopilot' ? this.button!.element : target, selection)); + host.toggle(this.presentation, selection === 'autopilot' || selection === undefined ? this.button!.element : target, selection)); this.sections!.update(sections); this.element!.classList.toggle('chat-pill-segmented', sections.length > 0); // Its own surface's trailing action, else that of the pill showing it as a lone entry, such as a pinned entry's Unpin. @@ -258,14 +287,6 @@ class ArtifactIntegrationPill extends ChatPillActionViewItem { })); } - protected override onDidClickButton(): void { - void this.actionRunner.run(this._action, this.button!.element); - } - - protected override hasOpenDropdown(): boolean { - return this.presentation.detailsHost.selected.get() === this.presentation; - } - protected override getLabelText(): string { const snapshot = this.presentation.snapshot.get(); return getArtifactMainContribution(snapshot)?.view.main?.label ?? this.presentation.baseEntry?.label ?? snapshot.artifact.label; @@ -281,7 +302,7 @@ class ArtifactIntegrationPill extends ChatPillActionViewItem { } protected override getAriaLabel(): string { - return localize('artifactShowDetails', "Show artifact details: {0}", this.mainDescription()); + return getArtifactOpenAriaLabel(this.getLabelText()); } protected override updateTooltip(): void { } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/chatView.ts b/src/vs/workbench/contrib/sessions/browser/chat/chatView.ts index 96b7e631b95a..1a43eef31d8e 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/chatView.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/chatView.ts @@ -58,7 +58,7 @@ import { IChatSessionsService, localChatSessionType } from '../../../chat/common import { IChatSessionHistoryStatus } from '../../../../../platform/chat/common/chatSessionHistory.js'; import { isPhoneLayout } from '../../../../browser/parts/sessions/mobileLayout.js'; import { ISelectNoWorkspaceOptions, ISelectWorkspaceOptions, WorkspaceSelectionResult } from '../../../../services/sessions/common/workspaceSelection.js'; -import { AbstractChatView, ChatViewKind, IChatViewOptions, IChatViewRequestOutcome, IChatViewRequestSubmission } from '../parts/chatView.js'; +import { AbstractChatView, ChatViewKind, IChatViewBackgroundReplica, IChatViewOptions, IChatViewRequestOutcome, IChatViewRequestSubmission } from '../parts/chatView.js'; import { IsPhoneLayoutContext, SessionUsesExperimentalComposerLayoutContext } from '../../common/contextkeys.js'; import { ChatInteractivity, getChatHarness, getSessionStatusMessage, IChat, isActiveSessionStatus, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; import { SessionStatusIcon } from '../sessionStatusIcon.js'; @@ -79,9 +79,6 @@ import { ISessionsChatViewStateService } from './chatViewStateService.js'; import { ExternalSessionBanner } from './externalSessionBanner.js'; import { ISessionOpenTelemetryService } from '../sessionOpenTelemetryService.js'; import { ISessionArchiveNudgeTarget, SessionArchiveNudge } from './sessionArchiveNudge.js'; -import { SessionsChatBackgroundReplica } from '../chatBackgroundRenderer.js'; -import { SESSIONS_CHAT_SURFACE_CLASS } from '../sessionsChatSurface.js'; -import { ISessionsChatBackgroundService } from '../chatBackgroundService.js'; import { SessionComparisonResult } from './sessionComparisonResult.js'; import { ISessionPickerVisibility, noSessionPickerVisibility } from '../../common/sessionPickerVisibility.js'; import { ISessionComparison, ISessionComparisonService, SessionComparisonParticipantRole } from '../../common/sessionComparison.js'; @@ -394,7 +391,8 @@ export class ChatView extends AbstractChatView { private _providerReloadCts: CancellationTokenSource | undefined; private _pendingLoadInput: { readonly resource: URI; readonly inputBeforeLoad: string; readonly inputModelToPreserve?: IInputModel } | undefined; - private readonly _stickyScrollBackgroundReplica = this._register(new MutableDisposable()); + private readonly _background: IChatViewOptions['background']; + private readonly _stickyScrollBackgroundReplica = this._register(new MutableDisposable()); private _stickyScrollBackgroundContainer: HTMLElement | undefined; /** Tracks the current chat's interactivity and hides the input for read-only chats. */ @@ -462,7 +460,6 @@ export class ChatView extends AbstractChatView { @ISessionsChatViewStateService private readonly viewStateService: ISessionsChatViewStateService, @ISessionOpenTelemetryService private readonly sessionOpenTelemetryService: ISessionOpenTelemetryService, @IChatOpenDiagnosticsService private readonly chatOpenDiagnosticsService: IChatOpenDiagnosticsService, - @ISessionsChatBackgroundService private readonly chatBackgroundService: ISessionsChatBackgroundService, @INotificationService private readonly notificationService: INotificationService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, @@ -472,8 +469,9 @@ export class ChatView extends AbstractChatView { ) { super(); this._composerOnly = options.inputOnly === true; + this._background = options.background; this._register(toDisposable(() => this._reportModelUnbound())); - this._chatItemHorizontalPadding = getSessionChatItemHorizontalPadding(!!this.chatBackgroundService.getBackground()); + this._chatItemHorizontalPadding = getSessionChatItemHorizontalPadding(this._background?.hasBackground() ?? false); this.element.classList.add('chat-view-chat'); this._widgetContainer = $('.chat-view-widget'); @@ -512,6 +510,7 @@ export class ChatView extends AbstractChatView { supportsFileReferences: true, rendererOptions: { renderInputRequests: options.inputOnly ? false : undefined, + renderHtmlPreviews: true, referencesExpandedWhenEmptyResponse: false, progressMessageAtBottomOfResponse: mode => mode !== ChatModeKind.Ask, contentHorizontalPadding: this._chatItemHorizontalPadding, @@ -532,7 +531,7 @@ export class ChatView extends AbstractChatView { sandboxToggleChecked: observeSessionSandboxToggle(this._currentSessionObs, this._currentChatResourceObs, this.sessionsProvidersService), transcriptTabIndex: -1, enableFind: true, - persistentContentHeight: this.chatBackgroundService.getBackground() ? 0 : SESSION_CHAT_INPUT_TOOLBAR_HEIGHT, + persistentContentHeight: this._background?.hasBackground() ? 0 : SESSION_CHAT_INPUT_TOOLBAR_HEIGHT, renderGettingStartedTip: () => shouldShowSessionChatTip(this._currentSessionObs.get()?.status.get()), }, this._buildStyles(this._isActive) @@ -555,8 +554,10 @@ export class ChatView extends AbstractChatView { updateExperimentalComposerLayout(); } })); - this._register(this._widget.onDidChangeStickyScrollDomNode(() => this._layoutStickyScrollBackground())); - this._register(this.chatBackgroundService.onDidChangeBackground(() => this._updateChatBackground())); + if (this._background) { + this._register(this._widget.onDidChangeStickyScrollDomNode(() => this._layoutStickyScrollBackground())); + this._register(this._background.onDidChange(() => this._updateChatBackground())); + } this._externalSessionBanner = this._register(scopedInstantiationService.createInstance( ExternalSessionBanner, this.element, @@ -644,7 +645,8 @@ export class ChatView extends AbstractChatView { this._setupInitialTranscriptContext(chatModel); this._selectionSideChatController = this._register(scopedInstantiationService.createInstance(ResponseSelectionSideChatController, this._widget, isResponseSelectionSupported(), { - useActionMenu: () => configurationService.getValue(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING), + useActionMenu: () => true, + showOnSelection: configurationService.getValue(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING) !== false, onAction: (variant, action) => logResponseSelectionWidgetAction(telemetryService, variant, action), })); @@ -712,6 +714,9 @@ export class ChatView extends AbstractChatView { if (e.affectsConfiguration(AGENT_SESSIONS_SCOPED_INPUT_HISTORY_SETTING)) { this._applyHistoryKey(); } + if (e.affectsConfiguration(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING)) { + this._selectionSideChatController.setShowOnSelection(this.configurationService.getValue(AGENT_SESSIONS_RESPONSE_SELECTION_MENU_SETTING) !== false); + } })); // Voice transcript overlay + input glow. @@ -1389,11 +1394,11 @@ export class ChatView extends AbstractChatView { } private _updateChatBackground(): void { - const background = this.chatBackgroundService.getBackground(); + const hasBackground = this._background?.hasBackground() ?? false; // Wallpaper cannot hide transcript content beneath floating controls. - this._widget.setPersistentContentHeight(background ? 0 : SESSION_CHAT_INPUT_TOOLBAR_HEIGHT); - this._updateChatItemHorizontalPadding(!!background); - this._stickyScrollBackgroundReplica.value?.setBackground(background); + this._widget.setPersistentContentHeight(hasBackground ? 0 : SESSION_CHAT_INPUT_TOOLBAR_HEIGHT); + this._updateChatItemHorizontalPadding(hasBackground); + this._stickyScrollBackgroundReplica.value?.updateBackground(); } private _updateChatItemHorizontalPadding(hasBackground: boolean): void { @@ -1407,6 +1412,9 @@ export class ChatView extends AbstractChatView { } private _layoutStickyScrollBackground(): void { + if (!this._background) { + return; + } const stickyContainer = this._widget.stickyScrollDomNode; if (stickyContainer !== this._stickyScrollBackgroundContainer) { this._stickyScrollBackgroundReplica.clear(); @@ -1419,16 +1427,13 @@ export class ChatView extends AbstractChatView { let replica = this._stickyScrollBackgroundReplica.value; if (!replica) { - const surface = this.element.closest(`.${SESSIONS_CHAT_SURFACE_CLASS}`); - const source = surface ? Array.from(surface.children).find(element => element.classList.contains('sessions-chat-background')) : undefined; - if (!isHTMLElement(source)) { + replica = this._background.createReplica(this.element, stickyContainer); + if (!replica) { return; } - - replica = new SessionsChatBackgroundReplica(source, stickyContainer); this._stickyScrollBackgroundReplica.value = replica; this._stickyScrollBackgroundContainer = stickyContainer; - replica.setBackground(this.chatBackgroundService.getBackground()); + replica.updateBackground(); } else { replica.layout(); } @@ -1684,11 +1689,7 @@ export function findInitialTranscriptContextEntry(requests: readonly { readonly : findTranscriptContextEntry(requests); } -/** - * Default {@link IChatViewFactory} implementation. Lives in the contrib - * layer where the concrete views are defined and is registered as an eager - * singleton via the entry point. - */ +/** Shared chat-view construction; each entry selects its presentation options. */ export class ChatViewFactory implements IChatViewFactory { declare readonly _serviceBrand: undefined; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/defaultChatViewFactory.ts b/src/vs/workbench/contrib/sessions/browser/chat/defaultChatViewFactory.ts new file mode 100644 index 000000000000..344f4dd6ced0 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chat/defaultChatViewFactory.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 { isHTMLElement } from '../../../../../base/browser/dom.js'; +import { IDisposable } from '../../../../../base/common/lifecycle.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { SessionsChatBackgroundReplica } from '../chatBackgroundRenderer.js'; +import { ISessionsChatBackgroundService } from '../chatBackgroundService.js'; +import { IChatViewOptions } from '../parts/chatView.js'; +import { SESSIONS_CHAT_SURFACE_CLASS, SessionsChatSurface } from '../sessionsChatSurface.js'; +import { ChatViewFactory } from './chatView.js'; + +export class DefaultChatViewFactory extends ChatViewFactory { + + protected override readonly viewOptions: IChatViewOptions; + + constructor( + @ISessionsChatBackgroundService backgroundService: ISessionsChatBackgroundService, + ) { + super(); + this.viewOptions = { + background: { + onDidChange: backgroundService.onDidChangeBackground, + hasBackground: () => !!backgroundService.getBackground(), + createReplica: (chatElement, container) => { + const surface = chatElement.closest(`.${SESSIONS_CHAT_SURFACE_CLASS}`); + const source = surface ? Array.from(surface.children).find(element => element.classList.contains('sessions-chat-background')) : undefined; + if (!isHTMLElement(source)) { + return undefined; + } + const replica = new SessionsChatBackgroundReplica(source, container); + return { + updateBackground: () => replica.setBackground(backgroundService.getBackground()), + layout: () => replica.layout(), + dispose: () => replica.dispose(), + }; + }, + }, + }; + } + + createChatBackground(container: HTMLElement, instantiationService: IInstantiationService): IDisposable { + return instantiationService.createInstance(SessionsChatSurface, container); + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chat/externalSessionBanner.ts b/src/vs/workbench/contrib/sessions/browser/chat/externalSessionBanner.ts index cbf42ea0157d..884c366628de 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/externalSessionBanner.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/externalSessionBanner.ts @@ -261,7 +261,7 @@ export class ExternalSessionBanner extends Disposable { mode: ChatExternalSessionsMode.Recent, item: { text: localize('externalSessionBanner.select.recent', "Recent"), - description: localize('externalSessionBanner.select.recent.description', "Show up to the 2 most recent external sessions updated in the last 7 days. Once at least 2 local sessions exist, external sessions older than the second-newest local session are hidden."), + description: localize('externalSessionBanner.select.recent.description', "Show the 2 most recently updated external sessions from the last 7 days, hiding any that are older than your 2 newest local sessions."), }, }, { diff --git a/src/vs/workbench/contrib/sessions/browser/chat/media/chatInput.css b/src/vs/workbench/contrib/sessions/browser/chat/media/chatInput.css index 38a0ae7c77ae..e31030787bad 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/media/chatInput.css +++ b/src/vs/workbench/contrib/sessions/browser/chat/media/chatInput.css @@ -46,6 +46,7 @@ * Outside the Agents window it still outranks chat.css's input margin and * padding by specificity rather than stylesheet order. */ .agent-sessions-workbench .new-chat-input-container.sessions-shared-chat-input .sessions-shared-chat-widget .interactive-session .interactive-input-part, +.sessions-chat .new-chat-input-container.sessions-shared-chat-input .sessions-shared-chat-widget .interactive-session .interactive-input-part, .new-chat-input-container .interactive-session .interactive-input-part { margin: 0; padding: 0; @@ -94,7 +95,8 @@ overflow: visible; } -.agent-sessions-workbench:not(.phone-layout) .chat-view-chat.experimental-session-composer .chat-input-container > .chat-context-usage-container { +.agent-sessions-workbench:not(.phone-layout) .chat-view-chat.experimental-session-composer .chat-input-container > .chat-context-usage-container, +.chat-view-chat.experimental-session-composer.sessions-chat:not(.phone-layout *) .chat-input-container > .chat-context-usage-container { position: absolute; top: var(--vscode-spacing-size120); right: calc(var(--vscode-spacing-size60) - 3px); @@ -102,7 +104,9 @@ } .agent-sessions-workbench:not(.phone-layout) .chat-view-chat.experimental-session-composer .chat-input-toolbar .action-item.model-picker-item, -.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .chat-input-toolbar .action-item.model-picker-item { +.chat-view-chat.experimental-session-composer.sessions-chat:not(.phone-layout *) .chat-input-toolbar .action-item.model-picker-item, +.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .chat-input-toolbar .action-item.model-picker-item, +.sessions-chat:not(.phone-layout *) .experimental-new-session-composer .chat-input-toolbar .action-item.model-picker-item { margin-left: auto; } @@ -190,7 +194,7 @@ padding: 0 var(--vscode-spacing-size60); background-color: transparent; border: none; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); cursor: pointer; touch-action: manipulation; color: var(--vscode-icon-foreground); diff --git a/src/vs/workbench/contrib/sessions/browser/chat/media/chatView.css b/src/vs/workbench/contrib/sessions/browser/chat/media/chatView.css index fefa076b2601..12c0bd308a26 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/media/chatView.css +++ b/src/vs/workbench/contrib/sessions/browser/chat/media/chatView.css @@ -156,28 +156,34 @@ /* Full width; their existing auto margins center them. */ .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .chat-view-chat .interactive-session > .interactive-input-part, -.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .chat-view-chat .interactive-session > .chat-suggest-next-widget { +:is(.part.sessionspart, .sessions-window-host) .chat-view-chat.sessions-chat .interactive-session > .interactive-input-part, +.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .chat-view-chat .interactive-session > .chat-suggest-next-widget, +:is(.part.sessionspart, .sessions-window-host) .chat-view-chat.sessions-chat .interactive-session > .chat-suggest-next-widget { width: 100%; margin-left: auto; margin-right: auto; } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows { background-color: transparent; } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.chat-sticky-progress { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.chat-sticky-progress, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-item-container.chat-sticky-progress { --vscode-chat-list-background: var(--vscode-editorWidget-background, var(--session-view-background)); inset-inline: var(--session-view-content-horizontal-padding, var(--vscode-spacing-size240)); padding-inline: var(--vscode-spacing-size120); } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-item-container.interactive-response { padding: var(--vscode-spacing-size80) calc(var(--session-view-content-horizontal-padding, var(--vscode-spacing-size240)) + var(--vscode-spacing-size120)); isolation: isolate; } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response::before { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response::before, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-item-container.interactive-response::before { content: ''; position: absolute; inset: 0 var(--session-view-content-horizontal-padding, var(--vscode-spacing-size240)); @@ -187,7 +193,9 @@ } .monaco-workbench.agent-sessions-workbench.hc-black :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response::before, -.monaco-workbench.agent-sessions-workbench.hc-light :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response::before { +.monaco-workbench.hc-black :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-item-container.interactive-response::before, +.monaco-workbench.agent-sessions-workbench.hc-light :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-item-container.interactive-response::before, +.monaco-workbench.hc-light :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-item-container.interactive-response::before { box-sizing: border-box; border: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder); } @@ -197,74 +205,95 @@ * to the opaque session view rather than `button.secondaryBackground`, which is * transparent in the default dark themes. */ .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .action-label, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .chat-context-usage-widget { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .action-label, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .chat-context-usage-widget, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .chat-context-usage-widget { background-color: var(--vscode-chat-list-background, var(--vscode-button-secondaryBackground)); background-image: linear-gradient(var(--vscode-button-secondaryBackground), var(--vscode-button-secondaryBackground)); border: var(--vscode-strokeThickness) solid var(--vscode-button-secondaryBorder); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-button-secondaryForeground); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .action-label:not(.agent-host-mode-permissions-trigger):hover, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .chat-context-usage-widget:hover { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .action-label:not(.agent-host-mode-permissions-trigger):hover, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .chat-context-usage-widget:hover, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .chat-context-usage-widget:hover { background-image: linear-gradient(var(--vscode-button-secondaryHoverBackground), var(--vscode-button-secondaryHoverBackground)); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .action-label.agent-host-mode-permissions-trigger:hover, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'] { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .action-label.agent-host-mode-permissions-trigger:hover, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .chat-secondary-toolbar .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'], +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .chat-secondary-toolbar .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'] { background-image: linear-gradient(var(--vscode-button-secondaryHoverBackground), var(--vscode-button-secondaryHoverBackground)); } .agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown, -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-item-container.interactive-request .value .chat-attached-context .chat-attached-context-attachment:not(.image-attachment) { +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown, +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-item-container.interactive-request .value .chat-attached-context .chat-attached-context-attachment:not(.image-attachment), +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .interactive-item-container.interactive-request .value .chat-attached-context .chat-attached-context-attachment:not(.image-attachment) { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-requestBubbleBackground), var(--vscode-chat-requestBubbleBackground)); } -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown.clickable:hover { +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown.clickable:hover, +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown.clickable:hover { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-requestBubbleHoverBackground), var(--vscode-chat-requestBubbleHoverBackground)); } -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-request-origin:not(.delegation) { +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-request-origin:not(.delegation), +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .chat-request-origin:not(.delegation) { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-requestBubbleBackground), var(--vscode-chat-requestBubbleBackground)); } -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-request-origin:not(.delegation):hover { +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-request-origin:not(.delegation):hover, +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .chat-request-origin:not(.delegation):hover { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-requestBubbleHoverBackground), var(--vscode-chat-requestBubbleHoverBackground)); } -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-action-request > .chat-action-request-card { +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .chat-action-request > .chat-action-request-card, +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .chat-action-request > .chat-action-request-card { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-statusBackground), var(--vscode-chat-statusBackground)); } /* The edit input takes the place of the request bubble, so it needs the same opaque base under the translucent bubble tint. */ .agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-input-part.editing .chat-input-container, -.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-request.editing .interactive-input-part .chat-input-container { +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .interactive-input-part.editing .chat-input-container, +.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .interactive-request.editing .interactive-input-part .chat-input-container, +:is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .interactive-request.editing .interactive-input-part .chat-input-container { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-chat-requestBubbleBackground), var(--vscode-chat-requestBubbleBackground)); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-container .monaco-toolbar .action-item:not(.confirming) > .action-label, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .checkpoint-container .monaco-toolbar .action-item:not(.confirming) > .action-label, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label { background-color: var(--session-view-background); border-color: var(--vscode-chat-requestBorder, var(--vscode-input-background)); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-container .monaco-toolbar .action-item:not(.confirming) > .action-label:hover, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label:hover { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .checkpoint-container .monaco-toolbar .action-item:not(.confirming) > .action-label:hover, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label:hover, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-session .checkpoint-restore-container .monaco-toolbar .action-item:not(.confirming) > .action-label:hover { background-image: linear-gradient(var(--vscode-toolbar-hoverBackground), var(--vscode-toolbar-hoverBackground)); } -.agent-sessions-workbench .interactive-session { +.agent-sessions-workbench .interactive-session, +.sessions-chat .interactive-session { max-width: none; } .monaco-workbench.vs.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows, -.monaco-workbench.vs-dark.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows { +.monaco-workbench.vs :is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows, +.monaco-workbench.vs-dark.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows, +.monaco-workbench.vs-dark :is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-list-rows { background: transparent !important; > .monaco-list-row { @@ -279,7 +308,8 @@ } } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-tree-sticky-container { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-tree-sticky-container, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-list > .monaco-list > .monaco-scrollable-element > .monaco-tree-sticky-container { background-color: transparent; --vscode-chat-list-background: transparent; @@ -289,18 +319,21 @@ } } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view .interactive-list > .monaco-list > .monaco-scrollable-element, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .chat-view.sessions-chat .interactive-list > .monaco-list > .monaco-scrollable-element { > .shadow.top, > .monaco-tree-sticky-container > .monaco-tree-sticky-container-shadow { display: none; } } -.agent-sessions-workbench .interactive-list > .monaco-list.mouse-support > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { +.agent-sessions-workbench .interactive-list > .monaco-list.mouse-support > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row, +.sessions-chat .interactive-list > .monaco-list.mouse-support > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { cursor: default; } -.agent-sessions-workbench .interactive-session .chat-scroll-down { +.agent-sessions-workbench .interactive-session .chat-scroll-down, +.sessions-chat .interactive-session .chat-scroll-down { /* Keep the arrow inside a short transcript (`.interactive-list` is its containing block) when a tall composer leaves little room. */ bottom: max(0px, min(calc(var(--vscode-spacing-size80) + var(--vscode-chat-persistent-content-height, 0px)), calc(100% - var(--vscode-spacing-size240)))); /* Keep the arrow clickable above the prompt timeline rail (15). */ @@ -308,11 +341,14 @@ } .agent-sessions-workbench .interactive-session.chat-transcript-progress-active > .interactive-list, -.agent-sessions-workbench .interactive-session.chat-transcript-context-active > .interactive-list { +.sessions-chat .interactive-session.chat-transcript-progress-active > .interactive-list, +.agent-sessions-workbench .interactive-session.chat-transcript-context-active > .interactive-list, +.sessions-chat .interactive-session.chat-transcript-context-active > .interactive-list { position: relative; } -.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-context { +.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-context, +.sessions-chat .interactive-session > .interactive-list > .chat-transcript-context { position: absolute; top: var(--vscode-spacing-size320); left: 0; @@ -327,11 +363,13 @@ pointer-events: none; } -.agent-sessions-workbench .chat-transcript-context > .chat-attached-context-attachment { +.agent-sessions-workbench .chat-transcript-context > .chat-attached-context-attachment, +.sessions-chat .chat-transcript-context > .chat-attached-context-attachment { pointer-events: auto; } -.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-progress { +.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-progress, +.sessions-chat .interactive-session > .interactive-list > .chat-transcript-progress { position: absolute; top: var(--vscode-spacing-size320); left: 0; @@ -340,18 +378,23 @@ pointer-events: none; } -.agent-sessions-workbench .interactive-session.chat-transcript-context-active > .interactive-list > .chat-transcript-progress { +.agent-sessions-workbench .interactive-session.chat-transcript-context-active > .interactive-list > .chat-transcript-progress, +.sessions-chat .interactive-session.chat-transcript-context-active > .interactive-list > .chat-transcript-progress { top: calc(var(--vscode-spacing-size320) + var(--vscode-spacing-size320)); } .agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-context[hidden], -.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-progress[hidden] { +.sessions-chat .interactive-session > .interactive-list > .chat-transcript-context[hidden], +.agent-sessions-workbench .interactive-session > .interactive-list > .chat-transcript-progress[hidden], +.sessions-chat .interactive-session > .interactive-list > .chat-transcript-progress[hidden] { display: none; } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .interactive-item-container:not(.chat-sticky-progress), +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .interactive-item-container:not(.chat-sticky-progress), .agent-sessions-workbench .chat-editor-relative .interactive-session .interactive-item-container:not(.chat-sticky-progress), .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session > .chat-suggest-next-widget, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session > .chat-suggest-next-widget, .agent-sessions-workbench .chat-editor-relative .interactive-session > .chat-suggest-next-widget { max-width: var(--session-view-centered-content-max-width, 950px); margin: 0 auto; @@ -361,29 +404,34 @@ } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .interactive-item-container:not(.chat-sticky-progress), +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .interactive-item-container:not(.chat-sticky-progress), .agent-sessions-workbench .chat-editor-relative .interactive-session .interactive-item-container:not(.chat-sticky-progress) { position: relative; } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-list .monaco-list-row.request > .monaco-tl-row > .monaco-tl-contents, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-list .monaco-list-row.request > .monaco-tl-row > .monaco-tl-contents, .agent-sessions-workbench .chat-editor-relative .interactive-list .monaco-list-row.request > .monaco-tl-row > .monaco-tl-contents { overflow: visible; } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .interactive-item-container.interactive-request .value > .chat-markdown-part.rendered-markdown a[data-href]:focus-visible:not(.chat-rich-link), +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .interactive-item-container.interactive-request .value > .chat-markdown-part.rendered-markdown a[data-href]:focus-visible:not(.chat-rich-link), .agent-sessions-workbench .chat-editor-relative .interactive-session .interactive-item-container.interactive-request .value > .chat-markdown-part.rendered-markdown a[data-href]:focus-visible:not(.chat-rich-link) { outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); outline-offset: var(--vscode-spacing-size20); } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown:has(.interactive-result-code-block), +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown:has(.interactive-result-code-block), .agent-sessions-workbench .chat-editor-relative .interactive-session .interactive-item-container.interactive-request .value .rendered-markdown:has(.interactive-result-code-block) { max-width: 100%; } /* ---- Chat Output ---- */ -.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .monaco-scrollable-element > .shadow.top { +.agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .monaco-scrollable-element > .shadow.top, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .monaco-scrollable-element > .shadow.top { height: 16px; background: linear-gradient(to bottom, var(--part-background), transparent); box-shadow: none; @@ -395,44 +443,54 @@ box-shadow: none; } -.agent-sessions-workbench .interactive-session .interactive-response .interactive-result-code-block { +.agent-sessions-workbench .interactive-session .interactive-response .interactive-result-code-block, +.sessions-chat .interactive-session .interactive-response .interactive-result-code-block { border-color: var(--vscode-editorWidget-border, var(--vscode-widget-border)); } /* ---- Chat Input ---- */ .agent-sessions-workbench .interactive-session .interactive-input-part > .chat-input-persistent-content, -.agent-sessions-workbench .interactive-session .interactive-input-part > .chat-input-persistent-content > .chat-sticky-progress { +.sessions-chat .interactive-session .interactive-input-part > .chat-input-persistent-content, +.agent-sessions-workbench .interactive-session .interactive-input-part > .chat-input-persistent-content > .chat-sticky-progress, +.sessions-chat .interactive-session .interactive-input-part > .chat-input-persistent-content > .chat-sticky-progress { padding-inline: inherit; } -.monaco-workbench.agent-sessions-workbench .interactive-session .chat-input-container { +.monaco-workbench.agent-sessions-workbench .interactive-session .chat-input-container, +.monaco-workbench .sessions-chat .interactive-session .chat-input-container { border-color: var(--vscode-agentsChatInput-border) !important; background-color: var(--vscode-agentsChatInput-background); color: var(--vscode-agentsChatInput-foreground); } -.agent-sessions-workbench .interactive-session .chat-input-container.focused { +.agent-sessions-workbench .interactive-session .chat-input-container.focused, +.sessions-chat .interactive-session .chat-input-container.focused { border-color: var(--vscode-agentsChatInput-focusBorder, var(--vscode-focusBorder)) !important; } -.agent-sessions-workbench .interactive-session .chat-input-container.working:not(.focused) { +.agent-sessions-workbench .interactive-session .chat-input-container.working:not(.focused), +.sessions-chat .interactive-session .chat-input-container.working:not(.focused) { border-color: var(--vscode-agentsChatInput-border) !important; } -.agent-sessions-workbench .interactive-session .chat-input-container.working.focused { +.agent-sessions-workbench .interactive-session .chat-input-container.working.focused, +.sessions-chat .interactive-session .chat-input-container.working.focused { border-color: color-mix(in srgb, var(--vscode-agentsChatInput-focusBorder, var(--vscode-focusBorder)) 40%, transparent) !important; } -.agent-sessions-workbench .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor { +.agent-sessions-workbench .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor, +.sessions-chat .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor { background-color: transparent; } -.agent-sessions-workbench .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor .monaco-editor-background { +.agent-sessions-workbench .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor .monaco-editor-background, +.sessions-chat .interactive-session .interactive-input-part .chat-editor-container .interactive-input-editor .monaco-editor .monaco-editor-background { background-color: var(--vscode-agentsChatInput-background); } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .interactive-input-part, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .interactive-input-part, .agent-sessions-workbench .chat-editor-relative .interactive-session .interactive-input-part { width: 100%; max-width: var(--session-view-centered-content-max-width, 950px); @@ -443,31 +501,40 @@ } .agent-sessions-workbench :is(.part.sessionspart, .sessions-window-host) .interactive-session .chat-edit-input-container .interactive-input-part, +:is(.part.sessionspart, .sessions-window-host) .sessions-chat .interactive-session .chat-edit-input-container .interactive-input-part, .agent-sessions-workbench .chat-editor-relative .interactive-session .chat-edit-input-container .interactive-input-part { padding: var(--vscode-spacing-size80) 0 var(--vscode-spacing-size40); } /* The single-row composer has no secondary toolbar row for the timestamp to share. */ -.agent-sessions-workbench:not(.phone-layout) .chat-view-chat.experimental-session-composer .interactive-request.editing .chat-request-timestamp-container { +.agent-sessions-workbench:not(.phone-layout) .chat-view-chat.experimental-session-composer .interactive-request.editing .chat-request-timestamp-container, +.chat-view-chat.experimental-session-composer.sessions-chat:not(.phone-layout *) .interactive-request.editing .chat-request-timestamp-container { margin-top: 0; } -.agent-sessions-workbench .interactive-session .chat-input-toolbars .chat-sessionPicker-container { +.agent-sessions-workbench .interactive-session .chat-input-toolbars .chat-sessionPicker-container, +.sessions-chat .interactive-session .chat-input-toolbars .chat-sessionPicker-container { display: none; } -.agent-sessions-workbench:not(.phone-layout) .interactive-session .chat-input-toolbars { +.agent-sessions-workbench:not(.phone-layout) .interactive-session .chat-input-toolbars, +.sessions-chat:not(.phone-layout *) .interactive-session .chat-input-toolbars { column-gap: var(--vscode-spacing-size80); } -.agent-sessions-workbench .interactive-session .compact-picker .sessions-chat-dropdown-label { +.agent-sessions-workbench .interactive-session .compact-picker .sessions-chat-dropdown-label, +.sessions-chat .interactive-session .compact-picker .sessions-chat-dropdown-label { display: none; } .agent-sessions-workbench .interactive-session .compact-picker .sessions-chat-picker-slot, +.sessions-chat .interactive-session .compact-picker .sessions-chat-picker-slot, .agent-sessions-workbench .interactive-session .sessions-chat-picker-slot.compact-picker, +.sessions-chat .interactive-session .sessions-chat-picker-slot.compact-picker, .agent-sessions-workbench .interactive-session .compact-picker .sessions-chat-picker-slot .action-label, -.agent-sessions-workbench .interactive-session .sessions-chat-picker-slot.compact-picker .action-label { +.sessions-chat .interactive-session .compact-picker .sessions-chat-picker-slot .action-label, +.agent-sessions-workbench .interactive-session .sessions-chat-picker-slot.compact-picker .action-label, +.sessions-chat .interactive-session .sessions-chat-picker-slot.compact-picker .action-label { box-sizing: border-box; width: 22px; height: 22px; @@ -477,7 +544,9 @@ } .agent-sessions-workbench .interactive-session .compact-picker .sessions-chat-picker-slot .action-label > .codicon, -.agent-sessions-workbench .interactive-session .sessions-chat-picker-slot.compact-picker .action-label > .codicon { +.sessions-chat .interactive-session .compact-picker .sessions-chat-picker-slot .action-label > .codicon, +.agent-sessions-workbench .interactive-session .sessions-chat-picker-slot.compact-picker .action-label > .codicon, +.sessions-chat .interactive-session .sessions-chat-picker-slot.compact-picker .action-label > .codicon { width: var(--vscode-codiconFontSize-compact); height: var(--vscode-codiconFontSize-compact); line-height: var(--vscode-codiconFontSize-compact); diff --git a/src/vs/workbench/contrib/sessions/browser/chat/media/chatWidget.css b/src/vs/workbench/contrib/sessions/browser/chat/media/chatWidget.css index 89c76284f903..8e8c93dd3fc2 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/media/chatWidget.css +++ b/src/vs/workbench/contrib/sessions/browser/chat/media/chatWidget.css @@ -131,7 +131,8 @@ margin-bottom: 0; } -.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-session-quick-chat-header { +.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-session-quick-chat-header, +.sessions-chat:not(.phone-layout *) .experimental-new-session-composer .new-session-quick-chat-header { width: 100%; margin: var(--vscode-spacing-size120) 0 0; padding: var(--vscode-spacing-size40) var(--vscode-spacing-size80) var(--vscode-spacing-size60); @@ -149,17 +150,20 @@ border-radius: var(--vscode-cornerRadius-large); } -.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-session-workspace-picker-container .new-chat-session-options { +.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-session-workspace-picker-container .new-chat-session-options, +.sessions-chat:not(.phone-layout *) .experimental-new-session-composer .new-session-workspace-picker-container .new-chat-session-options { max-width: calc(100% - 2 * (var(--vscode-spacing-size100) + var(--vscode-strokeThickness))); margin-inline: calc(var(--vscode-spacing-size100) + var(--vscode-strokeThickness)); } -.monaco-workbench.agent-sessions-workbench .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options { +.monaco-workbench.agent-sessions-workbench .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options, +.monaco-workbench .sessions-chat .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options { background-color: color-mix(in srgb, var(--vscode-agentsChatInput-background) 75%, var(--session-view-background)); border-radius: var(--vscode-cornerRadius-large) var(--vscode-cornerRadius-large) 0 0; } -.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options { +.monaco-workbench.agent-sessions-workbench:is(.hc-black, .hc-light) .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options, +.monaco-workbench:is(.hc-black, .hc-light) .sessions-chat .sessions-chat-widget .new-chat-widget-content.experimental-new-session-composer .new-chat-session-options { background-color: var(--vscode-agentsChatInput-background); } @@ -255,7 +259,7 @@ margin-left: var(--vscode-spacing-size80); padding: 0; border: 0; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-descriptionForeground); font-size: var(--vscode-codiconFontSize-compact); cursor: pointer; @@ -298,7 +302,7 @@ padding: var(--vscode-spacing-size20) var(--vscode-spacing-size60); background: transparent; border: var(--vscode-strokeThickness) solid transparent; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-descriptionForeground); font-size: var(--vscode-fontSize-label1); line-height: var(--vscode-spacing-size160); @@ -443,7 +447,8 @@ display: none; } -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container { overflow: hidden; } @@ -510,15 +515,20 @@ /* Expanded picker controls never shrink or ellipsize. */ .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .monaco-action-bar .action-item:not(.compact-picker), +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .monaco-action-bar .action-item:not(.compact-picker), .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker), -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .action-label { +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker), +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .action-label, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .action-label { flex-shrink: 0; min-width: 30px; overflow: visible; } .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .monaco-action-bar .action-item.repository-config-separator, -.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-chat-repo-config-container .monaco-action-bar .action-item.repository-config-separator { +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .monaco-action-bar .action-item.repository-config-separator, +.agent-sessions-workbench:not(.phone-layout) .experimental-new-session-composer .new-chat-repo-config-container .monaco-action-bar .action-item.repository-config-separator, +.sessions-chat:not(.phone-layout *) .experimental-new-session-composer .new-chat-repo-config-container .monaco-action-bar .action-item.repository-config-separator { min-width: 0; } @@ -530,7 +540,9 @@ } .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .sessions-chat-dropdown-label, -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .chat-session-option-label { +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .sessions-chat-dropdown-label, +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .chat-session-option-label, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .sessions-chat-picker-slot:not(.compact-picker) .chat-session-option-label { flex-shrink: 0; overflow: visible; text-overflow: clip; @@ -547,7 +559,9 @@ } .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.action-item, -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot { +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.action-item, +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot { box-sizing: border-box; width: var(--chat-input-control-height); height: var(--chat-input-control-height); @@ -556,7 +570,9 @@ } .agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.action-item .action-label, -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label { +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.action-item .action-label, +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label { box-sizing: border-box; width: var(--chat-input-control-height); height: var(--chat-input-control-height); @@ -565,13 +581,15 @@ padding: 0; } -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label > .codicon { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label > .codicon, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-picker-slot .action-label > .codicon { width: var(--vscode-codiconFontSize-compact); height: var(--vscode-codiconFontSize-compact); line-height: var(--vscode-codiconFontSize-compact); } -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-checkbox-chip .monaco-checkbox { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-checkbox-chip .monaco-checkbox, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .compact-picker.sessions-chat-checkbox-chip .monaco-checkbox { width: 12px; height: 12px; margin-right: 0; @@ -617,15 +635,18 @@ /* Over a chat background, use the same opaque secondary-control surface as the * in-session toolbar rather than relying on the transparent session view. */ .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .action-label:not(.separator), -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .action-label:not(.separator), +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label { background-color: var(--vscode-chat-list-background, var(--session-view-background)); background-image: linear-gradient(var(--vscode-button-secondaryBackground), var(--vscode-button-secondaryBackground)); border: var(--vscode-strokeThickness) solid var(--vscode-button-secondaryBorder); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-button-secondaryForeground); } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar { box-sizing: border-box; height: var(--chat-input-control-height); background-color: var(--vscode-chat-list-background, var(--session-view-background)); @@ -635,7 +656,8 @@ color: var(--vscode-button-secondaryForeground); } -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar .action-label:not(.separator) { +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar .action-label:not(.separator), +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container .monaco-action-bar .action-label:not(.separator) { background-color: transparent; background-image: none; border: none; @@ -646,25 +668,33 @@ } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container:hover .monaco-action-bar, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container[data-picker-open='true'] .monaco-action-bar { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container:hover .monaco-action-bar, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container[data-picker-open='true'] .monaco-action-bar, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .new-chat-repo-config-container[data-picker-open='true'] .monaco-action-bar { background-image: linear-gradient(var(--vscode-button-secondaryHoverBackground), var(--vscode-button-secondaryHoverBackground)); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .action-label:not(.agent-host-mode-permissions-trigger):not(.disabled):hover, +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .action-label:not(.agent-host-mode-permissions-trigger):not(.disabled):hover, .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label:not(.disabled):hover, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label[aria-expanded='true'] { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label:not(.disabled):hover, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label[aria-expanded='true'], +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .experimental-new-session-composer .sessions-chat-picker-slot.sessions-workspace-category-picker-slot:not(.new-chat-session-options *) .action-label[aria-expanded='true'] { background-image: linear-gradient(var(--vscode-button-secondaryHoverBackground), var(--vscode-button-secondaryHoverBackground)); } .monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .action-label.agent-host-mode-permissions-trigger:hover, -.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'] { +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .action-label.agent-host-mode-permissions-trigger:hover, +.monaco-workbench.agent-sessions-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .new-chat-widget-container .new-chat-bottom-container .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'], +.monaco-workbench :is(.part.sessionspart, .sessions-chat-surface).has-chat-background .sessions-chat .new-chat-widget-container .new-chat-bottom-container .action-label.agent-host-mode-permissions-trigger[data-mode-permissions-picker-open='true'] { background-image: linear-gradient(var(--vscode-button-secondaryHoverBackground), var(--vscode-button-secondaryHoverBackground)); } /* Outranks the shared action-bar hover in workbench style.css, which would * otherwise swap the opaque surface for a translucent one. The tint goes on the * background-image layer so it composites over that surface. */ -.monaco-workbench.agent-sessions-workbench .new-chat-widget-container .new-chat-bottom-container .action-label:not(.agent-host-mode-permissions-trigger):not(.disabled):hover { +.monaco-workbench.agent-sessions-workbench .new-chat-widget-container .new-chat-bottom-container .action-label:not(.agent-host-mode-permissions-trigger):not(.disabled):hover, +.monaco-workbench .sessions-chat .new-chat-widget-container .new-chat-bottom-container .action-label:not(.agent-host-mode-permissions-trigger):not(.disabled):hover { background-color: var(--session-view-background); background-image: linear-gradient(var(--vscode-toolbar-hoverBackground), var(--vscode-toolbar-hoverBackground)); } @@ -682,12 +712,14 @@ } /* Icon status actions use the compact control box; text actions remain intrinsic. */ -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .monaco-action-bar .action-item.new-chat-status-icon-action { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .monaco-action-bar .action-item.new-chat-status-icon-action, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .monaco-action-bar .action-item.new-chat-status-icon-action { width: 22px; min-width: 22px; } -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label { box-sizing: border-box; display: flex; align-items: center; @@ -698,7 +730,8 @@ padding: 0; } -.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label.codicon { +.agent-sessions-workbench:not(.phone-layout) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label.codicon, +.sessions-chat:not(.phone-layout *) .new-chat-widget-container .new-chat-bottom-container .new-chat-status-toolbar .new-chat-status-icon-action .action-label.codicon { font-size: var(--vscode-codiconFontSize-compact); } @@ -745,7 +778,7 @@ padding: 0 var(--vscode-spacing-size40); background-color: transparent; border-color: transparent; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); color: var(--vscode-icon-foreground); font-size: var(--vscode-fontSize-label2); } @@ -941,7 +974,7 @@ cursor: pointer; touch-action: manipulation; white-space: nowrap; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); min-width: 0; overflow: hidden; } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/media/newChatInSession.css b/src/vs/workbench/contrib/sessions/browser/chat/media/newChatInSession.css index ea4c775695b3..2c7e16a28caf 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/media/newChatInSession.css +++ b/src/vs/workbench/contrib/sessions/browser/chat/media/newChatInSession.css @@ -10,11 +10,22 @@ /* * The frame, the row layout and the dismiss button all come from * `.chat-input-notice`; only the two content elements are styled here. + * + * The icon box takes the tip's font size so that `1.4em` is the text's line box; + * the glyph keeps the codicon size and centers in it, on the first line of text + * at any chat font size. */ -.new-chat-in-session .sub-session-tip-icon { +.new-chat-in-session .sub-session-tip-icon.codicon { flex-shrink: 0; + display: flex; + align-items: center; + font-size: inherit; + height: 1.4em; color: var(--vscode-descriptionForeground); - transform: translateY(2px); +} + +.new-chat-in-session .sub-session-tip-icon.codicon::before { + font-size: var(--vscode-codiconFontSize); } .new-chat-in-session .sub-session-tip-text { diff --git a/src/vs/workbench/contrib/sessions/browser/chat/modelPicker.ts b/src/vs/workbench/contrib/sessions/browser/chat/modelPicker.ts new file mode 100644 index 000000000000..578791fff05a --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chat/modelPicker.ts @@ -0,0 +1,322 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js'; +import { onUnexpectedError } from '../../../../../base/common/errors.js'; +import { autorun, derived, IObservable, ISettableObservable, observableValue } from '../../../../../base/common/observable.js'; +import { localize2 } from '../../../../../nls.js'; +import { BaseActionViewItem } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { IActionViewItemService } from '../../../../../platform/actions/browser/actionViewItemService.js'; +import { Action2, registerAction2 } from '../../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; +import { IWorkbenchContribution } from '../../../../common/contributions.js'; +import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; +import { IChatInputPickerOptions } from '../../../chat/browser/widget/input/chatInputPickerActionItem.js'; +import { IModelPickerDelegate, ModelPickerActionItem } from '../../../chat/browser/widget/input/modelPicker/modelPickerActionItem.js'; +import { IChatPhoneInputPresenter } from '../../../chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { ChatPetAchievementIds, didExplicitlySwitchChatPetModel } from '../../../chat/browser/chatPetAchievements.js'; +import { IChatPetService } from '../../../chat/browser/chatPetService.js'; +import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { getAgentHostProviderForTelemetry, IChatSessionsService } from '../../../chat/common/chatSessionsService.js'; +import { IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; +import { LOCAL_AGENT_HOST_PROVIDER_ID } from '../../common/agentHostSessionsProvider.js'; +import { Menus } from '../menus.js'; +import { IsPhoneLayoutContext, SessionUsesCombinedConfigPickerContext } from '../../common/contextkeys.js'; +import { ISessionHost } from '../../../../services/sessions/browser/sessionHost.js'; +import { createChatPhoneInputSessionContext } from '../chatPhoneInputContext.js'; +import { SessionStatus } from '../../../../services/sessions/common/session.js'; +import { ISessionModelSelection } from './sessionModelSelection.js'; +import { INewChatModelPickerService } from './newChatModelPicker.js'; +import { reportNewChatPickerClosed } from '../newChatPickerTelemetry.js'; + +/** + * The sessions-core model picker. Unlike the previous per-provider pickers, + * this single widget reads the model list from the active session's provider + * via {@link ISessionsProvider.getModelsSnapshot}, remembers explicit model choices per + * shared or targeted model pool, and applies the selection through the existing + * {@link ISessionsProvider.setModel} API. It reuses the shared workbench + * {@link ModelPickerActionItem} so the dropdown looks and behaves like the + * other chat model pickers. + */ +export class ModelPicker extends Disposable { + + private readonly _delegate: IModelPickerDelegate; + private readonly _modelPicker: ModelPickerActionItem; + private _container: HTMLElement | undefined; + private _phonePickerOpen = false; + + constructor( + compact: IObservable, + @IInstantiationService instantiationService: IInstantiationService, + @ITelemetryService private readonly _telemetryService: ITelemetryService, + @INewChatModelPickerService private readonly _newChatModelPickerService: INewChatModelPickerService, + @IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService, + @IChatEntitlementService private readonly _chatEntitlementService: IChatEntitlementService, + @ISessionHost private readonly _sessionHost: ISessionHost, + @ISessionModelSelection private readonly _selectionModel: ISessionModelSelection, + @IChatPetService private readonly _chatPetService: IChatPetService, + @IChatSessionsService private readonly _chatSessionsService: IChatSessionsService, + @IAgentHostService private readonly _agentHostService: IAgentHostService, + @IChatPhoneInputPresenter phonePresenter: IChatPhoneInputPresenter, + ) { + super(); + const currentModel = derived(this, reader => this._selectionModel.state.read(reader).currentModel); + + this._delegate = { + comparison: this._selectionModel.comparison, + comparisonBusy: this._selectionModel.comparisonBusy, + showPicker: (anchor, configuration) => { + if (!phonePresenter.supportsUnifiedConfiguration) { + return false; + } + if (this._phonePickerOpen) { + return true; + } + this._phonePickerOpen = true; + anchor.setAttribute('aria-expanded', 'true'); + void phonePresenter.showCombinedModeAndModelSheet(anchor, { + kind: 'session', + getSessionContext: () => createChatPhoneInputSessionContext(this._sessionHost.session.get(), this._sessionHost.chat.get()), + modelDelegate: this._delegate, + initialSection: configuration ? 'modelConfiguration' : 'model', + }).finally(() => { + this._phonePickerOpen = false; + anchor.setAttribute('aria-expanded', 'false'); + }).catch(onUnexpectedError); + return true; + }, + currentModel, + modelConfiguration: this._selectionModel.modelConfiguration, + focusInput: () => this._newChatModelPickerService.focusInput(), + setModel: model => { + const previousModel = this._selectionModel.state.get().currentModel; + if (this._selectionModel.selectModel(model.identifier)) { + if (didExplicitlySwitchChatPetModel(previousModel?.identifier, model.identifier)) { + this._chatPetService.unlockAchievement(ChatPetAchievementIds.ModelSwitch); + } + reportNewChatPickerClosed(this._telemetryService, { + id: 'NewChatModelPicker', + optionIdBefore: previousModel?.identifier, + optionIdAfter: model.identifier, + optionLabelBefore: previousModel?.metadata.name, + optionLabelAfter: model.metadata.name, + isPII: false, + }); + } + }, + setModelProgrammatically: model => { + this._selectionModel.selectModel(model.identifier, false); + }, + getModels: () => [...this._selectionModel.state.get().models], + getAgentModelPreferences: () => this._selectionModel.state.get().agentModelPreferences, + getComparisonModels: () => [...(this._selectionModel.getComparisonModels?.() ?? this._selectionModel.state.get().models)], + getProvider: () => getAgentHostProviderForTelemetry(this._sessionHost.session.get()?.sessionType, this._chatSessionsService), + getSessionType: () => { + const state = this._selectionModel.state.get(); + return (state.currentModel ?? state.models[0])?.metadata.targetChatSessionType; + }, + // On-device models are offered only by the local Agent Host. + getLocalModelConnection: () => !this._selectionModel.state.get().agentModelPreferences?.required + && this._sessionHost.session.get()?.providerId === LOCAL_AGENT_HOST_PROVIDER_ID ? this._agentHostService : undefined, + getPresentationOptions: () => ({ + ...this._selectionModel.state.get().options, + showModelIcon: true, + }), + isCacheWarm: () => { + const session = this._sessionHost.session.get(); + // The session's prompt cache is warm once its first request has + // been sent (status leaves Untitled), matching the main-window + // picker which warms as soon as the first request is added. + return session ? session.status.get() !== SessionStatus.Untitled : false; + }, + }; + + const pickerOptions: IChatInputPickerOptions = { + compact, + minimal: compact, + }; + const action = { id: 'sessions.modelPicker', label: '', enabled: true, class: undefined, tooltip: '', run: () => { } }; + this._modelPicker = this._register(instantiationService.createInstance(ModelPickerActionItem, action, this._delegate, pickerOptions)); + this._register(this._newChatModelPickerService.registerModelPicker({ + getDomNode: () => this._container, + open: () => this._modelPicker.openModelPicker(), + openComparison: () => { + if (this._selectionModel.comparison?.available.get()) { + this._modelPicker.show(undefined, { startComparison: true }); + } + }, + switchToModel: modelIdentifier => this.switchToModel(modelIdentifier), + })); + this._register(autorun(reader => { + phonePresenter.enabled.read(reader); + if (phonePresenter.supportsUnifiedConfiguration) { + reader.store.add(phonePresenter.registerSessionModelPicker({ + getSessionContext: () => createChatPhoneInputSessionContext(this._sessionHost.session.read(undefined), this._sessionHost.chat.read(undefined)), + modelDelegate: this._delegate, + selectModel: identifier => this.switchToModel(identifier), + })); + } + })); + + this._register(autorun(reader => { + this._selectionModel.state.read(reader); + this._updatePickerState(); + })); + + // Re-evaluate when workspace trust changes (or finishes initializing): an + // untrusted workspace disables the model providers, and the shared widget + // then renders its Restricted Mode state. Visibility is recomputed so the + // picker stays visible to surface the "Models" placeholder + the Trust + // action instead of hiding as an empty picker. + this._register(this._workspaceTrustManagementService.onDidChangeTrust(() => this._updatePickerState())); + this._workspaceTrustManagementService.workspaceTrustInitialized.then(() => { + if (!this._store.isDisposed) { + this._updatePickerState(); + } + }); + + // Re-evaluate when entitlement / sentiment / anonymous access change: when + // Chat needs sign-in the shared widget renders a Sign In state, so the + // picker stays visible to surface it (e.g. after the user signs out/in). + this._register(this._chatEntitlementService.onDidChangeEntitlement(() => this._updatePickerState())); + this._register(this._chatEntitlementService.onDidChangeSentiment(() => this._updatePickerState())); + this._register(this._chatEntitlementService.onDidChangeAnonymous(() => this._updatePickerState())); + } + + render(container: HTMLElement): void { + this._container = container; + this._modelPicker.render(container); + this._updatePickerState(); + } + + switchToModel(modelIdentifier: string): boolean { + return this._selectionModel.selectModel(modelIdentifier); + } + + show(anchor?: HTMLElement): void { + this._modelPicker.show(anchor); + } + + /** + * Whether the model picker should be shown for the given session. Visible + * when the session has models, when its Auto model is unavailable (so the + * widget can render the "No models available" empty state), or when the + * workspace is untrusted / Chat still needs sign-in (so the widget can render + * its Restricted Mode or Sign In state). Otherwise hidden, matching the + * historical behavior for providers that offer no models. + */ + private _shouldShowPicker(): boolean { + const state = this._selectionModel.state.get(); + if (state.models.length > 0) { + return true; + } + if (this._modelPicker.isRestrictedMode() || this._modelPicker.isSetupRequired()) { + return true; + } + return !state.options.showAutoModel; + } + + private _updatePickerState(): void { + const visible = this._shouldShowPicker(); + this._modelPicker.setEnabled(visible); + this._updateVisibility(visible); + } + + private _updateVisibility(visible: boolean): void { + if (this._container) { + this._container.style.display = visible ? '' : 'none'; + } + } +} + +// -- Action View Item -- + +export class ModelPickerActionViewItem extends BaseActionViewItem { + constructor(private readonly picker: ModelPicker, private readonly compact?: ISettableObservable) { + super(undefined, { id: '', label: '', enabled: true, class: undefined, tooltip: '', run: () => { } }); + } + + override render(container: HTMLElement): void { + this.picker.render(container); + } + + isCompact(): boolean { + return this.compact?.get() ?? false; + } + + setCompact(compact: boolean): void { + this.compact?.set(compact, undefined); + } + + show(anchor?: HTMLElement): void { + this.picker.show(anchor); + } + + override dispose(): void { + this.picker.dispose(); + super.dispose(); + } +} + +/** Renders the Agents window model picker in the composer and Automations dialog toolbars. */ +export class ModelPickerToolbarsContribution extends Disposable implements IWorkbenchContribution { + static readonly ID = 'sessions.contrib.modelPickerToolbars'; + + constructor( + @IActionViewItemService actionViewItemService: IActionViewItemService, + ) { + super(); + for (const menu of [Menus.AutomationsDialogInputToolbar, Menus.NewSessionChatInputToolbar]) { + this._register(actionViewItemService.register(menu, 'sessions.modelPicker', (_action, _options, instantiationService) => { + const compact = observableValue(this, false); + const picker = instantiationService.createInstance(ModelPicker, compact); + return new ModelPickerActionViewItem(picker, compact); + })); + } + } +} + +/** + * Registers the model picker action of the new-session composer, until the returned disposable is disposed. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerModelPickerAction(): IDisposable { + const store = new DisposableStore(); + + store.add(registerAction2(class extends Action2 { + constructor() { + super({ + id: 'sessions.modelPicker', + title: localize2('sessionsModelPicker', "Model"), + f1: false, + menu: [{ + id: Menus.AutomationsDialogInputToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + ChatContextKeys.inAutomationsDialog, + ContextKeyExpr.or(IsPhoneLayoutContext.negate(), SessionUsesCombinedConfigPickerContext.negate()), + ), + }, { + id: Menus.NewSessionChatInputToolbar, + group: 'navigation', + order: 1, + // Hidden on phone when the active provider supplies a combined + // mode + model picker instead (see MobileChatInputConfigPicker). + when: ContextKeyExpr.or(IsPhoneLayoutContext.negate(), SessionUsesCombinedConfigPickerContext.negate()), + }], + }); + } + override async run(): Promise { /* handled by action view item */ } + })); + + return store; +} diff --git a/src/vs/workbench/contrib/sessions/browser/chat/nestedChatWorkspacePicker.ts b/src/vs/workbench/contrib/sessions/browser/chat/nestedChatWorkspacePicker.ts index b0fc615b612f..658632f8c141 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/nestedChatWorkspacePicker.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/nestedChatWorkspacePicker.ts @@ -184,7 +184,7 @@ export class NestedChatWorkspaceControls extends Disposable { private readonly _sessionFolderMissing = observableValue(this, false); /** Checks whether the preselected session folder still exists; settles once it is known or can't be told. */ private _folderCheck: Promise | undefined; - /** Settles once a {@link refresh} has re-read its folder (or was superseded), which restores the kept worktree choice. */ + /** Settles once a {@link refresh} has re-read its folder (or was superseded), validating the kept worktree choice. */ private _refreshResolution: Promise | undefined; private readonly _branches = observableValue(this, []); private readonly _resolve = this._register(new MutableDisposable()); @@ -226,11 +226,16 @@ export class NestedChatWorkspaceControls extends Disposable { return support && folder ? toNestedChatWorkspace(support, folder, this._worktree.get(), this._folderInfo.get(), this._branch.get()) : undefined; } - /** {@link getWorkspace} once a pending check of the session folder is done, so a chat never starts in a missing folder. */ + /** {@link getWorkspace} once the latest checks of the session folder and refreshed capabilities are done. */ async resolveWorkspace(): Promise { - // Until a refresh re-reads its folder, the kept worktree choice reads as "no worktree". - await Promise.all([this._folderCheck, this._refreshResolution]); - return this.getWorkspace(); + while (true) { + const folderCheck = this._folderCheck; + const refreshResolution = this._refreshResolution; + await Promise.all([folderCheck, refreshResolution]); + if (folderCheck === this._folderCheck && refreshResolution === this._refreshResolution) { + return this.getWorkspace(); + } + } } /** Back to the session's default, e.g. after the chat was sent. */ @@ -252,17 +257,19 @@ export class NestedChatWorkspaceControls extends Disposable { this.reset(); return; } - this._select(folder, { worktree: this._worktree.get(), branch: this._branch.get() }); + this._select(folder, true); } - private _select(choice: NestedChatFolderChoice | undefined, keep?: { readonly worktree: boolean; readonly branch: string | undefined }): void { + private _select(choice: NestedChatFolderChoice | undefined, keepSelection = false): void { const store = new DisposableStore(); this._resolve.value = store; transaction(tx => { this._folder.set(choice, tx); - this._worktree.set(false, tx); - this._branch.set(undefined, tx); - this._folderInfo.set(undefined, tx); + if (!keepSelection) { + this._worktree.set(false, tx); + this._branch.set(undefined, tx); + this._folderInfo.set(undefined, tx); + } this._branches.set([], tx); }); // "No workspace" and folders without Git have no worktree: only folders are resolved. @@ -294,15 +301,16 @@ export class NestedChatWorkspaceControls extends Disposable { } transaction(tx => { this._folderInfo.set(info, tx); - this._worktree.set(!!keep?.worktree && info.supportsWorktree, tx); - this._branch.set(keep?.worktree && info.supportsWorktree ? keep.branch ?? info.defaultBranch : info.defaultBranch, tx); + this._worktree.set(keepSelection && this._worktree.get() && info.supportsWorktree, tx); + this._branch.set(this._worktree.get() ? this._branch.get() ?? info.defaultBranch : info.defaultBranch, tx); }); }, error => { if (!cts.token.isCancellationRequested) { + this._folderInfo.set(undefined, undefined); onUnexpectedError(error); } }); - if (keep) { + if (keepSelection) { // Settle when superseded too, as a cancelled resolution may never answer. const refreshResolution = raceCancellation(resolution, cts.token).then(() => undefined); this._refreshResolution = refreshResolution; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/newChatWidget.ts b/src/vs/workbench/contrib/sessions/browser/chat/newChatWidget.ts index 2acb515751b6..4d0cf2a7294b 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/newChatWidget.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/newChatWidget.ts @@ -24,7 +24,7 @@ import { IInstantiationService } from '../../../../../platform/instantiation/com import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; -import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; import { observableConfigValue } from '../../../../../platform/observable/common/platformObservableUtils.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; @@ -101,7 +101,9 @@ import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/ import { ISessionsRecentWorkspacesService } from '../sessionsRecentWorkspacesService.js'; import { filterConfigurationToSchema } from '../../../chat/browser/widget/input/chatModelConfigurationLogic.js'; import { createSessionComparisonHarness } from '../sessionComparisonConfiguration.js'; -import { SESSIONS_LIST_INBOX_ENABLED_SETTING } from '../../common/sessionConfig.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { SessionsView, SessionsViewId } from '../views/sessionsView.js'; +import { SessionsGrouping } from '../views/sessionsList.js'; // #region --- New Chat Widget --- @@ -144,6 +146,16 @@ export function isSessionEnvironmentPickerEnabled(configurationService: IConfigu && configurationService.getValue(ENVIRONMENT_PICKER_SETTING) === true; } +/** + * Whether focus is in an input, a textarea or an editor. A workspace selection the user didn't make, such as + * the folder handoff of an Agents window that finishes during startup, must not move focus away from there, or + * the rest of what the user types, for example an SSH password in a quick input, lands in the composer. + */ +function isTypingInEditableElement(): boolean { + const activeElement = dom.getActiveElement(); + return !!activeElement && dom.isEditableElement(activeElement); +} + export class NewChatWidget extends Disposable { private readonly _usage: AgentsWindowUsage; @@ -242,6 +254,7 @@ export class NewChatWidget extends Disposable { }, @IInstantiationService private readonly instantiationService: IInstantiationService, @IContextKeyService private readonly contextKeyService: IContextKeyService, + @IViewsService private readonly viewsService: IViewsService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService private readonly configurationService: IConfigurationService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @@ -370,7 +383,8 @@ export class NewChatWidget extends Disposable { const selectedProvider = providerId ? this.sessionsProvidersService.getProvider(providerId) : undefined; const selected = picked ? environments.find(environment => environment.id === picked.id) ?? picked - : getDefaultSessionCreationEnvironment(environments, this._workspacePicker?.selectedFolderUri, providerId, !!containerRequested, selectedProvider); + : getDefaultSessionCreationEnvironment(environments, this._workspacePicker?.selectedFolderUri, providerId, !!containerRequested, selectedProvider, + this._workspacePicker?.preselectionSource === NewSessionWorkspacePreselectionSource.CheckedWorkspace); return selected && previous?.id === selected.id && previous.label === selected.label && previous.providerIds.length === selected.providerIds.length && previous.providerIds.every((id, index) => id === selected.providerIds[index]) ? previous : selected; @@ -465,8 +479,8 @@ export class NewChatWidget extends Disposable { observableFromEvent(this, Event.filter(this.configurationService.onDidChangeConfiguration, event => event.affectsConfiguration(COMPARE_AGENTS_SHOW_PICKER_HINT_SETTING)), () => this.configurationService.getValue(COMPARE_AGENTS_SHOW_PICKER_HINT_SETTING)), derived(this, reader => { - const session = this._session.read(reader); - return !session || session.loading.read(reader) || comparisonConfigResolving.read(reader); + comparisonWorkspaceChanged.read(reader); + return this._isComparisonPending(reader, comparisonConfigResolving); }))); const canSendRequest = derived(reader => { const session = this._session.read(reader); @@ -527,7 +541,7 @@ export class NewChatWidget extends Disposable { canApplyWorkspaceDefault: () => this._canApplyWorkspaceDefault(), sendRequest: async ({ query, attachments, background, userInteraction }) => this._send(query, attachments, background, userInteraction), inputSnapshot: this._draftHost?.input, - get preserveInputFocusOnSend() { return backgroundSend || configurationService.getValue(SESSIONS_LIST_INBOX_ENABLED_SETTING) === true; }, + get preserveInputFocusOnSend() { return backgroundSend || viewsService.getViewWithId(SessionsViewId)?.grouping === SessionsGrouping.Inbox; }, confirmSend: async query => this._comparisonSelection.enabled.get() || !this._worktreeSuggestion || this._worktreeSuggestion.confirmBeforeSend(query), modelPickerComparison: this._comparisonSelection, sendButtonLabel: derived(this, reader => this._comparisonSelection.enabled.read(reader) @@ -617,7 +631,7 @@ export class NewChatWidget extends Disposable { } })); - this._register(this._workspacePicker.onDidSelectWorkspace(folderUri => this._handleWorkspaceSelection(folderUri))); + this._register(this._workspacePicker.onDidSelectWorkspace(folderUri => this._handleWorkspaceSelection(folderUri, this._workspacePicker.selectionSnapshot.origin !== WorkspaceSelectionOrigin.User))); this._register(this._workspacePicker.onDidSelectWorkspaceMode(({ folderUri, preferDevContainer }) => { const environment = this._environment.get(); this._preferredDevContainerFolderUri = preferDevContainer || environment?.kind === 'container' ? folderUri : undefined; @@ -1888,7 +1902,7 @@ export class NewChatWidget extends Disposable { const submenuActions = providers.length > 1 ? providers.map(provider => { const action = toAction({ - id: `newSessionWorkspacePicker.quickChat.${provider.id}`, + id: 'newSessionWorkspacePicker.quickChat', label: getQuickChatProviderLabel(provider), checked: provider.id === activeProviderId, run: () => { @@ -2112,6 +2126,27 @@ export class NewChatWidget extends Disposable { return undefined; } + private _isComparisonPending(reader: IReader, configurationResolving: IObservable): boolean { + const session = this._session.read(reader); + if (!session || session.loading.read(reader) || configurationResolving.read(reader)) { + return true; + } + const selectedFolder = this._workspacePicker.selectedFolderUri; + const workspace = session.workspace.read(reader); + if (!selectedFolder) { + return workspace !== undefined; + } + const folder = workspace?.folders.find(folder => isEqual(folder.root, selectedFolder)); + if (!folder) { + return true; + } + const provider = this.sessionsProvidersService.getProvider(session.providerId, session.sessionId); + const config = provider && isAgentHostProvider(provider) ? provider.getSessionConfig(session.sessionId, session.mainChat.read(reader).resource) : undefined; + // The host resolves worktree support before publishing the draft's Git metadata. + return !!config && getSessionWorkspaceProperties(config.schema).isolation?.schema.enum?.includes('worktree') === true + && folder.gitRepository?.isRepository?.read(reader) !== true; + } + private _getComparisonModelIds(): Set { return new Set(this._newChatInput.getComparisonModels() .filter(isModelComparisonSupported) @@ -2415,7 +2450,7 @@ export class NewChatWidget extends Disposable { private async _send(query: string, attachedContext?: IChatRequestVariableEntry[], background?: boolean, userInteraction?: NewChatUserInteraction): Promise { background = this._backgroundSend || background; // A composer of a host of its own, such as a chat window's, shows the status of its background sends. - const showBackgroundSendStatus = this._backgroundSend || !!background && (!!this._draftHost || this.configurationService.getValue(SESSIONS_LIST_INBOX_ENABLED_SETTING) === true); + const showBackgroundSendStatus = this._backgroundSend || !!background && (!!this._draftHost || this.viewsService.getViewWithId(SessionsViewId)?.grouping === SessionsGrouping.Inbox); if (showBackgroundSendStatus) { this._lastBackgroundSentSessionResource = undefined; this._lastBackgroundSentSession = undefined; @@ -2501,7 +2536,12 @@ export class NewChatWidget extends Disposable { )(event => { clearFeedback(); restoreWorkspace(); - if (showBackgroundSendStatus && this._lastBackgroundSendOptions === sendOptions && !this._newChatInput.hasInput) { + if (!this._backgroundSend && !this._draftHost) { + this.notificationService.prompt(Severity.Info, localize('newSession.messageSent', "Message sent"), [{ + label: localize('newSession.openSentSession', "Open Session"), + run: () => this.sessionsService.openSession(event.session.resource, { source: 'link', forceMainChat: true }).catch(onUnexpectedError), + }]); + } else if (showBackgroundSendStatus && this._lastBackgroundSendOptions === sendOptions && !this._newChatInput.hasInput) { this._lastBackgroundSentSessionResource = event.session.resource; this._lastBackgroundSentSession = event.session; this._backgroundSendStatus.set(localize('newSession.messageSent', "Message sent"), undefined); @@ -2743,7 +2783,10 @@ export class NewChatWidget extends Disposable { this._newChatInput.focus(); } - private async _handleWorkspaceSelection(folderUri: URI | undefined): Promise { + /** + * @param notByUser The selection was not made by the user, for example the folder handoff of an Agents window. + */ + private async _handleWorkspaceSelection(folderUri: URI | undefined, notByUser?: boolean): Promise { const host = this._draftHost; if (host?.setRequestedTarget) { // In a Dev Container only as the user picked it, in the environment the folder was picked in. @@ -2752,7 +2795,7 @@ export class NewChatWidget extends Disposable { if (!this._isCurrentWorkspaceSelection(folderUri)) { await this._onWorkspaceSelected(folderUri); } - if (folderUri || !this._workspaceOptOutEnabled.get()) { + if ((folderUri || !this._workspaceOptOutEnabled.get()) && !(notByUser && isTypingInEditableElement())) { this._newChatInput.focus(); } } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/newSessionConfigToolbars.ts b/src/vs/workbench/contrib/sessions/browser/chat/newSessionConfigToolbars.ts new file mode 100644 index 000000000000..7ebb534608fa --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chat/newSessionConfigToolbars.ts @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { Menus } from '../menus.js'; +import { IHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegate.js'; + +/** Creates the provider-owned control toolbar shared by New Session configuration surfaces. */ +export function createNewSessionControlToolbar(container: HTMLElement, instantiationService: IInstantiationService, ariaLabel?: string, hoverDelegate?: IHoverDelegate): MenuWorkbenchToolBar { + return instantiationService.createInstance(MenuWorkbenchToolBar, container, Menus.NewSessionControl, { + ariaLabel, + hoverDelegate, + hiddenItemStrategy: HiddenItemStrategy.NoHide, + }); +} diff --git a/src/vs/workbench/contrib/sessions/browser/chat/newWorktreeChoice.ts b/src/vs/workbench/contrib/sessions/browser/chat/newWorktreeChoice.ts new file mode 100644 index 000000000000..c9e630e7128b --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chat/newWorktreeChoice.ts @@ -0,0 +1,165 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { onUnexpectedError } from '../../../../../base/common/errors.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { IObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { getSessionIsolationProperty, ISessionConfigProperty, isSessionConfigWritable, readSessionIsolation, writeSessionIsolation } from '../../../../../platform/agentHost/common/sessionConfigProperties.js'; +import { ISession, isSessionCreated } from '../../../../services/sessions/common/session.js'; +import { IAgentHostSessionsProvider, isAgentHostProvider } from '../../common/agentHostSessionsProvider.js'; +import { ISessionsProvidersService } from '../sessionsProvidersService.js'; +import { IWorkspacePickerNewWorktreeOption } from './sessionWorkspacePicker.js'; + +interface IDraftIsolation { + readonly provider: IAgentHostSessionsProvider; + readonly session: ISession; + readonly chat: URI; + readonly property: ISessionConfigProperty; + readonly isolation: string | undefined; +} + +interface IDraftChoice { + /** Whether the user chose New Worktree for the draft. */ + chosen: boolean; + /** + * Whether it set the draft's isolation to its folder by default once: it does not set it again by itself, also where + * the agent keeps a new worktree, which then shows as selected. The user's own choice still writes. + */ + defaulted: boolean; + /** The latest of the user's choices for the draft, which alone is undone as the agent rejects it. */ + latestChoice: number; + /** The latest write to the draft's isolation that the agent has not taken yet: the draft's isolation will be its target. */ + pending: { readonly target: string } | undefined; +} + +/** + * What is known of each draft, as long as the draft lives and across the composers that show it: a composer that sends its + * drafts in the background and starts new ones keeps nothing of the drafts that went, and a draft shown again, such as as its + * editor moves to another group, keeps the user's choice. + */ +const draftChoices = new WeakMap(); + +/** Fires for a draft as a write to its isolation settles, which changes what the draft shows as selected. */ +const onDidSettleDraft = new Emitter(); + +/** + * New Worktree for a composer restricted to its folders, such as an editor window's: its draft works in a new worktree of + * the selected folder, through its agent's isolation setting, which its own isolation picker sets in the Agents window. + * A draft works in its folder unless the user chose New Worktree for it, whatever isolation its agent remembers. + */ +export class NewWorktreeChoice implements IWorkspacePickerNewWorktreeOption { + + /** + * @param _enabled Whether the composer is restricted to its folders: none restrict it, and it offers no New Worktree. + */ + constructor( + private readonly _session: IObservable, + private readonly _enabled: IObservable, + @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, + ) { } + + /** Fires as what the current draft shows changes without a change of its configuration: a write settles or is undone. */ + readonly onDidChange: Event = Event.map(Event.filter(onDidSettleDraft.event, session => session === this._session.get()), () => undefined); + + isAvailable(): boolean { + return !!this._draftIsolation(); + } + + isSelected(): boolean { + const draft = this._draftIsolation(); + return !!draft && this._isolationOf(draft) === 'worktree'; + } + + setSelected(selected: boolean): void { + const draft = this._draftIsolation(); + if (!draft) { + return; + } + // The choice is known before the agent takes it: its configuration can change, and apply the default, meanwhile + const state = this._stateOf(draft.session); + const wasChosen = state.chosen; + state.chosen = selected; + const choice = ++state.latestChoice; + this._write(draft, state, selected, () => { + // The agent did not take it: unless the user chose again since, the draft is as before + if (state.latestChoice === choice) { + state.chosen = wasChosen; + } + }); + } + + /** Makes the current draft work in its folder, once, unless the user chose New Worktree for it. */ + applyDefault(): void { + const draft = this._draftIsolation(); + if (!draft || this._isolationOf(draft) !== 'worktree') { + return; + } + const state = this._stateOf(draft.session); + if (!state.chosen && !state.defaulted) { + state.defaulted = true; + this._write(draft, state, false); + } + } + + private _stateOf(session: ISession): IDraftChoice { + let state = draftChoices.get(session); + if (!state) { + state = { chosen: false, defaulted: false, latestChoice: 0, pending: undefined }; + draftChoices.set(session, state); + } + return state; + } + + /** The isolation the draft has or is about to have: the agent can take a write later than the choice. */ + private _isolationOf(draft: IDraftIsolation): string | undefined { + return draftChoices.get(draft.session)?.pending?.target ?? draft.isolation; + } + + private _write(draft: IDraftIsolation, state: IDraftChoice, worktree: boolean, onDidReject?: () => void): void { + const target = worktree ? 'worktree' : 'folder'; + const value = writeSessionIsolation(draft.property, target); + if (value === undefined || this._isolationOf(draft) === target) { + return; + } + const operation = draft.provider.setSessionConfigValue(draft.session.sessionId, draft.chat, draft.property.key, value); + draft.provider.trackSessionConfigOperation(draft.session.sessionId, operation); + const pending = state.pending = { target }; + const settle = () => { + if (state.pending === pending) { + state.pending = undefined; + } + }; + operation.then(() => { + settle(); + onDidSettleDraft.fire(draft.session); + }, error => { + settle(); + onDidReject?.(); + onDidSettleDraft.fire(draft.session); + onUnexpectedError(error); + }); + } + + /** The isolation of the current draft, when its agent lets it work in a new worktree and the setting can change. */ + private _draftIsolation(): IDraftIsolation | undefined { + const session = this._session.get(); + if (!this._enabled.get() || !session || isSessionCreated(session) || session.isQuickChat?.get()) { + return undefined; + } + const provider = this._sessionsProvidersService.getProvider(session.providerId, session.sessionId); + if (!provider || !isAgentHostProvider(provider)) { + return undefined; + } + const values = provider.getCreateSessionConfig(session.sessionId); + const chat = session.mainChat.get().resource; + const config = values && provider.getSessionConfig(session.sessionId, chat); + const property = config && getSessionIsolationProperty(config.schema); + if (!values || !property || !isSessionConfigWritable(property.schema, true) || writeSessionIsolation(property, 'worktree') === undefined) { + return undefined; + } + return { provider, session, chat, property, isolation: readSessionIsolation(property, values[property.key] ?? property.schema.default) }; + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.ts b/src/vs/workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.ts index ff575994223c..0fc5a658d02e 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/promptTemplatePlaceholder.ts @@ -3,13 +3,15 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Disposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { KeyCode } from '../../../../../base/common/keyCodes.js'; +import { Disposable, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { ICodeEditor, MouseTargetType } from '../../../../../editor/browser/editorBrowser.js'; import { Position } from '../../../../../editor/common/core/position.js'; import { Selection } from '../../../../../editor/common/core/selection.js'; import { IEditorDecorationsCollection } from '../../../../../editor/common/editorCommon.js'; import { localize } from '../../../../../nls.js'; import { IContextKey, RawContextKey } from '../../../../../platform/contextkey/common/contextkey.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; export const REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID = 'sessions.chat.replacePromptTemplatePlaceholder'; export const PromptTemplatePlaceholderFocused = new RawContextKey('sessionsPromptTemplatePlaceholderFocused', false, localize('sessionsPromptTemplatePlaceholderFocused', "Whether the caret is inside an editable prompt template placeholder.")); @@ -20,6 +22,20 @@ export function replaceActivePromptTemplatePlaceholder(): void { activePromptTemplatePlaceholderController?.replaceAtCursor(); } +/** + * Registers the command that replaces the placeholder under the caret, bound to Enter while the + * caret is inside one, until the returned disposable is disposed. + */ +export function registerReplacePromptTemplatePlaceholderCommand(): IDisposable { + return KeybindingsRegistry.registerCommandAndKeybindingRule({ + id: REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID, + weight: KeybindingWeight.WorkbenchContrib + 2, + when: PromptTemplatePlaceholderFocused, + primary: KeyCode.Enter, + handler: () => replaceActivePromptTemplatePlaceholder(), + }); +} + /** Highlights and replaces the editable task placeholder in an onboarding prompt. */ export class PromptTemplatePlaceholderController extends Disposable { private static readonly _className = 'sessions-prompt-template-placeholder'; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sessionArchiveNudge.ts b/src/vs/workbench/contrib/sessions/browser/chat/sessionArchiveNudge.ts index aeca84f910f6..3bea5ccbfe0e 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sessionArchiveNudge.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sessionArchiveNudge.ts @@ -27,8 +27,9 @@ import { IOnboardingScenarioService, ONBOARDING_ENABLED_CONFIG } from '../../../ import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; import { IViewsService } from '../../../../services/views/common/viewsService.js'; import { hashSessionIdForTelemetry } from '../../common/sessionsTelemetry.js'; -import { getSessionOwnedGitHubPullRequestRefs, IChat, isActiveSessionStatus, ISession, SessionArtifactKind, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { getChatCapabilities, getSessionOwnedGitHubPullRequestRefs, IChat, isActiveSessionStatus, ISession, SessionArtifactKind, SessionStatus } from '../../../../services/sessions/common/session.js'; import { ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { ISessionsService } from '../sessionsService.js'; import { IGitHubService } from '../github/githubService.js'; import { GitHubPullRequestState } from '../../common/github/types.js'; import { getPullRequestKey } from '../../common/github/utils.js'; @@ -44,7 +45,10 @@ const IMPRESSION_STORAGE_KEY_PREFIX = 'sessions.archiveNudge.impression.'; const ARCHIVE_COUNT_STORAGE_KEY = 'sessions.archiveNudge.archiveCount'; const COMPACT_AFTER_ARCHIVE_COUNT = 3; -/** The chat whose input shows the suggestion, and the session the suggestion archives. */ +/** + * The chat whose input shows the suggestion. The suggestion archives only that chat, except in the session's + * main chat, which lives and dies with its session. + */ export interface ISessionArchiveNudgeTarget { readonly session: ISession; readonly chat: IChat; @@ -52,6 +56,8 @@ export interface ISessionArchiveNudgeTarget { interface ISessionArchiveNudgeState { readonly session: ISession; + /** The chat archived on its own; absent when the suggestion archives the whole session from its main chat. */ + readonly chat?: IChat; readonly hasWorktree: boolean; readonly pullRequestCount: number; } @@ -98,15 +104,17 @@ type SessionArchiveNudgeEvent = { action: 'shown' | 'dismissed' | 'archived'; pullRequestCount: number; hasWorktree: boolean; + archivesChat: boolean; }; type SessionArchiveNudgeClassification = { owner: 'benibenj'; comment: 'Tracks exposure to and interaction with the session archive suggestion after GitHub pull requests associated with the session have merged.'; agentSessionId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'SHA-1 hash of the globally unique session identifier, matching session lifecycle events without exposing provider or resource details.' }; - action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the suggestion was shown, dismissed, or used to archive the session.' }; + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the suggestion was shown, dismissed, or used to archive the session or its chat.' }; pullRequestCount: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of distinct merged GitHub pull requests from the artifacts and session-owned associations of the chat showing the suggestion.' }; hasWorktree: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the suggestion explained worktree cleanup.' }; + archivesChat: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether the suggestion archives only the chat showing it rather than the whole session from its main chat.' }; }; export class SessionArchiveNudgeService extends Disposable implements ISessionArchiveNudgeService { @@ -216,9 +224,14 @@ export class SessionArchiveNudgeService extends Disposable implements ISessionAr } async archive(state: ISessionArchiveNudgeState): Promise { - await this._sessionsManagementService.archiveSession(state.session); - if (!state.session.isArchived.get()) { - throw new Error(localize('sessionArchiveNudge.updateFailed', "The session could not be updated. Check its connection and try again.")); + if (state.chat) { + // Providers reject chat archiving they cannot perform. + await this._sessionsManagementService.archiveChat(state.session, state.chat); + } else { + await this._sessionsManagementService.archiveSession(state.session); + if (!state.session.isArchived.get()) { + throw new Error(localize('sessionArchiveNudge.updateFailed', "The session could not be updated. Check its connection and try again.")); + } } const archiveCount = this._storageService.getNumber(ARCHIVE_COUNT_STORAGE_KEY, StorageScope.PROFILE, 0); this._storageService.store(ARCHIVE_COUNT_STORAGE_KEY, Math.min(archiveCount + 1, COMPACT_AFTER_ARCHIVE_COUNT), StorageScope.PROFILE, StorageTarget.MACHINE); @@ -287,6 +300,7 @@ export class SessionArchiveNudgeService extends Disposable implements ISessionAr action, pullRequestCount: state.pullRequestCount, hasWorktree: state.hasWorktree, + archivesChat: !!state.chat, }); } } @@ -396,6 +410,7 @@ export class SessionArchiveNudge extends Disposable { @IGitHubService gitHubService: IGitHubService, @ISessionArchiveNudgeService private readonly _nudgeService: ISessionArchiveNudgeService, @ICommandService commandService: ICommandService, + @ISessionsService private readonly _sessionsService: ISessionsService, ) { super(); @@ -408,6 +423,11 @@ export class SessionArchiveNudge extends Disposable { if (!current || !isSessionAvailableForArchiveNudge(current.session, reader)) { return undefined; } + // Another chat cannot fall back to archiving the whole session. + if (!isEqual(current.chat.resource, current.session.mainChat.read(reader).resource) + && (current.chat.isArchived.read(reader) || !getChatCapabilities(current.chat, current.session, reader).canArchive)) { + return undefined; + } if (!this._nudgeService.experimentTriggerPending.read(reader) && (!enabled.read(reader) || this._nudgeService.isDismissed(current.session, reader))) { return undefined; } @@ -430,12 +450,13 @@ export class SessionArchiveNudge extends Disposable { this._state = derivedOpts({ owner: this, equalsFn: (a: ISessionArchiveNudgeCandidate | undefined, b: ISessionArchiveNudgeCandidate | undefined) => - a?.session === b?.session && a?.hasWorktree === b?.hasWorktree && structuralEquals(a?.pullRequestKeys, b?.pullRequestKeys), + a?.session === b?.session && a?.chat === b?.chat && a?.hasWorktree === b?.hasWorktree && structuralEquals(a?.pullRequestKeys, b?.pullRequestKeys), }, reader => { - const current = eligibleTarget.read(reader)?.session; - if (!current) { + const eligible = eligibleTarget.read(reader); + if (!eligible) { return undefined; } + const current = eligible.session; const refs = pullRequests.read(reader); if (!refs?.length) { return undefined; @@ -445,10 +466,13 @@ export class SessionArchiveNudge extends Disposable { if (!pullRequestCount || !pullRequestModels?.every(model => model.pullRequest.read(reader)?.state === GitHubPullRequestState.Merged)) { return undefined; } + const chat = isEqual(eligible.chat.resource, current.mainChat.read(reader).resource) ? undefined : eligible.chat; const workspace = current.workspace.read(reader); return { session: current, - hasWorktree: !!workspace && !workspace.isVirtualWorkspace && (!!current.worktreePending?.read(reader) || workspace.folders.some(folder => !!folder.gitRepository?.workTreeUri)), + chat, + // Archiving a chat on its own keeps the session's worktree. + hasWorktree: !chat && !!workspace && !workspace.isVirtualWorkspace && (!!current.worktreePending?.read(reader) || workspace.folders.some(folder => !!folder.gitRepository?.workTreeUri)), pullRequestCount, pullRequestKeys: refs.map(ref => getPullRequestKey(ref.owner, ref.repo, ref.number)), }; @@ -461,20 +485,29 @@ export class SessionArchiveNudge extends Disposable { this.options = this._state.map((state, reader) => state && enabled.read(reader) && !this._nudgeService.isDismissed(state.session, reader) ? { hasWorktree: state.hasWorktree, pullRequestCount: state.pullRequestCount, + archivesChat: !!state.chat, compact: this._nudgeService.shouldShowCompact(reader), onDismiss: () => this._nudgeService.dismiss(state), onOpenCleanupSettings: () => commandService.executeCommand('workbench.action.openSettings', AUTOMATIC_MERGED_SESSION_CLEANUP_SETTINGS_QUERY), onArchive: async () => { - this._getArchiveState(state.session); - await this._nudgeService.showArchiveOnboarding(state.session); - await this._nudgeService.archive(this._getArchiveState(state.session)); + this._getArchiveState(state); + // The onboarding reveals the session's action in the sessions list, which would archive every chat. + if (!state.chat) { + await this._nudgeService.showArchiveOnboarding(state.session); + } + const archiveState = this._getArchiveState(state); + await this._nudgeService.archive(archiveState); + if (archiveState.chat) { + // Like Mark as Done on a chat, set the archived chat aside while its session and other chats stay open. + await this._sessionsService.closeChat(archiveState.session, archiveState.chat); + } }, } : undefined); } - private _getArchiveState(session: ISession): ISessionArchiveNudgeState { + private _getArchiveState(expected: ISessionArchiveNudgeState): ISessionArchiveNudgeState { const state = this._state.get(); - if (!state || state.session !== session || this._store.isDisposed) { + if (!state || state.session !== expected.session || state.chat !== expected.chat || this._store.isDisposed) { throw new Error(localize('sessionArchiveNudge.noLongerAvailable', "This suggestion is no longer available. Review the session before trying again.")); } return state; diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sessionArtifacts.ts b/src/vs/workbench/contrib/sessions/browser/chat/sessionArtifacts.ts index 0c11d6d6d2f0..137e79a31e67 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sessionArtifacts.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sessionArtifacts.ts @@ -627,14 +627,17 @@ class SessionGitHubCommitResolver extends Disposable { /** Publishes a session's artifact and reference sections for the chat input pills. */ export class SessionArtifacts extends Disposable { private readonly presentations = observableValue>(this, new Map()); + /** The IDs of the focused chat's records that are artifacts rather than references. */ + private readonly _artifactIds: IObservable>; /** Sections for the artifacts pill: what the session produced. */ readonly sections: IObservable; /** Sections for the references pill: what the session points the user at. */ readonly referenceSections: IObservable; /** - * Undecorated entries of the artifacts and references an integration presents in pills of their own, because their - * main integration assigns them a group ID; see {@link getPresentation}. The sections list the other integrated records. + * Undecorated entries of the artifacts an integration presents in pills of their own, because their main integration + * assigns them a group ID; see {@link getPresentation}. The sections list the other integrated records, including + * every reference. */ readonly integratedEntries: IObservable; @@ -673,6 +676,7 @@ export class SessionArtifacts extends Disposable { const gitHubResolver = this._register(new GitHubResourceDetailsResolver(workbenchGitHubService, logService)); // The session publishes every chat's records; this surface shows only the focused chat's, like the GitHub pills. const chatArtifacts = derived(this, reader => getChatSessionArtifacts(session.read(reader), chat.read(reader), reader)); + this._artifactIds = derived(this, reader => new Set(chatArtifacts.read(reader).filter(artifact => artifact.isArtifact).map(artifact => artifact.id))); this._register(autorun(reader => { const current = session.read(reader); const artifacts = chatArtifacts.read(reader); @@ -833,11 +837,13 @@ export class SessionArtifacts extends Disposable { }); // Integrated records listed in the pills for their kind show once per resource, like those in pills of their own. + // An artifact with a pill of its own never stands in for them: the pill's filters can hide it, and its pins are + // kept apart, so a reference to its resource stays listed with the other references. const hiddenAliases = derived(this, reader => { const integrated = presentations.read(reader); const candidates = chatArtifacts.read(reader).flatMap(artifact => { const snapshot = integrated.get(artifact.id)?.snapshot.read(reader); - return snapshot && snapshot.contributions.length > 0 && getArtifactIntegrationGroupId(snapshot) === undefined + return snapshot && snapshot.contributions.length > 0 && !this.hasOwnPill(artifact.id, reader) ? [{ id: artifact.id, isArtifact: artifact.isArtifact, ...getArtifactIntegrationAliasCandidate(snapshot) }] : []; }); const kept = new Set(collapseArtifactIntegrationAliases(candidates).map(candidate => candidate.id)); @@ -902,8 +908,14 @@ export class SessionArtifacts extends Disposable { return this.presentations.read(reader).get(id); } - /** Whether an integration presents the record in a pill of its own, rather than in the pill for its kind. */ + /** + * Whether an integration presents the record in a pill of its own, rather than in the pill for its kind. Only artifacts + * do; references stay in the References pill with the other references, whatever their group ID. + */ hasOwnPill(id: string, reader: IReader): boolean { + if (!this._artifactIds.read(reader).has(id)) { + return false; + } const snapshot = this.presentations.read(reader).get(id)?.snapshot.read(reader); return !!snapshot && getArtifactIntegrationGroupId(snapshot) !== undefined; } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sessionChatInputToolbar.ts b/src/vs/workbench/contrib/sessions/browser/chat/sessionChatInputToolbar.ts index 4d3261151498..3b7384176e86 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sessionChatInputToolbar.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sessionChatInputToolbar.ts @@ -46,7 +46,7 @@ import { getSessionGitHubReferences } from '../../common/github/sessionGitHubRef import { IGitHubService } from '../github/githubService.js'; import { IResolvedSessionPullRequest, SessionPullRequestPresentationModel } from '../github/pullRequestIconStatus.js'; import { ISessionChatPillVisibilityService, SESSION_CHAT_PILL_KINDS, SessionChatPillKind } from '../../../chat/common/sessionChatPills.js'; -import { getWindowHost, ISessionHost, SessionHostKind } from '../../../../services/sessions/browser/sessionHost.js'; +import { ISessionHost } from '../../../../services/sessions/browser/sessionHost.js'; import { ISessionsService } from '../sessionsService.js'; import { BRANCH_CHANGES_CHANGESET_ID, ChatOriginKind, IChat, ISession, isWorkspacelessQuickChat, SESSION_CHANGES_CHANGESET_ID, type IGitHubIssueRef, type IGitHubPullRequestRef, type ISessionWorkspace } from '../../../../services/sessions/common/session.js'; import { ISessionsManagementService } from '../../common/sessionsManagement.js'; @@ -60,6 +60,8 @@ import type { ISessionChatPillsDebugData } from './sessionChatInputToolbarDebug. import { activateHostPane, IActionTarget, SessionActivatingActionRunner } from '../sessionActionRunner.js'; import { computePullRequestIcon } from '../../../../common/chatPullRequest.js'; import { ISessionChangesStatsCache, readChatChangesStats, readLoadedChatChangesStats } from '../../../../services/sessions/common/sessionChangesStatsCache.js'; +import { IChatWindowService } from '../../../chatWindow/browser/chatWindow.js'; +import { getEditorTarget, getEditorTargetGroup, revealEditorTarget } from '../chatWindowEditorTarget.js'; import { ISessionChangesService } from '../../../../services/sessions/common/sessionChangesService.js'; import { Parts, IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; import { mainWindow } from '../../../../../base/browser/window.js'; @@ -484,6 +486,7 @@ export class SessionChatInputToolbar extends Disposable { @ISessionChangesStatsCache changesStatsCache: ISessionChangesStatsCache, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @ISessionsHostLayoutService hostLayoutService: ISessionsHostLayoutService, + @IChatWindowService chatWindowService: IChatWindowService, @IOpenerService openerService: IOpenerService, @ISessionChatPillVisibilityService visibility: ISessionChatPillVisibilityService, @IInstantiationService instantiationService: IInstantiationService, @@ -623,8 +626,10 @@ export class SessionChatInputToolbar extends Disposable { extensionService.onDidChangeExtensions, Event.filter(configurationService.onDidChangeConfiguration, event => event.affectsConfiguration(externalUriOpenersSettingId)), )); - const activityBarOpenerRefs = derivedOpts({ owner: this, equalsFn: structuralEquals }, reader => - pullRequestRefs.read(reader).map(ref => ({ id: ref.recordedReferenceId ?? ref.uri.toString(), uri: ref.uri }))); + const activityBarOpenerRefs = derivedOpts({ + owner: this, + equalsFn: (a, b) => a.length === b.length && a.every((ref, index) => ref.id === b[index].id && isEqual(ref.uri, b[index].uri)), + }, reader => pullRequestRefs.read(reader).map(ref => ({ id: ref.recordedReferenceId ?? ref.uri.toString(), uri: ref.uri }))); let supportedOpenerUris = new Set(); const activityBarOpeners = derived(this, reader => { openerChanges.read(reader); @@ -704,8 +709,13 @@ export class SessionChatInputToolbar extends Disposable { const existing = editors.find(({ editor }) => editor === editorService.activeEditor && matchesEditor(editor, entries)) ?? editors.find(({ editor }) => matchesEditor(editor, entries)); if (existing) { - hostLayoutService.revealEditorPartExplicitly(); - await editorService.openEditor(existing.editor, { revealIfOpened: true }, existing.groupId); + const target = getEditorTarget(chatWindowService, this._sessionHost); + if (!target) { + logService.trace('[SessionChatInputToolbar] The chat window of the chat is not available, not revealing its editor'); + return; + } + revealEditorTarget(hostLayoutService, target); + await editorService.openEditor(existing.editor, { revealIfOpened: true }, getEditorTargetGroup(target, existing.groupId)); return; } entries[0].open(); @@ -769,14 +779,19 @@ export class SessionChatInputToolbar extends Disposable { } const chat = this._chat.get(); const workspace = chat?.workspace?.get() ?? session.workspace.get(); - hostLayoutService.revealEditorPartExplicitly(); + const target = getEditorTarget(chatWindowService, this._sessionHost); + if (!target) { + logService.trace('[SessionChatInputToolbar] The chat window of the chat is not available, not opening its changes'); + return; + } + revealEditorTarget(hostLayoutService, target); void sessionChangesService.openChangesEditor(session.resource, { changesetSelection: { kind: 'id', id: getChangesPillChangesetId(workspace, isNestedChat(session, chat, undefined), session), }, - chatResource: getWindowHost(this._sessionHost).kind === SessionHostKind.ChatWindow ? chat?.resource : undefined, - }); + chatResource: target !== 'main' ? chat?.resource : undefined, + }, target !== 'main' ? target.mainPart.activeGroup : undefined); }, }, pullRequests: pullRequestData, @@ -819,7 +834,7 @@ export class SessionChatInputToolbar extends Disposable { } getChatPetPlatformElements(): readonly HTMLElement[] { - return this._inputPills.getPillElements(); + return this._inputPills.getPillItemElements(); } focusFirst(): boolean { diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.ts b/src/vs/workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.ts index d5d3cb2dc1bb..c8124a887559 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sessionEnvironmentPicker.ts @@ -6,11 +6,12 @@ import * as dom from '../../../../../base/browser/dom.js'; import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { escapeMarkdownSyntaxTokens } from '../../../../../base/common/htmlContent.js'; import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js'; import { autorun, IObservable, observableValue } from '../../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { localize } from '../../../../../nls.js'; -import { ActionListItemKind, IActionListItem } from '../../../../../platform/actionWidget/browser/actionList.js'; +import { ActionListItemKind, IActionListItem, IActionListOptions } from '../../../../../platform/actionWidget/browser/actionList.js'; import { IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; import { IMenuService, MenuItemAction } from '../../../../../platform/actions/common/actions.js'; import { cloudSandboxAddress } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; @@ -55,7 +56,7 @@ export function getSessionCreationEnvironments(providers: readonly ISessionsProv const visible = providers.filter(provider => provider.supportsWorkspaceSelection !== false && (!isAgentHostProvider(provider) || provider.isVisibleInEnvironmentPicker?.get() !== false && !provider.devContainerSourceWorkspace)); const local = visible.filter(provider => provider.environment.id === 'local'); - const cloud = visible.filter(provider => provider.environment.id === 'cloud' && !isAgentHostProvider(provider)); + const cloud = visible.filter(provider => provider.environment.id === 'cloud' && !isAgentHostProvider(provider) && provider.sessionTypes.length > 0); const environments: ISessionCreationEnvironment[] = []; if (local.length) { environments.push({ id: 'local', kind: 'local', label: localize('environmentPicker.local', "This Computer"), icon: Codicon.deviceDesktop, providerIds: local.map(provider => provider.id) }); @@ -105,9 +106,9 @@ export function resolveEnvironmentWorkspace(environment: ISessionCreationEnviron return undefined; } -export function getDefaultSessionCreationEnvironment(environments: readonly ISessionCreationEnvironment[], folderUri: URI | undefined, providerId: string | undefined, containerRequested = false, selectedProvider?: ISessionsProvider): ISessionCreationEnvironment | undefined { +export function getDefaultSessionCreationEnvironment(environments: readonly ISessionCreationEnvironment[], folderUri: URI | undefined, providerId: string | undefined, containerRequested = false, selectedProvider?: ISessionsProvider, preserveProvider = false): ISessionCreationEnvironment | undefined { const local = environments.find(environment => environment.kind === 'local'); - if (folderUri?.scheme === Schemas.file && !containerRequested && local) { + if (folderUri?.scheme === Schemas.file && !containerRequested && local && !preserveProvider) { return local; } return environments.find(environment => (environment.kind === 'container') === containerRequested && environment.providerIds.includes(providerId ?? '')) @@ -120,6 +121,12 @@ interface IEnvironmentPickerItem { readonly checked?: boolean; } +export const ENVIRONMENT_PICKER_LIST_OPTIONS = { + className: 'sessions-new-chat-picker-list', + minWidth: 240, + hideDefaultKeybindingTooltip: true, +} as const satisfies IActionListOptions; + export interface IEnvironmentPickerRenderOptions { readonly focusCommand?: { readonly id: string; readonly when: ContextKeyExpression; readonly enabled: IObservable }; readonly hoverDelegate?: IHoverDelegate; @@ -227,6 +234,8 @@ export class SessionEnvironmentPicker extends Disposable { kind: ActionListItemKind.Action, label: environment.label, description: environment.description, + hover: { content: this.getEnvironmentHover(environment, escapeMarkdownSyntaxTokens(environment.label)) }, + ariaDescription: this.getEnvironmentHover(environment, environment.label), submenuActions: showManage && this.isManagedInRemotes(environment) ? undefined : this.getActions(environment), group: { title: '', icon: environment.icon }, item: { run: () => this.select(environment), checked: environment.id === this.selected.get()?.id }, @@ -237,10 +246,13 @@ export class SessionEnvironmentPicker extends Disposable { items.push({ kind: ActionListItemKind.Separator, label: '' }); for (const action of actions) { if (action instanceof MenuItemAction) { + const tooltip = action.tooltip; items.push({ kind: ActionListItemKind.Action, label: action.label, disabled: !action.enabled, + hover: tooltip ? { content: escapeMarkdownSyntaxTokens(tooltip) } : undefined, + ariaDescription: tooltip || undefined, group: { title: '', icon: ThemeIcon.isThemeIcon(action.item.icon) ? action.item.icon : undefined }, item: { run: async () => { await action.run(); } }, }); @@ -250,11 +262,14 @@ export class SessionEnvironmentPicker extends Disposable { if (remotesEnabled && environmentPickerEnabled) { logSettingExperimentTrigger(this.telemetryService, ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING); if (showManage) { + const manageHover = localize('environmentPicker.manageHover', "Add, connect, and manage remote environments"); items.push( { kind: ActionListItemKind.Separator, label: '' }, { kind: ActionListItemKind.Action, label: localize('environmentPicker.manage', "Manage Remote Environments..."), + hover: { content: manageHover }, + ariaDescription: manageHover, group: { title: '', icon: Codicon.settingsGear }, item: { run: async () => { await this.commandService.executeCommand(OPEN_REMOTES_EDITOR_COMMAND_ID); } }, }, @@ -274,30 +289,58 @@ export class SessionEnvironmentPicker extends Disposable { } }, }, trigger, undefined, [], { - getAriaLabel: item => typeof item.description === 'string' && item.description - ? localize('environmentPicker.item', "{0}, {1}", item.label ?? '', item.description) : item.label ?? '', + getAriaLabel: item => [item.description, item.ariaDescription].reduce((label, part) => typeof part === 'string' && part + ? localize('environmentPicker.item', "{0}, {1}", label, part) : label, item.label ?? ''), getWidgetAriaLabel: () => localize('environmentPicker.title', "Environment"), - }, { className: 'sessions-new-chat-picker-list', minWidth: 240, hideDefaultKeybindingTooltip: true }); + }, ENVIRONMENT_PICKER_LIST_OPTIONS); + } + + private getEnvironmentHover(environment: ISessionCreationEnvironment, label: string): string { + switch (environment.kind) { + case 'local': + return localize('environmentPicker.localHover', "Run this session directly on this computer"); + case 'cloud': + return localize('environmentPicker.cloudHover', "Run this session in the cloud on GitHub"); + case 'container': + return localize('environmentPicker.containerHover', "Run this session in a dev container for the selected folder"); + case 'remote': + switch (this.getConnectionKind(environment)) { + case 'githubEnvironment': + return localize('environmentPicker.githubEnvironmentHover', "Run this session on {0}, shared through GitHub Environments", label); + case RemoteAgentHostEntryType.SSH: + return localize('environmentPicker.sshHover', "Run this session on {0} over SSH", label); + case RemoteAgentHostEntryType.Tunnel: + return localize('environmentPicker.tunnelHover', "Run this session on {0} through a dev tunnel", label); + case RemoteAgentHostEntryType.WSL: + return localize('environmentPicker.wslHover', "Run this session on {0} in WSL", label); + default: + return localize('environmentPicker.remoteHover', "Run this session on {0}", label); + } + } } private isManagedInRemotes(environment: ISessionCreationEnvironment): boolean { + const kind = this.getConnectionKind(environment); + return kind === RemoteAgentHostEntryType.WSL ? isWindows : !!kind; + } + + private getConnectionKind(environment: ISessionCreationEnvironment): 'githubEnvironment' | RemoteAgentHostEntryType.SSH | RemoteAgentHostEntryType.Tunnel | RemoteAgentHostEntryType.WSL | undefined { const provider = environment.kind === 'remote' && this.sessionsProvidersService.getProvider(environment.providerIds[0]); if (!provider || !isAgentHostProvider(provider) || !provider.remoteAddress) { - return false; + return undefined; } if (this.environmentService.enabled && this.environmentService.accountKey && this.environmentService.hosts.get().some(host => host.kind === 'user-local' && cloudSandboxAddress(host.id) === provider.remoteAddress)) { - return true; + return 'githubEnvironment'; } const connection = this.remoteAgentHostService.configuredEntries.find(entry => getEntryAddress(entry) === provider.remoteAddress)?.connection; switch (connection?.type) { case RemoteAgentHostEntryType.SSH: case RemoteAgentHostEntryType.Tunnel: - return true; case RemoteAgentHostEntryType.WSL: - return isWindows; + return connection.type; default: - return false; + return undefined; } } } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sessionWorkspacePicker.ts b/src/vs/workbench/contrib/sessions/browser/chat/sessionWorkspacePicker.ts index 6288ca2f68ab..e7043a71328a 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sessionWorkspacePicker.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sessionWorkspacePicker.ts @@ -15,6 +15,7 @@ import { Emitter, Event } from '../../../../../base/common/event.js'; import { disposableTimeout, Limiter, RunOnceScheduler } from '../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { getOrSet } from '../../../../../base/common/map.js'; import { Schemas } from '../../../../../base/common/network.js'; import { URI } from '../../../../../base/common/uri.js'; import { autorun, IObservable, IReader, observableValue, waitForState } from '../../../../../base/common/observable.js'; @@ -307,6 +308,7 @@ export class WorkspacePicker extends Disposable { private readonly _triggerOptions = new Map(); private readonly _triggerContents = new Map(); private readonly _contextSelections = new Map(); + private readonly _workspaceItemIds = new Map(); private readonly _renderDisposables = this._register(new DisposableStore()); private readonly _additionalRepositorySelections = new Map(); private readonly _additionalFolderSelections = new Map(); @@ -1720,10 +1722,12 @@ export class WorkspacePicker extends Disposable { return undefined; } + const currentFolder = this._selectedFolderUri?.scheme === Schemas.file ? this._selectedFolderUri : undefined; const result = await this.fileDialogService.showOpenDialog({ canSelectFolders: true, canSelectFiles: false, canSelectMany: false, + defaultUri: currentFolder ? this.uriIdentityService.extUri.dirname(currentFolder) : undefined, }); if (!result?.length) { return undefined; @@ -1892,7 +1896,7 @@ export class WorkspacePicker extends Disposable { const attached = this._additionalFolderSelections.has(this.uriIdentityService.extUri.getComparisonKey(folderUri)) || (repositoryId !== undefined && this._additionalRepositorySelections.has(repositoryId)); const item: IWorkspacePickerItem = { - id: `workspacePicker.workspace.${this.uriIdentityService.extUri.getComparisonKey(folderUri)}`, + id: `workspacePicker.workspace.${getOrSet(this._workspaceItemIds, this.uriIdentityService.extUri.getComparisonKey(folderUri), this._workspaceItemIds.size)}`, folderUri, providerId: environmentProvider ? environmentProvider.id : providerId, checked: selected || attached || undefined, diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposer.ts b/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposer.ts index abaccde3afcb..59a846a24a3a 100644 --- a/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposer.ts +++ b/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposer.ts @@ -1020,14 +1020,22 @@ export class SharedChatInputComposer extends Disposable implements INewSessionCo if (!this._canSendRequest.get()) { return false; } + const targetWindow = dom.getWindow(widget.domNode); + const hadFocus = widget.input.hasFocus(); + let disabledInputFocus = targetWindow.document.activeElement; + const canRestoreInputFocus = () => { + const activeElement = targetWindow.document.activeElement; + return this.options.inputVisible?.get() !== false && this.options.hostVisible?.get() !== false + && (activeElement === targetWindow.document.body || activeElement === disabledInputFocus || widget.input.hasFocus()); + }; if (this.options.confirmSend) { - const hadFocus = widget.input.hasFocus(); transaction(tx => { this._sending.set(true, tx); this._confirmingSend.set(true, tx); }); // The request is already captured, so edits made while the host confirms would be lost. widget.input.setInputEnabled(false, this.options.preserveInputFocusOnSend); + disabledInputFocus = targetWindow.document.activeElement; let confirmed = false; try { confirmed = await this.options.confirmSend(query); @@ -1038,7 +1046,7 @@ export class SharedChatInputComposer extends Disposable implements INewSessionCo }); if (this._widget === widget && widget.input) { widget.input.setInputEnabled(true); - if (!confirmed && hadFocus) { + if (!confirmed && hadFocus && canRestoreInputFocus()) { widget.input.focus(); } } @@ -1054,8 +1062,10 @@ export class SharedChatInputComposer extends Disposable implements INewSessionCo hostVisible: this.options.hostVisible, }); this._userInteractionSource.value = toDisposable(() => userInteraction?.disposeSource()); + const restoreFocusAfterSend = hadFocus && canRestoreInputFocus(); this._sending.set(true, undefined); widget.input.setInputEnabled(false, this.options.preserveInputFocusOnSend); + disabledInputFocus = targetWindow.document.activeElement; // The send can dispose the input widget, e.g. when the composer is left while a workspace is // applied or the send waits; the send itself completes and only the gone input is skipped. const isInputAlive = () => this._widget === widget && !!widget.input; @@ -1124,6 +1134,9 @@ export class SharedChatInputComposer extends Disposable implements INewSessionCo this._userInteractionSource.clear(); if (isInputAlive()) { widget.input.setInputEnabled(true); + if (!sent && restoreFocusAfterSend && canRestoreInputFocus()) { + widget.input.focus(); + } } this._sending.set(false, undefined); } diff --git a/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposerToolbar.ts b/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposerToolbar.ts new file mode 100644 index 000000000000..8ba4ae2624c2 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chat/sharedChatInputComposerToolbar.ts @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../base/browser/dom.js'; +import { BaseActionViewItem } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { IAction } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize, localize2 } from '../../../../../nls.js'; +import { IActionViewItemService } from '../../../../../platform/actions/browser/actionViewItemService.js'; +import { MenuWorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; +import { Action2, MenuRegistry, registerAction2 } from '../../../../../platform/actions/common/actions.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IWorkbenchContribution } from '../../../../common/contributions.js'; +import { CHAT_ATTACH_CONTEXT_ACTION_ID } from '../../../chat/common/constants.js'; +import { Menus } from '../menus.js'; +import { getLabeledPickerResponsiveItems } from './newChatComposerInput.js'; +import { createNewSessionControlToolbar } from './newSessionConfigToolbars.js'; +import { SharedChatInputComposerBusyContext } from './sharedChatInputComposer.js'; + +const COMPOSER_INITIALIZING_ACTION_ID = 'sessions.newChatComposer.initializing'; +const COMPOSER_SENDING_ACTION_ID = 'sessions.newChatComposer.sending'; +export const COMPOSER_SESSION_CONTROLS_ACTION_ID = 'sessions.newChatComposer.sessionControls'; + +/** Progress in the composer's input toolbar, labelled by its action. */ +class ComposerBusyActionViewItem extends BaseActionViewItem { + override render(container: HTMLElement): void { + // Not interactive, so without the base item's pointer handling. + this.element = container; + container.classList.add('sessions-shared-chat-input-busy'); + container.setAttribute('role', 'status'); + const icon = dom.append(container, renderIcon(ThemeIcon.modify(Codicon.loadingCompact, 'spin'))); + icon.setAttribute('aria-hidden', 'true'); + this.updateTooltip(); + } + + protected override getTooltip(): string { + return this.action.label; + } +} + +/** + * Hosts the session controls toolbar inside the input toolbar. + * The nested pickers own pointer and keyboard input, and focus moves into them. + */ +class ComposerSessionControlsActionViewItem extends BaseActionViewItem { + private _controls: HTMLElement | undefined; + private _toolbar: MenuWorkbenchToolBar | undefined; + + constructor(action: IAction, private readonly _instantiationService: IInstantiationService) { + super(undefined, action); + } + + override render(container: HTMLElement): void { + // The base item's pointer handling would cancel the pickers' focus, flash + // the whole group as pressed and run this placeholder action on click. + this.element = container; + container.classList.add('sessions-shared-chat-input-session-controls'); + const controls = this._controls = dom.append(container, dom.$('.sessions-chat-config-toolbar.new-chat-session-controls')); + this._toolbar = this._register(createNewSessionControlToolbar(controls, this._instantiationService, localize('sessionsSharedChatInput.sessionControlsAria', "Session controls"))); + } + + override focus(fromRight?: boolean): void { + const count = this._toolbar?.getItemsLength() ?? 0; + if (count > 0) { + this._toolbar?.focus(fromRight ? count - 1 : 0); + } + } + + override isFocused(): boolean { + return !!this._controls && dom.isAncestorOfActiveElement(this._controls); + } + + override blur(): void { + const active = this._controls && dom.getActiveElement(); + if (dom.isHTMLElement(active) && this._controls?.contains(active)) { + active.blur(); + } + } + + override setFocusable(focusable: boolean): void { + this._toolbar?.setFocusable(focusable); + } + + isCompact(): boolean { + const items = this._controls ? getLabeledPickerResponsiveItems(this._controls) : []; + return items.length > 0 && items.every(item => item.isCompact()); + } + + setCompact(compact: boolean): void { + for (const item of this._controls ? getLabeledPickerResponsiveItems(this._controls) : []) { + item.setCompact(compact); + } + } +} + +/** Renders the composer's progress and session controls in its input toolbar. */ +export class SharedChatInputComposerContribution extends Disposable implements IWorkbenchContribution { + static readonly ID = 'sessions.contrib.sharedChatInputComposer'; + + constructor(@IActionViewItemService actionViewItemService: IActionViewItemService) { + super(); + for (const id of [COMPOSER_INITIALIZING_ACTION_ID, COMPOSER_SENDING_ACTION_ID]) { + this._register(actionViewItemService.register(Menus.NewSessionChatInputToolbar, id, action => new ComposerBusyActionViewItem(undefined, action))); + } + this._register(actionViewItemService.register(Menus.NewSessionChatInputToolbar, COMPOSER_SESSION_CONTROLS_ACTION_ID, (action, _options, instantiationService) => new ComposerSessionControlsActionViewItem(action, instantiationService))); + } +} + +/** + * Registers the items of a new-session composer's input toolbar, until the returned disposable is disposed: Add Context, + * its progress and its session controls. {@link SharedChatInputComposerContribution} renders the progress and controls. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerSharedChatInputComposerToolbar(): IDisposable { + const store = new DisposableStore(); + + store.add(MenuRegistry.appendMenuItem(Menus.NewSessionChatInputToolbar, { + command: { id: CHAT_ATTACH_CONTEXT_ACTION_ID, title: localize('sessionsSharedChatInput.addContext', "Add Context..."), icon: Codicon.addCompact }, + group: 'navigation', + order: -2, + })); + + for (const [id, title, busy] of [ + [COMPOSER_INITIALIZING_ACTION_ID, localize2('sessionsSharedChatInput.initializing', "Initializing..."), 'initializing'], + [COMPOSER_SENDING_ACTION_ID, localize2('sessionsSharedChatInput.sending', "Loading..."), 'sending'], + ] as const) { + store.add(registerAction2(class extends Action2 { + constructor() { + super({ + id, + title, + f1: false, + menu: { id: Menus.NewSessionChatInputToolbar, group: 'navigation', order: 100, when: SharedChatInputComposerBusyContext.isEqualTo(busy) }, + }); + } + override run(): void { /* progress only */ } + })); + } + + store.add(registerAction2(class extends Action2 { + constructor() { + super({ + id: COMPOSER_SESSION_CONTROLS_ACTION_ID, + title: localize2('sessionsSharedChatInput.sessionControls', "Session Controls"), + f1: false, + menu: { id: Menus.NewSessionChatInputToolbar, group: 'navigation', order: 0 }, + }); + } + override run(): void { /* rendered by the action view item */ } + })); + + return store; +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts b/src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts index 2347f79b7bd1..10595eab88d4 100644 --- a/src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts +++ b/src/vs/workbench/contrib/sessions/browser/chatBackgroundRenderer.ts @@ -161,10 +161,12 @@ export class SessionsChatBackgroundRenderer extends Disposable { private readonly random: () => number = Math.random, ) { super(); - this.refreshScheduler = this._register(new RunOnceScheduler( - () => this.renderCodicons(this.element.clientWidth, this.element.clientHeight), - 0 - )); + this.refreshScheduler = this._register(new RunOnceScheduler(() => { + // Reading the element size forces a layout, so only do it when there are codicons to lay out. + if (this.background?.kind === 'codicons') { + this.renderCodicons(this.element.clientWidth, this.element.clientHeight); + } + }, 0)); this.backgroundLayer = $('.sessions-chat-background'); this.backgroundLayer.ariaHidden = 'true'; diff --git a/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditor.ts b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditor.ts new file mode 100644 index 000000000000..0b71ec4ff189 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditor.ts @@ -0,0 +1,521 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { registerContentDropTarget } from '../../../../browser/dnd.js'; +import { $ } from '../../../../../base/browser/dom.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { RunOnceScheduler } from '../../../../../base/common/async.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, derived, IObservable, IReader, observableValue } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.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 { Registry } from '../../../../../platform/registry/common/platform.js'; +import { ViewEditorInput } from '../../../../browser/parts/editor/viewEditorInput.js'; +import { ActiveEditorContext } from '../../../../common/contextkeys.js'; +import { IViewEditorRegistry, IViewEditorView, ViewEditorExtensions } from '../../../../browser/parts/editor/viewEditorRegistry.js'; +import { IEditorPaneTitleMenu } from '../../../../browser/parts/editor/editor.js'; +import { IEditorPart } from '../../../../services/editor/common/editorGroupsService.js'; +import { decideStackedChatInputOnlyWhileDragging } from '../../../chatWindow/common/chatWindowInputOnly.js'; +import { ChatWindowLayoutMode } from '../../../chatWindow/common/chatWindowLayout.js'; +import { AbstractChatView, ISessionViewHostOptions } from '../parts/chatView.js'; +import { ChatEditorContent, IChatEditorComposer } from './chatEditorContent.js'; + +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { EditorInputCapabilities, GroupIdentifier, Verbosity } from '../../../../common/editor.js'; +import { IChat, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { ISessionsListModelService } from '../sessionsListModelService.js'; +import { getChatCompletedStateIcon, ISessionAgentMergeConfiguration } from '../sessionAgentMerge.js'; +import { getSessionChatAncestors } from '../parts/sessionHeaderBar.js'; +import { getSessionConversationStatusAriaLabel } from '../sessionConversationGroups.js'; +import { ISessionPaneContent } from '../../../../services/sessions/common/sessionPane.js'; + +/** The view type of the chat of a session, shown as an editor: the chat part of a chat window shows it. */ +export const SESSION_CHAT_VIEW_TYPE = 'sessions.chat'; + +/** The least size of the chat of a chat window. */ +export const SESSION_CHAT_VIEW_MINIMUM_WIDTH = 280; +export const SESSION_CHAT_VIEW_MINIMUM_HEIGHT = 120; + +/** The most height the chat input, with what shows above it, grows to while the chat shows only its input. */ +export const SESSION_CHAT_VIEW_INPUT_ONLY_MAX_HEIGHT = 320; + +/** How the chat of a chat window shows its session: as the Sessions part does, with its pills and its Session Activity Bar. */ +export const SESSION_CHAT_VIEW_HOST_OPTIONS: ISessionViewHostOptions = { + showHeader: true, + showActivityBar: true, + input: { showPills: true }, +}; + +/** What a chat editor needs of the window it shows in: how the window lays out its chat, and its main part. */ +export interface IChatEditorWindow { + readonly layoutMode: IObservable; + readonly inputOnly: IObservable; + readonly resizing: IObservable; + /** Its main part, whose active editor the chat reads, such as for the checked entries of its Session Activity Bar. */ + readonly mainPart: IEditorPart; + toggleConversation(): void; +} + +/** What a chat editor shows, and the window it shows in, as whoever opens its editor gives it. */ +export interface ISessionChatViewHost { + /** + * What its pane shows, once the chat is known: the provider's session, the chat, and how its pane closes, which closes the + * chat in the window it shows in. + */ + readonly content: IObservable; + /** A new-session composer that its pane shows while {@link content} is undefined, until the composer's session is created. */ + readonly composer?: IObservable; + /** The window the view shows in, once it shows. */ + readonly window: IObservable; + /** Whether its chat is the active one of its window: only that one shows the Session Activity Bar, also beside its window's chat. */ + readonly active: IObservable; + /** Called with what the editor shows once it is created, until the returned disposable is disposed. */ + attach(view: ChatEditorContent): IDisposable; + /** + * Takes what is dropped on the view of the chat, `element`, and opens it, such as a session or chat that a chat window opens + * beside `chat`, until the returned disposable is disposed. Without it, the view takes only what the chat input does. + */ + createDropTarget?(element: HTMLElement, chat: () => URI | undefined): IDisposable; + /** + * What shows the chat: the last attached of those attached, such as the view where the chat moves to while the one it + * moves from is still there. + */ + readonly view: IObservable; +} + +const hosts = new Map(); + +/** Gives the session chat view of `input` what it shows; for as long as the returned disposable is not disposed. */ +export function registerSessionChatViewHost(input: ViewEditorInput, host: ISessionChatViewHost): IDisposable { + hosts.set(input, host); + return toDisposable(() => { + if (hosts.get(input) === host) { + hosts.delete(input); + } + }); +} + +/** What a chat editor shows, as far as its input-only state needs it. */ +export interface IInputOnlySessionView { + readonly primaryChatView: IObservable | undefined>; + /** The top of {@link primaryChatView} while the chat shows only its input, which hides the session header. */ + readonly inputOnlyChatViewTop: IObservable; +} + +/** + * Lets the chat of a chat window show only its input below the main part (Stacked), as its window's state says: the chat + * view collapses to its input, and the chat reports its input's height as its least and, but a pixel, its most height, + * which its part and the window respect. Dragged taller by the sash above it, it shows its conversation, and dragged + * back down to its input, only its input again. What the chat shows is what its view shows, which shows the conversation + * when it needs it, such as for a confirmation its input cannot show; what the user chose in the chat is kept for its window. + */ +export class SessionChatViewInputOnly extends Disposable { + + /** Whether the chat shows only its input, below the main part. */ + readonly shownInputOnly: IObservable; + + /** The height of the chat when it shows only its input, or 0 while that is not known. */ + readonly collapsedHeight: IObservable; + + /** + * The most height of the chat: about its collapsed height while it shows only its input, a pixel more so that the sash + * above it can be dragged, which then lets it grow, to show its conversation (see {@link layout}). + */ + readonly maximumHeight: IObservable; + + /** The least height of the chat: its input while it shows only its input; down to its input while it is below the main part. */ + readonly minimumHeight: IObservable; + + private readonly _window: IObservable | undefined>; + private _resizedHeight = 0; + private readonly _resizeScheduler = this._register(new RunOnceScheduler(() => this._showWhatResizeShows(), 0)); + + constructor( + sessionView: IInputOnlySessionView, + window: IObservable | undefined>, + ) { + super(); + this._window = window; + + const stacked = derived(this, reader => window.read(reader)?.layoutMode.read(reader) === ChatWindowLayoutMode.Stacked); + const view = sessionView.primaryChatView; + this.shownInputOnly = derived(this, reader => stacked.read(reader) && !!view.read(reader)?.inputOnly.read(reader)); + this.collapsedHeight = derived(this, reader => { + const inputHeight = view.read(reader)?.inputOnlyHeight.read(reader) ?? 0; + return inputHeight ? sessionView.inputOnlyChatViewTop.read(reader) + inputHeight : 0; + }); + this.maximumHeight = derived(this, reader => { + const collapsed = this.collapsedHeight.read(reader); + if (!this.shownInputOnly.read(reader) || !collapsed || window.read(reader)?.resizing.read(reader)) { + return Number.POSITIVE_INFINITY; + } + return collapsed + 1; + }); + this.minimumHeight = derived(this, reader => { + const collapsed = this.collapsedHeight.read(reader); + if (this.shownInputOnly.read(reader) && collapsed) { + return collapsed; + } + return stacked.read(reader) && collapsed ? Math.min(collapsed, SESSION_CHAT_VIEW_MINIMUM_HEIGHT) : SESSION_CHAT_VIEW_MINIMUM_HEIGHT; + }); + + const windowInputOnly = (reader: IReader | undefined) => !!window.read(reader)?.inputOnly.read(reader); + this._register(autorun(reader => { + const chatView = view.read(reader); + if (!chatView) { + return; + } + if (stacked.read(reader)) { + chatView.enableInputOnly({ maxHeight: SESSION_CHAT_VIEW_INPUT_ONLY_MAX_HEIGHT, inputOnly: windowInputOnly(undefined) }); + } else { + chatView.disableInputOnly(); + } + })); + this._register(autorun(reader => { + const inputOnly = windowInputOnly(reader); + if (stacked.read(reader)) { + view.read(reader)?.setInputOnly(inputOnly); + } + })); + // What the user chose in the chat, such as showing its conversation from it, is what its window shows next time; + // not the conversation the view shows while its input cannot show what it needs. + this._register(autorun(reader => { + const chatView = view.read(reader); + const chatWindow = window.read(reader); + if (!stacked.read(reader) || !chatView?.canShowInputOnly.read(reader) || !chatWindow) { + return; + } + if (chatView.inputOnly.read(reader) !== windowInputOnly(undefined)) { + chatWindow.toggleConversation(); + } + })); + // What a resize showed is announced once it lets go, not at each snap while it drags + let inputOnlyBeforeResize: boolean | undefined; + this._register(autorun(reader => { + const chatWindow = window.read(reader); + const resizing = !!chatWindow?.resizing.read(reader); + if (resizing) { + inputOnlyBeforeResize ??= windowInputOnly(undefined); + return; + } + const before = inputOnlyBeforeResize; + inputOnlyBeforeResize = undefined; + const inputOnly = windowInputOnly(undefined); + if (before !== undefined && before !== inputOnly && stacked.read(undefined)) { + status(inputOnly ? localize('chatConversationHidden', "Chat conversation hidden") : localize('chatConversationShown', "Chat conversation shown")); + } + })); + } + + /** + * The chat is laid out at `height`. While the user drags the sash beside it, it shows its conversation once dragged up + * past its input, and only its input once dragged back down to it: a snap, with a little room between the two so + * that a height at either does not flicker. What shows changes once the layout is done. + */ + layout(height: number): void { + this._resizedHeight = height; + const window = this._window.get(); + if (window?.layoutMode.get() === ChatWindowLayoutMode.Stacked && this.collapsedHeight.get() && window.resizing.get()) { + this._resizeScheduler.schedule(); + } + } + + private _showWhatResizeShows(): void { + const window = this._window.get(); + const collapsedHeight = this.collapsedHeight.get(); + if (!window?.resizing.get() || !collapsedHeight || window.layoutMode.get() !== ChatWindowLayoutMode.Stacked) { + return; + } + const inputOnly = window.inputOnly.get(); + if (decideStackedChatInputOnlyWhileDragging({ groupHeight: this._resizedHeight, collapsedHeight, inputOnly }) !== inputOnly) { + window.toggleConversation(); + } + } +} + +/** + * A chat as an editor: one chat, with the header of its session, as the chat part of a chat window shows its chats. It + * brings its own title, the session header, at the top of its card, as the main window shows a session. + */ +export class ChatEditorView extends Disposable implements IViewEditorView { + + readonly element: HTMLElement; + readonly sessionView: ChatEditorContent; + readonly providesTitle = true; + + /** Whether the view shows: not while another editor of its group, as a tab, shows. */ + private readonly _visible = observableValue(this, true); + + /** Whether the view shows its title, the session header: not while its group shows its tabs, which show its actions. */ + private readonly _providedTitleVisible = observableValue(this, true); + + /** The session header drags the chat. */ + get dragHandle(): HTMLElement { return this.sessionView.headerElement; } + + /** The actions of the session header, which the tab bar of its group shows while the header hides. */ + get titleMenu(): IEditorPaneTitleMenu { return this.sessionView.titleMenu; } + + private readonly _onDidChange = this._register(new Emitter<{ width: number; height: number } | undefined>()); + readonly onDidChange: Event<{ width: number; height: number } | undefined> = this._onDidChange.event; + + private readonly _inputOnly: SessionChatViewInputOnly; + + readonly minimumWidth = SESSION_CHAT_VIEW_MINIMUM_WIDTH; + readonly maximumWidth = Number.POSITIVE_INFINITY; + get minimumHeight(): number { return this._inputOnly.minimumHeight.get(); } + get maximumHeight(): number { return this._inputOnly.maximumHeight.get(); } + + /** The services of the view's own scope, which what it shows is created with: disposed after it, see {@link dispose}. */ + private readonly _scopedServices = new DisposableStore(); + + override dispose(): void { + super.dispose(); + this._scopedServices.dispose(); + } + + constructor( + host: ISessionChatViewHost | undefined, + @IInstantiationService instantiationService: IInstantiationService, + @IContextKeyService contextKeyService: IContextKeyService, + ) { + super(); + + // Styled as the session views of the Agents window are, which show in its sessions part or in a window of their own. + this.element = $('.session-chat-view-editor.sessions-window-host'); + // The chat takes what is dropped on it, such as files to attach; editors dropped on the edges of its part split it. + this._register(registerContentDropTarget(this.element)); + // What its host opens on a drop, such as a session or chat that a chat window opens beside it + if (host?.createDropTarget) { + this._register(host.createDropTarget(this.element, () => host.content.get()?.chat.get().resource)); + } + // The active editor, for what the chat shows, such as the checked entries of its Session Activity Bar, is the one of + // its window's main part, as the main window's chat reads the one of its editor area. + const scopedContextKeyService = this._scopedServices.add(contextKeyService.createScoped(this.element)); + const activeEditor = ActiveEditorContext.bindTo(scopedContextKeyService); + this._register(autorun(reader => { + const mainPart = host?.window.read(reader)?.mainPart; + if (!mainPart) { + activeEditor.reset(); + return; + } + const groupListener = reader.store.add(new MutableDisposable()); + const trackActiveGroup = () => { + const update = () => activeEditor.set(mainPart.activeGroup.activeEditorPane?.getId() ?? null); + groupListener.value = mainPart.activeGroup.onDidActiveEditorChange(update); + update(); + }; + reader.store.add(mainPart.onDidChangeActiveGroup(trackActiveGroup)); + trackActiveGroup(); + })); + const scopedInstantiationService = this._scopedServices.add(instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); + const sessionView = this.sessionView = this._register(scopedInstantiationService.createInstance(ChatEditorContent, SESSION_CHAT_VIEW_HOST_OPTIONS)); + this.element.appendChild(sessionView.element); + // Styled as the active session of the grid is. + sessionView.element.classList.add('is-active'); + + const window = derived(this, reader => host?.window.read(reader)); + this._inputOnly = this._register(new SessionChatViewInputOnly(sessionView, window)); + // The command center of the window names the session while the chat shows only its input, and the tabs of its group + // name the chat while they show: its header hides. + this._register(autorun(reader => sessionView.setHeaderHidden(this._inputOnly.shownInputOnly.read(reader) || !this._providedTitleVisible.read(reader)))); + this._register(autorun(reader => { + this._inputOnly.minimumHeight.read(reader); + this._inputOnly.maximumHeight.read(reader); + this._onDidChange.fire(undefined); + })); + + if (!host) { + return; + } + // Without the chat, such as while its window shows only its main part, or while another editor beside it, as a tab, + // shows, its view is hidden; as with what hosts it hidden, its Session Activity Bar can still show outside of it. Its + // host sees it shown or hidden from the moment the view attaches, such as to mark its chat read only while it shows. + this._register(autorun(reader => { + const mode = host.window.read(reader)?.layoutMode.read(reader); + const visible = mode !== ChatWindowLayoutMode.EditorOnly && this._visible.read(reader); + sessionView.setVisible(visible, visible); + })); + this._register(host.attach(sessionView)); + this._register(autorun(reader => sessionView.setComposer(host.composer?.read(reader)))); + this._register(autorun(reader => sessionView.setContent(host.content.read(reader)))); + this._register(autorun(reader => sessionView.setActive(host.active.read(reader)))); + } + + layout(width: number, height: number, top: number, left: number): void { + this.sessionView.layout(width, height, top, left); + this._inputOnly.layout(height); + } + + focus(): void { + this.sessionView.focus(); + } + + /** Hides the chat while another editor of its group, as a tab, shows, and shows it again. */ + setVisible(visible: boolean): void { + this._visible.set(visible, undefined); + } + + setProvidedTitleVisible(visible: boolean): void { + this._providedTitleVisible.set(visible, undefined); + } + + /** Saves what the chat shows, such as where it is scrolled to, before its editor moves: the view where it moves to shows the same. */ + saveViewState(): void { + this.sessionView.primaryChatView.get()?.saveViewState(); + } +} + +let sessionChatViewEditorRegistration: { readonly registration: IDisposable; references: number } | undefined; + +/** + * Registers the view editor of the chat of a session ({@link SESSION_CHAT_VIEW_TYPE}), until every returned disposable is + * disposed: the Agents window and the chat part of an editor window share one registration. + */ +export function registerSessionChatViewEditor(): IDisposable { + if (!sessionChatViewEditorRegistration) { + sessionChatViewEditorRegistration = { + registration: Registry.as(ViewEditorExtensions.ViewEditors).register({ + viewType: SESSION_CHAT_VIEW_TYPE, + name: localize('sessionChatViewEditor', "Chat"), + providesTitle: true, + createView: (instantiationService, input) => instantiationService.createInstance(ChatEditorView, hosts.get(input)), + }), + references: 0, + }; + } + const entry = sessionChatViewEditorRegistration; + entry.references++; + let disposed = false; + return toDisposable(() => { + if (disposed) { + return; + } + disposed = true; + if (--entry.references === 0) { + entry.registration.dispose(); + sessionChatViewEditorRegistration = undefined; + } + }); +} + +/** + * What the tab of the editor of `chat` of `session`, named `name`, shows of the chat besides its name: its status, as the + * sessions list shows it beside the chat, and its title with those of its session and parent chats, as its header does. + */ +export function getChatEditorInputDetails(session: ISession, chat: IChat, name: string, reader: IReader, sessionsListModelService: ISessionsListModelService, agentMergeConfiguration: () => IObservable): IChatEditorInputDetails { + const status = chat.status.read(reader); + const isRead = chat.isRead.read(reader); + const isArchived = chat.isArchived.read(reader); + const statusIcon = sessionsListModelService.getStatusIcon(status, isRead, isArchived, getChatCompletedStateIcon(session, chat, reader, agentMergeConfiguration)); + // A tab shows a chat in progress spinning, as other work in progress shows; it stands still while motion is reduced. + const icon = status === SessionStatus.InProgress ? { ...ThemeIcon.modify(Codicon.loading, 'spin'), color: statusIcon.color } : statusIcon; + const longTitle = [...getSessionChatAncestors(session, chat, reader), name].join(' / '); + const ariaLabel = localize('chatEditorInputAria', "{0}, {1}", longTitle, getSessionConversationStatusAriaLabel(status)); + return { icon, longTitle, ariaLabel: !isRead && !isArchived ? localize('chatEditorInputUnreadAria', "{0}, unread", ariaLabel) : ariaLabel }; +} + +/** What the tab of a chat editor shows of its chat besides its name; see {@link ChatEditorInput.setDetails}. */ +export interface IChatEditorInputDetails { + /** The status of the chat, as the sessions list shows it beside the chat. */ + readonly icon: ThemeIcon; + /** The title of the chat with those of its session and parent chats, such as for the tooltip of its tab. */ + readonly longTitle: string; + /** The title of the chat with its session and its status, as screen readers read its tab. */ + readonly ariaLabel: string; +} + +/** Where a chat editor can move to ({@link ChatEditorInput.setMoveRestriction}). */ +export interface IChatEditorMoveRestriction { + /** Shown when a move is refused. */ + readonly reason: string; + canMoveTo(group: GroupIdentifier): boolean; +} + +/** + * The editor of a chat, keyed by the chat's resource: one per chat, in the chat part of a chat window. Its tab shows the + * title of the chat. + */ +export class ChatEditorInput extends ViewEditorInput { + + private _name = ''; + private _details: IChatEditorInputDetails | undefined; + private _cannotClose = false; + private _moveRestriction: IChatEditorMoveRestriction | undefined; + + constructor(readonly chatResource: URI) { + super(SESSION_CHAT_VIEW_TYPE, chatResource); + } + + /** + * Keeps the editor in the groups `restriction` allows, such as those of its own window, with its reason elsewhere and + * for a new window. A copy of it is a move, as for any editor of a view. + */ + setMoveRestriction(restriction: IChatEditorMoveRestriction | undefined): void { + if (this._moveRestriction !== restriction) { + this._moveRestriction = restriction; + this._onDidChangeCapabilities.fire(); + } + } + + override canMove(sourceGroup: GroupIdentifier, targetGroup: GroupIdentifier): true | string { + const restriction = this._moveRestriction; + return !restriction || restriction.canMoveTo(targetGroup) ? super.canMove(sourceGroup, targetGroup) : restriction.reason; + } + + override canMoveToNewWindow(sourceGroup: GroupIdentifier): true | string { + return this._moveRestriction?.reason ?? super.canMoveToNewWindow(sourceGroup); + } + + setName(name: string): void { + if (this._name !== name) { + this._name = name; + this._onDidChangeLabel.fire(); + } + } + + /** What its tab shows of the chat besides its name: its status, its session, and what screen readers read of it. */ + setDetails(details: IChatEditorInputDetails | undefined): void { + const current = this._details; + const changed = !current || !details + ? current !== details + : !ThemeIcon.isEqual(current.icon, details.icon) || current.longTitle !== details.longTitle || current.ariaLabel !== details.ariaLabel; + if (changed) { + this._details = details; + this._onDidChangeLabel.fire(); + } + } + + setCannotClose(cannotClose: boolean): void { + if (this._cannotClose !== cannotClose) { + this._cannotClose = cannotClose; + this._onDidChangeCapabilities.fire(); + } + } + + override getName(): string { + return this._name || super.getName(); + } + + override getTitle(verbosity?: Verbosity): string { + return verbosity === Verbosity.LONG && this._details ? this._details.longTitle : this.getName(); + } + + override getAriaLabel(): string { + return this._details?.ariaLabel ?? super.getAriaLabel(); + } + + override getIcon(): ThemeIcon { + return this._details?.icon ?? Codicon.commentDiscussion; + } + + override get capabilities(): EditorInputCapabilities { + return super.capabilities | (this._cannotClose ? EditorInputCapabilities.CannotClose : 0); + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditorContent.ts b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditorContent.ts new file mode 100644 index 000000000000..b4a71aea2acf --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatEditorContent.ts @@ -0,0 +1,356 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, isAncestorOfActiveElement, size } from '../../../../../base/browser/dom.js'; +import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { autorun, constObservable, derived, IObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { createSessionHostServices, ISessionHost, ISessionHostService, SessionHost, SessionHostKind } from '../../../../services/sessions/browser/sessionHost.js'; +import { IChat, ISession, isSessionCreated } from '../../../../services/sessions/common/session.js'; +import { ISessionChangesStatsCache } from '../../../../services/sessions/common/sessionChangesStatsCache.js'; +import { setHostSessionContextKeys } from '../../common/sessionContextKeys.js'; +import { SessionInChatEditorContext } from '../../common/contextkeys.js'; +import { ChatGroupView, IChatGroupContext } from '../parts/chatGroupView.js'; +import { AbstractChatView, INewSessionDraftHost, ISessionViewHostOptions } from '../parts/chatView.js'; +import { IChatViewFactory } from '../chatViewFactory.js'; +import { SessionHeader } from '../parts/sessionHeader.js'; +import { Menus } from '../menus.js'; +import { IEditorPaneTitleMenu } from '../../../../browser/parts/editor/editor.js'; +import { ISessionPaneContent } from '../../../../services/sessions/common/sessionPane.js'; +import { IChatService } from '../../../chat/common/chatService/chatService.js'; +import { ChatModelHold } from './sessionChatOpening.js'; + +/** A new-session composer that a chat editor shows while its session is not created ({@link ChatEditorContent.setComposer}). */ +export interface IChatEditorComposer { + /** The host of the composer's drafts. */ + readonly draftHost: INewSessionDraftHost; + /** What the composer shows: its draft, or the session of the request it sent until that ends. */ + readonly session: IObservable; +} + +/** + * What a chat editor shows of one chat: the header of its session above the chat, with its Session Activity Bar, as a + * slot of the main window's grid shows a session's chat. It shows a session scoped to that chat: none of the session's + * other chats show beside it, as each shows in an editor of its own. + */ +export class ChatEditorContent extends Disposable { + + readonly element: HTMLElement = $('.session-view.chat-editor-content.modern-ui-editor-tab-group'); + + private readonly _header: SessionHeader; + private readonly _group: ChatGroupView; + private readonly _headerContainer: HTMLElement; + /** The services of its own scope, which what it shows is created with: disposed after it, see {@link dispose}. */ + private readonly _scopedServices = new DisposableStore(); + private readonly _content = observableValue(this, undefined); + private readonly _composer = observableValue(this, undefined); + private readonly _session = derived(this, reader => this._content.read(reader)?.session ?? this._composer.read(reader)?.session.read(reader)); + private readonly _chat = derived(this, reader => this._content.read(reader)?.chat.read(reader)); + private readonly _showHeader: boolean; + private _headerHidden = false; + private _lastLayout: { readonly width: number; readonly height: number; readonly top: number; readonly left: number } | undefined; + private readonly _visible = observableValue(this, true); + private _active = true; + private readonly _contentContainer: HTMLElement; + /** The view of its composer, or of the request the composer sent, while it shows instead of the chat. */ + private readonly _composerView = observableValue(this, undefined); + /** + * The chat model of a composer's session whose chat it shows, kept loaded from the composer until the chat's view has + * bound to it: only that handoff, as a model held longer cannot be released for its view to load it again, such as + * once its provider is replaced. + */ + private readonly _shownChatModel = this._register(new ChatModelHold(resource => this._chatService.acquireExistingSession(resource, 'ChatEditorContent'))); + /** Tracks whether the chat's view has bound to the model {@link _shownChatModel} holds. */ + private readonly _shownChatBinding = this._register(new MutableDisposable()); + private _moveFocusToGroup = false; + /** Whether it shows the chat: not while another editor of its group, as a tab, shows, nor while its window shows only its main part. */ + readonly visible: IObservable = this._visible; + + /** The host of what it shows: its chat, nested in the host of its window. */ + readonly host: ISessionHost; + /** The chat view of its chat, once it shows the chat. */ + readonly primaryChatView: IObservable; + /** The top of {@link primaryChatView} while it shows only its input: below the bar of its group, as the session header hides then. */ + readonly inputOnlyChatViewTop: IObservable; + /** The session header. */ + get headerElement(): HTMLElement { return this._header.element; } + /** The menu of the actions of the session header, with the context and the arguments they show and run with there. */ + readonly titleMenu: IEditorPaneTitleMenu; + + override dispose(): void { + super.dispose(); + this._scopedServices.dispose(); + } + + constructor( + private readonly _hostOptions: ISessionViewHostOptions | undefined, + @IInstantiationService instantiationService: IInstantiationService, + @IContextKeyService contextKeyService: IContextKeyService, + @ISessionHost parentHost: ISessionHost, + @ISessionHostService sessionHostService: ISessionHostService, + @ISessionChangesStatsCache changesStatsCache: ISessionChangesStatsCache, + @IChatViewFactory private readonly _chatViewFactory: IChatViewFactory, + @IChatService private readonly _chatService: IChatService, + ) { + super(); + this.element.setAttribute('role', 'region'); + this._register(autorun(reader => { + const chat = this._chat.read(reader); + this.element.setAttribute('aria-label', chat + ? localize('chatEditorContent', "Chat: {0}", chat.title.read(reader)) + : this._composer.read(reader) ? localize('chatEditorContentNewSession', "Chat: New Session") : localize('chatEditorContentEmpty', "Chat")); + })); + + const scopedContextKeyService = this._scopedServices.add(contextKeyService.createScoped(this.element)); + // What acts on the main window's grid, such as pinning the session there, does not show in it. + SessionInChatEditorContext.bindTo(scopedContextKeyService).set(true); + this.host = new SessionHost({ kind: SessionHostKind.Pane, parent: parentHost, session: this._session, chat: this._chat, contextKeyService: scopedContextKeyService }); + this._register(sessionHostService.registerHost(this.host)); + const scopedInstantiationService = this._scopedServices.add(instantiationService.createChild(createSessionHostServices(scopedContextKeyService, this.host))); + this._register(autorun(reader => { + const content = this._content.read(reader); + setHostSessionContextKeys(content?.session ?? this._session.read(reader), content?.chat.read(reader), content?.state, scopedContextKeyService, reader, changesStatsCache); + })); + + this._headerContainer = $('.session-view-centered-content'); + this.element.appendChild(this._headerContainer); + this._header = this._register(scopedInstantiationService.createInstance(SessionHeader)); + this._showHeader = _hostOptions?.showHeader ?? true; + this._header.setVisible(this._showHeader); + // It drags the editor that shows the chat (see `ChatEditorView.dragHandle`), which carries the session. + this._header.setDragsEditor(true); + this._headerContainer.appendChild(this._header.element); + this.titleMenu = { menuId: Menus.SessionBarToolbar, contextKeyService: scopedContextKeyService, options: this._header.menuActionOptions }; + this._register(this._header.onDidChangeVisibility(() => this._layoutChildren())); + this._register(this._header.onDidChangeHeight(() => this._layoutChildren())); + + const content = this._contentContainer = $('.session-view-content.standalone-chat'); + this.element.appendChild(content); + // Before the group: the group lets go of the chat before it goes. + this._register(toDisposable(() => this._group.setContext(undefined))); + this._group = this._register(scopedInstantiationService.createInstance(ChatGroupView, _hostOptions)); + content.appendChild(this._group.element); + this._group.setGroupPosition(0, 1); + this._group.setGroupActive(true); + this._register(this._group.onDidChange(() => this._layoutChildren())); + this.primaryChatView = this._group.chatView; + this.inputOnlyChatViewTop = this._group.chatViewTop; + + const showsComposer = derived(this, reader => !this._content.read(reader) && this._composer.read(reader)); + this._register(autorun(reader => { + const composer = showsComposer.read(reader); + if (composer) { + this._showComposer(composer, reader.store, scopedInstantiationService); + } else { + this._showGroup(); + } + })); + } + + /** + * Shows `composer` until the chat shows, as the main window's grid shows its composer: its view, kept while a request it + * sent prepares its session, so that a failure or cancellation gives the composer back its prompt, with the request's + * chat shown meanwhile. Focus moves between the two only where it was in the other. + */ + private _showComposer(composer: IChatEditorComposer, store: DisposableStore, instantiationService: IInstantiationService): void { + // Before its views go, as its session's chat shows: the chat model its input was bound to stays loaded while the chat + // shows, so the chat's view takes that model instead of loading the chat again from its provider, which can still have + // the composer's input as the chat's draft, such as an agent host that syncs drafts after a delay. + store.add(toDisposable(() => { + const chat = this._content.get() ? composer.session.get()?.mainChat.get() : undefined; + this._holdShownChatModel(chat?.resource); + })); + // Before its views go: where focus is then, such as once its session is created, moves to the chat. + store.add(toDisposable(() => this._moveFocusToGroup = isAncestorOfActiveElement(this._contentContainer))); + const view = store.add(this._chatViewFactory.createNewChatView(false, { hostVisible: this._visible, input: this._hostOptions?.input, session: composer.session, newSessionDraft: composer.draftHost }, instantiationService)); + store.add(toDisposable(() => this._composerView.set(undefined, undefined))); + const moveFocus = isAncestorOfActiveElement(this._group.element); + let restoreComposerFocus = false; + // The session a send prepares, whichever progress it reports: its chat shows from its first progress message until + // the send ends, and stays the same view as more messages come. + const preparing = derived(reader => { + const session = composer.session.read(reader); + return session && !isSessionCreated(session, reader) && session.isNewSessionRequestInProgress?.read(reader) && !!session.preparationProgress?.read(reader) ? session : undefined; + }); + store.add(autorun(reader => { + const session = preparing.read(reader); + if (session) { + const moveToPreparation = isAncestorOfActiveElement(view.element); + view.setVisible(false); + const preparationView = this._chatViewFactory.createChatView(instantiationService, { input: this._hostOptions?.input }); + // Before it goes: where focus is then moves back to the composer. + reader.store.add(toDisposable(() => restoreComposerFocus = isAncestorOfActiveElement(preparationView.element))); + reader.store.add(preparationView); + preparationView.setChat(session.mainChat.read(undefined), session.sessionId, session); + this._showComposerView(preparationView); + if (moveToPreparation) { + preparationView.focus(); + } + return; + } + this._showComposerView(view); + if (restoreComposerFocus) { + restoreComposerFocus = false; + view.focus(); + } + })); + if (moveFocus) { + view.focus(); + } + } + + /** + * Holds the model of `resource` until the chat's view has bound to it: it showed that it was loading it and is done, + * which is observed, so a load quicker than the hold polls is not missed. + */ + private _holdShownChatModel(resource: URI | undefined): void { + let loading = false; + let bound = false; + this._shownChatBinding.value = resource ? autorun(reader => { + if (this._group.chatView.read(reader)?.isLoadingTranscript.read(reader)) { + loading = true; + } else if (loading) { + bound = true; + } + }) : undefined; + this._shownChatModel.hold(resource, () => bound); + } + + private _showComposerView(view: AbstractChatView): void { + if (view.element.parentElement !== this._contentContainer) { + this._contentContainer.replaceChildren(view.element); + } + this._composerView.set(view, undefined); + view.setActive(this._active); + view.setVisible(this._visible.get()); + this._layoutChildren(); + } + + private _showGroup(): void { + if (this._group.element.parentElement === this._contentContainer) { + return; + } + const moveFocus = this._moveFocusToGroup; + this._moveFocusToGroup = false; + this._contentContainer.replaceChildren(this._group.element); + this._layoutChildren(); + if (moveFocus) { + this._group.focus(); + } + } + + /** + * Shows `composer` while no chat shows ({@link setContent}), such as for a session the composer did not send yet. Its + * session header hides meanwhile, as the composer shows what it creates the session for. + */ + setComposer(composer: IChatEditorComposer | undefined): void { + if (this._composer.get() !== composer) { + this._composer.set(composer, undefined); + this._updateHeaderVisibility(); + this._layoutChildren(); + } + } + + /** Shows `content`, the one chat of the provider's session its pane shows; nothing while undefined. */ + setContent(content: ISessionPaneContent | undefined): void { + if (this._content.get() === content) { + return; + } + this._shownChatModel.release(); + this._shownChatBinding.clear(); + const chat = content?.chat.get(); + // The group has the chat before it replaces a composer, which hands focus to it. + transaction(tx => { + this._content.set(content, tx); + this._header.setSession(content); + this._updateHeaderVisibility(); + this._group.setContext(content && chat ? this._createContext(content, chat) : undefined); + }); + this._layoutChildren(); + } + + private _createContext(content: ISessionPaneContent, chat: IChat): IChatGroupContext { + const session = content.session; + return { + session, + isDetached: content.state.isDetached, + closePane: () => content.close(), + options: { session: this._session, chat: this._chat }, + chats: constObservable([chat]), + activeChatResource: constObservable(chat.resource.toString()), + mainChatResource: session.mainChat.map(main => main.resource.toString()), + tabsVisible: constObservable(false), + chatHeaderVisible: constObservable(false), + activeChatIsPinned: constObservable(false), + showSessionActions: constObservable(false), + showParentContext: constObservable(false), + activate: () => { }, + openChat: () => { }, + onTabDragStart: () => { }, + onTabDragEnd: () => { }, + }; + } + + /** Hides the session header, such as while the chat shows only its input, and shows it again. */ + setHeaderHidden(hidden: boolean): void { + this._headerHidden = hidden; + this._updateHeaderVisibility(); + } + + private _updateHeaderVisibility(): void { + const showsComposer = !this._content.get() && !!this._composer.get(); + this._header.setVisible(this._showHeader && !this._headerHidden && !showsComposer); + } + + /** + * Shows or hides the chat, such as while another editor of its group, as a tab, shows; `partVisible` is false while + * what hosts it is hidden, so that its Session Activity Bar can still show outside of it. + */ + setVisible(visible: boolean, partVisible = true): void { + this._visible.set(visible, undefined); + this._group.setSessionVisible(visible, partVisible); + this._composerView.get()?.setVisible(visible); + this._layoutChildren(); + } + + /** Whether it shows the active chat, of those beside it: only that one shows the Session Activity Bar. */ + setActive(active: boolean): void { + this._active = active; + this._group.setGroupActive(active); + this._composerView.get()?.setActive(active); + } + + layout(width: number, height: number, top: number, left: number): void { + this._lastLayout = { width, height, top, left }; + this._layoutChildren(); + } + + private _layoutChildren(): void { + if (!this._lastLayout || !this._visible.get()) { + return; + } + const { width, height, top, left } = this._lastLayout; + const headerHeight = this._header.visible ? this._header.height : 0; + size(this._headerContainer, width, headerHeight); + const composerView = this._composerView.get(); + if (composerView) { + composerView.layout(width, Math.max(0, height - headerHeight), top + headerHeight, left); + } else { + this._group.layout(width, Math.max(0, height - headerHeight), top + headerHeight, left); + } + } + + focus(): void { + const composerView = this._composerView.get(); + if (composerView) { + composerView.focus(); + } else { + this._group.focus(); + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatEditor/chatWindowComposer.ts b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatWindowComposer.ts new file mode 100644 index 000000000000..b2d6dd50dc3b --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatEditor/chatWindowComposer.ts @@ -0,0 +1,574 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { isCancellationError } from '../../../../../base/common/errors.js'; +import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { derived, IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { parse, stringify } from '../../../../../base/common/marshalling.js'; +import { extUriBiasedIgnorePathCase } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IFolderLocation } from '../../../../../platform/workspace/common/folderLocations.js'; +import { generateUuid } from '../../../../../base/common/uuid.js'; +import { localize } from '../../../../../nls.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { INotificationService, Severity } from '../../../../../platform/notification/common/notification.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { IClipboardService } from '../../../../../platform/clipboard/common/clipboardService.js'; +import { IAction, toAction } from '../../../../../base/common/actions.js'; +import { IChatDraft } from '../../../chat/common/attachments/chatDraft.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { getInheritedNewSessionTarget } from '../chat/newSessionAction.js'; +import { INewSessionBackgroundSend, INewSessionDraftHost, INewSessionTarget } from '../parts/chatView.js'; +import { ISessionGroupsService } from '../sessionGroupsService.js'; +import { ISessionsProvidersService } from '../sessionsProvidersService.js'; +import { ComposerInputSnapshot, fromStoredChatDraft, IComposerInputState, toStoredChatDraft } from '../../common/newChatDraftState.js'; +import { IChat, ISession, isSessionCreated } from '../../../../services/sessions/common/session.js'; +import { INewSessionDraftSlot, ISessionsManagementService, trackNewSessionRequestEnd, WorkspaceNotTrustedError } from '../../common/sessionsManagement.js'; + +/** The scheme of the resource of a new-session composer in a chat window: its chat until it sends its session. */ +export const CHAT_WINDOW_COMPOSER_SCHEME = 'vscode-agents-composer'; + +/** A new resource for a composer of a chat window. */ +export function createChatWindowComposerResource(): URI { + return URI.from({ scheme: CHAT_WINDOW_COMPOSER_SCHEME, path: `/${generateUuid()}` }); +} + +/** Whether `resource` names a new-session composer of a chat window. */ +export function isChatWindowComposerResource(resource: URI): boolean { + return resource.scheme === CHAT_WINDOW_COMPOSER_SCHEME; +} + +/** + * What a composer opened from `session` and its `chat` starts its new session with: the session's folder (the source + * folder of its Dev Container), or no workspace as a quick chat has, the session's provider and agent where they serve + * it, and the chat's model and mode. Nothing without a session, or for a session without a workspace that is not a + * quick chat: the composer then starts as the main window's composer does. + */ +export function getChatWindowComposerTarget(sessionsManagementService: ISessionsManagementService, sessionsProvidersService: ISessionsProvidersService, session: ISession | undefined, chat: IChat | undefined): INewSessionTarget | undefined { + if (!session) { + return undefined; + } + const ofChat = (): Pick => { + const modelId = chat?.modelId?.get(); + const modeId = chat?.mode?.get()?.id; + return { ...(modelId ? { modelId } : {}), ...(modeId ? { modeId } : {}) }; + }; + if (session.isQuickChat?.get()) { + return { providerId: session.providerId, sessionTypeId: session.sessionType, ...ofChat() }; + } + const inherited = getInheritedNewSessionTarget(sessionsManagementService, sessionsProvidersService, session); + if (!inherited.folderUri) { + return undefined; + } + return { + folderUri: inherited.folderUri, + ...(inherited.providerId ? { providerId: inherited.providerId } : {}), + ...(inherited.sessionTypeId ? { sessionTypeId: inherited.sessionTypeId } : {}), + ...(inherited.requireDevContainer ? { requireDevContainer: true } : {}), + ...ofChat(), + }; +} + +/** How a background send that did not start gives its prompt back to its composer ({@link ChatWindowComposerBackgroundSends.track}). */ +export interface IBackgroundSendRecovery { + /** The prompt as the user wrote it, with its attachments and inline references. */ + readonly input: IChatDraft; + /** + * Whether the composer takes the prompt back without asking: it is still there, the send is its latest, and what it + * aims for did not change since the send. {@link restore} then gives it back only while its input is empty and idle. + */ + canRestoreSilently(): boolean; + /** Whether the composer is still there. */ + isAlive(): boolean; + /** + * Gives the prompt back to the composer, only while its input is empty and idle and shows it: never over what the user + * wrote since, nor while it sends, `busy` then; `gone` once the composer is gone. + */ + restore(): 'restored' | 'busy' | 'gone'; +} + +/** + * Follows the background sends of the composers of chat windows until each ends, also after its composer is gone, and + * reports a failure: the management service does not notify the failures of a composer's own draft slot. The prompt of + * a failed send goes back into its composer when nothing changed there since; otherwise the notification offers to + * restore it, without changing what the composer aims for now, or to copy it, also once the composer is gone. So does + * the prompt of an ordinary send that the composer sent in the background and the user cancelled, without an error. + */ +export class ChatWindowComposerBackgroundSends extends Disposable { + + private readonly _sends = this._register(new DisposableStore()); + + constructor( + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @INotificationService private readonly _notificationService: INotificationService, + @IAccessibilityService private readonly _accessibilityService: IAccessibilityService, + @IClipboardService private readonly _clipboardService: IClipboardService, + @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, + ) { + super(); + } + + /** Follows `send` of `owner` until it ends; disposing the result stops following it, such as when it was not dispatched. */ + track(owner: INewSessionDraftSlot, send: INewSessionBackgroundSend, recovery: IBackgroundSendRecovery): IDisposable { + const entry = this._sends.add(new DisposableStore()); + entry.add(toDisposable(() => this._sends.deleteAndLeak(entry))); + // Where it was sent, as it is when it ends, for its notification + let session = send.session; + entry.add(this._sessionsManagementService.onDidReplaceNewDraftSession(({ from, to }) => { + if (from.sessionId === session.sessionId) { + session = to; + } + })); + entry.add(trackNewSessionRequestEnd(this._sessionsManagementService, owner, send.session, ({ started, error }) => { + entry.dispose(); + if (started) { + return; + } + if (error !== undefined && !isCancellationError(error) && !(error instanceof WorkspaceNotTrustedError)) { + this._giveBack(session, recovery, error); + } else if (!send.requestedInBackground) { + // An ordinary send that the composer sent in the background, which the user did not start, such as by declining + // to trust its workspace: as that of a foreground send, its prompt goes back to the composer, without an error. + this._giveBack(session, recovery, undefined); + } + })); + return entry; + } + + /** Gives the prompt of a send that did not start back to its composer; reports `error` when it failed. */ + private _giveBack(session: ISession, recovery: IBackgroundSendRecovery, error: unknown): void { + if (recovery.canRestoreSilently() && recovery.restore() === 'restored') { + if (error !== undefined) { + this._notificationService.error(localize('chatWindowComposer.backgroundSendFailed', "Couldn't start the session: {0}", toErrorMessage(error))); + this._accessibilityService.status(localize('chatWindowComposer.promptRestored', "The prompt of the session that couldn't start is back in the composer.")); + } else { + this._accessibilityService.status(localize('chatWindowComposer.unstartedPromptRestored', "The prompt of the session that wasn't started is back in the composer.")); + } + return; + } + const actions: IAction[] = []; + if (recovery.isAlive()) { + actions.push(toAction({ + id: 'chatWindowComposer.restorePrompt', label: localize('chatWindowComposer.restorePrompt', "Restore Prompt"), run: async () => { + // Never over what the user wrote since, nor while it sends, nor once it is gone: the prompt goes to the clipboard instead. + if (recovery.restore() !== 'restored') { + await this._clipboardService.writeText(recovery.input.inputText); + this._notificationService.info(localize('chatWindowComposer.promptCopiedInstead', "The composer can't take the prompt back now, so it was copied to the clipboard instead.")); + } + }, + })); + } + actions.push(toAction({ id: 'chatWindowComposer.copyPrompt', label: localize('chatWindowComposer.copyPrompt', "Copy Prompt"), run: () => this._clipboardService.writeText(recovery.input.inputText) })); + const workspace = session.isQuickChat?.get() ? localize('chatWindowComposer.noWorkspace', "No Workspace") : session.workspace.get()?.label ?? localize('chatWindowComposer.noWorkspace', "No Workspace"); + const agent = this._sessionsProvidersService.getProvider(session.providerId, session.sessionId)?.sessionTypes.find(type => type.id === session.sessionType)?.label ?? session.sessionType; + this._notificationService.notify({ + severity: error !== undefined ? Severity.Error : Severity.Info, + message: error !== undefined + ? localize('chatWindowComposer.backgroundSendFailedIn', "Couldn't start the session in {0} with {1}: {2}", workspace, agent, toErrorMessage(error)) + : localize('chatWindowComposer.backgroundSendNotStartedIn', "The session in {0} with {1} wasn't started.", workspace, agent), + actions: { primary: actions }, + }); + } +} + +/** What a composer of a chat window starts with. */ +export interface IChatWindowComposerInit { + /** What it creates its drafts for; as the main window's composer does while undefined. */ + readonly target?: INewSessionTarget; + /** The custom group of the sessions list that the sessions it sends join. */ + readonly groupId?: string; + readonly input?: IComposerInputState; + /** + * The folders of the window it opens in, such as an editor window's, the only ones it creates sessions in besides the + * folder of its {@link target}. None restrict it, as in a window without folders. + */ + readonly allowedFolders?: IObservable; + /** How it shows one of its {@link allowedFolders}, such as a linked checkout of the window's folder. */ + readonly getFolderPresentation?: (folderUri: URI) => IFolderLocation | undefined; +} + +/** + * A new-session composer of a chat window, as the host of its drafts ({@link INewSessionDraftHost}): it holds them in a + * draft slot of its own, so that it never takes or replaces the main window composer's draft, and aims them at what it + * was opened with, until the user picks otherwise. The sessions it sends join its custom group of the sessions list. + * + * A foreground send keeps showing its session, as the composer's, until the request ends: once it started its session, + * {@link onDidStart} fires, and the composer's chat becomes the session's main chat; otherwise the composer shows its + * draft again. A background send leaves the composer with a new draft. + */ +export class ChatWindowComposerModel extends Disposable implements INewSessionDraftHost { + + readonly slot: INewSessionDraftSlot & IDisposable; + readonly input: ComposerInputSnapshot; + + /** Counts the user's changes of what it aims for, so that a failed background send knows whether it changed since. */ + private _targetGeneration = 0; + private _disposed = false; + + private readonly _requestedTarget = observableValue(this, undefined); + readonly requestedTarget: IObservable = this._requestedTarget; + + /** What it aimed for as it sent its last foreground request. */ + private _targetOfSend: { readonly target: INewSessionTarget | undefined } | undefined; + + /** The session of the foreground request it sent, until the request ends. */ + private readonly _sending = observableValue(this, undefined); + private readonly _sendingTracking = this._register(new MutableDisposable()); + + /** What it shows: its draft, or the session of the foreground request it sent, until the request ends. */ + readonly session: IObservable; + + private readonly _onDidStart = this._register(new Emitter()); + /** Fires with its session once a foreground request it sent started it. */ + readonly onDidStart = this._onDidStart.event; + + private readonly _onWillDispose = this._register(new Emitter()); + readonly onWillDispose = this._onWillDispose.event; + + /** The custom group of the sessions list that the sessions it sends join. */ + readonly groupId: string | undefined; + + readonly allowedFolders: IObservable | undefined; + private readonly _getFolderPresentation: ((folderUri: URI) => IFolderLocation | undefined) | undefined; + + constructor( + readonly resource: URI, + init: IChatWindowComposerInit, + private readonly _backgroundSends: ChatWindowComposerBackgroundSends, + private readonly _openStartedSession: (session: ISession) => Promise, + @ISessionsManagementService private readonly _sessionsManagementService: ISessionsManagementService, + @ISessionGroupsService sessionGroupsService: ISessionGroupsService, + ) { + super(); + this.groupId = init.groupId; + this._getFolderPresentation = init.getFolderPresentation; + const windowFolders = init.allowedFolders; + const targetFolder = init.target?.folderUri; + this.allowedFolders = windowFolders && derived(this, reader => { + const folders = windowFolders.read(reader); + return folders.length && targetFolder && !folders.some(folder => extUriBiasedIgnorePathCase.isEqual(folder, targetFolder)) ? [...folders, targetFolder] : folders; + }); + this._requestedTarget.set(init.target, undefined); + this.input = new ComposerInputSnapshot(init.input); + this.slot = this._register(_sessionsManagementService.createNewSessionSlot({ readoptOnFailure: session => this._isRequested(session) })); + this._register(sessionGroupsService.setDraftSlotGroup(this.slot.id, init.groupId)); + this.session = derived(this, reader => this._sending.read(reader) ?? this.slot.newSession.read(reader)); + this._register(_sessionsManagementService.onDidAcceptNewSessionRequest(({ session, owner, background }) => { + if (owner === this.slot && background) { + // Its send went out, so a reload restores neither it nor what was sent, also while its next draft is created. + const attempt = this.input.get().attempt; + if (attempt) { + this.input.endSendAttempt(attempt.id); + } + return; + } + if (owner === this.slot && !background) { + this._targetOfSend = { target: this._requestedTarget.get() }; + // A reload before the request ends restores the session it started, or else what was sent. + this.input.setSendAttemptSession(session.resource); + this._followSend(session); + } + })); + } + + override dispose(): void { + this._disposed = true; + this._onWillDispose.fire(); + super.dispose(); + } + + /** What it stores to be restored, such as after a reload: what it aims for, its group and its input. */ + toStored(): IStoredChatWindowComposer { + const target = this._requestedTarget.get(); + return { resource: this.resource, ...(target ? { target } : {}), ...(this.groupId ? { groupId: this.groupId } : {}), ...this.input.get() }; + } + + setRequestedTarget(target: INewSessionTarget, reason: 'user' | 'background' = 'user'): void { + this._requestedTarget.set(target, undefined); + if (reason === 'user') { + this._targetGeneration++; + } + } + + getFolderPresentation(folderUri: URI): IFolderLocation | undefined { + return this._getFolderPresentation?.(folderUri); + } + + openStartedSession(session: ISession): Promise { + return this._openStartedSession(session); + } + + trackBackgroundSend(send: INewSessionBackgroundSend): IDisposable { + // What the user wrote, as the send's attempt has it before the composer cleared it, with its inline references. + const input = this.input.get().attempt?.input ?? { inputText: send.query, attachments: [...(send.attachedContext ?? [])] }; + const generation = this._targetGeneration; + // Held weakly: these recovery callbacks do not keep the composer alive for a send that outlives it. + const composer = new WeakRef(this); + const alive = () => { + const target = composer.deref(); + return target && !target._disposed ? target : undefined; + }; + return this._backgroundSends.track(this.slot, send, { + input, + isAlive: () => !!alive(), + canRestoreSilently: () => { + const target = alive(); + return !!target && send.isLatest() && target._targetGeneration === generation; + }, + restore: () => { + const target = alive(); + if (!target) { + return 'gone'; + } + // Only once its input shows it: not while it sends, such as while it reseeds after another background send. + return target.isIdle() && target.input.restore(input) ? 'restored' : 'busy'; + }, + }); + } + + /** Whether its input is empty and no send of it is under way. */ + isIdle(): boolean { + const state = this.input.get(); + return !state.attempt && !state.input.inputText && !state.input.attachments.length; + } + + /** Whether closing it loses nothing: its input is empty, and no foreground request of it is under way. */ + isPristine(): boolean { + return !this._sending.get() && this.isIdle(); + } + + /** + * Whether the draft of a foreground request that failed is still what the composer aims for, to retry it: what it + * aims for did not change since it sent it. The draft's workspace is not compared with the requested folder, which + * it can be of without having its URI, such as a cloud agent's draft of the folder's GitHub repository. + */ + private _isRequested(_session: ISession): boolean { + return !!this._targetOfSend && this._targetOfSend.target === this._requestedTarget.get(); + } + + private _followSend(session: ISession): void { + const store = new DisposableStore(); + this._sendingTracking.value = store; + this._sending.set(session, undefined); + const follow = ({ from, to }: { readonly from: ISession; readonly to: ISession }) => { + if (from.sessionId === this._sending.get()?.sessionId) { + this._sending.set(to, undefined); + this.input.setSendAttemptSession(to.resource); + } + }; + store.add(this._sessionsManagementService.onDidReplaceNewDraftSession(follow)); + store.add(this._sessionsManagementService.onDidReplaceSession(follow)); + store.add(trackNewSessionRequestEnd(this._sessionsManagementService, this.slot, session, ({ session: ended, started }) => { + if (started) { + this._sending.set(ended, undefined); + this._onDidStart.fire(ended); + return; + } + if (this._sendingTracking.value === store) { + this._sendingTracking.clear(); + this._sending.set(undefined, undefined); + } + })); + } +} + +/** A composer of a chat window as it is stored ({@link ChatWindowComposerModel.toStored}). */ +export interface IStoredChatWindowComposer extends IComposerInputState { + readonly resource: URI; + readonly target?: INewSessionTarget; + readonly groupId?: string; +} + +/** What a stored composer restores as: the session that a send it had not seen end started, or a composer. */ +export type RestoredChatWindowComposer = { readonly kind: 'session'; readonly session: ISession } | { readonly kind: 'composer'; readonly composer: ChatWindowComposerModel }; + +/** The key of the composers of chat windows that were open when the window last closed. */ +export const CHAT_WINDOW_COMPOSERS_STORAGE_KEY = 'sessions.chatWindow.composers'; + +function isOptionalString(value: unknown): value is string | undefined { + return value === undefined || typeof value === 'string'; +} + +/** The stored composer that `value` is, unmarshalled; throws when it is none. */ +function fromStoredComposer(value: unknown): IStoredChatWindowComposer { + const entry = value as { resource?: unknown; target?: Partial>; groupId?: unknown; input?: unknown; attempt?: { id?: unknown; input?: unknown; session?: unknown } } | undefined; + const target = entry?.target; + const attempt = entry?.attempt; + if (!entry || !URI.isUri(entry.resource) || !isChatWindowComposerResource(entry.resource) || !isOptionalString(entry.groupId) + || (target !== undefined && (typeof target !== 'object' || target === null || (target.folderUri !== undefined && !URI.isUri(target.folderUri)) + || !isOptionalString(target.providerId) || !isOptionalString(target.sessionTypeId) || !isOptionalString(target.modelId) || !isOptionalString(target.modeId) + || (target.requireDevContainer !== undefined && typeof target.requireDevContainer !== 'boolean'))) + || (attempt !== undefined && (typeof attempt !== 'object' || attempt === null || typeof attempt.id !== 'string' || (attempt.session !== undefined && !URI.isUri(attempt.session))))) { + throw new Error('Invalid chat window composer.'); + } + return { + resource: entry.resource, + ...(target ? { target: target as INewSessionTarget } : {}), + ...(entry.groupId ? { groupId: entry.groupId } : {}), + input: fromStoredChatDraft(entry.input), + ...(attempt ? { attempt: { id: attempt.id as string, input: fromStoredChatDraft(attempt.input), ...(attempt.session ? { session: attempt.session as URI } : {}) } } : {}), + }; +} + +function toStoredComposer(composer: IStoredChatWindowComposer): unknown { + return { + resource: composer.resource, + target: composer.target, + groupId: composer.groupId, + input: toStoredChatDraft(composer.input), + attempt: composer.attempt && { id: composer.attempt.id, session: composer.attempt.session, input: toStoredChatDraft(composer.attempt.input) }, + }; +} + +/** + * The composers of the chat windows: those open, and those stored when the window last closed until they restore. It + * stores them all as the state of the window is saved, never as their input changes, and forgets the stored ones that + * the restoration of the chat windows did not restore ({@link didFinishRestore}). + */ +export class ChatWindowComposers extends Disposable { + + /** The background sends of the composers, followed also after their composer and window are gone. */ + readonly backgroundSends: ChatWindowComposerBackgroundSends; + + private readonly _stored = new Map(); + private readonly _live = new Map(); + /** The stored composers restoring, until they are restored. */ + private readonly _restoring = new Set(); + /** The stored composers restored, by the chat each restored as, until that chat opens in a window ({@link didOpen}). */ + private readonly _restoredAs = new Map(); + + /** + * @param _waitForSession Waits a while for the session of a resource to be known, such as once its provider loaded + * it; undefined when it does not become known. + */ + constructor( + private readonly _waitForSession: (resource: URI) => Promise, + @IStorageService private readonly _storageService: IStorageService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + this.backgroundSends = this._register(_instantiationService.createInstance(ChatWindowComposerBackgroundSends)); + this._read(); + this._register(_storageService.onWillSaveState(() => this._save())); + } + + /** Creates a composer of `resource`, which it stores while it is open. */ + create(resource: URI, init: IChatWindowComposerInit, openStartedSession: (session: ISession) => Promise): ChatWindowComposerModel { + const key = resource.toString(); + const composer = this._instantiationService.createInstance(ChatWindowComposerModel, resource, init, this.backgroundSends, openStartedSession); + this._live.set(key, composer); + Event.once(composer.onWillDispose)(() => { + if (this._live.get(key) === composer) { + this._live.delete(key); + } + // A restored composer that goes before its window opened, such as as opening the window failed, stays stored. + if (this._restoredAs.get(key) === key) { + this._restoredAs.delete(key); + } + }); + return composer; + } + + /** Whether the composer of `resource` was stored and was not restored in an open window yet. */ + hasStored(resource: URI): boolean { + return this._stored.has(resource.toString()); + } + + /** + * Restores the stored composer of `resource`: as the session that a foreground send it had sent started, once that + * session is known, or else as a composer with its input, or with the input of a send that did not end, which it no + * longer follows. It stays stored until the chat it restores as opens in a window ({@link didOpen}), so that a window + * that fails to open loses nothing. + */ + async restore(resource: URI, openStartedSession: (session: ISession) => Promise, folders?: Pick): Promise { + const key = resource.toString(); + const stored = this._stored.get(key); + if (!stored || this._live.has(key) || this._restoring.has(key)) { + return undefined; + } + this._restoring.add(key); + let sent: ISession | undefined; + try { + sent = stored.attempt?.session && await this._waitForSession(stored.attempt.session); + } finally { + this._restoring.delete(key); + } + if (this._stored.get(key) !== stored) { + return undefined; + } + if (sent && isSessionCreated(sent)) { + this._restoredAs.set(sent.mainChat.get().resource.toString(), key); + return { kind: 'session', session: sent }; + } + const input = stored.attempt?.input ?? stored.input; + this._restoredAs.set(key, key); + return { kind: 'composer', composer: this.create(resource, { target: stored.target, groupId: stored.groupId, input: { input }, ...folders }, openStartedSession) }; + } + + /** The session that a foreground send of the stored composer of `resource` went out with, if any. */ + storedAttemptSessionOf(resource: URI): URI | undefined { + return this._stored.get(resource.toString())?.attempt?.session; + } + + /** Forgets the stored composers that restored as one of `chats`, which are open in a window now. */ + didOpen(chats: readonly URI[]): void { + for (const chat of chats) { + const key = this._restoredAs.get(chat.toString()); + if (key !== undefined) { + this._restoredAs.delete(chat.toString()); + this._stored.delete(key); + } + } + } + + /** + * Forgets the stored composers that the restoration of the chat windows did not claim (`claimed`): the windows it + * restored, and those whose opening failed, which it keeps to restore next time. + */ + didFinishRestore(claimed: readonly URI[]): void { + const keep = new Set(claimed.map(resource => resource.toString())); + for (const key of [...this._stored.keys()]) { + if (!keep.has(key)) { + this._stored.delete(key); + } + } + } + + private _read(): void { + const raw = this._storageService.get(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, StorageScope.WORKSPACE); + if (!raw) { + return; + } + let entries: unknown; + try { + entries = parse(raw); + } catch (error) { + this._logService.error('[ChatWindow] Could not read the stored composers of chat windows', error); + return; + } + for (const entry of Array.isArray(entries) ? entries : []) { + try { + const stored = fromStoredComposer(entry); + this._stored.set(stored.resource.toString(), stored); + } catch (error) { + this._logService.warn('[ChatWindow] Not restoring a stored composer of a chat window', error); + } + } + } + + private _save(): void { + // A composer that restored and is open stores what it has now rather than what it restored from. + const composers = [...[...this._live.values()].map(composer => composer.toStored()), ...[...this._stored.entries()].filter(([key]) => !this._live.has(key)).map(([, stored]) => stored)]; + if (composers.length) { + this._storageService.store(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, stringify(composers.map(toStoredComposer)), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } else { + this._storageService.remove(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, StorageScope.WORKSPACE); + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatEditorHost.ts b/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatEditorHost.ts new file mode 100644 index 000000000000..10c19ee29cb4 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatEditorHost.ts @@ -0,0 +1,407 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { raceTimeout } from '../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, constObservable, derived, IObservable, IReader, ISettableObservable, observableSignal, observableValue, transaction } from '../../../../../base/common/observable.js'; +import { extUri, isEqual } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { localize } from '../../../../../nls.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IChatService } from '../../../chat/common/chatService/chatService.js'; +import { IChat, ISession, isSessionCreated } from '../../../../services/sessions/common/session.js'; +import { ISessionPaneContent } from '../../../../services/sessions/common/sessionPane.js'; +import { ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { getSessionAgentMergeConfigurationObservable } from '../sessionAgentMerge.js'; +import { ISessionsListModelService } from '../sessionsListModelService.js'; +import { ISessionsProvidersService } from '../sessionsProvidersService.js'; +import { ShownChatReadMarker } from '../shownChatReadMarker.js'; +import { ChatEditorInput, getChatEditorInputDetails, IChatEditorWindow, ISessionChatViewHost, registerSessionChatViewHost } from './chatEditor.js'; +import { ChatEditorContent, IChatEditorComposer } from './chatEditorContent.js'; +import { ChatModelHold, chatWindowTitle, isChatWindowChatGone } from './sessionChatOpening.js'; +import { ChatWindowComposerModel } from './chatWindowComposer.js'; + +/** How long a host of session chat editors waits for a session to be known, such as while its provider loads it. */ +export const SESSION_CHAT_WAIT_TIMEOUT = 30_000; + +/** A session and the chat of it that its editor shows. */ +export interface ISessionChatEditorShown { + readonly session: ISession; + readonly chat: IChat; +} + +/** A session, and the chat that a resource names: a session names its own; a chat, also by a previous identity, its session. */ +export interface IResolvedSessionChat { + readonly session: ISession; + /** The chat, by its current resource; undefined when the resource names the session. */ + readonly chat: URI | undefined; +} + +/** The session and chat that `resource` names, among the sessions known to the window. */ +export function resolveSessionChat(sessionsManagementService: ISessionsManagementService, resource: URI): IResolvedSessionChat | undefined { + const session = sessionsManagementService.getSession(resource); + if (session) { + return { session, chat: undefined }; + } + const owner = sessionsManagementService.getSessionForChatResource(resource); + return owner && { session: owner.session, chat: owner.chat.resource }; +} + +/** What {@link resolveSessionChat} resolves `resource` as, once a session that names it is known, or undefined after `timeout`. */ +export async function waitForSessionChat(sessionsManagementService: ISessionsManagementService, resource: URI, timeout = SESSION_CHAT_WAIT_TIMEOUT): Promise { + const resolved = resolveSessionChat(sessionsManagementService, resource); + if (resolved) { + return resolved; + } + const store = new DisposableStore(); + try { + return await raceTimeout(new Promise(resolve => { + // Of every session, also one outside a listing scope, such as of another folder, which a host can show + store.add(sessionsManagementService.onDidChangeSession(changes => { + if (store.isDisposed || (changes.length > 0 && changes.every(({ kind }) => kind === 'removed'))) { + return; + } + const loaded = resolveSessionChat(sessionsManagementService, resource); + if (loaded) { + // Stop following the sessions as soon as it resolves + store.dispose(); + resolve(loaded); + } + })); + }), timeout); + } finally { + store.dispose(); + } +} + +/** + * One chat that a host of session chat editors shows, such as a chat window or the chat part of an editor window: its editor, + * and the provider's session of the chat, which its editor shows. It observes the session without owning it, and follows + * the chat, such as when its session is replaced or the chat moves to another session; the chat ends ({@link onDidEnd}) once + * it is deleted or archived, or its session is removed. While it is a new-session composer, it shows the composer until a + * foreground request of it starts its session, whose main chat it then shows, in the same editor. + * + * A subclass calls {@link start} once it is constructed: what it starts calls the subclass's hooks. + */ +export abstract class SessionChatEditorEntry extends Disposable implements ISessionChatViewHost { + + readonly chat: ISettableObservable; + readonly input: ChatEditorInput; + readonly title: IObservable; + + private readonly _onDidEnd = this._register(new Emitter()); + /** Fires once the chat ends, such as once it is deleted: its host then closes its editor. */ + readonly onDidEnd: Event = this._onDidEnd.event; + private _ended = false; + private _disposed = false; + + private readonly _onWillDispose = this._register(new Emitter()); + readonly onWillDispose: Event = this._onWillDispose.event; + + /** The provider's session of the chat, and the chat, once known. */ + private readonly _shown = observableValue(this, undefined); + /** Its new-session composer while the chat is that, until the composer's foreground request starts its session. */ + private readonly _composer = observableValue(this, undefined); + private readonly _composerStore = this._register(new MutableDisposable()); + /** The session the composer sent and the session's main chat, once the session is created, until the chat becomes it. */ + private readonly _composerShown = derived(this, reader => { + const session = this._composer.read(reader)?.session.read(reader); + return session && isSessionCreated(session, reader) ? { session, chat: session.mainChat.read(reader) } : undefined; + }); + + /** What its editor shows of a session: the chat once known, or the session its composer started, until the chat becomes it. */ + readonly shown: IObservable = derived(this, reader => this._composer.read(reader) ? this._composerShown.read(reader) : this._shown.read(reader)); + /** The session of the chat, or of its composer, such as its draft. */ + readonly session: IObservable = derived(this, reader => { + const composer = this._composer.read(reader); + return composer ? composer.session.read(reader) : this._shown.read(reader)?.session; + }); + readonly shownChat: IObservable = derived(this, reader => this.shown.read(reader)?.chat); + readonly content: IObservable; + readonly composer: IObservable = derived(this, reader => { + const composer = this._composer.read(reader); + return composer && { draftHost: composer, session: composer.session }; + }); + /** Whether it is a new-session composer that has not sent its session yet, which cannot leave its window. */ + readonly isUnsentComposer: IObservable = derived(this, reader => !!this._composer.read(reader)); + /** Whether it is a new-session composer that has not sent its session yet. */ + get isComposer(): boolean { return !!this._composer.get(); } + /** Whether it is a new-session composer whose closing loses nothing (see {@link ChatWindowComposerModel.isPristine}). */ + get isPristineComposer(): boolean { return !!this._composer.get()?.isPristine(); } + /** The custom group of the sessions list that the sessions of its new-session composer join, while it is one. */ + get composerGroupId(): string | undefined { return this._composer.get()?.groupId; } + + /** The session the chat was last known in, so that its end is known while the session no longer lists it. */ + private _knownSession: ISession | undefined; + /** Whether its known session was removed, such as deleted: not hidden as its provider goes away, which removes nothing. */ + private _knownSessionRemoved = false; + + /** The views of its editor, the last of which shows it; see {@link view}. */ + private readonly _attachedViews: ChatEditorContent[] = []; + private readonly _view = observableValue(this, undefined); + readonly view: IObservable = this._view; + + /** The window its editor shows in. */ + abstract readonly window: IObservable; + /** Whether its chat is the active one of its window. */ + abstract readonly active: IObservable; + + constructor( + chatResource: URI, + @ISessionsManagementService protected readonly sessionsManagementService: ISessionsManagementService, + @IChatService private readonly _chatService: IChatService, + @ISessionsListModelService private readonly _sessionsListModelService: ISessionsListModelService, + @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, + @IConfigurationService private readonly _configurationService: IConfigurationService, + ) { + super(); + this.chat = observableValue(this, chatResource); + this.input = this._register(new ChatEditorInput(chatResource)); + this._register(registerSessionChatViewHost(this.input, this)); + this.title = derived(this, reader => { + if (this._composer.read(reader)) { + return localize('sessionChatEditor.newSession', "New Session"); + } + const session = this.session.read(reader); + return session ? chatWindowTitle(session, this.chat.read(reader), reader) : ''; + }); + this.content = derived(this, reader => { + const shown = this.shown.read(reader); + return shown && this._contentOf(shown, () => this.shown.read(undefined) === shown); + }); + } + + /** + * Starts following the chat, or showing `composer`, which it then owns: its tab, read state and session. `holdReason` + * names what holds the chat's loaded model until its editor's view binds to it. + */ + protected start(composer: ChatWindowComposerModel | undefined, holdReason: string): void { + this._register(autorun(reader => this.input.setName(this.title.read(reader)))); + // Its tab shows the status of the chat, as the sessions list does + this._register(autorun(reader => { + const shown = this._shown.read(reader); + this.input.setDetails(shown && getChatEditorInputDetails(shown.session, shown.chat, this.title.read(reader), reader, this._sessionsListModelService, + () => getSessionAgentMergeConfigurationObservable(shown.session, this._sessionsProvidersService, this._configurationService, shown.chat))); + })); + // It is read once it shows: while it is the active chat of its window, focused or not, and its editor shows it + const readMarker = new ShownChatReadMarker(this.sessionsManagementService, extUri); + this._register(autorun(reader => { + const shown = this._shown.read(reader); + if (!shown) { + readMarker.reset(); + return; + } + const visible = this.active.read(reader) && !!this._view.read(reader)?.visible.read(reader); + readMarker.update(shown.session, visible ? shown.chat : undefined, reader); + })); + + // The loaded model of the chat bridges its opening, such as its move from another window, which lets go of it + const heldChat = this._register(new ChatModelHold(resource => this._chatService.acquireExistingSession(resource, holdReason))); + if (composer) { + this._setComposer(composer); + } else { + heldChat.hold(this.chat.get(), this._boundCheck()); + } + + // Once it knows its session, only sessions added, removed or replaced can change where its chat is: what changes in its + // session it reads from that session. So the many changes of other sessions, such as while they stream, pass it by. + // A replacement, such as a pending session committed under the same ID, comes as a change of another object. + const sessionsChanged = observableSignal(this); + + // A session replaced by one with another ID, such as one its host hands off to another connection, is removed right + // after: the chat follows to the chat of the replacement that continues it, rather than ending with the session. + this._register(this.sessionsManagementService.onDidReplaceSession(({ from, to, chats }) => { + const known = this._knownSession; + if (this._ended || this._composer.get() || !known || !isEqual(known.resource, from.resource)) { + return; + } + const current = this.chat.get(); + const next = chats?.get(current) ?? (isEqual(current, from.mainChat.get().resource) ? to.mainChat.get().resource : undefined); + if (!next) { + return; + } + this._knownSession = to; + this._knownSessionRemoved = false; + if (isEqual(next, current)) { + // Its chat stays, such as in a session replaced under the same ID, whose change that follows passes it by as + // the change of the session it knows already + sessionsChanged.trigger(undefined); + } else { + this.chat.set(next, undefined); + heldChat.hold(next, this._boundCheck()); + } + })); + + // Of every session, also one outside a listing scope, such as of another folder, which its host can show + this._register(this.sessionsManagementService.onDidChangeSession(changes => { + const known = this._knownSession; + if (known && changes.some(({ session, kind }) => kind === 'removed' && isEqual(session.resource, known.resource))) { + this._knownSessionRemoved = true; + } + if (!known || changes.some(({ session, kind }) => kind !== 'changed' || (session !== known && session.sessionId === known.sessionId))) { + sessionsChanged.trigger(undefined); + } + })); + this._register(autorun(reader => { + sessionsChanged.read(reader); + this._update(reader); + })); + } + + /** Closes the chat where it shows, from its editor's pane, such as by its close action. `resource` is the chat's own. */ + protected abstract closeShown(resource: URI): void; + + /** Called as the chat shows in another session than before, such as once it is first known. */ + protected onDidShowSession(_shown: ISessionChatEditorShown): void { } + + /** Called as it shows `composer`, with what it disposes once the composer goes. */ + protected onDidSetComposer(_composer: ChatWindowComposerModel, _store: DisposableStore): void { } + + private _setComposer(composer: ChatWindowComposerModel): void { + const store = new DisposableStore(); + store.add(composer); + // Its tab shows while it is a composer, also alone in its group, so it can be closed there: until its session's chat + // shows, it has no title of its own, as its session header hides. + this.input.setRendersTitle(false); + store.add(toDisposable(() => this.input.setRendersTitle(true))); + store.add(composer.onDidStart(session => { + const main = session.mainChat.get().resource; + transaction(tx => { + this._composer.set(undefined, tx); + this.chat.set(main, tx); + }); + this._composerStore.clear(); + })); + this.onDidSetComposer(composer, store); + this._composerStore.value = store; + this._composer.set(composer, undefined); + } + + private _end(): void { + if (!this._ended) { + this._ended = true; + this._onDidEnd.fire(); + } + } + + private _update(reader: IReader): void { + if (this._ended || this._composer.read(reader)) { + return; + } + const chatResource = this.chat.read(reader); + // The chats of the session it was in, as these change without the sessions changing, such as as one is deleted + // or replaced; the lookup below is not observable. + this._knownSession?.chats.read(reader); + this._knownSession?.loading.read(reader); + const owner = this.sessionsManagementService.getSessionForChatResource(chatResource); + if (owner) { + if (this._knownSession !== owner.session) { + owner.session.chats.read(reader); + owner.session.loading.read(reader); + } + this._knownSession = owner.session; + this._knownSessionRemoved = false; + if (isChatWindowChatGone(owner.session, chatResource, reader)) { + this._end(); + return; + } + const shown = this._shown.get(); + if (shown?.session !== owner.session || shown.chat !== owner.chat) { + const sessionChanged = shown?.session.sessionId !== owner.session.sessionId; + const next = { session: owner.session, chat: owner.chat }; + this._shown.set(next, undefined); + if (sessionChanged) { + this.onDidShowSession(next); + } + } + return; + } + if (this._knownSessionRemoved && !(this._knownSession && this.sessionsManagementService.getSession(this._knownSession.resource))) { + // Its session is gone, such as deleted: its chats with it, also while the session's last state still lists them + this._end(); + return; + } + if (this._knownSession) { + // A provider registered again replaces the sessions it had: the chat shows once the session that replaces its + // session lists it, such as a chat that its session's chats publish later + const replacement = this.sessionsManagementService.getSession(this._knownSession.resource); + if (replacement && replacement !== this._knownSession) { + // Its chats can list the chat later than its loading says, so only the session being archived ends the chat + // meanwhile + if (replacement.isArchived.read(reader)) { + this._end(); + } else { + replacement.chats.read(reader); + } + return; + } + } + // Gone once the session it was in has loaded and no longer lists it, such as once it was deleted + if (this._knownSession && isChatWindowChatGone(this._knownSession, chatResource, reader)) { + this._end(); + } + } + + /** + * What its editor's pane shows of `shown`: its one chat, as a detached pane shows, apart from the session's slot. Closing + * the pane closes the chat ({@link closeShown}) while it still shows that chat of that session: a content kept past the + * chat moving or its session being replaced, its chat ending, or its host letting go of it closes nothing. + */ + private _contentOf(shown: ISessionChatEditorShown, isShown: () => boolean): ISessionPaneContent { + const chats = constObservable([shown.chat]); + return { + session: shown.session, + chat: constObservable(shown.chat), + state: { + sticky: constObservable(false), + tabs: { openChats: chats, closedChats: constObservable([]), lastClosedChat: undefined, visibleChatTabs: chats, shouldShowChatTabs: constObservable(true) }, + isDetached: true, + }, + close: () => { + if (this._disposed || this._ended || !isShown()) { + return; + } + // The chat's own resource while the composer shows its session, which its host knows the chat by + this.closeShown(this._composer.get() ? this.chat.get() : shown.chat.resource); + }, + }; + } + + attach(view: ChatEditorContent): IDisposable { + this._attachedViews.push(view); + this._view.set(view, undefined); + return toDisposable(() => { + const index = this._attachedViews.indexOf(view); + if (index >= 0) { + this._attachedViews.splice(index, 1); + } + this._view.set(this._attachedViews.at(-1), undefined); + }); + } + + /** Whether the chat view of its editor has bound to its model: it loaded, or showed that it was loading and is done. */ + private _boundCheck(): () => boolean { + let loading = false; + return () => { + const view = this._view.get()?.primaryChatView.get(); + if (!view) { + return false; + } + if (view.isLoadingTranscript.get()) { + loading = true; + return false; + } + return loading; + }; + } + + override dispose(): void { + // What it showed acts on it no more, such as a content its editor kept, once its host let go of it + this._disposed = true; + this._onWillDispose.fire(); + super.dispose(); + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatOpening.ts b/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatOpening.ts new file mode 100644 index 000000000000..cb83931eeb3c --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatEditor/sessionChatOpening.ts @@ -0,0 +1,90 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IntervalTimer, TimeoutTimer } from '../../../../../base/common/async.js'; +import { Disposable, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { IObservable, IReader } from '../../../../../base/common/observable.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IChat } from '../../../../services/sessions/common/session.js'; + +/** How long a chat model stays held for its view to bind to it, when the view never reports having done so. */ +export const CHAT_MODEL_HOLD_TIMEOUT = 10_000; + +/** + * Holds the loaded model of a chat while it moves between views, such as from the main window's grid to a chat window: + * the model is released when its last view lets go, so without it the view that takes over loads the history again. + * The hold only bridges the move: it is released as soon as the new view has bound to the model, so that switching chats + * afterwards does not keep a large model alive, and in any case after {@link CHAT_MODEL_HOLD_TIMEOUT}, or when disposed. + */ +export class ChatModelHold extends Disposable { + + private readonly _hold = this._register(new MutableDisposable()); + private readonly _poll = this._register(new IntervalTimer()); + /** The time the hold ends at, the view bound or not: a deadline, not a count of polls, which a window in the background makes fewer. */ + private readonly _expiry = this._register(new TimeoutTimer()); + + constructor( + private readonly _acquire: (resource: URI) => IDisposable | undefined, + private readonly _timeout = CHAT_MODEL_HOLD_TIMEOUT, + private readonly _pollInterval = 100, + ) { + super(); + } + + /** Holds the model of `resource` if it is loaded, instead of what is held; nothing when `resource` is undefined. `isBound` tells when the new view has bound. */ + hold(resource: URI | undefined, isBound: () => boolean): void { + this._poll.cancel(); + this._hold.value = resource ? this._acquire(resource) : undefined; + if (!this._hold.value) { + return; + } + this._poll.cancelAndSet(() => { + if (isBound()) { + this.release(); + } + }, this._pollInterval); + this._expiry.cancelAndSet(() => this.release(), this._timeout); + } + + release(): void { + this._poll.cancel(); + this._expiry.cancel(); + this._hold.clear(); + } + + get isHolding(): boolean { + return !!this._hold.value; + } +} + +/** The session of a chat window, as far as what its chat needs of it. */ +export interface IChatWindowChatSession { + readonly title: IObservable; + readonly loading: IObservable; + readonly chats: IObservable; + readonly mainChat: IObservable; +} + +/** The title of a chat window: the title of its chat, or of its session. */ +export function chatWindowTitle(session: IChatWindowChatSession, chatResource: URI | undefined, reader: IReader): string { + const chat = chatResource && session.chats.read(reader).find(candidate => isEqual(candidate.resource, chatResource)); + return chat?.title.read(reader) || session.title.read(reader); +} + +/** + * Whether the chat a window shows was deleted, or archived: the window closes with it. The chat resolves as in + * `getSessionForChatResource`, so a main chat the session does not list yet is still found. A session that still + * loads has not listed its chats yet, so a chat missing from it is not gone. Shared by the window and the links + * that open chats in it, so that a link never opens a chat the window would close. + */ +export function isChatWindowChatGone(session: Pick, chatResource: URI, reader: IReader | undefined): boolean { + let chat = session.chats.read(reader).find(candidate => isEqual(candidate.resource, chatResource)); + if (!chat) { + const mainChat = session.mainChat.read(reader); + chat = isEqual(mainChat.resource, chatResource) ? mainChat : undefined; + } + return chat ? chat.isArchived.read(reader) : !session.loading.read(reader); +} diff --git a/src/vs/workbench/contrib/sessions/browser/chatViewFactory.ts b/src/vs/workbench/contrib/sessions/browser/chatViewFactory.ts index c5bb2a672859..5c1feaa528ef 100644 --- a/src/vs/workbench/contrib/sessions/browser/chatViewFactory.ts +++ b/src/vs/workbench/contrib/sessions/browser/chatViewFactory.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { createDecorator, IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IDisposable } from '../../../../base/common/lifecycle.js'; import { AbstractChatView, IChatViewOptions } from './parts/chatView.js'; export const IChatViewFactory = createDecorator('chatViewFactory'); @@ -21,6 +22,9 @@ export interface IChatViewFactory { /** Entry-owned metrics for chat inputs composed outside a chat view, such as automation prompts. */ readonly inputEditorOptions: IChatViewOptions['inputEditorOptions']; + /** Paints the optional background behind a session grid. The grid owns the returned presentation. */ + createChatBackground?(container: HTMLElement, instantiationService: IInstantiationService): IDisposable; + /** * Creates a "new chat" view that lets the user pick a workspace and * start a new chat. This is the view the grid is seeded with on startup. `instantiationService` is the scope of the diff --git a/src/vs/workbench/contrib/sessions/browser/chatWindowEditorTarget.ts b/src/vs/workbench/contrib/sessions/browser/chatWindowEditorTarget.ts new file mode 100644 index 000000000000..0c394f23a6bc --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/chatWindowEditorTarget.ts @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IChatWindow, IChatWindowService } from '../../chatWindow/browser/chatWindow.js'; +import { ISessionsHostLayoutService } from '../../../services/sessions/browser/sessionsHostLayoutService.js'; +import { getWindowHost, ISessionHost, SessionHostKind } from '../../../services/sessions/browser/sessionHost.js'; + +/** Where the editors of a chat are shown: the main window, or the chat window the chat is in. */ +export type EditorTarget = IChatWindow | 'main'; + +/** + * The window that shows the editors of the chat in `host`. Returns `undefined` for a host in a chat window that is not + * registered (being created or torn down): nothing may fall back to the main window then. + */ +export function getEditorTarget(chatWindowService: IChatWindowService, host: ISessionHost | undefined): EditorTarget | undefined { + const windowHost = host && getWindowHost(host); + if (windowHost?.kind !== SessionHostKind.ChatWindow) { + return 'main'; + } + const windowId = windowHost.windowId.get(); + return windowId === undefined ? undefined : chatWindowService.getWindow(windowId); +} + +/** Reveals the editor area of `target`. */ +export function revealEditorTarget(layoutService: ISessionsHostLayoutService, target: EditorTarget): void { + if (target === 'main') { + layoutService.revealEditorPartExplicitly(); + } else { + target.showEditor(); + } +} + +/** The group an editor opens in: the main part's active group of a chat window, or the preferred group of the main window. */ +export function getEditorTargetGroup(target: EditorTarget, existingGroupId?: number): number | undefined { + if (target === 'main') { + return existingGroupId; + } + return existingGroupId !== undefined && target.mainPart.getGroup(existingGroupId) ? existingGroupId : target.mainPart.activeGroup.id; +} diff --git a/src/vs/workbench/contrib/sessions/browser/clientArtifactRuntime.ts b/src/vs/workbench/contrib/sessions/browser/clientArtifactRuntime.ts index f5e316ee9446..d054f60989b8 100644 --- a/src/vs/workbench/contrib/sessions/browser/clientArtifactRuntime.ts +++ b/src/vs/workbench/contrib/sessions/browser/clientArtifactRuntime.ts @@ -4,8 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from '../../../../base/common/event.js'; +import { structuralEquals } from '../../../../base/common/equals.js'; import { DisposableStore } from '../../../../base/common/lifecycle.js'; -import { constObservable, derived, IObservable, observableFromEvent } from '../../../../base/common/observable.js'; +import { constObservable, derived, IObservable, observableFromEvent, observableFromEventOpts } from '../../../../base/common/observable.js'; import { URI } from '../../../../base/common/uri.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { localize } from '../../../../nls.js'; @@ -121,7 +122,8 @@ export function createClientArtifactRuntime( acquireSession: async session => { await activateIntegrations?.(); const reference = connection.getSubscription(StateComponents.Session, URI.parse(session), 'artifactIntegrations'); - const value = observableFromEvent(reference, Event.any(reference.object.onDidChange, reference.object.onDidError ?? Event.None), (): ArtifactSessionState => { + // Session state changes far more often than its artifacts; every artifact model refreshes on each new value. + const value = observableFromEventOpts({ owner: reference, equalsFn: structuralEquals }, Event.any(reference.object.onDidChange, reference.object.onDidError ?? Event.None), (): ArtifactSessionState => { const error = reference.object.value instanceof Error ? reference.object.value : undefined; const state = reference.object.verifiedValue; return { diff --git a/src/vs/workbench/contrib/sessions/browser/customizationsNavigationState.ts b/src/vs/workbench/contrib/sessions/browser/customizationsNavigationState.ts index 7f25269ad6a6..2b2cd7d1e035 100644 --- a/src/vs/workbench/contrib/sessions/browser/customizationsNavigationState.ts +++ b/src/vs/workbench/contrib/sessions/browser/customizationsNavigationState.ts @@ -3,23 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { cancelOnDispose, CancellationToken } from '../../../../base/common/cancellation.js'; -import { isCancellationError } from '../../../../base/common/errors.js'; -import { Event } from '../../../../base/common/event.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; -import { autorun, derived, IObservable, observableSignalFromEvent, observableValue } from '../../../../base/common/observable.js'; -import { URI } from '../../../../base/common/uri.js'; +import { derived, IObservable } from '../../../../base/common/observable.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { ILogService } from '../../../../platform/log/common/log.js'; -import { IStorageService, StorageScope } from '../../../../platform/storage/common/storage.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; import { IAICustomizationItemsModel } from '../../chat/browser/aiCustomization/aiCustomizationItemsModel.js'; -import { getCustomizationMigrationCategory, homepageMigrationCategories } from '../../chat/browser/aiCustomization/customizationMigrationCategories.js'; -import { CUSTOMIZATION_MIGRATION_IGNORED_GROUPS_STORAGE_KEY, getIgnoredCustomizationMigrationGroups } from '../../chat/browser/aiCustomization/customizationMigrationIgnoredGroups.js'; +import { CustomizationMigrationState } from '../../chat/browser/aiCustomization/customizationMigrationState.js'; import { IAgentHostToolSetEnablementService } from '../../chat/browser/agentSessions/agentHost/agentHostToolSetEnablementService.js'; import { IAICustomizationWorkspaceService } from '../../chat/common/aiCustomizationWorkspaceService.js'; import { ICustomizationHarnessService } from '../../chat/common/customizationHarnessService.js'; -import { getChatSessionType } from '../../chat/common/model/chatUri.js'; -import { ICustomizationMigrationIgnoredGroup, ICustomizationMigrationService } from '../../chat/common/promptSyntax/service/customizationMigrationService.js'; +import { ICustomizationMigrationService } from '../../chat/common/promptSyntax/service/customizationMigrationService.js'; import { ILanguageModelToolsService } from '../../chat/common/tools/languageModelToolsService.js'; import { IFocusedSessionHostService } from '../../../services/sessions/browser/sessionHost.js'; import { IAICustomizationMcpServerCountService } from './customizationMcpServerCount.js'; @@ -30,8 +24,7 @@ export class CustomizationsNavigationState extends Disposable { readonly totalCount: IObservable; /** Whether the Customizations entry shows a badge for installed extensions that can be enabled in the Agents window. */ readonly extensionSuggestionsAvailable: IObservable; - private readonly migrationAvailableValue = observableValue(this, false); - readonly migrationAvailable: IObservable = this.migrationAvailableValue; + readonly migrationAvailable: IObservable; constructor( enabled: IObservable, @@ -45,7 +38,7 @@ export class CustomizationsNavigationState extends Disposable { @IConfigurationService configurationService: IConfigurationService, @IAICustomizationWorkspaceService workspaceService: IAICustomizationWorkspaceService, @IStorageService storageService: IStorageService, - @ILogService private readonly logService: ILogService, + @ILogService logService: ILogService, @IAgentsWindowExtensionSuggestionsService extensionSuggestionsService: IAgentsWindowExtensionSuggestionsService, ) { super(); @@ -65,59 +58,14 @@ export class CustomizationsNavigationState extends Disposable { }); this.extensionSuggestionsAvailable = derived(this, reader => enabled.read(reader) && extensionSuggestionsService.showBadge.read(reader)); - const migrationCategories = homepageMigrationCategories.map(getCustomizationMigrationCategory); - const configurationChanged = observableSignalFromEvent(this, Event.filter( - configurationService.onDidChangeConfiguration, - event => migrationCategories.some(category => event.affectsConfiguration(category.enablementSetting)), - )); - const customizationsChanged = observableSignalFromEvent(this, migrationService.onDidChangeCustomizations); - const ignoredGroupsChanged = observableSignalFromEvent(this, Event.filter( - storageService.onDidChangeValue(StorageScope.PROFILE, undefined, this._store), - event => event.key === CUSTOMIZATION_MIGRATION_IGNORED_GROUPS_STORAGE_KEY, - )); - this._register(autorun(reader => { + const context = derived(this, reader => { if (!enabled.read(reader)) { - this.migrationAvailableValue.set(false, undefined); - return; + return undefined; } - - configurationChanged.read(reader); - customizationsChanged.read(reader); - ignoredGroupsChanged.read(reader); harnessService.availableHarnesses.read(reader); const session = focusedSessionHostService.focusedHost.read(reader).session.read(reader); - if (!session) { - this.migrationAvailableValue.set(false, undefined); - return; - } - - const ignoredGroups = getIgnoredCustomizationMigrationGroups( - storageService, - getChatSessionType(session.resource), - workspaceService.activeProjectRoot.read(reader), - ); - void this.refreshMigrationAvailability(session.resource, migrationService, ignoredGroups, cancelOnDispose(reader.store)); - })); - } - - private async refreshMigrationAvailability( - sessionResource: URI, - migrationService: ICustomizationMigrationService, - ignoredGroups: readonly ICustomizationMigrationIgnoredGroup[], - token: CancellationToken, - ): Promise { - try { - const hint = await migrationService.computeMigrationHint(sessionResource, token, ignoredGroups); - if (!token.isCancellationRequested) { - this.migrationAvailableValue.set(hint !== undefined, undefined); - } - } catch (error) { - if (!isCancellationError(error)) { - this.logService.error('Failed to check customization migrations for the Sessions navigation', error); - } - if (!token.isCancellationRequested) { - this.migrationAvailableValue.set(false, undefined); - } - } + return session ? { sessionResource: session.resource, projectRoot: workspaceService.activeProjectRoot.read(reader) } : undefined; + }); + this.migrationAvailable = this._register(new CustomizationMigrationState(context, migrationService, configurationService, storageService, logService)).available; } } diff --git a/src/vs/workbench/contrib/sessions/browser/dnd.ts b/src/vs/workbench/contrib/sessions/browser/dnd.ts index af91891036a9..5dfc778d2f25 100644 --- a/src/vs/workbench/contrib/sessions/browser/dnd.ts +++ b/src/vs/workbench/contrib/sessions/browser/dnd.ts @@ -7,10 +7,10 @@ import { onUnexpectedError } from '../../../../base/common/errors.js'; import { IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; import { URI } from '../../../../base/common/uri.js'; import { stringHash } from '../../../../base/common/hash.js'; -import { CodeDataTransfers, DraggedChatReferenceIdentifier, fillInChatReferenceDragData, LocalSelectionTransfer } from '../../../../platform/dnd/browser/dnd.js'; -import { isHTMLElement } from '../../../../base/browser/dom.js'; -import { getInputDropTargetClipPath, isInputDropTarget } from '../../../browser/dnd.js'; -import { ISession } from '../../../services/sessions/common/session.js'; +import { fillInChatReferenceDragData, LocalSelectionTransfer } from '../../../../platform/dnd/browser/dnd.js'; +import { IChat, ISession } from '../../../services/sessions/common/session.js'; +import { isAgentHostProvider } from '../common/agentHostSessionsProvider.js'; +import { ISessionsProvidersService } from './sessionsProvidersService.js'; /** * Code data transfer mime types specific to the Agents window. @@ -24,20 +24,6 @@ export const SessionsDataTransfers = { DETACHED_CHAT: 'application/vnd.code.session.chat.detached', }; -/** Attachment inputs take precedence over grid placement for chat references. */ -export function isChatReferenceInputDrop(event: DragEvent): boolean { - return !!event.dataTransfer?.types.includes(CodeDataTransfers.CHAT_REFERENCE) - && isHTMLElement(event.target) && isInputDropTarget(event.target, event); -} - -/** Leave composer inputs outside the placement overlay's pointer hit region. */ -export function getChatReferenceDropClipPath(container: HTMLElement, event: DragEvent): string { - if (!event.dataTransfer?.types.includes(CodeDataTransfers.CHAT_REFERENCE)) { - return ''; - } - return getInputDropTargetClipPath(container); -} - /** Keep a small drag-free buffer beside the pane's resize boundaries. */ export function isSessionDragFromPaneEdge(element: HTMLElement, event: MouseEvent): boolean { const pane = element.closest('.chat-group-view, .session-view'); @@ -150,25 +136,16 @@ export function getSessionChatDragData(e: DragEvent): IDraggedSessionChat | unde } /** - * Shared local transfer for an in-process chat-reference drag. Unlike the - * `dataTransfer` mime payload it is readable during `dragover`, so the drop - * target can gate the overlay (e.g. suppress it for a self-reference) before the - * drop lands. - */ -const chatReferenceTransfer = LocalSelectionTransfer.getInstance(); - -/** - * Attach a chat-reference payload to a drag started from a chat tab in the - * Agents window, so it can be dropped into an agent-host chat input to insert an - * inline `#chat:` reference. The payload carries both the opaque + * Attach a chat-reference payload to a drag that stands for a chat in the + * Agents window, such as of its tab, so it can be dropped into an agent-host + * chat input to insert an inline `#chat:<title>` reference. The payload carries both the opaque * {@link chatResource backend chat URI} — forwarded verbatim into the reference * entry — and the {@link clientResource client chat resource} used only for * identity comparison, plus the display title. The payload is transient (never * persisted), so carrying both resources is fine. * - * Populates both the `dataTransfer` mime payload (read on drop) and an in-process - * {@link LocalSelectionTransfer} (readable during `dragover`). Callers MUST pair - * this with {@link clearChatReferenceDragData} on `dragend`. + * The payload is also readable during `dragover`, see {@link fillInChatReferenceDragData}. + * Callers MUST pair this with `clearChatReferenceDragData` on `dragend`. * * @param e The in-progress drag event to fill. * @param chatResource The referenced chat's opaque backend chat URI (the value @@ -180,19 +157,21 @@ const chatReferenceTransfer = LocalSelectionTransfer.getInstance<DraggedChatRefe */ export function fillChatReferenceDragData(e: DragEvent, chatResource: URI, clientResource: URI, title: string): void { const collapsedTitle = title.replace(/\s+/g, ' ').trim(); - const chatResourceString = chatResource.toString(); - const clientResourceString = clientResource.toString(); - fillInChatReferenceDragData({ chatResource: chatResourceString, clientResource: clientResourceString, title: collapsedTitle }, e); - chatReferenceTransfer.setData([new DraggedChatReferenceIdentifier(chatResourceString, clientResourceString, collapsedTitle)], DraggedChatReferenceIdentifier.prototype); + fillInChatReferenceDragData({ chatResource: chatResource.toString(), clientResource: clientResource.toString(), title: collapsedTitle }, e); } /** - * Clears the in-process chat-reference local transfer set by - * {@link fillChatReferenceDragData}. Call on `dragend` so a stale reference does - * not leak into a later, unrelated drag. + * Attach a reference to `chat` of `session` to a drag that stands for the chat, such as of its tab or of its session's + * row in the sessions list, see {@link fillChatReferenceDragData}. The reference needs the opaque backend chat URI, which + * only the owning agent-host provider knows: where it is unavailable (not agent-host backed, or state not yet hydrated), + * the drag simply carries no reference. */ -export function clearChatReferenceDragData(): void { - chatReferenceTransfer.clearData(DraggedChatReferenceIdentifier.prototype); +export function fillSessionChatReferenceDragData(e: DragEvent, session: ISession, chat: IChat, sessionsProvidersService: ISessionsProvidersService): void { + const provider = sessionsProvidersService.getProvider(session.providerId, session.sessionId); + const backendChatResource = provider && isAgentHostProvider(provider) ? provider.getBackendChatResource(chat.resource) : undefined; + if (backendChatResource) { + fillChatReferenceDragData(e, backendChatResource, chat.resource, chat.title.get()); + } } /** diff --git a/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowNullServices.ts b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowNullServices.ts new file mode 100644 index 000000000000..eae6d7351c21 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowNullServices.ts @@ -0,0 +1,187 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Event } from '../../../../../base/common/event.js'; +import { Disposable, IDisposable } from '../../../../../base/common/lifecycle.js'; +import { constObservable, IObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { IAutomationDescriptor, IAutomationRun } from '../../../chat/common/automations/automation.js'; +import { AutomationCatalogueState, IAutomationProviderDescriptor, IAutomationRunRequestResult, IAutomationService, IGuardedAutomationUpdateResult } from '../../../chat/common/automations/automationService.js'; +import { ICustomViewDescriptor, ICustomViewOpenRequest, ICustomViewService } from '../customView.js'; +import { IPinnedCanvas, IPinnedCanvasService } from '../pinnedCanvases.js'; +import { IAgentFeedbackNavigationBearing, IAgentFeedbackService } from '../agentFeedback.js'; +import { IAgentFeedback } from '../agentFeedbackModel.js'; +import { IAquariumService, IMountedToggleHandle } from '../aquarium.js'; +import { ICodeReviewService, IPRReviewCommentTarget, IPRReviewState, PRReviewStateKind } from '../codeReviewService.js'; +import { ISession, ISessionFileChange } from '../../../../services/sessions/common/session.js'; + +function notAvailable(): Promise<never> { + return Promise.reject(new Error('Automations are not available in this window')); +} + +/** + * The custom views of an editor window: it shows none, so the sessions list offers none of the + * entries that open one, such as Automations. + */ +export class EditorWindowCustomViewService implements ICustomViewService { + + declare readonly _serviceBrand: undefined; + + readonly activeCustomView: IObservable<ICustomViewDescriptor | undefined> = constObservable(undefined); + readonly activeCustomViewOpen: IObservable<ICustomViewOpenRequest | undefined> = constObservable(undefined); + + registerCustomView(): IDisposable { + return Disposable.None; + } + + showCustomView(): void { } + + hideCustomView(): void { } +} + +/** The automations of an editor window: it has none, so the sessions list shows no Automations entry. */ +export class EditorWindowAutomationService implements IAutomationService { + + declare readonly _serviceBrand: undefined; + + readonly unavailableProviders: IObservable<readonly IAutomationProviderDescriptor[]> = constObservable([]); + readonly availableProviders: IObservable<readonly IAutomationProviderDescriptor[]> = constObservable([]); + readonly catalogueState: IObservable<AutomationCatalogueState> = constObservable('unavailable'); + readonly automations: IObservable<readonly IAutomationDescriptor[]> = constObservable([]); + readonly runs: IObservable<readonly IAutomationRun[]> = constObservable([]); + + canCreateAutomation(): boolean { return false; } + getAutomation(): IAutomationDescriptor | undefined { return undefined; } + runsFor(): IObservable<readonly IAutomationRun[]> { return this.runs; } + createAutomation(): Promise<IAutomationDescriptor> { return notAvailable(); } + updateAutomation(): Promise<IAutomationDescriptor> { return notAvailable(); } + updateAutomationIfUnchanged(): Promise<IGuardedAutomationUpdateResult> { return notAvailable(); } + deleteAutomation(): Promise<void> { return notAvailable(); } + runAutomation(): Promise<IAutomationRunRequestResult> { return notAvailable(); } + getActiveRunFor(): IAutomationRun | undefined { return undefined; } + canRunAutomation(): boolean { return false; } + canUpdateAutomation(): boolean { return false; } + canDeleteAutomation(): boolean { return false; } +} + +/** The pinned canvases of an editor window: it has none, so the sessions list shows none. */ +export class EditorWindowPinnedCanvasService implements IPinnedCanvasService { + + declare readonly _serviceBrand: undefined; + + readonly enabled: IObservable<boolean> = constObservable(false); + readonly entries: IObservable<readonly IPinnedCanvas[]> = constObservable([]); + readonly selected: IObservable<IPinnedCanvas | undefined> = constObservable(undefined); + + getEntry(): IPinnedCanvas | undefined { return undefined; } + isPinned(): boolean { return false; } + isShown(): boolean { return false; } + getTrackedCanvas(): undefined { return undefined; } + pin(): boolean { return false; } + unpin(): void { } + async show(): Promise<void> { } + reconnect(): void { } + async goToChat(): Promise<void> { } + async closeCanvas(): Promise<void> { } +} + +/** + * The feedback on the changes of agent sessions in an editor window: the window offers none, as the + * Agents window's diff editors do, so the chats it shows have none to show or send. + */ +export class EditorWindowAgentFeedbackService implements IAgentFeedbackService { + + declare readonly _serviceBrand: undefined; + + readonly onDidChangeFeedback = Event.None; + readonly onDidChangeFeedbackVisibility = Event.None; + readonly onDidChangeNavigation = Event.None; + readonly onDidRevealSessionComment = Event.None; + readonly onDidChangeFeedbackScope = Event.None; + readonly onDidAddFeedback = Event.None; + readonly onDidConvertFeedback = Event.None; + readonly onDidAddReply = Event.None; + readonly onDidSubmitFeedback = Event.None; + + readonly activeFeedbackSessionResource: IObservable<URI> = constObservable(URI.from({ scheme: 'agent-feedback', path: '/none' })); + + addFeedback(): IAgentFeedback { + throw new Error('Agent feedback is not available in this window'); + } + acceptFeedback(): void { } + removeFeedback(): void { } + updateFeedback(): void { } + updateFeedbackSourcePullRequest(): void { } + setFeedbackResolved(): void { } + addReply(): void { } + getFeedback(): readonly IAgentFeedback[] { return []; } + getFeedbackObservable(): IObservable<readonly IAgentFeedback[]> { return constObservable([]); } + isAgentHostSession(): boolean { return false; } + showFeedbackInEditor(): void { } + hideFeedbackInEditor(): void { } + getVisibleResolvedFeedbackIds(): ReadonlySet<string> { return new Set(); } + hasLoadedFeedback(): boolean { return true; } + getSessionForFile(): ISession | undefined { return undefined; } + getChatChanges(): readonly ISessionFileChange[] { return []; } + getFeedbackSessionResource(): URI | undefined { return undefined; } + registerFeedbackResourceScope(): IDisposable { return Disposable.None; } + getMostRecentSessionForResource(): URI | undefined { return undefined; } + async revealFeedback(): Promise<void> { } + async revealSessionComment(): Promise<void> { } + getNextFeedback(): IAgentFeedback | undefined { return undefined; } + getNextNavigableItem(): undefined { return undefined; } + setNavigationAnchor(): void { } + getNavigationBearing(): IAgentFeedbackNavigationBearing { return { activeIdx: -1, totalCount: 0 }; } + clearFeedback(): void { } + markFeedbackSubmitted(): void { } + async submitFeedback(): Promise<boolean> { return false; } + async addFeedbackAndSubmit(): Promise<void> { } +} + +/** The aquarium of an editor window: it has none, as only the Agents window shows it. */ +export class EditorWindowAquariumService implements IAquariumService { + + declare readonly _serviceBrand: undefined; + + readonly actionVisible: IObservable<boolean> = constObservable(false); + + mountToggle(): IMountedToggleHandle { + return { setHostVisible: () => { }, dispose: () => { } }; + } + + toggleActionVisibility(): boolean { + return false; + } + + simulateStreak(): void { } +} + +/** The pull request reviews of agent sessions in an editor window: it loads none, as only the Agents window does. */ +export class EditorWindowCodeReviewService implements ICodeReviewService { + + declare readonly _serviceBrand: undefined; + + private readonly _none: IObservable<IPRReviewState> = constObservable({ kind: PRReviewStateKind.None }); + + getPRReviewState(): IObservable<IPRReviewState> { + return this._none; + } + + getPRReviewCommentPullRequests(): readonly [] { + return []; + } + + async getPRReviewCommentTargets(): Promise<readonly IPRReviewCommentTarget[]> { + return []; + } + + createPRReviewComment(): Promise<void> { + return Promise.reject(new Error('Pull request reviews are not available in this window')); + } + + async resolvePRReviewThread(): Promise<void> { } + markPRReviewCommentConverted(): void { } + dismissPRReviewComment(): void { } +} diff --git a/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessions.contribution.ts b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessions.contribution.ts new file mode 100644 index 000000000000..4fd1fe3fe445 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessions.contribution.ts @@ -0,0 +1,72 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { InstantiationType, registerSingleton } from '../../../../../platform/instantiation/common/extensions.js'; +import { ChatHostOpenerService, IChatHostOpenerService } from '../../../../services/sessions/browser/chatHostOpener.js'; +import { ISessionsHostLayoutService } from '../../../../services/sessions/browser/sessionsHostLayoutService.js'; +import { ISessionSectionOrderService, SessionSectionOrderService } from '../../../../services/sessions/browser/sessionSectionOrderService.js'; +import { ISessionChangesStatsCache, SessionChangesStatsCache } from '../../../../services/sessions/common/sessionChangesStatsCache.js'; +import { IAutomationService } from '../../../chat/common/automations/automationService.js'; +import { AgentHostFilterService } from '../agentHostFilterService.js'; +import { AgentsWindowExtensionSuggestionsService, IAgentsWindowExtensionSuggestionsService } from '../agentsWindowExtensionSuggestions.js'; +import { AICustomizationMcpServerCountService, IAICustomizationMcpServerCountService } from '../customizationMcpServerCount.js'; +import { ICustomViewService } from '../customView.js'; +import { DefaultSessionRepositoryPicker } from '../defaultSessionRepositoryPicker.js'; +import { DefaultSessionsListPresentation } from '../defaultSessionsListPresentation.js'; +import { IPullRequestIconCache, PullRequestIconCache } from '../github/pullRequestIconCache.js'; +import { IPinnedCanvasService } from '../pinnedCanvases.js'; +import { SessionComparisonService } from '../sessionComparisonService.js'; +import { ISessionGroupsService, SessionGroupsService } from '../sessionGroupsService.js'; +import { ISessionOpenTelemetryService, SessionOpenTelemetryService } from '../sessionOpenTelemetryService.js'; +import { ISessionRepositoryPicker } from '../sessionRepositoryPicker.js'; +import { ISessionsListPresentation } from '../sessionsListPresentation.js'; +import { SessionsManagementService } from '../sessionsManagementService.js'; +import { ISessionsProvidersService } from '../sessionsProvidersService.js'; +import { EditorWindowSessionsProvidersService } from './editorWindowSessionsProvidersService.js'; +import { ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService } from '../sessionsRecentWorkspacesService.js'; +import { IAgentHostFilterService } from '../../common/agentHostFilter.js'; +import { ISessionComparisonService } from '../../common/sessionComparison.js'; +import { ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { EditorWindowAgentFeedbackService, EditorWindowAquariumService, EditorWindowAutomationService, EditorWindowCodeReviewService, EditorWindowCustomViewService, EditorWindowPinnedCanvasService } from './editorWindowNullServices.js'; +import { ISessionsChatViewStateService, SessionsChatViewStateService } from '../chat/chatViewStateService.js'; +import { ISessionsChatBackgroundService, SessionsChatBackgroundService } from '../chatBackgroundService.js'; +import { INewSessionComposerService, NewSessionComposerService } from '../newSessionComposerService.js'; +import { IAgentFeedbackService } from '../agentFeedback.js'; +import { IAquariumService } from '../aquarium.js'; +import { ICodeReviewService } from '../codeReviewService.js'; +import { ISessionActivityBarActivityService, SessionActivityBarActivityService } from '../../common/sessionActivityBarActivityService.js'; +import { IDiffEditorOptionsService } from '../../../../services/editor/common/diffEditorOptionsService.js'; +import { DiffEditorOptionsService } from '../../../../services/editor/browser/diffEditorOptionsService.js'; +import { EditorWindowSessionsHostLayout } from './editorWindowSessionsHostLayout.js'; + +// The sessions services of an editor window, for the sessions features it can host. Every one is created only as it is +// first used, and nothing in the window uses them until such a feature does. +registerSingleton(ISessionsHostLayoutService, EditorWindowSessionsHostLayout, InstantiationType.Delayed); +registerSingleton(ISessionsProvidersService, EditorWindowSessionsProvidersService, InstantiationType.Delayed); +registerSingleton(ISessionsManagementService, SessionsManagementService, InstantiationType.Delayed); +registerSingleton(IChatHostOpenerService, ChatHostOpenerService, InstantiationType.Delayed); +registerSingleton(ISessionChangesStatsCache, SessionChangesStatsCache, InstantiationType.Delayed); +registerSingleton(ISessionOpenTelemetryService, SessionOpenTelemetryService, InstantiationType.Delayed); +registerSingleton(ISessionSectionOrderService, SessionSectionOrderService, InstantiationType.Delayed); +registerSingleton(ISessionGroupsService, SessionGroupsService, InstantiationType.Delayed); +registerSingleton(ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService, InstantiationType.Delayed); +registerSingleton(ISessionComparisonService, SessionComparisonService, InstantiationType.Delayed); +registerSingleton(IAgentHostFilterService, AgentHostFilterService, InstantiationType.Delayed); +registerSingleton(ISessionRepositoryPicker, DefaultSessionRepositoryPicker, InstantiationType.Delayed); +registerSingleton(ISessionsListPresentation, DefaultSessionsListPresentation, InstantiationType.Delayed); +registerSingleton(IPullRequestIconCache, PullRequestIconCache, InstantiationType.Delayed); +registerSingleton(IAICustomizationMcpServerCountService, AICustomizationMcpServerCountService, InstantiationType.Delayed); +registerSingleton(IAgentsWindowExtensionSuggestionsService, AgentsWindowExtensionSuggestionsService, InstantiationType.Delayed); +registerSingleton(ICustomViewService, EditorWindowCustomViewService, InstantiationType.Delayed); +registerSingleton(IAutomationService, EditorWindowAutomationService, InstantiationType.Delayed); +registerSingleton(IPinnedCanvasService, EditorWindowPinnedCanvasService, InstantiationType.Delayed); +registerSingleton(IAgentFeedbackService, EditorWindowAgentFeedbackService, InstantiationType.Delayed); +registerSingleton(IAquariumService, EditorWindowAquariumService, InstantiationType.Delayed); +registerSingleton(ICodeReviewService, EditorWindowCodeReviewService, InstantiationType.Delayed); +registerSingleton(ISessionsChatViewStateService, SessionsChatViewStateService, InstantiationType.Delayed); +registerSingleton(ISessionsChatBackgroundService, SessionsChatBackgroundService, InstantiationType.Delayed); +registerSingleton(INewSessionComposerService, NewSessionComposerService, InstantiationType.Delayed); +registerSingleton(ISessionActivityBarActivityService, SessionActivityBarActivityService, InstantiationType.Delayed); +registerSingleton(IDiffEditorOptionsService, DiffEditorOptionsService, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsHostLayout.ts b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsHostLayout.ts new file mode 100644 index 000000000000..3dc7f0cf7512 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsHostLayout.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { mainWindow } from '../../../../../base/browser/window.js'; +import { IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { IWorkbenchLayoutService, Parts } from '../../../../services/layout/browser/layoutService.js'; +import { AgentWorkbenchLayout, ISessionsHostLayoutService } from '../../../../services/sessions/browser/sessionsHostLayoutService.js'; + +/** + * The layout of an editor window for the sessions features it hosts: its editor area shows when they reveal it, and it + * never shows or hides by itself as editors open and close, so there is nothing to suppress. + */ +export class EditorWindowSessionsHostLayout implements ISessionsHostLayoutService { + + declare readonly _serviceBrand: undefined; + + readonly agentWorkbenchLayout = AgentWorkbenchLayout.Desktop; + + private suppressions = 0; + + constructor(@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService) { } + + revealEditorPartExplicitly(): void { + if (!this.layoutService.isVisible(Parts.EDITOR_PART, mainWindow)) { + this.layoutService.setPartHidden(false, Parts.EDITOR_PART); + } + } + + suppressEditorPartAutoVisibility(): IDisposable { + this.suppressions++; + return toDisposable(() => this.suppressions--); + } + + isEditorPartAutoVisibilitySuppressed(): boolean { + return this.suppressions > 0; + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsProvidersService.ts b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsProvidersService.ts new file mode 100644 index 000000000000..8b4332696aff --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/editorWindow/editorWindowSessionsProvidersService.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 { IDisposable } from '../../../../../base/common/lifecycle.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ILifecycleService } from '../../../../services/lifecycle/common/lifecycle.js'; +import { ISessionsListingScope, ISessionsProvider } from '../../common/sessionsProvider.js'; +import { SessionsProvidersService } from '../sessionsProvidersService.js'; +import { WorkspaceFolderRepositories } from '../workspaceFolderRepositories.js'; + +/** + * The sessions providers of an editor window: every provider and session backend that registers lists only the sessions + * of the window's folders and of their repositories (see {@link WorkspaceFolderRepositories}), whoever registers it, such + * as the local agent host's or Copilot Cloud's. Lookups still find every session. A provider without a listing scope + * lists every session. + */ +export class EditorWindowSessionsProvidersService extends SessionsProvidersService { + + private _listingScope: WorkspaceFolderRepositories | undefined; + + constructor( + @ILifecycleService lifecycleService: ILifecycleService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + ) { + super(lifecycleService); + } + + override registerProvider(provider: ISessionsProvider): IDisposable { + this._applyListingScope(provider); + return super.registerProvider(provider); + } + + override registerSessionBackend(ownerProviderId: string, backend: ISessionsProvider): IDisposable { + this._applyListingScope(backend); + return super.registerSessionBackend(ownerProviderId, backend); + } + + /** Scopes the listing of `provider` before it registers, so that no consumer sees it list another session. */ + private _applyListingScope(provider: ISessionsProvider): void { + provider.setListingScope?.(this._getListingScope()); + } + + private _getListingScope(): ISessionsListingScope { + this._listingScope ??= this._register(this._instantiationService.createInstance(WorkspaceFolderRepositories)); + return this._listingScope; + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/media/chatBackground.css b/src/vs/workbench/contrib/sessions/browser/media/chatBackground.css index 592d8f20465b..dbc080894df6 100644 --- a/src/vs/workbench/contrib/sessions/browser/media/chatBackground.css +++ b/src/vs/workbench/contrib/sessions/browser/media/chatBackground.css @@ -122,3 +122,19 @@ outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); outline-offset: calc(-1 * var(--vscode-strokeThickness)); } + +/* + * An editor part that shows chats over the chat surface, such as a chat part, paints the surface itself, whatever window + * it is in, as the Sessions part does: its content and editors show it through. A chat window's card paints it instead + * (`chatWindow.css`), with rules that take precedence. + */ +.monaco-workbench .part.editor.sessions-chat-surface { + /* Over the inline background of the part. */ + background-color: var(--vscode-agentsPanel-background) !important; +} + +.monaco-workbench .part.editor.sessions-chat-surface > .content, +.monaco-workbench .part.editor.sessions-chat-surface .editor-container { + /* Over the inline backgrounds of the part's content and of its editors. */ + background-color: transparent !important; +} diff --git a/src/vs/workbench/contrib/sessions/browser/media/customizationsToolbar.css b/src/vs/workbench/contrib/sessions/browser/media/customizationsToolbar.css index cacc1f5df75e..37b3f15bab8b 100644 --- a/src/vs/workbench/contrib/sessions/browser/media/customizationsToolbar.css +++ b/src/vs/workbench/contrib/sessions/browser/media/customizationsToolbar.css @@ -43,13 +43,15 @@ /* Customization header */ .ai-customization-toolbar .ai-customization-header { + position: relative; + isolation: isolate; display: flex; align-items: center; flex-shrink: 0; gap: var(--vscode-spacing-size40, 4px); -webkit-user-select: none; user-select: none; - padding: 6px 10px; + padding: var(--vscode-spacing-size60, 6px) var(--vscode-spacing-size100, 10px); font-size: var(--vscode-fontSize-label1, 12px); font-weight: var(--vscode-fontWeight-semiBold); line-height: normal; @@ -58,16 +60,41 @@ cursor: pointer; } -.ai-customization-toolbar .ai-customization-header:hover .ai-customization-header-label, +/* Inset the hover without shrinking the hit target or conflicting with the focus outline. */ +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered)::before { + content: ''; + position: absolute; + inset: 0 var(--vscode-spacing-size40, 4px); + z-index: -1; + pointer-events: none; + border-radius: var(--vscode-cornerRadius-small, 4px); + background-color: var(--vscode-list-hoverBackground); + outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder, transparent); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + .ai-customization-toolbar .ai-customization-header:focus-visible .ai-customization-header-label { color: var(--vscode-strongForeground); } +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered) .ai-customization-header-label { + color: var(--vscode-list-hoverForeground, var(--vscode-strongForeground)); +} + +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered) .ai-customization-header-total-count, +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered) .ai-customization-chevron { + color: var(--vscode-list-hoverForeground, var(--vscode-descriptionForeground)); +} + .ai-customization-toolbar .ai-customization-header:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; } +.ai-customization-toolbar .ai-customization-header:focus-visible::before { + outline: none; +} + .ai-customization-toolbar .ai-customization-header:focus:not(:focus-visible) { outline: none !important; } @@ -128,13 +155,17 @@ opacity: 0; } -.ai-customization-toolbar .ai-customization-header:hover .ai-customization-chevron, +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered) .ai-customization-chevron, .ai-customization-toolbar .ai-customization-header:focus-visible .ai-customization-chevron, .ai-customization-toolbar .ai-customization-header.collapsed .ai-customization-chevron { visibility: visible; opacity: 0.7; } +.ai-customization-toolbar .ai-customization-header:is(:hover, .hovered) .ai-customization-chevron { + opacity: 1; +} + .ai-customization-toolbar .ai-customization-chevron:hover { background-color: var(--vscode-toolbar-hoverBackground); } diff --git a/src/vs/workbench/contrib/sessions/browser/media/disclosure.css b/src/vs/workbench/contrib/sessions/browser/media/disclosure.css new file mode 100644 index 000000000000..96c6cbe6d9c1 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/media/disclosure.css @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* High contrast uses a dashed boundary for pointer hover. Keyboard-focused rows keep + * the solid boundary owned by the tree; pointer-focused rows retain the hover state. */ +.monaco-workbench:is(.hc-black, .hc-light) .sessions-disclosure:is(:hover, .hovered):not(:focus-visible, .focus-visible), +.monaco-workbench:is(.hc-black, .hc-light) .monaco-list-row.sessions-disclosure-row:is(:hover, .hovered) > .monaco-tl-row { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.monaco-workbench:is(.hc-black, .hc-light) :is(.sessions-list-control, .agent-sessions-navigation-container):not(.session-section-focus-from-pointer) .monaco-list:focus-within .monaco-list-row.sessions-disclosure-row.focused:is(:hover, .hovered) > .monaco-tl-row { + outline: none; +} diff --git a/src/vs/workbench/contrib/sessions/browser/media/scheduledChatTimePicker.css b/src/vs/workbench/contrib/sessions/browser/media/scheduledChatTimePicker.css new file mode 100644 index 000000000000..5a458132e821 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/media/scheduledChatTimePicker.css @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.scheduled-chat-time-picker { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size120); + padding: var(--vscode-spacing-size120); +} + +.scheduled-chat-time-fields, +.scheduled-chat-time-column { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size120); +} + +.scheduled-chat-time-field:not([hidden]) { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size40); + min-width: 0; +} + +.scheduled-chat-time-select .monaco-select-box { + width: 100%; + padding: var(--vscode-spacing-size40) var(--vscode-spacing-size240) var(--vscode-spacing-size40) var(--vscode-spacing-size80); +} + +.scheduled-chat-time-field input { + color-scheme: light; +} + +.vs-dark .scheduled-chat-time-field input, +.hc-black .scheduled-chat-time-field input { + color-scheme: dark; +} + +.scheduled-chat-calendar { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size40); +} + +.scheduled-chat-calendar-header { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); +} + +.scheduled-chat-calendar-header .monaco-button { + flex: none; + width: auto; + padding: var(--vscode-spacing-size20) var(--vscode-spacing-size40); +} + +.scheduled-chat-calendar-month { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + text-align: center; + font-weight: var(--vscode-fontWeight-semiBold); +} + +.scheduled-chat-calendar-row { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: var(--vscode-spacing-size20); +} + +.scheduled-chat-calendar-body { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size20); +} + +.scheduled-chat-calendar-weekday { + text-align: center; + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-label2); +} + +.scheduled-chat-calendar-day { + text-align: center; + padding: var(--vscode-spacing-size40) 0; + border-radius: var(--vscode-cornerRadius-small); +} + +.scheduled-chat-calendar-day[aria-disabled='false'] { + cursor: pointer; +} + +.scheduled-chat-calendar-day[aria-disabled='true'] { + color: var(--vscode-disabledForeground); +} + +.scheduled-chat-calendar-day.today { + font-weight: var(--vscode-fontWeight-semiBold); + text-decoration: underline; +} + +.scheduled-chat-calendar-day[aria-disabled='false'][aria-selected='false']:hover { + background-color: var(--vscode-list-hoverBackground); +} + +.scheduled-chat-calendar-day[aria-selected='true'] { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); +} + +.monaco-workbench:is(.hc-black, .hc-light) .scheduled-chat-calendar-day[aria-disabled='false'][aria-selected='false']:not(:focus-visible):hover { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); + outline-offset: -1px; +} + +.monaco-workbench:is(.hc-black, .hc-light) .scheduled-chat-calendar-day[aria-selected='true']:not(:focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: -1px; +} + +.scheduled-chat-time-summary { + font-weight: var(--vscode-fontWeight-semiBold); +} + +.scheduled-chat-time-hint { + color: var(--vscode-descriptionForeground); +} + +.scheduled-chat-time-actions { + display: flex; + gap: var(--vscode-spacing-size80); +} diff --git a/src/vs/workbench/contrib/sessions/browser/media/sessionsList.css b/src/vs/workbench/contrib/sessions/browser/media/sessionsList.css index 129c0778142e..7e1436d0f83f 100644 --- a/src/vs/workbench/contrib/sessions/browser/media/sessionsList.css +++ b/src/vs/workbench/contrib/sessions/browser/media/sessionsList.css @@ -127,7 +127,11 @@ /* The opaque sticky background hides the row tint, so paint it as an overlay. */ &:not(.selected):not(.focused):not(:hover, .hovered):has(.session-item.needs-input) { - background-image: linear-gradient(color-mix(in srgb, var(--vscode-list-warningForeground) 8%, transparent), color-mix(in srgb, var(--vscode-list-warningForeground) 8%, transparent)); + background-image: linear-gradient(color-mix(in srgb, var(--vscode-agentSessionNeedsInput-foreground) 8%, transparent), color-mix(in srgb, var(--vscode-agentSessionNeedsInput-foreground) 8%, transparent)); + + :is(.hc-black, .hc-light) & { + background-image: none; + } } } @@ -152,13 +156,16 @@ border-radius: var(--vscode-cornerRadius-small); > .monaco-tl-row { - border-radius: inherit; + border-radius: var(--vscode-cornerRadius-small); } } &.session-list-row-spacing .monaco-list-row:is(.session-list-inset-row, .session-list-show-more-row, .session-list-show-more-folders-row) { padding-bottom: var(--vscode-spacing-size20); background-clip: content-box; + /* Content-box clipping subtracts the bottom padding from the vertical corner radii. */ + border-bottom-left-radius: var(--vscode-cornerRadius-small) calc(var(--vscode-cornerRadius-small) + var(--vscode-spacing-size20)); + border-bottom-right-radius: var(--vscode-cornerRadius-small) calc(var(--vscode-cornerRadius-small) + var(--vscode-spacing-size20)); outline: 0 !important; } @@ -196,7 +203,26 @@ /* Suppressed while selected so the selection highlight is not overpainted. */ .monaco-list-row:not(.selected):not(.focused):not(:hover, .hovered):has(.session-item.needs-input), .monaco-list-row:not(.selected):not(.focused):not(:hover, .hovered) .session-chat-item.needs-input { - background-color: color-mix(in srgb, var(--vscode-list-warningForeground) 8%, transparent); + background-color: color-mix(in srgb, var(--vscode-agentSessionNeedsInput-foreground) 8%, transparent); + + :is(.hc-black, .hc-light) & { + background-color: transparent; + + .session-attention-indicator { + display: block; + } + } + } + + .session-attention-indicator { + display: none; + position: absolute; + top: var(--vscode-spacing-size40); + bottom: var(--vscode-spacing-size40); + left: 0; + width: var(--vscode-spacing-size20); + background-color: var(--vscode-agentSessionNeedsInput-foreground); + pointer-events: none; } .monaco-list-row .force-no-twistie { @@ -356,28 +382,12 @@ /* Session Item */ -.sessions-list-primary, -.sessions-list-inbox-footer { +.sessions-list-primary { height: 100%; min-height: 0; overflow: hidden; } -.sessions-list-inbox-resize { - position: absolute; - top: 0; - left: 0; - right: 0; - height: var(--vscode-spacing-size40); - pointer-events: none; - z-index: 1; - - &:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); - outline-offset: -1px; - } -} - .sessions-list-control.inbox-layout { &:not(.compact) .session-item:not(.quick-chat, .session-comparison-attempt) { padding-top: var(--vscode-spacing-size40); @@ -388,7 +398,7 @@ } } - .sessions-list-inbox-footer .session-section { + .session-section { font-weight: var(--vscode-fontWeight-regular); .session-section-count { @@ -427,6 +437,10 @@ border-radius: var(--vscode-cornerRadius-circle); background-color: var(--vscode-focusBorder); } + + > .session-attention-indicator { + left: var(--vscode-spacing-size40); + } } /* Quick-chat rows are compact single-line entries — no second (details) row. @@ -1001,6 +1015,29 @@ text-overflow: ellipsis; font-size: var(--vscode-fontSize-label1, 12px); } + + .session-approval-working-directory { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-label1); + + .codicon { + flex-shrink: 0; + font-size: var(--vscode-codiconFontSize-compact); + } + } + + /* Right-to-left so a long path is cut at its start, keeping the folders nearest the command. + `pre` rather than `nowrap` keeps repeated spaces, which can be all that tells two paths apart. */ + .session-approval-working-directory-path { + min-width: 0; + overflow: hidden; + white-space: pre; + text-overflow: ellipsis; + direction: rtl; + } } .session-approval-button { @@ -1014,6 +1051,11 @@ } } +/* The approval row's hover shows the working directory as inline code; keep its repeated spaces too. */ +.monaco-hover.session-approval-hover code { + white-space: pre-wrap; +} + /* * Hierarchy guides connect an expanded session to its nested chats. While the * pointer is anywhere over the Sessions pane, every hierarchy shows them, like @@ -1405,6 +1447,7 @@ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + color: var(--session-group-interaction-foreground, var(--session-group-foreground, inherit)); } .session-section-icon { @@ -1468,7 +1511,7 @@ } .session-section-toolbar .monaco-action-bar .action-label { - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .session-section-chevron { @@ -1536,7 +1579,28 @@ .sessions-list-control { .monaco-list-row:is(:hover, .hovered) .session-section .session-section-label, - .monaco-list-row.focused .session-section .session-section-label, + .monaco-list-row.focused .session-section .session-section-label { + color: var(--session-group-interaction-foreground, var(--session-group-hover-foreground, var(--vscode-strongForeground))); + } + + .monaco-list .monaco-list-row.focused .session-section-label { + --session-group-interaction-foreground: var(--session-group-inactive-focus-foreground); + } + + .monaco-list .monaco-list-row.selected .session-section-label { + --session-group-interaction-foreground: var(--session-group-inactive-selection-foreground); + } + + .monaco-list:focus .monaco-list-row.focused .session-section-label, + .monaco-list.sticky-scroll-focused .monaco-tree-sticky-row.focused .session-section-label { + --session-group-interaction-foreground: var(--session-group-focus-foreground); + } + + .monaco-list:focus .monaco-list-row.selected .session-section-label, + .monaco-list.sticky-scroll-focused .monaco-tree-sticky-row.selected .session-section-label { + --session-group-interaction-foreground: var(--session-group-selection-foreground); + } + .monaco-list-row:is(:hover, .hovered) .session-show-more-folders .session-show-more-label, .monaco-list-row.focused .session-show-more-folders .session-show-more-label { color: var(--vscode-strongForeground); diff --git a/src/vs/workbench/contrib/sessions/browser/media/sidebarActionButton.css b/src/vs/workbench/contrib/sessions/browser/media/sidebarActionButton.css index 78c712d807c7..0b65da9cbb65 100644 --- a/src/vs/workbench/contrib/sessions/browser/media/sidebarActionButton.css +++ b/src/vs/workbench/contrib/sessions/browser/media/sidebarActionButton.css @@ -31,7 +31,7 @@ text-align: left; justify-content: flex-start; text-decoration: none; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); cursor: pointer; gap: 6px; display: flex; diff --git a/src/vs/workbench/contrib/sessions/browser/menus.ts b/src/vs/workbench/contrib/sessions/browser/menus.ts index 84d2ca950659..c0ab75bb9f03 100644 --- a/src/vs/workbench/contrib/sessions/browser/menus.ts +++ b/src/vs/workbench/contrib/sessions/browser/menus.ts @@ -18,6 +18,8 @@ export function getNewSessionRepositoryConfigGroup(order: number, actionId: stri * Menu IDs for the Agent Sessions workbench layout. */ export const Menus = { + MobileSessionsDrawerHeader: new MenuId('SessionsMobileSessionsDrawerHeader'), + NewSessionPlace: new MenuId('SessionsNewSessionPlace'), BlockedSessionsHeader: new MenuId('SessionsBlockedSessionsHeader'), BlockedSessionsItem: new MenuId('SessionsBlockedSessionsItem'), SidebarSessionsHeader: new MenuId('SessionsSidebarSessionsHeader'), @@ -31,6 +33,7 @@ export const Menus = { SessionsViewHarness: new MenuId('SessionsViewHarness'), SessionsViewExternalFilter: new MenuId('SessionsViewExternalFilter'), SidebarCustomizations: new MenuId('SessionsSidebarCustomizations'), + SidebarCustomizationsEntryPoint: new MenuId('SessionsSidebarCustomizationsEntryPoint'), SidebarAgentHost: new MenuId('SessionsSidebarAgentHost'), AgentFeedbackEditorContent: new MenuId('AgentFeedbackEditorContent'), /** Context menu of a pinned canvas row in the sidebar. */ @@ -51,6 +54,7 @@ export const Menus = { NewSessionControl: new MenuId('NewSessions.SessionControlMenu'), NewSessionRepositoryConfig: new MenuId('NewSessions.RepositoryConfigMenu'), NewSessionWelcome: new MenuId('NewSessions.WelcomeMenu'), + NewSessionGlobalToolbar: new MenuId('NewSessions.GlobalToolbar'), NewSessionWelcomeContext: new MenuId('NewSessions.WelcomeContextMenu'), SessionWorkspaceManage: new MenuId('Sessions.SessionWorkspaceManage'), SessionBarToolbar: new MenuId('SessionsSessionBarToolbar'), diff --git a/src/vs/workbench/contrib/sessions/browser/mobile/mobilePickerSheet.ts b/src/vs/workbench/contrib/sessions/browser/mobile/mobilePickerSheet.ts index 37be6a40d392..ce23af04e558 100644 --- a/src/vs/workbench/contrib/sessions/browser/mobile/mobilePickerSheet.ts +++ b/src/vs/workbench/contrib/sessions/browser/mobile/mobilePickerSheet.ts @@ -56,9 +56,19 @@ export interface IMobilePickerSheetItem { readonly sectionTitle?: string; } +type MobilePickerSheetSelection = string | typeof MOBILE_PICKER_SHEET_CONFIRM | { readonly items: readonly IMobilePickerSheetItem[]; readonly focusItemId?: string } | void; + +/** Optional focus preferences when a provider refreshes the sheet's items. */ +export interface IMobilePickerSheetItemsChangeEvent { + readonly focusItemId?: string; + readonly focusFilter?: boolean; +} + export interface IMobilePickerSheetOptions { /** Dismisses the sheet when its owner or picker data becomes unavailable. */ readonly cancellationToken?: CancellationToken; + readonly initialFocusItemId?: string; + readonly itemProvider?: { readonly onDidChange: Event<IMobilePickerSheetItemsChangeEvent | void>; readonly getItems: () => readonly IMobilePickerSheetItem[] }; /** * Optional caption shown beneath the title (single-line, muted). Useful * for explaining what the picker controls (e.g. "Agents are pre-configured @@ -113,9 +123,10 @@ export interface IMobilePickerSheetOptions { * tapped row is treated as confirmed: the sheet resolves with that * row's id and closes immediately. * + * May await a write or confirmation and return replacement items reflecting the saved state. * Ignored when `stayOpenOnSelect` is false. */ - readonly onDidSelect?: (id: string) => string | typeof MOBILE_PICKER_SHEET_CONFIRM | void; + readonly onDidSelect?: (id: string) => MobilePickerSheetSelection | Promise<MobilePickerSheetSelection>; /** * Optional override for the dismiss button label (defaults to "Done"). @@ -123,6 +134,13 @@ export interface IMobilePickerSheetOptions { * header button is purely a dismiss affordance. */ readonly doneLabel?: string; + + /** + * Dismisses the sheet (resolving with `undefined`) when cancelled. + * Use this when the owner can go away while the sheet is open, e.g. + * a picker whose session is switched or closed underneath it. + */ + readonly dismissToken?: CancellationToken; } /** @@ -161,6 +179,10 @@ export interface IMobilePickerSheetSearchSource { readonly emptyMessage?: string; /** Notifies the sheet that the current query's results have changed. */ readonly onDidChangeItems?: Event<void>; + /** Search results replace the initial rows, including for an empty query. */ + readonly replaceStaticItems?: boolean; + /** Supplies a query setter for an owner that updates an already-open picker. */ + readonly onDidCreateFilter?: (setFilter: (query: string, focusItemId?: string) => void) => void; /** Loads the result rows for the given query. */ loadItems(query: string, token: CancellationToken): Promise<readonly IMobilePickerSheetItem[]>; /** @@ -292,6 +314,14 @@ export function showMobilePickerSheet( disposables.add(options.cancellationToken.onCancellationRequested(() => finish(undefined))); } + if (options?.dismissToken) { + if (options.dismissToken.isCancellationRequested) { + finish(undefined); + } else { + disposables.add(options.dismissToken.onCancellationRequested(() => finish(undefined))); + } + } + // -- Optional inline search input ------------------------------ // Sits between the title row and the scrollable list. Its value // drives `options.search.loadItems` (debounced + cancellable), @@ -345,13 +375,6 @@ export function showMobilePickerSheet( const list = DOM.append(sheet, $('div.mobile-picker-sheet-list')); list.setAttribute('role', 'list'); - // When `stayOpenOnSelect` is true, row taps call the caller's - // `onDidSelect` callback and leave the sheet open. The visual - // state (checkmark + aria) is updated immediately so the user - // sees which option is now active. Within each section, only - // one row can be checked at a time (radio-select semantics). - // When false (default), taps resolve the sheet promise and close. - // Registry of rendered rows keyed by section index, used to // toggle checkmarks within a section on tap. const rowsBySection = new Map<number, IMobilePickerSheetRowRef[]>(); @@ -359,13 +382,30 @@ export function showMobilePickerSheet( // Mutable reference so handleRowTap can trigger a search-query // update when onDidSelect returns a drill-down string. Populated // after the search section is created below. - let setSearchQuery: ((query: string) => void) | undefined; + let setSearchQuery: ((query: string, focusItemId?: string, focusFilter?: boolean, scrollTop?: number) => void) | undefined; + let selectionPending = false; + let itemsChangedWhileSelecting = false; + let pendingItemsChange: IMobilePickerSheetItemsChangeEvent | void; - const handleRowTap = options?.stayOpenOnSelect && options.onDidSelect - ? (id: string, _row: HTMLElement, sectionIndex: number) => { - // Update visual: uncheck all rows in the same section, - // then check the tapped row. Skipped for navigational - // rows (drill-down) — they don't carry a radio checkmark. + const applySelection = (result: MobilePickerSheetSelection, id: string, sectionIndex: number) => { + if (resolved) { + return; + } + if (result === MOBILE_PICKER_SHEET_CONFIRM) { + finish(id); + } else if (typeof result === 'string' && searchInput && setSearchQuery) { + searchInput.value = result; + setSearchQuery(result); + } else if (result && typeof result === 'object') { + itemsChangedWhileSelecting = false; + const scrollTop = list.scrollTop; + renderStaticItems(result.items); + list.scrollTop = scrollTop; + focusItem(result.focusItemId ?? id); + if (searchInput) { + setSearchQuery?.(searchInput.value); + } + } else { const sectionRows = rowsBySection.get(sectionIndex); const targetEntry = sectionRows?.find(entry => entry.id === id); if (sectionRows && !targetEntry?.navigates) { @@ -383,12 +423,36 @@ export function showMobilePickerSheet( } } } - const selectResult = options.onDidSelect!(id); - if (selectResult === MOBILE_PICKER_SHEET_CONFIRM) { - finish(id); - } else if (typeof selectResult === 'string' && searchInput && setSearchQuery) { - searchInput.value = selectResult; - setSearchQuery(selectResult); + } + }; + const handleRowTap = options?.stayOpenOnSelect && options.onDidSelect + ? (id: string, _row: HTMLElement, sectionIndex: number) => { + if (selectionPending || resolved) { + return; + } + const result = options.onDidSelect!(id); + if (result instanceof Promise) { + selectionPending = true; + list.setAttribute('aria-busy', 'true'); + const disabledRows = [...rowsBySection.values()].flat().map(entry => ({ row: entry.row, disabled: entry.row.disabled })); + for (const { row } of disabledRows) { + row.disabled = true; + } + void result.then(value => applySelection(value, id, sectionIndex)).catch(onUnexpectedError).finally(() => { + selectionPending = false; + list.removeAttribute('aria-busy'); + for (const { row, disabled } of disabledRows) { + row.disabled = disabled; + } + if (!resolved && itemsChangedWhileSelecting) { + refreshItems(pendingItemsChange); + } + if (!resolved && _row.isConnected) { + _row.focus(); + } + }); + } else { + applySelection(result, id, sectionIndex); } } : (id: string, _row: HTMLElement, _sectionIndex: number) => { finish(id); }; @@ -397,9 +461,53 @@ export function showMobilePickerSheet( // hide them while the user is browsing/searching (a non-empty // query), keeping recents from cluttering search results. const staticContainer = DOM.append(list, $('div.mobile-picker-sheet-static')); + const staticRowsStore = disposables.add(new DisposableStore()); const renderState: IRenderState = { firstRow: undefined, firstCheckedRow: undefined, sectionCount: 0 }; - for (const item of items) { - renderRow(staticContainer, item, renderState, handleRowTap, disposables, rowsBySection); + let searchSectionBase = 1; + const renderStaticItems = (nextItems: readonly IMobilePickerSheetItem[]) => { + staticRowsStore.clear(); + DOM.clearNode(staticContainer); + rowsBySection.clear(); + renderState.firstRow = undefined; + renderState.firstCheckedRow = undefined; + renderState.sectionCount = 0; + for (const item of nextItems) { + renderRow(staticContainer, item, renderState, handleRowTap, staticRowsStore, rowsBySection); + } + searchSectionBase = renderState.sectionCount + 1; + }; + const focusItem = (id: string | undefined) => { + const row = id ? [...rowsBySection.values()].flat().find(entry => entry.id === id && !entry.row.disabled)?.row : undefined; + (row ?? renderState.firstCheckedRow ?? renderState.firstRow)?.focus(); + }; + const refreshItems = (change: IMobilePickerSheetItemsChangeEvent | void) => { + itemsChangedWhileSelecting = false; + pendingItemsChange = undefined; + if (resolved || !options?.itemProvider) { + return; + } + const focusedId = change?.focusItemId ?? [...rowsBySection.values()].flat().find(entry => DOM.isActiveElement(entry.row))?.id; + const scrollTop = list.scrollTop; + renderStaticItems(options.itemProvider.getItems()); + if (searchInput) { + setSearchQuery?.(searchInput.value, focusedId, change?.focusFilter, scrollTop); + } else { + if (focusedId) { + focusItem(focusedId); + } + list.scrollTop = scrollTop; + } + }; + renderStaticItems(items); + if (options?.itemProvider) { + disposables.add(options.itemProvider.onDidChange(change => { + if (selectionPending) { + itemsChangedWhileSelecting = true; + pendingItemsChange = change; + } else { + refreshItems(change); + } + })); } // -- Dynamic search results ----------------------------------- @@ -412,7 +520,6 @@ export function showMobilePickerSheet( const resultsContainer = DOM.append(list, $('div.mobile-picker-sheet-search-results')); let currentQueryTokens: CancellationTokenSource | undefined; let debounceTimer: ReturnType<typeof setTimeout> | undefined; - const searchSectionBase = renderState.sectionCount + 1; const pruneSearchRows = () => { for (const key of [...rowsBySection.keys()]) { if (key >= searchSectionBase) { @@ -436,12 +543,15 @@ export function showMobilePickerSheet( }; disposables.add(toDisposable(cancelInflight)); - const renderResults = async (query: string): Promise<void> => { + const renderResults = async (query: string, focusItemId?: string, focusFilter?: boolean, scrollTop?: number): Promise<void> => { + if (resolved) { + return; + } cancelInflight(); // Recents (static items) are only relevant at the root. // Once the user types or drills into a path, hide them so // the list shows just the search results. - staticContainer.style.display = query ? 'none' : ''; + staticContainer.style.display = query || search.replaceStaticItems ? 'none' : ''; const tokens = new CancellationTokenSource(); currentQueryTokens = tokens; DOM.clearNode(resultsContainer); @@ -473,10 +583,21 @@ export function showMobilePickerSheet( if (results.length === 0) { const empty = DOM.append(resultsContainer, $('div.mobile-picker-sheet-search-empty')); empty.textContent = search.emptyMessage ?? localize('mobilePickerSheet.noResults', "No results"); - return; + } else { + for (const item of results) { + renderRow(resultsContainer, item, localState, handleRowTap, searchRowsStore, rowsBySection); + } + } + if (focusItemId) { + const rows = [...rowsBySection].filter(([section]) => section >= searchSectionBase).flatMap(([, rows]) => rows); + const row = rows.find(row => row.id === focusItemId && !row.row.disabled); + (row?.row ?? localState.firstCheckedRow ?? localState.firstRow)?.focus(); + } + if (scrollTop !== undefined) { + list.scrollTop = scrollTop; } - for (const item of results) { - renderRow(resultsContainer, item, localState, handleRowTap, searchRowsStore, rowsBySection); + if (focusFilter) { + searchInput!.focus(); } }; @@ -506,7 +627,15 @@ export function showMobilePickerSheet( // Expose a programmatic setter so handleRowTap can drive // drill-down navigation when onDidSelect returns a string. - setSearchQuery = (query: string) => renderResults(query); + setSearchQuery = (query, focusItemId, focusFilter, scrollTop) => { + void renderResults(query, focusItemId, focusFilter, scrollTop).catch(onUnexpectedError); + }; + search.onDidCreateFilter?.((query, focusItemId) => { + if (!resolved) { + searchInput!.value = query; + void renderResults(query, focusItemId); + } + }); } // Focus the search input if present, otherwise focus the first @@ -514,7 +643,7 @@ export function showMobilePickerSheet( if (searchInput) { searchInput.focus(); } else { - (renderState.firstCheckedRow ?? renderState.firstRow)?.focus(); + focusItem(options?.initialFocusItemId); } }); } diff --git a/src/vs/workbench/contrib/sessions/browser/newSessionInputPresentation.ts b/src/vs/workbench/contrib/sessions/browser/newSessionInputPresentation.ts new file mode 100644 index 000000000000..00ec3d24a1e3 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/newSessionInputPresentation.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { IHoverDelegate } from '../../../../base/browser/ui/hover/hoverDelegate.js'; +import type { Event } from '../../../../base/common/event.js'; +import type { IDisposable } from '../../../../base/common/lifecycle.js'; +import type { IObservable } from '../../../../base/common/observable.js'; +import type { IActionListItem } from '../../../../platform/actionWidget/browser/actionList.js'; +import type { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import type { ISession } from '../../../services/sessions/common/session.js'; +import type { NewSessionBanners } from '../common/newSessionBanners.js'; +import type { ISessionInputPickerVisibility } from '../common/sessionPickerVisibility.js'; + +/** The owning composer's state and interactions, without a dependency on an optional feature. */ +export interface INewSessionInputContext { + readonly session: IObservable<ISession | undefined>; + readonly pickerVisibility: ISessionInputPickerVisibility; + readonly visible: IObservable<boolean>; + readonly getInputValue: () => string; + readonly onDidChangeInput: Event<void>; + readonly focusInput: () => void; + readonly revealIsolationPicker: () => void; + readonly openIsolationPicker: () => void; + readonly banners: NewSessionBanners; +} + +export interface INewSessionInputController extends IDisposable { + confirmBeforeSend(query: string): Promise<boolean>; +} + +export interface IConfigPickerItem { + readonly id?: string; + readonly value: string; + readonly label: string; + readonly description?: string; + readonly checked?: boolean; + readonly disabled?: boolean; + readonly badge?: string; + readonly secondaryBadge?: boolean; + /** Runs instead of selecting a configuration value. */ + readonly run?: () => void; +} + +export interface IIsolationPickerTriggerContext { + readonly trigger: HTMLElement; + readonly sessionId: string; + readonly title: string; + readonly label: string; + readonly ariaLabel: string; + readonly tooltip: string | undefined; + readonly hoverDelegate: IHoverDelegate; +} + +/** A presentation captured for one open picker. Configuration writes remain owned by the picker. */ +export interface IIsolationPickerRecommendation { + readonly className?: string; + readonly minWidth?: number; + decorateOptions(items: readonly IConfigPickerItem[]): readonly IConfigPickerItem[]; + appendItems(items: IActionListItem<IConfigPickerItem>[]): IActionListItem<IConfigPickerItem>[]; + onSelect(value: string): void; + onDidShow?(options: IActionListItem<IConfigPickerItem>[], updateItems: (items: IActionListItem<IConfigPickerItem>[]) => void): IDisposable; +} + +export interface ISessionIsolationPickerPresentation { + /** The trigger owns the returned listeners, independently of the open picker's lifetime. */ + renderTrigger(context: IIsolationPickerTriggerContext): IDisposable; + getRecommendation(sessionId: string): IIsolationPickerRecommendation | undefined; +} + +/** Selected by the entry. Each factory uses the owning surface's instantiation scope. */ +export interface INewSessionInputPresentation { + getAccessibilityHelp?(): string; + createComposer?(container: HTMLElement, context: INewSessionInputContext, instantiationService: IInstantiationService): INewSessionInputController; + createIsolationPicker?(session: IObservable<ISession | undefined>, instantiationService: IInstantiationService): ISessionIsolationPickerPresentation; +} diff --git a/src/vs/workbench/contrib/sessions/browser/openInVSCodeUtils.ts b/src/vs/workbench/contrib/sessions/browser/openInVSCodeUtils.ts index af4ead64b3fb..007419431be9 100644 --- a/src/vs/workbench/contrib/sessions/browser/openInVSCodeUtils.ts +++ b/src/vs/workbench/contrib/sessions/browser/openInVSCodeUtils.ts @@ -4,6 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostEntryType } from '../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { computeSSHConnectionKey, ISSHRemoteAgentHostService } from '../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ITunnelAgentHostService } from '../../../../platform/agentHost/common/tunnelAgentHost.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService } from '../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { toLocalAgentHostSessionType } from '../../../../platform/agentHost/common/agentHostSessionType.js'; @@ -114,19 +116,37 @@ export function resolveRemoteFolderUri( return fromAgentHostUri(folderUri).with({ authority: remoteAuthority, scheme: Schemas.vscodeRemote }); } -/** - * Why editor windows cannot open a session, see {@link getEditorWindowSessionResource}. For `'remote'`, the editor's - * VS Code server runs its own agent host. For `'otherAgentHost'`, the tunnel's gateway connected this window to a - * different agent host on the tunnel's machine than the one its editor windows reach. - */ -export type EditorWindowSessionUnsupportedReason = 'remote' | 'otherAgentHost'; +/** Why the editor window cannot open a session from the connected remote agent host. */ +export type EditorWindowSessionUnsupportedReason = 'unsupported' | 'differentAgentHost'; + +/** Editor-owned endpoints are shared only when the editor window follows the same stored SSH preference. */ +export function getEditorWindowSessionUnsupportedReason( + entry: IRemoteAgentHostEntry | undefined, + tunnelAgentHostService: ITunnelAgentHostService, + sshRemoteAgentHostService: ISSHRemoteAgentHostService, + locationPreferenceService: IRemoteAgentHostLocationPreferenceService, +): EditorWindowSessionUnsupportedReason | undefined { + switch (entry?.connection.type) { + case RemoteAgentHostEntryType.Tunnel: + // Tunnel editor windows are named by label, so they cannot look up the stored preference and always use a standalone host. + return tunnelAgentHostService.getSelectedServerType(getEntryAddress(entry)) === 'editor' ? 'differentAgentHost' : undefined; + case RemoteAgentHostEntryType.SSH: { + const address = getEntryAddress(entry); + const hostKey = computeSSHConnectionKey({ sshConfigHost: entry.connection.sshConfigHost, username: entry.connection.user, host: entry.connection.hostName, port: entry.connection.port }); + return sshRemoteAgentHostService.connections.find(connection => connection.localAddress === address)?.serverType === 'editor' + && locationPreferenceService.getPreference(hostKey) !== 'editor' ? 'differentAgentHost' : undefined; + } + case RemoteAgentHostEntryType.WSL: + case RemoteAgentHostEntryType.DevContainer: + return undefined; + default: + return 'unsupported'; + } +} /** * Names a session or chat as the editor window that opens its folder does, or returns why that window cannot open it. - * An editor window of a VS Code remote reaches the agent host on its remote machine as its own agent host, while this - * window connects to the same host as a remote agent host, which names its sessions differently. Only a tunnel's - * editor windows share that agent host. Elsewhere, the editor's VS Code server runs its own agent host, with a session - * registry separate from that of the agent host this window starts. + * Supported remote editor windows reach the shared host as their own agent host, using local session schemes. */ export function getEditorWindowSessionResource( resource: URI, @@ -135,28 +155,30 @@ export function getEditorWindowSessionResource( remoteAgentHostService: IRemoteAgentHostService, agentHostConnectionsService: IAgentHostConnectionsService, tunnelAgentHostService: ITunnelAgentHostService, + sshRemoteAgentHostService: ISSHRemoteAgentHostService, + locationPreferenceService: IRemoteAgentHostLocationPreferenceService, ): URI | EditorWindowSessionUnsupportedReason { const connectionAuthority = agentHostConnectionsService.resolveSessionResourceIdentity(resource)?.connectionAuthority; if (!connectionAuthority || connectionAuthority === AMBIENT_AGENT_HOST_AUTHORITY) { return resource; } const sessionType = toLocalAgentHostSessionType(resource.scheme, connectionAuthority); - const entry = getRemoteAgentHostEntry(providerId, sessionsProvidersService, remoteAgentHostService); - if (!sessionType || entry?.connection.type !== RemoteAgentHostEntryType.Tunnel) { - return 'remote'; + if (!sessionType) { + return 'unsupported'; } - // The tunnel's editor windows reach its standalone agent host, which a gateway may not have selected for this window. - if (tunnelAgentHostService.getSelectedServerType(getEntryAddress(entry)) === 'editor') { - return 'otherAgentHost'; + const entry = getRemoteAgentHostEntry(providerId, sessionsProvidersService, remoteAgentHostService); + const reason = getEditorWindowSessionUnsupportedReason(entry, tunnelAgentHostService, sshRemoteAgentHostService, locationPreferenceService); + if (reason) { + return reason; } return resource.with({ scheme: sessionType }); } /** Explains why the editor window opened for a session's folder does not open the session as well. */ export function notifyEditorWindowSessionUnsupported(notificationService: INotificationService, reason: EditorWindowSessionUnsupportedReason): void { - notificationService.info(reason === 'otherAgentHost' - ? localize('openInVSCode.otherAgentHostSessionUnsupported', "The session's folder was opened in a new editor window, but the session can't be opened there. This window is connected to a different agent host on the tunnel's machine than the one its editor windows use.") - : localize('openInVSCode.remoteSessionUnsupported', "The session's folder was opened in a new editor window, but editor windows can't open sessions from this remote yet. Only local and tunnel sessions can be opened there.")); + notificationService.info(reason === 'differentAgentHost' + ? localize('openInVSCode.differentAgentHostSessionUnsupported', "The session's folder was opened in a new editor window, but the session can't be opened there. This window is connected to a different agent host on the remote machine than the one its editor windows use.") + : localize('openInVSCode.sessionUnsupported', "The session's folder was opened in a new editor window, but editor windows can't open sessions from this kind of remote.")); } /** diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatCompositeBar.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatCompositeBar.ts index fbf34aa98e1b..44edc97bf98b 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatCompositeBar.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatCompositeBar.ts @@ -33,7 +33,8 @@ import { localize } from '../../../../../nls.js'; import { ChatInteractivity, getChatCapabilities, getChatHarness, IChat, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; import { getHarnessPresentationOrDefault, IHarnessPresentation } from '../../common/sessionsProvider.js'; import { ISessionsManagementService } from '../../common/sessionsManagement.js'; -import { clearChatReferenceDragData, fillChatReferenceDragData, fillSessionChatDragData, isSessionDragFromPaneEdge, onDidEndSessionChatDrag } from '../dnd.js'; +import { fillSessionChatDragData, fillSessionChatReferenceDragData, isSessionDragFromPaneEdge, onDidEndSessionChatDrag } from '../dnd.js'; +import { clearChatReferenceDragData } from '../../../../../platform/dnd/browser/dnd.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { applySessionBarThemeColors } from './sessionBarStyles.js'; import { ISessionsProvidersService } from '../sessionsProvidersService.js'; @@ -134,6 +135,7 @@ export class ChatCompositeBar extends Disposable { private readonly _connectedTabOverflowEdge: HTMLElement; private _connectedTab: IChatTab | undefined; private readonly _sessionActionsContainer: HTMLElement; + private readonly _sessionToolbar: MenuWorkbenchToolBar; private readonly _sessionMenuArgs: unknown[] = []; private readonly _tabs: IChatTab[] = []; private readonly _tabDisposables = this._register(new DisposableStore()); @@ -212,7 +214,7 @@ export class ChatCompositeBar extends Disposable { this._tabsRow.appendChild(this._sessionActionsContainer); const sessionToolbarContainer = $('.chat-composite-bar-toolbar'); this._sessionActionsContainer.appendChild(sessionToolbarContainer); - this._register(this._instantiationService.createInstance(MenuWorkbenchToolBar, sessionToolbarContainer, Menus.SessionBarToolbar, { + this._sessionToolbar = this._register(this._instantiationService.createInstance(MenuWorkbenchToolBar, sessionToolbarContainer, Menus.SessionBarToolbar, { hoverDelegate: this._hoverDelegate, hiddenItemStrategy: HiddenItemStrategy.Ignore, menuOptions: { args: this._sessionMenuArgs }, @@ -286,6 +288,7 @@ export class ChatCompositeBar extends Disposable { } this._delegate = delegate; + this._sessionToolbar.context = delegate?.session; this._sessionMenuArgs.splice(0, this._sessionMenuArgs.length, ...(delegate?.session ? sessionMenuArgs(delegate.session, undefined, this._sessionHost) : [])); const store = new DisposableStore(); @@ -601,19 +604,10 @@ export class ChatCompositeBar extends Disposable { this._cancelTabEditing(); // Group-move payload (on dataTransfer, not the shared LocalSelectionTransfer - // singleton) lets the chat be moved between groups / split out. It must not - // use the singleton because the chat-reference payload below also uses it, - // and the singleton holds only one payload at a time. + // singleton) lets the chat be moved between groups / split out, and the + // chat-reference payload lets it drop into an agent-host chat input. fillSessionChatDragData(e, delegate.session.sessionId, chat.resource, delegate.isDetached); - - // Chat-reference payload: requires the opaque backend chat URI, which - // only the owning agent-host provider knows. When it is unavailable - // (not agent-host backed, or state not yet hydrated) the drag simply - // carries no reference. - const backendChatResource = this._backendChatResource(chat); - if (backendChatResource) { - fillChatReferenceDragData(e, backendChatResource, chat.resource, chat.title.get()); - } + fillSessionChatReferenceDragData(e, delegate.session, chat, this._sessionsProvidersService); e.dataTransfer.effectAllowed = 'copyMove'; applyDragImage(e, tab, chat.title.get()); @@ -734,22 +728,6 @@ export class ChatCompositeBar extends Disposable { return isHTMLElement(event.target) && !!event.target.closest('.chat-composite-bar-tab-input-container'); } - /** - * Resolves the opaque backend chat URI for a chat tab so a dragged `#chat:` - * reference can carry it. Reaches the owning agent-host provider by id and - * asks it to look up the host-supplied backend resource. Returns `undefined` - * when the session is not agent-host backed or the provider has no hydrated - * state for the chat — the caller then offers no chat-reference payload. - */ - private _backendChatResource(chat: IChat): URI | undefined { - const session = this._delegate?.session; - if (!session) { - return undefined; - } - const provider = this._sessionsProvidersService.getProvider(session.providerId, session.sessionId); - return provider && isAgentHostProvider(provider) ? provider.getBackendChatResource(chat.resource) : undefined; - } - startFocusedTabEditing(): boolean { const chatTab = this._tabs.find(tab => tab.element === tab.element.ownerDocument.activeElement); if (!chatTab) { @@ -820,7 +798,8 @@ export class ChatCompositeBar extends Disposable { // own key handlers only react to keys targeting the tab itself. })); - store.add(addDisposableListener(inputBox.inputElement, EventType.BLUR, () => finish(false))); + // Clicking away keeps the new name, like the rename in the sessions list. + store.add(addDisposableListener(inputBox.inputElement, EventType.BLUR, () => finish(true))); store.add(addDisposableListener(inputBox.element, EventType.CLICK, e => e.stopPropagation())); store.add(addDisposableListener(inputBox.element, EventType.DBLCLICK, e => e.stopPropagation())); diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupDropTarget.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupDropTarget.ts index 9649b6518117..4dfb0a4680dc 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupDropTarget.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupDropTarget.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import './media/chatGroupDropTarget.css'; -import { $, addDisposableListener, DragAndDropObserver, EventHelper, EventType, getWindow } from '../../../../../base/browser/dom.js'; +import { $, addDisposableListener, DragAndDropObserver, EventHelper, EventType, getWindow, isHTMLElement } from '../../../../../base/browser/dom.js'; import { RunOnceScheduler } from '../../../../../base/common/async.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { assertReturnsDefined } from '../../../../../base/common/types.js'; @@ -12,7 +12,8 @@ import { IInstantiationService } from '../../../../../platform/instantiation/com import { activeContrastBorder } from '../../../../../platform/theme/common/colorRegistry.js'; import { IThemeService, Themable } from '../../../../../platform/theme/common/themeService.js'; import { EDITOR_DRAG_AND_DROP_BACKGROUND } from '../../../../common/theme.js'; -import { getChatReferenceDropClipPath, IDraggedSessionChat, isChatReferenceInputDrop } from '../dnd.js'; +import { IDraggedSessionChat } from '../dnd.js'; +import { InputDropTargetHints, isInputDropTarget } from '../../../../browser/dnd.js'; /** Zone of a target group where a dragged chat can be dropped. */ export type ChatDropZone = 'left' | 'right' | 'top' | 'bottom' | 'center'; @@ -48,6 +49,7 @@ class ChatGroupDropOverlay extends Themable { private _container: HTMLElement | undefined; private _overlay: HTMLElement | undefined; + private _inputHints: InputDropTargetHints | undefined; private _currentZone: ChatDropZone | undefined; @@ -76,7 +78,6 @@ class ChatGroupDropOverlay extends Themable { private _create(event: DragEvent): void { const container = this._container = $('div', { id: ChatGroupDropOverlay.OVERLAY_ID }); - container.style.clipPath = getChatReferenceDropClipPath(this._targetElement, event); this._targetElement.appendChild(container); this._targetElement.classList.add('chat-group-dragged-over'); @@ -88,6 +89,9 @@ class ChatGroupDropOverlay extends Themable { this._overlay = $('.chat-group-drop-overlay-indicator'); container.appendChild(this._overlay); + this._inputHints = this._register(new InputDropTargetHints(this._targetElement, container)); + this._inputHints.update(event); + this._registerListeners(container); this.updateStyles(); } @@ -107,12 +111,19 @@ class ChatGroupDropOverlay extends Themable { private _registerListeners(container: HTMLElement): void { this._register(new DragAndDropObserver(container, { onDragOver: e => { + // An input that takes the drag takes it once the drag moves over it: the overlay, which covers the input + // until then, goes away. + if (isHTMLElement(e.target) && isInputDropTarget(e.target, e, this._targetElement)) { + this.dispose(); + return; + } + if (!this._isChatDrag(e)) { this._hideOverlay(); return; } - container.style.clipPath = getChatReferenceDropClipPath(this._targetElement, e); + this._inputHints?.update(e); this._positionOverlay(e.clientX, e.clientY); if (this._cleanupOverlayScheduler.isScheduled()) { @@ -279,7 +290,8 @@ export class ChatGroupDropTarget extends Themable { private _onDragEnter(event: DragEvent): void { this._counter++; - if (isChatReferenceInputDrop(event)) { + // An input under the drag that takes it, such as a chat input that attaches the dragged chat, takes it here. + if (isHTMLElement(event.target) && isInputDropTarget(event.target, event)) { this._disposeOverlay(); this._updateContainer(false); return; diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupView.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupView.ts index de51634387f8..b7ed2ce0107c 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupView.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupView.ts @@ -5,6 +5,7 @@ import { $, append, size, trackFocus } from '../../../../../base/browser/dom.js'; import { ISerializableView, IViewSize } from '../../../../../base/browser/ui/grid/grid.js'; +import { onUnexpectedError } from '../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; @@ -28,6 +29,8 @@ import { getArchivedChatBannerContent, ISessionReadOnlyBannerContent, SessionRea import { ISelectNoWorkspaceOptions, ISelectWorkspaceOptions, WorkspaceSelectionResult } from '../../../../services/sessions/common/workspaceSelection.js'; import { AbstractChatView, ChatViewKind, IChatViewOptions, ISessionViewHostOptions } from './chatView.js'; import { ChatViewSessionActivityBar } from './sessionActivityBar.js'; +import { ISessionHost, SessionHost, SessionHostKind, sessionMenuArgs } from '../../../../services/sessions/browser/sessionHost.js'; +import { CLOSE_CHAT_COMMAND_ID } from '../../common/sessionCommands.js'; import { ChatHeader } from './chatHeader.js'; import { IGridEdgeInsets, NO_GRID_EDGE_INSETS } from '../../../../browser/parts/partGrid/partGridGap.js'; @@ -132,7 +135,14 @@ export class ChatGroupView extends Disposable implements ISerializableView { private readonly _contextDisposables = this._register(new DisposableStore()); private readonly _currentView = this._register(new MutableDisposable<AbstractChatView>()); private _draftChatResource: URI | undefined; + private readonly _context = observableValue<IChatGroupContext | undefined>(this, undefined); + private readonly _activeChat = derived(this, reader => { + const context = this._context.read(reader); + const activeResource = context?.activeChatResource.read(reader); + return context?.chats.read(reader).find(c => c.resource.toString() === activeResource); + }); private readonly _scopedInstantiationService: IInstantiationService; + private readonly _chatViewInstantiationService: IInstantiationService; private readonly _activeChatIsClosableKey: IContextKey<boolean>; private readonly _activeChatCanArchiveKey: IContextKey<boolean>; private readonly _activeChatIsDeletableKey: IContextKey<boolean>; @@ -182,10 +192,19 @@ export class ChatGroupView extends Disposable implements ISerializableView { @ICommandService private readonly _commandService: ICommandService, @IConfigurationService configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, + @ISessionHost private readonly _sessionHost: ISessionHost, ) { super(); const scopedContextKeyService = this._register(contextKeyService.createScoped(this.element)); this._scopedInstantiationService = this._register(this._instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); + // The group's chat for its chat view, such as its input's pickers. Unregistered, so commands still find the pane. + this._chatViewInstantiationService = this._scopedInstantiationService.createChild(new ServiceCollection([ISessionHost, new SessionHost({ + kind: SessionHostKind.Pane, + parent: _sessionHost, + session: derived(reader => this._context.read(reader)?.session), + chat: this._activeChat, + contextKeyService: _sessionHost.contextKeyService, + })])); this._activeChatIsClosableKey = SessionActiveChatIsClosableContext.bindTo(scopedContextKeyService); this._activeChatCanArchiveKey = SessionActiveChatCanArchiveContext.bindTo(scopedContextKeyService); this._activeChatIsDeletableKey = SessionActiveChatIsDeletableContext.bindTo(scopedContextKeyService); @@ -273,6 +292,7 @@ export class ChatGroupView extends Disposable implements ISerializableView { /** Sets (or clears) the group this view renders. */ setContext(context: IChatGroupContext | undefined): void { this._contextDisposables.clear(); + this._context.set(context, undefined); this._connection.setSession(context?.session); if (!context) { @@ -298,15 +318,18 @@ export class ChatGroupView extends Disposable implements ISerializableView { return; } - const activeChat = derived(reader => { - const activeResource = context.activeChatResource.read(reader); - return context.chats.read(reader).find(c => c.resource.toString() === activeResource); - }); + const activeChat = this._activeChat; this._chatHeader.setChat({ session: context.session, chat: activeChat, isDetached: context.isDetached, activate: () => context.activate(), + close: () => { + const chat = activeChat.get(); + if (chat) { + void this._commandService.executeCommand(CLOSE_CHAT_COMMAND_ID, ...sessionMenuArgs(context.session, chat, this._sessionHost)).catch(onUnexpectedError); + } + }, }); this._contextDisposables.add(autorun(reader => { const visible = context.chatHeaderVisible.read(reader); @@ -428,7 +451,7 @@ export class ChatGroupView extends Disposable implements ISerializableView { let view = this._currentView.value; if (!view || view.kind !== desiredKind) { view = desiredKind === 'chat' - ? this._chatViewFactory.createChatView(this._scopedInstantiationService, { input: this._hostOptions?.input, session: context.options.session }) + ? this._chatViewFactory.createChatView(this._chatViewInstantiationService, { input: this._hostOptions?.input, session: context.options.session }) : this._chatViewFactory.createNewChatView(desiredKind === 'newChatInSession', context.options, this._scopedInstantiationService); this._contentContainer.replaceChildren(view.element, this._remoteHostUnavailableEmptyState.domNode); this._currentView.value = view; diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupsView.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupsView.ts index f18ccb497afd..c7ba87b7a200 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatGroupsView.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatGroupsView.ts @@ -31,6 +31,7 @@ import { DraggedSessionIdentifier, getSessionChatDragData, IDraggedSessionChat, import { SESSIONS_CHAT_TABS_DEFAULT, SESSIONS_CHAT_TABS_SETTING, SessionsChatTabsMode } from '../../common/sessionConfig.js'; import { getGridBottomCornerViews, getGridEdgeInsets, NO_GRID_EDGE_INSETS, updateGridGapSashes } from '../../../../browser/parts/partGrid/partGridGap.js'; import { ISessionPaneContent } from '../../../../services/sessions/common/sessionPane.js'; +import { updateSashEndpoints } from '../../../../browser/part.js'; interface IGroupEntry { readonly id: number; @@ -1263,7 +1264,7 @@ export class ChatGroupsView extends Themable { if (this._grid) { const hasGaps = gap > 0 && this._groups.length > 1; this.element.classList.toggle('chat-groups-view-has-gaps', hasGaps); - updateGridGapSashes(this._grid, hasGaps); + updateGridGapSashes(this._grid, hasGaps, gap); const corners = getGridBottomCornerViews(this._grid); for (const group of this._groups) { group.view.element.classList.toggle('chat-grid-bottom-left', group.view === corners.bottomLeft); @@ -1286,6 +1287,7 @@ export class ChatGroupsView extends Themable { this._grid.layout(width, height, top, left); this._gridDidLayout = true; this._gridTopologyChanged = false; + updateSashEndpoints(this._grid.element, hasGaps); } else { this.element.classList.remove('chat-groups-view-has-gaps'); } diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatHeader.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatHeader.ts index ddce58df75eb..d01e6035be3c 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatHeader.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatHeader.ts @@ -16,6 +16,7 @@ export interface IChatHeaderContext { /** Whether the header is of a pane that shows one chat of its session apart from its slot, such as a detached pane. */ readonly isDetached: boolean; readonly activate: () => void; + readonly close: () => void; } /** @@ -46,6 +47,7 @@ export class ChatHeader extends Disposable { actionsTargetChat: true, showParentContext: true, activateChatGroup: context.activate, + closeSession: context.close, } : undefined); } diff --git a/src/vs/workbench/contrib/sessions/browser/parts/chatView.ts b/src/vs/workbench/contrib/sessions/browser/parts/chatView.ts index 10787f988e42..e6f97edb6b49 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/chatView.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/chatView.ts @@ -40,6 +40,18 @@ export interface IChatViewRequestSubmission { readonly completion: Promise<IChatViewRequestOutcome>; } +export interface IChatViewBackgroundReplica extends IDisposable { + updateBackground(): void; + layout(): void; +} + +/** Entry-owned background presentation, omitted when a composition does not support backgrounds. */ +export interface IChatViewBackground { + readonly onDidChange: Event<void>; + hasBackground(): boolean; + createReplica(chatElement: HTMLElement, container: HTMLElement): IChatViewBackgroundReplica | undefined; +} + /** * Options passed to a chat view when it is created. */ @@ -47,6 +59,7 @@ export interface IChatViewOptions { readonly inputEditorOptions?: Pick<IEditorOptions, 'fontSize' | 'lineHeight'>; readonly showEmptyStateIcon?: boolean; readonly renderNewSessionHeader?: (container: HTMLElement, before: HTMLElement) => IDisposable; + readonly background?: IChatViewBackground; /** Visibility of the owning session slot, preserved across composer/preparation/transcript handoffs. */ readonly hostVisible?: IObservable<boolean>; /** Keep the custom view hosting this composer visible while preparing its draft. */ @@ -167,7 +180,11 @@ export interface ISessionViewHostOptions { */ export abstract class AbstractChatView extends Disposable implements ISerializableView { - readonly element: HTMLElement = $('.chat-view'); + /** + * The root of the chat: `.sessions-chat` is the class its styles are keyed on, so that it looks the same in every host, + * such as the Agents window, a chat window or the chat part of an editor window, whatever the host's own classes. + */ + readonly element: HTMLElement = $('.chat-view.sessions-chat'); readonly minimumWidth = 200; readonly maximumWidth = Number.POSITIVE_INFINITY; diff --git a/src/vs/workbench/contrib/sessions/browser/parts/media/chatCompositeBar.css b/src/vs/workbench/contrib/sessions/browser/parts/media/chatCompositeBar.css index d4d6f7c645c2..c4f5468b78ae 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/media/chatCompositeBar.css +++ b/src/vs/workbench/contrib/sessions/browser/parts/media/chatCompositeBar.css @@ -131,10 +131,15 @@ cursor: text; } -.chat-composite-bar-session-title.editable:hover { +.chat-composite-bar-session-title.editable:not(.editing):not(:focus-within):is(:hover, .hovered) { background-color: var(--vscode-toolbar-hoverBackground); } +:is(.hc-black, .hc-light) .chat-composite-bar-session-title.editable:not(.editing):not(:focus-within):is(:hover, .hovered) { + outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); +} + .chat-composite-bar-session-title.editing { flex: 1 1 auto; cursor: default; @@ -443,7 +448,7 @@ } .chat-composite-bar-tab.needs-input .chat-composite-bar-tab-indicator-icon::before { - background-color: var(--vscode-list-warningForeground); + background-color: var(--vscode-agentSessionNeedsInput-foreground); } .session-chat-tabs-bar .chat-composite-bar-tab.in-progress .chat-composite-bar-tab-indicator-icon { @@ -603,6 +608,7 @@ * Connected tabs retain the same ownership in compact density. */ .monaco-workbench.agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):is(.modern-ui-connected-editor-tabs, :not(.modern-ui-compact)) :is(.part.sessionspart.agents-part-card, .sessions-chat-surface.agents-card-surface) { border-color: transparent; + border-width: var(--agents-session-frame-inset); background-clip: padding-box; } @@ -612,7 +618,7 @@ .monaco-workbench.agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):is(.modern-ui-connected-editor-tabs, :not(.modern-ui-compact)) .session-view { position: relative; - border-radius: max(0px, calc(var(--agents-part-corner-radius, var(--vscode-cornerRadius-large)) - var(--vscode-strokeThickness))); + border-radius: max(0px, calc(var(--agents-component-corner-radius, var(--agents-part-corner-radius, var(--vscode-cornerRadius-large))) - var(--agents-session-frame-inset, var(--vscode-strokeThickness)))); overflow: hidden; } @@ -648,7 +654,7 @@ } .monaco-workbench.agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):is(.modern-ui-connected-editor-tabs, :not(.modern-ui-compact)) .chat-groups-view-has-gaps .chat-group-view-surface { - border-radius: max(0px, calc(var(--agents-part-corner-radius, var(--vscode-cornerRadius-large)) - var(--vscode-strokeThickness))); + border-radius: max(0px, calc(var(--agents-component-corner-radius, var(--agents-part-corner-radius, var(--vscode-cornerRadius-large))) - var(--agents-session-frame-inset, var(--vscode-strokeThickness)))); } .monaco-workbench.agent-sessions-workbench.modern-ui-tabs:not(.phone-layout):is(.modern-ui-connected-editor-tabs, :not(.modern-ui-compact)) .chat-groups-view-has-gaps .chat-group-view-content { diff --git a/src/vs/workbench/contrib/sessions/browser/parts/media/sessionActivityBar.css b/src/vs/workbench/contrib/sessions/browser/parts/media/sessionActivityBar.css index 39c5101b8141..8db687ed7b95 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/media/sessionActivityBar.css +++ b/src/vs/workbench/contrib/sessions/browser/parts/media/sessionActivityBar.css @@ -19,19 +19,32 @@ * fills the column from top to bottom, so the whole column is the activity bar and offers its context menu anywhere. * The column keeps the gap between cards to its left (`SessionActivityBarColumn`). */ .monaco-workbench .session-activity-bar-column .session-activity-bar.docked { - top: 0; - bottom: 0; + top: var(--agents-session-frame-inset, 0px); + bottom: var(--agents-session-frame-inset, 0px); right: 0; } -/* Beside the chat while the side pane is closed, whose visible frame is inset within its part: moved toward it by as - * much, so the gap between them is the gap between cards. */ -.monaco-workbench.noeditorpane .session-activity-bar-column .session-activity-bar.docked { - right: var(--agents-session-frame-inset); +.monaco-workbench .menu-activity-bar.session-activity-bar:not(.floating) { + background-color: var(--vscode-agentsActivityBar-background, transparent); + border-color: var(--vscode-agentsActivityBar-border, transparent); +} + +.monaco-workbench .menu-activity-bar.session-activity-bar.size-compact:not(.floating) { + --menu-activity-bar-gap: var(--vscode-spacing-size40); +} + +/* Match the connected panel header's centerline, including its shared bottom stroke. */ +.monaco-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs .menu-activity-bar.session-activity-bar.size-compact:not(.floating) { + padding-top: calc((var(--editor-group-tab-height, var(--vscode-spacing-size240)) + var(--vscode-spacing-size80) - var(--vscode-strokeThickness) - var(--menu-activity-bar-item-size)) / 2 - var(--vscode-strokeThickness)); +} + +.monaco-workbench.modern-ui-tabs.modern-ui-connected-editor-tabs.editor-tabs-compact-height .menu-activity-bar.session-activity-bar.size-compact:not(.floating) { + --editor-group-tab-height: var(--vscode-spacing-size200); } .monaco-workbench .session-activity-bar.docked { position: absolute; + top: 0; /* With an equal gap on either side in its column (`SESSION_ACTIVITY_BAR_COLUMN_WIDTH`). */ right: var(--vscode-spacing-size20); /* Above the chat transcript's layers (sticky scroll 13, scrollbar 14, prompt timeline rail 15, state indicator 16); @@ -72,7 +85,7 @@ justify-content: center; width: 100%; height: var(--vscode-spacing-size120); - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); cursor: grab; touch-action: none; } diff --git a/src/vs/workbench/contrib/sessions/browser/parts/media/sessionsGridContent.css b/src/vs/workbench/contrib/sessions/browser/parts/media/sessionsGridContent.css index 22649c1cd40a..9d4fc751faa8 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/media/sessionsGridContent.css +++ b/src/vs/workbench/contrib/sessions/browser/parts/media/sessionsGridContent.css @@ -9,6 +9,10 @@ z-index: 2; } +.session-grid.single-chat :is(.session-header-bar[draggable="true"], .chat-composite-bar-toolbar-floating) { + cursor: default; +} + .monaco-workbench :is(.part.sessionspart, .sessions-chat-surface) > .content .monaco-editor, .monaco-workbench :is(.part.sessionspart, .sessions-chat-surface) > .content .monaco-editor .margin, .monaco-workbench :is(.part.sessionspart, .sessions-chat-surface) > .content .monaco-editor .monaco-editor-background { diff --git a/src/vs/workbench/contrib/sessions/browser/parts/sessionActivityBar.ts b/src/vs/workbench/contrib/sessions/browser/parts/sessionActivityBar.ts index 8d969b66b1d7..f9fc86238e60 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/sessionActivityBar.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/sessionActivityBar.ts @@ -398,7 +398,8 @@ export class ChatViewSessionActivityBar extends Disposable { private applyPosition(): void { if (this.element?.isConnected && this.isShown(this.hostedIn.get()) && this.activityBar?.visible.get()) { - this.element.style.top = `${this.hostedIn.get() ? 0 : this.area.top + this.getOffset()}px`; + const host = this.hostedIn.get(); + this.element.style.top = host?.fullSize ? '' : `${host ? 0 : this.area.top + this.getOffset()}px`; } } diff --git a/src/vs/workbench/contrib/sessions/browser/parts/sessionDropTarget.ts b/src/vs/workbench/contrib/sessions/browser/parts/sessionDropTarget.ts index 1537c525986f..63cd54316611 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/sessionDropTarget.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/sessionDropTarget.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import './media/sessionDropTarget.css'; -import { $, addDisposableListener, DragAndDropObserver, EventHelper, EventType, getWindow } from '../../../../../base/browser/dom.js'; +import { $, addDisposableListener, DragAndDropObserver, EventHelper, EventType, getWindow, isHTMLElement } from '../../../../../base/browser/dom.js'; import { RunOnceScheduler } from '../../../../../base/common/async.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { assertReturnsAllDefined, assertReturnsDefined } from '../../../../../base/common/types.js'; @@ -13,7 +13,8 @@ import { LocalSelectionTransfer } from '../../../../../platform/dnd/browser/dnd. import { activeContrastBorder } from '../../../../../platform/theme/common/colorRegistry.js'; import { IThemeService, Themable } from '../../../../../platform/theme/common/themeService.js'; import { EDITOR_DRAG_AND_DROP_BACKGROUND } from '../../../../common/theme.js'; -import { DraggedSessionIdentifier, getChatReferenceDropClipPath, getSessionChatDragData, isChatReferenceInputDrop, isSessionChatDrag } from '../dnd.js'; +import { DraggedSessionIdentifier, getSessionChatDragData, isSessionChatDrag } from '../dnd.js'; +import { InputDropTargetHints, isInputDropTarget } from '../../../../browser/dnd.js'; import { URI } from '../../../../../base/common/uri.js'; import { ISession, isSessionCreated } from '../../../../services/sessions/common/session.js'; import { ISessionsManagementService } from '../../common/sessionsManagement.js'; @@ -44,6 +45,7 @@ class SessionDropOverlay extends Themable { private _container: HTMLElement | undefined; private _overlay: HTMLElement | undefined; + private _inputHints: InputDropTargetHints | undefined; private _currentSide: DropSide | undefined; @@ -73,7 +75,6 @@ class SessionDropOverlay extends Themable { private _create(event: DragEvent): void { const container = this._container = $('div', { id: SessionDropOverlay.OVERLAY_ID }); - container.style.clipPath = getChatReferenceDropClipPath(this._targetElement, event); this._targetElement.appendChild(container); this._targetElement.classList.add('dragged-over'); @@ -85,6 +86,9 @@ class SessionDropOverlay extends Themable { this._overlay = $('.session-drop-overlay-indicator'); container.appendChild(this._overlay); + this._inputHints = this._register(new InputDropTargetHints(this._targetElement, container)); + this._inputHints.update(event); + this._registerListeners(container); this.updateStyles(); } @@ -104,12 +108,19 @@ class SessionDropOverlay extends Themable { private _registerListeners(container: HTMLElement): void { this._register(new DragAndDropObserver(container, { onDragOver: e => { + // An input that takes the drag takes it once the drag moves over it: the overlay, which covers the input + // until then, goes away. + if (isHTMLElement(e.target) && isInputDropTarget(e.target, e, this._targetElement)) { + this.dispose(); + return; + } + if (!this._sessionTransfer.hasData(DraggedSessionIdentifier.prototype) && !isSessionChatDrag(e)) { this._hideOverlay(); return; } - container.style.clipPath = getChatReferenceDropClipPath(this._targetElement, e); + this._inputHints?.update(e); this._positionOverlay(e.clientX, e.clientY); if (this._cleanupOverlayScheduler.isScheduled()) { @@ -285,7 +296,8 @@ export class SessionDropTarget extends Themable { private _onDragEnter(event: DragEvent): void { this._counter++; - if (isChatReferenceInputDrop(event)) { + // An input under the drag that takes it, such as a chat input that attaches the dragged session's chat, takes it here. + if (isHTMLElement(event.target) && isInputDropTarget(event.target, event)) { this._disposeOverlay(); this._updateContainer(false); return; diff --git a/src/vs/workbench/contrib/sessions/browser/parts/sessionHeaderBar.ts b/src/vs/workbench/contrib/sessions/browser/parts/sessionHeaderBar.ts index b60da5092c95..32d578bd778d 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/sessionHeaderBar.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/sessionHeaderBar.ts @@ -268,19 +268,7 @@ export class SessionHeaderBar extends Disposable { this._register(addDisposableListener(this._container, EventType.DRAG_START, (e: DragEvent) => { const session = this._session; - // Its title drags the editor that shows the chat, as the editor's drag handle, which fills the drag: the header - // only adds the session and its chat, on the drag's own data, so that the editor's drag stays as it is and the - // chat can also drop where chats do, such as into the main window's grid. - if (this._dragsEditor) { - if (session) { - fillSessionDataTransfer(e, session); - if (this._activeChat) { - fillSessionChatDragData(e, session.sessionId, this._activeChat.resource); - } - } - return; - } - if (!session || !e.dataTransfer || this._dragFromPaneEdge) { + if (this._dragFromPaneEdge || (!this._dragsEditor && (!session || !e.dataTransfer))) { e.preventDefault(); return; } @@ -298,6 +286,22 @@ export class SessionHeaderBar extends Disposable { return; } + // The header drags the editor that shows the chat, as the editor's drag handle, which fills the drag: it only adds + // the session and its chat, on the drag's own data, so that the editor's drag stays as it is and the chat can + // also drop where chats do, such as into the main window's grid. + if (this._dragsEditor) { + if (session) { + fillSessionDataTransfer(e, session); + if (this._activeChat) { + fillSessionChatDragData(e, session.sessionId, this._activeChat.resource); + } + } + return; + } + + if (!session || !e.dataTransfer) { + return; + } if (this._actionsTargetChat) { const chat = this._activeChat; if (!chat) { @@ -318,14 +322,14 @@ export class SessionHeaderBar extends Disposable { this._sessionTransfer.clearData(DraggedSessionIdentifier.prototype); // The header's own drag, of its session or of its chat, can open it in a window of its own - if (e.target === this._container && this._session) { + if (e.target === this._container && this._session && !this._dragsEditor) { onDidEndSessionChatDrag(e, this._container, this._session, this._actionsTargetChat ? this._activeChat?.resource : undefined, this._titlePath); } })); } /** - * Lets its title drag the editor that shows the chat, as the drag handle of that editor, such as in a chat window, + * Lets it drag the editor that shows the chat, as the drag handle of that editor, such as in a chat window, * rather than the header dragging the session: the header then only adds the session and its chat to the drag. */ setDragsEditor(dragsEditor: boolean): void { @@ -591,7 +595,9 @@ export class SessionHeaderBar extends Disposable { export class SessionViewFloatingToolbar extends Disposable { private readonly _container: HTMLElement; + private readonly _toolbar: MenuWorkbenchToolBar; private readonly _toolbarContainer: HTMLElement; + private readonly _globalToolbarContainer: HTMLElement; private _session: ISession | undefined; private readonly _sessionDisposables = this._register(new MutableDisposable<DisposableStore>()); @@ -616,17 +622,23 @@ export class SessionViewFloatingToolbar extends Disposable { toolbar.style.display = 'none'; this._container.appendChild(toolbar); - this._register(instantiationService.createInstance(MenuWorkbenchToolBar, toolbar, Menus.SessionBarToolbar, { + this._toolbar = this._register(instantiationService.createInstance(MenuWorkbenchToolBar, toolbar, Menus.SessionBarToolbar, { hiddenItemStrategy: HiddenItemStrategy.Ignore, menuOptions: { args: this._menuActionArgs }, getSecondaryActionsPosition: getSessionToolbarSecondaryActionsPosition, highlightToggledItems: true, actionViewItemProvider: createSessionActionViewItemProvider(instantiationService, configurationService), })); + const globalToolbar = this._globalToolbarContainer = $('.chat-composite-bar-toolbar'); + this._container.appendChild(globalToolbar); + this._register(instantiationService.createInstance(MenuWorkbenchToolBar, globalToolbar, Menus.NewSessionGlobalToolbar, { + hiddenItemStrategy: HiddenItemStrategy.NoHide, + highlightToggledItems: true, + })); let canDrag = false; this._register(addDisposableGenericMouseDownListener(this._container, e => { - canDrag = !toolbar.contains(e.target as Node | null) && !isSessionDragFromPaneEdge(this._container, e); + canDrag = !toolbar.contains(e.target as Node | null) && !globalToolbar.contains(e.target as Node | null) && !isSessionDragFromPaneEdge(this._container, e); })); this._register(addDisposableListener(this._container, EventType.DRAG_START, (e: DragEvent) => { if (!canDrag || !e.dataTransfer || isSessionCreated(this._session)) { @@ -648,8 +660,10 @@ export class SessionViewFloatingToolbar extends Disposable { return; } this._session = session; + this._toolbar.context = session; this._menuActionArgs.splice(0, this._menuActionArgs.length, ...(session ? sessionMenuArgs(session, undefined, this._sessionHost) : [])); this._toolbarContainer.style.display = session ? '' : 'none'; + this._globalToolbarContainer.style.display = session ? 'none' : ''; const store = new DisposableStore(); this._sessionDisposables.value = store; diff --git a/src/vs/workbench/contrib/sessions/browser/parts/sessionView.ts b/src/vs/workbench/contrib/sessions/browser/parts/sessionView.ts index 9a2e05bb44e0..65a913da1ddc 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/sessionView.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/sessionView.ts @@ -59,9 +59,13 @@ export class SessionView extends Disposable implements ISerializableView, ISessi readonly element: HTMLElement = $('.session-view.modern-ui-editor-tab-group'); + /** The minimum height of the chat content below the session header, which the chat groups grid and standalone chats also keep. */ + private static readonly MINIMUM_CONTENT_HEIGHT = 200; + readonly minimumWidth = 200; readonly maximumWidth = Number.POSITIVE_INFINITY; - readonly minimumHeight = 200; + // The header sits above the chat content, so a session at its minimum still leaves the content its own minimum (see #339850). + get minimumHeight(): number { return SessionView.MINIMUM_CONTENT_HEIGHT + this._headerHeight.get(); } readonly maximumHeight = Number.POSITIVE_INFINITY; private readonly _onDidChange = this._register(new Emitter<IViewSize | undefined>()); @@ -129,9 +133,6 @@ export class SessionView extends Disposable implements ISerializableView, ISessi private readonly _headerHeight = observableValue<number>(this, 0); - /** The title of the session header. */ - get headerTitleElement(): HTMLElement { return this._header.titleElement; } - /** * The services of its own scope, which what it shows is created with: disposed after it, as what disposes may still * use them, such as a composer whose input clears as it goes away; see {@link dispose}. @@ -411,7 +412,11 @@ export class SessionView extends Disposable implements ISerializableView, ISessi } const barHeight = this._header.visible ? this._header.height : 0; - this._headerHeight.set(barHeight, undefined); + if (this._headerHeight.get() !== barHeight) { + this._headerHeight.set(barHeight, undefined); + // Let the session grid re-read the minimum height, which includes the header. + this._onDidChange.fire(undefined); + } const contentHeight = Math.max(0, height - barHeight); const contentTop = top + barHeight; this._standaloneSessionActivityBar?.layout(barHeight, contentHeight); diff --git a/src/vs/workbench/contrib/sessions/browser/parts/sessionsGridContent.ts b/src/vs/workbench/contrib/sessions/browser/parts/sessionsGridContent.ts index f7d76c7266ec..ec5d0f01347c 100644 --- a/src/vs/workbench/contrib/sessions/browser/parts/sessionsGridContent.ts +++ b/src/vs/workbench/contrib/sessions/browser/parts/sessionsGridContent.ts @@ -18,7 +18,7 @@ import { Emitter, Event } from '../../../../../base/common/event.js'; import { Color } from '../../../../../base/common/color.js'; import { contrastBorder } from '../../../../../platform/theme/common/colorRegistry.js'; import { SessionDropTarget, ISessionDropTargetDelegate } from './sessionDropTarget.js'; -import { SessionsChatSurface } from '../sessionsChatSurface.js'; +import { IChatViewFactory } from '../chatViewFactory.js'; import { noSessionPickerVisibility, SessionPickerVisibilityContextKeys } from '../../common/sessionPickerVisibility.js'; import { ISessionGridSlot, SessionGridRequest } from '../../../../services/sessions/browser/sessionsPartService.js'; import { ISessionGridPane, SessionGridPaneKind } from '../../../../services/sessions/browser/sessionGridPane.js'; @@ -87,6 +87,7 @@ export class SessionsGridContent extends Disposable implements ISessionsPartCont @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IThemeService private readonly themeService: IThemeService, + @IChatViewFactory private readonly chatViewFactory: IChatViewFactory, ) { super(); @@ -98,7 +99,10 @@ export class SessionsGridContent extends Disposable implements ISessionsPartCont } renderBackground(partContainer: HTMLElement): void { - this._register(this.instantiationService.createInstance(SessionsChatSurface, partContainer)); + const background = this.chatViewFactory.createChatBackground?.(partContainer, this.instantiationService); + if (background) { + this._register(background); + } } render(contentArea: HTMLElement): void { @@ -118,6 +122,10 @@ export class SessionsGridContent extends Disposable implements ISessionsPartCont this._slotsChanged.trigger(undefined); contentArea.appendChild(this._gridWidget.element); + this._register(autorun(reader => { + this._gridWidget?.element.classList.toggle('single-chat', this.shownChatCount.read(reader) <= 1); + })); + // Propagate the grid's maximized-view state to each session view so the // per-view toolbars can render the maximize action in its toggled state. this._register(this._gridWidget.onDidChangeMaximized(() => this._updateMaximizedState())); diff --git a/src/vs/workbench/contrib/sessions/browser/scheduledChatTimePicker.ts b/src/vs/workbench/contrib/sessions/browser/scheduledChatTimePicker.ts new file mode 100644 index 000000000000..be93e3f0eb2e --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/scheduledChatTimePicker.ts @@ -0,0 +1,311 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/scheduledChatTimePicker.css'; +import { $, addDisposableListener, append, EventHelper, EventType, reset } from '../../../../base/browser/dom.js'; +import { Button } from '../../../../base/browser/ui/button/button.js'; +import { InputBox } from '../../../../base/browser/ui/inputbox/inputBox.js'; +import { SelectBoxNative } from '../../../../base/browser/ui/selectBox/selectBoxNative.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { localize } from '../../../../nls.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { defaultButtonStyles, defaultInputBoxStyles, defaultSelectBoxStyles } from '../../../../platform/theme/browser/defaultStyles.js'; +import { parseScheduledChatTime } from '../common/scheduledChatRequest.js'; + +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} + +function addDays(date: Date, days: number): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days); +} + +function addMonths(date: Date, months: number): Date { + const lastDay = new Date(date.getFullYear(), date.getMonth() + months + 1, 0).getDate(); + return new Date(date.getFullYear(), date.getMonth() + months, Math.min(date.getDate(), lastDay)); +} + +function localDate(date: Date): string { + return `${date.getFullYear().toString().padStart(4, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`; +} + +/** A month grid for choosing a day with the mouse or keyboard, following the WAI-ARIA date picker grid pattern. */ +class ScheduledChatCalendar extends Disposable { + private readonly onDidSelectEmitter = this._register(new Emitter<void>()); + readonly onDidSelect = this.onDidSelectEmitter.event; + + private readonly monthLabel: HTMLElement; + private readonly body: HTMLElement; + private readonly previousButton: Button; + private readonly dates = new Map<HTMLElement, Date>(); + private month: Date; + private focused: Date; + + constructor(container: HTMLElement, private selected: Date, private readonly minimum: Date) { + super(); + const calendar = append(container, $('.scheduled-chat-calendar')); + const header = append(calendar, $('.scheduled-chat-calendar-header')); + const previousLabel = localize('sendLater.previousMonth', "Previous Month"); + this.previousButton = this._register(new Button(header, { ...defaultButtonStyles, secondary: true, supportIcons: true, ariaLabel: previousLabel, title: previousLabel })); + this.previousButton.label = '$(chevron-left)'; + const labelId = `scheduled-chat-calendar-${generateUuid()}`; + this.monthLabel = append(header, $('.scheduled-chat-calendar-month', { id: labelId, 'aria-live': 'polite' })); + const nextLabel = localize('sendLater.nextMonth', "Next Month"); + const nextButton = this._register(new Button(header, { ...defaultButtonStyles, secondary: true, supportIcons: true, ariaLabel: nextLabel, title: nextLabel })); + nextButton.label = '$(chevron-right)'; + + const grid = append(calendar, $('.scheduled-chat-calendar-grid', { role: 'grid', 'aria-labelledby': labelId })); + const weekdays = append(grid, $('.scheduled-chat-calendar-row', { role: 'row' })); + for (let day = 0; day < 7; day++) { + // January 1, 2023 was a Sunday. + const weekday = new Date(2023, 0, 1 + day); + append(weekdays, $('.scheduled-chat-calendar-weekday', { + role: 'columnheader', + 'aria-label': weekday.toLocaleDateString(undefined, { weekday: 'long' }), + }, weekday.toLocaleDateString(undefined, { weekday: 'narrow' }))); + } + this.body = append(grid, $('.scheduled-chat-calendar-body', { role: 'rowgroup' })); + + this.month = new Date(selected.getFullYear(), selected.getMonth(), 1); + this.focused = selected; + this._register(this.previousButton.onDidClick(() => this.showMonth(-1))); + this._register(nextButton.onDidClick(() => this.showMonth(1))); + this._register(addDisposableListener(this.body, EventType.CLICK, event => { + const cell = (event.target as HTMLElement).closest<HTMLElement>('[role="gridcell"]'); + const date = cell && this.dates.get(cell); + if (date) { + this.select(date); + } + })); + this._register(addDisposableListener(this.body, EventType.KEY_DOWN, event => this.onKeyDown(event))); + this.render(); + } + + get value(): Date { + return this.selected; + } + + focus(): void { + this.cellFor(this.focused)?.focus(); + } + + private onKeyDown(event: KeyboardEvent): void { + const moves: Record<string, (date: Date) => Date> = { + ArrowLeft: date => addDays(date, -1), + ArrowRight: date => addDays(date, 1), + ArrowUp: date => addDays(date, -7), + ArrowDown: date => addDays(date, 7), + Home: date => addDays(date, -date.getDay()), + End: date => addDays(date, 6 - date.getDay()), + PageUp: date => addMonths(date, -1), + PageDown: date => addMonths(date, 1), + }; + if (event.key === 'Enter' || event.key === ' ') { + this.select(this.focused); + } else if (Object.hasOwn(moves, event.key)) { + this.moveFocus(moves[event.key](this.focused)); + } else { + return; + } + event.preventDefault(); + event.stopPropagation(); + } + + private showMonth(offset: number): void { + const focused = addMonths(this.focused, offset); + this.focused = focused < this.minimum ? this.minimum : focused; + this.month = new Date(this.focused.getFullYear(), this.focused.getMonth(), 1); + this.render(); + } + + private moveFocus(date: Date): void { + this.focused = date < this.minimum ? this.minimum : date; + if (this.focused.getFullYear() !== this.month.getFullYear() || this.focused.getMonth() !== this.month.getMonth()) { + this.month = new Date(this.focused.getFullYear(), this.focused.getMonth(), 1); + this.render(); + } else { + this.updateStates(); + } + this.focus(); + } + + private select(date: Date): void { + if (date < this.minimum) { + return; + } + this.selected = date; + this.focused = date; + this.updateStates(); + this.onDidSelectEmitter.fire(); + } + + private cellFor(date: Date): HTMLElement | undefined { + for (const [cell, candidate] of this.dates) { + if (candidate.getTime() === date.getTime()) { + return cell; + } + } + return undefined; + } + + private render(): void { + this.monthLabel.textContent = this.month.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }); + this.previousButton.enabled = this.month > this.minimum; + this.dates.clear(); + reset(this.body); + const firstWeekday = this.month.getDay(); + const days = new Date(this.month.getFullYear(), this.month.getMonth() + 1, 0).getDate(); + for (let week = 0; week * 7 < firstWeekday + days; week++) { + const row = append(this.body, $('.scheduled-chat-calendar-row', { role: 'row' })); + for (let column = 0; column < 7; column++) { + const day = week * 7 + column - firstWeekday + 1; + const cell = append(row, $('.scheduled-chat-calendar-day', { role: 'gridcell' })); + if (day < 1 || day > days) { + continue; + } + const date = new Date(this.month.getFullYear(), this.month.getMonth(), day); + cell.textContent = String(day); + cell.setAttribute('aria-label', date.toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })); + this.dates.set(cell, date); + } + } + this.updateStates(); + } + + private updateStates(): void { + const today = startOfDay(new Date()).getTime(); + for (const [cell, date] of this.dates) { + const time = date.getTime(); + cell.tabIndex = time === this.focused.getTime() ? 0 : -1; + cell.setAttribute('aria-selected', String(time === this.selected.getTime())); + cell.setAttribute('aria-disabled', String(date < this.minimum)); + cell.classList.toggle('today', time === today); + } + } +} + +export async function pickScheduledChatTime(quickInputService: IQuickInputService, anchor?: HTMLElement): Promise<Date | undefined> { + const now = new Date(); + const formatTime = (date: Date) => date.toLocaleString(undefined, { timeZoneName: 'short' }); + const choices = [ + { minutes: 5, label: localize('sendLater.fiveMinutes', "In 5 Minutes") }, + { minutes: 10, label: localize('sendLater.tenMinutes', "In 10 Minutes") }, + { minutes: 15, label: localize('sendLater.fifteenMinutes', "In 15 Minutes") }, + { minutes: 30, label: localize('sendLater.thirtyMinutes', "In 30 Minutes") }, + { minutes: 60, label: localize('sendLater.oneHour', "In 1 Hour") }, + { minutes: 24 * 60, label: localize('sendLater.oneDay', "In 24 Hours") }, + ].map(({ minutes, label }) => { + const date = new Date(now.getTime() + minutes * 60_000); + return { label, date }; + }); + const tomorrow = new Date(now); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrow.setHours(9, 0, 0, 0); + choices.push({ label: localize('sendLater.tomorrowMorning', "Tomorrow Morning"), date: tomorrow }); + const picked = await quickInputService.pick([ + ...choices, + { label: localize('sendLater.customTime', "Choose Date and Time..."), date: undefined }, + ], { + title: localize('sendLater.title', "Send Later"), + placeHolder: localize('sendLater.pickTime', "Choose when to send."), + anchor, anchorPosition: anchor ? 'above' : undefined, + }); + if (!picked || picked.date) { + return picked?.date; + } + + const disposables = new DisposableStore(); + try { + const picker = disposables.add(quickInputService.createQuickWidget()); + picker.title = localize('sendLater.customTitle', "Send Later - Date and Time"); + picker.anchor = anchor; + picker.anchorPosition = anchor ? 'above' : undefined; + const form = $('.scheduled-chat-time-picker'); + picker.widget = form; + // Buttons blur themselves on Escape, which would close the picker without restoring focus to the invoking control. + disposables.add(addDisposableListener(form, EventType.KEY_DOWN, event => { + if (event.key === 'Escape') { + EventHelper.stop(event, true); + picker.hide(); + } + }, true)); + + const fields = append(form, $('.scheduled-chat-time-fields')); + const initial = new Date((Math.floor(Date.now() / 900_000) + 1) * 900_000); + const calendar = disposables.add(new ScheduledChatCalendar(fields, startOfDay(initial), startOfDay(new Date()))); + + const timeColumn = append(fields, $('.scheduled-chat-time-column')); + const timeLabel = append(timeColumn, $('.scheduled-chat-time-field')); + append(timeLabel, $('span', undefined, localize('sendLater.time', "Time"))); + const times = Array.from({ length: 96 }, (_, index) => { + const hours = Math.floor(index / 4); + const minutes = index % 4 * 15; + return { + text: new Date(2000, 0, 1, hours, minutes).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }), + value: `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`, + }; + }); + let timeIndex = initial.getHours() * 4 + initial.getMinutes() / 15; + const timeSelect = disposables.add(new SelectBoxNative([ + ...times, + { text: localize('sendLater.exactTime', "Exact Time...") }, + ], timeIndex, defaultSelectBoxStyles, { ariaLabel: localize('sendLater.time', "Time") })); + timeSelect.render(append(timeLabel, $('.scheduled-chat-time-select'))); + + const exactLabel = append(timeColumn, $('label.scheduled-chat-time-field')); + append(exactLabel, $('span', undefined, localize('sendLater.exactTimeLabel', "Exact time"))); + const exactInput = disposables.add(new InputBox(exactLabel, undefined, { + type: 'time', ariaLabel: localize('sendLater.exactTimeLabel', "Exact time"), inputBoxStyles: defaultInputBoxStyles, + })); + exactInput.value = times[timeIndex].value; + exactLabel.hidden = true; + + const summary = append(form, $('.scheduled-chat-time-summary', { role: 'status' })); + append(form, $('.scheduled-chat-time-hint', undefined, localize('sendLater.calendarHint', "Pick a day in the calendar and a time from the dropdown. Times use this device's time zone. The local agent host sends when available."))); + const actions = append(form, $('.scheduled-chat-time-actions')); + const scheduleButton = disposables.add(new Button(actions, defaultButtonStyles)); + scheduleButton.label = localize('sendLater.schedule', "Schedule"); + const cancelButton = disposables.add(new Button(actions, { ...defaultButtonStyles, secondary: true })); + cancelButton.label = localize('sendLater.cancel', "Cancel"); + const selectedDate = () => parseScheduledChatTime(`${localDate(calendar.value)} ${timeIndex < times.length ? times[timeIndex].value : exactInput.value}`); + const update = () => { + const date = selectedDate(); + const valid = !!date && date.getTime() > Date.now(); + scheduleButton.enabled = valid; + summary.textContent = valid + ? localize('sendLater.summary', "Send {0}", formatTime(date)) + : localize('sendLater.invalidTime', "Choose a valid future date and time."); + }; + disposables.add(calendar.onDidSelect(update)); + disposables.add(exactInput.onDidChange(update)); + disposables.add(timeSelect.onDidSelect(({ index }) => { + timeIndex = index; + exactLabel.hidden = index < times.length; + if (!exactLabel.hidden) { + exactInput.focus(); + } + update(); + })); + update(); + + return await new Promise<Date | undefined>(resolve => { + disposables.add(picker.onDidHide(() => resolve(undefined))); + disposables.add(cancelButton.onDidClick(() => picker.hide())); + disposables.add(scheduleButton.onDidClick(() => { + update(); + if (scheduleButton.enabled) { + resolve(selectedDate()); + picker.hide(); + } + })); + picker.show(); + calendar.focus(); + }); + } finally { + disposables.dispose(); + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/scheduledChatsService.ts b/src/vs/workbench/contrib/sessions/browser/scheduledChatsService.ts new file mode 100644 index 000000000000..03095d9d7135 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/scheduledChatsService.ts @@ -0,0 +1,925 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { isHTMLElement } from '../../../../base/browser/dom.js'; +import { status } from '../../../../base/browser/ui/aria/aria.js'; +import { toAction } from '../../../../base/common/actions.js'; +import { SequencerByKey } from '../../../../base/common/async.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { parse, stringify } from '../../../../base/common/marshalling.js'; +import { equals, stableStringify } from '../../../../base/common/objects.js'; +import { autorun, derived, IObservable, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../base/common/observable.js'; +import { basename, isEqual } from '../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { URI } from '../../../../base/common/uri.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { ITextModelService } from '../../../../editor/common/services/resolverService.js'; +import { localize } from '../../../../nls.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { IFileService } from '../../../../platform/files/common/files.js'; +import { Message, MessageKind } from '../../../../platform/agentHost/common/state/protocol/state.js'; +import { validateAutomationRunAt } from '../../../../platform/agentHost/common/automationRequest.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { IChatEntitlementService } from '../../../services/chat/common/chatEntitlementService.js'; +import { ChatInteractivity, ISession, SessionStatus } from '../../../services/sessions/common/session.js'; +import { IWorkingCopyService } from '../../../services/workingCopy/common/workingCopyService.js'; +import { ChatDynamicVariableModel } from '../../chat/browser/attachments/chatDynamicVariables.js'; +import { getDynamicVariablesForWidget } from '../../chat/browser/attachments/chatVariables.js'; +import { IChatWidget } from '../../chat/browser/chat.js'; +import { ChatAgentLocation } from '../../chat/common/constants.js'; +import { IChatService } from '../../chat/common/chatService/chatService.js'; +import { IChatDraft } from '../../chat/common/attachments/chatDraft.js'; +import { AutomationTarget, IAutomationDescriptor, IAutomationSchedule } from '../../chat/common/automations/automation.js'; +import { AutomationMutationGuard, AutomationMutationUncertainError, AutomationUnavailableError, IAutomationService, ICreateAutomationOptions, IGuardedAutomationUpdateResult, IUpdateAutomationOptions } from '../../chat/common/automations/automationService.js'; +import { CHAT_AUTOMATIONS_ENABLED_SETTING } from '../../chat/common/automations/automationsEnabled.js'; +import { ChatInputCanScheduleContext } from '../common/contextkeys.js'; +import { fromStoredChatDraft, toStoredChatDraft } from '../common/newChatDraftState.js'; +import { hasSessionDraftContent, ISavedSessionDraftTarget } from '../common/savedSessionDrafts.js'; +import { captureScheduledChatRequest } from '../common/scheduledChatRequest.js'; +import { SESSIONS_SEND_LATER_ENABLED_SETTING } from '../common/sessionConfig.js'; +import { ISessionsManagementService } from '../common/sessionsManagement.js'; +import { ISessionDraftsService } from './sessionDraftsService.js'; +import { ISessionGroupsService } from './sessionGroupsService.js'; +import { ISessionsService } from './sessionsService.js'; +import { IPendingSessionItem } from './views/pendingSessions.js'; +import { IChatScheduledRequest, IChatScheduledRequestEditing } from '../../chat/common/model/chatViewModel.js'; +import { pickScheduledChatTime } from './scheduledChatTimePicker.js'; + +const handoffStorageKey = 'sessions.scheduledChatHandoffs'; +const receiptStorageKey = 'sessions.scheduledChatReceipts'; +interface IScheduledChatReceipt { + readonly operationId: string; + readonly automationId: string; +} + +interface IScheduledChatHandoff { + readonly id: string; + readonly toolOperationId?: string; + readonly name?: string; + readonly compositionId: string; + readonly input: IChatDraft; + readonly target: ISavedSessionDraftTarget; + readonly automationTarget: AutomationTarget; + readonly request: Message; + readonly schedule: IAutomationSchedule; + readonly requestedAutomationId?: string; + readonly automationId?: string; + readonly conversation?: IAutomationDescriptor['conversation']; + readonly sourceTarget?: ISavedSessionDraftTarget; + readonly recoverySaved?: boolean; + readonly sourceReleased?: boolean; + readonly groupApplied?: boolean; +} + +export const IScheduledChatsService = createDecorator<IScheduledChatsService>('scheduledChatsService'); + +interface IScheduledChatItem extends IPendingSessionItem, IChatScheduledRequest { + readonly conversation?: IAutomationDescriptor['conversation']; +} + +export type IScheduledChatRequestOptions = Pick<ICreateAutomationOptions, 'name' | 'prompt' | 'schedule' | 'target' | 'sessionTemplate' | 'conversation'>; + +export interface IPendingScheduledChatRequest { + readonly handoffId: string; + readonly automationId?: string; + readonly providerId?: string; + readonly name: string; + readonly prompt: string; + readonly runAt: string; + readonly conversation?: IAutomationDescriptor['conversation']; +} + +export type ScheduledChatSubmission = + | { readonly status: 'accepted'; readonly automation: IAutomationDescriptor } + | { readonly status: 'unknown'; readonly pending: IPendingScheduledChatRequest; readonly message: string }; + +export interface IScheduledChatsService { + readonly _serviceBrand: undefined; + readonly enabled: IObservable<boolean>; + readonly items: IObservable<readonly IScheduledChatItem[]>; + readonly claimedDraftIds: IObservable<ReadonlySet<string>>; + canSchedule(session: ISession | undefined, conversation?: IAutomationDescriptor['conversation']): boolean; + readonly availableProviders: IAutomationService['availableProviders']; + schedule(input: IChatDraft, target: ISavedSessionDraftTarget, session: ISession, compositionId: string, conversation?: IAutomationDescriptor['conversation'], anchor?: HTMLElement): Promise<boolean>; + hasRequest(operationId: string): boolean; + scheduleRequest(options: IScheduledChatRequestOptions, operationId: string, mutationGuard?: AutomationMutationGuard, captureTemplate?: () => Promise<IScheduledChatRequestOptions['sessionTemplate']>): Promise<ScheduledChatSubmission>; + getPendingRequests(): readonly IPendingScheduledChatRequest[]; + updateRequest(automation: IAutomationDescriptor, patch: IUpdateAutomationOptions, mutationGuard?: AutomationMutationGuard): Promise<IGuardedAutomationUpdateResult>; + hasPendingHandoff(compositionId: string, input: IChatDraft): boolean; + releaseSource(compositionId: string): void; + assertUnscheduled(compositionId: string, input: IChatDraft): void; + registerChatInput(widget: IChatWidget, session: IObservable<ISession | undefined>, chatResource: IObservable<URI | undefined>, canSend: IObservable<boolean>): IDisposable; + scheduleChatInput(widget: IChatWidget): Promise<void>; + assertChatInputUnscheduled(widget: IChatWidget, query: string): void; +} + +export class ScheduledChatsService extends Disposable implements IScheduledChatsService { + declare readonly _serviceBrand: undefined; + readonly enabled: IObservable<boolean>; + readonly items: IObservable<readonly IScheduledChatItem[]>; + readonly claimedDraftIds: IObservable<ReadonlySet<string>>; + readonly availableProviders: IAutomationService['availableProviders']; + private readonly chatInputs = new Map<IChatWidget, { schedule(): Promise<void>; assertUnscheduled(query: string): void }>(); + private readonly automationsEnabled: IObservable<boolean>; + private readonly editingRequest = observableValue<{ id: string; state: IChatScheduledRequestEditing } | undefined>(this, undefined); + private readonly toolRequests = new SequencerByKey<string>(); + + constructor( + @IConfigurationService configurationService: IConfigurationService, + @IAutomationService private readonly automationService: IAutomationService, + @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, + @ISessionDraftsService private readonly draftsService: ISessionDraftsService, + @IChatEntitlementService private readonly entitlementService: IChatEntitlementService, + @IQuickInputService private readonly quickInputService: IQuickInputService, + @IDialogService private readonly dialogService: IDialogService, + @IStorageService private readonly storageService: IStorageService, + @ITextModelService private readonly textModelService: ITextModelService, + @IFileService private readonly fileService: IFileService, + @IWorkingCopyService private readonly workingCopyService: IWorkingCopyService, + @IChatService private readonly chatService: IChatService, + @ISessionsService private readonly sessionsService: ISessionsService, + @ISessionGroupsService groupsService: ISessionGroupsService, + ) { + super(); + const configured = observableConfigValue(SESSIONS_SEND_LATER_ENABLED_SETTING, false, configurationService); + this.automationsEnabled = observableConfigValue(CHAT_AUTOMATIONS_ENABLED_SETTING, false, configurationService); + const hidden = observableFromEvent(this, entitlementService.onDidChangeSentiment, () => entitlementService.sentiment.hidden); + this.enabled = derived(this, reader => configured.read(reader) && !hidden.read(reader)); + this.availableProviders = automationService.availableProviders; + const handoffsChanged = observableSignalFromEvent(this, storageService.onDidChangeValue(StorageScope.PROFILE, handoffStorageKey, this._store)); + this.claimedDraftIds = derived(this, reader => { + handoffsChanged.read(reader); + return new Set(this.enabled.read(reader) ? this.readHandoffs().filter(handoff => !handoff.conversation && !handoff.toolOperationId).map(handoff => handoff.compositionId) : []); + }); + const sessionsChanged = observableSignalFromEvent(this, sessionsManagementService.onDidChangeSessions); + this._register(autorun(reader => { + handoffsChanged.read(reader); + sessionsChanged.read(reader); + const automations = automationService.automations.read(reader); + const runs = automationService.runs.read(reader); + const catalogueState = automationService.catalogueState.read(reader); + const providers = automationService.availableProviders.read(reader); + for (const handoff of this.readHandoffs()) { + if (handoff.toolOperationId) { + const automation = automations.find(automation => automation.target.providerId === handoff.target.providerId + && (automation.id === handoff.automationId || automation.id === handoff.requestedAutomationId || automation.creationId === handoff.id)); + if (automation && !handoff.automationId) { + this.writeHandoff({ ...handoff, automationId: automation.id }); + } + if (handoff.automationId && (automation?.oneTimeDispatchedAt + || !automation && catalogueState === 'ready' && providers.some(provider => provider.id === handoff.target.providerId))) { + this.removeHandoff(handoff.id); + } + } + if (!handoff.target.groupId || handoff.conversation || handoff.groupApplied) { + continue; + } + const automation = automations.find(automation => automation.id === handoff.automationId && automation.oneTimeDispatchedAt); + const resource = runs.find(run => run.id === automation?.oneTimeRunId)?.sessionResource; + const session = resource && sessionsManagementService.getSession(resource); + if (session) { + if (groupsService.getGroup(handoff.target.groupId) && !groupsService.getGroupOfSession(session.sessionId)) { + groupsService.addToGroup(session.sessionId, handoff.target.groupId); + } + this.writeHandoff({ ...handoff, groupApplied: true }); + } + } + })); + this.items = derived(this, reader => { + if (!this.enabled.read(reader)) { + return []; + } + const runs = automationService.runs.read(reader); + handoffsChanged.read(reader); + const automations = automationService.automations.read(reader); + const handoffs = this.readHandoffs(); + const editing = this.editingRequest.read(reader); + const items = automationService.automations.read(reader) + .filter(automation => automation.purpose === 'scheduledChat' && (!automation.oneTimeDispatchedAt || editing?.id === automation.id)) + .sort((a, b) => (a.schedule.runAt ?? '').localeCompare(b.schedule.runAt ?? '')) + .map((automation): IScheduledChatItem => { + const handoff = handoffs.find(handoff => handoff.id === automation.creationId); + const conversation = automation.conversation ?? handoff?.conversation; + const requestEditing = editing?.id === automation.id ? editing.state : undefined; + const editAction = toAction({ + id: 'sessions.scheduled.edit', + label: conversation ? localize('scheduledChat.editMessage', "Edit") : localize('scheduledChat.edit', "Edit as Draft"), + class: ThemeIcon.asClassName(Codicon.edit), + enabled: !automation.readOnlyReason && (!automation.oneTimeRunId || !conversation && !!automation.oneTimeDispatchRejectedAt), + run: () => conversation ? this.startEditing(automation) : this.cancel(automation, true), + }); + return { + pendingSession: true, id: automation.id, kind: 'scheduled', + title: automation.name, + text: automation.request?.text ?? automation.prompt, + attachments: automation.request?.attachments?.map(attachment => attachment.label) ?? [], + conversation, + description: automation.readOnlyReason ?? (automation.oneTimeRunId + ? runs.find(run => run.id === automation.oneTimeRunId)?.errorMessage ?? localize('scheduledChat.startedOrFailed', "Starting or needs attention") + : automation.enabled ? localize('scheduledChat.at', "Scheduled for {0}", formatTime(automation.schedule.runAt)) : localize('scheduledChat.cancelled', "Not scheduled")), + folderUri: automation.target.kind === 'workspace' ? automation.target.folderUri : undefined, + providerId: automation.target.providerId, + sessionType: automation.target.sessionTypeId, + environmentId: handoff?.target.environmentId, + harness: handoff?.target.harness, + applicationId: handoff?.target.applicationId, + isQuickChat: automation.target.kind === 'quickChat', + open: async () => { if (conversation) { this.startEditing(automation); } else { await this.cancel(automation, true); } }, + editAction: conversation ? editAction : undefined, + editing: requestEditing, + actions: requestEditing ? [ + toAction({ id: 'sessions.scheduled.save', label: localize('scheduledChat.save', "Save"), class: ThemeIcon.asClassName(Codicon.check), run: () => requestEditing.save() }), + requestEditing.selectTime, + toAction({ id: 'sessions.scheduled.cancelEdit', label: localize('scheduledChat.cancelEdit', "Cancel Edit"), class: ThemeIcon.asClassName(Codicon.closeSmall), run: () => requestEditing.cancel() }), + ] : [ + ...(conversation ? [editAction] : [toAction({ id: 'sessions.scheduled.preview', label: localize('scheduledChat.preview', "Preview"), run: () => this.preview(automation) })]), + toAction({ id: 'sessions.scheduled.sendNow', label: localize('scheduledChat.sendNow', "Send Now"), class: ThemeIcon.asClassName(Codicon.newLine), enabled: !automation.readOnlyReason && !automation.oneTimeRunId && automationService.canRunAutomation(automation.id), run: () => this.sendNow(automation) }), + toAction({ id: 'sessions.scheduled.reschedule', label: localize('scheduledChat.reschedule', "Reschedule..."), class: ThemeIcon.asClassName(Codicon.clock), enabled: !automation.readOnlyReason && !automation.oneTimeRunId, run: (anchor?: HTMLElement) => this.reschedule(automation, isHTMLElement(anchor) ? anchor : undefined) }), + ...(conversation ? [] : [editAction]), + toAction({ id: 'sessions.scheduled.cancel', label: localize('scheduledChat.cancel', "Cancel Schedule"), class: ThemeIcon.asClassName(Codicon.closeSmall), enabled: !automation.readOnlyReason && (!automation.oneTimeRunId || !!automation.oneTimeDispatchRejectedAt), run: () => this.cancel(automation, false) }), + ], + }; + }); + for (const handoff of handoffs) { + if (handoff.automationId || automations.some(automation => automation.creationId === handoff.id && automation.target.providerId === handoff.target.providerId)) { + continue; + } + items.push({ + pendingSession: true, id: `handoff:${handoff.id}`, kind: 'scheduled', + title: handoff.input.inputText.trim().split('\n')[0] || localize('sendLater.attachmentTitle', "Scheduled Request"), + text: handoff.input.inputText, + attachments: handoff.request.attachments?.map(attachment => attachment.label) ?? [], + conversation: handoff.conversation, + description: localize('sendLater.confirming', "Scheduling outcome not yet confirmed"), + folderUri: handoff.target.folderUri, providerId: handoff.target.providerId, sessionType: handoff.target.sessionTypeId, isQuickChat: !handoff.target.folderUri, + environmentId: handoff.target.environmentId, harness: handoff.target.harness, applicationId: handoff.target.applicationId, + open: async () => { await this.retryHandoff(handoff); }, + actions: [toAction({ id: 'sessions.scheduled.reconcile', label: localize('sendLater.reconcile', "Reconcile Schedule"), class: ThemeIcon.asClassName(Codicon.sync), run: async () => { await this.retryHandoff(handoff); } })], + }); + } + return items; + }); + } + + canSchedule(session: ISession | undefined, conversation?: IAutomationDescriptor['conversation']): boolean { + return !!session && this.enabled.get() && !this.entitlementService.sentiment.hidden + && this.automationsEnabled.get() + && this.availableProviders.get().some(provider => provider.id === session.providerId && provider.supportsOneTimeAutomation && (!conversation || provider.supportsExistingChatAutomation)) + && this.automationService.canCreateAutomation(session.providerId); + } + + registerChatInput(widget: IChatWidget, session: IObservable<ISession | undefined>, chatResource: IObservable<URI | undefined>, canSend: IObservable<boolean>): IDisposable { + const store = new DisposableStore(); + const modelChanged = observableSignalFromEvent(this, widget.onDidChangeViewModel); + store.add(autorun(reader => { + modelChanged.read(reader); + const currentSession = session.read(reader); + const resource = chatResource.read(reader); + const requests = this.items.read(reader).filter(item => item.conversation + && isEqual(item.conversation.sessionResource, currentSession?.resource) + && isEqual(item.conversation.chatResource, resource)); + widget.viewModel?.setScheduledRequests(requests); + })); + store.add(toDisposable(() => widget.viewModel?.setScheduledRequests([]))); + const busy = observableValue(this, false); + let compositionId = generateUuid(); + const available = derived(this, reader => { + this.enabled.read(reader); + this.automationsEnabled.read(reader); + this.availableProviders.read(reader); + const currentSession = session.read(reader); + const resource = chatResource.read(reader); + const chat = currentSession?.chats.read(reader).find(chat => isEqual(chat.resource, resource)); + return !!currentSession && !!chat && canSend.read(reader) + && !this.items.read(reader).some(item => item.editing && isEqual(item.conversation?.chatResource, resource)) + && currentSession.status.read(reader) !== SessionStatus.Untitled + && !currentSession.isArchived.read(reader) && !chat.isArchived.read(reader) + && chat.interactivity.read(reader) === ChatInteractivity.Full + && this.canSchedule(currentSession, { sessionResource: currentSession.resource, chatResource: chat.resource }); + }); + const key = ChatInputCanScheduleContext.bindTo(widget.scopedContextKeyService); + store.add(autorun(reader => key.set(available.read(reader)))); + const registration = { + schedule: async () => { + const currentSession = session.get(); + const resource = chatResource.get(); + const model = widget.viewModel?.model; + if (busy.get() || !available.get() || !currentSession || !resource || !model || widget.viewModel?.editing) { + throw new Error(localize('sendLater.chatUnavailable', "Send Later is not available for this conversation.")); + } + const input = captureChatInput(widget); + if (!hasSessionDraftContent(input)) { + throw new Error(localize('sendLater.empty', "Enter a request before choosing Send Later.")); + } + const state = model.inputModel.state.get(); + const conversation = { sessionResource: currentSession.resource, chatResource: resource }; + const target: ISavedSessionDraftTarget = { + providerId: currentSession.providerId, sessionTypeId: currentSession.sessionType, + folderUri: currentSession.isQuickChat?.get() ? undefined : currentSession.workspace.get()?.folders[0]?.root, + environmentId: currentSession.environment, harness: currentSession.harness, applicationId: currentSession.application.get().id, + }; + busy.set(true, undefined); + widget.input.setInputEnabled(false); + try { + if (await this.schedule(input, target, currentSession, compositionId, conversation, widget.input.executeToolbarElement)) { + if (widget.viewModel?.model === model && stringify(toStoredChatDraft(captureChatInput(widget))) === stringify(toStoredChatDraft(input))) { + widget.setInput(''); + widget.attachmentModel.clearAndSetContext(); + } + const latestState = model.inputModel.state.get(); + if (latestState === state || latestState?.inputText === input.inputText + && stringify(latestState.attachments) === stringify(input.attachments) + && stringify(latestState.contrib?.[ChatDynamicVariableModel.ID] ?? []) === stringify(input.references ?? [])) { + model.inputModel.setState({ inputText: '', attachments: [], contrib: { ...state?.contrib, [ChatDynamicVariableModel.ID]: [] } }); + } + for (const handoff of this.readHandoffs()) { + if (handoff.automationId && !handoff.sourceReleased + && isEqual(handoff.conversation?.sessionResource, conversation.sessionResource) + && isEqual(handoff.conversation?.chatResource, conversation.chatResource) + && stringify(toStoredChatDraft(handoff.input)) === stringify(toStoredChatDraft(input))) { + this.writeHandoff({ ...handoff, sourceReleased: true }); + } + } + compositionId = generateUuid(); + } + } finally { + busy.set(false, undefined); + if (this.chatInputs.get(widget) === registration && widget.viewModel?.model === model) { + widget.input.setInputEnabled(canSend.get(), true); + } + } + }, + assertUnscheduled: (query: string) => { + if (query !== widget.getInput()) { + return; + } + const currentSession = session.get(); + const resource = chatResource.get(); + if (busy.get() || currentSession && resource && this.readHandoffs().some(handoff => + !handoff.recoverySaved && !handoff.sourceReleased && isEqual(handoff.conversation?.sessionResource, currentSession.resource) + && isEqual(handoff.conversation?.chatResource, resource) + && stringify(toStoredChatDraft(handoff.input)) === stringify(toStoredChatDraft(captureChatInput(widget))))) { + throw new Error(localize('sendLater.chatHandedOff', "This request is being scheduled. Reconcile or cancel it in this chat or Automations before sending it again.")); + } + }, + }; + this.chatInputs.set(widget, registration); + store.add(toDisposable(() => { this.chatInputs.delete(widget); key.reset(); })); + return store; + } + + async scheduleChatInput(widget: IChatWidget): Promise<void> { + const registration = this.chatInputs.get(widget); + if (!registration) { + throw new Error(localize('sendLater.noChatInput', "Send Later is not available in this chat input.")); + } + await registration.schedule(); + } + + assertChatInputUnscheduled(widget: IChatWidget, query: string): void { + this.chatInputs.get(widget)?.assertUnscheduled(query); + } + + private assertEnabled(): void { + if (!this.enabled.get() || this.entitlementService.sentiment.hidden) { + throw new Error(localize('sendLater.disabled', "Send Later is disabled. Manage existing scheduled requests in Automations.")); + } + } + + private readHandoffs(): IScheduledChatHandoff[] { + const raw = this.storageService.get(handoffStorageKey, StorageScope.PROFILE); + if (!raw) { + return []; + } + const value: { version?: number; handoffs?: IScheduledChatHandoff[] } = parse(raw); + if (value.version !== 1 || !Array.isArray(value.handoffs)) { + throw new Error(localize('sendLater.invalidStorage', "The saved scheduling handoff could not be read. Its stored content has not been changed.")); + } + return value.handoffs.map(handoff => ({ ...handoff, input: fromStoredChatDraft(handoff.input) })); + } + + private writeHandoff(handoff: IScheduledChatHandoff): void { + const handoffs = this.readHandoffs().filter(candidate => candidate.id !== handoff.id); + this.storageService.store(handoffStorageKey, stringify({ + version: 1, + handoffs: [...handoffs, handoff].map(value => ({ ...value, input: toStoredChatDraft(value.input) })), + }), StorageScope.PROFILE, StorageTarget.MACHINE); + } + + private removeHandoff(id: string): void { + const handoffs = this.readHandoffs(); + const handoff = handoffs.find(handoff => handoff.id === id); + if (handoff?.toolOperationId && handoff.automationId) { + const receipts = this.readReceipts().filter(receipt => receipt.operationId !== handoff.toolOperationId); + this.storageService.store(receiptStorageKey, stringify({ + version: 1, receipts: [...receipts, { operationId: handoff.toolOperationId, automationId: handoff.automationId }], + }), StorageScope.PROFILE, StorageTarget.MACHINE); + } + this.storageService.store(handoffStorageKey, stringify({ + version: 1, handoffs: handoffs.filter(handoff => handoff.id !== id).map(handoff => ({ ...handoff, input: toStoredChatDraft(handoff.input) })), + }), StorageScope.PROFILE, StorageTarget.MACHINE); + } + + private readReceipts(): IScheduledChatReceipt[] { + const raw = this.storageService.get(receiptStorageKey, StorageScope.PROFILE); + if (!raw) { + return []; + } + const value: { version?: number; receipts?: IScheduledChatReceipt[] } = parse(raw); + if (value.version !== 1 || !Array.isArray(value.receipts)) { + throw new Error(localize('sendLater.invalidReceipts', "The saved scheduling receipts could not be read. Their stored content has not been changed.")); + } + return value.receipts; + } + + hasRequest(operationId: string): boolean { + return this.readHandoffs().some(handoff => handoff.toolOperationId === operationId) + || this.readReceipts().some(receipt => receipt.operationId === operationId); + } + + private async acceptedRequest(automationId: string): Promise<ScheduledChatSubmission> { + await this.automationService.refresh?.(); + const automation = this.automationService.getAutomation(automationId); + if (!automation) { + throw new AutomationUnavailableError(localize('sendLater.previousRequestUnavailable', "This request was already accepted. Its definition is no longer available; it will not be recreated.")); + } + return { status: 'accepted', automation }; + } + + hasPendingHandoff(compositionId: string, input: IChatDraft): boolean { + const serialized = stringify(toStoredChatDraft(input)); + return this.readHandoffs().some(handoff => !handoff.toolOperationId && !handoff.conversation && !handoff.automationId && (handoff.compositionId === compositionId || stringify(toStoredChatDraft(handoff.input)) === serialized)); + } + + assertUnscheduled(compositionId: string, input: IChatDraft): void { + if (this.hasPendingHandoff(compositionId, input) || this.readHandoffs().some(handoff => handoff.compositionId === compositionId)) { + throw new Error(localize('sendLater.alreadyHandedOff', "This request has a scheduling handoff. Reconcile or cancel it in the sessions list or Automations before sending it again.")); + } + } + + releaseSource(compositionId: string): void { + for (const handoff of this.readHandoffs()) { + if (handoff.compositionId === compositionId && handoff.automationId && !handoff.sourceReleased) { + this.writeHandoff({ ...handoff, sourceReleased: true }); + } + } + } + + async schedule(input: IChatDraft, target: ISavedSessionDraftTarget, session: ISession, compositionId: string, conversation?: IAutomationDescriptor['conversation'], anchor?: HTMLElement): Promise<boolean> { + this.assertEnabled(); + if (!this.canSchedule(session, conversation) || target.requireDevContainer) { + throw new Error(localize('sendLater.unavailable', "Send Later requires a supported local agent host with Automations enabled.")); + } + const previous = this.readHandoffs().find(handoff => !handoff.toolOperationId && !handoff.sourceReleased && !handoff.recoverySaved + && isEqual(handoff.conversation?.sessionResource, conversation?.sessionResource) && isEqual(handoff.conversation?.chatResource, conversation?.chatResource) + && stringify(handoff.sourceTarget ?? handoff.target) === stringify(target) + && (handoff.compositionId === compositionId || stringify(toStoredChatDraft(handoff.input)) === stringify(toStoredChatDraft(input)))); + if (previous) { + if (!previous.automationId) { + await this.retryHandoff(previous); + } + return true; + } + const date = await this.pickTime(anchor); + if (!date) { + return false; + } + const capturedConfiguration = conversation ? undefined : await this.sessionsManagementService.getAutomationSessionConfiguration(session); + if (!conversation && !capturedConfiguration) { + throw new Error(localize('sendLater.configurationUnavailable', "The agent configuration is not ready. Your input has been kept.")); + } + const configuration = conversation ? undefined : { ...target.configuration, ...capturedConfiguration }; + const capturedInput = fromStoredChatDraft(parse(stringify(toStoredChatDraft(input)))); + const request = await this.captureRequest(capturedInput); + const schedule: IAutomationSchedule = { interval: 'once', runAt: date.toISOString(), scheduleHour: 0, scheduleMinute: 0, scheduleDay: 0 }; + const automationTarget: AutomationTarget = target.folderUri + ? { + kind: 'workspace', folderUri: target.folderUri, providerId: session.providerId, sessionTypeId: session.sessionType, + isolation: configuration?.isolationMode === 'worktree' + ? { kind: 'worktree', branch: configuration.branch ?? '' } + : configuration?.isolationMode === 'workspace' ? { kind: 'folder' } : { kind: 'default' }, + } + : { kind: 'quickChat', providerId: session.providerId, sessionTypeId: session.sessionType }; + const handoff: IScheduledChatHandoff = { id: generateUuid(), compositionId, input: capturedInput, sourceTarget: target, target: { ...target, configuration }, request, automationTarget, schedule, conversation }; + this.writeHandoff(handoff); + await this.submitHandoff(handoff, false); + return true; + } + + scheduleRequest(options: IScheduledChatRequestOptions, operationId: string, mutationGuard?: AutomationMutationGuard, captureTemplate?: () => Promise<IScheduledChatRequestOptions['sessionTemplate']>): Promise<ScheduledChatSubmission> { + return this.toolRequests.queue(operationId, async () => { + this.assertEnabled(); + mutationGuard?.(); + const runAt = validateAutomationRunAt(options.schedule.runAt); + if (options.schedule.interval !== 'once' || !options.prompt.trim() || !operationId) { + throw new Error(localize('sendLater.invalidRequest', "Scheduling requires a one-time request and a stable operation identity.")); + } + let handoff = this.readHandoffs().find(candidate => candidate.toolOperationId === operationId); + const retry = !!handoff; + if (handoff) { + if (handoff.name !== options.name || handoff.request.text !== options.prompt || handoff.schedule.runAt !== runAt + || !captureTemplate && stableStringify(handoff.target.configuration?.sessionTemplate) !== stableStringify(options.sessionTemplate) + || !equalScheduledTargets(handoff.automationTarget, options.target) + || !isEqual(handoff.conversation?.sessionResource, options.conversation?.sessionResource) + || !isEqual(handoff.conversation?.chatResource, options.conversation?.chatResource)) { + throw new Error(localize('sendLater.changedOperation', "This scheduling operation already has a different saved request. Reconcile it before scheduling another request.")); + } + if (handoff.automationId) { + return this.acceptedRequest(handoff.automationId); + } + } else { + const receipt = this.readReceipts().find(receipt => receipt.operationId === operationId); + if (receipt) { + return this.acceptedRequest(receipt.automationId); + } + if (Date.parse(runAt) <= Date.now()) { + throw new AutomationUnavailableError(localize('sendLater.timePassed', "Choose a future send time.")); + } + if (captureTemplate) { + options = { ...options, sessionTemplate: await captureTemplate() }; + } + mutationGuard?.(); + const target: ISavedSessionDraftTarget = { + providerId: options.target.providerId, + sessionTypeId: options.target.sessionTypeId, + ...(options.target.kind === 'workspace' ? { folderUri: options.target.folderUri } : {}), + configuration: options.conversation ? undefined : { + sessionTemplate: options.sessionTemplate, + ...(options.target.kind === 'workspace' ? { + isolationMode: options.target.isolation.kind === 'worktree' ? 'worktree' : options.target.isolation.kind === 'folder' ? 'workspace' : undefined, + branch: options.target.isolation.kind === 'worktree' ? options.target.isolation.branch : undefined, + } : {}), + }, + }; + handoff = { + id: generateUuid(), toolOperationId: operationId, name: options.name, compositionId: operationId, + input: { inputText: options.prompt, attachments: [] }, sourceReleased: true, + target, automationTarget: options.target, conversation: options.conversation, + request: { text: options.prompt, origin: { kind: MessageKind.User } }, + schedule: { interval: 'once', runAt, scheduleHour: 0, scheduleMinute: 0, scheduleDay: 0 }, + }; + this.writeHandoff(handoff); + } + let dispatchAuthorized = false; + const guard = () => { + mutationGuard?.(); + dispatchAuthorized = true; + }; + try { + const automation = retry ? await this.retryHandoff(handoff, guard) : await this.submitHandoff(handoff, false, guard); + return { status: 'accepted', automation }; + } catch (error) { + const saved = this.readHandoffs().find(candidate => candidate.id === handoff.id); + const receipt = !saved && this.readReceipts().find(receipt => receipt.operationId === operationId); + if (receipt) { + return this.acceptedRequest(receipt.automationId); + } + if (!retry && !dispatchAuthorized) { + this.removeHandoff(handoff.id); + throw error; + } + if (saved?.automationId) { + return this.acceptedRequest(saved.automationId); + } + return { status: 'unknown', pending: this.toPendingRequest(saved ?? handoff), message: error instanceof Error ? error.message : String(error) }; + } + }); + } + + getPendingRequests(): readonly IPendingScheduledChatRequest[] { + return this.readHandoffs().filter(handoff => handoff.toolOperationId && !handoff.automationId) + .map(handoff => this.toPendingRequest(handoff)); + } + + private toPendingRequest(handoff: IScheduledChatHandoff): IPendingScheduledChatRequest { + return { + handoffId: handoff.id, automationId: handoff.requestedAutomationId, providerId: handoff.target.providerId, + name: handoff.name ?? handoff.input.inputText, prompt: handoff.request.text, + runAt: handoff.schedule.runAt!, conversation: handoff.conversation, + }; + } + + async updateRequest(automation: IAutomationDescriptor, patch: IUpdateAutomationOptions, mutationGuard?: AutomationMutationGuard): Promise<IGuardedAutomationUpdateResult> { + const result = await this.automationService.updateAutomationIfUnchanged(automation.id, patch, automation, mutationGuard); + if (result.kind === 'updated') { + const handoff = this.readHandoffs().find(candidate => candidate.automationId === automation.id || candidate.id === automation.creationId); + if (handoff) { + this.writeHandoff({ + ...handoff, name: result.automation.name, schedule: result.automation.schedule, + request: result.automation.request ?? handoff.request, + input: { ...handoff.input, inputText: result.automation.prompt }, + }); + } + } + return result; + } + + private captureRequest(input: IChatDraft): Promise<Message> { + return captureScheduledChatRequest(input, async (uri, range) => { + const reference = await this.textModelService.createModelReference(uri); + try { + return range ? reference.object.textEditorModel.getValueInRange(range) : reference.object.textEditorModel.getValue(); + } finally { + reference.dispose(); + } + }, async uri => (await this.fileService.readFile(uri)).value, uri => this.workingCopyService.isDirty(uri)); + } + + private async retryHandoff(handoff: IScheduledChatHandoff, mutationGuard?: AutomationMutationGuard): Promise<IAutomationDescriptor> { + this.assertEnabled(); + mutationGuard?.(); + await this.automationService.refresh?.(); + const existing = this.automationService.automations.get().find(automation => + (automation.id === handoff.requestedAutomationId || automation.creationId === handoff.id) && + automation.target.providerId === handoff.target.providerId); + if (existing) { + this.writeHandoff({ ...handoff, automationId: existing.id }); + status(localize('sendLater.reconciled', "The agent host has accepted this scheduled request.")); + return existing; + } + return this.submitHandoff(handoff, true, mutationGuard); + } + + private async submitHandoff(handoff: IScheduledChatHandoff, retry: boolean, mutationGuard?: AutomationMutationGuard): Promise<IAutomationDescriptor> { + const guard = () => { + this.assertEnabled(); + if (!this.automationsEnabled.get() || !this.automationService.canCreateAutomation(handoff.target.providerId) || !this.availableProviders.get().some(provider => provider.id === handoff.target.providerId && provider.supportsOneTimeAutomation && (!handoff.conversation || provider.supportsExistingChatAutomation)) + || (!retry && Date.parse(handoff.schedule.runAt!) <= Date.now())) { + throw new AutomationUnavailableError(localize('sendLater.noLongerAvailable', "The scheduled time has passed or Send Later is no longer available. Your input has been kept.")); + } + mutationGuard?.(); + }; + const automation = await this.automationService.createAutomation({ + creationId: handoff.id, + onWillCreate: id => { + handoff = { ...handoff, requestedAutomationId: id }; + this.writeHandoff(handoff); + }, + name: handoff.name ?? (handoff.input.inputText.trim().split('\n')[0].slice(0, 100) || localize('sendLater.attachmentTitle', "Scheduled Request")), + prompt: handoff.request.text, + purpose: 'scheduledChat', + request: handoff.request, + conversation: handoff.conversation, + schedule: handoff.schedule, target: handoff.automationTarget, + sessionTemplate: handoff.target.configuration?.sessionTemplate, + enabled: true, + }, guard); + this.writeHandoff({ ...handoff, automationId: automation.id }); + status(localize('sendLater.saved', "Request scheduled for {0}", formatTime(handoff.schedule.runAt))); + return automation; + } + + private async pickTime(anchor?: HTMLElement): Promise<Date | undefined> { + return pickScheduledChatTime(this.quickInputService, anchor); + } + + private async preview(automation: IAutomationDescriptor): Promise<void> { + this.assertEnabled(); + await this.dialogService.prompt({ + message: automation.name, + detail: [ + localize('scheduledChat.previewTime', "Scheduled: {0}", formatTime(automation.schedule.runAt)), + localize('scheduledChat.previewTarget', "Target: {0}", automation.target.kind === 'workspace' ? basename(automation.target.folderUri) : localize('scheduledChat.noWorkspace', "No Workspace")), + localize('scheduledChat.previewModel', "Model: {0}", automation.sessionTemplate?.modelId ?? localize('scheduledChat.defaultModel', "Provider Default")), + localize('scheduledChat.previewAttachments', "Attachments: {0}", automation.request?.attachments?.map(attachment => attachment.label).join(', ') || localize('scheduledChat.noAttachments', "None")), + '', automation.prompt, + ].join('\n'), + buttons: [], + cancelButton: localize('scheduledChat.close', "Close"), + }); + } + + private async sendNow(automation: IAutomationDescriptor): Promise<void> { + this.assertEnabled(); + this.assertWritable(automation); + await this.automationService.runAutomation(automation.id); + } + + private async reschedule(automation: IAutomationDescriptor, anchor?: HTMLElement): Promise<void> { + this.assertEnabled(); + this.assertWritable(automation); + const date = await this.pickTime(anchor); + if (!date) { + return; + } + const result = await this.automationService.updateAutomationIfUnchanged(automation.id, { schedule: { ...automation.schedule, runAt: date.toISOString() } }, automation, () => this.assertEnabled()); + if (result.kind !== 'updated') { + throw new Error(localize('scheduledChat.changed', "The scheduled request changed or has started. Refresh the scheduled messages before trying again.")); + } + status(localize('scheduledChat.rescheduled', "Request rescheduled for {0}", formatTime(date.toISOString()))); + } + + private startEditing(automation: IAutomationDescriptor): void { + this.assertEnabled(); + this.assertWritable(automation); + const current = this.editingRequest.get(); + if (current?.id === automation.id) { + return; + } + if (current && this.automationService.automations.get().some(item => item.id === current.id && !item.oneTimeDispatchedAt)) { + throw new Error(localize('scheduledChat.finishEditing', "Save or cancel your other scheduled-message edit first.")); + } + if (automation.oneTimeRunId) { + throw new Error(localize('scheduledChat.changed', "The scheduled request changed or has started. Refresh the scheduled messages before trying again.")); + } + if ([...this.chatInputs.keys()].some(widget => widget.viewModel?.editing && isEqual(widget.viewModel.sessionResource, automation.conversation?.chatResource))) { + throw new Error(localize('scheduledChat.finishRequestEditing', "Save or cancel your other message edit first.")); + } + const handoff = this.readHandoffs().find(candidate => candidate.automationId === automation.id || candidate.id === automation.creationId); + const saving = observableValue(this, false); + const state: IChatScheduledRequestEditing = { + isSaving: saving, + text: automation.request?.text ?? automation.prompt, + input: handoff && fromStoredChatDraft(parse(stringify(toStoredChatDraft(handoff.input)))), + retainedAttachments: handoff ? [] : automation.request?.attachments?.map(attachment => attachment.label), + runAt: automation.schedule.runAt ?? '', + description: formatTime(automation.schedule.runAt), + selectTime: toAction({ + id: 'sessions.scheduled.editTime', label: localize('scheduledChat.editTime', "Change Send Time..."), class: ThemeIcon.asClassName(Codicon.clock), run: async (anchor?: HTMLElement) => { + const date = await this.pickTime(isHTMLElement(anchor) ? anchor : undefined); + if (date && this.editingRequest.get()?.state === state) { + state.runAt = date.toISOString(); + state.description = formatTime(state.runAt); + this.editingRequest.set({ id: automation.id, state }, undefined); + } + } + }), + save: async () => { + if (saving.get()) { + return; + } + saving.set(true, undefined); + try { + await this.saveEditedRequest(automation, state); + } finally { + saving.set(false, undefined); + } + }, + cancel: () => { + if (!saving.get() && this.editingRequest.get()?.state === state) { + this.editingRequest.set(undefined, undefined); + } + }, + }; + this.editingRequest.set({ id: automation.id, state }, undefined); + } + + private async saveEditedRequest(automation: IAutomationDescriptor, state: IChatScheduledRequestEditing): Promise<void> { + this.assertEnabled(); + this.assertWritable(automation); + if (this.editingRequest.get()?.state !== state) { + throw new Error(localize('scheduledChat.editClosed', "This scheduled-message edit is no longer open.")); + } + const text = state.text; + const schedule = { ...automation.schedule, runAt: state.runAt }; + if (!(Date.parse(schedule.runAt) > Date.now())) { + throw new Error(localize('scheduledChat.editTimePassed', "Choose a future send time before saving.")); + } + const handoff = this.readHandoffs().find(candidate => candidate.automationId === automation.id || candidate.id === automation.creationId); + const original = automation.request ?? handoff?.request; + if (!original) { + throw new Error(localize('scheduledChat.editUnavailable', "The saved request content is unavailable. Manage this request in Automations.")); + } + const textChanged = text !== original.text; + const input = state.input && fromStoredChatDraft(parse(stringify(toStoredChatDraft(state.input)))); + const retained = original.attachments?.map(attachment => textChanged ? { ...attachment, range: undefined } : attachment); + const attachments = input ? [ + ...(!handoff ? retained ?? [] : []), + ...await Promise.all(input.attachments.map(async entry => { + const originalIndex = handoff?.input.attachments.findIndex(attachment => attachment.id === entry.id) ?? -1; + if (originalIndex >= 0 && retained?.[originalIndex]) { + return retained[originalIndex]; + } + const captured = await this.captureRequest({ ...input, inputText: text, attachments: [entry] }); + return captured.attachments![0]; + })), + ] : retained; + if (!text.trim() && !attachments?.length) { + throw new Error(localize('scheduledChat.emptyEdit', "Enter a message or keep an attachment before saving.")); + } + const request = { ...original, text, attachments }; + const result = await this.automationService.updateAutomationIfUnchanged(automation.id, { + name: text.trim().split('\n')[0].slice(0, 100) || automation.name, + prompt: text, request, schedule, + }, automation, () => { + this.assertEnabled(); + if (this.editingRequest.get()?.state !== state || !(Date.parse(schedule.runAt) > Date.now())) { + throw new Error(localize('scheduledChat.editTimePassed', "Choose a future send time before saving.")); + } + }); + if (result.kind !== 'updated') { + throw new Error(localize('scheduledChat.changed', "The scheduled request changed or has started. Refresh the scheduled messages before trying again.")); + } + if (handoff) { + const recovery = input ?? handoff.input; + this.writeHandoff({ + ...handoff, request, schedule, + input: { + ...recovery, inputText: text, + attachments: textChanged ? recovery.attachments.map(attachment => ({ ...attachment, range: undefined })) : recovery.attachments, + references: textChanged ? [] : recovery.references, + }, + }); + } + if (this.editingRequest.get()?.state === state) { + this.editingRequest.set(undefined, undefined); + } + status(localize('scheduledChat.edited', "Scheduled message saved for {0}", formatTime(schedule.runAt))); + } + + private async cancel(automation: IAutomationDescriptor, edit: boolean): Promise<void> { + this.assertEnabled(); + this.assertWritable(automation); + const handoff = this.readHandoffs().find(candidate => candidate.automationId === automation.id || candidate.id === automation.creationId); + if (!handoff) { + throw new Error(localize('scheduledChat.recoveryUnavailable', "The original composition is unavailable on this device. Manage this request in Automations.")); + } + // The recovery copy is durable before cancellation; an uncertain result never becomes a sendable draft. + this.writeHandoff({ ...handoff, automationId: automation.id }); + if (automation.oneTimeRunId && !automation.oneTimeDispatchRejectedAt) { + throw new AutomationMutationUncertainError(localize('scheduledChat.cancellationLost', "The scheduled request changed or has started. Its content is retained; check Automations before sending it again.")); + } + if (automation.enabled && !automation.oneTimeDispatchRejectedAt) { + const result = await this.automationService.updateAutomationIfUnchanged(automation.id, { enabled: false }, automation, () => this.assertEnabled()); + if (result.kind !== 'updated' || result.automation.oneTimeRunId) { + throw new AutomationMutationUncertainError(localize('scheduledChat.cancellationLost', "The scheduled request changed or has started. Its content is retained; check Automations before sending it again.")); + } + } + if (handoff.conversation) { + const session = this.sessionsManagementService.getSession(handoff.conversation.sessionResource); + if (!session) { + throw new Error(localize('scheduledChat.conversationUnavailable', "The schedule is cancelled and its content is retained. Open the original conversation before recovering it.")); + } + const reference = await this.chatService.acquireOrLoadSession(handoff.conversation.chatResource, ChatAgentLocation.Chat, CancellationToken.None, 'scheduledChatRecovery'); + if (!reference) { + throw new Error(localize('scheduledChat.chatUnavailable', "The original chat could not be loaded. The cancelled request is retained.")); + } + try { + const state = reference.object.inputModel.state.get(); + if (!handoff.recoverySaved) { + if (state?.inputText.trim() || state?.attachments.length) { + throw new Error(localize('scheduledChat.chatOccupied', "The schedule is cancelled and its content is retained. Clear the original chat input before recovering this request.")); + } + reference.object.inputModel.setState({ inputText: handoff.input.inputText, attachments: handoff.input.attachments, contrib: { ...state?.contrib, [ChatDynamicVariableModel.ID]: handoff.input.references ?? [] } }); + this.writeHandoff({ ...handoff, recoverySaved: true }); + } + await this.automationService.deleteAutomation(automation.id); + this.removeHandoff(handoff.id); + if (edit) { + await this.sessionsService.openChat(session, handoff.conversation.chatResource); + } + } finally { + reference.dispose(); + } + } else if (this.draftsService.enabled.get()) { + if (!handoff.recoverySaved) { + this.draftsService.save(handoff.input, handoff.target, handoff.id); + this.writeHandoff({ ...handoff, recoverySaved: true }); + } + await this.automationService.deleteAutomation(automation.id); + this.removeHandoff(handoff.id); + if (edit) { + await this.draftsService.open(handoff.id, { removeFromDrafts: true }); + } + } else { + if (!handoff.recoverySaved) { + await this.draftsService.restoreRecovery(handoff.input, handoff.target); + this.writeHandoff({ ...handoff, recoverySaved: true }); + } + await this.automationService.deleteAutomation(automation.id); + this.removeHandoff(handoff.id); + } + status(localize('scheduledChat.cancelledAnnouncement', "Schedule cancelled. The request content has been kept.")); + } + + private assertWritable(automation: IAutomationDescriptor): void { + if (automation.readOnlyReason) { + throw new Error(automation.readOnlyReason); + } + } +} + +function captureChatInput(widget: IChatWidget): IChatDraft { + return fromStoredChatDraft(parse(stringify(toStoredChatDraft({ + inputText: widget.getInput(), + attachments: widget.input.getAttachedContext().asArray(), + references: [...getDynamicVariablesForWidget(widget)], + })))); +} + +function equalScheduledTargets(a: AutomationTarget, b: AutomationTarget): boolean { + return a.kind === b.kind && a.providerId === b.providerId && a.sessionTypeId === b.sessionTypeId + && (a.kind === 'quickChat' || b.kind === 'workspace' && isEqual(a.folderUri, b.folderUri) && equals(a.isolation, b.isolation)); +} + +function formatTime(value: string | undefined): string { + return value ? new Date(value).toLocaleString(undefined, { timeZoneName: 'short' }) : localize('scheduledChat.timeUnavailable', "Time unavailable"); +} diff --git a/src/vs/workbench/contrib/sessions/browser/sessionActionViewItem.ts b/src/vs/workbench/contrib/sessions/browser/sessionActionViewItem.ts index d144f598fea5..daeec06e4785 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionActionViewItem.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionActionViewItem.ts @@ -5,7 +5,8 @@ import { IActionViewItemProvider } from '../../../../base/browser/ui/actionbar/actionbar.js'; import { IActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; -import { ClickAnimation } from '../../../../base/browser/ui/animations/animations.js'; +import { ClickAnimation, triggerClickAnimation } from '../../../../base/browser/ui/animations/animations.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from '../../../../platform/actions/browser/menuEntryActionViewItem.js'; import { MenuItemAction } from '../../../../platform/actions/common/actions.js'; @@ -36,6 +37,9 @@ export function getSessionArchiveActionViewItemOptions(options: IActionViewItemO /** The Mark as Done button, whose click is where {@link SESSIONS_MARK_AS_DONE_CONFETTI_SETTING} decides whether to celebrate. */ export class SessionArchiveActionViewItem extends MenuEntryActionViewItem { + private readonly _beforeActionAnimationOptions: IMenuEntryActionViewItemOptions | undefined; + private readonly _animateBeforeAction: boolean; + constructor( action: MenuItemAction, options: IMenuEntryActionViewItemOptions | undefined, @@ -47,7 +51,14 @@ export class SessionArchiveActionViewItem extends MenuEntryActionViewItem { @IContextMenuService contextMenuService: IContextMenuService, @IAccessibilityService private readonly _accessibility: IAccessibilityService, ) { + const animateBeforeAction = action.id === ARCHIVE_SESSION_COMMAND_ID; super(action, options, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, _accessibility); + this._animateBeforeAction = animateBeforeAction; + this._beforeActionAnimationOptions = animateBeforeAction ? options : undefined; + } + + protected override get onClickAnimation(): ClickAnimation | undefined { + return this._animateBeforeAction ? undefined : super.onClickAnimation; } override onClick(event: MouseEvent): Promise<void> { @@ -55,6 +66,12 @@ export class SessionArchiveActionViewItem extends MenuEntryActionViewItem { if (!this._accessibility.isMotionReduced()) { logSettingExperimentTrigger(this._telemetryService, SESSIONS_MARK_AS_DONE_CONFETTI_SETTING); } + const animation = this._beforeActionAnimationOptions?.onClickAnimation; + if (animation && this.element && !this._accessibility.isMotionReduced() && (this._beforeActionAnimationOptions?.shouldTriggerClickAnimation?.(this._context) ?? true)) { + const icon = this._menuItemAction.item.icon; + triggerClickAnimation(this.element, animation, ThemeIcon.isThemeIcon(icon) ? icon : undefined); + this._beforeActionAnimationOptions?.onDidTriggerClickAnimation?.(); + } return super.onClick(event); } } diff --git a/src/vs/workbench/contrib/sessions/browser/sessionAgentMerge.ts b/src/vs/workbench/contrib/sessions/browser/sessionAgentMerge.ts index c2662c5ba2ca..c7dbc0502a94 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionAgentMerge.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionAgentMerge.ts @@ -145,6 +145,20 @@ export function isAgentMergePullRequestIcon(icon: ThemeIcon): boolean { return icon.id === Codicon.gitPullRequestError.id || icon.id === Codicon.gitPullRequestComment.id; } +/** + * The icon of the completed state of `session`, such as of its pull request, with the blockers Agent Merge owns hidden: + * what its status icon shows once the session is done, in its row of the sessions list and wherever else its status shows. + */ +export function getSessionCompletedStateIcon(session: ISession, reader: IReader, agentMergeConfiguration: () => IObservable<ISessionAgentMergeConfiguration | undefined>): ThemeIcon | undefined { + // A provider icon is authoritative: the workspace's pull requests may belong to other chats. + const pullRequestIcon = session.completedStateIcon + ? session.completedStateIcon.read(reader) + : getHighestPriorityPullRequestIcon(getGitHubPullRequestRefs(session.workspace.read(reader)?.folders[0]?.gitRepository?.gitHubInfo.read(reader)).map(pullRequest => pullRequest.icon)); + return pullRequestIcon && isAgentMergePullRequestIcon(pullRequestIcon) + ? getAgentMergeAwarePullRequestIcon(pullRequestIcon, agentMergeConfiguration().read(reader)) + : pullRequestIcon; +} + /** * The icon of the completed state of `chat`, such as of its pull request, with the blockers Agent Merge owns hidden: what * its status icon shows once the chat is done, beside it in the sessions list and wherever else its status shows. diff --git a/src/vs/workbench/contrib/sessions/browser/sessionAttentionService.ts b/src/vs/workbench/contrib/sessions/browser/sessionAttentionService.ts new file mode 100644 index 000000000000..7a00fc3c7f3e --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionAttentionService.ts @@ -0,0 +1,525 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { cancelOnDispose, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { arrayEquals } from '../../../../base/common/equals.js'; +import { onUnexpectedError } from '../../../../base/common/errors.js'; +import { hash } from '../../../../base/common/hash.js'; +import { Disposable, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { ResourceMap } from '../../../../base/common/map.js'; +import { autorun, derived, derivedOpts, IObservable, IReader, IReaderWithStore, mapObservableArrayCached, observableSignal, observableSignalFromEvent, observableValue } from '../../../../base/common/observable.js'; +import { getComparisonKey } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { isCopilotReviewAuthor } from '../../../../platform/github/common/pullRequestFeedback.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { IChatModelReference, IChatService, IChatToolInvocation } from '../../chat/common/chatService/chatService.js'; +import { IChatSessionsService } from '../../chat/common/chatSessionsService.js'; +import { ChatAgentLocation } from '../../chat/common/constants.js'; +import { IChatModel, IChatResponseModel } from '../../chat/common/model/chatModel.js'; +import { getChatSessionType } from '../../chat/common/model/chatUri.js'; +import { IGitHubService } from './github/githubService.js'; +import { getSessionGitHubReferences } from '../common/github/sessionGitHubReferences.js'; +import { GitHubCIOverallStatus, GitHubPullRequestState } from '../common/github/types.js'; +import { getPullRequestKey } from '../common/github/utils.js'; +import { IInboxSessionAttention, InboxNotificationPriority, InboxTab, ISessionAttentionService } from '../common/sessionAttentionService.js'; +import { ISessionsManagementService } from '../common/sessionsManagement.js'; +import { IChatEntitlementService } from '../../../services/chat/common/chatEntitlementService.js'; +import { getGitHubPullRequestRefs, getSessionOwnedGitHubPullRequestRefs, IGitHubPullRequestRef, ISession, SessionStatus } from '../../../services/sessions/common/session.js'; + +const ATTENTION_START_TIME_STORAGE_KEY = 'sessions.inboxNotifications.attentionStartTime'; + +const enum AttentionKind { + NeedsInput = 'needsInput', + FailingCI = 'failingCi', + PassingCI = 'passingCi', + PullRequestMerged = 'pullRequestMerged', + ReviewComments = 'reviewComments', +} + +interface IAttentionNotification { + readonly id: string; + readonly kind: AttentionKind; + readonly priority: InboxNotificationPriority; + readonly provisionalId?: string; + readonly timestamp?: number; +} + +interface IPullRequestCandidate { + readonly ref: IGitHubPullRequestRef; + readonly identity: string; + readonly timestamp?: number; +} + +export class SessionAttentionService extends Disposable implements ISessionAttentionService { + declare readonly _serviceBrand: undefined; + + readonly sessionAttention: IObservable<ReadonlyMap<string, IInboxSessionAttention>>; + private readonly _attentionConsumers = observableValue(this, 0); + private readonly _trackingEnabled: IObservable<boolean>; + private readonly _attentionStartTime: IObservable<number>; + private readonly _refreshedGitHubModels = new WeakSet<object>(); + private readonly _chatLoadToken = cancelOnDispose(this._store); + private readonly _activeNeedsInputChatResources = new Set<string>(); + private readonly _needsInputChatModelRefs = new Map<string, IChatModelReference>(); + private readonly _loadingNeedsInputChatModels = new Map<string, CancellationTokenSource>(); + private readonly _unregisteredChatProviders = new Set<string>(); + private readonly _chatProvidersChanged = observableSignal(this); + private readonly _chatModelChangeSignals = new WeakMap<IChatModel, IObservable<void>>(); + private readonly _responseChangeSignals = new WeakMap<IChatResponseModel, IObservable<void>>(); + + constructor( + @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, + @IChatService private readonly chatService: IChatService, + @IGitHubService private readonly gitHubService: IGitHubService, + @IStorageService private readonly storageService: IStorageService, + @IChatEntitlementService chatEntitlementService: IChatEntitlementService, + @IChatSessionsService chatSessionsService: IChatSessionsService, + ) { + super(); + this._trackingEnabled = derived(this, reader => this._attentionConsumers.read(reader) > 0 && !chatEntitlementService.sentimentObs.read(reader).hidden); + this._attentionStartTime = this.trackAttentionStartTime(); + const sessionsChanged = observableSignalFromEvent(this, this.sessionsManagementService.onDidChangeSessions); + this._register(chatSessionsService.onDidChangeContentProviderSchemes(({ added, removed }) => { + for (const type of removed) { + this._unregisteredChatProviders.add(type); + } + for (const [resource, cts] of this._loadingNeedsInputChatModels) { + if (removed.includes(getChatSessionType(URI.parse(resource)))) { + cts.cancel(); + } + } + for (const [resource, reference] of this._needsInputChatModelRefs) { + if (removed.includes(getChatSessionType(URI.parse(resource)))) { + this._needsInputChatModelRefs.delete(resource); + reference.dispose(); + } + } + for (const type of added) { + this._unregisteredChatProviders.delete(type); + } + this._chatProvidersChanged.trigger(undefined); + })); + this._register(autorun(reader => { + if (!this._trackingEnabled.read(reader)) { + return; + } + sessionsChanged.read(reader); + for (const session of this.sessionsManagementService.getSessions()) { + this.ensureGitHubModels(session, reader); + } + })); + this._register(toDisposable(() => { + for (const reference of this._needsInputChatModelRefs.values()) { + reference.dispose(); + } + this._needsInputChatModelRefs.clear(); + this._loadingNeedsInputChatModels.clear(); + this._activeNeedsInputChatResources.clear(); + })); + this._register(autorun(reader => { + this._activeNeedsInputChatResources.clear(); + if (this._trackingEnabled.read(reader)) { + sessionsChanged.read(reader); + this._chatProvidersChanged.read(reader); + this.chatService.chatModels.read(reader); + for (const session of this.sessionsManagementService.getSessions()) { + if (!session.isArchived.read(reader) && session.status.read(reader) === SessionStatus.NeedsInput) { + for (const chat of this.getNeedsInputChats(session, reader)) { + this.ensureChatModelLoaded(chat.resource); + } + } + } + } + for (const [resource, cts] of this._loadingNeedsInputChatModels) { + if (!this._activeNeedsInputChatResources.has(resource)) { + cts.cancel(); + } + } + for (const [resource, reference] of this._needsInputChatModelRefs) { + if (!this._activeNeedsInputChatResources.has(resource)) { + this._needsInputChatModelRefs.delete(resource); + reference.dispose(); + } + } + })); + + const sessions = derived(this, reader => { + if (!this._trackingEnabled.read(reader)) { + return []; + } + sessionsChanged.read(reader); + return this.sessionsManagementService.getSessions(); + }); + const pullRequestsBySession = derived(this, reader => { + const assignments = new ResourceMap<string[]>(getComparisonKey); + for (const [key, session] of this.getPullRequestNotificationSessions(sessions.read(reader), reader)) { + const keys = assignments.get(session.resource); + if (keys) { + keys.push(key); + } else { + assignments.set(session.resource, [key]); + } + } + return assignments; + }); + const entries = mapObservableArrayCached(this, sessions, session => { + const assignedPullRequests = derivedOpts<readonly string[]>({ owner: this, equalsFn: arrayEquals }, reader => + pullRequestsBySession.read(reader).get(session.resource) ?? []); + const attention = derived(this, reader => this.getSessionAttention( + session, new Map(assignedPullRequests.read(reader).map(key => [key, session])), reader)); + return { session, attention }; + }); + this.sessionAttention = derived(this, reader => { + const result = new Map<string, IInboxSessionAttention>(); + for (const entry of entries.read(reader)) { + const attention = entry.attention.read(reader); + if (attention) { + result.set(entry.session.sessionId, attention); + } + } + return result; + }); + } + + acquireSessionAttention(): IDisposable { + this._attentionConsumers.set(this._attentionConsumers.get() + 1, undefined); + return toDisposable(() => this._attentionConsumers.set(this._attentionConsumers.get() - 1, undefined)); + } + + getSessionAttentionAfterUnarchive(sessions: readonly ISession[]): ReadonlyMap<string, IInboxSessionAttention> { + return derived(this, reader => { + const result = new Map<string, IInboxSessionAttention>(); + if (!this._trackingEnabled.read(reader)) { + return result; + } + const restoring = new Set(sessions.map(session => session.sessionId)); + const owners = this.getPullRequestNotificationSessions(this.sessionsManagementService.getSessions(), reader, restoring); + for (const session of sessions) { + const attention = this.getSessionAttention(session, owners, reader, true); + if (attention) { + result.set(session.sessionId, attention); + } + } + return result; + }).get(); + } + + private getSessionAttention(session: ISession, owners: ReadonlyMap<string, ISession>, reader: IReaderWithStore, includeArchived = false): IInboxSessionAttention | undefined { + const status = session.status.read(reader); + if (status === SessionStatus.Untitled) { + return undefined; + } + this.chatService.chatModels.read(reader); + const notifications = this.collectSessionNotifications(session, owners, reader, includeArchived).sort((a, b) => a.priority - b.priority); + const pendingInput = notifications.find(item => item.kind === AttentionKind.NeedsInput); + const timestamp = session.lastTurnEnd.read(reader)?.getTime() ?? session.updatedAt.read(reader).getTime(); + const attentionStartTime = this._attentionStartTime.read(reader); + const needsAttention = notifications.some(item => item.kind !== AttentionKind.PassingCI); + return { + tab: needsAttention ? InboxTab.ReadyForYou : status === SessionStatus.InProgress ? InboxTab.Working + : notifications.some(item => item.kind === AttentionKind.PassingCI) ? InboxTab.ReadyToMerge : InboxTab.ReadyForYou, + priority: notifications[0]?.priority ?? InboxNotificationPriority.Later, + notificationIds: notifications.map(item => item.id).sort(), + ...(pendingInput?.provisionalId ? { pendingInput: { notificationId: pendingInput.id, provisionalId: pendingInput.provisionalId } } : {}), + isHistoricalCompletion: status === SessionStatus.Completed && Number.isFinite(attentionStartTime) && timestamp < attentionStartTime + && !notifications.some(item => item.kind !== AttentionKind.PullRequestMerged || item.timestamp !== undefined && item.timestamp >= attentionStartTime), + }; + } + + private trackAttentionStartTime(): IObservable<number> { + const startTime = observableValue(this, Number.POSITIVE_INFINITY); + this._register(this.storageService.onDidChangeValue(StorageScope.PROFILE, ATTENTION_START_TIME_STORAGE_KEY, this._store)(event => { + if (event.external) { + startTime.set(this.storageService.getNumber(ATTENTION_START_TIME_STORAGE_KEY, StorageScope.PROFILE, Number.POSITIVE_INFINITY), undefined); + } + })); + this._register(autorun(reader => { + if (this._trackingEnabled.read(reader)) { + // Persist first demand so late-arriving history cannot backfill the Inbox after reload. + const value = this.storageService.getNumber(ATTENTION_START_TIME_STORAGE_KEY, StorageScope.PROFILE) ?? Date.now(); + this.storageService.store(ATTENTION_START_TIME_STORAGE_KEY, value, StorageScope.PROFILE, StorageTarget.MACHINE); + startTime.set(value, undefined); + } + })); + return startTime; + } + + private getPullRequestNotificationSessions(sessions: readonly ISession[], reader: IReader, restoring?: ReadonlySet<string>): ReadonlyMap<string, ISession> { + const candidates = new Map<string, { session: ISession; owned: boolean; updatedAt: number }>(); + for (const session of sessions) { + if (session.isArchived.read(reader) && !restoring?.has(session.sessionId) || session.status.read(reader) === SessionStatus.InProgress) { + continue; + } + const ownedRefs = new Set(getSessionAttentionPullRequestRefs(session, reader).map(ref => getPullRequestKey(ref.owner, ref.repo, ref.number).toLowerCase())); + const updatedAt = session.updatedAt.read(reader).getTime(); + for (const ref of getSessionAttentionPullRequestRefs(session, reader, true)) { + const key = getPullRequestKey(ref.owner, ref.repo, ref.number).toLowerCase(); + const owned = ownedRefs.has(key); + const previous = candidates.get(key); + if (!previous || (owned && !previous.owned) || (owned === previous.owned + && (updatedAt > previous.updatedAt || (updatedAt === previous.updatedAt && session.sessionId < previous.session.sessionId)))) { + candidates.set(key, { session, owned, updatedAt }); + } + } + } + return new Map([...candidates].map(([key, candidate]) => [key, candidate.session])); + } + + private collectSessionNotifications(session: ISession, owners: ReadonlyMap<string, ISession>, reader: IReaderWithStore, includeArchived = false): IAttentionNotification[] { + const notifications: IAttentionNotification[] = []; + if (session.isArchived.read(reader) && !includeArchived) { + return notifications; + } + const status = session.status.read(reader); + const updatedAt = session.updatedAt.read(reader).getTime(); + if (status === SessionStatus.NeedsInput) { + const key = this.getNeedsInputKey(session, reader) ?? `${updatedAt}`; + notifications.push({ + id: `${session.sessionId}:needsInput:${key}`, kind: AttentionKind.NeedsInput, priority: InboxNotificationPriority.Now, + provisionalId: `${session.sessionId}:needsInput:${updatedAt}`, + }); + } + if (status !== SessionStatus.InProgress) { + this.collectPullRequestNotifications(notifications, session, owners, reader); + } + return notifications; + } + + private ensureGitHubModels(session: ISession, reader: IReaderWithStore): void { + if (session.isArchived.read(reader)) { + return; + } + for (const ref of getSessionAttentionPullRequestRefs(session, reader, true)) { + const model = reader.delayedStore.add(this.gitHubService.createPullRequestModelReference(ref.owner, ref.repo, ref.number)).object; + if (!this._refreshedGitHubModels.has(model)) { + this._refreshedGitHubModels.add(model); + void model.refresh({ priority: 'background' }).catch(onUnexpectedError); + } + const pullRequest = model.pullRequest.read(reader); + if ((pullRequest?.state ?? ref.liveState ?? ref.state) !== GitHubPullRequestState.Open) { + continue; + } + reader.delayedStore.add(model.startPolling()); + const reviews = reader.delayedStore.add(this.gitHubService.createPullRequestReviewThreadsModelReference(ref.owner, ref.repo, ref.number)).object; + if (!this._refreshedGitHubModels.has(reviews)) { + this._refreshedGitHubModels.add(reviews); + void reviews.refresh(false, { priority: 'background' }).catch(onUnexpectedError); + } + reader.delayedStore.add(reviews.startPolling()); + if (pullRequest?.headSha) { + const ci = reader.delayedStore.add(this.gitHubService.createPullRequestCIModelReference(ref.owner, ref.repo, ref.number, pullRequest.headSha)).object; + if (!this._refreshedGitHubModels.has(ci)) { + this._refreshedGitHubModels.add(ci); + void ci.refresh(false, { priority: 'background' }).catch(onUnexpectedError); + } + reader.delayedStore.add(ci.startPolling()); + } + } + } + + private collectPullRequestNotifications(notifications: IAttentionNotification[], session: ISession, owners: ReadonlyMap<string, ISession>, reader: IReaderWithStore): void { + const failing: IPullRequestCandidate[] = []; + const passing: IPullRequestCandidate[] = []; + const merged: IPullRequestCandidate[] = []; + const reviews: IPullRequestCandidate[] = []; + const owned = new Set(getSessionAttentionPullRequestRefs(session, reader).map(ref => ref.uri.toString())); + let openOwnedPullRequests = 0; + const updatedAt = session.updatedAt.read(reader).getTime(); + for (const ref of getSessionAttentionPullRequestRefs(session, reader, true)) { + const isOwned = owned.has(ref.uri.toString()); + const model = reader.delayedStore.add(this.gitHubService.createPullRequestModelReference(ref.owner, ref.repo, ref.number)).object; + const pullRequest = model.pullRequest.read(reader); + const state = pullRequest?.state ?? ref.liveState ?? ref.state; + if (isOwned && state !== GitHubPullRequestState.Merged && state !== GitHubPullRequestState.Closed) { + openOwnedPullRequests++; + } + if (state === GitHubPullRequestState.Merged) { + if (isOwned) { + // Modification time can identify a notification, but cannot establish when a merge happened. + merged.push({ + ref, + identity: pullRequest?.mergedAt ?? String(parseTimestamp(pullRequest?.updatedAt) ?? updatedAt), + timestamp: parseTimestamp(pullRequest?.mergedAt), + }); + } + continue; + } + if (state !== GitHubPullRequestState.Open || owners.get(getPullRequestKey(ref.owner, ref.repo, ref.number).toLowerCase()) !== session) { + continue; + } + const threadsModel = reader.delayedStore.add(this.gitHubService.createPullRequestReviewThreadsModelReference(ref.owner, ref.repo, ref.number)).object; + const threads = threadsModel.reviewThreads.read(reader).filter(thread => !thread.isResolved && isCopilotReviewAuthor(thread.comments[0]?.author.login)); + if (pullRequest?.headSha) { + const ci = reader.delayedStore.add(this.gitHubService.createPullRequestCIModelReference(ref.owner, ref.repo, ref.number, pullRequest.headSha)).object; + const status = ci.overallStatus.read(reader); + if (status === GitHubCIOverallStatus.Failure) { + failing.push({ ref, identity: pullRequest.headSha }); + } else if (status === GitHubCIOverallStatus.Success && !pullRequest.isDraft && isOwned) { + passing.push({ ref, identity: pullRequest.headSha }); + } + } + if (threads.length) { + reviews.push({ + ref, + identity: String(hash(threads.map(thread => [ + thread.id, ...thread.comments.map(comment => [comment.id, comment.updatedAt ?? comment.createdAt]), + ]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))))), + }); + } + } + this.addPullRequestNotification(notifications, session, AttentionKind.FailingCI, failing); + if (passing.length === openOwnedPullRequests) { + this.addPullRequestNotification(notifications, session, AttentionKind.PassingCI, passing); + } + this.addPullRequestNotification(notifications, session, AttentionKind.PullRequestMerged, merged); + this.addPullRequestNotification(notifications, session, AttentionKind.ReviewComments, reviews); + } + + private addPullRequestNotification(notifications: IAttentionNotification[], session: ISession, kind: AttentionKind, candidates: readonly IPullRequestCandidate[]): void { + if (candidates.length) { + const suffix = candidates.map(candidate => `${candidate.ref.owner}/${candidate.ref.repo}#${candidate.ref.number}:${candidate.identity}`).sort().join(','); + const timestamps = candidates.map(candidate => candidate.timestamp).filter(timestamp => timestamp !== undefined); + notifications.push({ + id: `${session.sessionId}:${kind}:${suffix}`, + kind, + priority: kind === AttentionKind.FailingCI || kind === AttentionKind.ReviewComments ? InboxNotificationPriority.Now : InboxNotificationPriority.Next, + ...(timestamps.length ? { timestamp: Math.max(...timestamps) } : {}), + }); + } + } + + private getNeedsInputChats(session: ISession, reader: IReader) { + const chats = session.chats.read(reader); + const waiting = chats.filter(chat => chat.status.read(reader) === SessionStatus.NeedsInput); + return waiting.length ? waiting : chats; + } + + private getNeedsInputKey(session: ISession, reader: IReaderWithStore): string | undefined { + let candidate: { key: string; startedWaitingAt: number } | undefined; + for (const chat of this.getNeedsInputChats(session, reader)) { + const model = this.chatService.getSession(chat.resource); + if (!model) { + continue; + } + let signal = this._chatModelChangeSignals.get(model); + if (!signal) { + signal = observableSignalFromEvent(this, model.onDidChange); + this._chatModelChangeSignals.set(model, signal); + } + signal.read(reader); + for (const request of model.getRequests().toReversed()) { + const response = request.response; + if (!response || response.isCanceled || request.isHiddenFromTranscript + || (request.shouldBeRemovedOnSend && !request.shouldBeRemovedOnSend.afterUndoStop)) { + continue; + } + let responseChanged = this._responseChangeSignals.get(response); + if (!responseChanged) { + responseChanged = observableSignalFromEvent(this, response.onDidChange); + this._responseChangeSignals.set(response, responseChanged); + } + responseChanged.read(reader); + const pending = response.isPendingConfirmation.read(reader); + if (!pending) { + continue; + } + const key = this.getResponseInputKey(response, reader); + if (!key) { + continue; + } + if (!candidate || pending.startedWaitingAt < candidate.startedWaitingAt) { + candidate = { key, startedWaitingAt: pending.startedWaitingAt }; + } + break; + } + } + return candidate?.key; + } + + private getResponseInputKey(response: IChatResponseModel, reader: IReader): string | undefined { + for (const part of response.response.value) { + if (part.kind === 'confirmation' && !part.isUsed) { + return `cf:${response.requestId}:${hash(part.title.replace(/\s+/g, ' ').trim())}`; + } + } + for (const [index, part] of response.response.value.entries()) { + if (part.kind === 'questionCarousel' && !part.isUsed && part.questions.length) { + return `qc:${response.requestId}:${part.resolveId || hash(part.questions.map(question => question.id || question.title).join('|'))}`; + } + if (part.kind === 'planReview' && !part.isUsed && !response.isComplete) { + return `pr:${response.requestId}:${part.resolveId ?? index}`; + } + if (part.kind === 'toolInvocation') { + const state = part.state.read(reader); + if (state.type === IChatToolInvocation.StateKind.WaitingForConfirmation || state.type === IChatToolInvocation.StateKind.WaitingForPostApproval) { + return `tc:${response.requestId}:${part.toolCallId}:${state.type === IChatToolInvocation.StateKind.WaitingForPostApproval ? 'result' : 'execution'}`; + } + } + } + return undefined; + } + + private ensureChatModelLoaded(resource: URI): void { + const key = resource.toString(); + this._activeNeedsInputChatResources.add(key); + if (this._unregisteredChatProviders.has(getChatSessionType(resource)) || this.chatService.getSession(resource) + || this._needsInputChatModelRefs.has(key) || this._loadingNeedsInputChatModels.has(key)) { + return; + } + const cts = new CancellationTokenSource(this._chatLoadToken); + this._loadingNeedsInputChatModels.set(key, cts); + void this.chatService.acquireOrLoadSession(resource, ChatAgentLocation.Chat, cts.token, 'SessionAttentionService') + .then(reference => { + if (!reference) { + return; + } + if (cts.token.isCancellationRequested || this._store.isDisposed || !this._activeNeedsInputChatResources.has(key)) { + reference.dispose(); + return; + } + this._needsInputChatModelRefs.set(key, reference); + }) + .catch(error => { + if (!cts.token.isCancellationRequested) { + onUnexpectedError(error); + } + }) + .finally(() => { + this._loadingNeedsInputChatModels.delete(key); + const cancelled = cts.token.isCancellationRequested; + cts.dispose(); + if (cancelled && !this._store.isDisposed) { + this._chatProvidersChanged.trigger(undefined); + } + }); + } +} + +function getSessionAttentionPullRequestRefs(session: ISession, reader: IReader, includeReferences = false): readonly IGitHubPullRequestRef[] { + const references = [ + ...getSessionGitHubReferences(session, reader).pullRequests.filter(ref => ref.createdByThisSession), + ...(session.workspace.read(reader)?.folders ?? []).flatMap(folder => { + const gitHubInfo = folder.gitRepository?.gitHubInfo.read(reader); + return includeReferences ? getGitHubPullRequestRefs(gitHubInfo) : getSessionOwnedGitHubPullRequestRefs(gitHubInfo); + }), + ]; + const seen = new Set<string>(); + return references.filter(ref => { + const key = `${ref.owner.toLowerCase()}/${ref.repo.toLowerCase()}#${ref.number}`; + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }); +} + +function parseTimestamp(value: string | undefined): number | undefined { + if (!value) { + return undefined; + } + const parsed = Date.parse(value); + return Number.isFinite(parsed) ? parsed : undefined; +} diff --git a/src/vs/workbench/contrib/sessions/browser/sessionComparisonConfiguration.ts b/src/vs/workbench/contrib/sessions/browser/sessionComparisonConfiguration.ts index 70aeb893dbb6..bc891227f723 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionComparisonConfiguration.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionComparisonConfiguration.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { filterConfigurationToSchema } from '../../chat/browser/widget/input/chatModelConfigurationLogic.js'; +import { getModelConfigProperty, getModelConfigValueLabel, MODEL_CONFIG_GROUP_EFFORT } from '../../chat/browser/widget/input/modelPicker/modelPickerModelConfig.js'; import { isModelComparisonSupported } from '../../chat/browser/widget/input/modelPicker/modelPickerPresentation.js'; import { ILanguageModelChatMetadataAndIdentifier } from '../../chat/common/languageModels.js'; import { localize } from '../../../../nls.js'; @@ -31,6 +32,7 @@ export function createSessionComparisonHarness( })) { throw new Error(localize('comparison.configurationUnavailable', "The requested model configuration is not supported by the selected model.")); } + const effort = getModelConfigProperty(model, { getModelConfiguration: () => configuration }, MODEL_CONFIG_GROUP_EFFORT, true); return { providerId, sessionTypeId: sessionType.id, @@ -38,6 +40,7 @@ export function createSessionComparisonHarness( modelId: model.identifier, modelLabel: model.metadata.name, modelConfiguration: Object.keys(configuration).length ? { ...configuration } : undefined, + ...(effort ? { modelConfigurationLabel: getModelConfigValueLabel(effort.schema, effort.value) } : {}), permissionId: permission.id, permissionLabel: permission.label, modeId: permission.comparisonModeId, diff --git a/src/vs/workbench/contrib/sessions/browser/sessionComparisonService.ts b/src/vs/workbench/contrib/sessions/browser/sessionComparisonService.ts index ebbeedbfeb08..e4c40ff7f52e 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionComparisonService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionComparisonService.ts @@ -34,10 +34,11 @@ interface IStoredSessionComparisonParticipant extends Omit<ISessionComparisonPar readonly chatResource?: string; } -interface IStoredSessionComparison extends Omit<ISessionComparison, 'workspace' | 'sessionResource' | 'attachedContext' | 'participants'> { +interface IStoredSessionComparison extends Omit<ISessionComparison, 'workspace' | 'sessionResource' | 'originatingChatResource' | 'attachedContext' | 'participants'> { readonly version?: number; readonly workspace?: string; readonly sessionResource?: string; + readonly originatingChatResource?: string; readonly attachedContext?: readonly IChatRequestVariableEntry[]; readonly participants: readonly IStoredSessionComparisonParticipant[]; } @@ -157,6 +158,7 @@ export class SessionComparisonService extends Disposable implements ISessionComp let comparison: ISessionComparison = { id, groupId: group.id, + originatingChatResource: options.originatingChatResource, title, createdAt: Date.now(), workspace: options.workspace, @@ -766,10 +768,15 @@ export class SessionComparisonService extends Disposable implements ISessionComp if (this._reportedAttemptTelemetry.has(key) || completion.elapsedMs === undefined) { continue; } + const firstTurnUsage = aggregateChatUsage([requests[0]?.response?.usage]); logSessionComparisonAttemptCompleted(this.telemetryService, { comparisonId: hashSessionIdForTelemetry(comparison.id), attemptIndex, elapsedMs: completion.elapsedMs, + inputTokens: firstTurnUsage?.inputTokens, + cachedTokens: firstTurnUsage?.cachedTokens, + outputTokens: firstTurnUsage?.outputTokens, + tokenCountIsComplete: firstTurnUsage?.isComplete ?? false, }); this._reportedAttemptTelemetry.add(key); telemetryChanged = true; @@ -1246,6 +1253,7 @@ export class SessionComparisonService extends Disposable implements ISessionComp launching: undefined, workspace: comparison.workspace ? URI.parse(comparison.workspace) : undefined, sessionResource: comparison.sessionResource ? URI.parse(comparison.sessionResource) : undefined, + originatingChatResource: comparison.originatingChatResource ? URI.parse(comparison.originatingChatResource) : undefined, attachedContext: comparison.attachedContext?.map(IChatRequestVariableEntry.fromExport), participants: comparison.participants.map(participant => ({ ...participant, @@ -1269,6 +1277,7 @@ export class SessionComparisonService extends Disposable implements ISessionComp version: 1, workspace: comparison.workspace?.toString(), sessionResource: comparison.sessionResource?.toString(), + originatingChatResource: comparison.originatingChatResource?.toString(), attachedContext: comparison.attachedContext?.map(IChatRequestVariableEntry.toExport), participants: comparison.participants.map(participant => ({ ...participant, diff --git a/src/vs/workbench/contrib/sessions/browser/sessionDraftsService.ts b/src/vs/workbench/contrib/sessions/browser/sessionDraftsService.ts new file mode 100644 index 000000000000..5fb7f4e93624 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionDraftsService.ts @@ -0,0 +1,433 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { toAction } from '../../../../base/common/actions.js'; +import { Sequencer } from '../../../../base/common/async.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { createCommandUri } from '../../../../base/common/htmlContent.js'; +import { Disposable, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { autorun, derived, IObservable, observableFromEvent } from '../../../../base/common/observable.js'; +import { basename } from '../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { localize } from '../../../../nls.js'; +import { CommandsRegistry } from '../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; +import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { NotificationText } from '../../../../platform/notification/common/notificationMessage.js'; +import { IStorageService } from '../../../../platform/storage/common/storage.js'; +import { IChatEntitlementService } from '../../../services/chat/common/chatEntitlementService.js'; +import { ILifecycleService } from '../../../services/lifecycle/common/lifecycle.js'; +import { IChatDraft } from '../../chat/common/attachments/chatDraft.js'; +import { writeNewChatDraftState } from '../common/newChatDraftState.js'; +import { hasSessionDraftContent, ISavedSessionDraft, ISavedSessionDraftTarget, SavedSessionDrafts } from '../common/savedSessionDrafts.js'; +import { SESSIONS_DRAFTS_ENABLED_SETTING } from '../common/sessionConfig.js'; +import { ISessionsManagementService } from '../common/sessionsManagement.js'; +import { ISendRequestOptions } from '../common/sessionsProvider.js'; +import { ISessionsService } from './sessionsService.js'; +import { ISessionGroupsService } from './sessionGroupsService.js'; +import { IPendingSessionSection } from './views/pendingSessions.js'; + +const openDraftCommandId = 'sessions.drafts.open'; + +export const ISessionDraftsService = createDecorator<ISessionDraftsService>('sessionDraftsService'); + +export interface ISessionDraftsService { + readonly _serviceBrand: undefined; + readonly enabled: IObservable<boolean>; + readonly sections: IObservable<readonly IPendingSessionSection[]>; + readonly onDidOpenDraft: Event<string>; + createComposer(): SessionDraftComposer; + registerComposer(composer: SessionDraftComposer, restore: (draft: ISavedSessionDraft, token?: CancellationToken) => Promise<void>, clear: () => void): IDisposable; + stowAndClear(composer?: SessionDraftComposer): ISavedSessionDraft | undefined; + open(id: string, options?: { removeFromDrafts?: boolean }): Promise<void>; + save(input: IChatDraft, target: ISavedSessionDraftTarget, id?: string): ISavedSessionDraft; + restoreRecovery(input: IChatDraft, target: ISavedSessionDraftTarget): Promise<void>; + getDraftRevision(composer: SessionDraftComposer): string | undefined; + finishScheduledComposer(composer: SessionDraftComposer, revision: string | undefined): void; + stow(composer: SessionDraftComposer, options?: { notifyCreated?: boolean }): ISavedSessionDraft | undefined; +} + +/** Snapshot ownership is independent of the provisional provider session and of its editor's lifetime. */ +export class SessionDraftComposer implements IDisposable { + id: string; + input: IChatDraft = { inputText: '', attachments: [] }; + target: ISavedSessionDraftTarget = {}; + sending: ISavedSessionDraft | undefined; + isSending = false; + isScheduling = false; + isRestoring = false; + disposed = false; + private sendTracked = false; + + constructor(private readonly service: SessionDraftsService) { + this.id = generateUuid(); + } + + updateInput(input: IChatDraft): void { + this.input = input; + this.service.updateNavigation(this); + } + + willSend(input: IChatDraft): void { + this.input = input; + this.sendTracked = false; + try { + this.sending = this.service.getDraftRevision(this) ? this.service.stow(this) : undefined; + } catch (error) { + this.service.reportSaveError(error); + } + this.isSending = true; + } + + trackSend(options: ISendRequestOptions, sessionId: string): void { + if (this.sending) { + this.service.trackSend(options, this.sending, sessionId); + this.sendTracked = true; + } + } + + didSend(accepted: boolean): void { + this.isSending = false; + if (accepted) { + if (this.sending && !this.sendTracked) { + this.service.acceptSend(this.sending); + } + this.id = generateUuid(); + } else if (this.disposed && this.sending) { + // A failed request's snapshot remains available even when navigation destroyed its editor. + this.service.retain(this.sending); + } + this.sending = undefined; + } + + dispose(): void { + this.disposed = true; + } +} + +export class SessionDraftsService extends Disposable implements ISessionDraftsService { + declare readonly _serviceBrand: undefined; + readonly enabled: IObservable<boolean>; + readonly sections: IObservable<readonly IPendingSessionSection[]>; + private readonly _onDidOpenDraft = this._register(new Emitter<string>()); + readonly onDidOpenDraft = this._onDidOpenDraft.event; + private readonly model: SavedSessionDrafts; + private current: { composer: SessionDraftComposer; restore: (draft: ISavedSessionDraft, token?: CancellationToken) => Promise<void>; clear: () => void } | undefined; + private readonly sends = new Map<ISendRequestOptions, { draft: ISavedSessionDraft; sessionId: string }>(); + private readonly openQueue = new Sequencer(); + private opening = false; + private stowing = false; + + constructor( + @IStorageService private readonly storageService: IStorageService, + @IConfigurationService configurationService: IConfigurationService, + @ISessionsService private readonly sessionsService: ISessionsService, + @ISessionsManagementService sessionsManagementService: ISessionsManagementService, + @IDialogService private readonly dialogService: IDialogService, + @INotificationService private readonly notificationService: INotificationService, + @ILogService private readonly logService: ILogService, + @ISessionGroupsService private readonly groupsService: ISessionGroupsService, + @IChatEntitlementService entitlementService: IChatEntitlementService, + @ILifecycleService private readonly lifecycleService: ILifecycleService, + ) { + super(); + const configured = observableConfigValue(SESSIONS_DRAFTS_ENABLED_SETTING, false, configurationService); + const hidden = observableFromEvent(this, entitlementService.onDidChangeSentiment, () => entitlementService.sentiment.hidden); + this.enabled = derived(this, reader => configured.read(reader) && !hidden.read(reader)); + this.model = this._register(new SavedSessionDrafts(storageService)); + this._register(CommandsRegistry.registerCommand(openDraftCommandId, async (_accessor, id: string) => { + if (!await this.openDraft(id, CancellationToken.None)) { + throw new Error(localize('draft.noLongerAvailable', "This draft is no longer available.")); + } + })); + this._register(autorun(reader => { + const error = this.model.error.read(reader); + if (error && this.enabled.read(reader)) { + this.logService.error('[SessionDrafts] Could not read saved drafts', error); + this.notificationService.error(localize('draft.storageFailed', "Could not read saved drafts. Their stored content has not been changed: {0}", error.message)); + } + })); + this._register(sessionsService.registerSavedDraftOpener(async (id, token) => { + if (!this.enabled.get() || !this.model.drafts.get().some(draft => draft.id === id) || token.isCancellationRequested) { + return false; + } + return this.openDraft(id, token); + })); + this._register(autorun(reader => { + this.enabled.read(reader); + if (this.current) { + this.updateNavigation(this.current.composer); + } + })); + this.sections = derived(this, reader => { + if (!this.enabled.read(reader)) { + return []; + } + const items = this.model.drafts.read(reader).map(draft => ({ + pendingSession: true as const, + id: draft.id, + kind: 'draft' as const, + title: draft.input.inputText.trim().split('\n')[0] || localize('draft.attachmentTitle', "Attached Context"), + description: draft.target.folderUri ? basename(draft.target.folderUri) : '', + folderUri: draft.target.folderUri, + providerId: draft.target.providerId, + sessionType: draft.target.sessionTypeId, + environmentId: draft.target.environmentId, + harness: draft.target.harness, + applicationId: draft.target.applicationId, + isQuickChat: !draft.target.folderUri, + open: () => this.open(draft.id), + actions: [ + toAction({ id: 'sessions.drafts.resume', label: localize('draft.resume', "Resume Draft"), class: ThemeIcon.asClassName(Codicon.play), run: () => this.open(draft.id) }), + toAction({ id: 'sessions.drafts.delete', label: localize('draft.delete', "Delete Draft"), class: ThemeIcon.asClassName(Codicon.trash), run: () => this.delete(draft.id) }), + ], + })); + return items.length ? [{ id: 'drafts', label: localize('drafts', "Drafts"), items }] : []; + }); + this._register(sessionsManagementService.onDidSendRequest(event => { + const send = this.sends.get(event.options); + if (send) { + this.model.remove(send.draft.id, send.draft.revision); + this.sends.delete(event.options); + } + })); + this._register(sessionsManagementService.onDidEndNewSessionRequest(event => { + for (const [options, send] of this.sends) { + if (send.sessionId === event.session.sessionId) { + this.sends.delete(options); + } + } + })); + this._register(sessionsManagementService.onDidReplaceNewDraftSession(event => { + for (const send of this.sends.values()) { + if (send.sessionId === event.from.sessionId) { + send.sessionId = event.to.sessionId; + } + } + })); + } + + createComposer(): SessionDraftComposer { + const composer = new SessionDraftComposer(this); + composer.target = { groupId: this.groupsService.getPendingNewSessionGroup() }; + return composer; + } + + registerComposer(composer: SessionDraftComposer, restore: (draft: ISavedSessionDraft, token?: CancellationToken) => Promise<void>, clear: () => void): IDisposable { + const restoreComposer = async (draft: ISavedSessionDraft, token?: CancellationToken) => { + composer.isRestoring = true; + try { + await restore(draft, token); + if (!token?.isCancellationRequested && !composer.disposed) { + composer.id = draft.id; + composer.target = draft.target; + } + } finally { + composer.isRestoring = false; + } + }; + this.current = { composer, restore: restoreComposer, clear }; + this.updateNavigation(composer); + return toDisposable(() => { + composer.dispose(); + if (this.current?.composer === composer) { + this.current = undefined; + } + }); + } + + stowAndClear(composer = this.current?.composer): ISavedSessionDraft | undefined { + const current = this.current; + if (!this.enabled.get() || !current || current.composer !== composer || current.composer.isSending) { + return undefined; + } + if (this.opening || current.composer.isScheduling) { + throw new Error(localize('draft.newSessionBusy', "Wait for the draft to finish opening or scheduling before starting a new session.")); + } + const saved = this.stow(current.composer, { notifyCreated: true }); + if (saved) { + this.clearLegacyInput(current.composer); + // Change identity before clearing: emptying the old identity would delete the saved draft. + this.stowing = true; + try { + current.composer.id = generateUuid(); + current.composer.updateInput({ inputText: '', attachments: [] }); + current.clear(); + this.sessionsService.setCurrentDraftId(undefined, true); + } finally { + this.stowing = false; + } + } + return saved; + } + + stow(composer: SessionDraftComposer, options?: { notifyCreated?: boolean }): ISavedSessionDraft | undefined { + if (!this.enabled.get() || this.lifecycleService.willShutdown || composer.isScheduling || composer.isRestoring) { + return undefined; + } + if (!hasSessionDraftContent(composer.input)) { + if (this.model.drafts.get().some(draft => draft.id === composer.id)) { + this.model.remove(composer.id); + } + return undefined; + } + const isNew = !this.model.drafts.get().some(draft => draft.id === composer.id); + const saved = this.model.save(composer.input, composer.target, composer.id); + if (isNew && options?.notifyCreated) { + this.notificationService.info(NotificationText.format( + localize('draft.created', "Created draft. {0}"), + NotificationText.link(localize('draft.open', "Open Draft"), createCommandUri(openDraftCommandId, saved.id).toString()), + )); + } + return saved; + } + + reportSaveError(error: unknown): void { + this.logService.error('[SessionDrafts] Save failed', error); + this.notificationService.error(localize('draft.saveFailed', "Could not save this draft. The current input has been kept: {0}", String(error))); + } + + save(input: IChatDraft, target: ISavedSessionDraftTarget, id?: string): ISavedSessionDraft { + if (!this.enabled.get()) { + throw new Error(localize('drafts.disabled', "Saved drafts are disabled.")); + } + return this.model.save(input, target, id); + } + + getDraftRevision(composer: SessionDraftComposer): string | undefined { + return this.model.drafts.get().find(draft => draft.id === composer.id)?.revision; + } + + finishScheduledComposer(composer: SessionDraftComposer, revision: string | undefined): void { + if (revision) { + this.model.remove(composer.id, revision); + } + composer.id = generateUuid(); + } + + async restoreRecovery(input: IChatDraft, target: ISavedSessionDraftTarget): Promise<void> { + if (this.current && (this.current.composer.isSending || hasSessionDraftContent(this.current.composer.input))) { + throw new Error(localize('draft.recoveryOccupied', "The schedule is cancelled and its content is retained. Open an empty New Session and choose Edit as Draft again to recover it without replacing your current input.")); + } + await this.sessionsService.openNewSession(); + if (!this.current || hasSessionDraftContent(this.current.composer.input)) { + throw new Error(localize('draft.recoveryNotReady', "The schedule is cancelled and its content is retained. Clear the new-session input before recovering this request.")); + } + const now = Date.now(); + await this.current.restore({ id: generateUuid(), revision: generateUuid(), createdAt: now, updatedAt: now, input, target }); + } + + retain(draft: ISavedSessionDraft): void { + if (!this.model.drafts.get().some(candidate => candidate.id === draft.id)) { + this.model.save(draft.input, draft.target, draft.id); + } + } + + updateNavigation(composer: SessionDraftComposer): void { + if (!this.opening && !this.stowing && this.current?.composer === composer) { + this.sessionsService.setCurrentDraftId(this.enabled.get() && hasSessionDraftContent(composer.input) ? composer.id : undefined); + } + } + + clearLegacyInput(composer: SessionDraftComposer): void { + if (this.current?.composer === composer) { + writeNewChatDraftState(this.storageService, { inputText: '', attachments: [] }); + } + } + + trackSend(options: ISendRequestOptions, draft: ISavedSessionDraft, sessionId: string): void { + this.sends.set(options, { draft, sessionId }); + } + + acceptSend(draft: ISavedSessionDraft): void { + this.model.remove(draft.id, draft.revision); + } + + async open(id: string, options?: { removeFromDrafts?: boolean }): Promise<void> { + await this.openDraft(id, CancellationToken.None, options?.removeFromDrafts); + } + + private openDraft(id: string, token: CancellationToken, removeFromDrafts = false): Promise<boolean> { + return this.queueRestore(() => this.doOpenDraft(id, token, removeFromDrafts)); + } + + private queueRestore<T>(restore: () => Promise<T>): Promise<T> { + return this.openQueue.queue(async () => { + this.opening = true; + try { + return await restore(); + } finally { + this.opening = false; + if (this.current) { + this.updateNavigation(this.current.composer); + } + } + }); + } + + private async doOpenDraft(id: string, token: CancellationToken, removeFromDrafts: boolean): Promise<boolean> { + if (token.isCancellationRequested) { + return false; + } + if (!this.enabled.get()) { + throw new Error(localize('drafts.disabled', "Saved drafts are disabled.")); + } + let draft = this.model.drafts.get().find(candidate => candidate.id === id); + if (!draft) { + return false; + } + if (this.current?.composer.isSending || this.current?.composer.isScheduling) { + throw new Error(localize('draft.busy', "Wait for the current request to start or finish scheduling before opening a draft.")); + } + if (this.current) { + const currentDraft = this.stow(this.current.composer, { notifyCreated: this.current.composer.id !== id }); + if (currentDraft?.id === id) { + draft = currentDraft; + } + } + await this.sessionsService.openNewSession({ preserveNavigation: true }, token); + if (token.isCancellationRequested) { + return false; + } + const current = this.current; + if (!current) { + throw new Error(localize('draft.noComposer', "Could not open the new-session composer.")); + } + await current.restore(draft, token); + if (token.isCancellationRequested || current.composer.disposed || this.current !== current) { + return false; + } + this.groupsService.setPendingNewSessionGroup(draft.target.groupId); + this.updateNavigation(current.composer); + if (removeFromDrafts) { + this.model.remove(draft.id, draft.revision); + } else { + this._onDidOpenDraft.fire(draft.id); + } + return true; + } + + private async delete(id: string): Promise<void> { + if (!this.enabled.get()) { + return; + } + if ((await this.dialogService.confirm({ message: localize('draft.deleteConfirm', "Delete this unsent draft?"), primaryButton: localize('draft.delete', "Delete Draft") })).confirmed) { + this.model.remove(id); + if (this.current?.composer.id === id) { + const composer = this.current.composer; + composer.id = generateUuid(); + composer.updateInput({ inputText: '', attachments: [] }); + this.current.clear(); + } + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/sessionGroupsService.ts b/src/vs/workbench/contrib/sessions/browser/sessionGroupsService.ts index cc9e287129d5..845b26799271 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionGroupsService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionGroupsService.ts @@ -20,7 +20,7 @@ import { ISessionSectionOrderService, ISessionSectionPositions, resolveSectionOr export interface ISessionGroupAppearance { /** Theme icon id chosen by the user. */ readonly icon?: string; - /** Theme color id applied to the group icon. */ + /** Theme color id applied to the group icon and name. */ readonly color?: string; } @@ -211,7 +211,7 @@ export interface ISessionGroupsService { /** Set a group's icon, or restore the default with `undefined`. */ setGroupIcon(groupId: string, icon: string | undefined): void; - /** Set a group's icon color, or restore the default with `undefined`. */ + /** Set a group's icon and name color, or restore the default with `undefined`. */ setGroupColor(groupId: string, color: string | undefined): void; /** Appearance of a workspace, repository, or environment section, keyed by its stable section id. */ @@ -220,7 +220,7 @@ export interface ISessionGroupsService { /** Set a grouping section's icon, or restore its default with `undefined`. */ setSectionIcon(sectionId: string, icon: string | undefined): void; - /** Set a grouping section's icon color, or restore its default with `undefined`. */ + /** Set a grouping section's icon and name color, or restore its default with `undefined`. */ setSectionColor(sectionId: string, color: string | undefined): void; /** diff --git a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/media/sessionInputBanners.css b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/media/sessionInputBanners.css index 82a4266c28b8..c2ad3ea4b6a4 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/media/sessionInputBanners.css +++ b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/media/sessionInputBanners.css @@ -261,6 +261,12 @@ z-index: 1; } +/* Paused while the banner is outside the viewport or its document is hidden. */ +.session-input-banner.working.session-input-banner-anim-paused::before, +.session-input-banner.working.session-input-banner-anim-paused::after { + animation-play-state: paused; +} + @media (prefers-reduced-motion: reduce) { .session-input-banner.working::before, .session-input-banner.working::after { diff --git a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerModel.ts b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerModel.ts index f980812d7926..571491febeac 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerModel.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerModel.ts @@ -523,6 +523,9 @@ export class SessionInputBannerModel extends Disposable { private _acceptComments(state: IBaseBannerState): void { this.target?.validate(); + if (this.target) { + return; + } for (const commentId of state.commentIds) { this.feedbackService.acceptFeedback(state.sessionResource, commentId); } diff --git a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerWidget.ts b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerWidget.ts index 50ddb054b93a..08f2c950bb9c 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerWidget.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionInputBannerWidget.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import './media/sessionInputBanners.css'; +import { pauseCSSAnimationsWhenHidden } from '../../../../../base/browser/animationSync.js'; import * as dom from '../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; @@ -80,6 +81,7 @@ export class SessionInputBannerWidget extends Disposable { private readonly _buttons: Array<{ readonly button: IButton; readonly primary: boolean }> = []; private readonly _showWorkingAnimation = this._register(new MutableDisposable()); + private readonly _workingBorderAnimations = this._register(new MutableDisposable()); private readonly _content = this._register(new MutableDisposable<DisposableStore>()); private _runningPrimaryAction = false; @@ -386,24 +388,43 @@ export class SessionInputBannerWidget extends Disposable { } private async _waitUntilReady(waitUntilReady: () => Promise<boolean>): Promise<boolean> { - this.domNode.setAttribute('aria-busy', 'true'); + this._setBusy(true); this._showWorkingAnimation.value = disposableTimeout(() => this.domNode.classList.add('working'), SHOW_WORKING_DELAY_MS); try { return await waitUntilReady(); } finally { this._showWorkingAnimation.clear(); this.domNode.classList.remove('working'); - this.domNode.setAttribute('aria-busy', 'false'); + this._setBusy(false); } } setWorking(working: boolean): void { this._working = working; this.domNode.classList.toggle('working', working); - this.domNode.setAttribute('aria-busy', String(working)); + this._setBusy(working); this._setPrimaryButtonsEnabled(!working); } + /** + * While busy, pauses the working border when it is outside the viewport or its document is hidden. + * Visibility tracking binds to the window the banner is mounted in, so it starts here rather than at + * construction, when the banner is still detached and may later be mounted in an auxiliary window. + * It is registered once per busy period, because the helper keeps one registration per element. + */ + private _setBusy(busy: boolean): void { + this.domNode.setAttribute('aria-busy', String(busy)); + if (!busy) { + this._workingBorderAnimations.clear(); + } else if (!this._workingBorderAnimations.value && !this._disposed && this.domNode.isConnected) { + this._workingBorderAnimations.value = pauseCSSAnimationsWhenHidden(this.domNode, { + pausedClass: 'session-input-banner-anim-paused', + subtree: true, + animationNames: new Set(['session-input-banner-working-border-spin']), + }); + } + } + private _setPrimaryButtonsEnabled(enabled: boolean): void { if (this._disposed) { return; diff --git a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.ts b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.ts index ab9ad3902930..8d14a019777c 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionInputBanners/sessionWorktreeCleanupService.ts @@ -11,7 +11,7 @@ import { CancellationError, getErrorMessage, isCancellationError } from '../../. import { Disposable } from '../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../base/common/network.js'; import { IObservable, observableValue } from '../../../../../base/common/observable.js'; -import { basename, extUri } from '../../../../../base/common/resources.js'; +import { basename, extUri, extUriBiasedIgnorePathCase } from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import type { IAgentHostWorktreeCleanupStatus } from '../../../../../platform/agentHost/common/agentHostWorktreeCleanup.js'; import { isAgentWorktreeBranch } from '../../../../../platform/agentHost/common/worktreePaths.js'; @@ -20,7 +20,7 @@ import { ConfigurationTarget, IConfigurationService } from '../../../../../platf import { ByteSize } from '../../../../../platform/files/common/files.js'; import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; -import { IProgressService, ProgressLocation } from '../../../../../platform/progress/common/progress.js'; +import { IProgress, IProgressService, IProgressStep, Progress, ProgressLocation } from '../../../../../platform/progress/common/progress.js'; import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { localize } from '../../../../../nls.js'; import { ISessionsListModelService } from '../sessionsListModelService.js'; @@ -44,27 +44,73 @@ type WorktreeCleanupOwner = | { readonly session?: undefined; readonly unlinkedWorktree: IManagedSessionWorktree }; export type ISessionWorktreeCleanupCandidate = WorktreeCleanupOwner & { + /** All sessions sharing these checkouts, including the representative session. */ + readonly sessions?: readonly ISession[]; + readonly worktreeId?: string; readonly sizeBytes: number | undefined; readonly worktreeCount: number; /** False for retained verification records absent from the current host inventory. */ readonly isListedByHost?: boolean; }; +export function getWorktreeCleanupSessions(owner: WorktreeCleanupOwner & { readonly sessions?: readonly ISession[] }): readonly ISession[] { + return owner.sessions ?? (owner.session ? [owner.session] : []); +} + +export function getWorktreeCleanupLastActivity(candidate: ISessionWorktreeCleanupCandidate): Date | undefined { + const sessions = getWorktreeCleanupSessions(candidate); + return sessions.length ? new Date(Math.max(...sessions.map(session => session.updatedAt.get().getTime()))) : undefined; +} + +function getPhysicalWorktreeId(providerId: string, repository: URI, worktree: URI): string { + const key = (uri: URI) => extUriBiasedIgnorePathCase.getComparisonKey(extUri.removeTrailingPathSeparator(extUri.normalizePath(uri))); + return JSON.stringify([providerId, key(repository), key(worktree)]); +} + +function getSessionWorktreeIds(session: ISession): readonly string[] { + return [...new Set(session.workspace.get()?.folders.flatMap(folder => folder.gitRepository?.workTreeUri + ? [getPhysicalWorktreeId(session.providerId, folder.gitRepository.uri, folder.gitRepository.workTreeUri)] : []) ?? [])]; +} + +function groupWorktreeSessions(sessions: readonly ISession[]): readonly (readonly ISession[])[] { + // Archiving is session-scoped, so overlapping multi-folder sessions must be selected together. + const byWorktree = new Map<string, Set<ISession>>(); + for (const session of sessions) { + const ids = getSessionWorktreeIds(session); + const group = new Set<ISession>([session]); + for (const id of ids) { + for (const member of byWorktree.get(id) ?? []) { + group.add(member); + } + } + for (const member of group) { + for (const id of getSessionWorktreeIds(member)) { + byWorktree.set(id, group); + } + } + } + return [...new Set(byWorktree.values())].map(group => [...group]); +} + export function isWorktreeCleanupBranchSupported(owner: WorktreeCleanupOwner): boolean { if (owner.unlinkedWorktree) { const { branch, worktree, repository } = owner.unlinkedWorktree; return isAgentWorktreeBranch(branch, URI.parse(worktree), URI.parse(repository)); } - return owner.session.workspace.get()?.folders.every(folder => !folder.gitRepository?.workTreeUri + return getWorktreeCleanupSessions(owner).every(session => session.workspace.get()?.folders.every(folder => !folder.gitRepository?.workTreeUri || folder.gitRepository.branchName === undefined - || isAgentWorktreeBranch(folder.gitRepository.branchName, folder.gitRepository.workTreeUri, folder.gitRepository.uri)) !== false; + || isAgentWorktreeBranch(folder.gitRepository.branchName, folder.gitRepository.workTreeUri, folder.gitRepository.uri)) !== false); } export function getWorktreeCleanupId(worktree: ISessionWorktreeCleanupCandidate): string { - return worktree.session ? worktree.session.sessionId : `managed:${worktree.unlinkedWorktree.providerId}:${worktree.unlinkedWorktree.worktree}`; + return worktree.worktreeId ?? (worktree.session ? worktree.session.sessionId : `managed:${worktree.unlinkedWorktree.providerId}:${worktree.unlinkedWorktree.worktree}`); } export function getWorktreeCleanupTitle(worktree: ISessionWorktreeCleanupCandidate): string { + if (worktree.sessions && worktree.sessions.length > 1) { + return [...new Set(worktree.sessions.flatMap(session => session.workspace.get()?.folders.flatMap(folder => folder.gitRepository?.workTreeUri + ? [folder.gitRepository.branchName || basename(folder.gitRepository.workTreeUri)] : []) ?? []))].join(', '); + } return worktree.session?.title.get() || (worktree.unlinkedWorktree ? worktree.unlinkedWorktree.branch || basename(URI.parse(worktree.unlinkedWorktree.worktree)) : localize('sessionWorktreeCleanup.untitled', "Untitled session")); } @@ -72,7 +118,7 @@ export function getWorktreeCleanupTitle(worktree: ISessionWorktreeCleanupCandida export function getWorktreeCleanupDiskUsage(worktrees: readonly ISessionWorktreeCleanupCandidate[]): number | undefined { let total = 0; for (const worktree of worktrees) { - if (worktree.session?.isArchived.get() || worktree.sizeBytes === undefined) { + if ((worktree.session && getWorktreeCleanupSessions(worktree).every(session => session.isArchived.get())) || worktree.sizeBytes === undefined) { return undefined; } total += worktree.sizeBytes; @@ -205,7 +251,7 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio this._updateSuggestion(); })); this._register(this.sessionsManagementService.onDidUnarchiveSession(session => { - this._cleanupOperations.set(this._cleanupOperations.get().filter(operation => operation.candidate.session?.sessionId !== session.sessionId), undefined); + this._cleanupOperations.set(this._cleanupOperations.get().filter(operation => !getWorktreeCleanupSessions(operation.candidate).some(candidate => candidate.sessionId === session.sessionId)), undefined); this._lastMeasuredWorktrees = undefined; this._lastScanAt = -Infinity; this._updateSuggestion(); @@ -304,9 +350,21 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio && session.workspace.get()?.folders.every(folder => !folder.gitRepository?.workTreeUri || folder.gitRepository.workTreeUri.scheme === Schemas.file) && isWorktreeCleanupBranchSupported({ session }) ); - const totalWorktrees = worktreeSessions.reduce((total, session) => total + (session.isArchived.get() ? 0 : this._countWorktrees(session)), 0); + const groups = groupWorktreeSessions(worktreeSessions); + const candidates = groups.map(sessions => { + const sorted = [...sessions].sort((a, b) => Number(a.isArchived.get()) - Number(b.isArchived.get()) || b.updatedAt.get().getTime() - a.updatedAt.get().getTime()); + const ids = [...new Set(sessions.flatMap(getSessionWorktreeIds))].sort(); + return { + session: sorted[0], + ...(sessions.length > 1 ? { sessions, worktreeId: `worktrees:${JSON.stringify(ids)}` } : {}), + sizeBytes: undefined, + worktreeCount: ids.length, + isMeasuring: sorted.some(session => !session.isArchived.get()), + }; + }); + const totalWorktrees = candidates.reduce((total, candidate) => total + (candidate.isMeasuring ? candidate.worktreeCount : 0), 0); let scannedWorktrees = 0; - const measured: (IMeasuredSessionWorktree | undefined)[] = worktreeSessions.map(session => session.isArchived.get() ? undefined : { session, sizeBytes: undefined, worktreeCount: this._countWorktrees(session), isMeasuring: true }); + const measured: (IMeasuredSessionWorktree | undefined)[] = candidates.map(candidate => candidate.isMeasuring ? candidate : undefined); onProgress({ scannedWorktrees, totalWorktrees, worktrees: coalesce(measured) }); if (worktreeSessions.length === 0) { @@ -314,9 +372,9 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio } const limiter = new Limiter<IMeasuredSessionWorktree>(2); - return Promise.all(worktreeSessions.map((session, index) => limiter.queue(async () => { - const worktreeCount = measured[index]?.isMeasuring ? this._countWorktrees(session) : 0; - const worktree = await this._measureSessionWorktree(session, token); + return Promise.all(candidates.map((candidate, index) => limiter.queue(async () => { + const worktreeCount = candidate.isMeasuring ? candidate.worktreeCount : 0; + const worktree = await this._measureWorktreeGroup(candidate, token); measured[index] = worktree; scannedWorktrees += worktreeCount; onProgress({ scannedWorktrees, totalWorktrees, worktrees: coalesce(measured) }); @@ -324,6 +382,33 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio }))); } + private async _measureWorktreeGroup(candidate: IMeasuredSessionWorktree, token: CancellationToken): Promise<IMeasuredSessionWorktree> { + const sessions = getWorktreeCleanupSessions(candidate); + const measuredIds = new Set<string>(); + const results: IMeasuredSessionWorktree[] = []; + let overlapping = false; + for (const session of [...sessions].sort((a, b) => Number(a.isArchived.get()) - Number(b.isArchived.get()) || b.updatedAt.get().getTime() - a.updatedAt.get().getTime())) { + const ids = getSessionWorktreeIds(session); + if (ids.every(id => measuredIds.has(id)) && !sessions.every(session => session.isArchived.get())) { + continue; + } + overlapping ||= ids.some(id => measuredIds.has(id)); + results.push(await this._measureSessionWorktree(session, token)); + ids.forEach(id => measuredIds.add(id)); + } + const status = ['failed', 'running', 'pending', 'inUse', 'skipped', 'unknown'].flatMap(state => results.flatMap(result => result.cleanupStatus?.state === state ? [result.cleanupStatus] : []))[0]; + return { + ...candidate, + sizeBytes: !overlapping && results.every(result => result.sizeBytes !== undefined) ? results.reduce((total, result) => total + result.sizeBytes!, 0) : undefined, + isMeasuring: false, + measurementFailed: results.some(result => result.measurementFailed), + cleanupStatus: status, + cleanupStatusError: results.find(result => result.cleanupStatusError)?.cleanupStatusError, + worktreeExists: results.every(result => result.worktreeExists === false) ? false : results.some(result => result.worktreeExists) ? true : undefined, + worktreeCheckError: results.find(result => result.worktreeCheckError)?.worktreeCheckError, + }; + } + private async _measureSessionWorktree(session: ISession, token: CancellationToken): Promise<IMeasuredSessionWorktree> { if (token.isCancellationRequested) { throw new CancellationError(); @@ -360,6 +445,8 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio } this.logService.warn(`[SessionWorktreeCleanupService] Failed to read cleanup status for session ${session.sessionId}`, error); } + } + if (session.isArchived.get() || sizeBytes === 0) { try { worktreeExists = await this.sessionsManagementService.sessionWorktreeExists?.(session, token); } catch (error) { @@ -369,6 +456,10 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio worktreeCheckError = getErrorMessage(error); this.logService.warn(`[SessionWorktreeCleanupService] Failed to check worktree existence for session ${session.sessionId}`, error); } + if (sizeBytes === 0 && worktreeExists === undefined) { + sizeBytes = undefined; + measurementFailed = true; + } } return { session, sizeBytes: session.isArchived.get() ? undefined : sizeBytes, worktreeCount: this._countWorktrees(session), isMeasuring: false, measurementFailed: !session.isArchived.get() && measurementFailed, cleanupStatus, cleanupStatusError, worktreeExists, worktreeCheckError }; } @@ -385,9 +476,9 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio const pendingIds = new Set(sessionIds); const updated = [...cached]; let published = cached; - await Promise.all(cached.map((worktree, index) => pendingIds.has(worktree.session.sessionId) && worktree.session.isArchived.get() + await Promise.all(cached.map((worktree, index) => (pendingIds.has(getWorktreeCleanupId(worktree)) || pendingIds.has(worktree.session.sessionId)) && getWorktreeCleanupSessions(worktree).every(session => session.isArchived.get()) ? limiter.queue(async () => { - updated[index] = await this._measureSessionWorktree(worktree.session, token); + updated[index] = await this._measureWorktreeGroup(worktree, token); // Another full scan or refresh may have superseded this snapshot while the request ran. if (this._lastMeasuredWorktrees === published) { published = [...updated]; @@ -576,11 +667,20 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio private _withCleanupState(worktrees: readonly IMeasuredSessionWorktree[], minimumAgeDays: number): readonly ISessionWorktree[] { const cutoff = Date.now() - minimumAgeDays * DAY_MS; - return worktrees.filter(isWorktreeCleanupBranchSupported).map(worktree => ({ - ...worktree, - ...(worktree.session.isArchived.get() ? { sizeBytes: worktree.worktreeExists === false ? 0 : undefined, isMeasuring: false, measurementFailed: false } : { worktreeExists: undefined, worktreeCheckError: undefined }), - cleanupState: this._getCleanupState(worktree.session, worktree.sizeBytes, cutoff), - })); + return worktrees.filter(isWorktreeCleanupBranchSupported).map(worktree => { + const states = getWorktreeCleanupSessions(worktree).map(session => this._getCleanupState(session, cutoff)); + const archived = states.every(state => state === 'archived'); + const blocked = states.find(state => state === 'running' || state === 'pinned' || state === 'recent' || state === 'untitled' || state === 'error'); + const active = states.find(state => state === 'active' || state === 'needsInput'); + const hasCurrentExistenceCheck = archived || worktree.sizeBytes === 0 || worktree.measurementFailed === true; + return { + ...worktree, + worktreeExists: hasCurrentExistenceCheck ? worktree.worktreeExists : undefined, + worktreeCheckError: hasCurrentExistenceCheck ? worktree.worktreeCheckError : undefined, + ...(archived ? { sizeBytes: worktree.worktreeExists === false ? 0 : undefined, isMeasuring: false, measurementFailed: false } : {}), + cleanupState: blocked ?? (archived ? 'archived' : worktree.measurementFailed ? 'unavailable' : active ?? states.find(state => state !== 'archived') ?? 'unavailable'), + }; + }); } private _getWorktreeSessionSignature(includeActivity = true): string { @@ -595,13 +695,10 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio .join('\n'); } - private _getCleanupState(session: ISession, sizeBytes: number | undefined, cutoff: number): SessionWorktreeCleanupState { + private _getCleanupState(session: ISession, cutoff: number): SessionWorktreeCleanupState { if (session.isArchived.get()) { return 'archived'; } - if (sizeBytes === undefined) { - return 'unavailable'; - } // A worktree that any window shows is never offered for cleanup. if (this.sessionHostService.isShown(session.resource)) { return 'active'; @@ -629,8 +726,8 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio private _getCleanupCandidates(worktrees: readonly ISessionWorktree[]): readonly (ISessionWorktreeCleanupCandidate & { readonly sizeBytes: number })[] { return worktrees - .filter((worktree): worktree is ISessionWorktree & { readonly session: ISession; readonly sizeBytes: number } => !!worktree.session && worktree.cleanupState === 'eligible' && worktree.sizeBytes !== undefined) - .map(worktree => ({ session: worktree.session, sizeBytes: worktree.sizeBytes, worktreeCount: worktree.worktreeCount })) + .filter((worktree): worktree is ISessionWorktree & { readonly session: ISession; readonly sizeBytes: number } => !!worktree.session && worktree.cleanupState === 'eligible' && worktree.sizeBytes !== undefined && worktree.worktreeExists !== false && !worktree.worktreeCheckError) + .map(worktree => ({ ...worktree })) .sort((a, b) => a.session.updatedAt.get().getTime() - b.session.updatedAt.get().getTime()); } @@ -764,7 +861,6 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio throw new Error(localize('worktreeCleanup.alreadyScheduled', "Cleanup is already scheduled for a selected worktree. Refresh its status before trying again.")); } - const selectedBytes = getWorktreeCleanupDiskUsage(selected); const worktreeCount = selected.reduce((total, candidate) => total + candidate.worktreeCount, 0); const confirmation = await this.dialogService.confirm({ message: force @@ -777,10 +873,8 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio detail: force ? localize('worktreeCleanup.forceDetail', "This permanently deletes the selected worktrees and all uncommitted changes, including ignored and untracked files, without saving them. This cannot be undone. Worktrees will be removed even if another session or chat is using them or their branch changed since they were listed. Those sessions or chats may stop working. Committed changes, branches, and session history are kept.") : selected.some(candidate => candidate.unlinkedWorktree) - ? localize('worktreeCleanup.confirm.unlinkedDetail', "Selected sessions will be marked as done. Worktrees with no matching session are removed only if the host verifies they are unused. Uncommitted changes are saved to their branch before removal; branches are kept. Ignored files are deleted. No session history will be created for these worktrees.") - : selectedBytes === undefined - ? localize('worktreeCleanup.confirm.unmeasuredDetail', "This schedules worktree cleanup and marks the selected sessions as done. Disk usage is not measured for sessions already marked as done. You can restore a session later to recreate its worktree.") - : localize('worktreeCleanup.confirm.diskUsageDetail', "Estimated disk usage: {0}. Actual freed space may be lower. The selected sessions will be marked as done. You can restore a session later to recreate its worktree.", ByteSize.formatSize(selectedBytes)), + ? localize('worktreeCleanup.confirm.managedDetail', "Sessions will be marked as done. Changes are saved to their branches; ignored files are deleted. Worktrees without a session have no session history to restore.") + : localize('worktreeCleanup.confirm.sessionDetail', "Sessions will be marked as done. Changes are saved to their branches; ignored files are deleted. You can restore sessions later."), primaryButton: force ? localize('worktreeCleanup.forcePrimary', "Force Remove") : localize('worktreeCleanup.confirm.primary', "Clean Up"), }); if (!confirmation.confirmed) { @@ -795,12 +889,7 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio onProgress?.({ state: 'started' }); const failures: string[] = []; let failedWorktrees = 0; - await this.progressService.withProgress({ - location: ProgressLocation.Notification, - title: worktreeCount === 1 - ? localize('worktreeCleanup.cleaning.one', "Scheduling cleanup for 1 agent session worktree...") - : localize('worktreeCleanup.cleaning.many', "Scheduling cleanup for {0} agent session worktrees...", worktreeCount), - }, async progress => { + const schedule = async (progress: IProgress<IProgressStep>) => { let completedWorktrees = 0; for (const candidate of selected) { const id = getWorktreeCleanupId(candidate); @@ -809,7 +898,7 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio continue; } try { - if (force && candidate.session && !candidate.session.isArchived.get()) { + if (force && getWorktreeCleanupSessions(candidate).some(session => !session.isArchived.get())) { throw new Error(localize('worktreeCleanup.forceNotArchived', "Only sessions marked as done can have their worktrees forcibly removed.")); } if (candidate.unlinkedWorktree) { @@ -820,16 +909,39 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio await this.sessionsManagementService.cleanupManagedWorktree(candidate.unlinkedWorktree, force || undefined); this._unlinkedWorktrees = this._unlinkedWorktrees.map(worktree => getWorktreeCleanupId(worktree) === getWorktreeCleanupId(candidate) ? { ...worktree, cleanupStatus: { state: 'pending' } } : worktree); - } else if (candidate.session.isArchived.get()) { - const result = await this.sessionsManagementService.sessionWorktreeCleanup?.(candidate.session, true, force || undefined); - if (!result) { + } else { + const sessions = getWorktreeCleanupSessions(candidate); + const alreadyArchived = sessions.every(session => session.isArchived.get()); + for (const session of sessions) { + if (isCancelled()) { + break; + } + await this.sessionsManagementService.prepareSessionWorktreeCleanup(session); + } + for (const session of sessions) { + if (isCancelled()) { + break; + } + if (!session.isArchived.get()) { + await this.sessionsManagementService.archiveSession(session); + } + } + if (!isCancelled() && this.sessionsManagementService.sessionWorktreeCleanup) { + for (const session of sessions) { + if (isCancelled()) { + break; + } + const result = await this.sessionsManagementService.sessionWorktreeCleanup(session, true, force || undefined); + if (!result || (!force && result.state === 'unknown' && await this.sessionsManagementService.sessionWorktreeExists?.(session) !== false)) { + throw new Error(localize('worktreeCleanup.notScheduled', "Worktree cleanup was not confirmed. Refresh the inventory and try again.")); + } + this._lastMeasuredWorktrees = this._lastMeasuredWorktrees?.map(worktree => getWorktreeCleanupId(worktree) === getWorktreeCleanupId(candidate) + ? { ...worktree, cleanupStatus: result, cleanupStatusError: undefined } + : worktree); + } + } else if (alreadyArchived) { throw new Error(localize('worktreeCleanup.retryUnavailable', "Retrying worktree cleanup is unavailable for this session.")); } - this._lastMeasuredWorktrees = this._lastMeasuredWorktrees?.map(worktree => worktree.session.sessionId === candidate.session?.sessionId - ? { ...worktree, cleanupStatus: result, cleanupStatusError: undefined } - : worktree); - } else { - await this.sessionsManagementService.archiveSession(candidate.session); } } catch (error) { const message = getErrorMessage(error); @@ -850,11 +962,21 @@ export class SessionWorktreeCleanupService extends Disposable implements ISessio onProgress?.({ state: 'scheduled', candidate }); completedWorktrees += candidate.worktreeCount; progress.report({ - increment: candidate.worktreeCount / worktreeCount * 100, - message: localize('worktreeCleanup.cleaningProgress', "scheduled {0} of {1} worktrees", completedWorktrees, worktreeCount), + increment: candidate.worktreeCount, + message: localize('worktreeCleanup.cleaningProgress', "{0} of {1} worktrees scheduled", completedWorktrees, worktreeCount), }); } - }); + }; + if (onProgress) { + await schedule(Progress.None); + } else { + await this.progressService.withProgress({ + location: ProgressLocation.Notification, + title: localize('worktreeCleanup.cleaning', "Scheduling worktree cleanup..."), + total: worktreeCount, + delay: 300, + }, schedule); + } this._lastScanAt = 0; if (failures.length > 0) { throw new Error(localize('worktreeCleanup.schedulingFailed', "Couldn't schedule cleanup for {0} worktrees.\n{1}", failedWorktrees, failures.join('\n'))); diff --git a/src/vs/workbench/contrib/sessions/browser/sessionScope.ts b/src/vs/workbench/contrib/sessions/browser/sessionScope.ts new file mode 100644 index 000000000000..9893121c2e73 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionScope.ts @@ -0,0 +1,213 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter, Event } from '../../../../base/common/event.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { ResourceSet } from '../../../../base/common/map.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { autorun, IReader, observableSignal } from '../../../../base/common/observable.js'; +import { extUriBiasedIgnorePathCase } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { getRepositoryRootFromWorktree } from '../../../../platform/agentHost/common/worktreePaths.js'; +import { GITHUB_REMOTE_FILE_SCHEME, ISession } from '../../../services/sessions/common/session.js'; +import { ISessionChangeEvent, ISessionsListingScope } from '../common/sessionsProvider.js'; + +/** Whether `uri` is on GitHub (`github-remote-file://github/<owner>/<repo>/<branch>/...`) in one of `repositories`. */ +function isGitHubRepositoryOf(uri: URI, repositories: ReadonlySet<string>): boolean { + if (!repositories.size || uri.scheme !== GITHUB_REMOTE_FILE_SCHEME || uri.authority !== 'github') { + return false; + } + const [owner, repo] = uri.path.split('/').filter(segment => segment.length > 0); + return !!owner && !!repo && repositories.has(`${owner}/${repo}`.toLowerCase()); +} + +/** Whether `workingDirectory` is a worktree that VS Code created for one of `repositories`, by its path. */ +function isWorktreeOf(workingDirectory: URI, repositories: ResourceSet): boolean { + const repository = workingDirectory.scheme === Schemas.file ? getRepositoryRootFromWorktree(workingDirectory) : undefined; + return !!repository && repositories.has(repository); +} + +/** + * The sessions a provider lists in a {@link ISessionsListingScope}, out of all of its sessions, and their changes. It follows + * the scope, the provider's changes and the sessions' workspaces, such as one that hydrates into the scope. + * + * A session that leaves the scope is reported as changed, not removed, as when its provider goes away: a removal means a + * deletion to consumers, which clean up after it. Removals of the provider's sessions are always reported, also of those + * the scope hides, as consumers can show them by their resource. + */ +export class SessionsListingScopeFilter extends Disposable { + + private readonly _onDidChangeSessions = this._register(new Emitter<ISessionChangeEvent>()); + readonly onDidChangeSessions: Event<ISessionChangeEvent> = this._onDidChangeSessions.event; + + private _listed = new Map<string, ISession>(); + /** Every session as of the last match to the scope, which the scope follows: a different object of an ID, such as a replacement, is matched again. */ + private _known = new Map<string, ISession>(); + private _initialized = false; + private readonly _pendingChanges: ISessionChangeEvent[] = []; + private readonly _allSessionsChanged = observableSignal(this); + + constructor( + scope: ISessionsListingScope, + getAllSessions: () => ISession[], + onDidChangeAllSessions: Event<ISessionChangeEvent>, + ) { + super(); + + this._register(onDidChangeAllSessions(e => { + if (this._initialized && !this._pendingChanges.length && !e.added.length && !e.removed.length && e.changed.length && e.changed.every(session => this._known.get(session.sessionId) === session)) { + // Changes of sessions only, such as of their status as they stream: what they are listed by, their workspaces, + // the scope follows itself, so the sessions it lists stay as they are + const changed = e.changed.flatMap(session => this._listed.get(session.sessionId) ?? []); + if (changed.length) { + this._onDidChangeSessions.fire({ added: [], removed: [], changed }); + } + return; + } + this._pendingChanges.push(e); + this._allSessionsChanged.trigger(undefined); + })); + this._register(autorun(reader => { + this._allSessionsChanged.read(reader); + const folders = scope.folders.read(reader); + const repositories = scope.repositories.read(reader); + const gitHubRepositories = scope.gitHubRepositories?.read(reader) ?? []; + const sessions = getAllSessions(); + this._known = new Map(sessions.map(session => [session.sessionId, session])); + const inScope = folders.length ? this._getSessionsInScope(sessions, folders, reader, repositories, gitHubRepositories) : undefined; + const listed = new Map<string, ISession>(); + for (const session of sessions) { + if (!inScope || inScope.has(session)) { + listed.set(session.sessionId, session); + } + } + this._update(listed, this._pendingChanges.splice(0)); + })); + } + + /** + * Matches every session to the scope again, at once. A provider that replaces a session, such as a draft that graduates + * into the session it committed, can drop the one it replaced without a change: it calls this before it reports the + * replacement, so that who learns of the replacement finds the sessions the scope lists as they are now. + */ + rematch(): void { + this._pendingChanges.push({ added: [], removed: [], changed: [] }); + this._allSessionsChanged.trigger(undefined); + } + + /** + * The `sessions` in the scope of `scopeFolders`, such as the folders of an editor window's workspace: the sessions with + * a folder that is, or is inside, a scope folder, and the sessions of the same git repositories, such as its worktrees. + * Only the metadata the providers already report is read, comparing whole URIs, so a session of another host never + * matches a local folder. A repository is known from a scope folder itself, from a session working in the scope, from + * `scopeRepositories`, and from the path of a worktree that VS Code created (`<repository>.worktrees/<name>`), as the + * Agent Host names it: for an opened worktree, also before any session works in it, and for sessions whose provider + * has not reported their repository yet. `scopeRepositories` are the repositories the scope folders are + * known to be checkouts of, such as the main checkout of an open worktree. `scopeGitHubRepositories`, as lowercase + * `owner/repo`, are the GitHub repositories of their `origin`: a session working in one of them on GitHub, on any branch, + * such as a Copilot Cloud session, is in the scope too. A workspace-less quick chat, by its own `isQuickChat` flag, is in + * every scope: a session whose workspace is not known yet is not, as it may still hydrate into another folder. The + * result follows the sessions' workspaces and quick-chat flags through `reader`. + */ + private _getSessionsInScope(sessions: readonly ISession[], scopeFolders: readonly URI[], reader: IReader, scopeRepositories: readonly URI[], scopeGitHubRepositories: readonly string[]): ReadonlySet<ISession> { + const extUri = extUriBiasedIgnorePathCase; + const gitHubRepositories = new Set(scopeGitHubRepositories.map(repository => repository.toLowerCase())); + const isInScope = (uri: URI | undefined) => !!uri && (scopeFolders.some(folder => extUri.isEqualOrParent(uri, folder)) || isGitHubRepositoryOf(uri, gitHubRepositories)); + const repositories = new ResourceSet([...scopeFolders, ...scopeRepositories], uri => extUri.getComparisonKey(uri)); + for (const scopeFolder of scopeFolders) { + const repository = scopeFolder.scheme === Schemas.file ? getRepositoryRootFromWorktree(scopeFolder) : undefined; + if (repository) { + repositories.add(repository); + } + } + const included = new Set<ISession>(); + for (const session of sessions) { + if (session.isQuickChat?.read(reader)) { + included.add(session); + continue; + } + for (const folder of session.workspace.read(reader)?.folders ?? []) { + if (isInScope(folder.workingDirectory) || isInScope(folder.root) || isInScope(folder.gitRepository?.workTreeUri)) { + included.add(session); + if (folder.gitRepository) { + repositories.add(folder.gitRepository.uri); + } + } + } + } + for (const session of sessions) { + if (!included.has(session) && session.workspace.read(reader)?.folders.some(folder => repositories.has(folder.root) || (!!folder.gitRepository && repositories.has(folder.gitRepository.uri)) || isWorktreeOf(folder.workingDirectory, repositories))) { + included.add(session); + } + } + return included; + } + + /** The sessions the scope lists. */ + getSessions(): ISession[] { + return [...this._listed.values()]; + } + + /** + * Reports how the sessions it lists differ from `previous`, those listed before it, such as without a scope or in an + * earlier one: a session it lists that was not listed as added, and one no longer listed as changed, as when it leaves + * the scope. + */ + announceFrom(previous: readonly ISession[]): void { + const previousIds = new Set(previous.map(session => session.sessionId)); + const added = [...this._listed.values()].filter(session => !previousIds.has(session.sessionId)); + const changed = previous.filter(session => !this._listed.has(session.sessionId)); + if (added.length || changed.length) { + this._onDidChangeSessions.fire({ added, removed: [], changed }); + } + } + + private _update(listed: Map<string, ISession>, changes: readonly ISessionChangeEvent[]): void { + const previous = this._listed; + this._listed = listed; + if (!this._initialized) { + this._initialized = true; + return; + } + + const added = new Map<string, ISession>(); + const removed = new Map<string, ISession>(); + const changed = new Map<string, ISession>(); + for (const change of changes) { + for (const session of change.removed) { + if (!listed.has(session.sessionId)) { + removed.set(session.sessionId, session); + } + } + for (const session of change.added) { + const listedSession = listed.get(session.sessionId); + if (listedSession) { + added.set(session.sessionId, listedSession); + } + } + } + for (const [sessionId, session] of listed) { + if (!previous.has(sessionId)) { + added.set(sessionId, session); + } + } + for (const [sessionId, session] of previous) { + if (!listed.has(sessionId) && !removed.has(sessionId)) { + changed.set(sessionId, session); + } + } + for (const change of changes) { + for (const session of change.changed) { + const listedSession = listed.get(session.sessionId); + if (listedSession && !added.has(session.sessionId)) { + changed.set(session.sessionId, listedSession); + } + } + } + if (added.size || removed.size || changed.size) { + this._onDidChangeSessions.fire({ added: [...added.values()], removed: [...removed.values()], changed: [...changed.values()] }); + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsConfiguration.ts b/src/vs/workbench/contrib/sessions/browser/sessionsConfiguration.ts new file mode 100644 index 000000000000..fe4fa7e07afb --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionsConfiguration.ts @@ -0,0 +1,107 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../nls.js'; +import { ConfigurationScope, IConfigurationPropertySchema } from '../../../../platform/configuration/common/configurationRegistry.js'; +import { SESSIONS_LIST_INDENT_ITEMS_SETTING, 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 { SESSIONS_MARK_AS_DONE_CONFETTI_SETTING } from '../../../../platform/chat/common/sessionArchiveActions.js'; +import { AutomationSessionsListMode, ExternalSessionApplicationBadgeMode, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SESSIONS_LIST_INBOX_ENABLED_SETTING, SESSIONS_LIST_SHOW_AUTOMATION_SESSIONS_SETTING, USE_WORKTREE_SETTING } from '../common/sessionConfig.js'; +import { IStringDictionary } from '../../../../base/common/collections.js'; + +/** The settings of the sessions list and of the sessions it opens. */ +export const sessionsListConfigurationProperties = { + [SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING]: { + type: 'boolean', + tags: ['preview'], + description: localize('sessions.list.groupExternalSessions', "Controls whether external sessions are shown in a separate External section instead of workspace or time groups. Pinned sessions and custom groups keep their placement."), + default: false, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_INBOX_ENABLED_SETTING]: { + type: 'boolean', + tags: ['experimental'], + description: localize('sessions.list.inboxEnabled', "Uses Inbox Mode as the default Sessions list grouping when no grouping has been chosen. Inbox Mode is always available in the Grouping menu. Explicit grouping choices are preserved."), + default: false, + }, + [SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING]: { + type: 'string', + tags: ['experimental'], + enum: [ + ExternalSessionApplicationBadgeMode.Off, + ExternalSessionApplicationBadgeMode.Title, + ExternalSessionApplicationBadgeMode.Details, + ], + enumDescriptions: [ + localize('sessions.list.externalApplicationBadge.off', "Do not show the creating application."), + localize('sessions.list.externalApplicationBadge.title', "Show the creating application next to the session title."), + localize('sessions.list.externalApplicationBadge.details', "Show the creating application first in the session details."), + ], + description: localize('sessions.list.externalApplicationBadge', "Controls where sessions created in an application other than VS Code show the creating application."), + default: ExternalSessionApplicationBadgeMode.Title, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING]: { + type: 'boolean', + tags: ['experimental', 'advanced'], + description: localize('sessions.list.externalApplicationBadgeShowFrom', "Controls whether session application badges include the word 'From'."), + default: false, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_SHOW_EMPTY_DEFAULT_GROUPS_SETTING]: { + type: 'boolean', + tags: ['preview'], + description: localize('sessions.list.showEmptyDefaultGroups', "Controls whether the Chats group is shown in the sessions list even when it is empty."), + default: true, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_SHOW_UNREAD_IN_COLLAPSED_SECTIONS_SETTING]: { + type: 'boolean', + tags: ['preview'], + description: localize('sessions.list.showUnreadInCollapsedSections', "Controls whether collapsed sections in the sessions list show needs-attention, CI-failure, or unread indicators for the unarchived sessions they contain."), + default: false, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_SHOW_ARCHIVED_BY_DEFAULT_SETTING]: { + type: 'boolean', + tags: ['experimental', 'advanced'], + description: localize('sessions.list.showArchivedByDefault', "Controls whether the Done or Archived section is shown by default in the sessions list. This default is ignored after the corresponding filter is changed."), + default: true, + scope: ConfigurationScope.APPLICATION, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_SHOW_AUTOMATION_SESSIONS_SETTING]: { + type: 'string', + tags: ['experimental', 'advanced'], + enum: [AutomationSessionsListMode.Always, AutomationSessionsListMode.AfterReply, AutomationSessionsListMode.Never], + enumDescriptions: [ + localize('sessions.list.showAutomationSessions.always', "Show every automation session in the sessions list."), + localize('sessions.list.showAutomationSessions.afterReply', "Show an automation session in the sessions list once you send a message in it."), + localize('sessions.list.showAutomationSessions.never', "Show automation sessions only in Automations."), + ], + description: localize('sessions.list.showAutomationSessions', "Controls when automation sessions automatically also appear in the sessions list. They always remain in Automations. Use Show in Sessions List or Hide from Sessions List in a session's context menu to override this for that session."), + default: AutomationSessionsListMode.AfterReply, + experiment: { mode: 'auto' } + }, + [SESSIONS_LIST_INDENT_ITEMS_SETTING]: { + type: 'boolean', + tags: ['experimental', 'advanced'], + description: localize('sessions.list.indentItems', "Controls whether sessions and other rows in the sessions list are indented below their section header to show the list's hierarchy."), + default: false, + experiment: { mode: 'auto' } + }, + [SESSIONS_MARK_AS_DONE_CONFETTI_SETTING]: { + type: 'boolean', + description: localize('sessions.markAsDoneConfetti', "Controls whether a confetti animation is shown when marking a session as done."), + default: true, + experiment: { mode: 'auto' } + // https://github.com/microsoft/vscode/issues/335801 + }, + [USE_WORKTREE_SETTING]: { + type: 'boolean', + default: false, + scope: ConfigurationScope.APPLICATION, + description: localize('sessions.useWorktree', "Controls whether New Worktree is checked for a workspace that has not started a session before. Each workspace otherwise uses the choice from its last started session."), + }, +} satisfies IStringDictionary<IConfigurationPropertySchema>; diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsListModelService.ts b/src/vs/workbench/contrib/sessions/browser/sessionsListModelService.ts index 33d3f9357e8f..8718fe244df6 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionsListModelService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionsListModelService.ts @@ -16,6 +16,7 @@ import { IConfigurationService } from '../../../../platform/configuration/common import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { agentSessionNeedsInputForeground } from '../../../common/agentsColors.js'; import { AutomationSessionsListMode, SESSIONS_LIST_SHOW_AUTOMATION_SESSIONS_SETTING } from '../common/sessionConfig.js'; import { ISession, SessionStatus } from '../../../services/sessions/common/session.js'; import { ISessionsManagementService } from '../common/sessionsManagement.js'; @@ -347,7 +348,13 @@ export class SessionsListModelService extends Disposable implements ISessionsLis if (state) { return state.kind !== 'resumed' && isSessionInboxStateCurrent(state, session, Date.now(), reader, attention) ? state : undefined; } - return attention?.isHistoricalCompletion ? { kind: 'done', activity: getSessionInboxActivity(session, reader), notificationIds: attention.notificationIds } : undefined; + if (attention?.isHistoricalCompletion) { + const unreadToday = !session.isRead.read(reader) && session.updatedAt.read(reader).toDateString() === new Date().toDateString(); + if (!unreadToday) { + return { kind: 'done', activity: getSessionInboxActivity(session, reader), notificationIds: attention.notificationIds }; + } + } + return undefined; } setInboxState(sessions: readonly ISession[], action: SessionInboxAction): () => void { @@ -658,7 +665,7 @@ export class SessionsListModelService extends Disposable implements ISessionsLis case SessionStatus.InProgress: return { ...Codicon.sessionInProgress, color: themeColorFromId('textLink.foreground') }; case SessionStatus.NeedsInput: - return { ...Codicon.reportQuestion, color: themeColorFromId('list.warningForeground') }; + return { ...Codicon.reportQuestion, color: themeColorFromId(agentSessionNeedsInputForeground) }; case SessionStatus.Error: return { ...Codicon.error, color: themeColorFromId('errorForeground') }; default: diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsManagementService.ts b/src/vs/workbench/contrib/sessions/browser/sessionsManagementService.ts index fd3dc1399e27..eeef0e451646 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionsManagementService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionsManagementService.ts @@ -923,6 +923,9 @@ export class SessionsManagementService extends Disposable implements ISessionsMa } const isNewSessionRequest = session.status.get() === SessionStatus.Untitled; + if (isNewSessionRequest && !provider.sessionTypes.some(type => type.id === session.sessionType)) { + throw new Error(localize('newSession.typeUnavailable', "{0} is no longer available for new sessions. Choose an available agent to try again.", provider.label)); + } const inFlightRequest = isNewSessionRequest ? this.trackInFlightNewSessionRequest(session, options) : undefined; if (options.background) { @@ -1452,7 +1455,7 @@ export class SessionsManagementService extends Disposable implements ISessionsMa if (!provider) { throw new Error(`Sessions provider '${session.providerId}' not found`); } - await this._sendRequestInBackground(provider, session, chat, { ...options, background: true }); + await this._sendRequestInBackground(provider, session, chat, { ...options, background: true, requireConnected: true }); } /** @@ -1526,6 +1529,14 @@ export class SessionsManagementService extends Disposable implements ISessionsMa return provider?.supportsForceWorktreeCleanup === true; } + async prepareSessionWorktreeCleanup(session: ISession): Promise<void> { + const provider = this._getProvider(session); + if (!provider?.prepareSessionWorktreeCleanup) { + throw new Error(localize('worktreeCleanupPreparationUnavailable', "This session provider does not support preparing worktree cleanup.")); + } + await provider.prepareSessionWorktreeCleanup(session.sessionId); + } + async sessionWorktreeCleanup(session: ISession, retry: boolean, force?: boolean) { const provider = this._getProvider(session); if (retry && !provider?.sessionWorktreeCleanup) { diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsNavigationService.ts b/src/vs/workbench/contrib/sessions/browser/sessionsNavigationService.ts new file mode 100644 index 000000000000..96be27affeb3 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionsNavigationService.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IObservable } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { ISessionGridPane } from '../../../services/sessions/browser/sessionGridPane.js'; +import { ISessionHost } from '../../../services/sessions/browser/sessionHost.js'; +import { IChat, ISession } from '../../../services/sessions/common/session.js'; +import type { IOpenChatOptions, IOpenSessionOptions } from './sessionsService.js'; + +export const ISessionsNavigationService = createDecorator<ISessionsNavigationService>('sessionsNavigationService'); + +/** + * What the sessions list and the session hosts need from the window that shows sessions: where its sessions and chats + * open, and which of them it shows. The Agents window shows them in its grid; another window, such as an editor window + * with the Sessions view, shows them in its own way. + */ +export interface ISessionsNavigationService { + readonly _serviceBrand: undefined; + + /** The host of the window's main surface, whose session the sessions list reveals. */ + readonly mainWindowHost: ISessionHost; + + /** The panes that show sessions, such as the slots of a grid. */ + readonly slotPanes: IObservable<readonly ISessionGridPane[]>; + + /** Opens `sessionResource` and shows it. */ + openSession(sessionResource: URI, options?: IOpenSessionOptions): Promise<void>; + + /** Opens `session` beside the sessions the window shows. */ + openSessionToSide(session: ISession, options?: IOpenSessionOptions): Promise<void>; + + /** Opens `chatUri` of `session` and shows it. */ + openChat(session: ISession, chatUri: URI, options?: IOpenChatOptions): Promise<void>; + + /** Opens `chatResource` of `session` beside what the window shows. */ + openChatToSide(session: ISession, chatResource: URI, options?: { readonly preserveFocus?: boolean }): Promise<void>; + + /** Whether `session` can open, such as after the user trusts its folders. */ + canOpenSession(session: ISession): Promise<boolean>; + + /** Moves focus into what the window shows of its active session. */ + focusActiveSession(): void; + + /** Stops showing `chat` of `session`, which was archived, where the window shows it as an open chat. */ + closeArchivedChat(session: ISession, chat: IChat): Promise<void>; +} diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsService.ts b/src/vs/workbench/contrib/sessions/browser/sessionsService.ts index 0ed808c1a114..f01fb8739462 100644 --- a/src/vs/workbench/contrib/sessions/browser/sessionsService.ts +++ b/src/vs/workbench/contrib/sessions/browser/sessionsService.ts @@ -31,7 +31,7 @@ import { SessionsRecencyHistory } from '../../../services/sessions/browser/sessi import { VisibleSessions } from '../../../services/sessions/browser/visibleSessions.js'; import { IContextKey, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { ISessionsPartService, SessionGridRequest } from '../../../services/sessions/browser/sessionsPartService.js'; -import { IChatHostClosedChat, IChatHostOpenerService } from '../../../services/sessions/browser/chatHostOpener.js'; +import { IChatHostClosedChat, IChatHostOpener, IChatHostOpenerService } from '../../../services/sessions/browser/chatHostOpener.js'; import { ICustomViewService } from './customView.js'; import { IWindowCanvasService } from './windowCanvas.js'; import { IsNewChatSessionContext } from '../common/contextkeys.js'; @@ -153,7 +153,10 @@ export interface INavigationOrigin { readonly from?: ISessionHost; } -export interface IOpenChatOptions extends IOpenSessionOptions, INavigationOrigin { } +export interface IOpenChatOptions extends IOpenSessionOptions, INavigationOrigin { + /** The chat this one was started from. When another surface, such as a chat window, shows it, the chat opens beside it there. */ + readonly referenceChatResource?: URI; +} export interface IOpenNewChatInSessionOptions extends ICreateNewChatInSessionOptions, INavigationOrigin { } @@ -1233,6 +1236,12 @@ export class SessionsService extends Disposable implements ISessionsService { await opener.reveal(chatUri, { preserveFocus: options?.preserveFocus }); return; } + const referenceOpener = this._getOpenerShowingReference(options?.referenceChatResource); + if (referenceOpener) { + navigation.complete(); + await referenceOpener.openBeside(chatUri, options!.referenceChatResource!, { preserveFocus: options?.preserveFocus }); + return; + } if (options?.source) { await this.sessionOpenTelemetryService.withOpenRequest(options.source, token, async telemetryAttempt => { this.sessionOpenTelemetryService.sessionResolved( @@ -1883,6 +1892,14 @@ export class SessionsService extends Disposable implements ISessionsService { } } + /** + * Returns the chat host opener, such as a chat window, that shows the chat a new chat was started from, so the new chat + * opens in that host rather than in the main window. + */ + private _getOpenerShowingReference(referenceChatResource: URI | undefined): IChatHostOpener | undefined { + return referenceChatResource ? this.chatHostOpenerService.getOpenerOf(referenceChatResource) : undefined; + } + private async _showChatToSide(session: ISession, chatResource: URI, options?: { preserveFocus?: boolean; referenceChatResource?: URI }): Promise<void> { // A chat another surface shows, such as a chat window, is revealed there; a subagent chat opens beside its reference // chat where that surface shows it. @@ -1892,8 +1909,8 @@ export class SessionsService extends Disposable implements ISessionsService { return; } const reference = options?.referenceChatResource; - const referenceShownBy = reference && this.chatHostOpenerService.getOpenerOf(reference); - if (reference && referenceShownBy && session.chats.get().find(candidate => this.uriIdentityService.extUri.isEqual(candidate.resource, chatResource))?.origin?.kind === ChatOriginKind.Tool) { + const referenceShownBy = this._getOpenerShowingReference(reference); + if (reference && referenceShownBy) { await referenceShownBy.openBeside(chatResource, reference, options); return; } @@ -2774,7 +2791,9 @@ export class SessionsService extends Disposable implements ISessionsService { const target = targets[idx]; let session: ISession | null | undefined; if (!target.resource) { - session = null; // empty new-session slot + const draft = this.sessionsManagementService.newSession.get(); + // Workspace restoration can populate the composer before the persisted grid is applied. + session = draft && this._slotSessions.get().some(visible => visible?.sessionId === draft.sessionId) ? draft : null; } else if (idx === activeIdx) { session = activeSession; } else { diff --git a/src/vs/workbench/contrib/sessions/browser/sessionsServiceNavigationService.ts b/src/vs/workbench/contrib/sessions/browser/sessionsServiceNavigationService.ts new file mode 100644 index 000000000000..b083cfc8e263 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/sessionsServiceNavigationService.ts @@ -0,0 +1,69 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IObservable } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ISessionGridPane } from '../../../services/sessions/browser/sessionGridPane.js'; +import { ISessionHost } from '../../../services/sessions/browser/sessionHost.js'; +import { IChat, ISession } from '../../../services/sessions/common/session.js'; +import { ISessionsPartService } from '../../../services/sessions/browser/sessionsPartService.js'; +import { isEqual } from '../../../../base/common/resources.js'; +import { ISessionsNavigationService } from './sessionsNavigationService.js'; +import { IOpenChatOptions, IOpenSessionOptions, ISessionsService } from './sessionsService.js'; + +/** The navigation of the Agents window: its grid, through {@link ISessionsService}. */ +export class SessionsServiceNavigationService implements ISessionsNavigationService { + + declare readonly _serviceBrand: undefined; + + constructor( + @ISessionsService private readonly sessionsService: ISessionsService, + @ISessionsPartService private readonly sessionsPartService: ISessionsPartService, + ) { } + + get mainWindowHost(): ISessionHost { + return this.sessionsService.gridHost; + } + + get slotPanes(): IObservable<readonly ISessionGridPane[]> { + return this.sessionsService.slotPanes; + } + + openSession(sessionResource: URI, options?: IOpenSessionOptions): Promise<void> { + return this.sessionsService.openSession(sessionResource, options); + } + + openSessionToSide(session: ISession, options?: IOpenSessionOptions): Promise<void> { + return this.sessionsService.openSessionToSide(session, options); + } + + openChat(session: ISession, chatUri: URI, options?: IOpenChatOptions): Promise<void> { + return this.sessionsService.openChat(session, chatUri, options); + } + + openChatToSide(session: ISession, chatResource: URI, options?: { readonly preserveFocus?: boolean }): Promise<void> { + return this.sessionsService.openChatToSide(session, chatResource, options); + } + + canOpenSession(session: ISession): Promise<boolean> { + return this.sessionsService.canOpenSession(session); + } + + focusActiveSession(): void { + this.sessionsService.focusActiveSession(); + } + + async closeArchivedChat(session: ISession, chat: IChat): Promise<void> { + // The chat leaves the grid's active pane when that pane shows it. + const activePane = this.sessionsPartService.getActiveSessionView()?.pane.get(); + const activeSession = activePane?.session.get(); + if (activePane && activeSession?.sessionId === session.sessionId) { + const openChat = activePane.tabs.openChats.get().find(candidate => isEqual(candidate.resource, chat.resource)); + if (openChat) { + await this.sessionsService.closeChat(activeSession, openChat); + } + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/views/pendingSessions.ts b/src/vs/workbench/contrib/sessions/browser/views/pendingSessions.ts new file mode 100644 index 000000000000..86eab859a01e --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/views/pendingSessions.ts @@ -0,0 +1,185 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as DOM from '../../../../../base/browser/dom.js'; +import { Gesture } from '../../../../../base/browser/touch.js'; +import { HighlightedLabel } from '../../../../../base/browser/ui/highlightedlabel/highlightedLabel.js'; +import { ITreeNode, ITreeRenderer } from '../../../../../base/browser/ui/tree/tree.js'; +import { ActionRunner, IAction, Separator, toAction } from '../../../../../base/common/actions.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { createMatches, FuzzyScore } from '../../../../../base/common/filters.js'; +import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { basename, getComparisonKey } from '../../../../../base/common/resources.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { localize } from '../../../../../nls.js'; +import { WorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { asCssVariable } from '../../../../../platform/theme/common/colorUtils.js'; +import { UNKNOWN_SESSION_APPLICATION_ID } from '../../../../services/sessions/common/sessionApplication.js'; +import { SessionsListFilters } from './sessionsListFilters.js'; +import type { SessionListItem } from './sessionsList.js'; + +/** Unsent work owned by the caller, never a provider-created session. */ +export interface IPendingSessionItem { + readonly pendingSession: true; + readonly id: string; + readonly kind: 'draft' | 'scheduled'; + readonly title: string; + readonly description: string; + readonly folderUri?: URI; + readonly providerId?: string; + readonly sessionType?: string; + readonly harness?: string; + readonly environmentId?: string; + readonly applicationId?: string; + /** Explicitly identifies No Workspace, rather than unavailable workspace metadata. */ + readonly isQuickChat?: boolean; + readonly actions: readonly IAction[]; + open(): Promise<void>; +} + +export interface IPendingSessionSection { + readonly id: 'drafts' | 'scheduled'; + readonly label: string; + readonly items: readonly IPendingSessionItem[]; +} + +export function isPendingSessionItem(item: SessionListItem): item is IPendingSessionItem { + return 'pendingSession' in item && item.pendingSession === true; +} + +export function matchesPendingSession(item: IPendingSessionItem, filters: SessionsListFilters, inbox: boolean, providerIds?: readonly string[]): boolean { + if (providerIds && (!item.providerId || !providerIds.includes(item.providerId))) { + return false; + } + if (item.harness && filters.isExcluded({ kind: 'harness', id: item.harness }) + || !inbox && item.environmentId && filters.isExcluded({ kind: 'environment', id: item.environmentId }) + || item.applicationId && item.applicationId !== UNKNOWN_SESSION_APPLICATION_ID && item.environmentId && filters.isExcluded({ kind: 'application', environment: item.environmentId, id: item.applicationId })) { + return false; + } + if (inbox) { + const { environment, workspace } = filters.inboxScope; + if (environment && item.environmentId !== environment.id) { + return false; + } + if (workspace === 'none') { + return item.isQuickChat === true; + } + if (workspace) { + return item.isQuickChat !== true && item.environmentId === workspace.environment + && !!item.folderUri && getComparisonKey(item.folderUri) === workspace.resource; + } + } + return true; +} + +export function getPendingSessionActions(item: IPendingSessionItem, multiple: boolean): IAction[] { + const actions = item.actions.length > 0 ? item.actions : [toAction({ + id: 'sessions.pending.open', + label: localize('openPendingSession', "Open"), + run: () => item.open(), + })]; + return actions.map(action => action instanceof Separator ? action : toAction({ + id: action.id, + label: action.label, + tooltip: action.tooltip, + class: action.class, + checked: action.checked, + enabled: !multiple && action.enabled, + run: () => !multiple && action.enabled ? action.run() : undefined, + })); +} + +export function getPendingSessionAriaLabel(item: IPendingSessionItem): string { + const description = getPendingSessionDescription(item); + return item.kind === 'draft' + ? description + ? localize('pendingDraftAria', "{0}, draft, {1}", item.title, description) + : localize('pendingDraftWithoutDescriptionAria', "{0}, draft", item.title) + : localize('pendingScheduledAria', "{0}, scheduled, {1}", item.title, description); +} + +function getPendingSessionDescription(item: IPendingSessionItem): string { + return item.kind === 'scheduled' && item.folderUri + ? localize('pendingScheduledWorkspace', "{0} - {1}", basename(item.folderUri), item.description) + : item.description; +} + +interface IPendingSessionTemplate { + readonly icon: HTMLElement; + readonly scheduledIndicator: HTMLElement; + readonly title: HighlightedLabel; + readonly description: HTMLElement; + readonly compactDescription: HTMLElement; + readonly toolbar: WorkbenchToolBar; + readonly toolbarContainer: HTMLElement; + readonly disposables: DisposableStore; +} + +export class PendingSessionRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, IPendingSessionTemplate> { + static readonly TEMPLATE_ID = 'pending-session'; + readonly templateId = PendingSessionRenderer.TEMPLATE_ID; + + constructor( + private readonly instantiationService: IInstantiationService, + private readonly showActions: (item: IPendingSessionItem, anchor: HTMLElement) => void, + private readonly onActionError: (error: Error) => void, + ) { } + + renderTemplate(container: HTMLElement): IPendingSessionTemplate { + const disposables = new DisposableStore(); + container.classList.add('session-item'); + const icon = DOM.append(container, DOM.$('.session-icon', { 'aria-hidden': 'true' })); + const main = DOM.append(container, DOM.$('.session-main')); + const titleRow = DOM.append(main, DOM.$('.session-title-row')); + const title = disposables.add(new HighlightedLabel(DOM.append(titleRow, DOM.$('.session-title')))); + const compactDescription = DOM.append(titleRow, DOM.$('.session-compact-hover-description')); + const scheduledIndicator = DOM.append(titleRow, DOM.$(`span.session-scheduled-indicator${ThemeIcon.asCSSSelector(Codicon.clock)}`, { 'aria-hidden': 'true' })); + const toolbarContainer = DOM.append(titleRow, DOM.$('.session-title-toolbar')); + const actionRunner = disposables.add(new ActionRunner()); + disposables.add(actionRunner.onDidRun(event => { + if (event.error) { + this.onActionError(event.error); + } + })); + const toolbar = disposables.add(this.instantiationService.createInstance(WorkbenchToolBar, toolbarContainer, { actionRunner })); + for (const type of ['pointerdown', 'pointerup', 'click', 'dblclick'] as const) { + disposables.add(DOM.addDisposableListener(toolbarContainer, type, e => e.stopPropagation())); + } + disposables.add(Gesture.ignoreTarget(toolbarContainer)); + const description = DOM.append(main, DOM.$('.session-details-row')); + return { icon, scheduledIndicator, title, description, compactDescription, toolbar, toolbarContainer, disposables }; + } + + renderElement(node: ITreeNode<SessionListItem, FuzzyScore>, _index: number, template: IPendingSessionTemplate): void { + const item = node.element; + if (!isPendingSessionItem(item)) { + return; + } + const icon = DOM.$(`span${ThemeIcon.asCSSSelector(Codicon.circleSmallFilled)}`); + icon.style.color = asCssVariable('agentSessionReadIndicator.foreground'); + DOM.reset(template.icon, icon); + template.scheduledIndicator.classList.toggle('visible', item.kind === 'scheduled'); + template.title.set(item.title, createMatches(node.filterData)); + const description = getPendingSessionDescription(item); + template.description.textContent = description; + template.compactDescription.textContent = description; + template.toolbar.setActions(item.kind === 'draft' ? getPendingSessionActions(item, false).filter(action => action.id !== 'sessions.drafts.resume') : [toAction({ + id: 'sessions.pending.actions', + label: localize('pendingSessionActions', "More Actions..."), + class: ThemeIcon.asClassName(Codicon.ellipsis), + run: () => this.showActions(item, template.toolbarContainer), + })]); + } + + disposeElement(_node: ITreeNode<SessionListItem, FuzzyScore>, _index: number, template: IPendingSessionTemplate): void { + template.toolbar.setActions([]); + } + + disposeTemplate(template: IPendingSessionTemplate): void { + template.disposables.dispose(); + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/views/sessionsInboxScope.ts b/src/vs/workbench/contrib/sessions/browser/views/sessionsInboxScope.ts new file mode 100644 index 000000000000..598d984c4c37 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/views/sessionsInboxScope.ts @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../../base/browser/dom.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { createInstantHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Disposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, derived, IObservable, observableSignalFromEvent } from '../../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize } from '../../../../../nls.js'; +import { ActionListItemKind, IActionListItem, IActionListOptions } from '../../../../../platform/actionWidget/browser/actionList.js'; +import { IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; +import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; +import { ISession, ISessionEnvironment } from '../../../../services/sessions/common/session.js'; +import { getCompactCodicon } from '../../../chat/browser/chatIcons.js'; +import { getNoWorkspaceChoicePresentation } from '../chat/noWorkspaceChoice.js'; +import { ENVIRONMENT_PICKER_LIST_OPTIONS } from '../chat/sessionEnvironmentPicker.js'; +import { createSessionPickerToolbar } from '../chat/sessionPickerToolbar.js'; +import { WORKSPACE_PICKER_LIST_OPTIONS } from '../chat/sessionWorkspacePicker.js'; +import { getInboxWorkspaceOptions, getSessionEnvironments, SessionsListFilters } from './sessionsListFilters.js'; + +interface IInboxScopePickerItem { + readonly checked: boolean; + readonly run: () => void; +} + +function getEnvironmentIcon(environment: string): ThemeIcon { + return environment === 'local' ? Codicon.deviceDesktop : environment === 'cloud' ? Codicon.cloud : Codicon.remote; +} + +export class SessionsInboxScope extends Disposable { + readonly element: HTMLElement; + private activeTrigger: HTMLElement | undefined; + + constructor( + container: HTMLElement, + filters: SessionsListFilters, + sessions: IObservable<readonly ISession[]>, + environments: IObservable<readonly ISessionEnvironment[]>, + localEnvironmentIds: IObservable<ReadonlySet<string>>, + @IInstantiationService instantiationService: IInstantiationService, + @IActionWidgetService private readonly actionWidgetService: IActionWidgetService, + ) { + super(); + this.element = dom.append(container, dom.$('.sessions-inbox-scope')); + this._register(toDisposable(() => this.hidePicker())); + const hoverDelegate = this._register(createInstantHoverDelegate()); + const changed = observableSignalFromEvent(this, filters.onDidChange); + this._register(autorun(reader => { + changed.read(reader); + const localIds = localEnvironmentIds.read(reader); + if (filters.inboxScope.environment && localIds.has(filters.inboxScope.environment.id)) { + filters.setInboxEnvironment({ id: 'local', label: localize('environment.local', "This Computer") }); + } + })); + const options = derived(this, reader => { + changed.read(reader); + const catalog = sessions.read(reader); + const localIds = localEnvironmentIds.read(reader); + const scope = filters.inboxScope; + const environmentOptions = new Map(getSessionEnvironments(environments.read(reader)).map(environment => [environment.id, environment])); + const availableEnvironments = new Set(environmentOptions.keys()); + for (const session of catalog) { + if (!localIds.has(session.environment) && !environmentOptions.has(session.environment)) { + environmentOptions.set(session.environment, { + id: session.environment, + label: scope.environment?.id === session.environment ? scope.environment.label : session.environment, + }); + } + } + if (scope.environment && !localIds.has(scope.environment.id) && !environmentOptions.has(scope.environment.id)) { + environmentOptions.set(scope.environment.id, scope.environment); + } + return { + scope, + environments: [...environmentOptions.values()].map(environment => ({ + id: environment.id, + label: environment.label, + disconnected: environment.isConnected?.read(reader) === false, + unavailable: !availableEnvironments.has(environment.id), + })), + workspaces: getInboxWorkspaceOptions(catalog, scope.environment?.id, reader), + hasQuickChats: catalog.some(session => (!scope.environment || scope.environment.id === session.environment) && session.isQuickChat?.read(reader)), + }; + }); + const workspaceLabel = derived(this, reader => { + const { scope, workspaces } = options.read(reader); + if (scope.workspace === undefined) { + return localize('allWorkspaces', "All Workspaces"); + } + if (scope.workspace === 'none') { + return localize('noWorkspace', "No Workspace"); + } + const selected = scope.workspace; + return workspaces.find(workspace => workspace.resource === selected.resource && workspace.environment === selected.environment)?.label + ?? localize('unavailableWorkspace', "Unavailable: {0}", selected.label); + }); + const environmentLabel = derived(this, reader => { + const { scope, environments } = options.read(reader); + if (!scope.environment) { + return localize('allEnvironments', "All Environments"); + } + const selected = environments.find(environment => environment.id === scope.environment?.id); + return selected?.unavailable + ? localize('unavailableEnvironment', "Unavailable: {0}", selected.label) + : selected?.disconnected + ? localize('disconnectedEnvironment', "Disconnected: {0}", selected.label) + : selected?.label ?? scope.environment.label; + }); + const announce = () => status(localize('scopeChanged', "Inbox scope: {0}, {1}.", workspaceLabel.get(), environmentLabel.get())); + const workspaceContainer = dom.append(this.element, dom.$('.scope-picker.workspace-picker')); + const workspace = createSessionPickerToolbar(this._store, workspaceContainer, instantiationService, 'sessions.inboxWorkspace', + localize('workspaceFilter', "Filter Inbox by Workspace"), () => pickWorkspace(), hoverDelegate); + const environmentContainer = dom.append(this.element, dom.$('.scope-picker.environment-picker')); + const environment = createSessionPickerToolbar(this._store, environmentContainer, instantiationService, 'sessions.inboxEnvironment', + localize('environmentFilter', "Filter Inbox by Environment"), () => pickEnvironment(), hoverDelegate); + const workspaceIcon = dom.append(workspace.trigger, dom.$('span', { 'aria-hidden': 'true' })); + const workspaceLabelElement = dom.append(workspace.trigger, dom.$('span.scope-label')); + const environmentIcon = dom.append(environment.trigger, dom.$('span', { 'aria-hidden': 'true' })); + const environmentLabelElement = dom.append(environment.trigger, dom.$('span.scope-label')); + for (const [picker, show] of [[workspace, () => pickWorkspace()], [environment, () => pickEnvironment()]] as const) { + picker.trigger.setAttribute('aria-haspopup', 'listbox'); + picker.trigger.setAttribute('aria-expanded', 'false'); + this._register(dom.addDisposableListener(picker.trigger, dom.EventType.KEY_DOWN, event => { + if (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown') { + dom.EventHelper.stop(event, true); + show(); + } + })); + } + this._register(autorun(reader => { + const workspaceText = workspaceLabel.read(reader); + const environmentText = environmentLabel.read(reader); + workspaceLabelElement.textContent = workspaceText; + environmentLabelElement.textContent = environmentText; + workspace.trigger.setAttribute('aria-label', localize('workspaceScopeLabel', "Filter Inbox by Workspace: {0}", workspaceText)); + environment.trigger.setAttribute('aria-label', localize('environmentScopeLabel', "Filter Inbox by Environment: {0}", environmentText)); + const scope = options.read(reader).scope; + workspaceIcon.className = ThemeIcon.asClassName(getCompactCodicon(scope.workspace === 'none' ? getNoWorkspaceChoicePresentation(undefined).icon : Codicon.folder)); + environmentIcon.className = ThemeIcon.asClassName(getCompactCodicon(scope.environment ? getEnvironmentIcon(scope.environment.id) : Codicon.globe)); + workspace.action.tooltip = scope.workspace && scope.workspace !== 'none' + ? localize('workspaceScopeDescription', "{0}: {1}", workspaceText, scope.workspace.description ?? scope.workspace.resource) + : workspaceText; + environment.action.tooltip = environmentText; + })); + + const pickWorkspace = () => { + const { scope, workspaces, environments, hasQuickChats } = options.get(); + const items: IActionListItem<IInboxScopePickerItem>[] = [{ + kind: ActionListItemKind.Action, + label: localize('allWorkspaces', "All Workspaces"), + group: { title: '', icon: Codicon.folder }, + item: { checked: scope.workspace === undefined, run: () => filters.setInboxWorkspace(undefined) }, + }]; + if (hasQuickChats || scope.workspace === 'none') { + items.push({ + kind: ActionListItemKind.Action, + label: localize('noWorkspace', "No Workspace"), + group: { title: '', icon: getNoWorkspaceChoicePresentation(undefined).icon }, + item: { checked: scope.workspace === 'none', run: () => filters.setInboxWorkspace('none') }, + }); + } + for (const workspace of workspaces) { + items.push({ + kind: ActionListItemKind.Action, + label: workspace.label, + description: localize('workspaceLocation', "{0} - {1}", workspace.description ?? workspace.resource, environments.find(environment => environment.id === workspace.environment)?.label ?? workspace.environment), + group: { title: '', icon: Codicon.folder }, + item: { + checked: !!scope.workspace && scope.workspace !== 'none' && scope.workspace.resource === workspace.resource && scope.workspace.environment === workspace.environment, + run: () => filters.setInboxWorkspace(workspace), + }, + }); + } + this.showPicker(workspace.trigger, items, localize('workspaceFilter', "Filter Inbox by Workspace"), { + ...WORKSPACE_PICKER_LIST_OPTIONS, + showFilter: true, + focusFilterOnOpen: true, + filterPlaceholder: localize('searchWorkspaces', "Search"), + }, announce); + }; + const pickEnvironment = () => { + const { scope, environments } = options.get(); + const selectEnvironment = (environment: { id: string; label: string } | undefined) => { + if (filters.setInboxEnvironment(environment)) { + status(localize('workspaceScopeReset', "Inbox environment: {0}. Workspace reset to All Workspaces.", environmentLabel.get())); + } else { + announce(); + } + }; + const items: IActionListItem<IInboxScopePickerItem>[] = [{ + kind: ActionListItemKind.Action, + label: localize('allEnvironments', "All Environments"), + group: { title: '', icon: Codicon.globe }, + item: { checked: scope.environment === undefined, run: () => selectEnvironment(undefined) }, + }, ...environments.map(environment => ({ + kind: ActionListItemKind.Action, + label: environment.label, + description: environment.unavailable ? localize('unavailable', "Unavailable") : environment.disconnected ? localize('disconnected', "Disconnected") : undefined, + group: { title: '', icon: getEnvironmentIcon(environment.id) }, + item: { + checked: environment.id === scope.environment?.id, + run: () => selectEnvironment({ id: environment.id, label: environment.label }), + }, + }))]; + this.showPicker(environment.trigger, items, localize('environmentFilter', "Filter Inbox by Environment"), ENVIRONMENT_PICKER_LIST_OPTIONS); + }; + } + + private showPicker(trigger: HTMLElement, items: IActionListItem<IInboxScopePickerItem>[], label: string, options: IActionListOptions, onSelect?: () => void): void { + if (this._store.isDisposed || this.element.hidden || this.actionWidgetService.isVisible) { + return; + } + this.activeTrigger = trigger; + trigger.setAttribute('aria-expanded', 'true'); + this.actionWidgetService.show('sessionsInboxScope', false, items, { + onSelect: item => { + this.actionWidgetService.hide(); + if (!this._store.isDisposed && !this.element.hidden) { + item.run(); + onSelect?.(); + } + }, + onHide: () => { + this.activeTrigger = undefined; + trigger.setAttribute('aria-expanded', 'false'); + if (!this._store.isDisposed && !this.element.hidden && trigger.isConnected) { + trigger.focus(); + } + }, + }, trigger, undefined, [], { getWidgetAriaLabel: () => label }, options); + } + + private hidePicker(): void { + if (this.activeTrigger) { + this.actionWidgetService.hide(true); + } + } + + setVisible(visible: boolean): void { + this.element.hidden = !visible; + if (!visible) { + this.hidePicker(); + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/views/sessionsList.ts b/src/vs/workbench/contrib/sessions/browser/views/sessionsList.ts index ec4b8ce5e00c..89554bfd97e1 100644 --- a/src/vs/workbench/contrib/sessions/browser/views/sessionsList.ts +++ b/src/vs/workbench/contrib/sessions/browser/views/sessionsList.ts @@ -5,6 +5,7 @@ import { SessionInlineActions } from './sessionInlineActions.js'; import '../media/sessionsList.css'; +import '../media/disclosure.css'; import { SessionGroupAppearancePicker } from './sessionGroupAppearancePicker.js'; import { findSearchWords, getSessionSearchHint, ISessionSearchDocument, ISessionSearchField, ISessionSearchHint, ISessionSearchMatch, ISessionsListSearchResults, matchSessionSearch, SessionsListFindController, SessionsListSearchQuery, SessionsListSearchTelemetry, SessionSearchFieldKind, toSearchFilterData } from './sessionsListSearch.js'; import * as DOM from '../../../../../base/browser/dom.js'; @@ -14,7 +15,6 @@ import { IListRenderer, IListVirtualDelegate, ListDragOverEffectPosition, ListDr import { IListStyles } from '../../../../../base/browser/ui/list/listWidget.js'; import { IObjectTreeElement, ITreeNode, ITreeRenderer, ITreeContextMenuEvent, ObjectTreeElementCollapseState, ITreeDragAndDrop, ITreeDragOverReaction, TreeDragOverBubble, TreeFilterResult, TreeVisibility } from '../../../../../base/browser/ui/tree/tree.js'; import { IFindFilter, RenderIndentGuides } from '../../../../../base/browser/ui/tree/abstractTree.js'; -import { LayoutPriority, Orientation, SplitView } from '../../../../../base/browser/ui/splitview/splitview.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { groupByMap } from '../../../../../base/common/collections.js'; import { onUnexpectedError } from '../../../../../base/common/errors.js'; @@ -24,6 +24,7 @@ import { createMatches, FuzzyScore, IMatch } from '../../../../../base/common/fi import { disposableTimeout } from '../../../../../base/common/async.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; +import { escapeControlAndFormatCharacters } from '../../../../../base/common/strings.js'; import { constObservable, IObservable, IReader, ISettableObservable, autorun, derived, observableFromEvent, observableSignalFromEvent, observableValue, runOnChange } from '../../../../../base/common/observable.js'; import { ThemeIcon, themeColorFromId } from '../../../../../base/common/themables.js'; import { hasKey, isDefined } from '../../../../../base/common/types.js'; @@ -53,6 +54,10 @@ import { WorkbenchList, WorkbenchObjectTree } from '../../../../../platform/list import { IStyleOverride, defaultButtonStyles, defaultFindWidgetStyles, defaultInputBoxStyles, defaultKeybindingLabelStyles, getButtonStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; import { chartsOrange } from '../../../../../platform/theme/common/colors/chartsColors.js'; import { asCssVariable } from '../../../../../platform/theme/common/colorUtils.js'; +import { listActiveSelectionBackground, listFocusBackground, listHoverBackground, listInactiveFocusBackground, listInactiveSelectionBackground } from '../../../../../platform/theme/common/colors/listColors.js'; +import { isHighContrast } from '../../../../../platform/theme/common/theme.js'; +import { IThemeService, Themable } from '../../../../../platform/theme/common/themeService.js'; +import { agentsBackground } from '../../common/theme.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { IWorkbenchContribution } from '../../../../common/contributions.js'; import { IConfigurationService, isConfigured } from '../../../../../platform/configuration/common/configuration.js'; @@ -65,9 +70,10 @@ import { IOpenerService } from '../../../../../platform/opener/common/opener.js' import { ISessionsListPresentation } from '../sessionsListPresentation.js'; import { ILabelService } from '../../../../../platform/label/common/label.js'; import { ChatSessionArchiveActionWording, ChatSessionArchiveActionWordingSettingId, getChatSessionArchivedSectionLabel, getChatSessionArchiveActionWording } from '../../../../../platform/chat/common/sessionArchiveActions.js'; -import { BRANCH_CHANGES_CHANGESET_ID, ChatInteractivity, ChatOriginKind, getChatCapabilities, getGitHubPullRequestRefs, getGitHubRepositoryOfRemoteFile, getGitHubRepositoryOfUrl, getHighestPriorityPullRequestIcon, getSessionFolderGitHubRepository, getSessionPresentationWorkspace, getSessionStatusMessage, getSessionWorkspaceKind, getUntitledSessionTitle, GITHUB_REMOTE_FILE_SCHEME, IChat, isActiveSessionStatus, ISession, ISessionEnvironment, ISessionWorkspace, SessionArtifactKind, SessionStatus, SessionWorkspaceKind, hasMixedChatHarnesses } from '../../../../services/sessions/common/session.js'; +import { BRANCH_CHANGES_CHANGESET_ID, ChatInteractivity, ChatOriginKind, getChatCapabilities, getGitHubPullRequestRefs, getGitHubRepositoryOfRemoteFile, getGitHubRepositoryOfUrl, getSessionFolderGitHubRepository, getSessionPresentationWorkspace, getSessionStatusMessage, getSessionWorkspaceKind, getUntitledSessionTitle, GITHUB_REMOTE_FILE_SCHEME, IChat, isActiveSessionStatus, ISession, ISessionEnvironment, ISessionWorkspace, SessionArtifactKind, SessionStatus, SessionWorkspaceKind, hasMixedChatHarnesses } from '../../../../services/sessions/common/session.js'; import { ISessionChangesStats, readChatChangesStats } from '../../../../services/sessions/common/sessionChangesStatsCache.js'; import { AgentSessionApprovalModel, agentSessionApprovalId, IAgentSessionApprovalInfo } from '../../../chat/browser/agentSessions/agentSessionApprovalModel.js'; +import { getTerminalExecutionTargetDescription, getTerminalExecutionTargetMessage } from '../../../chat/common/chat.js'; import { IVoicePlaybackService } from '../../../chat/common/voicePlaybackService.js'; import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; @@ -82,7 +88,7 @@ import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget. import { getDefaultHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { inheritableSessionTarget, ISessionsManagementService } from '../../common/sessionsManagement.js'; import { getMainWindowHost, ISessionHostService, shownChatOf } from '../../../../services/sessions/browser/sessionHost.js'; -import { getSessionComparisonChat, getSessionComparisonHarnessLabel, getSessionComparisonParticipantsInDisplayOrder, ISessionComparison, ISessionComparisonService, SessionComparisonParticipantRole } from '../../common/sessionComparison.js'; +import { getSessionComparisonChat, getSessionComparisonHarnessDisplayLabel, getSessionComparisonHarnessLabel, getSessionComparisonParticipantsInDisplayOrder, ISessionComparison, ISessionComparisonService, SessionComparisonParticipantRole } from '../../common/sessionComparison.js'; import { ISessionsService } from '../sessionsService.js'; import { ISessionListModelChangeEvent, ISessionsListModelService, SessionListModelChangeKind, SessionSortEntry, SessionSortMode } from '../sessionsListModelService.js'; import { getSessionGroupIdOfSection, getSessionGroupSectionId, ISessionGroup, ISessionGroupAppearance, ISessionGroupPlacement, ISessionGroupsService } from '../sessionGroupsService.js'; @@ -110,8 +116,8 @@ import { IAgentHostFilterService } from '../../common/agentHostFilter.js'; import { compareSessionEnvironments, getSessionEnvironments, ISessionsListResettableState, SessionsListFilters } from './sessionsListFilters.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { buildOpenSessionLinkUri } from '../../../../../platform/agentHost/common/openSessionLink.js'; -import { LocalSelectionTransfer } from '../../../../../platform/dnd/browser/dnd.js'; -import { DraggedSessionIdentifier, fillSessionChatDragData, onDidEndSessionChatDrag, SessionsDataTransfers } from '../dnd.js'; +import { clearChatReferenceDragData, LocalSelectionTransfer } from '../../../../../platform/dnd/browser/dnd.js'; +import { DraggedSessionIdentifier, fillSessionChatDragData, fillSessionChatReferenceDragData, onDidEndSessionChatDrag, SessionsDataTransfers } from '../dnd.js'; import { getChatMoveDestinations, getSessionMoveDestinations, getSessionsListChatDrop, getSessionsListSessionDrop, isChatMoveDndEnabled, isCrossAgentChatMoveEnabled, ISessionsListChatDropTarget, runSessionsListMove, SessionsListChatDrop, SessionsListMove, SessionsListSessionDrop } from './sessionsListChatMove.js'; import { INotificationService } from '../../../../../platform/notification/common/notification.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; @@ -127,19 +133,21 @@ import { IEditorService } from '../../../../services/editor/common/editorService import { ICustomViewService } from '../customView.js'; import { AUTOMATIONS_CUSTOM_VIEW_ID } from '../automationsConstants.js'; import { IOpenAICustomizationsCommandOptions, OPEN_AI_CUSTOMIZATIONS_COMMAND_ID } from '../customizationsConstants.js'; +import { ChatCustomizationsHover } from '../../../chat/browser/aiCustomization/chatCustomizationsHover.js'; +import { ChatCustomizationsTelemetry } from '../../../chat/browser/aiCustomization/chatCustomizationsTelemetry.js'; import { NEW_SESSION_ACTION_ID } from '../../common/chatConstants.js'; import { Menus } from '../menus.js'; import { getSessionConversationStatusAriaLabel } from '../sessionConversationGroups.js'; -import { getAgentMergeAwarePullRequestIcon, getChatCompletedStateIcon, getSessionAgentMergeConfigurationObservable, ISessionAgentMergeConfiguration, isAgentMergePullRequestIcon } from '../sessionAgentMerge.js'; +import { getChatCompletedStateIcon, getSessionAgentMergeConfigurationObservable, getSessionCompletedStateIcon, ISessionAgentMergeConfiguration } from '../sessionAgentMerge.js'; import { BlockedSessionReason, BlockedSessions } from '../blockedSessions.js'; import { ChatInboxEnabledContext, INBOX_CANVAS_ID, SHOW_INBOX_NOTIFICATIONS_COMMAND_ID } from '../inboxNotificationsConstants.js'; import { WindowCanvasInput } from '../windowCanvas.js'; -import { IInboxNotificationsService, InboxNotificationPriority } from '../../common/inboxNotificationsService.js'; +import { getInboxPullRequestMergeOperation, IInboxNotificationsService, InboxNotificationPriority } from '../../common/inboxNotificationsService.js'; import { getExtensionSuggestionsBadgeDescription } from '../agentsWindowExtensionSuggestions.js'; import { KeybindingLabel } from '../../../../../base/browser/ui/keybindingLabel/keybindingLabel.js'; import { IPinnedCanvas, IPinnedCanvasService, PINNED_CANVAS_PAGE_ID, PinnedCanvasConnectedContext, PinnedCanvasState } from '../pinnedCanvases.js'; import { logSessionsInteraction } from '../../common/sessionsTelemetry.js'; -import { getSessionInboxPriority, getSessionInboxSection, SessionInboxSection, sessionInboxSections } from '../../common/sessionInbox.js'; +import { getSessionInboxDescription, getSessionInboxPriority, getSessionInboxSection, SessionInboxSection, sessionInboxSections } from '../../common/sessionInbox.js'; import { ISessionGridPane } from '../../../../services/sessions/browser/sessionGridPane.js'; import { IShownChat } from '../../../../services/sessions/common/sessionPane.js'; @@ -193,6 +201,7 @@ export const SESSIONS_LIST_INDENT_ITEMS_SETTING = 'sessions.list.indentItems'; export const IsSessionPinnedContext = new RawContextKey<boolean>('sessionItem.isPinned', false); export const SessionItemInboxStateContext = new RawContextKey<string>('sessionItem.inboxState', ''); +export const SessionItemCanMergePullRequestContext = new RawContextKey<boolean>('sessionItem.canMergePullRequest', false); export const SessionItemStatusContext = new RawContextKey<SessionStatus>('sessionItem.status', SessionStatus.Completed); export const SessionItemHasUnreadNestedSessionsContext = new RawContextKey<boolean>('sessionItem.hasUnreadNestedSessions', false); type SessionContextKeyProvider = (session: ISession, reader: IReader | undefined) => Iterable<[string, ContextKeyValue]>; @@ -296,6 +305,7 @@ export interface ISessionGroupItem { readonly title: string; readonly launching: boolean; readonly summary: (reader?: IReader) => string; + readonly configuration: string; }; } @@ -466,7 +476,7 @@ function getSessionSectionIcon(sectionId: string): ThemeIcon | undefined { case SessionInboxSection.OnHold: return Codicon.history; case SessionInboxSection.Done: - return Codicon.check; + return Codicon.mailRead; case CUSTOMIZATIONS_SECTION_ID: return Codicon.extensions; case 'archived': @@ -825,7 +835,7 @@ class SessionsTreeDelegate implements IListVirtualDelegate<SessionListItem> { // with no chat rows aggregate an approval from any of the session's chats. approval = getSessionRowApproval(this._approvalModel, session, undefined, this._aggregateChatApprovals); if (approval) { - height += SessionItemRenderer.getApprovalRowHeight(approval.label, this._approvalRowMaxLines); + height += SessionItemRenderer.getApprovalRowHeight(approval, this._approvalRowMaxLines); } } if (!approval && this._isCompact() && this._getSessionStatus(session) === SessionStatus.NeedsInput) { @@ -857,7 +867,7 @@ class SessionsTreeDelegate implements IListVirtualDelegate<SessionListItem> { return height; } return height - + SessionItemRenderer.getApprovalRowHeight(approval.label, this._approvalRowMaxLines) + + SessionItemRenderer.getApprovalRowHeight(approval, this._approvalRowMaxLines) + (this._isPhone() ? SessionsTreeDelegate.CHAT_APPROVAL_PHONE_BOTTOM_SLACK : 0); } @@ -1009,6 +1019,7 @@ class SessionChatItemRenderer implements ITreeRenderer<SessionListItem, FuzzySco const elementDisposables = disposables.add(new DisposableStore()); container.classList.add('session-chat-item'); + DOM.append(container, $('span.session-attention-indicator', { 'aria-hidden': 'true' })); const titleRow = DOM.append(container, $('.session-chat-title-row')); const iconContainer = DOM.append(titleRow, $('.session-chat-icon')); iconContainer.setAttribute('aria-hidden', 'true'); @@ -1362,7 +1373,7 @@ interface IApprovalRowElements { * approval appears or clears). */ function approvalRowHeightFor(info: IAgentSessionApprovalInfo | undefined, maxLines: number): number { - return info ? SessionItemRenderer.getApprovalRowHeight(info.label, maxLines) : 0; + return info ? SessionItemRenderer.getApprovalRowHeight(info, maxLines) : 0; } interface ICompactInputNeededPresentationOptions { @@ -1426,17 +1437,26 @@ function renderApprovalRowContent( elements.label.textContent = ''; store.add(markdownRendererService.render(labelContent, {}, elements.label)); + if (info.executionTarget?.workingDirectory) { + appendApprovalWorkingDirectory(elements.label, info.executionTarget.workingDirectory); + } if (showHover) { const fullContent = new MarkdownString().appendCodeblock(info.languageId ?? 'json', info.label); + const executionTargetMessage = getTerminalExecutionTargetMessage(info); + if (executionTargetMessage) { + fullContent.appendMarkdown(`\n${executionTargetMessage.value}`); + } store.add(hoverService.setupDelayedHover(elements.label, { content: fullContent, style: HoverStyle.Pointer, position: { hoverPosition: HoverPosition.BELOW }, + additionalClasses: ['session-approval-hover'], })); } elements.buttonContainer.textContent = ''; + const executionTargetDescription = getTerminalExecutionTargetDescription(info); const button = store.add(new Button(elements.buttonContainer, { title: localize('allowActionOnce', "Allow once"), // All simultaneously visible "Allow" buttons share the same visible label @@ -1444,7 +1464,9 @@ function renderApprovalRowContent( // command/action it approves — otherwise screen-reader users can't tell // which chat's action a button belongs to. Keep the "once" scope so the // one-time nature of the permission is still conveyed. - ariaLabel: localize('allowActionAria', "Allow once: {0}", info.label), + ariaLabel: executionTargetDescription + ? localize('allowActionAriaWithExecutionTarget', "Allow once: {0} ({1})", info.label, executionTargetDescription) + : localize('allowActionAria', "Allow once: {0}", info.label), secondary: true, ...defaultButtonStyles })); @@ -1458,6 +1480,19 @@ function renderApprovalRowContent( })); } +/** + * Appends the line naming where a pending command runs. A long path is cut at + * its start, keeping the folders nearest the command, which tell same-named + * relative commands apart. + */ +function appendApprovalWorkingDirectory(container: HTMLElement, workingDirectory: string): void { + const line = DOM.append(container, $('.session-approval-working-directory')); + DOM.append(line, $(`span${ThemeIcon.asCSSSelector(Codicon.folderCompact)}`)); + const path = DOM.append(line, $('span.session-approval-working-directory-path')); + // Isolated left-to-right so the right-to-left box that moves the ellipsis to the start cannot reorder the path. + DOM.append(path, $('span', { dir: 'ltr' }, escapeControlAndFormatCharacters(workingDirectory))); +} + //#endregion //#region Session Item Renderer @@ -1668,8 +1703,8 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, /** Height of the single-line "Fix CI" row (label + orange button), including its top margin. */ static readonly CI_ROW_HEIGHT = 32; - static getApprovalRowHeight(label: string, maxLines: number = DEFAULT_APPROVAL_ROW_MAX_LINES): number { - const lineCount = Math.min(label.split(/\r?\n/).length, maxLines); + static getApprovalRowHeight(approval: IAgentSessionApprovalInfo, maxLines: number = DEFAULT_APPROVAL_ROW_MAX_LINES): number { + const lineCount = Math.min(approval.label.split(/\r?\n/).length, maxLines) + (approval.executionTarget?.workingDirectory ? 1 : 0); return lineCount * SessionItemRenderer._APPROVAL_ROW_LINE_HEIGHT + SessionItemRenderer._APPROVAL_ROW_OVERHEAD; } @@ -1695,6 +1730,7 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, getAdditionalContextKeys?: SessionContextKeyProvider; showMetadataWhileActive?: (session: ISession) => boolean; getCompletedStatusMessage?: (session: ISession, reader: IReader | undefined) => string | undefined; + getTriageDescription?: (session: ISession, reader: IReader | undefined) => string | undefined; onboardingTarget?: IObservable<ISessionOnboardingTarget | undefined>; isRenderedInExternalSection?: (session: ISession) => boolean; /** How many groups deep the custom group whose rows include the session's row is nested; the row steps in by that many levels. */ @@ -1735,6 +1771,7 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, container.classList.add('session-item'); DOM.append(container, $('span.session-group-connector', { 'aria-hidden': 'true' })); + DOM.append(container, $('span.session-attention-indicator', { 'aria-hidden': 'true' })); const iconContainer = DOM.append(container, $('.session-icon')); const statusIcon = disposables.add(this.instantiationService.createInstance(SessionStatusIcon, iconContainer)); const mainCol = DOM.append(container, $('.session-main')); @@ -1852,6 +1889,7 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, if (!isSessionItem(element)) { return; } + template.container.closest('.monaco-list-row')?.classList.toggle('sessions-disclosure-row', node.collapsible); this.renderSession(element, template, node.filterData && createMatches(node.filterData)); } @@ -1924,13 +1962,19 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, let rowObservesMainChatBranchChanges = false; if (this.options.showHover) { // Rich hover on the row: the same widget session pills use in chat output. - template.elementDisposables.add(this.hoverService.setupDelayedHover(template.container, () => - withSessionsListHoverPresentation(createSessionSummaryHover( + template.elementDisposables.add(this.hoverService.setupDelayedHover(template.container, () => { + const hover = createSessionSummaryHover( element, // Observed Branch Changes are read from memory; reading unobserved ones would load the chat from its backend. getSessionSummaryHoverData(element, this.sessionsProvidersService, this.openerService, this.labelService, getCreatorHoverData(element, this.sessionsManagementService, this.agentHostConnectionsService, this.openerService), this.options.compact(), rowObservesMainChatBranchChanges), this.openerService, - )), { groupId: 'sessions-list' })); + ); + const triage = this.options.getTriageDescription?.(element, undefined); + if (triage && DOM.isHTMLElement(hover.content)) { + DOM.append(hover.content, $('div', undefined, triage)); + } + return withSessionsListHoverPresentation(hover); + }, { groupId: 'sessions-list' })); } // Pending voice response indicator: a response arrived while this session @@ -2039,15 +2083,7 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, template.isQuickChatContext.set(isQuickChat); template.supportsMultipleChatsContext.set(capabilities.supportsMultipleChats); template.supportsDeleteContext.set(capabilities.supportsDelete === true); - const gitHubInfo = element.workspace.read(reader)?.folders[0]?.gitRepository?.gitHubInfo.read(reader); - // A provider icon is authoritative: the workspace's pull requests may belong to other chats. - let completedStateIcon = element.completedStateIcon - ? element.completedStateIcon.read(reader) - : getHighestPriorityPullRequestIcon(getGitHubPullRequestRefs(gitHubInfo).map(pullRequest => pullRequest.icon)); - if (completedStateIcon && isAgentMergePullRequestIcon(completedStateIcon)) { - agentMergeConfiguration ??= getSessionAgentMergeConfigurationObservable(element, this.sessionsProvidersService, this.configurationService); - completedStateIcon = getAgentMergeAwarePullRequestIcon(completedStateIcon, agentMergeConfiguration.read(reader)); - } + const completedStateIcon = getSessionCompletedStateIcon(element, reader, () => agentMergeConfiguration ??= getSessionAgentMergeConfigurationObservable(element, this.sessionsProvidersService, this.configurationService)); // The status icon widget snaps on row recycling and cross-fades real state changes. template.statusIcon.setStatus(sessionStatus, isRead, isArchived, completedStateIcon, element.resource); @@ -2140,7 +2176,7 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, DOM.clearNode(template.titleSearchHint); const hasDetailsRow = comparisonAttemptLabel === undefined && !(isQuickChat && this.options.useCompactQuickChatRows) && !this.options.compact(); - const workspaceBadgeLabel = getSessionRowLocationLabel(element, workspace, reader, this.options); + const workspaceBadgeLabel = getSessionRowLocationLabel(element, reader, this.options); // When the session is InProgress or NeedsInput, hide workspace/diff details in this row const hideDetails = !this.options.showMetadataWhileActive?.(element) && (sessionStatus === SessionStatus.InProgress || sessionStatus === SessionStatus.NeedsInput); const badgeLabel = isQuickChat @@ -2220,6 +2256,16 @@ class SessionItemRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, parts.push(badgeEl); } + const triage = this.options.getTriageDescription?.(element, reader); + if (triage) { + if (parts.length > 0) { + DOM.append(template.detailsRow, $('span.session-separator.has-separator')); + } + const label = DOM.append(template.detailsRow, $('span.session-description', undefined, triage)); + reader.store.add(this.hoverService.setupDelayedHoverAtMouse(label, { content: triage })); + parts.push(label); + } + if (searchHint) { if (parts.length > 0) { DOM.append(template.detailsRow, $('span.session-separator.has-separator')); @@ -2530,7 +2576,9 @@ interface ISessionRowLocationOptions { * repository section header omits the workspace that the header already names; in a * repository section, it names the environment instead. */ -function getSessionRowLocationLabel(session: ISession, workspace: ISessionWorkspace | undefined, reader: IReader, options: ISessionRowLocationOptions): string | undefined { +function getSessionRowLocationLabel(session: ISession, reader: IReader, options: ISessionRowLocationOptions): string | undefined { + // A multi-folder session works in its main chat's folder, like its hover and the title bar say. + const workspace = getSessionPresentationWorkspace(session, reader); if (!workspace) { return undefined; } @@ -2567,13 +2615,54 @@ function logDefaultSettingExperimentTrigger(configurationService: IConfiguration //#region Section Header Renderer interface ISessionHeaderTemplate { + readonly container: HTMLElement; readonly icon: HTMLElement; + readonly label: HTMLElement; readonly collapsed: ISettableObservable<boolean>; readonly toolbarContainer: HTMLElement; readonly toolbar: MenuWorkbenchToolBar; readonly elementDisposables: DisposableStore; } +const sessionHeaderLabelBackgrounds = [ + ['--session-group-foreground', agentsBackground], + ['--session-group-hover-foreground', listHoverBackground], + ['--session-group-focus-foreground', listFocusBackground], + ['--session-group-selection-foreground', listActiveSelectionBackground], + ['--session-group-inactive-focus-foreground', listInactiveFocusBackground], + ['--session-group-inactive-selection-foreground', listInactiveSelectionBackground], +] as const; + +class SessionHeaderLabelColor extends Themable { + constructor( + private readonly template: ISessionHeaderTemplate, + private readonly colorId: string, + @IThemeService themeService: IThemeService, + ) { + super(themeService); + this.updateStyles(); + } + + override updateStyles(): void { + const color = this.theme.getColor(this.colorId); + const background = this.theme.getColor(agentsBackground); + // A translucent shell has no single opaque surface against which to correct contrast. + const preserveForeground = isHighContrast(this.theme.type) || background?.isOpaque() === false; + for (const [property, backgroundId] of sessionHeaderLabelBackgrounds) { + const surface = background && (this.theme.getColor(backgroundId)?.flatten(background) ?? background); + const foreground = preserveForeground ? '' : color && surface ? surface.ensureConstrast(color.flatten(surface), 4.5).toString() : asCssVariable(this.colorId); + this.template.label.style.setProperty(property, foreground); + } + } + + override dispose(): void { + super.dispose(); + for (const [property] of sessionHeaderLabelBackgrounds) { + this.template.label.style.removeProperty(property); + } + } +} + const enum SessionHeaderStatus { NeedsInput, FailingCI, @@ -2633,6 +2722,9 @@ function couldShowSessionHeaderStatus(sessions: readonly ISession[], reader: IRe } function renderSessionHeaderIcon(template: ISessionHeaderTemplate, sessions: readonly ISession[], icon: ThemeIcon | undefined, showUnreadInCollapsedSections: IObservable<boolean>, sessionsWithFailingCI: IObservable<ReadonlySet<string>>, statusTrigger: ISessionHeaderStatusTrigger, instantiationService: IInstantiationService, iconOverride?: IObservable<ThemeIcon | undefined>): void { + if (icon?.color) { + template.elementDisposables.add(instantiationService.createInstance(SessionHeaderLabelColor, template, icon.color.id)); + } template.elementDisposables.add(autorun(reader => { if (statusTrigger.pending.read(reader) && (template.collapsed.read(reader) || statusTrigger.includeExpanded.read(reader)) && couldShowSessionHeaderStatus(sessions, reader)) { statusTrigger.report(); @@ -2891,6 +2983,7 @@ export class SessionSectionRenderer implements ITreeRenderer<SessionListItem, Fu private renderSection(element: ISessionSection, collapsible: boolean, collapsed: boolean, template: ISessionSectionTemplate): void { template.elementDisposables.clear(); this.renderedSections.set(template, element); + template.container.closest('.monaco-list-row')?.classList.toggle('sessions-disclosure-row', collapsible); setSessionGroupDepth(template.container, this.getGroupDepth(element)); template.container.classList.remove(SESSION_HEADER_DROP_TARGET_CLASS); template.container.classList.remove('session-section-shortcut'); @@ -2927,15 +3020,26 @@ export class SessionSectionRenderer implements ITreeRenderer<SessionListItem, Fu } if (element.id === CUSTOMIZATIONS_SECTION_ID) { template.container.classList.add('session-section-customizations'); - template.elementDisposables.add(this.hoverService.setupDelayedHover( + const hover = this.instantiationService.createInstance(ChatCustomizationsHover); + const hoverDelegate = getDefaultHoverDelegate('element'); + template.elementDisposables.add(this.hoverService.setupManagedHover( + { + placement: 'element', + get delay() { return hoverDelegate.delay; }, + showHover: (options, focus) => hoverDelegate.showHover({ + ...options, + additionalClasses: [...options.additionalClasses ?? [], 'sessions-list-hover'], + position: { ...options.position, hoverPosition: HoverPosition.RIGHT }, + appearance: { ...options.appearance, showPointer: true }, + }, focus), + }, template.container, - () => withSessionsListHoverPresentation({ - content: this.customizationMigrationsAvailable.get() - ? localize('customizationsMigrationHover', "Some customizations need an update to keep working.") - : this.customizationExtensionSuggestionsAvailable.get() - ? getExtensionSuggestionsBadgeDescription() - : element.label, - }), + () => hover.getManagedContent(this.customizationMigrationsAvailable.get() + ? localize('customizationsMigrationHover', "Some customizations need an update to keep working.") + : this.customizationExtensionSuggestionsAvailable.get() + ? getExtensionSuggestionsBadgeDescription() + : undefined), + hover.getHoverOptions('sessionsHeader'), )); template.elementDisposables.add(autorun(reader => { const active = this.customizationsActive.read(reader); @@ -3195,6 +3299,7 @@ class SessionGroupRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, private readonly instantiationService: IInstantiationService, private readonly contextKeyService: IContextKeyService, private readonly configurationService: IConfigurationService, + private readonly hoverService: IHoverService, ) { } renderTemplate(container: HTMLElement): ISessionGroupTemplate { @@ -3229,6 +3334,7 @@ class SessionGroupRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, if (!isSessionGroupItem(element)) { return; } + template.container.closest('.monaco-list-row')?.classList.toggle('sessions-disclosure-row', node.collapsible); template.elementDisposables.clear(); renderSessionHeaderToolbar(template, element, this.delegate.select); this.renderedGroups.set(template, element); @@ -3247,6 +3353,9 @@ class SessionGroupRenderer implements ITreeRenderer<SessionListItem, FuzzyScore, template.elementDisposables.add(autorun(reader => { template.description.textContent = comparison.summary(reader); })); + template.elementDisposables.add(this.hoverService.setupDelayedHover(template.container, () => withSessionsListHoverPresentation({ + content: comparison.configuration, + }), { groupId: 'sessions-list' })); } else { template.description.textContent = ''; } @@ -3492,6 +3601,7 @@ interface ISessionsAccessibilityProviderOptions extends ICompactInputNeededPrese readonly reportExternalApplicationBadgeModeExperimentTrigger?: () => void; readonly reportExternalApplicationBadgeShowFromExperimentTrigger?: () => void; readonly getCompletedStatusMessage?: (session: ISession, reader: IReader | undefined) => string | undefined; + readonly getTriageDescription?: (session: ISession, reader: IReader | undefined) => string | undefined; /** The harness label of a nested chat whose harness differs from its session's. */ readonly getChatHarnessLabel?: (session: ISession, chat: IChat, reader: IReader | undefined) => string | undefined; /** While searching, the field a session or a standalone chat matched in that neither its row, through `shownTexts`, nor its section headers show. */ @@ -3558,7 +3668,7 @@ class SessionsAccessibilityProvider { } if (isSessionGroupItem(element)) { return element.comparison - ? derived(this, reader => localize('comparisonGroupAria', "{0}, {1}", element.comparison!.title, element.comparison!.summary(reader))) + ? derived(this, reader => localize('comparisonGroupAria', "{0}, {1}, {2}", element.comparison!.title, element.comparison!.summary(reader), element.comparison!.configuration)) : this.getSectionAriaLabel(element.group.name, element.subtreeSessions); } if (isSessionSection(element)) { @@ -3689,6 +3799,10 @@ class SessionsAccessibilityProvider { if (historyStatusMessage) { label = localize('sessionItemHistoryStatusAria', "{0}, {1}", label, typeof historyStatusMessage === 'string' ? historyStatusMessage : renderAsPlaintext(historyStatusMessage, { omitMarkdownSyntax: true })); } + const triage = this.options?.getTriageDescription?.(element, reader); + if (triage) { + label = localize('sessionItemTriageAria', "{0}, {1}", label, triage); + } const eligible = isExternalApplicationBadgeEligible(element, reader); if (eligible) { this.options?.reportExternalApplicationBadgeModeExperimentTrigger?.(); @@ -3710,8 +3824,7 @@ class SessionsAccessibilityProvider { if (inputNeededMessage) { label = localize('sessionItemInputNeededMessageAria', "{0}, {1}", label, renderAsPlaintext(inputNeededMessage, { omitMarkdownSyntax: true })); } - const workspace = element.workspace.read(reader); - const locationLabel = this.options ? getSessionRowLocationLabel(element, workspace, reader, this.options) : undefined; + const locationLabel = this.options ? getSessionRowLocationLabel(element, reader, this.options) : undefined; const labeledLocation = showMetadataWhileActive || (status !== SessionStatus.InProgress && status !== SessionStatus.NeedsInput) ? locationLabel : undefined; @@ -3870,12 +3983,16 @@ interface ISessionsListDndDelegate { getHeaderDrop(header: IDraggedHeader, target: SessionListItem, sector: ListViewTargetSector | undefined): SessionHeaderDrop | undefined; /** How many rows the element renders: its own row and those of its visible descendants. */ getRenderedRowCount(element: SessionListItem): number; + /** The list index of the first row of the "+N more" area: its toggle row, or the first workspace it reveals. */ + getMoreFoldersDropIndex(): number | undefined; /** Move a dragged header to where it lands. */ moveHeader(header: IDraggedHeader, drop: SessionHeaderDrop): void; /** Steps the insertion line of a header drop in to the depth where the header lands, or resets it. */ setHeaderInsertionDepth(depth: number | undefined): void; /** The dragged chat row's chat, with its session, when moving chats by drag and drop is on and it can move. */ getMovableDraggedChat(item: ISessionChatItem): { readonly session: ISession; readonly chat: IChat } | undefined; + /** Attach a reference to the chat of `session` to the drag, such that it can also drop into a chat input that attaches it. */ + fillChatReferenceDragData(event: DragEvent, session: ISession, chat: IChat): void; /** Whether nested chat rows are shown in their session's chat order, so that a position among them is a position in that order. */ areChatPositionsShown(): boolean; /** Whether chats may also move into sessions of other agents that offer their harness (see {@link isCrossAgentChatMoveEnabled}). */ @@ -3920,7 +4037,7 @@ interface IDraggedHeader { * groups service orders; or inside a group as its first subgroup. */ type SessionHeaderDrop = - | { readonly kind: 'topLevel'; readonly targetId: string; readonly position: 'before' | 'after' } + | { readonly kind: 'topLevel'; readonly targetId: string; readonly position: 'before' | 'after'; readonly aboveMore?: boolean } | { readonly kind: 'subgroup'; readonly parentId: string; readonly depth: number; readonly placement: ISessionGroupPlacement } | { readonly kind: 'comparison'; readonly parent: ISessionSection | ISessionGroupItem; readonly anchor?: ISession | ISessionGroupItem; readonly position: 'before' | 'after'; readonly depth: number } | { readonly kind: 'into'; readonly groupId: string }; @@ -3998,6 +4115,7 @@ class SessionsListDragAndDrop extends Disposable implements ITreeDragAndDrop<Ses const chatItem = elements.find(isSessionChatItem); if (chatItem) { fillSessionChatDragData(originalEvent, chatItem.session.sessionId, chatItem.chat.resource); + this.delegate.fillChatReferenceDragData(originalEvent, chatItem.session, chatItem.chat); this._draggedChat = { item: chatItem, movable: this.delegate.getMovableDraggedChat(chatItem) }; return; } @@ -4009,6 +4127,10 @@ class SessionsListDragAndDrop extends Disposable implements ITreeDragAndDrop<Ses this._draggedSession = sessions.length === 1 ? sessions[0] : undefined; const identifiers = sessions.map(s => new DraggedSessionIdentifier(s.sessionId, s.resource)); this._transfer.setData(identifiers, DraggedSessionIdentifier.prototype); + if (this._draggedSession) { + // The session stands for its main chat, which a chat input can attach. + this.delegate.fillChatReferenceDragData(originalEvent, this._draggedSession, this._draggedSession.mainChat.get()); + } if (originalEvent.dataTransfer) { // Expose the first dragged session as a typed payload as well so external @@ -4031,6 +4153,7 @@ class SessionsListDragAndDrop extends Disposable implements ITreeDragAndDrop<Ses this._draggedSession = undefined; this._transfer.clearData(DraggedSessionIdentifier.prototype); + clearChatReferenceDragData(); this._draggedChat = undefined; this.delegate.setDropTargetHeader(undefined); this.delegate.setMoveDropFeedback('none'); @@ -4108,7 +4231,10 @@ class SessionsListDragAndDrop extends Disposable implements ITreeDragAndDrop<Ses index: position === 'after' && targetIndex !== undefined ? targetIndex + this.delegate.getRenderedRowCount(target) - 1 : undefined, }); if (drop.kind === 'topLevel') { - return { reaction: toDropReaction(insertionFeedback(drop.position)), insertionDepth: 0, run }; + // A header dropped on the "+N more" area lands above it, so draw the line there. + const moreIndex = drop.aboveMore ? this.delegate.getMoreFoldersDropIndex() : undefined; + const feedback = moreIndex !== undefined ? { position: ListDragOverEffectPosition.Before, index: moreIndex } : insertionFeedback(drop.position); + return { reaction: toDropReaction(feedback), insertionDepth: 0, run }; } if (drop.kind === 'subgroup') { return { reaction: toDropReaction(insertionFeedback(drop.placement.position)), insertionDepth: drop.depth, run }; @@ -4402,6 +4528,7 @@ interface ISessionsListControlBaseOptions { readonly sorting: () => SessionsSorting; readonly compact?: () => boolean; readonly showNavigationShortcuts?: () => boolean; + readonly showCustomizations?: () => boolean; readonly customizationsCount?: IObservable<number>; readonly customizationMigrationsAvailable?: IObservable<boolean>; /** Whether installed extensions can be enabled in the Agents window, signaled on the Customizations navigation entry. */ @@ -4585,17 +4712,6 @@ export class SessionsList extends Disposable implements ISessionsList { private readonly listContainer: HTMLElement; private readonly primaryContainer: HTMLElement; - private readonly inboxFooterContainer: HTMLElement; - private readonly inboxResizeHandle: HTMLElement; - private readonly inboxSplitView: SplitView; - private readonly inboxTree: WorkbenchObjectTree<SessionListItem, FuzzyScore>; - private readonly inboxFooterSizeChanged = this._register(new Emitter<number | undefined>()); - private inboxFooterMaximumSize = 0; - private inboxFooterMinimumSize = 0; - private inboxFooterPreferredSize: number | undefined; - private listHeight = 0; - private listWidth = 0; - private layingOutInbox = false; private readonly stickyShowMoreContainer: HTMLElement; private readonly stickyShowMoreButton: Button; private readonly stickyShowMoreLabel: HTMLElement; @@ -4603,6 +4719,7 @@ export class SessionsList extends Disposable implements ISessionsList { private stickyShowMoreItem: ISessionShowMore | undefined; private pendingOpenRequest: IListOpenRequest | undefined; protected readonly tree: WorkbenchObjectTree<SessionListItem, FuzzyScore>; + private readonly selectedSessions: IObservable<readonly ISession[]>; private readonly navigationList: WorkbenchList<ISessionSection> | undefined; private navigationSections: readonly ISessionSection[] = []; private sessions: ISession[] = []; @@ -4723,6 +4840,9 @@ export class SessionsList extends Disposable implements ISessionsList { */ private _topLevelOrder: string[] = []; + /** The workspace sections capped behind "+N more", shown in the list or not. */ + private _moreFolderSectionIds: ReadonlySet<string> = new Set(); + private readonly _onDidUpdate = this._register(new Emitter<void>()); readonly onDidUpdate: Event<void> = this._onDidUpdate.event; private readonly _onDidOpenSession = this._register(new Emitter<URI>()); @@ -4740,26 +4860,23 @@ export class SessionsList extends Disposable implements ISessionsList { } private isInboxLayout(): boolean { - return this.options.grouping() === SessionsGrouping.Inbox && !IsPhoneLayoutContext.getValue(this.contextKeyService); + return this.options.grouping() === SessionsGrouping.Inbox; } - protected getTree(element: SessionListItem): WorkbenchObjectTree<SessionListItem, FuzzyScore> { - return this.inboxTree?.hasElement(element) ? this.inboxTree : this.tree; + protected getTree(_element: SessionListItem): WorkbenchObjectTree<SessionListItem, FuzzyScore> { + return this.tree; } protected get trees(): readonly WorkbenchObjectTree<SessionListItem, FuzzyScore>[] { - return [this.tree, this.inboxTree]; + return [this.tree]; } protected getFocusedTree(): WorkbenchObjectTree<SessionListItem, FuzzyScore> { - return DOM.isAncestorOfActiveElement(this.inboxFooterContainer) - || !DOM.isAncestorOfActiveElement(this.primaryContainer) && this.inboxTree.getFocus().length > 0 - ? this.inboxTree : this.tree; + return this.tree; } private getRootNode(): ITreeNode<SessionListItem | null, FuzzyScore> { - const root = this.tree.getNode(); - return { ...root, children: [...root.children, ...this.inboxTree.getNode().children] }; + return this.tree.getNode(); } private getSelection(): (SessionListItem | null)[] { @@ -4781,7 +4898,7 @@ export class SessionsList extends Disposable implements ISessionsList { @ISessionComparisonService private readonly sessionComparisonService: ISessionComparisonService, @ISessionSectionOrderService private readonly _sessionSectionOrderService: ISessionSectionOrderService, @IAgentHostFilterService private readonly _agentHostFilterService: IAgentHostFilterService, - @IInstantiationService instantiationService: IInstantiationService, + @IInstantiationService private readonly instantiationService: IInstantiationService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IStorageService private readonly storageService: IStorageService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @@ -4824,57 +4941,15 @@ export class SessionsList extends Disposable implements ISessionsList { this.resettableStates = [ this.filters, // `undefined` follows the archived filter's default setting. - resettableValue(() => this._excludeArchivedIsDefault ? undefined : this._excludeArchived, exclude => this.applyExcludeArchived(exclude), true), + resettableValue(() => this._excludeArchivedIsDefault ? undefined : this._excludeArchived, exclude => this.applyExcludeArchived(exclude), undefined), resettableValue(() => this.workspaceGroupCapped, capped => this.applyWorkspaceGroupCapped(capped), true), resettableValue(() => this.loadSessionGroupExpansion(), state => this.storeSessionGroupExpansion(state), new Map()), resettableValue(() => this.expandedMoreFolders, expanded => { this.expandedMoreFolders = expanded; }, false), ]; this.listContainer = DOM.append(container, $('.sessions-list-control.session-list-row-spacing')); - this.primaryContainer = $('.sessions-list-primary'); - this.inboxFooterContainer = $('.sessions-list-inbox-footer'); - this.inboxResizeHandle = DOM.append(this.inboxFooterContainer, $('.sessions-list-inbox-resize', { - role: 'separator', 'aria-orientation': 'horizontal', 'aria-label': localize('resizeInboxCategories', "Resize Inbox Categories"), - })); - this._register(DOM.addDisposableListener(this.inboxResizeHandle, DOM.EventType.KEY_DOWN, (event: KeyboardEvent) => { - let size = this.inboxSplitView.getViewSize(1); - switch (event.key) { - case 'ArrowUp': size += 26; break; - case 'ArrowDown': size -= 26; break; - case 'Home': size = this.inboxFooterMinimumSize; break; - case 'End': size = this.inboxFooterMaximumSize; break; - default: return; - } - event.preventDefault(); - event.stopPropagation(); - this.inboxFooterPreferredSize = Math.max(this.inboxFooterMinimumSize, Math.min(size, this.inboxFooterMaximumSize)); - this.layoutInbox(); - })); - // Dispose tree editors before SplitView detaches their focused inputs and fires blur. + this.primaryContainer = DOM.append(this.listContainer, $('.sessions-list-primary')); const treeDisposables = this._register(new DisposableStore()); - this.inboxSplitView = this._register(new SplitView(this.listContainer, { orientation: Orientation.VERTICAL, proportionalLayout: false })); - this.inboxSplitView.addView({ - element: this.primaryContainer, - minimumSize: 0, - maximumSize: Number.POSITIVE_INFINITY, - priority: LayoutPriority.High, - onDidChange: Event.None, - layout: height => this.tree?.layout(height, this.listWidth), - }, 0); - const owner = this; - this.inboxSplitView.addView({ - element: this.inboxFooterContainer, - get minimumSize() { return owner.inboxFooterMinimumSize; }, - get maximumSize() { return owner.inboxFooterMaximumSize; }, - onDidChange: this.inboxFooterSizeChanged.event, - layout: height => this.inboxTree?.layout(height, this.listWidth), - }, 0); - this._register(this.inboxSplitView.onDidSashChange(() => { - if (!this.layingOutInbox) { - this.inboxFooterPreferredSize = this.inboxSplitView.getViewSize(1); - this.layoutInbox(); - } - })); const listContextKeyService = this._register(contextKeyService.createScoped(this.listContainer)); const treeInstantiationService = this._register(instantiationService.createChild(new ServiceCollection([IContextKeyService, listContextKeyService]))); this.listContainer.classList.toggle('compact', this.isCompact()); @@ -4969,8 +5044,12 @@ export class SessionsList extends Disposable implements ISessionsList { aggregateChatApprovals: false, toolbarMenuId: Menus.SessionItemToolbar, toolbarTelemetrySource: 'sessionsList.row', - getAdditionalContextKeys: (session, reader) => [[SessionItemInboxStateContext.key, - this.options.grouping() === SessionsGrouping.Inbox ? this._sessionsListModelService.getInboxState(session, reader)?.kind ?? '' : '']], + getAdditionalContextKeys: (session, reader) => [ + [SessionItemInboxStateContext.key, this.isInboxLayout() ? this._sessionsListModelService.getInboxState(session, reader)?.kind ?? '' : ''], + [SessionItemCanMergePullRequestContext.key, this.canMergeInboxPullRequest(session, reader)], + [SessionItemIsMultiSelectionContext.key, this.getMultiSelectedSessions(session, reader).length > 1], + ], + getTriageDescription: (session, reader) => this.getInboxDescription(session, reader), inlineRename: true, contextViewService: this.contextViewService, onDidDoubleClickRename: session => this.preservePendingOpenFocus(session), @@ -5124,7 +5203,7 @@ export class SessionsList extends Disposable implements ISessionsList { cancelEdit: group => this.cancelGroupEdit(group), select: selectHeader, toggleCollapsed: element => this.getTree(element).toggleCollapsed(element), - }, showUnreadInCollapsedSections, sessionsWithFailingCI, headerStatusTrigger, instantiationService, contextKeyService, this.configurationService); + }, showUnreadInCollapsedSections, sessionsWithFailingCI, headerStatusTrigger, instantiationService, contextKeyService, this.configurationService, hoverService); this._groupRenderer = groupRenderer; // Read (don't bind) `IsPhoneLayoutContext` from the parent context so we @@ -5209,6 +5288,7 @@ export class SessionsList extends Disposable implements ISessionsList { { accessibilityProvider: new SessionsAccessibilityProvider(sectionRenderer.automationStatus, { widgetAriaLabel: label, + getTriageDescription: (session, reader) => this.getInboxDescription(session, reader), grouping: this.options.grouping, getChatHarnessLabel: (session, chat, reader) => getDistinctChatHarnessLabel(session, chat, sessionsProvidersService, reader), isPinned: session => this.isSessionPinned(session), @@ -5239,8 +5319,10 @@ export class SessionsList extends Disposable implements ISessionsList { setDropTargetHeader: header => this.setDropTargetHeader(header), getHeaderDrop: (header, target, sector) => this.options.grouping() === SessionsGrouping.Inbox ? undefined : this.getHeaderDrop(header, target, sector), getRenderedRowCount: element => this.getTree(element).hasElement(element) ? this.getTree(element).getListRenderCount(element) : 1, + getMoreFoldersDropIndex: () => this.getMoreFoldersDropIndex(), moveHeader: (header, drop) => this.moveHeader(header, drop), getMovableDraggedChat: item => this.getMovableDraggedChat(item), + fillChatReferenceDragData: (event, session, chat) => fillSessionChatReferenceDragData(event, session, chat, this._sessionsProvidersService), areChatPositionsShown: () => this.areChatPositionsShown(), isCrossAgentChatMoveEnabled: () => isCrossAgentChatMoveEnabled(this.configurationService), canMoveSessionUnder: session => this.isChatMoveDndEnabled() && this._sessionsManagementService.canMoveSessionUnder(session), @@ -5329,8 +5411,8 @@ export class SessionsList extends Disposable implements ISessionsList { } )); this.tree = createTree(this.primaryContainer, localize('sessionsPrimaryList', "Sessions")); - this.inboxTree = createTree(this.inboxFooterContainer, localize('inboxCategories', "Inbox categories")); - this._register(this.inboxTree.onDidChangeContentHeight(() => this.layoutInbox())); + this.selectedSessions = observableFromEvent(this, this.tree.onDidChangeSelection, + () => this.getSelection().filter((item): item is ISession => !!item && isSessionItem(item))); this.findController = this._register(new SessionsListFindController(this.tree, this.searchFilter, this.contextViewService, { isSearching: () => this.searchFilter.isSearching, // Showing no chats of a session that has some makes its row stand for the whole session. @@ -5339,41 +5421,12 @@ export class SessionsList extends Disposable implements ISessionsList { }, { findWidgetContainer: this.options.findWidgetContainer, styles: defaultFindWidgetStyles, - additionalTrees: [this.inboxTree], })); const focusedChatItemContext = SessionsListFocusedChatItemContext.bindTo(listContextKeyService); this.focusedChatCanMoveUpContext = SessionChatItemCanMoveUpContext.bindTo(listContextKeyService); this.focusedChatCanMoveDownContext = SessionChatItemCanMoveDownContext.bindTo(listContextKeyService); for (const tree of this.trees) { tree.updateOptions({ indent: 0, defaultIndent: 0, expandOnDoubleClick: false }); - this._register(tree.onDidChangeFocus(e => { - if (this.isInboxLayout() && e.elements.length > 0) { - for (const other of this.trees) { - if (other !== tree) { - other.setFocus([]); - } - } - } - })); - this._register(tree.onDidChangeSelection(e => { - if (this.isInboxLayout() && e.elements.length > 0) { - const additive = e.browserEvent && DOM.isMouseEvent(e.browserEvent) && (tree.useAltAsMultipleSelectionModifier ? e.browserEvent.altKey : e.browserEvent.ctrlKey || e.browserEvent.metaKey); - for (const other of this.trees) { - if (other !== tree && (!additive || ![...e.elements, ...other.getSelection()].every(element => element && isSessionItem(element) && !element.isArchived.get()))) { - other.setSelection([]); - } - } - } - })); - this._register(tree.onPointer(e => { - if (this.isInboxLayout() && e.browserEvent.button === 0) { - for (const other of this.trees) { - if (other !== tree) { - other.setSelection([]); - } - } - } - })); } this.stickyShowMoreContainer = DOM.append(this.listContainer, $('.sessions-list-sticky-show-more')); this.stickyShowMoreContainer.hidden = true; @@ -5407,7 +5460,6 @@ export class SessionsList extends Disposable implements ISessionsList { this._register(this.stickyShowMoreButton.onDidEscape(() => this.tree.domFocus())); this._register(this.tree.onDidScroll(() => this.updateStickyShowMore())); this._register(this.tree.onDidChangeContentHeight(() => { - this.layoutInbox(); this.updateStickyShowMore(); })); this._register(Event.any(...this.trees.map(tree => tree.onDidChangeFocus))(e => { @@ -5638,8 +5690,8 @@ export class SessionsList extends Disposable implements ISessionsList { this._register(this._sessionsManagementService.onDidChangeSessions(e => { if (this.visible) { - // Move and reveal operations depend on concrete deltas being rendered synchronously. - if (e.added.length || e.removed.length || e.changed.length) { + // Additions and removals stay synchronous for move/reveal; lazy metadata changes must not reenter row rendering. + if (e.added.length || e.removed.length) { this.refresh(); } else { this.scheduleListUpdate(true); @@ -5895,7 +5947,7 @@ export class SessionsList extends Disposable implements ISessionsList { this.groupDepths.clear(); const topLevelGroupIds = topLevelGroups.filter(group => !comparisonsByGroupId.has(group.id)).map(group => getSessionGroupSectionId(group.id)); - const archivedSectionLabel = inbox ? localize('archivedInboxSessions', "Archived") : getChatSessionArchivedSectionLabel(getChatSessionArchiveActionWording(this.configurationService)); + const archivedSectionLabel = getChatSessionArchivedSectionLabel(getChatSessionArchiveActionWording(this.configurationService)); const environments = grouping === SessionsGrouping.Environment ? getSessionEnvironments(this._sessionsProvidersService.getProviders().map(provider => provider.environment)) : []; @@ -6056,6 +6108,7 @@ export class SessionsList extends Disposable implements ISessionsList { title: comparison.title, launching: comparison.launching === true, summary: reader => getComparisonGroupSummary(comparison, this.sessions, reader), + configuration: getComparisonGroupConfiguration(comparison, this.labelService), } : undefined, }; this.groupDepths.set(group.id, depth); @@ -6089,7 +6142,8 @@ export class SessionsList extends Disposable implements ISessionsList { const moreFolderSectionIds = new Set<string>(); if (partitionFolders) { const workspaceSections = sections.filter(s => isSessionGroupingSection(s.id) && this.getSectionParentId(s.id) === undefined); - if (workspaceSections.length > 0) { + // With only two workspaces, hiding one behind a "+1 more" row saves no space. + if (workspaceSections.length > 2) { const now = Date.now(); const isRecent = (section: ISessionSection) => section.sessions.some(s => s.updatedAt.get().getTime() >= now - FOUR_DAYS_MS); @@ -6223,7 +6277,7 @@ export class SessionsList extends Disposable implements ISessionsList { defaultCollapsed = ObjectTreeElementCollapseState.PreserveOrCollapsed; } } - if (section.id === 'archived' || this.isInboxLayout() && sessionInboxSections.some(id => id === section.id)) { + if (section.id === 'archived' || inbox && section.id !== SessionInboxSection.ReadyForYou && section.id !== SessionInboxSection.Done && sessionInboxSections.some(id => id === section.id)) { defaultCollapsed = ObjectTreeElementCollapseState.PreserveOrCollapsed; } @@ -6232,10 +6286,16 @@ export class SessionsList extends Disposable implements ISessionsList { if (section.id === 'pinned' && !inbox || section.id === QUICK_CHATS_SECTION_ID) { defaultCollapsed = ObjectTreeElementCollapseState.PreserveOrCollapsed; } + const savedCollapsed = this.getSavedCollapseState(section.collapseStateId ?? section.id, section.collapseStateId ? section.id : undefined); + if (savedCollapsed !== undefined) { + defaultCollapsed = inbox + ? savedCollapsed ? ObjectTreeElementCollapseState.PreserveOrCollapsed : ObjectTreeElementCollapseState.PreserveOrExpanded + : savedCollapsed; + } return { element: section as SessionListItem, - collapsible: !sessionInboxSections.some(id => id === section.id) || section.sessions.length > 0, - collapsed: resolveCollapsed(section, this.getSavedCollapseState(section.collapseStateId ?? section.id, section.collapseStateId ? section.id : undefined) ?? defaultCollapsed), + collapsible: section.id !== SessionInboxSection.ReadyForYou && (!sessionInboxSections.some(id => id === section.id) || section.sessions.length > 0), + collapsed: resolveCollapsed(section, defaultCollapsed), children: sectionChildren, }; }; @@ -6327,7 +6387,7 @@ export class SessionsList extends Disposable implements ISessionsList { children.push(renderSection(automationsSection)); } } - if (showNavigationShortcuts) { + if (this.options.showCustomizations?.() ?? showNavigationShortcuts) { navigationSections.push({ id: CUSTOMIZATIONS_SECTION_ID, label: localize('customizations', "Customizations"), sessions: [] }); } // Pinned canvases follow Automations: in the navigation list, or in the tree without one. @@ -6361,26 +6421,54 @@ export class SessionsList extends Disposable implements ISessionsList { // Match sessions again before filtering sections: their text may have changed since the last update. this.searchFilter.invalidate(); this.hiddenGroupingSections = []; - const footerChildren: IObjectTreeElement<SessionListItem>[] = []; + this._moreFolderSectionIds = new Set(); if (inbox) { this._topLevelOrder = []; for (const id of sessionInboxSections) { const sourceSection = sections.find(section => section.id === id); - const section = sourceSection && this.isInboxLayout() && this.hasFindPattern + const section = sourceSection && this.hasFindPattern ? { ...sourceSection, sessions: sourceSection.sessions.filter(session => !!this.searchFilter.getMatch(session)) } : sourceSection; - if (section) { - const rendered = renderWorkspaceSection(section); - if (!this.isInboxLayout()) { - children.push(rendered); - } else if (id === SessionInboxSection.ReadyForYou) { - const primary = [...rendered.children ?? []]; - children.push(...primary.length > 0 ? primary : [{ - element: { placeholder: true as const, sectionId: id, label: localize('inboxEmpty', "Your inbox is clear") }, - }]); - } else { - footerChildren.push(rendered); + if (section && (section.sessions.length > 0 || id === SessionInboxSection.ReadyForYou)) { + let rendered = renderWorkspaceSection(section); + if (id === SessionInboxSection.ReadyForYou) { + rendered = { ...rendered, collapsed: false }; + if (section.sessions.length === 0) { + const hasDismissed = sections.some(section => section.id === SessionInboxSection.Done && section.sessions.length > 0); + rendered = { + ...rendered, children: [{ + element: { + placeholder: true as const, sectionId: id, + label: hasDismissed ? localize('inboxEmptyHistory', "No new activity. See Dismissed below.") : localize('inboxEmpty', "Your inbox is clear"), + hover: hasDismissed ? localize('inboxHistoryHelp', "Dismissed includes completed turns from before Inbox mode was enabled. These sessions are not archived or necessarily finished. Choose Return to Inbox on a session to bring it back.") : undefined, + }, + }] + }; + } + } else if (id === SessionInboxSection.OnHold) { + const workspaces = new Map<string, { sessions: ISession[]; children: IObjectTreeElement<SessionListItem>[] }>(); + for (const child of rendered.children ?? []) { + const sessions = isSessionItem(child.element) ? [child.element] : isSessionGroupItem(child.element) ? child.element.sessions : []; + if (sessions.length === 0) { + continue; + } + const label = sessionWorkspaceLabel(sessions[0]); + let workspace = workspaces.get(label); + if (!workspace) { + workspace = { sessions: [], children: [] }; + workspaces.set(label, workspace); + } + workspace.sessions.push(...sessions); + workspace.children.push(child); + } + rendered = { + ...rendered, children: [...workspaces].sort(([a], [b]) => a.localeCompare(b)).map(([label, workspace]) => { + const section: ISessionSection = { id: `${SessionInboxSection.OnHold}:workspace:${label}`, label, sessions: workspace.sessions }; + return { ...renderSection(section), children: workspace.children }; + }) + }; } + children.push(rendered); } } } else if (grouping === SessionsGrouping.Date) { @@ -6440,6 +6528,7 @@ export class SessionsList extends Disposable implements ISessionsList { } const moreFolderSections = workspaceSections.filter(s => moreFolderSectionIds.has(s.id)); + this._moreFolderSectionIds = new Set(moreFolderSections.map(s => s.id)); if (moreFolderSections.length > 0) { const kind = grouping === SessionsGrouping.Environment ? 'environments' : grouping === SessionsGrouping.Repository ? 'repositories' : 'folders'; if (this.expandedMoreFolders) { @@ -6464,13 +6553,12 @@ export class SessionsList extends Disposable implements ISessionsList { } const archivedSection = sections.find(s => s.id === 'archived'); if (archivedSection) { - (this.isInboxLayout() ? footerChildren : children).push(renderSection(archivedSection)); + children.push(renderSection(archivedSection)); } const inboxLayoutChanged = this.listContainer.classList.contains('inbox-layout') !== this.isInboxLayout(); this.listContainer.classList.toggle('inbox-layout', this.isInboxLayout()); this.tree.getHTMLElement().setAttribute('aria-label', this.isInboxLayout() ? localize('inboxHeader', "Inbox") : localize('sessionsList', "Sessions")); - this.inboxTree.setChildren(null, footerChildren); this.tree.setChildren(null, children); if (inboxLayoutChanged) { for (const session of this.sessions) { @@ -6480,7 +6568,6 @@ export class SessionsList extends Disposable implements ISessionsList { } } } - this.layoutInbox(); this.updateArchiveDemand(); this.nestedSessionResources = nextNestedSessionResources; this.syncCollapsedSessionIds(); @@ -6542,10 +6629,6 @@ export class SessionsList extends Disposable implements ISessionsList { } private revealAboveStickyShowMore(element: SessionListItem): void { - if (this.getTree(element) === this.inboxTree) { - this.inboxTree.reveal(element); - return; - } this.tree.reveal(element); if (this.stickyShowMoreContainer.hidden) { return; @@ -6639,6 +6722,7 @@ export class SessionsList extends Disposable implements ISessionsList { await this.commandService.executeCommand(SHOW_INBOX_NOTIFICATIONS_COMMAND_ID); break; case CUSTOMIZATIONS_SECTION_ID: + this.instantiationService.createInstance(ChatCustomizationsTelemetry).logInteraction('buttonClicked', 'sessionsHeader'); if (this.options.customizationMigrationsAvailable?.get()) { await this.commandService.executeCommand(OPEN_AI_CUSTOMIZATIONS_COMMAND_ID, { migration: true, @@ -6753,13 +6837,25 @@ export class SessionsList extends Disposable implements ISessionsList { this.suspendCollapseStatePersistence = previousSuspendCollapseStatePersistence; } } - if (tree.getRelativeTop(chatItem) === null) { - tree.reveal(chatItem, 0.5); - } + this.revealActiveItem(chatItem); tree.setFocus([chatItem]); tree.setSelection([chatItem]); } + private revealActiveItem(element: SessionListItem): void { + const tree = this.getTree(element); + if (tree.getRelativeTop(element) !== null) { + return; + } + const previousSuspendCollapseStatePersistence = this.suspendCollapseStatePersistence; + this.suspendCollapseStatePersistence ||= this.isInboxLayout(); + try { + tree.reveal(element, 0.5); + } finally { + this.suspendCollapseStatePersistence = previousSuspendCollapseStatePersistence; + } + } + /** * The row of a session's chat and the session row it is nested under, if * any: a done chat of a session that is not done has a standalone row in @@ -6823,9 +6919,7 @@ export class SessionsList extends Disposable implements ISessionsList { } } } - if (tree.getRelativeTop(session) === null) { - tree.reveal(session, 0.5); - } + this.revealActiveItem(session); tree.setFocus([session]); tree.setSelection([session]); return true; @@ -6979,42 +7073,11 @@ export class SessionsList extends Disposable implements ISessionsList { layout(height: number, width: number): void { this.layoutNavigation(width); - this.listHeight = Math.max(0, height); - this.listWidth = width; this.listContainer.style.height = `${height}px`; - this.layoutInbox(); + this.tree.layout(Math.max(0, height), width); this.updateStickyShowMore(); } - private layoutInbox(): void { - if (this.layingOutInbox) { - return; - } - this.layingOutInbox = true; - try { - const enabled = this.isInboxLayout(); - this.inboxFooterContainer.hidden = !enabled; - const contentHeight = this.inboxTree.contentHeight; - const primaryContentHeight = this.tree.contentHeight; - const primaryMinimumSize = Math.min(primaryContentHeight, this.listHeight * 0.35); - this.inboxFooterMaximumSize = enabled ? Math.min(contentHeight, this.listHeight - primaryMinimumSize) : 0; - const collapsedHeight = this.inboxTree.getNode().children.filter(node => node.visible).length * (this.options.sectionRowHeight ?? 26); - this.inboxFooterMinimumSize = Math.min(collapsedHeight, this.inboxFooterMaximumSize); - const primaryPreferredSize = Math.min(primaryContentHeight, this.listHeight * 0.6); - const preferred = Math.max(collapsedHeight, this.inboxFooterPreferredSize ?? this.listHeight - primaryPreferredSize); - this.inboxFooterSizeChanged.fire(Math.min(preferred, this.inboxFooterMaximumSize)); - this.inboxSplitView.layout(this.listHeight); - this.inboxSplitView.resizeView(1, Math.min(preferred, this.inboxFooterMaximumSize)); - this.inboxResizeHandle.tabIndex = this.inboxFooterMaximumSize > this.inboxFooterMinimumSize ? 0 : -1; - const percent = (size: number) => String(this.listHeight > 0 ? Math.round(size / this.listHeight * 100) : 0); - this.inboxResizeHandle.setAttribute('aria-valuemin', percent(this.inboxFooterMinimumSize)); - this.inboxResizeHandle.setAttribute('aria-valuemax', percent(this.inboxFooterMaximumSize)); - this.inboxResizeHandle.setAttribute('aria-valuenow', percent(this.inboxSplitView.getViewSize(1))); - } finally { - this.layingOutInbox = false; - } - } - setCompact(): void { this.listContainer.classList.toggle('compact', this.isCompact()); this.update(); @@ -7278,7 +7341,7 @@ export class SessionsList extends Disposable implements ISessionsList { let succeeded = false; let updates = 0; const tryReveal = () => { - if (!succeeded || !target || store.isDisposed) { + if (!succeeded || !target || store.isDisposed || this.refreshPending) { return; } if (this.revealMoved(target.sessionId, target.chat) || ++updates > 5) { @@ -7832,7 +7895,7 @@ export class SessionsList extends Disposable implements ISessionsList { private sortComparisonChildren(children: IObjectTreeElement<SessionListItem>[]): IObjectTreeElement<SessionListItem>[] { const inbox = this.options.grouping() === SessionsGrouping.Inbox; const key = (child: IObjectTreeElement<SessionListItem>) => isSessionItem(child.element) || (isSessionGroupItem(child.element) && child.element.comparison) - ? inbox ? this.getListSortEntry(child.element).updatedAt.get().getTime() + ? inbox ? (this.options.sorting() === SessionsSorting.Created ? this.getListSortEntry(child.element).createdAt : this.getListSortEntry(child.element).updatedAt.get()).getTime() : this._sessionsListModelService.getSortKey(this.getListSortEntry(child.element), sortingToMode(this.options.sorting())) : Number.NEGATIVE_INFINITY; const priority = (child: IObjectTreeElement<SessionListItem>) => !inbox ? InboxNotificationPriority.Later @@ -7911,6 +7974,14 @@ export class SessionsList extends Disposable implements ISessionsList { const parent = this.tree.getParentElement(target); return parent ? this.getHeaderDrop(header, parent, sector) : undefined; } + if (this.isInMoreFolders(target)) { + // Workspaces behind "+N more" are not in the reorderable order: a header dropped on + // them or on the "+N more" row lands below the last always-visible header, above them. + const lastId = this._topLevelOrder.findLast(id => id !== header.id); + return lastId !== undefined && !(isSessionSection(target) && target.id === header.id) + ? { kind: 'topLevel', targetId: lastId, position: 'after', aboveMore: true } + : undefined; + } const groupTree = this._sessionGroupsService.getTree(); const draggedId = header.group?.group.id; const canNestIn = (groupId: string) => draggedId !== undefined @@ -7954,6 +8025,33 @@ export class SessionsList extends Disposable implements ISessionsList { return groupItem && canNestIn(groupItem.group.id) ? { kind: 'into', groupId: groupItem.group.id } : undefined; } + /** Whether the element is the "+N more" row, a workspace it reveals, or a row inside one. */ + private isInMoreFolders(element: SessionListItem): boolean { + if (isSessionShowMore(element) && element.sectionId === SHOW_MORE_FOLDERS_LABEL) { + return true; + } + if (this._moreFolderSectionIds.size === 0 || !this.tree.hasElement(element)) { + return false; + } + let topLevel = element; + for (let parent = this.tree.getParentElement(element); parent; parent = this.tree.getParentElement(parent)) { + topLevel = parent; + } + return isSessionSection(topLevel) && this._moreFolderSectionIds.has(topLevel.id); + } + + /** The list index of the first row of the "+N more" area, or `undefined` when the list has none. */ + private getMoreFoldersDropIndex(): number | undefined { + let index = 0; + for (const child of this.getRootNode().children) { + if (child.element && this.isInMoreFolders(child.element)) { + return index; + } + index += this.tree.getListRenderCount(child.element); + } + return undefined; + } + /** * Move a dragged header to where it lands. The groups service nests a dragged * group and orders it among its new siblings, while the list orders the @@ -8427,8 +8525,8 @@ export class SessionsList extends Disposable implements ISessionsList { }); } - private getMultiSelectedSessions(session: ISession): ISession[] { - const selection = this.getSelection().filter((s): s is ISession => !!s && isSessionItem(s)); + private getMultiSelectedSessions(session: ISession, reader?: IReader): ISession[] { + const selection = this.selectedSessions.read(reader); return selection.includes(session) ? [session, ...selection.filter(s => s !== session)] : [session]; } @@ -8471,6 +8569,7 @@ export class SessionsList extends Disposable implements ISessionsList { const inGroup = this._sessionGroupsService.getGroupOfSession(element.sessionId) !== undefined; const contextOverlay: [string, boolean | string][] = [ [SessionItemInboxStateContext.key, inboxStates.every(state => state === inboxStates[0]) ? inboxStates[0] ?? '' : 'mixed'], + [SessionItemCanMergePullRequestContext.key, this.canMergeInboxPullRequest(element)], [IsSessionPinnedContext.key, this.isSessionPinned(element)], [SessionItemIsMultiSelectionContext.key, selectedSessions.length > 1], [SessionItemHasMoveDestinationContext.key, getSessionMoveDestinations(element, this._sessionsManagementService.getSessions(), this._sessionsManagementService, isCrossAgentChatMoveEnabled(this.configurationService)).length > 0], @@ -8661,6 +8760,9 @@ export class SessionsList extends Disposable implements ISessionsList { } private showCreateGroupContextMenu(anchor: ITreeContextMenuEvent<SessionListItem | null>['anchor']): void { + if (this.isInboxLayout()) { + return; + } this.contextMenuService.showContextMenu({ getActions: () => [this.getCreateGroupAction()], getAnchor: () => anchor, @@ -8715,7 +8817,9 @@ export class SessionsList extends Disposable implements ISessionsList { color => this._sessionGroupsService.setSectionColor(section.id, color), )]); } - organize.push(this.getCreateGroupAction()); + if (grouping !== SessionsGrouping.Inbox) { + organize.push(this.getCreateGroupAction()); + } groups.push(['2_organize', organize]); this.showHeaderContextMenu(Menus.SessionSectionContext, contextKeyService, section, groups, anchor); } @@ -8931,6 +9035,18 @@ export class SessionsList extends Disposable implements ISessionsList { return getSessionInboxSection(session, this._sessionsListModelService.getInboxState(session), undefined, this.inboxNotificationsService.sessionAttention.get().get(session.sessionId)); } + private canMergeInboxPullRequest(session: ISession, reader?: IReader): boolean { + return this.isInboxLayout() && !session.isArchived.read(reader) + && getSessionInboxSection(session, this._sessionsListModelService.getInboxState(session, reader), reader, this.inboxNotificationsService.sessionAttention.read(reader).get(session.sessionId)) === SessionInboxSection.ReadyToMerge + && getInboxPullRequestMergeOperation(session, reader) !== undefined; + } + + private getInboxDescription(session: ISession, reader?: IReader): string | undefined { + return this.isInboxLayout() && !session.isArchived.read(reader) + ? getSessionInboxDescription(this._sessionsListModelService.getInboxState(session, reader)) + : undefined; + } + private getInboxPriority(session: ISession): InboxNotificationPriority { return getSessionInboxPriority(session, this.inboxNotificationsService.sessionAttention.get().get(session.sessionId)); } @@ -9668,6 +9784,32 @@ function isComparisonLaunchPending(comparison: ISessionComparison): boolean { return comparison.launching === true; } +function getComparisonGroupConfiguration(comparison: ISessionComparison, labelService: ILabelService): string { + const lines = [localize('comparisonGroup.originalConfiguration', "Original comparison settings")]; + if (comparison.workspace) { + lines.push(localize('comparisonGroup.repository', "Repository: {0}", labelService.getUriLabel(comparison.workspace))); + lines.push(localize('comparisonGroup.isolation', "Isolation: Separate worktrees")); + if (comparison.branch) { + lines.push(localize('comparisonGroup.branch', "Base branch: {0}", comparison.branch)); + } + } else { + lines.push(localize('comparisonGroup.noWorkspace', "Workspace: None")); + } + const attempts = comparison.participants.filter(participant => participant.role === SessionComparisonParticipantRole.Attempt); + for (const [index, attempt] of attempts.entries()) { + lines.push(localize('comparisonGroup.attemptConfiguration', "Attempt {0}: {1}", index + 1, getSessionComparisonHarnessDisplayLabel(attempt.harness))); + } + const judge = comparison.judgeHarness ?? comparison.participants.find(participant => participant.role === SessionComparisonParticipantRole.Judge)?.harness; + const synthesizer = comparison.synthesisHarness ?? comparison.participants.find(participant => participant.role === SessionComparisonParticipantRole.Synthesis)?.harness; + lines.push(judge + ? localize('comparisonGroup.judgeConfiguration', "Judge: {0}", getSessionComparisonHarnessDisplayLabel(judge)) + : localize('comparisonGroup.noJudge', "Judge: None")); + lines.push(synthesizer + ? localize('comparisonGroup.synthesizerConfiguration', "Synthesizer: {0}", getSessionComparisonHarnessDisplayLabel(synthesizer)) + : localize('comparisonGroup.noSynthesizer', "Synthesizer: None")); + return lines.join('\n'); +} + function getComparisonGroupSummary(comparison: ISessionComparison, sessions: readonly ISession[], reader?: IReader): string { if (comparison.launching) { const attempts = comparison.participants.filter(participant => participant.role === SessionComparisonParticipantRole.Attempt); @@ -9934,9 +10076,7 @@ export function groupSessionsForList( ? sessionInboxSections.map(id => ({ id, label: getSessionInboxSectionLabel(id), - sessions: regular.filter(session => getInboxSection(session) === id).sort((a, b) => - getInboxPriority(a) - getInboxPriority(b) - || b.updatedAt.get().getTime() - a.updatedAt.get().getTime()), + sessions: sortSessions(regular.filter(session => getInboxSection(session) === id), sorting).sort((a, b) => getInboxPriority(a) - getInboxPriority(b)), })) : grouping === SessionsGrouping.Workspace ? groupByWorkspace(regular) @@ -9959,11 +10099,11 @@ export function groupSessionsForList( function getSessionInboxSectionLabel(section: SessionInboxSection): string { switch (section) { - case SessionInboxSection.ReadyForYou: return localize('inboxReadyForYou', "Ready for you"); + case SessionInboxSection.ReadyForYou: return localize('inboxSection', "Inbox"); case SessionInboxSection.ReadyToMerge: return localize('inboxReadyToMerge', "Ready to merge"); case SessionInboxSection.Working: return localize('inboxWorking', "Working"); case SessionInboxSection.OnHold: return localize('inboxOnHold', "On hold"); - case SessionInboxSection.Done: return localize('inboxDone', "Done"); + case SessionInboxSection.Done: return localize('inboxDismissed', "Dismissed"); } } diff --git a/src/vs/workbench/contrib/sessions/browser/views/sessionsListActions.ts b/src/vs/workbench/contrib/sessions/browser/views/sessionsListActions.ts new file mode 100644 index 000000000000..5e83b4ee86fd --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/views/sessionsListActions.ts @@ -0,0 +1,1835 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../../base/common/codicons.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; +import { toErrorMessage } from '../../../../../base/common/errorMessage.js'; +import { onUnexpectedError } from '../../../../../base/common/errors.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { Disposable, DisposableStore, IDisposable } from '../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../base/common/resources.js'; +import { hasKey } from '../../../../../base/common/types.js'; +import { localize, localize2 } from '../../../../../nls.js'; +import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; +import { AccessibilitySignal, IAccessibilitySignalService } from '../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.js'; +import { Action2, MenuId, MenuRegistry, registerAction2 } from '../../../../../platform/actions/common/actions.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ContextKeyExpr, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; +import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { KeybindingsRegistry, KeybindingWeight } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { WorkbenchListFocusContextKey } from '../../../../../platform/list/browser/listService.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { FocusedViewContext, IsSessionsWindowContext } from '../../../../common/contextkeys.js'; +import { SessionsCategories } from '../../common/categories.js'; +import { SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING } from '../../common/sessionConfig.js'; +import { ACKNOWLEDGE_INBOX_SESSION_COMMAND_ID, ARCHIVE_CHAT_COMMAND_ID, ARCHIVE_SESSION_COMMAND_ID, ARCHIVE_SESSION_GROUP_COMMAND_ID, ARCHIVE_SESSIONS_WITH_UNDO_COMMAND_ID, DELETE_SESSION_GROUP_WITH_UNDO_COMMAND_ID, HIDE_AUTOMATION_SESSION_FROM_LIST_COMMAND_ID, HOLD_INBOX_SESSION_COMMAND_ID, MARK_SESSION_READ_COMMAND_ID, MARK_SESSION_UNREAD_COMMAND_ID, RENAME_SESSION_COMMAND_ID, RESUME_INBOX_SESSION_COMMAND_ID, SHOW_AUTOMATION_SESSION_IN_LIST_COMMAND_ID, SHOW_SESSION_APPLICATION_FILTERS_COMMAND_ID, UNARCHIVE_CHAT_COMMAND_ID, UNARCHIVE_SESSION_COMMAND_ID } from '../../common/sessionCommands.js'; +import { IsPhoneLayoutContext, SessionSupportsDeleteContext, SessionSupportsRenameContext, SessionActiveChatCanArchiveContext, SessionActiveChatIsUntitledContext, SessionHeaderTargetsChatContext, SessionIsArchivedContext, SessionIsCreatedContext, SessionIsReadContext, SessionItemIsMultiSelectionContext, SessionsListPromoteNewChatActionContext } from '../../common/contextkeys.js'; +import { getSessionListChats, isAutomationSession, SessionItemInboxStateContext, SessionItemCanAcknowledgeContext, SessionItemCanMergePullRequestContext, SessionItemCanImportContext, SessionItemContextMenuId, SessionItemIsAutomationContext, SessionItemIsInSessionsListContext, SessionItemOrganizeMenuGroup, SessionItemHasUnreadNestedSessionsContext, SessionSectionToolbarMenuId, SessionGroupToolbarMenuId, SessionSectionTypeContext, SessionGroupHasVisibleSessionsContext, SessionGroupIsEmptyContext, SessionGroupIsComparisonContext, IsSessionPinnedContext, SessionsGrouping, SessionsSorting, ISessionSection, ISessionGroupItem, ISessionChatItem, SessionChatItemCanArchiveContext, SessionChatItemCanMoveDownContext, SessionChatItemCanMoveUpContext, SessionChatItemCanSetReadStateContext, SessionChatItemIsArchivedContext, SessionChatItemIsReadContext, SessionChatItemIsStandaloneContext, SessionChatItemIsUntitledContext, SessionsListFocusedChatItemContext, SessionsListSearchOpenContext } from './sessionsList.js'; +import { getChatCapabilities, IChat, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { ISessionGroupsService } from '../sessionGroupsService.js'; +import { ISessionsListModelService } from '../sessionsListModelService.js'; +import { ISessionComparisonService } from '../../common/sessionComparison.js'; +import { IsWorkspaceGroupCappedContext, SessionsViewCompactContext, SessionsViewGroupingContext, SessionsViewId, SessionsView, SessionsViewSortingContext } from './sessionsView.js'; +import { Menus, SessionHeaderMenus } from '../menus.js'; +import { ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; +import { ChatSessionArchiveActionWording, ChatSessionArchiveActionWordingSettingId, getChatSessionArchiveActionPresentation, getChatSessionArchiveActionWording, SESSIONS_MARK_AS_DONE_CONFETTI_SETTING } from '../../../../../platform/chat/common/sessionArchiveActions.js'; +import { ISessionsPartService } from '../../../../services/sessions/browser/sessionsPartService.js'; +import { ISessionsService } from '../sessionsService.js'; +import { resolveSessionCommandTarget } from '../sessionCommandTarget.js'; +import { IWorkbenchContribution } from '../../../../common/contributions.js'; +import { registerExternalSessionsFilterMenu } from '../../../chat/browser/agentSessions/externalSessionsFilterMenu.js'; +import { ChatAutomationsEnabledContext } from '../../../chat/common/automations/automationsEnabled.js'; +import { AccessibleViewType } from '../../../../../platform/accessibility/browser/accessibleView.js'; +import { AccessibleViewRegistry } from '../../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { SessionsListNotificationFocused } from './sessionsListNotification.js'; +import { getInboxPullRequestMergeOperation, getSessionInboxSection, SessionInboxAction, SessionInboxSection } from '../../common/sessionInbox.js'; +import { ISessionAttentionService } from '../../common/sessionAttentionService.js'; + +async function archiveSessionsWithUndo( + sessions: readonly ISession[], + wording: ChatSessionArchiveActionWording, + sessionsManagementService: ISessionsManagementService, + groupsService: ISessionGroupsService, + viewsService: IViewsService, + comparisonService: ISessionComparisonService, +): Promise<void> { + const archived: { session: ISession; groupId: string | undefined }[] = []; + const candidates = sessions.filter(session => !session.isArchived.get()).map(session => ({ + session, + groupId: groupsService.getGroupOfSession(session.sessionId), + })); + const comparisonGroups = new Map(comparisonService.comparisons.get() + .filter(comparison => comparison.archivedAt === undefined && candidates.some(entry => entry.groupId === comparison.groupId)) + .map(comparison => [comparison.groupId, comparison.id])); + try { + for (const entry of candidates) { + await sessionsManagementService.archiveSession(entry.session); + archived.push(entry); + } + } finally { + // A partially completed batch must remain undoable even when a later archive fails. + if (archived.length > 0) { + const removedComparisonGroups = new Map([...comparisonGroups].filter(([groupId]) => !groupsService.getGroup(groupId))); + const restoredGroupIds = new Map<string, string>(); + const message = wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('sessionsMarkedDone', "{0} marked done", archived.length) + : localize('sessionsArchived', "{0} archived", archived.length); + viewsService.getViewWithId<SessionsView>(SessionsViewId)?.listNotification?.show({ + message, + help: localize('archiveNoticeHelp', "This notice appears after marking sessions done or archiving them. Undo restores the sessions and their previous custom groups, if those groups still exist. It does not restart stopped requests."), + undo: async () => { + for (const [groupId, comparisonId] of removedComparisonGroups) { + const restoredGroupId = restoredGroupIds.get(groupId); + if (!restoredGroupId || !groupsService.getGroup(restoredGroupId)) { + restoredGroupIds.set(groupId, comparisonService.restoreComparison(comparisonId)); + } + } + while (archived.length > 0) { + const { session, groupId } = archived[0]; + const current = sessionsManagementService.getSession(session.resource); + if (current?.isArchived.get()) { + await sessionsManagementService.unarchiveSession(current); + const restoredGroupId = groupId ? restoredGroupIds.get(groupId) ?? groupId : undefined; + if (restoredGroupId && groupsService.getGroup(restoredGroupId) && !groupsService.getGroupOfSession(current.sessionId)) { + groupsService.addToGroup(current.sessionId, restoredGroupId); + } + } + archived.shift(); + } + status(localize('sessionsRestored', "Sessions restored.")); + }, + }); + } + } +} + +/** + * Deletes a custom group and offers Undo when subgroups or nested sections are affected. + */ +function deleteSessionGroupWithUndo(groupId: string, groupsService: ISessionGroupsService, viewsService: IViewsService): void { + const deleted = groupsService.deleteGroup(groupId); + if (!deleted || (deleted.groups.length < 2 && deleted.sectionMembership.size === 0)) { + return; + } + viewsService.getViewWithId<SessionsView>(SessionsViewId)?.listNotification?.show({ + message: deleted.groups.length === 1 + ? localize('sessionGroupDeleted', "Group deleted") + : localize('sessionGroupsDeleted', "{0} groups deleted", deleted.groups.length), + help: localize('deleteGroupsNoticeHelp', "This notice appears after deleting a group that contains subgroups or nested sections. Undo restores the groups, their order, and their sessions and sections, except sessions that were marked done or items moved to another group since."), + undo: async () => { + groupsService.restoreGroups(deleted); + status(localize('sessionGroupsRestored', "Groups restored.")); + }, + }); +} + +// View Title Menu + +/** Non-date grouping caps its sections, which Show switches between Recent and All. */ +const GroupedBySectionContext = ContextKeyExpr.or( + SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Workspace), + SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Repository), + SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Environment), +); + +// Sort / Group Actions + +const InboxModeContext = SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Inbox); + +// Workspace Group Capping + +// Collapse All Groups + +// View Toolbar Actions + +// Escape in the list closes its find widget, as `list.closeFind` closes a tree's. + +// Section Actions + +/** Grouping sections whose New Session starts in a workspace that their sessions work in. */ +const ConfirmArchiveStorageKey = 'sessions.confirmArchive'; + +function getArchiveSectionConfirmationMessage(context: ISessionSection, wording: ChatSessionArchiveActionWording): string { + if (context.id === 'pinned') { + if (context.sessions.length === 1) { + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markPinnedSectionSessionDone.confirmSingle', "Are you sure you want to mark 1 pinned session as done?") + : localize('archivePinnedSectionSession.confirmSingle', "Are you sure you want to archive 1 pinned session?"); + } + + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markPinnedSectionSessionsDone.confirm', "Are you sure you want to mark {0} pinned sessions as done?", context.sessions.length) + : localize('archivePinnedSectionSessions.confirm', "Are you sure you want to archive {0} pinned sessions?", context.sessions.length); + } + + if (context.sessions.length === 1) { + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markSectionSessionDone.confirmSingle', "Are you sure you want to mark 1 session from '{0}' as done?", context.label) + : localize('archiveSectionSession.confirmSingle', "Are you sure you want to archive 1 session from '{0}'?", context.label); + } + + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markSectionSessionsDone.confirm', "Are you sure you want to mark {0} sessions from '{1}' as done?", context.sessions.length, context.label) + : localize('archiveSectionSessions.confirm', "Are you sure you want to archive {0} sessions from '{1}'?", context.sessions.length, context.label); +} + +abstract class BaseArchiveSectionAction extends Action2 { + constructor(private readonly wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).archiveAll; + super({ + id: 'sessionsView.sectionArchive', + title: action.title, + icon: action.icon, + menu: [SessionSectionToolbarMenuId, Menus.SessionSectionContext].map(id => ({ + id, + group: id === SessionSectionToolbarMenuId ? 'navigation' : '1_state', + order: id === SessionSectionToolbarMenuId ? 1 : 2, + // Not on Done itself, and not on the "Chats" (quick chats) section. + // Also not on Automations. + when: ContextKeyExpr.and( + InboxModeContext.negate(), + ContextKeyExpr.notEquals(SessionSectionTypeContext.key, 'archived'), + ContextKeyExpr.notEquals(SessionSectionTypeContext.key, 'quickchats'), + ContextKeyExpr.notEquals(SessionSectionTypeContext.key, 'automations'), + ), + })) + }); + } + async run(accessor: ServicesAccessor, context?: ISessionSection): Promise<void> { + if (!context || !context.sessions || context.sessions.length === 0) { + return; + } + + const dialogService = accessor.get(IDialogService); + const storageService = accessor.get(IStorageService); + const sessionsManagementService = accessor.get(ISessionsManagementService); + const groupsService = accessor.get(ISessionGroupsService); + const viewsService = accessor.get(IViewsService); + const comparisonService = accessor.get(ISessionComparisonService); + + const skipConfirmation = storageService.getBoolean(ConfirmArchiveStorageKey, StorageScope.PROFILE, false); + if (!skipConfirmation) { + const confirmed = await dialogService.confirm({ + message: getArchiveSectionConfirmationMessage(context, this.wording), + detail: this.wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markSectionSessionsDone.detail', "You can restore sessions later if needed from the sessions view.") + : localize('archiveSectionSessions.detail', "You can unarchive sessions later if needed from the sessions view."), + primaryButton: getChatSessionArchiveActionPresentation(this.wording).archiveAll.title.value, + checkbox: { + label: localize('doNotAskAgain', "Do not ask me again") + } + }); + + if (!confirmed.confirmed) { + return; + } + + if (confirmed.checkboxChecked) { + storageService.store(ConfirmArchiveStorageKey, true, StorageScope.PROFILE, StorageTarget.USER); + } + } + + await archiveSessionsWithUndo(context.sessions, this.wording, sessionsManagementService, groupsService, viewsService, comparisonService); + } +} + +class ArchiveSectionAction extends BaseArchiveSectionAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class MarkSectionSessionsDoneAction extends BaseArchiveSectionAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +// Group Header Actions + +function getArchiveGroupConfirmationMessage(groupName: string, sessionCount: number, wording: ChatSessionArchiveActionWording): string { + if (sessionCount === 1) { + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markGroupSessionDone.confirmSingle', "Are you sure you want to mark 1 session from '{0}' as done?", groupName) + : localize('archiveGroupSession.confirmSingle', "Are you sure you want to archive 1 session from '{0}'?", groupName); + } + + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markGroupSessionsDone.confirm', "Are you sure you want to mark {0} sessions from '{1}' as done?", sessionCount, groupName) + : localize('archiveGroupSessions.confirm', "Are you sure you want to archive {0} sessions from '{1}'?", sessionCount, groupName); +} + +abstract class BaseArchiveSessionsInGroupAction extends Action2 { + constructor(private readonly wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).archiveAll; + super({ + id: ARCHIVE_SESSION_GROUP_COMMAND_ID, + title: action.title, + icon: action.icon, + menu: [SessionGroupToolbarMenuId, Menus.SessionGroupContext].map(id => ({ + id, + group: id === SessionGroupToolbarMenuId ? 'navigation' : '1_state', + order: 2, + when: ContextKeyExpr.and(SessionGroupHasVisibleSessionsContext, InboxModeContext.negate()), + })) + }); + } + async run(accessor: ServicesAccessor, context?: ISessionGroupItem): Promise<void> { + if (!context || context.comparison?.launching) { + return; + } + + const dialogService = accessor.get(IDialogService); + const storageService = accessor.get(IStorageService); + const sessionsManagementService = accessor.get(ISessionsManagementService); + const groupsService = accessor.get(ISessionGroupsService); + const viewsService = accessor.get(IViewsService); + const comparisonService = accessor.get(ISessionComparisonService); + const comparison = context.comparison ? comparisonService.getComparison(context.comparison.id) : undefined; + // A group's sessions include those of its subgroups. + const sessions = comparison + ? comparison.participants.flatMap(participant => { + const session = participant.sessionResource ? sessionsManagementService.getSession(participant.sessionResource) : undefined; + return session && !session.isArchived.get() ? [session] : []; + }) + : context.subtreeSessions; + if (sessions.length === 0) { + return; + } + + const skipConfirmation = storageService.getBoolean(ConfirmArchiveStorageKey, StorageScope.PROFILE, false); + if (!skipConfirmation) { + const confirmed = await dialogService.confirm({ + message: getArchiveGroupConfirmationMessage(context.group.name, sessions.length, this.wording), + detail: this.wording === ChatSessionArchiveActionWording.MarkAsDone + ? localize('markGroupSessionsDone.detail', "You can restore sessions later if needed from the sessions view.") + : localize('archiveGroupSessions.detail', "You can unarchive sessions later if needed from the sessions view."), + primaryButton: getChatSessionArchiveActionPresentation(this.wording).archiveAll.title.value, + checkbox: { + label: localize('doNotAskAgain', "Do not ask me again") + } + }); + + if (!confirmed.confirmed) { + return; + } + + if (confirmed.checkboxChecked) { + storageService.store(ConfirmArchiveStorageKey, true, StorageScope.PROFILE, StorageTarget.USER); + } + } + + await archiveSessionsWithUndo(sessions, this.wording, sessionsManagementService, groupsService, viewsService, comparisonService); + } +} + +class ArchiveSessionsInGroupAction extends BaseArchiveSessionsInGroupAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class MarkAllSessionsInGroupAsDoneAction extends BaseArchiveSessionsInGroupAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +function getSessionActionTargets(accessor: ServicesAccessor, context?: ISession | ISession[]): readonly ISession[] { + if (context) { + return Array.isArray(context) ? context : [context]; + } + + const focusedSessions = getFocusedSessionListTargets(accessor); + if (focusedSessions) { + return focusedSessions; + } + + const activeSession = resolveSessionCommandTarget(accessor, [])?.session; + return activeSession ? [activeSession] : []; +} + +function getFocusedSessionListTargets(accessor: ServicesAccessor): readonly ISession[] | undefined { + return accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.sessionsControl?.getFocusedSessions(); +} + +function triageSessions(modelService: ISessionsListModelService, viewsService: IViewsService, sessions: readonly ISession[], action: SessionInboxAction): void { + const targets = sessions.filter(session => !session.isArchived.get()); + if (!targets.length) { + return; + } + const undo = modelService.setInboxState(targets, action); + const message = action === undefined ? localize('inboxResumed', "{0} returned to inbox", targets.length) + : action === 'done' ? localize('inboxAcknowledged', "{0} acknowledged", targets.length) + : action === 'hold' ? localize('inboxHeld', "{0} put on hold", targets.length) + : localize('inboxSnoozed', "{0} snoozed", targets.length); + if (targets.length === 1 || action === 'done') { + status(message); + return; + } + viewsService.getViewWithId<SessionsView>(SessionsViewId)?.listNotification?.show({ + message, + help: localize('inboxTriageHelp', "This changes only Inbox mode. It does not stop or archive sessions. Undo restores the previous triage state unless it has changed since."), + showCountdown: true, + undo: async () => { undo(); status(localize('inboxTriageUndone', "Inbox change undone.")); }, + }); +} + +abstract class BaseArchiveSessionAction extends Action2 { + constructor(wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).archive; + super({ + id: ARCHIVE_SESSION_COMMAND_ID, + title: action.title, + icon: action.icon, + menu: [{ + id: Menus.SessionItemToolbar, + group: 'navigation', + order: 2, + when: ContextKeyExpr.and(ChatContextKeys.enabled, SessionIsArchivedContext.negate()), + }, { + id: SessionItemContextMenuId, + group: '1_state', + order: 3, + when: ContextKeyExpr.and(ChatContextKeys.enabled, SessionIsArchivedContext.negate()), + }, ...SessionHeaderMenus.map(id => ({ + id, + group: 'secondary/1_state', + order: 20, + when: ContextKeyExpr.and(SessionIsCreatedContext, ContextKeyExpr.equals(SessionIsArchivedContext.key, false), SessionHeaderTargetsChatContext.negate()), + }))] + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const targets = context + ? (Array.isArray(context) ? context : [context]) + : getFocusedSessionListTargets(accessor) ?? []; + const sessions = targets.filter(session => !session.isArchived.get()); + const sessionsManagementService = accessor.get(ISessionsManagementService); + const configurationService = accessor.get(IConfigurationService); + const accessibilityService = accessor.get(IAccessibilityService); + const accessibilitySignalService = accessor.get(IAccessibilitySignalService); + if ( + sessions.length > 0 + && configurationService.getValue<boolean>(SESSIONS_MARK_AS_DONE_CONFETTI_SETTING) + && !accessibilityService.isMotionReduced() + ) { + void accessibilitySignalService.playSignal(AccessibilitySignal.confetti); + } + for (const session of sessions) { + await sessionsManagementService.archiveSession(session); + } + } +} + +export class ArchiveSessionAction extends BaseArchiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class MarkSessionAsDoneAction extends BaseArchiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +abstract class BaseUnarchiveSessionAction extends Action2 { + constructor(wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).unarchive; + super({ + id: UNARCHIVE_SESSION_COMMAND_ID, + title: action.title, + icon: action.icon, + menu: [{ + id: Menus.SessionItemToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.equals(SessionIsArchivedContext.key, true), + }, { + id: SessionItemContextMenuId, + group: '1_state', + order: 3, + when: ContextKeyExpr.equals(SessionIsArchivedContext.key, true), + }, ...SessionHeaderMenus.map(id => ({ + id, + group: 'secondary/1_state', + order: 20, + when: ContextKeyExpr.equals(SessionIsArchivedContext.key, true), + }))] + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const sessionsManagementService = accessor.get(ISessionsManagementService); + if (!context) { + const activeSession = resolveSessionCommandTarget(accessor, [])?.session; + if (activeSession) { + await sessionsManagementService.unarchiveSession(activeSession); + } + return; + } + const sessions = Array.isArray(context) ? context : [context]; + for (const session of sessions) { + await sessionsManagementService.unarchiveSession(session); + } + } +} + +class UnarchiveSessionAction extends BaseUnarchiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class RestoreArchivedSessionAction extends BaseUnarchiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +abstract class BaseArchiveChatAction extends Action2 { + constructor(wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).archive; + const when = ContextKeyExpr.and(ChatContextKeys.enabled, SessionChatItemCanArchiveContext, SessionChatItemIsArchivedContext.negate()); + super({ + id: ARCHIVE_CHAT_COMMAND_ID, + title: action.title, + icon: action.icon, + menu: [{ + id: Menus.SessionChatItemContext, + group: '1_state', + order: 2, + when, + }, { + id: Menus.SessionChatItemToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and(when, SessionChatItemIsUntitledContext.negate()), + }, ...SessionHeaderMenus.map(id => ({ + id, + group: 'secondary/1_state', + order: 20, + when: ContextKeyExpr.and(SessionHeaderTargetsChatContext, SessionActiveChatCanArchiveContext, SessionActiveChatIsUntitledContext.negate()), + }))], + }); + } + + override async run(accessor: ServicesAccessor, context?: ISessionChatItem | ISession, chat?: IChat): Promise<void> { + let target: ISessionChatItem | undefined; + if (context && chat && hasKey(context, { sessionId: true })) { + target = { session: context, chat }; + } else if (context && hasKey(context, { session: true, chat: true })) { + target = context; + } + if (!target || target.chat.isArchived.get() || !getChatCapabilities(target.chat, target.session, undefined).canArchive) { + return; + } + const sessionsService = accessor.get(ISessionsService); + const sessionsManagementService = accessor.get(ISessionsManagementService); + const sessionsPartService = accessor.get(ISessionsPartService); + await sessionsManagementService.archiveChat(target.session, target.chat); + + // The chat leaves the grid's active pane when that pane shows it. + const activePane = sessionsPartService.getActiveSessionView()?.pane.get(); + const activeSession = activePane?.session.get(); + if (activePane && activeSession?.sessionId === target.session.sessionId) { + const openChat = activePane.tabs.openChats.get().find(chat => isEqual(chat.resource, target.chat.resource)); + if (openChat) { + await sessionsService.closeChat(activeSession, openChat); + } + } + } +} + +export class ArchiveChatAction extends BaseArchiveChatAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class MarkChatAsDoneAction extends BaseArchiveChatAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +abstract class BaseUnarchiveChatAction extends Action2 { + constructor(wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).unarchive; + const when = ContextKeyExpr.and(ChatContextKeys.enabled, SessionChatItemCanArchiveContext, SessionChatItemIsArchivedContext); + super({ + id: UNARCHIVE_CHAT_COMMAND_ID, + title: action.title, + icon: action.icon, + menu: [{ + id: Menus.SessionChatItemContext, + group: '1_state', + order: 2, + when, + }, { + id: Menus.SessionChatItemToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and(when, SessionChatItemIsUntitledContext.negate()), + }], + }); + } + + override async run(accessor: ServicesAccessor, context?: ISessionChatItem): Promise<void> { + if (!context || !context.chat.isArchived.get() || !getChatCapabilities(context.chat, context.session, undefined).canArchive) { + return; + } + await accessor.get(ISessionsManagementService).unarchiveChat(context.session, context.chat); + } +} + +class UnarchiveChatAction extends BaseUnarchiveChatAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class RestoreArchivedChatAction extends BaseUnarchiveChatAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +/** Opens the session of a chat that the Sessions list shows on its own row, such as a done chat in the Done section. */ + +/** Moves a nested chat up or down among its session's chats in the Sessions list, through its provider, which owns their order. Only offered when sorting by creation, as the list shows that order. */ +abstract class BaseMoveSessionListChatAction extends Action2 { + constructor(private readonly direction: 'up' | 'down') { + super({ + id: direction === 'up' ? 'sessionsViewPane.moveChatUp' : 'sessionsViewPane.moveChatDown', + title: direction === 'up' ? localize2('moveChatUp', "Move Up") : localize2('moveChatDown', "Move Down"), + precondition: ChatContextKeys.enabled, + keybinding: { + primary: KeyMod.Shift | KeyMod.Alt | (direction === 'up' ? KeyCode.UpArrow : KeyCode.DownArrow), + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and(IsSessionsWindowContext, FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey, SessionsListFocusedChatItemContext, ContextKeyExpr.equals(SessionsViewSortingContext.key, SessionsSorting.Created), direction === 'up' ? SessionChatItemCanMoveUpContext : SessionChatItemCanMoveDownContext), + }, + menu: [{ + id: Menus.SessionChatItemContext, + group: '2_organize', + order: direction === 'up' ? 1 : 2, + when: ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.equals(SessionsViewSortingContext.key, SessionsSorting.Created), direction === 'up' ? SessionChatItemCanMoveUpContext : SessionChatItemCanMoveDownContext), + }], + }); + } + + override run(accessor: ServicesAccessor, context?: ISessionChatItem): void { + const sessionsList = accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.sessionsControl; + const target = context ?? sessionsList?.getFocusedChatItem(); + if (target) { + sessionsList?.moveChat(target, this.direction); + } + } +} + +function setSessionListChatReadState(sessionsManagementService: ISessionsManagementService, { session, chat }: ISessionChatItem, isRead: boolean): Promise<boolean | void> { + if (isEqual(chat.resource, session.mainChat.get().resource)) { + return isRead ? sessionsManagementService.markRead(session) : sessionsManagementService.markUnread(session); + } + return isRead ? sessionsManagementService.markChatRead(session, chat) : sessionsManagementService.markChatUnread(session, chat); +} + +async function markSessionListTargetsRead(accessor: ServicesAccessor, context: ISession | ISession[] | ISessionChatItem | undefined, isRead: boolean): Promise<void> { + const sessionsManagementService = accessor.get(ISessionsManagementService); + if (context && !Array.isArray(context) && hasKey(context, { session: true, chat: true })) { + await setSessionListChatReadState(sessionsManagementService, context, isRead); + return; + } + if (!context) { + const chats = accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.sessionsControl?.getFocusedChatItems() ?? []; + if (chats.length > 0) { + for (const chat of chats) { + await setSessionListChatReadState(sessionsManagementService, chat, isRead); + } + return; + } + } + const sessions = context ? (Array.isArray(context) ? context : [context]) : getFocusedSessionListTargets(accessor) ?? []; + for (const session of sessions) { + await (isRead ? sessionsManagementService.markRead(session) : sessionsManagementService.markUnread(session)); + } +} + +abstract class BaseUnarchiveActiveSessionAction extends Action2 { + + constructor(wording: ChatSessionArchiveActionWording) { + const action = getChatSessionArchiveActionPresentation(wording).unarchive; + super({ + id: 'agentSession.restore', + title: action.title, + icon: action.icon, + menu: [{ + id: MenuId.AgentsChangesToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and( + IsSessionsWindowContext, + SessionIsArchivedContext + ) + }] + }); + } + + async run(accessor: ServicesAccessor, sessionArg?: unknown): Promise<void> { + const sessionsManagementService = accessor.get(ISessionsManagementService); + const session = resolveSessionCommandTarget(accessor, [sessionArg])?.session; + if (!session || session.status.get() === SessionStatus.Untitled) { + return; + } + + await sessionsManagementService.unarchiveSession(session); + } +} + +class UnarchiveActiveSessionAction extends BaseUnarchiveActiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.Archive); + } +} + +class RestoreActiveSessionAction extends BaseUnarchiveActiveSessionAction { + constructor() { + super(ChatSessionArchiveActionWording.MarkAsDone); + } +} + +/** + * The archive actions for a wording. Both wordings share command ids, so only + * one set can be registered at a time. + */ +export function getSessionsArchiveActionConstructors(wording: ChatSessionArchiveActionWording): readonly { new(): Action2 }[] { + return wording === ChatSessionArchiveActionWording.MarkAsDone + ? [ + MarkSectionSessionsDoneAction, + MarkAllSessionsInGroupAsDoneAction, + MarkSessionAsDoneAction, + MarkChatAsDoneAction, + RestoreArchivedSessionAction, + RestoreArchivedChatAction, + RestoreActiveSessionAction, + ] + : [ + ArchiveSectionAction, + ArchiveSessionsInGroupAction, + ArchiveSessionAction, + ArchiveChatAction, + UnarchiveSessionAction, + UnarchiveChatAction, + UnarchiveActiveSessionAction, + ]; +} + +export class SessionsArchiveActionsContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.sessionsArchiveActions'; + + private readonly actionRegistrations = this._register(new DisposableStore()); + + constructor( + @IConfigurationService private readonly configurationService: IConfigurationService, + ) { + super(); + this.registerActions(); + this._register(this.configurationService.onDidChangeConfiguration(event => { + if (event.affectsConfiguration(ChatSessionArchiveActionWordingSettingId)) { + this.registerActions(); + } + })); + } + + private registerActions(): void { + this.actionRegistrations.clear(); + const wording = getChatSessionArchiveActionWording(this.configurationService); + for (const action of getSessionsArchiveActionConstructors(wording)) { + this.actionRegistrations.add(registerAction2(action)); + } + } +} + +/** + * Registers the actions, menu items, keybindings and accessibility help of the sessions list that do not depend on the + * window it shows in, until the returned disposable is disposed. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerSessionsListActions(): IDisposable { + const store = new DisposableStore(); + + store.add(AccessibleViewRegistry.register({ + name: 'sessions-list-notification', + type: AccessibleViewType.Help, + priority: 110, + when: SessionsListNotificationFocused, + getProvider: accessor => accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.listNotification?.getAccessibilityHelp(), + })); + + store.add(CommandsRegistry.registerCommand(ARCHIVE_SESSIONS_WITH_UNDO_COMMAND_ID, (accessor, sessions: readonly ISession[]) => archiveSessionsWithUndo( + sessions, + getChatSessionArchiveActionWording(accessor.get(IConfigurationService)), + accessor.get(ISessionsManagementService), + accessor.get(ISessionGroupsService), + accessor.get(IViewsService), + accessor.get(ISessionComparisonService), + ))); + + store.add(CommandsRegistry.registerCommand(DELETE_SESSION_GROUP_WITH_UNDO_COMMAND_ID, (accessor, groupId: string) => deleteSessionGroupWithUndo( + groupId, + accessor.get(ISessionGroupsService), + accessor.get(IViewsService), + ))); + + store.add(registerAction2(class ShowSessionApplicationFiltersAction extends Action2 { + constructor() { + super({ + id: SHOW_SESSION_APPLICATION_FILTERS_COMMAND_ID, + title: localize2('showApplicationFilters', "Filter Sessions by Application"), + precondition: ChatContextKeys.enabled, + }); + } + + override async run(accessor: ServicesAccessor): Promise<void> { + const view = await accessor.get(IViewsService).openView<SessionsView>(SessionsViewId); + view?.showApplicationFilters(); + } + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SidebarSessionsHeader, { + submenu: Menus.SessionsViewFilter, + title: localize2('filterSessions', "Filter Sessions"), + icon: Codicon.filter, + group: 'navigation', + order: 10, + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SidebarSessionsHeader, { + command: { + id: 'sessionsViewPane.find', + title: localize2('find', "Find Session"), + icon: Codicon.search, + }, + group: 'navigation', + order: 20, + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { + submenu: Menus.SessionsViewOrdering, + title: localize2('ordering', "Ordering"), + group: '1_presentation', + order: 0, + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { + submenu: Menus.SessionsViewGrouping, + title: localize2('grouping', "Grouping"), + group: '1_presentation', + order: 1, + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { + submenu: Menus.SessionsViewShow, + title: localize2('showSessions', "Show"), + when: GroupedBySectionContext, + group: '1_presentation', + order: 2, + })); + + for (const [index, item] of [ + { submenu: Menus.SessionsViewSource, title: localize2('createdIn', "Created In") }, + { submenu: Menus.SessionsViewHarness, title: localize2('harness', "Harness") }, + ].entries()) { + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { + ...item, + group: '2_filters', + order: index + 1, + })); + } + + store.add(registerExternalSessionsFilterMenu(Menus.SessionsViewFilter, Menus.SessionsViewExternalFilter, '3_visibility', false, localize2('createdExternally', "Created Externally"))); + + store.add(registerAction2(class ToggleExternalSessionsSectionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.toggleExternalSessionsSection', + title: localize2('showInExternalSection', "Show in External Section"), + toggled: ContextKeyExpr.equals(`config.${SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING}`, true), + menu: { + id: Menus.SessionsViewExternalFilter, + group: '2_grouping', + order: 0, + when: ChatContextKeys.enabled, + }, + }); + } + + override async run(accessor: ServicesAccessor): Promise<void> { + const configurationService = accessor.get(IConfigurationService); + await configurationService.updateValue( + SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, + !configurationService.getValue<boolean>(SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING), + ConfigurationTarget.USER, + ); + } + })); + + store.add(MenuRegistry.appendMenuItem(SessionSectionToolbarMenuId, { + submenu: Menus.SessionsViewExternalFilter, + title: localize2('configureExternalSessions', "Configure External Sessions"), + icon: Codicon.filter, + group: 'navigation', + order: 0, + when: ContextKeyExpr.equals(SessionSectionTypeContext.key, 'external'), + })); + + store.add(MenuRegistry.appendMenuItem(Menus.SessionSectionContext, { + submenu: Menus.SessionsViewExternalFilter, + title: localize2('configureExternalSessions', "Configure External Sessions"), + group: '4_manage', + order: 1, + when: ContextKeyExpr.equals(SessionSectionTypeContext.key, 'external'), + })); + + store.add(registerAction2(class InboxModeAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.inboxMode', + title: localize2('inboxMode', "Inbox Mode"), + category: SessionsCategories.Sessions, + f1: true, + precondition: ContextKeyExpr.and(IsSessionsWindowContext, ChatContextKeys.enabled), + toggled: InboxModeContext, + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 4, when: ChatContextKeys.enabled }], + }); + } + run(accessor: ServicesAccessor): void { + accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.setGrouping(SessionsGrouping.Inbox); + } + })); + + store.add(registerAction2(class SortByCreatedAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.sortByCreated', + title: localize2('created', "Created"), + category: SessionsCategories.Sessions, + toggled: ContextKeyExpr.equals(SessionsViewSortingContext.key, SessionsSorting.Created), + menu: [{ id: Menus.SessionsViewOrdering, group: '1_sort', order: 0 }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.setSorting(SessionsSorting.Created); + } + })); + + store.add(registerAction2(class SortByUpdatedAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.sortByUpdated', + title: localize2('updated', "Updated"), + category: SessionsCategories.Sessions, + toggled: ContextKeyExpr.equals(SessionsViewSortingContext.key, SessionsSorting.Updated), + menu: [{ id: Menus.SessionsViewOrdering, group: '1_sort', order: 1 }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.setSorting(SessionsSorting.Updated); + } + })); + + store.add(registerAction2(class GroupByWorkspaceAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.groupByWorkspace', + title: localize2('workspace', "Workspace"), + category: SessionsCategories.Sessions, + toggled: ContextKeyExpr.equals(SessionsViewGroupingContext.key, SessionsGrouping.Workspace), + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 1 }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.setGrouping(SessionsGrouping.Workspace); + } + })); + + store.add(registerAction2(class GroupByRepositoryAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.groupByRepository', + title: localize2('repository', "Repository"), + category: SessionsCategories.Sessions, + toggled: ContextKeyExpr.equals(SessionsViewGroupingContext.key, SessionsGrouping.Repository), + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 2 }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.setGrouping(SessionsGrouping.Repository); + } + })); + + store.add(registerAction2(class GroupByTimeAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.groupByTime', + title: localize2('time', "Time"), + category: SessionsCategories.Sessions, + toggled: ContextKeyExpr.equals(SessionsViewGroupingContext.key, SessionsGrouping.Date), + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 0 }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.setGrouping(SessionsGrouping.Date); + } + })); + + store.add(registerAction2(class GroupByEnvironmentAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.groupByEnvironment', + title: localize2('groupByEnvironment', "Environment"), + category: SessionsCategories.Sessions, + toggled: SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Environment), + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 3 }], + }); + } + override run(accessor: ServicesAccessor) { + const view = accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId); + view?.setGrouping(SessionsGrouping.Environment); + } + })); + + store.add(registerAction2(class ToggleCompactSessionsViewAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.toggleCompact', + title: localize2('toggleCompactSessionsView', "Compact View"), + category: SessionsCategories.Sessions, + toggled: SessionsViewCompactContext, + menu: [{ + id: Menus.SidebarSessionsHeader, + group: '1_view', + order: 0, + when: ContextKeyExpr.and(ChatContextKeys.enabled, IsPhoneLayoutContext.negate()), + }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.toggleCompact(); + } + })); + + store.add(registerAction2(class ShowRecentWorkspaceSessionsAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.showRecentSessions', + title: localize2('recent', "Recent"), + category: SessionsCategories.Sessions, + toggled: IsWorkspaceGroupCappedContext, + menu: [{ + id: Menus.SessionsViewShow, + group: '1_show', + order: 0, + when: GroupedBySectionContext, + }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.sessionsControl?.setWorkspaceGroupCapped(true); + IsWorkspaceGroupCappedContext.bindTo(accessor.get(IContextKeyService)).set(true); + } + })); + + store.add(registerAction2(class ShowAllWorkspaceSessionsAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.showAllSessions', + title: localize2('all', "All"), + category: SessionsCategories.Sessions, + toggled: IsWorkspaceGroupCappedContext.negate(), + menu: [{ + id: Menus.SessionsViewShow, + group: '1_show', + order: 1, + when: GroupedBySectionContext, + }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.sessionsControl?.setWorkspaceGroupCapped(false); + IsWorkspaceGroupCappedContext.bindTo(accessor.get(IContextKeyService)).set(false); + } + })); + + store.add(registerAction2(class CollapseAllGroupsAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.collapseAllGroups', + title: localize2('collapseAllGroups', "Collapse All Groups"), + category: SessionsCategories.Sessions, + menu: [{ id: Menus.SidebarSessionsHeader, group: '1_view', order: 1, when: ChatContextKeys.enabled }] + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + view?.sessionsControl?.collapseAllSections(); + } + })); + + store.add(registerAction2(class RefreshSessionsAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.refresh', + title: localize2('refresh', "Refresh Sessions"), + icon: Codicon.refresh, + f1: true, + category: SessionsCategories.Sessions, + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + return view?.sessionsControl?.refresh(); + } + })); + + store.add(registerAction2(class FindSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.find', + title: localize2('find', "Find Session"), + icon: Codicon.search, + category: SessionsCategories.Sessions, + keybinding: { + // The list has its own find widget, so it takes over the keybindings of the tree's (`list.find`). + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and(FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey), + primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyF, + secondary: [KeyCode.F3], + }, + }); + } + override run(accessor: ServicesAccessor) { + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + return view?.openFind(); + } + })); + + store.add(KeybindingsRegistry.registerCommandAndKeybindingRule({ + id: 'sessionsViewPane.closeFind', + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and(FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey, SessionsListSearchOpenContext), + primary: KeyCode.Escape, + handler: accessor => accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.sessionsControl?.closeFind(), + })); + + store.add(registerAction2(class DeleteEmptySessionGroupAction extends Action2 { + constructor() { + super({ + id: 'sessionsView.deleteEmptyGroup', + title: localize2('deleteEmptyGroup', "Delete Group"), + icon: Codicon.trash, + menu: [{ + id: SessionGroupToolbarMenuId, + group: 'navigation', + order: 2, + when: ContextKeyExpr.and(SessionGroupIsEmptyContext, SessionGroupIsComparisonContext.negate()), + }] + }); + } + run(accessor: ServicesAccessor, context?: ISessionGroupItem): void { + if (!context || context.comparison) { + return; + } + const sessionGroupsService = accessor.get(ISessionGroupsService); + const hasSubgroups = sessionGroupsService.getTree().getSubgroups(context.group.id).length > 0; + if (!hasSubgroups && sessionGroupsService.getSectionIdsInGroup(context.group.id).length === 0 && sessionGroupsService.getSessionIdsInGroup(context.group.id).length === 0) { + sessionGroupsService.deleteGroup(context.group.id); + } + } + })); + + store.add(registerAction2(class PinSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.pinSession', + title: localize2('pinSession', "Pin"), + icon: Codicon.pin, + menu: [{ + id: Menus.SessionItemToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and( + SessionsListPromoteNewChatActionContext.negate(), + ContextKeyExpr.equals(IsSessionPinnedContext.key, false), + ContextKeyExpr.equals(SessionIsArchivedContext.key, false), + ), + }, { + id: SessionItemContextMenuId, + group: SessionItemOrganizeMenuGroup, + order: 1, + when: ContextKeyExpr.and( + ContextKeyExpr.equals(IsSessionPinnedContext.key, false), + ContextKeyExpr.equals(SessionIsArchivedContext.key, false), + ), + }] + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + if (!context) { + return; + } + const sessions = Array.isArray(context) ? context : [context]; + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + for (const session of sessions) { + view?.sessionsControl?.pinSession(session); + } + } + })); + + store.add(registerAction2(class UnpinSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.unpinSession', + title: localize2('unpinSession', "Unpin"), + icon: Codicon.pinned, + menu: [{ + id: Menus.SessionItemToolbar, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and( + SessionsListPromoteNewChatActionContext.negate(), + ContextKeyExpr.equals(IsSessionPinnedContext.key, true), + ContextKeyExpr.equals(SessionIsArchivedContext.key, false), + ), + }, { + id: SessionItemContextMenuId, + group: SessionItemOrganizeMenuGroup, + order: 1, + when: ContextKeyExpr.and( + ContextKeyExpr.equals(IsSessionPinnedContext.key, true), + ContextKeyExpr.equals(SessionIsArchivedContext.key, false), + ), + }] + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + if (!context) { + return; + } + const sessions = Array.isArray(context) ? context : [context]; + const viewsService = accessor.get(IViewsService); + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId); + for (const session of sessions) { + view?.sessionsControl?.unpinSession(session); + } + } + })); + + store.add(registerAction2(class AcknowledgeInboxSessionAction extends Action2 { + constructor() { + super({ + id: ACKNOWLEDGE_INBOX_SESSION_COMMAND_ID, + title: localize2('inboxAcknowledge', "Acknowledge"), + tooltip: localize('inboxAcknowledgeTooltip', "Acknowledge: Remove from Inbox until new activity"), + icon: Codicon.eye, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), + menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ + id, + group: id === Menus.SessionItemToolbar ? 'navigation' : '1_state', + order: 0.5, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), + id === Menus.SessionItemToolbar ? SessionItemCanAcknowledgeContext : SessionItemInboxStateContext.notEqualsTo('done')), + })), + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + triageSessions(accessor.get(ISessionsListModelService), accessor.get(IViewsService), getSessionActionTargets(accessor, context), 'done'); + } + })); + + store.add(registerAction2(class ResumeInboxSessionAction extends Action2 { + constructor() { + super({ + id: RESUME_INBOX_SESSION_COMMAND_ID, + title: localize2('inboxResume', "Return to Inbox"), + icon: Codicon.inbox, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), + menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ + id, + group: id === Menus.SessionItemToolbar ? 'navigation' : '1_state', + order: 1, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), SessionItemInboxStateContext.notEqualsTo('')), + })), + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + triageSessions(accessor.get(ISessionsListModelService), accessor.get(IViewsService), getSessionActionTargets(accessor, context), undefined); + } + })); + + store.add(registerAction2(class SnoozeInboxSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.inboxSnooze', + title: localize2('inboxSnooze', "Snooze..."), + icon: Codicon.history, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), + menu: [{ + id: SessionItemContextMenuId, + group: '1_state', + order: 1.5, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate()), + }], + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const sessions = getSessionActionTargets(accessor, context); + const quickInput = accessor.get(IQuickInputService); + const modelService = accessor.get(ISessionsListModelService); + const viewsService = accessor.get(IViewsService); + const now = new Date(); + const morning = (days: number) => new Date(now.getFullYear(), now.getMonth(), now.getDate() + days, 9).getTime(); + const picked = await quickInput.pick([ + { label: localize('snoozeHour', "In One Hour"), value: now.getTime() + 60 * 60 * 1000 }, + { label: localize('snoozeTomorrow', "Tomorrow Morning"), value: morning(1) }, + { label: localize('snoozeWeek', "In One Week"), value: morning(7) }, + { label: localize('snoozeActivity', "Until New Activity"), value: 'untilActivity' as const }, + { label: localize('snoozeDate', "Pick a Date and Time..."), value: 'custom' as const }, + ], { placeHolder: localize('snoozeReturnPlaceholder', "When should these sessions leave On hold? They will return to Inbox, Working, or Ready to merge based on their activity.") }); + if (!picked) { + return; + } + let action: SessionInboxAction; + if (picked.value === 'custom') { + const parse = (value: string): number => { + if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(value)) { + return NaN; + } + const date = new Date(value.replace(' ', 'T')); + const formatted = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; + return formatted === value ? date.getTime() : NaN; + }; + const value = await quickInput.input({ + prompt: localize('snoozeDatePrompt', "Enter a future local date and time (YYYY-MM-DD HH:mm)"), + validateInput: async value => Number.isFinite(parse(value)) && parse(value) > Date.now() + ? undefined : localize('snoozeInvalidDate', "Enter a valid future date and time in YYYY-MM-DD HH:mm format."), + }); + if (value === undefined) { + return; + } + action = parse(value); + } else { + action = picked.value; + } + triageSessions(modelService, viewsService, sessions, action); + } + })); + + store.add(registerAction2(class MergeInboxPullRequestAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.inboxMergePullRequest', + title: localize2('inboxMergePullRequest', "Merge Pull Request"), + icon: Codicon.gitMerge, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionItemCanMergePullRequestContext, SessionItemIsMultiSelectionContext.negate()), + menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ + id, + group: id === Menus.SessionItemToolbar ? 'navigation' : '1_state', + order: 0, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), SessionItemCanMergePullRequestContext), + })), + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const sessions = getSessionActionTargets(accessor, context); + const session = sessions.length === 1 ? sessions[0] : undefined; + const attention = accessor.get(ISessionAttentionService).sessionAttention.get(); + const model = accessor.get(ISessionsListModelService); + const merge = session && !session.isArchived.get() + && getSessionInboxSection(session, model.getInboxState(session), undefined, attention.get(session.sessionId)) === SessionInboxSection.ReadyToMerge + ? getInboxPullRequestMergeOperation(session) : undefined; + if (!merge) { + throw new Error(localize('inboxMergeUnavailable', "This pull request is no longer available to merge.")); + } + await merge.changeset.invokeOperation(merge.operation.id); + } + })); + + store.add(registerAction2(class HoldInboxSessionAction extends Action2 { + constructor() { + super({ + id: HOLD_INBOX_SESSION_COMMAND_ID, + title: localize2('inboxHold', "Put on Hold"), + icon: Codicon.history, + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext), + menu: [{ + id: SessionItemContextMenuId, + group: '1_state', + order: 1.25, + when: ContextKeyExpr.and(ChatContextKeys.enabled, InboxModeContext, SessionIsArchivedContext.negate(), SessionItemInboxStateContext.notEqualsTo('hold')), + }], + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + triageSessions(accessor.get(ISessionsListModelService), accessor.get(IViewsService), getSessionActionTargets(accessor, context), 'hold'); + } + })); + + store.add(registerAction2(class ShowAutomationSessionInListAction extends Action2 { + constructor() { + super({ + id: SHOW_AUTOMATION_SESSION_IN_LIST_COMMAND_ID, + title: localize2('showAutomationSessionInList', "Show in Sessions List"), + menu: [{ + id: Menus.AutomationsHistoryItemContext, + group: SessionItemOrganizeMenuGroup, + order: 1, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + ChatAutomationsEnabledContext, + SessionItemIsAutomationContext, + SessionItemIsInSessionsListContext.negate(), + SessionIsArchivedContext.negate(), + ), + }], + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + const sessions = getSessionActionTargets(accessor, context).filter(session => isAutomationSession(session) && !session.isArchived.get()); + if (sessions.length === 0) { + return; + } + accessor.get(ISessionsListModelService).showAutomationSessions(sessions); + status(sessions.length === 1 + ? localize('automationSessionShownInList', "{0} is now shown in the Sessions list.", sessions[0].title.get()) + : localize('automationSessionsShownInList', "{0} sessions are now shown in the Sessions list.", sessions.length)); + } + })); + + store.add(registerAction2(class HideAutomationSessionFromListAction extends Action2 { + constructor() { + super({ + id: HIDE_AUTOMATION_SESSION_FROM_LIST_COMMAND_ID, + title: localize2('hideAutomationSessionFromList', "Hide from Sessions List"), + menu: [SessionItemContextMenuId, Menus.AutomationsHistoryItemContext].map(id => ({ + id, + group: SessionItemOrganizeMenuGroup, + order: 2, + when: ContextKeyExpr.and( + ChatContextKeys.enabled, + ChatAutomationsEnabledContext, + SessionItemIsAutomationContext, + SessionItemIsInSessionsListContext, + ), + })), + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + const sessions = getSessionActionTargets(accessor, context).filter(isAutomationSession); + if (sessions.length === 0) { + return; + } + accessor.get(ISessionsListModelService).hideAutomationSessions(sessions); + status(sessions.length === 1 + ? localize('automationSessionHiddenFromList', "{0} is now shown only in Automations.", sessions[0].title.get()) + : localize('automationSessionsHiddenFromList', "{0} sessions are now shown only in Automations.", sessions.length)); + } + })); + + store.add(KeybindingsRegistry.registerKeybindingRule({ + id: ARCHIVE_SESSION_COMMAND_ID, + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and( + IsSessionsWindowContext, + FocusedViewContext.isEqualTo(SessionsViewId), + WorkbenchListFocusContextKey, + ), + primary: KeyCode.Delete, + mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace }, + })); + + store.add(registerAction2(class ImportSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.importSession', + title: localize2('importSession', "Import"), + icon: Codicon.chatImport, + precondition: ChatContextKeys.enabled, + menu: [Menus.SessionItemToolbar, SessionItemContextMenuId].map(id => ({ + id, + group: 'navigation', + order: id === Menus.SessionItemToolbar ? 1.5 : 3, + when: ContextKeyExpr.and(ChatContextKeys.enabled, SessionItemCanImportContext, SessionIsArchivedContext.negate()), + })), + }); + } + + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const sessions = getSessionActionTargets(accessor, context).filter(session => + session.isExternal?.get() === true && session.capabilities.get().supportsImport && !session.isArchived.get()); + const sessionsManagementService = accessor.get(ISessionsManagementService); + for (const session of sessions) { + await sessionsManagementService.importSession(session); + } + if (sessions.length > 0) { + status(sessions.length === 1 + ? localize('sessionImported', "Imported {0}.", sessions[0].title.get()) + : localize('sessionsImported', "Imported {0} sessions.", sessions.length)); + } + } + })); + + store.add(registerAction2(class OpenParentSessionAction extends Action2 { + constructor() { + super({ + id: 'sessions.list.openParentSession', + title: localize2('openParentSession', "Open Parent Session"), + icon: Codicon.typeHierarchySuper, + f1: false, + menu: [{ + id: Menus.SessionChatItemContext, + group: 'navigation', + order: 1, + when: SessionChatItemIsStandaloneContext, + }, { + id: Menus.SessionChatItemToolbar, + group: 'navigation', + order: 0, + when: SessionChatItemIsStandaloneContext, + }], + }); + } + + override run(accessor: ServicesAccessor, context?: ISessionChatItem): void { + if (!context) { + return; + } + accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId)?.sessionsControl?.openSession(context.session); + } + })); + + store.add(registerAction2(class MoveSessionListChatUpAction extends BaseMoveSessionListChatAction { + constructor() { + super('up'); + } + })); + + store.add(registerAction2(class MoveSessionListChatDownAction extends BaseMoveSessionListChatAction { + constructor() { + super('down'); + } + })); + + store.add(registerAction2(class RenameSessionAction extends Action2 { + constructor() { + super({ + id: RENAME_SESSION_COMMAND_ID, + title: localize2('renameSession', "Rename..."), + icon: Codicon.edit, + precondition: SessionItemIsMultiSelectionContext.negate(), + keybinding: { + primary: KeyCode.F2, + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and( + IsSessionsWindowContext, + ContextKeyExpr.or( + ContextKeyExpr.and(FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey), + ContextKeyExpr.and(ChatContextKeys.inChatSession, SessionSupportsRenameContext), + ), + ), + }, + menu: [{ + id: SessionItemContextMenuId, + group: '4_manage', + order: 2, + when: SessionSupportsRenameContext, + }] + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + const focusedSessions = context ? undefined : getFocusedSessionListTargets(accessor); + const session = getSessionActionTargets(accessor, context)[0]; + if (!session || !session.capabilities.get().supportsRename) { + return; + } + if (focusedSessions?.includes(session)) { + const view = accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId); + if (view?.sessionsControl?.beginRenameSession(session)) { + return; + } + } + const quickInputService = accessor.get(IQuickInputService); + const sessionsManagementService = accessor.get(ISessionsManagementService); + const newTitle = await quickInputService.input({ + value: session.title.get(), + prompt: localize('renameSession.prompt', "New agent session title"), + validateInput: async value => { + if (!value.trim()) { + return localize('renameSession.empty', "Title cannot be empty"); + } + return undefined; + } + }); + if (newTitle) { + const trimmedTitle = newTitle.trim(); + if (trimmedTitle && trimmedTitle !== session.title.get().trim()) { + await sessionsManagementService.renameSession(session, trimmedTitle); + } + } + } + })); + + store.add(registerAction2(class DeleteSessionAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.deleteSession', + title: localize2('deleteSession', "Delete..."), + menu: [{ + id: SessionItemContextMenuId, + group: '4_manage', + order: 3, + when: SessionSupportsDeleteContext, + }] + }); + } + async run(accessor: ServicesAccessor, context?: ISession | ISession[]): Promise<void> { + if (!context) { + return; + } + const sessions = (Array.isArray(context) ? context : [context]).filter(session => session.capabilities.get().supportsDelete); + if (sessions.length === 0) { + return; + } + + const dialogService = accessor.get(IDialogService); + const sessionsManagementService = accessor.get(ISessionsManagementService); + + const confirmed = await dialogService.confirm({ + message: sessions.length === 1 + ? localize('deleteSession.confirm', "Are you sure you want to delete this session?") + : localize('deleteSessions.confirm', "Are you sure you want to delete {0} sessions?", sessions.length), + detail: localize('deleteSession.detail', "This action cannot be undone."), + primaryButton: localize('deleteSession.delete', "Delete") + }); + if (!confirmed.confirmed) { + return; + } + + try { + await sessionsManagementService.deleteSessions(sessions); + } catch (err) { + dialogService.error(sessions.length === 1 + ? localize('deleteSession.error', "Failed to delete the session: {0}", toErrorMessage(err)) + : localize('deleteSessions.error', "Failed to delete the sessions: {0}", toErrorMessage(err))); + } + } + })); + + store.add(CommandsRegistry.registerCommandAlias('sessionsViewPane.markRead', MARK_SESSION_READ_COMMAND_ID)); + + store.add(CommandsRegistry.registerCommandAlias('sessionsViewPane.markUnread', MARK_SESSION_UNREAD_COMMAND_ID)); + + store.add(registerAction2(class MarkSessionReadAction extends Action2 { + constructor() { + super({ + id: MARK_SESSION_READ_COMMAND_ID, + title: localize2('markRead', "Mark as Read"), + keybinding: { + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and(IsSessionsWindowContext, FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey), + primary: KeyMod.Shift | KeyCode.KeyI, + }, + menu: [{ + id: SessionItemContextMenuId, + group: '1_state', + order: 1, + when: ContextKeyExpr.and( + SessionIsReadContext.negate(), + SessionIsArchivedContext.negate(), + ), + }, { + id: Menus.SessionChatItemContext, + group: '1_state', + order: 1, + when: ContextKeyExpr.and( + SessionChatItemCanSetReadStateContext, + SessionChatItemIsReadContext.negate(), + SessionChatItemIsArchivedContext.negate(), + ), + }, ...SessionHeaderMenus.map(id => ({ + id, + group: 'secondary/1_state', + order: 10, + when: ContextKeyExpr.and( + SessionIsCreatedContext, + SessionIsReadContext.negate(), + SessionIsArchivedContext.negate(), + ), + }))] + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[] | ISessionChatItem): Promise<void> { + return markSessionListTargetsRead(accessor, context, true); + } + })); + + store.add(registerAction2(class MarkSessionUnreadAction extends Action2 { + constructor() { + super({ + id: MARK_SESSION_UNREAD_COMMAND_ID, + title: localize2('markUnread', "Mark as Unread"), + keybinding: { + weight: KeybindingWeight.SessionsContrib, + when: ContextKeyExpr.and(IsSessionsWindowContext, FocusedViewContext.isEqualTo(SessionsViewId), WorkbenchListFocusContextKey), + primary: KeyMod.Shift | KeyCode.KeyU, + }, + menu: [{ + id: SessionItemContextMenuId, + group: '1_state', + order: 1, + when: ContextKeyExpr.and( + SessionIsReadContext, + SessionIsArchivedContext.negate(), + ), + }, { + id: Menus.SessionChatItemContext, + group: '1_state', + order: 1, + when: ContextKeyExpr.and( + SessionChatItemCanSetReadStateContext, + SessionChatItemIsReadContext, + SessionChatItemIsArchivedContext.negate(), + ), + }, ...SessionHeaderMenus.map(id => ({ + id, + group: 'secondary/1_state', + order: 10, + when: ContextKeyExpr.and( + SessionIsCreatedContext, + SessionIsReadContext, + SessionIsArchivedContext.negate(), + ), + }))] + }); + } + run(accessor: ServicesAccessor, context?: ISession | ISession[] | ISessionChatItem): Promise<void> { + return markSessionListTargetsRead(accessor, context, false); + } + })); + + store.add(registerAction2(class MarkAllNestedSessionsReadAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.markAllNestedRead', + title: localize2('markAllNestedRead', "Mark Nested Sessions as Read"), + menu: [{ + id: SessionItemContextMenuId, + group: '1_state', + order: 2, + when: SessionItemHasUnreadNestedSessionsContext, + }] + }); + } + + run(accessor: ServicesAccessor, context?: ISession | ISession[]): void { + if (!context) { + return; + } + const sessions = Array.isArray(context) ? context : [context]; + const sessionsManagementService = accessor.get(ISessionsManagementService); + void Promise.all(sessions.map(session => { + if (session.isArchived.get() || session.capabilities.get().supportsIndependentChatReadState !== true) { + return; + } + return sessionsManagementService.markChatsRead(session, getSessionListChats(session).filter(chat => !chat.isRead.get())); + })).catch(onUnexpectedError); + } + })); + + for (const [menu, submenu] of [ + [Menus.SessionItemContextMenu, Menus.SessionItemOpenIn], + [Menus.SessionChatItemContext, Menus.SessionChatItemOpenIn], + ]) { + store.add(MenuRegistry.appendMenuItem(menu, { + title: localize2('openIn', "Open in"), + submenu, + group: 'navigation', + order: 1, + when: ContextKeyExpr.and(ChatContextKeys.enabled, IsSessionsWindowContext), + })); + } + + // Worktree grouping is offered only outside the Agents window, which shares the stored grouping and never shows it + const OffersWorktreeGroupingContext = IsSessionsWindowContext.negate(); + const GroupedByWorktreeContext = ContextKeyExpr.and(OffersWorktreeGroupingContext, SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Worktree)); + + store.add(registerAction2(class GroupByWorktreeAction extends Action2 { + constructor() { + super({ + id: 'sessionsViewPane.groupByWorktree', + title: localize2('groupByWorktree', "Worktree"), + category: SessionsCategories.Sessions, + toggled: GroupedByWorktreeContext, + precondition: OffersWorktreeGroupingContext, + menu: [{ id: Menus.SessionsViewGrouping, group: '1_group', order: 3.5, when: OffersWorktreeGroupingContext }], + }); + } + override run(accessor: ServicesAccessor) { + const view = accessor.get(IViewsService).getViewWithId<SessionsView>(SessionsViewId); + view?.setGrouping(SessionsGrouping.Worktree); + } + })); + + // Worktree grouping caps its sections as the other groupings by section do, which Show switches between Recent and All + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { + submenu: Menus.SessionsViewShow, + title: localize2('showSessions', "Show"), + when: GroupedByWorktreeContext, + group: '1_presentation', + order: 2, + })); + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewShow, { + command: { id: 'sessionsViewPane.showRecentSessions', title: localize2('recent', "Recent"), toggled: IsWorkspaceGroupCappedContext }, + group: '1_show', + order: 0, + when: GroupedByWorktreeContext, + })); + store.add(MenuRegistry.appendMenuItem(Menus.SessionsViewShow, { + command: { id: 'sessionsViewPane.showAllSessions', title: localize2('all', "All"), toggled: IsWorkspaceGroupCappedContext.negate() }, + group: '1_show', + order: 1, + when: GroupedByWorktreeContext, + })); + + return store; +} diff --git a/src/vs/workbench/contrib/sessions/browser/views/sessionsListFilters.ts b/src/vs/workbench/contrib/sessions/browser/views/sessionsListFilters.ts index 6b273b25c74e..185fe4a30757 100644 --- a/src/vs/workbench/contrib/sessions/browser/views/sessionsListFilters.ts +++ b/src/vs/workbench/contrib/sessions/browser/views/sessionsListFilters.ts @@ -5,12 +5,16 @@ import { Emitter } from '../../../../../base/common/event.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; -import { IReader } from '../../../../../base/common/observable.js'; +import { IReader, observableSignalFromEvent } from '../../../../../base/common/observable.js'; +import { getComparisonKey } from '../../../../../base/common/resources.js'; +import { isObject } from '../../../../../base/common/types.js'; import { localize } from '../../../../../nls.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { getSessionApplication, UNKNOWN_SESSION_APPLICATION_ID } from '../../../../services/sessions/common/sessionApplication.js'; import { ISession, ISessionEnvironment } from '../../../../services/sessions/common/session.js'; +import { isAgentHostProvider } from '../../common/agentHostSessionsProvider.js'; +import { ISessionsProvider } from '../../common/sessionsProvider.js'; export type SessionFilter = | { readonly kind: 'harness' | 'environment'; readonly id: string } @@ -22,6 +26,58 @@ export interface ISessionFilterOption { readonly group: string; } +export interface IInboxWorkspaceFilter { + readonly environment: string; + readonly resource: string; + readonly label: string; + readonly description?: string; +} + +export interface IInboxScope { + readonly environment?: { readonly id: string; readonly label: string }; + readonly workspace?: IInboxWorkspaceFilter | 'none'; +} + +export function getInboxWorkspaceFilter(session: ISession, reader?: IReader): IInboxWorkspaceFilter | undefined { + const workspace = session.workspace.read(reader); + if (!workspace || session.isQuickChat?.read(reader)) { + return undefined; + } + return { + environment: session.environment, + resource: getComparisonKey(workspace.uri), + label: workspace.label, + description: workspace.description ?? workspace.uri.path, + }; +} + +export function getInboxWorkspaceOptions(sessions: readonly ISession[], environment?: string, reader?: IReader): IInboxWorkspaceFilter[] { + const options = new Map<string, IInboxWorkspaceFilter>(); + for (const session of sessions) { + const workspace = getInboxWorkspaceFilter(session, reader); + if (workspace && (environment === undefined || workspace.environment === environment)) { + options.set(JSON.stringify([workspace.environment, workspace.resource]), workspace); + } + } + return [...options.values()].sort((a, b) => a.label.localeCompare(b.label) || a.resource.localeCompare(b.resource) || a.environment.localeCompare(b.environment)); +} + +function isInboxScope(value: unknown): value is IInboxScope { + if (!isObject(value)) { + return false; + } + const environment = 'environment' in value ? value.environment : undefined; + const workspace = 'workspace' in value ? value.workspace : undefined; + return (environment === undefined || typeof environment === 'object' && environment !== null + && 'id' in environment && typeof environment.id === 'string' && environment.id.length > 0 + && 'label' in environment && typeof environment.label === 'string') + && (workspace === undefined || workspace === 'none' || typeof workspace === 'object' && workspace !== null + && 'environment' in workspace && typeof workspace.environment === 'string' + && 'resource' in workspace && typeof workspace.resource === 'string' && workspace.resource.length > 0 + && 'label' in workspace && typeof workspace.label === 'string' + && (!('description' in workspace) || workspace.description === undefined || typeof workspace.description === 'string')); +} + export function sessionFilterKey(filter: SessionFilter): string { return JSON.stringify(filter.kind === 'application' ? [filter.kind, filter.environment, filter.id] : [filter.kind, filter.id]); } @@ -55,6 +111,20 @@ export function getSessionEnvironments(environments: readonly ISessionEnvironmen return [...byId.values()].sort(compareSessionEnvironments); } +/** Sharing registrations of this computer are already represented by This Computer. */ +export function getSessionFilterEnvironments(providers: readonly ISessionsProvider[], reader?: IReader): { environments: ISessionEnvironment[]; localEnvironmentIds: ReadonlySet<string> } { + const environments: ISessionEnvironment[] = []; + const localEnvironmentIds = new Set<string>(); + for (const provider of providers) { + if (isAgentHostProvider(provider) && provider.localRegistration?.read(reader)) { + localEnvironmentIds.add(provider.environment.id); + } else { + environments.push(provider.environment); + } + } + return { environments, localEnvironmentIds }; +} + /** * The filter options for the given sessions. Only sessions the list includes, as * decided by `isSessionListed`, contribute their creating applications. @@ -98,9 +168,17 @@ export function getSessionFilterOptions(sessions: readonly ISession[], environme export class SessionsListFilters extends Disposable implements ISessionsListResettableState { private static readonly STORAGE_KEY = 'sessionsListControl.filters'; + private static readonly INBOX_SCOPE_STORAGE_KEY = 'sessionsListControl.inboxScope'; + private static readonly SHOW_AUTOMATION_RUNS_KEY = 'showAutomationRuns'; + private static readonly SCHEDULED_ONLY_KEY = 'scheduledOnly'; private readonly excluded: Map<string, boolean>; + private _inboxScope: IInboxScope = {}; + get inboxScope(): IInboxScope { return this._inboxScope; } + get hasInboxScope(): boolean { return this._inboxScope.workspace !== undefined || this._inboxScope.environment !== undefined; } + get hasInboxWorkspaceScope(): boolean { return !!this._inboxScope.workspace && this._inboxScope.workspace !== 'none'; } private readonly _onDidChange = this._register(new Emitter<void>()); readonly onDidChange = this._onDidChange.event; + private readonly changeSignal = observableSignalFromEvent(this, this.onDidChange); constructor( @IStorageService private readonly storageService: IStorageService, @@ -121,6 +199,18 @@ export class SessionsListFilters extends Disposable implements ISessionsListRese logService.warn('Unable to restore session filter preferences.', error); } } + const scope = storageService.get(SessionsListFilters.INBOX_SCOPE_STORAGE_KEY, StorageScope.PROFILE); + if (scope !== undefined) { + try { + const value: unknown = JSON.parse(scope); + if (!isInboxScope(value)) { + throw new Error('Invalid Inbox scope.'); + } + this._inboxScope = value; + } catch (error) { + logService.warn('Unable to restore Inbox scope.', error); + } + } } isExcluded(filter: SessionFilter): boolean { @@ -136,17 +226,68 @@ export class SessionsListFilters extends Disposable implements ISessionsListRese this.save(); } - matches(session: Pick<ISession, 'harness' | 'environment' | 'application'>): boolean { + isShowAutomationRuns(reader?: IReader): boolean { + if (reader) { + this.changeSignal.read(reader); + } + return this.excluded.get(SessionsListFilters.SHOW_AUTOMATION_RUNS_KEY) ?? false; + } + + setShowAutomationRuns(show: boolean): void { + this.excluded.set(SessionsListFilters.SHOW_AUTOMATION_RUNS_KEY, show); + this.save(); + } + + isScheduledOnly(): boolean { + return this.excluded.get(SessionsListFilters.SCHEDULED_ONLY_KEY) ?? false; + } + + setScheduledOnly(scheduledOnly: boolean): void { + this.excluded.set(SessionsListFilters.SCHEDULED_ONLY_KEY, scheduledOnly); + this.save(); + } + + setInboxWorkspace(workspace: IInboxScope['workspace']): void { + this._inboxScope = { ...this._inboxScope, workspace }; + this.save(); + } + + setInboxEnvironment(environment: IInboxScope['environment']): boolean { + const workspace = this._inboxScope.workspace; + const resetWorkspace = !!environment && !!workspace && workspace !== 'none' && workspace.environment !== environment.id; + this._inboxScope = { environment, workspace: resetWorkspace ? undefined : workspace }; + this.save(); + return resetWorkspace; + } + + matchesInboxScope(session: ISession): boolean { + const { environment, workspace } = this._inboxScope; + if (environment && session.environment !== environment.id) { + return false; + } + if (workspace === 'none') { + return session.isQuickChat?.get() === true; + } + if (workspace) { + const candidate = getInboxWorkspaceFilter(session); + return candidate?.environment === workspace.environment && candidate.resource === workspace.resource; + } + return true; + } + + matches(session: Pick<ISession, 'harness' | 'environment' | 'application'>, inbox = false): boolean { const application = session.application.get(); return !this.isExcluded({ kind: 'harness', id: session.harness }) - && !this.isExcluded({ kind: 'environment', id: session.environment }) + && (inbox || !this.isExcluded({ kind: 'environment', id: session.environment })) && (application.id === UNKNOWN_SESSION_APPLICATION_ID || !this.isExcluded({ kind: 'application', environment: session.environment, id: application.id })); } capture(): () => void { const excluded = [...this.excluded]; + const inboxScope = this._inboxScope; return () => { + this._inboxScope = inboxScope; this.excluded.clear(); for (const [key, value] of excluded) { this.excluded.set(key, value); @@ -157,10 +298,16 @@ export class SessionsListFilters extends Disposable implements ISessionsListRese reset(): void { this.excluded.clear(); + this._inboxScope = {}; this.save(); } private save(): void { + if (this.hasInboxScope) { + this.storageService.store(SessionsListFilters.INBOX_SCOPE_STORAGE_KEY, JSON.stringify(this._inboxScope), StorageScope.PROFILE, StorageTarget.MACHINE); + } else { + this.storageService.remove(SessionsListFilters.INBOX_SCOPE_STORAGE_KEY, StorageScope.PROFILE); + } if (this.excluded.size === 0) { this.storageService.remove(SessionsListFilters.STORAGE_KEY, StorageScope.PROFILE); } else { diff --git a/src/vs/workbench/contrib/sessions/browser/views/sessionsView.ts b/src/vs/workbench/contrib/sessions/browser/views/sessionsView.ts index b5b18423cc36..1ce064181213 100644 --- a/src/vs/workbench/contrib/sessions/browser/views/sessionsView.ts +++ b/src/vs/workbench/contrib/sessions/browser/views/sessionsView.ts @@ -9,7 +9,7 @@ import { status } from '../../../../../base/browser/ui/aria/aria.js'; import { onUnexpectedError } from '../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { DisposableStore, MutableDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { autorun, derivedOpts, IObservable, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; +import { autorun, derivedOpts, IObservable, IReader, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; import { structuralEquals } from '../../../../../base/common/equals.js'; import { isWeb } from '../../../../../base/common/platform.js'; import { Orientation } from '../../../../../base/browser/ui/sash/sash.js'; @@ -67,6 +67,8 @@ import { createSessionsListNotices, ISessionsListNoticeHost } from './sessionsLi import { SessionStorageCleanupNotice } from './sessionStorageCleanupNotice.js'; import { SessionsListNotification } from './sessionsListNotification.js'; import { readPaneSessions } from '../../../../services/sessions/browser/sessionGridPane.js'; +import { ChatCustomizationsLocation, resolveChatCustomizationsLocation } from '../../../chat/common/customizationsLocation.js'; +import { ChatConfiguration } from '../../../chat/common/constants.js'; const $ = DOM.$; export const SessionsViewId = 'sessions.workbench.view.sessionsView'; @@ -78,11 +80,12 @@ const SESSIONS_SECTION_MIN_HEIGHT = 120; const SESSIONS_HEADER_ELLIPSIS_MIN_WIDTH = 8; export type CustomizationsPresentation = 'hidden' | 'control' | 'treatment'; -export function getCustomizationsPresentation(phoneLayout: boolean, aiEnabled: boolean, aiHidden: boolean, treatment: boolean): CustomizationsPresentation { +export function getCustomizationsPresentation(phoneLayout: boolean, aiEnabled: boolean, aiHidden: boolean, treatment: boolean, location: ChatCustomizationsLocation = 'auto'): CustomizationsPresentation { if (phoneLayout || !aiEnabled || aiHidden) { return 'hidden'; } - return treatment ? 'treatment' : 'control'; + const resolved = resolveChatCustomizationsLocation(location, true, treatment); + return resolved === 'sidebar' ? 'control' : resolved === 'sessionsHeader' ? 'treatment' : 'hidden'; } export const SessionsViewGroupingContext = new RawContextKey<string>('sessionsViewPane.grouping', SessionsGrouping.Workspace); @@ -169,7 +172,9 @@ export class SessionsView extends ViewPane { private readonly customizationsNavigationVisible = observableValue(this, false); private readonly customizationsNavigationState: CustomizationsNavigationState; private customizationsPresentation: CustomizationsPresentation = 'hidden'; - private currentGrouping: SessionsGrouping = SessionsGrouping.Workspace; + private navigationShortcutsVisible = false; + private readonly customizationsLocation: IObservable<ChatCustomizationsLocation>; + private currentGrouping: SessionsGrouping | undefined; private currentSorting: SessionsSorting = SessionsSorting.Created; private currentCompact = false; private groupingContextKey: IContextKey | undefined; @@ -214,6 +219,7 @@ export class SessionsView extends ViewPane { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, hoverService); this._mainWindowHost = getMainWindowHost(sessionHostService); this.separateNavigation = observableConfigValue(SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING, false, configurationService); + this.customizationsLocation = observableConfigValue<ChatCustomizationsLocation>(ChatConfiguration.ChatCustomizationsLocation, 'auto', configurationService); this.customizationsNavigationState = this._register(instantiationService.createInstance(CustomizationsNavigationState, this.customizationsNavigationVisible)); this.sessionsListRearrangeContext = SessionsListRearrangeContext.bindTo(this.scopedContextKeyService); @@ -235,7 +241,7 @@ export class SessionsView extends ViewPane { this.groupingContextKey = SessionsViewGroupingContext.bindTo(contextKeyService); this.groupingContextKey.set(this.grouping); this._register(this.configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING)) { + if (e.affectsConfiguration(SESSIONS_LIST_INBOX_ENABLED_SETTING) && this.currentGrouping === undefined) { this.groupingContextKey?.set(this.grouping); this.sessionsControl?.update(true); this.updateHeaderLayout(); @@ -328,7 +334,8 @@ export class SessionsView extends ViewPane { grouping: () => this.grouping, sorting: () => this.currentSorting, compact: () => this.currentCompact, - showNavigationShortcuts: () => this.customizationsPresentation === 'treatment', + showNavigationShortcuts: () => this.navigationShortcutsVisible, + showCustomizations: () => this.customizationsPresentation === 'treatment', customizationsCount: this.customizationsNavigationState.totalCount, customizationMigrationsAvailable: this.customizationsNavigationState.migrationAvailable, customizationExtensionSuggestionsAvailable: this.customizationsNavigationState.extensionSuggestionsAvailable, @@ -473,11 +480,7 @@ export class SessionsView extends ViewPane { const aiVisibilityChanged = observableSignalFromEvent(this, this.scopedContextKeyService.onDidChangeContext); this._register(autorun(reader => { aiVisibilityChanged.read(reader); - const treatment = this.separateNavigation.read(reader); - const sentiment = this.chatEntitlementService.sentimentObs.read(reader); - const aiEnabled = this.scopedContextKeyService.contextMatchesRules(ChatContextKeys.enabled); - const presentation = getCustomizationsPresentation(isPhoneLayout(this.layoutService), aiEnabled, sentiment.hidden === true, treatment); - this.updateCustomizationsPresentation(presentation); + this.refreshCustomizationsPresentation(reader); })); const updateSplitViewStyles = () => { @@ -534,20 +537,34 @@ export class SessionsView extends ViewPane { }); } - private updateCustomizationsPresentation(presentation: CustomizationsPresentation): void { - if (this.customizationsPresentation === presentation) { + private refreshCustomizationsPresentation(reader?: IReader): void { + const phone = isPhoneLayout(this.layoutService); + const enabled = this.scopedContextKeyService.contextMatchesRules(ChatContextKeys.enabled); + const hidden = this.chatEntitlementService.sentimentObs.read(reader).hidden === true; + const navigation = this.separateNavigation.read(reader); + this.updateCustomizationsPresentation( + getCustomizationsPresentation(phone, enabled, hidden, navigation, this.customizationsLocation.read(reader)), + navigation && !phone && enabled && !hidden, + ); + } + + private updateCustomizationsPresentation(presentation: CustomizationsPresentation, navigationShortcutsVisible = presentation === 'treatment'): void { + const compact = this.configurationService.getValue<ChatCustomizationsLocation>(ChatConfiguration.ChatCustomizationsLocation) === 'sidebar'; + if (this.customizationsPresentation === presentation && this.navigationShortcutsVisible === navigationShortcutsVisible && (presentation !== 'control' || this._customizationsWidget?.compact === compact)) { return; } const customizationsFocused = this._customizationsWidget?.hasFocus() === true || this.sessionsControl?.isCustomizationsFocused() === true; const automationsFocused = this.sessionsControl?.isAutomationsFocused() === true; const wasTreatment = this.customizationsPresentation === 'treatment'; + const navigationChanged = this.navigationShortcutsVisible !== navigationShortcutsVisible; this.customizationsPresentation = presentation; - this.sessionsListRearrangeContext.set(presentation === 'treatment'); + this.navigationShortcutsVisible = navigationShortcutsVisible; + this.sessionsListRearrangeContext.set(navigationShortcutsVisible); this.customizationsNavigationVisible.set(presentation === 'treatment', undefined); this.updateHeaderLayout(); - if (wasTreatment !== (presentation === 'treatment')) { + if (wasTreatment !== (presentation === 'treatment') || navigationChanged) { this.sessionsControl?.updateNavigationVisibility(); } @@ -604,6 +621,7 @@ export class SessionsView extends ViewPane { store.add(toDisposable(() => customizationsSection.remove())); const customizationsSizeChange = store.add(new Emitter<void>()); const customizationsWidget = this._customizationsWidget = store.add(this.instantiationService.createInstance(AICustomizationShortcutsWidget, customizationsSection, { + compact: this.configurationService.getValue<ChatCustomizationsLocation>(ChatConfiguration.ChatCustomizationsLocation) === 'sidebar', onDidChangeLayout: () => { customizationsSizeChange.fire(); this.layoutSidebarSplitView(); @@ -763,7 +781,6 @@ export class SessionsView extends ViewPane { id: Menus.SessionsViewFilter, group: '3_visibility', order: 1, - when: SessionsViewGroupingContext.notEqualsTo(SessionsGrouping.Inbox), }] }); } @@ -773,16 +790,6 @@ export class SessionsView extends ViewPane { archivedContextKeyInstance.set(excluding); // was excluding → now showing } })); - this.archivedFilterRegistration.add(MenuRegistry.appendMenuItem(Menus.SessionsViewFilter, { - command: { - id: 'sessionsViewPane.filterArchived', - title: localize('showArchived', "Show Archived"), - toggled: ContextKeyExpr.equals(archivedContextKey.key, true), - }, - group: '3_visibility', - order: 1, - when: SessionsViewGroupingContext.isEqualTo(SessionsGrouping.Inbox), - })); }; registerArchivedFilter(); this._register(this.configurationService.onDidChangeConfiguration(e => { @@ -861,12 +868,7 @@ export class SessionsView extends ViewPane { this.currentBodyHeight = height; this.currentBodyWidth = width; this.updateHeaderLayout(); - this.updateCustomizationsPresentation(getCustomizationsPresentation( - isPhoneLayout(this.layoutService), - this.scopedContextKeyService.contextMatchesRules(ChatContextKeys.enabled), - this.chatEntitlementService.sentiment.hidden === true, - this.separateNavigation.get(), - )); + this.refreshCustomizationsPresentation(); this.layoutSidebarSplitView(); if (this.sidebarSplitView || !this.sessionsControl || !this.sessionsControlContainer) { @@ -1003,7 +1005,7 @@ export class SessionsView extends ViewPane { group: 'group', }, ]; - if (this.configurationService.getValue<boolean>(SESSIONS_LIST_INBOX_ENABLED_SETTING) && !this.chatEntitlementService.sentiment.hidden) { + if (!this.chatEntitlementService.sentiment.hidden) { items.push({ id: SessionsGrouping.Inbox, label: localize('inboxMode', "Inbox Mode"), @@ -1025,9 +1027,9 @@ export class SessionsView extends ViewPane { } get grouping(): SessionsGrouping { - return this.currentGrouping === SessionsGrouping.Inbox && !this.configurationService.getValue<boolean>(SESSIONS_LIST_INBOX_ENABLED_SETTING) - ? SessionsGrouping.Workspace - : this.currentGrouping; + return this.currentGrouping ?? (this.configurationService.getValue<boolean>(SESSIONS_LIST_INBOX_ENABLED_SETTING) + ? SessionsGrouping.Inbox + : SessionsGrouping.Workspace); } get sorting(): SessionsSorting { @@ -1039,14 +1041,11 @@ export class SessionsView extends ViewPane { } setGrouping(grouping: SessionsGrouping): void { - if (grouping === SessionsGrouping.Inbox && !this.configurationService.getValue<boolean>(SESSIONS_LIST_INBOX_ENABLED_SETTING)) { - throw new Error(localize('inboxModeDisabled', "Enable {0} to use Inbox Mode.", SESSIONS_LIST_INBOX_ENABLED_SETTING)); - } if (this.currentGrouping === grouping) { return; } - const preserveCollapseState = this.currentGrouping === SessionsGrouping.Inbox || grouping === SessionsGrouping.Inbox; + const preserveCollapseState = this.grouping === SessionsGrouping.Inbox || grouping === SessionsGrouping.Inbox; this.currentGrouping = grouping; this.storageService.store(GROUPING_STORAGE_KEY, this.currentGrouping, StorageScope.PROFILE, StorageTarget.USER); this.groupingContextKey?.set(this.currentGrouping); diff --git a/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts b/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts new file mode 100644 index 000000000000..a46d51811d4f --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts @@ -0,0 +1,183 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { ResourceMap } from '../../../../base/common/map.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { IObservable, observableFromEvent, observableValue, transaction } from '../../../../base/common/observable.js'; +import { isAbsolute } from '../../../../base/common/path.js'; +import { basename, dirname, isEqual, joinPath } from '../../../../base/common/resources.js'; +import { isDefined } from '../../../../base/common/types.js'; +import { URI } from '../../../../base/common/uri.js'; +import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../platform/files/common/files.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js'; +import { ISessionsListingScope } from '../common/sessionsProvider.js'; +import { parseGitHubRepositoryFromGitConfig } from './gitHubRepositoryResolver.js'; + +/** The hosts of the GitHub repositories that Copilot Cloud sessions work in (`github-remote-file://github/...`). */ +const GITHUB_HOSTS = ['github.com']; + +/** What a local folder is a checkout of: its git repository, and the GitHub repository of that repository's `origin`. */ +interface IFolderCheckout { + readonly repository: URI | undefined; + readonly gitHubRepository: string | undefined; +} + +/** + * The scope the sessions providers of an editor window list their sessions in: the folders of the window's workspace, the + * git repositories of its local folders, read from their `.git`, and the GitHub repositories of those repositories' + * `origin`, read from their `.git/config`, such as for Copilot Cloud sessions. Each folder's `.git` and its repository's + * `.git/config` are read once, as the folder joins the workspace, and again only after a read that failed; there are no + * watchers. A folder that leaves the workspace stops counting at once. + */ +export class WorkspaceFolderRepositories extends Disposable implements ISessionsListingScope { + + readonly folders: IObservable<readonly URI[]>; + + private readonly _repositories = observableValue<readonly URI[]>(this, []); + readonly repositories: IObservable<readonly URI[]> = this._repositories; + + private readonly _gitHubRepositories = observableValue<readonly string[]>(this, []); + readonly gitHubRepositories: IObservable<readonly string[]> = this._gitHubRepositories; + + /** The read of each folder's checkout, while it is pending or after it succeeded. */ + private readonly _reads = new ResourceMap<Promise<IFolderCheckout | undefined>>(); + /** The checkout of each folder whose read succeeded. */ + private readonly _resolved = new ResourceMap<IFolderCheckout>(); + private _generation = 0; + + constructor( + @IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService, + @IFileService private readonly _fileService: IFileService, + @ILogService private readonly _logService: ILogService, + ) { + super(); + this.folders = observableFromEvent(this, _workspaceContextService.onDidChangeWorkspaceFolders, () => _workspaceContextService.getWorkspace().folders.map(folder => folder.uri)); + this._register(_workspaceContextService.onDidChangeWorkspaceFolders(() => void this._update())); + void this._update(); + } + + private async _update(): Promise<void> { + const generation = ++this._generation; + const folders = this._workspaceContextService.getWorkspace().folders.map(folder => folder.uri).filter(folder => folder.scheme === Schemas.file); + for (const folder of [...this._reads.keys(), ...this._resolved.keys()]) { + if (!folders.some(candidate => isEqual(candidate, folder))) { + this._reads.delete(folder); + this._resolved.delete(folder); + } + } + // The folders that left stop counting now, before the folders that joined are read. + this._publish(folders.map(folder => this._resolved.get(folder))); + const checkouts = await Promise.all(folders.map(folder => this._read(folder))); + if (generation === this._generation && !this._store.isDisposed) { + this._publish(checkouts); + } + } + + private _publish(checkouts: readonly (IFolderCheckout | undefined)[]): void { + transaction(tx => { + this._repositories.set(checkouts.map(checkout => checkout?.repository).filter(isDefined), tx); + this._gitHubRepositories.set(checkouts.map(checkout => checkout?.gitHubRepository).filter(isDefined), tx); + }); + } + + private _read(folder: URI): Promise<IFolderCheckout | undefined> { + let read = this._reads.get(folder); + if (!read) { + const pending = this._readCheckout(folder).then(({ checkout, readAgain }) => { + if (this._reads.get(folder) === pending) { + this._resolved.set(folder, checkout); + if (readAgain) { + this._reads.delete(folder); + } + } + return checkout; + }, error => { + // A read that failed, other than for a missing `.git`, is tried again as the folders change. + this._logService.warn(`[WorkspaceFolderRepositories] Could not read the git repository of ${folder.toString()}`, error); + if (this._reads.get(folder) === pending) { + this._reads.delete(folder); + } + return undefined; + }); + read = pending; + this._reads.set(folder, read); + } + return read; + } + + /** The checkout of `folder`, and whether to read it again as the folders change, as its `origin` could not be read. */ + private async _readCheckout(folder: URI): Promise<{ readonly checkout: IFolderCheckout; readonly readAgain: boolean }> { + const repository = await WorkspaceFolderRepositories._readFolderGitRepository(this._fileService, folder); + if (!repository) { + return { checkout: { repository, gitHubRepository: undefined }, readAgain: false }; + } + try { + return { checkout: { repository, gitHubRepository: await WorkspaceFolderRepositories._readRepositoryGitHubOrigin(this._fileService, repository) }, readAgain: false }; + } catch (error) { + // The repository still counts; its `origin` is read again, like a failed read of `.git`, as the folders change. + this._logService.warn(`[WorkspaceFolderRepositories] Could not read the git origin of ${repository.toString()}`, error); + return { checkout: { repository, gitHubRepository: undefined }, readAgain: true }; + } + } + + /** + * The git repository that a local folder is a checkout of, read from its `.git`: the folder itself when `.git` is a + * directory, and the main checkout when `.git` is the file of a worktree (`gitdir: <repository>/.git/worktrees/<name>`). + * `undefined` for a folder without `.git`, or whose `.git` names no worktree, such as a submodule's. Throws when `.git` + * exists but cannot be read. + */ + private static async _readFolderGitRepository(fileService: IFileService, folder: URI): Promise<URI | undefined> { + const dotGit = joinPath(folder, '.git'); + let isDirectory: boolean; + try { + isDirectory = (await fileService.stat(dotGit)).isDirectory; + } catch (error) { + if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { + return undefined; + } + throw error; + } + if (isDirectory) { + return folder; + } + const content = (await fileService.readFile(dotGit)).value.toString(); + const gitdir = /^gitdir:\s*(?<path>.+?)\s*$/m.exec(content)?.groups?.path; + if (!gitdir) { + return undefined; + } + const worktreeGitDir = isAbsolute(gitdir) ? URI.file(gitdir) : joinPath(folder, gitdir); + const worktreesDir = dirname(worktreeGitDir); + const commonGitDir = dirname(worktreesDir); + return basename(worktreesDir) === 'worktrees' && basename(commonGitDir) === '.git' && !isEqual(commonGitDir, worktreesDir) + ? dirname(commonGitDir) + : undefined; + } + + /** + * The GitHub repository, as lowercase `owner/repo`, that the `origin` remote of a git `config` names, such as + * `https://github.com/owner/repo.git` or `git@github.com:owner/repo`; `undefined` for another host or without `origin`. + */ + private static _parseGitHubOrigin(config: string): string | undefined { + const repository = parseGitHubRepositoryFromGitConfig(config, GITHUB_HOSTS, 'origin'); + return repository && `${repository.owner}/${repository.repo}`.toLowerCase(); + } + + /** + * The GitHub repository the `origin` of a local git `repository` names, read from its `.git/config` (see + * {@link _parseGitHubOrigin}). `undefined` without that file; throws when it exists but cannot be read. + */ + private static async _readRepositoryGitHubOrigin(fileService: IFileService, repository: URI): Promise<string | undefined> { + try { + return WorkspaceFolderRepositories._parseGitHubOrigin((await fileService.readFile(joinPath(repository, '.git', 'config'))).value.toString()); + } catch (error) { + if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { + return undefined; + } + throw error; + } + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionInputPresentation.ts b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionInputPresentation.ts new file mode 100644 index 000000000000..cd85d76b419e --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionInputPresentation.ts @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { INewSessionInputPresentation } from '../newSessionInputPresentation.js'; +import { WorktreeSuggestionController } from './worktreeSuggestionController.js'; +import { WorktreeSuggestionIsolationPicker } from './worktreeSuggestionIsolationPicker.js'; +import { getWorktreeSuggestionAccessibilityHelp } from './worktreeSuggestionPresentation.js'; + +export const worktreeSuggestionInputPresentation: INewSessionInputPresentation = { + getAccessibilityHelp: getWorktreeSuggestionAccessibilityHelp, + createComposer: (container, context, instantiationService) => instantiationService.createInstance(WorktreeSuggestionController, container, context), + createIsolationPicker: (session, instantiationService) => instantiationService.createInstance(WorktreeSuggestionIsolationPicker, session), +}; diff --git a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionIsolationPicker.ts b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionIsolationPicker.ts new file mode 100644 index 000000000000..b8d8d3361eec --- /dev/null +++ b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionIsolationPicker.ts @@ -0,0 +1,157 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/worktreeSuggestion.css'; +import * as dom from '../../../../../base/browser/dom.js'; +import { DisposableStore, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, IObservable, IReader } from '../../../../../base/common/observable.js'; +import { localize } from '../../../../../nls.js'; +import { ActionListItemKind, IActionListItem } from '../../../../../platform/actionWidget/browser/actionList.js'; +import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { ISession, ISessionFileChange } from '../../../../services/sessions/common/session.js'; +import { FOCUS_NEW_SESSION_WORKTREE_PICKER_COMMAND_ID } from '../../common/sessionCommands.js'; +import { WorktreeSuggestionVariant } from '../../common/worktreeSuggestion.js'; +import { IConfigPickerItem, IIsolationPickerRecommendation, IIsolationPickerTriggerContext, ISessionIsolationPickerPresentation } from '../newSessionInputPresentation.js'; +import { getChangedFileUri, getModifiedFilesSectionLabel, getUncommittedFilesDescription } from './worktreeSuggestionPresentation.js'; +import { IUncommittedChangesListItem, IWorktreeSuggestion, IWorktreeSuggestionService } from './worktreeSuggestionService.js'; + +const LISTED_FILES_MAX = 3; +const LISTED_FILES_CLASS = 'sessions-chat-isolation-listed-changes'; +const LISTED_FILE_VALUE_PREFIX = '\0worktreeSuggestion:'; + +function withWorktreeSuggestion(item: IConfigPickerItem, suggestion: IWorktreeSuggestion, hasCreatedWorktreeSession: boolean): IConfigPickerItem { + if (item.value === 'worktree') { + return item.disabled ? item : { ...item, badge: localize('agentHostSessionConfig.isolation.recommended', "Recommended"), secondaryBadge: hasCreatedWorktreeSession }; + } + if (item.value === 'folder' || item.value === 'workspace') { + return { + ...item, + description: suggestion.uncommittedChanges === 1 + ? localize('agentHostSessionConfig.isolation.branchWithChangesSingular', "Works alongside your uncommitted file") + : localize('agentHostSessionConfig.isolation.branchWithChangesPlural', "Works alongside your {0} uncommitted files", suggestion.uncommittedChanges), + }; + } + return item; +} + +function getListedFilesKey(changes: readonly ISessionFileChange[] | undefined): string { + return changes?.map(change => `${getChangedFileUri(change).toString()}\t${change.insertions}\t${change.deletions}`).join('\n') ?? ''; +} + +function toConfigPickerItems(items: readonly IActionListItem<IUncommittedChangesListItem>[]): IActionListItem<IConfigPickerItem>[] { + return items.map((row, index): IActionListItem<IConfigPickerItem> => { + // The rows replace no items when filtered. + const { item, filterItems: _, ...rest } = row; + return item ? { ...rest, item: { value: `${LISTED_FILE_VALUE_PREFIX}${index}`, label: row.label ?? '', run: item.run } } : rest; + }); +} + +/** Optional hints and file previews; the shared picker still owns configuration writes and navigation. */ +export class WorktreeSuggestionIsolationPicker implements ISessionIsolationPickerPresentation { + constructor( + private readonly _session: IObservable<ISession | undefined>, + @IWorktreeSuggestionService private readonly _service: IWorktreeSuggestionService, + @IHoverService private readonly _hoverService: IHoverService, + @IKeybindingService private readonly _keybindingService: IKeybindingService, + ) { } + + renderTrigger({ trigger, sessionId, title, label, ariaLabel, tooltip, hoverDelegate }: IIsolationPickerTriggerContext): IDisposable { + const store = new DisposableStore(); + const element = dom.append(trigger, dom.$('span.sessions-chat-uncommitted-count', { 'aria-hidden': 'true' })); + store.add(toDisposable(() => element.remove())); + let counted: IWorktreeSuggestion | undefined; + // Hidden and icon-only triggers do not count as an exposure until the count is laid out. + const reportShown = () => { + if (counted && element.isConnected && element.offsetWidth > 0) { + this._service.markShown(WorktreeSuggestionVariant.UncommittedFilesCount, counted); + } + }; + const resizeObserver = store.add(new dom.DisposableResizeObserver('AgentHostSessionConfigPicker.uncommittedFilesCount', reportShown, dom.getWindow(trigger))); + store.add(resizeObserver.observe(element)); + store.add(autorun(reader => { + counted = this._getCountedSuggestion(sessionId, reader); + if (counted) { + this._service.getUncommittedChanges(counted, reader); + } + element.classList.toggle('visible', !!counted); + element.textContent = counted ? String(counted.uncommittedChanges) : ''; + trigger.setAttribute('aria-label', counted + ? localize('agentHostSessionConfig.isolation.uncommittedCountAria', "{0}: {1}. {2}", title, label, getUncommittedFilesDescription(counted)) + : ariaLabel); + reportShown(); + })); + if (tooltip) { + store.add(this._hoverService.setupManagedHover(hoverDelegate, trigger, () => { + const current = this._getCountedSuggestion(sessionId, undefined); + return this._keybindingService.appendKeybinding(current ? getUncommittedFilesDescription(current) : tooltip, FOCUS_NEW_SESSION_WORKTREE_PICKER_COMMAND_ID); + })); + } + return store; + } + + getRecommendation(sessionId: string): IIsolationPickerRecommendation | undefined { + const variant = this._service.variant.get(); + if (variant !== WorktreeSuggestionVariant.InlineHint && variant !== WorktreeSuggestionVariant.UncommittedFilesCount) { + return undefined; + } + const suggestion = this._getSuggestion(sessionId, undefined); + if (!suggestion || variant === WorktreeSuggestionVariant.InlineHint + && (this._service.isHintClosed(undefined) || this._service.hasDeclined(variant, suggestion, undefined))) { + return undefined; + } + const hasCreatedWorktreeSession = this._service.hasCreatedWorktreeSession(undefined); + const listedFiles = variant === WorktreeSuggestionVariant.UncommittedFilesCount ? suggestion : undefined; + return { + className: listedFiles ? LISTED_FILES_CLASS : undefined, + minWidth: listedFiles ? 300 : undefined, + decorateOptions: items => items.map(item => withWorktreeSuggestion(item, suggestion, hasCreatedWorktreeSession)), + appendItems: options => this._withListedFiles(listedFiles, options), + onSelect: value => { + if (value === 'worktree') { + this._service.markAccepted(variant, suggestion); + } else { + this._service.decline(variant, suggestion); + } + }, + onDidShow: listedFiles ? (options, updateItems) => { + // Listing the files can be the first exposure when the chip is icon-only. + this._service.markShown(WorktreeSuggestionVariant.UncommittedFilesCount, listedFiles); + this._service.markOpened(WorktreeSuggestionVariant.UncommittedFilesCount, listedFiles); + let listedKey = getListedFilesKey(this._service.getUncommittedChanges(listedFiles, undefined)); + return autorun(reader => { + const key = getListedFilesKey(this._service.getUncommittedChanges(listedFiles, reader)); + if (key !== listedKey) { + listedKey = key; + updateItems(this._withListedFiles(listedFiles, options)); + } + }); + } : undefined, + }; + } + + private _getSuggestion(sessionId: string, reader: IReader | undefined): IWorktreeSuggestion | undefined { + const session = this._session.read(reader); + return session?.sessionId === sessionId ? this._service.getSuggestion(session, reader) : undefined; + } + + private _getCountedSuggestion(sessionId: string, reader: IReader | undefined): IWorktreeSuggestion | undefined { + return this._service.variant.read(reader) === WorktreeSuggestionVariant.UncommittedFilesCount + ? this._getSuggestion(sessionId, reader) + : undefined; + } + + private _withListedFiles(suggestion: IWorktreeSuggestion | undefined, options: IActionListItem<IConfigPickerItem>[]): IActionListItem<IConfigPickerItem>[] { + if (!suggestion) { + return options; + } + const total = this._service.getUncommittedChanges(suggestion, undefined)?.length ?? suggestion.uncommittedChanges; + const sectionLabel = getModifiedFilesSectionLabel(total); + const files = toConfigPickerItems(this._service.getUncommittedChangesListItems(WorktreeSuggestionVariant.UncommittedFilesCount, suggestion, LISTED_FILES_MAX)) + // Screen readers skip separators, so each row carries the section in its group title. + .map(row => ({ ...row, group: { ...row.group, title: sectionLabel } })); + return files.length ? [...options, { kind: ActionListItemKind.Separator, label: sectionLabel }, ...files] : options; + } +} diff --git a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionPresentation.ts b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionPresentation.ts index f548b9e1765f..78de3bb01a44 100644 --- a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionPresentation.ts +++ b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionPresentation.ts @@ -63,11 +63,11 @@ export function getUseWorktreeLabel(): string { return localize('worktreeSuggestion.useWorktree', "Use Worktree"); } -/** Heads the uncommitted files listed among the options of a picker, e.g. "5 Uncommitted Files". */ -export function getUncommittedFilesSectionLabel(count: number): string { +/** Heads the uncommitted files listed among the options of a picker, e.g. "5 Modified Files". */ +export function getModifiedFilesSectionLabel(count: number): string { return count === 1 - ? localize('worktreeSuggestion.uncommittedFilesSectionSingular', "1 Uncommitted File") - : localize('worktreeSuggestion.uncommittedFilesSectionPlural', "{0} Uncommitted Files", count); + ? localize('worktreeSuggestion.modifiedFilesSectionSingular', "1 Modified File") + : localize('worktreeSuggestion.modifiedFilesSectionPlural', "{0} Modified Files", count); } /** Stands for the uncommitted files a list leaves out, e.g. "2 more". */ diff --git a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.ts b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.ts index 354e7d60da78..e48949dbb431 100644 --- a/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.ts +++ b/src/vs/workbench/contrib/sessions/browser/worktreeSuggestion/worktreeSuggestionService.ts @@ -36,6 +36,7 @@ import { isDevContainerWorktreeEnabled } from '../../common/devContainerAgentHos import { ISessionsProvidersService } from '../sessionsProvidersService.js'; import { ISessionFileChange, isSessionCreated, UNCOMMITTED_CHANGES_CHANGESET_ID, ISession } from '../../../../services/sessions/common/session.js'; import { ISessionsProvider } from '../../common/sessionsProvider.js'; +import { ISessionsManagementService } from '../../common/sessionsManagement.js'; import { CHANGES_VIEW_ID } from '../../common/changes.js'; import { ISessionChangesService } from '../../../../services/sessions/common/sessionChangesService.js'; import { createWorktreeSuggestionTour } from '../tours/worktreeSuggestionTour.js'; @@ -131,6 +132,12 @@ export interface IWorktreeSuggestionService { /** Whether the user closed the inline hint, which then never shows again. */ isHintClosed(reader: IReader | undefined): boolean; + /** + * Whether the user started a session in a new worktree, after which New Worktree is recommended less + * prominently. A preview starts without one, but records one the user starts during it. + */ + hasCreatedWorktreeSession(reader: IReader | undefined): boolean; + /** Stops showing the inline hint. */ closeHint(suggestion: IWorktreeSuggestion): void; @@ -152,7 +159,10 @@ export interface IWorktreeSuggestionService { */ setPreview(variant: WorktreeSuggestionVariant | undefined): void; - /** Forgets earlier responses, so a closed hint and a spotlight that was shown can appear again. */ + /** + * Forgets earlier responses and sessions started in a new worktree, so a closed hint, a spotlight that + * was shown and the prominent recommendation can appear again. + */ reset(): void; } @@ -163,9 +173,11 @@ const STATE_STORAGE_KEY = 'sessions.worktreeSuggestion.state'; interface IWorktreeSuggestionState { /** Whether the user closed the inline hint. */ readonly hintClosed: boolean; + /** Whether the user started a session in a new worktree. */ + readonly worktreeSessionCreated: boolean; } -const INITIAL_STATE: IWorktreeSuggestionState = { hintClosed: false }; +const INITIAL_STATE: IWorktreeSuggestionState = { hintClosed: false, worktreeSessionCreated: false }; type WorktreeSuggestionAction = 'shown' | 'opened' | 'reviewed' | 'accepted' | 'declined' | 'dismissed'; @@ -217,6 +229,7 @@ export class WorktreeSuggestionService extends Disposable implements IWorktreeSu @ISessionsHostLayoutService private readonly _layoutService: ISessionsHostLayoutService, @INotificationService private readonly _notificationService: INotificationService, @ILogService private readonly _logService: ILogService, + @ISessionsManagementService sessionsManagementService: ISessionsManagementService, ) { super(); @@ -253,6 +266,12 @@ export class WorktreeSuggestionService extends Disposable implements IWorktreeSu watchProviders(event.added); })); watchProviders(_sessionsProvidersService.getProviders({ includeSessionBackends: true })); + + this._register(sessionsManagementService.onDidSendRequest(({ isNewSession, newSessionConfig }) => { + if (isNewSession && newSessionConfig?.isolation === 'worktree') { + this._recordWorktreeSessionCreated(); + } + })); } getSuggestion(session: ISession | undefined, reader: IReader | undefined): IWorktreeSuggestion | undefined { @@ -412,6 +431,10 @@ export class WorktreeSuggestionService extends Disposable implements IWorktreeSu this._report(WorktreeSuggestionVariant.InlineHint, 'dismissed', suggestion); } + hasCreatedWorktreeSession(reader: IReader | undefined): boolean { + return this._getState(reader).worktreeSessionCreated; + } + canShowSpotlight(): boolean { return this._preview.get() !== undefined || this._configurationService.getValue<boolean>(ONBOARDING_ENABLED_CONFIG) !== false && !this._onboardingService.hasBeenShown(WORKTREE_SUGGESTION_TOUR_ID); @@ -501,9 +524,13 @@ export class WorktreeSuggestionService extends Disposable implements IWorktreeSu if (this._preview.read(reader) !== undefined) { return this._previewState.read(reader); } + return this._getStoredState(reader); + } + + private _getStoredState(reader: IReader | undefined): IWorktreeSuggestionState { this._stateChanged.read(reader); const state = this._storageService.getObject<Partial<IWorktreeSuggestionState>>(STATE_STORAGE_KEY, StorageScope.PROFILE); - return { hintClosed: state?.hintClosed === true }; + return { hintClosed: state?.hintClosed === true, worktreeSessionCreated: state?.worktreeSessionCreated === true }; } private _updateState(update: Partial<IWorktreeSuggestionState>): void { @@ -513,4 +540,15 @@ export class WorktreeSuggestionService extends Disposable implements IWorktreeSu } this._storageService.store(STATE_STORAGE_KEY, { ...this._getState(undefined), ...update }, StorageScope.PROFILE, StorageTarget.MACHINE); } + + /** Unlike a response to a suggestion, a session started in a new worktree is stored during a preview too. */ + private _recordWorktreeSessionCreated(): void { + if (this._preview.get() !== undefined) { + this._previewState.set({ ...this._previewState.get(), worktreeSessionCreated: true }, undefined); + } + const stored = this._getStoredState(undefined); + if (!stored.worktreeSessionCreated) { + this._storageService.store(STATE_STORAGE_KEY, { ...stored, worktreeSessionCreated: true }, StorageScope.PROFILE, StorageTarget.MACHINE); + } + } } diff --git a/src/vs/workbench/contrib/sessions/common/agentHostSessionsProvider.ts b/src/vs/workbench/contrib/sessions/common/agentHostSessionsProvider.ts index 0866420c3fb3..70a771996b40 100644 --- a/src/vs/workbench/contrib/sessions/common/agentHostSessionsProvider.ts +++ b/src/vs/workbench/contrib/sessions/common/agentHostSessionsProvider.ts @@ -109,6 +109,7 @@ export type AgentHostMcpTool = { readonly name: string; readonly title?: string; readonly description?: string; + readonly annotations?: { readonly title?: string }; }; /** diff --git a/src/vs/workbench/contrib/sessions/common/contextkeys.ts b/src/vs/workbench/contrib/sessions/common/contextkeys.ts index d01266e10c0a..734604025975 100644 --- a/src/vs/workbench/contrib/sessions/common/contextkeys.ts +++ b/src/vs/workbench/contrib/sessions/common/contextkeys.ts @@ -19,6 +19,7 @@ export const SessionActivityBarSizeContext = new RawContextKey<string>('sessionA export const IsNewChatSessionContext = new RawContextKey<boolean>('isNewChatSession', true); export const NewSessionComposerFocusContext = new RawContextKey<boolean>('newSessionComposerFocus', false, localize('newSessionComposerFocus', "Whether focus is within the new-session composer or its pickers")); export const ChatInputSupportsBackgroundContext = new RawContextKey<boolean>('sessionsChatInputSupportsBackground', false, localize('sessionsChatInputSupportsBackground', "Whether the chat input supports sending in the background")); +export const ChatInputCanScheduleContext = new RawContextKey<boolean>('sessionsChatInputCanSchedule', false, localize('sessionsChatInputCanSchedule', "Whether the chat input supports sending later")); export const SessionIdContext = new RawContextKey<string>('sessionId', '', localize('sessionId', "The identifier of the session in scope (the active session globally, or a specific session within an isolated component such as the session view or a context menu overlay)")); export const SessionProviderIdContext = new RawContextKey<string>('sessionProviderId', '', localize('sessionProviderId', "The provider ID of the session in scope (the active session globally, or a specific session within an isolated component such as the session view or a context menu overlay)")); export const SessionTypeContext = new RawContextKey<string>('sessionType', '', localize('sessionType', "The session type of the session in scope (the active session globally, or a specific session within an isolated component such as the session view or a context menu overlay)")); @@ -114,6 +115,13 @@ export const SessionAgentMergeEnabledContext = new RawContextKey<boolean>('sessi */ export const SessionHasOpenPullRequestContext = new RawContextKey<boolean>('sessionHasOpenPullRequest', false, localize('sessionHasOpenPullRequest', "Whether the active session's branch has an open pull request")); +/** + * Whether artifact integrations apply to the active session: they are enabled + * and its provider supports them. Pull request actions that a recorded pull + * request artifact offers, such as Fix Checks or Merge, are then left to it. + */ +export const SessionArtifactIntegrationsEnabledContext = new RawContextKey<boolean>('sessionArtifactIntegrationsEnabled', false, localize('sessionArtifactIntegrationsEnabled', "Whether artifact integrations are enabled and supported for the active session")); + //#endregion //#region < --- Welcome --- > diff --git a/src/vs/workbench/contrib/sessions/common/devContainerAgentHostService.ts b/src/vs/workbench/contrib/sessions/common/devContainerAgentHostService.ts index bd6fefeaf333..331b481f2dcb 100644 --- a/src/vs/workbench/contrib/sessions/common/devContainerAgentHostService.ts +++ b/src/vs/workbench/contrib/sessions/common/devContainerAgentHostService.ts @@ -25,6 +25,9 @@ export const DevContainerIdleTimeoutSettingId = 'chat.agentHost.devContainer.idl /** Hidden experimental setting that enables combining Dev Container execution with a new worktree. */ export const DevContainerWorktreeEnabledSettingId = 'chat.agentHost.devContainer.worktree.enabled'; +/** Experimental setting that keeps user and agent state of new Dev Containers on a volume across rebuilds. */ +export const DevContainerStateVolumeEnabledSettingId = 'chat.agentHost.devContainer.stateVolume.enabled'; + /** Whether new sample workspaces can be selected, independently of already-created sessions. */ export function areDevContainerSamplesEnabled(configurationService: IConfigurationService): boolean { return configurationService.getValue<boolean>(DevContainerSamplesEnabledSettingId) === true @@ -92,9 +95,4 @@ export interface IDevContainerAgentHostService { getSandboxSupported?(workspaceUri: URI): boolean | undefined; showLog(workspaceUri: URI): Promise<void>; disconnect(workspaceUri: URI): Promise<void>; - /** Register a source workspace without starting its container or connecting. */ - addWorkspace(workspaceUri: URI, name: string): void; - /** Forget a location and disconnect its transport without deleting its container. */ - removeWorkspace(workspaceUri: URI): Promise<void>; - getWorkspaces(): readonly { readonly workspaceUri: URI; readonly name: string }[]; } diff --git a/src/vs/workbench/contrib/sessions/common/savedSessionDrafts.ts b/src/vs/workbench/contrib/sessions/common/savedSessionDrafts.ts new file mode 100644 index 000000000000..f232531d4fec --- /dev/null +++ b/src/vs/workbench/contrib/sessions/common/savedSessionDrafts.ts @@ -0,0 +1,172 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { toErrorMessage } from '../../../../base/common/errorMessage.js'; +import { parse, stringify } from '../../../../base/common/marshalling.js'; +import { equals } from '../../../../base/common/objects.js'; +import { observableValue } from '../../../../base/common/observable.js'; +import { URI } from '../../../../base/common/uri.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { IChatDraft } from '../../chat/common/attachments/chatDraft.js'; +import { fromStoredChatDraft, toStoredChatDraft } from './newChatDraftState.js'; +import { ISessionDraftConfiguration } from './sessionsProvider.js'; + +export interface ISavedSessionDraftTarget { + readonly folderUri?: URI; + readonly providerId?: string; + readonly sessionTypeId?: string; + readonly configuration?: ISessionDraftConfiguration; + readonly modelId?: string; + readonly modeId?: string; + readonly environmentId?: string; + readonly harness?: string; + readonly applicationId?: string; + readonly requireDevContainer?: boolean; + readonly groupId?: string; +} + +export interface ISavedSessionDraft { + readonly id: string; + readonly revision: string; + readonly createdAt: number; + readonly updatedAt: number; + readonly input: IChatDraft; + readonly target: ISavedSessionDraftTarget; +} + +const storageKey = 'sessions.savedDrafts'; +const revisionPrefix = `${storageKey}.revision.`; +const removedPrefix = `${storageKey}.removed.`; + +interface IStoredSavedSessionDraft extends ISavedSessionDraft { + readonly legacy?: boolean; +} + +export function hasSessionDraftContent(input: IChatDraft): boolean { + return input.inputText.trim().length > 0 || input.attachments.length > 0; +} + +/** Immutable revision keys keep independently cached windows from overwriting one another's compositions. */ +export class SavedSessionDrafts extends Disposable { + readonly drafts = observableValue<readonly ISavedSessionDraft[]>(this, []); + readonly error = observableValue<Error | undefined>(this, undefined); + + constructor(private readonly storageService: IStorageService) { + super(); + this.refresh(); + this._register(storageService.onDidChangeValue(StorageScope.PROFILE, undefined, this._store)(event => { + if (event.key === storageKey || event.key.startsWith(revisionPrefix) || event.key.startsWith(removedPrefix)) { + this.refresh(); + } + })); + } + + private read(): IStoredSavedSessionDraft[] { + const revisions = new Map<string, IStoredSavedSessionDraft>(); + for (const key of [storageKey, ...this.storageService.keys(StorageScope.PROFILE).filter(key => key.startsWith(revisionPrefix))]) { + for (const draft of this.readKey(key)) { + if (!this.storageService.getBoolean(`${removedPrefix}${draft.revision}`, StorageScope.PROFILE)) { + revisions.set(draft.revision, draft); + } + } + } + return [...revisions.values()].sort((a, b) => b.updatedAt - a.updatedAt || a.revision.localeCompare(b.revision)); + } + + private readKey(key: string): IStoredSavedSessionDraft[] { + const raw = this.storageService.get(key, StorageScope.PROFILE); + if (!raw) { + return []; + } + const data: { version?: number; drafts?: IStoredSavedSessionDraft[] } = parse(raw); + if (data?.version !== 1 || !Array.isArray(data.drafts)) { + throw new Error('Unsupported saved session draft storage.'); + } + return data.drafts.map(draft => { + if (!draft || typeof draft.id !== 'string' || typeof draft.revision !== 'string' || !Number.isFinite(draft.createdAt) || !Number.isFinite(draft.updatedAt) || !draft.target || typeof draft.target !== 'object' + || (draft.target.folderUri !== undefined && !URI.isUri(draft.target.folderUri)) + || (draft.target.providerId !== undefined && typeof draft.target.providerId !== 'string') + || (draft.target.sessionTypeId !== undefined && typeof draft.target.sessionTypeId !== 'string')) { + throw new Error('Invalid saved session draft.'); + } + return { ...draft, legacy: key === storageKey || draft.legacy !== false, input: fromStoredChatDraft(draft.input) }; + }); + } + + private refresh(): void { + try { + const latest = new Map<string, ISavedSessionDraft>(); + for (const draft of this.read()) { + if (!latest.has(draft.id)) { + const { legacy: _legacy, ...visible } = draft; + latest.set(draft.id, visible); + } + } + this.drafts.set([...latest.values()], undefined); + this.error.set(undefined, undefined); + } catch (error) { + this.error.set(error instanceof Error ? error : new Error(toErrorMessage(error)), undefined); + } + } + + private write(draft: IStoredSavedSessionDraft): void { + this.storageService.store(`${revisionPrefix}${draft.revision}`, stringify({ + version: 1, + drafts: [{ ...draft, legacy: draft.legacy ?? false, input: toStoredChatDraft(draft.input) }], + }), StorageScope.PROFILE, StorageTarget.MACHINE); + } + + private migrate(): void { + for (const draft of this.readKey(storageKey)) { + if (!this.storageService.getBoolean(`${removedPrefix}${draft.revision}`, StorageScope.PROFILE)) { + this.write(draft); + } + } + this.storageService.remove(storageKey, StorageScope.PROFILE); + } + + private removeRevision(draft: IStoredSavedSessionDraft): void { + // Only the finite legacy collection can be replayed by a stale migrator. + if (draft.legacy) { + this.storageService.store(`${removedPrefix}${draft.revision}`, true, StorageScope.PROFILE, StorageTarget.MACHINE); + } + this.storageService.remove(`${revisionPrefix}${draft.revision}`, StorageScope.PROFILE); + } + + save(input: IChatDraft, target: ISavedSessionDraftTarget, id = generateUuid()): ISavedSessionDraft { + const drafts = this.read(); + const previous = drafts.find(draft => draft.id === id); + const savedInput = fromStoredChatDraft(parse(stringify(toStoredChatDraft(input)))); + const savedTarget: ISavedSessionDraftTarget = parse(stringify(target)); + if (previous && equals(previous.input, savedInput) && equals(previous.target, savedTarget)) { + const { legacy: _legacy, ...unchanged } = previous; + return unchanged; + } + const now = Date.now(); + const draft: ISavedSessionDraft = { + id, revision: generateUuid(), createdAt: previous?.createdAt ?? now, updatedAt: now, + input: savedInput, + target: savedTarget, + }; + this.migrate(); + this.write(draft); + for (const previous of drafts.filter(candidate => candidate.id === id)) { + this.removeRevision(previous); + } + this.refresh(); + return draft; + } + + remove(id: string, revision?: string): void { + const drafts = this.read(); + this.migrate(); + for (const draft of drafts.filter(draft => draft.id === id && (revision === undefined || draft.revision === revision))) { + this.removeRevision(draft); + } + this.refresh(); + } +} diff --git a/src/vs/workbench/contrib/sessions/common/scheduledChatRequest.ts b/src/vs/workbench/contrib/sessions/common/scheduledChatRequest.ts new file mode 100644 index 000000000000..513c8f554ce0 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/common/scheduledChatRequest.ts @@ -0,0 +1,97 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; +import { detectImageMimeType } from '../../../../base/common/image.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IRange } from '../../../../editor/common/core/range.js'; +import { OffsetRange } from '../../../../editor/common/core/ranges/offsetRange.js'; +import { PositionOffsetTransformer } from '../../../../editor/common/core/text/positionToOffset.js'; +import { isLocation } from '../../../../editor/common/languages.js'; +import { localize } from '../../../../nls.js'; +import { Message, MessageAttachment, MessageAttachmentKind, MessageKind } from '../../../../platform/agentHost/common/state/protocol/state.js'; +import { IChatDraft } from '../../chat/common/attachments/chatDraft.js'; +import { coerceImageBuffer } from '../../chat/common/chatImageExtraction.js'; + +/** Captures ephemeral context now; only host-readable files and folders may remain references. */ +export async function captureScheduledChatRequest( + input: IChatDraft, + readSelection: (uri: URI, range?: IRange) => Promise<string>, + readFile: (uri: URI) => Promise<VSBuffer>, + isDirty: (uri: URI) => boolean = () => false, +): Promise<Message> { + const positions = new PositionOffsetTransformer(input.inputText); + const attachments: MessageAttachment[] = []; + for (const entry of input.attachments) { + const reference = input.references?.find(reference => reference.id === entry.id); + const range = reference?.range ?? (entry.range ? positions.getRange(new OffsetRange(entry.range.start, entry.range.endExclusive)) : undefined); + const common = { + label: entry.name, + ...(entry._meta ? { _meta: entry._meta } : {}), + ...(range ? { + range: { + start: { line: range.startLineNumber - 1, character: range.startColumn - 1 }, + end: { line: range.endLineNumber - 1, character: range.endColumn - 1 }, + } + } : {}), + }; + if ((entry.kind === 'file' || entry.kind === 'symbol') && isLocation(entry.value)) { + if (entry.value.uri.scheme !== Schemas.untitled) { + assertLocalResource(entry.value.uri); + } + attachments.push({ ...common, type: MessageAttachmentKind.EmbeddedResource, displayKind: 'selection', contentType: 'text/plain', data: encodeBase64(VSBuffer.fromString(await readSelection(entry.value.uri, entry.value.range))) }); + } else if ((entry.kind === 'file' || entry.kind === 'directory' || entry.kind === 'promptFile') && URI.isUri(entry.value)) { + if (entry.kind !== 'directory' && (entry.value.scheme === Schemas.untitled || isDirty(entry.value))) { + attachments.push({ ...common, type: MessageAttachmentKind.EmbeddedResource, displayKind: 'document', contentType: 'text/plain', data: encodeBase64(VSBuffer.fromString(await readSelection(entry.value))) }); + } else { + assertLocalResource(entry.value); + attachments.push({ ...common, type: MessageAttachmentKind.Resource, uri: entry.value.toString(), displayKind: entry.kind === 'directory' ? 'directory' : 'document' }); + } + } else if (entry.kind === 'image') { + let bytes = coerceImageBuffer(entry.value); + if (!bytes) { + const uri = entry.references?.find(reference => URI.isUri(reference.reference))?.reference; + if (URI.isUri(uri)) { + assertLocalResource(uri); + bytes = (await readFile(uri)).buffer; + } + } + if (!bytes) { + throw new Error(localize('sendLater.imageUnavailable', "The image '{0}' cannot be saved for later. Attach the image again.", entry.name)); + } + const contentType = detectImageMimeType(bytes) ?? entry.mimeType; + if (!contentType) { + throw new Error(localize('sendLater.imageTypeUnavailable', "The type of image '{0}' could not be determined.", entry.name)); + } + attachments.push({ ...common, type: MessageAttachmentKind.EmbeddedResource, data: encodeBase64(VSBuffer.wrap(bytes)), contentType, displayKind: 'image' }); + } else if (entry.kind === 'paste') { + attachments.push({ ...common, type: MessageAttachmentKind.Simple, modelRepresentation: entry.code }); + } else if ((entry.kind === 'promptText' || entry.kind === 'string' || entry.kind === 'workspace') && typeof entry.value === 'string') { + attachments.push({ ...common, type: MessageAttachmentKind.Simple, modelRepresentation: entry.value }); + } else { + throw new Error(localize('sendLater.unsupportedAttachment', "The attachment '{0}' cannot be saved for later. Remove it or send this request now.", entry.name)); + } + } + return { text: input.inputText, origin: { kind: MessageKind.User }, ...(attachments.length ? { attachments } : {}) }; +} + +function assertLocalResource(uri: URI): void { + if (uri.scheme !== Schemas.file) { + throw new Error(localize('sendLater.nonLocalAttachment', "Send Later requires attachments on this device. Capture the content or remove the remote attachment.")); + } +} + +/** Parses local wall-clock input without silently normalizing invalid or skipped DST times. */ +export function parseScheduledChatTime(value: string): Date | undefined { + const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})[T ](?<hour>\d{2}):(?<minute>\d{2})$/.exec(value.trim()); + if (!match?.groups) { + return undefined; + } + const { year, month, day, hour, minute } = match.groups; + const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute)); + return date.getFullYear() === Number(year) && date.getMonth() === Number(month) - 1 && date.getDate() === Number(day) + && date.getHours() === Number(hour) && date.getMinutes() === Number(minute) ? date : undefined; +} diff --git a/src/vs/workbench/contrib/sessions/common/sessionAttentionService.ts b/src/vs/workbench/contrib/sessions/common/sessionAttentionService.ts new file mode 100644 index 000000000000..62a591282258 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/common/sessionAttentionService.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IDisposable } from '../../../../base/common/lifecycle.js'; +import { IObservable } from '../../../../base/common/observable.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { ISession } from '../../../services/sessions/common/session.js'; + +export const ISessionAttentionService = createDecorator<ISessionAttentionService>('sessionAttentionService'); + +export const enum InboxTab { + ReadyForYou = 'readyForYou', + Working = 'working', + ReadyToMerge = 'readyToMerge', +} + +export const enum InboxNotificationPriority { + Now = 0, + Next = 1, + Later = 2, +} + +/** Live attention classification, independent of sidebar triage decisions. */ +export interface IInboxSessionAttention { + readonly tab: InboxTab.ReadyForYou | InboxTab.Working | InboxTab.ReadyToMerge; + readonly priority: InboxNotificationPriority; + readonly notificationIds: readonly string[]; + /** Links a hydrated input identity to its provisional identity while provider activity is unchanged. */ + readonly pendingInput?: { readonly notificationId: string; readonly provisionalId: string }; + /** Completed before sidebar Inbox activation without actionable notifications. */ + readonly isHistoricalCompletion: boolean; +} + +export interface ISessionAttentionService { + readonly _serviceBrand: undefined; + readonly sessionAttention: IObservable<ReadonlyMap<string, IInboxSessionAttention>>; + /** Classifies a restoration batch using current metadata without changing archive state or starting polling. */ + getSessionAttentionAfterUnarchive(sessions: readonly ISession[]): ReadonlyMap<string, IInboxSessionAttention>; + acquireSessionAttention(): IDisposable; +} diff --git a/src/vs/workbench/contrib/sessions/common/sessionComparison.ts b/src/vs/workbench/contrib/sessions/common/sessionComparison.ts index 61a16a334a36..010fc18ee254 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionComparison.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionComparison.ts @@ -136,6 +136,8 @@ export interface ISessionComparisonSynthesisPlan { export interface ISessionComparison { readonly id: string; readonly groupId: string; + /** Exact initiating chat for agent-created comparisons; absent for manual and older comparisons. */ + readonly originatingChatResource?: URI; /** Legacy owning session for comparisons persisted with nested participants. */ readonly sessionResource?: URI; readonly title: string; @@ -159,6 +161,7 @@ export interface ISessionComparison { } export interface IStartSessionComparisonOptions { + readonly originatingChatResource?: URI; readonly workspace?: URI; readonly prompt: string; readonly attachedContext?: readonly IChatRequestVariableEntry[]; diff --git a/src/vs/workbench/contrib/sessions/common/sessionComparisonConstants.ts b/src/vs/workbench/contrib/sessions/common/sessionComparisonConstants.ts index ce491dd0a405..9564c183852c 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionComparisonConstants.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionComparisonConstants.ts @@ -3,5 +3,5 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -export const OPEN_SESSION_COMPARISON_COMMAND_ID = 'sessions.openComparison'; +export { OPEN_SESSION_COMPARISON_COMMAND_ID } from '../../../common/sessionComparisonConstants.js'; export const HIDE_INACTIVE_COMPARISON_INPUTS_SETTING = 'sessions.chat.compareAgents.hideInactiveInputs'; diff --git a/src/vs/workbench/contrib/sessions/common/sessionConfig.ts b/src/vs/workbench/contrib/sessions/common/sessionConfig.ts index c4e7184db875..9f2800d14ee3 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionConfig.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionConfig.ts @@ -7,8 +7,16 @@ import type { ResolveSessionConfigResult } from '../../../../platform/agentHost/ export const USE_WORKTREE_SETTING = 'sessions.useWorktree'; +export const SESSIONS_DRAFTS_ENABLED_SETTING = 'sessions.drafts.enabled'; +export const SESSIONS_SEND_LATER_ENABLED_SETTING = 'sessions.sendLater.enabled'; + export const SESSIONS_CHAT_TABS_SETTING = 'sessions.showChatTabs'; +export const SESSIONS_DETAILS_POSITION_SETTING = 'sessions.experimental.detailsPosition'; +export const SESSIONS_FLOATING_DETAILS_SETTING = 'sessions.experimental.floatingDetails'; + +export type DetailsPosition = 'right' | 'left' | 'top' | 'bottom'; + /** Whether the Session Activity Bar is shown beside the active chat in the desktop Agents window. */ export const SESSION_ACTIVITY_BAR_SETTING = 'sessions.showSessionActivityBar'; @@ -42,6 +50,7 @@ export const enum AutomationSessionsListMode { /** 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_INLINE_ACTIONS_SETTING = 'sessions.list.inlineActions'; export const SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING = 'sessions.list.externalApplicationBadge'; @@ -60,6 +69,24 @@ export const enum ExternalSessionApplicationBadgeMode { export const SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING = 'sessions.sidebar.separateNavigation'; +/** + * Whether Customizations keeps its own section below the Sessions list rather than joining the separate navigation + * list. Only applies when {@link SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING} is enabled. Not nested under it: a + * setting cannot also be the parent of another setting. + */ +export const SESSIONS_SIDEBAR_CUSTOMIZATIONS_AT_BOTTOM_SETTING = 'sessions.sidebar.customizationsAtBottom'; + +/** + * Which customization categories the Customizations section below the Sessions list shows. + */ +export const SESSIONS_SIDEBAR_CUSTOMIZATIONS_CATEGORIES_SETTING = 'sessions.sidebar.customizationsCategories'; + +export const enum SessionsSidebarCustomizationsCategories { + All = 'all', + /** Only the categories that are shown when reduced, and a More menu with the others. */ + Reduced = 'reduced', +} + export const SESSIONS_LIST_REARRANGE_TREATMENT = 'sessions.list.rearrage'; export const enum SessionsChatTabsMode { diff --git a/src/vs/workbench/contrib/sessions/common/sessionInbox.ts b/src/vs/workbench/contrib/sessions/common/sessionInbox.ts index 934c9484a159..9287f6b7a840 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionInbox.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionInbox.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { IReader } from '../../../../base/common/observable.js'; +import { localize } from '../../../../nls.js'; import { IInboxSessionAttention, InboxNotificationPriority, InboxTab } from './inboxNotificationsService.js'; import { ISession, SessionStatus } from '../../../services/sessions/common/session.js'; @@ -57,6 +58,13 @@ export function getSessionInboxSection(session: ISession, state?: SessionInboxSt if (state) { return SessionInboxSection.OnHold; } + const chats = session.chats.read(reader).filter(chat => !chat.isArchived.read(reader)); + if (chats.length > 1 && chats.some(chat => { + const status = chat.status.read(reader); + return status === SessionStatus.Completed || status === SessionStatus.NeedsInput || status === SessionStatus.Error; + }) && (attention?.tab === InboxTab.Working || !attention && session.status.read(reader) === SessionStatus.InProgress)) { + return SessionInboxSection.ReadyForYou; + } if (attention) { switch (attention.tab) { case InboxTab.ReadyForYou: return SessionInboxSection.ReadyForYou; @@ -68,8 +76,19 @@ export function getSessionInboxSection(session: ISession, state?: SessionInboxSt if (status === SessionStatus.NeedsInput || status === SessionStatus.Error) { return SessionInboxSection.ReadyForYou; } + if (status === SessionStatus.InProgress) { return SessionInboxSection.Working; } return SessionInboxSection.ReadyForYou; } + +export function getSessionInboxDescription(state: SessionInboxState | undefined): string | undefined { + switch (state?.kind) { + case 'snoozed': return localize('inboxSnoozedUntil', "Snoozed until {0}", new Date(state.until).toLocaleString()); + case 'untilActivity': return localize('inboxSnoozedUntilActivity', "Snoozed until new activity"); + case 'hold': return localize('inboxHeldUntilResumed', "On hold until you return it to Inbox"); + case 'done': return localize('inboxDismissedNotArchived', "Dismissed from Inbox, not archived"); + default: return undefined; + } +} diff --git a/src/vs/workbench/contrib/sessions/common/sessionWorktreeIcon.ts b/src/vs/workbench/contrib/sessions/common/sessionWorktreeIcon.ts new file mode 100644 index 000000000000..4c4bdd7b3e71 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/common/sessionWorktreeIcon.ts @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../base/common/codicons.js'; + +/** + * The icon of a git worktree of a repository wherever the editor window shows one: a location of the window's folder, + * a worktree of the composer's folder picker and its New Worktree option, as a Worktree section of the Sessions list + * shows one. + */ +export const SESSION_WORKTREE_ICON = Codicon.gitBranchCheckout; diff --git a/src/vs/workbench/contrib/sessions/common/sessionsManagement.ts b/src/vs/workbench/contrib/sessions/common/sessionsManagement.ts index 7da2eae7f02c..9d946a401c0c 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionsManagement.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionsManagement.ts @@ -638,6 +638,7 @@ export interface ISessionsManagementService { /** Reports cleanup status, optionally retrying removal without restoring or deleting session history. */ canForceWorktreeCleanup?(owner: ISession | IManagedSessionWorktree): boolean; sessionWorktreeCleanup?(session: ISession, retry: boolean, force?: boolean): Promise<IAgentHostWorktreeCleanupStatus | undefined>; + prepareSessionWorktreeCleanup(session: ISession): Promise<void>; listManagedWorktrees?(knownWorktrees?: readonly IManagedSessionWorktree[]): Promise<IManagedSessionWorktree[]>; cleanupManagedWorktree?(worktree: IManagedSessionWorktree, force?: boolean): Promise<void>; managedWorktreeExists?(worktree: IManagedSessionWorktree): Promise<boolean | undefined>; diff --git a/src/vs/workbench/contrib/sessions/common/sessionsProvider.ts b/src/vs/workbench/contrib/sessions/common/sessionsProvider.ts index 0bff72e198a4..5f9603a44170 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionsProvider.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionsProvider.ts @@ -180,6 +180,8 @@ export interface IPreparedNewSession { * Options for sending a request to a session. */ export interface ISendRequestOptions { + /** Reject an unavailable connection instead of retaining the request for reconnection. */ + readonly requireConnected?: boolean; /** Initial configuration resolved by the target provider before its first turn. */ readonly sessionConfig?: Readonly<Record<string, unknown>>; /** UI-only response observation, forwarded to the chat service rather than the backend. */ @@ -745,6 +747,7 @@ export interface ISessionsProvider { /** Returns undefined when cleanup status and retry are not supported by this session's host. */ readonly supportsForceWorktreeCleanup?: boolean; sessionWorktreeCleanup?(sessionId: string, retry: boolean, force?: boolean): Promise<IAgentHostWorktreeCleanupStatus | undefined>; + prepareSessionWorktreeCleanup?(sessionId: string): Promise<void>; listManagedWorktrees?(repositories?: readonly URI[]): Promise<IAgentHostManagedWorktree[]>; cleanupManagedWorktree?(worktree: IAgentHostManagedWorktree, force?: boolean): Promise<void>; managedWorktreeExists?(worktree: IAgentHostManagedWorktree): Promise<boolean | undefined>; diff --git a/src/vs/workbench/contrib/sessions/common/sessionsTelemetry.ts b/src/vs/workbench/contrib/sessions/common/sessionsTelemetry.ts index 75162c53e591..1bef55c30d01 100644 --- a/src/vs/workbench/contrib/sessions/common/sessionsTelemetry.ts +++ b/src/vs/workbench/contrib/sessions/common/sessionsTelemetry.ts @@ -92,16 +92,24 @@ export interface ISessionComparisonAttemptCompletedTelemetry { readonly comparisonId: string; readonly attemptIndex: number; readonly elapsedMs: number; + readonly inputTokens?: number; + readonly cachedTokens?: number; + readonly outputTokens?: number; + readonly tokenCountIsComplete: boolean; } type SessionComparisonAttemptCompletedEvent = ISessionComparisonAttemptCompletedTelemetry; type SessionComparisonAttemptCompletedClassification = { owner: 'meganrogge'; - comment: 'Tracks the elapsed time of a comparison attempt before its first turn becomes terminal.'; + comment: 'Tracks elapsed time and token usage of a comparison attempt when its first turn becomes terminal.'; comparisonId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'A hashed identifier used to join this attempt with its Judge model outcome.' }; attemptIndex: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The zero-based ordinal of this attempt among the attempts reviewed by the Judge.' }; elapsedMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Provider-reported elapsed milliseconds for the terminal first turn.' }; + inputTokens?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Input tokens for the first turn, omitted when usage is unavailable.' }; + cachedTokens?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Cached input tokens for the first turn, omitted when accounting is incomplete. Already included in inputTokens.' }; + outputTokens?: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Output tokens for the first turn, omitted when usage is unavailable.' }; + tokenCountIsComplete: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Whether token accounting covers the complete first turn. False when usage is missing or partial.' }; }; export function logSessionComparisonAttemptCompleted(telemetryService: ITelemetryService, data: ISessionComparisonAttemptCompletedTelemetry): void { diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/AGENT_HOST_SESSIONS_PROVIDER.md b/src/vs/workbench/contrib/sessions/providers/agentHost/AGENT_HOST_SESSIONS_PROVIDER.md index de17ec85a234..aa8fdfcdde19 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/AGENT_HOST_SESSIONS_PROVIDER.md +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/AGENT_HOST_SESSIONS_PROVIDER.md @@ -141,7 +141,9 @@ Session workflow operations such as pull-request creation and Agent Merge are ad Branch, Uncommitted, This Turn, and Session Changes entries all offer the resource-scoped `discard-changes` operation, and the host dispatches on the changeset kind. On Branch it restores the file from its displayed Git baseline, and on Uncommitted it restores the file from Git. On This Turn it is offered only for the chat's latest turn, including in folders that aren't Git repositories, and reverts only that turn's tracked edits to the file, one recorded edit at a time: other changes to the file are kept, including edits made between the turn's tool calls, and the file is left untouched when later edits overlap the turn's edits. The host records the discard by appending a synthetic edit row to that turn's tracked edits, so the file leaves This Turn and Session Changes while the transcript keeps the agent's original edits. The file only changes inside the transaction that appends the row. A file that the turn created is deleted, along with any later changes to it, like undoing a file that a chat editing session created; it goes to the trash where the file system supports that. A file that another chat in the session also edited can't be discarded, because Session Changes can't order one chat's discard against another chat's edits. -On Session Changes it is offered unless the changeset spans more than one folder, also in folders that aren't Git repositories, and reverts the tracked edits of every turn that changed the file the same way, keeping changes made outside those turns and deleting a file the session created. Edits that an earlier discard already undid aren't reverted again, because their discard rows record the whole turn rather than what that discard changed on disk. The host appends one synthetic row per turn, newest turn first, in a single transaction, so the file leaves Session Changes and every turn's changeset, and the last row restores the file's content from before its first tracked edit. It is rejected while a turn runs in any chat of the session, and for files that another chat also edited and renamed files. +On Session Changes it is offered in single-folder and multi-root workspaces, including folders that aren't Git repositories, and reverts the tracked edits of every turn that changed the file the same way, keeping changes made outside those turns and deleting a file the session created. Edits that an earlier discard already undid aren't reverted again, because their discard rows record the whole turn rather than what that discard changed on disk. The host appends one synthetic row per turn, newest turn first, in a single transaction, so the file leaves Session Changes and every turn's changeset, and the last row restores the file's content from before its first tracked edit. It is rejected while a turn runs in any chat of the session, and for files that another chat also edited and renamed files. + +The Working Set supports both file and range discard across workspace folders, keeping accepted edits and non-overlapping user changes. Both Working Set and Session Changes discards match the target's full resource path within the owner's workspace and tracked folder scope, so a file with the same relative path in another root is unaffected; files edited by multiple chats remain unsupported. Chat catalogues with the same normalized effective working directories reference one session-scoped folder Branch Changes resource using the `ahp-folder-changeset:` scheme. The resource belongs to the folder/worktree scope rather than to a particular chat, so the default chat and matching peers advertise the same stable URI while chats in different folders or worktrees advertise different URIs. A multi-root workspace forms one composite scope, including when its folders contain multiple Git repositories, while distinct worktree paths remain separate scopes even when they come from the same repository. The selected base branch affects the diff computed for the resource but not its identity. The Agent Host resolves a representative chat as the folder scope's computation and persistence context, allowing matching chats to share branch computation, review state, monitoring, and picker content without making that chat the resource owner. diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentPicker.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentPicker.ts index ef70c7bd59e1..9f0e965ca42d 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentPicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentPicker.ts @@ -5,19 +5,20 @@ import { BaseActionViewItem, IActionViewItemOptions } from '../../../../../../base/browser/ui/actionbar/actionViewItems.js'; import * as dom from '../../../../../../base/browser/dom.js'; +import { Event } from '../../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; -import { autorun, derived, IObservable, IReader, observableSignalFromEvent } from '../../../../../../base/common/observable.js'; -import { URI } from '../../../../../../base/common/uri.js'; +import { autorun, derived, IObservable, IReader, observableFromEvent, observableSignalFromEvent } from '../../../../../../base/common/observable.js'; import * as nls from '../../../../../../nls.js'; import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; import { Action2, MenuId } from '../../../../../../platform/actions/common/actions.js'; -import { CustomizationType } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { agentHostAgentPickerStorageKey, resolveAgentHostAgent } from '../../../../../../platform/agentHost/common/customAgents.js'; import { ContextKeyExpr, IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; -import { IStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; +import { IStorageService, StorageScope } from '../../../../../../platform/storage/common/storage.js'; import { IWorkbenchContribution } from '../../../../../common/contributions.js'; import { IChatWidgetService } from '../../../../chat/browser/chat.js'; +import { registerAgentPickerSpotlight } from '../../../../chat/browser/onboarding/agentPickerSpotlight.js'; +import { AgentsWindowUsage } from '../../../../chat/common/agentsWindowUsage.js'; import { ChatContextKeyExprs, ChatContextKeys } from '../../../../chat/common/actions/chatContextKeys.js'; import { ChatMode, IChatMode } from '../../../../chat/common/chatModes.js'; import { IChatService } from '../../../../chat/common/chatService/chatService.js'; @@ -31,7 +32,8 @@ import { IsSessionsWindowContext } from '../../../../../common/contextkeys.js'; import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; import { IChat, ISession, ISessionAgentRef, SessionStatus } from '../../../../../services/sessions/common/session.js'; import { ModePicker, ScopedModePickerModelCache } from '../../copilotChatSessions/browser/modePicker.js'; -import { IFocusedSessionHostService, InSessionHostScopeContext, ISessionHost } from '../../../../../services/sessions/browser/sessionHost.js'; +import { IFocusedSessionHostService, InSessionHostScopeContext, ISessionHost, SessionHostKind } from '../../../../../services/sessions/browser/sessionHost.js'; +import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { IAction } from '../../../../../../base/common/actions.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; @@ -40,12 +42,17 @@ import { Codicon } from '../../../../../../base/common/codicons.js'; import { IChatContextPickService, IChatContextValueItem } from '../../../../chat/browser/attachments/chatContextPickService.js'; import { ITelemetryService } from '../../../../../../platform/telemetry/common/telemetry.js'; import { logSettingExperimentTrigger } from '../../../../../../platform/telemetry/common/experimentTrigger.js'; +import { getAgentHostAgentPickerState, setAgentHostAgent } from './agentHostAgentSelection.js'; +import { IProductService } from '../../../../../../platform/product/common/productService.js'; const IsActiveSessionAgentHost = ContextKeyExpr.or( ContextKeyExpr.equals(SessionProviderIdContext.key, LOCAL_AGENT_HOST_PROVIDER_ID), ContextKeyExpr.regex(SessionProviderIdContext.key, REMOTE_AGENT_HOST_PROVIDER_RE), ); +/** Session-starting Agents Window requests a user must have sent before the custom agents spotlight shows, so it does not overwhelm new users. */ +const AGENT_PICKER_SPOTLIGHT_MIN_CREATED_SESSIONS = 3; + // -- Agent Host Agent Picker Action -- const AGENT_HOST_AGENT_PICKER_ACTION_ID = 'sessions.agentHost.agentPicker'; @@ -215,6 +222,8 @@ export class AgentHostAgentPickerContribution extends Disposable implements IWor @IChatContextPickService chatContextPickService: IChatContextPickService, @ITelemetryService telemetryService: ITelemetryService, @INewSessionComposerService private readonly newSessionComposerService: INewSessionComposerService, + @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, + @IProductService productService: IProductService, ) { super(); let settingAgentInternally = false; @@ -228,6 +237,33 @@ export class AgentHostAgentPickerContribution extends Disposable implements IWor const shouldHidePicker = (chat: IChat | undefined, reader: IReader): boolean => configurationService.getValue<boolean>(AGENTS_PICKER_IN_ATTACH_CONTEXT_MENU_SETTING) && !isCustomAgentSelected(chat, reader); + if (environmentService.isSessionsWindow) { + const usage = new AgentsWindowUsage(storageService); + const hasEnoughRequests = observableFromEvent(this, usage.onDidChangeCreatedSessionCount(this._store), () => usage.createdSessionCount >= AGENT_PICKER_SPOTLIGHT_MIN_CREATED_SESSIONS); + const widgetsChanged = observableSignalFromEvent(this, Event.any( + chatWidgetService.onDidAddWidget, + chatWidgetService.onDidRemoveWidget, + chatWidgetService.onDidChangeWidgetVisibility, + chatWidgetService.onDidChangeFocusedSession, + Event.filter(contextKeyService.onDidChangeContext, event => event.affectsSome(new Set([IsPhoneLayoutContext.key]))), + )); + this._register(registerAgentPickerSpotlight(derived(this, reader => { + widgetsChanged.read(reader); + configurationChanged.read(reader); + if (!hasEnoughRequests.read(reader)) { + return []; + } + const host = focusedSessionHostService.focusedHost.read(reader); + const session = host.session.read(reader); + const chat = host.chat.read(reader); + if (!shouldHidePicker(chat, reader) || host.kind === SessionHostKind.AutomationDialog || !isEligible(session, chat)) { + return []; + } + const widget = chat && chatWidgetService.getWidgetBySessionResource(chat.resource); + return widget?.visible ? [widget] : []; + }), productService)); + } + const renderedPickers = new Set<{ readonly session: IObservable<ISession | undefined>; readonly item: AgentHostModePickerActionViewItem }>(); openActiveAgentPicker = anchor => { const activeSession = focusedSessionHostService.focusedHost.get().session.get(); @@ -391,26 +427,10 @@ export class AgentHostAgentPickerContribution extends Disposable implements IWor return; } - const customizations = provider.getCustomizations(session.sessionId); - const rawAgents = provider.getCustomAgents(session.sessionId); - const agents = rawAgents.map(agent => { - const containers = customizations.filter(customization => customization.type !== CustomizationType.McpServer && customization.children?.some(child => child.uri === agent.uri)); - return containers.length > 0 - ? { ...agent, uri: provider.mapAgentHostResource(URI.parse(agent.uri)).toString() } - : agent; - }); + const { agents, toPickerUri } = getAgentHostAgentPickerState(session.sessionId, provider); const storedUri = isUntitled ? this.storageService.get(agentHostAgentPickerStorageKey(session.resource.scheme), StorageScope.PROFILE) : undefined; - // Resolve selected, remembered, or draft-source URIs to the client-space URI the picker lists. - const toPickerUri = (uri: string | undefined) => { - if (!uri) { - return undefined; - } - const hostUri = provider.resolveCustomAgent?.(session.sessionId, uri)?.uri ?? uri; - const index = rawAgents.findIndex(agent => agent.uri === hostUri); - return index >= 0 ? agents[index].uri : uri; - }; const resolved = resolveAgentHostAgent(agents, toPickerUri(selectedAgentUri), toPickerUri(storedUri)); if (!selectedAgentUri && isUntitled && resolved) { @@ -445,12 +465,6 @@ export class AgentHostAgentPickerContribution extends Disposable implements IWor } private _setAgent(session: ISession, provider: IAgentHostSessionsProvider, agent: ISessionAgentRef | undefined): void { - const key = agentHostAgentPickerStorageKey(session.resource.scheme); - if (agent) { - this.storageService.store(key, agent.uri, StorageScope.PROFILE, StorageTarget.MACHINE); - } else { - this.storageService.remove(key, StorageScope.PROFILE); - } - provider.setAgent?.(session.sessionId, agent ? { uri: agent.uri, name: agent.name } : undefined); + setAgentHostAgent(session, provider, agent, this.storageService); } } diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentSelection.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentSelection.ts new file mode 100644 index 000000000000..054c3648e5e6 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostAgentSelection.ts @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { URI } from '../../../../../../base/common/uri.js'; +import { agentHostAgentPickerStorageKey } from '../../../../../../platform/agentHost/common/customAgents.js'; +import { CustomizationType } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; +import { IAgentHostSessionsProvider } from '../../../common/agentHostSessionsProvider.js'; +import { ISession, ISessionAgentRef } from '../../../../../services/sessions/common/session.js'; + +/** Uses the same client-space identity for listed, selected, and remembered custom agents. */ +export function getAgentHostAgentPickerState(sessionId: string, provider: IAgentHostSessionsProvider) { + const customizations = provider.getCustomizations(sessionId); + const rawAgents = provider.getCustomAgents(sessionId); + const agents = rawAgents.map(agent => { + const contained = customizations.some(customization => customization.type !== CustomizationType.McpServer && customization.children?.some(child => child.uri === agent.uri)); + return contained ? { ...agent, uri: provider.mapAgentHostResource(URI.parse(agent.uri)).toString() } : agent; + }); + const toPickerUri = (uri: string | undefined): string | undefined => { + if (!uri) { + return undefined; + } + const hostUri = provider.resolveCustomAgent?.(sessionId, uri)?.uri ?? uri; + const index = rawAgents.findIndex(agent => agent.uri === hostUri); + return index >= 0 ? agents[index].uri : uri; + }; + return { agents, toPickerUri }; +} + +export function setAgentHostAgent(session: ISession, provider: IAgentHostSessionsProvider, agent: ISessionAgentRef | undefined, storageService: IStorageService): void { + const key = agentHostAgentPickerStorageKey(session.resource.scheme); + if (agent) { + storageService.store(key, agent.uri, StorageScope.PROFILE, StorageTarget.MACHINE); + } else { + storageService.remove(key, StorageScope.PROFILE); + } + provider.setAgent?.(session.sessionId, agent ? { uri: agent.uri, name: agent.name } : undefined); +} diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostArtifactIntegrations.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostArtifactIntegrations.ts index 07b71994cf58..23a9b8af4ba8 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostArtifactIntegrations.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostArtifactIntegrations.ts @@ -3,16 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Disposable, DisposableStore, IDisposable, IReference, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, IDisposable, IReference, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { CancellationError } from '../../../../../../base/common/errors.js'; -import { autorun, derived, IObservable, observableFromEvent, observableValue, observableValueOpts } from '../../../../../../base/common/observable.js'; +import { structuralEquals } from '../../../../../../base/common/equals.js'; +import { autorun, constObservable, derived, derivedOpts, IObservable, ISettableObservable, observableFromEvent, observableValue, observableValueOpts } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { localize } from '../../../../../../nls.js'; import { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; import { getAgentHostArtifactIntegrationsCapability } from '../../../../../../platform/agentHost/common/meta/agentHostArtifactIntegrationMeta.js'; import { AuthRequiredReason } from '../../../../../../platform/agentHost/common/state/protocol/notifications.js'; import { LocalArtifactIntegrationHost } from '../../../../../../platform/artifactIntegrations/browser/localArtifactIntegrationHost.js'; -import { ArtifactActionView, ArtifactIntegrationsSettingId, ArtifactRun, IArtifactIntegrationAccess, IArtifactModel, toArtifactIntegrationDescriptor } from '../../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; +import { ArtifactActionView, ArtifactIntegrationsSettingId, ArtifactRun, ArtifactSnapshot, IArtifactIntegrationAccess, IArtifactModel, toArtifactIntegrationDescriptor } from '../../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; import { ArtifactAuthenticationHandler, ArtifactIntegrationClient, ArtifactIntegrationServer } from '../../../../../../platform/artifactIntegrations/common/artifactIntegrationProtocol.js'; import { IArtifactIntegrationRegistry } from '../../../../../../platform/artifactIntegrations/common/artifactIntegrationRegistry.js'; import { CompositeArtifactModel } from '../../../../../../platform/artifactIntegrations/common/compositeArtifactModel.js'; @@ -42,8 +43,21 @@ export type ArtifactWorkspaceConfigurationSynchronizer = ( session: string, artifactId: string, workspace: IObservable<IArtifactWorkspaceConfigurationContext | undefined>, - model: IArtifactModel, -) => void; + snapshot: IObservable<ArtifactSnapshot | undefined>, +) => IObservable<boolean>; + +interface IArtifactWorkspaceConfigurationSource { + readonly workspace: IObservable<IArtifactWorkspaceConfigurationContext | undefined>; + readonly snapshot: IObservable<ArtifactSnapshot | undefined>; +} + +interface IArtifactWorkspaceConfigurationWriter { + readonly sources: ISettableObservable<readonly IArtifactWorkspaceConfigurationSource[]>; + /** Whether a changed value is waiting to settle before it is published. */ + readonly pending: IObservable<boolean>; + readonly release: MutableDisposable<IDisposable>; + readonly store: DisposableStore; +} /** Adapts advertised chat identifiers without changing execution, history cursors, or run ownership. */ export function mapArtifactModelChats( @@ -55,7 +69,8 @@ export function mapArtifactModelChats( ? { ...run, chat: mapping.find(chat => chat.backend === run.chat)?.client.toString() } : run; return { - snapshot: derived(reader => { + // The chat mapping changes with every chat of the session; publish a snapshot only when its content changes. + snapshot: derivedOpts<ArtifactSnapshot>({ equalsFn: structuralEquals }, reader => { const snapshot = model.snapshot.read(reader); const mapping = chats.read(reader); const mapAction = (action: ArtifactActionView): ArtifactActionView => !action.chatAvailability ? action : { @@ -142,6 +157,7 @@ export class AgentHostArtifactIntegrations extends Disposable { private readonly client = this._register(new MutableDisposable<ArtifactIntegrationClient>()); private readonly bridge = this._register(new MutableDisposable()); private readonly fallback = this._register(new MutableDisposable<IClientArtifactHost>()); + private readonly workspaceConfigurationWriters = new Map<string, IArtifactWorkspaceConfigurationWriter>(); private readonly permitted; private current: IAgentConnection | undefined; private selected: 'host' | 'client' | undefined; @@ -165,6 +181,12 @@ export class AgentHostArtifactIntegrations extends Disposable { @IConfigurationService configurationService: IConfigurationService, ) { super(); + this._register(toDisposable(() => { + for (const writer of this.workspaceConfigurationWriters.values()) { + writer.store.dispose(); + } + this.workspaceConfigurationWriters.clear(); + })); const authentication = instantiationService.createInstance(AgentHostInteractiveAuthentication); this.scope = JSON.stringify([profileService.currentProfile.id, targetHost]); this.selectionKey = `artifactIntegrations.authority.${this.scope}`; @@ -313,7 +335,7 @@ export class AgentHostArtifactIntegrations extends Disposable { }).catch(error => this.logService.error('[ArtifactIntegrations] Could not acquire client integration', error)); } if (workspace && this.client.value) { - this.synchronizeWorkspaceConfiguration?.(store, this.connection, () => this.selected === 'host', session, artifactId, workspace, reference.object); + store.add(this.retainWorkspaceConfiguration(session, artifactId, { workspace, snapshot: reference.object.snapshot })); } return { object: model, dispose: () => store.dispose() }; } catch (error) { @@ -321,4 +343,57 @@ export class AgentHostArtifactIntegrations extends Disposable { throw error; } } + + /** + * Publishes an artifact's workspace configuration through one writer shared by all of its live references, using the + * most recently acquired one. Separate writers would each send their own context and overwrite one another. + */ + private retainWorkspaceConfiguration(session: string, artifactId: string, source: IArtifactWorkspaceConfigurationSource): IDisposable { + const synchronize = this.synchronizeWorkspaceConfiguration; + if (!synchronize) { + return Disposable.None; + } + const key = JSON.stringify([session, artifactId]); + let writer = this.workspaceConfigurationWriters.get(key); + if (!writer) { + const sources = observableValue<readonly IArtifactWorkspaceConfigurationSource[]>(this, []); + const current = derived(reader => sources.read(reader).at(-1)); + const store = new DisposableStore(); + const pending = synchronize(store, this.connection, () => this.selected === 'host', session, artifactId, + derived(reader => current.read(reader)?.workspace.read(reader)), + derived(reader => current.read(reader)?.snapshot.read(reader))); + writer = { sources, pending, release: store.add(new MutableDisposable()), store }; + this.workspaceConfigurationWriters.set(key, writer); + } + const retained = writer; + if (retained.release.value) { + // The released context was only kept to settle its publication. + retained.release.clear(); + retained.sources.set([source], undefined); + } else { + retained.sources.set([...retained.sources.get(), source], undefined); + } + return toDisposable(() => { + const remaining = retained.sources.get().filter(candidate => candidate !== source); + if (remaining.length > 0) { + retained.sources.set(remaining, undefined); + } else if (this.workspaceConfigurationWriters.get(key) === retained && !retained.release.value) { + const disposeWriter = () => { + this.workspaceConfigurationWriters.delete(key); + retained.store.dispose(); + }; + if (!retained.pending.get()) { + disposeWriter(); + return; + } + // Host automation outlives the reference, so a change still settling is published with the last context. + retained.sources.set([{ workspace: constObservable(source.workspace.get()), snapshot: constObservable(source.snapshot.get()) }], undefined); + retained.release.value = autorun(reader => { + if (!retained.pending.read(reader) && this.workspaceConfigurationWriters.get(key) === retained) { + disposeWriter(); + } + }); + } + }); + } } diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostModePicker.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostModePicker.ts index ace6356e0296..7068e7ad609d 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostModePicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostModePicker.ts @@ -63,6 +63,7 @@ export abstract class AgentHostSessionEnumPicker extends Disposable { private _slotElement: HTMLElement | undefined; protected _triggerElement: HTMLElement | undefined; private _pickerVisible = false; + private _pickerPresenter: ((anchor: HTMLElement) => Promise<void>) | undefined; protected abstract readonly _property: string; protected abstract readonly _pickerId: string; @@ -292,8 +293,12 @@ export abstract class AgentHostSessionEnumPicker extends Disposable { } } + setPickerPresenter(presenter: (anchor: HTMLElement) => Promise<void>): void { + this._pickerPresenter = presenter; + } + protected _showPicker(anchor = this._triggerElement, onHide?: () => void, listOptions = this._getListOptions()): boolean { - if (!anchor || this._actionWidgetService.isVisible) { + if (!anchor || this._pickerVisible || this._actionWidgetService.isVisible) { return false; } const ctx = this._getActiveContext(); @@ -304,6 +309,19 @@ export abstract class AgentHostSessionEnumPicker extends Disposable { if (this._isCurrentlyResolvingConfig()) { return false; } + if (this._pickerPresenter) { + this._pickerVisible = true; + anchor.setAttribute('aria-expanded', 'true'); + void this._pickerPresenter(anchor).finally(() => { + this._pickerVisible = false; + anchor.setAttribute('aria-expanded', 'false'); + if (anchor.isConnected) { + anchor.focus(); + } + onHide?.(); + }).catch(onUnexpectedError); + return true; + } const actionItems = this._getActionItems(ctx.items, ctx.currentValue); actionItems.push(...this._getFooterActionItems()); diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.ts index 7081c4a16933..f3471537c232 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostPermissionPickerDelegate.ts @@ -214,7 +214,7 @@ export class AgentHostPermissionPickerDelegate extends Disposable implements IPe return createAgentHostSandboxToggle(() => this._sandboxState.get(), enabled => this.setSandboxEnabled(enabled)); } - setSandboxEnabled(enabled: boolean): void { + setSandboxEnabled(enabled: boolean): Promise<void> { const session = this._session.get(); const chat = this._chat.get(); const provider = session && this._getProvider(session.providerId, session.sessionId); @@ -226,7 +226,7 @@ export class AgentHostPermissionPickerDelegate extends Disposable implements IPe } const operation = provider.setSessionConfigValue(session.sessionId, chat.resource, SessionConfigKey.SandboxEnabled, enabled ? 'on' : 'off'); provider.trackSessionConfigOperation?.(session.sessionId, operation); - void operation.catch(onUnexpectedError); + return operation.catch(onUnexpectedError); } async setPermissionLevel(level: ChatPermissionLevel): Promise<void> { diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.ts index 1647728c48dd..bf2f56f857cb 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/agentHostSessionConfigPicker.ts @@ -59,7 +59,9 @@ import { NEW_WORKTREE_LABEL } from '../../../browser/chat/branchPicker.js'; import { ISessionChangesService } from '../../../../../services/sessions/common/sessionChangesService.js'; import { CHANGES_VIEW_ID } from '../../../common/changes.js'; import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; -import { getFocusedSessionChatSource, IFocusedSessionHostService, InSessionHostScopeContext, ISessionChatSource, ISessionHost } from '../../../../../services/sessions/browser/sessionHost.js'; +import { getFocusedSessionChatSource, IFocusedSessionHostService, InSessionHostScopeContext, ISessionChatSource, ISessionHost, ISessionHostService } from '../../../../../services/sessions/browser/sessionHost.js'; +import { IChatPhoneInputPresenter } from '../../../../chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { createChatPhoneInputSessionContext } from '../../../browser/chatPhoneInputContext.js'; import { ISessionsService } from '../../../browser/sessionsService.js'; import type { ISessionsProvider } from '../../../common/sessionsProvider.js'; import { type IAgentHostSessionsProvider, isAgentHostProvider, LOCAL_AGENT_HOST_PROVIDER_ID, REMOTE_AGENT_HOST_PROVIDER_RE } from '../../../common/agentHostSessionsProvider.js'; @@ -85,9 +87,8 @@ import { CodexSessionConfigKey } from '../../../../../../platform/agentHost/comm import { type IChat, type ISessionChangeset, type ISessionFileChange, UNCOMMITTED_CHANGES_CHANGESET_ID, ISession } from '../../../../../services/sessions/common/session.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { IUncommittedChangesListItem, IWorktreeSuggestion, IWorktreeSuggestionService } from '../../../browser/worktreeSuggestion/worktreeSuggestionService.js'; -import { getChangedFileUri, getUncommittedFilesDescription, getUncommittedFilesSectionLabel } from '../../../browser/worktreeSuggestion/worktreeSuggestionPresentation.js'; +import { getChangedFileUri, getModifiedFilesSectionLabel, getUncommittedFilesDescription } from '../../../browser/worktreeSuggestion/worktreeSuggestionPresentation.js'; import { WorktreeSuggestionVariant } from '../../../common/worktreeSuggestion.js'; -import { readPaneSessions } from '../../../../../services/sessions/browser/sessionGridPane.js'; const ExperimentalSessionComposerLayout = SessionUsesExperimentalComposerLayoutContext; const LegacySessionComposerLayout = SessionUsesExperimentalComposerLayoutContext.negate(); @@ -119,6 +120,8 @@ export interface IConfigPickerItem { readonly disabled?: boolean; /** Text shown after the label, such as "Recommended". */ readonly badge?: string; + /** Shows {@link badge} as a quiet secondary pill instead of in the badge color. */ + readonly secondaryBadge?: boolean; /** Runs instead of selecting a value, for rows that are not options, such as reviewing uncommitted changes. */ readonly run?: () => void; } @@ -158,10 +161,13 @@ function formatUncommittedChanges(count: number): string { : localize('agentHostSessionConfig.branchItemUncommittedPlural', "{0} uncommitted files", count); } -/** Recommends New Worktree over Branch in the isolation picker while the worktree suggestion applies. */ -function withWorktreeSuggestion(item: IConfigPickerItem, suggestion: IWorktreeSuggestion): IConfigPickerItem { +/** + * Recommends New Worktree over Branch in the isolation picker while the worktree suggestion applies. Once + * the user has started a session in a new worktree, the recommendation is a quieter secondary pill. + */ +function withWorktreeSuggestion(item: IConfigPickerItem, suggestion: IWorktreeSuggestion, hasCreatedWorktreeSession: boolean): IConfigPickerItem { if (item.value === 'worktree') { - return item.disabled ? item : { ...item, badge: localize('agentHostSessionConfig.isolation.recommended', "Recommended") }; + return item.disabled ? item : { ...item, badge: localize('agentHostSessionConfig.isolation.recommended', "Recommended"), secondaryBadge: hasCreatedWorktreeSession }; } if (item.value === 'folder' || item.value === 'workspace') { return { @@ -186,6 +192,9 @@ const LISTED_FILES_MAX = 3; /** Aligns the label of the isolation picker's section of uncommitted files with the files. */ const LISTED_FILES_CLASS = 'sessions-chat-isolation-listed-changes'; +/** Styles the badge of a row whose item has {@link IConfigPickerItem.secondaryBadge}. */ +const SECONDARY_BADGE_CLASS = 'sessions-chat-config-secondary-badge'; + /** Prefixes the values of rows that are not options, which no option value contains. */ const LISTED_FILE_VALUE_PREFIX = '\0worktreeSuggestion:'; @@ -258,7 +267,7 @@ function toActionItems(property: string, items: readonly IConfigPickerItem[], cu return { kind: ActionListItemKind.Action, label: item.label, - ...(property === SessionConfigKey.AutoApprove ? getPermissionLevelBadge(item.value, disabled, organizationDefault) : item.badge ? { badge: item.badge } : {}), + ...(property === SessionConfigKey.AutoApprove ? getPermissionLevelBadge(item.value, disabled, organizationDefault) : item.badge ? { badge: item.badge, ...(item.secondaryBadge ? { className: SECONDARY_BADGE_CLASS } : {}) } : {}), detail, group: { title: '', icon: getConfigIcon(property, item.value, uncommittedChanges !== undefined) }, ariaDescription: detail, @@ -1200,7 +1209,7 @@ export class AgentHostSessionConfigPicker extends Disposable { } // Counts the files the section lists, which the repository's count can briefly disagree with. const total = this._worktreeSuggestionService.getUncommittedChanges(suggestion, undefined)?.length ?? suggestion.uncommittedChanges; - const sectionLabel = getUncommittedFilesSectionLabel(total); + const sectionLabel = getModifiedFilesSectionLabel(total); const files = toConfigPickerItems(this._worktreeSuggestionService.getUncommittedChangesListItems(WorktreeSuggestionVariant.UncommittedFilesCount, suggestion, LISTED_FILES_MAX)) // Screen readers skip separators and the header, so each row carries the section in its group title. .map(row => ({ ...row, group: { ...row.group, title: sectionLabel } })); @@ -1317,7 +1326,8 @@ export class AgentHostSessionConfigPicker extends Disposable { } const { items: filteredItems, policyRestricted } = applyAutoApproveFiltering(rawItems, property, this._configurationService); const isolationSuggestion = presentation === SessionConfigKey.Isolation ? this._getIsolationPickerRecommendation(sessionId) : undefined; - const items = isolationSuggestion ? filteredItems.map(item => withWorktreeSuggestion(item, isolationSuggestion.suggestion)) : filteredItems; + const hasCreatedWorktreeSession = !!isolationSuggestion && this._worktreeSuggestionService.hasCreatedWorktreeSession(undefined); + const items = isolationSuggestion ? filteredItems.map(item => withWorktreeSuggestion(item, isolationSuggestion.suggestion, hasCreatedWorktreeSession)) : filteredItems; const isAutoApproveProperty = property === SessionConfigKey.AutoApprove; const config = this._getSessionConfig(provider, sessionId); const currentValue = config?.values[property] ?? schema.default; @@ -2035,6 +2045,8 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme @IContextKeyService private readonly _contextKeyService: IContextKeyService, @ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService, @ISessionsService private readonly _sessionsService: ISessionsService, + @ISessionHostService private readonly _sessionHostService: ISessionHostService, + @IChatPhoneInputPresenter private readonly _phonePresenter: IChatPhoneInputPresenter, ) { super(); // The mode-picker factories below pick the mobile subclass at @@ -2048,9 +2060,13 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme // because the classes are only accessed inside these factory // callbacks, which run at `AfterRestored` — well after both // modules have finished evaluating. + let shownKey: string | undefined; this._register(autorun(reader => { - readPaneSessions(this._sessionsService.slotPanes, reader); - this._refreshRepositoryMenuItems(actionViewItemService); + const key = this._readShownSessions(reader).map(shown => `${shown.session.sessionId} ${shown.chat.toString()}`).join('\n'); + if (key !== shownKey) { + shownKey = key; + this._refreshRepositoryMenuItems(actionViewItemService); + } })); this._watchProviders(this._sessionsProvidersService.getProviders({ includeSessionBackends: true }), actionViewItemService); this._register(this._sessionsProvidersService.onDidChangeProviders(e => { @@ -2101,7 +2117,7 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme NEW_SESSION_PERMISSION_MODE_PICKER_ID, (_action, _options, scopedInstantiationService) => { const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); - return new PickerActionViewItem(scopedInstantiationService.createInstance(AgentHostClaudePermissionModePicker, host)); + return this._createEnumPermissionPicker(scopedInstantiationService.createInstance(AgentHostClaudePermissionModePicker, host), host); }, )); this._register(actionViewItemService.register( @@ -2109,7 +2125,7 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme NEW_SESSION_CODEX_APPROVALS_PICKER_ID, (_action, _options, scopedInstantiationService) => { const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); - return new PickerActionViewItem(scopedInstantiationService.createInstance(AgentHostCodexApprovalsPicker, host)); + return this._createEnumPermissionPicker(scopedInstantiationService.createInstance(AgentHostCodexApprovalsPicker, host), host); }, )); registerRunningSessionPicker( @@ -2120,14 +2136,14 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme RUNNING_SESSION_PERMISSION_MODE_PICKER_ID, (_action, _options, scopedInstantiationService) => { const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); - return new PickerActionViewItem(scopedInstantiationService.createInstance(AgentHostClaudePermissionModePicker, host)); + return this._createEnumPermissionPicker(scopedInstantiationService.createInstance(AgentHostClaudePermissionModePicker, host), host); }, ); registerRunningSessionPicker( RUNNING_SESSION_CODEX_APPROVALS_PICKER_ID, (_action, _options, scopedInstantiationService) => { const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); - return new PickerActionViewItem(scopedInstantiationService.createInstance(AgentHostCodexApprovalsPicker, host)); + return this._createEnumPermissionPicker(scopedInstantiationService.createInstance(AgentHostCodexApprovalsPicker, host), host); }, ); } @@ -2139,25 +2155,37 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme } // Menu items are derived only from visible sessions; refreshing them recreates the repository pickers. this._providerListeners.set(provider.id, provider.onDidChangeSessionConfig(sessionId => { - if (readPaneSessions(this._sessionsService.slotPanes, undefined).some(session => session.sessionId === sessionId)) { + if (this._readShownSessions(undefined).some(shown => shown.session.sessionId === sessionId)) { this._refreshRepositoryMenuItems(actionViewItemService); } })); } } + private _readShownSessions(reader: IReader | undefined): readonly { readonly session: ISession; readonly chat: URI }[] { + const shown = new Map<string, { readonly session: ISession; readonly chat: URI }>(); + const add = (session: ISession | undefined, chat: IChat | undefined) => { + if (session && !shown.has(session.sessionId)) { + shown.set(session.sessionId, { session, chat: (chat ?? session.mainChat.read(reader)).resource }); + } + }; + for (const pane of this._sessionsService.slotPanes.read(reader)) { + add(pane.session.read(reader), pane.chat.read(reader)); + } + for (const host of this._sessionHostService.hosts.read(reader)) { + add(host.session.read(reader), host.chat.read(reader)); + } + return [...shown.values()]; + } + private _refreshRepositoryMenuItems(actionViewItemService: IActionViewItemService): void { this._repositoryMenuItems.clear(); - for (const pane of this._sessionsService.slotPanes.get()) { - const session = pane.session.get(); - if (!session) { - continue; - } + for (const { session, chat } of this._readShownSessions(undefined)) { const provider = this._sessionsProvidersService.getProvider(session.providerId, session.sessionId); if (!provider || !isAgentHostProvider(provider)) { continue; } - const config = provider.getSessionConfig(session.sessionId, (pane.chat.get() ?? session.mainChat.get()).resource); + const config = provider.getSessionConfig(session.sessionId, chat); if (!config) { continue; } @@ -2234,6 +2262,17 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme return new PickerActionViewItem(picker, delegate); } + private _createEnumPermissionPicker(picker: AgentHostClaudePermissionModePicker | AgentHostCodexApprovalsPicker, host: ISessionHost): PickerActionViewItem { + if (this._phonePresenter.supportsUnifiedConfiguration) { + picker.setPickerPresenter(anchor => this._phonePresenter.showCombinedModeAndModelSheet(anchor, { + kind: 'session', + getSessionContext: () => createChatPhoneInputSessionContext(host.session.get(), host.chat.get()), + initialSection: 'permissions', + })); + } + return new PickerActionViewItem(picker); + } + /** * Inside a running chat widget, use the workbench * {@link PermissionPickerActionItem} so it matches the standard chat-input @@ -2244,6 +2283,9 @@ export class AgentHostSessionConfigPickerContribution extends Disposable impleme if (!(action instanceof MenuItemAction)) { return undefined; } + if (this._phonePresenter.supportsUnifiedConfiguration) { + return this._createNewSessionPermissionPicker(instantiationService); + } const host = instantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); const pickerOptions = { compact: observableValue<boolean, void>(action, false), diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/baseAgentHostSessionsProvider.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/baseAgentHostSessionsProvider.ts index fa22f0e7079d..a894a93dc527 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/baseAgentHostSessionsProvider.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/baseAgentHostSessionsProvider.ts @@ -977,6 +977,8 @@ function toSessionRemoteConnectionStatus(owner: object, connectionStatus: IObser case 'disconnected': switch (status.reason) { case AgentHostTransportFailureReason.Unknown: + case AgentHostTransportFailureReason.AuthenticationFailed: + case AgentHostTransportFailureReason.SSHAuthenticationFailed: return { kind: status.kind, reason: SessionRemoteConnectionFailureReason.Unknown }; case AgentHostTransportFailureReason.HostNotRunning: return { kind: status.kind, reason: SessionRemoteConnectionFailureReason.HostNotRunning }; @@ -1494,14 +1496,17 @@ export class AgentHostSessionAdapter extends Disposable implements ISession { * The chats that recorded each pull request, by link key. A tool chat is * not listed, so its pull requests belong to the chat that started it. An * owner that is not a listed chat is kept, so no listed chat claims its - * pull request; a record without an owner belongs to the main chat. + * pull request; a record without an owner belongs to the main chat. When a + * pull request is an artifact of some chat, only those chats own it; the + * others merely reference it. */ private readonly _pullRequestOwners = derivedOpts<ReadonlyMap<string, readonly string[]>>({ owner: this, equalsFn: (a, b) => a.size === b.size && [...a].every(([key, owners]) => arrayEquals(owners, b.get(key) ?? [])), }, reader => { const chats = this._chatsObs.read(reader); - const result = new Map<string, string[]>(); + const referenceOwners = new Map<string, string[]>(); + const artifactOwners = new Map<string, string[]>(); for (const artifact of this.artifacts.read(reader)) { if (artifact.kind !== SessionArtifactKind.PullRequest || !artifact.link) { continue; @@ -1515,13 +1520,18 @@ export class AgentHostSessionAdapter extends Disposable implements ISession { owner = chat.origin.parentChat; } const key = linkKey(artifact.link.toString()); - const owners = result.get(key) ?? []; - if (!owners.includes(owner.toString())) { - owners.push(owner.toString()); + for (const target of artifact.isArtifact ? [referenceOwners, artifactOwners] : [referenceOwners]) { + const owners = target.get(key) ?? []; + if (!owners.includes(owner.toString())) { + owners.push(owner.toString()); + } + target.set(key, owners); } - result.set(key, owners); } - return result; + for (const [key, owners] of artifactOwners) { + referenceOwners.set(key, owners); + } + return referenceOwners; }); /** Whether this session was created with worktree isolation. */ private readonly _worktreeIsolation = observableValue<boolean>('worktreeIsolation', false); @@ -4612,6 +4622,8 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement * `customizations` and `activeClient.customizations` for the picker. */ protected readonly _lastSessionStates = new Map<string, SessionState>(); + /** The chat that recorded each artifact, parsed once per session `_meta` value rather than once per artifact. */ + private readonly _recordedArtifactOrigins = new WeakMap<SessionMeta, ReadonlyMap<string, string | undefined>>(); /** Fires when {@link _lastSessionStates} or {@link _sessionCache} changes, for readers of a backend session's default chat. */ private readonly _backendSessionsChanged = observableSignal(this); @@ -7811,7 +7823,23 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement // -- Session actions ------------------------------------------------------ async archiveSession(sessionId: string): Promise<void> { - this._setSessionArchived(sessionId, true); + this._assertSessionAvailable(sessionId); + const rawId = this._sessionKeyFromChatId(sessionId); + const cached = rawId ? this._sessionCache.get(rawId) : undefined; + const connection = this.connection; + if (!cached || !connection) { + throw new Error(localize('sessionArchiveUnavailable', "Connect to this session's host to mark it as done.")); + } + const subscription = connection.getSubscription(StateComponents.Session, cached.backendUri, 'archiveSession'); + try { + const result = await connection.dispatchConfirmed(cached.backendUri.toString(), subscription.object, { type: ActionType.SessionIsArchivedChanged, isArchived: true }, CancellationToken.None); + if (result.rejectionReason) { + throw new Error(result.rejectionReason); + } + this._setSessionArchivedLocally(sessionId, true); + } finally { + subscription.dispose(); + } } async importSession(sessionId: string): Promise<void> { @@ -8032,6 +8060,17 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement return supportsForceWorktreeCleanup(this.connection?.initializeResult.get()); } + async prepareSessionWorktreeCleanup(sessionId: string): Promise<void> { + this._assertSessionAvailable(sessionId); + const rawId = this._sessionKeyFromChatId(sessionId); + const session = rawId ? this._sessionCache.get(rawId) : undefined; + const connection = this.connection; + if (!session || !connection?.prepareSessionWorktreeCleanup) { + throw new Error(localize('worktreeCleanupPreparationUnavailable', "Connect to an updated session host to prepare worktree cleanup.")); + } + await connection.prepareSessionWorktreeCleanup(session.backendUri); + } + async sessionWorktreeCleanup(sessionId: string, retry: boolean, force?: boolean) { this._assertSessionAvailable(sessionId); const rawId = this._sessionKeyFromChatId(sessionId); @@ -8389,6 +8428,25 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement return this._artifactIntegrations.value; } + /** Every artifact's workspace reads its origin, so a session update parses the recorded artifacts once for all of them. */ + private _getRecordedArtifactOrigin(meta: SessionMeta | undefined, artifactId: string): string | undefined { + if (!meta) { + return undefined; + } + let origins = this._recordedArtifactOrigins.get(meta); + if (!origins) { + const parsed = new Map<string, string | undefined>(); + for (const artifact of readSessionArtifacts(meta)) { + if (!parsed.has(artifact.id)) { + parsed.set(artifact.id, artifact.origin?.chat); + } + } + origins = parsed; + this._recordedArtifactOrigins.set(meta, origins); + } + return origins.get(artifactId); + } + async acquireArtifactIntegration(sessionId: string, artifactId: string): Promise<IReference<IArtifactModel>> { const rawId = this._sessionKeyFromChatId(sessionId); const session = rawId ? this._sessionCache.get(rawId) : undefined; @@ -8403,8 +8461,7 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement return undefined; } const state = this._lastSessionStates.get(session.sessionId); - const recorded = readSessionArtifacts(state?._meta).find(artifact => artifact.id === artifactId); - const origin = recorded?.origin?.chat ?? state?.defaultChat; + const origin = this._getRecordedArtifactOrigin(state?._meta, artifactId) ?? state?.defaultChat; const chat = state && session.chats.read(reader).find(chat => getSessionChatResource(state, chat.resource.fragment || DEFAULT_CHAT_ID, state.defaultChat) === origin); const folder = chat?.workspace.read(reader)?.folders[0]; // eslint-disable-next-line local/code-agent-host-uri-mapping -- TODO(agent-host-uri): artifact integration workspace context needs the owning connection mapper @@ -8867,6 +8924,7 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement async sendRequest(chatId: string, chatResource: URI, options: ISendRequestOptions): Promise<ISession> { this._assertSessionAvailable(chatId); + this._assertSendConnectionAvailable(options); const newSession = this._getNewSession(chatId); if (newSession) { return this._sendNewSessionRequest(newSession, chatId, chatResource, options); @@ -8874,6 +8932,12 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement return this._sendCommittedChatRequest(chatId, chatResource, options); } + private _assertSendConnectionAvailable(options: ISendRequestOptions): void { + if (options.requireConnected && (!this.connection || this.connection.connectionAvailable?.get() === false)) { + throw new Error(localize('agentHost.sendUnavailable', "The agent host is unavailable. Reconnect and try again.")); + } + } + /** Send the first request for an already-committed peer chat, then clear its `new` flag. */ private async _sendCommittedChatRequest(chatId: string, chatResource: URI, options: ISendRequestOptions): Promise<ISession> { const rawId = this._sessionKeyFromChatId(chatId); @@ -8934,6 +8998,7 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement } try { + this._assertSendConnectionAvailable(options); this._applyChatSessionState(modelRef, selectedModelId, selectedAgentUri, { modelConfiguration: selectedModelConfiguration }); const result = await this._chatService.sendRequest(chatResource, query, sendOptions); diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/githubPullRequestArtifactWorkspaceConfiguration.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/githubPullRequestArtifactWorkspaceConfiguration.ts index 6d454a521675..c8e64a1f4105 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/githubPullRequestArtifactWorkspaceConfiguration.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/githubPullRequestArtifactWorkspaceConfiguration.ts @@ -3,21 +3,43 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { RunOnceScheduler } from '../../../../../../base/common/async.js'; import { structuralEquals } from '../../../../../../base/common/equals.js'; -import { autorun, observableSignal, observableSignalFromEvent } from '../../../../../../base/common/observable.js'; +import { autorun, derived, observableSignal, observableSignalFromEvent, observableValue } from '../../../../../../base/common/observable.js'; import { IAgentConnection } from '../../../../../../platform/agentHost/common/agentService.js'; import { gitHubPullRequestArtifactIntegrationId, gitHubPullRequestArtifactWorkspaceSettingsKey, gitHubPullRequestMarkReadyIgnoredChecksSetting } from '../../../../../../platform/agentHost/common/githubPullRequestArtifact.js'; import { ActionType } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { ArtifactWorkspaceConfigurationSynchronizer } from './agentHostArtifactIntegrations.js'; +type WorkspaceSettings = { readonly chat: string; readonly workingDirectory: string; readonly ignoredChecks: unknown } | null; + +/** + * How long a changed value must stay unchanged before it is published. The workspace context derives from session + * state that the host rewrites after every configuration change, so publishing each transient value could feed a loop + * that floods the session's channel. + */ +export const gitHubPullRequestArtifactWorkspaceSettingsPublishDelay = 250; + export function createGitHubPullRequestArtifactWorkspaceConfigurationSynchronizer(configurationService: IConfigurationService): ArtifactWorkspaceConfigurationSynchronizer { - return (store, connectionObservable, isHostSelected, session, artifactId, workspace, model) => { + return (store, connectionObservable, isHostSelected, session, artifactId, workspace, snapshot) => { const settingsChanged = observableSignalFromEvent(store, configurationService.onDidChangeConfiguration); - let lastValue: { readonly chat: string; readonly workingDirectory: string; readonly ignoredChecks: unknown } | null | undefined; + let lastValue: WorkspaceSettings | undefined; let lastConnection: IAgentConnection | undefined; + const pending = observableValue<{ readonly connection: IAgentConnection; readonly value: WorkspaceSettings } | undefined>('pendingWorkspaceSettings', undefined); const settingsKey = gitHubPullRequestArtifactWorkspaceSettingsKey(artifactId); const resync = observableSignal(store); + const publish = store.add(new RunOnceScheduler(() => { + const next = pending.get(); + pending.set(undefined, undefined); + if (next && isHostSelected()) { + lastValue = next.value; + next.connection.dispatch(session, { + type: ActionType.SessionConfigChanged, + config: { [settingsKey]: next.value }, + }); + } + }, gitHubPullRequestArtifactWorkspaceSettingsPublishDelay)); store.add(autorun(reader => { const connection = connectionObservable.read(reader); if (connection) { @@ -35,9 +57,11 @@ export function createGitHubPullRequestArtifactWorkspaceConfigurationSynchronize resync.read(reader); const connection = connectionObservable.read(reader); const context = workspace.read(reader); - const integrated = model.snapshot.read(reader).contributions.some(contribution => contribution.integrationId === gitHubPullRequestArtifactIntegrationId); + const integrated = snapshot.read(reader)?.contributions.some(contribution => contribution.integrationId === gitHubPullRequestArtifactIntegrationId) ?? false; if (!isHostSelected() || connection?.connectionAvailable?.read(reader) !== true || !integrated) { lastValue = undefined; + pending.set(undefined, undefined); + publish.cancel(); return; } if (connection !== lastConnection) { @@ -46,14 +70,17 @@ export function createGitHubPullRequestArtifactWorkspaceConfigurationSynchronize } const inspected = context ? configurationService.inspect<readonly string[]>(gitHubPullRequestMarkReadyIgnoredChecksSetting, { resource: context.resource }) : undefined; const ignoredChecks = inspected?.workspaceFolderValue ?? inspected?.workspaceValue; - const value = context && ignoredChecks !== undefined ? { chat: context.chat, workingDirectory: context.workingDirectory, ignoredChecks } : null; - if (!structuralEquals(value, lastValue)) { - lastValue = value; - connection.dispatch(session, { - type: ActionType.SessionConfigChanged, - config: { [settingsKey]: value }, - }); + const value: WorkspaceSettings = context && ignoredChecks !== undefined ? { chat: context.chat, workingDirectory: context.workingDirectory, ignoredChecks } : null; + const current = pending.read(undefined); + if (structuralEquals(value, lastValue)) { + pending.set(undefined, undefined); + publish.cancel(); + } else if (current?.connection !== connection || !structuralEquals(value, current.value)) { + // Each distinct value restarts the delay, so a value that keeps alternating is never published. + pending.set({ connection, value }, undefined); + publish.schedule(); } })); + return derived(reader => pending.read(reader) !== undefined); }; } diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/localAgentHostSessionsProviderRegistration.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/localAgentHostSessionsProviderRegistration.ts new file mode 100644 index 000000000000..1b37e4533ba2 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/localAgentHostSessionsProviderRegistration.ts @@ -0,0 +1,80 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IDisposable, DisposableMap, DisposableStore, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../../../base/common/observable.js'; +import { IInstantiationService, ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { AgentHostContribution } from '../../../../chat/browser/agentSessions/agentHost/agentHostChatContribution.js'; +import { IAgentHostSessionWorkingDirectoryResolver } from '../../../../chat/browser/agentSessions/agentHost/agentHostSessionWorkingDirectoryResolver.js'; +import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; +import { SessionStatus } from '../../../../../services/sessions/common/session.js'; +import { IAgentHostEnablementService } from '../../../../../../platform/agentHost/common/agentHostEnablementService.js'; +import { LocalAgentHostSessionsProvider } from './localAgentHostSessionsProvider.js'; + +/** + * Registers the {@link LocalAgentHostSessionsProvider} while the Agent Host is available in this runtime, with the working + * directory resolvers of its session types, until the returned disposable is disposed. + * + * {@link AgentHostContribution} handles all the heavy lifting — agent discovery, + * session handler registration, language model providers, customization harness — + * via {@link IChatSessionsService}. This only bridges the session + * listing and lifecycle to the {@link ISessionsProvidersService} layer used by + * the sessions UI. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerLocalAgentHostSessionsProvider(accessor: ServicesAccessor): IDisposable { + const agentHostEnablementService = accessor.get(IAgentHostEnablementService); + const instantiationService = accessor.get(IInstantiationService); + const sessionsProvidersService = accessor.get(ISessionsProvidersService); + const workingDirectoryResolver = accessor.get(IAgentHostSessionWorkingDirectoryResolver); + + const disposables = new DisposableStore(); + + const registration = disposables.add(new MutableDisposable<DisposableStore>()); + const initialize = () => { + if (registration.value) { + return; + } + const store = new DisposableStore(); + const provider = store.add(instantiationService.createInstance(LocalAgentHostSessionsProvider)); + store.add(sessionsProvidersService.registerProvider(provider)); + + const resolverRegistrations = store.add(new DisposableMap<string>()); + const registerResolvers = () => { + const sessionTypeIds = new Set(provider.sessionTypes.map(sessionType => `agent-host-${sessionType.id}`)); + for (const [sessionTypeId] of resolverRegistrations) { + if (!sessionTypeIds.has(sessionTypeId)) { + resolverRegistrations.deleteAndDispose(sessionTypeId); + } + } + + for (const sessionType of provider.sessionTypes) { + const resourceScheme = `agent-host-${sessionType.id}`; + if (resolverRegistrations.has(resourceScheme)) { + continue; + } + resolverRegistrations.set(resourceScheme, workingDirectoryResolver.registerResolver(resourceScheme, sessionResource => { + return provider.getSessionByResource(sessionResource)?.workspace.get()?.folders[0]?.workingDirectory; + }, sessionResource => { + return provider.getSessionByResource(sessionResource)?.status.get() === SessionStatus.Untitled; + })); + } + }; + registerResolvers(); + store.add(provider.onDidChangeSessionTypes(registerResolvers)); + registration.value = store; + }; + + disposables.add(autorun(reader => { + if (agentHostEnablementService.enabled.read(reader)) { + initialize(); + } else { + registration.clear(); + } + })); + return disposables; +} diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/media/agentHostSessionConfigPicker.css b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/media/agentHostSessionConfigPicker.css index f26f7356e38c..ad7a1c3f58bc 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/media/agentHostSessionConfigPicker.css +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/media/agentHostSessionConfigPicker.css @@ -81,3 +81,18 @@ .action-widget .actionList.sessions-chat-isolation-listed-changes .monaco-list-row.separator > span:not(:empty) { padding-left: 0; } + +/* Like the count after Branch, the label of the uncommitted files shares the color of modified files. */ +.action-widget .actionList.sessions-chat-isolation-listed-changes .monaco-list-row.separator > span:not(:empty) { + color: var(--vscode-gitDecoration-modifiedResourceForeground); +} + +/* A quiet pill, like Recommended in the permissions picker, for a recommendation the user already knows. */ +.action-widget .monaco-list-row.action.sessions-chat-config-secondary-badge .action-item-badge { + background-color: color-mix(in srgb, var(--vscode-foreground) 10%, transparent); + color: var(--vscode-descriptionForeground); +} + +.action-widget .monaco-list-row.action.sessions-chat-config-secondary-badge.focused .action-item-badge { + color: inherit; +} diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileAgentHostModePicker.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileAgentHostModePicker.ts index 1c8b1108117a..8a7c642b5db8 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileAgentHostModePicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileAgentHostModePicker.ts @@ -18,6 +18,7 @@ import { ISessionsProvidersService } from '../../../../browser/sessionsProviders import { ISessionChatSource } from '../../../../../../services/sessions/browser/sessionHost.js'; import { AgentHostModePicker } from '../agentHostModePicker.js'; import { createChatPhoneInputSessionContext } from '../../../../browser/chatPhoneInputContext.js'; +import { onUnexpectedError } from '../../../../../../../base/common/errors.js'; /** * Phone-aware variant of {@link AgentHostModePicker}. On phone-layout @@ -29,6 +30,7 @@ import { createChatPhoneInputSessionContext } from '../../../../browser/chatPhon * transitions. */ export class MobileAgentHostModePicker extends AgentHostModePicker { + private _phoneSheetOpen = false; constructor( source: ISessionChatSource, @@ -47,7 +49,7 @@ export class MobileAgentHostModePicker extends AgentHostModePicker { } protected override _showPicker(anchor = this._triggerElement, onHide?: () => void, listOptions?: IActionListOptions): boolean { - if (!anchor) { + if (!anchor || this._phoneSheetOpen) { return false; } // Guard applies to both the phone sheet and the desktop popover — @@ -56,10 +58,12 @@ export class MobileAgentHostModePicker extends AgentHostModePicker { return false; } if (this._phonePresenter.enabled.get()) { + this._phoneSheetOpen = true; this._phonePresenter.showCombinedModeAndModelSheet(anchor, { kind: 'session', + initialSection: 'mode', getSessionContext: () => createChatPhoneInputSessionContext(this._session.get(), this._chat.get()), - selectModel: modelIdentifier => { + selectModel: this._phonePresenter.supportsUnifiedConfiguration ? undefined : modelIdentifier => { const chatResource = this._chat.get()?.resource; const inputPart = chatResource ? this._chatWidgetService.getWidgetBySessionResource(chatResource)?.inputPart : undefined; const previousModelIdentifier = inputPart?.selectedLanguageModel.get()?.identifier; @@ -71,9 +75,12 @@ export class MobileAgentHostModePicker extends AgentHostModePicker { }, }) .finally(() => { - anchor.focus(); + this._phoneSheetOpen = false; + if (anchor.isConnected) { + anchor.focus(); + } onHide?.(); - }); + }).catch(onUnexpectedError); return true; } return super._showPicker(anchor, onHide, listOptions); diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.ts index ae44176c31fd..99fe2a88fb66 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/browser/mobile/mobileChatInputConfigPicker.ts @@ -97,6 +97,15 @@ class MobileChatInputConfigPicker extends Disposable { open: () => { void this._showSheet(); }, switchToModel: modelIdentifier => this._switchToModel(modelIdentifier), })); + this._register(autorun(reader => { + this._phonePresenter.enabled.read(reader); + if (this._phonePresenter.supportsUnifiedConfiguration) { + reader.store.add(this._phonePresenter.registerSessionModelPicker({ + getSessionContext: () => createChatPhoneInputSessionContext(this._session.read(undefined), this._chat.read(undefined)), + selectModel: identifier => this._switchToModel(identifier), + })); + } + })); // Re-render the trigger whenever the active session, its config, // its model, or the available language models change. The diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostArtifactIntegrations.test.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostArtifactIntegrations.test.ts index 86be9a46257a..ad9d0ddc5ba7 100644 --- a/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostArtifactIntegrations.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostArtifactIntegrations.test.ts @@ -8,12 +8,13 @@ import { DeferredPromise, timeout } from '../../../../../../../base/common/async import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, ImmortalReference, IReference } from '../../../../../../../base/common/lifecycle.js'; -import { constObservable, derived, IObservable, observableValue, waitForState } from '../../../../../../../base/common/observable.js'; +import { autorun, constObservable, derived, IObservable, observableValue, waitForState } from '../../../../../../../base/common/observable.js'; import { deepFreeze } from '../../../../../../../base/common/objects.js'; import { isEqual } from '../../../../../../../base/common/resources.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { mock, upcastPartial } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { runWithFakedTimers } from '../../../../../../../base/test/common/timeTravelScheduler.js'; import { IAgentConnection } from '../../../../../../../platform/agentHost/common/agentService.js'; import { IAgentSubscription } from '../../../../../../../platform/agentHost/common/state/agentSubscription.js'; import { ChatState, ComponentToState, RootState, ROOT_STATE_URI, SessionState, StateComponents } from '../../../../../../../platform/agentHost/common/state/sessionState.js'; @@ -39,7 +40,7 @@ import { IChatEntitlementService } from '../../../../../../services/chat/common/ import { IExtensionService } from '../../../../../../services/extensions/common/extensions.js'; import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; import { AgentHostArtifactIntegrations, createHostFacingArtifactAccess, IArtifactWorkspaceConfigurationContext, mapArtifactModelChats } from '../../browser/agentHostArtifactIntegrations.js'; -import { createGitHubPullRequestArtifactWorkspaceConfigurationSynchronizer } from '../../browser/githubPullRequestArtifactWorkspaceConfiguration.js'; +import { createGitHubPullRequestArtifactWorkspaceConfigurationSynchronizer, gitHubPullRequestArtifactWorkspaceSettingsPublishDelay } from '../../browser/githubPullRequestArtifactWorkspaceConfiguration.js'; import { createClientArtifactRuntime } from '../../../../browser/clientArtifactRuntime.js'; suite('Agent Host artifact chat mapping', () => { @@ -141,6 +142,19 @@ suite('Agent Host artifact chat mapping', () => { availability: f.model.snapshot.get().contributions[0].view.stateActions[0].chatAvailability, }, { snapshot: [undefined, replacement.toString(), undefined], page: [undefined, replacement.toString(), undefined], result: replacement.toString(), availability: { [replacement.toString()]: { enabled: false } } }); }); + + test('publishes a new snapshot only when a change to the chats changes its content', () => { + const f = fixture(); + const published: (string | undefined)[][] = []; + const listener = autorun(reader => { published.push(f.model.snapshot.read(reader).runs.map(run => run.chat)); }); + f.chats.set([...f.chats.get()], undefined); + f.chats.set([{ client: f.clients[0], backend: f.backend[0] }], undefined); + listener.dispose(); + assert.deepStrictEqual(published, [ + [f.clients[0].toString(), f.clients[1].toString(), undefined], + [f.clients[0].toString(), undefined, undefined], + ]); + }); }); suite('Agent Host host-facing artifact access', () => { @@ -498,7 +512,7 @@ suite('Agent Host artifact workspace settings', () => { }); } - test('mirrors only workspace overrides into artifact-scoped session configuration and resends after reconnect', async () => { + async function createWorkspaceSettingsFixture() { const { instantiation } = createInstantiation(store); let inspected: IConfigurationValue<readonly string[]> = { userValue: ['Global *'], workspaceValue: ['Workspace *'], workspaceFolderValue: ['Folder *'] }; const configuration = new class extends TestConfigurationService { @@ -546,27 +560,79 @@ suite('Agent Host artifact workspace settings', () => { createGitHubPullRequestArtifactWorkspaceConfigurationSynchronizer(configuration), )); integrations.setConnection(connection); - const workspace = observableValue<IArtifactWorkspaceConfigurationContext | undefined>('workspace', { - chat: 'chat', workingDirectory: 'file:///repo', resource: URI.file('/repo'), - }); - const reference = store.add(await integrations.acquireArtifact('session', 'pr', workspace)); - connected.set(false, undefined); - connected.set(true, undefined); - actions.fire({ channel: 'another-session', serverSeq: 1, origin: undefined, action: { type: ActionType.SessionConfigChanged, config: {}, replace: true } }); - actions.fire({ channel: 'session', serverSeq: 2, origin: undefined, action: { type: ActionType.SessionConfigChanged, config: {}, replace: true } }); - inspected = { userValue: ['Global *'] }; + const key = gitHubPullRequestArtifactWorkspaceSettingsKey('pr'); + return { + integrations, connected, actions, patches, + setInspected: (value: IConfigurationValue<readonly string[]>) => { inspected = value; }, + workspace: (workingDirectory: string) => observableValue<IArtifactWorkspaceConfigurationContext | undefined>('workspace', { chat: 'chat', workingDirectory, resource: URI.file('/repo') }), + patch: (workingDirectory: string | null) => ({ channel: 'session', config: { [key]: workingDirectory === null ? null : { chat: 'chat', workingDirectory, ignoredChecks: ['Folder *'] } } }), + replaceSessionConfig: (channel: string) => actions.fire({ channel, serverSeq: 1, origin: undefined, action: { type: ActionType.SessionConfigChanged, config: {}, replace: true } }), + settle: () => timeout(gitHubPullRequestArtifactWorkspaceSettingsPublishDelay), + }; + } + + test('mirrors only workspace overrides into artifact-scoped session configuration and resends after reconnect', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const f = await createWorkspaceSettingsFixture(); + const workspace = f.workspace('file:///repo'); + const reference = store.add(await f.integrations.acquireArtifact('session', 'pr', workspace)); + await f.settle(); + f.connected.set(false, undefined); + f.connected.set(true, undefined); + await f.settle(); + f.replaceSessionConfig('another-session'); + f.replaceSessionConfig('session'); + await f.settle(); + f.setInspected({ userValue: ['Global *'] }); workspace.set({ ...workspace.get()!, resource: URI.file('/another-workspace') }, undefined); + await f.settle(); reference.dispose(); workspace.set(undefined, undefined); - actions.fire({ channel: 'session', serverSeq: 3, origin: undefined, action: { type: ActionType.SessionConfigChanged, config: {}, replace: true } }); - const key = gitHubPullRequestArtifactWorkspaceSettingsKey('pr'); - assert.deepStrictEqual(patches, [ - { channel: 'session', config: { [key]: { chat: 'chat', workingDirectory: 'file:///repo', ignoredChecks: ['Folder *'] } } }, - { channel: 'session', config: { [key]: { chat: 'chat', workingDirectory: 'file:///repo', ignoredChecks: ['Folder *'] } } }, - { channel: 'session', config: { [key]: { chat: 'chat', workingDirectory: 'file:///repo', ignoredChecks: ['Folder *'] } } }, - { channel: 'session', config: { [key]: null } }, - ]); - }); + f.replaceSessionConfig('session'); + await f.settle(); + assert.deepStrictEqual(f.patches, [f.patch('file:///repo'), f.patch('file:///repo'), f.patch('file:///repo'), f.patch(null)]); + })); + + test('publishes one context for all live references to an artifact, from the most recently acquired one', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const f = await createWorkspaceSettingsFixture(); + const first = store.add(await f.integrations.acquireArtifact('session', 'pr', f.workspace('file:///worktree-a'))); + await f.settle(); + const second = store.add(await f.integrations.acquireArtifact('session', 'pr', f.workspace('file:///worktree-b'))); + await f.settle(); + f.replaceSessionConfig('session'); + await f.settle(); + second.dispose(); + await f.settle(); + first.dispose(); + f.replaceSessionConfig('session'); + await f.settle(); + assert.deepStrictEqual(f.patches, [f.patch('file:///worktree-a'), f.patch('file:///worktree-b'), f.patch('file:///worktree-b'), f.patch('file:///worktree-a')]); + })); + + test('publishes a workspace context only once it stops alternating', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const f = await createWorkspaceSettingsFixture(); + const workspace = f.workspace('file:///worktree-a'); + store.add(await f.integrations.acquireArtifact('session', 'pr', workspace)); + await f.settle(); + for (let i = 0; i < 20; i++) { + workspace.set({ ...workspace.get()!, workingDirectory: i % 2 ? 'file:///worktree-a' : 'file:///worktree-b' }, undefined); + await timeout(gitHubPullRequestArtifactWorkspaceSettingsPublishDelay / 10); + } + await f.settle(); + workspace.set({ ...workspace.get()!, workingDirectory: 'file:///worktree-b' }, undefined); + await f.settle(); + assert.deepStrictEqual(f.patches, [f.patch('file:///worktree-a'), f.patch('file:///worktree-b')]); + })); + + test('publishes a change still settling when its last reference is released, unless the connection is lost first', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const f = await createWorkspaceSettingsFixture(); + (await f.integrations.acquireArtifact('session', 'pr', f.workspace('file:///worktree-a'))).dispose(); + await f.settle(); + (await f.integrations.acquireArtifact('session', 'pr', f.workspace('file:///worktree-b'))).dispose(); + f.connected.set(false, undefined); + f.connected.set(true, undefined); + await f.settle(); + assert.deepStrictEqual(f.patches, [f.patch('file:///worktree-a')]); + })); for (const remoteAddress of [undefined, 'custom-host:opaque-address']) { test(`artifact sign-in uses the advertised resource and ${remoteAddress ? 'remote credential transform' : 'local authentication flow'}`, async () => { diff --git a/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostSessionConfigPickerContribution.test.ts b/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostSessionConfigPickerContribution.test.ts new file mode 100644 index 000000000000..6825dee189d0 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/providers/agentHost/test/browser/agentHostSessionConfigPickerContribution.test.ts @@ -0,0 +1,139 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Emitter, Event } from '../../../../../../../base/common/event.js'; +import { Disposable } from '../../../../../../../base/common/lifecycle.js'; +import { constObservable, IObservable, observableValue } from '../../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { IActionViewItemService } from '../../../../../../../platform/actions/browser/actionViewItemService.js'; +import { isIMenuItem, MenuRegistry } from '../../../../../../../platform/actions/common/actions.js'; +import { SessionConfigKey } from '../../../../../../../platform/agentHost/common/sessionConfigKeys.js'; +import { ResolveSessionConfigResult } from '../../../../../../../platform/agentHost/common/state/protocol/commands.js'; +import { IWorkbenchLayoutService } from '../../../../../../services/layout/browser/layoutService.js'; +import { ISessionHost, ISessionHostService } from '../../../../../../services/sessions/browser/sessionHost.js'; +import { IChat, ISession } from '../../../../../../services/sessions/common/session.js'; +import { workbenchInstantiationService } from '../../../../../../test/browser/workbenchTestServices.js'; +import { IChatPhoneInputPresenter } from '../../../../../chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { Menus } from '../../../../browser/menus.js'; +import { ISessionsProvidersService } from '../../../../browser/sessionsProvidersService.js'; +import { ISessionsService } from '../../../../browser/sessionsService.js'; +import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../../common/agentHostSessionsProvider.js'; +import { AgentHostSessionConfigPickerContribution } from '../../browser/agentHostSessionConfigPicker.js'; + +suite('AgentHostSessionConfigPickerContribution', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + const config: ResolveSessionConfigResult = { + schema: { + type: 'object', + properties: { + [SessionConfigKey.Isolation]: { type: 'string', title: 'Isolation', enum: ['folder', 'worktree'], default: 'folder' }, + [SessionConfigKey.Branch]: { type: 'string', title: 'Branch', enum: ['main'], default: 'main' }, + }, + }, + values: {}, + }; + + function sessionOf(sessionId: string): { session: ISession; chat: IChat } { + const resource = URI.parse(`agent-host-copilot:/${sessionId}`); + const chat = upcastPartial<IChat>({ resource: resource.with({ fragment: `chat-of-${sessionId}` }) }); + const mainChat = upcastPartial<IChat>({ resource }); + return { session: upcastPartial<ISession>({ sessionId, providerId: LOCAL_AGENT_HOST_PROVIDER_ID, resource, mainChat: constObservable(mainChat) }), chat }; + } + + function hostShowing(shown: IObservable<{ session: ISession; chat: IChat } | undefined>): ISessionHost { + return upcastPartial<ISessionHost>({ session: shown.map(value => value?.session), chat: shown.map(value => value?.chat) }); + } + + function setup(options: { panes?: readonly { session: ISession; chat: IChat }[] } = {}) { + const instantiationService = workbenchInstantiationService(undefined, store); + const configResources: string[] = []; + const provider = upcastPartial<IAgentHostSessionsProvider>({ + id: LOCAL_AGENT_HOST_PROVIDER_ID, + onDidChangeSessionConfig: new Emitter<string>().event, + getSessionConfig: (_sessionId, chat) => { + configResources.push(chat.toString()); + return config; + }, + getCreateSessionConfig: () => ({}), + }); + instantiationService.stub(ISessionsProvidersService, upcastPartial<ISessionsProvidersService>({ + onDidChangeProviders: Event.None, + getProviders: () => [provider], + getProvider: <T>() => provider as T, + })); + instantiationService.stub(ISessionsService, upcastPartial<ISessionsService>({ + slotPanes: constObservable((options.panes ?? []).map(pane => ({ session: constObservable(pane.session), chat: constObservable(pane.chat) }))) as unknown as ISessionsService['slotPanes'], + })); + const hosts = observableValue<readonly ISessionHost[]>('hosts', []); + instantiationService.stub(ISessionHostService, upcastPartial<ISessionHostService>({ hosts })); + instantiationService.stub(IActionViewItemService, upcastPartial<IActionViewItemService>({ register: () => Disposable.None })); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial<IWorkbenchLayoutService>({ mainContainer: document.createElement('div') })); + instantiationService.stub(IChatPhoneInputPresenter, upcastPartial<IChatPhoneInputPresenter>({})); + const contribution = store.add(instantiationService.createInstance(AgentHostSessionConfigPickerContribution)); + return { hosts, contribution, configResources }; + } + + function pickersOf(sessionId: string): string[] { + return MenuRegistry.getMenuItems(Menus.NewSessionRepositoryConfig) + .filter(isIMenuItem) + .filter(item => item.when?.serialize().includes(`'${sessionId}'`)) + .map(item => item.command.title as string) + .sort(); + } + + test('registers the repository pickers of the draft a chat window composer shows, with the chat it shows', () => { + const { hosts, configResources } = setup(); + const draft = sessionOf('chat-window-draft'); + hosts.set([hostShowing(constObservable(draft))], undefined); + + assert.deepStrictEqual({ pickers: pickersOf('chat-window-draft'), configResources: [...new Set(configResources)] }, { + pickers: ['Branch', 'Isolation'], + configResources: [draft.chat.resource.toString()], + }); + }); + + test('registers a session a pane and a host both show once', () => { + const shown = sessionOf('shared'); + const { hosts } = setup({ panes: [shown] }); + hosts.set([hostShowing(constObservable(shown))], undefined); + + assert.deepStrictEqual(pickersOf('shared'), ['Branch', 'Isolation']); + }); + + test('moves the pickers with the session a host shows and drops them with the host', () => { + const { hosts } = setup(); + const first = sessionOf('first'); + const second = sessionOf('second'); + const shown = observableValue<{ session: ISession; chat: IChat } | undefined>('shown', first); + hosts.set([hostShowing(shown)], undefined); + const initial = { first: pickersOf('first'), second: pickersOf('second') }; + + shown.set(second, undefined); + const switched = { first: pickersOf('first'), second: pickersOf('second') }; + + hosts.set([], undefined); + const removed = { first: pickersOf('first'), second: pickersOf('second') }; + + assert.deepStrictEqual({ initial, switched, removed }, { + initial: { first: ['Branch', 'Isolation'], second: [] }, + switched: { first: [], second: ['Branch', 'Isolation'] }, + removed: { first: [], second: [] }, + }); + }); + + test('drops the pickers when the contribution is disposed', () => { + const { hosts, contribution } = setup(); + hosts.set([hostShowing(constObservable(sessionOf('disposed')))], undefined); + const before = pickersOf('disposed'); + + contribution.dispose(); + + assert.deepStrictEqual({ before, after: pickersOf('disposed') }, { before: ['Branch', 'Isolation'], after: [] }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvider.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvider.ts index 9daf2d590647..7005adf72499 100644 --- a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvider.ts +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvider.ts @@ -43,6 +43,7 @@ import { ExtensionIdentifier } from '../../../../../../platform/extensions/commo import { IChatRequestVariableEntry } from '../../../../chat/common/attachments/chatVariableEntries.js'; import { localize } from '../../../../../../nls.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; import { ILabelService } from '../../../../../../platform/label/common/label.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; @@ -1085,6 +1086,9 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions readonly order = 0; get sessionTypes(): readonly ISessionType[] { + if (!this._cloudSessionsEnabled) { + return []; + } return this.providerMode === 'sandbox' ? [CopilotSandboxSessionType] : [CopilotCloudSessionType]; } @@ -1133,12 +1137,16 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions }>(); private readonly _localGitRepositoryResolutionStarted = new Set<string>(); + private get _cloudSessionsEnabled(): boolean { + return this.defaultAccountService.currentDefaultAccount?.entitlementsData?.cloud_sessions_enabled !== false; + } + get supportsLocalWorkspaces(): boolean { return this.providerMode !== 'sandbox'; } readonly automations: CloudAutomationStore | undefined; get supportsAutomationSessionConfiguration(): boolean { return this.providerMode === 'default' && this.automations?.enabled.get() === true; } get supportsQuickChats(): boolean { - return isCloudSandboxEnabled(this.configurationService) && !this.configurationService.getValue<boolean>(ChatAIDisabledSettingId); + return this._cloudSessionsEnabled && isCloudSandboxEnabled(this.configurationService) && !this.configurationService.getValue<boolean>(ChatAIDisabledSettingId); } constructor( @@ -1161,6 +1169,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions @IStorageService private readonly storageService: IStorageService, @ICloudSandboxDraftPreparationService private readonly draftPreparationService: ICloudSandboxDraftPreparationService, @ISessionRepositoryPicker private readonly sessionRepositoryPicker: ISessionRepositoryPicker, + @IDefaultAccountService private readonly defaultAccountService: IDefaultAccountService, ) { super(); @@ -1170,6 +1179,19 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } })); this._loadCreatedBySessions(); + let cloudSessionsEnabled = this._cloudSessionsEnabled; + const updateAvailability = () => { + if (this._store.isDisposed || cloudSessionsEnabled === this._cloudSessionsEnabled) { + return; + } + cloudSessionsEnabled = this._cloudSessionsEnabled; + this._onDidChangeSessionTypes.fire(); + this._onDidChangeCapabilities.fire(); + }; + this._register(this.defaultAccountService.onDidChangeDefaultAccount(updateAvailability)); + void this.defaultAccountService.getDefaultAccount().then(updateAvailability, error => { + this.logService.error('[CopilotChatSessionsProvider] Failed to initialize account:', error); + }); if (providerMode === 'default') { this.automations = this._register(this.instantiationService.createInstance(CloudAutomationStore, this.id, CopilotCloudSessionType.id, async uri => { if (uri.scheme === GITHUB_REMOTE_FILE_SCHEME) { @@ -1309,6 +1331,9 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions // -- Sessions -- getSessionTypes(workspaceUri: URI): ISessionType[] { + if (!this._cloudSessionsEnabled) { + return []; + } if (this.providerMode === 'sandbox') { return this.resolveWorkspace(workspaceUri) ? [CopilotSandboxSessionType] : []; } @@ -1460,7 +1485,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions prepareNewSessionWhileComposing(sessionId: string): void { const session = this._newSessions.get(sessionId); - if (!session || session.isNewSessionRequestInProgress.get()) { + if (!session || session.isNewSessionRequestInProgress.get() || !this._cloudSessionsEnabled) { return; } const repoNwo = session.repoNwo; @@ -1472,6 +1497,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } private _createDraftSession(workspaceUri: URI | undefined, sessionTypeId: string, options?: ISessionsProviderCreateSessionOptions): ISession { + this._assertCloudSessionsEnabled(); if (this.providerMode === 'sandbox') { if (!isCloudSandboxEnabled(this.configurationService) || this.configurationService.getValue<boolean>(ChatAIDisabledSettingId)) { throw new Error(localize('sandbox.disabled', "GitHub sandbox sessions are not enabled.")); @@ -1576,6 +1602,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } createQuickChat(sessionTypeId: string, options?: ISessionsProviderCreateSessionOptions): ISession { + this._assertCloudSessionsEnabled(); if (!this.supportsQuickChats) { throw new Error(localize('sandbox.disabled', "GitHub sandbox sessions are not enabled.")); } @@ -1913,6 +1940,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } async prepareNewSession(sessionId: string, token: CancellationToken, query: string): Promise<IPreparedNewSession> { + this._assertCloudSessionsEnabled(); const session = this._newSessions.get(sessionId); if (!session) { throw new Error(`Cannot prepare unknown new session '${sessionId}'.`); @@ -1978,6 +2006,12 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } } + private _assertCloudSessionsEnabled(): void { + if (!this._cloudSessionsEnabled) { + throw new Error(localize('cloudSessions.unavailable', "Cloud session creation is not available for your account.")); + } + } + private _validateSandboxSession(session: RemoteNewSession): void { if (!this.supportsQuickChats) { throw new Error(localize('sandbox.unavailable', "GitHub sandbox creation is no longer available. Enable the feature to try again.")); @@ -2262,6 +2296,7 @@ export class CopilotChatSessionsProvider extends Disposable implements ISessions } const newSession = this._newSessions.get(sessionId); if (newSession) { + this._assertCloudSessionsEnabled(); if (!this.uriIdentityService.extUri.isEqual(newSession.mainChat.get().resource, chatResource)) { throw new Error('Chat resource does not match the main chat of the current new session'); } diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvidersRegistration.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvidersRegistration.ts new file mode 100644 index 000000000000..c63c0acd41ca --- /dev/null +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotChatSessionsProvidersRegistration.ts @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IInstantiationService, ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { IDisposable, DisposableStore, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { isWeb } from '../../../../../../base/common/platform.js'; +import { CopilotChatSessionsProvider } from './copilotChatSessionsProvider.js'; +import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { CloudSandboxEnabledSettingId, isCloudSandboxEnabled } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; +import { RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; +import { IChatEntitlementService } from '../../../../../services/chat/common/chatEntitlementService.js'; + +/** + * Registers the {@link CopilotChatSessionsProvider} as a sessions provider, and on the web also its cloud sandbox provider + * while cloud sandboxes are enabled, until the returned disposable is disposed. + * + * The provider only surfaces Copilot Cloud sessions from the Copilot extension; + * local Copilot CLI sessions are owned by the agent host providers. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerCopilotChatSessionsProviders(accessor: ServicesAccessor): IDisposable { + const instantiationService = accessor.get(IInstantiationService); + const sessionsProvidersService = accessor.get(ISessionsProvidersService); + const configurationService = accessor.get(IConfigurationService); + const chatEntitlementService = accessor.get(IChatEntitlementService); + + const disposables = new DisposableStore(); + + const provider = disposables.add(instantiationService.createInstance(CopilotChatSessionsProvider, 'default')); + disposables.add(sessionsProvidersService.registerProvider(provider)); + + if (isWeb) { + const sandboxRegistration = disposables.add(new MutableDisposable<DisposableStore>()); + const updateSandboxRegistration = () => { + if (!isCloudSandboxEnabled(configurationService) || chatEntitlementService.sentiment.hidden) { + sandboxRegistration.clear(); + } else if (!sandboxRegistration.value) { + const store = new DisposableStore(); + sandboxRegistration.value = store; + const sandboxProvider = store.add(instantiationService.createInstance(CopilotChatSessionsProvider, 'sandbox')); + store.add(sessionsProvidersService.registerProvider(sandboxProvider)); + } + }; + disposables.add(configurationService.onDidChangeConfiguration(event => { + if (event.affectsConfiguration(CloudSandboxEnabledSettingId) || event.affectsConfiguration(RemoteAgentHostsEnabledSettingId)) { + updateSandboxRegistration(); + } + })); + disposables.add(chatEntitlementService.onDidChangeSentiment(updateSandboxRegistration)); + updateSandboxRegistration(); + } + return disposables; +} diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotSandboxPickers.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotSandboxPickers.ts new file mode 100644 index 000000000000..16dc71e1ace6 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/copilotSandboxPickers.ts @@ -0,0 +1,79 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Disposable, DisposableStore, IDisposable } from '../../../../../../base/common/lifecycle.js'; +import { localize2 } from '../../../../../../nls.js'; +import { IActionViewItemService } from '../../../../../../platform/actions/browser/actionViewItemService.js'; +import { Action2, registerAction2 } from '../../../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../../../platform/contextkey/common/contextkey.js'; +import { IWorkbenchContribution } from '../../../../../common/contributions.js'; +import { Menus } from '../../../browser/menus.js'; +import { SessionProviderIdContext, IsNewChatSessionContext } from '../../../common/contextkeys.js'; +import { CLOUD_SANDBOX_CREATION_PROVIDER_ID, COPILOT_PROVIDER_ID } from '../common/copilotChatSessions.js'; +import { ChatContextKeys } from '../../../../chat/common/actions/chatContextKeys.js'; +import { ISessionHost } from '../../../../../services/sessions/browser/sessionHost.js'; +import { AgentHostModePicker } from '../../agentHost/browser/agentHostModePicker.js'; +import { AgentHostPermissionPickerDelegate } from '../../agentHost/browser/agentHostPermissionPickerDelegate.js'; +import { PickerActionViewItem } from '../../agentHost/browser/agentHostSessionConfigPicker.js'; +import { MobilePermissionPicker } from './mobilePermissionPicker.js'; +import { MobileAgentHostModePicker } from '../../agentHost/browser/mobile/mobileAgentHostModePicker.js'; +import { isPhoneLayout } from '../../../../../browser/parts/sessions/mobileLayout.js'; +import { IWorkbenchLayoutService } from '../../../../../services/layout/browser/layoutService.js'; + +const IsActiveCopilotChatSessionProvider = ContextKeyExpr.equals(SessionProviderIdContext.key, COPILOT_PROVIDER_ID); + +// -- Actions -- + +const IsNewCloudSession = ContextKeyExpr.and(IsNewChatSessionContext, ChatContextKeys.enabled, ContextKeyExpr.or( + IsActiveCopilotChatSessionProvider, + SessionProviderIdContext.isEqualTo(CLOUD_SANDBOX_CREATION_PROVIDER_ID), +)); + +// -- Action View Item Registrations -- + +export class CopilotPickerActionViewItemContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.copilotPickerActionViewItems'; + + constructor( + @IActionViewItemService actionViewItemService: IActionViewItemService, + @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, + ) { + super(); + this._register(actionViewItemService.register(Menus.NewSessionControl, 'sessions.sandbox.modePicker', (_action, _options, scopedInstantiationService) => { + const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); + return new PickerActionViewItem(scopedInstantiationService.createInstance(isPhoneLayout(layoutService) ? MobileAgentHostModePicker : AgentHostModePicker, host)); + })); + this._register(actionViewItemService.register(Menus.NewSessionControl, 'sessions.sandbox.approvalPicker', (_action, _options, scopedInstantiationService) => { + const host = scopedInstantiationService.invokeFunction(accessor => accessor.get(ISessionHost)); + const delegate = scopedInstantiationService.createInstance(AgentHostPermissionPickerDelegate, host); + return new PickerActionViewItem(scopedInstantiationService.createInstance(MobilePermissionPicker, delegate), delegate, true); + })); + } +} + +/** + * Registers the mode and approvals pickers of new Copilot Cloud and sandbox sessions, until the returned disposable is disposed. + * + * Call it once per window, from the one module or contribution that owns these registrations: its registrations are + * global, and registering them twice throws or duplicates them. + */ +export function registerCopilotSandboxPickerActions(): IDisposable { + const store = new DisposableStore(); + + for (const [id, title, order] of [ + ['sessions.sandbox.modePicker', localize2('sandbox.modePicker', "Agent Mode"), 0], + ['sessions.sandbox.approvalPicker', localize2('sandbox.approvalPicker', "Approvals"), 1], + ] as const) { + store.add(registerAction2(class extends Action2 { + constructor() { + super({ id, title, menu: [{ id: Menus.NewSessionControl, group: 'navigation', order, when: IsNewCloudSession }] }); + } + override run(): void { } + })); + } + + return store; +} diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/mobilePermissionPicker.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/mobilePermissionPicker.ts index 48c4b782e99a..1d6cb0ef0d55 100644 --- a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/mobilePermissionPicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/mobilePermissionPicker.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { URI } from '../../../../../../base/common/uri.js'; +import { onUnexpectedError } from '../../../../../../base/common/errors.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { localize } from '../../../../../../nls.js'; import { IActionWidgetService } from '../../../../../../platform/actionWidget/browser/actionWidget.js'; @@ -17,6 +18,9 @@ import { ITelemetryService } from '../../../../../../platform/telemetry/common/t import { IWorkbenchLayoutService } from '../../../../../services/layout/browser/layoutService.js'; import { ChatPermissionLevel } from '../../../../chat/common/constants.js'; import { getPermissionLevelBadge } from '../../../../chat/browser/agentSessions/agentHost/agentHostModePickerPresentation.js'; +import { IChatPhoneInputPresenter } from '../../../../chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { ISessionHost } from '../../../../../services/sessions/browser/sessionHost.js'; +import { createChatPhoneInputSessionContext } from '../../../browser/chatPhoneInputContext.js'; import { IPermissionPickerDelegate, PermissionPicker } from './permissionPicker.js'; import { isPhoneLayout } from '../../../../../browser/parts/sessions/mobileLayout.js'; import { IMobilePickerSheetItem, showMobilePickerSheet } from '../../../browser/mobile/mobilePickerSheet.js'; @@ -33,6 +37,7 @@ const LEARN_MORE_ID = 'learn-more'; * (e.g. user resized past the breakpoint after the picker rendered). */ export class MobilePermissionPicker extends PermissionPicker { + private _configurationOpen = false; constructor( _delegate: IPermissionPickerDelegate, @@ -45,6 +50,8 @@ export class MobilePermissionPicker extends PermissionPicker { @IHoverService hoverService: IHoverService, @IWorkbenchLayoutService private readonly _layoutService: IWorkbenchLayoutService, @IAgentHostEnablementService agentHostEnablementService: IAgentHostEnablementService, + @IChatPhoneInputPresenter private readonly _phonePresenter: IChatPhoneInputPresenter, + @ISessionHost private readonly _sessionHost: ISessionHost, ) { super(_delegate, actionWidgetService, configurationService, dialogService, openerService, storageService, telemetryService, hoverService, agentHostEnablementService); } @@ -54,7 +61,24 @@ export class MobilePermissionPicker extends PermissionPicker { } protected override _showPicker(): void { - if (!this._triggerElement || this.actionWidgetService.isVisible || this._isResolving()) { + if (!this._triggerElement || this._configurationOpen || this.actionWidgetService.isVisible || this._isResolving()) { + return; + } + if (this._phonePresenter.supportsUnifiedConfiguration) { + const trigger = this._triggerElement; + this._configurationOpen = true; + trigger.setAttribute('aria-expanded', 'true'); + void this._phonePresenter.showCombinedModeAndModelSheet(trigger, { + kind: 'session', + getSessionContext: () => createChatPhoneInputSessionContext(this._sessionHost.session.get(), this._sessionHost.chat.get()), + initialSection: 'permissions', + }).finally(() => { + this._configurationOpen = false; + trigger.setAttribute('aria-expanded', 'false'); + if (trigger.isConnected) { + trigger.focus(); + } + }).catch(onUnexpectedError); return; } if (!isPhoneLayout(this._layoutService)) { diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/permissionPicker.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/permissionPicker.ts index a1b5936574d9..f28c7c19041f 100644 --- a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/permissionPicker.ts +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/browser/permissionPicker.ts @@ -98,7 +98,7 @@ export interface IPermissionPickerDelegate { readonly sandboxSelectionRejected?: IObservable<boolean>; readonly sandboxDevContainer?: IObservable<boolean>; readonly sandboxDevContainerSupported?: IObservable<boolean | undefined>; - setSandboxEnabled?(enabled: boolean): void; + setSandboxEnabled?(enabled: boolean): void | Promise<void>; readonly managedSandboxEnforced?: IObservable<boolean>; readonly managedSandboxAllowsBypass?: IObservable<boolean>; readonly sandboxToggleConfigurationKeys?: readonly string[]; diff --git a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/test/browser/permissionPicker.test.ts b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/test/browser/permissionPicker.test.ts index 0c79755457ee..a79db570e4f5 100644 --- a/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/test/browser/permissionPicker.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/copilotChatSessions/test/browser/permissionPicker.test.ts @@ -40,6 +40,8 @@ import { DEFAULT_PERMISSION_LEVELS, getPermissionLevelMeta, IPermissionPickerDel import { IUnavailablePermissionLevel } from '../../../../../chat/browser/agentSessions/agentHost/agentHostModePickerPresentation.js'; import { MobilePermissionPicker } from '../../browser/mobilePermissionPicker.js'; import { PickerActionViewItem } from '../../../agentHost/browser/agentHostSessionConfigPicker.js'; +import { IChatPhoneInputPresenter } from '../../../../../chat/browser/widget/input/chatPhoneInputPresenter.js'; +import { ISessionHost } from '../../../../../../services/sessions/browser/sessionHost.js'; const POLICY_DESCRIPTION = '$(briefcase) Disabled by your organization'; const POLICY_HOVER = 'Your organization doesn\'t allow this permission level. Contact your administrator.'; @@ -113,6 +115,8 @@ suite('Copilot PermissionPicker', () => { override readonly mainContainer = container; }(), unmanagedEnablementService, + new class extends mock<IChatPhoneInputPresenter>() { }(), + new class extends mock<ISessionHost>() { }(), )); picker.render(container); picker.showPicker(); @@ -378,7 +382,7 @@ suite('Copilot PermissionPicker', () => { getSandboxToggleProvider: () => 'copilotcli', getSandboxToggleSettingId: () => sandboxSettingId, sandboxEnabled, - setSandboxEnabled: enabled => writes.push({ session: 'test-session', enabled }), + setSandboxEnabled: enabled => { writes.push({ session: 'test-session', enabled }); }, managedSandboxEnforced, }, actionWidgetService, @@ -584,7 +588,7 @@ suite('Copilot PermissionPicker', () => { sandboxEnabled: constObservable(requestedOn), sandboxDevContainer, managedSandboxEnforced: constObservable(managed), - setSandboxEnabled: value => writes.push(value), + setSandboxEnabled: value => { writes.push(value); }, }, actionWidget, configuration, new TestDialogService(), NullOpenerService, store.add(new TestStorageService()), NullTelemetryService, NullHoverService, unmanagedEnablementService)); const container = dom.append(document.body, dom.$('div')); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md index 6c3fc265758a..817bf8e985d8 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/REMOTE_AGENT_HOST_SESSIONS_PROVIDER.md @@ -30,7 +30,7 @@ Kind-specific contributions create and register one provider for each reusable r Opening the desktop Agents Window from an SSH, WSL, or Tunnel editor window also registers hosts. The provider-neutral window-opening handoff passes the editor's remote authority and folder path to `IRemoteWorkspaceHandoffService` ([remoteWorkspaceHandoff.ts](../../../../../sessions/common/remoteWorkspaceHandoff.ts)), which this contribution implements. It matches an already registered host, or registers the host with the same stores as Remotes management, returns the folder in that provider's `vscode-agent-host` URI space, and then reveals the provider and starts a user-initiated connection. An unregistered tunnel is looked up with each signed-in account; when none lists it and an account needs to sign in first, the handoff explains why and, once the user confirms, signs in with that account and looks again. A registered tunnel whose account is signed out gets the same explanation and sign-in before the handoff connects it, since the connection would otherwise fail or start an unexplained sign-in. Dev Containers on such hosts resolve to the source folder on that host, including WSL sources, which Dev Containers identifies by UNC path rather than a parent authority. Other remotes are not mapped; the handoff starts without a workspace instead of falling back to an unrelated local folder. -Sessions move between tunnel editor windows and the Agents Window in both directions. `code tunnel` runs one agent host and bridges its VS Code servers to it, so both windows use the same host. The editor window reaches it as its own agent host and names its sessions with the local `agent-host-<provider>` scheme, while the Agents Window names them `remote-<authority>-<provider>` after its connection to the host. Revealing an editor window's session therefore also passes the editor's remote authority: the handoff resolves the host as for a folder and reports whether its connection succeeds, and the Agents Window opens the session under its own connection's scheme. Opening an Agents Window session in its tunnel's editor window maps it back to the local scheme. SSH, WSL, and Dev Container editor windows instead use an agent host that their VS Code server starts, with a session registry separate from the agent host the Agents Window starts, so sessions do not move between those windows. Likewise, a tunnel's protocol gateway can select the agent host of an editor on the tunnel's machine for the Agents Window, which then does not share the host of the tunnel's editor windows. In these cases both directions explain this instead of failing silently, and an editor window's session reveal falls back to opening that window's folder. +Sessions move between SSH, WSL, and tunnel editor windows and the Agents Window when both reach the same agent host. The editor window names its sessions with the local `agent-host-<provider>` scheme, while the Agents Window uses `remote-<authority>-<provider>`. Revealing an editor window's session passes its remote authority so the handoff can resolve and connect the host before translating the scheme. Opening an Agents Window session in the editor translates it back; this also works for registered Dev Container connections. SSH editor windows pass the host's stored location preference to their VS Code server, which selects an endpoint with the same rule as the Agents Window's SSH connection, so an SSH connection to an editor-owned endpoint is shared when that preference is `editor`. Location preferences are application-scoped, machine-local state shared by desktop windows and apply on the next connection. Tunnel editor windows are named by label and cannot look up the preference, so a tunnel gateway that selects an editor-owned endpoint does not share the editor window's host. When the hosts differ, both handoff directions explain the mismatch and open the folder instead. Dev Container editor-to-Agents session handoff remains unsupported because the host resolver does not resolve container authorities; it silently falls back to the source workspace when available, without attempting to open the container session on the source host. Agent discovery is dynamic. Changes to a host's advertised agents update the provider's session types without recreating the provider. diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/devContainerAgentHostService.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/devContainerAgentHostService.ts index a612cb9a5806..a2b288fba990 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/devContainerAgentHostService.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/devContainerAgentHostService.ts @@ -261,26 +261,6 @@ export class DevContainerAgentHostService extends Disposable implements IDevCont return this._connector?.isAvailable(workspaceUri) ?? Promise.resolve(false); } - getWorkspaces(): readonly { readonly workspaceUri: URI; readonly name: string }[] { - return [...this._storedConnections.values()].map(connection => ({ - workspaceUri: URI.parse(connection.workspaceUri), - name: connection.name, - })); - } - - addWorkspace(workspaceUri: URI, name: string): void { - this._ensureProvider(workspaceUri, name); - this._storeConnection(workspaceUri, name); - this._onDidChangeAvailability.fire(); - } - - async removeWorkspace(workspaceUri: URI): Promise<void> { - await this.disconnect(workspaceUri); - const key = getComparisonKey(workspaceUri); - this._removeStoredConnection(key); - this._removeProvider(key); - } - getSandboxSupported(workspaceUri: URI): boolean | undefined { return this._knownSandboxSupport.get(getComparisonKey(workspaceUri)); } diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/media/remotesWidget.css b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/media/remotesWidget.css index 21f4f6b87d71..c31bc7fe2c89 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/media/remotesWidget.css +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/media/remotesWidget.css @@ -167,13 +167,24 @@ .remotes-widget .remotes-name, .remotes-widget .remotes-empty-description, -.remotes-widget .remotes-connection-state { +.remotes-widget .remotes-connection-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.remotes-widget .remotes-connection-state { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size40); + min-width: 0; +} + +.remotes-widget .remotes-connection-icon { + flex-shrink: 0; +} + .remotes-widget .remotes-name-content { display: flex; flex-direction: column; @@ -215,6 +226,16 @@ color: var(--vscode-descriptionForeground); } +.remotes-widget .remotes-github-environment { + display: flex; + flex-shrink: 0; + color: var(--vscode-descriptionForeground); +} + +.remotes-widget .remotes-github-environment.remotes-github-environment-error { + color: var(--vscode-editorWarning-foreground); +} + .remotes-widget .remotes-gutter-column, .remotes-widget .remotes-actions-column { padding-inline: var(--vscode-spacing-size40); @@ -277,10 +298,12 @@ } .remotes-widget .remotes-group-count[hidden], +.remotes-widget .remotes-github-environment[hidden], .remotes-widget .remotes-group-progress[hidden], .remotes-widget .remotes-empty-signin[hidden], .remotes-widget .remotes-signin-progress[hidden], .remotes-widget .remotes-refresh-warning[hidden], +.remotes-widget .remotes-connection-icon[hidden], .remotes-widget .remotes-connection-warning[hidden], .remotes-widget .remotes-empty-description[hidden], .remotes-widget .remotes-empty-actions[hidden] { diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/missionControlAgentHostContribution.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/missionControlAgentHostContribution.ts index 4aeff91958f3..cb6f32e0221a 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/missionControlAgentHostContribution.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/missionControlAgentHostContribution.ts @@ -14,7 +14,7 @@ import { IInstantiationService } from '../../../../../../platform/instantiation/ import { INotificationService } from '../../../../../../platform/notification/common/notification.js'; import { cloudSandboxAddress, cloudSandboxEnvironmentId } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { IMissionControlEnvironmentService, IMissionControlSharingService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { IMissionControlEnvironmentService, IMissionControlSharingService, IRemoteGitHubEnvironmentSharingService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { IRemoteAgentHostService, RemoteAgentHostAutoConnectSettingId, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId, type IRemoteAgentHostEntry } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../../platform/storage/common/storage.js'; @@ -49,6 +49,7 @@ export class MissionControlAgentHostContribution extends EntryDrivenProviderCont @IMissionControlSharingService sharingService: IMissionControlSharingService, @IStorageService private readonly _storageService: IStorageService, @IAgentHostConnectionsService private readonly _agentHostConnectionsService: IAgentHostConnectionsService, + @IRemoteGitHubEnvironmentSharingService private readonly _remoteSharing: IRemoteGitHubEnvironmentSharingService, ) { super(remoteAgentHostService, configurationService, instantiationService, sessionsProvidersService, notificationService); const updateProjects = () => sharingService.setProjectFolders(recentWorkspacesService @@ -68,7 +69,9 @@ export class MissionControlAgentHostContribution extends EntryDrivenProviderCont })); this._register(autorun(reader => { this._inventory.hosts.read(reader); + this._inventory.discoveredOnlineHostIds.read(reader); this._inventory.ownEnvironmentId.read(reader); + this._remoteSharing.environmentIds.read(reader); this._reconcile(); this._requestAutoConnections(); })); @@ -118,9 +121,11 @@ export class MissionControlAgentHostContribution extends EntryDrivenProviderCont return; } const ownEnvironmentId = this._inventory.ownEnvironmentId.get(); + const discoveredOnlineHostIds = this._inventory.discoveredOnlineHostIds.get(); + const sharedRemoteEnvironmentIds = this._remoteSharing.environmentIds.get(); for (const host of this._inventory.hosts.get()) { const provider = this._providerInstances.get(cloudSandboxAddress(host.id)); - if (host.id === ownEnvironmentId || host.status !== 'online' || !provider + if (host.id === ownEnvironmentId || sharedRemoteEnvironmentIds.has(host.id) || host.status !== 'online' || !discoveredOnlineHostIds.has(host.id) || !provider || !this.isWebPlatform && !this._storageService.getBoolean(this._previouslyConnectedKey(host.id, account), StorageScope.PROFILE, false) || this._storageService.getBoolean(this._autoConnectSuppressionKey(host.id, account), StorageScope.PROFILE, false) || !RemoteAgentHostConnectionStatus.isDisconnected(provider.connectionStatus.get())) { @@ -259,8 +264,9 @@ export class MissionControlAgentHostContribution extends EntryDrivenProviderCont }, sessionCacheKey: `missionControl.userLocalSessions.v1.${encodeURIComponent(this._profileService.currentProfile.id)}.${encodeURIComponent(account)}.${id}`, readOnlyWhenDisconnected: true, - // This computer's own registration runs sessions directly as This Computer. + // This computer's own registration runs sessions directly as This Computer, and remotes shared from here are listed by their direct connections. isVisibleInEnvironmentPicker: derived(this, reader => this._inventory.ownEnvironmentId.read(reader) !== id + && !this._remoteSharing.environmentIds.read(reader).has(id) && this._inventory.hosts.read(reader).some(host => host.id === id && host.status === 'online')), localRegistration: derived(this, reader => this._inventory.ownEnvironmentId.read(reader) === id ? 'githubEnvironment' : undefined), pickerVisibilityKey: getRemoteAgentHostPickerKey(cloudSandboxAddress(id), account), diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesModel.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesModel.ts index a3151cd375ff..fe53d8d15fb5 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesModel.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesModel.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { raceTimeout } from '../../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Disposable, IDisposable } from '../../../../../../base/common/lifecycle.js'; @@ -10,7 +11,7 @@ import { autorun, IObservable, IReader, observableSignalFromEvent, observableVal import { isWindows, OperatingSystem } from '../../../../../../base/common/platform.js'; import { localize } from '../../../../../../nls.js'; import { cloudSandboxAddress } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; -import { IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlHost } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlHost, IRemoteGitHubEnvironmentShare, IRemoteGitHubEnvironmentSharingService } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { addSSHRemoteAgentHostEntry, getEntryAddress, IRemoteAgentHostEntry, IRemoteAgentHostService, IRemoteAgentHostSSHConnection, readSSHRemoteAgentHostEntries, removeSSHRemoteAgentHostEntry, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { computeSSHConnectionKey, ISSHRemoteAgentHostService } from '../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { isTunnelHosted, ITunnelAgentHostService, ITunnelInfo, TUNNEL_ADDRESS_PREFIX, TUNNEL_MIN_PROTOCOL_VERSION, TunnelAuthenticationRequiredError } from '../../../../../../platform/agentHost/common/tunnelAgentHost.js'; @@ -53,6 +54,10 @@ export interface ICustomizationRemote { readonly unavailableReason?: string; readonly hidden?: boolean; readonly pickerUnavailableReason?: string; + /** Whether this remote's agent host can be shared as a GitHub environment now. */ + readonly canShareAsGitHubEnvironment?: boolean; + /** Present while this remote's agent host is, or is being, shared as a GitHub environment. */ + readonly gitHubEnvironment?: IRemoteGitHubEnvironmentShare; } export type IRemoteRefreshProgress = @@ -71,6 +76,7 @@ export interface IRemotesModel extends IDisposable { copyAddress(id: string): Promise<void>; changePreferredAgentLocation(id: string): Promise<void>; updateServer(id: string): Promise<void>; + setSharedAsGitHubEnvironment(id: string, shared: boolean): Promise<void>; deleteTunnel(id: string): Promise<void>; deleteSSHHost(id: string): Promise<void>; remove(id: string): Promise<void>; @@ -127,6 +133,7 @@ export class RemotesModel extends Disposable implements IRemotesModel { @IProgressService private readonly progressService: IProgressService, @IProductService private readonly productService: IProductService, @IRemoteTunnelService remoteTunnelService: IRemoteTunnelService, + @IRemoteGitHubEnvironmentSharingService private readonly remoteSharing: IRemoteGitHubEnvironmentSharingService, ) { super(); this.pickerVisibility = this._register(new RemoteAgentHostPickerVisibility(storageService)); @@ -138,6 +145,10 @@ export class RemotesModel extends Disposable implements IRemotesModel { this._register(autorun(reader => { providersChanged.read(reader); environmentAvailabilityService.available.read(reader); + // Read unconditionally: `update` only reads them while GitHub environments are enabled. + remoteSharing.shareable.read(reader); + remoteSharing.shares.read(reader); + remoteSharing.environmentIds.read(reader); for (const provider of providersService.getProviders().filter(isAgentHostProvider)) { provider.localRegistration?.read(reader); } @@ -335,6 +346,27 @@ export class RemotesModel extends Disposable implements IRemotesModel { await upgradeRemoteHost(provider, status.vscodeUpgradeMethod, this.remoteAgentHostService, this.notificationService, this.progressService); } + async setSharedAsGitHubEnvironment(id: string, shared: boolean): Promise<void> { + const target = this.targets.get(id); + const remote = this._remotes.get().find(remote => remote.id === id); + if (!this.enabled || this._store.isDisposed || !remote || !target || target.kind === 'environment' || remote.gitHubEnvironment?.state === 'unavailable' + || (shared ? !remote.canShareAsGitHubEnvironment : !remote.gitHubEnvironment)) { + throw new Error(localize('remotes.unavailable', "This remote is no longer available.")); + } + await this.remoteSharing.setShared(id, shared); + } + + /** + * Stops sharing a remote before it is removed, while it can still withdraw its registration. + * Bounded so that an unresponsive remote cannot block removal; the service retries a failed withdrawal. + */ + private async unshareBeforeRemoval(id: string): Promise<void> { + const share = this.remoteSharing.shares.get().get(id); + if (share && share.state !== 'unavailable') { + await raceTimeout(this.remoteSharing.setShared(id, false), 5000); + } + } + async rename(id: string): Promise<void> { const remote = this._remotes.get().find(remote => remote.id === id); if (!remote || !this.enabled) { @@ -389,6 +421,7 @@ export class RemotesModel extends Disposable implements IRemotesModel { if (!provider) { throw new Error(localize('remotes.providerUnavailable', "The remote is not ready to be removed. Try again.")); } + await this.unshareBeforeRemoval(id); await removeRemoteHost(provider, this.remoteAgentHostService, this.configurationService); } this.targets.delete(id); @@ -413,6 +446,7 @@ export class RemotesModel extends Disposable implements IRemotesModel { throw new CancellationError(); } this.checkTunnelDeletion(current.tunnel); + await this.unshareBeforeRemoval(id); await this.tunnelService.deleteTunnel(current.tunnel, current.authProvider); this.tunnelDiscoveryVersion++; this.targets.delete(id); @@ -437,6 +471,7 @@ export class RemotesModel extends Disposable implements IRemotesModel { if (sshConnectionKey(current) !== sshConnectionKey(connection)) { throw new CancellationError(); } + await this.unshareBeforeRemoval(id); removeSSHRemoteAgentHostEntry(this.storageService, id); this.sshDiscoveryVersion++; try { @@ -604,6 +639,10 @@ export class RemotesModel extends Disposable implements IRemotesModel { const tunnels = this.tunnelService.getCachedTunnels().filter(tunnel => !this.tunnelService.isTunnelDismissed(tunnel.tunnelId)); const environments = this.environmentService.hosts.read(reader); const environmentsEnabled = this.enabled && this.environmentService.enabled; + const shareable = environmentsEnabled ? this.remoteSharing.shareable.read(reader) : new Set<string>(); + const shares = environmentsEnabled ? this.remoteSharing.shares.read(reader) : new Map<string, IRemoteGitHubEnvironmentShare>(); + // Remotes this client shares as GitHub environments are already listed under their own kind. + const sharedEnvironmentIds = environmentsEnabled ? this.remoteSharing.environmentIds.read(reader) : new Set<string>(); for (const [id, target] of this.targets) { if (target.kind === 'environment') { this.targets.delete(id); @@ -612,7 +651,7 @@ export class RemotesModel extends Disposable implements IRemotesModel { const account = this.environmentService.accountKey; if (environmentsEnabled && account) { for (const host of environments) { - if (host.kind === 'user-local') { + if (host.kind === 'user-local' && !sharedEnvironmentIds.has(host.id)) { const target = { kind: 'environment' as const, host, account }; this.targets.set(this.getId(target), target); } @@ -692,6 +731,10 @@ export class RemotesModel extends Disposable implements IRemotesModel { canDelete: this.registered.has(id) && target.entry.connection.type === RemoteAgentHostEntryType.SSH && !this.isSSHHostConfigured(target.entry.connection), } : {}), hidden, pickerUnavailableReason: this.getPickerUnavailableReason(target, provider, hidden, reader), + ...(target.kind !== 'environment' && (shareable.has(id) || shares.has(id)) ? { + canShareAsGitHubEnvironment: shareable.has(id), + ...(shares.has(id) ? { gitHubEnvironment: shares.get(id) } : {}), + } : {}), connectionStatus: connectionStatuses.get(id) ?? RemoteAgentHostConnectionStatus.disconnected, ...(connectionErrors.has(id) ? { lastConnectionError: connectionErrors.get(id) } : {}), }); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesTable.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesTable.ts index 3b10c9209e7e..b343b1ae9264 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesTable.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesTable.ts @@ -61,7 +61,7 @@ export interface IRemoteTableRow { } type RemoteColumn = 'gutter' | 'name' | 'connection' | 'actions'; -export type RemoteRowAction = 'toggleGroup' | 'toggleVisibility' | 'configure' | 'documentation' | 'connect' | 'rename' | 'copyAddress' | 'locationPreference' | 'updateServer' | 'delete' | 'signIn'; +export type RemoteRowAction = 'toggleGroup' | 'toggleVisibility' | 'configure' | 'documentation' | 'connect' | 'rename' | 'copyAddress' | 'locationPreference' | 'githubEnvironment' | 'updateServer' | 'delete' | 'signIn'; type RemoteCellTemplate = { readonly container: HTMLElement; @@ -69,16 +69,58 @@ type RemoteCellTemplate = { readonly elementDisposables: DisposableStore; row?: IRemoteTableRow; } & ( - | { readonly column: 'name'; readonly label: HTMLElement; readonly count: HTMLElement; readonly progress: HTMLElement; readonly warning: HTMLElement; readonly description: HTMLElement; readonly links: HTMLElement; readonly actionContainer: HTMLElement; actionLink?: Link; actionProgress?: HTMLElement; link?: Link } - | { readonly column: 'connection'; readonly label: HTMLElement; readonly warning: HTMLElement } + | { readonly column: 'name'; readonly label: HTMLElement; readonly gitHubEnvironment: HTMLElement; readonly count: HTMLElement; readonly progress: HTMLElement; readonly warning: HTMLElement; readonly description: HTMLElement; readonly links: HTMLElement; readonly actionContainer: HTMLElement; actionLink?: Link; actionProgress?: HTMLElement; link?: Link } + | { readonly column: 'connection'; readonly state: HTMLElement; readonly icon: HTMLElement; readonly label: HTMLElement; readonly warning: HTMLElement } | { readonly column: 'gutter'; readonly action: Action; readonly toolbar: WorkbenchToolBar } - | { readonly column: 'actions'; readonly action: Action; readonly rename: Action; readonly copyAddress: Action; readonly locationPreference: Action; readonly updateServer: Action; readonly delete: Action; readonly documentation: Action; readonly toolbar: WorkbenchToolBar; actionLayout: string } + | { readonly column: 'actions'; readonly action: Action; readonly rename: Action; readonly copyAddress: Action; readonly locationPreference: Action; readonly gitHubEnvironment: Action; readonly updateServer: Action; readonly delete: Action; readonly documentation: Action; readonly toolbar: WorkbenchToolBar; actionLayout: string } ); +const connectionProgressIcon = ThemeIcon.modify(Codicon.loading, 'spin'); + +function getGitHubEnvironmentState(remote: ICustomizationRemote): { readonly label: string; readonly icon: ThemeIcon; readonly error: boolean } | undefined { + const share = remote.gitHubEnvironment; + switch (share?.state) { + case undefined: return undefined; + case 'connecting': return { label: localize('remotes.gitHubEnvironmentSharing', "Sharing {0} as a GitHub environment...", remote.name), icon: connectionProgressIcon, error: false }; + case 'error': return { label: localize('remotes.gitHubEnvironmentError', "{0} could not be shared as a GitHub environment: {1}", remote.name, share.error ?? ''), icon: Codicon.warning, error: true }; + case 'unavailable': return { + label: share.unavailableReason === 'host' + ? localize('remotes.gitHubEnvironmentSharedByHost', "{0} is shared as a GitHub environment by the remote itself.", remote.name) + : localize('remotes.gitHubEnvironmentSharedByAccount', "{0} is shared as a GitHub environment by another GitHub account.", remote.name), + icon: Codicon.github, + error: false, + }; + default: return { label: localize('remotes.gitHubEnvironmentShared', "{0} is shared as a GitHub environment for other apps signed in with your GitHub account.", remote.name), icon: Codicon.github, error: false }; + } +} + +/** + * Describes whether a remote is shared as a GitHub environment, for its row's accessible label. + */ +export function getGitHubEnvironmentLabel(remote: ICustomizationRemote): string | undefined { + return getGitHubEnvironmentState(remote)?.label; +} + +function getConnectionState(remote: ICustomizationRemote, connecting?: boolean): { readonly label: string; readonly icon: ThemeIcon } { + if (connecting !== undefined) { + return { + label: connecting ? getAgentHostConnectionStatusLabel(RemoteAgentHostConnectionStatus.connecting) : localize('remotes.disconnecting', "Disconnecting"), + icon: connectionProgressIcon, + }; + } + if (remote.kind === 'environment' && remote.unavailableReason && RemoteAgentHostConnectionStatus.isDisconnected(remote.connectionStatus)) { + return { label: localize('remotes.hostOffline', "Host offline"), icon: Codicon.circleSlash }; + } + const label = getAgentHostConnectionStatusLabel(remote.connectionStatus); + switch (remote.connectionStatus.kind) { + case 'connected': return { label, icon: Codicon.plug }; + case 'connecting': return { label, icon: connectionProgressIcon }; + default: return { label, icon: Codicon.debugDisconnect }; + } +} + export function getConnectionLabel(remote: ICustomizationRemote, connecting?: boolean): string { - return connecting === undefined ? remote.kind === 'environment' && remote.unavailableReason && RemoteAgentHostConnectionStatus.isDisconnected(remote.connectionStatus) - ? localize('remotes.offline', "Offline") : getAgentHostConnectionStatusLabel(remote.connectionStatus) - : connecting ? getAgentHostConnectionStatusLabel(RemoteAgentHostConnectionStatus.connecting) : localize('remotes.disconnecting', "Disconnecting"); + return getConnectionState(remote, connecting).label; } export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, RemoteCellTemplate> { @@ -112,6 +154,7 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem template = { ...base, column: this.column, label: dom.append(nameRow, dom.$('.remotes-name')), + gitHubEnvironment: dom.append(nameRow, dom.$('.remotes-github-environment')), count: dom.append(nameRow, dom.$('.remotes-group-count')), progress: dom.append(nameRow, dom.$('.remotes-group-progress', { 'aria-hidden': 'true' })), warning: dom.append(nameRow, dom.$('.remotes-refresh-warning')), @@ -122,10 +165,12 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem break; } case 'connection': { - const label = dom.append(container, dom.$('.remotes-connection-state')); + const state = dom.append(container, dom.$('.remotes-connection-state')); + const icon = dom.append(state, dom.$('span.remotes-connection-icon', { 'aria-hidden': 'true' })); + const label = dom.append(state, dom.$('span.remotes-connection-text')); const warning = dom.append(container, dom.$('.remotes-connection-warning')); dom.append(warning, renderIcon(Codicon.warning)).setAttribute('aria-hidden', 'true'); - template = { ...base, column: this.column, label, warning }; + template = { ...base, column: this.column, state, icon, label, warning }; break; } default: { @@ -168,12 +213,17 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem this.onAction(template.row.entry, 'locationPreference'); } })); + const gitHubEnvironment = disposables.add(new Action('remotes.githubEnvironment', '', ThemeIcon.asClassName(Codicon.github), true, async () => { + if (template.row?.entry.type === 'remote') { + this.onAction(template.row.entry, 'githubEnvironment'); + } + })); const updateServer = disposables.add(new Action('remotes.updateServer', '', ThemeIcon.asClassName(Codicon.cloudDownload), true, async () => { if (template.row?.entry.type === 'remote') { this.onAction(template.row.entry, 'updateServer'); } })); - template = { ...base, column: this.column, action, rename, copyAddress, locationPreference, updateServer, delete: deleteAction, documentation, toolbar, actionLayout: '' }; + template = { ...base, column: this.column, action, rename, copyAddress, locationPreference, gitHubEnvironment, updateServer, delete: deleteAction, documentation, toolbar, actionLayout: '' }; } disposables.add(dom.addDisposableGenericMouseDownListener(container, event => dom.EventHelper.stop(event, true))); break; @@ -217,6 +267,17 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem listRow.setAttribute('aria-busy', String(entry.type === 'group' ? entry.refreshing : entry.type === 'remote' ? entry.busy : signingIn)); template.label.textContent = entry.type === 'remote' ? entry.remote.name : entry.label; template.label.classList.toggle('remotes-empty-label', entry.type === 'empty'); + dom.clearNode(template.gitHubEnvironment); + const gitHubEnvironment = entry.type === 'remote' ? getGitHubEnvironmentState(entry.remote) : undefined; + template.gitHubEnvironment.hidden = !gitHubEnvironment; + template.gitHubEnvironment.classList.toggle('remotes-github-environment-error', !!gitHubEnvironment?.error); + if (gitHubEnvironment) { + // The row's accessible label already includes this state. + dom.append(template.gitHubEnvironment, renderIcon(gitHubEnvironment.icon)).setAttribute('aria-hidden', 'true'); + template.elementDisposables.add(this.hoverService.setupDelayedHover(template.gitHubEnvironment, { + content: gitHubEnvironment.label, style: HoverStyle.Pointer, + }, { groupId: this.hoverGroupId })); + } template.count.textContent = entry.type === 'group' ? String(entry.count) : ''; template.count.hidden = entry.type !== 'group'; template.progress.hidden = entry.type !== 'group' || !entry.refreshing; @@ -269,7 +330,10 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem break; } case 'connection': { - template.label.textContent = entry.type === 'remote' ? getConnectionLabel(entry.remote, entry.connecting) : ''; + const state = entry.type === 'remote' ? getConnectionState(entry.remote, entry.connecting) : undefined; + template.label.textContent = state?.label ?? ''; + template.icon.className = state ? `remotes-connection-icon ${ThemeIcon.asClassName(state.icon)}` : 'remotes-connection-icon'; + template.icon.hidden = !state; const error = entry.type === 'remote' && entry.connecting === undefined ? entry.remote.lastConnectionError : undefined; template.warning.hidden = !error; @@ -279,7 +343,7 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem }, { groupId: this.hoverGroupId })); } if (entry.type === 'remote') { - template.elementDisposables.add(this.hoverService.setupDelayedHover(template.label, { + template.elementDisposables.add(this.hoverService.setupDelayedHover(template.state, { content: entry.connecting === undefined ? error ?? entry.remote.unavailableReason ?? getStatusHover(entry.remote.connectionStatus) : template.label.textContent, style: HoverStyle.Pointer, }, { groupId: this.hoverGroupId })); @@ -296,13 +360,16 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem const showConnection = template.column === 'actions' && entry.type === 'remote'; const showDelete = showConnection && (entry.remote.kind === 'environment' && entry.remote.canRemove || (entry.remote.kind === 'tunnel' || entry.remote.kind === 'ssh') && !!entry.remote.canDelete); const showLocationPreference = showConnection && (entry.remote.kind === 'tunnel' || entry.remote.kind === 'ssh'); + const showGitHubEnvironment = showConnection && (entry.remote.kind === 'ssh' || entry.remote.kind === 'wsl' || entry.remote.kind === 'tunnel') + && (!!entry.remote.canShareAsGitHubEnvironment || !!entry.remote.gitHubEnvironment); const showUpdate = showConnection && RemoteAgentHostConnectionStatus.isIncompatible(entry.remote.connectionStatus) && !!entry.remote.connectionStatus.vscodeUpgradeMethod; - const actionLayout = `${showConfig}:${showDocumentation}:${showConnection}:${showDelete}:${showLocationPreference}:${showUpdate}`; + const actionLayout = `${showConfig}:${showDocumentation}:${showConnection}:${showDelete}:${showLocationPreference}:${showGitHubEnvironment}:${showUpdate}`; if (template.column === 'actions' && template.actionLayout !== actionLayout) { template.actionLayout = actionLayout; template.toolbar.setActions(showConnection ? [ template.action, template.rename, template.copyAddress, ...(showLocationPreference ? [template.locationPreference] : []), + ...(showGitHubEnvironment ? [template.gitHubEnvironment] : []), ...(showDelete ? [template.delete] : []), ...(showUpdate ? [template.updateServer] : []), ] : [ @@ -348,6 +415,14 @@ export class RemotesTableRenderer implements ITableRenderer<IRemoteTableRow, Rem template.locationPreference.enabled = !entry.busy && !RemoteAgentHostConnectionStatus.isConnecting(entry.remote.connectionStatus) && !RemoteAgentHostConnectionStatus.isReconnecting(entry.remote.connectionStatus); + const share = entry.remote.gitHubEnvironment; + template.gitHubEnvironment.label = share?.state === 'connecting' || share?.state === 'unavailable' + ? getGitHubEnvironmentLabel(entry.remote) ?? '' + : share + ? localize('remotes.stopSharingAsGitHubEnvironment', "Stop Sharing {0} as GitHub Environment", entry.remote.name) + : localize('remotes.shareAsGitHubEnvironment', "Share {0} as GitHub Environment", entry.remote.name); + template.gitHubEnvironment.enabled = showGitHubEnvironment && !entry.busy && share?.state !== 'connecting' && share?.state !== 'unavailable'; + template.gitHubEnvironment.class = ThemeIcon.asClassName(share?.state === 'connecting' ? connectionProgressIcon : Codicon.github); template.delete.label = localize('remotes.delete', "Delete {0}", entry.remote.name); template.delete.enabled = showDelete && !entry.busy; template.updateServer.label = localize('remotes.updateServer', "Update Server for {0}", entry.remote.name); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesWidget.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesWidget.ts index 600ffb0579a6..0aac3c741eb8 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesWidget.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/browser/remotesWidget.ts @@ -41,7 +41,7 @@ import { AccessibilityVerbositySettingId } from '../../../../accessibility/brows import { IEditorService, MODAL_GROUP } from '../../../../../services/editor/common/editorService.js'; import { IPreferencesService } from '../../../../../services/preferences/common/preferences.js'; import { getVisibleRemoteKinds, ICustomizationRemote, IRemotesModel, RemoteKind, remoteKindLabels } from './remotesModel.js'; -import { getConnectionLabel, IRemoteEmptyEntry, IRemoteTableRow, RemotesTableRenderer, RemoteRowAction, RemoteTableEntry } from './remotesTable.js'; +import { getConnectionLabel, getGitHubEnvironmentLabel, IRemoteEmptyEntry, IRemoteTableRow, RemotesTableRenderer, RemoteRowAction, RemoteTableEntry } from './remotesTable.js'; import './media/remotesWidget.css'; const remoteSetup: Record<RemoteKind, { readonly label: string; readonly description: string; readonly documentation?: { readonly label: string; readonly href: string } }> = { @@ -278,6 +278,8 @@ export class RemotesWidget extends Disposable { void this.copyAddress(entry.remote.id); } else if (action === 'locationPreference' && (entry.remote.kind === 'tunnel' || entry.remote.kind === 'ssh')) { void this.manageRemote(entry.remote.id, 'locationPreference'); + } else if (action === 'githubEnvironment' && entry.remote.gitHubEnvironment?.state !== 'unavailable' && (entry.remote.canShareAsGitHubEnvironment || entry.remote.gitHubEnvironment)) { + void this.manageRemote(entry.remote.id, 'githubEnvironment'); } else if (action === 'updateServer') { void this.manageRemote(entry.remote.id, 'updateServer'); } else if (action === 'delete' && (entry.remote.kind === 'environment' && entry.remote.canRemove || (entry.remote.kind === 'tunnel' || entry.remote.kind === 'ssh') && entry.remote.canDelete)) { @@ -498,7 +500,7 @@ export class RemotesWidget extends Disposable { } } - private async manageRemote(id: string, action: 'rename' | 'locationPreference' | 'updateServer'): Promise<void> { + private async manageRemote(id: string, action: 'rename' | 'locationPreference' | 'githubEnvironment' | 'updateServer'): Promise<void> { if (this.pendingActions.has(id) || this.pendingConnections.has(id)) { return; } @@ -509,6 +511,9 @@ export class RemotesWidget extends Disposable { try { if (action === 'locationPreference') { await this.model.changePreferredAgentLocation(id); + } else if (action === 'githubEnvironment') { + const remote = this.model.remotes.get().find(remote => remote.id === id); + await this.model.setSharedAsGitHubEnvironment(id, !remote?.gitHubEnvironment); } else if (action === 'updateServer') { await this.model.updateServer(id); } else { @@ -597,6 +602,10 @@ export class RemotesWidget extends Disposable { if (!this.pendingConnections.has(remote.id) && error) { label = localize('remotes.accessibleConnectionError', "{0}. Connection error: {1}", label, error); } + const gitHubEnvironment = getGitHubEnvironmentLabel(remote); + if (gitHubEnvironment) { + label = localize('remotes.accessibleGitHubEnvironment', "{0}. {1}", label, gitHubEnvironment); + } return remote.unavailableReason ? localize('remotes.accessibleUnavailableRow', "{0}. {1}", label, remote.unavailableReason) : label; } diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/electron-browser/thisComputerSection.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/electron-browser/thisComputerSection.ts index 45e7ebba9e14..55491edb6ddb 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/electron-browser/thisComputerSection.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/electron-browser/thisComputerSection.ts @@ -10,7 +10,6 @@ import { getDefaultHoverDelegate } from '../../../../../../base/browser/ui/hover import { renderIcon } from '../../../../../../base/browser/ui/iconLabel/iconLabels.js'; import { IRadioOptionItem, Radio } from '../../../../../../base/browser/ui/radio/radio.js'; import { Action } from '../../../../../../base/common/actions.js'; -import { Sequencer } from '../../../../../../base/common/async.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { Disposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; @@ -48,12 +47,9 @@ export class ThisComputerSection extends Disposable { private readonly status: HTMLElement; private readonly policy: HTMLElement; private readonly policyText = localize('thisComputer.policyDisabled', "GitHub Environments is disabled by your organization. Contact your administrator."); - private readonly descriptionText = localize('thisComputer.description', "Local sessions run directly here. Sharing lets other clients access agents and folders on this computer."); + private readonly descriptionText = localize('thisComputer.description', "Local sessions run directly here. Sharing lets other devices use agents and folders on this computer. Files and tools stay here."); private methods: readonly RemoteConnectionsMethod[] = []; private itemsKey: string | undefined; - /** The method the user chose while it is being applied, so the control does not snap back meanwhile. */ - private pendingMethod: RemoteConnectionsMethod | undefined; - private readonly selections = new Sequencer(); constructor( container: HTMLElement, @@ -85,12 +81,12 @@ export class ThisComputerSection extends Disposable { const controls = dom.append(this.domNode, dom.$('.remotes-this-computer-controls')); const methodLabelId = generateUuid(); - dom.append(controls, dom.$('.remotes-this-computer-method-label', { id: methodLabelId }, localize('thisComputer.remoteConnections', "Remote Connections"))); + dom.append(controls, dom.$('.remotes-this-computer-method-label', { id: methodLabelId }, localize('thisComputer.allowConnectionsHere', "Allow Connections Here"))); // Choosing a method starts or stops sharing, so arrow keys only move focus. this.radio = this._register(new Radio({ items: [], arrowKeyBehavior: 'focus' })); this.radio.domNode.setAttribute('aria-labelledby', methodLabelId); controls.appendChild(this.radio.domNode); - this._register(this.radio.onDidSelect(index => this.select(this.methods[index]))); + this._register(this.radio.onDidSelect(index => { void this.sharing.selectMethod(this.methods[index]); })); this.status = dom.append(controls, dom.$('p.remotes-this-computer-status', { role: 'status' })); // A disabled option cannot be focused, so the policy reason and its next step stay outside the options. @@ -125,26 +121,12 @@ export class ThisComputerSection extends Disposable { ].join('\n'); } - private async select(method: RemoteConnectionsMethod): Promise<void> { - this.pendingMethod = method; - this.update(); - try { - // A choice made while another is being applied must act on the resulting state rather than the transitional one. - await this.selections.queue(() => this.sharing.selectMethod(method)); - } finally { - if (this.pendingMethod === method) { - this.pendingMethod = undefined; - } - if (!this._store.isDisposed) { - this.update(); - } - } - } - private update(): void { const state = this.sharing.getState(); const active = this.sharing.activeMethod; - const shown = this.pendingMethod ?? active; + // Shows the method chosen last, so the control does not snap back while choices are being applied. + const pending = this.sharing.pendingMethod; + const shown = pending ?? active; const availability = this.sharing.gitHubEnvironmentsAvailability; const methods: RemoteConnectionsMethod[] = ['off']; if (availability !== 'unavailable' || shown === 'githubEnvironment') { @@ -172,10 +154,10 @@ export class ThisComputerSection extends Disposable { this.nameHover.update(name ?? ''); this.rename.enabled = !!name && !state.isConnecting; - this.status.textContent = this.pendingMethod && this.pendingMethod !== active - ? this.pendingMethod === 'off' + this.status.textContent = pending && pending !== active + ? pending === 'off' ? localize('thisComputer.stopping', "Turning off remote connections...") - : localize('thisComputer.starting', "Remote connections are starting via {0}...", getMethodLabel(this.pendingMethod)) + : localize('thisComputer.starting', "Remote connections are starting via {0}...", getMethodLabel(pending)) : active === 'off' ? localize('thisComputer.statusOff', "Remote connections are off.") : state.isConnecting diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/cloudSandboxAgentHostContribution.test.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/cloudSandboxAgentHostContribution.test.ts index 746fbe29b32e..21e21be6ea36 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/cloudSandboxAgentHostContribution.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/cloudSandboxAgentHostContribution.test.ts @@ -5,7 +5,6 @@ import assert from 'assert'; import { DeferredPromise, RunOnceScheduler, timeout } from '../../../../../../../base/common/async.js'; -import { bufferToStream, VSBuffer } from '../../../../../../../base/common/buffer.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../../base/common/codicons.js'; import { CancellationError, isCancellationError } from '../../../../../../../base/common/errors.js'; @@ -59,6 +58,7 @@ import { ChatAIDisabledSettingId } from '../../../../../../../platform/chat/comm import { ICommandService } from '../../../../../../../platform/commands/common/commands.js'; import { TestConfigurationService } from '../../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILabelService } from '../../../../../../../platform/label/common/label.js'; import { ILogService, NullLogService } from '../../../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../../../platform/product/common/productService.js'; import { IRequestService } from '../../../../../../../platform/request/common/request.js'; @@ -73,6 +73,11 @@ import { IHostService } from '../../../../../../services/host/browser/host.js'; import { IPowerService } from '../../../../../../services/power/common/powerService.js'; import { IAuthenticationService } from '../../../../../../services/authentication/common/authentication.js'; import { IWorkbenchGitHubService } from '../../../../../../services/github/common/githubService.js'; +import { IGitHubAccountClient } from '../../../../../../../platform/github/common/account/account.js'; +import { AccountClient } from '../../../../../../../platform/github/common/account/accountClient.js'; +import { LocalMissionControlRequestProvider } from '../../../../../../../platform/github/common/client/localMissionControlRequestProvider.js'; +import { IGitHubCredentials } from '../../../../../../../platform/github/common/githubCredentialService.js'; +import { GitHubTransport } from '../../../../../../../platform/github/common/githubTransport.js'; import { IUserDataProfileService } from '../../../../../../services/userDataProfile/common/userDataProfile.js'; import { IUserDataProfile } from '../../../../../../../platform/userDataProfile/common/userDataProfile.js'; import { ILifecycleService } from '../../../../../../services/lifecycle/common/lifecycle.js'; @@ -623,7 +628,7 @@ async function createContribution(store: Pick<DisposableStore, 'add'>, sessions: upcastPartial<IAgentHostService>({ onAgentHostStart: Event.None, onAgentHostExit: Event.None }), instantiationService.get(IRemoteAgentHostService), upcastPartial<IPathService>({ registerPathProvider: () => Disposable.None }), - new NullLogService(), + upcastPartial<ILabelService>({ registerFormatter: () => Disposable.None }), )); instantiationService.stub(IAgentHostConnectionsService, resolutionService); instantiationService.stub(IAgentHostFilterService, new class extends mock<IAgentHostFilterService>() { @@ -3069,17 +3074,16 @@ suite('CloudSandboxAgentHostContribution discovery refresh', () => { test('successive short-gap reconnects send since from the last successful list until full repair is due', () => runWithFakedTimers<void>({ useFakeTimers: true }, async () => { const requests: { since: string | null; environment: string | null; repository: string | null; archived: string | null; limit: string | null; page: string | null }[][] = []; let currentRequests: typeof requests[number] = []; + const transport = store.add(new GitHubTransport(async input => { + const query = new URL(String(input)).searchParams; + currentRequests.push({ + since: query.get('since'), environment: query.get('include_environment_kinds'), + repository: query.get('with_repo'), archived: query.get('is_archived'), limit: query.get('per_page'), page: query.get('page'), + }); + return Response.json({ tasks: [] }, { headers: { date: new Date().toUTCString() } }); + })); const api = store.add(new CloudSandboxApiService( - new class extends mock<IRequestService>() { - override async request(options: { url?: string }) { - const query = new URL(options.url!).searchParams; - currentRequests.push({ - since: query.get('since'), environment: query.get('include_environment_kinds'), - repository: query.get('with_repo'), archived: query.get('is_archived'), limit: query.get('per_page'), page: query.get('page'), - }); - return { res: { statusCode: 200, headers: { date: new Date().toUTCString() } }, stream: bufferToStream(VSBuffer.fromString('{"tasks":[]}')) }; - } - }(), + new class extends mock<IRequestService>() { }(), new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = Event.None; override readonly onDidRegisterAuthenticationProvider = Event.None; @@ -3091,7 +3095,22 @@ suite('CloudSandboxAgentHostContribution discovery refresh', () => { override reportDiscovery() { } override reportRequest() { } }(), - new class extends mock<IWorkbenchGitHubService>() { }(), + new class extends mock<IWorkbenchGitHubService>() { + override async acquireAccountApiClient(authorization: IGitHubAccountClient['authorization']): Promise<IGitHubAccountClient> { + const lifetime = new DisposableStore(); + const controller = new AbortController(); + lifetime.add(toDisposable(() => controller.abort())); + const credentials: IGitHubCredentials = { + onDidInvalidate: Event.None, + getCredential: async () => ({ account: { host: 'api.github.com', accountId: 'account-1' }, token: 'token', generation: 0, signal: controller.signal }), + handleRequestError: () => { }, + }; + const provider = new LocalMissionControlRequestProvider({ + apiBaseUri: 'https://api.githubcopilot.com/agents', integrationId: 'test', + }, credentials, transport, new NullLogService(), controller.signal); + return new AccountClient(authorization, { rest: provider, graphql: provider, missionControl: provider }, lifetime); + } + }(), new class extends mock<IUserDataProfileService>() { override readonly currentProfile = upcastPartial<IUserDataProfile>({ id: 'test-profile' }); override readonly onDidChangeCurrentProfile = Event.None; @@ -3336,7 +3355,7 @@ suite('CloudSandboxAgentHostContribution discovery refresh', () => { h.setFocused(true); await h.runDiscovery('automatic'); await h.runDiscovery(); - assert.deepStrictEqual(requests.map(({ diagnostics, ...options } = {}) => options), [ + assert.deepStrictEqual(requests.map(({ diagnostics, ...options }: ICloudSandboxDiscoveryOptions = {}) => options), [ { incremental: false, includeArchived: false, trigger: 'startup' }, ...connected ? [] : [{ incremental: true, includeArchived: false, trigger: 'focus' }], { incremental: false, includeArchived: false, trigger: 'manual' }, @@ -3366,7 +3385,7 @@ suite('CloudSandboxAgentHostContribution discovery refresh', () => { h.changeAccount('["github","account-1"]'); await listed.p; await h.contribution.checkForUpdates(); - assert.deepStrictEqual({ requests: requests.map(({ diagnostics, ...options } = {}) => options), disposed: provider.disposed, disconnects: h.disconnectedFrom, negotiations }, { + assert.deepStrictEqual({ requests: requests.map(({ diagnostics, ...options }: ICloudSandboxDiscoveryOptions = {}) => options), disposed: provider.disposed, disconnects: h.disconnectedFrom, negotiations }, { requests: [ { incremental: false, includeArchived: false, trigger: 'startup' }, { incremental: true, includeArchived: false, trigger: 'configurationChange' }, diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/devContainerAgentHostService.test.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/devContainerAgentHostService.test.ts index b62a322c21a9..608f3d5cb452 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/devContainerAgentHostService.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/devContainerAgentHostService.test.ts @@ -257,35 +257,6 @@ class TestDevContainerAgentHostService extends DevContainerAgentHostService { suite('Dev Container Agent Host Service', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - test('registers and removes an offline location without starting or deleting a container', async () => { - const storage = store.add(new InMemoryStorageService()); - const providers = store.add(new TestSessionsProvidersService()); - const service = store.add(new TestDevContainerAgentHostService( - store.add(new TestInstantiationService()), store.add(new TestRemoteAgentHostService()), providers, storage, - )); - const workspaceUri = URI.file('/project'); - service.addWorkspace(workspaceUri, 'Project'); - const added = { workspaces: service.getWorkspaces().map(workspace => ({ name: workspace.name, uri: workspace.workspaceUri.toString() })), providers: providers.getProviders().length }; - service.dispose(); - const restored = store.add(new TestDevContainerAgentHostService( - store.add(new TestInstantiationService()), store.add(new TestRemoteAgentHostService()), providers, storage, - )); - const restoredWorkspaces = restored.getWorkspaces().map(workspace => ({ name: workspace.name, uri: workspace.workspaceUri.toString() })); - const availabilityChanges: { workspaces: number; providers: number }[] = []; - store.add(restored.onDidChangeAvailability(() => availabilityChanges.push({ - workspaces: restored.getWorkspaces().length, providers: providers.getProviders().length, - }))); - await restored.removeWorkspace(workspaceUri); - assert.deepStrictEqual({ - added, restoredWorkspaces, removed: restored.getWorkspaces(), providers: providers.getProviders().length, availabilityChanges, - }, { - added: { workspaces: [{ uri: workspaceUri.toString(), name: 'Project' }], providers: 1 }, - restoredWorkspaces: [{ uri: workspaceUri.toString(), name: 'Project' }], - removed: [], providers: 0, - availabilityChanges: [{ workspaces: 0, providers: 0 }], - }); - }); - test('publishes inspected sandbox support even when the first connection fails', async () => { const instantiationService = store.add(new TestInstantiationService()); const service = store.add(new TestDevContainerAgentHostService( diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesModel.test.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesModel.test.ts index 08e5a46afebd..8cc9156e3a51 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesModel.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesModel.test.ts @@ -14,7 +14,7 @@ import { mock } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; import { runWithFakedTimers } from '../../../../../../../base/test/common/virtualScheduling/index.js'; import { cloudSandboxAddress } from '../../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; -import { GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlHost } from '../../../../../../../platform/agentHost/common/missionControlEnvironment.js'; +import { GitHubEnvironmentsEnabledSettingId, IMissionControlAvailabilityService, IMissionControlEnvironmentService, IMissionControlHost, IRemoteGitHubEnvironmentShare, IRemoteGitHubEnvironmentSharingService } from '../../../../../../../platform/agentHost/common/missionControlEnvironment.js'; import { addSSHRemoteAgentHostEntry, IRemoteAgentHostConnectionInfo, IRemoteAgentHostService, readSSHRemoteAgentHostEntries, removeSSHRemoteAgentHostEntry, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { ISSHRemoteAgentHostService } from '../../../../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { ICachedTunnel, ITunnelAgentHostService, ITunnelInfo, TunnelAuthenticationRequiredError } from '../../../../../../../platform/agentHost/common/tunnelAgentHost.js'; @@ -193,6 +193,28 @@ suite('RemotesModel', () => { environmentHosts.set(environmentHosts.get().map(host => host.id === id ? { ...host, displayName: name?.trim() || undefined } : host), undefined); }, }); + const sharing = { + shareable: observableValue<ReadonlySet<string>>(store, new Set()), + shares: observableValue<ReadonlyMap<string, IRemoteGitHubEnvironmentShare>>(store, new Map()), + environmentIds: observableValue<ReadonlySet<string>>(store, new Set()), + // Records how many removals had happened, to verify that sharing stops first. + events: [] as string[], + }; + instantiationService.stub(IRemoteGitHubEnvironmentSharingService, { + shareable: sharing.shareable, + shares: sharing.shares, + environmentIds: sharing.environmentIds, + setShared: async (address, shared) => { + sharing.events.push(`${shared ? 'share' : 'unshare'} ${address} after ${removals.length + sshDisconnects.length + deletedTunnels.length} removals`); + const shares = new Map(sharing.shares.get()); + if (shared) { + shares.set(address, { state: 'enabled', environmentId: `env-${address}` }); + } else { + shares.delete(address); + } + sharing.shares.set(shares, undefined); + }, + }); instantiationService.stub(ISSHRemoteAgentHostService, { listSSHConfigHosts: () => sshDiscovery(), disconnect: async key => { @@ -310,7 +332,7 @@ suite('RemotesModel', () => { getWSLDiscoveryCalls: () => wslDiscoveryCalls, setSSHDiscovery: (discovery: () => Promise<string[]>) => { sshDiscovery = discovery; }, setTunnelDiscovery: (discovery: () => Promise<ITunnelInfo[]>) => { tunnelDiscovery = discovery; }, setTunnelAuthentication: (authentication: () => Promise<'github' | 'microsoft' | undefined>) => { tunnelAuthentication = authentication; }, - environmentHosts, environmentAvailable, environmentState, environmentConnections, environmentNames, environmentDeletions, confirmations, + environmentHosts, environmentAvailable, environmentState, environmentConnections, environmentNames, environmentDeletions, confirmations, sharing, setConfiguration: async (key: string, value: boolean) => { await configuration.setUserConfiguration(key, value); configuration.onDidChangeConfigurationEmitter.fire({ @@ -1478,6 +1500,63 @@ suite('RemotesModel', () => { }); }); + test('GitHub environment sharing is gated, lists shared remotes once and rejects unsupported targets', async () => { + const { model, configuration, setConfiguration, environmentAvailable, environmentHosts, sharing } = setup(); + await model.refresh(CancellationToken.None); + sharing.shareable.set(new Set(['ssh:build', 'tunnel:laptop']), undefined); + const snapshot = () => ({ + rows: model.remotes.get().filter(remote => remote.canShareAsGitHubEnvironment !== undefined) + .map(remote => `${remote.id}: ${remote.canShareAsGitHubEnvironment ? 'shareable' : 'not shareable'}${remote.gitHubEnvironment ? `, ${remote.gitHubEnvironment.state}` : ''}`), + environments: model.remotes.get().filter(remote => remote.kind === 'environment').map(remote => remote.name), + }); + const gated = snapshot(); + await assert.rejects(model.setSharedAsGitHubEnvironment('ssh:build', true), /no longer available/); + await configuration.setUserConfiguration(GitHubEnvironmentsEnabledSettingId, true); + environmentAvailable.set(true, undefined); + environmentHosts.set([ + { id: 'shared-build', name: 'Shared build', kind: 'user-local', status: 'online' }, + { id: 'desktop', name: 'Desktop', kind: 'user-local', status: 'online' }, + ], undefined); + await model.setSharedAsGitHubEnvironment('ssh:build', true); + sharing.environmentIds.set(new Set(['shared-build']), undefined); + const shared = snapshot(); + await assert.rejects(model.setSharedAsGitHubEnvironment('wsl:Ubuntu', true), /no longer available/); + await assert.rejects(model.setSharedAsGitHubEnvironment('tunnel:laptop', false), /no longer available/); + await assert.rejects(model.setSharedAsGitHubEnvironment(cloudSandboxAddress('desktop'), true), /no longer available/); + await setConfiguration(GitHubEnvironmentsEnabledSettingId, false); + const disabled = snapshot(); + await setConfiguration(GitHubEnvironmentsEnabledSettingId, true); + await model.setSharedAsGitHubEnvironment('ssh:build', false); + sharing.environmentIds.set(new Set(), undefined); + assert.deepStrictEqual({ gated, shared, disabled, unshared: snapshot(), events: sharing.events }, { + gated: { rows: [], environments: [] }, + shared: { rows: ['ssh:build: shareable, enabled', 'tunnel:laptop: shareable'], environments: ['Desktop'] }, + disabled: { rows: [], environments: [] }, + unshared: { rows: ['ssh:build: shareable', 'tunnel:laptop: shareable'], environments: ['Desktop', 'Shared build'] }, + events: ['share ssh:build after 0 removals', 'unshare ssh:build after 0 removals'], + }); + }); + + test('removing or deleting a shared remote stops sharing it first', async () => { + const { model, storage, configuration, environmentAvailable, sharing } = setup(); + await configuration.setUserConfiguration(GitHubEnvironmentsEnabledSettingId, true); + environmentAvailable.set(true, undefined); + addSSHRemoteAgentHostEntry(storage, savedSSHHost); + await model.refresh(CancellationToken.None); + const ids = ['ssh:removed', 'wsl:Ubuntu', 'tunnel:laptop']; + sharing.shareable.set(new Set(ids), undefined); + for (const id of ids) { + await model.setSharedAsGitHubEnvironment(id, true); + } + await model.deleteSSHHost('ssh:removed'); + await model.remove('wsl:Ubuntu'); + await model.deleteTunnel('tunnel:laptop'); + assert.deepStrictEqual({ events: sharing.events.slice(ids.length), shares: [...sharing.shares.get().keys()] }, { + events: ['unshare ssh:removed after 0 removals', 'unshare wsl:Ubuntu after 1 removals', 'unshare tunnel:laptop after 2 removals'], + shares: [], + }); + }); + test('environment rename uses inventory names and cancels when the account changes during the prompt', async () => { const { model, configuration, environmentAvailable, environmentHosts, environmentState, environmentNames, setRenameInput } = setup(); await configuration.setUserConfiguration(GitHubEnvironmentsEnabledSettingId, true); diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.fixture.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.fixture.ts index f66ebce8583b..37f419a81316 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.fixture.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.fixture.ts @@ -111,6 +111,9 @@ async function render({ container, disposableStore, theme }: ComponentFixtureCon async updateServer(id: string) { await this.setConnected(id, true); } + async setSharedAsGitHubEnvironment(id: string, shared: boolean) { + this.remotes.set(this.remotes.get().map(remote => remote.id === id ? { ...remote, gitHubEnvironment: shared ? { state: 'enabled' } : undefined } : remote), undefined); + } async deleteTunnel(id: string) { const remote = this.remotes.get().find(remote => remote.id === id); if (remote && await confirmTunnelDeletion(instantiationService.get(IDialogService), remote.name)) { diff --git a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.test.ts b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.test.ts index d78bc4e07e97..eb9b6bb15f86 100644 --- a/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.test.ts +++ b/src/vs/workbench/contrib/sessions/providers/remoteAgentHost/test/browser/remotesWidget.test.ts @@ -51,6 +51,7 @@ class TestRemotesModel extends Disposable implements IRemotesModel { readonly copiedAddresses: string[] = []; readonly locationChanges: string[] = []; readonly serverUpdates: string[] = []; + readonly gitHubEnvironmentChanges: { id: string; shared: boolean }[] = []; readonly tunnelDeletions: string[] = []; readonly sshDeletions: string[] = []; copyFailure: Error | undefined; @@ -105,6 +106,12 @@ class TestRemotesModel extends Disposable implements IRemotesModel { this.remotes.set(this.remotes.get().map(remote => remote.id === id ? { ...remote, connectionStatus: RemoteAgentHostConnectionStatus.connected } : remote), undefined); } + async setSharedAsGitHubEnvironment(id: string, shared: boolean): Promise<void> { + this.gitHubEnvironmentChanges.push({ id, shared }); + await this.pendingManagement?.p; + this.remotes.set(this.remotes.get().map(remote => remote.id === id ? { ...remote, gitHubEnvironment: shared ? { state: 'enabled' } : undefined } : remote), undefined); + } + async deleteTunnel(id: string): Promise<void> { this.tunnelDeletions.push(id); await this.pendingManagement?.p; @@ -747,6 +754,40 @@ suite('RemotesWidget', () => { assert.deepStrictEqual(labels, [null, null, 'Update Server for Build server', null, null]); }); + test('GitHub environment action offers Stop Sharing once the remote is shared', async () => { + const { parent, model } = createWidget(); + model.remotes.set(model.remotes.get().map(remote => remote.id === 'ssh:build' ? { ...remote, canShareAsGitHubEnvironment: true } : remote), undefined); + const action = () => [...parent.querySelectorAll<HTMLElement>('[data-remote-id="ssh:build"] .remotes-actions-column [role="button"]')] + .find(button => button.getAttribute('aria-label')?.includes('GitHub'))!; + const state = () => ({ label: action().getAttribute('aria-label'), disabled: action().getAttribute('aria-disabled'), pressed: action().getAttribute('aria-pressed') }); + const states = [state()]; + action().click(); + await timeout(0); + states.push(state()); + model.remotes.set(model.remotes.get().map(remote => remote.id === 'ssh:build' ? { ...remote, gitHubEnvironment: { state: 'connecting' } } : remote), undefined); + states.push(state()); + model.remotes.set(model.remotes.get().map(remote => remote.id === 'ssh:build' ? { ...remote, gitHubEnvironment: { state: 'error', error: 'Denied' } } : remote), undefined); + states.push(state()); + action().click(); + await timeout(0); + states.push(state()); + model.remotes.set(model.remotes.get().map(remote => remote.id === 'ssh:build' ? { ...remote, gitHubEnvironment: { state: 'unavailable', unavailableReason: 'account' } } : remote), undefined); + states.push(state()); + action().click(); + await timeout(0); + assert.deepStrictEqual({ states, changes: model.gitHubEnvironmentChanges }, { + states: [ + { label: 'Share Build server as GitHub Environment', disabled: null, pressed: null }, + { label: 'Stop Sharing Build server as GitHub Environment', disabled: null, pressed: null }, + { label: 'Sharing Build server as a GitHub environment...', disabled: 'true', pressed: null }, + { label: 'Stop Sharing Build server as GitHub Environment', disabled: null, pressed: null }, + { label: 'Share Build server as GitHub Environment', disabled: null, pressed: null }, + { label: 'Build server is shared as a GitHub environment by another GitHub account.', disabled: 'true', pressed: null }, + ], + changes: [{ id: 'ssh:build', shared: true }, { id: 'ssh:build', shared: false }], + }); + }); + test('Update Server supports keyboard activation, blocks duplicates and restores focus when it disappears', async () => { const { parent, model } = createWidget(); model.remotes.set([{ @@ -1291,7 +1332,7 @@ suite('RemotesWidget', () => { tooltip: hoverContents.get(connection), infoIcons: row.querySelectorAll('.codicon-info').length, addressColumns: parent.querySelectorAll('.remotes-address-column').length, - accessibleView: widget.getAccessibilityContent().includes('Desktop. Status: Offline. Start the owning application.'), + accessibleView: widget.getAccessibilityContent().includes('Desktop. Status: Host offline. Start the owning application.'), }; model.remotes.set(model.remotes.get().map(remote => ({ ...remote, unavailableReason: undefined })), undefined); assert.deepStrictEqual({ @@ -1299,7 +1340,7 @@ suite('RemotesWidget', () => { available: parent.querySelector('[data-remote-id] .remotes-connection-state')?.textContent, tableFocused: dom.getActiveElement() === table, }, { - offline: { connection: 'Offline', tooltip: 'Start the owning application.', infoIcons: 0, addressColumns: 0, accessibleView: true }, + offline: { connection: 'Host offline', tooltip: 'Start the owning application.', infoIcons: 0, addressColumns: 0, accessibleView: true }, available: 'Disconnected', tableFocused: true, }); }); @@ -1317,18 +1358,30 @@ suite('RemotesWidget', () => { { ...offline, connectionStatus: RemoteAgentHostConnectionStatus.connecting }, { ...offline, connectionStatus: RemoteAgentHostConnectionStatus.reconnecting }, ]; + const status = () => { + const state = parent.querySelector('[data-remote-id] .remotes-connection-state'); + const icon = [...state?.querySelector('.remotes-connection-icon')?.classList ?? []].filter(name => name.startsWith('codicon-')).join(' '); + return `${state?.textContent} (${icon})`; + }; const observed = states.map(remote => { model.remotes.set([remote], undefined); - return parent.querySelector('[data-remote-id] .remotes-connection-state')?.textContent; + return status(); }); model.remotes.set([{ ...offline, connectionStatus: RemoteAgentHostConnectionStatus.connected }], undefined); model.pendingConnection = new DeferredPromise<void>(); getConnectionAction(parent, offline.id).click(); - observed.push(parent.querySelector('[data-remote-id] .remotes-connection-state')?.textContent); + observed.push(status()); await model.pendingConnection.complete(); await timeout(0); - observed.push(parent.querySelector('[data-remote-id] .remotes-connection-state')?.textContent); - assert.deepStrictEqual(observed, ['Offline', 'Connected', 'Connecting', 'Disconnected', 'Disconnecting', 'Offline']); + observed.push(status()); + assert.deepStrictEqual(observed, [ + 'Host offline (codicon-circle-slash)', + 'Connected (codicon-plug)', + 'Connecting (codicon-loading codicon-modifier-spin)', + 'Disconnected (codicon-debug-disconnect)', + 'Disconnecting (codicon-loading codicon-modifier-spin)', + 'Host offline (codicon-circle-slash)', + ]); }); test('Rename is reachable and operable through toolbar keyboard navigation', async () => { diff --git a/src/vs/workbench/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.test.ts b/src/vs/workbench/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.test.ts new file mode 100644 index 000000000000..a19e6b3c7581 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/aiCustomizationShortcutsWidget.test.ts @@ -0,0 +1,188 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import * as DOM from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { constObservable } from '../../../../../base/common/observable.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IAICustomizationItemsModel } from '../../../chat/browser/aiCustomization/aiCustomizationItemsModel.js'; +import { IAgentHostToolSetEnablementService } from '../../../chat/browser/agentSessions/agentHost/agentHostToolSetEnablementService.js'; +import { IAICustomizationWorkspaceService } from '../../../chat/common/aiCustomizationWorkspaceService.js'; +import { ICustomizationHarnessService, IHarnessDescriptor } from '../../../chat/common/customizationHarnessService.js'; +import { ILanguageModelToolsService, IToolSet } from '../../../chat/common/tools/languageModelToolsService.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { AICustomizationShortcutsWidget } from '../../browser/aiCustomizationShortcutsWidget.js'; +import { IAICustomizationMcpServerCountService } from '../../browser/customizationMcpServerCount.js'; + +suite('AI customization shortcuts header', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + let container: HTMLElement; + let header: HTMLElement; + + // A cycle invalidates the token without inheriting a value from the surrounding theme. + const invalidateToken = (name: string) => container.style.setProperty(name, `var(${name})`); + + setup(() => { + container = DOM.append(mainWindow.document.body, DOM.$('div')); + container.style.cssText = 'position: fixed; top: 0; left: 0; width: 300px; height: 200px; z-index: 10000;'; + disposables.add(toDisposable(() => container.remove())); + + const instantiationService = workbenchInstantiationService({}, disposables); + instantiationService.stub(ICommandService, { executeCommand: async () => undefined }); + instantiationService.stub(IAICustomizationItemsModel, { + getCount: () => constObservable(1), + getPluginCount: () => constObservable(1), + }); + instantiationService.stub(IAICustomizationMcpServerCountService, { count: constObservable(1) }); + instantiationService.stub(ILanguageModelToolsService, { toolSets: constObservable<readonly IToolSet[]>([]) }); + instantiationService.stub(IAgentHostToolSetEnablementService, { + observe: () => constObservable({ toolSets: new Map<string, boolean>(), tools: new Map<string, boolean>() }), + }); + const descriptor = upcastPartial<IHarnessDescriptor>({ id: 'test', label: 'Test', icon: Codicon.extensions }); + instantiationService.stub(ICustomizationHarnessService, { + activeHarness: constObservable('test'), + availableHarnesses: constObservable([descriptor]), + getActiveDescriptor: () => descriptor, + }); + instantiationService.stub(IAICustomizationWorkspaceService, { managementSections: [] }); + disposables.add(instantiationService.createInstance(AICustomizationShortcutsWidget, container, undefined)); + + const renderedHeader = container.querySelector<HTMLElement>('.ai-customization-header'); + assert.ok(renderedHeader); + header = renderedHeader; + container.style.setProperty('--vscode-spacing-size40', '4px'); + container.style.setProperty('--vscode-spacing-size60', '6px'); + container.style.setProperty('--vscode-spacing-size100', '10px'); + container.style.setProperty('--vscode-strokeThickness', '1px'); + container.style.setProperty('--vscode-list-hoverBackground', 'rgb(240, 240, 240)'); + container.style.setProperty('--vscode-list-hoverForeground', 'rgb(0, 0, 0)'); + container.style.setProperty('--vscode-contrastActiveBorder', 'rgb(255, 0, 0)'); + container.style.setProperty('--vscode-strongForeground', 'rgb(255, 255, 255)'); + container.style.setProperty('--vscode-descriptionForeground', 'rgb(200, 200, 200)'); + }); + + test('keeps both edges clickable while the hover remains inset', () => { + header.classList.add('hovered'); + const toolbar = container.querySelector<HTMLElement>('.ai-customization-toolbar'); + const label = header.querySelector<HTMLElement>('.ai-customization-header-label'); + assert.ok(toolbar && label); + const bounds = toolbar.getBoundingClientRect(); + const headerBounds = header.getBoundingClientRect(); + const labelBounds = label.getBoundingClientRect(); + const clickAt = (x: number) => { + const target = mainWindow.document.elementFromPoint(x, headerBounds.top + headerBounds.height / 2); + target?.dispatchEvent(new MouseEvent('click', { bubbles: true })); + return { target, expanded: header.getAttribute('aria-expanded') }; + }; + const clicks = [bounds.left + 1, bounds.right - 1, labelBounds.left + labelBounds.width / 2].map(clickAt); + const hoverStyle = mainWindow.getComputedStyle(header, '::before'); + + assert.deepStrictEqual({ + insideHeader: clicks.map(({ target }) => header.contains(target)), + lastHitIsDescendant: clicks[2].target !== header, + expanded: clicks.map(({ expanded }) => expanded), + hoverInsets: [hoverStyle.left, hoverStyle.right], + }, { + insideHeader: [true, true, true], + lastHitIsDescendant: true, + expanded: ['false', 'true', 'false'], + hoverInsets: ['4px', '4px'], + }); + }); + + test('keeps the hover geometry when size tokens are unavailable', () => { + for (const token of ['--vscode-spacing-size40', '--vscode-spacing-size60', '--vscode-spacing-size100', '--vscode-cornerRadius-small', '--vscode-strokeThickness']) { + invalidateToken(token); + } + header.classList.add('hovered'); + const headerStyle = mainWindow.getComputedStyle(header); + const hoverStyle = mainWindow.getComputedStyle(header, '::before'); + + assert.deepStrictEqual({ + padding: [headerStyle.paddingTop, headerStyle.paddingRight], + insets: [hoverStyle.left, hoverStyle.right], + radius: hoverStyle.borderTopLeftRadius, + outline: [hoverStyle.outlineStyle, hoverStyle.outlineWidth, hoverStyle.outlineOffset], + }, { + padding: ['6px', '10px'], + insets: ['4px', '4px'], + radius: '4px', + outline: ['dashed', '1px', '-1px'], + }); + }); + + test('pairs the hover background with themed text and a contrast outline', () => { + header.click(); + header.classList.add('hovered'); + const label = header.querySelector<HTMLElement>('.ai-customization-header-label'); + const count = header.querySelector<HTMLElement>('.ai-customization-header-total-count'); + const chevron = header.querySelector<HTMLElement>('.ai-customization-chevron'); + assert.ok(label && count && chevron); + const colors = () => ({ + label: mainWindow.getComputedStyle(label).color, + count: mainWindow.getComputedStyle(count).color, + chevron: mainWindow.getComputedStyle(chevron).color, + chevronOpacity: mainWindow.getComputedStyle(chevron).opacity, + }); + const hoverStyle = mainWindow.getComputedStyle(header, '::before'); + const themed = colors(); + const background = hoverStyle.backgroundColor; + const outline = [hoverStyle.outlineStyle, hoverStyle.outlineColor]; + invalidateToken('--vscode-list-hoverForeground'); + const fallback = colors(); + + assert.deepStrictEqual({ background, outline, themed, fallback }, { + background: 'rgb(240, 240, 240)', + outline: ['dashed', 'rgb(255, 0, 0)'], + themed: { label: 'rgb(0, 0, 0)', count: 'rgb(0, 0, 0)', chevron: 'rgb(0, 0, 0)', chevronOpacity: '1' }, + fallback: { label: 'rgb(255, 255, 255)', count: 'rgb(200, 200, 200)', chevron: 'rgb(200, 200, 200)', chevronOpacity: '1' }, + }); + }); + + test('preserves the hover outline after pointer focus and the keyboard focus ring', function () { + // Hidden Electron windows do not match focus pseudo-classes; run this check in a browser. + if (!mainWindow.document.hasFocus()) { + this.skip(); + } + + header.classList.add('hovered'); + container.style.setProperty('--vscode-focusBorder', 'rgb(0, 0, 255)'); + + // Avoid inheriting focus-visible from a previously focused test element. + const activeElement = mainWindow.document.activeElement; + if (activeElement instanceof HTMLElement) { + activeElement.blur(); + } + const pointerFocus = { preventScroll: true, focusVisible: false }; + header.focus(pointerFocus); + const pointer = { + focused: mainWindow.document.activeElement === header, + focusVisible: header.matches(':focus-visible'), + headerOutline: mainWindow.getComputedStyle(header).outlineStyle, + hoverOutline: mainWindow.getComputedStyle(header, '::before').outlineStyle, + }; + + header.blur(); + const keyboardFocus = { preventScroll: true, focusVisible: true }; + header.focus(keyboardFocus); + const keyboard = { + focused: mainWindow.document.activeElement === header, + focusVisible: header.matches(':focus-visible'), + headerOutline: mainWindow.getComputedStyle(header).outlineStyle, + headerOutlineColor: mainWindow.getComputedStyle(header).outlineColor, + hoverOutline: mainWindow.getComputedStyle(header, '::before').outlineStyle, + }; + + assert.deepStrictEqual({ pointer, keyboard }, { + pointer: { focused: true, focusVisible: false, headerOutline: 'none', hoverOutline: 'dashed' }, + keyboard: { focused: true, focusVisible: true, headerOutline: 'solid', headerOutlineColor: 'rgb(0, 0, 255)', hoverOutline: 'none' }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationGroup.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationGroup.test.ts index e1026e71ac26..fea89bc49a91 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationGroup.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationGroup.test.ts @@ -137,7 +137,7 @@ suite('Artifact Integration Groups', () => { ['experiment', 'stepArtifact+scorecard1+scorecard2+stepArtifact2', 'loading1', 'loading2', 'remote', 'stepWithAutopilot']); }); - test('offers Open, the entry actions in pill dropdown order with Pin before Remove, and keeps the dropdown open only for membership changes', () => { + test('offers the entry actions in pill dropdown order with Pin before Remove, and keeps the dropdown open only for membership changes', () => { const action = (id: string): IChatPillAction => toAction({ id, label: id, run: () => { } }); const [copy, changes, pin, remove] = ['copy', 'changes', 'pin', 'remove'].map(action); const entry: IChatPillEntry = { id: 'pr', label: 'Pull request', ariaLabel: 'Open Pull Request', toolbarActions: [changes, copy], promotedAction: remove, open: () => { } }; @@ -148,8 +148,8 @@ suite('Artifact Integration Groups', () => { // Without pinning, such as before a chat is known, and without removal support. minimal: describe({ entry: { ...entry, promotedAction: undefined, toolbarActions: [copy] } }), }, { - full: ['Open Pull Request', 'changes', 'copy', 'pin (stays open)', 'remove (stays open)'], - minimal: ['Open Pull Request', 'copy'], + full: ['changes', 'copy', 'pin (stays open)', 'remove (stays open)'], + minimal: ['copy'], }); }); @@ -250,7 +250,7 @@ suite('Artifact Integration Groups', () => { const active = getActiveElement(); return isHTMLElement(active) ? active.getAttribute('aria-label') ?? active.className : undefined; }; - const keyCodes: Record<string, number> = { ArrowDown: 40, ArrowRight: 39, Escape: 27 }; + const keyCodes: Record<string, number> = { ArrowDown: 40, ArrowRight: 39, Enter: 13, Escape: 27 }; const key = (target: HTMLElement, code: string) => target.dispatchEvent(new KeyboardEvent('keydown', { key: code, code, keyCode: keyCodes[code], bubbles: true, cancelable: true })); return { instantiation, detailsHost, members, models, group, button, dropdown, rows, describeRow, focused, key, toggles, ran, selected, member, hovers }; } @@ -277,15 +277,15 @@ suite('Artifact Integration Groups', () => { opened: { expanded: 'true', header: 'Experiments', rows: [ - { label: '#1', title: 'Title of 1', statuses: ['3/5'], actions: ['Open Title of 1', 'Copy Link 1', 'Pin 1', 'Remove 1'] }, - { label: '#2', title: 'Title of 2', statuses: ['1'], actions: ['Open Title of 2', 'Copy Link 2', 'Pin 2', 'Remove 2'] }, + { label: '#1', title: 'Title of 1', statuses: ['3/5'], actions: ['Copy Link 1', 'Pin 1', 'Remove 1'] }, + { label: '#2', title: 'Title of 2', statuses: ['1'], actions: ['Copy Link 2', 'Pin 2', 'Remove 2'] }, ], - focused: 'Show artifact details: Experiment 1 is running', + focused: 'Open #1', }, }); }); - test('navigates rows and controls with the keyboard, opens details or a status list, and returns focus on Escape', () => { + test('navigates rows and controls with the keyboard, opens the artifact or a status list, and returns focus on Escape', () => { const f = fixture(); f.button().focus(); f.button().click(); @@ -301,21 +301,37 @@ suite('Artifact Integration Groups', () => { const escaped = { open: !!f.dropdown(), focusOnPill: getActiveElement() === f.button(), expanded: f.button().getAttribute('aria-expanded') }; f.button().click(); - f.rows()[1].querySelector<HTMLElement>('.artifact-group-row-title')!.click(); - const afterRow = !!f.dropdown(); + f.key(f.dropdown()!, 'ArrowDown'); + f.key(f.dropdown()!, 'Enter'); + const afterMain = { open: !!f.dropdown(), focusOnPill: getActiveElement() === f.button() }; + f.button().click(); + f.rows()[0].querySelector<HTMLElement>('.artifact-group-row-title')!.click(); + const afterTitle = !!f.dropdown(); f.button().click(); f.rows()[0].querySelector<HTMLElement>('.artifact-group-row-status')!.click(); - assert.deepStrictEqual({ steps, escaped, afterRow, open: !!f.dropdown(), toggles: f.toggles }, { - steps: [ - 'Show artifact details: Experiment 1 is running', - 'Show artifact details: Experiment 2 is running', - 'Show Autopilot: 1 enabled', - 'Show artifact details: Experiment 1 is running', - ], + assert.deepStrictEqual({ steps, escaped, afterMain, afterTitle, open: !!f.dropdown(), ran: f.ran, toggles: f.toggles }, { + steps: ['Open #1', 'Open #2', 'Show Autopilot: 1 enabled', 'Open #1'], escaped: { open: false, focusOnPill: true, expanded: 'false' }, - afterRow: false, + afterMain: { open: false, focusOnPill: true }, + afterTitle: false, + open: false, + ran: ['open.2', 'open.1'], + toggles: [{ id: '1', target: 'pill', selection: ['experiments', 'checks'] }], + }); + }); + + test('a row without status sections offers a Details section that opens the artifact\'s details', () => { + const f = fixture(); + f.members.set([...f.members.get(), f.member(snapshot('3', { groupLabel: 'Experiments' }))], undefined); + f.button().click(); + const details = f.rows()[2].querySelector<HTMLElement>('.artifact-group-row-status')!; + const described = { statuses: f.describeRow(f.rows()[2]).statuses, label: details.getAttribute('aria-label'), icon: !!details.querySelector('.codicon-info') }; + details.click(); + assert.deepStrictEqual({ described, open: !!f.dropdown(), ran: f.ran, toggles: f.toggles }, { + described: { statuses: [''], label: 'Show artifact details: Experiment 3 is running', icon: true }, open: false, - toggles: [{ id: '2', target: 'pill' }, { id: '1', target: 'pill', selection: ['experiments', 'checks'] }], + ran: [], + toggles: [{ id: '3', target: 'pill' }], }); }); @@ -332,22 +348,22 @@ suite('Artifact Integration Groups', () => { tab(); steps.push(f.focused()); assert.deepStrictEqual({ steps, open: !!f.dropdown() }, { - steps: ['Show artifact details: Experiment 1 is running', 'Remove 2', 'Show artifact details: Experiment 1 is running', 'Show details: 3/5 for 1'], + steps: ['Open #1', 'Remove 2', 'Open #1', 'Show details: 3/5 for 1'], open: true, }); }); - test('runs row actions, keeping the dropdown open for pinning and closing it for open and copy', async () => { + test('runs row actions, keeping the dropdown open for pinning and closing it for copy', async () => { const f = fixture(); f.button().click(); const actions = (index: number) => [...f.rows()[index].querySelectorAll<HTMLElement>('.artifact-group-row-action')]; - actions(0)[2].click(); + actions(0)[1].click(); const afterPin = !!f.dropdown(); // The pinned artifact leaves the group while its row has focus; focus moves to a neighbour and the dropdown stays. f.members.set([f.members.get()[1], f.member(snapshot('3', { groupLabel: 'Experiments' }))], undefined); await timeout(0); const updated = { rows: f.rows().map(row => row.querySelector('.artifact-group-row-label')?.textContent), label: f.button().querySelector('.chat-pill-label')?.textContent }; - actions(1)[1].click(); + actions(1)[0].click(); assert.deepStrictEqual({ afterPin, updated, afterCopy: !!f.dropdown(), ran: f.ran }, { afterPin: true, updated: { rows: ['#2', '#3'], label: '2 Experiments' }, afterCopy: false, ran: ['pin.1', 'copy.3'], }); @@ -389,7 +405,7 @@ suite('Artifact Integration Groups', () => { const [one, two, three] = ['1', '2', '3'].map(id => f.member(snapshot(id, { groupLabel: 'Experiments' }))); const reference = f.member(snapshot('ref')); const item = (member: IArtifactIntegrationGroupMember, kind = SessionChatPillKind.Artifacts, isArtifact = true): IArtifactIntegrationPillItem => - ({ entry: member.entry, presentation: member.presentation, kind, isArtifact, visible: true }); + ({ entry: member.entry, presentation: member.presentation, kind, isArtifact, visible: true }); const items = observableValue<readonly IArtifactIntegrationPillItem[]>('items', [item(one), item(reference, SessionChatPillKind.References, false), item(two), item(three)]); const sources = store.add(f.instantiation.createInstance(ArtifactIntegrationPillSources, items, constObservable('chat'), f.detailsHost)); const pills = derived(reader => sources.sources.read(reader).filter(source => source.isVisible?.read(reader) ?? true).flatMap(source => source.pills.read(reader))); @@ -415,7 +431,7 @@ suite('Artifact Integration Groups', () => { test('pill sources group artifacts by group ID across integrations, and apart from other group IDs', () => { const f = fixture(); const withGroupId = (value: ArtifactSnapshot, groupId: string): ArtifactSnapshot => - ({ ...value, contributions: value.contributions.map(contribution => ({ ...contribution, view: { ...contribution.view, groupId } })) }); + ({ ...value, contributions: value.contributions.map(contribution => ({ ...contribution, view: { ...contribution.view, groupId } })) }); const item = (value: ArtifactSnapshot): IArtifactIntegrationPillItem => { const member = f.member(value); return { entry: member.entry, presentation: member.presentation, kind: SessionChatPillKind.Artifacts, isArtifact: true, visible: true }; @@ -440,7 +456,7 @@ suite('Artifact Integration Groups', () => { return f.member({ ...base, contributions: base.contributions.map(contribution => ({ ...contribution, resourceKey })) }); }; const item = (member: IArtifactIntegrationGroupMember, isArtifact: boolean): IArtifactIntegrationPillItem => - ({ entry: member.entry, presentation: member.presentation, kind: isArtifact ? SessionChatPillKind.Artifacts : SessionChatPillKind.References, isArtifact, visible: true }); + ({ entry: member.entry, presentation: member.presentation, kind: isArtifact ? SessionChatPillKind.Artifacts : SessionChatPillKind.References, isArtifact, visible: true }); const items = observableValue<readonly IArtifactIntegrationPillItem[]>('items', [ item(bound('draft', 'experiment/draft'), true), item(bound('scorecard1', 'step'), false), @@ -468,7 +484,7 @@ suite('Artifact Integration Groups', () => { return f.member({ ...base, contributions: base.contributions.map(contribution => ({ ...contribution, resourceKey })) }); }; const item = (member: IArtifactIntegrationGroupMember): IArtifactIntegrationPillItem => - ({ entry: member.entry, presentation: member.presentation, kind: SessionChatPillKind.Artifacts, isArtifact: true, visible: true }); + ({ entry: member.entry, presentation: member.presentation, kind: SessionChatPillKind.Artifacts, isArtifact: true, visible: true }); const items = observableValue<readonly IArtifactIntegrationPillItem[]>('items', [item(bound('a', 'step')), item(bound('b', 'step')), item(bound('c', 'other'))]); const sources = store.add(f.instantiation.createInstance(ArtifactIntegrationPillSources, items, constObservable('chat'), f.detailsHost)); const pills = derived(reader => sources.sources.read(reader).filter(source => source.isVisible?.read(reader) ?? true).flatMap(source => source.pills.read(reader))); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationPresentation.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationPresentation.test.ts index 5c4e292c1976..e1e339c59b0e 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationPresentation.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/artifactIntegrationPresentation.test.ts @@ -403,14 +403,23 @@ suite('Artifact Integration Presentation', () => { f.contextView.layout(); } + /** Opens the whole artifact's details as its Details section does, or a status section's when given. */ async function open(f: Fixture, a: Artifact, section?: number): Promise<HTMLElement> { - (section === undefined ? a.main : a.container.querySelectorAll<HTMLElement>('.artifact-pill-sections [role="button"]')[section]).click(); + if (section === undefined) { + f.controller.toggle(a.presentation, a.main); + } else { + sections(a)[section].click(); + } await settle(f); const panel = f.host.querySelector<HTMLElement>('.artifact-integration-panel'); assert.ok(panel); return panel; } + function sections(a: Artifact): HTMLElement[] { + return [...a.container.querySelectorAll<HTMLElement>('.artifact-pill-sections [role="button"]')]; + } + function button(panel: HTMLElement, label: string): HTMLElement { const result = [...panel.querySelectorAll<HTMLElement>('[role="button"]')].find(button => button.textContent === label || button.getAttribute('aria-label') === label); assert.ok(result, `Missing button: ${label}`); @@ -700,6 +709,31 @@ suite('Artifact Integration Presentation', () => { }); }); + test('omits user clicks on footer actions, even after the integration becomes unavailable, but keeps agent and unreconciled runs', async () => { + const f = fixture(); + const a = f.artifact(); + setActivities(a, [ + activity(a, 'state', { createdAt: 1 }), + activity(a, 'footer', { actionId: 'branch', actionKind: 'code', generalAction: true, createdAt: 2 }), + activity(a, 'agent', { actionId: 'branch', actionKind: 'code', generalAction: true, requestedBy: { kind: 'agent', chat: 'artifact-chat:/agent' }, createdAt: 3 }), + activity(a, 'unknown', { actionId: 'branch', actionKind: 'code', generalAction: true, state: 'interrupted', indeterminate: true, createdAt: 4 }), + ]); + const current = a.snapshot.get(); + // An unavailable integration retains its runs but no longer offers its general actions. + a.snapshot.set({ + ...current, contributions: current.contributions.map(contribution => ({ + ...contribution, view: { ...contribution.view, availability: { kind: 'unavailable', reason: 'Offline' }, stateActions: [], generalActions: [] }, + })), + }, undefined); + const panel = await open(f, a); + await expand(f, panel); + const text = store.add(f.controller.getAccessibilityProvider(AccessibleViewType.View)!).provideContent(); + assert.deepStrictEqual({ + rows: rows(panel).length, + shown: ['state', 'footer', 'agent', 'unknown'].filter(id => text.includes(`Activity ${id}\n`)), + }, { rows: 3, shown: ['state', 'agent', 'unknown'] }); + }); + for (const destination of ['turn', 'queued', 'response'] as const) { test(`reveals a ${destination} destination through Sessions navigation`, async () => { const f = fixture(); @@ -950,8 +984,37 @@ suite('Artifact Integration Presentation', () => { assert.deepStrictEqual({ hover: hover().content, acquired: a.acquired, inline: a.entry.get().inlinePill === a.presentation.inlinePill, labels: [...a.container.querySelectorAll('.chat-pill-label')].map(element => element.textContent), - popup: a.main.getAttribute('aria-haspopup'), expanded: a.main.getAttribute('aria-expanded'), - }, { hover: 'Open: compact status', acquired: [], inline: true, labels: ['#42', '1/2', '1'], popup: 'dialog', expanded: 'false' }); + main: { label: a.main.getAttribute('aria-label'), description: a.main.getAttribute('aria-description'), popup: a.main.getAttribute('aria-haspopup') }, + sections: sections(a).map(section => ({ popup: section.getAttribute('aria-haspopup'), expanded: section.getAttribute('aria-expanded') })), + }, { + hover: 'Open: compact status', acquired: [], inline: true, labels: ['#42', '1/2', '1'], + main: { label: 'Open #42', description: 'Open: compact status', popup: null }, + sections: [{ popup: 'dialog', expanded: 'false' }, { popup: 'dialog', expanded: 'false' }], + }); + }); + + test('the main part opens the resource, and a Details section toggles the details while there are no status sections', async () => { + const f = fixture(); + const a = f.artifact(); + a.main.click(); + await settle(f); + const afterMain = { opens: a.counts().resourceOpens, selected: f.controller.selected.get(), acquired: [...a.acquired] }; + updateContribution(a, c => ({ ...c, view: { ...c.view, sections: [] } })); + const details = sections(a); + details[0].click(); + await settle(f); + const opened = { selected: f.controller.selected.get() === a.presentation, expanded: details[0].getAttribute('aria-expanded') }; + updateContribution(a, c => ({ ...c, view: { ...c.view, sections: [{ id: 'status', icon: { id: 'pass' }, label: '2/2', detailsId: 'checks' }] } })); + assert.deepStrictEqual({ + afterMain, opened, + details: details.map(section => ({ label: section.textContent, ariaLabel: section.getAttribute('aria-label'), icon: !!section.querySelector('.codicon-info') })), + replaced: sections(a).map(section => section.textContent), + }, { + afterMain: { opens: 1, selected: undefined, acquired: [] }, + opened: { selected: true, expanded: 'true' }, + details: [{ label: '', ariaLabel: 'Show artifact details: Open: compact status', icon: true }], + replaced: ['2/2'], + }); }); test('an integration pill shares pointer hovers across its adjacent section buttons', () => { @@ -998,7 +1061,7 @@ suite('Artifact Integration Presentation', () => { }, { beforeDelay: undefined, firstShown: true, sectionShownImmediately: true }); })); - test('main click opens full details; the title navigates and shell actions remain available', async () => { + test('whole-artifact details show the full title, which navigates, and shell actions remain available', async () => { const f = fixture(); const a = f.artifact(); const panel = await open(f, a); @@ -1010,8 +1073,8 @@ suite('Artifact Integration Presentation', () => { assert.deepStrictEqual({ before, after: a.counts(), title: panel.querySelector('h2')?.textContent, description: panel.querySelector('.artifact-details-description-content')?.textContent, - selected: a.container.classList.contains('artifact-pill-selected'), expanded: a.main.getAttribute('aria-expanded'), - controls: a.main.getAttribute('aria-controls'), rootId: panel.parentElement?.id, + selected: a.container.classList.contains('artifact-pill-selected'), expanded: sections(a)[0].getAttribute('aria-expanded'), + controls: sections(a)[0].getAttribute('aria-controls'), rootId: panel.parentElement?.id, acquired: a.acquired, headerActions: [...panel.querySelectorAll('.artifact-header-actions [role="button"]')].map(element => element.getAttribute('aria-label')), footerActions: [...panel.querySelectorAll('.artifact-general-actions [role="button"]')].map(element => element.textContent), @@ -1151,14 +1214,18 @@ suite('Artifact Integration Presentation', () => { ]); }); - test('the active main pill toggles closed; Escape and Close restore focus to the trigger', async () => { + test('the Details section toggles closed; Escape and Close restore focus to the main part', async () => { const f = fixture(); const a = f.artifact(); + updateContribution(a, c => ({ ...c, view: { ...c.view, sections: [] } })); + const [details] = sections(a); const results = []; for (const method of ['toggle', 'escape', 'close']) { - const panel = await open(f, a); + details.click(); + await settle(f); + const panel = f.host.querySelector<HTMLElement>('.artifact-integration-panel')!; if (method === 'toggle') { - a.main.click(); + details.click(); } else if (method === 'escape') { const action = button(panel, 'Fix CI'); action.focus(); @@ -1166,7 +1233,7 @@ suite('Artifact Integration Presentation', () => { } else { button(panel, 'Close Artifact Details').click(); } - results.push({ selected: f.controller.selected.get() !== undefined, focused: getActiveElement() === a.main, expanded: a.main.getAttribute('aria-expanded') }); + results.push({ selected: f.controller.selected.get() !== undefined, focused: getActiveElement() === a.main, expanded: details.getAttribute('aria-expanded') }); } assert.deepStrictEqual(results, Array(3).fill({ selected: false, focused: true, expanded: 'false' })); }); @@ -1177,8 +1244,8 @@ suite('Artifact Integration Presentation', () => { const b = f.artifact('second'); const first = await open(f, a); const root = first.parentElement; - b.main.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true })); - const second = await open(f, b); + sections(b)[0].dispatchEvent(new MouseEvent('pointerdown', { bubbles: true })); + const second = await open(f, b, 0); assert.deepStrictEqual({ sameRoot: second.parentElement === root, contextShows: f.contextShows(), title: second.querySelector('h2')?.textContent, selection: [a, b].map(a => a.container.classList.contains('artifact-pill-selected')), @@ -2000,7 +2067,7 @@ suite('Artifact Integration Presentation', () => { const a = f.artifact(); await open(f, a); f.sentiment.set({ hidden: true }, undefined); - a.main.click(); + sections(a)[0].click(); const hidden = f.controller.selected.get() === undefined; f.sentiment.set({ hidden: false }, undefined); await open(f, a); @@ -2585,8 +2652,9 @@ suite('Artifact Integration Presentation', () => { assert.deepStrictEqual({ states, sameTabs: [...panel.querySelectorAll('[role="tab"]')].every((tab, index) => tab === tabs[index]), - pillSections: a.container.querySelectorAll('.artifact-pill-sections [role="button"]').length, - }, { states: [[true, true], [true, true], [true, true], [true, true]], sameTabs: true, pillSections: 0 }); + // Only the Details section remains to reach the details. + pillSections: sections(a).map(section => section.getAttribute('aria-label')), + }, { states: [[true, true], [true, true], [true, true], [true, true]], sameTabs: true, pillSections: ['Show artifact details: Open: compact status'] }); }); test('tabbed lists retain tabs and controls across refresh and collapse when the selected list is removed', async () => { @@ -2808,18 +2876,29 @@ suite('Artifact Integration Presentation', () => { }); }); - test('Autopilot partial enablement is explicit and failed writes never fabricate saved consent', async () => { + test('Autopilot master is on while any rule is on, revokes only enabled rules, and failed writes keep saved state', async () => { const f = fixture(); const a = f.artifact(); updateContribution(a, contribution => ({ ...contribution, configuration: { ...contribution.configuration, values: { ...contribution.configuration.values, fix: true } } })); const panel = await open(f, a); const master = panel.querySelector<HTMLElement>('.artifact-card-heading [role="switch"]')!; + const summary = () => panel.querySelector('.artifact-autopilot-summary')?.textContent; const before = master.getAttribute('aria-checked'); a.setConfigureResult(Promise.reject(new Error('Consent revision changed'))); master.click(); await settle(f); - assert.deepStrictEqual({ before, after: master.getAttribute('aria-checked'), summary: panel.querySelector('.artifact-autopilot-summary')?.textContent, errors: f.errors, invoked: a.invoked }, { - before: 'false', after: 'false', summary: '1 of 3 on', + const failed = { checked: master.getAttribute('aria-checked'), summary: summary() }; + a.setConfigureResult(Promise.resolve()); + master.click(); + await settle(f); + assert.deepStrictEqual({ before, failed, after: { checked: master.getAttribute('aria-checked'), summary: summary() }, configured: a.configured, errors: f.errors, invoked: a.invoked }, { + before: 'true', + failed: { checked: 'true', summary: '1 of 3 on' }, + after: { checked: 'false', summary: '0 of 3 on' }, + configured: [ + { integrationId: 'test', revision: 4, values: { fix: false } }, + { integrationId: 'test', revision: 4, values: { fix: false } }, + ], errors: ['The artifact operation failed: Consent revision changed'], invoked: [], }); }); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/nestedChatComposer.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/nestedChatComposer.test.ts index b52f14b23197..f2bf16161489 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/nestedChatComposer.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/nestedChatComposer.test.ts @@ -10,6 +10,8 @@ import { IManagedHoverContentOrFactory } from '../../../../../../base/browser/ui import { IHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate.js'; import { getBaseLayerHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate2.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { errorHandler, setUnexpectedErrorHandler } from '../../../../../../base/common/errors.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { constObservable, IObservable, observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; @@ -53,7 +55,7 @@ suite('Sessions - New Nested Session composer', () => { } /** Picks the list entry whose label matches, the way a user does in the action widget. */ - function createControls(value: IObservable<INestedChatWorkspaceSupport | undefined>, folderInfo: INestedChatFolderInfo = git, host: Partial<Pick<INestedChatWorkspaceHost, 'describeFolder' | 'describeNoWorkspace' | 'folderExists'>> & { recentFolders?: readonly URI[] } = {}) { + function createControls(value: IObservable<INestedChatWorkspaceSupport | undefined>, folderInfo: INestedChatFolderInfo = git, host: Partial<Pick<INestedChatWorkspaceHost, 'describeFolder' | 'describeNoWorkspace' | 'folderExists' | 'resolveFolder'>> & { recentFolders?: readonly URI[] } = {}) { let pick: string | undefined; const shown: string[][] = []; const accessibilityProviderKeys: string[][] = []; @@ -102,7 +104,7 @@ suite('Sessions - New Nested Session composer', () => { store.add(toDisposable(() => setupManagedHover.restore())); const controls = store.add(instantiationService.createInstance(NestedChatWorkspaceControls, { support: value, - resolveFolder: async () => folderInfo, + resolveFolder: host.resolveFolder ?? (async () => folderInfo), getBranches: async () => ['main', 'release'], getFolderSources: () => ({ recentFolders: host.recentFolders ?? [URI.file('/recent')], canOpenLocalFolder: true }), describeNoWorkspace: host.describeNoWorkspace ?? (() => getNoWorkspaceChoicePresentation(undefined)), @@ -443,11 +445,116 @@ suite('Sessions - New Nested Session composer', () => { answerAll(); assert.deepStrictEqual({ whileReading, sent: await sent }, { - whileReading: { kind: 'folder', folder: other, isolation: 'folder' }, + whileReading: { kind: 'folder', folder: other, isolation: 'worktree', baseBranch: 'main' }, sent: { kind: 'folder', folder: other, isolation: 'worktree', baseBranch: 'main' }, }); }); + test('keeps repository controls and their selection stable while refreshing the same folder for another harness', async () => { + const answers: ((info: INestedChatFolderInfo) => void)[] = []; + const h = createControls(constObservable(support(repo)), git, { + resolveFolder: () => new Promise(resolve => answers.push(resolve)), + }); + answers.shift()!(git); + await h.controls.resolveWorkspace(); + await h.pickIsolation('New Worktree'); + const before = { state: h.state(), repository: h.repositoryState() }; + + h.controls.refresh(); + const refreshing = { state: h.state(), repository: h.repositoryState() }; + h.controls.refresh(); + const refreshingAgain = { state: h.state(), repository: h.repositoryState() }; + const superseded = answers.shift()!; + answers.shift()!(git); + await h.controls.resolveWorkspace(); + superseded({ supportsWorktree: false, defaultBranch: undefined }); + await Promise.resolve(); + + assert.deepStrictEqual({ + refreshing, + refreshingAgain, + refreshed: { state: h.state(), repository: h.repositoryState() }, + }, { refreshing: before, refreshingAgain: before, refreshed: before }); + }); + + test('a selection made during refresh is not overwritten by the refreshed folder', async () => { + const refreshed = new DeferredPromise<INestedChatFolderInfo>(); + let resolveFolder = async () => git; + const h = createControls(constObservable(support(repo)), git, { resolveFolder: () => resolveFolder() }); + await h.controls.resolveWorkspace(); + await h.pickIsolation('New Worktree'); + resolveFolder = () => refreshed.p; + h.controls.refresh(); + await h.pickIsolation('Branch'); + await refreshed.complete(git); + assert.strictEqual(await h.controls.resolveWorkspace(), undefined); + }); + + test('a send waits for a superseding refresh before using its capabilities or handling its failure', async () => { + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + const errors: Error[] = []; + setUnexpectedErrorHandler(error => errors.push(error)); + const results: { sentBeforeLatest: boolean; workspace: INestedChatWorkspace | undefined; worktreeOffered: boolean }[] = []; + const failure = new Error('Folder resolution failed'); + try { + for (const fails of [false, true]) { + const superseded = new DeferredPromise<INestedChatFolderInfo>(); + const refreshed = new DeferredPromise<INestedChatFolderInfo>(); + let resolveFolder = async () => git; + const h = createControls(constObservable(support(repo)), git, { resolveFolder: () => resolveFolder() }); + await h.controls.resolveWorkspace(); + await h.pickIsolation('New Worktree'); + resolveFolder = () => superseded.p; + h.controls.refresh(); + let sentSettled = false; + const sent = h.controls.resolveWorkspace().then(workspace => { + sentSettled = true; + return workspace; + }); + resolveFolder = () => refreshed.p; + h.controls.refresh(); + await superseded.complete(git); + await new Promise(resolve => setTimeout(resolve, 0)); + const sentBeforeLatest = sentSettled; + if (fails) { + await refreshed.error(failure); + } else { + await refreshed.complete({ supportsWorktree: false, defaultBranch: undefined }); + } + results.push({ sentBeforeLatest, workspace: await sent, worktreeOffered: h.state().worktreeOffered }); + } + } finally { + setUnexpectedErrorHandler(previousHandler); + } + assert.deepStrictEqual({ results, errors }, { + results: [{ sentBeforeLatest: false, workspace: undefined, worktreeOffered: false }, { sentBeforeLatest: false, workspace: undefined, worktreeOffered: false }], + errors: [failure], + }); + }); + + test('a send waits for the latest folder existence check after a refresh is superseded', async () => { + const superseded = new DeferredPromise<boolean>(); + const refreshed = new DeferredPromise<boolean>(); + let folderExists = async () => true; + const h = createControls(constObservable(support(repo)), git, { folderExists: () => folderExists() }); + await h.controls.resolveWorkspace(); + await h.pickIsolation('New Worktree'); + folderExists = () => superseded.p; + h.controls.refresh(); + let sentSettled = false; + const sent = h.controls.resolveWorkspace().then(workspace => { + sentSettled = true; + return workspace; + }); + folderExists = () => refreshed.p; + h.controls.refresh(); + await superseded.complete(true); + await new Promise(resolve => setTimeout(resolve, 0)); + const sentBeforeLatest = sentSettled; + await refreshed.complete(false); + assert.deepStrictEqual({ sentBeforeLatest, workspace: await sent }, { sentBeforeLatest: false, workspace: { kind: 'scratch' } }); + }); + /** The input's shared harness picker, rendering its slot like the real one. */ function fakeHarnessPicker(isVisible: IObservable<boolean>) { return { diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/newWorktreeChoice.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/newWorktreeChoice.test.ts new file mode 100644 index 000000000000..543ca7da0d32 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/newWorktreeChoice.test.ts @@ -0,0 +1,302 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../../base/common/async.js'; +import { CancellationError } from '../../../../../../base/common/errors.js'; +import { constObservable, observableValue } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IChat, ISession, SessionStatus } from '../../../../../services/sessions/common/session.js'; +import { NewWorktreeChoice } from '../../../browser/chat/newWorktreeChoice.js'; +import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; +import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID } from '../../../common/agentHostSessionsProvider.js'; +import { ISessionsProvider } from '../../../common/sessionsProvider.js'; + +suite('NewWorktreeChoice', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + /** + * Drafts of the local agent host, whose isolation starts as its agent remembers it, a new worktree, until their + * configuration resolves; the writes the choice makes apply as the agent takes them, later. + */ + function create(options?: { readOnly?: boolean; synchronous?: boolean; ignoresWrites?: boolean; deferred?: boolean; initial?: string }) { + const values = new Map<string, Record<string, unknown>>(); + const resolved = new Set<string>(); + const writes: string[] = []; + const pending: (() => void)[] = []; + const rejects: (() => void)[] = []; + const provider = upcastPartial<IAgentHostSessionsProvider>({ + id: LOCAL_AGENT_HOST_PROVIDER_ID, + getCreateSessionConfig: sessionId => values.get(sessionId), + getSessionConfig: sessionId => resolved.has(sessionId) ? { + schema: { type: 'object', properties: { isolation: { type: 'string', title: 'Isolation', enum: ['folder', 'worktree'], default: 'folder', readOnly: options?.readOnly } } }, + values: values.get(sessionId) ?? {}, + } : undefined, + setSessionConfigValue: async (sessionId, _chat, property, value) => { + writes.push(`${sessionId}=${value}`); + const apply = () => values.set(sessionId, { ...values.get(sessionId), [property]: value }); + if (options?.ignoresWrites) { + // An agent that keeps its isolation: its configuration resolves again, unchanged, and it tells of it + onDidChangeSessionConfig(); + return; + } + if (options?.deferred) { + // A write the agent does not take, as one it cancels, which is not reported as an unexpected error + return new Promise<void>((_resolve, reject) => rejects.push(() => reject(new CancellationError()))); + } + if (options?.synchronous) { + // As the agent host's provider does: its cache changes and it tells at once, which applies the default + apply(); + onDidChangeSessionConfig(); + } else { + pending.push(apply); + } + }, + trackSessionConfigOperation: () => { }, + }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ISessionsProvidersService, upcastPartial<ISessionsProvidersService>({ getProvider: <T extends ISessionsProvider>() => provider as unknown as T })); + const session = observableValue<ISession | undefined>('session', undefined); + const enabled = observableValue('enabled', true); + const choice = instantiationService.createInstance(NewWorktreeChoice, session, enabled); + // As the composer does on each change of its draft's configuration + const onDidChangeSessionConfig = () => choice.applyDefault(); + const draft = (sessionId: string) => { + values.set(sessionId, { isolation: options?.initial ?? 'worktree' }); + return upcastPartial<ISession>({ + sessionId, + providerId: LOCAL_AGENT_HOST_PROVIDER_ID, + status: constObservable(SessionStatus.Untitled), + mainChat: constObservable(upcastPartial<IChat>({ resource: URI.parse(`test:/${sessionId}`) })), + }); + }; + return { + choice, + enabled, + /** A composer that shows the same drafts again, such as as its editor moves to another group. */ + another: () => instantiationService.createInstance(NewWorktreeChoice, session, enabled), + show: (sessionId: string) => { + const shown = draft(sessionId); + session.set(shown, undefined); + return shown; + }, + /** Shows a draft again, such as one the composer adopts again. */ + showAgain: (shown: ISession) => session.set(shown, undefined), + resolve: (sessionId: string) => resolved.add(sessionId), + applyWrites: () => pending.splice(0).forEach(apply => apply()), + writes, + rejects, + remember: (sessionId: string, isolation: string) => values.set(sessionId, { isolation }), + state: () => ({ available: choice.isAvailable(), selected: choice.isSelected() }), + }; + } + + test('a draft works in its folder by default, also where its agent remembers a new worktree, and in a new worktree once the user chooses one', () => { + const { choice, show, resolve, applyWrites, writes, state } = create(); + show('a'); + // Its configuration is not known yet: nothing to change + choice.applyDefault(); + const unresolved = state(); + resolve('a'); + choice.applyDefault(); + applyWrites(); + const byDefault = state(); + choice.setSelected(true); + applyWrites(); + // As its configuration changes again, the user's choice stays + choice.applyDefault(); + + assert.deepStrictEqual({ unresolved, byDefault, chosen: state(), writes }, { + unresolved: { available: false, selected: false }, + byDefault: { available: true, selected: false }, + chosen: { available: true, selected: true }, + writes: ['a=folder', 'a=worktree'], + }); + }); + + test('the user\'s New Worktree stays where its agent takes it, and tells of the change, at once', () => { + const { choice, show, resolve, writes, state } = create({ synchronous: true }); + show('a'); + resolve('a'); + choice.applyDefault(); + choice.setSelected(true); + + assert.deepStrictEqual({ state: state(), writes }, { state: { available: true, selected: true }, writes: ['a=folder', 'a=worktree'] }); + }); + + test('picking another folder after New Worktree: the folder\'s new draft works in it, as its configuration resolves after the pick', () => { + const { choice, show, resolve, applyWrites, writes, state } = create(); + show('a'); + resolve('a'); + // Chosen where its agent's remembered isolation is a new worktree already: nothing to write + choice.setSelected(true); + applyWrites(); + // The folder is picked: the picker leaves New Worktree, then the folder's draft replaces the first + choice.setSelected(false); + show('b'); + choice.applyDefault(); + const beforeResolved = state(); + resolve('b'); + choice.applyDefault(); + applyWrites(); + + assert.deepStrictEqual({ beforeResolved, afterResolved: state(), writes }, { + beforeResolved: { available: false, selected: false }, + afterResolved: { available: true, selected: false }, + writes: ['a=folder', 'b=folder'], + }); + }); + + test('offers nothing and writes nothing where the isolation is read-only, also from a menu that showed it before', () => { + const { choice, show, resolve, writes, state } = create({ readOnly: true }); + show('a'); + resolve('a'); + choice.setSelected(true); + choice.applyDefault(); + + assert.deepStrictEqual({ state: state(), writes }, { state: { available: false, selected: false }, writes: [] }); + }); + + test('sets a draft to its folder by default once: where its agent keeps a new worktree and tells of it again, it writes no more, and shows the new worktree', async () => { + const { choice, show, resolve, writes, state } = create({ ignoresWrites: true }); + show('a'); + resolve('a'); + choice.applyDefault(); + choice.applyDefault(); + await timeout(0); + + assert.deepStrictEqual({ state: state(), writes }, { state: { available: true, selected: true }, writes: ['a=folder'] }); + }); + + test('tells of what the draft shows as its agent keeps a new worktree after the last change of its configuration, as its write settles', async () => { + const { choice, show, resolve, state } = create({ ignoresWrites: true }); + const shown: boolean[] = []; + store.add(choice.onDidChange(() => shown.push(state().selected))); + show('a'); + resolve('a'); + // The agent tells of its configuration, unchanged, before its write settles: the draft shows as in its folder until then + choice.applyDefault(); + const before = state().selected; + await timeout(0); + + assert.deepStrictEqual({ before, shown, after: state().selected }, { before: false, shown: [true], after: true }); + }); + + test('undoes only the user\'s latest choice as its agent rejects it', async () => { + const { choice, show, resolve, writes, rejects, remember } = create({ deferred: true, initial: 'folder' }); + show('a'); + resolve('a'); + // New Worktree, then the folder and New Worktree again before the agent answers: the user's latest choice stands + // as the agent rejects the first + choice.setSelected(true); + choice.setSelected(false); + choice.setSelected(true); + rejects.shift()!(); + await timeout(0); + remember('a', 'worktree'); + choice.applyDefault(); + const afterStaleRejection = [...writes]; + + // A draft whose latest choice is rejected is as before: it works in its folder by default + show('b'); + resolve('b'); + choice.setSelected(true); + rejects.pop()!(); + await timeout(0); + remember('b', 'worktree'); + choice.applyDefault(); + + assert.deepStrictEqual({ afterStaleRejection, writes }, { + afterStaleRejection: ['a=worktree', 'a=folder', 'a=worktree'], + writes: ['a=worktree', 'a=folder', 'a=worktree', 'b=worktree', 'b=folder'], + }); + }); + + test('keeps what it knows of each draft only as long as the draft: a new draft defaults, also under a known ID, a stale rejection leaves the current draft, and a draft shown again keeps its choice', async () => { + const { choice, show, showAgain, resolve, writes, rejects, remember } = create({ deferred: true, initial: 'folder' }); + resolve('a'); + resolve('b'); + // The user chooses New Worktree for a draft, which the composer then leaves for another before the agent answers + const first = show('a'); + choice.setSelected(true); + const second = show('b'); + choice.setSelected(true); + rejects.shift()!(); + await timeout(0); + // The second draft's choice stands as the first's write is rejected + remember('b', 'worktree'); + choice.applyDefault(); + const afterStaleRejection = [...writes]; + // The first draft, shown again, is as before its rejected choice: it works in its folder by default + showAgain(first); + remember('a', 'worktree'); + choice.applyDefault(); + // A new draft, as after a background send, defaults once again, also where it reuses the ID of one that went + show('a'); + remember('a', 'worktree'); + choice.applyDefault(); + // The second draft, shown again, keeps its choice + showAgain(second); + choice.applyDefault(); + + assert.deepStrictEqual({ afterStaleRejection, writes }, { + afterStaleRejection: ['a=worktree', 'b=worktree'], + writes: ['a=worktree', 'b=worktree', 'a=folder', 'a=folder'], + }); + }); + + test('the user\'s final choice wins where the agent has not taken the earlier ones yet', () => { + const { choice, show, resolve, applyWrites, writes, state } = create({ initial: 'folder' }); + show('a'); + resolve('a'); + choice.setSelected(true); + choice.setSelected(false); + choice.setSelected(true); + const beforeTaken = state(); + applyWrites(); + + assert.deepStrictEqual({ beforeTaken, taken: state(), writes }, { + beforeTaken: { available: true, selected: true }, + taken: { available: true, selected: true }, + writes: ['a=worktree', 'a=folder', 'a=worktree'], + }); + }); + + test('offers nothing and defaults nothing where the composer is not restricted to folders, and does as it becomes restricted', () => { + const { choice, enabled, show, resolve, applyWrites, writes, state } = create(); + show('a'); + resolve('a'); + enabled.set(false, undefined); + choice.applyDefault(); + const unrestricted = state(); + enabled.set(true, undefined); + choice.applyDefault(); + applyWrites(); + + assert.deepStrictEqual({ unrestricted, restricted: state(), writes }, { + unrestricted: { available: false, selected: false }, + restricted: { available: true, selected: false }, + writes: ['a=folder'], + }); + }); + + test('a composer that shows the draft again keeps the user\'s choice, and its default, as another composer', () => { + const { choice, another, show, resolve, applyWrites, writes } = create(); + show('a'); + resolve('a'); + choice.applyDefault(); + choice.setSelected(true); + applyWrites(); + const other = another(); + other.applyDefault(); + applyWrites(); + + assert.deepStrictEqual({ selected: other.isSelected(), writes }, { selected: true, writes: ['a=folder', 'a=worktree'] }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/promptTemplatePlaceholder.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/promptTemplatePlaceholder.test.ts index d052635db08d..ed95fe352b2e 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/promptTemplatePlaceholder.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/promptTemplatePlaceholder.test.ts @@ -9,7 +9,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/ import { Position } from '../../../../../../editor/common/core/position.js'; import { withTestCodeEditor } from '../../../../../../editor/test/browser/testCodeEditor.js'; import { CommandsRegistry } from '../../../../../../platform/commands/common/commands.js'; -import { PromptTemplatePlaceholderController, REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID } from '../../../browser/chat/promptTemplatePlaceholder.js'; +import { PromptTemplatePlaceholderController, registerReplacePromptTemplatePlaceholderCommand, REPLACE_PROMPT_TEMPLATE_PLACEHOLDER_COMMAND_ID } from '../../../browser/chat/promptTemplatePlaceholder.js'; suite('PromptTemplatePlaceholderController', () => { ensureNoDisposablesAreLeakedInTestSuite(); @@ -65,6 +65,7 @@ suite('PromptTemplatePlaceholderController', () => { withTestCodeEditor('Help me complete [describe the coding task] in this project.', {}, editor => { const disposables = new DisposableStore(); try { + disposables.add(registerReplacePromptTemplatePlaceholderCommand()); const placeholder = '[describe the coding task]'; const controller = disposables.add(new PromptTemplatePlaceholderController(editor, () => undefined)); controller.setPlaceholder(placeholder); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArchiveNudge.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArchiveNudge.test.ts index d756590db445..e5135d56383b 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArchiveNudge.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArchiveNudge.test.ts @@ -43,6 +43,7 @@ import { ONBOARDING_DEVELOPER_MODE_CONFIG, ONBOARDING_ENABLED_CONFIG } from '../ import { hashSessionIdForTelemetry } from '../../../common/sessionsTelemetry.js'; import { IChat, IGitHubInfo, IGitHubPullRequestRef, ISession, ISessionArtifact, ISessionWorkspace, SessionArtifactKind, SessionRemoteConnectionStatus, SessionStatus } from '../../../../../services/sessions/common/session.js'; import { ISessionsChangeEvent, ISessionsManagementService } from '../../../common/sessionsManagement.js'; +import { ISessionsService } from '../../../browser/sessionsService.js'; import { IGitHubService } from '../../../browser/github/githubService.js'; import { GitHubPullRequestModel } from '../../../browser/github/models/githubPullRequestModel.js'; import { GitHubPullRequestState, IGitHubPullRequest } from '../../../common/github/types.js'; @@ -90,6 +91,16 @@ suite('SessionArchiveNudge', () => { }(); } + function createPeerChat(path: string, canArchive = true) { + return new class extends mock<IChat>() { + override readonly resource = URI.from({ scheme: 'test-chat', path: `/${path}` }); + override readonly status = observableValue<SessionStatus>(this, SessionStatus.Completed); + override readonly workspace = observableValue<ISessionWorkspace | undefined>(this, undefined); + override readonly isArchived = observableValue(this, false); + override readonly capabilities = constObservable({ canRename: true, canArchive, canDelete: true }); + }(); + } + function pullRequestRef(number: number, overrides: Partial<IGitHubPullRequestRef> = {}): IGitHubPullRequestRef { return { owner: 'owner', repo: 'repo', number, uri: URI.parse(`https://github.com/owner/repo/pull/${number}`), createdByThisSession: true, ...overrides }; } @@ -130,6 +141,7 @@ suite('SessionArchiveNudge', () => { let archiveError: Error | undefined; let archiveNoop = false; const archiveTargets: ISession[] = []; + const chatArchiveTargets: string[] = []; const management = new class extends mock<ISessionsManagementService>() { override readonly onDidArchiveSession = archived.event; override readonly onDidUnarchiveSession = unarchived.event; @@ -146,6 +158,18 @@ suite('SessionArchiveNudge', () => { archived.fire(session); } } + override async archiveChat(session: ISession, chat: IChat): Promise<void> { + chatArchiveTargets.push(chat.resource.path); + if (archiveError) { + throw archiveError; + } + } + }(); + const closedChats: string[] = []; + const sessionsService = new class extends mock<ISessionsService>() { + override async closeChat(session: ISession, chat: IChat): Promise<void> { + closedChats.push(chat.resource.path); + } }(); const requests: string[] = []; const commands: { id: string; args: readonly unknown[] }[] = []; @@ -269,12 +293,12 @@ suite('SessionArchiveNudge', () => { const shownChat = chat ? chat.read(reader) : session?.mainChat.read(reader); return session && shownChat ? { session, chat: shownChat } : undefined; }); - const nudge = store.add(new SessionArchiveNudge(target, configuration, entitlement, github, service, commandService)); + const nudge = store.add(new SessionArchiveNudge(target, configuration, entitlement, github, service, commandService, sessionsService)); store.add(autorun(reader => nudge.options.read(reader))); return nudge; } return { - current, configuration, entitlement, storage, archived, unarchived, deleted, changed, events, requests, archiveTargets, commands, + current, configuration, entitlement, storage, archived, unarchived, deleted, changed, events, requests, archiveTargets, chatArchiveTargets, closedChats, commands, triggers: triggerTelemetry.triggers, get service() { return service; }, get counts() { return { references, polling, refreshes }; }, @@ -293,7 +317,7 @@ suite('SessionArchiveNudge', () => { service.dispose(); service = store.add(new SessionArchiveNudgeService(storage, management, telemetry, configuration, viewsService, onboardingService, chatService)); }, - setArchiveError(error: Error) { archiveError = error; }, + setArchiveError(error: Error | undefined) { archiveError = error; }, setArchiveNoop() { archiveNoop = true; }, setCatalog(next: ISession[], event: ISessionsChangeEvent) { catalog = next; @@ -454,7 +478,7 @@ suite('SessionArchiveNudge', () => { count: nudge.options.get()?.pullRequestCount, requests: context.requests, counts: context.counts, events: context.events, }, { count: 2, requests: ['owner/repo/1', 'owner/repo/2'], counts: { references: 2, polling: 2, refreshes: 2 }, - events: [{ name: 'agents/sessionArchiveNudge', data: { agentSessionId: hashSessionIdForTelemetry(session.sessionId), action: 'shown', pullRequestCount: 2, hasWorktree: false } }], + events: [{ name: 'agents/sessionArchiveNudge', data: { agentSessionId: hashSessionIdForTelemetry(session.sessionId), action: 'shown', pullRequestCount: 2, hasWorktree: false, archivesChat: false } }], }); }); @@ -560,11 +584,7 @@ suite('SessionArchiveNudge', () => { test('scopes pull requests to the chat that recorded them, excluding associations echoed from other chats', () => { const session = createSession(); - const nestedChat = upcastPartial<IChat>({ - resource: URI.from({ scheme: 'test-chat', path: '/nested' }), - status: observableValue<SessionStatus>('nestedStatus', SessionStatus.Completed), - workspace: observableValue<ISessionWorkspace | undefined>('nestedWorkspace', undefined), - }); + const nestedChat = createPeerChat('nested'); session.chats.set([nestedChat], undefined); session.artifacts.set([artifact(1, { chat: nestedChat.resource })], undefined); // Providers echo every chat's records into the workspace associations and can rediscover them from git. @@ -589,6 +609,66 @@ suite('SessionArchiveNudge', () => { }); }); + test('archives and closes only the peer chat showing the suggestion, and the whole session only from its main chat', async () => { + const session = createSession(); + const peer = createPeerChat('peer'); + const unarchivablePeer = createPeerChat('unarchivable', false); + session.chats.set([peer, unarchivablePeer], undefined); + session.artifacts.set([artifact(1), artifact(2, { chat: peer.resource }), artifact(3, { chat: unarchivablePeer.resource })], undefined); + session.workspace.set(upcastPartial<ISessionWorkspace>({ + folders: [{ + root: URI.file('/folder'), workingDirectory: URI.file('/folder'), name: 'folder', description: undefined, + gitRepository: { uri: URI.file('/repo'), workTreeUri: URI.file('/worktree'), baseBranchName: undefined, gitHubInfo: observableValue('gitHubInfo', undefined) }, + }], + isVirtualWorkspace: false, + }), undefined); + const context = setup([session], true, undefined, true); + for (const number of [1, 2, 3]) { + context.setPullRequest(number, GitHubPullRequestState.Merged); + } + const main = context.createNudge(); + const peerNudge = context.createNudge(constObservable(peer)); + const unarchivable = context.createNudge(constObservable(unarchivablePeer)); + const describe = (nudge: SessionArchiveNudge) => { + const options = nudge.options.get(); + return options && { archivesChat: options.archivesChat, hasWorktree: options.hasWorktree }; + }; + const before = { main: describe(main), peer: describe(peerNudge), unarchivable: describe(unarchivable) }; + peerNudge.markShown(); + context.setArchiveError(new Error('Chat archive failed')); + await assert.rejects(peerNudge.options.get()!.onArchive(), /Chat archive failed/); + const closedAfterFailure = [...context.closedChats]; + context.setArchiveError(undefined); + await peerNudge.options.get()!.onArchive(); + peer.isArchived.set(true, undefined); + + assert.deepStrictEqual({ + before, + after: { main: describe(main), peer: describe(peerNudge) }, + chatArchiveTargets: context.chatArchiveTargets, + closedAfterFailure, + closedChats: context.closedChats, + sessionArchiveTargets: context.archiveTargets, + sessionArchived: session.isArchived.get(), + onboarding: context.onboarding.events, + events: context.events.map(event => event.data), + }, { + before: { + main: { archivesChat: false, hasWorktree: true }, + peer: { archivesChat: true, hasWorktree: false }, + unarchivable: undefined, + }, + after: { main: { archivesChat: false, hasWorktree: true }, peer: undefined }, + chatArchiveTargets: ['/peer', '/peer'], + closedAfterFailure: [], + closedChats: ['/peer'], + sessionArchiveTargets: [], + sessionArchived: false, + onboarding: [], + events: ['shown', 'archived'].map(action => ({ agentSessionId: hashSessionIdForTelemetry(session.sessionId), action, pullRequestCount: 1, hasWorktree: false, archivesChat: true })), + }); + }); + test('hides during work, input requests, loading, disconnection, and archiving', () => { const session = createSession(); const context = setup([session]); @@ -808,11 +888,7 @@ suite('SessionArchiveNudge', () => { test('keeps a continued chat suggestion suppressed after another chat shows its own pull requests, including after reload', () => { const session = createSession(); - const nestedChat = upcastPartial<IChat>({ - resource: URI.from({ scheme: 'test-chat', path: '/nested' }), - status: observableValue<SessionStatus>('nestedStatus', SessionStatus.Completed), - workspace: observableValue<ISessionWorkspace | undefined>('nestedWorkspace', undefined), - }); + const nestedChat = createPeerChat('nested'); session.chats.set([nestedChat], undefined); session.artifacts.set([artifact(1), artifact(2, { chat: nestedChat.resource })], undefined); const context = setup([session]); @@ -991,7 +1067,7 @@ suite('SessionArchiveNudge', () => { context.archived.fire(session); nudge.markShown(); await nudge.options.get()!.onArchive(); - const payload = { agentSessionId: hashSessionIdForTelemetry(session.sessionId), pullRequestCount: 1, hasWorktree: false }; + const payload = { agentSessionId: hashSessionIdForTelemetry(session.sessionId), pullRequestCount: 1, hasWorktree: false, archivesChat: false }; assert.deepStrictEqual({ events: context.events, targets: context.archiveTargets.map(target => target.sessionId), diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArtifacts.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArtifacts.test.ts index 77a31e0ad596..3a66fb39d497 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArtifacts.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionArtifacts.test.ts @@ -1094,6 +1094,32 @@ suite('Session Artifacts', () => { }); }); + test('lists references in the references pill whatever their group ID, even when an artifact with a pill of its own presents the same resource', async () => { + const site = (id: string, isArtifact: boolean): ISessionArtifact => ({ id, kind: SessionArtifactKind.Website, label: id, isArtifact, link: URI.parse(`https://example.test/${id}`) }); + const snapshots: Record<string, ArtifactSnapshot> = { + experiment: integratedSnapshot('experiment', 'experiments', { resourceKey: 'experiment' }), + experimentLink: integratedSnapshot('experimentLink', 'experiments', { resourceKey: 'experiment' }), + scorecard: integratedSnapshot('scorecard', 'experiments', { resourceKey: 'step' }), + otherScorecard: integratedSnapshot('otherScorecard', 'experiments', { resourceKey: 'step' }), + commit: integratedSnapshot('commit', undefined, { resourceKey: 'commit' }), + }; + const { presentation } = createPresentation(Object.keys(snapshots).map(id => site(id, id === 'experiment')), + undefined, undefined, undefined, false, undefined, false, id => snapshots[id]); + await timeout(0); + + assert.deepStrictEqual({ + integrated: presentation.integratedEntries.get().map(entry => entry.id), + ownPills: derived(reader => Object.keys(snapshots).filter(id => presentation.hasOwnPill(id, reader))).get(), + ...visibleEntries(presentation), + }, { + integrated: ['experiment'], + ownPills: ['experiment'], + artifacts: [], + // References bound to the same resource as each other show once. + references: ['experimentLink', 'scorecard', 'commit'], + }); + }); + test('retains non-GitHub and noncanonical entries even when their URLs are surfaced', () => { const pullRequest: ISessionArtifact = { id: 'pr', kind: SessionArtifactKind.PullRequest, label: 'PR', isArtifact: true, isGitHub: true, diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionEnvironmentPicker.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionEnvironmentPicker.test.ts index 2e4250599ae0..a236b10c588e 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/sessionEnvironmentPicker.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/sessionEnvironmentPicker.test.ts @@ -11,7 +11,7 @@ import { constObservable, observableValue } from '../../../../../../base/common/ import { URI } from '../../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { ActionListItemKind, IActionListDelegate, IActionListItem } from '../../../../../../platform/actionWidget/browser/actionList.js'; +import { ActionListItemKind, IActionListItemHover } from '../../../../../../platform/actionWidget/browser/actionList.js'; import { IActionWidgetService } from '../../../../../../platform/actionWidget/browser/actionWidget.js'; import { IMenuService, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; import { IMissionControlEnvironmentService, IMissionControlHost } from '../../../../../../platform/agentHost/common/missionControlEnvironment.js'; @@ -46,6 +46,7 @@ suite('SessionEnvironmentPicker', () => { function provider(id: string, environment: string, options: Partial<ISessionsProvider> = {}): ISessionsProvider { return upcastPartial<ISessionsProvider>({ id, environment: { id: environment, label: environment }, label: id, icon: Codicon.remote, + sessionTypes: [{ id: 'test', label: 'Test', icon: Codicon.remote, authRequirement: SessionTypeAuthRequirement.GitHub }], resolveWorkspace: () => workspace, getSessionTypes: () => [], ...options, @@ -94,6 +95,16 @@ suite('SessionEnvironmentPicker', () => { ]); }); + test('preserves the checked workspace provider across provider registration order', () => { + assert.deepStrictEqual([ + getDefaultSessionCreationEnvironment([cloud], folder, 'cloud', false, undefined, true)?.id, + getDefaultSessionCreationEnvironment([cloud, local], folder, 'cloud', false, undefined, true)?.id, + getDefaultSessionCreationEnvironment([local, cloud], folder, 'cloud', false, undefined, true)?.id, + getDefaultSessionCreationEnvironment([local, cloud], folder, LOCAL_AGENT_HOST_PROVIDER_ID, false, undefined, true)?.id, + getDefaultSessionCreationEnvironment([local], folder, 'cloud', false, undefined, true)?.id, + ], ['cloud', 'cloud', 'cloud', 'local', 'local']); + }); + test('Cloud requires a supported session type, not merely a resolvable local folder', () => { const localProvider = provider(LOCAL_AGENT_HOST_PROVIDER_ID, 'local'); const cloudProvider = provider('cloud', 'cloud'); @@ -108,6 +119,15 @@ suite('SessionEnvironmentPicker', () => { ], [LOCAL_AGENT_HOST_PROVIDER_ID, undefined, 'cloud']); }); + test('hides Cloud creation without disabling its workspace browse contributions', () => { + const cloudProvider = provider('cloud', 'cloud', { sessionTypes: [] }); + assert.deepStrictEqual({ + environments: getSessionCreationEnvironments([cloudProvider]), + workspace: cloudProvider.resolveWorkspace(folder), + workspaceSelection: cloudProvider.supportsWorkspaceSelection !== false, + }, { environments: [], workspace, workspaceSelection: true }); + }); + test('connection descriptions use the shared Connected, Connecting and Disconnected labels', () => { const states = [ RemoteAgentHostConnectionStatus.connected, RemoteAgentHostConnectionStatus.connecting, @@ -182,13 +202,18 @@ suite('SessionEnvironmentPicker', () => { let hide: (() => void) | undefined; let accept: ((index: number) => void) | undefined; let labels: (string | undefined)[] = []; + let hovers: IActionListItemHover['content'][] = []; + let ariaLabels: (string | undefined)[] = []; const selected = observableValue<ISessionCreationEnvironment | undefined>('environment', local); const tooltipLabels: string[] = []; instantiation.stub(IActionWidgetService, upcastPartial<IActionWidgetService>({ isVisible: false, hide: () => hide?.(), - show: <T>(_user: string, _preview: boolean, items: IActionListItem<T>[], delegate: IActionListDelegate<T>) => { + show: (...args: Parameters<IActionWidgetService['show']>) => { + const [, , items, delegate, , , , accessibilityProvider] = args; labels = items.map(item => item.label); + hovers = items.map(item => item.hover?.content); + ariaLabels = items.map(item => accessibilityProvider?.getAriaLabel?.(item)?.toString()); hide = () => delegate.onHide(); accept = index => delegate.onSelect(items[index].item!); }, @@ -222,17 +247,83 @@ suite('SessionEnvironmentPicker', () => { assert.deepStrictEqual({ order: container.textContent, labels, + hovers, + ariaLabels, selected: selected.get()?.id, ariaLabel: trigger.getAttribute('aria-label'), expanded: trigger.getAttribute('aria-expanded'), toolbar: !!trigger.closest('.monaco-toolbar'), tooltipLabels, }, { - order: 'CloudRepository', labels: ['This Computer', 'Cloud'], selected: 'cloud', ariaLabel: 'Environment where the agent runs: Cloud', expanded: 'false', toolbar: true, + order: 'CloudRepository', labels: ['This Computer', 'Cloud'], + hovers: ['Run this session directly on this computer', 'Run this session in the cloud on GitHub'], + ariaLabels: ['This Computer, Run this session directly on this computer', 'Cloud, Run this session in the cloud on GitHub'], + selected: 'cloud', ariaLabel: 'Environment where the agent runs: Cloud', expanded: 'false', toolbar: true, tooltipLabels: ['Environment where the agent runs: This Computer', 'Environment where the agent runs: Cloud'], }); }); + test('describes every entry kind in its hover and accessible name', () => { + const instantiation = store.add(new TestInstantiationService()); + const configuration = new TestConfigurationService({ + [RemoteAgentHostsEnabledSettingId]: true, [ENVIRONMENT_PICKER_SETTING]: true, [ENVIRONMENT_PICKER_MANAGE_REMOTES_SETTING]: true, + }); + store.add(configuration.onDidChangeConfigurationEmitter); + instantiation.stub(IConfigurationService, configuration); + const entries: readonly IRemoteAgentHostEntry[] = [ + { name: 'build-box', connection: { type: RemoteAgentHostEntryType.SSH, address: 'ssh:remote', hostName: 'remote' } }, + { name: 'laptop', connection: { type: RemoteAgentHostEntryType.Tunnel, tunnelId: 'remote', clusterId: 'test' } }, + { name: 'Ubuntu', connection: { type: RemoteAgentHostEntryType.WSL, address: 'wsl:Ubuntu', distro: 'Ubuntu' } }, + { name: 'desktop', connection: { type: RemoteAgentHostEntryType.CloudSandbox, address: 'cloudsandbox:remote', environmentId: 'remote', environmentKind: 'user-local' } }, + { name: 'my_host*', connection: { type: RemoteAgentHostEntryType.WebSocket, address: 'ws://localhost:3000' } }, + ]; + const providers = entries.map((entry, index) => upcastPartial<IAgentHostSessionsProvider>({ + ...provider(`agenthost-remote-${index}`, 'remote'), label: entry.name, remoteAddress: getEntryAddress(entry), + connectionStatus: constObservable(RemoteAgentHostConnectionStatus.disconnected), + })); + instantiation.stub(ISessionsProvidersService, { getProvider: <T extends ISessionsProvider>(id: string) => providers.find(provider => provider.id === id) as T | undefined }); + instantiation.stub(IRemoteAgentHostService, { configuredEntries: entries.filter(entry => entry.connection.type !== RemoteAgentHostEntryType.CloudSandbox) }); + instantiation.stub(IMissionControlEnvironmentService, { enabled: true, accountKey: 'account', hosts: constObservable([{ id: 'remote', name: 'desktop', kind: 'user-local', status: 'online' }]) }); + instantiation.stub(ITelemetryService, new TestExperimentTriggerTelemetryService()); + instantiation.stub(IContextKeyService, new MockContextKeyService()); + instantiation.stub(IHoverService, NullHoverService); + instantiation.stub(IKeybindingService, new MockKeybindingService()); + instantiation.stub(ICommandService, {}); + const menuActions = [ + instantiation.createInstance(MenuItemAction, { id: 'test.ssh', title: 'SSH...', tooltip: 'Connect over *SSH*' }, undefined, undefined, undefined, undefined), + instantiation.createInstance(MenuItemAction, { id: 'test.other', title: 'Other...' }, undefined, undefined, undefined, undefined), + ]; + instantiation.stub(IMenuService, { getMenuActions: () => [['navigation', menuActions]] }); + let described: { hover: IActionListItemHover['content']; aria: string | undefined }[] = []; + instantiation.stub(IActionWidgetService, upcastPartial<IActionWidgetService>({ + isVisible: false, + hide: () => { }, + show: (...args: Parameters<IActionWidgetService['show']>) => { + const [, , items, , , , , accessibilityProvider] = args; + described = items.filter(item => item.kind === ActionListItemKind.Action) + .map(item => ({ hover: item.hover?.content, aria: accessibilityProvider?.getAriaLabel?.(item)?.toString() })); + }, + })); + const container: ISessionCreationEnvironment = { id: 'container:local', kind: 'container', label: 'Dev Container', icon: Codicon.remote, providerIds: [LOCAL_AGENT_HOST_PROVIDER_ID] }; + const picker = store.add(instantiation.createInstance(SessionEnvironmentPicker, constObservable([local, cloud, ...getSessionCreationEnvironments(providers), container]), observableValue<ISessionCreationEnvironment | undefined>(store, local), async () => { }, () => [])); + store.add(picker.render(dom.$('div'))); + picker.showPicker(); + const remote = (name: string, hover: string, escaped = hover) => ({ hover: escaped, aria: `${name}, Disconnected, ${hover}` }); + assert.deepStrictEqual(described, [ + { hover: 'Run this session directly on this computer', aria: 'This Computer, Run this session directly on this computer' }, + { hover: 'Run this session in the cloud on GitHub', aria: 'Cloud, Run this session in the cloud on GitHub' }, + remote('build-box', 'Run this session on build-box over SSH'), + remote('laptop', 'Run this session on laptop through a dev tunnel'), + remote('Ubuntu', 'Run this session on Ubuntu in WSL'), + remote('desktop', 'Run this session on desktop, shared through GitHub Environments'), + remote('my_host*', 'Run this session on my_host*', 'Run this session on my\\_host\\*'), + { hover: 'Run this session in a dev container for the selected folder', aria: 'Dev Container, Run this session in a dev container for the selected folder' }, + { hover: 'Connect over \\*SSH\\*', aria: 'SSH..., Connect over *SSH*' }, + { hover: undefined, aria: 'Other...' }, + { hover: 'Add, connect, and manage remote environments', aria: 'Manage Remote Environments..., Add, connect, and manage remote environments' }, + ]); + }); + for (const { remotesEnabled, environmentPickerEnabled } of [false, true].flatMap(remotesEnabled => [false, true].map(environmentPickerEnabled => ({ remotesEnabled, environmentPickerEnabled })))) { for (const manageEnabled of [undefined, false, true]) { test(`Manage visibility follows all gates (remotes: ${remotesEnabled}, picker: ${environmentPickerEnabled}, manage: ${manageEnabled})`, async () => { diff --git a/src/vs/workbench/contrib/sessions/test/browser/chat/sharedChatInputComposer.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chat/sharedChatInputComposer.test.ts index 423337e36f21..9a511e2add5a 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/chat/sharedChatInputComposer.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/chat/sharedChatInputComposer.test.ts @@ -4,10 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import * as dom from '../../../../../../base/browser/dom.js'; import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; -import { DisposableStore, IDisposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { constObservable, observableValue, transaction } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; @@ -33,7 +34,9 @@ import { IEditorGroupsService } from '../../../../../services/editor/common/edit import { IEditorService } from '../../../../../services/editor/common/editorService.js'; import { IViewsService } from '../../../../../services/views/common/viewsService.js'; import { IChatWidget, IQuickChatService } from '../../../../chat/browser/chat.js'; +import { IChatViewHostService } from '../../../../chat/browser/chatViewHost.js'; import { ChatWidgetService } from '../../../../chat/browser/widget/chatWidgetService.js'; +import { ChatInputPart } from '../../../../chat/browser/widget/input/chatInputPart.js'; import { IChatService } from '../../../../chat/common/chatService/chatService.js'; import { ComposerInputSnapshot, IComposerInputSnapshot, IComposerSendAttempt, readNewChatDraftState } from '../../../common/newChatDraftState.js'; import { IChat } from '../../../../../services/sessions/common/session.js'; @@ -77,6 +80,7 @@ suite('SharedChatInputComposer', () => { addContext: (...entries: IChatRequestVariableEntry[]) => { attachments = [...attachments, ...entries]; }, }; const widget: { input: object | undefined;[key: string]: unknown } = { + domNode: dom.$('div'), getInput: () => { assert.ok(widget.input, 'Cannot read the disposed widget input'); return text; @@ -200,6 +204,109 @@ suite('SharedChatInputComposer', () => { } } + for (const [moveFocus, disableMovesFocus] of [[false, false], [true, false], [false, true], [true, true]]) { + test(`restores actual editor focus after rejection without stealing it from another control (moved: ${moveFocus}, toolbar: ${disableMovesFocus})`, async () => { + const root = dom.append(dom.getActiveWindow().document.body, dom.$('div')); + store.add(toDisposable(() => root.remove())); + const editor = dom.append(root, dom.$<HTMLTextAreaElement>('textarea')); + const sendControl = dom.append(root, dom.$('button')); + const otherControl = dom.append(root, dom.$('button')); + const { composer, widget, state } = createComposer({ + sendResult: false, + onSend: () => { + if (moveFocus) { + otherControl.focus(); + } + }, + }); + widget.domNode = root; + Object.assign(widget.input!, { + hasFocus: () => dom.getWindow(editor).document.activeElement === editor, + setInputEnabled: (enabled: boolean) => { + editor.disabled = !enabled; + if (!enabled && disableMovesFocus) { + sendControl.focus(); + } + }, + focus: () => editor.focus(), + }); + editor.focus(); + + const sent = await composer.submit(true); + + assert.deepStrictEqual({ sent, input: state().input.text, focused: dom.getWindow(root).document.activeElement === (moveFocus ? otherControl : editor) }, { + sent: false, input: 'Build it', focused: true, + }); + }); + } + + for (const moveFocus of ['none', 'confirmation', 'send']) { + test(`restores foreground editor focus after confirmation and rejection unless focus moved during ${moveFocus}`, async () => { + const root = dom.append(dom.getActiveWindow().document.body, dom.$('div')); + store.add(toDisposable(() => root.remove())); + const editorHost = dom.append(root, dom.$('div')); + const editor = dom.append(editorHost, dom.$<HTMLTextAreaElement>('textarea')); + const inputActions = dom.append(root, dom.$('div')); + const sendControl = dom.append(root, dom.$('button')); + const otherControl = dom.append(root, dom.$('button')); + const confirmation = new DeferredPromise<boolean>(); + const { composer, widget, state } = createComposer({ + sendResult: false, + confirmSend: confirmation, + onSend: () => { + if (moveFocus === 'send') { + otherControl.focus(); + } + }, + }); + const input: ChatInputPart = Object.assign(Object.create(widget.input!), { + inputEnabled: true, + _inputEditor: { + hasWidgetFocus: () => dom.getWindow(editor).document.activeElement === editor, + updateOptions: ({ readOnly }: { readOnly: boolean }) => { editor.readOnly = readOnly; }, + focus: () => editor.focus(), + }, + _inputEditorElement: editorHost, + attachmentsContainer: dom.append(root, dom.$('div')), + inputActionsToolbar: { getElement: () => inputActions }, + secondaryToolbarContainer: dom.append(root, dom.$('div')), + dnd: { setDisabledOverlay: () => { } }, + executeToolbar: { focus: () => sendControl.focus() }, + setInputEnabled: ChatInputPart.prototype.setInputEnabled, + hasFocus: ChatInputPart.prototype.hasFocus, + focus: ChatInputPart.prototype.focus, + }); + widget.domNode = root; + widget.input = input; + editor.focus(); + + const sending = composer.submit(false); + await timeout(0); + const toolbarFocusedDuringConfirmation = dom.getWindow(root).document.activeElement === sendControl; + if (moveFocus === 'confirmation') { + otherControl.focus(); + } + confirmation.complete(true); + const sent = await sending; + + assert.deepStrictEqual({ + sent, + toolbarFocusedDuringConfirmation, + input: state().input.text, + attachments: state().input.attachments, + readOnly: editor.readOnly, + focused: dom.getWindow(root).document.activeElement === (moveFocus === 'none' ? editor : otherControl), + }, { + sent: false, + toolbarFocusedDuringConfirmation: true, + input: 'Build it', + attachments: ['context'], + readOnly: false, + focused: true, + }); + }); + } + for (const background of [false, true]) { for (const sendResult of [false, new Error('send failed')]) { test(`restores the prompt when the host does not send (${background ? 'background' : 'foreground'}, ${sendResult instanceof Error ? 'error' : 'declined'})`, async () => { @@ -259,6 +366,7 @@ suite('SharedChatInputComposer', () => { instantiationService.stub(IEditorService, {}); instantiationService.stub(IChatService, {}); instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IChatViewHostService, {}); const widgets = store.add(instantiationService.createInstance(ChatWidgetService)); // As a chat widget does: focusing its input counts as its focus. const createWidget = () => { diff --git a/src/vs/workbench/contrib/sessions/test/browser/chatEditor/chatWindowComposer.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/chatWindowComposer.test.ts new file mode 100644 index 000000000000..69190b7218dc --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/chatWindowComposer.test.ts @@ -0,0 +1,675 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; +import { CancellationError } from '../../../../../../base/common/errors.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { DisposableStore, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { constObservable, IObservable, ISettableObservable, observableValue } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INotification, INotificationHandle, INotificationService, NotificationMessage } from '../../../../../../platform/notification/common/notification.js'; +import { IAccessibilityService } from '../../../../../../platform/accessibility/common/accessibility.js'; +import { IClipboardService } from '../../../../../../platform/clipboard/common/clipboardService.js'; +import { IAction } from '../../../../../../base/common/actions.js'; +import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; +import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; +import { IStorageService, StorageScope, StorageTarget, WillSaveStateReason } from '../../../../../../platform/storage/common/storage.js'; +import { TestStorageService } from '../../../../../test/common/workbenchTestServices.js'; +import { parse, stringify } from '../../../../../../base/common/marshalling.js'; +import { Range } from '../../../../../../editor/common/core/range.js'; +import { IAgentHostSessionsProvider } from '../../../common/agentHostSessionsProvider.js'; +import { ISessionsProvider } from '../../../common/sessionsProvider.js'; +import { ISessionGroupsService } from '../../../browser/sessionGroupsService.js'; +import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; +import { IChat, ISession, ISessionWorkspace, SessionStatus } from '../../../../../services/sessions/common/session.js'; +import { ICreateNewSessionSlotOptions, INewSessionDraftSlot, INewSessionRequestAcceptedEvent, INewSessionRequestEndedEvent, ISessionsManagementService, WorkspaceNotTrustedError } from '../../../common/sessionsManagement.js'; +import { IChatRequestVariableEntry } from '../../../../chat/common/attachments/chatVariableEntries.js'; +import { ChatDynamicVariableModel } from '../../../../chat/browser/attachments/chatDynamicVariables.js'; +import { IDynamicVariable } from '../../../../chat/common/attachments/chatVariables.js'; +import { SharedChatInputComposer } from '../../../browser/chat/sharedChatInputComposer.js'; +import { CHAT_WINDOW_COMPOSERS_STORAGE_KEY, ChatWindowComposerBackgroundSends, ChatWindowComposerModel, ChatWindowComposers, getChatWindowComposerTarget } from '../../../browser/chatEditor/chatWindowComposer.js'; + +suite('Chat window composer', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function createSession(sessionId: string, options?: { readonly folder?: string; readonly quickChat?: boolean; readonly providerId?: string; readonly status?: IObservable<SessionStatus> }): ISession { + const main = new class extends mock<IChat>() { + override readonly resource = URI.parse(`test:/${sessionId}-main`); + override readonly modelId = constObservable('model'); + override readonly mode = constObservable({ id: 'agent', kind: 'agent' }); + }(); + const folder = options?.folder; + return new class extends mock<ISession>() { + override readonly sessionId = sessionId; + override readonly resource = URI.parse(`test:/${sessionId}`); + override readonly providerId = options?.providerId ?? 'provider'; + override readonly sessionType = 'type'; + override readonly status = options?.status ?? constObservable(SessionStatus.Untitled); + override readonly workspace = constObservable(folder ? upcastPartial<ISessionWorkspace>({ uri: URI.file(folder), label: folder.slice(1) }) : undefined); + override readonly isQuickChat = constObservable(!!options?.quickChat); + override readonly mainChat = constObservable(main); + }(); + } + + function createServices(store: DisposableStore, sessions: readonly ISession[] = []) { + const events: string[] = []; + const onDidAccept = store.add(new Emitter<INewSessionRequestAcceptedEvent>()); + const onDidEnd = store.add(new Emitter<INewSessionRequestEndedEvent>()); + const onDidReplace = store.add(new Emitter<{ readonly from: ISession; readonly to: ISession }>()); + const slots: { readonly slot: INewSessionDraftSlot & { readonly newSession: ISettableObservable<ISession | undefined> }; readonly options?: ICreateNewSessionSlotOptions }[] = []; + /** The actions of the last notification with actions. */ + const actions: IAction[] = []; + const notifications = new class extends TestNotificationService { + override error(message: NotificationMessage): INotificationHandle { + events.push(`error: ${message}`); + return super.error(message); + } + override info(message: NotificationMessage): INotificationHandle { + events.push(`info: ${message}`); + return super.info(message); + } + override notify(notification: INotification): INotificationHandle { + // Those with actions; `error` notifies through here too. + if (notification.actions) { + actions.splice(0, actions.length, ...(notification.actions.primary ?? [])); + events.push(`notify: ${notification.message} [${actions.map(action => action.label).join(', ')}]`); + } + return super.notify(notification); + } + }(); + + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(INotificationService, notifications); + instantiationService.stub(IAccessibilityService, new class extends mock<IAccessibilityService>() { + override status(message: string) { events.push(`status: ${message}`); } + }()); + instantiationService.stub(IClipboardService, new class extends mock<IClipboardService>() { + override async writeText(text: string) { events.push(`copied: ${text}`); } + }()); + const storageService = store.add(new TestStorageService()); + instantiationService.stub(IStorageService, storageService); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(ISessionsProvidersService, new class extends mock<ISessionsProvidersService>() { + // The local agent host, whose drafts can run in a Dev Container + override getProvider<T extends ISessionsProvider>(providerId: string): T | undefined { + return providerId === 'local-agent-host' ? upcastPartial<IAgentHostSessionsProvider>({ id: providerId, isDevContainerRequested: () => true }) as ISessionsProvider as T : undefined; + } + }()); + instantiationService.stub(ISessionGroupsService, new class extends mock<ISessionGroupsService>() { + override setDraftSlotGroup(slotId: string, groupId: string | undefined) { + events.push(`group ${slotId} ${groupId}`); + return toDisposable(() => events.push(`ungroup ${slotId}`)); + } + }()); + const sessionsManagementService = new class extends mock<ISessionsManagementService>() { + override readonly onDidAcceptNewSessionRequest = onDidAccept.event; + override readonly onDidEndNewSessionRequest = onDidEnd.event; + override readonly onDidReplaceNewDraftSession = onDidReplace.event; + override readonly onDidReplaceSession = Event.None; + override getNewSessionTarget() { return undefined; } + override getSession(resource: URI) { return sessions.find(session => session.resource.toString() === resource.toString()); } + override isNewSessionTargetAvailable(_folder: URI, target: { readonly providerId: string }) { return target.providerId !== 'unavailable'; } + override createNewSessionSlot(options?: ICreateNewSessionSlotOptions) { + const id = `slot${slots.length + 1}`; + const slot = new class extends mock<INewSessionDraftSlot & { readonly newSession: ISettableObservable<ISession | undefined>; dispose(): void }>() { + override readonly id = id; + override readonly newSession = observableValue<ISession | undefined>(this, undefined); + override dispose() { events.push(`dispose ${id}`); } + }(); + slots.push({ slot, options }); + return slot; + } + }(); + instantiationService.stub(ISessionsManagementService, sessionsManagementService); + const backgroundSends = store.add(instantiationService.createInstance(ChatWindowComposerBackgroundSends)); + const createComposer = (target = { folderUri: URI.file('/repo'), providerId: 'provider', sessionTypeId: 'type' }) => instantiationService.createInstance(ChatWindowComposerModel, URI.parse('vscode-agents-composer:/1'), { target, groupId: 'group' }, backgroundSends, async () => { }); + return { events, actions, onDidAccept, onDidEnd, onDidReplace, slots, sessionsManagementService, backgroundSends, createComposer, sessionsProvidersService: instantiationService.get(ISessionsProvidersService), instantiationService, storageService }; + } + + test('a composer starts its session as the chat it opened from: the session\'s folder, provider and agent where they serve the folder, and the chat\'s model and mode; a Dev Container it runs in; a quick chat\'s provider and agent with no workspace; nothing without a session or a workspace', () => { + const store = disposables.add(new DisposableStore()); + const { sessionsManagementService, sessionsProvidersService } = createServices(store); + const target = (session: ISession | undefined) => getChatWindowComposerTarget(sessionsManagementService, sessionsProvidersService, session, session?.mainChat.get()); + + assert.deepStrictEqual({ + workspace: target(createSession('workspace', { folder: '/repo' })), + unavailable: target(createSession('unavailable', { folder: '/repo', providerId: 'unavailable' })), + devContainer: target(createSession('container', { folder: '/repo', providerId: 'local-agent-host' })), + quickChat: target(createSession('quick', { quickChat: true })), + noWorkspace: target(createSession('none')), + noSession: target(undefined), + }, { + workspace: { folderUri: URI.file('/repo'), providerId: 'provider', sessionTypeId: 'type', modelId: 'model', modeId: 'agent' }, + unavailable: { folderUri: URI.file('/repo'), modelId: 'model', modeId: 'agent' }, + devContainer: { folderUri: URI.file('/repo'), providerId: 'local-agent-host', sessionTypeId: 'type', requireDevContainer: true, modelId: 'model', modeId: 'agent' }, + quickChat: { providerId: 'provider', sessionTypeId: 'type', modelId: 'model', modeId: 'agent' }, + noWorkspace: undefined, + noSession: undefined, + }); + }); + + test('a composer holds its drafts in a slot of its own, whose sends join its group; it shows the session of a foreground send until it ends, retries a failed draft only while what it aims for did not change since it sent it, also a draft of the folder without its URI, and closing it discards only its slot', () => { + const store = disposables.add(new DisposableStore()); + const { events, onDidAccept, onDidEnd, onDidReplace, slots, createComposer } = createServices(store); + const composer = createComposer(); + const { slot, options } = slots[0]; + const draft = createSession('draft', { folder: '/repo' }); + slot.newSession.set(draft, undefined); + const shown = () => composer.session.get()?.sessionId; + + const showsDraft = shown(); + onDidAccept.fire({ session: draft, owner: slot, background: true }); + slot.newSession.set(undefined, undefined); + const afterBackground = shown(); + slot.newSession.set(draft, undefined); + onDidAccept.fire({ session: draft, owner: slot, background: false }); + slot.newSession.set(undefined, undefined); + const sending = shown(); + const prepared = createSession('prepared', { folder: '/repo' }); + onDidReplace.fire({ from: draft, to: prepared }); + const afterReplace = shown(); + onDidEnd.fire({ session: prepared, owner: slot, started: false, readopted: false }); + const afterFailure = shown(); + // A cloud agent's draft of the folder is of its GitHub repository, not of the folder's URI. + const unchanged = options?.readoptOnFailure?.(createSession('cloud', { folder: '/owner/repo/HEAD', providerId: 'cloud' })); + composer.setRequestedTarget({ folderUri: URI.file('/other'), providerId: 'provider', sessionTypeId: 'type' }); + const readopt = { unchanged, afterAnotherTarget: options?.readoptOnFailure?.(prepared) }; + composer.dispose(); + + assert.deepStrictEqual({ showsDraft, afterBackground, sending, afterReplace, afterFailure, readopt, events }, { + showsDraft: 'draft', + afterBackground: undefined, + sending: 'draft', + afterReplace: 'prepared', + afterFailure: undefined, + readopt: { unchanged: true, afterAnotherTarget: false }, + events: ['group slot1 group', 'dispose slot1', 'ungroup slot1'], + }); + }); + + test('a foreground send that starts its session fires once, with the started session, which the composer shows until its chat takes over', () => { + const store = disposables.add(new DisposableStore()); + const { onDidAccept, onDidEnd, onDidReplace, slots, createComposer } = createServices(store); + const composer = store.add(createComposer()); + const { slot } = slots[0]; + const draft = createSession('draft', { folder: '/repo' }); + const started: string[] = []; + store.add(composer.onDidStart(session => started.push(session.sessionId))); + onDidAccept.fire({ session: draft, owner: slot, background: false }); + onDidEnd.fire({ session: createSession('other'), owner: slot, started: true, readopted: false }); + const startedSession = createSession('started', { folder: '/repo' }); + onDidReplace.fire({ from: draft, to: startedSession }); + onDidEnd.fire({ session: startedSession, owner: slot, started: true, readopted: false }); + onDidEnd.fire({ session: startedSession, owner: slot, started: true, readopted: false }); + + assert.deepStrictEqual({ started, shown: composer.session.get()?.sessionId }, { started: ['started'], shown: 'started' }); + }); + + test('a failed background send is reported once, also after its composer is gone, following the draft\'s replacements; not when it started, was cancelled, or was not dispatched', () => { + const store = disposables.add(new DisposableStore()); + const { events, onDidEnd, onDidReplace, slots, createComposer } = createServices(store); + const composer = createComposer(); + const { slot } = slots[0]; + const send = (sessionId: string) => { + const session = createSession(sessionId, { folder: '/repo' }); + return { session, tracked: composer.trackBackgroundSend({ session, query: 'hello', attachedContext: undefined, requestedInBackground: true, isLatest: () => true }) }; + }; + const failed = send('failed'); + const replaced = send('replaced'); + const startedSend = send('started'); + const cancelled = send('cancelled'); + const notDispatched = send('notDispatched'); + notDispatched.tracked.dispose(); + composer.dispose(); + events.length = 0; + + const to = createSession('replacement'); + onDidReplace.fire({ from: replaced.session, to }); + onDidEnd.fire({ session: failed.session, owner: slot, started: false, readopted: false, error: new Error('no agent') }); + onDidEnd.fire({ session: failed.session, owner: slot, started: false, readopted: false, error: new Error('again') }); + onDidEnd.fire({ session: to, owner: slot, started: false, readopted: false, error: new Error('replaced failed') }); + onDidEnd.fire({ session: startedSend.session, owner: slot, started: true, readopted: false }); + onDidEnd.fire({ session: cancelled.session, owner: slot, started: false, readopted: false, error: new CancellationError() }); + onDidEnd.fire({ session: notDispatched.session, owner: slot, started: false, readopted: false, error: new Error('not dispatched') }); + + assert.deepStrictEqual(events, ['notify: Couldn\'t start the session in repo with type: no agent [Copy Prompt]', 'notify: Couldn\'t start the session in No Workspace with type: replaced failed [Copy Prompt]']); + }); + + test('a failed background send gives its prompt back to its composer when nothing changed there, announcing it; once the user typed, picked another target or sent again, it offers Restore Prompt, which keeps the current target, and Copy Prompt; only Copy Prompt once the composer is gone; Restore Prompt never replaces what the user wrote since, copying the prompt instead', async () => { + const store = disposables.add(new DisposableStore()); + const { events, actions, onDidEnd, slots, createComposer } = createServices(store); + const composer = store.add(createComposer()); + const { slot } = slots[0]; + events.length = 0; + const written = { inputText: '#attachment:index.ts fix it', attachments: [], references: [{ id: 'a', range: new Range(1, 1, 1, 21), data: URI.file('/repo/index.ts') }] }; + const restored: string[] = []; + store.add(composer.input.registerRestorer(draft => { restored.push(draft.inputText); return true; })); + let latest = true; + // As the composer sends in the background: it records what was written, clears its input, and sends. + const send = (name: string) => { + const attempt = composer.input.beginSendAttempt(written); + composer.input.set({ inputText: '', attachments: [] }); + const session = createSession(name, { folder: '/repo' }); + composer.trackBackgroundSend({ session, query: 'fix it', attachedContext: undefined, requestedInBackground: true, isLatest: () => latest }); + composer.input.endSendAttempt(attempt); + return session; + }; + const fail = (session: ISession) => onDidEnd.fire({ session, owner: slot, started: false, readopted: false, error: new Error('no agent') }); + + fail(send('idle')); + const silently = { input: composer.input.get().input, restored: [...restored], events: events.splice(0) }; + composer.input.set({ inputText: '', attachments: [] }); + const retargeted = send('retargeted'); + composer.setRequestedTarget({ folderUri: URI.file('/other') }); + fail(retargeted); + const afterRetarget = { input: composer.input.get().input.inputText, events: events.splice(0) }; + await actions[0].run(); + await actions[1].run(); + const afterActions = { input: composer.input.get().input.inputText, target: composer.requestedTarget.get()?.folderUri?.path, events: events.splice(0) }; + composer.input.set({ inputText: '', attachments: [] }); + const typedOver = send('typed'); + composer.input.set({ inputText: 'next', attachments: [] }); + fail(typedOver); + // Restore Prompt never replaces what the user wrote since. + await actions[0].run(); + const typedKept = composer.input.get().input.inputText; + composer.input.set({ inputText: '', attachments: [] }); + const superseded = send('superseded'); + latest = false; + fail(superseded); + latest = true; + const gone = send('gone'); + composer.dispose(); + fail(gone); + + assert.deepStrictEqual({ silently, afterRetarget, afterActions, typedKept, rest: events, restored }, { + silently: { input: written, restored: ['#attachment:index.ts fix it'], events: ['error: Couldn\'t start the session: no agent', 'status: The prompt of the session that couldn\'t start is back in the composer.'] }, + afterRetarget: { input: '', events: ['notify: Couldn\'t start the session in repo with type: no agent [Restore Prompt, Copy Prompt]'] }, + afterActions: { input: '#attachment:index.ts fix it', target: '/other', events: ['copied: #attachment:index.ts fix it'] }, + typedKept: 'next', + rest: [ + 'notify: Couldn\'t start the session in repo with type: no agent [Restore Prompt, Copy Prompt]', + 'copied: #attachment:index.ts fix it', + 'info: The composer can\'t take the prompt back now, so it was copied to the clipboard instead.', + 'notify: Couldn\'t start the session in repo with type: no agent [Restore Prompt, Copy Prompt]', + 'dispose slot1', + 'ungroup slot1', + 'notify: Couldn\'t start the session in repo with type: no agent [Copy Prompt]', + ], + restored: ['#attachment:index.ts fix it', '#attachment:index.ts fix it'], + }); + }); + + test('an ordinary send that the composer sent in the background and the user did not start, by declining to trust its workspace or cancelling it, gives its prompt back without an error, with its inline references; once the user typed, it offers Restore Prompt and Copy Prompt; one the user sent in the background gives nothing back', async () => { + const store = disposables.add(new DisposableStore()); + const { events, actions, onDidEnd, slots, createComposer } = createServices(store); + const composer = store.add(createComposer()); + const { slot } = slots[0]; + events.length = 0; + const written = { inputText: '#attachment:index.ts fix it', attachments: [], references: [{ id: 'a', range: new Range(1, 1, 1, 21), data: URI.file('/repo/index.ts') }] }; + store.add(composer.input.registerRestorer(() => true)); + // As the composer sends in the background: it records what was written, clears its input, and sends. + const send = (name: string, requestedInBackground: boolean) => { + const attempt = composer.input.beginSendAttempt(written); + composer.input.set({ inputText: '', attachments: [] }); + const session = createSession(name, { folder: '/repo' }); + composer.trackBackgroundSend({ session, query: 'fix it', attachedContext: undefined, requestedInBackground, isLatest: () => true }); + composer.input.endSendAttempt(attempt); + return session; + }; + const end = (session: ISession, error: unknown) => onDidEnd.fire({ session, owner: slot, started: false, readopted: false, error }); + + end(send('untrusted', false), new WorkspaceNotTrustedError()); + const untrusted = { input: composer.input.get().input, events: events.splice(0) }; + composer.input.set({ inputText: '', attachments: [] }); + end(send('cancelled', false), new CancellationError()); + const cancelled = { input: composer.input.get().input.inputText, events: events.splice(0) }; + composer.input.set({ inputText: '', attachments: [] }); + const typedOver = send('typed', false); + composer.input.set({ inputText: 'next', attachments: [] }); + end(typedOver, new CancellationError()); + const typed = { input: composer.input.get().input.inputText, events: events.splice(0) }; + await actions[1].run(); + const copied = events.splice(0); + composer.input.set({ inputText: '', attachments: [] }); + end(send('requested', true), new WorkspaceNotTrustedError()); + const requested = { input: composer.input.get().input.inputText, events: events.splice(0) }; + + assert.deepStrictEqual({ untrusted, cancelled, typed, copied, requested }, { + untrusted: { input: written, events: ['status: The prompt of the session that wasn\'t started is back in the composer.'] }, + cancelled: { input: '#attachment:index.ts fix it', events: ['status: The prompt of the session that wasn\'t started is back in the composer.'] }, + typed: { input: 'next', events: ['notify: The session in repo with type wasn\'t started. [Restore Prompt, Copy Prompt]'] }, + copied: ['copied: #attachment:index.ts fix it'], + requested: { input: '', events: [] }, + }); + }); + + test('a background send that fails while the composer\'s input still sends, such as while it reseeds after the send was accepted, is not reported as given back: its prompt stays in the notification, which restores it once the input shows it, and copies it while the input cannot; one that fails once the input is idle shows in the input', async () => { + const store = disposables.add(new DisposableStore()); + const { events, actions, onDidAccept, onDidEnd, slots, createComposer } = createServices(store); + const composer = store.add(createComposer()); + const { slot } = slots[0]; + events.length = 0; + + // The composer's shared input, tracking the host's snapshot as it does once rendered, over a widget that keeps its state. + const changed = store.add(new Emitter<void>()); + const state: { text: string; attachments: IChatRequestVariableEntry[]; references: IDynamicVariable[] } = { text: '', attachments: [], references: [] }; + const widget = { + getInput: () => state.text, + setInput: (value: string) => { state.text = value; changed.fire(); }, + inputEditor: { onDidChangeModelContent: changed.event, getModel: () => undefined }, + attachmentModel: { + get attachments() { return state.attachments; }, + onDidChange: changed.event, + addContext: (...entries: IChatRequestVariableEntry[]) => { state.attachments = [...state.attachments, ...entries]; changed.fire(); }, + clearAndSetContext: (...entries: IChatRequestVariableEntry[]) => { state.attachments = entries; changed.fire(); }, + }, + getContrib: () => ({ + get variables() { return state.references; }, + onDidChangeReferences: changed.event, + setInputState: (inputState: Record<string, unknown>) => { state.references = inputState[ChatDynamicVariableModel.ID] as IDynamicVariable[]; changed.fire(); }, + }), + input: { get attachmentModel() { return widget.attachmentModel; }, inlineAttachments: undefined }, + }; + const sending = observableValue('sending', false); + const input = Object.assign(Object.create(SharedChatInputComposer.prototype), { + _widget: widget, _sending: sending, _pendingAttachments: [], options: { session: constObservable(undefined), inputSnapshot: composer.input }, + }) as SharedChatInputComposer; + store.add(Reflect.get(SharedChatInputComposer.prototype, '_trackInputSnapshot').call(input, widget) as IDisposable); + + const attachment = upcastPartial<IChatRequestVariableEntry>({ id: 'file', name: 'index.ts', kind: 'file', value: URI.file('/repo/index.ts') }); + const reference: IDynamicVariable = { id: 'a', range: new Range(1, 1, 1, 21), data: URI.file('/repo/index.ts') }; + const shown = () => ({ text: state.text, attachments: state.attachments.map(entry => entry.id), references: state.references.map(entry => entry.id), snapshot: composer.input.get().input.inputText, attempt: !!composer.input.get().attempt }); + // As the input sends in the background: it records what was written, clears itself, and sends; its send is accepted, which + // ends the attempt, while the input still sends until it reseeds. + const send = (name: string) => { + state.text = '#attachment:index.ts fix it'; state.attachments = [attachment]; state.references = [reference]; changed.fire(); + sending.set(true, undefined); + composer.input.beginSendAttempt({ inputText: state.text, attachments: [...state.attachments], references: [...state.references] }); + state.text = ''; state.attachments = []; state.references = []; changed.fire(); + const session = createSession(name, { folder: '/repo' }); + composer.trackBackgroundSend({ session, query: 'fix it', attachedContext: undefined, requestedInBackground: true, isLatest: () => true }); + onDidAccept.fire({ session, owner: slot, background: true }); + return session; + }; + const fail = (session: ISession) => onDidEnd.fire({ session, owner: slot, started: false, readopted: false, error: new Error('no agent') }); + + fail(send('while reseeding')); + const whileSending = { input: shown(), events: events.splice(0) }; + // Restore Prompt while the input still sends: copied, never lost in an input that does not show it. + await actions[0].run(); + const restoreWhileSending = { input: shown(), events: events.splice(0) }; + // The reseed ends: nothing shows by itself, the notification still has it. + sending.set(false, undefined); + const reseeded = shown(); + await actions[0].run(); + const restoreOnceIdle = { input: shown(), events: events.splice(0) }; + + // A send that fails once the input is idle: given back, and the input shows it. + state.text = ''; state.attachments = []; state.references = []; changed.fire(); + const idle = send('idle'); + sending.set(false, undefined); + fail(idle); + const givenBack = { input: shown(), events: events.splice(0) }; + + const prompt = { text: '#attachment:index.ts fix it', attachments: ['file'], references: ['a'], snapshot: '#attachment:index.ts fix it', attempt: false }; + const empty = { text: '', attachments: [], references: [], snapshot: '', attempt: false }; + assert.deepStrictEqual({ whileSending, restoreWhileSending, reseeded, restoreOnceIdle, givenBack }, { + whileSending: { input: empty, events: ['notify: Couldn\'t start the session in repo with type: no agent [Restore Prompt, Copy Prompt]'] }, + restoreWhileSending: { input: empty, events: ['copied: #attachment:index.ts fix it', 'info: The composer can\'t take the prompt back now, so it was copied to the clipboard instead.'] }, + reseeded: empty, + restoreOnceIdle: { input: prompt, events: [] }, + givenBack: { input: prompt, events: ['error: Couldn\'t start the session: no agent', 'status: The prompt of the session that couldn\'t start is back in the composer.'] }, + }); + }); + + test('a background send that fails while no input of the composer shows, such as before its input renders or once it went, is not reported as given back: the snapshot does not take its prompt, which the notification offers to restore once an input shows and copies until then', async () => { + const store = disposables.add(new DisposableStore()); + const { events, actions, onDidEnd, slots, createComposer } = createServices(store); + const composer = store.add(createComposer()); + const { slot } = slots[0]; + events.length = 0; + const written = { inputText: 'fix it', attachments: [] }; + const send = (name: string) => { + const attempt = composer.input.beginSendAttempt(written); + composer.input.set({ inputText: '', attachments: [] }); + const session = createSession(name, { folder: '/repo' }); + composer.trackBackgroundSend({ session, query: 'fix it', attachedContext: undefined, requestedInBackground: true, isLatest: () => true }); + composer.input.endSendAttempt(attempt); + return session; + }; + const fail = (session: ISession) => onDidEnd.fire({ session, owner: slot, started: false, readopted: false, error: new Error('no agent') }); + + // Before an input registers. + fail(send('unrendered')); + const unrendered = { snapshot: composer.input.get().input.inputText, events: events.splice(0) }; + await actions[0].run(); + const restoreUnrendered = { snapshot: composer.input.get().input.inputText, events: events.splice(0) }; + // Once its input went: its registration is disposed. + const shownBy: string[] = []; + store.add(composer.input.registerRestorer(() => true)).dispose(); + fail(send('gone input')); + const goneInput = { snapshot: composer.input.get().input.inputText, events: events.splice(0) }; + // An input shows again: Restore Prompt gives it back there. + store.add(composer.input.registerRestorer(draft => { shownBy.push(draft.inputText); return true; })); + await actions[0].run(); + const restoreShown = { snapshot: composer.input.get().input.inputText, events: events.splice(0), shownBy }; + + const offered = ['notify: Couldn\'t start the session in repo with type: no agent [Restore Prompt, Copy Prompt]']; + assert.deepStrictEqual({ unrendered, restoreUnrendered, goneInput, restoreShown }, { + unrendered: { snapshot: '', events: offered }, + restoreUnrendered: { snapshot: '', events: ['copied: fix it', 'info: The composer can\'t take the prompt back now, so it was copied to the clipboard instead.'] }, + goneInput: { snapshot: '', events: offered }, + restoreShown: { snapshot: 'fix it', events: [], shownBy: ['fix it'] }, + }); + }); + + test('a composer of a window with folders creates sessions only in them and in the folder it aims at; one of a window without folders anywhere', () => { + const store = disposables.add(new DisposableStore()); + const { instantiationService } = createServices(store); + const composers = store.add(instantiationService.createInstance(ChatWindowComposers, async () => undefined)); + const windowFolders = observableValue<readonly URI[]>('windowFolders', [URI.file('/repo')]); + const allowed = (target: string | undefined) => { + const composer = store.add(composers.create(URI.parse(`vscode-agents-composer:/${target ?? 'none'}`), { target: target ? { folderUri: URI.file(target) } : undefined, allowedFolders: windowFolders }, async () => { })); + return composer.allowedFolders?.get().map(folder => folder.path); + }; + const inWindow = { window: allowed('/repo'), sibling: allowed('/repo.worktrees/feature'), none: allowed(undefined) }; + windowFolders.set([], undefined); + + assert.deepStrictEqual({ ...inWindow, emptyWindow: allowed('/repo.worktrees/feature'), chatWindow: store.add(composers.create(URI.parse('vscode-agents-composer:/chat-window'), {}, async () => { })).allowedFolders }, { + window: ['/repo'], + sibling: ['/repo', '/repo.worktrees/feature'], + none: ['/repo'], + emptyWindow: [], + chatWindow: undefined, + }); + }); + + test('the composers of chat windows are stored as the state is saved, not as their input changes, with what they aim for, their group, their input and a send that did not end; they restore as a composer with that input or with what the send sent, or as the session a send started; a discarded composer and a malformed entry are not stored', async () => { + const store = disposables.add(new DisposableStore()); + const started = createSession('started', { folder: '/repo', status: constObservable(SessionStatus.Completed) }); + const { instantiationService, storageService } = createServices(store, [started]); + const read = () => storageService.get(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, StorageScope.WORKSPACE); + const resource = (name: string) => URI.parse(`vscode-agents-composer:/${name}`); + const open = async () => { }; + const file = { kind: 'file' as const, id: 'a', name: 'index.ts', value: URI.file('/repo/index.ts') }; + const reference = { id: 'a', range: new Range(1, 1, 1, 21), data: file.value, isFile: true, isAttachmentReference: true }; + + const waitForSession = async (resource: URI) => resource.toString() === started.resource.toString() ? started : undefined; + const composers = instantiationService.createInstance(ChatWindowComposers, waitForSession); + const typed = composers.create(resource('typed'), { target: { folderUri: URI.file('/repo'), providerId: 'provider', sessionTypeId: 'type', modelId: 'model', requireDevContainer: true }, groupId: 'group' }, open); + typed.input.set({ inputText: '#attachment:index.ts fix it', attachments: [file], references: [reference] }); + const sending = composers.create(resource('sending'), {}, open); + sending.input.beginSendAttempt({ inputText: 'in flight', attachments: [] }); + const sent = composers.create(resource('sent'), {}, open); + sent.input.beginSendAttempt({ inputText: 'started it', attachments: [] }); + sent.input.setSendAttemptSession(started.resource); + composers.create(resource('discarded'), {}, open).dispose(); + const beforeSave = read(); + storageService.testEmitWillSaveState(WillSaveStateReason.NONE); + // The window closes, with a malformed entry stored beside its composers. + storageService.store(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, stringify([...parse(read()!), { resource: 'not a composer', input: { inputText: 'x', attachments: [] } }]), StorageScope.WORKSPACE, StorageTarget.MACHINE); + composers.dispose(); + [typed, sending, sent].forEach(composer => composer.dispose()); + + const reloaded = store.add(instantiationService.createInstance(ChatWindowComposers, waitForSession)); + const stored = ['typed', 'sending', 'sent', 'discarded'].map(name => reloaded.hasStored(resource(name))); + const restoredTyped = await reloaded.restore(resource('typed'), open); + const restoredSending = await reloaded.restore(resource('sending'), open); + const restoredSent = await reloaded.restore(resource('sent'), open); + const composerOf = (restored: typeof restoredTyped) => restored?.kind === 'composer' ? store.add(restored.composer) : undefined; + const typedComposer = composerOf(restoredTyped); + const sendingComposer = composerOf(restoredSending); + const typedInput = typedComposer?.input.get(); + + assert.deepStrictEqual({ + beforeSave, + stored, + typed: typedComposer && { target: { ...typedComposer.requestedTarget.get(), folderUri: typedComposer.requestedTarget.get()?.folderUri?.toString() }, groupId: typedComposer.groupId, text: typedInput?.input.inputText, attachments: typedInput?.input.attachments.map(attachment => URI.isUri(attachment.value) ? attachment.value.path : undefined), references: typedInput?.input.references?.map(ref => ref.id) }, + sending: sendingComposer?.input.get(), + sent: restoredSent?.kind === 'session' ? restoredSent.session.sessionId : undefined, + }, { + beforeSave: undefined, + stored: [true, true, true, false], + typed: { target: { folderUri: URI.file('/repo').toString(), providerId: 'provider', sessionTypeId: 'type', modelId: 'model', requireDevContainer: true }, groupId: 'group', text: '#attachment:index.ts fix it', attachments: ['/repo/index.ts'], references: ['a'] }, + sending: { input: { inputText: 'in flight', attachments: [], references: undefined } }, + sent: 'started', + }); + }); + + test('the stored composers the restoration of the chat windows did not claim are forgotten, while open ones and claimed ones are stored again', () => { + const store = disposables.add(new DisposableStore()); + const { instantiationService, storageService } = createServices(store); + const resource = (name: string) => URI.parse(`vscode-agents-composer:/${name}`); + const open = async () => { }; + const composers = instantiationService.createInstance(ChatWindowComposers, async () => undefined); + const all = ['claimed', 'unclaimed', 'open'].map(name => composers.create(resource(name), {}, open)); + storageService.testEmitWillSaveState(WillSaveStateReason.NONE); + composers.dispose(); + all.forEach(composer => composer.dispose()); + + const reloaded = store.add(instantiationService.createInstance(ChatWindowComposers, async () => undefined)); + const open2 = store.add(reloaded.create(resource('opened'), {}, open)); + reloaded.didFinishRestore([resource('claimed')]); + storageService.testEmitWillSaveState(WillSaveStateReason.NONE); + + assert.deepStrictEqual({ stored: (parse(storageService.get(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, StorageScope.WORKSPACE)!) as { resource: URI }[]).map(entry => entry.resource.path), opened: open2.resource.path }, { + stored: ['/opened', '/claimed'], + opened: '/opened', + }); + }); + + test('a stored composer stays stored while it restores, until the chat it restores as opens in a window: one whose window fails to open restores again with what it had; once open, what it has now is stored, and nothing once it is closed', async () => { + const store = disposables.add(new DisposableStore()); + const { instantiationService, storageService } = createServices(store); + const resource = URI.parse('vscode-agents-composer:/typed'); + const open = async () => { }; + const save = () => { + storageService.testEmitWillSaveState(WillSaveStateReason.NONE); + const raw = storageService.get(CHAT_WINDOW_COMPOSERS_STORAGE_KEY, StorageScope.WORKSPACE); + return raw ? (parse(raw) as { input: { inputText: string } }[]).map(entry => entry.input.inputText) : []; + }; + const composers = instantiationService.createInstance(ChatWindowComposers, async () => undefined); + const original = composers.create(resource, {}, open); + original.input.set({ inputText: 'unsent', attachments: [] }); + save(); + composers.dispose(); + original.dispose(); + + const reloaded = store.add(instantiationService.createInstance(ChatWindowComposers, async () => undefined)); + const first = await reloaded.restore(resource, open); + const whileRestored = { again: await reloaded.restore(resource, open), stored: reloaded.hasStored(resource) }; + // Its window fails to open: the composer goes with it. + if (first?.kind === 'composer') { + first.composer.dispose(); + } + const afterFailure = { stored: reloaded.hasStored(resource), saved: save() }; + const second = await reloaded.restore(resource, open); + const composer = second?.kind === 'composer' ? second.composer : undefined; + const restoredInput = composer?.input.get().input.inputText; + reloaded.didOpen([resource]); + composer?.input.set({ inputText: 'edited', attachments: [] }); + const whileOpen = { stored: reloaded.hasStored(resource), saved: save() }; + composer?.dispose(); + + assert.deepStrictEqual({ whileRestored, afterFailure, restoredInput, whileOpen, afterClose: save() }, { + whileRestored: { again: undefined, stored: true }, + afterFailure: { stored: true, saved: ['unsent'] }, + restoredInput: 'unsent', + whileOpen: { stored: false, saved: ['edited'] }, + afterClose: [], + }); + }); + + test('a stored composer whose foreground send had gone out restores as its session once that is known, waiting for it, and as a composer with what was sent when it does not become known; one whose send was not accepted restores at once with what was sent', async () => { + const store = disposables.add(new DisposableStore()); + const started = createSession('started', { folder: '/repo', status: constObservable(SessionStatus.Completed) }); + const { instantiationService, storageService } = createServices(store); + const resource = (name: string) => URI.parse(`vscode-agents-composer:/${name}`); + const open = async () => { }; + const waits: string[] = []; + const late = new DeferredPromise<ISession | undefined>(); + const never = new DeferredPromise<ISession | undefined>(); + const waitForSession = (session: URI) => { + waits.push(session.path); + return session.path === '/late' ? late.p : never.p; + }; + const composers = instantiationService.createInstance(ChatWindowComposers, waitForSession); + const originals: IDisposable[] = []; + for (const [name, session] of [['late', 'test:/late'], ['unknown', 'test:/unknown'], ['unaccepted', undefined]] as const) { + const composer = composers.create(resource(name), {}, open); + originals.push(composer); + composer.input.beginSendAttempt({ inputText: `sent ${name}`, attachments: [] }); + if (session) { + composer.input.setSendAttemptSession(URI.parse(session)); + } + } + storageService.testEmitWillSaveState(WillSaveStateReason.NONE); + composers.dispose(); + originals.forEach(composer => composer.dispose()); + + const reloaded = store.add(instantiationService.createInstance(ChatWindowComposers, waitForSession)); + const restoring = ['late', 'unknown'].map(name => reloaded.restore(resource(name), open)); + const unaccepted = await reloaded.restore(resource('unaccepted'), open); + late.complete(started); + never.complete(undefined); + const [lateRestored, unknownRestored] = await Promise.all(restoring); + const inputOf = (restored: typeof unaccepted) => restored?.kind === 'composer' ? store.add(restored.composer).input.get() : undefined; + + assert.deepStrictEqual({ + waits, + late: lateRestored?.kind === 'session' ? lateRestored.session.sessionId : undefined, + unknown: inputOf(unknownRestored), + unaccepted: inputOf(unaccepted), + }, { + waits: ['/late', '/unknown'], + late: 'started', + unknown: { input: { inputText: 'sent unknown', attachments: [], references: undefined } }, + unaccepted: { input: { inputText: 'sent unaccepted', attachments: [], references: undefined } }, + }); + }); + + test('a background send that went out ends its send attempt, so a reload while the next draft is created restores neither; a send not accepted keeps it, so a reload restores what was sent', () => { + const store = disposables.add(new DisposableStore()); + const { onDidAccept, slots, createComposer } = createServices(store); + const sentInBackground = store.add(createComposer()); + const declined = store.add(createComposer()); + for (const composer of [sentInBackground, declined]) { + composer.input.beginSendAttempt({ inputText: 'sent', attachments: [] }); + composer.input.set({ inputText: '', attachments: [] }); + } + onDidAccept.fire({ session: createSession('draft', { folder: '/repo' }), owner: slots[0].slot, background: true }); + + assert.deepStrictEqual({ sentInBackground: sentInBackground.toStored().attempt, declined: declined.toStored().attempt?.input.inputText }, { + sentInBackground: undefined, + declined: 'sent', + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatEditorHost.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatEditorHost.test.ts new file mode 100644 index 000000000000..086345509220 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatEditorHost.test.ts @@ -0,0 +1,96 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Emitter } from '../../../../../../base/common/event.js'; +import { isEqual } from '../../../../../../base/common/resources.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { IChat, ISession } from '../../../../../services/sessions/common/session.js'; +import { resolveSessionChat, waitForSessionChat } from '../../../browser/chatEditor/sessionChatEditorHost.js'; +import { ISessionChange, ISessionsManagementService } from '../../../common/sessionsManagement.js'; + +suite('resolveSessionChat', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('resolves a session by its resource, and a chat, also by a previous identity of its session, as the chat by its current resource', () => { + const session = upcastPartial<ISession>({ resource: URI.parse('test:/session') }); + const chat = upcastPartial<IChat>({ resource: URI.parse('test:/session#chat') }); + // The management service finds the chat also by the resource its session had before, such as before a migration + const previous = URI.parse('test:/legacy-session#chat'); + const sessionsManagementService = upcastPartial<ISessionsManagementService>({ + getSession: (resource: URI) => isEqual(resource, session.resource) ? session : undefined, + getSessionForChatResource: (resource: URI) => isEqual(resource, chat.resource) || isEqual(resource, previous) ? { session, chat } : undefined, + }); + const resolve = (resource: string) => { + const resolved = resolveSessionChat(sessionsManagementService, URI.parse(resource)); + return resolved && { session: resolved.session === session, chat: resolved.chat?.toString() }; + }; + + assert.deepStrictEqual({ + session: resolve('test:/session'), + chat: resolve('test:/session#chat'), + previous: resolve('test:/legacy-session#chat'), + unknown: resolve('test:/unknown'), + }, { + session: { session: true, chat: undefined }, + chat: { session: true, chat: 'test:/session#chat' }, + previous: { session: true, chat: 'test:/session#chat' }, + unknown: undefined, + }); + }); + + test('waits for the chat to resolve once for each change of sessions, and stops as it resolves', async () => { + const session = upcastPartial<ISession>({ resource: URI.parse('test:/session') }); + const chat = upcastPartial<IChat>({ resource: URI.parse('test:/session#chat') }); + const onDidChangeSession = store.add(new Emitter<readonly ISessionChange[]>()); + let known = false; + let lookups = 0; + const sessionsManagementService = upcastPartial<ISessionsManagementService>({ + onDidChangeSession: onDidChangeSession.event, + getSession: () => undefined, + getSessionForChatResource: () => { + lookups++; + return known ? { session, chat } : undefined; + }, + }); + const other = (id: string): ISessionChange => ({ session: upcastPartial<ISession>({ resource: URI.parse(`test:/${id}`) }), kind: 'added' }); + const waiting = waitForSessionChat(sessionsManagementService, chat.resource); + const initial = lookups; + // Sessions added together, such as as a provider registers: one lookup + onDidChangeSession.fire([other('a'), other('b'), other('c')]); + const afterBatch = lookups - initial; + known = true; + onDidChangeSession.fire([other('d'), { session, kind: 'added' }]); + const afterResolved = lookups - initial; + // Once resolved, it no longer looks the chat up, also before its result is taken + onDidChangeSession.fire([other('e')]); + const resolved = await waiting; + + assert.deepStrictEqual({ afterBatch, afterResolved, afterMore: lookups - initial, chat: resolved?.chat?.toString() }, { + afterBatch: 1, afterResolved: 2, afterMore: 2, chat: 'test:/session#chat', + }); + }); + + test('waits through an empty change of sessions, such as an invalidation of what a provider lists, and resolves after it', async () => { + const session = upcastPartial<ISession>({ resource: URI.parse('test:/session') }); + const chat = upcastPartial<IChat>({ resource: URI.parse('test:/session#chat') }); + const onDidChangeSession = store.add(new Emitter<readonly ISessionChange[]>()); + let known = false; + const sessionsManagementService = upcastPartial<ISessionsManagementService>({ + onDidChangeSession: onDidChangeSession.event, + getSession: () => undefined, + getSessionForChatResource: () => known ? { session, chat } : undefined, + }); + const waiting = waitForSessionChat(sessionsManagementService, chat.resource); + // What a hidden session turns visible by, with no session added, removed or changed + known = true; + onDidChangeSession.fire([]); + + assert.strictEqual((await waiting)?.chat?.toString(), 'test:/session#chat'); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatOpening.test.ts b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatOpening.test.ts new file mode 100644 index 000000000000..0bcc5a333793 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/chatEditor/sessionChatOpening.test.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { IObservable, IReader, observableValue } from '../../../../../../base/common/observable.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { ChatModelHold, IChatWindowChatSession, isChatWindowChatGone } from '../../../browser/chatEditor/sessionChatOpening.js'; + +suite('Chat window opening (sessions)', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + suite('Chat model hold', () => { + + const resource = URI.parse('chat:/a'); + + function setup() { + const counter = { refs: 0, acquired: 0 }; + const acquire = () => { counter.refs++; counter.acquired++; return toDisposable(() => counter.refs--); }; + return { counter, acquire }; + } + + test('is held until the view has bound, then released', async () => { + const { counter, acquire } = setup(); + const hold = disposables.add(new ChatModelHold(acquire, 10_000, 5)); + let bound = false; + hold.hold(resource, () => bound); + const held = counter.refs; + bound = true; + await timeout(30); + + assert.deepStrictEqual({ held, after: counter.refs, holding: hold.isHolding }, { held: 1, after: 0, holding: false }); + }); + + test('is released after the timeout when the view never reports binding', async () => { + const { counter, acquire } = setup(); + const hold = disposables.add(new ChatModelHold(acquire, 20, 5)); + hold.hold(resource, () => false); + await timeout(60); + + assert.strictEqual(counter.refs, 0); + }); + + test('is released at its timeout also while the view is polled less often, as in a window in the background', async () => { + const { counter, acquire } = setup(); + const hold = disposables.add(new ChatModelHold(acquire, 20, 10_000)); + hold.hold(resource, () => false); + await timeout(60); + + assert.deepStrictEqual({ refs: counter.refs, holding: hold.isHolding }, { refs: 0, holding: false }); + }); + + test('a hold for another chat replaces the previous one, and none is taken without a chat or a loaded model', () => { + const { counter, acquire } = setup(); + const hold = disposables.add(new ChatModelHold(acquire, 10_000, 5)); + hold.hold(resource, () => false); + hold.hold(URI.parse('chat:/b'), () => false); + const replaced = counter.refs; + hold.hold(undefined, () => false); + const none = counter.refs; + const unloaded = disposables.add(new ChatModelHold(() => undefined)); + unloaded.hold(resource, () => false); + + assert.deepStrictEqual({ replaced, none, unloaded: unloaded.isHolding }, { replaced: 1, none: 0, unloaded: false }); + }); + + test('disposing the hold, as closing the window or a failed opening does, releases it', () => { + const { counter, acquire } = setup(); + const hold = new ChatModelHold(acquire, 10_000, 5); + hold.hold(resource, () => false); + hold.dispose(); + + assert.strictEqual(counter.refs, 0); + }); + }); + + test('a chat window closes with its chat once the session listed its chats, or when the chat is archived', () => { + const chat = { resource: URI.parse('test:/chat'), isArchived: observableValue('archived', false) }; + const chats = observableValue('chats', [chat]); + const loading = observableValue('loading', false); + const mainChat = { resource: URI.parse('test:/main'), isArchived: observableValue('mainArchived', false) }; + const session = { chats, loading, mainChat: observableValue('mainChat', mainChat) } as unknown as IChatWindowChatSession; + const gone = () => isChatWindowChatGone(session, chat.resource, { readObservable: (o: IObservable<unknown>) => o.get() } as unknown as IReader); + + const states = [gone()]; + chat.isArchived.set(true, undefined); + states.push(gone()); + chat.isArchived.set(false, undefined); + chats.set([], undefined); + loading.set(true, undefined); + states.push(gone()); + loading.set(false, undefined); + states.push(gone()); + + assert.deepStrictEqual(states, [false, true, false, true]); + }); + + test('the main chat a session does not list yet is archived while the session loads, and is otherwise kept', () => { + const mainChat = { resource: URI.parse('test:/main'), isArchived: observableValue('archived', false) }; + const loading = observableValue('loading', true); + const session = { chats: observableValue('chats', []), loading, mainChat: observableValue('mainChat', mainChat) } as unknown as IChatWindowChatSession; + const reader = { readObservable: (o: IObservable<unknown>) => o.get() } as unknown as IReader; + const states = [isChatWindowChatGone(session, mainChat.resource, reader)]; + mainChat.isArchived.set(true, undefined); + states.push(isChatWindowChatGone(session, mainChat.resource, reader)); + states.push(isChatWindowChatGone(session, URI.parse('test:/other'), reader)); + + assert.deepStrictEqual(states, [false, true, false]); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/disclosureStyles.test.ts b/src/vs/workbench/contrib/sessions/test/browser/disclosureStyles.test.ts new file mode 100644 index 000000000000..98cd5fc425b9 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/disclosureStyles.test.ts @@ -0,0 +1,55 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../browser/media/disclosure.css'; +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'; + +suite('Sessions Disclosure Styles', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('uses the same dashed high contrast hover boundary for direct and tree disclosures', () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.hc-black')); + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.style.setProperty('--vscode-contrastActiveBorder', '#f38518'); + store.add(toDisposable(() => root.remove())); + + const direct = append(root, $('.sessions-disclosure.hovered')); + const row = append(root, $('.monaco-list-row.sessions-disclosure-row.hovered')); + const tree = append(row, $('.monaco-tl-row')); + const focusedDirect = append(root, $('.sessions-disclosure.hovered.focus-visible')); + const control = append(root, $('.sessions-list-control')); + const list = append(control, $('.monaco-list')); + list.tabIndex = 0; + const focusedRow = append(list, $('.monaco-list-row.sessions-disclosure-row.hovered.focused')); + const focusedTree = append(focusedRow, $('.monaco-tl-row')); + list.focus(); + const readOutline = (element: HTMLElement) => { + const style = mainWindow.getComputedStyle(element); + const hasOutline = style.outlineStyle !== 'none'; + return { + color: hasOutline ? style.outlineColor : 'none', + offset: hasOutline ? style.outlineOffset : '0px', + style: style.outlineStyle, + width: hasOutline ? style.outlineWidth : '0px', + }; + }; + + assert.deepStrictEqual({ + direct: readOutline(direct), + tree: readOutline(tree), + focusedDirect: readOutline(focusedDirect), + focusedTree: readOutline(focusedTree), + }, { + direct: { color: 'rgb(243, 133, 24)', offset: '-1px', style: 'dashed', width: '1px' }, + tree: { color: 'rgb(243, 133, 24)', offset: '-1px', style: 'dashed', width: '1px' }, + focusedDirect: { color: 'none', offset: '0px', style: 'none', width: '0px' }, + focusedTree: { color: 'none', offset: '0px', style: 'none', width: '0px' }, + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessions.test.ts b/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessions.test.ts new file mode 100644 index 000000000000..a9688b401fb2 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessions.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 { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { getSingletonServiceDescriptors } from '../../../../../../platform/instantiation/common/extensions.js'; +import { _util, ServiceIdentifier } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { IFocusedSessionHostService, ISessionHost, ISessionHostService } from '../../../../../services/sessions/browser/sessionHost.js'; +import { ISessionsPartService } from '../../../../../services/sessions/browser/sessionsPartService.js'; +import { ISessionsNavigationService } from '../../../browser/sessionsNavigationService.js'; +import { ISessionsService } from '../../../browser/sessionsService.js'; +import '../../../browser/editorWindow/editorWindowSessions.contribution.js'; +import { ChatHostOpenerService, IChatHostOpenerService } from '../../../../../services/sessions/browser/chatHostOpener.js'; +import { ISessionsHostLayoutService } from '../../../../../services/sessions/browser/sessionsHostLayoutService.js'; +import { ISessionSectionOrderService, SessionSectionOrderService } from '../../../../../services/sessions/browser/sessionSectionOrderService.js'; +import { ISessionChangesStatsCache, SessionChangesStatsCache } from '../../../../../services/sessions/common/sessionChangesStatsCache.js'; +import { IAutomationService } from '../../../../chat/common/automations/automationService.js'; +import { AgentHostFilterService } from '../../../browser/agentHostFilterService.js'; +import { AgentsWindowExtensionSuggestionsService, IAgentsWindowExtensionSuggestionsService } from '../../../browser/agentsWindowExtensionSuggestions.js'; +import { AICustomizationMcpServerCountService, IAICustomizationMcpServerCountService } from '../../../browser/customizationMcpServerCount.js'; +import { ICustomViewService } from '../../../browser/customView.js'; +import { DefaultSessionRepositoryPicker } from '../../../browser/defaultSessionRepositoryPicker.js'; +import { DefaultSessionsListPresentation } from '../../../browser/defaultSessionsListPresentation.js'; +import { IPullRequestIconCache, PullRequestIconCache } from '../../../browser/github/pullRequestIconCache.js'; +import { IPinnedCanvasService } from '../../../browser/pinnedCanvases.js'; +import { SessionComparisonService } from '../../../browser/sessionComparisonService.js'; +import { ISessionGroupsService, SessionGroupsService } from '../../../browser/sessionGroupsService.js'; +import { ISessionOpenTelemetryService, SessionOpenTelemetryService } from '../../../browser/sessionOpenTelemetryService.js'; +import { ISessionRepositoryPicker } from '../../../browser/sessionRepositoryPicker.js'; +import { ISessionsListPresentation } from '../../../browser/sessionsListPresentation.js'; +import { SessionsManagementService } from '../../../browser/sessionsManagementService.js'; +import { ISessionsProvidersService } from '../../../browser/sessionsProvidersService.js'; +import { EditorWindowSessionsProvidersService } from '../../../browser/editorWindow/editorWindowSessionsProvidersService.js'; +import { ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService } from '../../../browser/sessionsRecentWorkspacesService.js'; +import { IAgentHostFilterService } from '../../../common/agentHostFilter.js'; +import { ISessionComparisonService } from '../../../common/sessionComparison.js'; +import { ISessionsManagementService } from '../../../common/sessionsManagement.js'; +import { EditorWindowAgentFeedbackService, EditorWindowAquariumService, EditorWindowAutomationService, EditorWindowCodeReviewService, EditorWindowCustomViewService, EditorWindowPinnedCanvasService } from '../../../browser/editorWindow/editorWindowNullServices.js'; +import { ISessionsChatViewStateService, SessionsChatViewStateService } from '../../../browser/chat/chatViewStateService.js'; +import { ISessionsChatBackgroundService, SessionsChatBackgroundService } from '../../../browser/chatBackgroundService.js'; +import { INewSessionComposerService, NewSessionComposerService } from '../../../browser/newSessionComposerService.js'; +import { IAgentFeedbackService } from '../../../browser/agentFeedback.js'; +import { IAquariumService } from '../../../browser/aquarium.js'; +import { ICodeReviewService } from '../../../browser/codeReviewService.js'; +import { ISessionActivityBarActivityService, SessionActivityBarActivityService } from '../../../common/sessionActivityBarActivityService.js'; +import { IDiffEditorOptionsService } from '../../../../../services/editor/common/diffEditorOptionsService.js'; +import { DiffEditorOptionsService } from '../../../../../services/editor/browser/diffEditorOptionsService.js'; +import { EditorWindowSessionsHostLayout } from '../../../browser/editorWindow/editorWindowSessionsHostLayout.js'; + +suite('Editor window sessions services', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + const registered: readonly [ServiceIdentifier<unknown>, Function][] = [ + [ISessionsHostLayoutService, EditorWindowSessionsHostLayout], + [ISessionsProvidersService, EditorWindowSessionsProvidersService], + [ISessionsManagementService, SessionsManagementService], + [IChatHostOpenerService, ChatHostOpenerService], + [ISessionChangesStatsCache, SessionChangesStatsCache], + [ISessionOpenTelemetryService, SessionOpenTelemetryService], + [ISessionSectionOrderService, SessionSectionOrderService], + [ISessionGroupsService, SessionGroupsService], + [ISessionsRecentWorkspacesService, SessionsRecentWorkspacesService], + [ISessionComparisonService, SessionComparisonService], + [IAgentHostFilterService, AgentHostFilterService], + [ISessionRepositoryPicker, DefaultSessionRepositoryPicker], + [ISessionsListPresentation, DefaultSessionsListPresentation], + [IPullRequestIconCache, PullRequestIconCache], + [IAICustomizationMcpServerCountService, AICustomizationMcpServerCountService], + [IAgentsWindowExtensionSuggestionsService, AgentsWindowExtensionSuggestionsService], + [ICustomViewService, EditorWindowCustomViewService], + [IAutomationService, EditorWindowAutomationService], + [IPinnedCanvasService, EditorWindowPinnedCanvasService], + [IAgentFeedbackService, EditorWindowAgentFeedbackService], + [IAquariumService, EditorWindowAquariumService], + [ICodeReviewService, EditorWindowCodeReviewService], + [ISessionsChatViewStateService, SessionsChatViewStateService], + [ISessionsChatBackgroundService, SessionsChatBackgroundService], + [INewSessionComposerService, NewSessionComposerService], + [ISessionActivityBarActivityService, SessionActivityBarActivityService], + [IDiffEditorOptionsService, DiffEditorOptionsService], + ]; + + test('registers every service to be created only as it is first used', () => { + const descriptors = getSingletonServiceDescriptors(); + assert.deepStrictEqual( + registered.map(([id, ctor]) => { + const own = descriptors.filter(([candidate, descriptor]) => candidate === id && descriptor.ctor === ctor); + // The Agents window registers some of them too, the same way, where its modules load in the same run + return { id: id.toString(), registered: own.length > 0, delayed: own.every(([, descriptor]) => descriptor.supportsDelayedInstantiation) }; + }), + registered.map(([id]) => ({ id: id.toString(), registered: true, delayed: true })), + ); + }); + + test('none of the services depends, also through another of them, on a service only the Agents window has', () => { + const agentsWindowOnly = new Set<ServiceIdentifier<unknown>>([ISessionsService, ISessionsNavigationService, ISessionHost, ISessionHostService, IFocusedSessionHostService, ISessionsPartService]); + const ctors = new Map(registered); + const dependsOnAgentsWindow = (id: ServiceIdentifier<unknown>, seen: Set<ServiceIdentifier<unknown>>): string[] => { + const ctor = ctors.get(id); + if (!ctor || seen.has(id)) { + return []; + } + seen.add(id); + return _util.getServiceDependencies(ctor as _util.DI_TARGET_OBJ).flatMap(({ id: dependency }) => agentsWindowOnly.has(dependency) + ? [`${id} -> ${dependency}`] + : dependsOnAgentsWindow(dependency, seen)); + }; + assert.deepStrictEqual(registered.flatMap(([id]) => dependsOnAgentsWindow(id, new Set())), []); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessionsProvidersService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessionsProvidersService.test.ts new file mode 100644 index 000000000000..4495c97bfe2e --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/editorWindow/editorWindowSessionsProvidersService.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 'assert'; +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 { IFileService } from '../../../../../../platform/files/common/files.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js'; +import { IWorkspace, IWorkspaceContextService, IWorkspaceFolder } from '../../../../../../platform/workspace/common/workspace.js'; +import { ILifecycleService } from '../../../../../services/lifecycle/common/lifecycle.js'; +import { EditorWindowSessionsProvidersService } from '../../../browser/editorWindow/editorWindowSessionsProvidersService.js'; +import { ISessionsListingScope, ISessionsProvider } from '../../../common/sessionsProvider.js'; + +suite('EditorWindowSessionsProvidersService', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createService() { + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(ILifecycleService, upcastPartial<ILifecycleService>({ willShutdown: false })); + instantiationService.stub(IFileService, upcastPartial<IFileService>({ stat: () => Promise.reject(new Error('no .git')) })); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IWorkspaceContextService, upcastPartial<IWorkspaceContextService>({ + onDidChangeWorkspaceFolders: Event.None, + getWorkspace: () => upcastPartial<IWorkspace>({ folders: [upcastPartial<IWorkspaceFolder>({ uri: URI.parse('vscode-remote://host/work/repo') })] }), + })); + return store.add(instantiationService.createInstance(EditorWindowSessionsProvidersService)); + } + + /** A provider that records the listing scopes it is given, as they are set before it is registered. */ + function createProvider(id: string, scopes: { readonly id: string; readonly registered: boolean; readonly folders: string[] }[], service: EditorWindowSessionsProvidersService): ISessionsProvider { + return upcastPartial<ISessionsProvider>({ + id, + order: 0, + setListingScope: (scope: ISessionsListingScope) => scopes.push({ id, registered: !!service.getProvider(id), folders: scope.folders.get().map(folder => folder.toString()) }), + }); + } + + test('scopes every provider and session backend to the window\'s folders before it registers, whoever registers it', () => { + const scopes: { readonly id: string; readonly registered: boolean; readonly folders: string[] }[] = []; + const service = createService(); + store.add(service.registerProvider(createProvider('local', scopes, service))); + // Such as a Dev Container provider that its service restores, later + store.add(service.registerProvider(createProvider('dev-container', scopes, service))); + store.add(service.registerSessionBackend('local', createProvider('backend', scopes, service))); + // A provider that cannot scope its listing still registers + store.add(service.registerProvider(upcastPartial<ISessionsProvider>({ id: 'unscoped', order: 0 }))); + + assert.deepStrictEqual({ scopes, providers: service.getProviders({ includeSessionBackends: true }).map(provider => provider.id) }, { + scopes: [ + { id: 'local', registered: false, folders: ['vscode-remote://host/work/repo'] }, + { id: 'dev-container', registered: false, folders: ['vscode-remote://host/work/repo'] }, + { id: 'backend', registered: false, folders: ['vscode-remote://host/work/repo'] }, + ], + providers: ['local', 'dev-container', 'unscoped', 'backend'], + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/mobile/mobilePickerSheet.test.ts b/src/vs/workbench/contrib/sessions/test/browser/mobile/mobilePickerSheet.test.ts index a38165a6a5a4..130cc09dc2e5 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/mobile/mobilePickerSheet.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/mobile/mobilePickerSheet.test.ts @@ -4,10 +4,12 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import * as dom from '../../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../../base/browser/window.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; +import { Emitter } from '../../../../../../base/common/event.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IMobileContentSheetOptions, showMobileContentSheet, showMobilePickerSheet } from '../../../browser/mobile/mobilePickerSheet.js'; @@ -15,6 +17,29 @@ import { IMobileContentSheetOptions, showMobileContentSheet, showMobilePickerShe suite('MobilePickerSheet', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('a provider refresh without focus preferences preserves the focused row', async () => { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const changed = store.add(new Emitter<void>()); + let items = [{ id: 'one', label: 'One' }, { id: 'two', label: 'Two' }]; + const closed = showMobilePickerSheet(container, 'Choices', items, { + initialFocusItemId: 'two', + itemProvider: { onDidChange: changed.event, getItems: () => items }, + }); + store.add(toDisposable(() => container.querySelector<HTMLButtonElement>('.mobile-picker-sheet-done')?.click())); + const sheet = container.querySelector('.mobile-picker-sheet'); + items = [{ id: 'two', label: 'Updated two' }, { id: 'one', label: 'One' }]; + changed.fire(); + const state = { + sameSheet: container.querySelector('.mobile-picker-sheet') === sheet, + focus: mainWindow.document.activeElement?.textContent, + }; + container.querySelector<HTMLButtonElement>('.mobile-picker-sheet-item')!.click(); + assert.deepStrictEqual({ ...state, selected: await closed, remaining: container.childElementCount }, { + sameSheet: true, focus: 'Updated two', selected: 'two', remaining: 0, + }); + }); + for (const alreadyCancelled of [false, true]) { test(`owner cancellation dismisses the picker without selection (${alreadyCancelled ? 'before' : 'after'} opening)`, async () => { const container = dom.append(mainWindow.document.body, dom.$('div')); @@ -35,6 +60,40 @@ suite('MobilePickerSheet', () => { }); } + test('async selection refreshes the confirmed state without replacing the sheet or stealing section focus', async () => { + const container = dom.append(mainWindow.document.body, dom.$('div')); + store.add(toDisposable(() => container.remove())); + const pending = new DeferredPromise<void>(); + const items = [{ id: 'default', label: 'Default', checked: true }, { id: 'allow', label: 'Allow all', checked: false }]; + let selections = 0; + const closed = showMobilePickerSheet(container, 'Configure Session', items, { + initialFocusItemId: 'allow', + stayOpenOnSelect: true, + onDidSelect: async () => { selections++; await pending.p; return { items }; }, + }); + store.add(toDisposable(() => container.querySelector<HTMLButtonElement>('.mobile-picker-sheet-done')?.click())); + const sheet = container.querySelector('.mobile-picker-sheet'); + const initialFocus = mainWindow.document.activeElement?.textContent; + const row = container.querySelectorAll<HTMLButtonElement>('.mobile-picker-sheet-item')[1]; + row.click(); + row.click(); + const during = { busy: container.querySelector('[role="list"]')?.getAttribute('aria-busy'), checked: row.getAttribute('aria-current') }; + await pending.complete(); + await timeout(0); + const after = { + sameSheet: container.querySelector('.mobile-picker-sheet') === sheet, + focus: mainWindow.document.activeElement?.textContent, + checked: Array.from(container.querySelectorAll('.checked .mobile-picker-sheet-label'), element => element.textContent), + }; + container.querySelector<HTMLButtonElement>('.mobile-picker-sheet-done')!.click(); + await closed; + assert.deepStrictEqual({ initialFocus, selections, during, after }, { + initialFocus: 'Allow all', selections: 1, + during: { busy: 'true', checked: 'false' }, + after: { sameSheet: true, focus: 'Allow all', checked: ['Default'] }, + }); + }); + for (const description of [undefined, 'Evaluates risk before running tools']) { test(`renders and announces item badges${description ? ' with descriptions' : ''}`, async () => { const container = dom.append(mainWindow.document.body, dom.$('div')); diff --git a/src/vs/workbench/contrib/sessions/test/browser/parts/sessionDragAndDrop.test.ts b/src/vs/workbench/contrib/sessions/test/browser/parts/sessionDragAndDrop.test.ts index f6db4010bbce..03116ac0e5f8 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/parts/sessionDragAndDrop.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/parts/sessionDragAndDrop.test.ts @@ -8,10 +8,14 @@ import { DataTransfers } from '../../../../../../base/browser/dnd.js'; import { $ } from '../../../../../../base/browser/dom.js'; import { timeout } from '../../../../../../base/common/async.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { isEqual } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; import { mock, upcastDeepPartial, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { clearChatReferenceDragData } from '../../../../../../platform/dnd/browser/dnd.js'; import { IExtensionDescription } from '../../../../../../platform/extensions/common/extensions.js'; import { ISharedWebContentExtractorService } from '../../../../../../platform/webContentExtractor/common/webContentExtractor.js'; import { IExtensionService } from '../../../../../services/extensions/common/extensions.js'; @@ -27,7 +31,7 @@ import { IEditorGroupsService } from '../../../../../services/editor/common/edit import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; import { ChatGroupDropTarget } from '../../../browser/parts/chatGroupDropTarget.js'; import { SessionDropTarget } from '../../../browser/parts/sessionDropTarget.js'; -import { clearChatReferenceDragData, fillChatReferenceDragData, fillSessionChatDragData, getSessionChatDragData, isSessionChatDrag } from '../../../browser/dnd.js'; +import { fillChatReferenceDragData, fillSessionChatDragData, getSessionChatDragData, isSessionChatDrag } from '../../../browser/dnd.js'; import { ISessionsService } from '../../../browser/sessionsService.js'; import { ISessionsManagementService } from '../../../common/sessionsManagement.js'; import '../../../../chat/browser/widget/media/chat.css'; @@ -35,100 +39,139 @@ import '../../../../chat/browser/widget/media/chat.css'; suite('Sessions - Chat Reference Drop Priority', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + const targetResource = URI.parse('agent-host-copilotcli:/target'); + const sourceResource = URI.parse('agent-host-copilotcli:/source'); + const otherHostResource = URI.parse('agent-host-copilotcli:/other-host'); + const backendResource = URI.parse('copilotcli-chat://backend/source'); + + /** A session view whose chat widget has an input at its bottom, under a placement target for the given scope. */ + function setup(scope: 'session' | 'chatGroup') { + const services = workbenchInstantiationService(undefined, store); + const moves: string[] = []; + services.stub(ISessionsService, new class extends mock<ISessionsService>() { + override async moveChatToGrid(): Promise<void> { moves.push('session'); } + }()); + services.stub(ISessionsManagementService, new class extends mock<ISessionsManagementService>() { }()); + services.stub(IExtensionService, new class extends mock<IExtensionService>() { }()); + services.stub(ISharedWebContentExtractorService, new class extends mock<ISharedWebContentExtractorService>() { }()); + services.stub(IChatAttachmentResolveService, new class extends mock<IChatAttachmentResolveService>() { }()); + services.stub(IAgentHostConnectionsService, upcastPartial<IAgentHostConnectionsService>({ + resolveSessionResourceIdentity: resource => ({ connectionAuthority: isEqual(resource, otherHostResource) ? 'remote' : 'local', backendSession: URI.parse('opaque-session:/session') }), + })); + const container = $('.session-view'); + container.style.cssText = 'position:fixed;left:0;top:0;width:400px;height:300px;'; + const group = $('.chat-group-view'); + group.style.cssText = 'position:relative;width:100%;height:100%;'; + const widget = $('.interactive-session'); + widget.style.cssText = 'position:relative;width:100%;height:100%;'; + const transcript = $('.test-transcript', undefined, 'Transcript'); + transcript.style.height = '180px'; + const input = $('.test-chat-input'); + input.style.cssText = 'position:absolute;left:20px;bottom:20px;width:360px;height:80px;border-radius:0 0 8px 8px;'; + const inputContent = $('span', undefined, 'Input'); + input.appendChild(inputContent); + widget.append(transcript, input); + group.appendChild(widget); + container.appendChild(group); + document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + store.add(toDisposable(clearChatReferenceDragData)); + const attachments: IChatRequestVariableEntry[] = []; + const inputDnd = store.add(services.createInstance(ChatDragAndDrop, + () => upcastDeepPartial<IChatWidget>({ viewModel: { model: upcastPartial<IChatModel>({ sessionResource: targetResource }) } }), + { attachments, addAttachments: entries => attachments.push(...entries) }, + { overlayBackground: '', listForeground: '', listBackground: '' }, + )); + inputDnd.addOverlay(widget, widget, input); + if (scope === 'session') { + store.add(services.createInstance(SessionDropTarget, container, { + findTargetView: () => ({ sessionId: 'target', gridSlotId: 'target-slot', element: container }), + })); + } else { + store.add(services.createInstance(ChatGroupDropTarget, group, { + isChatDrag: event => isSessionChatDrag(event, 'target'), + getChatDragData: getSessionChatDragData, + findTargetGroup: () => ({ id: 1, element: group }), + onChatDrop: () => moves.push('chatGroup'), + })); + } + const overlayId = scope === 'session' ? '#monaco-workbench-session-drop-overlay' : '#monaco-workbench-chat-group-drop-overlay'; + const inputBounds = input.getBoundingClientRect(); + const inputPoint = { clientX: inputBounds.left + inputBounds.width / 2, clientY: inputBounds.top + inputBounds.height / 2 }; + const transcriptBounds = transcript.getBoundingClientRect(); + const transcriptPoint = { clientX: transcriptBounds.left + 10, clientY: transcriptBounds.top + 80 }; + /** A drag of a chat, of the source session or of the target session as `scope` drags, that references `clientResource`. */ + const drag = (clientResource: URI) => { + const event = new DragEvent('dragstart', { dataTransfer: new DataTransfer() }); + fillSessionChatDragData(event, scope === 'session' ? 'source' : 'target', clientResource); + fillChatReferenceDragData(event, backendResource, clientResource, 'Source Chat'); + return event.dataTransfer!; + }; + const dispatch = (element: HTMLElement, type: string, dataTransfer: DataTransfer, point = inputPoint) => element.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, ...point })); + return { container, widget, transcript, input, inputContent, inputDnd, attachments, moves, overlayId, inputPoint, transcriptPoint, drag, dispatch }; + } + for (const scope of ['session', 'chatGroup'] as const) { test(`${scope} placement does not intercept a chat reference dropped into an input`, async () => { - const services = workbenchInstantiationService(undefined, store); - const moves: string[] = []; - services.stub(ISessionsService, new class extends mock<ISessionsService>() { - override async moveChatToGrid(): Promise<void> { moves.push('session'); } - }()); - services.stub(ISessionsManagementService, new class extends mock<ISessionsManagementService>() { }()); - services.stub(IExtensionService, new class extends mock<IExtensionService>() { }()); - services.stub(ISharedWebContentExtractorService, new class extends mock<ISharedWebContentExtractorService>() { }()); - services.stub(IChatAttachmentResolveService, new class extends mock<IChatAttachmentResolveService>() { }()); - services.stub(IAgentHostConnectionsService, upcastPartial<IAgentHostConnectionsService>({ - resolveSessionResourceIdentity: () => ({ connectionAuthority: 'local', backendSession: URI.parse('opaque-session:/session') }), - })); - const container = $('.session-view'); - container.style.cssText = 'position:fixed;left:0;top:0;width:400px;height:300px;'; - const group = $('.chat-group-view'); - group.style.cssText = 'position:relative;width:100%;height:100%;'; - const widget = $('.interactive-session'); - widget.style.cssText = 'position:relative;width:100%;height:100%;'; - const transcript = $('.test-transcript', undefined, 'Transcript'); - transcript.style.height = '180px'; - const input = $('.test-chat-input'); - input.style.cssText = 'position:absolute;left:20px;bottom:20px;width:360px;height:80px;'; - const inputContent = $('span', undefined, 'Input'); - input.appendChild(inputContent); - widget.append(transcript, input); - group.appendChild(widget); - container.appendChild(group); - document.body.appendChild(container); - store.add(toDisposable(() => container.remove())); - store.add(toDisposable(clearChatReferenceDragData)); - const targetResource = URI.parse('agent-host-copilotcli:/target'); - const sourceResource = URI.parse('agent-host-copilotcli:/source'); - const backendResource = URI.parse('copilotcli-chat://backend/source'); - const attachments: IChatRequestVariableEntry[] = []; - const inputDnd = store.add(services.createInstance(ChatDragAndDrop, - () => upcastDeepPartial<IChatWidget>({ viewModel: { model: upcastPartial<IChatModel>({ sessionResource: targetResource }) } }), - { attachments, addAttachments: entries => attachments.push(...entries) }, - { overlayBackground: '', listForeground: '', listBackground: '' }, - )); - inputDnd.addOverlay(widget, widget, input); - if (scope === 'session') { - store.add(services.createInstance(SessionDropTarget, container, { - findTargetView: () => ({ sessionId: 'target', gridSlotId: 'target-slot', element: container }), - })); - } else { - store.add(services.createInstance(ChatGroupDropTarget, group, { - isChatDrag: event => isSessionChatDrag(event, 'target'), - getChatDragData: getSessionChatDragData, - findTargetGroup: () => ({ id: 1, element: group }), - onChatDrop: () => moves.push('chatGroup'), - })); - } - const drag = new DragEvent('dragstart', { dataTransfer: new DataTransfer() }); - fillSessionChatDragData(drag, scope === 'session' ? 'source' : 'target', sourceResource); - fillChatReferenceDragData(drag, backendResource, sourceResource, 'Source Chat'); - group.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer: drag.dataTransfer })); - const overlayId = scope === 'session' ? '#monaco-workbench-session-drop-overlay' : '#monaco-workbench-chat-group-drop-overlay'; + const { container, widget, transcript, input, inputContent, inputDnd, attachments, moves, overlayId, inputPoint, transcriptPoint, drag, dispatch } = setup(scope); + const dataTransfer = drag(sourceResource); + dispatch(transcript, 'dragenter', dataTransfer, transcriptPoint); const gridOverlay = container.querySelector<HTMLElement>(overlayId)!; assert.ok(gridOverlay); - const bounds = input.getBoundingClientRect(); - const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2); - const inputReceivesPointer = !!hit && input.contains(hit); - inputContent.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer: drag.dataTransfer })); + const coveringHit = document.elementFromPoint(inputPoint.clientX, inputPoint.clientY); + const gridCoversInput = !!coveringHit && gridOverlay.contains(coveringHit); + const inputHints = [...gridOverlay.querySelectorAll<HTMLElement>('.input-drop-target-hint')].map(hint => ({ text: hint.textContent, top: hint.style.top, height: hint.style.height, borderRadius: hint.style.borderRadius })); + dispatch(gridOverlay, 'dragover', dataTransfer); const removedGridOverlay = !container.querySelector(overlayId); - inputContent.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: drag.dataTransfer })); - inputContent.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: drag.dataTransfer })); + const hit = document.elementFromPoint(inputPoint.clientX, inputPoint.clientY); + const inputReceivesPointer = !!hit && input.contains(hit); + dispatch(inputContent, 'dragenter', dataTransfer); + const gridOverlayReturned = !!container.querySelector(overlayId); + dispatch(inputContent, 'dragover', dataTransfer); + const inputOverlay = widget.querySelector<HTMLElement>('.chat-dnd-overlay')!; + const inputFeedback = { visible: inputOverlay.classList.contains('visible'), top: inputOverlay.style.top, height: inputOverlay.style.height, borderRadius: inputOverlay.style.borderRadius }; + const registered = isInputDropTarget(inputContent, new DragEvent('dragover', { dataTransfer })); + dispatch(inputContent, 'drop', dataTransfer); await timeout(0); - const registered = isInputDropTarget(inputContent); const inputMoves = [...moves]; - transcript.dispatchEvent(new DragEvent('dragenter', { bubbles: true, dataTransfer: drag.dataTransfer })); + dispatch(transcript, 'dragenter', dataTransfer, transcriptPoint); const placementOverlay = container.querySelector<HTMLElement>(overlayId); assert.ok(placementOverlay, 'placement stays available over the transcript despite the whole-widget attachment handler'); - const transcriptBounds = transcript.getBoundingClientRect(); - const clientX = transcriptBounds.left + 10; - const clientY = transcriptBounds.top + 80; - const placementHit = document.elementFromPoint(clientX, clientY); + const placementHit = document.elementFromPoint(transcriptPoint.clientX, transcriptPoint.clientY); const placementReceivesPointer = !!placementHit && placementOverlay.contains(placementHit); - placementOverlay.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: drag.dataTransfer, clientX, clientY })); - placementOverlay.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: drag.dataTransfer, clientX, clientY })); + dispatch(placementOverlay, 'dragover', dataTransfer, transcriptPoint); + dispatch(placementOverlay, 'drop', dataTransfer, transcriptPoint); await timeout(0); - const transcriptIsInput = isInputDropTarget(transcript); + const transcriptIsInput = isInputDropTarget(transcript, new DragEvent('dragover', { dataTransfer, ...transcriptPoint })); inputDnd.removeOverlay(widget); assert.deepStrictEqual({ - inputReceivesPointer, removedGridOverlay, inputMoves, placementReceivesPointer, moves, transcriptIsInput, + gridCoversInput, inputHints, removedGridOverlay, inputReceivesPointer, gridOverlayReturned, inputFeedback, inputMoves, placementReceivesPointer, moves, transcriptIsInput, attachments: attachments.map(entry => ({ kind: entry.kind, name: entry.name, value: entry.value?.toString() })), - registered, removed: !isInputDropTarget(inputContent), + registered, removed: !isInputDropTarget(inputContent, new DragEvent('dragover', { dataTransfer })), }, { - inputReceivesPointer: true, removedGridOverlay: true, inputMoves: [], placementReceivesPointer: true, moves: [scope], transcriptIsInput: false, + // The placement covers the input, and shows where it is, until the drag moves over the input, which then takes it. + gridCoversInput: true, inputHints: [{ text: 'Drag here to attach to chat', top: '200px', height: '80px', borderRadius: '0px 0px 8px 8px' }], + removedGridOverlay: true, inputReceivesPointer: true, gridOverlayReturned: false, + // The feedback covers the input, shaped as it is, which takes the drop, not the transcript, whose drop the placement takes. + inputFeedback: { visible: true, top: '200px', height: '80px', borderRadius: '0px 0px 8px 8px' }, + inputMoves: [], placementReceivesPointer: true, moves: [scope], transcriptIsInput: false, attachments: [{ kind: 'chatReference', name: 'Source Chat', value: backendResource.toString() }], registered: true, removed: true, }); }); + + test(`${scope} placement covers an input that does not take the drag, such as a chat of another agent host, and takes its drop`, async () => { + const { container, inputContent, attachments, moves, overlayId, drag, dispatch } = setup(scope); + const dataTransfer = drag(otherHostResource); + dispatch(inputContent, 'dragenter', dataTransfer); + const placementOverlay = container.querySelector<HTMLElement>(overlayId); + assert.ok(placementOverlay); + const inputHints = placementOverlay.querySelectorAll('.input-drop-target-hint').length; + dispatch(placementOverlay, 'dragover', dataTransfer); + dispatch(placementOverlay, 'drop', dataTransfer); + await timeout(0); + assert.deepStrictEqual({ inputHints, moves, attachments }, { inputHints: 0, moves: [scope], attachments: [] }); + }); } }); @@ -183,13 +226,17 @@ suite('Sessions - Inbox Composer Drop Priority', () => { const dataTransfer = new DataTransfer(); dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([URI.file('/Screenshot.png').toString()])); dataTransfer.items.add(new File(['image'], 'Screenshot.png', { type: 'image/png' })); - const dispatch = (element: HTMLElement, type: string) => element.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer })); + const bounds = input.getBoundingClientRect(); + const inputPoint = { clientX: bounds.left + bounds.width / 2, clientY: bounds.top + bounds.height / 2 }; + const dispatch = (element: HTMLElement, type: string, point?: { clientX: number; clientY: number }) => element.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, ...point })); if (enterThroughBackground) { dispatch(background, 'dragenter'); - assert.ok(group.querySelector('#monaco-workbench-editor-drop-overlay'), 'editor placement is still available outside the input'); + const editorOverlay = group.querySelector<HTMLElement>('#monaco-workbench-editor-drop-overlay'); + assert.ok(editorOverlay, 'editor placement is still available outside the input'); + // The placement covers the input until the drag moves over it + dispatch(editorOverlay, 'dragover', inputPoint); } - const bounds = input.getBoundingClientRect(); - const hit = document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2); + const hit = document.elementFromPoint(inputPoint.clientX, inputPoint.clientY); const inputReceivesPointer = !!hit && input.contains(hit); dispatch(inputContent, 'dragenter'); const editorOverlayIntercepted = !!group.querySelector('#monaco-workbench-editor-drop-overlay'); @@ -212,3 +259,62 @@ suite('Sessions - Inbox Composer Drop Priority', () => { } } }); + +suite('Chat Editor Drop Feedback', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('while the key to drop into the editor lets the drag through, the chat shows its feedback on the input, as with the drag over it', () => { + const services = workbenchInstantiationService(undefined, store); + services.stub(IConfigurationService, new TestConfigurationService({ 'editor.dropIntoEditor.enabled': true })); + services.stub(IExtensionService, new class extends mock<IExtensionService>() { }()); + services.stub(ISharedWebContentExtractorService, new class extends mock<ISharedWebContentExtractorService>() { }()); + services.stub(IChatAttachmentResolveService, new class extends mock<IChatAttachmentResolveService>() { }()); + + // An editor area with a chat editor, whose chat widget takes drags anywhere, and has an input at its bottom + const container = $('.test-editor-part'); + container.style.cssText = 'position:fixed;left:0;top:0;width:400px;height:300px;'; + const widget = $('.interactive-session'); + widget.style.cssText = 'position:relative;width:100%;height:100%;'; + const transcript = $('.test-transcript', undefined, 'Transcript'); + transcript.style.height = '180px'; + const input = $('.test-chat-input'); + input.style.cssText = 'position:absolute;left:20px;bottom:20px;width:360px;height:80px;'; + widget.append(transcript, input); + container.appendChild(widget); + document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + store.add(services.createInstance(EditorDropTarget, upcastDeepPartial<IEditorGroupsView>({ partOptions: { allowDropIntoGroup: true } }), container, {})); + const inputDnd = store.add(services.createInstance(ChatDragAndDrop, + () => undefined, + { attachments: [], addAttachments: () => { } }, + { overlayBackground: '', listForeground: '', listBackground: '' }, + )); + inputDnd.addOverlay(widget, widget, input); + + const dataTransfer = new DataTransfer(); + dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify([URI.file('/README.md').toString()])); + const bounds = transcript.getBoundingClientRect(); + const dispatch = (type: string, shiftKey: boolean) => transcript.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, clientX: bounds.left + 10, clientY: bounds.top + 80, shiftKey })); + const dragOverTranscript = (shiftKey: boolean) => { + dispatch('dragover', shiftKey); + const overlay = widget.querySelector<HTMLElement>('.chat-dnd-overlay')!; + return { visible: overlay.classList.contains('visible'), top: overlay.style.top, left: overlay.style.left, width: overlay.style.width, height: overlay.style.height }; + }; + + dispatch('dragenter', true); + const notLetThrough = dragOverTranscript(false); + const held = dragOverTranscript(true); + const released = dragOverTranscript(false); + dispatch('dragleave', false); + const nextDrag = dragOverTranscript(false); + + const overInput = { visible: true, top: '200px', left: '20px', width: '360px', height: '80px' }; + const overChat = { visible: true, top: '', left: '', width: '', height: '' }; + assert.deepStrictEqual({ notLetThrough, held, released, nextDrag }, { + // A drag that reaches the chat otherwise, such as one that the editor area does not take, shows over the whole chat + notLetThrough: overChat, + // The input takes the drag let through, also once the key is released, until the drag leaves + held: overInput, released: overInput, nextDrag: overChat, + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/parts/sessionHeader.test.ts b/src/vs/workbench/contrib/sessions/test/browser/parts/sessionHeader.test.ts index 7045ab678dce..8d86ba1fe161 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/parts/sessionHeader.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/parts/sessionHeader.test.ts @@ -18,7 +18,7 @@ import { IAccessibilityService } from '../../../../../../platform/accessibility/ import { IMenu, IMenuService, MenuId, MenuItemAction } from '../../../../../../platform/actions/common/actions.js'; import { IContextKeyService } from '../../../../../../platform/contextkey/common/contextkey.js'; import { LocalSelectionTransfer } from '../../../../../../platform/dnd/browser/dnd.js'; -import { DraggedSessionIdentifier, getSessionChatDragData, SessionsDataTransfers } from '../../../browser/dnd.js'; +import { DraggedSessionIdentifier, getSessionChatDragData, registerSessionChatDragEndHandler, SessionsDataTransfers } from '../../../browser/dnd.js'; import { DraggedEditorIdentifier } from '../../../../../browser/dnd.js'; import { IEditorIdentifier } from '../../../../../common/editor.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; @@ -35,6 +35,7 @@ import { ChatOriginKind, IChat, ISession, ISessionCapabilities, SessionStatus } import { LegacyFakePaneState, testPaneContentOf } from '../sessionHostTestUtils.js'; import { ISessionsManagementService } from '../../../common/sessionsManagement.js'; import { ISessionHost, isSessionHostCommandContext } from '../../../../../services/sessions/browser/sessionHost.js'; +import '../../../browser/parts/media/chatCompositeBar.css'; function createHarness(disposables: Pick<DisposableStore, 'add'>, capabilities: ISessionCapabilities = { supportsMultipleChats: false }, mainChatStatus = SessionStatus.Completed) { const store = disposables.add(new DisposableStore()); @@ -117,6 +118,47 @@ function createHarness(disposables: Pick<DisposableStore, 'add'>, capabilities: suite('Sessions - Headers', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + test('shows high contrast hover only for editable read-mode titles', () => { + const editable = createHarness(disposables, { supportsMultipleChats: false, supportsRename: true }); + const editing = createHarness(disposables, { supportsMultipleChats: false, supportsRename: true }); + const readOnly = createHarness(disposables); + const root = mainWindow.document.createElement('div'); + root.className = 'monaco-workbench hc-black'; + root.style.setProperty('--vscode-contrastActiveBorder', '#f38518'); + root.style.setProperty('--vscode-strokeThickness', '1px'); + root.append(editable.header.element.parentElement!, editing.header.element.parentElement!, readOnly.header.element.parentElement!); + mainWindow.document.body.appendChild(root); + disposables.add(toDisposable(() => root.remove())); + const editableTitle = editable.header.element.querySelector<HTMLElement>('.chat-composite-bar-session-title')!; + editing.header.startTitleEditing(); + const editingTitle = editing.header.element.querySelector<HTMLElement>('.chat-composite-bar-session-title')!; + const readOnlyTitle = readOnly.header.element.querySelector<HTMLElement>('.chat-composite-bar-session-title')!; + editableTitle.classList.add('hovered'); + editingTitle.classList.add('hovered'); + readOnlyTitle.classList.add('hovered'); + const describe = (element: HTMLElement) => { + const style = mainWindow.getComputedStyle(element); + return { + editable: element.classList.contains('editable'), + editing: element.classList.contains('editing'), + color: style.outlineStyle === 'none' ? 'none' : style.outlineColor, + offset: style.outlineOffset, + style: style.outlineStyle, + width: style.outlineStyle === 'none' ? '0px' : style.outlineWidth, + }; + }; + + assert.deepStrictEqual({ + editable: describe(editableTitle), + editing: describe(editingTitle), + readOnly: describe(readOnlyTitle), + }, { + editable: { editable: true, editing: false, color: 'rgb(243, 133, 24)', offset: '-1px', style: 'dashed', width: '1px' }, + editing: { editable: true, editing: true, color: 'none', offset: '0px', style: 'none', width: '0px' }, + readOnly: { editable: false, editing: false, color: 'none', offset: '0px', style: 'none', width: '0px' }, + }); + }); + test('reports only actual integer border-box height changes, including hidden ancestors and disposal', () => { const { instantiationService, session, mainChat } = createHarness(disposables); let observer: TestResizeObserver | undefined; @@ -215,6 +257,40 @@ suite('Sessions - Headers', () => { }); }); + test('a header that drags the editor of its chat carries the session and its chat from anywhere but its toolbar, which keeps the mouse', () => { + const { header, session, mainChat } = createHarness(disposables); + header.setDragsEditor(true); + const titleActions = header.element.querySelector<HTMLElement>('.chat-composite-bar-title-actions')!; + + const fromToolbar = simulateDragFrom(header, titleActions); + const fromHeader = simulateDragFrom(header, header.element); + + assert.deepStrictEqual({ + toolbarPrevented: fromToolbar.defaultPrevented, + headerPrevented: fromHeader.defaultPrevented, + session: JSON.parse(fromHeader.dataTransfer!.getData(SessionsDataTransfers.SESSION) || '{}').sessionId, + chat: getSessionChatDragData(fromHeader), + }, { + toolbarPrevented: true, + headerPrevented: false, + session: session.sessionId, + chat: { sessionId: session.sessionId, resource: mainChat.resource.toString() }, + }); + }); + + test('the end of a drag of the header, that of the session or its chat, is handed to the session drag-out, and not when the header drags the editor of its chat', () => { + const ended: string[] = []; + disposables.add(registerSessionChatDragEndHandler(async (_e, _element, session) => { ended.push(session.sessionId); return true; })); + const { header, session } = createHarness(disposables); + + header.element.dispatchEvent(new DragEvent(EventType.DRAG_END, { bubbles: true })); + const sessionDrag = [...ended]; + header.setDragsEditor(true); + header.element.dispatchEvent(new DragEvent(EventType.DRAG_END, { bubbles: true })); + + assert.deepStrictEqual({ sessionDrag, afterEditorDrag: ended }, { sessionDrag: [session.sessionId], afterEditorDrag: [session.sessionId] }); + }); + test('a small pointer move over the title actions toolbar does not start a session drag', () => { const { header } = createHarness(disposables); @@ -239,7 +315,7 @@ suite('Sessions - Headers', () => { test(`${paneClass} headers leave a six-pixel drag-free buffer by resize boundaries`, () => { const { store, instantiationService, header: sessionHeader, session, activeChat } = createHarness(disposables); const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { } }); + chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { }, close: () => { } }); const header = paneClass === 'session-view' ? sessionHeader : chatHeader; const pane = $(`.${paneClass}`); pane.style.width = '400px'; @@ -266,7 +342,7 @@ suite('Sessions - Headers', () => { const { store, instantiationService, header, session, activeChat, secondChat } = createHarness(disposables); activeChat.set(secondChat, undefined); const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { } }); + chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { }, close: () => { } }); const transfer = LocalSelectionTransfer.getInstance<DraggedSessionIdentifier>(); const describeDrag = (target: SessionHeader | ChatHeader) => { const event = simulateDragFrom(target, target.element); @@ -290,7 +366,7 @@ suite('Sessions - Headers', () => { test('a main-chat group header drags its chat while the session header still drags the session', () => { const { store, instantiationService, header, session, activeChat, mainChat } = createHarness(disposables); const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { } }); + chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { }, close: () => { } }); const chatDrag = simulateDragFrom(chatHeader, chatHeader.element); const sessionDrag = simulateDragFrom(header, header.element); header.element.dispatchEvent(new DragEvent(EventType.DRAG_END)); @@ -315,7 +391,7 @@ suite('Sessions - Headers', () => { test('chat header toolbar gestures and title editing do not start a drag', () => { const { store, instantiationService, header, session, activeChat } = createHarness(disposables, { supportsRename: true, supportsMultipleChats: true }); const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { } }); + chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { }, close: () => { } }); const toolbarDrag = simulateDragFrom(chatHeader, chatHeader.element.querySelector<HTMLElement>('.chat-composite-bar-title-actions')!); header.startTitleEditing(); const editingDrag = simulateDragFrom(header, header.element); @@ -428,6 +504,7 @@ suite('Sessions - Headers', () => { chat: activeChat, isDetached: false, activate: () => activationCalls++, + close: () => { }, }); header.element.querySelector<HTMLElement>('.chat-composite-bar-title-actions') @@ -436,10 +513,11 @@ suite('Sessions - Headers', () => { assert.strictEqual(activationCalls, 1); }); - test('middle-clicking a session title closes only the session header', () => { + test('middle-clicking session and chat titles closes their represented panes', () => { const { store, instantiationService, header, session, activeChat, closedSessions } = createHarness(disposables); const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { } }); + let closedChats = 0; + chatHeader.setChat({ session, chat: activeChat, isDetached: false, activate: () => { }, close: () => closedChats++ }); const sessionMiddleClick = new MouseEvent(EventType.AUXCLICK, { bubbles: true, button: 1, cancelable: true }); const sessionRightClick = new MouseEvent(EventType.AUXCLICK, { bubbles: true, button: 2, cancelable: true }); const chatMiddleClick = new MouseEvent(EventType.AUXCLICK, { bubbles: true, button: 1, cancelable: true }); @@ -450,6 +528,7 @@ suite('Sessions - Headers', () => { assert.deepStrictEqual({ closedSessions, + closedChats, sessionMiddleClickDefaultPrevented: sessionMiddleClick.defaultPrevented, sessionDispatchResult, sessionRightClickDefaultPrevented: sessionRightClick.defaultPrevented, @@ -457,11 +536,12 @@ suite('Sessions - Headers', () => { chatDispatchResult, }, { closedSessions: ['session'], + closedChats: 1, sessionMiddleClickDefaultPrevented: true, sessionDispatchResult: false, sessionRightClickDefaultPrevented: false, - chatMiddleClickDefaultPrevented: false, - chatDispatchResult: true, + chatMiddleClickDefaultPrevented: true, + chatDispatchResult: false, }); }); @@ -495,6 +575,7 @@ suite('Sessions - Headers', () => { chat: activeChat, isDetached: false, activate: () => { }, + close: () => { }, }); const describe = (args: readonly unknown[]) => args.map(arg => arg === session ? 'session' @@ -600,7 +681,7 @@ suite('Sessions - Headers', () => { secondChat.status.set(SessionStatus.InProgress, undefined); const createChatHeader = (chat: IChat) => { const header = store.add(instantiationService.createInstance(ChatHeader)); - header.setChat({ session, chat: constObservable(chat), isDetached: false, activate: () => { } }); + header.setChat({ session, chat: constObservable(chat), isDetached: false, activate: () => { }, close: () => { } }); return header; }; const mainHeader = createChatHeader(mainChat); @@ -626,7 +707,7 @@ suite('Sessions - Headers', () => { session.chats.set([mainChat, child], undefined); const createChatHeader = (chat: IChat) => { const chatHeader = store.add(instantiationService.createInstance(ChatHeader)); - chatHeader.setChat({ session, chat: constObservable(chat), isDetached: false, activate: () => { } }); + chatHeader.setChat({ session, chat: constObservable(chat), isDetached: false, activate: () => { }, close: () => { } }); return chatHeader; }; const mainHeader = createChatHeader(mainChat); @@ -715,6 +796,7 @@ suite('Sessions - Headers', () => { chat: activeChat, isDetached: false, activate: () => { }, + close: () => { }, }); assert.strictEqual(header.element.querySelector<HTMLElement>('.chat-composite-bar-session-title-text .label-name')?.textContent, 'New Session'); diff --git a/src/vs/workbench/contrib/sessions/test/browser/scheduledChatTimePicker.test.ts b/src/vs/workbench/contrib/sessions/test/browser/scheduledChatTimePicker.test.ts new file mode 100644 index 000000000000..aefe885aae77 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/scheduledChatTimePicker.test.ts @@ -0,0 +1,196 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../base/browser/dom.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IPickOptions, IQuickInputHideEvent, IQuickInputService, IQuickPickItem, IQuickWidget, QuickInputHideReason, QuickPickInput } from '../../../../../platform/quickinput/common/quickInput.js'; +import { pickScheduledChatTime } from '../../browser/scheduledChatTimePicker.js'; + +suite('Scheduled chat time picker', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + // Local midday mid-month, so rounding the suggestion up to the next quarter hour never crosses a day or month. + const fixedNow = new Date(2030, 4, 15, 12, 0).getTime(); + const timedTest = (name: string, fn: () => Promise<void>) => test(name, () => runWithFakedTimers({ startTime: fixedNow }, fn)); + + function create(preset?: string) { + const onDidHide = store.add(new Emitter<IQuickInputHideEvent>()); + const shown = new DeferredPromise<void>(); + const container = document.body.appendChild($('div')); + store.add(toDisposable(() => container.remove())); + let choices: readonly IQuickPickItem[] = []; + let focusedAtHide: Element | null | undefined; + const picker = upcastPartial<IQuickWidget>({ + onDidHide: onDidHide.event, + show: () => { + container.appendChild(picker.widget as HTMLElement); + shown.complete(); + }, + hide: () => { + focusedAtHide = document.activeElement; + onDidHide.fire({ reason: QuickInputHideReason.Gesture }); + }, + dispose: () => { container.replaceChildren(); }, + }); + const quickInput = new class extends mock<IQuickInputService>() { + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options: IPickOptions<T> & { canPickMany: true }): Promise<T[] | undefined>; + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options: IPickOptions<T> & { canPickMany: false }): Promise<T | undefined>; + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: Omit<IPickOptions<T>, 'canPickMany'>): Promise<T | undefined>; + override async pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: IPickOptions<T>): Promise<T | T[] | undefined> { + const picks = (await items).filter((item): item is T => item.type !== 'separator'); + choices = picks; + const item = preset ? picks.find(item => item.label === preset) : picks.at(-1); + return options?.canPickMany ? item && [item] : item; + } + override createQuickWidget() { return picker; } + }; + const result = pickScheduledChatTime(quickInput); + const ready = async () => { + await shown.p; + const query = (selector: string) => container.querySelector<HTMLElement>(selector)!; + return { + time: container.querySelector('select')!, + exact: container.querySelector<HTMLInputElement>('input[type="time"]')!, + previousMonth: container.querySelectorAll<HTMLElement>('.scheduled-chat-calendar-header .monaco-button')[0], + nextMonth: container.querySelectorAll<HTMLElement>('.scheduled-chat-calendar-header .monaco-button')[1], + schedule: query('.scheduled-chat-time-actions .monaco-button'), + cancel: container.querySelectorAll<HTMLElement>('.scheduled-chat-time-actions .monaco-button')[1], + summary: query('[role="status"]'), + day: (day: number) => [...container.querySelectorAll<HTMLElement>('[role="gridcell"]')].find(cell => cell.textContent === String(day))!, + focusedDay: () => container.querySelector<HTMLElement>('[role="gridcell"][tabindex="0"]')!, + press: (key: string) => container.querySelector<HTMLElement>('[role="gridcell"][tabindex="0"]')!.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })), + selectTime: (index: number) => { + const time = container.querySelector('select')!; + time.selectedIndex = index; + time.dispatchEvent(new InputEvent('change')); + }, + }; + }; + return { result, ready, picker, get choices() { return choices; }, get focusedAtHide() { return focusedAtHide; } }; + } + + function today(offsetDays = 0, hours = 0, minutes = 0): Date { + const now = new Date(); + return new Date(now.getFullYear(), now.getMonth(), now.getDate() + offsetDays, hours, minutes); + } + + timedTest('presets omit timestamps and schedule tomorrow at local 9 AM', async () => { + const fixture = create('Tomorrow Morning'); + const date = await fixture.result; + assert.deepStrictEqual({ + labels: fixture.choices.map(item => item.label), + hasDescriptions: fixture.choices.some(item => !!item.description), + date: date?.getTime(), + }, { + labels: ['In 5 Minutes', 'In 10 Minutes', 'In 15 Minutes', 'In 30 Minutes', 'In 1 Hour', 'In 24 Hours', 'Tomorrow Morning', 'Choose Date and Time...'], + hasDescriptions: false, + date: today(1, 9).getTime(), + }); + }); + + timedTest('calendar clicks and quarter-hour dropdown schedule a local time without text input', async () => { + const fixture = create(); + const { nextMonth, day, selectTime, schedule, summary, time } = await fixture.ready(); + nextMonth.click(); + day(15).click(); + selectTime(38); + const expected = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15, 9, 30); + const summaryText = summary.textContent; + const selected = day(15).getAttribute('aria-selected'); + schedule.click(); + assert.deepStrictEqual({ + date: (await fixture.result)?.getTime(), + options: time.options.length, + selected, + summary: summaryText, + }, { + date: expected.getTime(), + options: 97, + selected: 'true', + summary: `Send ${expected.toLocaleString(undefined, { timeZoneName: 'short' })}`, + }); + }); + + timedTest('calendar keyboard navigation moves by day and week, stops at today, and selects with Enter', async () => { + const fixture = create(); + const { press, focusedDay, previousMonth, selectTime, schedule } = await fixture.ready(); + for (let i = 0; i < 40; i++) { + press('ArrowLeft'); + } + const clampedToToday = focusedDay().getAttribute('aria-label'); + press('ArrowDown'); + press('ArrowRight'); + press('Enter'); + const focusFollowed = document.activeElement === focusedDay(); + selectTime(38); + schedule.click(); + assert.deepStrictEqual({ + clampedToToday, + focusFollowed, + previousMonthEnabled: previousMonth.getAttribute('aria-disabled') !== 'true', + date: (await fixture.result)?.getTime(), + }, { + clampedToToday: today().toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), + focusFollowed: true, + previousMonthEnabled: today(8).getMonth() !== today().getMonth(), + date: today(8, 9, 30).getTime(), + }); + }); + + timedTest('exact time supports minutes outside the quarter-hour options', async () => { + const fixture = create(); + const { nextMonth, day, selectTime, exact, schedule } = await fixture.ready(); + nextMonth.click(); + day(15).click(); + selectTime(96); + const focused = document.activeElement === exact; + exact.value = '09:37'; + exact.dispatchEvent(new InputEvent('input')); + schedule.click(); + assert.deepStrictEqual({ focused, date: (await fixture.result)?.getTime() }, { + focused: true, date: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 15, 9, 37).getTime(), + }); + }); + + timedTest('past and incomplete times cannot be scheduled and expose a visible reason', async () => { + const fixture = create(); + const { press, selectTime, exact, schedule, summary, cancel } = await fixture.ready(); + press('ArrowLeft'); + press('Enter'); + const state = () => ({ enabled: schedule.getAttribute('aria-disabled') !== 'true', reason: summary.textContent }); + selectTime(0); + const past = state(); + selectTime(96); + exact.value = ''; + exact.dispatchEvent(new InputEvent('input')); + const incomplete = state(); + cancel.click(); + const invalid = { enabled: false, reason: 'Choose a valid future date and time.' }; + assert.deepStrictEqual({ past, incomplete, date: await fixture.result }, { past: invalid, incomplete: invalid, date: undefined }); + }); + + timedTest('Escape on a picker button cancels while focus is still inside the picker', async () => { + const fixture = create(); + const { nextMonth } = await fixture.ready(); + nextMonth.focus(); + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + nextMonth.dispatchEvent(event); + assert.deepStrictEqual({ date: await fixture.result, focusedAtHide: fixture.focusedAtHide === nextMonth, handled: event.defaultPrevented }, { + date: undefined, focusedAtHide: true, handled: true, + }); + }); + + timedTest('dismissing the custom picker returns no date', async () => { + const fixture = create(); + await fixture.ready(); + fixture.picker.hide(); + assert.strictEqual(await fixture.result, undefined); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/scheduledChatsService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/scheduledChatsService.test.ts new file mode 100644 index 000000000000..c4f6a234b2c9 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/scheduledChatsService.test.ts @@ -0,0 +1,879 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $ } from '../../../../../base/browser/dom.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { parse } from '../../../../../base/common/marshalling.js'; +import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ITextModelService } from '../../../../../editor/common/services/resolverService.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestDialogService } from '../../../../../platform/dialogs/test/common/testDialogService.js'; +import { IFileService } from '../../../../../platform/files/common/files.js'; +import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IPickOptions, IQuickInputHideEvent, IQuickInputService, IQuickPickItem, IQuickWidget, QuickInputHideReason, QuickPickInput } from '../../../../../platform/quickinput/common/quickInput.js'; +import { InMemoryStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; +import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { ChatInteractivity, IChat, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { IWorkingCopyService } from '../../../../services/workingCopy/common/workingCopyService.js'; +import { IChatDraft } from '../../../chat/common/attachments/chatDraft.js'; +import { ChatRequestVariableSet } from '../../../chat/common/attachments/chatVariableEntries.js'; +import { ChatAttachmentModel } from '../../../chat/browser/attachments/chatAttachmentModel.js'; +import { IChatWidget } from '../../../chat/browser/chat.js'; +import { ChatInputPart } from '../../../chat/browser/widget/input/chatInputPart.js'; +import { IChatScheduledRequest, IChatViewModel } from '../../../chat/common/model/chatViewModel.js'; +import { IChatModel, IChatModelInputState } from '../../../chat/common/model/chatModel.js'; +import { MockChatModel } from '../../../chat/test/common/model/mockChatModel.js'; +import { IChatService } from '../../../chat/common/chatService/chatService.js'; +import { IAutomationDescriptor, IAutomationRun } from '../../../chat/common/automations/automation.js'; +import { AutomationMutationGuard, IAutomationService, ICreateAutomationOptions, IUpdateAutomationOptions } from '../../../chat/common/automations/automationService.js'; +import { CHAT_AUTOMATIONS_ENABLED_SETTING } from '../../../chat/common/automations/automationsEnabled.js'; +import { IScheduledChatRequestOptions, ScheduledChatsService } from '../../browser/scheduledChatsService.js'; +import { ISessionsService } from '../../browser/sessionsService.js'; +import { ISessionDraftsService } from '../../browser/sessionDraftsService.js'; +import { ISessionGroupsService } from '../../browser/sessionGroupsService.js'; +import { ISavedSessionDraftTarget } from '../../common/savedSessionDrafts.js'; +import { ChatInputCanScheduleContext } from '../../common/contextkeys.js'; +import { SESSIONS_DRAFTS_ENABLED_SETTING, SESSIONS_SEND_LATER_ENABLED_SETTING } from '../../common/sessionConfig.js'; +import { ISessionsChangeEvent, ISessionsManagementService } from '../../common/sessionsManagement.js'; + +suite('Scheduled chat handoffs', () => { + // The custom picker fixture chooses the 15th of next month at 9:30. Tests that use it freeze the clock at a local + // midday mid-month, so the picker's initial suggestion never rounds into another month. + const fixedNow = new Date(2030, 4, 15, 12, 0).getTime(); + const customTime = new Date(2030, 5, 15, 9, 30); + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const input: IChatDraft = { inputText: 'Review the changes', attachments: [] }; + const target: ISavedSessionDraftTarget = { providerId: 'local', sessionTypeId: 'copilot' }; + const session = new class extends mock<ISession>() { + override readonly providerId = 'local'; + override readonly sessionType = 'copilot'; + }; + + function create(sendLater = true, savedDrafts = true, pickerWait?: Promise<void>, existingStorage?: InMemoryStorageService) { + const storage = existingStorage ?? disposables.add(new InMemoryStorageService()); + const config = new TestConfigurationService({ + [SESSIONS_SEND_LATER_ENABLED_SETTING]: sendLater, + [SESSIONS_DRAFTS_ENABLED_SETTING]: savedDrafts, + [CHAT_AUTOMATIONS_ENABLED_SETTING]: true, + }); + const calls: string[] = []; + const openedDrafts: Parameters<ISessionDraftsService['open']>[] = []; + const loadedChats: URI[] = []; + const openedChats: URI[] = []; + const recoveredInputs: Parameters<IChatModel['inputModel']['setState']>[0][] = []; + const requests: ICreateAutomationOptions[] = []; + let failCreate = false; + let failDelete = false; + let publishBeforeFailure = false; + let conflict = false; + let occupied = false; + let picks = 0; + let customTime = false; + const pickerAnchors: Pick<IPickOptions<IQuickPickItem>, 'anchor' | 'anchorPosition'>[] = []; + const automations = observableValue<readonly IAutomationDescriptor[]>('automations', []); + const runs = observableValue<readonly IAutomationRun[]>('runs', []); + const sessionsChanged = disposables.add(new Emitter<ISessionsChangeEvent>()); + const sessions = new Map<string, ISession>(); + const memberships = new Map<string, string>(); + const automationService = new class extends mock<IAutomationService>() { + override readonly automations = automations; + override readonly runs = runs; + override readonly catalogueState = constObservable('ready' as const); + override readonly availableProviders = constObservable([{ id: 'local', label: 'Local', supportsOneTimeAutomation: true, supportsExistingChatAutomation: true }]); + override canCreateAutomation() { return true; } + override canRunAutomation() { return true; } + override getAutomation(id: string) { return automations.get().find(automation => automation.id === id); } + override async refresh() { calls.push('refresh'); } + override async createAutomation(options: ICreateAutomationOptions, guard?: AutomationMutationGuard): Promise<IAutomationDescriptor> { + guard?.(); + assert.ok(storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE), 'The complete handoff must be durable before dispatch'); + const { onWillCreate, ...request } = options; + onWillCreate?.('opaque:definition'); + requests.push(request); + assert.strictEqual(JSON.parse(storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs.at(-1).requestedAutomationId, 'opaque:definition'); + const definition: IAutomationDescriptor = { ...options, id: 'opaque:definition', enabled: options.enabled ?? true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; + if (!failCreate || publishBeforeFailure) { + automations.set([definition], undefined); + } + if (failCreate) { + throw new Error('Acknowledgement lost'); + } + return definition; + } + override async updateAutomationIfUnchanged(id: string, patch: IUpdateAutomationOptions, expected: IAutomationDescriptor, guard?: AutomationMutationGuard) { + guard?.(); + if (expected.purpose === 'scheduledChat' && !expected.enabled) { + throw new Error('Cancelled scheduled chats cannot be updated'); + } + calls.push(patch.enabled === false ? 'disable' : 'update'); + if (conflict) { + return { kind: 'conflict' as const, current: expected }; + } + const updated = { + ...expected, enabled: patch.enabled ?? expected.enabled, + name: patch.name ?? expected.name, prompt: patch.prompt ?? expected.prompt, + request: patch.request ?? expected.request, schedule: patch.schedule ?? expected.schedule, + }; + automations.set([updated], undefined); + return { kind: 'updated' as const, automation: updated }; + } + override async deleteAutomation() { + calls.push('delete'); + if (failDelete) { + throw new Error('Deletion failed'); + } + automations.set([], undefined); + } + }; + const drafts = new class extends mock<ISessionDraftsService>() { + override readonly enabled = constObservable(savedDrafts); + override save(input: IChatDraft, target: ISavedSessionDraftTarget) { + calls.push('save'); + return { id: 'recovery', revision: 'revision', input, target, createdAt: 0, updatedAt: 0 }; + } + override async open(...args: Parameters<ISessionDraftsService['open']>) { + calls.push('open'); + openedDrafts.push(args); + } + override async restoreRecovery() { + calls.push('recover'); + if (occupied) { + throw new Error('Composer occupied'); + } + } + }; + const quickInput = new class extends mock<IQuickInputService>() { + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: IPickOptions<T> & { canPickMany: true }): Promise<T[] | undefined>; + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: IPickOptions<T> & { canPickMany: false }): Promise<T | undefined>; + override pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: Omit<IPickOptions<T>, 'canPickMany'>): Promise<T | undefined>; + override async pick<T extends IQuickPickItem>(items: QuickPickInput<T>[] | Promise<QuickPickInput<T>[]>, options?: IPickOptions<T>): Promise<T | T[] | undefined> { + picks++; + pickerAnchors.push({ anchor: options?.anchor, anchorPosition: options?.anchorPosition }); + await pickerWait; + const choices = (await items).filter((item): item is T => item.type !== 'separator'); + const item = customTime ? choices.at(-1) : choices[0]; + return options?.canPickMany ? item && [item] : item; + } + override createQuickWidget(): IQuickWidget { + const onDidHide = disposables.add(new Emitter<IQuickInputHideEvent>()); + const picker = upcastPartial<IQuickWidget>({ + onDidHide: onDidHide.event, + show: () => { + pickerAnchors.push({ anchor: picker.anchor, anchorPosition: picker.anchorPosition }); + const form = picker.widget as HTMLElement; + form.querySelectorAll<HTMLElement>('.scheduled-chat-calendar-header .monaco-button')[1].click(); + [...form.querySelectorAll<HTMLElement>('[role="gridcell"]')].find(cell => cell.textContent === '15')!.click(); + const time = form.querySelector('select')!; + time.selectedIndex = 38; + time.dispatchEvent(new InputEvent('change')); + form.querySelector<HTMLElement>('.scheduled-chat-time-actions .monaco-button')!.click(); + }, + hide: () => onDidHide.fire({ reason: QuickInputHideReason.Gesture }), + dispose: () => { }, + }); + return picker; + } + }; + const service = disposables.add(new ScheduledChatsService(config, automationService, + new class extends mock<ISessionsManagementService>() { + override readonly onDidChangeSessions = sessionsChanged.event; + override getSession(resource: URI) { return sessions.get(resource.toString()); } + override async getAutomationSessionConfiguration() { return { sessionTemplate: { modelId: 'chosen-model', config: { permission: 'default' } } }; } + }, drafts, + new class extends mock<IChatEntitlementService>() { + override readonly sentiment = {}; + override readonly onDidChangeSentiment = Event.None; + }, quickInput, new class extends TestDialogService { + override async confirm(): Promise<never> { throw new Error('Scheduling must not open a confirmation dialog'); } + }(), storage, + new class extends mock<ITextModelService>() { }, new class extends mock<IFileService>() { }, + new class extends mock<IWorkingCopyService>() { override isDirty() { return false; } }, + new class extends mock<IChatService>() { + override async acquireOrLoadSession(resource: URI) { + calls.push('load'); + loadedChats.push(resource); + return { + object: upcastPartial<IChatModel>({ + inputModel: upcastPartial<IChatModel['inputModel']>({ + state: constObservable<IChatModelInputState | undefined>(occupied ? { + inputText: 'already typing', attachments: [], contrib: {}, + mode: { id: 'agent', kind: undefined }, selectedModel: undefined, selections: [], + } : undefined), + setState: state => { calls.push('restore'); recoveredInputs.push(state); }, + }), + }), + dispose: () => { calls.push('release'); }, + }; + } + }, new class extends mock<ISessionsService>() { + override async openChat(_session: ISession, resource: URI) { + calls.push('openChat'); + openedChats.push(resource); + } + }, + new class extends mock<ISessionGroupsService>() { + override getGroup(id: string) { return { id, name: 'Group', createdAt: 0 }; } + override getGroupOfSession(id: string) { return memberships.get(id); } + override addToGroup(ids: string | Iterable<string>, groupId: string) { + for (const id of typeof ids === 'string' ? [ids] : ids) { + memberships.set(id, groupId); + calls.push('group'); + } + } + })); + return { + service, storage, config, calls, openedDrafts, loadedChats, openedChats, recoveredInputs, requests, automations, runs, sessions, sessionsChanged, memberships, pickerAnchors, + set customTime(value: boolean) { customTime = value; }, + get picks() { return picks; }, + set failCreate(value: boolean) { failCreate = value; }, + set failDelete(value: boolean) { failDelete = value; }, + set publishBeforeFailure(value: boolean) { publishBeforeFailure = value; }, + set conflict(value: boolean) { conflict = value; }, + set occupied(value: boolean) { occupied = value; }, + }; + } + + function registerInput(service: ScheduledChatsService, resource = URI.parse('agent-host-copilot:/session/non-main'), sessionResource = URI.parse('agent-host-copilot:/session')) { + const interactivity = observableValue('interactivity', ChatInteractivity.Full); + const chat = upcastPartial<IChat>({ resource, interactivity, isArchived: constObservable(false) }); + const currentSession = upcastPartial<ISession>({ + resource: sessionResource, providerId: 'local', sessionType: 'copilot', + status: constObservable(SessionStatus.Completed), chats: constObservable([chat]), + isArchived: constObservable(false), workspace: constObservable(undefined), isQuickChat: constObservable(true), + environment: 'local', harness: 'copilot', application: constObservable({ id: 'vscode', label: 'VS Code' }), + }); + const model = disposables.add(new MockChatModel(resource)); + let text = input.inputText; + let enabled = true; + let scheduled: readonly IChatScheduledRequest[] = []; + const context = disposables.add(new MockContextKeyService()); + const anchor = $('div'); + const widget = upcastPartial<IChatWidget>({ + scopedContextKeyService: context, + onDidChangeViewModel: Event.None, + viewModel: upcastPartial<IChatViewModel>({ model, sessionResource: resource, setScheduledRequests: requests => { scheduled = requests; } }), + getInput: () => text, + setInput: value => { text = value ?? ''; }, + getContrib: () => undefined, + attachmentModel: upcastPartial<ChatAttachmentModel>({ clearAndSetContext: () => { } }), + input: upcastPartial<ChatInputPart>({ + executeToolbarElement: anchor, + getAttachedContext: () => new ChatRequestVariableSet(), + setInputEnabled: value => { enabled = value; }, + }), + }); + disposables.add(service.registerChatInput(widget, constObservable(currentSession), constObservable(resource), constObservable(true))); + return { widget, context, interactivity, resource, anchor, get scheduled() { return scheduled; }, get text() { return text; }, get enabled() { return enabled; } }; + } + + for (const existingChat of [false, true]) { + test(`anchors the time picker and custom calendar above the send controls (existing chat: ${existingChat})`, () => runWithFakedTimers({ startTime: fixedNow }, async () => { + const fixture = create(); + fixture.customTime = true; + const source = registerInput(fixture.service); + if (existingChat) { + await fixture.service.scheduleChatInput(source.widget); + } else { + await fixture.service.schedule(input, target, session, 'new-composition', undefined, source.anchor); + } + assert.deepStrictEqual(fixture.pickerAnchors, [ + { anchor: source.anchor, anchorPosition: 'above' }, + { anchor: source.anchor, anchorPosition: 'above' }, + ]); + })); + } + + test('opening the time picker retains dropdown availability but prevents duplicate scheduling', async () => { + const picker = new DeferredPromise<void>(); + const fixture = create(true, true, picker.p); + const source = registerInput(fixture.service); + const scheduling = fixture.service.scheduleChatInput(source.widget); + const during = { available: source.context.getContextKeyValue(ChatInputCanScheduleContext.key), inputEnabled: source.enabled }; + await assert.rejects(() => fixture.service.scheduleChatInput(source.widget), /not available/); + picker.complete(); + await scheduling; + assert.deepStrictEqual({ during, picks: fixture.picks, inputEnabled: source.enabled }, { + during: { available: true, inputEnabled: false }, picks: 1, inputEnabled: true, + }); + }); + + test('rescheduling anchors both time pickers above the scheduled message', () => runWithFakedTimers({ startTime: fixedNow }, async () => { + const fixture = create(); + const source = registerInput(fixture.service); + await fixture.service.scheduleChatInput(source.widget); + fixture.customTime = true; + const anchor = $('div.rendered-markdown'); + await source.scheduled[0].actions.find(action => action.id === 'sessions.scheduled.reschedule')!.run(anchor); + assert.deepStrictEqual({ + anchors: fixture.pickerAnchors.slice(1), + runAt: fixture.automations.get()[0].schedule.runAt, + }, { + anchors: [{ anchor, anchorPosition: 'above' }, { anchor, anchorPosition: 'above' }], + runAt: customTime.toISOString(), + }); + })); + + test('scheduled messages belong only to their exact session and chat, and disappear after dispatch', async () => { + const fixture = create(); + const source = registerInput(fixture.service); + const otherChat = registerInput(fixture.service, URI.parse('agent-host-copilot:/session/other')); + const otherSession = registerInput(fixture.service, source.resource, URI.parse('agent-host-copilot:/other-session')); + await fixture.service.scheduleChatInput(source.widget); + const before = [source, otherChat, otherSession].map(input => input.scheduled.map(request => request.text)); + fixture.automations.set([{ ...fixture.automations.get()[0], oneTimeDispatchedAt: new Date().toISOString() }], undefined); + assert.deepStrictEqual({ before, after: source.scheduled }, { before: [[input.inputText], [], []], after: [] }); + }); + + test('draft and send-later gates are independent in all four combinations', () => { + assert.deepStrictEqual([false, true].flatMap(sendLater => [false, true].map(savedDrafts => { + const { service } = create(sendLater, savedDrafts); + return service.canSchedule(session); + })), [false, false, true, true]); + }); + + test('scheduled conversation messages offer Edit and inline management actions, not draft or preview actions', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + fixture.sessions.set(conversation.sessionResource.toString(), session); + await fixture.service.schedule(input, target, session, 'composition', conversation); + // Older descriptors can omit the conversation; the durable handoff still identifies it. + fixture.automations.set([{ ...fixture.automations.get()[0], conversation: undefined }], undefined); + const item = fixture.service.items.get()[0]; + await item.editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + assert.deepStrictEqual({ + actions: item.actions.map(action => ({ label: action.label, hasIcon: !!action.class })), + editIsShared: item.editAction === item.actions[0], + calls: fixture.calls, loadedChats: fixture.loadedChats, openedChats: fixture.openedChats, + input: fixture.recoveredInputs.map(input => input.inputText), editingText: editing.text, + enabled: fixture.automations.get()[0].enabled, + }, { + actions: ['Edit', 'Send Now', 'Reschedule...', 'Cancel Schedule'].map(label => ({ label, hasIcon: true })), + editIsShared: true, calls: [], loadedChats: [], openedChats: [], + input: [], editingText: input.inputText, enabled: true, + }); + }); + + test('scheduled conversation edits update text and send time without occupying the chat input', () => runWithFakedTimers({ startTime: fixedNow }, async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + fixture.sessions.set(conversation.sessionResource.toString(), session); + await fixture.service.schedule(input, target, session, 'composition', conversation); + fixture.occupied = true; + await fixture.service.items.get()[0].editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + editing.text = 'Changed scheduled message'; + fixture.customTime = true; + const anchor = $('button'); + await editing.selectTime.run(anchor); + await editing.save(); + const updated = fixture.automations.get()[0]; + assert.deepStrictEqual({ + text: updated.request?.text, prompt: updated.prompt, enabled: updated.enabled, + runAt: updated.schedule.runAt, calls: fixture.calls, recoveredInputs: fixture.recoveredInputs, + editing: fixture.service.items.get()[0].editing, + anchors: fixture.pickerAnchors.slice(1).map(options => options.anchor === anchor && options.anchorPosition === 'above'), + recoveryText: parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs[0].input.inputText, + }, { + text: 'Changed scheduled message', prompt: 'Changed scheduled message', enabled: true, + runAt: customTime.toISOString(), calls: ['update'], recoveredInputs: [], + editing: undefined, anchors: [true, true], recoveryText: 'Changed scheduled message', + }); + })); + + test('scheduled conversation edit conflicts preserve edits and cancellation keeps the original schedule', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + await fixture.service.schedule(input, target, session, 'composition', conversation); + const original = fixture.automations.get()[0]; + await fixture.service.items.get()[0].editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + editing.text = 'Unsaved change'; + fixture.conflict = true; + await assert.rejects(() => editing.save(), /changed or has started/); + const retainedText = fixture.service.items.get()[0].editing?.text; + editing.cancel(); + assert.deepStrictEqual({ + retainedText, editing: fixture.service.items.get()[0].editing, + unchanged: fixture.automations.get()[0] === original, calls: fixture.calls, + }, { + retainedText: 'Unsaved change', editing: undefined, unchanged: true, calls: ['update'], + }); + }); + + test('scheduled conversation edits keep attachments and clear stale inline ranges, including attachment-only edits', async () => { + for (const text of ['Changed text', '']) { + const fixture = create(); + const resource = URI.file('/workspace/notes.txt'); + const attached: IChatDraft = { + inputText: '#notes Review this', + attachments: [{ kind: 'file', id: 'notes', name: 'notes.txt', value: resource, range: { start: 0, endExclusive: 6 } }], + references: [{ id: 'notes', data: resource, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 7 } }], + }; + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + await fixture.service.schedule(attached, target, session, 'composition', conversation); + // Older descriptors rely on the durable handoff for captured attachments. + fixture.automations.set([{ ...fixture.automations.get()[0], request: undefined }], undefined); + await fixture.service.items.get()[0].editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + editing.text = text; + await editing.save(); + const stored = parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs[0]; + assert.deepStrictEqual({ + request: fixture.automations.get()[0].request, + recovery: stored.input, durableRequest: stored.request, + }, { + request: { text, origin: { kind: 'user' }, attachments: [{ type: 'resource', label: 'notes.txt', uri: resource.toString(), displayKind: 'document', range: undefined }] }, + recovery: { inputText: text, attachments: [{ kind: 'file', id: 'notes', name: 'notes.txt', value: resource }], references: [] }, + durableRequest: { text, origin: { kind: 'user' }, attachments: [{ type: 'resource', label: 'notes.txt', uri: resource.toString(), displayKind: 'document' }] }, + }); + } + }); + + test('scheduled edits add and remove context without recapturing retained snapshots', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + const attached: IChatDraft = { + inputText: 'Review context', + attachments: [ + { kind: 'string', id: 'keep', name: 'Snapshot', value: 'captured content', uri: URI.file('/workspace/snapshot'), handle: 1 }, + { kind: 'string', id: 'remove', name: 'Removed', value: 'remove this', uri: URI.file('/workspace/removed'), handle: 2 }, + ], + }; + await fixture.service.schedule(attached, target, session, 'composition', conversation); + await fixture.service.items.get()[0].editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + editing.input = { + inputText: attached.inputText, + attachments: [ + { kind: 'string', id: 'keep', name: 'Snapshot', value: 'changed since scheduling', uri: URI.file('/workspace/snapshot'), handle: 1 }, + { kind: 'string', id: 'new', name: 'Added', value: 'new content', uri: URI.file('/workspace/added'), handle: 3 }, + ], + }; + await editing.save(); + assert.deepStrictEqual({ + attachments: fixture.automations.get()[0].request?.attachments, + recoveryIds: parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs[0].input.attachments.map((entry: { id: string }) => entry.id), + saving: editing.isSaving?.get(), + }, { + attachments: [ + { type: 'simple', label: 'Snapshot', modelRepresentation: 'captured content' }, + { type: 'simple', label: 'Added', modelRepresentation: 'new content' }, + ], + recoveryIds: ['keep', 'new'], saving: false, + }); + }); + + test('scheduled edits without a local recovery copy keep captured context when adding attachments', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/session/secondary') }; + await fixture.service.schedule({ + inputText: 'Review', + attachments: [{ kind: 'string', id: 'original', name: 'Snapshot', value: 'original content', uri: URI.file('/workspace/snapshot'), handle: 1 }], + }, target, session, 'composition', conversation); + fixture.storage.remove('sessions.scheduledChatHandoffs', StorageScope.PROFILE); + await fixture.service.items.get()[0].editAction!.run(); + const editing = fixture.service.items.get()[0].editing!; + editing.input = { inputText: 'Review', attachments: [{ kind: 'string', id: 'new', name: 'Added', value: 'new content', uri: URI.file('/workspace/added'), handle: 2 }] }; + await editing.save(); + assert.deepStrictEqual(fixture.automations.get()[0].request?.attachments, [ + { type: 'simple', label: 'Snapshot', modelRepresentation: 'original content' }, + { type: 'simple', label: 'Added', modelRepresentation: 'new content' }, + ]); + }); + + test('expired scheduled conversation edits retain unsaved text without changing the schedule', async () => { + const fixture = create(); + const source = registerInput(fixture.service); + await fixture.service.scheduleChatInput(source.widget); + const original = fixture.automations.get()[0]; + await source.scheduled[0].editAction!.run(); + const editing = source.scheduled[0].editing!; + editing.text = 'Keep this edit'; + editing.runAt = '2000-01-01T00:00:00Z'; + await assert.rejects(() => editing.save(), /future send time/); + assert.deepStrictEqual({ + text: source.scheduled[0].editing?.text, unchanged: fixture.automations.get()[0] === original, calls: fixture.calls, + }, { text: 'Keep this edit', unchanged: true, calls: [] }); + }); + + test('an existing chat clears only after acceptance, retains rejected input, and blocks an uncertain ordinary send', async () => { + const fixture = create(); + const source = registerInput(fixture.service); + fixture.failCreate = true; + await assert.rejects(() => fixture.service.scheduleChatInput(source.widget), /Acknowledgement lost/); + const retained = { text: source.text, enabled: source.enabled }; + assert.throws(() => fixture.service.assertChatInputUnscheduled(source.widget, source.text), /being scheduled/); + fixture.failCreate = false; + await fixture.service.scheduleChatInput(source.widget); + assert.deepStrictEqual({ retained, text: source.text, enabled: source.enabled, picks: fixture.picks }, { + retained: { text: input.inputText, enabled: true }, text: '', enabled: true, picks: 1, + }); + }); + + test('existing chat availability follows interactivity and live setting changes, including stale commands', async () => { + const fixture = create(); + const source = registerInput(fixture.service); + source.interactivity.set(ChatInteractivity.ReadOnly, undefined); + const readOnly = source.context.getContextKeyValue(ChatInputCanScheduleContext.key); + await assert.rejects(() => fixture.service.scheduleChatInput(source.widget), /not available/); + source.interactivity.set(ChatInteractivity.Full, undefined); + await fixture.config.setUserConfiguration(SESSIONS_SEND_LATER_ENABLED_SETTING, false); + fixture.config.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: key => key === SESSIONS_SEND_LATER_ENABLED_SETTING, affectedKeys: new Set([SESSIONS_SEND_LATER_ENABLED_SETTING]), source: 1, change: { keys: [SESSIONS_SEND_LATER_ENABLED_SETTING], overrides: [] } }); + await assert.rejects(() => fixture.service.scheduleChatInput(source.widget), /not available/); + assert.deepStrictEqual({ readOnly, disabled: source.context.getContextKeyValue(ChatInputCanScheduleContext.key), requests: fixture.requests.length, text: source.text }, { + readOnly: false, disabled: false, requests: 0, text: input.inputText, + }); + }); + + test('the first time option schedules the request in 5 minutes', () => runWithFakedTimers({}, async () => { + const fixture = create(); + const now = Date.now(); + await fixture.service.schedule(input, target, session, 'composition'); + assert.strictEqual(fixture.requests[0].schedule.runAt, new Date(now + 5 * 60_000).toISOString()); + })); + + test('persists immutable input and configuration before accepting a schedule', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + const request = fixture.requests[0]; + const stored = parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!); + assert.deepStrictEqual({ + prompt: request.request?.text, model: request.sessionTemplate?.modelId, + schedule: stored.handoffs[0].schedule, accepted: stored.handoffs[0].automationId, + creationId: stored.handoffs[0].id, picks: fixture.picks, + }, { prompt: input.inputText, model: 'chosen-model', schedule: request.schedule, accepted: 'opaque:definition', creationId: request.creationId, picks: 1 }); + }); + + function toolRequest(conversation?: IAutomationDescriptor['conversation']): IScheduledChatRequestOptions { + return { + name: 'Check build', prompt: input.inputText, + schedule: { interval: 'once', runAt: '2099-01-01T10:00:00.000Z', scheduleHour: 0, scheduleMinute: 0, scheduleDay: 0 }, + target: { kind: 'quickChat', providerId: 'local', sessionTypeId: 'copilot' }, + conversation, + }; + } + + test('tool scheduling uses durable handoffs without opening a picker or claiming composer input', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/peer') }; + const result = await fixture.service.scheduleRequest(toolRequest(conversation), 'chat/call'); + assert.deepStrictEqual({ + status: result.status, picks: fixture.picks, claimed: [...fixture.service.claimedDraftIds.get()], + pending: fixture.service.hasPendingHandoff('composer', input), + conversation: fixture.requests[0].conversation, request: fixture.requests[0].request, + recovered: fixture.recoveredInputs, + }, { + status: 'accepted', picks: 0, claimed: [], pending: false, conversation, + request: { text: input.inputText, origin: { kind: 'user' } }, recovered: [], + }); + }); + + test('tool retries after reload reuse the saved identity and do not duplicate accepted schedules', async () => { + const first = create(); + first.failCreate = true; + const unknown = await first.service.scheduleRequest(toolRequest(), 'chat/call'); + const pending = first.service.getPendingRequests(); + first.service.dispose(); + const restored = create(true, true, undefined, first.storage); + const accepted = await restored.service.scheduleRequest(toolRequest(), 'chat/call'); + await restored.service.scheduleRequest(toolRequest(), 'chat/call'); + assert.deepStrictEqual({ + outcomes: [unknown.status, accepted.status], + pendingIds: pending.map(request => request.automationId), + creates: restored.requests, + remaining: restored.service.getPendingRequests(), + composerClaim: restored.service.hasPendingHandoff('composer', input), + }, { + outcomes: ['unknown', 'accepted'], pendingIds: ['opaque:definition'], + creates: [first.requests[0]], remaining: [], composerClaim: false, + }); + }); + + test('tool operation identities serialize duplicates but allow intentionally identical new requests', async () => { + const fixture = create(); + await Promise.all([ + fixture.service.scheduleRequest(toolRequest(), 'chat/call'), + fixture.service.scheduleRequest(toolRequest(), 'chat/call'), + ]); + await fixture.service.scheduleRequest(toolRequest(), 'chat/another-call'); + assert.deepStrictEqual({ count: fixture.requests.length, identities: new Set(fixture.requests.map(request => request.creationId)).size, picks: fixture.picks }, { count: 2, identities: 2, picks: 0 }); + }); + + test('a restored overdue tool handoff reuses captured configuration instead of reading live settings again', () => runWithFakedTimers<void>({ useFakeTimers: true }, async () => { + const first = create(); + first.failCreate = true; + const options = { ...toolRequest(), schedule: { ...toolRequest().schedule, runAt: new Date(Date.now() + 60_000).toISOString() } }; + await first.service.scheduleRequest(options, 'chat/call', undefined, async () => ({ modelId: 'original', config: { autoApprove: 'default' } })); + first.service.dispose(); + await timeout(60_001); + const restored = create(true, true, undefined, first.storage); + const result = await restored.service.scheduleRequest(options, 'chat/call', undefined, async () => { + throw new Error('Live configuration is unavailable'); + }); + assert.deepStrictEqual({ status: result.status, template: restored.requests[0].sessionTemplate }, { + status: 'accepted', template: { modelId: 'original', config: { autoApprove: 'default' } }, + }); + })); + + test('tool replay compares resource identity and persisted templates rather than URI caches or undefined keys', async () => { + for (const existingChat of [false, true]) { + const first = create(); + const folderUri = URI.file('/workspace'); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/peer') }; + const options: IScheduledChatRequestOptions = existingChat ? toolRequest(conversation) : { + ...toolRequest(), sessionTemplate: { modelId: undefined, config: { mode: 'plan' } }, + target: { kind: 'workspace', folderUri, isolation: { kind: 'default' }, providerId: 'local', sessionTypeId: 'copilot' }, + }; + folderUri.toString(); + void folderUri.fsPath; + conversation.chatResource.toString(); + first.failCreate = true; + await first.service.scheduleRequest(options, 'chat/call'); + first.service.dispose(); + const restored = create(true, true, undefined, first.storage); + const replay = await restored.service.scheduleRequest({ + ...options, + ...(options.target.kind === 'workspace' ? { target: { ...options.target, folderUri: URI.file('/workspace') } } : {}), + conversation: existingChat ? { + sessionResource: URI.parse('agent-host-copilot:/session'), + chatResource: URI.parse('agent-host-copilot:/peer'), + } : undefined, + }, 'chat/call'); + assert.deepStrictEqual({ status: replay.status, creates: restored.requests.length }, { status: 'accepted', creates: 1 }); + } + }); + + test('catalogue reconciliation durably records lost acknowledgements before definition removal', async () => { + const fixture = create(); + fixture.failCreate = true; + await fixture.service.scheduleRequest(toolRequest(), 'chat/call'); + fixture.automations.set([{ + ...fixture.requests[0], id: 'opaque:definition', enabled: true, + createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', + }], undefined); + const acceptedId = parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs[0].automationId; + fixture.automations.set([], undefined); + fixture.service.dispose(); + const restored = create(true, true, undefined, fixture.storage); + await assert.rejects(restored.service.scheduleRequest(toolRequest(), 'chat/call'), /already accepted.*will not be recreated/); + assert.deepStrictEqual({ acceptedId, pending: restored.service.getPendingRequests(), creates: restored.requests }, { + acceptedId: 'opaque:definition', pending: [], creates: [], + }); + }); + + for (const complete of [false, true]) { + test(`tool ${complete ? 'dispatch' : 'recovery'} compacts payloads to durable replay receipts`, async () => { + const fixture = create(); + await fixture.service.scheduleRequest({ ...toolRequest(), sessionTemplate: { modelId: 'captured' } }, 'chat/call'); + if (complete) { + fixture.automations.set(fixture.automations.get().map(automation => ({ ...automation, oneTimeDispatchedAt: '2026-01-01T00:00:00.000Z' })), undefined); + } else { + await fixture.service.items.get()[0].open(); + } + const handoffs = parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!).handoffs; + const receipts = parse(fixture.storage.get('sessions.scheduledChatReceipts', StorageScope.PROFILE)!).receipts; + assert.deepStrictEqual({ handoffs, receipts, pending: fixture.service.getPendingRequests(), known: fixture.service.hasRequest('chat/call') }, { + handoffs: [], receipts: [{ operationId: 'chat/call', automationId: 'opaque:definition' }], pending: [], known: true, + }); + }); + } + + test('tool scheduling rejects past instants and changed operations without replaying a different request', async () => { + const fixture = create(); + await assert.rejects(fixture.service.scheduleRequest({ ...toolRequest(), schedule: { ...toolRequest().schedule, runAt: '2000-01-01T00:00:00.000Z' } }, 'past'), /future send time/); + await fixture.service.scheduleRequest(toolRequest(), 'chat/call'); + await assert.rejects(fixture.service.scheduleRequest({ ...toolRequest(), prompt: 'Different request' }, 'chat/call'), /different saved request/); + await assert.rejects(fixture.service.scheduleRequest({ ...toolRequest(), sessionTemplate: { modelId: 'different-model' } }, 'chat/call'), /different saved request/); + fixture.automations.set([], undefined); + await assert.rejects(fixture.service.scheduleRequest(toolRequest(), 'chat/call'), /will not be recreated/); + assert.deepStrictEqual({ creates: fixture.requests.length, pending: fixture.service.getPendingRequests() }, { creates: 1, pending: [] }); + }); + + test('tool prompt edits update recovery content as well as the durable request', async () => { + const fixture = create(); + await fixture.service.scheduleRequest(toolRequest(), 'chat/call'); + const automation = fixture.automations.get()[0]; + await fixture.service.updateRequest(automation, { prompt: 'Changed', request: { ...automation.request!, text: 'Changed' } }); + const stored = parse(fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE)!); + assert.deepStrictEqual({ request: stored.handoffs[0].request.text, recovery: stored.handoffs[0].input.inputText, host: fixture.automations.get()[0].request?.text }, { request: 'Changed', recovery: 'Changed', host: 'Changed' }); + }); + + test('lost acknowledgements replay the same identity, time and captured message without asking for a new time', async () => { + const fixture = create(); + fixture.failCreate = true; + await assert.rejects(() => fixture.service.schedule(input, target, session, 'composition'), /Acknowledgement lost/); + assert.throws(() => fixture.service.assertUnscheduled('composition', input), /scheduling handoff/); + fixture.failCreate = false; + await fixture.service.schedule(input, target, session, 'composition'); + assert.deepStrictEqual({ requests: fixture.requests, picks: fixture.picks }, { requests: [fixture.requests[0], fixture.requests[0]], picks: 1 }); + }); + + test('reconciliation recognizes an accepted definition without another create', async () => { + const fixture = create(); + fixture.failCreate = true; + fixture.publishBeforeFailure = true; + await assert.rejects(() => fixture.service.schedule(input, target, session, 'composition'), /Acknowledgement lost/); + fixture.automations.set(fixture.automations.get().map(automation => ({ ...automation, creationId: undefined })), undefined); + await fixture.service.schedule(input, target, session, 'composition'); + assert.deepStrictEqual({ creates: fixture.requests.length, pending: fixture.service.hasPendingHandoff('composition', input) }, { creates: 1, pending: false }); + }); + + test('a follow-up keeps the exact non-main chat and does not capture or reapply a session template', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/opaque-secondary-chat') }; + await fixture.service.schedule(input, target, session, 'follow-up', conversation); + assert.deepStrictEqual({ + conversation: fixture.requests[0].conversation, + template: fixture.requests[0].sessionTemplate, + request: fixture.requests[0].request, + }, { conversation, template: undefined, request: { text: input.inputText, origin: { kind: 'user' } } }); + }); + + test('a released new-session source can schedule an identical new composition', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'first'); + fixture.service.releaseSource('first'); + await fixture.service.schedule(input, target, session, 'second'); + assert.strictEqual(fixture.requests.length, 2); + }); + + test('identical input in another conversation does not reconcile the wrong handoff', async () => { + const fixture = create(); + const conversation = { sessionResource: URI.parse('agent-host-copilot:/session'), chatResource: URI.parse('agent-host-copilot:/first') }; + fixture.failCreate = true; + await assert.rejects(() => fixture.service.schedule(input, target, session, 'first', conversation), /Acknowledgement lost/); + fixture.failCreate = false; + const other = { ...conversation, chatResource: URI.parse('agent-host-copilot:/second') }; + await fixture.service.schedule(input, target, session, 'second', other); + assert.deepStrictEqual({ targets: fixture.requests.map(request => request.conversation), picks: fixture.picks }, { targets: [conversation, other], picks: 2 }); + }); + + test('cancellation conflicts never release editable content; confirmed cancellation saves before deletion', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + const action = fixture.service.items.get()[0].actions.find(action => action.id === 'sessions.scheduled.edit')!; + fixture.conflict = true; + await assert.rejects(async () => action.run(), /changed or has started/); + const conflictCalls = [...fixture.calls]; + fixture.conflict = false; + await action.run(); + assert.deepStrictEqual({ conflictCalls, successCalls: fixture.calls.slice(conflictCalls.length) }, { conflictCalls: ['disable'], successCalls: ['disable', 'save', 'delete', 'open'] }); + assert.doesNotThrow(() => fixture.service.assertUnscheduled('composition', input)); + }); + + for (const savedDrafts of [true, false]) { + test(`opening a scheduled draft cancels and restores it with saved drafts ${savedDrafts ? 'enabled' : 'disabled'}`, async () => { + const fixture = create(true, savedDrafts); + await fixture.service.schedule(input, target, session, 'composition'); + const creationId = fixture.automations.get()[0].creationId; + await fixture.service.items.get()[0].open(); + assert.deepStrictEqual({ + calls: fixture.calls, remaining: fixture.service.items.get(), openedDrafts: fixture.openedDrafts, + }, { + calls: savedDrafts ? ['disable', 'save', 'delete', 'open'] : ['disable', 'recover', 'delete'], + remaining: [], openedDrafts: savedDrafts ? [[creationId, { removeFromDrafts: true }]] : [], + }); + }); + } + + test('with saved drafts disabled an occupied composer leaves cancelled content recoverable', async () => { + const fixture = create(true, false); + await fixture.service.schedule(input, target, session, 'composition'); + fixture.occupied = true; + await assert.rejects(async () => fixture.service.items.get()[0].open(), /Composer occupied/); + assert.deepStrictEqual({ + calls: fixture.calls, enabled: fixture.automations.get()[0].enabled, + retained: !!fixture.storage.get('sessions.scheduledChatHandoffs', StorageScope.PROFILE), + }, { calls: ['disable', 'recover'], enabled: false, retained: true }); + fixture.occupied = false; + await fixture.service.items.get()[0].open(); + assert.deepStrictEqual({ calls: fixture.calls, remaining: fixture.service.items.get() }, { + calls: ['disable', 'recover', 'recover', 'delete'], remaining: [], + }); + }); + + test('durable dispatch confirmation hides a consumed schedule even after run history eviction', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + fixture.automations.set([{ ...fixture.automations.get()[0], oneTimeRunId: 'opaque:run', oneTimeDispatchedAt: new Date().toISOString() }], undefined); + assert.deepStrictEqual(fixture.service.items.get(), []); + }); + + test('only a positively rejected dispatch allows consumed-request recovery', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + const claimed = { ...fixture.automations.get()[0], oneTimeRunId: 'run' }; + fixture.automations.set([claimed], undefined); + const uncertain = fixture.service.items.get()[0].actions.find(action => action.id === 'sessions.scheduled.edit')!.enabled; + fixture.automations.set([{ ...claimed, oneTimeDispatchRejectedAt: new Date().toISOString() }], undefined); + await fixture.service.items.get()[0].actions.find(action => action.id === 'sessions.scheduled.edit')!.run(); + assert.deepStrictEqual({ uncertain, calls: fixture.calls, claimed: [...fixture.service.claimedDraftIds.get()] }, { + uncertain: false, calls: ['save', 'delete', 'open'], claimed: [], + }); + }); + + test('unresolved conversations remain read-only, including stale action invocations', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + fixture.automations.set([{ ...fixture.automations.get()[0], readOnlyReason: 'Original conversation unavailable' }], undefined); + const item = fixture.service.items.get()[0]; + const edit = item.actions.find(action => action.id === 'sessions.scheduled.edit')!; + await assert.rejects(async () => edit.run(), /Original conversation unavailable/); + assert.deepStrictEqual({ enabled: item.actions.map(action => action.enabled), calls: fixture.calls }, { + enabled: [true, false, false, false, false], calls: [], + }); + }); + + test('retrying failed deletion does not overwrite recovered draft edits', async () => { + const fixture = create(); + await fixture.service.schedule(input, target, session, 'composition'); + fixture.failDelete = true; + await assert.rejects(async () => fixture.service.items.get()[0].actions.find(action => action.id === 'sessions.scheduled.edit')!.run(), /Deletion failed/); + fixture.failDelete = false; + await fixture.service.items.get()[0].actions.find(action => action.id === 'sessions.scheduled.edit')!.run(); + assert.deepStrictEqual(fixture.calls, ['disable', 'save', 'delete', 'delete', 'open']); + }); + + test('sidebar reconciliation keeps the original chat input guarded until it is released', async () => { + const fixture = create(); + const source = registerInput(fixture.service); + fixture.failCreate = true; + await assert.rejects(() => fixture.service.scheduleChatInput(source.widget), /Acknowledgement lost/); + fixture.failCreate = false; + await fixture.service.items.get()[0].open(); + assert.throws(() => fixture.service.assertChatInputUnscheduled(source.widget, source.text), /being scheduled/); + await fixture.service.scheduleChatInput(source.widget); + assert.deepStrictEqual({ input: source.text, requests: fixture.requests.length, picks: fixture.picks }, { + input: '', requests: 2, picks: 1, + }); + }); + + test('newly dispatched sessions inherit the captured group without later overriding user moves', async () => { + const fixture = create(); + await fixture.service.schedule(input, { ...target, groupId: 'chosen-group' }, session, 'composition'); + const resource = URI.parse('agent-host-copilot:/created'); + const created = upcastPartial<ISession>({ resource, sessionId: 'created' }); + fixture.runs.set([{ + id: 'run', automationId: fixture.automations.get()[0].id, status: 'running', trigger: 'schedule', + startedAt: new Date().toISOString(), sessionResource: resource, + }], undefined); + fixture.automations.set([{ ...fixture.automations.get()[0], oneTimeRunId: 'run', oneTimeDispatchedAt: new Date().toISOString() }], undefined); + fixture.sessions.set(resource.toString(), created); + fixture.sessionsChanged.fire({ added: [created], removed: [], changed: [] }); + const inherited = fixture.memberships.get('created'); + fixture.memberships.set('created', 'user-moved'); + fixture.runs.set([...fixture.runs.get()], undefined); + assert.deepStrictEqual({ inherited, current: fixture.memberships.get('created'), calls: fixture.calls }, { + inherited: 'chosen-group', current: 'user-moved', calls: ['group'], + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionActionViewItem.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionActionViewItem.test.ts index 9133c76ae3e7..0cf689c39a0d 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionActionViewItem.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionActionViewItem.test.ts @@ -46,7 +46,7 @@ suite('SessionActionViewItem', () => { ); } - function createArchiveActionViewItem(run: () => Promise<void>, options: IMenuEntryActionViewItemOptions = { onClickAnimation: ClickAnimation.Confetti }): MenuEntryActionViewItem { + function createArchiveActionViewItem(run: () => Promise<void>, options: IMenuEntryActionViewItemOptions = { onClickAnimation: ClickAnimation.Confetti }, viewItemType: 'base' | 'session' = 'base'): MenuEntryActionViewItem { const action = new MenuItemAction( { id: ARCHIVE_SESSION_COMMAND_ID, title: ARCHIVE_SESSION_COMMAND_ID }, undefined, @@ -63,18 +63,17 @@ suite('SessionActionViewItem', () => { } }(), ); - const viewItem = disposables.add(new MenuEntryActionViewItem( - action, - options, - new class extends mock<IKeybindingService>() { }(), - new TestNotificationService(), - new class extends mock<IContextKeyService>() { }(), - new TestThemeService(), - new class extends mock<IContextMenuService>() { }(), - new class extends TestAccessibilityService { - override isMotionReduced(): boolean { return false; } - }(), - )); + const keybindingService = new class extends mock<IKeybindingService>() { }(); + const notificationService = new TestNotificationService(); + const contextKeyService = new class extends mock<IContextKeyService>() { }(); + const themeService = new TestThemeService(); + const contextMenuService = new class extends mock<IContextMenuService>() { }(); + const accessibilityService = new class extends TestAccessibilityService { + override isMotionReduced(): boolean { return false; } + }(); + const viewItem = disposables.add(viewItemType === 'session' + ? new SessionArchiveActionViewItem(action, options, new TestExperimentTriggerTelemetryService(), keybindingService, notificationService, contextKeyService, themeService, contextMenuService, accessibilityService) + : new MenuEntryActionViewItem(action, options, keybindingService, notificationService, contextKeyService, themeService, contextMenuService, accessibilityService)); viewItem.actionRunner = disposables.add(new ActionRunner()); viewItem.element = dom.$('button'); return viewItem; @@ -157,7 +156,7 @@ suite('SessionActionViewItem', () => { }); }); - test('animates archive actions only after successful completion', async () => { + test('keeps post-action animations limited to successful completion', async () => { const success = new DeferredPromise<void>(); const successfulViewItem = createArchiveActionViewItem(() => success.p); const successfulClick = successfulViewItem.onClick(new MouseEvent('click')); @@ -184,6 +183,26 @@ suite('SessionActionViewItem', () => { }); }); + test('starts archive animation before action completion', async () => { + const completion = new DeferredPromise<void>(); + const configurationService = new TestConfigurationService({ [SESSIONS_MARK_AS_DONE_CONFETTI_SETTING]: true }); + const viewItem = createArchiveActionViewItem(() => completion.p, getSessionArchiveActionViewItemOptions({}, configurationService), 'session'); + const click = viewItem.onClick(new MouseEvent('click')); + const animationBeforeCompletion = document.body.querySelector('.animation-overlay'); + await completion.error(new Error('Archive failed')); + await click; + const animationsAfterFailure = document.body.querySelectorAll('.animation-overlay'); + animationBeforeCompletion?.remove(); + + assert.deepStrictEqual({ + animationBeforeCompletion: !!animationBeforeCompletion, + animationCountAfterFailure: animationsAfterFailure.length, + }, { + animationBeforeCompletion: true, + animationCountAfterFailure: 1, + }); + }); + for (const confirmed of [false, true]) { test(`checks animation eligibility against the original context after disposal (${confirmed})`, async () => { const context = { confirmed }; @@ -205,16 +224,17 @@ suite('SessionActionViewItem', () => { }); } - test('keeps confetti at the original button position when archiving disposes the view item', async () => { + test('starts confetti at the button position before archiving disposes the view item', async () => { const workbench = dom.append(document.body, dom.$('.monaco-workbench')); disposables.add(toDisposable(() => workbench.remove())); const row = dom.append(workbench, dom.$('div')); const completion = new DeferredPromise<void>(); + const configurationService = new TestConfigurationService({ [SESSIONS_MARK_AS_DONE_CONFETTI_SETTING]: true }); const viewItem = createArchiveActionViewItem(() => { viewItem.dispose(); row.remove(); return completion.p; - }); + }, getSessionArchiveActionViewItemOptions({}, configurationService), 'session'); const button = viewItem.element!; button.style.cssText = 'position: fixed; left: 120px; top: 80px; width: 48px; height: 24px; box-sizing: border-box;'; row.appendChild(button); @@ -235,7 +255,7 @@ suite('SessionActionViewItem', () => { particleOrigin: particle && [particle.style.left, particle.style.top], inheritsWorkbenchTheme: overlay?.parentElement === workbench, }, { - animationBeforeCompletion: null, + animationBeforeCompletion: overlay, element: undefined, buttonConnected: false, bounds: ['120px', '80px', '48px', '24px'], diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionAttentionService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionAttentionService.test.ts new file mode 100644 index 000000000000..de070c02e508 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionAttentionService.test.ts @@ -0,0 +1,812 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { hash } from '../../../../../base/common/hash.js'; +import { IDisposable, IReference, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, ISettableObservable, observableValue, transaction } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { InMemoryStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; +import { IChatModelReference, IChatPlanReview, IChatService, IChatToolInvocation } from '../../../chat/common/chatService/chatService.js'; +import { IChatSessionsService } from '../../../chat/common/chatSessionsService.js'; +import { ChatAgentLocation } from '../../../chat/common/constants.js'; +import { ChatResponseModelChangeReason, IChatChangeEvent, IChatModel, IChatRequestModel, IChatResponseModel } from '../../../chat/common/model/chatModel.js'; +import { SessionsListModelService } from '../../browser/sessionsListModelService.js'; +import { GitHubPullRequestCIModel } from '../../browser/github/models/githubPullRequestCIModel.js'; +import { GitHubPullRequestModel } from '../../browser/github/models/githubPullRequestModel.js'; +import { GitHubPullRequestReviewThreadsModel } from '../../browser/github/models/githubPullRequestReviewThreadsModel.js'; +import { IGitHubService } from '../../browser/github/githubService.js'; +import { GitHubCIOverallStatus, GitHubPullRequestState, IGitHubPullRequest, IGitHubPullRequestReviewThread } from '../../common/github/types.js'; +import { InboxNotificationPriority, InboxTab } from '../../common/sessionAttentionService.js'; +import { getSessionInboxActivity, isSessionInboxStateCurrent, SessionInboxState } from '../../common/sessionInbox.js'; +import { ISessionsChangeEvent, ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { IChatEntitlementService, IChatSentiment } from '../../../../services/chat/common/chatEntitlementService.js'; +import { IChat, IGitHubInfo, ISession, ISessionArtifact, ISessionWorkspace, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { SessionAttentionService } from '../../browser/sessionAttentionService.js'; + +suite('SessionAttentionService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const attentionStartTimeStorageKey = 'sessions.inboxNotifications.attentionStartTime'; + + function createSession(id: string, status = SessionStatus.Completed, updatedAt = 100, pullRequests: readonly { number: number; owned?: boolean; state?: GitHubPullRequestState }[] = []): ISession { + const chat = upcastPartial<IChat>({ resource: URI.parse(`test:///chat/${id}`), status: observableValue('chat.status', status) }); + const gitHubInfo: IGitHubInfo = { + owner: 'owner', repo: 'repo', + pullRequests: pullRequests.map(ref => ({ + owner: 'owner', repo: 'repo', number: ref.number, state: ref.state ?? GitHubPullRequestState.Open, + uri: URI.parse(`https://github.com/owner/repo/pull/${ref.number}`), + createdByThisSession: ref.owned ?? true, + })), + }; + return upcastPartial<ISession>({ + sessionId: id, + resource: URI.parse(`test:///session/${id}`), + status: observableValue('session.status', status), + loading: observableValue('session.loading', false), + updatedAt: observableValue('session.updatedAt', new Date(updatedAt)), + lastTurnEnd: observableValue('session.lastTurnEnd', new Date(updatedAt)), + isArchived: observableValue('session.archived', false), + isRead: observableValue('session.read', false), + chats: observableValue('session.chats', [chat]), + artifacts: observableValue<readonly ISessionArtifact[]>('session.artifacts', []), + workspace: observableValue<ISessionWorkspace | undefined>('session.workspace', pullRequests.length ? { + uri: URI.parse(`test:///workspace/${id}`), label: id, icon: Codicon.folder, + folders: [{ + root: URI.parse(`test:///workspace/${id}`), workingDirectory: URI.parse(`test:///workspace/${id}`), name: id, description: undefined, + gitRepository: { + uri: URI.parse(`test:///workspace/${id}`), workTreeUri: undefined, baseBranchName: undefined, + gitHubInfo: observableValue('gitHubInfo', gitHubInfo), + }, + }], + requiresWorkspaceTrust: false, isVirtualWorkspace: false, + } : undefined), + }); + } + + function createFixture(initialSessions: readonly ISession[], storage = store.add(new InMemoryStorageService())) { + const sessionsChanged = store.add(new Emitter<ISessionsChangeEvent>()); + const contentProvidersChanged = store.add(new Emitter<{ added: string[]; removed: string[] }>()); + let sessions = initialSessions; + const chat = new TestChatService(); + const github = new TestGitHubService(); + const sentiment = observableValue<IChatSentiment>('sentiment', {}); + const sessionsManagement = upcastPartial<ISessionsManagementService>({ + onDidChangeSessions: sessionsChanged.event, onDidDeleteSession: Event.None, onDidReplaceSession: Event.None, getSessions: () => [...sessions], + }); + const service = store.add(new SessionAttentionService( + sessionsManagement, + upcastPartial<IChatService>(chat), + upcastPartial<IGitHubService>(github), + storage, + upcastPartial<IChatEntitlementService>({ sentimentObs: sentiment }), + upcastPartial<IChatSessionsService>({ onDidChangeContentProviderSchemes: contentProvidersChanged.event }), + )); + return { + service, chat, github, sentiment, storage, contentProvidersChanged, + createListModel() { + return store.add(new SessionsListModelService(storage, sessionsManagement, new TestConfigurationService(), service)); + }, + setSessions(value: readonly ISession[]) { + sessions = value; + sessionsChanged.fire({ added: [], removed: [], changed: [...sessions] }); + }, + observe() { + return store.add(autorun(reader => service.sessionAttention.read(reader))); + }, + }; + } + + test('history cutoff starts on first visible demand and survives late history, metadata changes, new turns and restart', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const old = createSession('old', SessionStatus.Completed, Date.now() - 1); + const fixture = createFixture([]); + fixture.sentiment.set({ hidden: true }, undefined); + const lease = store.add(fixture.service.acquireSessionAttention()); + const whileHidden = fixture.storage.getNumber(attentionStartTimeStorageKey, StorageScope.PROFILE); + fixture.sentiment.set({}, undefined); + const start = fixture.storage.getNumber(attentionStartTimeStorageKey, StorageScope.PROFILE)!; + const boundary = createSession('boundary', SessionStatus.Completed, start); + const late = createSession('late', SessionStatus.Completed, start - 2); + const pending = createSession('pending', SessionStatus.NeedsInput, start - 2); + fixture.setSessions([old, boundary, late, pending]); + const historical = (service: SessionAttentionService) => [...service.sessionAttention.get()].filter(([, value]) => value.isHistoricalCompletion).map(([id]) => id); + const initial = historical(fixture.service); + (old.updatedAt as ISettableObservable<Date>).set(new Date(start + 1), undefined); + (old.isRead as ISettableObservable<boolean>).set(true, undefined); + const metadata = historical(fixture.service); + transaction(tx => { + (old.status as ISettableObservable<SessionStatus>).set(SessionStatus.InProgress, tx); + (old.lastTurnEnd as ISettableObservable<Date | undefined>).set(undefined, tx); + }); + const working = historical(fixture.service); + transaction(tx => { + (old.status as ISettableObservable<SessionStatus>).set(SessionStatus.Completed, tx); + (old.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(start + 1), tx); + }); + lease.dispose(); + fixture.service.dispose(); + await timeout(1000); + const restored = createFixture([old, boundary, late, pending, createSession('offline', SessionStatus.Completed, start + 500)], fixture.storage); + store.add(restored.service.acquireSessionAttention()); + assert.deepStrictEqual({ + whileHidden, initial, metadata, working, restored: historical(restored.service), + cutoff: restored.storage.getNumber(attentionStartTimeStorageKey, StorageScope.PROFILE), + canvasCutoff: restored.storage.getNumber('sessions.inboxNotifications.completionStartTime', StorageScope.APPLICATION), + }, { whileHidden: undefined, initial: ['old', 'late'], metadata: ['old', 'late'], working: ['late'], restored: ['late'], cutoff: start, canvasCutoff: undefined }); + })); + + test('reading Inbox completions does not dismiss them across restart', () => runWithFakedTimers({ startTime: new Date(2026, 10, 11, 12).getTime() }, async () => { + const fixture = createFixture([]); + store.add(fixture.service.acquireSessionAttention()); + const start = Date.now(); + await timeout(1000); + const read = createSession('read', SessionStatus.Completed, Date.now()); + const unread = createSession('unread', SessionStatus.Completed, Date.now()); + const actionable = createSession('actionable', SessionStatus.Completed, Date.now(), [{ number: 42 }]); + (read.isRead as ISettableObservable<boolean>).set(true, undefined); + (actionable.isRead as ISettableObservable<boolean>).set(true, undefined); + fixture.setSessions([read, unread, actionable]); + const model = fixture.createListModel(); + const initial = [read, unread, actionable].map(session => model.getInboxState(session)?.kind); + fixture.service.dispose(); + await timeout(1000); + const restored = createFixture([read, unread, actionable], fixture.storage); + restored.github.setPullRequest(42, openPullRequest(42)); + restored.github.setCIStatus(42, GitHubCIOverallStatus.Failure); + store.add(restored.service.acquireSessionAttention()); + await timeout(0); + const restoredModel = restored.createListModel(); + const afterRestart = [read, unread, actionable].map(session => restoredModel.getInboxState(session)?.kind); + await timeout(1000); + (read.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(Date.now()), undefined); + assert.deepStrictEqual({ + initial, afterRestart, newCompletion: restoredModel.getInboxState(read)?.kind, + cutoff: restored.storage.getNumber(attentionStartTimeStorageKey, StorageScope.PROFILE), + }, { + initial: [undefined, undefined, undefined], afterRestart: [undefined, undefined, undefined], + newCompletion: undefined, cutoff: start, + }); + })); + + test('non-PR completions keep notification identities empty across metadata, model residency and new turns', () => { + const session = createSession('complete'); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + const state = () => fixture.service.sessionAttention.get().get('complete'); + const initial = state(); + (session.updatedAt as ISettableObservable<Date>).set(new Date(200), undefined); + (session.isRead as ISettableObservable<boolean>).set(true, undefined); + fixture.chat.setRequests(session.chats.get()[0].resource, []); + const resident = state(); + fixture.chat.removeSession(session.chats.get()[0].resource); + const unloaded = state(); + (session.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(300), undefined); + assert.deepStrictEqual({ initial, resident, unloaded, next: state()?.notificationIds, loaded: fixture.chat.acquired }, { + initial: { tab: InboxTab.ReadyForYou, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: true }, + resident: initial, unloaded: initial, next: [], loaded: [], + }); + }); + + test('reading sessions returned by activity still requires dismissal after restart', () => runWithFakedTimers({ startTime: new Date(2026, 10, 11, 12).getTime() }, async () => { + const fixture = createFixture([]); + store.add(fixture.service.acquireSessionAttention()); + await timeout(1000); + const sessions = ['read', 'unread', 'explicit', 'snoozed'].map(id => createSession(id, SessionStatus.Completed, Date.now())); + fixture.setSessions(sessions); + const model = fixture.createListModel(); + model.setInboxState(sessions, 'done'); + await timeout(1000); + for (const session of sessions) { + (session.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(Date.now()), undefined); + } + for (const session of [sessions[0], sessions[2], sessions[3]]) { + (session.isRead as ISettableObservable<boolean>).set(true, undefined); + } + model.setInboxState([sessions[2]], undefined); + model.setInboxState([sessions[3]], Date.now() + 100); + await timeout(101); + const before = sessions.map(session => model.getInboxState(session)?.kind); + model.dispose(); + fixture.service.dispose(); + await timeout(1000); + const restored = createFixture(sessions, fixture.storage); + store.add(restored.service.acquireSessionAttention()); + const restoredModel = restored.createListModel(); + const after = sessions.map(session => restoredModel.getInboxState(session)?.kind); + restoredModel.setInboxState([sessions[0]], 'done'); + restoredModel.dispose(); + const reloadedModel = restored.createListModel(); + const dismissed = reloadedModel.getInboxState(sessions[0])?.kind; + await timeout(1000); + (sessions[0].lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(Date.now()), undefined); + assert.deepStrictEqual({ before, after, dismissed, newCompletion: reloadedModel.getInboxState(sessions[0])?.kind }, { + before: [undefined, undefined, undefined, undefined], + after: [undefined, undefined, undefined, undefined], + dismissed: 'done', + newCompletion: undefined, + }); + })); + + test('existing completed-session triage stays current until provider activity changes', () => { + const session = createSession('complete'); + const fixture = createFixture([session]); + const activity = getSessionInboxActivity(session); + const decisions: SessionInboxState[] = [ + { kind: 'done', activity, notificationIds: [] }, + { kind: 'untilActivity', activity, notificationIds: [] }, + { kind: 'done', activity, notificationIds: ['complete:completed:100'] }, + ]; + store.add(fixture.service.acquireSessionAttention()); + const current = () => decisions.map(decision => isSessionInboxStateCurrent( + decision, session, Date.now(), undefined, fixture.service.sessionAttention.get().get(session.sessionId), + )); + const baseline = current(); + (session.isRead as ISettableObservable<boolean>).set(true, undefined); + fixture.chat.setRequests(session.chats.get()[0].resource, []); + const resident = current(); + fixture.chat.removeSession(session.chats.get()[0].resource); + const unloaded = current(); + (session.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(300), undefined); + assert.deepStrictEqual({ baseline, resident, unloaded, nextTurn: current(), nextIds: fixture.service.sessionAttention.get().get(session.sessionId)!.notificationIds }, { + baseline: [true, true, true], resident: [true, true, true], unloaded: [true, true, true], + nextTurn: [false, false, false], nextIds: [], + }); + }); + + test('attention demand is ref-counted and releases polling while hidden or without demand', async () => { + const fixture = createFixture([ + createSession('input', SessionStatus.NeedsInput), + createSession('working', SessionStatus.InProgress), + createSession('old'), + createSession('pr', SessionStatus.Completed, 100, [{ number: 42 }]), + ]); + fixture.github.setPullRequest(42, openPullRequest(42)); + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Success); + const polling = [fixture.github.pollingCount]; + const first = store.add(fixture.service.acquireSessionAttention()); + const second = store.add(fixture.service.acquireSessionAttention()); + await timeout(0); + const attention = [...fixture.service.sessionAttention.get()].map(([id, value]) => [id, value.tab, value.priority, value.isHistoricalCompletion]); + polling.push(fixture.github.pollingCount); + first.dispose(); + polling.push(fixture.github.pollingCount); + fixture.sentiment.set({ hidden: true }, undefined); + const hidden = fixture.service.sessionAttention.get().size; + polling.push(fixture.github.pollingCount); + fixture.sentiment.set({}, undefined); + polling.push(fixture.github.pollingCount); + second.dispose(); + polling.push(fixture.github.pollingCount); + assert.deepStrictEqual({ attention, polling, hidden, released: fixture.service.sessionAttention.get().size }, { + attention: [ + ['input', InboxTab.ReadyForYou, InboxNotificationPriority.Now, false], + ['working', InboxTab.Working, InboxNotificationPriority.Later, false], + ['old', InboxTab.ReadyForYou, InboxNotificationPriority.Later, true], + ['pr', InboxTab.ReadyToMerge, InboxNotificationPriority.Next, false], + ], + polling: [0, 3, 3, 0, 3, 0], hidden: 0, released: 0, + }); + }); + + for (const stop of ['release', 'hidden', 'removed', 'disposed'] as const) { + test(`disposes an in-flight input model arriving after demand is ${stop}`, async () => { + const fixture = createFixture([createSession('input', SessionStatus.NeedsInput)]); + const pending = new DeferredPromise<IChatModelReference>(); + let token: CancellationToken | undefined; + fixture.chat.acquire = async (_resource, value) => { token = value; return pending.p; }; + const lease = store.add(fixture.service.acquireSessionAttention()); + let disposed = false; + if (stop === 'release') { + lease.dispose(); + } else if (stop === 'hidden') { + fixture.sentiment.set({ hidden: true }, undefined); + } else if (stop === 'removed') { + fixture.setSessions([]); + } else { + fixture.service.dispose(); + } + const cancelled = token?.isCancellationRequested; + await pending.complete({ object: upcastPartial<IChatModel>({}), dispose: () => { disposed = true; } }); + await timeout(0); + assert.deepStrictEqual({ cancelled, disposed }, { cancelled: true, disposed: true }); + }); + } + + test('releases retained input references when hiding AI and reacquires on renewed demand', async () => { + const fixture = createFixture([createSession('input', SessionStatus.NeedsInput)]); + let references = 0; + fixture.chat.acquire = async () => { + references++; + return { object: upcastPartial<IChatModel>({}), dispose: () => { references--; } }; + }; + const lease = store.add(fixture.service.acquireSessionAttention()); + await timeout(0); + const loaded = references; + fixture.sentiment.set({ hidden: true }, undefined); + const hidden = references; + fixture.sentiment.set({}, undefined); + await timeout(0); + const restored = references; + lease.dispose(); + assert.deepStrictEqual({ loaded, hidden, restored, released: references }, { loaded: 1, hidden: 0, restored: 1, released: 0 }); + }); + + test('provider removal cancels acquisition and retries only after registration and old acquisition settle', async () => { + const fixture = createFixture([createSession('input', SessionStatus.NeedsInput)]); + const pending = new DeferredPromise<IChatModelReference>(); + let disposed = 0; + let loads = 0; + fixture.chat.acquire = async () => { + loads++; + return loads === 1 ? pending.p : { object: upcastPartial<IChatModel>({}), dispose: () => { disposed++; } }; + }; + store.add(fixture.service.acquireSessionAttention()); + fixture.contentProvidersChanged.fire({ added: [], removed: ['test'] }); + fixture.contentProvidersChanged.fire({ added: ['test'], removed: [] }); + const beforeSettlement = loads; + await pending.complete({ object: upcastPartial<IChatModel>({}), dispose: () => { disposed++; } }); + await timeout(0); + fixture.contentProvidersChanged.fire({ added: [], removed: ['test'] }); + assert.deepStrictEqual({ beforeSettlement, loads, disposed }, { beforeSettlement: 1, loads: 2, disposed: 2 }); + }); + + test('pending identities refine during hydration and structural streaming without a catalog update', () => { + const session = createSession('input', SessionStatus.NeedsInput); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + fixture.observe(); + const ids = () => fixture.service.sessionAttention.get().get('input')!.notificationIds; + const fallback = ids(); + const changed = store.add(new Emitter<IChatChangeEvent>()); + let requests: IChatRequestModel[] = []; + fixture.chat.setModel(session.chats.get()[0].resource, upcastPartial<IChatModel>({ + onDidChange: changed.event, getRequests: () => requests, + })); + requests = [pendingRequest('r', [question('one')])]; + changed.fire({ kind: 'addRequest', request: requests[0] }); + const hydrated = ids(); + requests = [pendingRequest('r', [question('two')])]; + changed.fire({ kind: 'changedRequest', request: requests[0] }); + assert.deepStrictEqual({ fallback, hydrated, next: ids() }, { + fallback: ['input:needsInput:100'], hydrated: ['input:needsInput:qc:r:one'], next: ['input:needsInput:qc:r:two'], + }); + }); + + for (const action of ['done', 'untilActivity'] as const) { + for (const initiallyHydrated of [false, true]) { + test(`persisted ${action} survives delayed input hydration after triaging ${initiallyHydrated ? 'hydrated' : 'provisional'} input`, async () => { + const session = createSession('input', SessionStatus.NeedsInput); + const resource = session.chats.get()[0].resource; + const original = createFixture([session]); + if (initiallyHydrated) { + original.chat.setRequests(resource, [pendingRequest('r', [question('one')])]); + } + store.add(original.service.acquireSessionAttention()); + const list = original.createListModel(); + list.setInboxState([session], action); + list.dispose(); + original.service.dispose(); + + const restored = createFixture([session], original.storage); + const pending = new DeferredPromise<IChatModelReference>(); + restored.chat.acquire = async () => pending.p; + const restoredList = restored.createListModel(); + store.add(restored.service.acquireSessionAttention()); + const provisional = restoredList.getInboxState(session)?.kind; + restored.chat.setRequests(resource, [pendingRequest('r', [question('one')])]); + await pending.complete({ object: restored.chat.getSession(resource)!, dispose: () => { } }); + await timeout(0); + const hydrated = restoredList.getInboxState(session)?.kind; + restoredList.dispose(); + const reloadedList = restored.createListModel(); + const reloaded = reloadedList.getInboxState(session)?.kind; + restored.chat.setRequests(resource, [pendingRequest('r', [question('two')])]); + assert.deepStrictEqual({ provisional, hydrated, reloaded, newInput: reloadedList.getInboxState(session)?.kind }, { + provisional: action, hydrated: action, reloaded: action, newInput: undefined, + }); + }); + } + + for (const kind of ['question', 'plan'] as const) { + test(`${action} expires on a response-only ${kind} change and releases response listeners`, () => { + const session = createSession('input', SessionStatus.NeedsInput); + const fixture = createFixture([session]); + const changed = store.add(new Emitter<ChatResponseModelChangeReason>()); + const part = (id: string) => kind === 'question' ? question(id) + : upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false, resolveId: id }); + const parts = [part('one')]; + const request = pendingRequest('r', parts, 10, changed.event); + fixture.chat.setRequests(session.chats.get()[0].resource, [request]); + const lease = store.add(fixture.service.acquireSessionAttention()); + const list = fixture.createListModel(); + list.setInboxState([session], action); + const before = list.getInboxState(session)?.kind; + const listening = changed.hasListeners(); + parts.splice(0, 1, part('two')); + changed.fire({ reason: 'other' }); + const after = list.getInboxState(session)?.kind; + const next = fixture.service.sessionAttention.get().get(session.sessionId)!.notificationIds; + lease.dispose(); + assert.deepStrictEqual({ before, listening, after, next, released: !changed.hasListeners() }, { + before: action, listening: true, after: undefined, + next: [`input:needsInput:${kind === 'question' ? 'qc' : 'pr'}:r:two`], released: true, + }); + }); + } + } + + test('triage before hydration remains undoable after its identity is refined', () => { + const session = createSession('input', SessionStatus.NeedsInput); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + const list = fixture.createListModel(); + const undo = list.setInboxState([session], 'done'); + fixture.chat.setRequests(session.chats.get()[0].resource, [pendingRequest('r', [question('one')])]); + const hydrated = list.getInboxState(session)?.kind; + undo(); + assert.deepStrictEqual({ hydrated, undone: list.getInboxState(session)?.kind }, { hydrated: 'done', undone: undefined }); + }); + + test('input identities distinguish approvals, confirmation precedence, successive plans and question fallback keys', () => { + const session = createSession('input', SessionStatus.NeedsInput); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + const resource = session.chats.get()[0].resource; + const identity = (parts: IChatResponseModel['response']['value']) => { + fixture.chat.setRequests(resource, [pendingRequest('r', parts)]); + return fixture.service.sessionAttention.get().get('input')!.notificationIds[0]; + }; + const approval = observableValue<IChatToolInvocation.State>('approval', upcastPartial<IChatToolInvocation.State>({ type: IChatToolInvocation.StateKind.WaitingForConfirmation })); + const tool = upcastPartial<IChatToolInvocation>({ kind: 'toolInvocation', toolCallId: 'tool', state: approval }); + const execution = identity([tool]); + approval.set(upcastPartial<IChatToolInvocation.State>({ type: IChatToolInvocation.StateKind.WaitingForPostApproval }), undefined); + const result = identity([tool]); + const confirmation = identity([question('q'), { kind: 'confirmation', title: ' Confirm action ', message: '', data: {} }]); + const firstPlan = identity([upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false })]); + const nextPlan = identity([{ kind: 'markdownContent', content: { value: '' } }, upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false })]); + const resolvedPlan = identity([upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false, resolveId: 'plan' })]); + const fallbackQuestion = identity([{ ...question(''), resolveId: undefined }]); + assert.deepStrictEqual({ execution, result, confirmation, firstPlan, nextPlan, resolvedPlan, fallbackQuestion }, { + execution: 'input:needsInput:tc:r:tool:execution', result: 'input:needsInput:tc:r:tool:result', + confirmation: `input:needsInput:cf:r:${hash('Confirm action')}`, + firstPlan: 'input:needsInput:pr:r:0', nextPlan: 'input:needsInput:pr:r:1', resolvedPlan: 'input:needsInput:pr:r:plan', + fallbackQuestion: `input:needsInput:qc:r:${hash('q')}`, + }); + }); + + test('scans waiting chats first, chooses the oldest pending request and ignores answered or hidden responses', () => { + const session = createSession('input', SessionStatus.NeedsInput); + const fixture = createFixture([session]); + const first = session.chats.get()[0]; + const second = upcastPartial<IChat>({ resource: URI.parse('test:///chat/second'), status: observableValue('second.status', SessionStatus.NeedsInput) }); + (session.chats as ISettableObservable<readonly IChat[]>).set([first, second], undefined); + fixture.chat.setRequests(first.resource, [pendingRequest('new', [question('new')], 20)]); + fixture.chat.setRequests(second.resource, [pendingRequest('old', [question('old')], 10)]); + store.add(fixture.service.acquireSessionAttention()); + const ids = () => fixture.service.sessionAttention.get().get('input')!.notificationIds; + const oldest = ids(); + (second.status as ISettableObservable<SessionStatus>).set(SessionStatus.Completed, undefined); + const waitingOnly = ids(); + const hidden = pendingRequest('hidden', [question('hidden')]); + fixture.chat.setRequests(first.resource, [ + upcastPartial<IChatRequestModel>({ ...hidden, isHiddenFromTranscript: true }), + pendingRequest('used', [{ ...question('used'), isUsed: true }]), + pendingRequest('empty', [{ ...question('empty'), questions: [] }]), + upcastPartial<IChatRequestModel>({ ...pendingRequest('cancelled', [question('cancelled')]), response: upcastPartial<IChatResponseModel>({ ...hidden.response, isCanceled: true }) }), + upcastPartial<IChatRequestModel>({ ...pendingRequest('complete-plan', [upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false })]), response: upcastPartial<IChatResponseModel>({ ...pendingRequest('complete-plan', [upcastPartial<IChatPlanReview>({ kind: 'planReview', isUsed: false })]).response, isComplete: true }) }), + ]); + assert.deepStrictEqual({ oldest, waitingOnly, ignored: ids(), acquired: fixture.chat.acquired }, { + oldest: ['input:needsInput:qc:old:old'], waitingOnly: ['input:needsInput:qc:new:new'], ignored: ['input:needsInput:100'], acquired: [], + }); + }); + + test('PR attention tracks CI, drafts, Copilot review identities, merging and new completions', () => { + const session = createSession('pr', SessionStatus.Completed, 100, [{ number: 42 }]); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + fixture.github.setPullRequest(42, openPullRequest(42)); + const state = () => { + const attention = fixture.service.sessionAttention.get().get('pr')!; + return [attention.tab, attention.priority, attention.isHistoricalCompletion, attention.notificationIds]; + }; + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Failure); + const failing = state(); + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Success); + const passing = state(); + const threads = [reviewThread('copilot[bot]')]; + fixture.github.setReviewThreads(42, threads); + const review = state(); + (session.updatedAt as ISettableObservable<Date>).set(new Date(200), undefined); + const metadata = state(); + fixture.github.setReviewThreads(42, [reviewThread('human')]); + const resolved = state(); + fixture.github.setPullRequest(42, { ...openPullRequest(42), isDraft: true }); + const draft = state(); + fixture.github.setPullRequest(42, { ...openPullRequest(42), state: GitHubPullRequestState.Merged, mergedAt: '2026-09-21T16:00:00Z' }); + const merged = state(); + (session.lastTurnEnd as ISettableObservable<Date | undefined>).set(new Date(Date.now() + 1), undefined); + const reviewId = `pr:reviewComments:owner/repo#42:${hash(threads.map(thread => [thread.id, ...thread.comments.map(comment => [comment.id, comment.updatedAt ?? comment.createdAt])]))}`; + assert.deepStrictEqual({ failing, passing, review, metadata, resolved, draft, merged, newCompletion: state() }, { + failing: [InboxTab.ReadyForYou, InboxNotificationPriority.Now, false, ['pr:failingCi:owner/repo#42:sha42']], + passing: [InboxTab.ReadyToMerge, InboxNotificationPriority.Next, false, ['pr:passingCi:owner/repo#42:sha42']], + review: [InboxTab.ReadyForYou, InboxNotificationPriority.Now, false, ['pr:passingCi:owner/repo#42:sha42', reviewId]], + metadata: review, + resolved: [InboxTab.ReadyToMerge, InboxNotificationPriority.Next, false, ['pr:passingCi:owner/repo#42:sha42']], + draft: [InboxTab.ReadyForYou, InboxNotificationPriority.Later, true, []], + merged: [InboxTab.ReadyForYou, InboxNotificationPriority.Next, true, ['pr:pullRequestMerged:owner/repo#42:2026-09-21T16:00:00Z']], + newCompletion: [InboxTab.ReadyForYou, InboxNotificationPriority.Next, false, ['pr:pullRequestMerged:owner/repo#42:2026-09-21T16:00:00Z']], + }); + }); + + test('new PR merges return historical completions to Inbox without overriding holds or timed snoozes', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const start = Date.now(); + const sessions = ['historical', 'cleared', 'untilActivity', 'held', 'snoozed'].map((id, index) => + createSession(id, SessionStatus.Completed, start - 1000, [{ number: index + 1 }])); + for (const session of sessions) { + (session.isRead as ISettableObservable<boolean>).set(true, undefined); + } + const fixture = createFixture(sessions); + for (const [index] of sessions.entries()) { + fixture.github.setPullRequest(index + 1, { + ...openPullRequest(index + 1), state: GitHubPullRequestState.Merged, mergedAt: new Date(start - 1).toISOString(), + }); + } + store.add(fixture.service.acquireSessionAttention()); + const list = fixture.createListModel(); + const states = () => sessions.map(session => list.getInboxState(session)?.kind); + const historical = states(); + list.setInboxState([sessions[1]], 'done'); + list.setInboxState([sessions[2]], 'untilActivity'); + list.setInboxState([sessions[3]], 'hold'); + list.setInboxState([sessions[4]], start + 60_000); + for (const [index] of sessions.entries()) { + fixture.github.setPullRequest(index + 1, openPullRequest(index + 1)); + } + const beforeMerge = states(); + for (const [index] of sessions.entries()) { + fixture.github.setPullRequest(index + 1, { + ...openPullRequest(index + 1), state: GitHubPullRequestState.Merged, mergedAt: new Date(start).toISOString(), + }); + } + const merged = states(); + list.setInboxState([sessions[0]], 'done'); + const acknowledged = states(); + list.dispose(); + const restored = fixture.createListModel(); + assert.deepStrictEqual({ + historical, beforeMerge, merged, acknowledged, + restored: sessions.map(session => restored.getInboxState(session)?.kind), + }, { + historical: ['done', 'done', 'done', 'done', 'done'], + beforeMerge: ['done', 'done', 'untilActivity', 'hold', 'snoozed'], + merged: [undefined, undefined, undefined, 'hold', 'snoozed'], + acknowledged: ['done', undefined, undefined, 'hold', 'snoozed'], + restored: ['done', undefined, undefined, 'hold', 'snoozed'], + }); + })); + + for (const mergedAt of [undefined, 'invalid']) { + test(`historical merges with ${mergedAt === undefined ? 'missing' : 'invalid'} merge times wait for authoritative metadata`, () => runWithFakedTimers({}, async () => { + const start = Date.now(); + const session = createSession('pr', SessionStatus.Completed, start - 1000, [ + { number: 41, state: GitHubPullRequestState.Merged }, + { number: 42, state: GitHubPullRequestState.Merged }, + ]); + (session.isRead as ISettableObservable<boolean>).set(true, undefined); + (session.updatedAt as ISettableObservable<Date>).set(new Date(start + 1000), undefined); + const fixture = createFixture([session]); + store.add(fixture.service.acquireSessionAttention()); + const list = fixture.createListModel(); + const states = [list.getInboxState(session)?.kind]; + fixture.github.setPullRequest(41, { + ...openPullRequest(41), state: GitHubPullRequestState.Merged, mergedAt: new Date(start - 1).toISOString(), + }); + states.push(list.getInboxState(session)?.kind); + const partial = { + ...openPullRequest(42), state: GitHubPullRequestState.Merged, mergedAt, updatedAt: new Date(start + 1000).toISOString(), + }; + fixture.github.setPullRequest(42, partial); + states.push(list.getInboxState(session)?.kind); + fixture.github.setPullRequest(42, { ...partial, updatedAt: new Date(start + 2000).toISOString() }); + states.push(list.getInboxState(session)?.kind); + fixture.github.setPullRequest(42, { ...partial, mergedAt: new Date(start).toISOString() }); + states.push(list.getInboxState(session)?.kind); + assert.deepStrictEqual(states, ['done', 'done', 'done', 'done', undefined]); + })); + } + + test('prospective restoration uses batch PR ownership without changing archive state or polling', () => { + const older = createSession('older', SessionStatus.Completed, 100, [{ number: 42 }]); + const newer = createSession('newer', SessionStatus.Completed, 200, [{ number: 42 }]); + const linked = createSession('linked', SessionStatus.Completed, 300, [{ number: 42, owned: false }]); + for (const session of [older, newer]) { + (session.isArchived as ISettableObservable<boolean>).set(true, undefined); + } + const fixture = createFixture([older, newer, linked]); + fixture.github.setPullRequest(42, openPullRequest(42)); + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Success); + store.add(fixture.service.acquireSessionAttention()); + const prospective = fixture.service.getSessionAttentionAfterUnarchive([older, newer]); + const snapshot = { + tabs: [older, newer].map(session => prospective.get(session.sessionId)?.tab), + archived: [older, newer].map(session => session.isArchived.get()), + polling: fixture.github.pollingCount, + currentTabs: [older, newer].map(session => fixture.service.sessionAttention.get().get(session.sessionId)?.tab), + }; + transaction(tx => { + for (const session of [older, newer]) { + (session.isArchived as ISettableObservable<boolean>).set(false, tx); + } + }); + assert.deepStrictEqual({ + snapshot, + restored: [older, newer].map(session => fixture.service.sessionAttention.get().get(session.sessionId)), + }, { + snapshot: { + tabs: [InboxTab.ReadyForYou, InboxTab.ReadyToMerge], archived: [true, true], polling: 3, + currentTabs: [InboxTab.ReadyForYou, InboxTab.ReadyForYou], + }, + restored: [older, newer].map(session => prospective.get(session.sessionId)), + }); + }); + + test('PR ownership deduplicates alerts, excludes busy and archived owners, and requires all open owned PRs to pass', () => { + const owner = createSession('owner', SessionStatus.Completed, 100, [{ number: 42 }, { number: 43 }]); + const linked = createSession('linked', SessionStatus.Completed, 200, [{ number: 42, owned: false }]); + const fixture = createFixture([linked, owner]); + for (const number of [42, 43]) { + fixture.github.setPullRequest(number, openPullRequest(number)); + } + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Success); + store.add(fixture.service.acquireSessionAttention()); + const ids = (id: string) => fixture.service.sessionAttention.get().get(id)!.notificationIds; + const partial = ids('owner'); + fixture.github.setCIStatus(43, GitHubCIOverallStatus.Success); + const ready = ids('owner'); + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Failure); + const failingOwner = ids('owner'); + const duplicate = ids('linked'); + (owner.status as ISettableObservable<SessionStatus>).set(SessionStatus.InProgress, undefined); + const busyOwner = ids('owner'); + const linkedFailure = ids('linked'); + (owner.status as ISettableObservable<SessionStatus>).set(SessionStatus.Completed, undefined); + (owner.isArchived as ISettableObservable<boolean>).set(true, undefined); + const archivedOwner = ids('owner'); + fixture.github.setCIStatus(42, GitHubCIOverallStatus.Success); + assert.deepStrictEqual({ partial, ready, failingOwner, duplicate, busyOwner, linkedFailure, archivedOwner, linkedSuccess: ids('linked') }, { + partial: [], ready: ['owner:passingCi:owner/repo#42:sha42,owner/repo#43:sha43'], + failingOwner: ['owner:failingCi:owner/repo#42:sha42'], duplicate: [], busyOwner: [], + linkedFailure: ['linked:failingCi:owner/repo#42:sha42'], archivedOwner: [], linkedSuccess: [], + }); + }); +}); + +function openPullRequest(number: number): IGitHubPullRequest { + return upcastPartial<IGitHubPullRequest>({ number, state: GitHubPullRequestState.Open, headSha: `sha${number}`, isDraft: false }); +} + +function reviewThread(login: string): IGitHubPullRequestReviewThread { + return upcastPartial<IGitHubPullRequestReviewThread>({ + id: 'thread', isResolved: false, + comments: [upcastPartial<IGitHubPullRequestReviewThread['comments'][number]>({ id: 1, author: { login, avatarUrl: '' }, createdAt: '2026-09-21T16:00:00Z', updatedAt: '2026-09-21T16:00:00Z' })], + }); +} + +function question(resolveId: string): Extract<IChatResponseModel['response']['value'][number], { kind: 'questionCarousel' }> { + return { kind: 'questionCarousel', resolveId, allowSkip: true, questions: [{ id: 'q', type: 'text', title: 'Question', required: true }], isUsed: false }; +} + +function pendingRequest(requestId: string, parts: IChatResponseModel['response']['value'], startedWaitingAt = 10, onDidChange: IChatResponseModel['onDidChange'] = Event.None): IChatRequestModel { + return upcastPartial<IChatRequestModel>({ + response: upcastPartial<IChatResponseModel>({ + requestId, isCanceled: false, isComplete: false, onDidChange, + response: upcastPartial<IChatResponseModel['response']>({ value: parts }), + isPendingConfirmation: observableValue('pending', { startedWaitingAt }), + }), + }); +} + +class TestChatService { + private readonly _models = new Map<string, IChatModel>(); + readonly chatModels = observableValue<readonly IChatModel[]>('chatModels', []); + readonly acquired: string[] = []; + acquire: (resource: URI, token: CancellationToken) => Promise<IChatModelReference | undefined> = async () => undefined; + + getSession(resource: URI): IChatModel | undefined { + return this._models.get(resource.toString()); + } + + async acquireOrLoadSession(resource: URI, _location: ChatAgentLocation, token: CancellationToken): Promise<IChatModelReference | undefined> { + this.acquired.push(resource.toString()); + return this.acquire(resource, token); + } + + setModel(resource: URI, model: IChatModel): void { + this._models.set(resource.toString(), model); + this.chatModels.set([...this._models.values()], undefined); + } + + setRequests(resource: URI, requests: readonly IChatRequestModel[]): void { + this.setModel(resource, upcastPartial<IChatModel>({ onDidChange: Event.None, getRequests: () => [...requests] })); + } + + removeSession(resource: URI): void { + this._models.delete(resource.toString()); + this.chatModels.set([...this._models.values()], undefined); + } +} + +class TestGitHubService { + pollingCount = 0; + private readonly _pullRequests = new Map<number, ReturnType<TestGitHubService['pullRequestModel']>>(); + private readonly _ci = new Map<number, ReturnType<TestGitHubService['ciModel']>>(); + private readonly _reviews = new Map<number, ReturnType<TestGitHubService['reviewModel']>>(); + + private trackPolling(): IDisposable { + this.pollingCount++; + return toDisposable(() => { this.pollingCount--; }); + } + + private pullRequestModel() { + return { pullRequest: observableValue<IGitHubPullRequest | undefined>('pr', undefined), refresh: async () => { }, startPolling: () => this.trackPolling() }; + } + + private ciModel() { + return { overallStatus: observableValue('ci', GitHubCIOverallStatus.Neutral), refresh: async () => { }, startPolling: () => this.trackPolling() }; + } + + private reviewModel() { + return { reviewThreads: observableValue<readonly IGitHubPullRequestReviewThread[]>('reviews', []), refresh: async () => { }, startPolling: () => this.trackPolling() }; + } + + createPullRequestModelReference(_owner: string, _repo: string, number: number): IReference<GitHubPullRequestModel> { + let model = this._pullRequests.get(number); + if (!model) { + model = this.pullRequestModel(); + this._pullRequests.set(number, model); + } + return { object: upcastPartial<GitHubPullRequestModel>(model), dispose: () => { } }; + } + + createPullRequestCIModelReference(_owner: string, _repo: string, number: number): IReference<GitHubPullRequestCIModel> { + let model = this._ci.get(number); + if (!model) { + model = this.ciModel(); + this._ci.set(number, model); + } + return { object: upcastPartial<GitHubPullRequestCIModel>(model), dispose: () => { } }; + } + + createPullRequestReviewThreadsModelReference(_owner: string, _repo: string, number: number): IReference<GitHubPullRequestReviewThreadsModel> { + let model = this._reviews.get(number); + if (!model) { + model = this.reviewModel(); + this._reviews.set(number, model); + } + return { object: upcastPartial<GitHubPullRequestReviewThreadsModel>(model), dispose: () => { } }; + } + + setPullRequest(number: number, value: IGitHubPullRequest): void { + this.createPullRequestModelReference('', '', number); + this._pullRequests.get(number)!.pullRequest.set(value, undefined); + } + + setCIStatus(number: number, value: GitHubCIOverallStatus): void { + this.createPullRequestCIModelReference('', '', number); + this._ci.get(number)!.overallStatus.set(value, undefined); + } + + setReviewThreads(number: number, value: readonly IGitHubPullRequestReviewThread[]): void { + this.createPullRequestReviewThreadsModelReference('', '', number); + this._reviews.get(number)!.reviewThreads.set(value, undefined); + } +} diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionComparisonService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionComparisonService.test.ts index 7393c9179cb0..c32bf68ee6c2 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionComparisonService.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionComparisonService.test.ts @@ -19,14 +19,16 @@ import { InMemoryStorageService, StorageScope, StorageTarget } from '../../../.. import { NullTelemetryServiceShape } from '../../../../../platform/telemetry/common/telemetryUtils.js'; import { IChatModelReference, IChatService, IChatUsage } from '../../../chat/common/chatService/chatService.js'; import { IChatModel, IChatRequestModel, IChatResponseModel } from '../../../chat/common/model/chatModel.js'; +import { ILanguageModelChatMetadata } from '../../../chat/common/languageModels.js'; import { getChatNotificationResource } from '../../../chat/common/chatNotification.js'; import { hashSessionIdForTelemetry } from '../../common/sessionsTelemetry.js'; -import { ChatInteractivity, ChatOriginKind, IChat, ISession, SessionStatus } from '../../../../services/sessions/common/session.js'; +import { ChatInteractivity, ChatOriginKind, IChat, ISession, ISessionType, SessionStatus } from '../../../../services/sessions/common/session.js'; import { getSessionComparisonHarnessDisplayLabel, getSessionComparisonWorkspaceError, ISessionComparison, ISessionComparisonHarness, ISessionComparisonSynthesisPlan, ISessionComparisonVerdict, SessionComparisonParticipantRole, SessionComparisonValidationSource, SessionComparisonValidationState } from '../../common/sessionComparison.js'; import { IChatDeletedEvent, ICreateNewSessionOptions, ISendRequestOptions, ISessionsManagementService, NewSessionRequestOptions } from '../../common/sessionsManagement.js'; import { IChatMovedEvent, ISessionChangeEvent } from '../../common/sessionsProvider.js'; import { IDeletedSessionGroups, ISessionGroup, ISessionGroupsChangeEvent, ISessionGroupsService } from '../../browser/sessionGroupsService.js'; import { SessionComparisonService } from '../../browser/sessionComparisonService.js'; +import { createSessionComparisonHarness } from '../../browser/sessionComparisonConfiguration.js'; suite('SessionComparisonService', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); @@ -42,6 +44,24 @@ suite('SessionComparisonService', () => { ], ['Copilot', 'Opus', 'Balance', 'Opus · High', 'Copilot · Opus · High']); }); + test('saves Fusion effort labels from the model schema, including the default', () => { + const effort = { type: 'string' as const, group: 'navigation', enum: ['standard', 'high'], enumItemLabels: ['Standard', 'High'], default: 'standard' }; + const create = (configuration: Record<string, string>) => createSessionComparisonHarness( + 'local-agent-host', + upcastPartial<ISessionType>({ id: 'copilotcli', label: 'Copilot' }), + { identifier: 'fusion', metadata: upcastPartial<ILanguageModelChatMetadata>({ name: 'Copilot Fusion', autoModelFusion: true, configurationSchema: { properties: { tier: effort } } }) }, + configuration, + { id: 'default', label: 'Manual', description: 'Ask before running tools' }, + ); + const high = create({ tier: 'high' }); + const standard = create({}); + effort.enumItemLabels[1] = 'Changed after launch'; + assert.deepStrictEqual([ + getSessionComparisonHarnessDisplayLabel(high), + getSessionComparisonHarnessDisplayLabel(standard), + ], ['Copilot · Copilot Fusion · High', 'Copilot · Copilot Fusion · Standard']); + }); + test('workspace validation requires available Git branch information', () => { assert.deepStrictEqual({ unresolved: getSessionComparisonWorkspaceError(undefined), @@ -1624,6 +1644,10 @@ suite('SessionComparisonService', () => { completions: completionEvents.map(event => ({ attemptIndex: event.data.attemptIndex, elapsedMs: event.data.elapsedMs, + inputTokens: event.data.inputTokens, + cachedTokens: event.data.cachedTokens, + outputTokens: event.data.outputTokens, + tokenCountIsComplete: event.data.tokenCountIsComplete, })), outcomes: outcomeEvents.map(event => ({ attemptIndex: event.data.attemptIndex, @@ -1649,8 +1673,8 @@ suite('SessionComparisonService', () => { persistedCompletionCount: JSON.parse(storageService.get('sessions.comparisonAttemptTelemetry', StorageScope.PROFILE) ?? '[]').length, }, { completions: [ - { attemptIndex: 0, elapsedMs: 95_000 }, - { attemptIndex: 1, elapsedMs: 120_000 }, + { attemptIndex: 0, elapsedMs: 95_000, inputTokens: 30, cachedTokens: 12, outputTokens: 8, tokenCountIsComplete: true }, + { attemptIndex: 1, elapsedMs: 120_000, inputTokens: 20, cachedTokens: undefined, outputTokens: 5, tokenCountIsComplete: false }, ], outcomes: [ { attemptIndex: 0, attemptCount: 2, providerId: 'other', agentId: 'type-one', modelId: 'model-one', recommended: false, judgeProviderId: 'other', judgeAgentId: 'judge-type', judgeModelId: 'judge-model' }, @@ -1670,6 +1694,46 @@ suite('SessionComparisonService', () => { }); }); + test('reports first-turn tokens without follow-up usage and distinguishes zero from missing usage', async () => { + const { service, sessionsManagementService, chatService, telemetryService } = createServices(); + const firstStatus = observableValue('firstStatus', SessionStatus.InProgress); + const secondStatus = observableValue('secondStatus', SessionStatus.InProgress); + sessionsManagementService.enqueue(stubSession('attempt-one', firstStatus)); + sessionsManagementService.enqueue(stubSession('attempt-two', secondStatus)); + chatService.setUsage(URI.parse('test-chat:/attempt-one'), [{ + kind: 'usage', + promptTokens: 0, + completionTokens: 0, + modelTotals: [{ model: 'model-one', inputTokens: 0, cachedTokens: 0, outputTokens: 0 }], + }, { + kind: 'usage', + promptTokens: 100, + completionTokens: 50, + modelTotals: [{ model: 'model-one', inputTokens: 100, cachedTokens: 20, outputTokens: 50 }], + }], 10); + chatService.setUsage(URI.parse('test-chat:/attempt-two'), [undefined], 20); + + await service.startComparison({ ...startOptions(), judgeHarness: undefined, synthesisHarness: undefined }); + firstStatus.set(SessionStatus.Completed, undefined); + secondStatus.set(SessionStatus.Error, undefined); + sessionsManagementService.fireChange(); + await timeout(0); + + assert.deepStrictEqual(telemetryService.events + .filter(event => event.name === 'agents/sessionComparisonAttemptCompleted') + .map(event => ({ + attemptIndex: event.data.attemptIndex, + elapsedMs: event.data.elapsedMs, + inputTokens: event.data.inputTokens, + cachedTokens: event.data.cachedTokens, + outputTokens: event.data.outputTokens, + tokenCountIsComplete: event.data.tokenCountIsComplete, + })), [ + { attemptIndex: 0, elapsedMs: 10, inputTokens: 0, cachedTokens: 0, outputTokens: 0, tokenCountIsComplete: true }, + { attemptIndex: 1, elapsedMs: 20, inputTokens: undefined, cachedTokens: undefined, outputTokens: undefined, tokenCountIsComplete: false }, + ]); + }); + test('removes remote connection details from comparison model telemetry', async () => { const { service, sessionsManagementService, telemetryService } = createServices(); const firstStatus = observableValue('firstStatus', SessionStatus.InProgress); @@ -1877,6 +1941,23 @@ suite('SessionComparisonService', () => { ]); }); + test('preserves the exact initiating chat independently of participants across reload', async () => { + const { service, sessionsManagementService, storageService, groupsService, chatService } = createServices(); + sessionsManagementService.enqueue(stubSession('attempt-one')); + sessionsManagementService.enqueue(stubSession('attempt-two')); + const originatingChatResource = URI.parse('test:/evaluator#nested-chat'); + const comparison = await service.startComparison({ + ...startOptions(), originatingChatResource, judgeHarness: undefined, synthesisHarness: undefined, + }); + service.dispose(); + const restored = disposables.add(new SessionComparisonService(sessionsManagementService, groupsService, storageService, new NullLogService(), chatService, new RecordingTelemetryService())); + assert.deepStrictEqual({ + created: comparison.originatingChatResource?.toString(), + restored: restored.getComparison(comparison.id)?.originatingChatResource?.toString(), + legacyParent: restored.getComparison(comparison.id)?.sessionResource, + }, { created: originatingChatResource.toString(), restored: originatingChatResource.toString(), legacyParent: undefined }); + }); + test('restores persisted URI fields', () => { const storageService = disposables.add(new InMemoryStorageService()); storageService.store('sessions.comparisons', JSON.stringify([{ @@ -2406,12 +2487,12 @@ class TestSessionsManagementService extends mock<ISessionsManagementService>() i } class TestChatService extends mock<IChatService>() { - private readonly _responses = new Map<string, readonly { usage: IChatUsage; elapsedMs?: number }[]>(); + private readonly _responses = new Map<string, readonly { usage: IChatUsage | undefined; elapsedMs?: number }[]>(); readonly releasedModels: string[] = []; readonly acquiredModels: IChatModel[] = []; readonly requestInProgress = observableValue('requestInProgress', true); - setUsage(resource: URI, usages: readonly IChatUsage[], firstTurnElapsedMs?: number): void { + setUsage(resource: URI, usages: readonly (IChatUsage | undefined)[], firstTurnElapsedMs?: number): void { this._responses.set(resource.toString(), usages.map((usage, index) => ({ usage, elapsedMs: index === 0 ? firstTurnElapsedMs : undefined, diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionDraftsService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionDraftsService.test.ts new file mode 100644 index 000000000000..37be4c2f7949 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionDraftsService.test.ts @@ -0,0 +1,583 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestDialogService } from '../../../../../platform/dialogs/test/common/testDialogService.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { INotificationService, NotificationMessage } from '../../../../../platform/notification/common/notification.js'; +import { NotificationText } from '../../../../../platform/notification/common/notificationMessage.js'; +import { InMemoryStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; +import { ILifecycleService } from '../../../../services/lifecycle/common/lifecycle.js'; +import { IChat, ISession } from '../../../../services/sessions/common/session.js'; +import { SessionDraftsService } from '../../browser/sessionDraftsService.js'; +import { getPendingSessionAriaLabel } from '../../browser/views/pendingSessions.js'; +import { ISessionGroupsService } from '../../browser/sessionGroupsService.js'; +import { ISessionsService } from '../../browser/sessionsService.js'; +import { ISavedSessionDraft } from '../../common/savedSessionDrafts.js'; +import { ISendRequestSentEvent, ISessionsManagementService } from '../../common/sessionsManagement.js'; +import { SESSIONS_DRAFTS_ENABLED_SETTING } from '../../common/sessionConfig.js'; + +suite('Saved session draft lifecycle', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function create(enabled = true, storage = disposables.add(new InMemoryStorageService())) { + const config = new TestConfigurationService({ [SESSIONS_DRAFTS_ENABLED_SETTING]: enabled }); + const sent = disposables.add(new Emitter<ISendRequestSentEvent>()); + const navigation: (string | undefined)[] = []; + const notifications: string[] = []; + const infoNotifications: NotificationMessage[] = []; + const lifecycle = new class extends mock<ILifecycleService>() { + override willShutdown = false; + }; + let openSavedDraft: ((id: string, token: CancellationToken) => Promise<boolean>) | undefined; + const view = new class extends mock<ISessionsService>() { + override registerSavedDraftOpener(opener: (id: string, token: CancellationToken) => Promise<boolean>) { openSavedDraft = opener; return Disposable.None; } + override setCurrentDraftId(id: string | undefined) { navigation.push(id); } + override async openNewSession(_options?: Parameters<ISessionsService['openNewSession']>[0]) { return { session: undefined, trustDeclined: false }; } + }; + const management = new class extends mock<ISessionsManagementService>() { + override readonly onDidSendRequest = sent.event; + override readonly onDidEndNewSessionRequest = Event.None; + override readonly onDidReplaceNewDraftSession = Event.None; + }; + const groups = new class extends mock<ISessionGroupsService>() { + override getPendingNewSessionGroup() { return 'group'; } + override setPendingNewSessionGroup() { } + }; + const entitlement = new class extends mock<IChatEntitlementService>() { + override readonly sentiment = {}; + override readonly onDidChangeSentiment = Event.None; + }; + const service = disposables.add(new SessionDraftsService(storage, config, view, management, + new TestDialogService({ confirmed: true }), new class extends mock<INotificationService>() { + override error(message: Parameters<INotificationService['error']>[0]) { notifications.push(String(message)); } + override info(message: NotificationMessage | NotificationMessage[]) { infoNotifications.push(...Array.isArray(message) ? message : [message]); } + }, new NullLogService(), groups, entitlement, lifecycle)); + return { service, storage, config, sent, navigation, view, notifications, infoNotifications, lifecycle, openSavedDraft: (id: string, token: CancellationToken) => openSavedDraft!(id, token) }; + } + + test('default-off preserves the singleton behavior without creating a collection or draft history', () => { + const { service, storage, navigation } = create(false); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async () => { }, () => { })); + composer.updateInput({ inputText: 'unsent', attachments: [] }); + registration.dispose(); + assert.deepStrictEqual({ + saved: storage.get('sessions.savedDrafts', StorageScope.PROFILE), + sections: service.sections.get(), + draftHistory: navigation.filter(Boolean), + }, { saved: undefined, sections: [], draftHistory: [] }); + }); + + test('draft rows show only workspace metadata while retaining accessible draft semantics', () => { + const { service } = create(); + service.save({ inputText: 'Workspace request', attachments: [] }, { folderUri: URI.file('/workspace/vscode') }); + service.save({ inputText: 'Unscoped request', attachments: [] }, {}); + assert.deepStrictEqual(service.sections.get()[0].items.map(item => ({ + title: item.title, description: item.description, ariaLabel: getPendingSessionAriaLabel(item), + })).sort((a, b) => a.title.localeCompare(b.title)), [ + { title: 'Unscoped request', description: '', ariaLabel: 'Unscoped request, draft' }, + { title: 'Workspace request', description: 'vscode', ariaLabel: 'Workspace request, draft, vscode' }, + ]); + }); + + test('navigation creates an info notification whose link restores the saved draft', async () => { + const { service, infoNotifications } = create(); + const openedDrafts: string[] = []; + disposables.add(service.onDidOpenDraft(id => openedDrafts.push(id))); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async () => { }, () => { })); + composer.updateInput({ inputText: 'Keep this draft', attachments: [] }); + const saved = service.stowAndClear(composer)!; + registration.dispose(); + const message = infoNotifications[0]; + assert.ok(message instanceof NotificationText); + const link = message.nodes.find(node => typeof node !== 'string'); + assert.ok(link); + const uri = URI.parse(link.href); + const command = CommandsRegistry.getCommand(uri.path); + assert.ok(command); + const next = service.createComposer(); + disposables.add(service.registerComposer(next, async draft => next.updateInput(draft.input), () => { })); + const instantiation = disposables.add(new TestInstantiationService()); + const args = JSON.parse(decodeURIComponent(uri.query)); + await instantiation.invokeFunction(command.handler, ...args); + service.stow(next, { notifyCreated: true }); + assert.deepStrictEqual({ + count: infoNotifications.length, message: message.toString(), label: link.label, + scheme: uri.scheme, restored: next.input, id: next.id, + openedDrafts, + }, { + count: 1, message: 'Created draft. Open Draft', label: 'Open Draft', + scheme: 'command', restored: saved.input, id: saved.id, + openedDrafts: [saved.id], + }); + await service.sections.get()[0].items.find(item => item.id === saved.id)!.actions.find(action => action.id === 'sessions.drafts.delete')!.run(); + await assert.rejects(async () => instantiation.invokeFunction(command.handler, ...args), /no longer available/); + }); + + test('draft notifications exclude disabled, empty, scheduling, restoration, and background saves', () => { + const results = ['disabled', 'empty', 'scheduling', 'restoring', 'background'].map(reason => { + const { service, infoNotifications } = create(reason !== 'disabled'); + const composer = service.createComposer(); + composer.updateInput({ inputText: reason === 'empty' ? ' ' : 'Unsent', attachments: [] }); + composer.isScheduling = reason === 'scheduling'; + composer.isRestoring = reason === 'restoring'; + service.stow(composer, { notifyCreated: reason !== 'background' }); + return { reason, count: infoNotifications.length }; + }); + assert.deepStrictEqual(results, ['disabled', 'empty', 'scheduling', 'restoring', 'background'].map(reason => ({ reason, count: 0 }))); + }); + + test('repeated navigation and disposal do not duplicate the creation notification', () => { + const { service, infoNotifications } = create(); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async () => { }, () => { })); + composer.updateInput({ inputText: 'Unsent', attachments: [] }); + service.stowAndClear(composer); + service.stowAndClear(composer); + registration.dispose(); + assert.deepStrictEqual(infoNotifications.map(message => message.toString()), ['Created draft. Open Draft']); + }); + + test('typing, autosave, reload, and disposal never create drafts or restore one automatically', async () => { + const storage = disposables.add(new InMemoryStorageService()); + const first = create(true, storage); + const composer = first.service.createComposer(); + const registration = disposables.add(first.service.registerComposer(composer, async () => { }, () => { })); + composer.updateInput({ inputText: 'Keep across reload', attachments: [] }); + await storage.flush(); + const afterAutosave = first.service.sections.get(); + first.lifecycle.willShutdown = true; + first.service.stowAndClear(composer); + registration.dispose(); + first.service.dispose(); + + const next = create(true, storage); + const nextComposer = next.service.createComposer(); + const nextRegistration = disposables.add(next.service.registerComposer(nextComposer, async () => assert.fail('Reload must not restore a saved draft'), () => { })); + nextComposer.updateInput({ inputText: 'Unsent after reload', attachments: [] }); + nextRegistration.dispose(); + assert.deepStrictEqual({ + afterAutosave, afterReload: next.service.sections.get(), + notifications: [...first.infoNotifications, ...next.infoNotifications], + }, { afterAutosave: [], afterReload: [], notifications: [] }); + }); + + test('saves several compositions, resumes the same identity, and retains them on live disable', async () => { + const { service, config } = create(); + const first = service.createComposer(); + const registration = disposables.add(service.registerComposer(first, async () => { }, () => { })); + first.updateInput({ inputText: 'first', attachments: [] }); + const firstDraft = service.stowAndClear(first)!; + registration.dispose(); + const second = service.createComposer(); + let restored: ISavedSessionDraft | undefined; + disposables.add(service.registerComposer(second, async draft => { + restored = draft; + second.updateInput(draft.input); + }, () => { })); + second.updateInput({ inputText: 'second', attachments: [] }); + await service.open(firstDraft.id); + const titles = service.sections.get().flatMap(section => section.items.map(item => item.title)).sort(); + await config.setUserConfiguration(SESSIONS_DRAFTS_ENABLED_SETTING, false); + config.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: key => key === SESSIONS_DRAFTS_ENABLED_SETTING, affectedKeys: new Set([SESSIONS_DRAFTS_ENABLED_SETTING]), source: 1, change: { keys: [SESSIONS_DRAFTS_ENABLED_SETTING], overrides: [] } }); + const hidden = service.sections.get(); + assert.deepStrictEqual({ titles, restoredId: restored?.id, composerId: second.id, hidden }, { + titles: ['first', 'second'], restoredId: firstDraft.id, composerId: firstDraft.id, hidden: [], + }); + }); + + test('starting a new composition saves and clears the input, then resumes its text, attachments and target', async () => { + const { service } = create(); + const composer = service.createComposer(); + const input = { inputText: 'keep this request', attachments: [{ kind: 'file' as const, id: 'file', name: 'file.ts', value: URI.file('/workspace/file.ts') }], references: undefined }; + const target = { folderUri: URI.file('/workspace'), providerId: 'provider', sessionTypeId: 'agent', modelId: 'model', groupId: 'group' }; + let visibleInput = input; + disposables.add(service.registerComposer(composer, async draft => { + composer.updateInput(draft.input); + }, () => { visibleInput = { inputText: '', attachments: [], references: undefined }; })); + composer.target = target; + composer.updateInput(input); + const id = composer.id; + const saved = service.stowAndClear(); + const cleared = { + visibleInput, input: composer.input, newIdentity: composer.id !== id, + savedInput: saved?.input, savedTarget: saved?.target, + }; + composer.updateInput({ inputText: 'another request', attachments: [] }); + await service.open(id); + assert.deepStrictEqual({ cleared, restored: composer.input, titles: service.sections.get()[0].items.map(item => item.title).sort() }, { + cleared: { visibleInput: { inputText: '', attachments: [], references: undefined }, input: { inputText: '', attachments: [] }, newIdentity: true, savedInput: input, savedTarget: target }, + restored: input, titles: ['another request', 'keep this request'], + }); + }); + + test('starting a new composition preserves disabled drafts and does not create empty drafts', () => { + const results = [false, true].map(enabled => { + const { service } = create(enabled); + const composer = service.createComposer(); + let cleared = false; + disposables.add(service.registerComposer(composer, async () => { }, () => { cleared = true; })); + composer.updateInput({ inputText: enabled ? ' ' : 'keep singleton input', attachments: [] }); + const id = composer.id; + service.stowAndClear(); + return { cleared, sameIdentity: composer.id === id, input: composer.input.inputText, sections: service.sections.get() }; + }); + assert.deepStrictEqual(results, [ + { cleared: false, sameIdentity: true, input: 'keep singleton input', sections: [] }, + { cleared: false, sameIdentity: true, input: ' ', sections: [] }, + ]); + }); + + test('opening a recovered schedule consumes its saved revision and stows occupied input', async () => { + const { service } = create(); + const draft = service.save({ + inputText: 'scheduled request', + attachments: [{ kind: 'file', id: 'file', name: 'file.ts', value: URI.file('/workspace/file.ts') }], + }, { folderUri: URI.file('/workspace'), providerId: 'provider', modelId: 'model', groupId: 'group' }); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async value => { + composer.updateInput(value.input); + }, () => { })); + composer.updateInput({ inputText: 'previous input', attachments: [] }); + + await service.open(draft.id, { removeFromDrafts: true }); + + const opened = { + input: composer.input, target: composer.target, id: composer.id, + saved: service.sections.get().flatMap(section => section.items.map(item => item.title)), + }; + service.stowAndClear(composer); + registration.dispose(); + assert.deepStrictEqual({ + opened, + afterLeaving: service.sections.get().flatMap(section => section.items.map(item => item.title)).sort(), + }, { + opened: { input: draft.input, target: draft.target, id: draft.id, saved: ['previous input'] }, + afterLeaving: ['previous input', 'scheduled request'], + }); + }); + + for (const outcome of ['failed', 'disposed'] as const) { + test(`opening a recovered schedule retains its saved revision when restoration is ${outcome}`, async () => { + const { service } = create(); + const draft = service.save({ inputText: 'recoverable request', attachments: [] }, {}); + const composer = service.createComposer(); + const started = new DeferredPromise<void>(); + const resume = new DeferredPromise<void>(); + const registration = disposables.add(service.registerComposer(composer, async () => { + started.complete(); + await resume.p; + if (outcome === 'failed') { + throw new Error('Restore failed'); + } + }, () => { })); + const opening = service.open(draft.id, { removeFromDrafts: true }); + await started.p; + if (outcome === 'disposed') { + registration.dispose(); + } + resume.complete(); + if (outcome === 'failed') { + await assert.rejects(opening, /Restore failed/); + } else { + await opening; + } + assert.deepStrictEqual(service.sections.get().flatMap(section => section.items.map(item => item.id)), [draft.id]); + }); + } + + test('opening a recovered schedule does not consume a newer saved revision', async () => { + const { service } = create(); + const draft = service.save({ inputText: 'original request', attachments: [] }, {}); + const composer = service.createComposer(); + disposables.add(service.registerComposer(composer, async value => { + service.save({ inputText: 'newer request', attachments: [] }, {}, draft.id); + composer.updateInput(value.input); + }, () => { })); + await service.open(draft.id, { removeFromDrafts: true }); + assert.deepStrictEqual({ + input: composer.input.inputText, + saved: service.sections.get().flatMap(section => section.items.map(item => item.title)), + }, { input: 'original request', saved: ['newer request'] }); + }); + + test('a failed save leaves the current input and identity intact', () => { + const { service, storage } = create(); + const composer = service.createComposer(); + let cleared = false; + disposables.add(service.registerComposer(composer, async () => { }, () => { cleared = true; })); + composer.updateInput({ inputText: 'must not lose this', attachments: [] }); + const id = composer.id; + const store = storage.store; + storage.store = () => { throw new Error('Storage unavailable'); }; + try { + assert.throws(() => service.stowAndClear(), /Storage unavailable/); + assert.deepStrictEqual({ cleared, sameIdentity: composer.id === id, input: composer.input.inputText }, { + cleared: false, sameIdentity: true, input: 'must not lose this', + }); + } finally { + storage.store = store; + } + }); + + test('overlapping opens cannot save the previous input under the next draft identity', async () => { + const { service } = create(); + const first = service.save({ inputText: 'first', attachments: [] }, {}); + const second = service.save({ inputText: 'second', attachments: [] }, {}); + const composer = service.createComposer(); + const started = new DeferredPromise<void>(); + const resume = new DeferredPromise<void>(); + disposables.add(service.registerComposer(composer, async draft => { + if (draft.id === first.id) { + started.complete(); + await resume.p; + } + composer.updateInput(draft.input); + }, () => { })); + const openingFirst = service.open(first.id); + await started.p; + const openingSecond = service.open(second.id); + resume.complete(); + await Promise.all([openingFirst, openingSecond]); + assert.deepStrictEqual({ + input: composer.input.inputText, id: composer.id, + titles: service.sections.get().flatMap(section => section.items.map(item => item.title)).sort(), + }, { input: 'second', id: second.id, titles: ['first', 'second'] }); + }); + + test('opening a draft restores only the requested draft when the composer registers', async () => { + const { service, view } = create(); + const previous = service.save({ inputText: 'previous draft', attachments: [] }, {}); + const requested = service.save({ inputText: 'requested draft', attachments: [] }, {}); + const composer = service.createComposer(); + composer.id = previous.id; + const restored: string[] = []; + view.openNewSession = async () => { + disposables.add(service.registerComposer(composer, async draft => { + restored.push(draft.id); + composer.updateInput(draft.input); + }, () => { })); + return { session: undefined, trustDeclined: false }; + }; + + await service.open(requested.id); + + assert.deepStrictEqual({ restored, input: composer.input, id: composer.id }, { + restored: [requested.id], input: requested.input, id: requested.id, + }); + }); + + test('registering a composer does not automatically restore an existing draft', async () => { + const { service, storage } = create(); + const previous = service.save({ inputText: 'previous draft', attachments: [] }, {}); + const requested = service.save({ inputText: 'requested draft', attachments: [] }, {}); + storage.store('sessions.savedDrafts.active', previous.id, StorageScope.WORKSPACE, StorageTarget.MACHINE); + const composer = service.createComposer(); + const originalId = composer.id; + composer.id = previous.id; + const restored: string[] = []; + disposables.add(service.registerComposer(composer, async draft => { + restored.push(draft.id); + composer.updateInput(draft.input); + }, () => { })); + + await Promise.resolve(); + assert.deepStrictEqual(restored, []); + composer.id = originalId; + await service.open(requested.id); + + assert.deepStrictEqual({ + restored, input: composer.input, id: composer.id, + titles: service.sections.get()[0].items.map(item => item.title).sort(), + }, { + restored: [requested.id], input: requested.input, id: requested.id, + titles: ['previous draft', 'requested draft'], + }); + }); + + test('restoring input does not record an intermediate empty composer in navigation', async () => { + const { service, navigation, view } = create(); + view.openNewSession = async options => { + if (!options?.preserveNavigation) { + navigation.push('intermediate composer'); + } + return { session: undefined, trustDeclined: false }; + }; + const draft = service.save({ inputText: 'saved', attachments: [] }, {}); + const composer = service.createComposer(); + disposables.add(service.registerComposer(composer, async value => { + composer.updateInput({ inputText: '', attachments: [] }); + composer.updateInput(value.input); + }, () => { })); + navigation.length = 0; + await service.open(draft.id); + assert.deepStrictEqual(navigation, [draft.id]); + }); + + test('background completion removes only the submitted draft and never a newer composition', () => { + const { service, sent } = create(); + const composer = service.createComposer(); + disposables.add(service.registerComposer(composer, async () => { }, () => { })); + const input = { inputText: 'sent input', attachments: [] }; + composer.updateInput(input); + service.stow(composer); + composer.willSend(input); + const options = { query: input.inputText, background: true }; + composer.trackSend(options, 'first'); + composer.updateInput({ inputText: '', attachments: [] }); + composer.didSend(true); + composer.updateInput({ inputText: 'new input', attachments: [] }); + service.stow(composer); + sent.fire({ session: new class extends mock<ISession>() { override readonly sessionId = 'first'; override readonly resource = URI.parse('test:/first'); }, chat: new class extends mock<IChat>() { }, isNewSession: true, isNewChat: true, options }); + assert.deepStrictEqual(service.sections.get().flatMap(section => section.items.map(item => item.title)), ['new input']); + }); + + test('emptying a saved composition removes its old record on navigation away', () => { + const { service } = create(); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async () => { }, () => { })); + composer.updateInput({ inputText: 'old input', attachments: [] }); + service.stow(composer); + composer.updateInput({ inputText: ' ', attachments: [] }); + service.stowAndClear(composer); + registration.dispose(); + assert.deepStrictEqual(service.sections.get(), []); + }); + + test('deleting the active draft cannot recreate its input during subsequent disposal', async () => { + const { service } = create(); + const composer = service.createComposer(); + let restored = false; + let cleared = false; + const registration = disposables.add(service.registerComposer(composer, async () => { restored = true; }, () => { cleared = true; })); + composer.updateInput({ inputText: 'delete me', attachments: [] }); + service.stow(composer); + await service.sections.get()[0].items[0].actions.find(action => action.id === 'sessions.drafts.delete')!.run(); + registration.dispose(); + assert.deepStrictEqual({ restored, cleared, input: composer.input, sections: service.sections.get() }, { restored: false, cleared: true, input: { inputText: '', attachments: [] }, sections: [] }); + }); + + test('a draft cannot replace a composition while its scheduling acknowledgment is pending', async () => { + const { service } = create(); + const next = service.save({ inputText: 'next', attachments: [] }, {}); + const composer = service.createComposer(); + disposables.add(service.registerComposer(composer, async () => assert.fail('Must not replace input'), () => { })); + composer.updateInput({ inputText: 'scheduling', attachments: [] }); + composer.isScheduling = true; + await assert.rejects(service.open(next.id), /finish scheduling/); + assert.strictEqual(composer.input.inputText, 'scheduling'); + }); + + test('a removed active draft does not reuse its scheduling identity on reload', () => { + const storage = disposables.add(new InMemoryStorageService()); + storage.store('sessions.savedDrafts.active', 'scheduled-composition', StorageScope.WORKSPACE, StorageTarget.MACHINE); + const { service } = create(true, storage); + assert.notStrictEqual(service.createComposer().id, 'scheduled-composition'); + }); + + test('unreadable draft storage reports the read failure without blocking a send', () => { + const { service, storage, notifications } = create(); + const raw = '{"version":99,"drafts":[]}'; + storage.store('sessions.savedDrafts', raw, StorageScope.PROFILE, StorageTarget.MACHINE); + const composer = service.createComposer(); + composer.willSend({ inputText: 'send this', attachments: [] }); + assert.deepStrictEqual({ + sending: composer.isSending, input: composer.input.inputText, + stored: storage.get('sessions.savedDrafts', StorageScope.PROFILE), + notified: notifications.some(message => message.includes('Could not read saved drafts')), + }, { sending: true, input: 'send this', stored: raw, notified: true }); + composer.didSend(false); + }); + + test('comparison acceptance removes its captured revision, while failure preserves it', () => { + const results = [true, false].map(accepted => { + const { service } = create(); + const composer = service.createComposer(); + composer.updateInput({ inputText: 'compare this', attachments: [] }); + service.stow(composer); + composer.willSend({ inputText: 'compare this', attachments: [] }); + composer.didSend(accepted); + return service.sections.get().flatMap(section => section.items.map(item => item.title)); + }); + assert.deepStrictEqual(results, [[], ['compare this']]); + }); + + test('cancelling and disposing during restore cannot persist old input under the requested identity', async () => { + const { service, openSavedDraft } = create(); + const requested = service.save({ inputText: 'requested', attachments: [] }, {}); + const composer = service.createComposer(); + const previousId = composer.id; + const started = new DeferredPromise<void>(); + const resume = new DeferredPromise<void>(); + const registration = disposables.add(service.registerComposer(composer, async (draft, token) => { + started.complete(); + await resume.p; + if (!token?.isCancellationRequested) { + composer.updateInput(draft.input); + } + }, () => { })); + composer.updateInput({ inputText: 'previous', attachments: [] }); + const cancellation = disposables.add(new CancellationTokenSource()); + const opening = openSavedDraft(requested.id, cancellation.token); + await started.p; + cancellation.cancel(); + registration.dispose(); + resume.complete(); + await opening; + assert.deepStrictEqual({ + id: composer.id, input: composer.input.inputText, + drafts: service.sections.get()[0].items.map(item => item.title).sort(), + }, { id: previousId, input: 'previous', drafts: ['previous', 'requested'] }); + }); + + test('failed send after navigation retains the original prompt', () => { + const { service } = create(); + const composer = service.createComposer(); + const registration = disposables.add(service.registerComposer(composer, async () => { }, () => { })); + const input = { inputText: 'recover me', attachments: [] }; + composer.updateInput(input); + service.stow(composer); + composer.willSend(input); + composer.updateInput({ inputText: '', attachments: [] }); + registration.dispose(); + composer.didSend(false); + assert.deepStrictEqual(service.sections.get().flatMap(section => section.items.map(item => item.title)), ['recover me']); + }); + + test('sending a new composition does not create a saved draft', () => { + const { service, infoNotifications } = create(); + const composer = service.createComposer(); + composer.willSend({ inputText: 'Send without drafting', attachments: [] }); + composer.dispose(); + composer.didSend(false); + assert.deepStrictEqual({ drafts: service.sections.get(), notifications: infoNotifications }, { drafts: [], notifications: [] }); + }); + + test('navigating away with attachments only creates a draft and its notification', () => { + const { service, infoNotifications } = create(); + const composer = service.createComposer(); + disposables.add(service.registerComposer(composer, async () => { }, () => { })); + const input = { inputText: '', attachments: [{ kind: 'file' as const, id: 'file', name: 'file.ts', value: URI.file('/workspace/file.ts') }] }; + composer.updateInput(input); + const saved = service.stowAndClear(composer); + assert.deepStrictEqual({ + savedInput: saved?.input, titles: service.sections.get()[0].items.map(item => item.title), + notifications: infoNotifications.map(message => message.toString()), currentInput: composer.input, + }, { savedInput: { ...input, references: undefined }, titles: ['Attached Context'], notifications: ['Created draft. Open Draft'], currentInput: { inputText: '', attachments: [] } }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBannerWidget.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBannerWidget.test.ts index 1daf79ce499e..a6c07e09d1fd 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBannerWidget.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBannerWidget.test.ts @@ -4,8 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { mainWindow } from '../../../../../../base/browser/window.js'; import type { IManagedHover } from '../../../../../../base/browser/ui/hover/hover.js'; -import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { DeferredPromise, retry, timeout } from '../../../../../../base/common/async.js'; import { IAction } from '../../../../../../base/common/actions.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; @@ -94,6 +95,40 @@ suite('SessionInputBannerWidget', () => { assert.strictEqual(primaryButton.getAttribute('aria-disabled'), 'false'); })); + test('pauses the working border while it is outside the viewport', async () => { + const host = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + host.style.cssText = 'position: fixed; top: 0; left: 0; width: 400px; height: 100px; overflow: hidden;'; + disposables.add(toDisposable(() => host.remove())); + const hoverService = upcastPartial<IHoverService>({ + setupManagedHover: () => upcastPartial<IManagedHover>({ dispose() { } }), + }); + const contextMenuService = upcastPartial<IContextMenuService>({ showContextMenu() { } }); + const widget = disposables.add(new SessionInputBannerWidget({ + icon: Codicon.warning, + accent: true, + text: '2 Checks Failing', + ariaLabel: '2 Checks Failing', + actions: [], + }, hoverService, contextMenuService)); + host.appendChild(widget.domNode); + widget.setWorking(true); + + // Under reduced motion the border has no animation, but its paused state is still tracked. + const reduced = mainWindow.matchMedia('(prefers-reduced-motion: reduce)').matches; + const waitForBorder = (state: 'running' | 'paused') => retry(async () => assert.deepStrictEqual({ + paused: widget.domNode.classList.contains('session-input-banner-anim-paused'), + animations: widget.domNode.getAnimations({ subtree: true }).map(animation => animation.playState), + }, { + paused: state === 'paused', + animations: reduced ? [] : [state, state], + }), 10, 100); + await waitForBorder('running'); + // Refreshing an already working banner must keep its visibility tracking. + widget.setWorking(true); + widget.domNode.style.marginTop = '200px'; + await waitForBorder('paused'); + }); + test('does not run a primary action whose readiness resolves after disposal', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const ready = new DeferredPromise<boolean>(); let primaryRuns = 0; diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBanners.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBanners.test.ts index aef265c02f86..3d2c424dc8d6 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBanners.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionInputBanners.test.ts @@ -144,6 +144,75 @@ suite('SessionInputBanners', () => { main.dispose(); }); + for (const kind of ['checks', 'prComments', 'agentComments', 'combined'] as const) { + test(`inline ${kind} shows pending feedback, reports a failed send, and remains available to retry`, async () => { + const built = buildTestSession({ id: `retry-${kind}`, title: 'Retry' }); + const chat = { ...built.mainChat.chat, workspace: constObservable(workspaceWithPullRequests('/retry', [pullRequest(42)])) }; + const session = { ...built.session, mainChat: constObservable(chat), chats: constObservable([chat]) }; + const feedback = observableValue<readonly IAgentFeedback[]>('feedback', kind === 'checks' ? [] + : [kind === 'agentComments' ? agentFeedback('selected', session.resource) : prFeedback('selected', session.resource, 42)]); + const ci = ciModel(kind === 'checks' || kind === 'combined' ? [failedCheck(1)] : []); + const instantiationService = store.add(new TestInstantiationService()); + const configuration = new TestConfigurationService({ [SESSIONS_LIST_INLINE_ACTIONS_SETTING]: true }); + store.add(configuration.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configuration); + instantiationService.stub(IContextKeyService, store.add(new ContextKeyService(configuration))); + instantiationService.stub(ISessionHost, new class extends mock<ISessionHost>() { }()); + instantiationService.stub(ISessionsProvidersService, { onDidChangeProviders: Event.None, getProvider: () => undefined }); + instantiationService.stub(ICommandService, new class extends mock<ICommandService>() { }()); + instantiationService.stub(IStorageService, store.add(new TestStorageService())); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IChatWidgetService, { getWidgetBySessionResource: () => { throw new Error('Must not open a widget'); } }); + instantiationService.stub(IGitHubService, { + createPullRequestModelReference: () => new ImmortalReference(pullRequestModel(42, 'PR', false)), + createPullRequestCIModelReference: () => new ImmortalReference(ci), + }); + let acceptance = new DeferredPromise<void>(); + let sends = 0; + const send = async () => { sends++; await acceptance.p; }; + instantiationService.stub(IAgentFeedbackService, { + onDidChangeFeedback: Event.None, + getFeedbackObservable: () => feedback, + acceptFeedback: (_resource, id) => feedback.set(feedback.get().map(item => item.id === id ? { ...item, state: AgentFeedbackState.Accepted } : item), undefined), + submitFeedback: async (_resource, options) => { + await send(); + feedback.set(feedback.get().map(item => options?.feedbackIds?.includes(item.id) ? { ...item, state: AgentFeedbackState.Submitted } : item), undefined); + options?.onRequestAccepted?.(); + return true; + }, + }); + instantiationService.stub(ISessionsManagementService, { getSession: () => session, sendRequestInBackground: send }); + const errors: string[] = []; + instantiationService.stub(INotificationService, { error: error => errors.push(String(error)) }); + instantiationService.stub(IChatEntitlementService, { onDidChangeSentiment: Event.None, sentiment: {} }); + const host = mainWindow.document.createElement('div'); + const before = host.appendChild(mainWindow.document.createElement('div')); + const row = store.add(instantiationService.createInstance(SessionInlineActions, session, undefined, before, constObservable(true), () => { }, () => { })); + const button = () => host.querySelector<HTMLElement>('.session-inline-actions:not([hidden]) .monaco-button')!; + const label = button().textContent; + button().dispatchEvent(new KeyboardEvent('keydown', { key: ' ', keyCode: 32, bubbles: true })); + await timeout(0); + const pending = { label: button().textContent?.trim(), disabled: button().getAttribute('aria-disabled'), states: feedback.get().map(item => item.state), ciRequested: ci.fixRequested.get() }; + row.dispose(); + store.add(instantiationService.createInstance(SessionInlineActions, session, undefined, before, constObservable(true), () => { }, () => { })); + button().click(); + await acceptance.error(new Error('Host unavailable')); + await timeout(0); + const failed = { label: button().textContent, disabled: button().getAttribute('aria-disabled'), states: feedback.get().map(item => item.state), ciRequested: ci.fixRequested.get(), sends, errors: [...errors] }; + + acceptance = new DeferredPromise<void>(); + button().click(); + await timeout(0); + await acceptance.complete(); + await timeout(0); + assert.deepStrictEqual({ pending, failed, retried: { hidden: host.querySelector<HTMLElement>('.session-inline-actions')!.hidden, sends, states: feedback.get().map(item => item.state), ciRequested: ci.fixRequested.get() } }, { + pending: { label: 'Sending...', disabled: 'true', states: kind === 'checks' ? [] : [AgentFeedbackState.Created], ciRequested: false }, + failed: { label, disabled: 'false', states: kind === 'checks' ? [] : [AgentFeedbackState.Created], ciRequested: false, sends: 1, errors: ['Error: Host unavailable'] }, + retried: { hidden: true, sends: 2, states: kind === 'checks' ? [] : [AgentFeedbackState.Submitted], ciRequested: kind === 'checks' || kind === 'combined' }, + }); + }); + } + test('shows the pull requests of the session of its window, not of the globally active session', () => { // One failing check per pull request: each session's pull request has its own number of failing checks. const sessionOf = (id: string, prNumber: number) => { diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionWorktreeCleanupService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionWorktreeCleanupService.test.ts index 1488a0d2f277..c487fed0659d 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionWorktreeCleanupService.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionInputBanners/sessionWorktreeCleanupService.test.ts @@ -21,13 +21,13 @@ import { IConfirmation, IDialogService } from '../../../../../../platform/dialog import { ByteSize } from '../../../../../../platform/files/common/files.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; import { IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; -import { IProgress, IProgressOptions, IProgressService, IProgressStep } from '../../../../../../platform/progress/common/progress.js'; +import { IProgress, IProgressOptions, IProgressService, IProgressStep, ProgressLocation } from '../../../../../../platform/progress/common/progress.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ISessionsListModelService } from '../../../browser/sessionsListModelService.js'; import { ISessionHostService } from '../../../../../services/sessions/browser/sessionHost.js'; import { DEFAULT_CHAT_CAPABILITIES, IChat, ISession, SessionStatus } from '../../../../../services/sessions/common/session.js'; import { IManagedSessionWorktree, ISessionsChangeEvent, ISessionsManagementService } from '../../../common/sessionsManagement.js'; -import { AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING, getWorktreeCleanupId, getWorktreeCleanupTitle, ISessionWorktree, SessionWorktreeCleanupProgress, SessionWorktreeCleanupService } from '../../../browser/sessionInputBanners/sessionWorktreeCleanupService.js'; +import { AGENT_SESSIONS_STORAGE_CLEANUP_SUGGESTION_SETTING, getWorktreeCleanupId, getWorktreeCleanupLastActivity, getWorktreeCleanupTitle, ISessionWorktree, SessionWorktreeCleanupProgress, SessionWorktreeCleanupService } from '../../../browser/sessionInputBanners/sessionWorktreeCleanupService.js'; suite('SessionWorktreeCleanupService', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); @@ -36,6 +36,158 @@ suite('SessionWorktreeCleanupService', () => { return { providerId: 'test', repository: URI.file('/repo').toString(), worktree: URI.file(worktree).toString(), branch: 'agents/unlinked', cleanupStatus: { state: 'unknown' } }; } + test('groups shared checkouts, measures once, and cleans up every associated session', async () => { + const first = createSession('first', oldDate()); + const latest = { ...createSession('latest', new Date()), workspace: first.workspace }; + const sessions = [first, latest]; + const measured: string[] = []; + const archived: string[] = []; + const scheduled: string[] = []; + const service = disposables.add(createService(sessions, true, session => { + measured.push(session.sessionId); + return 100; + }, undefined, undefined, undefined, undefined, undefined, undefined, undefined, { + onArchive: async session => { archived.push(session.sessionId); }, + onCleanup: async (session, retry) => { if (retry) { scheduled.push(session.sessionId); } return { state: 'pending' }; }, + dialogService: upcastPartial<IDialogService>({ confirm: async () => ({ confirmed: true }) }), + })); + const rows = await service.getWorktrees(0); + sessions.reverse(); + const reordered = await service.getWorktrees(0, undefined, undefined, true); + await service.cleanupWorktrees(rows); + assert.deepStrictEqual({ + count: rows.length, worktrees: rows[0].worktreeCount, bytes: rows[0].sizeBytes, + lastActivity: getWorktreeCleanupLastActivity(rows[0]), measured, archived: archived.sort(), scheduled: scheduled.sort(), + stableIdentity: getWorktreeCleanupId(rows[0]) === getWorktreeCleanupId(reordered[0]), + }, { + count: 1, worktrees: 1, bytes: 100, lastActivity: latest.updatedAt.get(), + measured: ['latest', 'latest'], archived: ['first', 'latest'], scheduled: ['first', 'latest'], stableIdentity: true, + }); + }); + + test('shared worktrees use the newest activity and protect a running or pinned associated session', async () => { + const first = createSession('first', oldDate()); + const status = observableValue('status', SessionStatus.Completed); + const updatedAt = observableValue('updatedAt', new Date()); + const latest = { ...createSession('latest', oldDate()), workspace: first.workspace, status, updatedAt }; + const service = disposables.add(createService([first, latest], true, () => 100)); + const recent = (await service.getWorktrees(15))[0].cleanupState; + updatedAt.set(oldDate(), undefined); + status.set(SessionStatus.InProgress, undefined); + const running = (await service.getWorktrees(0))[0].cleanupState; + status.set(SessionStatus.Completed, undefined); + const pinnedService = disposables.add(createService([first, latest], true, () => 100, undefined, undefined, undefined, undefined, latest)); + assert.deepStrictEqual({ recent, running, pinned: (await pinnedService.getWorktrees(0))[0].cleanupState }, { recent: 'recent', running: 'running', pinned: 'pinned' }); + }); + + test('overlapping multi-folder sessions stay together without double-counting worktrees or storage', async () => { + const first = createSession('first', oldDate(), SessionStatus.Completed, false, true, 2); + const other = createSession('other', oldDate()); + const overlap = { + ...other, + workspace: constObservable({ ...other.workspace.get()!, folders: [first.workspace.get()!.folders[1], ...other.workspace.get()!.folders] }), + }; + const service = disposables.add(createService([first, overlap], true, () => 200)); + const rows = await service.getWorktrees(0); + assert.deepStrictEqual(rows.map(row => ({ count: row.worktreeCount, size: row.sizeBytes, state: row.cleanupState, sessions: row.sessions?.length })), [ + { count: 3, size: undefined, state: 'eligible', sessions: 2 }, + ]); + }); + + test('active and needs-input members outrank eligible members regardless of representative order', async () => { + const first = createSession('first', oldDate()); + const active = { ...createSession('active', oldDate()), workspace: first.workspace }; + const needsInput = { ...createSession('input', oldDate(), SessionStatus.NeedsInput), workspace: first.workspace }; + const results: string[] = []; + for (const member of [active, needsInput]) { + for (const sessions of [[first, member], [member, first]]) { + const service = disposables.add(createService(sessions, true, () => 100, undefined, undefined, [active])); + results.push((await service.getWorktrees(0))[0].cleanupState); + } + } + const pinned = disposables.add(createService([first, needsInput], true, () => 100, undefined, undefined, [], undefined, first)); + results.push((await pinned.getWorktrees(0))[0].cleanupState); + assert.deepStrictEqual(results, ['active', 'active', 'needsInput', 'needsInput', 'pinned']); + }); + + test('prepares every shared session before archive and awaits archive completion before retry', async () => { + const first = createSession('first', oldDate()); + const second = { ...createSession('second', new Date(0)), workspace: first.workspace }; + const archiveStarted = new DeferredPromise<void>(); + const archiveCompleted = new DeferredPromise<void>(); + const calls: string[] = []; + const service = disposables.add(createService([first, second], true, () => 100, undefined, undefined, undefined, undefined, undefined, undefined, undefined, { + onPrepare: async session => { calls.push(`prepare:${session.sessionId}`); }, + onArchive: async session => { + calls.push(`archive:${session.sessionId}`); + await archiveStarted.complete(); + await archiveCompleted.p; + }, + onCleanup: async (session, retry) => { if (retry) { calls.push(`retry:${session.sessionId}`); } return { state: 'pending' }; }, + dialogService: upcastPartial<IDialogService>({ confirm: async () => ({ confirmed: true }) }), + })); + const cleanup = service.cleanupWorktrees([{ session: first, sessions: [first, second], sizeBytes: 100, worktreeCount: 1 }]); + await archiveStarted.p; + const beforeAcknowledgement = [...calls]; + await archiveCompleted.complete(); + await cleanup; + assert.deepStrictEqual({ beforeAcknowledgement, calls }, { + beforeAcknowledgement: ['prepare:first', 'prepare:second', 'archive:first'], + calls: ['prepare:first', 'prepare:second', 'archive:first', 'archive:second', 'retry:first', 'retry:second'], + }); + }); + + test('preparation failure prevents archiving any associated session', async () => { + const first = createSession('first', oldDate()); + const second = { ...createSession('second', new Date(0)), workspace: first.workspace }; + const calls: string[] = []; + const service = disposables.add(createService([first, second], true, () => 100, undefined, undefined, undefined, undefined, undefined, undefined, undefined, { + onPrepare: async session => { + calls.push(`prepare:${session.sessionId}`); + if (session === second) { + throw new Error('Unsupported cleanup preparation'); + } + }, + onArchive: async session => { calls.push(`archive:${session.sessionId}`); }, + dialogService: upcastPartial<IDialogService>({ confirm: async () => ({ confirmed: true }) }), + })); + await assert.rejects(service.cleanupWorktrees([{ session: first, sessions: [first, second], sizeBytes: 100, worktreeCount: 1 }]), /Unsupported cleanup preparation/); + assert.deepStrictEqual(calls, ['prepare:first', 'prepare:second']); + }); + + test('publishes cleanup eligibility before disk usage is available', async () => { + const measurement = new DeferredPromise<number>(); + const session = createSession('ready', oldDate()); + const service = disposables.add(createService([session], true, () => measurement.p)); + const snapshots: { state: string; measuring: boolean | undefined; size: number | undefined }[] = []; + const loading = service.getWorktrees(0, rows => { + if (rows[0]) { + snapshots.push({ state: rows[0].cleanupState, measuring: rows[0].isMeasuring, size: rows[0].sizeBytes }); + } + }); + await measurement.complete(100); + await loading; + assert.deepStrictEqual([snapshots[0], snapshots[snapshots.length - 1]], [ + { state: 'eligible', measuring: true, size: undefined }, + { state: 'eligible', measuring: false, size: 100 }, + ]); + }); + + test('explicit cleanup verifies scheduling after archive and rejects an unknown outcome', async () => { + const session = createSession('branch', oldDate()); + const calls: string[] = []; + const progress: string[] = []; + const service = disposables.add(createService([session], true, () => 100, undefined, undefined, undefined, undefined, undefined, undefined, undefined, { + onArchive: async () => { calls.push('archive'); }, + onCleanup: async (_session, retry) => { calls.push(`cleanup:${retry}`); return { state: 'unknown' }; }, + dialogService: upcastPartial<IDialogService>({ confirm: async () => ({ confirmed: true }) }), + })); + await assert.rejects(service.cleanupWorktrees([{ session, sizeBytes: 100, worktreeCount: 1 }], update => progress.push(update.state)), /cleanup was not confirmed/); + assert.deepStrictEqual({ calls, progress, operations: service.cleanupOperations.get().map(operation => operation.state) }, { + calls: ['archive', 'cleanup:true'], progress: ['started', 'failed'], operations: ['failed'], + }); + }); + test('excludes remote linked and unlinked worktrees before measuring or publishing inventory', async () => { const local = createSession('local', oldDate()); const original = createSession('remote', oldDate()); @@ -898,6 +1050,62 @@ suite('SessionWorktreeCleanupService', () => { assert.deepStrictEqual({ before, during, after, measurements }, { before: ByteSize.GB, during: undefined, after: 2 * ByteSize.GB, measurements: 2 }); }); + test('distinguishes empty worktrees from missing or unverified worktrees before displaying zero usage', async () => { + const session = createSession('session', oldDate()); + const results: { exists: boolean | undefined; size: number | undefined; failed: boolean | undefined; error: string | undefined }[] = []; + for (const exists of [true, false, undefined, 'error'] as const) { + const service = disposables.add(createService([session], true, () => 0, undefined, undefined, undefined, undefined, undefined, undefined, Event.None, { + onExists: async () => { + if (exists === 'error') { + throw new Error('Host disconnected'); + } + return exists; + }, + })); + const [worktree] = await service.getWorktrees(0); + results.push({ exists: worktree.worktreeExists, size: worktree.sizeBytes, failed: worktree.measurementFailed, error: worktree.worktreeCheckError }); + } + assert.deepStrictEqual(results, [ + { exists: true, size: 0, failed: false, error: undefined }, + { exists: false, size: 0, failed: false, error: undefined }, + { exists: undefined, size: undefined, failed: true, error: undefined }, + { exists: undefined, size: undefined, failed: true, error: 'Host disconnected' }, + ]); + }); + + test('does not count missing unarchived worktrees toward cleanup suggestions and rechecks them on refresh', async () => { + const sessions = Array.from({ length: 20 }, (_, index) => createSession(`missing-${index}`, oldDate())); + let exists = false; + const service = disposables.add(createService(sessions, true, () => 0, undefined, undefined, undefined, undefined, undefined, undefined, Event.None, { + onExists: async () => exists, + })); + await service.activate(); + const before = { suggestion: !!service.suggestion.get(), missing: (await service.getWorktrees(0)).filter(worktree => worktree.worktreeExists === false).length }; + exists = true; + await service.refresh(); + const after = { suggestion: !!service.suggestion.get(), missing: (await service.getWorktrees(0)).filter(worktree => worktree.worktreeExists === false).length }; + assert.deepStrictEqual({ before, after }, { + before: { suggestion: false, missing: 20 }, + after: { suggestion: true, missing: 0 }, + }); + }); + + test('does not hide a restored session using an in-flight archived existence check', async () => { + const archived = observableValue('archived', true); + const session = createSession('session', oldDate(), SessionStatus.Completed, true, true, 1, archived); + const started = new DeferredPromise<void>(); + const existence = new DeferredPromise<boolean>(); + const service = disposables.add(createService([session], true, () => 100, undefined, undefined, undefined, undefined, undefined, undefined, Event.None, { + onExists: async () => { started.complete(); return existence.p; }, + })); + const loading = service.getWorktrees(0); + await started.p; + archived.set(false, undefined); + await existence.complete(false); + const [worktree] = await loading; + assert.deepStrictEqual({ state: worktree.cleanupState, exists: worktree.worktreeExists }, { state: 'eligible', exists: undefined }); + }); + test('rechecks archived existence on cached loads without scanning sizes or reusing absence after recreation', async () => { const archived = createSession('archived', oldDate(), SessionStatus.Completed, true); let exists = true; @@ -1214,9 +1422,9 @@ suite('SessionWorktreeCleanupService', () => { await service.cleanupWorktrees([archivedCandidate]); await service.cleanupWorktrees([activeCandidate, archivedCandidate]); assert.deepStrictEqual(dialogs, [ - { message: 'Clean up 1 worktree?', detail: 'Estimated disk usage: 1.00GB. Actual freed space may be lower. The selected sessions will be marked as done. You can restore a session later to recreate its worktree.' }, - { message: 'Clean up 1 worktree?', detail: 'This schedules worktree cleanup and marks the selected sessions as done. Disk usage is not measured for sessions already marked as done. You can restore a session later to recreate its worktree.' }, - { message: 'Clean up 2 worktrees?', detail: 'This schedules worktree cleanup and marks the selected sessions as done. Disk usage is not measured for sessions already marked as done. You can restore a session later to recreate its worktree.' }, + { message: 'Clean up 1 worktree?', detail: 'Sessions will be marked as done. Changes are saved to their branches; ignored files are deleted. You can restore sessions later.' }, + { message: 'Clean up 1 worktree?', detail: 'Sessions will be marked as done. Changes are saved to their branches; ignored files are deleted. You can restore sessions later.' }, + { message: 'Clean up 2 worktrees?', detail: 'Sessions will be marked as done. Changes are saved to their branches; ignored files are deleted. You can restore sessions later.' }, ]); }); @@ -1378,7 +1586,7 @@ suite('SessionWorktreeCleanupService', () => { assert.strictEqual(cleanups, 0); }); - test('reports cleanup scheduling progress after each archived session', async () => { + test('shows concise scheduling progress when no caller handles it', async () => { const archived: string[] = []; const progressService = new TestProgressService(); const first = createSession('first', oldDate(), SessionStatus.Completed, false, true, 2); @@ -1410,6 +1618,7 @@ suite('SessionWorktreeCleanupService', () => { cleaned, archived, progress: progressService.options.map(options => ({ + location: options.location, title: options.title, total: options.total, })), @@ -1418,23 +1627,26 @@ suite('SessionWorktreeCleanupService', () => { cleaned: true, archived: ['first', 'second'], progress: [{ - title: 'Scheduling cleanup for 3 agent session worktrees...', - total: undefined, + location: ProgressLocation.Notification, + title: 'Scheduling worktree cleanup...', + total: 3, }], reports: [ - { increment: 2 / 3 * 100, message: 'scheduled 2 of 3 worktrees' }, - { increment: 1 / 3 * 100, message: 'scheduled 3 of 3 worktrees' }, + { increment: 2, message: '2 of 3 worktrees scheduled' }, + { increment: 1, message: '3 of 3 worktrees scheduled' }, ], }); }); - test('publishes confirmation and individual outcomes while continuing after scheduling failures', async () => { + test('publishes inline progress without a duplicate notification while continuing after scheduling failures', async () => { const first = createSession('first', oldDate(), SessionStatus.Completed, false, true, 2); const second = createSession('second', oldDate()); const third = createSession('third', oldDate()); const archived: string[] = []; const updates: SessionWorktreeCleanupProgress[] = []; + const progressService = new TestProgressService(); const service = disposables.add(createService([first, second, third], true, () => 100, undefined, undefined, undefined, undefined, undefined, undefined, Event.None, { + progressService, dialogService: upcastPartial<IDialogService>({ confirm: async () => ({ confirmed: true }) }), onArchive: async session => { archived.push(session.sessionId); @@ -1451,6 +1663,7 @@ suite('SessionWorktreeCleanupService', () => { ], progress => updates.push(progress)), /Couldn't schedule cleanup for 1 worktrees\.\nsecond: host disconnected/); assert.deepStrictEqual({ archived, + notifications: progressService.options, updates: updates.map(progress => progress.state === 'started' ? progress : { state: progress.state, session: getWorktreeCleanupId(progress.candidate), @@ -1458,6 +1671,7 @@ suite('SessionWorktreeCleanupService', () => { }), }, { archived: ['first', 'second', 'third'], + notifications: [], updates: [ { state: 'started' }, { state: 'scheduled', session: 'first', message: undefined }, @@ -1955,6 +2169,7 @@ function createService( readonly progressService?: IProgressService; readonly dialogService?: IDialogService; readonly onArchive?: (session: ISession) => Promise<void>; + readonly onPrepare?: ISessionsManagementService['prepareSessionWorktreeCleanup']; readonly onCleanup?: ISessionsManagementService['sessionWorktreeCleanup']; readonly canForceWorktreeCleanup?: ISessionsManagementService['canForceWorktreeCleanup']; readonly onExists?: ISessionsManagementService['sessionWorktreeExists']; @@ -1970,6 +2185,7 @@ function createService( getSessions: () => sessions, getSessionWorktreeDiskUsage: async (session, token) => sizeForSession(session, token), archiveSession: async session => overrides.onArchive?.(session), + prepareSessionWorktreeCleanup: async session => overrides.onPrepare?.(session), sessionWorktreeCleanup: overrides.onCleanup, canForceWorktreeCleanup: overrides.canForceWorktreeCleanup, sessionWorktreeExists: overrides.onExists ?? (async () => true), diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionScope.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionScope.test.ts new file mode 100644 index 000000000000..3e9ef229bacf --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionScope.test.ts @@ -0,0 +1,215 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Emitter, Event } from '../../../../../base/common/event.js'; +import { constObservable, ISettableObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { GITHUB_REMOTE_FILE_SCHEME, ISession, ISessionWorkspace } from '../../../../services/sessions/common/session.js'; +import { SessionsListingScopeFilter } from '../../browser/sessionScope.js'; +import { ISessionChangeEvent } from '../../common/sessionsProvider.js'; +import { buildTestSession, buildTestWorkspace } from '../common/testSessionBuilder.js'; + +suite('SessionsListingScopeFilter', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** A session working in the folder `/home/user/projects/<folder>`, which can move to another folder. */ + function createSession(id: string, folder: string): ISession & { readonly workspace: ISettableObservable<ISessionWorkspace | undefined> } { + return { ...buildTestSession({ id, title: id }).session, workspace: observableValue<ISessionWorkspace | undefined>(id, buildTestWorkspace(folder)) }; + } + + test('reports a session entering the scope as added, one leaving it as changed, and every removal as removed', () => { + const here = createSession('here', 'repo'); + const elsewhere = createSession('elsewhere', 'other'); + const hydrating = createSession('hydrating', 'other'); + const sessions = [here, elsewhere, hydrating]; + const changes = disposables.add(new Emitter<ISessionChangeEvent>()); + const folders = observableValue<readonly URI[]>('folders', [URI.file('/home/user/projects/repo')]); + const filter = disposables.add(new SessionsListingScopeFilter({ folders, repositories: constObservable([]) }, () => sessions, changes.event)); + const ids = (list: readonly ISession[]) => list.map(session => session.sessionId).sort().join(','); + const events: string[] = []; + disposables.add(filter.onDidChangeSessions(e => events.push(`added=${ids(e.added)} removed=${ids(e.removed)} changed=${ids(e.changed)}`))); + const listed: string[] = [ids(filter.getSessions())]; + + // A session's workspace hydrates into the scope, without an event of its provider + hydrating.workspace.set(buildTestWorkspace('repo'), undefined); + listed.push(ids(filter.getSessions())); + // Changes of hidden sessions are not reported, those of listed ones are + changes.fire({ added: [], removed: [], changed: [elsewhere, here] }); + // The window's folder changes: the listed sessions are hidden, not removed + folders.set([URI.file('/home/user/projects/other')], undefined); + listed.push(ids(filter.getSessions())); + // A removal of a hidden session is still reported, as an open of it can show it + sessions.splice(sessions.indexOf(here), 1); + changes.fire({ added: [], removed: [here], changed: [] }); + // Without folders, every session is listed + folders.set([], undefined); + listed.push(ids(filter.getSessions())); + + assert.deepStrictEqual({ listed, events }, { + listed: ['here', 'here,hydrating', 'elsewhere', 'elsewhere,hydrating'], + events: [ + 'added=hydrating removed= changed=', + 'added= removed= changed=here', + 'added=elsewhere removed= changed=here,hydrating', + 'added= removed=here changed=', + 'added=hydrating removed= changed=', + ], + }); + }); + + test('lists the replacement of a session, as a change of its sessions only reports it, and matches it to the scope again', () => { + const here = createSession('here', 'repo'); + const other = createSession('other', 'repo'); + const sessions: ISession[] = [here, other]; + const changes = disposables.add(new Emitter<ISessionChangeEvent>()); + const folders = observableValue<readonly URI[]>('folders', [URI.file('/home/user/projects/repo')]); + const filter = disposables.add(new SessionsListingScopeFilter({ folders, repositories: constObservable([]) }, () => sessions, changes.event)); + const events: { readonly added: readonly ISession[]; readonly removed: readonly ISession[]; readonly changed: readonly ISession[] }[] = []; + disposables.add(filter.onDidChangeSessions(e => events.push(e))); + + // A pending session committed under the same ID: another object, which comes as a change only + const committed = createSession('here', 'repo'); + sessions[0] = committed; + changes.fire({ added: [], removed: [], changed: [committed] }); + const listedCommitted = filter.getSessions().find(session => session.sessionId === 'here'); + // A replacement that works elsewhere leaves the scope + const moved = createSession('other', 'elsewhere'); + sessions[1] = moved; + changes.fire({ added: [], removed: [], changed: [moved] }); + + assert.deepStrictEqual({ + listedCommitted: listedCommitted === committed, + listed: filter.getSessions().map(session => session.sessionId), + events: events.map(e => ({ added: e.added.length, removed: e.removed.length, changed: e.changed.map(session => session === committed ? 'committed' : session === other ? 'other' : session === moved ? 'moved' : 'stale') })), + }, { + listedCommitted: true, + listed: ['here'], + events: [{ added: 0, removed: 0, changed: ['committed'] }, { added: 0, removed: 0, changed: ['other'] }], + }); + }); + + test('lists the replacement of a hidden session that moves into the scope, and the session a draft graduates into', () => { + const hidden = createSession('hidden', 'other'); + const draft = createSession('draft', 'repo'); + const sessions: ISession[] = [hidden]; + const changes = disposables.add(new Emitter<ISessionChangeEvent>()); + const folders = observableValue<readonly URI[]>('folders', [URI.file('/home/user/projects/repo')]); + const filter = disposables.add(new SessionsListingScopeFilter({ folders, repositories: constObservable([]) }, () => sessions, changes.event)); + const listed = () => filter.getSessions().map(session => session === hidden ? 'hidden (stale)' : session === draft ? 'draft' : session.sessionId === 'hidden' ? 'hidden (replacement)' : session.sessionId); + + // A replacement under the same ID that works in the scope, reported as a change only + const moved = createSession('hidden', 'repo'); + sessions[0] = moved; + changes.fire({ added: [], removed: [], changed: [moved] }); + const afterMove = listed(); + // A draft is added and listed; its provider then drops it for the session it committed, with no change, and matches again + sessions.push(draft); + changes.fire({ added: [draft], removed: [], changed: [] }); + const withDraft = listed(); + sessions.splice(sessions.indexOf(draft), 1, createSession('committed', 'repo')); + filter.rematch(); + + assert.deepStrictEqual({ afterMove, withDraft, graduated: listed() }, { + afterMove: ['hidden (replacement)'], + withDraft: ['hidden (replacement)', 'draft'], + graduated: ['hidden (replacement)', 'committed'], + }); + }); + + test('announces how it lists the sessions differently from those listed before it', () => { + const here = createSession('here', 'repo'); + const elsewhere = createSession('elsewhere', 'other'); + const sessions = [here, elsewhere]; + const folders = observableValue<readonly URI[]>('folders', [URI.file('/home/user/projects/repo')]); + const filter = disposables.add(new SessionsListingScopeFilter({ folders, repositories: constObservable([]) }, () => sessions, Event.None)); + const ids = (list: readonly ISession[]) => list.map(session => session.sessionId).sort().join(','); + const events: string[] = []; + disposables.add(filter.onDidChangeSessions(e => events.push(`added=${ids(e.added)} removed=${ids(e.removed)} changed=${ids(e.changed)}`))); + + // From every session, as without a scope; from an earlier scope of the other folder; from the same sessions + filter.announceFrom(sessions); + filter.announceFrom([elsewhere]); + filter.announceFrom([here]); + + assert.deepStrictEqual(events, [ + 'added= removed= changed=elsewhere', + 'added=here removed= changed=elsewhere', + ]); + }); + + test('lists workspace-less quick chats in every scope, but not a session whose workspace is still hydrating', () => { + const quickChatFlag = observableValue('isQuickChat', true); + const quickChat: ISession = { ...createSession('quickChat', 'scratch'), workspace: observableValue<ISessionWorkspace | undefined>('quickChat', undefined), isQuickChat: quickChatFlag }; + const hydrating = { ...createSession('hydrating', 'repo'), isQuickChat: constObservable(false) }; + hydrating.workspace.set(undefined, undefined); + const sessions = [quickChat, hydrating]; + const changes = disposables.add(new Emitter<ISessionChangeEvent>()); + const filter = disposables.add(new SessionsListingScopeFilter({ folders: constObservable([URI.file('/home/user/projects/repo')]), repositories: constObservable([]) }, () => sessions, changes.event)); + const ids = (list: readonly ISession[]) => list.map(session => session.sessionId).sort().join(','); + const events: string[] = []; + disposables.add(filter.onDidChangeSessions(e => events.push(`added=${ids(e.added)} removed=${ids(e.removed)} changed=${ids(e.changed)}`))); + const listed: string[] = [ids(filter.getSessions())]; + + // The hydrating session's workspace arrives, in the scope + hydrating.workspace.set(buildTestWorkspace('repo'), undefined); + listed.push(ids(filter.getSessions())); + // The quick chat stops being one, without a workspace in the scope + quickChatFlag.set(false, undefined); + listed.push(ids(filter.getSessions())); + + assert.deepStrictEqual({ listed, events }, { + listed: ['quickChat', 'hydrating,quickChat', 'hydrating'], + events: [ + 'added=hydrating removed= changed=', + 'added= removed= changed=quickChat', + ], + }); + }); + + test('reports changes of sessions only for those it lists, without matching the sessions to the scope again', () => { + const here = createSession('here', 'repo'); + const elsewhere = createSession('elsewhere', 'other'); + const changes = disposables.add(new Emitter<ISessionChangeEvent>()); + let reads = 0; + const filter = disposables.add(new SessionsListingScopeFilter({ folders: constObservable([URI.file('/home/user/projects/repo')]), repositories: constObservable([]) }, () => { reads++; return [here, elsewhere]; }, changes.event)); + const events: string[] = []; + disposables.add(filter.onDidChangeSessions(e => events.push(`added=${e.added.length} removed=${e.removed.length} changed=${e.changed.map(session => session.sessionId).join(',')}`))); + const initialReads = reads; + + // Such as of the sessions' status as they stream + changes.fire({ added: [], removed: [], changed: [here, elsewhere] }); + changes.fire({ added: [], removed: [], changed: [elsewhere] }); + const afterChanges = reads - initialReads; + // A change of what the provider lists, such as as it hides another agent's sessions, matches them again + changes.fire({ added: [], removed: [], changed: [] }); + + assert.deepStrictEqual({ afterChanges, afterRequery: reads - initialReads, events }, { + afterChanges: 0, + afterRequery: 1, + events: ['added=0 removed=0 changed=here'], + }); + }); + + test('lists the sessions on GitHub of the repositories of the folders\' origin, on any branch, and every session in an empty window', () => { + const onGitHub = (id: string, path: string) => { + const root = URI.from({ scheme: GITHUB_REMOTE_FILE_SCHEME, authority: 'github', path }); + return { ...buildTestSession({ id, title: id }).session, workspace: constObservable<ISessionWorkspace | undefined>({ ...buildTestWorkspace(id), folders: [{ root, workingDirectory: root, name: id, description: undefined, gitRepository: undefined }] }) }; + }; + const sessions = [onGitHub('main', '/Microsoft/VSCode/HEAD'), onGitHub('branch', '/microsoft/vscode/feature%2Fx'), onGitHub('other', '/microsoft/vscode-tools/HEAD'), createSession('local', 'repo')]; + const folders = observableValue<readonly URI[]>('folders', [URI.file('/home/user/projects/elsewhere')]); + const filter = disposables.add(new SessionsListingScopeFilter({ folders, repositories: constObservable([]), gitHubRepositories: constObservable(['microsoft/vscode']) }, () => sessions, Event.None)); + const listed = () => filter.getSessions().map(session => session.sessionId).sort(); + const scoped = listed(); + folders.set([], undefined); + + assert.deepStrictEqual({ scoped, emptyWindow: listed() }, { + scoped: ['branch', 'main'], + emptyWindow: ['branch', 'local', 'main', 'other'], + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionsListModelService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionsListModelService.test.ts index 479f3524c133..786e8f7828ed 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/sessionsListModelService.test.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionsListModelService.test.ts @@ -140,12 +140,84 @@ suite('SessionsListModelService', () => { assert.deepStrictEqual( { id: icon.id, color: icon.color?.id }, - { id: Codicon.reportQuestion.id, color: 'list.warningForeground' }, + { id: Codicon.reportQuestion.id, color: 'agentSessionNeedsInput.foreground' }, ); }); // -- Inbox -- + test('historical unread completions only bypass the cutoff when modified today locally', () => runWithFakedTimers({ startTime: new Date(2026, 0, 1, 12).getTime() }, async () => { + const cases = [ + { id: 'yesterday-unread', updatedAt: new Date(2025, 11, 31, 23, 59, 59, 999), isRead: false, historical: true }, + { id: 'midnight-unread', updatedAt: new Date(2026, 0, 1), isRead: false, historical: true }, + { id: 'today-unread', updatedAt: new Date(2026, 0, 1, 11), isRead: false, historical: true }, + { id: 'today-read', updatedAt: new Date(2026, 0, 1, 11), isRead: true, historical: true }, + { id: 'last-month-unread', updatedAt: new Date(2025, 11, 1, 11), isRead: false, historical: true }, + { id: 'last-year-unread', updatedAt: new Date(2025, 0, 1, 11), isRead: false, historical: true }, + { id: 'after-cutoff-yesterday', updatedAt: new Date(2025, 11, 31, 23), isRead: false, historical: false }, + ]; + sessions.push(...cases.map(({ id, updatedAt, isRead }) => ({ + ...createSession(id, SessionStatus.Completed, { updatedAt }), + isRead: constObservable(isRead), + lastTurnEnd: constObservable(new Date(2025, 11, 31)), + }))); + attention.set(new Map(cases.map(({ id, historical }) => [id, { + tab: InboxTab.ReadyForYou, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: historical, + }])), undefined); + assert.deepStrictEqual(sessions.map(session => [session.sessionId, service.getInboxState(session)?.kind]), [ + ['yesterday-unread', 'done'], + ['midnight-unread', undefined], + ['today-unread', undefined], + ['today-read', 'done'], + ['last-month-unread', 'done'], + ['last-year-unread', 'done'], + ['after-cutoff-yesterday', undefined], + ]); + })); + + test('historical unread completions react to modification and read changes across reload', () => runWithFakedTimers({ startTime: new Date(2026, 0, 1, 12).getTime() }, async () => { + const isRead = observableValue('historicalRead', false); + const updatedAt = observableValue('historicalUpdatedAt', new Date(2025, 11, 31, 23)); + const session = { ...createSession('historical'), isRead, updatedAt }; + sessions.push(session); + attention.set(new Map([[session.sessionId, { + tab: InboxTab.ReadyForYou, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: true, + }]]), undefined); + const states: (string | undefined)[] = []; + const observer = disposables.add(autorun(reader => states.push(service.getInboxState(session, reader)?.kind))); + updatedAt.set(new Date(2026, 0, 1, 11), undefined); + isRead.set(true, undefined); + isRead.set(false, undefined); + observer.dispose(); + service.dispose(); + service = disposables.add(instantiationService.createInstance(SessionsListModelService)); + assert.deepStrictEqual({ states, restored: service.getInboxState(session)?.kind }, { + states: ['done', undefined, 'done', undefined], restored: undefined, + }); + })); + + test('explicit triage of historical unread completions survives reload', () => { + sessions.push(...['dismissed', 'held', 'timed', 'untilActivity'].map(id => ({ + ...createSession(id), isRead: constObservable(false), + }))); + attention.set(new Map(sessions.map(session => [session.sessionId, { + tab: InboxTab.ReadyForYou, priority: InboxNotificationPriority.Later, notificationIds: [], isHistoricalCompletion: true, + }])), undefined); + const undoDismiss = service.setInboxState([sessions[0]], 'done'); + const dismissed = service.getInboxState(sessions[0])?.kind; + undoDismiss(); + const undone = service.getInboxState(sessions[0])?.kind; + service.setInboxState([sessions[0]], 'done'); + service.setInboxState([sessions[1]], 'hold'); + service.setInboxState([sessions[2]], Date.now() + 60_000); + service.setInboxState([sessions[3]], 'untilActivity'); + service.dispose(); + service = disposables.add(instantiationService.createInstance(SessionsListModelService)); + assert.deepStrictEqual({ dismissed, undone, restored: sessions.map(session => service.getInboxState(session)?.kind) }, { + dismissed: 'done', undone: undefined, restored: ['done', 'hold', 'snoozed', 'untilActivity'], + }); + }); + test('historical completions start Done while Return to Inbox persists and remains undoable', () => { const session = createSession('historical'); sessions.push(session); diff --git a/src/vs/workbench/contrib/sessions/test/browser/sessionsServiceNavigationService.test.ts b/src/vs/workbench/contrib/sessions/test/browser/sessionsServiceNavigationService.test.ts new file mode 100644 index 000000000000..d759b4fd3d34 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/sessionsServiceNavigationService.test.ts @@ -0,0 +1,93 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { constObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ISessionGridPane } from '../../../../services/sessions/browser/sessionGridPane.js'; +import { ISessionHost } from '../../../../services/sessions/browser/sessionHost.js'; +import { ISessionsPartService, ISessionView } from '../../../../services/sessions/browser/sessionsPartService.js'; +import { IChat, ISession } from '../../../../services/sessions/common/session.js'; +import { SessionsServiceNavigationService } from '../../browser/sessionsServiceNavigationService.js'; +import { ISessionsService } from '../../browser/sessionsService.js'; + +suite('SessionsServiceNavigationService', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + const session = upcastPartial<ISession>({ sessionId: 'a', resource: URI.parse('session:/a') }); + const other = upcastPartial<ISession>({ sessionId: 'b', resource: URI.parse('session:/b') }); + const chat = upcastPartial<IChat>({ resource: URI.parse('chat:/a/side') }); + + /** The navigation over a sessions service that records what it is asked, with the grid's active pane showing `active` and its open chats. */ + function create(active?: { readonly session: ISession; readonly openChats: readonly IChat[] }) { + const calls: unknown[][] = []; + const record = (name: string) => async (...args: unknown[]) => { calls.push([name, ...args]); }; + const gridHost = upcastPartial<ISessionHost>({}); + const slotPanes = constObservable<readonly ISessionGridPane[]>([]); + const sessionsService = upcastPartial<ISessionsService>({ + gridHost, + slotPanes, + openSession: record('openSession'), + openSessionToSide: record('openSessionToSide'), + openChat: record('openChat'), + openChatToSide: record('openChatToSide'), + canOpenSession: async candidate => { calls.push(['canOpenSession', candidate]); return candidate === session; }, + focusActiveSession: () => { calls.push(['focusActiveSession']); }, + closeChat: record('closeChat'), + }); + const pane = active && upcastPartial<ISessionGridPane>({ session: constObservable(active.session), tabs: upcastPartial<ISessionGridPane['tabs']>({ openChats: constObservable(active.openChats) }) }); + const sessionsPartService = upcastPartial<ISessionsPartService>({ getActiveSessionView: () => pane && upcastPartial<ISessionView>({ pane: constObservable(pane) }) }); + return { host: new SessionsServiceNavigationService(sessionsService, sessionsPartService), calls, gridHost, slotPanes }; + } + + test('forwards every navigation to the sessions service of the Agents window as is', async () => { + const { host, calls, gridHost, slotPanes } = create(); + const options = { preserveFocus: true }; + + await host.openSession(session.resource, options); + await host.openSessionToSide(session, options); + await host.openChat(session, chat.resource, options); + await host.openChatToSide(session, chat.resource, options); + const canOpen = [await host.canOpenSession(session), await host.canOpenSession(other)]; + host.focusActiveSession(); + + assert.deepStrictEqual({ mainWindowHost: host.mainWindowHost === gridHost, slotPanes: host.slotPanes === slotPanes, canOpen, calls }, { + mainWindowHost: true, + slotPanes: true, + canOpen: [true, false], + calls: [ + ['openSession', session.resource, options], + ['openSessionToSide', session, options], + ['openChat', session, chat.resource, options], + ['openChatToSide', session, chat.resource, options], + ['canOpenSession', session], + ['canOpenSession', other], + ['focusActiveSession'], + ], + }); + }); + + test('closes an archived chat only where the grid\'s active pane shows it as an open chat of its session', async () => { + const closed = async (active: { readonly session: ISession; readonly openChats: readonly IChat[] } | undefined) => { + const { host, calls } = create(active); + await host.closeArchivedChat(session, chat); + return calls; + }; + + assert.deepStrictEqual({ + shown: await closed({ session, openChats: [upcastPartial<IChat>({ resource: chat.resource })] }), + notOpen: await closed({ session, openChats: [] }), + otherSession: await closed({ session: other, openChats: [chat] }), + noPane: await closed(undefined), + }, { + shown: [['closeChat', session, { resource: chat.resource }]], + notOpen: [], + otherSession: [], + noPane: [], + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/workspaceFolderRepositories.test.ts b/src/vs/workbench/contrib/sessions/test/browser/workspaceFolderRepositories.test.ts new file mode 100644 index 000000000000..c62b5c337e79 --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/browser/workspaceFolderRepositories.test.ts @@ -0,0 +1,265 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStatWithMetadata } from '../../../../../platform/files/common/files.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { IWorkspace, IWorkspaceContextService, IWorkspaceFolder, IWorkspaceFoldersChangeEvent } from '../../../../../platform/workspace/common/workspace.js'; +import { WorkspaceFolderRepositories } from '../../browser/workspaceFolderRepositories.js'; +import { parseGitHubRepositoryFromGitConfig } from '../../browser/gitHubRepositoryResolver.js'; + +suite('WorkspaceFolderRepositories', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + /** A file service over `.git` entries: a string is the content of a `.git` file, `true` a `.git` directory, `false` one that cannot be read. */ + function createFileService(entries: Record<string, string | boolean>) { + const reads: string[] = []; + const fileService = upcastPartial<IFileService>({ + stat: async (resource: URI) => { + reads.push(resource.path); + const entry = entries[resource.path]; + if (entry === false) { + throw new FileOperationError('permission denied', FileOperationResult.FILE_PERMISSION_DENIED); + } + if (entry === undefined) { + throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); + } + return upcastPartial<IFileStatWithMetadata>({ isDirectory: entry === true }); + }, + readFile: async (resource: URI) => upcastPartial<IFileContent>({ value: VSBuffer.fromString(String(entries[resource.path])) }), + }); + return { fileService, reads }; + } + + /** The scope of a window with `folders` over the `.git` entries of {@link createFileService}, once its reads settle. */ + async function readScope(entries: Record<string, string | boolean>, folders: readonly string[]) { + const { fileService } = createFileService(entries); + const warnings: string[] = []; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(ILogService, upcastPartial<ILogService>({ warn: (message: string) => { warnings.push(message); } })); + instantiationService.stub(IWorkspaceContextService, upcastPartial<IWorkspaceContextService>({ + onDidChangeWorkspaceFolders: store.add(new Emitter<IWorkspaceFoldersChangeEvent>()).event, + getWorkspace: () => upcastPartial<IWorkspace>({ folders: folders.map(folder => upcastPartial<IWorkspaceFolder>({ uri: URI.file(folder) })) }), + })); + const scope = store.add(instantiationService.createInstance(WorkspaceFolderRepositories)); + await timeout(0); + return { repositories: scope.repositories.get().map(uri => uri.path), gitHubRepositories: scope.gitHubRepositories.get(), warnings: warnings.length }; + } + + test('reads the repository of a checkout, of a worktree and of no checkout', async () => { + const entries = { + '/work/vscode/.git': true, + '/work/owners/scope/.git': 'gitdir: /work/vscode/.git/worktrees/scope\n', + '/work/relative/.git': 'gitdir: ../vscode/.git/worktrees/relative', + '/work/submodule/.git': 'gitdir: ../vscode/.git/modules/submodule', + '/work/denied/.git': false, + }; + const read = async (folder: string) => { + const { repositories, warnings } = await readScope(entries, [folder]); + return warnings ? 'failed' : repositories[0]; + }; + + assert.deepStrictEqual({ + checkout: await read('/work/vscode'), + worktree: await read('/work/owners/scope'), + relativeWorktree: await read('/work/relative'), + submodule: await read('/work/submodule'), + plain: await read('/work/plain'), + denied: await read('/work/denied'), + }, { + checkout: '/work/vscode', + worktree: '/work/vscode', + relativeWorktree: '/work/vscode', + submodule: undefined, + plain: undefined, + denied: 'failed', + }); + }); + + test('reads each folder once as it joins, drops a folder as it leaves, and reads again after a failure', async () => { + const entries: Record<string, string | boolean> = { + '/work/vscode/.git': true, + '/work/owners/scope/.git': 'gitdir: /work/vscode/.git/worktrees/scope', + '/work/other/.git': true, + '/work/denied/.git': false, + }; + const { fileService, reads } = createFileService(entries); + const onDidChangeWorkspaceFolders = store.add(new Emitter<IWorkspaceFoldersChangeEvent>()); + let folders = [URI.file('/work/owners/scope'), URI.file('/work/plain'), URI.file('/work/denied'), URI.parse('vscode-remote://host/work/remote')]; + const warnings: string[] = []; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(ILogService, upcastPartial<ILogService>({ warn: (message: string) => { warnings.push(message); } })); + instantiationService.stub(IWorkspaceContextService, upcastPartial<IWorkspaceContextService>({ + onDidChangeWorkspaceFolders: onDidChangeWorkspaceFolders.event, + getWorkspace: () => upcastPartial<IWorkspace>({ folders: folders.map(uri => upcastPartial<IWorkspaceFolder>({ uri })) }), + })); + const repositories = store.add(instantiationService.createInstance(WorkspaceFolderRepositories)); + const settled = () => timeout(0); + const changeFolders = (next: URI[]) => { + folders = next; + onDidChangeWorkspaceFolders.fire({ added: [], removed: [], changed: [] }); + }; + const snapshot = () => ({ repositories: repositories.repositories.get().map(uri => uri.path), reads: reads.length, warnings: warnings.length }); + + await settled(); + const initial = snapshot(); + entries['/work/denied/.git'] = true; + changeFolders([...folders, URI.file('/work/other')]); + await settled(); + const added = snapshot(); + changeFolders(folders.filter(folder => folder.path !== '/work/owners/scope')); + const removedAtOnce = snapshot(); + + assert.deepStrictEqual({ initial, added, removedAtOnce }, { + // The scope worktree names its main checkout; the plain folder has no `.git`; the denied one is logged. + initial: { repositories: ['/work/vscode'], reads: 3, warnings: 1 }, + // Only the folder that joined and the one that failed are read again. + added: { repositories: ['/work/vscode', '/work/denied', '/work/other'], reads: 5, warnings: 1 }, + removedAtOnce: { repositories: ['/work/denied', '/work/other'], reads: 5, warnings: 1 }, + }); + }); + + test('parses the GitHub repository of the origin remote', async () => { + const gitHubOf = async (config: string) => (await readScope({ '/work/repo/.git': true, '/work/repo/.git/config': config }, ['/work/repo'])).gitHubRepositories[0]; + const origin = (url: string, remote = 'origin', headerComment = '') => gitHubOf(`[core]\n\tbare = false\n[remote "${remote}"]${headerComment}\n\turl = ${url}\n\tfetch = +refs/heads/*:refs/remotes/${remote}/*\n`); + assert.deepStrictEqual({ + https: await origin('https://github.com/Microsoft/VSCode.git'), + httpsWithoutSuffix: await origin('https://github.com/microsoft/vscode'), + httpsWithUser: await origin('https://user@github.com/microsoft/vscode.git'), + scp: await origin('git@github.com:microsoft/vscode.git'), + ssh: await origin('ssh://git@github.com/microsoft/vscode'), + quoted: await origin('"https://github.com/microsoft/vscode.git"'), + comment: await origin('https://github.com/microsoft/vscode.git # the main repository'), + quotedWithComment: await origin('"git@github.com:microsoft/vscode.git" ; a comment'), + headerHashComment: await origin('https://github.com/microsoft/vscode.git', 'origin', ' # the main repository'), + headerSemicolonComment: await origin('https://github.com/microsoft/vscode.git', 'origin', '; the main repository'), + // Only origin's URL counts, also with comments on both headers + originAfterCommentedUpstream: await gitHubOf('[remote "upstream"] # x\n\turl = https://github.com/other/upstream.git\n[remote "origin"] ; y\n\turl = git@github.com:microsoft/vscode.git\n'), + commentedUpstreamOnly: await gitHubOf('[remote "upstream"] # x\n\turl = https://github.com/other/upstream.git\n'), + // The other callers of the shared parser read headers exactly as before + otherCallersHeaderComment: parseGitHubRepositoryFromGitConfig('[remote "origin"] # comment\n\turl = https://github.com/microsoft/vscode.git\n'), + otherHost: await origin('https://gitlab.com/microsoft/vscode.git'), + otherRemote: await origin('https://github.com/microsoft/vscode.git', 'upstream'), + }, { + https: 'microsoft/vscode', + httpsWithoutSuffix: 'microsoft/vscode', + httpsWithUser: 'microsoft/vscode', + scp: 'microsoft/vscode', + ssh: 'microsoft/vscode', + quoted: 'microsoft/vscode', + comment: 'microsoft/vscode', + quotedWithComment: 'microsoft/vscode', + headerHashComment: 'microsoft/vscode', + headerSemicolonComment: 'microsoft/vscode', + originAfterCommentedUpstream: 'microsoft/vscode', + commentedUpstreamOnly: undefined, + otherCallersHeaderComment: undefined, + otherHost: undefined, + otherRemote: undefined, + }); + }); + + test('reads the GitHub origin of each folder\'s repository, of a worktree\'s from its main checkout, once, and again after a failure', async () => { + const config = (url: string) => `[remote "origin"]\n\turl = ${url}\n`; + const files: Record<string, string | boolean> = { + '/work/vscode/.git': true, + '/work/vscode/.git/config': config('git@github.com:microsoft/vscode.git'), + '/work/owners/scope/.git': 'gitdir: /work/vscode/.git/worktrees/scope', + '/work/tools/.git': true, + '/work/tools/.git/config': false, + '/work/local/.git': true, + }; + const reads: string[] = []; + const read = (resource: URI) => { + reads.push(resource.path); + const entry = files[resource.path]; + if (entry === false) { + throw new FileOperationError('permission denied', FileOperationResult.FILE_PERMISSION_DENIED); + } + if (entry === undefined) { + throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); + } + return entry; + }; + const fileService = upcastPartial<IFileService>({ + stat: async (resource: URI) => upcastPartial<IFileStatWithMetadata>({ isDirectory: read(resource) === true }), + readFile: async (resource: URI) => upcastPartial<IFileContent>({ value: VSBuffer.fromString(String(read(resource))) }), + }); + const onDidChangeWorkspaceFolders = store.add(new Emitter<IWorkspaceFoldersChangeEvent>()); + const folders = [URI.file('/work/owners/scope'), URI.file('/work/tools'), URI.file('/work/local')]; + const warnings: string[] = []; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(ILogService, upcastPartial<ILogService>({ warn: (message: string) => { warnings.push(message); } })); + instantiationService.stub(IWorkspaceContextService, upcastPartial<IWorkspaceContextService>({ + onDidChangeWorkspaceFolders: onDidChangeWorkspaceFolders.event, + getWorkspace: () => upcastPartial<IWorkspace>({ folders: folders.map(uri => upcastPartial<IWorkspaceFolder>({ uri })) }), + })); + const scope = store.add(instantiationService.createInstance(WorkspaceFolderRepositories)); + const settled = () => timeout(0); + const snapshot = () => ({ repositories: scope.repositories.get().map(uri => uri.path), gitHub: scope.gitHubRepositories.get(), configReads: reads.filter(path => path.endsWith('/config')).sort(), warnings: warnings.length }); + + await settled(); + const initial = snapshot(); + files['/work/tools/.git/config'] = config('https://github.com/microsoft/vscode-tools'); + onDidChangeWorkspaceFolders.fire({ added: [], removed: [], changed: [] }); + await settled(); + + assert.deepStrictEqual({ initial, afterChange: snapshot() }, { + // The worktree reads its main checkout's config; a missing config is no GitHub repository; a failed read is logged + initial: { repositories: ['/work/vscode', '/work/tools', '/work/local'], gitHub: ['microsoft/vscode'], configReads: ['/work/local/.git/config', '/work/tools/.git/config', '/work/vscode/.git/config'], warnings: 1 }, + // Only the config that failed is read again + afterChange: { repositories: ['/work/vscode', '/work/tools', '/work/local'], gitHub: ['microsoft/vscode', 'microsoft/vscode-tools'], configReads: ['/work/local/.git/config', '/work/tools/.git/config', '/work/tools/.git/config', '/work/vscode/.git/config'], warnings: 1 }, + }); + }); + + test('drops a replaced folder\'s repository before the read of the folder replacing it settles', async () => { + const readOfB = new DeferredPromise<void>(); + const fileService = upcastPartial<IFileService>({ + stat: async (resource: URI) => { + if (resource.path === '/work/b/.git') { + await readOfB.p; + } + return upcastPartial<IFileStatWithMetadata>({ isDirectory: true }); + }, + }); + const onDidChangeWorkspaceFolders = store.add(new Emitter<IWorkspaceFoldersChangeEvent>()); + let folders = [URI.file('/work/a')]; + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(ILogService, upcastPartial<ILogService>({ warn: () => { } })); + instantiationService.stub(IWorkspaceContextService, upcastPartial<IWorkspaceContextService>({ + onDidChangeWorkspaceFolders: onDidChangeWorkspaceFolders.event, + getWorkspace: () => upcastPartial<IWorkspace>({ folders: folders.map(uri => upcastPartial<IWorkspaceFolder>({ uri })) }), + })); + const repositories = store.add(instantiationService.createInstance(WorkspaceFolderRepositories)); + const settled = () => timeout(0); + const published = () => repositories.repositories.get().map(uri => uri.path); + + await settled(); + const beforeReplace = published(); + folders = [URI.file('/work/b')]; + onDidChangeWorkspaceFolders.fire({ added: [], removed: [], changed: [] }); + await settled(); + const whileBIsRead = published(); + readOfB.complete(); + await settled(); + + assert.deepStrictEqual({ beforeReplace, whileBIsRead, afterBIsRead: published() }, { + beforeReplace: ['/work/a'], + whileBIsRead: [], + afterBIsRead: ['/work/b'], + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/test/browser/worktreeSuggestion/worktreeSuggestionTestUtils.ts b/src/vs/workbench/contrib/sessions/test/browser/worktreeSuggestion/worktreeSuggestionTestUtils.ts index eb2b22b24373..87b45c92fa6e 100644 --- a/src/vs/workbench/contrib/sessions/test/browser/worktreeSuggestion/worktreeSuggestionTestUtils.ts +++ b/src/vs/workbench/contrib/sessions/test/browser/worktreeSuggestion/worktreeSuggestionTestUtils.ts @@ -38,6 +38,8 @@ export class TestWorktreeSuggestionService extends mock<IWorktreeSuggestionServi /** What the user chooses in the next spotlight, or `undefined` when it cannot show. */ spotlightChoice: WorktreeSpotlightChoice | undefined; private readonly _hintClosed = observableValue('hintClosed', false); + /** Whether the user started a session in a new worktree. */ + readonly worktreeSessionCreated = observableValue('worktreeSessionCreated', false); private readonly _declined = observableValue<ReadonlySet<string>>('declined', new Set()); private readonly _changes: ISettableObservable<readonly ISessionFileChange[] | undefined>; @@ -105,6 +107,9 @@ export class TestWorktreeSuggestionService extends mock<IWorktreeSuggestionServi this.calls.push('hintClosed'); this._hintClosed.set(true, undefined); } + override hasCreatedWorktreeSession(reader: IReader | undefined): boolean { + return this.worktreeSessionCreated.read(reader); + } override canShowSpotlight(): boolean { return this.spotlightAvailable; } diff --git a/src/vs/workbench/contrib/sessions/test/common/scheduledChatRequest.test.ts b/src/vs/workbench/contrib/sessions/test/common/scheduledChatRequest.test.ts new file mode 100644 index 000000000000..11175819159f --- /dev/null +++ b/src/vs/workbench/contrib/sessions/test/common/scheduledChatRequest.test.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { decodeBase64, VSBuffer } from '../../../../../base/common/buffer.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { Range } from '../../../../../editor/common/core/range.js'; +import { MessageAttachmentKind } from '../../../../../platform/agentHost/common/state/protocol/state.js'; +import { captureScheduledChatRequest, parseScheduledChatTime } from '../../common/scheduledChatRequest.js'; + +suite('Scheduled chat request', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('captures selections and image bytes while retaining normal file reference semantics and mention ranges', async () => { + const uri = URI.file('/workspace/a.ts'); + const reads: string[] = []; + const message = await captureScheduledChatRequest({ + inputText: 'Review #a', + attachments: [ + { kind: 'file', id: 'selection', name: 'selection', value: { uri, range: new Range(2, 1, 3, 1) } }, + { kind: 'file', id: 'file', name: 'a.ts', value: uri, range: { start: 7, endExclusive: 9 } }, + { kind: 'image', id: 'image', name: 'screenshot', value: new Uint8Array([1, 2, 3]), mimeType: 'image/png' }, + ], + }, async (resource, range) => { + reads.push(`${resource.path}:${range?.startLineNumber}`); + return 'captured selection'; + }, async () => { throw new Error('Unexpected image file read'); }); + assert.deepStrictEqual({ + text: message.text, + reads, + attachments: message.attachments?.map(attachment => ({ + type: attachment.type, + content: attachment.type === MessageAttachmentKind.EmbeddedResource ? [...decodeBase64(attachment.data).buffer] : attachment.type === MessageAttachmentKind.Resource ? attachment.uri : undefined, + range: attachment.range, + })), + }, { + text: 'Review #a', + reads: ['/workspace/a.ts:2'], + attachments: [ + { type: MessageAttachmentKind.EmbeddedResource, content: [...VSBuffer.fromString('captured selection').buffer], range: undefined }, + { type: MessageAttachmentKind.Resource, content: uri.toString(), range: { start: { line: 0, character: 7 }, end: { line: 0, character: 9 } } }, + { type: MessageAttachmentKind.EmbeddedResource, content: [1, 2, 3], range: undefined }, + ], + }); + }); + + test('captures dirty files and untitled buffers instead of retaining unresolvable or stale references', async () => { + const dirty = URI.file('/workspace/dirty.ts'); + const untitled = URI.parse('untitled:Untitled-1'); + const message = await captureScheduledChatRequest({ + inputText: 'review', attachments: [dirty, untitled].map((value, i) => ({ kind: 'file', id: String(i), name: value.path, value })), + }, async uri => uri.toString() === dirty.toString() ? 'unsaved changes' : 'new buffer', async () => { throw new Error('Unexpected disk read'); }, uri => uri.toString() === dirty.toString()); + assert.deepStrictEqual(message.attachments?.map(attachment => attachment.type === MessageAttachmentKind.EmbeddedResource ? decodeBase64(attachment.data).toString() : attachment.type), ['unsaved changes', 'new buffer']); + }); + + test('refuses remote and unsupported context rather than silently dropping attachments', async () => { + const readSelection = async () => ''; + const readFile = async () => VSBuffer.alloc(0); + await assert.rejects(() => captureScheduledChatRequest({ + inputText: 'review', attachments: [{ kind: 'file', id: 'remote', name: 'remote.ts', value: URI.parse('vscode-remote://host/path') }], + }, readSelection, readFile), /attachments on this device/); + await assert.rejects(() => captureScheduledChatRequest({ + inputText: 'review', attachments: [{ kind: 'tool', id: 'tool', name: 'tool', value: undefined }], + }, readSelection, readFile), /cannot be saved for later/); + }); + + test('parses local calendar values without rolling invalid dates or accepting ambiguous text', () => { + const valid = parseScheduledChatTime('2030-07-14 09:30'); + assert.deepStrictEqual({ + valid: valid && [valid.getFullYear(), valid.getMonth() + 1, valid.getDate(), valid.getHours(), valid.getMinutes()], + invalid: ['2030-02-30 09:30', '2030-13-01 09:30', '2030-01-01 24:00', 'tomorrow', '2030-01-01T09:30Z'].map(parseScheduledChatTime), + }, { valid: [2030, 7, 14, 9, 30], invalid: [undefined, undefined, undefined, undefined, undefined] }); + }); +}); diff --git a/src/vs/workbench/contrib/splash/browser/partsSplash.ts b/src/vs/workbench/contrib/splash/browser/partsSplash.ts index 43cd923deb6e..0a9ecfa8b307 100644 --- a/src/vs/workbench/contrib/splash/browser/partsSplash.ts +++ b/src/vs/workbench/contrib/splash/browser/partsSplash.ts @@ -23,6 +23,8 @@ import { mainWindow } from '../../../../base/browser/window.js'; import { ILifecycleService, LifecyclePhase } from '../../../services/lifecycle/common/lifecycle.js'; import { TitleBarSetting } from '../../../../platform/window/common/window.js'; import { IWorkbenchThemeService } from '../../../services/themes/common/workbenchThemeService.js'; +import { ISizeService } from '../../../../platform/theme/common/sizeService.js'; +import { activityBarCornerRadius, secondarySideBarCornerRadius, editorAreaCornerRadius, toolsPanelCornerRadius, primarySideBarCornerRadius } from '../../../../platform/theme/common/sizeRegistry.js'; export class PartsSplash { @@ -42,6 +44,7 @@ export class PartsSplash { @ISplashStorageService private readonly _partSplashService: ISplashStorageService, @IEditorGroupsService editorGroupsService: IEditorGroupsService, @ILifecycleService lifecycleService: ILifecycleService, + @ISizeService private readonly _sizeService: ISizeService, ) { Event.once(_layoutService.onDidLayoutMainContainer)(() => { this._removePartsSplash(); @@ -53,7 +56,7 @@ export class PartsSplash { lastIdleSchedule.value = dom.runWhenWindowIdle(mainWindow, () => this._savePartsSplash(), 2500); }; lifecycleService.when(LifecyclePhase.Restored).then(() => { - Event.any(Event.filter(onDidChangeFullscreen, windowId => windowId === mainWindow.vscodeWindowId), editorGroupsService.mainPart.onDidLayout, _themeService.onDidColorThemeChange)(savePartsSplashSoon, undefined, this._disposables); + Event.any(Event.filter(onDidChangeFullscreen, windowId => windowId === mainWindow.vscodeWindowId), editorGroupsService.mainPart.onDidLayout, _themeService.onDidColorThemeChange, _sizeService.onDidChangeSizes)(savePartsSplashSoon, undefined, this._disposables); savePartsSplashSoon(); }); @@ -119,6 +122,7 @@ export class PartsSplash { windowBorderRadius: this._layoutService.getMainWindowBorderRadius(), modernUI: this._layoutService.isFloatingPanelsEnabled(), modernUICompact: this._layoutService.isModernUICompact(), + panelSpacing: this._layoutService.getPanelSpacing(), partBounds: this._layoutService.isFloatingPanelsEnabled() ? { activityBar: this._getPartBounds(Parts.ACTIVITYBAR_PART), sideBar: this._getPartBounds(Parts.SIDEBAR_PART), @@ -143,11 +147,19 @@ export class PartsSplash { const position = dom.getDomNodePagePosition(container); const classPrefix = part === Parts.EDITOR_PART ? 'floating-editor' : 'floating-part'; const activityBarOnLeft = this._layoutService.getSideBarPosition() === Position.LEFT; + const radiusToken = { + [Parts.ACTIVITYBAR_PART]: activityBarCornerRadius, + [Parts.SIDEBAR_PART]: primarySideBarCornerRadius, + [Parts.AUXILIARYBAR_PART]: secondarySideBarCornerRadius, + [Parts.PANEL_PART]: toolsPanelCornerRadius, + [Parts.EDITOR_PART]: editorAreaCornerRadius, + }[part]; return { top: position.top, left: position.left, width: position.width, height: position.height, + cornerRadius: this._sizeService.getSize(radiusToken, this._themeService.getColorTheme())?.value, outerEdges: part === Parts.ACTIVITYBAR_PART ? { left: activityBarOnLeft, right: !activityBarOnLeft, @@ -167,14 +179,14 @@ export class PartsSplash { } private _removePartsSplash(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.getElementById(PartsSplash._splashElementId); if (element) { element.style.display = 'none'; } // remove initial colors - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const defaultStyles = mainWindow.document.head.getElementsByClassName('initialShellColors'); defaultStyles[0]?.remove(); } diff --git a/src/vs/workbench/contrib/tasks/browser/abstractTaskService.ts b/src/vs/workbench/contrib/tasks/browser/abstractTaskService.ts index e4b99d90fe44..896da8d5ba18 100644 --- a/src/vs/workbench/contrib/tasks/browser/abstractTaskService.ts +++ b/src/vs/workbench/contrib/tasks/browser/abstractTaskService.ts @@ -50,7 +50,7 @@ import { ITerminalProfileResolverService } from '../../terminal/common/terminal. import { CommandString, ConfiguringTask, ContributedTask, CustomTask, ExecutionEngine, InMemoryTask, InstancePolicy, ITaskConfig, ITaskEvent, ITaskIdentifier, ITaskInactiveEvent, ITaskProcessEndedEvent, ITaskSet, JsonSchemaVersion, KeyedTaskIdentifier, RerunAllRunningTasksCommandId, RuntimeType, Task, TASK_RUNNING_STATE, TaskDefinition, TaskEventKind, TaskGroup, TaskRunSource, TaskSettingId, TaskSorter, TaskSourceKind, TasksSchemaProperties, USER_TASKS_GROUP_KEY } from '../common/tasks.js'; import { ChatAgentLocation, ChatModeKind } from '../../chat/common/constants.js'; import { CustomExecutionSupportedContext, ICustomizationProperties, IProblemMatcherRunOptions, ITaskFilter, ITaskProvider, ITaskService, IWorkspaceFolderTaskResult, ProcessExecutionSupportedContext, ServerlessWebContext, ShellExecutionSupportedContext, TaskCommandsRegistered, TaskExecutionSupportedContext, TasksAvailableContext } from '../common/taskService.js'; -import { ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind, Triggers, VerifiedTask } from '../common/taskSystem.js'; +import { assertTaskWorkspaceTrust, ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind, Triggers, VerifiedTask } from '../common/taskSystem.js'; import { getTemplates as getTaskTemplates } from '../common/taskTemplates.js'; import * as TaskConfig from '../common/taskConfiguration.js'; @@ -2087,6 +2087,7 @@ export abstract class AbstractTaskService extends Disposable implements ITaskSer ? await this.getTask(taskFolder, taskIdentifier, false, taskType) : task) ?? task; } await ProblemMatcherRegistry.onReady(); + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); const executeResult = runSource === TaskRunSource.Reconnect ? this._getTaskSystem().reconnect(taskToRun, resolver) : this._getTaskSystem().run(taskToRun, resolver); if (executeResult) { return this._handleExecuteResult(executeResult, runSource); @@ -2289,7 +2290,8 @@ export abstract class AbstractTaskService extends Disposable implements ITaskSer } } return undefined; - } + }, + this._workspaceTrustManagementService ); } diff --git a/src/vs/workbench/contrib/tasks/browser/runAutomaticTasks.ts b/src/vs/workbench/contrib/tasks/browser/runAutomaticTasks.ts index 19bcf87e2223..55a9adb7db87 100644 --- a/src/vs/workbench/contrib/tasks/browser/runAutomaticTasks.ts +++ b/src/vs/workbench/contrib/tasks/browser/runAutomaticTasks.ts @@ -26,6 +26,7 @@ const ALLOW_AUTOMATIC_TASKS = 'task.allowAutomaticTasks'; export class RunAutomaticTasks extends Disposable implements IWorkbenchContribution { private _hasRunTasks: boolean = false; + private _trustVersion = 0; constructor( @ITaskService private readonly _taskService: ITaskService, @IConfigurationService private readonly _configurationService: IConfigurationService, @@ -36,11 +37,26 @@ export class RunAutomaticTasks extends Disposable implements IWorkbenchContribut @IOpenerService private readonly _openerService: IOpenerService) { super(); if (this._taskService.isReconnected) { - this._tryRunTasks(); + this._tryRunTasks().catch(error => this._logService.error('Automatic task execution failed', error)); } else { - this._register(Event.once(this._taskService.onDidReconnectToTasks)(async () => await this._tryRunTasks())); + this._register(Event.once(this._taskService.onDidReconnectToTasks)(() => { + this._tryRunTasks().catch(error => this._logService.error('Automatic task execution failed', error)); + })); } - this._register(this._workspaceTrustManagementService.onDidChangeTrust(async () => await this._tryRunTasks())); + this._register(this._workspaceTrustManagementService.onDidChangeTrust(trusted => { + if (!trusted) { + this._trustVersion++; + } + this._tryRunTasks().catch(error => this._logService.error('Automatic task execution failed', error)); + })); + } + + private _canRunTasks(trustVersion: number): boolean { + const canRun = !this._store.isDisposed && trustVersion === this._trustVersion && this._workspaceTrustManagementService.isWorkspaceTrusted(); + if (!canRun) { + this._logService.trace('RunAutomaticTasks: Cancelled pending automatic tasks.'); + } + return canRun; } private async _tryRunTasks() { @@ -53,16 +69,20 @@ export class RunAutomaticTasks extends Disposable implements IWorkbenchContribut return; } this._hasRunTasks = true; + const trustVersion = this._trustVersion; this._logService.trace('RunAutomaticTasks: Trying to run tasks.'); // Wait until we have task system info (the extension host and workspace folders are available). - while (!this._store.isDisposed && !this._taskService.hasTaskSystemInfo) { + while (this._canRunTasks(trustVersion) && !this._taskService.hasTaskSystemInfo) { this._logService.trace('RunAutomaticTasks: Awaiting task system info.'); await Event.toPromise(Event.filter(this._taskService.onDidChangeTaskSystemInfo, () => this._taskService.hasTaskSystemInfo), this._store); } - if (this._store.isDisposed) { + if (!this._canRunTasks(trustVersion)) { return; } let workspaceTasks = await this._taskService.getWorkspaceTasks(TaskRunSource.FolderOpen); + if (!this._canRunTasks(trustVersion)) { + return; + } this._logService.trace(`RunAutomaticTasks: Found ${workspaceTasks.size} automatic tasks`); let autoTasks = this._findAutoTasks(this._taskService, workspaceTasks); @@ -79,31 +99,32 @@ export class RunAutomaticTasks extends Disposable implements IWorkbenchContribut const timer = setTimeout(() => { clearTimeout(timer); resolve(false); }, 10000); })]); + if (!this._canRunTasks(trustVersion)) { + return; + } if (!updatedWithinTimeout) { this._logService.trace(`RunAutomaticTasks: waited some extra time, but no update of tasks configuration`); return; } workspaceTasks = await this._taskService.getWorkspaceTasks(TaskRunSource.FolderOpen); + if (!this._canRunTasks(trustVersion)) { + return; + } autoTasks = this._findAutoTasks(this._taskService, workspaceTasks); this._logService.trace(`RunAutomaticTasks: updated taskNames=${JSON.stringify(autoTasks.taskNames)}`); } - this._runWithPermission(this._taskService, this._configurationService, this._storageService, this._notificationService, this._openerService, autoTasks.tasks, autoTasks.taskNames, autoTasks.locations); + await this._runWithPermission(this._taskService, this._configurationService, this._storageService, this._notificationService, this._openerService, autoTasks.tasks, autoTasks.taskNames, autoTasks.locations, trustVersion); } - private _runTasks(taskService: ITaskService, tasks: Array<Task | Promise<Task | undefined>>) { - tasks.forEach(task => { - if (task instanceof Promise) { - task.then(promiseResult => { - if (promiseResult) { - taskService.run(promiseResult); - } - }); - } else { - taskService.run(task); + private async _runTasks(taskService: ITaskService, tasks: Array<Task | Promise<Task | undefined>>, trustVersion: number) { + await Promise.all(tasks.map(async task => { + const taskToRun = await task; + if (taskToRun && this._canRunTasks(trustVersion)) { + await taskService.run(taskToRun); } - }); + })); } private _getTaskSource(source: TaskSource): URI | undefined { @@ -161,12 +182,12 @@ export class RunAutomaticTasks extends Disposable implements IWorkbenchContribut return { tasks, taskNames, locations }; } - private async _runWithPermission(taskService: ITaskService, configurationService: IConfigurationService, storageService: IStorageService, notificationService: INotificationService, openerService: IOpenerService, tasks: (Task | Promise<Task | undefined>)[], taskNames: string[], locations: Map<string, URI>) { - if (taskNames.length === 0) { + private async _runWithPermission(taskService: ITaskService, configurationService: IConfigurationService, storageService: IStorageService, notificationService: INotificationService, openerService: IOpenerService, tasks: (Task | Promise<Task | undefined>)[], taskNames: string[], locations: Map<string, URI>, trustVersion: number) { + if (taskNames.length === 0 || !this._canRunTasks(trustVersion)) { return; } if (configurationService.getValue(ALLOW_AUTOMATIC_TASKS) === 'on') { - this._runTasks(taskService, tasks); + await this._runTasks(taskService, tasks, trustVersion); return; } const hasShownPromptForAutomaticTasks = storageService.getBoolean(HAS_PROMPTED_FOR_AUTOMATIC_TASKS, StorageScope.WORKSPACE, false); @@ -175,8 +196,8 @@ export class RunAutomaticTasks extends Disposable implements IWorkbenchContribut } // We have automatic tasks - prompt to allow. const allow = await this._showPrompt(notificationService, storageService, openerService, configurationService, taskNames, locations); - if (allow) { - this._runTasks(taskService, tasks); + if (allow && this._canRunTasks(trustVersion)) { + await this._runTasks(taskService, tasks, trustVersion); } } diff --git a/src/vs/workbench/contrib/tasks/browser/taskTerminalStatus.ts b/src/vs/workbench/contrib/tasks/browser/taskTerminalStatus.ts index 9f5f923e886b..e9b6d2785c0f 100644 --- a/src/vs/workbench/contrib/tasks/browser/taskTerminalStatus.ts +++ b/src/vs/workbench/contrib/tasks/browser/taskTerminalStatus.ts @@ -38,7 +38,6 @@ const INFO_INACTIVE_TASK_STATUS: ITerminalStatus = { id: TASK_TERMINAL_STATUS_ID export class TaskTerminalStatus extends Disposable { private terminalMap: DisposableMap<number, ITerminalData> = this._register(new DisposableMap()); - private _marker: IMarker | undefined; constructor(@ITaskService taskService: ITaskService, @IAccessibilitySignalService private readonly _accessibilitySignalService: IAccessibilitySignalService) { super(); this._register(taskService.onDidStateChange((event) => { @@ -55,20 +54,21 @@ export class TaskTerminalStatus extends Disposable { const status: ITerminalStatus = { id: TASK_TERMINAL_STATUS_ID, severity: Severity.Info }; terminal.statusList.add(status); const store = new DisposableStore(); + let marker: IMarker | undefined; store.add(problemMatcher.onDidFindFirstMatch(() => { - this._marker = terminal.registerMarker(); - if (this._marker) { - store.add(this._marker); + marker = terminal.registerMarker(); + if (marker) { + store.add(marker); } })); store.add(problemMatcher.onDidFindErrors(() => { - if (this._marker) { - terminal.addBufferMarker({ marker: this._marker, hoverMessage: nls.localize('task.watchFirstError', "Beginning of detected errors for this run"), disableCommandStorage: true }); + if (marker) { + terminal.addBufferMarker({ marker, hoverMessage: nls.localize('task.watchFirstError', "Beginning of detected errors for this run"), disableCommandStorage: true }); } })); store.add(problemMatcher.onDidRequestInvalidateLastMarker(() => { - this._marker?.dispose(); - this._marker = undefined; + marker?.dispose(); + marker = undefined; })); store.add(terminal.onDisposed(() => { diff --git a/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts b/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts index 8560e38f8957..8d94e83d387d 100644 --- a/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts +++ b/src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts @@ -39,7 +39,7 @@ import { IViewsService } from '../../../services/views/common/viewsService.js'; import { TaskTerminalStatus } from './taskTerminalStatus.js'; import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from '../common/problemCollectors.js'; import { GroupKind } from '../common/taskConfiguration.js'; -import { IResolveSet, IResolvedVariables, ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskSystemInfoResolver, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind, Triggers, VerifiedTask } from '../common/taskSystem.js'; +import { assertTaskWorkspaceTrust, IResolveSet, IResolvedVariables, ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskSystemInfoResolver, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind, Triggers, VerifiedTask } from '../common/taskSystem.js'; import { CommandOptions, CommandString, ContributedTask, CustomTask, DependsOrder, ICommandConfiguration, IConfigurationProperties, IExtensionTaskSource, IPresentationOptions, IShellConfiguration, IShellQuotingOptions, ITaskEvent, InMemoryTask, PanelKind, RerunForActiveTerminalCommandId, RevealKind, RevealProblemKind, RuntimeType, ShellQuoting, TASK_TERMINAL_ACTIVE, Task, TaskEvent, TaskEventKind, TaskScope, TaskSourceKind, rerunTaskIcon } from '../common/tasks.js'; import { ITerminalGroupService, ITerminalInstance, ITerminalService } from '../../terminal/browser/terminal.js'; import { VSCodeOscProperty, VSCodeOscPt, VSCodeSequence } from '../../terminal/browser/terminalEscapeSequences.js'; @@ -54,6 +54,7 @@ import { IContextKey, IContextKeyService } from '../../../../platform/contextkey import { TaskProblemMonitor } from './taskProblemMonitor.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { serializeVSCodeOscMessage } from '../../../../platform/terminal/common/xterm/shellIntegrationAddon.js'; +import { IWorkspaceTrustManagementService } from '../../../../platform/workspace/common/workspaceTrust.js'; interface ITerminalData { terminal: ITerminalInstance; @@ -171,7 +172,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { private _previousTerminalInstance: ITerminalInstance | undefined; private _terminalStatusManager: TaskTerminalStatus; private _taskProblemMonitor: TaskProblemMonitor; - private _terminalCreationQueue: Promise<ITerminalInstance | void> = Promise.resolve(); + private readonly _terminalCreationQueue = new Async.Sequencer(); private _hasReconnected: boolean = false; private readonly _onDidStateChange: Emitter<ITaskEvent>; private _terminalTabActions = [{ id: RerunForActiveTerminalCommandId, label: nls.localize('rerunTask', 'Rerun Task'), icon: rerunTaskIcon }]; @@ -223,6 +224,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { instantiationService: IInstantiationService, taskSystemInfoResolver: ITaskSystemInfoResolver, private _taskLookup: (taskKey: string) => Promise<Task | undefined>, + private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService, ) { super(); @@ -277,6 +279,8 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { const executeResult = { kind: TaskExecuteKind.Started, task, started: {}, promise: this._executeTask(task, resolver, trigger, new Set(), new Map(), undefined) }; executeResult.promise.then(summary => { this._lastTask = this._currentTask; + }, error => { + this._logService.error('Task execution failed', error); }); return executeResult; } catch (error) { @@ -532,12 +536,14 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { // any of the code in the then runs (see #180541 and #180578). Wrapping // it in Promise.resolve().then() ensures that. const promise = Promise.resolve().then(async () => { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); alreadyResolved = alreadyResolved ?? new Map<string, string>(); const promises: Promise<ITaskSummary>[] = []; if (task.configurationProperties.dependsOn) { const nextLiveDependencies = new Set(liveDependencies).add(task.getCommonTaskId()); for (const dependency of task.configurationProperties.dependsOn) { const dependencyTask = await resolver.resolve(dependency.uri, dependency.task); + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); if (dependencyTask) { this._adoptConfigurationForDependencyTask(dependencyTask, task); @@ -568,6 +574,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { } encounteredTasks.set(commonKey, taskResult); promises.push(taskResult); + taskResult.catch(error => this._logService.error('Task dependency failed', error)); if (task.configurationProperties.dependsOrder === DependsOrder.sequence) { const promiseResult = await taskResult; if (promiseResult.exitCode !== 0) { @@ -586,6 +593,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { } return Promise.all(promises).then((summaries): Async.MaybePromise<ITaskSummary> => { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); for (const summary of summaries) { if (summary.exitCode !== 0) { return { exitCode: summary.exitCode }; @@ -620,15 +628,19 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { return promise; } - private _createInactiveDependencyPromise(task: Task): Promise<ITaskSummary> { - return new Promise<ITaskSummary>(resolve => { - const taskInactiveDisposable = this.onDidStateChange(taskEvent => { - if ((taskEvent.kind === TaskEventKind.Inactive) && (taskEvent.__task === task)) { - taskInactiveDisposable.dispose(); + private _createInactiveDependencyPromise(task: Task, execution: Promise<ITaskSummary>): Promise<ITaskSummary> { + const disposables = new DisposableStore(); + const inactivePromise = new Promise<ITaskSummary>(resolve => { + disposables.add(this.onDidStateChange(taskEvent => { + if (taskEvent.kind === TaskEventKind.End && taskEvent.__task === task) { + disposables.dispose(); + } else if (taskEvent.kind === TaskEventKind.Inactive && taskEvent.__task === task) { + disposables.dispose(); resolve({ exitCode: 0 }); } - }); + })); }); + return Promise.race([inactivePromise, execution]).finally(() => disposables.dispose()); } private _taskHasErrors(task: Task): boolean { @@ -677,7 +689,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { if (task.state === TaskEventKind.Inactive) { return { exitCode: 0 }; } - return this._createInactiveDependencyPromise(task.task); + return this._createInactiveDependencyPromise(task.task, task.promise); } private async _executeDependencyTask(task: Task, resolver: ITaskResolver, trigger: string, liveDependencies: Set<string>, encounteredTasks: Map<string, Promise<ITaskSummary>>, alreadyResolved?: Map<string, string>): Promise<ITaskSummary> { @@ -687,8 +699,8 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { return this._executeTask(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved); } - const inactivePromise = this._createInactiveDependencyPromise(task); - return Promise.race([inactivePromise, this._executeTask(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved)]); + const execution = this._executeTask(task, resolver, trigger, liveDependencies, encounteredTasks, alreadyResolved); + return this._createInactiveDependencyPromise(task, execution); } private async _resolveAndFindExecutable(systemInfo: ITaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, cwd: string | undefined, envPath: string | undefined): Promise<string> { @@ -837,6 +849,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { const resolvedVariables = this._acquireInput(systemInfo, workspaceFolder, task, variables, alreadyResolved); return resolvedVariables.then((resolvedVariables) => { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); if (resolvedVariables && !this._isTaskEmpty(task)) { this._currentTask.resolvedVariables = resolvedVariables; return this._executeInTerminal(task, trigger, new VariableResolver(workspaceFolder, systemInfo, resolvedVariables.variables, this._configurationResolverService), workspaceFolder); @@ -876,6 +889,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { if (!hasAllVariables) { return this._acquireInput(lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().workspaceFolder, task, variables, alreadyResolved).then((resolvedVariables) => { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); if (!resolvedVariables) { // Allows the taskExecutions array to be updated in the extension host this._fireTaskEvent(TaskEvent.general(TaskEventKind.End, task)); @@ -893,6 +907,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { } private async _executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder | undefined): Promise<ITaskSummary> { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); let terminal: ITerminalInstance | undefined = undefined; let error: TaskError | undefined = undefined; let promise: Promise<ITaskSummary> | undefined = undefined; @@ -941,14 +956,28 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { })); watchingProblemMatcher.aboutToStart(); let delayer: Async.Delayer<void> | undefined = undefined; - [terminal, error] = await this._createTerminal(task, resolver, workspaceFolder); - - if (error) { - return Promise.reject(new Error((<TaskError>error).message)); - } - if (!terminal) { - return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`)); + try { + [terminal, error] = await this._createTerminal(task, resolver, workspaceFolder); + if (error) { + throw new Error(error.message); + } + if (!terminal) { + throw new Error(`Failed to create terminal for task ${task._label}`); + } + } catch (error) { + watchingProblemMatcher.dispose(); + toDispose.dispose(); + delete this._busyTasks[mapKey]; + this._cleanupTaskTracking(task); + // End must precede cleanup Inactive events so dependencies cannot interpret failure as readiness. + this._fireTaskEvent(TaskEvent.general(TaskEventKind.End, task)); + while (eventCounter > 0) { + eventCounter--; + this._fireTaskEvent(TaskEvent.inactive(task)); + } + throw error; } + this._terminalStatusManager.addTerminal(task, terminal, watchingProblemMatcher); this._taskProblemMonitor.addTerminal(terminal, watchingProblemMatcher); let processStartedSignaled = false; @@ -980,10 +1009,13 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { promise = new Promise<ITaskSummary>((resolve, reject) => { const boundTerminal = terminal!; - const onExit = terminal!.onExit((terminalLaunchResult) => { + const onExit = terminal!.onExit(async (terminalLaunchResult) => { const exitCode = typeof terminalLaunchResult === 'number' ? terminalLaunchResult : terminalLaunchResult?.code; onData?.dispose(); onExit.dispose(); + // Wait for the problems of the last lines before the task is + // released, so that a new run can't be affected by this one. + await watchingProblemMatcher.done(); const key = task.getMapKey(); if (this._busyTasks[mapKey]) { delete this._busyTasks[mapKey]; @@ -1016,7 +1048,6 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { // There is nothing else to do here. } } - watchingProblemMatcher.done(); watchingProblemMatcher.dispose(); if (!processStartedSignaled) { this._fireTaskEvent(TaskEvent.processStarted(task, terminal!.instanceId, terminal!.processId!)); @@ -1451,6 +1482,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { private async _doCreateTerminal(task: Task, group: string | undefined, launchConfigs: IShellLaunchConfig): Promise<ITerminalInstance> { const reconnectedTerminal = await this._reconnectToTerminal(task); + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); const registerOnDisposed = (terminal: ITerminalInstance) => { const listener = terminal.onDisposed(() => { this._fireTaskEvent(TaskEvent.terminated(task, terminal.instanceId, terminal.exitReason)); @@ -1549,6 +1581,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { if (task.command.runtime === RuntimeType.CustomExecution) { this._currentTask.shellLaunchConfig = launchConfigs = { customPtyImplementation: (id, cols, rows) => new TerminalProcessExtHostProxy(id, cols, rows, this._terminalService), + type: TaskTerminalType, waitOnExit, name: this._createTerminalName(task), initialText: task.command.presentation && task.command.presentation.echo ? formatMessageForTerminal(nls.localize({ @@ -1569,6 +1602,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { return [undefined, new TaskError(Severity.Error, nls.localize('TerminalTaskSystem', 'Can\'t execute a shell command on an UNC drive using cmd.exe.'), TaskErrors.UnknownError)]; } } + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); const prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated; const allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared; const group = presentationOptions.group; @@ -1625,8 +1659,7 @@ export class TerminalTaskSystem extends Disposable implements ITaskSystem { return [terminalToReuse.terminal, undefined]; } - this._terminalCreationQueue = this._terminalCreationQueue.then(() => this._doCreateTerminal(task, group, launchConfigs)); - const terminal: ITerminalInstance = (await this._terminalCreationQueue)!; + const terminal = await this._terminalCreationQueue.queue(() => this._doCreateTerminal(task, group, launchConfigs)); if (task.configurationProperties.isBackground) { terminal.shellLaunchConfig.reconnectionProperties = { ownerId: TaskTerminalType, data: { lastTask: task.getCommonTaskId(), group, label: task._label, id: task._id } }; } diff --git a/src/vs/workbench/contrib/tasks/common/problemCollectors.ts b/src/vs/workbench/contrib/tasks/common/problemCollectors.ts index cdace8e4abd1..8cbf24291751 100644 --- a/src/vs/workbench/contrib/tasks/common/problemCollectors.ts +++ b/src/vs/workbench/contrib/tasks/common/problemCollectors.ts @@ -352,6 +352,15 @@ export abstract class AbstractProblemCollector extends Disposable implements IDi this.reportMarkers(); this.cleanAllMarkers(); } + + /** + * Resolves once the lines passed to `processLine` so far have been + * processed. Lines are processed asynchronously, one after the other. + */ + protected linesProcessed(): Promise<void> { + const ignore = () => { }; + return this.tail ? this.tail.then(ignore, ignore) : Promise.resolve(); + } } export const enum ProblemHandlingStrategy { @@ -598,10 +607,17 @@ export class WatchingProblemCollector extends AbstractProblemCollector implement } } - public override done(): void { + /** + * Reports the markers and cleans up the markers of the previous run. A + * background task can exit right after printing its output, before its last + * lines have been processed, so this waits for them first. The returned + * promise resolves once the markers have been reported. + */ + public override async done(): Promise<void> { [...this.applyToByOwner.keys()].forEach(owner => { this.recordResourcesToClean(owner); }); + await this.linesProcessed(); super.done(); } diff --git a/src/vs/workbench/contrib/tasks/common/taskSystem.ts b/src/vs/workbench/contrib/tasks/common/taskSystem.ts index ec05fe3438ba..f5e19840cf80 100644 --- a/src/vs/workbench/contrib/tasks/common/taskSystem.ts +++ b/src/vs/workbench/contrib/tasks/common/taskSystem.ts @@ -15,6 +15,20 @@ import { ConfigurationTarget } from '../../../../platform/configuration/common/c import { IShellLaunchConfig } from '../../../../platform/terminal/common/terminal.js'; import { IMarkerData } from '../../../../platform/markers/common/markers.js'; import type { SingleOrMany } from '../../../../base/common/types.js'; +import { IWorkspaceTrustManagementService } from '../../../../platform/workspace/common/workspaceTrust.js'; +import { localize } from '../../../../nls.js'; + +export class TaskWorkspaceTrustError extends Error { + constructor() { + super(localize('task.workspaceTrustRevoked', "Task execution was cancelled because the workspace is no longer trusted.")); + } +} + +export function assertTaskWorkspaceTrust(workspaceTrustManagementService: IWorkspaceTrustManagementService): void { + if (!workspaceTrustManagementService.isWorkspaceTrusted()) { + throw new TaskWorkspaceTrustError(); + } +} export const enum TaskErrors { NotConfigured, diff --git a/src/vs/workbench/contrib/tasks/test/browser/abstractTaskService.test.ts b/src/vs/workbench/contrib/tasks/test/browser/abstractTaskService.test.ts index 00d3ed9a889f..c5d728e5dbad 100644 --- a/src/vs/workbench/contrib/tasks/test/browser/abstractTaskService.test.ts +++ b/src/vs/workbench/contrib/tasks/test/browser/abstractTaskService.test.ts @@ -10,12 +10,87 @@ import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; import { AbstractTaskService } from '../../browser/abstractTaskService.js'; +import { ProblemMatcherRegistry } from '../../common/problemMatcher.js'; import { ITaskProvider, IWorkspaceFolderTaskResult } from '../../common/taskService.js'; -import { ContributedTask, ITaskSet, JsonSchemaVersion, Task, TaskScope, TaskSourceKind } from '../../common/tasks.js'; +import { ITaskSummary, TaskExecuteKind } from '../../common/taskSystem.js'; +import { ContributedTask, ITaskSet, JsonSchemaVersion, Task, TaskRunSource, TaskScope, TaskSourceKind } from '../../common/tasks.js'; +import { TestWorkspaceTrustManagementService } from '../../../../test/common/workbenchTestServices.js'; suite('AbstractTaskService', () => { - ensureNoDisposablesAreLeakedInTestSuite(); + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + for (const runSource of [TaskRunSource.System, TaskRunSource.Reconnect]) { + for (const preparation of ['save', 'matchers'] as const) { + test(`does not dispatch ${runSource} tasks when trust is revoked during ${preparation}`, async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const pending = new DeferredPromise<void>(); + const entered = new DeferredPromise<void>(); + const pause = async () => { + await entered.complete(); + await pending.p; + }; + sinon.stub(ProblemMatcherRegistry, 'onReady').callsFake(preparation === 'matchers' ? pause : async () => { }); + const launches: string[] = []; + const errors: Error[] = []; + const task = new ContributedTask('test', { + kind: TaskSourceKind.Extension, label: 'test', extension: 'test', scope: TaskScope.Workspace, workspaceFolder: undefined + }, 'test', 'test', { type: 'test', _key: 'test' }, {}, false, {}, {}); + const dispatch = (kind: string) => { + launches.push(kind); + return { kind: TaskExecuteKind.Started, task, promise: Promise.resolve({ exitCode: 0 }) }; + }; + const service = Object.assign(Object.create(AbstractTaskService.prototype), { + _workspaceTrustManagementService: trust, + _trust: async () => trust.isWorkspaceTrusted(), + _createResolver: () => ({}), + _saveBeforeRun: async () => { + if (preparation === 'save') { + await pause(); + } + return false; + }, + _getTaskSystem: () => ({ + run: () => dispatch('run'), + reconnect: () => dispatch('reconnect') + }), + _handleExecuteResult: async (result: { promise: Promise<ITaskSummary> }) => result.promise, + _handleError: (error: Error) => errors.push(error) + }) as AbstractTaskService; + const execution = service.run(task, undefined, runSource); + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + await trust.setWorkspaceTrust(false); + await pending.complete(); + await rejected; + assert.deepStrictEqual({ launches, errors: errors.length }, { launches: [], errors: 1 }); + }); + } + } + + test('dispatches tasks normally while workspace trust is retained', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + sinon.stub(ProblemMatcherRegistry, 'onReady').resolves(); + const task = new ContributedTask('test', { + kind: TaskSourceKind.Extension, label: 'test', extension: 'test', scope: TaskScope.Workspace, workspaceFolder: undefined + }, 'test', 'test', { type: 'test', _key: 'test' }, {}, false, {}, {}); + const launches: Task[] = []; + const service = Object.assign(Object.create(AbstractTaskService.prototype), { + _workspaceTrustManagementService: trust, + _trust: async () => true, + _createResolver: () => ({}), + _saveBeforeRun: async () => false, + _getTaskSystem: () => ({ + run: (task: Task) => { + launches.push(task); + return { kind: TaskExecuteKind.Started, task, promise: Promise.resolve({ exitCode: 0 }) }; + } + }), + _handleExecuteResult: async (result: { promise: Promise<ITaskSummary> }) => result.promise + }) as AbstractTaskService; + assert.deepStrictEqual({ result: await service.run(task), launches }, { result: { exitCode: 0 }, launches: [task] }); + }); for (const settlement of ['reject', 'resolve'] as const) { test(`counts a timed-out provider only once when it later ${settlement}s`, async () => { diff --git a/src/vs/workbench/contrib/tasks/test/browser/taskSystemReadiness.test.ts b/src/vs/workbench/contrib/tasks/test/browser/taskSystemReadiness.test.ts index ddb9969e62f9..ffa74961fac8 100644 --- a/src/vs/workbench/contrib/tasks/test/browser/taskSystemReadiness.test.ts +++ b/src/vs/workbench/contrib/tasks/test/browser/taskSystemReadiness.test.ts @@ -6,7 +6,7 @@ import * as assert from 'assert'; import * as sinon from 'sinon'; import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; -import { Emitter } from '../../../../../base/common/event.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../base/common/network.js'; import * as Platform from '../../../../../base/common/platform.js'; @@ -23,6 +23,10 @@ import { RunAutomaticTasks } from '../../browser/runAutomaticTasks.js'; import { TaskService } from '../../browser/taskService.js'; import { ITaskService, IWorkspaceFolderTaskResult } from '../../common/taskService.js'; import { ITaskSystemInfo } from '../../common/taskSystem.js'; +import { IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestWorkspaceTrustManagementService } from '../../../../test/common/workbenchTestServices.js'; +import { ContributedTask, RunOnOptions, Task, TaskScope, TaskSourceKind } from '../../common/tasks.js'; class TestTaskService extends TaskService { get whenTaskSystemReady(): Promise<void> { @@ -134,6 +138,60 @@ suite('Task system readiness', function () { assert.strictEqual(getWorkspaceTasks.callCount, 1); }); + for (const preparation of ['discovery', 'permission', 'resolution'] as const) { + test(`revoking trust invalidates automatic tasks pending ${preparation}, even after trust is restored`, async () => { + const instantiationService = workbenchInstantiationService(undefined, store); + const trust = store.add(new TestWorkspaceTrustManagementService()); + instantiationService.stub(IWorkspaceTrustManagementService, trust); + const configurationService = instantiationService.get(IConfigurationService); + sinon.stub(configurationService, 'inspect').returns({ value: 'on', userValue: 'on' }); + sinon.stub(configurationService, 'getValue').returns(preparation === 'permission' ? 'off' : 'on'); + const pending = new DeferredPromise<void>(); + const entered = new DeferredPromise<void>(); + const pause = async () => { + await entered.complete(); + await pending.p; + }; + const launches: Task[] = []; + instantiationService.stub(ITaskService, new class extends mock<ITaskService>() { + override readonly isReconnected = true; + override readonly hasTaskSystemInfo = true; + override readonly onDidChangeTaskSystemInfo = Event.None; + override async getWorkspaceTasks() { + if (preparation === 'discovery') { + await pause(); + } + return new Map<string, IWorkspaceFolderTaskResult>(); + } + override async run(task: Task | undefined) { + if (task) { + launches.push(task); + } + return { exitCode: 0 }; + } + }); + const task = new ContributedTask('automatic', { + kind: TaskSourceKind.Extension, label: 'test', extension: 'test', scope: TaskScope.Workspace, workspaceFolder: undefined + }, 'automatic', 'test', { type: 'test', _key: 'automatic' }, {}, false, { runOn: RunOnOptions.folderOpen }, {}); + sinon.stub(RunAutomaticTasks.prototype, '_findAutoTasks' as keyof RunAutomaticTasks).value(() => ({ + tasks: preparation === 'resolution' ? [pause().then(() => task)] : [task], + taskNames: [task._label], + locations: new Map() + })); + sinon.stub(RunAutomaticTasks.prototype, '_showPrompt' as keyof RunAutomaticTasks).value(async () => { + await pause(); + return true; + }); + store.add(instantiationService.createInstance(RunAutomaticTasks)); + await entered.p; + await trust.setWorkspaceTrust(false); + await trust.setWorkspaceTrust(true); + await pending.complete(); + await timeout(0); + assert.deepStrictEqual(launches, []); + }); + } + for (const readinessBeforeDisposal of ['waiting', 'ready', 'lost'] as const) { test(`disposing automatic tasks stops pending readiness work (readiness before disposal: ${readinessBeforeDisposal})`, async () => { const { taskService, instantiationService } = createTaskService('test-remote'); diff --git a/src/vs/workbench/contrib/tasks/test/browser/taskTerminalStatus.test.ts b/src/vs/workbench/contrib/tasks/test/browser/taskTerminalStatus.test.ts index 5793903997b2..d2f186418008 100644 --- a/src/vs/workbench/contrib/tasks/test/browser/taskTerminalStatus.test.ts +++ b/src/vs/workbench/contrib/tasks/test/browser/taskTerminalStatus.test.ts @@ -3,19 +3,28 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { ok } from 'assert'; +import { deepStrictEqual, ok } from 'assert'; +import { importAMDNodeModule } from '../../../../../amdX.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; -import { Disposable } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IModelService } from '../../../../../editor/common/services/model.js'; import { AccessibilitySignal, IAccessibilitySignalService } from '../../../../../platform/accessibilitySignal/browser/accessibilitySignalService.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; +import { BufferMarkCapability } from '../../../../../platform/terminal/common/capabilities/bufferMarkCapability.js'; +import { TestXtermLogger } from '../../../../../platform/terminal/test/common/terminalTestHelpers.js'; import { ACTIVE_TASK_STATUS, FAILED_TASK_STATUS, SUCCEEDED_TASK_STATUS, TaskTerminalStatus } from '../../browser/taskTerminalStatus.js'; -import { AbstractProblemCollector } from '../../common/problemCollectors.js'; +import { AbstractProblemCollector, WatchingProblemCollector } from '../../common/problemCollectors.js'; +import { ApplyToKind, FileLocationKind } from '../../common/problemMatcher.js'; import { CommonTask, ITaskEvent, TaskEventKind, TaskRunType } from '../../common/tasks.js'; import { ITaskService, Task } from '../../common/taskService.js'; import { ITerminalInstance } from '../../../terminal/browser/terminal.js'; import { ITerminalStatusList, TerminalStatusList } from '../../../terminal/browser/terminalStatusList.js'; +import { writeP } from '../../../terminal/browser/terminalTestHelpers.js'; +import { LineDataEventAddon } from '../../../terminal/browser/xterm/lineDataEventAddon.js'; import { ITerminalStatus } from '../../../terminal/common/terminal.js'; import { IMarker } from '../../../../../platform/markers/common/markers.js'; @@ -131,6 +140,76 @@ suite('Task Terminal Status', () => { taskService.triggerStateChange({ kind: TaskEventKind.ProcessEnded, exitCode: 0 }); assertStatus(testTerminal.statusList, SUCCEEDED_TASK_STATUS); }); + + suite('background task markers', () => { + async function createBackgroundTerminal(instanceId: number) { + const disposables = store.add(new DisposableStore()); + const TerminalCtor = (await importAMDNodeModule<typeof import('@xterm/xterm')>('@xterm/xterm', 'lib/xterm.js')).Terminal; + const xterm = store.add(new TerminalCtor({ allowProposedApi: true, logger: TestXtermLogger })); + const marks = store.add(new BufferMarkCapability(xterm)); + const collector = store.add(new WatchingProblemCollector([{ + owner: `task${instanceId}`, + applyTo: ApplyToKind.allDocuments, + fileLocation: FileLocationKind.Relative, + filePrefix: '/workspace', + pattern: { regexp: /^(.*):(\d+): (.*)$/, file: 1, line: 2, message: 3 }, + watching: { activeOnStart: false, beginsPattern: { regexp: /^begin$/ }, endsPattern: { regexp: /^end$/ } } + }], store.add(new MarkerService()), upcastPartial<IModelService>({ + onModelAdded: Event.None, + onModelRemoved: Event.None, + getModels: () => [] + }))); + taskTerminalStatus.addTerminal(testTask, upcastPartial<ITerminalInstance>({ + instanceId, + statusList: store.add(new TerminalStatusList(new TestConfigurationService())), + onDisposed: Event.None, + registerMarker: offset => xterm.registerMarker(offset), + addBufferMarker: properties => marks.addMark(properties) + }), collector); + const lineData = store.add(new LineDataEventAddon()); + xterm.loadAddon(lineData); + store.add(lineData.onLineData(line => collector.processLine(line))); + return { + xterm, + marks, + async write(data: string) { + const stateChanged = Event.toPromise(collector.onDidStateChange, disposables); + await writeP(xterm, data); + await stateChanged; + } + }; + } + + test('keeps error markers in their own terminal when background tasks overlap', async () => { + const first = await createBackgroundTerminal(1); + const second = await createBackgroundTerminal(2); + + await first.write('first prelude\r\nbegin\r\n'); + await second.write('second prelude\r\nmore output\r\nmore output\r\nbegin\r\n'); + await first.write('a.ts:1: first error\r\nend\r\n'); + await second.write('b.ts:1: second error\r\nend\r\n'); + + deepStrictEqual([ + Array.from(first.marks.markers(), marker => marker.line), + Array.from(second.marks.markers(), marker => marker.line) + ], [[2], [4]]); + }); + + test('a clean background task does not invalidate another terminal marker', async () => { + const first = await createBackgroundTerminal(1); + const second = await createBackgroundTerminal(2); + + await first.write('begin\r\n'); + await second.write('second prelude\r\nmore output\r\nbegin\r\n'); + await first.write('end\r\n'); + await second.write('b.ts:1: second error\r\nend\r\n'); + + deepStrictEqual({ + firstMarkers: first.xterm.markers.map(marker => marker.line), + secondMarks: Array.from(second.marks.markers(), marker => marker.line) + }, { firstMarkers: [], secondMarks: [3] }); + }); + }); }); function assertStatus(actual: ITerminalStatusList, expected: ITerminalStatus): void { diff --git a/src/vs/workbench/contrib/tasks/test/browser/terminalTaskSystem.test.ts b/src/vs/workbench/contrib/tasks/test/browser/terminalTaskSystem.test.ts new file mode 100644 index 000000000000..5bfcf2e33ee6 --- /dev/null +++ b/src/vs/workbench/contrib/tasks/test/browser/terminalTaskSystem.test.ts @@ -0,0 +1,318 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as assert from 'assert'; +import { DeferredPromise, Sequencer, timeout } from '../../../../../base/common/async.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { IModelService } from '../../../../../editor/common/services/model.js'; +import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { ITerminalInstance } from '../../../terminal/browser/terminal.js'; +import { IShellLaunchConfig } from '../../../../../platform/terminal/common/terminal.js'; +import { TestWorkspaceTrustManagementService } from '../../../../test/common/workbenchTestServices.js'; +import { TerminalTaskSystem } from '../../browser/terminalTaskSystem.js'; +import { assertTaskWorkspaceTrust, ITaskResolver, ITaskSummary } from '../../common/taskSystem.js'; +import { ContributedTask, DependsOrder, ITaskEvent, PanelKind, PresentationOptions, RuntimeType, Task, TaskEvent, TaskEventKind, TaskScope, TaskSourceKind } from '../../common/tasks.js'; +import { ApplyToKind, FileLocationKind, ProblemMatcher } from '../../common/problemMatcher.js'; + +suite('TerminalTaskSystem workspace trust', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const folder = new WorkspaceFolder({ uri: URI.file('/workspace'), name: 'workspace', index: 0 }); + + function createTask(id: string): ContributedTask { + return new ContributedTask(id, { + kind: TaskSourceKind.Extension, label: 'test', extension: 'test', scope: TaskScope.Folder, workspaceFolder: folder + }, id, 'test', { type: 'test', _key: id }, { + runtime: RuntimeType.Process, name: 'recorder', presentation: { ...PresentationOptions.defaults, panel: PanelKind.New } + }, false, {}, {}); + } + + for (const preparation of ['dependency resolution', 'dependency completion', 'input'] as const) { + test(`does not start a command after trust is revoked during ${preparation}`, async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const pending = new DeferredPromise<void>(); + const entered = new DeferredPromise<void>(); + const pause = async () => { + await entered.complete(); + await pending.p; + }; + const launches: string[] = []; + const task = createTask('parent'); + const dependency = createTask('dependency'); + if (preparation !== 'input') { + task.configurationProperties.dependsOn = [{ uri: folder.uri, task: dependency._id }]; + task.configurationProperties.dependsOrder = DependsOrder.sequence; + } + const resolver: ITaskResolver = { + resolve: async () => { + if (preparation === 'dependency resolution') { + await pause(); + } + return dependency; + } + }; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _workspaceTrustManagementService: trust, + _activeTasks: {}, + _taskDependencies: {}, + _getInstances: () => [], + _showTaskLoadErrors: () => { }, + _fireTaskEvent: () => { }, + _adoptConfigurationForDependencyTask: () => { }, + _executeDependencyTask: async () => { + launches.push('dependency'); + await pause(); + return { exitCode: 0 }; + }, + _taskSystemInfoResolver: () => undefined, + _acquireInput: async () => { + await pause(); + return { variables: new Map<string, string>() }; + }, + _executeInTerminal: async (task: Task) => { + launches.push(task._id); + return { exitCode: 0 }; + }, + _logService: { error: () => { } } + }) as TerminalTaskSystem; + const execution = system.run(task, resolver).promise; + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + await trust.setWorkspaceTrust(false); + await pending.complete(); + await rejected; + assert.deepStrictEqual(launches, preparation === 'dependency completion' ? ['dependency'] : []); + }); + } + + test('releases the inactive listener when a background dependency is cancelled', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const emitter = store.add(new Emitter<ITaskEvent>()); + const pending = new DeferredPromise<void>(); + const task = createTask('background'); + task.configurationProperties.isBackground = true; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _onDidStateChange: emitter, + _executeTask: async () => { + await pending.p; + assertTaskWorkspaceTrust(trust); + return { exitCode: 0 }; + } + }) as { + _executeDependencyTask(task: Task, resolver: ITaskResolver, trigger: string, liveDependencies: Set<string>, encounteredTasks: Map<string, Promise<ITaskSummary>>): Promise<ITaskSummary>; + }; + const execution = system._executeDependencyTask(task, { resolve: async () => undefined }, 'command', new Set(), new Map()); + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await trust.setWorkspaceTrust(false); + await pending.complete(); + await rejected; + assert.strictEqual(emitter.hasListeners(), false); + }); + + test('balances background activity and rejects readiness when terminal preparation is cancelled', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const emitter = store.add(new Emitter<ITaskEvent>()); + const events: TaskEventKind[] = []; + const observer = store.add(emitter.event(event => events.push(event.kind))); + const pending = new DeferredPromise<void>(); + const entered = new DeferredPromise<void>(); + const task = createTask('background'); + const matcher: ProblemMatcher = { + owner: 'test', applyTo: ApplyToKind.allDocuments, fileLocation: FileLocationKind.Relative, filePrefix: '/workspace', + pattern: { regexp: /^(.*):(\d+): (.*)$/, file: 1, line: 2, message: 3 }, + watching: { activeOnStart: true, beginsPattern: { regexp: /^begin$/ }, endsPattern: { regexp: /^end$/ } } + }; + task.configurationProperties.isBackground = true; + task.configurationProperties.problemMatchers = [matcher]; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _workspaceTrustManagementService: trust, + _onDidStateChange: emitter, + _activeTasks: {}, + _busyTasks: {}, + _taskDependencies: {}, + _taskErrors: {}, + _getInstances: () => [], + _showTaskLoadErrors: () => { }, + _logService: store.add(new NullLogService()), + _markerService: store.add(new MarkerService()), + _modelService: new class extends mock<IModelService>() { + override readonly onModelAdded = Event.None; + override readonly onModelRemoved = Event.None; + override getModels() { return []; } + }, + _resolveMatchers: async () => [matcher, { ...matcher, owner: 'second' }], + _executeCommand: () => system._executeInTerminal(task, 'command', { values: new Map() }, folder), + _createTerminal: async () => { + await entered.complete(); + await pending.p; + assertTaskWorkspaceTrust(trust); + throw new Error('Expected task cancellation'); + } + }) as { + getBusyTasks(): Task[]; + _executeInTerminal(task: Task, trigger: string, resolver: { values: Map<string, string> }, folder: WorkspaceFolder): Promise<ITaskSummary>; + _executeDependencyTask(task: Task, resolver: ITaskResolver, trigger: string, liveDependencies: Set<string>, encounteredTasks: Map<string, Promise<ITaskSummary>>): Promise<ITaskSummary>; + _getDependencyPromise(task: { task: Task; state: TaskEventKind; promise: Promise<ITaskSummary> }): Promise<ITaskSummary>; + }; + const execution = system._executeDependencyTask(task, { resolve: async () => undefined }, 'command', new Set(), new Map()); + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + assert.deepStrictEqual(system.getBusyTasks(), [task]); + const alreadyActiveRejected = assert.rejects(system._getDependencyPromise({ task, state: TaskEventKind.Active, promise: execution }), /workspace is no longer trusted/); + await trust.setWorkspaceTrust(false); + await pending.complete(); + await Promise.all([rejected, alreadyActiveRejected]); + observer.dispose(); + assert.deepStrictEqual({ + busyTasks: system.getBusyTasks(), events, hasListeners: emitter.hasListeners() + }, { + busyTasks: [], + events: [TaskEventKind.Active, TaskEventKind.Active, TaskEventKind.End, TaskEventKind.Inactive, TaskEventKind.Inactive], + hasListeners: false + }); + }); + + for (const outcome of ['ready', 'exit successfully', 'exit unsuccessfully'] as const) { + test(`preserves background dependency completion when tasks ${outcome}`, async () => { + const emitter = store.add(new Emitter<ITaskEvent>()); + const pending = new DeferredPromise<ITaskSummary>(); + const task = createTask('background'); + task.configurationProperties.isBackground = true; + task.configurationProperties.problemMatchers = ['$test']; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _onDidStateChange: emitter + }) as { + _getDependencyPromise(task: { task: Task; state: TaskEventKind; promise: Promise<ITaskSummary> }): Promise<ITaskSummary>; + }; + const readiness = system._getDependencyPromise({ task, state: TaskEventKind.Active, promise: pending.p }); + emitter.fire(outcome === 'ready' ? TaskEvent.inactive(task, 1) : TaskEvent.general(TaskEventKind.End, task)); + if (outcome !== 'ready') { + await pending.complete({ exitCode: outcome === 'exit successfully' ? 0 : 7 }); + } + const summary = await readiness; + if (outcome === 'ready') { + await pending.complete({ exitCode: 7 }); + } + assert.deepStrictEqual({ summary, hasListeners: emitter.hasListeners() }, { + summary: { exitCode: outcome === 'exit unsuccessfully' ? 7 : 0 }, hasListeners: false + }); + }); + } + + test('observes pending parallel dependency failures after parent cancellation', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const entered = new DeferredPromise<void>(); + const pendingResolver = new DeferredPromise<Task>(); + const dependencyResult = new DeferredPromise<ITaskSummary>(); + const errors: Error[] = []; + const task = createTask('parent'); + task.configurationProperties.dependsOn = [ + { uri: folder.uri, task: 'first' }, + { uri: folder.uri, task: 'second' } + ]; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _workspaceTrustManagementService: trust, + _activeTasks: {}, + _taskDependencies: {}, + _getInstances: () => [], + _showTaskLoadErrors: () => { }, + _fireTaskEvent: () => { }, + _adoptConfigurationForDependencyTask: () => { }, + _executeDependencyTask: () => dependencyResult.p, + _logService: { error: (_message: string, error: Error) => errors.push(error) } + }) as TerminalTaskSystem; + const execution = system.run(task, { + resolve: async (_uri, identifier) => { + if (identifier === 'first') { + return createTask('first'); + } + await entered.complete(); + return pendingResolver.p; + } + }).promise; + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + await trust.setWorkspaceTrust(false); + await pendingResolver.complete(createTask('second')); + await rejected; + await dependencyResult.error(new Error('dependency cancelled')); + await timeout(0); + assert.deepStrictEqual(errors.map(error => error.message.includes('workspace is no longer trusted') ? 'parent cancelled' : error.message), ['parent cancelled', 'dependency cancelled']); + }); + + test('rechecks trust after launch configuration resolution before reusing a terminal', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const pending = new DeferredPromise<IShellLaunchConfig>(); + const entered = new DeferredPromise<void>(); + const launches: string[] = []; + const task = createTask('test'); + task.command.presentation!.panel = PanelKind.Dedicated; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _workspaceTrustManagementService: trust, + _currentTask: {}, + _resolveOptions: async () => ({}), + _resolveCommandAndArgs: async () => ({ command: 'recorder', args: [] }), + _createShellLaunchConfig: async () => { + await entered.complete(); + return pending.p; + }, + _sameTaskTerminals: { [task.getMapKey()]: '1' }, + _terminals: { + '1': { terminal: { scrollToBottom: () => { }, reuseTerminal: async () => launches.push('reuse') } } + } + }) as { _createTerminal(task: Task, resolver: { taskSystemInfo: undefined }, folder: WorkspaceFolder): Promise<[ITerminalInstance | undefined, Error | undefined]> }; + const execution = system._createTerminal(task, { taskSystemInfo: undefined }, folder); + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + await trust.setWorkspaceTrust(false); + await pending.complete({ type: 'Task' }); + await rejected; + assert.deepStrictEqual(launches, []); + }); + + test('queued terminal creation rechecks trust and a rejected creation does not block later work', async () => { + const trust = store.add(new TestWorkspaceTrustManagementService()); + const pending = new DeferredPromise<void>(); + const entered = new DeferredPromise<void>(); + const launches: string[] = []; + const system = Object.assign(Object.create(TerminalTaskSystem.prototype), { + _workspaceTrustManagementService: trust, + _currentTask: {}, + _resolveOptions: async () => ({}), + _resolveCommandAndArgs: async () => ({ command: 'recorder', args: [] }), + _createShellLaunchConfig: async () => ({ type: 'Task' }), + _terminalCreationQueue: new Sequencer(), + _terminals: {}, + _reconnectToTerminal: async () => { + await entered.complete(); + await pending.p; + return undefined; + }, + _terminalService: { + createTerminal: async () => { + launches.push('create'); + return { instanceId: 1, shellLaunchConfig: { type: 'Task' }, onDisposed: Event.None }; + } + }, + _logService: { trace: () => { } } + }) as { _createTerminal(task: Task, resolver: { taskSystemInfo: undefined }, folder: WorkspaceFolder): Promise<[ITerminalInstance | undefined, Error | undefined]> }; + const execution = system._createTerminal(createTask('test'), { taskSystemInfo: undefined }, folder); + const rejected = assert.rejects(execution, /workspace is no longer trusted/); + await entered.p; + const queued = system._createTerminal(createTask('queued'), { taskSystemInfo: undefined }, folder); + const queuedRejected = assert.rejects(queued, /workspace is no longer trusted/); + await trust.setWorkspaceTrust(false); + await pending.complete(); + await rejected; + await queuedRejected; + await trust.setWorkspaceTrust(true); + await system._createTerminal(createTask('next'), { taskSystemInfo: undefined }, folder); + assert.deepStrictEqual(launches, ['create']); + }); +}); diff --git a/src/vs/workbench/contrib/tasks/test/common/problemCollectors.test.ts b/src/vs/workbench/contrib/tasks/test/common/problemCollectors.test.ts index 130819f134eb..e36983e4a535 100644 --- a/src/vs/workbench/contrib/tasks/test/common/problemCollectors.test.ts +++ b/src/vs/workbench/contrib/tasks/test/common/problemCollectors.test.ts @@ -12,7 +12,7 @@ import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelSc import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { ITextModel } from '../../../../../editor/common/model.js'; import { IModelService } from '../../../../../editor/common/services/model.js'; -import { IMarker, IMarkerService } from '../../../../../platform/markers/common/markers.js'; +import { IMarker, IMarkerData, IMarkerService } from '../../../../../platform/markers/common/markers.js'; import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; import { ProblemCollectorEventKind, WatchingProblemCollector } from '../../common/problemCollectors.js'; import { ApplyToKind, FileLocationKind, ProblemMatcher } from '../../common/problemMatcher.js'; @@ -159,4 +159,55 @@ suite('ProblemCollectors', () => { assert.deepStrictEqual(matchCounts, [1, 2, 3]); })); + + test('reports markers of lines still being processed when done is called', () => runWithFakedTimers<void>({ useFakeTimers: true }, async () => { + const modelService = new class extends mock<IModelService>() { + override readonly onModelAdded = Event.None; + override readonly onModelRemoved = Event.None; + override getModels(): ITextModel[] { return []; } + }; + + const delivered = new Map<string, string[]>(); + const markerService = new class extends mock<IMarkerService>() { + override readonly onMarkerChanged = Event.None; + override read() { return []; } + override changeOne(_owner: string, resource: URI, markers: IMarkerData[]) { + delivered.set(resource.path, markers.map(marker => marker.message)); + } + override remove() { } + }; + + const problemMatcher: ProblemMatcher = { + owner: 'test', + applyTo: ApplyToKind.allDocuments, + fileLocation: FileLocationKind.Absolute, + pattern: { regexp: /^(.*):(\d+):\s+([^:]+):\s+(.*)$/, file: 1, line: 2, severity: 3, message: 4 }, + watching: { + activeOnStart: true, + beginsPattern: { regexp: /^Start$/ }, + endsPattern: { regexp: /^End$/ } + } + }; + const collector = store.add(new WatchingProblemCollector([problemMatcher], markerService, modelService)); + collector.aboutToStart(); + + // The task process exits right after printing its output, before the + // end pattern is seen, while the lines are still being processed. + for (const line of [ + 'Start', + '/file1:150: error: problem1', + '/file1:825: error: problem2', + '/file2:468: error: problem3', + '/file2:550: error: problem4', + ]) { + collector.processLine(line); + } + // The markers are reported by the time the returned promise resolves. + await collector.done(); + + assert.deepStrictEqual([...delivered.entries()].sort(), [ + ['/file1', ['problem1', 'problem2']], + ['/file2', ['problem3', 'problem4']], + ]); + })); }); diff --git a/src/vs/workbench/contrib/terminal/browser/agentHostTerminalService.ts b/src/vs/workbench/contrib/terminal/browser/agentHostTerminalService.ts index 570dac16c63a..0460ae2839c7 100644 --- a/src/vs/workbench/contrib/terminal/browser/agentHostTerminalService.ts +++ b/src/vs/workbench/contrib/terminal/browser/agentHostTerminalService.ts @@ -16,7 +16,7 @@ import { IAgentConnection } from '../../../../platform/agentHost/common/agentSer import { IRemoteAgentHostService } from '../../../../platform/agentHost/common/remoteAgentHostService.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js'; -import { ITerminalLogService } from '../../../../platform/terminal/common/terminal.js'; +import { IShellLaunchConfig, ITerminalLogService } from '../../../../platform/terminal/common/terminal.js'; import { AgentHostPty } from './agentHostPty.js'; import { AgentHostOutputChannel } from './agentHostOutputChannel.js'; import { AhpTerminalCommandSource } from './ahpTerminalCommandSource.js'; @@ -125,7 +125,9 @@ export interface IAgentHostTerminalService { /** * The address of the agent host a terminal runs on, or `undefined` when it - * is not an agent host terminal or its host is no longer registered. + * is not an agent host terminal or its host is no longer registered. It is + * known as soon as the terminal service fires `onDidCreateInstance` for a + * terminal that {@link createTerminal} creates. */ getAgentHostAddress(instance: ITerminalInstance): string | undefined; @@ -171,6 +173,12 @@ export class AgentHostTerminalService extends Disposable implements IAgentHostTe private readonly _activePtys = new Map<string, { pty: AgentHostPty; clientId: string }>(); /** The {@link _activePtys} key and connection of each agent host terminal, keyed by instance id. */ private readonly _instanceKeys = new Map<number, { readonly key: string; readonly clientId: string }>(); + /** + * The {@link _activePtys} key and connection of each agent host terminal the + * terminal service is creating, keyed by the launch config its instance keeps, + * so that the terminal's host is known from the moment its instance exists. + */ + private readonly _creatingInstanceKeys = new Map<IShellLaunchConfig, { readonly key: string; readonly clientId: string }>(); private readonly _pendingRevives = new Map<string, Promise<ITerminalInstance>>(); constructor( @@ -347,31 +355,33 @@ export class AgentHostTerminalService extends Disposable implements IAgentHostTe const key = terminalUri.toString(); const ptyRegistration = this._createPtyRegistration(key, connection.clientId); + const config: IShellLaunchConfig = { + customPtyImplementation: (id, cols, rows) => { + const pty = new AgentHostPty(id, connection, terminalUri, { + name, + cwd: options?.cwd, + }, this._logService); + if (cols > 0 && rows > 0) { + pty.resize(cols, rows); + } + ptyRegistration.setPty(pty); + return pty; + }, + name, + hostLabel: this._getHostLabel(connection), + isRemotePty: connection.clientConnectionKind !== AgentHostClientConnectionKind.Local, + isFeatureTerminal: false, + }; + let instance: ITerminalInstance; + this._creatingInstanceKeys.set(config, { key, clientId: connection.clientId }); try { - instance = await this._terminalService.createTerminal({ - config: { - customPtyImplementation: (id, cols, rows) => { - const pty = new AgentHostPty(id, connection, terminalUri, { - name, - cwd: options?.cwd, - }, this._logService); - if (cols > 0 && rows > 0) { - pty.resize(cols, rows); - } - ptyRegistration.setPty(pty); - return pty; - }, - name, - hostLabel: this._getHostLabel(connection), - isRemotePty: connection.clientConnectionKind !== AgentHostClientConnectionKind.Local, - isFeatureTerminal: false, - }, - location: options?.location, - }); + instance = await this._terminalService.createTerminal({ config, location: options?.location }); } catch (error) { ptyRegistration.dispose(); throw error; + } finally { + this._creatingInstanceKeys.delete(config); } this._registerInstancePtyCleanup(instance, key, connection.clientId, ptyRegistration); @@ -502,7 +512,7 @@ export class AgentHostTerminalService extends Disposable implements IAgentHostTe } getAgentHostAddress(instance: ITerminalInstance): string | undefined { - const registration = this._instanceKeys.get(instance.instanceId); + const registration = this._instanceKeys.get(instance.instanceId) ?? this._creatingInstanceKeys.get(instance.shellLaunchConfig); if (!registration) { return undefined; } diff --git a/src/vs/workbench/contrib/terminal/browser/media/terminal.css b/src/vs/workbench/contrib/terminal/browser/media/terminal.css index bd4dd2d72a89..61a4649e1ee0 100644 --- a/src/vs/workbench/contrib/terminal/browser/media/terminal.css +++ b/src/vs/workbench/contrib/terminal/browser/media/terminal.css @@ -56,6 +56,8 @@ .monaco-workbench .xterm .xterm-helper-textarea:focus { /* Override the general vscode style applies `opacity:1!important` to textareas */ opacity: 0 !important; + /* xterm renders its own cursor; avoid native caret blink work on the hidden textarea. */ + caret-animation: manual; } .monaco-workbench .terminal-tab:not(.terminal-uri-icon)::before { diff --git a/src/vs/workbench/contrib/terminal/browser/remotePty.ts b/src/vs/workbench/contrib/terminal/browser/remotePty.ts index 68d16e842f82..9c0d958eb7b8 100644 --- a/src/vs/workbench/contrib/terminal/browser/remotePty.ts +++ b/src/vs/workbench/contrib/terminal/browser/remotePty.ts @@ -12,6 +12,7 @@ import { hasKey } from '../../../../base/common/types.js'; export class RemotePty extends BasePty implements ITerminalChildProcess { private readonly _startBarrier: Barrier; + private _startRequested = false; constructor( id: number, @@ -25,6 +26,7 @@ export class RemotePty extends BasePty implements ITerminalChildProcess { } async start(): Promise<ITerminalLaunchError | ITerminalLaunchResult | undefined> { + this._startRequested = true; // Fetch the environment to check shell permissions const env = await this._remoteAgentService.getEnvironment(); if (!env) { @@ -46,10 +48,16 @@ export class RemotePty extends BasePty implements ITerminalChildProcess { } async detach(forcePersist?: boolean): Promise<void> { - await this._startBarrier.wait(); + if (this._startRequested) { + await this._startBarrier.wait(); + } return this._remoteTerminalChannel.detachFromProcess(this.id, forcePersist); } + cancelBeforeStart(): Promise<void> { + return this._remoteTerminalChannel.shutdown(this.id, true); + } + shutdown(immediate: boolean): void { this._startBarrier.wait().then(_ => { this._remoteTerminalChannel.shutdown(this.id, immediate); diff --git a/src/vs/workbench/contrib/terminal/browser/terminal.ts b/src/vs/workbench/contrib/terminal/browser/terminal.ts index 930bf5ed4218..f00d03c023f8 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminal.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminal.ts @@ -436,6 +436,8 @@ export interface IDetachedXTermOptions { capabilities?: ITerminalCapabilityStore & IDisposable; readonly?: boolean; processInfo: ITerminalProcessInfo; + /** Whether to disable shell integration activation timeout reporting. */ + disableShellIntegrationReporting?: boolean; disableOverviewRuler?: boolean; /** The rows of scrollback to keep, overriding the `terminal.integrated.scrollback` setting. */ scrollback?: number; @@ -1592,6 +1594,9 @@ export interface IDetachedXtermTerminal extends IXtermTerminal { */ write(data: string | Uint8Array, callback?: () => void): void; + /** Registers a handler for an OSC sequence, returning a disposable to remove it. */ + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable; + /** * Resizes the terminal. */ @@ -1636,7 +1641,7 @@ export interface IInternalXtermTerminal { * **WARNING:** This should never be used outside of the terminal component and only for * developer purposed inside the terminal component. */ - _writeText(data: string): void; // eslint-disable-line @typescript-eslint/naming-convention + _writeText(data: string): void; // eslint-disable-line ts-eslint-js/naming-convention } export interface IXtermColorProvider { diff --git a/src/vs/workbench/contrib/terminal/browser/terminalContextMenu.ts b/src/vs/workbench/contrib/terminal/browser/terminalContextMenu.ts index ccc9030589c6..edb659464c75 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalContextMenu.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalContextMenu.ts @@ -36,7 +36,7 @@ export class InstanceContext { export class TerminalContextActionRunner extends ActionRunner { - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention protected override async runAction(action: IAction, context?: SingleOrMany<InstanceContext>): Promise<void> { if (Array.isArray(context) && context.every(e => e instanceof InstanceContext)) { // arg1: The (first) focused instance diff --git a/src/vs/workbench/contrib/terminal/browser/terminalEditor.ts b/src/vs/workbench/contrib/terminal/browser/terminalEditor.ts index 8b40d4693755..08e6eb8f45d5 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalEditor.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalEditor.ts @@ -7,7 +7,7 @@ import * as dom from '../../../../base/browser/dom.js'; import { IActionViewItem } from '../../../../base/browser/ui/actionbar/actionbar.js'; import { IAction } from '../../../../base/common/actions.js'; import { CancellationToken } from '../../../../base/common/cancellation.js'; -import { DropdownWithPrimaryActionViewItem } from '../../../../platform/actions/browser/dropdownWithPrimaryActionViewItem.js'; +import { DropdownWithPrimaryActionViewItem, IDropdownWithPrimaryActionViewItemOptions } from '../../../../platform/actions/browser/dropdownWithPrimaryActionViewItem.js'; import { IMenu, IMenuService, MenuId, MenuItemAction } from '../../../../platform/actions/common/actions.js'; import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; @@ -27,8 +27,42 @@ import { openContextMenu } from './terminalContextMenu.js'; import { ACTIVE_GROUP } from '../../../services/editor/common/editorService.js'; import { IWorkbenchLayoutService, Parts } from '../../../services/layout/browser/layoutService.js'; import { IBaseActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; -import { DisposableStore, MutableDisposable } from '../../../../base/common/lifecycle.js'; +import { DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; import { ITerminalProfile, TerminalLocation } from '../../../../platform/terminal/common/terminal.js'; +import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; +import { IActionProvider } from '../../../../base/browser/ui/dropdown/dropdown.js'; + +export class TerminalEditorDropdownWithPrimaryActionViewItem extends DropdownWithPrimaryActionViewItem { + readonly actionDisposables = this._register(new DisposableStore()); + private _onDidDispose?: () => void; + + constructor( + primaryAction: MenuItemAction, + dropdownAction: IAction, + dropdownMenuActions: readonly IAction[] | IActionProvider, + className: string, + options: IDropdownWithPrimaryActionViewItemOptions | undefined, + @IContextMenuService contextMenuProvider: IContextMenuService, + @IKeybindingService keybindingService: IKeybindingService, + @INotificationService notificationService: INotificationService, + @IContextKeyService contextKeyService: IContextKeyService, + @IThemeService themeService: IThemeService, + @IAccessibilityService accessibilityService: IAccessibilityService + ) { + super(primaryAction, dropdownAction, dropdownMenuActions, className, options, contextMenuProvider, keybindingService, notificationService, contextKeyService, themeService, accessibilityService); + } + + setOnDidDispose(fn: () => void): void { + this._onDidDispose = fn; + } + + override dispose(): void { + this._onDidDispose?.(); + super.dispose(); + } +} export class TerminalEditor extends EditorPane { @@ -45,12 +79,10 @@ export class TerminalEditor extends EditorPane { private _cancelContextMenu: boolean = false; - private readonly _newDropdown: MutableDisposable<DropdownWithPrimaryActionViewItem> = this._register(new MutableDisposable()); + private readonly _newDropdowns: Set<TerminalEditorDropdownWithPrimaryActionViewItem> = new Set(); private readonly _sessionDisposables = this._register(new DisposableStore()); - private readonly _disposableStore = this._register(new DisposableStore()); - constructor( group: IEditorGroup, @ITelemetryService telemetryService: ITelemetryService, @@ -71,6 +103,12 @@ export class TerminalEditor extends EditorPane { this._dropdownMenu = this._register(menuService.createMenu(MenuId.TerminalNewDropdownContext, contextKeyService)); this._instanceMenu = this._register(menuService.createMenu(MenuId.TerminalInstanceContext, contextKeyService)); this._register(this._terminalProfileService.onDidChangeAvailableProfiles(profiles => this._updateTabActionBar(profiles))); + this._register(toDisposable(() => { + for (const dropdown of Array.from(this._newDropdowns)) { + dropdown.dispose(); + } + this._newDropdowns.clear(); + })); } override async setInput(newInput: TerminalEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken) { @@ -113,7 +151,7 @@ export class TerminalEditor extends EditorPane { this._editorInput?.terminalInstance?.focus(true); } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention protected createEditor(parent: HTMLElement): void { this._editorInstanceElement = parent; this._overflowGuardElement = dom.$('.terminal-overflow-guard.terminal-editor'); @@ -155,9 +193,11 @@ export class TerminalEditor extends EditorPane { } private _updateTabActionBar(profiles: ITerminalProfile[]): void { - this._disposableStore.clear(); - const actions = getTerminalActionBarArgs(TerminalLocation.Editor, profiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu, this._disposableStore); - this._newDropdown.value?.update(actions.dropdownAction, actions.dropdownMenuActions); + for (const dropdown of this._newDropdowns) { + dropdown.actionDisposables.clear(); + const actions = getTerminalActionBarArgs(TerminalLocation.Editor, profiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu, dropdown.actionDisposables); + dropdown.update(actions.dropdownAction, actions.dropdownMenuActions); + } } layout(dimension: dom.Dimension): void { @@ -179,11 +219,21 @@ export class TerminalEditor extends EditorPane { case TerminalCommandId.CreateTerminalEditorSameGroup: { if (action instanceof MenuItemAction) { const location = { viewColumn: ACTIVE_GROUP }; - this._disposableStore.clear(); - const actions = getTerminalActionBarArgs(location, this._terminalProfileService.availableProfiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu, this._disposableStore); - this._newDropdown.value = this._instantiationService.createInstance(DropdownWithPrimaryActionViewItem, action, actions.dropdownAction, actions.dropdownMenuActions, actions.className, { hoverDelegate: options.hoverDelegate }); - this._newDropdown.value?.update(actions.dropdownAction, actions.dropdownMenuActions); - return this._newDropdown.value; + const actionDisposables = new DisposableStore(); + const actions = getTerminalActionBarArgs(location, this._terminalProfileService.availableProfiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._terminalService, this._dropdownMenu, actionDisposables); + const dropdown = this._instantiationService.createInstance( + TerminalEditorDropdownWithPrimaryActionViewItem, + action, + actions.dropdownAction, + actions.dropdownMenuActions, + actions.className, + { hoverDelegate: options.hoverDelegate } + ); + dropdown.actionDisposables.add(actionDisposables); + dropdown.update(actions.dropdownAction, actions.dropdownMenuActions); + dropdown.setOnDidDispose(() => this._newDropdowns.delete(dropdown)); + this._newDropdowns.add(dropdown); + return dropdown; } } } diff --git a/src/vs/workbench/contrib/terminal/browser/terminalInstance.ts b/src/vs/workbench/contrib/terminal/browser/terminalInstance.ts index 7f84c98293de..d3163f1c3194 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalInstance.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalInstance.ts @@ -80,7 +80,7 @@ import { isHorizontal, IWorkbenchLayoutService } from '../../../services/layout/ import { IPathService } from '../../../services/path/common/pathService.js'; import { IPreferencesService } from '../../../services/preferences/common/preferences.js'; import { importAMDNodeModule } from '../../../../amdX.js'; -import type { IMarker, Terminal as XTermTerminal, IBufferLine } from '@xterm/xterm'; +import type { IMarker, Terminal as XTermTerminal } from '@xterm/xterm'; import { AccessibilityCommandId } from '../../accessibility/common/accessibilityCommands.js'; import { getTerminalAccessibleTitle, terminalStrings } from '../common/terminalStrings.js'; import { TerminalIconPicker } from './terminalIconPicker.js'; @@ -2110,7 +2110,10 @@ export class TerminalInstance extends Disposable implements ITerminalInstance { // Any of the above setting changes could have changed the dimensions of the // terminal, re-evaluate now. - this._initDimensions(); + if (this._lastLayoutDimensions && this._lastLayoutDimensions.width > 0 && this._lastLayoutDimensions.height > 0) { + // Use the last layout, the container can have a temporary size while its view is laid out + this._evaluateColsAndRows(this._lastLayoutDimensions.width, this._lastLayoutDimensions.height); + } cols = this.cols; rows = this.rows; @@ -2338,13 +2341,7 @@ export class TerminalInstance extends Disposable implements ITerminalInstance { // work around for https://github.com/xtermjs/xterm.js/issues/3482 if (isWindows) { for (let i = this.xterm.raw.buffer.active.viewportY; i < this.xterm.raw.buffer.active.length; i++) { - interface ILineWithInternals extends IBufferLine { - _line: { - isWrapped: boolean; - }; - } - const line = this.xterm.raw.buffer.active.getLine(i); - (line as ILineWithInternals)._line.isWrapped = false; + this.xterm.setBufferLineWrapped(i, false); } } } diff --git a/src/vs/workbench/contrib/terminal/browser/terminalProcessManager.ts b/src/vs/workbench/contrib/terminal/browser/terminalProcessManager.ts index 11d5160c6648..eed8ff088d42 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalProcessManager.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalProcessManager.ts @@ -48,6 +48,8 @@ import { BugIndicatingError } from '../../../../base/common/errors.js'; import type { MaybePromise } from '../../../../base/common/async.js'; import { isString } from '../../../../base/common/types.js'; import { IHostService } from '../../../services/host/browser/host.js'; +import { IWorkspaceTrustManagementService } from '../../../../platform/workspace/common/workspaceTrust.js'; +import { assertTaskWorkspaceTrust, TaskWorkspaceTrustError } from '../../tasks/common/taskSystem.js'; const enum ProcessConstants { /** @@ -165,7 +167,8 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce @INotificationService private readonly _notificationService: INotificationService, @IAccessibilityService private readonly _accessibilityService: IAccessibilityService, @ITerminalService private readonly _terminalService: ITerminalService, - @IHostService private readonly _hostService: IHostService + @IHostService private readonly _hostService: IHostService, + @IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService ) { super(); this._cwdWorkspaceFolder = terminalEnvironment.getWorkspaceForTerminal(cwd, this._workspaceContextService, this._historyService); @@ -250,12 +253,30 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce cols: number, rows: number, reset: boolean = true + ): Promise<ITerminalLaunchError | ITerminalLaunchResult | undefined> { + try { + return await this._createProcess(shellLaunchConfig, cols, rows, reset); + } catch (error) { + if (error instanceof TaskWorkspaceTrustError) { + this._logService.warn(error.message); + return { message: error.message }; + } + throw error; + } + } + + private async _createProcess( + shellLaunchConfig: IShellLaunchConfig, + cols: number, + rows: number, + reset: boolean = true ): Promise<ITerminalLaunchError | ITerminalLaunchResult | undefined> { this._shellLaunchConfig = shellLaunchConfig; this._dimensions.cols = cols; this._dimensions.rows = rows; let newProcess: ITerminalChildProcess | undefined; + let isLiveAttachment = false; if (shellLaunchConfig.customPtyImplementation) { this._processType = ProcessType.PsuedoTerminal; @@ -295,6 +316,7 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce const result = await backend.attachToProcess(shellLaunchConfig.attachPersistentProcess.id); if (result) { newProcess = result; + isLiveAttachment = !result.isRevived && shellLaunchConfig.attachPersistentProcess.pid > 0; if (this._extEnvironmentVariableCollection) { this._onEnvironmentVariableCollectionChange(); } @@ -325,6 +347,9 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce isScreenReaderOptimized: this._accessibilityService.isScreenReaderOptimized() }; try { + if (shellLaunchConfig.type === 'Task') { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); + } newProcess = await backend.createProcess( shellLaunchConfig, '', // TODO: Fix cwd @@ -352,6 +377,7 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce const result = findRevivedId ? await backend.attachToRevivedProcess(id, pid) : await backend.attachToProcess(id); if (result) { newProcess = result; + isLiveAttachment = !(result.isRevived ?? findRevivedId) && pid > 0; if (this._extEnvironmentVariableCollection) { this._onEnvironmentVariableCollectionChange(); } @@ -374,12 +400,21 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce await this._resolveParentWindowHandle(); } - // If the process was disposed during its creation, shut it down and return failure if (this._isDisposed) { - newProcess.shutdown(false); + await this._releaseProcessBeforeStart(newProcess, isLiveAttachment); return undefined; } + // No awaits between this check and start(), so cancellation cannot dispose a live attachment. + if (shellLaunchConfig.type === 'Task') { + try { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); + } catch (error) { + await this._releaseProcessBeforeStart(newProcess, isLiveAttachment); + throw error; + } + } + this._process = newProcess; // Don't report the previous shell's pid for the new process before it's ready this.shellProcessId = undefined; @@ -456,6 +491,20 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce return undefined; } + private async _releaseProcessBeforeStart(process: ITerminalChildProcess, isLiveAttachment: boolean): Promise<void> { + if (isLiveAttachment) { + if (process.detach) { + await process.detach(); + } else { + this._logService.warn('Cannot detach an existing terminal process without detach support'); + } + } else if (process.cancelBeforeStart) { + await process.cancelBeforeStart(); + } else { + process.shutdown(false); + } + } + async relaunch(shellLaunchConfig: IShellLaunchConfig, cols: number, rows: number, reset: boolean): Promise<ITerminalLaunchError | ITerminalLaunchResult | undefined> { this.ptyProcessReady = this._createPtyProcessReadyPromise(); this._logService.trace(`Relaunching terminal instance ${this._instanceId}`); @@ -563,6 +612,9 @@ export class TerminalProcessManager extends Disposable implements ITerminalProce isScreenReaderOptimized: this._accessibilityService.isScreenReaderOptimized() }; const shouldPersist = ((this._configurationService.getValue(TaskSettingId.Reconnection) && shellLaunchConfig.reconnectionProperties) || !shellLaunchConfig.isFeatureTerminal) && this._terminalConfigurationService.config.enablePersistentSessions && !shellLaunchConfig.isTransient; + if (shellLaunchConfig.type === 'Task') { + assertTaskWorkspaceTrust(this._workspaceTrustManagementService); + } return await backend.createProcess(shellLaunchConfig, initialCwd, cols, rows, this._terminalConfigurationService.config.unicodeVersion, env, options, shouldPersist); } diff --git a/src/vs/workbench/contrib/terminal/browser/terminalService.ts b/src/vs/workbench/contrib/terminal/browser/terminalService.ts index 08dd4027d112..419888915acd 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalService.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalService.ts @@ -1119,6 +1119,7 @@ export class TerminalService extends Disposable implements ITerminalService { rows: options.rows, xtermColorProvider: options.colorProvider, capabilities, + disableShellIntegrationReporting: options.disableShellIntegrationReporting, disableOverviewRuler: options.disableOverviewRuler, scrollback: options.scrollback, detached: true, diff --git a/src/vs/workbench/contrib/terminal/browser/terminalTabbedView.ts b/src/vs/workbench/contrib/terminal/browser/terminalTabbedView.ts index 7a3dd5844588..3788c1cf7615 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalTabbedView.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalTabbedView.ts @@ -235,7 +235,7 @@ export class TerminalTabbedView extends Disposable { const ctx = offscreenCanvas.getContext('2d'); if (ctx) { const style = dom.getWindow(this._tabListElement).getComputedStyle(this._tabListElement); - ctx.font = `${style.fontStyle} ${style.fontSize} ${style.fontFamily}`; + ctx.font = `${style.fontStyle} ${style.fontSize} ${style.fontFamily}`.trimStart(); const maxInstanceWidth = this._terminalGroupService.instances.reduce((p, c) => { return Math.max(p, ctx.measureText(c.title + (c.description || '')).width + this._getAdditionalWidth(c)); }, 0); diff --git a/src/vs/workbench/contrib/terminal/browser/terminalTabsList.ts b/src/vs/workbench/contrib/terminal/browser/terminalTabsList.ts index 4fbf739c1283..9e1709bf4e57 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalTabsList.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalTabsList.ts @@ -426,7 +426,7 @@ class TerminalTabsRenderer implements IListRenderer<ITerminalInstance, ITerminal }); template.label.element.classList.toggle('editable-tab', !!editableData); if (editableData) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax template.elementDisposables.add(this._renderInputBox(template.label.element.querySelector('.monaco-icon-label-container')!, instance, editableData)); template.actionBar.clear(); } diff --git a/src/vs/workbench/contrib/terminal/browser/terminalView.ts b/src/vs/workbench/contrib/terminal/browser/terminalView.ts index d845f788366f..8f2d71e5e2a2 100644 --- a/src/vs/workbench/contrib/terminal/browser/terminalView.ts +++ b/src/vs/workbench/contrib/terminal/browser/terminalView.ts @@ -185,7 +185,7 @@ export class TerminalViewPane extends ViewPane { } } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention protected override renderBody(container: HTMLElement): void { super.renderBody(container); @@ -241,7 +241,7 @@ export class TerminalViewPane extends ViewPane { this._terminalTabbedView = this._register(this.instantiationService.createInstance(TerminalTabbedView, this._parentDomElement)); } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention protected override layoutBody(height: number, width: number): void { super.layoutBody(height, width); this._terminalTabbedView?.layout(width, height); @@ -462,7 +462,7 @@ class SingleTerminalTabActionViewItem extends MenuEntryActionViewItem { } } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention protected override updateLabel(e?: ITerminalInstance): void { // Only update if it's the active instance if (e && e !== this._terminalGroupService.activeInstance) { diff --git a/src/vs/workbench/contrib/terminal/browser/xterm-private.d.ts b/src/vs/workbench/contrib/terminal/browser/xterm-private.d.ts index e9a94fcd5dec..0903127bd1e5 100644 --- a/src/vs/workbench/contrib/terminal/browser/xterm-private.d.ts +++ b/src/vs/workbench/contrib/terminal/browser/xterm-private.d.ts @@ -16,6 +16,12 @@ export interface IXtermCore { onUserInput: IEvent<void>; }; + _bufferService: { + buffer: { + setWrapped(lineIndex: number, isWrapped: boolean): void; + }; + }; + viewport?: { readonly scrollBarWidth: number; _innerRefresh(): void; diff --git a/src/vs/workbench/contrib/terminal/browser/xterm/decorationAddon.ts b/src/vs/workbench/contrib/terminal/browser/xterm/decorationAddon.ts index 0294c9fae451..cbeb197c40dc 100644 --- a/src/vs/workbench/contrib/terminal/browser/xterm/decorationAddon.ts +++ b/src/vs/workbench/contrib/terminal/browser/xterm/decorationAddon.ts @@ -145,7 +145,7 @@ export class DecorationAddon extends Disposable implements ITerminalAddon, IDeco } private _updateGutterDecorationVisibility(): void { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const commandDecorationElements = this._terminal?.element?.querySelectorAll(DecorationSelector.CommandDecoration); if (commandDecorationElements) { for (const commandDecorationElement of commandDecorationElements) { diff --git a/src/vs/workbench/contrib/terminal/browser/xterm/terminalFontRendering.ts b/src/vs/workbench/contrib/terminal/browser/xterm/terminalFontRendering.ts index 2697b22f5aad..025262d6eaa5 100644 --- a/src/vs/workbench/contrib/terminal/browser/xterm/terminalFontRendering.ts +++ b/src/vs/workbench/contrib/terminal/browser/xterm/terminalFontRendering.ts @@ -12,6 +12,51 @@ const enum CssClasses { Grayscale = 'terminal-font-rendering-grayscale' } +const leadingCssWhitespace = /^[ \t\r\n\f]+/; +const patchedCanvasRealms = new WeakSet<Window>(); +let needsCanvasFontTrim: boolean | undefined; + +/** + * TODO(deepak1556): Remove once runtime fix is in place. + */ +export function ensureCanvasFontLeadingWhitespaceFix(targetWindow: Window): void { + if (needsCanvasFontTrim === undefined) { + const ctx = targetWindow.document.createElement('canvas').getContext('2d'); + if (ctx) { + ctx.font = ' 24px monospace'; + needsCanvasFontTrim = ctx.font === '10px sans-serif'; + } else { + needsCanvasFontTrim = false; + } + } + if (!needsCanvasFontTrim || patchedCanvasRealms.has(targetWindow)) { + return; + } + patchedCanvasRealms.add(targetWindow); + + const windowWithCtors = targetWindow as Window & typeof globalThis; + for (const ctor of [windowWithCtors.CanvasRenderingContext2D, windowWithCtors.OffscreenCanvasRenderingContext2D]) { + const proto = ctor?.prototype; + const descriptor = proto && Object.getOwnPropertyDescriptor(proto, 'font'); + if (!descriptor?.set) { + continue; + } + const originalSet = descriptor.set; + Object.defineProperty(proto, 'font', { + ...descriptor, + set(value: string) { + if (typeof value === 'string' && value.length > 0) { + const firstChar = value.charCodeAt(0); + if (firstChar === 32 /* ' ' */ || firstChar === 9 /* '\t' */ || firstChar === 10 /* '\n' */ || firstChar === 12 /* '\f' */ || firstChar === 13 /* '\r' */) { + value = value.replace(leadingCssWhitespace, ''); + } + } + originalSet.call(this, value); + } + }); + } +} + export function updateTerminalFontRendering(terminal: Terminal, fontRendering: ITerminalConfiguration['fontRendering']): void { const element = terminal.element; if (!element) { diff --git a/src/vs/workbench/contrib/terminal/browser/xterm/xtermTerminal.ts b/src/vs/workbench/contrib/terminal/browser/xterm/xtermTerminal.ts index 47a5ec2a558b..e42c8d7b0874 100644 --- a/src/vs/workbench/contrib/terminal/browser/xterm/xtermTerminal.ts +++ b/src/vs/workbench/contrib/terminal/browser/xterm/xtermTerminal.ts @@ -12,9 +12,10 @@ import type { SerializeAddon as SerializeAddonType } from '@xterm/addon-serializ import type { ImageAddon as ImageAddonType } from '@xterm/addon-image'; import type { ClipboardAddon as ClipboardAddonType } from '@xterm/addon-clipboard'; import * as dom from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; import { IXtermCore } from '../xterm-private.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; -import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { IEditorOptions } from '../../../../../editor/common/config/editorOptions.js'; import { IShellIntegration, ITerminalLogService, TerminalSettingId, type IDecorationAddon } from '../../../../../platform/terminal/common/terminal.js'; import { ITerminalFont, ITerminalConfiguration } from '../../common/terminal.js'; @@ -50,7 +51,7 @@ import { isNumber } from '../../../../../base/common/types.js'; import { clamp } from '../../../../../base/common/numbers.js'; import { LayoutSettings } from '../../../../services/layout/browser/layoutService.js'; import { ILifecycleService } from '../../../../services/lifecycle/common/lifecycle.js'; -import { updateTerminalFontRendering } from './terminalFontRendering.js'; +import { ensureCanvasFontLeadingWhitespaceFix, updateTerminalFontRendering } from './terminalFontRendering.js'; const enum RenderConstants { SmoothScrollDuration = 125 @@ -547,7 +548,7 @@ export class XtermTerminal extends Disposable implements IXtermTerminal, IDetach this._attached = { container, options }; // Screen must be created at this point as xterm.open is called - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax return this._attached?.container.querySelector('.xterm-screen')!; } @@ -730,6 +731,10 @@ export class XtermTerminal extends Disposable implements IXtermTerminal, IDetach return this._terminalConfigurationService.getFont(dom.getWindow(this.raw.element), this._core); } + setBufferLineWrapped(lineIndex: number, isWrapped: boolean): void { + this._core._bufferService.buffer.setWrapped(lineIndex, isWrapped); + } + getLongestViewportWrappedLineLength(): number { let maxLineLength = 0; for (let i = this.raw.buffer.active.length - 1; i >= this.raw.buffer.active.viewportY; i--) { @@ -830,6 +835,10 @@ export class XtermTerminal extends Disposable implements IXtermTerminal, IDetach this.raw.reset(); } + registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable { + return this.raw.parser.registerOscHandler(ident, callback); + } + hasSelection(): boolean { return this.raw.hasSelection(); } @@ -973,6 +982,7 @@ export class XtermTerminal extends Disposable implements IXtermTerminal, IDetach customGlyphs }); this._webglWindow = dom.getWindow(this.raw.element); + ensureCanvasFontLeadingWhitespaceFix(mainWindow); try { this.raw.loadAddon(this._webglAddon); this._logService.trace('Webgl was loaded'); @@ -1209,7 +1219,7 @@ export class XtermTerminal extends Disposable implements IXtermTerminal, IDetach } } - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention _writeText(data: string): void { this.raw.write(data); } diff --git a/src/vs/workbench/contrib/terminal/electron-browser/localPty.ts b/src/vs/workbench/contrib/terminal/electron-browser/localPty.ts index f11bf5e7db24..3ea1a99e28d6 100644 --- a/src/vs/workbench/contrib/terminal/electron-browser/localPty.ts +++ b/src/vs/workbench/contrib/terminal/electron-browser/localPty.ts @@ -15,7 +15,8 @@ export class LocalPty extends BasePty implements ITerminalChildProcess { constructor( id: number, shouldPersist: boolean, - private readonly _proxy: IPtyService + private readonly _proxy: IPtyService, + readonly isRevived: boolean = false ) { super(id, shouldPersist); } diff --git a/src/vs/workbench/contrib/terminal/electron-browser/localTerminalBackend.ts b/src/vs/workbench/contrib/terminal/electron-browser/localTerminalBackend.ts index a0e5774529c8..98b0ce43a1d6 100644 --- a/src/vs/workbench/contrib/terminal/electron-browser/localTerminalBackend.ts +++ b/src/vs/workbench/contrib/terminal/electron-browser/localTerminalBackend.ts @@ -221,11 +221,11 @@ export class LocalTerminalBackend extends BaseTerminalBackend implements ITermin return pty; } - async attachToProcess(id: number, pid?: number): Promise<ITerminalChildProcess | undefined> { + async attachToProcess(id: number, pid?: number, isRevived: boolean = false): Promise<ITerminalChildProcess | undefined> { await this._connectToDirectProxy(); try { await this._proxy.attachToProcess(id, pid); - const pty = new LocalPty(id, true, this._proxy); + const pty = new LocalPty(id, true, this._proxy, isRevived); this._ptys.set(id, pty); return pty; } catch (e) { @@ -239,7 +239,7 @@ export class LocalTerminalBackend extends BaseTerminalBackend implements ITermin try { const newId = await this._proxy.getRevivedPtyNewId(this._getWorkspaceId(), id); if (newId !== undefined) { - return await this.attachToProcess(newId); + return await this.attachToProcess(newId, undefined, true); } // The original ID may belong to another window's process after a pty host restart return await this.attachToProcess(id, pid > 0 ? pid : undefined); diff --git a/src/vs/workbench/contrib/terminal/test/browser/agentHostTerminalService.test.ts b/src/vs/workbench/contrib/terminal/test/browser/agentHostTerminalService.test.ts index 276754f40e5c..0fbe2844c566 100644 --- a/src/vs/workbench/contrib/terminal/test/browser/agentHostTerminalService.test.ts +++ b/src/vs/workbench/contrib/terminal/test/browser/agentHostTerminalService.test.ts @@ -27,7 +27,10 @@ import { AgentHostTerminalService } from '../../browser/agentHostTerminalService import { ICreateTerminalOptions, ITerminalChatService, ITerminalInstance, ITerminalService } from '../../browser/terminal.js'; import { ITerminalProfileProvider, ITerminalProfileService } from '../../common/terminal.js'; +let nextTestInstanceId = 1; + class TestTerminalInstance extends mock<ITerminalInstance>() { + override readonly instanceId = nextTestInstanceId++; override readonly store = new DisposableStore(); private readonly _onDisposed = this.store.add(new Emitter<ITerminalInstance>()); override readonly onDisposed = this._onDisposed.event; @@ -35,6 +38,10 @@ class TestTerminalInstance extends mock<ITerminalInstance>() { private _isDisposed = false; override get isDisposed(): boolean { return this._isDisposed; } + constructor(override readonly shellLaunchConfig: IShellLaunchConfig = {}) { + super(); + } + override dispose(): void { if (this._isDisposed) { return; @@ -50,6 +57,7 @@ class TestTerminalService extends mock<ITerminalService>() { readonly createdConfigs: IShellLaunchConfig[] = []; failNextCreation = false; disposeInstanceOnCreation = false; + onCreatingInstance: ((instance: ITerminalInstance) => void) | undefined; constructor(private readonly _store: Pick<DisposableStore, 'add'>) { super(); @@ -66,7 +74,8 @@ class TestTerminalService extends mock<ITerminalService>() { this.failNextCreation = false; throw new Error('terminal creation failed'); } - const instance = this._store.add(new TestTerminalInstance()); + const instance = this._store.add(new TestTerminalInstance(config as IShellLaunchConfig)); + this.onCreatingInstance?.(instance); if (this.disposeInstanceOnCreation) { instance.dispose(); } @@ -270,6 +279,19 @@ suite('AgentHostTerminalService', () => { }); }); + test('knows the host of a terminal from the moment the terminal service creates its instance', async () => { + store.add(service.registerEntry({ name: 'devbox', address: 'ssh://devbox', getConnection: () => connection })); + const addresses: (string | undefined)[] = []; + terminalService.onCreatingInstance = instance => addresses.push(service.getAgentHostAddress(instance)); + + const instance = await service.createTerminal(connection); + addresses.push(service.getAgentHostAddress(instance)); + // Another terminal launched with the same settings is not that terminal. + addresses.push(service.getAgentHostAddress(store.add(new TestTerminalInstance({ ...instance.shellLaunchConfig })))); + + assert.deepStrictEqual(addresses, ['ssh://devbox', 'ssh://devbox', undefined]); + }); + test('a failed terminal creation disposes the PTY registration', async () => { terminalService.failNextCreation = true; await assert.rejects(() => service.createTerminal(connection)); diff --git a/src/vs/workbench/contrib/terminal/test/browser/terminalEditor.test.ts b/src/vs/workbench/contrib/terminal/test/browser/terminalEditor.test.ts new file mode 100644 index 000000000000..8b4462c2796b --- /dev/null +++ b/src/vs/workbench/contrib/terminal/test/browser/terminalEditor.test.ts @@ -0,0 +1,109 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Codicon } from '../../../../../base/common/codicons.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { MenuItemAction } from '../../../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ITerminalProfile, TerminalLocation } from '../../../../../platform/terminal/common/terminal.js'; +import { TestEditorGroupView, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { ITerminalConfigurationService, ITerminalEditorService, ITerminalService } from '../../browser/terminal.js'; +import { TerminalEditor, TerminalEditorDropdownWithPrimaryActionViewItem } from '../../browser/terminalEditor.js'; +import { ITerminalProfileResolverService, ITerminalProfileService, TerminalCommandId } from '../../common/terminal.js'; + +suite('TerminalEditor - ActionViewItem regression', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('should support multiple action view items for create terminal dropdown without cross-disposing (#346848)', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + const contextKeyService = instantiationService.get(IContextKeyService); + const commandService = instantiationService.get(ICommandService); + + function createMenuItemAction(id: string): MenuItemAction { + return new MenuItemAction({ id, title: id, icon: Codicon.plus }, undefined, undefined, undefined, undefined, contextKeyService, commandService); + } + + const onDidChangeAvailableProfiles = store.add(new Emitter<ITerminalProfile[]>()); + instantiationService.stub(ITerminalProfileService, upcastPartial<ITerminalProfileService>({ + availableProfiles: [{ profileName: 'bash', path: '/bin/bash', isAutoDetected: false, isDefault: true }], + contributedProfiles: [], + getDefaultProfileName: () => 'bash', + onDidChangeAvailableProfiles: onDidChangeAvailableProfiles.event, + })); + + instantiationService.stub(ITerminalProfileResolverService, upcastPartial<ITerminalProfileResolverService>({ + defaultProfileName: 'bash' + })); + + instantiationService.stub(ITerminalService, upcastPartial<ITerminalService>({ + resolveLocation: () => Promise.resolve(TerminalLocation.Editor), + })); + + instantiationService.stub(ITerminalEditorService, upcastPartial<ITerminalEditorService>({ + setActiveInstance: () => { }, + instances: [], + })); + + instantiationService.stub(ITerminalConfigurationService, upcastPartial<ITerminalConfigurationService>({ + config: upcastPartial<ITerminalConfigurationService['config']>({ rightClickBehavior: 'default' }) + })); + + const editor = instantiationService.createInstance(TerminalEditor, new TestEditorGroupView(0)); + + const action1 = createMenuItemAction(TerminalCommandId.CreateTerminalEditorSameGroup); + const action2 = createMenuItemAction(TerminalCommandId.CreateTerminalEditorSameGroup); + + // Toolbar 1 requests action view item + const item1 = editor.getActionViewItem(action1, {}) as TerminalEditorDropdownWithPrimaryActionViewItem; + assert.ok(item1); + assert.strictEqual(item1.actionDisposables.isDisposed, false); + + // Toolbar 2 requests action view item (simulates pinned tabs row on separate row) + const item2 = editor.getActionViewItem(action2, {}) as TerminalEditorDropdownWithPrimaryActionViewItem; + assert.ok(item2); + assert.notStrictEqual(item1, item2); + assert.strictEqual(item2.actionDisposables.isDisposed, false); + + // Regression verification: item1 must NOT have been disposed when item2 was requested + assert.strictEqual(item1.actionDisposables.isDisposed, false); + + // Spy on update calls + let item1Updates = 0; + let item2Updates = 0; + const origUpdate1 = item1.update.bind(item1); + item1.update = (dropdownAction, dropdownMenuActions) => { + item1Updates++; + origUpdate1(dropdownAction, dropdownMenuActions); + }; + const origUpdate2 = item2.update.bind(item2); + item2.update = (dropdownAction, dropdownMenuActions) => { + item2Updates++; + origUpdate2(dropdownAction, dropdownMenuActions); + }; + + // Profile change should update both items without disposing them + onDidChangeAvailableProfiles.fire([{ profileName: 'zsh', path: '/bin/zsh', isAutoDetected: false, isDefault: true }]); + assert.strictEqual(item1Updates, 1); + assert.strictEqual(item2Updates, 1); + assert.strictEqual(item1.actionDisposables.isDisposed, false); + assert.strictEqual(item2.actionDisposables.isDisposed, false); + + // Disposing item1 cleans up only item1 + item1.dispose(); + assert.strictEqual(item1.actionDisposables.isDisposed, true); + assert.strictEqual(item2.actionDisposables.isDisposed, false); + + onDidChangeAvailableProfiles.fire([{ profileName: 'fish', path: '/bin/fish', isAutoDetected: false, isDefault: true }]); + assert.deepStrictEqual({ item1Updates, item2Updates }, { item1Updates: 1, item2Updates: 2 }); + + // Disposing the editor cleans up the remaining active dropdowns (item2) + editor.dispose(); + assert.strictEqual(item2.actionDisposables.isDisposed, true); + }); +}); diff --git a/src/vs/workbench/contrib/terminal/test/browser/terminalInstance.test.ts b/src/vs/workbench/contrib/terminal/test/browser/terminalInstance.test.ts index f132896baec7..166db4e0cc94 100644 --- a/src/vs/workbench/contrib/terminal/test/browser/terminalInstance.test.ts +++ b/src/vs/workbench/contrib/terminal/test/browser/terminalInstance.test.ts @@ -348,6 +348,23 @@ suite('Workbench - TerminalInstance', () => { strictEqual(second.fixedCols, undefined); }); + test('keeps the prompt when shown before its view has a valid layout', async () => { + const instance = await createTerminalInstance(); + // While a view is first laid out its container can have a temporary width but a valid height + const container = document.createElement('div'); + container.style.width = '120px'; + container.style.height = '300px'; + document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + instance.attachToElement(container); + const prompt = 'PS /Users/user/Desktop/vscode> '; + await writeP(instance.xterm!.raw, prompt); + instance.layout(new Dimension(120, -22)); + instance.setVisible(true); + instance.layout(new Dimension(800, 300)); + strictEqual(instance.xterm!.raw.buffer.active.getLine(0)?.translateToString(true), prompt); + }); + test('should create an instance of TerminalInstance with env from default profile', async () => { terminalInstance = await createTerminalInstance(); // Wait for the terminal instance to resolve shell launch config env. diff --git a/src/vs/workbench/contrib/terminal/test/browser/terminalProcessManager.test.ts b/src/vs/workbench/contrib/terminal/test/browser/terminalProcessManager.test.ts index 1600d57a3002..c899e33b45d3 100644 --- a/src/vs/workbench/contrib/terminal/test/browser/terminalProcessManager.test.ts +++ b/src/vs/workbench/contrib/terminal/test/browser/terminalProcessManager.test.ts @@ -11,19 +11,23 @@ import { Schemas } from '../../../../../base/common/network.js'; import { getCaseInsensitive } from '../../../../../base/common/objects.js'; import { isWindows, OperatingSystem, type IProcessEnvironment } from '../../../../../base/common/platform.js'; import { URI } from '../../../../../base/common/uri.js'; +import { hasKey } from '../../../../../base/common/types.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { IConfigurationService, type IConfigurationChangeEvent } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { EnvironmentVariableMutatorType, type IEnvironmentVariableCollection } from '../../../../../platform/terminal/common/environmentVariable.js'; import { ITerminalChildProcess, TitleEventSource, type IProcessReadyEvent, type ITerminalBackend, type ITerminalProcessOptions } from '../../../../../platform/terminal/common/terminal.js'; import { ITerminalInstanceService, ITerminalService } from '../../browser/terminal.js'; import { TerminalProcessManager } from '../../browser/terminalProcessManager.js'; +import { RemotePty } from '../../browser/remotePty.js'; +import { RemoteTerminalChannelClient } from '../../common/remote/remoteTerminalChannel.js'; import { IEnvironmentVariableService } from '../../common/environmentVariable.js'; import { IRemoteAgentService } from '../../../../services/remote/common/remoteAgentService.js'; import { IHostService } from '../../../../services/host/browser/host.js'; import { IRemoteAgentEnvironment } from '../../../../../platform/remote/common/remoteAgentEnvironment.js'; import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { IWorkspaceTrustManagementService } from '../../../../../platform/workspace/common/workspaceTrust.js'; function listenerCount(emitter: Emitter<unknown>): number { return (emitter as unknown as { _size: number })._size ?? 0; @@ -154,6 +158,157 @@ suite('Workbench - TerminalProcessManager', () => { return options.environmentVariableCollections?.flatMap(([, collection]) => collection.map(([, mutator]) => mutator.variable)) ?? []; } + for (const remote of [false, true]) { + test(`revalidates task trust after ${remote ? 'remote' : 'local'} environment preparation without restricting ordinary terminals`, async () => { + const trust = instantiationService.get(IWorkspaceTrustManagementService); + const entered = new DeferredPromise<void>(); + const pending = new DeferredPromise<void>(); + const backend = await terminalInstanceService.getBackend(); + backend.getShellEnvironment = async () => { + await entered.complete(); + await pending.p; + return {}; + }; + instantiationService.stub(ITerminalInstanceService, { getBackend: async () => backend }); + if (remote) { + instantiationService.stub(IRemoteAgentService, { + getEnvironment: async () => upcastPartial<IRemoteAgentEnvironment>({ os: OperatingSystem.Linux, userHome: URI.file('/home/test') }) + }); + } + const taskManager = store.add(instantiationService.createInstance(TerminalProcessManager, 2, + remote ? URI.from({ scheme: Schemas.vscodeRemote, authority: 'test-remote', path: '/workspace' }) : undefined, undefined, undefined)); + const execution = taskManager.createProcess({ type: 'Task', isFeatureTerminal: true }, 80, 24, false); + await entered.p; + await trust.setWorkspaceTrust(false); + await pending.complete(); + const result = await execution; + ok(result && hasKey(result, { message: true }) && result.message.includes('workspace is no longer trusted')); + const taskLaunches = terminalInstanceService.createdProcesses.length; + await taskManager.createProcess({}, 80, 24, false); + deepStrictEqual({ taskLaunches, ordinaryLaunches: terminalInstanceService.createdProcesses.length }, { taskLaunches: 0, ordinaryLaunches: 1 }); + }); + } + + test('shuts down an unstarted task process when trust is revoked while the backend prepares it', async () => { + const trust = instantiationService.get(IWorkspaceTrustManagementService); + const entered = new DeferredPromise<void>(); + const pending = new DeferredPromise<void>(); + const backend = await terminalInstanceService.getBackend(); + const createProcess = backend.createProcess; + backend.createProcess = async (...args) => { + const child = await createProcess(...args); + await entered.complete(); + await pending.p; + return child; + }; + instantiationService.stub(ITerminalInstanceService, { getBackend: async () => backend }); + const taskManager = store.add(instantiationService.createInstance(TerminalProcessManager, 2, undefined, undefined, undefined)); + const execution = taskManager.createProcess({ type: 'Task', isFeatureTerminal: true }, 80, 24, false); + await entered.p; + const child = terminalInstanceService.createdProcesses[0]; + const shutdownCalls: boolean[] = []; + child.shutdown = immediate => shutdownCalls.push(immediate); + await trust.setWorkspaceTrust(false); + await pending.complete(); + const result = await execution; + deepStrictEqual({ + cancelled: result && hasKey(result, { message: true }) && result.message.includes('workspace is no longer trusted'), + startCalls: child.calls.filter(call => call === 'start'), + shutdownCalls + }, { cancelled: true, startCalls: [], shutdownCalls: [false] }); + }); + + for (const remote of [false, true]) { + for (const attachment of ['new', 'live', 'live with revival lookup', 'revived', 'unstarted'] as const) { + for (const cancellation of ['trust', 'disposal'] as const) { + test(`releases a ${remote ? 'remote' : 'local'} ${attachment} process safely after ${cancellation}`, async () => { + const trust = instantiationService.get(IWorkspaceTrustManagementService); + const entered = new DeferredPromise<void>(); + const pending = new DeferredPromise<void>(); + const calls: string[] = []; + const allocations = new Set([1]); + const isLiveAttachment = attachment === 'live' || attachment === 'live with revival lookup'; + const channel = new class extends mock<RemoteTerminalChannelClient>() { + override async start() { calls.push('start'); return undefined; } + override async shutdown(id: number, immediate: boolean) { + calls.push(`shutdown ${immediate}`); + allocations.delete(id); + } + override async detachFromProcess() { calls.push('detach'); } + }; + const child = remote + ? store.add(instantiationService.createInstance(RemotePty, 1, true, channel)) + : Object.assign(new TestTerminalChildProcess(true), { + isRevived: attachment === 'revived', + async detach() { calls.push('detach'); }, + shutdown(immediate: boolean) { calls.push(`shutdown ${immediate}`); allocations.delete(1); }, + async start() { calls.push('start'); return undefined; } + }); + const backend = await terminalInstanceService.getBackend(); + const attach = async () => { + await entered.complete(); + await pending.p; + return child; + }; + backend.attachToProcess = attach; + backend.attachToRevivedProcess = attach; + backend.createProcess = attach; + instantiationService.stub(ITerminalInstanceService, { getBackend: async () => backend }); + if (remote) { + instantiationService.stub(IRemoteAgentService, { + getEnvironment: async () => upcastPartial<IRemoteAgentEnvironment>({ os: OperatingSystem.Linux, userHome: URI.file('/home/test') }) + }); + } + const taskManager = store.add(instantiationService.createInstance(TerminalProcessManager, 2, + remote ? URI.from({ scheme: Schemas.vscodeRemote, authority: 'test-remote', path: '/workspace' }) : undefined, undefined, undefined)); + const execution = taskManager.createProcess({ + type: 'Task', + attachPersistentProcess: attachment === 'new' ? undefined : { + id: 1, pid: attachment === 'unstarted' || (remote && attachment === 'revived') ? -1 : 123, + findRevivedId: attachment === 'revived' || attachment === 'live with revival lookup', title: 'task', titleSource: TitleEventSource.Process, cwd: '', shellIntegrationNonce: '' + } + }, 80, 24, false); + await entered.p; + if (cancellation === 'trust') { + await trust.setWorkspaceTrust(false); + } else { + taskManager.dispose(); + } + await pending.complete(); + const result = await execution; + taskManager.dispose(); + deepStrictEqual({ + cancelled: !!(result && hasKey(result, { message: true }) && result.message.includes('workspace is no longer trusted')), + calls, + allocations: [...allocations] + }, { + cancelled: cancellation === 'trust', + calls: [isLiveAttachment ? 'detach' : `shutdown ${remote}`], + allocations: isLiveAttachment ? [1] : [] + }); + }); + } + } + } + + test('does not start a custom task terminal after trust is revoked', async () => { + const trust = instantiationService.get(IWorkspaceTrustManagementService); + const child = new TestTerminalChildProcess(false); + const trustChanges: Promise<void>[] = []; + const result = await manager.createProcess({ + type: 'Task', + customPtyImplementation: () => { + trustChanges.push(trust.setWorkspaceTrust(false)); + return child; + } + }, 80, 24, false); + await Promise.all(trustChanges); + deepStrictEqual({ + cancelled: result && hasKey(result, { message: true }) && result.message.includes('workspace is no longer trusted'), + startCalls: child.calls.filter(call => call === 'start') + }, { cancelled: true, startCalls: [] }); + }); + test('does not apply or serialize PATH from a different terminal host while retaining non-PATH variables', async () => { setCollection('foreign.extension', { remoteAuthority: 'ssh-remote+foreign-host', diff --git a/src/vs/workbench/contrib/terminal/test/browser/xterm/xtermTerminal.test.ts b/src/vs/workbench/contrib/terminal/test/browser/xterm/xtermTerminal.test.ts index 98538c54d50c..5db843ce5c14 100644 --- a/src/vs/workbench/contrib/terminal/test/browser/xterm/xtermTerminal.test.ts +++ b/src/vs/workbench/contrib/terminal/test/browser/xterm/xtermTerminal.test.ts @@ -116,6 +116,28 @@ suite('XtermTerminal', () => { strictEqual(xterm.raw.rows, 30); }); + for (const buffer of ['normal', 'alternate'] as const) { + test(`setBufferLineWrapped updates the active ${buffer} buffer`, async () => { + xterm.raw.resize(5, 3); + if (buffer === 'alternate') { + await write('\x1b[?1049h'); + } + await write('12345678901'); + const before = Array.from({ length: 3 }, (_, lineIndex) => xterm.raw.buffer.active.getLine(lineIndex)?.isWrapped); + xterm.setBufferLineWrapped(1, false); + const after = Array.from({ length: 3 }, (_, lineIndex) => xterm.raw.buffer.active.getLine(lineIndex)?.isWrapped); + deepStrictEqual({ + activeBuffer: xterm.raw.buffer.active.type, + before, + after + }, { + activeBuffer: buffer, + before: [false, true, true], + after: [false, false, true] + }); + }); + } + for (const buffer of ['normal', 'alternate'] as const) { test(`clearBuffer should ${buffer === 'normal' ? 'clear rich and partial command history including scrollback' : 'preserve normal-buffer command history and decorations when clearing the alternate buffer'}`, async () => { class TestTerminal extends XTermBaseCtor { diff --git a/src/vs/workbench/contrib/terminal/test/electron-browser/localTerminalBackend.test.ts b/src/vs/workbench/contrib/terminal/test/electron-browser/localTerminalBackend.test.ts index bfd6ecb454cd..6b1d2068f3ed 100644 --- a/src/vs/workbench/contrib/terminal/test/electron-browser/localTerminalBackend.test.ts +++ b/src/vs/workbench/contrib/terminal/test/electron-browser/localTerminalBackend.test.ts @@ -78,7 +78,7 @@ suite('LocalTerminalBackend', () => { if (pty instanceof LocalPty) { store.add(pty); } - return { attachedId: pty?.id, requests: [...attachRequests] }; + return { attachedId: pty?.id, isRevived: pty?.isRevived, requests: [...attachRequests] }; } deepStrictEqual({ @@ -92,15 +92,15 @@ suite('LocalTerminalBackend', () => { originalMissing: await attach(() => backend.attachToRevivedProcess(4, 404)), attachById: await attach(() => backend.attachToProcess(3)), }, { - revivedWithNewId: { attachedId: 1, requests: [[1, undefined]] }, - revivedWithSameId: { attachedId: 2, requests: [[2, undefined]] }, - revivedButMissing: { attachedId: undefined, requests: [[5, undefined]] }, - originalWithSavedPid: { attachedId: 3, requests: [[3, 303]] }, - originalWithOtherPid: { attachedId: undefined, requests: [[3, 9009]] }, - originalWithUnknownPid: { attachedId: 3, requests: [[3, undefined]] }, - originalWithNegativePid: { attachedId: 3, requests: [[3, undefined]] }, - originalMissing: { attachedId: undefined, requests: [[4, 404]] }, - attachById: { attachedId: 3, requests: [[3, undefined]] }, + revivedWithNewId: { attachedId: 1, isRevived: true, requests: [[1, undefined]] }, + revivedWithSameId: { attachedId: 2, isRevived: true, requests: [[2, undefined]] }, + revivedButMissing: { attachedId: undefined, isRevived: undefined, requests: [[5, undefined]] }, + originalWithSavedPid: { attachedId: 3, isRevived: false, requests: [[3, 303]] }, + originalWithOtherPid: { attachedId: undefined, isRevived: undefined, requests: [[3, 9009]] }, + originalWithUnknownPid: { attachedId: 3, isRevived: false, requests: [[3, undefined]] }, + originalWithNegativePid: { attachedId: 3, isRevived: false, requests: [[3, undefined]] }, + originalMissing: { attachedId: undefined, isRevived: undefined, requests: [[4, 404]] }, + attachById: { attachedId: 3, isRevived: false, requests: [[3, undefined]] }, }); }); diff --git a/src/vs/workbench/contrib/terminalContrib/autoReplies/browser/terminal.autoReplies.contribution.ts b/src/vs/workbench/contrib/terminalContrib/autoReplies/browser/terminal.autoReplies.contribution.ts index da977e986f21..e397d4498277 100644 --- a/src/vs/workbench/contrib/terminalContrib/autoReplies/browser/terminal.autoReplies.contribution.ts +++ b/src/vs/workbench/contrib/terminalContrib/autoReplies/browser/terminal.autoReplies.contribution.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { raceTimeout } from '../../../../../base/common/async.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; import { generateUuid } from '../../../../../base/common/uuid.js'; import { localize } from '../../../../../nls.js'; @@ -14,6 +15,14 @@ import { ITerminalInstanceService } from '../../../terminal/browser/terminal.js' import { TERMINAL_CONFIG_SECTION } from '../../../terminal/common/terminal.js'; import { TerminalAutoRepliesSettingId, type ITerminalAutoRepliesConfiguration } from '../common/terminalAutoRepliesConfiguration.js'; +const enum Constants { + /** + * How long shutdown waits for a backend to remove this window's auto replies. A pty host that + * never answers must not block quitting, reloading or closing the window. + */ + ShutdownCleanupTimeout = 2000 +} + // #region Workbench contributions export class TerminalAutoRepliesContribution extends Disposable implements IWorkbenchContribution { @@ -35,6 +44,10 @@ export class TerminalAutoRepliesContribution extends Disposable implements IWork } private _installListenersOnBackend(backend: ITerminalBackend): void { + // Only replies this window installed need removing on shutdown, so most windows never call + // into the backend while shutting down + let hasInstalledAutoReplies = false; + // Listen for config changes const initialConfig = this._configurationService.getValue<ITerminalAutoRepliesConfiguration>(TERMINAL_CONFIG_SECTION); for (const match of Object.keys(initialConfig.autoReplies)) { @@ -42,6 +55,7 @@ export class TerminalAutoRepliesContribution extends Disposable implements IWork const reply = initialConfig.autoReplies[match] as string | null; if (reply) { backend.installAutoReply(match, reply, this._ownerId); + hasInstalledAutoReplies = true; } } @@ -54,14 +68,18 @@ export class TerminalAutoRepliesContribution extends Disposable implements IWork const reply = config.autoReplies[match] as string | null; if (reply) { backend.installAutoReply(match, reply, this._ownerId); + hasInstalledAutoReplies = true; } } } })); this._register(this._lifecycleService.onWillShutdown(e => { configListener.dispose(); + if (!hasInstalledAutoReplies) { + return; + } // Finish while remote IPC is still connected, before the final disconnect joiner. - e.join(backend.uninstallAllAutoReplies(this._ownerId), { + e.join(raceTimeout(backend.uninstallAllAutoReplies(this._ownerId), Constants.ShutdownCleanupTimeout), { id: 'join.terminalAutoReplies', label: localize('removeTerminalAutoReplies', "Remove Terminal Auto Replies") }); diff --git a/src/vs/workbench/contrib/terminalContrib/autoReplies/test/browser/terminalAutoRepliesContribution.test.ts b/src/vs/workbench/contrib/terminalContrib/autoReplies/test/browser/terminalAutoRepliesContribution.test.ts index 8ac2711073d8..36f62d5369c1 100644 --- a/src/vs/workbench/contrib/terminalContrib/autoReplies/test/browser/terminalAutoRepliesContribution.test.ts +++ b/src/vs/workbench/contrib/terminalContrib/autoReplies/test/browser/terminalAutoRepliesContribution.test.ts @@ -63,13 +63,14 @@ suite('TerminalAutoRepliesContribution', () => { let disconnected = false; const lifecycleService = createLifecycleService(() => { disconnected = true; }); const makeBackend = (name: string): ITerminalBackend => new class extends mock<ITerminalBackend>() { + override async installAutoReply(): Promise<void> { } override uninstallAllAutoReplies(): Promise<void> { calls.push(name); return cleanup.p; } }; const didRegisterBackend = store.add(new Emitter<ITerminalBackend>()); - const configurationService = new TestConfigurationService({ 'terminal.integrated': { autoReplies: {} } }); + const configurationService = new TestConfigurationService({ 'terminal.integrated': { autoReplies: { 'prompt': 'reply' } } }); store.add(configurationService.onDidChangeConfigurationEmitter); const contribution = store.add(new TerminalAutoRepliesContribution(configurationService, createInstanceService([makeBackend('local')], didRegisterBackend.event), lifecycleService)); didRegisterBackend.fire(makeBackend('remote')); @@ -114,4 +115,67 @@ suite('TerminalAutoRepliesContribution', () => { assert.deepStrictEqual({ owners: [...activeOwners], installCount }, { owners: ['live peer'], installCount: 1 }); } })); + + test('does not block shutdown when the backend never finishes cleanup', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + let cleanupStarted = false; + let disconnected = false; + const lifecycleService = createLifecycleService(() => { disconnected = true; }); + const backend = new class extends mock<ITerminalBackend>() { + override async installAutoReply(): Promise<void> { } + override uninstallAllAutoReplies(): Promise<void> { + cleanupStarted = true; + // An unresponsive pty host never answers + return new Promise<void>(() => { }); + } + }; + const configurationService = new TestConfigurationService({ 'terminal.integrated': { autoReplies: { 'prompt': 'reply' } } }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const contribution = store.add(new TerminalAutoRepliesContribution(configurationService, createInstanceService([backend]), lifecycleService)); + + await lifecycleService.shutdown(); + contribution.dispose(); + assert.deepStrictEqual({ cleanupStarted, disconnected }, { cleanupStarted: true, disconnected: true }); + })); + + test('does not call the backend on shutdown when no auto replies were installed', async () => { + const calls: string[] = []; + let disconnected = false; + const lifecycleService = createLifecycleService(() => { disconnected = true; }); + const backend = new class extends mock<ITerminalBackend>() { + override async uninstallAllAutoReplies(): Promise<void> { + calls.push('uninstall'); + } + }; + const configurationService = new TestConfigurationService({ 'terminal.integrated': { autoReplies: {} } }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const contribution = store.add(new TerminalAutoRepliesContribution(configurationService, createInstanceService([backend]), lifecycleService)); + + await lifecycleService.shutdown(); + contribution.dispose(); + assert.deepStrictEqual({ calls, disconnected }, { calls: [], disconnected: true }); + }); + + test('cleans up auto replies installed by a setting change', async () => { + const calls: string[] = []; + const lifecycleService = createLifecycleService(() => { }); + const backend = new class extends mock<ITerminalBackend>() { + override async installAutoReply(match: string): Promise<void> { + calls.push(`install ${match}`); + } + override async uninstallAllAutoReplies(): Promise<void> { + calls.push('uninstall'); + } + }; + const configurationService = new TestConfigurationService({ 'terminal.integrated': { autoReplies: {} } }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const contribution = store.add(new TerminalAutoRepliesContribution(configurationService, createInstanceService([backend]), lifecycleService)); + + await configurationService.setUserConfiguration('terminal.integrated', { autoReplies: { 'prompt': 'reply' } }); + configurationService.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: () => true, affectedKeys: new Set(), change: { keys: [], overrides: [] }, source: ConfigurationTarget.USER + }); + await lifecycleService.shutdown(); + contribution.dispose(); + assert.deepStrictEqual(calls, ['uninstall', 'install prompt', 'uninstall']); + }); }); diff --git a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminal.chatAgentTools.contribution.ts b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminal.chatAgentTools.contribution.ts index 294aab71f971..daf14763659a 100644 --- a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminal.chatAgentTools.contribution.ts +++ b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminal.chatAgentTools.contribution.ts @@ -16,7 +16,9 @@ import { registerWorkbenchContribution2, WorkbenchPhase, type IWorkbenchContribu import { IChatWidgetService } from '../../../chat/browser/chat.js'; import { ChatContextKeys } from '../../../chat/common/actions/chatContextKeys.js'; import { ChatConfiguration } from '../../../chat/common/constants.js'; +import { ILanguageModelToolsConfirmationService } from '../../../chat/common/tools/languageModelToolsConfirmationService.js'; import { ILanguageModelToolsService } from '../../../chat/common/tools/languageModelToolsService.js'; +import { TerminalToolId } from '../../../chat/common/tools/terminalToolIds.js'; import { IToolResultCompressor } from '../../../chat/common/tools/toolResultCompressor.js'; import { registerActiveInstanceAction, sharedWhenClause } from '../../../terminal/browser/terminalActions.js'; import { TerminalContextMenuGroup } from '../../../terminal/browser/terminalMenus.js'; @@ -25,6 +27,7 @@ import { TerminalChatAgentToolsCommandId } from '../common/terminal.chatAgentToo import { TerminalChatAgentToolsSettingId } from '../common/terminalChatAgentToolsConfiguration.js'; import { AgentNetworkDomainSettingId } from '../../../../../platform/networkFilter/common/settings.js'; import { AgentHostSandboxForwarder } from './agentHostSandboxForwarder.js'; +import { TerminalToolConfirmationContribution } from './terminalToolConfirmationContribution.js'; import { GetTerminalLastCommandTool, GetTerminalLastCommandToolData } from './tools/getTerminalLastCommandTool.js'; import { KillTerminalTool, KillTerminalToolData } from './tools/killTerminalTool.js'; import { GetTerminalOutputTool, GetTerminalOutputToolData } from './tools/getTerminalOutputTool.js'; @@ -93,6 +96,7 @@ export class ChatAgentToolsContribution extends Disposable implements IWorkbench @ILanguageModelToolsService private readonly _toolsService: ILanguageModelToolsService, @IConfigurationService private readonly _configurationService: IConfigurationService, @IToolResultCompressor toolResultCompressor: IToolResultCompressor, + @ILanguageModelToolsConfirmationService private readonly _confirmationService: ILanguageModelToolsConfirmationService, ) { super(); @@ -179,6 +183,7 @@ export class ChatAgentToolsContribution extends Disposable implements IWorkbench const store = new DisposableStore(); store.add(this._toolsService.registerToolData(runInTerminalToolData)); store.add(this._toolsService.registerToolImplementation(runInTerminalToolData.id, this._runInTerminalTool)); + store.add(this._confirmationService.registerConfirmationContribution(TerminalToolId.RunInTerminal, this._instantiationService.createInstance(TerminalToolConfirmationContribution))); store.add(this._toolsService.executeToolSet.addTool(runInTerminalToolData)); this._runInTerminalToolRegistration.value = store; }); diff --git a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminalToolConfirmationContribution.ts b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminalToolConfirmationContribution.ts new file mode 100644 index 000000000000..0ce7771a6c70 --- /dev/null +++ b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/browser/terminalToolConfirmationContribution.ts @@ -0,0 +1,97 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Codicon } from '../../../../../base/common/codicons.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; +import { localize } from '../../../../../nls.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IQuickInputButton, IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IPreferencesService } from '../../../../services/preferences/common/preferences.js'; +import { ILanguageModelToolConfirmationContribution, ILanguageModelToolConfirmationContributionQuickTreeItem } from '../../../chat/common/tools/languageModelToolsConfirmationService.js'; +import { TerminalChatAgentToolsSettingId } from '../common/terminalChatAgentToolsConfiguration.js'; + +type TerminalAutoApproveRules = Record<string, boolean | null | { approve: boolean; matchCommandLine?: boolean }>; + +const trashButton: IQuickInputButton = { + iconClass: ThemeIcon.asClassName(Codicon.trash), + tooltip: localize('delete', "Delete") +}; + +/** Contributes user command rules to the tool approval picker. */ +export class TerminalToolConfirmationContribution implements ILanguageModelToolConfirmationContribution { + constructor( + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IQuickInputService private readonly _quickInputService: IQuickInputService, + @IPreferencesService private readonly _preferencesService: IPreferencesService + ) { } + + getManageActions(): ILanguageModelToolConfirmationContributionQuickTreeItem[] { + const items: ILanguageModelToolConfirmationContributionQuickTreeItem[] = []; + + for (const [command, rule] of Object.entries(this._getUserRules())) { + if (rule === null) { + continue; + } + const approved = typeof rule === 'boolean' ? rule : rule.approve; + const description = approved ? localize('autoApproved', "Auto-approved") : localize('requiresApproval', "Requires approval"); + items.push({ + id: `terminal/${command}`, + label: command, + description: typeof rule === 'object' && rule.matchCommandLine + ? localize('fullCommandLine', "{0}, full command line", description) + : description, + checked: approved, + buttons: [trashButton], + onDidChangeChecked: async checked => { + const rules = this._getUserRules(); + await this._configurationService.updateValue(TerminalChatAgentToolsSettingId.AutoApprove, { + ...rules, + [command]: typeof rule === 'boolean' ? checked : { ...rule, approve: checked } + }, ConfigurationTarget.USER); + }, + onDidTriggerItemButton: async button => { + if (button !== trashButton) { + return; + } + const rules = { ...this._getUserRules() }; + delete rules[command]; + await this._configurationService.updateValue(TerminalChatAgentToolsSettingId.AutoApprove, rules, ConfigurationTarget.USER); + } + }); + } + + items.push({ + pickable: false, + label: localize('addCommandRule', "Add Command Rule..."), + onDidOpen: async () => { + const command = (await this._quickInputService.input({ + prompt: localize('addCommandRulePrompt', "Enter a command prefix to run without approval, e.g. npm test, or a /regex/"), + validateInput: async value => value.trim() ? undefined : localize('commandRuleRequired', "Enter a command prefix or regular expression.") + }))?.trim(); + if (!command) { + return; + } + await this._configurationService.updateValue(TerminalChatAgentToolsSettingId.AutoApprove, { + ...this._getUserRules(), + [command]: true + }, ConfigurationTarget.USER); + } + }, { + pickable: false, + label: localize('moreOptions', "More Options..."), + description: localize('openSettings', "Open settings"), + closesPicker: true, + onDidOpen: async () => { + await this._preferencesService.openUserSettings({ query: TerminalChatAgentToolsSettingId.AutoApprove }); + } + }); + + return items; + } + + private _getUserRules(): TerminalAutoApproveRules { + return this._configurationService.inspect<TerminalAutoApproveRules>(TerminalChatAgentToolsSettingId.AutoApprove).userValue ?? {}; + } +} diff --git a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/browser/terminalToolConfirmationContribution.test.ts b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/browser/terminalToolConfirmationContribution.test.ts new file mode 100644 index 000000000000..20f1bc76ec57 --- /dev/null +++ b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/browser/terminalToolConfirmationContribution.test.ts @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IInputOptions, IQuickInputService } from '../../../../../../platform/quickinput/common/quickInput.js'; +import { IPreferencesService } from '../../../../../services/preferences/common/preferences.js'; +import { TerminalToolConfirmationContribution } from '../../browser/terminalToolConfirmationContribution.js'; +import { TerminalChatAgentToolsSettingId } from '../../common/terminalChatAgentToolsConfiguration.js'; + +suite('TerminalToolConfirmationContribution', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + test('manages user command rules without changing their matching scope', async () => { + const setting = TerminalChatAgentToolsSettingId.AutoApprove; + const configurationService = new TestConfigurationService({ + [setting]: { + git: true, + rm: false, + '/deploy/': { approve: false, matchCommandLine: true }, + node: { approve: true, matchCommandLine: false }, + ignored: null, + } + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const update = sinon.stub(configurationService, 'updateValue').callsFake((key, value) => configurationService.setUserConfiguration(key, value)); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + const inputs = [' npm test ', undefined, ' ', '/test/']; + let inputOptions: IInputOptions | undefined; + instantiationService.stub(IQuickInputService, { + input: async options => { + inputOptions = options; + return inputs.shift(); + } + }); + const settingsQueries: (string | undefined)[] = []; + instantiationService.stub(IPreferencesService, { + openUserSettings: async options => { + settingsQueries.push(options?.query); + return undefined; + } + }); + const contribution = instantiationService.createInstance(TerminalToolConfirmationContribution); + const items = contribution.getManageActions(); + const initialItems = items.map(item => [item.label, item.description, item.checked, item.pickable, item.buttons?.map(button => button.tooltip)]); + for (const item of items.slice(0, 4)) { + await item.onDidChangeChecked!(!item.checked); + } + const toggledRules = configurationService.inspect(setting).userValue; + const removeItem = items[1]; + await removeItem.onDidTriggerItemButton!(removeItem.buttons![0]); + const addItem = items[4]; + for (let index = 0; index < 4; index++) { + await addItem.onDidOpen!(); + } + await items[5].onDidOpen!(); + + assert.deepStrictEqual({ + initialItems, + toggledRules, + rules: configurationService.inspect(setting).userValue, + writeCount: update.callCount, + userSettingsOnly: update.args.every(arguments_ => arguments_.at(-1) === ConfigurationTarget.USER), + validation: await Promise.all(['', ' ', 'npm test'].map(value => inputOptions?.validateInput?.(value))), + settingsQueries, + }, { + initialItems: [ + ['git', 'Auto-approved', true, undefined, ['Delete']], + ['rm', 'Requires approval', false, undefined, ['Delete']], + ['/deploy/', 'Requires approval, full command line', false, undefined, ['Delete']], + ['node', 'Auto-approved', true, undefined, ['Delete']], + ['Add Command Rule...', undefined, undefined, false, undefined], + ['More Options...', 'Open settings', undefined, false, undefined], + ], + toggledRules: { + git: false, + rm: true, + '/deploy/': { approve: true, matchCommandLine: true }, + node: { approve: false, matchCommandLine: false }, + ignored: null, + }, + rules: { + git: false, + '/deploy/': { approve: true, matchCommandLine: true }, + node: { approve: false, matchCommandLine: false }, + ignored: null, + 'npm test': true, + '/test/': true, + }, + writeCount: 7, + userSettingsOnly: true, + validation: ['Enter a command prefix or regular expression.', 'Enter a command prefix or regular expression.', undefined], + settingsQueries: [setting], + }); + }); +}); diff --git a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/electron-browser/runInTerminalTool.test.ts b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/electron-browser/runInTerminalTool.test.ts index 819aceb8652a..ebec59105f68 100644 --- a/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/electron-browser/runInTerminalTool.test.ts +++ b/src/vs/workbench/contrib/terminalContrib/chatAgentTools/test/electron-browser/runInTerminalTool.test.ts @@ -43,6 +43,7 @@ import { LocalChatSessionUri } from '../../../../chat/common/model/chatUri.js'; import { ChatRequestTextPart } from '../../../../chat/common/requestParser/chatParserTypes.js'; import { ITerminalSandboxService, TerminalSandboxPrerequisiteCheck, TerminalSandboxPreCheckRemediation, type ITerminalSandboxCommand, type ITerminalSandboxPrecheckInputs, type ITerminalSandboxPrerequisiteCheckResult } from '../../common/terminalSandboxService.js'; import { ILanguageModelToolsService, IPreparedToolInvocation, IToolData, IToolImpl, IToolInvocation, IToolInvocationPreparationContext, IToolResult, ToolDataSource, ToolProgress, ToolSet, type ToolConfirmationAction } from '../../../../chat/common/tools/languageModelToolsService.js'; +import { ILanguageModelToolsConfirmationService } from '../../../../chat/common/tools/languageModelToolsConfirmationService.js'; import { IToolResultCompressor } from '../../../../chat/common/tools/toolResultCompressor.js'; import { ITerminalChatService, ITerminalService, type ITerminalInstance } from '../../../../terminal/browser/terminal.js'; import { ITerminalProfileResolverService } from '../../../../terminal/common/terminal.js'; @@ -2811,7 +2812,7 @@ suite('RunInTerminalTool', () => { }); const toolSpecificData = { kind: 'terminal', commandLine: { original: 'npm test' }, language: 'bash' } as IChatTerminalToolInvocationData; - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention (runInTerminalTool as unknown as { _registerCompletionNotification: (terminal: ITerminalInstance, termId: string, session: URI, commandName: string, toolSpecificData: IChatTerminalToolInvocationData) => void }) ._registerCompletionNotification(terminalInstance, termId, sessionResource, 'npm test', toolSpecificData); await new Promise<void>(resolve => setTimeout(resolve, 0)); @@ -2869,7 +2870,7 @@ suite('RunInTerminalTool', () => { getOutput: () => output, }); - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention (runInTerminalTool as unknown as { _registerCompletionNotification: (terminal: ITerminalInstance, termId: string, session: URI, commandName: string, toolSpecificData: IChatTerminalToolInvocationData, outputMonitor: { onDidDetectInputNeeded: Event<void>; onDidDetectSensitiveInputNeeded: Event<void>; continueMonitoringAsync: () => void; dispose: () => void }) => void }) ._registerCompletionNotification(terminalInstance, termId, sessionResource, 'npm init', toolSpecificData, outputMonitor); @@ -2916,7 +2917,7 @@ suite('RunInTerminalTool', () => { getOutput: () => output, }); - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention (runInTerminalTool as unknown as { _registerCompletionNotification: (terminal: ITerminalInstance, termId: string, session: URI, commandName: string, toolSpecificData: IChatTerminalToolInvocationData, outputMonitor: { onDidDetectInputNeeded: Event<void>; onDidDetectSensitiveInputNeeded: Event<void>; continueMonitoringAsync: () => void; dispose: () => void }) => void }) ._registerCompletionNotification(terminalInstance, termId, sessionResource, 'git --no-pager diff -- foo.ts', toolSpecificData, outputMonitor); @@ -2969,7 +2970,7 @@ suite('RunInTerminalTool', () => { // the agent has already received `output` as the tool result, so the BG // monitor's first re-detection of the same prompt must not fire a steering // message that would yield the agent's in-flight `send_to_terminal` reply. - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention (runInTerminalTool as unknown as { _registerCompletionNotification: (terminal: ITerminalInstance, termId: string, session: URI, commandName: string, toolSpecificData: IChatTerminalToolInvocationData, outputMonitor: { onDidDetectInputNeeded: Event<void>; onDidDetectSensitiveInputNeeded: Event<void>; continueMonitoringAsync: () => void; dispose: () => void }, alreadyNotifiedInputNeededOutput?: string) => void }) ._registerCompletionNotification(terminalInstance, termId, sessionResource, 'mkdir -p foo && cd foo && npm init', toolSpecificData, outputMonitor, output); @@ -3025,7 +3026,7 @@ suite('RunInTerminalTool', () => { dispose: () => { }, }); - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention (runInTerminalTool as unknown as { _registerCompletionNotification: (terminal: ITerminalInstance, termId: string, session: URI, commandName: string, toolSpecificData: IChatTerminalToolInvocationData, outputMonitor: { onDidDetectInputNeeded: Event<void>; onDidDetectSensitiveInputNeeded: Event<void>; continueMonitoringAsync: () => void; dispose: () => void }) => void }) ._registerCompletionNotification(terminalInstance, termId, sessionResource, 'ssh host', toolSpecificData, outputMonitor); @@ -3116,7 +3117,7 @@ suite('RunInTerminalTool', () => { suite('input-needed steering text', () => { function buildSteeringText(hungHint: 'none' | 'timeout' | 'idleSilence'): string { const sessionResource = LocalChatSessionUri.forSession('input-needed-steering-session'); - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention return (runInTerminalTool as unknown as { _buildInputNeededSteeringText(s: URI, t: string, h: 'none' | 'timeout' | 'idleSilence'): string }) ._buildInputNeededSteeringText(sessionResource, 'test-term-id', hungHint); } @@ -3571,6 +3572,7 @@ suite('ChatAgentToolsContribution - tool registration refresh', () => { readToolSet: new ToolSet('read', 'read', Codicon.book, ToolDataSource.Internal, undefined, undefined, undefined, undefined, undefined, contextKeyService), }; instantiationService.stub(ILanguageModelToolsService, mockToolsService as ILanguageModelToolsService); + instantiationService.stub(ILanguageModelToolsConfirmationService, { registerConfirmationContribution: () => toDisposable(() => { }) }); instantiationService.stub(IToolResultCompressor, { _serviceBrand: undefined, diff --git a/src/vs/workbench/contrib/terminalContrib/commandGuide/browser/terminal.commandGuide.contribution.ts b/src/vs/workbench/contrib/terminalContrib/commandGuide/browser/terminal.commandGuide.contribution.ts index b89f7fa5c09d..8fcc5dbb96af 100644 --- a/src/vs/workbench/contrib/terminalContrib/commandGuide/browser/terminal.commandGuide.contribution.ts +++ b/src/vs/workbench/contrib/terminalContrib/commandGuide/browser/terminal.commandGuide.contribution.ts @@ -60,9 +60,9 @@ class TerminalCommandGuideContribution extends Disposable implements ITerminalCo if (!showCommandGuide) { this._activeCommandGuide.clear(); } else { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const screenElement = xterm.raw.element!.querySelector('.xterm-screen')!; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const viewportElement = xterm.raw.element!.querySelector('.xterm-viewport')!; this._activeCommandGuide.value = combinedDisposable( addDisposableListener(screenElement, 'mousemove', (e: MouseEvent) => this._tryShowHighlight(screenElement, xterm, e)), diff --git a/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalLinkManager.test.ts b/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalLinkManager.test.ts index 67e3787418f7..02a8d4fa09ea 100644 --- a/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalLinkManager.test.ts +++ b/src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalLinkManager.test.ts @@ -120,7 +120,7 @@ suite('TerminalLinkManager', () => { }); }); - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line ts-eslint-js/naming-convention type TestableLinkManager = { _showHover: (...args: unknown[]) => IDisposable | undefined }; function overrideXtermEvent<T>(terminal: Terminal, eventName: string, handler: (listener: (e: T) => void) => IDisposable): IDisposable { diff --git a/src/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollOverlay.ts b/src/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollOverlay.ts index 3cb0d6feb1ce..c6ef4c42b0be 100644 --- a/src/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollOverlay.ts +++ b/src/vs/workbench/contrib/terminalContrib/stickyScroll/browser/terminalStickyScrollOverlay.ts @@ -191,7 +191,7 @@ export class TerminalStickyScrollOverlay extends Disposable { // scrolling horizontally in a pager this._xterm.raw.onCursorMove, )(() => this._refresh()), - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax addStandardDisposableListener(this._xterm.raw.element!.querySelector('.xterm-viewport')!, 'scroll', () => this._refresh()), ); } diff --git a/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.ts b/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.ts index 688094c6839c..91233bf4d3c5 100644 --- a/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.ts +++ b/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminal.suggest.contribution.ts @@ -241,7 +241,7 @@ class TerminalSuggestContribution extends DisposableStore implements ITerminalCo const container = this._resolveAddonContainer(xtermElement); addon.setContainerWithOverflow(container); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const screenElement = xtermElement?.querySelector('.xterm-screen'); if (dom.isHTMLElement(screenElement)) { addon.setScreen(screenElement); diff --git a/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminalSuggestAddon.ts b/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminalSuggestAddon.ts index 5fa0fd05f02a..8339622dc95a 100644 --- a/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminalSuggestAddon.ts +++ b/src/vs/workbench/contrib/terminalContrib/suggest/browser/terminalSuggestAddon.ts @@ -878,7 +878,7 @@ export class SuggestAddon extends Disposable implements ITerminalAddon, ISuggest })); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = this._terminal?.element?.querySelector('.xterm-helper-textarea'); if (element) { this._register(dom.addDisposableListener(dom.getActiveDocument(), 'click', (event) => { diff --git a/src/vs/workbench/contrib/testing/browser/explorerProjections/treeProjection.ts b/src/vs/workbench/contrib/testing/browser/explorerProjections/treeProjection.ts index c97c256c9d63..0dc8bc261bec 100644 --- a/src/vs/workbench/contrib/testing/browser/explorerProjections/treeProjection.ts +++ b/src/vs/workbench/contrib/testing/browser/explorerProjections/treeProjection.ts @@ -10,7 +10,7 @@ import { Iterable } from '../../../../../base/common/iterator.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; import { ITestTreeProjection, TestExplorerTreeElement, TestItemTreeElement, TestTreeErrorMessage, getChildrenForParent, testIdentityProvider } from './index.js'; import { ISerializedTestTreeCollapseState, isCollapsedInSerializedTestTree } from './testingViewState.js'; -import { IComputedStateAndDurationAccessor, refreshComputedState } from '../../common/getComputedState.js'; +import { ComputedStateCache, IComputedStateAndDurationAccessor, refreshComputedState } from '../../common/getComputedState.js'; import { TestId } from '../../common/testId.js'; import { TestResultItemChangeReason } from '../../common/testResult.js'; import { ITestResultService } from '../../common/testResultService.js'; @@ -18,6 +18,7 @@ import { ITestService } from '../../common/testService.js'; import { ITestItemUpdate, InternalTestItem, TestDiffOpType, TestItemExpandState, TestResultState, TestsDiff, applyTestItemUpdate } from '../../common/testTypes.js'; const computedStateAccessor: IComputedStateAndDurationAccessor<TreeTestItemElement> = { + getCache: i => i.computedStateCache, getOwnState: i => i instanceof TestItemTreeElement ? i.ownState : TestResultState.Unset, getCurrentComputedState: i => i.state, setComputedState: (i, s) => i.state = s, @@ -41,6 +42,7 @@ const computedStateAccessor: IComputedStateAndDurationAccessor<TreeTestItemEleme * Test tree element element that groups be hierarchy. */ class TreeTestItemElement extends TestItemTreeElement { + public readonly computedStateCache = new ComputedStateCache(); /** * Own, non-computed state. * @internal @@ -132,8 +134,9 @@ export class TreeProjection extends Disposable implements ITestTreeProjection { for (const inTree of [...this.items.values()].sort((a, b) => b.depth - a.depth)) { const lookup = this.results.getStateById(inTree.test.item.extId)?.[1]; + inTree.ownState = lookup?.ownComputedState ?? TestResultState.Unset; inTree.ownDuration = lookup?.ownDuration; - refreshComputedState(computedStateAccessor, inTree, lookup?.ownComputedState ?? TestResultState.Unset).forEach(i => i.fireChange()); + refreshComputedState(computedStateAccessor, inTree).forEach(i => i.fireChange()); } })); @@ -161,10 +164,10 @@ export class TreeProjection extends Disposable implements ITestTreeProjection { // Skip refreshing the duration if we can trivially tell it didn't change. const refreshDuration = ev.reason === TestResultItemChangeReason.OwnStateChange && ev.previousOwnDuration !== result.ownDuration; - // For items without children, always use the computed state. They are - // either leaves (for which it's fine) or nodes where we haven't expanded - // children and should trust whatever the result service gives us. - const explicitComputed = item.children.size ? undefined : result.computedState; + // Child events already update parents; only recompute when the parent's own state changes. + const explicitComputed = item.children.size + ? (item.ownState === result.ownComputedState ? item.state : undefined) + : result.computedState; item.retired = !!result.retired; item.ownState = result.ownComputedState; @@ -240,7 +243,7 @@ export class TreeProjection extends Disposable implements ITestTreeProjection { } if (parent instanceof TreeTestItemElement) { - refreshComputedState(computedStateAccessor, parent, undefined, !!parent.duration).forEach(i => i.fireChange()); + refreshComputedState(computedStateAccessor, parent, undefined, parent.duration !== undefined).forEach(i => i.fireChange()); } } } @@ -322,7 +325,7 @@ export class TreeProjection extends Disposable implements ITestTreeProjection { treeElement.ownState = prevState.computedState; treeElement.ownDuration = prevState.ownDuration; - refreshComputedState(computedStateAccessor, treeElement, undefined, !!treeElement.ownDuration).forEach(i => i.fireChange()); + refreshComputedState(computedStateAccessor, treeElement, undefined, treeElement.ownDuration !== undefined).forEach(i => i.fireChange()); } } } diff --git a/src/vs/workbench/contrib/testing/browser/testResultsView/testResultsOutput.ts b/src/vs/workbench/contrib/testing/browser/testResultsView/testResultsOutput.ts index 8ab6a0c4823a..96afa225c494 100644 --- a/src/vs/workbench/contrib/testing/browser/testResultsView/testResultsOutput.ts +++ b/src/vs/workbench/contrib/testing/browser/testResultsView/testResultsOutput.ts @@ -27,6 +27,7 @@ import { IInstantiationService } from '../../../../../platform/instantiation/com import { TerminalCapability } from '../../../../../platform/terminal/common/capabilities/capabilities.js'; import { TerminalCapabilityStore } from '../../../../../platform/terminal/common/capabilities/terminalCapabilityStore.js'; import { formatMessageForTerminal } from '../../../../../platform/terminal/common/terminalStrings.js'; +import { parseMarkSequence, ShellIntegrationOscPs } from '../../../../../platform/terminal/common/xterm/shellIntegrationAddon.js'; import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; import { IEditorConfiguration } from '../../../../browser/parts/editor/textEditor.js'; import { EditorModel } from '../../../../common/editor/editorModel.js'; @@ -424,8 +425,10 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender /** Active terminal instance. */ private readonly terminal = this._register(new MutableDisposable<IDetachedTerminalInstance>()); + private readonly terminalProcessInfo = this._register(new MutableDisposable<DetachedProcessInfo>()); /** Listener for streaming result data */ private readonly outputDataListener = this._register(new MutableDisposable()); + private readonly outputMarkListener = this._register(new MutableDisposable()); constructor( private readonly container: HTMLElement, @@ -458,12 +461,14 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender updateCwd: () => { }, }); - return this.terminal.value = await this.terminalService.createDetachedTerminal({ + const processInfo = this.terminalProcessInfo.value = new DetachedProcessInfo({ initialCwd: cwd.value }); + const terminal = await this.terminalService.createDetachedTerminal({ rows: 10, cols: 80, readonly: true, + disableShellIntegrationReporting: true, capabilities, - processInfo: new DetachedProcessInfo({ initialCwd: cwd.value }), + processInfo, colorProvider: { getBackgroundColor: theme => { const terminalBackground = theme.getColor(TERMINAL_BACKGROUND_COLOR); @@ -480,6 +485,12 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender }, } }); + if (this._store.isDisposed) { + terminal.dispose(); + return undefined; + } + + return this.terminal.value = terminal; } public async update(subject: InspectSubject): Promise<boolean> { @@ -559,14 +570,35 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender } const terminal = await this.makeTerminal(); + if (!terminal || this._store.isDisposed) { + return; + } + + // Only the selected message needs hidden output markers. Tracking every + // message makes xterm update thousands of unused markers as output scrolls. + const selectedMarker = opts.subject instanceof MessageSubject && opts.subject.message.type === TestMessageType.Output + ? opts.subject.message.marker : undefined; + const selectedMarks = selectedMarker === undefined ? undefined : new Set([getMarkId(selectedMarker, true), getMarkId(selectedMarker, false)]); + this.outputMarkListener.value = terminal.xterm.registerOscHandler(ShellIntegrationOscPs.VSCode, data => { + if (!data.startsWith('SetMark;')) { + return false; + } + const mark = parseMarkSequence(data.split(';').slice(1)); + return !!mark.hidden && (!mark.id || !selectedMarks?.has(mark.id)); + }); let didWriteData = false; - const pendingWrites = new MutableObservableValue(0); + let pendingWrites = 0; + let resolveWrites: (() => void) | undefined; if (result instanceof LiveTestResult) { for (const chunk of opts.doInitialWrite(target, result)) { didWriteData ||= chunk.byteLength > 0; - pendingWrites.value++; - terminal.xterm.write(chunk.buffer, () => pendingWrites.value--); + pendingWrites++; + terminal.xterm.write(chunk.buffer, () => { + if (--pendingWrites === 0) { + resolveWrites?.(); + } + }); } } else { didWriteData = true; @@ -596,14 +628,9 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender // Ensure pending writes finish, otherwise the selection in `updateForTestSubject` // can happen before the markers are processed. - if (pendingWrites.value > 0) { + if (pendingWrites > 0) { await new Promise<void>(resolve => { - const l = pendingWrites.onDidChange(() => { - if (pendingWrites.value === 0) { - l.dispose(); - resolve(); - } - }); + resolveWrites = resolve; }); } @@ -630,8 +657,10 @@ export class TerminalMessagePeek extends Disposable implements IPeekOutputRender private clear() { this.outputDataListener.clear(); + this.outputMarkListener.clear(); this.xtermLayoutDelayer.cancel(); this.terminal.clear(); + this.terminalProcessInfo.clear(); } public layout(dimensions: dom.IDimension) { diff --git a/src/vs/workbench/contrib/testing/common/getComputedState.ts b/src/vs/workbench/contrib/testing/common/getComputedState.ts index fe33b38a5860..0834679a6f9c 100644 --- a/src/vs/workbench/contrib/testing/common/getComputedState.ts +++ b/src/vs/workbench/contrib/testing/common/getComputedState.ts @@ -5,12 +5,20 @@ import { Iterable } from '../../../../base/common/iterator.js'; import { TestResultState } from './testTypes.js'; -import { makeEmptyCounts, maxPriority, statePriority } from './testingStates.js'; +import { makeEmptyCounts, maxPriority, statePriority, statesInOrder } from './testingStates.js'; + +/** Cached child aggregates, owned by the node whose children they describe. */ +export class ComputedStateCache { + /** State counts for nodes above LARGE_NODE_THRESHOLD. */ + public childrenStates?: { [K in TestResultState]: number }; + public childrenWithDuration?: number; +} /** * Accessor for nodes in get and refresh computed state. */ export interface IComputedStateAccessor<T> { + getCache(item: T): ComputedStateCache; getOwnState(item: T): TestResultState | undefined; getCurrentComputedState(item: T): TestResultState; setComputedState(item: T, state: TestResultState): void; @@ -32,7 +40,7 @@ const isDurationAccessor = <T>(accessor: IComputedStateAccessor<T>): accessor is * if it was previously set. */ -const getComputedState = <T extends object>(accessor: IComputedStateAccessor<T>, node: T, force = false) => { +const getComputedState = <T>(accessor: IComputedStateAccessor<T>, node: T, force = false) => { let computed = accessor.getCurrentComputedState(node); if (computed === undefined || force) { computed = accessor.getOwnState(node) ?? TestResultState.Unset; @@ -51,7 +59,9 @@ const getComputedState = <T extends object>(accessor: IComputedStateAccessor<T>, } if (childrenCount > LARGE_NODE_THRESHOLD) { - largeNodeChildrenStates.set(node, stateMap); + accessor.getCache(node).childrenStates = stateMap; + } else { + accessor.getCache(node).childrenStates = undefined; } accessor.setComputedState(node, computed); @@ -66,14 +76,18 @@ const getComputedDuration = <T>(accessor: IComputedStateAndDurationAccessor<T>, const own = accessor.getOwnDuration(node); if (own !== undefined) { computed = own; + accessor.getCache(node).childrenWithDuration = undefined; } else { computed = undefined; + let childrenWithDuration = 0; for (const child of accessor.getChildren(node)) { const d = getComputedDuration(accessor, child); if (d !== undefined) { + childrenWithDuration++; computed = (computed || 0) + d; } } + accessor.getCache(node).childrenWithDuration = childrenWithDuration; } accessor.setComputedDuration(node, computed); @@ -82,19 +96,33 @@ const getComputedDuration = <T>(accessor: IComputedStateAndDurationAccessor<T>, return computed; }; -const LARGE_NODE_THRESHOLD = 64; +/** Updates the parent's cached duration aggregate, rebuilding it when necessary. */ +const getNewDurationCached = <T>( + accessor: IComputedStateAndDurationAccessor<T>, + parent: T, + oldDuration: number | undefined, + previousChildDuration: number | undefined, + childDuration: number | undefined, +): number | undefined => { + const cache = accessor.getCache(parent); + const childCount = cache.childrenWithDuration; + if (childCount !== undefined && accessor.getOwnDuration(parent) === undefined + && Number.isFinite(oldDuration ?? 0) && Number.isFinite(previousChildDuration ?? 0) && Number.isFinite(childDuration ?? 0)) { + const newChildCount = childCount + Number(childDuration !== undefined) - Number(previousChildDuration !== undefined); + cache.childrenWithDuration = newChildCount; + return newChildCount ? (oldDuration ?? 0) - (previousChildDuration ?? 0) + (childDuration ?? 0) : undefined; + } -/** - * Map of how many nodes have in each state. This is used to optimize state - * computation in large nodes with children above the `LARGE_NODE_THRESHOLD`. - */ -const largeNodeChildrenStates = new WeakMap<object, { [K in TestResultState]: number }>(); + return getComputedDuration(accessor, parent, true); +}; + +const LARGE_NODE_THRESHOLD = 64; /** * Refreshes the computed state for the node and its parents. Any changes * elements cause `addUpdated` to be called. */ -export const refreshComputedState = <T extends object>( +export const refreshComputedState = <T>( accessor: IComputedStateAccessor<T>, node: T, explicitNewComputedState?: TestResultState, @@ -114,7 +142,7 @@ export const refreshComputedState = <T extends object>( let moveToState = newState; for (const parent of accessor.getParents(node)) { - const lnm = largeNodeChildrenStates.get(parent); + const lnm = accessor.getCache(parent).childrenStates; if (lnm) { lnm[moveFromState]--; lnm[moveToState]++; @@ -144,7 +172,9 @@ export const refreshComputedState = <T extends object>( break; } - moveToState = getComputedState(accessor, parent, true); + moveToState = lnm + ? maxPriority(accessor.getOwnState(parent) ?? TestResultState.Unset, statesInOrder.find(state => lnm[state] > 0) ?? TestResultState.Unset) + : getComputedState(accessor, parent, true); accessor.setComputedState(parent, moveToState); toUpdate.add(parent); } @@ -154,15 +184,21 @@ export const refreshComputedState = <T extends object>( } if (isDurationAccessor(accessor) && refreshDuration) { + let previousChildDuration: number | undefined; + let childDuration: number | undefined; for (const parent of Iterable.concat(Iterable.single(node), accessor.getParents(node))) { const oldDuration = accessor.getCurrentComputedDuration(parent); - const newDuration = getComputedDuration(accessor, parent, true); + const newDuration = parent === node + ? getComputedDuration(accessor, parent, true) + : getNewDurationCached(accessor, parent, oldDuration, previousChildDuration, childDuration); if (oldDuration === newDuration) { break; } accessor.setComputedDuration(parent, newDuration); toUpdate.add(parent); + previousChildDuration = oldDuration; + childDuration = newDuration; } } diff --git a/src/vs/workbench/contrib/testing/common/testResult.ts b/src/vs/workbench/contrib/testing/common/testResult.ts index 48ffa5bd080d..943a8bcbd5fe 100644 --- a/src/vs/workbench/contrib/testing/common/testResult.ts +++ b/src/vs/workbench/contrib/testing/common/testResult.ts @@ -15,7 +15,7 @@ import { removeAnsiEscapeCodes } from '../../../../base/common/strings.js'; import { localize } from '../../../../nls.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; -import { IComputedStateAccessor, refreshComputedState } from './getComputedState.js'; +import { ComputedStateCache, IComputedStateAccessor, refreshComputedState } from './getComputedState.js'; import { TestCoverage } from './testCoverage.js'; import { TestId } from './testId.js'; import { makeEmptyCounts, maxPriority, statesInOrder, terminalStatePriorities, TestStateCount } from './testingStates.js'; @@ -247,6 +247,7 @@ export const maxCountPriority = (counts: Readonly<TestStateCount>) => { const getMarkCode = (marker: number, start: boolean) => `\x1b]633;SetMark;Id=${getMarkId(marker, start)};Hidden\x07`; interface TestResultItemWithChildren extends TestResultItem { + computedStateCache?: ComputedStateCache; /** Children in the run */ children: TestResultItemWithChildren[]; } @@ -320,6 +321,7 @@ export class LiveTestResult extends Disposable implements ITestResult { } private readonly computedStateAccessor: IComputedStateAccessor<TestResultItemWithChildren> = { + getCache: i => i.computedStateCache ??= new ComputedStateCache(), getOwnState: i => i.ownComputedState, getCurrentComputedState: i => i.computedState, setComputedState: (i, s) => i.computedState = s, @@ -414,7 +416,8 @@ export class LiveTestResult extends Disposable implements ITestResult { } for (let i = 1; i < chain.length; i++) { - parent = this.addTestToRun(controllerId, chain[i], parent.item.extId); + // Another profile's batch may register the same node after it has reported results. + parent = this.testById.get(chain[i].extId) ?? this.addTestToRun(controllerId, chain[i], parent.item.extId); } return undefined; diff --git a/src/vs/workbench/contrib/testing/common/testServiceImpl.ts b/src/vs/workbench/contrib/testing/common/testServiceImpl.ts index 26c5a86431e9..b45576dff0fb 100644 --- a/src/vs/workbench/contrib/testing/common/testServiceImpl.ts +++ b/src/vs/workbench/contrib/testing/common/testServiceImpl.ts @@ -299,7 +299,7 @@ export class TestService extends Disposable implements ITestService { */ public async provideTestFollowups(req: TestMessageFollowupRequest, token: CancellationToken): Promise<ITestFollowups> { const reqs = await Promise.all([...this.testExtHosts].map(async ctrl => - ({ ctrl, followups: await ctrl.provideTestFollowups(req, token) }))); + ({ ctrl, followups: await ctrl.provideTestFollowups(req, token) }))); const followups: ITestFollowups = { followups: reqs.flatMap(({ ctrl, followups }) => followups.map(f => ({ diff --git a/src/vs/workbench/contrib/testing/test/browser/explorerProjections/treeProjection.test.ts b/src/vs/workbench/contrib/testing/test/browser/explorerProjections/treeProjection.test.ts index 5e349aa21e92..9134127ed677 100644 --- a/src/vs/workbench/contrib/testing/test/browser/explorerProjections/treeProjection.test.ts +++ b/src/vs/workbench/contrib/testing/test/browser/explorerProjections/treeProjection.test.ts @@ -4,16 +4,21 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import sinon from 'sinon'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { MockContextKeyService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { NullTelemetryService } from '../../../../../../platform/telemetry/common/telemetryUtils.js'; import { TreeProjection } from '../../../browser/explorerProjections/treeProjection.js'; import { TestId } from '../../../common/testId.js'; import { TestResultItemChange, TestResultItemChangeReason } from '../../../common/testResult.js'; -import { TestDiffOpType, TestItemExpandState, TestResultItem, TestResultState } from '../../../common/testTypes.js'; +import { TestDiffOpType, TestItemExpandState, TestResultItem, TestResultState, TestRunProfileBitset } from '../../../common/testTypes.js'; import { TestTreeTestHarness } from '../testObjectTree.js'; import { TestTestItem } from '../../common/testStubs.js'; import { upcastPartial } from '../../../../../../base/test/common/mock.js'; -import { ITestResultService } from '../../../common/testResultService.js'; +import { ITestResultService, TestResultService } from '../../../common/testResultService.js'; +import { ITestResultStorage } from '../../../common/testResultStorage.js'; +import { ITestProfileService } from '../../../common/testProfileService.js'; class TestHierarchicalByLocationProjection extends TreeProjection { } @@ -22,6 +27,7 @@ suite('Workbench - Testing Explorer Hierarchal by Location Projection', () => { let harness: TestTreeTestHarness<TestHierarchicalByLocationProjection>; let onTestChanged: Emitter<TestResultItemChange>; let resultsService: ITestResultService; + teardown(() => sinon.restore()); const ds = ensureNoDisposablesAreLeakedInTestSuite(); setup(() => { @@ -156,6 +162,56 @@ suite('Workbench - Testing Explorer Hierarchal by Location Projection', () => { ]); }); + test('does not recompute children for a computed state notification', () => { + harness.flush(); + const parent = harness.projection.getElementByTestId('ctrlId\0id-a')!; + harness.tree.expand(parent); + harness.flush(); + const child = harness.projection.getElementByTestId('ctrlId\0id-a\0id-aa')!; + onTestChanged.fire({ + reason: TestResultItemChangeReason.OwnStateChange, + result: undefined!, + previousState: TestResultState.Unset, + previousOwnDuration: undefined, + item: { ...child.test, tasks: [], ownComputedState: TestResultState.Running, computedState: TestResultState.Running }, + }); + + const children = sinon.spy(parent.children, 'values'); + try { + onTestChanged.fire({ + reason: TestResultItemChangeReason.ComputedStateChange, + result: undefined!, + item: { ...parent.test, tasks: [], ownComputedState: TestResultState.Unset, computedState: TestResultState.Running, retired: true }, + }); + assert.deepStrictEqual({ state: parent.state, retired: parent.retired, scans: children.callCount }, { state: TestResultState.Running, retired: true, scans: 0 }); + } finally { + children.restore(); + } + }); + + test('updates durations after removing a child with a zero duration', () => { + harness.flush(); + const parent = harness.projection.getElementByTestId('ctrlId\0id-a')!; + harness.tree.expand(parent); + harness.flush(); + const first = harness.projection.getElementByTestId('ctrlId\0id-a\0id-aa')!; + const second = harness.projection.getElementByTestId('ctrlId\0id-a\0id-ab')!; + const updateDuration = (item: typeof first, ownDuration: number | undefined, previousOwnDuration?: number) => onTestChanged.fire({ + reason: TestResultItemChangeReason.OwnStateChange, + result: undefined!, + previousState: TestResultState.Passed, + previousOwnDuration, + item: { ...item.test, tasks: [], ownComputedState: TestResultState.Passed, computedState: TestResultState.Passed, ownDuration }, + }); + updateDuration(first, 0); + harness.c.root.children.get('id-a')!.children.delete('id-aa'); + harness.flush(); + assert.strictEqual(parent.duration, undefined); + updateDuration(second, 2); + updateDuration(second, undefined, 2); + assert.strictEqual(parent.duration, undefined); + }); + test('applies test changes (resort)', async () => { harness.flush(); harness.tree.expand(harness.projection.getElementByTestId(new TestId(['ctrlId', 'id-a']).toString())!); @@ -310,3 +366,91 @@ suite('Workbench - Testing Explorer Hierarchal by Location Projection', () => { ]); }); }); + +suite('Workbench - Testing Explorer result clearing', () => { + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + for (const completed of [false, true]) { + test(`recomputes suite state when clearing ${completed ? 'completed' : 'active'} results and retiring tests`, () => { + const results = ds.add(new TestResultService( + new MockContextKeyService(), + upcastPartial<ITestResultStorage>({ read: async () => [], persist: async () => { } }), + upcastPartial<ITestProfileService>({}), + NullTelemetryService, + )); + const harness = ds.add(new TestTreeTestHarness(l => new TreeProjection({}, l, results))); + harness.flush(); + const suite = harness.projection.getElementByTestId('ctrlId\0id-a')!; + harness.tree.expand(suite); + harness.flush(); + const child = harness.projection.getElementByTestId('ctrlId\0id-a\0id-aa')!; + const root = harness.projection.getElementByTestId('ctrlId')!; + const result = ds.add(results.createLiveResult({ group: TestRunProfileBitset.Run, targets: [] })); + result.addTask({ id: 'task', name: 'task', running: true, ctrlId: 'ctrlId' }); + result.addTestChainToRun('ctrlId', [root.test.item, suite.test.item, child.test.item]); + result.updateState(child.test.item.extId, 'task', TestResultState.Passed, 7); + if (completed) { + result.updateState(suite.test.item.extId, 'task', TestResultState.Passed, 11); + result.markComplete(); + } + + results.clear(); + const afterClear = [suite.state, child.state, suite.duration, child.duration]; + result.markRetired(undefined); + assert.deepStrictEqual({ afterClear, afterRetirement: [suite.state, child.state, suite.duration, child.duration] }, completed ? { + afterClear: [TestResultState.Unset, TestResultState.Unset, undefined, undefined], + afterRetirement: [TestResultState.Unset, TestResultState.Unset, undefined, undefined], + } : { + afterClear: [TestResultState.Passed, TestResultState.Passed, 7, 7], + afterRetirement: [TestResultState.Passed, TestResultState.Passed, 7, 7], + }); + }); + } +}); + +suite('Workbench - Testing Explorer result durations', () => { + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + for (const ownDuration of [0, 20]) { + test(`recomputes suite duration across results after an own duration of ${ownDuration}`, () => { + const results = ds.add(new TestResultService( + new MockContextKeyService(), + upcastPartial<ITestResultStorage>({ read: async () => [], persist: async () => { } }), + upcastPartial<ITestProfileService>({}), + NullTelemetryService, + )); + const harness = ds.add(new TestTreeTestHarness(l => new TreeProjection({}, l, results))); + harness.flush(); + const suite = harness.projection.getElementByTestId('ctrlId\0id-a')!; + harness.tree.expand(suite); + harness.flush(); + const child = harness.projection.getElementByTestId('ctrlId\0id-a\0id-aa')!; + const root = harness.projection.getElementByTestId('ctrlId')!; + const createResult = () => { + const result = ds.add(results.createLiveResult({ group: TestRunProfileBitset.Run, targets: [] })); + result.addTask({ id: 'task', name: 'task', running: true, ctrlId: 'ctrlId' }); + result.addTestChainToRun('ctrlId', [root.test.item, suite.test.item, child.test.item]); + result.updateState(suite.test.item.extId, 'task', TestResultState.Running); + return result; + }; + + const first = createResult(); + first.updateState(child.test.item.extId, 'task', TestResultState.Passed, 5); + first.updateState(suite.test.item.extId, 'task', TestResultState.Passed, ownDuration); + first.markComplete(); + const durations = [[suite.duration, child.duration]]; + + const second = createResult(); + second.updateState(child.test.item.extId, 'task', TestResultState.Passed, 3); + durations.push([suite.duration, child.duration]); + second.markComplete(); + + const third = createResult(); + third.updateState(child.test.item.extId, 'task', TestResultState.Passed, 4); + durations.push([suite.duration, child.duration]); + third.markComplete(); + + assert.deepStrictEqual(durations, [[ownDuration, 5], [3, 3], [4, 4]]); + }); + } +}); diff --git a/src/vs/workbench/contrib/testing/test/browser/testResultsOutput.test.ts b/src/vs/workbench/contrib/testing/test/browser/testResultsOutput.test.ts new file mode 100644 index 000000000000..2ea8d1feeb86 --- /dev/null +++ b/src/vs/workbench/contrib/testing/test/browser/testResultsOutput.test.ts @@ -0,0 +1,179 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type { Terminal } from '@xterm/xterm'; +import assert from 'assert'; +import * as sinon from 'sinon'; +import { importAMDNodeModule } from '../../../../../amdX.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { VSBuffer } from '../../../../../base/common/buffer.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { TerminalCapability } from '../../../../../platform/terminal/common/capabilities/capabilities.js'; +import { ShellIntegrationAddon } from '../../../../../platform/terminal/common/xterm/shellIntegrationAddon.js'; +import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js'; +import { IViewDescriptorService } from '../../../../common/views.js'; +import { IDetachedTerminalInstance, IDetachedXTermOptions, IDetachedXtermTerminal, ITerminalService } from '../../../terminal/browser/terminal.js'; +import { writeP } from '../../../terminal/browser/terminalTestHelpers.js'; +import { ITerminalFont } from '../../../terminal/common/terminal.js'; +import { TestXtermLogger } from '../../../../../platform/terminal/test/common/terminalTestHelpers.js'; +import { TerminalMessagePeek } from '../../browser/testResultsView/testResultsOutput.js'; +import { MessageSubject, TaskSubject, TestOutputSubject } from '../../browser/testResultsView/testResultsSubject.js'; +import { LiveTestResult } from '../../common/testResult.js'; +import { TestRunProfileBitset } from '../../common/testTypes.js'; + +suite('Testing output terminal', () => { + teardown(async () => { + sinon.restore(); + // Drain queued layout work before the fixture disposal hook runs. + await new Promise<void>(resolve => mainWindow.requestAnimationFrame(() => resolve())); + }); + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + let result: LiveTestResult; + let peek: TerminalMessagePeek; + let xterm: IDetachedXtermTerminal; + let raw: Terminal; + let integration: ShellIntegrationAddon; + let logService: NullLogService; + let telemetryService: ITelemetryService; + let selected: sinon.SinonSpy; + let terminal: IDetachedTerminalInstance; + let terminalCreation: DeferredPromise<IDetachedTerminalInstance> | undefined; + + setup(async () => { + const TerminalCtor = (await importAMDNodeModule<typeof import('@xterm/xterm')>('@xterm/xterm', 'lib/xterm.js')).Terminal; + raw = store.add(new TerminalCtor({ allowProposedApi: true, cols: 80, rows: 10, logger: TestXtermLogger })); + logService = store.add(new NullLogService()); + telemetryService = new class extends mock<ITelemetryService>() { override publicLog2 = () => { }; }; + selected = sinon.spy((start: string, end: string) => { + const marks = integration.capabilities.get(TerminalCapability.BufferMarkDetection); + assert.ok(marks?.getMark(start)); + assert.ok(marks?.getMark(end)); + }); + xterm = new class extends mock<IDetachedXtermTerminal>() { + override write = raw.write.bind(raw); + override registerOscHandler = raw.parser.registerOscHandler.bind(raw.parser); + override clearBuffer = () => raw.clear(); + override clearSearchDecorations = () => { }; + override selectMarkedRange = selected; + override getFont = () => upcastPartial<ITerminalFont>({}); + }; + terminalCreation = undefined; + terminal = new class extends mock<IDetachedTerminalInstance>() { + override xterm = xterm; + override attachToElement = () => { }; + override dispose = () => { }; + }; + peek = store.add(new TerminalMessagePeek(mainWindow.document.createElement('div'), false, + new class extends mock<ITerminalService>() { + override async createDetachedTerminal(options: IDetachedXTermOptions) { + store.add(options.capabilities!); + integration = store.add(new ShellIntegrationAddon('', options.disableShellIntegrationReporting, undefined, telemetryService, logService)); + raw.loadAddon(integration); + return terminalCreation ? terminalCreation.p : terminal; + } + }, + new class extends mock<IViewDescriptorService>() { }, + new class extends mock<IWorkspaceContextService>() { override getWorkspace = () => ({ id: 'workspace', folders: [] }); }, + )); + result = store.add(new LiveTestResult('result', false, { group: TestRunProfileBitset.Run, targets: [] }, 0, NullTelemetryService)); + result.addTask({ id: 'task', name: 'task', running: true, ctrlId: 'ctrl' }); + result.addTestChainToRun('ctrl', [{ extId: 'ctrl', label: 'test', tags: [], busy: false, uri: undefined, range: null, description: null, error: null, sortText: null }]); + result.appendOutput(VSBuffer.fromString('hello \u2713\r\n'), 'task', undefined, 'ctrl'); + }); + + for (const scope of ['task', 'test'] as const) { + test(`does not report a shell integration timeout for ${scope} output with filtered markers`, async () => { + const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const warn = sinon.spy(logService, 'warn'); + const telemetry = sinon.spy(telemetryService, 'publicLog2'); + const subject = scope === 'task' + ? new TaskSubject(result, 0) + : new TestOutputSubject(result, 0, result.getStateById('ctrl')!); + const update = peek.update(subject); + await clock.tickAsync(0); + await update; + await clock.tickAsync(10001); + assert.deepStrictEqual({ + warnings: warn.args, + timeouts: telemetry.args.filter(args => args[0] === 'terminal/shellIntegrationActivationTimeout'), + text: raw.buffer.active.getLine(0)?.translateToString(true), + markers: raw.markers.length, + }, { warnings: [], timeouts: [], text: 'hello \u2713', markers: 0 }); + } finally { + clock.restore(); + } + }); + } + + test('whole-run output does not create hidden per-message markers', async () => { + await peek.update(new TaskSubject(result, 0)); + assert.strictEqual(raw.buffer.active.getLine(0)?.translateToString(true), 'hello \u2713'); + assert.strictEqual(raw.markers.length, 0); + result.appendOutput(VSBuffer.fromString('streamed\r\n'), 'task', undefined, 'ctrl'); + await writeP(raw, ''); + assert.strictEqual(raw.buffer.active.getLine(1)?.translateToString(true), 'streamed'); + assert.strictEqual(raw.markers.length, 0); + await writeP(raw, '\x1b]633;SetMark;Id=visible\x07'); + assert.ok(integration.capabilities.get(TerminalCapability.BufferMarkDetection)?.getMark('visible')); + }); + + test('only keeps the selected message markers when switching output scopes', async () => { + result.appendOutput(VSBuffer.fromString('second\r\n'), 'task', undefined, 'ctrl'); + await peek.update(new TaskSubject(result, 0)); + const test = result.getStateById('ctrl')!; + await peek.update(new TestOutputSubject(result, 0, test)); + assert.strictEqual(raw.markers.length, 0); + await peek.update(new MessageSubject(result, test, 0, 1)); + assert.strictEqual(raw.markers.length, 2); + assert.ok(integration.capabilities.get(TerminalCapability.BufferMarkDetection)?.getMark('s1')); + assert.ok(integration.capabilities.get(TerminalCapability.BufferMarkDetection)?.getMark('e1')); + assert.deepStrictEqual(selected.firstCall.args, ['s1', 'e1', true]); + assert.strictEqual(raw.buffer.active.getLine(0)?.translateToString(true), 'hello \u2713'); + await peek.update(new TaskSubject(result, 0)); + assert.strictEqual(raw.markers.length, 0); + }); + + test('removes the marker filter when the output view is disposed', async () => { + await peek.update(new TaskSubject(result, 0)); + await new Promise<void>(resolve => mainWindow.requestAnimationFrame(() => resolve())); + peek.dispose(); + await writeP(raw, '\x1b]633;SetMark;Id=after-disposal;Hidden\x07'); + assert.ok(integration.capabilities.get(TerminalCapability.BufferMarkDetection)?.getMark('after-disposal')); + }); + + for (const scope of ['task', 'message'] as const) { + test(`disposes a terminal created after the ${scope} output view is disposed`, async () => { + terminalCreation = new DeferredPromise<IDetachedTerminalInstance>(); + const dispose = sinon.spy(terminal, 'dispose'); + const registerOscHandler = sinon.spy(xterm, 'registerOscHandler'); + const write = sinon.spy(xterm, 'write'); + const attach = sinon.spy(terminal, 'attachToElement'); + const subject = scope === 'task' + ? new TaskSubject(result, 0) + : new MessageSubject(result, result.getStateById('ctrl')!, 0, 0); + const update = peek.update(subject); + peek.dispose(); + await terminalCreation.complete(terminal); + await update; + + assert.strictEqual(dispose.callCount, 1); + assert.strictEqual(registerOscHandler.callCount, 0); + assert.strictEqual(write.callCount, 0); + assert.strictEqual(attach.callCount, 0); + assert.strictEqual(selected.callCount, 0); + result.appendOutput(VSBuffer.fromString('after disposal\r\n'), 'task', undefined, 'ctrl'); + assert.strictEqual(write.callCount, 0); + await writeP(raw, '\x1b]633;SetMark;Id=after-disposal;Hidden\x07'); + assert.ok(integration.capabilities.get(TerminalCapability.BufferMarkDetection)?.getMark('after-disposal')); + }); + } +}); diff --git a/src/vs/workbench/contrib/testing/test/common/getComputedState.test.ts b/src/vs/workbench/contrib/testing/test/common/getComputedState.test.ts new file mode 100644 index 000000000000..d04687298267 --- /dev/null +++ b/src/vs/workbench/contrib/testing/test/common/getComputedState.test.ts @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { ComputedStateCache, IComputedStateAndDurationAccessor, refreshComputedState } from '../../common/getComputedState.js'; +import { TestResultState } from '../../common/testTypes.js'; + +interface TestNode { + computedStateCache?: ComputedStateCache; + parent?: TestNode; + children: TestNode[]; + ownState: TestResultState; + state: TestResultState; + ownDuration?: number; + duration?: number; +} + +suite('Testing computed state and duration', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + let childVisits: number; + const accessor: IComputedStateAndDurationAccessor<TestNode> = { + getCache: node => node.computedStateCache ??= new ComputedStateCache(), + getOwnState: node => node.ownState, + getCurrentComputedState: node => node.state, + setComputedState: (node, state) => node.state = state, + getOwnDuration: node => node.ownDuration, + getCurrentComputedDuration: node => node.duration, + setComputedDuration: (node, duration) => node.duration = duration, + *getChildren(node) { + for (const child of node.children) { + childVisits++; + yield child; + } + }, + *getParents(node) { + for (let parent = node.parent; parent; parent = parent.parent) { + yield parent; + } + }, + }; + + const createNode = (parent?: TestNode): TestNode => { + const node: TestNode = { parent, children: [], ownState: TestResultState.Unset, state: TestResultState.Unset }; + parent?.children.push(node); + return node; + }; + + const setDuration = (node: TestNode, duration: number | undefined) => { + node.ownDuration = duration; + return refreshComputedState(accessor, node); + }; + + setup(() => childVisits = 0); + + test('sequential test states do not rescan a large suite', () => { + const suite = createNode(); + const tests = Array.from({ length: 100 }, () => createNode(suite)); + for (const test of tests) { + test.ownState = TestResultState.Running; + refreshComputedState(accessor, test, undefined, false); + assert.strictEqual(suite.state, TestResultState.Running); + test.ownState = TestResultState.Passed; + refreshComputedState(accessor, test, undefined, false); + assert.strictEqual(suite.state, TestResultState.Passed); + } + assert.ok(childVisits <= tests.length * 2, `${childVisits} child visits`); + }); + + test('duration updates and clearing results do not rescan siblings', () => { + const suite = createNode(); + const tests = Array.from({ length: 100 }, () => createNode(suite)); + for (const test of tests) { + setDuration(test, 1); + } + assert.strictEqual(suite.duration, tests.length); + for (const test of tests) { + setDuration(test, undefined); + } + assert.strictEqual(suite.duration, undefined); + assert.ok(childVisits <= tests.length * 2, `${childVisits} child visits`); + }); + + test('distinguishes a zero duration from no duration through multiple parents', () => { + const root = createNode(); + const suite = createNode(root); + const first = createNode(suite); + const second = createNode(suite); + setDuration(first, 0); + setDuration(second, 0); + setDuration(first, undefined); + assert.deepStrictEqual([suite.duration, root.duration], [0, 0]); + setDuration(second, undefined); + assert.deepStrictEqual([suite.duration, root.duration], [undefined, undefined]); + }); + + test('updates durations through multiple parents and stops at an own duration', () => { + const root = createNode(); + const suite = createNode(root); + const first = createNode(suite); + const second = createNode(suite); + setDuration(first, 2); + setDuration(second, 3); + setDuration(first, 7); + assert.deepStrictEqual([suite.duration, root.duration], [10, 10]); + setDuration(suite, 20); + setDuration(first, 9); + assert.deepStrictEqual([suite.duration, root.duration], [20, 20]); + setDuration(suite, undefined); + assert.deepStrictEqual([suite.duration, root.duration], [12, 12]); + setDuration(second, undefined); + assert.deepStrictEqual([suite.duration, root.duration], [9, 9]); + }); + + test('recomputes non-finite duration sums', () => { + const suite = createNode(); + const first = createNode(suite); + const second = createNode(suite); + setDuration(first, Infinity); + setDuration(second, 2); + assert.strictEqual(suite.duration, Infinity); + setDuration(first, 1); + assert.strictEqual(suite.duration, 3); + }); + + test('refreshes duration counts when children are added or removed', () => { + const root = createNode(); + const suite = createNode(root); + const first = createNode(suite); + setDuration(first, 3); + const second = createNode(suite); + setDuration(second, 2); + suite.children.splice(suite.children.indexOf(first), 1); + refreshComputedState(accessor, suite); + assert.deepStrictEqual([suite.duration, root.duration], [2, 2]); + setDuration(second, undefined); + assert.deepStrictEqual([suite.duration, root.duration], [undefined, undefined]); + }); + + test('preserves the parents own state and the highest priority child state', () => { + const root = createNode(); + const suite = createNode(root); + const tests = Array.from({ length: 100 }, () => createNode(suite)); + suite.ownState = TestResultState.Failed; + refreshComputedState(accessor, suite, undefined, false); + for (const test of tests) { + test.ownState = TestResultState.Running; + refreshComputedState(accessor, test, undefined, false); + test.ownState = TestResultState.Passed; + refreshComputedState(accessor, test, undefined, false); + } + assert.deepStrictEqual([suite.state, root.state], [TestResultState.Failed, TestResultState.Failed]); + suite.ownState = TestResultState.Unset; + refreshComputedState(accessor, suite, undefined, false); + assert.deepStrictEqual([suite.state, root.state], [TestResultState.Passed, TestResultState.Passed]); + }); + + test('drops cached state counts when a suite becomes small', () => { + const suite = createNode(); + const tests = Array.from({ length: 100 }, () => createNode(suite)); + for (const test of tests) { + test.ownState = TestResultState.Failed; + refreshComputedState(accessor, test, undefined, false); + } + refreshComputedState(accessor, suite, undefined, false); + assert.ok(suite.computedStateCache?.childrenStates); + suite.children.splice(1); + refreshComputedState(accessor, suite, undefined, false); + tests[0].ownState = TestResultState.Running; + refreshComputedState(accessor, tests[0], undefined, false); + tests[0].ownState = TestResultState.Passed; + refreshComputedState(accessor, tests[0], undefined, false); + assert.strictEqual(suite.state, TestResultState.Passed); + }); +}); diff --git a/src/vs/workbench/contrib/testing/test/common/testResultService.test.ts b/src/vs/workbench/contrib/testing/test/common/testResultService.test.ts index 4faad9ae2cea..8ec4fbf2c792 100644 --- a/src/vs/workbench/contrib/testing/test/common/testResultService.test.ts +++ b/src/vs/workbench/contrib/testing/test/common/testResultService.test.ts @@ -260,6 +260,7 @@ suite('Workbench - Test Results Service', () => { expected.item.children = undefined; expected.retired = true; delete expected.children; + delete expected.computedStateCache; assert.deepStrictEqual(actual, { ...expected }); assert.deepStrictEqual(rehydrated.counts, r.counts); assert.strictEqual(typeof rehydrated.completedAt, 'number'); diff --git a/src/vs/workbench/contrib/update/browser/media/updateTitleBarEntry.css b/src/vs/workbench/contrib/update/browser/media/updateTitleBarEntry.css index 974ea0a895bb..3122c82d59ae 100644 --- a/src/vs/workbench/contrib/update/browser/media/updateTitleBarEntry.css +++ b/src/vs/workbench/contrib/update/browser/media/updateTitleBarEntry.css @@ -42,7 +42,7 @@ } /* Progress underline bar (shared base) */ -.monaco-action-bar .update-indicator.progress-indefinite .indicator-label::after, +.monaco-action-bar .update-indicator.progress-indefinite .indicator-progress, .monaco-action-bar .update-indicator.progress-percent .indicator-label::after { content: ''; position: absolute; @@ -52,22 +52,37 @@ border-radius: 1px; } -/* Progress: indefinite — animated shimmer underline */ -.monaco-action-bar .update-indicator.progress-indefinite .indicator-label::after { +/* + * Progress: indefinite — animated shimmer underline. + * The bar clips a strip of two gradient tiles (each twice the bar width), so moving the strip + * by one tile with a compositor-only transform loops seamlessly without repainting. + */ +.monaco-action-bar .update-indicator.progress-indefinite .indicator-progress { width: 100%; + overflow: hidden; +} + +.monaco-action-bar .update-indicator.progress-indefinite .indicator-progress::after { + content: ''; + position: absolute; + top: 0; + left: 0; + height: 100%; + width: 400%; background: linear-gradient( 90deg, transparent 0%, var(--vscode-progressBar-background) 80%, transparent 100% ); - background-size: 200% 100%; + background-size: 50% 100%; + transform: translateX(-50%); animation: update-indicator-shimmer 1.5s ease-in-out infinite; } @keyframes update-indicator-shimmer { - 0% { background-position: 100% 0; } - 100% { background-position: -100% 0; } + 0% { transform: translateX(-75%); } + 100% { transform: translateX(-25%); } } /* Progress: percentage — left-to-right fill underline */ @@ -82,7 +97,7 @@ } /* Reduced motion */ -.monaco-workbench.monaco-reduce-motion .update-indicator.progress-indefinite .indicator-label::after { +.monaco-workbench.monaco-reduce-motion .update-indicator.progress-indefinite .indicator-progress::after { animation: none; } diff --git a/src/vs/workbench/contrib/update/browser/releaseNotesAccessibilityHelp.ts b/src/vs/workbench/contrib/update/browser/releaseNotesAccessibilityHelp.ts index 60666e9391bd..473b7702dd1e 100644 --- a/src/vs/workbench/contrib/update/browser/releaseNotesAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/update/browser/releaseNotesAccessibilityHelp.ts @@ -32,6 +32,7 @@ export class ReleaseNotesAccessibilityHelp implements IAccessibleViewImplementat () => [ localize('releaseNotes.help.overview', "You are in the release notes. Use your screen reader's reading and heading navigation commands to explore the document and its table of contents."), localize('releaseNotes.help.currentSection', "The table of contents identifies the current section as you scroll. This does not move keyboard focus."), + localize('releaseNotes.help.video', "When a highlights video is available and enabled, its section starts expanded. Press Enter or Space on Watch release highlights to collapse or expand it. Tab to the native video controls and any provided transcript or external video link. Use captions when provided. Expanding the section does not start playback."), localize('releaseNotes.help.navigation', "Press Tab or Shift+Tab to move between links, settings, the update preference checkbox, and available setup actions. Press Enter to activate a link. Press Space or Enter to activate a setup button."), localize('releaseNotes.help.tryouts', "Feature example links may use custom labels and open locally registered examples. Reading, hovering, or focusing a link does not run it. If an example is unavailable, its explanation and any available setup action appear beside it. Setup does not automatically run the example."), localize('releaseNotes.help.windows', "Some actions open another editor or window, including the Agents window. Chat examples prepare an input for you to review and do not send it automatically."), diff --git a/src/vs/workbench/contrib/update/browser/releaseNotesEditor.ts b/src/vs/workbench/contrib/update/browser/releaseNotesEditor.ts index 5a3848e3c699..6e80e83c86a4 100644 --- a/src/vs/workbench/contrib/update/browser/releaseNotesEditor.ts +++ b/src/vs/workbench/contrib/update/browser/releaseNotesEditor.ts @@ -6,6 +6,7 @@ import { CancellationToken } from '../../../../base/common/cancellation.js'; import { $, addDisposableListener, getWindow } from '../../../../base/browser/dom.js'; import { safeSetInnerHtml, sanitizeHtml } from '../../../../base/browser/domSanitize.js'; +import { mainWindow } from '../../../../base/browser/window.js'; import { allowedMarkdownHtmlAttributes, allowedMarkdownHtmlTags } from '../../../../base/browser/markdownRenderer.js'; import { status } from '../../../../base/browser/ui/aria/aria.js'; import { RunOnceScheduler } from '../../../../base/common/async.js'; @@ -23,7 +24,7 @@ import { generateTokensCSSForColorMap } from '../../../../editor/common/language import { ILanguageService } from '../../../../editor/common/languages/language.js'; import { tokenizeToString } from '../../../../editor/common/languages/textToHtmlTokenizer.js'; import * as nls from '../../../../nls.js'; -import { IEnvironmentService } from '../../../../platform/environment/common/environment.js'; +import { IWorkbenchEnvironmentService } from '../../../services/environment/common/environmentService.js'; import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IProductService } from '../../../../platform/product/common/productService.js'; @@ -35,8 +36,9 @@ import { IEditorGroupsService } from '../../../services/editor/common/editorGrou import { ACTIVE_GROUP, IEditorService } from '../../../services/editor/common/editorService.js'; import { IExtensionService } from '../../../services/extensions/common/extensions.js'; import { getTelemetryLevel, supportsTelemetry } from '../../../../platform/telemetry/common/telemetryUtils.js'; -import { IConfigurationChangeEvent, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { TelemetryLevel } from '../../../../platform/telemetry/common/telemetry.js'; +import { IConfigurationChangeEvent, IConfigurationService, isConfigured } from '../../../../platform/configuration/common/configuration.js'; +import { ITelemetryService, TelemetryLevel } from '../../../../platform/telemetry/common/telemetry.js'; +import { logSettingExperimentTrigger } from '../../../../platform/telemetry/common/experimentTrigger.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../base/common/lifecycle.js'; import { SimpleSettingRenderer } from '../../markdown/browser/markdownSettingRenderer.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; @@ -54,6 +56,7 @@ import { IHostService } from '../../../services/host/browser/host.js'; import { ILifecycleService } from '../../../services/lifecycle/common/lifecycle.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { encodeHex, VSBuffer } from '../../../../base/common/buffer.js'; +import { isWeb } from '../../../../base/common/platform.js'; interface IReleaseNotesCodeBlock { readonly id: string; @@ -71,6 +74,14 @@ interface IReleaseNotesTelemetryDocument extends IDisposable { refresh(): void; } +interface IHighlightsVideoOptions { + readonly enabled: boolean; + readonly onDidResolve?: (available: boolean) => void; + readonly onInvalid?: () => void; +} + +const highlightsVideoSetting = 'update.showReleaseHighlightsVideo'; + export class ReleaseNotesManager extends Disposable { private readonly _simpleSettingRenderer: SimpleSettingRenderer; private readonly _releaseNotesCache = new Map<string, Promise<{ text: string; revision: string }>>(); @@ -85,7 +96,7 @@ export class ReleaseNotesManager extends Disposable { private readonly _telemetryDocument = this._register(new MutableDisposable<IReleaseNotesTelemetryDocument>()); constructor( - @IEnvironmentService private readonly _environmentService: IEnvironmentService, + @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @ILanguageService private readonly _languageService: ILanguageService, @IOpenerService private readonly _openerService: IOpenerService, @@ -102,6 +113,7 @@ export class ReleaseNotesManager extends Disposable { @IHostService private readonly _hostService: IHostService, @ILifecycleService private readonly _lifecycleService: ILifecycleService, @ILogService private readonly _logService: ILogService, + @ITelemetryService private readonly _telemetryService: ITelemetryService, ) { super(); @@ -188,7 +200,7 @@ export class ReleaseNotesManager extends Disposable { const codeBlocks: IReleaseNotesCodeBlock[] = []; let html: string; try { - html = await this.renderBody({ text: releaseNotes.text, base, mediaBaseUrl: useCurrentFile ? undefined : 'https://code.visualstudio.com/assets/updates/' }, tryouts, codeBlocks, telemetry); + html = await this.renderBody({ text: releaseNotes.text, base, mediaBaseUrl: useCurrentFile ? undefined : 'https://code.visualstudio.com/assets/updates/', isPreview: useCurrentFile }, tryouts, codeBlocks, telemetry); } catch (error) { if (this._pendingDocument.value === tryouts) { this._pendingDocument.clear(); @@ -480,10 +492,20 @@ export class ReleaseNotesManager extends Disposable { return uri; } - private async renderBody(fileContent: { text: string; base: URI; mediaBaseUrl?: string }, tryouts: ReleaseNotesTryouts, codeBlocks: IReleaseNotesCodeBlock[], telemetry?: ReleaseNotesTelemetry) { + private async renderBody(fileContent: { text: string; base: URI; mediaBaseUrl?: string; isPreview: boolean }, tryouts: ReleaseNotesTryouts, codeBlocks: IReleaseNotesCodeBlock[], telemetry?: ReleaseNotesTelemetry) { const nonce = generateUuid(); - const processedContent = await renderReleaseNotesMarkdown(fileContent.text, this._extensionService, this._languageService, this._simpleSettingRenderer, this._productService.quality, tryouts, codeBlocks, telemetry, fileContent.mediaBaseUrl); + const supported = !isWeb && !this._environmentService.isSessionsWindow; + const preference = this._configurationService.inspect<boolean>(highlightsVideoSetting); + const processedContent = await renderReleaseNotesMarkdown(fileContent.text, this._extensionService, this._languageService, this._simpleSettingRenderer, this._productService.quality, tryouts, codeBlocks, telemetry, fileContent.mediaBaseUrl, { + enabled: supported && this._configurationService.getValue<boolean>(highlightsVideoSetting) === true, + onDidResolve: available => { + if (available && supported && !fileContent.isPreview && !isConfigured(preference) && preference.policyValue === undefined && preference.memoryValue === undefined) { + logSettingExperimentTrigger(this._telemetryService, highlightsVideoSetting); + } + }, + onInvalid: () => this._logService.warn('[ReleaseNotes] Invalid highlights video candidate'), + }); const colorMap = TokenizationRegistry.getColorMap(); const css = colorMap ? generateTokensCSSForColorMap(colorMap) : ''; @@ -713,6 +735,54 @@ export class ReleaseNotesManager extends Disposable { margin-bottom: 0; } + .release-highlights-video { + border-top: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, var(--vscode-textSeparator-foreground)); + margin-top: var(--vscode-spacing-size160); + padding-top: var(--vscode-spacing-size80); + } + + .release-highlights-video > summary { + cursor: pointer; + border-radius: var(--vscode-cornerRadius-small); + padding: var(--vscode-spacing-size80) var(--vscode-spacing-size40); + font-weight: var(--vscode-fontWeight-semiBold); + } + + .release-highlights-video > summary:hover { + background-color: var(--vscode-list-hoverBackground); + } + + body:is(.vscode-high-contrast, .vscode-high-contrast-light) .release-highlights-video > summary:hover:not(:focus-visible) { + outline: var(--vscode-strokeThickness) dashed var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); + } + + body:is(.vscode-high-contrast, .vscode-high-contrast-light) .release-highlights-video[open] > summary:not(:focus-visible) { + outline: var(--vscode-strokeThickness) solid var(--vscode-contrastActiveBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); + } + + .release-highlights-video > summary:focus-visible, + .release-highlights-video video:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); + } + + .release-highlights-video video { + display: block; + width: 100%; + height: auto; + border-radius: var(--vscode-cornerRadius-small); + margin-top: var(--vscode-spacing-size80); + } + + .release-highlights-video > p { + color: var(--vscode-descriptionForeground); + font-size: var(--vscode-fontSize-label1); + margin-top: var(--vscode-spacing-size80); + overflow-wrap: anywhere; + } + .highlights-table { width: 100%; table-layout: fixed; @@ -897,7 +967,7 @@ export class ReleaseNotesManager extends Disposable { input.addEventListener('change', event => { vscode.postMessage({ type: 'showReleaseNotes', documentId, value: input.checked }, '*'); }); - ${telemetry ? `(${initializeReleaseNotesTelemetry.toString()})(document, window, documentId, ${JSON.stringify(telemetry.manifest.regions)}, vscode, ${JSON.stringify(telemetry.manifest.tryouts.map(tryout => tryout.index))});` : ''} + ${telemetry ? `(${initializeReleaseNotesTelemetry.toString()})(document, window, documentId, ${JSON.stringify(telemetry.manifest.regions)}, vscode, ${JSON.stringify(telemetry.manifest.tryouts.map(tryout => tryout.index))}, ${!!telemetry.manifest.highlightsVideo});` : ''} vscode.postMessage({ type: 'releaseNotesReady', documentId }); (${initializeReleaseNotesNavigation.toString()})(document, window); </script> @@ -947,6 +1017,7 @@ export class ReleaseNotesManager extends Disposable { * - `STABLE` - Content shown in VS Code Stable only * - `INSIDERS` - Content shown in VS Code Insiders only * - `TRYOUTS` - Content shown only when the local Try This renderer is provided + * - `HIGHLIGHTS_VIDEO` - An available highlights video enabled by the local preference * * On the website, the entire block is a single HTML comment, so the * content is hidden by default. The website renderer would activate @@ -977,6 +1048,7 @@ export async function renderReleaseNotesMarkdown( codeBlocks?: IReleaseNotesCodeBlock[], telemetry?: ReleaseNotesTelemetry, mediaBaseUrl?: string, + highlightsVideo?: IHighlightsVideoOptions, ): Promise<TrustedHTML> { // Remove HTML comment markers around table of contents navigation text = text @@ -984,6 +1056,65 @@ export async function renderReleaseNotesMarkdown( .replace(/<!--\s*TOC\s*/gi, '') .replace(/\s*Navigation End\s*-->/gi, ''); + let videoAvailable = false; + /* eslint-disable eslint-js/no-restricted-syntax -- Inspect only authored release-note HTML in an inert document. */ + text = text.replace(/<!--\s*%IF\s+HIGHLIGHTS_VIDEO\s*%([\s\S]*?)%ENDIF\s*%\s*-->/gi, (_match, block: string) => { + if (!block.trim()) { + return ''; + } + // A document without a browsing context keeps media inert while checking both arms. + const candidate = mainWindow.document.implementation.createHTMLDocument().body; + safeSetInnerHtml(candidate, block, { + allowedTags: { override: ['details', 'summary', 'video', 'source', 'track', 'p', 'a'] }, + allowedAttributes: { override: ['class', 'open', 'src', 'poster', 'title', 'aria-label', 'controls', 'preload', 'playsinline', 'crossorigin', 'kind', 'srclang', 'label', 'default', 'href'] }, + allowedLinkProtocols: { override: [Schemas.https] }, + allowedMediaProtocols: { override: [Schemas.https] }, + allowRelativeMediaPaths: true, + }); + if (!candidate.children.length && !candidate.textContent?.trim()) { + return ''; + } + const video = candidate.querySelector('video'); + const validMedia = (value: string | null | undefined) => !!value && !/[<>]/.test(value) && /^(?:https:\/\/|(?:\.\/)?images\/)/.test(value); + if (videoAvailable || !video || !validMedia(video.getAttribute('src') ?? video.querySelector('source')?.getAttribute('src'))) { + highlightsVideo?.onInvalid?.(); + return ''; + } + videoAvailable = true; + let disclosure = video.closest('details'); + if (!disclosure) { + const content = Array.from(candidate.childNodes); + disclosure = $<HTMLDetailsElement>('details'); + candidate.appendChild(disclosure); + disclosure.append(...content); + } + disclosure.classList.add('release-highlights-video'); + let summary = disclosure.querySelector('summary'); + if (!summary) { + summary = $('summary'); + disclosure.prepend(summary); + } + if (!summary.textContent?.trim()) { + summary.textContent = nls.localize('releaseNotes.highlightsVideoSummary', "Watch release highlights"); + } + if (!video.getAttribute('title')?.trim() && !video.getAttribute('aria-label')?.trim()) { + video.setAttribute('aria-label', nls.localize('releaseNotes.highlightsVideoLabel', "Release highlights video")); + } + disclosure.setAttribute('open', ''); + video.setAttribute('controls', ''); + video.setAttribute('preload', 'none'); + video.setAttribute('playsinline', ''); + highlightsVideo?.onDidResolve?.(true); + return highlightsVideo?.enabled ? disclosure.outerHTML : ''; + }); + /* eslint-enable eslint-js/no-restricted-syntax */ + if (!videoAvailable) { + highlightsVideo?.onDidResolve?.(false); + } + if (telemetry) { + telemetry.metadata.highlightsVideoVariant = videoAvailable ? highlightsVideo?.enabled ? 'video' : 'text' : 'unavailable'; + } + // Process conditional blocks based on active conditions const activeConditions = new Set<string>(['IN_PRODUCT']); if (quality === 'stable') { @@ -1005,8 +1136,8 @@ export async function renderReleaseNotesMarkdown( allowedLinkProtocols: { override: [Schemas.http, Schemas.https, Schemas.command, Schemas.codeSetting] }, - allowedTags: { augment: ['nav', 'svg', 'path'] }, - allowedAttributes: { augment: ['aria-role', 'viewBox', 'fill', 'xmlns', 'd'] } + allowedTags: { augment: ['nav', 'svg', 'path', 'track'] }, + allowedAttributes: { augment: ['aria-role', 'viewBox', 'fill', 'xmlns', 'd', 'open', 'preload', 'crossorigin', 'kind', 'srclang', 'label', 'default', 'aria-label'] } }; const codeBlockIds = new WeakMap<marked.Token, string>(); const tryoutCodeSpans = new WeakSet<marked.Tokens.Codespan>(); @@ -1052,8 +1183,8 @@ export async function renderReleaseNotesMarkdown( const container = $('div'); safeSetInnerHtml(container, content.toString(), tryoutSanitizerConfig); if (mediaBaseUrl) { - // eslint-disable-next-line no-restricted-syntax -- These media elements are authored in the release note Markdown. - for (const element of container.querySelectorAll('img, video, source')) { + // eslint-disable-next-line eslint-js/no-restricted-syntax -- These media elements are authored in the release note Markdown. + for (const element of container.querySelectorAll('img, video, source, track')) { for (const attribute of ['src', 'poster']) { const value = element.getAttribute(attribute); if (value) { @@ -1069,7 +1200,7 @@ export async function renderReleaseNotesMarkdown( return sanitizeHtml(container.innerHTML, tryoutSanitizerConfig); } -/* eslint-disable no-restricted-syntax -- These serialized functions access IDs owned by the isolated release notes webview. */ +/* eslint-disable eslint-js/no-restricted-syntax -- These serialized functions access IDs owned by the isolated release notes webview. */ export function initializeReleaseNotesNavigation(targetDocument: Document, targetWindow: Window & typeof globalThis): () => void { const navigation = targetDocument.getElementById('toc-nav'); if (!navigation) { @@ -1175,4 +1306,4 @@ export function applyReleaseNotesTokenization(targetDocument: Document, update: scrollingElement.scrollLeft = scrollLeft; } } -/* eslint-enable no-restricted-syntax */ +/* eslint-enable eslint-js/no-restricted-syntax */ diff --git a/src/vs/workbench/contrib/update/browser/releaseNotesTelemetry.ts b/src/vs/workbench/contrib/update/browser/releaseNotesTelemetry.ts index c2ba37349cb3..29b80be0d9ad 100644 --- a/src/vs/workbench/contrib/update/browser/releaseNotesTelemetry.ts +++ b/src/vs/workbench/contrib/update/browser/releaseNotesTelemetry.ts @@ -12,7 +12,8 @@ export type ReleaseNotesSource = 'automaticUpdate' | 'command' | 'updateMenu' | type ContentKind = 'section' | 'note' | 'highlights' | 'highlight'; type Reason = 'periodic' | 'hidden' | 'blur' | 'idle' | 'contentExit' | 'qualified' | 'closed' | 'replaced' | 'shutdown'; type Action = 'link' | 'sectionNavigation' | 'setting' | 'tryoutRun' | 'tryoutSetup' | 'showOnUpdateChanged'; -type TargetKind = 'documentation' | 'external' | 'command' | 'anchor' | 'other'; +type TargetKind = 'documentation' | 'external' | 'command' | 'anchor' | 'highlightsVideo' | 'other'; +type VideoAction = 'shown' | 'played' | 'ended' | 'error'; export interface IReleaseNotesRegion { readonly index: number; @@ -26,6 +27,7 @@ export interface IReleaseNotesManifest { readonly regions: readonly IReleaseNotesRegion[]; readonly links: readonly { readonly index: number; readonly contentIndex: number; readonly targetKind: TargetKind; readonly settingUri?: string }[]; readonly tryouts: readonly { readonly index: number; readonly linkIndex: number; readonly contentIndex: number }[]; + readonly highlightsVideo?: boolean; } interface ISample { @@ -33,6 +35,7 @@ interface ISample { readonly tryouts: readonly number[]; readonly depth: number; readonly isScrollable: boolean; + readonly highlightsVideoVisible?: boolean; } interface ICallbacks { @@ -46,6 +49,7 @@ type CommonEvent = { notesVersion: string; notesRevision: string; contentVariant: 'stable' | 'insider' | 'other'; + highlightsVideoVariant: 'unavailable' | 'text' | 'video'; }; type CommonClassification = { @@ -56,6 +60,12 @@ type CommonClassification = { notesVersion: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The normalized public release major and minor version.' }; notesRevision: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'SHA-256 of the public, unpersonalized release document; empty if fetching failed.' }; contentVariant: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The bounded conditional-rendering variant: stable, insider, or other.' }; + highlightsVideoVariant: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the source has no usable highlights video, the candidate was omitted, or the player was rendered. Combined with the source revision and content variant to identify positional occurrences.' }; +}; +type VideoEvent = CommonEvent & { action: VideoAction; errorCode: 'none' | 'aborted' | 'network' | 'decode' | 'unsupported' }; +type VideoClassification = CommonClassification & { + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'First visible player exposure, actual playback, reaching ended (which may follow seeking), or a media error, once per action per opening.' }; + errorCode: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Bounded native media error category, or none; no error text or media URL.' }; }; type OpenEvent = CommonEvent & { source: ReleaseNotesSource; outcome: 'rendered' | 'failed' | 'superseded'; durationMs: number; failureStage?: 'fetch' | 'render' }; type OpenClassification = CommonClassification & { @@ -150,6 +160,7 @@ export class ReleaseNotesTelemetry extends Disposable { private readonly dwell = new Map<number, IDwell>(); private readonly tryoutDwell = new Map<number, { key: string; continuousMs: number }>(); private readonly shownTryouts = new Set<string>(); + private readonly videoActions = new Set<VideoAction>(); private visibleMs = 0; private activeReadingMs = 0; private checkpointActiveMs = 0; @@ -168,9 +179,10 @@ export class ReleaseNotesTelemetry extends Disposable { ) { super(); this.metadata = { - schemaVersion: 1, viewInstanceId: ++nextInstanceId, + schemaVersion: 2, viewInstanceId: ++nextInstanceId, notesVersion: /^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[a-zA-Z0-9.-]+)?$/.test(version) ? version.split('.').slice(0, 2).join('.') : 'unknown', notesRevision: '', contentVariant: quality === 'stable' || quality === 'insider' ? quality : 'other', + highlightsVideoVariant: 'unavailable', }; this.started = this.lastTime = this.lastActivity = callbacks.now(); this.enabled = telemetryService.telemetryLevel === TelemetryLevel.USAGE; @@ -215,6 +227,7 @@ export class ReleaseNotesTelemetry extends Disposable { this.active = active && visible; this.updateRegions(); this.show(); + this.showVideo(); } activity(): void { @@ -229,21 +242,34 @@ export class ReleaseNotesTelemetry extends Disposable { return false; } if (message.type === 'releaseNotesTelemetrySample') { - if (Object.keys(message).some(key => !['type', 'documentId', 'contents', 'tryouts', 'depth', 'isScrollable'].includes(key)) + if (Object.keys(message).some(key => !['type', 'documentId', 'contents', 'tryouts', 'depth', 'isScrollable', 'highlightsVideoVisible'].includes(key)) || !this.validIndexes(message.contents, this.manifest.regions) || !this.validIndexes(message.tryouts, this.manifest.tryouts) || typeof message.depth !== 'number' || !Number.isFinite(message.depth) || message.depth < 0 || message.depth > 100 - || typeof message.isScrollable !== 'boolean') { + || typeof message.isScrollable !== 'boolean' + || message.highlightsVideoVisible !== undefined && (typeof message.highlightsVideoVisible !== 'boolean' || message.highlightsVideoVisible && !this.manifest.highlightsVideo)) { return false; } this.tick(); - this.sample = { contents: message.contents, tryouts: message.tryouts, depth: message.depth, isScrollable: message.isScrollable }; + this.sample = { contents: message.contents, tryouts: message.tryouts, depth: message.depth, isScrollable: message.isScrollable, highlightsVideoVisible: message.highlightsVideoVisible === true }; if (!this.ready) { this.lastActivity = this.callbacks.now(); this.ready = true; } this.updateRegions(); this.show(); + this.showVideo(); + } else if (message.type === 'releaseNotesTelemetryVideo') { + if (!this.manifest.highlightsVideo || this.metadata.highlightsVideoVariant !== 'video' + || Object.keys(message).some(key => !['type', 'documentId', 'action', 'errorCode'].includes(key)) + || message.action !== 'played' && message.action !== 'ended' && message.action !== 'error' + || (message.action === 'error' + ? typeof message.errorCode !== 'number' || !Number.isInteger(message.errorCode) || message.errorCode < 1 || message.errorCode > 4 + : message.errorCode !== undefined)) { + return false; + } + const errorCode = message.errorCode === 1 ? 'aborted' : message.errorCode === 2 ? 'network' : message.errorCode === 3 ? 'decode' : message.errorCode === 4 ? 'unsupported' : 'none'; + this.video(message.action, errorCode); } else if (message.type === 'releaseNotesTelemetryActivity') { if (Object.keys(message).some(key => !['type', 'documentId'].includes(key))) { return false; @@ -264,6 +290,20 @@ export class ReleaseNotesTelemetry extends Disposable { return true; } + private showVideo(): void { + if (this.sample.highlightsVideoVisible && this.manifest.highlightsVideo && this.metadata.highlightsVideoVariant === 'video') { + this.video('shown', 'none'); + } + } + + private video(action: VideoAction, errorCode: VideoEvent['errorCode']): void { + if (!this.canLog() || !this.ready || !this.visible || this.videoActions.has(action)) { + return; + } + this.videoActions.add(action); + this.telemetryService.publicLog2<VideoEvent, VideoClassification>('releaseNotes.highlightsVideo', { ...this.metadata, action, errorCode }); + } + private validIndexes(value: unknown, entries: readonly { readonly index: number }[]): value is number[] { const indexes = new Set(entries.map(entry => entry.index)); return Array.isArray(value) && value.length <= indexes.size @@ -304,7 +344,9 @@ export class ReleaseNotesTelemetry extends Disposable { while (sectionIndex >= 0 && !this.manifest.regions[sectionIndex].headingLevel) { sectionIndex = this.manifest.regions[sectionIndex].parentIndex; } - this.interactions++; + if (link?.targetKind !== 'highlightsVideo') { + this.interactions++; + } this.telemetryService.publicLog2<InteractionEvent, InteractionClassification>('releaseNotes.interaction', { ...this.metadata, action, contentIndex, sectionIndex, linkIndex: index, ...(link ? { targetKind: link.targetKind } : {}), ...extra, @@ -477,7 +519,7 @@ export class ReleaseNotesTelemetry extends Disposable { } } -/* eslint-disable no-restricted-syntax -- These helpers inspect only the isolated release-notes document. */ +/* eslint-disable eslint-js/no-restricted-syntax -- These helpers inspect only the isolated release-notes document. */ /** Assigns bounded identities after sanitization; labels are available only in the offline manifest. */ export function indexReleaseNotesContent(container: HTMLElement): IReleaseNotesManifest { for (const element of container.querySelectorAll('[data-release-notes-content-index], [data-release-notes-link-index]')) { @@ -548,7 +590,7 @@ export function indexReleaseNotesContent(container: HTMLElement): IReleaseNotesM const index = links.length; const occurrence = anchor?.closest<HTMLElement>('[data-release-notes-tryout-index]'); const fallback = element.matches('.release-notes-tryout-fallback') || element.querySelector('.release-notes-tryout-fallback'); - const targetKind: TargetKind = occurrence || fallback ? 'command' + const targetKind: TargetKind = element.closest('.release-highlights-video') ? 'highlightsVideo' : occurrence || fallback ? 'command' : href.startsWith('#') ? 'anchor' : uri.scheme === Schemas.command ? 'command' : uri.scheme === Schemas.http || uri.scheme === Schemas.https ? uri.authority === 'code.visualstudio.com' ? 'documentation' : 'external' : 'other'; links.push({ index, contentIndex, targetKind, ...(uri.scheme === Schemas.codeSetting ? { settingUri: (anchor as HTMLAnchorElement).href } : {}) }); @@ -557,7 +599,7 @@ export function indexReleaseNotesContent(container: HTMLElement): IReleaseNotesM tryouts.push({ index: Number(occurrence.dataset.releaseNotesTryoutIndex), linkIndex: index, contentIndex }); } } - return { regions: ranged, links, tryouts }; + return { regions: ranged, links, tryouts, ...(container.querySelector('.release-highlights-video video') ? { highlightsVideo: true } : {}) }; } /** Serialized into the existing nonce-protected webview; it never sends text or destinations. */ @@ -568,6 +610,7 @@ export function initializeReleaseNotesTelemetry( regions: readonly IReleaseNotesRegion[], vscode: { postMessage(message: object): void }, tryoutIndexes: readonly number[] = [], + hasHighlightsVideo = false, ): () => void { const controller = new targetWindow.AbortController(); const options = { signal: controller.signal }; @@ -578,6 +621,8 @@ export function initializeReleaseNotesTelemetry( let frame: number | undefined; let presented = false; let lastActivity = -Infinity; + const video = hasHighlightsVideo ? targetDocument.querySelector<HTMLVideoElement>('.release-highlights-video video') : null; + const videoDisclosure = video?.closest('details'); const intersecting = (top: number, bottom: number) => { const height = Math.max(0, bottom - top); return height > 0 && Math.min(bottom, targetWindow.innerHeight) - Math.max(top, 0) >= Math.min(height, targetWindow.innerHeight) / 2; @@ -615,6 +660,7 @@ export function initializeReleaseNotesTelemetry( type: 'releaseNotesTelemetrySample', documentId, contents, tryouts, depth: distance > 0 ? Math.max(0, Math.min(100, 100 * scrolling!.scrollTop / distance)) : 100, isScrollable: distance > 0, + ...(video ? { highlightsVideoVisible: !!videoDisclosure?.open && !video.hidden && video.getClientRects().length > 0 && intersecting(video.getBoundingClientRect().top, video.getBoundingClientRect().bottom) } : {}), }); }; const schedule = () => { @@ -640,6 +686,25 @@ export function initializeReleaseNotesTelemetry( targetWindow.addEventListener('resize', schedule, options); targetWindow.addEventListener('pageshow', schedule, options); targetDocument.addEventListener('visibilitychange', schedule, options); + if (video) { + const report = (action: 'played' | 'ended' | 'error', event: Event) => { + if (event.isTrusted && presented && targetDocument.visibilityState === 'visible') { + vscode.postMessage({ type: 'releaseNotesTelemetryVideo', documentId, action, ...(action === 'error' ? { errorCode: video.error?.code } : {}) }); + } + }; + video.addEventListener('playing', event => { + if (!video.paused && !video.ended && video.readyState >= 2) { + report('played', event); + } + }, options); + video.addEventListener('ended', event => { + if (video.ended) { + report('ended', event); + } + }, options); + video.addEventListener('error', event => report('error', event), options); + videoDisclosure?.addEventListener('toggle', schedule, options); + } targetWindow.addEventListener('message', event => { if (event.data?.type === 'releaseNotesTelemetryMeasure' && event.data.documentId === documentId) { // The webview shell delivers host messages only after presenting and restoring the content. @@ -659,4 +724,4 @@ export function initializeReleaseNotesTelemetry( targetWindow.addEventListener('pagehide', dispose, { ...options, once: true }); return dispose; } -/* eslint-enable no-restricted-syntax */ +/* eslint-enable eslint-js/no-restricted-syntax */ diff --git a/src/vs/workbench/contrib/update/browser/releaseNotesTryouts.ts b/src/vs/workbench/contrib/update/browser/releaseNotesTryouts.ts index f181b3b38b48..d7726447506c 100644 --- a/src/vs/workbench/contrib/update/browser/releaseNotesTryouts.ts +++ b/src/vs/workbench/contrib/update/browser/releaseNotesTryouts.ts @@ -108,13 +108,13 @@ export class ReleaseNotesTryouts extends Disposable { } render(container: HTMLElement): void { - // eslint-disable-next-line no-restricted-syntax -- Fetched HTML does not have workbench element references. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- Fetched HTML does not have workbench element references. for (const element of container.querySelectorAll('[data-release-notes-tryout-id], [data-release-notes-tryout-index]')) { element.removeAttribute('data-release-notes-tryout-id'); element.removeAttribute('data-release-notes-tryout-index'); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const link of container.querySelectorAll<HTMLAnchorElement>('a[href]')) { let id: string | undefined; try { @@ -350,7 +350,7 @@ export class ReleaseNotesTryouts extends Disposable { } } -/* eslint-disable no-restricted-syntax -- These functions inspect an isolated, serialized webview document. */ +/* eslint-disable eslint-js/no-restricted-syntax -- These functions inspect an isolated, serialized webview document. */ function applyReleaseNotesTryoutState(element: HTMLElement, state: IReleaseNotesTryoutState): void { const link = element.querySelector<HTMLAnchorElement>('.release-notes-tryout-link')!; const message = element.querySelector<HTMLElement>('.release-notes-tryout-message')!; @@ -442,4 +442,4 @@ export function initializeReleaseNotesTryouts( vscode.postMessage({ type: 'releaseNotesTryoutsReady', documentId }); return () => controller.abort(); } -/* eslint-enable no-restricted-syntax */ +/* eslint-enable eslint-js/no-restricted-syntax */ diff --git a/src/vs/workbench/contrib/update/browser/updateTitleBarEntry.ts b/src/vs/workbench/contrib/update/browser/updateTitleBarEntry.ts index edaddf9ca884..241c2a7cc241 100644 --- a/src/vs/workbench/contrib/update/browser/updateTitleBarEntry.ts +++ b/src/vs/workbench/contrib/update/browser/updateTitleBarEntry.ts @@ -354,12 +354,12 @@ export class UpdateTitleBarEntry extends BaseActionViewItem { case StateType.CheckingForUpdates: label.textContent = localize('updateIndicator.checking', "Checking..."); - this.renderProgressState(this.content); + this.renderProgressState(this.content, label); break; case StateType.Overwriting: label.textContent = localize('updateIndicator.overwriting', "Updating..."); - this.renderProgressState(this.content); + this.renderProgressState(this.content, label); break; case StateType.AvailableForDownload: @@ -371,22 +371,22 @@ export class UpdateTitleBarEntry extends BaseActionViewItem { case StateType.Downloading: label.textContent = localize('updateIndicator.downloading', "Downloading..."); - this.renderProgressState(this.content, computeProgressPercent(state.downloadedBytes, state.totalBytes)); + this.renderProgressState(this.content, label, computeProgressPercent(state.downloadedBytes, state.totalBytes)); break; case StateType.Updating: label.textContent = localize('updateIndicator.installing', "Installing..."); - this.renderProgressState(this.content, computeProgressPercent(state.currentProgress, state.maxProgress)); + this.renderProgressState(this.content, label, computeProgressPercent(state.currentProgress, state.maxProgress)); break; case StateType.Restarting: label.textContent = localize('updateIndicator.restarting', "Restarting..."); - this.renderProgressState(this.content); + this.renderProgressState(this.content, label); break; case StateType.Cancelling: label.textContent = localize('updateIndicator.cancelling', "Cancelling..."); - this.renderProgressState(this.content); + this.renderProgressState(this.content, label); break; default: @@ -397,12 +397,13 @@ export class UpdateTitleBarEntry extends BaseActionViewItem { this.element?.setAttribute('aria-label', label.textContent); } - private renderProgressState(content: HTMLElement, percentage?: number) { + private renderProgressState(content: HTMLElement, label: HTMLElement, percentage?: number) { if (percentage !== undefined) { content.classList.add('progress-percent'); content.style.setProperty('--update-progress', `${percentage}%`); } else { content.classList.add('progress-indefinite'); + dom.append(label, dom.$('span.indicator-progress')); } } } diff --git a/src/vs/workbench/contrib/update/test/browser/releaseNotesEditor.test.ts b/src/vs/workbench/contrib/update/test/browser/releaseNotesEditor.test.ts index 495e4cfe1232..70a3aa666abb 100644 --- a/src/vs/workbench/contrib/update/test/browser/releaseNotesEditor.test.ts +++ b/src/vs/workbench/contrib/update/test/browser/releaseNotesEditor.test.ts @@ -14,6 +14,8 @@ import { Emitter, Event } from '../../../../../base/common/event.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { FileAccess, Schemas } from '../../../../../base/common/network.js'; import { URI } from '../../../../../base/common/uri.js'; +import { VSBuffer, bufferToStream } from '../../../../../base/common/buffer.js'; +import { isWeb } from '../../../../../base/common/platform.js'; import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; @@ -28,7 +30,7 @@ import { AccessibleViewProviderId } from '../../../../../platform/accessibility/ import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; import { ICommandService } from '../../../../../platform/commands/common/commands.js'; -import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ContextMenuService } from '../../../../../platform/contextview/browser/contextMenuService.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; @@ -41,12 +43,17 @@ import { INotificationService } from '../../../../../platform/notification/commo import { TestNotificationService } from '../../../../../platform/notification/test/common/testNotificationService.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IRequestService } from '../../../../../platform/request/common/request.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; +import { TestExperimentTriggerTelemetryService } from '../../../../../platform/telemetry/test/common/experimentTriggerTestUtils.js'; import { TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; import { IHostService } from '../../../../services/host/browser/host.js'; import { ILifecycleService } from '../../../../services/lifecycle/common/lifecycle.js'; import { IEditorGroup, IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; import { IEditorService } from '../../../../services/editor/common/editorService.js'; import { IExtensionService } from '../../../../services/extensions/common/extensions.js'; +import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; import { AccessibilityVerbositySettingId } from '../../../accessibility/browser/accessibilityConfiguration.js'; import { createOnboardingTryoutUri, IOnboardingTryoutService, OnboardingTryoutAvailability, OnboardingTryoutResult, RUN_ONBOARDING_TRYOUT_COMMAND_ID } from '../../../onboarding/common/onboardingTryout.js'; import { IOverlayWebview, WebviewMessageReceivedEvent } from '../../../webview/browser/webview.js'; @@ -54,6 +61,7 @@ import { WebviewInput } from '../../../webviewPanel/browser/webviewEditorInput.j import { IWebviewWorkbenchService } from '../../../webviewPanel/browser/webviewWorkbenchService.js'; import { ReleaseNotesAccessibilityHelp } from '../../browser/releaseNotesAccessibilityHelp.js'; import { applyReleaseNotesTokenization, initializeReleaseNotesNavigation, ReleaseNotesManager } from '../../browser/releaseNotesEditor.js'; +import { releaseNotesWithHighlightsVideo } from './releaseNotesTestUtils.js'; suite('Release notes editor Try This integration', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -138,6 +146,7 @@ suite('Release notes editor Try This integration', () => { instantiationService.stub(IConfigurationService, new TestConfigurationService({ update: { showReleaseNotes: true } })); instantiationService.stub(IProductService, { quality: 'stable', enableTelemetry: false }); instantiationService.stub(IEnvironmentService, { isBuilt: false }); + instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(IExtensionService, { whenInstalledExtensionsRegistered: () => whenExtensionsRegistered() }); instantiationService.stub(ILanguageService, store.add(new LanguageService())); instantiationService.stub(IContextMenuService, store.add(instantiationService.createInstance(ContextMenuService))); @@ -150,6 +159,84 @@ suite('Release notes editor Try This integration', () => { return /const documentId = "(?<id>[^"]+)"/.exec(html[html.length - 1])!.groups!.id; } + function createVideoManager(enabled: boolean, explicit = false, sessionsWindow = false) { + manager.dispose(); + const telemetry = new TestExperimentTriggerTelemetryService(); + const configuration = new TestConfigurationService({ update: { showReleaseNotes: true, showReleaseHighlightsVideo: enabled } }); + const inspect = stub(configuration, 'inspect').callsFake(() => ({ value: enabled, defaultValue: enabled, ...(explicit ? { userValue: enabled } : {}) })); + store.add(toDisposable(() => inspect.restore())); + const request = stub().callsFake(async () => ({ res: { statusCode: 200, headers: {} }, stream: bufferToStream(VSBuffer.fromString(markdown)) })); + instantiationService.stub(IConfigurationService, configuration); + instantiationService.stub(ITelemetryService, telemetry); + instantiationService.stub(IRequestService, { request }); + instantiationService.stub(IWorkbenchEnvironmentService, { isBuilt: false, isSessionsWindow: sessionsWindow }); + instantiationService.stub(IEditorService, { + get activeEditor() { return activeEditor; }, + visibleEditorPanes: [], + onDidActiveEditorChange: Event.None, + onDidVisibleEditorsChange: Event.None, + }); + manager = store.add(instantiationService.createInstance(ReleaseNotesManager)); + return { telemetry, configuration, request }; + } + + test('video eligibility triggers in both arms once, excluding explicit choices and unsupported windows', async () => { + const results: { enabled: boolean; explicit: boolean; sessionsWindow: boolean; triggers: string[]; video: boolean }[] = []; + markdown = releaseNotesWithHighlightsVideo; + for (const enabled of [false, true]) { + for (const [explicit, sessionsWindow] of [[false, false], [true, false], [false, true]]) { + const { telemetry } = createVideoManager(enabled, explicit, sessionsWindow); + await manager.show('1.147.0', false); + await manager.show('1.147.0', false); + results.push({ enabled, explicit, sessionsWindow, triggers: telemetry.triggers, video: html.at(-1)!.includes('<video') }); + } + } + assert.deepStrictEqual(results, [false, true].flatMap(enabled => [[false, false], [true, false], [false, true]].map(([explicit, sessionsWindow]) => ({ + enabled, explicit, sessionsWindow, + triggers: !isWeb && !explicit && !sessionsWindow ? ['config.update.showReleaseHighlightsVideo'] : [], + video: !isWeb && !sessionsWindow && enabled, + })))); + }); + + test('missing videos stay cached until a fresh manager fetches the later revision', async () => { + markdown = '# Notes\n\nNo video yet.'; + const first = createVideoManager(true); + await manager.show('1.147.0', false); + markdown = releaseNotesWithHighlightsVideo; + await manager.show('1.147.0', false); + const cached = { requests: first.request.callCount, triggers: [...first.telemetry.triggers], video: html.at(-1)!.includes('<video') }; + const fresh = createVideoManager(true); + await manager.show('1.147.0', false); + assert.deepStrictEqual({ + cached, + fresh: { requests: fresh.request.callCount, triggers: fresh.telemetry.triggers, video: html.at(-1)!.includes('<video') }, + }, { + cached: { requests: 1, triggers: [], video: false }, + fresh: { requests: 1, triggers: isWeb ? [] : ['config.update.showReleaseHighlightsVideo'], video: !isWeb }, + }); + }); + + test('preference changes apply on the next opening without rewriting the existing document', async () => { + markdown = releaseNotesWithHighlightsVideo; + const { configuration } = createVideoManager(false, true); + await manager.show('1.147.0', true); + const before = html.length; + await configuration.setUserConfiguration('update.showReleaseHighlightsVideo', true); + configuration.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: key => key === 'update.showReleaseHighlightsVideo', affectedKeys: new Set(['update.showReleaseHighlightsVideo']), source: ConfigurationTarget.USER, change: { keys: [], overrides: [] } }); + const afterChange = html.length; + await manager.show('1.147.0', true); + assert.deepStrictEqual({ before, afterChange, afterReopen: html.length, video: html.at(-1)!.includes('<video') }, { + before: 1, afterChange: 1, afterReopen: 2, video: !isWeb, + }); + }); + + test('current-file video previews never trigger the experiment', async () => { + markdown = releaseNotesWithHighlightsVideo; + const { telemetry } = createVideoManager(true); + await manager.show('1.147.0', true); + assert.deepStrictEqual({ triggers: telemetry.triggers, productionTelemetry: html.at(-1)!.includes('releaseNotesTelemetrySample') }, { triggers: [], productionTelemetry: false }); + }); + test('preserves the CSP and only extends the existing command allowlist with the dispatcher', async () => { markdown += '\n<script>untrustedScript()</script>'; await manager.show('1.100.0', true); diff --git a/src/vs/workbench/contrib/update/test/browser/releaseNotesRenderer.test.ts b/src/vs/workbench/contrib/update/test/browser/releaseNotesRenderer.test.ts index c00a52a587d0..26f3b60da44d 100644 --- a/src/vs/workbench/contrib/update/test/browser/releaseNotesRenderer.test.ts +++ b/src/vs/workbench/contrib/update/test/browser/releaseNotesRenderer.test.ts @@ -17,6 +17,8 @@ import { IPreferencesService } from '../../../../services/preferences/common/pre import { processConditionalBlocks, renderReleaseNotesMarkdown } from '../../browser/releaseNotesEditor.js'; import { URI } from '../../../../../base/common/uri.js'; import { Emitter } from '../../../../../base/common/event.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { releaseNotesWithHighlightsVideo } from './releaseNotesTestUtils.js'; suite('Release notes renderer', () => { @@ -90,6 +92,130 @@ Navigation End --> assert.strictEqual(result.toString(), '<h2 id="editor">Editor</h2>\n<p>Details.</p>\n'); }); + test('preserves the accessible initially open video through both sanitization passes', async () => { + for (const mediaBaseUrl of [undefined, 'https://code.visualstudio.com/assets/updates/']) { + const availability: boolean[] = []; + const result = await renderReleaseNotesMarkdown(releaseNotesWithHighlightsVideo, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, mediaBaseUrl, { + enabled: true, onDidResolve: available => availability.push(available), + }); + const document = new mainWindow.DOMParser().parseFromString(result.toString(), 'text/html'); + const disclosure = document.querySelector('details'); + const video = disclosure?.querySelector('video'); + const captions = video?.querySelector('track'); + const base = mediaBaseUrl ?? 'images/'; + assert.deepStrictEqual({ + availability, + inHighlights: !!disclosure?.closest('.release-notes-highlights'), + open: disclosure?.open, + video: video ? ['src', 'poster', 'preload', 'controls', 'playsinline', 'autoplay', 'loop'].map(name => video.getAttribute(name)) : [], + captions: captions ? ['src', 'kind', 'srclang', 'label', 'default'].map(name => captions.getAttribute(name)) : [], + transcript: disclosure?.querySelector('.release-highlights-video-transcript')?.getAttribute('href'), + }, { + availability: [true], inHighlights: true, open: true, + video: [`${base}1_147/highlights.mp4`, `${base}1_147/highlights.webp`, 'none', '', '', null, null], + captions: [`${base}1_147/highlights.en.vtt`, 'captions', 'en', 'English', ''], + transcript: 'https://code.visualstudio.com/transcript', + }); + } + }); + + test('control detects the same candidate without rendering any video resources or disclosure', async () => { + const availability: boolean[] = []; + const result = await renderReleaseNotesMarkdown(releaseNotesWithHighlightsVideo, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, undefined, { + enabled: false, onDidResolve: available => availability.push(available), + }); + const document = new mainWindow.DOMParser().parseFromString(result.toString(), 'text/html'); + assert.deepStrictEqual({ + availability, + video: document.querySelector('details, video, track, source'), + videoLinks: document.querySelectorAll('.release-highlights-video-transcript, .release-highlights-video-fallback').length, + highlights: document.querySelector('.release-notes-highlights li')?.textContent, + remainingLink: document.querySelector('h2#editor + p a')?.getAttribute('href'), + }, { availability: [true], video: null, videoLinks: 0, highlights: 'Editor improvements', remainingLink: 'https://code.visualstudio.com/docs/editor' }); + }); + + test('a video source alone is sufficient and gets an accessible disclosure in treatment', async () => { + for (const enabled of [false, true]) { + for (const videoMarkup of ['<video src="images/1_146/demo.mp4"></video>', '<video><source src="images/1_146/demo.mp4"></video>']) { + const availability: boolean[] = []; + let invalid = 0; + const content = `<!-- %IF HIGHLIGHTS_VIDEO %\n${videoMarkup}\n%ENDIF % -->`; + const html = await renderReleaseNotesMarkdown(content, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, 'https://code.visualstudio.com/assets/updates/', { + enabled, onDidResolve: available => availability.push(available), onInvalid: () => invalid++, + }); + const document = new mainWindow.DOMParser().parseFromString(html.toString(), 'text/html'); + const disclosure = document.querySelector<HTMLDetailsElement>('details.release-highlights-video'); + const video = disclosure?.querySelector('video'); + assert.deepStrictEqual({ + availability, invalid, + open: disclosure?.open, + summary: disclosure?.querySelector('summary')?.textContent, + label: video?.getAttribute('aria-label'), + source: video?.getAttribute('src') ?? video?.querySelector('source')?.getAttribute('src'), + optionalContent: document.querySelector('track, a, [poster]'), + }, { + availability: [true], invalid: 0, + open: enabled ? true : undefined, + summary: enabled ? 'Watch release highlights' : undefined, + label: enabled ? 'Release highlights video' : undefined, + source: enabled ? 'https://code.visualstudio.com/assets/updates/1_146/demo.mp4' : undefined, + optionalContent: null, + }); + } + } + }); + + test('missing or incomplete optional metadata does not suppress an available video', async () => { + for (const content of [ + releaseNotesWithHighlightsVideo.replace(/<track[^>]*>/, '').replace(/<p><a class="release-highlights-video-transcript"[\s\S]*?<\/p>/, ''), + releaseNotesWithHighlightsVideo.replace('release-highlights-video-transcript', 'custom-transcript').replace('images/1_147/highlights.en.vtt', ''), + releaseNotesWithHighlightsVideo.replace('poster="images/1_147/highlights.webp"', '').replace('title="Video showing release highlights."', ''), + ]) { + const available: boolean[] = []; + let invalid = 0; + const html = await renderReleaseNotesMarkdown(content, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, undefined, { + enabled: true, onDidResolve: value => available.push(value), onInvalid: () => invalid++, + }); + assert.deepStrictEqual({ available, invalid, hasVideo: html.toString().includes('<video') }, { + available: [true], invalid: 0, hasVideo: true, + }); + } + }); + + test('absent and empty optional video blocks remain normal text in both arms', async () => { + const results: { enabled: boolean; availability: boolean[]; invalid: number; html: string }[] = []; + for (const enabled of [false, true]) { + for (const block of ['', '<!-- %IF HIGHLIGHTS_VIDEO %\n%ENDIF % -->', '<!-- %IF HIGHLIGHTS_VIDEO %\n<!-- No video yet. -->\n%ENDIF % -->']) { + const availability: boolean[] = []; + let invalid = 0; + const html = await renderReleaseNotesMarkdown(`# Notes\n\n${block}`, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, undefined, { + enabled, onDidResolve: available => availability.push(available), onInvalid: () => invalid++, + }); + results.push({ enabled, availability, invalid, html: html.toString().trim() }); + } + } + assert.deepStrictEqual(results, [false, true].flatMap(enabled => Array.from({ length: 3 }, () => ({ + enabled, availability: [false], invalid: 0, html: '<h1 id="notes">Notes</h1>', + })))); + }); + + test('malformed populated candidates are diagnosed and never rendered', async () => { + const results: { available: boolean[]; invalid: number; hasVideo: boolean }[] = []; + for (const content of [ + releaseNotesWithHighlightsVideo.replace('images/1_147/highlights.mp4', 'javascript:alert(1)'), + releaseNotesWithHighlightsVideo.replace('images/1_147/highlights.mp4', ''), + releaseNotesWithHighlightsVideo.replace(/<video[\s\S]*?<\/video>/, ''), + ]) { + const available: boolean[] = []; + let invalid = 0; + const html = await renderReleaseNotesMarkdown(content, extensionService, languageService, instantiationService.createInstance(SimpleSettingRenderer), 'stable', undefined, undefined, undefined, undefined, { + enabled: true, onDidResolve: value => available.push(value), onInvalid: () => invalid++, + }); + results.push({ available, invalid, hasVideo: html.toString().includes('<video') }); + } + assert.deepStrictEqual(results, Array.from({ length: 3 }, () => ({ available: [false], invalid: 1, hasVideo: false }))); + }); + test('Should render code settings', async () => { // Stub preferences service with a known setting so the SimpleSettingRenderer treats it as valid const testSettingId = 'editor.wordWrap'; diff --git a/src/vs/workbench/contrib/update/test/browser/releaseNotesTelemetry.test.ts b/src/vs/workbench/contrib/update/test/browser/releaseNotesTelemetry.test.ts new file mode 100644 index 000000000000..ad6285888ebf --- /dev/null +++ b/src/vs/workbench/contrib/update/test/browser/releaseNotesTelemetry.test.ts @@ -0,0 +1,144 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mainWindow } from '../../../../../base/browser/window.js'; +import { $, addDisposableListener, getWindow } from '../../../../../base/browser/dom.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TelemetryLevel } from '../../../../../platform/telemetry/common/telemetry.js'; +import { CapturingTelemetryService } from '../../../../../platform/telemetry/test/common/testTelemetryService.js'; +import { indexReleaseNotesContent, initializeReleaseNotesTelemetry, ReleaseNotesTelemetry } from '../../browser/releaseNotesTelemetry.js'; + +suite('Release notes highlights video telemetry', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const sample = { type: 'releaseNotesTelemetrySample', contents: [], tryouts: [], depth: 0, isScrollable: true, highlightsVideoVisible: true }; + + function createTracker() { + const service = new CapturingTelemetryService<{ action?: string; errorCode?: string; interactionCount?: number }>(); + const tracker = store.add(new ReleaseNotesTelemetry('1.147.0', 'stable', 'command', { now: () => 0, getTryout: () => undefined }, service)); + tracker.metadata.highlightsVideoVariant = 'video'; + tracker.manifest = { regions: [], links: [], tryouts: [], highlightsVideo: true }; + tracker.setVisibility(true, true); + return { service, tracker, events: () => service.events.filter(event => event.eventName === 'releaseNotes.highlightsVideo').map(event => event.data) }; + } + + test('deduplicates visible exposure and bounded playback diagnostics per document', () => { + const { tracker, events } = createTracker(); + tracker.receive(sample); + tracker.receive(sample); + for (let i = 0; i < 2; i++) { + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'played' }); + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'ended' }); + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'error', errorCode: 3 }); + } + assert.deepStrictEqual(events().map(({ action, errorCode }) => ({ action, errorCode })), [ + { action: 'shown', errorCode: 'none' }, + { action: 'played', errorCode: 'none' }, + { action: 'ended', errorCode: 'none' }, + { action: 'error', errorCode: 'decode' }, + ]); + }); + + test('rejects invalid messages and video messages for text-only documents', () => { + const { tracker, events } = createTracker(); + tracker.receive(sample); + const invalid = [ + { action: 'play' }, + { action: 'played', errorCode: 1 }, + { action: 'error', errorCode: NaN }, + { action: 'error', errorCode: 0 }, + { action: 'error', errorCode: 5 }, + { action: 'error', errorCode: 2.5 }, + { action: 'error', errorCode: 2, url: 'https://example.com/private' }, + ].map(message => tracker.receive({ type: 'releaseNotesTelemetryVideo', ...message })); + tracker.metadata.highlightsVideoVariant = 'text'; + const text = tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'played' }); + tracker.manifest = { regions: [], links: [], tryouts: [] }; + const missing = tracker.receive(sample); + assert.deepStrictEqual({ invalid, text, missing, actions: events().map(event => event.action) }, { + invalid: Array(7).fill(false), text: false, missing: false, actions: ['shown'], + }); + }); + + test('does not report video events before presentation, when hidden, without consent, or after disposal', () => { + const { tracker, service, events } = createTracker(); + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'played' }); + tracker.setVisibility(false, false); + tracker.receive(sample); + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'ended' }); + service.telemetryLevel = TelemetryLevel.NONE; + tracker.setVisibility(true, true); + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'played' }); + tracker.dispose(); + service.telemetryLevel = TelemetryLevel.USAGE; + tracker.receive({ type: 'releaseNotesTelemetryVideo', action: 'error', errorCode: 2 }); + assert.deepStrictEqual(events(), []); + }); + + test('video links have separate attribution and cannot inflate generic engagement counts', () => { + const { tracker, service } = createTracker(); + const document = new mainWindow.DOMParser().parseFromString('<h2>Highlights</h2><details class="release-highlights-video"><video></video><a href="https://example.com/transcript">Transcript</a></details><a href="https://code.visualstudio.com/docs">Documentation</a>', 'text/html'); + tracker.manifest = indexReleaseNotesContent(document.body); + tracker.receive({ ...sample, highlightsVideoVisible: false }); + tracker.receive({ type: 'releaseNotesTelemetryLink', index: 0 }); + tracker.receive({ type: 'releaseNotesTelemetryLink', index: 1 }); + tracker.finish('closed'); + assert.deepStrictEqual({ + targets: tracker.manifest.links.map(link => link.targetKind), + counts: service.events.filter(event => event.eventName === 'releaseNotes.engagement').map(event => event.data.interactionCount), + }, { targets: ['highlightsVideo', 'documentation'], counts: [1] }); + }); + + for (const serialized of [false, true]) { + test(`samples the real disclosure without autoplay or synthetic playback (${serialized ? 'serialized' : 'direct'})`, async () => { + const url = mainWindow.URL.createObjectURL(new Blob(['<!DOCTYPE html><body><details class="release-highlights-video" open><summary>Watch release highlights</summary><video width="320" height="120" preload="none"></video></details></body>'], { type: 'text/html' })); + store.add(toDisposable(() => mainWindow.URL.revokeObjectURL(url))); + const iframe = $<HTMLIFrameElement>('iframe', { src: url }); + const loaded = new DeferredPromise<void>(); + store.add(addDisposableListener(iframe, 'load', () => loaded.complete())); + iframe.style.cssText = 'position:fixed;top:0;left:0;width:600px;height:300px'; + mainWindow.document.body.appendChild(iframe); + store.add(toDisposable(() => iframe.remove())); + await loaded.p; + const document = iframe.contentDocument!; + const window = getWindow(document.body); + const disclosure = document.querySelector('details')!; + const video = document.querySelector('video')!; + const messages: object[] = []; + const initialize: typeof initializeReleaseNotesTelemetry = serialized ? new Function(`return (${initializeReleaseNotesTelemetry.toString()});`)() : initializeReleaseNotesTelemetry; + const dispose = initialize(document, window, 'video-document', [], { postMessage: message => messages.push(message) }, [], true); + store.add(toDisposable(dispose)); + const render = async () => { + window.dispatchEvent(new window.Event('resize')); + await new Promise<void>(resolve => window.requestAnimationFrame(() => resolve())); + }; + const visible = () => messages.filter((message): message is { highlightsVideoVisible: boolean } => 'highlightsVideoVisible' in message).at(-1)?.highlightsVideoVisible; + await render(); + const beforePresentation = messages.length; + window.dispatchEvent(new window.MessageEvent('message', { data: { type: 'releaseNotesTelemetryMeasure', documentId: 'stale-document' } })); + await render(); + const stalePresentation = messages.length; + window.dispatchEvent(new window.MessageEvent('message', { data: { type: 'releaseNotesTelemetryMeasure', documentId: 'video-document' } })); + await render(); + const expanded = visible(); + disclosure.open = false; + await render(); + const collapsed = visible(); + disclosure.open = true; + await render(); + video.dispatchEvent(new window.Event('playing')); + video.dispatchEvent(new window.Event('ended')); + video.dispatchEvent(new window.Event('error')); + dispose(); + assert.deepStrictEqual({ + beforePresentation, stalePresentation, expanded, collapsed, reexpanded: visible(), + paused: video.paused, + playbackMessages: messages.filter((message): message is { type: 'releaseNotesTelemetryVideo' } => 'type' in message && message.type === 'releaseNotesTelemetryVideo').length, + }, { beforePresentation: 0, stalePresentation: 0, expanded: true, collapsed: false, reexpanded: true, paused: true, playbackMessages: 0 }); + }); + } +}); diff --git a/src/vs/workbench/contrib/update/test/browser/releaseNotesTestUtils.ts b/src/vs/workbench/contrib/update/test/browser/releaseNotesTestUtils.ts new file mode 100644 index 000000000000..a8874bf35d08 --- /dev/null +++ b/src/vs/workbench/contrib/update/test/browser/releaseNotesTestUtils.ts @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export const releaseNotesWithHighlightsVideo = `# Release Notes + +<!-- RELEASE_HIGHLIGHTS_START --> +## Release highlights + +* [Editor improvements](#editor) + +<!-- %IF HIGHLIGHTS_VIDEO % +<details class="release-highlights-video"> + <summary>Watch release highlights (1 minute)</summary> + <video src="images/1_147/highlights.mp4" poster="images/1_147/highlights.webp" title="Video showing release highlights." autoplay loop> + <track kind="captions" src="images/1_147/highlights.en.vtt" srclang="en" label="English" default> + </video> + <p><a class="release-highlights-video-transcript" href="https://code.visualstudio.com/transcript">Read the transcript</a>. <a class="release-highlights-video-fallback" href="https://code.visualstudio.com/highlights.mp4">Open the video</a>.</p> +</details> +%ENDIF % --> +<!-- RELEASE_HIGHLIGHTS_END --> + +## Editor + +[Learn more](https://code.visualstudio.com/docs/editor). +`; diff --git a/src/vs/workbench/contrib/userDataProfile/browser/media/userDataProfilesEditor.css b/src/vs/workbench/contrib/userDataProfile/browser/media/userDataProfilesEditor.css index 683b23ee55c0..5119f02de812 100644 --- a/src/vs/workbench/contrib/userDataProfile/browser/media/userDataProfilesEditor.css +++ b/src/vs/workbench/contrib/userDataProfile/browser/media/userDataProfilesEditor.css @@ -201,7 +201,7 @@ cursor: pointer; line-height: 18px; padding: 0px 23px 0px 8px; - border-radius: 2px; + border-radius: var(--workbench-custom-inputs-corner-radius, 2px); } .profiles-editor .contents-container .profile-copy-from-container .profile-select-container { diff --git a/src/vs/workbench/contrib/webview/browser/overlayWebview.ts b/src/vs/workbench/contrib/webview/browser/overlayWebview.ts index 86d357e665c4..152a6e9fd0ad 100644 --- a/src/vs/workbench/contrib/webview/browser/overlayWebview.ts +++ b/src/vs/workbench/contrib/webview/browser/overlayWebview.ts @@ -14,6 +14,8 @@ import { URI } from '../../../../base/common/uri.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { IContextKey, IContextKeyService, IScopedContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js'; +import { ISizeService } from '../../../../platform/theme/common/sizeService.js'; +import { IThemeService } from '../../../../platform/theme/common/themeService.js'; import { IWorkbenchLayoutService } from '../../../services/layout/browser/layoutService.js'; import { IOverlayWebview, IWebview, IWebviewElement, IWebviewService, KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_ENABLED, KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_VISIBLE, WebviewContentOptions, WebviewExtensionDescription, WebviewInitInfo, WebviewMessageReceivedEvent, WebviewOptions } from './webview.js'; @@ -66,6 +68,8 @@ export class OverlayWebview extends Disposable implements IOverlayWebview { @IWorkbenchLayoutService private readonly _layoutService: IWorkbenchLayoutService, @IWebviewService private readonly _webviewService: IWebviewService, @IContextKeyService private readonly _baseContextKeyService: IContextKeyService, + @ISizeService sizeService: ISizeService, + @IThemeService themeService: IThemeService, ) { super(); @@ -76,6 +80,13 @@ export class OverlayWebview extends Disposable implements IOverlayWebview { this._extension = initInfo.extension; this._options = initInfo.options; this._contentOptions = initInfo.contentOptions; + const updateCorners = () => { + if (this._anchorState) { + this._syncOuterEdgeClasses(this._anchorState.anchorElement.closest('.part')); + } + }; + this._register(sizeService.onDidChangeSizes(updateCorners)); + this._register(themeService.onDidColorThemeChange(updateCorners)); } public get isFocused() { @@ -213,6 +224,10 @@ export class OverlayWebview extends Disposable implements IOverlayWebview { if (part) { const observer = new (getWindow(part).MutationObserver)(() => this._syncOuterEdgeClasses(part)); observer.observe(part, { attributes: true, attributeFilter: ['class'] }); + const root = part.closest('.monaco-workbench'); + if (root) { + observer.observe(root, { attributes: true, attributeFilter: ['class'] }); + } this._outerEdgeObserver.value = toDisposable(() => observer.disconnect()); } } @@ -237,6 +252,23 @@ export class OverlayWebview extends Disposable implements IOverlayWebview { || false); this.overlayLayout.content.classList.toggle(`webview-overlay-outer-${edge}`, isOuterEdge); } + + this.overlayLayout.content.style.removeProperty('border-radius'); + const root = part?.closest('.monaco-workbench'); + if (part && anchorBounds && contentBounds && !part.classList.contains('modal-editor-part') + && root?.matches('.floating-panels, .agent-sessions-workbench:not(.phone-layout)')) { + const touches = (edge: 'left' | 'right' | 'top' | 'bottom') => Math.abs(anchorBounds[edge] - contentBounds[edge]) <= 1; + // The anchor can cover only a subregion of the card, so resolve its actual exposed corners. + const css = getWindow(part).getComputedStyle(part); + const radius = (value: string, firstBorder: string, secondBorder: string) => + Math.max(0, Number.parseFloat(value) - Math.max(Number.parseFloat(firstBorder), Number.parseFloat(secondBorder))); + this.overlayLayout.content.style.borderRadius = [ + touches('top') && touches('left') ? radius(css.borderTopLeftRadius, css.borderTopWidth, css.borderLeftWidth) : 0, + touches('top') && touches('right') ? radius(css.borderTopRightRadius, css.borderTopWidth, css.borderRightWidth) : 0, + touches('bottom') && touches('right') ? radius(css.borderBottomRightRadius, css.borderBottomWidth, css.borderRightWidth) : 0, + touches('bottom') && touches('left') ? radius(css.borderBottomLeftRadius, css.borderBottomWidth, css.borderLeftWidth) : 0, + ].map(value => `${value}px`).join(' '); + } } private _show(targetWindow: CodeWindow) { diff --git a/src/vs/workbench/contrib/webview/browser/pre/index.html b/src/vs/workbench/contrib/webview/browser/pre/index.html index 0b840cb731b1..ab1372198daf 100644 --- a/src/vs/workbench/contrib/webview/browser/pre/index.html +++ b/src/vs/workbench/contrib/webview/browser/pre/index.html @@ -5,7 +5,7 @@ <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" - content="default-src 'none'; script-src 'sha256-29YeDbmHnhN2BgMJKVq7vDCMiuya6rpEctI6SkJFfJc=' 'self'; frame-src 'self'; style-src 'unsafe-inline';"> + content="default-src 'none'; script-src 'sha256-VY65u6y1DZWK8Cb4MlVpSVlMYcM338BRDVhygiwXLLg=' 'self'; frame-src 'self'; style-src 'unsafe-inline';"> <!-- Disable pinch zooming --> <meta name="viewport" @@ -1085,7 +1085,11 @@ } newFrame.setAttribute('sandbox', Array.from(sandboxRules).join(' ')); - const allowRules = ['cross-origin-isolated;', 'autoplay;', 'local-network-access;']; + const allowRules = ['cross-origin-isolated;', 'autoplay;']; + const supportedFeatures = /** @type {HTMLIFrameElement & { featurePolicy?: { features(): string[] } }} */ (newFrame).featurePolicy?.features(); + if (supportedFeatures?.includes('local-network-access')) { + allowRules.push('local-network-access;'); + } if (!isFirefox && options.allowScripts) { allowRules.push('clipboard-read;', 'clipboard-write;'); } @@ -1191,7 +1195,9 @@ const postSize = () => { hostMessaging.postMessage('updated-intrinsic-content-size', { width: docEl.offsetWidth, - height: docEl.offsetHeight + height: options.includeHorizontalScrollbarInContentHeight + ? Math.ceil(docEl.getBoundingClientRect().height + Math.max(0, contentWindow.innerHeight - docEl.clientHeight)) + : docEl.offsetHeight }); }; diff --git a/src/vs/workbench/contrib/webview/browser/pre/service-worker.js b/src/vs/workbench/contrib/webview/browser/pre/service-worker.js index d602e90988bd..fb6839c555d4 100644 --- a/src/vs/workbench/contrib/webview/browser/pre/service-worker.js +++ b/src/vs/workbench/contrib/webview/browser/pre/service-worker.js @@ -399,8 +399,22 @@ sw.addEventListener('install', (event) => { event.waitUntil(sw.skipWaiting()); // Activate worker immediately }); -sw.addEventListener('activate', (event) => { - event.waitUntil(sw.clients.claim()); // Become available to all pages +sw.addEventListener('activate', event => { + event.waitUntil((async () => { + try { + const cacheNames = await caches.keys(); + await Promise.all(cacheNames.map(async cacheName => { + const cacheVersion = /^vscode-resource-cache-(?<version>\d+)$/.exec(cacheName)?.groups?.version; + if (cacheVersion !== undefined && Number(cacheVersion) < VERSION) { + await caches.delete(cacheName); + } + })); + } catch { + // Cache cleanup must not prevent the webview from loading. + } + + await sw.clients.claim(); + })()); }); diff --git a/src/vs/workbench/contrib/webview/browser/themeing.ts b/src/vs/workbench/contrib/webview/browser/themeing.ts index fd4af39d746a..8588af5ed1ca 100644 --- a/src/vs/workbench/contrib/webview/browser/themeing.ts +++ b/src/vs/workbench/contrib/webview/browser/themeing.ts @@ -12,6 +12,7 @@ import { IConfigurationService } from '../../../../platform/configuration/common import * as colorRegistry from '../../../../platform/theme/common/colorRegistry.js'; import { getSizeRegistry, sizeValueToCss } from '../../../../platform/theme/common/sizeRegistry.js'; import { ColorScheme } from '../../../../platform/theme/common/theme.js'; +import { ISizeService } from '../../../../platform/theme/common/sizeService.js'; import { IWorkbenchColorTheme, IWorkbenchThemeService } from '../../../services/themes/common/workbenchThemeService.js'; import { WebviewStyles } from './webview.js'; @@ -32,12 +33,14 @@ export class WebviewThemeDataProvider extends Disposable { constructor( @IWorkbenchThemeService private readonly _themeService: IWorkbenchThemeService, @IConfigurationService private readonly _configurationService: IConfigurationService, + @ISizeService private readonly _sizeService: ISizeService, ) { super(); this._register(this._themeService.onDidColorThemeChange(() => { this._reset(); })); + this._register(this._sizeService.onDidChangeSizes(() => this._reset())); const webviewConfigurationKeys = ['editor.fontFamily', 'editor.fontWeight', 'editor.fontSize', 'editor.fontLigatures', 'accessibility.underlineLinks']; this._register(this._configurationService.onDidChangeConfiguration(e => { @@ -71,7 +74,7 @@ export class WebviewThemeDataProvider extends Disposable { const sizeRegistry = getSizeRegistry(); const exportedSizes = sizeRegistry.getSizes().reduce<Record<string, string>>((sizes, entry) => { - const sizeValue = sizeRegistry.resolveDefaultSize(entry.id, theme); + const sizeValue = this._sizeService.getSize(entry.id, theme); if (sizeValue) { sizes['vscode-' + entry.id.replace(/\./g, '-')] = sizeValueToCss(sizeValue); } diff --git a/src/vs/workbench/contrib/webview/browser/webview.ts b/src/vs/workbench/contrib/webview/browser/webview.ts index f950b7b5a64e..268ea1ea4a0e 100644 --- a/src/vs/workbench/contrib/webview/browser/webview.ts +++ b/src/vs/workbench/contrib/webview/browser/webview.ts @@ -5,6 +5,7 @@ import { IMouseWheelEvent } from '../../../../base/browser/mouseEvent.js'; import { CodeWindow } from '../../../../base/browser/window.js'; +import { IAction } from '../../../../base/common/actions.js'; import { equals } from '../../../../base/common/arrays.js'; import { Event } from '../../../../base/common/event.js'; import { IDisposable } from '../../../../base/common/lifecycle.js'; @@ -102,9 +103,15 @@ export interface WebviewOptions { */ readonly disableServiceWorker?: boolean; + /** Round up intrinsic height and include native horizontal scrollbar space for auto-sized content. */ + readonly includeHorizontalScrollbarInContentHeight?: boolean; + readonly tryRestoreScrollPosition?: boolean; readonly retainContextWhenHidden?: boolean; transformCssVariables?(styles: WebviewStyles): WebviewStyles; + + /** Host-owned actions prepended to this webview's context menu. */ + getContextMenuActions?(): IAction[]; } export interface WebviewContentOptions { diff --git a/src/vs/workbench/contrib/webview/browser/webviewElement.ts b/src/vs/workbench/contrib/webview/browser/webviewElement.ts index 22f5f8c4fb2f..dbb9b44fb1d3 100644 --- a/src/vs/workbench/contrib/webview/browser/webviewElement.ts +++ b/src/vs/workbench/contrib/webview/browser/webviewElement.ts @@ -93,8 +93,8 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi private _windowId: number | undefined = undefined; private get window() { return typeof this._windowId === 'number' ? getWindowById(this._windowId)?.window : undefined; } - private _encodedWebviewOriginPromise?: Promise<string>; private _encodedWebviewOrigin: string | undefined; + private readonly _mountDisposables = this._register(new DisposableStore()); protected get platform(): string { return 'browser'; } @@ -284,6 +284,7 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi ]); contextMenuService.showContextMenu({ menuId: MenuId.WebviewContext, + getActions: this._options.getContextMenuActions, menuActionOptions: { shouldForwardArgs: true }, contextKeyService, getActionsContext: (): WebviewActionContext => ({ ...data.context, webview: this.providedViewType }), @@ -430,7 +431,11 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi element.className = `webview ${options.customClasses || ''}`; element.sandbox.add('allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads'); - const allowRules = ['cross-origin-isolated', 'autoplay', 'local-network-access']; + const allowRules = ['cross-origin-isolated', 'autoplay']; + const supportedFeatures = (element as HTMLIFrameElement & { featurePolicy?: { features(): string[] } }).featurePolicy?.features(); + if (supportedFeatures?.includes('local-network-access')) { + allowRules.push('local-network-access'); + } if (!isFirefox) { allowRules.push('clipboard-read', 'clipboard-write'); } @@ -482,17 +487,31 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi this.element!.setAttribute('src', `${this.webviewContentEndpoint(encodedWebviewOrigin)}/${fileName}?${queryString}`); } + protected hashParentOrigin(parentOrigin: string): Promise<string> { + return parentOriginHash(parentOrigin, this.origin); + } + public mountTo(element: HTMLElement, targetWindow: CodeWindow) { if (!this.element) { return; } + this._mountDisposables.clear(); + this.element.remove(); this._windowId = targetWindow.vscodeWindowId; this._mountId = generateUuid(); - this._encodedWebviewOriginPromise = parentOriginHash(targetWindow.origin, this.origin).then(id => this._encodedWebviewOrigin = id); - this._encodedWebviewOriginPromise.then(encodedWebviewOrigin => { - if (!this._disposed) { + const mountId = this._mountId; + const originPromise = this.hashParentOrigin(targetWindow.origin).then(id => { + if (this._mountId === mountId) { + this._encodedWebviewOrigin = id; + } + return id; + }); + originPromise.then(encodedWebviewOrigin => { + if (!this._disposed && this._mountId === mountId) { this._initElement(encodedWebviewOrigin, this.extension, this._options, targetWindow); + this.perfMark('mounted'); + element.appendChild(this.element!); } }); this._registerMessageHandler(targetWindow); @@ -502,21 +521,18 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi } for (const eventName of [EventType.MOUSE_DOWN, EventType.MOUSE_MOVE, EventType.DROP]) { - this._register(addDisposableListener(element, eventName, () => { + this._mountDisposables.add(addDisposableListener(element, eventName, () => { this._stopBlockingIframeDragEvents(); })); } for (const node of [element, targetWindow]) { - this._register(addDisposableListener(node, EventType.DRAG_END, () => { + this._mountDisposables.add(addDisposableListener(node, EventType.DRAG_END, () => { this._stopBlockingIframeDragEvents(); })); } element.id = this.id; // This is used by aria-flow for accessibility order - - this.perfMark('mounted'); - element.appendChild(this.element); } private resetHostChannel(): void { @@ -717,6 +733,7 @@ export class WebviewElement extends Disposable implements IWebviewElement, Webvi allowMultipleAPIAcquire: !!this._content.options.allowMultipleAPIAcquire, allowScripts: allowScripts, allowForms: this._content.options.allowForms ?? allowScripts, // For back compat, we allow forms by default when scripts are enabled + includeHorizontalScrollbarInContentHeight: this._options.includeHorizontalScrollbarInContentHeight, }, state: this._content.state, cspSource: webviewGenericCspSource, diff --git a/src/vs/workbench/contrib/webview/browser/webviewMessages.d.ts b/src/vs/workbench/contrib/webview/browser/webviewMessages.d.ts index 78de0fa57c2e..f4e0901e636a 100644 --- a/src/vs/workbench/contrib/webview/browser/webviewMessages.d.ts +++ b/src/vs/workbench/contrib/webview/browser/webviewMessages.d.ts @@ -55,6 +55,7 @@ interface UpdateContentEvent { allowMultipleAPIAcquire: boolean; allowScripts: boolean; allowForms: boolean; + includeHorizontalScrollbarInContentHeight?: boolean; }; state: any; cspSource: string; diff --git a/src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts b/src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts index 51ccfc465d0f..55737844ac7b 100644 --- a/src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts +++ b/src/vs/workbench/contrib/webview/electron-browser/webviewCommands.ts @@ -27,7 +27,7 @@ export class OpenWebviewDeveloperToolsAction extends Action2 { async run(accessor: ServicesAccessor): Promise<void> { const nativeHostService = accessor.get(INativeHostService); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const iframeWebviewElements = getActiveWindow().document.querySelectorAll('iframe.webview.ready'); if (iframeWebviewElements.length) { console.info(nls.localize('iframeWebviewAlert', "Using standard dev tools to debug iframe based webview")); diff --git a/src/vs/workbench/contrib/webview/test/browser/overlayWebview.test.ts b/src/vs/workbench/contrib/webview/test/browser/overlayWebview.test.ts index ff86326df5fd..8226b75711f2 100644 --- a/src/vs/workbench/contrib/webview/test/browser/overlayWebview.test.ts +++ b/src/vs/workbench/contrib/webview/test/browser/overlayWebview.test.ts @@ -13,17 +13,23 @@ import { TestInstantiationService } from '../../../../../platform/instantiation/ import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; import { OverlayWebview } from '../../browser/overlayWebview.js'; import { IWebviewService } from '../../browser/webview.js'; +import { Event, Emitter } from '../../../../../base/common/event.js'; +import { ISizeService } from '../../../../../platform/theme/common/sizeService.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; import '../../../../browser/media/style.css'; import '../../../../browser/media/floatingPanels.css'; +import '../../../../contrib/modernUI/browser/media/editorBorder.css'; suite('OverlayWebview', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - function createOverlay(root: HTMLElement): OverlayWebview { + function createOverlay(root: HTMLElement, onDidChangeSizes = Event.None): OverlayWebview { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IWorkbenchLayoutService, { getContainer: () => root }); instantiationService.stub(IWebviewService, {}); instantiationService.stub(IContextKeyService, {}); + instantiationService.stub(ISizeService, { onDidChangeSizes }); + instantiationService.stub(IThemeService, { onDidColorThemeChange: Event.None }); return store.add(instantiationService.createInstance(OverlayWebview, { title: undefined, options: {}, @@ -116,7 +122,7 @@ suite('OverlayWebview', () => { root.className = 'monaco-workbench modern-ui floating-panels mac macos-tahoe nostatusbar'; root.style.cssText = '--vscode-cornerRadius-large: 8px; --vscode-spacing-size40: 4px; --vscode-strokeThickness: 1px; --window-zoom-factor: 1;'; const part = root.appendChild(document.createElement('div')); - part.className = 'part floating-editor-outer-left floating-editor-outer-right floating-editor-outer-top floating-editor-outer-bottom'; + part.className = 'part editor floating-editor-outer-left floating-editor-outer-right floating-editor-outer-top floating-editor-outer-bottom'; part.style.cssText = 'position: relative; width: 400px; height: 400px; border: 1px solid transparent; box-sizing: border-box;'; const anchors = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'].map((name, index) => { const anchor = part.appendChild(document.createElement('div')); @@ -142,18 +148,45 @@ suite('OverlayWebview', () => { assert.deepStrictEqual({ defaultZoom, zoomedOut, movedEdges: getOuterEdges(overlay.container) }, { defaultZoom: { - topLeft: ['8px', '8px'], - topRight: ['8px', '8px'], - bottomLeft: ['11px', '8px'], - bottomRight: ['8px', '11px'], + topLeft: ['0px', '0px'], + topRight: ['0px', '0px'], + bottomLeft: ['11px', '0px'], + bottomRight: ['0px', '11px'], }, zoomedOut: { - topLeft: ['8px', '8px'], - topRight: ['8px', '8px'], - bottomLeft: ['27px', '8px'], - bottomRight: ['8px', '27px'], + topLeft: ['0px', '0px'], + topRight: ['0px', '0px'], + bottomLeft: ['27px', '0px'], + bottomRight: ['0px', '27px'], }, movedEdges: { left: false, right: true, top: false, bottom: true }, }); }); + + test('webview content follows exposed component corners rather than rounding title and split seams', () => { + const root = document.createElement('div'); + root.className = 'monaco-workbench agent-sessions-workbench'; + const part = root.appendChild(document.createElement('div')); + part.className = 'part editor'; + part.style.cssText = 'position: relative; width: 400px; height: 400px; border: 1px solid transparent; border-radius: 6px 0 0 6px; box-sizing: border-box;'; + const anchor = part.appendChild(document.createElement('div')); + anchor.style.cssText = 'position: absolute; top: 30px; bottom: 0; left: 0; right: 0;'; + document.body.appendChild(root); + store.add(toDisposable(() => root.remove())); + const changes = store.add(new Emitter<void>()); + const overlay = createOverlay(root, changes.event); + overlay.setAnchorElement(anchor); + const initial = getWindow(root).getComputedStyle(overlay.container).borderRadius; + part.style.borderRadius = '3px'; + changes.fire(); + const updated = getWindow(root).getComputedStyle(overlay.container).borderRadius; + anchor.style.right = '50%'; + overlay.setAnchorElement(anchor); + const split = getWindow(root).getComputedStyle(overlay.container).borderRadius; + assert.deepStrictEqual({ initial, updated, split }, { + initial: '0px 0px 0px 5px', + updated: '0px 0px 2px 2px', + split: '0px 0px 0px 2px', + }); + }); }); diff --git a/src/vs/workbench/contrib/webview/test/browser/resourceLoading.test.ts b/src/vs/workbench/contrib/webview/test/browser/resourceLoading.test.ts index edda1d5d21e5..b0cc97662fa1 100644 --- a/src/vs/workbench/contrib/webview/test/browser/resourceLoading.test.ts +++ b/src/vs/workbench/contrib/webview/test/browser/resourceLoading.test.ts @@ -300,7 +300,7 @@ suite('Webview Resource Loading - getResourceToLoad', () => { { os: OperatingSystem.Linux, root: '/home/user/allowed', path: '/home/user/allowed/../outside.txt' }, ]; assert.deepStrictEqual(await Promise.all(cases.map(async ({ os, root, path }) => - (await getResourceToLoad(remote(decodeURIComponent(path)), [remote(root)], uriIdentityService, fileService, os)) + (await getResourceToLoad(remote(decodeURIComponent(path)), [remote(root)], uriIdentityService, fileService, os)) )), cases.map(() => undefined)); }); diff --git a/src/vs/workbench/contrib/webview/test/browser/themeing.test.ts b/src/vs/workbench/contrib/webview/test/browser/themeing.test.ts new file mode 100644 index 000000000000..c79aa82738e2 --- /dev/null +++ b/src/vs/workbench/contrib/webview/test/browser/themeing.test.ts @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Event } from '../../../../../base/common/event.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ConfigurationTarget } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { SIZE_CUSTOMIZATIONS_SETTING } from '../../../../../platform/theme/common/sizeService.js'; +import { ColorScheme } from '../../../../../platform/theme/common/theme.js'; +import { IWorkbenchThemeService } from '../../../../services/themes/common/workbenchThemeService.js'; +import { ColorThemeData } from '../../../../services/themes/common/colorThemeData.js'; +import { WorkbenchSizeService } from '../../../../services/themes/browser/workbenchSizeService.js'; +import { WebviewThemeDataProvider } from '../../browser/themeing.js'; + +suite('Webview semantic sizes', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('exports resolved sizes and invalidates the cache when customizations change', async () => { + const configuration = new TestConfigurationService({ + editor: {}, [SIZE_CUSTOMIZATIONS_SETTING]: { + 'default.cornerRadius': 3, 'toolsPanel.cornerRadius': 0, 'controls.cornerRadius': 2, 'popups.cornerRadius': 6, 'menus.cornerRadius': 0, + } + }); + store.add(configuration.onDidChangeConfigurationEmitter); + const sizes = store.add(new WorkbenchSizeService(configuration, store.add(new NullLogService()))); + const theme = ColorThemeData.createUnloadedThemeForThemeType(ColorScheme.DARK); + const themes = new class extends mock<IWorkbenchThemeService>() { + override getColorTheme() { return theme; } + override onDidColorThemeChange = Event.None; + }(); + const provider = store.add(new WebviewThemeDataProvider(themes, configuration, sizes)); + const read = () => { + const styles = provider.getWebviewThemeData().styles; + return [ + styles['vscode-toolsPanel-cornerRadius'], styles['vscode-primarySideBar-cornerRadius'], styles['vscode-cornerRadius-large'], + styles['vscode-buttons-cornerRadius'], styles['vscode-inputs-cornerRadius'], styles['vscode-menus-cornerRadius'], styles['vscode-dialogs-cornerRadius'], + ]; + }; + const before = read(); + let events = 0; + store.add(provider.onThemeDataChanged(() => events++)); + await configuration.setUserConfiguration(SIZE_CUSTOMIZATIONS_SETTING, { 'default.cornerRadius': 5 }); + configuration.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === SIZE_CUSTOMIZATIONS_SETTING, + source: ConfigurationTarget.USER, + affectedKeys: new Set([SIZE_CUSTOMIZATIONS_SETTING]), + change: { keys: [SIZE_CUSTOMIZATIONS_SETTING], overrides: [] }, + }); + assert.deepStrictEqual({ before, after: read(), events }, { + before: ['0px', '3px', '8px', '2px', '2px', '0px', '6px'], after: ['5px', '5px', '8px', '4px', '4px', '8px', '8px'], events: 1, + }); + }); +}); diff --git a/src/vs/workbench/contrib/webview/test/browser/webviewElement.test.ts b/src/vs/workbench/contrib/webview/test/browser/webviewElement.test.ts index d67e8bcf0737..a3d5e0894d23 100644 --- a/src/vs/workbench/contrib/webview/test/browser/webviewElement.test.ts +++ b/src/vs/workbench/contrib/webview/test/browser/webviewElement.test.ts @@ -10,6 +10,7 @@ import { $, addDisposableListener, append, registerWindow } from '../../../../.. import { Orientation, Sash } from '../../../../../base/browser/ui/sash/sash.js'; import { ensureCodeWindow, mainWindow } from '../../../../../base/browser/window.js'; import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Action } from '../../../../../base/common/actions.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { errorHandler, setUnexpectedErrorHandler } from '../../../../../base/common/errors.js'; @@ -25,6 +26,8 @@ import { IAccessibilityService } from '../../../../../platform/accessibility/com import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { MenuId } from '../../../../../platform/actions/common/actions.js'; +import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; import { FileService } from '../../../../../platform/files/common/fileService.js'; import { FileSystemProviderCapabilities, IFileReadStreamOptions, IFileService } from '../../../../../platform/files/common/files.js'; @@ -44,6 +47,7 @@ import { TestFileService } from '../../../../test/common/workbenchTestServices.j import { SASH_GRIPPERS_HIDDEN_ATTRIBUTE, SashGrippersController } from '../../../sash/browser/sash.js'; import { WebviewThemeDataProvider } from '../../browser/themeing.js'; import { WebviewElement } from '../../browser/webviewElement.js'; +import { WebviewOptions } from '../../browser/webview.js'; import { FromWebviewMessage, ToWebviewMessage } from '../../browser/webviewMessages.js'; import { asWebviewUri, WebviewMouseActivity, webviewMouseActivityEvent, webviewRootResourceAuthority } from '../../common/webview.js'; @@ -53,13 +57,18 @@ suite('WebviewElement', () => { teardown(() => sinon.restore()); - async function createWebview(extensionId?: string, platform = 'browser', connect = true, targetWindow = mainWindow) { + async function createWebview(extensionId?: string, platform = 'browser', connect = true, targetWindow = mainWindow, hashParentOrigin?: (parentOrigin: string, defaultHash: () => Promise<string>) => Promise<string>, options: WebviewOptions = {}) { let initialized = new DeferredPromise<string>(); class TestWebviewElement extends WebviewElement { public override get element(): HTMLIFrameElement | undefined { return super.element; } protected override get platform(): string { return platform; } + protected override hashParentOrigin(parentOrigin: string): Promise<string> { + const defaultHash = () => super.hashParentOrigin(parentOrigin); + return hashParentOrigin ? hashParentOrigin(parentOrigin, defaultHash) : defaultHash(); + } + protected override webviewContentEndpoint(encodedWebviewOrigin: string): string { const origin = `https://${encodedWebviewOrigin}.invalid`; initialized.complete(origin); @@ -71,8 +80,9 @@ suite('WebviewElement', () => { const configurationService = new TestConfigurationService(); store.add(configurationService.onDidChangeConfigurationEmitter); const errorNotification = sinon.stub(); + const contextMenus: (Parameters<IContextMenuService['showContextMenu']>[0] & { menuId?: MenuId })[] = []; instantiationService.stub(IConfigurationService, configurationService); - instantiationService.stub(IContextMenuService, { onDidHideContextMenu: Event.None }); + instantiationService.stub(IContextMenuService, { onDidHideContextMenu: Event.None, showContextMenu: delegate => { contextMenus.push(delegate); } }); instantiationService.stub(INotificationService, { error: errorNotification }); instantiationService.stub(IWorkbenchEnvironmentService, {}); instantiationService.stub(ILogService, store.add(new NullLogService())); @@ -91,7 +101,7 @@ suite('WebviewElement', () => { const webview = store.add(instantiationService.createInstance(TestWebviewElement, { title: 'Test view', - options: {}, + options, contentOptions: {}, extension: extensionId ? { id: new ExtensionIdentifier(extensionId) } : undefined, }, upcastPartial<WebviewThemeDataProvider>({ @@ -99,12 +109,16 @@ suite('WebviewElement', () => { getWebviewThemeData: () => ({ styles: {}, activeTheme: 'vscode-dark', themeLabel: 'Dark', themeId: 'test' }), }))); const container = document.createElement('div'); + const addListener = sinon.spy(container, 'addEventListener'); + const removeListener = sinon.spy(container, 'removeEventListener'); targetWindow.document.body.appendChild(container); store.add(toDisposable(() => container.remove())); assert.ok(webview.element); const frame = webview.element; + const connectedWhenSourceAssigned: boolean[] = []; // Capture the shell URL without navigating away from the test document. const setSource = sinon.stub(frame, 'setAttribute').withArgs('src', sinon.match.string); + setSource.callsFake(() => { connectedWhenSourceAssigned.push(frame.isConnected); }); webview.mountTo(container, targetWindow); const origin = await initialized.p; @@ -128,7 +142,8 @@ suite('WebviewElement', () => { } channel.port2.start(); return { - webview, instantiationService, port: channel.port2, errorNotification, frame, container, configurationService, createReadyEvent, + webview, instantiationService, port: channel.port2, errorNotification, contextMenus, frame, container, configurationService, createReadyEvent, setSource, connectedWhenSourceAssigned, + activeMountListeners: () => addListener.callCount - removeListener.callCount, remount: async () => { initialized = new DeferredPromise<string>(); webview.reinitializeAfterDismount(); @@ -157,6 +172,51 @@ suite('WebviewElement', () => { await sendWebviewMessage(webview, port, 'did-mouse-move', event); } + test('adds host-owned context actions only to the opted-in webview and retains the standard menu', async () => { + const action = store.add(new Action('test.preview', 'Preview')); + const customized = await createWebview(undefined, 'browser', true, mainWindow, undefined, { getContextMenuActions: () => [action] }); + const ordinary = await createWebview(); + const result = []; + for (const { webview, port, contextMenus } of [customized, ordinary]) { + webview.setContextKeyService(store.add(new MockContextKeyService())); + await sendWebviewMessage(webview, port, 'did-context-menu', { clientX: 20, clientY: 30, context: {} }); + const menu = contextMenus[0]; + result.push({ + menuId: menu.menuId, + actions: menu.getActions?.().map(action => action.id), + }); + } + assert.deepStrictEqual(result, [ + { menuId: MenuId.WebviewContext, actions: ['test.preview'] }, + { menuId: MenuId.WebviewContext, actions: undefined }, + ]); + }); + + test('assigns the isolated shell URL before attaching or remounting its iframe', async () => { + const { frame, container, connectedWhenSourceAssigned, remount } = await createWebview(); + await remount(); + assert.deepStrictEqual({ + connectedWhenSourceAssigned, + parent: frame.parentElement === container, + sandbox: [...frame.sandbox], + }, { + connectedWhenSourceAssigned: [false, false], + parent: true, + sandbox: ['allow-scripts', 'allow-same-origin', 'allow-forms', 'allow-pointer-lock', 'allow-downloads'], + }); + }); + + test('repeated remounts replace their DOM listeners and disposal releases them', async () => { + const { webview, remount, activeMountListeners } = await createWebview(); + const counts = [activeMountListeners()]; + for (let index = 0; index < 8; index++) { + await remount(); + counts.push(activeMountListeners()); + } + webview.dispose(); + assert.deepStrictEqual({ counts, disposed: activeMountListeners() }, { counts: Array(9).fill(4), disposed: 0 }); + }); + test('reports webview activity without synthesizing mouse input', async () => { const { webview, port } = await createWebview(); const activities: WebviewMouseActivity[] = []; @@ -329,6 +389,41 @@ suite('WebviewElement', () => { } } + test('ignores an earlier mount whose origin hash finishes after a remount', async () => { + const firstHash = new DeferredPromise<string>(); + const secondHash = new DeferredPromise<string>(); + let delayedHashes: DeferredPromise<string>[] = []; + const { webview, container, setSource, createReadyEvent } = await createWebview(undefined, 'browser', false, mainWindow, (_origin, defaultHash) => { + const delayed = delayedHashes.shift(); + return delayed ? delayed.p : defaultHash(); + }); + delayedHashes = [firstHash, secondHash]; + const before = setSource.callCount; + + webview.mountTo(container, mainWindow); + webview.mountTo(container, mainWindow); + secondHash.complete('current-origin'); + await secondHash.p; + await timeout(0); + const afterSecondMount = setSource.callCount - before; + firstHash.complete('stale-origin'); + await firstHash.p; + await timeout(0); + // The stale hash must not replace the origin that the current mount's shell is checked against. + const channel = new MessageChannel(); + store.add(toDisposable(() => { + channel.port1.close(); + channel.port2.close(); + })); + mainWindow.dispatchEvent(new MessageEvent('message', { ...createReadyEvent(channel.port1), origin: 'https://current-origin.invalid' })); + + assert.deepStrictEqual({ afterSecondMount, afterStaleCompletion: setSource.callCount - before, acceptedCurrentOrigin: channel.port1.onmessage !== null }, { + afterSecondMount: 1, + afterStaleCompletion: 1, + acceptedCurrentOrigin: true, + }); + }); + test('remount rejects the old handshake and key token', async () => { const { webview, frame, createReadyEvent, remount } = await createWebview(); const oldReady = createReadyEvent(); diff --git a/src/vs/workbench/contrib/webview/test/node/webviewServiceWorker.test.ts b/src/vs/workbench/contrib/webview/test/node/webviewServiceWorker.test.ts new file mode 100644 index 000000000000..c4df8e530be2 --- /dev/null +++ b/src/vs/workbench/contrib/webview/test/node/webviewServiceWorker.test.ts @@ -0,0 +1,77 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { readFileSync } from 'fs'; +import { FileAccess } from '../../../../../base/common/network.js'; +import { join, resolve } from '../../../../../base/common/path.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; + +suite('Webview service worker', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + const version = 3; + + async function activateWorker(cacheStorage: Pick<CacheStorage, 'keys' | 'delete'>): Promise<number> { + const compiledDir = FileAccess.asFileUri('vs/workbench/contrib/webview/test/node').fsPath; + const sourceDir = resolve(compiledDir).replaceAll('\\', '/').replace('/out/vs/workbench/', '/src/vs/workbench/'); + const source = readFileSync(join(sourceDir, '../../browser/pre/service-worker.js'), 'utf8'); + const activate = source.match(/sw\.addEventListener\('activate',[\s\S]*?\r?\n\}\);/)?.[0]; + assert.ok(activate); + + let claims = 0; + let activation: Promise<void> | undefined; + new Function('sw', 'caches', 'VERSION', activate)({ + clients: { + claim: async () => { claims++; }, + }, + addEventListener: (_type: string, handler: (event: { waitUntil: (promise: Promise<void>) => void }) => void) => { + handler({ waitUntil: promise => { activation = promise; } }); + }, + }, cacheStorage, version); + + assert.ok(activation); + await activation; + return claims; + } + + test('removes only resource caches from older versions on activation', async () => { + const currentCache = `vscode-resource-cache-${version}`; + const newerCache = `vscode-resource-cache-${version + 1}`; + const cacheNames = new Set([ + 'vscode-resource-cache-1', + 'vscode-resource-cache-2', + currentCache, + newerCache, + 'extension-cache', + 'vscode-resource-cache-custom', + ]); + const claims = await activateWorker({ + keys: async () => [...cacheNames], + delete: async name => cacheNames.delete(name), + }); + + assert.deepStrictEqual({ caches: [...cacheNames], claims }, { + caches: [currentCache, newerCache, 'extension-cache', 'vscode-resource-cache-custom'], + claims: 1, + }); + }); + + for (const failure of ['keys', 'delete']) { + test(`claims clients when cache ${failure} fails`, async () => { + const claims = await activateWorker({ + keys: async () => { + if (failure === 'keys') { + throw new Error('Cache storage is unavailable'); + } + return ['vscode-resource-cache-1']; + }, + delete: async () => { throw new Error('Cache storage is unavailable'); }, + }); + + assert.strictEqual(claims, 1); + }); + } +}); diff --git a/src/vs/workbench/contrib/webview/test/node/webviewShellMessaging.test.ts b/src/vs/workbench/contrib/webview/test/node/webviewShellMessaging.test.ts index 5c2809653388..fff4d0985172 100644 --- a/src/vs/workbench/contrib/webview/test/node/webviewShellMessaging.test.ts +++ b/src/vs/workbench/contrib/webview/test/node/webviewShellMessaging.test.ts @@ -139,6 +139,56 @@ suite('Webview shell messaging', () => { }); }); + test('opted-in intrinsic height fits fractional content and native scrollbars without changing other webviews', () => { + const compiledDir = FileAccess.asFileUri('vs/workbench/contrib/webview/test/node').fsPath; + const sourceDir = resolve(compiledDir).replaceAll('\\', '/').replace('/out/vs/workbench/', '/src/vs/workbench/'); + const html = readFileSync(join(sourceDir, '../../browser/pre/index.html'), 'utf8'); + const reporter = html.match(/const postSize = \(\) => \{[\s\S]*?\r?\n\t+\};/)?.[0]; + assert.ok(reporter); + const sizes: { width: number; height: number }[] = []; + for (const [includeHorizontalScrollbarInContentHeight, clientHeight] of [[false, 184], [true, 184], [false, 200], [true, 200]] as const) { + new Function('docEl', 'contentWindow', 'options', 'hostMessaging', `${reporter}\npostSize();`)( + { offsetWidth: 440, offsetHeight: 200, clientHeight, getBoundingClientRect: () => ({ height: 200.45 }) }, + { innerHeight: 200 }, + { includeHorizontalScrollbarInContentHeight }, + { postMessage: (_channel: string, data: typeof sizes[number]) => sizes.push(data) }, + ); + } + assert.deepStrictEqual(sizes, [200, 217, 200, 201].map(height => ({ width: 440, height }))); + }); + + test('only delegates recognized network permissions while preserving script and browser restrictions', () => { + const compiledDir = FileAccess.asFileUri('vs/workbench/contrib/webview/test/node').fsPath; + const sourceDir = resolve(compiledDir).replaceAll('\\', '/').replace('/out/vs/workbench/', '/src/vs/workbench/'); + const html = readFileSync(join(sourceDir, '../../browser/pre/index.html'), 'utf8'); + const allow = html.match(/const allowRules = \[[\s\S]*?newFrame\.setAttribute\('allow',[\s\S]*?\);/)?.[0]; + assert.ok(allow); + const cases = [ + { features: [], allowScripts: false, isFirefox: false }, + { features: ['local-network-access'], allowScripts: false, isFirefox: false }, + { features: [], allowScripts: true, isFirefox: false }, + { features: undefined, allowScripts: true, isFirefox: true }, + ]; + const policies = cases.map(testCase => { + let policy: string | undefined; + new Function('newFrame', 'isFirefox', 'options', allow)( + { + featurePolicy: testCase.features ? { features: () => testCase.features } : undefined, + setAttribute: (_name: string, value: string) => { policy = value; }, + }, + testCase.isFirefox, + { allowScripts: testCase.allowScripts }, + ); + return policy; + }); + assert.deepStrictEqual(policies, [ + 'cross-origin-isolated; autoplay;', + 'cross-origin-isolated; autoplay; local-network-access;', + 'cross-origin-isolated; autoplay; clipboard-read; clipboard-write;', + 'cross-origin-isolated; autoplay;', + ]); + }); + for (const command of ['copy', 'cut', 'paste']) { for (const activeRoot of ['body', 'documentElement'] as const) { test(`preserves the document selection for ${command} with ${activeRoot} focused`, () => { diff --git a/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts b/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts index db913f20c450..52ed6c1196c4 100644 --- a/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts +++ b/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts @@ -269,9 +269,9 @@ export class GettingStartedPage extends EditorPane { ourCategory.title = category.title; ourCategory.description = category.description; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelectorAll<HTMLDivElement>(`[x-category-title-for="${category.id}"]`).forEach(step => (step as HTMLDivElement).innerText = ourCategory.title); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelectorAll<HTMLDivElement>(`[x-category-description-for="${category.id}"]`).forEach(step => (step as HTMLDivElement).innerText = ourCategory.description); })); @@ -297,7 +297,7 @@ export class GettingStartedPage extends EditorPane { ourStep.done = step.done; if (category.id === this.currentWalkthrough?.id) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const badgeelements = assertReturnsDefined(this.window.document.querySelectorAll(`[data-done-step-id="${step.id}"]`)); badgeelements.forEach(badgeelement => { if (step.done) { @@ -412,7 +412,7 @@ export class GettingStartedPage extends EditorPane { private registerDispatchListeners() { this.dispatchListeners.clear(); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelectorAll('[x-dispatch]').forEach(element => { const dispatch = element.getAttribute('x-dispatch') ?? ''; let command, argument; @@ -827,11 +827,11 @@ export class GettingStartedPage extends EditorPane { return; } if (id) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax let stepElement = this.container.querySelector<HTMLDivElement>(`[data-step-id="${id}"]`); if (!stepElement) { // Selected an element that is not in-context, just fallback to whatever. - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stepElement = this.container.querySelector<HTMLDivElement>(`[data-step-id]`); if (!stepElement) { // No steps around... just ignore. @@ -839,12 +839,12 @@ export class GettingStartedPage extends EditorPane { } id = assertReturnsDefined(stepElement.getAttribute('data-step-id')); } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax stepElement.parentElement?.querySelectorAll<HTMLElement>('.expanded').forEach(node => { if (node.getAttribute('data-step-id') !== id) { node.classList.remove('expanded'); node.setAttribute('aria-expanded', 'false'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const codiconElement = node.querySelector('.codicon'); if (codiconElement) { codiconElement.removeAttribute('tabindex'); @@ -860,7 +860,7 @@ export class GettingStartedPage extends EditorPane { stepElement.classList.add('expanded'); stepElement.setAttribute('aria-expanded', 'true'); this.buildMediaComponent(id, true); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const codiconElement = stepElement.querySelector('.codicon'); if (codiconElement) { codiconElement.setAttribute('tabindex', '0'); @@ -956,7 +956,7 @@ export class GettingStartedPage extends EditorPane { const agentsBanner = createAgentsBanner( { cssClass: 'getting-started-category.agents-banner', - graphic: { element: agentsWindowGraphic.element, shownDesign: agentsWindowGraphic.shownDesign, isExposed: this.categoriesSlideShown }, + graphic: { element: agentsWindowGraphic.element, shownDesign: agentsWindowGraphic.shownDesign, isExposed: this.categoriesSlideShown, hasMultipleEditorWindows: agentsWindowGraphic.hasMultipleEditorWindows }, }, this.commandService, this.telemetryService, @@ -1347,7 +1347,7 @@ export class GettingStartedPage extends EditorPane { } private updateCategoryProgress() { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.window.document.querySelectorAll('.category-progress').forEach(element => { const categoryID = element.getAttribute('x-data-category-id'); const category = this.gettingStartedCategories.find(c => c.id === categoryID); @@ -1355,7 +1355,7 @@ export class GettingStartedPage extends EditorPane { const stats = this.getWalkthroughCompletionStats(category); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const bar = assertReturnsDefined(element.querySelector('.progress-bar-inner')) as HTMLDivElement; bar.setAttribute('aria-valuemin', '0'); bar.setAttribute('aria-valuenow', '' + stats.stepsComplete); @@ -1780,35 +1780,35 @@ export class GettingStartedPage extends EditorPane { } private setSlide(toEnable: 'details' | 'categories', firstLaunch: boolean = false) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const slideManager = assertReturnsDefined(this.container.querySelector('.gettingStarted')); this.categoriesSlideShown.set(toEnable === 'categories', undefined); if (toEnable === 'categories') { slideManager.classList.remove('showDetails'); slideManager.classList.add('showCategories'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector<HTMLButtonElement>('.prev-button.button-link')!.style.display = 'none'; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideDetails')!.querySelectorAll('button').forEach(button => button.disabled = true); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideCategories')!.querySelectorAll('button').forEach(button => button.disabled = false); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideCategories')!.querySelectorAll('input').forEach(button => button.disabled = false); } else { slideManager.classList.add('showDetails'); slideManager.classList.remove('showCategories'); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const prevButton = this.container.querySelector<HTMLButtonElement>('.prev-button.button-link'); prevButton!.style.display = this.editorInput?.showWelcome || this.editorInput?.returnToCommand || this.prevWalkthrough ? 'block' : 'none'; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const moreTextElement = prevButton!.querySelector('.moreText'); moreTextElement!.textContent = firstLaunch ? localize('welcome', "Welcome") : localize('goBack', "Go Back"); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideDetails')!.querySelectorAll('button').forEach(button => button.disabled = false); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideCategories')!.querySelectorAll('button').forEach(button => button.disabled = true); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax this.container.querySelector('.gettingStartedSlideCategories')!.querySelectorAll('input').forEach(button => button.disabled = true); } } diff --git a/src/vs/workbench/contrib/welcomeOnboarding/browser/media/variationA.css b/src/vs/workbench/contrib/welcomeOnboarding/browser/media/variationA.css index e3b521c840ef..1bca8e35bf21 100644 --- a/src/vs/workbench/contrib/welcomeOnboarding/browser/media/variationA.css +++ b/src/vs/workbench/contrib/welcomeOnboarding/browser/media/variationA.css @@ -450,7 +450,7 @@ .onboarding-a-signin-ghe-input .monaco-inputbox { height: 40px; - border-radius: 8px; + border-radius: var(--workbench-custom-inputs-corner-radius, 8px); font-size: 13px; line-height: 40px; } diff --git a/src/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughPart.ts b/src/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughPart.ts index c6fb17f85252..b76550a70147 100644 --- a/src/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughPart.ts +++ b/src/vs/workbench/contrib/welcomeWalkthrough/browser/walkThroughPart.ts @@ -158,10 +158,10 @@ export class WalkThroughPart extends EditorPane { this.disposables.add(this.addEventListener(this.content, 'click', event => { for (let node = event.target as HTMLElement; node; node = node.parentNode as HTMLElement) { if (isHTMLAnchorElement(node) && node.href) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const baseElement = node.ownerDocument.getElementsByTagName('base')[0] || this.window.location; if (baseElement && node.href.indexOf(baseElement.href) >= 0 && node.hash) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const scrollTarget = this.content.querySelector(node.hash); const innerContent = this.content.firstElementChild; if (scrollTarget && innerContent) { @@ -314,7 +314,7 @@ export class WalkThroughPart extends EditorPane { return; } const id = `snippet-${model.uri.fragment}`; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const div = innerContent.querySelector(`#${id.replace(/[\\.]/g, '\\$&')}`) as HTMLElement; const options = this.getEditorOptions(model.getLanguageId()); @@ -427,7 +427,7 @@ export class WalkThroughPart extends EditorPane { } private decorateContent() { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const keys = this.content.querySelectorAll('.shortcut[data-command]'); Array.prototype.forEach.call(keys, (key: Element) => { const command = key.getAttribute('data-command'); @@ -438,7 +438,7 @@ export class WalkThroughPart extends EditorPane { } key.appendChild(document.createTextNode(label)); }); - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const ifkeys = this.content.querySelectorAll('.if_shortcut[data-command]'); Array.prototype.forEach.call(ifkeys, (key: HTMLElement) => { const command = key.getAttribute('data-command'); @@ -451,7 +451,7 @@ export class WalkThroughPart extends EditorPane { const labels = UILabelProvider.modifierLabels[OS]; const value = this.configurationService.getValue('editor.multiCursorModifier'); const modifier = labels[value === 'ctrlCmd' ? (OS === OperatingSystem.Macintosh ? 'metaKey' : 'ctrlKey') : 'altKey']; - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const keys = this.content.querySelectorAll('.multi-cursor-modifier'); Array.prototype.forEach.call(keys, (key: Element) => { while (key.firstChild) { diff --git a/src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts b/src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts index 1f5152248c98..c55e92906ae1 100644 --- a/src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts +++ b/src/vs/workbench/contrib/workspace/browser/workspaceTrustEditor.ts @@ -178,18 +178,18 @@ export class WorkspaceTrustedUrisTable extends Disposable { addButton.label = localize('addButton', "Add Folder"); this._register(addButton.onDidClick(async () => { - const uri = await this.fileDialogService.showOpenDialog({ + const uris = await this.fileDialogService.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, - canSelectMany: false, + canSelectMany: true, defaultUri: this.currentWorkspaceUri, - openLabel: localize('trustUri', "Trust Folder"), - title: localize('selectTrustedUri', "Select Folder To Trust") + openLabel: localize('trustUris', "Trust Folders"), + title: localize('selectTrustedUris', "Select Folders to Trust") }); - if (uri?.length) { + if (uris?.length) { try { - await this.addTrustedUri(uri[0]); + await this.addTrustedUris(uris); } catch (error) { onUnexpectedError(error); } @@ -201,21 +201,35 @@ export class WorkspaceTrustedUrisTable extends Disposable { })); } - private async addTrustedUri(uri: URI): Promise<void> { - await this.workspaceTrustManagementService.setUrisTrust([uri], true); + private async addTrustedUris(uris: URI[]): Promise<void> { + // A single call trusts either all of the folders or, when one of them cannot be trusted, none of them. + await this.workspaceTrustManagementService.setUrisTrust(uris, true); if (this._store.isDisposed) { return; } - // Resolve the folder's own stored (canonical) entry: after adding it, the longest trusted match is that + // Resolve each folder's own stored (canonical) entry: after adding it, the longest trusted match is that // exact entry, even when canonicalization changed its path. Implicitly trusted (virtual or remote) // folders resolve to themselves and have no row, so unrelated or parent rows are never selected. - const trustInfo = await this.workspaceTrustManagementService.getUriTrustInfo(uri); - if (this._store.isDisposed || !trustInfo.trusted) { + const trustInfos = await Promise.all(uris.map(uri => this.workspaceTrustManagementService.getUriTrustInfo(uri))); + if (this._store.isDisposed) { return; } - this.selectTrustedUriEntry({ uri: trustInfo.uri, parentOfWorkspaceItem: false }); + // The table is single-select: select the topmost of the folders' rows. + let topmostIndex = -1; + for (const trustInfo of trustInfos) { + if (trustInfo.trusted) { + const index = this.getIndexOfTrustedUriEntry({ uri: trustInfo.uri, parentOfWorkspaceItem: false }); + if (index !== -1 && (topmostIndex === -1 || index < topmostIndex)) { + topmostIndex = index; + } + } + } + + if (topmostIndex !== -1) { + this.selectTrustedUriEntry(this.table.row(topmostIndex)); + } } private getIndexOfTrustedUriEntry(item: ITrustedUriItem): number { diff --git a/src/vs/workbench/contrib/workspace/test/browser/workspaceTrustEditor.test.ts b/src/vs/workbench/contrib/workspace/test/browser/workspaceTrustEditor.test.ts index 38e6b0d2d621..82ed8ec04c89 100644 --- a/src/vs/workbench/contrib/workspace/test/browser/workspaceTrustEditor.test.ts +++ b/src/vs/workbench/contrib/workspace/test/browser/workspaceTrustEditor.test.ts @@ -12,6 +12,7 @@ import { Emitter, Event } from '../../../../../base/common/event.js'; import { normalizeDriveLetter } from '../../../../../base/common/labels.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { isWindows } from '../../../../../base/common/platform.js'; +import { basename } from '../../../../../base/common/resources.js'; import { ScrollbarVisibility } from '../../../../../base/common/scrollable.js'; import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; @@ -31,8 +32,10 @@ import { WorkspaceTrustEditorInput } from '../../../../services/workspaces/brows class PickerFileDialogService extends TestFileDialogService { nextPick: URI[] | undefined; + readonly openDialogOptions: IOpenDialogOptions[] = []; - override showOpenDialog(_options: IOpenDialogOptions): Promise<URI[] | undefined> { + override showOpenDialog(options: IOpenDialogOptions): Promise<URI[] | undefined> { + this.openDialogOptions.push(options); return Promise.resolve(this.nextPick); } } @@ -52,8 +55,12 @@ class FakeWorkspaceTrustManagementService extends TestWorkspaceTrustManagementSe verificationGate: Promise<void> | undefined; completionGate: Promise<void> | undefined; failure: Error | undefined; + /** Like the real service, rejects the whole batch before any change when one of its URIs cannot be trusted. */ + rejects: ((uri: URI) => boolean) | undefined; + trustInfoGate: Promise<void> | undefined; autoTrusted: ((uri: URI) => boolean) | undefined; canonicalize: ((uri: URI) => URI) | undefined; + readonly calls: URI[][] = []; constructor(entries: URI[]) { super(); @@ -65,6 +72,7 @@ class FakeWorkspaceTrustManagementService extends TestWorkspaceTrustManagementSe } override async getUriTrustInfo(uri: URI): Promise<IWorkspaceTrustUriInfo> { + await this.trustInfoGate; const canonical = this.getCanonicalUri(uri); if (this.autoTrusted?.(canonical)) { return { trusted: true, uri: canonical }; @@ -76,9 +84,13 @@ class FakeWorkspaceTrustManagementService extends TestWorkspaceTrustManagementSe } override async setUrisTrust(uris: URI[], trusted: boolean): Promise<void> { + this.calls.push(uris); if (this.failure) { throw this.failure; } + if (uris.some(uri => this.rejects?.(uri))) { + throw new Error('unverified source'); + } let changed = false; for (const uri of uris.map(uri => this.getCanonicalUri(uri))) { @@ -369,36 +381,100 @@ suite('WorkspaceTrustedUrisTable', () => { ]); }); - test('reveals the added folder in the surrounding scrollable element', async () => { - // Mirrors the editor: the table is laid out to fit all rows inside a constrained-height - // scrollable body that is scrolled down to the Add Folder button. - const content = mainWindow.document.createElement('div'); - const scrollableElement = store.add(new DomScrollableElement(content, { vertical: ScrollbarVisibility.Auto })); - const viewport = scrollableElement.getDomNode(); - // max-height rather than height: the browser test page renders in quirks mode, where the - // table's `height: 100%` would otherwise resolve against this constrained ancestor. - viewport.style.maxHeight = '200px'; - content.style.maxHeight = '200px'; - const spacer = content.appendChild(mainWindow.document.createElement('div')); - spacer.style.height = '300px'; - content.appendChild(container); - mainWindow.document.body.appendChild(viewport); - store.add(toDisposable(() => viewport.remove())); - createTable(Array.from({ length: 20 }, (_, i) => `n-${String(i).padStart(2, '0')}`), scrollableElement); - scrollableElement.scanDomNode(); - scrollableElement.setScrollPosition({ scrollTop: Number.MAX_SAFE_INTEGER }); - const scrollTopBefore = scrollableElement.getScrollPosition().scrollTop; - - await addFolder([folder('a-first')]); - - const row = Array.from(container.querySelectorAll('.monaco-list-row')).find(row => label(row) === 'a-first')!; - const rowRect = row.getBoundingClientRect(); - const viewportRect = viewport.getBoundingClientRect(); + for (const pick of [['a-first'], ['zz-end', 'a-first']]) { + test(`reveals the topmost added folder in the surrounding scrollable element (${pick.join(', ')})`, async () => { + // Mirrors the editor: the table is laid out to fit all rows inside a constrained-height + // scrollable body that is scrolled down to the Add Folder button. + const content = mainWindow.document.createElement('div'); + const scrollableElement = store.add(new DomScrollableElement(content, { vertical: ScrollbarVisibility.Auto })); + const viewport = scrollableElement.getDomNode(); + // max-height rather than height: the browser test page renders in quirks mode, where the + // table's `height: 100%` would otherwise resolve against this constrained ancestor. + viewport.style.maxHeight = '200px'; + content.style.maxHeight = '200px'; + const spacer = content.appendChild(mainWindow.document.createElement('div')); + spacer.style.height = '300px'; + content.appendChild(container); + mainWindow.document.body.appendChild(viewport); + store.add(toDisposable(() => viewport.remove())); + createTable(Array.from({ length: 20 }, (_, i) => `n-${String(i).padStart(2, '0')}`), scrollableElement); + scrollableElement.scanDomNode(); + scrollableElement.setScrollPosition({ scrollTop: Number.MAX_SAFE_INTEGER }); + const scrollTopBefore = scrollableElement.getScrollPosition().scrollTop; + + await addFolder(pick.map(folder)); + + const row = Array.from(container.querySelectorAll('.monaco-list-row')).find(row => label(row) === 'a-first')!; + const rowRect = row.getBoundingClientRect(); + const viewportRect = viewport.getBoundingClientRect(); + assert.deepStrictEqual({ + scrolledUp: scrollableElement.getScrollPosition().scrollTop < scrollTopBefore, + rowVisible: rowRect.top >= viewportRect.top && rowRect.bottom <= viewportRect.bottom, + focused: getState().focused, + }, { scrolledUp: true, rowVisible: true, focused: ['a-first'] }); + }); + } + + test('trusts every picked folder in one call and focuses the topmost picked row', async () => { + const results: { state: ITableState; calls: string[][] }[] = []; + for (const pick of [['z-new', 'm-new'], ['z-new', 'b-existing', 'm-new']]) { + container.replaceChildren(); + createTable(['b-existing', 'z-last']); + selectRow('z-last'); + await addFolder(pick.map(folder)); + results.push({ state: getState(), calls: trustService.calls.map(call => call.map(uri => basename(uri))) }); + } + + assert.deepStrictEqual(results, [ + { state: focusedState(['b-existing', 'm-new', 'z-last', 'z-new'], 'm-new'), calls: [['z-new', 'm-new']] }, + { state: focusedState(['b-existing', 'm-new', 'z-last', 'z-new'], 'b-existing'), calls: [['z-new', 'b-existing', 'm-new']] }, + ]); + }); + + test('focuses the topmost picked row that gets an entry', async () => { + createTable(['c-two', 'z-last']); + selectRow('z-last'); + trustService.autoTrusted = uri => uri.path.endsWith('/a-implicit'); + await addFolder([folder('a-implicit'), folder('m-new')]); + assert.deepStrictEqual(getState(), focusedState(['c-two', 'm-new', 'z-last'], 'm-new')); + }); + + test('trusts none of the picked folders when one of them is rejected', async () => { + createTable(['c-two', 'z-last']); + selectRow('z-last'); + trustService.rejects = uri => uri.path.endsWith('/m-bad'); + const errors: unknown[] = []; + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + errorHandler.setUnexpectedErrorHandler(error => errors.push(error)); + try { + await addFolder([folder('a-good'), folder('m-bad')]); + } finally { + errorHandler.setUnexpectedErrorHandler(previousHandler); + } assert.deepStrictEqual({ - scrolledUp: scrollableElement.getScrollPosition().scrollTop < scrollTopBefore, - rowVisible: rowRect.top >= viewportRect.top && rowRect.bottom <= viewportRect.bottom, - focused: getState().focused, - }, { scrolledUp: true, rowVisible: true, focused: ['a-first'] }); + trusted: trustService.getTrustedUris().map(uri => basename(uri)), + errors: errors.length, + selected: getState().selected, + addButtonFocused: mainWindow.document.activeElement === getAddButton(), + }, { trusted: ['c-two', 'z-last'], errors: 1, selected: ['z-last'], addButtonFocused: true }); + }); + + test('keeps focus on the add button when no picked folder gets an entry', async () => { + createTable(['c-two', 'z-last']); + selectRow('z-last'); + trustService.autoTrusted = () => true; + await addFolder([folder('a-implicit'), folder('m-implicit')]); + assert.deepStrictEqual([getState().rows, getState().selected, mainWindow.document.activeElement === getAddButton()], [['c-two', 'z-last'], ['z-last'], true]); + }); + + test('add picks several folders while edit picks one', async () => { + createTable(['c-two']); + await addFolder(undefined); + await table.edit({ uri: folder('c-two'), parentOfWorkspaceItem: false }, true); + assert.deepStrictEqual(dialogService.openDialogOptions.map(({ canSelectMany, title, openLabel }) => ({ canSelectMany, title, openLabel })), [ + { canSelectMany: true, title: 'Select Folders to Trust', openLabel: 'Trust Folders' }, + { canSelectMany: false, title: 'Select Folder To Trust', openLabel: 'Trust Folder' }, + ]); }); test('moves focus only after the addition completes', async () => { @@ -633,6 +709,25 @@ suite('WorkspaceTrustedUrisTable', () => { assert.deepStrictEqual([errors, mainWindow.document.activeElement === list], [[], false]); }); + test('does not touch the table when disposed while resolving the added folders', async () => { + createTable(['c-two', 'z-last']); + const gate = new DeferredPromise<void>(); + trustService.trustInfoGate = gate.p; + await addFolder([folder('m-middle'), folder('a-first')]); + const list = container.querySelector('.monaco-list'); + const errors: unknown[] = []; + const previousHandler = errorHandler.getUnexpectedErrorHandler(); + errorHandler.setUnexpectedErrorHandler(error => errors.push(error)); + try { + table.dispose(); + gate.complete(); + await timeout(0); + } finally { + errorHandler.setUnexpectedErrorHandler(previousHandler); + } + assert.deepStrictEqual([errors, mainWindow.document.activeElement === list], [[], false]); + }); + test('edit selects the row matching an equivalent URI', () => { createTable(['c-two', 'm-middle', 'z-last']); selectRow('z-last'); diff --git a/src/vs/workbench/contrib/workspaces/browser/folderLocationStatusBar.ts b/src/vs/workbench/contrib/workspaces/browser/folderLocationStatusBar.ts new file mode 100644 index 000000000000..a48a3c161271 --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/browser/folderLocationStatusBar.ts @@ -0,0 +1,403 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { DisposableResizeObserver, scheduleAtNextAnimationFrame } from '../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../base/browser/window.js'; +import { isCancellationError, onUnexpectedError } from '../../../../base/common/errors.js'; +import { CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { IntervalTimer } from '../../../../base/common/async.js'; +import { Disposable, DisposableStore, MutableDisposable } from '../../../../base/common/lifecycle.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { observableValue } from '../../../../base/common/observable.js'; +import { basename } from '../../../../base/common/resources.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Action2, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { IActionWidgetService } from '../../../../platform/actionWidget/browser/actionWidget.js'; +import { ActionListItemKind, IActionListItem } from '../../../../platform/actionWidget/browser/actionList.js'; +import { AnchorPosition } from '../../../../base/common/layout.js'; +import { ICommandService } from '../../../../platform/commands/common/commands.js'; +import { ILabelService } from '../../../../platform/label/common/label.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../platform/quickinput/common/quickInput.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IFolderLocation, IWorkspaceFolderLocationService } from '../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js'; +import { registerOnboardingTargetProvider, resolveOnboardingTarget } from '../../onboarding/browser/spotlight/onboardingTarget.js'; +import { ISpotlightPayload, ISpotlightStep, SPOTLIGHT_PRESENTATION_KIND } from '../../onboarding/browser/spotlight/spotlightTypes.js'; +import { onboardingScenarioRegistry } from '../../onboarding/common/onboardingRegistry.js'; +import { IOnboardingScenario } from '../../onboarding/common/onboardingScenario.js'; +import { IOnboardingScenarioService } from '../../onboarding/common/onboardingScenarioService.js'; +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { IWorkbenchLayoutService, Parts } from '../../../services/layout/browser/layoutService.js'; +import { IStatusbarEntryAccessor, IStatusbarService, StatusbarAlignment } from '../../../services/statusbar/browser/statusbar.js'; +import { IWorkspaceEditingService } from '../../../services/workspaces/common/workspaceEditing.js'; + +const FOLDER_LOCATION_INTRODUCTION_ID = 'workbench.folderLocation.introduction'; +const FOLDER_LOCATION_INTRODUCTION_TARGET_ID = 'workbench.folderLocation.statusEntry'; +const FOLDER_LOCATION_STATUS_ENTRY_ID = 'status.workspace.folderLocation'; + +/** Coarse fallback for state without a change event (the onboarding service has none for "shown"). */ +const FOLDER_LOCATION_INTRODUCTION_POLL_INTERVAL = 2000; + +/** Just above the SCM entries (left priority 10000) and below the remote indicator (Number.MAX_VALUE). */ +const FOLDER_LOCATION_STATUS_ENTRY_PRIORITY = 10000.1; + +interface ILocationEntry { + readonly uri: URI; + readonly label: string; + readonly description?: string; + readonly icon: ThemeIcon; +} + +/** The action widget item data: the widget focuses by `id` and starts on the `checked` item. */ +interface IActionWidgetLocation extends ILocationEntry { + readonly id: string; + readonly checked: boolean; +} + +interface ILocationQuickPickItem extends IQuickPickItem { + readonly uri: URI; +} + +export const RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID = 'workbench.action.returnToPrimaryFolderLocation'; +export const SWITCH_FOLDER_LOCATION_COMMAND_ID = 'workbench.action.switchFolderLocation'; + +/** + * Shows the location of the workspace folder in the status bar while + * the folder is at an alternate location. + */ +export class FolderLocationStatusBarContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.folderLocationStatusBar'; + + private readonly entry = this._register(new MutableDisposable<IStatusbarEntryAccessor>()); + private readonly introductionReady = observableValue<boolean>(this, false); + private readonly introductionObservation = this._register(new MutableDisposable<DisposableStore>()); + private primaryName: string | undefined; + + constructor( + @IWorkspaceFolderLocationService private readonly folderLocationService: IWorkspaceFolderLocationService, + @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, + @ILabelService private readonly labelService: ILabelService, + @IStatusbarService private readonly statusbarService: IStatusbarService, + @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, + @ICommandService private readonly commandService: ICommandService, + @IOnboardingScenarioService private readonly onboardingService: IOnboardingScenarioService + ) { + super(); + + this.registerIntroduction(); + + this._register(this.folderLocationService.onDidChangeLocation(() => this.update())); + this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.update())); + this.update(); + } + + /** + * Introduces the status bar entry the first time the folder is at an alternate location, + * with a spotlight anchored on the entry. The onboarding engine shows it once, announces it and + * dismisses it with Escape. + */ + private registerIntroduction(): void { + this._register(registerOnboardingTargetProvider(FOLDER_LOCATION_INTRODUCTION_TARGET_ID, scope => { + // The status bar names each item element after its entry id, but does not expose the element otherwise. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- see above + const element = scope === undefined ? mainWindow.document.getElementById(FOLDER_LOCATION_STATUS_ENTRY_ID) : null; + return element ? { element } : undefined; + })); + + const scenario: IOnboardingScenario<ISpotlightPayload> = { + id: FOLDER_LOCATION_INTRODUCTION_ID, + trigger: { kind: 'observable', signal: this.introductionReady }, + presentation: { + kind: SPOTLIGHT_PRESENTATION_KIND, + payload: { + steps: [], + resolveSteps: async () => [this.createIntroductionStep()] + } + } + }; + this._register(onboardingScenarioRegistry.register(scenario)); + } + + private createIntroductionStep(): ISpotlightStep { + const primaryName = this.primaryName ?? ''; + const folder = this.contextService.getWorkspace().folders[0]; + const locationText = (folder && this.labelService.getFolderLocationLabel(folder.uri)) ?? ''; + return { + id: 'folderLocation', + targetId: FOLDER_LOCATION_INTRODUCTION_TARGET_ID, + title: localize('folderLocationIntroductionTitle', "Folder Location"), + description: localize('folderLocationSwitched', "The folder is now at the location '{0}'. Files, search, terminals and extensions use this location.", locationText), + primaryAction: { + label: localize('returnToPrimaryNamed', "Return to {0}", primaryName), + run: () => this.commandService.executeCommand(RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID), + advance: true + }, + endTourLabel: localize('gotIt', "Got It"), + focusEndTour: true, + placement: 'above', + missingTarget: { kind: 'abort' } + }; + } + + private update(): void { + const workspace = this.contextService.getWorkspace(); + const folder = workspace.folders[0]; + const location = folder ? this.folderLocationService.getLocation(folder) : undefined; + const identity = workspace.uri; + if (!folder || !location || !identity) { + this.entry.clear(); + this.introductionReady.set(false, undefined); + this.introductionObservation.clear(); + this.primaryName = undefined; + return; + } + + const primaryName = basename(identity); + this.primaryName = primaryName; + const props = { + name: localize('folderLocation', "Folder Location"), + text: `$(${location.icon?.id ?? Codicon.gitBranchCheckout.id}) ${location.label}`, + ariaLabel: localize('folderLocationAria', "Folder Location, {0}", this.labelService.getFolderLocationLabel(folder.uri)), + tooltip: localize('folderLocationTooltip', "{0} (alternate location of '{1}')", this.labelService.getFolderLocationLabel(folder.uri), primaryName), + command: { id: SWITCH_FOLDER_LOCATION_COMMAND_ID, title: localize('folderLocation', "Folder Location"), arguments: [FOLDER_LOCATION_STATUS_ENTRY_ID] }, + kind: 'prominent' as const + }; + + if (this.entry.value) { + this.entry.value.update(props); + } else { + this.entry.value = this.statusbarService.addEntry(props, FOLDER_LOCATION_STATUS_ENTRY_ID, StatusbarAlignment.LEFT, FOLDER_LOCATION_STATUS_ENTRY_PRIORITY); + if (!this.onboardingService.hasBeenShown(FOLDER_LOCATION_INTRODUCTION_ID)) { + this.observeIntroductionTarget(); + } + } + } + + /** + * The introduction is ready only while the entry is rendered and visible, because + * the onboarding engine marks a scenario as seen before it resolves its target. + * Readiness is re-evaluated, once per frame, when something that can change it happens (the + * status bar resizes or changes visibility, the entry hides or shows) until the introduction + * is shown or consumed. The onboarding service has no event for that, so a coarse timer, + * paused while the window is hidden, notices it. Nothing runs while idle. + */ + private observeIntroductionTarget(): void { + const store = new DisposableStore(); + const frame = store.add(new MutableDisposable()); + const check = () => { + if (this.onboardingService.hasBeenShown(FOLDER_LOCATION_INTRODUCTION_ID)) { + this.introductionObservation.clear(); + return; + } + this.introductionReady.set(!!resolveOnboardingTarget(mainWindow, FOLDER_LOCATION_INTRODUCTION_TARGET_ID), undefined); + }; + const scheduleCheck = () => { + if (!frame.value) { + frame.value = scheduleAtNextAnimationFrame(mainWindow, () => { + frame.clear(); + check(); + }); + } + }; + + const container = this.layoutService.getContainer(mainWindow, Parts.STATUSBAR_PART); + if (container) { + const resizeObserver = store.add(new DisposableResizeObserver('folderLocationIntroduction', scheduleCheck)); + store.add(resizeObserver.observe(container)); + } + store.add(this.statusbarService.onDidChangeEntryVisibility(e => e.id === FOLDER_LOCATION_STATUS_ENTRY_ID && scheduleCheck())); + store.add(this.layoutService.onDidChangePartVisibility(e => e.partId === Parts.STATUSBAR_PART && scheduleCheck())); + store.add(new IntervalTimer()).cancelAndSet(() => { + if (!mainWindow.document.hidden) { + scheduleCheck(); + } + }, FOLDER_LOCATION_INTRODUCTION_POLL_INTERVAL); + + scheduleCheck(); + this.introductionObservation.value = store; + } +} + +registerAction2(class ReturnToPrimaryFolderLocationAction extends Action2 { + + constructor() { + super({ + id: RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID, + title: localize2('returnToPrimaryFolderLocation', "Return to Primary Location"), + f1: false + }); + } + + async run(accessor: ServicesAccessor): Promise<void> { + const workspace = accessor.get(IWorkspaceContextService).getWorkspace(); + const identity = workspace.uri; + if (identity && workspace.folders[0] && accessor.get(IWorkspaceFolderLocationService).isAtAlternateLocation(workspace.folders[0])) { + await accessor.get(IWorkspaceEditingService).setFolderLocation(identity, { reason: 'user' }); + } + } +}); + +registerAction2(class SwitchFolderLocationAction extends Action2 { + + constructor() { + super({ + id: SWITCH_FOLDER_LOCATION_COMMAND_ID, + title: localize2('switchFolderLocation', "Switch Folder Location..."), + f1: false + }); + } + + async run(accessor: ServicesAccessor, anchorElementId?: string): Promise<void> { + const contextService = accessor.get(IWorkspaceContextService); + const workspace = contextService.getWorkspace(); + const folder = workspace.folders[0]; + const primary = workspace.uri; + if (!folder || !primary) { + return; + } + const folderLocationService = accessor.get(IWorkspaceFolderLocationService); + + const workspaceEditingService = accessor.get(IWorkspaceEditingService); + const uriIdentityService = accessor.get(IUriIdentityService); + + // The status bar names each item element after its entry id, but does not expose the element otherwise. + // eslint-disable-next-line eslint-js/no-restricted-syntax -- see above + const anchor = anchorElementId ? mainWindow.document.getElementById(anchorElementId) : null; + + const isCurrentUri = (uri: URI) => uriIdentityService.extUri.isEqual(uri, folder.uri); + const currentLocation = folderLocationService.getLocation(folder); + const primaryEntry: ILocationEntry = { uri: primary, label: basename(primary), description: localize('primaryLocation', "Primary Location"), icon: Codicon.folder }; + // Seed the current location so that accepting before the lookup resolves keeps it + const currentSeed: ILocationEntry | undefined = currentLocation ? { uri: folder.uri, label: currentLocation.label, description: currentLocation.description, icon: currentLocation.icon ?? Codicon.gitBranchCheckout } : undefined; + const seedEntries = currentSeed ? [primaryEntry, currentSeed] : [primaryEntry]; + const toEntries = (locations: readonly IFolderLocation[]) => [primaryEntry, ...locations.map((location): ILocationEntry => ({ uri: location.uri, label: location.label, description: location.description, icon: location.icon ?? Codicon.gitBranchCheckout }))]; + + const store = new DisposableStore(); + const cts = store.add(new CancellationTokenSource()); + // Show the picker right away: resolving the locations can take a while + const loadLocations = (onResolved: (entries: ILocationEntry[]) => void, onDone: () => void) => { + folderLocationService.getLocations(primary, cts.token).then(locations => { + if (!cts.token.isCancellationRequested) { + onResolved(toEntries(locations)); + } + }, error => { + if (!cts.token.isCancellationRequested && !isCancellationError(error)) { + onUnexpectedError(error); + } + }).finally(() => { + if (!cts.token.isCancellationRequested) { + onDone(); + } + }); + }; + + let picked: ILocationEntry | undefined; + if (anchor) { + const actionWidgetService = accessor.get(IActionWidgetService); + const toActionItems = (entries: readonly ILocationEntry[]): IActionListItem<IActionWidgetLocation>[] => entries.map(entry => { + const checked = isCurrentUri(entry.uri); + return { + kind: ActionListItemKind.Action, + item: { ...entry, id: uriIdentityService.extUri.getComparisonKey(entry.uri), checked }, + label: entry.label, + description: entry.description, + labelIcon: entry.icon, + group: { title: '', icon: checked ? Codicon.check : Codicon.blank } + }; + }); + picked = await new Promise<ILocationEntry | undefined>(resolve => { + actionWidgetService.show<IActionWidgetLocation>( + 'folderLocationPicker', + false, + toActionItems(seedEntries), + { + onSelect: entry => { + // Resolve first: hiding runs onHide synchronously, which would report a cancellation + resolve(entry); + actionWidgetService.hide(); + }, + onHide: () => { + // The status bar item wrapper is not focusable, its label is + const label = Array.from(anchor.children).find(child => child.classList.contains('statusbar-item-label')) as HTMLElement | undefined; + (label ?? anchor).focus(); + resolve(undefined); + } + }, + anchor, + undefined, + [], + { + getAriaLabel: listItem => { + const entry = listItem.item; + if (!entry) { + return ''; + } + const text = entry.description ? localize('folderLocationItemAria', "{0}, {1}", entry.label, entry.description) : entry.label; + return entry.checked ? localize('folderLocationCurrentItemAria', "{0}, Current", text) : text; + }, + getWidgetAriaLabel: () => localize('folderLocationPickerAria', "Folder Location") + }, + // The status bar sits at the bottom, so size the list for the space above it. The label keeps its width, the description gives way + { preferredAnchorPosition: AnchorPosition.ABOVE, inlineDescription: true } + ); + const focusId = uriIdentityService.extUri.getComparisonKey((currentSeed ?? primaryEntry).uri); + actionWidgetService.focusItemById(focusId); + loadLocations(entries => actionWidgetService.updateItems(toActionItems(entries)), () => { }); + }).finally(() => { + cts.cancel(); + store.dispose(); + }); + } else { + const quickInputService = accessor.get(IQuickInputService); + const toItem = (entry: ILocationEntry): ILocationQuickPickItem => ({ + uri: entry.uri, + label: entry.label, + iconClass: ThemeIcon.asClassName(entry.icon), + description: isCurrentUri(entry.uri) ? (entry.description ? localize('currentLocationWithDescription', "{0} (Current)", entry.description) : localize('currentLocation', "Current")) : entry.description + }); + const quickPick = store.add(quickInputService.createQuickPick<ILocationQuickPickItem>({ useSeparators: false })); + quickPick.placeholder = localize('switchFolderLocationPlaceholder', "Select a Location for the Folder"); + quickPick.matchOnDescription = true; + const seedItems = seedEntries.map(toItem); + quickPick.items = seedItems; + quickPick.activeItems = [seedItems[seedItems.length - 1]]; + quickPick.busy = true; + const pickedItem = await new Promise<ILocationQuickPickItem | undefined>(resolve => { + store.add(quickPick.onDidAccept(() => resolve(quickPick.selectedItems[0]))); + store.add(quickPick.onDidHide(() => resolve(undefined))); + quickPick.show(); + loadLocations(entries => { + const items = entries.map(toItem); + quickPick.items = items; + const currentItem = items.find(item => isCurrentUri(item.uri)); + if (currentItem) { + quickPick.activeItems = [currentItem]; + } + }, () => { + quickPick.busy = false; + }); + }).finally(() => { + cts.cancel(); + store.dispose(); + }); + picked = pickedItem && { uri: pickedItem.uri, label: pickedItem.label ?? '', icon: Codicon.blank }; + } + if (!picked) { + return; + } + + // Re-submitting the current location is deliberate: it supersedes a different switch that is still pending + const currentIdentity = contextService.getWorkspace().uri; + if (!currentIdentity || !uriIdentityService.extUri.isEqual(currentIdentity, primary)) { + return; + } + + await workspaceEditingService.setFolderLocation(picked.uri, { reason: 'user' }); + } +}); diff --git a/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.contribution.ts b/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.contribution.ts new file mode 100644 index 000000000000..affcc361b67d --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.contribution.ts @@ -0,0 +1,10 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js'; +import { FolderLocationWorkingSetsContribution } from './folderLocationWorkingSets.js'; + +// Registered from the workbench entry point only: the Agents window keeps its own per-session editor sets. +registerWorkbenchContribution2(FolderLocationWorkingSetsContribution.ID, FolderLocationWorkingSetsContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.ts b/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.ts new file mode 100644 index 000000000000..d74e2048a90c --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/browser/folderLocationWorkingSets.ts @@ -0,0 +1,338 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Sequencer } from '../../../../base/common/async.js'; +import { Event } from '../../../../base/common/event.js'; +import { Disposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IWorkspaceFolderLocationService } from '../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, IWorkspaceFolder } from '../../../../platform/workspace/common/workspace.js'; +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { GroupModelChangeKind } from '../../../common/editor.js'; +import { EditorInput } from '../../../common/editor/editorInput.js'; +import { SideBySideEditorInput } from '../../../common/editor/sideBySideEditorInput.js'; +import { IEditorGroupsService, IEditorWorkingSet } from '../../../services/editor/common/editorGroupsService.js'; +import { IEditorService } from '../../../services/editor/common/editorService.js'; +import { IWorkingCopyBackupService } from '../../../services/workingCopy/common/workingCopyBackup.js'; +import { IWorkingCopyService } from '../../../services/workingCopy/common/workingCopyService.js'; + +export const FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY = 'folderLocation.workingSets'; +export const FOLDER_LOCATION_MAX_WORKING_SETS = 20; + +/** Marks the working sets owned by this contribution, so that unreferenced ones can be told apart from others. */ +export const FOLDER_LOCATION_WORKING_SET_NAME_PREFIX = 'folderLocation:'; + +interface IStoredWorkingSets { + readonly version: 1; + + /** The location whose editors are in the editor area. */ + readonly owner?: string; + + /** The editor area may only partially hold the editors of the owner, whose saved working set is authoritative. */ + readonly partial?: boolean; + readonly entries: readonly { readonly key: string; readonly workingSet: IEditorWorkingSet }[]; +} + +/** + * Keeps one working set of open editors per location of the workspace folder: + * when the folder switches location, the editors of the location being left are + * saved and the ones of the location being entered are restored. A location that + * is visited for the first time starts with no editors. + * + * The location that owns the editor area is persisted, so that a window that starts at + * another location than the one it was closed at (for example because the alternate + * location is gone) swaps the editors of the last session out. + */ +export class FolderLocationWorkingSetsContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.folderLocationWorkingSets'; + + private readonly sequencer = new Sequencer(); + + /** Ordered from least to most recently saved. */ + private workingSets: { key: string; workingSet: IEditorWorkingSet }[]; + + /** The location whose editors are in the editor area. Only changes once they were applied. */ + private owner: string | undefined; + + /** + * Set from right before an apply starts until one succeeds: applying can close editors before it + * fails or while it is pending, so the editor area is no longer a faithful copy of the owner's editors. + * The saved working set of the owner is kept as is until an apply succeeds. + */ + private partial: boolean; + + private disposed = false; + + /** Set while a switch waits for the backups of editors it would close to be restored. */ + private deferred = false; + + /** Counts the changes of dirty state of working copies and editors and unregistrations of working copies, which can make a deferred switch possible. */ + private workingCopyGeneration = 0; + + constructor( + @IWorkspaceFolderLocationService private readonly folderLocationService: IWorkspaceFolderLocationService, + @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, + @IEditorGroupsService private readonly editorGroupsService: IEditorGroupsService, + @IStorageService private readonly storageService: IStorageService, + @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, + @ILogService private readonly logService: ILogService, + @IWorkingCopyBackupService private readonly workingCopyBackupService: IWorkingCopyBackupService, + @IWorkingCopyService private readonly workingCopyService: IWorkingCopyService, + @IEditorService editorService: IEditorService + ) { + super(); + + this._register(toDisposable(() => this.disposed = true)); + + const stored = this.load(); + this.workingSets = stored.entries; + this.owner = stored.owner ?? this.getCurrentKey(); + this.partial = stored.partial; + this.deleteOrphans(); + + this._register(this.folderLocationService.onDidChangeLocation(() => this.reconcile())); + + // A restored backup makes its editor dirty, and an unregistered working copy discards its backup + // An editor can change whether it closes without its working copy changing, for example when a save fails + const onDidChangeEditorDirty = Event.filter(editorService.onDidEditorsChange, e => e.event.kind === GroupModelChangeKind.EDITOR_DIRTY); + this._register(Event.any<unknown>(this.workingCopyService.onDidChangeDirty, this.workingCopyService.onDidUnregister, onDidChangeEditorDirty)(() => { + this.workingCopyGeneration++; + if (this.deferred) { + this.reconcile(); + } + })); + this.reconcile(); + } + + /** The folder whose location is tracked: only the folder of a workspace that supports locations. */ + private getFolder(): IWorkspaceFolder | undefined { + const folder = this.contextService.getWorkspace().folders.at(0); + return folder && this.folderLocationService.canSetLocation(folder) ? folder : undefined; + } + + private getCurrentKey(): string | undefined { + const folder = this.getFolder(); + return folder ? this.toKey(folder.uri) : undefined; + } + + private toKey(uri: URI): string { + return this.uriIdentityService.extUri.getComparisonKey(uri); + } + + /** Makes the editor area hold the editors of the current location. */ + private reconcile(): void { + // Always queue: the owner can still change while an earlier apply is pending, so + // whether anything is left to do is decided once the earlier work has settled. + this.sequencer.queue(async () => { + this.deferred = false; + + // Restored editors, for example untitled ones whose backup is still being restored, must not be closed + await this.editorGroupsService.whenRestored; + + // Outside of a workspace that supports locations nothing is switched or saved, and the stored data is kept + const entering = this.getCurrentKey(); + if (this.disposed || !this.owner || !entering || (this.owner === entering && !this.partial)) { + return; + } + + // Closing an input whose backup is not restored yet discards the backup, and closing a side by side editor disposes + // its dirty sides: retried once inputs change their dirty state. A change that comes in while the backups are + // queried could be missed by them, so it checks again right away. + const generation = this.workingCopyGeneration; + this.deferred = await this.wouldCloseUnsavedInputs(); + if (this.deferred || this.disposed) { + if (this.deferred && generation !== this.workingCopyGeneration) { + this.reconcile(); + } else if (this.deferred) { + this.logService.info('[folderLocation] Deferring the switch of the editors until their backups are restored and the dirty sides of closing side by side editors are saved'); + } + return; + } + + await this.switchWorkingSet(this.owner, entering); + }).catch(error => this.logService.error('[folderLocation] Failed to switch the editors', error)); + } + + /** + * Whether applying a working set would dispose unsaved content: an input that has a backup that is not + * restored yet, or a dirty side of a side by side editor that closes because its primary side is not dirty or is saving. + * A backup only exists for unsaved content and a restored one makes its input dirty: so a backup of an + * input that is not dirty is not restored yet, also when its working copy is already registered. + * A backup whose input never restores, or a dirty side that is never saved, keeps the switch deferred. + */ + private async wouldCloseUnsavedInputs(): Promise<boolean> { + if (this.getClosingInputs().length === 0) { + return false; + } + + const backups = await this.workingCopyBackupService.getBackups(); + + // The editors are only looked at once the backups are known, so that they are current + return this.getClosingInputs().some(({ input, side }) => input.isDirty() + ? side + : backups.some(backup => this.uriIdentityService.extUri.isEqual(input.resource, backup.resource))); + } + + /** + * The inputs that applying a working set disposes: the editors that close without confirmation + * (that are not dirty, or are dirty and saving) and, for side by side editors, all of their sides, + * also the dirty ones, because closing the editor disposes them. + */ + private getClosingInputs(): { input: EditorInput; side: boolean }[] { + const inputs: { input: EditorInput; side: boolean }[] = []; + const add = (input: EditorInput, side: boolean) => { + inputs.push({ input, side }); + if (input instanceof SideBySideEditorInput) { + add(input.primary, true); + add(input.secondary, true); + } + }; + for (const part of this.editorGroupsService.parts) { + if (part.isTransient) { + continue; + } + for (const group of part.groups) { + for (const editor of group.editors) { + if (!editor.isDirty() || editor.isSaving()) { + add(editor, false); + } + } + } + } + return inputs; + } + + private async switchWorkingSet(leaving: string, entering: string): Promise<void> { + + // Save the editors of the location being left. Nothing is saved for an empty editor + // area so that the location restores to what it had before the editors were closed. + // The editors of the main part and of the windows that are part of working sets count. + // The editor area is not saved over the working set of an owner it only partially holds. + if (!this.partial && this.editorGroupsService.parts.some(part => !part.isTransient && part.groups.some(group => group.count > 0))) { + this.save(leaving, entering); + } + + // Apply the editors of the location being entered. The location only owns the editor + // area once that worked. When its saved working set cannot be applied, the editors of the + // location being left (already saved above) must not stay open: they belong to another + // location. The entering location then starts empty. Its saved set is kept, because + // the failure can be transient: it is replaced when the location is left with editors open. + const target = this.workingSets.find(entry => entry.key === entering); + if (this.disposed) { + return; + } + + // Applying replaces the editors before it settles: until it succeeded, the saved working set + // of the owner stays authoritative, also for a window that restarts meanwhile. + if (!this.partial) { + this.partial = true; + this.store(); + } + if (target && await this.tryApply(target.workingSet)) { + this.owner = entering; + this.partial = false; + this.store(); + return; + } + if (leaving !== entering && await this.tryApply('empty')) { + this.owner = entering; + this.partial = false; + this.store(); + } + } + + private async tryApply(workingSet: IEditorWorkingSet | 'empty'): Promise<boolean> { + try { + if (await this.editorGroupsService.applyWorkingSet(workingSet, { preserveFocus: true })) { + return true; + } + this.logService.error('[folderLocation] The working set could not be applied'); + } catch (error) { + this.logService.error('[folderLocation] Failed to apply the working set', error); + } + return false; + } + + private save(key: string, protectedKey: string): void { + const previous = this.workingSets.find(entry => entry.key === key); + const workingSet = this.editorGroupsService.saveWorkingSet(FOLDER_LOCATION_WORKING_SET_NAME_PREFIX + key); + + this.workingSets = this.workingSets.filter(entry => entry !== previous); + this.workingSets.push({ key, workingSet }); + if (previous) { + this.editorGroupsService.deleteWorkingSet(previous.workingSet); + } + + // The location being entered is about to be restored, so it is the last to be evicted + while (this.workingSets.length > FOLDER_LOCATION_MAX_WORKING_SETS) { + const index = this.workingSets.findIndex(entry => entry.key !== protectedKey); + const [evicted] = this.workingSets.splice(index, 1); + this.editorGroupsService.deleteWorkingSet(evicted.workingSet); + } + + this.store(); + } + + /** Deletes the working sets that were saved but never made it into the stored mapping, for example because of a crash. */ + private deleteOrphans(): void { + const referenced = new Set(this.workingSets.map(entry => entry.workingSet.id)); + for (const workingSet of this.editorGroupsService.getWorkingSets()) { + if (workingSet.name.startsWith(FOLDER_LOCATION_WORKING_SET_NAME_PREFIX) && !referenced.has(workingSet.id)) { + this.editorGroupsService.deleteWorkingSet(workingSet); + } + } + } + + private load(): { owner: string | undefined; partial: boolean; entries: { key: string; workingSet: IEditorWorkingSet }[] } { + const raw = this.storageService.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE); + if (!raw) { + return { owner: undefined, partial: false, entries: [] }; + } + + let stored: IStoredWorkingSets | undefined; + try { + stored = JSON.parse(raw); + } catch { + return { owner: undefined, partial: false, entries: [] }; + } + if (stored?.version !== 1 || !Array.isArray(stored.entries)) { + return { owner: undefined, partial: false, entries: [] }; + } + + // Drop handles whose editor state no longer exists. Keys are normalized, so that a location + // stored with another casing of its path is the same location. The most recently saved wins. + const existing = new Set(this.editorGroupsService.getWorkingSets().map(workingSet => workingSet.id)); + const entries = new Map<string, { key: string; workingSet: IEditorWorkingSet }>(); + for (const entry of stored.entries) { + const key = typeof entry.key === 'string' ? this.normalizeKey(entry.key) : undefined; + if (key && existing.has(entry.workingSet?.id)) { + entries.delete(key); + entries.set(key, { key, workingSet: entry.workingSet }); + } + } + return { + owner: typeof stored.owner === 'string' ? this.normalizeKey(stored.owner) : undefined, + partial: stored.partial === true, + entries: [...entries.values()].slice(-FOLDER_LOCATION_MAX_WORKING_SETS) + }; + } + + private normalizeKey(key: string): string | undefined { + try { + return this.toKey(URI.parse(key, true)); + } catch { + return undefined; + } + } + + private store(): void { + const stored: IStoredWorkingSets = { version: 1, owner: this.owner, partial: this.partial || undefined, entries: this.workingSets }; + this.storageService.store(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, JSON.stringify(stored), StorageScope.WORKSPACE, StorageTarget.MACHINE); + } +} diff --git a/src/vs/workbench/contrib/workspaces/electron-browser/folderLocationPersistence.ts b/src/vs/workbench/contrib/workspaces/electron-browser/folderLocationPersistence.ts new file mode 100644 index 000000000000..4fead55c0f19 --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/electron-browser/folderLocationPersistence.ts @@ -0,0 +1,222 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { Disposable, DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { localize } from '../../../../nls.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { INotificationService, Severity } from '../../../../platform/notification/common/notification.js'; +import { INativeHostService } from '../../../../platform/native/common/native.js'; +import { IWorkspaceFolderLocationService, IResolvedFolderLocation } from '../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, isSingleFolderWorkspaceIdentifier, toWorkspaceIdentifier } from '../../../../platform/workspace/common/workspace.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IWindowFolderLocation } from '../../../../platform/window/common/window.js'; +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { INativeWorkbenchEnvironmentService } from '../../../services/environment/electron-browser/environmentService.js'; +import { IWorkspaceEditingService } from '../../../services/workspaces/common/workspaceEditing.js'; + +/** + * The time to wait for a provider to confirm the persisted location. Providers + * may register after the window has been restored. + */ +export const FOLDER_LOCATION_RESTORE_TIMEOUT = 10000; + +/** + * Keeps the main process informed about the alternate location the window is at + * so that it survives a reload or restart, and confirms the location the window + * has been started at. + * + * The main process only starts a window at an alternate location that exists (otherwise the window + * opens at the primary location and `folderLocationMissing` tells the user). The window starts there + * without any trust being granted. Once a provider confirms the location, it becomes the current + * location. If no provider does, the user is offered to return to the primary location: the window + * never switches back by itself. + */ +export class FolderLocationPersistenceContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.folderLocationPersistence'; + + constructor( + @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, + @IWorkspaceFolderLocationService private readonly folderLocationService: IWorkspaceFolderLocationService, + @IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService, + @INativeHostService private readonly nativeHostService: INativeHostService, + @INativeWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, + @INotificationService private readonly notificationService: INotificationService, + @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, + @ILogService private readonly logService: ILogService + ) { + super(); + + this._register(this.folderLocationService.onDidChangeLocation(e => this.persist(this.folderLocationService.getLocation(e.folder)))); + + const missing = environmentService.folderLocationMissing; + if (missing) { + this.notificationService.notify({ + id: 'workbench.folderLocationMissing', + severity: Severity.Warning, + message: localize('folderLocationMissing', "The folder location '{0}' no longer exists. The folder was opened at its primary location.", missing.label) + }); + } + + const persisted = environmentService.folderLocation; + if (persisted) { + const cts = new CancellationTokenSource(); + this._register(toDisposable(() => cts.dispose(true))); + this.restore(persisted, cts.token); + } else { + + // A switch may have been confirmed before this contribution was instantiated + const current = this.contextService.getWorkspace(); + const folder = current.folders[0]; + const confirmed = folder && isSingleFolderWorkspaceIdentifier(toWorkspaceIdentifier(current)) ? this.folderLocationService.getLocation(folder) : undefined; + if (confirmed) { + this.persist(confirmed); + } + } + } + + private persist(location: IResolvedFolderLocation | undefined): void { + const value: IWindowFolderLocation | undefined = location ? { uri: location.uri.toString(), label: location.label, providerId: location.providerId } : undefined; + this.nativeHostService.setWindowFolderLocation(value); + } + + private isAtAlternate(location: URI): boolean { + const folder = this.contextService.getWorkspace().folders[0]; + return !!folder && this.folderLocationService.isAtAlternateLocation(folder) && this.uriIdentityService.extUri.isEqual(folder.uri, location); + } + + private async restore(persisted: IWindowFolderLocation, token: CancellationToken): Promise<void> { + const location = URI.parse(persisted.uri); + + // The state is reconciled against the current workspace: it may have changed since startup + const current = this.contextService.getWorkspace(); + const folder = current.folders[0]; + if (!folder || !isSingleFolderWorkspaceIdentifier(toWorkspaceIdentifier(current))) { + this.nativeHostService.setWindowFolderLocation(undefined); // stale: no longer a single-folder window + return; + } + + const confirmed = this.folderLocationService.getLocation(folder); + if (confirmed) { + this.persist(confirmed); // already switched and confirmed, that state is authoritative + return; + } + + if (!this.isAtAlternate(location)) { + if (this.folderLocationService.isAtAlternateLocation(folder)) { + this.nativeHostService.setWindowFolderLocation(undefined); // moved to another location in the meantime + } else { + + // The window could not start at the persisted location, for example because it is gone + this.discard(persisted); + } + return; + } + + const workspace = this.contextService.getWorkspace(); + const primary = workspace.uri ?? workspace.folders[0].uri; + + const resolved = await this.resolve(primary, location, token); + if (token.isCancellationRequested || this.folderLocationService.getLocation(this.contextService.getWorkspace().folders[0]) || !this.isAtAlternate(location)) { + return; // disposed, or switched by someone else in the meantime + } + + if (resolved) { + this.folderLocationService.setLocation(this.contextService.getWorkspace().folders[0], resolved); + } else { + this.offerReturnToPrimary(persisted, primary); + } + } + + /** + * Resolves the location through the providers, waiting for providers to register until the + * deadline. The deadline covers the resolution itself, and results arriving after it are dropped. + */ + private async resolve(primary: URI, location: URI, token: CancellationToken): Promise<IResolvedFolderLocation | undefined> { + const store = new DisposableStore(); + try { + const source = store.add(new CancellationTokenSource(token)); + const handle = setTimeout(() => source.cancel(), FOLDER_LOCATION_RESTORE_TIMEOUT); + store.add(toDisposable(() => clearTimeout(handle))); + + const stopped = new Promise<undefined>(resolve => store.add(source.token.onCancellationRequested(() => resolve(undefined)))); + + // Observed before resolving, so that a provider registering meanwhile is never missed + let generation = 0; + let wake: (() => void) | undefined; + store.add(this.folderLocationService.onDidChangeProviders(() => { + generation++; + wake?.(); + })); + + while (!source.token.isCancellationRequested) { + const seen = generation; + const resolved = await Promise.race([this.folderLocationService.resolveLocation(primary, location, source.token).catch(() => undefined), stopped]); + if (source.token.isCancellationRequested) { + return undefined; + } + if (resolved) { + return resolved; + } + + if (generation === seen) { + await Promise.race([new Promise<void>(resolve => { wake = resolve; }), stopped]); + wake = undefined; + } + } + + return undefined; + } finally { + store.dispose(); + } + } + + private offerReturnToPrimary(persisted: IWindowFolderLocation, primary: URI): void { + const location = URI.parse(persisted.uri); + const handle = this.notificationService.prompt( + Severity.Warning, + localize('folderLocationUnconfirmed', "The folder location '{0}' could not be confirmed. The folder is still open there.", persisted.label), + [{ + label: localize('returnToPrimaryFolderLocation', "Return to Primary Location"), + run: () => { + if (this.isStillAt(primary, location)) { + return this.workspaceEditingService.setFolderLocation(primary).catch(error => this.logService.error('Failed to return the folder to its primary location', error)); + } + return undefined; + } + }], + { sticky: true } + ); + + // The question is moot once the location is confirmed or changed, the workspace changes or this is disposed + const store = this._register(new DisposableStore()); + store.add(toDisposable(() => handle.close())); + const stop = () => store.dispose(); + store.add(this.folderLocationService.onDidChangeLocation(stop)); + store.add(this.contextService.onDidChangeWorkbenchState(stop)); + store.add(this.contextService.onDidChangeWorkspaceFolders(stop)); + store.add(handle.onDidClose(stop)); + } + + private isStillAt(primary: URI, location: URI): boolean { + const workspace = this.contextService.getWorkspace(); + const folder = workspace.folders[0]; + return !!folder && isSingleFolderWorkspaceIdentifier(toWorkspaceIdentifier(workspace)) + && this.uriIdentityService.extUri.isEqual(workspace.uri ?? folder.uri, primary) + && !this.folderLocationService.getLocation(folder) + && this.isAtAlternate(location); + } + + private discard(persisted: IWindowFolderLocation): void { + this.nativeHostService.setWindowFolderLocation(undefined); + this.notificationService.notify({ + id: 'workbench.folderLocationRestoreFailed', + severity: Severity.Warning, + message: localize('folderLocationRestoreFailed', "Could not restore the folder location '{0}'. The folder is open at its primary location.", persisted.label) + }); + } +} diff --git a/src/vs/workbench/contrib/workspaces/electron-browser/workspaces.contribution.ts b/src/vs/workbench/contrib/workspaces/electron-browser/workspaces.contribution.ts new file mode 100644 index 000000000000..a8ac6f383e29 --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/electron-browser/workspaces.contribution.ts @@ -0,0 +1,9 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js'; +import { FolderLocationPersistenceContribution } from './folderLocationPersistence.js'; + +registerWorkbenchContribution2(FolderLocationPersistenceContribution.ID, FolderLocationPersistenceContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/workbench/contrib/workspaces/test/browser/folderLocationStatusBar.test.ts b/src/vs/workbench/contrib/workspaces/test/browser/folderLocationStatusBar.test.ts new file mode 100644 index 000000000000..fd0e3dccc0fa --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/test/browser/folderLocationStatusBar.test.ts @@ -0,0 +1,427 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { AnchorPosition } from '../../../../../base/common/layout.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { errorHandler } from '../../../../../base/common/errors.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; +import { CommandsRegistry, ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { extUri } from '../../../../../base/common/resources.js'; +import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; +import { IResolvedFolderLocation, IWorkspaceFolderLocationService } from '../../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { resolveOnboardingTarget } from '../../../onboarding/browser/spotlight/onboardingTarget.js'; +import { ISpotlightPayload } from '../../../onboarding/browser/spotlight/spotlightTypes.js'; +import { onboardingScenarioRegistry } from '../../../onboarding/common/onboardingRegistry.js'; +import { IOnboardingScenarioService } from '../../../onboarding/common/onboardingScenarioService.js'; +import { IWorkbenchLayoutService, Parts } from '../../../../services/layout/browser/layoutService.js'; +import { IStatusbarEntry, IStatusbarService, StatusbarAlignment } from '../../../../services/statusbar/browser/statusbar.js'; +import { ILabelService } from '../../../../../platform/label/common/label.js'; +import { IWorkspaceEditingService } from '../../../../services/workspaces/common/workspaceEditing.js'; +import { FolderLocationStatusBarContribution, RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID, SWITCH_FOLDER_LOCATION_COMMAND_ID } from '../../browser/folderLocationStatusBar.js'; + +function identityFake(getWorkspace: () => Workspace) { + return { + isAtAlternateLocation: () => { const workspace = getWorkspace(); return workspace.uri!.toString() !== workspace.folders[0].uri.toString(); }, + }; +} + +suite('FolderLocationStatusBarContribution', () => { + + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + const primary = URI.file('/work/project'); + const alternate = URI.file('/work/project-alt'); + const location: IResolvedFolderLocation = { uri: alternate, label: 'Alternate', description: 'feature/x', icon: Codicon.gitBranch, providerId: 'test', builtIn: true }; + + function createFixture(shown = { value: false }) { + const entries: IStatusbarEntry[] = []; + const added: { alignment: unknown; priority: unknown }[] = []; + let visible = false; + const executed: string[] = []; + const onDidChangeCurrentLocation = ds.add(new Emitter<void>()); + const onDidChangeWorkspaceFolders = ds.add(new Emitter<void>()); + const onDidChangeEntryVisibility = ds.add(new Emitter<{ id: string; visible: boolean }>()); + const onDidChangePartVisibility = ds.add(new Emitter<{ partId: string; visible: boolean }>()); + const statusbarContainer = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + ds.add({ dispose: () => statusbarContainer.remove() }); + + let currentLocation: IResolvedFolderLocation | undefined; + let workspace = new Workspace('id', [new WorkspaceFolder({ uri: primary, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + + const contribution = ds.add(new FolderLocationStatusBarContribution( + { ...identityFake(() => workspace), getLocation: () => identityFake(() => workspace).isAtAlternateLocation() ? currentLocation : undefined, onDidChangeLocation: onDidChangeCurrentLocation.event } as unknown as IWorkspaceFolderLocationService, + { getWorkspace: () => workspace, onDidChangeWorkspaceFolders: onDidChangeWorkspaceFolders.event } as unknown as IWorkspaceContextService, + { getFolderLocationLabel: () => currentLocation ? `${currentLocation.label} · ${currentLocation.description}` : undefined } as unknown as ILabelService, + { + onDidChangeEntryVisibility: onDidChangeEntryVisibility.event, + addEntry(entry: IStatusbarEntry, _id: string, alignment: unknown, priority: unknown) { + added.push({ alignment, priority }); + entries.push(entry); + visible = true; + return { update: (e: IStatusbarEntry) => { entries.push(e); }, dispose: () => { visible = false; } }; + } + } as unknown as IStatusbarService, + { getContainer: () => statusbarContainer, onDidChangePartVisibility: onDidChangePartVisibility.event } as unknown as IWorkbenchLayoutService, + { executeCommand: async (id: string) => { executed.push(id); } } as unknown as ICommandService, + { hasBeenShown: () => shown.value } as unknown as IOnboardingScenarioService + )); + + return { + contribution, entries, executed, added, statusbarContainer, + entryVisibilityChanged: () => onDidChangeEntryVisibility.fire({ id: 'status.workspace.folderLocation', visible: true }), + partVisibilityChanged: () => onDidChangePartVisibility.fire({ partId: Parts.STATUSBAR_PART, visible: true }), + isVisible: () => visible, + switchTo() { + currentLocation = location; + workspace = new Workspace('id', [new WorkspaceFolder({ uri: alternate, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + onDidChangeCurrentLocation.fire(); + }, + returnToPrimary() { + currentLocation = undefined; + workspace = new Workspace('id', [new WorkspaceFolder({ uri: primary, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + onDidChangeCurrentLocation.fire(); + } + }; + } + + test('entry sits after the remote indicator and before the SCM entries', () => { + const fixture = createFixture(); + fixture.switchTo(); + assert.deepStrictEqual(fixture.added, [{ alignment: StatusbarAlignment.LEFT, priority: 10000.1 }]); + }); + + test('entry is prominent and shown only at an alternate location', () => { + const fixture = createFixture(); + assert.strictEqual(fixture.isVisible(), false); + + fixture.switchTo(); + assert.deepStrictEqual( + { visible: fixture.isVisible(), text: fixture.entries[0].text, ariaLabel: fixture.entries[0].ariaLabel, command: fixture.entries[0].command, kind: fixture.entries[0].kind, tooltip: fixture.entries[0].tooltip }, + { visible: true, text: '$(git-branch) Alternate', ariaLabel: 'Folder Location, Alternate · feature/x', command: { id: SWITCH_FOLDER_LOCATION_COMMAND_ID, title: 'Folder Location', arguments: ['status.workspace.folderLocation'] }, kind: 'prominent', tooltip: `Alternate · feature/x (alternate location of 'project')` }); + + fixture.returnToPrimary(); + assert.strictEqual(fixture.isVisible(), false); + }); + + test('the introduction is a spotlight on the entry that can return to the primary', async () => { + const fixture = createFixture(); + const scenario = () => onboardingScenarioRegistry.getScenario('workbench.folderLocation.introduction')!; + const signal = () => { + const trigger = scenario().trigger; + return trigger.kind === 'observable' && trigger.signal.get(); + }; + assert.strictEqual(signal(), false); + + const element = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + element.id = 'status.workspace.folderLocation'; + element.style.cssText = 'width: 10px; height: 10px; display: none'; + ds.add({ dispose: () => element.remove() }); + const nextFrame = () => new Promise<void>(resolve => mainWindow.requestAnimationFrame(() => resolve())); + + fixture.switchTo(); + await nextFrame(); + const whileHidden = signal(); + + element.style.display = 'block'; + fixture.entryVisibilityChanged(); + for (let i = 0; i < 20 && !signal(); i++) { + await nextFrame(); + } + const [step] = await (scenario().presentation.payload as ISpotlightPayload).resolveSteps!(); + assert.deepStrictEqual( + { whileHidden, signal: signal(), target: resolveOnboardingTarget(mainWindow, step.targetId)?.element === element, primaryAction: step.primaryAction?.label, endTour: step.endTourLabel, focusEndTour: step.focusEndTour }, + { whileHidden: false, signal: true, target: true, primaryAction: 'Return to project', endTour: 'Got It', focusEndTour: true }); + + await step.primaryAction!.run(undefined as never); + assert.deepStrictEqual(fixture.executed, [RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID]); + + fixture.returnToPrimary(); + assert.strictEqual(signal(), false); + }); + + suite('introduction observation', () => { + + function setup(shown: { value: boolean }) { + const fixture = createFixture(shown); + const trigger = onboardingScenarioRegistry.getScenario('workbench.folderLocation.introduction')!.trigger; + const signal = () => trigger.kind === 'observable' && trigger.signal.get(); + const element = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + element.id = 'status.workspace.folderLocation'; + element.style.cssText = 'width: 10px; height: 10px; display: block'; + ds.add({ dispose: () => element.remove() }); + const frames = async (count: number) => { + for (let i = 0; i < count; i++) { + await new Promise<void>(resolve => mainWindow.requestAnimationFrame(() => resolve())); + } + }; + return { fixture, signal, element, frames }; + } + + test('no observer when the introduction was already shown', async () => { + const { fixture, signal, frames } = setup({ value: true }); + fixture.switchTo(); + await frames(5); + assert.strictEqual(signal(), false); + }); + + test('readiness follows visibility changes at an unchanged size, and observation ends once it was shown', async () => { + const shown = { value: false }; + const { fixture, signal, element, frames } = setup(shown); + fixture.switchTo(); + await frames(3); + assert.strictEqual(signal(), true); + + element.style.visibility = 'hidden'; + fixture.entryVisibilityChanged(); + await frames(3); + assert.strictEqual(signal(), false); + + element.style.visibility = 'visible'; + fixture.partVisibilityChanged(); + await frames(3); + assert.strictEqual(signal(), true); + + // marked as shown while hidden, at an unchanged size: the next event ends the observation + element.style.visibility = 'hidden'; + shown.value = true; + fixture.entryVisibilityChanged(); + await frames(3); + element.style.visibility = 'visible'; + fixture.entryVisibilityChanged(); + await frames(3); + assert.strictEqual(signal(), true); + }); + + test('a re-created entry is found when the status bar resizes', async () => { + const { fixture, signal, element, frames } = setup({ value: false }); + element.remove(); + fixture.switchTo(); + await frames(3); + assert.strictEqual(signal(), false); + + mainWindow.document.body.appendChild(element); + fixture.statusbarContainer.style.width = '40px'; + fixture.statusbarContainer.style.height = '10px'; + await frames(5); + assert.strictEqual(signal(), true); + }); + + test('no frame is requested while idle', async () => { + const { fixture, frames } = setup({ value: false }); + fixture.switchTo(); + await frames(5); + + const original = mainWindow.requestAnimationFrame; + let requested = 0; + mainWindow.requestAnimationFrame = callback => { requested++; return original.call(mainWindow, callback); }; + try { + await new Promise<void>(resolve => setTimeout(resolve, 300)); + } finally { + mainWindow.requestAnimationFrame = original; + } + assert.strictEqual(requested, 0); + }); + + test('no observer when switching again after it was shown', async () => { + const shown = { value: false }; + const { fixture, signal, frames } = setup(shown); + fixture.switchTo(); + await frames(5); + shown.value = true; + fixture.returnToPrimary(); + fixture.switchTo(); + await frames(5); + assert.strictEqual(signal(), false); + }); + }); + + test('return command switches back to the primary location', async () => { + const calls: [URI, string | undefined][] = []; + const workspace = new Workspace('id', [new WorkspaceFolder({ uri: alternate, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + const accessor = { + get: (id: unknown) => id === IWorkspaceContextService ? { getWorkspace: () => workspace } : id === IWorkspaceEditingService ? { setFolderLocation: async (l: URI, o?: { reason?: string }) => { calls.push([l, o?.reason]); } } : id === IWorkspaceFolderLocationService ? identityFake(() => workspace) : id === IUriIdentityService ? { extUri } : undefined + } as unknown as ServicesAccessor; + + await CommandsRegistry.getCommand(RETURN_TO_PRIMARY_FOLDER_LOCATION_COMMAND_ID)!.handler(accessor); + + assert.deepStrictEqual(calls, [[primary, 'user']]); + }); + + suite('switch command', () => { + + async function pickLocation(choose: (items: { label: string; description?: string; iconClass?: string }[]) => number | undefined, switchedWhileOpen?: URI, primaryChangedTo?: URI, atPrimary?: boolean, lookup?: Promise<void>) { + const calls: [string, string | undefined][] = []; + let shown: { label: string; description?: string; iconClass?: string }[] = []; + let activeItem: IQuickPickItem | undefined; + let shownAtAccept: string[] = []; + let firstShown: { items: readonly { label: string }[]; busy: boolean } | undefined; + let workspace = new Workspace('id', [new WorkspaceFolder({ uri: atPrimary ? primary : alternate, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + const accessor = { + get: (id: unknown) => id === IWorkspaceContextService ? { getWorkspace: () => workspace } + : id === IWorkspaceFolderLocationService ? { ...identityFake(() => workspace), getLocation: () => atPrimary ? undefined : { uri: alternate, label: 'Alternate', description: 'feature/x', icon: Codicon.gitBranch }, getLocations: async () => { await lookup; return [{ uri: alternate, label: 'Alternate', description: 'feature/x', icon: Codicon.gitBranch }, { uri: URI.file('/work/other'), label: 'Other' }]; } } + : id === IUriIdentityService ? { extUri } + : id === IQuickInputService ? { + createQuickPick: () => { + const accept = new Emitter<void>(); + const hide = new Emitter<void>(); + const pick = { + items: [] as (IQuickPickItem & { uri: URI })[], activeItems: [] as IQuickPickItem[], selectedItems: [] as IQuickPickItem[], busy: false, placeholder: '', matchOnDescription: false, + onDidAccept: accept.event, onDidHide: hide.event, dispose: () => { }, + show: () => { + firstShown = { items: pick.items, busy: pick.busy }; + const settle = async () => { + await Promise.resolve(); + await new Promise(r => setTimeout(r, 0)); + shownAtAccept = pick.items.map(item => item.label); shown = pick.items; activeItem = pick.activeItems[0]; + const index = choose(pick.items); + if (switchedWhileOpen) { workspace = new Workspace('id', [new WorkspaceFolder({ uri: switchedWhileOpen, name: 'project', index: 0 })], false, null, () => false, undefined, primaryChangedTo ?? primary); } + if (index === undefined) { hide.fire(); } else { pick.selectedItems = [pick.items[index]]; accept.fire(); } + }; + void settle(); + } + }; + return pick; + } + } + : id === IWorkspaceEditingService ? { setFolderLocation: async (l: URI, o?: { reason?: string }) => { calls.push([l.toString(), o?.reason]); } } : undefined + } as unknown as ServicesAccessor; + + await CommandsRegistry.getCommand(SWITCH_FOLDER_LOCATION_COMMAND_ID)!.handler(accessor); + return { shown, calls, activeItem, firstShown, shownAtAccept }; + } + + test('shows the picker at once in a busy state, then lists the primary and the locations with icons next to their labels, marking the current one', async () => { + const { shown, calls, activeItem, firstShown } = await pickLocation(() => undefined); + assert.deepStrictEqual({ labels: firstShown!.items.map(item => item.label), busy: firstShown!.busy }, { labels: ['project', 'Alternate'], busy: true }); + assert.deepStrictEqual({ shown: shown.map(item => ({ ...item, uri: (item as unknown as { uri: URI }).uri.toString() })), active: (activeItem as unknown as { uri: URI }).uri.toString(), calls }, { + shown: [ + { uri: primary.toString(), label: 'project', iconClass: 'codicon codicon-folder', description: 'Primary Location' }, + { uri: alternate.toString(), label: 'Alternate', iconClass: 'codicon codicon-git-branch', description: 'feature/x (Current)' }, + { uri: URI.file('/work/other').toString(), label: 'Other', iconClass: 'codicon codicon-git-branch-checkout', description: undefined } + ], + active: alternate.toString(), + calls: [] + }); + }); + + test('accepting before the locations resolve keeps the current location', async () => { + let release!: () => void; + const lookup = new Promise<void>(resolve => release = resolve); + const early = await pickLocation(items => items.findIndex(item => item.description?.endsWith('(Current)')), undefined, undefined, false, lookup); + release(); + assert.deepStrictEqual({ shownAtAccept: early.shownAtAccept, active: (early.activeItem as unknown as { label: string }).label, calls: early.calls }, { shownAtAccept: ['project', 'Alternate'], active: 'Alternate', calls: [[alternate.toString(), 'user']] }); + }); + + test('hiding before the locations resolve does nothing, a rejected lookup is reported', async () => { + let release!: () => void; + assert.deepStrictEqual((await pickLocation(() => undefined, undefined, undefined, false, new Promise<void>(resolve => release = resolve))).calls, []); + release(); + + const errors: unknown[] = []; + const previous = errorHandler.getUnexpectedErrorHandler(); + errorHandler.setUnexpectedErrorHandler(error => errors.push(error)); + try { + const failure = new Error('lookup failed'); + const rejected = await pickLocation(() => 0, undefined, undefined, false, Promise.reject(failure)); + await new Promise(resolve => setTimeout(resolve, 0)); + assert.deepStrictEqual({ calls: rejected.calls, errors }, { calls: [[primary.toString(), 'user']], errors: [failure] }); + } finally { + errorHandler.setUnexpectedErrorHandler(previous); + } + }); + + test('invoked from the status entry the list is anchored there, starts on the current location and selecting it works', async () => { + const anchor = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + anchor.id = 'status.workspace.folderLocation'; + const label = anchor.appendChild(mainWindow.document.createElement('a')); + label.className = 'statusbar-item-label'; + label.tabIndex = -1; + try { + type Entry = { id: string; label: string; description?: string; checked: boolean }; + type ListItem = { item: Entry; labelIcon: { id: string }; group: { icon: { id: string } } }; + const calls: string[] = []; + const workspace = new Workspace('id', [new WorkspaceFolder({ uri: alternate, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + let shownAnchor: unknown; + let shownOptions: unknown; + let shownItems: ListItem[] = []; + let initiallyFocused: string | undefined; + let aria: ((item: ListItem) => string) | undefined; + let delegate!: { onSelect(item: Entry): void; onHide(): void }; + let release!: () => void; + const lookup = new Promise<void>(resolve => release = resolve); + const widget = { + show: (_user: string, _preview: boolean, items: ListItem[], shownDelegate: typeof delegate, anchorElement: unknown, _container: unknown, _actions: unknown, accessibility: { getAriaLabel(item: ListItem): string }, options: unknown) => { + shownOptions = options; shownAnchor = anchorElement; shownItems = items; delegate = shownDelegate; aria = accessibility.getAriaLabel; + initiallyFocused = items.find(item => item.item.checked)?.item.id; + // like the real widget, selecting an item is followed by a hide that reports it synchronously + queueMicrotask(() => delegate.onSelect(items.find(item => item.item.id === initiallyFocused)!.item)); + }, + focusItemById: () => { }, + updateItems: () => { }, + hide: () => delegate.onHide() + }; + const accessor = { + get: (id: unknown) => id === IWorkspaceContextService ? { getWorkspace: () => workspace } + : id === IWorkspaceFolderLocationService ? { ...identityFake(() => workspace), getLocation: () => ({ uri: alternate, label: 'Alternate', description: 'feature/x', icon: Codicon.gitBranchCheckout }), getLocations: async () => { await lookup; return []; } } + : id === IUriIdentityService ? { extUri } + : id === IActionWidgetService ? widget + : id === IWorkspaceEditingService ? { setFolderLocation: async (l: URI) => { calls.push(l.toString()); } } : undefined + } as unknown as ServicesAccessor; + await CommandsRegistry.getCommand(SWITCH_FOLDER_LOCATION_COMMAND_ID)!.handler(accessor, 'status.workspace.folderLocation'); + release(); + assert.deepStrictEqual({ + anchored: shownAnchor === anchor, + options: shownOptions, + items: shownItems.map(item => ({ id: item.item.id, aria: aria!(item), icon: item.labelIcon.id, check: item.group.icon.id })), + initiallyFocused, + calls, + focusReturnedToLabel: mainWindow.document.activeElement === label + }, { + anchored: true, + options: { preferredAnchorPosition: AnchorPosition.ABOVE, inlineDescription: true }, + items: [ + { id: extUri.getComparisonKey(primary), aria: 'project, Primary Location', icon: 'folder', check: 'blank' }, + { id: extUri.getComparisonKey(alternate), aria: 'Alternate, feature/x, Current', icon: 'git-branch-checkout', check: 'check' } + ], + initiallyFocused: extUri.getComparisonKey(alternate), + calls: [alternate.toString()], + focusReturnedToLabel: true + }); + } finally { + anchor.remove(); + } + }); + + test('picking a location switches to it as a user choice, the primary returns, the current one is submitted', async () => { + assert.deepStrictEqual((await pickLocation(() => 2)).calls, [[URI.file('/work/other').toString(), 'user']]); + assert.deepStrictEqual((await pickLocation(() => 0)).calls, [[primary.toString(), 'user']]); + // the current location is submitted too, so that it supersedes a different switch that is still pending + assert.deepStrictEqual((await pickLocation(() => 1)).calls, [[alternate.toString(), 'user']]); + }); + + test('at the primary location the picker lists the locations, marks the primary and switches as a user choice', async () => { + const atPrimaryPick = await pickLocation(items => { assert.deepStrictEqual(items.map(item => item.description), ['Primary Location (Current)', 'feature/x', undefined]); return 1; }, undefined, undefined, true); + assert.deepStrictEqual(atPrimaryPick.calls, [[alternate.toString(), 'user']]); + }); + + test('a switch while the picker is open does not drop the user choice', async () => { + const other = URI.file('/work/other'); + // current location (alternate) is picked after another switch moved the folder to `other` + assert.deepStrictEqual((await pickLocation(() => 1, other)).calls, [[alternate.toString(), 'user']]); + // picking the location the folder moved to is submitted as well + assert.deepStrictEqual((await pickLocation(() => 2, other)).calls, [[other.toString(), 'user']]); + // a picker opened for a primary that has since changed is stale + assert.deepStrictEqual((await pickLocation(() => 1, other, URI.file('/work/changed'))).calls, []); + }); + }); +}); diff --git a/src/vs/workbench/contrib/workspaces/test/browser/folderLocationWorkingSets.test.ts b/src/vs/workbench/contrib/workspaces/test/browser/folderLocationWorkingSets.test.ts new file mode 100644 index 000000000000..d58e19e7a2b4 --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/test/browser/folderLocationWorkingSets.test.ts @@ -0,0 +1,775 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mainWindow } from '../../../../../base/browser/window.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { VSBuffer, bufferToReadable } from '../../../../../base/common/buffer.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { extUriIgnorePathCase } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { MockScopableContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { InMemoryStorageService, IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IWorkspaceFolderLocationService } from '../../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { EditorExtensions, EditorsOrder, IEditorFactoryRegistry } from '../../../../common/editor.js'; +import { DiffEditorInput } from '../../../../common/editor/diffEditorInput.js'; +import { IAuxiliaryWindowService } from '../../../../services/auxiliaryWindow/browser/auxiliaryWindowService.js'; +import { EditorService } from '../../../../services/editor/browser/editorService.js'; +import { IEditorGroupsService, IEditorWorkingSet } from '../../../../services/editor/common/editorGroupsService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { UntitledTextEditorInput } from '../../../../services/untitled/common/untitledTextEditorInput.js'; +import { IUntitledTextEditorService } from '../../../../services/untitled/common/untitledTextEditorService.js'; +import { IResolvedWorkingCopyBackup, IWorkingCopyBackupService } from '../../../../services/workingCopy/common/workingCopyBackup.js'; +import { IWorkingCopyBackupMeta, IWorkingCopyIdentifier } from '../../../../services/workingCopy/common/workingCopy.js'; +import { IWorkingCopyService } from '../../../../services/workingCopy/common/workingCopyService.js'; +import { createEditorParts, TestFileEditorInput, TestWorkingCopyBackupService, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { FOLDER_LOCATION_MAX_WORKING_SETS, FOLDER_LOCATION_WORKING_SET_NAME_PREFIX, FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, FolderLocationWorkingSetsContribution } from '../../browser/folderLocationWorkingSets.js'; + +suite('FolderLocationWorkingSetsContribution', () => { + + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + const primary = URI.file('/work/project'); + const alternate = URI.file('/work/project-alt'); + + const prefix = FOLDER_LOCATION_WORKING_SET_NAME_PREFIX; + + /** The editors of a fake editor area, and the working sets saved from it. */ + class EditorArea { + content = ''; + counter = 0; + readonly sets = new Map<string, { name: string; content: string }>(); + applyResult: boolean | 'throw' = true; + /** When set, only applying a saved working set fails: applying an empty editor area works. */ + emptyAlwaysWorks = false; + /** When set, a failing apply first leaves this content behind, like closing some editors before an editor vetoes. */ + contentOnFailure: string | undefined; + gate: Promise<void> | undefined; + auxiliaryEditors = 0; + /** The editors of the main part, for the backup checks. */ + editors: { resource: URI; dirty?: boolean }[] = []; + backups: IWorkingCopyIdentifier[] = []; + backupsGate: Promise<void> | undefined; + + saved(): Record<string, string> { + return Object.fromEntries([...this.sets.values()].map(set => [set.name, set.content])); + } + } + + function createFixture(options?: { area?: EditorArea; storage?: InMemoryStorageService; folder?: URI; otherFolders?: URI[]; whenRestored?: Promise<void> }) { + const errors: string[] = []; + const infos: string[] = []; + const onDidChangeCurrentLocation = ds.add(new Emitter<{ readonly reason: 'user' | 'programmatic' }>()); + const onDidChangeDirty = ds.add(new Emitter<{ resource: URI }>()); + const storage = options?.storage ?? ds.add(new InMemoryStorageService()); + const area = options?.area ?? new EditorArea(); + let folderUri = options?.folder ?? primary; + const otherFolders = options?.otherFolders ?? []; + + const editorGroupsService = { + whenRestored: options?.whenRestored ?? Promise.resolve(), + parts: [ + { get groups() { return [{ count: area.content ? 1 : 0, editors: area.editors.map(editor => ({ resource: editor.resource, isDirty: () => !!editor.dirty, isSaving: () => false })) }]; } }, + { get groups() { return [{ count: area.auxiliaryEditors, editors: [] }]; } }, + { isTransient: true, groups: [{ count: 5, editors: [] }] } + ], + saveWorkingSet: (name: string): IEditorWorkingSet => { const id = `set-${++area.counter}`; area.sets.set(id, { name, content: area.content }); return { id, name }; }, + getWorkingSets: () => [...area.sets].map(([id, set]) => ({ id, name: set.name })), + deleteWorkingSet: (ws: IEditorWorkingSet) => { area.sets.delete(ws.id); }, + applyWorkingSet: async (ws: IEditorWorkingSet | 'empty', applyOptions?: { preserveFocus?: boolean }) => { + assert.strictEqual(applyOptions?.preserveFocus, true); + await area.gate; + const result = area.emptyAlwaysWorks && ws === 'empty' ? true : area.applyResult; + if (result !== true && area.contentOnFailure !== undefined) { + area.content = area.contentOnFailure; + } + if (result === 'throw') { + throw new Error('apply failed'); + } + if (result) { + area.content = ws === 'empty' ? '' : area.sets.get(ws.id)!.content; + } + return result === true; + } + } as unknown as IEditorGroupsService; + + const contribution = ds.add(new FolderLocationWorkingSetsContribution( + { onDidChangeLocation: onDidChangeCurrentLocation.event, onDidChangeCanSetLocation: Event.None, canSetLocation: () => otherFolders.length === 0 } as unknown as IWorkspaceFolderLocationService, + { getWorkspace: () => new Workspace('id', [folderUri, ...otherFolders].map((uri, index) => new WorkspaceFolder({ uri, name: `folder-${index}`, index })), false, null, () => false) } as unknown as IWorkspaceContextService, + editorGroupsService, + storage as unknown as IStorageService, + { asCanonicalUri: (uri: URI) => uri, extUri: extUriIgnorePathCase } as unknown as IUriIdentityService, + { error: (message: string) => errors.push(message), info: (message: string) => infos.push(message) } as unknown as ILogService, + { getBackups: async () => { await area.backupsGate; return area.backups; } } as unknown as IWorkingCopyBackupService, + { onDidChangeDirty: onDidChangeDirty.event, onDidUnregister: Event.None } as unknown as IWorkingCopyService, + { onDidEditorsChange: Event.None } as unknown as IEditorService + )); + + return { + area, errors, infos, storage, contribution, + switchTo(uri: URI, reason: 'user' | 'programmatic' = 'programmatic') { folderUri = uri; onDidChangeCurrentLocation.fire({ reason }); }, + restoreBackup(resource: URI) { area.editors = area.editors.map(editor => editor.resource.toString() === resource.toString() ? { ...editor, dirty: true } : editor); onDidChangeDirty.fire({ resource }); }, + holdApply() { let release!: () => void; area.gate = new Promise<void>(resolve => release = resolve); return () => { area.gate = undefined; release(); }; }, + stored() { return JSON.parse(storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE)!); } + }; + } + + const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0)); + const p = primary.toString(); + const a = alternate.toString(); + + test('the editors of each location are saved when leaving it and restored when returning, for user and programmatic switches', async () => { + const fixture = createFixture(); + fixture.area.content = 'P1'; + + fixture.switchTo(alternate, 'user'); + await settle(); + const firstVisit = fixture.area.content; + fixture.area.content = 'A1'; + fixture.switchTo(primary, 'programmatic'); + await settle(); + const backAtPrimary = fixture.area.content; + fixture.area.content = 'P2'; + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ firstVisit, backAtPrimary, backAtAlternate: fixture.area.content, saved: fixture.area.saved() }, { + firstVisit: '', + backAtPrimary: 'P1', + backAtAlternate: 'A1', + saved: { [prefix + a]: 'A1', [prefix + p]: 'P2' } + }); + }); + + test('an empty editor area saves nothing', async () => { + const fixture = createFixture(); + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual(fixture.area.saved(), {}); + }); + + test('editors that are only in another window are saved', async () => { + const fixture = createFixture(); + fixture.area.auxiliaryEditors = 1; + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual(Object.keys(fixture.area.saved()), [prefix + p]); + }); + + test('returning to the oldest location at capacity keeps its working set', async () => { + const fixture = createFixture(); + fixture.area.content = 'P'; + for (let i = 0; i < FOLDER_LOCATION_MAX_WORKING_SETS; i++) { + fixture.switchTo(URI.file(`/work/alt-${i}`)); + await settle(); + fixture.area.content = `alt-${i}`; + } + + fixture.switchTo(primary); + await settle(); + + assert.deepStrictEqual({ content: fixture.area.content, sets: fixture.area.sets.size }, { content: 'P', sets: FOLDER_LOCATION_MAX_WORKING_SETS }); + }); + + test('queued switches do not run once the contribution is disposed', async () => { + const fixture = createFixture(); + fixture.area.content = 'P'; + const release = fixture.holdApply(); + fixture.switchTo(alternate); + await settle(); + fixture.switchTo(primary); + fixture.contribution.dispose(); + release(); + await settle(); + + assert.deepStrictEqual({ content: fixture.area.content, saved: fixture.area.saved() }, { content: '', saved: { [prefix + p]: 'P' } }); + }); + + test('a quick back and forth leaves the last location with its editors', async () => { + const fixture = createFixture(); + fixture.area.content = 'P'; + fixture.switchTo(alternate); + fixture.switchTo(primary); + await settle(); + + assert.strictEqual(fixture.area.content, 'P'); + }); + + test('a location that stays the same, also one whose metadata changes, switches nothing', async () => { + const fixture = createFixture(); + fixture.area.content = 'P'; + fixture.switchTo(primary); + await settle(); + + assert.deepStrictEqual({ content: fixture.area.content, saved: fixture.area.saved() }, { content: 'P', saved: {} }); + }); + + test('a saved working set that cannot be applied leaves the location empty instead of with the editors of the previous one, which stay restorable', async () => { + for (const failure of [false, 'throw'] as const) { + const fixture = createFixture(); + fixture.area.content = 'P1'; + fixture.switchTo(alternate); + await settle(); + fixture.area.content = 'A1'; + + fixture.area.applyResult = failure; + fixture.area.emptyAlwaysWorks = true; + fixture.switchTo(primary); + await settle(); + const afterFailure = { content: fixture.area.content, saved: fixture.area.saved(), owner: fixture.stored().owner, errors: fixture.errors.length }; + + fixture.area.applyResult = true; + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ afterFailure, content: fixture.area.content, saved: fixture.area.saved(), owner: fixture.stored().owner }, { + afterFailure: { content: '', saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' }, owner: p, errors: 1 }, + content: 'A1', + saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' }, + owner: a + }, `${failure}`); + } + }); + + test('the saved working set of a location that failed to apply is kept until the location is left with editors open, which replaces it', async () => { + const fixture = createFixture(); + fixture.area.content = 'P1'; + fixture.switchTo(alternate); + await settle(); + fixture.area.content = 'A1'; + + fixture.area.applyResult = 'throw'; + fixture.area.emptyAlwaysWorks = true; + fixture.switchTo(primary); + await settle(); + const kept = fixture.area.saved(); + + fixture.area.applyResult = true; + fixture.area.content = 'P2'; + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ kept, replaced: fixture.area.saved(), content: fixture.area.content }, { + kept: { [prefix + p]: 'P1', [prefix + a]: 'A1' }, + replaced: { [prefix + p]: 'P2', [prefix + a]: 'A1' }, + content: 'A1' + }); + }); + + test('a partially applied working set never replaces the saved one of the owner, also after a restart', async () => { + for (const failure of [false, 'throw'] as const) { + const storage = ds.add(new InMemoryStorageService()); + const area = new EditorArea(); + const fixture = createFixture({ area, storage }); + area.content = 'P1'; + fixture.switchTo(alternate); + await settle(); + area.content = 'A1'; + + area.applyResult = failure; + area.contentOnFailure = 'PARTIAL'; + fixture.switchTo(primary); + await settle(); + const afterFailure = { content: area.content, saved: area.saved() }; + + area.applyResult = true; + fixture.switchTo(URI.file('/work/other')); + await settle(); + const afterNextSwitch = { content: area.content, saved: area.saved() }; + + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ afterFailure, afterNextSwitch, content: area.content, saved: area.saved() }, { + afterFailure: { content: 'PARTIAL', saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' } }, + afterNextSwitch: { content: '', saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' } }, + content: 'A1', + saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' } + }, `${failure}`); + } + }); + + test('a window that starts with a partially applied editor area restores the saved working set of its location', async () => { + const storage = ds.add(new InMemoryStorageService()); + const area = new EditorArea(); + const first = createFixture({ area, storage }); + area.content = 'P1'; + first.switchTo(alternate); + await settle(); + area.content = 'A1'; + area.applyResult = false; + area.contentOnFailure = 'PARTIAL'; + first.switchTo(primary); + await settle(); + + area.applyResult = true; + createFixture({ area, storage, folder: alternate }); + await settle(); + + assert.deepStrictEqual({ content: area.content, saved: area.saved() }, { content: 'A1', saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' } }); + }); + + test('when the empty fallback fails as well, the owner stays and the saved working sets survive, also over later switches', async () => { + for (const failure of [false, 'throw'] as const) { + const fixture = createFixture(); + fixture.area.content = 'P1'; + fixture.switchTo(alternate); + await settle(); + fixture.area.content = 'A1'; + fixture.switchTo(primary); + await settle(); + fixture.area.content = 'P1'; + + fixture.area.applyResult = failure; + fixture.switchTo(alternate); + await settle(); + const afterFailure = { content: fixture.area.content, saved: fixture.area.saved(), errors: fixture.errors.length, owner: fixture.stored().owner }; + + fixture.area.applyResult = true; + fixture.switchTo(URI.file('/work/other')); + await settle(); + + assert.deepStrictEqual({ afterFailure, afterNextSwitch: fixture.area.saved() }, { + afterFailure: { content: 'P1', saved: { [prefix + a]: 'A1', [prefix + p]: 'P1' }, errors: 2, owner: p }, + afterNextSwitch: { [prefix + a]: 'A1', [prefix + p]: 'P1' } + }, `${failure}`); + } + }); + + test('switching to another location and back while the first apply is pending restores the editors of the original location', async () => { + const fixture = createFixture(); + fixture.area.content = 'P1'; + + const release = fixture.holdApply(); + fixture.switchTo(alternate); + await settle(); + fixture.switchTo(primary); + await settle(); + release(); + await settle(); + + assert.deepStrictEqual({ content: fixture.area.content, owner: fixture.stored().owner, errors: fixture.errors }, { content: 'P1', owner: p, errors: [] }); + }); + + test('a window that starts at another location than the one it was closed at swaps the editors of the last session out', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.content = 'A1'; + + // The alternate location is gone: the window starts at the primary with the editors of the alternate + const restarted = createFixture({ area: first.area, storage: first.storage, folder: primary }); + await settle(); + const afterStartup = { content: restarted.area.content, saved: restarted.area.saved(), owner: restarted.stored().owner }; + + restarted.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ afterStartup, content: restarted.area.content, saved: restarted.area.saved() }, { + afterStartup: { content: 'P1', saved: { [prefix + a]: 'A1', [prefix + p]: 'P1' }, owner: p }, + content: 'A1', + saved: { [prefix + a]: 'A1', [prefix + p]: 'P1' } + }); + }); + + test('a window that starts at the location it was closed at keeps its editors', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.content = 'A-edited'; + + const restarted = createFixture({ area: first.area, storage: first.storage, folder: alternate }); + await settle(); + + assert.deepStrictEqual({ content: restarted.area.content, saved: restarted.area.saved() }, { content: 'A-edited', saved: { [prefix + p]: 'P1' } }); + }); + + test('working sets that were saved but never stored are deleted on startup, the ones of others and of the mapping are kept', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.sets.set('orphan', { name: prefix + '/work/crashed', content: 'x' }); + first.area.sets.set('foreign', { name: 'scm-branch', content: 'y' }); + + const restarted = createFixture({ area: first.area, storage: first.storage, folder: alternate }); + await settle(); + + assert.deepStrictEqual(Object.keys(restarted.area.saved()).sort(), [prefix + p, 'scm-branch']); + }); + + test('handles of deleted working sets are dropped on load', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.sets.clear(); + + const restarted = createFixture({ area: first.area, storage: first.storage, folder: alternate }); + restarted.switchTo(primary); + await settle(); + + assert.deepStrictEqual({ content: restarted.area.content, stored: restarted.stored().entries.length }, { content: '', stored: 0 }); + }); + + test('the number of stored working sets is capped', async () => { + const fixture = createFixture(); + fixture.area.content = 'P'; + for (let i = 0; i <= FOLDER_LOCATION_MAX_WORKING_SETS; i++) { + fixture.switchTo(URI.file(`/work/alt-${i}`)); + await settle(); + fixture.area.content = `alt-${i}`; + } + + assert.strictEqual(fixture.area.sets.size, FOLDER_LOCATION_MAX_WORKING_SETS); + }); + + test('nothing is switched before the editors are restored, also not a location change that comes in meanwhile', async () => { + let restored!: () => void; + const fixture = createFixture({ whenRestored: new Promise<void>(resolve => restored = resolve) }); + fixture.area.content = 'P'; + fixture.switchTo(alternate); + await settle(); + const beforeRestored = { content: fixture.area.content, saved: fixture.area.saved() }; + + restored(); + await settle(); + + assert.deepStrictEqual({ beforeRestored, content: fixture.area.content, saved: fixture.area.saved() }, { + beforeRestored: { content: 'P', saved: {} }, + content: '', + saved: { [prefix + p]: 'P' } + }); + }); + + test('a switch is deferred while an editor that would close has a backup that is not restored yet, and happens once it is', async () => { + const untitled = URI.from({ scheme: 'untitled', path: 'Untitled-1' }); + const results: Record<string, string> = {}; + for (const [name, editor, backup] of [['unrestored backup', { resource: untitled }, true], ['dirty editor', { resource: untitled, dirty: true }, true], ['no backup', { resource: untitled }, false]] as const) { + const fixture = createFixture(); + fixture.area.content = 'P'; + fixture.area.editors = [editor]; + fixture.area.backups = backup ? [{ resource: untitled, typeId: '' }] : []; + await settle(); + fixture.switchTo(alternate); + await settle(); + results[name] = fixture.area.content; + if (name === 'unrestored backup') { + results.stored = String(fixture.storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE)); + results.infos = String(fixture.infos.length); + fixture.restoreBackup(untitled); + await settle(); + results.afterRestored = fixture.area.content; + } + } + + assert.deepStrictEqual(results, { 'unrestored backup': 'P', stored: 'undefined', infos: '1', afterRestored: '', 'dirty editor': '', 'no backup': '' }); + }); + + test('an editor whose backup is restored while the backups are queried does not keep the switch deferred', async () => { + const untitled = URI.from({ scheme: 'untitled', path: 'Untitled-1' }); + const fixture = createFixture(); + fixture.area.content = 'P'; + fixture.area.editors = [{ resource: untitled }]; + fixture.area.backups = [{ resource: untitled, typeId: '' }]; + await settle(); + + let release!: () => void; + fixture.area.backupsGate = new Promise<void>(resolve => release = resolve); + fixture.switchTo(alternate); + await settle(); + fixture.restoreBackup(untitled); + release(); + await settle(); + + assert.deepStrictEqual({ content: fixture.area.content, saved: fixture.area.saved() }, { content: '', saved: { [prefix + p]: 'P' } }); + }); + + test('stored locations that only differ in the casing of their path are the same location', async () => { + const storage = ds.add(new InMemoryStorageService()); + const area = new EditorArea(); + area.sets.set('legacy', { name: prefix + 'file:///work/Project-Alt', content: 'A1' }); + storage.store(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, JSON.stringify({ version: 1, owner: 'file:///work/Project', entries: [{ key: 'file:///work/Project-Alt', workingSet: { id: 'legacy', name: prefix + 'file:///work/Project-Alt' } }] }), StorageScope.WORKSPACE, StorageTarget.MACHINE); + area.content = 'P1'; + + const fixture = createFixture({ area, storage, folder: primary }); + await settle(); + const afterStartup = area.content; + + fixture.switchTo(alternate); + await settle(); + + assert.deepStrictEqual({ afterStartup, content: area.content }, { afterStartup: 'P1', content: 'A1' }); + }); + + test('a workspace with more than one folder switches and saves nothing and keeps the stored working sets', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.content = 'M'; + const stored = first.storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE); + + const multiRoot = createFixture({ area: first.area, storage: first.storage, folder: primary, otherFolders: [URI.file('/work/other')] }); + await settle(); + multiRoot.switchTo(URI.file('/work/third')); + await settle(); + + assert.deepStrictEqual({ content: multiRoot.area.content, saved: multiRoot.area.saved(), unchanged: multiRoot.storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE) === stored }, { + content: 'M', + saved: { [prefix + p]: 'P1' }, + unchanged: true + }); + }); + + test('the editor area is stored as partial while a working set is applied, so that a restart during the apply restores the saved working set of the owner', async () => { + const first = createFixture(); + first.area.content = 'P1'; + first.switchTo(alternate); + await settle(); + first.area.content = 'A1'; + first.switchTo(primary); + await settle(); + + first.holdApply(); + first.switchTo(alternate); + await settle(); + const duringApply = { partial: first.stored().partial, owner: first.stored().owner }; + + // The apply replaced the editors before the window restarted + first.area.content = 'A-PARTIAL'; + first.area.gate = undefined; + const restarted = createFixture({ area: first.area, storage: first.storage, folder: primary }); + await settle(); + + assert.deepStrictEqual({ duringApply, content: restarted.area.content, saved: restarted.area.saved(), partial: restarted.stored().partial }, { + duringApply: { partial: true, owner: p }, + content: 'P1', + saved: { [prefix + p]: 'P1', [prefix + a]: 'A1' }, + partial: undefined + }); + }); +}); + +suite('FolderLocationWorkingSetsContribution with the editor parts', () => { + + const alternateKey = URI.file('/work/project-alt').toString(); + + const disposables = new DisposableStore(); + + teardown(() => { + disposables.clear(); + }); + + ensureNoDisposablesAreLeakedInTestSuite(); + + class HeldWorkingCopyBackupService extends TestWorkingCopyBackupService { + gate: Promise<void> | undefined; + + override async resolve<T extends IWorkingCopyBackupMeta>(identifier: IWorkingCopyIdentifier): Promise<IResolvedWorkingCopyBackup<T> | undefined> { + await this.gate; + return super.resolve<T>(identifier); + } + } + + /** A file editor whose save is running and can fail, which only its editor reports, not its working copy. */ + class SavingFileEditorInput extends TestFileEditorInput { + saving = true; + + override isSaving(): boolean { + return this.saving; + } + + failSave(): void { + this.saving = false; + this._onDidChangeDirty.fire(); + } + } + + /** + * Switches the location while the backup of an untitled editor, which is only in an inactive tab of its own, + * or of a diff editor as its modified or its original side, is being restored. + */ + async function createWorkbench() { + const backupService = disposables.add(new HeldWorkingCopyBackupService()); + const instantiationService = workbenchInstantiationService({ contextKeyService: instantiationService => instantiationService.createInstance(MockScopableContextKeyService), workingCopyBackupService: () => backupService }, disposables); + instantiationService.invokeFunction(accessor => Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).start(accessor)); + instantiationService.stub(IAuxiliaryWindowService, new class extends mock<IAuxiliaryWindowService>() { override getWindow() { return undefined; } }()); + const parts = await createEditorParts(instantiationService, disposables); + instantiationService.stub(IEditorGroupsService, parts); + const editorService = disposables.add(instantiationService.createInstance(EditorService, undefined)); + instantiationService.stub(IEditorService, editorService); + const container = parts.testMainPart.getContainer()!; + mainWindow.document.body.appendChild(container); + disposables.add({ dispose: () => container.remove() }); + const storage = instantiationService.invokeFunction(accessor => accessor.get(IStorageService)); + const owner = (): string | undefined => JSON.parse(storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE) ?? '{}').owner; + + /** Starts the contribution at the primary location and returns a function that switches to the alternate one. */ + const startAtPrimary = () => { + let folder = URI.file('/work/project'); + const onDidChangeLocation = disposables.add(new Emitter<{ readonly reason: 'user' | 'programmatic' }>()); + disposables.add(instantiationService.invokeFunction(accessor => new FolderLocationWorkingSetsContribution( + { onDidChangeLocation: onDidChangeLocation.event, onDidChangeCanSetLocation: Event.None, canSetLocation: () => true } as unknown as IWorkspaceFolderLocationService, + { getWorkspace: () => new Workspace('id', [new WorkspaceFolder({ uri: folder, name: 'project', index: 0 })], false, null, () => false) } as unknown as IWorkspaceContextService, + parts, + storage, + accessor.get(IUriIdentityService), + accessor.get(ILogService), + backupService, + accessor.get(IWorkingCopyService), + editorService + ))); + return () => { + folder = URI.file('/work/project-alt'); + onDidChangeLocation.fire({ reason: 'programmatic' }); + }; + }; + + return { backupService, instantiationService, parts, storage, owner, startAtPrimary }; + } + + async function switchWhileRestoring(tab: 'untitled' | 'diff' | 'diffOriginal') { + const { backupService, instantiationService, parts, storage, owner, startAtPrimary } = await createWorkbench(); + + // Restored inactive: the working copy of the untitled editor is registered and clean while its backup resolves + const model = disposables.add(instantiationService.invokeFunction(accessor => accessor.get(IUntitledTextEditorService)).create()); + const identifier = { resource: model.resource, typeId: model.typeId }; + await backupService.backup(identifier, bufferToReadable(VSBuffer.fromString('backed up'))); + let release!: () => void; + backupService.gate = new Promise<void>(resolve => release = resolve); + const untitled = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, model)); + const active = disposables.add(new TestFileEditorInput(URI.file('/work/project/active.txt'), 'testTypeId')); + const file = disposables.add(new TestFileEditorInput(URI.file('/work/project/file.txt'), 'testTypeId')); + const inactive = tab === 'diff' ? disposables.add(instantiationService.createInstance(DiffEditorInput, undefined, undefined, file, untitled, undefined)) + : tab === 'diffOriginal' ? disposables.add(instantiationService.createInstance(DiffEditorInput, undefined, undefined, untitled, file, undefined)) + : untitled; + const group = parts.testMainPart.activeGroup; + await group.openEditor(active, { pinned: true }); + await group.openEditor(inactive, { pinned: true, inactive: true }); + const resolving = untitled.resolve(); + await parts.whenRestored; + + const switchToAlternate = startAtPrimary(); + + const editors = () => group.getEditors(EditorsOrder.SEQUENTIAL).map(editor => editor === inactive ? tab : editor === active ? 'active' : 'other'); + // The entering location only becomes the owner once its editors are applied + const switched = Event.toPromise(Event.filter(storage.onDidChangeValue(StorageScope.WORKSPACE, FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, disposables), () => JSON.parse(storage.get(FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, StorageScope.WORKSPACE)!).owner === alternateKey), disposables); + switchToAlternate(); + await timeout(50); + const whileRestoring = { editors: editors(), disposed: untitled.isDisposed(), dirty: untitled.isDirty(), backup: backupService.hasBackupSync(identifier) }; + + release(); + if (tab === 'diffOriginal') { + // The diff closes while its original side is dirty: nothing switches, so wait for the retry the restore triggers + const restored = Event.toPromise(instantiationService.invokeFunction(accessor => accessor.get(IWorkingCopyService)).onDidChangeDirty, disposables); + await resolving; + await restored; + await timeout(50); + } else { + await resolving; + await switched; + } + + return { whileRestoring, editors: editors(), disposed: untitled.isDisposed(), dirty: untitled.isDirty(), content: model.textEditorModel?.getValue(), backup: backupService.hasBackupSync(identifier), owner: owner() }; + } + + test('an inactive untitled editor whose backup is still being restored is neither closed nor discarded by a switch, and travels along once it is restored', async () => { + assert.deepStrictEqual(await switchWhileRestoring('untitled'), { + whileRestoring: { editors: ['active', 'untitled'], disposed: false, dirty: false, backup: true }, + editors: ['untitled'], + disposed: false, + dirty: true, + content: 'backed up', + backup: true, + owner: alternateKey + }); + }); + + test('an inactive diff editor whose original side is an untitled editor with a backup keeps a switch deferred while it is restored and once it is dirty, since closing the diff would dispose it', async () => { + assert.deepStrictEqual(await switchWhileRestoring('diffOriginal'), { + whileRestoring: { editors: ['active', 'diffOriginal'], disposed: false, dirty: false, backup: true }, + editors: ['active', 'diffOriginal'], + disposed: false, + dirty: true, + content: 'backed up', + backup: true, + owner: undefined + }); + }); + + test('an inactive diff editor whose original side is dirty keeps a switch deferred, since closing the diff would dispose it', async () => { + const { instantiationService, parts, owner, startAtPrimary } = await createWorkbench(); + const model = disposables.add(instantiationService.invokeFunction(accessor => accessor.get(IUntitledTextEditorService)).create({ initialValue: 'unsaved' })); + const untitled = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, model)); + await untitled.resolve(); + const active = disposables.add(new TestFileEditorInput(URI.file('/work/project/active.txt'), 'testTypeId')); + const file = disposables.add(new TestFileEditorInput(URI.file('/work/project/file.txt'), 'testTypeId')); + const diff = disposables.add(instantiationService.createInstance(DiffEditorInput, undefined, undefined, untitled, file, undefined)); + const group = parts.testMainPart.activeGroup; + await group.openEditor(active, { pinned: true }); + await group.openEditor(diff, { pinned: true, inactive: true }); + await parts.whenRestored; + + startAtPrimary()(); + await timeout(50); + + assert.deepStrictEqual({ editors: group.count, diffDirty: diff.isDirty(), disposed: untitled.isDisposed(), dirty: untitled.isDirty(), content: model.textEditorModel?.getValue(), owner: owner() }, { + editors: 2, diffDirty: false, disposed: false, dirty: true, content: 'unsaved', owner: undefined + }); + }); + + test('a switch deferred by a closing diff editor whose dirty modified side is saving proceeds when the save fails, and the diff travels along', async () => { + const { instantiationService, parts, storage, owner, startAtPrimary } = await createWorkbench(); + const active = disposables.add(new TestFileEditorInput(URI.file('/work/project/active.txt'), 'testTypeId')); + const original = disposables.add(new TestFileEditorInput(URI.file('/work/project/original.txt'), 'testTypeId')); + const modified = disposables.add(new SavingFileEditorInput(URI.file('/work/project/modified.txt'), 'testTypeId')); + modified.setDirty(); + const diff = disposables.add(instantiationService.createInstance(DiffEditorInput, undefined, undefined, original, modified, undefined)); + const group = parts.testMainPart.activeGroup; + await group.openEditor(active, { pinned: true }); + await group.openEditor(diff, { pinned: true, inactive: true }); + await parts.whenRestored; + + const switched = Event.toPromise(Event.filter(storage.onDidChangeValue(StorageScope.WORKSPACE, FOLDER_LOCATION_WORKING_SETS_STORAGE_KEY, disposables), () => owner() === alternateKey), disposables); + startAtPrimary()(); + await timeout(50); + const whileSaving = { editors: group.count, owner: owner() }; + + modified.failSave(); + await switched; + + assert.deepStrictEqual({ whileSaving, editors: group.getEditors(EditorsOrder.SEQUENTIAL).map(editor => editor === diff ? 'diff' : 'other'), dirty: modified.isDirty(), disposed: [diff.isDisposed(), modified.isDisposed()], owner: owner() }, { + whileSaving: { editors: 2, owner: undefined }, + editors: ['diff'], + dirty: true, + disposed: [false, false], + owner: alternateKey + }); + }); + + test('an inactive diff editor whose modified side is an untitled editor with a backup that is still being restored is not closed by a switch, and travels along once it is restored', async () => { + assert.deepStrictEqual(await switchWhileRestoring('diff'), { + whileRestoring: { editors: ['active', 'diff'], disposed: false, dirty: false, backup: true }, + editors: ['diff'], + disposed: false, + dirty: true, + content: 'backed up', + backup: true, + owner: alternateKey + }); + }); +}); diff --git a/src/vs/workbench/contrib/workspaces/test/electron-browser/folderLocationPersistence.test.ts b/src/vs/workbench/contrib/workspaces/test/electron-browser/folderLocationPersistence.test.ts new file mode 100644 index 000000000000..1a4ec28f5124 --- /dev/null +++ b/src/vs/workbench/contrib/workspaces/test/electron-browser/folderLocationPersistence.test.ts @@ -0,0 +1,310 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { extUri } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; +import { INativeHostService } from '../../../../../platform/native/common/native.js'; +import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; +import { IWindowFolderLocation } from '../../../../../platform/window/common/window.js'; +import { IResolvedFolderLocation, IWorkspaceFolderLocationService } from '../../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { INativeWorkbenchEnvironmentService } from '../../../../services/environment/electron-browser/environmentService.js'; +import { IWorkspaceEditingService } from '../../../../services/workspaces/common/workspaceEditing.js'; +import { FOLDER_LOCATION_RESTORE_TIMEOUT, FolderLocationPersistenceContribution } from '../../electron-browser/folderLocationPersistence.js'; + +suite('FolderLocationPersistenceContribution', () => { + + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + const primary = URI.file('/work/project'); + const alternate = URI.file('/work/project-alt'); + const resolvedLocation: IResolvedFolderLocation = { uri: alternate, label: 'Alternate', providerId: 'test', builtIn: true }; + const persisted: IWindowFolderLocation = { uri: alternate.toString(), label: 'Alternate', providerId: 'test' }; + + interface IFixtureOptions { + readonly persisted?: IWindowFolderLocation; + readonly folderUri?: URI; + readonly providerAvailable?: boolean; + readonly folderLocationMissing?: { readonly label: string }; + readonly resolveLocation?: () => Promise<IResolvedFolderLocation | undefined>; + readonly multiRoot?: boolean; + readonly confirmed?: IResolvedFolderLocation; + readonly setFolderLocation?: (location: URI, options?: { readonly ifIdle?: boolean }) => Promise<void>; + } + + function createFixture(options: IFixtureOptions) { + const persistedCalls: (IWindowFolderLocation | undefined)[] = []; + const notifications: string[] = []; + const notificationIds: (string | undefined)[] = []; + const errors: string[] = []; + const returns: URI[] = []; + const prompts: { readonly choices: string[]; run(): Promise<void>; closed(): boolean }[] = []; + const onDidChangeProviders = ds.add(new Emitter<void>()); + const onDidChangeWorkbenchState = ds.add(new Emitter<void>()); + const onDidChangeWorkspaceFolders = ds.add(new Emitter<void>()); + const onDidChangeCurrentLocation = ds.add(new Emitter<{ readonly folder: unknown; readonly reason: 'user' | 'programmatic' }>()); + let currentLocation: IResolvedFolderLocation | undefined = options.confirmed; + let providerAvailable = !!options.providerAvailable; + let folderUri = options.folderUri ?? alternate; + + let multiRoot = !!options.multiRoot; + const getWorkspace = () => multiRoot + ? new Workspace('multi', [new WorkspaceFolder({ uri: folderUri, name: 'project', index: 0 })], false, URI.file('/work/a.code-workspace'), () => false) + : new Workspace('id', [new WorkspaceFolder({ uri: folderUri, name: 'project', index: 0 })], false, null, () => false, undefined, primary); + + const locationService = { + onDidChangeProviders: onDidChangeProviders.event, + onDidChangeLocation: onDidChangeCurrentLocation.event, + isAtAlternateLocation: () => !multiRoot && !extUri.isEqual(folderUri, primary), + getLocation: () => currentLocation, + setLocation(folder: unknown, location: IResolvedFolderLocation | undefined) { currentLocation = location; onDidChangeCurrentLocation.fire({ folder, reason: 'programmatic' }); }, + resolveLocation: options.resolveLocation ?? (async () => providerAvailable ? resolvedLocation : undefined) + } as unknown as IWorkspaceFolderLocationService; + + const contribution = ds.add(new FolderLocationPersistenceContribution( + { getWorkspace, onDidChangeWorkbenchState: onDidChangeWorkbenchState.event, onDidChangeWorkspaceFolders: onDidChangeWorkspaceFolders.event } as unknown as IWorkspaceContextService, + locationService, + { + setFolderLocation: options.setFolderLocation ?? (async (l: URI) => { returns.push(l); folderUri = l; }) + } as unknown as IWorkspaceEditingService, + { setWindowFolderLocation: (value: IWindowFolderLocation | undefined) => { persistedCalls.push(value); } } as unknown as INativeHostService, + { folderLocation: options.persisted, folderLocationMissing: options.folderLocationMissing } as unknown as INativeWorkbenchEnvironmentService, + { + notify: (n: { message: string; id?: string }) => { notifications.push(n.message); notificationIds.push(n.id); }, + prompt: (_severity: unknown, _message: string, choices: { label: string; run: () => unknown }[]) => { + const onDidClose = ds.add(new Emitter<void>()); + let closed = false; + prompts.push({ choices: choices.map(c => c.label), run: async () => { await choices[0].run(); }, closed: () => closed }); + return { onDidClose: onDidClose.event, close: () => { closed = true; onDidClose.fire(); } }; + } + } as unknown as INotificationService, + { extUri } as unknown as IUriIdentityService, + { error: (message: string) => { errors.push(message); } } as unknown as ILogService + )); + + return { + persistedCalls, notifications, notificationIds, errors, returns, prompts, locationService, contribution, + registerProvider() { providerAvailable = true; onDidChangeProviders.fire(); }, + fireProvidersChanged() { onDidChangeProviders.fire(); }, + current: () => currentLocation, + setCurrent(location: IResolvedFolderLocation | undefined) { currentLocation = location; onDidChangeCurrentLocation.fire({ folder: getWorkspace().folders[0], reason: 'programmatic' }); }, + hasProvidersListener: () => onDidChangeProviders.hasListeners(), + moveFolderTo(uri: URI) { folderUri = uri; }, + enterMultiRoot() { multiRoot = true; onDidChangeWorkbenchState.fire(); onDidChangeWorkspaceFolders.fire(); }, + dispose: () => contribution.dispose() + }; + } + + const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0)); + + test('a confirmed location becomes the current location and is persisted', async () => { + const fixture = createFixture({ persisted, providerAvailable: true }); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current()?.label, persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns }, + { current: 'Alternate', persisted: [persisted], notifications: [], returns: [] }); + }); + + test('the restore failure notification carries an id so that it is never duplicated', async () => { + const fixture = createFixture({ persisted, folderUri: primary }); + await settle(); + + assert.deepStrictEqual(fixture.notificationIds, ['workbench.folderLocationRestoreFailed']); + }); + + test('a missing location is discarded and the user is notified', async () => { + const fixture = createFixture({ persisted, folderUri: primary }); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current(), persisted: fixture.persistedCalls, notifications: fixture.notifications.length, returns: fixture.returns }, + { current: undefined, persisted: [undefined], notifications: 1, returns: [] }); + }); + + test('a provider registering late confirms the location', async () => { + const fixture = createFixture({ persisted }); + await settle(); + const before: IResolvedFolderLocation | undefined = fixture.current(); + assert.strictEqual(before, undefined); + + fixture.registerProvider(); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current()?.label, notifications: fixture.notifications, returns: fixture.returns }, + { current: 'Alternate', notifications: [], returns: [] }); + }); + + test('a fresh open at the primary persists nothing and does not notify', async () => { + const fixture = createFixture({ folderUri: primary }); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current(), persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns }, + { current: undefined, persisted: [], notifications: [], returns: [] }); + }); + + test('a provider that never resolves leaves the window at the location and offers to return, without switching', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + assert.deepStrictEqual( + { current: fixture.current(), persisted: fixture.persistedCalls, prompts: fixture.prompts.map(p => p.choices), returns: fixture.returns, listeners: fixture.hasProvidersListener() }, + { current: undefined, persisted: [], prompts: [['Return to Primary Location']], returns: [], listeners: false }); + })); + + test('the return offered for an unconfirmed location switches to the primary when chosen', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + await fixture.prompts[0].run(); + + assert.deepStrictEqual(fixture.returns.map(r => r.toString()), [primary.toString()]); + })); + + test('a failing return chosen by the user is logged', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }), setFolderLocation: async () => { throw new Error('failed'); } }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + await fixture.prompts[0].run(); + + assert.strictEqual(fixture.errors.length, 1); + })); + + test('the offer to return is withdrawn once the location is switched by someone else', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + fixture.setCurrent(resolvedLocation); + + assert.strictEqual(fixture.prompts[0].closed(), true); + })); + + test('the offer to return is withdrawn when the contribution is disposed', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + fixture.dispose(); + + assert.strictEqual(fixture.prompts[0].closed(), true); + })); + + test('the offer to return is withdrawn when the workspace becomes multi-root', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + fixture.enterMultiRoot(); + await fixture.prompts[0].run(); + + assert.deepStrictEqual({ closed: fixture.prompts[0].closed(), returns: fixture.returns }, { closed: true, returns: [] }); + })); + + test('the offer to return does nothing when the folder is no longer at the location', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted, resolveLocation: () => new Promise(() => { }) }); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + fixture.moveFolderTo(primary); + await fixture.prompts[0].run(); + + assert.deepStrictEqual(fixture.returns, []); + })); + + test('a positive result after the deadline is ignored', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const resolution = new DeferredPromise<IResolvedFolderLocation | undefined>(); + const fixture = createFixture({ persisted, resolveLocation: () => resolution.p }); + + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + resolution.complete(resolvedLocation); + await timeout(1); + + assert.deepStrictEqual({ current: fixture.current(), returns: fixture.returns, prompts: fixture.prompts.length }, { current: undefined, returns: [], prompts: 1 }); + })); + + test('a location that no longer exists is reported once and nothing is persisted', async () => { + const fixture = createFixture({ folderUri: primary, folderLocationMissing: { label: 'Gone' } }); + await settle(); + + assert.deepStrictEqual( + { notifications: fixture.notifications, ids: fixture.notificationIds, persisted: fixture.persistedCalls, returns: fixture.returns }, + { notifications: ['The folder location \'Gone\' no longer exists. The folder was opened at its primary location.'], ids: ['workbench.folderLocationMissing'], persisted: [], returns: [] }); + }); + + test('a provider registering while the resolution is pending is not missed', async () => { + const first = new DeferredPromise<IResolvedFolderLocation | undefined>(); + let calls = 0; + const fixture = createFixture({ persisted, resolveLocation: () => ++calls === 1 ? first.p : Promise.resolve(resolvedLocation) }); + await settle(); + + fixture.fireProvidersChanged(); + first.complete(undefined); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current()?.label, calls, notifications: fixture.notifications, returns: fixture.returns }, + { current: 'Alternate', calls: 2, notifications: [], returns: [] }); + }); + + test('disposing while the resolution is pending has no side effects', async () => { + const resolution = new DeferredPromise<IResolvedFolderLocation | undefined>(); + const fixture = createFixture({ persisted, resolveLocation: () => resolution.p }); + await settle(); + + fixture.contribution.dispose(); + resolution.complete(resolvedLocation); + await settle(); + + assert.deepStrictEqual( + { current: fixture.current(), persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns, listeners: fixture.hasProvidersListener() }, + { current: undefined, persisted: [], notifications: [], returns: [], listeners: false }); + }); + + test('disposing while waiting for providers has no side effects', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const fixture = createFixture({ persisted }); + await timeout(1); + + fixture.contribution.dispose(); + await timeout(FOLDER_LOCATION_RESTORE_TIMEOUT + 1); + + assert.deepStrictEqual( + { current: fixture.current(), persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns, listeners: fixture.hasProvidersListener() }, + { current: undefined, persisted: [], notifications: [], returns: [], listeners: false }); + })); + + test('a location already confirmed at construction is respected and persisted', async () => { + const other: IResolvedFolderLocation = { uri: URI.file('/work/project-other'), label: 'Other', providerId: 'test', builtIn: true }; + const fixture = createFixture({ persisted, folderUri: other.uri, confirmed: other }); + await settle(); + + assert.deepStrictEqual( + { persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns }, + { persisted: [{ uri: other.uri.toString(), label: 'Other', providerId: 'test' }], notifications: [], returns: [] }); + }); + + test('a location confirmed before instantiation without a startup location is persisted', async () => { + const other: IResolvedFolderLocation = { uri: URI.file('/work/project-other'), label: 'Other', providerId: 'test', builtIn: true }; + const fixture = createFixture({ folderUri: other.uri, confirmed: other }); + await settle(); + + assert.deepStrictEqual(fixture.persistedCalls, [{ uri: other.uri.toString(), label: 'Other', providerId: 'test' }]); + }); + + test('a stale location in a multi-root window is cleaned up without a warning', async () => { + const fixture = createFixture({ persisted, multiRoot: true }); + await settle(); + + assert.deepStrictEqual( + { persisted: fixture.persistedCalls, notifications: fixture.notifications, returns: fixture.returns }, + { persisted: [undefined], notifications: [], returns: [] }); + }); +}); diff --git a/src/vs/workbench/electron-browser/actions/windowActions.ts b/src/vs/workbench/electron-browser/actions/windowActions.ts index e2659d27dbc9..3ba5e2819ce4 100644 --- a/src/vs/workbench/electron-browser/actions/windowActions.ts +++ b/src/vs/workbench/electron-browser/actions/windowActions.ts @@ -29,7 +29,7 @@ import { KeybindingWeight } from '../../../platform/keybinding/common/keybinding import { isMacintosh } from '../../../base/common/platform.js'; import { getActiveWindow } from '../../../base/browser/dom.js'; import { IOpenedAuxiliaryWindow, IOpenedMainWindow, isOpenedAuxiliaryWindow } from '../../../platform/window/common/window.js'; -import { IsAuxiliaryWindowContext, IsAuxiliaryWindowFocusedContext, IsWindowAlwaysOnTopContext } from '../../common/contextkeys.js'; +import { IsAuxiliaryWindowContext, IsWindowAlwaysOnTopContext } from '../../common/contextkeys.js'; import { isAuxiliaryWindow, mainWindow } from '../../../base/browser/window.js'; import { ContextKeyExpr } from '../../../platform/contextkey/common/contextkey.js'; @@ -497,19 +497,13 @@ export class ToggleWindowAlwaysOnTopAction extends Action2 { super({ id: ToggleWindowAlwaysOnTopAction.ID, title: localize2('toggleWindowAlwaysOnTop', "Toggle Window Always on Top"), - f1: true, - precondition: IsAuxiliaryWindowFocusedContext + f1: true }); } override async run(accessor: ServicesAccessor): Promise<void> { const nativeHostService = accessor.get(INativeHostService); - const targetWindow = getActiveWindow(); - if (!isAuxiliaryWindow(targetWindow.window)) { - return; // Currently, we only support toggling always on top for auxiliary windows - } - return nativeHostService.toggleWindowAlwaysOnTop({ targetWindowId: getActiveWindow().vscodeWindowId }); } } diff --git a/src/vs/workbench/electron-browser/parts/titlebar/menubarControl.ts b/src/vs/workbench/electron-browser/parts/titlebar/menubarControl.ts index 716f2280413e..37060b02a751 100644 --- a/src/vs/workbench/electron-browser/parts/titlebar/menubarControl.ts +++ b/src/vs/workbench/electron-browser/parts/titlebar/menubarControl.ts @@ -177,9 +177,11 @@ export class NativeMenubarControl extends MenubarControl { private getAdditionalKeybindings(): { [id: string]: IMenubarKeybinding } { const keybindings: { [id: string]: IMenubarKeybinding } = {}; if (isMacintosh) { - const keybinding = this.getMenubarKeybinding('workbench.action.quit'); - if (keybinding) { - keybindings['workbench.action.quit'] = keybinding; + for (const commandId of ['workbench.action.quit', 'workbench.action.toggleWindowAlwaysOnTop']) { + const keybinding = this.getMenubarKeybinding(commandId); + if (keybinding) { + keybindings[commandId] = keybinding; + } } } diff --git a/src/vs/workbench/electron-browser/window.ts b/src/vs/workbench/electron-browser/window.ts index e22f12ed6d36..3f1760251b7a 100644 --- a/src/vs/workbench/electron-browser/window.ts +++ b/src/vs/workbench/electron-browser/window.ts @@ -35,7 +35,7 @@ import { IMainProcessService } from '../../platform/ipc/common/mainProcessServic import { ProxyChannel } from '../../base/parts/ipc/common/ipc.js'; import { IWorkspaceFolderCreationData } from '../../platform/workspaces/common/workspaces.js'; import { IIntegrityService } from '../services/integrity/common/integrity.js'; -import { isWindows, isMacintosh } from '../../base/common/platform.js'; +import { isWindows, isMacintosh, isLinux } from '../../base/common/platform.js'; import { IProductService } from '../../platform/product/common/productService.js'; import { INotificationService, NeverShowAgainScope, NotificationPriority, Severity } from '../../platform/notification/common/notification.js'; import { IKeybindingService } from '../../platform/keybinding/common/keybinding.js'; @@ -776,11 +776,12 @@ export class NativeWindow extends BaseWindow { } } - // macOS 11 warning + // macOS 13 and 14 warning if (isMacintosh) { const majorVersion = this.nativeEnvironmentService.os.release.split('.')[0]; const eolReleases = new Map<string, string>([ - ['20', 'macOS Big Sur'], + ['22', 'macOS Ventura'], + ['23', 'macOS Sonoma'], ]); if (eolReleases.has(majorVersion)) { @@ -794,7 +795,7 @@ export class NativeWindow extends BaseWindow { run: () => this.openerService.open(URI.parse('https://aka.ms/vscode-faq-old-macOS')) }], { - neverShowAgain: { id: 'macoseol', isSecondary: true, scope: NeverShowAgainScope.APPLICATION }, + neverShowAgain: { id: `macoseol.${majorVersion}`, isSecondary: true, scope: NeverShowAgainScope.APPLICATION }, priority: NotificationPriority.URGENT, sticky: true } @@ -802,6 +803,25 @@ export class NativeWindow extends BaseWindow { } } + // Linux arm32 warning + if (isLinux && this.nativeEnvironmentService.os.arch === 'arm') { + const message = localize('linuxarm32eolmessage', "{0} on 32-bit ARM Linux will soon stop receiving updates. Consider using a 64-bit version of {0} and a 64-bit operating system.", this.productService.nameLong); + + this.notificationService.prompt( + Severity.Warning, + message, + [{ + label: localize('learnMore', "Learn More"), + run: () => this.openerService.open(URI.parse('https://aka.ms/vscode-linux-arm-32-eol')) + }], + { + neverShowAgain: { id: 'linuxarm32eol', isSecondary: true, scope: NeverShowAgainScope.APPLICATION }, + priority: NotificationPriority.URGENT, + sticky: true + } + ); + } + // Slow shell environment progress indicator const shellEnv = process.shellEnv(); this.progressService.withProgress({ diff --git a/src/vs/workbench/services/accounts/browser/defaultAccount.ts b/src/vs/workbench/services/accounts/browser/defaultAccount.ts index 00164eda5511..37f70aecf610 100644 --- a/src/vs/workbench/services/accounts/browser/defaultAccount.ts +++ b/src/vs/workbench/services/accounts/browser/defaultAccount.ts @@ -1042,6 +1042,7 @@ export class DefaultAccountProvider extends Disposable implements IDefaultAccoun copilotTokenInfo: { sn: tokenMap.get('sn'), fcv1: tokenMap.get('fcv1'), + st: tokenMap.get('st'), }, }; } diff --git a/src/vs/workbench/services/accounts/browser/managedSettings.ts b/src/vs/workbench/services/accounts/browser/managedSettings.ts index 8ffe0e2b56f5..908a69e8b67d 100644 --- a/src/vs/workbench/services/accounts/browser/managedSettings.ts +++ b/src/vs/workbench/services/accounts/browser/managedSettings.ts @@ -68,6 +68,16 @@ export interface IManagedSettingsResponse { readonly allowManagedMcpServersOnly?: boolean; readonly allowManagedHooksOnly?: boolean; readonly forceRemoteSettingsRefresh?: boolean; + /** VS Code-specific managed preferences, which the Copilot runtime preserves without interpreting. */ + readonly vscode?: { + /** + * Third-party harnesses (`claude`, `codex`) permitted while managed settings are present. A + * present list denies the harnesses it does not name, so `[]` denies both. Other entries + * are ignored. + */ + readonly allowedHarnesses?: readonly string[]; + readonly [key: string]: unknown; + }; readonly telemetry?: { readonly enabled?: boolean; readonly endpoint?: string; diff --git a/src/vs/workbench/services/accounts/test/browser/defaultAccount.test.ts b/src/vs/workbench/services/accounts/test/browser/defaultAccount.test.ts index ee042bc05d59..730661fef343 100644 --- a/src/vs/workbench/services/accounts/test/browser/defaultAccount.test.ts +++ b/src/vs/workbench/services/accounts/test/browser/defaultAccount.test.ts @@ -1652,12 +1652,14 @@ suite('DefaultAccountProvider', () => { const provider = await createProvider(requestService, {}, {}, undefined, { getSessions: async () => [selected] }, configuration); outcomes.push({ settings: provider.resolveGitHubUrl('settings/copilot'), + tokenStamp: provider.copilotTokenInfo?.st, requests: requestService.requests.map(request => ({ url: request.url?.split('?')[0], token: request.headers?.Authorization })), }); } assert.deepStrictEqual(outcomes, cases.map(({ base, api }) => ({ settings: `${base}settings/copilot`, + tokenStamp: 'proxima', requests: paths.map(path => ({ url: `${api}${path}`, token: 'Bearer b-token' })), }))); }); @@ -1979,7 +1981,7 @@ suite('DefaultAccountProvider', () => { async function enterpriseResponse(request: IRequestOptions): Promise<IRequestContext> { switch (request.callSite) { case 'defaultAccount.entitlements': return jsonResponse({ chat_enabled: true }); - case 'defaultAccount.tokenEntitlements': return jsonResponse({ token: 'mcp=1;sn=test:signature' }); + case 'defaultAccount.tokenEntitlements': return jsonResponse({ token: 'mcp=1;sn=test;st=proxima:signature' }); case 'defaultAccount.managedSettings': return jsonResponse({ model: new URL(request.url!).hostname }); case 'defaultAccount.mcpRegistryProvider': return jsonResponse({ mcp_registries: [{ url: 'https://registry.example.test', registry_access: 'registry_only' }] }); default: throw new Error(`Unexpected request: ${request.callSite}`); diff --git a/src/vs/workbench/services/actions/common/menusExtensionPoint.ts b/src/vs/workbench/services/actions/common/menusExtensionPoint.ts index e6c222d455c6..6f4a1022326b 100644 --- a/src/vs/workbench/services/actions/common/menusExtensionPoint.ts +++ b/src/vs/workbench/services/actions/common/menusExtensionPoint.ts @@ -576,6 +576,18 @@ const apiMenus: IAPIMenu[] = [ description: localize('menus.agentsChangeInline', "The Changes view inline menu in the agents window."), proposed: 'chatSessionsProvider' }, + { + key: 'titleBar', + id: MenuId.TitleBar, + description: localize('menus.titleBar', "The title bar of the editor window."), + proposed: 'contribTitleBar' + }, + { + key: 'agents/titleBar', + id: MenuId.AgentsTitleBar, + description: localize('menus.agentsTitleBar', "The title bar of the agents window."), + proposed: 'contribTitleBar' + }, ]; namespace schema { diff --git a/src/vs/workbench/services/agentEditorComments/browser/media/agentEditorCommentsOverlayWidget.css b/src/vs/workbench/services/agentEditorComments/browser/media/agentEditorCommentsOverlayWidget.css index f73e79a4a2e7..6d36e8f7a118 100644 --- a/src/vs/workbench/services/agentEditorComments/browser/media/agentEditorCommentsOverlayWidget.css +++ b/src/vs/workbench/services/agentEditorComments/browser/media/agentEditorCommentsOverlayWidget.css @@ -26,7 +26,7 @@ padding: 4px 6px; font-size: var(--vscode-fontSize-body2); line-height: 14px; - border-radius: var(--vscode-cornerRadius-small); + border-radius: var(--workbench-custom-buttons-corner-radius, var(--vscode-cornerRadius-small)); } .agent-editor-comments-overlay-widget .monaco-action-bar .actions-container { diff --git a/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts b/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts index d2266bc738f5..690762333c3d 100644 --- a/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts +++ b/src/vs/workbench/services/agentHost/browser/editorRemoteAgentHostServiceClient.ts @@ -11,8 +11,9 @@ import type { CancellationToken } from '../../../../base/common/cancellation.js'; import { Emitter, Event } from '../../../../base/common/event.js'; -import { Disposable, IReference } from '../../../../base/common/lifecycle.js'; +import { Disposable, IReference, MutableDisposable } from '../../../../base/common/lifecycle.js'; import { autorun, IObservable, ISettableObservable, observableValue, constObservable } from '../../../../base/common/observable.js'; +import { env } from '../../../../base/common/process.js'; import { URI } from '../../../../base/common/uri.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ILabelService } from '../../../../platform/label/common/label.js'; @@ -22,6 +23,8 @@ import type { IChatUserInteractionTiming } from '../../../../platform/otel/commo import { AgentHostIpcChannels, IAgentCreateChatRequestOptions, IAgentCreateChatWorkspace, IAgentCreateSessionConfig, IAgentHostInspectInfo, IAgentHostManagedSettingsDiagnostics, IAgentHostNetworkDiagnosticsInfo, IAgentHostNetworkFetchResult, IAgentHostService, IAgentHostSocketInfo, IAgentResolveSessionConfigParams, IAgentSessionConfigCompletionsParams, IAgentSessionMetadata, AuthenticateParams, AuthenticateResult, IMcpNotification, type AgentHostDebugLogsArtifactKind, type IAgentHostDebugLogsArtifact, type IAgentHostDebugLogsChunk } from '../../../../platform/agentHost/common/agentService.js'; import type { AgentChatMoveDestination } from '../../../../platform/agentHost/common/agentHostChatMove.js'; import { IAgentHostEnablementService } from '../../../../platform/agentHost/common/agentHostEnablementService.js'; +import { IRemoteAgentHostLocationPreferenceService } from '../../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; +import { getSSHRemoteAuthorityConnectionKey } from '../../../../platform/agentHost/common/sshRemoteAgentHost.js'; import { AgentHostIpcChannelTransport } from '../../../../platform/agentHost/browser/agentHostIpcChannelTransport.js'; import { AgentHostClientConnectionKind } from '../../../../platform/agentHost/common/agentHostTelemetry.js'; import { AgentHostClientState, AgentHostProtocolClient } from '../../../../platform/agentHost/browser/agentHostProtocolClient.js'; @@ -39,6 +42,7 @@ import { IRemoteAgentService } from '../../remote/common/remoteAgentService.js'; import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js'; import { agentsWindowAgentHostClientInfo, editorWindowAgentHostClientInfo } from '../../../../platform/agentHost/common/agentHostClientInfo.js'; import { agentHostAuthority, agentHostLabelFormatter, createEditorRemoteAgentHostResourceUriMapper, identityAgentHostResourceUriMapper } from '../../../../platform/agentHost/common/agentHostUri.js'; +import { getAgentHostPathStyle } from '../../../../platform/agentHost/common/agentHostPathStyle.js'; import { IAgentHostFileSystemService } from '../common/agentHostFileSystemService.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { IRequestService } from '../../../../platform/request/common/request.js'; @@ -88,6 +92,7 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA }; private _connectStarted = false; private _useHostProxy = false; + private readonly _labelFormatter = this._register(new MutableDisposable()); constructor( @IRemoteAgentService private readonly _remoteAgentService: IRemoteAgentService, @@ -100,6 +105,7 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA @IRemoteAuthorityResolverService remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IConfigurationService configurationService: IConfigurationService, @IRequestService requestService: IRequestService, + @IRemoteAgentHostLocationPreferenceService locationPreferenceService: IRemoteAgentHostLocationPreferenceService, ) { super(); @@ -121,15 +127,19 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA undefined, AgentHostClientConnectionKind.RemoteExtensionHost, async () => { + const hostKey = getSSHRemoteAuthorityConnectionKey(connection.remoteAuthority); + const preferredAgentLocation = hostKey ? locationPreferenceService.getPreference(hostKey) : undefined; + const preference = preferredAgentLocation === undefined ? undefined : { preferredAgentLocation }; this._useHostProxy = (await this._remoteAgentService.getRawEnvironment())?.useHostProxy === true; let resolverResult: ResolverResult; try { resolverResult = await remoteAuthorityResolverService.resolveAuthority(connection.remoteAuthority); } catch { this._logService.warn(`${LOG_PREFIX} Unable to resolve the remote environment; connecting without environment overrides.`); - return undefined; + return preference; } return { + ...preference, env: resolverResult.options?.extensionHostEnv ?? {}, debugEnv: environmentService.debugExtensionHost.env, }; @@ -146,7 +156,7 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA isEnabled: () => sharesClientNetwork() && configurationService.getValue<boolean>('http.systemCertificates') === true, loadCertificates: () => requestService.loadCertificates(), }, - clientProxy: instantiationService.createInstance(AgentHostClientProxy, sharesClientNetwork), + clientProxy: instantiationService.createInstance(AgentHostClientProxy, sharesClientNetwork, env), })); // Resources this client hands out (e.g. debug-log artifacts) are stamped with the // address-derived authority, so register it for reads. The ambient `local` authority @@ -158,6 +168,7 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA })); this._register(this._protocolClient.onDidChangeConnectionState(state => { if (state === AgentHostClientState.Connected) { + this._updateLabelFormatter(); this._logService.info(`${LOG_PREFIX} Connected; clientId=${this._protocolClient?.clientId}`); this._onAgentHostStart.fire(); } @@ -176,13 +187,17 @@ export class EditorRemoteAgentHostServiceClient extends Disposable implements IA } this._connectStarted = true; this._logService.info(`${LOG_PREFIX} Connecting to remote agent host...`); - const remoteEnvironment = await this._remoteAgentService.getRawEnvironment(); - if (remoteEnvironment && this._connectionAuthority) { - this._register(this._labelService.registerFormatter(agentHostLabelFormatter(this._connectionAuthority, remoteEnvironment.os))); - } + await this._remoteAgentService.getRawEnvironment(); await this._protocolClient.connect(); } + private _updateLabelFormatter(): void { + const pathStyle = this._protocolClient ? getAgentHostPathStyle(this._protocolClient) : undefined; + this._labelFormatter.value = this._connectionAuthority && pathStyle + ? this._labelService.registerFormatter(agentHostLabelFormatter(this._connectionAuthority, pathStyle)) + : undefined; + } + private _requireClient(): AgentHostProtocolClient { if (!this._protocolClient) { throw new Error('Remote agent host is not enabled or no remote connection is available.'); diff --git a/src/vs/workbench/services/agentHost/common/agentHostFileSystemService.ts b/src/vs/workbench/services/agentHost/common/agentHostFileSystemService.ts index ee6c328390e3..99224d02a1d4 100644 --- a/src/vs/workbench/services/agentHost/common/agentHostFileSystemService.ts +++ b/src/vs/workbench/services/agentHost/common/agentHostFileSystemService.ts @@ -4,10 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import { Disposable, IDisposable } from '../../../../base/common/lifecycle.js'; -import { OS } from '../../../../base/common/platform.js'; import { AgentHostFileSystemProvider, type IRemoteFilesystemConnection } from '../../../../platform/agentHost/common/agentHostFileSystemProvider.js'; import { SYNCED_CUSTOMIZATION_DISPLAY_NAME, SYNCED_CUSTOMIZATION_SCHEME } from '../../../../platform/agentHost/common/agentHostCustomizationUri.js'; -import { AGENT_HOST_LABEL_FORMATTER, AGENT_HOST_SCHEME, agentHostLabelFormatter, LOCAL_AGENT_HOST_AUTHORITY } from '../../../../platform/agentHost/common/agentHostUri.js'; +import { AGENT_HOST_LABEL_FORMATTER, AGENT_HOST_SCHEME } from '../../../../platform/agentHost/common/agentHostUri.js'; import { IFileService } from '../../../../platform/files/common/files.js'; import { InMemoryFileSystemProvider } from '../../../../platform/files/common/inMemoryFilesystemProvider.js'; import { IBrowserResourceService } from '../../../../platform/files/common/browserResourceService.js'; @@ -59,10 +58,7 @@ class AgentHostFileSystemService extends Disposable implements IAgentHostFileSys const searchProvider = this._register(instantiationService.createInstance(FileSystemFileSearchProvider)); this._register(searchService.registerSearchResultProvider(AGENT_HOST_SCHEME, SearchProviderType.file, searchProvider)); - // Two formatters: the scheme-wide fallback for hosts whose operating - // system is unknown, and a more specific one for the in-process host. this._register(labelService.registerFormatter(AGENT_HOST_LABEL_FORMATTER)); - this._register(labelService.registerFormatter(agentHostLabelFormatter(LOCAL_AGENT_HOST_AUTHORITY, OS))); } registerAuthority(authority: string, connection: IRemoteFilesystemConnection): IDisposable { diff --git a/src/vs/workbench/services/agentHost/test/browser/agentHostLabelFormatter.test.ts b/src/vs/workbench/services/agentHost/test/browser/agentHostLabelFormatter.test.ts index 69c0b234af95..78a3dbc43ec4 100644 --- a/src/vs/workbench/services/agentHost/test/browser/agentHostLabelFormatter.test.ts +++ b/src/vs/workbench/services/agentHost/test/browser/agentHostLabelFormatter.test.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { OperatingSystem } from '../../../../../base/common/platform.js'; import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { AGENT_HOST_LABEL_FORMATTER, agentHostLabelFormatter, LOCAL_AGENT_HOST_AUTHORITY, toAgentHostUri } from '../../../../../platform/agentHost/common/agentHostUri.js'; @@ -14,6 +13,7 @@ import { TestContextService, TestStorageService } from '../../../../test/common/ import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { extUri } from '../../../../../base/common/resources.js'; import { mock } from '../../../../../base/test/common/mock.js'; +import { PathStyle } from '../../../../../platform/agentHost/common/state/protocol/common/commands.js'; suite('AgentHost label formatter', () => { @@ -38,7 +38,7 @@ suite('AgentHost label formatter', () => { test('a Windows host renders paths natively, so they match the `file:` side of a diff', () => { const labelService = createLabelService(); - disposables.add(labelService.registerFormatter(agentHostLabelFormatter(LOCAL_AGENT_HOST_AUTHORITY, OperatingSystem.Windows))); + disposables.add(labelService.registerFormatter(agentHostLabelFormatter(LOCAL_AGENT_HOST_AUTHORITY, PathStyle.Windows))); // Agent host URIs carry a lower-cased drive letter because they // round-trip through `URI.toString()` on the way to the client @@ -49,18 +49,18 @@ suite('AgentHost label formatter', () => { test('a POSIX host renders paths natively', () => { const labelService = createLabelService(); - disposables.add(labelService.registerFormatter(agentHostLabelFormatter(LOCAL_AGENT_HOST_AUTHORITY, OperatingSystem.Linux))); + disposables.add(labelService.registerFormatter(agentHostLabelFormatter(LOCAL_AGENT_HOST_AUTHORITY, PathStyle.Posix))); const wrapped = toAgentHostUri(URI.from({ scheme: 'session-db', path: '/home/user/repo/src/app.ts' }), LOCAL_AGENT_HOST_AUTHORITY); assert.strictEqual(labelService.getUriLabel(wrapped), '/home/user/repo/src/app.ts'); }); - test('a host of unknown operating system renders the path losslessly', () => { + test('a host of unknown path style renders the path losslessly', () => { const labelService = createLabelService(); // `/c:/…` is a valid POSIX path too, so without knowing the host's - // operating system neither form may be rewritten + // path style neither form may be rewritten const windowsUri = toAgentHostUri(URI.from({ scheme: 'session-db', path: '/c:/Code/repo/src/app.ts' }), 'remotehost'); const posixUri = toAgentHostUri(URI.from({ scheme: 'session-db', path: '/home/user/repo/src/app.ts' }), 'remotehost'); diff --git a/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts b/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts index e2a6140fce64..4aa089415ba7 100644 --- a/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts +++ b/src/vs/workbench/services/agentHost/test/browser/editorRemoteAgentHostServiceClient.test.ts @@ -5,16 +5,17 @@ import assert from 'assert'; import * as sinon from 'sinon'; +import { encodeHex, VSBuffer } from '../../../../../base/common/buffer.js'; import { DeferredPromise } from '../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; import { autorun, constObservable, observableValue } from '../../../../../base/common/observable.js'; -import { OperatingSystem } from '../../../../../base/common/platform.js'; import { hasKey } from '../../../../../base/common/types.js'; import { URI } from '../../../../../base/common/uri.js'; import type { IChannel, IServerChannel } from '../../../../../base/parts/ipc/common/ipc.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IRemoteAgentHostLocationPreferenceService, RemoteAgentHostLocationPreference } from '../../../../../platform/agentHost/common/remoteAgentHostLocationPreference.js'; import { IAgentHostEnablementService } from '../../../../../platform/agentHost/common/agentHostEnablementService.js'; import { IWorkbenchEnvironmentService } from '../../../environment/common/environmentService.js'; import { AgentHostClientState, AgentHostProtocolClient, type IAgentHostProtocolClientOptions } from '../../../../../platform/agentHost/browser/agentHostProtocolClient.js'; @@ -39,6 +40,7 @@ import { TestRemoteAgentService } from '../../../../test/browser/workbenchTestSe import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IRequestService } from '../../../../../platform/request/common/request.js'; +import { PathStyle } from '../../../../../platform/agentHost/common/state/protocol/common/commands.js'; class TestRemoteAgentConnection extends Disposable implements IRemoteAgentConnection { readonly isConnected = true; @@ -90,11 +92,12 @@ suite('EditorRemoteAgentHostServiceClient', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); teardown(() => sinon.restore()); - function createTransportFactory(channel: IChannel, resolveAuthority: IRemoteAuthorityResolverService['resolveAuthority'], isSessionsWindow = false, logService = new NullLogService(), certificates?: { useHostProxy: boolean; systemCertificates: boolean; authority?: string }, onOptions?: (options: IAgentHostProtocolClientOptions) => void): () => IClientTransport { - const remoteAgentService = new DeferredRemoteAgentService(disposables.add(new TestRemoteAgentConnection(channel, certificates ? certificates.authority ?? 'wsl+test' : 'codespaces+test'))); + function createTransportFactory(channel: IChannel, resolveAuthority: IRemoteAuthorityResolverService['resolveAuthority'], isSessionsWindow = false, logService = new NullLogService(), certificates?: { useHostProxy: boolean; systemCertificates: boolean; authority?: string }, onOptions?: (options: IAgentHostProtocolClientOptions) => void, remoteAuthority = 'codespaces+test', getPreference: IRemoteAgentHostLocationPreferenceService['getPreference'] = () => undefined): () => IClientTransport { + const remoteAgentService = new DeferredRemoteAgentService(disposables.add(new TestRemoteAgentConnection(channel, certificates ? certificates.authority ?? 'wsl+test' : remoteAuthority))); remoteAgentService.environmentReady.complete(upcastPartial<IRemoteAgentEnvironment>({ useHostProxy: certificates?.useHostProxy ?? false })); const instantiationService = disposables.add(new TestInstantiationService(new ServiceCollection( [IRemoteAgentService, remoteAgentService], + [IRemoteAgentHostLocationPreferenceService, upcastPartial<IRemoteAgentHostLocationPreferenceService>({ getPreference })], [IConfigurationService, new TestConfigurationService({ 'http.systemCertificates': certificates?.systemCertificates ?? false })], [IRequestService, upcastPartial<IRequestService>({ loadCertificates: async () => { @@ -126,6 +129,51 @@ suite('EditorRemoteAgentHostServiceClient', () => { return protocolClientCall?.args[2] as () => IClientTransport; } + for (const [remoteAuthority, expectedKey] of [ + ['ssh-remote+myhost', 'ssh:myhost'], + [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'MyHost' })))}`, 'ssh:MyHost'], + [`ssh-remote+${encodeHex(VSBuffer.fromString(JSON.stringify({ hostName: 'myhost', user: 'me', port: 2222 })))}`, 'me@myhost:2222'], + ['ssh-remote+me@myhost:2222', 'me@myhost:2222'], + ['ssh-remote+myhost:2222', undefined], + ['tunnel+my-tunnel', undefined], + ['wsl+test', undefined], + ['dev-container+test', undefined], + ] as const) { + test(`reads the stored location on each connection for ${remoteAuthority}, even if environment resolution fails`, async () => { + const calls: unknown[] = []; + const keys: string[] = []; + let preference: RemoteAgentHostLocationPreference | undefined = 'editor'; + const channel: IChannel = { + call: async <T>(_command: string, arg?: unknown) => { calls.push(arg); return undefined as T; }, + listen: () => Event.None, + }; + const createTransport = createTransportFactory(channel, async () => { throw new Error('Resolver unavailable'); }, false, new NullLogService(), undefined, undefined, remoteAuthority, key => { + keys.push(key); + return preference; + }); + await disposables.add(createTransport()).connect(); + preference = 'dedicated'; + await disposables.add(createTransport()).connect(); + preference = undefined; + await disposables.add(createTransport()).connect(); + assert.deepStrictEqual({ keys, calls }, { + keys: expectedKey ? [expectedKey, expectedKey, expectedKey] : [], + calls: expectedKey ? [{ preferredAgentLocation: 'editor' }, { preferredAgentLocation: 'dedicated' }, undefined] : [undefined, undefined, undefined], + }); + }); + } + + test('forwards the location preference alongside the resolver environment', async () => { + const calls: unknown[] = []; + const channel: IChannel = { + call: async <T>(_command: string, arg?: unknown) => { calls.push(arg); return undefined as T; }, + listen: () => Event.None, + }; + const createTransport = createTransportFactory(channel, async () => upcastPartial<ResolverResult>({ options: { extensionHostEnv: { REMOTE: 'value' } } }), false, new NullLogService(), undefined, undefined, 'ssh-remote+myhost', () => 'editor'); + await disposables.add(createTransport()).connect(); + assert.deepStrictEqual(calls, [{ preferredAgentLocation: 'editor', env: { REMOTE: 'value' }, debugEnv: { GITHUB_TOKEN: 'debug-token', DEBUG_ENV: 'debug-value' } }]); + }); + for (const useHostProxy of [true, false]) { for (const systemCertificates of [true, false]) { test(`forwards certificates only for local-network remotes (useHostProxy=${useHostProxy}, systemCertificates=${systemCertificates})`, async () => { @@ -269,7 +317,12 @@ suite('EditorRemoteAgentHostServiceClient', () => { onDidNotification: Event.None, onDidAction: Event.None, onMcpNotification: Event.None, - initializeResult: constObservable(undefined), + initializeResult: constObservable({ + protocolVersion: '1.0.0', + serverSeq: 0, + snapshots: [], + environment: { pathStyle: PathStyle.Windows }, + }), rootState: { value: undefined, verifiedValue: undefined, @@ -285,6 +338,7 @@ suite('EditorRemoteAgentHostServiceClient', () => { const agentHostEnabled = observableValue('agentHostEnabled', false); const instantiationService = disposables.add(new TestInstantiationService(new ServiceCollection( [IRemoteAgentService, remoteAgentService], + [IRemoteAgentHostLocationPreferenceService, upcastPartial<IRemoteAgentHostLocationPreferenceService>({ getPreference: () => undefined })], [IRemoteAuthorityResolverService, upcastPartial<IRemoteAuthorityResolverService>({})], [IAgentHostEnablementService, { _serviceBrand: undefined, enabled: agentHostEnabled, managedSandboxEnforced: constObservable(false) }], [ILogService, new NullLogService()], @@ -315,7 +369,7 @@ suite('EditorRemoteAgentHostServiceClient', () => { agentHostEnabled.set(true, undefined); const beforeReady = connectCalls; - remoteAgentService.environmentReady.complete(upcastPartial<IRemoteAgentEnvironment>({ os: OperatingSystem.Windows })); + remoteAgentService.environmentReady.complete(upcastPartial<IRemoteAgentEnvironment>({})); while (connectCalls === 0) { await Promise.resolve(); } @@ -364,6 +418,7 @@ suite('EditorRemoteAgentHostServiceClient', () => { }))); const instantiationService = disposables.add(new TestInstantiationService(new ServiceCollection( [IRemoteAgentService, remoteAgentService], + [IRemoteAgentHostLocationPreferenceService, upcastPartial<IRemoteAgentHostLocationPreferenceService>({ getPreference: () => undefined })], [IRemoteAuthorityResolverService, upcastPartial<IRemoteAuthorityResolverService>({})], [IAgentHostEnablementService, { _serviceBrand: undefined, enabled: constObservable(false), managedSandboxEnforced: constObservable(false) }], [ILogService, new NullLogService()], @@ -421,6 +476,7 @@ suite('EditorRemoteAgentHostServiceClient', () => { : new TestRemoteAgentService(); const instantiationService = disposables.add(new TestInstantiationService(new ServiceCollection( [IRemoteAgentService, remoteAgentService], + [IRemoteAgentHostLocationPreferenceService, upcastPartial<IRemoteAgentHostLocationPreferenceService>({ getPreference: () => undefined })], [IRemoteAuthorityResolverService, upcastPartial<IRemoteAuthorityResolverService>({})], [IAgentHostEnablementService, { _serviceBrand: undefined, enabled: constObservable(false), managedSandboxEnforced: constObservable(false) }], [ILogService, new NullLogService()], diff --git a/src/vs/workbench/services/assignment/common/assignmentFilters.ts b/src/vs/workbench/services/assignment/common/assignmentFilters.ts index e5f316eec4f0..441d12aad293 100644 --- a/src/vs/workbench/services/assignment/common/assignmentFilters.ts +++ b/src/vs/workbench/services/assignment/common/assignmentFilters.ts @@ -6,7 +6,8 @@ import type { IExperimentationFilterProvider } from 'tas-client'; import { Emitter } from '../../../../base/common/event.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; -import { getInternalOrg } from '../../../../platform/assignment/common/assignment.js'; +import { mapsStrictEqualIgnoreOrder } from '../../../../base/common/map.js'; +import { getInternalOrg, isInternalAccount } from '../../../../platform/assignment/common/assignment.js'; import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js'; import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js'; import { ILogService } from '../../../../platform/log/common/log.js'; @@ -55,6 +56,11 @@ export enum ExtensionsFilter { * Whether the `fcv1` flag is set to `'1'` in the copilot token. */ CopilotIsFcv1 = 'X-GitHub-Copilot-IsFcv1', + + /** + * Whether the account belongs to a Proxima deployment. + */ + CopilotIsProxima = 'X-GitHub-Copilot-IsProxima', } enum StorageVersionKeys { @@ -66,6 +72,7 @@ enum StorageVersionKeys { CopilotTrackingId = 'extensionsAssignmentFilterProvider.copilotTrackingId', CopilotIsSn = 'extensionsAssignmentFilterProvider.copilotIsSn', CopilotIsFcv1 = 'extensionsAssignmentFilterProvider.copilotIsFcv1', + CopilotIsProxima = 'extensionsAssignmentFilterProvider.copilotIsProxima', } export class CopilotAssignmentFilterProvider extends Disposable implements IExperimentationFilterProvider { @@ -79,6 +86,7 @@ export class CopilotAssignmentFilterProvider extends Disposable implements IExpe private copilotTrackingId: string | undefined; private copilotIsSn: string | undefined; private copilotIsFcv1: string | undefined; + private copilotIsProxima: string | undefined; private readonly _onDidChangeFilters = this._register(new Emitter<void>()); readonly onDidChangeFilters = this._onDidChangeFilters.event; @@ -100,6 +108,7 @@ export class CopilotAssignmentFilterProvider extends Disposable implements IExpe this.copilotTrackingId = this._storageService.get(StorageVersionKeys.CopilotTrackingId, StorageScope.PROFILE); this.copilotIsSn = this._storageService.get(StorageVersionKeys.CopilotIsSn, StorageScope.PROFILE); this.copilotIsFcv1 = this._storageService.get(StorageVersionKeys.CopilotIsFcv1, StorageScope.PROFILE); + this.copilotIsProxima = this._storageService.get(StorageVersionKeys.CopilotIsProxima, StorageScope.PROFILE); this.updateExtensionVersions(); this.updateCopilotEntitlementInfo(); @@ -181,16 +190,19 @@ export class CopilotAssignmentFilterProvider extends Disposable implements IExpe const tokenInfo = this._defaultAccountService.copilotTokenInfo; const newIsSn = tokenInfo?.sn === '1' ? '1' : '0'; const newIsFcv1 = tokenInfo?.fcv1 === '1' ? '1' : '0'; + const newIsProxima = tokenInfo?.st && tokenInfo.st !== 'dotcom' ? '1' : '0'; - if (this.copilotIsSn === newIsSn && this.copilotIsFcv1 === newIsFcv1) { + if (this.copilotIsSn === newIsSn && this.copilotIsFcv1 === newIsFcv1 && this.copilotIsProxima === newIsProxima) { return; } this.copilotIsSn = newIsSn; this.copilotIsFcv1 = newIsFcv1; + this.copilotIsProxima = newIsProxima; this._storageService.store(StorageVersionKeys.CopilotIsSn, this.copilotIsSn, StorageScope.PROFILE, StorageTarget.MACHINE); this._storageService.store(StorageVersionKeys.CopilotIsFcv1, this.copilotIsFcv1, StorageScope.PROFILE, StorageTarget.MACHINE); + this._storageService.store(StorageVersionKeys.CopilotIsProxima, this.copilotIsProxima, StorageScope.PROFILE, StorageTarget.MACHINE); // Notify that the filters have changed. this._onDidChangeFilters.fire(); @@ -228,6 +240,8 @@ export class CopilotAssignmentFilterProvider extends Disposable implements IExpe return this.copilotIsSn ?? null; case ExtensionsFilter.CopilotIsFcv1: return this.copilotIsFcv1 ?? null; + case ExtensionsFilter.CopilotIsProxima: + return this.copilotIsProxima ?? null; default: return null; } @@ -246,9 +260,6 @@ export class CopilotAssignmentFilterProvider extends Disposable implements IExpe /** Maps the core-available Copilot filters to new TAS userParams without forwarding legacy headers. */ getAssignmentsFilters(): Map<string, string | null> { return new Map([ - ['github_core_copilotsku', this.getFilterValue(ExtensionsFilter.CopilotSku)], - ['github_core_issn', this.getFilterValue(ExtensionsFilter.CopilotIsSn)], - ['github_core_isfcv1', this.getFilterValue(ExtensionsFilter.CopilotIsFcv1)], ['vscode_core_copilotchatextensionversion', this.getFilterValue(ExtensionsFilter.CopilotChatExtensionVersion)], ]); } @@ -264,6 +275,9 @@ export enum GitHubAssignmentsFilter { /** Whether the account is staff or belongs to a recognized internal organization. */ IsGhOrMsftStaff = 'github_core_isghormsftstaff', GhMsftOrExternal = 'github_core_ghmsftorexternal', + CopilotSku = 'github_core_copilotsku', + CopilotIsSn = 'github_core_issn', + CopilotIsFcv1 = 'github_core_isfcv1', } /** @@ -271,55 +285,47 @@ export enum GitHubAssignmentsFilter { * the new userParam key names. */ export class GitHubCoreAssignmentsFilterProvider extends Disposable implements IExperimentationFilterProvider { - private copilotTrackingId: string | undefined; - private internalOrg: 'vscode' | 'github' | 'microsoft' | undefined; - private isInternal = false; + private filters: Map<string, string | null>; private readonly _onDidChangeFilters = this._register(new Emitter<void>()); readonly onDidChangeFilters = this._onDidChangeFilters.event; constructor( - @IChatEntitlementService private readonly _chatEntitlementService: IChatEntitlementService, + @IDefaultAccountService private readonly _defaultAccountService: IDefaultAccountService, ) { super(); - this._register(this._chatEntitlementService.onDidChangeEntitlement(() => this.update())); - this.update(); + this.filters = this.getFilters(); + this._register(this._defaultAccountService.onDidChangeDefaultAccount(() => this.update())); + this._register(this._defaultAccountService.onDidChangeCopilotTokenInfo(() => this.update())); } private update(): void { - const newTrackingId = this._chatEntitlementService.copilotTrackingId ?? this.copilotTrackingId; - const newInternalOrg = getInternalOrg(this._chatEntitlementService.organisations); - const newIsInternal = this._chatEntitlementService.isInternal; - - if (this.copilotTrackingId === newTrackingId && this.internalOrg === newInternalOrg && this.isInternal === newIsInternal) { + const filters = this.getFilters(); + if (mapsStrictEqualIgnoreOrder(this.filters, filters)) { return; } - - this.copilotTrackingId = newTrackingId; - this.internalOrg = newInternalOrg; - this.isInternal = newIsInternal; - + this.filters = filters; this._onDidChangeFilters.fire(); } getFilterValue(filter: string): string | null { - // copilotTrackingId is the stable user id (it never changes) but can be unavailable - // during sign-in delays. Latch the first known value and fall back to it so the - // filter is not dropped from later requests once we have seen it. - const liveTrackingId = this._chatEntitlementService.copilotTrackingId; - if (liveTrackingId) { - this.copilotTrackingId = liveTrackingId; - } - const copilotTrackingId = liveTrackingId ?? this.copilotTrackingId; - const internalOrg = getInternalOrg(this._chatEntitlementService.organisations) ?? this.internalOrg; + const account = this._defaultAccountService.currentDefaultAccount; + const entitlements = account?.entitlementsData; + const tokenInfo = account ? this._defaultAccountService.copilotTokenInfo : null; switch (filter) { case GitHubAssignmentsFilter.CopilotTrackingId: - return copilotTrackingId ?? null; + return entitlements?.analytics_tracking_id ?? null; case GitHubAssignmentsFilter.IsGhOrMsftStaff: - return this._chatEntitlementService.isInternal ? '1' : '0'; + return isInternalAccount(entitlements?.is_staff, entitlements?.organization_login_list) ? '1' : '0'; case GitHubAssignmentsFilter.GhMsftOrExternal: - return internalOrg ?? 'external'; + return getInternalOrg(entitlements?.organization_login_list) ?? 'external'; + case GitHubAssignmentsFilter.CopilotSku: + return entitlements?.access_type_sku ?? null; + case GitHubAssignmentsFilter.CopilotIsSn: + return tokenInfo?.sn === '1' ? '1' : '0'; + case GitHubAssignmentsFilter.CopilotIsFcv1: + return tokenInfo?.fcv1 === '1' ? '1' : '0'; default: return null; } diff --git a/src/vs/workbench/services/assignment/common/assignmentService.ts b/src/vs/workbench/services/assignment/common/assignmentService.ts index 9317a06bc6a9..f6ddd1b878d1 100644 --- a/src/vs/workbench/services/assignment/common/assignmentService.ts +++ b/src/vs/workbench/services/assignment/common/assignmentService.ts @@ -21,8 +21,8 @@ import { IConfigurationRegistry, Extensions as ConfigurationExtensions, Configur import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js'; import { resolveAmdNodeModulePath } from '../../../../amdX.js'; import { asJson, IRequestService } from '../../../../platform/request/common/request.js'; -import { CancellationToken } from '../../../../base/common/cancellation.js'; -import { RunOnceScheduler, timeout } from '../../../../base/common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; +import { DeferredPromise, disposableTimeout, RunOnceScheduler, timeout } from '../../../../base/common/async.js'; import { StopWatch } from '../../../../base/common/stopwatch.js'; import { CopilotAssignmentFilterProvider, GitHubCoreAssignmentsFilterProvider } from './assignmentFilters.js'; import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js'; @@ -33,6 +33,8 @@ import { experimentsEnabled } from '../../telemetry/common/workbenchTelemetryUti import { CancellationError } from '../../../../base/common/errors.js'; import { mapsStrictEqualIgnoreOrder } from '../../../../base/common/map.js'; import { ILogService } from '../../../../platform/log/common/log.js'; +import { IDefaultAccount } from '../../../../base/common/defaultAccount.js'; +import { isObject } from '../../../../base/common/types.js'; export interface IAssignmentFilter { /** @@ -53,6 +55,13 @@ export const IWorkbenchAssignmentService = createDecorator<IWorkbenchAssignmentS * bare lookup misses. This is an interim workaround until tas-client strips the scope itself. */ const ASSIGNMENTS_SCOPE_PREFIX = '/vscode/'; +const SIGNED_OUT_ASSIGNMENTS_ENDPOINTS = [ + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + 'https://exp.business.githubcopilot.com/api/v1/assignments', + 'https://exp.individual.githubcopilot.com/api/v1/assignments', +]; +const SIGNED_OUT_ASSIGNMENTS_TIMEOUT = 5_000; +const SIGNED_OUT_ASSIGNMENTS_STAGGER = 1_000; /** * Resolves a treatment value preferring the `/vscode/`-scoped key emitted by the new TAS @@ -256,6 +265,9 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen private refetchAfterFilterChange = false; private assignmentsEndpoint: string | undefined; + private signedOutAssignmentsEndpoint: string | undefined; + private assignmentsAccount: IDefaultAccount | null | undefined; + private accountInitialized = false; private networkInitialized = false; private setupGeneration = 0; @@ -290,12 +302,21 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen if (this.experimentsEnabled) { this.tasClient = this.setupTASClient(); - // The assignments endpoint is sourced from account entitlements, which load - // asynchronously. The initial account load resolves the readiness barrier without - // firing onDidChangeDefaultAccount, so proactively re-check once it is ready, and - // again whenever the account changes later. - this.defaultAccountService.getDefaultAccount().then(() => this.recreateTasClientIfEndpointChanged()); - this._register(this.defaultAccountService.onDidChangeDefaultAccount(() => this.recreateTasClientIfEndpointChanged())); + this._register(this.defaultAccountService.onDidChangeDefaultAccount(() => this.recreateTasClientIfAccountChanged())); + this.defaultAccountService.getDefaultAccount().then(() => { + if (!this._store.isDisposed) { + this.accountInitialized = true; + const client = this.tasClient; + this.recreateTasClientIfAccountChanged(); + if (client === this.tasClient && this.defaultAccountService.currentDefaultAccount && !this.assignmentsEndpoint) { + this.logMissingAssignmentsEndpoint(); + } + } + }, error => { + if (!this._store.isDisposed) { + this.logService.error('WorkbenchAssignmentService: Failed to initialize account routing', error); + } + }); // Revoke the final client's wrappers before disposing it. this._register(toDisposable(() => { @@ -380,36 +401,48 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen throw new CancellationError(); } - /** - * Resolves the new TAS assignments API URL from the account entitlements `exp` endpoint, - * or `undefined` when no account/endpoint is available. - */ + /** Signed-out requests discover a reachable endpoint; signed-in routing remains account-specific. */ private getAssignmentsEndpoint(): string | undefined { const account = this.defaultAccountService.currentDefaultAccount; - const endpoints = account?.entitlementsData?.endpoints; - const exp = endpoints?.exp; - if (!exp) { + // A known account can be routed before initialization completes; null is ambiguous until then. + if (!this.accountInitialized && !account) { return undefined; } + if (!account) { + return SIGNED_OUT_ASSIGNMENTS_ENDPOINTS[0]; + } + let exp = account?.entitlementsData?.endpoints?.exp; + if (!exp) { + const plan = account?.entitlementsData?.copilot_plan; + const isIndividual = plan === 'free' || plan === 'individual' || plan?.startsWith('individual_'); + if (this.defaultAccountService.getDefaultAccountAuthenticationProvider().enterprise || account?.enterprise || (account && !isIndividual)) { + return undefined; + } + exp = 'https://exp.individual.githubcopilot.com'; + } return `${exp.replace(/\/+$/, '')}/api/v1/assignments`; } - /** Recreates the TAS client when the resolved assignments endpoint has changed. */ - private recreateTasClientIfEndpointChanged(): void { - if (this._store.isDisposed) { - return; // the service was disposed before the (async) account load resolved + private logMissingAssignmentsEndpoint(): void { + this.logService.warn('WorkbenchAssignmentService: Waiting for an account-provided TAS endpoint from account updates.'); + } + + /** Account changes invalidate new-endpoint assignments even when the endpoint stays the same. */ + private recreateTasClientIfAccountChanged(): void { + if (this._store.isDisposed || !this.accountInitialized) { + return; } const next = this.getAssignmentsEndpoint(); - if (next !== this.assignmentsEndpoint) { + const account = this.defaultAccountService.currentDefaultAccount; + // Without a new endpoint no account identity is sent, so only an endpoint change matters. + const accountChanged = (next !== undefined || this.assignmentsEndpoint !== undefined) + && (account?.sessionId !== this.assignmentsAccount?.sessionId || account?.authenticationProvider.id !== this.assignmentsAccount?.authenticationProvider.id); + if (next !== this.assignmentsEndpoint || accountChanged) { this.tasClient = this.setupTASClient(); } } - /** - * Transport for the new assignments endpoint, backed by the main-process request service - * (avoids renderer CORS). Shape matches tas-client's injectable `assignmentsFetch`. - */ - private readonly assignmentsFetch = async (url: string, init: { method: 'POST'; headers: Record<string, string>; body: string }): Promise<{ status: number; json(): Promise<unknown> }> => { + private readonly assignmentsFetch = async (url: string, init: { method: 'POST'; headers: Record<string, string>; body: string }, token = CancellationToken.None): Promise<{ status: number; json(): Promise<unknown> }> => { const context = await this.requestService.request({ type: init.method, url, @@ -417,13 +450,93 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen headers: init.headers, disableCache: true, callSite: 'assignmentService.assignments', - }, CancellationToken.None); + }, token); return { status: context.res.statusCode ?? 0, json: async () => (await asJson(context)) ?? {}, }; }; + private async fetchSignedOutAssignments(init: Parameters<typeof this.assignmentsFetch>[1], isRevoked: () => boolean): Promise<{ status: number; json(): Promise<unknown> }> { + const preferred = this.signedOutAssignmentsEndpoint; + const endpoints = preferred + ? [preferred, ...SIGNED_OUT_ASSIGNMENTS_ENDPOINTS.filter(endpoint => endpoint !== preferred)] + : SIGNED_OUT_ASSIGNMENTS_ENDPOINTS; + // A remembered host only fails over on errors; time-based hedging is limited to discovery. + const hedge = !preferred; + const disposables = new DisposableStore(); + const cancellation = new CancellationTokenSource(); + disposables.add(toDisposable(() => cancellation.dispose(true))); + const result = new DeferredPromise<{ status: number; json(): Promise<unknown> }>(); + let next = 0; + let pending = 0; + const launchNext = async () => { + if (result.isSettled) { + return; + } + if (isRevoked()) { + result.error(new CancellationError()); + return; + } + const endpoint = endpoints[next++]; + pending++; + if (hedge && next < endpoints.length) { + scheduler.schedule(); + } + try { + const response = await this.assignmentsFetch(endpoint, init, cancellation.token); + if (response.status < 200 || response.status >= 300) { + throw new Error(`TAS returned HTTP ${response.status}`); + } + const data = await response.json(); + const fields = isObject(data) ? data as Record<string, unknown> : undefined; + if (!fields || !isObject(fields.featureVariables) || typeof fields.assignmentContext !== 'string' + || !Object.values(fields.featureVariables).every(value => typeof value === 'string')) { + throw new Error('Invalid TAS assignments response'); + } + if (result.isSettled) { + return; + } + if (isRevoked()) { + throw new CancellationError(); + } + this.signedOutAssignmentsEndpoint = endpoint; + result.complete({ status: response.status, json: async () => data }); + } catch (error) { + if (result.isSettled) { + return; + } + if (isRevoked()) { + result.error(new CancellationError()); + return; + } + this.logService.warn(`WorkbenchAssignmentService: Signed-out TAS request failed at ${endpoint}`, error); + pending--; + if (next < endpoints.length) { + scheduler.cancel(); + void launchNext(); + } else if (pending === 0) { + result.error(new Error('All signed-out TAS endpoints failed')); + } + } + }; + const scheduler = disposables.add(new RunOnceScheduler(() => { void launchNext(); }, SIGNED_OUT_ASSIGNMENTS_STAGGER)); + disposableTimeout(() => { + this.logService.warn('WorkbenchAssignmentService: Signed-out TAS discovery timed out'); + // An unresponsive remembered host never fails over, so rediscover with hedging next time. + if (preferred && this.signedOutAssignmentsEndpoint === preferred) { + this.signedOutAssignmentsEndpoint = undefined; + } + result.error(new Error('Signed-out TAS discovery timed out')); + }, SIGNED_OUT_ASSIGNMENTS_TIMEOUT, disposables); + try { + void launchNext(); + return await result.p; + } finally { + disposables.dispose(); + } + } + private async setupTASClient(): Promise<TASClient> { this.tasSetupDisposables.clear(); this.refetchScheduler.cancel(); @@ -491,30 +604,29 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen this.tasSetupDisposables.add(extensionsFilterProvider); this.tasSetupDisposables.add(extensionsFilterProvider.onDidChangeFilters(() => this.refetchAssignments(true))); - // New TAS assignments API. Its endpoint is sourced from account entitlements and it - // uses dedicated providers that emit the new userParam key names, so the legacy filter - // keys never reach it. Its assignments are merged with the legacy provider's results. + // Both endpoints remain active; the assignments API uses its own userParam names. const assignmentsEndpoint = this.getAssignmentsEndpoint(); + const signedOut = !this.defaultAccountService.currentDefaultAccount; this.assignmentsEndpoint = assignmentsEndpoint; - let assignmentsFilterProviders: IExperimentationFilterProvider[] | undefined; - if (assignmentsEndpoint) { - const coreAssignmentsFilterProvider = new VSCodeCoreAssignmentsFilterProvider( - this.productService.version, - this.productService.nameLong, - this.telemetryService.devDeviceId, - targetPopulation, - this.productService.date ?? '', - this.environmentService.isSessionsWindow ? WindowKind.Agents : WindowKind.Editor - ); - const githubAssignmentsFilterProvider = this.instantiationService.createInstance(GitHubCoreAssignmentsFilterProvider); - this.tasSetupDisposables.add(githubAssignmentsFilterProvider); - this.tasSetupDisposables.add(githubAssignmentsFilterProvider.onDidChangeFilters(() => this.refetchAssignments(true))); - assignmentsFilterProviders = [ - coreAssignmentsFilterProvider, - githubAssignmentsFilterProvider, - { getFilters: () => extensionsFilterProvider.getAssignmentsFilters() }, - ]; + this.assignmentsAccount = this.defaultAccountService.currentDefaultAccount; + if (this.assignmentsAccount && !assignmentsEndpoint) { + this.logMissingAssignmentsEndpoint(); } + const coreAssignmentsFilterProvider = new VSCodeCoreAssignmentsFilterProvider( + this.productService.version, + this.productService.nameLong, + this.telemetryService.devDeviceId, + targetPopulation, + this.productService.date ?? '', + this.environmentService.isSessionsWindow ? WindowKind.Agents : WindowKind.Editor + ); + const githubAssignmentsFilterProvider = this.tasSetupDisposables.add(this.instantiationService.createInstance(GitHubCoreAssignmentsFilterProvider)); + this.tasSetupDisposables.add(githubAssignmentsFilterProvider.onDidChangeFilters(() => this.refetchAssignments(true))); + const assignmentsFilterProviders: IExperimentationFilterProvider[] = [ + coreAssignmentsFilterProvider, + githubAssignmentsFilterProvider, + { getFilters: () => extensionsFilterProvider.getAssignmentsFilters() }, + ]; const tasConfig = this.productService.tasConfig!; @@ -538,12 +650,13 @@ export class WorkbenchAssignmentService extends Disposable implements IAssignmen endpoint: tasConfig.endpoint, extensionName: 'vscode-core', assignmentsEndpoint, - assignmentsFilterProviders, - // Route the assignments request through the main-process request service so it is - // not subject to renderer CORS (parity with how core reaches api.github.com). - assignmentsFetch: assignmentsEndpoint - ? (url, init) => (revoked ? Promise.resolve({ status: 0, json: async () => ({}) }) : service.assignmentsFetch(url, init)) - : undefined, + assignmentsFilterProviders: assignmentsEndpoint ? assignmentsFilterProviders : undefined, + assignmentsFetch: (url, init) => { + if (revoked) { + throw new CancellationError(); + } + return signedOut ? service.fetchSignedOutAssignments(init, () => revoked) : service.assignmentsFetch(url, init); + }, // TAS polling only updates persistent storage after treatments have been consumed. refetchInterval: 0, }); diff --git a/src/vs/workbench/services/assignment/test/browser/assignmentService.test.ts b/src/vs/workbench/services/assignment/test/browser/assignmentService.test.ts index ebdc291251e5..2b35f0af4d05 100644 --- a/src/vs/workbench/services/assignment/test/browser/assignmentService.test.ts +++ b/src/vs/workbench/services/assignment/test/browser/assignmentService.test.ts @@ -7,41 +7,62 @@ import assert from 'assert'; import * as sinon from 'sinon'; import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; import { bufferToStream, VSBuffer } from '../../../../../base/common/buffer.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { ICopilotTokenInfo, IDefaultAccount, IEntitlementsData } from '../../../../../base/common/defaultAccount.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; -import { IRequestOptions } from '../../../../../base/parts/request/common/request.js'; +import { IRequestContext, IRequestOptions } from '../../../../../base/parts/request/common/request.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { runWithFakedTimers } from '../../../../../base/test/common/virtualScheduling/index.js'; -import { ASSIGNMENT_REFETCH_INTERVAL } from '../../../../../platform/assignment/common/assignment.js'; +import { ASSIGNMENT_REFETCH_INTERVAL, ASSIGNMENT_STORAGE_KEY } from '../../../../../platform/assignment/common/assignment.js'; import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; +import { COPILOT_INTEGRATION_ID } from '../../../../../platform/endpoint/common/licenseAgreement.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IRequestService } from '../../../../../platform/request/common/request.js'; -import { InMemoryStorageService, IStorageService } from '../../../../../platform/storage/common/storage.js'; +import { InMemoryStorageService, IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; import { NullTelemetryService } from '../../../../../platform/telemetry/common/telemetryUtils.js'; import { IChatEntitlementService } from '../../../chat/common/chatEntitlementService.js'; import { IWorkbenchEnvironmentService } from '../../../environment/common/environmentService.js'; import { IExtensionService } from '../../../extensions/common/extensions.js'; import { WorkbenchAssignmentService } from '../../common/assignmentService.js'; +import { Memento } from '../../../../common/memento.js'; // The real TAS client loads through the workbench's browser URL resolver, so these tests need a browser loader. suite('WorkbenchAssignmentService polling', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); const treatmentName = 'config.test.polling'; + setup(() => Memento.clear(StorageScope.APPLICATION)); + teardown(() => Memento.clear(StorageScope.APPLICATION)); + const signedOutEndpoints = [ + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + 'https://exp.business.githubcopilot.com/api/v1/assignments', + 'https://exp.individual.githubcopilot.com/api/v1/assignments', + ]; + + function response(status: number, body: string): IRequestContext { + return { res: { headers: {}, statusCode: status }, stream: bufferToStream(VSBuffer.fromString(body)) }; + } /* eslint-disable local/code-no-bracket-notation-for-identifiers -- Await client readiness and exercise refresh races without public test-only APIs. */ - function createService(enabled = true) { + function createService(enabled = true, accountState: 'signedIn' | 'signedOut' | 'missingEndpoint' = 'signedIn', options: { endpoint?: string; plan?: string; enterprise?: boolean; accountReady?: DeferredPromise<void>; cached?: Record<string, string | number | boolean>; aiDisabled?: boolean; telemetryLevel?: 'all' | 'error' | 'crash' | 'off' } = {}) { const instantiationService = store.add(new TestInstantiationService()); - const configuration = new TestConfigurationService({ 'workbench.enableExperiments': enabled, 'telemetry.telemetryLevel': 'all' }); + const configuration = new TestConfigurationService({ 'workbench.enableExperiments': enabled, 'telemetry.telemetryLevel': options.telemetryLevel ?? 'all', 'chat.disableAIFeatures': options.aiDisabled ?? false }); store.add(configuration.onDidChangeConfigurationEmitter); instantiationService.stub(IConfigurationService, configuration); - instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); + const storage = store.add(new InMemoryStorageService()); + instantiationService.stub(IStorageService, storage); + if (options.cached) { + const memento = new Memento<Record<string, unknown>>('experiment.service.memento', storage); + memento.getMemento(StorageScope.APPLICATION, StorageTarget.MACHINE)[ASSIGNMENT_STORAGE_KEY] = { + features: [], assignmentContext: 'cached-context', configs: [{ Id: 'vscode', Parameters: options.cached }], + }; + } instantiationService.stub(ITelemetryService, NullTelemetryService); instantiationService.stub(IProductService, { version: '1.100.0', nameLong: 'Test', quality: 'insider', @@ -60,18 +81,35 @@ suite('WorkbenchAssignmentService polling', () => { }())); const accountChanged = store.add(new Emitter<IDefaultAccount | null>()); const entitlements = new class extends mock<IEntitlementsData>() { - override endpoints = { exp: 'https://assignments.example.com' }; + override endpoints = accountState === 'missingEndpoint' ? undefined : { exp: options.endpoint ?? 'https://assignments.example.com' }; + override copilot_plan = options.plan ?? 'individual'; + override access_type_sku = 'pro'; + override analytics_tracking_id = 'account-user'; + override is_staff = false; }(); + const authenticationProvider = { id: options.enterprise ? 'github-enterprise' : 'github', name: 'GitHub', enterprise: options.enterprise ?? false }; const account = new class extends mock<IDefaultAccount>() { + override readonly sessionId = 'account-session'; + override readonly authenticationProvider = authenticationProvider; + override readonly enterprise = authenticationProvider.enterprise; override readonly entitlementsData = entitlements; }(); const tokenChanged = store.add(new Emitter<ICopilotTokenInfo | null>()); + let refreshAccount = () => { }; const defaultAccountService = new class extends mock<IDefaultAccountService>() { - override readonly currentDefaultAccount = account; + override currentDefaultAccount: IDefaultAccount | null = accountState === 'signedOut' ? null : account; override readonly onDidChangeDefaultAccount = accountChanged.event; override copilotTokenInfo: ICopilotTokenInfo | null = { sn: '0' }; override readonly onDidChangeCopilotTokenInfo = tokenChanged.event; - override async getDefaultAccount() { return account; } + override async getDefaultAccount() { + await options.accountReady?.p; + return this.currentDefaultAccount; + } + override getDefaultAccountAuthenticationProvider() { return authenticationProvider; } + override async refresh() { + refreshAccount(); + return this.currentDefaultAccount; + } }(); instantiationService.stub(IDefaultAccountService, defaultAccountService); instantiationService.stub(IExtensionService, new class extends mock<IExtensionService>() { @@ -83,17 +121,26 @@ suite('WorkbenchAssignmentService polling', () => { override readonly onDidChangeEntitlement = entitlementChanged.event; override sku = 'pro'; override isInternal = false; + override copilotTrackingId = 'stale-chat-user'; }(); instantiationService.stub(IChatEntitlementService, chatEntitlementService); let value: string | undefined = 'initial'; const requestedFilters: Record<string, string>[] = []; + const requestedHeaders: IRequestOptions['headers'][] = []; + const requestedUrls: (string | undefined)[] = []; let waitForResponse = async () => { }; + let respond: ((options: IRequestOptions, token: CancellationToken) => Promise<IRequestContext>) | undefined; instantiationService.stub(IRequestService, new class extends mock<IRequestService>() { - override async request(options: IRequestOptions) { + override async request(options: IRequestOptions, token: CancellationToken) { assert.ok(options.data); const body: { userParams: Record<string, string> } = JSON.parse(options.data); requestedFilters.push(body.userParams); + requestedHeaders.push(options.headers); + requestedUrls.push(options.url); + if (respond) { + return respond(options, token); + } const response = { featureVariables: value === undefined ? {} : { [`/vscode/${treatmentName}`]: value }, assignmentContext: 'unchanged-context', @@ -104,6 +151,7 @@ suite('WorkbenchAssignmentService polling', () => { }()); const service = store.add(instantiationService.createInstance(WorkbenchAssignmentService)); const ready = async () => { + await defaultAccountService.getDefaultAccount(); const client = await service['tasClient']; await client?.initialFetch; await service['refetchPromise']; @@ -111,10 +159,12 @@ suite('WorkbenchAssignmentService polling', () => { return client; }; return { - service, ready, errors, requestedFilters, + service, ready, errors, requestedFilters, requestedHeaders, requestedUrls, entitlements, requests: () => requestedFilters.length, setValue: (next: string | undefined) => { value = next; }, setWaitForResponse: (wait: () => Promise<void>) => { waitForResponse = wait; }, + setResponse: (next: typeof respond) => { respond = next; }, + setRefreshAccount: (refresh: () => void) => { refreshAccount = refresh; }, changeFilters: (kind: 'sku' | 'token' | 'staff', updated: boolean) => { if (kind === 'token') { defaultAccountService.copilotTokenInfo = { sn: updated ? '1' : '0' }; @@ -122,19 +172,422 @@ suite('WorkbenchAssignmentService polling', () => { } else { if (kind === 'sku') { chatEntitlementService.sku = updated ? 'business' : 'pro'; + entitlements.access_type_sku = chatEntitlementService.sku; } else { chatEntitlementService.isInternal = updated; + entitlements.is_staff = updated; } entitlementChanged.fire(); + accountChanged.fire(defaultAccountService.currentDefaultAccount); } }, changeEndpoint: () => { entitlements.endpoints = { exp: 'https://replacement.example.com' }; accountChanged.fire(account); }, + changeAccount: (exp: string | null | undefined) => { + entitlements.endpoints = exp ? { exp } : undefined; + defaultAccountService.currentDefaultAccount = exp === null ? null : account; + accountChanged.fire(defaultAccountService.currentDefaultAccount); + }, }; } + for (const accountState of ['signedIn', 'signedOut'] as const) { + test(`keeps integrator targeting in the body with CORS-compatible headers (${accountState})`, async () => { + const { service, ready, requestedFilters, requestedHeaders } = createService(true, accountState); + await ready(); + assert.deepStrictEqual({ + treatment: await service.getTreatment(treatmentName), + integratorIds: requestedFilters.map(filters => filters.integratorid), + headers: requestedHeaders, + }, { + treatment: 'initial', + integratorIds: [COPILOT_INTEGRATION_ID], + headers: [{ 'Content-Type': 'application/json' }], + }); + }); + } + + test('serves cached treatments before account discovery without calling a new endpoint', () => runWithFakedTimers({}, async () => { + const accountReady = new DeferredPromise<void>(); + const { service, ready, requestedUrls, requestedFilters, changeAccount } = createService(true, 'signedOut', { + accountReady, + cached: { [`/vscode/${treatmentName}`]: false, '/vscode/config.test.zero': 0 }, + }); + try { + const value = await service.getTreatment(treatmentName); + const assignment = await service.getTreatmentWithAssignment('config.test.zero'); + const pending = { requests: requestedUrls.length, value, assignedValue: assignment.value, hasAssignment: await assignment.hasAssignment }; + changeAccount('https://exp.business.githubcopilot.com'); + await accountReady.complete(); + await ready(); + assert.deepStrictEqual({ pending, urls: requestedUrls, trackingIds: requestedFilters.map(filters => filters.copilottrackingid) }, { + pending: { requests: 0, value: false, assignedValue: 0, hasAssignment: true }, + urls: ['https://exp.business.githubcopilot.com/api/v1/assignments'], + trackingIds: ['account-user'], + }); + } finally { + service.dispose(); + await accountReady.complete(); + } + })); + + for (const { experiments, telemetryLevel } of [ + { experiments: true, telemetryLevel: 'all' }, + { experiments: false, telemetryLevel: 'all' }, + { experiments: true, telemetryLevel: 'error' }, + { experiments: true, telemetryLevel: 'crash' }, + { experiments: true, telemetryLevel: 'off' }, + ] as const) { + test(`AI-disabled discovery respects experiments=${experiments}, telemetry=${telemetryLevel}`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, requestedFilters } = createService(experiments, 'signedOut', { aiDisabled: true, telemetryLevel }); + try { + await ready(); + const enabled = experiments && telemetryLevel === 'all'; + if (!enabled) { + await timeout(ASSIGNMENT_REFETCH_INTERVAL * 2); + } + assert.deepStrictEqual({ + urls: requestedUrls, + accountIdentities: requestedFilters.map(filters => filters.copilottrackingid), + hasClient: !!service['tasClient'], + polling: service['refetchScheduler'].isScheduled(), + }, { + urls: enabled ? [signedOutEndpoints[0]] : [], + accountIdentities: enabled ? [undefined] : [], + hasClient: enabled, + polling: enabled, + }); + } finally { + service.dispose(); + } + })); + } + + for (const endpoint of ['https://exp.individual.githubcopilot.com', 'https://exp.business.githubcopilot.com']) { + test(`clears account filters and refetches on sign-out from ${endpoint}`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, requestedFilters, changeAccount, entitlements } = createService(true, 'signedIn', { endpoint }); + entitlements.access_type_sku = ''; + try { + await ready(); + changeAccount(null); + await ready(); + assert.deepStrictEqual({ + urls: requestedUrls, + identity: requestedFilters.map(filters => ({ tid: filters.copilottrackingid, sku: filters.github_core_copilotsku })), + }, { + urls: [`${endpoint}/api/v1/assignments`, signedOutEndpoints[0]], + identity: [{ tid: 'account-user', sku: undefined }, { tid: undefined, sku: undefined }], + }); + } finally { + service.dispose(); + } + })); + } + + for (const { accountState, plan, enterprise } of [ + { accountState: 'missingEndpoint', plan: 'business', enterprise: false }, + { accountState: 'missingEndpoint', plan: 'enterprise', enterprise: false }, + { accountState: 'missingEndpoint', plan: 'unknown', enterprise: false }, + { accountState: 'missingEndpoint', plan: 'individual', enterprise: true }, + ] as const) { + test(`does not use public fallback for ${accountState}, ${plan}, enterprise=${enterprise}`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls } = createService(true, accountState, { plan, enterprise }); + try { + await ready(); + assert.deepStrictEqual(requestedUrls, []); + } finally { + service.dispose(); + } + })); + } + + test('uses account updates without forcing entitlements on hourly or filter-driven refresh', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, changeAccount, changeFilters, setRefreshAccount } = createService(true, 'missingEndpoint', { plan: 'enterprise' }); + try { + await ready(); + let discoveries = 0; + setRefreshAccount(() => { + discoveries++; + }); + await timeout(ASSIGNMENT_REFETCH_INTERVAL); + await ready(); + changeFilters('sku', true); + await timeout(1); + await ready(); + changeAccount('https://exp.enterprise.githubcopilot.com'); + await ready(); + assert.deepStrictEqual({ discoveries, urls: requestedUrls }, { + discoveries: 0, + urls: ['https://exp.enterprise.githubcopilot.com/api/v1/assignments'], + }); + } finally { + service.dispose(); + } + })); + + for (const accountState of ['signedOut', 'missingEndpoint'] as const) { + test(`merges new TAS and legacy treatments when ${accountState}`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls } = createService(true, accountState); + try { + const client = (await ready())!; + // Stub only the legacy provider: Electron's Node HTTP transport cannot fetch the data URL fixture. + const legacy = sinon.stub(client['featureProviders']![0], 'getFeatures').resolves({ + features: [], + assignmentContext: 'legacy-context', + configs: [{ Id: 'vscode', Parameters: { [treatmentName]: 'legacy', 'config.test.legacyOnly': 'legacy-only' } }], + }); + store.add(toDisposable(() => legacy.restore())); + await service['refetchAssignments'](); + assert.deepStrictEqual({ + urls: requestedUrls, + merged: await service.getTreatment(treatmentName), + legacyOnly: await service.getTreatment('config.test.legacyOnly'), + }, { + urls: Array(2).fill(accountState === 'signedOut' ? signedOutEndpoints[0] : signedOutEndpoints[2]), + merged: 'initial', + legacyOnly: 'legacy-only', + }); + } finally { + service.dispose(); + } + })); + } + + test('switches between discovered and account routing even on the same host', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, changeAccount, setValue } = createService(true, 'signedOut'); + try { + await ready(); + const values = [await service.getTreatment(treatmentName)]; + setValue('signed-in'); + changeAccount('https://exp.enterprise.githubcopilot.com///'); + await ready(); + values.push(await service.getTreatment(treatmentName)); + setValue('signed-out'); + changeAccount(null); + await ready(); + values.push(await service.getTreatment(treatmentName)); + assert.deepStrictEqual({ urls: requestedUrls, values }, { + urls: [ + signedOutEndpoints[0], + 'https://exp.enterprise.githubcopilot.com/api/v1/assignments', + signedOutEndpoints[0], + ], + values: ['initial', 'signed-in', 'signed-out'], + }); + } finally { + service.dispose(); + } + })); + + for (const failure of ['network', 'http', 'json', 'schema', 'timeout'] as const) { + test(`signed-out discovery advances after ${failure} failure and reuses a valid empty response`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, requestedFilters, setResponse } = createService(true, 'signedOut', { enterprise: true }); + let aborted = false; + setResponse(async (options, token) => { + if (options.url === signedOutEndpoints[0]) { + switch (failure) { + case 'network': throw new Error('Blocked'); + case 'http': return response(403, 'Forbidden'); + case 'json': return response(200, '<html>Blocked</html>'); + case 'schema': return response(200, '{"featureVariables":[],"assignmentContext":""}'); + case 'timeout': { + return new Promise<IRequestContext>((_resolve, reject) => { + const listener = token.onCancellationRequested(() => { + aborted = true; + listener.dispose(); + reject(new Error('Aborted')); + }); + store.add(listener); + }); + } + } + } + return response(200, '{"featureVariables":{},"assignmentContext":""}'); + }); + try { + await ready(); + await service['refetchAssignments'](); + assert.deepStrictEqual({ + urls: requestedUrls, + identities: requestedFilters.map(filters => filters.copilottrackingid), + value: await service.getTreatment(treatmentName), + aborted, + }, { + urls: [signedOutEndpoints[0], signedOutEndpoints[1], signedOutEndpoints[1]], + identities: [undefined, undefined, undefined], + value: undefined, + aborted: failure === 'timeout', + }); + } finally { + service.dispose(); + } + })); + } + + for (const winner of [0, 1, 2, undefined] as const) { + test(`staggers discovery and cancels outstanding work with ${winner === undefined ? 'a shared deadline' : `winner ${winner}`}`, () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, setResponse } = createService(true, 'signedOut'); + const starts: number[] = []; + const cancelled: (string | undefined)[] = []; + setResponse(async (options, token) => { + starts.push(Date.now()); + if (winner !== undefined && options.url === signedOutEndpoints[winner]) { + return response(200, '{"featureVariables":{},"assignmentContext":""}'); + } + return new Promise<IRequestContext>((_resolve, reject) => { + const listener = store.add(token.onCancellationRequested(() => { + cancelled.push(options.url); + listener.dispose(); + reject(new Error('Aborted')); + })); + }); + }); + try { + await ready(); + const elapsed = Date.now() - starts[0]; + await timeout(1000); + const count = winner === undefined ? 3 : winner + 1; + assert.deepStrictEqual({ + urls: requestedUrls, + starts: starts.map(start => start - starts[0]), + elapsed, + cancelled, + }, { + urls: signedOutEndpoints.slice(0, count), + starts: [0, 1000, 2000].slice(0, count), + elapsed: winner === undefined ? 5000 : winner * 1000, + cancelled: signedOutEndpoints.slice(0, winner ?? 3), + }); + } finally { + service.dispose(); + } + })); + } + + test('does not hedge a remembered host and rediscovers after it stops responding', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, setResponse } = createService(true, 'signedOut'); + let hangPreferred = false; + setResponse(async (options, token) => { + if (hangPreferred && options.url === signedOutEndpoints[0]) { + return new Promise<IRequestContext>((_resolve, reject) => { + const listener = store.add(token.onCancellationRequested(() => { + listener.dispose(); + reject(new Error('Aborted')); + })); + }); + } + return response(200, '{"featureVariables":{},"assignmentContext":""}'); + }); + try { + await ready(); + hangPreferred = true; + await service['refetchAssignments'](); + await service['refetchAssignments'](); + assert.deepStrictEqual(requestedUrls, [signedOutEndpoints[0], signedOutEndpoints[0], signedOutEndpoints[0], signedOutEndpoints[1]]); + } finally { + service.dispose(); + } + })); + + for (const { name, accountState, plan, resolvesLate, urls } of [ + { name: 'a managed account without an endpoint resolves after startup', accountState: 'signedOut', plan: 'enterprise', resolvesLate: true, urls: [] }, + { name: 'an account with an endpoint is known before initialization', accountState: 'signedIn', plan: 'individual', resolvesLate: false, urls: ['https://assignments.example.com/api/v1/assignments'] }, + ] as const) { + test(`creates a single client when ${name}`, () => runWithFakedTimers({}, async () => { + const accountReady = new DeferredPromise<void>(); + const { service, ready, requestedUrls, changeAccount } = createService(true, accountState, { plan, accountReady }); + try { + if (resolvesLate) { + changeAccount(undefined); + } + await accountReady.complete(); + await ready(); + assert.deepStrictEqual({ clients: service['setupGeneration'], urls: requestedUrls }, { clients: 1, urls }); + } finally { + service.dispose(); + await accountReady.complete(); + } + })); + } + + test('a late successful loser cannot replace the remembered winner', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, setResponse } = createService(true, 'signedOut'); + const late = new DeferredPromise<IRequestContext>(); + setResponse(async options => options.url === signedOutEndpoints[0] + ? late.p + : response(200, '{"featureVariables":{},"assignmentContext":""}')); + try { + await ready(); + await late.complete(response(200, '{"featureVariables":{},"assignmentContext":""}')); + await timeout(0); + await service['refetchAssignments'](); + assert.deepStrictEqual(requestedUrls, [signedOutEndpoints[0], signedOutEndpoints[1], signedOutEndpoints[1]]); + } finally { + service.dispose(); + await late.complete(response(503, 'Unavailable')); + } + })); + + test('tries each signed-out host once, retries after total failure, and replaces a failed preferred host', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, setResponse, changeAccount } = createService(true, 'signedOut'); + let workingEndpoint: string | undefined; + setResponse(async options => options.url === workingEndpoint + ? response(200, '{"featureVariables":{},"assignmentContext":""}') + : response(503, 'Unavailable')); + try { + await ready(); + workingEndpoint = signedOutEndpoints[2]; + await timeout(ASSIGNMENT_REFETCH_INTERVAL); + await ready(); + workingEndpoint = signedOutEndpoints[1]; + await service['refetchAssignments'](); + await service['refetchAssignments'](); + const discovered = requestedUrls.slice(); + changeAccount(signedOutEndpoints[2].replace('/api/v1/assignments', '')); + await ready(); + assert.deepStrictEqual({ discovered, signedIn: requestedUrls.slice(discovered.length) }, { + discovered: [ + ...signedOutEndpoints, ...signedOutEndpoints, + signedOutEndpoints[2], signedOutEndpoints[0], signedOutEndpoints[1], signedOutEndpoints[1], + ], + signedIn: [signedOutEndpoints[2]], + }); + } finally { + service.dispose(); + } + })); + + test('stops anonymous discovery when sign-in supersedes an in-flight attempt', () => runWithFakedTimers({}, async () => { + const { service, ready, requestedUrls, requestedFilters, setResponse, changeAccount } = createService(true, 'signedOut'); + const pending = new DeferredPromise<IRequestContext>(); + const started = new DeferredPromise<void>(); + setResponse(async () => { + await started.complete(); + return pending.p; + }); + try { + const initial = ready(); + await started.p; + setResponse(undefined); + changeAccount('https://exp.individual.githubcopilot.com'); + await ready(); + await pending.complete(response(503, 'Unavailable')); + await initial; + assert.deepStrictEqual({ + urls: requestedUrls, + identities: requestedFilters.map(filters => filters.copilottrackingid), + }, { + urls: [signedOutEndpoints[0], signedOutEndpoints[2]], + identities: [undefined, 'account-user'], + }); + } finally { + service.dispose(); + await pending.complete(response(503, 'Unavailable')); + } + })); + test('refreshes consumed values every hour and publishes assignment removal with unchanged context', () => runWithFakedTimers({}, async () => { const { service, ready, requests, setValue } = createService(); try { @@ -393,7 +846,7 @@ suite('WorkbenchAssignmentService polling', () => { })); test('does not start a client or polling when experiments are disabled', () => runWithFakedTimers({}, async () => { - const { service, ready, requests } = createService(false); + const { service, ready, requests } = createService(false, 'signedOut'); try { await ready(); await timeout(ASSIGNMENT_REFETCH_INTERVAL * 2); diff --git a/src/vs/workbench/services/assignment/test/common/assignmentFilters.test.ts b/src/vs/workbench/services/assignment/test/common/assignmentFilters.test.ts index 71addf6ed84e..ea1db0d40a8d 100644 --- a/src/vs/workbench/services/assignment/test/common/assignmentFilters.test.ts +++ b/src/vs/workbench/services/assignment/test/common/assignmentFilters.test.ts @@ -4,11 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { ICopilotTokenInfo } from '../../../../../base/common/defaultAccount.js'; +import { ICopilotTokenInfo, IDefaultAccount, IEntitlementsData } from '../../../../../base/common/defaultAccount.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { Lazy } from '../../../../../base/common/lazy.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { isInternalAccount } from '../../../../../platform/assignment/common/assignment.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { IExtensionDescription } from '../../../../../platform/extensions/common/extensions.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; @@ -23,6 +22,18 @@ suite('CopilotAssignmentFilterProvider', () => { const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + class TestDefaultAccountService extends mock<IDefaultAccountService>() { + private readonly _onDidChangeCopilotTokenInfo = disposables.add(new Emitter<ICopilotTokenInfo | null>()); + override readonly onDidChangeCopilotTokenInfo = this._onDidChangeCopilotTokenInfo.event; + + override copilotTokenInfo: ICopilotTokenInfo | null = null; + + setCopilotTokenInfo(tokenInfo: ICopilotTokenInfo | null): void { + this.copilotTokenInfo = tokenInfo; + this._onDidChangeCopilotTokenInfo.fire(tokenInfo); + } + } + test('initializes entitlement filters before subscribing to entitlement changes', () => { const onDidChangeEntitlement = disposables.add(new Emitter<void>()); const chatEntitlementService = new class extends mock<IChatEntitlementService>() { @@ -39,10 +50,7 @@ suite('CopilotAssignmentFilterProvider', () => { return this.trackingId.value; } }(); - const defaultAccountService = new class extends mock<IDefaultAccountService>() { - override readonly copilotTokenInfo = null; - override readonly onDidChangeCopilotTokenInfo = Event.None; - }(); + const defaultAccountService = new TestDefaultAccountService(); const instantiationService = disposables.add(new TestInstantiationService()); instantiationService.stub(IExtensionService, new TestExtensionService()); instantiationService.stub(ILogService, new NullLogService()); @@ -55,19 +63,16 @@ suite('CopilotAssignmentFilterProvider', () => { assert.strictEqual(provider.getFilterValue(ExtensionsFilter.CopilotTrackingId), 'tracking-id'); }); - test('maps available Copilot filters to new TAS names and refreshes their values', async () => { + test('maps extension versions without forwarding cached account filters to new TAS', async () => { const onDidChangeEntitlement = disposables.add(new Emitter<void>()); - const onDidChangeCopilotTokenInfo = disposables.add(new Emitter<ICopilotTokenInfo | null>()); const entitlement = new class extends mock<IChatEntitlementService>() { override readonly onDidChangeEntitlement = onDidChangeEntitlement.event; override sku: string | undefined = 'pro'; override readonly organisations = undefined; override readonly copilotTrackingId = undefined; }(); - const account = new class extends mock<IDefaultAccountService>() { - override copilotTokenInfo: ICopilotTokenInfo | null = { sn: '1', fcv1: '1' }; - override readonly onDidChangeCopilotTokenInfo = onDidChangeCopilotTokenInfo.event; - }(); + const account = new TestDefaultAccountService(); + account.copilotTokenInfo = { sn: '1', fcv1: '1' }; const extension = new class extends mock<IExtensionDescription>() { override readonly version = '0.68.0-insider'; }(); @@ -89,18 +94,15 @@ suite('CopilotAssignmentFilterProvider', () => { const initial = Object.fromEntries(provider.getAssignmentsFilters()); let changes = 0; disposables.add(provider.onDidChangeFilters(() => changes++)); - account.copilotTokenInfo = { sn: '1', fcv1: '0' }; - onDidChangeCopilotTokenInfo.fire(account.copilotTokenInfo); + account.setCopilotTokenInfo({ sn: '1', fcv1: '0' }); const fcv1Changed = Object.fromEntries(provider.getAssignmentsFilters()); entitlement.sku = 'enterprise'; onDidChangeEntitlement.fire(); - account.copilotTokenInfo = { sn: '0' }; - onDidChangeCopilotTokenInfo.fire(account.copilotTokenInfo); + account.setCopilotTokenInfo({ sn: '0' }); const refreshed = Object.fromEntries(provider.getAssignmentsFilters()); entitlement.sku = undefined; onDidChangeEntitlement.fire(); - account.copilotTokenInfo = null; - onDidChangeCopilotTokenInfo.fire(account.copilotTokenInfo); + account.setCopilotTokenInfo(null); assert.deepStrictEqual({ initial, @@ -113,101 +115,149 @@ suite('CopilotAssignmentFilterProvider', () => { provider.getFilterValue(ExtensionsFilter.CopilotSku), provider.getFilterValue(ExtensionsFilter.CopilotIsSn), provider.getFilterValue(ExtensionsFilter.CopilotIsFcv1), + provider.getFilterValue(ExtensionsFilter.CopilotIsProxima), ], }, { initial: { - github_core_copilotsku: 'pro', - github_core_issn: '1', - github_core_isfcv1: '1', vscode_core_copilotchatextensionversion: '0.68.0', }, fcv1Changed: { - github_core_copilotsku: 'pro', - github_core_issn: '1', - github_core_isfcv1: '0', vscode_core_copilotchatextensionversion: '0.68.0', }, refreshed: { - github_core_copilotsku: 'enterprise', - github_core_issn: '0', - github_core_isfcv1: '0', vscode_core_copilotchatextensionversion: '0.68.0', }, signedOut: { - github_core_copilotsku: null, - github_core_issn: '0', - github_core_isfcv1: '0', vscode_core_copilotchatextensionversion: '0.68.0', }, changes: 4, - legacy: ['0.68.0', null, '0', '0'], + legacy: ['0.68.0', null, '0', '0', '0'], }); }); -}); -suite('GitHubCoreAssignmentsFilterProvider', () => { + test('classifies Proxima from the token stamp and fails closed while it is unresolved', () => { + const entitlement = new class extends mock<IChatEntitlementService>() { + override readonly onDidChangeEntitlement = Event.None; + override readonly organisations = undefined; + override readonly copilotTrackingId = undefined; + }(); + const account = new TestDefaultAccountService(); + const extensionService = new class extends mock<IExtensionService>() { + override readonly onDidChangeExtensionsStatus = Event.None; + override async getExtension(): Promise<undefined> { + return undefined; + } + }(); + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IExtensionService, extensionService); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IStorageService, disposables.add(new InMemoryStorageService())); + instantiationService.stub(IChatEntitlementService, entitlement); + instantiationService.stub(IDefaultAccountService, account); - const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const provider = disposables.add(instantiationService.createInstance(CopilotAssignmentFilterProvider)); + let changes = 0; + disposables.add(provider.onDidChangeFilters(() => changes++)); + const values = [provider.getFilterValue(ExtensionsFilter.CopilotIsProxima)]; + account.setCopilotTokenInfo({ st: 'dotcom' }); + values.push(provider.getFilterValue(ExtensionsFilter.CopilotIsProxima)); + account.setCopilotTokenInfo({ st: 'proxima' }); + values.push(provider.getFilterValue(ExtensionsFilter.CopilotIsProxima)); + account.setCopilotTokenInfo({}); + values.push(provider.getFilterValue(ExtensionsFilter.CopilotIsProxima)); + account.setCopilotTokenInfo(null); + values.push(provider.getFilterValue(ExtensionsFilter.CopilotIsProxima)); - class TestChatEntitlementService extends mock<IChatEntitlementService>() { - private readonly _onDidChangeEntitlement = disposables.add(new Emitter<void>()); - override readonly onDidChangeEntitlement = this._onDidChangeEntitlement.event; + assert.deepStrictEqual({ + values, + changes, + assignmentsFilters: Object.fromEntries(provider.getAssignmentsFilters()), + }, { + values: ['0', '0', '1', '0', '0'], + changes: 2, + assignmentsFilters: { + vscode_core_copilotchatextensionversion: null, + }, + }); + }); +}); - override copilotTrackingId: string | undefined; - override organisations: string[] | undefined; - isStaff: boolean | undefined; +suite('GitHubCoreAssignmentsFilterProvider', () => { - override get isInternal(): boolean { - return isInternalAccount(this.isStaff, this.organisations); - } + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); - fireChange(): void { - this._onDidChangeEntitlement.fire(); + class TestDefaultAccountService extends mock<IDefaultAccountService>() { + private readonly accountChanged = disposables.add(new Emitter<IDefaultAccount | null>()); + override readonly onDidChangeDefaultAccount = this.accountChanged.event; + override readonly onDidChangeCopilotTokenInfo = Event.None; + override copilotTokenInfo: ICopilotTokenInfo | null = null; + override currentDefaultAccount: IDefaultAccount | null = null; + + setEntitlements(entitlements?: Partial<IEntitlementsData>): void { + this.currentDefaultAccount = entitlements ? new class extends mock<IDefaultAccount>() { + override readonly entitlementsData = Object.assign(new class extends mock<IEntitlementsData>() { }(), entitlements); + }() : null; + this.accountChanged.fire(this.currentDefaultAccount); } } - function createProvider(entitlement: TestChatEntitlementService): GitHubCoreAssignmentsFilterProvider { + function createProvider(account: TestDefaultAccountService): GitHubCoreAssignmentsFilterProvider { const instantiationService = disposables.add(new TestInstantiationService()); - instantiationService.stub(IChatEntitlementService, entitlement); + instantiationService.stub(IDefaultAccountService, account); return disposables.add(instantiationService.createInstance(GitHubCoreAssignmentsFilterProvider)); } test('emits the core GitHub assignment filters map', () => { - const entitlement = new TestChatEntitlementService(); - entitlement.copilotTrackingId = 'tid-1'; - entitlement.organisations = ['github']; - - const provider = createProvider(entitlement); + const account = new TestDefaultAccountService(); + account.setEntitlements({ analytics_tracking_id: 'tid-1', organization_login_list: ['github'], access_type_sku: 'pro' }); + account.copilotTokenInfo = { sn: '1', fcv1: '0' }; + const provider = createProvider(account); const filters = provider.getFilters(); assert.deepStrictEqual([...filters.entries()], [ [GitHubAssignmentsFilter.CopilotTrackingId, 'tid-1'], [GitHubAssignmentsFilter.IsGhOrMsftStaff, '1'], [GitHubAssignmentsFilter.GhMsftOrExternal, 'github'], + [GitHubAssignmentsFilter.CopilotSku, 'pro'], + [GitHubAssignmentsFilter.CopilotIsSn, '1'], + [GitHubAssignmentsFilter.CopilotIsFcv1, '0'], ]); }); - test('latches a late tracking id and keeps it after it becomes unavailable', () => { - const entitlement = new TestChatEntitlementService(); - entitlement.organisations = undefined; - - const provider = createProvider(entitlement); - - // Not yet available during sign-in delay. - assert.strictEqual(provider.getFilterValue(GitHubAssignmentsFilter.CopilotTrackingId), null); - - // Becomes available later. - entitlement.copilotTrackingId = 'tid-late'; - assert.strictEqual(provider.getFilterValue(GitHubAssignmentsFilter.CopilotTrackingId), 'tid-late'); + test('clears account filters on sign-out even before token info is cleared', () => { + const account = new TestDefaultAccountService(); + account.setEntitlements({ analytics_tracking_id: 'old-user', access_type_sku: 'enterprise', organization_login_list: ['github'] }); + account.copilotTokenInfo = { sn: '1', fcv1: '1' }; + const provider = createProvider(account); + let changes = 0; + disposables.add(provider.onDidChangeFilters(() => changes++)); + account.setEntitlements(); + assert.deepStrictEqual({ filters: Object.fromEntries(provider.getFilters()), changes }, { + filters: { + copilottrackingid: null, + github_core_isghormsftstaff: '0', + github_core_ghmsftorexternal: 'external', + github_core_copilotsku: null, + github_core_issn: '0', + github_core_isfcv1: '0', + }, + changes: 1, + }); + }); - // Latched: survives the live value going away again. - entitlement.copilotTrackingId = undefined; - assert.strictEqual(provider.getFilterValue(GitHubAssignmentsFilter.CopilotTrackingId), 'tid-late'); + test('does not retain another account tracking id while the next account has no entitlements', () => { + const account = new TestDefaultAccountService(); + const provider = createProvider(account); + const values = [{ analytics_tracking_id: 'first' }, {}, { analytics_tracking_id: 'second' }, undefined]; + assert.deepStrictEqual(values.map(value => { + account.setEntitlements(value); + return provider.getFilterValue(GitHubAssignmentsFilter.CopilotTrackingId); + }), ['first', null, 'second', null]); }); test('reflects organization classification changes', () => { - const entitlement = new TestChatEntitlementService(); - const provider = createProvider(entitlement); + const account = new TestDefaultAccountService(); + const provider = createProvider(account); const organizations = [ undefined, ['microsoft'], @@ -220,8 +270,7 @@ suite('GitHubCoreAssignmentsFilterProvider', () => { ]; assert.deepStrictEqual(organizations.map(organisations => { - entitlement.organisations = organisations; - entitlement.fireChange(); + account.setEntitlements({ organization_login_list: organisations }); const filters = provider.getFilters(); return [ filters.get(GitHubAssignmentsFilter.GhMsftOrExternal), @@ -240,16 +289,14 @@ suite('GitHubCoreAssignmentsFilterProvider', () => { }); test('includes staff without internal organizations and notifies on staff-only changes', () => { - const entitlement = new TestChatEntitlementService(); - entitlement.organisations = ['contoso']; - entitlement.isStaff = true; - const provider = createProvider(entitlement); + const account = new TestDefaultAccountService(); + account.setEntitlements({ organization_login_list: ['contoso'], is_staff: true }); + const provider = createProvider(account); let changes = 0; disposables.add(provider.onDidChangeFilters(() => changes++)); assert.deepStrictEqual([true, false, false, true, undefined].map(isStaff => { - entitlement.isStaff = isStaff; - entitlement.fireChange(); + account.setEntitlements({ organization_login_list: ['contoso'], is_staff: isStaff }); const filters = provider.getFilters(); return [ filters.get(GitHubAssignmentsFilter.IsGhOrMsftStaff), @@ -266,27 +313,23 @@ suite('GitHubCoreAssignmentsFilterProvider', () => { }); test('fires onDidChangeFilters only when relevant inputs change', () => { - const entitlement = new TestChatEntitlementService(); - entitlement.copilotTrackingId = 'tid-1'; - entitlement.organisations = ['github']; - - const provider = createProvider(entitlement); + const account = new TestDefaultAccountService(); + account.setEntitlements({ analytics_tracking_id: 'tid-1', organization_login_list: ['github'] }); + const provider = createProvider(account); let changes = 0; disposables.add(provider.onDidChangeFilters(() => changes++)); // No relevant change -> no event. - entitlement.fireChange(); + account.setEntitlements({ analytics_tracking_id: 'tid-1', organization_login_list: ['github'] }); assert.strictEqual(changes, 0); // Org change -> event. - entitlement.organisations = ['microsoft']; - entitlement.fireChange(); + account.setEntitlements({ analytics_tracking_id: 'tid-1', organization_login_list: ['microsoft'] }); assert.strictEqual(changes, 1); // Tracking id change -> event. - entitlement.copilotTrackingId = 'tid-2'; - entitlement.fireChange(); + account.setEntitlements({ analytics_tracking_id: 'tid-2', organization_login_list: ['microsoft'] }); assert.strictEqual(changes, 2); }); }); diff --git a/src/vs/workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.ts b/src/vs/workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.ts index abf2104cb89f..ad5f0e57488a 100644 --- a/src/vs/workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.ts +++ b/src/vs/workbench/services/auxiliaryWindow/browser/auxiliaryWindowService.ts @@ -48,6 +48,7 @@ export interface IAuxiliaryWindowOpenOptions { readonly mode?: AuxiliaryWindowMode; readonly zoomLevel?: number; + /** Initial state; native windows inherit the main window's current state when omitted. */ readonly alwaysOnTop?: boolean; readonly nativeTitlebar?: boolean; @@ -426,7 +427,7 @@ export class BrowserAuxiliaryWindowService extends Disposable implements IAuxili private applyMeta(auxiliaryWindow: CodeWindow): void { for (const metaTag of ['meta[charset="utf-8"]', 'meta[http-equiv="Content-Security-Policy"]', 'meta[name="viewport"]', 'meta[name="theme-color"]']) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const metaElement = mainWindow.document.querySelector(metaTag); if (metaElement) { const clonedMetaElement = createMetaElement(auxiliaryWindow.document.head); @@ -441,7 +442,7 @@ export class BrowserAuxiliaryWindowService extends Disposable implements IAuxili } } - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const originalIconLinkTag = mainWindow.document.querySelector('link[rel="icon"]'); if (originalIconLinkTag) { const icon = createLinkElement(auxiliaryWindow.document.head); @@ -489,7 +490,7 @@ export class BrowserAuxiliaryWindowService extends Disposable implements IAuxili // all style related nodes have been cloned. pendingLinksToSettle++; try { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax for (const originalNode of mainWindow.document.head.querySelectorAll('link[rel="stylesheet"], style')) { cloneNode(originalNode); } diff --git a/src/vs/workbench/services/auxiliaryWindow/electron-browser/auxiliaryWindowService.ts b/src/vs/workbench/services/auxiliaryWindow/electron-browser/auxiliaryWindowService.ts index 1a35eedb2702..d0f068f12848 100644 --- a/src/vs/workbench/services/auxiliaryWindow/electron-browser/auxiliaryWindowService.ts +++ b/src/vs/workbench/services/auxiliaryWindow/electron-browser/auxiliaryWindowService.ts @@ -6,7 +6,7 @@ import { localize } from '../../../../nls.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import { IWorkbenchLayoutService } from '../../layout/browser/layoutService.js'; -import { AuxiliaryWindow, AuxiliaryWindowMode, BrowserAuxiliaryWindowService, IAuxiliaryWindowOpenOptions, IAuxiliaryWindowService } from '../browser/auxiliaryWindowService.js'; +import { AuxiliaryWindow, AuxiliaryWindowMode, BrowserAuxiliaryWindowService, IAuxiliaryWindow, IAuxiliaryWindowOpenOptions, IAuxiliaryWindowService } from '../browser/auxiliaryWindowService.js'; import { ISandboxGlobals } from '../../../../base/parts/sandbox/electron-browser/globals.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { DisposableStore } from '../../../../base/common/lifecycle.js'; @@ -158,6 +158,13 @@ export class NativeAuxiliaryWindowService extends BrowserAuxiliaryWindowService super(layoutService, dialogService, configurationService, telemetryService, hostService, environmentService, contextMenuService); } + override async open(options?: IAuxiliaryWindowOpenOptions): Promise<IAuxiliaryWindow> { + return super.open({ + ...options, + alwaysOnTop: options?.alwaysOnTop ?? await this.nativeHostService.isWindowAlwaysOnTop() + }); + } + protected override async resolveWindowId(auxiliaryWindow: NativeCodeWindow): Promise<number> { mark('code/auxiliaryWindow/willResolveWindowId'); const windowId = await auxiliaryWindow.vscode.ipcRenderer.invoke('vscode:registerAuxiliaryWindow', this.nativeHostService.windowId); diff --git a/src/vs/workbench/services/auxiliaryWindow/test/electron-browser/auxiliaryWindowService.test.ts b/src/vs/workbench/services/auxiliaryWindow/test/electron-browser/auxiliaryWindowService.test.ts new file mode 100644 index 000000000000..a00682c03c0a --- /dev/null +++ b/src/vs/workbench/services/auxiliaryWindow/test/electron-browser/auxiliaryWindowService.test.ts @@ -0,0 +1,71 @@ +/*--------------------------------------------------------------------------------------------- + * 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 sinon from 'sinon'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { INativeHostService } from '../../../../../platform/native/common/native.js'; +import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { BrowserAuxiliaryWindowService, IAuxiliaryWindow } from '../../browser/auxiliaryWindowService.js'; +import { NativeAuxiliaryWindowService } from '../../electron-browser/auxiliaryWindowService.js'; + +suite('NativeAuxiliaryWindowService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + teardown(() => sinon.restore()); + + function createService(initialAlwaysOnTop: boolean) { + const instantiationService = workbenchInstantiationService(undefined, store); + const isWindowAlwaysOnTop = sinon.stub().resolves(initialAlwaysOnTop); + instantiationService.stub(INativeHostService, { isWindowAlwaysOnTop }); + const open = sinon.stub(BrowserAuxiliaryWindowService.prototype, 'open').resolves(upcastPartial<IAuxiliaryWindow>({})); + const service = store.add(instantiationService.createInstance(NativeAuxiliaryWindowService)); + return { service, isWindowAlwaysOnTop, open }; + } + + for (const initialAlwaysOnTop of [false, true]) { + test(`inherits ${initialAlwaysOnTop} only when opening a new window`, async () => { + const { service, isWindowAlwaysOnTop, open } = createService(initialAlwaysOnTop); + + await service.open({ compact: true }); + isWindowAlwaysOnTop.resolves(!initialAlwaysOnTop); + await service.open(); + + assert.deepStrictEqual({ + options: open.args, + reads: isWindowAlwaysOnTop.args + }, { + options: [[{ compact: true, alwaysOnTop: initialAlwaysOnTop }], [{ alwaysOnTop: !initialAlwaysOnTop }]], + reads: [[], []] + }); + }); + } + + for (const alwaysOnTop of [false, true]) { + test(`preserves an explicitly requested or restored value of ${alwaysOnTop}`, async () => { + const { service, isWindowAlwaysOnTop, open } = createService(!alwaysOnTop); + + await service.open({ alwaysOnTop }); + + assert.deepStrictEqual({ + options: open.args, + reads: isWindowAlwaysOnTop.args + }, { + options: [[{ alwaysOnTop }]], + reads: [] + }); + }); + } + + test('does not open a window if reading the inherited state fails', async () => { + const { service, isWindowAlwaysOnTop, open } = createService(false); + const error = new Error('Unable to read window state'); + isWindowAlwaysOnTop.rejects(error); + + await assert.rejects(service.open(), error); + assert.deepStrictEqual(open.args, []); + }); +}); diff --git a/src/vs/workbench/services/chat/common/chatEntitlementService.ts b/src/vs/workbench/services/chat/common/chatEntitlementService.ts index 29ce4272e788..6056d171ef92 100644 --- a/src/vs/workbench/services/chat/common/chatEntitlementService.ts +++ b/src/vs/workbench/services/chat/common/chatEntitlementService.ts @@ -32,7 +32,7 @@ import { Mutable } from '../../../../base/common/types.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; import { IObservable, observableFromEvent } from '../../../../base/common/observable.js'; import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js'; -import { IDefaultAccount, IEntitlementsData } from '../../../../base/common/defaultAccount.js'; +import { IDefaultAccount, IEntitlementsData, IQuotaSnapshotData } from '../../../../base/common/defaultAccount.js'; import { isInternalAccount } from '../../../../platform/assignment/common/assignment.js'; export namespace ChatEntitlementContextKeys { @@ -347,7 +347,11 @@ type ChatEntitlementEvent = { chatDisabled: boolean; }; -function logChatEntitlements(state: IChatEntitlementContextState, configurationService: IConfigurationService, telemetryService: ITelemetryService): void { +function logChatEntitlements(state: IChatEntitlementContextState, configurationService: IConfigurationService, telemetryService: ITelemetryService, storageService: IStorageService): void { + if (readSimulatedEntitlement(storageService) !== undefined) { + return; // never report a simulated entitlement as the actual one + } + telemetryService.publicLog2<ChatEntitlementEvent, ChatEntitlementClassification>('chatEntitlements', { chatHidden: Boolean(state.hidden), chatDisabled: Boolean(state.disabled), @@ -441,6 +445,7 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme ChatEntitlementContextKeys.Setup.completed.key, ChatEntitlementContextKeys.Setup.hidden.key, ChatEntitlementContextKeys.Setup.disabled.key, + ChatEntitlementContextKeys.Setup.disabledInWorkspace.key, ChatEntitlementContextKeys.Setup.untrusted.key, ChatEntitlementContextKeys.Setup.installed.key, ChatEntitlementContextKeys.Setup.later.key, @@ -462,7 +467,7 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme const context = this.context = new Lazy(() => this._register(instantiationService.createInstance(ChatEntitlementContext))); this.requests = new Lazy(() => this._register(instantiationService.createInstance(ChatEntitlementRequests, context.value, { clearQuotas: () => this.clearQuotas(), - acceptQuotas: quotas => this.acceptQuotas(quotas) + acceptQuotas: quotas => this.doAcceptQuotas(quotas) }))); this.registerListeners(); @@ -569,7 +574,7 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme this.anonymousContextKey.set(newAnonymousUsage); if (this.context?.hasValue) { - logChatEntitlements(this.context.value.state, this.configurationService, this.telemetryService); + logChatEntitlements(this.context.value.state, this.configurationService, this.telemetryService, this.storageService); } this._onDidChangeAnonymous.fire(); @@ -587,6 +592,15 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme } acceptQuotas(incomingQuotas: IQuotas): void { + if (this.requests?.hasValue && this.requests.value.simulatedEntitlement !== undefined) { + this.logService.trace('[chat entitlement]: ignoring quotas while an entitlement is simulated'); + return; // keep the quotas of the simulated entitlement stable + } + + this.doAcceptQuotas(incomingQuotas); + } + + private doAcceptQuotas(incomingQuotas: IQuotas): void { const oldQuota = this._quotas; const cachedQuota = this.quotaCopilotTrackingId === this.copilotTrackingId ? oldQuota : {}; const quotas: IQuotas = { @@ -632,6 +646,10 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme this._onDidChangeUsageBasedBilling.fire(); } + if (this.requests?.hasValue && this.requests.value.simulatedEntitlement !== undefined) { + return; // never report simulated quotas as actual ones + } + // Track additional spend configuration changes (only when both values come from server snapshots) if (oldQuota.additionalUsageEnabled !== undefined && quotas.additionalUsageEnabled !== undefined && oldQuota.additionalUsageEnabled !== quotas.additionalUsageEnabled) { this.telemetryService.publicLog2<ChatAdditionalSpendConfigurationEvent, ChatAdditionalSpendConfigurationClassification>('chatAdditionalSpendConfiguration', { @@ -666,7 +684,7 @@ export class ChatEntitlementService extends Disposable implements IChatEntitleme } clearQuotas(): void { - this.acceptQuotas({}); + this.doAcceptQuotas({}); } private updateContextKeys(): void { @@ -1030,12 +1048,140 @@ export function parseQuotas(entitlementsData: IEntitlementsData): IQuotas { return quotas; } +/** + * Maps an entitlements response to the chat entitlement of the user. + */ +export function getChatEntitlement(entitlementsData: IEntitlementsData): ChatEntitlement { + if (entitlementsData.access_type_sku === 'free_limited_copilot') { + return ChatEntitlement.Free; + } else if (entitlementsData.access_type_sku === 'free_educational_quota') { + return ChatEntitlement.EDU; + } else if (entitlementsData.can_signup_for_limited) { + return ChatEntitlement.Available; + } else if (entitlementsData.copilot_plan === 'individual_edu') { + return ChatEntitlement.EDU; + } else if (entitlementsData.copilot_plan === 'individual') { + return ChatEntitlement.Pro; + } else if (entitlementsData.copilot_plan === 'individual_pro') { + return ChatEntitlement.ProPlus; + } else if (entitlementsData.copilot_plan === 'individual_max') { + return ChatEntitlement.Max; + } else if (entitlementsData.copilot_plan === 'business') { + return ChatEntitlement.Business; + } else if (entitlementsData.copilot_plan === 'enterprise') { + return ChatEntitlement.Enterprise; + } + + return ChatEntitlement.Unavailable; +} + +//#region Entitlement Simulation + +const SIMULATED_ENTITLEMENT_STORAGE_KEY = 'chat.entitlement.simulated'; + +/** + * Entitlements a signed-in developer can simulate to try the product as such a user. + */ +export const SIMULATABLE_CHAT_ENTITLEMENTS = [ + ChatEntitlement.Available, + ChatEntitlement.Unavailable, + ChatEntitlement.Free, + ChatEntitlement.EDU, + ChatEntitlement.Pro, + ChatEntitlement.ProPlus, + ChatEntitlement.Max, + ChatEntitlement.Business, + ChatEntitlement.Enterprise, +] as const; + +export type SimulatedChatEntitlement = typeof SIMULATABLE_CHAT_ENTITLEMENTS[number]; + +function readSimulatedEntitlement(storageService: IStorageService): SimulatedChatEntitlement | undefined { + // Profile scoped like the cached entitlement context, so that both always agree + const value = storageService.getNumber(SIMULATED_ENTITLEMENT_STORAGE_KEY, StorageScope.PROFILE); + return SIMULATABLE_CHAT_ENTITLEMENTS.find(entitlement => entitlement === value); +} + +interface ISimulatedPlan { + readonly sku: string; + readonly plan: string; + readonly canUpgradePlan: boolean; + /** Monthly allowances; `undefined` means unlimited. Values are illustrative only. */ + readonly chat?: number; + readonly completions?: number; + /** Monthly premium allowance; `undefined` means the plan has none. */ + readonly premium?: number; +} + +const SIMULATED_PLANS: { readonly [K in SimulatedChatEntitlement]: ISimulatedPlan } = { + [ChatEntitlement.Available]: { sku: 'no_access', plan: 'individual', canUpgradePlan: false }, + [ChatEntitlement.Unavailable]: { sku: 'no_access', plan: '', canUpgradePlan: false }, + [ChatEntitlement.Free]: { sku: 'free_limited_copilot', plan: 'free', canUpgradePlan: true, chat: 50, completions: 2000 }, + [ChatEntitlement.EDU]: { sku: 'free_educational_quota', plan: 'individual', canUpgradePlan: true, premium: 300 }, + [ChatEntitlement.Pro]: { sku: 'monthly_subscriber_quota', plan: 'individual', canUpgradePlan: true, premium: 300 }, + [ChatEntitlement.ProPlus]: { sku: 'plus_monthly_subscriber_quota', plan: 'individual_pro', canUpgradePlan: true, premium: 1500 }, + [ChatEntitlement.Max]: { sku: 'max_monthly_subscriber_quota', plan: 'individual_max', canUpgradePlan: false, premium: 3900 }, + [ChatEntitlement.Business]: { sku: 'copilot_for_business_seat_quota', plan: 'business', canUpgradePlan: false, premium: 300 }, + [ChatEntitlement.Enterprise]: { sku: 'copilot_enterprise_seat_quota', plan: 'enterprise', canUpgradePlan: false, premium: 1000 }, +}; + +/** + * Synthesizes the entitlements response of a user with the given entitlement. + * Account identity (organisations, staff flag, tracking id, endpoints) is kept + * from the actual response so that internal-user checks keep working. + */ +export function simulateEntitlementsData(entitlement: SimulatedChatEntitlement, actual: IEntitlementsData | null | undefined): IEntitlementsData { + const plan = SIMULATED_PLANS[entitlement]; + const hasCopilot = entitlement !== ChatEntitlement.Available && entitlement !== ChatEntitlement.Unavailable; + + const now = new Date(); + const resetDate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)); + + const snapshot = (allowance: number | undefined): IQuotaSnapshotData => allowance === undefined + ? { overage_count: 0, overage_entitlement: 0, overage_permitted: false, percent_remaining: 100, unlimited: true } + : { overage_count: 0, overage_entitlement: 0, overage_permitted: false, percent_remaining: 75, unlimited: false, entitlement: String(allowance), quota_remaining: allowance * 0.75 }; + + return { + access_type_sku: plan.sku, + copilot_plan: plan.plan, + can_signup_for_limited: entitlement === ChatEntitlement.Available, + can_upgrade_plan: plan.canUpgradePlan, + chat_enabled: hasCopilot, + assigned_date: actual?.assigned_date ?? '', + organization_login_list: actual?.organization_login_list ?? [], + is_staff: actual?.is_staff, + analytics_tracking_id: actual?.analytics_tracking_id ?? '', + endpoints: actual?.endpoints, + token_based_billing: hasCopilot && entitlement !== ChatEntitlement.Free ? actual?.token_based_billing : undefined, + quota_reset_date: hasCopilot ? resetDate.toISOString().slice(0, 10) : undefined, + quota_reset_date_utc: hasCopilot ? resetDate.toISOString() : undefined, + quota_snapshots: hasCopilot ? { + chat: snapshot(plan.chat), + completions: snapshot(plan.completions), + premium_interactions: plan.premium !== undefined ? snapshot(plan.premium) : undefined + } : undefined + }; +} + +//#endregion + export class ChatEntitlementRequests extends Disposable { private state: IEntitlements; private pendingResolveCts = new CancellationTokenSource(); + private _simulatedEntitlement: SimulatedChatEntitlement | undefined; + + /** + * The entitlement that is simulated instead of the actual one, if any. + * Only applies to signed-in users. + */ + get simulatedEntitlement(): SimulatedChatEntitlement | undefined { return this._simulatedEntitlement; } + + private readonly _onDidChangeSimulatedEntitlement = this._register(new Emitter<void>()); + readonly onDidChangeSimulatedEntitlement = this._onDidChangeSimulatedEntitlement.event; + constructor( private readonly context: ChatEntitlementContext, private readonly chatQuotasAccessor: IChatQuotasAccessor, @@ -1047,10 +1193,12 @@ export class ChatEntitlementRequests extends Disposable { @ILifecycleService private readonly lifecycleService: ILifecycleService, @IDefaultAccountService private readonly defaultAccountService: IDefaultAccountService, @IAuthenticationService private readonly authenticationService: IAuthenticationService, + @IStorageService private readonly storageService: IStorageService, ) { super(); this.state = { entitlement: this.context.state.entitlement }; + this._simulatedEntitlement = readSimulatedEntitlement(this.storageService); this.registerListeners(); @@ -1060,6 +1208,9 @@ export class ChatEntitlementRequests extends Disposable { private registerListeners(): void { this._register(this.defaultAccountService.onDidChangeDefaultAccount(() => this.resolve())); + // Apply simulation changes from other windows of the same profile + this._register(this.storageService.onDidChangeValue(StorageScope.PROFILE, SIMULATED_ENTITLEMENT_STORAGE_KEY, this._store)(() => this.onDidChangeSimulatedEntitlementStorage())); + this._register(this.context.onDidChange(() => { if (this.context.state.disabled || this.context.state.entitlement === ChatEntitlement.Unknown) { // When the extension is disabled or the user is not entitled @@ -1070,6 +1221,38 @@ export class ChatEntitlementRequests extends Disposable { })); } + /** + * Simulates the given entitlement instead of the actual one until + * cleared with `undefined`. Persists across reloads. + */ + async setSimulatedEntitlement(entitlement: SimulatedChatEntitlement | undefined): Promise<void> { + if (entitlement === undefined) { + this.storageService.remove(SIMULATED_ENTITLEMENT_STORAGE_KEY, StorageScope.PROFILE); + } else { + this.storageService.store(SIMULATED_ENTITLEMENT_STORAGE_KEY, entitlement, StorageScope.PROFILE, StorageTarget.MACHINE); + } + + this.onDidChangeSimulatedEntitlementStorage(); + await this.pendingSimulationResolve; + } + + private pendingSimulationResolve: Promise<void> = Promise.resolve(); + + private onDidChangeSimulatedEntitlementStorage(): void { + const entitlement = readSimulatedEntitlement(this.storageService); + if (entitlement === this._simulatedEntitlement) { + return; + } + + this.logService.info(entitlement === undefined ? '[chat entitlement]: stopped simulating an entitlement' : `[chat entitlement]: simulating entitlement ${entitlement}`); + this._simulatedEntitlement = entitlement; + this._onDidChangeSimulatedEntitlement.fire(); + + // Never merge actual and simulated quotas + this.chatQuotasAccessor.clearQuotas(); + this.pendingSimulationResolve = this.resolve(); + } + private async resolve(): Promise<void> { this.pendingResolveCts.dispose(true); const cts = this.pendingResolveCts = new CancellationTokenSource(); @@ -1113,37 +1296,17 @@ export class ChatEntitlementRequests extends Disposable { return undefined; } - const entitlementsData = defaultAccount.entitlementsData; + const simulatedEntitlement = this._simulatedEntitlement; + const entitlementsData = simulatedEntitlement !== undefined + ? simulateEntitlementsData(simulatedEntitlement, defaultAccount.entitlementsData) + : defaultAccount.entitlementsData; if (!entitlementsData) { this.logService.trace('[chat entitlement]: no entitlements data available on default account'); return { entitlement: entitlementsData === null ? ChatEntitlement.Unknown : ChatEntitlement.Unresolved }; } - let entitlement: ChatEntitlement; - if (entitlementsData.access_type_sku === 'free_limited_copilot') { - entitlement = ChatEntitlement.Free; - } else if (entitlementsData.access_type_sku === 'free_educational_quota') { - entitlement = ChatEntitlement.EDU; - } else if (entitlementsData.can_signup_for_limited) { - entitlement = ChatEntitlement.Available; - } else if (entitlementsData.copilot_plan === 'individual_edu') { - entitlement = ChatEntitlement.EDU; - } else if (entitlementsData.copilot_plan === 'individual') { - entitlement = ChatEntitlement.Pro; - } else if (entitlementsData.copilot_plan === 'individual_pro') { - entitlement = ChatEntitlement.ProPlus; - } else if (entitlementsData.copilot_plan === 'individual_max') { - entitlement = ChatEntitlement.Max; - } else if (entitlementsData.copilot_plan === 'business') { - entitlement = ChatEntitlement.Business; - } else if (entitlementsData.copilot_plan === 'enterprise') { - entitlement = ChatEntitlement.Enterprise; - } else { - entitlement = ChatEntitlement.Unavailable; - } - const entitlements: IEntitlements = { - entitlement, + entitlement: getChatEntitlement(entitlementsData), organisations: entitlementsData.organization_login_list, isStaff: entitlementsData.is_staff, quotas: this.toQuotas(entitlementsData), @@ -1151,7 +1314,11 @@ export class ChatEntitlementRequests extends Disposable { copilotTrackingId: entitlementsData.analytics_tracking_id }; - this.logService.trace(`[chat entitlement]: resolved to ${entitlements.entitlement}, quotas: ${JSON.stringify(entitlements.quotas)}`); + this.logService.trace(`[chat entitlement]: resolved to ${entitlements.entitlement}${simulatedEntitlement !== undefined ? ' (simulated)' : ''}, quotas: ${JSON.stringify(entitlements.quotas)}`); + if (simulatedEntitlement !== undefined) { + return entitlements; // never report a simulated entitlement as the actual one + } + this.telemetryService.publicLog2<EntitlementEvent, EntitlementClassification>('chatInstallEntitlement', { entitlement: entitlements.entitlement, tid: entitlementsData.analytics_tracking_id, @@ -1244,10 +1411,18 @@ export class ChatEntitlementRequests extends Disposable { if (sessions.length === 0) { return undefined; } + return this.doSignUpFree(sessions); } private async doSignUpFree(sessions: AuthenticationSession[]): Promise<true /* signed up */ | false /* already signed up */ | { errorCode: number } /* error */> { + if (this._simulatedEntitlement !== undefined) { + // Never sign up the actual account while simulating (also on retries), continue as a Free user instead + this.logService.info('[chat entitlement]: simulating sign-up for Copilot Free'); + await this.setSimulatedEntitlement(ChatEntitlement.Free); + return true; + } + const body = { restricted_telemetry: this.telemetryService.telemetryLevel === TelemetryLevel.NONE ? 'disabled' : 'enabled', public_code_suggestions: 'enabled' @@ -1628,7 +1803,7 @@ export class ChatEntitlementContext extends Disposable { this.registeredContext.set(!!state.registered); this.logService.trace(`[chat entitlement context] updateContext(): ${JSON.stringify(state)}`); - logChatEntitlements(state, this.configurationService, this.telemetryService); + logChatEntitlements(state, this.configurationService, this.telemetryService, this.storageService); this._onDidChange.fire(); } diff --git a/src/vs/workbench/services/configuration/common/configurationEditing.ts b/src/vs/workbench/services/configuration/common/configurationEditing.ts index 59b9f92c264f..dc531516b8b8 100644 --- a/src/vs/workbench/services/configuration/common/configurationEditing.ts +++ b/src/vs/workbench/services/configuration/common/configurationEditing.ts @@ -162,6 +162,10 @@ export class ConfigurationEditing { async writeConfiguration(target: EditableConfigurationTarget, value: IConfigurationValue, options: IConfigurationEditingOptions = {}): Promise<void> { const operation = this.getConfigurationEditOperation(target, value, options.scopes || {}); + return this.queueWriteConfiguration(operation, options); + } + + private queueWriteConfiguration(operation: IConfigurationEditOperation, options: IConfigurationEditingOptions): Promise<void> { // queue up writes to prevent race conditions return this.queue.queue(async () => { try { @@ -306,10 +310,7 @@ export class ConfigurationEditing { this.notificationService.prompt(Severity.Error, error.message, [{ label: nls.localize('saveAndRetry', "Save and Retry"), - run: () => { - const key = operation.key ? `${operation.workspaceStandAloneConfigurationKey}.${operation.key}` : operation.workspaceStandAloneConfigurationKey!; - this.writeConfiguration(operation.target, { key, value: operation.value }, { handleDirtyFile: 'save', scopes }); - } + run: () => this.queueWriteConfiguration(operation, { handleDirtyFile: 'save', scopes }) }, { label: openStandAloneConfigurationActionLabel, @@ -320,7 +321,7 @@ export class ConfigurationEditing { this.notificationService.prompt(Severity.Error, error.message, [{ label: nls.localize('saveAndRetry', "Save and Retry"), - run: () => this.writeConfiguration(operation.target, { key: operation.key, value: operation.value }, { handleDirtyFile: 'save', scopes }) + run: () => this.queueWriteConfiguration(operation, { handleDirtyFile: 'save', scopes }) }, { label: nls.localize('open', "Open Settings"), diff --git a/src/vs/workbench/services/configuration/test/browser/configurationEditing.test.ts b/src/vs/workbench/services/configuration/test/browser/configurationEditing.test.ts index 1ffa01982ded..056c135235d1 100644 --- a/src/vs/workbench/services/configuration/test/browser/configurationEditing.test.ts +++ b/src/vs/workbench/services/configuration/test/browser/configurationEditing.test.ts @@ -16,7 +16,7 @@ import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from '. import { WorkspaceService } from '../../browser/configurationService.js'; import { ConfigurationEditing, ConfigurationEditingErrorCode, EditableConfigurationTarget } from '../../common/configurationEditing.js'; import { WORKSPACE_STANDALONE_CONFIGURATIONS, FOLDER_SETTINGS_PATH, USER_STANDALONE_CONFIGURATIONS, IConfigurationCache } from '../../common/configuration.js'; -import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ITextFileService } from '../../../textfile/common/textfiles.js'; import { ITextModelService } from '../../../../../editor/common/services/resolverService.js'; @@ -39,7 +39,7 @@ import { joinPath } from '../../../../../base/common/resources.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; import { RemoteAgentService } from '../../../remote/browser/remoteAgentService.js'; import { getSingleFolderWorkspaceIdentifier } from '../../../../../platform/workspaces/common/workspaceIdentifier.js'; -import { IUserDataProfilesService, UserDataProfilesService } from '../../../../../platform/userDataProfile/common/userDataProfile.js'; +import { InMemoryUserDataProfilesService, IUserDataProfilesService } from '../../../../../platform/userDataProfile/common/userDataProfile.js'; import { hash } from '../../../../../base/common/hash.js'; import { FilePolicyService } from '../../../../../platform/policy/common/filePolicyService.js'; import { runWithFakedTimers } from '../../../../../base/test/common/timeTravelScheduler.js'; @@ -116,8 +116,9 @@ suite('ConfigurationEditing', () => { environmentService.policyFile = joinPath(workspaceFolder, 'policies.json'); instantiationService.stub(IEnvironmentService, environmentService); const uriIdentityService = disposables.add(new UriIdentityService(fileService)); - const userDataProfilesService = instantiationService.stub(IUserDataProfilesService, disposables.add(new UserDataProfilesService(environmentService, fileService, uriIdentityService, logService))); + const userDataProfilesService = instantiationService.stub(IUserDataProfilesService, disposables.add(new InMemoryUserDataProfilesService(environmentService, fileService, uriIdentityService, logService))); userDataProfileService = disposables.add(new UserDataProfileService(userDataProfilesService.defaultProfile)); + instantiationService.stub(IUserDataProfileService, userDataProfileService); const remoteAgentService = disposables.add(instantiationService.createInstance(RemoteAgentService)); disposables.add(fileService.registerProvider(Schemas.vscodeUserData, disposables.add(new FileUserDataProvider(ROOT.scheme, fileSystemProvider, Schemas.vscodeUserData, userDataProfilesService, uriIdentityService, logService)))); instantiationService.stub(IFileService, fileService); @@ -193,6 +194,102 @@ suite('ConfigurationEditing', () => { assert.fail('Should fail with ERROR_CONFIGURATION_FILE_DIRTY error.'); }); + for (const switchProfile of [false, true]) { + test(`Save and Retry preserves the original profile's settings and drafts${switchProfile ? ' after switching profiles' : ''}`, async () => { + workspaceService.acquireInstantiationService(instantiationService); + const profilesService = instantiationService.get(IUserDataProfilesService); + const profile = await profilesService.createNamedProfile('Profile A'); + const otherProfile = await profilesService.createNamedProfile('Profile B'); + const key = 'configurationEditing.service.testSetting'; + const draftKey = 'configurationEditing.service.testSettingTwo'; + await fileService.writeFile(profile.settingsResource, VSBuffer.fromString(JSON.stringify({ [key]: 'profile A' }))); + await fileService.writeFile(otherProfile.settingsResource, VSBuffer.fromString(JSON.stringify({ [key]: 'profile B' }))); + await userDataProfileService.updateCurrentProfile(profile); + + const model = disposables.add(await instantiationService.get(ITextModelService).createModelReference(profile.settingsResource)); + const otherModel = disposables.add(await instantiationService.get(ITextModelService).createModelReference(otherProfile.settingsResource)); + const textFileService = instantiationService.get(ITextFileService); + try { + model.object.textEditorModel.setValue(JSON.stringify({ [key]: 'profile A', [draftKey]: 'draft A' })); + otherModel.object.textEditorModel.setValue(JSON.stringify({ [key]: 'profile B', [draftKey]: 'draft B' })); + const prompt = sinon.spy(instantiationService.get(INotificationService), 'prompt'); + + await workspaceService.updateValue(key, 'updated A', ConfigurationTarget.USER_LOCAL); + assert.strictEqual(prompt.callCount, 1); + const retry = prompt.firstCall.args[2][0]; + assert.strictEqual(retry.label, 'Save and Retry'); + if (switchProfile) { + await userDataProfileService.updateCurrentProfile(otherProfile); + } + await retry.run(); + + assert.deepStrictEqual({ + settings: json.parse((await fileService.readFile(profile.settingsResource)).value.toString()), + otherSettings: json.parse((await fileService.readFile(otherProfile.settingsResource)).value.toString()), + dirty: textFileService.isDirty(profile.settingsResource), + otherDirty: textFileService.isDirty(otherProfile.settingsResource), + otherDraft: json.parse(otherModel.object.textEditorModel.getValue()) + }, { + settings: { [key]: 'updated A', [draftKey]: 'draft A' }, + otherSettings: { [key]: 'profile B' }, + dirty: false, + otherDirty: true, + otherDraft: { [key]: 'profile B', [draftKey]: 'draft B' } + }); + } finally { + await textFileService.revert(profile.settingsResource); + await textFileService.revert(otherProfile.settingsResource); + const disposed = Promise.all([ + Event.toPromise(model.object.textEditorModel.onWillDispose), + Event.toPromise(otherModel.object.textEditorModel.onWillDispose) + ]); + model.dispose(); + otherModel.dispose(); + await disposed; + } + }); + } + + test('Save and Retry keeps user tasks in their original profile', async () => { + const profilesService = instantiationService.get(IUserDataProfilesService); + const profile = await profilesService.createNamedProfile('Profile A'); + const otherProfile = await profilesService.createNamedProfile('Profile B'); + const tasks = [{ label: 'Updated A', type: 'shell', command: 'echo A' }]; + const original = { version: '2.0.0', tasks: [] }; + await fileService.writeFile(profile.tasksResource, VSBuffer.fromString(JSON.stringify(original))); + await fileService.writeFile(otherProfile.tasksResource, VSBuffer.fromString(JSON.stringify(original))); + await userDataProfileService.updateCurrentProfile(profile); + + const model = disposables.add(await instantiationService.get(ITextModelService).createModelReference(profile.tasksResource)); + const textFileService = instantiationService.get(ITextFileService); + try { + const inputs = [{ id: 'name', type: 'promptString', description: 'Name' }]; + model.object.textEditorModel.setValue(JSON.stringify({ ...original, inputs })); + const prompt = sinon.spy(instantiationService.get(INotificationService), 'prompt'); + await testObject.writeConfiguration(EditableConfigurationTarget.USER_LOCAL, { key: 'tasks.tasks', value: tasks }); + assert.strictEqual(prompt.callCount, 1); + await userDataProfileService.updateCurrentProfile(otherProfile); + + const saved = Event.toPromise(Event.filter(textFileService.files.onDidSave, event => + json.parse(event.model.textEditorModel!.getValue()).tasks?.[0]?.label === 'Updated A')); + await prompt.firstCall.args[2][0].run(); + await saved; + + assert.deepStrictEqual({ + tasks: json.parse((await fileService.readFile(profile.tasksResource)).value.toString()), + otherTasks: json.parse((await fileService.readFile(otherProfile.tasksResource)).value.toString()) + }, { + tasks: { ...original, tasks, inputs }, + otherTasks: original + }); + } finally { + await textFileService.revert(profile.tasksResource); + const disposed = Event.toPromise(model.object.textEditorModel.onWillDispose); + model.dispose(); + await disposed; + } + }); + test('do not notify error', async () => { instantiationService.stub(ITextFileService, 'isDirty', true); const target = sinon.stub(); diff --git a/src/vs/workbench/services/contextmenu/electron-browser/contextmenuService.ts b/src/vs/workbench/services/contextmenu/electron-browser/contextmenuService.ts index 493e9eff84f9..a036b36ffb64 100644 --- a/src/vs/workbench/services/contextmenu/electron-browser/contextmenuService.ts +++ b/src/vs/workbench/services/contextmenu/electron-browser/contextmenuService.ts @@ -133,7 +133,7 @@ export class NativeContextMenuService extends Disposable implements IContextMenu let x: number | undefined; let y: number | undefined; - let zoom = getZoomFactor(targetWindow); + const zoom = getZoomFactor(targetWindow); if (dom.isHTMLElement(anchor)) { const clientRect = anchor.getBoundingClientRect(); const elementPosition = { left: clientRect.left, top: clientRect.top, width: clientRect.width, height: clientRect.height }; @@ -144,12 +144,6 @@ export class NativeContextMenuService extends Disposable implements IContextMenu const vh = win.innerHeight; const isClipped = clientRect.left < 0 || clientRect.top < 0 || clientRect.right > vw || clientRect.bottom > vh; - // When drawing context menus, we adjust the pixel position for native menus using zoom level - // In areas where zoom is applied to the element or its ancestors, we need to adjust accordingly - // e.g. The title bar has counter zoom behavior meaning it applies the inverse of zoom level. - // Window Zoom Level: 1.5, Title Bar Zoom: 1/1.5, Coordinate Multiplier: 1.5 * 1.0 / 1.5 = 1.0 - zoom *= dom.getDomNodeZoomLevel(anchor); - if (isClipped) { // Element is partially out of viewport: always place at bottom-right visible corner x = Math.min(Math.max(clientRect.right, 0), vw); diff --git a/src/vs/workbench/services/contextmenu/test/electron-browser/contextmenuService.test.ts b/src/vs/workbench/services/contextmenu/test/electron-browser/contextmenuService.test.ts index a1e47d1fee5e..f3c19ee5c86b 100644 --- a/src/vs/workbench/services/contextmenu/test/electron-browser/contextmenuService.test.ts +++ b/src/vs/workbench/services/contextmenu/test/electron-browser/contextmenuService.test.ts @@ -4,13 +4,15 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { getZoomFactor, setZoomFactor } from '../../../../../base/browser/browser.js'; import { ModifierKeyEmitter } from '../../../../../base/browser/dom.js'; +import { AnchorAlignment } from '../../../../../base/browser/ui/contextview/contextview.js'; import { StandardMouseEvent } from '../../../../../base/browser/mouseEvent.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { Action, ActionRunner, Separator, SubmenuAction, toAction } from '../../../../../base/common/actions.js'; import { DeferredPromise } from '../../../../../base/common/async.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; -import { isLinux, isWindows } from '../../../../../base/common/platform.js'; +import { isLinux, isMacintosh, isWindows } from '../../../../../base/common/platform.js'; import { IContextMenuItem, IPopupOptions } from '../../../../../base/parts/contextmenu/common/contextmenu.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { MenuItemAction } from '../../../../../platform/actions/common/actions.js'; @@ -212,4 +214,38 @@ suite('Native ContextMenuService', () => { } } + test('scales native menu popup coordinates by window zoom without double-counting CSS zoom', () => { + const initialZoom = getZoomFactor(mainWindow); + store.add(toDisposable(() => setZoomFactor(initialZoom, mainWindow))); + setZoomFactor(0.8, mainWindow); + + const counterZoomed = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + counterZoomed.style.cssText = 'position: fixed; top: 0; left: 0; zoom: 1.25;'; + store.add(toDisposable(() => counterZoomed.remove())); + const anchor = counterZoomed.appendChild(mainWindow.document.createElement('div')); + anchor.style.cssText = 'position: absolute; top: 8px; left: 20px; width: 40px; height: 20px;'; + + const action = store.add(new Action('test', 'Test')); + const measure = (anchorAlignment: AnchorAlignment) => { + service.showContextMenu({ + getAnchor: () => anchor, + getActions: () => [action], + anchorAlignment, + }); + const result = { x: popupOptions?.x, y: popupOptions?.y }; + closeMenu?.(); + return result; + }; + + const rect = anchor.getBoundingClientRect(); + const expectedY = Math.floor(rect.bottom * 0.8 + (isMacintosh ? 4 : 0)); + assert.deepStrictEqual({ + left: measure(AnchorAlignment.LEFT), + right: measure(AnchorAlignment.RIGHT), + }, { + left: { x: Math.floor(rect.left * 0.8), y: expectedY }, + right: { x: Math.floor(rect.right * 0.8), y: expectedY }, + }); + }); + }); diff --git a/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts b/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts index 399b03bd1740..9d7624d1cc5e 100644 --- a/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts +++ b/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts @@ -25,6 +25,7 @@ import { equalsIgnoreCase, format, startsWithIgnoreCase } from '../../../../base import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; import { IRemoteAgentEnvironment } from '../../../../platform/remote/common/remoteAgentEnvironment.js'; import { isValidBasename } from '../../../../base/common/extpath.js'; +import { win32 } from '../../../../base/common/path.js'; import { Emitter } from '../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../base/common/lifecycle.js'; import { createCancelablePromise, CancelablePromise } from '../../../../base/common/async.js'; @@ -1096,11 +1097,8 @@ export class SimpleFileDialog extends Disposable implements ISimpleFileDialog { private async resolvePathFormatting(): Promise<void> { if (this.scopedAuthority) { const resource = URI.from({ scheme: this.scheme, authority: this.scopedAuthority, path: '/' }); - const [operatingSystem, path] = await Promise.all([ - this.pathService.getOperatingSystem(resource), - this.pathService.getPath(resource), - ]); - this.isWindows = operatingSystem === OperatingSystem.Windows; + const path = await this.pathService.getPath(resource); + this.isWindows = path === win32; this.separator = path?.sep ?? '/'; return; } diff --git a/src/vs/workbench/services/dialogs/test/browser/simpleFileDialog.test.ts b/src/vs/workbench/services/dialogs/test/browser/simpleFileDialog.test.ts index 5858a6eab906..fb77135f324a 100644 --- a/src/vs/workbench/services/dialogs/test/browser/simpleFileDialog.test.ts +++ b/src/vs/workbench/services/dialogs/test/browser/simpleFileDialog.test.ts @@ -8,7 +8,6 @@ import { timeout } from '../../../../../base/common/async.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; import { Schemas } from '../../../../../base/common/network.js'; import { posix, win32 } from '../../../../../base/common/path.js'; -import { OperatingSystem } from '../../../../../base/common/platform.js'; import * as resources from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; @@ -483,10 +482,6 @@ suite('SimpleFileDialog', () => { }, }, pathService: { - getOperatingSystem: async (uri: URI) => { - semanticRequests.push(`os:${uri.toString()}`); - return OperatingSystem.Windows; - }, getPath: async (uri: URI) => { semanticRequests.push(`path:${uri.toString()}`); return win32; @@ -534,7 +529,6 @@ suite('SimpleFileDialog', () => { separator: '\\', isWindows: true, semanticRequests: [ - 'os:vscode-agent-host://windows-host/', 'path:vscode-agent-host://windows-host/', ], }); @@ -552,7 +546,6 @@ suite('SimpleFileDialog', () => { }, }, pathService: { - getOperatingSystem: async () => OperatingSystem.Linux, getPath: async () => posix, }, }) as unknown as { @@ -585,7 +578,6 @@ suite('SimpleFileDialog', () => { }, }, pathService: { - getOperatingSystem: async () => undefined, getPath: async () => undefined, }, }) as unknown as { diff --git a/src/vs/workbench/services/driver/browser/driver.ts b/src/vs/workbench/services/driver/browser/driver.ts index 1f82b39945d7..17ff08b4593a 100644 --- a/src/vs/workbench/services/driver/browser/driver.ts +++ b/src/vs/workbench/services/driver/browser/driver.ts @@ -42,7 +42,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async setValue(selector: string, text: string): Promise<void> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { @@ -57,7 +57,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async isActiveElement(selector: string): Promise<boolean> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (element !== mainWindow.document.activeElement) { @@ -80,7 +80,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async getElements(selector: string, recursive: boolean): Promise<IElement[]> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const query = mainWindow.document.querySelectorAll(selector); const result: IElement[] = []; for (let i = 0; i < query.length; i++) { @@ -131,7 +131,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async typeInEditor(selector: string, text: string): Promise<void> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { @@ -170,7 +170,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async getEditorSelection(selector: string): Promise<{ selectionStart: number; selectionEnd: number }> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { throw new Error(`Editor not found: ${selector}`); @@ -189,7 +189,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async getTerminalBuffer(selector: string): Promise<string[]> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { @@ -212,7 +212,7 @@ export class BrowserWindowDriver implements IWindowDriver { } async writeInTerminal(selector: string, text: string): Promise<void> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { @@ -245,7 +245,7 @@ export class BrowserWindowDriver implements IWindowDriver { } protected async _getElementXY(selector: string, offset?: { x: number; y: number }): Promise<{ x: number; y: number }> { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const element = mainWindow.document.querySelector(selector); if (!element) { diff --git a/src/vs/workbench/services/editor/common/editorGroupsService.ts b/src/vs/workbench/services/editor/common/editorGroupsService.ts index 2d4e16aa27a9..3049ea5e02b0 100644 --- a/src/vs/workbench/services/editor/common/editorGroupsService.ts +++ b/src/vs/workbench/services/editor/common/editorGroupsService.ts @@ -127,6 +127,11 @@ export interface IMergeGroupOptions { * they are in the source group. */ readonly preserveExistingIndex?: boolean; + + /** + * Set this to not move focus to the moved editors. + */ + readonly preserveFocus?: boolean; } export interface ICloseEditorOptions { @@ -480,6 +485,12 @@ export interface IEditorGroupsContainer { */ export interface IEditorPart extends IEditorGroupsContainer { + /** + * Whether the part is owned by someone else than the editor parts service, + * in which case it is not part of working sets. + */ + readonly isTransient?: boolean; + /** * An event for when the editor part receives focus. */ @@ -538,9 +549,12 @@ export interface IAuxiliaryEditorPart extends IEditorPart { * dirty editors of all groups back to the main editor * part. * + * @param options `preserveFocus` keeps the focus where it is instead of + * moving it to the group that received the editors. + * * @returns `false` if an editor could not be moved back. */ - close(): boolean; + close(options?: { preserveFocus?: boolean }): boolean; } /** @@ -735,7 +749,31 @@ export interface IEditorWorkingSet { readonly name: string; } +export interface IResolvedEditorWorkingSet extends IDisposable { + + /** + * The editors of the main part's groups, in group and editor order, with an editor shown in several groups listed once. + */ + readonly editors: readonly EditorInput[]; + + /** + * The editor that was active in the main part's active group. + */ + readonly activeEditor: EditorInput | undefined; + + /** + * Disposes the editors that no group shows, as the editors are not needed: editors that are shown, such as + * an editor of a file that another group has open as well, stay open. + */ + dispose(): void; +} + export interface IEditorWorkingSetOptions { + + /** + * Keeps the focus where it is: focus outside of the editor parts is not touched, + * and focus inside of an editor part moves to the new active editor. + */ readonly preserveFocus?: boolean; } @@ -851,6 +889,14 @@ export interface IEditorGroupsService extends IEditorGroupsContainer { */ applyWorkingSet(workingSet: IEditorWorkingSet | 'empty', options?: IEditorWorkingSetOptions): Promise<boolean>; + /** + * Resolves the editors of the main part of a working set without applying it or + * changing any part. The returned editors are the caller's to show or to dispose. + * + * @returns `undefined` when the working set does not exist, or when it has editors that cannot be restored. + */ + resolveWorkingSet(workingSet: IEditorWorkingSet): IResolvedEditorWorkingSet | undefined; + /** * Deletes a working set. */ diff --git a/src/vs/workbench/services/editor/test/browser/editorGroupsService.test.ts b/src/vs/workbench/services/editor/test/browser/editorGroupsService.test.ts index d8a5207b0e06..fb5fa87ad3b7 100644 --- a/src/vs/workbench/services/editor/test/browser/editorGroupsService.test.ts +++ b/src/vs/workbench/services/editor/test/browser/editorGroupsService.test.ts @@ -4,12 +4,16 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { workbenchInstantiationService, registerTestEditor, TestFileEditorInput, TestEditorPart, TestServiceAccessor, ITestInstantiationService, workbenchTeardown, createEditorParts, TestEditorParts, TestLayoutService } from '../../../../test/browser/workbenchTestServices.js'; +import { createSandbox } from 'sinon'; +import { Action } from '../../../../../base/common/actions.js'; +import { DeferredPromise } from '../../../../../base/common/async.js'; +import { workbenchInstantiationService, registerTestEditor, TestFileEditorInput, TestEditorPart, TestServiceAccessor, ITestInstantiationService, workbenchTeardown, createEditorParts, TestEditorParts, TestLayoutService, TestMenuService } from '../../../../test/browser/workbenchTestServices.js'; +import { IMenu, IMenuService, MenuId } from '../../../../../platform/actions/common/actions.js'; import { GroupDirection, GroupsOrder, MergeGroupMode, GroupOrientation, GroupLocation, isEditorGroup, IEditorGroupsService, GroupsArrangement, IEditorGroupContextKeyProvider, GroupActivationReason, IEditorGroupActivationEvent } from '../../common/editorGroupsService.js'; import { CloseDirection, IEditorPartOptions, EditorsOrder, EditorInputCapabilities, GroupModelChangeKind, SideBySideEditor, IEditorFactoryRegistry, EditorExtensions } from '../../../../common/editor.js'; import { URI } from '../../../../../base/common/uri.js'; import { SyncDescriptor } from '../../../../../platform/instantiation/common/descriptors.js'; -import { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; import { MockScopableContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { ConfirmResult } from '../../../../../platform/dialogs/common/dialogs.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -74,6 +78,180 @@ suite('EditorGroupsService', () => { return input; } + async function createToolbarTestGroup() { + const [part, instantiationService] = await createPart(); + const group = part.activeGroup; + const change = disposables.add(new Emitter<void>()); + const action = (label: string) => disposables.add(new Action(label, label)); + const previousActions = [action('Old One'), action('Old Two')]; + const previousLayoutActions = [action('Old Layout')]; + const nextActions = [action('New Action')]; + const nextLayoutActions = [action('New Layout')]; + let primary = previousActions; + let layout = previousLayoutActions; + const sandbox = createSandbox(); + disposables.add(toDisposable(() => sandbox.restore())); + sandbox.stub(group, 'createEditorActions').callsFake((_store, menuId) => ({ + actions: { primary: menuId === MenuId.EditorTitleLayout ? layout : primary, secondary: [] }, + onDidChange: change.event + })); + await group.openEditor(createTestFileEditorInput(URI.file('/toolbar/initial.txt'), TEST_EDITOR_INPUT_ID), { pinned: true }); + + return { + part, + group, + editorService: instantiationService.createInstance(TestServiceAccessor).editorService, + setActions(next: boolean | undefined) { + primary = next === undefined ? [] : next ? nextActions : previousActions; + layout = next === undefined ? [] : next ? nextLayoutActions : previousLayoutActions; + change.fire(); + }, + snapshot() { + const toolbar = group.element.querySelector<HTMLElement>('.editor-actions, .title-actions')!; + return { + actions: Array.from(toolbar.querySelectorAll('.action-label'), action => action.getAttribute('aria-label')), + layout: Array.from(group.element.querySelectorAll('.editor-layout-actions .action-label'), action => action.getAttribute('aria-label')), + inert: toolbar.inert, + }; + } + }; + } + + function createPendingToolbarInput(name: string) { + const started = new DeferredPromise<void>(); + const resolved = new DeferredPromise<void>(); + disposables.add(toDisposable(() => resolved.complete())); + const input = disposables.add(new class extends TestFileEditorInput { + override async resolve() { + started.complete(); + await resolved.p; + return null; + } + }(URI.file(`/toolbar/${name}`), TEST_EDITOR_INPUT_ID)); + return { input, started: started.p, resolved }; + } + + test('editor toolbar stays unchanged when reopening the current editor', async () => { + const toolbar = await createToolbarTestGroup(); + const firstAction = toolbar.group.element.querySelector('.editor-actions .action-label'); + const opening = toolbar.group.openEditor(toolbar.group.activeEditor!, { pinned: true }); + const pending = toolbar.snapshot().inert; + await opening; + + assert.deepStrictEqual({ + pending, + ready: toolbar.snapshot().inert, + retainedAction: toolbar.group.element.querySelector('.editor-actions .action-label') === firstAction + }, { pending: false, ready: false, retainedAction: true }); + }); + + test('editor toolbar changes once when the replacement editor is ready', async () => { + const toolbar = await createToolbarTestGroup(); + const incoming = createPendingToolbarInput('next.md'); + const opening = toolbar.group.openEditor(incoming.input, { pinned: true }); + await incoming.started; + toolbar.setActions(undefined); + const loading = toolbar.snapshot(); + toolbar.setActions(true); + await incoming.resolved.complete(); + await opening; + const ready = toolbar.snapshot(); + toolbar.setActions(false); + + assert.deepStrictEqual({ loading, ready, liveUpdate: toolbar.snapshot() }, { + loading: { actions: ['Old One', 'Old Two'], layout: ['Old Layout'], inert: true }, + ready: { actions: ['New Action'], layout: ['New Layout'], inert: false }, + liveUpdate: { actions: ['Old One', 'Old Two'], layout: ['Old Layout'], inert: false }, + }); + }); + + test('editor toolbar stays unchanged when reusing the current side-by-side editor', async () => { + const toolbar = await createToolbarTestGroup(); + const input = toolbar.group.activeEditor!; + const sideBySide = disposables.add(new SideBySideEditorInput(undefined, undefined, input, input, toolbar.editorService)); + await toolbar.group.openEditor(sideBySide, { pinned: true }); + await toolbar.group.closeEditor(input); + const firstAction = toolbar.group.element.querySelector('.editor-actions .action-label'); + const opening = toolbar.group.openEditor(input, { pinned: true }); + const pending = toolbar.snapshot().inert; + await opening; + + assert.deepStrictEqual({ + pending, + retainedEditor: toolbar.group.activeEditor === sideBySide, + retainedAction: toolbar.group.element.querySelector('.editor-actions .action-label') === firstAction + }, { pending: false, retainedEditor: true, retainedAction: true }); + }); + + test('editor toolbar ignores superseded editor completion in either order', async () => { + const toolbar = await createToolbarTestGroup(); + const results = []; + for (const olderFirst of [true, false]) { + toolbar.setActions(false); + const older = createPendingToolbarInput(`older-${olderFirst}.txt`); + const newer = createPendingToolbarInput(`newer-${olderFirst}.md`); + const first = toolbar.group.openEditor(older.input, { pinned: true }); + await older.started; + const second = toolbar.group.openEditor(newer.input, { pinned: true }); + await newer.started; + toolbar.setActions(undefined); + if (olderFirst) { + await older.resolved.complete(); + await first; + results.push(toolbar.snapshot()); + } + toolbar.setActions(true); + await newer.resolved.complete(); + await second; + if (!olderFirst) { + results.push(toolbar.snapshot()); + await older.resolved.complete(); + await first; + } + results.push(toolbar.snapshot()); + } + assert.deepStrictEqual(results, [ + { actions: ['Old One', 'Old Two'], layout: ['Old Layout'], inert: true }, + { actions: ['New Action'], layout: ['New Layout'], inert: false }, + { actions: ['New Action'], layout: ['New Layout'], inert: false }, + { actions: ['New Action'], layout: ['New Layout'], inert: false }, + ]); + }); + + test('editor toolbar resumes after an editor fails to open', async () => { + const toolbar = await createToolbarTestGroup(); + const incoming = createPendingToolbarInput('failed.txt'); + const opening = toolbar.group.openEditor(incoming.input, { pinned: true }); + await incoming.started; + toolbar.setActions(undefined); + const loading = toolbar.snapshot(); + await incoming.resolved.error(new Error('Test editor failed to resolve')); + await opening; + toolbar.setActions(true); + + assert.deepStrictEqual({ loading, recovered: toolbar.snapshot() }, { + loading: { actions: ['Old One', 'Old Two'], layout: ['Old Layout'], inert: true }, + recovered: { actions: ['New Action'], layout: ['New Layout'], inert: false }, + }); + }); + + test('editor toolbar refreshes a tabs control recreated during opening', async () => { + const toolbar = await createToolbarTestGroup(); + const incoming = createPendingToolbarInput('recreated.md'); + const opening = toolbar.group.openEditor(incoming.input, { pinned: true }); + await incoming.started; + disposables.add(toolbar.part.enforcePartOptions({ showTabs: 'single' })); + const loading = toolbar.snapshot(); + toolbar.setActions(true); + await incoming.resolved.complete(); + await opening; + + assert.deepStrictEqual({ loading, ready: toolbar.snapshot() }, { + loading: { actions: [], layout: [], inert: true }, + ready: { actions: ['New Action'], layout: ['New Layout'], inert: false }, + }); + }); + test('groups basics', async function () { const instantiationService = workbenchInstantiationService({ contextKeyService: instantiationService => instantiationService.createInstance(MockScopableContextKeyService) }, disposables); const [part] = await createPart(instantiationService); @@ -249,6 +427,25 @@ suite('EditorGroupsService', () => { assert.strictEqual(part.count, 2); }); + test('main part shows the new tab button of its menu in the tab bar of its groups', async () => { + const instantiationService = workbenchInstantiationService({ contextKeyService: instantiationService => instantiationService.createInstance(MockScopableContextKeyService) }, disposables); + const requestedMenus: MenuId[] = []; + instantiationService.stub(IMenuService, new class extends TestMenuService { + override createMenu(id: MenuId, contextKeyService: IContextKeyService): IMenu { + requestedMenus.push(id); + return super.createMenu(id, contextKeyService); + } + }); + const [part] = await createPart(instantiationService); + part.addGroup(part.activeGroup, GroupDirection.RIGHT); + + assert.deepStrictEqual({ + requested: requestedMenus.filter(id => id === MenuId.EditorTabsBarAddTab).length, + // Hidden while its menu has no entries, as while the setting is off. + hidden: [...part.element.querySelectorAll('.tabs-bar-add-tab')].map(element => element.classList.contains('hidden')), + }, { requested: 2, hidden: [true, true] }); + }); + test('save & restore state', async function () { const [part, instantiationService] = await createPart(); diff --git a/src/vs/workbench/services/editor/test/browser/editorParts.test.ts b/src/vs/workbench/services/editor/test/browser/editorParts.test.ts index 0058ff74b4ff..64c2ae991bd1 100644 --- a/src/vs/workbench/services/editor/test/browser/editorParts.test.ts +++ b/src/vs/workbench/services/editor/test/browser/editorParts.test.ts @@ -5,6 +5,9 @@ import assert from 'assert'; import { mainWindow } from '../../../../../base/browser/window.js'; +import { timeout } from '../../../../../base/common/async.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { IEditorOptions } from '../../../../../platform/editor/common/editor.js'; import { URI } from '../../../../../base/common/uri.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; @@ -25,8 +28,12 @@ import { IEditorGroupView, IEditorGroupViewOptions, IEditorPartsView } from '../ import { EditorPart } from '../../../../browser/parts/editor/editorPart.js'; import { PART_GRID_CLASS } from '../../../../browser/parts/editor/partGridClass.js'; import { EditorGroupLockActionsHiddenContext } from '../../../../common/contextkeys.js'; -import { EditorExtensions, IEditorFactoryRegistry } from '../../../../common/editor.js'; -import { createEditorParts, TestEditorParts, TestFileEditorInput, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; +import { EditorExtensions, EditorsOrder, IEditorFactoryRegistry, IEditorOpenContext, IEditorSerializer } from '../../../../common/editor.js'; +import { EditorPane } from '../../../../browser/parts/editor/editorPane.js'; +import { EditorPaneDescriptor, IEditorPaneRegistry } from '../../../../browser/editor.js'; +import { SyncDescriptor } from '../../../../../platform/instantiation/common/descriptors.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { createEditorParts, registerTestEditor, TestEditorParts, TestFileEditorInput, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; import { EditorInput } from '../../../../common/editor/editorInput.js'; import { UntitledTextEditorInput } from '../../../untitled/common/untitledTextEditorInput.js'; import { IUntitledTextEditorService } from '../../../untitled/common/untitledTextEditorService.js'; @@ -65,6 +72,17 @@ class TestOwnedEditorPart extends EditorPart { } } +class TestMergingEditorPart extends TestOwnedEditorPart { + + override get isTransient(): boolean { + return false; + } + + close(options?: { preserveFocus?: boolean }): boolean { + return this.mergeGroupsToMainPart(undefined, options); + } +} + suite('Editor Parts', () => { const disposables = new DisposableStore(); @@ -322,6 +340,275 @@ suite('Editor Parts', () => { parts.deleteWorkingSet(workingSet); }); + test('applying a working set keeps the focus where it is when asked, also when it merges an editor of a window back into the main part', async () => { + const { instantiationService, parts } = await createServices(); + const outside = mainWindow.document.body.appendChild(mainWindow.document.createElement('input')); + disposables.add({ dispose: () => outside.remove() }); + + const applyWith = async (preserveFocus: boolean) => { + const container = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + disposables.add({ dispose: () => container.remove() }); + const part = disposables.add(instantiationService.createInstance(TestMergingEditorPart, parts)); + disposables.add(parts.registerPart(part)); + part.create(container); + part.layout(400, 300, 0, 0); + + const dirty = disposables.add(new TestFileEditorInput(URI.file(`/dirty-${preserveFocus}.txt`), 'testTypeId')); + dirty.setDirty(); + await part.activeGroup.openEditor(dirty, { pinned: true }); + + outside.focus(); + await parts.applyWorkingSet('empty', { preserveFocus }); + return mainWindow.document.activeElement === outside; + }; + + assert.deepStrictEqual({ preserved: await applyWith(true), notPreserved: await applyWith(false) }, { preserved: true, notPreserved: false }); + }); + + test('applying a working set with preserved focus moves the focus of an editor to the new active editor and leaves other focus alone', async () => { + const { parts } = await createServices(); + const mainPart = parts.testMainPart; + const outside = mainWindow.document.body.appendChild(mainWindow.document.createElement('input')); + disposables.add({ dispose: () => outside.remove() }); + + const first = disposables.add(new TestFileEditorInput(URI.file('/first.txt'), 'testTypeId')); + await mainPart.activeGroup.openEditor(first, { pinned: true }); + const workingSet = parts.saveWorkingSet('with-editor'); + + const focusAfterApply = async () => { + await parts.applyWorkingSet('empty', { preserveFocus: true }); + return { + inEditorPart: mainPart.getContainer()!.contains(mainWindow.document.activeElement), + onBody: mainWindow.document.activeElement === mainWindow.document.body, + onOutside: mainWindow.document.activeElement === outside + }; + }; + + focusIn(mainPart.activeGroup.element.querySelector<HTMLElement>('.editor-container')!.firstElementChild as HTMLElement); + const editorFocused = await focusAfterApply(); + await parts.applyWorkingSet(workingSet, { preserveFocus: true }); + outside.focus(); + const outsideFocused = await focusAfterApply(); + + assert.deepStrictEqual({ editorFocused, outsideFocused }, { + editorFocused: { inEditorPart: true, onBody: false, onOutside: false }, + outsideFocused: { inEditorPart: false, onBody: false, onOutside: true } + }); + parts.deleteWorkingSet(workingSet); + }); + + test('applying a working set does not pull the focus back to the editor when it moved elsewhere while applying', async () => { + const { parts } = await createServices(); + const mainPart = parts.testMainPart; + const outside = mainWindow.document.body.appendChild(mainWindow.document.createElement('input')); + disposables.add({ dispose: () => outside.remove() }); + + const first = disposables.add(new TestFileEditorInput(URI.file('/first.txt'), 'testTypeId')); + await mainPart.activeGroup.openEditor(first, { pinned: true }); + focusIn(mainPart.activeGroup.element.querySelector<HTMLElement>('.editor-container')!.firstElementChild as HTMLElement); + + const applied = parts.applyWorkingSet('empty', { preserveFocus: true }); + outside.focus(); // the user moves on while the apply is pending + await applied; + + assert.strictEqual(mainWindow.document.activeElement, outside); + }); + + test('applying a working set with preserved focus recovers focus lost to the body when it started outside of the editor parts', async () => { + const { parts } = await createServices(); + const mainPart = parts.testMainPart; + const transient = mainWindow.document.body.appendChild(mainWindow.document.createElement('input')); + disposables.add({ dispose: () => transient.remove() }); + + const first = disposables.add(new TestFileEditorInput(URI.file('/first.txt'), 'testTypeId')); + await mainPart.activeGroup.openEditor(first, { pinned: true }); + + transient.focus(); + const applied = parts.applyWorkingSet('empty', { preserveFocus: true }); + transient.remove(); // like the quick input hiding while the state is applied + await applied; + + assert.strictEqual(mainPart.getContainer()!.contains(mainWindow.document.activeElement), true); + }); + + test('applying a working set with preserved focus focuses the restored editor, which opens after the state is applied', async () => { + class FocusableEditorPane extends EditorPane { + private field: HTMLInputElement | undefined; + constructor(group: IEditorGroup, @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService) { + super('focusableEditorPane', group, telemetryService, themeService, storageService); + } + protected createEditor(parent: HTMLElement): void { this.field = parent.appendChild(mainWindow.document.createElement('input')); } + override async setInput(input: EditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { + await super.setInput(input, options, context, token); + await timeout(10); + this.ready = true; + } + private ready = false; + override focus(): void { if (this.ready) { this.field?.focus(); } } + layout(): void { } + } + disposables.add(Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(EditorPaneDescriptor.create(FocusableEditorPane, 'focusableEditorPane', 'Focusable'), [new SyncDescriptor(TestFileEditorInput)])); + + disposables.add(registerTestEditor('serializerOnlyEditor', [new SyncDescriptor(TestFileEditorInput)], 'testTypeId')); + + const { parts } = await createServices(); + const mainPart = parts.testMainPart; + + const first = disposables.add(new TestFileEditorInput(URI.file('/first.txt'), 'testTypeId')); + await mainPart.activeGroup.openEditor(first, { pinned: true }); + const workingSet = parts.saveWorkingSet('with-editor'); + mainPart.activeGroup.activeEditorPane?.focus(); + assert.strictEqual(mainWindow.document.activeElement?.tagName, 'INPUT'); + + await parts.applyWorkingSet(workingSet, { preserveFocus: true }); + + assert.deepStrictEqual({ editorOpen: !!mainPart.activeGroup.activeEditorPane, focused: mainWindow.document.activeElement?.tagName }, { editorOpen: true, focused: 'INPUT' }); + await mainPart.activeGroup.closeAllEditors(); + parts.deleteWorkingSet(workingSet); + }); + + test('resolving a working set gives the editors applying it opens, without changing the part', async () => { + const { parts } = await createServices(); + disposables.add(Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer('testTypeId', class implements IEditorSerializer { + canSerialize(): boolean { return true; } + serialize(editor: EditorInput): string { return (editor as TestFileEditorInput).resource.toString(); } + deserialize(instantiationService: IInstantiationService, serializedEditor: string): EditorInput { return instantiationService.createInstance(TestFileEditorInput, URI.parse(serializedEditor), 'testTypeId'); } + })); + const first = disposables.add(new TestFileEditorInput(URI.file('/first.txt'), 'testTypeId')); + const second = disposables.add(new TestFileEditorInput(URI.file('/second.txt'), 'testTypeId')); + await parts.testMainPart.activeGroup.openEditor(first, { pinned: true }); + await parts.testMainPart.activeGroup.openEditor(second, { pinned: true }); + const workingSet = parts.saveWorkingSet('test'); + await parts.testMainPart.activeGroup.closeAllEditors(); + + const resolved = parts.resolveWorkingSet(workingSet); + const partWhileResolved = parts.testMainPart.activeGroup.count; + await parts.applyWorkingSet(workingSet); + const appliedEditors = parts.testMainPart.activeGroup.getEditors(EditorsOrder.SEQUENTIAL); + const applied = appliedEditors.map(editor => editor.resource?.toString()); + appliedEditors.forEach(editor => disposables.add(editor)); + + assert.deepStrictEqual({ + resolved: resolved?.editors.map(editor => editor.resource?.toString()), + active: resolved?.activeEditor?.resource?.toString(), + partWhileResolved, + applied, + unknown: parts.resolveWorkingSet({ id: 'unknown', name: 'unknown' }), + }, { + resolved: ['file:///first.txt', 'file:///second.txt'], + active: 'file:///second.txt', + partWhileResolved: 0, + applied: ['file:///first.txt', 'file:///second.txt'], + unknown: undefined, + }); + + resolved?.editors.forEach(editor => editor.dispose()); + parts.deleteWorkingSet(workingSet); + }); + + function registerTestSerializer() { + return Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer('testTypeId', class implements IEditorSerializer { + canSerialize(): boolean { return true; } + serialize(editor: EditorInput): string { return (editor as TestFileEditorInput).resource.toString(); } + deserialize(instantiationService: IInstantiationService, serializedEditor: string): EditorInput { return instantiationService.createInstance(TestFileEditorInput, URI.parse(serializedEditor), 'testTypeId'); } + }); + } + + test('resolving a working set gives one editor for a file shown in several groups', async () => { + const { parts } = await createServices(); + disposables.add(registerTestSerializer()); + const input = disposables.add(new TestFileEditorInput(URI.file('/shared.txt'), 'testTypeId')); + const group = parts.testMainPart.activeGroup; + const otherGroup = parts.testMainPart.addGroup(group, GroupDirection.RIGHT); + await group.openEditor(input, { pinned: true }); + await otherGroup.openEditor(input, { pinned: true }); + const workingSet = parts.saveWorkingSet('test'); + + const resolved = parts.resolveWorkingSet(workingSet); + + assert.deepStrictEqual({ + editors: resolved?.editors.map(editor => editor.resource?.toString()), + activeIsListed: resolved?.activeEditor ? resolved.editors.includes(resolved.activeEditor) : undefined, + }, { + editors: ['file:///shared.txt'], + activeIsListed: true, + }); + + resolved?.editors.forEach(editor => editor.dispose()); + parts.deleteWorkingSet(workingSet); + }); + + test('resolving a working set whose editors cannot be deserialized leaves it unchanged', async () => { + const { parts } = await createServices(); + const registration = registerTestSerializer(); + const sticky = disposables.add(new TestFileEditorInput(URI.file('/sticky.txt'), 'testTypeId')); + const regular = disposables.add(new TestFileEditorInput(URI.file('/regular.txt'), 'testTypeId')); + await parts.testMainPart.activeGroup.openEditor(sticky, { pinned: true, sticky: true }); + await parts.testMainPart.activeGroup.openEditor(regular, { pinned: true }); + const workingSet = parts.saveWorkingSet('test'); + await parts.testMainPart.activeGroup.closeAllEditors(); + registration.dispose(); + + parts.resolveWorkingSet(workingSet); + parts.resolveWorkingSet(workingSet); + disposables.add(registerTestSerializer()); + await parts.applyWorkingSet(workingSet); + const group = parts.testMainPart.activeGroup; + const editors = group.getEditors(EditorsOrder.SEQUENTIAL); + editors.forEach(editor => disposables.add(editor)); + + assert.deepStrictEqual(editors.map(editor => [editor.resource?.toString(), group.isSticky(editor)]), [['file:///sticky.txt', true], ['file:///regular.txt', false]]); + + parts.deleteWorkingSet(workingSet); + }); + + test('resolving a working set whose editors only partly deserialize gives nothing', async () => { + const { parts } = await createServices(); + disposables.add(registerTestSerializer()); + const kept = disposables.add(new TestFileEditorInput(URI.file('/kept.txt'), 'testTypeId')); + const lost = disposables.add(new TestFileEditorInput(URI.file('/lost.txt'), 'lostTypeId')); + const lostRegistration = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer('lostTypeId', class implements IEditorSerializer { + canSerialize(): boolean { return true; } + serialize(editor: EditorInput): string { return (editor as TestFileEditorInput).resource.toString(); } + deserialize(instantiationService: IInstantiationService, serializedEditor: string): EditorInput { return instantiationService.createInstance(TestFileEditorInput, URI.parse(serializedEditor), 'lostTypeId'); } + }); + await parts.testMainPart.activeGroup.openEditor(kept, { pinned: true }); + await parts.testMainPart.activeGroup.openEditor(lost, { pinned: true }); + const workingSet = parts.saveWorkingSet('test'); + await parts.testMainPart.activeGroup.closeAllEditors(); + lostRegistration.dispose(); + + assert.strictEqual(parts.resolveWorkingSet(workingSet), undefined); + + parts.deleteWorkingSet(workingSet); + }); + + test('disposing a resolved working set keeps the editors another group shows', async () => { + const { parts } = await createServices(); + const shown = disposables.add(new TestFileEditorInput(URI.file('/shown.txt'), 'testTypeId')); + disposables.add(Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer('testTypeId', class implements IEditorSerializer { + canSerialize(): boolean { return true; } + serialize(editor: EditorInput): string { return (editor as TestFileEditorInput).resource.toString(); } + deserialize(_instantiationService: IInstantiationService, serializedEditor: string): EditorInput { return serializedEditor === shown.resource.toString() ? shown : new TestFileEditorInput(URI.parse(serializedEditor), 'testTypeId'); } + })); + const own = disposables.add(new TestFileEditorInput(URI.file('/own.txt'), 'testTypeId')); + const group = parts.testMainPart.activeGroup; + await group.openEditor(shown, { pinned: true }); + await group.openEditor(own, { pinned: true }); + const workingSet = parts.saveWorkingSet('test'); + await group.closeEditor(own); + + const resolved = parts.resolveWorkingSet(workingSet); + resolved?.dispose(); + + assert.deepStrictEqual({ + shownDisposed: shown.isDisposed(), + resolvedOthersDisposed: resolved?.editors.filter(editor => editor !== shown).map(editor => editor.isDisposed()), + }, { shownDisposed: false, resolvedOthersDisposed: [true] }); + + parts.deleteWorkingSet(workingSet); + }); + async function moveGroupAcrossParts(inputs: (instantiationService: IInstantiationService) => EditorInput[]) { const { instantiationService, parts } = await createServices(); const partA = createOwnedPart(instantiationService, parts); @@ -367,6 +654,38 @@ suite('Editor Parts', () => { }, { sourceRemoved: true, partACount: 1, partAEditors: 0, partBCount: 2, targetEditors: ['/first.txt', '/second.txt'], disposed: [false, false] }); }); + test('applying an empty working set leaves a dirty and an untitled editor open with their content, without confirmation, and applying the saved one keeps them', async () => { + const { instantiationService, parts } = await createServices(); + const group = parts.testMainPart.activeGroup; + const dirty = disposables.add(new TestFileEditorInput(URI.file('/dirty.txt'), 'testTypeId')); + dirty.setDirty(); + const model = disposables.add(instantiationService.invokeFunction(accessor => accessor.get(IUntitledTextEditorService)).create({ initialValue: 'content' })); + const untitled = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, model)); + (await untitled.resolve()).textEditorModel?.setValue('changed'); + await group.openEditor(dirty, { pinned: true }); + await group.openEditor(untitled, { pinned: true }); + + const workingSet = parts.saveWorkingSet('location'); + const emptied = await parts.applyWorkingSet('empty', { preserveFocus: true }); + const whileEmpty = { editors: group.count, dirty: dirty.isDirty(), untitledDirty: untitled.isDirty(), disposed: [dirty.gotDisposed, untitled.isDisposed()] }; + const restored = await parts.applyWorkingSet(workingSet, { preserveFocus: true }); + const editors = group.getEditors(EditorsOrder.SEQUENTIAL); + + assert.deepStrictEqual({ + emptied, whileEmpty, restored, + restoredSameEditors: editors.length === 2 && editors.includes(dirty) && editors.includes(untitled), + content: (await untitled.resolve()).textEditorModel?.getValue(), + dirty: [dirty.isDirty(), untitled.isDirty()] + }, { + emptied: true, + whileEmpty: { editors: 2, dirty: true, untitledDirty: true, disposed: [false, false] }, + restored: true, + restoredSameEditors: true, + content: 'changed', + dirty: [true, true] + }); + }); + test('moving a group with a dirty editor into another part moves it without confirmation and keeps it dirty and alive', async () => { const clean = disposables.add(new TestFileEditorInput(URI.file('/clean.txt'), 'testTypeId')); const dirty = disposables.add(new TestFileEditorInput(URI.file('/dirty.txt'), 'testTypeId')); diff --git a/src/vs/workbench/services/editor/test/browser/viewEditor.test.ts b/src/vs/workbench/services/editor/test/browser/viewEditor.test.ts index cb8220f18301..b8517acd4c98 100644 --- a/src/vs/workbench/services/editor/test/browser/viewEditor.test.ts +++ b/src/vs/workbench/services/editor/test/browser/viewEditor.test.ts @@ -752,4 +752,22 @@ suite('View Editors', () => { transferAfterEnd: false }); }); + + test('the view\'s drag handle does not start a drag that something in front of it cancelled', async () => { + const { part } = await createServices(); + await part.activeGroup.openEditor(createViewInput('test.titled', '/chat/a')); + const handle = views[0].dragHandle!; + + const veto = (e: globalThis.Event) => e.preventDefault(); + handle.addEventListener('dragstart', veto, true); + dispatch(handle, 'dragstart'); + const transferWhenCancelled = editorTransfer.hasData(DraggedEditorIdentifier.prototype); + handle.removeEventListener('dragstart', veto, true); + + dispatch(handle, 'dragstart'); + const transferWhenNot = editorTransfer.hasData(DraggedEditorIdentifier.prototype); + dispatch(handle, 'dragend'); + + assert.deepStrictEqual({ transferWhenCancelled, transferWhenNot }, { transferWhenCancelled: false, transferWhenNot: true }); + }); }); diff --git a/src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts b/src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts index 2a674e633441..935430f69311 100644 --- a/src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts +++ b/src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts @@ -56,7 +56,7 @@ export class BuiltinExtensionsScannerService implements IBuiltinExtensionsScanne bundledExtensions = [/*BUILD->INSERT_BUILTIN_EXTENSIONS*/]; } else { // Find builtin extensions by checking for DOM - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const builtinExtensionsElement = mainWindow.document.getElementById('vscode-workbench-builtin-extensions'); const builtinExtensionsElementAttribute = builtinExtensionsElement ? builtinExtensionsElement.getAttribute('data-settings') : undefined; if (builtinExtensionsElementAttribute) { diff --git a/src/vs/workbench/services/extensionManagement/electron-browser/extensionGalleryAccountService.ts b/src/vs/workbench/services/extensionManagement/electron-browser/extensionGalleryAccountService.ts index 1d1cd8c855a9..dceb1a21a5bd 100644 --- a/src/vs/workbench/services/extensionManagement/electron-browser/extensionGalleryAccountService.ts +++ b/src/vs/workbench/services/extensionManagement/electron-browser/extensionGalleryAccountService.ts @@ -172,7 +172,7 @@ export class GitHubGalleryAccountProvider extends AbstractGalleryAccountProvider } } -/** Entitlement decided locally from the token's tenant claim. The bearer travels with it. */ +/** Entitlement from the sign-in token's tenant claim; only resource-scoped bearers leave the provider. */ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvider { constructor( @@ -219,10 +219,10 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi return {}; } const protectedResource = await this.getProtectedResource(cache); - if (!protectedResource || protectedResource.invalidScopes) { - return { accessToken: session.accessToken }; + if (!protectedResource || protectedResource.invalidScopes || !this.hasResourceScopes(protectedResource.scopes)) { + return {}; } - return { accessToken: (await this.getResourceSession(session, protectedResource))?.accessToken ?? session.accessToken }; + return { accessToken: (await this.getResourceSession(session, protectedResource))?.accessToken }; } /** Work/school tenant is eligible, personal is not. Fails closed on an unreadable token. */ @@ -259,6 +259,12 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi return session; } + private hasResourceScopes(scopes: readonly string[]): boolean { + // Microsoft authentication turns OIDC-only requests into Graph token requests. + return scopes.every(scope => !scope.startsWith('VSCODE_')) + && scopes.some(scope => !['openid', 'email', 'profile', 'offline_access'].includes(scope)); + } + /** * Requests the resource-scoped session (RFC 8707) for the already-chosen account. The * marketplace names its own authorization server, so it is the authentication provider that @@ -266,12 +272,11 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi * treated here as simply having no session. */ private async getResourceSession(session: AuthenticationSession, protectedResource: IMarketplaceProtectedResource): Promise<AuthenticationSession | undefined> { - const resourceScopes = protectedResource.scopes.length ? [...protectedResource.scopes] : this.scopes; - if (!resourceScopes) { + if (!this.hasResourceScopes(protectedResource.scopes)) { return undefined; } try { - const sessions = await this.authenticationService.getSessions('microsoft', resourceScopes, { + const sessions = await this.authenticationService.getSessions('microsoft', [...protectedResource.scopes], { account: session.account, authorizationServer: URI.parse(protectedResource.authorizationServer) }); @@ -349,6 +354,9 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi this.logService.warn('[Marketplace] Ignoring invalid protected resource scopes'); return { authorizationServer, scopes: [], invalidScopes: true }; } + if (!this.hasResourceScopes(scopes)) { + this.logService.warn('[Marketplace] No usable marketplace resource scopes are advertised. Requests will be rejected if the marketplace requires authentication. Contact the marketplace administrator to configure scopes_supported.'); + } return { authorizationServer, scopes }; } catch { return attempts.length > 0 && attempts.every(attempt => attempt.status === 404 || attempt.status === 410) ? null : undefined; @@ -422,7 +430,7 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi return; } const protectedResource = await this.getProtectedResource(cache, true); - if (!protectedResource || protectedResource.invalidScopes) { + if (!protectedResource || protectedResource.invalidScopes || !this.hasResourceScopes(protectedResource.scopes)) { return; } if (await this.getResourceSession(session, protectedResource)) { @@ -431,12 +439,8 @@ export class MicrosoftGalleryAccountProvider extends AbstractGalleryAccountProvi if (this._store.isDisposed || this.protectedResourceCache !== cache || cache.value !== protectedResource || isExpired(cache.expiresAt)) { return; } - const resourceScopes = protectedResource.scopes.length ? [...protectedResource.scopes] : this.scopes; - if (!resourceScopes) { - return; - } try { - await this.authenticationService.createSession('microsoft', resourceScopes, { + await this.authenticationService.createSession('microsoft', [...protectedResource.scopes], { account: session.account, authorizationServer: URI.parse(protectedResource.authorizationServer) }); diff --git a/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryAccountService.test.ts b/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryAccountService.test.ts index 6193f02187d4..702992ed0754 100644 --- a/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryAccountService.test.ts +++ b/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryAccountService.test.ts @@ -33,6 +33,7 @@ suite('MicrosoftGalleryAccountProvider - protected resource metadata', () => { const resourceScopes = ['marketplace.read']; const cacheLifetime = 5 * 60 * 1000; const absenceLifetime = 30 * 1000; + const scopeWarning = '[Marketplace] No usable marketplace resource scopes are advertised. Requests will be rejected if the marketplace requires authentication. Contact the marketplace administrator to configure scopes_supported.'; const session: AuthenticationSession = { id: 'session', accessToken: 'signin-token', @@ -48,6 +49,7 @@ suite('MicrosoftGalleryAccountProvider - protected resource metadata', () => { let requestHandler: (options: IRequestOptions) => IRequestContext | Promise<IRequestContext>; let requests: IRequestOptions[]; let createdSessions: { scopes: readonly string[]; authorizationServer: string | undefined }[]; + let warnings: string[]; function response(body: object, statusCode = 200): IRequestContext { return { res: { headers: {}, statusCode }, stream: bufferToStream(VSBuffer.fromString(JSON.stringify(body))) }; @@ -68,6 +70,7 @@ suite('MicrosoftGalleryAccountProvider - protected resource metadata', () => { requestHandler = () => metadataResponse(); requests = []; createdSessions = []; + warnings = []; instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = Event.None; @@ -101,7 +104,11 @@ suite('MicrosoftGalleryAccountProvider - protected resource metadata', () => { }); instantiationService.stub(IStorageService, store.add(new InMemoryStorageService())); instantiationService.stub(ITelemetryService, new NullTelemetryServiceShape()); - instantiationService.stub(ILogService, store.add(new NullLogService())); + instantiationService.stub(ILogService, store.add(new class extends NullLogService { + override warn(message: string): void { + warnings.push(message); + } + }())); }); test('reuses successful metadata without caching credentials', async () => { @@ -110,13 +117,47 @@ suite('MicrosoftGalleryAccountProvider - protected resource metadata', () => { resourceToken = 'updated-resource-token'; const second = await provider.getAccount(marketplaceUrl); - assert.deepStrictEqual({ first: first?.accessToken, second: second?.accessToken, requests: requests.map(request => ({ url: request.url, authorization: request.headers?.Authorization })) }, { + assert.deepStrictEqual({ first: first?.accessToken, second: second?.accessToken, requests: requests.map(request => ({ url: request.url, authorization: request.headers?.Authorization })), warnings }, { first: 'resource-token', second: 'updated-resource-token', requests: [{ url: metadataUrl, authorization: undefined }], + warnings: [], }); }); + for (const { name, scopes } of [ + { name: 'omitted', scopes: undefined }, + { name: 'empty', scopes: [] }, + { name: 'OIDC-only', scopes: ['openid', 'profile', 'email', 'offline_access'] }, + { name: 'internal', scopes: ['VSCODE_TENANT:tenant'] }, + { name: 'mixed internal', scopes: [...resourceScopes, 'VSCODE_CLIENT_ID:client'] }, + ]) { + test(`warns once per discovery for ${name} scopes without credentials or resource consent`, () => runWithFakedTimers({}, async () => { + requestHandler = () => response({ resource: marketplaceUrl, authorization_servers: [authorizationServer], scopes_supported: scopes }); + let resourceLookups = 0; + resourceSessions = async () => { + resourceLookups++; + return [{ ...session, accessToken: resourceToken }]; + }; + const provider = createProvider(); + const accounts = await Promise.all([provider.getAccount(marketplaceUrl), provider.getAccount(marketplaceUrl)]); + accounts.push(await provider.getAccount(marketplaceUrl)); + await provider.signIn(); + const beforeExpiration = { requests: requests.length, warnings: [...warnings] }; + await timeout(cacheLifetime); + accounts.push(await provider.getAccount(marketplaceUrl)); + + assert.deepStrictEqual({ accounts, beforeExpiration, requests: requests.length, warnings, resourceLookups, createdSessions }, { + accounts: [{}, {}, {}, {}], + beforeExpiration: { requests: 1, warnings: [scopeWarning] }, + requests: 2, + warnings: [scopeWarning, scopeWarning], + resourceLookups: 0, + createdSessions: [{ scopes: signInScopes, authorizationServer: undefined }], + }); + })); + } + test('coalesces concurrent metadata lookups', async () => { const pending = new DeferredPromise<IRequestContext>(); const started = new DeferredPromise<void>(); diff --git a/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryManifestService.test.ts b/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryManifestService.test.ts index 9ffd95dc299b..74e4d0ab0e62 100644 --- a/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryManifestService.test.ts +++ b/src/vs/workbench/services/extensionManagement/test/electron-browser/extensionGalleryManifestService.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import { bufferToStream, encodeBase64, VSBuffer } from '../../../../../base/common/buffer.js'; import { IDefaultAccount, IEntitlementsData } from '../../../../../base/common/defaultAccount.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; +import { IChannel } from '../../../../../base/parts/ipc/common/ipc.js'; import { IRequestContext, IRequestOptions } from '../../../../../base/parts/request/common/request.js'; import { mock } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; @@ -15,7 +16,7 @@ import { IConfigurationChangeEvent, IConfigurationService } from '../../../../.. import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { IEnvironmentService } from '../../../../../platform/environment/common/environment.js'; -import { ExtensionGalleryManifestStatus, ExtensionGalleryAuthProviderConfigKey, ExtensionGalleryServiceUrlConfigKey, IExtensionGalleryManifestService } from '../../../../../platform/extensionManagement/common/extensionGalleryManifest.js'; +import { ExtensionGalleryManifestStatus, ExtensionGalleryAuthProviderConfigKey, ExtensionGalleryServiceUrlConfigKey, IExtensionGalleryManifest, IExtensionGalleryManifestService } from '../../../../../platform/extensionManagement/common/extensionGalleryManifest.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ISharedProcessService } from '../../../../../platform/ipc/electron-browser/services.js'; @@ -29,7 +30,7 @@ import { NullTelemetryServiceShape } from '../../../../../platform/telemetry/com import { IConfirmation, IDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticationCreateSessionOptions, IAuthenticationGetSessionsOptions, IAuthenticationService, IAuthenticationWwwAuthenticateRequest } from '../../../authentication/common/authentication.js'; import { IHostService } from '../../../host/browser/host.js'; -import { IRemoteAgentService } from '../../../remote/common/remoteAgentService.js'; +import { IRemoteAgentConnection, IRemoteAgentService } from '../../../remote/common/remoteAgentService.js'; import { WorkbenchExtensionGalleryManifestService } from '../../electron-browser/extensionGalleryManifestService.js'; import { ExtensionGalleryAccountService, GitHubGalleryAccountProvider, MicrosoftGalleryAccountProvider } from '../../electron-browser/extensionGalleryAccountService.js'; import { ExtensionGalleryAccountStatus, IExtensionGalleryAccountService } from '../../common/extensionGalleryAccount.js'; @@ -106,6 +107,7 @@ suite('WorkbenchExtensionGalleryManifestService', () => { let onDidChangeDefaultAccount: Emitter<IDefaultAccount | null>; let onDidChangeSessions: Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }>; let requestHandler: (options: IRequestOptions) => IRequestContext | Promise<IRequestContext>; + let marketplaceRequests: IRequestOptions[]; let defaultAccount: IDefaultAccount | null; let microsoftSessions: AuthenticationSession[]; let configurationService: TestConfigurationService; @@ -115,14 +117,17 @@ suite('WorkbenchExtensionGalleryManifestService', () => { let sharedAuthorizationError: Error | undefined; let authorizationService: IExtensionGalleryManifestService; let accountService: ExtensionGalleryAccountService; + let marketplaceWarnings: string[]; setup(() => { defaultAccount = null; microsoftSessions = []; requestHandler = () => mockResponse(200, createGalleryManifest()); + marketplaceRequests = []; storageData = new Map(); restartPrompts = []; sharedAuthorizationError = undefined; + marketplaceWarnings = []; onDidChangeDefaultAccount = disposableStore.add(new Emitter<IDefaultAccount | null>()); onDidChangeSessions = disposableStore.add(new Emitter<{ providerId: string; label: string; event: AuthenticationSessionsChangeEvent }>()); @@ -175,6 +180,7 @@ suite('WorkbenchExtensionGalleryManifestService', () => { }()); instantiationService.stub(ISharedProcessService, new class extends mock<ISharedProcessService>() { + override registerChannel(): void { } override getChannel(_channelName: string): any { return { call: () => { @@ -192,6 +198,7 @@ suite('WorkbenchExtensionGalleryManifestService', () => { instantiationService.stub(IRequestService, new class extends mock<IRequestService>() { override async request(options: IRequestOptions) { + marketplaceRequests.push(options); return requestHandler(options); } }()); @@ -201,7 +208,11 @@ suite('WorkbenchExtensionGalleryManifestService', () => { override async getDefaultAccount() { return defaultAccount; } }()); - instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(ILogService, new class extends NullLogService { + override warn(message: string): void { + marketplaceWarnings.push(message); + } + }()); instantiationService.stub(IDialogService, new class extends mock<IDialogService>() { override async confirm(confirmation: IConfirmation) { restartPrompts.push(confirmation.message); return { confirmed: false }; } @@ -249,10 +260,12 @@ suite('WorkbenchExtensionGalleryManifestService', () => { test('manifest service publishes authorization from the resolved account', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); microsoftSessions = [createMicrosoftSession('signin-token')]; + stubResourceScopedAuthentication(); + requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); const service = createService(); await service.getExtensionGalleryManifest(); - assert.strictEqual(await service.getAccessToken('https://marketplace.example.com'), 'signin-token'); + assert.strictEqual(await service.getAccessToken(MARKETPLACE_URL), 'resource-token'); }); test('GitHub provider — enterprise account → Available', async () => { @@ -345,7 +358,6 @@ suite('WorkbenchExtensionGalleryManifestService', () => { test('Microsoft provider — eligible (work/school) session → Available', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - // A work/school (Entra) tenant is eligible; the index is then fetched with the session token. microsoftSessions = [createMicrosoftSession()]; requestHandler = () => mockResponse(200, createGalleryManifest()); @@ -794,7 +806,10 @@ suite('WorkbenchExtensionGalleryManifestService', () => { test('Microsoft — switching to a different eligible account publishes that account catalog', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); microsoftSessions = [createMicrosoftSession('token-a', 'ms-account-1', 'ms-session-1')]; - requestHandler = () => mockResponse(200, { ...createGalleryManifest(), resources: [{ id: 'tenantA', type: 'ExtensionQueryService' }] }); + stubResourceScopedAuthentication(); + requestHandler = options => options.url?.includes('/.well-known/oauth-protected-resource') + ? mockResponse(200, PROTECTED_RESOURCE_METADATA) + : mockResponse(200, { ...createGalleryManifest(), resources: [{ id: 'tenantA', type: 'ExtensionQueryService' }] }); const service = createService(); const first = await service.getExtensionGalleryManifest(); @@ -804,7 +819,9 @@ suite('WorkbenchExtensionGalleryManifestService', () => { // A private marketplace is account-scoped, so a different eligible account can be served a // different catalog. The already-available status must not suppress the new one. microsoftSessions = [createMicrosoftSession('token-b', 'ms-account-2', 'ms-session-2')]; - requestHandler = () => mockResponse(200, { ...createGalleryManifest(), resources: [{ id: 'tenantB', type: 'ExtensionQueryService' }] }); + requestHandler = options => options.url?.includes('/.well-known/oauth-protected-resource') + ? mockResponse(200, PROTECTED_RESOURCE_METADATA) + : mockResponse(200, { ...createGalleryManifest(), resources: [{ id: 'tenantB', type: 'ExtensionQueryService' }] }); onDidChangeSessions.fire({ providerId: 'microsoft', label: 'Microsoft', event: { added: [], removed: [], changed: [] } }); await new Promise(resolve => setTimeout(resolve, 0)); @@ -814,17 +831,20 @@ suite('WorkbenchExtensionGalleryManifestService', () => { test('Microsoft — a transient auth failure does not downgrade an available marketplace', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; let authFails = false; instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = onDidChangeSessions.event; - override async getSessions(): Promise<readonly AuthenticationSession[]> { + override async getSessions(_providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions): Promise<readonly AuthenticationSession[]> { if (authFails) { throw new Error('Auth service unavailable'); } - return [createMicrosoftSession()]; + return options?.authorizationServer + ? [{ ...createMicrosoftSession('resource-token'), scopes: [...PROTECTED_RESOURCE_METADATA.scopes_supported] }] + : microsoftSessions; } }()); - requestHandler = () => mockResponse(200, createGalleryManifest()); + requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); const service = createService(); await service.getExtensionGalleryManifest(); @@ -847,9 +867,10 @@ suite('WorkbenchExtensionGalleryManifestService', () => { test('Microsoft — authorization projection failure does not require sign in', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession()]; + microsoftSessions = [createMicrosoftSession('signin-token')]; + stubResourceScopedAuthentication(); sharedAuthorizationError = new Error('Shared process unavailable'); - requestHandler = () => mockResponse(200, createGalleryManifest()); + requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); const service = createService(); await service.getExtensionGalleryManifest(); @@ -892,7 +913,7 @@ suite('WorkbenchExtensionGalleryManifestService', () => { for (const statusCode of [200, 400, 401, 403]) { test(`Microsoft — sign-out supersedes an in-flight manifest response (${statusCode})`, async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession()]; + microsoftSessions = [createMicrosoftSession('signin-token')]; stubResourceScopedAuthentication(); let releaseRequest!: () => void; const requestBlocked = new Promise<void>(resolve => releaseRequest = resolve); @@ -931,11 +952,13 @@ suite('WorkbenchExtensionGalleryManifestService', () => { status: service.extensionGalleryManifestStatus, manifest, token: await authorizationService.getAccessToken(MARKETPLACE_URL), + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), }, { requests: [{ url: MARKETPLACE_URL, method: 'GET', authorization: 'Bearer resource-token' }], status: ExtensionGalleryManifestStatus.RequiresSignIn, manifest: null, token: undefined, + requestAuthorizations: [undefined, 'Bearer resource-token'], }); }); } @@ -1072,7 +1095,7 @@ suite('WorkbenchExtensionGalleryManifestService', () => { * Answers the marketplace's protected resource metadata, and gates the index on the * resource-scoped bearer so a test fails if the sign-in token is presented instead. */ - function gatedMarketplace(resourceToken: string, metadata?: object): (options: IRequestOptions) => IRequestContext { + function gatedMarketplace(resourceToken: string, metadata?: object, statusCode = 401): (options: IRequestOptions) => IRequestContext { return options => { if (options.url?.includes('/.well-known/oauth-protected-resource')) { return metadata @@ -1081,108 +1104,396 @@ suite('WorkbenchExtensionGalleryManifestService', () => { } return options.headers?.Authorization === `Bearer ${resourceToken}` ? mockResponse(200, createGalleryManifest()) - : mockResponse(401, { message: 'authentication required' }); + : mockResponse(statusCode, { message: 'authentication required' }); }; } const MARKETPLACE_URL = 'https://marketplace.example.com'; + const SCOPE_CONFIGURATION_WARNING = '[Marketplace] No usable marketplace resource scopes are advertised. Requests will be rejected if the marketplace requires authentication. Contact the marketplace administrator to configure scopes_supported.'; + const INVALID_SCOPE_WARNING = '[Marketplace] Ignoring invalid protected resource scopes'; const PROTECTED_RESOURCE_METADATA = { resource: 'https://marketplace.example.com', authorization_servers: ['https://login.example.com/common'], - scopes_supported: ['api://marketplace.example.com/.default'], + scopes_supported: ['api://11111111-2222-4333-8444-555555555555/access_as_user'], }; - /** Mints `resource-token` only for a request that names the advertised authorization server. */ - function stubResourceScopedAuthentication(): void { + /** Mints `resource-token` only for the advertised resource scopes and authorization server. */ + function stubResourceScopedAuthentication(resourceScopes: readonly string[] = PROTECTED_RESOURCE_METADATA.scopes_supported) { + const resourceRequests: (readonly string[] | IAuthenticationWwwAuthenticateRequest | undefined)[] = []; instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = onDidChangeSessions.event; - override async getSessions(providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { + override async getSessions(providerId: string, scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { if (providerId !== 'microsoft') { return []; } - return options?.authorizationServer ? [createMicrosoftSession('resource-token')] : microsoftSessions; + if (!options?.authorizationServer) { + return microsoftSessions; + } + resourceRequests.push(scopes); + if (options.authorizationServer.toString(true) !== PROTECTED_RESOURCE_METADATA.authorization_servers[0] + || scopes?.length !== resourceScopes.length || !scopes.every((scope, index) => scope === resourceScopes[index])) { + return microsoftSessions; + } + const session = microsoftSessions.find(session => session.account.id === options.account?.id); + return session ? [{ ...session, accessToken: 'resource-token', scopes: [...resourceScopes] }] : []; + } + override async getAccounts() { + return microsoftSessions.map(session => session.account); + } + override async createSession(_providerId: string, scopes: readonly string[] | IAuthenticationWwwAuthenticateRequest, options?: IAuthenticationCreateSessionOptions) { + if (options?.authorizationServer) { + resourceRequests.push(scopes); + } + return createMicrosoftSession('signin-token'); } - override async createSession() { return createMicrosoftSession(); } }()); + return resourceRequests; } - test('Microsoft — gated index resolves a resource-scoped token and becomes Available', async () => { - configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession('signin-token')]; - stubResourceScopedAuthentication(); - // The sign-in token identifies the user but is not minted for the marketplace, so the index - // rejects it; only the token acquired against the advertised authorization server is accepted. - requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); + function recordManifestChannels() { + type ManifestArguments = readonly [IExtensionGalleryManifest | null, string | undefined, string | undefined]; + const calls: { target: string; command: string; args: ManifestArguments | undefined }[] = []; + let resolvePublished!: () => void; + const published = new Promise<void>(resolve => { resolvePublished = resolve; }); + const createChannel = (target: string): IChannel => new class extends mock<IChannel>() { + override async call<T>(command: string, args?: ManifestArguments): Promise<T> { + calls.push({ target, command, args }); + if (calls.length === 2) { + resolvePublished(); + } + return undefined as T; + } + }(); + const sharedChannel = createChannel('shared'); + const remoteChannel = createChannel('remote'); + instantiationService.stub(ISharedProcessService, new class extends mock<ISharedProcessService>() { + override registerChannel(): void { } + override getChannel<T extends IChannel>(): T { + return sharedChannel as T; + } + }()); + const remoteConnection = disposableStore.add(new class extends mock<IRemoteAgentConnection>() { + override registerChannel(): void { } + override getChannel<T extends IChannel>(): T { + return remoteChannel as T; + } + override dispose(): void { } + }()); + instantiationService.stub(IRemoteAgentService, new class extends mock<IRemoteAgentService>() { + override getConnection() { + return remoteConnection; + } + }()); + return { calls, published }; + } + async function assertAnonymousMarketplace( + metadata: object | undefined, + gated: boolean, + expectedStatus = gated ? ExtensionGalleryManifestStatus.RequiresSignIn : ExtensionGalleryManifestStatus.Available, + statusCode = 401, + expectedScopeWarnings: readonly string[] = [], + ): Promise<void> { + const marketplace = gatedMarketplace('resource-token', metadata, statusCode); + requestHandler = options => !gated && options.url === MARKETPLACE_URL + ? mockResponse(200, createGalleryManifest()) + : marketplace(options); + const { calls, published } = recordManifestChannels(); const service = createService(); - await service.getExtensionGalleryManifest(); + const manifest = await service.getExtensionGalleryManifest(); + await published; - assert.strictEqual(service.extensionGalleryManifestStatus, ExtensionGalleryManifestStatus.Available); - assert.strictEqual(await authorizationService.getAccessToken(MARKETPLACE_URL), 'resource-token'); - }); + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + requests: marketplaceRequests.map(request => ({ url: request.url, authorization: request.headers?.Authorization })), + channelCalls: calls, + accessToken: await authorizationService.getAccessToken(MARKETPLACE_URL), + scopeWarnings: marketplaceWarnings, + }, { + status: expectedStatus, + requests: [ + { url: `${MARKETPLACE_URL}/.well-known/oauth-protected-resource`, authorization: undefined }, + { url: MARKETPLACE_URL, authorization: undefined }, + ], + channelCalls: ['shared', 'remote'].map(target => ({ + target, + command: 'setExtensionGalleryManifest', + args: [manifest, undefined, gated ? undefined : MARKETPLACE_URL], + })), + accessToken: undefined, + scopeWarnings: expectedScopeWarnings, + }); + } - test('Microsoft — an index without protected resource metadata uses the sign-in token', async () => { - configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession('signin-token')]; - let wellKnownRequests = 0; - requestHandler = options => { - if (options.url?.includes('/.well-known/oauth-protected-resource')) { - wellKnownRequests++; - } - return mockResponse(200, createGalleryManifest()); - }; + for (const resourceScopes of [ + PROTECTED_RESOURCE_METADATA.scopes_supported, + ['api://11111111-2222-4333-8444-555555555555/.default'], + ['openid', 'api://11111111-2222-4333-8444-555555555555/access_as_user', 'offline_access'], + ]) { + test(`Microsoft - gated index resolves advertised scopes ${resourceScopes.join(', ')} without inferring the resource`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(resourceScopes); + requestHandler = gatedMarketplace('resource-token', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: resourceScopes }); + const { calls, published } = recordManifestChannels(); - const service = createService(); - await service.getExtensionGalleryManifest(); + const service = createService(); + const manifest = await service.getExtensionGalleryManifest(); + await published; - assert.strictEqual(service.extensionGalleryManifestStatus, ExtensionGalleryManifestStatus.Available); - assert.strictEqual(wellKnownRequests, 1); - assert.strictEqual(await authorizationService.getAccessToken(MARKETPLACE_URL), 'signin-token'); + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + resourceRequests, + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), + channelCalls: calls, + accessToken: await authorizationService.getAccessToken(MARKETPLACE_URL), + }, { + status: ExtensionGalleryManifestStatus.Available, + resourceRequests: [resourceScopes], + requestAuthorizations: [undefined, 'Bearer resource-token'], + channelCalls: ['shared', 'remote'].map(target => ({ + target, + command: 'setExtensionGalleryManifest', + args: [manifest, 'resource-token', MARKETPLACE_URL], + })), + accessToken: 'resource-token', + }); + }); + } + + test('Microsoft — an index without protected resource metadata uses anonymous requests', async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + stubResourceScopedAuthentication(); + await assertAnonymousMarketplace(undefined, false); }); test('Microsoft — gated index advertising no protected resource → RequiresSignIn without a token', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); microsoftSessions = [createMicrosoftSession('signin-token')]; stubResourceScopedAuthentication(); - // The index gates every read but publishes no metadata, so no token can be minted for it. - requestHandler = gatedMarketplace('resource-token'); + await assertAnonymousMarketplace(undefined, true); + }); - const service = createService(); - await service.getExtensionGalleryManifest(); + for (const [scenario, metadata, expectedScopeWarnings] of [ + ['malformed metadata', { authorization_servers: PROTECTED_RESOURCE_METADATA.authorization_servers }, []], + ['malformed scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: 'openid' }, []], + ['no authorization server', { ...PROTECTED_RESOURCE_METADATA, authorization_servers: [] }, []], + ['missing resource scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: undefined }, [SCOPE_CONFIGURATION_WARNING]], + ['empty resource scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [] }, [SCOPE_CONFIGURATION_WARNING]], + ['blank resource scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [' '] }, [INVALID_SCOPE_WARNING]], + ['invalid scope entries', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [42] }, [INVALID_SCOPE_WARNING]], + ['mixed invalid resource scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [...PROTECTED_RESOURCE_METADATA.scopes_supported, ''] }, [INVALID_SCOPE_WARNING]], + ['identity-only scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: ['openid', 'profile', 'email', 'offline_access'] }, [SCOPE_CONFIGURATION_WARNING]], + ['internal authentication scopes', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: ['VSCODE_CLIENT_ID:11111111-2222-4333-8444-555555555555'] }, [SCOPE_CONFIGURATION_WARNING]], + ] as const) { + for (const gated of [false, true]) { + test(`Microsoft - ${gated ? 'gated' : 'open'} index with ${scenario} never uses identity credentials`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(); + + const status = gated + ? ExtensionGalleryManifestStatus.RequiresSignIn + : ExtensionGalleryManifestStatus.Available; + await assertAnonymousMarketplace(metadata, gated, status, 401, expectedScopeWarnings); + await accountService.signIn(); + + assert.deepStrictEqual(resourceRequests, []); + }); + } + } - assert.strictEqual(service.extensionGalleryManifestStatus, ExtensionGalleryManifestStatus.RequiresSignIn); - assert.strictEqual(await authorizationService.getAccessToken(MARKETPLACE_URL), undefined); - }); + for (const statusCode of [400, 401, 500]) { + test(`Microsoft - missing scope warnings do not change HTTP status handling (${statusCode})`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(); + + await assertAnonymousMarketplace({ ...PROTECTED_RESOURCE_METADATA, scopes_supported: [] }, true, + statusCode === 401 ? ExtensionGalleryManifestStatus.RequiresSignIn : ExtensionGalleryManifestStatus.AccessDenied, + statusCode, [SCOPE_CONFIGURATION_WARNING]); + + assert.deepStrictEqual(resourceRequests, []); + }); + } - test('Microsoft — a marketplace that still refuses the resolved identity asks to sign in, not an administrator', async () => { + test('Microsoft - a 403 remains denied without exposing identity credentials', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); microsoftSessions = [createMicrosoftSession('signin-token')]; - // The marketplace advertises its resource, but no resource-scoped session can be acquired - // silently — the tenant has not consented yet, and the access check cannot prompt. That is - // resolvable by signing in again, so it must not be reported as a denied account: the - // access-denied view only says "contact your administrator" and offers no way to act. - instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { - override readonly onDidChangeSessions = onDidChangeSessions.event; - override async getSessions(providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { - if (providerId !== 'microsoft' || options?.authorizationServer) { - return []; + const resourceRequests = stubResourceScopedAuthentication(); + requestHandler = gatedMarketplace('resource-token', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [] }, 403); + const { calls, published } = recordManifestChannels(); + const service = createService(); + const manifest = await service.getExtensionGalleryManifest(); + await published; + + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + scopeWarnings: marketplaceWarnings, + manifest, + resourceRequests, + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), + channelCalls: calls, + accessToken: await service.getAccessToken(MARKETPLACE_URL), + }, { + status: ExtensionGalleryManifestStatus.AccessDenied, + scopeWarnings: [SCOPE_CONFIGURATION_WARNING], + manifest: null, + resourceRequests: [], + requestAuthorizations: [undefined, undefined], + channelCalls: ['shared', 'remote'].map(target => ({ + target, + command: 'setExtensionGalleryManifest', + args: [null, undefined, undefined], + })), + accessToken: undefined, + }); + }); + + for (const failure of ['not found', 'unavailable', 'malformed', 'network'] as const) { + test(`Microsoft - ${failure} metadata stays retryable without diagnosing missing scopes`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(); + requestHandler = options => { + if (options.url?.includes('/.well-known/oauth-protected-resource')) { + if (failure === 'network') { + throw new Error('network unavailable'); + } + return mockResponse(failure === 'not found' ? 404 : failure === 'unavailable' ? 503 : 200, {}); } - return microsoftSessions; - } - override async createSession() { return createMicrosoftSession(); } - }()); - requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); + return mockResponse(401, { message: 'authentication required' }); + }; + const { calls, published } = recordManifestChannels(); + const service = createService(); + await service.getExtensionGalleryManifest(); + await published; - const service = createService(); - await service.getExtensionGalleryManifest(); + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + resourceRequests, + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), + channelCalls: calls, + }, { + status: ExtensionGalleryManifestStatus.RequiresSignIn, + resourceRequests: [], + requestAuthorizations: [undefined, undefined], + channelCalls: ['shared', 'remote'].map(target => ({ + target, + command: 'setExtensionGalleryManifest', + args: [null, undefined, undefined], + })), + }); + }); + } + test('Microsoft - reloading after corrected metadata publishes only the resource token', async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(); + requestHandler = gatedMarketplace('resource-token', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [] }); + const { calls, published } = recordManifestChannels(); + let service = createService(); + await service.getExtensionGalleryManifest(); + await published; assert.strictEqual(service.extensionGalleryManifestStatus, ExtensionGalleryManifestStatus.RequiresSignIn); - assert.strictEqual(await authorizationService.getAccessToken(MARKETPLACE_URL), undefined); + + requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); + service = createService(); + const manifest = await service.getExtensionGalleryManifest(); + + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + resourceRequests, + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), + channelCalls: calls, + accessToken: await service.getAccessToken(MARKETPLACE_URL), + }, { + status: ExtensionGalleryManifestStatus.Available, + resourceRequests: [PROTECTED_RESOURCE_METADATA.scopes_supported], + requestAuthorizations: [undefined, undefined, undefined, 'Bearer resource-token'], + channelCalls: [ + ...['shared', 'remote'].map(target => ({ target, command: 'setExtensionGalleryManifest', args: [null, undefined, undefined] })), + ...['shared', 'remote'].map(target => ({ target, command: 'setExtensionGalleryManifest', args: [manifest, 'resource-token', MARKETPLACE_URL] })), + ], + accessToken: 'resource-token', + }); }); + for (const recovery of ['open marketplace', 'unavailable metadata'] as const) { + test(`Microsoft - reloading with ${recovery} does not retain a previous missing-scope diagnosis`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const resourceRequests = stubResourceScopedAuthentication(); + const metadata = { ...PROTECTED_RESOURCE_METADATA, scopes_supported: [] }; + requestHandler = gatedMarketplace('resource-token', metadata); + const { calls, published } = recordManifestChannels(); + let service = createService(); + await service.getExtensionGalleryManifest(); + await published; + assert.strictEqual(service.extensionGalleryManifestStatus, ExtensionGalleryManifestStatus.RequiresSignIn); + + const open = recovery === 'open marketplace'; + requestHandler = options => { + if (options.url?.includes('/.well-known/oauth-protected-resource')) { + return open ? mockResponse(200, metadata) : mockResponse(503, {}); + } + return open ? mockResponse(200, createGalleryManifest()) : mockResponse(401, {}); + }; + const expectedStatus = open ? ExtensionGalleryManifestStatus.Available : ExtensionGalleryManifestStatus.RequiresSignIn; + service = createService(); + const manifest = await service.getExtensionGalleryManifest(); + + assert.deepStrictEqual({ + status: service.extensionGalleryManifestStatus, + resourceRequests, + requestAuthorizations: marketplaceRequests.map(request => request.headers?.Authorization), + channelCalls: calls, + accessToken: await service.getAccessToken(MARKETPLACE_URL), + }, { + status: expectedStatus, + resourceRequests: [], + requestAuthorizations: [undefined, undefined, undefined, undefined], + channelCalls: [ + ...['shared', 'remote'].map(target => ({ target, command: 'setExtensionGalleryManifest', args: [null, undefined, undefined] })), + ...['shared', 'remote'].map(target => ({ target, command: 'setExtensionGalleryManifest', args: [manifest, undefined, open ? MARKETPLACE_URL : undefined] })), + ], + accessToken: undefined, + }); + }); + } + + for (const lookup of ['empty', 'throwing', 'unsupported'] as const) { + for (const gated of [false, true]) { + test(`Microsoft - ${gated ? 'gated' : 'open'} index with ${lookup} resource-session lookup never uses identity credentials`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + let resourceLookups = 0; + instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { + override readonly onDidChangeSessions = onDidChangeSessions.event; + override async getSessions(_providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { + if (options?.authorizationServer) { + resourceLookups++; + if (lookup !== 'empty') { + throw new Error(lookup === 'unsupported' ? 'Unsupported authorization server' : 'Auth service unavailable'); + } + return []; + } + return microsoftSessions; + } + }()); + + await assertAnonymousMarketplace(PROTECTED_RESOURCE_METADATA, gated); + + assert.strictEqual(resourceLookups, 1); + }); + } + } + test('Microsoft — a rejected bearer is not retried or retained', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession('rejected-token')]; + microsoftSessions = [createMicrosoftSession('signin-token')]; instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = onDidChangeSessions.event; override async getSessions(providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { @@ -1226,61 +1537,67 @@ suite('WorkbenchExtensionGalleryManifestService', () => { }); }); - test('Microsoft — interactive sign-in consents to the discovered marketplace resource', async () => { - configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); - microsoftSessions = [createMicrosoftSession('signin-token')]; - const createdSessions: { readonly scopes: readonly string[]; readonly authorizationServer: string | undefined }[] = []; - let resourceSession: AuthenticationSession | undefined; - instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { - override readonly onDidChangeSessions = onDidChangeSessions.event; - override async getSessions(providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { - if (providerId !== 'microsoft') { - return []; + for (const resourceScopes of [ + PROTECTED_RESOURCE_METADATA.scopes_supported, + ['api://11111111-2222-4333-8444-555555555555/.default'], + ]) { + test(`Microsoft - interactive sign-in consents to advertised scopes ${resourceScopes.join(', ')}`, async () => { + configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); + microsoftSessions = [createMicrosoftSession('signin-token')]; + const createdSessions: { readonly scopes: readonly string[]; readonly authorizationServer: string | undefined; readonly accountId: string | undefined }[] = []; + let resourceSession: AuthenticationSession | undefined; + instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { + override readonly onDidChangeSessions = onDidChangeSessions.event; + override async getSessions(providerId: string, _scopes?: readonly string[], options?: IAuthenticationGetSessionsOptions) { + if (providerId !== 'microsoft') { + return []; + } + return options?.authorizationServer ? (resourceSession ? [resourceSession] : []) : microsoftSessions; } - return options?.authorizationServer ? (resourceSession ? [resourceSession] : []) : microsoftSessions; - } - override async getAccounts() { - return microsoftSessions.map(session => session.account); - } - override async createSession(_providerId: string, scopeListOrRequest: readonly string[] | IAuthenticationWwwAuthenticateRequest, options?: IAuthenticationCreateSessionOptions) { - createdSessions.push({ - scopes: Array.isArray(scopeListOrRequest) ? scopeListOrRequest : [], - authorizationServer: options?.authorizationServer?.toString(true) - }); - if (options?.authorizationServer) { - resourceSession = createMicrosoftSession('resource-token'); - onDidChangeSessions.fire({ providerId: 'microsoft', label: 'Microsoft', event: { added: [resourceSession], removed: [], changed: [] } }); - return resourceSession; + override async getAccounts() { + return microsoftSessions.map(session => session.account); } - return createMicrosoftSession('signin-token'); - } - }()); - requestHandler = gatedMarketplace('resource-token', PROTECTED_RESOURCE_METADATA); + override async createSession(_providerId: string, scopeListOrRequest: readonly string[] | IAuthenticationWwwAuthenticateRequest, options?: IAuthenticationCreateSessionOptions) { + createdSessions.push({ + scopes: Array.isArray(scopeListOrRequest) ? scopeListOrRequest : [], + authorizationServer: options?.authorizationServer?.toString(true), + accountId: options?.account?.id + }); + if (options?.authorizationServer) { + resourceSession = { ...createMicrosoftSession('resource-token'), scopes: resourceScopes }; + onDidChangeSessions.fire({ providerId: 'microsoft', label: 'Microsoft', event: { added: [resourceSession], removed: [], changed: [] } }); + return resourceSession; + } + return createMicrosoftSession('signin-token'); + } + }()); + requestHandler = gatedMarketplace('resource-token', { ...PROTECTED_RESOURCE_METADATA, scopes_supported: resourceScopes }); - const service = createService(); - await service.getExtensionGalleryManifest(); - const initialStatus = service.extensionGalleryManifestStatus; - const available = new Promise<ExtensionGalleryManifestStatus>(resolve => { - disposableStore.add(Event.once(Event.filter(service.onDidChangeExtensionGalleryManifestStatus, status => status === ExtensionGalleryManifestStatus.Available))(resolve)); - }); - await accountService.signIn(); - await available; + const service = createService(); + await service.getExtensionGalleryManifest(); + const initialStatus = service.extensionGalleryManifestStatus; + const available = new Promise<ExtensionGalleryManifestStatus>(resolve => { + disposableStore.add(Event.once(Event.filter(service.onDidChangeExtensionGalleryManifestStatus, status => status === ExtensionGalleryManifestStatus.Available))(resolve)); + }); + await accountService.signIn(); + await available; - assert.deepStrictEqual({ - initialStatus, - status: service.extensionGalleryManifestStatus, - authorization: await service.getAccessToken(MARKETPLACE_URL), - createdSessions, - }, { - initialStatus: ExtensionGalleryManifestStatus.RequiresSignIn, - status: ExtensionGalleryManifestStatus.Available, - authorization: 'resource-token', - createdSessions: [ - { scopes: ['openid', 'profile', 'email', 'offline_access'], authorizationServer: undefined }, - { scopes: ['api://marketplace.example.com/.default'], authorizationServer: 'https://login.example.com/common' }, - ], + assert.deepStrictEqual({ + initialStatus, + status: service.extensionGalleryManifestStatus, + authorization: await service.getAccessToken(MARKETPLACE_URL), + createdSessions, + }, { + initialStatus: ExtensionGalleryManifestStatus.RequiresSignIn, + status: ExtensionGalleryManifestStatus.Available, + authorization: 'resource-token', + createdSessions: [ + { scopes: ['openid', 'profile', 'email', 'offline_access'], authorizationServer: undefined, accountId: 'ms-account-1' }, + { scopes: resourceScopes, authorizationServer: 'https://login.example.com/common', accountId: 'ms-account-1' }, + ], + }); }); - }); + } test('Microsoft — sign-out retracts the published marketplace token', async () => { configurationService.setUserConfiguration(ExtensionGalleryAuthProviderConfigKey, 'microsoft'); diff --git a/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts b/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts index a0b2866d400c..bd3fc8c25b49 100644 --- a/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts +++ b/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts @@ -16,6 +16,7 @@ import { IWorkbenchEnvironmentService } from '../../environment/common/environme import { Extensions, IExtensionFeatureMarkdownRenderer, IExtensionFeaturesRegistry, IRenderedData } from '../../extensionManagement/common/extensionFeatures.js'; import { IMarkdownString, MarkdownString } from '../../../../base/common/htmlContent.js'; import { Mutable } from '../../../../base/common/types.js'; +import { extensionsAllowedAnyApiProposal } from './extensionsProposedApiExceptions.js'; export class ExtensionsProposedApi { @@ -77,6 +78,11 @@ export class ExtensionsProposedApi { } + if (extensionsAllowedAnyApiProposal.has(key)) { + // hard-coded exception: the extension uses the proposals it declares + return; + } + if (this._productEnabledExtensions.has(key)) { // NOTE that proposals that are listed in product.json override whatever is declared in the extension // itself. This is needed for us to know what proposals are used "in the wild". Merging product.json-proposals diff --git a/src/vs/workbench/services/extensions/common/extensionsProposedApiExceptions.ts b/src/vs/workbench/services/extensions/common/extensionsProposedApiExceptions.ts new file mode 100644 index 000000000000..1f2b65e46142 --- /dev/null +++ b/src/vs/workbench/services/extensions/common/extensionsProposedApiExceptions.ts @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Extensions that may use every API proposal they declare in their package.json, in every build, + * regardless of `product.json#extensionEnabledApiProposals`. + * + * Keep this list as short as possible. Changes require approval from the API owners (see .github/CODEOWNERS). + * Entries are extension identifiers in lower case. + */ +export const extensionsAllowedAnyApiProposal: ReadonlySet<string> = new Set([ + 'ms-vscode.vscode-team-tools', +]); diff --git a/src/vs/workbench/services/extensions/test/common/extensionsProposedApi.test.ts b/src/vs/workbench/services/extensions/test/common/extensionsProposedApi.test.ts new file mode 100644 index 000000000000..cec592154b6d --- /dev/null +++ b/src/vs/workbench/services/extensions/test/common/extensionsProposedApi.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 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ExtensionIdentifier, IExtensionDescription } from '../../../../../platform/extensions/common/extensions.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { TestProductService } from '../../../../test/common/workbenchTestServices.js'; +import { IWorkbenchEnvironmentService } from '../../../environment/common/environmentService.js'; +import { nullExtensionDescription } from '../../common/extensions.js'; +import { ExtensionsProposedApi } from '../../common/extensionsProposedApi.js'; +import { extensionsAllowedAnyApiProposal } from '../../common/extensionsProposedApiExceptions.js'; + +suite('ExtensionsProposedApi', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + const builtEnvironment = { isBuilt: true, isExtensionDevelopment: false, extensionEnabledProposedApi: undefined } as IWorkbenchEnvironmentService; + + function getEnabledApiProposals(extensionId: string, extensionEnabledApiProposals: IProductService['extensionEnabledApiProposals'], declared: string[]): readonly string[] | undefined { + const productService: IProductService = { ...TestProductService, extensionEnabledApiProposals }; + const extension: IExtensionDescription = { ...nullExtensionDescription, identifier: new ExtensionIdentifier(extensionId), enabledApiProposals: declared }; + new ExtensionsProposedApi(new NullLogService(), builtEnvironment, productService).updateEnabledApiProposals([extension]); + return extension.enabledApiProposals; + } + + test('product.json allowlist overrides the extension declaration', () => { + assert.deepStrictEqual(getEnabledApiProposals('pub.ext', { 'pub.ext': ['externalUriOpener'] }, ['externalUriOpener', 'terminalShellEnv']), ['externalUriOpener']); + }); + + test('extensions not listed in product.json cannot use proposals', () => { + assert.deepStrictEqual(getEnabledApiProposals('pub.ext', {}, ['externalUriOpener']), []); + }); + + test('hard-coded exceptions use every declared proposal, even when product.json lists fewer', () => { + assert.deepStrictEqual(getEnabledApiProposals('MS-VSCODE.vscode-team-tools', { 'ms-vscode.vscode-team-tools': ['externalUriOpener'] }, ['externalUriOpener', 'terminalShellEnv', 'doesNotExist']), ['externalUriOpener', 'terminalShellEnv']); + }); + + test('hard-coded exceptions are stored in lower case', () => { + for (const id of extensionsAllowedAnyApiProposal) { + assert.strictEqual(id, ExtensionIdentifier.toKey(id)); + } + }); +}); diff --git a/src/vs/workbench/services/keybinding/browser/keybindingService.ts b/src/vs/workbench/services/keybinding/browser/keybindingService.ts index 5db49b2be121..77537e137b8e 100644 --- a/src/vs/workbench/services/keybinding/browser/keybindingService.ts +++ b/src/vs/workbench/services/keybinding/browser/keybindingService.ts @@ -441,8 +441,11 @@ export class WorkbenchKeybindingService extends AbstractKeybindingService { protected _getResolver(): KeybindingResolver { if (!this._cachedResolver) { - const defaults = this._resolveKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true); - const overrides = this._resolveUserKeybindingItems(this.userKeybindings.keybindings, false); + const { defaults, overrides } = KeybindingResolver.applyAliases( + this._resolveKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true), + this._resolveUserKeybindingItems(this.userKeybindings.keybindings, false), + KeybindingsRegistry.getKeybindingAliases() + ); this._cachedResolver = new KeybindingResolver(defaults, overrides, (str) => this._log(str)); } return this._cachedResolver; diff --git a/src/vs/workbench/services/layout/browser/layoutService.ts b/src/vs/workbench/services/layout/browser/layoutService.ts index db8216427ebc..01c233a616c5 100644 --- a/src/vs/workbench/services/layout/browser/layoutService.ts +++ b/src/vs/workbench/services/layout/browser/layoutService.ts @@ -75,13 +75,7 @@ export const enum ModernUIDensity { Compact = 'compact' } -/** - * The margin (in pixels) reserved on each side of a part when the Modern UI Update - * experiment (`LayoutSettings.MODERN_UI`) is enabled. Parts grow or shrink their - * content by this amount to leave room for the margin/border applied in CSS - * (`src/vs/workbench/browser/media/floatingPanels.css`, `.floating-panels`). - * Keep in sync with the `--vscode-spacing-size40` (4px) token used there. - */ +/** Default panel gutter, retained at exterior edges. Inter-panel spacing is resolved separately. */ export const FLOATING_PANEL_MARGIN = 4; /** @@ -93,16 +87,11 @@ export const COMPACT_FLOATING_PANEL_MARGIN = 0; * Compact Modern UI density connects the card cluster directly to the window chrome. */ export const COMPACT_FLOATING_PANEL_OUTER_MARGIN = 0; -/** - * The trailing card margin (in pixels) when the Modern UI Update experiment is - * enabled. Together with the next card's leading {@link FLOATING_PANEL_MARGIN}, - * it forms the 4px inter-card gap. Keep in sync with the - * `--vscode-spacing-sizeNone` (0px) token used in `floatingPanels.css`. - */ +/** The trailing card margin; the following card supplies the resolved inter-panel gap. */ export const FLOATING_PANEL_INNER_MARGIN = 0; export function getFloatingPanelMargin(layoutService: IWorkbenchLayoutService): number { - return layoutService.isModernUICompact() ? COMPACT_FLOATING_PANEL_MARGIN : FLOATING_PANEL_MARGIN; + return layoutService.isModernUICompact() ? COMPACT_FLOATING_PANEL_MARGIN : layoutService.getPanelSpacing(); } /** @@ -123,14 +112,14 @@ export const enum ActivityBarPosition { /** * Whether the compact menu is owned by the title bar rather than the activity bar. * This is the case when the activity bar is at the top or bottom, because the activity - * bar then lives in the side bar and disappears with the side bar. The title bar - * only owns the menu while the custom title bar is shown in the main window; otherwise - * the activity bar keeps it so that the menu remains reachable. + * bar then lives in the side bar and disappears with the side bar, and when the activity + * bar is hidden. The title bar only owns the menu while the custom title bar is shown in + * the main window; otherwise the activity bar keeps it so that the menu remains reachable. */ export function isCompactMenuInTitlebar(configurationService: IConfigurationService): boolean { const activityBarLocation = configurationService.getValue<ActivityBarPosition>(LayoutSettings.ACTIVITY_BAR_LOCATION); return getMenuBarVisibility(configurationService) === 'compact' - && (activityBarLocation === ActivityBarPosition.TOP || activityBarLocation === ActivityBarPosition.BOTTOM) + && (activityBarLocation === ActivityBarPosition.TOP || activityBarLocation === ActivityBarPosition.BOTTOM || activityBarLocation === ActivityBarPosition.HIDDEN) && shouldShowCustomTitleBar(configurationService, mainWindow); } @@ -356,7 +345,6 @@ export function getFloatingPaneCompositeVerticalMargins( } const outerEdges = getFloatingPaneCompositeVerticalOuterEdges(layoutService, partId, targetWindow); - const statusBarVisible = layoutService.isVisible(Parts.STATUSBAR_PART, targetWindow); const margin = getFloatingPanelMargin(layoutService); const outerMargin = getFloatingPanelOuterMargin(layoutService); @@ -365,7 +353,7 @@ export function getFloatingPaneCompositeVerticalMargins( ? isFloatingTopEdgeExposed(layoutService, targetWindow) ? outerMargin : FLOATING_PANEL_INNER_MARGIN : margin, bottom: outerEdges.bottom - ? statusBarVisible ? margin : outerMargin + ? outerMargin : FLOATING_PANEL_INNER_MARGIN }; } @@ -416,7 +404,7 @@ export function getFloatingEditorVerticalMargins( ? isFloatingTopEdgeExposed(layoutService, targetWindow) ? outerMargin : FLOATING_PANEL_INNER_MARGIN : margin, bottom: outerEdges.bottom - ? layoutService.isVisible(Parts.STATUSBAR_PART, targetWindow) ? margin : outerMargin + ? outerMargin : FLOATING_PANEL_INNER_MARGIN }; } @@ -587,6 +575,9 @@ export interface IWorkbenchLayoutService extends ILayoutService { */ isModernUICompact(): boolean; + /** Effective gap between panel areas, in pixels. Compact and phone layouts return zero. */ + getPanelSpacing(): number; + /** * Focuses the part in the target window. If the part is not visible this is a noop. */ @@ -762,7 +753,7 @@ export function shouldShowCustomTitleBar(configurationService: IConfigurationSer } } - if (!isTitleBarEmpty(configurationService)) { + if (!isTitleBarEmpty(configurationService, window)) { return true; } @@ -803,7 +794,7 @@ export function shouldShowCustomTitleBar(configurationService: IConfigurationSer } } -function isTitleBarEmpty(configurationService: IConfigurationService): boolean { +function isTitleBarEmpty(configurationService: IConfigurationService, window: Window): boolean { // with the command center enabled, we should always show if (configurationService.getValue<boolean>(LayoutSettings.COMMAND_CENTER)) { @@ -816,6 +807,11 @@ function isTitleBarEmpty(configurationService: IConfigurationService): boolean { return false; } + // with the activity bar hidden, the main window title bar hosts the compact menu, so we should always show + if (activityBarPosition === ActivityBarPosition.HIDDEN && !isAuxiliaryWindow(window) && getMenuBarVisibility(configurationService) === 'compact') { + return false; + } + // with the editor actions on top, we should always show const editorActionsLocation = configurationService.getValue<EditorActionsLocation>(LayoutSettings.EDITOR_ACTIONS_LOCATION); const editorTabsMode = configurationService.getValue<EditorTabsMode>(LayoutSettings.EDITOR_TABS_MODE); diff --git a/src/vs/workbench/services/mcp/browser/mcpGalleryManifestService.ts b/src/vs/workbench/services/mcp/browser/mcpGalleryManifestService.ts index 6ea431810716..71fc9e2c5b07 100644 --- a/src/vs/workbench/services/mcp/browser/mcpGalleryManifestService.ts +++ b/src/vs/workbench/services/mcp/browser/mcpGalleryManifestService.ts @@ -11,11 +11,12 @@ import { IRequestService } from '../../../../platform/request/common/request.js' import { ILogService } from '../../../../platform/log/common/log.js'; import { Emitter } from '../../../../base/common/event.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { IMcpGalleryConfig, mcpGalleryServiceUrlConfig } from '../../../../platform/mcp/common/mcpManagement.js'; +import { getConfiguredCustomMcpGalleryUrl, isProductMcpGalleryEnabled, mcpGalleryServiceEnablementConfig, mcpGalleryServiceUrlConfig } from '../../../../platform/mcp/common/mcpManagement.js'; export class WorkbenchMcpGalleryManifestService extends McpGalleryManifestService implements IMcpGalleryManifestService { private mcpGalleryManifest: IMcpGalleryManifest | null = null; + private manifestUpdateCounter = 0; private _onDidChangeMcpGalleryManifest = this._register(new Emitter<IMcpGalleryManifest | null>()); override readonly onDidChangeMcpGalleryManifest = this._onDidChangeMcpGalleryManifest.event; @@ -26,13 +27,13 @@ export class WorkbenchMcpGalleryManifestService extends McpGalleryManifestServic override readonly onDidChangeMcpGalleryManifestStatus = this._onDidChangeMcpGalleryManifestStatus.event; constructor( - @IProductService productService: IProductService, + @IProductService private readonly workbenchProductService: IProductService, @IRemoteAgentService remoteAgentService: IRemoteAgentService, @IRequestService requestService: IRequestService, @ILogService logService: ILogService, @IConfigurationService private readonly configurationService: IConfigurationService, ) { - super(productService, requestService, logService); + super(workbenchProductService, requestService, logService); const remoteConnection = remoteAgentService.getConnection(); if (remoteConnection) { const channel = remoteConnection.getChannel('mcpGalleryManifest'); @@ -56,18 +57,28 @@ export class WorkbenchMcpGalleryManifestService extends McpGalleryManifestServic await this.getAndUpdateMcpGalleryManifest(); this._register(this.configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(mcpGalleryServiceUrlConfig) || e.affectsConfiguration('chat.mcp.gallery.version')) { - this.getAndUpdateMcpGalleryManifest(); + if (e.affectsConfiguration(mcpGalleryServiceEnablementConfig) + || e.affectsConfiguration(mcpGalleryServiceUrlConfig) + || e.affectsConfiguration('chat.mcp.gallery.version')) { + void this.getAndUpdateMcpGalleryManifest(); } })); } private async getAndUpdateMcpGalleryManifest(): Promise<void> { - const mcpGalleryConfig = this.configurationService.getValue<IMcpGalleryConfig | undefined>('chat.mcp.gallery'); - if (mcpGalleryConfig?.serviceUrl) { - this.update(await this.createMcpGalleryManifest(mcpGalleryConfig.serviceUrl, mcpGalleryConfig.version)); + const updateCounter = ++this.manifestUpdateCounter; + const customMcpGalleryServiceUrl = getConfiguredCustomMcpGalleryUrl(this.configurationService, this.workbenchProductService); + let manifest: IMcpGalleryManifest | null; + if (customMcpGalleryServiceUrl) { + const customMcpGalleryServiceVersion = this.configurationService.getValue<string>('chat.mcp.gallery.version'); + manifest = await this.createMcpGalleryManifest(customMcpGalleryServiceUrl, customMcpGalleryServiceVersion); + } else if (isProductMcpGalleryEnabled(this.configurationService, this.workbenchProductService)) { + manifest = await super.getMcpGalleryManifest(); } else { - this.update(await super.getMcpGalleryManifest()); + manifest = null; + } + if (updateCounter === this.manifestUpdateCounter) { + this.update(manifest); } } diff --git a/src/vs/workbench/services/mcp/test/browser/mcpGalleryManifestService.test.ts b/src/vs/workbench/services/mcp/test/browser/mcpGalleryManifestService.test.ts new file mode 100644 index 000000000000..bae43c2c357f --- /dev/null +++ b/src/vs/workbench/services/mcp/test/browser/mcpGalleryManifestService.test.ts @@ -0,0 +1,178 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; +import { Event } from '../../../../../base/common/event.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IConfigurationChangeEvent } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { IMcpGalleryManifest, McpGalleryManifestStatus } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; +import { mcpGalleryServiceEnablementConfig, mcpGalleryServiceUrlConfig } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { IProductService } from '../../../../../platform/product/common/productService.js'; +import { IRequestService } from '../../../../../platform/request/common/request.js'; +import { TestRemoteAgentService } from '../../../../test/browser/workbenchTestServices.js'; +import { WorkbenchMcpGalleryManifestService } from '../../browser/mcpGalleryManifestService.js'; + +suite('WorkbenchMcpGalleryManifestService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const productGalleryUrl = 'https://product.test'; + const customGalleryUrl = 'https://custom.test'; + const productService = upcastPartial<IProductService>({ + mcpGallery: { + serviceUrl: productGalleryUrl, + itemWebUrl: `${productGalleryUrl}/items/{name}`, + publisherUrl: `${productGalleryUrl}/publishers/{publisher}`, + supportUrl: `${productGalleryUrl}/support`, + privacyPolicyUrl: `${productGalleryUrl}/privacy`, + termsOfServiceUrl: `${productGalleryUrl}/terms`, + reportUrl: `${productGalleryUrl}/report`, + } + }); + const requestService = upcastPartial<IRequestService>({}); + + function createService(configuration: Record<string, unknown>) { + const configurationService = new TestConfigurationService({ + 'chat.mcp.gallery.version': 'v0.1', + ...configuration, + }); + const service = store.add(new WorkbenchMcpGalleryManifestService( + productService, + new TestRemoteAgentService(), + requestService, + new NullLogService(), + configurationService, + )); + return { service, configurationService }; + } + + async function settle(): Promise<void> { + await timeout(0); + } + + function fireConfigurationChange(configurationService: TestConfigurationService, key: string): void { + configurationService.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ + affectsConfiguration: candidate => candidate === key, + })); + } + + test('selects product and custom manifests based on product gallery enablement', async () => { + const enabled = createService({ [mcpGalleryServiceEnablementConfig]: true }); + const disabled = createService({ [mcpGalleryServiceEnablementConfig]: false }); + const unset = createService({}); + const custom = createService({ + [mcpGalleryServiceEnablementConfig]: false, + [mcpGalleryServiceUrlConfig]: `${customGalleryUrl}/`, + }); + const matchingProduct = createService({ + [mcpGalleryServiceEnablementConfig]: false, + [mcpGalleryServiceUrlConfig]: `${productGalleryUrl}/`, + }); + + await Promise.all([ + enabled.service.getMcpGalleryManifest(), + disabled.service.getMcpGalleryManifest(), + unset.service.getMcpGalleryManifest(), + custom.service.getMcpGalleryManifest(), + matchingProduct.service.getMcpGalleryManifest(), + ]); + + assert.deepStrictEqual({ + enabled: (await enabled.service.getMcpGalleryManifest())?.url, + enabledStatus: enabled.service.mcpGalleryManifestStatus, + disabled: await disabled.service.getMcpGalleryManifest(), + disabledStatus: disabled.service.mcpGalleryManifestStatus, + unset: (await unset.service.getMcpGalleryManifest())?.url, + custom: (await custom.service.getMcpGalleryManifest())?.url, + customStatus: custom.service.mcpGalleryManifestStatus, + matchingProduct: await matchingProduct.service.getMcpGalleryManifest(), + }, { + enabled: productGalleryUrl, + enabledStatus: McpGalleryManifestStatus.Available, + disabled: null, + disabledStatus: McpGalleryManifestStatus.Unavailable, + unset: productGalleryUrl, + custom: customGalleryUrl, + customStatus: McpGalleryManifestStatus.Available, + matchingProduct: null, + }); + }); + + test('updates manifest and status when product gallery enablement changes', async () => { + const { service, configurationService } = createService({ [mcpGalleryServiceEnablementConfig]: true }); + await service.getMcpGalleryManifest(); + + const disabledManifest = Event.toPromise(service.onDidChangeMcpGalleryManifest); + const disabledStatus = Event.toPromise(service.onDidChangeMcpGalleryManifestStatus); + await configurationService.setUserConfiguration(mcpGalleryServiceEnablementConfig, false); + fireConfigurationChange(configurationService, mcpGalleryServiceEnablementConfig); + + assert.deepStrictEqual({ + manifest: await disabledManifest, + status: await disabledStatus, + current: await service.getMcpGalleryManifest(), + }, { + manifest: null, + status: McpGalleryManifestStatus.Unavailable, + current: null, + }); + + const enabledManifest = Event.toPromise(service.onDidChangeMcpGalleryManifest); + const enabledStatus = Event.toPromise(service.onDidChangeMcpGalleryManifestStatus); + await configurationService.setUserConfiguration(mcpGalleryServiceEnablementConfig, true); + fireConfigurationChange(configurationService, mcpGalleryServiceEnablementConfig); + + assert.deepStrictEqual({ + manifest: (await enabledManifest)?.url, + status: await enabledStatus, + current: (await service.getMcpGalleryManifest())?.url, + }, { + manifest: productGalleryUrl, + status: McpGalleryManifestStatus.Available, + current: productGalleryUrl, + }); + }); + + test('does not publish an older asynchronous manifest refresh', async () => { + const blockedManifest = new DeferredPromise<IMcpGalleryManifest>(); + const configurationService = new TestConfigurationService({ + [mcpGalleryServiceEnablementConfig]: false, + 'chat.mcp.gallery.version': 'v0.1', + }); + const service = store.add(new class extends WorkbenchMcpGalleryManifestService { + protected override async createMcpGalleryManifest(url: string, version?: string): Promise<IMcpGalleryManifest> { + if (url === customGalleryUrl) { + return blockedManifest.p; + } + return super.createMcpGalleryManifest(url, version); + } + }( + productService, + new TestRemoteAgentService(), + requestService, + new NullLogService(), + configurationService, + )); + await service.getMcpGalleryManifest(); + + await configurationService.setUserConfiguration(mcpGalleryServiceUrlConfig, customGalleryUrl); + fireConfigurationChange(configurationService, mcpGalleryServiceUrlConfig); + await configurationService.setUserConfiguration(mcpGalleryServiceUrlConfig, 'https://newer.test'); + const newerManifest = Event.toPromise(service.onDidChangeMcpGalleryManifest); + fireConfigurationChange(configurationService, mcpGalleryServiceUrlConfig); + assert.strictEqual((await newerManifest)?.url, 'https://newer.test'); + + blockedManifest.complete({ + url: customGalleryUrl, + version: 'v0.1', + resources: [], + }); + await settle(); + + assert.strictEqual((await service.getMcpGalleryManifest())?.url, 'https://newer.test'); + }); +}); diff --git a/src/vs/workbench/services/path/common/pathService.ts b/src/vs/workbench/services/path/common/pathService.ts index b32825f66855..f10542579a57 100644 --- a/src/vs/workbench/services/path/common/pathService.ts +++ b/src/vs/workbench/services/path/common/pathService.ts @@ -119,16 +119,6 @@ export abstract class AbstractPathService implements IPathService { } async getOperatingSystem(resource: URI): Promise<OperatingSystem | undefined> { - const providers = this.pathProviders.get(resource.scheme.toLowerCase()); - if (providers) { - for (let index = providers.length - 1; index >= 0; index--) { - const operatingSystem = await providers[index].getOperatingSystem(resource); - if (operatingSystem !== undefined) { - return operatingSystem; - } - } - } - if (resource.scheme === Schemas.file) { return OS; } @@ -139,6 +129,16 @@ export abstract class AbstractPathService implements IPathService { } async getPath(resource: URI): Promise<IPath | undefined> { + const providers = this.pathProviders.get(resource.scheme.toLowerCase()); + if (providers) { + for (let index = providers.length - 1; index >= 0; index--) { + const path = await providers[index].getPath(resource); + if (path !== undefined) { + return path; + } + } + } + const operatingSystem = await this.getOperatingSystem(resource); return operatingSystem === undefined ? undefined : this.pathForOperatingSystem(operatingSystem); } diff --git a/src/vs/workbench/services/path/test/browser/pathService.test.ts b/src/vs/workbench/services/path/test/browser/pathService.test.ts index 1e87f363393a..9185f35cd1d6 100644 --- a/src/vs/workbench/services/path/test/browser/pathService.test.ts +++ b/src/vs/workbench/services/path/test/browser/pathService.test.ts @@ -5,6 +5,7 @@ import assert from 'assert'; import { Schemas } from '../../../../../base/common/network.js'; +import { posix, win32 } from '../../../../../base/common/path.js'; import { OperatingSystem } from '../../../../../base/common/platform.js'; import { URI } from '../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../base/test/common/mock.js'; @@ -47,10 +48,10 @@ suite('PathService', () => { test('resolves mixed registered authorities and falls back when semantics are unknown', async () => { const pathService = createPathService(undefined); const first = disposables.add(pathService.registerPathProvider('test-remote', { - getOperatingSystem: async resource => resource.authority === 'windows' ? OperatingSystem.Windows : undefined, + getPath: async resource => resource.authority === 'windows' ? win32 : undefined, })); const second = pathService.registerPathProvider('test-remote', { - getOperatingSystem: async resource => resource.authority === 'linux' ? OperatingSystem.Linux : undefined, + getPath: async resource => resource.authority === 'linux' ? posix : undefined, }); const windows = URI.from({ scheme: 'test-remote', authority: 'windows', path: '/' }); const linux = URI.from({ scheme: 'test-remote', authority: 'linux', path: '/' }); @@ -68,11 +69,11 @@ suite('PathService', () => { unknown: await pathService.getPath(unknown), }, { windows: { - operatingSystem: OperatingSystem.Windows, + operatingSystem: undefined, separator: '\\', }, linux: { - operatingSystem: OperatingSystem.Linux, + operatingSystem: undefined, separator: '/', }, unknown: undefined, diff --git a/src/vs/workbench/services/policies/common/accountPolicyService.ts b/src/vs/workbench/services/policies/common/accountPolicyService.ts index 6c631d0307ae..491baf79cea6 100644 --- a/src/vs/workbench/services/policies/common/accountPolicyService.ts +++ b/src/vs/workbench/services/policies/common/accountPolicyService.ts @@ -12,7 +12,7 @@ import { localize } from '../../../../nls.js'; import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../platform/log/common/log.js'; -import { INativeManagedSettingsService, IFileManagedSettingsService, IManagedSettingsPick, IManagedSettingsService, MANAGED_SETTINGS_CHANNELS, ManagedSettingsChannel, collectManagedSettingsDefinitions, hasManagedSettingsDefinitions, hasRawManagedSettings, isManagedSettingGovernanceActive, projectManagedSettings, pickManagedSettings } from '../../../../platform/policy/common/copilotManagedSettings.js'; +import { COPILOT_ALLOWED_HARNESSES_KEY, INativeManagedSettingsService, IFileManagedSettingsService, IManagedSettingsPick, IManagedSettingsService, MANAGED_SETTINGS_CHANNELS, ManagedSettingsChannel, collectManagedSettingsDefinitions, hasManagedSettingsDefinitions, hasRawManagedSettings, isManagedSettingGovernanceActive, parseAllowedHarnesses, projectManagedSettings, pickManagedSettings } from '../../../../platform/policy/common/copilotManagedSettings.js'; import { IManagedSettingsFreshness, isManagedSettingsFreshnessBlocking, ManagedSettingsFreshnessState } from '../../../../platform/policy/common/managedSettingsFreshness.js'; import { AbstractPolicyService, getRestrictedPolicyValue, IPolicyService, PolicyDefinition, PolicyValue, PolicyValueSource } from '../../../../platform/policy/common/policy.js'; import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js'; @@ -92,6 +92,7 @@ export class AccountPolicyService extends AbstractPolicyService implements IPoli readonly onDidChangeGateInfo = this._onDidChangeGateInfo.event; private _managedSettings: ManagedSettingsData = {}; + private allowedHarnessesWarning: string | undefined; private readonly _onDidChangeManagedSettings = this._register(new Emitter<void>()); readonly onDidChangeManagedSettings = this._onDidChangeManagedSettings.event; @@ -295,6 +296,7 @@ export class AccountPolicyService extends AbstractPolicyService implements IPoli this._managedSettings = pick.values; this._onDidChangeManagedSettings.fire(); } + this.reportAllowedHarnessesProblem(pick.values[COPILOT_ALLOWED_HARNESSES_KEY]); const declaredManagedSettings = collectManagedSettingsDefinitions(this.policyDefinitions); const managedSettingsData = projectManagedSettings( pick.values, @@ -316,6 +318,26 @@ export class AccountPolicyService extends AbstractPolicyService implements IPoli }; } + /** + * Warn once each time the effective harness permission list starts to have a problem. The + * messages name the key but never its value, which is enterprise configuration. + */ + private reportAllowedHarnessesProblem(value: ManagedSettingValue | undefined): void { + let warning: string | undefined; + if (value !== undefined) { + const allowedHarnesses = parseAllowedHarnesses(value); + if (!allowedHarnesses) { + warning = `[AccountPolicy] Invalid managed setting "${COPILOT_ALLOWED_HARNESSES_KEY}": expected an array of "claude" or "codex". It permits no third-party harness.`; + } else if (allowedHarnesses.hasUnrecognizedEntries) { + warning = `[AccountPolicy] Ignoring entries of managed setting "${COPILOT_ALLOWED_HARNESSES_KEY}" other than "claude" or "codex".`; + } + } + if (warning && warning !== this.allowedHarnessesWarning) { + this.logService.warn(warning); + } + this.allowedHarnessesWarning = warning; + } + private computeGateInfo(): IAccountPolicyGateInfo { const freshness = this.defaultAccountService.managedSettingsFreshness; if (isManagedSettingsFreshnessBlocking(freshness)) { diff --git a/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts b/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts index 83d5e982e32a..f2537198ae1a 100644 --- a/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts +++ b/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts @@ -17,7 +17,7 @@ import { TestConfigurationService } from '../../../../../platform/configuration/ import { IDefaultAccountProvider, IDefaultAccountService, MANAGED_SETTINGS_FRESHNESS_NOT_REQUIRED } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; -import { COPILOT_AUTO_TIER_KEY, COPILOT_DEFAULT_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_ASSISTED_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_BYPASS_PERMISSIONS_MODE_KEY, COPILOT_ENABLED_PLUGINS_KEY, COPILOT_OTEL_CAPTURE_IDENTITY_KEY, COPILOT_PERMISSION_RULES_KEYS, COPILOT_SANDBOX_ENABLED_KEY, COPILOT_TEMPORARY_DEFAULT_TO_LOCAL_HARNESS_KEY, COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, hasManagedPermissionDenials, INativeManagedSettingsService, IFileManagedSettingsService, RawManagedSettingsData, managedDefaultConfigurationValue, managedSettingsDisabledValue, managedSettingValue, normalizeManagedSettings, requiresCopilotAgentHost, TemporaryDefaultToLocalHarnessSettingId, thirdPartyAgentEnabledValue } from '../../../../../platform/policy/common/copilotManagedSettings.js'; +import { COPILOT_ALLOWED_HARNESSES_KEY, COPILOT_AUTO_TIER_KEY, COPILOT_DEFAULT_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_ASSISTED_PERMISSIONS_MODE_KEY, COPILOT_DISABLE_BYPASS_PERMISSIONS_MODE_KEY, COPILOT_ENABLED_PLUGINS_KEY, COPILOT_OTEL_CAPTURE_IDENTITY_KEY, COPILOT_PERMISSION_RULES_KEYS, COPILOT_SANDBOX_ENABLED_KEY, COPILOT_TEMPORARY_DEFAULT_TO_LOCAL_HARNESS_KEY, COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY, hasManagedPermissionDenials, INativeManagedSettingsService, IFileManagedSettingsService, RawManagedSettingsData, managedDefaultConfigurationValue, managedSettingsDisabledValue, managedSettingValue, normalizeManagedSettings, requiresCopilotAgentHost, TemporaryDefaultToLocalHarnessSettingId, thirdPartyAgentEnabledValue } from '../../../../../platform/policy/common/copilotManagedSettings.js'; import { IManagedSettingsFreshness, ManagedSettingsFreshnessFailure, ManagedSettingsFreshnessState } from '../../../../../platform/policy/common/managedSettingsFreshness.js'; import { AbstractPolicyService, IPolicyService, PolicyDefinition, PolicyValue, PolicyValueSource } from '../../../../../platform/policy/common/policy.js'; import { Registry } from '../../../../../platform/registry/common/platform.js'; @@ -88,10 +88,10 @@ suite('AccountPolicyService', () => { const logService = new NullLogService(); function thirdPartyAgentPolicies(): Record<string, PolicyDefinition> { - return Object.fromEntries(['Claude', 'Codex'].map(name => [name, { + return Object.fromEntries(([['Claude', 'claude'], ['Codex', 'codex']] as const).map(([name, harness]) => [name, { type: 'boolean', - value: thirdPartyAgentEnabledValue, - managedSettings: { [COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY]: { type: 'boolean' } }, + value: thirdPartyAgentEnabledValue(harness), + managedSettings: { [COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY]: { type: 'boolean' }, [COPILOT_ALLOWED_HARNESSES_KEY]: { type: 'string' } }, }])); } @@ -736,8 +736,8 @@ suite('AccountPolicyService', () => { await defaultAccountService.refresh(); policyService = disposables.add(new AccountPolicyService(logService, defaultAccountService, undefined, native, file)); const definitions: Record<string, PolicyDefinition> = { - Claude: { type: 'boolean', value: thirdPartyAgentEnabledValue }, - Codex: { type: 'boolean', value: thirdPartyAgentEnabledValue }, + Claude: { type: 'boolean', value: thirdPartyAgentEnabledValue('claude') }, + Codex: { type: 'boolean', value: thirdPartyAgentEnabledValue('codex') }, }; await policyService.updatePolicyDefinitions(definitions); const results = []; @@ -871,6 +871,74 @@ suite('AccountPolicyService', () => { ]); }); + test('allowed harnesses resolve as one list by channel precedence across refresh and removal', async () => { + const key = COPILOT_ALLOWED_HARNESSES_KEY; + const warnings: string[] = []; + const logger = new class extends NullLogService { + override warn(message: string): void { + warnings.push(message); + } + }(); + const native = disposables.add(new FakeNativeManagedSettingsService()); + const file = disposables.add(new FakeFileManagedSettingsService()); + const changed = disposables.add(new Emitter<IPolicyData | null>()); + const provider = new class extends DefaultAccountProvider { + override readonly onDidChangePolicyData = changed.event; + override policyData: IPolicyData = {}; + }(BASE_DEFAULT_ACCOUNT); + defaultAccountService.setDefaultAccountProvider(provider); + await defaultAccountService.refresh(); + policyService = disposables.add(new AccountPolicyService(logger, defaultAccountService, undefined, native, file)); + const definitions: Record<string, PolicyDefinition> = { + ...thirdPartyAgentPolicies(), + Presence: { type: 'boolean', value: managedSettingsDisabledValue }, + }; + const list = (allowedHarnesses: unknown): RawManagedSettingsData => allowedHarnesses === undefined ? {} : { vscode: { allowedHarnesses } }; + const steps: readonly { native?: unknown; server?: unknown; file?: unknown; governed: boolean }[] = [ + { governed: true }, + { file: ['claude'], governed: true }, + { server: ['codex'], file: ['claude'], governed: true }, + { native: [], server: ['codex'], file: ['claude'], governed: true }, + { native: 'private-value', server: ['codex'], file: ['claude'], governed: true }, + { native: ['private-value', 'codex'], file: ['claude'], governed: true }, + { server: ['claude', 'codex'], governed: true }, + { server: ['claude'], governed: false }, + { governed: false }, + ]; + const results = []; + for (const step of steps) { + const fileSettings = list(step.file); + native.setManagedSettings(normalizeManagedSettings(list(step.native))); + file.setManagedSettings(normalizeManagedSettings(fileSettings), fileSettings); + provider.policyData = adaptManagedSettings({ ...list(step.server), ...(step.governed ? { permissions: { allow: [] } } : {}) }); + changed.fire(provider.policyData); + await policyService.updatePolicyDefinitions({ ...definitions, ...thirdPartyAgentPolicies() }); + results.push({ + effective: policyService.getManagedSettingValue(key), + claude: policyService.getPolicyValue('Claude'), codex: policyService.getPolicyValue('Codex'), + presence: policyService.getPolicyValue('Presence'), + }); + } + assert.deepStrictEqual({ results, warnings, watched: native.registeredManagedSettings[key] }, { + results: [ + { effective: undefined, claude: false, codex: false, presence: false }, + { effective: '["claude"]', claude: undefined, codex: false, presence: false }, + { effective: '["codex"]', claude: false, codex: undefined, presence: false }, + { effective: '[]', claude: false, codex: false, presence: false }, + { effective: '"private-value"', claude: false, codex: false, presence: false }, + { effective: '["private-value","codex"]', claude: false, codex: undefined, presence: false }, + { effective: '["claude","codex"]', claude: undefined, codex: undefined, presence: false }, + { effective: '["claude"]', claude: undefined, codex: false, presence: undefined }, + { effective: undefined, claude: undefined, codex: undefined, presence: undefined }, + ], + warnings: [ + '[AccountPolicy] Invalid managed setting "vscode.allowedHarnesses": expected an array of "claude" or "codex". It permits no third-party harness.', + '[AccountPolicy] Ignoring entries of managed setting "vscode.allowedHarnesses" other than "claude" or "codex".', + ], + watched: { type: 'string' }, + }); + }); + for (const channel of ['nativeMdm', 'file'] as const) { test(`temporary Local permission from ${channel} disables third-party harnesses without an account`, async () => { const key = COPILOT_TEMPORARY_ALLOW_LOCAL_HARNESS_KEY; diff --git a/src/vs/workbench/services/textfile/common/textEditorService.ts b/src/vs/workbench/services/textfile/common/textEditorService.ts index df9346511688..1daf4374c644 100644 --- a/src/vs/workbench/services/textfile/common/textEditorService.ts +++ b/src/vs/workbench/services/textfile/common/textEditorService.ts @@ -143,7 +143,8 @@ export class TextEditorService extends Disposable implements ITextEditorService const untitledOptions: Partial<INewUntitledTextEditorOptions> = { languageId: untitledInput.languageId, initialValue: untitledInput.contents, - encoding: untitledInput.encoding + encoding: untitledInput.encoding, + origin: untitledInput.untitledOrigin }; // Untitled resource: use as hint for an existing untitled editor diff --git a/src/vs/workbench/services/themes/README.md b/src/vs/workbench/services/themes/README.md new file mode 100644 index 000000000000..474b2a7a7c52 --- /dev/null +++ b/src/vs/workbench/services/themes/README.md @@ -0,0 +1,107 @@ +# Semantic size customizations + +`workbench.sizeCustomizations` customizes panel, control, and pop-up corners and the space between panels in the editor and Agents windows, independently of the selected color theme. Corner radii are integers from 0 through 8 pixels; inter-panel spacing is an integer from 0 through 16 pixels, defaulting to 4. + +```json +{ + "workbench.sizeCustomizations": { + "panels.cornerRadius": 4, + "panels.spacing": 8, + "primarySideBar.cornerRadius": 2, + "toolsPanel.cornerRadius": 0, + "agentsWindow.panels.cornerRadius": 2, + "agentsWindow.panels.spacing": 6, + "agentsWindow.toolsPanel.cornerRadius": 0, + "controls.cornerRadius": 3, + "buttons.cornerRadius": 2, + "popups.cornerRadius": 6, + "menus.cornerRadius": 0 + } +} +``` + +## Resolution layers + +1. **Primitives** define the built-in scale, such as `cornerRadius.large`. They are not user-customizable. +2. **Shared defaults** establish a common appearance with `default.cornerRadius` and `panels.cornerRadius`. +3. **Named areas** inherit a shared default and can be overridden independently. + +## Names and visible areas + +| Name | What it changes | Inherits from | +| --- | --- | --- | +| `default.cornerRadius` | The default corner radius for panel areas; not the app window itself | Built-in radius scale | +| `panels.cornerRadius` | A shared value for all the areas below | `default.cornerRadius` | +| `toolsPanel.cornerRadius` | The panel containing Terminal, Output, Problems, and Debug Console, including when moved to a side | `panels.cornerRadius` | +| `primarySideBar.cornerRadius` | The editor window's Primary Side Bar, where Explorer, Search, and Source Control normally appear | `panels.cornerRadius` | +| `secondarySideBar.cornerRadius` | The Secondary Side Bar, often Chat in the editor window or Files and Changes in the Agents window | `panels.cornerRadius` | +| `editorArea.cornerRadius` | The file editor area, including its tab strip, but not individual tab shapes | `panels.cornerRadius` | +| `activityBar.cornerRadius` | The Activity Bar containing the Explorer, Search, and Source Control icons, but not individual buttons | `primarySideBar.cornerRadius` | +| `agentsWindow.panels.cornerRadius` | A shared corner radius for Agents window areas only | `panels.cornerRadius` | +| `agentsWindow.toolsPanel.cornerRadius` | The Agents window's Terminal, Output, Problems, and Debug Console panel | `agentsWindow.panels.cornerRadius` | +| `agentsWindow.editorArea.cornerRadius` | The Agents window's file editor area | `agentsWindow.panels.cornerRadius` | +| `agentsWindow.secondarySideBar.cornerRadius` | Files, Changes, and other side views in the Agents window | `agentsWindow.panels.cornerRadius` | +| `agentsWindow.chatPanels.cornerRadius` | Outer panel frames containing conversations in the Agents window—not individual messages, message bubbles, or the chat input | `agentsWindow.panels.cornerRadius` | +| `pages.cornerRadius` | Pages such as Automations that open in place of chats in the Agents window | `agentsWindow.panels.cornerRadius` | +| `panels.spacing` | Space between Modern UI editor panel areas; also the default for Agents panel spacing | Built-in spacing scale (4px) | +| `agentsWindow.panels.spacing` | Space between Agents panel areas and between split chats | `panels.spacing` | +| `controls.cornerRadius` | Standard buttons, toolbar/icon actions, inputs, selects, checkboxes, find toggles, radio groups, and segmented controls in both windows | Built-in small radius (4px) | +| `buttons.cornerRadius` | Standard text, toolbar/icon, and split buttons; joined edges remain square | `controls.cornerRadius` | +| `inputs.cornerRadius` | Standard text inputs, find inputs, browser address inputs, and select controls; not the chat composer | `controls.cornerRadius` | +| `popups.cornerRadius` | Custom menus, hovers, dialogs, Command Palette, and Modern UI editor pop-ups in both windows | Built-in large radius (8px) | +| `menus.cornerRadius` | Custom context menus, action pickers, and select-option pop-ups, including background and clipping layers | `popups.cornerRadius` | +| `hovers.cornerRadius` | Editor hovers and workbench tooltips | `popups.cornerRadius` | +| `dialogs.cornerRadius` | Custom in-app dialogs; not native operating system dialogs | `popups.cornerRadius` | + +The unprefixed `toolsPanel`, `editorArea`, and `secondarySideBar` corner tokens apply to the editor window; their `agentsWindow` counterparts customize the Agents window independently. For Chat in an editor-window side bar, customize that side bar rather than `agentsWindow.chatPanels.cornerRadius`. Names identify areas, not their current screen positions: moving the tools panel or swapping side bars does not change which name applies. + +The initial inheritance graph is: + +```text +cornerRadius.large +└── default.cornerRadius + └── panels.cornerRadius + ├── toolsPanel.cornerRadius + ├── primarySideBar.cornerRadius + │ └── activityBar.cornerRadius + ├── secondarySideBar.cornerRadius + ├── editorArea.cornerRadius + └── agentsWindow.panels.cornerRadius + ├── agentsWindow.toolsPanel.cornerRadius + ├── agentsWindow.editorArea.cornerRadius + ├── agentsWindow.secondarySideBar.cornerRadius + ├── agentsWindow.chatPanels.cornerRadius + └── pages.cornerRadius +``` + +An individual area's value wins over a shared default. Removing an override restores inheritance, including any current ancestor customization. For example, setting `panels.cornerRadius` to 4 and `toolsPanel.cornerRadius` to 0 gives panel areas 4px corners except for the square tools panel. + +## Control and pop-up families + +Controls and pop-ups are independent of panel corners and of `default.cornerRadius`. Their shared family values apply to editor and Agents windows alike, including classic editor windows where the standard widget is used. + +```text +cornerRadius.small cornerRadius.large +└── controls.cornerRadius └── popups.cornerRadius + ├── buttons.cornerRadius ├── menus.cornerRadius + └── inputs.cornerRadius ├── hovers.cornerRadius + └── dialogs.cornerRadius +``` + +Without a valid customization, widgets keep their current host-specific appearance, such as the Agents window's default dialog radius. Setting a family or leaf explicitly applies the resolved numeric radius; removing it restores the original appearance. Checkbox, toggle, icon-selector, and radio/segmented-control corners follow `controls.cornerRadius`; they are independent of the button and input leaf overrides. Segmented backgrounds and selection indicators follow the same radius, while connected segments retain flat internal seams. + +The shared controls and their feature-specific overrides are wired together, including extension installation buttons, Settings checkboxes, Command Palette filters, chat toolbars, and Agents changes/create-pull-request/run-script controls. Input backgrounds and split-button focus outlines track the same corners as their containing controls. The Command Palette follows `popups.cornerRadius` rather than the menus override. Native menus and dialogs, notifications, tabs, list rows, circular or pill-shaped controls (including switches and send buttons), and the chat composer are not restyled. + +## Consumers and constraints + +The size registry owns token definitions, references, and the customization schema. The workbench size service validates settings and resolves values for both programmatic consumers and the generated workbench and webview CSS variables. Unknown tokens, internal primitives, out-of-range values, fractions, and non-numeric values are rejected with warnings; valid entries in the same object still apply. + +Workbench stylesheets propagate to auxiliary windows through the existing shared stylesheet mechanism. Webviews receive resolved size variables and refresh their cached theme data when sizes change. The startup splash saves each visible workbench part's resolved radius and the inter-panel spacing. + +Spacing uses the same resolved numeric value in CSS, panel content calculations, session grids, and sash positioning. Changes reapply content layout even when the grid allocations are unchanged. Window-edge gutters retain their default size; compact and phone layouts remain gapless. Agents inset frames reserve no more space than the gap permits. + +Resize sashes and hover lines keep their configured thickness. Dividers are centered within their own gap, and their ends extend or retract along the divider to meet adjoining gap midpoints at T-junctions. This applies to top-level and split-chat dividers, including odd-pixel gaps. Compact layouts remove gap-specific endpoint and centering adjustments. + +Component geometry remains authoritative: joined edges, inset frame radii, mobile presentation, and native window corners retain their existing rules. Size customization does not inject arbitrary CSS or add blanket content-clipping rules. Widget corner overrides leave hit areas, padding, keyboard behavior, focus indicators, typography, and stroke widths unchanged. + +Extension-contributed size themes and other layout-affecting dimensions are not part of this implementation. A layout-affecting token must have a common numeric source of truth for CSS and layout calculations before it can be exposed. diff --git a/src/vs/workbench/services/themes/browser/colorThemeCss.ts b/src/vs/workbench/services/themes/browser/colorThemeCss.ts index 0d597784a99f..c621a53965f2 100644 --- a/src/vs/workbench/services/themes/browser/colorThemeCss.ts +++ b/src/vs/workbench/services/themes/browser/colorThemeCss.ts @@ -5,8 +5,9 @@ import { IColorTheme, ICssStyleCollector, IThemingParticipant } from '../../../../platform/theme/common/themeService.js'; import { asCssVariableName, getColorRegistry } from '../../../../platform/theme/common/colorRegistry.js'; -import { asCssVariableName as asSizeCssVariableName, getSizeRegistry, sizeValueToCss } from '../../../../platform/theme/common/sizeRegistry.js'; +import { asCssVariableName as asSizeCssVariableName, buttonsCornerRadius, controlsCornerRadius, dialogsCornerRadius, getSizeRegistry, hoversCornerRadius, inputsCornerRadius, menusCornerRadius, popupsCornerRadius, sizeValueToCss } from '../../../../platform/theme/common/sizeRegistry.js'; import { IEnvironmentService } from '../../../../platform/environment/common/environment.js'; +import { ISizeService } from '../../../../platform/theme/common/sizeService.js'; /** * Generates CSS content (variables + theming participant rules) for a color theme. @@ -21,7 +22,8 @@ export function generateColorThemeCSS( theme: IColorTheme, scopeSelector: string, themingParticipants?: readonly IThemingParticipant[], - environmentService?: IEnvironmentService + environmentService?: IEnvironmentService, + sizeService?: ISizeService, ): CSSValue { const cssRules = new Set<string>(); const ruleCollector: ICssStyleCollector = { @@ -53,12 +55,27 @@ export function generateColorThemeCSS( // Size CSS variables for (const item of getSizeRegistry().getSizes()) { - const sizeValue = getSizeRegistry().resolveDefaultSize(item.id, theme); + const sizeValue = sizeService ? sizeService.getSize(item.id, theme) : getSizeRegistry().resolveDefaultSize(item.id, theme); if (sizeValue) { variables.push(`${asSizeCssVariableName(item.id)}: ${sizeValueToCss(sizeValue)};`); } } + // Only customized widget families override existing, context-specific default shapes. + for (const [id, property] of [ + [controlsCornerRadius, '--workbench-custom-controls-corner-radius'], + [buttonsCornerRadius, '--workbench-custom-buttons-corner-radius'], + [inputsCornerRadius, '--workbench-custom-inputs-corner-radius'], + [popupsCornerRadius, '--workbench-custom-popups-corner-radius'], + [menusCornerRadius, '--workbench-custom-menus-corner-radius'], + [hoversCornerRadius, '--workbench-custom-hovers-corner-radius'], + [dialogsCornerRadius, '--workbench-custom-dialogs-corner-radius'], + ]) { + if (sizeService?.isCustomized(id)) { + variables.push(`${property}: var(${asSizeCssVariableName(id)});`); + } + } + ruleCollector.addRule(`${scopeSelector} { ${variables.join('\n')} }`); return new CSSValue([...cssRules].join('\n')); diff --git a/src/vs/workbench/services/themes/browser/workbenchSizeService.ts b/src/vs/workbench/services/themes/browser/workbenchSizeService.ts new file mode 100644 index 000000000000..42c3024c081a --- /dev/null +++ b/src/vs/workbench/services/themes/browser/workbenchSizeService.ts @@ -0,0 +1,86 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Emitter } from '../../../../base/common/event.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { registerSingleton, InstantiationType } from '../../../../platform/instantiation/common/extensions.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { getSizeRegistry, SizeIdentifier, SizeValue } from '../../../../platform/theme/common/sizeRegistry.js'; +import { ISizeService, SIZE_CUSTOMIZATIONS_SETTING } from '../../../../platform/theme/common/sizeService.js'; +import { IColorTheme } from '../../../../platform/theme/common/themeService.js'; + +export class WorkbenchSizeService extends Disposable implements ISizeService { + declare readonly _serviceBrand: undefined; + + private readonly _onDidChangeSizes = this._register(new Emitter<void>()); + readonly onDidChangeSizes = this._onDidChangeSizes.event; + + private customizations: Record<string, number> = Object.create(null); + + constructor( + @IConfigurationService private readonly configurationService: IConfigurationService, + @ILogService private readonly logService: ILogService, + ) { + super(); + this.update(); + this._register(configurationService.onDidChangeConfiguration(e => { + if (e.affectsConfiguration(SIZE_CUSTOMIZATIONS_SETTING)) { + this.update(); + this._onDidChangeSizes.fire(); + } + })); + this._register(getSizeRegistry().onDidChangeSchema(() => { + this.update(); + this._onDidChangeSizes.fire(); + })); + } + + getSize(id: SizeIdentifier, theme: IColorTheme): SizeValue | undefined { + return getSizeRegistry().resolveSize(id, theme, this.customizations); + } + + isCustomized(id: SizeIdentifier): boolean { + const sizes = getSizeRegistry().getSizes(); + const visited = new Set<SizeIdentifier>(); + while (!visited.has(id)) { + visited.add(id); + if (Object.hasOwn(this.customizations, id)) { + return true; + } + const defaults = sizes.find(size => size.id === id)?.defaults; + if (typeof defaults !== 'string') { + break; + } + id = defaults; + } + return false; + } + + private update(): void { + this.customizations = Object.create(null); + const value = this.configurationService.getValue<unknown>(SIZE_CUSTOMIZATIONS_SETTING); + if (value === undefined) { + return; + } + if (!value || typeof value !== 'object' || Array.isArray(value)) { + this.logService.warn(`${SIZE_CUSTOMIZATIONS_SETTING} must be an object of semantic size tokens.`); + return; + } + const sizes = new Map(getSizeRegistry().getSizes().map(size => [size.id, size])); + for (const [id, customized] of Object.entries(value)) { + const customization = sizes.get(id)?.customization; + if (!customization) { + this.logService.warn(`${SIZE_CUSTOMIZATIONS_SETTING}: '${id}' is not a customizable semantic size token.`); + } else if (typeof customized !== 'number' || !Number.isInteger(customized) || customized < customization.minimum || customized > customization.maximum) { + this.logService.warn(`${SIZE_CUSTOMIZATIONS_SETTING}: '${id}' must be an integer between ${customization.minimum} and ${customization.maximum}.`); + } else { + this.customizations[id] = customized; + } + } + } +} + +registerSingleton(ISizeService, WorkbenchSizeService, InstantiationType.Delayed); diff --git a/src/vs/workbench/services/themes/browser/workbenchThemeService.ts b/src/vs/workbench/services/themes/browser/workbenchThemeService.ts index 28ab75641c8a..5ad7b04ec8db 100644 --- a/src/vs/workbench/services/themes/browser/workbenchThemeService.ts +++ b/src/vs/workbench/services/themes/browser/workbenchThemeService.ts @@ -46,6 +46,8 @@ import { generateColorThemeCSS } from './colorThemeCss.js'; import { INotificationService, Severity } from '../../../../platform/notification/common/notification.js'; import { IHostService } from '../../host/browser/host.js'; import { toAction } from '../../../../base/common/actions.js'; +import { ISizeService } from '../../../../platform/theme/common/sizeService.js'; +import './workbenchSizeService.js'; // implementation @@ -116,7 +118,8 @@ export class WorkbenchThemeService extends Disposable implements IWorkbenchTheme @IUserDataInitializationService private readonly userDataInitializationService: IUserDataInitializationService, @ILanguageService private readonly languageService: ILanguageService, @INotificationService private readonly notificationService: INotificationService, - @IHostService private readonly hostService: IHostService + @IHostService private readonly hostService: IHostService, + @ISizeService private readonly sizeService: ISizeService, ) { super(); this.container = layoutService.mainContainer; @@ -166,6 +169,7 @@ export class WorkbenchThemeService extends Disposable implements IWorkbenchTheme } themeData.setCustomizations(this.settings); this.applyTheme(themeData, undefined, true); + this._register(sizeService.onDidChangeSizes(() => this.updateDynamicCSSRules(this.currentColorTheme))); const fileIconData = FileIconThemeData.fromStorageData(this.storageService); if (fileIconData) { @@ -596,7 +600,8 @@ export class WorkbenchThemeService extends Disposable implements IWorkbenchTheme themeData, '.monaco-workbench', themingRegistry.getThemingParticipants(), - this.environmentService + this.environmentService, + this.sizeService, ); _applyRules(css.code, colorThemeRulesClassName); } @@ -913,7 +918,7 @@ class ThemeFileWatcher { } function _applyRules(styleSheetContent: string, rulesClassName: string) { - // eslint-disable-next-line no-restricted-syntax + // eslint-disable-next-line eslint-js/no-restricted-syntax const themeStyles = mainWindow.document.head.getElementsByClassName(rulesClassName); if (themeStyles.length === 0) { const elStyle = createStyleSheet(); diff --git a/src/vs/workbench/services/themes/common/themeConfiguration.ts b/src/vs/workbench/services/themes/common/themeConfiguration.ts index 98c5d5b608c0..980ce7a76feb 100644 --- a/src/vs/workbench/services/themes/common/themeConfiguration.ts +++ b/src/vs/workbench/services/themes/common/themeConfiguration.ts @@ -11,6 +11,8 @@ import { IConfigurationRegistry, Extensions as ConfigurationExtensions, IConfigu import { IJSONSchema } from '../../../../base/common/jsonSchema.js'; import { textmateColorsSchemaId, textmateColorGroupSchemaId } from './colorThemeSchema.js'; import { workbenchColorsSchemaId } from '../../../../platform/theme/common/colorRegistry.js'; +import { sizeCustomizationsSchemaId } from '../../../../platform/theme/common/sizeRegistry.js'; +import { SIZE_CUSTOMIZATIONS_SETTING } from '../../../../platform/theme/common/sizeService.js'; import { tokenStylingSchemaId } from '../../../../platform/theme/common/tokenClassificationRegistry.js'; import { ThemeSettings, IWorkbenchColorTheme, IWorkbenchFileIconTheme, IColorCustomizations, ITokenColorCustomizations, IWorkbenchProductIconTheme, ISemanticTokenColorCustomizations, ThemeSettingTarget, ThemeSettingDefaults } from './workbenchThemeService.js'; import { IConfigurationService, ConfigurationTarget } from '../../../../platform/configuration/common/configuration.js'; @@ -139,6 +141,12 @@ const themeSettingsConfiguration: IConfigurationNode = { [ThemeSettings.PREFERRED_HC_LIGHT_THEME]: preferredHCLightThemeSettingSchema, [ThemeSettings.FILE_ICON_THEME]: fileIconThemeSettingSchema, [ThemeSettings.COLOR_CUSTOMIZATIONS]: colorCustomizationsSchema, + [SIZE_CUSTOMIZATIONS_SETTING]: { + type: 'object', + default: {}, + allOf: [{ $ref: sizeCustomizationsSchemaId }], + description: nls.localize('sizeCustomizations', "Customizes corners and inter-panel spacing in pixels. Use panels.cornerRadius, controls.cornerRadius, and popups.cornerRadius (0-8) for independent families, with individual area and widget overrides. Use panels.spacing (0-16) for panel gaps. Agents window panels also support agentsWindow overrides. Compact layouts remain gapless, and joined edges remain square. Native operating system surfaces and window-edge gutters are unchanged."), + }, [ThemeSettings.PRODUCT_ICON_THEME]: productIconThemeSettingSchema } }; diff --git a/src/vs/workbench/services/themes/test/browser/widgetCornerSizes.test.ts b/src/vs/workbench/services/themes/test/browser/widgetCornerSizes.test.ts new file mode 100644 index 000000000000..33a811841f2c --- /dev/null +++ b/src/vs/workbench/services/themes/test/browser/widgetCornerSizes.test.ts @@ -0,0 +1,407 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { createStyleSheet } from '../../../../../base/browser/domStylesheets.js'; +import { ActionBar } from '../../../../../base/browser/ui/actionbar/actionbar.js'; +import { Button, ButtonWithDropdown, unthemedButtonStyles } from '../../../../../base/browser/ui/button/button.js'; +import { InputBox, unthemedInboxStyles } from '../../../../../base/browser/ui/inputbox/inputBox.js'; +import { Menu, unthemedMenuStyles } from '../../../../../base/browser/ui/menu/menu.js'; +import { Radio } from '../../../../../base/browser/ui/radio/radio.js'; +import { Switch } from '../../../../../base/browser/ui/toggle/switch.js'; +import { Checkbox, Toggle, unthemedToggleStyles } from '../../../../../base/browser/ui/toggle/toggle.js'; +import { Action } from '../../../../../base/common/actions.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ConfigurationTarget } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { defaultCheckboxStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; +import { buttonsCornerRadius, controlsCornerRadius, dialogsCornerRadius, hoversCornerRadius, inputsCornerRadius, menusCornerRadius, popupsCornerRadius } from '../../../../../platform/theme/common/sizeRegistry.js'; +import { SIZE_CUSTOMIZATIONS_SETTING } from '../../../../../platform/theme/common/sizeService.js'; +import { ColorScheme } from '../../../../../platform/theme/common/theme.js'; +import { TestColorTheme } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { generateColorThemeCSS } from '../../browser/colorThemeCss.js'; +import { WorkbenchSizeService } from '../../browser/workbenchSizeService.js'; +import '../../../../../base/browser/ui/selectBox/selectBox.css'; +import '../../../../../base/browser/ui/selectBox/selectBoxCustom.css'; +import '../../../../../base/browser/ui/dialog/dialog.css'; +import '../../../../../base/browser/ui/findinput/findInput.css'; +import '../../../../../base/browser/ui/icons/iconSelectBox.css'; +import '../../../../../base/browser/ui/menu/menubar.css'; +import '../../../../../base/browser/ui/dropdown/dropdown.css'; +import '../../../../../platform/actions/browser/menuEntryActionViewItem.css'; +import '../../../../../platform/hover/browser/hover.css'; +import '../../../../../platform/quickinput/browser/media/quickInput.css'; +import '../../../../../platform/actionWidget/browser/actionWidget.css'; +import '../../../../../platform/actionWidget/browser/tabbedActionListWidget.css'; +import '../../../../../editor/contrib/hover/browser/hover.css'; +import '../../../../browser/media/style.css'; +import '../../../../contrib/modernUI/browser/media/roundedCorners.css'; +import '../../../../contrib/extensions/browser/media/extension.css'; +import '../../../../contrib/extensions/browser/media/extensionEditor.css'; +import '../../../../contrib/preferences/browser/media/settingsEditor2.css'; +import '../../../../contrib/chat/browser/widget/media/chat.css'; +// eslint-disable-next-line local/code-import-patterns, local/code-layering -- Exercise browser chrome CSS without creating a native browser view. +import '../../../../contrib/browserView/electron-browser/media/browser.css'; +// eslint-disable-next-line local/code-import-patterns -- Verify the shared theme output against Agents-specific widget overrides. +import '../../../../../sessions/browser/media/style.css'; +import '../../../../contrib/sessionChanges/browser/media/changesView.css'; +import '../../../../contrib/sessionChanges/browser/media/createPullRequest.css'; +// eslint-disable-next-line local/code-import-patterns -- Exercise the Agents-specific radio and button overrides. +import '../../../../../sessions/contrib/chat/browser/media/runScriptAction.css'; +import '../../../../contrib/sessions/browser/chat/media/chatInput.css'; + +suite('Widget corner sizes', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createWidgets(customizations: Record<string, number> = {}, agents = false, scheme = ColorScheme.DARK) { + const configuration = new TestConfigurationService({ [SIZE_CUSTOMIZATIONS_SETTING]: customizations }); + store.add(configuration.onDidChangeConfigurationEmitter); + const log = store.add(new class extends NullLogService { + readonly warnings: string[] = []; + override warn(message: string): void { this.warnings.push(message); } + }()); + const sizes = store.add(new WorkbenchSizeService(configuration, log)); + const theme = new TestColorTheme({}, scheme); + const sheet = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + const updateCSS = () => sheet.textContent = generateColorThemeCSS(theme, '.widget-size-test', undefined, undefined, sizes).code; + updateCSS(); + store.add(sizes.onDidChangeSizes(updateCSS)); + const root = append(document.body, $('.monaco-workbench.widget-size-test')); + root.classList.add(agents ? 'agent-sessions-workbench' : 'modern-ui', 'modern-ui-tabs'); + if (scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT) { + root.classList.add(scheme === ColorScheme.HIGH_CONTRAST_DARK ? 'hc-black' : 'hc-light'); + } + store.add(toDisposable(() => root.remove())); + const button = store.add(new Button(root, { ...unthemedButtonStyles, title: '' })); + button.label = 'Test button'; + button.setAriaLabel('Test button'); + const split = store.add(new ButtonWithDropdown(root, { + ...unthemedButtonStyles, title: '', actions: [], contextMenuProvider: { showContextMenu: () => { } }, + })); + split.label = 'Split button'; + const input = store.add(new InputBox(root, undefined, { inputBoxStyles: unthemedInboxStyles, ariaLabel: 'Test input' })); + input.value = 'Input'; + const select = append(root, $<HTMLSelectElement>('select.monaco-select-box')); + const options = append(root, $('.monaco-select-box-dropdown-container.visible')); + const menuHost = append(root, $('.context-view')); + const action = store.add(new Action('test-action', 'Test action')); + const menu = store.add(new Menu(menuHost, [action], { ariaLabel: 'Test menu' }, unthemedMenuStyles)); + const actionPicker = append(root, $('.action-widget')); + const hover = append(root, $('.monaco-hover.workbench-hover')); + const pointerHover = append(root, $('.monaco-hover.workbench-hover.with-pointer')); + const editor = append(root, $('.monaco-editor')); + const editorHover = append(editor, $('.monaco-resizable-hover')); + const editorHoverContents = append(editorHover, $('.monaco-hover')); + const dialog = append(root, $('.monaco-dialog-box')); + const palette = append(root, $('.quick-input-widget')); + const paletteHeader = append(palette, $('.quick-input-header')); + const toggle = store.add(new Toggle({ ...unthemedToggleStyles, title: 'Test toggle', isChecked: false })); + append(root, toggle.domNode); + const checkbox = store.add(new Checkbox('Test checkbox', false, defaultCheckboxStyles)); + append(root, checkbox.domNode); + const radio = store.add(new Radio({ ariaLabel: 'Test radio', items: [{ text: 'First' }, { text: 'Middle' }, { text: 'Last' }] })); + append(root, radio.domNode); + const segmented = store.add(new Radio({ ariaLabel: 'Test segments', className: 'segmented', items: [{ text: 'One' }, { text: 'Two' }] })); + append(root, segmented.domNode); + const toolbar = store.add(new ActionBar(root)); + toolbar.push(store.add(new Action('test-toolbar', 'Test toolbar action', 'codicon codicon-add')), { icon: true, label: false }); + const toolbarLabel = toolbar.domNode.querySelector<HTMLElement>('.action-label')!; + const paletteInput = store.add(new InputBox(append(paletteHeader, $('.quick-input-filter')), undefined, { inputBoxStyles: unthemedInboxStyles })); + const paletteToolbar = store.add(new ActionBar(paletteHeader)); + const paletteToggle = store.add(new Toggle({ ...unthemedToggleStyles, title: 'Test palette toggle', isChecked: false })); + append(paletteToolbar.domNode, paletteToggle.domNode); + const actionFilter = append(actionPicker, $<HTMLInputElement>('input.action-list-filter-input')); + const iconSelector = append(append(append(root, $('.icon-select-box')), $('.icon-select-icons-container')), $('.icon-container')); + const menubarTitle = append(append(append(root, $('.menubar')), $('.menubar-menu-button')), $('.menubar-menu-title')); + const pillSwitch = store.add(new Switch({ ariaLabel: 'Test switch' })); + append(root, pillSwitch.domNode); + const pill = append(root, $('.test-pill')); + pill.style.borderRadius = 'var(--vscode-cornerRadius-circle)'; + const tab = append(root, $('.test-tab')); + tab.style.borderRadius = 'var(--vscode-cornerRadius-small)'; + const radius = (element: HTMLElement) => getWindow(element).getComputedStyle(element).borderRadius; + const snapshot = () => ({ + button: radius(button.element), + split: [radius(split.primaryButton.element), radius(split.dropdownButton.element)], + input: [radius(input.element), radius(input.inputElement)], + select: radius(select), + options: radius(options), + menu: [radius(menuHost), radius(menuHost.querySelector<HTMLElement>('.monaco-menu')!), radius(menu.getContainer())], + actionPicker: radius(actionPicker), + hovers: [hover, pointerHover, editorHover, editorHoverContents].map(radius), + dialog: radius(dialog), + palette: radius(palette), + paletteHeader: agents ? radius(paletteHeader) : undefined, + pill: radius(pill), + tab: radius(tab), + }); + const controlSnapshot = () => ({ + toggle: radius(toggle.domNode), + checkbox: radius(checkbox.domNode), + radio: radio.optionElements.map(radius), + segmented: [radius(segmented.domNode), ...segmented.optionElements.map(radius), radius(segmented.domNode.querySelector<HTMLElement>('.monaco-radio-selection')!)], + toolbar: radius(toolbarLabel), + paletteInput: [radius(paletteInput.element), radius(paletteInput.inputElement)], + paletteToggle: radius(paletteToggle.domNode), + actionFilter: radius(actionFilter), + iconSelector: radius(iconSelector), + menubarTitle: radius(menubarTitle), + switch: [radius(pillSwitch.domNode), radius(pillSwitch.domNode.querySelector<HTMLElement>('.monaco-switch-thumb')!)], + menuItem: radius(menuHost.querySelector<HTMLElement>('.action-menu-item')!), + }); + const update = async (value: Record<string, number>) => { + await configuration.setUserConfiguration(SIZE_CUSTOMIZATIONS_SETTING, value); + configuration.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === SIZE_CUSTOMIZATIONS_SETTING, + source: ConfigurationTarget.USER, + affectedKeys: new Set([SIZE_CUSTOMIZATIONS_SETTING]), + change: { keys: [SIZE_CUSTOMIZATIONS_SETTING], overrides: [] }, + }); + }; + return { root, sizes, theme, log, button, input, toggle, checkbox, radio, segmented, toolbarLabel, controlSnapshot, snapshot, update }; + } + + for (const agents of [false, true]) { + for (const scheme of [ColorScheme.LIGHT, ColorScheme.DARK, ColorScheme.HIGH_CONTRAST_DARK, ColorScheme.HIGH_CONTRAST_LIGHT]) { + for (const radius of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { + test(`applies ${radius}px widget corners with Agents ${agents} and scheme ${scheme}`, () => { + const { snapshot, controlSnapshot } = createWidgets({ 'controls.cornerRadius': radius, 'popups.cornerRadius': radius }, agents, scheme); + const all = `${radius}px`; + assert.deepStrictEqual({ ...snapshot(), controls: controlSnapshot() }, { + button: all, + split: [`${all} 0px 0px ${all}`, `0px ${all} ${all} 0px`].map(value => radius === 0 ? '0px' : value), + input: [all, all], + select: all, + options: all, + menu: [all, all, all], + actionPicker: all, + hovers: [all, all, all, all], + dialog: all, + palette: all, + paletteHeader: agents ? all : undefined, + pill: '9999px', + tab: '4px', + controls: { + toggle: all, checkbox: all, + radio: [`${all} 0px 0px ${all}`, '0px', `0px ${all} ${all} 0px`].map(value => radius === 0 ? '0px' : value), + segmented: [all, all, all, all], + toolbar: all, paletteInput: [all, all], paletteToggle: all, + actionFilter: all, iconSelector: all, menubarTitle: all, + switch: ['9999px', '9999px'], menuItem: '6px', + }, + }); + }); + } + } + + test(`specific widget values override families, update live and reset with Agents ${agents}`, async () => { + const { sizes, theme, snapshot, controlSnapshot, update } = createWidgets({}, agents); + const baseline = snapshot(); + const controlBaseline = controlSnapshot(); + await update({ + 'panels.cornerRadius': 0, + 'controls.cornerRadius': 3, 'buttons.cornerRadius': 2, 'inputs.cornerRadius': 1, + 'popups.cornerRadius': 6, 'menus.cornerRadius': 4, 'hovers.cornerRadius': 5, 'dialogs.cornerRadius': 0, + }); + const customized = snapshot(); + const customizedControls = controlSnapshot(); + const resolved = [controlsCornerRadius, buttonsCornerRadius, inputsCornerRadius, popupsCornerRadius, menusCornerRadius, hoversCornerRadius, dialogsCornerRadius] + .map(id => ({ value: sizes.getSize(id, theme)?.value, customized: sizes.isCustomized(id) })); + await update({ 'default.cornerRadius': 0, 'panels.cornerRadius': 0 }); + assert.deepStrictEqual({ + customized: { + button: customized.button, input: customized.input, menu: customized.menu, + hovers: customized.hovers, dialog: customized.dialog, palette: customized.palette, + }, + resolved, + reset: snapshot(), + customizedControls, + resetControls: controlSnapshot(), + }, { + customized: { button: '2px', input: ['1px', '1px'], menu: ['4px', '4px', '4px'], hovers: ['5px', '5px', '5px', '5px'], dialog: '0px', palette: '6px' }, + resolved: [3, 2, 1, 6, 4, 5, 0].map(value => ({ value, customized: true })), + reset: baseline, + customizedControls: { + toggle: '3px', checkbox: '3px', radio: ['3px 0px 0px 3px', '0px', '0px 3px 3px 0px'], + segmented: ['3px', '3px', '3px', '3px'], toolbar: '2px', + paletteInput: ['1px', '1px'], paletteToggle: '3px', actionFilter: '1px', + iconSelector: '3px', menubarTitle: '2px', switch: ['9999px', '9999px'], menuItem: '6px', + }, + resetControls: controlBaseline, + }); + }); + + for (const scheme of [ColorScheme.LIGHT, ColorScheme.DARK, ColorScheme.HIGH_CONTRAST_DARK, ColorScheme.HIGH_CONTRAST_LIGHT]) { + test(`feature overrides follow controls and restore their defaults with Agents ${agents} and scheme ${scheme}`, async () => { + const { root, update } = createWidgets({}, agents, scheme); + const within = (parent: HTMLElement, ...selectors: string[]) => selectors.reduce((container, selector) => append(container, $(selector)), parent); + const listActions = within(root, '.extension-list-item', '.details', '.footer', '.monaco-action-bar', '.actions-container'); + const listSplit = append(listActions, $('.action-item.action-dropdown-item')); + const listLeading = append(listSplit, $('a.action-label.extension-action.label')); + const listTrailing = within(listSplit, '.monaco-dropdown', 'a.action-label.extension-action.label.dropdown'); + const editorActions = within(root, '.extension-editor', '.header', '.details', '.actions-status-container', '.monaco-action-bar', '.actions-container'); + const editorSplit = append(editorActions, $('.action-item.action-dropdown-item')); + const editorLeading = append(editorSplit, $('a.action-label.extension-action.label')); + const editorTrailing = within(editorSplit, '.monaco-dropdown', 'a.action-label.extension-action.label.dropdown'); + const changes = within(root, '.changes-view-body', '.chat-editing-session-actions.outside-card'); + const changesSplit = store.add(new ButtonWithDropdown(changes, { + ...unthemedButtonStyles, secondary: true, title: '', actions: [], contextMenuProvider: { showContextMenu: () => { } }, + })); + changesSplit.label = 'Test changes action'; + const pullRequestInput = store.add(new InputBox(append(root, $('.create-pull-request-widget')), undefined, { inputBoxStyles: unthemedInboxStyles })); + const settingCheckbox = store.add(new Checkbox('Test setting', false, defaultCheckboxStyles)); + settingCheckbox.domNode.classList.add('setting-value-checkbox'); + append(within(root, '.settings-editor', '.settings-body', '.settings-tree-container', '.setting-item-bool'), settingCheckbox.domNode); + const scriptSection = append(root, $('.run-script-action-section')); + const scriptRadio = store.add(new Radio({ ariaLabel: 'Test script option', items: [{ text: 'One' }, { text: 'Two' }] })); + append(scriptSection, scriptRadio.domNode); + const scriptButton = store.add(new Button(within(root, '.run-script-action-buttons'), { ...unthemedButtonStyles, title: '' })); + scriptButton.label = 'Run'; + const browserUrl = within(root, '.browser-root', '.browser-url-container'); + const remoteIndicator = append(browserUrl, $('.browser-remote-indicator')); + const sendButton = within(root, '.interactive-session', '.chat-input-toolbars', '.chat-execute-toolbar', '.monaco-action-bar', '.action-item.chat-submit-button', 'a.action-label'); + const tab = within(root, '.extension-editor', '.body', '.navbar', '.monaco-action-bar', '.actions-container', '.action-item', 'a.action-label'); + const rows = within(root, '.monaco-list', '.monaco-list-row'); + const pickerTab = within(root, '.action-widget', '.tabbed-action-list-tabbar', '.monaco-custom-radio', '.monaco-button'); + const read = (element: HTMLElement) => getWindow(element).getComputedStyle(element).borderRadius; + const snapshot = () => ({ + list: [read(listLeading), read(listTrailing)], + editor: [read(editorLeading), read(editorTrailing)], + changes: [read(changesSplit.primaryButton.element), read(changesSplit.dropdownButton.element)], + input: [read(pullRequestInput.element), read(pullRequestInput.inputElement)], + checkbox: read(settingCheckbox.domNode), + script: [read(scriptRadio.domNode), ...scriptRadio.optionElements.map(read), read(scriptButton.element)], + browser: [read(browserUrl), read(remoteIndicator)], + special: [read(sendButton), read(tab), read(rows), read(pickerTab)], + }); + const baseline = snapshot(); + for (const value of [0, 2, 8]) { + await update({ 'controls.cornerRadius': value }); + const all = `${value}px`; + const leading = value ? `${all} 0px 0px ${all}` : all; + const trailing = value ? `0px ${all} ${all} 0px` : all; + assert.deepStrictEqual(snapshot(), { + list: [leading, trailing], editor: [leading, trailing], changes: [leading, trailing], + input: [all, all], checkbox: all, script: [all, all, all, all], + browser: [all, leading], special: baseline.special, + }); + } + await update({}); + assert.deepStrictEqual(snapshot(), baseline); + }); + } + } + + test('keeps host-specific defaults until a widget family is actually customized', () => { + const modern = createWidgets(); + const agents = createWidgets({}, true); + const modernDefaults = modern.snapshot(); + const agentsDefaults = agents.snapshot(); + assert.deepStrictEqual({ + modern: { button: modernDefaults.button, input: modernDefaults.input, dialog: modernDefaults.dialog, palette: modernDefaults.palette }, + agents: { button: agentsDefaults.button, input: agentsDefaults.input, dialog: agentsDefaults.dialog, palette: agentsDefaults.palette, hover: agentsDefaults.hovers[0] }, + isCustomized: [buttonsCornerRadius, menusCornerRadius].map(id => agents.sizes.isCustomized(id)), + }, { + modern: { button: '4px', input: ['4px', '4px'], dialog: '8px', palette: '8px' }, + agents: { button: '4px', input: ['4px', '4px'], dialog: '12px', palette: '12px', hover: '5px' }, + isCustomized: [false, false], + }); + }); + + test('invalid widget overrides log warnings and do not replace current shapes', async () => { + const { snapshot, update, log, sizes } = createWidgets(); + const baseline = snapshot(); + await update({ + 'controls.cornerRadius': -1, 'buttons.cornerRadius': 9, 'inputs.cornerRadius': 1.5, + 'popups.cornerRadius': NaN, 'menus.cornerRadius': Infinity, 'hovers.cornerRadius': -2, 'dialogs.cornerRadius': 9, + }); + assert.deepStrictEqual({ shapes: snapshot(), warnings: log.warnings.length, isCustomized: sizes.isCustomized(buttonsCornerRadius) }, { + shapes: baseline, warnings: 7, isCustomized: false, + }); + }); + + test('button and input leaf overrides leave other control shapes at their built-in defaults', async () => { + const { controlSnapshot, update } = createWidgets(); + const baseline = controlSnapshot(); + await update({ 'buttons.cornerRadius': 0, 'inputs.cornerRadius': 8 }); + const customized = controlSnapshot(); + await update({}); + assert.deepStrictEqual({ customized, reset: controlSnapshot() }, { + customized: { + ...baseline, toolbar: '0px', menubarTitle: '0px', + paletteInput: ['8px', '8px'], actionFilter: '8px', + }, + reset: baseline, + }); + }); + + test('shared widget families also work without Modern UI enabled', async () => { + const { root, snapshot, update } = createWidgets(); + root.classList.remove('modern-ui', 'modern-ui-tabs'); + const baseline = snapshot(); + await update({ 'controls.cornerRadius': 0, 'popups.cornerRadius': 3 }); + const customized = snapshot(); + await update({}); + assert.deepStrictEqual({ + button: customized.button, input: customized.input, dialog: customized.dialog, palette: customized.palette, + reset: snapshot(), defaults: [baseline.dialog, baseline.palette], + }, { + button: '0px', input: ['0px', '0px'], dialog: '3px', palette: '3px', + reset: baseline, defaults: ['12px', '12px'], + }); + }); + + test('radius changes preserve keyboard focus, accessible names, dimensions and focus outlines', async () => { + const { button, input, update } = createWidgets(); + button.focus(); + const read = () => { + const css = getWindow(button.element).getComputedStyle(button.element); + return { + focused: button.hasFocus(), role: button.element.getAttribute('role'), + label: button.element.getAttribute('aria-label'), inputLabel: input.inputElement.getAttribute('aria-label'), + width: button.element.offsetWidth, height: button.element.offsetHeight, + outlineWidth: css.outlineWidth, outlineStyle: css.outlineStyle, outlineOffset: css.outlineOffset, + }; + }; + const before = read(); + await update({ 'controls.cornerRadius': 0, 'popups.cornerRadius': 0 }); + assert.deepStrictEqual({ before, after: read() }, { + before, after: before, + }); + assert.deepStrictEqual({ focused: before.focused, role: before.role, label: before.label, inputLabel: before.inputLabel }, { + focused: true, role: 'button', label: 'Test button', inputLabel: 'Test input', + }); + }); + + test('custom corners preserve checkbox, toggle and radio keyboard interaction and accessibility', async () => { + const { toggle, checkbox, radio, update } = createWidgets(); + const dimensions = () => [toggle.domNode, checkbox.domNode, ...radio.optionElements].map(element => ({ + width: element.offsetWidth, height: element.offsetHeight, + role: element.getAttribute('role'), label: element.getAttribute('aria-label'), + })); + const before = dimensions(); + await update({ 'controls.cornerRadius': 8 }); + const customizedDimensions = dimensions(); + const keyboard = (element: HTMLElement, key: string, keyCode: number) => + element.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true })); + toggle.focus(); + keyboard(toggle.domNode, ' ', 32); + checkbox.focus(); + keyboard(checkbox.domNode, ' ', 32); + radio.optionElements[0].focus(); + keyboard(radio.optionElements[0], 'ArrowRight', 39); + assert.deepStrictEqual({ + dimensions: customizedDimensions, toggle: toggle.domNode.getAttribute('aria-checked'), + checkbox: checkbox.domNode.getAttribute('aria-checked'), + selected: radio.optionElements.map(element => element.getAttribute('aria-checked')), + focused: getWindow(radio.domNode).document.activeElement === radio.optionElements[1], + }, { + dimensions: before, toggle: 'true', checkbox: 'true', selected: ['false', 'true', 'false'], focused: true, + }); + }); +}); diff --git a/src/vs/workbench/services/themes/test/browser/workbenchSizeService.test.ts b/src/vs/workbench/services/themes/test/browser/workbenchSizeService.test.ts new file mode 100644 index 000000000000..83e3b37abeb9 --- /dev/null +++ b/src/vs/workbench/services/themes/test/browser/workbenchSizeService.test.ts @@ -0,0 +1,281 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { $, append, getWindow } from '../../../../../base/browser/dom.js'; +import { cloneGlobalStylesheets, createStyleSheet } from '../../../../../base/browser/domStylesheets.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ConfigurationTarget } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { agentsPanelsCornerRadius, agentsPanelsSpacing, agentsToolsPanelCornerRadius, getSizeRegistry, panelsSpacing, primarySideBarCornerRadius, toolsPanelCornerRadius, editorAreaCornerRadius, agentsChatPanelsCornerRadius } from '../../../../../platform/theme/common/sizeRegistry.js'; +import { SIZE_CUSTOMIZATIONS_SETTING } from '../../../../../platform/theme/common/sizeService.js'; +import { TestColorTheme } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { WorkbenchSizeService } from '../../browser/workbenchSizeService.js'; +import { generateColorThemeCSS } from '../../browser/colorThemeCss.js'; +import { getFloatingEditorVerticalMargins, getFloatingPaneCompositeHorizontalMargins, getFloatingPanelOuterMargin, Parts, Position } from '../../../layout/browser/layoutService.js'; +import { TestLayoutService } from '../../../../test/browser/workbenchTestServices.js'; +import '../../common/themeConfiguration.js'; +import '../../../../browser/media/floatingPanels.css'; +import '../../../../browser/media/part.css'; +import '../../../../contrib/modernUI/browser/media/editorBorder.css'; + +suite('WorkbenchSizeService', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const theme = new TestColorTheme(); + + function createService(value: unknown = {}) { + const configuration = new TestConfigurationService({ workbench: { sizeCustomizations: value } }); + store.add(configuration.onDidChangeConfigurationEmitter); + const log = store.add(new class extends NullLogService { + readonly warnings: string[] = []; + override warn(message: string): void { this.warnings.push(message); } + }()); + const service = store.add(new WorkbenchSizeService(configuration, log)); + return { service, configuration, log }; + } + + test('registers the size customizations setting', () => { + const property = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties()[SIZE_CUSTOMIZATIONS_SETTING]; + assert.deepStrictEqual({ type: property.type, default: property.default, allOf: property.allOf }, { + type: 'object', default: {}, allOf: [{ $ref: 'vscode://schemas/size-customizations' }], + }); + }); + + for (const value of [null, [], '3px', 3]) { + test(`rejects a non-object customization value ${JSON.stringify(value)}`, () => { + const { service, log } = createService(value); + assert.deepStrictEqual({ radius: service.getSize(toolsPanelCornerRadius, theme)?.value, warnings: log.warnings.length }, { + radius: 8, warnings: 1, + }); + }); + } + + test('rejects invalid and internal overrides explicitly while applying valid entries', () => { + const { service, log } = createService({ + 'default.cornerRadius': 5, + 'toolsPanel.cornerRadius': 0, + 'primarySideBar.cornerRadius': -1, + 'secondarySideBar.cornerRadius': 9, + 'editorArea.cornerRadius': 1.5, + 'agentsWindow.chatPanels.cornerRadius': '2px', + 'pages.cornerRadius': NaN, + 'cornerRadius.large': 0, + 'spacing.size40': 0, + 'unknown.size': 1, + }); + assert.deepStrictEqual({ + values: [toolsPanelCornerRadius, primarySideBarCornerRadius, editorAreaCornerRadius, agentsChatPanelsCornerRadius].map(id => service.getSize(id, theme)?.value), + warnings: log.warnings.length, + attribution: log.warnings.every(message => message.includes(SIZE_CUSTOMIZATIONS_SETTING)), + }, { + values: [0, 5, 5, 5], warnings: 8, attribution: true, + }); + }); + + test('removing a component override restores the current role rather than a cached default', async () => { + const { service, configuration } = createService({ 'default.cornerRadius': 6, 'primarySideBar.cornerRadius': 2 }); + const values: number[] = []; + store.add(service.onDidChangeSizes(() => values.push(service.getSize(primarySideBarCornerRadius, theme)!.value))); + for (const value of [{ 'default.cornerRadius': 3 }, {}]) { + await configuration.setUserConfiguration(SIZE_CUSTOMIZATIONS_SETTING, value); + configuration.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === SIZE_CUSTOMIZATIONS_SETTING, + source: ConfigurationTarget.USER, + affectedKeys: new Set([SIZE_CUSTOMIZATIONS_SETTING]), + change: { keys: [SIZE_CUSTOMIZATIONS_SETTING], overrides: [] }, + }); + } + assert.deepStrictEqual(values, [3, 8]); + }); + + test('Agents window controls inherit shared defaults without changing editor-window overrides', () => { + const { service } = createService({ + 'panels.cornerRadius': 6, + 'toolsPanel.cornerRadius': 0, + 'agentsWindow.panels.cornerRadius': 2, + 'agentsWindow.toolsPanel.cornerRadius': 3, + 'panels.spacing': 8, + 'agentsWindow.panels.spacing': 12, + }); + assert.deepStrictEqual([ + toolsPanelCornerRadius, agentsPanelsCornerRadius, agentsToolsPanelCornerRadius, agentsChatPanelsCornerRadius, panelsSpacing, agentsPanelsSpacing, + ].map(id => service.getSize(id, theme)?.value), [0, 2, 3, 2, 8, 12]); + }); + + test('rejects invalid spacing overrides without changing valid shared spacing', () => { + const results = [-1, 17, 1.5, '8px', NaN].map(value => { + const { service, log } = createService({ 'panels.spacing': 8, 'agentsWindow.panels.spacing': value }); + return { spacing: service.getSize(agentsPanelsSpacing, theme)?.value, warnings: log.warnings.length }; + }); + assert.deepStrictEqual(results, Array.from({ length: 5 }, () => ({ spacing: 8, warnings: 1 }))); + }); + + for (const spacing of [0, 1, 4, 8, 16]) { + test(`matches the rendered ${spacing}px editor gap to numeric content insets while preserving outer gutters`, () => { + const { service } = createService({ 'panels.spacing': spacing }); + const sheet = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + sheet.textContent = generateColorThemeCSS(theme, '.semantic-spacing-test', undefined, undefined, service).code; + const root = append(document.body, $('.monaco-workbench.semantic-spacing-test.modern-ui.floating-panels.noactivitybar.nopanel')); + store.add(toDisposable(() => root.remove())); + const grid = append(root, $('.monaco-grid-view')); + grid.style.display = 'flex'; + const sidebar = append(grid, $('.part.sidebar.left.floating-part-outer-left')); + const editor = append(grid, $('.part.editor')); + for (const element of [sidebar, editor]) { + element.style.width = '200px'; + element.style.height = '100px'; + element.style.flexShrink = '0'; + } + const layout = new class extends TestLayoutService { + override isFloatingPanelsEnabled() { return true; } + override getPanelSpacing() { return this.isModernUICompact() ? 0 : service.getSize(panelsSpacing, theme)!.value; } + override getPanelPosition() { return Position.BOTTOM; } + override isVisible(part: Parts) { return [Parts.TITLEBAR_PART, Parts.SIDEBAR_PART, Parts.EDITOR_PART, Parts.STATUSBAR_PART].includes(part); } + }(); + const read = () => ({ + visualGap: editor.getBoundingClientRect().left - sidebar.getBoundingClientRect().right, + contentInsets: getFloatingPaneCompositeHorizontalMargins(layout, Parts.EDITOR_PART), + outerGutter: getFloatingPanelOuterMargin(layout), + sidebarBottom: getWindow(root).getComputedStyle(sidebar).marginBottom, + editorVertical: getFloatingEditorVerticalMargins(layout, getWindow(root)), + }); + const regular = read(); + root.classList.add('modern-ui-compact'); + layout.isModernUICompact = () => true; + assert.deepStrictEqual({ regular, compact: read() }, { + regular: { visualGap: spacing, contentInsets: { left: spacing, right: 4 }, outerGutter: 4, sidebarBottom: '4px', editorVertical: { top: 0, bottom: 4 } }, + compact: { visualGap: 0, contentInsets: { left: 0, right: 0 }, outerGutter: 0, sidebarBottom: '0px', editorVertical: { top: 0, bottom: 0 } }, + }); + }); + } + + for (const spacing of [0, 1, 4, 8, 16]) { + for (const sashSize of [2, 4, 20]) { + test(`keeps ${sashSize}px workbench sashes thin and centered within a ${spacing}px gap`, () => { + const { service } = createService({ 'panels.spacing': spacing }); + const sheet = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + sheet.textContent = generateColorThemeCSS(theme, '.semantic-sash-test', undefined, undefined, service).code; + const root = append(document.body, $('.monaco-workbench.semantic-sash-test.floating-panels')); + root.style.setProperty('--vscode-sash-size', `${sashSize}px`); + root.style.setProperty('--vscode-sash-hover-size', '4px'); + root.style.cssText += '; position: relative; width: 400px; height: 400px;'; + store.add(toDisposable(() => root.remove())); + const vertical = append(root, $('.monaco-sash.vertical')); + vertical.style.cssText = `left: ${100 - sashSize / 2}px; top: 0; height: 100px;`; + const horizontal = append(root, $('.monaco-sash.horizontal')); + horizontal.style.cssText = `top: ${100 - sashSize / 2}px; left: 0; width: 100px;`; + const targetWindow = getWindow(root); + const read = () => [vertical, horizontal].map((sash, index) => { + const css = targetWindow.getComputedStyle(sash); + const hover = targetWindow.getComputedStyle(sash, '::before'); + const hit = Number.parseFloat(index === 0 ? css.width : css.height); + const hoverSize = Number.parseFloat(index === 0 ? hover.width : hover.height); + const hoverOffset = Number.parseFloat(index === 0 ? hover.left : hover.top); + const rect = sash.getBoundingClientRect(); + const rootRect = root.getBoundingClientRect(); + return { + hit, hoverSize, + hoverCenterOffset: hoverOffset + hoverSize / 2 - hit / 2, + center: (index === 0 ? rect.left - rootRect.left : rect.top - rootRect.top) + hit / 2, + }; + }); + const regular = read(); + root.classList.add('modern-ui-compact'); + assert.deepStrictEqual({ regular, compact: read() }, { + regular: Array.from({ length: 2 }, () => ({ + hit: sashSize, hoverSize: 4, hoverCenterOffset: 0, center: 100 + spacing / 2, + })), + compact: Array.from({ length: 2 }, () => ({ + hit: sashSize, hoverSize: 4, hoverCenterOffset: 0, center: 100, + })), + }); + }); + } + } + + for (const radius of [0, 1, 2, 3, 4, 5, 6, 7, 8]) { + test(`renders ${radius}px semantic sizes without changing primitives or compact seams`, () => { + const { service } = createService({ 'panels.cornerRadius': radius, 'primarySideBar.cornerRadius': 2 }); + const style = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + style.textContent = generateColorThemeCSS(theme, '.semantic-size-test', undefined, undefined, service).code; + const root = append(document.body, $('.monaco-workbench.semantic-size-test.modern-ui.floating-panels')); + store.add(toDisposable(() => root.remove())); + const grid = append(root, $('.monaco-grid-view')); + const sidebar = append(grid, $('.part.sidebar.left')); + const panel = append(grid, $('.part.panel')); + const editor = append(grid, $('.part.editor')); + const content = append(editor, $('.content')); + const rail = append(grid, $('.part.activitybar.left')); + const read = () => [sidebar, panel, editor, content, rail].map(element => { + const css = getWindow(element).getComputedStyle(element); + return [css.borderTopLeftRadius, css.borderTopRightRadius, css.borderBottomRightRadius, css.borderBottomLeftRadius]; + }); + const regular = read(); + const primitive = getWindow(root).getComputedStyle(root).getPropertyValue('--vscode-cornerRadius-large').trim(); + root.classList.add('modern-ui-compact'); + const compact = read(); + root.classList.remove('modern-ui-compact'); + const newlyAddedPanel = append(grid, $('.part.panel')); + assert.deepStrictEqual({ regular, compact, primitive, newPanel: getWindow(root).getComputedStyle(newlyAddedPanel).borderRadius }, { + regular: [ + ['0px', '2px', '2px', '0px'], + [`${radius}px`, `${radius}px`, `${radius}px`, `${radius}px`], + [`${radius}px`, `${radius}px`, `${radius}px`, `${radius}px`], + [`${radius}px`, `${radius}px`, `${radius}px`, `${radius}px`], + ['2px', '0px', '0px', '2px'], + ], + compact: Array.from({ length: 5 }, () => ['0px', '0px', '0px', '0px']), + primitive: '8px', + newPanel: `${radius}px`, + }); + }); + } + + test('cloned auxiliary-window styles receive initial sizes and live updates', async () => { + const { service, configuration } = createService({ 'panels.cornerRadius': 3 }); + const style = createStyleSheet(undefined, undefined, store.add(new DisposableStore())); + const update = () => style.textContent = generateColorThemeCSS(theme, '.semantic-auxiliary-test', undefined, undefined, service).code; + update(); + store.add(service.onDidChangeSizes(update)); + const frame = append(document.body, $<HTMLIFrameElement>('iframe')); + store.add(toDisposable(() => frame.remove())); + const targetWindow = frame.contentWindow; + assert.ok(targetWindow); + store.add(cloneGlobalStylesheets(targetWindow)); + const root = $('.monaco-workbench.semantic-auxiliary-test'); + targetWindow.document.body.appendChild(root); + const initial = targetWindow.getComputedStyle(root).getPropertyValue('--vscode-toolsPanel-cornerRadius').trim(); + await configuration.setUserConfiguration(SIZE_CUSTOMIZATIONS_SETTING, { 'panels.cornerRadius': 5 }); + configuration.onDidChangeConfigurationEmitter.fire({ + affectsConfiguration: key => key === SIZE_CUSTOMIZATIONS_SETTING, + source: ConfigurationTarget.USER, + affectedKeys: new Set([SIZE_CUSTOMIZATIONS_SETTING]), + change: { keys: [SIZE_CUSTOMIZATIONS_SETTING], overrides: [] }, + }); + await new Promise<void>(resolve => { + const observer = new (getWindow(root).MutationObserver)(() => { + observer.disconnect(); + resolve(); + }); + store.add(toDisposable(() => observer.disconnect())); + observer.observe(targetWindow.document.head, { subtree: true, childList: true, characterData: true }); + }); + assert.deepStrictEqual({ initial, updated: targetWindow.getComputedStyle(root).getPropertyValue('--vscode-toolsPanel-cornerRadius').trim() }, { + initial: '3px', updated: '5px', + }); + }); + + test('registry defaults remain independent of user customizations', () => { + const { service } = createService({ 'default.cornerRadius': 0 }); + assert.deepStrictEqual([ + service.getSize(toolsPanelCornerRadius, theme)?.value, + getSizeRegistry().resolveDefaultSize(toolsPanelCornerRadius, theme)?.value, + ], [0, 8]); + }); +}); diff --git a/src/vs/workbench/services/untitled/common/untitledDocumentTelemetry.ts b/src/vs/workbench/services/untitled/common/untitledDocumentTelemetry.ts new file mode 100644 index 000000000000..0f078930219a --- /dev/null +++ b/src/vs/workbench/services/untitled/common/untitledDocumentTelemetry.ts @@ -0,0 +1,25 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { URI } from '../../../../base/common/uri.js'; +import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; + +export const IUntitledDocumentTelemetryService = createDecorator<IUntitledDocumentTelemetryService>('untitledDocumentTelemetryService'); + +/** + * Follows untitled text documents from creation to their end (saved, closed) and sends + * `untitledDocument` telemetry events. All events about the same document carry the same + * random `untitledDocumentId`, which survives window reloads through hot exit. + */ +export interface IUntitledDocumentTelemetryService { + + readonly _serviceBrand: undefined; + + /** + * The telemetry id of the untitled document with this resource, for other events + * that want to be correlated with the untitled document funnel. + */ + getUntitledDocumentId(resource: URI | undefined): string | undefined; +} diff --git a/src/vs/workbench/services/untitled/common/untitledTextEditorModel.ts b/src/vs/workbench/services/untitled/common/untitledTextEditorModel.ts index d167c5dc4bd3..63322613c94d 100644 --- a/src/vs/workbench/services/untitled/common/untitledTextEditorModel.ts +++ b/src/vs/workbench/services/untitled/common/untitledTextEditorModel.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { ISaveOptions } from '../../../common/editor.js'; +import { ISaveOptions, UntitledTextEditorOrigin } from '../../../common/editor.js'; import { BaseTextEditorModel } from '../../../common/editor/textEditorModel.js'; import { URI } from '../../../../base/common/uri.js'; import { ILanguageService } from '../../../../editor/common/languages/language.js'; @@ -56,6 +56,11 @@ export interface IUntitledTextEditorModel extends ITextEditorModel, ILanguageSup */ readonly hasLanguageSetExplicitly: boolean; + /** + * Where the untitled editor was created from. Only used for telemetry. + */ + readonly origin?: UntitledTextEditorOrigin; + /** * Sets the encoding to use for this untitled model. */ @@ -141,6 +146,7 @@ export class UntitledTextEditorModel extends BaseTextEditorModel implements IUnt private readonly initialValue: string | undefined, private preferredLanguageId: string | undefined, private preferredEncoding: string | undefined, + readonly origin: UntitledTextEditorOrigin | undefined, @ILanguageService languageService: ILanguageService, @IModelService modelService: IModelService, @IWorkingCopyBackupService private readonly workingCopyBackupService: IWorkingCopyBackupService, @@ -325,6 +331,9 @@ export class UntitledTextEditorModel extends BaseTextEditorModel implements IUnt private ignoreDirtyOnModelContentChange = false; override async resolve(): Promise<void> { + if (this.isDisposed()) { + return; + } // Create text editor model if not yet done let createdUntitledModel = false; @@ -346,6 +355,9 @@ export class UntitledTextEditorModel extends BaseTextEditorModel implements IUnt // to create the text factory to respect encodings // accordingly. const untitledContentsFactory = await createTextBufferFactoryFromStream(await this.textFileService.getDecodedStream(this.resource, untitledContents, { encoding: UTF8 })); + if (this.isDisposed()) { + return; + } this.createTextEditorModel(untitledContentsFactory, this.resource, this.preferredLanguageId); createdUntitledModel = true; diff --git a/src/vs/workbench/services/untitled/common/untitledTextEditorService.ts b/src/vs/workbench/services/untitled/common/untitledTextEditorService.ts index d5b060dd1fb5..fd30ce611b7b 100644 --- a/src/vs/workbench/services/untitled/common/untitledTextEditorService.ts +++ b/src/vs/workbench/services/untitled/common/untitledTextEditorService.ts @@ -12,6 +12,7 @@ import { Event, Emitter } from '../../../../base/common/event.js'; import { Schemas } from '../../../../base/common/network.js'; import { Disposable, DisposableResourceMap, DisposableStore } from '../../../../base/common/lifecycle.js'; import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { UntitledTextEditorOrigin } from '../../../common/editor.js'; export const IUntitledTextEditorService = createDecorator<IUntitledTextEditorService>('untitledTextEditorService'); @@ -32,6 +33,11 @@ export interface INewUntitledTextEditorOptions { * Preferred encoding to use when saving the untitled editor. */ encoding?: string; + + /** + * Where the untitled editor is created from. Only used for telemetry. + */ + origin?: UntitledTextEditorOrigin; } export interface IExistingUntitledTextEditorOptions extends INewUntitledTextEditorOptions { @@ -256,6 +262,7 @@ export class UntitledTextEditorService extends Disposable implements IUntitledTe // Take over encoding and initial value massagedOptions.encoding = options.encoding; massagedOptions.initialValue = options.initialValue; + massagedOptions.origin = options.origin; return massagedOptions; } @@ -273,7 +280,7 @@ export class UntitledTextEditorService extends Disposable implements IUntitledTe } // Create new model with provided options - const model = this.instantiationService.createInstance(UntitledTextEditorModel, untitledResource, !!options.associatedResource, options.initialValue, options.languageId, options.encoding); + const model = this.instantiationService.createInstance(UntitledTextEditorModel, untitledResource, !!options.associatedResource, options.initialValue, options.languageId, options.encoding, options.origin); this.registerModel(model); diff --git a/src/vs/workbench/services/untitled/test/browser/untitledTextEditor.test.ts b/src/vs/workbench/services/untitled/test/browser/untitledTextEditor.test.ts index 92c442d17156..e34770b9f08b 100644 --- a/src/vs/workbench/services/untitled/test/browser/untitledTextEditor.test.ts +++ b/src/vs/workbench/services/untitled/test/browser/untitledTextEditor.test.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import sinon from 'sinon'; import { URI } from '../../../../../base/common/uri.js'; import { join } from '../../../../../base/common/path.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; @@ -25,7 +26,7 @@ import { Schemas } from '../../../../../base/common/network.js'; import { UntitledTextEditorWorkingCopyEditorHandler } from '../../common/untitledTextEditorHandler.js'; import { NO_TYPE_ID } from '../../../workingCopy/common/workingCopy.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; -import { timeout } from '../../../../../base/common/async.js'; +import { DeferredPromise, timeout } from '../../../../../base/common/async.js'; suite('Untitled text editors', () => { @@ -44,6 +45,7 @@ suite('Untitled text editors', () => { }); teardown(() => { + sinon.restore(); disposables.clear(); }); @@ -256,6 +258,55 @@ suite('Untitled text editors', () => { assert.strictEqual(workingCopyService.dirtyCount, 1); }); + test('disposed models do not resolve', async () => { + const model = disposables.add(accessor.untitledTextEditorService.create({ initialValue: 'Discarded initial contents' })); + model.dispose(); + + await model.resolve(); + + assert.strictEqual(accessor.workingCopyBackupService.resolved.has(model), false); + assert.strictEqual(accessor.modelService.getModel(model.resource), null); + assert.strictEqual(accessor.untitledTextEditorService.get(model.resource), undefined); + }); + + test('disposing while resolving a backup does not create a text model', async () => { + const model = disposables.add(accessor.untitledTextEditorService.create({ initialValue: 'Discarded initial contents' })); + await accessor.workingCopyBackupService.backup(model, (await model.backup(CancellationToken.None)).content); + const resolving = model.resolve(); + model.dispose(); + + await resolving; + + assert.strictEqual(accessor.modelService.getModel(model.resource), null); + assert.strictEqual(accessor.untitledTextEditorService.get(model.resource), undefined); + }); + + test('disposing while decoding initial contents does not create a text model', async () => { + const model = disposables.add(accessor.untitledTextEditorService.create({ initialValue: 'Discarded initial contents' })); + const decoding = new DeferredPromise<void>(); + const continueDecoding = new DeferredPromise<void>(); + const getDecodedStream = accessor.textFileService.getDecodedStream.bind(accessor.textFileService); + const stub = sinon.stub(accessor.textFileService, 'getDecodedStream').callsFake(async (...args) => { + const stream = await getDecodedStream(...args); + await decoding.complete(); + await continueDecoding.p; + return stream; + }); + try { + const resolving = model.resolve(); + await decoding.p; + model.dispose(); + await continueDecoding.complete(); + await resolving; + + assert.strictEqual(accessor.modelService.getModel(model.resource), null); + assert.strictEqual(accessor.untitledTextEditorService.get(model.resource), undefined); + } finally { + await continueDecoding.complete(); + stub.restore(); + } + }); + test('created with files.defaultLanguage setting', () => { const defaultLanguage = 'javascript'; const config = accessor.testConfigurationService; diff --git a/src/vs/workbench/services/userDataProfile/browser/media/userDataProfileView.css b/src/vs/workbench/services/userDataProfile/browser/media/userDataProfileView.css index f5de028325f0..fad2dc1883b7 100644 --- a/src/vs/workbench/services/userDataProfile/browser/media/userDataProfileView.css +++ b/src/vs/workbench/services/userDataProfile/browser/media/userDataProfileView.css @@ -125,5 +125,5 @@ cursor: pointer; line-height: 17px; padding: 2px 23px 2px 8px; - border-radius: 2px; + border-radius: var(--workbench-custom-inputs-corner-radius, 2px); } diff --git a/src/vs/workbench/services/views/test/browser/viewsService.test.ts b/src/vs/workbench/services/views/test/browser/viewsService.test.ts new file mode 100644 index 000000000000..2c015ce40ee9 --- /dev/null +++ b/src/vs/workbench/services/views/test/browser/viewsService.test.ts @@ -0,0 +1,64 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Event } from '../../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ContextKeyValue, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyService } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { KeybindingsRegistry } from '../../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { PaneCompositeRegistry } from '../../../../browser/panecomposite.js'; +import { getEnabledViewContainerContextKey, LayoutModeContext } from '../../../../common/contextkeys.js'; +import { IViewDescriptorService, IViewContainerModel, ViewContainer, ViewContainerLocation } from '../../../../common/views.js'; +import { IEditorService } from '../../../editor/common/editorService.js'; +import { IWorkbenchLayoutService } from '../../../layout/browser/layoutService.js'; +import { IPaneCompositePartService } from '../../../panecomposite/browser/panecomposite.js'; +import { ViewsService } from '../../browser/viewsService.js'; + +const paneCompositesRegistryId = 'test.viewsService.paneComposites'; +Registry.add(paneCompositesRegistryId, new PaneCompositeRegistry()); + +suite('ViewsService', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('the key of a view container\'s open command applies in a window without layout modes, not in one with them, such as a chat window, whose parts are not the main window\'s', () => { + const viewContainer = upcastPartial<ViewContainer>({ + id: 'test.viewsService.container', + title: { value: 'Container', original: 'Container' }, + openCommandActionDescriptor: { id: 'test.viewsService.openContainer', keybindings: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyE } }, + }); + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IContextKeyService, disposables.add(new ContextKeyService(new TestConfigurationService()))); + instantiationService.stub(IViewDescriptorService, upcastPartial<IViewDescriptorService>({ + viewContainers: [viewContainer], + getViewContainerLocation: () => ViewContainerLocation.AuxiliaryBar, + getViewContainerModel: () => upcastPartial<IViewContainerModel>({ allViewDescriptors: [], activeViewDescriptors: [], onDidChangeAllViewDescriptors: Event.None, onDidChangeActiveViewDescriptors: Event.None }), + onDidChangeViewContainers: Event.None, + onDidChangeContainerLocation: Event.None, + })); + instantiationService.stub(IPaneCompositePartService, upcastPartial<IPaneCompositePartService>({ onDidPaneCompositeOpen: Event.None, onDidPaneCompositeClose: Event.None, getRegistryId: () => paneCompositesRegistryId })); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial<IWorkbenchLayoutService>({})); + instantiationService.stub(IEditorService, upcastPartial<IEditorService>({})); + disposables.add(instantiationService.createInstance(ViewsService)); + + const rule = KeybindingsRegistry.getDefaultKeybindings().find(candidate => candidate.command === 'test.viewsService.openContainer')!; + const applies = (values: Record<string, ContextKeyValue>) => rule.when?.evaluate({ getValue: <T extends ContextKeyValue>(key: string) => values[key] as T | undefined }) !== false; + const enabled = { [getEnabledViewContainerContextKey(viewContainer.id)]: true }; + + assert.deepStrictEqual({ + window: applies(enabled), + windowWithLayoutModes: applies({ ...enabled, [LayoutModeContext.key]: 'sideBySide' }), + }, { + window: true, + windowWithLayoutModes: false, + }); + }); +}); diff --git a/src/vs/workbench/services/workingCopy/common/workingCopyBackupService.ts b/src/vs/workbench/services/workingCopy/common/workingCopyBackupService.ts index 9af61a834ffd..1a185d880a54 100644 --- a/src/vs/workbench/services/workingCopy/common/workingCopyBackupService.ts +++ b/src/vs/workbench/services/workingCopy/common/workingCopyBackupService.ts @@ -575,7 +575,7 @@ export class InMemoryWorkingCopyBackupService extends Disposable implements IWor declare readonly _serviceBrand: undefined; - private backups = new ResourceMap<{ typeId: string; content: VSBuffer; meta?: IWorkingCopyBackupMeta }>(); + private backups = new ResourceMap<{ resource: URI; typeId: string; content: VSBuffer; meta?: IWorkingCopyBackupMeta }>(); hasBackupSync(identifier: IWorkingCopyIdentifier, versionId?: number): boolean { const backupResource = this.toBackupResource(identifier); @@ -586,6 +586,7 @@ export class InMemoryWorkingCopyBackupService extends Disposable implements IWor async backup(identifier: IWorkingCopyIdentifier, content?: VSBufferReadable | VSBufferReadableStream, versionId?: number, meta?: IWorkingCopyBackupMeta, token?: CancellationToken): Promise<void> { const backupResource = this.toBackupResource(identifier); this.backups.set(backupResource, { + resource: identifier.resource, typeId: identifier.typeId, content: content instanceof VSBuffer ? content : content ? isReadableStream(content) ? await streamToBuffer(content) : readableToBuffer(content) : VSBuffer.fromString(''), meta @@ -603,7 +604,7 @@ export class InMemoryWorkingCopyBackupService extends Disposable implements IWor } async getBackups(): Promise<IWorkingCopyIdentifier[]> { - return Array.from(this.backups.entries()).map(([resource, backup]) => ({ typeId: backup.typeId, resource })); + return Array.from(this.backups.values()).map(backup => ({ typeId: backup.typeId, resource: backup.resource })); } async discardBackup(identifier: IWorkingCopyIdentifier): Promise<void> { @@ -629,7 +630,8 @@ export class InMemoryWorkingCopyBackupService extends Disposable implements IWor } toBackupResource(identifier: IWorkingCopyIdentifier): URI { - return URI.from({ scheme: Schemas.inMemory, path: hashIdentifier(identifier) }); + // Prevent single-letter URI schemes from being normalised as drive letters. + return URI.from({ scheme: Schemas.inMemory, path: `/backup/${identifier.resource.toString()}`, query: JSON.stringify(identifier.typeId) }); } async joinBackups(): Promise<void> { diff --git a/src/vs/workbench/services/workingCopy/test/electron-browser/workingCopyBackupService.test.ts b/src/vs/workbench/services/workingCopy/test/electron-browser/workingCopyBackupService.test.ts index 2139e8813abf..d556e203427d 100644 --- a/src/vs/workbench/services/workingCopy/test/electron-browser/workingCopyBackupService.test.ts +++ b/src/vs/workbench/services/workingCopy/test/electron-browser/workingCopyBackupService.test.ts @@ -16,12 +16,12 @@ import { Schemas } from '../../../../../base/common/network.js'; import { FileService } from '../../../../../platform/files/common/fileService.js'; import { LogLevel, NullLogService } from '../../../../../platform/log/common/log.js'; import { NativeWorkbenchEnvironmentService } from '../../../environment/electron-browser/environmentService.js'; -import { toBufferOrReadable } from '../../../textfile/common/textfiles.js'; +import { ITextFileService, toBufferOrReadable } from '../../../textfile/common/textfiles.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; import { NativeWorkingCopyBackupService } from '../../electron-browser/workingCopyBackupService.js'; import { FileUserDataProvider } from '../../../../../platform/userData/common/fileUserDataProvider.js'; import { bufferToReadable, bufferToStream, streamToBuffer, VSBuffer, VSBufferReadable, VSBufferReadableStream } from '../../../../../base/common/buffer.js'; -import { TestLifecycleService, toTypedWorkingCopyId, toUntypedWorkingCopyId } from '../../../../test/browser/workbenchTestServices.js'; +import { TestLifecycleService, TestServiceAccessor, toTypedWorkingCopyId, toUntypedWorkingCopyId, workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { IWorkingCopyBackupMeta, IWorkingCopyIdentifier } from '../../common/workingCopy.js'; import { consumeStream } from '../../../../../base/common/stream.js'; @@ -34,6 +34,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { UserDataProfilesService } from '../../../../../platform/userDataProfile/common/userDataProfile.js'; import { UriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentityService.js'; +import { NativeTextFileService } from '../../../textfile/electron-browser/nativeTextFileService.js'; const homeDir = URI.file('home').with({ scheme: Schemas.inMemory }); const tmpDir = URI.file('tmp').with({ scheme: Schemas.inMemory }); @@ -1322,3 +1323,173 @@ suite('WorkingCopyBackupService', () => { ensureNoDisposablesAreLeakedInTestSuite(); }); + +suite('WorkingCopyBackupService (in memory)', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + const resource = URI.file('/working-copy-backups/file.txt'); + const fileIdentifier = toUntypedWorkingCopyId(resource); + const untitledIdentifier = toUntypedWorkingCopyId(resource.with({ scheme: Schemas.untitled })); + + let service: NativeWorkingCopyBackupService; + let fileService: FileService; + let textFileService: ITextFileService; + + setup(() => { + const environmentService = new NativeWorkbenchEnvironmentService({ + ...TestNativeWindowConfiguration, + extensionDevelopmentPath: [joinPath(tmpDir, 'extension').fsPath] + }, TestProductService); + const logService = new NullLogService(); + fileService = disposables.add(new FileService(logService)); + disposables.add(fileService.registerProvider(Schemas.file, disposables.add(new InMemoryFileSystemProvider()))); + service = disposables.add(new NativeWorkingCopyBackupService(environmentService, fileService, logService, disposables.add(new TestLifecycleService()))); + const instantiationService = workbenchInstantiationService({ + environmentService: () => environmentService, + fileService: () => fileService, + workingCopyBackupService: () => service, + textFileService: instantiationService => disposables.add(instantiationService.createInstance(NativeTextFileService)) + }, disposables); + textFileService = instantiationService.createInstance(TestServiceAccessor).textFileService; + }); + + test('file model restores its own backup', async () => { + await fileService.writeFile(resource, VSBuffer.fromString('saved file')); + const file = disposables.add(await textFileService.files.resolve(resource)); + file.textEditorModel?.setValue('unsaved file'); + const backup = await file.backup(CancellationToken.None); + await service.backup(file, backup.content, undefined, backup.meta); + file.dispose(); + + const restored = disposables.add(await textFileService.files.resolve(resource)); + + assert.deepStrictEqual({ + content: restored.textEditorModel?.getValue(), + dirty: restored.isDirty(), + stored: (await fileService.readFile(resource)).value.toString() + }, { content: 'unsaved file', dirty: true, stored: 'saved file' }); + }); + + for (const [upperScheme, lowerScheme] of [['P', 'p'], ['PX', 'px']]) { + test(`file models keep ${upperScheme}: and ${lowerScheme}: backups separate`, async () => { + for (const scheme of [upperScheme, lowerScheme]) { + disposables.add(fileService.registerProvider(scheme, disposables.add(new InMemoryFileSystemProvider()))); + } + const identityService = disposables.add(new UriIdentityService(fileService)); + const upper = identityService.asCanonicalUri(URI.from({ scheme: upperScheme, path: resource.path })); + const lower = identityService.asCanonicalUri(URI.from({ scheme: lowerScheme, path: resource.path })); + await fileService.writeFile(upper, VSBuffer.fromString('upper saved')); + await fileService.writeFile(lower, VSBuffer.fromString('lower saved')); + + const source = disposables.add(await textFileService.files.resolve(upper)); + source.textEditorModel?.setValue('upper unsaved'); + const backup = await source.backup(CancellationToken.None); + await service.backup(source, backup.content, undefined, backup.meta); + const target = disposables.add(await textFileService.files.resolve(lower)); + + assert.deepStrictEqual({ + sameCanonicalUri: identityService.extUri.isEqual(upper, lower), + source: source.textEditorModel?.getValue(), + target: target.textEditorModel?.getValue(), + targetDirty: target.isDirty(), + sourceStored: (await fileService.readFile(upper)).value.toString(), + targetStored: (await fileService.readFile(lower)).value.toString() + }, { + sameCanonicalUri: false, + source: 'upper unsaved', + target: 'lower saved', + targetDirty: false, + sourceStored: 'upper saved', + targetStored: 'lower saved' + }); + }); + } + + test('file model does not restore the associated untitled backup', async () => { + const untitled = disposables.add(await textFileService.untitled.resolve({ associatedResource: resource, initialValue: 'unsaved untitled' })); + const backup = await untitled.backup(CancellationToken.None); + await service.backup(untitled, backup.content, undefined, backup.meta); + + await fileService.writeFile(resource, VSBuffer.fromString('saved file')); + const file = disposables.add(await textFileService.files.resolve(resource)); + + assert.deepStrictEqual({ + file: file.textEditorModel?.getValue(), + dirty: file.isDirty(), + untitled: untitled.textEditorModel?.getValue(), + stored: (await fileService.readFile(resource)).value.toString() + }, { file: 'saved file', dirty: false, untitled: 'unsaved untitled', stored: 'saved file' }); + }); + + test('untitled model does not restore the associated file backup', async () => { + await fileService.writeFile(resource, VSBuffer.fromString('saved file')); + const file = disposables.add(await textFileService.files.resolve(resource)); + file.textEditorModel?.setValue('unsaved file'); + const backup = await file.backup(CancellationToken.None); + await service.backup(file, backup.content, undefined, backup.meta); + + const untitled = disposables.add(await textFileService.untitled.resolve({ associatedResource: resource, initialValue: 'unsaved untitled' })); + + assert.deepStrictEqual({ + file: file.textEditorModel?.getValue(), + untitled: untitled.textEditorModel?.getValue(), + stored: (await fileService.readFile(resource)).value.toString() + }, { file: 'unsaved file', untitled: 'unsaved untitled', stored: 'saved file' }); + }); + + test('preserves resource and type identities when resolving and listing backups', async () => { + const identifiers = [ + fileIdentifier, + untitledIdentifier, + toTypedWorkingCopyId(resource), + toUntypedWorkingCopyId(resource.with({ query: 'query' })), + toUntypedWorkingCopyId(resource.with({ fragment: 'fragment' })) + ]; + for (const [index, identifier] of identifiers.entries()) { + await service.backup(identifier, bufferToReadable(VSBuffer.fromString(`backup ${index}`)), undefined, { index }); + } + + const backups = []; + for (const identifier of identifiers) { + const backup = await service.resolve(identifier); + backups.push({ + exists: service.hasBackupSync(identifier), + content: backup && (await streamToBuffer(backup.value)).toString(), + meta: backup?.meta + }); + } + + assert.deepStrictEqual({ identifiers: await service.getBackups(), backups }, { + identifiers, + backups: identifiers.map((_, index) => ({ exists: true, content: `backup ${index}`, meta: { index } })) + }); + }); + + test('discarding an untitled backup preserves its associated file backup', async () => { + await service.backup(fileIdentifier, bufferToReadable(VSBuffer.fromString('file backup'))); + await service.backup(untitledIdentifier, bufferToReadable(VSBuffer.fromString('untitled backup'))); + + await service.discardBackup(untitledIdentifier); + + const backup = await service.resolve(fileIdentifier); + assert.deepStrictEqual({ + file: backup && (await streamToBuffer(backup.value)).toString(), + untitled: await service.resolve(untitledIdentifier) + }, { file: 'file backup', untitled: undefined }); + }); + + test('filtered discard retains only the original excluded identifier', async () => { + await service.backup(fileIdentifier); + await service.backup(untitledIdentifier, bufferToReadable(VSBuffer.fromString('untitled backup'))); + await service.backup(toTypedWorkingCopyId(resource)); + + await service.discardBackups({ except: [untitledIdentifier] }); + + const backup = await service.resolve(untitledIdentifier); + assert.deepStrictEqual({ + identifiers: await service.getBackups(), + content: backup && (await streamToBuffer(backup.value)).toString(), + file: service.hasBackupSync(fileIdentifier), + typedFile: service.hasBackupSync(toTypedWorkingCopyId(resource)) + }, { identifiers: [untitledIdentifier], content: 'untitled backup', file: false, typedFile: false }); + }); +}); diff --git a/src/vs/workbench/services/workspaces/common/workspaceFolderLocationService.ts b/src/vs/workbench/services/workspaces/common/workspaceFolderLocationService.ts new file mode 100644 index 000000000000..4e17fbbabe81 --- /dev/null +++ b/src/vs/workbench/services/workspaces/common/workspaceFolderLocationService.ts @@ -0,0 +1,147 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { onUnexpectedError } from '../../../../base/common/errors.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { toDisposable, Disposable, IDisposable } from '../../../../base/common/lifecycle.js'; +import { ResourceMap, ResourceSet } from '../../../../base/common/map.js'; +import { URI } from '../../../../base/common/uri.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { ILabelService } from '../../../../platform/label/common/label.js'; +import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js'; +import { Schemas } from '../../../../base/common/network.js'; +import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from '../../../../platform/workspace/common/workspace.js'; +import { FolderLocationChangeReason, IFolderLocation, IFolderLocationChangeEvent, IResolvedFolderLocation, IWorkspaceFolderLocationProvider, IWorkspaceFolderLocationService } from '../../../../platform/workspace/common/folderLocations.js'; + +interface IRegisteredProvider { + readonly provider: IWorkspaceFolderLocationProvider; + readonly builtIn: boolean; +} + +export class WorkspaceFolderLocationService extends Disposable implements IWorkspaceFolderLocationService { + + declare readonly _serviceBrand: undefined; + + private readonly providers: IRegisteredProvider[] = []; + + private readonly _onDidChangeProviders = this._register(new Emitter<void>()); + readonly onDidChangeProviders = this._onDidChangeProviders.event; + + private readonly locations = new ResourceMap<IResolvedFolderLocation>(); + + private readonly _onDidChangeLocation = this._register(new Emitter<IFolderLocationChangeEvent>()); + readonly onDidChangeLocation = this._onDidChangeLocation.event; + + readonly onDidChangeCanSetLocation: Event<void>; + + constructor( + @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, + @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, + @ILabelService labelService: ILabelService + ) { + super(); + + this.onDidChangeCanSetLocation = Event.any<unknown>(contextService.onDidChangeWorkbenchState, contextService.onDidChangeWorkspaceFolders) as Event<void>; + + this._register(labelService.registerWorkspaceLabelDecorator({ + onDidChange: Event.map(this.onDidChangeLocation, e => e.folder.uri), + getFolderLocationLabel: folder => this.getFolderLocationLabel(folder) + })); + } + + getLocation(folder: IWorkspaceFolder): IResolvedFolderLocation | undefined { + return this.isAtAlternateLocation(folder) ? this.locations.get(folder.uri) : undefined; + } + + canSetLocation(folder: IWorkspaceFolder): boolean { + const workspace = this.contextService.getWorkspace(); + return this.contextService.getWorkbenchState() === WorkbenchState.FOLDER + && workspace.folders.length === 1 + && this.uriIdentityService.extUri.isEqual(workspace.folders[0].uri, folder.uri) + && (workspace.uri ?? folder.uri).scheme === Schemas.file; + } + + isAtAlternateLocation(folder: IWorkspaceFolder): boolean { + const workspace = this.contextService.getWorkspace(); + const extUri = this.uriIdentityService.extUri; + return !workspace.configuration && !!workspace.uri && workspace.folders.length === 1 && extUri.isEqual(workspace.folders[0].uri, folder.uri) && !extUri.isEqual(folder.uri, workspace.uri); + } + + setLocation(folder: IWorkspaceFolder, location: IResolvedFolderLocation | undefined, reason: FolderLocationChangeReason = 'programmatic'): void { + this.locations.clear(); // only single-folder workspaces are supported + if (location) { + this.locations.set(folder.uri, location); + } + this._onDidChangeLocation.fire({ folder, reason }); + } + + /** + * The label of the location of the folder with the given `uri`, which is either its current + * location or, as the label of the workspace is derived from it, the identity of its workspace. + */ + private getFolderLocationLabel(uri: URI): string | undefined { + const workspace = this.contextService.getWorkspace(); + const primary = workspace.configuration ? undefined : workspace.uri; + const extUri = this.uriIdentityService.extUri; + const folder = workspace.folders.find(folder => extUri.isEqual(folder.uri, uri) || (primary && extUri.isEqual(primary, uri))); + const location = folder && this.getLocation(folder); + if (!location) { + return undefined; + } + return location.description && location.description !== location.label ? `${location.label} · ${location.description}` : location.label; + } + + registerProvider(provider: IWorkspaceFolderLocationProvider, options?: { readonly builtIn?: boolean }): IDisposable { + const entry: IRegisteredProvider = { provider, builtIn: !!options?.builtIn }; + this.providers.push(entry); + this._onDidChangeProviders.fire(); + return toDisposable(() => { + const index = this.providers.indexOf(entry); + if (index !== -1) { + this.providers.splice(index, 1); + this._onDidChangeProviders.fire(); + } + }); + } + + async getLocations(primary: URI, token: CancellationToken): Promise<IFolderLocation[]> { + const results = await Promise.all([...this.providers].map(async ({ provider }) => { + try { + return await provider.provideLocations(primary, token); + } catch (error) { + onUnexpectedError(error); + return []; + } + })); + + const seen = new ResourceSet(); + const locations: IFolderLocation[] = []; + for (const location of results.flat()) { + if (!seen.has(location.uri)) { + seen.add(location.uri); + locations.push(location); + } + } + return locations; + } + + async resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise<IResolvedFolderLocation | undefined> { + for (const { provider, builtIn } of [...this.providers]) { + try { + const resolved = await provider.resolveLocation(primary, location, token); + if (resolved) { + return { ...resolved, providerId: provider.id, builtIn }; + } + } catch (error) { + // a failing provider must not hide the others + onUnexpectedError(error); + } + } + return undefined; + } +} + +registerSingleton(IWorkspaceFolderLocationService, WorkspaceFolderLocationService, InstantiationType.Delayed); diff --git a/src/vs/workbench/services/workspaces/test/browser/workspacesService.test.ts b/src/vs/workbench/services/workspaces/test/browser/workspacesService.test.ts new file mode 100644 index 000000000000..d8ce4b9fc311 --- /dev/null +++ b/src/vs/workbench/services/workspaces/test/browser/workspacesService.test.ts @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { timeout } from '../../../../../base/common/async.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { UriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentityService.js'; +import { Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { isRecentFolder } from '../../../../../platform/workspaces/common/workspaces.js'; +import { IWorkbenchEnvironmentService } from '../../../environment/common/environmentService.js'; +import { TestContextService, TestFileService, TestStorageService } from '../../../../test/common/workbenchTestServices.js'; +import { BrowserWorkspacesService } from '../../browser/workspacesService.js'; + +suite('BrowserWorkspacesService', () => { + + const ds = ensureNoDisposablesAreLeakedInTestSuite(); + + test('recents track the primary location while at an alternate location', async () => { + const primary = URI.parse('vscode-vfs://host/primary'); + const alternate = URI.parse('vscode-vfs://host/alternate'); + const folder = new WorkspaceFolder({ uri: alternate, name: 'primary', index: 0 }); + + const fileService = ds.add(new TestFileService()); + const uriIdentityService = ds.add(new UriIdentityService(fileService)); + const service = ds.add(new BrowserWorkspacesService( + ds.add(new TestStorageService()), + new TestContextService(new Workspace('id', [folder], false, null, () => false, undefined, primary)), + new NullLogService(), + fileService, + { remoteAuthority: undefined } as IWorkbenchEnvironmentService, + uriIdentityService, + )); + + await timeout(0); + const recents = (await service.getRecentlyOpened()).workspaces.filter(isRecentFolder).map(recent => recent.folderUri.toString()); + assert.deepStrictEqual(recents, [primary.toString()]); + }); +}); diff --git a/src/vs/workbench/services/workspaces/test/common/workspaceFolderLocationService.test.ts b/src/vs/workbench/services/workspaces/test/common/workspaceFolderLocationService.test.ts new file mode 100644 index 000000000000..ea67e25edd5a --- /dev/null +++ b/src/vs/workbench/services/workspaces/test/common/workspaceFolderLocationService.test.ts @@ -0,0 +1,158 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { errorHandler, setUnexpectedErrorHandler } from '../../../../../base/common/errors.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ILabelService, IWorkspaceLabelDecorator } from '../../../../../platform/label/common/label.js'; +import { NullLogService } from '../../../../../platform/log/common/log.js'; +import { FileService } from '../../../../../platform/files/common/fileService.js'; +import { UriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentityService.js'; +import { IWorkspaceContextService, IWorkspaceFoldersChangeEvent, WorkbenchState, Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { IFolderLocation, IWorkspaceFolderLocationProvider } from '../../../../../platform/workspace/common/folderLocations.js'; +import { TestContextService } from '../../../../test/common/workbenchTestServices.js'; +import { WorkspaceFolderLocationService } from '../../common/workspaceFolderLocationService.js'; + +suite('WorkspaceFolderLocationService', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const primary = URI.file('/primary'); + const a = URI.file('/a'); + const b = URI.file('/b'); + + function provider(id: string, locations: IFolderLocation[], fail = false): IWorkspaceFolderLocationProvider { + return { + id, + provideLocations: async () => { if (fail) { throw new Error('fail'); } return locations; }, + resolveLocation: async (_primary, location) => { if (fail) { throw new Error('fail'); } return locations.find(l => l.uri.toString() === location.toString()); } + }; + } + + function createService(workspace = new Workspace('id', [new WorkspaceFolder({ uri: primary, name: '', index: 0 })], false, null, () => false), decorators: IWorkspaceLabelDecorator[] = []): WorkspaceFolderLocationService { + const labelService = new class extends mock<ILabelService>() { + override registerWorkspaceLabelDecorator(decorator: IWorkspaceLabelDecorator) { decorators.push(decorator); return toDisposable(() => { }); } + }(); + return new WorkspaceFolderLocationService(disposables.add(new UriIdentityService(disposables.add(new FileService(new NullLogService())))), new TestContextService(workspace), labelService); + } + + const folder = (uri: URI) => new WorkspaceFolder({ uri, name: '', index: 0 }); + const atAlternate = () => new Workspace('id', [folder(a)], false, null, () => false, undefined, primary); + + test('getLocations merges providers, dedupes and reports failures', async () => { + const reported: string[] = []; + const previous = errorHandler.getUnexpectedErrorHandler(); + setUnexpectedErrorHandler(error => reported.push(error.message)); + disposables.add(toDisposable(() => setUnexpectedErrorHandler(previous))); + const service = disposables.add(createService()); + disposables.add(service.registerProvider(provider('x', [{ uri: a, label: 'A' }], true))); + disposables.add(service.registerProvider(provider('y', [{ uri: a, label: 'A' }, { uri: b, label: 'B' }]))); + disposables.add(service.registerProvider(provider('z', [{ uri: a, label: 'A2' }]))); + + const actual = await service.getLocations(primary, CancellationToken.None); + + assert.deepStrictEqual({ labels: actual.map(l => l.label), reported }, { labels: ['A', 'B'], reported: ['fail'] }); + }); + + test('resolveLocation reports provider and built-in flag', async () => { + const service = disposables.add(createService()); + const registration = disposables.add(service.registerProvider(provider('x', [{ uri: a, label: 'A' }]), { builtIn: true })); + disposables.add(service.registerProvider(provider('y', [{ uri: b, label: 'B' }]))); + + const resolvedA = await service.resolveLocation(primary, a, CancellationToken.None); + const resolvedB = await service.resolveLocation(primary, b, CancellationToken.None); + const unknown = await service.resolveLocation(primary, URI.file('/c'), CancellationToken.None); + registration.dispose(); + const afterDispose = await service.resolveLocation(primary, a, CancellationToken.None); + + assert.deepStrictEqual( + { a: [resolvedA?.providerId, resolvedA?.builtIn], b: [resolvedB?.providerId, resolvedB?.builtIn], unknown, afterDispose }, + { a: ['x', true], b: ['y', false], unknown: undefined, afterDispose: undefined }); + }); + + test('setLocation fires a per-folder event and getLocation follows it', () => { + const workspace = atAlternate(); + const service = disposables.add(createService(workspace)); + const events: string[] = []; + disposables.add(service.onDidChangeLocation(e => events.push(`${e.folder.uri.path}:${e.reason}`))); + const location = { uri: a, label: 'A', providerId: 'x', builtIn: false }; + + service.setLocation(workspace.folders[0], location, 'user'); + const set = service.getLocation(workspace.folders[0]); + service.setLocation(workspace.folders[0], undefined); + + assert.deepStrictEqual({ events, set, cleared: service.getLocation(workspace.folders[0]) }, { events: ['/a:user', '/a:programmatic'], set: location, cleared: undefined }); + }); + + test('folder identity and alternate location checks', () => { + const check = (workspace: Workspace) => disposables.add(createService(workspace)).isAtAlternateLocation(workspace.folders[0]); + + assert.deepStrictEqual( + { + alternate: check(atAlternate()), + atIdentity: check(new Workspace('id', [folder(primary)], false, null, () => false, undefined, primary)), + withoutIdentity: check(new Workspace('id', [folder(a)], false, null, () => false)), + multiRootSingleFolder: check(new Workspace('id', [folder(a)], false, URI.file('/ws.code-workspace'), () => false)) + }, + { alternate: true, atIdentity: false, withoutIdentity: false, multiRootSingleFolder: false }); + }); + + test('label decorator describes the folder at an alternate location by its current location and identity', () => { + const decorators: IWorkspaceLabelDecorator[] = []; + const workspace = atAlternate(); + const service = disposables.add(createService(workspace, decorators)); + const decorator = decorators[0]; + const before = decorator.getFolderLocationLabel(a); + + service.setLocation(workspace.folders[0], { uri: a, label: 'A', description: 'x', providerId: 'x', builtIn: false }); + const changed: string[] = []; + disposables.add(decorator.onDidChange(uri => changed.push(uri.path))); + service.setLocation(workspace.folders[0], { uri: a, label: 'A', providerId: 'x', builtIn: false }); + + assert.deepStrictEqual( + { before, current: decorator.getFolderLocationLabel(a), byIdentity: decorator.getFolderLocationLabel(primary), other: decorator.getFolderLocationLabel(b), changed }, + { before: undefined, current: 'A', byIdentity: 'A', other: undefined, changed: ['/a'] }); + }); + + test('canSetLocation is true only for the folder of a local single-folder workspace', () => { + const service = (workspace: Workspace) => disposables.add(createService(workspace)); + const remote = URI.from({ scheme: 'vscode-remote', authority: 'host', path: '/r' }); + const multiRoot = new Workspace('id', [folder(a), folder(b)], false, URI.file('/w.code-workspace'), () => false); + + assert.deepStrictEqual({ + singleFolder: service(new Workspace('id', [folder(primary)], false, null, () => false)).canSetLocation(folder(primary)), + atAlternate: service(atAlternate()).canSetLocation(folder(a)), + otherFolder: service(atAlternate()).canSetLocation(folder(b)), + multiRoot: service(multiRoot).canSetLocation(folder(a)), + empty: service(new Workspace('id', [], false, null, () => false)).canSetLocation(folder(a)), + remote: service(new Workspace('id', [folder(remote)], false, null, () => false)).canSetLocation(folder(remote)) + }, { singleFolder: true, atAlternate: true, otherFolder: false, multiRoot: false, empty: false, remote: false }); + }); + + test('onDidChangeCanSetLocation fires when the workspace folders or state change', () => { + const folders = disposables.add(new Emitter<IWorkspaceFoldersChangeEvent>()); + const state = disposables.add(new Emitter<WorkbenchState>()); + const contextService = new class extends mock<IWorkspaceContextService>() { + override onDidChangeWorkspaceFolders = folders.event; + override onDidChangeWorkbenchState = state.event; + }(); + const labelService = new class extends mock<ILabelService>() { + override registerWorkspaceLabelDecorator() { return toDisposable(() => { }); } + }(); + const service = disposables.add(new WorkspaceFolderLocationService(disposables.add(new UriIdentityService(disposables.add(new FileService(new NullLogService())))), contextService, labelService)); + let fired = 0; + disposables.add(service.onDidChangeCanSetLocation(() => fired++)); + + folders.fire({ added: [], removed: [], changed: [] }); + state.fire(WorkbenchState.WORKSPACE); + + assert.strictEqual(fired, 2); + }); +}); diff --git a/src/vs/workbench/test/browser/actions/navigationActions.test.ts b/src/vs/workbench/test/browser/actions/navigationActions.test.ts new file mode 100644 index 000000000000..443ae3bed1a5 --- /dev/null +++ b/src/vs/workbench/test/browser/actions/navigationActions.test.ts @@ -0,0 +1,71 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Direction } from '../../../../base/browser/ui/grid/grid.js'; +import { upcastPartial } from '../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { CommandsRegistry, ICommandService } from '../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { TestInstantiationService } from '../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { NAVIGATE_VIEW_COMMANDS } from '../../../browser/actions/navigationActions.js'; +import { IEditorGroup, IEditorGroupsService } from '../../../services/editor/common/editorGroupsService.js'; +import { IWorkbenchLayoutService, Parts } from '../../../services/layout/browser/layoutService.js'; +import { ViewContainerLocation } from '../../../common/views.js'; +import { IPaneCompositePartService } from '../../../services/panecomposite/browser/panecomposite.js'; + +suite('Navigate to the view on the left or right', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + /** + * Navigates from the focused part to its neighbor, in a window whose parts are, from left to right, `order`: the + * parts that show. Records what gets focus. + */ + async function navigate(order: readonly Parts[], focused: Parts, direction: Direction.Left | Direction.Right): Promise<string[]> { + const focusCalls: string[] = []; + const instantiationService = disposables.add(new TestInstantiationService()); + instantiationService.stub(IContextKeyService, upcastPartial<IContextKeyService>({ contextMatchesRules: () => false })); + instantiationService.stub(ICommandService, upcastPartial<ICommandService>({})); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial<IWorkbenchLayoutService>({ + hasFocus: part => part === focused, + isVisible: part => order.includes(part), + getVisibleNeighborPart: (part, neighborDirection) => order[order.indexOf(part) + (neighborDirection === Direction.Right ? 1 : -1)], + focusPart: part => { focusCalls.push(`focusPart ${part}`); }, + })); + const group = (name: string) => upcastPartial<IEditorGroup>({ focus: () => { focusCalls.push(`focus group ${name}`); } }); + instantiationService.stub(IEditorGroupsService, upcastPartial<IEditorGroupsService>({ + activeGroup: group('active'), + findGroup: () => undefined, + })); + instantiationService.stub(IPaneCompositePartService, upcastPartial<IPaneCompositePartService>({ + getActivePaneComposite: () => ({ getId: () => 'viewlet' }) as ReturnType<IPaneCompositePartService['getActivePaneComposite']>, + openPaneComposite: async (id, location) => { focusCalls.push(`open ${location}`); return undefined; }, + })); + const id = direction === Direction.Right ? NAVIGATE_VIEW_COMMANDS.right : NAVIGATE_VIEW_COMMANDS.left; + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand(id)!.handler(accessor)); + return focusCalls; + } + + test('enters and leaves a visible chat part beside the editor, and skips one that is absent', async () => { + const withChat = [Parts.SIDEBAR_PART, Parts.CHAT_PART, Parts.EDITOR_PART]; + const withoutChat = [Parts.SIDEBAR_PART, Parts.EDITOR_PART]; + assert.deepStrictEqual({ + sideBarRight: await navigate(withChat, Parts.SIDEBAR_PART, Direction.Right), + editorLeft: await navigate(withChat, Parts.EDITOR_PART, Direction.Left), + chatLeft: await navigate(withChat, Parts.CHAT_PART, Direction.Left), + chatRight: await navigate(withChat, Parts.CHAT_PART, Direction.Right), + withoutChatSideBarRight: await navigate(withoutChat, Parts.SIDEBAR_PART, Direction.Right), + withoutChatEditorLeft: await navigate(withoutChat, Parts.EDITOR_PART, Direction.Left), + }, { + sideBarRight: [`focusPart ${Parts.CHAT_PART}`], + editorLeft: [`focusPart ${Parts.CHAT_PART}`], + chatLeft: [`open ${ViewContainerLocation.Sidebar}`], + chatRight: [`focusPart ${Parts.EDITOR_PART}`], + withoutChatSideBarRight: ['focus group active'], + withoutChatEditorLeft: [`open ${ViewContainerLocation.Sidebar}`], + }); + }); +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/aiStats.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/aiStats.fixture.ts deleted file mode 100644 index 0ab26885d3ed..000000000000 --- a/src/vs/workbench/test/browser/componentFixtures/aiStats.fixture.ts +++ /dev/null @@ -1,92 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { observableValue } from '../../../../base/common/observable.js'; -import { createAiStatsHover, IAiStatsHoverData } from '../../../contrib/editTelemetry/browser/editStats/aiStatsStatusBar.js'; -import { ISessionData } from '../../../contrib/editTelemetry/browser/editStats/aiStatsChart.js'; -import { Random } from '../../../../editor/test/common/core/random.js'; -import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup } from './fixtureUtils.js'; - -export default defineThemedFixtureGroup({ path: 'chat/' }, { - AiStatsHover: defineComponentFixture({ - labels: { kind: 'screenshot' }, - render: (context) => renderAiStatsHover({ ...context, data: createSampleDataWithSessions() }), - }), - - AiStatsHoverNoData: defineComponentFixture({ - labels: { kind: 'screenshot' }, - render: (context) => renderAiStatsHover({ ...context, data: createEmptyData() }), - }), -}); - -function createSampleDataWithSessions(): IAiStatsHoverData { - const random = Random.create(42); - - // Use a fixed base time for determinism (Jan 1, 2025, 12:00:00 UTC) - const baseTime = 1735732800000; - const dayMs = 24 * 60 * 60 * 1000; - const sessionLengthMs = 5 * 60 * 1000; - - // Generate fake session data for the last 7 days - const fakeSessions: ISessionData[] = []; - for (let day = 6; day >= 0; day--) { - const dayStart = baseTime - day * dayMs; - const sessionsPerDay = random.nextIntRange(3, 9); - for (let s = 0; s < sessionsPerDay; s++) { - const sessionTime = dayStart + s * sessionLengthMs * 2; - fakeSessions.push({ - startTime: sessionTime, - typedCharacters: random.nextIntRange(100, 600), - aiCharacters: random.nextIntRange(200, 1000), - acceptedInlineSuggestions: random.nextIntRange(1, 16), - chatEditCount: random.nextIntRange(0, 5), - }); - } - } - - const totalAi = fakeSessions.reduce((sum, s) => sum + s.aiCharacters, 0); - const totalTyped = fakeSessions.reduce((sum, s) => sum + s.typedCharacters, 0); - const aiRate = totalAi / (totalAi + totalTyped); - - // "Today" for the fixture is the baseTime day - const startOfToday = baseTime - (baseTime % dayMs); - const todaySessions = fakeSessions.filter(s => s.startTime >= startOfToday); - const acceptedToday = todaySessions.reduce((sum, s) => sum + (s.acceptedInlineSuggestions ?? 0), 0); - - return { - aiRate: observableValue('aiRate', aiRate), - acceptedInlineSuggestionsToday: observableValue('acceptedToday', acceptedToday), - sessions: observableValue('sessions', fakeSessions), - }; -} - -function createEmptyData(): IAiStatsHoverData { - return { - aiRate: observableValue('aiRate', 0), - acceptedInlineSuggestionsToday: observableValue('acceptedToday', 0), - sessions: observableValue('sessions', []), - }; -} - -interface RenderAiStatsOptions extends ComponentFixtureContext { - data: IAiStatsHoverData; -} - -function renderAiStatsHover({ container, disposableStore, data }: RenderAiStatsOptions): void { - container.style.width = '320px'; - container.style.padding = '8px'; - container.style.backgroundColor = 'var(--vscode-editorHoverWidget-background)'; - container.style.border = '1px solid var(--vscode-editorHoverWidget-border)'; - container.style.borderRadius = '4px'; - container.style.color = 'var(--vscode-editorHoverWidget-foreground)'; - - const hover = createAiStatsHover({ - data, - onOpenSettings: () => console.log('Open settings clicked'), - }); - - const elem = hover.keepUpdated(disposableStore).element; - container.appendChild(elem); -} diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatArtifactAction.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatArtifactAction.fixture.ts index 407ddda42bb9..a260220d8ed2 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatArtifactAction.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatArtifactAction.fixture.ts @@ -23,7 +23,7 @@ const pullRequest = { const checks: ArtifactRequestPresentation = { version: 1, integrationLabel: 'GitHub Pull Requests', source: 'automation', - action: { label: 'Fix CI', iconId: 'tools' }, + action: { label: 'Fix CI', iconId: 'lightbulb' }, artifact: pullRequest, details: [{ title: 'Checks', description: '1 of 5 checks passed; 3 failed; 1 in progress.', @@ -40,7 +40,7 @@ const checks: ArtifactRequestPresentation = { const comments: ArtifactRequestPresentation = { ...checks, - action: { label: 'Address Comments', iconId: 'comment-discussion' }, + action: { label: 'Address Comments', iconId: 'comment' }, details: [{ title: 'Comments', description: '2 unresolved review comments.', availability: { kind: 'available' }, links: [], completeness: 'complete', diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatCustomizationsHover.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatCustomizationsHover.fixture.ts new file mode 100644 index 000000000000..a2407d0cca84 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatCustomizationsHover.fixture.ts @@ -0,0 +1,136 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { constObservable } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { McpServerStatus } from '../../../../../platform/agentHost/common/state/protocol/state.js'; +import { HoverWidget } from '../../../../../platform/hover/browser/hoverWidget.js'; +import { IMarkdownRendererService, MarkdownRendererService } from '../../../../../platform/markdown/browser/markdownRenderer.js'; +import { IChatWidgetService } from '../../../../contrib/chat/browser/chat.js'; +import { IAgentHostCustomizationService } from '../../../../contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.js'; +import { IAICustomizationItemsModel, ItemsModelSection } from '../../../../contrib/chat/browser/aiCustomization/aiCustomizationItemsModel.js'; +import { ChatCustomizationsHover } from '../../../../contrib/chat/browser/aiCustomization/chatCustomizationsHover.js'; +import { AgentHostMcpServer } from '../../../../contrib/chat/browser/aiCustomization/mcpServerCount.js'; +import { IAICustomizationWorkspaceService } from '../../../../contrib/chat/common/aiCustomizationWorkspaceService.js'; +import { ICustomizationHarnessService, IHarnessDescriptor } from '../../../../contrib/chat/common/customizationHarnessService.js'; +import { CustomizationMigrationType, ICustomizationMigrationHint, ICustomizationMigrationService } from '../../../../contrib/chat/common/promptSyntax/service/customizationMigrationService.js'; +import { IMcpService } from '../../../../contrib/mcp/common/mcpTypes.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../fixtureUtils.js'; + +interface IHoverState { + readonly migrationCount?: number; + readonly authRequiredCount?: number; + readonly serverNames?: readonly string[]; +} + +const sessionResource = URI.parse('agent-host-copilotcli:/fixture-session'); +const descriptor: IHarnessDescriptor = { id: sessionResource.scheme, label: 'Copilot', icon: Codicon.copilot }; +const sectionCounts: Record<ItemsModelSection, number> = { agents: 4, skills: 77, instructions: 41, prompts: 0, hooks: 2 }; +const serverNames = ['GitHub', 'Figma', 'Azure DevOps', 'Documentation', 'PostgreSQL', 'Workspace Tools']; + +async function renderHover({ container, disposableStore, theme }: ComponentFixtureContext, state: IHoverState = {}): Promise<void> { + const servers = (state.serverNames ?? serverNames).map((name, index) => new class extends mock<AgentHostMcpServer>() { + override readonly id = `fixture/server-${index}`; + override readonly name = name; + override readonly enabled = true; + override readonly status = index < (state.authRequiredCount ?? 0) ? McpServerStatus.AuthRequired : McpServerStatus.Ready; + }()); + const migration: ICustomizationMigrationHint | undefined = state.migrationCount ? { + migrationFlowId: 'fixture-migration', + message: 'Customizations need migration.', + counts: [{ type: CustomizationMigrationType.UserData, count: state.migrationCount }], + } : undefined; + const instantiationService = createEditorServices(disposableStore, { + colorTheme: theme, + additionalServices: registry => { + registerWorkbenchServices(registry); + registry.define(IMarkdownRendererService, MarkdownRendererService); + registry.defineInstance(IAICustomizationItemsModel, new class extends mock<IAICustomizationItemsModel>() { + override async whenSectionLoaded(): Promise<void> { } + override getPluginCount() { return constObservable(4); } + override getCount(section: ItemsModelSection) { return constObservable(sectionCounts[section]); } + }); + registry.defineInstance(ICustomizationHarnessService, new class extends mock<ICustomizationHarnessService>() { + override readonly activeSessionResource = constObservable(sessionResource); + override getActiveDescriptor() { return descriptor; } + }); + registry.defineInstance(IAICustomizationWorkspaceService, new class extends mock<IAICustomizationWorkspaceService>() { + override readonly activeProjectRoot = constObservable(URI.file('/workspace/project')); + override readonly activeProjectLabel = constObservable('project'); + }); + registry.defineInstance(IMcpService, new class extends mock<IMcpService>() { + override readonly servers = constObservable([]); + }); + registry.defineInstance(IAgentHostCustomizationService, new class extends mock<IAgentHostCustomizationService>() { + override getMcpServers() { return servers; } + }); + registry.defineInstance(IChatWidgetService, new class extends mock<IChatWidgetService>() { + override getAllWidgets() { return []; } + }); + registry.defineInstance(ICustomizationMigrationService, new class extends mock<ICustomizationMigrationService>() { + override async computeMigrationHint() { return migration; } + }); + }, + }); + + container.style.width = 'fit-content'; + container.style.padding = '20px'; + container.style.backgroundColor = 'var(--vscode-editor-background)'; + + const content = await instantiationService.createInstance(ChatCustomizationsHover).getContent(CancellationToken.None); + if (!content) { + throw new Error('The session customizations hover fixture did not finish discovery.'); + } + const hover = disposableStore.add(instantiationService.createInstance(HoverWidget, { + content, + target: container, + additionalClasses: ['chat-customizations-hover'], + appearance: { compact: true, skipFadeInAnimation: true }, + })); + hover.domNode.style.position = 'relative'; + hover.domNode.style.display = 'inline-block'; + container.appendChild(hover.domNode); +} + +export default defineThemedFixtureGroup({ path: 'chat/' }, { + Default: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: true }, + expectedVisualDescriptions: [ + 'A compact Session Customizations hover has breathing room above its title and a muted Copilot and project context line, followed by five icon-labelled inventory rows with right-aligned counts, no visible table header, and no Needs attention section.', + 'The footer shows a plus icon vertically centered with Browse Additional on the left and a settings gear aligned with the counts on the right.', + ], + render: context => renderHover(context), + }), + Migrations: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['Below the five inventory rows, Needs attention contains a link for 3 customizations needing migration and no MCP sign-in warning.'], + render: context => renderHover(context, { migrationCount: 3 }), + }), + McpAuthentication: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['Needs attention reports 2 MCP servers requiring sign-in, lists GitHub and Figma as individual sign-in links below it, and has no migration warning.'], + render: context => renderHover(context, { authRequiredCount: 2 }), + }), + MigrationsAndMcpAuthentication: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: true }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'Needs attention contains both a 3-customization migration warning and a 4-MCP-server sign-in warning below the inventory and above the footer.', + 'Only GitHub and Figma are named as individual sign-in links, followed by +2 more. The settings gear is right-aligned with the inventory counts.', + ], + render: context => renderHover(context, { migrationCount: 3, authRequiredCount: 4 }), + }), + LongMcpServerNames: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['Both long server-name links under the sign-in warning are individually truncated with ellipses, followed by +1 more, without widening the compact hover or displacing the settings gear.'], + render: context => renderHover(context, { + authRequiredCount: 3, + serverNames: ['Company GitHub Enterprise Integration', 'Workspace Design and Collaboration Service', 'Documentation'], + }), + }), +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatNativeComponents.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatNativeComponents.fixture.ts new file mode 100644 index 000000000000..92e557b139f3 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatNativeComponents.fixture.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 * as dom from '../../../../../base/browser/dom.js'; +import { renderNativeComponents } from '../../../../contrib/chat/browser/widget/chatContentParts/chatNativeComponentsRenderer.js'; +import { parseNativeComponents } from '../../../../contrib/chat/common/nativeComponents/nativeComponentsParser.js'; +import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup } from '../fixtureUtils.js'; + +import '../../../../contrib/chat/browser/widget/media/chat.css'; + +const catalogue = [ + '<Columns>', + ' <Metric label="Full build" value="12.4 s" />', + ' <Metric label="Incremental build" value="1.8 s" delta="-85%" tone="positive" />', + ' <Metric label="Failing tests" value="3" delta="+2 since Monday" tone="negative" />', + ' <Metric label="Flaky tests" value="7" tone="warning" />', + '</Columns>', + '<Badge>Draft</Badge>', + '<Badge tone="positive">Passing</Badge>', + '<Badge tone="negative">Blocked</Badge>', + '<Badge tone="warning">Needs review</Badge>', + '<BarChart title="Build duration by target" unit="s">', + ' <Bar label="Full build" value="12.4" />', + ' <Bar label="Incremental build after a one-line change" value="1.8" />', + ' <Bar label="Cached" value="0" />', + '</BarChart>', + '<Table caption="Duration by target">', + ' <Column>Target</Column>', + ' <Column align="end">Before</Column>', + ' <Column align="end">After</Column>', + ' <Row><Cell>Full build</Cell><Cell>12.9 s</Cell><Cell>12.4 s</Cell></Row>', + ' <Row><Cell>Incremental build</Cell><Cell>11.7 s</Cell><Cell>1.8 s</Cell></Row>', + '</Table>', + '<Text variant="heading">Notes</Text>', + '<Text>Most of the improvement comes from caching the module graph between runs.</Text>', + '<Text variant="caption">Measured on a warm cache.</Text>', + '<Disclosure summary="How this was measured">', + ' <Text>Median of five runs.</Text>', + '</Disclosure>', + '<Disclosure summary="Known limits">', + ' <Text>The first build after a branch switch is not cached.</Text>', + '</Disclosure>', +].join('\n'); + +/** Renders the catalogue inside the ancestors of a response's Markdown, so that the chat styles apply as they do in a transcript. */ +function renderCatalogue({ container }: ComponentFixtureContext, width: number): void { + const { document, error } = parseNativeComponents(catalogue); + if (!document) { + throw new Error(error.message); + } + const visual = renderNativeComponents(document); + visual.disclosures[visual.disclosures.length - 1].open = true; + + container.style.width = `${width}px`; + container.style.padding = '12px'; + container.style.backgroundColor = 'var(--vscode-editor-background)'; + container.classList.add('interactive-session'); + const part = dom.$('.chat-native-components', undefined, dom.$('.chat-native-components-visual', undefined, visual.element)); + const markdown = dom.$('.rendered-markdown', undefined, dom.$('div', { 'data-code': '0' }, part)); + container.appendChild(dom.$('.interactive-item-container.interactive-response', undefined, dom.$('.value', undefined, markdown))); +} + +export default defineThemedFixtureGroup({ path: 'chat/' }, { + Catalogue: defineComponentFixture({ + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + labels: { kind: 'screenshot' }, + render: context => renderCatalogue(context, 560), + }), + CatalogueInNarrowChat: defineComponentFixture({ + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + labels: { kind: 'screenshot' }, + render: context => renderCatalogue(context, 260), + }), +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatQuestionCarousel.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatQuestionCarousel.fixture.ts index f8c96aa7f069..5c5473972a19 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatQuestionCarousel.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatQuestionCarousel.fixture.ts @@ -18,6 +18,7 @@ import { observableValue } from '../../../../../base/common/observable.js'; import { IChatRequestViewModel } from '../../../../contrib/chat/common/model/chatViewModel.js'; import { ChatQuestionCarouselData } from '../../../../contrib/chat/common/model/chatProgressTypes/chatQuestionCarouselData.js'; import { ITerminalChatService } from '../../../../contrib/terminal/browser/terminal.js'; +import '../../../../contrib/sessions/browser/parts/media/sessionsGridContent.css'; import '../../../../contrib/chat/browser/widget/chatContentParts/media/chatQuestionCarousel.css'; function createCarousel(questions: IChatQuestion[], allowSkip: boolean = true): IChatQuestionCarousel { @@ -53,8 +54,8 @@ function createOptions(overrides: Partial<IChatQuestionCarouselOptions> = {}): I }; } -function renderCarousel(context: ComponentFixtureContext, carousel: IChatQuestionCarousel, standalone: boolean = false, options: Partial<IChatQuestionCarouselOptions> = {}, afterRender?: (part: ChatQuestionCarouselPart) => void): void { - const { container, disposableStore } = context; +function renderCarousel(context: ComponentFixtureContext, carousel: IChatQuestionCarousel, standalone: boolean = false, options: Partial<IChatQuestionCarouselOptions> = {}, afterRender?: (part: ChatQuestionCarouselPart) => void, host: HTMLElement = context.container): void { + const { disposableStore } = context; const instantiationService = createEditorServices(disposableStore, { colorTheme: context.theme, @@ -78,21 +79,28 @@ function renderCarousel(context: ComponentFixtureContext, carousel: IChatQuestio ) ); - container.style.width = '400px'; - container.style.padding = '8px'; - container.classList.add('interactive-session'); + host.style.width = '400px'; + host.style.padding = '8px'; + host.classList.add('interactive-session'); // The CSS uses `.interactive-session .interactive-input-part > .chat-question-carousel-widget-container` // for most layout rules, so we need those wrapper elements. const inputPart = dom.$('.interactive-input-part'); const widgetContainer = dom.$('.chat-question-carousel-widget-container'); inputPart.appendChild(widgetContainer); - container.appendChild(inputPart); + host.appendChild(inputPart); widgetContainer.appendChild(part.domNode); afterRender?.(part); } +function renderAgentSessionsCarousel(context: ComponentFixtureContext, carousel: IChatQuestionCarousel): void { + context.container.classList.add('monaco-workbench'); + const sessionsSurface = dom.append(context.container, dom.$('.sessions-chat-surface')); + const content = dom.append(sessionsSurface, dom.$('.content')); + renderCarousel(context, carousel, false, {}, undefined, content); +} + interface ICarouselLayout { readonly card: HTMLElement; readonly title: HTMLElement; @@ -210,6 +218,15 @@ const deleteBranchesQuestion: IChatQuestion = { required: true, }; +const publishDashboardQuestion: IChatQuestion = { + id: 'publish-dashboard', + type: 'singleSelect', + title: 'Publish the dashboard changes?', + message: 'Both queries passed validation. May I publish them to the shared dashboard?', + options: booleanOptions, + allowFreeformInput: true, +}; + const experimentGateQuestion: IChatQuestion = { id: 'experiment-gate', type: 'singleSelect', @@ -339,6 +356,8 @@ function createDeploymentCarousel(optionCount: number, description: string | und // Fixtures // ============================================================================ +const defaultThemes = ['darkModern', 'light2026', 'darkPlus', 'lightPlus', 'visualStudioDark', 'visualStudioLight', 'darkHighContrast', 'lightHighContrast'] as const; + export default defineThemedFixtureGroup({ path: 'chat/' }, { SingleTextQuestion: defineComponentFixture({ labels: { kind: 'screenshot' }, @@ -350,6 +369,22 @@ export default defineThemedFixtureGroup({ path: 'chat/' }, { render: (context) => renderCarousel(context, createCarousel([singleSelectQuestion])), }), + AgentSessionsSingleSelectQuestion: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: defaultThemes, + expectedVisualDescriptions: ['The custom answer editor is a single, uniform input surface without an inset panel-colored editor area or gutters.'], + virtualTime: { enabled: false }, + render: context => renderAgentSessionsCarousel(context, createCarousel([singleSelectQuestion])), + }), + + AgentSessionsBooleanCustomAnswer: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: defaultThemes, + expectedVisualDescriptions: ['Yes and No appear as vertical options above the custom answer editor, which uses the same input frame as other single-select questions.'], + virtualTime: { enabled: false }, + render: context => renderAgentSessionsCarousel(context, createCarousel([publishDashboardQuestion])), + }), + MultiSelectQuestion: defineComponentFixture({ labels: { kind: 'screenshot' }, render: (context) => renderCarousel(context, createCarousel([multiSelectQuestion])), diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatRendering.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatRendering.fixture.ts index f95a77c5cdb8..dcb9d26937f5 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatRendering.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatRendering.fixture.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { URI } from '../../../../../base/common/uri.js'; +import { getWindow } from '../../../../../base/browser/dom.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; @@ -11,7 +12,7 @@ import { ChatModeKind, ChatPermissionLevel, ChatProgressAnimation, ChatProgressV import { ChatToolInvocation } from '../../../../contrib/chat/common/model/chatProgressTypes/chatToolInvocation.js'; import { IChatQuestionCarousel, ToolConfirmKind } from '../../../../contrib/chat/common/chatService/chatService.js'; import { ILanguageModelToolsService, ToolDataSource } from '../../../../contrib/chat/common/tools/languageModelToolsService.js'; -import { getToolInvocationSummaryFromInput } from '../../../../contrib/chat/common/tools/toolInvocationSummary.js'; +import { getToolInvocationSummaryFromInput, type ChatToolInvocationSummary } from '../../../../contrib/chat/common/tools/toolInvocationSummary.js'; import { ILanguageModelToolsConfirmationService } from '../../../../contrib/chat/common/tools/languageModelToolsConfirmationService.js'; import { MockLanguageModelToolsConfirmationService } from '../../../../contrib/chat/test/common/tools/mockLanguageModelToolsConfirmationService.js'; import { MockLanguageModelToolsService } from '../../../../contrib/chat/test/common/tools/mockLanguageModelToolsService.js'; @@ -333,6 +334,92 @@ async function renderDeterministicToolSummaries(context: ComponentFixtureContext }, 'Deterministic tool summaries did not settle'); } +/** + * Finished Conversation sections: tool summaries with their time, including one whose reasoning + * has a heading, reasoning alone, and a tool summary whose time was not recorded. With `completedSteps` + * they are folded into the completed response's closed disclosure. + */ +async function renderConversationSections(context: ComponentFixtureContext, completedSteps = false): Promise<void> { + const titles = ['Ran 1 command - 9s', 'Ran 2 commands, read summary.ts - 31s', 'Thought for 26s', 'Edited 2 files, 1 other step']; + const height = completedSteps ? 220 : 420; + await renderChatWidget(context, { + width: 500, height, listHeight: height, inputVisible: false, + persistentProgress: ChatProgressAnimation.Draw, + persistentProgressVerbosity: ChatProgressVerbosity.Conversation, + collapseCompletedResponses: completedSteps, + thinkingPhrases: ['Working'], + messages: [{ user: 'Collapse the terminal output once its command finishes', responseComplete: false, assistant: [] }], + onRendered: ({ model }) => { + const request = model.getRequests()[0]; + const reason = (id: string, value: string, reasoningDurationMs: number) => model.acceptResponseProgress(request, { kind: 'thinking', id, value, reasoningTimingSource: 'provider', reasoningDurationMs }); + const say = (text: string) => model.acceptResponseProgress(request, { kind: 'markdownContent', content: new MarkdownString(text) }); + const tool = (toolCallId: string, message: string, summary: ChatToolInvocationSummary, startedAt?: number, completedAt?: number) => model.acceptResponseProgress(request, { + kind: 'toolInvocationSerialized', toolId: toolCallId, toolCallId, invocationMessage: new MarkdownString(message), pastTenseMessage: new MarkdownString(message), + isComplete: true, isConfirmed: { type: ToolConfirmKind.ConfirmationNotNeeded }, source: ToolDataSource.Internal, + presentation: undefined, originMessage: undefined, summary, startedAt, completedAt, + }); + + reason('review', '**Reviewing the completion handler**\n\nThe output stays open after the command exits, so the handler is the place to start.', 5000); + tool('status', 'Ran `git status --short`', { kind: 'command' }, 10_000, 14_000); + say('The handler only collapses commands it saw start.'); + + reason('plan', 'The card is rebuilt when the tool call completes, so the state it remembers has to be keyed by the invocation.', 23_000); + tool('build', 'Ran `pnpm run build-fast`', { kind: 'command' }, 30_000, 32_000); + tool('test', 'Ran `scripts/test.sh`', { kind: 'command' }, 31_000, 33_000); + tool('read', 'Read summary.ts', { kind: 'read', resources: [{ uri: URI.file('/workspace/summary.ts') }] }, 40_000, 41_000); + reason('compare', 'Both layouts collapse now, so the tests can cover them together.', 4000); + say('The card collapses in every layout.'); + + reason('verify', 'A rebuilt card must not expand again when late output arrives.', 26_000); + say('Late output no longer reopens the card.'); + + for (const file of ['/workspace/progressPart.ts', '/workspace/progressPart.test.ts']) { + model.acceptResponseProgress(request, { kind: 'externalEdit', uri: URI.file(file), editKind: 'edit', diff: { added: 12, removed: 4 }, undoStopId: 'edits' }); + } + tool('memory', 'Stored a memory', { kind: 'unknown' }); + say('The fix and its tests are in place.'); + request.response?.setElapsedMs(123_000); + request.response?.complete(); + }, + }); + const sections = () => [...context.container.querySelectorAll<HTMLElement>('.chat-thinking-conversation')]; + const isSettled = () => !context.container.getAnimations({ subtree: true }).some(animation => + (animation.playState === 'running' || animation.pending) && animation.effect?.getComputedTiming().endTime !== Infinity); + await waitForFixtureCondition(() => { + const rendered = sections().map(section => section.querySelector(':scope > .chat-used-context-label .monaco-button-mdlabel')?.textContent); + return rendered.length === titles.length && rendered.every((title, index) => title === titles[index]) && isSettled(); + }, 'Conversation section titles did not settle'); + if (completedSteps) { + await waitForFixtureCondition(() => context.container.querySelector<HTMLDetailsElement>('.completed-response-disclosure')?.open === false, 'Completed steps did not collapse'); + } + await waitForFixtureCondition(() => conversationChevronsStartOnTextEdge(context.container), 'Conversation chevrons do not start on the left edge of the text they lead'); +} + +/** + * Whether the chevron of each laid out, closed Conversation header starts on the header's left edge, + * where the response's text starts. A chevron's glyph is narrower than its box, so this measures its ink. + */ +function conversationChevronsStartOnTextEdge(container: HTMLElement): boolean { + const targetWindow = getWindow(container); + const canvas = targetWindow.document.createElement('canvas').getContext('2d'); + if (!canvas) { + return false; + } + const headers = container.querySelectorAll<HTMLElement>('.chat-thinking-conversation > .chat-used-context-label, .completed-response-conversation > .completed-response-summary'); + return Array.from(headers).every(header => { + const chevron = header.querySelector<HTMLElement>('.codicon-chevron-right-compact'); + const box = chevron?.getBoundingClientRect(); + if (!chevron || !box?.width) { + // The headers inside closed completed steps are not laid out + return true; + } + const glyph = targetWindow.getComputedStyle(chevron, '::before'); + canvas.font = `${glyph.fontSize} ${glyph.fontFamily}`; + const ink = canvas.measureText(glyph.content.replace(/["']/g, '')); + return Math.abs(box.left - ink.actualBoundingBoxLeft - header.getBoundingClientRect().left) < 0.5; + }); +} + function renderReadPills(context: ComponentFixtureContext, complete: boolean): Promise<void> { const resource = URI.file('/workspace/chatListRenderer.ts'); const diff = { @@ -443,6 +530,17 @@ export default defineThemedFixtureGroup({ path: 'chat/' }, { deferPaint: true, render: context => renderDeterministicToolSummaries(context, 280), }), + ConversationSections: defineComponentFixture({ + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + virtualTime: { enabled: false }, + deferPaint: true, + render: context => renderConversationSections(context), + }), + ConversationCompletedSteps: defineComponentFixture({ + virtualTime: { enabled: false }, + deferPaint: true, + render: context => renderConversationSections(context, true), + }), SuccessfulCommands: defineComponentFixture({ virtualTime: { enabled: false }, deferPaint: true, diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatSessionPathConfirmation.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatSessionPathConfirmation.fixture.ts new file mode 100644 index 000000000000..a4edb6f2d884 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatSessionPathConfirmation.fixture.ts @@ -0,0 +1,91 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { toSlashes } from '../../../../../base/common/extpath.js'; +import { extUri } from '../../../../../base/common/resources.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { getSessionPathDisplay } from '../../../../../platform/agentHost/common/sessionPathDisplay.js'; +import { ConfirmationOptionKind, ToolCallStatus } from '../../../../../platform/agentHost/common/state/protocol/state.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IMarkerService } from '../../../../../platform/markers/common/markers.js'; +import { MarkerService } from '../../../../../platform/markers/common/markerService.js'; +import { toolCallStateToInvocation } from '../../../../contrib/chat/browser/agentSessions/agentHost/stateToProgressAdapter.js'; +import { ILanguageModelToolsConfirmationService } from '../../../../contrib/chat/common/tools/languageModelToolsConfirmationService.js'; +import { ILanguageModelToolsService } from '../../../../contrib/chat/common/tools/languageModelToolsService.js'; +import { MockLanguageModelToolsConfirmationService } from '../../../../contrib/chat/test/common/tools/mockLanguageModelToolsConfirmationService.js'; +import { MockLanguageModelToolsService } from '../../../../contrib/chat/test/common/tools/mockLanguageModelToolsService.js'; +import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup, waitForFixtureCondition } from '../fixtureUtils.js'; +import { renderChatWidget } from './chatWidget.fixture.js'; + +type Scenario = 'current' | 'sibling' | 'other' | 'movedSource' | 'movedDestination' | 'unknown' | 'terminal'; + +async function renderConfirmation(context: ComponentFixtureContext, scenario: Scenario, width = 620): Promise<void> { + const source = URI.parse('copilot:/source'); + const destination = URI.parse('copilot:/destination'); + const isOther = scenario === 'other' || scenario === 'movedSource' || scenario === 'movedDestination'; + const current = scenario === 'movedDestination' ? destination : source; + const sdkId = scenario === 'sibling' ? 'peer-chat-sdk' : isOther ? 'moved-chat-sdk' : 'current-chat-sdk'; + const rootPath = `C:\\Users\\example\\.copilot\\session-state\\${sdkId}`; + const path = `${rootPath}\\files\\notes.txt`; + const root = URI.file(toSlashes(rootPath)); + const display = getSessionPathDisplay(path, URI.joinPath(root, 'files', 'notes.txt'), current, scenario === 'unknown' ? [] : [ + { root, session: isOther ? destination : source, title: 'Review authentication' }, + ], extUri); + const invocation = toolCallStateToInvocation({ + toolCallId: 'session-grant', toolName: scenario === 'terminal' ? 'shell' : 'read_file', + displayName: scenario === 'terminal' ? 'Shell' : 'Read file', status: ToolCallStatus.PendingConfirmation, + confirmationTitle: 'Allow sandbox path access and retry?', + invocationMessage: { + markdown: `${display.isCurrentSession ? `Allow read access to \`${display.relativePath}\` in this session's storage.` : `Allow read access to \`${display.label}\` and retry inside the sandbox.`}\n\nSession access is shared by chats in this session and saved when you resume it. User access is saved to your user sandbox settings and shared with connected agent hosts across workspaces and sessions. Your organization's restrictions still apply.`, + }, + toolInput: scenario === 'terminal' ? 'Get-Content notes.txt' : JSON.stringify({ path }), + options: [ + { id: 'save-session-sandbox-path', label: 'Allow for This Session', kind: ConfirmationOptionKind.Approve, group: 1 }, + { id: 'save-sandbox-path', label: 'Allow for This User', kind: ConfirmationOptionKind.Approve, group: 1 }, + { id: 'skip', label: 'Skip', kind: ConfirmationOptionKind.Deny, group: 2 }, + ], + _meta: { + 'vscode.sandboxPathGrant': { path, access: 'read' }, + ...(scenario === 'terminal' ? { toolKind: 'terminal', language: 'powershell' } : {}), + }, + }, undefined, current, ''); + await renderChatWidget(context, { + width, height: 440, listHeight: 440, inputVisible: false, + messages: [{ user: 'Read the session notes', assistant: [], responseComplete: false }], + additionalServices: reg => { + reg.define(IMarkerService, MarkerService); + reg.defineInstance(ILanguageModelToolsConfirmationService, new MockLanguageModelToolsConfirmationService()); + reg.defineInstance(ILanguageModelToolsService, context.disposableStore.add(new MockLanguageModelToolsService())); + }, + onRendered: ({ model, instantiationService }) => { + const commandService = instantiationService.get(ICommandService); + instantiationService.stub(ICommandService, { + onWillExecuteCommand: commandService.onWillExecuteCommand, + onDidExecuteCommand: commandService.onDidExecuteCommand, + async executeCommand<R>(id: string, ...args: unknown[]): Promise<R | undefined> { + // The JSON extension is not loaded in component fixtures. + return id === 'json.validate' ? undefined : commandService.executeCommand<R>(id, ...args); + }, + }); + model.acceptResponseProgress(model.getRequests()[0], invocation); + }, + }); + const cardSelector = '.chat-tool-confirmation-carousel .chat-confirmation-widget2'; + await waitForFixtureCondition(() => (context.container.querySelector(cardSelector)?.getBoundingClientRect().height ?? 0) > 0, 'Confirmation did not render'); +} + +export default defineThemedFixtureGroup({ path: 'chat/SessionPathConfirmation/' }, { + Current: defineComponentFixture({ render: context => renderConfirmation(context, 'current') }), + SiblingChat: defineComponentFixture({ render: context => renderConfirmation(context, 'sibling') }), + OtherSession: defineComponentFixture({ render: context => renderConfirmation(context, 'other') }), + MovedFromSource: defineComponentFixture({ render: context => renderConfirmation(context, 'movedSource') }), + MovedToDestination: defineComponentFixture({ render: context => renderConfirmation(context, 'movedDestination') }), + Unknown: defineComponentFixture({ render: context => renderConfirmation(context, 'unknown') }), + Terminal: defineComponentFixture({ render: context => renderConfirmation(context, 'terminal') }), + Narrow: defineComponentFixture({ + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderConfirmation(context, 'other', 320), + }), +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/chatWidget.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/chatWidget.fixture.ts index 34c786e97d09..a76eca37407c 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/chatWidget.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/chatWidget.fixture.ts @@ -19,7 +19,7 @@ import { EditorMarkdownCodeBlockRenderer } from '../../../../../editor/browser/w import { IMenuItem, IMenuService, MenuId, MenuItemAction } from '../../../../../platform/actions/common/actions.js'; import { IAccessibilityService } from '../../../../../platform/accessibility/common/accessibility.js'; import { TestAccessibilityService } from '../../../../../platform/accessibility/test/common/testAccessibilityService.js'; -import { ChatRequestTextPart } from '../../../../contrib/chat/common/requestParser/chatParserTypes.js'; +import { ChatRequestSlashPromptPart, ChatRequestTextPart, IParsedChatRequest } from '../../../../contrib/chat/common/requestParser/chatParserTypes.js'; import { ChatModel, ChatRequestModel, ChatRequestSource, IChatRequestModeInfo, IChatRequestModel } from '../../../../contrib/chat/common/model/chatModel.js'; import { ChatViewModel } from '../../../../contrib/chat/common/model/chatViewModel.js'; import { ChatListWidget } from '../../../../contrib/chat/browser/widget/chatListWidget.js'; @@ -81,6 +81,7 @@ export interface IFixtureFileChange { export interface IFixtureMessage { readonly user: string; // user prompt text + readonly parts?: IParsedChatRequest['parts']; readonly variables?: readonly IChatRequestVariableEntry[]; readonly timestamp?: number; readonly modeInfo?: IChatRequestModeInfo; @@ -445,7 +446,7 @@ export async function renderChatWidget(context: ComponentFixtureContext, options for (const message of options.messages) { const request = model.addRequest( - makeUserMessage(message.user), + message.parts ? { text: message.user, parts: message.parts } : makeUserMessage(message.user), { variables: message.variables ?? [] }, 0, message.modeInfo, @@ -739,10 +740,12 @@ export async function renderChatWidget(context: ComponentFixtureContext, options const inputPart = disposableStore.add(instantiationService.createInstance(ChatInputPart, ChatAgentLocation.Chat, inputOptions, inputStyles, false)); + const listContainer = dom.$('.interactive-list'); const fixtureWidget = new class extends mock<IChatWidget>() { override readonly onDidChangeViewModel = disposableStore.add(new Emitter<never>()).event; override readonly viewModel = viewModel; override readonly domNode = session; + override readonly transcriptDomNode = listContainer; override readonly contribs = []; override readonly location = ChatAgentLocation.Chat; override readonly viewContext = {}; @@ -760,7 +763,6 @@ export async function renderChatWidget(context: ComponentFixtureContext, options options.decorateInputPart?.(inputPart, instantiationService); inputPart.element.classList.toggle('chat-input-hidden', options.inputVisible === false); - const listContainer = dom.$('.interactive-list'); listContainer.style.flex = options.hostLayoutMode ? '0 0 auto' : '1 1 auto'; listContainer.style.minHeight = '0'; listContainer.style.position = 'relative'; @@ -1734,18 +1736,27 @@ interface IVerbosityComparisonOptions { readonly expand?: boolean; /** Names the running tool call with a file link, which renders beside the section's header button. */ readonly linkedTitle?: boolean; + /** Names the running tool call with a file pill, which must not make the header taller than a plain title. */ + readonly filePillTitle?: boolean; /** Ends the running response with reasoning that has a summary heading. */ readonly reasoningLast?: boolean; + /** Ends the running response with reasoning that has no summary heading, and a first line longer than the header's row. */ + readonly unheadedReasoningLast?: boolean; } async function renderPersistentVerbosityComparison(context: ComponentFixtureContext, verbosity: ChatProgressVerbosity, complete: boolean, options: IVerbosityComparisonOptions = {}): Promise<void> { - const patchComplete = complete || !!options.reasoningLast; - const runningPatchMessage = options.linkedTitle ? 'Updating [progress.ts](file:///workspace/src/progress.ts)' : 'Updating the progress renderer...'; + const lastReasoning = options.reasoningLast ? '**Checking the related tests**\nConfirm the tests cover the tool and reasoning paths.' + : options.unheadedReasoningLast ? 'The tool and reasoning paths share one renderer, so the related tests should cover both of them before the header changes how it names what the response is doing.\n\nThen update the tests.' + : undefined; + const patchComplete = complete || lastReasoning !== undefined; + const runningPatchMessage = options.filePillTitle ? 'Updating [progress.ts](file:///workspace/src/progress.ts?vscodeLinkType=file)' + : options.linkedTitle ? 'Updating [progress.ts](file:///workspace/src/progress.ts)' : 'Updating the progress renderer...'; await renderChatWidget(context, { width: 620, height: 340, listHeight: 340, inputVisible: false, + additionalServices: options.filePillTitle ? reg => reg.defineInstance(IFileService, context.disposableStore.add(new TestFileService())) : undefined, persistentProgress: ChatProgressAnimation.Draw, persistentProgressVerbosity: verbosity, thinkingStyle: ThinkingDisplayMode.Collapsed, @@ -1757,7 +1768,7 @@ async function renderPersistentVerbosityComparison(context: ComponentFixtureCont { kind: 'tool', toolId: 'read_file', displayName: 'Read file', invocationMessage: 'Read `src/progress.ts`', complete: true }, { kind: 'tool', toolId: 'search_workspace', displayName: 'Search workspace', invocationMessage: 'Found 12 progress renderer tests', complete: true }, { kind: 'tool', toolId: 'apply_patch', displayName: 'Apply patch', invocationMessage: patchComplete ? 'Updated the progress renderer' : runningPatchMessage, complete: patchComplete }, - ...(options.reasoningLast ? [{ kind: 'thinking' as const, text: '**Checking the related tests**\nConfirm the tests cover the tool and reasoning paths.' }] : []), + ...(lastReasoning !== undefined ? [{ kind: 'thinking' as const, text: lastReasoning }] : []), ...(complete ? [{ kind: 'markdown' as const, text: 'Updated the progress renderer and checked the related tests.' }] : []), ], responseComplete: complete, @@ -2529,10 +2540,7 @@ const CODE_BLOCK_IN_LIST: IFixtureMessage[] = [ }, ]; -/** - * A request whose pasted image and file are shown as pills inline with its - * text, see `chat.inlineAttachments.enabled`, optionally in a custom chat font. - */ +/** A request with image and file pills, a slash command and text, optionally in a custom chat font. */ async function renderInlineAttachmentPills(context: ComponentFixtureContext, chatFont?: IChatWidgetFixtureOptions['chatFont']): Promise<void> { const canvas = dom.$<HTMLCanvasElement>('canvas'); canvas.width = 48; @@ -2548,15 +2556,21 @@ async function renderInlineAttachmentPills(context: ComponentFixtureContext, cha canvasContext.fillRect(6, 14, 36, 4); canvasContext.fillRect(6, 22, 18, 4); const imageBytes = Uint8Array.from(atob(canvas.toDataURL('image/png').split(',')[1]), character => character.charCodeAt(0)); + const text = 'Pasted Image /explain #file:index.ts in detail'; await renderChatWidget(context, { messages: [{ - user: 'Why does #file:index.ts look different from Pasted Image?', + user: text, + parts: [ + new ChatRequestTextPart(new OffsetRange(0, 13), new Range(1, 1, 1, 14), text.slice(0, 13)), + new ChatRequestSlashPromptPart(new OffsetRange(13, 21), new Range(1, 14, 1, 22), 'explain'), + new ChatRequestTextPart(new OffsetRange(21, text.length), new Range(1, 22, 1, text.length + 1), text.slice(21)), + ], variables: [ { kind: 'file', id: 'file:///repo/src/index.ts', name: 'index.ts', value: URI.file('/repo/src/index.ts') }, { kind: 'image', id: 'pasted-image', name: 'Pasted Image', value: imageBytes, mimeType: 'image/png', isPasted: true }, ], - assistant: [{ kind: 'markdown', text: 'Both pills should center their label vertically.' }], + assistant: [{ kind: 'markdown', text: 'Attachment pills and slash commands should be level, with their labels on the baseline of the request text.' }], }], height: 200, listHeight: 200, @@ -2838,7 +2852,9 @@ export default defineThemedFixtureGroup({ path: 'chat/widget/' }, { CompactCompleted: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Compact, true) }), ConversationStreaming: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, false) }), ConversationStreamingLinkedTitle: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, false, { linkedTitle: true }) }), + ConversationStreamingFilePillTitle: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, false, { filePillTitle: true }) }), ConversationStreamingReasoning: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, false, { reasoningLast: true }) }), + ConversationStreamingUnheadedReasoning: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, false, { unheadedReasoningLast: true }) }), ConversationCompleted: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, true) }), ConversationExpanded: defineComponentFixture({ virtualTime: { enabled: false }, render: context => renderPersistentVerbosityComparison(context, ChatProgressVerbosity.Conversation, true, { expand: true }) }), }), diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/cloudModelPicker.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/cloudModelPicker.fixture.ts index 2e5f0f3e3741..552f4b446741 100644 --- a/src/vs/workbench/test/browser/componentFixtures/chat/cloudModelPicker.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/chat/cloudModelPicker.fixture.ts @@ -3,10 +3,14 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { bufferToStream, VSBuffer } from '../../../../../base/common/buffer.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Event } from '../../../../../base/common/event.js'; +import { Disposable } from '../../../../../base/common/lifecycle.js'; import { mock } from '../../../../../base/test/common/mock.js'; +import { AccountClient } from '../../../../../platform/github/common/account/accountClient.js'; +import { ApiRequest, ApiResponse, IApiRequestProvider } from '../../../../../platform/github/common/client/request.js'; +import { parse } from '../../../../../platform/github/common/client/schema.js'; +import { GitHubAuthorizationContext } from '../../../../../platform/github/common/githubTypes.js'; import { NullLogService } from '../../../../../platform/log/common/log.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IRequestService } from '../../../../../platform/request/common/request.js'; @@ -16,39 +20,38 @@ import { withCloudSandboxDraftModelConfig } from '../../../../contrib/chat/brows import { ICloudSandboxTelemetryService } from '../../../../contrib/chat/browser/remoteAgentHost/cloudSandboxTelemetry.js'; import { IAuthenticationService } from '../../../../services/authentication/common/authentication.js'; import { IWorkbenchGitHubService } from '../../../../services/github/common/githubService.js'; -import { IUserDataProfileService } from '../../../../services/userDataProfile/common/userDataProfile.js'; +import { TestUserDataProfileService } from '../../../common/workbenchTestServices.js'; import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup, waitForFixtureCondition } from '../fixtureUtils.js'; import { renderPicker } from './tabbedModelPicker.fixture.js'; async function renderCloudPicker(context: ComponentFixtureContext, view: 'list' | 'pricing' | 'long' | 'unknown', connected = false): Promise<void> { const details = view !== 'list'; const unknownLimits = view === 'unknown'; + const requestProvider: IApiRequestProvider = { + request: async <T>(_request: ApiRequest, _signal: AbortSignal, parser?: parse.Parser<T>): Promise<ApiResponse<T | void>> => ({ + status: 200, + data: parser?.(JSON.stringify({ + data: [ + { id: 'auto', name: 'Auto', billing: { is_premium: true, multiplier: 0.9 } }, + { + id: 'cloud-model', name: 'Cloud Model', model_picker_price_category: 'medium', + billing: { + token_prices: unknownLimits + ? { batch_size: 1_000_000, input_price: 200_000_000_000, output_price: 1_000_000_000_000, cache_price: 10_000_000_000 } + : { + batch_size: 1_000_000, + default: { context_max: 272_000, input_price: 200, output_price: 1000, cache_price: 10, cache_write_price: 250 }, + long_context: { context_max: 922_000, input_price: 400, output_price: 1500, cache_price: 20, cache_write_price: 500 }, + } + }, + capabilities: { supports: { reasoning_effort: ['low', 'medium', 'high', 'xhigh', 'max'] }, limits: { max_context_window_tokens: 1_050_000 } }, + }, + ], + })), + }), + }; const api = context.disposableStore.add(new CloudSandboxApiService( - new class extends mock<IRequestService>() { - override async request() { - return { - res: { statusCode: 200, headers: {} }, - stream: bufferToStream(VSBuffer.fromString(JSON.stringify({ - data: [ - { id: 'auto', name: 'Auto', billing: { is_premium: true, multiplier: 0.9 } }, - { - id: 'cloud-model', name: 'Cloud Model', model_picker_price_category: 'medium', - billing: { - token_prices: unknownLimits - ? { batch_size: 1_000_000, input_price: 200_000_000_000, output_price: 1_000_000_000_000, cache_price: 10_000_000_000 } - : { - batch_size: 1_000_000, - default: { context_max: 272_000, input_price: 200, output_price: 1000, cache_price: 10, cache_write_price: 250 }, - long_context: { context_max: 922_000, input_price: 400, output_price: 1500, cache_price: 20, cache_write_price: 500 }, - } - }, - capabilities: { supports: { reasoning_effort: ['low', 'medium', 'high', 'xhigh', 'max'] }, limits: { max_context_window_tokens: 1_050_000 } }, - }, - ], - }))), - }; - } - }(), + new class extends mock<IRequestService>() { }(), new class extends mock<IAuthenticationService>() { override readonly onDidChangeSessions = Event.None; override readonly onDidRegisterAuthenticationProvider = Event.None; @@ -62,10 +65,12 @@ async function renderCloudPicker(context: ComponentFixtureContext, view: 'list' new class extends mock<ICloudSandboxTelemetryService>() { override reportRequest(): void { } }(), - new class extends mock<IWorkbenchGitHubService>() { }(), - new class extends mock<IUserDataProfileService>() { - override readonly onDidChangeCurrentProfile = Event.None; + new class extends mock<IWorkbenchGitHubService>() { + override async acquireAccountApiClient(authorization: GitHubAuthorizationContext) { + return new AccountClient(authorization, { rest: requestProvider, graphql: requestProvider, missionControl: requestProvider }, Disposable.None); + } }(), + new TestUserDataProfileService(), )); const catalog = await api.listModels(CancellationToken.None); const provider = context.disposableStore.add(new AgentHostLanguageModelProvider('cloud-sandbox', 'cloud-models')); diff --git a/src/vs/workbench/test/browser/componentFixtures/chat/promptTimelineGutter.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/chat/promptTimelineGutter.fixture.ts new file mode 100644 index 000000000000..60dce28240f2 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/chat/promptTimelineGutter.fixture.ts @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as DOM from '../../../../../base/browser/dom.js'; +import { PromptTimelineGutterRail } from '../../../../contrib/chat/browser/promptTimeline/promptTimelineGutterRail.js'; +import { PromptTick } from '../../../../contrib/chat/browser/promptTimeline/promptTimelineModel.js'; +import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup } from '../fixtureUtils.js'; + +function tick(requestId: string, text: string, stat?: PromptTick['stat']): PromptTick { + return { + requestId, + allRequestIds: [requestId], + text, + timestamp: 0, + count: 1, + ariaLabel: `Prompt: ${text}`, + stat, + }; +} + +function renderPromptTimelineGutter({ container, disposableStore }: ComponentFixtureContext): void { + container.classList.add('monaco-workbench', 'agent-sessions-workbench'); + container.style.width = '340px'; + container.style.height = '260px'; + container.style.position = 'relative'; + container.style.background = 'var(--vscode-editor-background)'; + + const host = DOM.append(container, DOM.$('.prompt-timeline-host')); + host.style.width = '320px'; + host.style.height = '240px'; + host.style.position = 'relative'; + + const rail = disposableStore.add(new PromptTimelineGutterRail()); + host.appendChild(rail.domNode); + rail.setHostWidth(320); + rail.setTicks([ + tick('one', 'Investigate the failure'), + tick('two', 'Do a thing', { added: 3, removed: 1, fileCount: 1 }), + tick('three', 'Do something that needs input'), + ]); + rail.setActive('two'); + rail.domNode.classList.add('revealed'); + const activeJump = rail.domNode.querySelectorAll<HTMLElement>('.prompt-timeline-gutter-row-jump')[1]; + activeJump.classList.add('hovered'); +} + +export default defineThemedFixtureGroup({ path: 'chat/promptTimelineGutter/' }, { + ActivePromptHover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The active prompt row is pointer-hovered in the Prompt Timeline gutter. In high contrast themes, a dashed active-contrast boundary keeps the hover visible over the active-row state.'], + render: renderPromptTimelineGutter, + }), +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/editor/tabs.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/editor/tabs.fixture.ts index f20e459745ba..cbb36e48872b 100644 --- a/src/vs/workbench/test/browser/componentFixtures/editor/tabs.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/editor/tabs.fixture.ts @@ -672,6 +672,9 @@ function createDensityFixtures() { } function createLayoutFixtures() { + const narrowFixedEditors = ['a.ts', 'b.ts', 'c.ts'].map((name, index) => ({ + resource: file(`/project/${name}`), pinned: true, active: index === 1, + })); return { ActionsHidden: defineComponentFixture({ render: render(true, { partOptions: { tabActionCloseVisibility: false } }), @@ -722,6 +725,28 @@ function createLayoutFixtures() { render: render(true, { partOptions: { tabSizing: 'fixed', tabSizingFixedMinWidth: 120, tabSizingFixedMaxWidth: 120 }, editors: longLabelEditorSpecs(), width: 520 }), expectedVisualDescriptions: ['Fixed-size long labels use equal tab widths, real ellipses, and stable action columns.'], }), + FixedWidthMaximum: defineComponentFixture({ + fileIconTheme: 'none', + themes: ['dark'], + additionalThemes: ['light2026', 'darkHighContrast'], + render: render(true, { + editors: narrowFixedEditors, + partOptions: { tabSizing: 'fixed', tabSizingFixedMinWidth: 50, tabSizingFixedMaxWidth: 60, editorActionsLocation: 'hidden' }, + width: 420, + }), + expectedVisualDescriptions: ['Fixed Connected tabs honor a maximum below 80px while keeping the active Close action inside its tab.'], + }), + FixedWidthMinimum: defineComponentFixture({ + fileIconTheme: 'none', + themes: ['dark'], + additionalThemes: ['light2026', 'darkHighContrast'], + render: render(true, { + editors: narrowFixedEditors, + partOptions: { tabSizing: 'fixed', tabSizingFixedMinWidth: 50, tabSizingFixedMaxWidth: 160, editorActionsLocation: 'hidden' }, + width: 150, + }), + expectedVisualDescriptions: ['Fixed Connected tabs shrink to the configured minimum before overflowing a narrow editor group.'], + }), LongNamesShrink: defineComponentFixture({ render: render(true, { partOptions: { tabSizing: 'shrink' }, editors: longLabelEditorSpecs(), width: 520 }), expectedVisualDescriptions: ['Shrink-sized long labels ellipsize while preserving extensions and action targets.'], diff --git a/src/vs/workbench/test/browser/componentFixtures/fixtureUtils.ts b/src/vs/workbench/test/browser/componentFixtures/fixtureUtils.ts index 6173ac76a8b1..d6c4c11dc56d 100644 --- a/src/vs/workbench/test/browser/componentFixtures/fixtureUtils.ts +++ b/src/vs/workbench/test/browser/componentFixtures/fixtureUtils.ts @@ -962,13 +962,13 @@ export function registerWorkbenchServices(registration: ServiceRegistration): vo setImpl: () => ({ dispose: () => { } }), }); - // Workspace trust stubs so chat-input fixtures can instantiate the model - // picker (ModelPickerWidget reads workspace trust to detect Restricted Mode). - // Reports the workspace as trusted so the picker renders normally. + // Chat-input fixtures use trusted workspace and folder state. registration.defineInstance(IWorkspaceTrustManagementService, new class extends mock<IWorkspaceTrustManagementService>() { override onDidChangeTrust = Event.None; + override onDidChangeTrustedFolders = Event.None; override readonly workspaceTrustInitialized = Promise.resolve(); override isWorkspaceTrusted() { return true; } + override async getUriTrustInfo(uri: URI) { return { uri, trusted: true }; } }()); registration.defineInstance(IWorkspaceTrustRequestService, new class extends mock<IWorkspaceTrustRequestService>() { override async requestWorkspaceTrust() { return true; } diff --git a/src/vs/workbench/test/browser/componentFixtures/scm/scmFixtureUtils.ts b/src/vs/workbench/test/browser/componentFixtures/scm/scmFixtureUtils.ts new file mode 100644 index 000000000000..363f76f53177 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/scm/scmFixtureUtils.ts @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/** + * Maps the Git decoration colors to built-in colors of a similar hue, because the Git extension contributes them. + */ +export function setGitDecorationColors(container: HTMLElement): void { + container.style.setProperty('--vscode-gitDecoration-modifiedResourceForeground', 'var(--vscode-editorWarning-foreground)'); + container.style.setProperty('--vscode-gitDecoration-addedResourceForeground', 'var(--vscode-charts-green)'); + container.style.setProperty('--vscode-gitDecoration-untrackedResourceForeground', 'var(--vscode-charts-green)'); + container.style.setProperty('--vscode-gitDecoration-deletedResourceForeground', 'var(--vscode-editorError-foreground)'); + container.style.setProperty('--vscode-gitDecoration-renamedResourceForeground', 'var(--vscode-charts-yellow)'); +} diff --git a/src/vs/workbench/test/browser/componentFixtures/scm/scmResourceDecorations.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/scm/scmResourceDecorations.fixture.ts index dcab7566e83d..506111f0e590 100644 --- a/src/vs/workbench/test/browser/componentFixtures/scm/scmResourceDecorations.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/scm/scmResourceDecorations.fixture.ts @@ -4,13 +4,17 @@ *--------------------------------------------------------------------------------------------*/ import { $, append } from '../../../../../base/browser/dom.js'; +import { ITreeNode } from '../../../../../base/browser/ui/tree/tree.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Event } from '../../../../../base/common/event.js'; +import { FuzzyScore } from '../../../../../base/common/filters.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import * as resourceUtils from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; +import { Range } from '../../../../../editor/common/core/range.js'; +import { StructuralDiffClassification, SymbolKind } from '../../../../../editor/common/languages.js'; import { FileKind } from '../../../../../platform/files/common/files.js'; import { UnthemedProductIconTheme } from '../../../../../platform/theme/browser/iconsStyleSheet.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; @@ -18,18 +22,25 @@ import { TestThemeService } from '../../../../../platform/theme/test/common/test import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../../browser/labels.js'; import '../../../../contrib/scm/browser/media/scm.css'; +import { SCMStructuralDiffRenderer } from '../../../../contrib/scm/browser/scmStructuralDiffRenderer.js'; +import { ISCMResource } from '../../../../contrib/scm/common/scm.js'; +import { SCMStructuralDiffElement, SCMStructuralDiffNode } from '../../../../contrib/scm/common/scmStructuralDiff.js'; import { DecorationsService } from '../../../../services/decorations/browser/decorationsService.js'; import { IDecorationData, IDecorationsProvider, IDecorationsService } from '../../../../services/decorations/common/decorations.js'; import { INotebookDocumentService } from '../../../../services/notebook/common/notebookDocumentService.js'; import { ITextFileService } from '../../../../services/textfile/common/textfiles.js'; import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../fixtureUtils.js'; +import { setGitDecorationColors } from './scmFixtureUtils.js'; interface SCMDecorationFixture { readonly resource: URI; readonly fileKind: FileKind; + readonly structuralChange?: 'modified' | 'added' | 'deleted' | 'renamed'; } const modifiedResource = URI.file('/workspace/modified.ts'); +const diagnosticsResource = URI.file('/workspace/modified-with-problems.ts'); +const addedResource = URI.file('/workspace/added.ts'); const untrackedResource = URI.file('/workspace/untracked.ts'); const deletedResource = URI.file('/workspace/deleted.ts'); const renamedResource = URI.file('/workspace/renamed.ts'); @@ -46,8 +57,18 @@ const fixtureResources: readonly SCMDecorationFixture[] = [ { resource: bubbledParentResource, fileKind: FileKind.FOLDER }, ]; +const mixedFixtureResources: readonly SCMDecorationFixture[] = [ + { resource: modifiedResource, fileKind: FileKind.FILE, structuralChange: 'modified' }, + { resource: diagnosticsResource, fileKind: FileKind.FILE, structuralChange: 'modified' }, + { resource: addedResource, fileKind: FileKind.FILE, structuralChange: 'added' }, + { resource: deletedResource, fileKind: FileKind.FILE, structuralChange: 'deleted' }, + { resource: renamedResource, fileKind: FileKind.FILE, structuralChange: 'renamed' }, +]; + const fixtureDecorations = new Map<string, IDecorationData>([ [modifiedResource.toString(), { letter: 'M', tooltip: 'Modified', color: 'gitDecoration.modifiedResourceForeground' }], + [diagnosticsResource.toString(), { letter: 'M', tooltip: 'Modified', color: 'gitDecoration.modifiedResourceForeground' }], + [addedResource.toString(), { letter: 'A', tooltip: 'Added', color: 'gitDecoration.addedResourceForeground' }], [untrackedResource.toString(), { letter: 'U', tooltip: 'Untracked', color: 'gitDecoration.untrackedResourceForeground' }], [deletedResource.toString(), { letter: 'D', tooltip: 'Deleted', color: 'gitDecoration.deletedResourceForeground', strikethrough: true }], [renamedResource.toString(), { letter: 'R', tooltip: 'Renamed', color: 'gitDecoration.renamedResourceForeground' }], @@ -62,7 +83,23 @@ export default defineThemedFixtureGroup({ path: 'scm/' }, { expectedVisualDescriptions: [ 'Six Source Control resource rows show modified, untracked, deleted, renamed, read-only, and contains-changes states. The M, U, D, and R text decorations use the same text size, each is centered in an equal-width box, and their centers form one vertical column. The deleted filename is struck through and each decoration retains its Git theme color. The read-only lock and bubbled-child glyph retain their existing icon size and weight instead of using the text-badge typography.', ], - render: renderResourceDecorations, + render: context => renderResourceDecorations(context, fixtureResources, 280), + }), + ResourceAndStructuralDecorations: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'Five file rows each have an indented structural child. Single M, A, D, and R status letters on file and structural rows use the same text size and dimmed opacity, each is centered in an equal-width box, and their centers form one vertical column. The wider 5, M diagnostic badge ends at the same right edge and extends to the left, so its M sits slightly right of that column. Implementation annotations stay before the M on structural rows, while renames have R without an annotation. Filenames, symbol icons, and theme colors are preserved.', + ], + render: context => renderResourceDecorations(context, mixedFixtureResources, 360), + }), + ResourceAndStructuralDecorationsNarrow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'A narrow Source Control list shows files and indented structural children. Single M, A, D, and R status letters remain fully visible, each centered in an equal-width box, and their centers form one vertical column. The 5, M diagnostic badge retains its count, ends at the same right edge, and extends to the left. Long file and symbol names truncate with ellipses before the annotations and badges.', + ], + render: context => renderResourceDecorations(context, mixedFixtureResources, 220), }), }); @@ -75,18 +112,21 @@ function registerFixtureDecorations(decorationsService: IDecorationsService, dis }, }; disposableStore.add(decorationsService.registerDecorationsProvider(provider)); + disposableStore.add(decorationsService.registerDecorationsProvider({ + label: 'SCM Fixture Problems', + onDidChange: Event.None, + provideDecorations: resource => resourceUtils.isEqual(resource, diagnosticsResource) + ? { letter: '5', tooltip: '5 Problems', weight: 10, color: 'editorError.foreground' } + : undefined, + })); } -function renderResourceDecorations({ container, disposableStore, theme, fileIconTheme }: ComponentFixtureContext): void { +function renderResourceDecorations({ container, disposableStore, theme, fileIconTheme }: ComponentFixtureContext, resources: readonly SCMDecorationFixture[], width: number): void { container.classList.add('scm-view'); - container.style.width = '280px'; + container.style.width = `${width}px`; container.style.padding = 'var(--vscode-spacing-size120)'; - container.style.fontFamily = 'var(--vscode-font-family)'; container.style.fontSize = 'var(--vscode-fontSize-body1)'; - container.style.setProperty('--vscode-gitDecoration-modifiedResourceForeground', 'var(--vscode-editorWarning-foreground)'); - container.style.setProperty('--vscode-gitDecoration-untrackedResourceForeground', 'var(--vscode-charts-green)'); - container.style.setProperty('--vscode-gitDecoration-deletedResourceForeground', 'var(--vscode-editorError-foreground)'); - container.style.setProperty('--vscode-gitDecoration-renamedResourceForeground', 'var(--vscode-charts-yellow)'); + setGitDecorationColors(container); const instantiationService = createEditorServices(disposableStore, { colorTheme: theme, @@ -113,14 +153,23 @@ function renderResourceDecorations({ container, disposableStore, theme, fileIcon decorationsService.getDecoration(bubbledChildResource, false)?.dispose(); const resourceLabels = disposableStore.add(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); + const structuralRenderer = instantiationService.createInstance(SCMStructuralDiffRenderer); const list = append(container, $('.monaco-list')); - - for (const fixtureResource of fixtureResources) { + // Structural children need tree rows for indentation; plain resource lists keep flat list rows. + const treeRows = resources.some(resource => resource.structuralChange); + const createRow = (nested: boolean) => { const row = append(list, $('.monaco-list-row')); row.style.position = 'relative'; row.style.height = '22px'; - - const resource = append(row, $('.resource')); + if (!treeRows) { + return row; + } + const contents = append(row, $('.monaco-tl-contents')); + contents.style.paddingLeft = nested ? 'var(--vscode-spacing-size160)' : ''; + return contents; + }; + for (const fixtureResource of resources) { + const resource = append(createRow(false), $('.resource')); const name = append(resource, $('.name')); const label = resourceLabels.create(name); label.setFile(fixtureResource.resource, { @@ -128,5 +177,30 @@ function renderResourceDecorations({ container, disposableStore, theme, fileIcon fileDecorations: { colors: false, badges: true }, hidePath: true, }); + if (fixtureResource.structuralChange) { + const scmResource = new class extends mock<ISCMResource>() { + override readonly sourceUri = fixtureResource.resource; + }; + const range = new Range(1, 1, 3, 1); + const item = { name: 'calculateWithValidation', kind: SymbolKind.Method, range }; + const element: SCMStructuralDiffNode = { + type: 'structuralDiff', id: fixtureResource.resource.toString(), generation: 1, order: 0, resource: scmResource, parent: scmResource, children: [], + node: { + id: 'method', + originalItem: fixtureResource.structuralChange === 'added' ? undefined + : fixtureResource.structuralChange === 'renamed' ? { ...item, name: 'calculate' } : item, + modifiedItem: fixtureResource.structuralChange === 'deleted' ? undefined : item, + originalChanges: [], + modifiedChanges: fixtureResource.structuralChange === 'modified' + ? [{ textChangeIndex: 0, range, classification: StructuralDiffClassification.Implementation }] : [], + children: [], + }, + }; + const template = disposableStore.add(structuralRenderer.renderTemplate(createRow(true))); + structuralRenderer.renderElement(new class extends mock<ITreeNode<SCMStructuralDiffElement, FuzzyScore>>() { + override readonly element = element; + override readonly filterData = FuzzyScore.Default; + }, 0, template); + } } } diff --git a/src/vs/workbench/test/browser/componentFixtures/scm/scmStructuralDiff.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/scm/scmStructuralDiff.fixture.ts new file mode 100644 index 000000000000..45d6f759dca4 --- /dev/null +++ b/src/vs/workbench/test/browser/componentFixtures/scm/scmStructuralDiff.fixture.ts @@ -0,0 +1,162 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { ObjectTree } from '../../../../../base/browser/ui/tree/objectTree.js'; +import { ITreeElement } from '../../../../../base/browser/ui/tree/tree.js'; +import { FuzzyScore } from '../../../../../base/common/filters.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { Range } from '../../../../../editor/common/core/range.js'; +import { StructuralDiffClassification, StructuralDiffNode, SymbolKind } from '../../../../../editor/common/languages.js'; +import { getListStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; +import { SCMStructuralDiffRenderer } from '../../../../contrib/scm/browser/scmStructuralDiffRenderer.js'; +import { ISCMResource } from '../../../../contrib/scm/common/scm.js'; +import { SCMStructuralDiffElement, SCMStructuralDiffNode, SCMStructuralDiffStatus, getSCMStructuralDiffAriaLabel, getSCMStructuralDiffLabel } from '../../../../contrib/scm/common/scmStructuralDiff.js'; +import '../../../../browser/parts/views/media/views.css'; +import '../../../../contrib/scm/browser/media/scm.css'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup } from '../fixtureUtils.js'; +import { setGitDecorationColors } from './scmFixtureUtils.js'; + +export default defineThemedFixtureGroup({ path: 'scm/' }, { + StructuralChanges: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'A class named Calculator contains a changed calculate method, an added newMethod, and a deleted oldMethod. Only the expanded Calculator class has a twistie. The methods and the warning row cannot expand, so like files next to folders in the Explorer they have no twistie, and their icons start in the twistie column. The changed method has a muted impl annotation without brackets aligned on the right, immediately before its M status marker. The signature stays beside the method name. The class and method icons use their respective Outline symbol theme colors, with normal Source Control row spacing. The single-letter M, A, and D status markers align on the right, using the corresponding Git decoration theme colors, dimmed like file badges. Added/deleted methods have no change-part annotation, and the unchanged Calculator container has neither an annotation nor a status marker. A warning row below the class says Partial structural changes.', + ], + render: context => renderStructuralChanges(context), + }), + StructuralChangesSelected: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'The changed calculate method is selected in a focused list. Like file badges in selected rows, its M status marker uses the selection foreground together with its name, signature, and impl annotation, while the A and D markers of the other methods keep their Git decoration colors.', + ], + render: context => renderStructuralChanges(context, { selected: true }), + }), + StructuralChangesNarrow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'A narrow Source Control symbol tree keeps its icons and indentation aligned. The long calculate method name and signature truncate with an ellipsis instead of overflowing, while the right-aligned impl annotation without brackets and M status marker remain fully visible. Right-aligned A and D status markers remain visible for added and deleted methods, and a partial-results warning appears below the class.', + ], + render: context => renderStructuralChanges(context, { width: 220 }), + }), + StructuralDeclarationChanges: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'The changed calculate method has a muted decl annotation without brackets aligned on the right, immediately before its M status marker. Its name and signature remain on the left. Added/deleted methods and the unchanged Calculator container have no change-part annotation.', + ], + render: context => renderStructuralChanges(context, { classifications: [StructuralDiffClassification.Header] }), + }), + StructuralDeclarationAndImplementationChanges: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'The changed calculate method has a muted decl+impl annotation without brackets aligned on the right, immediately before its M status marker. Its name and signature remain on the left. Added/deleted methods and the unchanged Calculator container have no change-part annotation.', + ], + render: context => renderStructuralChanges(context, { classifications: [StructuralDiffClassification.Header, StructuralDiffClassification.Implementation] }), + }), + StructuralRename: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'The renamed calculate method has a right-aligned R status marker retaining the modified-resource theme color, without a change annotation. The displayed name is calculate, while the hover and accessible label identify its previous name compute. Added/deleted methods and the unchanged Calculator container have no change-part annotation.', + ], + render: context => renderStructuralChanges(context, { classifications: [StructuralDiffClassification.Header], originalName: 'compute' }), + }), + StructuralLoadFailures: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: [ + 'Two rows say Unable to load structural changes and Structural changes took too long to load. Each has the same warning icon as the partial-results row, in the regular foreground color, and neither row has a twistie, an annotation, or a status marker.', + ], + render: context => renderStructuralDiffTree(context, 360, [createStatus('error', 0), createStatus('timedOut', 1)]), + }), +}); + +const resource = new class extends mock<ISCMResource>() { + override readonly sourceUri = URI.file('/workspace/calculator.ts'); +}; + +function createStatus(status: SCMStructuralDiffStatus['status'], order: number): SCMStructuralDiffStatus { + return { type: 'structuralDiffStatus', id: status, status, generation: 1, order, resource, parent: resource }; +} + +interface StructuralChangesOptions { + readonly width?: number; + readonly classifications?: readonly StructuralDiffClassification[]; + readonly originalName?: string; + /** Whether the changed method is selected in a focused list. */ + readonly selected?: boolean; +} + +function renderStructuralChanges(context: ComponentFixtureContext, { width = 360, classifications = [StructuralDiffClassification.Implementation], originalName, selected = false }: StructuralChangesOptions = {}): void { + const range = new Range(1, 1, 20, 1); + const members: SCMStructuralDiffNode[] = []; + const nodes: StructuralDiffNode[] = []; + const parent: SCMStructuralDiffNode = { + type: 'structuralDiff', id: 'class', generation: 1, order: 0, resource, parent: resource, children: members, + node: { + id: 'class', + originalItem: { name: 'Calculator', kind: SymbolKind.Class, range }, + modifiedItem: { name: 'Calculator', kind: SymbolKind.Class, range }, + originalChanges: [], modifiedChanges: [], children: nodes, + }, + }; + for (const [order, status] of ['changed', 'added', 'deleted'].entries()) { + const name = status === 'changed' ? width < 300 ? 'calculateWithAdditionalValidation' : 'calculate' : status === 'added' ? 'newMethod' : 'oldMethod'; + const item = { name, kind: SymbolKind.Method, range, detail: status === 'changed' ? '(value: number): number' : undefined }; + const node: StructuralDiffNode = { + id: status, + originalItem: status === 'added' ? undefined : status === 'changed' && originalName ? { ...item, name: originalName } : item, + modifiedItem: status === 'deleted' ? undefined : item, + originalChanges: [], + modifiedChanges: status === 'changed' ? classifications.map((classification, index) => ({ + textChangeIndex: 0, range: new Range(index + 3, 1, index + 3, 12), classification, + })) : [], + children: [], + }; + nodes.push(node); + members.push({ type: 'structuralDiff', id: status, generation: 1, order, resource, parent, node, children: [] }); + } + renderStructuralDiffTree(context, width, [parent, createStatus('incomplete', 1)], selected ? members[0] : undefined); +} + +function renderStructuralDiffTree(context: ComponentFixtureContext, width: number, elements: readonly SCMStructuralDiffElement[], selection?: SCMStructuralDiffElement): void { + const { container, disposableStore, theme, fileIconTheme } = context; + const instantiationService = createEditorServices(disposableStore, { colorTheme: theme }); + // The SCM view in list mode hides the twisties of rows that cannot expand when the file icon theme has file icons + container.classList.add('scm-view', 'file-icon-themable-tree'); + container.classList.toggle('align-icons-and-twisties', fileIconTheme.hasFileIcons); + container.style.width = `${width}px`; + container.style.fontSize = 'var(--vscode-fontSize-body1)'; + setGitDecorationColors(container); + const renderer = instantiationService.createInstance(SCMStructuralDiffRenderer); + const tree = disposableStore.add(new ObjectTree<SCMStructuralDiffElement, FuzzyScore>('SCM structural diff fixture', container, { + getHeight: () => 22, + getTemplateId: () => SCMStructuralDiffRenderer.TEMPLATE_ID, + }, [renderer], { + identityProvider: { getId: element => element.id }, + keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: getSCMStructuralDiffLabel }, + accessibilityProvider: { getWidgetAriaLabel: () => 'Structural changes', getAriaLabel: getSCMStructuralDiffAriaLabel }, + horizontalScrolling: false, + })); + tree.style(getListStyles({})); + // As in the SCM view, only symbols with children can expand + const toTreeElement = (element: SCMStructuralDiffElement): ITreeElement<SCMStructuralDiffElement> => ({ + element, + children: element.type === 'structuralDiff' ? element.children.map(toTreeElement) : [], + }); + tree.setChildren(null, elements.map(toTreeElement)); + container.style.height = `${tree.contentHeight}px`; + tree.layout(tree.contentHeight, width); + if (selection) { + tree.setFocus([selection]); + tree.setSelection([selection]); + context.focus({ focus: () => tree.domFocus() }); + } +} diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts index 68676d03bd4a..2100a49a4d3e 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts @@ -67,7 +67,7 @@ import { CustomizationMarketplaceInstallService } from '../../../../contrib/chat import { ICopilotConnector, ICopilotConnectorsService } from '../../../../contrib/chat/browser/aiCustomization/copilotConnectorsService.js'; import { ICopilotExtensionsService } from '../../../../contrib/chat/browser/aiCustomization/copilotExtensionsService.js'; import { EmbeddedConnectorDetail } from '../../../../contrib/chat/browser/aiCustomization/embeddedConnectorDetail.js'; -import { ICustomizationHarnessService, ICustomizationItem, ICustomizationItemProvider, ICustomizationMarketplaceManagementProvider, ICustomizationMcpServerCompatibility, ICustomizationMcpServerMigrationProvider, ICustomizationSourceFolder, IHarnessDescriptor, createVSCodeHarnessDescriptor } from '../../../../contrib/chat/common/customizationHarnessService.js'; +import { ICustomizationHarnessService, ICustomizationItem, ICustomizationItemProvider, ICustomizationMarketplaceManagementProvider, ICustomizationMcpServerCompatibility, ICustomizationMcpServerMigrationProvider, ICustomizationOrganizationControl, ICustomizationSourceFolder, IHarnessDescriptor, createVSCodeHarnessDescriptor } from '../../../../contrib/chat/common/customizationHarnessService.js'; import { IChatSessionsService } from '../../../../contrib/chat/common/chatSessionsService.js'; import { getChatSessionType, LocalChatSessionUri } from '../../../../contrib/chat/common/model/chatUri.js'; import { CustomizationMigrationType, ICustomizationMigrationService, IMcpServerCustomizationMigrationCandidate } from '../../../../contrib/chat/common/promptSyntax/service/customizationMigrationService.js'; @@ -102,9 +102,10 @@ import { EmbeddedAgentPluginDetail } from '../../../../contrib/chat/browser/aiCu import { AgentPluginItemKind, IAgentPluginItem } from '../../../../contrib/chat/browser/agentPluginEditor/agentPluginItems.js'; import { ContributionEnablementState } from '../../../../contrib/chat/common/enablement.js'; import { AICustomizationManagementEditorInput } from '../../../../contrib/chat/browser/aiCustomization/aiCustomizationManagementEditorInput.js'; -import { IConfigurationChangeEvent, IConfigurationService, IConfigurationValue } from '../../../../../platform/configuration/common/configuration.js'; +import { IConfigurationChangeEvent, IConfigurationOverrides, IConfigurationService, IConfigurationValue } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; -import { mcpAccessConfig, McpAccessValue } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { mcpAccessConfig, McpAccessValue, mcpAllowedServersConfig } from '../../../../../platform/mcp/common/mcpManagement.js'; +import { COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG, COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG, COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG } from '../../../../../platform/policy/common/copilotManagedSettings.js'; import { IMcpGalleryManifestService, McpGalleryManifestStatus } from '../../../../../platform/mcp/common/mcpGalleryManifest.js'; import { McpServerType } from '../../../../../platform/mcp/common/mcpPlatformTypes.js'; import { McpResourceFormat } from '../../../../../platform/mcp/common/mcpWorkspaceConfiguration.js'; @@ -138,11 +139,34 @@ import '../../../../contrib/chat/browser/aiCustomization/customizationMarketplac import { ISecretStorageService } from '../../../../../platform/secrets/common/secrets.js'; import '../../../../contrib/chat/browser/aiCustomization/copilotCanvases.contribution.js'; import { TestSecretStorageService } from '../../../../../platform/secrets/test/common/testSecretStorageService.js'; +import { createDecorator } from '../../../../../platform/instantiation/common/instantiation.js'; // ============================================================================ // Mock helpers // ============================================================================ +/** Describes the badge of the contributed Extensions section in a fixture. */ +interface IFixtureExtensionsSectionBadge { + readonly _serviceBrand: undefined; + readonly badge: IObservable<string | undefined>; +} + +const IFixtureExtensionsSectionBadge = createDecorator<IFixtureExtensionsSectionBadge>('fixtureExtensionsSectionBadge'); + +// The explorer mounts the fixtures of a folder together, and they share the section registry, which returns the first +// contribution of a section. So the Extensions section is registered once, and each fixture supplies its badge with its +// own services. +aiCustomizationManagementSectionRegistry.register({ + id: AICustomizationManagementSection.Extensions, + label: 'Extensions', + icon: Codicon.extensions, + description: 'Choose which installed extensions run in the Agents window.', + separatorBefore: true, + supportsHarness: () => true, + getBadge: accessor => accessor.get(IFixtureExtensionsSectionBadge).badge, + create: () => ({ dispose: () => { } }), +}); + const userHome = URI.file('/home/dev'); const BUILTIN_STORAGE = 'builtin'; @@ -183,6 +207,8 @@ interface IFixtureFile { readonly applyTo?: string; readonly extensionId?: string; readonly extensionDisplayName?: string; + /** Set when the user's organization manages this customization. */ + readonly organizationControl?: ICustomizationOrganizationControl; } function createMockEditorGroup(): IEditorGroup { @@ -251,8 +277,12 @@ interface IFixtureAgentHostPlugin { readonly name: string; readonly description: string; readonly scope: AICustomizationScope; + readonly status?: ICustomizationItem['status']; + readonly statusMessage?: string; /** Organization that requires the plugin. */ readonly organization?: string; + readonly enabled?: boolean; + readonly organizationControl?: ICustomizationOrganizationControl; } function createFixtureAgentHostItemProvider(files: readonly IFixtureFile[], remoteClientSkillName?: string, plugins: readonly IFixtureAgentHostPlugin[] = []): ICustomizationItemProvider { @@ -268,6 +298,10 @@ function createFixtureAgentHostItemProvider(files: readonly IFixtureFile[], remo groupKey: 'remote-host', scope: plugin.scope, origin: plugin.organization ? { kind: 'account', label: plugin.organization } : undefined, + status: plugin.status, + statusMessage: plugin.statusMessage, + enabled: plugin.enabled, + organizationControl: plugin.organizationControl, extensionId: undefined, pluginUri: undefined, })); @@ -282,6 +316,7 @@ function createFixtureAgentHostItemProvider(files: readonly IFixtureFile[], remo : file.type === PromptsType.skill && file.name === remoteClientSkillName ? 'remote-client' : 'remote-host', extensionId: file.extensionId, pluginUri: undefined, + organizationControl: file.organizationControl, }))]; }, async provideSourceFolders(_sessionResource, type): Promise<readonly ICustomizationSourceFolder[]> { @@ -745,6 +780,22 @@ const reconciledConnectorMcpServers: FixtureAgentHostMcpServer[] = [ { ...activeSessionMcpServers[1], id: 'session/github-copilot-connector-94d26095770df60673dd', name: 'github-copilot-connector-94d26095770df60673dd', displayName: 'Azure Data Explorer', source: 'managed', sourceUri: undefined }, ]; +// Organization managed-settings states for the agent-host harness. +const organizationManagedMcpServers: FixtureAgentHostMcpServer[] = [ + { ...activeSessionMcpServers[0], id: 'session/contoso-tickets', name: 'contoso-tickets', displayName: 'Contoso Tickets', source: 'managed', sourceUri: undefined }, + { ...activeSessionMcpServers[0], id: 'session/contoso-docs', name: 'contoso-docs', displayName: 'Contoso Docs', source: 'managed', sourceUri: undefined }, + { ...activeSessionMcpServers[0] }, + { ...activeSessionMcpServers[0], id: 'mcp-top-level:fixture:session:GitHub', name: 'GitHub' }, +]; + +const organizationManagedHookFiles: IFixtureFile[] = [ + { uri: URI.file('/home/dev/.copilot/managed/hooks/audit-tool-calls.json'), storage: PromptsStorage.user, type: PromptsType.hook, name: 'Audit Tool Calls', description: 'Record every tool call for compliance', organizationControl: { requiredEnabled: true } }, + { uri: URI.file('/home/dev/.copilot/managed/hooks/block-secrets.json'), storage: PromptsStorage.user, type: PromptsType.hook, name: 'Block Secrets', description: 'Stop prompts that contain credentials', organizationControl: { requiredEnabled: true } }, +]; + + +const organizationPluginOnlyPolicy: Record<string, unknown> = { [COPILOT_STRICT_PLUGIN_ONLY_CUSTOMIZATION_CONFIG]: true }; + const allStateMcpServers: FixtureAgentHostMcpServer[] = [ { ...activeSessionMcpServers[0] }, { ...activeSessionMcpServers[0], id: 'mcp-top-level:fixture:session:PostgreSQL', name: 'PostgreSQL', status: McpServerStatus.Error, state: { kind: McpServerStatus.Error, error: { errorType: 'fixture', message: 'Connection refused at localhost:5432. Check that the database is running before starting this server again.' } } }, @@ -1286,6 +1337,24 @@ interface IRenderEditorOptions { readonly pluginMarketplaceMigration?: boolean; readonly pluginMarketplaceMigrationOnly?: boolean; readonly pluginMarketplaceMigrationDeselected?: boolean; + /** Describes the badge of the contributed Extensions section, which shows none unless given. */ + readonly extensionsSectionBadge?: string; + /** Settings whose values come from organization policy. */ + readonly policyConfiguration?: Record<string, unknown>; + /** Adds local plugins that organization policy requires or blocks. */ + readonly organizationManagedLocalPlugins?: boolean; +} + +/** Reports the given settings as organization policy values. */ +class PolicyTestConfigurationService extends TestConfigurationService { + constructor(private readonly policy: Record<string, unknown>, configuration: Record<string, unknown>) { + super({ ...configuration, ...policy }); + } + + override inspect<T>(key: string, overrides?: IConfigurationOverrides): IConfigurationValue<T> { + const value = super.inspect<T>(key, overrides); + return Object.hasOwn(this.policy, key) ? { ...value, userValue: undefined, userLocalValue: undefined, policyValue: this.policy[key] as T } : value; + } } // ============================================================================ @@ -1470,9 +1539,15 @@ async function renderEditor(ctx: ComponentFixtureContext, options: IRenderEditor const requiredPluginResource = customizationMarketplaceResources.find(resource => resource.identifier === 'example/figma-plugin')!; const requiredPluginUri = URI.file('/user/plugins/figma-plugin'); const requiredPluginTarget: CustomizationMarketplaceInstallationTarget = { kind: 'plugin', uri: requiredPluginUri }; - const fixturePlugins = options.customizationMarketplaceInstallationState === 'requiredPlugin' - ? [...installedPlugins, makeInstalledPlugin('Figma', requiredPluginUri, true, false, undefined, true)] - : installedPlugins; + const fixturePlugins = [ + ...(options.customizationMarketplaceInstallationState === 'requiredPlugin' + ? [...installedPlugins, makeInstalledPlugin('Figma', requiredPluginUri, true, false, undefined, true)] + : installedPlugins), + ...(options.organizationManagedLocalPlugins ? [ + makeInstalledPlugin('Contoso Compliance', URI.file('/workspace/.copilot/plugins/contoso-compliance'), true, false, undefined, true), + makeInstalledPlugin('Unapproved Deploy', URI.file('/workspace/.copilot/plugins/unapproved-deploy'), false, true), + ] : []), + ]; if (options.customizationMarketplaceInstallationState === 'requiredPlugin') { customizationMarketplaceInstallStates.set(getCustomizationMarketplaceResourceKey(requiredPluginResource), { kind: 'installed', target: requiredPluginTarget }); } @@ -1499,7 +1574,7 @@ async function renderEditor(ctx: ComponentFixtureContext, options: IRenderEditor const harnessService = createMockHarnessService(options.sessionResource, availableHarnesses); const agentFeedbackService = createMockAgentFeedbackService(); const codeReviewService = createMockCodeReviewService(); - const configurationService = marketplaceConfiguration = new TestConfigurationService({ + const configurationService = marketplaceConfiguration = new PolicyTestConfigurationService(options.policyConfiguration ?? {}, { [ChatConfiguration.ChatCustomizationsStructuredPreviewEnabled]: true, [ChatConfiguration.ChatCustomizationsMigrationEnabled]: true, [CustomizationMarketplaceConfiguration.CopilotConnectorsEnabled]: options.copilotConnectorsEnabled ?? false, @@ -1513,6 +1588,7 @@ async function renderEditor(ctx: ComponentFixtureContext, options: IRenderEditor const sourceEnabled = () => configurationService.getValue<boolean>(CustomizationMarketplaceConfiguration.MarketplaceEnabled) === true; ctx.disposableStore.add({ dispose: () => configurationService.onDidChangeConfigurationEmitter.dispose() }); registerWorkbenchServices(reg); + reg.defineInstance(IFixtureExtensionsSectionBadge, { _serviceBrand: undefined, badge: constObservable(options.extensionsSectionBadge) }); if (options.migrationConfirmation) { reg.defineInstance(IDialogService, new class extends mock<IDialogService>() { override confirm(confirmation: IConfirmation): Promise<IConfirmationResult> { @@ -2832,6 +2908,7 @@ async function renderMcpBrowseMode(ctx: ComponentFixtureContext): Promise<void> additionalServices: (reg) => { registerWorkbenchServices(reg); reg.define(IListService, ListService); + reg.defineInstance(IProductService, new class extends mock<IProductService>() { }()); reg.defineInstance(IMcpGalleryManifestService, createMockMcpGalleryManifestService()); reg.defineInstance(ICustomizationMarketplaceInstallService, createEmptyCustomizationMarketplaceInstallService()); reg.defineInstance(ICustomizationMarketplaceService, createEmptyCustomizationMarketplaceService()); @@ -3133,6 +3210,7 @@ function renderMcpDisabled(ctx: ComponentFixtureContext, byPolicy: boolean): voi additionalServices: (reg) => { registerWorkbenchServices(reg); reg.define(IListService, ListService); + reg.defineInstance(IProductService, new class extends mock<IProductService>() { }()); reg.defineInstance(IMcpGalleryManifestService, createMockMcpGalleryManifestService()); reg.defineInstance(ICustomizationMarketplaceInstallService, createEmptyCustomizationMarketplaceInstallService()); reg.defineInstance(ICustomizationMarketplaceService, createEmptyCustomizationMarketplaceService()); @@ -3768,36 +3846,25 @@ export default defineThemedFixtureGroup({ path: 'chat/aiCustomizations/' }, { // Sessions variant whose contributed section shows a badge in the navigation list. SessionsContributedSectionBadge: defineComponentFixture({ labels: { kind: 'screenshot', blocksCi: false }, - render: ctx => { - ctx.disposableStore.add(aiCustomizationManagementSectionRegistry.register({ - id: AICustomizationManagementSection.Extensions, - label: 'Extensions', - icon: Codicon.extensions, - description: 'Choose which installed extensions run in the Agents window.', - separatorBefore: true, - supportsHarness: () => true, - getBadge: () => constObservable('Some installed extensions can be enabled in the Agents window.'), - create: () => ({ dispose: () => { } }), - })); - return renderEditor(ctx, { - sessionResource: localSessionResource, - isSessionsWindow: true, - selectedSection: AICustomizationManagementSection.Agents, - availableHarnesses: [ - createVSCodeHarnessDescriptor(), - ], - managementSections: [ - AICustomizationManagementSection.Plugins, - AICustomizationManagementSection.McpServers, - AICustomizationManagementSection.Skills, - AICustomizationManagementSection.Instructions, - AICustomizationManagementSection.Agents, - AICustomizationManagementSection.Hooks, - AICustomizationManagementSection.Tools, - AICustomizationManagementSection.Extensions, - ], - }); - }, + render: ctx => renderEditor(ctx, { + sessionResource: localSessionResource, + isSessionsWindow: true, + selectedSection: AICustomizationManagementSection.Agents, + availableHarnesses: [ + createVSCodeHarnessDescriptor(), + ], + managementSections: [ + AICustomizationManagementSection.Plugins, + AICustomizationManagementSection.McpServers, + AICustomizationManagementSection.Skills, + AICustomizationManagementSection.Instructions, + AICustomizationManagementSection.Agents, + AICustomizationManagementSection.Hooks, + AICustomizationManagementSection.Tools, + AICustomizationManagementSection.Extensions, + ], + extensionsSectionBadge: 'Some installed extensions can be enabled in the Agents window.', + }), }), // Sessions variant whose contributed section after the separator is selected in the navigation list. @@ -3805,36 +3872,26 @@ export default defineThemedFixtureGroup({ path: 'chat/aiCustomizations/' }, { labels: { kind: 'screenshot', blocksCi: false }, expectedVisualDescriptions: [ 'In the navigation list, a thin divider separates Hooks from the selected Extensions entry. The divider is not inside the selection background of Extensions, which has the same height and the same space above and below its label as the backgrounds of the other entries.', + 'The Extensions entry shows no badge.', ], - render: ctx => { - ctx.disposableStore.add(aiCustomizationManagementSectionRegistry.register({ - id: AICustomizationManagementSection.Extensions, - label: 'Extensions', - icon: Codicon.extensions, - description: 'Choose which installed extensions run in the Agents window.', - separatorBefore: true, - supportsHarness: () => true, - create: () => ({ dispose: () => { } }), - })); - return renderEditor(ctx, { - sessionResource: localSessionResource, - isSessionsWindow: true, - selectedSection: AICustomizationManagementSection.Extensions, - availableHarnesses: [ - createVSCodeHarnessDescriptor(), - ], - managementSections: [ - AICustomizationManagementSection.Plugins, - AICustomizationManagementSection.McpServers, - AICustomizationManagementSection.Skills, - AICustomizationManagementSection.Instructions, - AICustomizationManagementSection.Agents, - AICustomizationManagementSection.Hooks, - AICustomizationManagementSection.Tools, - AICustomizationManagementSection.Extensions, - ], - }); - }, + render: ctx => renderEditor(ctx, { + sessionResource: localSessionResource, + isSessionsWindow: true, + selectedSection: AICustomizationManagementSection.Extensions, + availableHarnesses: [ + createVSCodeHarnessDescriptor(), + ], + managementSections: [ + AICustomizationManagementSection.Plugins, + AICustomizationManagementSection.McpServers, + AICustomizationManagementSection.Skills, + AICustomizationManagementSection.Instructions, + AICustomizationManagementSection.Agents, + AICustomizationManagementSection.Hooks, + AICustomizationManagementSection.Tools, + AICustomizationManagementSection.Extensions, + ], + }), }), // Sessions Skills tab showing UI Integration badges on built-in skills @@ -4461,19 +4518,123 @@ export default defineThemedFixtureGroup({ path: 'chat/aiCustomizations/' }, { // Plugins tab AgentHostPluginsTab: defineComponentFixture({ labels: { kind: 'screenshot', blocksCi: false }, - expectedVisualDescriptions: ['Plugins installed on the agent host are listed in flat scope groups ordered Workspace, User, then Built-in. Organization-contributed plugins show "Organization: name" as their secondary text, and the Built-in plugin has no Copilot tag. Browse replaces the Available group.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Plugins installed on the agent host are listed in flat scope groups ordered Workspace, User, then Built-in. Successfully loaded plugins have no status indicator. Loading, warning, and error states use compact icons rather than pills. Organization-contributed plugins show "Organization: name" as their secondary text, and the Built-in plugin has no Copilot tag. Browse replaces the Available group.'], render: ctx => renderEditor(ctx, { sessionResource: agentHostCopilotSessionResource, selectedSection: AICustomizationManagementSection.Plugins, marketplaceVisibilityEnabled: true, agentHostPlugins: [ - { name: 'azure', description: 'Deploy and diagnose Azure resources', scope: 'user' }, - { name: 'contoso-release', description: 'Required by the Contoso organization', scope: 'user', organization: 'contoso' }, - { name: 'github', description: 'GitHub workflows built into Copilot', scope: 'application' }, + { name: 'azure', description: 'Deploy and diagnose Azure resources', scope: 'user', status: 'loaded' }, + { name: 'contoso-release', description: 'Required by the Contoso organization', scope: 'user', organization: 'contoso', status: 'loading' }, + { name: 'github', description: 'GitHub workflows built into Copilot', scope: 'application', status: 'degraded', statusMessage: 'Some contributions could not be loaded' }, + { name: 'invalid-plugin', description: 'Plugin with an invalid manifest', scope: 'application', status: 'error', statusMessage: 'Error parsing plugin' }, ], height: 1180, }), }), + // Organization managed settings: agent-host plugins the organization requires, + // blocks, or requires but could not install. + OrgManagedAgentHostPlugins: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.Plugins, + marketplaceVisibilityEnabled: true, + agentHostPlugins: [ + { name: 'azure', description: 'Deploy and diagnose Azure resources', scope: 'user', status: 'loaded' }, + { name: 'contoso-compliance', description: 'Compliance checks for Contoso repositories', scope: 'user', status: 'loaded', organizationControl: { requiredEnabled: true } }, + { name: 'unapproved-deploy', description: 'Deploys to unapproved environments', scope: 'user', enabled: false, organizationControl: { requiredEnabled: false } }, + { name: 'contoso-security', description: 'Security scanning required by your organization', scope: 'user', status: 'error', statusMessage: 'Your organization requires this plugin, but it isn\'t installed.', organizationControl: { requiredEnabled: true } }, + { name: 'github', description: 'GitHub workflows built into Copilot', scope: 'application', status: 'loaded' }, + ], + height: 1180, + }), + }), + + // Organization managed settings: local plugins whose enablement policy locks. + OrgManagedLocalPlugins: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: localSessionResource, + selectedSection: AICustomizationManagementSection.Plugins, + organizationManagedLocalPlugins: true, + height: 1000, + }), + }), + + // Organization managed settings: skills restricted to plugins. + OrgSkillsPluginOnly: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.Skills, + agentHostFiles: allFiles.filter(file => file.type !== PromptsType.skill || file.storage === PromptsStorage.builtIn), + policyConfiguration: organizationPluginOnlyPolicy, + }), + }), + + // Organization managed settings: agents restricted to plugins. + OrgAgentsPluginOnly: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.Agents, + agentHostFiles: allFiles.filter(file => file.type !== PromptsType.agent || file.storage === PromptsStorage.extension), + policyConfiguration: organizationPluginOnlyPolicy, + }), + }), + + // Organization managed settings: hooks the organization provides are tagged + // and locked on, alongside the user's own hooks. + OrgManagedHooks: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.Hooks, + agentHostFiles: [...allFiles, ...organizationManagedHookFiles], + height: 800, + }), + }), + + // Organization managed settings: only organization-provided hooks may load. + OrgHooksOrganizationOnly: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.Hooks, + agentHostFiles: [...allFiles.filter(file => file.type !== PromptsType.hook), ...organizationManagedHookFiles], + policyConfiguration: { [COPILOT_ALLOW_MANAGED_HOOKS_ONLY_CONFIG]: true }, + }), + }), + + // Organization managed settings: MCP servers restricted to an allowlist. + OrgMcpAllowlist: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.McpServers, + activeSessionMcpServers: organizationManagedMcpServers, + mcpWorkbenchServers: [], + mcpRuntimeServers: [], + policyConfiguration: { [mcpAllowedServersConfig]: [{ serverName: 'contoso-tickets' }, { serverName: 'contoso-docs' }, { serverName: 'component-explorer' }, { serverName: 'GitHub' }] }, + }), + }), + + // Organization managed settings: only organization-provided MCP servers may load. + OrgMcpOrganizationOnly: defineComponentFixture({ + labels: { kind: 'screenshot', blocksCi: false }, + render: ctx => renderEditor(ctx, { + sessionResource: agentHostCopilotSessionResource, + selectedSection: AICustomizationManagementSection.McpServers, + activeSessionMcpServers: organizationManagedMcpServers.filter(server => server.source === 'managed'), + mcpWorkbenchServers: [], + mcpRuntimeServers: [], + policyConfiguration: { [COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG]: true }, + }), + }), + + PluginsTab: defineComponentFixture({ labels: { kind: 'screenshot', blocksCi: false }, additionalThemes: ['darkHighContrast', 'lightHighContrast'], @@ -5093,7 +5254,7 @@ export default defineThemedFixtureGroup({ path: 'chat/aiCustomizations/' }, { copilotConnectorsEnabled: true, mcpSearchQuery: 'workiq', openFirstItem: true, - openItemLabel: 'workiq-mail-mcp', + openItemLabel: 'Work IQ Mail', }), }), diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/chatCompositeBar.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/chatCompositeBar.fixture.ts index 9cd15be08534..742df688b94d 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/chatCompositeBar.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/chatCompositeBar.fixture.ts @@ -189,7 +189,7 @@ function renderBar(ctx: ComponentFixtureContext, chats: readonly IChat[], active async function renderStickyMessageFrame(ctx: ComponentFixtureContext, width: number): Promise<void> { const chat = createMockChat({ title: 'Review panel edges' }); const content = renderBar(ctx, [chat], chat, { width }); - const chatView = $('.chat-view'); + const chatView = $('.chat-view.sessions-chat'); content.style.height = '320px'; content.appendChild(chatView); let handle: IChatWidgetFixtureHandle | undefined; diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionHeader.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionHeader.fixture.ts index 5bd5ca05e61b..7439536a540c 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionHeader.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionHeader.fixture.ts @@ -76,7 +76,7 @@ function createMockListModelService(): ISessionsListModelService { }(); } -function renderHeader(ctx: ComponentFixtureContext, session: ITestSessionWithChat, withBackground = false): void { +function renderHeader(ctx: ComponentFixtureContext, session: ITestSessionWithChat, withBackground = false, hovered = false): void { const { container, disposableStore } = ctx; const instantiationService = createEditorServices(disposableStore, { colorTheme: ctx.theme, @@ -109,6 +109,9 @@ function renderHeader(ctx: ComponentFixtureContext, session: ITestSessionWithCha const header = disposableStore.add(instantiationService.createInstance(SessionHeader)); header.setSession(testPaneContentOf(session, () => { })); headerHost.appendChild(header.element); + if (hovered) { + header.element.querySelector<HTMLElement>('.chat-composite-bar-session-title')?.classList.add('hovered'); + } } export default defineThemedFixtureGroup({ path: 'sessions/' }, { @@ -135,4 +138,10 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { title: 'Investigate and fix the flaky integration test in the notebook editor viewport rendering pipeline', })), }), + SessionHeader_Hover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the editable chat title. In high contrast themes, a dashed active-contrast boundary surrounds the title without outlining the full header.'], + render: ctx => renderHeader(ctx, createMockSession({ title: 'Unclear message' }), false, true), + }), }); diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionsTitleBarWidget.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionsTitleBarWidget.fixture.ts index d5c0dcb53031..6c8da2332e01 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionsTitleBarWidget.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionsTitleBarWidget.fixture.ts @@ -125,6 +125,7 @@ interface ITitleBarState { blocked?: readonly IBlockedSpec[]; /** Number of recently approved sessions (drives the green "Approved N sessions"). */ approvedCount?: number; + hovered?: boolean; } // ============================================================================ @@ -221,6 +222,9 @@ function renderTitleBar(ctx: ComponentFixtureContext, state: ITitleBarState): vo disposableStore.add(instantiationService.createInstance(BlockedSessionsIndicatorModel, approvalModel, blockedSessionsModel, ciFixModel)), )); widget.render(widgetHost); + if (state.hovered) { + widgetHost.classList.add('hovered'); + } } // ============================================================================ @@ -271,6 +275,15 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { activeSession: createMockActiveSession('Quick chat'), }), }), + SessionsTitleBar_Hover: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The pointer is over the normal command center. In high contrast themes, a dashed active-contrast boundary replaces the resting border without showing a duplicate title hover.'], + render: ctx => renderTitleBar(ctx, { + activeSession: createMockActiveSession('Audit Agents HC themes', 'Audit Agents HC themes'), + hovered: true, + }), + }), // Requires-input: generic orange state (a mix, or unclassified needs-input). SessionsTitleBar_RequiresInput: defineComponentFixture({ diff --git a/src/vs/workbench/test/browser/componentFixtures/welcome/welcomePageAgentsWindowGraphic.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/welcome/welcomePageAgentsWindowGraphic.fixture.ts index dee78f502974..1a7d68c8ad3c 100644 --- a/src/vs/workbench/test/browser/componentFixtures/welcome/welcomePageAgentsWindowGraphic.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/welcome/welcomePageAgentsWindowGraphic.fixture.ts @@ -120,7 +120,7 @@ async function renderWelcomePageFooter({ container, disposableStore, theme }: Co const banner = createAgentsBanner( { cssClass: 'getting-started-category.agents-banner', - graphic: { element: graphic.element, shownDesign: graphic.shownDesign, isExposed: constObservable(true) }, + graphic: { element: graphic.element, shownDesign: graphic.shownDesign, isExposed: constObservable(true), hasMultipleEditorWindows: graphic.hasMultipleEditorWindows }, }, instantiationService.get(ICommandService), NullTelemetryService, diff --git a/src/vs/workbench/test/browser/layout.test.ts b/src/vs/workbench/test/browser/layout.test.ts new file mode 100644 index 000000000000..14195bab6ab2 --- /dev/null +++ b/src/vs/workbench/test/browser/layout.test.ts @@ -0,0 +1,417 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Grid, Direction, ISerializedGrid, ISerializedNode, Orientation, SerializableGrid } from '../../../base/browser/ui/grid/grid.js'; +import { mainWindow } from '../../../base/browser/window.js'; +import { Event } from '../../../base/common/event.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 { Layout } from '../../browser/layout.js'; +import { Part, updateSashEndpoints } from '../../browser/part.js'; +import { PanelAlignment, Parts, Position } from '../../services/layout/browser/layoutService.js'; +import { NullTelemetryService } from '../../../platform/telemetry/common/telemetryUtils.js'; + +suite('Workbench layout sash endpoints', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function createLayout() { + const parts = new Map<Parts, Part>(); + const view = (id: Parts) => { + const part = new class extends mock<Part>() { + override readonly element = $(`.part.${id.split('.').pop()}`); + override readonly minimumWidth = 0; + override readonly maximumWidth = Number.POSITIVE_INFINITY; + override readonly minimumHeight = 0; + override readonly maximumHeight = Number.POSITIVE_INFINITY; + override get onDidChange() { return Event.None; } + override layout() { } + override getContainer() { return this.element; } + override updateStyles() { } + override toJSON() { return { type: id }; } + }(); + parts.set(id, part); + return part; + }; + const titleBarPartView = view(Parts.TITLEBAR_PART); + const bannerPartView = view(Parts.BANNER_PART); + const activityBarPartView = view(Parts.ACTIVITYBAR_PART); + const sideBarPartView = view(Parts.SIDEBAR_PART); + const editorPartView = view(Parts.EDITOR_PART); + const panelPartView = view(Parts.PANEL_PART); + const auxiliaryBarPartView = view(Parts.AUXILIARYBAR_PART); + const statusBarPartView = view(Parts.STATUSBAR_PART); + const chatPartView = view(Parts.CHAT_PART); + const layout = store.add(new class extends Layout { + compact = false; + override isFloatingPanelsEnabled() { return true; } + override isModernUICompact() { return this.compact; } + override isPanelMaximized() { return false; } + override setAuxiliaryBarMaximized() { return false; } + override isVisible() { return true; } + override hasFocus() { return false; } + protected override getPart(id: Parts) { return parts.get(id)!; } + }(mainWindow.document.body)); + const root = append(mainWindow.document.body, layout.mainContainer); + store.add(toDisposable(() => root.remove())); + root.className = 'monaco-workbench floating-panels panel-position-bottom panel-alignment-center'; + root.style.cssText = 'position: relative; width: 800px; height: 600px; --vscode-panels-spacing: 16px; --vscode-sash-size: 4px; --vscode-sash-hover-size: 4px; --vscode-spacing-size40: 4px; --vscode-spacing-sizeNone: 0px;'; + const grid = store.add(new Grid(titleBarPartView)); + grid.orientation = Orientation.VERTICAL; + append(root, grid.element); + grid.layout(800, 600); + grid.addView(bannerPartView, 24, titleBarPartView, Direction.Down); + grid.addView(editorPartView, 500, bannerPartView, Direction.Down); + grid.addView(statusBarPartView, 24, editorPartView, Direction.Down); + grid.addView(activityBarPartView, 40, editorPartView, Direction.Left); + grid.addView(sideBarPartView, 160, editorPartView, Direction.Left); + grid.addView(auxiliaryBarPartView, 160, editorPartView, Direction.Right); + grid.addView(panelPartView, 200, editorPartView, Direction.Down); + // Beside the editor, above the panel: its sash meets the panel's + grid.addView(chatPartView, 120, editorPartView, Direction.Left); + const values = new Map<string, number | string>(); + Object.assign(layout, { + workbenchGrid: grid, titleBarPartView, bannerPartView, activityBarPartView, sideBarPartView, + editorPartView, panelPartView, auxiliaryBarPartView, statusBarPartView, chatPartView, chatPartHidden: false, + stateModel: { + getRuntimeValue: (key: { name: string; defaultValue: number | string }) => values.get(key.name) ?? key.defaultValue, + setRuntimeValue: (key: { name: string }, value: number | string) => values.set(key.name, value), + }, + }); + const endpoints = () => Array.from(grid.element.querySelectorAll<HTMLElement>('.monaco-sash')).map(sash => { + const bounds = sash.getBoundingClientRect(); + return { + start: sash.classList.contains('workbench-sash-start-at-gap'), + end: sash.classList.contains('workbench-sash-end-at-gap'), + startOffset: sash.style.getPropertyValue('--workbench-sash-start'), + endOffset: sash.style.getPropertyValue('--workbench-sash-end'), + bounds: [bounds.left, bounds.top, bounds.right, bounds.bottom], + }; + }); + updateSashEndpoints(grid.element, true); + assert.ok(endpoints().some(sash => sash.start || sash.end)); + return { layout, root, grid, endpoints }; + } + + for (const compact of [false, true]) { + test(`refreshes sash endpoints immediately after panel alignment changes, compact=${compact}`, () => { + const { layout, root, grid, endpoints } = createLayout(); + layout.compact = compact; + root.classList.toggle('modern-ui-compact', compact); + for (const alignment of ['justify', 'right', 'center'] satisfies PanelAlignment[]) { + layout.setPanelAlignment(alignment); + const actual = endpoints(); + updateSashEndpoints(grid.element, !compact); + assert.deepStrictEqual(actual, endpoints(), alignment); + } + }); + + test(`refreshes sash endpoints immediately after the chat part hides or shows, compact=${compact}`, () => { + const { layout, root, grid, endpoints } = createLayout(); + layout.compact = compact; + root.classList.toggle('modern-ui-compact', compact); + for (const hidden of [true, false]) { + layout.setPartHidden(hidden, Parts.CHAT_PART); + const actual = endpoints(); + updateSashEndpoints(grid.element, !compact); + assert.deepStrictEqual(actual, endpoints(), `hidden=${hidden}`); + } + }); + + test(`refreshes sash endpoints immediately after panel position changes, compact=${compact}`, () => { + const { layout, root, grid, endpoints } = createLayout(); + layout.compact = compact; + root.classList.toggle('modern-ui-compact', compact); + for (const position of [Position.RIGHT, Position.TOP, Position.BOTTOM]) { + layout.setPanelPosition(position); + const actual = endpoints(); + updateSashEndpoints(grid.element, !compact); + assert.deepStrictEqual(actual, endpoints(), `${position}`); + } + }); + } +}); + +suite('Workbench layout chat part', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + interface ILayoutConfiguration { + readonly sideBar: Position; + readonly panel: Position; + readonly alignment: PanelAlignment; + /** The chat part, with the layout it was left in; none without a chat part. */ + readonly chat?: { readonly visible: boolean; readonly size: number } | 'noLayout'; + } + + /** The state a window left, to start another window from, as after a reload. */ + interface ISavedLayout { + readonly runtime: ReadonlyMap<string, unknown>; + readonly stored: string | undefined; + } + + function createLayout(configuration: ILayoutConfiguration, saved?: ISavedLayout) { + const views = new Map<Parts, Part>(); + const view = (id: Parts, minimumWidth = 0, minimumHeight = 0) => { + const element = $(`.part.${id.split('.').pop()}`); + const part = new class extends mock<Part>() { + override readonly element = element; + override readonly minimumWidth = minimumWidth; + override readonly maximumWidth = Number.POSITIVE_INFINITY; + override readonly minimumHeight = minimumHeight; + override readonly maximumHeight = Number.POSITIVE_INFINITY; + override get onDidChange() { return Event.None; } + override layout() { } + override setVisible() { } + override getContainer() { return element; } + override updateStyles() { } + override toJSON() { return { type: id }; } + }(); + views.set(id, part); + return part; + }; + const parts = { + titleBarPartView: view(Parts.TITLEBAR_PART, 0, 30), + bannerPartView: view(Parts.BANNER_PART), + activityBarPartView: view(Parts.ACTIVITYBAR_PART, 48), + sideBarPartView: view(Parts.SIDEBAR_PART, 170), + editorPartView: view(Parts.EDITOR_PART, 220), + panelPartView: view(Parts.PANEL_PART, 300, 77), + auxiliaryBarPartView: view(Parts.AUXILIARYBAR_PART, 170), + statusBarPartView: view(Parts.STATUSBAR_PART, 0, 22), + chatPartView: configuration.chat ? view(Parts.CHAT_PART, 280) : undefined, + }; + const runtime = saved ? new Map(saved.runtime) : new Map<string, unknown>([ + ['sideBar.position', configuration.sideBar], + ['panel.position', configuration.panel], + ['panel.alignment', configuration.alignment], + ['panel.hidden', false], + ['auxiliaryBar.hidden', false], + ]); + const initialization = new Map<string, unknown>([['sideBar.size', 250], ['auxiliaryBar.size', 260], ['panel.size', 200]]); + let stored = saved ? saved.stored : configuration.chat && configuration.chat !== 'noLayout' ? JSON.stringify({ version: 1, ...configuration.chat }) : undefined; + const layout = store.add(new class extends Layout { + override isVisible(part: Parts, targetWindow?: Window): boolean { + return part === Parts.TITLEBAR_PART || super.isVisible(part, targetWindow); + } + override hasFocus() { return false; } + override isFloatingPanelsEnabled() { return false; } + protected override getPart(id: Parts) { return views.get(id)!; } + }(mainWindow.document.body)); + Object.assign(layout, { + ...parts, + _mainContainerDimension: { width: 1600, height: 900 }, + telemetryService: NullTelemetryService, + // No view containers: the side bar and the panel show and hide empty + paneCompositeService: { getActivePaneComposite: () => undefined, getLastActivePaneCompositeId: () => undefined }, + viewDescriptorService: { getViewContainersByLocation: () => [] }, + configurationService: { getValue: () => undefined }, + storageService: { get: () => stored, store: (_key: string, value: string) => stored = value }, + stateModel: { + getRuntimeValue: (key: { name: string; defaultValue: unknown }) => runtime.has(key.name) ? runtime.get(key.name) : key.defaultValue, + setRuntimeValue: (key: { name: string }, value: unknown) => runtime.set(key.name, value), + getInitializationValue: (key: { name: string; defaultValue: unknown }) => initialization.get(key.name) ?? key.defaultValue, + }, + }); + const descriptor = (Reflect.get(layout, 'createGridDescriptor') as () => ISerializedGrid).call(layout); + const save = (): ISavedLayout => { + (Reflect.get(layout, 'saveChatPartLayout') as () => void).call(layout); + return { runtime, stored }; + }; + return { layout, views, descriptor, save }; + } + + /** The parts of `node`, nested as the grid nests them, marking hidden parts. */ + function shape(node: ISerializedNode): unknown { + if (node.type === 'leaf') { + const name = (node.data as { type: string }).type.split('.').pop(); + return node.visible === false ? `(${name})` : name; + } + return (node.data as ISerializedNode[]).map(shape); + } + + /** `node` without the chat part, with its width back to the editor, as the layout without a chat part describes it. */ + function withoutChat(node: ISerializedNode): ISerializedNode { + if (node.type === 'leaf') { + return node; + } + const children = node.data as ISerializedNode[]; + const chat = children.find(child => child.type === 'leaf' && (child.data as { type: string }).type === Parts.CHAT_PART); + const rest = children.filter(child => child !== chat).map(withoutChat); + const editor = rest.find(child => child.type === 'leaf' && (child.data as { type: string }).type === Parts.EDITOR_PART); + if (chat && editor && chat.visible !== false) { + editor.size += chat.size; + } + // A branch of the chat part and the editor alone is the editor alone, at the branch's size + return rest.length === 1 && chat ? { ...rest[0], size: node.size } : { ...node, data: rest }; + } + + const configurations: ILayoutConfiguration[] = []; + for (const sideBar of [Position.LEFT, Position.RIGHT]) { + for (const panel of [Position.BOTTOM, Position.TOP, Position.LEFT, Position.RIGHT]) { + for (const alignment of ['center', 'justify', 'left', 'right'] satisfies PanelAlignment[]) { + configurations.push({ sideBar, panel, alignment }); + } + } + } + + test('the chat part sits immediately beside the editor on the primary side bar\'s side, and changes nothing else of the grid', () => { + const changed: string[] = []; + for (const configuration of configurations) { + const { descriptor: withoutChatPart } = createLayout(configuration); + for (const chat of [{ visible: true, size: 400 }, { visible: false, size: 400 }]) { + const { descriptor } = createLayout({ ...configuration, chat }); + const label = `${configuration.sideBar}/${configuration.panel}/${configuration.alignment}/${chat.visible}`; + if (JSON.stringify({ ...descriptor, root: withoutChat(descriptor.root) }) !== JSON.stringify(withoutChatPart)) { + changed.push(label); + } + } + } + assert.deepStrictEqual(changed, []); + }); + + test('places the chat part between the editor and the parts on the side bar\'s side', () => { + const middle = (configuration: ILayoutConfiguration) => shape((createLayout(configuration).descriptor.root.data as ISerializedNode[])[2]); + assert.deepStrictEqual({ + bottomPanel: middle({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }), + bottomPanelJustified: middle({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'justify', chat: { visible: true, size: 400 } }), + bottomPanelSideBarRight: middle({ sideBar: Position.RIGHT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }), + leftPanel: middle({ sideBar: Position.LEFT, panel: Position.LEFT, alignment: 'center', chat: { visible: true, size: 400 } }), + rightPanelSideBarRight: middle({ sideBar: Position.RIGHT, panel: Position.RIGHT, alignment: 'center', chat: { visible: false, size: 400 } }), + }, { + bottomPanel: ['activitybar', 'sidebar', [['chat', 'editor'], 'panel'], 'auxiliarybar'], + bottomPanelJustified: ['activitybar', [['sidebar', 'chat', 'editor', 'auxiliarybar'], 'panel']], + bottomPanelSideBarRight: ['auxiliarybar', [['editor', 'chat'], 'panel'], 'sidebar', 'activitybar'], + leftPanel: ['activitybar', 'sidebar', 'panel', 'chat', 'editor', 'auxiliarybar'], + rightPanelSideBarRight: ['auxiliarybar', 'editor', '(chat)', 'panel', 'sidebar', 'activitybar'], + }); + }); + + test('a chat part without a layout of its own, or with one of another version, starts hidden at a default width', () => { + const { descriptor } = createLayout({ sideBar: Position.LEFT, panel: Position.LEFT, alignment: 'center', chat: 'noLayout' }); + const chat = (descriptor.root.data as ISerializedNode[])[2].data as ISerializedNode[]; + assert.deepStrictEqual(chat.map(node => ({ part: shape(node), size: node.size })).filter(node => node.part === '(chat)'), [{ part: '(chat)', size: 480 }]); + }); + + function createGridLayout(configuration: ILayoutConfiguration, saved?: ISavedLayout) { + const { layout, views, descriptor, save } = createLayout(configuration, saved); + const grid = store.add(SerializableGrid.deserialize(descriptor, { fromJSON: ({ type }: { type: Parts }) => views.get(type)! }, { proportionalLayout: false })); + append(layout.mainContainer, grid.element); + grid.layout(1600, 900); + Object.assign(layout, { workbenchGrid: grid }); + const middle = () => shape((grid.serialize().root.data as ISerializedNode[])[2]); + return { layout, grid, middle, save }; + } + + test('the visible neighbors of the parts beside a chat part are the chat part, as long as it shows', () => { + const neighbors = (chat: ILayoutConfiguration['chat']) => { + const { layout } = createGridLayout({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat }); + const neighbor = (part: Parts, direction: Direction) => layout.getVisibleNeighborPart(part, direction)?.split('.').pop(); + return { + sideBarRight: neighbor(Parts.SIDEBAR_PART, Direction.Right), + editorLeft: neighbor(Parts.EDITOR_PART, Direction.Left), + chatLeft: chat ? neighbor(Parts.CHAT_PART, Direction.Left) : undefined, + chatRight: chat ? neighbor(Parts.CHAT_PART, Direction.Right) : undefined, + }; + }; + assert.deepStrictEqual({ shown: neighbors({ visible: true, size: 400 }), hidden: neighbors({ visible: false, size: 400 }), absent: neighbors(undefined) }, { + shown: { sideBarRight: 'chat', editorLeft: 'chat', chatLeft: 'sidebar', chatRight: 'editor' }, + hidden: { sideBarRight: 'editor', editorLeft: 'sidebar', chatLeft: undefined, chatRight: undefined }, + absent: { sideBarRight: 'editor', editorLeft: 'sidebar', chatLeft: undefined, chatRight: undefined }, + }); + }); + + test('the grid without a chat part is as before it existed', () => { + const { layout, descriptor } = createLayout({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center' }); + const bannerFirst = (Reflect.get(layout, 'shouldShowBannerFirst') as () => boolean).call(layout); + assert.deepStrictEqual(shape(descriptor.root), [ + ...(bannerFirst ? ['(banner)', 'titlebar'] : ['titlebar', '(banner)']), + ['activitybar', 'sidebar', ['editor', 'panel'], 'auxiliarybar'], + 'statusbar', + ]); + }); + + test('keeps the chat part beside the editor as the side bar and the panel move', () => { + const { layout, middle } = createGridLayout({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }); + const setSideBarPosition = (position: Position) => (Reflect.get(layout, 'setSideBarPosition') as (position: Position) => void).call(layout, position); + const steps: Record<string, unknown> = {}; + setSideBarPosition(Position.RIGHT); + steps.sideBarRight = middle(); + layout.setPanelPosition(Position.RIGHT); + steps.panelRight = middle(); + setSideBarPosition(Position.LEFT); + steps.sideBarLeft = middle(); + layout.setPanelPosition(Position.LEFT); + steps.panelLeft = middle(); + layout.setPanelPosition(Position.TOP); + steps.panelTop = middle(); + layout.setPanelAlignment('justify'); + steps.justified = middle(); + assert.deepStrictEqual(steps, { + sideBarRight: ['auxiliarybar', [['editor', 'chat'], 'panel'], 'sidebar', 'activitybar'], + panelRight: ['auxiliarybar', 'editor', 'chat', 'panel', 'sidebar', 'activitybar'], + sideBarLeft: ['activitybar', 'sidebar', 'chat', 'editor', 'panel', 'auxiliarybar'], + panelLeft: ['activitybar', 'sidebar', 'panel', 'chat', 'editor', 'auxiliarybar'], + panelTop: ['activitybar', 'sidebar', ['panel', ['chat', 'editor']], 'auxiliarybar'], + justified: ['activitybar', ['panel', ['sidebar', 'chat', 'editor', 'auxiliarybar']]], + }); + }); + + test('hides the chat part with the editor for a maximized panel and shows it again with the editor, as showing the chat part does', () => { + const { layout } = createGridLayout({ sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }); + const visible = () => ({ chat: layout.isVisible(Parts.CHAT_PART), editor: layout.isVisible(Parts.EDITOR_PART, mainWindow), panel: layout.isVisible(Parts.PANEL_PART) }); + const steps: Record<string, unknown> = {}; + layout.toggleMaximizedPanel(); + steps.maximized = visible(); + layout.toggleMaximizedPanel(); + steps.restored = visible(); + layout.setPartHidden(true, Parts.CHAT_PART); + steps.closed = visible(); + layout.toggleMaximizedPanel(); + layout.toggleMaximizedPanel(); + steps.closedAfterMaximize = visible(); + layout.toggleMaximizedPanel(); + layout.setPartHidden(false, Parts.CHAT_PART); + steps.shownWhileMaximized = visible(); + assert.deepStrictEqual(steps, { + maximized: { chat: false, editor: false, panel: true }, + restored: { chat: true, editor: true, panel: true }, + closed: { chat: false, editor: true, panel: true }, + closedAfterMaximize: { chat: false, editor: true, panel: true }, + shownWhileMaximized: { chat: true, editor: true, panel: true }, + }); + }); + + test('a chat part hidden for a maximized panel or secondary side bar stays hidden after a reload, and shows again when that is restored', () => { + const configuration: ILayoutConfiguration = { sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }; + const reload = (toggleMaximized: (layout: Layout) => void) => { + const before = createGridLayout(configuration); + toggleMaximized(before.layout); + const { layout } = createGridLayout(configuration, before.save()); + const reloaded = layout.isVisible(Parts.CHAT_PART); + toggleMaximized(layout); + return { reloaded, restored: layout.isVisible(Parts.CHAT_PART) }; + }; + assert.deepStrictEqual({ + panel: reload(layout => layout.toggleMaximizedPanel()), + auxiliaryBar: reload(layout => layout.toggleMaximizedAuxiliaryBar()), + }, { + panel: { reloaded: false, restored: true }, + auxiliaryBar: { reloaded: false, restored: true }, + }); + }); + + test('a chat part hidden for a maximized panel shows after a reload when the panel no longer opens maximized there, as for a justified bottom panel', () => { + const configuration: ILayoutConfiguration = { sideBar: Position.LEFT, panel: Position.BOTTOM, alignment: 'center', chat: { visible: true, size: 400 } }; + const before = createGridLayout(configuration); + before.layout.toggleMaximizedPanel(); + const saved = before.save(); + // The panel alignment is kept per profile: another workspace justified it meanwhile + const runtime = new Map(saved.runtime).set('panel.alignment', 'justify'); + const { layout } = createGridLayout(configuration, { ...saved, runtime }); + assert.deepStrictEqual({ panelMaximized: layout.isPanelMaximized(), chat: layout.isVisible(Parts.CHAT_PART) }, { panelMaximized: false, chat: true }); + }); +}); diff --git a/src/vs/workbench/test/browser/part.test.ts b/src/vs/workbench/test/browser/part.test.ts index 12bd7e5d54f5..bde68c49b6c4 100644 --- a/src/vs/workbench/test/browser/part.test.ts +++ b/src/vs/workbench/test/browser/part.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { Part } from '../../browser/part.js'; +import { Part, relayoutWorkbenchParts, updateSashEndpoints } from '../../browser/part.js'; import { isEmptyObject } from '../../../base/common/types.js'; import { TestThemeService } from '../../../platform/theme/test/common/testThemeService.js'; import { append, $, Dimension, hide } from '../../../base/browser/dom.js'; @@ -14,11 +14,107 @@ import { TestStorageService } from '../common/workbenchTestServices.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; import { DisposableStore } from '../../../base/common/lifecycle.js'; import { mainWindow } from '../../../base/browser/window.js'; +import { Grid, ISerializableView } from '../../../base/browser/ui/grid/grid.js'; +import { Event } from '../../../base/common/event.js'; +import '../../../base/browser/ui/sash/sash.css'; suite('Workbench parts', () => { const disposables = new DisposableStore(); + for (const gap of [0, 1, 4, 7, 16]) { + for (const junction of ['start', 'end', 'horizontal'] as const) { + test(`thin ${junction} sashes reach the center of adjoining ${gap}px gaps`, () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.floating-panels.panel-position-bottom')); + root.style.cssText = `position: relative; width: 800px; height: 600px; --vscode-panels-spacing: ${gap}px; --vscode-sash-size: 4px; --vscode-sash-hover-size: 4px; --vscode-spacing-size40: 4px; --vscode-spacing-sizeNone: 0px;`; + const grid = append(root, $('.monaco-grid-view')); + const outerBranch = append(grid, $('.monaco-grid-branch-node')); + const outerSplit = append(outerBranch, $('.monaco-split-view2.vertical')); + const scrollable = append(outerSplit, $('.monaco-scrollable-element')); + const views = append(scrollable, $('.split-view-container')); + const nestedView = append(views, $('.split-view-view.visible')); + nestedView.style.cssText = 'width: 800px; height: 600px; top: 0; left: 0;'; + const innerBranch = append(nestedView, $('.monaco-grid-branch-node')); + const innerSplit = append(innerBranch, $('.monaco-split-view2.horizontal')); + const verticalContainer = append(innerSplit, $('.sash-container')); + verticalContainer.style.cssText = `position: absolute; left: 0; top: ${junction === 'start' ? 300 : 0}px; width: 800px; height: ${junction === 'horizontal' ? 600 : 300}px;`; + const vertical = append(verticalContainer, $('.monaco-sash.vertical')); + vertical.style.left = `${junction === 'horizontal' ? 198 : 398}px`; + const horizontalContainer = append(outerSplit, $('.sash-container')); + horizontalContainer.style.cssText = `position: absolute; left: ${junction === 'horizontal' ? 200 : 0}px; top: 0; width: ${junction === 'horizontal' ? 400 : 800}px; height: 600px;`; + const horizontal = append(horizontalContainer, $('.monaco-sash.horizontal')); + horizontal.style.top = '298px'; + const trailing = junction === 'horizontal' ? append(verticalContainer, $('.monaco-sash.vertical')) : undefined; + if (trailing) { + trailing.style.left = '598px'; + } + try { + const beforeThickness = [vertical.getBoundingClientRect().width, horizontal.getBoundingClientRect().height]; + updateSashEndpoints(grid, true); + const verticalBounds = vertical.getBoundingClientRect(); + const horizontalBounds = horizontal.getBoundingClientRect(); + const horizontalCenter = horizontalBounds.top + horizontalBounds.height / 2; + const hover = mainWindow.getComputedStyle(junction === 'horizontal' ? horizontal : vertical, '::before'); + const endpoint = junction === 'horizontal' ? horizontalBounds.left : junction === 'start' ? verticalBounds.top : verticalBounds.bottom; + const crossing = junction === 'horizontal' ? verticalBounds.left + verticalBounds.width / 2 : horizontalCenter; + const hoverEndpoint = junction === 'horizontal' ? horizontalBounds.left + parseFloat(hover.left) + : junction === 'start' ? verticalBounds.top + parseFloat(hover.top) : verticalBounds.bottom - parseFloat(hover.bottom); + const actual = { + beforeThickness, + thickness: [verticalBounds.width, horizontalBounds.height], + hoverThickness: Number.parseFloat(junction === 'horizontal' ? hover.height : hover.width), + endpointOffset: endpoint - crossing, + hoverEndpointOffset: hoverEndpoint - crossing, + trailingOffset: trailing ? horizontalBounds.right - (trailing.getBoundingClientRect().left + trailing.getBoundingClientRect().width / 2) : 0, + }; + updateSashEndpoints(grid, false); + assert.deepStrictEqual({ + ...actual, + cleared: Array.from(grid.querySelectorAll<HTMLElement>('.monaco-sash')).every(sash => !sash.classList.contains('workbench-sash-start-at-gap') + && !sash.classList.contains('workbench-sash-end-at-gap') + && sash.style.getPropertyValue('--workbench-sash-start') === '' && sash.style.getPropertyValue('--workbench-sash-end') === ''), + }, { + beforeThickness: [4, 4], + thickness: [4, 4], + hoverThickness: 4, + endpointOffset: 0, + hoverEndpointOffset: 0, + trailingOffset: 0, + cleared: true, + }); + } finally { + root.remove(); + } + }); + } + } + + test('reapplies content spacing without changing grid allocations', () => { + let spacing = 4; + const layouts: { width: number; height: number; top: number; left: number; contentWidth: number }[] = []; + const view: ISerializableView = { + element: $('div'), + minimumWidth: 0, + maximumWidth: Number.POSITIVE_INFINITY, + minimumHeight: 0, + maximumHeight: Number.POSITIVE_INFINITY, + onDidChange: Event.None, + layout: (width, height, top, left) => layouts.push({ width, height, top, left, contentWidth: width - spacing }), + toJSON: () => ({}), + }; + const grid = disposables.add(new Grid(view)); + grid.layout(800, 600); + layouts.length = 0; + spacing = 16; + grid.layout(800, 600); + const cachedLayouts = layouts.length; + relayoutWorkbenchParts(grid); + assert.deepStrictEqual({ cachedLayouts, layouts }, { + cachedLayouts: 0, + layouts: [{ width: 800, height: 600, top: 0, left: 0, contentWidth: 784 }], + }); + }); + class SimplePart extends Part { minimumWidth: number = 50; @@ -92,6 +188,10 @@ suite('Workbench parts', () => { this.setFooterArea(footerContainer); } + testRemoveFooterArea(): void { + this.removeFooterArea(); + } + testLayoutContents(width: number, height: number) { return this.layoutContents(width, height); } @@ -223,6 +323,30 @@ suite('Workbench parts', () => { }); }); + test('Part reflects footer presence on its container', () => { + const part = disposables.add(new MyPart2()); + part.create(fixture); + const footer = document.createElement('div'); + + part.testSetFooterArea(footer); + const withFooter = { + hasClass: fixture.classList.contains('has-footer'), + footerClass: footer.classList.contains('footer'), + }; + part.testRemoveFooterArea(); + + assert.deepStrictEqual({ + withFooter, + afterRemoval: { + hasClass: fixture.classList.contains('has-footer'), + footerConnected: footer.isConnected, + }, + }, { + withFooter: { hasClass: true, footerClass: true }, + afterRemoval: { hasClass: false, footerConnected: false }, + }); + }); + test('Part Layout supports a custom title height', () => { let titleHeight: number | undefined = 28; const part = disposables.add(new MyPart2(new TestLayoutService(), () => titleHeight)); diff --git a/src/vs/workbench/test/browser/parts/activitybar/activitybarPart.test.ts b/src/vs/workbench/test/browser/parts/activitybar/activitybarPart.test.ts index fcc161012480..e86ea75a47fd 100644 --- a/src/vs/workbench/test/browser/parts/activitybar/activitybarPart.test.ts +++ b/src/vs/workbench/test/browser/parts/activitybar/activitybarPart.test.ts @@ -13,7 +13,7 @@ import { TestStorageService } from '../../../common/workbenchTestServices.js'; import { TestHostService, TestLayoutService, TestMenuService, workbenchInstantiationService } from '../../workbenchTestServices.js'; import { ActivitybarPart, ActivityBarCompositeBar } from '../../../../browser/parts/activitybar/activitybarPart.js'; import { IViewSize } from '../../../../../base/browser/ui/grid/grid.js'; -import { COMPACT_FLOATING_PANEL_OUTER_MARGIN, isCompactMenuInTitlebar, IWorkbenchLayoutService, LayoutSettings, ModernUIDensity, Parts, Position } from '../../../../services/layout/browser/layoutService.js'; +import { COMPACT_FLOATING_PANEL_OUTER_MARGIN, isCompactMenuInTitlebar, IWorkbenchLayoutService, LayoutSettings, ModernUIDensity, ModernUIEditorTabStyle, Parts, Position } from '../../../../services/layout/browser/layoutService.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { IPaneCompositePart } from '../../../../browser/parts/paneCompositePart.js'; @@ -24,7 +24,8 @@ import { Extensions, PaneCompositeDescriptor } from '../../../../browser/panecom import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { IViewDescriptorService, ViewContainerLocation } from '../../../../common/views.js'; import { IActivityService } from '../../../../services/activity/common/activity.js'; -import { ACTIVITY_BAR_BACKGROUND, ACTIVITY_BAR_BORDER, MODERN_ACTIVITY_BAR_BACKGROUND, MODERN_ACTIVITY_BAR_INACTIVE_BACKGROUND } from '../../../../common/theme.js'; +import { ACTIVITY_BAR_BACKGROUND, ACTIVITY_BAR_BORDER, EDITOR_GROUP_HEADER_CONNECTED_TABS_BACKGROUND, EDITOR_GROUP_HEADER_TABS_BACKGROUND, MODERN_ACTIVITY_BAR_BACKGROUND, MODERN_ACTIVITY_BAR_INACTIVE_BACKGROUND } from '../../../../common/theme.js'; +import { editorBackground } from '../../../../../platform/theme/common/colorRegistry.js'; import { ActionsOrientation } from '../../../../../base/browser/ui/actionbar/actionbar.js'; import { Dimension } from '../../../../../base/browser/dom.js'; import { GlobalCompositeBar } from '../../../../browser/parts/globalCompositeBar.js'; @@ -67,6 +68,7 @@ interface ILayoutTestHarness { lastLayoutDimensions?: Dimension; options: { orientation: ActionsOrientation }; compositeBar: { layout: (dimension: Dimension) => void }; + recomputeSizesIfVisible(): void; } // `super.layout()` resolves through the prototype chain, so calling the extracted method @@ -129,11 +131,12 @@ suite('ActivitybarPart', () => { disposables.clear(); }); - function createActivitybarPart(compact: boolean, floatingPanelsEnabled = false, sideBarPosition = Position.LEFT, colors: { [id: string]: string | undefined } = {}, modernUICompact = false, instantiationService?: IInstantiationService): { part: ActivitybarPart; configService: TestConfigurationService; layoutService: TestFloatingPanelsLayoutService; hostService: TestHostService } { + function createActivitybarPart(compact: boolean, floatingPanelsEnabled = false, sideBarPosition = Position.LEFT, colors: { [id: string]: string | undefined } = {}, modernUICompact = false, instantiationService?: IInstantiationService, tabStyle = ModernUIEditorTabStyle.Pill): { part: ActivitybarPart; configService: TestConfigurationService; layoutService: TestFloatingPanelsLayoutService; hostService: TestHostService } { const configService = new TestConfigurationService({ [LayoutSettings.ACTIVITY_BAR_COMPACT]: compact, [LayoutSettings.MODERN_UI]: floatingPanelsEnabled, [LayoutSettings.MODERN_UI_DENSITY]: modernUICompact ? ModernUIDensity.Compact : ModernUIDensity.Default, + [LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE]: tabStyle, }); const storageService = disposables.add(new TestStorageService()); const themeService = new TestThemeService(new TestColorTheme(colors)); @@ -560,6 +563,36 @@ suite('ActivitybarPart', () => { }); }); + test('default Activity Bar keeps its own colors when connected tabs are enabled', async () => { + const actual = []; + for (const colors of [ + { [editorBackground]: '#000000', [EDITOR_GROUP_HEADER_CONNECTED_TABS_BACKGROUND]: '#ffffff80', [EDITOR_GROUP_HEADER_TABS_BACKGROUND]: '#123456' }, + { [editorBackground]: '#000000', [EDITOR_GROUP_HEADER_TABS_BACKGROUND]: '#345678' }, + { [editorBackground]: '#102030' }, + ]) { + const { part, configService, hostService } = createActivitybarPart(false, true, Position.LEFT, { + [MODERN_ACTIVITY_BAR_BACKGROUND]: '#abcdef', + [MODERN_ACTIVITY_BAR_INACTIVE_BACKGROUND]: '#654321', + ...colors, + }, false, undefined, ModernUIEditorTabStyle.Connected); + hostService.setActiveWindow(mainWindow.vscodeWindowId); + const element = document.createElement('div'); + fixture.appendChild(element); + part.create(element); + const active = element.style.backgroundColor; + hostService.setActiveWindow(mainWindow.vscodeWindowId + 1); + const inactive = element.style.backgroundColor; + await configService.setUserConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE, ModernUIEditorTabStyle.Pill); + fireConfigChange(configService, LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + actual.push({ active, inactive, pill: element.style.backgroundColor }); + } + assert.deepStrictEqual(actual, [ + { active: 'rgb(171, 205, 239)', inactive: 'rgb(101, 67, 33)', pill: 'rgb(101, 67, 33)' }, + { active: 'rgb(171, 205, 239)', inactive: 'rgb(101, 67, 33)', pill: 'rgb(101, 67, 33)' }, + { active: 'rgb(171, 205, 239)', inactive: 'rgb(101, 67, 33)', pill: 'rgb(101, 67, 33)' }, + ]); + }); + // --- toJSON ------------------------------------------------------------ test('toJSON returns correct part type', () => { @@ -640,7 +673,7 @@ suite('ActivitybarPart', () => { // The composite bar decides how many activity icons fit before collapsing the rest into // the overflow ("Additional Views") menu, so the size it is handed has to match the // vertical space an item actually occupies in the current mode. - function capturedCompositeBarOptions(compact: boolean, floatingPanelsEnabled: boolean, modernUICompact = false): { options: IPaneCompositeBarOptions; globalActivities: { actionHeight: number; actionGap: number } } { + function capturedCompositeBarOptions(compact: boolean, floatingPanelsEnabled: boolean, modernUICompact = false, tabStyle = ModernUIEditorTabStyle.Pill): { options: IPaneCompositeBarOptions; globalActivities: { actionHeight: number; actionGap: number } } { let captured: IPaneCompositeBarOptions | undefined; let capturedGlobalActivities: { actionHeight: number; actionGap: number } | undefined; const stubCompositeBar = { create: () => { }, layout: () => { }, dispose: () => { } }; @@ -650,7 +683,7 @@ suite('ActivitybarPart', () => { capturedGlobalActivities = globalActivities; return stubCompositeBar; } - } as unknown as IInstantiationService); + } as unknown as IInstantiationService, tabStyle); const el = document.createElement('div'); fixture.appendChild(el); @@ -688,6 +721,49 @@ suite('ActivitybarPart', () => { ); }); + test('default Activity Bar retains its existing row and overflow sizes with connected tabs', () => { + const actual = []; + for (const compactDensity of [false, true]) { + for (const compactIcons of [false, true]) { + const { options, globalActivities } = capturedCompositeBarOptions(compactIcons, true, compactDensity, ModernUIEditorTabStyle.Connected); + actual.push({ + actionHeight: globalActivities.actionHeight, + actionGap: globalActivities.actionGap, + compositeSize: options.compositeSize, + overflowActionSize: options.overflowActionSize, + }); + } + } + assert.deepStrictEqual(actual, [ + { actionHeight: 36, actionGap: 8, compositeSize: 44, overflowActionSize: 44 }, + { actionHeight: 28, actionGap: 0, compositeSize: 28, overflowActionSize: 28 }, + { actionHeight: 36, actionGap: 4, compositeSize: 40, overflowActionSize: 40 }, + { actionHeight: 28, actionGap: 0, compositeSize: 28, overflowActionSize: 28 }, + ]); + }); + + test('changing the tab style leaves the default Activity Bar dimensions unchanged', async () => { + const { part, configService } = createActivitybarPart(false, true, Position.LEFT, {}, false, undefined, ModernUIEditorTabStyle.Connected); + const element = document.createElement('div'); + fixture.appendChild(element); + part.create(element); + const capture = () => ({ + width: element.style.getPropertyValue('--activity-bar-width'), + height: element.style.getPropertyValue('--activity-bar-action-height'), + }); + const connected = capture(); + await configService.setUserConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE, ModernUIEditorTabStyle.Pill); + fireConfigChange(configService, LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + const pill = capture(); + await configService.setUserConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE, ModernUIEditorTabStyle.Connected); + fireConfigChange(configService, LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + assert.deepStrictEqual({ connected, pill, restored: capture() }, { + connected: { width: '36px', height: '36px' }, + pill: { width: '36px', height: '36px' }, + restored: { width: '36px', height: '36px' }, + }); + }); + // The gap is rendered *between* items, so N items occupy `N * height + (N - 1) * gap`. // `compositeSize` bakes a trailing gap into every item, which over-counts by exactly one // gap, so `layout()` hands that gap back to the composite bar. Without it the last item @@ -756,6 +832,7 @@ suite('ActivitybarPart', () => { globalActivities: { actionHeight: itemHeight, actionGap: gap }, options: { orientation: ActionsOrientation.VERTICAL }, compositeBar: { layout: dimension => { laidOut = dimension; } }, + recomputeSizesIfVisible: () => { }, }, ActivitybarPart.FLOATING_ACTIVITYBAR_WIDTH, 300); return laidOut!.height; @@ -792,6 +869,7 @@ suite('ActivitybarPart', () => { globalActivities: undefined, options: { orientation: ActionsOrientation.HORIZONTAL }, compositeBar: { layout: dimension => { laidOut = dimension; } }, + recomputeSizesIfVisible: () => { }, }, 300, 35); assert.deepStrictEqual(laidOut, new Dimension(265, 35)); @@ -895,7 +973,7 @@ suite('ActivitybarPart', () => { const record = (location: string) => observed.push({ location, activityBarMenubars: harness.menubars(), titlebarOwns: isCompactMenuInTitlebar(harness.configurationService) }); record('default'); - for (const location of ['top', 'bottom', 'default', 'top', 'default', 'hidden']) { + for (const location of ['top', 'bottom', 'default', 'top', 'default', 'hidden', 'default']) { harness.setLocation(location); record(location); } @@ -907,64 +985,67 @@ suite('ActivitybarPart', () => { { location: 'default', activityBarMenubars: 1, titlebarOwns: false }, { location: 'top', activityBarMenubars: 0, titlebarOwns: true }, { location: 'default', activityBarMenubars: 1, titlebarOwns: false }, - { location: 'hidden', activityBarMenubars: 1, titlebarOwns: false }, + { location: 'hidden', activityBarMenubars: 0, titlebarOwns: true }, + { location: 'default', activityBarMenubars: 1, titlebarOwns: false }, ]); }); - test('activity bar takes the compact menu when the custom title bar is hidden and releases it when shown', function () { - const windowConfig = { - titleBarStyle: 'native', - menuStyle: 'custom', - customTitleBarVisibility: 'auto', - }; - const precondition = new TestConfigurationService({ window: { menuBarVisibility: 'compact', ...windowConfig } }); - if (isWeb || isMacintosh) { - this.skip(); - } - assert.deepStrictEqual({ nativeTitlebar: hasNativeTitlebar(precondition), nativeMenu: hasNativeMenu(precondition), menuBarVisibility: getMenuBarVisibility(precondition) }, { nativeTitlebar: true, nativeMenu: false, menuBarVisibility: 'compact' }); - const harness = createActivityBarCompositeBar('compact', 'top', 'left', windowConfig); - const observed: { step: string; activityBarMenubars: number; titlebarOwns: boolean }[] = []; - const record = (step: string) => observed.push({ step, activityBarMenubars: harness.menubars(), titlebarOwns: isCompactMenuInTitlebar(harness.configurationService) }); - - try { - record('initial'); - harness.setWindowSetting('customTitleBarVisibility', 'never'); - record('hidden'); - harness.setWindowSetting('customTitleBarVisibility', 'auto'); - record('shown'); - harness.setWindowSetting('customTitleBarVisibility', 'never'); - record('hiddenAgain'); - harness.setWindowSetting('customTitleBarVisibility', 'windowed'); - record('windowed'); - setFullscreen(true, mainWindow); - record('fullscreen'); - setFullscreen(false, mainWindow); - record('exitFullscreen'); - setFullscreen(true, mainWindow); - record('fullscreenAgain'); - setFullscreen(false, mainWindow); - record('exitFullscreenAgain'); - } finally { - setFullscreen(false, mainWindow); - } + for (const location of ['top', 'hidden']) { + test(`activity bar takes the compact menu when the custom title bar is hidden and releases it when shown, with the activity bar ${location}`, function () { + const windowConfig = { + titleBarStyle: 'native', + menuStyle: 'custom', + customTitleBarVisibility: 'auto', + }; + const precondition = new TestConfigurationService({ window: { menuBarVisibility: 'compact', ...windowConfig } }); + if (isWeb || isMacintosh) { + this.skip(); + } + assert.deepStrictEqual({ nativeTitlebar: hasNativeTitlebar(precondition), nativeMenu: hasNativeMenu(precondition), menuBarVisibility: getMenuBarVisibility(precondition) }, { nativeTitlebar: true, nativeMenu: false, menuBarVisibility: 'compact' }); + const harness = createActivityBarCompositeBar('compact', location, 'left', windowConfig); + const observed: { step: string; activityBarMenubars: number; titlebarOwns: boolean }[] = []; + const record = (step: string) => observed.push({ step, activityBarMenubars: harness.menubars(), titlebarOwns: isCompactMenuInTitlebar(harness.configurationService) }); + + try { + record('initial'); + harness.setWindowSetting('customTitleBarVisibility', 'never'); + record('hidden'); + harness.setWindowSetting('customTitleBarVisibility', 'auto'); + record('shown'); + harness.setWindowSetting('customTitleBarVisibility', 'never'); + record('hiddenAgain'); + harness.setWindowSetting('customTitleBarVisibility', 'windowed'); + record('windowed'); + setFullscreen(true, mainWindow); + record('fullscreen'); + setFullscreen(false, mainWindow); + record('exitFullscreen'); + setFullscreen(true, mainWindow); + record('fullscreenAgain'); + setFullscreen(false, mainWindow); + record('exitFullscreenAgain'); + } finally { + setFullscreen(false, mainWindow); + } - const titlebar = { activityBarMenubars: 0, titlebarOwns: true }; - const activityBar = { activityBarMenubars: 1, titlebarOwns: false }; - assert.deepStrictEqual(observed, [ - { step: 'initial', ...titlebar }, - { step: 'hidden', ...activityBar }, - { step: 'shown', ...titlebar }, - { step: 'hiddenAgain', ...activityBar }, - { step: 'windowed', ...titlebar }, - { step: 'fullscreen', ...activityBar }, - { step: 'exitFullscreen', ...titlebar }, - { step: 'fullscreenAgain', ...activityBar }, - { step: 'exitFullscreenAgain', ...titlebar }, - ]); - }); + const titlebar = { activityBarMenubars: 0, titlebarOwns: true }; + const activityBar = { activityBarMenubars: 1, titlebarOwns: false }; + assert.deepStrictEqual(observed, [ + { step: 'initial', ...titlebar }, + { step: 'hidden', ...activityBar }, + { step: 'shown', ...titlebar }, + { step: 'hiddenAgain', ...activityBar }, + { step: 'windowed', ...titlebar }, + { step: 'fullscreen', ...activityBar }, + { step: 'exitFullscreen', ...titlebar }, + { step: 'fullscreenAgain', ...activityBar }, + { step: 'exitFullscreenAgain', ...titlebar }, + ]); + }); + } - for (const location of ['top', 'bottom']) { - test(`activity bar does not install the compact menu when created with the activity bar at the ${location}`, function () { + for (const location of ['top', 'bottom', 'hidden']) { + test(`activity bar does not install the compact menu when created with the activity bar location ${location}`, function () { if (!compactSupported) { this.skip(); } diff --git a/src/vs/workbench/test/browser/parts/chat/chatHostPart.test.ts b/src/vs/workbench/test/browser/parts/chat/chatHostPart.test.ts new file mode 100644 index 000000000000..c5513c1a0767 --- /dev/null +++ b/src/vs/workbench/test/browser/parts/chat/chatHostPart.test.ts @@ -0,0 +1,347 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { Direction, Grid } from '../../../../../base/browser/ui/grid/grid.js'; +import { IView } from '../../../../../base/browser/ui/grid/gridview.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Event } from '../../../../../base/common/event.js'; +import { DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { ChatHostPart } from '../../../../browser/parts/chat/chatHostPart.js'; +import { IContentPart } from '../../../../services/editor/common/editorGroupsService.js'; +import { IWorkbenchLayoutService, PanelAlignment, Parts, Position } from '../../../../services/layout/browser/layoutService.js'; +import { TestStorageService } from '../../../common/workbenchTestServices.js'; +import '../../../../browser/media/floatingPanels.css'; +import '../../../../browser/parts/chat/media/chatHostPart.css'; +import '../../../../contrib/modernUI/browser/media/editorBorder.css'; + +suite('ChatHostPart', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + test('draws no frame of its own, so that its chats look as in a chat window', () => { + const frameOf = (workbenchClasses: string[]) => { + const workbench = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + workbench.classList.add('monaco-workbench', ...workbenchClasses); + const part = workbench.appendChild(mainWindow.document.createElement('div')); + part.classList.add('part', 'chat'); + const style = mainWindow.getComputedStyle(part); + const frame = [style.borderTopWidth, style.borderRightWidth, style.borderBottomWidth, style.borderLeftWidth]; + workbench.remove(); + return frame; + }; + + assert.deepStrictEqual({ docked: frameOf([]), floating: frameOf(['floating-panels']) }, { + docked: ['0px', '0px', '0px', '0px'], + floating: ['0px', '0px', '0px', '0px'], + }); + }); + + /** + * Lays out, from left to right, the primary side bar, the chat part, the editor and the secondary side bar, each in a cell + * of the workbench grid, and measures the cards they show: the chat part is the real part, showing an editor part, as it + * does in a window; the others reserve their margins and edges as their parts do in code, under the same styles. + */ + function measureCards(floating: boolean, modernUI = false) { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench')); + store.add(toDisposable(() => workbench.remove())); + workbench.classList.toggle('floating-panels', floating); + workbench.classList.toggle('modern-ui', modernUI); + workbench.style.cssText = 'position: absolute; top: 0; left: 0; width: 1000px; height: 400px; --vscode-panels-spacing: 16px; --vscode-spacing-size40: 4px; --vscode-spacing-sizeNone: 0px; --vscode-strokeThickness: 1px; --vscode-foreground: rgb(255, 255, 255);'; + const grid = append(workbench, $('.monaco-grid-view')); + grid.style.cssText = 'display: flex; width: 100%; height: 100%;'; + const cell = (width: number) => { + const element = append(grid, $('.split-view-view')); + element.style.cssText = `position: relative; flex: none; width: ${width}px; height: 100%;`; + return element; + }; + const reservingCard = (parent: HTMLElement, classes: string) => { + const card = append(parent, $(classes)); + card.style.boxSizing = 'border-box'; + card.style.width = 'calc(100% - var(--modern-ui-floating-card-margin, 0px) - var(--modern-ui-floating-card-inner-margin, 0px))'; + card.style.height = 'calc(100% - var(--modern-ui-floating-card-inner-margin, 0px) - var(--modern-ui-floating-card-statusbar-margin, 0px))'; + return card; + }; + + const sideBar = reservingCard(cell(200), '.part.sidebar'); + const chatCell = cell(300); + const editor = reservingCard(cell(300), '.part.editor'); + const auxiliaryBar = reservingCard(cell(200), '.part.auxiliarybar'); + + const visible = new Set<Parts>([Parts.TITLEBAR_PART, Parts.ACTIVITYBAR_PART, Parts.SIDEBAR_PART, Parts.CHAT_PART, Parts.EDITOR_PART, Parts.AUXILIARYBAR_PART]); + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => floating, + isModernUICompact: () => false, + getPanelSpacing: () => 16, + getSideBarPosition: () => Position.LEFT, + getPanelPosition: () => Position.BOTTOM, + getPanelAlignment: (): PanelAlignment => 'center', + isVisible: (part: Parts) => visible.has(part), + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + const chatElement = append(chatCell, $('.part.chat')); + chatPart.create(chatElement); + // As an editor part, it sizes what it shows, and its box takes that and its own edge + const content = $('.part.editor'); + const contentArea = append(content, $('.content')); + store.add(chatPart.setContent(upcastPartial<IContentPart>({ + element: content, + minimumWidth: 0, + onDidChange: Event.None, + setVisible: () => { }, + layout: (width: number, height: number) => { + contentArea.style.width = `${width}px`; + contentArea.style.height = `${height}px`; + }, + }))); + chatPart.layout(300, 400, 0, 200); + + const cards = [sideBar, content, editor, auxiliaryBar].map(card => card.getBoundingClientRect()); + const edgeOf = (element: HTMLElement) => { + const style = mainWindow.getComputedStyle(element); + return [style.borderTopWidth, style.borderRightWidth, style.borderBottomWidth, style.borderLeftWidth, style.borderTopStyle, style.borderTopColor, style.borderTopLeftRadius].join(' '); + }; + const result = { + gaps: cards.slice(1).map((card, index) => card.left - cards[index].right), + tops: cards.map(card => card.top), + bottoms: cards.map(card => card.bottom), + edges: { part: edgeOf(chatElement), chat: edgeOf(content), editor: edgeOf(editor) }, + }; + store.dispose(); + return result; + } + + test('with floating panels, the chat part keeps the same gaps as the other cards, and their top and bottom edges', () => { + const { gaps, tops, bottoms } = measureCards(true); + assert.deepStrictEqual({ gaps, tops, bottoms }, { + gaps: [16, 16, 16], + tops: [0, 0, 0, 0], + bottoms: [396, 396, 396, 396], + }); + }); + + test('docked, the chat part fills its cell, as the other parts do', () => { + const { gaps, tops, bottoms } = measureCards(false); + assert.deepStrictEqual({ gaps, tops, bottoms }, { + gaps: [0, 0, 0], + tops: [0, 0, 0, 0], + bottoms: [400, 400, 400, 400], + }); + }); + + test('shows only the content set last: the one it replaces leaves without being disposed, and disposing its handle leaves the new one shown', () => { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench')); + store.add(toDisposable(() => workbench.remove())); + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => false, + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + const container = append(workbench, $('.part.chat')); + chatPart.create(container); + chatPart.setVisible(true); + const content = (name: string) => { + const element = $(`.content-${name}`); + let visible: boolean | undefined; + const part = upcastPartial<IContentPart>({ element, minimumWidth: 0, onDidChange: Event.None, setVisible: value => { visible = value; }, layout: () => { } }); + return { part, state: () => ({ inPart: container.contains(element), visible }) }; + }; + const first = content('first'); + const second = content('second'); + + const firstHandle = chatPart.setContent(first.part); + const secondHandle = store.add(chatPart.setContent(second.part)); + const replaced = { first: first.state(), second: second.state() }; + firstHandle.dispose(); + const afterStaleDispose = { first: first.state(), second: second.state() }; + secondHandle.dispose(); + + assert.deepStrictEqual({ replaced, afterStaleDispose, afterDispose: second.state().inPart }, { + replaced: { first: { inPart: false, visible: false }, second: { inPart: true, visible: true } }, + afterStaleDispose: { first: { inPart: false, visible: false }, second: { inPart: true, visible: true } }, + afterDispose: false, + }); + }); + + test('reads the edge of what it shows once, and again only as the window\'s classes change, laying it out again at that edge', async () => { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench.modern-ui')); + store.add(toDisposable(() => workbench.remove())); + workbench.style.cssText = 'position: absolute; width: 400px; height: 400px; --vscode-strokeThickness: 1px; --vscode-foreground: rgb(255, 255, 255);'; + const grid = append(workbench, $('.monaco-grid-view')); + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => false, + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + chatPart.create(append(grid, $('.part.chat'))); + const content = $('.part.editor'); + const widths: number[] = []; + store.add(chatPart.setContent(upcastPartial<IContentPart>({ + element: content, + minimumWidth: 0, + onDidChange: Event.None, + setVisible: () => { }, + layout: (width: number) => widths.push(width), + }))); + + chatPart.layout(300, 400, 0, 0); + content.style.borderLeftWidth = '5px'; + chatPart.layout(300, 400, 0, 0); + // As Modern UI changes the density: the window lays out as soon as the classes change + workbench.classList.add('modern-ui-compact'); + chatPart.layout(300, 400, 0, 0); + await Promise.resolve(); + + // The first layout as the content is set, then those of the test, then the one at the new edge + assert.deepStrictEqual(widths.slice(-4), [298, 298, 298, 294]); + store.dispose(); + }); + + test('tells the grid that its least width changes as content is set or leaves', () => { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench')); + store.add(toDisposable(() => workbench.remove())); + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => false, + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + chatPart.create(append(workbench, $('.part.chat'))); + const minimumWidths: number[] = []; + store.add(chatPart.onDidChange(() => minimumWidths.push(chatPart.minimumWidth))); + + const handle = chatPart.setContent(upcastPartial<IContentPart>({ element: $('.content'), minimumWidth: 500, onDidChange: Event.None, setVisible: () => { }, layout: () => { } })); + handle.dispose(); + + assert.deepStrictEqual(minimumWidths, [500, ChatHostPart.MINIMUM_WIDTH]); + store.dispose(); + }); + + /** + * Lays out the primary side bar, the chat part when `withChat`, the editor and the secondary side bar in a grid of the + * workbench, under the floating panel styles, and measures how far each sash between them is from the middle of the + * gap between their cards. + */ + function measureSashOffsets(withChat: boolean): number[] { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench.floating-panels')); + store.add(toDisposable(() => workbench.remove())); + workbench.style.cssText = 'position: absolute; top: 0; left: 0; width: 1000px; height: 400px; --vscode-panels-spacing: 16px; --vscode-spacing-size40: 4px; --vscode-spacing-sizeNone: 0px; --vscode-sash-size: 4px; --vscode-sash-hover-size: 4px; --vscode-strokeThickness: 1px; --vscode-foreground: rgb(255, 255, 255);'; + const cardView = (classes: string): IView => { + const element = $(classes); + element.style.boxSizing = 'border-box'; + element.style.width = 'calc(100% - var(--modern-ui-floating-card-margin) - var(--modern-ui-floating-card-inner-margin))'; + element.style.height = 'calc(100% - var(--modern-ui-floating-card-inner-margin) - var(--modern-ui-floating-card-statusbar-margin))'; + return { element, minimumWidth: 0, maximumWidth: Number.POSITIVE_INFINITY, minimumHeight: 0, maximumHeight: Number.POSITIVE_INFINITY, onDidChange: Event.None, layout: () => { } }; + }; + const sideBar = cardView('.part.sidebar'); + const editor = cardView('.part.editor'); + const auxiliaryBar = cardView('.part.auxiliarybar'); + const grid = store.add(new Grid<IView>(sideBar)); + append(workbench, grid.element); + grid.layout(1000, 400); + const cards = [sideBar.element]; + let reference: IView = sideBar; + if (withChat) { + const visible = new Set<Parts>([Parts.TITLEBAR_PART, Parts.ACTIVITYBAR_PART, Parts.SIDEBAR_PART, Parts.CHAT_PART, Parts.EDITOR_PART, Parts.AUXILIARYBAR_PART]); + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => true, + isModernUICompact: () => false, + getPanelSpacing: () => 16, + getSideBarPosition: () => Position.LEFT, + getPanelPosition: () => Position.BOTTOM, + getPanelAlignment: (): PanelAlignment => 'center', + isVisible: (part: Parts) => visible.has(part), + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + chatPart.create($('.part.chat')); + const content = $('.part.editor'); + append(content, $('.content')); + store.add(chatPart.setContent(upcastPartial<IContentPart>({ element: content, minimumWidth: 0, onDidChange: Event.None, setVisible: () => { }, layout: () => { } }))); + grid.addView(chatPart, 300, sideBar, Direction.Right); + cards.push(content); + reference = chatPart; + } + grid.addView(editor, withChat ? 300 : 600, reference, Direction.Right); + grid.addView(auxiliaryBar, 200, editor, Direction.Right); + cards.push(editor.element, auxiliaryBar.element); + + const rects = cards.map(card => card.getBoundingClientRect()); + const sashes = Array.from(grid.element.querySelectorAll<HTMLElement>('.monaco-sash.vertical')).map(sash => sash.getBoundingClientRect()).sort((a, b) => a.left - b.left); + const offsets = sashes.map((sash, index) => Math.round(((sash.left + sash.right) / 2) - ((rects[index].right + rects[index + 1].left) / 2))); + store.dispose(); + return offsets; + } + + test('with floating panels, the sashes beside the chat part sit in the middle of their gaps, as without it', () => { + assert.deepStrictEqual({ withoutChat: measureSashOffsets(false), withChat: measureSashOffsets(true) }, { withoutChat: [0, 0], withChat: [0, 0, 0] }); + }); + + test('with floating panels and Modern UI, the chat card has one edge, the editor card\'s, all of it inside the part', () => { + const { gaps, tops, bottoms, edges } = measureCards(true, true); + assert.deepStrictEqual({ gaps, tops, bottoms, partDrawsNoEdge: edges.part.startsWith('0px 0px 0px 0px'), chatEdgeIsEditorEdge: edges.chat === edges.editor, chatEdgeIsDrawn: edges.chat.startsWith('1px 1px 1px 1px solid') }, { + gaps: [16, 16, 16], + tops: [0, 0, 0, 0], + bottoms: [396, 396, 396, 396], + partDrawsNoEdge: true, + chatEdgeIsEditorEdge: true, + chatEdgeIsDrawn: true, + }); + }); + + test('in compact density, the chat card draws its edges as the cards beside it do, which a layer over what it shows, such as a chat background, does not cover', () => { + const store = disposables.add(new DisposableStore()); + const workbench = append(mainWindow.document.body, $('.monaco-workbench.floating-panels.modern-ui.modern-ui-compact')); + store.add(toDisposable(() => workbench.remove())); + workbench.style.cssText = 'position: absolute; top: 0; left: 0; width: 400px; height: 400px; --vscode-spacing-sizeNone: 0px; --vscode-strokeThickness: 1px; --vscode-surface-border: rgb(1, 2, 3); --vscode-foreground: rgb(255, 255, 255);'; + const grid = append(workbench, $('.monaco-grid-view')); + grid.style.cssText = 'width: 300px; height: 400px;'; + const layoutService = upcastPartial<IWorkbenchLayoutService>({ + registerPart: () => toDisposable(() => { }), + mainContainer: workbench, + isFloatingPanelsEnabled: () => true, + isModernUICompact: () => true, + getPanelSpacing: () => 0, + getSideBarPosition: () => Position.LEFT, + getPanelPosition: () => Position.BOTTOM, + getPanelAlignment: (): PanelAlignment => 'center', + isVisible: (part: Parts) => part !== Parts.PANEL_PART, + }); + const chatPart = store.add(new ChatHostPart(new TestThemeService(), store.add(new TestStorageService()), layoutService)); + const chatElement = append(grid, $('.part.chat')); + chatPart.create(chatElement); + const content = $('.part.editor'); + content.style.cssText = 'width: 100%; height: 100%;'; + // As the chat background is laid over the editor part the chat part shows + const layer = append(content, $('.layer')); + layer.style.cssText = 'position: absolute; inset: 0;'; + store.add(chatPart.setContent(upcastPartial<IContentPart>({ element: content, minimumWidth: 0, onDidChange: Event.None, setVisible: () => { }, layout: () => { } }))); + chatPart.layout(300, 400, 0, 0); + + const card = content.getBoundingClientRect(); + const covered = layer.getBoundingClientRect(); + const style = mainWindow.getComputedStyle(content); + const result = { + uncoveredEdge: [covered.top - card.top, card.right - covered.right, card.bottom - covered.bottom], + topEdgeColor: style.getPropertyValue('--modern-ui-floating-card-top-border-color').trim(), + }; + store.dispose(); + assert.deepStrictEqual(result, { uncoveredEdge: [1, 1, 1], topEdgeColor: 'rgb(1, 2, 3)' }); + }); +}); diff --git a/src/vs/workbench/test/browser/parts/compositeBarActions.test.ts b/src/vs/workbench/test/browser/parts/compositeBarActions.test.ts index 015ad8cb164a..25a8498d1005 100644 --- a/src/vs/workbench/test/browser/parts/compositeBarActions.test.ts +++ b/src/vs/workbench/test/browser/parts/compositeBarActions.test.ts @@ -90,6 +90,9 @@ suite('CompositeBarActionViewItem', () => { fontSize: style.fontSize, spinning: content.classList.contains('codicon-modifier-spin'), label: container.getAttribute('aria-label'), + decorativeCap: container.querySelector('.active-item-indicator > .tab-connected-edge')?.getAttribute('aria-hidden'), + decorativeDivider: container.querySelector('.tab-divider')?.getAttribute('aria-hidden'), + legacyDividerDisplay: mainWindow.getComputedStyle(container.querySelector('.tab-divider')!).display, }, { width: layout.size, height: layout.size, @@ -100,6 +103,9 @@ suite('CompositeBarActionViewItem', () => { fontSize: '12px', spinning: true, label: 'Testing - Tests are running', + decorativeCap: 'true', + decorativeDivider: 'true', + legacyDividerDisplay: 'none', }); action.activities = [{ badge: numberBadge }]; diff --git a/src/vs/workbench/test/browser/parts/editor/editorDropTarget.test.ts b/src/vs/workbench/test/browser/parts/editor/editorDropTarget.test.ts index 476b47ed33b5..90785b6ffbec 100644 --- a/src/vs/workbench/test/browser/parts/editor/editorDropTarget.test.ts +++ b/src/vs/workbench/test/browser/parts/editor/editorDropTarget.test.ts @@ -22,7 +22,7 @@ import { IWorkspaceContextService } from '../../../../../platform/workspace/comm import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, registerContentDropTarget, registerInputDropTarget } from '../../../../browser/dnd.js'; import { DEFAULT_EDITOR_MIN_DIMENSIONS, DEFAULT_EDITOR_PART_OPTIONS, GroupTransferKind, IEditorGroupsView, IEditorGroupView } from '../../../../browser/parts/editor/editor.js'; import { EditorDropTarget } from '../../../../browser/parts/editor/editorDropTarget.js'; -import { EditorInputWithOptions, GroupIdentifier } from '../../../../common/editor.js'; +import { EditorInputCapabilities, EditorInputWithOptions, GroupIdentifier } from '../../../../common/editor.js'; import { EditorInput } from '../../../../common/editor/editorInput.js'; import { GroupDirection, IEditorGroup, IEditorGroupsService, IEditorPart, IMergeGroupOptions, MergeGroupMode } from '../../../../services/editor/common/editorGroupsService.js'; import { IEditorService } from '../../../../services/editor/common/editorService.js'; @@ -42,23 +42,33 @@ suite('EditorDropTarget', () => { readonly transferKinds: GroupTransferKind[]; } - function setup(options?: { readonly contentCoversGroup?: boolean; readonly inputAtBottomEdge?: boolean; readonly dragEditor?: boolean; readonly groupWidth?: number; readonly groupMinimumWidth?: number; readonly fromOtherPart?: boolean; readonly moveVeto?: string; readonly closeEmptyGroups?: boolean; readonly sourceCount?: number; readonly dragGroup?: boolean; readonly addsGroupsToSourcePart?: boolean }): ITestSetup { + function setup(options?: { readonly contentCoversGroup?: boolean; readonly inputAtBottomEdge?: boolean; readonly dragEditor?: boolean; readonly groupWidth?: number; readonly groupMinimumWidth?: number; readonly fromOtherPart?: boolean; readonly moveVeto?: string; readonly closeEmptyGroups?: boolean; readonly sourceCount?: number; readonly dragGroup?: boolean; readonly addsGroupsToSourcePart?: boolean; readonly inputAccepts?: boolean; readonly dropIntoEditor?: boolean; readonly inputArea?: boolean }): ITestSetup { const operations: string[] = []; const transferKinds: GroupTransferKind[] = []; // A 300x300 group at the viewport origin with a registered input drop target in its lower center - // (or at its bottom edge), optionally inside registered content that covers the group, like a chat view + // (or at its bottom edge), optionally inside registered content that covers the group, like a chat view, + // and optionally taking the drags let through to the lower half of the group, as a chat input does over its chat const groupElement = $('div'); groupElement.style.cssText = 'position: fixed; left: 0; top: 0; width: 300px; height: 300px;'; const content = append(groupElement, $('div')); content.style.cssText = 'position: absolute; left: 0; top: 0; width: 300px; height: 300px;'; + let area: HTMLElement | undefined; + if (options?.inputArea) { + area = append(content, $('div')); + area.style.cssText = 'position: absolute; left: 0; top: 150px; width: 300px; height: 150px;'; + } const input = append(content, $('div')); input.style.cssText = options?.inputAtBottomEdge ? 'position: absolute; left: 0; top: 270px; width: 300px; height: 30px;' : 'position: absolute; left: 100px; top: 200px; width: 100px; height: 50px;'; mainWindow.document.body.appendChild(groupElement); store.add(toDisposable(() => groupElement.remove())); - store.add(registerInputDropTarget(input)); + store.add(registerInputDropTarget(input, { + accepts: () => options?.inputAccepts ?? true, + area, + getHint: modifier => modifier ? `Drag here or hold __${modifier}__ to attach` : 'Drag here to attach', + })); if (options?.contentCoversGroup) { store.add(registerContentDropTarget(content)); } @@ -88,6 +98,12 @@ suite('EditorDropTarget', () => { override readonly groupsView = groupsView; override readonly minimumWidth = options?.groupMinimumWidth ?? 0; override readonly minimumHeight = 0; + // An editor that takes drops into it while the key is held, such as a chat editor + override readonly activeEditor = options?.dropIntoEditor ? new class extends mock<EditorInput>() { + override readonly typeId = 'droppableEditorInput'; + override readonly resource = undefined; + override hasCapability(capability: EditorInputCapabilities): boolean { return capability === EditorInputCapabilities.CanDropIntoEditor; } + }() : null; override isActive(): boolean { return true; } override isSticky(): boolean { return false; } override focus(): void { } @@ -116,7 +132,7 @@ suite('EditorDropTarget', () => { const instantiation = store.add(new TestInstantiationService()); instantiation.stub(IThemeService, new TestThemeService()); - instantiation.stub(IConfigurationService, new TestConfigurationService({ 'editor.dropIntoEditor.enabled': false })); + instantiation.stub(IConfigurationService, new TestConfigurationService({ 'editor.dropIntoEditor.enabled': !!options?.dropIntoEditor })); instantiation.stub(IEditorGroupsService, new class extends mock<IEditorGroupsService>() { override readonly groups = [groupView]; override getGroup(): IEditorGroup { return sourceGroup; } @@ -171,23 +187,74 @@ suite('EditorDropTarget', () => { return groupElement.querySelector<HTMLElement>('#monaco-workbench-editor-drop-overlay'); } - test('does not show the overlay over an input drop target, and leaves the input out of the overlay', () => { + function getInputHints(overlay: HTMLElement | null) { + return [...overlay?.querySelectorAll<HTMLElement>('.input-drop-target-hint') ?? []].map(hint => ({ + text: hint.textContent, top: hint.style.top, left: hint.style.left, width: hint.style.width, height: hint.style.height, + })); + } + + test('does not show the overlay over an input drop target, and the overlay over the group shows where the input is until the drag moves over it', () => { const { groupElement, input } = setup(); // Entering the input directly does not create the overlay dispatch(input, 'dragenter', 150, 225); const overlayOnInputEnter = !!getOverlay(groupElement); - // An overlay created over the group leaves the input out of its hit region, so the input takes the drop + // An overlay created over the group covers the input, and shows where it is dispatch(groupElement, 'dragenter', 150, 100); const overlay = getOverlay(groupElement); - const clipped = !!overlay && overlay.style.clipPath.includes('100px 200px'); - dispatch(groupElement, 'dragend', 150, 100); + const coversInput = { clipPath: overlay?.style.clipPath, hints: getInputHints(overlay) }; - assert.deepStrictEqual({ overlayOnInputEnter, overlayOnGroupEnter: !!overlay, clipped }, { + // The drag that moves over the input leaves the overlay for the input + dispatch(overlay!, 'dragover', 150, 225); + const overlayOverInput = !!getOverlay(groupElement); + dispatch(groupElement, 'dragend', 150, 225); + + assert.deepStrictEqual({ overlayOnInputEnter, overlayOnGroupEnter: !!overlay, coversInput, overlayOverInput }, { overlayOnInputEnter: false, overlayOnGroupEnter: true, - clipped: true + coversInput: { clipPath: '', hints: [{ text: 'Drag here to attach', top: '200px', left: '100px', width: '100px', height: '50px' }] }, + overlayOverInput: false + }); + }); + + test('an input drop target that does not take the drag leaves it to the overlay, which covers the input and takes its drop', () => { + const { groupElement, input, operations } = setup({ inputAccepts: false, inputAtBottomEdge: true }); + + dispatch(input, 'dragenter', 150, 285); + const overlay = getOverlay(groupElement); + const hints = getInputHints(overlay); + dispatch(overlay!, 'dragover', 150, 285); + dispatch(overlay!, 'drop', 150, 285); + dispatch(groupElement, 'dragend', 150, 285); + + assert.deepStrictEqual({ overlayOnInputEnter: !!overlay, hints, operations }, { + overlayOnInputEnter: true, + hints: [], + operations: [`split ${GroupDirection.DOWN}`, 'move 1 editor(s) to new group'] + }); + }); + + test('where the input takes what drops into the editor, as a chat input in a chat editor does, its hint says to hold the key, in place of the drop into editor prompt', () => { + const { groupElement } = setup({ dropIntoEditor: true, inputArea: true }); + + const dragOver = (x: number, y: number) => { + dispatch(getOverlay(groupElement)!, 'dragover', x, y); + const overlay = getOverlay(groupElement); + return { + hints: getInputHints(overlay).map(hint => hint.text), + prompt: overlay?.querySelector<HTMLElement>('.editor-group-overlay-drop-into-prompt')?.style.opacity, + }; + }; + + dispatch(groupElement, 'dragenter', 150, 100); + const outsideArea = dragOver(150, 100); + const insideArea = dragOver(150, 170); + dispatch(groupElement, 'dragend', 150, 170); + + assert.deepStrictEqual({ outsideArea, insideArea }, { + outsideArea: { hints: ['Drag here to attach'], prompt: '1' }, + insideArea: { hints: [`Drag here or hold ${isMacintosh ? '⇧' : 'Shift'} to attach`], prompt: '0' }, }); }); @@ -319,7 +386,7 @@ suite('EditorDropTarget', () => { otherInput.style.cssText = 'position: absolute; left: 0; top: 100px; width: 300px; height: 100px;'; mainWindow.document.body.appendChild(otherPart); store.add(toDisposable(() => otherPart.remove())); - store.add(registerInputDropTarget(otherInput)); + store.add(registerInputDropTarget(otherInput, { accepts: () => true, getHint: () => 'Drag here to attach' })); dispatch(groupElement, 'dragenter', 5, 150); const overlay = getOverlay(groupElement); @@ -345,16 +412,16 @@ suite('EditorDropTarget', () => { const indicator = overlay?.querySelector<HTMLElement>('.editor-group-overlay-indicator'); const onCenter = { overlay: !!overlay, width: indicator?.style.width, left: indicator?.style.left }; - // Over the input, the input takes it: the overlay has a hole there - const inputClipped = !!overlay && overlay.style.clipPath.includes('100px 200px'); + // Over the input, the input takes it: the overlay shows where it is + const inputHints = getInputHints(overlay).map(hint => hint.text); dispatch(getOverlay(groupElement)!, 'dragover', 150, 150); dispatch(getOverlay(groupElement)!, 'drop', 150, 150); dispatch(groupElement, 'dragend', 150, 150); - assert.deepStrictEqual({ onCenter, inputClipped, operations }, { + assert.deepStrictEqual({ onCenter, inputHints, operations }, { onCenter: { overlay: true, width: '100%', left: '0px' }, - inputClipped: true, + inputHints: ['Drag here to attach'], operations: ['move 1 editor(s) to target group'] }); }); diff --git a/src/vs/workbench/test/browser/parts/editor/multiEditorTabsControl.test.ts b/src/vs/workbench/test/browser/parts/editor/multiEditorTabsControl.test.ts index 822dc7c3995e..bfa31ac2efa3 100644 --- a/src/vs/workbench/test/browser/parts/editor/multiEditorTabsControl.test.ts +++ b/src/vs/workbench/test/browser/parts/editor/multiEditorTabsControl.test.ts @@ -20,6 +20,8 @@ import { IMenu, IMenuService, MenuId, MenuItemAction } from '../../../../../plat import { IContextMenuDelegate } from '../../../../../base/browser/contextmenu.js'; import { ICommandService } from '../../../../../platform/commands/common/commands.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js'; +import { CapturingTelemetryService } from '../../../../../platform/telemetry/test/common/testTelemetryService.js'; import { ColorScheme } from '../../../../../platform/theme/common/theme.js'; import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; import { TestColorTheme, TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; @@ -988,6 +990,107 @@ suite('MultiEditorTabsControl', () => { assert.deepStrictEqual(results, results.map(result => ({ ...result, allIconsVisible: true }))); }); + test('fixed tabs respect configured width bounds across tab styles', async () => { + const group = connectedGroup(); + const root = group.closest<HTMLElement>('.monaco-workbench')!; + openNamedEditors(['short.ts', 'a-significantly-longer-filename.ts', 'another-significantly-longer-filename.ts']); + const results = []; + for (const style of ['legacy', 'pill', 'connected']) { + root.classList.toggle('modern-ui-tabs', style !== 'legacy'); + root.classList.toggle('modern-ui-connected-editor-tabs', style === 'connected'); + for (const [minimum, maximum] of [[50, 50], [50, 60], [50, 160], [120, 140]]) { + for (const tabActionLocation of ['left', 'right'] as const) { + if (style !== 'connected' && tabActionLocation === 'left') { + continue; + } + for (const tabActionReserveSpace of [false, true]) { + const oldOptions = partOptions; + partOptions = { ...partOptions, tabSizing: 'fixed', tabActionLocation, tabActionReserveSpace, tabSizingFixedMinWidth: minimum, tabSizingFixedMaxWidth: maximum, editorActionsLocation: 'hidden' }; + control.updateOptions(oldOptions, partOptions); + for (const [available, expectedWidth] of [[maximum * 3 + 100, maximum], [minimum * 3 - 20, minimum]]) { + await layoutConnectedGroup(group, available); + const tabs = Array.from(container.querySelectorAll<HTMLElement>('.tabs-container > .tab')); + results.push({ + style, tabActionLocation, tabActionReserveSpace, minimum, maximum, available, + widths: tabs.map(tab => tab.getBoundingClientRect().width), + widthsMatch: tabs.every(tab => Math.abs(tab.getBoundingClientRect().width - expectedWidth) < 1 / 32), + actionsInBounds: style === 'legacy' || tabs.every(tab => { + const action = tab.querySelector<HTMLElement>('.action-label')!; + const bounds = action.getBoundingClientRect(); + const tabBounds = tab.getBoundingClientRect(); + return bounds.left >= tabBounds.left && bounds.right <= tabBounds.right; + }), + }); + } + } + } + } + } + assert.deepStrictEqual(results.filter(result => !result.widthsMatch || !result.actionsInBounds), []); + }); + + test('connected fixed width bounds leave compact and shrink pinned tabs at their dedicated widths', async () => { + const group = connectedGroup(); + openNamedEditors(['sticky.ts', 'regular.ts']); + const sticky = model.getEditorByIndex(0)!; + model.stick(sticky); + control.stickEditor(sticky); + const results = []; + for (const pinnedTabSizing of ['compact', 'shrink'] as const) { + for (const minimum of [50, 120]) { + const oldOptions = partOptions; + partOptions = { ...partOptions, tabSizing: 'fixed', pinnedTabSizing, tabSizingFixedMinWidth: minimum, tabSizingFixedMaxWidth: 140, editorActionsLocation: 'hidden' }; + control.updateOptions(oldOptions, partOptions); + await layoutConnectedGroup(group, 600); + results.push({ + pinnedTabSizing, minimum, + width: container.querySelector<HTMLElement>('.tab.sticky')!.getBoundingClientRect().width, + }); + } + } + assert.deepStrictEqual(results, results.map(result => ({ ...result, width: result.pinnedTabSizing === 'compact' ? 28 : 80 }))); + }); + + test('fit and shrink tabs ignore fixed width bounds and respond to available space', async () => { + const group = connectedGroup(); + const root = group.closest<HTMLElement>('.monaco-workbench')!; + openNamedEditors(['short.ts', 'a-significantly-longer-filename.ts', 'another-significantly-longer-filename.ts']); + const results = []; + for (const connected of [false, true]) { + root.classList.toggle('modern-ui-connected-editor-tabs', connected); + for (const tabSizing of ['fit', 'shrink'] as const) { + let baseline: number[] | undefined; + for (const fixedWidth of [38, 200]) { + const oldOptions = partOptions; + partOptions = { ...partOptions, tabSizing, tabActionReserveSpace: true, tabSizingFixedMinWidth: fixedWidth, tabSizingFixedMaxWidth: fixedWidth, editorActionsLocation: 'hidden' }; + control.updateOptions(oldOptions, partOptions); + await layoutConnectedGroup(group, 1200); + const tabs = Array.from(container.querySelectorAll<HTMLElement>('.tabs-container > .tab')); + const widths = () => tabs.map(tab => tab.getBoundingClientRect().width); + const fullNames = () => tabs.every(tab => { + const name = tab.querySelector<HTMLElement>('.monaco-icon-name-container')!; + return name.scrollWidth <= name.clientWidth; + }); + const wide = widths(); + const baselineWidths = baseline ??= wide; + const wideNamesComplete = fullNames(); + await layoutConnectedGroup(group, 240); + const narrow = widths(); + const narrowMatchesMode = tabSizing === 'fit' + ? narrow.every((width, index) => Math.abs(width - wide[index]) < 1 / 32) && fullNames() + : narrow.every((width, index) => width <= wide[index] + 1 / 32) && narrow.some((width, index) => width < wide[index] - 1) && !fullNames(); + await layoutConnectedGroup(group, 1200); + results.push({ + connected, tabSizing, fixedWidth, wideNamesComplete, narrowMatchesMode, + ignoresFixedBounds: wide.every((width, index) => Math.abs(width - baselineWidths[index]) < 1 / 32), + restored: widths().every((width, index) => Math.abs(width - wide[index]) < 1 / 32) && fullNames(), + }); + } + } + } + assert.deepStrictEqual(results, results.map(result => ({ ...result, wideNamesComplete: true, narrowMatchesMode: true, ignoresFixedBounds: true, restored: true }))); + }); + test('connected shrink tabs preserve icons as the editor width changes', async () => { const group = connectedGroup(); const iconStyle = document.createElement('style'); @@ -4782,5 +4885,40 @@ suite('MultiEditorTabsControl', () => { assert.deepStrictEqual(ran, [[{ groupId: groupView.id }]]); }); + test('logs the journey through the Add Tab menu: opened, then picked or dismissed', async () => { + const telemetryService = new CapturingTelemetryService(); + instantiationService.stub(ITelemetryService, telemetryService); + instantiationService.stub(ICommandService, new class extends mock<ICommandService>() { + override async executeCommand<R>(): Promise<R> { return undefined as R; } + }()); + let shownMenu: IContextMenuDelegate | undefined; + instantiationService.stub(IContextMenuService, new class extends mock<IContextMenuService>() { + override readonly onDidShowContextMenu = Event.None; + override readonly onDidHideContextMenu = Event.None; + override showContextMenu(delegate: IContextMenuDelegate): void { shownMenu = delegate; } + }()); + control.dispose(); + reset(container); + control = createControl({ tabsBarAddTab: MenuId.for('test.addTab.journey') }); + + const open = () => container.querySelector<HTMLElement>('.tabs-bar-add-tab .action-label')!.dispatchEvent(new MouseEvent(EventType.MOUSE_DOWN, { button: 0, detail: 1, bubbles: true })); + open(); + const [entry] = shownMenu!.getActions(); + // Like the context menu: running an entry first hides the menu + const onWillRun = shownMenu!.actionRunner!.onWillRun(() => shownMenu!.onHide?.(false)); + await shownMenu!.actionRunner!.run(entry, shownMenu!.getActionsContext?.()); + onWillRun.dispose(); + open(); + shownMenu!.onHide?.(true); + await timeout(0); + + assert.deepStrictEqual(telemetryService.events.filter(e => e.eventName === 'editorAddTabMenu').map(e => e.data), [ + { kind: 'opened', menuId: 'test.addTab.journey', entry: undefined }, + { kind: 'picked', menuId: 'test.addTab.journey', entry: 'test.connectedTabs.newEditor' }, + { kind: 'opened', menuId: 'test.addTab.journey', entry: undefined }, + { kind: 'dismissed', menuId: 'test.addTab.journey', entry: undefined }, + ]); + }); + ensureNoDisposablesAreLeakedInTestSuite(); }); diff --git a/src/vs/workbench/test/browser/parts/editor/textResourceEditor.test.ts b/src/vs/workbench/test/browser/parts/editor/textResourceEditor.test.ts new file mode 100644 index 000000000000..b5415d2b5036 --- /dev/null +++ b/src/vs/workbench/test/browser/parts/editor/textResourceEditor.test.ts @@ -0,0 +1,69 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { DisposableStore } from '../../../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { ICodeEditor } from '../../../../../editor/browser/editorBrowser.js'; +import { Handler } from '../../../../../editor/common/editorCommon.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IUserInteractionService, MockUserInteractionService } from '../../../../../platform/userInteraction/browser/userInteractionService.js'; +import { TextResourceEditor } from '../../../../browser/parts/editor/textResourceEditor.js'; +import { UntitledTextEditorInput } from '../../../../services/untitled/common/untitledTextEditorInput.js'; +import { TestEditorGroupView, TestServiceAccessor, workbenchInstantiationService } from '../../workbenchTestServices.js'; + +suite('TextResourceEditor', () => { + + const disposables = new DisposableStore(); + + teardown(() => { + disposables.clear(); + }); + + async function pasteIntoUntitled(settings: Record<string, unknown>, mode?: string): Promise<{ languageId: string; insertSpaces: boolean; tabSize: number }> { + const configurationService = new TestConfigurationService({ editor: settings }); + const instantiationService = workbenchInstantiationService({ configurationService: () => configurationService }, disposables); + instantiationService.stub(IUserInteractionService, new MockUserInteractionService()); + const accessor = instantiationService.createInstance(TestServiceAccessor); + disposables.add(accessor.languageService.registerLanguage({ id: 'typescript' })); + + const editor = disposables.add(instantiationService.createInstance(TextResourceEditor, new TestEditorGroupView(0))); + editor.create(document.createElement('div')); + + const input = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, accessor.untitledTextEditorService.create())); + await editor.setInput(input, undefined, Object.create(null), CancellationToken.None); + + const control = editor.getControl() as ICodeEditor; + control.trigger('keyboard', Handler.Paste, { text: 'export const a = () => {\n return 1;\n};', mode }); + + const model = control.getModel()!; + const options = model.getOptions(); + return { languageId: model.getLanguageId(), insertSpaces: options.insertSpaces, tabSize: options.tabSize }; + } + + test('paste into untitled detects indentation by default', async () => { + assert.deepStrictEqual( + await pasteIntoUntitled({ detectIndentation: true, insertSpaces: false, tabSize: 4 }, 'typescript'), + { languageId: 'typescript', insertSpaces: true, tabSize: 2 } + ); + }); + + test('paste into untitled respects editor.detectIndentation: false (#330504)', async () => { + assert.deepStrictEqual( + await pasteIntoUntitled({ detectIndentation: false, insertSpaces: false, tabSize: 4 }, 'typescript'), + { languageId: 'typescript', insertSpaces: false, tabSize: 4 } + ); + }); + + test('paste from outside VS Code into untitled respects editor.detectIndentation: false (#330504)', async () => { + assert.deepStrictEqual( + await pasteIntoUntitled({ detectIndentation: false, insertSpaces: false, tabSize: 4 }), + { languageId: 'plaintext', insertSpaces: false, tabSize: 4 } + ); + }); + + ensureNoDisposablesAreLeakedInTestSuite(); +}); diff --git a/src/vs/workbench/test/browser/parts/paneCompositePart.test.ts b/src/vs/workbench/test/browser/parts/paneCompositePart.test.ts index 0fea4333fb69..83c7056bed3a 100644 --- a/src/vs/workbench/test/browser/parts/paneCompositePart.test.ts +++ b/src/vs/workbench/test/browser/parts/paneCompositePart.test.ts @@ -4,16 +4,25 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import sinon from 'sinon'; import { $, append } from '../../../../base/browser/dom.js'; +import { ActionsOrientation } from '../../../../base/browser/ui/actionbar/actionbar.js'; +import { HoverPosition } from '../../../../base/browser/ui/hover/hoverWidget.js'; import { mainWindow } from '../../../../base/browser/window.js'; +import { toAction } from '../../../../base/common/actions.js'; import { Event } from '../../../../base/common/event.js'; import { toDisposable } from '../../../../base/common/lifecycle.js'; import { assertReturnsDefined } from '../../../../base/common/types.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import { mock } from '../../../../base/test/common/mock.js'; +import { timeout } from '../../../../base/common/async.js'; +import { IConfigurationChangeEvent, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../platform/configuration/test/common/testConfigurationService.js'; import { IViewDescriptorService, ViewContainerLocation } from '../../../common/views.js'; import { PanelPart } from '../../../browser/parts/panel/panelPart.js'; -import { IWorkbenchLayoutService, Parts, Position } from '../../../services/layout/browser/layoutService.js'; +import { CompositeBar } from '../../../browser/parts/compositeBar.js'; +import { CompositeBarAction } from '../../../browser/parts/compositeBarActions.js'; +import { IWorkbenchLayoutService, LayoutSettings, Parts, Position } from '../../../services/layout/browser/layoutService.js'; import { TestLayoutService, workbenchInstantiationService } from '../workbenchTestServices.js'; class TestPaneCompositeLayoutService extends TestLayoutService { @@ -40,6 +49,14 @@ class TestPaneCompositeLayoutService extends TestLayoutService { override getPanelPosition(): Position { return this.panelPosition; } override isVisible(part: Parts): boolean { return this.visibleParts.has(part); } override getContainer(): HTMLElement { return this.container; } + + setPanelVisible(visible: boolean): void { + if (visible) { + this.visibleParts.add(Parts.PANEL_PART); + } else { + this.visibleParts.delete(Parts.PANEL_PART); + } + } } class TestViewDescriptorService extends mock<IViewDescriptorService>() { @@ -57,6 +74,14 @@ class TestViewDescriptorService extends mock<IViewDescriptorService>() { override getViewContainersByLocation(_location: ViewContainerLocation) { return []; } + + override getViewContainerById() { + return null; + } + + override getViewContainerBadgeEnablementState(): boolean { + return true; + } } class TestPanelPart extends PanelPart { @@ -76,6 +101,129 @@ suite('Pane composite part layout', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + teardown(() => sinon.restore()); + + test('remeasures pane tabs after appearance changes and cancels pending measurements on disposal', async () => { + const root = append(mainWindow.document.body, $('.monaco-workbench')); + store.add(toDisposable(() => root.remove())); + const container = append(root, $('.part.panel')); + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IWorkbenchLayoutService, new TestPaneCompositeLayoutService(root)); + instantiationService.stub(IViewDescriptorService, new TestViewDescriptorService()); + instantiationService.stub(IConfigurationService, configurationService); + const part = store.add(instantiationService.createInstance(TestPanelPart)); + part.create(container); + part.layout(300, 200, 0, 0); + await timeout(0); + + const measuredStates: boolean[] = []; + sinon.stub(CompositeBar.prototype, 'recomputeSizes').callsFake(() => { + measuredStates.push(root.classList.contains('modern-ui-connected-editor-tabs')); + }); + const changeConfiguration = (key: string) => configurationService.onDidChangeConfigurationEmitter.fire(new class extends mock<IConfigurationChangeEvent>() { + override affectsConfiguration(setting: string): boolean { + return setting === key; + } + }); + + changeConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + assert.deepStrictEqual(measuredStates, []); + root.classList.add('modern-ui-connected-editor-tabs'); + await timeout(0); + changeConfiguration('workbench.panel.showLabels'); + await timeout(0); + changeConfiguration(LayoutSettings.MODERN_UI); + changeConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + root.classList.remove('modern-ui-connected-editor-tabs'); + await timeout(0); + changeConfiguration(LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE); + part.dispose(); + await timeout(0); + assert.deepStrictEqual(measuredStates, [true, false]); + }); + + test('remeasures changed hidden tabs on reopening before applying narrow overflow', async () => { + const root = append(mainWindow.document.body, $('.monaco-workbench.test-pane-appearance')); + store.add(toDisposable(() => root.remove())); + const style = append(root, $('style')); + style.textContent = ` + .test-pane-appearance .composite-bar .action-item { box-sizing: border-box; width: 80px; flex-shrink: 0; } + .test-pane-appearance.wider-tabs .composite-bar .action-item { width: 100px; } + `; + const container = append(root, $('.part.panel')); + const layoutService = new TestPaneCompositeLayoutService(root); + const configurationService = new TestConfigurationService(); + store.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IWorkbenchLayoutService, layoutService); + instantiationService.stub(IViewDescriptorService, new TestViewDescriptorService()); + instantiationService.stub(IConfigurationService, configurationService); + const actions = ['First', 'Second', 'Third'].map(label => store.add(new CompositeBarAction({ id: label, name: label }))); + const getAction = (id: string) => assertReturnsDefined(actions.find(action => action.id === id)); + const compositeBar = store.add(instantiationService.createInstance(CompositeBar, actions.map(action => ({ + id: action.id, name: action.label, pinned: true, visible: true, + })), { + icon: false, + orientation: ActionsOrientation.HORIZONTAL, + colors: () => ({}), + compositeSize: 0, + overflowActionSize: 44, + dndHandler: { drop() { }, onDragOver: () => true, onDragEnter: () => true }, + activityHoverOptions: { position: () => HoverPosition.BELOW }, + getActivityAction: getAction, + getCompositePinnedAction: id => toAction({ id, label: '', run: () => { } }), + getCompositeBadgeAction: id => toAction({ id, label: '', run: () => { } }), + getOnCompositeClickAction: getAction, + fillExtraContextMenuActions: () => { }, + getContextMenuActionsForComposite: () => [], + openComposite: async () => null, + getDefaultCompositeId: () => undefined, + })); + instantiationService.stubInstance(CompositeBar, compositeBar); + const part = store.add(instantiationService.createInstance(TestPanelPart)); + part.create(container); + part.layout(400, 200, 0, 0); + await timeout(0); + const capture = () => ({ + tabs: Array.from(container.querySelectorAll<HTMLElement>('.composite-bar .action-item:not([aria-haspopup])')).map(item => ({ + label: item.textContent, + width: item.getBoundingClientRect().width, + })), + overflow: container.querySelector('.composite-bar .action-item[aria-haspopup]') !== null, + }); + const initial = capture(); + const recomputeSizes = sinon.spy(compositeBar, 'recomputeSizes'); + layoutService.setPanelVisible(false); + container.style.display = 'none'; + root.classList.add('wider-tabs'); + configurationService.onDidChangeConfigurationEmitter.fire(new class extends mock<IConfigurationChangeEvent>() { + override affectsConfiguration(key: string): boolean { + return key === LayoutSettings.MODERN_UI_EDITOR_TAB_STYLE; + } + }); + await timeout(0); + const hiddenMeasurements = recomputeSizes.callCount; + layoutService.setPanelVisible(true); + container.style.display = ''; + part.layout(0, 0, 0, 0); + const zeroSizeMeasurements = recomputeSizes.callCount; + part.layout(300, 200, 0, 0); + const reopenedNarrow = capture(); + part.layout(400, 200, 0, 0); + const widened = capture(); + assert.deepStrictEqual({ + initial, reopenedNarrow, widened, + measurements: { hidden: hiddenMeasurements, zeroSize: zeroSizeMeasurements, visible: recomputeSizes.callCount }, + }, { + initial: { tabs: [{ label: 'First', width: 80 }, { label: 'Second', width: 80 }, { label: 'Third', width: 80 }], overflow: false }, + reopenedNarrow: { tabs: [{ label: 'First', width: 100 }, { label: 'Second', width: 100 }], overflow: true }, + widened: { tabs: [{ label: 'First', width: 100 }, { label: 'Second', width: 100 }, { label: 'Third', width: 100 }], overflow: false }, + measurements: { hidden: 0, zeroSize: 0, visible: 1 }, + }); + }); + test('preserves panel layout across classic and DPR 2.5 floating modes', () => { const root = append(mainWindow.document.body, $('.monaco-workbench')); store.add(toDisposable(() => root.remove())); diff --git a/src/vs/workbench/test/browser/parts/sessions/sessionsPart.test.ts b/src/vs/workbench/test/browser/parts/sessions/sessionsPart.test.ts index 133a8df47aba..fcd9266a19c7 100644 --- a/src/vs/workbench/test/browser/parts/sessions/sessionsPart.test.ts +++ b/src/vs/workbench/test/browser/parts/sessions/sessionsPart.test.ts @@ -62,6 +62,7 @@ suite('Sessions - Sessions part frame and content registry', () => { override registerPart(): IDisposable { return Disposable.None; } override isVisible(part: Parts) { return part === Parts.SESSIONS_PART; } override isModernUICompact() { return false; } + override getPanelSpacing() { return 4; } override isFloatingPanelsEnabled() { return false; } }()); instantiationService.stub(ISessionsHostLayoutService, new class extends mock<ISessionsHostLayoutService>() { }()); diff --git a/src/vs/workbench/test/browser/parts/titlebar/commandCenterLabel.test.ts b/src/vs/workbench/test/browser/parts/titlebar/commandCenterLabel.test.ts new file mode 100644 index 000000000000..7ad94b8e4b04 --- /dev/null +++ b/src/vs/workbench/test/browser/parts/titlebar/commandCenterLabel.test.ts @@ -0,0 +1,98 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { IHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegate.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../base/common/uri.js'; +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 { IResolvedFolderLocation } from '../../../../../platform/workspace/common/folderLocations.js'; +import { CommandCenterLabel } from '../../../../browser/parts/titlebar/commandCenterLabel.js'; + +suite('CommandCenterLabel', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const hoverDelegate = {} as IHoverDelegate; + + function createLocation(description?: string, icon = Codicon.gitBranch): IResolvedFolderLocation { + return { uri: URI.file('/work/repo.worktrees/feature'), label: 'feature', description, icon, providerId: 'test', builtIn: true }; + } + + function createLabel(hovers: string[] = []) { + const element = document.createElement('div'); + const hoverService = new class extends mock<IHoverService>() { + override setupManagedHover(_delegate: IHoverDelegate, _element: HTMLElement, content: string | HTMLElement | (() => string | HTMLElement)) { + hovers.push(String(content)); + return toDisposable(() => hovers.push('disposed')) as ReturnType<IHoverService['setupManagedHover']>; + } + }(); + return { element, label: disposables.add(new CommandCenterLabel(element, hoverDelegate, hoverService)) }; + } + + test('renders the location icon, name and branch group', () => { + const hovers: string[] = []; + const { element, label } = createLabel(hovers); + + label.update('repo', createLocation('feature-branch')); + label.dispose(); + + assert.deepStrictEqual({ + hasLocation: element.classList.contains('has-folder-location'), + aria: element.getAttribute('aria-label'), + name: element.querySelector('.folder-location-name')?.textContent, + hasIcon: !!element.querySelector('.folder-location-icon'), + branch: element.querySelector('.folder-location-branch')?.textContent, + hovers, + hasBranchIcon: !!element.querySelector('.folder-location-branch-icon'), + }, { + hasLocation: true, + aria: 'repo, branch feature-branch', + name: 'repo', + hasIcon: true, + branch: 'feature-branch', + hovers: ['feature-branch', 'disposed'], + hasBranchIcon: true, + }); + }); + + test('renders the folder-with-branch icon by default and the location own icon otherwise', () => { + const iconClass = (icon: typeof Codicon.gitBranch | undefined) => { + const { element, label } = createLabel(); + label.update('repo', { ...createLocation(), icon }); + return /codicon-(git-branch-checkout|git-branch)\b/.exec(element.querySelector('.folder-location-icon')?.className ?? '')?.[1]; + }; + + assert.deepStrictEqual([iconClass(Codicon.gitBranchCheckout), iconClass(undefined), iconClass(Codicon.gitBranch)], ['git-branch-checkout', 'git-branch-checkout', 'git-branch']); + }); + + test('without a description has no branch group', () => { + const { element, label } = createLabel(); + + label.update('repo', createLocation()); + + assert.deepStrictEqual({ + aria: element.getAttribute('aria-label'), + hasBranchGroup: !!element.querySelector('.folder-location-branch-group'), + name: element.querySelector('.folder-location-name')?.textContent, + }, { aria: 'repo', hasBranchGroup: false, name: 'repo' }); + }); + + test('resets to plain text at the primary location', () => { + const { element, label } = createLabel(); + label.update('repo', createLocation('feature-branch')); + + label.update('repo', undefined); + + assert.deepStrictEqual({ + hasLocation: element.classList.contains('has-folder-location'), + aria: element.getAttribute('aria-label'), + html: element.innerHTML, + }, { hasLocation: false, aria: null, html: 'repo' }); + }); +}); diff --git a/src/vs/workbench/test/browser/parts/titlebar/titlebarPart.test.ts b/src/vs/workbench/test/browser/parts/titlebar/titlebarPart.test.ts index 9bc39124e76a..ece10ff5bc8e 100644 --- a/src/vs/workbench/test/browser/parts/titlebar/titlebarPart.test.ts +++ b/src/vs/workbench/test/browser/parts/titlebar/titlebarPart.test.ts @@ -31,7 +31,7 @@ import { IActivityService } from '../../../../services/activity/common/activity. import { ACCOUNTS_ACTIVITY_ID, GLOBAL_ACTIVITY_ID } from '../../../../common/activity.js'; import { IEditorGroupsContainer } from '../../../../services/editor/common/editorGroupsService.js'; import { IHostService } from '../../../../services/host/browser/host.js'; -import { ActivityBarPosition, EditorActionsLocation, EditorTabsMode, isCompactMenuInTitlebar, IWorkbenchLayoutService, Parts } from '../../../../services/layout/browser/layoutService.js'; +import { ActivityBarPosition, EditorActionsLocation, EditorTabsMode, isCompactMenuInTitlebar, IWorkbenchLayoutService, Parts, shouldShowCustomTitleBar } from '../../../../services/layout/browser/layoutService.js'; import { TestContextMenuService, TestHostService, TestLayoutService, TestMenuService, workbenchInstantiationService } from '../../workbenchTestServices.js'; import { TestActivityService } from '../../../common/workbenchTestServices.js'; @@ -274,7 +274,7 @@ suite('Workbench - Titlebar Part', () => { }); }); - test('compact menu is owned by the titlebar only when the activity bar is at the top or bottom', () => { + test('compact menu is owned by the titlebar only when the activity bar is at the top, bottom or hidden', () => { const config = (menuBarVisibility: string, location: string) => new TestConfigurationService({ window: { menuBarVisibility }, workbench: { activityBar: { location } } @@ -290,21 +290,62 @@ suite('Workbench - Titlebar Part', () => { compactHidden: owner('compact', ActivityBarPosition.HIDDEN), classicTop: owner('classic', ActivityBarPosition.TOP), classicBottom: owner('classic', ActivityBarPosition.BOTTOM), + classicHidden: owner('classic', ActivityBarPosition.HIDDEN), }, { compactTop: compactSupported, compactDefault: false, compactBottom: compactSupported, - compactHidden: false, + compactHidden: compactSupported, classicTop: false, classicBottom: false, + classicHidden: false, }); }); - function createHandoffConfiguration(): TestConfigurationService { + test('custom title bar stays visible in fullscreen to host the compact menu of a hidden activity bar', () => { + const config = (menuBarVisibility: string, location: string) => new TestConfigurationService({ + window: { menuBarVisibility }, + workbench: { activityBar: { location } } + }); + const hidden = config('compact', ActivityBarPosition.HIDDEN); + const compactSupported = getMenuBarVisibility(hidden) === 'compact'; + const auxiliaryWindow = new class extends mock<CodeWindow>() { + override vscodeWindowId = mainWindow.vscodeWindowId + 1000; + }(); + const observe = () => ({ + hidden: shouldShowCustomTitleBar(hidden, mainWindow), + default: shouldShowCustomTitleBar(config('compact', ActivityBarPosition.DEFAULT), mainWindow), + hiddenAuxiliary: shouldShowCustomTitleBar(hidden, auxiliaryWindow), + classicHidden: shouldShowCustomTitleBar(config('classic', ActivityBarPosition.HIDDEN), mainWindow), + toggleHidden: shouldShowCustomTitleBar(config('toggle', ActivityBarPosition.HIDDEN), mainWindow), + }); + + setFullscreen(true, mainWindow); + setFullscreen(true, auxiliaryWindow); + let result: ReturnType<typeof observe>; + try { + result = observe(); + } finally { + setFullscreen(false, mainWindow); + setFullscreen(false, auxiliaryWindow); + } + + // Only the compact menu needs the title bar: auxiliary windows never host the menu bar, and + // other menu bar visibilities keep their existing fullscreen behavior. + assert.deepStrictEqual(result, { + hidden: compactSupported, + default: false, + hiddenAuxiliary: false, + classicHidden: false, + toggleHidden: false, + }); + }); + + function createHandoffConfiguration(location: ActivityBarPosition): TestConfigurationService { // A native title bar with a custom menu keeps the compact menu bar while allowing the custom title bar to be hidden. return new TestConfigurationService({ window: { titleBarStyle: 'native', menuStyle: 'custom', menuBarVisibility: 'compact', customTitleBarVisibility: 'auto' }, - workbench: { activityBar: { location: ActivityBarPosition.TOP } } + workbench: { activityBar: { location } } }); } @@ -318,57 +359,59 @@ suite('Workbench - Titlebar Part', () => { configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: (k: string) => k === key } as IConfigurationChangeEvent); } - test('compact menu leaves the titlebar when the custom title bar is hidden and returns when it is shown', function () { - const configurationService = createHandoffConfiguration(); - if (!isHandoffSupported(configurationService)) { - this.skip(); - } - const { part, container } = createTitlebar(configurationService); + for (const location of [ActivityBarPosition.TOP, ActivityBarPosition.HIDDEN]) { + test(`compact menu leaves the titlebar when the custom title bar is hidden and returns when it is shown, with the activity bar ${location}`, function () { + const configurationService = createHandoffConfiguration(location); + if (!isHandoffSupported(configurationService)) { + this.skip(); + } + const { part, container } = createTitlebar(configurationService); - const states: Record<string, { owner: boolean; count: number; compact: boolean }> = {}; - const record = (name: string) => states[name] = { owner: isCompactMenuInTitlebar(configurationService), ...menubarState(container) }; - try { - record('initial'); - setSetting(configurationService, 'window.customTitleBarVisibility', 'never'); - record('hidden'); - setSetting(configurationService, 'window.customTitleBarVisibility', 'auto'); - record('shown'); - setSetting(configurationService, 'window.customTitleBarVisibility', 'never'); - record('hiddenAgain'); - setSetting(configurationService, 'window.customTitleBarVisibility', 'auto'); - record('shownAgain'); - - // 'windowed' hides the custom title bar only while the window is fullscreen. - setSetting(configurationService, 'window.customTitleBarVisibility', 'windowed'); - record('windowed'); - setFullscreen(true, mainWindow); - record('fullscreen'); - setFullscreen(false, mainWindow); - record('exitFullscreen'); - setFullscreen(true, mainWindow); - record('fullscreenAgain'); - setFullscreen(false, mainWindow); - record('exitFullscreenAgain'); - } finally { - setFullscreen(false, mainWindow); - part.dispose(); - } + const states: Record<string, { owner: boolean; count: number; compact: boolean }> = {}; + const record = (name: string) => states[name] = { owner: isCompactMenuInTitlebar(configurationService), ...menubarState(container) }; + try { + record('initial'); + setSetting(configurationService, 'window.customTitleBarVisibility', 'never'); + record('hidden'); + setSetting(configurationService, 'window.customTitleBarVisibility', 'auto'); + record('shown'); + setSetting(configurationService, 'window.customTitleBarVisibility', 'never'); + record('hiddenAgain'); + setSetting(configurationService, 'window.customTitleBarVisibility', 'auto'); + record('shownAgain'); + + // 'windowed' hides the custom title bar only while the window is fullscreen. + setSetting(configurationService, 'window.customTitleBarVisibility', 'windowed'); + record('windowed'); + setFullscreen(true, mainWindow); + record('fullscreen'); + setFullscreen(false, mainWindow); + record('exitFullscreen'); + setFullscreen(true, mainWindow); + record('fullscreenAgain'); + setFullscreen(false, mainWindow); + record('exitFullscreenAgain'); + } finally { + setFullscreen(false, mainWindow); + part.dispose(); + } - const owned = { owner: true, count: 1, compact: true }; - const released = { owner: false, count: 0, compact: false }; - assert.deepStrictEqual(states, { - initial: owned, - hidden: released, - shown: owned, - hiddenAgain: released, - shownAgain: owned, - windowed: owned, - fullscreen: released, - exitFullscreen: owned, - fullscreenAgain: released, - exitFullscreenAgain: owned, + const owned = { owner: true, count: 1, compact: true }; + const released = { owner: false, count: 0, compact: false }; + assert.deepStrictEqual(states, { + initial: owned, + hidden: released, + shown: owned, + hiddenAgain: released, + shownAgain: owned, + windowed: owned, + fullscreen: released, + exitFullscreen: owned, + fullscreenAgain: released, + exitFullscreenAgain: owned, + }); }); - }); + } function createTitlebar(configurationService: TestConfigurationService, partCtor: typeof BrowserTitlebarPart = BrowserTitlebarPart) { const root = document.createElement('div'); @@ -434,6 +477,8 @@ suite('Workbench - Titlebar Part', () => { states.compactTopThird = menubarState(container); setConfiguration(configurationService, 'compact', ActivityBarPosition.BOTTOM); states.compactBottom = menubarState(container); + setConfiguration(configurationService, 'compact', ActivityBarPosition.HIDDEN); + states.compactHidden = menubarState(container); setConfiguration(configurationService, 'compact', ActivityBarPosition.DEFAULT); states.compactDefaultAgain = menubarState(container); part.dispose(); @@ -449,6 +494,7 @@ suite('Workbench - Titlebar Part', () => { classicAgain: classic, compactTopThird: titlebarCompact, compactBottom: titlebarCompact, + compactHidden: titlebarCompact, compactDefaultAgain: compactSupported ? none : classic, }); }); @@ -474,8 +520,8 @@ suite('Workbench - Titlebar Part', () => { }); }); - for (const location of [ActivityBarPosition.TOP, ActivityBarPosition.BOTTOM]) { - test(`titlebar-owned compact menu opens rightward and downward with the activity bar at the ${location} and the sidebar on the right`, function () { + for (const location of [ActivityBarPosition.TOP, ActivityBarPosition.BOTTOM, ActivityBarPosition.HIDDEN]) { + test(`titlebar-owned compact menu opens rightward and downward with the activity bar location ${location} and the sidebar on the right`, function () { const compactSupported = getMenuBarVisibility(new TestConfigurationService({ window: { menuBarVisibility: 'compact' } })) === 'compact'; const customSupported = !hasNativeMenu(new TestConfigurationService({ window: { menuBarVisibility: 'classic' } })) && (!isMacintosh || isWeb); if (!compactSupported || !customSupported) { @@ -506,6 +552,63 @@ suite('Workbench - Titlebar Part', () => { } }); } + + test('counter-zooms titlebar menus once without shrinking dropdown buttons or nested submenus', () => { + const workbench = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); + store.add(toDisposable(() => workbench.remove())); + workbench.className = 'monaco-workbench'; + const titlebar = workbench.appendChild(mainWindow.document.createElement('div')); + titlebar.className = 'part titlebar'; + titlebar.style.setProperty('--zoom-factor', '0.8'); + const titlebarContainer = titlebar.appendChild(mainWindow.document.createElement('div')); + titlebarContainer.className = 'titlebar-container counter-zoom'; + const toolbar = titlebarContainer.appendChild(mainWindow.document.createElement('div')); + toolbar.className = 'monaco-toolbar'; + const splitItem = toolbar.appendChild(mainWindow.document.createElement('div')); + splitItem.className = 'monaco-dropdown-with-primary'; + const primary = splitItem.appendChild(mainWindow.document.createElement('div')); + primary.className = 'action-container'; + primary.style.cssText = 'width: 20px; height: 24px;'; + const dropdown = splitItem.appendChild(mainWindow.document.createElement('div')); + dropdown.className = 'dropdown-action-container'; + dropdown.style.cssText = 'width: 16px; height: 24px;'; + const shadowHost = dropdown.appendChild(mainWindow.document.createElement('div')); + shadowHost.className = 'shadow-root-host'; + const contextView = titlebarContainer.appendChild(mainWindow.document.createElement('div')); + contextView.className = 'context-view'; + const appendSubmenu = (parent: HTMLElement) => { + const submenu = parent.appendChild(mainWindow.document.createElement('div')); + submenu.className = 'monaco-submenu menubar-menu-items-holder context-view'; + return submenu; + }; + const contextViewSubmenu = appendSubmenu(appendSubmenu(contextView)); + const menubarButton = titlebarContainer.appendChild(mainWindow.document.createElement('div')); + menubarButton.className = 'menubar'; + const menubarButtonInner = menubarButton.appendChild(mainWindow.document.createElement('div')); + menubarButtonInner.className = 'menubar-menu-button'; + const menubarHolder = menubarButtonInner.appendChild(mainWindow.document.createElement('div')); + menubarHolder.className = 'menubar-menu-items-holder monaco-menu-container'; + const menubarSubmenu = appendSubmenu(appendSubmenu(menubarHolder)); + const zoomOf = (element: HTMLElement) => mainWindow.getComputedStyle(element).getPropertyValue('zoom'); + + assert.deepStrictEqual({ + primaryWidth: Math.round(primary.getBoundingClientRect().width), + dropdownWidth: Math.round(dropdown.getBoundingClientRect().width), + shadowHostZoom: zoomOf(shadowHost), + contextViewZoom: zoomOf(contextView), + nestedContextViewSubmenuZooms: [zoomOf(contextViewSubmenu.parentElement!), zoomOf(contextViewSubmenu)], + menubarHolderZoom: zoomOf(menubarHolder), + nestedMenubarSubmenuZooms: [zoomOf(menubarSubmenu.parentElement!), zoomOf(menubarSubmenu)], + }, { + primaryWidth: 25, + dropdownWidth: 20, + shadowHostZoom: '0.8', + contextViewZoom: '0.8', + nestedContextViewSubmenuZooms: ['1', '1'], + menubarHolderZoom: '0.8', + nestedMenubarSubmenuZooms: ['1', '1'], + }); + }); }); function createMeasuredElement(clientWidth: () => number, scrollWidth: () => number): HTMLElement { diff --git a/src/vs/workbench/test/browser/parts/titlebar/windowTitle.test.ts b/src/vs/workbench/test/browser/parts/titlebar/windowTitle.test.ts new file mode 100644 index 000000000000..a122461e0405 --- /dev/null +++ b/src/vs/workbench/test/browser/parts/titlebar/windowTitle.test.ts @@ -0,0 +1,164 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { mainWindow } from '../../../../../base/browser/window.js'; +import { Emitter, Event } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { IFolderLocationChangeEvent, IResolvedFolderLocation, IWorkspaceFolderLocationService } from '../../../../../platform/workspace/common/folderLocations.js'; +import { IWorkspaceContextService, Workspace, WorkspaceFolder } from '../../../../../platform/workspace/common/workspace.js'; +import { Workspace as DerivedIdentityWorkspace } from '../../../../../platform/workspace/test/common/testWorkspace.js'; +import { defaultWindowTitle, WindowTitle } from '../../../../browser/parts/titlebar/windowTitle.js'; +import { TestContextService } from '../../../common/workbenchTestServices.js'; +import { TestViewsService, workbenchInstantiationService } from '../../workbenchTestServices.js'; +import { IViewsService } from '../../../../services/views/common/viewsService.js'; +import { IEditorService } from '../../../../services/editor/common/editorService.js'; +import { IUserDataProfileService } from '../../../../services/userDataProfile/common/userDataProfile.js'; +import { IUserDataProfile } from '../../../../../platform/userDataProfile/common/userDataProfile.js'; +import { EditorInput } from '../../../../common/editor/editorInput.js'; + +suite('Folder Location in Window Title and Command Center', () => { + + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + const primary = URI.file('/work/repo'); + const alternate = URI.file('/work/repo.worktrees/feature'); + + function createLocation(description?: string): IResolvedFolderLocation { + return { uri: alternate, label: 'feature', description, icon: Codicon.gitBranch, providerId: 'test', builtIn: true }; + } + + function createWindowTitle(windowTitleFormat: string, atAlternate = true) { + const workspace = new Workspace('id', [new WorkspaceFolder({ uri: atAlternate ? alternate : primary, index: 0, name: 'repo' })], false, null, () => false, undefined, primary); + const onDidChangeLocation = disposables.add(new Emitter<IFolderLocationChangeEvent>()); + const locationService = new class extends mock<IWorkspaceFolderLocationService>() { + current: IResolvedFolderLocation | undefined = undefined; + override readonly onDidChangeLocation = onDidChangeLocation.event; + override getLocation() { return atAlternate ? this.current : undefined; } + }(); + + const configurationService = new TestConfigurationService({ window: { title: windowTitleFormat, titleSeparator: ' - ' } }); + const instantiationService = workbenchInstantiationService({}, disposables); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IWorkspaceContextService, new TestContextService(workspace)); + instantiationService.stub(IWorkspaceFolderLocationService, locationService); + instantiationService.stub(IViewsService, new TestViewsService()); + + const title = disposables.add(instantiationService.createInstance(WindowTitle, mainWindow)); + return { title, locationService, onDidChangeLocation, workspace }; + } + + async function changes(title: WindowTitle, action: () => void): Promise<number> { + let count = 0; + const listener = title.onDidChange(() => count++); + action(); + await new Promise(resolve => setTimeout(resolve, 10)); + listener.dispose(); + return count; + } + + test('window title fires a change on a location change even if a custom title format leaves the title text unchanged', async () => { + const { title, locationService, onDidChangeLocation, workspace } = createWindowTitle('${rootName}'); + + locationService.current = createLocation('feature-branch'); + const count = await changes(title, () => onDidChangeLocation.fire({ folder: workspace.folders[0], reason: 'programmatic' })); + + assert.deepStrictEqual({ count, info: title.folderLocationInfo?.description }, { count: 1, info: 'feature-branch' }); + }); + + test('window title does not fire again when the location is unchanged', async () => { + const { title, locationService, onDidChangeLocation, workspace } = createWindowTitle('${rootName}'); + + locationService.current = createLocation('feature-branch'); + await changes(title, () => onDidChangeLocation.fire({ folder: workspace.folders[0], reason: 'programmatic' })); + const count = await changes(title, () => onDidChangeLocation.fire({ folder: workspace.folders[0], reason: 'programmatic' })); + + assert.strictEqual(count, 0); + }); + + test('command center label is the folder name at an alternate location regardless of title format and tabs', () => { + const { title, locationService } = createWindowTitle('constant'); + locationService.current = createLocation('feature-branch'); + + assert.deepStrictEqual( + [title.getCommandCenterLabel({ showFileName: false }), title.getCommandCenterLabel({ showFileName: true })], + [title.workspaceName, title.workspaceName]); + }); + + test('command center label follows the custom title format at the primary location', () => { + const { title } = createWindowTitle('constant', false); + + assert.deepStrictEqual( + { label: title.getCommandCenterLabel({ showFileName: false }), custom: title.getWindowTitle() }, + { label: 'constant', custom: 'constant' }); + }); + + suite('without a location, titles are identical to a default title without ${folderLocation}', () => { + + const mainDefaultWindowTitle = defaultWindowTitle.replace('${separator}${folderLocation}', ''); + + function render(format: string, workspace: Workspace, options?: { dirtyEditor?: boolean; profileName?: string }): { title: string; commandCenter: string[] } { + const locationService = new class extends mock<IWorkspaceFolderLocationService>() { + override readonly onDidChangeLocation = Event.None; + override getLocation() { return undefined; } + }(); + const editor = options?.dirtyEditor ? new class extends mock<EditorInput>() { + override get typeId() { return 'test'; } + override get resource() { return undefined; } + override readonly onDidChangeDirty = Event.None; + override readonly onDidChangeLabel = Event.None; + override getTitle() { return 'file.ts'; } + override isDirty() { return true; } + override isSaving() { return false; } + }() : undefined; + const profileName = options?.profileName; + const instantiationService = workbenchInstantiationService({}, disposables); + instantiationService.stub(IConfigurationService, new TestConfigurationService({ window: { title: format, titleSeparator: ' - ' } })); + instantiationService.stub(IWorkspaceContextService, new TestContextService(workspace)); + instantiationService.stub(IWorkspaceFolderLocationService, locationService); + instantiationService.stub(IViewsService, new TestViewsService()); + if (editor) { + instantiationService.stub(IEditorService, new class extends mock<IEditorService>() { + override readonly onDidActiveEditorChange = Event.None; + override get activeEditor() { return editor; } + override get activeTextEditorLanguageId() { return undefined; } + }()); + } + if (profileName) { + instantiationService.stub(IUserDataProfileService, new class extends mock<IUserDataProfileService>() { + override readonly onDidChangeCurrentProfile = Event.None; + override get currentProfile() { return { isDefault: false, name: profileName } as IUserDataProfile; } + }()); + } + const title = disposables.add(instantiationService.createInstance(WindowTitle, mainWindow)); + return { + title: title.getWindowTitle(), + commandCenter: [title.getCommandCenterLabel({ showFileName: false }), title.getCommandCenterLabel({ showFileName: true }), title.workspaceName] + }; + } + + const folder = (uri: URI, index: number) => new WorkspaceFolder({ uri, index, name: 'repo' }); + const workspaces: Record<string, () => Workspace> = { + 'single folder': () => new DerivedIdentityWorkspace('id', [folder(primary, 0)]), + 'multi-root': () => new DerivedIdentityWorkspace('id', [folder(primary, 0), folder(alternate, 1)], URI.file('/work/my.code-workspace')), + 'empty': () => new DerivedIdentityWorkspace('id', []), + }; + + for (const [name, createWorkspace] of Object.entries(workspaces)) { + test(`default window title and command center label are unchanged for ${name} workspace`, () => { + const options = [{}, { dirtyEditor: true }, { profileName: 'Work' }, { dirtyEditor: true, profileName: 'Work' }]; + + assert.deepStrictEqual( + options.map(option => render(defaultWindowTitle, createWorkspace(), option)), + options.map(option => render(mainDefaultWindowTitle, createWorkspace(), option))); + }); + } + }); +}); diff --git a/src/vs/workbench/test/browser/parts/views/viewPaneContainer.test.ts b/src/vs/workbench/test/browser/parts/views/viewPaneContainer.test.ts new file mode 100644 index 000000000000..00cfebb956b6 --- /dev/null +++ b/src/vs/workbench/test/browser/parts/views/viewPaneContainer.test.ts @@ -0,0 +1,86 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { spy } from 'sinon'; +import { $, append, Dimension } from '../../../../../base/browser/dom.js'; +import { PaneView } from '../../../../../base/browser/ui/splitview/paneview.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Event } from '../../../../../base/common/event.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 { SyncDescriptor } from '../../../../../platform/instantiation/common/descriptors.js'; +import { ViewPaneContainer } from '../../../../browser/parts/views/viewPaneContainer.js'; +import { IViewContainerModel, IViewDescriptorService, ViewContainer, ViewContainerLocation } from '../../../../common/views.js'; +import { IExtensionService } from '../../../../services/extensions/common/extensions.js'; +import { IWorkbenchLayoutService, Position } from '../../../../services/layout/browser/layoutService.js'; +import { TestLayoutService, workbenchInstantiationService } from '../../workbenchTestServices.js'; + +suite('ViewPaneContainer', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('keeps pane-internal bottom spacing independent of inter-panel spacing', async () => { + const instantiationService = workbenchInstantiationService(undefined, store); + const layoutService = new class extends TestLayoutService { + compact = false; + spacing = 4; + floating = true; + position = Position.BOTTOM; + override isModernUICompact() { return this.compact; } + override getPanelSpacing() { return this.spacing; } + override isFloatingPanelsEnabled() { return this.floating; } + override getPanelPosition() { return this.position; } + }(); + instantiationService.stub(IWorkbenchLayoutService, layoutService); + const viewContainer: ViewContainer = { + id: 'test.viewPaneContainer', + title: { value: 'Test', original: 'Test' }, + ctorDescriptor: new SyncDescriptor(ViewPaneContainer), + }; + const model = new class extends mock<IViewContainerModel>() { + override readonly visibleViewDescriptors = []; + override readonly onDidAddVisibleViewDescriptors = Event.None; + override readonly onDidRemoveVisibleViewDescriptors = Event.None; + override readonly onDidChangeActiveViewDescriptors = Event.None; + override setSizes() { } + }(); + let location = ViewContainerLocation.Sidebar; + instantiationService.stub(IViewDescriptorService, new class extends mock<IViewDescriptorService>() { + override getViewContainerById() { return viewContainer; } + override getViewContainerModel() { return model; } + override getViewContainerLocation() { return location; } + override canMoveViews() { return false; } + override readonly onDidChangeContainerLocation = Event.None; + }()); + const element = append(mainWindow.document.body, $('.view-pane-container-test')); + store.add(toDisposable(() => element.remove())); + const container = store.add(instantiationService.createInstance(ViewPaneContainer, viewContainer.id, { mergeViewWithContainerWhenSingleView: false })); + container.create(element); + await instantiationService.get(IExtensionService).whenInstalledExtensionsRegistered(); + const childLayout = spy(PaneView.prototype, 'layout'); + store.add(toDisposable(() => childLayout.restore())); + + for (const compact of [false, true]) { + layoutService.compact = compact; + for (const spacing of [0, 4, 16]) { + layoutService.spacing = spacing; + container.layout(new Dimension(300, 600)); + } + } + layoutService.compact = false; + location = ViewContainerLocation.Panel; + layoutService.position = Position.TOP; + container.layout(new Dimension(300, 600)); + layoutService.floating = false; + container.layout(new Dimension(300, 600)); + + assert.deepStrictEqual(childLayout.args, [ + [595, 300], [595, 300], [595, 300], + [599, 300], [599, 300], [599, 300], + [599, 300], [600, 300], + ]); + }); +}); diff --git a/src/vs/workbench/test/browser/treeview.test.ts b/src/vs/workbench/test/browser/treeview.test.ts index b692823727ac..db17f18bf4f9 100644 --- a/src/vs/workbench/test/browser/treeview.test.ts +++ b/src/vs/workbench/test/browser/treeview.test.ts @@ -86,6 +86,32 @@ suite('TreeView', function () { assert.strictEqual(container.querySelectorAll('.monaco-list-row').length, 10); }); + test('issue #347994 - a refresh served from the cache keeps the children of every expanded node', async () => { + const childrenByHandle = new Map<string, ITreeItem[]>(); + const item = (handle: string, children: ITreeItem[] = []): ITreeItem => { + childrenByHandle.set(handle, children); + return { handle, accessibilityInformation: { label: handle }, collapsibleState: children.length ? TreeItemCollapsibleState.Expanded : TreeItemCollapsibleState.None }; + }; + // The first expanded node has an expanded child, so its children are refreshed while its siblings are still waiting for theirs + const roots = [item('P1', [item('folder', [item('file1')])]), item('P2', [item('file2')]), item('P3', [item('file3')])]; + const cachedTreeView = disposables.add(instantiationService.createInstance(TreeView, 'cachedRefreshTree', 'Test Title')); + cachedTreeView.dataProvider = { + getChildren: async (element?: ITreeItem) => element ? childrenByHandle.get(element.handle) : roots + }; + const container = mainWindow.document.body.appendChild($('.monaco-workbench')); + disposables.add(toDisposable(() => container.remove())); + + cachedTreeView.setVisibility(true); // starts loading the tree + cachedTreeView.show(container); + cachedTreeView.layout(300, 300); + await cachedTreeView.refresh(); // waits for the initial load, which caches every node's children, then refreshes from that cache + + assert.deepStrictEqual( + [...container.querySelectorAll('.monaco-list-row')].map(row => row.getAttribute('aria-label')), + ['P1', 'folder', 'file1', 'P2', 'file2', 'P3', 'file3'] + ); + }); + }); diff --git a/src/vs/workbench/test/browser/workbenchTestServices.ts b/src/vs/workbench/test/browser/workbenchTestServices.ts index 4be8be97959e..7cd7e54f954c 100644 --- a/src/vs/workbench/test/browser/workbenchTestServices.ts +++ b/src/vs/workbench/test/browser/workbenchTestServices.ts @@ -155,7 +155,7 @@ import { CodeEditorService } from '../../services/editor/browser/codeEditorServi import { EditorPaneService } from '../../services/editor/browser/editorPaneService.js'; import { EditorResolverService } from '../../services/editor/browser/editorResolverService.js'; import { CustomEditorLabelService, ICustomEditorLabelService } from '../../services/editor/common/customEditorLabelService.js'; -import { EditorGroupLayout, GroupDirection, GroupOrientation, GroupsArrangement, GroupsOrder, IAuxiliaryEditorPart, ICloseAllEditorsOptions, ICloseEditorOptions, ICloseEditorsFilter, IEditorDropTargetDelegate, IEditorGroup, IEditorGroupActivationEvent, IEditorGroupContextKeyProvider, IEditorGroupsContainer, IEditorGroupsService, IEditorPart, IEditorReplacement, IEditorWorkingSet, IEditorWorkingSetOptions, IFindGroupScope, IMergeGroupOptions, IModalEditorPart, IContentPart } from '../../services/editor/common/editorGroupsService.js'; +import { EditorGroupLayout, GroupDirection, GroupOrientation, GroupsArrangement, GroupsOrder, IAuxiliaryEditorPart, ICloseAllEditorsOptions, ICloseEditorOptions, ICloseEditorsFilter, IEditorDropTargetDelegate, IEditorGroup, IEditorGroupActivationEvent, IEditorGroupContextKeyProvider, IEditorGroupsContainer, IEditorGroupsService, IEditorPart, IEditorReplacement, IEditorWorkingSet, IEditorWorkingSetOptions, IFindGroupScope, IMergeGroupOptions, IModalEditorPart, IContentPart, IResolvedEditorWorkingSet } from '../../services/editor/common/editorGroupsService.js'; import { IEditorPaneService } from '../../services/editor/common/editorPaneService.js'; import { IEditorResolverService } from '../../services/editor/common/editorResolverService.js'; import { IEditorsChangeEvent, IEditorService, IRevertAllEditorsOptions, ISaveEditorsOptions, ISaveEditorsResult, IVisibleEditorsChangeEvent, PreferredGroup } from '../../services/editor/common/editorService.js'; @@ -682,6 +682,7 @@ export class TestLayoutService implements IWorkbenchLayoutService { hasFocus(_part: Parts): boolean { return false; } isFloatingPanelsEnabled(): boolean { return false; } isModernUICompact(): boolean { return false; } + getPanelSpacing(): number { return this.isModernUICompact() ? 0 : 4; } focusPart(_part: Parts): void { } hasMainWindowBorder(): boolean { return false; } getMainWindowBorderRadius(): string | undefined { return undefined; } @@ -928,6 +929,7 @@ export class TestEditorGroupsService implements IEditorGroupsService { saveWorkingSet(name: string): IEditorWorkingSet { throw new Error('Method not implemented.'); } getWorkingSets(): IEditorWorkingSet[] { throw new Error('Method not implemented.'); } applyWorkingSet(workingSet: IEditorWorkingSet | 'empty', options?: IEditorWorkingSetOptions): Promise<boolean> { throw new Error('Method not implemented.'); } + resolveWorkingSet(workingSet: IEditorWorkingSet): IResolvedEditorWorkingSet | undefined { throw new Error('Method not implemented.'); } deleteWorkingSet(workingSet: IEditorWorkingSet): Promise<boolean> { throw new Error('Method not implemented.'); } getGroups(_order?: GroupsOrder): readonly IEditorGroup[] { return this.groups; } getGroup(identifier: number): IEditorGroup | undefined { return this.groups.find(group => group.id === identifier); } @@ -995,6 +997,7 @@ export class TestEditorGroupView implements IEditorGroupView { titleHeight!: IEditorGroupTitleHeight; isEmpty = true; + isOpeningEditor = false; readonly onWillDispose: Event<void> = Event.None; readonly onDidModelChange: Event<IGroupModelChangeEvent> = Event.None; @@ -1744,6 +1747,7 @@ export class TestEditorPart extends MainEditorPart implements IEditorGroupsServi saveWorkingSet(name: string): IEditorWorkingSet { throw new Error('Method not implemented.'); } getWorkingSets(): IEditorWorkingSet[] { throw new Error('Method not implemented.'); } applyWorkingSet(workingSet: IEditorWorkingSet | 'empty', options?: IEditorWorkingSetOptions): Promise<boolean> { throw new Error('Method not implemented.'); } + resolveWorkingSet(workingSet: IEditorWorkingSet): IResolvedEditorWorkingSet | undefined { throw new Error('Method not implemented.'); } deleteWorkingSet(workingSet: IEditorWorkingSet): Promise<boolean> { throw new Error('Method not implemented.'); } registerContextKeyProvider<T extends ContextKeyValue>(provider: IEditorGroupContextKeyProvider<T>): IDisposable { throw new Error('Method not implemented.'); } @@ -2221,6 +2225,7 @@ export class TestChatWidgetService implements IChatWidgetService { async reveal(widget: IChatWidget, preserveFocus?: boolean): Promise<boolean> { return false; } async revealWidget(preserveFocus?: boolean): Promise<IChatWidget | undefined> { return undefined; } + async revealChatView(preserveFocus?: boolean): Promise<IChatWidget | undefined> { return undefined; } getAllWidgets(): ReadonlyArray<IChatWidget> { return []; } getWidgetByInputUri(uri: URI): IChatWidget | undefined { return undefined; } openSession(sessionResource: URI): Promise<IChatWidget | undefined>; diff --git a/src/vs/workbench/test/common/agentsColors.test.ts b/src/vs/workbench/test/common/agentsColors.test.ts new file mode 100644 index 000000000000..7ae69ad8c683 --- /dev/null +++ b/src/vs/workbench/test/common/agentsColors.test.ts @@ -0,0 +1,61 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { editorWarningForeground } from '../../../platform/theme/common/colors/editorColors.js'; +import { listWarningForeground } from '../../../platform/theme/common/colors/listColors.js'; +import { ColorScheme, isHighContrast } from '../../../platform/theme/common/theme.js'; +import { agentSessionNeedsInputForeground, agentsBackground } from '../../common/agentsColors.js'; +import { ColorThemeData } from '../../services/themes/common/colorThemeData.js'; + +suite('Agent session colors', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + const expectedColors = { + [ColorScheme.DARK]: '#cca700', + [ColorScheme.LIGHT]: '#b36b00', + [ColorScheme.HIGH_CONTRAST_DARK]: '#ffd370', + [ColorScheme.HIGH_CONTRAST_LIGHT]: '#806600', + }; + + for (const scheme of Object.values(ColorScheme)) { + test(`needs-input indicator is opaque and contrasts with its row in ${scheme}`, () => { + const theme = ColorThemeData.createUnloadedThemeForThemeType(scheme); + const foreground = theme.getColor(agentSessionNeedsInputForeground)!; + const background = theme.getColor(agentsBackground)!; + const rowBackground = isHighContrast(scheme) ? background : foreground.transparent(0.08).makeOpaque(background); + + assert.deepStrictEqual({ + color: foreground.toString(), + opaque: foreground.isOpaque(), + contrastsWithRow: foreground.getContrastRatio(rowBackground) >= 3, + }, { + color: expectedColors[scheme], + opaque: true, + contrastsWithRow: true, + }); + }); + + test(`needs-input color is customizable independently of warning colors in ${scheme}`, () => { + const theme = ColorThemeData.createUnloadedThemeForThemeType(scheme, { + [listWarningForeground]: '#123456', + [editorWarningForeground]: '#654321', + }); + const inheritedColor = theme.getColor(agentSessionNeedsInputForeground)?.toString(); + theme.setCustomColors({ [agentSessionNeedsInputForeground]: '#abcdef' }); + + assert.deepStrictEqual({ + inheritedColor, + customColor: theme.getColor(agentSessionNeedsInputForeground)?.toString(), + warningColor: theme.getColor(listWarningForeground)?.toString(), + }, { + inheritedColor: scheme === ColorScheme.DARK ? '#123456' : scheme === ColorScheme.HIGH_CONTRAST_DARK ? '#654321' : expectedColors[scheme], + customColor: '#abcdef', + warningColor: '#123456', + }); + }); + } +}); diff --git a/src/vs/workbench/test/common/chatIssue.test.ts b/src/vs/workbench/test/common/chatIssue.test.ts index c47a1f29ff62..d416b6db78b5 100644 --- a/src/vs/workbench/test/common/chatIssue.test.ts +++ b/src/vs/workbench/test/common/chatIssue.test.ts @@ -18,7 +18,7 @@ suite('Chat Issue Icons', () => { computeIssueIcon('closed', 'duplicate'), ]; assert.deepStrictEqual(icons.map(icon => ({ id: icon.id, color: icon.color?.id })), [ - { id: 'issue-opened', color: 'charts.green' }, + { id: 'issues', color: 'charts.green' }, { id: 'issue-closed', color: 'charts.purple' }, { id: 'issue-closed', color: 'descriptionForeground' }, { id: 'issue-closed', color: 'descriptionForeground' }, @@ -34,9 +34,9 @@ suite('Chat Issue Icons', () => { computeAggregateIssueIcon([{ state: 'closed', stateReason: 'not_planned' }, { state: 'closed', stateReason: 'duplicate' }]), ]; assert.deepStrictEqual(icons.map(icon => ({ id: icon.id, color: icon.color?.id })), [ - { id: 'issue-opened', color: 'charts.green' }, - { id: 'issue-opened', color: 'charts.green' }, - { id: 'issue-opened', color: 'charts.green' }, + { id: 'issues', color: 'charts.green' }, + { id: 'issues', color: 'charts.green' }, + { id: 'issues', color: 'charts.green' }, { id: 'issue-closed', color: 'charts.purple' }, { id: 'issue-closed', color: 'descriptionForeground' }, ]); diff --git a/src/vs/workbench/test/electron-browser/nativeMenubarControl.test.ts b/src/vs/workbench/test/electron-browser/nativeMenubarControl.test.ts new file mode 100644 index 000000000000..c824dfec10bc --- /dev/null +++ b/src/vs/workbench/test/electron-browser/nativeMenubarControl.test.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 assert from 'assert'; +import { DeferredPromise } from '../../../base/common/async.js'; +import { Event } from '../../../base/common/event.js'; +import { KeyCode } from '../../../base/common/keyCodes.js'; +import { KeyCodeChord } from '../../../base/common/keybindings.js'; +import { isMacintosh, OperatingSystem } from '../../../base/common/platform.js'; +import { mock } from '../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { IMenu, IMenuService } from '../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../platform/commands/common/commands.js'; +import { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js'; +import { USLayoutResolvedKeybinding } from '../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; +import { IMenubarData } from '../../../platform/menubar/common/menubar.js'; +import { IMenubarService } from '../../../platform/menubar/electron-browser/menubar.js'; +import { INativeHostService } from '../../../platform/native/common/native.js'; +import { IUpdateService, State } from '../../../platform/update/common/update.js'; +import { NativeMenubarControl } from '../../electron-browser/parts/titlebar/menubarControl.js'; +import { IPreferencesService } from '../../services/preferences/common/preferences.js'; +import { TestMenuService, workbenchInstantiationService } from '../browser/workbenchTestServices.js'; +import { TestNativeHostService } from './workbenchTestServices.js'; + +class EmptyMenubarMenuService extends TestMenuService { + override createMenu(): IMenu { + return { + onDidChange: Event.None, + dispose: () => { }, + getActions: () => [['', []]] + }; + } +} + +suite('NativeMenubarControl', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + const commandId = 'workbench.action.toggleWindowAlwaysOnTop'; + const shortcut = new USLayoutResolvedKeybinding([new KeyCodeChord(true, false, false, false, KeyCode.KeyT)], OperatingSystem.Macintosh); + const chord = new USLayoutResolvedKeybinding([ + new KeyCodeChord(true, false, false, false, KeyCode.KeyK), + new KeyCodeChord(true, false, false, false, KeyCode.KeyT) + ], OperatingSystem.Macintosh); + + for (const { name, binding, expected } of [ + { name: 'native shortcut', binding: shortcut, expected: { label: 'Ctrl+T', userSettingsLabel: 'ctrl+t' } }, + { name: 'chord', binding: chord, expected: { label: chord.getLabel(), isNative: false, userSettingsLabel: 'ctrl+k ctrl+t' } }, + { name: 'no shortcut', binding: undefined, expected: undefined } + ]) { + (isMacintosh ? test : test.skip)(`forwards Always on Top keybinding metadata with ${name}`, async () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(INativeHostService, new TestNativeHostService()); + instantiationService.stub(IMenuService, new EmptyMenubarMenuService()); + instantiationService.stub(IUpdateService, new class extends mock<IUpdateService>() { + override readonly onStateChange = Event.None; + override readonly state = State.Uninitialized; + }); + instantiationService.stub(IPreferencesService, new class extends mock<IPreferencesService>() { }); + instantiationService.stub(ICommandService, new class extends mock<ICommandService>() { }); + instantiationService.stub(IKeybindingService, 'lookupKeybinding', (id: string) => id === commandId ? binding : shortcut); + const update = new DeferredPromise<IMenubarData>(); + instantiationService.stub(IMenubarService, { + updateMenubar: async (_windowId: number, data: IMenubarData) => { await update.complete(data); } + }); + + store.add(instantiationService.createInstance(NativeMenubarControl)); + const data = await update.p; + + assert.deepStrictEqual(data.keybindings, { + 'workbench.action.quit': { label: 'Ctrl+T', userSettingsLabel: 'ctrl+t' }, + ...(expected ? { [commandId]: expected } : {}) + }); + }); + } +}); diff --git a/src/vs/workbench/test/electron-browser/windowActions.test.ts b/src/vs/workbench/test/electron-browser/windowActions.test.ts new file mode 100644 index 000000000000..f24dbc408ceb --- /dev/null +++ b/src/vs/workbench/test/electron-browser/windowActions.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 sinon from 'sinon'; +import { mainWindow } from '../../../base/browser/window.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { TestInstantiationService } from '../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { INativeHostService } from '../../../platform/native/common/native.js'; +import { ToggleWindowAlwaysOnTopAction } from '../../electron-browser/actions/windowActions.js'; + +suite('ToggleWindowAlwaysOnTopAction', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('toggles always on top for the main window', async () => { + const instantiationService = store.add(new TestInstantiationService()); + const toggleWindowAlwaysOnTop = sinon.stub().resolves(); + instantiationService.stub(INativeHostService, { toggleWindowAlwaysOnTop }); + + await new ToggleWindowAlwaysOnTopAction().run(instantiationService); + + assert.deepStrictEqual(toggleWindowAlwaysOnTop.args, [[{ targetWindowId: mainWindow.vscodeWindowId }]]); + }); + + test('propagates native failures when toggling the main window', async () => { + const instantiationService = store.add(new TestInstantiationService()); + const error = new Error('Unable to change window level'); + instantiationService.stub(INativeHostService, { toggleWindowAlwaysOnTop: sinon.stub().rejects(error) }); + + await assert.rejects(new ToggleWindowAlwaysOnTopAction().run(instantiationService), error); + }); +}); diff --git a/src/vs/workbench/workbench.common.main.ts b/src/vs/workbench/workbench.common.main.ts index ea647deaeae6..de5193a270a3 100644 --- a/src/vs/workbench/workbench.common.main.ts +++ b/src/vs/workbench/workbench.common.main.ts @@ -142,6 +142,7 @@ import './services/inlineCompletions/common/inlineCompletionsUnification.js'; import './services/chat/common/chatEntitlementService.js'; import './services/agentHost/common/agentHostResourceService.js'; import '../platform/agentHost/browser/agentHostConnectionsService.js'; +import '../platform/agentHost/browser/remoteAgentHostLocationPreferenceService.js'; import './services/log/common/defaultLogLevels.js'; import { InstantiationType, registerSingleton } from '../platform/instantiation/common/extensions.js'; @@ -239,6 +240,7 @@ import './contrib/agentsVoice/browser/agentsVoice.contribution.js'; import './contrib/mcp/browser/mcp.contribution.js'; import './contrib/mcp/browser/mcp.view.contribution.js'; import './contrib/chat/browser/chatSessions/chatSessions.contribution.js'; +import './contrib/sessions/browser/editorWindow/editorWindowSessions.contribution.js'; import './contrib/chat/browser/contextContrib/chatContext.contribution.js'; import './contrib/imageCarousel/browser/imageCarousel.contribution.js'; @@ -406,6 +408,7 @@ import './contrib/welcomeOnboarding/browser/welcomeOnboarding.contribution.js'; import './contrib/onboarding/browser/onboarding.contribution.js'; import './contrib/chat/browser/onboarding/modelPickerTryout.contribution.js'; import './contrib/chat/browser/onboarding/chatInputSpotlightTour.js'; +import './contrib/chat/browser/onboarding/agentPickerSpotlight.contribution.js'; import './contrib/codeEditor/browser/diffEditorTryout.contribution.js'; // Call Hierarchy @@ -454,6 +457,7 @@ import './contrib/workspace/browser/workspace.contribution.js'; // Workspaces import './contrib/workspaces/browser/workspaces.contribution.js'; +import './contrib/workspaces/browser/folderLocationWorkingSets.contribution.js'; // List import './contrib/list/browser/list.contribution.js'; diff --git a/src/vscode-dts/vscode.proposed.chatArtifactIntegrations.d.ts b/src/vscode-dts/vscode.proposed.chatArtifactIntegrations.d.ts index cd4764daa660..2a0a73aaff83 100644 --- a/src/vscode-dts/vscode.proposed.chatArtifactIntegrations.d.ts +++ b/src/vscode-dts/vscode.proposed.chatArtifactIntegrations.d.ts @@ -98,8 +98,8 @@ declare module 'vscode' { /** * Gives this artifact a pill of its own, shared with every other artifact assigned the same ID, including those of * other providers, and named by {@link ChatArtifactIntegrationProvider.groupLabel}. Without one, the artifact is listed - * in the pill for its kind, such as Artifacts, with the other artifacts. Only consulted when this provider presents - * the artifact's main part. + * in the pill for its kind, such as Artifacts, with the other artifacts. References are always listed in the + * References pill with the other references. Only consulted when this provider presents the artifact's main part. */ readonly groupId?: string; /** diff --git a/src/vscode-dts/vscode.proposed.contribChatDockedViews.d.ts b/src/vscode-dts/vscode.proposed.contribChatDockedViews.d.ts new file mode 100644 index 000000000000..9267a8fab8db --- /dev/null +++ b/src/vscode-dts/vscode.proposed.contribChatDockedViews.d.ts @@ -0,0 +1,11 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// empty placeholder declaration for the `chatDockedViews` contribution point + +// The `chatDockedViews` contribution point docks a view above the input of every chat whose per-chat resource +// exists, toggled by a pill. Each entry has an `id`, a `label`, an optional `icon`, and a `resource` URI template +// in which `${chatSessionId}` is replaced with the last path segment of the chat's session resource. The view is +// the resource's custom editor (see `customEditors`), shown readonly and sized to the height of its content. diff --git a/src/vscode-dts/vscode.proposed.contribChatResources.d.ts b/src/vscode-dts/vscode.proposed.contribChatResources.d.ts new file mode 100644 index 000000000000..c5588a168c40 --- /dev/null +++ b/src/vscode-dts/vscode.proposed.contribChatResources.d.ts @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// empty placeholder declaration for the `chatResources` contribution point + +// The `chatResources` contribution point adds a resource to every chat whose resource exists. Each entry has an `id`, a +// `label`, an optional `icon`, and a `resource` URI template in which `${chatSessionId}` is replaced with the agent host's +// identifier of the chat and `${agentSessionId}` with the agent host's identifier of the session, the `<id>` of +// `ahp-session:/<id>`, which agents get from the `get_current_session` tool. While the resource exists, the chat lists it in its Artifacts pill, where it can be pinned and shown above +// the chat input, rendered by its default editor (for example a custom editor). Whatever makes the resource exist, such as +// the extension's file system provider or a tool that writes a file, makes it appear. diff --git a/src/vscode-dts/vscode.proposed.contribTitleBar.d.ts b/src/vscode-dts/vscode.proposed.contribTitleBar.d.ts new file mode 100644 index 000000000000..ff7c4a30f16f --- /dev/null +++ b/src/vscode-dts/vscode.proposed.contribTitleBar.d.ts @@ -0,0 +1,6 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// empty placeholder declaration for the `titleBar` and `agents/titleBar` menus diff --git a/src/vscode-dts/vscode.proposed.github.d.ts b/src/vscode-dts/vscode.proposed.github.d.ts deleted file mode 100644 index b44d45b8dae7..000000000000 --- a/src/vscode-dts/vscode.proposed.github.d.ts +++ /dev/null @@ -1,196 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -declare module 'vscode' { - - /** - * Typed access to GitHub through the editor's shared GitHub service. - * - * Requests are executed by the editor, which owns request scheduling, rate-limit handling, proxy - * configuration and credentials. Access tokens are never exposed through this API. - */ - export namespace github { - - /** - * Get a client whose requests are authenticated with an existing GitHub.com authentication - * session from the `github` authentication provider. - * - * The extension is responsible for choosing the session, for example with - * `authentication.getSession('github', ...)`. Acquisition never prompts, never signs in, and never - * substitutes another account: it fails with a {@link GitHubError} whose code is - * `authentication` when the session does not exist in the `github` provider, is no longer - * available, or the calling extension has not been granted access to its account. When the - * session is later signed out or the extension's access is revoked, requests made with the client - * fail with the same code. - * - * @param sessionId The {@link AuthenticationSession.id id} of a `github` provider session to bind. - * @param token A cancellation token for the acquisition only; it does not limit the client's lifetime. - * @returns A client that must be {@link GitHubClient.dispose disposed} when no longer needed. - */ - export function getClient(sessionId: string, token?: CancellationToken): Thenable<GitHubClient>; - - /** - * Get a client for public, read-only GitHub.com data. Its requests never carry credentials, - * even when the user is signed in. - * - * @param token A cancellation token for the acquisition only; it does not limit the client's lifetime. - * @returns A client that must be {@link GitHubAnonymousClient.dispose disposed} when no longer needed. - */ - export function getAnonymousClient(token?: CancellationToken): Thenable<GitHubAnonymousClient>; - } - - /** - * A client for public GitHub data. - * - * {@link Disposable.dispose Disposing} the client releases it: outstanding requests are cancelled - * and later requests fail with a {@link GitHubError} whose code is `disposed`. - */ - export interface GitHubAnonymousClient extends Disposable { - /** - * Read access to gists. - */ - readonly gists: GitHubGistReader; - } - - /** - * A client bound to one GitHub authentication session. - * - * {@link Disposable.dispose Disposing} the client releases it: outstanding requests are cancelled - * and later requests fail with a {@link GitHubError} whose code is `disposed`. - */ - export interface GitHubClient extends Disposable { - /** - * Gist retrieval and creation. - */ - readonly gists: GitHubGists; - } - - /** - * Gist read operations. - */ - export interface GitHubGistReader { - /** - * Get a gist, including the inline content of its files. - * - * @param gistId The gist identifier. - * @param token A cancellation token. - */ - get(gistId: string, token?: CancellationToken): Thenable<GitHubGist>; - } - - /** - * Gist read and write operations. - */ - export interface GitHubGists extends GitHubGistReader { - /** - * Create a gist owned by the client's account. The session must have the `gist` scope. - * - * Gist creation is not retried. A cancellation that arrives after the request was sent may - * not prevent the gist from being created. - * - * @param gist The gist to create. - * @param token A cancellation token. - */ - create(gist: GitHubGistCreateOptions, token?: CancellationToken): Thenable<GitHubGist>; - } - - /** - * The contents of a gist to create. - */ - export interface GitHubGistCreateOptions { - /** - * Whether the gist is public. Defaults to `false`, which creates a secret gist: it is not - * listed publicly, but anyone with its URL can read it. - */ - readonly public?: boolean; - - /** - * One or more files keyed by file name. File names must not contain `/` or `\`. - */ - readonly files: { readonly [fileName: string]: { readonly content: string } }; - } - - /** - * A gist and the inline content of its files. - */ - export interface GitHubGist { - /** - * The gist identifier. - */ - readonly id: string; - - /** - * The gist's page on GitHub. - */ - readonly htmlUrl: Uri; - - /** - * The gist's files, in the order returned by GitHub. - */ - readonly files: readonly GitHubGistFile[]; - } - - /** - * A gist file with its inline content. - */ - export interface GitHubGistFile { - /** - * The inline file content. It is base64-encoded when {@link GitHubGistFile.isBinary isBinary} - * is `true`, and incomplete when {@link GitHubGistFile.truncated truncated} is `true`. - */ - readonly content: string; - - /** - * Whether GitHub treats the file as binary, in which case {@link GitHubGistFile.content content} - * is base64-encoded. - */ - readonly isBinary: boolean; - - /** - * Whether {@link GitHubGistFile.content content} contains only part of the file. - */ - readonly truncated: boolean; - } - - /** - * Categories of {@link GitHubError GitHub errors}. - * - * - `authentication`: the session is unavailable, signed out, not accessible to the extension, or was rejected. - * - `authorization`: the account is not permitted to perform the operation. - * - `notFound`: the resource does not exist or is not visible to the client. - * - `validation`: the request was invalid. - * - `rateLimit`: the request was rejected by rate limits or local admission control. - * - `network`: the request could not reach GitHub. - * - `timeout`: the request did not complete in time. - * - `server`: GitHub reported a server failure. - * - `invalidResponse`: GitHub returned a response that could not be used. - * - `disposed`: the client was disposed. - * - `unknown`: any other failure. - */ - export type GitHubErrorCode = 'authentication' | 'authorization' | 'notFound' | 'validation' | 'rateLimit' | 'network' | 'timeout' | 'server' | 'invalidResponse' | 'disposed' | 'unknown'; - - /** - * An error reported by a GitHub client. Cancellation is reported with a {@link CancellationError}. - */ - export class GitHubError extends Error { - - /** - * The error category. - */ - readonly code: GitHubErrorCode; - - /** - * The HTTP status reported by GitHub, if any. - */ - readonly status: number | undefined; - - /** - * @param message A human-readable message. - * @param code The error category. - * @param status The HTTP status, if any. - */ - constructor(message: string, code: GitHubErrorCode, status?: number); - } -} diff --git a/src/vscode-dts/vscode.proposed.structuralDiff.d.ts b/src/vscode-dts/vscode.proposed.structuralDiff.d.ts new file mode 100644 index 000000000000..f2943c1a08b1 --- /dev/null +++ b/src/vscode-dts/vscode.proposed.structuralDiff.d.ts @@ -0,0 +1,323 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +declare module 'vscode' { + + /** + * A textual change between the original and modified documents. + * + * Ranges use zero-based lines and UTF-16 character offsets, with an exclusive end. + * The editor compares UTF-16 code units, so a change can start or end between the + * two code units of a character such as an emoji. + * Replacement ranges need not have the same length. + * + * For example, if the first line of the original document is `foo(a, b)`: + * - Deletion: removing `, b` gives `foo(a)`. The original range is + * `new Range(0, 5, 0, 8)`, which covers `, b`. The modified range is the empty + * range `new Range(0, 5, 0, 5)`, the position between `a` and `)`. + * - Change: replacing `b` with `42` gives `foo(a, 42)`. The original range is + * `new Range(0, 7, 0, 8)`, which covers `b`. The modified range is + * `new Range(0, 7, 0, 9)`, which covers `42`. + * - Insertion: adding `, c` gives `foo(a, b, c)`. The original range is the empty + * range `new Range(0, 8, 0, 8)`, the position between `b` and `)`. The modified + * range is `new Range(0, 8, 0, 11)`, which covers `, c`. + */ + export interface DiffTextChange { + /** + * The changed range in the original document. Empty for an insertion, where it + * is the position at which the text is inserted. + */ + readonly originalRange: Range; + + /** + * The changed range in the modified document. Empty for a deletion, where it + * is the position at which the text was deleted. + * At least one of the two ranges must be non-empty. + */ + readonly modifiedRange: Range; + } + + /** + * Textual changes for a structural diff request. + */ + export interface StructuralDiffContext { + /** + * Textual changes computed by the editor, ordered by source position and + * non-overlapping in each document. As in the diff editor, a change can + * include short unchanged text that makes it easier to read, such as the + * rest of a changed word or short text that would otherwise separate two + * changes. + * + * Providers classify these changes, including such unchanged text, rather + * than computing another textual diff. Changes can be smaller than a line. + * Array indices identify changes within this request. + */ + readonly changes: readonly DiffTextChange[]; + } + + /** + * A structural item, such as a class or a function, as it appears in one document. + */ + export interface StructuralDiffItem { + /** + * The name of the item. + */ + readonly name: string; + + /** + * Optional display detail, such as a function signature. + */ + readonly detail?: string; + + /** + * A language-independent symbol category. + */ + readonly kind: SymbolKind; + + /** + * The complete range of the item in the corresponding document. + */ + readonly range: Range; + + /** + * The range to select when navigating to this item. + * Must be contained in {@link StructuralDiffItem.range range}. + */ + readonly selectionRange?: Range; + } + + /** + * The syntactic role of changed text. Classification does not imply + * behavioral equivalence, impact, or safety. + */ + export enum StructuralDiffClassification { + /** + * A complete item was introduced or removed. + */ + Declaration = 1, + + /** + * An item's header, including its signature, modifiers, attributes, + * decorators, or inheritance clauses. + */ + Header = 2, + + /** + * Executable statements, expressions, or implementation details. + */ + Implementation = 3, + + /** + * Imports, includes, or equivalent dependency declarations. + */ + Dependency = 4, + + /** + * Changed text not covered by another classification. This does not + * indicate an analysis failure. + */ + Other = 5, + } + + /** + * Additional information about classified text. + */ + export enum StructuralDiffTag { + /** + * The classified text belongs to test code. The absence of this tag + * does not guarantee that the text is not test code. + */ + Test = 1, + } + + /** + * Classification of a portion of one supplied textual change, in either + * the original or modified document. + */ + export interface StructuralDiffCoverage { + /** + * A zero-based index into {@link StructuralDiffContext.changes}. + */ + readonly textChangeIndex: number; + + /** + * A non-empty range contained in the corresponding side of the + * referenced textual change and in the range of the containing node's + * item in the same document. + * + * The containing node's {@link StructuralDiffNode.originalChanges originalChanges} + * or {@link StructuralDiffNode.modifiedChanges modifiedChanges} property + * determines which document this range refers to. + */ + readonly range: Range; + + /** + * The syntactic role of this range. + */ + readonly classification: StructuralDiffClassification; + + /** + * Optional additional information about this range. + */ + readonly tags?: readonly StructuralDiffTag[]; + } + + /** + * A node in a sparse, file-local structural diff tree. + * + * A node with both versions asserts that the items correspond; different names + * on those versions represent a detected rename. Providers + * are not required to detect renames or moves. Unmatched items can be + * represented as separate additions and deletions. + */ + export interface StructuralDiffNode { + /** + * An identifier unique within this result. Stability across requests + * is not implied. + */ + readonly id: string; + + /** + * The item in the original document. Absent when the item was added. + */ + readonly originalItem?: StructuralDiffItem; + + /** + * The item in the modified document. Absent when the item was removed. + * At least one of originalItem or modifiedItem must be present. + */ + readonly modifiedItem?: StructuralDiffItem; + + /** + * Original-side changes owned directly by this node, excluding coverage + * owned by descendants. Must be empty when originalItem is absent. + */ + readonly originalChanges: readonly StructuralDiffCoverage[]; + + /** + * Modified-side changes owned directly by this node, excluding coverage + * owned by descendants. Must be empty when modifiedItem is absent. + */ + readonly modifiedChanges: readonly StructuralDiffCoverage[]; + + /** + * Changed descendants and the ancestors needed to contain them. A node + * is changed if a supplied textual change intersects its range in a + * document in which it exists. Unchanged subtrees are omitted. An + * ancestor retained for context can have no directly owned changes. + * Can be omitted when the node has no changed descendants. + * + * Parenthood represents lexical containment, not semantic ownership. + * On each side where a child exists, its parent must also exist and its + * range must contain the child's range. A structural move that cannot + * satisfy this shared hierarchy can be represented as a deletion and + * an addition. + */ + readonly children?: readonly StructuralDiffNode[]; + } + + /** + * A structural interpretation of the supplied textual changes. + */ + export interface StructuralDiff { + /** + * A source-file node with {@link SymbolKind.File} on both sides and + * ranges covering the complete respective documents. File-level changes + * belong directly to this node. + * + * When the documents are identical, the root has no changes or children. + */ + readonly root: StructuralDiffNode; + + /** + * Whether some supplied changed text could not be classified. + * + * For a complete result, every non-empty side of every supplied textual + * change must be covered exactly once across the tree. Coverage must + * not overlap on the same side, including between ancestors and descendants. + * + * An incomplete result may omit coverage but must otherwise satisfy the + * same invariants. Providers should not use + * {@link StructuralDiffClassification.Other} to hide analysis failures. + */ + readonly isIncomplete: boolean; + } + + /** + * The result of executing the `vscode.executeStructuralDiffProvider` command, + * which takes the {@link Uri uris} of the original and the modified document + * and resolves to `undefined` when no provider supplies a result. + * + * The command rejects when the textual diff does not complete within the time + * configured by the `diffEditor.maxComputationTime` setting, because the + * textual changes would be incomplete. + */ + export interface StructuralDiffResult extends StructuralDiff { + /** + * The textual changes that were classified. The + * {@link StructuralDiffCoverage.textChangeIndex textChangeIndex} of a coverage + * is an index into {@link StructuralDiffContext.changes}. + */ + readonly context: StructuralDiffContext; + } + + /** + * Provides language-specific structural interpretation of textual changes. + */ + export interface StructuralDiffProvider { + /** + * Provides a file-local structural diff for two versions of a document. + * + * Ranges in the result refer to the respective input documents. The editor + * captures their versions before dispatch and cancels and discards the + * request if either document changes. Providers must honor cancellation + * and must not mix content from different document versions. + * + * The two versions need not exist as separate files on disk. A provider + * may use the same backing `file:` URI for language-service identity, but + * must analyze each supplied document's contents rather than the backing + * file's current disk contents. + * + * @param originalDocument The original version of the document. + * @param modifiedDocument The modified version of the document. + * @param context The paired textual changes to classify. + * @param token A cancellation token. + * @returns A structural diff, or `undefined` or `null` when the provider + * cannot supply a result. Failures should be reported by throwing an + * error or returning a rejected promise. A result that does not satisfy the + * requirements described on {@link StructuralDiff} and its members is + * treated as a failure. + */ + provideStructuralDiff(originalDocument: TextDocument, modifiedDocument: TextDocument, context: StructuralDiffContext, token: CancellationToken): ProviderResult<StructuralDiff>; + } + + export namespace languages { + + /** + * Registers a structural diff provider. + * + * Providers are selected using only the modified document and must support + * analyzing both supplied documents. Providers are ordered by their + * {@link languages.match selector score} and queried in sequence. The + * first non-null result is used; trees from different providers are not + * merged. A failing provider does not prevent querying another provider. + * + * The original document need not match the selector and may use a different + * URI scheme. For example, Git working-tree changes pair a `git:` original + * with a `file:` modified document, whereas staged changes pair two `git:` + * documents. + * + * Structural diffs can be requested for documents that are not open, and the + * editor only offers them while a provider is registered. Register providers + * when the extension activates instead of waiting for a language-specific + * activation event such as `onLanguage`. + * + * @param selector A selector for modified documents. + * @param provider A structural diff provider. + * @returns A disposable that unregisters the provider. + */ + export function registerStructuralDiffProvider(selector: DocumentSelector, provider: StructuralDiffProvider): Disposable; + } +} diff --git a/test/automation/src/agentsWindow.ts b/test/automation/src/agentsWindow.ts index d627dcb10537..7306daef6d93 100644 --- a/test/automation/src/agentsWindow.ts +++ b/test/automation/src/agentsWindow.ts @@ -363,21 +363,38 @@ export class AgentsWindow { throw new Error(`Timed out selecting Dev Container. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`); } + /** + * Switches the new-session environment from Cloud to This Computer. + * + * The workspace handoff of a window opened with a folder can switch the + * environment to This Computer on its own after startup. That re-renders the + * composer and closes an open Environment picker, so each attempt is bounded + * and the loop ends as soon as the picker no longer shows Cloud. + */ private async selectLocalEnvironment(): Promise<void> { const page = this.code.driver.currentPage; - const cloudEnvironment = page.locator(ENVIRONMENT_PICKER).filter({ hasText: /^Cloud$/ }); + const environmentPicker = page.locator(ENVIRONMENT_PICKER); + const cloudEnvironment = environmentPicker.filter({ hasText: /^Cloud$/ }); + const localEnvironment = page.locator(WORKSPACE_PICKER_ROW).filter({ has: page.getByText('This Computer', { exact: true }) }); const deadline = Date.now() + 60_000; + let lastError: unknown; while (await cloudEnvironment.isVisible()) { - await cloudEnvironment.click(); - const localEnvironment = page.locator(WORKSPACE_PICKER_ROW).filter({ has: page.getByText('This Computer', { exact: true }) }); - if (await localEnvironment.isVisible()) { - await localEnvironment.click(); - await page.locator(ENVIRONMENT_PICKER).filter({ hasText: 'This Computer' }).waitFor(); - return; - } - await page.keyboard.press('Escape'); if (Date.now() >= deadline) { - throw new Error('Timed out waiting for This Computer in the Environment picker'); + throw new Error(`Timed out selecting This Computer in the Environment picker. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`); + } + try { + await cloudEnvironment.click({ timeout: 5_000 }); + if (await localEnvironment.isVisible()) { + await localEnvironment.click({ timeout: 5_000 }); + await environmentPicker.filter({ hasText: 'This Computer' }).waitFor({ timeout: 15_000 }); + return; + } + lastError = new Error('This Computer is not listed in the Environment picker'); + } catch (error) { + lastError = error; + } + if (await environmentPicker.getAttribute('aria-expanded', { timeout: 5_000 }).catch(() => undefined) === 'true') { + await page.keyboard.press('Escape'); } await new Promise(resolve => setTimeout(resolve, 500)); } @@ -653,7 +670,30 @@ export class AgentsWindow { } } - await this.code.waitAndClick(ACTIVE_SESSION_SEND_BUTTON_ENABLED); + await this.clickActiveSessionSendButton(); + } + + /** + * Clicks the enabled send button of the active session. A modal dialog, such as a proxy login dialog opened by a + * concurrent request, swallows the click, so this waits for it to close first, and clicks again if one opened in the + * meantime and the prompt was not sent, which disables the send button or replaces it with the stop button. + */ + private async clickActiveSessionSendButton(): Promise<void> { + const page = this.code.driver.currentPage; + const modalDialog = page.locator('.monaco-dialog-modal-block').first(); + const sendButton = page.locator(ACTIVE_SESSION_SEND_BUTTON_ENABLED).first(); + for (let attempt = 1; ; attempt++) { + await modalDialog.waitFor({ state: 'hidden', timeout: 2 * 60_000 }); + await this.code.waitAndClick(ACTIVE_SESSION_SEND_BUTTON_ENABLED); + if (attempt === 3 || !await modalDialog.isVisible().catch(() => false)) { + return; + } + await modalDialog.waitFor({ state: 'hidden', timeout: 2 * 60_000 }); + if (await sendButton.waitFor({ state: 'detached', timeout: 5_000 }).then(() => true, () => false)) { + return; + } + this.code.logger.log('[agentsWindow] A modal dialog swallowed the click on the send button, clicking it again'); + } } private async _activeSessionContainsResponse(label: string): Promise<boolean> { diff --git a/test/automation/src/chat.ts b/test/automation/src/chat.ts index c9773cbb7690..3f0090623609 100644 --- a/test/automation/src/chat.ts +++ b/test/automation/src/chat.ts @@ -72,17 +72,6 @@ export class Chat { return element?.attributes['data-bound-chat-resource']; } - /** - * Waits until the chat view is bound to a chat session other than - * `previousSessionResource`. Commands that start a new chat in the view - * keep running after the command palette closes, so a message sent before - * the new session is bound lands in the outgoing session and its response - * is never shown. - */ - async waitForChatViewSessionChange(previousSessionResource: string | undefined, retryCount?: number): Promise<void> { - await this.code.waitForElement(CHAT_VIEW_BOUND_SESSION, element => !!element && element.attributes['data-bound-chat-resource'] !== previousSessionResource, retryCount); - } - /** * Waits until the chat view is bound to a local chat session other than * `previousSessionResource`, such as the one `smoketest.openLocalChat` diff --git a/test/componentFixtures/blocks-ci-screenshots.md b/test/componentFixtures/blocks-ci-screenshots.md index 301040abf020..7afd4b4c0ac4 100644 --- a/test/componentFixtures/blocks-ci-screenshots.md +++ b/test/componentFixtures/blocks-ci-screenshots.md @@ -6,6 +6,12 @@ #### baseUI/KeyboardFocusedToggle/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/dfbb0ce3586e7a15bdb7354ff70df81563ed19b5b857c71d7a02e11ef7ad13fd) +#### chat/chatCustomizationsHover/Default/Light +![screenshot](https://hediet-screenshots.azurewebsites.net/images/ee82e7855b504c48ca9487cc06428fa0144b134c8a21f96f25ba1c0c34da7382) + +#### chat/chatCustomizationsHover/MigrationsAndMcpAuthentication/Light +![screenshot](https://hediet-screenshots.azurewebsites.net/images/5e63fb51d5307fd8614817015b731adcd7f18acdaf7230aab5bde94359172c7c) + #### chat/chatPetAccessoryRig/chatPetAccessoryRig/AllAccessoriesFacing/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/53dc97e97d4f9e8d02d144012794cce528d3d25d659149df8c854f7c42e54d74) @@ -79,7 +85,7 @@ ![screenshot](https://hediet-screenshots.azurewebsites.net/images/f530eaa95aa2ca7e7a6f4c3b9a7df82becdba7bd536383e04b1a722070f2f3ec) #### editor/inlineChatZoneWidget/InlineChatZoneWidget/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/149a3762c5eef80f2a1c74385c9d45871821de012a9cc36ecaa8d22858ac1ad2) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/a50c6b1aa065a2b53a2e70cc226298c36bd04617f3163ffe11892fba9b141cf1) #### editor/inlineChatZoneWidget/InlineChatZoneWidgetTerminated/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/8d8b39f9a3dd85453ad1594df888c7ac1908d5c7ed80a5b15238d818a89aeb1b) @@ -115,7 +121,7 @@ ![screenshot](https://hediet-screenshots.azurewebsites.net/images/701b67f35b07c17d6548488179641c4049343144210d1436fff11972acef6ec7) #### sessions/chat/newWidget/newChatWidget/NewSessionAttachedContext/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/60f021f38c2b08175d0eb489f61dbc91f4ecbca12b353b066526f31eb4c796b1) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/bda16146f9fc5332ff4c5a14aae9528b63280cd985eebaacdee9cd54539ea93e) #### sessions/chat/newWidget/newChatWidget/NewSessionAutoModel/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/257a578b04ba15a9979fd399bc49b5e0755b515367349bef17047f94d06b7bf9) @@ -133,7 +139,7 @@ ![screenshot](https://hediet-screenshots.azurewebsites.net/images/6d0ec65bdd8ab2271cf5b1566cbff91a5fca2886d76ae42b602f387f90cc2278) #### sessions/chat/newWidget/newChatWidget/NewSessionPhoneAttachedContext/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/3a798b6c99f178259d7d29f5a2dfec1eaf76363e22fc422ee2543cb8d3d7ce43) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/d36e5b3148dfd452aef5c6dee07be23f33c47b7f0f035cb34f658d3054d4ac5d) #### sessions/chat/newWidget/newChatWidget/NewSessionPhoneWelcomePhrase/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/7cfac85698a7ca7373a9b6d9f22e2ef6ae6177b8ceff6e6a3f9c4737547fc5fd) @@ -169,34 +175,34 @@ ![screenshot](https://hediet-screenshots.azurewebsites.net/images/f42a0f833c857ea204c962b46aee410bd8466c054dc4c0b4b66450fd44150b24) #### sessions/sessionsList/SessionsList_ArchivedNestedChat/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/ff8c3f01d7176e8ccc6124ed5514314ed39fecd306c001e084ea5a8aa7491b0f) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/7940f891e1f2f0bc422276aadcfdaa5a8d932280b01b2ffe5f536cfc60d1682e) #### sessions/sessionsList/SessionsList_CompactArchivedNestedChat/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/7c4c3c5a3300fdcd3998b7634a1c01ad55d2d0ef7cc87598fe49f4d3cedd85c2) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/544e3c4179be8e33bae9d98145b4dbf5ae0d02b9371a8b18257ffb360d5adb86) #### sessions/sessionsList/SessionsList_CompactChatRename/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/133b77cee2dd44df7906261b12cbf019eb0a4dbc2dc9d88a865d04687cdbbf8f) #### sessions/sessionsList/SessionsList_CompactNeedsInput/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/778c3e04d207f63666014e25e3adb8de274a39505e0a38050b9a75a71373f520) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/e973a7bb1098848aeb7083b06dd580e2553b9e3dee82384e9201a7ea62b8d32a) #### sessions/sessionsList/SessionsList_CompactNestedChatActions/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/8806d13377c47bb5e81a5ddda8756bb91d06b05a07b0a997b6a9947311649169) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/28a03ec78b54de1f600a6d58204ec68be7326611dfa25cd87a46edec80ba0356) #### sessions/sessionsList/SessionsList_CompactNestedChatApprovals/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/e6748a205f7f3cebe5e08ed4e64c00355c6a2914c0972a24cfc122d6d020be0a) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/6bb9a9018f47a11b949c63e7f6ecd4e558b8b8c169ed5687bfc37be3cde682f9) #### sessions/sessionsList/SessionsList_CompactNestedChatPrimaryAction/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/ed18223f207e2dd6968527c3594213879ca07b1462e6e91b6cfc233d8578cf20) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/5370914cc0cae9d6dd4677c1610936afde3783bd3b86d05d8890b3a83fe77a83) #### sessions/sessionsList/SessionsList_CompactNestedChats/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/f19102a0fda2488cb430211399995392dc1fa4832d084e0902fed869de64ec5b) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/72a8a6536056d6346030d6f6c7818ac7bf766efbe4bcbf5eb1ff98c1a5dcfc59) #### sessions/sessionsList/SessionsList_CompactSessionRename/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/eae654d7b4ff4c5fc8fb397d7e4439e26cf8db259f67a1c49acbb872b1f63200) #### sessions/sessionsList/SessionsList_CompactUnreadStatusIcons/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/6b55aca75f5a6d0083f5ca287fd06343294ad5db730db2919f1842c96b9f8f2b) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/d9a2ae34e8d118e1006023600907f022d1ef272062c9df74206c5810b11f4152) #### sessions/sessionsList/SessionsList_LightweightNewButton/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/27750194694cd6b4941e11c7752732c04f934269141b93ad9bbd6131217ace45) @@ -205,19 +211,19 @@ ![screenshot](https://hediet-screenshots.azurewebsites.net/images/54f5cf2d72ea720ff9c6f07388c686f91f7541abff62ef516b321588260da824) #### sessions/sessionsList/SessionsList_NarrowHoverToolbar/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/f9131b39316ff95f77330e056a208bcc4ac7a9f23122a237cee65724a99d1f4b) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/7703c4c7a2ec7ef33592293efb5d19ab59b7ab4fd2449ba0697f31de7e6620d0) #### sessions/sessionsList/SessionsList_NestedChatHierarchyGuides/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/33261b5e9c3e809bfd3a44fb4b909884b6e7c21aa864a5322c631b1708604b05) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/b1fa06195e71ecf99c71e868e8f5de999074d0a16ee7752554b32b253305ca2e) #### sessions/sessionsList/SessionsList_PeerChatInProgress/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/099a8af9024eaa3576657cbf8ae184bd4d38d5bedf6cdb776c329f23b02040a9) #### sessions/sessionsList/SessionsList_SelectedKeyboardFocus/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/8ce3a612a7d5f50553d976259d4cbf04007a7d709bd0d7fd6734d57fbe69d271) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/a777f115e04dcc53218597dbe23359a92dc345e18c9ec36559d4b8a6c184b31c) #### sessions/sessionsList/SessionsList_UnreadStatusIcons/Light -![screenshot](https://hediet-screenshots.azurewebsites.net/images/88c647be929c8888beb6c218940f4ed9d6cb02b6cb901851c24dcf4f1d0be5ce) +![screenshot](https://hediet-screenshots.azurewebsites.net/images/665282c67124b517da9ecc4dabf7faea6241974a313f244e92ee21d91c2dd00e) #### workbench/activityBarMenu/CompactActivityBarMenu_CompactDensity/Light ![screenshot](https://hediet-screenshots.azurewebsites.net/images/6dc0ca91d25531aeea79c4b9d145c1fafd7b705047d0805fc69192d1b372e650) diff --git a/test/componentFixtures/playwright/package.json b/test/componentFixtures/playwright/package.json index 1baf0c4978a1..04df31ad6303 100644 --- a/test/componentFixtures/playwright/package.json +++ b/test/componentFixtures/playwright/package.json @@ -1,7 +1,6 @@ { "name": "code-oss-component-fixture-tests", "version": "0.1.0", - "packageManager": "pnpm@12.16.0", "private": true, "license": "MIT", "type": "module", diff --git a/test/componentFixtures/playwright/tests/sessionsListTwistie.spec.ts b/test/componentFixtures/playwright/tests/sessionsListTwistie.spec.ts index af4f84444d3b..a4003f4b3b53 100644 --- a/test/componentFixtures/playwright/tests/sessionsListTwistie.spec.ts +++ b/test/componentFixtures/playwright/tests/sessionsListTwistie.spec.ts @@ -132,7 +132,7 @@ for (const theme of ['Dark', 'Light']) { for (const theme of ['Dark', 'Light', 'DarkHighContrast', 'LightHighContrast']) { for (const { name, fixture, ariaStatus, indicatorClass, color, count } of [ { name: 'unread', fixture: 'SessionsList_CollapsedUnreadSections', ariaStatus: 'contains unread sessions', indicatorClass: '.codicon-circle-filled', color: '--vscode-textLink-foreground', count: 1 }, - { name: 'needs-input', fixture: 'SessionsList_CollapsedNeedsInputSections', ariaStatus: 'session needs attention', indicatorClass: '.codicon-report-question', color: '--vscode-list-warningForeground', count: 2 }, + { name: 'needs-input', fixture: 'SessionsList_CollapsedNeedsInputSections', ariaStatus: 'session needs attention', indicatorClass: '.codicon-report-question', color: '--vscode-agentSessionNeedsInput-foreground', count: 2 }, { name: 'CI-failure', fixture: 'SessionsList_CollapsedCIFailureSections', ariaStatus: 'session has failing CI checks', indicatorClass: '.codicon-circle-filled', color: '--vscode-list-warningForeground', count: 2 }, ]) { test.describe(`collapsed section ${name} indicators (${theme})`, () => { diff --git a/test/integration/browser/src/index.ts b/test/integration/browser/src/index.ts index a77e0f556607..ab0701384ce6 100644 --- a/test/integration/browser/src/index.ts +++ b/test/integration/browser/src/index.ts @@ -18,6 +18,9 @@ import { promises } from 'fs'; const root = path.join(__dirname, '..', '..', '..', '..'); const logsPath = path.join(root, '.build', 'logs', 'integration-tests-browser'); +// Set once the tests finished and the runner stops the server itself; any other server exit fails the run. +let serverStopRequested = false; + const args = minimist(process.argv.slice(2), { string: [ // path to the workspace (folder or *.code-workspace file) to open in the test @@ -117,6 +120,7 @@ async function runTestsInBrowser(browserType: BrowserType, browserChannel: Brows } try { + serverStopRequested = true; await promisify(kill)(server.pid!); } catch (error) { console.error(`Error when killing server process tree (pid: ${server.pid}): ${error}`); @@ -188,6 +192,8 @@ async function launchServer(browserType: BrowserType, browserChannel: BrowserCha const env = { VSCODE_BROWSER: browserChannel ? `${browserType}-${browserChannel}` : browserType, + // The server records why it exits in server-exit-diagnostics.log in its logs directory. + VSCODE_SERVER_EXIT_DIAGNOSTICS: '1', ...process.env }; @@ -214,7 +220,10 @@ async function launchServer(browserType: BrowserType, browserChannel: BrowserCha console.log(`Storing log files into '${serverLogsPath}'`); serverArgs.push('--logsPath', serverLogsPath); - const stdio: cp.StdioOptions = args.debug ? 'pipe' : ['ignore', 'pipe', 'ignore']; + const maxServerStderr = 8 * 1024; + let serverStderr = ''; + + const stdio: cp.StdioOptions = args.debug ? 'pipe' : ['ignore', 'pipe', 'pipe']; const shell: boolean = (process.platform === 'win32'); const serverProcess = cp.spawn( serverLocation, @@ -225,8 +234,35 @@ async function launchServer(browserType: BrowserType, browserChannel: BrowserCha if (args.debug) { serverProcess.stderr!.on('data', error => console.log(`Server stderr: ${error}`)); serverProcess.stdout!.on('data', data => console.log(`Server stdout: ${data}`)); + } else { + serverProcess.stderr!.on('data', data => { + serverStderr = (serverStderr + data.toString()).slice(-maxServerStderr); + }); } + // Without this, a server that dies during a run leaves the page waiting for it until the CI step times out. + serverProcess.on('exit', async (code, signal) => { + if (!serverStopRequested) { + // The last stderr output can arrive after 'exit'. Wait for the pipe to close, but not for long: a process the + // server started can keep it open. + if (serverProcess.stderr && !serverProcess.stderr.closed) { + const stderr = serverProcess.stderr; + await new Promise<void>(resolve => { + const timer = setTimeout(resolve, 2000); + stderr.once('close', () => { + clearTimeout(timer); + resolve(); + }); + }); + } + console.error(`Server exited unexpectedly (code: ${code}, signal: ${signal}). See server-exit-diagnostics.log in '${serverLogsPath}'.`); + if (serverStderr) { + console.error(`Last server stderr output:\n${serverStderr}`); + } + process.exit(1); + } + }); + process.on('exit', () => serverProcess.kill()); process.on('SIGINT', () => { serverProcess.kill(); diff --git a/test/smoke/src/areas/chat/chatSessions.test.ts b/test/smoke/src/areas/chat/chatSessions.test.ts index eb498bb6b5a6..ea305a877f9f 100644 --- a/test/smoke/src/areas/chat/chatSessions.test.ts +++ b/test/smoke/src/areas/chat/chatSessions.test.ts @@ -194,13 +194,15 @@ async function openSession(app: Application, session: { readonly command: string await app.workbench.quickaccess.runCommand(session.command); await app.workbench.chat.waitForChatEditor(600); } else { - // The chat view may already be open, so wait for the command to bind a - // new session to it rather than just for the view to exist. Otherwise - // the prompt can be sent into the outgoing session, which the view then - // replaces with an empty one. + // Wait for the command to bind a new local session to the view, not + // just any session. The view can open first with its default Agent Host + // Copilot session while the command still waits for the local chat + // command to register, as when this test is the first of the suite in + // a cold window. A prompt sent then goes to that session and never gets + // the local reply. const previousSessionResource = await app.workbench.chat.getChatViewSessionResource(); await app.workbench.quickaccess.runCommand(session.command); - await app.workbench.chat.waitForChatViewSessionChange(previousSessionResource, 600); + await app.workbench.chat.waitForNewLocalChatViewSession(previousSessionResource, 600); } } diff --git a/test/smoke/src/utils.ts b/test/smoke/src/utils.ts index 83d5b223cba7..46083538ce9f 100644 --- a/test/smoke/src/utils.ts +++ b/test/smoke/src/utils.ts @@ -17,7 +17,11 @@ export interface MockLlmServer { close(): Promise<void>; } -/** Checks only the latest user message so scenario tags from earlier turns cannot match. */ +/** + * Checks only the latest user message so scenario tags from earlier turns cannot match. + * The runtime may append user items that contain only `<system_reminder>` blocks (for + * example, when deferred tools are available) after the prompt; those are skipped. + */ export function latestUserInputCarriesTag(body: unknown, scenarioTag: string): boolean { if (!body || typeof body !== 'object') { return false; @@ -28,18 +32,32 @@ export function latestUserInputCarriesTag(body: unknown, scenarioTag: string): b return false; } - const message = input.findLast((item: unknown): item is Record<string, unknown> => - !!item && typeof item === 'object' && (item as Record<string, unknown>).role === 'user'); - const content = message?.content; - const text = typeof content === 'string' - ? content - : Array.isArray(content) - ? content.map((part: unknown) => { - const text = part && typeof part === 'object' ? (part as Record<string, unknown>).text : undefined; - return typeof text === 'string' ? text : ''; - }).join('') - : ''; - return text.includes(scenarioTag); + for (let i = input.length - 1; i >= 0; i--) { + const item: unknown = input[i]; + if (!item || typeof item !== 'object' || (item as Record<string, unknown>).role !== 'user') { + continue; + } + const text = getMessageText((item as Record<string, unknown>).content); + const withoutReminders = text.replace(/<system_reminder>[\s\S]*?<\/system_reminder>/g, ''); + if (withoutReminders !== text && !withoutReminders.trim()) { + continue; + } + return text.includes(scenarioTag); + } + return false; +} + +function getMessageText(content: unknown): string { + if (typeof content === 'string') { + return content; + } + if (!Array.isArray(content)) { + return ''; + } + return content.map((part: unknown) => { + const text = part && typeof part === 'object' ? (part as Record<string, unknown>).text : undefined; + return typeof text === 'string' ? text : ''; + }).join(''); } /** diff --git a/test/smoke/wslDevContainer.ps1 b/test/smoke/wslDevContainer.ps1 index 3abe9f86f856..817390f62b40 100644 --- a/test/smoke/wslDevContainer.ps1 +++ b/test/smoke/wslDevContainer.ps1 @@ -24,6 +24,7 @@ param( $ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $false +$scriptStartTime = [DateTime]::UtcNow Import-Module (Join-Path $PSScriptRoot '..\..\build\azure-pipelines\common\wsl.psm1') -Force $wsl = Join-Path $env:SystemRoot 'System32\wsl.exe' $workspace = if ($CI -eq 'AzureDevOps') { $env:BUILD_SOURCESDIRECTORY } else { $env:GITHUB_WORKSPACE } @@ -253,6 +254,79 @@ function Import-RootfsDistribution([string] $Install) { Invoke-Wsl 'uname -a; cat /etc/os-release' 120 } +<# +.SYNOPSIS +Downloads the .deb files listed in apt's --print-uris output to a directory until a deadline, and returns how many of +them it got. It leaves the packages it does not get to apt. + +.DESCRIPTION +The packages are downloaded by the host rather than by apt in the distribution. The Azure mirror at times serves package +files at under 100 KB/s for minutes, or not at all for a while, while its index files stay fast, and apt keeps such a +connection until this step times out. Here the packages are downloaded in parallel, so stalls overlap rather than add +up. A transfer that stays below 256 KB/s for 20 seconds is stopped and continued on a fresh connection from where it +stopped, so a slow connection loses no bytes. Retries back off only after an attempt that got no bytes. The Azure mirror +is the only source, as archive.ubuntu.com answers 403 to the build agents. +A file of the wrong hash is downloaded again once, and apt checks each file against the index when it installs. +#> +function Save-DebPackages([string] $UriList, [string] $Directory, [datetime] $Deadline) { + $packages = foreach ($line in Get-Content -LiteralPath $UriList) { + if ($line -match "^'(https?://[^']+)' ([A-Za-z0-9_.+~%-]+\.deb) (\d+) (SHA512|SHA256|SHA1|MD5Sum):([0-9a-f]+)") { + [pscustomobject]@{ + Url = $Matches[1] + Name = $Matches[2] + Destination = Join-Path $Directory $Matches[2] + Size = [long]$Matches[3] + Algorithm = @{ SHA512 = 'SHA512'; SHA256 = 'SHA256'; SHA1 = 'SHA1'; MD5Sum = 'MD5' }[$Matches[4]] + Hash = $Matches[5].ToUpperInvariant() + } + } + } + $downloaded = $packages | ForEach-Object -ThrottleLimit 6 -Parallel { + $package = $_ + $deadline = $using:Deadline + $retryDelay = 1 + $hashMismatches = 0 + while ($true) { + $length = if (Test-Path -LiteralPath $package.Destination) { (Get-Item -LiteralPath $package.Destination).Length } else { 0 } + if ($length -eq $package.Size) { + if ((Get-FileHash -LiteralPath $package.Destination -Algorithm $package.Algorithm).Hash -eq $package.Hash) { + return $package.Name + } + $hashMismatches++ + Write-Host "$($package.Name) does not match its $($package.Algorithm) hash." + } + if ($length -ge $package.Size) { + Remove-Item -LiteralPath $package.Destination + $length = 0 + } + $remainingSeconds = [int]($deadline - [DateTime]::UtcNow).TotalSeconds + if ($remainingSeconds -lt 10 -or $hashMismatches -ge 2) { + Remove-Item -LiteralPath $package.Destination -ErrorAction SilentlyContinue + Write-Host "Leaving $($package.Name) for apt to download (got $length of $($package.Size) bytes)." + return + } + $curlOutput = curl.exe --fail --location --silent --show-error --connect-timeout 10 --max-time ([Math]::Min(120, $remainingSeconds)) --speed-limit 262144 --speed-time 20 --continue-at - --output $package.Destination $package.Url 2>&1 + $exitCode = $LASTEXITCODE + if ($exitCode -eq 0) { + continue + } + # 33: the server did not accept the range request, so the next attempt starts over. + if ($exitCode -eq 33) { + Remove-Item -LiteralPath $package.Destination -ErrorAction SilentlyContinue + } + $newLength = if (Test-Path -LiteralPath $package.Destination) { (Get-Item -LiteralPath $package.Destination).Length } else { 0 } + Write-Host "Download of $($package.Name) stopped at $newLength of $($package.Size) bytes: $(($curlOutput | Out-String).Trim())" + if ($newLength -gt $length) { + $retryDelay = 1 + } else { + Start-Sleep -Seconds $retryDelay + $retryDelay = [Math]::Min(2 * $retryDelay, 16) + } + } + } + return @($downloaded).Count +} + <# .SYNOPSIS Installs the pinned Linux server, the apt packages and the non-root test user into the distribution. @@ -295,44 +369,11 @@ done apt-get install -y -qq --print-uris --no-install-recommends $aptPackages > '$linuxRoot/apt-uris.txt' "@ 180 - # The packages are downloaded by the host rather than by apt in the distribution. The Azure mirror at times serves - # package files to the distribution at about 120 KB/s for minutes while its index files stay fast, and apt keeps such - # a connection rather than giving up on it. Here a transfer that stays below 1 MB/s for 15 seconds is abandoned and - # retried on a fresh connection, then on the main Ubuntu archive. apt checks each file against the index when it installs. - # The host gives up after 4 minutes in total, leaving the packages it did not get to apt, within the step's timeout. - $debCount = 0 - $hostDownloadDeadline = [DateTime]::UtcNow.AddMinutes(4) - foreach ($line in Get-Content -LiteralPath (Join-Path $Root 'apt-uris.txt')) { - if ($line -notmatch "^'(https?://[^']+)' ([A-Za-z0-9_.+~%-]+\.deb) (\d+) (SHA512|SHA256|SHA1|MD5Sum):([0-9a-f]+)") { - continue - } - $url, $name, $size, $hash = $Matches[1], $Matches[2], [long]$Matches[3], $Matches[5] - $algorithm = @{ SHA512 = 'SHA512'; SHA256 = 'SHA256'; SHA1 = 'SHA1'; MD5Sum = 'MD5' }[$Matches[4]] - $destination = Join-Path $debDirectory $name - $downloaded = $false - # Each attempt opens a fresh connection: the Azure mirror twice, then the main Ubuntu archive. - $fallback = $url -replace '^http://azure\.archive\.ubuntu\.com/', 'http://archive.ubuntu.com/' - foreach ($candidate in @($url, $url, $fallback)) { - $remainingSeconds = [int]($hostDownloadDeadline - [DateTime]::UtcNow).TotalSeconds - if ($remainingSeconds -lt 10) { - break - } - curl.exe --fail --location --silent --show-error --connect-timeout 10 --max-time ([Math]::Min(120, $remainingSeconds)) --speed-limit 1048576 --speed-time 15 --output $destination $candidate - if ($LASTEXITCODE -eq 0 -and (Get-Item -LiteralPath $destination).Length -eq $size -and (Get-FileHash -LiteralPath $destination -Algorithm $algorithm).Hash -eq $hash.ToUpperInvariant()) { - $downloaded = $true - break - } - Write-Host "Download of $name from $candidate failed (curl exit code $LASTEXITCODE)." - } - if (-not $downloaded) { - Remove-Item -LiteralPath $destination -ErrorAction SilentlyContinue - Write-Host "Leaving $name for apt to download." - continue - } - $debCount++ - } + # The host stops 10 minutes after the script started, leaving at least 5 minutes of the Azure DevOps step's 15-minute + # timeout for installing. + $debCount = Save-DebPackages (Join-Path $Root 'apt-uris.txt') $debDirectory $scriptStartTime.AddMinutes(10) Write-Host "Downloaded $debCount packages on the host." - # A failed curl above must not become the exit code of this script. + # A failed curl in Save-DebPackages must not become the exit code of this script. $global:LASTEXITCODE = 0 Invoke-Wsl @" diff --git a/test/unit/README.md b/test/unit/README.md index c967bf95bf0c..d0d320ad87b1 100644 --- a/test/unit/README.md +++ b/test/unit/README.md @@ -8,7 +8,7 @@ All unit tests are run inside a Electron renderer environment which access to DO - use the `--dev` to see an electron window with dev tools which allows for debugging - to run only a subset of tests use the `--run` or `--glob` options -- use `--rerun-failed-files <count>` to rerun failures, each time in a fresh window, up to `<count>` more times. Every rerun runs only the tests that did not pass yet, and the suite of a failed hook, by full title. A failure only counts as passed when the rerun ran and passed it, so a test whose title changes from run to run, or that depends on other tests of its file, still fails the run. With more than 50 failures, or a `--grep` of the form `/pattern/flags`, a rerun runs their whole test files instead. The run passes when every failure passes in a later attempt, and those failures are reported as flaky tests. Pull request CI uses `--rerun-failed-files 2`. Failures are not rerun when a failure does not belong to a test file, and a rerun with such a failure does not count +- use `--rerun-failed-files <count>` to rerun failures, each time in a fresh window, up to `<count>` more times. Every rerun runs only the tests that did not pass yet, and the suite of a failed hook, by full title. A failure only counts as passed when the rerun ran and passed it, so a test whose title changes from run to run, or that depends on other tests of its file, still fails the run. With more than 50 failures, or a `--grep` of the form `/pattern/flags`, a rerun runs their whole test files instead. The run passes when every failure passes in a later attempt, and those failures are reported as flaky tests. Pull request CI and the product build use `--rerun-failed-files 2`. Failures are not rerun when a failure does not belong to a test file, and a rerun with such a failure does not count - use `--workers <count>` to run all test files, or those of `--runList`, in `<count>` parallel processes. The count is required, and capped at one worker per CPU and per 2 GB of memory. Every worker is a separate Electron process that loads all test files of the run, but only runs the files it claims: workers claim the next file whenever they finish one, in the usual order, so each worker runs a subsequence of a single-window run. A worker also starts its own window and loads all listed files, so with `--runList` the runner starts one worker per 75 of the listed test files that it runs, but at least 2, and never more than there are files: a single file runs in a single window, up to 224 files in 2 workers, and 300 or more in 4 (see `getWorkerCountForFiles` in [parallel.ts](./parallel.ts)). The number of files does not tell how long they take: in a single window, one slow test file holds up all the others, while a second worker costs about a second. With `--run`, `--runGlob`, bare file paths, `--grep`, `--testSplit`, `--dev`, `--waitServer` or coverage, the tests run in a single window: `--runGlob` can select tests that never ran in workers, such as the node.js integration tests of `scripts/test-integration.sh`. Failures of all workers are rerun in a single window with `--rerun-failed-files`. A worker that does not complete normally, or a test file that no worker ran, fails the run and is not rerun. A failed worker's output ends with the test files it ran, in order, to pass to `--run` to reproduce the failure. With `--tfs`, every worker writes its own results file. Pull request CI uses `--workers 4` - use `pnpm run watch` to automatically compile changes @@ -26,7 +26,7 @@ Unit tests from layers `common` and `browser` are run inside `chromium`, `webkit - to run only a subset of tests use the `--run` or `--glob` options - test module import failures abort the run with a nonzero exit code, even when `--grep` would exclude the module's tests - if no test progress is reported for 5 minutes (e.g. the page is frozen), the run aborts and prints the in-flight test, whether the page still responds, and the browser processes' CPU usage; on macOS it also writes native stack samples to `.build/logs/browser-unit-stall`. Use `--stall-timeout <seconds>` to change the limit or `--stall-timeout 0` to disable it (it is always disabled with `--debug`) -- use `--rerun-failed-files <count>` to rerun failures up to `<count>` more times, each time in a freshly launched browser, as with the Electron runner: only the failed tests (the suite of a failed hook), or their whole test files when there are too many failures. Each browser reruns its own failures. A failure only counts as passed when its test (or a test of its hook's suite) actually passes with the same suite ancestry in the same test file; skipped or renamed tests and ambiguous duplicate test or suite paths do not count. Failures that passed on a rerun are reported as flaky tests. Pull request CI uses `--rerun-failed-files 2`. Reruns are disabled with `--debug` +- use `--rerun-failed-files <count>` to rerun failures up to `<count>` more times, each time in a freshly launched browser, as with the Electron runner: only the failed tests (the suite of a failed hook), or their whole test files when there are too many failures. Each browser reruns its own failures. A failure only counts as passed when its test (or a test of its hook's suite) actually passes with the same suite ancestry in the same test file; skipped or renamed tests and ambiguous duplicate test or suite paths do not count. Failures that passed on a rerun are reported as flaky tests. Pull request CI and the product build use `--rerun-failed-files 2`. Reruns are disabled with `--debug` - use `--workers <count>` to run all test files, or those of `--runList`, in `<count>` parallel processes, as with the Electron runner: every worker is a separate process with its own browser that loads all test files of the run, but only runs the files it claims, in the usual order. The count is required, and capped at one worker per CPU and per 2 GB of memory, and with `--runList`, the runner starts one worker per 75 of the listed test files that it runs, but at least 2 and never more than there are files, as with the Electron runner. With several browsers, they run one at a time. With `--run`, `--runGlob`, `--grep` or `--debug`, the tests run in a single browser. Failures of all workers are rerun in a single browser with `--rerun-failed-files`. A worker that does not complete normally, or a test file that no worker ran, fails the run and is not rerun. A failed worker's output ends with the test files it ran, in order, to pass to `--run` to reproduce the failure. With `--tfs`, every worker writes its own results file. Pull request CI uses `--workers 4` **Note**: you can enable verbose logging of playwright library by setting a `DEBUG` environment variable before running the tests (https://playwright.dev/docs/debug#verbose-api-logs) @@ -43,7 +43,7 @@ Use `--timeout <ms>` (or `-t <ms>`) to override the default, or `--timeout 0` to Use `--grep <pattern>` to run only the tests whose full title matches `<pattern>`. The runner's own loader and unexpected-error checks still run regardless of the filter. -Use `--rerun-failed-files <count>` to rerun failures, each time in a fresh process, up to `<count>` more times, as with the Electron runner: only the failed tests (the suite of a failed hook), or their whole test files when there are too many failures. Pull request CI uses `--rerun-failed-files 2`. Failures of the runner's own checks, such as unexpected errors, do not belong to a test file and are not rerun, but every rerun runs these checks again. Full-suite retries retain the Loader check, so stderr written while reloading a failed file also fails the run. +Use `--rerun-failed-files <count>` to rerun failures, each time in a fresh process, up to `<count>` more times, as with the Electron runner: only the failed tests (the suite of a failed hook), or their whole test files when there are too many failures. Pull request CI and the product build use `--rerun-failed-files 2`. Failures of the runner's own checks, such as unexpected errors, do not belong to a test file and are not rerun, but every rerun runs these checks again. Full-suite retries retain the Loader check, so stderr written while reloading a failed file also fails the run. A rerun must exit normally with an exit code matching its reported results. A startup failure, signal, or inconsistent exit code fails the run, even if the rerun wrote a passing report. diff --git a/test/unit/electron/index.js b/test/unit/electron/index.js index 327e1205d6e9..a3d62012dfbd 100644 --- a/test/unit/electron/index.js +++ b/test/unit/electron/index.js @@ -411,6 +411,10 @@ app.on('ready', async () => { // A second view lets tests blur the page without stealing desktop focus. /** @type {Map<number, import('electron').WebContentsView>} */ const focusTestViews = new Map(); + // Moves the page's pointer off the window, so `:hover` from a real pointer does not carry over between suites. + ipcMain.handle('vscode:test-pointer-leave', event => { + event.sender.sendInputEvent({ type: 'mouseLeave', x: -1, y: -1 }); + }); ipcMain.handle('vscode:test-set-web-contents-focus', async (event, focused) => { const window = BrowserWindow.fromWebContents(event.sender); if (!window) { diff --git a/test/unit/electron/renderer.js b/test/unit/electron/renderer.js index aac122a9f270..d866bf8d1328 100644 --- a/test/unit/electron/renderer.js +++ b/test/unit/electron/renderer.js @@ -278,11 +278,16 @@ async function loadTests(opts) { const { assertCleanState } = await loadFn('vs/workbench/test/common/utils'); const { installRegistryLeakCheck } = await loadFn('vs/platform/actions/test/common/registryLeakCheck'); installRegistryLeakCheck(mocha.suite); - const { installIsolationCheck, defaultIsolationDetectors, animationFrameQueueDetector } = await loadFn('vs/base/test/browser/isolationCheck'); + const { installIsolationCheck, defaultIsolationDetectors, hoverDetector, animationFrameQueueDetector } = await loadFn('vs/base/test/browser/isolationCheck'); const { menuChangeListenerDetector } = await loadFn('vs/platform/actions/test/common/menuChangeListenerDetector'); // The animation frame probe changes when queued runners run, so only reporting runs use it. const isolationProbes = process.env.VSCODE_TEST_ISOLATION_REPORT ? [animationFrameQueueDetector] : []; - installIsolationCheck(mocha.suite, [...defaultIsolationDetectors, menuChangeListenerDetector, ...isolationProbes]); + // Under Xvfb on Linux, the real pointer stays over the window once a suite activates it, so `:hover` applies to + // whatever a later suite renders there. Moving the pointer off the window after every top-level suite stops that. + const detectors = defaultIsolationDetectors.map(detector => process.platform === 'linux' && detector === hoverDetector + ? { ...detector, reset: () => ipcRenderer.invoke('vscode:test-pointer-leave') } + : detector); + installIsolationCheck(mocha.suite, [...detectors, menuChangeListenerDetector, ...isolationProbes]); suite('Tests are using suiteSetup and setup correctly', () => { test('assertCleanState - check that registries are clean at the start of test running', () => {